xref: /xnu-8792.81.2/bsd/kern/mach_loader.c (revision 19c3b8c28c31cb8130e034cfb5df6bf9ba342d90) !
1 /*
2  * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  *	Copyright (C) 1988, 1989,  NeXT, Inc.
30  *
31  *	File:	kern/mach_loader.c
32  *	Author:	Avadis Tevanian, Jr.
33  *
34  *	Mach object file loader (kernel version, for now).
35  *
36  * 21-Jul-88  Avadis Tevanian, Jr. (avie) at NeXT
37  *	Started.
38  */
39 
40 #include <sys/param.h>
41 #include <sys/vnode_internal.h>
42 #include <sys/uio.h>
43 #include <sys/namei.h>
44 #include <sys/proc_internal.h>
45 #include <sys/kauth.h>
46 #include <sys/stat.h>
47 #include <sys/malloc.h>
48 #include <sys/mount_internal.h>
49 #include <sys/fcntl.h>
50 #include <sys/file_internal.h>
51 #include <sys/ubc_internal.h>
52 #include <sys/imgact.h>
53 #include <sys/codesign.h>
54 #include <sys/proc_uuid_policy.h>
55 #include <sys/reason.h>
56 #include <sys/kdebug.h>
57 #include <sys/spawn_internal.h>
58 
59 #include <mach/mach_types.h>
60 #include <mach/vm_map.h>        /* vm_allocate() */
61 #include <mach/mach_vm.h>       /* mach_vm_allocate() */
62 #include <mach/vm_statistics.h>
63 #include <mach/task.h>
64 #include <mach/thread_act.h>
65 
66 #include <machine/vmparam.h>
67 #include <machine/exec.h>
68 #include <machine/pal_routines.h>
69 
70 #include <kern/ast.h>
71 #include <kern/kern_types.h>
72 #include <kern/cpu_number.h>
73 #include <kern/mach_loader.h>
74 #include <kern/mach_fat.h>
75 #include <kern/kalloc.h>
76 #include <kern/task.h>
77 #include <kern/thread.h>
78 #include <kern/page_decrypt.h>
79 
80 #include <mach-o/fat.h>
81 #include <mach-o/loader.h>
82 
83 #include <vm/pmap.h>
84 #include <vm/vm_map.h>
85 #include <vm/vm_kern.h>
86 #include <vm/vm_pager.h>
87 #include <vm/vnode_pager.h>
88 #include <vm/vm_protos.h>
89 #include <vm/vm_shared_region.h>
90 #include <IOKit/IOReturn.h>     /* for kIOReturnNotPrivileged */
91 #include <IOKit/IOBSD.h>        /* for IOVnodeHasEntitlement */
92 
93 #include <os/log.h>
94 #include <os/overflow.h>
95 
96 #include "kern_exec_internal.h"
97 
98 /* XXX should have prototypes in a shared header file */
99 extern int      get_map_nentries(vm_map_t);
100 
101 extern kern_return_t    memory_object_signed(memory_object_control_t control,
102     boolean_t is_signed);
103 
104 
105 /* An empty load_result_t */
106 static const load_result_t load_result_null = {
107 	.mach_header = MACH_VM_MIN_ADDRESS,
108 	.entry_point = MACH_VM_MIN_ADDRESS,
109 	.user_stack = MACH_VM_MIN_ADDRESS,
110 	.user_stack_size = 0,
111 	.user_stack_alloc = MACH_VM_MIN_ADDRESS,
112 	.user_stack_alloc_size = 0,
113 	.all_image_info_addr = MACH_VM_MIN_ADDRESS,
114 	.all_image_info_size = 0,
115 	.thread_count = 0,
116 	.unixproc = 0,
117 	.dynlinker = 0,
118 	.needs_dynlinker = 0,
119 	.validentry = 0,
120 	.using_lcmain = 0,
121 	.is_64bit_addr = 0,
122 	.is_64bit_data = 0,
123 	.custom_stack = 0,
124 	.csflags = 0,
125 	.has_pagezero = 0,
126 	.uuid = { 0 },
127 	.min_vm_addr = MACH_VM_MAX_ADDRESS,
128 	.max_vm_addr = MACH_VM_MIN_ADDRESS,
129 	.cs_end_offset = 0,
130 	.threadstate = NULL,
131 	.threadstate_sz = 0,
132 	.is_rosetta = 0,
133 	.dynlinker_mach_header = MACH_VM_MIN_ADDRESS,
134 	.dynlinker_fd = -1,
135 };
136 
137 /*
138  * Prototypes of static functions.
139  */
140 static load_return_t
141 parse_machfile(
142 	struct vnode            *vp,
143 	vm_map_t                map,
144 	thread_t                thread,
145 	struct mach_header      *header,
146 	off_t                   file_offset,
147 	off_t                   macho_size,
148 	int                     depth,
149 	int64_t                 slide,
150 	int64_t                 dyld_slide,
151 	load_result_t           *result,
152 	load_result_t           *binresult,
153 	struct image_params     *imgp
154 	);
155 
156 static load_return_t
157 load_segment(
158 	struct load_command             *lcp,
159 	uint32_t                        filetype,
160 	void                            *control,
161 	off_t                           pager_offset,
162 	off_t                           macho_size,
163 	struct vnode                    *vp,
164 	vm_map_t                        map,
165 	int64_t                         slide,
166 	load_result_t                   *result,
167 	struct image_params             *imgp
168 	);
169 
170 static load_return_t
171 load_uuid(
172 	struct uuid_command             *uulp,
173 	char                            *command_end,
174 	load_result_t                   *result
175 	);
176 
177 static load_return_t
178 load_version(
179 	struct version_min_command     *vmc,
180 	boolean_t               *found_version_cmd,
181 	struct image_params             *imgp,
182 	load_result_t           *result
183 	);
184 
185 static load_return_t
186 load_code_signature(
187 	struct linkedit_data_command    *lcp,
188 	struct vnode                    *vp,
189 	off_t                           macho_offset,
190 	off_t                           macho_size,
191 	cpu_type_t                      cputype,
192 	cpu_subtype_t                   cpusubtype,
193 	load_result_t                   *result,
194 	struct image_params             *imgp);
195 
196 #if CONFIG_CODE_DECRYPTION
197 static load_return_t
198 set_code_unprotect(
199 	struct encryption_info_command  *lcp,
200 	caddr_t                         addr,
201 	vm_map_t                        map,
202 	int64_t                         slide,
203 	struct vnode                    *vp,
204 	off_t                           macho_offset,
205 	cpu_type_t                      cputype,
206 	cpu_subtype_t                   cpusubtype);
207 #endif
208 
209 static
210 load_return_t
211 load_main(
212 	struct entry_point_command      *epc,
213 	thread_t                thread,
214 	int64_t                         slide,
215 	load_result_t           *result
216 	);
217 
218 static
219 load_return_t
220 setup_driver_main(
221 	thread_t                thread,
222 	int64_t                         slide,
223 	load_result_t           *result
224 	);
225 
226 static load_return_t
227 load_unixthread(
228 	struct thread_command   *tcp,
229 	thread_t                        thread,
230 	int64_t                         slide,
231 	boolean_t                       is_x86_64_compat_binary,
232 	load_result_t                   *result
233 	);
234 
235 static load_return_t
236 load_threadstate(
237 	thread_t                thread,
238 	uint32_t        *ts,
239 	uint32_t        total_size,
240 	load_result_t *
241 	);
242 
243 static load_return_t
244 load_threadstack(
245 	thread_t                thread,
246 	uint32_t                *ts,
247 	uint32_t                total_size,
248 	mach_vm_offset_t        *user_stack,
249 	int                     *customstack,
250 	boolean_t               is_x86_64_compat_binary,
251 	load_result_t           *result
252 	);
253 
254 static load_return_t
255 load_threadentry(
256 	thread_t                thread,
257 	uint32_t        *ts,
258 	uint32_t        total_size,
259 	mach_vm_offset_t        *entry_point
260 	);
261 
262 static load_return_t
263 load_dylinker(
264 	struct dylinker_command *lcp,
265 	integer_t               archbits,
266 	vm_map_t                map,
267 	thread_t                thread,
268 	int                     depth,
269 	int64_t                 slide,
270 	load_result_t           *result,
271 	struct image_params     *imgp
272 	);
273 
274 
275 #if CONFIG_ROSETTA
276 static load_return_t
277 load_rosetta(
278 	vm_map_t                        map,
279 	thread_t                        thread,
280 	load_result_t           *result,
281 	struct image_params     *imgp
282 	);
283 #endif
284 
285 #if __x86_64__
286 extern int bootarg_no32exec;
287 static boolean_t
288 check_if_simulator_binary(
289 	struct image_params     *imgp,
290 	off_t                   file_offset,
291 	off_t                   macho_size);
292 #endif
293 
294 struct macho_data;
295 
296 static load_return_t
297 get_macho_vnode(
298 	const char                      *path,
299 	integer_t               archbits,
300 	struct mach_header      *mach_header,
301 	off_t                   *file_offset,
302 	off_t                   *macho_size,
303 	struct macho_data       *macho_data,
304 	struct vnode            **vpp,
305 	struct image_params     *imgp
306 	);
307 
308 static inline void
widen_segment_command(const struct segment_command * scp32,struct segment_command_64 * scp)309 widen_segment_command(const struct segment_command *scp32,
310     struct segment_command_64 *scp)
311 {
312 	scp->cmd = scp32->cmd;
313 	scp->cmdsize = scp32->cmdsize;
314 	bcopy(scp32->segname, scp->segname, sizeof(scp->segname));
315 	scp->vmaddr = scp32->vmaddr;
316 	scp->vmsize = scp32->vmsize;
317 	scp->fileoff = scp32->fileoff;
318 	scp->filesize = scp32->filesize;
319 	scp->maxprot = scp32->maxprot;
320 	scp->initprot = scp32->initprot;
321 	scp->nsects = scp32->nsects;
322 	scp->flags = scp32->flags;
323 }
324 
325 static void
note_all_image_info_section(const struct segment_command_64 * scp,boolean_t is64,size_t section_size,const void * sections,int64_t slide,load_result_t * result)326 note_all_image_info_section(const struct segment_command_64 *scp,
327     boolean_t is64, size_t section_size, const void *sections,
328     int64_t slide, load_result_t *result)
329 {
330 	const union {
331 		struct section s32;
332 		struct section_64 s64;
333 	} *sectionp;
334 	unsigned int i;
335 
336 
337 	if (strncmp(scp->segname, "__DATA_DIRTY", sizeof(scp->segname)) != 0 &&
338 	    strncmp(scp->segname, "__DATA", sizeof(scp->segname)) != 0) {
339 		return;
340 	}
341 	for (i = 0; i < scp->nsects; ++i) {
342 		sectionp = (const void *)
343 		    ((const char *)sections + section_size * i);
344 		if (0 == strncmp(sectionp->s64.sectname, "__all_image_info",
345 		    sizeof(sectionp->s64.sectname))) {
346 			result->all_image_info_addr =
347 			    is64 ? sectionp->s64.addr : sectionp->s32.addr;
348 			result->all_image_info_addr += slide;
349 			result->all_image_info_size =
350 			    is64 ? sectionp->s64.size : sectionp->s32.size;
351 			return;
352 		}
353 	}
354 }
355 
356 #if __arm64__
357 /*
358  * Allow bypassing some security rules (hard pagezero, no write+execute)
359  * in exchange for better binary compatibility for legacy apps built
360  * before 16KB-alignment was enforced.
361  */
362 const int fourk_binary_compatibility_unsafe = TRUE;
363 const int fourk_binary_compatibility_allow_wx = FALSE;
364 #endif /* __arm64__ */
365 
366 #if __has_feature(ptrauth_calls) && XNU_TARGET_OS_OSX
367 /**
368  * Determines whether this is an arm64e process which may host in-process
369  * plugins.
370  */
371 static inline bool
arm64e_plugin_host(struct image_params * imgp,load_result_t * result)372 arm64e_plugin_host(struct image_params *imgp, load_result_t *result)
373 {
374 	if (imgp->ip_flags & IMGPF_NOJOP) {
375 		return false;
376 	}
377 
378 	if (!result->platform_binary) {
379 		return false;
380 	}
381 
382 	struct cs_blob *csblob = csvnode_get_blob(imgp->ip_vp, imgp->ip_arch_offset);
383 	const char *identity = csblob_get_identity(csblob);
384 	if (!identity) {
385 		return false;
386 	}
387 
388 	/* Check if override host plugin entitlement is present and posix spawn attribute to disable A keys is passed */
389 	if (IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, OVERRIDE_PLUGIN_HOST_ENTITLEMENT)) {
390 		bool ret = imgp->ip_flags & IMGPF_PLUGIN_HOST_DISABLE_A_KEYS;
391 		if (ret) {
392 			proc_t p = vfs_context_proc(imgp->ip_vfs_context);
393 			set_proc_name(imgp, p);
394 			os_log(OS_LOG_DEFAULT, "%s: running binary \"%s\" in keys-off mode due to posix_spawnattr_disable_ptr_auth_a_keys_np", __func__, p->p_name);
395 		}
396 		return ret;
397 	}
398 
399 	/* Disabling library validation is a good signal that this process plans to host plugins */
400 	const char *const disable_lv_entitlements[] = {
401 		"com.apple.security.cs.disable-library-validation",
402 		"com.apple.private.cs.automator-plugins",
403 		CLEAR_LV_ENTITLEMENT,
404 	};
405 	for (size_t i = 0; i < ARRAY_COUNT(disable_lv_entitlements); i++) {
406 		const char *entitlement = disable_lv_entitlements[i];
407 		if (IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, entitlement)) {
408 			proc_t p = vfs_context_proc(imgp->ip_vfs_context);
409 			set_proc_name(imgp, p);
410 			os_log(OS_LOG_DEFAULT, "%s: running binary \"%s\" in keys-off mode due to entitlement: %s", __func__, p->p_name, entitlement);
411 			return true;
412 		}
413 	}
414 
415 	/* From /System/Library/Security/HardeningExceptions.plist */
416 	const char *const hardening_exceptions[] = {
417 		"com.apple.perl5", /* Scripting engines may load third party code and jit*/
418 		"com.apple.perl", /* Scripting engines may load third party code and jit*/
419 		"org.python.python", /* Scripting engines may load third party code and jit*/
420 		"com.apple.expect", /* Scripting engines may load third party code and jit*/
421 		"com.tcltk.wish", /* Scripting engines may load third party code and jit*/
422 		"com.tcltk.tclsh", /* Scripting engines may load third party code and jit*/
423 		"com.apple.ruby", /* Scripting engines may load third party code and jit*/
424 		"com.apple.bash", /* Required for the 'enable' command */
425 		"com.apple.zsh", /* Required for the 'zmodload' command */
426 		"com.apple.ksh", /* Required for 'builtin' command */
427 	};
428 	for (size_t i = 0; i < ARRAY_COUNT(hardening_exceptions); i++) {
429 		if (strncmp(hardening_exceptions[i], identity, strlen(hardening_exceptions[i])) == 0) {
430 			proc_t p = vfs_context_proc(imgp->ip_vfs_context);
431 			set_proc_name(imgp, p);
432 			os_log(OS_LOG_DEFAULT, "%s: running binary \"%s\" in keys-off mode due to identity: %s", __func__, p->p_name, identity);
433 			return true;
434 		}
435 	}
436 
437 	return false;
438 }
439 #endif /* __has_feature(ptrauth_calls) && XNU_TARGET_OS_OSX */
440 
441 load_return_t
load_machfile(struct image_params * imgp,struct mach_header * header,thread_t thread,vm_map_t * mapp,load_result_t * result)442 load_machfile(
443 	struct image_params     *imgp,
444 	struct mach_header      *header,
445 	thread_t                thread,
446 	vm_map_t                *mapp,
447 	load_result_t           *result
448 	)
449 {
450 	struct vnode            *vp = imgp->ip_vp;
451 	off_t                   file_offset = imgp->ip_arch_offset;
452 	off_t                   macho_size = imgp->ip_arch_size;
453 	off_t                   total_size = 0;
454 	off_t                   file_size = imgp->ip_vattr->va_data_size;
455 	pmap_t                  pmap = 0;       /* protected by create_map */
456 	vm_map_t                map;
457 	load_result_t           myresult;
458 	load_return_t           lret;
459 	boolean_t enforce_hard_pagezero = TRUE;
460 	int in_exec = (imgp->ip_flags & IMGPF_EXEC);
461 	task_t task = current_task();
462 	int64_t                 aslr_page_offset = 0;
463 	int64_t                 dyld_aslr_page_offset = 0;
464 	int64_t                 aslr_section_size = 0;
465 	int64_t                 aslr_section_offset = 0;
466 	kern_return_t           kret;
467 	unsigned int            pmap_flags = 0;
468 
469 	if (os_add_overflow(file_offset, macho_size, &total_size) ||
470 	    total_size > file_size) {
471 		return LOAD_BADMACHO;
472 	}
473 
474 	result->is_64bit_addr = ((imgp->ip_flags & IMGPF_IS_64BIT_ADDR) == IMGPF_IS_64BIT_ADDR);
475 	result->is_64bit_data = ((imgp->ip_flags & IMGPF_IS_64BIT_DATA) == IMGPF_IS_64BIT_DATA);
476 #if defined(HAS_APPLE_PAC)
477 	pmap_flags |= (imgp->ip_flags & IMGPF_NOJOP) ? PMAP_CREATE_DISABLE_JOP : 0;
478 #endif /* defined(HAS_APPLE_PAC) */
479 #if CONFIG_ROSETTA
480 	pmap_flags |= (imgp->ip_flags & IMGPF_ROSETTA) ? PMAP_CREATE_ROSETTA : 0;
481 #endif
482 	pmap_flags |= result->is_64bit_addr ? PMAP_CREATE_64BIT : 0;
483 
484 	task_t ledger_task;
485 	if (imgp->ip_new_thread) {
486 		ledger_task = get_threadtask(imgp->ip_new_thread);
487 	} else {
488 		ledger_task = task;
489 	}
490 
491 #if XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES
492 	if (imgp->ip_px_sa != NULL) {
493 		struct _posix_spawnattr* psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
494 		if (psa->psa_flags & _POSIX_SPAWN_FORCE_4K_PAGES) {
495 			pmap_flags |= PMAP_CREATE_FORCE_4K_PAGES;
496 		}
497 	}
498 #endif /* XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGE */
499 
500 	pmap = pmap_create_options(get_task_ledger(ledger_task),
501 	    (vm_map_size_t) 0,
502 	    pmap_flags);
503 	if (pmap == NULL) {
504 		return LOAD_RESOURCE;
505 	}
506 	map = vm_map_create_options(pmap, 0,
507 	    vm_compute_max_offset(result->is_64bit_addr),
508 	    VM_MAP_CREATE_PAGEABLE);
509 
510 #if defined(__arm64__)
511 	if (result->is_64bit_addr) {
512 		/* enforce 16KB alignment of VM map entries */
513 		vm_map_set_page_shift(map, SIXTEENK_PAGE_SHIFT);
514 	} else {
515 		vm_map_set_page_shift(map, page_shift_user32);
516 	}
517 #endif /* __arm64__ */
518 
519 #if PMAP_CREATE_FORCE_4K_PAGES
520 	if (pmap_flags & PMAP_CREATE_FORCE_4K_PAGES) {
521 		DEBUG4K_LIFE("***** launching '%s' as 4k *****\n", vp->v_name);
522 		vm_map_set_page_shift(map, FOURK_PAGE_SHIFT);
523 	}
524 #endif /* PMAP_CREATE_FORCE_4K_PAGES */
525 
526 #ifndef CONFIG_ENFORCE_SIGNED_CODE
527 	/* This turns off faulting for executable pages, which allows
528 	 * to circumvent Code Signing Enforcement. The per process
529 	 * flag (CS_ENFORCEMENT) is not set yet, but we can use the
530 	 * global flag.
531 	 */
532 	if (!cs_process_global_enforcement() && (header->flags & MH_ALLOW_STACK_EXECUTION)) {
533 		vm_map_disable_NX(map);
534 		// TODO: Message Trace or log that this is happening
535 	}
536 #endif
537 
538 	/* Forcibly disallow execution from data pages on even if the arch
539 	 * normally permits it. */
540 	if ((header->flags & MH_NO_HEAP_EXECUTION) && !(imgp->ip_flags & IMGPF_ALLOW_DATA_EXEC)) {
541 		vm_map_disallow_data_exec(map);
542 	}
543 
544 	/*
545 	 * Compute a random offset for ASLR, and an independent random offset for dyld.
546 	 */
547 	if (!(imgp->ip_flags & IMGPF_DISABLE_ASLR)) {
548 		vm_map_get_max_aslr_slide_section(map, &aslr_section_offset, &aslr_section_size);
549 		aslr_section_offset = (random() % aslr_section_offset) * aslr_section_size;
550 
551 		aslr_page_offset = random();
552 		aslr_page_offset = (aslr_page_offset % (vm_map_get_max_aslr_slide_pages(map) - 1)) + 1;
553 		aslr_page_offset <<= vm_map_page_shift(map);
554 
555 		dyld_aslr_page_offset = random();
556 		dyld_aslr_page_offset = (dyld_aslr_page_offset %
557 		    (vm_map_get_max_loader_aslr_slide_pages(map) - 1)) + 1;
558 		dyld_aslr_page_offset <<= vm_map_page_shift(map);
559 
560 		aslr_page_offset += aslr_section_offset;
561 	}
562 	if (vm_map_page_shift(map) < (int)PAGE_SHIFT) {
563 		DEBUG4K_LOAD("slide=0x%llx dyld_slide=0x%llx\n", aslr_page_offset, dyld_aslr_page_offset);
564 	}
565 
566 	if (!result) {
567 		result = &myresult;
568 	}
569 
570 	*result = load_result_null;
571 
572 	/*
573 	 * re-set the bitness on the load result since we cleared the load result above.
574 	 */
575 	result->is_64bit_addr = ((imgp->ip_flags & IMGPF_IS_64BIT_ADDR) == IMGPF_IS_64BIT_ADDR);
576 	result->is_64bit_data = ((imgp->ip_flags & IMGPF_IS_64BIT_DATA) == IMGPF_IS_64BIT_DATA);
577 
578 	lret = parse_machfile(vp, map, thread, header, file_offset, macho_size,
579 	    0, aslr_page_offset, dyld_aslr_page_offset, result,
580 	    NULL, imgp);
581 
582 	if (lret != LOAD_SUCCESS) {
583 		vm_map_deallocate(map); /* will lose pmap reference too */
584 		return lret;
585 	}
586 
587 #if __x86_64__
588 	/*
589 	 * On x86, for compatibility, don't enforce the hard page-zero restriction for 32-bit binaries.
590 	 */
591 	if (!result->is_64bit_addr) {
592 		enforce_hard_pagezero = FALSE;
593 	}
594 
595 	/*
596 	 * For processes with IMGPF_HIGH_BITS_ASLR, add a few random high bits
597 	 * to the start address for "anywhere" memory allocations.
598 	 */
599 #define VM_MAP_HIGH_START_BITS_COUNT 8
600 #define VM_MAP_HIGH_START_BITS_SHIFT 27
601 	if (result->is_64bit_addr &&
602 	    (imgp->ip_flags & IMGPF_HIGH_BITS_ASLR)) {
603 		int random_bits;
604 		vm_map_offset_t high_start;
605 
606 		random_bits = random();
607 		random_bits &= (1 << VM_MAP_HIGH_START_BITS_COUNT) - 1;
608 		high_start = (((vm_map_offset_t)random_bits)
609 		        << VM_MAP_HIGH_START_BITS_SHIFT);
610 		vm_map_set_high_start(map, high_start);
611 	}
612 #endif /* __x86_64__ */
613 
614 	/*
615 	 * Check to see if the page zero is enforced by the map->min_offset.
616 	 */
617 	if (enforce_hard_pagezero &&
618 	    (vm_map_has_hard_pagezero(map, 0x1000) == FALSE)) {
619 #if __arm64__
620 		if (
621 			!result->is_64bit_addr && /* not 64-bit address space */
622 			!(header->flags & MH_PIE) &&      /* not PIE */
623 			(vm_map_page_shift(map) != FOURK_PAGE_SHIFT ||
624 			PAGE_SHIFT != FOURK_PAGE_SHIFT) && /* page size != 4KB */
625 			result->has_pagezero && /* has a "soft" page zero */
626 			fourk_binary_compatibility_unsafe) {
627 			/*
628 			 * For backwards compatibility of "4K" apps on
629 			 * a 16K system, do not enforce a hard page zero...
630 			 */
631 		} else
632 #endif /* __arm64__ */
633 		{
634 			vm_map_deallocate(map); /* will lose pmap reference too */
635 			return LOAD_BADMACHO;
636 		}
637 	}
638 
639 #if __arm64__
640 	if (enforce_hard_pagezero && result->is_64bit_addr && (header->cputype == CPU_TYPE_ARM64)) {
641 		/* 64 bit ARM binary must have "hard page zero" of 4GB to cover the lower 32 bit address space */
642 		if (vm_map_has_hard_pagezero(map, 0x100000000) == FALSE) {
643 			vm_map_deallocate(map); /* will lose pmap reference too */
644 			return LOAD_BADMACHO;
645 		}
646 	}
647 #endif
648 
649 	vm_commit_pagezero_status(map);
650 
651 	/*
652 	 * If this is an exec, then we are going to destroy the old
653 	 * task, and it's correct to halt it; if it's spawn, the
654 	 * task is not yet running, and it makes no sense.
655 	 */
656 	if (in_exec) {
657 		proc_t p = current_proc();
658 		/*
659 		 * Mark the task as halting and start the other
660 		 * threads towards terminating themselves.  Then
661 		 * make sure any threads waiting for a process
662 		 * transition get informed that we are committed to
663 		 * this transition, and then finally complete the
664 		 * task halting (wait for threads and then cleanup
665 		 * task resources).
666 		 *
667 		 * NOTE: task_start_halt() makes sure that no new
668 		 * threads are created in the task during the transition.
669 		 * We need to mark the workqueue as exiting before we
670 		 * wait for threads to terminate (at the end of which
671 		 * we no longer have a prohibition on thread creation).
672 		 *
673 		 * Finally, clean up any lingering workqueue data structures
674 		 * that may have been left behind by the workqueue threads
675 		 * as they exited (and then clean up the work queue itself).
676 		 */
677 		kret = task_start_halt(task);
678 		if (kret != KERN_SUCCESS) {
679 			vm_map_deallocate(map); /* will lose pmap reference too */
680 			return LOAD_FAILURE;
681 		}
682 		proc_transcommit(p, 0);
683 		workq_mark_exiting(p);
684 		task_complete_halt(task);
685 		workq_exit(p);
686 
687 		/*
688 		 * Roll up accounting info to new task. The roll up is done after
689 		 * task_complete_halt to make sure the thread accounting info is
690 		 * rolled up to current_task.
691 		 */
692 		task_rollup_accounting_info(get_threadtask(thread), task);
693 	}
694 	*mapp = map;
695 
696 #if __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX)
697 	/*
698 	 * arm64e plugin hosts currently run with JOP keys disabled, since they
699 	 * may need to run arm64 plugins.
700 	 */
701 	if (arm64e_plugin_host(imgp, result)) {
702 		imgp->ip_flags |= IMGPF_NOJOP;
703 		pmap_disable_user_jop(pmap);
704 	}
705 
706 #if CONFIG_ROSETTA
707 	/* Disable JOP keys if the Rosetta runtime being used isn't arm64e */
708 	if (result->is_rosetta && (imgp->ip_flags & IMGPF_NOJOP)) {
709 		pmap_disable_user_jop(pmap);
710 	}
711 #endif /* CONFIG_ROSETTA */
712 #endif /* __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX) */
713 
714 
715 	return LOAD_SUCCESS;
716 }
717 
718 int macho_printf = 0;
719 #define MACHO_PRINTF(args)                              \
720 	do {                                            \
721 	        if (macho_printf) {                     \
722 	                printf args;                    \
723 	        }                                       \
724 	} while (0)
725 
726 
727 static boolean_t
pie_required(cpu_type_t exectype,cpu_subtype_t execsubtype)728 pie_required(
729 	cpu_type_t exectype,
730 	cpu_subtype_t execsubtype)
731 {
732 	switch (exectype) {
733 	case CPU_TYPE_X86_64:
734 		return FALSE;
735 	case CPU_TYPE_ARM64:
736 		return TRUE;
737 	case CPU_TYPE_ARM:
738 		switch (execsubtype) {
739 		case CPU_SUBTYPE_ARM_V7K:
740 			return TRUE;
741 		}
742 		break;
743 	}
744 	return FALSE;
745 }
746 
747 /*
748  * The file size of a mach-o file is limited to 32 bits; this is because
749  * this is the limit on the kalloc() of enough bytes for a mach_header and
750  * the contents of its sizeofcmds, which is currently constrained to 32
751  * bits in the file format itself.  We read into the kernel buffer the
752  * commands section, and then parse it in order to parse the mach-o file
753  * format load_command segment(s).  We are only interested in a subset of
754  * the total set of possible commands. If "map"==VM_MAP_NULL or
755  * "thread"==THREAD_NULL, do not make permament VM modifications,
756  * just preflight the parse.
757  */
758 static
759 load_return_t
parse_machfile(struct vnode * vp,vm_map_t map,thread_t thread,struct mach_header * header,off_t file_offset,off_t macho_size,int depth,int64_t aslr_offset,int64_t dyld_aslr_offset,load_result_t * result,load_result_t * binresult,struct image_params * imgp)760 parse_machfile(
761 	struct vnode            *vp,
762 	vm_map_t                map,
763 	thread_t                thread,
764 	struct mach_header      *header,
765 	off_t                   file_offset,
766 	off_t                   macho_size,
767 	int                     depth,
768 	int64_t                 aslr_offset,
769 	int64_t                 dyld_aslr_offset,
770 	load_result_t           *result,
771 	load_result_t           *binresult,
772 	struct image_params     *imgp
773 	)
774 {
775 	uint32_t                ncmds;
776 	struct load_command     *lcp;
777 	struct dylinker_command *dlp = 0;
778 	void *                  control;
779 	load_return_t           ret = LOAD_SUCCESS;
780 	void *                  addr;
781 	vm_size_t               alloc_size, cmds_size;
782 	size_t                  offset;
783 	size_t                  oldoffset;      /* for overflow check */
784 	int                     pass;
785 	proc_t                  p = vfs_context_proc(imgp->ip_vfs_context);
786 	int                     error;
787 	int                     resid = 0;
788 	int                     spawn = (imgp->ip_flags & IMGPF_SPAWN);
789 	size_t                  mach_header_sz = sizeof(struct mach_header);
790 	boolean_t               abi64;
791 	boolean_t               got_code_signatures = FALSE;
792 	boolean_t               found_header_segment = FALSE;
793 	boolean_t               found_xhdr = FALSE;
794 	boolean_t               found_version_cmd = FALSE;
795 	int64_t                 slide = 0;
796 	boolean_t               dyld_no_load_addr = FALSE;
797 	boolean_t               is_dyld = FALSE;
798 	vm_map_offset_t         effective_page_mask = PAGE_MASK;
799 #if __arm64__
800 	uint64_t                pagezero_end = 0;
801 	uint64_t                executable_end = 0;
802 	uint64_t                writable_start = 0;
803 	vm_map_size_t           effective_page_size;
804 
805 	effective_page_mask = vm_map_page_mask(map);
806 	effective_page_size = vm_map_page_size(map);
807 #endif /* __arm64__ */
808 
809 	if (header->magic == MH_MAGIC_64 ||
810 	    header->magic == MH_CIGAM_64) {
811 		mach_header_sz = sizeof(struct mach_header_64);
812 	}
813 
814 	/*
815 	 *	Break infinite recursion
816 	 */
817 	if (depth > 2) {
818 		return LOAD_FAILURE;
819 	}
820 
821 	depth++;
822 
823 	/*
824 	 * Set CS_NO_UNTRUSTED_HELPERS by default; load_dylinker and load_rosetta
825 	 * will unset it if necessary.
826 	 */
827 	if (depth == 1) {
828 		result->csflags |= CS_NO_UNTRUSTED_HELPERS;
829 	}
830 
831 	/*
832 	 *	Check to see if right machine type.
833 	 */
834 	if (((cpu_type_t)(header->cputype & ~CPU_ARCH_MASK) != (cpu_type() & ~CPU_ARCH_MASK))
835 	    ) {
836 		return LOAD_BADARCH;
837 	}
838 
839 	if (!grade_binary(header->cputype,
840 	    header->cpusubtype & ~CPU_SUBTYPE_MASK,
841 	    header->cpusubtype & CPU_SUBTYPE_MASK, TRUE)) {
842 		return LOAD_BADARCH;
843 	}
844 
845 	abi64 = ((header->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64);
846 
847 	switch (header->filetype) {
848 	case MH_EXECUTE:
849 		if (depth != 1 && depth != 3) {
850 			return LOAD_FAILURE;
851 		}
852 		if (header->flags & MH_DYLDLINK) {
853 			/* Check properties of dynamic executables */
854 			if (!(header->flags & MH_PIE) && pie_required(header->cputype, header->cpusubtype & ~CPU_SUBTYPE_MASK)) {
855 				return LOAD_FAILURE;
856 			}
857 			result->needs_dynlinker = TRUE;
858 		} else if (header->cputype == CPU_TYPE_X86_64) {
859 			/* x86_64 static binaries allowed */
860 #if CONFIG_ROSETTA
861 		} else if (imgp->ip_flags & IMGPF_ROSETTA) {
862 			/* Rosetta runtime allowed */
863 #endif /* CONFIG_X86_64_COMPAT */
864 		} else {
865 			/* Check properties of static executables (disallowed except for development) */
866 #if !(DEVELOPMENT || DEBUG)
867 			return LOAD_FAILURE;
868 #endif
869 		}
870 		break;
871 	case MH_DYLINKER:
872 		if (depth != 2) {
873 			return LOAD_FAILURE;
874 		}
875 		is_dyld = TRUE;
876 		break;
877 
878 	default:
879 		return LOAD_FAILURE;
880 	}
881 
882 	/*
883 	 *	For PIE and dyld, slide everything by the ASLR offset.
884 	 */
885 	if ((header->flags & MH_PIE) || is_dyld) {
886 		slide = aslr_offset;
887 	}
888 
889 	/*
890 	 *	Get the pager for the file.
891 	 */
892 	control = ubc_getobject(vp, UBC_FLAGS_NONE);
893 
894 	/* ensure header + sizeofcmds falls within the file */
895 	if (os_add_overflow(mach_header_sz, header->sizeofcmds, &cmds_size) ||
896 	    (off_t)cmds_size > macho_size ||
897 	    round_page_overflow(cmds_size, &alloc_size) ||
898 	    alloc_size > INT_MAX) {
899 		return LOAD_BADMACHO;
900 	}
901 
902 	/*
903 	 * Map the load commands into kernel memory.
904 	 */
905 	addr = kalloc_data(alloc_size, Z_WAITOK);
906 	if (addr == NULL) {
907 		return LOAD_NOSPACE;
908 	}
909 
910 	error = vn_rdwr(UIO_READ, vp, addr, (int)alloc_size, file_offset,
911 	    UIO_SYSSPACE, 0, vfs_context_ucred(imgp->ip_vfs_context), &resid, p);
912 	if (error) {
913 		kfree_data(addr, alloc_size);
914 		return LOAD_IOERROR;
915 	}
916 
917 	if (resid) {
918 		{
919 			/* We must be able to read in as much as the mach_header indicated */
920 			kfree_data(addr, alloc_size);
921 			return LOAD_BADMACHO;
922 		}
923 	}
924 
925 	/*
926 	 *  Scan through the commands, processing each one as necessary.
927 	 *  We parse in three passes through the headers:
928 	 *  0: determine if TEXT and DATA boundary can be page-aligned, load platform version
929 	 *  1: thread state, uuid, code signature
930 	 *  2: segments
931 	 *  3: dyld, encryption, check entry point
932 	 */
933 
934 	boolean_t slide_realign = FALSE;
935 #if __arm64__
936 	if (!abi64) {
937 		slide_realign = TRUE;
938 	}
939 #endif
940 
941 	for (pass = 0; pass <= 3; pass++) {
942 		if (pass == 1) {
943 #if __arm64__
944 			boolean_t       is_pie;
945 			int64_t         adjust;
946 
947 			is_pie = ((header->flags & MH_PIE) != 0);
948 			if (pagezero_end != 0 &&
949 			    pagezero_end < effective_page_size) {
950 				/* need at least 1 page for PAGEZERO */
951 				adjust = effective_page_size;
952 				MACHO_PRINTF(("pagezero boundary at "
953 				    "0x%llx; adjust slide from "
954 				    "0x%llx to 0x%llx%s\n",
955 				    (uint64_t) pagezero_end,
956 				    slide,
957 				    slide + adjust,
958 				    (is_pie
959 				    ? ""
960 				    : " BUT NO PIE ****** :-(")));
961 				if (is_pie) {
962 					slide += adjust;
963 					pagezero_end += adjust;
964 					executable_end += adjust;
965 					writable_start += adjust;
966 				}
967 			}
968 			if (pagezero_end != 0) {
969 				result->has_pagezero = TRUE;
970 			}
971 			if (executable_end == writable_start &&
972 			    (executable_end & effective_page_mask) != 0 &&
973 			    (executable_end & FOURK_PAGE_MASK) == 0) {
974 				/*
975 				 * The TEXT/DATA boundary is 4K-aligned but
976 				 * not page-aligned.  Adjust the slide to make
977 				 * it page-aligned and avoid having a page
978 				 * with both write and execute permissions.
979 				 */
980 				adjust =
981 				    (effective_page_size -
982 				    (executable_end & effective_page_mask));
983 				MACHO_PRINTF(("page-unaligned X-W boundary at "
984 				    "0x%llx; adjust slide from "
985 				    "0x%llx to 0x%llx%s\n",
986 				    (uint64_t) executable_end,
987 				    slide,
988 				    slide + adjust,
989 				    (is_pie
990 				    ? ""
991 				    : " BUT NO PIE ****** :-(")));
992 				if (is_pie) {
993 					slide += adjust;
994 				}
995 			}
996 #endif /* __arm64__ */
997 
998 			if (dyld_no_load_addr && binresult) {
999 				/*
1000 				 * The dyld Mach-O does not specify a load address. Try to locate
1001 				 * it right after the main binary. If binresult == NULL, load
1002 				 * directly to the given slide.
1003 				 */
1004 				mach_vm_address_t max_vm_addr = binresult->max_vm_addr;
1005 				slide = vm_map_round_page(slide + max_vm_addr, effective_page_mask);
1006 			}
1007 		}
1008 
1009 		/*
1010 		 * Check that the entry point is contained in an executable segment
1011 		 */
1012 		if ((pass == 3) && (thread != THREAD_NULL)) {
1013 			if (depth == 1 && imgp && (imgp->ip_flags & IMGPF_DRIVER)) {
1014 				/* Driver binaries must have driverkit platform */
1015 				if (result->ip_platform == PLATFORM_DRIVERKIT) {
1016 					/* Driver binaries have no entry point */
1017 					ret = setup_driver_main(thread, slide, result);
1018 				} else {
1019 					ret = LOAD_FAILURE;
1020 				}
1021 			} else if (!result->using_lcmain && result->validentry == 0) {
1022 				ret = LOAD_FAILURE;
1023 			}
1024 			if (ret != KERN_SUCCESS) {
1025 				thread_state_initialize(thread);
1026 				break;
1027 			}
1028 		}
1029 
1030 		/*
1031 		 * Check that some segment maps the start of the mach-o file, which is
1032 		 * needed by the dynamic loader to read the mach headers, etc.
1033 		 */
1034 		if ((pass == 3) && (found_header_segment == FALSE)) {
1035 			ret = LOAD_BADMACHO;
1036 			break;
1037 		}
1038 
1039 		/*
1040 		 * Loop through each of the load_commands indicated by the
1041 		 * Mach-O header; if an absurd value is provided, we just
1042 		 * run off the end of the reserved section by incrementing
1043 		 * the offset too far, so we are implicitly fail-safe.
1044 		 */
1045 		offset = mach_header_sz;
1046 		ncmds = header->ncmds;
1047 
1048 		while (ncmds--) {
1049 			/* ensure enough space for a minimal load command */
1050 			if (offset + sizeof(struct load_command) > cmds_size) {
1051 				ret = LOAD_BADMACHO;
1052 				break;
1053 			}
1054 
1055 			/*
1056 			 *	Get a pointer to the command.
1057 			 */
1058 			lcp = (struct load_command *)((uintptr_t)addr + offset);
1059 			oldoffset = offset;
1060 
1061 			/*
1062 			 * Perform prevalidation of the struct load_command
1063 			 * before we attempt to use its contents.  Invalid
1064 			 * values are ones which result in an overflow, or
1065 			 * which can not possibly be valid commands, or which
1066 			 * straddle or exist past the reserved section at the
1067 			 * start of the image.
1068 			 */
1069 			if (os_add_overflow(offset, lcp->cmdsize, &offset) ||
1070 			    lcp->cmdsize < sizeof(struct load_command) ||
1071 			    offset > cmds_size) {
1072 				ret = LOAD_BADMACHO;
1073 				break;
1074 			}
1075 
1076 			/*
1077 			 * Act on struct load_command's for which kernel
1078 			 * intervention is required.
1079 			 * Note that each load command implementation is expected to validate
1080 			 * that lcp->cmdsize is large enough to fit its specific struct type
1081 			 * before dereferencing fields not covered by struct load_command.
1082 			 */
1083 			switch (lcp->cmd) {
1084 			case LC_SEGMENT: {
1085 				struct segment_command *scp = (struct segment_command *) lcp;
1086 				if (scp->cmdsize < sizeof(*scp)) {
1087 					ret = LOAD_BADMACHO;
1088 					break;
1089 				}
1090 				if (pass == 0) {
1091 					if (is_dyld && scp->vmaddr == 0 && scp->fileoff == 0) {
1092 						dyld_no_load_addr = TRUE;
1093 						if (!slide_realign) {
1094 							/* got what we need, bail early on pass 0 */
1095 							continue;
1096 						}
1097 					}
1098 
1099 #if __arm64__
1100 					assert(!abi64);
1101 
1102 					if (scp->initprot == 0 && scp->maxprot == 0 && scp->vmaddr == 0) {
1103 						/* PAGEZERO */
1104 						if (os_add3_overflow(scp->vmaddr, scp->vmsize, slide, &pagezero_end) || pagezero_end > UINT32_MAX) {
1105 							ret = LOAD_BADMACHO;
1106 							break;
1107 						}
1108 					}
1109 					if (scp->initprot & VM_PROT_EXECUTE) {
1110 						/* TEXT */
1111 						if (os_add3_overflow(scp->vmaddr, scp->vmsize, slide, &executable_end) || executable_end > UINT32_MAX) {
1112 							ret = LOAD_BADMACHO;
1113 							break;
1114 						}
1115 					}
1116 					if (scp->initprot & VM_PROT_WRITE) {
1117 						/* DATA */
1118 						if (os_add_overflow(scp->vmaddr, slide, &writable_start) || writable_start > UINT32_MAX) {
1119 							ret = LOAD_BADMACHO;
1120 							break;
1121 						}
1122 					}
1123 #endif /* __arm64__ */
1124 					break;
1125 				}
1126 
1127 				if (pass == 1 && !strncmp(scp->segname, "__XHDR", sizeof(scp->segname))) {
1128 					found_xhdr = TRUE;
1129 				}
1130 
1131 				if (pass != 2) {
1132 					break;
1133 				}
1134 
1135 				if (abi64) {
1136 					/*
1137 					 * Having an LC_SEGMENT command for the
1138 					 * wrong ABI is invalid <rdar://problem/11021230>
1139 					 */
1140 					ret = LOAD_BADMACHO;
1141 					break;
1142 				}
1143 
1144 				ret = load_segment(lcp,
1145 				    header->filetype,
1146 				    control,
1147 				    file_offset,
1148 				    macho_size,
1149 				    vp,
1150 				    map,
1151 				    slide,
1152 				    result,
1153 				    imgp);
1154 				if (ret == LOAD_SUCCESS && scp->fileoff == 0 && scp->filesize > 0) {
1155 					/* Enforce a single segment mapping offset zero, with R+X
1156 					 * protection. */
1157 					if (found_header_segment ||
1158 					    ((scp->initprot & (VM_PROT_READ | VM_PROT_EXECUTE)) != (VM_PROT_READ | VM_PROT_EXECUTE))) {
1159 						ret = LOAD_BADMACHO;
1160 						break;
1161 					}
1162 					found_header_segment = TRUE;
1163 				}
1164 
1165 				break;
1166 			}
1167 			case LC_SEGMENT_64: {
1168 				struct segment_command_64 *scp64 = (struct segment_command_64 *) lcp;
1169 				if (scp64->cmdsize < sizeof(*scp64)) {
1170 					ret = LOAD_BADMACHO;
1171 					break;
1172 				}
1173 				if (pass == 0) {
1174 					if (is_dyld && scp64->vmaddr == 0 && scp64->fileoff == 0) {
1175 						dyld_no_load_addr = TRUE;
1176 					}
1177 					/* got what we need, bail early on pass 0 */
1178 					continue;
1179 				}
1180 
1181 				if (pass == 1 && !strncmp(scp64->segname, "__XHDR", sizeof(scp64->segname))) {
1182 					found_xhdr = TRUE;
1183 				}
1184 
1185 				if (pass != 2) {
1186 					break;
1187 				}
1188 
1189 				if (!abi64) {
1190 					/*
1191 					 * Having an LC_SEGMENT_64 command for the
1192 					 * wrong ABI is invalid <rdar://problem/11021230>
1193 					 */
1194 					ret = LOAD_BADMACHO;
1195 					break;
1196 				}
1197 
1198 				ret = load_segment(lcp,
1199 				    header->filetype,
1200 				    control,
1201 				    file_offset,
1202 				    macho_size,
1203 				    vp,
1204 				    map,
1205 				    slide,
1206 				    result,
1207 				    imgp);
1208 
1209 				if (ret == LOAD_SUCCESS && scp64->fileoff == 0 && scp64->filesize > 0) {
1210 					/* Enforce a single segment mapping offset zero, with R+X
1211 					 * protection. */
1212 					if (found_header_segment ||
1213 					    ((scp64->initprot & (VM_PROT_READ | VM_PROT_EXECUTE)) != (VM_PROT_READ | VM_PROT_EXECUTE))) {
1214 						ret = LOAD_BADMACHO;
1215 						break;
1216 					}
1217 					found_header_segment = TRUE;
1218 				}
1219 
1220 				break;
1221 			}
1222 			case LC_UNIXTHREAD: {
1223 				boolean_t is_x86_64_compat_binary = FALSE;
1224 				if (pass != 1) {
1225 					break;
1226 				}
1227 #if CONFIG_ROSETTA
1228 				if (depth == 2 && (imgp->ip_flags & IMGPF_ROSETTA)) {
1229 					// Ignore dyld, Rosetta will parse it's load commands to get the
1230 					// entry point.
1231 					result->validentry = 1;
1232 					break;
1233 				}
1234 #endif
1235 				ret = load_unixthread(
1236 					(struct thread_command *) lcp,
1237 					thread,
1238 					slide,
1239 					is_x86_64_compat_binary,
1240 					result);
1241 				break;
1242 			}
1243 			case LC_MAIN:
1244 				if (pass != 1) {
1245 					break;
1246 				}
1247 				if (depth != 1) {
1248 					break;
1249 				}
1250 				ret = load_main(
1251 					(struct entry_point_command *) lcp,
1252 					thread,
1253 					slide,
1254 					result);
1255 				break;
1256 			case LC_LOAD_DYLINKER:
1257 				if (pass != 3) {
1258 					break;
1259 				}
1260 				if ((depth == 1) && (dlp == 0)) {
1261 					dlp = (struct dylinker_command *)lcp;
1262 				} else {
1263 					ret = LOAD_FAILURE;
1264 				}
1265 				break;
1266 			case LC_UUID:
1267 				if (pass == 1 && depth == 1) {
1268 					ret = load_uuid((struct uuid_command *) lcp,
1269 					    (char *)addr + cmds_size,
1270 					    result);
1271 				}
1272 				break;
1273 			case LC_CODE_SIGNATURE:
1274 				/* CODE SIGNING */
1275 				if (pass != 1) {
1276 					break;
1277 				}
1278 
1279 				/* pager -> uip ->
1280 				 *  load signatures & store in uip
1281 				 *  set VM object "signed_pages"
1282 				 */
1283 				ret = load_code_signature(
1284 					(struct linkedit_data_command *) lcp,
1285 					vp,
1286 					file_offset,
1287 					macho_size,
1288 					header->cputype,
1289 					header->cpusubtype,
1290 					result,
1291 					imgp);
1292 				if (ret != LOAD_SUCCESS) {
1293 					printf("proc %d: load code signature error %d "
1294 					    "for file \"%s\"\n",
1295 					    proc_getpid(p), ret, vp->v_name);
1296 					/*
1297 					 * Allow injections to be ignored on devices w/o enforcement enabled
1298 					 */
1299 					if (!cs_process_global_enforcement()) {
1300 						ret = LOAD_SUCCESS; /* ignore error */
1301 					}
1302 				} else {
1303 					got_code_signatures = TRUE;
1304 				}
1305 
1306 				if (got_code_signatures) {
1307 					unsigned tainted = CS_VALIDATE_TAINTED;
1308 					boolean_t valid = FALSE;
1309 					vm_size_t off = 0;
1310 
1311 
1312 					if (cs_debug > 10) {
1313 						printf("validating initial pages of %s\n", vp->v_name);
1314 					}
1315 
1316 					while (off < alloc_size && ret == LOAD_SUCCESS) {
1317 						tainted = CS_VALIDATE_TAINTED;
1318 
1319 						valid = cs_validate_range(vp,
1320 						    NULL,
1321 						    file_offset + off,
1322 						    (const void *)((uintptr_t)addr + off),
1323 						    MIN(PAGE_SIZE, cmds_size),
1324 						    &tainted);
1325 						if (!valid || (tainted & CS_VALIDATE_TAINTED)) {
1326 							if (cs_debug) {
1327 								printf("CODE SIGNING: %s[%d]: invalid initial page at offset %lld validated:%d tainted:%d csflags:0x%x\n",
1328 								    vp->v_name, proc_getpid(p), (long long)(file_offset + off), valid, tainted, result->csflags);
1329 							}
1330 							if (cs_process_global_enforcement() ||
1331 							    (result->csflags & (CS_HARD | CS_KILL | CS_ENFORCEMENT))) {
1332 								ret = LOAD_FAILURE;
1333 							}
1334 							result->csflags &= ~CS_VALID;
1335 						}
1336 						off += PAGE_SIZE;
1337 					}
1338 				}
1339 
1340 				break;
1341 #if CONFIG_CODE_DECRYPTION
1342 			case LC_ENCRYPTION_INFO:
1343 			case LC_ENCRYPTION_INFO_64:
1344 				if (pass != 3) {
1345 					break;
1346 				}
1347 				ret = set_code_unprotect(
1348 					(struct encryption_info_command *) lcp,
1349 					addr, map, slide, vp, file_offset,
1350 					header->cputype, header->cpusubtype);
1351 				if (ret != LOAD_SUCCESS) {
1352 					os_reason_t load_failure_reason = OS_REASON_NULL;
1353 					printf("proc %d: set_code_unprotect() error %d "
1354 					    "for file \"%s\"\n",
1355 					    proc_getpid(p), ret, vp->v_name);
1356 					/*
1357 					 * Don't let the app run if it's
1358 					 * encrypted but we failed to set up the
1359 					 * decrypter. If the keys are missing it will
1360 					 * return LOAD_DECRYPTFAIL.
1361 					 */
1362 					if (ret == LOAD_DECRYPTFAIL) {
1363 						/* failed to load due to missing FP keys */
1364 						proc_lock(p);
1365 						p->p_lflag |= P_LTERM_DECRYPTFAIL;
1366 						proc_unlock(p);
1367 
1368 						KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1369 						    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_FAIRPLAY_DECRYPT, 0, 0);
1370 						load_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_FAIRPLAY_DECRYPT);
1371 					} else {
1372 						KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1373 						    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_DECRYPT, 0, 0);
1374 						load_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_DECRYPT);
1375 					}
1376 
1377 					/*
1378 					 * Don't signal the process if it was forked and in a partially constructed
1379 					 * state as part of a spawn -- it will just be torn down when the exec fails.
1380 					 */
1381 					if (!spawn) {
1382 						assert(load_failure_reason != OS_REASON_NULL);
1383 						{
1384 							psignal_with_reason(current_proc(), SIGKILL, load_failure_reason);
1385 							load_failure_reason = OS_REASON_NULL;
1386 						}
1387 					} else {
1388 						os_reason_free(load_failure_reason);
1389 						load_failure_reason = OS_REASON_NULL;
1390 					}
1391 				}
1392 				break;
1393 #endif
1394 			case LC_VERSION_MIN_IPHONEOS:
1395 			case LC_VERSION_MIN_MACOSX:
1396 			case LC_VERSION_MIN_WATCHOS:
1397 			case LC_VERSION_MIN_TVOS: {
1398 				struct version_min_command *vmc;
1399 
1400 				if (depth != 1 || pass != 0) {
1401 					break;
1402 				}
1403 				vmc = (struct version_min_command *) lcp;
1404 				ret = load_version(vmc, &found_version_cmd, imgp, result);
1405 #if XNU_TARGET_OS_OSX
1406 				if (ret == LOAD_SUCCESS) {
1407 					if (result->ip_platform == PLATFORM_IOS) {
1408 						vm_map_mark_alien(map);
1409 					} else {
1410 						assert(!vm_map_is_alien(map));
1411 					}
1412 				}
1413 #endif /* XNU_TARGET_OS_OSX */
1414 				break;
1415 			}
1416 			case LC_BUILD_VERSION: {
1417 				if (depth != 1 || pass != 0) {
1418 					break;
1419 				}
1420 				struct build_version_command* bvc = (struct build_version_command*)lcp;
1421 				if (bvc->cmdsize < sizeof(*bvc)) {
1422 					ret = LOAD_BADMACHO;
1423 					break;
1424 				}
1425 				if (found_version_cmd == TRUE) {
1426 					ret = LOAD_BADMACHO;
1427 					break;
1428 				}
1429 				result->ip_platform = bvc->platform;
1430 				result->lr_sdk = bvc->sdk;
1431 				result->lr_min_sdk = bvc->minos;
1432 				found_version_cmd = TRUE;
1433 #if XNU_TARGET_OS_OSX
1434 				if (result->ip_platform == PLATFORM_IOS) {
1435 					vm_map_mark_alien(map);
1436 				} else {
1437 					assert(!vm_map_is_alien(map));
1438 				}
1439 #endif /* XNU_TARGET_OS_OSX */
1440 				break;
1441 			}
1442 			default:
1443 				/* Other commands are ignored by the kernel */
1444 				ret = LOAD_SUCCESS;
1445 				break;
1446 			}
1447 			if (ret != LOAD_SUCCESS) {
1448 				break;
1449 			}
1450 		}
1451 		if (ret != LOAD_SUCCESS) {
1452 			break;
1453 		}
1454 	}
1455 
1456 	if (ret == LOAD_SUCCESS) {
1457 		if (!got_code_signatures && cs_process_global_enforcement()) {
1458 			ret = LOAD_FAILURE;
1459 		}
1460 
1461 		/* Make sure if we need dyld, we got it */
1462 		if (result->needs_dynlinker && !dlp) {
1463 			ret = LOAD_FAILURE;
1464 		}
1465 
1466 		if ((ret == LOAD_SUCCESS) && (dlp != 0)) {
1467 			/*
1468 			 * load the dylinker, and slide it by the independent DYLD ASLR
1469 			 * offset regardless of the PIE-ness of the main binary.
1470 			 */
1471 			ret = load_dylinker(dlp, header->cputype, map, thread, depth,
1472 			    dyld_aslr_offset, result, imgp);
1473 		}
1474 
1475 #if CONFIG_ROSETTA
1476 		if ((ret == LOAD_SUCCESS) && (depth == 1) && (imgp->ip_flags & IMGPF_ROSETTA)) {
1477 			ret = load_rosetta(map, thread, result, imgp);
1478 			if (ret == LOAD_SUCCESS) {
1479 				if (result->user_stack_alloc_size != 0) {
1480 					// If a stack allocation is required then add a 4gb gap after the main
1481 					// binary/dyld for the worst case static translation size.
1482 					mach_vm_size_t reserved_aot_size = 0x100000000;
1483 					vm_map_offset_t mask = vm_map_page_mask(map);
1484 
1485 					mach_vm_address_t vm_end;
1486 					if (dlp != 0) {
1487 						vm_end = vm_map_round_page(result->dynlinker_max_vm_addr, mask);
1488 					} else {
1489 						vm_end = vm_map_round_page(result->max_vm_addr, mask);
1490 					}
1491 
1492 					mach_vm_size_t user_stack_size = vm_map_round_page(result->user_stack_alloc_size, mask);
1493 					result->user_stack = vm_map_round_page(vm_end + user_stack_size + reserved_aot_size + slide, mask);
1494 				}
1495 			}
1496 		}
1497 #endif
1498 
1499 		if ((ret == LOAD_SUCCESS) && (depth == 1)) {
1500 			if (result->thread_count == 0) {
1501 				ret = LOAD_FAILURE;
1502 			}
1503 #if CONFIG_ENFORCE_SIGNED_CODE
1504 			if (!(result->csflags & CS_NO_UNTRUSTED_HELPERS)) {
1505 				ret = LOAD_FAILURE;
1506 			}
1507 #endif
1508 		}
1509 	}
1510 
1511 	if (ret == LOAD_BADMACHO && found_xhdr) {
1512 		ret = LOAD_BADMACHO_UPX;
1513 	}
1514 
1515 	kfree_data(addr, alloc_size);
1516 
1517 	return ret;
1518 }
1519 
1520 load_return_t
validate_potential_simulator_binary(cpu_type_t exectype __unused,struct image_params * imgp __unused,off_t file_offset __unused,off_t macho_size __unused)1521 validate_potential_simulator_binary(
1522 	cpu_type_t               exectype __unused,
1523 	struct image_params      *imgp __unused,
1524 	off_t                    file_offset __unused,
1525 	off_t                    macho_size __unused)
1526 {
1527 #if __x86_64__
1528 	/* Allow 32 bit exec only for simulator binaries */
1529 	if (bootarg_no32exec && imgp != NULL && exectype == CPU_TYPE_X86) {
1530 		if (imgp->ip_simulator_binary == IMGPF_SB_DEFAULT) {
1531 			boolean_t simulator_binary = check_if_simulator_binary(imgp, file_offset, macho_size);
1532 			imgp->ip_simulator_binary = simulator_binary ? IMGPF_SB_TRUE : IMGPF_SB_FALSE;
1533 		}
1534 
1535 		if (imgp->ip_simulator_binary != IMGPF_SB_TRUE) {
1536 			return LOAD_BADARCH;
1537 		}
1538 	}
1539 #endif
1540 	return LOAD_SUCCESS;
1541 }
1542 
1543 #if __x86_64__
1544 static boolean_t
check_if_simulator_binary(struct image_params * imgp,off_t file_offset,off_t macho_size)1545 check_if_simulator_binary(
1546 	struct image_params     *imgp,
1547 	off_t                   file_offset,
1548 	off_t                   macho_size)
1549 {
1550 	struct mach_header      *header;
1551 	char                    *ip_vdata = NULL;
1552 	kauth_cred_t            cred = NULL;
1553 	uint32_t                ncmds;
1554 	struct load_command     *lcp;
1555 	boolean_t               simulator_binary = FALSE;
1556 	void *                  addr = NULL;
1557 	vm_size_t               alloc_size, cmds_size;
1558 	size_t                  offset;
1559 	proc_t                  p = current_proc();             /* XXXX */
1560 	int                     error;
1561 	int                     resid = 0;
1562 	size_t                  mach_header_sz = sizeof(struct mach_header);
1563 
1564 
1565 	cred =  kauth_cred_proc_ref(p);
1566 
1567 	/* Allocate page to copyin mach header */
1568 	ip_vdata = kalloc_data(PAGE_SIZE, Z_WAITOK | Z_ZERO);
1569 	if (ip_vdata == NULL) {
1570 		goto bad;
1571 	}
1572 
1573 	/* Read the Mach-O header */
1574 	error = vn_rdwr(UIO_READ, imgp->ip_vp, ip_vdata,
1575 	    PAGE_SIZE, file_offset,
1576 	    UIO_SYSSPACE, (IO_UNIT | IO_NODELOCKED),
1577 	    cred, &resid, p);
1578 	if (error) {
1579 		goto bad;
1580 	}
1581 
1582 	header = (struct mach_header *)ip_vdata;
1583 
1584 	if (header->magic == MH_MAGIC_64 ||
1585 	    header->magic == MH_CIGAM_64) {
1586 		mach_header_sz = sizeof(struct mach_header_64);
1587 	}
1588 
1589 	/* ensure header + sizeofcmds falls within the file */
1590 	if (os_add_overflow(mach_header_sz, header->sizeofcmds, &cmds_size) ||
1591 	    (off_t)cmds_size > macho_size ||
1592 	    round_page_overflow(cmds_size, &alloc_size) ||
1593 	    alloc_size > INT_MAX) {
1594 		goto bad;
1595 	}
1596 
1597 	/*
1598 	 * Map the load commands into kernel memory.
1599 	 */
1600 	addr = kalloc_data(alloc_size, Z_WAITOK);
1601 	if (addr == NULL) {
1602 		goto bad;
1603 	}
1604 
1605 	error = vn_rdwr(UIO_READ, imgp->ip_vp, addr, (int)alloc_size, file_offset,
1606 	    UIO_SYSSPACE, IO_NODELOCKED, cred, &resid, p);
1607 	if (error) {
1608 		goto bad;
1609 	}
1610 
1611 	if (resid) {
1612 		/* We must be able to read in as much as the mach_header indicated */
1613 		goto bad;
1614 	}
1615 
1616 	/*
1617 	 * Loop through each of the load_commands indicated by the
1618 	 * Mach-O header; if an absurd value is provided, we just
1619 	 * run off the end of the reserved section by incrementing
1620 	 * the offset too far, so we are implicitly fail-safe.
1621 	 */
1622 	offset = mach_header_sz;
1623 	ncmds = header->ncmds;
1624 
1625 	while (ncmds--) {
1626 		/* ensure enough space for a minimal load command */
1627 		if (offset + sizeof(struct load_command) > cmds_size) {
1628 			break;
1629 		}
1630 
1631 		/*
1632 		 *	Get a pointer to the command.
1633 		 */
1634 		lcp = (struct load_command *)((uintptr_t)addr + offset);
1635 
1636 		/*
1637 		 * Perform prevalidation of the struct load_command
1638 		 * before we attempt to use its contents.  Invalid
1639 		 * values are ones which result in an overflow, or
1640 		 * which can not possibly be valid commands, or which
1641 		 * straddle or exist past the reserved section at the
1642 		 * start of the image.
1643 		 */
1644 		if (os_add_overflow(offset, lcp->cmdsize, &offset) ||
1645 		    lcp->cmdsize < sizeof(struct load_command) ||
1646 		    offset > cmds_size) {
1647 			break;
1648 		}
1649 
1650 		/* Check if its a simulator binary. */
1651 		switch (lcp->cmd) {
1652 		case LC_VERSION_MIN_WATCHOS:
1653 			simulator_binary = TRUE;
1654 			break;
1655 
1656 		case LC_BUILD_VERSION: {
1657 			struct build_version_command *bvc;
1658 
1659 			bvc = (struct build_version_command *) lcp;
1660 			if (bvc->cmdsize < sizeof(*bvc)) {
1661 				/* unsafe to use this command struct if cmdsize
1662 				* validated above is too small for it to fit */
1663 				break;
1664 			}
1665 			if (bvc->platform == PLATFORM_IOSSIMULATOR ||
1666 			    bvc->platform == PLATFORM_WATCHOSSIMULATOR) {
1667 				simulator_binary = TRUE;
1668 			}
1669 
1670 			break;
1671 		}
1672 
1673 		case LC_VERSION_MIN_IPHONEOS: {
1674 			simulator_binary = TRUE;
1675 			break;
1676 		}
1677 
1678 		default:
1679 			/* ignore other load commands */
1680 			break;
1681 		}
1682 
1683 		if (simulator_binary == TRUE) {
1684 			break;
1685 		}
1686 	}
1687 
1688 bad:
1689 	if (ip_vdata) {
1690 		kfree_data(ip_vdata, PAGE_SIZE);
1691 	}
1692 
1693 	if (cred) {
1694 		kauth_cred_unref(&cred);
1695 	}
1696 
1697 	if (addr) {
1698 		kfree_data(addr, alloc_size);
1699 	}
1700 
1701 	return simulator_binary;
1702 }
1703 #endif /* __x86_64__ */
1704 
1705 #if CONFIG_CODE_DECRYPTION
1706 
1707 #define APPLE_UNPROTECTED_HEADER_SIZE   (3 * 4096)
1708 
1709 static load_return_t
unprotect_dsmos_segment(uint64_t file_off,uint64_t file_size,struct vnode * vp,off_t macho_offset,vm_map_t map,vm_map_offset_t map_addr,vm_map_size_t map_size)1710 unprotect_dsmos_segment(
1711 	uint64_t        file_off,
1712 	uint64_t        file_size,
1713 	struct vnode    *vp,
1714 	off_t           macho_offset,
1715 	vm_map_t        map,
1716 	vm_map_offset_t map_addr,
1717 	vm_map_size_t   map_size)
1718 {
1719 	kern_return_t   kr;
1720 	uint64_t        slice_off;
1721 
1722 	/*
1723 	 * The first APPLE_UNPROTECTED_HEADER_SIZE bytes (from offset 0 of
1724 	 * this part of a Universal binary) are not protected...
1725 	 * The rest needs to be "transformed".
1726 	 */
1727 	slice_off = file_off - macho_offset;
1728 	if (slice_off <= APPLE_UNPROTECTED_HEADER_SIZE &&
1729 	    slice_off + file_size <= APPLE_UNPROTECTED_HEADER_SIZE) {
1730 		/* it's all unprotected, nothing to do... */
1731 		kr = KERN_SUCCESS;
1732 	} else {
1733 		if (slice_off <= APPLE_UNPROTECTED_HEADER_SIZE) {
1734 			/*
1735 			 * We start mapping in the unprotected area.
1736 			 * Skip the unprotected part...
1737 			 */
1738 			uint64_t delta_file;
1739 			vm_map_offset_t delta_map;
1740 
1741 			delta_file = (uint64_t)APPLE_UNPROTECTED_HEADER_SIZE;
1742 			delta_file -= slice_off;
1743 			if (os_convert_overflow(delta_file, &delta_map)) {
1744 				return LOAD_BADMACHO;
1745 			}
1746 			if (os_add_overflow(map_addr, delta_map, &map_addr)) {
1747 				return LOAD_BADMACHO;
1748 			}
1749 			if (os_sub_overflow(map_size, delta_map, &map_size)) {
1750 				return LOAD_BADMACHO;
1751 			}
1752 		}
1753 		/* ... transform the rest of the mapping. */
1754 		struct pager_crypt_info crypt_info;
1755 		crypt_info.page_decrypt = dsmos_page_transform;
1756 		crypt_info.crypt_ops = NULL;
1757 		crypt_info.crypt_end = NULL;
1758 #pragma unused(vp, macho_offset)
1759 		crypt_info.crypt_ops = (void *)0x2e69cf40;
1760 		vm_map_offset_t crypto_backing_offset;
1761 		crypto_backing_offset = -1; /* i.e. use map entry's offset */
1762 #if VM_MAP_DEBUG_APPLE_PROTECT
1763 		if (vm_map_debug_apple_protect) {
1764 			struct proc *p;
1765 			p = current_proc();
1766 			printf("APPLE_PROTECT: %d[%s] map %p "
1767 			    "[0x%llx:0x%llx] %s(%s)\n",
1768 			    proc_getpid(p), p->p_comm, map,
1769 			    (uint64_t) map_addr,
1770 			    (uint64_t) (map_addr + map_size),
1771 			    __FUNCTION__, vp->v_name);
1772 		}
1773 #endif /* VM_MAP_DEBUG_APPLE_PROTECT */
1774 
1775 		/* The DSMOS pager can only be used by apple signed code */
1776 		struct cs_blob * blob = csvnode_get_blob(vp, file_off);
1777 		if (blob == NULL || !blob->csb_platform_binary || blob->csb_platform_path) {
1778 			return LOAD_FAILURE;
1779 		}
1780 
1781 		kr = vm_map_apple_protected(map,
1782 		    map_addr,
1783 		    map_addr + map_size,
1784 		    crypto_backing_offset,
1785 		    &crypt_info,
1786 		    CRYPTID_APP_ENCRYPTION);
1787 	}
1788 
1789 	if (kr != KERN_SUCCESS) {
1790 		return LOAD_FAILURE;
1791 	}
1792 	return LOAD_SUCCESS;
1793 }
1794 #else   /* CONFIG_CODE_DECRYPTION */
1795 static load_return_t
unprotect_dsmos_segment(__unused uint64_t file_off,__unused uint64_t file_size,__unused struct vnode * vp,__unused off_t macho_offset,__unused vm_map_t map,__unused vm_map_offset_t map_addr,__unused vm_map_size_t map_size)1796 unprotect_dsmos_segment(
1797 	__unused        uint64_t        file_off,
1798 	__unused        uint64_t        file_size,
1799 	__unused        struct vnode    *vp,
1800 	__unused        off_t           macho_offset,
1801 	__unused        vm_map_t        map,
1802 	__unused        vm_map_offset_t map_addr,
1803 	__unused        vm_map_size_t   map_size)
1804 {
1805 	return LOAD_SUCCESS;
1806 }
1807 #endif  /* CONFIG_CODE_DECRYPTION */
1808 
1809 
1810 /*
1811  * map_segment:
1812  *	Maps a Mach-O segment, taking care of mis-alignment (wrt the system
1813  *	page size) issues.
1814  *
1815  *	The mapping might result in 1, 2 or 3 map entries:
1816  *      1. for the first page, which could be overlap with the previous
1817  *         mapping,
1818  *      2. for the center (if applicable),
1819  *      3. for the last page, which could overlap with the next mapping.
1820  *
1821  *	For each of those map entries, we might have to interpose a
1822  *	"fourk_pager" to deal with mis-alignment wrt the system page size,
1823  *	either in the mapping address and/or size or the file offset and/or
1824  *	size.
1825  *	The "fourk_pager" itself would be mapped with proper alignment
1826  *	wrt the system page size and would then be populated with the
1827  *	information about the intended mapping, with a "4KB" granularity.
1828  */
1829 static kern_return_t
map_segment(vm_map_t map,vm_map_offset_t vm_start,vm_map_offset_t vm_end,memory_object_control_t control,vm_map_offset_t file_start,vm_map_offset_t file_end,vm_prot_t initprot,vm_prot_t maxprot,load_result_t * result)1830 map_segment(
1831 	vm_map_t                map,
1832 	vm_map_offset_t         vm_start,
1833 	vm_map_offset_t         vm_end,
1834 	memory_object_control_t control,
1835 	vm_map_offset_t         file_start,
1836 	vm_map_offset_t         file_end,
1837 	vm_prot_t               initprot,
1838 	vm_prot_t               maxprot,
1839 	load_result_t           *result)
1840 {
1841 	vm_map_offset_t cur_offset, cur_start, cur_end;
1842 	kern_return_t   ret;
1843 	vm_map_offset_t effective_page_mask;
1844 	vm_map_kernel_flags_t vmk_flags, cur_vmk_flags;
1845 
1846 	if (vm_end < vm_start ||
1847 	    file_end < file_start) {
1848 		return LOAD_BADMACHO;
1849 	}
1850 	if (vm_end == vm_start ||
1851 	    file_end == file_start) {
1852 		/* nothing to map... */
1853 		return LOAD_SUCCESS;
1854 	}
1855 
1856 	effective_page_mask = vm_map_page_mask(map);
1857 
1858 	vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
1859 	if (vm_map_page_aligned(vm_start, effective_page_mask) &&
1860 	    vm_map_page_aligned(vm_end, effective_page_mask) &&
1861 	    vm_map_page_aligned(file_start, effective_page_mask) &&
1862 	    vm_map_page_aligned(file_end, effective_page_mask)) {
1863 		/* all page-aligned and map-aligned: proceed */
1864 	} else {
1865 #if __arm64__
1866 		/* use an intermediate "4K" pager */
1867 		vmk_flags.vmkf_fourk = TRUE;
1868 #else /* __arm64__ */
1869 		panic("map_segment: unexpected mis-alignment "
1870 		    "vm[0x%llx:0x%llx] file[0x%llx:0x%llx]\n",
1871 		    (uint64_t) vm_start,
1872 		    (uint64_t) vm_end,
1873 		    (uint64_t) file_start,
1874 		    (uint64_t) file_end);
1875 #endif /* __arm64__ */
1876 	}
1877 
1878 	cur_offset = 0;
1879 	cur_start = vm_start;
1880 	cur_end = vm_start;
1881 #if __arm64__
1882 	if (!vm_map_page_aligned(vm_start, effective_page_mask)) {
1883 		/* one 4K pager for the 1st page */
1884 		cur_end = vm_map_round_page(cur_start, effective_page_mask);
1885 		if (cur_end > vm_end) {
1886 			cur_end = vm_start + (file_end - file_start);
1887 		}
1888 		if (control != MEMORY_OBJECT_CONTROL_NULL) {
1889 			/* no copy-on-read for mapped binaries */
1890 			vmk_flags.vmkf_no_copy_on_read = 1;
1891 			ret = vm_map_enter_mem_object_control(
1892 				map,
1893 				&cur_start,
1894 				cur_end - cur_start,
1895 				(mach_vm_offset_t)0,
1896 				VM_FLAGS_FIXED,
1897 				vmk_flags,
1898 				VM_KERN_MEMORY_NONE,
1899 				control,
1900 				file_start + cur_offset,
1901 				TRUE, /* copy */
1902 				initprot, maxprot,
1903 				VM_INHERIT_DEFAULT);
1904 		} else {
1905 			ret = vm_map_enter_mem_object(
1906 				map,
1907 				&cur_start,
1908 				cur_end - cur_start,
1909 				(mach_vm_offset_t)0,
1910 				VM_FLAGS_FIXED,
1911 				vmk_flags,
1912 				VM_KERN_MEMORY_NONE,
1913 				IPC_PORT_NULL,
1914 				0, /* offset */
1915 				TRUE, /* copy */
1916 				initprot, maxprot,
1917 				VM_INHERIT_DEFAULT);
1918 		}
1919 		if (ret != KERN_SUCCESS) {
1920 			return LOAD_NOSPACE;
1921 		}
1922 		cur_offset += cur_end - cur_start;
1923 	}
1924 #endif /* __arm64__ */
1925 	if (cur_end >= vm_start + (file_end - file_start)) {
1926 		/* all mapped: done */
1927 		goto done;
1928 	}
1929 	if (vm_map_round_page(cur_end, effective_page_mask) >=
1930 	    vm_map_trunc_page(vm_start + (file_end - file_start),
1931 	    effective_page_mask)) {
1932 		/* no middle */
1933 	} else {
1934 		cur_start = cur_end;
1935 		if ((vm_start & effective_page_mask) !=
1936 		    (file_start & effective_page_mask)) {
1937 			/* one 4K pager for the middle */
1938 			cur_vmk_flags = vmk_flags;
1939 		} else {
1940 			/* regular mapping for the middle */
1941 			cur_vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
1942 		}
1943 
1944 #if !defined(XNU_TARGET_OS_OSX)
1945 		(void) result;
1946 #else /* !defined(XNU_TARGET_OS_OSX) */
1947 		/*
1948 		 * This process doesn't have its new csflags (from
1949 		 * the image being loaded) yet, so tell VM to override the
1950 		 * current process's CS_ENFORCEMENT for this mapping.
1951 		 */
1952 		if (result->csflags & CS_ENFORCEMENT) {
1953 			cur_vmk_flags.vmkf_cs_enforcement = TRUE;
1954 		} else {
1955 			cur_vmk_flags.vmkf_cs_enforcement = FALSE;
1956 		}
1957 		cur_vmk_flags.vmkf_cs_enforcement_override = TRUE;
1958 #endif /* !defined(XNU_TARGET_OS_OSX) */
1959 
1960 		if (result->is_rosetta && (initprot & VM_PROT_EXECUTE) == VM_PROT_EXECUTE) {
1961 			cur_vmk_flags.vmkf_translated_allow_execute = TRUE;
1962 		}
1963 
1964 		cur_end = vm_map_trunc_page(vm_start + (file_end -
1965 		    file_start),
1966 		    effective_page_mask);
1967 		if (control != MEMORY_OBJECT_CONTROL_NULL) {
1968 			/* no copy-on-read for mapped binaries */
1969 			cur_vmk_flags.vmkf_no_copy_on_read = 1;
1970 			ret = vm_map_enter_mem_object_control(
1971 				map,
1972 				&cur_start,
1973 				cur_end - cur_start,
1974 				(mach_vm_offset_t)0,
1975 				VM_FLAGS_FIXED,
1976 				cur_vmk_flags,
1977 				VM_KERN_MEMORY_NONE,
1978 				control,
1979 				file_start + cur_offset,
1980 				TRUE, /* copy */
1981 				initprot, maxprot,
1982 				VM_INHERIT_DEFAULT);
1983 		} else {
1984 			ret = vm_map_enter_mem_object(
1985 				map,
1986 				&cur_start,
1987 				cur_end - cur_start,
1988 				(mach_vm_offset_t)0,
1989 				VM_FLAGS_FIXED,
1990 				cur_vmk_flags,
1991 				VM_KERN_MEMORY_NONE,
1992 				IPC_PORT_NULL,
1993 				0, /* offset */
1994 				TRUE, /* copy */
1995 				initprot, maxprot,
1996 				VM_INHERIT_DEFAULT);
1997 		}
1998 		if (ret != KERN_SUCCESS) {
1999 			return LOAD_NOSPACE;
2000 		}
2001 		cur_offset += cur_end - cur_start;
2002 	}
2003 	if (cur_end >= vm_start + (file_end - file_start)) {
2004 		/* all mapped: done */
2005 		goto done;
2006 	}
2007 	cur_start = cur_end;
2008 #if __arm64__
2009 	if (!vm_map_page_aligned(vm_start + (file_end - file_start),
2010 	    effective_page_mask)) {
2011 		/* one 4K pager for the last page */
2012 		cur_end = vm_start + (file_end - file_start);
2013 		if (control != MEMORY_OBJECT_CONTROL_NULL) {
2014 			/* no copy-on-read for mapped binaries */
2015 			vmk_flags.vmkf_no_copy_on_read = 1;
2016 			ret = vm_map_enter_mem_object_control(
2017 				map,
2018 				&cur_start,
2019 				cur_end - cur_start,
2020 				(mach_vm_offset_t)0,
2021 				VM_FLAGS_FIXED,
2022 				vmk_flags,
2023 				VM_KERN_MEMORY_NONE,
2024 				control,
2025 				file_start + cur_offset,
2026 				TRUE, /* copy */
2027 				initprot, maxprot,
2028 				VM_INHERIT_DEFAULT);
2029 		} else {
2030 			ret = vm_map_enter_mem_object(
2031 				map,
2032 				&cur_start,
2033 				cur_end - cur_start,
2034 				(mach_vm_offset_t)0,
2035 				VM_FLAGS_FIXED,
2036 				vmk_flags,
2037 				VM_KERN_MEMORY_NONE,
2038 				IPC_PORT_NULL,
2039 				0, /* offset */
2040 				TRUE, /* copy */
2041 				initprot, maxprot,
2042 				VM_INHERIT_DEFAULT);
2043 		}
2044 		if (ret != KERN_SUCCESS) {
2045 			return LOAD_NOSPACE;
2046 		}
2047 		cur_offset += cur_end - cur_start;
2048 	}
2049 #endif /* __arm64__ */
2050 done:
2051 	assert(cur_end >= vm_start + (file_end - file_start));
2052 	return LOAD_SUCCESS;
2053 }
2054 
2055 static
2056 load_return_t
load_segment(struct load_command * lcp,uint32_t filetype,void * control,off_t pager_offset,off_t macho_size,struct vnode * vp,vm_map_t map,int64_t slide,load_result_t * result,struct image_params * imgp)2057 load_segment(
2058 	struct load_command     *lcp,
2059 	uint32_t                filetype,
2060 	void *                  control,
2061 	off_t                   pager_offset,
2062 	off_t                   macho_size,
2063 	struct vnode            *vp,
2064 	vm_map_t                map,
2065 	int64_t                 slide,
2066 	load_result_t           *result,
2067 	struct image_params     *imgp)
2068 {
2069 	struct segment_command_64 segment_command, *scp;
2070 	kern_return_t           ret;
2071 	vm_map_size_t           delta_size;
2072 	vm_prot_t               initprot;
2073 	vm_prot_t               maxprot;
2074 	size_t                  segment_command_size, total_section_size,
2075 	    single_section_size;
2076 	uint64_t                file_offset, file_size;
2077 	vm_map_offset_t         vm_offset;
2078 	size_t                  vm_size;
2079 	vm_map_offset_t         vm_start, vm_end, vm_end_aligned;
2080 	vm_map_offset_t         file_start, file_end;
2081 	kern_return_t           kr;
2082 	boolean_t               verbose;
2083 	vm_map_size_t           effective_page_size;
2084 	vm_map_offset_t         effective_page_mask;
2085 #if __arm64__
2086 	vm_map_kernel_flags_t   vmk_flags;
2087 	boolean_t               fourk_align;
2088 #endif /* __arm64__ */
2089 
2090 	(void)imgp;
2091 
2092 	effective_page_size = vm_map_page_size(map);
2093 	effective_page_mask = vm_map_page_mask(map);
2094 
2095 	verbose = FALSE;
2096 	if (LC_SEGMENT_64 == lcp->cmd) {
2097 		segment_command_size = sizeof(struct segment_command_64);
2098 		single_section_size  = sizeof(struct section_64);
2099 #if __arm64__
2100 		/* 64-bit binary: should already be 16K-aligned */
2101 		fourk_align = FALSE;
2102 
2103 		if (vm_map_page_shift(map) == FOURK_PAGE_SHIFT &&
2104 		    PAGE_SHIFT != FOURK_PAGE_SHIFT) {
2105 			fourk_align = TRUE;
2106 			verbose = TRUE;
2107 		}
2108 #endif /* __arm64__ */
2109 	} else {
2110 		segment_command_size = sizeof(struct segment_command);
2111 		single_section_size  = sizeof(struct section);
2112 #if __arm64__
2113 		/* 32-bit binary: might need 4K-alignment */
2114 		if (effective_page_size != FOURK_PAGE_SIZE) {
2115 			/* not using 4K page size: need fourk_pager */
2116 			fourk_align = TRUE;
2117 			verbose = TRUE;
2118 		} else {
2119 			/* using 4K page size: no need for re-alignment */
2120 			fourk_align = FALSE;
2121 		}
2122 #endif /* __arm64__ */
2123 	}
2124 	if (lcp->cmdsize < segment_command_size) {
2125 		DEBUG4K_ERROR("LOAD_BADMACHO cmdsize %d < %zu\n", lcp->cmdsize, segment_command_size);
2126 		return LOAD_BADMACHO;
2127 	}
2128 	total_section_size = lcp->cmdsize - segment_command_size;
2129 
2130 	if (LC_SEGMENT_64 == lcp->cmd) {
2131 		scp = (struct segment_command_64 *)lcp;
2132 	} else {
2133 		scp = &segment_command;
2134 		widen_segment_command((struct segment_command *)lcp, scp);
2135 	}
2136 
2137 	if (verbose) {
2138 		MACHO_PRINTF(("+++ load_segment %s "
2139 		    "vm[0x%llx:0x%llx] file[0x%llx:0x%llx] "
2140 		    "prot %d/%d flags 0x%x\n",
2141 		    scp->segname,
2142 		    (uint64_t)(slide + scp->vmaddr),
2143 		    (uint64_t)(slide + scp->vmaddr + scp->vmsize),
2144 		    pager_offset + scp->fileoff,
2145 		    pager_offset + scp->fileoff + scp->filesize,
2146 		    scp->initprot,
2147 		    scp->maxprot,
2148 		    scp->flags));
2149 	}
2150 
2151 	/*
2152 	 * Make sure what we get from the file is really ours (as specified
2153 	 * by macho_size).
2154 	 */
2155 	if (scp->fileoff + scp->filesize < scp->fileoff ||
2156 	    scp->fileoff + scp->filesize > (uint64_t)macho_size) {
2157 		DEBUG4K_ERROR("LOAD_BADMACHO fileoff 0x%llx filesize 0x%llx macho_size 0x%llx\n", scp->fileoff, scp->filesize, (uint64_t)macho_size);
2158 		return LOAD_BADMACHO;
2159 	}
2160 	/*
2161 	 * Ensure that the number of sections specified would fit
2162 	 * within the load command size.
2163 	 */
2164 	if (total_section_size / single_section_size < scp->nsects) {
2165 		DEBUG4K_ERROR("LOAD_BADMACHO 0x%zx 0x%zx %d\n", total_section_size, single_section_size, scp->nsects);
2166 		return LOAD_BADMACHO;
2167 	}
2168 	/*
2169 	 * Make sure the segment is page-aligned in the file.
2170 	 */
2171 	if (os_add_overflow(pager_offset, scp->fileoff, &file_offset)) {
2172 		DEBUG4K_ERROR("LOAD_BADMACHO file_offset: 0x%llx + 0x%llx\n", pager_offset, scp->fileoff);
2173 		return LOAD_BADMACHO;
2174 	}
2175 	file_size = scp->filesize;
2176 #if __arm64__
2177 	if (fourk_align) {
2178 		if ((file_offset & FOURK_PAGE_MASK) != 0) {
2179 			/*
2180 			 * we can't mmap() it if it's not at least 4KB-aligned
2181 			 * in the file
2182 			 */
2183 			DEBUG4K_ERROR("LOAD_BADMACHO file_offset 0x%llx\n", file_offset);
2184 			return LOAD_BADMACHO;
2185 		}
2186 	} else
2187 #endif /* __arm64__ */
2188 	if ((file_offset & PAGE_MASK_64) != 0 ||
2189 	    /* we can't mmap() it if it's not page-aligned in the file */
2190 	    (file_offset & vm_map_page_mask(map)) != 0) {
2191 		/*
2192 		 * The 1st test would have failed if the system's page size
2193 		 * was what this process believe is the page size, so let's
2194 		 * fail here too for the sake of consistency.
2195 		 */
2196 		DEBUG4K_ERROR("LOAD_BADMACHO file_offset 0x%llx\n", file_offset);
2197 		return LOAD_BADMACHO;
2198 	}
2199 
2200 	/*
2201 	 * If we have a code signature attached for this slice
2202 	 * require that the segments are within the signed part
2203 	 * of the file.
2204 	 */
2205 	if (result->cs_end_offset &&
2206 	    result->cs_end_offset < (off_t)scp->fileoff &&
2207 	    result->cs_end_offset - scp->fileoff < scp->filesize) {
2208 		if (cs_debug) {
2209 			printf("section outside code signature\n");
2210 		}
2211 		DEBUG4K_ERROR("LOAD_BADMACHO end_offset 0x%llx fileoff 0x%llx filesize 0x%llx\n", result->cs_end_offset, scp->fileoff, scp->filesize);
2212 		return LOAD_BADMACHO;
2213 	}
2214 
2215 	if (os_add_overflow(scp->vmaddr, slide, &vm_offset)) {
2216 		if (cs_debug) {
2217 			printf("vmaddr too large\n");
2218 		}
2219 		DEBUG4K_ERROR("LOAD_BADMACHO vmaddr 0x%llx slide 0x%llx vm_offset 0x%llx\n", scp->vmaddr, slide, (uint64_t)vm_offset);
2220 		return LOAD_BADMACHO;
2221 	}
2222 
2223 	if (scp->vmsize > SIZE_MAX) {
2224 		DEBUG4K_ERROR("LOAD_BADMACHO vmsize 0x%llx\n", scp->vmsize);
2225 		return LOAD_BADMACHO;
2226 	}
2227 
2228 	vm_size = (size_t)scp->vmsize;
2229 
2230 	if (vm_size == 0) {
2231 		return LOAD_SUCCESS;
2232 	}
2233 	if (scp->vmaddr == 0 &&
2234 	    file_size == 0 &&
2235 	    vm_size != 0 &&
2236 	    (scp->initprot & VM_PROT_ALL) == VM_PROT_NONE &&
2237 	    (scp->maxprot & VM_PROT_ALL) == VM_PROT_NONE) {
2238 		if (map == VM_MAP_NULL) {
2239 			return LOAD_SUCCESS;
2240 		}
2241 
2242 		/*
2243 		 * For PIE, extend page zero rather than moving it.  Extending
2244 		 * page zero keeps early allocations from falling predictably
2245 		 * between the end of page zero and the beginning of the first
2246 		 * slid segment.
2247 		 */
2248 		/*
2249 		 * This is a "page zero" segment:  it starts at address 0,
2250 		 * is not mapped from the binary file and is not accessible.
2251 		 * User-space should never be able to access that memory, so
2252 		 * make it completely off limits by raising the VM map's
2253 		 * minimum offset.
2254 		 */
2255 		vm_end = (vm_map_offset_t)(vm_offset + vm_size);
2256 		if (vm_end < vm_offset) {
2257 			DEBUG4K_ERROR("LOAD_BADMACHO vm_end 0x%llx vm_offset 0x%llx vm_size 0x%llx\n", (uint64_t)vm_end, (uint64_t)vm_offset, (uint64_t)vm_size);
2258 			return LOAD_BADMACHO;
2259 		}
2260 
2261 		if (verbose) {
2262 			MACHO_PRINTF(("++++++ load_segment: "
2263 			    "page_zero up to 0x%llx\n",
2264 			    (uint64_t) vm_end));
2265 		}
2266 #if __arm64__
2267 		if (fourk_align) {
2268 			/* raise min_offset as much as page-alignment allows */
2269 			vm_end_aligned = vm_map_trunc_page(vm_end,
2270 			    effective_page_mask);
2271 		} else
2272 #endif /* __arm64__ */
2273 		{
2274 			vm_end = vm_map_round_page(vm_end,
2275 			    PAGE_MASK_64);
2276 			vm_end_aligned = vm_end;
2277 		}
2278 		ret = vm_map_raise_min_offset(map,
2279 		    vm_end_aligned);
2280 #if __arm64__
2281 		if (ret == 0 &&
2282 		    vm_end > vm_end_aligned) {
2283 			/* use fourk_pager to map the rest of pagezero */
2284 			assert(fourk_align);
2285 			vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
2286 			vmk_flags.vmkf_fourk = TRUE;
2287 			ret = vm_map_enter_mem_object(
2288 				map,
2289 				&vm_end_aligned,
2290 				vm_end - vm_end_aligned,
2291 				(mach_vm_offset_t) 0,   /* mask */
2292 				VM_FLAGS_FIXED,
2293 				vmk_flags,
2294 				VM_KERN_MEMORY_NONE,
2295 				IPC_PORT_NULL,
2296 				0,
2297 				FALSE,  /* copy */
2298 				(scp->initprot & VM_PROT_ALL),
2299 				(scp->maxprot & VM_PROT_ALL),
2300 				VM_INHERIT_DEFAULT);
2301 		}
2302 #endif /* __arm64__ */
2303 
2304 		if (ret != KERN_SUCCESS) {
2305 			DEBUG4K_ERROR("LOAD_FAILURE ret 0x%x\n", ret);
2306 			return LOAD_FAILURE;
2307 		}
2308 		return LOAD_SUCCESS;
2309 	} else {
2310 #if !defined(XNU_TARGET_OS_OSX)
2311 		/* not PAGEZERO: should not be mapped at address 0 */
2312 		if (filetype != MH_DYLINKER && (imgp->ip_flags & IMGPF_ROSETTA) == 0 && scp->vmaddr == 0) {
2313 			DEBUG4K_ERROR("LOAD_BADMACHO filetype %d vmaddr 0x%llx\n", filetype, scp->vmaddr);
2314 			return LOAD_BADMACHO;
2315 		}
2316 #endif /* !defined(XNU_TARGET_OS_OSX) */
2317 	}
2318 
2319 #if __arm64__
2320 	if (fourk_align) {
2321 		/* 4K-align */
2322 		file_start = vm_map_trunc_page(file_offset,
2323 		    FOURK_PAGE_MASK);
2324 		file_end = vm_map_round_page(file_offset + file_size,
2325 		    FOURK_PAGE_MASK);
2326 		vm_start = vm_map_trunc_page(vm_offset,
2327 		    FOURK_PAGE_MASK);
2328 		vm_end = vm_map_round_page(vm_offset + vm_size,
2329 		    FOURK_PAGE_MASK);
2330 
2331 		if (file_offset - file_start > FOURK_PAGE_MASK ||
2332 		    file_end - file_offset - file_size > FOURK_PAGE_MASK) {
2333 			DEBUG4K_ERROR("LOAD_BADMACHO file_start / file_size wrap "
2334 			    "[0x%llx:0x%llx] -> [0x%llx:0x%llx]\n",
2335 			    file_offset,
2336 			    file_offset + file_size,
2337 			    (uint64_t) file_start,
2338 			    (uint64_t) file_end);
2339 			return LOAD_BADMACHO;
2340 		}
2341 
2342 		if (!strncmp(scp->segname, "__LINKEDIT", 11) &&
2343 		    page_aligned(file_start) &&
2344 		    vm_map_page_aligned(file_start, vm_map_page_mask(map)) &&
2345 		    page_aligned(vm_start) &&
2346 		    vm_map_page_aligned(vm_start, vm_map_page_mask(map))) {
2347 			/* XXX last segment: ignore mis-aligned tail */
2348 			file_end = vm_map_round_page(file_end,
2349 			    effective_page_mask);
2350 			vm_end = vm_map_round_page(vm_end,
2351 			    effective_page_mask);
2352 		}
2353 	} else
2354 #endif /* __arm64__ */
2355 	{
2356 		file_start = vm_map_trunc_page(file_offset,
2357 		    effective_page_mask);
2358 		file_end = vm_map_round_page(file_offset + file_size,
2359 		    effective_page_mask);
2360 		vm_start = vm_map_trunc_page(vm_offset,
2361 		    effective_page_mask);
2362 		vm_end = vm_map_round_page(vm_offset + vm_size,
2363 		    effective_page_mask);
2364 
2365 		if (file_offset - file_start > effective_page_mask ||
2366 		    file_end - file_offset - file_size > effective_page_mask) {
2367 			DEBUG4K_ERROR("LOAD_BADMACHO file_start / file_size wrap "
2368 			    "[0x%llx:0x%llx] -> [0x%llx:0x%llx]\n",
2369 			    file_offset,
2370 			    file_offset + file_size,
2371 			    (uint64_t) file_start,
2372 			    (uint64_t) file_end);
2373 			return LOAD_BADMACHO;
2374 		}
2375 	}
2376 
2377 	if (vm_start < result->min_vm_addr) {
2378 		result->min_vm_addr = vm_start;
2379 	}
2380 	if (vm_end > result->max_vm_addr) {
2381 		result->max_vm_addr = vm_end;
2382 	}
2383 
2384 	if (map == VM_MAP_NULL) {
2385 		return LOAD_SUCCESS;
2386 	}
2387 
2388 	if (vm_size > 0) {
2389 		initprot = (scp->initprot) & VM_PROT_ALL;
2390 		maxprot = (scp->maxprot) & VM_PROT_ALL;
2391 		/*
2392 		 *	Map a copy of the file into the address space.
2393 		 */
2394 		if (verbose) {
2395 			MACHO_PRINTF(("++++++ load_segment: "
2396 			    "mapping at vm [0x%llx:0x%llx] of "
2397 			    "file [0x%llx:0x%llx]\n",
2398 			    (uint64_t) vm_start,
2399 			    (uint64_t) vm_end,
2400 			    (uint64_t) file_start,
2401 			    (uint64_t) file_end));
2402 		}
2403 		ret = map_segment(map,
2404 		    vm_start,
2405 		    vm_end,
2406 		    control,
2407 		    file_start,
2408 		    file_end,
2409 		    initprot,
2410 		    maxprot,
2411 		    result);
2412 		if (ret) {
2413 			DEBUG4K_ERROR("LOAD_NOSPACE start 0x%llx end 0x%llx ret 0x%x\n", (uint64_t)vm_start, (uint64_t)vm_end, ret);
2414 			return LOAD_NOSPACE;
2415 		}
2416 
2417 #if FIXME
2418 		/*
2419 		 *	If the file didn't end on a page boundary,
2420 		 *	we need to zero the leftover.
2421 		 */
2422 		delta_size = map_size - scp->filesize;
2423 		if (delta_size > 0) {
2424 			void *tmp = kalloc_data(delta_size, Z_WAITOK | Z_ZERO);
2425 			int rc;
2426 
2427 			if (tmp == NULL) {
2428 				DEBUG4K_ERROR("LOAD_RESOURCE delta_size 0x%llx ret 0x%x\n", delta_size, ret);
2429 				return LOAD_RESOURCE;
2430 			}
2431 
2432 			rc = copyout(tmp, map_addr + scp->filesize, delta_size);
2433 			kfree_data(tmp, delta_size);
2434 
2435 			if (rc) {
2436 				DEBUG4K_ERROR("LOAD_FAILURE copyout 0x%llx 0x%llx\n", map_addr + scp->filesize, delta_size);
2437 				return LOAD_FAILURE;
2438 			}
2439 		}
2440 #endif /* FIXME */
2441 	}
2442 
2443 	/*
2444 	 *	If the virtual size of the segment is greater
2445 	 *	than the size from the file, we need to allocate
2446 	 *	zero fill memory for the rest.
2447 	 */
2448 	if ((vm_end - vm_start) > (file_end - file_start)) {
2449 		delta_size = (vm_end - vm_start) - (file_end - file_start);
2450 	} else {
2451 		delta_size = 0;
2452 	}
2453 	if (delta_size > 0) {
2454 		vm_map_offset_t tmp_start;
2455 		vm_map_offset_t tmp_end;
2456 
2457 		if (os_add_overflow(vm_start, file_end - file_start, &tmp_start)) {
2458 			DEBUG4K_ERROR("LOAD_NOSPACE tmp_start: 0x%llx + 0x%llx\n", (uint64_t)vm_start, (uint64_t)(file_end - file_start));
2459 			return LOAD_NOSPACE;
2460 		}
2461 
2462 		if (os_add_overflow(tmp_start, delta_size, &tmp_end)) {
2463 			DEBUG4K_ERROR("LOAD_NOSPACE tmp_end: 0x%llx + 0x%llx\n", (uint64_t)tmp_start, (uint64_t)delta_size);
2464 			return LOAD_NOSPACE;
2465 		}
2466 
2467 		if (verbose) {
2468 			MACHO_PRINTF(("++++++ load_segment: "
2469 			    "delta mapping vm [0x%llx:0x%llx]\n",
2470 			    (uint64_t) tmp_start,
2471 			    (uint64_t) tmp_end));
2472 		}
2473 		kr = map_segment(map,
2474 		    tmp_start,
2475 		    tmp_end,
2476 		    MEMORY_OBJECT_CONTROL_NULL,
2477 		    0,
2478 		    delta_size,
2479 		    scp->initprot,
2480 		    scp->maxprot,
2481 		    result);
2482 		if (kr != KERN_SUCCESS) {
2483 			DEBUG4K_ERROR("LOAD_NOSPACE 0x%llx 0x%llx kr 0x%x\n", (unsigned long long)tmp_start, (uint64_t)delta_size, kr);
2484 			return LOAD_NOSPACE;
2485 		}
2486 	}
2487 
2488 	if ((scp->fileoff == 0) && (scp->filesize != 0)) {
2489 		result->mach_header = vm_offset;
2490 	}
2491 
2492 	if (scp->flags & SG_PROTECTED_VERSION_1) {
2493 		ret = unprotect_dsmos_segment(file_start,
2494 		    file_end - file_start,
2495 		    vp,
2496 		    pager_offset,
2497 		    map,
2498 		    vm_start,
2499 		    vm_end - vm_start);
2500 		if (ret != LOAD_SUCCESS) {
2501 			DEBUG4K_ERROR("unprotect 0x%llx 0x%llx ret %d \n", (uint64_t)vm_start, (uint64_t)vm_end, ret);
2502 			return ret;
2503 		}
2504 	} else {
2505 		ret = LOAD_SUCCESS;
2506 	}
2507 
2508 	if (LOAD_SUCCESS == ret &&
2509 	    filetype == MH_DYLINKER &&
2510 	    result->all_image_info_addr == MACH_VM_MIN_ADDRESS) {
2511 		note_all_image_info_section(scp,
2512 		    LC_SEGMENT_64 == lcp->cmd,
2513 		    single_section_size,
2514 		    ((const char *)lcp +
2515 		    segment_command_size),
2516 		    slide,
2517 		    result);
2518 	}
2519 
2520 	if (result->entry_point != MACH_VM_MIN_ADDRESS) {
2521 		if ((result->entry_point >= vm_offset) && (result->entry_point < (vm_offset + vm_size))) {
2522 			if ((scp->initprot & (VM_PROT_READ | VM_PROT_EXECUTE)) == (VM_PROT_READ | VM_PROT_EXECUTE)) {
2523 				result->validentry = 1;
2524 			} else {
2525 				/* right range but wrong protections, unset if previously validated */
2526 				result->validentry = 0;
2527 			}
2528 		}
2529 	}
2530 
2531 	if (ret != LOAD_SUCCESS && verbose) {
2532 		DEBUG4K_ERROR("ret %d\n", ret);
2533 	}
2534 	return ret;
2535 }
2536 
2537 static
2538 load_return_t
load_uuid(struct uuid_command * uulp,char * command_end,load_result_t * result)2539 load_uuid(
2540 	struct uuid_command     *uulp,
2541 	char                    *command_end,
2542 	load_result_t           *result
2543 	)
2544 {
2545 	/*
2546 	 * We need to check the following for this command:
2547 	 * - The command size should be atleast the size of struct uuid_command
2548 	 * - The UUID part of the command should be completely within the mach-o header
2549 	 */
2550 
2551 	if ((uulp->cmdsize < sizeof(struct uuid_command)) ||
2552 	    (((char *)uulp + sizeof(struct uuid_command)) > command_end)) {
2553 		return LOAD_BADMACHO;
2554 	}
2555 
2556 	memcpy(&result->uuid[0], &uulp->uuid[0], sizeof(result->uuid));
2557 	return LOAD_SUCCESS;
2558 }
2559 
2560 static
2561 load_return_t
load_version(struct version_min_command * vmc,boolean_t * found_version_cmd,struct image_params * imgp __unused,load_result_t * result)2562 load_version(
2563 	struct version_min_command     *vmc,
2564 	boolean_t               *found_version_cmd,
2565 	struct image_params             *imgp __unused,
2566 	load_result_t           *result
2567 	)
2568 {
2569 	uint32_t platform = 0;
2570 	uint32_t sdk;
2571 	uint32_t min_sdk;
2572 
2573 	if (vmc->cmdsize < sizeof(*vmc)) {
2574 		return LOAD_BADMACHO;
2575 	}
2576 	if (*found_version_cmd == TRUE) {
2577 		return LOAD_BADMACHO;
2578 	}
2579 	*found_version_cmd = TRUE;
2580 	sdk = vmc->sdk;
2581 	min_sdk = vmc->version;
2582 	switch (vmc->cmd) {
2583 	case LC_VERSION_MIN_MACOSX:
2584 		platform = PLATFORM_MACOS;
2585 		break;
2586 #if __x86_64__ /* __x86_64__ */
2587 	case LC_VERSION_MIN_IPHONEOS:
2588 		platform = PLATFORM_IOSSIMULATOR;
2589 		break;
2590 	case LC_VERSION_MIN_WATCHOS:
2591 		platform = PLATFORM_WATCHOSSIMULATOR;
2592 		break;
2593 	case LC_VERSION_MIN_TVOS:
2594 		platform = PLATFORM_TVOSSIMULATOR;
2595 		break;
2596 #else
2597 	case LC_VERSION_MIN_IPHONEOS: {
2598 #if __arm64__
2599 		if (vmc->sdk < (12 << 16)) {
2600 			/* app built with a pre-iOS12 SDK: apply legacy footprint mitigation */
2601 			result->legacy_footprint = TRUE;
2602 		}
2603 #endif /* __arm64__ */
2604 		platform = PLATFORM_IOS;
2605 		break;
2606 	}
2607 	case LC_VERSION_MIN_WATCHOS:
2608 		platform = PLATFORM_WATCHOS;
2609 		break;
2610 	case LC_VERSION_MIN_TVOS:
2611 		platform = PLATFORM_TVOS;
2612 		break;
2613 #endif /* __x86_64__ */
2614 	/* All LC_VERSION_MIN_* load commands are legacy and we will not be adding any more */
2615 	default:
2616 		sdk = (uint32_t)-1;
2617 		min_sdk = (uint32_t)-1;
2618 		__builtin_unreachable();
2619 	}
2620 	result->ip_platform = platform;
2621 	result->lr_min_sdk = min_sdk;
2622 	result->lr_sdk = sdk;
2623 	return LOAD_SUCCESS;
2624 }
2625 
2626 static
2627 load_return_t
load_main(struct entry_point_command * epc,thread_t thread,int64_t slide,load_result_t * result)2628 load_main(
2629 	struct entry_point_command      *epc,
2630 	thread_t                thread,
2631 	int64_t                         slide,
2632 	load_result_t           *result
2633 	)
2634 {
2635 	mach_vm_offset_t addr;
2636 	kern_return_t   ret;
2637 
2638 	if (epc->cmdsize < sizeof(*epc)) {
2639 		return LOAD_BADMACHO;
2640 	}
2641 	if (result->thread_count != 0) {
2642 		return LOAD_FAILURE;
2643 	}
2644 
2645 	if (thread == THREAD_NULL) {
2646 		return LOAD_SUCCESS;
2647 	}
2648 
2649 	/*
2650 	 * LC_MAIN specifies stack size but not location.
2651 	 * Add guard page to allocation size (MAXSSIZ includes guard page).
2652 	 */
2653 	if (epc->stacksize) {
2654 		if (os_add_overflow(epc->stacksize, 4 * PAGE_SIZE, &result->user_stack_size)) {
2655 			/*
2656 			 * We are going to immediately throw away this result, but we want
2657 			 * to make sure we aren't loading a dangerously close to
2658 			 * overflowing value, since this will have a guard page added to it
2659 			 * and be rounded to page boundaries
2660 			 */
2661 			return LOAD_BADMACHO;
2662 		}
2663 		result->user_stack_size = epc->stacksize;
2664 		if (os_add_overflow(epc->stacksize, PAGE_SIZE, &result->user_stack_alloc_size)) {
2665 			return LOAD_BADMACHO;
2666 		}
2667 		result->custom_stack = TRUE;
2668 	} else {
2669 		result->user_stack_alloc_size = MAXSSIZ;
2670 	}
2671 
2672 	/* use default location for stack */
2673 	ret = thread_userstackdefault(&addr, result->is_64bit_addr);
2674 	if (ret != KERN_SUCCESS) {
2675 		return LOAD_FAILURE;
2676 	}
2677 
2678 	/* The stack slides down from the default location */
2679 	result->user_stack = (user_addr_t)mach_vm_trunc_page((user_addr_t)addr - slide);
2680 
2681 	if (result->using_lcmain || result->entry_point != MACH_VM_MIN_ADDRESS) {
2682 		/* Already processed LC_MAIN or LC_UNIXTHREAD */
2683 		return LOAD_FAILURE;
2684 	}
2685 
2686 	/* kernel does *not* use entryoff from LC_MAIN.	 Dyld uses it. */
2687 	result->needs_dynlinker = TRUE;
2688 	result->using_lcmain = TRUE;
2689 
2690 	ret = thread_state_initialize( thread );
2691 	if (ret != KERN_SUCCESS) {
2692 		return LOAD_FAILURE;
2693 	}
2694 
2695 	result->unixproc = TRUE;
2696 	result->thread_count++;
2697 
2698 	return LOAD_SUCCESS;
2699 }
2700 
2701 static
2702 load_return_t
setup_driver_main(thread_t thread,int64_t slide,load_result_t * result)2703 setup_driver_main(
2704 	thread_t                thread,
2705 	int64_t                         slide,
2706 	load_result_t           *result
2707 	)
2708 {
2709 	mach_vm_offset_t addr;
2710 	kern_return_t   ret;
2711 
2712 	/* Driver binaries have no LC_MAIN, use defaults */
2713 
2714 	if (thread == THREAD_NULL) {
2715 		return LOAD_SUCCESS;
2716 	}
2717 
2718 	result->user_stack_alloc_size = MAXSSIZ;
2719 
2720 	/* use default location for stack */
2721 	ret = thread_userstackdefault(&addr, result->is_64bit_addr);
2722 	if (ret != KERN_SUCCESS) {
2723 		return LOAD_FAILURE;
2724 	}
2725 
2726 	/* The stack slides down from the default location */
2727 	result->user_stack = (user_addr_t)addr;
2728 	result->user_stack -= slide;
2729 
2730 	if (result->using_lcmain || result->entry_point != MACH_VM_MIN_ADDRESS) {
2731 		/* Already processed LC_MAIN or LC_UNIXTHREAD */
2732 		return LOAD_FAILURE;
2733 	}
2734 
2735 	result->needs_dynlinker = TRUE;
2736 
2737 	ret = thread_state_initialize( thread );
2738 	if (ret != KERN_SUCCESS) {
2739 		return LOAD_FAILURE;
2740 	}
2741 
2742 	result->unixproc = TRUE;
2743 	result->thread_count++;
2744 
2745 	return LOAD_SUCCESS;
2746 }
2747 
2748 static
2749 load_return_t
load_unixthread(struct thread_command * tcp,thread_t thread,int64_t slide,boolean_t is_x86_64_compat_binary,load_result_t * result)2750 load_unixthread(
2751 	struct thread_command   *tcp,
2752 	thread_t                thread,
2753 	int64_t                         slide,
2754 	boolean_t               is_x86_64_compat_binary,
2755 	load_result_t           *result
2756 	)
2757 {
2758 	load_return_t   ret;
2759 	int customstack = 0;
2760 	mach_vm_offset_t addr;
2761 	if (tcp->cmdsize < sizeof(*tcp)) {
2762 		return LOAD_BADMACHO;
2763 	}
2764 	if (result->thread_count != 0) {
2765 		return LOAD_FAILURE;
2766 	}
2767 
2768 	if (thread == THREAD_NULL) {
2769 		return LOAD_SUCCESS;
2770 	}
2771 
2772 	ret = load_threadstack(thread,
2773 	    (uint32_t *)(((vm_offset_t)tcp) +
2774 	    sizeof(struct thread_command)),
2775 	    tcp->cmdsize - sizeof(struct thread_command),
2776 	    &addr, &customstack, is_x86_64_compat_binary, result);
2777 	if (ret != LOAD_SUCCESS) {
2778 		return ret;
2779 	}
2780 
2781 	/* LC_UNIXTHREAD optionally specifies stack size and location */
2782 
2783 	if (customstack) {
2784 		result->custom_stack = TRUE;
2785 	} else {
2786 		result->user_stack_alloc_size = MAXSSIZ;
2787 	}
2788 
2789 	/* The stack slides down from the default location */
2790 	result->user_stack = (user_addr_t)mach_vm_trunc_page((user_addr_t)addr - slide);
2791 
2792 	{
2793 		ret = load_threadentry(thread,
2794 		    (uint32_t *)(((vm_offset_t)tcp) +
2795 		    sizeof(struct thread_command)),
2796 		    tcp->cmdsize - sizeof(struct thread_command),
2797 		    &addr);
2798 		if (ret != LOAD_SUCCESS) {
2799 			return ret;
2800 		}
2801 
2802 		if (result->using_lcmain || result->entry_point != MACH_VM_MIN_ADDRESS) {
2803 			/* Already processed LC_MAIN or LC_UNIXTHREAD */
2804 			return LOAD_FAILURE;
2805 		}
2806 
2807 		result->entry_point = (user_addr_t)addr;
2808 		result->entry_point += slide;
2809 
2810 		ret = load_threadstate(thread,
2811 		    (uint32_t *)(((vm_offset_t)tcp) + sizeof(struct thread_command)),
2812 		    tcp->cmdsize - sizeof(struct thread_command),
2813 		    result);
2814 		if (ret != LOAD_SUCCESS) {
2815 			return ret;
2816 		}
2817 	}
2818 
2819 	result->unixproc = TRUE;
2820 	result->thread_count++;
2821 
2822 	return LOAD_SUCCESS;
2823 }
2824 
2825 static
2826 load_return_t
load_threadstate(thread_t thread,uint32_t * ts,uint32_t total_size,load_result_t * result)2827 load_threadstate(
2828 	thread_t        thread,
2829 	uint32_t        *ts,
2830 	uint32_t        total_size,
2831 	load_result_t   *result
2832 	)
2833 {
2834 	uint32_t        size;
2835 	int             flavor;
2836 	uint32_t        thread_size;
2837 	uint32_t        *local_ts = NULL;
2838 	uint32_t        local_ts_size = 0;
2839 	int             ret;
2840 
2841 	(void)thread;
2842 
2843 	if (total_size > 0) {
2844 		local_ts_size = total_size;
2845 		local_ts = (uint32_t *)kalloc_data(local_ts_size, Z_WAITOK);
2846 		if (local_ts == NULL) {
2847 			return LOAD_FAILURE;
2848 		}
2849 		memcpy(local_ts, ts, local_ts_size);
2850 		ts = local_ts;
2851 	}
2852 
2853 	/*
2854 	 * Validate the new thread state; iterate through the state flavors in
2855 	 * the Mach-O file.
2856 	 * XXX: we should validate the machine state here, to avoid failing at
2857 	 * activation time where we can't bail out cleanly.
2858 	 */
2859 	while (total_size > 0) {
2860 		if (total_size < 2 * sizeof(uint32_t)) {
2861 			return LOAD_BADMACHO;
2862 		}
2863 
2864 		flavor = *ts++;
2865 		size = *ts++;
2866 
2867 		if (os_add_and_mul_overflow(size, 2, sizeof(uint32_t), &thread_size) ||
2868 		    os_sub_overflow(total_size, thread_size, &total_size)) {
2869 			ret = LOAD_BADMACHO;
2870 			goto bad;
2871 		}
2872 
2873 		ts += size;     /* ts is a (uint32_t *) */
2874 	}
2875 
2876 	result->threadstate = local_ts;
2877 	result->threadstate_sz = local_ts_size;
2878 	return LOAD_SUCCESS;
2879 
2880 bad:
2881 	if (local_ts) {
2882 		kfree_data(local_ts, local_ts_size);
2883 	}
2884 	return ret;
2885 }
2886 
2887 
2888 static
2889 load_return_t
load_threadstack(thread_t thread,uint32_t * ts,uint32_t total_size,mach_vm_offset_t * user_stack,int * customstack,__unused boolean_t is_x86_64_compat_binary,load_result_t * result)2890 load_threadstack(
2891 	thread_t                thread,
2892 	uint32_t                *ts,
2893 	uint32_t                total_size,
2894 	mach_vm_offset_t        *user_stack,
2895 	int                     *customstack,
2896 	__unused boolean_t      is_x86_64_compat_binary,
2897 	load_result_t           *result
2898 	)
2899 {
2900 	kern_return_t   ret;
2901 	uint32_t        size;
2902 	int             flavor;
2903 	uint32_t        stack_size;
2904 
2905 	if (total_size == 0) {
2906 		return LOAD_BADMACHO;
2907 	}
2908 
2909 	while (total_size > 0) {
2910 		if (total_size < 2 * sizeof(uint32_t)) {
2911 			return LOAD_BADMACHO;
2912 		}
2913 
2914 		flavor = *ts++;
2915 		size = *ts++;
2916 		if (UINT32_MAX - 2 < size ||
2917 		    UINT32_MAX / sizeof(uint32_t) < size + 2) {
2918 			return LOAD_BADMACHO;
2919 		}
2920 		stack_size = (size + 2) * sizeof(uint32_t);
2921 		if (stack_size > total_size) {
2922 			return LOAD_BADMACHO;
2923 		}
2924 		total_size -= stack_size;
2925 
2926 		/*
2927 		 * Third argument is a kernel space pointer; it gets cast
2928 		 * to the appropriate type in thread_userstack() based on
2929 		 * the value of flavor.
2930 		 */
2931 		{
2932 			ret = thread_userstack(thread, flavor, (thread_state_t)ts, size, user_stack, customstack, result->is_64bit_data);
2933 			if (ret != KERN_SUCCESS) {
2934 				return LOAD_FAILURE;
2935 			}
2936 		}
2937 
2938 		ts += size;     /* ts is a (uint32_t *) */
2939 	}
2940 	return LOAD_SUCCESS;
2941 }
2942 
2943 static
2944 load_return_t
load_threadentry(thread_t thread,uint32_t * ts,uint32_t total_size,mach_vm_offset_t * entry_point)2945 load_threadentry(
2946 	thread_t        thread,
2947 	uint32_t        *ts,
2948 	uint32_t        total_size,
2949 	mach_vm_offset_t        *entry_point
2950 	)
2951 {
2952 	kern_return_t   ret;
2953 	uint32_t        size;
2954 	int             flavor;
2955 	uint32_t        entry_size;
2956 
2957 	/*
2958 	 *	Set the thread state.
2959 	 */
2960 	*entry_point = MACH_VM_MIN_ADDRESS;
2961 	while (total_size > 0) {
2962 		if (total_size < 2 * sizeof(uint32_t)) {
2963 			return LOAD_BADMACHO;
2964 		}
2965 
2966 		flavor = *ts++;
2967 		size = *ts++;
2968 		if (UINT32_MAX - 2 < size ||
2969 		    UINT32_MAX / sizeof(uint32_t) < size + 2) {
2970 			return LOAD_BADMACHO;
2971 		}
2972 		entry_size = (size + 2) * sizeof(uint32_t);
2973 		if (entry_size > total_size) {
2974 			return LOAD_BADMACHO;
2975 		}
2976 		total_size -= entry_size;
2977 		/*
2978 		 * Third argument is a kernel space pointer; it gets cast
2979 		 * to the appropriate type in thread_entrypoint() based on
2980 		 * the value of flavor.
2981 		 */
2982 		ret = thread_entrypoint(thread, flavor, (thread_state_t)ts, size, entry_point);
2983 		if (ret != KERN_SUCCESS) {
2984 			return LOAD_FAILURE;
2985 		}
2986 		ts += size;     /* ts is a (uint32_t *) */
2987 	}
2988 	return LOAD_SUCCESS;
2989 }
2990 
2991 struct macho_data {
2992 	struct nameidata        __nid;
2993 	union macho_vnode_header {
2994 		struct mach_header      mach_header;
2995 		struct fat_header       fat_header;
2996 		char    __pad[512];
2997 	} __header;
2998 };
2999 
3000 #define DEFAULT_DYLD_PATH "/usr/lib/dyld"
3001 
3002 #if (DEVELOPMENT || DEBUG)
3003 extern char dyld_alt_path[];
3004 extern int use_alt_dyld;
3005 
3006 extern char dyld_suffix[];
3007 extern int use_dyld_suffix;
3008 
3009 typedef struct _dyld_suffix_map_entry {
3010 	const char *suffix;
3011 	const char *path;
3012 } dyld_suffix_map_entry_t;
3013 
3014 static const dyld_suffix_map_entry_t _dyld_suffix_map[] = {
3015 	[0] = {
3016 		.suffix = "",
3017 		.path = DEFAULT_DYLD_PATH,
3018 	}, {
3019 		.suffix = "release",
3020 		.path = DEFAULT_DYLD_PATH,
3021 	}, {
3022 		.suffix = "bringup",
3023 		.path = "/usr/appleinternal/lib/dyld.bringup",
3024 	},
3025 };
3026 #endif
3027 
3028 static load_return_t
load_dylinker(struct dylinker_command * lcp,cpu_type_t cputype,vm_map_t map,thread_t thread,int depth,int64_t slide,load_result_t * result,struct image_params * imgp)3029 load_dylinker(
3030 	struct dylinker_command *lcp,
3031 	cpu_type_t              cputype,
3032 	vm_map_t                map,
3033 	thread_t        thread,
3034 	int                     depth,
3035 	int64_t                 slide,
3036 	load_result_t           *result,
3037 	struct image_params     *imgp
3038 	)
3039 {
3040 	const char              *name;
3041 	struct vnode            *vp = NULLVP;   /* set by get_macho_vnode() */
3042 	struct mach_header      *header;
3043 	off_t                   file_offset = 0; /* set by get_macho_vnode() */
3044 	off_t                   macho_size = 0; /* set by get_macho_vnode() */
3045 	load_result_t           *myresult;
3046 	kern_return_t           ret;
3047 	struct macho_data       *macho_data;
3048 	struct {
3049 		struct mach_header      __header;
3050 		load_result_t           __myresult;
3051 		struct macho_data       __macho_data;
3052 	} *dyld_data;
3053 
3054 	if (lcp->cmdsize < sizeof(*lcp) || lcp->name.offset >= lcp->cmdsize) {
3055 		return LOAD_BADMACHO;
3056 	}
3057 
3058 	name = (const char *)lcp + lcp->name.offset;
3059 
3060 	/* Check for a proper null terminated string. */
3061 	size_t maxsz = lcp->cmdsize - lcp->name.offset;
3062 	size_t namelen = strnlen(name, maxsz);
3063 	if (namelen >= maxsz) {
3064 		return LOAD_BADMACHO;
3065 	}
3066 
3067 #if (DEVELOPMENT || DEBUG)
3068 
3069 	/*
3070 	 * rdar://23680808
3071 	 * If an alternate dyld has been specified via boot args, check
3072 	 * to see if PROC_UUID_ALT_DYLD_POLICY has been set on this
3073 	 * executable and redirect the kernel to load that linker.
3074 	 */
3075 
3076 	if (use_alt_dyld) {
3077 		int policy_error;
3078 		uint32_t policy_flags = 0;
3079 		int32_t policy_gencount = 0;
3080 
3081 		policy_error = proc_uuid_policy_lookup(result->uuid, &policy_flags, &policy_gencount);
3082 		if (policy_error == 0) {
3083 			if (policy_flags & PROC_UUID_ALT_DYLD_POLICY) {
3084 				name = dyld_alt_path;
3085 			}
3086 		}
3087 	} else if (use_dyld_suffix) {
3088 		size_t i = 0;
3089 
3090 #define countof(x) (sizeof(x) / sizeof(x[0]))
3091 		for (i = 0; i < countof(_dyld_suffix_map); i++) {
3092 			const dyld_suffix_map_entry_t *entry = &_dyld_suffix_map[i];
3093 
3094 			if (strcmp(entry->suffix, dyld_suffix) == 0) {
3095 				name = entry->path;
3096 				break;
3097 			}
3098 		}
3099 	}
3100 #endif
3101 
3102 #if !(DEVELOPMENT || DEBUG)
3103 	if (0 != strcmp(name, DEFAULT_DYLD_PATH)) {
3104 		return LOAD_BADMACHO;
3105 	}
3106 #endif
3107 
3108 	/* Allocate wad-of-data from heap to reduce excessively deep stacks */
3109 
3110 	dyld_data = kalloc_type(typeof(*dyld_data), Z_WAITOK);
3111 	header = &dyld_data->__header;
3112 	myresult = &dyld_data->__myresult;
3113 	macho_data = &dyld_data->__macho_data;
3114 
3115 	{
3116 		cputype = (cputype & CPU_ARCH_MASK) | (cpu_type() & ~CPU_ARCH_MASK);
3117 	}
3118 
3119 	ret = get_macho_vnode(name, cputype, header,
3120 	    &file_offset, &macho_size, macho_data, &vp, imgp);
3121 	if (ret) {
3122 		goto novp_out;
3123 	}
3124 
3125 	*myresult = load_result_null;
3126 	myresult->is_64bit_addr = result->is_64bit_addr;
3127 	myresult->is_64bit_data = result->is_64bit_data;
3128 
3129 	ret = parse_machfile(vp, map, thread, header, file_offset,
3130 	    macho_size, depth, slide, 0, myresult, result, imgp);
3131 
3132 	if (ret == LOAD_SUCCESS) {
3133 		if (result->threadstate) {
3134 			/* don't use the app's threadstate if we have a dyld */
3135 			kfree_data(result->threadstate, result->threadstate_sz);
3136 		}
3137 		result->threadstate = myresult->threadstate;
3138 		result->threadstate_sz = myresult->threadstate_sz;
3139 
3140 		result->dynlinker = TRUE;
3141 		result->entry_point = myresult->entry_point;
3142 		result->validentry = myresult->validentry;
3143 		result->all_image_info_addr = myresult->all_image_info_addr;
3144 		result->all_image_info_size = myresult->all_image_info_size;
3145 		if (!myresult->platform_binary) {
3146 			result->csflags &= ~CS_NO_UNTRUSTED_HELPERS;
3147 		}
3148 
3149 #if CONFIG_ROSETTA
3150 		if (imgp->ip_flags & IMGPF_ROSETTA) {
3151 			extern const struct fileops vnops;
3152 			// Save the file descriptor and mach header address for dyld. These will
3153 			// be passed on the stack for the Rosetta runtime's use.
3154 			struct fileproc *fp;
3155 			int dyld_fd;
3156 			proc_t p = vfs_context_proc(imgp->ip_vfs_context);
3157 			int error = falloc(p, &fp, &dyld_fd, imgp->ip_vfs_context);
3158 			if (error == 0) {
3159 				error = VNOP_OPEN(vp, FREAD, imgp->ip_vfs_context);
3160 				if (error == 0) {
3161 					fp->fp_glob->fg_flag = FREAD;
3162 					fp->fp_glob->fg_ops = &vnops;
3163 					fp_set_data(fp, vp);
3164 
3165 					proc_fdlock(p);
3166 					procfdtbl_releasefd(p, dyld_fd, NULL);
3167 					fp_drop(p, dyld_fd, fp, 1);
3168 					proc_fdunlock(p);
3169 
3170 					vnode_ref(vp);
3171 
3172 					result->dynlinker_fd = dyld_fd;
3173 					result->dynlinker_fp = fp;
3174 					result->dynlinker_mach_header = myresult->mach_header;
3175 					result->dynlinker_max_vm_addr = myresult->max_vm_addr;
3176 				} else {
3177 					fp_free(p, dyld_fd, fp);
3178 					ret = LOAD_IOERROR;
3179 				}
3180 			} else {
3181 				ret = LOAD_IOERROR;
3182 			}
3183 		}
3184 #endif
3185 	}
3186 
3187 	struct vnode_attr *va;
3188 	va = kalloc_type(struct vnode_attr, Z_WAITOK | Z_ZERO);
3189 	VATTR_INIT(va);
3190 	VATTR_WANTED(va, va_fsid64);
3191 	VATTR_WANTED(va, va_fsid);
3192 	VATTR_WANTED(va, va_fileid);
3193 	int error = vnode_getattr(vp, va, imgp->ip_vfs_context);
3194 	if (error == 0) {
3195 		imgp->ip_dyld_fsid = vnode_get_va_fsid(va);
3196 		imgp->ip_dyld_fsobjid = va->va_fileid;
3197 	}
3198 
3199 	vnode_put(vp);
3200 	kfree_type(struct vnode_attr, va);
3201 novp_out:
3202 	kfree_type(typeof(*dyld_data), dyld_data);
3203 	return ret;
3204 }
3205 
3206 #if CONFIG_ROSETTA
3207 #if defined(APPLEVORTEX)
3208 static const char* rosetta_runtime_path = "/usr/libexec/rosetta/runtime_t8027";
3209 #else
3210 static const char* rosetta_runtime_path = "/usr/libexec/rosetta/runtime";
3211 #endif
3212 
3213 #if (DEVELOPMENT || DEBUG)
3214 static const char* rosetta_runtime_path_alt_x86 = "/usr/local/libexec/rosetta/runtime_internal";
3215 static const char* rosetta_runtime_path_alt_arm = "/usr/local/libexec/rosetta/runtime_arm_internal";
3216 #endif
3217 
3218 static load_return_t
load_rosetta(vm_map_t map,thread_t thread,load_result_t * result,struct image_params * imgp)3219 load_rosetta(
3220 	vm_map_t                        map,
3221 	thread_t                        thread,
3222 	load_result_t           *result,
3223 	struct image_params     *imgp)
3224 {
3225 	struct vnode            *vp = NULLVP;   /* set by get_macho_vnode() */
3226 	struct mach_header      *header;
3227 	off_t                   file_offset = 0; /* set by get_macho_vnode() */
3228 	off_t                   macho_size = 0; /* set by get_macho_vnode() */
3229 	load_result_t           *myresult;
3230 	kern_return_t           ret;
3231 	struct macho_data       *macho_data;
3232 	const char              *rosetta_file_path;
3233 	struct {
3234 		struct mach_header      __header;
3235 		load_result_t           __myresult;
3236 		struct macho_data       __macho_data;
3237 	} *rosetta_data;
3238 	mach_vm_address_t rosetta_load_addr;
3239 	mach_vm_size_t    rosetta_size;
3240 	mach_vm_address_t shared_cache_base = SHARED_REGION_BASE_ARM64;
3241 	int64_t           slide = 0;
3242 
3243 	/* Allocate wad-of-data from heap to reduce excessively deep stacks */
3244 	rosetta_data = kalloc_type(typeof(*rosetta_data), Z_WAITOK | Z_NOFAIL);
3245 	header = &rosetta_data->__header;
3246 	myresult = &rosetta_data->__myresult;
3247 	macho_data = &rosetta_data->__macho_data;
3248 
3249 	rosetta_file_path = rosetta_runtime_path;
3250 
3251 #if (DEVELOPMENT || DEBUG)
3252 	bool use_alt_rosetta = false;
3253 	if (imgp->ip_flags & IMGPF_ALT_ROSETTA) {
3254 		use_alt_rosetta = true;
3255 	} else {
3256 		int policy_error;
3257 		uint32_t policy_flags = 0;
3258 		int32_t policy_gencount = 0;
3259 		policy_error = proc_uuid_policy_lookup(result->uuid, &policy_flags, &policy_gencount);
3260 		if (policy_error == 0 && (policy_flags & PROC_UUID_ALT_ROSETTA_POLICY) != 0) {
3261 			use_alt_rosetta = true;
3262 		}
3263 	}
3264 
3265 	if (use_alt_rosetta) {
3266 		if (imgp->ip_origcputype == CPU_TYPE_X86_64) {
3267 			rosetta_file_path = rosetta_runtime_path_alt_x86;
3268 		} else if (imgp->ip_origcputype == CPU_TYPE_ARM64) {
3269 			rosetta_file_path = rosetta_runtime_path_alt_arm;
3270 		} else {
3271 			ret = LOAD_BADARCH;
3272 			goto novp_out;
3273 		}
3274 	}
3275 #endif
3276 
3277 	ret = get_macho_vnode(rosetta_file_path, CPU_TYPE_ARM64, header,
3278 	    &file_offset, &macho_size, macho_data, &vp, imgp);
3279 	if (ret) {
3280 		goto novp_out;
3281 	}
3282 
3283 	*myresult = load_result_null;
3284 	myresult->is_64bit_addr = TRUE;
3285 	myresult->is_64bit_data = TRUE;
3286 
3287 	ret = parse_machfile(vp, NULL, NULL, header, file_offset, macho_size,
3288 	    2, 0, 0, myresult, NULL, imgp);
3289 	if (ret != LOAD_SUCCESS) {
3290 		goto out;
3291 	}
3292 
3293 	if (!(imgp->ip_flags & IMGPF_DISABLE_ASLR)) {
3294 		slide = random();
3295 		slide = (slide % (vm_map_get_max_loader_aslr_slide_pages(map) - 1)) + 1;
3296 		slide <<= vm_map_page_shift(map);
3297 	}
3298 
3299 	if (imgp->ip_origcputype == CPU_TYPE_X86_64) {
3300 		shared_cache_base = SHARED_REGION_BASE_X86_64;
3301 	}
3302 
3303 	rosetta_size = round_page(myresult->max_vm_addr - myresult->min_vm_addr);
3304 	rosetta_load_addr = shared_cache_base - rosetta_size - slide;
3305 
3306 	*myresult = load_result_null;
3307 	myresult->is_64bit_addr = TRUE;
3308 	myresult->is_64bit_data = TRUE;
3309 	myresult->is_rosetta = TRUE;
3310 
3311 	ret = parse_machfile(vp, map, thread, header, file_offset, macho_size,
3312 	    2, rosetta_load_addr, 0, myresult, result, imgp);
3313 	if (ret == LOAD_SUCCESS) {
3314 		if (result) {
3315 			if (result->threadstate) {
3316 				/* don't use the app's/dyld's threadstate */
3317 				kfree_data(result->threadstate, result->threadstate_sz);
3318 			}
3319 			assert(myresult->threadstate != NULL);
3320 
3321 			result->is_rosetta = TRUE;
3322 
3323 			result->threadstate = myresult->threadstate;
3324 			result->threadstate_sz = myresult->threadstate_sz;
3325 
3326 			result->entry_point = myresult->entry_point;
3327 			result->validentry = myresult->validentry;
3328 			if (!myresult->platform_binary) {
3329 				result->csflags &= ~CS_NO_UNTRUSTED_HELPERS;
3330 			}
3331 
3332 			if ((header->cpusubtype & ~CPU_SUBTYPE_MASK) != CPU_SUBTYPE_ARM64E) {
3333 				imgp->ip_flags |= IMGPF_NOJOP;
3334 			}
3335 		}
3336 	}
3337 
3338 out:
3339 	vnode_put(vp);
3340 novp_out:
3341 	kfree_type(typeof(*rosetta_data), rosetta_data);
3342 	return ret;
3343 }
3344 #endif
3345 
3346 static void
set_signature_error(struct vnode * vp,struct image_params * imgp,const char * fatal_failure_desc,const size_t fatal_failure_desc_len)3347 set_signature_error(
3348 	struct vnode* vp,
3349 	struct image_params * imgp,
3350 	const char* fatal_failure_desc,
3351 	const size_t fatal_failure_desc_len)
3352 {
3353 	char *vn_path = NULL;
3354 	vm_size_t vn_pathlen = MAXPATHLEN;
3355 	char const *path = NULL;
3356 
3357 	vn_path = zalloc(ZV_NAMEI);
3358 	if (vn_getpath(vp, vn_path, (int*)&vn_pathlen) == 0) {
3359 		path = vn_path;
3360 	} else {
3361 		path = "(get vnode path failed)";
3362 	}
3363 	os_reason_t reason = os_reason_create(OS_REASON_CODESIGNING,
3364 	    CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG);
3365 
3366 	if (reason == OS_REASON_NULL) {
3367 		printf("load_code_signature: %s: failure to allocate exit reason for validation failure: %s\n",
3368 		    path, fatal_failure_desc);
3369 		goto out;
3370 	}
3371 
3372 	imgp->ip_cs_error = reason;
3373 	reason->osr_flags = (OS_REASON_FLAG_GENERATE_CRASH_REPORT |
3374 	    OS_REASON_FLAG_CONSISTENT_FAILURE);
3375 
3376 	mach_vm_address_t data_addr = 0;
3377 
3378 	int reason_error = 0;
3379 	int kcdata_error = 0;
3380 
3381 	if ((reason_error = os_reason_alloc_buffer_noblock(reason, kcdata_estimate_required_buffer_size
3382 	    (1, (uint32_t)fatal_failure_desc_len))) == 0 &&
3383 	    (kcdata_error = kcdata_get_memory_addr(&reason->osr_kcd_descriptor,
3384 	    EXIT_REASON_USER_DESC, (uint32_t)fatal_failure_desc_len,
3385 	    &data_addr)) == KERN_SUCCESS) {
3386 		kern_return_t mc_error = kcdata_memcpy(&reason->osr_kcd_descriptor, (mach_vm_address_t)data_addr,
3387 		    fatal_failure_desc, (uint32_t)fatal_failure_desc_len);
3388 
3389 		if (mc_error != KERN_SUCCESS) {
3390 			printf("load_code_signature: %s: failed to copy reason string "
3391 			    "(kcdata_memcpy error: %d, length: %ld)\n",
3392 			    path, mc_error, fatal_failure_desc_len);
3393 		}
3394 	} else {
3395 		printf("load_code_signature: %s: failed to allocate space for reason string "
3396 		    "(os_reason_alloc_buffer error: %d, kcdata error: %d, length: %ld)\n",
3397 		    path, reason_error, kcdata_error, fatal_failure_desc_len);
3398 	}
3399 out:
3400 	if (vn_path) {
3401 		zfree(ZV_NAMEI, vn_path);
3402 	}
3403 }
3404 
3405 static load_return_t
load_code_signature(struct linkedit_data_command * lcp,struct vnode * vp,off_t macho_offset,off_t macho_size,cpu_type_t cputype,cpu_subtype_t cpusubtype,load_result_t * result,struct image_params * imgp)3406 load_code_signature(
3407 	struct linkedit_data_command    *lcp,
3408 	struct vnode                    *vp,
3409 	off_t                           macho_offset,
3410 	off_t                           macho_size,
3411 	cpu_type_t                      cputype,
3412 	cpu_subtype_t                   cpusubtype,
3413 	load_result_t                   *result,
3414 	struct image_params             *imgp)
3415 {
3416 	int             ret;
3417 	kern_return_t   kr;
3418 	vm_offset_t     addr;
3419 	int             resid;
3420 	struct cs_blob  *blob;
3421 	int             error;
3422 	vm_size_t       blob_size;
3423 	uint32_t        sum;
3424 	boolean_t               anyCPU;
3425 
3426 	addr = 0;
3427 	blob = NULL;
3428 
3429 	cpusubtype &= ~CPU_SUBTYPE_MASK;
3430 
3431 	blob = ubc_cs_blob_get(vp, cputype, cpusubtype, macho_offset);
3432 
3433 	if (blob != NULL) {
3434 		/* we already have a blob for this vnode and cpu(sub)type */
3435 		anyCPU = blob->csb_cpu_type == -1;
3436 		if ((blob->csb_cpu_type != cputype &&
3437 		    blob->csb_cpu_subtype != cpusubtype && !anyCPU) ||
3438 		    (blob->csb_base_offset != macho_offset) ||
3439 		    ((blob->csb_flags & CS_VALID) == 0)) {
3440 			/* the blob has changed for this vnode: fail ! */
3441 			ret = LOAD_BADMACHO;
3442 			const char* fatal_failure_desc = "embedded signature doesn't match attached signature";
3443 			const size_t fatal_failure_desc_len = strlen(fatal_failure_desc) + 1;
3444 
3445 			printf("load_code_signature: %s\n", fatal_failure_desc);
3446 			set_signature_error(vp, imgp, fatal_failure_desc, fatal_failure_desc_len);
3447 			goto out;
3448 		}
3449 
3450 		/* It matches the blob we want here, let's verify the version */
3451 		if (!anyCPU && ubc_cs_generation_check(vp) == 0) {
3452 			/* No need to revalidate, we're good! */
3453 			ret = LOAD_SUCCESS;
3454 			goto out;
3455 		}
3456 
3457 		/* That blob may be stale, let's revalidate. */
3458 		error = ubc_cs_blob_revalidate(vp, blob, imgp, 0, result->ip_platform);
3459 		if (error == 0) {
3460 			/* Revalidation succeeded, we're good! */
3461 			/* If we were revaliding a CS blob with any CPU arch we adjust it */
3462 			if (anyCPU) {
3463 				vnode_lock_spin(vp);
3464 				struct cs_cpu_info cpu_info = {
3465 					.csb_cpu_type = cputype,
3466 					.csb_cpu_subtype = cpusubtype
3467 				};
3468 				zalloc_ro_update_field(ZONE_ID_CS_BLOB, blob, csb_cpu_info, &cpu_info);
3469 				vnode_unlock(vp);
3470 			}
3471 			ret = LOAD_SUCCESS;
3472 			goto out;
3473 		}
3474 
3475 		if (error != EAGAIN) {
3476 			printf("load_code_signature: revalidation failed: %d\n", error);
3477 			ret = LOAD_FAILURE;
3478 			goto out;
3479 		}
3480 
3481 		assert(error == EAGAIN);
3482 
3483 		/*
3484 		 * Revalidation was not possible for this blob. We just continue as if there was no blob,
3485 		 * rereading the signature, and ubc_cs_blob_add will do the right thing.
3486 		 */
3487 		blob = NULL;
3488 	}
3489 
3490 	if (lcp->cmdsize != sizeof(struct linkedit_data_command)) {
3491 		ret = LOAD_BADMACHO;
3492 		goto out;
3493 	}
3494 
3495 	sum = 0;
3496 	if (os_add_overflow(lcp->dataoff, lcp->datasize, &sum) || sum > macho_size) {
3497 		ret = LOAD_BADMACHO;
3498 		goto out;
3499 	}
3500 
3501 	blob_size = lcp->datasize;
3502 	kr = ubc_cs_blob_allocate(&addr, &blob_size);
3503 	if (kr != KERN_SUCCESS) {
3504 		ret = LOAD_NOSPACE;
3505 		goto out;
3506 	}
3507 
3508 	resid = 0;
3509 	error = vn_rdwr(UIO_READ,
3510 	    vp,
3511 	    (caddr_t) addr,
3512 	    lcp->datasize,
3513 	    macho_offset + lcp->dataoff,
3514 	    UIO_SYSSPACE,
3515 	    0,
3516 	    kauth_cred_get(),
3517 	    &resid,
3518 	    current_proc());
3519 	if (error || resid != 0) {
3520 		ret = LOAD_IOERROR;
3521 		goto out;
3522 	}
3523 
3524 	if (ubc_cs_blob_add(vp,
3525 	    result->ip_platform,
3526 	    cputype,
3527 	    cpusubtype,
3528 	    macho_offset,
3529 	    &addr,
3530 	    lcp->datasize,
3531 	    imgp,
3532 	    0,
3533 	    &blob)) {
3534 		if (addr) {
3535 			ubc_cs_blob_deallocate(addr, blob_size);
3536 			addr = 0;
3537 		}
3538 		ret = LOAD_FAILURE;
3539 		goto out;
3540 	} else {
3541 		/* ubc_cs_blob_add() has consumed "addr" */
3542 		addr = 0;
3543 	}
3544 
3545 #if CHECK_CS_VALIDATION_BITMAP
3546 	ubc_cs_validation_bitmap_allocate( vp );
3547 #endif
3548 
3549 	ret = LOAD_SUCCESS;
3550 out:
3551 	if (ret == LOAD_SUCCESS) {
3552 		if (blob == NULL) {
3553 			panic("success, but no blob!");
3554 		}
3555 
3556 		result->csflags |= blob->csb_flags;
3557 		result->platform_binary = blob->csb_platform_binary;
3558 		result->cs_end_offset = blob->csb_end_offset;
3559 	}
3560 	if (addr != 0) {
3561 		ubc_cs_blob_deallocate(addr, blob_size);
3562 		addr = 0;
3563 	}
3564 
3565 	return ret;
3566 }
3567 
3568 
3569 #if CONFIG_CODE_DECRYPTION
3570 
3571 static load_return_t
set_code_unprotect(struct encryption_info_command * eip,caddr_t addr,vm_map_t map,int64_t slide,struct vnode * vp,off_t macho_offset,cpu_type_t cputype,cpu_subtype_t cpusubtype)3572 set_code_unprotect(
3573 	struct encryption_info_command *eip,
3574 	caddr_t addr,
3575 	vm_map_t map,
3576 	int64_t slide,
3577 	struct vnode *vp,
3578 	off_t macho_offset,
3579 	cpu_type_t cputype,
3580 	cpu_subtype_t cpusubtype)
3581 {
3582 	int error, len;
3583 	pager_crypt_info_t crypt_info;
3584 	const char * cryptname = 0;
3585 	char *vpath;
3586 
3587 	size_t offset;
3588 	struct segment_command_64 *seg64;
3589 	struct segment_command *seg32;
3590 	vm_map_offset_t map_offset, map_size;
3591 	vm_object_offset_t crypto_backing_offset;
3592 	kern_return_t kr;
3593 
3594 	if (eip->cmdsize < sizeof(*eip)) {
3595 		return LOAD_BADMACHO;
3596 	}
3597 
3598 	switch (eip->cryptid) {
3599 	case 0:
3600 		/* not encrypted, just an empty load command */
3601 		return LOAD_SUCCESS;
3602 	case 1:
3603 		cryptname = "com.apple.unfree";
3604 		break;
3605 	case 0x10:
3606 		/* some random cryptid that you could manually put into
3607 		 * your binary if you want NULL */
3608 		cryptname = "com.apple.null";
3609 		break;
3610 	default:
3611 		return LOAD_BADMACHO;
3612 	}
3613 
3614 	if (map == VM_MAP_NULL) {
3615 		return LOAD_SUCCESS;
3616 	}
3617 	if (NULL == text_crypter_create) {
3618 		return LOAD_FAILURE;
3619 	}
3620 
3621 	vpath = zalloc(ZV_NAMEI);
3622 
3623 	len = MAXPATHLEN;
3624 	error = vn_getpath(vp, vpath, &len);
3625 	if (error) {
3626 		zfree(ZV_NAMEI, vpath);
3627 		return LOAD_FAILURE;
3628 	}
3629 
3630 	if (eip->cryptsize == 0) {
3631 		printf("%s:%d '%s': cryptoff 0x%llx cryptsize 0x%llx cryptid 0x%x ignored\n", __FUNCTION__, __LINE__, vpath, (uint64_t)eip->cryptoff, (uint64_t)eip->cryptsize, eip->cryptid);
3632 		zfree(ZV_NAMEI, vpath);
3633 		return LOAD_SUCCESS;
3634 	}
3635 
3636 	/* set up decrypter first */
3637 	crypt_file_data_t crypt_data = {
3638 		.filename = vpath,
3639 		.cputype = cputype,
3640 		.cpusubtype = cpusubtype
3641 	};
3642 	kr = text_crypter_create(&crypt_info, cryptname, (void*)&crypt_data);
3643 #if VM_MAP_DEBUG_APPLE_PROTECT
3644 	if (vm_map_debug_apple_protect) {
3645 		struct proc *p;
3646 		p  = current_proc();
3647 		printf("APPLE_PROTECT: %d[%s] map %p %s(%s) -> 0x%x\n",
3648 		    proc_getpid(p), p->p_comm, map, __FUNCTION__, vpath, kr);
3649 	}
3650 #endif /* VM_MAP_DEBUG_APPLE_PROTECT */
3651 	zfree(ZV_NAMEI, vpath);
3652 
3653 	if (kr) {
3654 		printf("set_code_unprotect: unable to create decrypter %s, kr=%d\n",
3655 		    cryptname, kr);
3656 		if (kr == kIOReturnNotPrivileged) {
3657 			/* text encryption returned decryption failure */
3658 			return LOAD_DECRYPTFAIL;
3659 		} else {
3660 			return LOAD_RESOURCE;
3661 		}
3662 	}
3663 
3664 	/* this is terrible, but we have to rescan the load commands to find the
3665 	 * virtual address of this encrypted stuff. This code is gonna look like
3666 	 * the dyld source one day... */
3667 	struct mach_header *header = (struct mach_header *)addr;
3668 	size_t mach_header_sz = sizeof(struct mach_header);
3669 	if (header->magic == MH_MAGIC_64 ||
3670 	    header->magic == MH_CIGAM_64) {
3671 		mach_header_sz = sizeof(struct mach_header_64);
3672 	}
3673 	offset = mach_header_sz;
3674 	uint32_t ncmds = header->ncmds;
3675 	while (ncmds--) {
3676 		/*
3677 		 *	Get a pointer to the command.
3678 		 */
3679 		struct load_command *lcp = (struct load_command *)(addr + offset);
3680 		offset += lcp->cmdsize;
3681 
3682 		switch (lcp->cmd) {
3683 		case LC_SEGMENT_64:
3684 			seg64 = (struct segment_command_64 *)lcp;
3685 			if ((seg64->fileoff <= eip->cryptoff) &&
3686 			    (seg64->fileoff + seg64->filesize >=
3687 			    eip->cryptoff + eip->cryptsize)) {
3688 				map_offset = (vm_map_offset_t)(seg64->vmaddr + eip->cryptoff - seg64->fileoff + slide);
3689 				map_size = eip->cryptsize;
3690 				crypto_backing_offset = macho_offset + eip->cryptoff;
3691 				goto remap_now;
3692 			}
3693 			break;
3694 		case LC_SEGMENT:
3695 			seg32 = (struct segment_command *)lcp;
3696 			if ((seg32->fileoff <= eip->cryptoff) &&
3697 			    (seg32->fileoff + seg32->filesize >=
3698 			    eip->cryptoff + eip->cryptsize)) {
3699 				map_offset = (vm_map_offset_t)(seg32->vmaddr + eip->cryptoff - seg32->fileoff + slide);
3700 				map_size = eip->cryptsize;
3701 				crypto_backing_offset = macho_offset + eip->cryptoff;
3702 				goto remap_now;
3703 			}
3704 			break;
3705 		}
3706 	}
3707 
3708 	/* if we get here, did not find anything */
3709 	return LOAD_BADMACHO;
3710 
3711 remap_now:
3712 	/* now remap using the decrypter */
3713 	MACHO_PRINTF(("+++ set_code_unprotect: vm[0x%llx:0x%llx]\n",
3714 	    (uint64_t) map_offset,
3715 	    (uint64_t) (map_offset + map_size)));
3716 	kr = vm_map_apple_protected(map,
3717 	    map_offset,
3718 	    map_offset + map_size,
3719 	    crypto_backing_offset,
3720 	    &crypt_info,
3721 	    CRYPTID_APP_ENCRYPTION);
3722 	if (kr) {
3723 		printf("set_code_unprotect(): mapping failed with %x\n", kr);
3724 		return LOAD_PROTECT;
3725 	}
3726 
3727 	return LOAD_SUCCESS;
3728 }
3729 
3730 #endif
3731 
3732 /*
3733  * This routine exists to support the load_dylinker().
3734  *
3735  * This routine has its own, separate, understanding of the FAT file format,
3736  * which is terrifically unfortunate.
3737  */
3738 static
3739 load_return_t
get_macho_vnode(const char * path,cpu_type_t cputype,struct mach_header * mach_header,off_t * file_offset,off_t * macho_size,struct macho_data * data,struct vnode ** vpp,struct image_params * imgp)3740 get_macho_vnode(
3741 	const char              *path,
3742 	cpu_type_t              cputype,
3743 	struct mach_header      *mach_header,
3744 	off_t                   *file_offset,
3745 	off_t                   *macho_size,
3746 	struct macho_data       *data,
3747 	struct vnode            **vpp,
3748 	struct image_params     *imgp
3749 	)
3750 {
3751 	struct vnode            *vp;
3752 	vfs_context_t           ctx = vfs_context_current();
3753 	proc_t                  p = vfs_context_proc(ctx);
3754 	kauth_cred_t            kerncred;
3755 	struct nameidata        *ndp = &data->__nid;
3756 	boolean_t               is_fat;
3757 	struct fat_arch         fat_arch;
3758 	int                     error;
3759 	int resid;
3760 	union macho_vnode_header *header = &data->__header;
3761 	off_t fsize = (off_t)0;
3762 
3763 	/*
3764 	 * Capture the kernel credential for use in the actual read of the
3765 	 * file, since the user doing the execution may have execute rights
3766 	 * but not read rights, but to exec something, we have to either map
3767 	 * or read it into the new process address space, which requires
3768 	 * read rights.  This is to deal with lack of common credential
3769 	 * serialization code which would treat NOCRED as "serialize 'root'".
3770 	 */
3771 	kerncred = vfs_context_ucred(vfs_context_kernel());
3772 
3773 	/* init the namei data to point the file user's program name */
3774 	NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW | LOCKLEAF, UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
3775 
3776 	if ((error = namei(ndp)) != 0) {
3777 		if (error == ENOENT) {
3778 			error = LOAD_ENOENT;
3779 		} else {
3780 			error = LOAD_FAILURE;
3781 		}
3782 		return error;
3783 	}
3784 	nameidone(ndp);
3785 	vp = ndp->ni_vp;
3786 
3787 	/* check for regular file */
3788 	if (vp->v_type != VREG) {
3789 		error = LOAD_PROTECT;
3790 		goto bad1;
3791 	}
3792 
3793 	/* get size */
3794 	if ((error = vnode_size(vp, &fsize, ctx)) != 0) {
3795 		error = LOAD_FAILURE;
3796 		goto bad1;
3797 	}
3798 
3799 	/* Check mount point */
3800 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
3801 		error = LOAD_PROTECT;
3802 		goto bad1;
3803 	}
3804 
3805 	/* check access */
3806 	if ((error = vnode_authorize(vp, NULL, KAUTH_VNODE_EXECUTE | KAUTH_VNODE_READ_DATA, ctx)) != 0) {
3807 		error = LOAD_PROTECT;
3808 		goto bad1;
3809 	}
3810 
3811 	/* try to open it */
3812 	if ((error = VNOP_OPEN(vp, FREAD, ctx)) != 0) {
3813 		error = LOAD_PROTECT;
3814 		goto bad1;
3815 	}
3816 
3817 	if ((error = vn_rdwr(UIO_READ, vp, (caddr_t)header, sizeof(*header), 0,
3818 	    UIO_SYSSPACE, IO_NODELOCKED, kerncred, &resid, p)) != 0) {
3819 		error = LOAD_IOERROR;
3820 		goto bad2;
3821 	}
3822 
3823 	if (resid) {
3824 		error = LOAD_BADMACHO;
3825 		goto bad2;
3826 	}
3827 
3828 	if (header->mach_header.magic == MH_MAGIC ||
3829 	    header->mach_header.magic == MH_MAGIC_64) {
3830 		is_fat = FALSE;
3831 	} else if (OSSwapBigToHostInt32(header->fat_header.magic) == FAT_MAGIC) {
3832 		is_fat = TRUE;
3833 	} else {
3834 		error = LOAD_BADMACHO;
3835 		goto bad2;
3836 	}
3837 
3838 	if (is_fat) {
3839 		error = fatfile_validate_fatarches((vm_offset_t)(&header->fat_header),
3840 		    sizeof(*header), fsize);
3841 		if (error != LOAD_SUCCESS) {
3842 			goto bad2;
3843 		}
3844 
3845 		/* Look up our architecture in the fat file. */
3846 		error = fatfile_getbestarch_for_cputype(cputype, CPU_SUBTYPE_ANY,
3847 		    (vm_offset_t)(&header->fat_header), sizeof(*header), imgp, &fat_arch);
3848 		if (error != LOAD_SUCCESS) {
3849 			goto bad2;
3850 		}
3851 
3852 		/* Read the Mach-O header out of it */
3853 		error = vn_rdwr(UIO_READ, vp, (caddr_t)&header->mach_header,
3854 		    sizeof(header->mach_header), fat_arch.offset,
3855 		    UIO_SYSSPACE, IO_NODELOCKED, kerncred, &resid, p);
3856 		if (error) {
3857 			error = LOAD_IOERROR;
3858 			goto bad2;
3859 		}
3860 
3861 		if (resid) {
3862 			error = LOAD_BADMACHO;
3863 			goto bad2;
3864 		}
3865 
3866 		/* Is this really a Mach-O? */
3867 		if (header->mach_header.magic != MH_MAGIC &&
3868 		    header->mach_header.magic != MH_MAGIC_64) {
3869 			error = LOAD_BADMACHO;
3870 			goto bad2;
3871 		}
3872 
3873 		*file_offset = fat_arch.offset;
3874 		*macho_size = fat_arch.size;
3875 	} else {
3876 		/*
3877 		 * Force get_macho_vnode() to fail if the architecture bits
3878 		 * do not match the expected architecture bits.  This in
3879 		 * turn causes load_dylinker() to fail for the same reason,
3880 		 * so it ensures the dynamic linker and the binary are in
3881 		 * lock-step.  This is potentially bad, if we ever add to
3882 		 * the CPU_ARCH_* bits any bits that are desirable but not
3883 		 * required, since the dynamic linker might work, but we will
3884 		 * refuse to load it because of this check.
3885 		 */
3886 		if ((cpu_type_t)header->mach_header.cputype != cputype) {
3887 			error = LOAD_BADARCH;
3888 			goto bad2;
3889 		}
3890 
3891 		*file_offset = 0;
3892 		*macho_size = fsize;
3893 	}
3894 
3895 	*mach_header = header->mach_header;
3896 	*vpp = vp;
3897 
3898 	ubc_setsize(vp, fsize);
3899 	return error;
3900 
3901 bad2:
3902 	(void) VNOP_CLOSE(vp, FREAD, ctx);
3903 bad1:
3904 	vnode_put(vp);
3905 	return error;
3906 }
3907