2 * Copyright (c) 2000-2013 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
30 * Mach Operating System
31 * Copyright (c) 1987 Carnegie-Mellon University
32 * All rights reserved. The CMU software License Agreement specifies
33 * the terms and conditions for use and redistribution.
37 * Copyright (c) 1982, 1986, 1991, 1993
38 * The Regents of the University of California. All rights reserved.
39 * (c) UNIX System Laboratories, Inc.
40 * All or some portions of this file are derived from material licensed
41 * to the University of California by American Telephone and Telegraph
42 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
43 * the permission of UNIX System Laboratories, Inc.
45 * Redistribution and use in source and binary forms, with or without
46 * modification, are permitted provided that the following conditions
48 * 1. Redistributions of source code must retain the above copyright
49 * notice, this list of conditions and the following disclaimer.
50 * 2. Redistributions in binary form must reproduce the above copyright
51 * notice, this list of conditions and the following disclaimer in the
52 * documentation and/or other materials provided with the distribution.
53 * 3. All advertising materials mentioning features or use of this software
54 * must display the following acknowledgement:
55 * This product includes software developed by the University of
56 * California, Berkeley and its contributors.
57 * 4. Neither the name of the University nor the names of its contributors
58 * may be used to endorse or promote products derived from this software
59 * without specific prior written permission.
61 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
62 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
63 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
65 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
66 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
67 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
68 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
69 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
70 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73 * from: @(#)kern_exec.c 8.1 (Berkeley) 6/10/93
76 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
77 * support for mandatory and extensible security protections. This notice
78 * is included in support of clause 2.2 (b) of the Apple Public License,
81 #include <machine/reg.h>
82 #include <machine/cpu_capabilities.h>
84 #include <sys/param.h>
85 #include <sys/systm.h>
86 #include <sys/filedesc.h>
87 #include <sys/kernel.h>
88 #include <sys/proc_internal.h>
89 #include <sys/kauth.h>
91 #include <sys/socketvar.h>
92 #include <sys/malloc.h>
93 #include <sys/namei.h>
94 #include <sys/mount_internal.h>
95 #include <sys/vnode_internal.h>
96 #include <sys/file_internal.h>
98 #include <sys/uio_internal.h>
100 #include <sys/exec.h>
101 #include <sys/kdebug.h>
102 #include <sys/signal.h>
103 #include <sys/aio_kern.h>
104 #include <sys/sysproto.h>
105 #include <sys/persona.h>
106 #include <sys/reason.h>
108 #include <sys/shm_internal.h> /* shmexec() */
110 #include <sys/ubc_internal.h> /* ubc_map() */
111 #include <sys/spawn.h>
112 #include <sys/spawn_internal.h>
113 #include <sys/process_policy.h>
114 #include <sys/codesign.h>
115 #include <sys/random.h>
116 #include <crypto/sha1.h>
118 #include <libkern/libkern.h>
120 #include <security/audit/audit.h>
122 #include <ipc/ipc_types.h>
124 #include <mach/mach_types.h>
125 #include <mach/port.h>
126 #include <mach/task.h>
127 #include <mach/task_access.h>
128 #include <mach/thread_act.h>
129 #include <mach/vm_map.h>
130 #include <mach/mach_vm.h>
131 #include <mach/vm_param.h>
133 #include <kern/sched_prim.h> /* thread_wakeup() */
134 #include <kern/affinity.h>
135 #include <kern/assert.h>
136 #include <kern/task.h>
137 #include <kern/coalition.h>
138 #include <kern/policy_internal.h>
139 #include <kern/kalloc.h>
142 #include <security/mac.h>
143 #include <security/mac_mach_internal.h>
146 #include <vm/vm_map.h>
147 #include <vm/vm_kern.h>
148 #include <vm/vm_protos.h>
149 #include <vm/vm_kern.h>
150 #include <vm/vm_fault.h>
151 #include <vm/vm_pageout.h>
153 #include <kdp/kdp_dyld.h>
155 #include <machine/pal_routines.h>
157 #include <pexpert/pexpert.h>
159 #if CONFIG_MEMORYSTATUS
160 #include <sys/kern_memorystatus.h>
164 /* Do not include dtrace.h, it redefines kmem_[alloc/free] */
165 extern void dtrace_proc_exec(proc_t
);
166 extern void (*dtrace_proc_waitfor_exec_ptr
)(proc_t
);
169 * Since dtrace_proc_waitfor_exec_ptr can be added/removed in dtrace_subr.c,
170 * we will store its value before actually calling it.
172 static void (*dtrace_proc_waitfor_hook
)(proc_t
) = NULL
;
174 #include <sys/dtrace_ptss.h>
177 /* support for child creation in exec after vfork */
178 thread_t
fork_create_child(task_t parent_task
, coalition_t
*parent_coalition
, proc_t child_proc
, int inherit_memory
, int is64bit
, int in_exec
);
179 void vfork_exit(proc_t p
, int rv
);
180 extern void proc_apply_task_networkbg_internal(proc_t
, thread_t
);
181 extern void task_set_did_exec_flag(task_t task
);
182 extern void task_clear_exec_copy_flag(task_t task
);
183 proc_t
proc_exec_switch_task(proc_t p
, task_t old_task
, task_t new_task
, thread_t new_thread
);
184 boolean_t
task_is_active(task_t
);
185 boolean_t
thread_is_active(thread_t thread
);
186 void thread_copy_resource_info(thread_t dst_thread
, thread_t src_thread
);
187 void *ipc_importance_exec_switch_task(task_t old_task
, task_t new_task
);
188 extern void ipc_importance_release(void *elem
);
191 * Mach things for which prototypes are unavailable from Mach headers
195 void ipc_thread_reset(
197 kern_return_t
ipc_object_copyin(
199 mach_port_name_t name
,
200 mach_msg_type_name_t msgt_name
,
201 ipc_object_t
*objectp
);
202 void ipc_port_release_send(ipc_port_t
);
204 #if DEVELOPMENT || DEBUG
205 void task_importance_update_owner_info(task_t
);
208 extern struct savearea
*get_user_regs(thread_t
);
210 __attribute__((noinline
)) int __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port
, int32_t new_pid
);
212 #include <kern/thread.h>
213 #include <kern/task.h>
214 #include <kern/ast.h>
215 #include <kern/mach_loader.h>
216 #include <kern/mach_fat.h>
217 #include <mach-o/fat.h>
218 #include <mach-o/loader.h>
219 #include <machine/vmparam.h>
220 #include <sys/imgact.h>
226 * EAI_ITERLIMIT The maximum number of times to iterate an image
227 * activator in exec_activate_image() before treating
228 * it as malformed/corrupt.
230 #define EAI_ITERLIMIT 3
233 * For #! interpreter parsing
235 #define IS_WHITESPACE(ch) ((ch == ' ') || (ch == '\t'))
236 #define IS_EOL(ch) ((ch == '#') || (ch == '\n'))
238 extern vm_map_t bsd_pageable_map
;
239 extern const struct fileops vnops
;
241 #define USER_ADDR_ALIGN(addr, val) \
242 ( ( (user_addr_t)(addr) + (val) - 1) \
245 struct image_params
; /* Forward */
246 static int exec_activate_image(struct image_params
*imgp
);
247 static int exec_copyout_strings(struct image_params
*imgp
, user_addr_t
*stackp
);
248 static int load_return_to_errno(load_return_t lrtn
);
249 static int execargs_alloc(struct image_params
*imgp
);
250 static int execargs_free(struct image_params
*imgp
);
251 static int exec_check_permissions(struct image_params
*imgp
);
252 static int exec_extract_strings(struct image_params
*imgp
);
253 static int exec_add_apple_strings(struct image_params
*imgp
, const load_result_t
*load_result
);
254 static int exec_handle_sugid(struct image_params
*imgp
);
255 static int sugid_scripts
= 0;
256 SYSCTL_INT (_kern
, OID_AUTO
, sugid_scripts
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &sugid_scripts
, 0, "");
257 static kern_return_t
create_unix_stack(vm_map_t map
, load_result_t
* load_result
, proc_t p
);
258 static int copyoutptr(user_addr_t ua
, user_addr_t ptr
, int ptr_size
);
259 static void exec_resettextvp(proc_t
, struct image_params
*);
260 static int check_for_signature(proc_t
, struct image_params
*);
261 static void exec_prefault_data(proc_t
, struct image_params
*, load_result_t
*);
262 static errno_t
exec_handle_port_actions(struct image_params
*imgp
, boolean_t
* portwatch_present
, ipc_port_t
* portwatch_ports
);
263 static errno_t
exec_handle_spawnattr_policy(proc_t p
, int psa_apptype
, uint64_t psa_qos_clamp
, uint64_t psa_darwin_role
,
264 ipc_port_t
* portwatch_ports
, int portwatch_count
);
267 * exec_add_user_string
269 * Add the requested string to the string space area.
271 * Parameters; struct image_params * image parameter block
272 * user_addr_t string to add to strings area
273 * int segment from which string comes
274 * boolean_t TRUE if string contributes to NCARGS
277 * !0 Failure errno from copyinstr()
280 * (imgp->ip_strendp) updated location of next add, if any
281 * (imgp->ip_strspace) updated byte count of space remaining
282 * (imgp->ip_argspace) updated byte count of space in NCARGS
285 exec_add_user_string(struct image_params
*imgp
, user_addr_t str
, int seg
, boolean_t is_ncargs
)
294 space
= imgp
->ip_argspace
; /* by definition smaller than ip_strspace */
296 space
= imgp
->ip_strspace
;
303 if (!UIO_SEG_IS_USER_SPACE(seg
)) {
304 char *kstr
= CAST_DOWN(char *,str
); /* SAFE */
305 error
= copystr(kstr
, imgp
->ip_strendp
, space
, &len
);
307 error
= copyinstr(str
, imgp
->ip_strendp
, space
, &len
);
310 imgp
->ip_strendp
+= len
;
311 imgp
->ip_strspace
-= len
;
313 imgp
->ip_argspace
-= len
;
315 } while (error
== ENAMETOOLONG
);
321 * dyld is now passed the executable path as a getenv-like variable
322 * in the same fashion as the stack_guard and malloc_entropy keys.
324 #define EXECUTABLE_KEY "executable_path="
329 * To support new app package launching for Mac OS X, the dyld needs the
330 * first argument to execve() stored on the user stack.
332 * Save the executable path name at the bottom of the strings area and set
333 * the argument vector pointer to the location following that to indicate
334 * the start of the argument and environment tuples, setting the remaining
335 * string space count to the size of the string area minus the path length.
337 * Parameters; struct image_params * image parameter block
338 * char * path used to invoke program
339 * int segment from which path comes
341 * Returns: int 0 Success
343 * copy[in]str:EFAULT Bad address
344 * copy[in]str:ENAMETOOLONG Filename too long
347 * (imgp->ip_strings) saved path
348 * (imgp->ip_strspace) space remaining in ip_strings
349 * (imgp->ip_strendp) start of remaining copy area
350 * (imgp->ip_argspace) space remaining of NCARGS
351 * (imgp->ip_applec) Initial applev[0]
353 * Note: We have to do this before the initial namei() since in the
354 * path contains symbolic links, namei() will overwrite the
355 * original path buffer contents. If the last symbolic link
356 * resolved was a relative pathname, we would lose the original
357 * "path", which could be an absolute pathname. This might be
358 * unacceptable for dyld.
361 exec_save_path(struct image_params
*imgp
, user_addr_t path
, int seg
, const char **excpath
)
367 // imgp->ip_strings can come out of a cache, so we need to obliterate the
369 memset(imgp
->ip_strings
, '\0', strlen(EXECUTABLE_KEY
) + MAXPATHLEN
);
371 len
= MIN(MAXPATHLEN
, imgp
->ip_strspace
);
374 case UIO_USERSPACE32
:
375 case UIO_USERSPACE64
: /* Same for copyin()... */
376 error
= copyinstr(path
, imgp
->ip_strings
+ strlen(EXECUTABLE_KEY
), len
, &len
);
379 kpath
= CAST_DOWN(char *,path
); /* SAFE */
380 error
= copystr(kpath
, imgp
->ip_strings
+ strlen(EXECUTABLE_KEY
), len
, &len
);
388 bcopy(EXECUTABLE_KEY
, imgp
->ip_strings
, strlen(EXECUTABLE_KEY
));
389 len
+= strlen(EXECUTABLE_KEY
);
391 imgp
->ip_strendp
+= len
;
392 imgp
->ip_strspace
-= len
;
395 *excpath
= imgp
->ip_strings
+ strlen(EXECUTABLE_KEY
);
403 * exec_reset_save_path
405 * If we detect a shell script, we need to reset the string area
406 * state so that the interpreter can be saved onto the stack.
408 * Parameters; struct image_params * image parameter block
410 * Returns: int 0 Success
413 * (imgp->ip_strings) saved path
414 * (imgp->ip_strspace) space remaining in ip_strings
415 * (imgp->ip_strendp) start of remaining copy area
416 * (imgp->ip_argspace) space remaining of NCARGS
420 exec_reset_save_path(struct image_params
*imgp
)
422 imgp
->ip_strendp
= imgp
->ip_strings
;
423 imgp
->ip_argspace
= NCARGS
;
424 imgp
->ip_strspace
= ( NCARGS
+ PAGE_SIZE
);
432 * Image activator for interpreter scripts. If the image begins with
433 * the characters "#!", then it is an interpreter script. Verify the
434 * length of the script line indicating the interpreter is not in
435 * excess of the maximum allowed size. If this is the case, then
436 * break out the arguments, if any, which are separated by white
437 * space, and copy them into the argument save area as if they were
438 * provided on the command line before all other arguments. The line
439 * ends when we encounter a comment character ('#') or newline.
441 * Parameters; struct image_params * image parameter block
443 * Returns: -1 not an interpreter (keep looking)
444 * -3 Success: interpreter: relookup
445 * >0 Failure: interpreter: error number
447 * A return value other than -1 indicates subsequent image activators should
448 * not be given the opportunity to attempt to activate the image.
451 exec_shell_imgact(struct image_params
*imgp
)
453 char *vdata
= imgp
->ip_vdata
;
455 char *line_startp
, *line_endp
;
463 * Make sure it's a shell script. If we've already redirected
464 * from an interpreted file once, don't do it again.
466 if (vdata
[0] != '#' ||
468 (imgp
->ip_flags
& IMGPF_INTERPRET
) != 0) {
472 if (imgp
->ip_origcputype
!= 0) {
473 /* Fat header previously matched, don't allow shell script inside */
477 imgp
->ip_flags
|= IMGPF_INTERPRET
;
478 imgp
->ip_interp_sugid_fd
= -1;
479 imgp
->ip_interp_buffer
[0] = '\0';
481 /* Check to see if SUGID scripts are permitted. If they aren't then
482 * clear the SUGID bits.
483 * imgp->ip_vattr is known to be valid.
485 if (sugid_scripts
== 0) {
486 imgp
->ip_origvattr
->va_mode
&= ~(VSUID
| VSGID
);
489 /* Try to find the first non-whitespace character */
490 for( ihp
= &vdata
[2]; ihp
< &vdata
[IMG_SHSIZE
]; ihp
++ ) {
492 /* Did not find interpreter, "#!\n" */
494 } else if (IS_WHITESPACE(*ihp
)) {
495 /* Whitespace, like "#! /bin/sh\n", keep going. */
497 /* Found start of interpreter */
502 if (ihp
== &vdata
[IMG_SHSIZE
]) {
503 /* All whitespace, like "#! " */
509 /* Try to find the end of the interpreter+args string */
510 for ( ; ihp
< &vdata
[IMG_SHSIZE
]; ihp
++ ) {
515 /* Still part of interpreter or args */
519 if (ihp
== &vdata
[IMG_SHSIZE
]) {
520 /* A long line, like "#! blah blah blah" without end */
524 /* Backtrack until we find the last non-whitespace */
525 while (IS_EOL(*ihp
) || IS_WHITESPACE(*ihp
)) {
529 /* The character after the last non-whitespace is our logical end of line */
533 * Now we have pointers to the usable part of:
535 * "#! /usr/bin/int first second third \n"
536 * ^ line_startp ^ line_endp
539 /* copy the interpreter name */
540 interp
= imgp
->ip_interp_buffer
;
541 for ( ihp
= line_startp
; (ihp
< line_endp
) && !IS_WHITESPACE(*ihp
); ihp
++)
545 exec_reset_save_path(imgp
);
546 exec_save_path(imgp
, CAST_USER_ADDR_T(imgp
->ip_interp_buffer
),
549 /* Copy the entire interpreter + args for later processing into argv[] */
550 interp
= imgp
->ip_interp_buffer
;
551 for ( ihp
= line_startp
; (ihp
< line_endp
); ihp
++)
556 * If we have a SUID oder SGID script, create a file descriptor
557 * from the vnode and pass /dev/fd/%d instead of the actual
558 * path name so that the script does not get opened twice
560 if (imgp
->ip_origvattr
->va_mode
& (VSUID
| VSGID
)) {
561 p
= vfs_context_proc(imgp
->ip_vfs_context
);
562 error
= falloc(p
, &fp
, &fd
, imgp
->ip_vfs_context
);
566 fp
->f_fglob
->fg_flag
= FREAD
;
567 fp
->f_fglob
->fg_ops
= &vnops
;
568 fp
->f_fglob
->fg_data
= (caddr_t
)imgp
->ip_vp
;
571 procfdtbl_releasefd(p
, fd
, NULL
);
572 fp_drop(p
, fd
, fp
, 1);
574 vnode_ref(imgp
->ip_vp
);
576 imgp
->ip_interp_sugid_fd
= fd
;
587 * Image activator for fat 1.0 binaries. If the binary is fat, then we
588 * need to select an image from it internally, and make that the image
589 * we are going to attempt to execute. At present, this consists of
590 * reloading the first page for the image with a first page from the
591 * offset location indicated by the fat header.
593 * Parameters; struct image_params * image parameter block
595 * Returns: -1 not a fat binary (keep looking)
596 * -2 Success: encapsulated binary: reread
597 * >0 Failure: error number
599 * Important: This image activator is byte order neutral.
601 * Note: A return value other than -1 indicates subsequent image
602 * activators should not be given the opportunity to attempt
603 * to activate the image.
605 * If we find an encapsulated binary, we make no assertions
606 * about its validity; instead, we leave that up to a rescan
607 * for an activator to claim it, and, if it is claimed by one,
608 * that activator is responsible for determining validity.
611 exec_fat_imgact(struct image_params
*imgp
)
613 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
614 kauth_cred_t cred
= kauth_cred_proc_ref(p
);
615 struct fat_header
*fat_header
= (struct fat_header
*)imgp
->ip_vdata
;
616 struct _posix_spawnattr
*psa
= NULL
;
617 struct fat_arch fat_arch
;
621 if (imgp
->ip_origcputype
!= 0) {
622 /* Fat header previously matched, don't allow another fat file inside */
623 error
= -1; /* not claimed */
627 /* Make sure it's a fat binary */
628 if (OSSwapBigToHostInt32(fat_header
->magic
) != FAT_MAGIC
) {
629 error
= -1; /* not claimed */
633 /* imgp->ip_vdata has PAGE_SIZE, zerofilled if the file is smaller */
634 lret
= fatfile_validate_fatarches((vm_offset_t
)fat_header
, PAGE_SIZE
);
635 if (lret
!= LOAD_SUCCESS
) {
636 error
= load_return_to_errno(lret
);
640 /* If posix_spawn binprefs exist, respect those prefs. */
641 psa
= (struct _posix_spawnattr
*) imgp
->ip_px_sa
;
642 if (psa
!= NULL
&& psa
->psa_binprefs
[0] != 0) {
645 /* Check each preference listed against all arches in header */
646 for (pr
= 0; pr
< NBINPREFS
; pr
++) {
647 cpu_type_t pref
= psa
->psa_binprefs
[pr
];
649 /* No suitable arch in the pref list */
654 if (pref
== CPU_TYPE_ANY
) {
655 /* Fall through to regular grading */
656 goto regular_grading
;
659 lret
= fatfile_getbestarch_for_cputype(pref
,
660 (vm_offset_t
)fat_header
,
663 if (lret
== LOAD_SUCCESS
) {
668 /* Requested binary preference was not honored */
674 /* Look up our preferred architecture in the fat file. */
675 lret
= fatfile_getbestarch((vm_offset_t
)fat_header
,
678 if (lret
!= LOAD_SUCCESS
) {
679 error
= load_return_to_errno(lret
);
684 /* Read the Mach-O header out of fat_arch */
685 error
= vn_rdwr(UIO_READ
, imgp
->ip_vp
, imgp
->ip_vdata
,
686 PAGE_SIZE
, fat_arch
.offset
,
687 UIO_SYSSPACE
, (IO_UNIT
|IO_NODELOCKED
),
694 memset(imgp
->ip_vdata
+ (PAGE_SIZE
- resid
), 0x0, resid
);
697 /* Success. Indicate we have identified an encapsulated binary */
699 imgp
->ip_arch_offset
= (user_size_t
)fat_arch
.offset
;
700 imgp
->ip_arch_size
= (user_size_t
)fat_arch
.size
;
701 imgp
->ip_origcputype
= fat_arch
.cputype
;
702 imgp
->ip_origcpusubtype
= fat_arch
.cpusubtype
;
705 kauth_cred_unref(&cred
);
710 activate_exec_state(task_t task
, proc_t p
, thread_t thread
, load_result_t
*result
)
714 task_set_dyld_info(task
, MACH_VM_MIN_ADDRESS
, 0);
715 if (result
->is64bit
) {
716 task_set_64bit(task
, TRUE
);
717 OSBitOrAtomic(P_LP64
, &p
->p_flag
);
719 task_set_64bit(task
, FALSE
);
720 OSBitAndAtomic(~((uint32_t)P_LP64
), &p
->p_flag
);
723 ret
= thread_state_initialize(thread
);
724 if (ret
!= KERN_SUCCESS
) {
728 if (result
->threadstate
) {
729 uint32_t *ts
= result
->threadstate
;
730 uint32_t total_size
= result
->threadstate_sz
;
732 while (total_size
> 0) {
733 uint32_t flavor
= *ts
++;
734 uint32_t size
= *ts
++;
736 ret
= thread_setstatus(thread
, flavor
, (thread_state_t
)ts
, size
);
741 total_size
-= (size
+ 2) * sizeof(uint32_t);
745 thread_setentrypoint(thread
, result
->entry_point
);
752 * Set p->p_comm and p->p_name to the name passed to exec
755 set_proc_name(struct image_params
*imgp
, proc_t p
)
757 int p_name_len
= sizeof(p
->p_name
) - 1;
759 if (imgp
->ip_ndp
->ni_cnd
.cn_namelen
> p_name_len
) {
760 imgp
->ip_ndp
->ni_cnd
.cn_namelen
= p_name_len
;
763 bcopy((caddr_t
)imgp
->ip_ndp
->ni_cnd
.cn_nameptr
, (caddr_t
)p
->p_name
,
764 (unsigned)imgp
->ip_ndp
->ni_cnd
.cn_namelen
);
765 p
->p_name
[imgp
->ip_ndp
->ni_cnd
.cn_namelen
] = '\0';
767 if (imgp
->ip_ndp
->ni_cnd
.cn_namelen
> MAXCOMLEN
) {
768 imgp
->ip_ndp
->ni_cnd
.cn_namelen
= MAXCOMLEN
;
771 bcopy((caddr_t
)imgp
->ip_ndp
->ni_cnd
.cn_nameptr
, (caddr_t
)p
->p_comm
,
772 (unsigned)imgp
->ip_ndp
->ni_cnd
.cn_namelen
);
773 p
->p_comm
[imgp
->ip_ndp
->ni_cnd
.cn_namelen
] = '\0';
779 * Image activator for mach-o 1.0 binaries.
781 * Parameters; struct image_params * image parameter block
783 * Returns: -1 not a fat binary (keep looking)
784 * -2 Success: encapsulated binary: reread
785 * >0 Failure: error number
786 * EBADARCH Mach-o binary, but with an unrecognized
788 * ENOMEM No memory for child process after -
789 * can only happen after vfork()
791 * Important: This image activator is NOT byte order neutral.
793 * Note: A return value other than -1 indicates subsequent image
794 * activators should not be given the opportunity to attempt
795 * to activate the image.
797 * TODO: More gracefully handle failures after vfork
800 exec_mach_imgact(struct image_params
*imgp
)
802 struct mach_header
*mach_header
= (struct mach_header
*)imgp
->ip_vdata
;
803 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
806 task_t new_task
= NULL
; /* protected by vfexec */
808 struct uthread
*uthread
;
809 vm_map_t old_map
= VM_MAP_NULL
;
810 vm_map_t map
= VM_MAP_NULL
;
812 load_result_t load_result
;
813 struct _posix_spawnattr
*psa
= NULL
;
814 int spawn
= (imgp
->ip_flags
& IMGPF_SPAWN
);
815 int vfexec
= (imgp
->ip_flags
& IMGPF_VFORK_EXEC
);
816 int exec
= (imgp
->ip_flags
& IMGPF_EXEC
);
817 os_reason_t exec_failure_reason
= OS_REASON_NULL
;
820 * make sure it's a Mach-O 1.0 or Mach-O 2.0 binary; the difference
821 * is a reserved field on the end, so for the most part, we can
822 * treat them as if they were identical. Reverse-endian Mach-O
823 * binaries are recognized but not compatible.
825 if ((mach_header
->magic
== MH_CIGAM
) ||
826 (mach_header
->magic
== MH_CIGAM_64
)) {
831 if ((mach_header
->magic
!= MH_MAGIC
) &&
832 (mach_header
->magic
!= MH_MAGIC_64
)) {
837 if (mach_header
->filetype
!= MH_EXECUTE
) {
842 if (imgp
->ip_origcputype
!= 0) {
843 /* Fat header previously had an idea about this thin file */
844 if (imgp
->ip_origcputype
!= mach_header
->cputype
||
845 imgp
->ip_origcpusubtype
!= mach_header
->cpusubtype
) {
850 imgp
->ip_origcputype
= mach_header
->cputype
;
851 imgp
->ip_origcpusubtype
= mach_header
->cpusubtype
;
854 task
= current_task();
855 thread
= current_thread();
856 uthread
= get_bsdthread_info(thread
);
858 if ((mach_header
->cputype
& CPU_ARCH_ABI64
) == CPU_ARCH_ABI64
)
859 imgp
->ip_flags
|= IMGPF_IS_64BIT
;
861 /* If posix_spawn binprefs exist, respect those prefs. */
862 psa
= (struct _posix_spawnattr
*) imgp
->ip_px_sa
;
863 if (psa
!= NULL
&& psa
->psa_binprefs
[0] != 0) {
865 for (pr
= 0; pr
< NBINPREFS
; pr
++) {
866 cpu_type_t pref
= psa
->psa_binprefs
[pr
];
868 /* No suitable arch in the pref list */
873 if (pref
== CPU_TYPE_ANY
) {
874 /* Jump to regular grading */
878 if (pref
== imgp
->ip_origcputype
) {
879 /* We have a match! */
887 if (!grade_binary(imgp
->ip_origcputype
, imgp
->ip_origcpusubtype
& ~CPU_SUBTYPE_MASK
)) {
892 /* Copy in arguments/environment from the old process */
893 error
= exec_extract_strings(imgp
);
897 AUDIT_ARG(argv
, imgp
->ip_startargv
, imgp
->ip_argc
,
898 imgp
->ip_endargv
- imgp
->ip_startargv
);
899 AUDIT_ARG(envv
, imgp
->ip_endargv
, imgp
->ip_envc
,
900 imgp
->ip_endenvv
- imgp
->ip_endargv
);
903 * We are being called to activate an image subsequent to a vfork()
904 * operation; in this case, we know that our task, thread, and
905 * uthread are actually those of our parent, and our proc, which we
906 * obtained indirectly from the image_params vfs_context_t, is the
910 imgp
->ip_new_thread
= fork_create_child(task
, NULL
, p
, FALSE
, (imgp
->ip_flags
& IMGPF_IS_64BIT
), FALSE
);
911 /* task and thread ref returned, will be released in __mac_execve */
912 if (imgp
->ip_new_thread
== NULL
) {
919 /* reset local idea of thread, uthread, task */
920 thread
= imgp
->ip_new_thread
;
921 uthread
= get_bsdthread_info(thread
);
922 task
= new_task
= get_threadtask(thread
);
925 * Load the Mach-O file.
927 * NOTE: An error after this point indicates we have potentially
928 * destroyed or overwritten some process state while attempting an
929 * execve() following a vfork(), which is an unrecoverable condition.
930 * We send the new process an immediate SIGKILL to avoid it executing
931 * any instructions in the mutated address space. For true spawns,
932 * this is not the case, and "too late" is still not too late to
933 * return an error code to the parent process.
937 * Actually load the image file we previously decided to load.
939 lret
= load_machfile(imgp
, mach_header
, thread
, &map
, &load_result
);
940 if (lret
!= LOAD_SUCCESS
) {
941 error
= load_return_to_errno(lret
);
943 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_CREATE
) | DBG_FUNC_NONE
,
944 p
->p_pid
, OS_REASON_EXEC
, EXEC_EXIT_REASON_BAD_MACHO
, 0, 0);
945 if (lret
== LOAD_BADMACHO_UPX
) {
946 /* set anything that might be useful in the crash report */
947 set_proc_name(imgp
, p
);
949 exec_failure_reason
= os_reason_create(OS_REASON_EXEC
, EXEC_EXIT_REASON_UPX
);
950 exec_failure_reason
->osr_flags
|= OS_REASON_FLAG_GENERATE_CRASH_REPORT
;
951 exec_failure_reason
->osr_flags
|= OS_REASON_FLAG_CONSISTENT_FAILURE
;
953 exec_failure_reason
= os_reason_create(OS_REASON_EXEC
, EXEC_EXIT_REASON_BAD_MACHO
);
960 p
->p_cputype
= imgp
->ip_origcputype
;
961 p
->p_cpusubtype
= imgp
->ip_origcpusubtype
;
964 vm_map_set_user_wire_limit(map
, p
->p_rlimit
[RLIMIT_MEMLOCK
].rlim_cur
);
967 * Set code-signing flags if this binary is signed, or if parent has
968 * requested them on exec.
970 if (load_result
.csflags
& CS_VALID
) {
971 imgp
->ip_csflags
|= load_result
.csflags
&
972 (CS_VALID
|CS_SIGNED
|CS_DEV_CODE
|
973 CS_HARD
|CS_KILL
|CS_RESTRICT
|CS_ENFORCEMENT
|CS_REQUIRE_LV
|
974 CS_ENTITLEMENTS_VALIDATED
|CS_DYLD_PLATFORM
|
975 CS_ENTITLEMENT_FLAGS
|
976 CS_EXEC_SET_HARD
|CS_EXEC_SET_KILL
|CS_EXEC_SET_ENFORCEMENT
);
978 imgp
->ip_csflags
&= ~CS_VALID
;
981 if (p
->p_csflags
& CS_EXEC_SET_HARD
)
982 imgp
->ip_csflags
|= CS_HARD
;
983 if (p
->p_csflags
& CS_EXEC_SET_KILL
)
984 imgp
->ip_csflags
|= CS_KILL
;
985 if (p
->p_csflags
& CS_EXEC_SET_ENFORCEMENT
)
986 imgp
->ip_csflags
|= CS_ENFORCEMENT
;
987 if (p
->p_csflags
& CS_EXEC_SET_INSTALLER
)
988 imgp
->ip_csflags
|= CS_INSTALLER
;
991 * Set up the system reserved areas in the new address space.
993 vm_map_exec(map
, task
, load_result
.is64bit
, (void *)p
->p_fd
->fd_rdir
, cpu_type());
996 * Close file descriptors which specify close-on-exec.
998 fdexec(p
, psa
!= NULL
? psa
->psa_flags
: 0);
1001 * deal with set[ug]id.
1003 error
= exec_handle_sugid(imgp
);
1005 vm_map_deallocate(map
);
1007 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_CREATE
) | DBG_FUNC_NONE
,
1008 p
->p_pid
, OS_REASON_EXEC
, EXEC_EXIT_REASON_SUGID_FAILURE
, 0, 0);
1009 exec_failure_reason
= os_reason_create(OS_REASON_EXEC
, EXEC_EXIT_REASON_SUGID_FAILURE
);
1014 * Commit to new map.
1016 * Swap the new map for the old for target task, which consumes
1017 * our new map reference but each leaves us responsible for the
1018 * old_map reference. That lets us get off the pmap associated
1019 * with it, and then we can release it.
1021 * The map needs to be set on the target task which is different
1022 * than current task, thus swap_task_map is used instead of
1025 old_map
= swap_task_map(task
, thread
, map
);
1026 vm_map_deallocate(old_map
);
1029 lret
= activate_exec_state(task
, p
, thread
, &load_result
);
1030 if (lret
!= KERN_SUCCESS
) {
1032 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_CREATE
) | DBG_FUNC_NONE
,
1033 p
->p_pid
, OS_REASON_EXEC
, EXEC_EXIT_REASON_ACTV_THREADSTATE
, 0, 0);
1034 exec_failure_reason
= os_reason_create(OS_REASON_EXEC
, EXEC_EXIT_REASON_ACTV_THREADSTATE
);
1039 * deal with voucher on exec-calling thread.
1041 if (imgp
->ip_new_thread
== NULL
)
1042 thread_set_mach_voucher(current_thread(), IPC_VOUCHER_NULL
);
1044 /* Make sure we won't interrupt ourself signalling a partial process */
1045 if (!vfexec
&& !spawn
&& (p
->p_lflag
& P_LTRACED
))
1046 psignal(p
, SIGTRAP
);
1048 if (load_result
.unixproc
&&
1049 create_unix_stack(get_task_map(task
),
1051 p
) != KERN_SUCCESS
) {
1052 error
= load_return_to_errno(LOAD_NOSPACE
);
1054 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_CREATE
) | DBG_FUNC_NONE
,
1055 p
->p_pid
, OS_REASON_EXEC
, EXEC_EXIT_REASON_STACK_ALLOC
, 0, 0);
1056 exec_failure_reason
= os_reason_create(OS_REASON_EXEC
, EXEC_EXIT_REASON_STACK_ALLOC
);
1060 error
= exec_add_apple_strings(imgp
, &load_result
);
1063 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_CREATE
) | DBG_FUNC_NONE
,
1064 p
->p_pid
, OS_REASON_EXEC
, EXEC_EXIT_REASON_APPLE_STRING_INIT
, 0, 0);
1065 exec_failure_reason
= os_reason_create(OS_REASON_EXEC
, EXEC_EXIT_REASON_APPLE_STRING_INIT
);
1069 /* Switch to target task's map to copy out strings */
1070 old_map
= vm_map_switch(get_task_map(task
));
1072 if (load_result
.unixproc
) {
1076 * Copy the strings area out into the new process address
1080 error
= exec_copyout_strings(imgp
, &ap
);
1082 vm_map_switch(old_map
);
1084 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_CREATE
) | DBG_FUNC_NONE
,
1085 p
->p_pid
, OS_REASON_EXEC
, EXEC_EXIT_REASON_COPYOUT_STRINGS
, 0, 0);
1086 exec_failure_reason
= os_reason_create(OS_REASON_EXEC
, EXEC_EXIT_REASON_COPYOUT_STRINGS
);
1090 thread_setuserstack(thread
, ap
);
1093 if (load_result
.dynlinker
) {
1095 int new_ptr_size
= (imgp
->ip_flags
& IMGPF_IS_64BIT
) ? 8 : 4;
1097 /* Adjust the stack */
1098 ap
= thread_adjuserstack(thread
, -new_ptr_size
);
1099 error
= copyoutptr(load_result
.mach_header
, ap
, new_ptr_size
);
1102 vm_map_switch(old_map
);
1104 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_CREATE
) | DBG_FUNC_NONE
,
1105 p
->p_pid
, OS_REASON_EXEC
, EXEC_EXIT_REASON_COPYOUT_DYNLINKER
, 0, 0);
1106 exec_failure_reason
= os_reason_create(OS_REASON_EXEC
, EXEC_EXIT_REASON_COPYOUT_DYNLINKER
);
1109 task_set_dyld_info(task
, load_result
.all_image_info_addr
,
1110 load_result
.all_image_info_size
);
1113 /* Avoid immediate VM faults back into kernel */
1114 exec_prefault_data(p
, imgp
, &load_result
);
1116 vm_map_switch(old_map
);
1118 /* Stop profiling */
1122 * Reset signal state.
1124 execsigs(p
, thread
);
1127 * need to cancel async IO requests that can be cancelled and wait for those
1128 * already active. MAY BLOCK!
1133 /* FIXME: Till vmspace inherit is fixed: */
1134 if (!vfexec
&& p
->vm_shm
)
1138 /* Clean up the semaphores */
1143 * Remember file name for accounting.
1145 p
->p_acflag
&= ~AFORK
;
1147 set_proc_name(imgp
, p
);
1149 #if CONFIG_SECLUDED_MEMORY
1150 if (secluded_for_apps
) {
1151 if (strncmp(p
->p_name
,
1153 sizeof (p
->p_name
)) == 0 ||
1157 sizeof (p
->p_name
)) == 0 ||
1161 sizeof (p
->p_name
)) == 0) {
1162 task_set_could_use_secluded_mem(task
, TRUE
);
1164 task_set_could_use_secluded_mem(task
, FALSE
);
1166 if (strncmp(p
->p_name
,
1168 sizeof (p
->p_name
)) == 0) {
1169 task_set_could_also_use_secluded_mem(task
, TRUE
);
1172 #endif /* CONFIG_SECLUDED_MEMORY */
1174 pal_dbg_set_task_name( task
);
1176 #if DEVELOPMENT || DEBUG
1178 * Update the pid an proc name for importance base if any
1180 task_importance_update_owner_info(task
);
1183 memcpy(&p
->p_uuid
[0], &load_result
.uuid
[0], sizeof(p
->p_uuid
));
1186 dtrace_proc_exec(p
);
1189 if (kdebug_enable
) {
1190 long dbg_arg1
, dbg_arg2
, dbg_arg3
, dbg_arg4
;
1193 * Collect the pathname for tracing
1195 kdbg_trace_string(p
, &dbg_arg1
, &dbg_arg2
, &dbg_arg3
, &dbg_arg4
);
1197 KERNEL_DEBUG_CONSTANT1(TRACE_DATA_EXEC
| DBG_FUNC_NONE
,
1198 p
->p_pid
,0,0,0, (uintptr_t)thread_tid(thread
));
1199 KERNEL_DEBUG_CONSTANT1(TRACE_STRING_EXEC
| DBG_FUNC_NONE
,
1200 dbg_arg1
, dbg_arg2
, dbg_arg3
, dbg_arg4
, (uintptr_t)thread_tid(thread
));
1204 * If posix_spawned with the START_SUSPENDED flag, stop the
1205 * process before it runs.
1207 if (imgp
->ip_px_sa
!= NULL
) {
1208 psa
= (struct _posix_spawnattr
*) imgp
->ip_px_sa
;
1209 if (psa
->psa_flags
& POSIX_SPAWN_START_SUSPENDED
) {
1213 (void) task_suspend_internal(task
);
1218 * mark as execed, wakeup the process that vforked (if any) and tell
1219 * it that it now has its own resources back
1221 OSBitOrAtomic(P_EXEC
, &p
->p_flag
);
1222 proc_resetregister(p
);
1223 if (p
->p_pptr
&& (p
->p_lflag
& P_LPPWAIT
)) {
1225 p
->p_lflag
&= ~P_LPPWAIT
;
1227 wakeup((caddr_t
)p
->p_pptr
);
1231 * Pay for our earlier safety; deliver the delayed signals from
1232 * the incomplete vfexec process now that it's complete.
1234 if (vfexec
&& (p
->p_lflag
& P_LTRACED
)) {
1235 psignal_vfork(p
, new_task
, thread
, SIGTRAP
);
1241 /* Don't allow child process to execute any instructions */
1244 assert(exec_failure_reason
!= OS_REASON_NULL
);
1245 psignal_vfork_with_reason(p
, new_task
, thread
, SIGKILL
, exec_failure_reason
);
1246 exec_failure_reason
= OS_REASON_NULL
;
1248 assert(exec_failure_reason
!= OS_REASON_NULL
);
1249 psignal_with_reason(p
, SIGKILL
, exec_failure_reason
);
1250 exec_failure_reason
= OS_REASON_NULL
;
1253 /* Terminate the exec copy task */
1254 task_terminate_internal(task
);
1258 /* We can't stop this system call at this point, so just pretend we succeeded */
1261 os_reason_free(exec_failure_reason
);
1262 exec_failure_reason
= OS_REASON_NULL
;
1267 /* notify only if it has not failed due to FP Key error */
1268 if ((p
->p_lflag
& P_LTERM_DECRYPTFAIL
) == 0)
1269 proc_knote(p
, NOTE_EXEC
);
1272 if (load_result
.threadstate
) {
1273 kfree(load_result
.threadstate
, load_result
.threadstate_sz
);
1274 load_result
.threadstate
= NULL
;
1278 /* If we hit this, we likely would have leaked an exit reason */
1279 assert(exec_failure_reason
== OS_REASON_NULL
);
1287 * Our image activator table; this is the table of the image types we are
1288 * capable of loading. We list them in order of preference to ensure the
1289 * fastest image load speed.
1291 * XXX hardcoded, for now; should use linker sets
1294 int (*ex_imgact
)(struct image_params
*);
1295 const char *ex_name
;
1297 { exec_mach_imgact
, "Mach-o Binary" },
1298 { exec_fat_imgact
, "Fat Binary" },
1299 { exec_shell_imgact
, "Interpreter Script" },
1305 * exec_activate_image
1307 * Description: Iterate through the available image activators, and activate
1308 * the image associated with the imgp structure. We start with
1311 * Parameters: struct image_params * Image parameter block
1313 * Returns: 0 Success
1314 * EBADEXEC The executable is corrupt/unknown
1315 * execargs_alloc:EINVAL Invalid argument
1316 * execargs_alloc:EACCES Permission denied
1317 * execargs_alloc:EINTR Interrupted function
1318 * execargs_alloc:ENOMEM Not enough space
1319 * exec_save_path:EFAULT Bad address
1320 * exec_save_path:ENAMETOOLONG Filename too long
1321 * exec_check_permissions:EACCES Permission denied
1322 * exec_check_permissions:ENOEXEC Executable file format error
1323 * exec_check_permissions:ETXTBSY Text file busy [misuse of error code]
1324 * exec_check_permissions:???
1326 * vn_rdwr:??? [anything vn_rdwr can return]
1327 * <ex_imgact>:??? [anything an imgact can return]
1328 * EDEADLK Process is being terminated
1331 exec_activate_image(struct image_params
*imgp
)
1333 struct nameidata
*ndp
= NULL
;
1334 const char *excpath
;
1337 int once
= 1; /* save SGUID-ness for interpreted files */
1340 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
1342 error
= execargs_alloc(imgp
);
1346 error
= exec_save_path(imgp
, imgp
->ip_user_fname
, imgp
->ip_seg
, &excpath
);
1351 /* Use excpath, which contains the copyin-ed exec path */
1352 DTRACE_PROC1(exec
, uintptr_t, excpath
);
1354 MALLOC(ndp
, struct nameidata
*, sizeof(*ndp
), M_TEMP
, M_WAITOK
| M_ZERO
);
1360 NDINIT(ndp
, LOOKUP
, OP_LOOKUP
, FOLLOW
| LOCKLEAF
| AUDITVNPATH1
,
1361 UIO_SYSSPACE
, CAST_USER_ADDR_T(excpath
), imgp
->ip_vfs_context
);
1367 imgp
->ip_ndp
= ndp
; /* successful namei(); call nameidone() later */
1368 imgp
->ip_vp
= ndp
->ni_vp
; /* if set, need to vnode_put() at some point */
1371 * Before we start the transition from binary A to binary B, make
1372 * sure another thread hasn't started exiting the process. We grab
1373 * the proc lock to check p_lflag initially, and the transition
1374 * mechanism ensures that the value doesn't change after we release
1378 if (p
->p_lflag
& P_LEXIT
) {
1383 error
= proc_transstart(p
, 1, 0);
1388 error
= exec_check_permissions(imgp
);
1392 /* Copy; avoid invocation of an interpreter overwriting the original */
1395 *imgp
->ip_origvattr
= *imgp
->ip_vattr
;
1398 error
= vn_rdwr(UIO_READ
, imgp
->ip_vp
, imgp
->ip_vdata
, PAGE_SIZE
, 0,
1399 UIO_SYSSPACE
, IO_NODELOCKED
,
1400 vfs_context_ucred(imgp
->ip_vfs_context
),
1401 &resid
, vfs_context_proc(imgp
->ip_vfs_context
));
1406 memset(imgp
->ip_vdata
+ (PAGE_SIZE
- resid
), 0x0, resid
);
1409 encapsulated_binary
:
1410 /* Limit the number of iterations we will attempt on each binary */
1411 if (++itercount
> EAI_ITERLIMIT
) {
1416 for(i
= 0; error
== -1 && execsw
[i
].ex_imgact
!= NULL
; i
++) {
1418 error
= (*execsw
[i
].ex_imgact
)(imgp
);
1421 /* case -1: not claimed: continue */
1422 case -2: /* Encapsulated binary, imgp->ip_XXX set for next iteration */
1423 goto encapsulated_binary
;
1425 case -3: /* Interpreter */
1428 * Copy the script label for later use. Note that
1429 * the label can be different when the script is
1430 * actually read by the interpreter.
1432 if (imgp
->ip_scriptlabelp
)
1433 mac_vnode_label_free(imgp
->ip_scriptlabelp
);
1434 imgp
->ip_scriptlabelp
= mac_vnode_label_alloc();
1435 if (imgp
->ip_scriptlabelp
== NULL
) {
1439 mac_vnode_label_copy(imgp
->ip_vp
->v_label
,
1440 imgp
->ip_scriptlabelp
);
1443 * Take a ref of the script vnode for later use.
1445 if (imgp
->ip_scriptvp
)
1446 vnode_put(imgp
->ip_scriptvp
);
1447 if (vnode_getwithref(imgp
->ip_vp
) == 0)
1448 imgp
->ip_scriptvp
= imgp
->ip_vp
;
1453 vnode_put(imgp
->ip_vp
);
1454 imgp
->ip_vp
= NULL
; /* already put */
1455 imgp
->ip_ndp
= NULL
; /* already nameidone */
1457 /* Use excpath, which exec_shell_imgact reset to the interpreter */
1458 NDINIT(ndp
, LOOKUP
, OP_LOOKUP
, FOLLOW
| LOCKLEAF
,
1459 UIO_SYSSPACE
, CAST_USER_ADDR_T(excpath
), imgp
->ip_vfs_context
);
1461 proc_transend(p
, 0);
1470 * Call out to allow 3rd party notification of exec.
1471 * Ignore result of kauth_authorize_fileop call.
1473 if (error
== 0 && kauth_authorize_fileop_has_listeners()) {
1474 kauth_authorize_fileop(vfs_context_ucred(imgp
->ip_vfs_context
),
1476 (uintptr_t)ndp
->ni_vp
, 0);
1479 proc_transend(p
, 0);
1482 if (imgp
->ip_strings
)
1483 execargs_free(imgp
);
1485 nameidone(imgp
->ip_ndp
);
1494 * exec_handle_spawnattr_policy
1496 * Description: Decode and apply the posix_spawn apptype, qos clamp, and watchport ports to the task.
1498 * Parameters: proc_t p process to apply attributes to
1499 * int psa_apptype posix spawn attribute apptype
1501 * Returns: 0 Success
1504 exec_handle_spawnattr_policy(proc_t p
, int psa_apptype
, uint64_t psa_qos_clamp
, uint64_t psa_darwin_role
,
1505 ipc_port_t
* portwatch_ports
, int portwatch_count
)
1507 int apptype
= TASK_APPTYPE_NONE
;
1508 int qos_clamp
= THREAD_QOS_UNSPECIFIED
;
1509 int role
= TASK_UNSPECIFIED
;
1511 if ((psa_apptype
& POSIX_SPAWN_PROC_TYPE_MASK
) != 0) {
1512 int proctype
= psa_apptype
& POSIX_SPAWN_PROC_TYPE_MASK
;
1515 case POSIX_SPAWN_PROC_TYPE_DAEMON_INTERACTIVE
:
1516 apptype
= TASK_APPTYPE_DAEMON_INTERACTIVE
;
1518 case POSIX_SPAWN_PROC_TYPE_DAEMON_STANDARD
:
1519 apptype
= TASK_APPTYPE_DAEMON_STANDARD
;
1521 case POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE
:
1522 apptype
= TASK_APPTYPE_DAEMON_ADAPTIVE
;
1524 case POSIX_SPAWN_PROC_TYPE_DAEMON_BACKGROUND
:
1525 apptype
= TASK_APPTYPE_DAEMON_BACKGROUND
;
1527 case POSIX_SPAWN_PROC_TYPE_APP_DEFAULT
:
1528 apptype
= TASK_APPTYPE_APP_DEFAULT
;
1530 case POSIX_SPAWN_PROC_TYPE_APP_TAL
:
1531 apptype
= TASK_APPTYPE_APP_TAL
;
1534 apptype
= TASK_APPTYPE_NONE
;
1535 /* TODO: Should an invalid value here fail the spawn? */
1540 if (psa_qos_clamp
!= POSIX_SPAWN_PROC_CLAMP_NONE
) {
1541 switch (psa_qos_clamp
) {
1542 case POSIX_SPAWN_PROC_CLAMP_UTILITY
:
1543 qos_clamp
= THREAD_QOS_UTILITY
;
1545 case POSIX_SPAWN_PROC_CLAMP_BACKGROUND
:
1546 qos_clamp
= THREAD_QOS_BACKGROUND
;
1548 case POSIX_SPAWN_PROC_CLAMP_MAINTENANCE
:
1549 qos_clamp
= THREAD_QOS_MAINTENANCE
;
1552 qos_clamp
= THREAD_QOS_UNSPECIFIED
;
1553 /* TODO: Should an invalid value here fail the spawn? */
1558 if (psa_darwin_role
!= PRIO_DARWIN_ROLE_DEFAULT
) {
1559 proc_darwin_role_to_task_role(psa_darwin_role
, &role
);
1562 if (apptype
!= TASK_APPTYPE_NONE
||
1563 qos_clamp
!= THREAD_QOS_UNSPECIFIED
||
1564 role
!= TASK_UNSPECIFIED
) {
1565 proc_set_task_spawnpolicy(p
->task
, apptype
, qos_clamp
, role
,
1566 portwatch_ports
, portwatch_count
);
1574 * exec_handle_port_actions
1576 * Description: Go through the _posix_port_actions_t contents,
1577 * calling task_set_special_port, task_set_exception_ports
1578 * and/or audit_session_spawnjoin for the current task.
1580 * Parameters: struct image_params * Image parameter block
1582 * Returns: 0 Success
1584 * ENOTSUP Illegal posix_spawn attr flag was set
1587 exec_handle_port_actions(struct image_params
*imgp
, boolean_t
* portwatch_present
,
1588 ipc_port_t
* portwatch_ports
)
1590 _posix_spawn_port_actions_t pacts
= imgp
->ip_px_spa
;
1592 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
1594 _ps_port_action_t
*act
= NULL
;
1595 task_t task
= get_threadtask(imgp
->ip_new_thread
);
1596 ipc_port_t port
= NULL
;
1601 *portwatch_present
= FALSE
;
1603 for (i
= 0; i
< pacts
->pspa_count
; i
++) {
1604 act
= &pacts
->pspa_actions
[i
];
1606 if (MACH_PORT_VALID(act
->new_port
)) {
1607 kr
= ipc_object_copyin(get_task_ipcspace(current_task()),
1608 act
->new_port
, MACH_MSG_TYPE_COPY_SEND
,
1609 (ipc_object_t
*) &port
);
1611 if (kr
!= KERN_SUCCESS
) {
1616 /* it's NULL or DEAD */
1617 port
= CAST_MACH_NAME_TO_PORT(act
->new_port
);
1620 switch (act
->port_type
) {
1622 kr
= task_set_special_port(task
, act
->which
, port
);
1624 if (kr
!= KERN_SUCCESS
)
1628 case PSPA_EXCEPTION
:
1629 kr
= task_set_exception_ports(task
, act
->mask
, port
,
1630 act
->behavior
, act
->flavor
);
1631 if (kr
!= KERN_SUCCESS
)
1635 case PSPA_AU_SESSION
:
1636 ret
= audit_session_spawnjoin(p
, task
, port
);
1639 case PSPA_IMP_WATCHPORTS
:
1640 if (portwatch_ports
!= NULL
&& IPC_PORT_VALID(port
)) {
1641 *portwatch_present
= TRUE
;
1642 /* hold on to this till end of spawn */
1643 portwatch_ports
[i
] = port
;
1645 ipc_port_release_send(port
);
1655 /* action failed, so release port resources */
1656 ipc_port_release_send(port
);
1663 DTRACE_PROC1(spawn__port__failure
, mach_port_name_t
, act
->new_port
);
1668 * exec_handle_file_actions
1670 * Description: Go through the _posix_file_actions_t contents applying the
1671 * open, close, and dup2 operations to the open file table for
1672 * the current process.
1674 * Parameters: struct image_params * Image parameter block
1676 * Returns: 0 Success
1679 * Note: Actions are applied in the order specified, with the credential
1680 * of the parent process. This is done to permit the parent
1681 * process to utilize POSIX_SPAWN_RESETIDS to drop privilege in
1682 * the child following operations the child may in fact not be
1683 * normally permitted to perform.
1686 exec_handle_file_actions(struct image_params
*imgp
, short psa_flags
)
1690 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
1691 _posix_spawn_file_actions_t px_sfap
= imgp
->ip_px_sfa
;
1692 int ival
[2]; /* dummy retval for system calls) */
1694 for (action
= 0; action
< px_sfap
->psfa_act_count
; action
++) {
1695 _psfa_action_t
*psfa
= &px_sfap
->psfa_act_acts
[ action
];
1697 switch(psfa
->psfaa_type
) {
1700 * Open is different, in that it requires the use of
1701 * a path argument, which is normally copied in from
1702 * user space; because of this, we have to support an
1703 * open from kernel space that passes an address space
1704 * context of UIO_SYSSPACE, and casts the address
1705 * argument to a user_addr_t.
1708 struct vnode_attr
*vap
;
1709 struct nameidata
*ndp
;
1710 int mode
= psfa
->psfaa_openargs
.psfao_mode
;
1711 struct dup2_args dup2a
;
1712 struct close_nocancel_args ca
;
1715 MALLOC(bufp
, char *, sizeof(*vap
) + sizeof(*ndp
), M_TEMP
, M_WAITOK
| M_ZERO
);
1721 vap
= (struct vnode_attr
*) bufp
;
1722 ndp
= (struct nameidata
*) (bufp
+ sizeof(*vap
));
1725 /* Mask off all but regular access permissions */
1726 mode
= ((mode
&~ p
->p_fd
->fd_cmask
) & ALLPERMS
) & ~S_ISTXT
;
1727 VATTR_SET(vap
, va_mode
, mode
& ACCESSPERMS
);
1729 NDINIT(ndp
, LOOKUP
, OP_OPEN
, FOLLOW
| AUDITVNPATH1
, UIO_SYSSPACE
,
1730 CAST_USER_ADDR_T(psfa
->psfaa_openargs
.psfao_path
),
1731 imgp
->ip_vfs_context
);
1733 error
= open1(imgp
->ip_vfs_context
,
1735 psfa
->psfaa_openargs
.psfao_oflag
,
1737 fileproc_alloc_init
, NULL
,
1743 * If there's an error, or we get the right fd by
1744 * accident, then drop out here. This is easier than
1745 * reworking all the open code to preallocate fd
1746 * slots, and internally taking one as an argument.
1748 if (error
|| ival
[0] == psfa
->psfaa_filedes
)
1753 * If we didn't fall out from an error, we ended up
1754 * with the wrong fd; so now we've got to try to dup2
1755 * it to the right one.
1757 dup2a
.from
= origfd
;
1758 dup2a
.to
= psfa
->psfaa_filedes
;
1761 * The dup2() system call implementation sets
1762 * ival to newfd in the success case, but we
1763 * can ignore that, since if we didn't get the
1764 * fd we wanted, the error will stop us.
1766 error
= dup2(p
, &dup2a
, ival
);
1771 * Finally, close the original fd.
1775 error
= close_nocancel(p
, &ca
, ival
);
1780 struct dup2_args dup2a
;
1782 dup2a
.from
= psfa
->psfaa_filedes
;
1783 dup2a
.to
= psfa
->psfaa_openargs
.psfao_oflag
;
1786 * The dup2() system call implementation sets
1787 * ival to newfd in the success case, but we
1788 * can ignore that, since if we didn't get the
1789 * fd we wanted, the error will stop us.
1791 error
= dup2(p
, &dup2a
, ival
);
1796 struct close_nocancel_args ca
;
1798 ca
.fd
= psfa
->psfaa_filedes
;
1800 error
= close_nocancel(p
, &ca
, ival
);
1804 case PSFA_INHERIT
: {
1805 struct fcntl_nocancel_args fcntla
;
1808 * Check to see if the descriptor exists, and
1809 * ensure it's -not- marked as close-on-exec.
1811 * Attempting to "inherit" a guarded fd will
1812 * result in a error.
1814 fcntla
.fd
= psfa
->psfaa_filedes
;
1815 fcntla
.cmd
= F_GETFD
;
1816 if ((error
= fcntl_nocancel(p
, &fcntla
, ival
)) != 0)
1819 if ((ival
[0] & FD_CLOEXEC
) == FD_CLOEXEC
) {
1820 fcntla
.fd
= psfa
->psfaa_filedes
;
1821 fcntla
.cmd
= F_SETFD
;
1822 fcntla
.arg
= ival
[0] & ~FD_CLOEXEC
;
1823 error
= fcntl_nocancel(p
, &fcntla
, ival
);
1834 /* All file actions failures are considered fatal, per POSIX */
1837 if (PSFA_OPEN
== psfa
->psfaa_type
) {
1838 DTRACE_PROC1(spawn__open__failure
, uintptr_t,
1839 psfa
->psfaa_openargs
.psfao_path
);
1841 DTRACE_PROC1(spawn__fd__failure
, int, psfa
->psfaa_filedes
);
1847 if (error
!= 0 || (psa_flags
& POSIX_SPAWN_CLOEXEC_DEFAULT
) == 0)
1851 * If POSIX_SPAWN_CLOEXEC_DEFAULT is set, behave (during
1852 * this spawn only) as if "close on exec" is the default
1853 * disposition of all pre-existing file descriptors. In this case,
1854 * the list of file descriptors mentioned in the file actions
1855 * are the only ones that can be inherited, so mark them now.
1857 * The actual closing part comes later, in fdexec().
1860 for (action
= 0; action
< px_sfap
->psfa_act_count
; action
++) {
1861 _psfa_action_t
*psfa
= &px_sfap
->psfa_act_acts
[action
];
1862 int fd
= psfa
->psfaa_filedes
;
1864 switch (psfa
->psfaa_type
) {
1866 fd
= psfa
->psfaa_openargs
.psfao_oflag
;
1870 *fdflags(p
, fd
) |= UF_INHERIT
;
1884 * exec_spawnattr_getmacpolicyinfo
1887 exec_spawnattr_getmacpolicyinfo(const void *macextensions
, const char *policyname
, size_t *lenp
)
1889 const struct _posix_spawn_mac_policy_extensions
*psmx
= macextensions
;
1895 for (i
= 0; i
< psmx
->psmx_count
; i
++) {
1896 const _ps_mac_policy_extension_t
*extension
= &psmx
->psmx_extensions
[i
];
1897 if (strncmp(extension
->policyname
, policyname
, sizeof(extension
->policyname
)) == 0) {
1899 *lenp
= extension
->datalen
;
1900 return extension
->datap
;
1910 spawn_copyin_macpolicyinfo(const struct user__posix_spawn_args_desc
*px_args
, _posix_spawn_mac_policy_extensions_t
*psmxp
)
1912 _posix_spawn_mac_policy_extensions_t psmx
= NULL
;
1919 if (px_args
->mac_extensions_size
< PS_MAC_EXTENSIONS_SIZE(1) ||
1920 px_args
->mac_extensions_size
> PAGE_SIZE
) {
1925 MALLOC(psmx
, _posix_spawn_mac_policy_extensions_t
, px_args
->mac_extensions_size
, M_TEMP
, M_WAITOK
);
1926 if ((error
= copyin(px_args
->mac_extensions
, psmx
, px_args
->mac_extensions_size
)) != 0)
1929 if (PS_MAC_EXTENSIONS_SIZE(psmx
->psmx_count
) > px_args
->mac_extensions_size
) {
1934 for (i
= 0; i
< psmx
->psmx_count
; i
++) {
1935 _ps_mac_policy_extension_t
*extension
= &psmx
->psmx_extensions
[i
];
1936 if (extension
->datalen
== 0 || extension
->datalen
> PAGE_SIZE
) {
1942 for (copycnt
= 0; copycnt
< psmx
->psmx_count
; copycnt
++) {
1943 _ps_mac_policy_extension_t
*extension
= &psmx
->psmx_extensions
[copycnt
];
1946 MALLOC(data
, void *, extension
->datalen
, M_TEMP
, M_WAITOK
);
1947 if ((error
= copyin(extension
->data
, data
, extension
->datalen
)) != 0) {
1951 extension
->datap
= data
;
1959 for (i
= 0; i
< copycnt
; i
++)
1960 FREE(psmx
->psmx_extensions
[i
].datap
, M_TEMP
);
1967 spawn_free_macpolicyinfo(_posix_spawn_mac_policy_extensions_t psmx
)
1973 for (i
= 0; i
< psmx
->psmx_count
; i
++)
1974 FREE(psmx
->psmx_extensions
[i
].datap
, M_TEMP
);
1977 #endif /* CONFIG_MACF */
1979 #if CONFIG_COALITIONS
1980 static inline void spawn_coalitions_release_all(coalition_t coal
[COALITION_NUM_TYPES
])
1982 for (int c
= 0; c
< COALITION_NUM_TYPES
; c
++) {
1984 coalition_remove_active(coal
[c
]);
1985 coalition_release(coal
[c
]);
1992 static int spawn_validate_persona(struct _posix_spawn_persona_info
*px_persona
)
1995 struct persona
*persona
= NULL
;
1996 int verify
= px_persona
->pspi_flags
& POSIX_SPAWN_PERSONA_FLAGS_VERIFY
;
1999 * TODO: rdar://problem/19981151
2000 * Add entitlement check!
2002 if (!kauth_cred_issuser(kauth_cred_get()))
2005 persona
= persona_lookup(px_persona
->pspi_id
);
2012 if (px_persona
->pspi_flags
& POSIX_SPAWN_PERSONA_UID
) {
2013 if (px_persona
->pspi_uid
!= persona_get_uid(persona
)) {
2018 if (px_persona
->pspi_flags
& POSIX_SPAWN_PERSONA_GID
) {
2019 if (px_persona
->pspi_gid
!= persona_get_gid(persona
)) {
2024 if (px_persona
->pspi_flags
& POSIX_SPAWN_PERSONA_GROUPS
) {
2026 gid_t groups
[NGROUPS_MAX
];
2028 if (persona_get_groups(persona
, &ngroups
, groups
,
2029 px_persona
->pspi_ngroups
) != 0) {
2033 if (ngroups
!= (int)px_persona
->pspi_ngroups
) {
2038 if (px_persona
->pspi_groups
[ngroups
] != groups
[ngroups
]) {
2043 if (px_persona
->pspi_gmuid
!= persona_get_gmuid(persona
)) {
2052 persona_put(persona
);
2057 static int spawn_persona_adopt(proc_t p
, struct _posix_spawn_persona_info
*px_persona
)
2061 struct persona
*persona
= NULL
;
2062 int override
= !!(px_persona
->pspi_flags
& POSIX_SPAWN_PERSONA_FLAGS_OVERRIDE
);
2065 return persona_proc_adopt_id(p
, px_persona
->pspi_id
, NULL
);
2068 * we want to spawn into the given persona, but we want to override
2069 * the kauth with a different UID/GID combo
2071 persona
= persona_lookup(px_persona
->pspi_id
);
2075 cred
= persona_get_cred(persona
);
2081 if (px_persona
->pspi_flags
& POSIX_SPAWN_PERSONA_UID
) {
2082 cred
= kauth_cred_setresuid(cred
,
2083 px_persona
->pspi_uid
,
2084 px_persona
->pspi_uid
,
2085 px_persona
->pspi_uid
,
2089 if (px_persona
->pspi_flags
& POSIX_SPAWN_PERSONA_GID
) {
2090 cred
= kauth_cred_setresgid(cred
,
2091 px_persona
->pspi_gid
,
2092 px_persona
->pspi_gid
,
2093 px_persona
->pspi_gid
);
2096 if (px_persona
->pspi_flags
& POSIX_SPAWN_PERSONA_GROUPS
) {
2097 cred
= kauth_cred_setgroups(cred
,
2098 px_persona
->pspi_groups
,
2099 px_persona
->pspi_ngroups
,
2100 px_persona
->pspi_gmuid
);
2103 ret
= persona_proc_adopt(p
, persona
, cred
);
2106 persona_put(persona
);
2114 * Parameters: uap->pid Pointer to pid return area
2115 * uap->fname File name to exec
2116 * uap->argp Argument list
2117 * uap->envp Environment list
2119 * Returns: 0 Success
2120 * EINVAL Invalid argument
2121 * ENOTSUP Not supported
2122 * ENOEXEC Executable file format error
2123 * exec_activate_image:EINVAL Invalid argument
2124 * exec_activate_image:EACCES Permission denied
2125 * exec_activate_image:EINTR Interrupted function
2126 * exec_activate_image:ENOMEM Not enough space
2127 * exec_activate_image:EFAULT Bad address
2128 * exec_activate_image:ENAMETOOLONG Filename too long
2129 * exec_activate_image:ENOEXEC Executable file format error
2130 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
2131 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
2132 * exec_activate_image:???
2133 * mac_execve_enter:???
2135 * TODO: Expect to need __mac_posix_spawn() at some point...
2136 * Handle posix_spawnattr_t
2137 * Handle posix_spawn_file_actions_t
2140 posix_spawn(proc_t ap
, struct posix_spawn_args
*uap
, int32_t *retval
)
2142 proc_t p
= ap
; /* quiet bogus GCC vfork() warning */
2143 user_addr_t pid
= uap
->pid
;
2144 int ival
[2]; /* dummy retval for setpgid() */
2146 struct image_params
*imgp
;
2147 struct vnode_attr
*vap
;
2148 struct vnode_attr
*origvap
;
2149 struct uthread
*uthread
= 0; /* compiler complains if not set to 0*/
2151 int is_64
= IS_64BIT_PROCESS(p
);
2152 struct vfs_context context
;
2153 struct user__posix_spawn_args_desc px_args
;
2154 struct _posix_spawnattr px_sa
;
2155 _posix_spawn_file_actions_t px_sfap
= NULL
;
2156 _posix_spawn_port_actions_t px_spap
= NULL
;
2157 struct __kern_sigaction vec
;
2158 boolean_t spawn_no_exec
= FALSE
;
2159 boolean_t proc_transit_set
= TRUE
;
2160 boolean_t exec_done
= FALSE
;
2161 int portwatch_count
= 0;
2162 ipc_port_t
* portwatch_ports
= NULL
;
2163 vm_size_t px_sa_offset
= offsetof(struct _posix_spawnattr
, psa_ports
);
2164 task_t new_task
= NULL
;
2165 boolean_t should_release_proc_ref
= FALSE
;
2166 void *inherit
= NULL
;
2168 struct _posix_spawn_persona_info
*px_persona
= NULL
;
2172 * Allocate a big chunk for locals instead of using stack since these
2173 * structures are pretty big.
2175 MALLOC(bufp
, char *, (sizeof(*imgp
) + sizeof(*vap
) + sizeof(*origvap
)), M_TEMP
, M_WAITOK
| M_ZERO
);
2176 imgp
= (struct image_params
*) bufp
;
2181 vap
= (struct vnode_attr
*) (bufp
+ sizeof(*imgp
));
2182 origvap
= (struct vnode_attr
*) (bufp
+ sizeof(*imgp
) + sizeof(*vap
));
2184 /* Initialize the common data in the image_params structure */
2185 imgp
->ip_user_fname
= uap
->path
;
2186 imgp
->ip_user_argv
= uap
->argv
;
2187 imgp
->ip_user_envv
= uap
->envp
;
2188 imgp
->ip_vattr
= vap
;
2189 imgp
->ip_origvattr
= origvap
;
2190 imgp
->ip_vfs_context
= &context
;
2191 imgp
->ip_flags
= (is_64
? IMGPF_WAS_64BIT
: IMGPF_NONE
);
2192 imgp
->ip_seg
= (is_64
? UIO_USERSPACE64
: UIO_USERSPACE32
);
2193 imgp
->ip_mac_return
= 0;
2194 imgp
->ip_px_persona
= NULL
;
2195 imgp
->ip_cs_error
= OS_REASON_NULL
;
2197 if (uap
->adesc
!= USER_ADDR_NULL
) {
2199 error
= copyin(uap
->adesc
, &px_args
, sizeof(px_args
));
2201 struct user32__posix_spawn_args_desc px_args32
;
2203 error
= copyin(uap
->adesc
, &px_args32
, sizeof(px_args32
));
2206 * Convert arguments descriptor from external 32 bit
2207 * representation to internal 64 bit representation
2209 px_args
.attr_size
= px_args32
.attr_size
;
2210 px_args
.attrp
= CAST_USER_ADDR_T(px_args32
.attrp
);
2211 px_args
.file_actions_size
= px_args32
.file_actions_size
;
2212 px_args
.file_actions
= CAST_USER_ADDR_T(px_args32
.file_actions
);
2213 px_args
.port_actions_size
= px_args32
.port_actions_size
;
2214 px_args
.port_actions
= CAST_USER_ADDR_T(px_args32
.port_actions
);
2215 px_args
.mac_extensions_size
= px_args32
.mac_extensions_size
;
2216 px_args
.mac_extensions
= CAST_USER_ADDR_T(px_args32
.mac_extensions
);
2217 px_args
.coal_info_size
= px_args32
.coal_info_size
;
2218 px_args
.coal_info
= CAST_USER_ADDR_T(px_args32
.coal_info
);
2219 px_args
.persona_info_size
= px_args32
.persona_info_size
;
2220 px_args
.persona_info
= CAST_USER_ADDR_T(px_args32
.persona_info
);
2225 if (px_args
.attr_size
!= 0) {
2227 * We are not copying the port_actions pointer,
2228 * because we already have it from px_args.
2229 * This is a bit fragile: <rdar://problem/16427422>
2232 if ((error
= copyin(px_args
.attrp
, &px_sa
, px_sa_offset
) != 0))
2235 bzero( (void *)( (unsigned long) &px_sa
+ px_sa_offset
), sizeof(px_sa
) - px_sa_offset
);
2237 imgp
->ip_px_sa
= &px_sa
;
2239 if (px_args
.file_actions_size
!= 0) {
2240 /* Limit file_actions to allowed number of open files */
2241 int maxfa
= (p
->p_limit
? p
->p_rlimit
[RLIMIT_NOFILE
].rlim_cur
: NOFILE
);
2242 if (px_args
.file_actions_size
< PSF_ACTIONS_SIZE(1) ||
2243 px_args
.file_actions_size
> PSF_ACTIONS_SIZE(maxfa
)) {
2247 MALLOC(px_sfap
, _posix_spawn_file_actions_t
, px_args
.file_actions_size
, M_TEMP
, M_WAITOK
);
2248 if (px_sfap
== NULL
) {
2252 imgp
->ip_px_sfa
= px_sfap
;
2254 if ((error
= copyin(px_args
.file_actions
, px_sfap
,
2255 px_args
.file_actions_size
)) != 0)
2258 /* Verify that the action count matches the struct size */
2259 if (PSF_ACTIONS_SIZE(px_sfap
->psfa_act_count
) != px_args
.file_actions_size
) {
2264 if (px_args
.port_actions_size
!= 0) {
2265 /* Limit port_actions to one page of data */
2266 if (px_args
.port_actions_size
< PS_PORT_ACTIONS_SIZE(1) ||
2267 px_args
.port_actions_size
> PAGE_SIZE
) {
2272 MALLOC(px_spap
, _posix_spawn_port_actions_t
,
2273 px_args
.port_actions_size
, M_TEMP
, M_WAITOK
);
2274 if (px_spap
== NULL
) {
2278 imgp
->ip_px_spa
= px_spap
;
2280 if ((error
= copyin(px_args
.port_actions
, px_spap
,
2281 px_args
.port_actions_size
)) != 0)
2284 /* Verify that the action count matches the struct size */
2285 if (PS_PORT_ACTIONS_SIZE(px_spap
->pspa_count
) != px_args
.port_actions_size
) {
2291 /* copy in the persona info */
2292 if (px_args
.persona_info_size
!= 0 && px_args
.persona_info
!= 0) {
2293 /* for now, we need the exact same struct in user space */
2294 if (px_args
.persona_info_size
!= sizeof(*px_persona
)) {
2299 MALLOC(px_persona
, struct _posix_spawn_persona_info
*, px_args
.persona_info_size
, M_TEMP
, M_WAITOK
|M_ZERO
);
2300 if (px_persona
== NULL
) {
2304 imgp
->ip_px_persona
= px_persona
;
2306 if ((error
= copyin(px_args
.persona_info
, px_persona
,
2307 px_args
.persona_info_size
)) != 0)
2309 if ((error
= spawn_validate_persona(px_persona
)) != 0)
2314 if (px_args
.mac_extensions_size
!= 0) {
2315 if ((error
= spawn_copyin_macpolicyinfo(&px_args
, (_posix_spawn_mac_policy_extensions_t
*)&imgp
->ip_px_smpx
)) != 0)
2318 #endif /* CONFIG_MACF */
2321 /* set uthread to parent */
2322 uthread
= get_bsdthread_info(current_thread());
2325 * <rdar://6640530>; this does not result in a behaviour change
2326 * relative to Leopard, so there should not be any existing code
2327 * which depends on it.
2329 if (uthread
->uu_flag
& UT_VFORK
) {
2335 * If we don't have the extension flag that turns "posix_spawn()"
2336 * into "execve() with options", then we will be creating a new
2337 * process which does not inherit memory from the parent process,
2338 * which is one of the most expensive things about using fork()
2341 if (imgp
->ip_px_sa
== NULL
|| !(px_sa
.psa_flags
& POSIX_SPAWN_SETEXEC
)){
2343 /* Set the new task's coalition, if it is requested. */
2344 coalition_t coal
[COALITION_NUM_TYPES
] = { COALITION_NULL
};
2345 #if CONFIG_COALITIONS
2347 kern_return_t kr
= KERN_SUCCESS
;
2348 struct _posix_spawn_coalition_info coal_info
;
2349 int coal_role
[COALITION_NUM_TYPES
];
2351 if (imgp
->ip_px_sa
== NULL
|| !px_args
.coal_info
)
2354 memset(&coal_info
, 0, sizeof(coal_info
));
2356 if (px_args
.coal_info_size
> sizeof(coal_info
))
2357 px_args
.coal_info_size
= sizeof(coal_info
);
2358 error
= copyin(px_args
.coal_info
,
2359 &coal_info
, px_args
.coal_info_size
);
2364 for (i
= 0; i
< COALITION_NUM_TYPES
; i
++) {
2365 uint64_t cid
= coal_info
.psci_info
[i
].psci_id
;
2368 * don't allow tasks which are not in a
2369 * privileged coalition to spawn processes
2370 * into coalitions other than their own
2372 if (!task_is_in_privileged_coalition(p
->task
, i
)) {
2373 coal_dbg("ERROR: %d not in privilegd "
2374 "coalition of type %d",
2376 spawn_coalitions_release_all(coal
);
2381 coal_dbg("searching for coalition id:%llu", cid
);
2383 * take a reference and activation on the
2384 * coalition to guard against free-while-spawn
2387 coal
[i
] = coalition_find_and_activate_by_id(cid
);
2388 if (coal
[i
] == COALITION_NULL
) {
2389 coal_dbg("could not find coalition id:%llu "
2390 "(perhaps it has been terminated or reaped)", cid
);
2392 * release any other coalition's we
2393 * may have a reference to
2395 spawn_coalitions_release_all(coal
);
2399 if (coalition_type(coal
[i
]) != i
) {
2400 coal_dbg("coalition with id:%lld is not of type:%d"
2401 " (it's type:%d)", cid
, i
, coalition_type(coal
[i
]));
2405 coal_role
[i
] = coal_info
.psci_info
[i
].psci_role
;
2409 if (ncoals
< COALITION_NUM_TYPES
) {
2411 * If the user is attempting to spawn into a subset of
2412 * the known coalition types, then make sure they have
2413 * _at_least_ specified a resource coalition. If not,
2414 * the following fork1() call will implicitly force an
2415 * inheritance from 'p' and won't actually spawn the
2416 * new task into the coalitions the user specified.
2417 * (also the call to coalitions_set_roles will panic)
2419 if (coal
[COALITION_TYPE_RESOURCE
] == COALITION_NULL
) {
2420 spawn_coalitions_release_all(coal
);
2426 #endif /* CONFIG_COALITIONS */
2429 * note that this will implicitly inherit the
2430 * caller's persona (if it exists)
2432 error
= fork1(p
, &imgp
->ip_new_thread
, PROC_CREATE_SPAWN
, coal
);
2433 /* returns a thread and task reference */
2436 new_task
= get_threadtask(imgp
->ip_new_thread
);
2438 #if CONFIG_COALITIONS
2439 /* set the roles of this task within each given coalition */
2441 kr
= coalitions_set_roles(coal
, get_threadtask(imgp
->ip_new_thread
), coal_role
);
2442 if (kr
!= KERN_SUCCESS
)
2446 /* drop our references and activations - fork1() now holds them */
2447 spawn_coalitions_release_all(coal
);
2448 #endif /* CONFIG_COALITIONS */
2452 imgp
->ip_flags
|= IMGPF_SPAWN
; /* spawn w/o exec */
2453 spawn_no_exec
= TRUE
; /* used in later tests */
2457 * If the parent isn't in a persona (launchd), and
2458 * hasn't specified a new persona for the process,
2459 * then we'll put the process into the system persona
2461 * TODO: this will have to be re-worked because as of
2462 * now, without any launchd adoption, the resulting
2463 * xpcproxy process will not have sufficient
2464 * privileges to setuid/gid.
2467 if (!proc_has_persona(p
) && imgp
->ip_px_persona
== NULL
) {
2468 MALLOC(px_persona
, struct _posix_spawn_persona_info
*,
2469 sizeof(*px_persona
), M_TEMP
, M_WAITOK
|M_ZERO
);
2470 if (px_persona
== NULL
) {
2474 px_persona
->pspi_id
= persona_get_id(g_system_persona
);
2475 imgp
->ip_px_persona
= px_persona
;
2478 #endif /* CONFIG_PERSONAS */
2481 * For execve case, create a new task and thread
2482 * which points to current_proc. The current_proc will point
2483 * to the new task after image activation and proc ref drain.
2485 * proc (current_proc) <----- old_task (current_task)
2488 * | ----------------------------------
2490 * --------- new_task (task marked as TF_EXEC_COPY)
2492 * After image activation, the proc will point to the new task
2493 * and would look like following.
2495 * proc (current_proc) <----- old_task (current_task, marked as TPF_DID_EXEC)
2498 * | ----------> new_task
2502 * During exec any transition from new_task -> proc is fine, but don't allow
2503 * transition from proc->task, since it will modify old_task.
2505 imgp
->ip_new_thread
= fork_create_child(current_task(),
2506 NULL
, p
, FALSE
, p
->p_flag
& P_LP64
, TRUE
);
2507 /* task and thread ref returned by fork_create_child */
2508 if (imgp
->ip_new_thread
== NULL
) {
2513 new_task
= get_threadtask(imgp
->ip_new_thread
);
2514 imgp
->ip_flags
|= IMGPF_EXEC
;
2517 if (spawn_no_exec
) {
2518 p
= (proc_t
)get_bsdthreadtask_info(imgp
->ip_new_thread
);
2521 * We had to wait until this point before firing the
2522 * proc:::create probe, otherwise p would not point to the
2525 DTRACE_PROC1(create
, proc_t
, p
);
2529 context
.vc_thread
= imgp
->ip_new_thread
;
2530 context
.vc_ucred
= p
->p_ucred
; /* XXX must NOT be kauth_cred_get() */
2533 * Post fdcopy(), pre exec_handle_sugid() - this is where we want
2534 * to handle the file_actions. Since vfork() also ends up setting
2535 * us into the parent process group, and saved off the signal flags,
2536 * this is also where we want to handle the spawn flags.
2539 /* Has spawn file actions? */
2540 if (imgp
->ip_px_sfa
!= NULL
) {
2542 * The POSIX_SPAWN_CLOEXEC_DEFAULT flag
2543 * is handled in exec_handle_file_actions().
2545 if ((error
= exec_handle_file_actions(imgp
,
2546 imgp
->ip_px_sa
!= NULL
? px_sa
.psa_flags
: 0)) != 0)
2550 /* Has spawn port actions? */
2551 if (imgp
->ip_px_spa
!= NULL
) {
2552 boolean_t is_adaptive
= FALSE
;
2553 boolean_t portwatch_present
= FALSE
;
2555 /* Will this process become adaptive? The apptype isn't ready yet, so we can't look there. */
2556 if (imgp
->ip_px_sa
!= NULL
&& px_sa
.psa_apptype
== POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE
)
2561 * Allocate a place to store the ports we want to bind to the new task
2562 * We can't bind them until after the apptype is set.
2564 if (px_spap
->pspa_count
!= 0 && is_adaptive
) {
2565 portwatch_count
= px_spap
->pspa_count
;
2566 MALLOC(portwatch_ports
, ipc_port_t
*, (sizeof(ipc_port_t
) * portwatch_count
), M_TEMP
, M_WAITOK
| M_ZERO
);
2568 portwatch_ports
= NULL
;
2571 if ((error
= exec_handle_port_actions(imgp
, &portwatch_present
, portwatch_ports
)) != 0)
2574 if (portwatch_present
== FALSE
&& portwatch_ports
!= NULL
) {
2575 FREE(portwatch_ports
, M_TEMP
);
2576 portwatch_ports
= NULL
;
2577 portwatch_count
= 0;
2581 /* Has spawn attr? */
2582 if (imgp
->ip_px_sa
!= NULL
) {
2584 * Set the process group ID of the child process; this has
2585 * to happen before the image activation.
2587 if (px_sa
.psa_flags
& POSIX_SPAWN_SETPGROUP
) {
2588 struct setpgid_args spga
;
2589 spga
.pid
= p
->p_pid
;
2590 spga
.pgid
= px_sa
.psa_pgroup
;
2592 * Effectively, call setpgid() system call; works
2593 * because there are no pointer arguments.
2595 if((error
= setpgid(p
, &spga
, ival
)) != 0)
2600 * Reset UID/GID to parent's RUID/RGID; This works only
2601 * because the operation occurs *after* the vfork() and
2602 * before the call to exec_handle_sugid() by the image
2603 * activator called from exec_activate_image(). POSIX
2604 * requires that any setuid/setgid bits on the process
2605 * image will take precedence over the spawn attributes
2608 * Modifications to p_ucred must be guarded using the
2609 * proc's ucred lock. This prevents others from accessing
2610 * a garbage credential.
2612 while (px_sa
.psa_flags
& POSIX_SPAWN_RESETIDS
) {
2613 kauth_cred_t my_cred
= kauth_cred_proc_ref(p
);
2614 kauth_cred_t my_new_cred
= kauth_cred_setuidgid(my_cred
, kauth_cred_getruid(my_cred
), kauth_cred_getrgid(my_cred
));
2616 if (my_cred
== my_new_cred
) {
2617 kauth_cred_unref(&my_cred
);
2621 /* update cred on proc */
2624 if (p
->p_ucred
!= my_cred
) {
2625 proc_ucred_unlock(p
);
2626 kauth_cred_unref(&my_new_cred
);
2630 /* donate cred reference on my_new_cred to p->p_ucred */
2631 p
->p_ucred
= my_new_cred
;
2632 PROC_UPDATE_CREDS_ONPROC(p
);
2633 proc_ucred_unlock(p
);
2635 /* drop additional reference that was taken on the previous cred */
2636 kauth_cred_unref(&my_cred
);
2640 if (spawn_no_exec
&& imgp
->ip_px_persona
!= NULL
) {
2642 * If we were asked to spawn a process into a new persona,
2643 * do the credential switch now (which may override the UID/GID
2644 * inherit done just above). It's important to do this switch
2645 * before image activation both for reasons stated above, and
2646 * to ensure that the new persona has access to the image/file
2649 error
= spawn_persona_adopt(p
, imgp
->ip_px_persona
);
2653 #endif /* CONFIG_PERSONAS */
2656 * Disable ASLR for the spawned process.
2658 * But only do so if we are not embedded + RELEASE.
2659 * While embedded allows for a boot-arg (-disable_aslr)
2660 * to deal with this (which itself is only honored on
2661 * DEVELOPMENT or DEBUG builds of xnu), it is often
2662 * useful or necessary to disable ASLR on a per-process
2663 * basis for unit testing and debugging.
2665 if (px_sa
.psa_flags
& _POSIX_SPAWN_DISABLE_ASLR
)
2666 OSBitOrAtomic(P_DISABLE_ASLR
, &p
->p_flag
);
2667 #endif /* !SECURE_KERNEL */
2670 * Forcibly disallow execution from data pages for the spawned process
2671 * even if it would otherwise be permitted by the architecture default.
2673 if (px_sa
.psa_flags
& _POSIX_SPAWN_ALLOW_DATA_EXEC
)
2674 imgp
->ip_flags
|= IMGPF_ALLOW_DATA_EXEC
;
2678 * Disable ASLR during image activation. This occurs either if the
2679 * _POSIX_SPAWN_DISABLE_ASLR attribute was found above or if
2680 * P_DISABLE_ASLR was inherited from the parent process.
2682 if (p
->p_flag
& P_DISABLE_ASLR
)
2683 imgp
->ip_flags
|= IMGPF_DISABLE_ASLR
;
2686 * Clear transition flag so we won't hang if exec_activate_image() causes
2687 * an automount (and launchd does a proc sysctl to service it).
2689 * <rdar://problem/6848672>, <rdar://problem/5959568>.
2691 if (spawn_no_exec
) {
2692 proc_transend(p
, 0);
2693 proc_transit_set
= 0;
2696 #if MAC_SPAWN /* XXX */
2697 if (uap
->mac_p
!= USER_ADDR_NULL
) {
2698 error
= mac_execve_enter(uap
->mac_p
, imgp
);
2705 * Activate the image
2707 error
= exec_activate_image(imgp
);
2709 if (error
== 0 && !spawn_no_exec
) {
2710 p
= proc_exec_switch_task(p
, current_task(), new_task
, imgp
->ip_new_thread
);
2711 /* proc ref returned */
2712 should_release_proc_ref
= TRUE
;
2716 /* process completed the exec */
2718 } else if (error
== -1) {
2719 /* Image not claimed by any activator? */
2724 * If we have a spawn attr, and it contains signal related flags,
2725 * the we need to process them in the "context" of the new child
2726 * process, so we have to process it following image activation,
2727 * prior to making the thread runnable in user space. This is
2728 * necessitated by some signal information being per-thread rather
2729 * than per-process, and we don't have the new allocation in hand
2730 * until after the image is activated.
2732 if (!error
&& imgp
->ip_px_sa
!= NULL
) {
2733 thread_t child_thread
= imgp
->ip_new_thread
;
2734 uthread_t child_uthread
= get_bsdthread_info(child_thread
);
2737 * Mask a list of signals, instead of them being unmasked, if
2738 * they were unmasked in the parent; note that some signals
2741 if (px_sa
.psa_flags
& POSIX_SPAWN_SETSIGMASK
)
2742 child_uthread
->uu_sigmask
= (px_sa
.psa_sigmask
& ~sigcantmask
);
2744 * Default a list of signals instead of ignoring them, if
2745 * they were ignored in the parent. Note that we pass
2746 * spawn_no_exec to setsigvec() to indicate that we called
2747 * fork1() and therefore do not need to call proc_signalstart()
2750 if (px_sa
.psa_flags
& POSIX_SPAWN_SETSIGDEF
) {
2751 vec
.sa_handler
= SIG_DFL
;
2755 for (sig
= 1; sig
< NSIG
; sig
++)
2756 if (px_sa
.psa_sigdefault
& (1 << (sig
-1))) {
2757 error
= setsigvec(p
, child_thread
, sig
, &vec
, spawn_no_exec
);
2762 * Activate the CPU usage monitor, if requested. This is done via a task-wide, per-thread CPU
2763 * usage limit, which will generate a resource exceeded exception if any one thread exceeds the
2766 * Userland gives us interval in seconds, and the kernel SPI expects nanoseconds.
2768 if (px_sa
.psa_cpumonitor_percent
!= 0) {
2770 * Always treat a CPU monitor activation coming from spawn as entitled. Requiring
2771 * an entitlement to configure the monitor a certain way seems silly, since
2772 * whomever is turning it on could just as easily choose not to do so.
2774 error
= proc_set_task_ruse_cpu(p
->task
,
2775 TASK_POLICY_RESOURCE_ATTRIBUTE_NOTIFY_EXC
,
2776 px_sa
.psa_cpumonitor_percent
,
2777 px_sa
.psa_cpumonitor_interval
* NSEC_PER_SEC
,
2785 /* reset delay idle sleep status if set */
2786 if ((p
->p_flag
& P_DELAYIDLESLEEP
) == P_DELAYIDLESLEEP
)
2787 OSBitAndAtomic(~((uint32_t)P_DELAYIDLESLEEP
), &p
->p_flag
);
2788 /* upon successful spawn, re/set the proc control state */
2789 if (imgp
->ip_px_sa
!= NULL
) {
2790 switch (px_sa
.psa_pcontrol
) {
2791 case POSIX_SPAWN_PCONTROL_THROTTLE
:
2792 p
->p_pcaction
= P_PCTHROTTLE
;
2794 case POSIX_SPAWN_PCONTROL_SUSPEND
:
2795 p
->p_pcaction
= P_PCSUSP
;
2797 case POSIX_SPAWN_PCONTROL_KILL
:
2798 p
->p_pcaction
= P_PCKILL
;
2800 case POSIX_SPAWN_PCONTROL_NONE
:
2806 exec_resettextvp(p
, imgp
);
2808 #if CONFIG_MEMORYSTATUS
2809 /* Has jetsam attributes? */
2810 if (imgp
->ip_px_sa
!= NULL
&& (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_SET
)) {
2812 * With 2-level high-water-mark support, POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND is no
2813 * longer relevant, as background limits are described via the inactive limit slots.
2814 * At the kernel layer, the flag is ignored.
2816 * That said, however, if the POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND is passed in,
2817 * we attempt to mimic previous behavior by forcing the BG limit data into the
2818 * inactive/non-fatal mode and force the active slots to hold system_wide/fatal mode.
2819 * The kernel layer will flag this mapping.
2821 if (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND
) {
2822 memorystatus_update(p
, px_sa
.psa_priority
, 0,
2823 (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY
),
2826 px_sa
.psa_memlimit_inactive
, FALSE
,
2827 (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND
));
2829 memorystatus_update(p
, px_sa
.psa_priority
, 0,
2830 (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY
),
2832 px_sa
.psa_memlimit_active
,
2833 (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_MEMLIMIT_ACTIVE_FATAL
),
2834 px_sa
.psa_memlimit_inactive
,
2835 (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_MEMLIMIT_INACTIVE_FATAL
),
2836 (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND
));
2840 #endif /* CONFIG_MEMORYSTATUS */
2844 * If we successfully called fork1(), we always need to do this;
2845 * we identify this case by noting the IMGPF_SPAWN flag. This is
2846 * because we come back from that call with signals blocked in the
2847 * child, and we have to unblock them, but we want to wait until
2848 * after we've performed any spawn actions. This has to happen
2849 * before check_for_signature(), which uses psignal.
2851 if (spawn_no_exec
) {
2852 if (proc_transit_set
)
2853 proc_transend(p
, 0);
2856 * Drop the signal lock on the child which was taken on our
2857 * behalf by forkproc()/cloneproc() to prevent signals being
2858 * received by the child in a partially constructed state.
2860 proc_signalend(p
, 0);
2862 /* flag the 'fork' has occurred */
2863 proc_knote(p
->p_pptr
, NOTE_FORK
| p
->p_pid
);
2864 /* then flag exec has occurred */
2865 /* notify only if it has not failed due to FP Key error */
2866 if ((p
->p_lflag
& P_LTERM_DECRYPTFAIL
) == 0)
2867 proc_knote(p
, NOTE_EXEC
);
2872 * We need to initialize the bank context behind the protection of
2873 * the proc_trans lock to prevent a race with exit. We can't do this during
2874 * exec_activate_image because task_bank_init checks entitlements that
2875 * aren't loaded until subsequent calls (including exec_resettextvp).
2877 error
= proc_transstart(p
, 0, 0);
2880 task_bank_init(get_threadtask(imgp
->ip_new_thread
));
2881 proc_transend(p
, 0);
2885 /* Inherit task role from old task to new task for exec */
2886 if (error
== 0 && !spawn_no_exec
) {
2887 proc_inherit_task_role(get_threadtask(imgp
->ip_new_thread
), current_task());
2891 * Apply the spawnattr policy, apptype (which primes the task for importance donation),
2892 * and bind any portwatch ports to the new task.
2893 * This must be done after the exec so that the child's thread is ready,
2894 * and after the in transit state has been released, because priority is
2895 * dropped here so we need to be prepared for a potentially long preemption interval
2897 * TODO: Consider splitting this up into separate phases
2899 if (error
== 0 && imgp
->ip_px_sa
!= NULL
) {
2900 struct _posix_spawnattr
*psa
= (struct _posix_spawnattr
*) imgp
->ip_px_sa
;
2902 exec_handle_spawnattr_policy(p
, psa
->psa_apptype
, psa
->psa_qos_clamp
, psa
->psa_darwin_role
,
2903 portwatch_ports
, portwatch_count
);
2907 * Need to transfer pending watch port boosts to the new task while still making
2908 * sure that the old task remains in the importance linkage. Create an importance
2909 * linkage from old task to new task, then switch the task importance base
2910 * of old task and new task. After the switch the port watch boost will be
2911 * boosting the new task and new task will be donating importance to old task.
2913 if (error
== 0 && task_did_exec(current_task())) {
2914 inherit
= ipc_importance_exec_switch_task(current_task(), get_threadtask(imgp
->ip_new_thread
));
2917 /* Apply the main thread qos */
2919 thread_t main_thread
= imgp
->ip_new_thread
;
2921 task_set_main_thread_qos(get_threadtask(imgp
->ip_new_thread
), main_thread
);
2925 * Release any ports we kept around for binding to the new task
2926 * We need to release the rights even if the posix_spawn has failed.
2928 if (portwatch_ports
!= NULL
) {
2929 for (int i
= 0; i
< portwatch_count
; i
++) {
2930 ipc_port_t port
= NULL
;
2931 if ((port
= portwatch_ports
[i
]) != NULL
) {
2932 ipc_port_release_send(port
);
2935 FREE(portwatch_ports
, M_TEMP
);
2936 portwatch_ports
= NULL
;
2937 portwatch_count
= 0;
2941 * We have to delay operations which might throw a signal until after
2942 * the signals have been unblocked; however, we want that to happen
2943 * after exec_resettextvp() so that the textvp is correct when they
2947 error
= check_for_signature(p
, imgp
);
2950 * Pay for our earlier safety; deliver the delayed signals from
2951 * the incomplete spawn process now that it's complete.
2953 if (imgp
!= NULL
&& spawn_no_exec
&& (p
->p_lflag
& P_LTRACED
)) {
2954 psignal_vfork(p
, p
->task
, imgp
->ip_new_thread
, SIGTRAP
);
2957 if (error
== 0 && !spawn_no_exec
)
2958 KDBG(BSDDBG_CODE(DBG_BSD_PROC
,BSD_PROC_EXEC
),
2965 vnode_put(imgp
->ip_vp
);
2966 if (imgp
->ip_scriptvp
)
2967 vnode_put(imgp
->ip_scriptvp
);
2968 if (imgp
->ip_strings
)
2969 execargs_free(imgp
);
2970 if (imgp
->ip_px_sfa
!= NULL
)
2971 FREE(imgp
->ip_px_sfa
, M_TEMP
);
2972 if (imgp
->ip_px_spa
!= NULL
)
2973 FREE(imgp
->ip_px_spa
, M_TEMP
);
2975 if (imgp
->ip_px_persona
!= NULL
)
2976 FREE(imgp
->ip_px_persona
, M_TEMP
);
2979 if (imgp
->ip_px_smpx
!= NULL
)
2980 spawn_free_macpolicyinfo(imgp
->ip_px_smpx
);
2981 if (imgp
->ip_execlabelp
)
2982 mac_cred_label_free(imgp
->ip_execlabelp
);
2983 if (imgp
->ip_scriptlabelp
)
2984 mac_vnode_label_free(imgp
->ip_scriptlabelp
);
2985 if (imgp
->ip_cs_error
!= OS_REASON_NULL
) {
2986 os_reason_free(imgp
->ip_cs_error
);
2987 imgp
->ip_cs_error
= OS_REASON_NULL
;
2993 if (spawn_no_exec
) {
2995 * In the original DTrace reference implementation,
2996 * posix_spawn() was a libc routine that just
2997 * did vfork(2) then exec(2). Thus the proc::: probes
2998 * are very fork/exec oriented. The details of this
2999 * in-kernel implementation of posix_spawn() is different
3000 * (while producing the same process-observable effects)
3001 * particularly w.r.t. errors, and which thread/process
3002 * is constructing what on behalf of whom.
3005 DTRACE_PROC1(spawn__failure
, int, error
);
3007 DTRACE_PROC(spawn__success
);
3009 * Some DTrace scripts, e.g. newproc.d in
3010 * /usr/bin, rely on the the 'exec-success'
3011 * probe being fired in the child after the
3012 * new process image has been constructed
3013 * in order to determine the associated pid.
3015 * So, even though the parent built the image
3016 * here, for compatibility, mark the new thread
3017 * so 'exec-success' fires on it as it leaves
3020 dtrace_thread_didexec(imgp
->ip_new_thread
);
3024 DTRACE_PROC1(exec__failure
, int, error
);
3026 DTRACE_PROC(exec__success
);
3030 if ((dtrace_proc_waitfor_hook
= dtrace_proc_waitfor_exec_ptr
) != NULL
) {
3031 (*dtrace_proc_waitfor_hook
)(p
);
3035 * exec-success dtrace probe fired, clear bsd_info from
3036 * old task if it did exec.
3038 if (task_did_exec(current_task())) {
3039 set_bsdtask_info(current_task(), NULL
);
3042 /* clear bsd_info from new task and terminate it if exec failed */
3043 if (new_task
!= NULL
&& task_is_exec_copy(new_task
)) {
3044 set_bsdtask_info(new_task
, NULL
);
3045 task_terminate_internal(new_task
);
3048 /* Return to both the parent and the child? */
3049 if (imgp
!= NULL
&& spawn_no_exec
) {
3051 * If the parent wants the pid, copy it out
3053 if (pid
!= USER_ADDR_NULL
)
3054 (void)suword(pid
, p
->p_pid
);
3058 * If we had an error, perform an internal reap ; this is
3059 * entirely safe, as we have a real process backing us.
3063 p
->p_listflag
|= P_LIST_DEADPARENT
;
3066 /* make sure no one else has killed it off... */
3067 if (p
->p_stat
!= SZOMB
&& p
->exit_thread
== NULL
) {
3068 p
->exit_thread
= current_thread();
3070 exit1(p
, 1, (int *)NULL
);
3072 /* someone is doing it for us; just skip it */
3079 * Do not terminate the current task, if proc_exec_switch_task did not
3080 * switch the tasks, terminating the current task without the switch would
3081 * result in loosing the SIGKILL status.
3083 if (task_did_exec(current_task())) {
3084 /* Terminate the current task, since exec will start in new task */
3085 task_terminate_internal(current_task());
3088 /* Release the thread ref returned by fork_create_child/fork1 */
3089 if (imgp
!= NULL
&& imgp
->ip_new_thread
) {
3090 /* wake up the new thread */
3091 task_clear_return_wait(get_threadtask(imgp
->ip_new_thread
));
3092 thread_deallocate(imgp
->ip_new_thread
);
3093 imgp
->ip_new_thread
= NULL
;
3096 /* Release the ref returned by fork_create_child/fork1 */
3098 task_deallocate(new_task
);
3102 if (should_release_proc_ref
) {
3110 if (inherit
!= NULL
) {
3111 ipc_importance_release(inherit
);
3118 * proc_exec_switch_task
3120 * Parameters: p proc
3121 * old_task task before exec
3122 * new_task task after exec
3123 * new_thread thread in new task
3127 * Note: The function will switch the task pointer of proc
3128 * from old task to new task. The switch needs to happen
3129 * after draining all proc refs and inside a proc translock.
3130 * In the case of failure to switch the task, which might happen
3131 * if the process received a SIGKILL or jetsam killed it, it will make
3132 * sure that the new tasks terminates. User proc ref returned
3135 * This function is called after point of no return, in the case
3136 * failure to switch, it will terminate the new task and swallow the
3137 * error and let the terminated process complete exec and die.
3140 proc_exec_switch_task(proc_t p
, task_t old_task
, task_t new_task
, thread_t new_thread
)
3143 boolean_t task_active
;
3144 boolean_t proc_active
;
3145 boolean_t thread_active
;
3146 thread_t old_thread
= current_thread();
3149 * Switch the task pointer of proc to new task.
3150 * Before switching the task, wait for proc_refdrain.
3151 * After the switch happens, the proc can disappear,
3152 * take a ref before it disappears.
3154 p
= proc_refdrain_with_refwait(p
, TRUE
);
3155 /* extra proc ref returned to the caller */
3157 assert(get_threadtask(new_thread
) == new_task
);
3158 task_active
= task_is_active(new_task
);
3160 /* Take the proc_translock to change the task ptr */
3162 proc_active
= !(p
->p_lflag
& P_LEXIT
);
3164 /* Check if the current thread is not aborted due to SIGKILL */
3165 thread_active
= thread_is_active(old_thread
);
3168 * Do not switch the task if the new task or proc is already terminated
3169 * as a result of error in exec past point of no return
3171 if (proc_active
&& task_active
&& thread_active
) {
3172 error
= proc_transstart(p
, 1, 0);
3174 uthread_t new_uthread
= get_bsdthread_info(new_thread
);
3175 uthread_t old_uthread
= get_bsdthread_info(current_thread());
3178 * bsd_info of old_task will get cleared in execve and posix_spawn
3179 * after firing exec-success/error dtrace probe.
3183 /* Copy the signal state, dtrace state and set bsd ast on new thread */
3184 act_set_astbsd(new_thread
);
3185 new_uthread
->uu_siglist
= old_uthread
->uu_siglist
;
3186 new_uthread
->uu_sigwait
= old_uthread
->uu_sigwait
;
3187 new_uthread
->uu_sigmask
= old_uthread
->uu_sigmask
;
3188 new_uthread
->uu_oldmask
= old_uthread
->uu_oldmask
;
3189 new_uthread
->uu_vforkmask
= old_uthread
->uu_vforkmask
;
3190 new_uthread
->uu_exit_reason
= old_uthread
->uu_exit_reason
;
3192 new_uthread
->t_dtrace_sig
= old_uthread
->t_dtrace_sig
;
3193 new_uthread
->t_dtrace_stop
= old_uthread
->t_dtrace_stop
;
3194 new_uthread
->t_dtrace_resumepid
= old_uthread
->t_dtrace_resumepid
;
3195 assert(new_uthread
->t_dtrace_scratch
== NULL
);
3196 new_uthread
->t_dtrace_scratch
= old_uthread
->t_dtrace_scratch
;
3198 old_uthread
->t_dtrace_sig
= 0;
3199 old_uthread
->t_dtrace_stop
= 0;
3200 old_uthread
->t_dtrace_resumepid
= 0;
3201 old_uthread
->t_dtrace_scratch
= NULL
;
3203 /* Copy the resource accounting info */
3204 thread_copy_resource_info(new_thread
, current_thread());
3206 /* Clear the exit reason and signal state on old thread */
3207 old_uthread
->uu_exit_reason
= NULL
;
3208 old_uthread
->uu_siglist
= 0;
3210 /* Add the new uthread to proc uthlist and remove the old one */
3211 TAILQ_INSERT_TAIL(&p
->p_uthlist
, new_uthread
, uu_list
);
3212 TAILQ_REMOVE(&p
->p_uthlist
, old_uthread
, uu_list
);
3214 task_set_did_exec_flag(old_task
);
3215 task_clear_exec_copy_flag(new_task
);
3217 proc_transend(p
, 1);
3224 if (error
!= 0 || !task_active
|| !proc_active
|| !thread_active
) {
3225 task_terminate_internal(new_task
);
3234 * Parameters: uap->fname File name to exec
3235 * uap->argp Argument list
3236 * uap->envp Environment list
3238 * Returns: 0 Success
3239 * __mac_execve:EINVAL Invalid argument
3240 * __mac_execve:ENOTSUP Invalid argument
3241 * __mac_execve:EACCES Permission denied
3242 * __mac_execve:EINTR Interrupted function
3243 * __mac_execve:ENOMEM Not enough space
3244 * __mac_execve:EFAULT Bad address
3245 * __mac_execve:ENAMETOOLONG Filename too long
3246 * __mac_execve:ENOEXEC Executable file format error
3247 * __mac_execve:ETXTBSY Text file busy [misuse of error code]
3250 * TODO: Dynamic linker header address on stack is copied via suword()
3254 execve(proc_t p
, struct execve_args
*uap
, int32_t *retval
)
3256 struct __mac_execve_args muap
;
3259 memoryshot(VM_EXECVE
, DBG_FUNC_NONE
);
3261 muap
.fname
= uap
->fname
;
3262 muap
.argp
= uap
->argp
;
3263 muap
.envp
= uap
->envp
;
3264 muap
.mac_p
= USER_ADDR_NULL
;
3265 err
= __mac_execve(p
, &muap
, retval
);
3273 * Parameters: uap->fname File name to exec
3274 * uap->argp Argument list
3275 * uap->envp Environment list
3276 * uap->mac_p MAC label supplied by caller
3278 * Returns: 0 Success
3279 * EINVAL Invalid argument
3280 * ENOTSUP Not supported
3281 * ENOEXEC Executable file format error
3282 * exec_activate_image:EINVAL Invalid argument
3283 * exec_activate_image:EACCES Permission denied
3284 * exec_activate_image:EINTR Interrupted function
3285 * exec_activate_image:ENOMEM Not enough space
3286 * exec_activate_image:EFAULT Bad address
3287 * exec_activate_image:ENAMETOOLONG Filename too long
3288 * exec_activate_image:ENOEXEC Executable file format error
3289 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
3290 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
3291 * exec_activate_image:???
3292 * mac_execve_enter:???
3294 * TODO: Dynamic linker header address on stack is copied via suword()
3297 __mac_execve(proc_t p
, struct __mac_execve_args
*uap
, int32_t *retval
)
3300 struct image_params
*imgp
;
3301 struct vnode_attr
*vap
;
3302 struct vnode_attr
*origvap
;
3304 int is_64
= IS_64BIT_PROCESS(p
);
3305 struct vfs_context context
;
3306 struct uthread
*uthread
;
3307 task_t new_task
= NULL
;
3308 boolean_t should_release_proc_ref
= FALSE
;
3309 boolean_t exec_done
= FALSE
;
3310 boolean_t in_vfexec
= FALSE
;
3311 void *inherit
= NULL
;
3313 context
.vc_thread
= current_thread();
3314 context
.vc_ucred
= kauth_cred_proc_ref(p
); /* XXX must NOT be kauth_cred_get() */
3316 /* Allocate a big chunk for locals instead of using stack since these
3317 * structures a pretty big.
3319 MALLOC(bufp
, char *, (sizeof(*imgp
) + sizeof(*vap
) + sizeof(*origvap
)), M_TEMP
, M_WAITOK
| M_ZERO
);
3320 imgp
= (struct image_params
*) bufp
;
3323 goto exit_with_error
;
3325 vap
= (struct vnode_attr
*) (bufp
+ sizeof(*imgp
));
3326 origvap
= (struct vnode_attr
*) (bufp
+ sizeof(*imgp
) + sizeof(*vap
));
3328 /* Initialize the common data in the image_params structure */
3329 imgp
->ip_user_fname
= uap
->fname
;
3330 imgp
->ip_user_argv
= uap
->argp
;
3331 imgp
->ip_user_envv
= uap
->envp
;
3332 imgp
->ip_vattr
= vap
;
3333 imgp
->ip_origvattr
= origvap
;
3334 imgp
->ip_vfs_context
= &context
;
3335 imgp
->ip_flags
= (is_64
? IMGPF_WAS_64BIT
: IMGPF_NONE
) | ((p
->p_flag
& P_DISABLE_ASLR
) ? IMGPF_DISABLE_ASLR
: IMGPF_NONE
);
3336 imgp
->ip_seg
= (is_64
? UIO_USERSPACE64
: UIO_USERSPACE32
);
3337 imgp
->ip_mac_return
= 0;
3338 imgp
->ip_cs_error
= OS_REASON_NULL
;
3340 uthread
= get_bsdthread_info(current_thread());
3341 if (uthread
->uu_flag
& UT_VFORK
) {
3342 imgp
->ip_flags
|= IMGPF_VFORK_EXEC
;
3345 imgp
->ip_flags
|= IMGPF_EXEC
;
3348 * For execve case, create a new task and thread
3349 * which points to current_proc. The current_proc will point
3350 * to the new task after image activation and proc ref drain.
3352 * proc (current_proc) <----- old_task (current_task)
3355 * | ----------------------------------
3357 * --------- new_task (task marked as TF_EXEC_COPY)
3359 * After image activation, the proc will point to the new task
3360 * and would look like following.
3362 * proc (current_proc) <----- old_task (current_task, marked as TPF_DID_EXEC)
3365 * | ----------> new_task
3369 * During exec any transition from new_task -> proc is fine, but don't allow
3370 * transition from proc->task, since it will modify old_task.
3372 imgp
->ip_new_thread
= fork_create_child(current_task(),
3373 NULL
, p
, FALSE
, p
->p_flag
& P_LP64
, TRUE
);
3374 /* task and thread ref returned by fork_create_child */
3375 if (imgp
->ip_new_thread
== NULL
) {
3377 goto exit_with_error
;
3380 new_task
= get_threadtask(imgp
->ip_new_thread
);
3381 context
.vc_thread
= imgp
->ip_new_thread
;
3385 if (uap
->mac_p
!= USER_ADDR_NULL
) {
3386 error
= mac_execve_enter(uap
->mac_p
, imgp
);
3388 kauth_cred_unref(&context
.vc_ucred
);
3389 goto exit_with_error
;
3394 error
= exec_activate_image(imgp
);
3395 /* thread and task ref returned for vfexec case */
3397 if (imgp
->ip_new_thread
!= NULL
) {
3399 * task reference might be returned by exec_activate_image
3402 new_task
= get_threadtask(imgp
->ip_new_thread
);
3405 if (!error
&& !in_vfexec
) {
3406 p
= proc_exec_switch_task(p
, current_task(), new_task
, imgp
->ip_new_thread
);
3407 /* proc ref returned */
3408 should_release_proc_ref
= TRUE
;
3411 kauth_cred_unref(&context
.vc_ucred
);
3413 /* Image not claimed by any activator? */
3419 assert(imgp
->ip_new_thread
!= NULL
);
3421 exec_resettextvp(p
, imgp
);
3422 error
= check_for_signature(p
, imgp
);
3424 if (imgp
->ip_vp
!= NULLVP
)
3425 vnode_put(imgp
->ip_vp
);
3426 if (imgp
->ip_scriptvp
!= NULLVP
)
3427 vnode_put(imgp
->ip_scriptvp
);
3428 if (imgp
->ip_strings
)
3429 execargs_free(imgp
);
3431 if (imgp
->ip_execlabelp
)
3432 mac_cred_label_free(imgp
->ip_execlabelp
);
3433 if (imgp
->ip_scriptlabelp
)
3434 mac_vnode_label_free(imgp
->ip_scriptlabelp
);
3436 if (imgp
->ip_cs_error
!= OS_REASON_NULL
) {
3437 os_reason_free(imgp
->ip_cs_error
);
3438 imgp
->ip_cs_error
= OS_REASON_NULL
;
3443 * We need to initialize the bank context behind the protection of
3444 * the proc_trans lock to prevent a race with exit. We can't do this during
3445 * exec_activate_image because task_bank_init checks entitlements that
3446 * aren't loaded until subsequent calls (including exec_resettextvp).
3448 error
= proc_transstart(p
, 0, 0);
3452 task_bank_init(get_threadtask(imgp
->ip_new_thread
));
3453 proc_transend(p
, 0);
3455 /* Sever any extant thread affinity */
3456 thread_affinity_exec(current_thread());
3458 /* Inherit task role from old task to new task for exec */
3460 proc_inherit_task_role(get_threadtask(imgp
->ip_new_thread
), current_task());
3463 thread_t main_thread
= imgp
->ip_new_thread
;
3465 task_set_main_thread_qos(new_task
, main_thread
);
3467 DTRACE_PROC(exec__success
);
3470 if ((dtrace_proc_waitfor_hook
= dtrace_proc_waitfor_exec_ptr
) != NULL
)
3471 (*dtrace_proc_waitfor_hook
)(p
);
3475 vfork_return(p
, retval
, p
->p_pid
);
3478 DTRACE_PROC1(exec__failure
, int, error
);
3484 * exec-success dtrace probe fired, clear bsd_info from
3485 * old task if it did exec.
3487 if (task_did_exec(current_task())) {
3488 set_bsdtask_info(current_task(), NULL
);
3491 /* clear bsd_info from new task and terminate it if exec failed */
3492 if (new_task
!= NULL
&& task_is_exec_copy(new_task
)) {
3493 set_bsdtask_info(new_task
, NULL
);
3494 task_terminate_internal(new_task
);
3498 * Need to transfer pending watch port boosts to the new task while still making
3499 * sure that the old task remains in the importance linkage. Create an importance
3500 * linkage from old task to new task, then switch the task importance base
3501 * of old task and new task. After the switch the port watch boost will be
3502 * boosting the new task and new task will be donating importance to old task.
3504 if (error
== 0 && task_did_exec(current_task())) {
3505 inherit
= ipc_importance_exec_switch_task(current_task(), get_threadtask(imgp
->ip_new_thread
));
3510 * Do not terminate the current task, if proc_exec_switch_task did not
3511 * switch the tasks, terminating the current task without the switch would
3512 * result in loosing the SIGKILL status.
3514 if (task_did_exec(current_task())) {
3515 /* Terminate the current task, since exec will start in new task */
3516 task_terminate_internal(current_task());
3519 /* Release the thread ref returned by fork_create_child */
3520 if (imgp
->ip_new_thread
) {
3521 /* wake up the new exec thread */
3522 task_clear_return_wait(get_threadtask(imgp
->ip_new_thread
));
3523 thread_deallocate(imgp
->ip_new_thread
);
3524 imgp
->ip_new_thread
= NULL
;
3528 /* Release the ref returned by fork_create_child */
3530 task_deallocate(new_task
);
3534 if (should_release_proc_ref
) {
3542 if (inherit
!= NULL
) {
3543 ipc_importance_release(inherit
);
3553 * Description: Copy a pointer in from user space to a user_addr_t in kernel
3554 * space, based on 32/64 bitness of the user space
3556 * Parameters: froma User space address
3557 * toptr Address of kernel space user_addr_t
3558 * ptr_size 4/8, based on 'froma' address space
3560 * Returns: 0 Success
3561 * EFAULT Bad 'froma'
3564 * *ptr_size Modified
3567 copyinptr(user_addr_t froma
, user_addr_t
*toptr
, int ptr_size
)
3571 if (ptr_size
== 4) {
3572 /* 64 bit value containing 32 bit address */
3575 error
= copyin(froma
, &i
, 4);
3576 *toptr
= CAST_USER_ADDR_T(i
); /* SAFE */
3578 error
= copyin(froma
, toptr
, 8);
3587 * Description: Copy a pointer out from a user_addr_t in kernel space to
3588 * user space, based on 32/64 bitness of the user space
3590 * Parameters: ua User space address to copy to
3591 * ptr Address of kernel space user_addr_t
3592 * ptr_size 4/8, based on 'ua' address space
3594 * Returns: 0 Success
3599 copyoutptr(user_addr_t ua
, user_addr_t ptr
, int ptr_size
)
3603 if (ptr_size
== 4) {
3604 /* 64 bit value containing 32 bit address */
3605 unsigned int i
= CAST_DOWN_EXPLICIT(unsigned int,ua
); /* SAFE */
3607 error
= copyout(&i
, ptr
, 4);
3609 error
= copyout(&ua
, ptr
, 8);
3616 * exec_copyout_strings
3618 * Copy out the strings segment to user space. The strings segment is put
3619 * on a preinitialized stack frame.
3621 * Parameters: struct image_params * the image parameter block
3622 * int * a pointer to the stack offset variable
3624 * Returns: 0 Success
3628 * (*stackp) The stack offset, modified
3630 * Note: The strings segment layout is backward, from the beginning
3631 * of the top of the stack to consume the minimal amount of
3632 * space possible; the returned stack pointer points to the
3633 * end of the area consumed (stacks grow downward).
3635 * argc is an int; arg[i] are pointers; env[i] are pointers;
3636 * the 0's are (void *)NULL's
3638 * The stack frame layout is:
3640 * +-------------+ <- p->user_stack
3681 * sp-> +-------------+
3683 * Although technically a part of the STRING AREA, we treat the PATH AREA as
3684 * a separate entity. This allows us to align the beginning of the PATH AREA
3685 * to a pointer boundary so that the exec_path, env[i], and argv[i] pointers
3686 * which preceed it on the stack are properly aligned.
3690 exec_copyout_strings(struct image_params
*imgp
, user_addr_t
*stackp
)
3692 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
3693 int ptr_size
= (imgp
->ip_flags
& IMGPF_IS_64BIT
) ? 8 : 4;
3695 void *ptr_buffer_start
, *ptr_buffer
;
3698 user_addr_t string_area
; /* *argv[], *env[] */
3699 user_addr_t ptr_area
; /* argv[], env[], applev[] */
3700 user_addr_t argc_area
; /* argc */
3705 struct copyout_desc
{
3709 user_addr_t
*dtrace_cookie
;
3711 boolean_t null_term
;
3714 .start_string
= imgp
->ip_startargv
,
3715 .count
= imgp
->ip_argc
,
3717 .dtrace_cookie
= &p
->p_dtrace_argv
,
3722 .start_string
= imgp
->ip_endargv
,
3723 .count
= imgp
->ip_envc
,
3725 .dtrace_cookie
= &p
->p_dtrace_envp
,
3730 .start_string
= imgp
->ip_strings
,
3733 .dtrace_cookie
= NULL
,
3738 .start_string
= imgp
->ip_endenvv
,
3739 .count
= imgp
->ip_applec
- 1, /* exec_path handled above */
3741 .dtrace_cookie
= NULL
,
3750 * All previous contributors to the string area
3751 * should have aligned their sub-area
3753 if (imgp
->ip_strspace
% ptr_size
!= 0) {
3758 /* Grow the stack down for the strings we've been building up */
3759 string_size
= imgp
->ip_strendp
- imgp
->ip_strings
;
3760 stack
-= string_size
;
3761 string_area
= stack
;
3764 * Need room for one pointer for each string, plus
3765 * one for the NULLs terminating the argv, envv, and apple areas.
3767 ptr_area_size
= (imgp
->ip_argc
+ imgp
->ip_envc
+ imgp
->ip_applec
+ 3) *
3769 stack
-= ptr_area_size
;
3772 /* We'll construct all the pointer arrays in our string buffer,
3773 * which we already know is aligned properly, and ip_argspace
3774 * was used to verify we have enough space.
3776 ptr_buffer_start
= ptr_buffer
= (void *)imgp
->ip_strendp
;
3779 * Need room for pointer-aligned argc slot.
3785 * Record the size of the arguments area so that sysctl_procargs()
3786 * can return the argument area without having to parse the arguments.
3789 p
->p_argc
= imgp
->ip_argc
;
3790 p
->p_argslen
= (int)(*stackp
- string_area
);
3793 /* Return the initial stack address: the location of argc */
3797 * Copy out the entire strings area.
3799 error
= copyout(imgp
->ip_strings
, string_area
,
3804 for (i
= 0; i
< sizeof(descriptors
)/sizeof(descriptors
[0]); i
++) {
3805 char *cur_string
= descriptors
[i
].start_string
;
3809 if (descriptors
[i
].dtrace_cookie
) {
3811 *descriptors
[i
].dtrace_cookie
= ptr_area
+ ((uintptr_t)ptr_buffer
- (uintptr_t)ptr_buffer_start
); /* dtrace convenience */
3814 #endif /* CONFIG_DTRACE */
3817 * For each segment (argv, envv, applev), copy as many pointers as requested
3818 * to our pointer buffer.
3820 for (j
= 0; j
< descriptors
[i
].count
; j
++) {
3821 user_addr_t cur_address
= string_area
+ (cur_string
- imgp
->ip_strings
);
3823 /* Copy out the pointer to the current string. Alignment has been verified */
3824 if (ptr_size
== 8) {
3825 *(uint64_t *)ptr_buffer
= (uint64_t)cur_address
;
3827 *(uint32_t *)ptr_buffer
= (uint32_t)cur_address
;
3830 ptr_buffer
= (void *)((uintptr_t)ptr_buffer
+ ptr_size
);
3831 cur_string
+= strlen(cur_string
) + 1; /* Only a NUL between strings in the same area */
3834 if (descriptors
[i
].null_term
) {
3835 if (ptr_size
== 8) {
3836 *(uint64_t *)ptr_buffer
= 0ULL;
3838 *(uint32_t *)ptr_buffer
= 0;
3841 ptr_buffer
= (void *)((uintptr_t)ptr_buffer
+ ptr_size
);
3846 * Copy out all our pointer arrays in bulk.
3848 error
= copyout(ptr_buffer_start
, ptr_area
,
3853 /* argc (int32, stored in a ptr_size area) */
3854 error
= copyoutptr((user_addr_t
)imgp
->ip_argc
, argc_area
, ptr_size
);
3864 * exec_extract_strings
3866 * Copy arguments and environment from user space into work area; we may
3867 * have already copied some early arguments into the work area, and if
3868 * so, any arguments opied in are appended to those already there.
3869 * This function is the primary manipulator of ip_argspace, since
3870 * these are the arguments the client of execve(2) knows about. After
3871 * each argv[]/envv[] string is copied, we charge the string length
3872 * and argv[]/envv[] pointer slot to ip_argspace, so that we can
3873 * full preflight the arg list size.
3875 * Parameters: struct image_params * the image parameter block
3877 * Returns: 0 Success
3881 * (imgp->ip_argc) Count of arguments, updated
3882 * (imgp->ip_envc) Count of environment strings, updated
3883 * (imgp->ip_argspace) Count of remaining of NCARGS
3884 * (imgp->ip_interp_buffer) Interpreter and args (mutated in place)
3887 * Note: The argument and environment vectors are user space pointers
3888 * to arrays of user space pointers.
3891 exec_extract_strings(struct image_params
*imgp
)
3894 int ptr_size
= (imgp
->ip_flags
& IMGPF_WAS_64BIT
) ? 8 : 4;
3895 int new_ptr_size
= (imgp
->ip_flags
& IMGPF_IS_64BIT
) ? 8 : 4;
3896 user_addr_t argv
= imgp
->ip_user_argv
;
3897 user_addr_t envv
= imgp
->ip_user_envv
;
3900 * Adjust space reserved for the path name by however much padding it
3901 * needs. Doing this here since we didn't know if this would be a 32-
3902 * or 64-bit process back in exec_save_path.
3904 while (imgp
->ip_strspace
% new_ptr_size
!= 0) {
3905 *imgp
->ip_strendp
++ = '\0';
3906 imgp
->ip_strspace
--;
3907 /* imgp->ip_argspace--; not counted towards exec args total */
3911 * From now on, we start attributing string space to ip_argspace
3913 imgp
->ip_startargv
= imgp
->ip_strendp
;
3916 if((imgp
->ip_flags
& IMGPF_INTERPRET
) != 0) {
3918 char *argstart
, *ch
;
3920 /* First, the arguments in the "#!" string are tokenized and extracted. */
3921 argstart
= imgp
->ip_interp_buffer
;
3924 while (*ch
&& !IS_WHITESPACE(*ch
)) {
3929 /* last argument, no need to NUL-terminate */
3930 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(argstart
), UIO_SYSSPACE
, TRUE
);
3935 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(argstart
), UIO_SYSSPACE
, TRUE
);
3938 * Find the next string. We know spaces at the end of the string have already
3942 while (IS_WHITESPACE(*argstart
)) {
3947 /* Error-check, regardless of whether this is the last interpreter arg or not */
3950 if (imgp
->ip_argspace
< new_ptr_size
) {
3954 imgp
->ip_argspace
-= new_ptr_size
; /* to hold argv[] entry */
3960 * If we are running an interpreter, replace the av[0] that was
3961 * passed to execve() with the path name that was
3962 * passed to execve() for interpreters which do not use the PATH
3963 * to locate their script arguments.
3965 error
= copyinptr(argv
, &arg
, ptr_size
);
3969 argv
+= ptr_size
; /* consume without using */
3973 if (imgp
->ip_interp_sugid_fd
!= -1) {
3974 char temp
[19]; /* "/dev/fd/" + 10 digits + NUL */
3975 snprintf(temp
, sizeof(temp
), "/dev/fd/%d", imgp
->ip_interp_sugid_fd
);
3976 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(temp
), UIO_SYSSPACE
, TRUE
);
3978 error
= exec_add_user_string(imgp
, imgp
->ip_user_fname
, imgp
->ip_seg
, TRUE
);
3983 if (imgp
->ip_argspace
< new_ptr_size
) {
3987 imgp
->ip_argspace
-= new_ptr_size
; /* to hold argv[] entry */
3991 while (argv
!= 0LL) {
3994 error
= copyinptr(argv
, &arg
, ptr_size
);
4007 error
= exec_add_user_string(imgp
, arg
, imgp
->ip_seg
, TRUE
);
4010 if (imgp
->ip_argspace
< new_ptr_size
) {
4014 imgp
->ip_argspace
-= new_ptr_size
; /* to hold argv[] entry */
4018 /* Save space for argv[] NULL terminator */
4019 if (imgp
->ip_argspace
< new_ptr_size
) {
4023 imgp
->ip_argspace
-= new_ptr_size
;
4025 /* Note where the args ends and env begins. */
4026 imgp
->ip_endargv
= imgp
->ip_strendp
;
4029 /* Now, get the environment */
4030 while (envv
!= 0LL) {
4033 error
= copyinptr(envv
, &env
, ptr_size
);
4044 error
= exec_add_user_string(imgp
, env
, imgp
->ip_seg
, TRUE
);
4047 if (imgp
->ip_argspace
< new_ptr_size
) {
4051 imgp
->ip_argspace
-= new_ptr_size
; /* to hold envv[] entry */
4055 /* Save space for envv[] NULL terminator */
4056 if (imgp
->ip_argspace
< new_ptr_size
) {
4060 imgp
->ip_argspace
-= new_ptr_size
;
4062 /* Align the tail of the combined argv+envv area */
4063 while (imgp
->ip_strspace
% new_ptr_size
!= 0) {
4064 if (imgp
->ip_argspace
< 1) {
4068 *imgp
->ip_strendp
++ = '\0';
4069 imgp
->ip_strspace
--;
4070 imgp
->ip_argspace
--;
4073 /* Note where the envv ends and applev begins. */
4074 imgp
->ip_endenvv
= imgp
->ip_strendp
;
4077 * From now on, we are no longer charging argument
4078 * space to ip_argspace.
4086 * Libc has an 8-element array set up for stack guard values. It only fills
4087 * in one of those entries, and both gcc and llvm seem to use only a single
4088 * 8-byte guard. Until somebody needs more than an 8-byte guard value, don't
4089 * do the work to construct them.
4091 #define GUARD_VALUES 1
4092 #define GUARD_KEY "stack_guard="
4095 * System malloc needs some entropy when it is initialized.
4097 #define ENTROPY_VALUES 2
4098 #define ENTROPY_KEY "malloc_entropy="
4101 * System malloc engages nanozone for UIAPP.
4103 #define NANO_ENGAGE_KEY "MallocNanoZone=1"
4105 #define PFZ_KEY "pfz="
4106 extern user32_addr_t commpage_text32_location
;
4107 extern user64_addr_t commpage_text64_location
;
4109 #define MAIN_STACK_VALUES 4
4110 #define MAIN_STACK_KEY "main_stack="
4112 #define HEX_STR_LEN 18 // 64-bit hex value "0x0123456701234567"
4115 exec_add_entropy_key(struct image_params
*imgp
,
4120 const int limit
= 8;
4121 uint64_t entropy
[limit
];
4122 char str
[strlen(key
) + (HEX_STR_LEN
+ 1) * limit
+ 1];
4123 if (values
> limit
) {
4127 read_random(entropy
, sizeof(entropy
[0]) * values
);
4130 entropy
[0] &= ~(0xffull
<< 8);
4133 int len
= snprintf(str
, sizeof(str
), "%s0x%llx", key
, entropy
[0]);
4134 int remaining
= sizeof(str
) - len
;
4135 for (int i
= 1; i
< values
&& remaining
> 0; ++i
) {
4136 int start
= sizeof(str
) - remaining
;
4137 len
= snprintf(&str
[start
], remaining
, ",0x%llx", entropy
[i
]);
4141 return exec_add_user_string(imgp
, CAST_USER_ADDR_T(str
), UIO_SYSSPACE
, FALSE
);
4145 * Build up the contents of the apple[] string vector
4148 exec_add_apple_strings(struct image_params
*imgp
,
4149 const load_result_t
*load_result
)
4152 int img_ptr_size
= (imgp
->ip_flags
& IMGPF_IS_64BIT
) ? 8 : 4;
4154 /* exec_save_path stored the first string */
4155 imgp
->ip_applec
= 1;
4157 /* adding the pfz string */
4159 char pfz_string
[strlen(PFZ_KEY
) + HEX_STR_LEN
+ 1];
4161 if (img_ptr_size
== 8) {
4162 snprintf(pfz_string
, sizeof(pfz_string
), PFZ_KEY
"0x%llx", commpage_text64_location
);
4164 snprintf(pfz_string
, sizeof(pfz_string
), PFZ_KEY
"0x%x", commpage_text32_location
);
4166 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(pfz_string
), UIO_SYSSPACE
, FALSE
);
4173 /* adding the NANO_ENGAGE_KEY key */
4174 if (imgp
->ip_px_sa
) {
4175 int proc_flags
= (((struct _posix_spawnattr
*) imgp
->ip_px_sa
)->psa_flags
);
4177 if ((proc_flags
& _POSIX_SPAWN_NANO_ALLOCATOR
) == _POSIX_SPAWN_NANO_ALLOCATOR
) {
4178 const char *nano_string
= NANO_ENGAGE_KEY
;
4179 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(nano_string
), UIO_SYSSPACE
, FALSE
);
4188 * Supply libc with a collection of random values to use when
4189 * implementing -fstack-protector.
4191 * (The first random string always contains an embedded NUL so that
4192 * __stack_chk_guard also protects against C string vulnerabilities)
4194 error
= exec_add_entropy_key(imgp
, GUARD_KEY
, GUARD_VALUES
, TRUE
);
4201 * Supply libc with entropy for system malloc.
4203 error
= exec_add_entropy_key(imgp
, ENTROPY_KEY
, ENTROPY_VALUES
, FALSE
);
4210 * Add MAIN_STACK_KEY: Supplies the address and size of the main thread's
4211 * stack if it was allocated by the kernel.
4213 * The guard page is not included in this stack size as libpthread
4214 * expects to add it back in after receiving this value.
4216 if (load_result
->unixproc
) {
4217 char stack_string
[strlen(MAIN_STACK_KEY
) + (HEX_STR_LEN
+ 1) * MAIN_STACK_VALUES
+ 1];
4218 snprintf(stack_string
, sizeof(stack_string
),
4219 MAIN_STACK_KEY
"0x%llx,0x%llx,0x%llx,0x%llx",
4220 (uint64_t)load_result
->user_stack
,
4221 (uint64_t)load_result
->user_stack_size
,
4222 (uint64_t)load_result
->user_stack_alloc
,
4223 (uint64_t)load_result
->user_stack_alloc_size
);
4224 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(stack_string
), UIO_SYSSPACE
, FALSE
);
4231 /* Align the tail of the combined applev area */
4232 while (imgp
->ip_strspace
% img_ptr_size
!= 0) {
4233 *imgp
->ip_strendp
++ = '\0';
4234 imgp
->ip_strspace
--;
4241 #define unix_stack_size(p) (p->p_rlimit[RLIMIT_STACK].rlim_cur)
4244 * exec_check_permissions
4246 * Description: Verify that the file that is being attempted to be executed
4247 * is in fact allowed to be executed based on it POSIX file
4248 * permissions and other access control criteria
4250 * Parameters: struct image_params * the image parameter block
4252 * Returns: 0 Success
4253 * EACCES Permission denied
4254 * ENOEXEC Executable file format error
4255 * ETXTBSY Text file busy [misuse of error code]
4257 * vnode_authorize:???
4260 exec_check_permissions(struct image_params
*imgp
)
4262 struct vnode
*vp
= imgp
->ip_vp
;
4263 struct vnode_attr
*vap
= imgp
->ip_vattr
;
4264 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
4266 kauth_action_t action
;
4268 /* Only allow execution of regular files */
4269 if (!vnode_isreg(vp
))
4272 /* Get the file attributes that we will be using here and elsewhere */
4274 VATTR_WANTED(vap
, va_uid
);
4275 VATTR_WANTED(vap
, va_gid
);
4276 VATTR_WANTED(vap
, va_mode
);
4277 VATTR_WANTED(vap
, va_fsid
);
4278 VATTR_WANTED(vap
, va_fileid
);
4279 VATTR_WANTED(vap
, va_data_size
);
4280 if ((error
= vnode_getattr(vp
, vap
, imgp
->ip_vfs_context
)) != 0)
4284 * Ensure that at least one execute bit is on - otherwise root
4285 * will always succeed, and we don't want to happen unless the
4286 * file really is executable.
4288 if (!vfs_authopaque(vnode_mount(vp
)) && ((vap
->va_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)) == 0))
4291 /* Disallow zero length files */
4292 if (vap
->va_data_size
== 0)
4295 imgp
->ip_arch_offset
= (user_size_t
)0;
4296 imgp
->ip_arch_size
= vap
->va_data_size
;
4298 /* Disable setuid-ness for traced programs or if MNT_NOSUID */
4299 if ((vp
->v_mount
->mnt_flag
& MNT_NOSUID
) || (p
->p_lflag
& P_LTRACED
))
4300 vap
->va_mode
&= ~(VSUID
| VSGID
);
4303 * Disable _POSIX_SPAWN_ALLOW_DATA_EXEC and _POSIX_SPAWN_DISABLE_ASLR
4304 * flags for setuid/setgid binaries.
4306 if (vap
->va_mode
& (VSUID
| VSGID
))
4307 imgp
->ip_flags
&= ~(IMGPF_ALLOW_DATA_EXEC
| IMGPF_DISABLE_ASLR
);
4310 error
= mac_vnode_check_exec(imgp
->ip_vfs_context
, vp
, imgp
);
4315 /* Check for execute permission */
4316 action
= KAUTH_VNODE_EXECUTE
;
4317 /* Traced images must also be readable */
4318 if (p
->p_lflag
& P_LTRACED
)
4319 action
|= KAUTH_VNODE_READ_DATA
;
4320 if ((error
= vnode_authorize(vp
, NULL
, action
, imgp
->ip_vfs_context
)) != 0)
4324 /* Don't let it run if anyone had it open for writing */
4326 if (vp
->v_writecount
) {
4327 panic("going to return ETXTBSY %x", vp
);
4335 /* XXX May want to indicate to underlying FS that vnode is open */
4344 * Initially clear the P_SUGID in the process flags; if an SUGID process is
4345 * exec'ing a non-SUGID image, then this is the point of no return.
4347 * If the image being activated is SUGID, then replace the credential with a
4348 * copy, disable tracing (unless the tracing process is root), reset the
4349 * mach task port to revoke it, set the P_SUGID bit,
4351 * If the saved user and group ID will be changing, then make sure it happens
4352 * to a new credential, rather than a shared one.
4354 * Set the security token (this is probably obsolete, given that the token
4355 * should not technically be separate from the credential itself).
4357 * Parameters: struct image_params * the image parameter block
4359 * Returns: void No failure indication
4362 * <process credential> Potentially modified/replaced
4363 * <task port> Potentially revoked
4364 * <process flags> P_SUGID bit potentially modified
4365 * <security token> Potentially modified
4368 exec_handle_sugid(struct image_params
*imgp
)
4370 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
4371 kauth_cred_t cred
= vfs_context_ucred(imgp
->ip_vfs_context
);
4372 kauth_cred_t my_cred
, my_new_cred
;
4374 int leave_sugid_clear
= 0;
4375 int mac_reset_ipc
= 0;
4379 int mac_transition
, disjoint_cred
= 0;
4380 int label_update_return
= 0;
4383 * Determine whether a call to update the MAC label will result in the
4384 * credential changing.
4386 * Note: MAC policies which do not actually end up modifying
4387 * the label subsequently are strongly encouraged to
4388 * return 0 for this check, since a non-zero answer will
4389 * slow down the exec fast path for normal binaries.
4391 mac_transition
= mac_cred_check_label_update_execve(
4392 imgp
->ip_vfs_context
,
4394 imgp
->ip_arch_offset
,
4396 imgp
->ip_scriptlabelp
,
4397 imgp
->ip_execlabelp
,
4402 OSBitAndAtomic(~((uint32_t)P_SUGID
), &p
->p_flag
);
4405 * Order of the following is important; group checks must go last,
4406 * as we use the success of the 'ismember' check combined with the
4407 * failure of the explicit match to indicate that we will be setting
4408 * the egid of the process even though the new process did not
4409 * require VSUID/VSGID bits in order for it to set the new group as
4412 * Note: Technically, by this we are implying a call to
4413 * setegid() in the new process, rather than implying
4414 * it used its VSGID bit to set the effective group,
4415 * even though there is no code in that process to make
4418 if (((imgp
->ip_origvattr
->va_mode
& VSUID
) != 0 &&
4419 kauth_cred_getuid(cred
) != imgp
->ip_origvattr
->va_uid
) ||
4420 ((imgp
->ip_origvattr
->va_mode
& VSGID
) != 0 &&
4421 ((kauth_cred_ismember_gid(cred
, imgp
->ip_origvattr
->va_gid
, &leave_sugid_clear
) || !leave_sugid_clear
) ||
4422 (kauth_cred_getgid(cred
) != imgp
->ip_origvattr
->va_gid
)))) {
4425 /* label for MAC transition and neither VSUID nor VSGID */
4426 handle_mac_transition
:
4430 * Replace the credential with a copy of itself if euid or
4433 * Note: setuid binaries will automatically opt out of
4434 * group resolver participation as a side effect
4435 * of this operation. This is an intentional
4436 * part of the security model, which requires a
4437 * participating credential be established by
4438 * escalating privilege, setting up all other
4439 * aspects of the credential including whether
4440 * or not to participate in external group
4441 * membership resolution, then dropping their
4442 * effective privilege to that of the desired
4443 * final credential state.
4445 * Modifications to p_ucred must be guarded using the
4446 * proc's ucred lock. This prevents others from accessing
4447 * a garbage credential.
4449 while (imgp
->ip_origvattr
->va_mode
& VSUID
) {
4450 my_cred
= kauth_cred_proc_ref(p
);
4451 my_new_cred
= kauth_cred_setresuid(my_cred
, KAUTH_UID_NONE
, imgp
->ip_origvattr
->va_uid
, imgp
->ip_origvattr
->va_uid
, KAUTH_UID_NONE
);
4453 if (my_new_cred
== my_cred
) {
4454 kauth_cred_unref(&my_cred
);
4458 /* update cred on proc */
4461 if (p
->p_ucred
!= my_cred
) {
4462 proc_ucred_unlock(p
);
4463 kauth_cred_unref(&my_new_cred
);
4467 /* donate cred reference on my_new_cred to p->p_ucred */
4468 p
->p_ucred
= my_new_cred
;
4469 PROC_UPDATE_CREDS_ONPROC(p
);
4470 proc_ucred_unlock(p
);
4472 /* drop additional reference that was taken on the previous cred */
4473 kauth_cred_unref(&my_cred
);
4478 while (imgp
->ip_origvattr
->va_mode
& VSGID
) {
4479 my_cred
= kauth_cred_proc_ref(p
);
4480 my_new_cred
= kauth_cred_setresgid(my_cred
, KAUTH_GID_NONE
, imgp
->ip_origvattr
->va_gid
, imgp
->ip_origvattr
->va_gid
);
4482 if (my_new_cred
== my_cred
) {
4483 kauth_cred_unref(&my_cred
);
4487 /* update cred on proc */
4490 if (p
->p_ucred
!= my_cred
) {
4491 proc_ucred_unlock(p
);
4492 kauth_cred_unref(&my_new_cred
);
4496 /* donate cred reference on my_new_cred to p->p_ucred */
4497 p
->p_ucred
= my_new_cred
;
4498 PROC_UPDATE_CREDS_ONPROC(p
);
4499 proc_ucred_unlock(p
);
4501 /* drop additional reference that was taken on the previous cred */
4502 kauth_cred_unref(&my_cred
);
4509 * If a policy has indicated that it will transition the label,
4510 * before making the call into the MAC policies, get a new
4511 * duplicate credential, so they can modify it without
4512 * modifying any others sharing it.
4514 if (mac_transition
) {
4516 * This hook may generate upcalls that require
4517 * importance donation from the kernel.
4520 thread_t thread
= current_thread();
4521 thread_enable_send_importance(thread
, TRUE
);
4522 kauth_proc_label_update_execve(p
,
4523 imgp
->ip_vfs_context
,
4525 imgp
->ip_arch_offset
,
4527 imgp
->ip_scriptlabelp
,
4528 imgp
->ip_execlabelp
,
4531 &disjoint_cred
, /* will be non zero if disjoint */
4532 &label_update_return
);
4533 thread_enable_send_importance(thread
, FALSE
);
4535 if (disjoint_cred
) {
4537 * If updating the MAC label resulted in a
4538 * disjoint credential, flag that we need to
4539 * set the P_SUGID bit. This protects
4540 * against debuggers being attached by an
4541 * insufficiently privileged process onto the
4542 * result of a transition to a more privileged
4545 leave_sugid_clear
= 0;
4548 imgp
->ip_mac_return
= label_update_return
;
4551 mac_reset_ipc
= mac_proc_check_inherit_ipc_ports(p
, p
->p_textvp
, p
->p_textoff
, imgp
->ip_vp
, imgp
->ip_arch_offset
, imgp
->ip_scriptvp
);
4553 #endif /* CONFIG_MACF */
4556 * If 'leave_sugid_clear' is non-zero, then we passed the
4557 * VSUID and MACF checks, and successfully determined that
4558 * the previous cred was a member of the VSGID group, but
4559 * that it was not the default at the time of the execve,
4560 * and that the post-labelling credential was not disjoint.
4561 * So we don't set the P_SUGID or reset mach ports and fds
4562 * on the basis of simply running this code.
4564 if (mac_reset_ipc
|| !leave_sugid_clear
) {
4566 * Have mach reset the task and thread ports.
4567 * We don't want anyone who had the ports before
4568 * a setuid exec to be able to access/control the
4569 * task/thread after.
4571 ipc_task_reset((imgp
->ip_new_thread
!= NULL
) ?
4572 get_threadtask(imgp
->ip_new_thread
) : p
->task
);
4573 ipc_thread_reset((imgp
->ip_new_thread
!= NULL
) ?
4574 imgp
->ip_new_thread
: current_thread());
4577 if (!leave_sugid_clear
) {
4579 * Flag the process as setuid.
4581 OSBitOrAtomic(P_SUGID
, &p
->p_flag
);
4584 * Radar 2261856; setuid security hole fix
4585 * XXX For setuid processes, attempt to ensure that
4586 * stdin, stdout, and stderr are already allocated.
4587 * We do not want userland to accidentally allocate
4588 * descriptors in this range which has implied meaning
4591 for (i
= 0; i
< 3; i
++) {
4593 if (p
->p_fd
->fd_ofiles
[i
] != NULL
)
4597 * Do the kernel equivalent of
4600 * (void) open("/dev/null", O_RDONLY);
4602 * (void) open("/dev/null", O_WRONLY);
4605 struct fileproc
*fp
;
4608 struct nameidata
*ndp
= NULL
;
4615 if ((error
= falloc(p
,
4616 &fp
, &indx
, imgp
->ip_vfs_context
)) != 0)
4619 MALLOC(ndp
, struct nameidata
*, sizeof(*ndp
), M_TEMP
, M_WAITOK
| M_ZERO
);
4621 fp_free(p
, indx
, fp
);
4626 NDINIT(ndp
, LOOKUP
, OP_OPEN
, FOLLOW
, UIO_SYSSPACE
,
4627 CAST_USER_ADDR_T("/dev/null"),
4628 imgp
->ip_vfs_context
);
4630 if ((error
= vn_open(ndp
, flag
, 0)) != 0) {
4631 fp_free(p
, indx
, fp
);
4636 struct fileglob
*fg
= fp
->f_fglob
;
4639 fg
->fg_ops
= &vnops
;
4640 fg
->fg_data
= ndp
->ni_vp
;
4642 vnode_put(ndp
->ni_vp
);
4645 procfdtbl_releasefd(p
, indx
, NULL
);
4646 fp_drop(p
, indx
, fp
, 1);
4656 * We are here because we were told that the MAC label will
4657 * be transitioned, and the binary is not VSUID or VSGID; to
4658 * deal with this case, we could either duplicate a lot of
4659 * code, or we can indicate we want to default the P_SUGID
4660 * bit clear and jump back up.
4662 if (mac_transition
) {
4663 leave_sugid_clear
= 1;
4664 goto handle_mac_transition
;
4668 #endif /* CONFIG_MACF */
4671 * Implement the semantic where the effective user and group become
4672 * the saved user and group in exec'ed programs.
4674 * Modifications to p_ucred must be guarded using the
4675 * proc's ucred lock. This prevents others from accessing
4676 * a garbage credential.
4679 my_cred
= kauth_cred_proc_ref(p
);
4680 my_new_cred
= kauth_cred_setsvuidgid(my_cred
, kauth_cred_getuid(my_cred
), kauth_cred_getgid(my_cred
));
4682 if (my_new_cred
== my_cred
) {
4683 kauth_cred_unref(&my_cred
);
4687 /* update cred on proc */
4690 if (p
->p_ucred
!= my_cred
) {
4691 proc_ucred_unlock(p
);
4692 kauth_cred_unref(&my_new_cred
);
4696 /* donate cred reference on my_new_cred to p->p_ucred */
4697 p
->p_ucred
= my_new_cred
;
4698 PROC_UPDATE_CREDS_ONPROC(p
);
4699 proc_ucred_unlock(p
);
4701 /* drop additional reference that was taken on the previous cred */
4702 kauth_cred_unref(&my_cred
);
4708 /* Update the process' identity version and set the security token */
4711 if (imgp
->ip_new_thread
!= NULL
) {
4712 task
= get_threadtask(imgp
->ip_new_thread
);
4716 set_security_token_task_internal(p
, task
);
4725 * Description: Set the user stack address for the process to the provided
4726 * address. If a custom stack was not set as a result of the
4727 * load process (i.e. as specified by the image file for the
4728 * executable), then allocate the stack in the provided map and
4729 * set up appropriate guard pages for enforcing administrative
4730 * limits on stack growth, if they end up being needed.
4732 * Parameters: p Process to set stack on
4733 * load_result Information from mach-o load commands
4734 * map Address map in which to allocate the new stack
4736 * Returns: KERN_SUCCESS Stack successfully created
4737 * !KERN_SUCCESS Mach failure code
4739 static kern_return_t
4740 create_unix_stack(vm_map_t map
, load_result_t
* load_result
,
4743 mach_vm_size_t size
, prot_size
;
4744 mach_vm_offset_t addr
, prot_addr
;
4747 mach_vm_address_t user_stack
= load_result
->user_stack
;
4750 p
->user_stack
= user_stack
;
4753 if (load_result
->user_stack_alloc_size
> 0) {
4755 * Allocate enough space for the maximum stack size we
4756 * will ever authorize and an extra page to act as
4757 * a guard page for stack overflows. For default stacks,
4758 * vm_initial_limit_stack takes care of the extra guard page.
4759 * Otherwise we must allocate it ourselves.
4761 if (mach_vm_round_page_overflow(load_result
->user_stack_alloc_size
, &size
)) {
4762 return KERN_INVALID_ARGUMENT
;
4764 addr
= mach_vm_trunc_page(load_result
->user_stack
- size
);
4765 kr
= mach_vm_allocate(map
, &addr
, size
,
4766 VM_MAKE_TAG(VM_MEMORY_STACK
) |
4768 if (kr
!= KERN_SUCCESS
) {
4769 // Can't allocate at default location, try anywhere
4771 kr
= mach_vm_allocate(map
, &addr
, size
,
4772 VM_MAKE_TAG(VM_MEMORY_STACK
) |
4774 if (kr
!= KERN_SUCCESS
) {
4778 user_stack
= addr
+ size
;
4779 load_result
->user_stack
= user_stack
;
4782 p
->user_stack
= user_stack
;
4786 load_result
->user_stack_alloc
= addr
;
4789 * And prevent access to what's above the current stack
4790 * size limit for this process.
4792 if (load_result
->user_stack_size
== 0) {
4793 load_result
->user_stack_size
= unix_stack_size(p
);
4794 prot_size
= mach_vm_trunc_page(size
- load_result
->user_stack_size
);
4796 prot_size
= PAGE_SIZE
;
4800 kr
= mach_vm_protect(map
,
4805 if (kr
!= KERN_SUCCESS
) {
4806 (void)mach_vm_deallocate(map
, addr
, size
);
4811 return KERN_SUCCESS
;
4814 #include <sys/reboot.h>
4817 * load_init_program_at_path
4819 * Description: Load the "init" program; in most cases, this will be "launchd"
4821 * Parameters: p Process to call execve() to create
4822 * the "init" program
4823 * scratch_addr Page in p, scratch space
4824 * path NULL terminated path
4826 * Returns: KERN_SUCCESS Success
4827 * !KERN_SUCCESS See execve/mac_execve for error codes
4829 * Notes: The process that is passed in is the first manufactured
4830 * process on the system, and gets here via bsd_ast() firing
4831 * for the first time. This is done to ensure that bsd_init()
4832 * has run to completion.
4834 * The address map of the first manufactured process matches the
4835 * word width of the kernel. Once the self-exec completes, the
4836 * initproc might be different.
4839 load_init_program_at_path(proc_t p
, user_addr_t scratch_addr
, const char* path
)
4843 struct execve_args init_exec_args
;
4844 user_addr_t argv0
= USER_ADDR_NULL
, argv1
= USER_ADDR_NULL
;
4847 * Validate inputs and pre-conditions
4850 assert(scratch_addr
);
4854 * Copy out program name.
4856 size_t path_length
= strlen(path
) + 1;
4857 argv0
= scratch_addr
;
4858 error
= copyout(path
, argv0
, path_length
);
4862 scratch_addr
= USER_ADDR_ALIGN(scratch_addr
+ path_length
, sizeof(user_addr_t
));
4865 * Put out first (and only) argument, similarly.
4866 * Assumes everything fits in a page as allocated above.
4868 if (boothowto
& RB_SINGLE
) {
4869 const char *init_args
= "-s";
4870 size_t init_args_length
= strlen(init_args
)+1;
4872 argv1
= scratch_addr
;
4873 error
= copyout(init_args
, argv1
, init_args_length
);
4877 scratch_addr
= USER_ADDR_ALIGN(scratch_addr
+ init_args_length
, sizeof(user_addr_t
));
4880 if (proc_is64bit(p
)) {
4881 user64_addr_t argv64bit
[3];
4883 argv64bit
[0] = argv0
;
4884 argv64bit
[1] = argv1
;
4885 argv64bit
[2] = USER_ADDR_NULL
;
4887 error
= copyout(argv64bit
, scratch_addr
, sizeof(argv64bit
));
4891 user32_addr_t argv32bit
[3];
4893 argv32bit
[0] = (user32_addr_t
)argv0
;
4894 argv32bit
[1] = (user32_addr_t
)argv1
;
4895 argv32bit
[2] = USER_ADDR_NULL
;
4897 error
= copyout(argv32bit
, scratch_addr
, sizeof(argv32bit
));
4903 * Set up argument block for fake call to execve.
4905 init_exec_args
.fname
= argv0
;
4906 init_exec_args
.argp
= scratch_addr
;
4907 init_exec_args
.envp
= USER_ADDR_NULL
;
4910 * So that init task is set with uid,gid 0 token
4912 set_security_token(p
);
4914 return execve(p
, &init_exec_args
, retval
);
4917 static const char * init_programs
[] = {
4919 "/usr/local/sbin/launchd.debug",
4921 #if DEVELOPMENT || DEBUG
4922 "/usr/local/sbin/launchd.development",
4930 * Description: Load the "init" program; in most cases, this will be "launchd"
4932 * Parameters: p Process to call execve() to create
4933 * the "init" program
4937 * Notes: The process that is passed in is the first manufactured
4938 * process on the system, and gets here via bsd_ast() firing
4939 * for the first time. This is done to ensure that bsd_init()
4940 * has run to completion.
4942 * In DEBUG & DEVELOPMENT builds, the launchdsuffix boot-arg
4943 * may be used to select a specific launchd executable. As with
4944 * the kcsuffix boot-arg, setting launchdsuffix to "" or "release"
4945 * will force /sbin/launchd to be selected.
4947 * Search order by build:
4949 * DEBUG DEVELOPMENT RELEASE PATH
4950 * ----------------------------------------------------------------------------------
4951 * 1 1 NA /usr/local/sbin/launchd.$LAUNCHDSUFFIX
4952 * 2 NA NA /usr/local/sbin/launchd.debug
4953 * 3 2 NA /usr/local/sbin/launchd.development
4954 * 4 3 1 /sbin/launchd
4957 load_init_program(proc_t p
)
4961 vm_map_t map
= current_map();
4962 mach_vm_offset_t scratch_addr
= 0;
4963 mach_vm_size_t map_page_size
= vm_map_page_size(map
);
4965 (void) mach_vm_allocate(map
, &scratch_addr
, map_page_size
, VM_FLAGS_ANYWHERE
);
4966 #if CONFIG_MEMORYSTATUS && CONFIG_JETSAM
4967 (void) memorystatus_init_at_boot_snapshot();
4968 #endif /* CONFIG_MEMORYSTATUS && CONFIG_JETSAM */
4970 #if DEBUG || DEVELOPMENT
4971 /* Check for boot-arg suffix first */
4972 char launchd_suffix
[64];
4973 if (PE_parse_boot_argn("launchdsuffix", launchd_suffix
, sizeof(launchd_suffix
))) {
4974 char launchd_path
[128];
4975 boolean_t is_release_suffix
= ((launchd_suffix
[0] == 0) ||
4976 (strcmp(launchd_suffix
, "release") == 0));
4978 if (is_release_suffix
) {
4979 error
= load_init_program_at_path(p
, (user_addr_t
)scratch_addr
, "/sbin/launchd");
4983 panic("Process 1 exec of launchd.release failed, errno %d", error
);
4985 strlcpy(launchd_path
, "/usr/local/sbin/launchd.", sizeof(launchd_path
));
4986 strlcat(launchd_path
, launchd_suffix
, sizeof(launchd_path
));
4988 /* All the error data is lost in the loop below, don't
4989 * attempt to save it. */
4990 if (!load_init_program_at_path(p
, (user_addr_t
)scratch_addr
, launchd_path
)) {
4998 for (i
= 0; i
< sizeof(init_programs
)/sizeof(init_programs
[0]); i
++) {
4999 error
= load_init_program_at_path(p
, (user_addr_t
)scratch_addr
, init_programs
[i
]);
5004 panic("Process 1 exec of %s failed, errno %d", ((i
== 0) ? "<null>" : init_programs
[i
-1]), error
);
5008 * load_return_to_errno
5010 * Description: Convert a load_return_t (Mach error) to an errno (BSD error)
5012 * Parameters: lrtn Mach error number
5014 * Returns: (int) BSD error number
5016 * EBADARCH Bad architecture
5017 * EBADMACHO Bad Mach object file
5018 * ESHLIBVERS Bad shared library version
5019 * ENOMEM Out of memory/resource shortage
5020 * EACCES Access denied
5021 * ENOENT Entry not found (usually "file does
5023 * EIO An I/O error occurred
5024 * EBADEXEC The executable is corrupt/unknown
5027 load_return_to_errno(load_return_t lrtn
)
5035 case LOAD_BADMACHO_UPX
:
5049 case LOAD_DECRYPTFAIL
:
5055 #include <mach/mach_types.h>
5056 #include <mach/vm_prot.h>
5057 #include <mach/semaphore.h>
5058 #include <mach/sync_policy.h>
5059 #include <kern/clock.h>
5060 #include <mach/kern_return.h>
5065 * Description: Allocate the block of memory used by the execve arguments.
5066 * At the same time, we allocate a page so that we can read in
5067 * the first page of the image.
5069 * Parameters: struct image_params * the image parameter block
5071 * Returns: 0 Success
5072 * EINVAL Invalid argument
5073 * EACCES Permission denied
5074 * EINTR Interrupted function
5075 * ENOMEM Not enough space
5077 * Notes: This is a temporary allocation into the kernel address space
5078 * to enable us to copy arguments in from user space. This is
5079 * necessitated by not mapping the process calling execve() into
5080 * the kernel address space during the execve() system call.
5082 * We assemble the argument and environment, etc., into this
5083 * region before copying it as a single block into the child
5084 * process address space (at the top or bottom of the stack,
5085 * depending on which way the stack grows; see the function
5086 * exec_copyout_strings() for details).
5088 * This ends up with a second (possibly unnecessary) copy compared
5089 * with assembing the data directly into the child address space,
5090 * instead, but since we cannot be guaranteed that the parent has
5091 * not modified its environment, we can't really know that it's
5092 * really a block there as well.
5096 static int execargs_waiters
= 0;
5097 lck_mtx_t
*execargs_cache_lock
;
5100 execargs_lock_lock(void) {
5101 lck_mtx_lock_spin(execargs_cache_lock
);
5105 execargs_lock_unlock(void) {
5106 lck_mtx_unlock(execargs_cache_lock
);
5109 static wait_result_t
5110 execargs_lock_sleep(void) {
5111 return(lck_mtx_sleep(execargs_cache_lock
, LCK_SLEEP_DEFAULT
, &execargs_free_count
, THREAD_INTERRUPTIBLE
));
5114 static kern_return_t
5115 execargs_purgeable_allocate(char **execarg_address
) {
5116 kern_return_t kr
= vm_allocate(bsd_pageable_map
, (vm_offset_t
*)execarg_address
, BSD_PAGEABLE_SIZE_PER_EXEC
, VM_FLAGS_ANYWHERE
| VM_FLAGS_PURGABLE
);
5117 assert(kr
== KERN_SUCCESS
);
5121 static kern_return_t
5122 execargs_purgeable_reference(void *execarg_address
) {
5123 int state
= VM_PURGABLE_NONVOLATILE
;
5124 kern_return_t kr
= vm_purgable_control(bsd_pageable_map
, (vm_offset_t
) execarg_address
, VM_PURGABLE_SET_STATE
, &state
);
5126 assert(kr
== KERN_SUCCESS
);
5130 static kern_return_t
5131 execargs_purgeable_volatilize(void *execarg_address
) {
5132 int state
= VM_PURGABLE_VOLATILE
| VM_PURGABLE_ORDERING_OBSOLETE
;
5134 kr
= vm_purgable_control(bsd_pageable_map
, (vm_offset_t
) execarg_address
, VM_PURGABLE_SET_STATE
, &state
);
5136 assert(kr
== KERN_SUCCESS
);
5142 execargs_wakeup_waiters(void) {
5143 thread_wakeup(&execargs_free_count
);
5147 execargs_alloc(struct image_params
*imgp
)
5151 int i
, cache_index
= -1;
5153 execargs_lock_lock();
5155 while (execargs_free_count
== 0) {
5157 res
= execargs_lock_sleep();
5159 if (res
!= THREAD_AWAKENED
) {
5160 execargs_lock_unlock();
5165 execargs_free_count
--;
5167 for (i
= 0; i
< execargs_cache_size
; i
++) {
5168 vm_offset_t element
= execargs_cache
[i
];
5171 imgp
->ip_strings
= (char *)(execargs_cache
[i
]);
5172 execargs_cache
[i
] = 0;
5177 assert(execargs_free_count
>= 0);
5179 execargs_lock_unlock();
5181 if (cache_index
== -1) {
5182 kret
= execargs_purgeable_allocate(&imgp
->ip_strings
);
5185 kret
= execargs_purgeable_reference(imgp
->ip_strings
);
5187 assert(kret
== KERN_SUCCESS
);
5188 if (kret
!= KERN_SUCCESS
) {
5192 /* last page used to read in file headers */
5193 imgp
->ip_vdata
= imgp
->ip_strings
+ ( NCARGS
+ PAGE_SIZE
);
5194 imgp
->ip_strendp
= imgp
->ip_strings
;
5195 imgp
->ip_argspace
= NCARGS
;
5196 imgp
->ip_strspace
= ( NCARGS
+ PAGE_SIZE
);
5204 * Description: Free the block of memory used by the execve arguments and the
5205 * first page of the executable by a previous call to the function
5208 * Parameters: struct image_params * the image parameter block
5210 * Returns: 0 Success
5211 * EINVAL Invalid argument
5212 * EINTR Oeration interrupted
5215 execargs_free(struct image_params
*imgp
)
5219 boolean_t needs_wakeup
= FALSE
;
5221 kret
= execargs_purgeable_volatilize(imgp
->ip_strings
);
5223 execargs_lock_lock();
5224 execargs_free_count
++;
5226 for (i
= 0; i
< execargs_cache_size
; i
++) {
5227 vm_offset_t element
= execargs_cache
[i
];
5229 execargs_cache
[i
] = (vm_offset_t
) imgp
->ip_strings
;
5230 imgp
->ip_strings
= NULL
;
5235 assert(imgp
->ip_strings
== NULL
);
5237 if (execargs_waiters
> 0)
5238 needs_wakeup
= TRUE
;
5240 execargs_lock_unlock();
5242 if (needs_wakeup
== TRUE
)
5243 execargs_wakeup_waiters();
5245 return ((kret
== KERN_SUCCESS
? 0 : EINVAL
));
5249 exec_resettextvp(proc_t p
, struct image_params
*imgp
)
5253 vnode_t tvp
= p
->p_textvp
;
5257 offset
= imgp
->ip_arch_offset
;
5260 panic("exec_resettextvp: expected valid vp");
5262 ret
= vnode_ref(vp
);
5266 p
->p_textoff
= offset
;
5268 p
->p_textvp
= NULLVP
; /* this is paranoia */
5273 if ( tvp
!= NULLVP
) {
5274 if (vnode_getwithref(tvp
) == 0) {
5283 * If the process is not signed or if it contains entitlements, we
5284 * need to communicate through the task_access_port to taskgated.
5286 * taskgated will provide a detached code signature if present, and
5287 * will enforce any restrictions on entitlements.
5291 taskgated_required(proc_t p
, boolean_t
*require_success
)
5298 csvnode_print_debug(p
->p_textvp
);
5300 const int can_skip_taskgated
= csproc_get_platform_binary(p
) && !csproc_get_platform_path(p
);
5301 if (can_skip_taskgated
) {
5302 if (cs_debug
) printf("taskgated not required for: %s\n", p
->p_name
);
5303 *require_success
= FALSE
;
5307 if ((p
->p_csflags
& CS_VALID
) == 0) {
5308 *require_success
= FALSE
;
5312 error
= cs_entitlements_blob_get(p
, &blob
, &length
);
5313 if (error
== 0 && blob
!= NULL
) {
5315 * fatal on the desktop when entitlements are present,
5316 * unless we started in single-user mode
5318 if ((boothowto
& RB_SINGLE
) == 0)
5319 *require_success
= TRUE
;
5321 * Allow initproc to run without causing taskgated to launch
5323 if (p
== initproc
) {
5324 *require_success
= FALSE
;
5328 if (cs_debug
) printf("taskgated required for: %s\n", p
->p_name
);
5333 *require_success
= FALSE
;
5338 * __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__
5340 * Description: Waits for the userspace daemon to respond to the request
5341 * we made. Function declared non inline to be visible in
5342 * stackshots and spindumps as well as debugging.
5344 __attribute__((noinline
)) int
5345 __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port
, int32_t new_pid
)
5347 return find_code_signature(task_access_port
, new_pid
);
5351 check_for_signature(proc_t p
, struct image_params
*imgp
)
5353 mach_port_t port
= NULL
;
5354 kern_return_t kr
= KERN_FAILURE
;
5356 boolean_t unexpected_failure
= FALSE
;
5357 unsigned char hash
[SHA1_RESULTLEN
];
5358 boolean_t require_success
= FALSE
;
5359 int spawn
= (imgp
->ip_flags
& IMGPF_SPAWN
);
5360 int vfexec
= (imgp
->ip_flags
& IMGPF_VFORK_EXEC
);
5361 os_reason_t signature_failure_reason
= OS_REASON_NULL
;
5364 * Override inherited code signing flags with the
5365 * ones for the process that is being successfully
5369 p
->p_csflags
= imgp
->ip_csflags
;
5372 /* Set the switch_protect flag on the map */
5373 if(p
->p_csflags
& (CS_HARD
|CS_KILL
)) {
5374 vm_map_switch_protect(get_task_map(p
->task
), TRUE
);
5378 * image activation may be failed due to policy
5379 * which is unexpected but security framework does not
5380 * approve of exec, kill and return immediately.
5382 if (imgp
->ip_mac_return
!= 0) {
5384 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_CREATE
) | DBG_FUNC_NONE
,
5385 p
->p_pid
, OS_REASON_EXEC
, EXEC_EXIT_REASON_SECURITY_POLICY
, 0, 0);
5386 signature_failure_reason
= os_reason_create(OS_REASON_EXEC
, EXEC_EXIT_REASON_SECURITY_POLICY
);
5387 error
= imgp
->ip_mac_return
;
5388 unexpected_failure
= TRUE
;
5392 if (imgp
->ip_cs_error
!= OS_REASON_NULL
) {
5393 signature_failure_reason
= imgp
->ip_cs_error
;
5394 imgp
->ip_cs_error
= OS_REASON_NULL
;
5399 /* check if callout to taskgated is needed */
5400 if (!taskgated_required(p
, &require_success
)) {
5405 kr
= task_get_task_access_port(p
->task
, &port
);
5406 if (KERN_SUCCESS
!= kr
|| !IPC_PORT_VALID(port
)) {
5408 if (require_success
) {
5409 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_CREATE
) | DBG_FUNC_NONE
,
5410 p
->p_pid
, OS_REASON_CODESIGNING
, CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT
, 0, 0);
5411 signature_failure_reason
= os_reason_create(OS_REASON_CODESIGNING
, CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT
);
5418 * taskgated returns KERN_SUCCESS if it has completed its work
5419 * and the exec should continue, KERN_FAILURE if the exec should
5420 * fail, or it may error out with different error code in an
5421 * event of mig failure (e.g. process was signalled during the
5422 * rpc call, taskgated died, mig server died etc.).
5425 kr
= __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(port
, p
->p_pid
);
5433 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_CREATE
) | DBG_FUNC_NONE
,
5434 p
->p_pid
, OS_REASON_CODESIGNING
, CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG
, 0, 0);
5435 signature_failure_reason
= os_reason_create(OS_REASON_CODESIGNING
, CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG
);
5440 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_CREATE
) | DBG_FUNC_NONE
,
5441 p
->p_pid
, OS_REASON_EXEC
, EXEC_EXIT_REASON_TASKGATED_OTHER
, 0, 0);
5442 signature_failure_reason
= os_reason_create(OS_REASON_EXEC
, EXEC_EXIT_REASON_TASKGATED_OTHER
);
5443 unexpected_failure
= TRUE
;
5447 /* Only do this if exec_resettextvp() did not fail */
5448 if (p
->p_textvp
!= NULLVP
) {
5450 * If there's a new code directory, mark this process
5453 if (0 == ubc_cs_getcdhash(p
->p_textvp
, p
->p_textoff
, hash
)) {
5455 p
->p_csflags
|= CS_VALID
;
5462 if (!unexpected_failure
)
5463 p
->p_csflags
|= CS_KILLED
;
5464 /* make very sure execution fails */
5465 if (vfexec
|| spawn
) {
5466 assert(signature_failure_reason
!= OS_REASON_NULL
);
5467 psignal_vfork_with_reason(p
, p
->task
, imgp
->ip_new_thread
,
5468 SIGKILL
, signature_failure_reason
);
5469 signature_failure_reason
= OS_REASON_NULL
;
5472 assert(signature_failure_reason
!= OS_REASON_NULL
);
5473 psignal_with_reason(p
, SIGKILL
, signature_failure_reason
);
5474 signature_failure_reason
= OS_REASON_NULL
;
5478 /* If we hit this, we likely would have leaked an exit reason */
5479 assert(signature_failure_reason
== OS_REASON_NULL
);
5484 * Typically as soon as we start executing this process, the
5485 * first instruction will trigger a VM fault to bring the text
5486 * pages (as executable) into the address space, followed soon
5487 * thereafter by dyld data structures (for dynamic executable).
5488 * To optimize this, as well as improve support for hardware
5489 * debuggers that can only access resident pages present
5490 * in the process' page tables, we prefault some pages if
5491 * possible. Errors are non-fatal.
5493 static void exec_prefault_data(proc_t p __unused
, struct image_params
*imgp
, load_result_t
*load_result
)
5496 size_t expected_all_image_infos_size
;
5499 * Prefault executable or dyld entry point.
5501 vm_fault(current_map(),
5502 vm_map_trunc_page(load_result
->entry_point
,
5503 vm_map_page_mask(current_map())),
5504 VM_PROT_READ
| VM_PROT_EXECUTE
,
5506 THREAD_UNINT
, NULL
, 0);
5508 if (imgp
->ip_flags
& IMGPF_IS_64BIT
) {
5509 expected_all_image_infos_size
= sizeof(struct user64_dyld_all_image_infos
);
5511 expected_all_image_infos_size
= sizeof(struct user32_dyld_all_image_infos
);
5514 /* Decode dyld anchor structure from <mach-o/dyld_images.h> */
5515 if (load_result
->dynlinker
&&
5516 load_result
->all_image_info_addr
&&
5517 load_result
->all_image_info_size
>= expected_all_image_infos_size
) {
5519 struct user64_dyld_all_image_infos infos64
;
5520 struct user32_dyld_all_image_infos infos32
;
5524 * Pre-fault to avoid copyin() going through the trap handler
5525 * and recovery path.
5527 vm_fault(current_map(),
5528 vm_map_trunc_page(load_result
->all_image_info_addr
,
5529 vm_map_page_mask(current_map())),
5530 VM_PROT_READ
| VM_PROT_WRITE
,
5532 THREAD_UNINT
, NULL
, 0);
5533 if ((load_result
->all_image_info_addr
& PAGE_MASK
) + expected_all_image_infos_size
> PAGE_SIZE
) {
5534 /* all_image_infos straddles a page */
5535 vm_fault(current_map(),
5536 vm_map_trunc_page(load_result
->all_image_info_addr
+ expected_all_image_infos_size
- 1,
5537 vm_map_page_mask(current_map())),
5538 VM_PROT_READ
| VM_PROT_WRITE
,
5540 THREAD_UNINT
, NULL
, 0);
5543 ret
= copyin(load_result
->all_image_info_addr
,
5545 expected_all_image_infos_size
);
5546 if (ret
== 0 && all_image_infos
.infos32
.version
>= 9) {
5548 user_addr_t notification_address
;
5549 user_addr_t dyld_image_address
;
5550 user_addr_t dyld_version_address
;
5551 user_addr_t dyld_all_image_infos_address
;
5552 user_addr_t dyld_slide_amount
;
5554 if (imgp
->ip_flags
& IMGPF_IS_64BIT
) {
5555 notification_address
= all_image_infos
.infos64
.notification
;
5556 dyld_image_address
= all_image_infos
.infos64
.dyldImageLoadAddress
;
5557 dyld_version_address
= all_image_infos
.infos64
.dyldVersion
;
5558 dyld_all_image_infos_address
= all_image_infos
.infos64
.dyldAllImageInfosAddress
;
5560 notification_address
= all_image_infos
.infos32
.notification
;
5561 dyld_image_address
= all_image_infos
.infos32
.dyldImageLoadAddress
;
5562 dyld_version_address
= all_image_infos
.infos32
.dyldVersion
;
5563 dyld_all_image_infos_address
= all_image_infos
.infos32
.dyldAllImageInfosAddress
;
5567 * dyld statically sets up the all_image_infos in its Mach-O
5568 * binary at static link time, with pointers relative to its default
5569 * load address. Since ASLR might slide dyld before its first
5570 * instruction is executed, "dyld_slide_amount" tells us how far
5571 * dyld was loaded compared to its default expected load address.
5572 * All other pointers into dyld's image should be adjusted by this
5573 * amount. At some point later, dyld will fix up pointers to take
5574 * into account the slide, at which point the all_image_infos_address
5575 * field in the structure will match the runtime load address, and
5576 * "dyld_slide_amount" will be 0, if we were to consult it again.
5579 dyld_slide_amount
= load_result
->all_image_info_addr
- dyld_all_image_infos_address
;
5582 kprintf("exec_prefault: 0x%016llx 0x%08x 0x%016llx 0x%016llx 0x%016llx 0x%016llx\n",
5583 (uint64_t)load_result
->all_image_info_addr
,
5584 all_image_infos
.infos32
.version
,
5585 (uint64_t)notification_address
,
5586 (uint64_t)dyld_image_address
,
5587 (uint64_t)dyld_version_address
,
5588 (uint64_t)dyld_all_image_infos_address
);
5591 vm_fault(current_map(),
5592 vm_map_trunc_page(notification_address
+ dyld_slide_amount
,
5593 vm_map_page_mask(current_map())),
5594 VM_PROT_READ
| VM_PROT_EXECUTE
,
5596 THREAD_UNINT
, NULL
, 0);
5597 vm_fault(current_map(),
5598 vm_map_trunc_page(dyld_image_address
+ dyld_slide_amount
,
5599 vm_map_page_mask(current_map())),
5600 VM_PROT_READ
| VM_PROT_EXECUTE
,
5602 THREAD_UNINT
, NULL
, 0);
5603 vm_fault(current_map(),
5604 vm_map_trunc_page(dyld_version_address
+ dyld_slide_amount
,
5605 vm_map_page_mask(current_map())),
5608 THREAD_UNINT
, NULL
, 0);
5609 vm_fault(current_map(),
5610 vm_map_trunc_page(dyld_all_image_infos_address
+ dyld_slide_amount
,
5611 vm_map_page_mask(current_map())),
5612 VM_PROT_READ
| VM_PROT_WRITE
,
5614 THREAD_UNINT
, NULL
, 0);