]> git.saurik.com Git - apple/xnu.git/blame - bsd/kern/mach_loader.c
xnu-4570.51.1.tar.gz
[apple/xnu.git] / bsd / kern / mach_loader.c
CommitLineData
1c79356b 1/*
6d2010ae 2 * Copyright (c) 2000-2010 Apple Inc. All rights reserved.
5d5c5d0d 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
1c79356b 5 *
2d21ac55
A
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.
8f6c56a5 14 *
2d21ac55
A
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
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
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.
8f6c56a5 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b
A
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 */
91447636 39
1c79356b 40#include <sys/param.h>
91447636 41#include <sys/vnode_internal.h>
1c79356b
A
42#include <sys/uio.h>
43#include <sys/namei.h>
91447636
A
44#include <sys/proc_internal.h>
45#include <sys/kauth.h>
1c79356b
A
46#include <sys/stat.h>
47#include <sys/malloc.h>
91447636 48#include <sys/mount_internal.h>
1c79356b 49#include <sys/fcntl.h>
91447636
A
50#include <sys/ubc_internal.h>
51#include <sys/imgact.h>
39236c6e 52#include <sys/codesign.h>
39037602
A
53#include <sys/proc_uuid_policy.h>
54#include <sys/reason.h>
55#include <sys/kdebug.h>
1c79356b 56
1c79356b 57#include <mach/mach_types.h>
91447636
A
58#include <mach/vm_map.h> /* vm_allocate() */
59#include <mach/mach_vm.h> /* mach_vm_allocate() */
60#include <mach/vm_statistics.h>
91447636
A
61#include <mach/task.h>
62#include <mach/thread_act.h>
63
64#include <machine/vmparam.h>
2d21ac55 65#include <machine/exec.h>
6d2010ae 66#include <machine/pal_routines.h>
1c79356b 67
527f9951 68#include <kern/ast.h>
91447636
A
69#include <kern/kern_types.h>
70#include <kern/cpu_number.h>
1c79356b 71#include <kern/mach_loader.h>
b0d623f7 72#include <kern/mach_fat.h>
91447636 73#include <kern/kalloc.h>
55e303ae 74#include <kern/task.h>
91447636 75#include <kern/thread.h>
593a1d5f 76#include <kern/page_decrypt.h>
1c79356b
A
77
78#include <mach-o/fat.h>
79#include <mach-o/loader.h>
80
91447636 81#include <vm/pmap.h>
1c79356b
A
82#include <vm/vm_map.h>
83#include <vm/vm_kern.h>
84#include <vm/vm_pager.h>
85#include <vm/vnode_pager.h>
a39ff7e2 86#include <vm/vm_protos.h>
39236c6e 87#include <IOKit/IOReturn.h> /* for kIOReturnNotPrivileged */
9bccf70c 88
490019cf
A
89#include <os/overflow.h>
90
a39ff7e2
A
91#if __x86_64__
92extern int bootarg_no32exec; /* bsd_init.c */
93#endif
94
91447636
A
95/*
96 * XXX vm/pmap.h should not treat these prototypes as MACH_KERNEL_PRIVATE
97 * when KERNEL is defined.
98 */
316670eb
A
99extern pmap_t pmap_create(ledger_t ledger, vm_map_size_t size,
100 boolean_t is_64bit);
91447636
A
101
102/* XXX should have prototypes in a shared header file */
91447636 103extern int get_map_nentries(vm_map_t);
91447636 104
2d21ac55
A
105extern kern_return_t memory_object_signed(memory_object_control_t control,
106 boolean_t is_signed);
91447636
A
107
108/* An empty load_result_t */
39037602 109static const load_result_t load_result_null = {
2d21ac55
A
110 .mach_header = MACH_VM_MIN_ADDRESS,
111 .entry_point = MACH_VM_MIN_ADDRESS,
112 .user_stack = MACH_VM_MIN_ADDRESS,
316670eb 113 .user_stack_size = 0,
39037602
A
114 .user_stack_alloc = MACH_VM_MIN_ADDRESS,
115 .user_stack_alloc_size = 0,
b0d623f7
A
116 .all_image_info_addr = MACH_VM_MIN_ADDRESS,
117 .all_image_info_size = 0,
2d21ac55
A
118 .thread_count = 0,
119 .unixproc = 0,
120 .dynlinker = 0,
316670eb 121 .needs_dynlinker = 0,
6d2010ae 122 .validentry = 0,
c18c124e 123 .using_lcmain = 0,
39037602 124 .is64bit = 0,
b0d623f7 125 .csflags = 0,
3e170ce0 126 .has_pagezero = 0,
6d2010ae
A
127 .uuid = { 0 },
128 .min_vm_addr = MACH_VM_MAX_ADDRESS,
04b8595b 129 .max_vm_addr = MACH_VM_MIN_ADDRESS,
490019cf
A
130 .cs_end_offset = 0,
131 .threadstate = NULL,
132 .threadstate_sz = 0
91447636 133};
9bccf70c 134
1c79356b
A
135/*
136 * Prototypes of static functions.
137 */
91447636 138static load_return_t
1c79356b
A
139parse_machfile(
140 struct vnode *vp,
91447636 141 vm_map_t map,
2d21ac55 142 thread_t thread,
1c79356b 143 struct mach_header *header,
91447636
A
144 off_t file_offset,
145 off_t macho_size,
91447636 146 int depth,
6d2010ae 147 int64_t slide,
39037602
A
148 int64_t dyld_slide,
149 load_result_t *result,
150 load_result_t *binresult,
151 struct image_params *imgp
91447636
A
152);
153
154static load_return_t
1c79356b 155load_segment(
b0d623f7
A
156 struct load_command *lcp,
157 uint32_t filetype,
158 void *control,
91447636
A
159 off_t pager_offset,
160 off_t macho_size,
b0d623f7 161 struct vnode *vp,
91447636 162 vm_map_t map,
6d2010ae 163 int64_t slide,
91447636
A
164 load_result_t *result
165);
166
39236c6e
A
167static load_return_t
168load_uuid(
169 struct uuid_command *uulp,
170 char *command_end,
171 load_result_t *result
172);
173
6d2010ae
A
174static load_return_t
175load_code_signature(
2d21ac55
A
176 struct linkedit_data_command *lcp,
177 struct vnode *vp,
178 off_t macho_offset,
179 off_t macho_size,
180 cpu_type_t cputype,
39037602
A
181 load_result_t *result,
182 struct image_params *imgp);
2d21ac55 183
593a1d5f
A
184#if CONFIG_CODE_DECRYPTION
185static load_return_t
186set_code_unprotect(
187 struct encryption_info_command *lcp,
188 caddr_t addr,
189 vm_map_t map,
316670eb 190 int64_t slide,
3e170ce0
A
191 struct vnode *vp,
192 off_t macho_offset,
39236c6e 193 cpu_type_t cputype,
3e170ce0 194 cpu_subtype_t cpusubtype);
593a1d5f
A
195#endif
196
316670eb
A
197static
198load_return_t
199load_main(
200 struct entry_point_command *epc,
201 thread_t thread,
202 int64_t slide,
203 load_result_t *result
204);
205
91447636 206static load_return_t
1c79356b
A
207load_unixthread(
208 struct thread_command *tcp,
2d21ac55 209 thread_t thread,
6d2010ae 210 int64_t slide,
0b4e3aa0 211 load_result_t *result
91447636
A
212);
213
214static load_return_t
1c79356b 215load_threadstate(
0b4e3aa0 216 thread_t thread,
b0d623f7 217 uint32_t *ts,
490019cf
A
218 uint32_t total_size,
219 load_result_t *
91447636
A
220);
221
222static load_return_t
1c79356b 223load_threadstack(
0b4e3aa0 224 thread_t thread,
39037602
A
225 uint32_t *ts,
226 uint32_t total_size,
6d2010ae 227 mach_vm_offset_t *user_stack,
39037602
A
228 int *customstack,
229 load_result_t *result
91447636
A
230);
231
232static load_return_t
1c79356b 233load_threadentry(
0b4e3aa0 234 thread_t thread,
b0d623f7
A
235 uint32_t *ts,
236 uint32_t total_size,
91447636
A
237 mach_vm_offset_t *entry_point
238);
239
240static load_return_t
1c79356b
A
241load_dylinker(
242 struct dylinker_command *lcp,
91447636 243 integer_t archbits,
39037602
A
244 vm_map_t map,
245 thread_t thread,
246 int depth,
6d2010ae 247 int64_t slide,
39037602
A
248 load_result_t *result,
249 struct image_params *imgp
91447636
A
250);
251
6d2010ae
A
252struct macho_data;
253
91447636 254static load_return_t
1c79356b 255get_macho_vnode(
5ba3f43e 256 const char *path,
91447636 257 integer_t archbits,
1c79356b 258 struct mach_header *mach_header,
91447636
A
259 off_t *file_offset,
260 off_t *macho_size,
6d2010ae 261 struct macho_data *macho_data,
1c79356b
A
262 struct vnode **vpp
263);
264
b0d623f7
A
265static inline void
266widen_segment_command(const struct segment_command *scp32,
267 struct segment_command_64 *scp)
268{
269 scp->cmd = scp32->cmd;
270 scp->cmdsize = scp32->cmdsize;
271 bcopy(scp32->segname, scp->segname, sizeof(scp->segname));
272 scp->vmaddr = scp32->vmaddr;
273 scp->vmsize = scp32->vmsize;
274 scp->fileoff = scp32->fileoff;
275 scp->filesize = scp32->filesize;
276 scp->maxprot = scp32->maxprot;
277 scp->initprot = scp32->initprot;
278 scp->nsects = scp32->nsects;
279 scp->flags = scp32->flags;
280}
281
282static void
283note_all_image_info_section(const struct segment_command_64 *scp,
284 boolean_t is64, size_t section_size, const void *sections,
6d2010ae 285 int64_t slide, load_result_t *result)
b0d623f7
A
286{
287 const union {
288 struct section s32;
289 struct section_64 s64;
290 } *sectionp;
291 unsigned int i;
292
5ba3f43e 293
b0d623f7
A
294 if (strncmp(scp->segname, "__DATA", sizeof(scp->segname)) != 0)
295 return;
296 for (i = 0; i < scp->nsects; ++i) {
297 sectionp = (const void *)
298 ((const char *)sections + section_size * i);
299 if (0 == strncmp(sectionp->s64.sectname, "__all_image_info",
300 sizeof(sectionp->s64.sectname))) {
301 result->all_image_info_addr =
302 is64 ? sectionp->s64.addr : sectionp->s32.addr;
6d2010ae 303 result->all_image_info_addr += slide;
b0d623f7
A
304 result->all_image_info_size =
305 is64 ? sectionp->s64.size : sectionp->s32.size;
306 return;
307 }
308 }
309}
310
5ba3f43e
A
311#if __arm64__
312/*
313 * Allow bypassing some security rules (hard pagezero, no write+execute)
314 * in exchange for better binary compatibility for legacy apps built
315 * before 16KB-alignment was enforced.
316 */
317int fourk_binary_compatibility_unsafe = TRUE;
318int fourk_binary_compatibility_allow_wx = FALSE;
319#endif /* __arm64__ */
3e170ce0 320
1c79356b
A
321load_return_t
322load_machfile(
91447636 323 struct image_params *imgp,
1c79356b 324 struct mach_header *header,
2d21ac55 325 thread_t thread,
490019cf 326 vm_map_t *mapp,
91447636 327 load_result_t *result
1c79356b
A
328)
329{
91447636
A
330 struct vnode *vp = imgp->ip_vp;
331 off_t file_offset = imgp->ip_arch_offset;
332 off_t macho_size = imgp->ip_arch_size;
316670eb 333 off_t file_size = imgp->ip_vattr->va_data_size;
91447636 334 pmap_t pmap = 0; /* protected by create_map */
1c79356b 335 vm_map_t map;
1c79356b 336 load_result_t myresult;
1c79356b 337 load_return_t lret;
fe8ab488 338 boolean_t enforce_hard_pagezero = TRUE;
743345f9 339 int in_exec = (imgp->ip_flags & IMGPF_EXEC);
b0d623f7 340 task_t task = current_task();
13f56ec4 341 proc_t p = current_proc();
5ba3f43e
A
342 int64_t aslr_page_offset = 0;
343 int64_t dyld_aslr_page_offset = 0;
344 int64_t aslr_section_size = 0;
345 int64_t aslr_section_offset = 0;
6d2010ae 346 kern_return_t kret;
b0d623f7 347
316670eb
A
348 if (macho_size > file_size) {
349 return(LOAD_BADMACHO);
350 }
351
39037602
A
352 result->is64bit = ((imgp->ip_flags & IMGPF_IS_64BIT) == IMGPF_IS_64BIT);
353
743345f9
A
354 task_t ledger_task;
355 if (imgp->ip_new_thread) {
356 ledger_task = get_threadtask(imgp->ip_new_thread);
357 } else {
358 ledger_task = task;
0b4e3aa0 359 }
743345f9
A
360 pmap = pmap_create(get_task_ledger(ledger_task),
361 (vm_map_size_t) 0,
362 result->is64bit);
363 map = vm_map_create(pmap,
364 0,
365 vm_compute_max_offset(result->is64bit),
366 TRUE);
0c530ab8 367
5ba3f43e
A
368#if defined(__arm64__)
369 if (result->is64bit) {
370 /* enforce 16KB alignment of VM map entries */
371 vm_map_set_page_shift(map, SIXTEENK_PAGE_SHIFT);
372 } else {
373 vm_map_set_page_shift(map, page_shift_user32);
374 }
375#elif (__ARM_ARCH_7K__ >= 2) && defined(PLATFORM_WatchOS)
3e170ce0
A
376 /* enforce 16KB alignment for watch targets with new ABI */
377 vm_map_set_page_shift(map, SIXTEENK_PAGE_SHIFT);
378#endif /* __arm64__ */
fe8ab488 379
7e4a7d39 380#ifndef CONFIG_ENFORCE_SIGNED_CODE
39236c6e
A
381 /* This turns off faulting for executable pages, which allows
382 * to circumvent Code Signing Enforcement. The per process
383 * flag (CS_ENFORCEMENT) is not set yet, but we can use the
384 * global flag.
385 */
386 if ( !cs_enforcement(NULL) && (header->flags & MH_ALLOW_STACK_EXECUTION) )
0c530ab8 387 vm_map_disable_NX(map);
7e4a7d39 388#endif
6d2010ae
A
389
390 /* Forcibly disallow execution from data pages on even if the arch
391 * normally permits it. */
392 if ((header->flags & MH_NO_HEAP_EXECUTION) && !(imgp->ip_flags & IMGPF_ALLOW_DATA_EXEC))
393 vm_map_disallow_data_exec(map);
5ba3f43e 394
6d2010ae 395 /*
39236c6e 396 * Compute a random offset for ASLR, and an independent random offset for dyld.
6d2010ae
A
397 */
398 if (!(imgp->ip_flags & IMGPF_DISABLE_ASLR)) {
5ba3f43e
A
399 vm_map_get_max_aslr_slide_section(map, &aslr_section_offset, &aslr_section_size);
400 aslr_section_offset = (random() % aslr_section_offset) * aslr_section_size;
39236c6e 401
5ba3f43e
A
402 aslr_page_offset = random();
403 aslr_page_offset %= vm_map_get_max_aslr_slide_pages(map);
404 aslr_page_offset <<= vm_map_page_shift(map);
39236c6e 405
5ba3f43e
A
406 dyld_aslr_page_offset = random();
407 dyld_aslr_page_offset %= vm_map_get_max_loader_aslr_slide_pages(map);
408 dyld_aslr_page_offset <<= vm_map_page_shift(map);
39236c6e 409
5ba3f43e 410 aslr_page_offset += aslr_section_offset;
6d2010ae 411 }
5ba3f43e 412
1c79356b
A
413 if (!result)
414 result = &myresult;
415
91447636 416 *result = load_result_null;
1c79356b 417
39037602
A
418 /*
419 * re-set the bitness on the load result since we cleared the load result above.
420 */
421 result->is64bit = ((imgp->ip_flags & IMGPF_IS_64BIT) == IMGPF_IS_64BIT);
422
2d21ac55 423 lret = parse_machfile(vp, map, thread, header, file_offset, macho_size,
5ba3f43e 424 0, aslr_page_offset, dyld_aslr_page_offset, result,
39037602 425 NULL, imgp);
1c79356b
A
426
427 if (lret != LOAD_SUCCESS) {
743345f9 428 vm_map_deallocate(map); /* will lose pmap reference too */
1c79356b
A
429 return(lret);
430 }
55e303ae 431
fe8ab488
A
432#if __x86_64__
433 /*
434 * On x86, for compatibility, don't enforce the hard page-zero restriction for 32-bit binaries.
435 */
39037602 436 if (!result->is64bit) {
fe8ab488
A
437 enforce_hard_pagezero = FALSE;
438 }
5ba3f43e
A
439
440 /*
441 * For processes with IMGPF_HIGH_BITS_ASLR, add a few random high bits
442 * to the start address for "anywhere" memory allocations.
443 */
444#define VM_MAP_HIGH_START_BITS_COUNT 8
445#define VM_MAP_HIGH_START_BITS_SHIFT 27
446 if (result->is64bit &&
447 (imgp->ip_flags & IMGPF_HIGH_BITS_ASLR)) {
448 int random_bits;
449 vm_map_offset_t high_start;
450
451 random_bits = random();
452 random_bits &= (1 << VM_MAP_HIGH_START_BITS_COUNT)-1;
453 high_start = (((vm_map_offset_t)random_bits)
454 << VM_MAP_HIGH_START_BITS_SHIFT);
455 vm_map_set_high_start(map, high_start);
456 }
457#endif /* __x86_64__ */
458
0c530ab8 459 /*
fe8ab488 460 * Check to see if the page zero is enforced by the map->min_offset.
0c530ab8 461 */
3e170ce0
A
462 if (enforce_hard_pagezero &&
463 (vm_map_has_hard_pagezero(map, 0x1000) == FALSE)) {
5ba3f43e
A
464#if __arm64__
465 if (!result->is64bit && /* not 64-bit */
466 !(header->flags & MH_PIE) && /* not PIE */
467 (vm_map_page_shift(map) != FOURK_PAGE_SHIFT ||
468 PAGE_SHIFT != FOURK_PAGE_SHIFT) && /* page size != 4KB */
469 result->has_pagezero && /* has a "soft" page zero */
470 fourk_binary_compatibility_unsafe) {
471 /*
472 * For backwards compatibility of "4K" apps on
473 * a 16K system, do not enforce a hard page zero...
474 */
475 } else
476#endif /* __arm64__ */
3e170ce0 477 {
743345f9 478 vm_map_deallocate(map); /* will lose pmap reference too */
3e170ce0 479 return (LOAD_BADMACHO);
fe8ab488 480 }
316670eb 481 }
fe8ab488 482
39037602
A
483 vm_commit_pagezero_status(map);
484
743345f9
A
485 /*
486 * If this is an exec, then we are going to destroy the old
487 * task, and it's correct to halt it; if it's spawn, the
488 * task is not yet running, and it makes no sense.
489 */
490 if (in_exec) {
b0d623f7 491 /*
743345f9
A
492 * Mark the task as halting and start the other
493 * threads towards terminating themselves. Then
494 * make sure any threads waiting for a process
495 * transition get informed that we are committed to
496 * this transition, and then finally complete the
497 * task halting (wait for threads and then cleanup
498 * task resources).
499 *
500 * NOTE: task_start_halt() makes sure that no new
501 * threads are created in the task during the transition.
502 * We need to mark the workqueue as exiting before we
503 * wait for threads to terminate (at the end of which
504 * we no longer have a prohibition on thread creation).
505 *
506 * Finally, clean up any lingering workqueue data structures
507 * that may have been left behind by the workqueue threads
508 * as they exited (and then clean up the work queue itself).
b0d623f7 509 */
743345f9
A
510 kret = task_start_halt(task);
511 if (kret != KERN_SUCCESS) {
512 vm_map_deallocate(map); /* will lose pmap reference too */
513 return (LOAD_FAILURE);
316670eb 514 }
743345f9
A
515 proc_transcommit(p, 0);
516 workqueue_mark_exiting(p);
517 task_complete_halt(task);
518 workqueue_exit(p);
5ba3f43e 519
743345f9
A
520 /*
521 * Roll up accounting info to new task. The roll up is done after
522 * task_complete_halt to make sure the thread accounting info is
523 * rolled up to current_task.
524 */
525 task_rollup_accounting_info(get_threadtask(thread), task);
0b4e3aa0 526 }
743345f9 527 *mapp = map;
527f9951
A
528
529#ifdef CONFIG_32BIT_TELEMETRY
530 if (!result->is64bit) {
531 /*
532 * This may not need to be an AST; we merely need to ensure that
533 * we gather telemetry at the point where all of the information
534 * that we want has been added to the process.
535 */
536 task_set_32bit_log_flag(get_threadtask(thread));
537 act_set_astbsd(thread);
538 }
539#endif /* CONFIG_32BIT_TELEMETRY */
540
1c79356b
A
541 return(LOAD_SUCCESS);
542}
543
3e170ce0
A
544int macho_printf = 0;
545#define MACHO_PRINTF(args) \
546 do { \
547 if (macho_printf) { \
548 printf args; \
549 } \
550 } while (0)
551
91447636
A
552/*
553 * The file size of a mach-o file is limited to 32 bits; this is because
554 * this is the limit on the kalloc() of enough bytes for a mach_header and
555 * the contents of its sizeofcmds, which is currently constrained to 32
556 * bits in the file format itself. We read into the kernel buffer the
557 * commands section, and then parse it in order to parse the mach-o file
558 * format load_command segment(s). We are only interested in a subset of
6d2010ae
A
559 * the total set of possible commands. If "map"==VM_MAP_NULL or
560 * "thread"==THREAD_NULL, do not make permament VM modifications,
561 * just preflight the parse.
91447636 562 */
1c79356b
A
563static
564load_return_t
565parse_machfile(
91447636 566 struct vnode *vp,
1c79356b 567 vm_map_t map,
2d21ac55 568 thread_t thread,
1c79356b 569 struct mach_header *header,
91447636
A
570 off_t file_offset,
571 off_t macho_size,
1c79356b 572 int depth,
6d2010ae 573 int64_t aslr_offset,
39236c6e 574 int64_t dyld_aslr_offset,
39037602
A
575 load_result_t *result,
576 load_result_t *binresult,
577 struct image_params *imgp
1c79356b
A
578)
579{
a3d08fcd 580 uint32_t ncmds;
91447636 581 struct load_command *lcp;
1c79356b 582 struct dylinker_command *dlp = 0;
91447636 583 integer_t dlarchbits = 0;
b0d623f7 584 void * control;
55e303ae 585 load_return_t ret = LOAD_SUCCESS;
5ba3f43e
A
586 void * addr;
587 vm_size_t alloc_size, cmds_size;
a3d08fcd
A
588 size_t offset;
589 size_t oldoffset; /* for overflow check */
1c79356b 590 int pass;
2d21ac55 591 proc_t p = current_proc(); /* XXXX */
1c79356b 592 int error;
3e170ce0 593 int resid = 0;
91447636
A
594 size_t mach_header_sz = sizeof(struct mach_header);
595 boolean_t abi64;
2d21ac55 596 boolean_t got_code_signatures = FALSE;
39037602
A
597 boolean_t found_header_segment = FALSE;
598 boolean_t found_xhdr = FALSE;
6d2010ae 599 int64_t slide = 0;
39037602
A
600 boolean_t dyld_no_load_addr = FALSE;
601 boolean_t is_dyld = FALSE;
602 vm_map_offset_t effective_page_mask = MAX(PAGE_MASK, vm_map_page_mask(map));
5ba3f43e
A
603#if __arm64__
604 uint32_t pagezero_end = 0;
605 uint32_t executable_end = 0;
606 uint32_t writable_start = 0;
607 vm_map_size_t effective_page_size;
608
609 effective_page_size = MAX(PAGE_SIZE, vm_map_page_size(map));
610#endif /* __arm64__ */
91447636
A
611
612 if (header->magic == MH_MAGIC_64 ||
613 header->magic == MH_CIGAM_64) {
614 mach_header_sz = sizeof(struct mach_header_64);
615 }
1c79356b
A
616
617 /*
618 * Break infinite recursion
619 */
c18c124e 620 if (depth > 1) {
1c79356b 621 return(LOAD_FAILURE);
2d21ac55 622 }
0b4e3aa0 623
1c79356b
A
624 depth++;
625
626 /*
627 * Check to see if right machine type.
628 */
39236c6e 629 if (((cpu_type_t)(header->cputype & ~CPU_ARCH_MASK) != (cpu_type() & ~CPU_ARCH_MASK)) ||
a39ff7e2 630 !grade_binary(header->cputype,
2d21ac55 631 header->cpusubtype & ~CPU_SUBTYPE_MASK))
1c79356b 632 return(LOAD_BADARCH);
a39ff7e2
A
633
634#if __x86_64__
635 if (bootarg_no32exec && (header->cputype == CPU_TYPE_X86)) {
636 return(LOAD_BADARCH_X86);
637 }
638#endif
639
91447636 640 abi64 = ((header->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64);
a39ff7e2 641
1c79356b 642 switch (header->filetype) {
a39ff7e2 643
1c79356b 644 case MH_EXECUTE:
2d21ac55 645 if (depth != 1) {
1c79356b 646 return (LOAD_FAILURE);
2d21ac55 647 }
5ba3f43e
A
648#if CONFIG_EMBEDDED
649 if (header->flags & MH_DYLDLINK) {
650 /* Check properties of dynamic executables */
651 if (!(header->flags & MH_PIE) && pie_required(header->cputype, header->cpusubtype & ~CPU_SUBTYPE_MASK)) {
652 return (LOAD_FAILURE);
653 }
654 result->needs_dynlinker = TRUE;
655 } else {
656 /* Check properties of static executables (disallowed except for development) */
657#if !(DEVELOPMENT || DEBUG)
658 return (LOAD_FAILURE);
659#endif
660 }
661#endif /* CONFIG_EMBEDDED */
1c79356b 662
c18c124e 663 break;
1c79356b 664 case MH_DYLINKER:
2d21ac55 665 if (depth != 2) {
1c79356b 666 return (LOAD_FAILURE);
2d21ac55 667 }
39037602 668 is_dyld = TRUE;
1c79356b
A
669 break;
670
671 default:
672 return (LOAD_FAILURE);
673 }
674
675 /*
676 * Get the pager for the file.
677 */
b0d623f7 678 control = ubc_getobject(vp, UBC_FLAGS_NONE);
1c79356b 679
5ba3f43e
A
680 /* ensure header + sizeofcmds falls within the file */
681 if (os_add_overflow(mach_header_sz, header->sizeofcmds, &cmds_size) ||
682 (off_t)cmds_size > macho_size ||
683 round_page_overflow(cmds_size, &alloc_size)) {
684 return LOAD_BADMACHO;
685 }
1c79356b
A
686
687 /*
688 * Map the load commands into kernel memory.
689 */
5ba3f43e
A
690 addr = kalloc(alloc_size);
691 if (addr == NULL) {
692 return LOAD_NOSPACE;
693 }
0b4e3aa0 694
5ba3f43e 695 error = vn_rdwr(UIO_READ, vp, addr, alloc_size, file_offset,
b0d623f7 696 UIO_SYSSPACE, 0, kauth_cred_get(), &resid, p);
91447636 697 if (error) {
5ba3f43e
A
698 kfree(addr, alloc_size);
699 return LOAD_IOERROR;
1c79356b 700 }
6d2010ae 701
c18c124e
A
702 if (resid) {
703 /* We must be able to read in as much as the mach_header indicated */
5ba3f43e
A
704 kfree(addr, alloc_size);
705 return LOAD_BADMACHO;
c18c124e
A
706 }
707
6d2010ae
A
708 /*
709 * For PIE and dyld, slide everything by the ASLR offset.
710 */
39037602 711 if ((header->flags & MH_PIE) || is_dyld) {
6d2010ae
A
712 slide = aslr_offset;
713 }
714
39037602 715 /*
39236c6e
A
716 * Scan through the commands, processing each one as necessary.
717 * We parse in three passes through the headers:
3e170ce0 718 * 0: determine if TEXT and DATA boundary can be page-aligned
39236c6e
A
719 * 1: thread state, uuid, code signature
720 * 2: segments
721 * 3: dyld, encryption, check entry point
1c79356b 722 */
39037602
A
723
724 boolean_t slide_realign = FALSE;
5ba3f43e
A
725#if __arm64__
726 if (!abi64) {
727 slide_realign = TRUE;
728 }
729#endif
39037602 730
3e170ce0
A
731 for (pass = 0; pass <= 3; pass++) {
732
39037602
A
733 if (pass == 0 && !slide_realign && !is_dyld) {
734 /* if we dont need to realign the slide or determine dyld's load
735 * address, pass 0 can be skipped */
3e170ce0
A
736 continue;
737 } else if (pass == 1) {
5ba3f43e
A
738#if __arm64__
739 boolean_t is_pie;
740 int64_t adjust;
741
742 is_pie = ((header->flags & MH_PIE) != 0);
743 if (pagezero_end != 0 &&
744 pagezero_end < effective_page_size) {
745 /* need at least 1 page for PAGEZERO */
746 adjust = effective_page_size;
747 MACHO_PRINTF(("pagezero boundary at "
748 "0x%llx; adjust slide from "
749 "0x%llx to 0x%llx%s\n",
750 (uint64_t) pagezero_end,
751 slide,
752 slide + adjust,
753 (is_pie
754 ? ""
755 : " BUT NO PIE ****** :-(")));
756 if (is_pie) {
757 slide += adjust;
758 pagezero_end += adjust;
759 executable_end += adjust;
760 writable_start += adjust;
761 }
762 }
763 if (pagezero_end != 0) {
764 result->has_pagezero = TRUE;
765 }
766 if (executable_end == writable_start &&
767 (executable_end & effective_page_mask) != 0 &&
768 (executable_end & FOURK_PAGE_MASK) == 0) {
769
770 /*
771 * The TEXT/DATA boundary is 4K-aligned but
772 * not page-aligned. Adjust the slide to make
773 * it page-aligned and avoid having a page
774 * with both write and execute permissions.
775 */
776 adjust =
777 (effective_page_size -
778 (executable_end & effective_page_mask));
779 MACHO_PRINTF(("page-unaligned X-W boundary at "
780 "0x%llx; adjust slide from "
781 "0x%llx to 0x%llx%s\n",
782 (uint64_t) executable_end,
783 slide,
784 slide + adjust,
785 (is_pie
786 ? ""
787 : " BUT NO PIE ****** :-(")));
788 if (is_pie)
789 slide += adjust;
790 }
791#endif /* __arm64__ */
39037602
A
792
793 if (dyld_no_load_addr && binresult) {
794 /*
795 * The dyld Mach-O does not specify a load address. Try to locate
796 * it right after the main binary. If binresult == NULL, load
797 * directly to the given slide.
798 */
799 slide = vm_map_round_page(slide + binresult->max_vm_addr, effective_page_mask);
800 }
3e170ce0 801 }
6d2010ae 802
6d2010ae
A
803 /*
804 * Check that the entry point is contained in an executable segments
805 */
c18c124e 806 if ((pass == 3) && (!result->using_lcmain && result->validentry == 0)) {
6d2010ae
A
807 thread_state_initialize(thread);
808 ret = LOAD_FAILURE;
809 break;
810 }
6d2010ae 811
39037602
A
812 /*
813 * Check that some segment maps the start of the mach-o file, which is
814 * needed by the dynamic loader to read the mach headers, etc.
815 */
816 if ((pass == 3) && (found_header_segment == FALSE)) {
817 ret = LOAD_BADMACHO;
818 break;
819 }
820
a3d08fcd
A
821 /*
822 * Loop through each of the load_commands indicated by the
823 * Mach-O header; if an absurd value is provided, we just
824 * run off the end of the reserved section by incrementing
825 * the offset too far, so we are implicitly fail-safe.
826 */
91447636 827 offset = mach_header_sz;
1c79356b 828 ncmds = header->ncmds;
6d2010ae 829
1c79356b 830 while (ncmds--) {
5ba3f43e
A
831
832 /* ensure enough space for a minimal load command */
833 if (offset + sizeof(struct load_command) > cmds_size) {
834 ret = LOAD_BADMACHO;
835 break;
836 }
837
1c79356b
A
838 /*
839 * Get a pointer to the command.
840 */
841 lcp = (struct load_command *)(addr + offset);
a3d08fcd 842 oldoffset = offset;
1c79356b
A
843
844 /*
a3d08fcd
A
845 * Perform prevalidation of the struct load_command
846 * before we attempt to use its contents. Invalid
847 * values are ones which result in an overflow, or
848 * which can not possibly be valid commands, or which
849 * straddle or exist past the reserved section at the
850 * start of the image.
1c79356b 851 */
5ba3f43e
A
852 if (os_add_overflow(offset, lcp->cmdsize, &offset) ||
853 lcp->cmdsize < sizeof(struct load_command) ||
854 offset > cmds_size) {
91447636 855 ret = LOAD_BADMACHO;
a3d08fcd 856 break;
1c79356b
A
857 }
858
859 /*
a3d08fcd
A
860 * Act on struct load_command's for which kernel
861 * intervention is required.
1c79356b
A
862 */
863 switch(lcp->cmd) {
39037602
A
864 case LC_SEGMENT: {
865 struct segment_command *scp = (struct segment_command *) lcp;
866
3e170ce0 867 if (pass == 0) {
39037602
A
868 if (is_dyld && scp->vmaddr == 0 && scp->fileoff == 0) {
869 dyld_no_load_addr = TRUE;
870 if (!slide_realign) {
871 /* got what we need, bail early on pass 0 */
872 continue;
873 }
874 }
875
5ba3f43e
A
876#if __arm64__
877 assert(!abi64);
878
879 if (scp->initprot == 0 && scp->maxprot == 0 && scp->vmaddr == 0) {
880 /* PAGEZERO */
881 if (os_add3_overflow(scp->vmaddr, scp->vmsize, slide, &pagezero_end)) {
882 ret = LOAD_BADMACHO;
883 break;
884 }
885 }
886 if (scp->initprot & VM_PROT_EXECUTE) {
887 /* TEXT */
888 if (os_add3_overflow(scp->vmaddr, scp->vmsize, slide, &executable_end)) {
889 ret = LOAD_BADMACHO;
890 break;
891 }
892 }
893 if (scp->initprot & VM_PROT_WRITE) {
894 /* DATA */
895 if (os_add_overflow(scp->vmaddr, slide, &writable_start)) {
896 ret = LOAD_BADMACHO;
897 break;
898 }
899 }
900#endif /* __arm64__ */
3e170ce0
A
901 break;
902 }
903
39037602
A
904 if (pass == 1 && !strncmp(scp->segname, "__XHDR", sizeof(scp->segname))) {
905 found_xhdr = TRUE;
906 }
907
39236c6e
A
908 if (pass != 2)
909 break;
910
911 if (abi64) {
912 /*
913 * Having an LC_SEGMENT command for the
914 * wrong ABI is invalid <rdar://problem/11021230>
915 */
916 ret = LOAD_BADMACHO;
917 break;
918 }
919
920 ret = load_segment(lcp,
921 header->filetype,
922 control,
923 file_offset,
924 macho_size,
925 vp,
926 map,
927 slide,
928 result);
39037602
A
929
930 if (ret == LOAD_SUCCESS && scp->fileoff == 0 && scp->filesize > 0) {
931 /* Enforce a single segment mapping offset zero, with R+X
932 * protection. */
933 if (found_header_segment ||
934 ((scp->initprot & (VM_PROT_READ|VM_PROT_EXECUTE)) != (VM_PROT_READ|VM_PROT_EXECUTE))) {
935 ret = LOAD_BADMACHO;
936 break;
937 }
938 found_header_segment = TRUE;
939 }
940
39236c6e 941 break;
39037602
A
942 }
943 case LC_SEGMENT_64: {
944 struct segment_command_64 *scp64 = (struct segment_command_64 *) lcp;
945
946 if (pass == 0) {
947 if (is_dyld && scp64->vmaddr == 0 && scp64->fileoff == 0) {
948 dyld_no_load_addr = TRUE;
949 if (!slide_realign) {
950 /* got what we need, bail early on pass 0 */
951 continue;
952 }
953 }
954 }
955
956 if (pass == 1 && !strncmp(scp64->segname, "__XHDR", sizeof(scp64->segname))) {
957 found_xhdr = TRUE;
958 }
959
6d2010ae 960 if (pass != 2)
1c79356b 961 break;
39236c6e
A
962
963 if (!abi64) {
964 /*
965 * Having an LC_SEGMENT_64 command for the
966 * wrong ABI is invalid <rdar://problem/11021230>
967 */
968 ret = LOAD_BADMACHO;
969 break;
970 }
971
b0d623f7 972 ret = load_segment(lcp,
39236c6e
A
973 header->filetype,
974 control,
975 file_offset,
976 macho_size,
977 vp,
978 map,
979 slide,
980 result);
39037602
A
981
982 if (ret == LOAD_SUCCESS && scp64->fileoff == 0 && scp64->filesize > 0) {
983 /* Enforce a single segment mapping offset zero, with R+X
984 * protection. */
985 if (found_header_segment ||
986 ((scp64->initprot & (VM_PROT_READ|VM_PROT_EXECUTE)) != (VM_PROT_READ|VM_PROT_EXECUTE))) {
987 ret = LOAD_BADMACHO;
988 break;
989 }
990 found_header_segment = TRUE;
991 }
992
1c79356b 993 break;
39037602 994 }
1c79356b 995 case LC_UNIXTHREAD:
6d2010ae 996 if (pass != 1)
1c79356b
A
997 break;
998 ret = load_unixthread(
91447636 999 (struct thread_command *) lcp,
6d2010ae
A
1000 thread,
1001 slide,
1c79356b
A
1002 result);
1003 break;
316670eb
A
1004 case LC_MAIN:
1005 if (pass != 1)
1006 break;
1007 if (depth != 1)
1008 break;
1009 ret = load_main(
1010 (struct entry_point_command *) lcp,
1011 thread,
1012 slide,
1013 result);
1014 break;
1c79356b 1015 case LC_LOAD_DYLINKER:
6d2010ae 1016 if (pass != 3)
1c79356b 1017 break;
91447636 1018 if ((depth == 1) && (dlp == 0)) {
1c79356b 1019 dlp = (struct dylinker_command *)lcp;
91447636
A
1020 dlarchbits = (header->cputype & CPU_ARCH_MASK);
1021 } else {
1c79356b 1022 ret = LOAD_FAILURE;
91447636 1023 }
1c79356b 1024 break;
b0d623f7 1025 case LC_UUID:
6d2010ae 1026 if (pass == 1 && depth == 1) {
39236c6e 1027 ret = load_uuid((struct uuid_command *) lcp,
5ba3f43e 1028 (char *)addr + cmds_size,
39236c6e 1029 result);
b0d623f7
A
1030 }
1031 break;
2d21ac55
A
1032 case LC_CODE_SIGNATURE:
1033 /* CODE SIGNING */
6d2010ae 1034 if (pass != 1)
2d21ac55
A
1035 break;
1036 /* pager -> uip ->
1037 load signatures & store in uip
1038 set VM object "signed_pages"
1039 */
1040 ret = load_code_signature(
1041 (struct linkedit_data_command *) lcp,
1042 vp,
1043 file_offset,
1044 macho_size,
1045 header->cputype,
39037602
A
1046 result,
1047 imgp);
2d21ac55
A
1048 if (ret != LOAD_SUCCESS) {
1049 printf("proc %d: load code signature error %d "
1050 "for file \"%s\"\n",
1051 p->p_pid, ret, vp->v_name);
c18c124e
A
1052 /*
1053 * Allow injections to be ignored on devices w/o enforcement enabled
1054 */
1055 if (!cs_enforcement(NULL))
1056 ret = LOAD_SUCCESS; /* ignore error */
1057
2d21ac55
A
1058 } else {
1059 got_code_signatures = TRUE;
1060 }
04b8595b
A
1061
1062 if (got_code_signatures) {
c18c124e
A
1063 unsigned tainted = CS_VALIDATE_TAINTED;
1064 boolean_t valid = FALSE;
04b8595b
A
1065 vm_size_t off = 0;
1066
1067
1068 if (cs_debug > 10)
1069 printf("validating initial pages of %s\n", vp->v_name);
04b8595b 1070
5ba3f43e 1071 while (off < alloc_size && ret == LOAD_SUCCESS) {
c18c124e
A
1072 tainted = CS_VALIDATE_TAINTED;
1073
39037602
A
1074 valid = cs_validate_range(vp,
1075 NULL,
1076 file_offset + off,
1077 addr + off,
1078 PAGE_SIZE,
1079 &tainted);
c18c124e 1080 if (!valid || (tainted & CS_VALIDATE_TAINTED)) {
04b8595b
A
1081 if (cs_debug)
1082 printf("CODE SIGNING: %s[%d]: invalid initial page at offset %lld validated:%d tainted:%d csflags:0x%x\n",
1083 vp->v_name, p->p_pid, (long long)(file_offset + off), valid, tainted, result->csflags);
1084 if (cs_enforcement(NULL) ||
1085 (result->csflags & (CS_HARD|CS_KILL|CS_ENFORCEMENT))) {
1086 ret = LOAD_FAILURE;
1087 }
1088 result->csflags &= ~CS_VALID;
1089 }
1090 off += PAGE_SIZE;
1091 }
1092 }
1093
2d21ac55 1094 break;
593a1d5f
A
1095#if CONFIG_CODE_DECRYPTION
1096 case LC_ENCRYPTION_INFO:
39236c6e 1097 case LC_ENCRYPTION_INFO_64:
6d2010ae 1098 if (pass != 3)
593a1d5f
A
1099 break;
1100 ret = set_code_unprotect(
1101 (struct encryption_info_command *) lcp,
3e170ce0 1102 addr, map, slide, vp, file_offset,
39236c6e 1103 header->cputype, header->cpusubtype);
593a1d5f 1104 if (ret != LOAD_SUCCESS) {
39037602 1105 os_reason_t load_failure_reason = OS_REASON_NULL;
c910b4d9 1106 printf("proc %d: set_code_unprotect() error %d "
593a1d5f
A
1107 "for file \"%s\"\n",
1108 p->p_pid, ret, vp->v_name);
39236c6e
A
1109 /*
1110 * Don't let the app run if it's
c910b4d9 1111 * encrypted but we failed to set up the
39236c6e
A
1112 * decrypter. If the keys are missing it will
1113 * return LOAD_DECRYPTFAIL.
1114 */
1115 if (ret == LOAD_DECRYPTFAIL) {
1116 /* failed to load due to missing FP keys */
1117 proc_lock(p);
1118 p->p_lflag |= P_LTERM_DECRYPTFAIL;
1119 proc_unlock(p);
39037602
A
1120
1121 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1122 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_FAIRPLAY_DECRYPT, 0, 0);
1123 load_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_FAIRPLAY_DECRYPT);
1124 } else {
1125
1126 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1127 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_DECRYPT, 0, 0);
1128 load_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_DECRYPT);
3e170ce0 1129 }
39037602
A
1130
1131 assert(load_failure_reason != OS_REASON_NULL);
1132 psignal_with_reason(p, SIGKILL, load_failure_reason);
593a1d5f
A
1133 }
1134 break;
1135#endif
1c79356b 1136 default:
a3d08fcd
A
1137 /* Other commands are ignored by the kernel */
1138 ret = LOAD_SUCCESS;
91447636 1139 break;
1c79356b
A
1140 }
1141 if (ret != LOAD_SUCCESS)
1142 break;
1143 }
1144 if (ret != LOAD_SUCCESS)
1145 break;
1146 }
fe8ab488 1147
527f9951
A
1148 if (ret == LOAD_SUCCESS) {
1149 if(!got_code_signatures && cs_enforcement(NULL)) {
1150 ret = LOAD_FAILURE;
c18c124e 1151 }
91447636 1152
316670eb 1153 /* Make sure if we need dyld, we got it */
3e170ce0 1154 if (result->needs_dynlinker && !dlp) {
316670eb
A
1155 ret = LOAD_FAILURE;
1156 }
3e170ce0 1157
c18c124e 1158 if ((ret == LOAD_SUCCESS) && (dlp != 0)) {
fe8ab488 1159 /*
c18c124e
A
1160 * load the dylinker, and slide it by the independent DYLD ASLR
1161 * offset regardless of the PIE-ness of the main binary.
1162 */
fe8ab488 1163 ret = load_dylinker(dlp, dlarchbits, map, thread, depth,
39037602 1164 dyld_aslr_offset, result, imgp);
fe8ab488 1165 }
39037602
A
1166
1167 if ((ret == LOAD_SUCCESS) && (depth == 1)) {
316670eb
A
1168 if (result->thread_count == 0) {
1169 ret = LOAD_FAILURE;
1170 }
5ba3f43e
A
1171#if CONFIG_EMBEDDED
1172 if (result->needs_dynlinker && !(result->csflags & CS_DYLD_PLATFORM)) {
1173 ret = LOAD_FAILURE;
1174 }
1175#endif
91447636 1176 }
1c79356b
A
1177 }
1178
39037602
A
1179 if (ret == LOAD_BADMACHO && found_xhdr) {
1180 ret = LOAD_BADMACHO_UPX;
1181 }
1182
5ba3f43e 1183 kfree(addr, alloc_size);
0b4e3aa0 1184
5ba3f43e 1185 return ret;
1c79356b
A
1186}
1187
593a1d5f 1188#if CONFIG_CODE_DECRYPTION
0c530ab8 1189
3e170ce0 1190#define APPLE_UNPROTECTED_HEADER_SIZE (3 * 4096)
0c530ab8
A
1191
1192static load_return_t
fe8ab488 1193unprotect_dsmos_segment(
0c530ab8
A
1194 uint64_t file_off,
1195 uint64_t file_size,
b0d623f7
A
1196 struct vnode *vp,
1197 off_t macho_offset,
0c530ab8
A
1198 vm_map_t map,
1199 vm_map_offset_t map_addr,
1200 vm_map_size_t map_size)
1201{
1202 kern_return_t kr;
1203
1204 /*
1205 * The first APPLE_UNPROTECTED_HEADER_SIZE bytes (from offset 0 of
1206 * this part of a Universal binary) are not protected...
1207 * The rest needs to be "transformed".
1208 */
1209 if (file_off <= APPLE_UNPROTECTED_HEADER_SIZE &&
1210 file_off + file_size <= APPLE_UNPROTECTED_HEADER_SIZE) {
1211 /* it's all unprotected, nothing to do... */
1212 kr = KERN_SUCCESS;
1213 } else {
1214 if (file_off <= APPLE_UNPROTECTED_HEADER_SIZE) {
1215 /*
1216 * We start mapping in the unprotected area.
1217 * Skip the unprotected part...
1218 */
1219 vm_map_offset_t delta;
1220
1221 delta = APPLE_UNPROTECTED_HEADER_SIZE;
1222 delta -= file_off;
1223 map_addr += delta;
1224 map_size -= delta;
1225 }
1226 /* ... transform the rest of the mapping. */
593a1d5f
A
1227 struct pager_crypt_info crypt_info;
1228 crypt_info.page_decrypt = dsmos_page_transform;
1229 crypt_info.crypt_ops = NULL;
1230 crypt_info.crypt_end = NULL;
b0d623f7
A
1231#pragma unused(vp, macho_offset)
1232 crypt_info.crypt_ops = (void *)0x2e69cf40;
3e170ce0
A
1233 vm_map_offset_t crypto_backing_offset;
1234 crypto_backing_offset = -1; /* i.e. use map entry's offset */
39037602
A
1235#if VM_MAP_DEBUG_APPLE_PROTECT
1236 if (vm_map_debug_apple_protect) {
1237 struct proc *p;
1238 p = current_proc();
1239 printf("APPLE_PROTECT: %d[%s] map %p "
1240 "[0x%llx:0x%llx] %s(%s)\n",
1241 p->p_pid, p->p_comm, map,
1242 (uint64_t) map_addr,
1243 (uint64_t) (map_addr + map_size),
1244 __FUNCTION__, vp->v_name);
1245 }
1246#endif /* VM_MAP_DEBUG_APPLE_PROTECT */
7e41aa88
A
1247
1248 /* The DSMOS pager can only be used by apple signed code */
1249 struct cs_blob * blob = csvnode_get_blob(vp, file_off);
1250 if( blob == NULL || !blob->csb_platform_binary || blob->csb_platform_path)
1251 {
1252 return LOAD_FAILURE;
1253 }
1254
0c530ab8
A
1255 kr = vm_map_apple_protected(map,
1256 map_addr,
593a1d5f 1257 map_addr + map_size,
3e170ce0 1258 crypto_backing_offset,
593a1d5f 1259 &crypt_info);
0c530ab8
A
1260 }
1261
1262 if (kr != KERN_SUCCESS) {
1263 return LOAD_FAILURE;
1264 }
1265 return LOAD_SUCCESS;
1266}
593a1d5f 1267#else /* CONFIG_CODE_DECRYPTION */
b0d623f7 1268static load_return_t
fe8ab488 1269unprotect_dsmos_segment(
b0d623f7
A
1270 __unused uint64_t file_off,
1271 __unused uint64_t file_size,
1272 __unused struct vnode *vp,
1273 __unused off_t macho_offset,
1274 __unused vm_map_t map,
1275 __unused vm_map_offset_t map_addr,
1276 __unused vm_map_size_t map_size)
1c79356b 1277{
b0d623f7 1278 return LOAD_SUCCESS;
1c79356b 1279}
b0d623f7 1280#endif /* CONFIG_CODE_DECRYPTION */
1c79356b 1281
3e170ce0
A
1282
1283/*
1284 * map_segment:
1285 * Maps a Mach-O segment, taking care of mis-alignment (wrt the system
1286 * page size) issues.
1287 *
1288 * The mapping might result in 1, 2 or 3 map entries:
1289 * 1. for the first page, which could be overlap with the previous
1290 * mapping,
1291 * 2. for the center (if applicable),
1292 * 3. for the last page, which could overlap with the next mapping.
1293 *
1294 * For each of those map entries, we might have to interpose a
1295 * "fourk_pager" to deal with mis-alignment wrt the system page size,
1296 * either in the mapping address and/or size or the file offset and/or
1297 * size.
1298 * The "fourk_pager" itself would be mapped with proper alignment
1299 * wrt the system page size and would then be populated with the
1300 * information about the intended mapping, with a "4KB" granularity.
1301 */
1302static kern_return_t
1303map_segment(
1304 vm_map_t map,
1305 vm_map_offset_t vm_start,
1306 vm_map_offset_t vm_end,
1307 memory_object_control_t control,
1308 vm_map_offset_t file_start,
1309 vm_map_offset_t file_end,
1310 vm_prot_t initprot,
1311 vm_prot_t maxprot)
1312{
3e170ce0
A
1313 vm_map_offset_t cur_offset, cur_start, cur_end;
1314 kern_return_t ret;
1315 vm_map_offset_t effective_page_mask;
5ba3f43e 1316 vm_map_kernel_flags_t vmk_flags, cur_vmk_flags;
3e170ce0
A
1317
1318 if (vm_end < vm_start ||
1319 file_end < file_start) {
1320 return LOAD_BADMACHO;
1321 }
1322 if (vm_end == vm_start ||
1323 file_end == file_start) {
1324 /* nothing to map... */
1325 return LOAD_SUCCESS;
1326 }
1327
1328 effective_page_mask = MAX(PAGE_MASK, vm_map_page_mask(map));
1329
5ba3f43e 1330 vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
3e170ce0
A
1331 if (vm_map_page_aligned(vm_start, effective_page_mask) &&
1332 vm_map_page_aligned(vm_end, effective_page_mask) &&
1333 vm_map_page_aligned(file_start, effective_page_mask) &&
1334 vm_map_page_aligned(file_end, effective_page_mask)) {
1335 /* all page-aligned and map-aligned: proceed */
1336 } else {
5ba3f43e
A
1337#if __arm64__
1338 /* use an intermediate "4K" pager */
1339 vmk_flags.vmkf_fourk = TRUE;
1340#else /* __arm64__ */
3e170ce0
A
1341 panic("map_segment: unexpected mis-alignment "
1342 "vm[0x%llx:0x%llx] file[0x%llx:0x%llx]\n",
1343 (uint64_t) vm_start,
1344 (uint64_t) vm_end,
1345 (uint64_t) file_start,
1346 (uint64_t) file_end);
5ba3f43e 1347#endif /* __arm64__ */
3e170ce0
A
1348 }
1349
1350 cur_offset = 0;
1351 cur_start = vm_start;
1352 cur_end = vm_start;
5ba3f43e
A
1353#if __arm64__
1354 if (!vm_map_page_aligned(vm_start, effective_page_mask)) {
1355 /* one 4K pager for the 1st page */
1356 cur_end = vm_map_round_page(cur_start, effective_page_mask);
1357 if (cur_end > vm_end) {
1358 cur_end = vm_start + (file_end - file_start);
1359 }
1360 if (control != MEMORY_OBJECT_CONTROL_NULL) {
1361 ret = vm_map_enter_mem_object_control(
1362 map,
1363 &cur_start,
1364 cur_end - cur_start,
1365 (mach_vm_offset_t)0,
1366 VM_FLAGS_FIXED,
1367 vmk_flags,
1368 VM_KERN_MEMORY_NONE,
1369 control,
1370 file_start + cur_offset,
1371 TRUE, /* copy */
1372 initprot, maxprot,
1373 VM_INHERIT_DEFAULT);
1374 } else {
1375 ret = vm_map_enter_mem_object(
1376 map,
1377 &cur_start,
1378 cur_end - cur_start,
1379 (mach_vm_offset_t)0,
1380 VM_FLAGS_FIXED,
1381 vmk_flags,
1382 VM_KERN_MEMORY_NONE,
1383 IPC_PORT_NULL,
1384 0, /* offset */
1385 TRUE, /* copy */
1386 initprot, maxprot,
1387 VM_INHERIT_DEFAULT);
1388 }
1389 if (ret != KERN_SUCCESS) {
1390 return (LOAD_NOSPACE);
1391 }
1392 cur_offset += cur_end - cur_start;
1393 }
1394#endif /* __arm64__ */
3e170ce0
A
1395 if (cur_end >= vm_start + (file_end - file_start)) {
1396 /* all mapped: done */
1397 goto done;
1398 }
1399 if (vm_map_round_page(cur_end, effective_page_mask) >=
1400 vm_map_trunc_page(vm_start + (file_end - file_start),
1401 effective_page_mask)) {
1402 /* no middle */
1403 } else {
1404 cur_start = cur_end;
1405 if ((vm_start & effective_page_mask) !=
1406 (file_start & effective_page_mask)) {
1407 /* one 4K pager for the middle */
5ba3f43e 1408 cur_vmk_flags = vmk_flags;
3e170ce0
A
1409 } else {
1410 /* regular mapping for the middle */
5ba3f43e 1411 cur_vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
3e170ce0
A
1412 }
1413 cur_end = vm_map_trunc_page(vm_start + (file_end -
1414 file_start),
1415 effective_page_mask);
1416 if (control != MEMORY_OBJECT_CONTROL_NULL) {
1417 ret = vm_map_enter_mem_object_control(
1418 map,
1419 &cur_start,
1420 cur_end - cur_start,
1421 (mach_vm_offset_t)0,
5ba3f43e
A
1422 VM_FLAGS_FIXED,
1423 cur_vmk_flags,
1424 VM_KERN_MEMORY_NONE,
3e170ce0
A
1425 control,
1426 file_start + cur_offset,
1427 TRUE, /* copy */
1428 initprot, maxprot,
1429 VM_INHERIT_DEFAULT);
1430 } else {
1431 ret = vm_map_enter_mem_object(
1432 map,
1433 &cur_start,
1434 cur_end - cur_start,
1435 (mach_vm_offset_t)0,
5ba3f43e
A
1436 VM_FLAGS_FIXED,
1437 cur_vmk_flags,
1438 VM_KERN_MEMORY_NONE,
3e170ce0
A
1439 IPC_PORT_NULL,
1440 0, /* offset */
1441 TRUE, /* copy */
1442 initprot, maxprot,
1443 VM_INHERIT_DEFAULT);
1444 }
1445 if (ret != KERN_SUCCESS) {
1446 return (LOAD_NOSPACE);
1447 }
1448 cur_offset += cur_end - cur_start;
1449 }
1450 if (cur_end >= vm_start + (file_end - file_start)) {
1451 /* all mapped: done */
1452 goto done;
1453 }
1454 cur_start = cur_end;
5ba3f43e
A
1455#if __arm64__
1456 if (!vm_map_page_aligned(vm_start + (file_end - file_start),
1457 effective_page_mask)) {
1458 /* one 4K pager for the last page */
1459 cur_end = vm_start + (file_end - file_start);
1460 if (control != MEMORY_OBJECT_CONTROL_NULL) {
1461 ret = vm_map_enter_mem_object_control(
1462 map,
1463 &cur_start,
1464 cur_end - cur_start,
1465 (mach_vm_offset_t)0,
1466 VM_FLAGS_FIXED,
1467 vmk_flags,
1468 VM_KERN_MEMORY_NONE,
1469 control,
1470 file_start + cur_offset,
1471 TRUE, /* copy */
1472 initprot, maxprot,
1473 VM_INHERIT_DEFAULT);
1474 } else {
1475 ret = vm_map_enter_mem_object(
1476 map,
1477 &cur_start,
1478 cur_end - cur_start,
1479 (mach_vm_offset_t)0,
1480 VM_FLAGS_FIXED,
1481 vmk_flags,
1482 VM_KERN_MEMORY_NONE,
1483 IPC_PORT_NULL,
1484 0, /* offset */
1485 TRUE, /* copy */
1486 initprot, maxprot,
1487 VM_INHERIT_DEFAULT);
1488 }
1489 if (ret != KERN_SUCCESS) {
1490 return (LOAD_NOSPACE);
1491 }
1492 cur_offset += cur_end - cur_start;
1493 }
1494#endif /* __arm64__ */
3e170ce0
A
1495done:
1496 assert(cur_end >= vm_start + (file_end - file_start));
1497 return LOAD_SUCCESS;
1498}
1499
1c79356b
A
1500static
1501load_return_t
b0d623f7 1502load_segment(
3e170ce0
A
1503 struct load_command *lcp,
1504 uint32_t filetype,
1505 void * control,
1506 off_t pager_offset,
1507 off_t macho_size,
1508 struct vnode *vp,
1509 vm_map_t map,
1510 int64_t slide,
1511 load_result_t *result)
1c79356b 1512{
b0d623f7 1513 struct segment_command_64 segment_command, *scp;
91447636 1514 kern_return_t ret;
3e170ce0 1515 vm_map_size_t delta_size;
91447636
A
1516 vm_prot_t initprot;
1517 vm_prot_t maxprot;
b0d623f7
A
1518 size_t segment_command_size, total_section_size,
1519 single_section_size;
3e170ce0
A
1520 vm_map_offset_t file_offset, file_size;
1521 vm_map_offset_t vm_offset, vm_size;
1522 vm_map_offset_t vm_start, vm_end, vm_end_aligned;
1523 vm_map_offset_t file_start, file_end;
1524 kern_return_t kr;
1525 boolean_t verbose;
1526 vm_map_size_t effective_page_size;
1527 vm_map_offset_t effective_page_mask;
5ba3f43e
A
1528#if __arm64__
1529 vm_map_kernel_flags_t vmk_flags;
1530 boolean_t fourk_align;
1531#endif /* __arm64__ */
3e170ce0
A
1532
1533 effective_page_size = MAX(PAGE_SIZE, vm_map_page_size(map));
1534 effective_page_mask = MAX(PAGE_MASK, vm_map_page_mask(map));
1535
1536 verbose = FALSE;
b0d623f7
A
1537 if (LC_SEGMENT_64 == lcp->cmd) {
1538 segment_command_size = sizeof(struct segment_command_64);
1539 single_section_size = sizeof(struct section_64);
5ba3f43e
A
1540#if __arm64__
1541 /* 64-bit binary: should already be 16K-aligned */
1542 fourk_align = FALSE;
1543#endif /* __arm64__ */
b0d623f7
A
1544 } else {
1545 segment_command_size = sizeof(struct segment_command);
1546 single_section_size = sizeof(struct section);
5ba3f43e
A
1547#if __arm64__
1548 /* 32-bit binary: might need 4K-alignment */
1549 if (effective_page_size != FOURK_PAGE_SIZE) {
1550 /* not using 4K page size: need fourk_pager */
1551 fourk_align = TRUE;
1552 verbose = TRUE;
1553 } else {
1554 /* using 4K page size: no need for re-alignment */
1555 fourk_align = FALSE;
1556 }
1557#endif /* __arm64__ */
b0d623f7
A
1558 }
1559 if (lcp->cmdsize < segment_command_size)
1560 return (LOAD_BADMACHO);
1561 total_section_size = lcp->cmdsize - segment_command_size;
1562
3e170ce0 1563 if (LC_SEGMENT_64 == lcp->cmd) {
6d2010ae 1564 scp = (struct segment_command_64 *)lcp;
3e170ce0 1565 } else {
6d2010ae
A
1566 scp = &segment_command;
1567 widen_segment_command((struct segment_command *)lcp, scp);
1568 }
1569
3e170ce0
A
1570 if (verbose) {
1571 MACHO_PRINTF(("+++ load_segment %s "
1572 "vm[0x%llx:0x%llx] file[0x%llx:0x%llx] "
1573 "prot %d/%d flags 0x%x\n",
1574 scp->segname,
1575 (uint64_t)(slide + scp->vmaddr),
1576 (uint64_t)(slide + scp->vmaddr + scp->vmsize),
1577 pager_offset + scp->fileoff,
1578 pager_offset + scp->fileoff + scp->filesize,
1579 scp->initprot,
1580 scp->maxprot,
1581 scp->flags));
1582 }
1583
91447636
A
1584 /*
1585 * Make sure what we get from the file is really ours (as specified
1586 * by macho_size).
1587 */
b0d623f7 1588 if (scp->fileoff + scp->filesize < scp->fileoff ||
3e170ce0 1589 scp->fileoff + scp->filesize > (uint64_t)macho_size) {
b0d623f7 1590 return (LOAD_BADMACHO);
3e170ce0 1591 }
b0d623f7
A
1592 /*
1593 * Ensure that the number of sections specified would fit
1594 * within the load command size.
1595 */
3e170ce0 1596 if (total_section_size / single_section_size < scp->nsects) {
91447636 1597 return (LOAD_BADMACHO);
3e170ce0 1598 }
2d21ac55
A
1599 /*
1600 * Make sure the segment is page-aligned in the file.
1601 */
3e170ce0
A
1602 file_offset = pager_offset + scp->fileoff; /* limited to 32 bits */
1603 file_size = scp->filesize;
5ba3f43e
A
1604#if __arm64__
1605 if (fourk_align) {
1606 if ((file_offset & FOURK_PAGE_MASK) != 0) {
1607 /*
1608 * we can't mmap() it if it's not at least 4KB-aligned
1609 * in the file
1610 */
1611 return LOAD_BADMACHO;
1612 }
1613 } else
1614#endif /* __arm64__ */
3e170ce0
A
1615 if ((file_offset & PAGE_MASK_64) != 0 ||
1616 /* we can't mmap() it if it's not page-aligned in the file */
1617 (file_offset & vm_map_page_mask(map)) != 0) {
1618 /*
1619 * The 1st test would have failed if the system's page size
1620 * was what this process believe is the page size, so let's
1621 * fail here too for the sake of consistency.
1622 */
b0d623f7 1623 return (LOAD_BADMACHO);
3e170ce0 1624 }
91447636 1625
04b8595b
A
1626 /*
1627 * If we have a code signature attached for this slice
1628 * require that the segments are within the signed part
1629 * of the file.
1630 */
1631 if (result->cs_end_offset &&
1632 result->cs_end_offset < (off_t)scp->fileoff &&
1633 result->cs_end_offset - scp->fileoff < scp->filesize)
1634 {
1635 if (cs_debug)
1636 printf("section outside code signature\n");
1637 return LOAD_BADMACHO;
1638 }
1639
3e170ce0
A
1640 vm_offset = scp->vmaddr + slide;
1641 vm_size = scp->vmsize;
1642
1643 if (vm_size == 0)
1644 return (LOAD_SUCCESS);
1645 if (scp->vmaddr == 0 &&
1646 file_size == 0 &&
1647 vm_size != 0 &&
b0d623f7
A
1648 (scp->initprot & VM_PROT_ALL) == VM_PROT_NONE &&
1649 (scp->maxprot & VM_PROT_ALL) == VM_PROT_NONE) {
0c530ab8 1650 /*
6d2010ae
A
1651 * For PIE, extend page zero rather than moving it. Extending
1652 * page zero keeps early allocations from falling predictably
1653 * between the end of page zero and the beginning of the first
1654 * slid segment.
0c530ab8 1655 */
fe8ab488
A
1656 /*
1657 * This is a "page zero" segment: it starts at address 0,
1658 * is not mapped from the binary file and is not accessible.
1659 * User-space should never be able to access that memory, so
1660 * make it completely off limits by raising the VM map's
1661 * minimum offset.
1662 */
3e170ce0
A
1663 vm_end = vm_offset + vm_size;
1664 if (vm_end < vm_offset) {
1665 return (LOAD_BADMACHO);
1666 }
1667 if (verbose) {
1668 MACHO_PRINTF(("++++++ load_segment: "
1669 "page_zero up to 0x%llx\n",
1670 (uint64_t) vm_end));
1671 }
5ba3f43e
A
1672#if __arm64__
1673 if (fourk_align) {
1674 /* raise min_offset as much as page-alignment allows */
1675 vm_end_aligned = vm_map_trunc_page(vm_end,
1676 effective_page_mask);
1677 } else
1678#endif /* __arm64__ */
3e170ce0
A
1679 {
1680 vm_end = vm_map_round_page(vm_end,
1681 PAGE_MASK_64);
1682 vm_end_aligned = vm_end;
1683 }
1684 ret = vm_map_raise_min_offset(map,
1685 vm_end_aligned);
5ba3f43e
A
1686#if __arm64__
1687 if (ret == 0 &&
1688 vm_end > vm_end_aligned) {
1689 /* use fourk_pager to map the rest of pagezero */
1690 assert(fourk_align);
1691 vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
1692 vmk_flags.vmkf_fourk = TRUE;
1693 ret = vm_map_enter_mem_object(
1694 map,
1695 &vm_end_aligned,
1696 vm_end - vm_end_aligned,
1697 (mach_vm_offset_t) 0, /* mask */
1698 VM_FLAGS_FIXED,
1699 vmk_flags,
1700 VM_KERN_MEMORY_NONE,
1701 IPC_PORT_NULL,
1702 0,
1703 FALSE, /* copy */
1704 (scp->initprot & VM_PROT_ALL),
1705 (scp->maxprot & VM_PROT_ALL),
1706 VM_INHERIT_DEFAULT);
1707 }
1708#endif /* __arm64__ */
3e170ce0 1709
fe8ab488
A
1710 if (ret != KERN_SUCCESS) {
1711 return (LOAD_FAILURE);
0c530ab8 1712 }
fe8ab488 1713 return (LOAD_SUCCESS);
3e170ce0 1714 } else {
5ba3f43e
A
1715#if CONFIG_EMBEDDED
1716 /* not PAGEZERO: should not be mapped at address 0 */
1717 if (filetype != MH_DYLINKER && scp->vmaddr == 0) {
1718 return LOAD_BADMACHO;
1719 }
1720#endif /* CONFIG_EMBEDDED */
0c530ab8
A
1721 }
1722
5ba3f43e
A
1723#if __arm64__
1724 if (fourk_align) {
1725 /* 4K-align */
1726 file_start = vm_map_trunc_page(file_offset,
1727 FOURK_PAGE_MASK);
1728 file_end = vm_map_round_page(file_offset + file_size,
1729 FOURK_PAGE_MASK);
1730 vm_start = vm_map_trunc_page(vm_offset,
1731 FOURK_PAGE_MASK);
1732 vm_end = vm_map_round_page(vm_offset + vm_size,
1733 FOURK_PAGE_MASK);
1734 if (!strncmp(scp->segname, "__LINKEDIT", 11) &&
1735 page_aligned(file_start) &&
1736 vm_map_page_aligned(file_start, vm_map_page_mask(map)) &&
1737 page_aligned(vm_start) &&
1738 vm_map_page_aligned(vm_start, vm_map_page_mask(map))) {
1739 /* XXX last segment: ignore mis-aligned tail */
1740 file_end = vm_map_round_page(file_end,
1741 effective_page_mask);
1742 vm_end = vm_map_round_page(vm_end,
1743 effective_page_mask);
1744 }
1745 } else
1746#endif /* __arm64__ */
3e170ce0
A
1747 {
1748 file_start = vm_map_trunc_page(file_offset,
1749 effective_page_mask);
1750 file_end = vm_map_round_page(file_offset + file_size,
1751 effective_page_mask);
1752 vm_start = vm_map_trunc_page(vm_offset,
1753 effective_page_mask);
1754 vm_end = vm_map_round_page(vm_offset + vm_size,
1755 effective_page_mask);
1756 }
6d2010ae 1757
3e170ce0
A
1758 if (vm_start < result->min_vm_addr)
1759 result->min_vm_addr = vm_start;
1760 if (vm_end > result->max_vm_addr)
1761 result->max_vm_addr = vm_end;
6d2010ae
A
1762
1763 if (map == VM_MAP_NULL)
1764 return (LOAD_SUCCESS);
1765
3e170ce0 1766 if (vm_size > 0) {
b0d623f7
A
1767 initprot = (scp->initprot) & VM_PROT_ALL;
1768 maxprot = (scp->maxprot) & VM_PROT_ALL;
91447636
A
1769 /*
1770 * Map a copy of the file into the address space.
1771 */
3e170ce0
A
1772 if (verbose) {
1773 MACHO_PRINTF(("++++++ load_segment: "
1774 "mapping at vm [0x%llx:0x%llx] of "
1775 "file [0x%llx:0x%llx]\n",
1776 (uint64_t) vm_start,
1777 (uint64_t) vm_end,
1778 (uint64_t) file_start,
1779 (uint64_t) file_end));
39236c6e 1780 }
3e170ce0
A
1781 ret = map_segment(map,
1782 vm_start,
1783 vm_end,
1784 control,
1785 file_start,
1786 file_end,
1787 initprot,
1788 maxprot);
1789 if (ret) {
1790 return LOAD_NOSPACE;
1791 }
1792
1793#if FIXME
91447636
A
1794 /*
1795 * If the file didn't end on a page boundary,
1796 * we need to zero the leftover.
1797 */
b0d623f7 1798 delta_size = map_size - scp->filesize;
91447636
A
1799 if (delta_size > 0) {
1800 mach_vm_offset_t tmp;
1801
5ba3f43e 1802 ret = mach_vm_allocate_kernel(kernel_map, &tmp, delta_size, VM_FLAGS_ANYWHERE, VM_KERN_MEMORY_BSD);
3e170ce0 1803 if (ret != KERN_SUCCESS) {
91447636 1804 return(LOAD_RESOURCE);
3e170ce0 1805 }
91447636 1806
b0d623f7 1807 if (copyout(tmp, map_addr + scp->filesize,
91447636 1808 delta_size)) {
b0d623f7 1809 (void) mach_vm_deallocate(
91447636 1810 kernel_map, tmp, delta_size);
2d21ac55 1811 return (LOAD_FAILURE);
91447636 1812 }
1c79356b 1813
b0d623f7 1814 (void) mach_vm_deallocate(kernel_map, tmp, delta_size);
91447636
A
1815 }
1816#endif /* FIXME */
1817 }
1c79356b 1818
91447636
A
1819 /*
1820 * If the virtual size of the segment is greater
1821 * than the size from the file, we need to allocate
1822 * zero fill memory for the rest.
1823 */
3e170ce0
A
1824 if ((vm_end - vm_start) > (file_end - file_start)) {
1825 delta_size = (vm_end - vm_start) - (file_end - file_start);
1826 } else {
1827 delta_size = 0;
1828 }
91447636 1829 if (delta_size > 0) {
3e170ce0
A
1830 mach_vm_offset_t tmp;
1831
1832 tmp = vm_start + (file_end - file_start);
1833 if (verbose) {
1834 MACHO_PRINTF(("++++++ load_segment: "
1835 "delta mapping vm [0x%llx:0x%llx]\n",
1836 (uint64_t) tmp,
1837 (uint64_t) (tmp + delta_size)));
1838 }
1839 kr = map_segment(map,
1840 tmp,
1841 tmp + delta_size,
1842 MEMORY_OBJECT_CONTROL_NULL,
1843 0,
1844 delta_size,
1845 scp->initprot,
1846 scp->maxprot);
1847 if (kr != KERN_SUCCESS) {
91447636 1848 return(LOAD_NOSPACE);
3e170ce0 1849 }
91447636 1850 }
1c79356b 1851
b0d623f7 1852 if ( (scp->fileoff == 0) && (scp->filesize != 0) )
3e170ce0 1853 result->mach_header = vm_offset;
0c530ab8 1854
b0d623f7 1855 if (scp->flags & SG_PROTECTED_VERSION_1) {
3e170ce0
A
1856 ret = unprotect_dsmos_segment(file_start,
1857 file_end - file_start,
1858 vp,
1859 pager_offset,
1860 map,
1861 vm_start,
1862 vm_end - vm_start);
1863 if (ret != LOAD_SUCCESS) {
1864 return ret;
1865 }
0c530ab8
A
1866 } else {
1867 ret = LOAD_SUCCESS;
1868 }
3e170ce0
A
1869
1870 if (LOAD_SUCCESS == ret &&
1871 filetype == MH_DYLINKER &&
1872 result->all_image_info_addr == MACH_VM_MIN_ADDRESS) {
b0d623f7 1873 note_all_image_info_section(scp,
3e170ce0
A
1874 LC_SEGMENT_64 == lcp->cmd,
1875 single_section_size,
1876 ((const char *)lcp +
1877 segment_command_size),
1878 slide,
1879 result);
1880 }
1c79356b 1881
c18c124e 1882 if (result->entry_point != MACH_VM_MIN_ADDRESS) {
3e170ce0 1883 if ((result->entry_point >= vm_offset) && (result->entry_point < (vm_offset + vm_size))) {
c18c124e
A
1884 if ((scp->initprot & (VM_PROT_READ|VM_PROT_EXECUTE)) == (VM_PROT_READ|VM_PROT_EXECUTE)) {
1885 result->validentry = 1;
1886 } else {
1887 /* right range but wrong protections, unset if previously validated */
1888 result->validentry = 0;
1889 }
1890 }
1891 }
0b4e3aa0 1892
6d2010ae 1893 return ret;
1c79356b
A
1894}
1895
39236c6e
A
1896static
1897load_return_t
1898load_uuid(
1899 struct uuid_command *uulp,
1900 char *command_end,
1901 load_result_t *result
1902)
1903{
1904 /*
1905 * We need to check the following for this command:
1906 * - The command size should be atleast the size of struct uuid_command
1907 * - The UUID part of the command should be completely within the mach-o header
1908 */
316670eb 1909
39236c6e
A
1910 if ((uulp->cmdsize < sizeof(struct uuid_command)) ||
1911 (((char *)uulp + sizeof(struct uuid_command)) > command_end)) {
1912 return (LOAD_BADMACHO);
1913 }
1914
1915 memcpy(&result->uuid[0], &uulp->uuid[0], sizeof(result->uuid));
1916 return (LOAD_SUCCESS);
1917}
316670eb
A
1918
1919static
1920load_return_t
1921load_main(
1922 struct entry_point_command *epc,
1923 thread_t thread,
1924 int64_t slide,
1925 load_result_t *result
1926)
1927{
1928 mach_vm_offset_t addr;
1929 kern_return_t ret;
1930
1931 if (epc->cmdsize < sizeof(*epc))
1932 return (LOAD_BADMACHO);
1933 if (result->thread_count != 0) {
316670eb
A
1934 return (LOAD_FAILURE);
1935 }
1936
1937 if (thread == THREAD_NULL)
1938 return (LOAD_SUCCESS);
1939
39037602
A
1940 /*
1941 * LC_MAIN specifies stack size but not location.
1942 * Add guard page to allocation size (MAXSSIZ includes guard page).
1943 */
316670eb 1944 if (epc->stacksize) {
39037602
A
1945 if (os_add_overflow(epc->stacksize, 4*PAGE_SIZE, &result->user_stack_size)) {
1946 /*
1947 * We are going to immediately throw away this result, but we want
1948 * to make sure we aren't loading a dangerously close to
1949 * overflowing value, since this will have a guard page added to it
1950 * and be rounded to page boundaries
1951 */
1952 return LOAD_BADMACHO;
1953 }
316670eb 1954 result->user_stack_size = epc->stacksize;
39037602
A
1955 if (os_add_overflow(epc->stacksize, PAGE_SIZE, &result->user_stack_alloc_size)) {
1956 return LOAD_BADMACHO;
1957 }
316670eb 1958 } else {
39037602 1959 result->user_stack_alloc_size = MAXSSIZ;
316670eb 1960 }
316670eb
A
1961
1962 /* use default location for stack */
39037602 1963 ret = thread_userstackdefault(&addr, result->is64bit);
316670eb
A
1964 if (ret != KERN_SUCCESS)
1965 return(LOAD_FAILURE);
1966
1967 /* The stack slides down from the default location */
1968 result->user_stack = addr;
1969 result->user_stack -= slide;
1970
c18c124e
A
1971 if (result->using_lcmain || result->entry_point != MACH_VM_MIN_ADDRESS) {
1972 /* Already processed LC_MAIN or LC_UNIXTHREAD */
1973 return (LOAD_FAILURE);
1974 }
1975
316670eb
A
1976 /* kernel does *not* use entryoff from LC_MAIN. Dyld uses it. */
1977 result->needs_dynlinker = TRUE;
c18c124e 1978 result->using_lcmain = TRUE;
39037602
A
1979
1980 ret = thread_state_initialize( thread );
1981 if (ret != KERN_SUCCESS) {
1982 return(LOAD_FAILURE);
1983 }
1984
316670eb
A
1985 result->unixproc = TRUE;
1986 result->thread_count++;
1987
1988 return(LOAD_SUCCESS);
1989}
1990
1991
91447636
A
1992static
1993load_return_t
1994load_unixthread(
1995 struct thread_command *tcp,
1996 thread_t thread,
6d2010ae 1997 int64_t slide,
91447636
A
1998 load_result_t *result
1999)
2000{
2001 load_return_t ret;
2002 int customstack =0;
316670eb 2003 mach_vm_offset_t addr;
91447636 2004
b0d623f7
A
2005 if (tcp->cmdsize < sizeof(*tcp))
2006 return (LOAD_BADMACHO);
2d21ac55 2007 if (result->thread_count != 0) {
91447636 2008 return (LOAD_FAILURE);
2d21ac55 2009 }
6d2010ae
A
2010
2011 if (thread == THREAD_NULL)
2012 return (LOAD_SUCCESS);
91447636
A
2013
2014 ret = load_threadstack(thread,
b0d623f7 2015 (uint32_t *)(((vm_offset_t)tcp) +
91447636
A
2016 sizeof(struct thread_command)),
2017 tcp->cmdsize - sizeof(struct thread_command),
39037602 2018 &addr, &customstack, result);
91447636
A
2019 if (ret != LOAD_SUCCESS)
2020 return(ret);
2021
316670eb
A
2022 /* LC_UNIXTHREAD optionally specifies stack size and location */
2023
39037602
A
2024 if (!customstack) {
2025 result->user_stack_alloc_size = MAXSSIZ;
316670eb 2026 }
6d2010ae 2027
316670eb
A
2028 /* The stack slides down from the default location */
2029 result->user_stack = addr;
2030 result->user_stack -= slide;
6d2010ae 2031
91447636 2032 ret = load_threadentry(thread,
b0d623f7 2033 (uint32_t *)(((vm_offset_t)tcp) +
91447636
A
2034 sizeof(struct thread_command)),
2035 tcp->cmdsize - sizeof(struct thread_command),
316670eb 2036 &addr);
91447636
A
2037 if (ret != LOAD_SUCCESS)
2038 return(ret);
2039
c18c124e
A
2040 if (result->using_lcmain || result->entry_point != MACH_VM_MIN_ADDRESS) {
2041 /* Already processed LC_MAIN or LC_UNIXTHREAD */
2042 return (LOAD_FAILURE);
2043 }
2044
316670eb 2045 result->entry_point = addr;
6d2010ae
A
2046 result->entry_point += slide;
2047
91447636 2048 ret = load_threadstate(thread,
490019cf
A
2049 (uint32_t *)(((vm_offset_t)tcp) + sizeof(struct thread_command)),
2050 tcp->cmdsize - sizeof(struct thread_command),
2051 result);
91447636
A
2052 if (ret != LOAD_SUCCESS)
2053 return (ret);
2054
2055 result->unixproc = TRUE;
2056 result->thread_count++;
2057
2058 return(LOAD_SUCCESS);
2059}
2060
1c79356b
A
2061static
2062load_return_t
2063load_threadstate(
2064 thread_t thread,
b0d623f7 2065 uint32_t *ts,
490019cf
A
2066 uint32_t total_size,
2067 load_result_t *result
1c79356b
A
2068)
2069{
b0d623f7 2070 uint32_t size;
1c79356b 2071 int flavor;
b0d623f7 2072 uint32_t thread_size;
490019cf
A
2073 uint32_t *local_ts = NULL;
2074 uint32_t local_ts_size = 0;
2075 int ret;
1c79356b 2076
490019cf 2077 (void)thread;
04b8595b 2078
04b8595b
A
2079 if (total_size > 0) {
2080 local_ts_size = total_size;
2081 local_ts = kalloc(local_ts_size);
2082 if (local_ts == NULL) {
490019cf 2083 return LOAD_FAILURE;
04b8595b
A
2084 }
2085 memcpy(local_ts, ts, local_ts_size);
2086 ts = local_ts;
2087 }
2088
1c79356b 2089 /*
490019cf
A
2090 * Validate the new thread state; iterate through the state flavors in
2091 * the Mach-O file.
2092 * XXX: we should validate the machine state here, to avoid failing at
2093 * activation time where we can't bail out cleanly.
1c79356b 2094 */
1c79356b
A
2095 while (total_size > 0) {
2096 flavor = *ts++;
2097 size = *ts++;
490019cf 2098
39037602 2099 if (os_add_and_mul_overflow(size, 2, sizeof(uint32_t), &thread_size) ||
490019cf 2100 os_sub_overflow(total_size, thread_size, &total_size)) {
04b8595b 2101 ret = LOAD_BADMACHO;
490019cf 2102 goto bad;
2d21ac55 2103 }
490019cf 2104
b0d623f7 2105 ts += size; /* ts is a (uint32_t *) */
1c79356b 2106 }
04b8595b 2107
490019cf
A
2108 result->threadstate = local_ts;
2109 result->threadstate_sz = local_ts_size;
2110 return LOAD_SUCCESS;
2111
2112bad:
2113 if (local_ts) {
04b8595b 2114 kfree(local_ts, local_ts_size);
04b8595b
A
2115 }
2116 return ret;
1c79356b
A
2117}
2118
2119static
2120load_return_t
2121load_threadstack(
39037602
A
2122 thread_t thread,
2123 uint32_t *ts,
2124 uint32_t total_size,
6d2010ae 2125 mach_vm_offset_t *user_stack,
39037602
A
2126 int *customstack,
2127 load_result_t *result
1c79356b
A
2128)
2129{
2130 kern_return_t ret;
b0d623f7 2131 uint32_t size;
1c79356b 2132 int flavor;
b0d623f7 2133 uint32_t stack_size;
1c79356b 2134
1c79356b
A
2135 while (total_size > 0) {
2136 flavor = *ts++;
2137 size = *ts++;
b0d623f7
A
2138 if (UINT32_MAX-2 < size ||
2139 UINT32_MAX/sizeof(uint32_t) < size+2)
2140 return (LOAD_BADMACHO);
2141 stack_size = (size+2)*sizeof(uint32_t);
91447636 2142 if (stack_size > total_size)
1c79356b 2143 return(LOAD_BADMACHO);
91447636
A
2144 total_size -= stack_size;
2145
2146 /*
2147 * Third argument is a kernel space pointer; it gets cast
2148 * to the appropriate type in thread_userstack() based on
2149 * the value of flavor.
2150 */
39037602 2151 ret = thread_userstack(thread, flavor, (thread_state_t)ts, size, user_stack, customstack, result->is64bit);
2d21ac55 2152 if (ret != KERN_SUCCESS) {
1c79356b 2153 return(LOAD_FAILURE);
2d21ac55 2154 }
b0d623f7 2155 ts += size; /* ts is a (uint32_t *) */
1c79356b
A
2156 }
2157 return(LOAD_SUCCESS);
2158}
2159
2160static
2161load_return_t
2162load_threadentry(
2163 thread_t thread,
b0d623f7
A
2164 uint32_t *ts,
2165 uint32_t total_size,
91447636 2166 mach_vm_offset_t *entry_point
1c79356b
A
2167)
2168{
2169 kern_return_t ret;
b0d623f7 2170 uint32_t size;
1c79356b 2171 int flavor;
b0d623f7 2172 uint32_t entry_size;
1c79356b
A
2173
2174 /*
2175 * Set the thread state.
2176 */
91447636 2177 *entry_point = MACH_VM_MIN_ADDRESS;
1c79356b
A
2178 while (total_size > 0) {
2179 flavor = *ts++;
2180 size = *ts++;
b0d623f7
A
2181 if (UINT32_MAX-2 < size ||
2182 UINT32_MAX/sizeof(uint32_t) < size+2)
2183 return (LOAD_BADMACHO);
2184 entry_size = (size+2)*sizeof(uint32_t);
91447636 2185 if (entry_size > total_size)
1c79356b 2186 return(LOAD_BADMACHO);
91447636
A
2187 total_size -= entry_size;
2188 /*
2189 * Third argument is a kernel space pointer; it gets cast
2190 * to the appropriate type in thread_entrypoint() based on
2191 * the value of flavor.
2192 */
2193 ret = thread_entrypoint(thread, flavor, (thread_state_t)ts, size, entry_point);
2d21ac55 2194 if (ret != KERN_SUCCESS) {
1c79356b 2195 return(LOAD_FAILURE);
2d21ac55 2196 }
b0d623f7 2197 ts += size; /* ts is a (uint32_t *) */
1c79356b
A
2198 }
2199 return(LOAD_SUCCESS);
2200}
2201
6d2010ae
A
2202struct macho_data {
2203 struct nameidata __nid;
2204 union macho_vnode_header {
2205 struct mach_header mach_header;
2206 struct fat_header fat_header;
2207 char __pad[512];
2208 } __header;
2209};
1c79356b 2210
c18c124e
A
2211#define DEFAULT_DYLD_PATH "/usr/lib/dyld"
2212
39037602
A
2213#if (DEVELOPMENT || DEBUG)
2214extern char dyld_alt_path[];
2215extern int use_alt_dyld;
2216#endif
2217
5ba3f43e
A
2218static uint64_t get_va_fsid(struct vnode_attr *vap)
2219{
2220 if (VATTR_IS_SUPPORTED(vap, va_fsid64)) {
2221 return *(uint64_t *)&vap->va_fsid64;
2222 } else {
2223 return vap->va_fsid;
2224 }
2225}
2226
6d2010ae 2227static load_return_t
1c79356b
A
2228load_dylinker(
2229 struct dylinker_command *lcp,
91447636 2230 integer_t archbits,
1c79356b 2231 vm_map_t map,
2d21ac55 2232 thread_t thread,
1c79356b 2233 int depth,
6d2010ae 2234 int64_t slide,
39037602
A
2235 load_result_t *result,
2236 struct image_params *imgp
1c79356b
A
2237)
2238{
5ba3f43e 2239 const char *name;
2d21ac55 2240 struct vnode *vp = NULLVP; /* set by get_macho_vnode() */
6d2010ae 2241 struct mach_header *header;
2d21ac55
A
2242 off_t file_offset = 0; /* set by get_macho_vnode() */
2243 off_t macho_size = 0; /* set by get_macho_vnode() */
6d2010ae 2244 load_result_t *myresult;
1c79356b 2245 kern_return_t ret;
6d2010ae
A
2246 struct macho_data *macho_data;
2247 struct {
2248 struct mach_header __header;
2249 load_result_t __myresult;
2250 struct macho_data __macho_data;
2251 } *dyld_data;
1c79356b 2252
5ba3f43e
A
2253 if (lcp->cmdsize < sizeof(*lcp) || lcp->name.offset >= lcp->cmdsize)
2254 return LOAD_BADMACHO;
b0d623f7 2255
5ba3f43e 2256 name = (const char *)lcp + lcp->name.offset;
39037602 2257
5ba3f43e
A
2258 /* Check for a proper null terminated string. */
2259 size_t maxsz = lcp->cmdsize - lcp->name.offset;
2260 size_t namelen = strnlen(name, maxsz);
2261 if (namelen >= maxsz) {
2262 return LOAD_BADMACHO;
2263 }
1c79356b 2264
39037602
A
2265#if (DEVELOPMENT || DEBUG)
2266
2267 /*
2268 * rdar://23680808
2269 * If an alternate dyld has been specified via boot args, check
2270 * to see if PROC_UUID_ALT_DYLD_POLICY has been set on this
2271 * executable and redirect the kernel to load that linker.
2272 */
2273
2274 if (use_alt_dyld) {
2275 int policy_error;
2276 uint32_t policy_flags = 0;
2277 int32_t policy_gencount = 0;
2278
2279 policy_error = proc_uuid_policy_lookup(result->uuid, &policy_flags, &policy_gencount);
2280 if (policy_error == 0) {
2281 if (policy_flags & PROC_UUID_ALT_DYLD_POLICY) {
2282 name = dyld_alt_path;
2283 }
2284 }
2285 }
2286#endif
2287
c18c124e
A
2288#if !(DEVELOPMENT || DEBUG)
2289 if (0 != strcmp(name, DEFAULT_DYLD_PATH)) {
2290 return (LOAD_BADMACHO);
2291 }
2292#endif
2293
6d2010ae
A
2294 /* Allocate wad-of-data from heap to reduce excessively deep stacks */
2295
2296 MALLOC(dyld_data, void *, sizeof (*dyld_data), M_TEMP, M_WAITOK);
2297 header = &dyld_data->__header;
2298 myresult = &dyld_data->__myresult;
2299 macho_data = &dyld_data->__macho_data;
2300
2301 ret = get_macho_vnode(name, archbits, header,
2302 &file_offset, &macho_size, macho_data, &vp);
1c79356b 2303 if (ret)
6d2010ae
A
2304 goto novp_out;
2305
2306 *myresult = load_result_null;
39037602 2307 myresult->is64bit = result->is64bit;
1c79356b 2308
6d2010ae 2309 ret = parse_machfile(vp, map, thread, header, file_offset,
39037602 2310 macho_size, depth, slide, 0, myresult, result, imgp);
6d2010ae 2311
490019cf
A
2312 if (ret == LOAD_SUCCESS) {
2313 if (result->threadstate) {
2314 /* don't use the app's threadstate if we have a dyld */
2315 kfree(result->threadstate, result->threadstate_sz);
2316 }
2317 result->threadstate = myresult->threadstate;
2318 result->threadstate_sz = myresult->threadstate_sz;
2319
1c79356b 2320 result->dynlinker = TRUE;
6d2010ae 2321 result->entry_point = myresult->entry_point;
316670eb 2322 result->validentry = myresult->validentry;
6d2010ae
A
2323 result->all_image_info_addr = myresult->all_image_info_addr;
2324 result->all_image_info_size = myresult->all_image_info_size;
fe8ab488
A
2325 if (myresult->platform_binary) {
2326 result->csflags |= CS_DYLD_PLATFORM;
2327 }
1c79356b 2328 }
39037602 2329
5ba3f43e
A
2330 struct vnode_attr va;
2331 VATTR_INIT(&va);
2332 VATTR_WANTED(&va, va_fsid64);
2333 VATTR_WANTED(&va, va_fsid);
2334 VATTR_WANTED(&va, va_fileid);
2335 int error = vnode_getattr(vp, &va, imgp->ip_vfs_context);
2336 if (error == 0) {
2337 imgp->ip_dyld_fsid = get_va_fsid(&va);
2338 imgp->ip_dyld_fsobjid = va.va_fileid;
2339 }
2340
91447636 2341 vnode_put(vp);
6d2010ae
A
2342novp_out:
2343 FREE(dyld_data, M_TEMP);
1c79356b
A
2344 return (ret);
2345
2346}
2347
6d2010ae 2348static load_return_t
2d21ac55
A
2349load_code_signature(
2350 struct linkedit_data_command *lcp,
2351 struct vnode *vp,
2352 off_t macho_offset,
2353 off_t macho_size,
2354 cpu_type_t cputype,
39037602
A
2355 load_result_t *result,
2356 struct image_params *imgp)
2d21ac55
A
2357{
2358 int ret;
2359 kern_return_t kr;
2360 vm_offset_t addr;
2361 int resid;
2362 struct cs_blob *blob;
2363 int error;
593a1d5f 2364 vm_size_t blob_size;
2d21ac55
A
2365
2366 addr = 0;
2367 blob = NULL;
2368
2369 if (lcp->cmdsize != sizeof (struct linkedit_data_command) ||
2370 lcp->dataoff + lcp->datasize > macho_size) {
2371 ret = LOAD_BADMACHO;
2372 goto out;
2373 }
2374
04b8595b 2375 blob = ubc_cs_blob_get(vp, cputype, macho_offset);
fe8ab488
A
2376 if (blob != NULL) {
2377 /* we already have a blob for this vnode and cputype */
2378 if (blob->csb_cpu_type == cputype &&
813fb2f6 2379 blob->csb_base_offset == macho_offset) {
fe8ab488
A
2380 /* it matches the blob we want here, lets verify the version */
2381 if(0 != ubc_cs_generation_check(vp)) {
39037602 2382 if (0 != ubc_cs_blob_revalidate(vp, blob, imgp, 0)) {
fe8ab488
A
2383 ret = LOAD_FAILURE; /* set error same as from ubc_cs_blob_add */
2384 goto out;
2385 }
2386 }
2387 ret = LOAD_SUCCESS;
2388 } else {
2389 /* the blob has changed for this vnode: fail ! */
2390 ret = LOAD_BADMACHO;
2391 }
2d21ac55
A
2392 goto out;
2393 }
2394
593a1d5f
A
2395 blob_size = lcp->datasize;
2396 kr = ubc_cs_blob_allocate(&addr, &blob_size);
2d21ac55
A
2397 if (kr != KERN_SUCCESS) {
2398 ret = LOAD_NOSPACE;
2399 goto out;
2400 }
2401
2402 resid = 0;
2403 error = vn_rdwr(UIO_READ,
2404 vp,
2405 (caddr_t) addr,
2406 lcp->datasize,
2407 macho_offset + lcp->dataoff,
b0d623f7 2408 UIO_SYSSPACE,
2d21ac55
A
2409 0,
2410 kauth_cred_get(),
2411 &resid,
2412 current_proc());
2413 if (error || resid != 0) {
2414 ret = LOAD_IOERROR;
2415 goto out;
2416 }
2417
2418 if (ubc_cs_blob_add(vp,
2419 cputype,
2420 macho_offset,
39037602 2421 &addr,
3e170ce0 2422 lcp->datasize,
39037602 2423 imgp,
3e170ce0
A
2424 0,
2425 &blob)) {
39037602
A
2426 if (addr) {
2427 ubc_cs_blob_deallocate(addr, blob_size);
2428 }
2d21ac55
A
2429 ret = LOAD_FAILURE;
2430 goto out;
2431 } else {
2432 /* ubc_cs_blob_add() has consumed "addr" */
2433 addr = 0;
2434 }
6d2010ae
A
2435
2436#if CHECK_CS_VALIDATION_BITMAP
2437 ubc_cs_validation_bitmap_allocate( vp );
2438#endif
2d21ac55 2439
2d21ac55
A
2440 ret = LOAD_SUCCESS;
2441out:
fe8ab488 2442 if (ret == LOAD_SUCCESS) {
3e170ce0 2443 if (blob == NULL)
5ba3f43e 2444 panic("success, but no blob!");
3e170ce0 2445
2d21ac55 2446 result->csflags |= blob->csb_flags;
fe8ab488 2447 result->platform_binary = blob->csb_platform_binary;
04b8595b 2448 result->cs_end_offset = blob->csb_end_offset;
2d21ac55
A
2449 }
2450 if (addr != 0) {
593a1d5f 2451 ubc_cs_blob_deallocate(addr, blob_size);
2d21ac55
A
2452 addr = 0;
2453 }
2454
2455 return ret;
2456}
2457
593a1d5f
A
2458
2459#if CONFIG_CODE_DECRYPTION
2460
2461static load_return_t
2462set_code_unprotect(
3e170ce0
A
2463 struct encryption_info_command *eip,
2464 caddr_t addr,
2465 vm_map_t map,
2466 int64_t slide,
2467 struct vnode *vp,
2468 off_t macho_offset,
2469 cpu_type_t cputype,
2470 cpu_subtype_t cpusubtype)
593a1d5f 2471{
3e170ce0 2472 int error, len;
593a1d5f
A
2473 pager_crypt_info_t crypt_info;
2474 const char * cryptname = 0;
6d2010ae 2475 char *vpath;
593a1d5f
A
2476
2477 size_t offset;
2478 struct segment_command_64 *seg64;
2479 struct segment_command *seg32;
2480 vm_map_offset_t map_offset, map_size;
3e170ce0 2481 vm_object_offset_t crypto_backing_offset;
593a1d5f 2482 kern_return_t kr;
b0d623f7 2483
6d2010ae 2484 if (eip->cmdsize < sizeof(*eip)) return LOAD_BADMACHO;
593a1d5f
A
2485
2486 switch(eip->cryptid) {
2487 case 0:
2488 /* not encrypted, just an empty load command */
2489 return LOAD_SUCCESS;
2490 case 1:
2491 cryptname="com.apple.unfree";
2492 break;
2493 case 0x10:
2494 /* some random cryptid that you could manually put into
2495 * your binary if you want NULL */
2496 cryptname="com.apple.null";
2497 break;
2498 default:
c910b4d9 2499 return LOAD_BADMACHO;
593a1d5f
A
2500 }
2501
6d2010ae
A
2502 if (map == VM_MAP_NULL) return (LOAD_SUCCESS);
2503 if (NULL == text_crypter_create) return LOAD_FAILURE;
2504
2505 MALLOC_ZONE(vpath, char *, MAXPATHLEN, M_NAMEI, M_WAITOK);
2506 if(vpath == NULL) return LOAD_FAILURE;
2507
593a1d5f 2508 len = MAXPATHLEN;
3e170ce0
A
2509 error = vn_getpath(vp, vpath, &len);
2510 if (error) {
6d2010ae
A
2511 FREE_ZONE(vpath, MAXPATHLEN, M_NAMEI);
2512 return LOAD_FAILURE;
2513 }
593a1d5f
A
2514
2515 /* set up decrypter first */
39236c6e
A
2516 crypt_file_data_t crypt_data = {
2517 .filename = vpath,
2518 .cputype = cputype,
2519 .cpusubtype = cpusubtype};
2520 kr=text_crypter_create(&crypt_info, cryptname, (void*)&crypt_data);
39037602
A
2521#if VM_MAP_DEBUG_APPLE_PROTECT
2522 if (vm_map_debug_apple_protect) {
2523 struct proc *p;
2524 p = current_proc();
2525 printf("APPLE_PROTECT: %d[%s] map %p %s(%s) -> 0x%x\n",
2526 p->p_pid, p->p_comm, map, __FUNCTION__, vpath, kr);
2527 }
2528#endif /* VM_MAP_DEBUG_APPLE_PROTECT */
6d2010ae 2529 FREE_ZONE(vpath, MAXPATHLEN, M_NAMEI);
593a1d5f
A
2530
2531 if(kr) {
c910b4d9 2532 printf("set_code_unprotect: unable to create decrypter %s, kr=%d\n",
593a1d5f 2533 cryptname, kr);
39236c6e
A
2534 if (kr == kIOReturnNotPrivileged) {
2535 /* text encryption returned decryption failure */
2536 return(LOAD_DECRYPTFAIL);
2537 }else
2538 return LOAD_RESOURCE;
593a1d5f
A
2539 }
2540
2541 /* this is terrible, but we have to rescan the load commands to find the
2542 * virtual address of this encrypted stuff. This code is gonna look like
2543 * the dyld source one day... */
2544 struct mach_header *header = (struct mach_header *)addr;
2545 size_t mach_header_sz = sizeof(struct mach_header);
2546 if (header->magic == MH_MAGIC_64 ||
2547 header->magic == MH_CIGAM_64) {
2548 mach_header_sz = sizeof(struct mach_header_64);
2549 }
2550 offset = mach_header_sz;
2551 uint32_t ncmds = header->ncmds;
2552 while (ncmds--) {
2553 /*
2554 * Get a pointer to the command.
2555 */
2556 struct load_command *lcp = (struct load_command *)(addr + offset);
2557 offset += lcp->cmdsize;
2558
2559 switch(lcp->cmd) {
2560 case LC_SEGMENT_64:
2561 seg64 = (struct segment_command_64 *)lcp;
2562 if ((seg64->fileoff <= eip->cryptoff) &&
2563 (seg64->fileoff+seg64->filesize >=
2564 eip->cryptoff+eip->cryptsize)) {
316670eb 2565 map_offset = seg64->vmaddr + eip->cryptoff - seg64->fileoff + slide;
593a1d5f 2566 map_size = eip->cryptsize;
3e170ce0 2567 crypto_backing_offset = macho_offset + eip->cryptoff;
593a1d5f
A
2568 goto remap_now;
2569 }
2570 case LC_SEGMENT:
2571 seg32 = (struct segment_command *)lcp;
2572 if ((seg32->fileoff <= eip->cryptoff) &&
2573 (seg32->fileoff+seg32->filesize >=
2574 eip->cryptoff+eip->cryptsize)) {
316670eb 2575 map_offset = seg32->vmaddr + eip->cryptoff - seg32->fileoff + slide;
593a1d5f 2576 map_size = eip->cryptsize;
3e170ce0 2577 crypto_backing_offset = macho_offset + eip->cryptoff;
593a1d5f
A
2578 goto remap_now;
2579 }
2580 }
2581 }
2582
2583 /* if we get here, did not find anything */
c910b4d9 2584 return LOAD_BADMACHO;
593a1d5f
A
2585
2586remap_now:
2587 /* now remap using the decrypter */
3e170ce0
A
2588 MACHO_PRINTF(("+++ set_code_unprotect: vm[0x%llx:0x%llx]\n",
2589 (uint64_t) map_offset,
2590 (uint64_t) (map_offset+map_size)));
2591 kr = vm_map_apple_protected(map,
2592 map_offset,
2593 map_offset+map_size,
2594 crypto_backing_offset,
2595 &crypt_info);
2596 if (kr) {
c910b4d9 2597 printf("set_code_unprotect(): mapping failed with %x\n", kr);
c910b4d9
A
2598 return LOAD_PROTECT;
2599 }
593a1d5f
A
2600
2601 return LOAD_SUCCESS;
2602}
2603
2604#endif
2605
91447636
A
2606/*
2607 * This routine exists to support the load_dylinker().
2608 *
2609 * This routine has its own, separate, understanding of the FAT file format,
2610 * which is terrifically unfortunate.
2611 */
1c79356b
A
2612static
2613load_return_t
2614get_macho_vnode(
5ba3f43e 2615 const char *path,
91447636 2616 integer_t archbits,
1c79356b 2617 struct mach_header *mach_header,
91447636
A
2618 off_t *file_offset,
2619 off_t *macho_size,
6d2010ae 2620 struct macho_data *data,
1c79356b
A
2621 struct vnode **vpp
2622)
2623{
2624 struct vnode *vp;
2d21ac55
A
2625 vfs_context_t ctx = vfs_context_current();
2626 proc_t p = vfs_context_proc(ctx);
2627 kauth_cred_t kerncred;
6d2010ae 2628 struct nameidata *ndp = &data->__nid;
1c79356b
A
2629 boolean_t is_fat;
2630 struct fat_arch fat_arch;
6d2010ae 2631 int error;
1c79356b 2632 int resid;
6d2010ae 2633 union macho_vnode_header *header = &data->__header;
0b4e3aa0 2634 off_t fsize = (off_t)0;
6d2010ae 2635
2d21ac55
A
2636 /*
2637 * Capture the kernel credential for use in the actual read of the
2638 * file, since the user doing the execution may have execute rights
2639 * but not read rights, but to exec something, we have to either map
2640 * or read it into the new process address space, which requires
2641 * read rights. This is to deal with lack of common credential
2642 * serialization code which would treat NOCRED as "serialize 'root'".
2643 */
2644 kerncred = vfs_context_ucred(vfs_context_kernel());
91447636 2645
1c79356b 2646 /* init the namei data to point the file user's program name */
6d2010ae 2647 NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW | LOCKLEAF, UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
1c79356b 2648
91447636 2649 if ((error = namei(ndp)) != 0) {
2d21ac55 2650 if (error == ENOENT) {
55e303ae 2651 error = LOAD_ENOENT;
2d21ac55 2652 } else {
55e303ae 2653 error = LOAD_FAILURE;
2d21ac55 2654 }
1c79356b 2655 return(error);
55e303ae 2656 }
91447636 2657 nameidone(ndp);
1c79356b 2658 vp = ndp->ni_vp;
6d2010ae 2659
1c79356b
A
2660 /* check for regular file */
2661 if (vp->v_type != VREG) {
55e303ae 2662 error = LOAD_PROTECT;
1c79356b
A
2663 goto bad1;
2664 }
2665
91447636 2666 /* get size */
2d21ac55 2667 if ((error = vnode_size(vp, &fsize, ctx)) != 0) {
55e303ae 2668 error = LOAD_FAILURE;
1c79356b 2669 goto bad1;
55e303ae 2670 }
1c79356b
A
2671
2672 /* Check mount point */
2673 if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
55e303ae 2674 error = LOAD_PROTECT;
1c79356b
A
2675 goto bad1;
2676 }
2677
91447636 2678 /* check access */
39236c6e 2679 if ((error = vnode_authorize(vp, NULL, KAUTH_VNODE_EXECUTE | KAUTH_VNODE_READ_DATA, ctx)) != 0) {
55e303ae 2680 error = LOAD_PROTECT;
1c79356b 2681 goto bad1;
55e303ae 2682 }
0b4e3aa0 2683
1c79356b 2684 /* try to open it */
2d21ac55 2685 if ((error = VNOP_OPEN(vp, FREAD, ctx)) != 0) {
55e303ae 2686 error = LOAD_PROTECT;
1c79356b 2687 goto bad1;
0b4e3aa0
A
2688 }
2689
6d2010ae 2690 if ((error = vn_rdwr(UIO_READ, vp, (caddr_t)header, sizeof (*header), 0,
b0d623f7 2691 UIO_SYSSPACE, IO_NODELOCKED, kerncred, &resid, p)) != 0) {
55e303ae 2692 error = LOAD_IOERROR;
1c79356b 2693 goto bad2;
55e303ae 2694 }
6d2010ae 2695
c18c124e
A
2696 if (resid) {
2697 error = LOAD_BADMACHO;
2698 goto bad2;
2699 }
2700
6d2010ae
A
2701 if (header->mach_header.magic == MH_MAGIC ||
2702 header->mach_header.magic == MH_MAGIC_64) {
2703 is_fat = FALSE;
c18c124e
A
2704 } else if (OSSwapBigToHostInt32(header->fat_header.magic) == FAT_MAGIC) {
2705 is_fat = TRUE;
6d2010ae
A
2706 } else {
2707 error = LOAD_BADMACHO;
2708 goto bad2;
1c79356b
A
2709 }
2710
2711 if (is_fat) {
c18c124e
A
2712
2713 error = fatfile_validate_fatarches((vm_offset_t)(&header->fat_header),
2714 sizeof(*header));
2715 if (error != LOAD_SUCCESS) {
2716 goto bad2;
2717 }
2718
0b4e3aa0 2719 /* Look up our architecture in the fat file. */
c18c124e
A
2720 error = fatfile_getarch_with_bits(archbits,
2721 (vm_offset_t)(&header->fat_header), sizeof(*header), &fat_arch);
0b4e3aa0 2722 if (error != LOAD_SUCCESS)
1c79356b 2723 goto bad2;
0b4e3aa0
A
2724
2725 /* Read the Mach-O header out of it */
6d2010ae
A
2726 error = vn_rdwr(UIO_READ, vp, (caddr_t)&header->mach_header,
2727 sizeof (header->mach_header), fat_arch.offset,
2728 UIO_SYSSPACE, IO_NODELOCKED, kerncred, &resid, p);
1c79356b 2729 if (error) {
55e303ae 2730 error = LOAD_IOERROR;
1c79356b
A
2731 goto bad2;
2732 }
2733
c18c124e
A
2734 if (resid) {
2735 error = LOAD_BADMACHO;
2736 goto bad2;
2737 }
2738
0b4e3aa0 2739 /* Is this really a Mach-O? */
6d2010ae
A
2740 if (header->mach_header.magic != MH_MAGIC &&
2741 header->mach_header.magic != MH_MAGIC_64) {
1c79356b
A
2742 error = LOAD_BADMACHO;
2743 goto bad2;
2744 }
0b4e3aa0 2745
1c79356b 2746 *file_offset = fat_arch.offset;
2d21ac55 2747 *macho_size = fat_arch.size;
1c79356b 2748 } else {
91447636
A
2749 /*
2750 * Force get_macho_vnode() to fail if the architecture bits
2751 * do not match the expected architecture bits. This in
2752 * turn causes load_dylinker() to fail for the same reason,
2753 * so it ensures the dynamic linker and the binary are in
2754 * lock-step. This is potentially bad, if we ever add to
2755 * the CPU_ARCH_* bits any bits that are desirable but not
2756 * required, since the dynamic linker might work, but we will
2757 * refuse to load it because of this check.
2758 */
6d2010ae
A
2759 if ((cpu_type_t)(header->mach_header.cputype & CPU_ARCH_MASK) != archbits) {
2760 error = LOAD_BADARCH;
2761 goto bad2;
2762 }
0b4e3aa0 2763
1c79356b 2764 *file_offset = 0;
91447636 2765 *macho_size = fsize;
1c79356b
A
2766 }
2767
6d2010ae 2768 *mach_header = header->mach_header;
0b4e3aa0 2769 *vpp = vp;
91447636
A
2770
2771 ubc_setsize(vp, fsize);
0b4e3aa0
A
2772 return (error);
2773
1c79356b 2774bad2:
6d2010ae 2775 (void) VNOP_CLOSE(vp, FREAD, ctx);
1c79356b 2776bad1:
91447636 2777 vnode_put(vp);
1c79356b
A
2778 return(error);
2779}