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