2 * Copyright (c) 2000-2011 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>
106 #include <sys/shm_internal.h> /* shmexec() */
108 #include <sys/ubc_internal.h> /* ubc_map() */
109 #include <sys/spawn.h>
110 #include <sys/spawn_internal.h>
111 #include <sys/process_policy.h>
112 #include <sys/codesign.h>
113 #include <crypto/sha1.h>
115 #include <libkern/libkern.h>
117 #include <security/audit/audit.h>
119 #include <ipc/ipc_types.h>
121 #include <mach/mach_types.h>
122 #include <mach/port.h>
123 #include <mach/task.h>
124 #include <mach/task_access.h>
125 #include <mach/thread_act.h>
126 #include <mach/vm_map.h>
127 #include <mach/mach_vm.h>
128 #include <mach/vm_param.h>
130 #include <kern/sched_prim.h> /* thread_wakeup() */
131 #include <kern/affinity.h>
132 #include <kern/assert.h>
133 #include <kern/task.h>
134 #include <kern/coalition.h>
137 #include <security/mac.h>
138 #include <security/mac_mach_internal.h>
141 #include <vm/vm_map.h>
142 #include <vm/vm_kern.h>
143 #include <vm/vm_protos.h>
144 #include <vm/vm_kern.h>
145 #include <vm/vm_fault.h>
146 #include <vm/vm_pageout.h>
148 #include <kdp/kdp_dyld.h>
150 #include <machine/pal_routines.h>
152 #include <pexpert/pexpert.h>
154 #if CONFIG_MEMORYSTATUS
155 #include <sys/kern_memorystatus.h>
159 /* Do not include dtrace.h, it redefines kmem_[alloc/free] */
160 extern void (*dtrace_fasttrap_exec_ptr
)(proc_t
);
161 extern void (*dtrace_proc_waitfor_exec_ptr
)(proc_t
);
162 extern void (*dtrace_helpers_cleanup
)(proc_t
);
163 extern void dtrace_lazy_dofs_destroy(proc_t
);
166 * Since dtrace_proc_waitfor_exec_ptr can be added/removed in dtrace_subr.c,
167 * we will store its value before actually calling it.
169 static void (*dtrace_proc_waitfor_hook
)(proc_t
) = NULL
;
171 #include <sys/dtrace_ptss.h>
174 /* support for child creation in exec after vfork */
175 thread_t
fork_create_child(task_t parent_task
, coalition_t parent_coalition
, proc_t child_proc
, int inherit_memory
, int is64bit
);
176 void vfork_exit(proc_t p
, int rv
);
177 int setsigvec(proc_t
, thread_t
, int, struct __kern_sigaction
*, boolean_t in_sigstart
);
178 extern void proc_apply_task_networkbg_internal(proc_t
, thread_t
);
181 * Mach things for which prototypes are unavailable from Mach headers
185 void ipc_thread_reset(
187 kern_return_t
ipc_object_copyin(
189 mach_port_name_t name
,
190 mach_msg_type_name_t msgt_name
,
191 ipc_object_t
*objectp
);
192 void ipc_port_release_send(ipc_port_t
);
194 #if DEVELOPMENT || DEBUG
195 void task_importance_update_owner_info(task_t
);
198 extern struct savearea
*get_user_regs(thread_t
);
200 __attribute__((noinline
)) int __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port
, int32_t new_pid
);
202 #include <kern/thread.h>
203 #include <kern/task.h>
204 #include <kern/ast.h>
205 #include <kern/mach_loader.h>
206 #include <kern/mach_fat.h>
207 #include <mach-o/fat.h>
208 #include <mach-o/loader.h>
209 #include <machine/vmparam.h>
210 #include <sys/imgact.h>
216 * EAI_ITERLIMIT The maximum number of times to iterate an image
217 * activator in exec_activate_image() before treating
218 * it as malformed/corrupt.
220 #define EAI_ITERLIMIT 10
223 * For #! interpreter parsing
225 #define IS_WHITESPACE(ch) ((ch == ' ') || (ch == '\t'))
226 #define IS_EOL(ch) ((ch == '#') || (ch == '\n'))
228 extern vm_map_t bsd_pageable_map
;
229 extern const struct fileops vnops
;
231 #define ROUND_PTR(type, addr) \
232 (type *)( ( (uintptr_t)(addr) + 16 - 1) \
235 struct image_params
; /* Forward */
236 static int exec_activate_image(struct image_params
*imgp
);
237 static int exec_copyout_strings(struct image_params
*imgp
, user_addr_t
*stackp
);
238 static int load_return_to_errno(load_return_t lrtn
);
239 static int execargs_alloc(struct image_params
*imgp
);
240 static int execargs_free(struct image_params
*imgp
);
241 static int exec_check_permissions(struct image_params
*imgp
);
242 static int exec_extract_strings(struct image_params
*imgp
);
243 static int exec_add_apple_strings(struct image_params
*imgp
);
244 static int exec_handle_sugid(struct image_params
*imgp
);
245 static int sugid_scripts
= 0;
246 SYSCTL_INT (_kern
, OID_AUTO
, sugid_scripts
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &sugid_scripts
, 0, "");
247 static kern_return_t
create_unix_stack(vm_map_t map
, load_result_t
* load_result
, proc_t p
);
248 static int copyoutptr(user_addr_t ua
, user_addr_t ptr
, int ptr_size
);
249 static void exec_resettextvp(proc_t
, struct image_params
*);
250 static int check_for_signature(proc_t
, struct image_params
*);
251 static void exec_prefault_data(proc_t
, struct image_params
*, load_result_t
*);
252 static errno_t
exec_handle_port_actions(struct image_params
*imgp
, short psa_flags
, boolean_t
* portwatch_present
, ipc_port_t
* portwatch_ports
);
253 static errno_t
exec_handle_spawnattr_policy(proc_t p
, int psa_apptype
, uint64_t psa_qos_clamp
,
254 ipc_port_t
* portwatch_ports
, int portwatch_count
);
257 * exec_add_user_string
259 * Add the requested string to the string space area.
261 * Parameters; struct image_params * image parameter block
262 * user_addr_t string to add to strings area
263 * int segment from which string comes
264 * boolean_t TRUE if string contributes to NCARGS
267 * !0 Failure errno from copyinstr()
270 * (imgp->ip_strendp) updated location of next add, if any
271 * (imgp->ip_strspace) updated byte count of space remaining
272 * (imgp->ip_argspace) updated byte count of space in NCARGS
275 exec_add_user_string(struct image_params
*imgp
, user_addr_t str
, int seg
, boolean_t is_ncargs
)
284 space
= imgp
->ip_argspace
; /* by definition smaller than ip_strspace */
286 space
= imgp
->ip_strspace
;
293 if (!UIO_SEG_IS_USER_SPACE(seg
)) {
294 char *kstr
= CAST_DOWN(char *,str
); /* SAFE */
295 error
= copystr(kstr
, imgp
->ip_strendp
, space
, &len
);
297 error
= copyinstr(str
, imgp
->ip_strendp
, space
, &len
);
300 imgp
->ip_strendp
+= len
;
301 imgp
->ip_strspace
-= len
;
303 imgp
->ip_argspace
-= len
;
305 } while (error
== ENAMETOOLONG
);
313 * To support new app package launching for Mac OS X, the dyld needs the
314 * first argument to execve() stored on the user stack.
316 * Save the executable path name at the bottom of the strings area and set
317 * the argument vector pointer to the location following that to indicate
318 * the start of the argument and environment tuples, setting the remaining
319 * string space count to the size of the string area minus the path length.
321 * Parameters; struct image_params * image parameter block
322 * char * path used to invoke program
323 * int segment from which path comes
325 * Returns: int 0 Success
327 * copy[in]str:EFAULT Bad address
328 * copy[in]str:ENAMETOOLONG Filename too long
331 * (imgp->ip_strings) saved path
332 * (imgp->ip_strspace) space remaining in ip_strings
333 * (imgp->ip_strendp) start of remaining copy area
334 * (imgp->ip_argspace) space remaining of NCARGS
335 * (imgp->ip_applec) Initial applev[0]
337 * Note: We have to do this before the initial namei() since in the
338 * path contains symbolic links, namei() will overwrite the
339 * original path buffer contents. If the last symbolic link
340 * resolved was a relative pathname, we would lose the original
341 * "path", which could be an absolute pathname. This might be
342 * unacceptable for dyld.
345 exec_save_path(struct image_params
*imgp
, user_addr_t path
, int seg
)
351 len
= MIN(MAXPATHLEN
, imgp
->ip_strspace
);
354 case UIO_USERSPACE32
:
355 case UIO_USERSPACE64
: /* Same for copyin()... */
356 error
= copyinstr(path
, imgp
->ip_strings
, len
, &len
);
359 kpath
= CAST_DOWN(char *,path
); /* SAFE */
360 error
= copystr(kpath
, imgp
->ip_strings
, len
, &len
);
368 imgp
->ip_strendp
+= len
;
369 imgp
->ip_strspace
-= len
;
376 * exec_reset_save_path
378 * If we detect a shell script, we need to reset the string area
379 * state so that the interpreter can be saved onto the stack.
381 * Parameters; struct image_params * image parameter block
383 * Returns: int 0 Success
386 * (imgp->ip_strings) saved path
387 * (imgp->ip_strspace) space remaining in ip_strings
388 * (imgp->ip_strendp) start of remaining copy area
389 * (imgp->ip_argspace) space remaining of NCARGS
393 exec_reset_save_path(struct image_params
*imgp
)
395 imgp
->ip_strendp
= imgp
->ip_strings
;
396 imgp
->ip_argspace
= NCARGS
;
397 imgp
->ip_strspace
= ( NCARGS
+ PAGE_SIZE
);
405 * Image activator for interpreter scripts. If the image begins with the
406 * characters "#!", then it is an interpreter script. Verify that we are
407 * not already executing in PowerPC mode, and that the length of the script
408 * line indicating the interpreter is not in excess of the maximum allowed
409 * size. If this is the case, then break out the arguments, if any, which
410 * are separated by white space, and copy them into the argument save area
411 * as if they were provided on the command line before all other arguments.
412 * The line ends when we encounter a comment character ('#') or newline.
414 * Parameters; struct image_params * image parameter block
416 * Returns: -1 not an interpreter (keep looking)
417 * -3 Success: interpreter: relookup
418 * >0 Failure: interpreter: error number
420 * A return value other than -1 indicates subsequent image activators should
421 * not be given the opportunity to attempt to activate the image.
424 exec_shell_imgact(struct image_params
*imgp
)
426 char *vdata
= imgp
->ip_vdata
;
428 char *line_startp
, *line_endp
;
436 * Make sure it's a shell script. If we've already redirected
437 * from an interpreted file once, don't do it again.
439 * Note: We disallow PowerPC, since the expectation is that we
440 * may run a PowerPC interpreter, but not an interpret a PowerPC
441 * image. This is consistent with historical behaviour.
443 if (vdata
[0] != '#' ||
445 (imgp
->ip_flags
& IMGPF_INTERPRET
) != 0) {
449 imgp
->ip_flags
|= IMGPF_INTERPRET
;
450 imgp
->ip_interp_sugid_fd
= -1;
451 imgp
->ip_interp_buffer
[0] = '\0';
453 /* Check to see if SUGID scripts are permitted. If they aren't then
454 * clear the SUGID bits.
455 * imgp->ip_vattr is known to be valid.
457 if (sugid_scripts
== 0) {
458 imgp
->ip_origvattr
->va_mode
&= ~(VSUID
| VSGID
);
461 /* Try to find the first non-whitespace character */
462 for( ihp
= &vdata
[2]; ihp
< &vdata
[IMG_SHSIZE
]; ihp
++ ) {
464 /* Did not find interpreter, "#!\n" */
466 } else if (IS_WHITESPACE(*ihp
)) {
467 /* Whitespace, like "#! /bin/sh\n", keep going. */
469 /* Found start of interpreter */
474 if (ihp
== &vdata
[IMG_SHSIZE
]) {
475 /* All whitespace, like "#! " */
481 /* Try to find the end of the interpreter+args string */
482 for ( ; ihp
< &vdata
[IMG_SHSIZE
]; ihp
++ ) {
487 /* Still part of interpreter or args */
491 if (ihp
== &vdata
[IMG_SHSIZE
]) {
492 /* A long line, like "#! blah blah blah" without end */
496 /* Backtrack until we find the last non-whitespace */
497 while (IS_EOL(*ihp
) || IS_WHITESPACE(*ihp
)) {
501 /* The character after the last non-whitespace is our logical end of line */
505 * Now we have pointers to the usable part of:
507 * "#! /usr/bin/int first second third \n"
508 * ^ line_startp ^ line_endp
511 /* copy the interpreter name */
512 interp
= imgp
->ip_interp_buffer
;
513 for ( ihp
= line_startp
; (ihp
< line_endp
) && !IS_WHITESPACE(*ihp
); ihp
++)
517 exec_reset_save_path(imgp
);
518 exec_save_path(imgp
, CAST_USER_ADDR_T(imgp
->ip_interp_buffer
),
521 /* Copy the entire interpreter + args for later processing into argv[] */
522 interp
= imgp
->ip_interp_buffer
;
523 for ( ihp
= line_startp
; (ihp
< line_endp
); ihp
++)
528 * If we have a SUID oder SGID script, create a file descriptor
529 * from the vnode and pass /dev/fd/%d instead of the actual
530 * path name so that the script does not get opened twice
532 if (imgp
->ip_origvattr
->va_mode
& (VSUID
| VSGID
)) {
533 p
= vfs_context_proc(imgp
->ip_vfs_context
);
534 error
= falloc(p
, &fp
, &fd
, imgp
->ip_vfs_context
);
538 fp
->f_fglob
->fg_flag
= FREAD
;
539 fp
->f_fglob
->fg_ops
= &vnops
;
540 fp
->f_fglob
->fg_data
= (caddr_t
)imgp
->ip_vp
;
543 procfdtbl_releasefd(p
, fd
, NULL
);
544 fp_drop(p
, fd
, fp
, 1);
546 vnode_ref(imgp
->ip_vp
);
548 imgp
->ip_interp_sugid_fd
= fd
;
559 * Image activator for fat 1.0 binaries. If the binary is fat, then we
560 * need to select an image from it internally, and make that the image
561 * we are going to attempt to execute. At present, this consists of
562 * reloading the first page for the image with a first page from the
563 * offset location indicated by the fat header.
565 * Parameters; struct image_params * image parameter block
567 * Returns: -1 not a fat binary (keep looking)
568 * -2 Success: encapsulated binary: reread
569 * >0 Failure: error number
571 * Important: This image activator is byte order neutral.
573 * Note: A return value other than -1 indicates subsequent image
574 * activators should not be given the opportunity to attempt
575 * to activate the image.
577 * If we find an encapsulated binary, we make no assertions
578 * about its validity; instead, we leave that up to a rescan
579 * for an activator to claim it, and, if it is claimed by one,
580 * that activator is responsible for determining validity.
583 exec_fat_imgact(struct image_params
*imgp
)
585 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
586 kauth_cred_t cred
= kauth_cred_proc_ref(p
);
587 struct fat_header
*fat_header
= (struct fat_header
*)imgp
->ip_vdata
;
588 struct _posix_spawnattr
*psa
= NULL
;
589 struct fat_arch fat_arch
;
593 /* Make sure it's a fat binary */
594 if ((fat_header
->magic
!= FAT_MAGIC
) &&
595 (fat_header
->magic
!= FAT_CIGAM
)) {
600 #if DEVELOPMENT || DEBUG
601 if (cpu_type() == CPU_TYPE_ARM64
) {
602 uint32_t fat_nfat_arch
= OSSwapBigToHostInt32(fat_header
->nfat_arch
);
603 struct fat_arch
*archs
;
604 int vfexec
= (imgp
->ip_flags
& IMGPF_VFORK_EXEC
);
605 int spawn
= (imgp
->ip_flags
& IMGPF_SPAWN
);
607 archs
= (struct fat_arch
*)(imgp
->ip_vdata
+ sizeof(struct fat_header
));
609 /* ip_vdata always has PAGE_SIZE of data */
610 if (PAGE_SIZE
>= (sizeof(struct fat_header
) + (fat_nfat_arch
+ 1) * sizeof(struct fat_arch
))) {
611 if (fat_nfat_arch
> 0
612 && OSSwapBigToHostInt32(archs
[fat_nfat_arch
].cputype
) == CPU_TYPE_ARM64
) {
614 /* rdar://problem/15001727 */
615 printf("Attempt to execute malformed binary %s\n", imgp
->ip_strings
);
618 p
->p_csflags
|= CS_KILLED
;
622 * We can't stop the system call, so make sure the child never executes
623 * For vfork exec, the current implementation has not set up the thread in the
624 * child process, so we cannot signal it. Return an error code in that case.
626 if (!vfexec
&& !spawn
) {
638 /* If posix_spawn binprefs exist, respect those prefs. */
639 psa
= (struct _posix_spawnattr
*) imgp
->ip_px_sa
;
640 if (psa
!= NULL
&& psa
->psa_binprefs
[0] != 0) {
641 struct fat_arch
*arches
= (struct fat_arch
*) (fat_header
+ 1);
642 int nfat_arch
= 0, pr
= 0, f
= 0;
644 nfat_arch
= OSSwapBigToHostInt32(fat_header
->nfat_arch
);
646 /* make sure bogus nfat_arch doesn't cause chaos - 19376072 */
647 if ( (sizeof(struct fat_header
) + (nfat_arch
* sizeof(struct fat_arch
))) > PAGE_SIZE
) {
652 /* Check each preference listed against all arches in header */
653 for (pr
= 0; pr
< NBINPREFS
; pr
++) {
654 cpu_type_t pref
= psa
->psa_binprefs
[pr
];
656 /* No suitable arch in the pref list */
661 if (pref
== CPU_TYPE_ANY
) {
662 /* Fall through to regular grading */
666 for (f
= 0; f
< nfat_arch
; f
++) {
667 cpu_type_t archtype
= OSSwapBigToHostInt32(
669 cpu_type_t archsubtype
= OSSwapBigToHostInt32(
670 arches
[f
].cpusubtype
) & ~CPU_SUBTYPE_MASK
;
671 if (pref
== archtype
&&
672 grade_binary(archtype
, archsubtype
)) {
673 /* We have a winner! */
674 fat_arch
.cputype
= archtype
;
675 fat_arch
.cpusubtype
= archsubtype
;
676 fat_arch
.offset
= OSSwapBigToHostInt32(
678 fat_arch
.size
= OSSwapBigToHostInt32(
680 fat_arch
.align
= OSSwapBigToHostInt32(
688 /* Look up our preferred architecture in the fat file. */
689 lret
= fatfile_getarch_affinity(imgp
->ip_vp
,
690 (vm_offset_t
)fat_header
,
692 (p
->p_flag
& P_AFFINITY
));
693 if (lret
!= LOAD_SUCCESS
) {
694 error
= load_return_to_errno(lret
);
699 /* Read the Mach-O header out of fat_arch */
700 error
= vn_rdwr(UIO_READ
, imgp
->ip_vp
, imgp
->ip_vdata
,
701 PAGE_SIZE
, fat_arch
.offset
,
702 UIO_SYSSPACE
, (IO_UNIT
|IO_NODELOCKED
),
708 /* Did we read a complete header? */
714 /* Success. Indicate we have identified an encapsulated binary */
716 imgp
->ip_arch_offset
= (user_size_t
)fat_arch
.offset
;
717 imgp
->ip_arch_size
= (user_size_t
)fat_arch
.size
;
720 kauth_cred_unref(&cred
);
727 * Image activator for mach-o 1.0 binaries.
729 * Parameters; struct image_params * image parameter block
731 * Returns: -1 not a fat binary (keep looking)
732 * -2 Success: encapsulated binary: reread
733 * >0 Failure: error number
734 * EBADARCH Mach-o binary, but with an unrecognized
736 * ENOMEM No memory for child process after -
737 * can only happen after vfork()
739 * Important: This image activator is NOT byte order neutral.
741 * Note: A return value other than -1 indicates subsequent image
742 * activators should not be given the opportunity to attempt
743 * to activate the image.
745 * TODO: More gracefully handle failures after vfork
748 exec_mach_imgact(struct image_params
*imgp
)
750 struct mach_header
*mach_header
= (struct mach_header
*)imgp
->ip_vdata
;
751 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
754 task_t new_task
= NULL
; /* protected by vfexec */
756 struct uthread
*uthread
;
757 vm_map_t old_map
= VM_MAP_NULL
;
760 load_result_t load_result
;
761 struct _posix_spawnattr
*psa
= NULL
;
762 int spawn
= (imgp
->ip_flags
& IMGPF_SPAWN
);
763 int vfexec
= (imgp
->ip_flags
& IMGPF_VFORK_EXEC
);
766 * make sure it's a Mach-O 1.0 or Mach-O 2.0 binary; the difference
767 * is a reserved field on the end, so for the most part, we can
768 * treat them as if they were identical. Reverse-endian Mach-O
769 * binaries are recognized but not compatible.
771 if ((mach_header
->magic
== MH_CIGAM
) ||
772 (mach_header
->magic
== MH_CIGAM_64
)) {
777 if ((mach_header
->magic
!= MH_MAGIC
) &&
778 (mach_header
->magic
!= MH_MAGIC_64
)) {
783 switch (mach_header
->filetype
) {
790 if (!imgp
->ip_origcputype
) {
791 imgp
->ip_origcputype
= mach_header
->cputype
;
792 imgp
->ip_origcpusubtype
= mach_header
->cpusubtype
;
795 task
= current_task();
796 thread
= current_thread();
797 uthread
= get_bsdthread_info(thread
);
799 if ((mach_header
->cputype
& CPU_ARCH_ABI64
) == CPU_ARCH_ABI64
)
800 imgp
->ip_flags
|= IMGPF_IS_64BIT
;
802 /* If posix_spawn binprefs exist, respect those prefs. */
803 psa
= (struct _posix_spawnattr
*) imgp
->ip_px_sa
;
804 if (psa
!= NULL
&& psa
->psa_binprefs
[0] != 0) {
806 for (pr
= 0; pr
< NBINPREFS
; pr
++) {
807 cpu_type_t pref
= psa
->psa_binprefs
[pr
];
809 /* No suitable arch in the pref list */
814 if (pref
== CPU_TYPE_ANY
) {
815 /* Jump to regular grading */
819 if (pref
== imgp
->ip_origcputype
) {
820 /* We have a match! */
828 if (!grade_binary(imgp
->ip_origcputype
, imgp
->ip_origcpusubtype
& ~CPU_SUBTYPE_MASK
)) {
833 /* Copy in arguments/environment from the old process */
834 error
= exec_extract_strings(imgp
);
838 error
= exec_add_apple_strings(imgp
);
842 AUDIT_ARG(argv
, imgp
->ip_startargv
, imgp
->ip_argc
,
843 imgp
->ip_endargv
- imgp
->ip_startargv
);
844 AUDIT_ARG(envv
, imgp
->ip_endargv
, imgp
->ip_envc
,
845 imgp
->ip_endenvv
- imgp
->ip_endargv
);
848 * We are being called to activate an image subsequent to a vfork()
849 * operation; in this case, we know that our task, thread, and
850 * uthread are actually those of our parent, and our proc, which we
851 * obtained indirectly from the image_params vfs_context_t, is the
854 if (vfexec
|| spawn
) {
856 imgp
->ip_new_thread
= fork_create_child(task
, COALITION_NULL
, p
, FALSE
, (imgp
->ip_flags
& IMGPF_IS_64BIT
));
857 if (imgp
->ip_new_thread
== NULL
) {
863 /* reset local idea of thread, uthread, task */
864 thread
= imgp
->ip_new_thread
;
865 uthread
= get_bsdthread_info(thread
);
866 task
= new_task
= get_threadtask(thread
);
867 map
= get_task_map(task
);
873 * We set these flags here; this is OK, since if we fail after
874 * this point, we have already destroyed the parent process anyway.
876 task_set_dyld_info(task
, MACH_VM_MIN_ADDRESS
, 0);
877 if (imgp
->ip_flags
& IMGPF_IS_64BIT
) {
878 task_set_64bit(task
, TRUE
);
879 OSBitOrAtomic(P_LP64
, &p
->p_flag
);
881 task_set_64bit(task
, FALSE
);
882 OSBitAndAtomic(~((uint32_t)P_LP64
), &p
->p_flag
);
886 * Load the Mach-O file.
888 * NOTE: An error after this point indicates we have potentially
889 * destroyed or overwritten some process state while attempting an
890 * execve() following a vfork(), which is an unrecoverable condition.
891 * We send the new process an immediate SIGKILL to avoid it executing
892 * any instructions in the mutated address space. For true spawns,
893 * this is not the case, and "too late" is still not too late to
894 * return an error code to the parent process.
898 * Actually load the image file we previously decided to load.
900 lret
= load_machfile(imgp
, mach_header
, thread
, map
, &load_result
);
902 if (lret
!= LOAD_SUCCESS
) {
903 error
= load_return_to_errno(lret
);
908 p
->p_cputype
= imgp
->ip_origcputype
;
909 p
->p_cpusubtype
= imgp
->ip_origcpusubtype
;
912 vm_map_set_user_wire_limit(get_task_map(task
), p
->p_rlimit
[RLIMIT_MEMLOCK
].rlim_cur
);
915 * Set code-signing flags if this binary is signed, or if parent has
916 * requested them on exec.
918 if (load_result
.csflags
& CS_VALID
) {
919 imgp
->ip_csflags
|= load_result
.csflags
&
921 CS_HARD
|CS_KILL
|CS_ENFORCEMENT
|CS_REQUIRE_LV
|CS_DYLD_PLATFORM
|
922 CS_EXEC_SET_HARD
|CS_EXEC_SET_KILL
|CS_EXEC_SET_ENFORCEMENT
);
924 imgp
->ip_csflags
&= ~CS_VALID
;
927 if (p
->p_csflags
& CS_EXEC_SET_HARD
)
928 imgp
->ip_csflags
|= CS_HARD
;
929 if (p
->p_csflags
& CS_EXEC_SET_KILL
)
930 imgp
->ip_csflags
|= CS_KILL
;
931 if (p
->p_csflags
& CS_EXEC_SET_ENFORCEMENT
)
932 imgp
->ip_csflags
|= CS_ENFORCEMENT
;
933 if (p
->p_csflags
& CS_EXEC_SET_INSTALLER
)
934 imgp
->ip_csflags
|= CS_INSTALLER
;
938 * Set up the system reserved areas in the new address space.
940 vm_map_exec(get_task_map(task
),
942 (void *) p
->p_fd
->fd_rdir
,
946 * Close file descriptors which specify close-on-exec.
948 fdexec(p
, psa
!= NULL
? psa
->psa_flags
: 0);
951 * deal with set[ug]id.
953 error
= exec_handle_sugid(imgp
);
959 * deal with voucher on exec-calling thread.
961 if (imgp
->ip_new_thread
== NULL
)
962 thread_set_mach_voucher(current_thread(), IPC_VOUCHER_NULL
);
964 /* Make sure we won't interrupt ourself signalling a partial process */
965 if (!vfexec
&& !spawn
&& (p
->p_lflag
& P_LTRACED
))
968 if (load_result
.unixproc
&&
969 create_unix_stack(get_task_map(task
),
971 p
) != KERN_SUCCESS
) {
972 error
= load_return_to_errno(LOAD_NOSPACE
);
976 if (vfexec
|| spawn
) {
977 old_map
= vm_map_switch(get_task_map(task
));
980 if (load_result
.unixproc
) {
984 * Copy the strings area out into the new process address
988 error
= exec_copyout_strings(imgp
, &ap
);
991 vm_map_switch(old_map
);
995 thread_setuserstack(thread
, ap
);
998 if (load_result
.dynlinker
) {
1000 int new_ptr_size
= (imgp
->ip_flags
& IMGPF_IS_64BIT
) ? 8 : 4;
1002 /* Adjust the stack */
1003 ap
= thread_adjuserstack(thread
, -new_ptr_size
);
1004 error
= copyoutptr(load_result
.mach_header
, ap
, new_ptr_size
);
1007 if (vfexec
|| spawn
)
1008 vm_map_switch(old_map
);
1011 task_set_dyld_info(task
, load_result
.all_image_info_addr
,
1012 load_result
.all_image_info_size
);
1015 /* Avoid immediate VM faults back into kernel */
1016 exec_prefault_data(p
, imgp
, &load_result
);
1018 if (vfexec
|| spawn
) {
1019 vm_map_switch(old_map
);
1021 /* Set the entry point */
1022 thread_setentrypoint(thread
, load_result
.entry_point
);
1024 /* Stop profiling */
1028 * Reset signal state.
1030 execsigs(p
, thread
);
1033 * need to cancel async IO requests that can be cancelled and wait for those
1034 * already active. MAY BLOCK!
1039 /* FIXME: Till vmspace inherit is fixed: */
1040 if (!vfexec
&& p
->vm_shm
)
1044 /* Clean up the semaphores */
1049 * Remember file name for accounting.
1051 p
->p_acflag
&= ~AFORK
;
1052 /* If the translated name isn't NULL, then we want to use
1053 * that translated name as the name we show as the "real" name.
1054 * Otherwise, use the name passed into exec.
1056 if (0 != imgp
->ip_p_comm
[0]) {
1057 bcopy((caddr_t
)imgp
->ip_p_comm
, (caddr_t
)p
->p_comm
,
1060 if (imgp
->ip_ndp
->ni_cnd
.cn_namelen
> MAXCOMLEN
)
1061 imgp
->ip_ndp
->ni_cnd
.cn_namelen
= MAXCOMLEN
;
1062 bcopy((caddr_t
)imgp
->ip_ndp
->ni_cnd
.cn_nameptr
, (caddr_t
)p
->p_comm
,
1063 (unsigned)imgp
->ip_ndp
->ni_cnd
.cn_namelen
);
1064 p
->p_comm
[imgp
->ip_ndp
->ni_cnd
.cn_namelen
] = '\0';
1067 pal_dbg_set_task_name( p
->task
);
1069 #if DEVELOPMENT || DEBUG
1071 * Update the pid an proc name for importance base if any
1073 task_importance_update_owner_info(p
->task
);
1076 memcpy(&p
->p_uuid
[0], &load_result
.uuid
[0], sizeof(p
->p_uuid
));
1078 // <rdar://6598155> dtrace code cleanup needed
1081 * Invalidate any predicate evaluation already cached for this thread by DTrace.
1082 * That's because we've just stored to p_comm and DTrace refers to that when it
1083 * evaluates the "execname" special variable. uid and gid may have changed as well.
1085 dtrace_set_thread_predcache(current_thread(), 0);
1088 * Free any outstanding lazy dof entries. It is imperative we
1089 * always call dtrace_lazy_dofs_destroy, rather than null check
1090 * and call if !NULL. If we NULL test, during lazy dof faulting
1091 * we can race with the faulting code and proceed from here to
1092 * beyond the helpers cleanup. The lazy dof faulting will then
1093 * install new helpers which no longer belong to this process!
1095 dtrace_lazy_dofs_destroy(p
);
1099 * Clean up any DTrace helpers for the process.
1101 if (p
->p_dtrace_helpers
!= NULL
&& dtrace_helpers_cleanup
) {
1102 (*dtrace_helpers_cleanup
)(p
);
1106 * Cleanup the DTrace provider associated with this process.
1109 if (p
->p_dtrace_probes
&& dtrace_fasttrap_exec_ptr
) {
1110 (*dtrace_fasttrap_exec_ptr
)(p
);
1115 if (kdebug_enable
) {
1116 long dbg_arg1
, dbg_arg2
, dbg_arg3
, dbg_arg4
;
1119 * Collect the pathname for tracing
1121 kdbg_trace_string(p
, &dbg_arg1
, &dbg_arg2
, &dbg_arg3
, &dbg_arg4
);
1123 if (vfexec
|| spawn
) {
1124 KERNEL_DEBUG_CONSTANT1(TRACE_DATA_EXEC
| DBG_FUNC_NONE
,
1125 p
->p_pid
,0,0,0, (uintptr_t)thread_tid(thread
));
1126 KERNEL_DEBUG_CONSTANT1(TRACE_STRING_EXEC
| DBG_FUNC_NONE
,
1127 dbg_arg1
, dbg_arg2
, dbg_arg3
, dbg_arg4
, (uintptr_t)thread_tid(thread
));
1129 KERNEL_DEBUG_CONSTANT(TRACE_DATA_EXEC
| DBG_FUNC_NONE
,
1131 KERNEL_DEBUG_CONSTANT(TRACE_STRING_EXEC
| DBG_FUNC_NONE
,
1132 dbg_arg1
, dbg_arg2
, dbg_arg3
, dbg_arg4
, 0);
1137 * Ensure the 'translated' and 'affinity' flags are cleared, since we
1138 * no longer run PowerPC binaries.
1140 OSBitAndAtomic(~((uint32_t)(P_TRANSLATED
| P_AFFINITY
)), &p
->p_flag
);
1143 * If posix_spawned with the START_SUSPENDED flag, stop the
1144 * process before it runs.
1146 if (imgp
->ip_px_sa
!= NULL
) {
1147 psa
= (struct _posix_spawnattr
*) imgp
->ip_px_sa
;
1148 if (psa
->psa_flags
& POSIX_SPAWN_START_SUSPENDED
) {
1152 (void) task_suspend(p
->task
);
1157 * mark as execed, wakeup the process that vforked (if any) and tell
1158 * it that it now has its own resources back
1160 OSBitOrAtomic(P_EXEC
, &p
->p_flag
);
1161 proc_resetregister(p
);
1162 if (p
->p_pptr
&& (p
->p_lflag
& P_LPPWAIT
)) {
1164 p
->p_lflag
&= ~P_LPPWAIT
;
1166 wakeup((caddr_t
)p
->p_pptr
);
1170 * Pay for our earlier safety; deliver the delayed signals from
1171 * the incomplete vfexec process now that it's complete.
1173 if (vfexec
&& (p
->p_lflag
& P_LTRACED
)) {
1174 psignal_vfork(p
, new_task
, thread
, SIGTRAP
);
1180 /* Don't allow child process to execute any instructions */
1183 psignal_vfork(p
, new_task
, thread
, SIGKILL
);
1185 psignal(p
, SIGKILL
);
1188 /* We can't stop this system call at this point, so just pretend we succeeded */
1194 /* notify only if it has not failed due to FP Key error */
1195 if ((p
->p_lflag
& P_LTERM_DECRYPTFAIL
) == 0)
1196 proc_knote(p
, NOTE_EXEC
);
1199 /* Drop extra references for cases where we don't expect the caller to clean up */
1200 if (vfexec
|| (spawn
&& error
== 0)) {
1201 task_deallocate(new_task
);
1202 thread_deallocate(thread
);
1213 * Our image activator table; this is the table of the image types we are
1214 * capable of loading. We list them in order of preference to ensure the
1215 * fastest image load speed.
1217 * XXX hardcoded, for now; should use linker sets
1220 int (*ex_imgact
)(struct image_params
*);
1221 const char *ex_name
;
1223 { exec_mach_imgact
, "Mach-o Binary" },
1224 { exec_fat_imgact
, "Fat Binary" },
1225 { exec_shell_imgact
, "Interpreter Script" },
1231 * exec_activate_image
1233 * Description: Iterate through the available image activators, and activate
1234 * the image associated with the imgp structure. We start with
1237 * Parameters: struct image_params * Image parameter block
1239 * Returns: 0 Success
1240 * EBADEXEC The executable is corrupt/unknown
1241 * execargs_alloc:EINVAL Invalid argument
1242 * execargs_alloc:EACCES Permission denied
1243 * execargs_alloc:EINTR Interrupted function
1244 * execargs_alloc:ENOMEM Not enough space
1245 * exec_save_path:EFAULT Bad address
1246 * exec_save_path:ENAMETOOLONG Filename too long
1247 * exec_check_permissions:EACCES Permission denied
1248 * exec_check_permissions:ENOEXEC Executable file format error
1249 * exec_check_permissions:ETXTBSY Text file busy [misuse of error code]
1250 * exec_check_permissions:???
1252 * vn_rdwr:??? [anything vn_rdwr can return]
1253 * <ex_imgact>:??? [anything an imgact can return]
1256 exec_activate_image(struct image_params
*imgp
)
1258 struct nameidata
*ndp
= NULL
;
1261 int once
= 1; /* save SGUID-ness for interpreted files */
1263 int iterlimit
= EAI_ITERLIMIT
;
1264 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
1266 error
= execargs_alloc(imgp
);
1270 error
= exec_save_path(imgp
, imgp
->ip_user_fname
, imgp
->ip_seg
);
1275 /* Use imgp->ip_strings, which contains the copyin-ed exec path */
1276 DTRACE_PROC1(exec
, uintptr_t, imgp
->ip_strings
);
1278 MALLOC(ndp
, struct nameidata
*, sizeof(*ndp
), M_TEMP
, M_WAITOK
| M_ZERO
);
1284 NDINIT(ndp
, LOOKUP
, OP_LOOKUP
, FOLLOW
| LOCKLEAF
| AUDITVNPATH1
,
1285 UIO_SYSSPACE
, CAST_USER_ADDR_T(imgp
->ip_strings
), imgp
->ip_vfs_context
);
1291 imgp
->ip_ndp
= ndp
; /* successful namei(); call nameidone() later */
1292 imgp
->ip_vp
= ndp
->ni_vp
; /* if set, need to vnode_put() at some point */
1295 * Before we start the transition from binary A to binary B, make
1296 * sure another thread hasn't started exiting the process. We grab
1297 * the proc lock to check p_lflag initially, and the transition
1298 * mechanism ensures that the value doesn't change after we release
1302 if (p
->p_lflag
& P_LEXIT
) {
1306 error
= proc_transstart(p
, 1, 0);
1311 error
= exec_check_permissions(imgp
);
1315 /* Copy; avoid invocation of an interpreter overwriting the original */
1318 *imgp
->ip_origvattr
= *imgp
->ip_vattr
;
1321 error
= vn_rdwr(UIO_READ
, imgp
->ip_vp
, imgp
->ip_vdata
, PAGE_SIZE
, 0,
1322 UIO_SYSSPACE
, IO_NODELOCKED
,
1323 vfs_context_ucred(imgp
->ip_vfs_context
),
1324 &resid
, vfs_context_proc(imgp
->ip_vfs_context
));
1328 encapsulated_binary
:
1329 /* Limit the number of iterations we will attempt on each binary */
1330 if (--iterlimit
== 0) {
1335 for(i
= 0; error
== -1 && execsw
[i
].ex_imgact
!= NULL
; i
++) {
1337 error
= (*execsw
[i
].ex_imgact
)(imgp
);
1340 /* case -1: not claimed: continue */
1341 case -2: /* Encapsulated binary */
1342 goto encapsulated_binary
;
1344 case -3: /* Interpreter */
1347 * Copy the script label for later use. Note that
1348 * the label can be different when the script is
1349 * actually read by the interpreter.
1351 if (imgp
->ip_scriptlabelp
)
1352 mac_vnode_label_free(imgp
->ip_scriptlabelp
);
1353 imgp
->ip_scriptlabelp
= mac_vnode_label_alloc();
1354 if (imgp
->ip_scriptlabelp
== NULL
) {
1358 mac_vnode_label_copy(imgp
->ip_vp
->v_label
,
1359 imgp
->ip_scriptlabelp
);
1362 * Take a ref of the script vnode for later use.
1364 if (imgp
->ip_scriptvp
)
1365 vnode_put(imgp
->ip_scriptvp
);
1366 if (vnode_getwithref(imgp
->ip_vp
) == 0)
1367 imgp
->ip_scriptvp
= imgp
->ip_vp
;
1372 vnode_put(imgp
->ip_vp
);
1373 imgp
->ip_vp
= NULL
; /* already put */
1374 imgp
->ip_ndp
= NULL
; /* already nameidone */
1376 /* Use imgp->ip_strings, which exec_shell_imgact reset to the interpreter */
1377 NDINIT(ndp
, LOOKUP
, OP_LOOKUP
, FOLLOW
| LOCKLEAF
,
1378 UIO_SYSSPACE
, CAST_USER_ADDR_T(imgp
->ip_strings
), imgp
->ip_vfs_context
);
1380 proc_transend(p
, 0);
1389 * Call out to allow 3rd party notification of exec.
1390 * Ignore result of kauth_authorize_fileop call.
1392 if (error
== 0 && kauth_authorize_fileop_has_listeners()) {
1393 kauth_authorize_fileop(vfs_context_ucred(imgp
->ip_vfs_context
),
1395 (uintptr_t)ndp
->ni_vp
, 0);
1399 proc_transend(p
, 0);
1402 if (imgp
->ip_strings
)
1403 execargs_free(imgp
);
1405 nameidone(imgp
->ip_ndp
);
1414 * exec_handle_spawnattr_policy
1416 * Description: Decode and apply the posix_spawn apptype, qos clamp, and watchport ports to the task.
1418 * Parameters: proc_t p process to apply attributes to
1419 * int psa_apptype posix spawn attribute apptype
1421 * Returns: 0 Success
1424 exec_handle_spawnattr_policy(proc_t p
, int psa_apptype
, uint64_t psa_qos_clamp
,
1425 ipc_port_t
* portwatch_ports
, int portwatch_count
)
1427 int apptype
= TASK_APPTYPE_NONE
;
1428 int qos_clamp
= THREAD_QOS_UNSPECIFIED
;
1430 if ((psa_apptype
& POSIX_SPAWN_PROC_TYPE_MASK
) != 0) {
1431 int proctype
= psa_apptype
& POSIX_SPAWN_PROC_TYPE_MASK
;
1434 case POSIX_SPAWN_PROC_TYPE_DAEMON_INTERACTIVE
:
1435 apptype
= TASK_APPTYPE_DAEMON_INTERACTIVE
;
1437 case POSIX_SPAWN_PROC_TYPE_DAEMON_STANDARD
:
1438 apptype
= TASK_APPTYPE_DAEMON_STANDARD
;
1440 case POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE
:
1441 apptype
= TASK_APPTYPE_DAEMON_ADAPTIVE
;
1443 case POSIX_SPAWN_PROC_TYPE_DAEMON_BACKGROUND
:
1444 apptype
= TASK_APPTYPE_DAEMON_BACKGROUND
;
1446 case POSIX_SPAWN_PROC_TYPE_APP_DEFAULT
:
1447 apptype
= TASK_APPTYPE_APP_DEFAULT
;
1449 case POSIX_SPAWN_PROC_TYPE_APP_TAL
:
1450 apptype
= TASK_APPTYPE_APP_TAL
;
1453 apptype
= TASK_APPTYPE_NONE
;
1454 /* TODO: Should an invalid value here fail the spawn? */
1459 if (psa_qos_clamp
!= POSIX_SPAWN_PROC_CLAMP_NONE
) {
1460 switch (psa_qos_clamp
) {
1461 case POSIX_SPAWN_PROC_CLAMP_UTILITY
:
1462 qos_clamp
= THREAD_QOS_UTILITY
;
1464 case POSIX_SPAWN_PROC_CLAMP_BACKGROUND
:
1465 qos_clamp
= THREAD_QOS_BACKGROUND
;
1467 case POSIX_SPAWN_PROC_CLAMP_MAINTENANCE
:
1468 qos_clamp
= THREAD_QOS_MAINTENANCE
;
1471 qos_clamp
= THREAD_QOS_UNSPECIFIED
;
1472 /* TODO: Should an invalid value here fail the spawn? */
1477 if (psa_apptype
!= TASK_APPTYPE_NONE
|| qos_clamp
!= THREAD_QOS_UNSPECIFIED
) {
1478 proc_set_task_spawnpolicy(p
->task
, apptype
, qos_clamp
,
1479 portwatch_ports
, portwatch_count
);
1487 * exec_handle_port_actions
1489 * Description: Go through the _posix_port_actions_t contents,
1490 * calling task_set_special_port, task_set_exception_ports
1491 * and/or audit_session_spawnjoin for the current task.
1493 * Parameters: struct image_params * Image parameter block
1494 * short psa_flags posix spawn attribute flags
1496 * Returns: 0 Success
1498 * ENOTSUP Illegal posix_spawn attr flag was set
1501 exec_handle_port_actions(struct image_params
*imgp
, short psa_flags
, boolean_t
* portwatch_present
, ipc_port_t
* portwatch_ports
)
1503 _posix_spawn_port_actions_t pacts
= imgp
->ip_px_spa
;
1504 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
1505 _ps_port_action_t
*act
= NULL
;
1506 task_t task
= p
->task
;
1507 ipc_port_t port
= NULL
;
1511 *portwatch_present
= FALSE
;
1513 for (i
= 0; i
< pacts
->pspa_count
; i
++) {
1514 act
= &pacts
->pspa_actions
[i
];
1516 if (ipc_object_copyin(get_task_ipcspace(current_task()),
1517 act
->new_port
, MACH_MSG_TYPE_COPY_SEND
,
1518 (ipc_object_t
*) &port
) != KERN_SUCCESS
) {
1523 switch (act
->port_type
) {
1525 /* Only allowed when not under vfork */
1526 if (!(psa_flags
& POSIX_SPAWN_SETEXEC
))
1528 else if (task_set_special_port(task
,
1529 act
->which
, port
) != KERN_SUCCESS
)
1533 case PSPA_EXCEPTION
:
1534 /* Only allowed when not under vfork */
1535 if (!(psa_flags
& POSIX_SPAWN_SETEXEC
))
1537 else if (task_set_exception_ports(task
,
1538 act
->mask
, port
, act
->behavior
,
1539 act
->flavor
) != KERN_SUCCESS
)
1543 case PSPA_AU_SESSION
:
1544 ret
= audit_session_spawnjoin(p
, port
);
1547 case PSPA_IMP_WATCHPORTS
:
1548 if (portwatch_ports
!= NULL
) {
1549 *portwatch_present
= TRUE
;
1550 /* hold on to this till end of spawn */
1551 portwatch_ports
[i
] = port
;
1554 ipc_port_release_send(port
);
1561 /* action failed, so release port resources */
1564 ipc_port_release_send(port
);
1571 DTRACE_PROC1(spawn__port__failure
, mach_port_name_t
, act
->new_port
);
1576 * exec_handle_file_actions
1578 * Description: Go through the _posix_file_actions_t contents applying the
1579 * open, close, and dup2 operations to the open file table for
1580 * the current process.
1582 * Parameters: struct image_params * Image parameter block
1584 * Returns: 0 Success
1587 * Note: Actions are applied in the order specified, with the credential
1588 * of the parent process. This is done to permit the parent
1589 * process to utilize POSIX_SPAWN_RESETIDS to drop privilege in
1590 * the child following operations the child may in fact not be
1591 * normally permitted to perform.
1594 exec_handle_file_actions(struct image_params
*imgp
, short psa_flags
)
1598 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
1599 _posix_spawn_file_actions_t px_sfap
= imgp
->ip_px_sfa
;
1600 int ival
[2]; /* dummy retval for system calls) */
1602 for (action
= 0; action
< px_sfap
->psfa_act_count
; action
++) {
1603 _psfa_action_t
*psfa
= &px_sfap
->psfa_act_acts
[ action
];
1605 switch(psfa
->psfaa_type
) {
1608 * Open is different, in that it requires the use of
1609 * a path argument, which is normally copied in from
1610 * user space; because of this, we have to support an
1611 * open from kernel space that passes an address space
1612 * context of UIO_SYSSPACE, and casts the address
1613 * argument to a user_addr_t.
1616 struct vnode_attr
*vap
;
1617 struct nameidata
*ndp
;
1618 int mode
= psfa
->psfaa_openargs
.psfao_mode
;
1619 struct dup2_args dup2a
;
1620 struct close_nocancel_args ca
;
1623 MALLOC(bufp
, char *, sizeof(*vap
) + sizeof(*ndp
), M_TEMP
, M_WAITOK
| M_ZERO
);
1629 vap
= (struct vnode_attr
*) bufp
;
1630 ndp
= (struct nameidata
*) (bufp
+ sizeof(*vap
));
1633 /* Mask off all but regular access permissions */
1634 mode
= ((mode
&~ p
->p_fd
->fd_cmask
) & ALLPERMS
) & ~S_ISTXT
;
1635 VATTR_SET(vap
, va_mode
, mode
& ACCESSPERMS
);
1637 NDINIT(ndp
, LOOKUP
, OP_OPEN
, FOLLOW
| AUDITVNPATH1
, UIO_SYSSPACE
,
1638 CAST_USER_ADDR_T(psfa
->psfaa_openargs
.psfao_path
),
1639 imgp
->ip_vfs_context
);
1641 error
= open1(imgp
->ip_vfs_context
,
1643 psfa
->psfaa_openargs
.psfao_oflag
,
1645 fileproc_alloc_init
, NULL
,
1651 * If there's an error, or we get the right fd by
1652 * accident, then drop out here. This is easier than
1653 * reworking all the open code to preallocate fd
1654 * slots, and internally taking one as an argument.
1656 if (error
|| ival
[0] == psfa
->psfaa_filedes
)
1661 * If we didn't fall out from an error, we ended up
1662 * with the wrong fd; so now we've got to try to dup2
1663 * it to the right one.
1665 dup2a
.from
= origfd
;
1666 dup2a
.to
= psfa
->psfaa_filedes
;
1669 * The dup2() system call implementation sets
1670 * ival to newfd in the success case, but we
1671 * can ignore that, since if we didn't get the
1672 * fd we wanted, the error will stop us.
1674 error
= dup2(p
, &dup2a
, ival
);
1679 * Finally, close the original fd.
1683 error
= close_nocancel(p
, &ca
, ival
);
1688 struct dup2_args dup2a
;
1690 dup2a
.from
= psfa
->psfaa_filedes
;
1691 dup2a
.to
= psfa
->psfaa_openargs
.psfao_oflag
;
1694 * The dup2() system call implementation sets
1695 * ival to newfd in the success case, but we
1696 * can ignore that, since if we didn't get the
1697 * fd we wanted, the error will stop us.
1699 error
= dup2(p
, &dup2a
, ival
);
1704 struct close_nocancel_args ca
;
1706 ca
.fd
= psfa
->psfaa_filedes
;
1708 error
= close_nocancel(p
, &ca
, ival
);
1712 case PSFA_INHERIT
: {
1713 struct fcntl_nocancel_args fcntla
;
1716 * Check to see if the descriptor exists, and
1717 * ensure it's -not- marked as close-on-exec.
1719 * Attempting to "inherit" a guarded fd will
1720 * result in a error.
1722 fcntla
.fd
= psfa
->psfaa_filedes
;
1723 fcntla
.cmd
= F_GETFD
;
1724 if ((error
= fcntl_nocancel(p
, &fcntla
, ival
)) != 0)
1727 if ((ival
[0] & FD_CLOEXEC
) == FD_CLOEXEC
) {
1728 fcntla
.fd
= psfa
->psfaa_filedes
;
1729 fcntla
.cmd
= F_SETFD
;
1730 fcntla
.arg
= ival
[0] & ~FD_CLOEXEC
;
1731 error
= fcntl_nocancel(p
, &fcntla
, ival
);
1742 /* All file actions failures are considered fatal, per POSIX */
1745 if (PSFA_OPEN
== psfa
->psfaa_type
) {
1746 DTRACE_PROC1(spawn__open__failure
, uintptr_t,
1747 psfa
->psfaa_openargs
.psfao_path
);
1749 DTRACE_PROC1(spawn__fd__failure
, int, psfa
->psfaa_filedes
);
1755 if (error
!= 0 || (psa_flags
& POSIX_SPAWN_CLOEXEC_DEFAULT
) == 0)
1759 * If POSIX_SPAWN_CLOEXEC_DEFAULT is set, behave (during
1760 * this spawn only) as if "close on exec" is the default
1761 * disposition of all pre-existing file descriptors. In this case,
1762 * the list of file descriptors mentioned in the file actions
1763 * are the only ones that can be inherited, so mark them now.
1765 * The actual closing part comes later, in fdexec().
1768 for (action
= 0; action
< px_sfap
->psfa_act_count
; action
++) {
1769 _psfa_action_t
*psfa
= &px_sfap
->psfa_act_acts
[action
];
1770 int fd
= psfa
->psfaa_filedes
;
1772 switch (psfa
->psfaa_type
) {
1774 fd
= psfa
->psfaa_openargs
.psfao_oflag
;
1778 *fdflags(p
, fd
) |= UF_INHERIT
;
1792 * exec_spawnattr_getmacpolicyinfo
1795 exec_spawnattr_getmacpolicyinfo(const void *macextensions
, const char *policyname
, size_t *lenp
)
1797 const struct _posix_spawn_mac_policy_extensions
*psmx
= macextensions
;
1803 for (i
= 0; i
< psmx
->psmx_count
; i
++) {
1804 const _ps_mac_policy_extension_t
*extension
= &psmx
->psmx_extensions
[i
];
1805 if (strncmp(extension
->policyname
, policyname
, sizeof(extension
->policyname
)) == 0) {
1807 *lenp
= extension
->datalen
;
1808 return extension
->datap
;
1818 spawn_copyin_macpolicyinfo(const struct user__posix_spawn_args_desc
*px_args
, _posix_spawn_mac_policy_extensions_t
*psmxp
)
1820 _posix_spawn_mac_policy_extensions_t psmx
= NULL
;
1827 if (px_args
->mac_extensions_size
< PS_MAC_EXTENSIONS_SIZE(1) ||
1828 px_args
->mac_extensions_size
> PAGE_SIZE
) {
1833 MALLOC(psmx
, _posix_spawn_mac_policy_extensions_t
, px_args
->mac_extensions_size
, M_TEMP
, M_WAITOK
);
1834 if ((error
= copyin(px_args
->mac_extensions
, psmx
, px_args
->mac_extensions_size
)) != 0)
1837 if (PS_MAC_EXTENSIONS_SIZE(psmx
->psmx_count
) > px_args
->mac_extensions_size
) {
1842 for (i
= 0; i
< psmx
->psmx_count
; i
++) {
1843 _ps_mac_policy_extension_t
*extension
= &psmx
->psmx_extensions
[i
];
1844 if (extension
->datalen
== 0 || extension
->datalen
> PAGE_SIZE
) {
1850 for (copycnt
= 0; copycnt
< psmx
->psmx_count
; copycnt
++) {
1851 _ps_mac_policy_extension_t
*extension
= &psmx
->psmx_extensions
[copycnt
];
1854 MALLOC(data
, void *, extension
->datalen
, M_TEMP
, M_WAITOK
);
1855 if ((error
= copyin(extension
->data
, data
, extension
->datalen
)) != 0) {
1859 extension
->datap
= data
;
1867 for (i
= 0; i
< copycnt
; i
++)
1868 FREE(psmx
->psmx_extensions
[i
].datap
, M_TEMP
);
1875 spawn_free_macpolicyinfo(_posix_spawn_mac_policy_extensions_t psmx
)
1881 for (i
= 0; i
< psmx
->psmx_count
; i
++)
1882 FREE(psmx
->psmx_extensions
[i
].datap
, M_TEMP
);
1885 #endif /* CONFIG_MACF */
1890 * Parameters: uap->pid Pointer to pid return area
1891 * uap->fname File name to exec
1892 * uap->argp Argument list
1893 * uap->envp Environment list
1895 * Returns: 0 Success
1896 * EINVAL Invalid argument
1897 * ENOTSUP Not supported
1898 * ENOEXEC Executable file format error
1899 * exec_activate_image:EINVAL Invalid argument
1900 * exec_activate_image:EACCES Permission denied
1901 * exec_activate_image:EINTR Interrupted function
1902 * exec_activate_image:ENOMEM Not enough space
1903 * exec_activate_image:EFAULT Bad address
1904 * exec_activate_image:ENAMETOOLONG Filename too long
1905 * exec_activate_image:ENOEXEC Executable file format error
1906 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
1907 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
1908 * exec_activate_image:???
1909 * mac_execve_enter:???
1911 * TODO: Expect to need __mac_posix_spawn() at some point...
1912 * Handle posix_spawnattr_t
1913 * Handle posix_spawn_file_actions_t
1916 posix_spawn(proc_t ap
, struct posix_spawn_args
*uap
, int32_t *retval
)
1918 proc_t p
= ap
; /* quiet bogus GCC vfork() warning */
1919 user_addr_t pid
= uap
->pid
;
1920 int ival
[2]; /* dummy retval for setpgid() */
1922 struct image_params
*imgp
;
1923 struct vnode_attr
*vap
;
1924 struct vnode_attr
*origvap
;
1925 struct uthread
*uthread
= 0; /* compiler complains if not set to 0*/
1927 char alt_p_comm
[sizeof(p
->p_comm
)] = {0}; /* for PowerPC */
1928 int is_64
= IS_64BIT_PROCESS(p
);
1929 struct vfs_context context
;
1930 struct user__posix_spawn_args_desc px_args
;
1931 struct _posix_spawnattr px_sa
;
1932 _posix_spawn_file_actions_t px_sfap
= NULL
;
1933 _posix_spawn_port_actions_t px_spap
= NULL
;
1934 struct __kern_sigaction vec
;
1935 boolean_t spawn_no_exec
= FALSE
;
1936 boolean_t proc_transit_set
= TRUE
;
1937 boolean_t exec_done
= FALSE
;
1938 int portwatch_count
= 0;
1939 ipc_port_t
* portwatch_ports
= NULL
;
1940 vm_size_t px_sa_offset
= offsetof(struct _posix_spawnattr
, psa_ports
);
1943 * Allocate a big chunk for locals instead of using stack since these
1944 * structures are pretty big.
1946 MALLOC(bufp
, char *, (sizeof(*imgp
) + sizeof(*vap
) + sizeof(*origvap
)), M_TEMP
, M_WAITOK
| M_ZERO
);
1947 imgp
= (struct image_params
*) bufp
;
1952 vap
= (struct vnode_attr
*) (bufp
+ sizeof(*imgp
));
1953 origvap
= (struct vnode_attr
*) (bufp
+ sizeof(*imgp
) + sizeof(*vap
));
1955 /* Initialize the common data in the image_params structure */
1956 imgp
->ip_user_fname
= uap
->path
;
1957 imgp
->ip_user_argv
= uap
->argv
;
1958 imgp
->ip_user_envv
= uap
->envp
;
1959 imgp
->ip_vattr
= vap
;
1960 imgp
->ip_origvattr
= origvap
;
1961 imgp
->ip_vfs_context
= &context
;
1962 imgp
->ip_flags
= (is_64
? IMGPF_WAS_64BIT
: IMGPF_NONE
);
1963 imgp
->ip_p_comm
= alt_p_comm
; /* for PowerPC */
1964 imgp
->ip_seg
= (is_64
? UIO_USERSPACE64
: UIO_USERSPACE32
);
1965 imgp
->ip_mac_return
= 0;
1967 if (uap
->adesc
!= USER_ADDR_NULL
) {
1969 error
= copyin(uap
->adesc
, &px_args
, sizeof(px_args
));
1971 struct user32__posix_spawn_args_desc px_args32
;
1973 error
= copyin(uap
->adesc
, &px_args32
, sizeof(px_args32
));
1976 * Convert arguments descriptor from external 32 bit
1977 * representation to internal 64 bit representation
1979 px_args
.attr_size
= px_args32
.attr_size
;
1980 px_args
.attrp
= CAST_USER_ADDR_T(px_args32
.attrp
);
1981 px_args
.file_actions_size
= px_args32
.file_actions_size
;
1982 px_args
.file_actions
= CAST_USER_ADDR_T(px_args32
.file_actions
);
1983 px_args
.port_actions_size
= px_args32
.port_actions_size
;
1984 px_args
.port_actions
= CAST_USER_ADDR_T(px_args32
.port_actions
);
1985 px_args
.mac_extensions_size
= px_args32
.mac_extensions_size
;
1986 px_args
.mac_extensions
= CAST_USER_ADDR_T(px_args32
.mac_extensions
);
1991 if (px_args
.attr_size
!= 0) {
1993 * We are not copying the port_actions pointer,
1994 * because we already have it from px_args.
1995 * This is a bit fragile: <rdar://problem/16427422>
1998 if ((error
= copyin(px_args
.attrp
, &px_sa
, px_sa_offset
) != 0))
2001 bzero( (void *)( (unsigned long) &px_sa
+ px_sa_offset
), sizeof(px_sa
) - px_sa_offset
);
2003 imgp
->ip_px_sa
= &px_sa
;
2005 if (px_args
.file_actions_size
!= 0) {
2006 /* Limit file_actions to allowed number of open files */
2007 int maxfa
= (p
->p_limit
? p
->p_rlimit
[RLIMIT_NOFILE
].rlim_cur
: NOFILE
);
2008 if (px_args
.file_actions_size
< PSF_ACTIONS_SIZE(1) ||
2009 px_args
.file_actions_size
> PSF_ACTIONS_SIZE(maxfa
)) {
2013 MALLOC(px_sfap
, _posix_spawn_file_actions_t
, px_args
.file_actions_size
, M_TEMP
, M_WAITOK
);
2014 if (px_sfap
== NULL
) {
2018 imgp
->ip_px_sfa
= px_sfap
;
2020 if ((error
= copyin(px_args
.file_actions
, px_sfap
,
2021 px_args
.file_actions_size
)) != 0)
2024 /* Verify that the action count matches the struct size */
2025 if (PSF_ACTIONS_SIZE(px_sfap
->psfa_act_count
) != px_args
.file_actions_size
) {
2030 if (px_args
.port_actions_size
!= 0) {
2031 /* Limit port_actions to one page of data */
2032 if (px_args
.port_actions_size
< PS_PORT_ACTIONS_SIZE(1) ||
2033 px_args
.port_actions_size
> PAGE_SIZE
) {
2038 MALLOC(px_spap
, _posix_spawn_port_actions_t
,
2039 px_args
.port_actions_size
, M_TEMP
, M_WAITOK
);
2040 if (px_spap
== NULL
) {
2044 imgp
->ip_px_spa
= px_spap
;
2046 if ((error
= copyin(px_args
.port_actions
, px_spap
,
2047 px_args
.port_actions_size
)) != 0)
2050 /* Verify that the action count matches the struct size */
2051 if (PS_PORT_ACTIONS_SIZE(px_spap
->pspa_count
) != px_args
.port_actions_size
) {
2057 if (px_args
.mac_extensions_size
!= 0) {
2058 if ((error
= spawn_copyin_macpolicyinfo(&px_args
, (_posix_spawn_mac_policy_extensions_t
*)&imgp
->ip_px_smpx
)) != 0)
2061 #endif /* CONFIG_MACF */
2064 /* set uthread to parent */
2065 uthread
= get_bsdthread_info(current_thread());
2068 * <rdar://6640530>; this does not result in a behaviour change
2069 * relative to Leopard, so there should not be any existing code
2070 * which depends on it.
2072 if (uthread
->uu_flag
& UT_VFORK
) {
2078 * If we don't have the extension flag that turns "posix_spawn()"
2079 * into "execve() with options", then we will be creating a new
2080 * process which does not inherit memory from the parent process,
2081 * which is one of the most expensive things about using fork()
2084 if (imgp
->ip_px_sa
== NULL
|| !(px_sa
.psa_flags
& POSIX_SPAWN_SETEXEC
)){
2087 * Set the new task's coalition, if it is requested.
2088 * TODO: privilege check - 15365900
2090 coalition_t coal
= COALITION_NULL
;
2091 #if CONFIG_COALITIONS
2092 if (imgp
->ip_px_sa
) {
2093 uint64_t cid
= px_sa
.psa_coalitionid
;
2096 printf("%s: searching for coalition ID %llu\n", __func__
, cid
);
2098 coal
= coalition_find_and_activate_by_id(cid
);
2099 if (coal
== COALITION_NULL
) {
2101 printf("%s: could not find coalition ID %llu (perhaps it has been terminated or reaped)\n", __func__
, cid
);
2108 #endif /* CONFIG_COALITIONS */
2110 error
= fork1(p
, &imgp
->ip_new_thread
, PROC_CREATE_SPAWN
, coal
);
2113 if (coal
!= COALITION_NULL
) {
2114 #if CONFIG_COALITIONS
2115 coalition_remove_active(coal
);
2116 coalition_release(coal
);
2117 #endif /* CONFIG_COALITIONS */
2121 imgp
->ip_flags
|= IMGPF_SPAWN
; /* spawn w/o exec */
2122 spawn_no_exec
= TRUE
; /* used in later tests */
2124 if (coal
!= COALITION_NULL
) {
2125 #if CONFIG_COALITIONS
2126 coalition_remove_active(coal
);
2127 coalition_release(coal
);
2128 #endif /* CONFIG_COALITIONS */
2132 if (spawn_no_exec
) {
2133 p
= (proc_t
)get_bsdthreadtask_info(imgp
->ip_new_thread
);
2136 * We had to wait until this point before firing the
2137 * proc:::create probe, otherwise p would not point to the
2140 DTRACE_PROC1(create
, proc_t
, p
);
2144 /* By default, the thread everyone plays with is the parent */
2145 context
.vc_thread
= current_thread();
2146 context
.vc_ucred
= p
->p_ucred
; /* XXX must NOT be kauth_cred_get() */
2149 * However, if we're not in the setexec case, redirect the context
2150 * to the newly created process instead
2153 context
.vc_thread
= imgp
->ip_new_thread
;
2156 * Post fdcopy(), pre exec_handle_sugid() - this is where we want
2157 * to handle the file_actions. Since vfork() also ends up setting
2158 * us into the parent process group, and saved off the signal flags,
2159 * this is also where we want to handle the spawn flags.
2162 /* Has spawn file actions? */
2163 if (imgp
->ip_px_sfa
!= NULL
) {
2165 * The POSIX_SPAWN_CLOEXEC_DEFAULT flag
2166 * is handled in exec_handle_file_actions().
2168 if ((error
= exec_handle_file_actions(imgp
,
2169 imgp
->ip_px_sa
!= NULL
? px_sa
.psa_flags
: 0)) != 0)
2173 /* Has spawn port actions? */
2174 if (imgp
->ip_px_spa
!= NULL
) {
2175 boolean_t is_adaptive
= FALSE
;
2176 boolean_t portwatch_present
= FALSE
;
2178 /* Will this process become adaptive? The apptype isn't ready yet, so we can't look there. */
2179 if (imgp
->ip_px_sa
!= NULL
&& px_sa
.psa_apptype
== POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE
)
2184 * Allocate a place to store the ports we want to bind to the new task
2185 * We can't bind them until after the apptype is set.
2187 if (px_spap
->pspa_count
!= 0 && is_adaptive
) {
2188 portwatch_count
= px_spap
->pspa_count
;
2189 MALLOC(portwatch_ports
, ipc_port_t
*, (sizeof(ipc_port_t
) * portwatch_count
), M_TEMP
, M_WAITOK
| M_ZERO
);
2191 portwatch_ports
= NULL
;
2194 if ((error
= exec_handle_port_actions(imgp
,
2195 imgp
->ip_px_sa
!= NULL
? px_sa
.psa_flags
: 0, &portwatch_present
, portwatch_ports
)) != 0)
2198 if (portwatch_present
== FALSE
&& portwatch_ports
!= NULL
) {
2199 FREE(portwatch_ports
, M_TEMP
);
2200 portwatch_ports
= NULL
;
2201 portwatch_count
= 0;
2205 /* Has spawn attr? */
2206 if (imgp
->ip_px_sa
!= NULL
) {
2208 * Set the process group ID of the child process; this has
2209 * to happen before the image activation.
2211 if (px_sa
.psa_flags
& POSIX_SPAWN_SETPGROUP
) {
2212 struct setpgid_args spga
;
2213 spga
.pid
= p
->p_pid
;
2214 spga
.pgid
= px_sa
.psa_pgroup
;
2216 * Effectively, call setpgid() system call; works
2217 * because there are no pointer arguments.
2219 if((error
= setpgid(p
, &spga
, ival
)) != 0)
2224 * Reset UID/GID to parent's RUID/RGID; This works only
2225 * because the operation occurs *after* the vfork() and
2226 * before the call to exec_handle_sugid() by the image
2227 * activator called from exec_activate_image(). POSIX
2228 * requires that any setuid/setgid bits on the process
2229 * image will take precedence over the spawn attributes
2232 * The use of p_ucred is safe, since we are acting on the
2233 * new process, and it has no threads other than the one
2234 * we are creating for it.
2236 if (px_sa
.psa_flags
& POSIX_SPAWN_RESETIDS
) {
2237 kauth_cred_t my_cred
= p
->p_ucred
;
2238 kauth_cred_t my_new_cred
= kauth_cred_setuidgid(my_cred
, kauth_cred_getruid(my_cred
), kauth_cred_getrgid(my_cred
));
2239 if (my_new_cred
!= my_cred
) {
2240 p
->p_ucred
= my_new_cred
;
2241 /* update cred on proc */
2242 PROC_UPDATE_CREDS_ONPROC(p
);
2247 * Disable ASLR for the spawned process.
2250 * But only do so if we are not embedded; embedded allows for a
2251 * boot-arg (-disable_aslr) to deal with this (which itself is
2252 * only honored on DEVELOPMENT or DEBUG builds of xnu).
2254 if (px_sa
.psa_flags
& _POSIX_SPAWN_DISABLE_ASLR
)
2255 OSBitOrAtomic(P_DISABLE_ASLR
, &p
->p_flag
);
2258 * Forcibly disallow execution from data pages for the spawned process
2259 * even if it would otherwise be permitted by the architecture default.
2261 if (px_sa
.psa_flags
& _POSIX_SPAWN_ALLOW_DATA_EXEC
)
2262 imgp
->ip_flags
|= IMGPF_ALLOW_DATA_EXEC
;
2266 * Disable ASLR during image activation. This occurs either if the
2267 * _POSIX_SPAWN_DISABLE_ASLR attribute was found above or if
2268 * P_DISABLE_ASLR was inherited from the parent process.
2270 if (p
->p_flag
& P_DISABLE_ASLR
)
2271 imgp
->ip_flags
|= IMGPF_DISABLE_ASLR
;
2274 * Clear transition flag so we won't hang if exec_activate_image() causes
2275 * an automount (and launchd does a proc sysctl to service it).
2277 * <rdar://problem/6848672>, <rdar://problem/5959568>.
2279 if (spawn_no_exec
) {
2280 proc_transend(p
, 0);
2281 proc_transit_set
= 0;
2284 #if MAC_SPAWN /* XXX */
2285 if (uap
->mac_p
!= USER_ADDR_NULL
) {
2286 error
= mac_execve_enter(uap
->mac_p
, imgp
);
2293 * Activate the image
2295 error
= exec_activate_image(imgp
);
2298 /* process completed the exec */
2300 } else if (error
== -1) {
2301 /* Image not claimed by any activator? */
2306 * If we have a spawn attr, and it contains signal related flags,
2307 * the we need to process them in the "context" of the new child
2308 * process, so we have to process it following image activation,
2309 * prior to making the thread runnable in user space. This is
2310 * necessitated by some signal information being per-thread rather
2311 * than per-process, and we don't have the new allocation in hand
2312 * until after the image is activated.
2314 if (!error
&& imgp
->ip_px_sa
!= NULL
) {
2315 thread_t child_thread
= current_thread();
2316 uthread_t child_uthread
= uthread
;
2319 * If we created a new child thread, then the thread and
2320 * uthread are different than the current ones; otherwise,
2321 * we leave them, since we are in the exec case instead.
2323 if (spawn_no_exec
) {
2324 child_thread
= imgp
->ip_new_thread
;
2325 child_uthread
= get_bsdthread_info(child_thread
);
2329 * Mask a list of signals, instead of them being unmasked, if
2330 * they were unmasked in the parent; note that some signals
2333 if (px_sa
.psa_flags
& POSIX_SPAWN_SETSIGMASK
)
2334 child_uthread
->uu_sigmask
= (px_sa
.psa_sigmask
& ~sigcantmask
);
2336 * Default a list of signals instead of ignoring them, if
2337 * they were ignored in the parent. Note that we pass
2338 * spawn_no_exec to setsigvec() to indicate that we called
2339 * fork1() and therefore do not need to call proc_signalstart()
2342 if (px_sa
.psa_flags
& POSIX_SPAWN_SETSIGDEF
) {
2343 vec
.sa_handler
= SIG_DFL
;
2347 for (sig
= 0; sig
< NSIG
; sig
++)
2348 if (px_sa
.psa_sigdefault
& (1 << sig
)) {
2349 error
= setsigvec(p
, child_thread
, sig
+ 1, &vec
, spawn_no_exec
);
2354 * Activate the CPU usage monitor, if requested. This is done via a task-wide, per-thread CPU
2355 * usage limit, which will generate a resource exceeded exception if any one thread exceeds the
2358 * Userland gives us interval in seconds, and the kernel SPI expects nanoseconds.
2360 if (px_sa
.psa_cpumonitor_percent
!= 0) {
2362 * Always treat a CPU monitor activation coming from spawn as entitled. Requiring
2363 * an entitlement to configure the monitor a certain way seems silly, since
2364 * whomever is turning it on could just as easily choose not to do so.
2366 * XXX - Ignore the parameters that we get from userland. The spawnattr method of
2367 * activating the monitor always gets the system default parameters. Once we have
2368 * an explicit spawn SPI for configuring the defaults, we can revert this to
2369 * respect the params passed in from userland.
2371 error
= proc_set_task_ruse_cpu(p
->task
,
2372 TASK_POLICY_RESOURCE_ATTRIBUTE_NOTIFY_EXC
,
2373 PROC_POLICY_CPUMON_DEFAULTS
, 0,
2381 /* reset delay idle sleep status if set */
2382 if ((p
->p_flag
& P_DELAYIDLESLEEP
) == P_DELAYIDLESLEEP
)
2383 OSBitAndAtomic(~((uint32_t)P_DELAYIDLESLEEP
), &p
->p_flag
);
2384 /* upon successful spawn, re/set the proc control state */
2385 if (imgp
->ip_px_sa
!= NULL
) {
2386 switch (px_sa
.psa_pcontrol
) {
2387 case POSIX_SPAWN_PCONTROL_THROTTLE
:
2388 p
->p_pcaction
= P_PCTHROTTLE
;
2390 case POSIX_SPAWN_PCONTROL_SUSPEND
:
2391 p
->p_pcaction
= P_PCSUSP
;
2393 case POSIX_SPAWN_PCONTROL_KILL
:
2394 p
->p_pcaction
= P_PCKILL
;
2396 case POSIX_SPAWN_PCONTROL_NONE
:
2402 exec_resettextvp(p
, imgp
);
2404 #if CONFIG_MEMORYSTATUS && CONFIG_JETSAM
2405 /* Has jetsam attributes? */
2406 if (imgp
->ip_px_sa
!= NULL
&& (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_SET
)) {
2407 memorystatus_update(p
, px_sa
.psa_priority
, 0, (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY
),
2408 TRUE
, px_sa
.psa_high_water_mark
, (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND
),
2409 (px_sa
.psa_jetsam_flags
& POSIX_SPAWN_JETSAM_MEMLIMIT_FATAL
));
2415 * If we successfully called fork1(), we always need to do this;
2416 * we identify this case by noting the IMGPF_SPAWN flag. This is
2417 * because we come back from that call with signals blocked in the
2418 * child, and we have to unblock them, but we want to wait until
2419 * after we've performed any spawn actions. This has to happen
2420 * before check_for_signature(), which uses psignal.
2422 if (spawn_no_exec
) {
2423 if (proc_transit_set
)
2424 proc_transend(p
, 0);
2427 * Drop the signal lock on the child which was taken on our
2428 * behalf by forkproc()/cloneproc() to prevent signals being
2429 * received by the child in a partially constructed state.
2431 proc_signalend(p
, 0);
2433 /* flag the 'fork' has occurred */
2434 proc_knote(p
->p_pptr
, NOTE_FORK
| p
->p_pid
);
2435 /* then flag exec has occurred */
2436 /* notify only if it has not failed due to FP Key error */
2437 if ((p
->p_lflag
& P_LTERM_DECRYPTFAIL
) == 0)
2438 proc_knote(p
, NOTE_EXEC
);
2439 } else if (error
== 0) {
2440 /* reset the importance attribute from our previous life */
2441 task_importance_reset(p
->task
);
2443 /* reset atm context from task */
2444 task_atm_reset(p
->task
);
2448 * Apply the spawnattr policy, apptype (which primes the task for importance donation),
2449 * and bind any portwatch ports to the new task.
2450 * This must be done after the exec so that the child's thread is ready,
2451 * and after the in transit state has been released, because priority is
2452 * dropped here so we need to be prepared for a potentially long preemption interval
2454 * TODO: Consider splitting this up into separate phases
2456 if (error
== 0 && imgp
->ip_px_sa
!= NULL
) {
2457 struct _posix_spawnattr
*psa
= (struct _posix_spawnattr
*) imgp
->ip_px_sa
;
2459 exec_handle_spawnattr_policy(p
, psa
->psa_apptype
, psa
->psa_qos_clamp
,
2460 portwatch_ports
, portwatch_count
);
2463 /* Apply the main thread qos */
2465 thread_t main_thread
= (imgp
->ip_new_thread
!= NULL
) ? imgp
->ip_new_thread
: current_thread();
2467 task_set_main_thread_qos(p
->task
, main_thread
);
2471 * Release any ports we kept around for binding to the new task
2472 * We need to release the rights even if the posix_spawn has failed.
2474 if (portwatch_ports
!= NULL
) {
2475 for (int i
= 0; i
< portwatch_count
; i
++) {
2476 ipc_port_t port
= NULL
;
2477 if ((port
= portwatch_ports
[i
]) != NULL
) {
2478 ipc_port_release_send(port
);
2481 FREE(portwatch_ports
, M_TEMP
);
2482 portwatch_ports
= NULL
;
2483 portwatch_count
= 0;
2487 * We have to delay operations which might throw a signal until after
2488 * the signals have been unblocked; however, we want that to happen
2489 * after exec_resettextvp() so that the textvp is correct when they
2493 error
= check_for_signature(p
, imgp
);
2496 * Pay for our earlier safety; deliver the delayed signals from
2497 * the incomplete spawn process now that it's complete.
2499 if (imgp
!= NULL
&& spawn_no_exec
&& (p
->p_lflag
& P_LTRACED
)) {
2500 psignal_vfork(p
, p
->task
, imgp
->ip_new_thread
, SIGTRAP
);
2507 vnode_put(imgp
->ip_vp
);
2508 if (imgp
->ip_scriptvp
)
2509 vnode_put(imgp
->ip_scriptvp
);
2510 if (imgp
->ip_strings
)
2511 execargs_free(imgp
);
2512 if (imgp
->ip_px_sfa
!= NULL
)
2513 FREE(imgp
->ip_px_sfa
, M_TEMP
);
2514 if (imgp
->ip_px_spa
!= NULL
)
2515 FREE(imgp
->ip_px_spa
, M_TEMP
);
2518 if (imgp
->ip_px_smpx
!= NULL
)
2519 spawn_free_macpolicyinfo(imgp
->ip_px_smpx
);
2520 if (imgp
->ip_execlabelp
)
2521 mac_cred_label_free(imgp
->ip_execlabelp
);
2522 if (imgp
->ip_scriptlabelp
)
2523 mac_vnode_label_free(imgp
->ip_scriptlabelp
);
2528 if (spawn_no_exec
) {
2530 * In the original DTrace reference implementation,
2531 * posix_spawn() was a libc routine that just
2532 * did vfork(2) then exec(2). Thus the proc::: probes
2533 * are very fork/exec oriented. The details of this
2534 * in-kernel implementation of posix_spawn() is different
2535 * (while producing the same process-observable effects)
2536 * particularly w.r.t. errors, and which thread/process
2537 * is constructing what on behalf of whom.
2540 DTRACE_PROC1(spawn__failure
, int, error
);
2542 DTRACE_PROC(spawn__success
);
2544 * Some DTrace scripts, e.g. newproc.d in
2545 * /usr/bin, rely on the the 'exec-success'
2546 * probe being fired in the child after the
2547 * new process image has been constructed
2548 * in order to determine the associated pid.
2550 * So, even though the parent built the image
2551 * here, for compatibility, mark the new thread
2552 * so 'exec-success' fires on it as it leaves
2555 dtrace_thread_didexec(imgp
->ip_new_thread
);
2559 DTRACE_PROC1(exec__failure
, int, error
);
2561 DTRACE_PROC(exec__success
);
2565 if ((dtrace_proc_waitfor_hook
= dtrace_proc_waitfor_exec_ptr
) != NULL
)
2566 (*dtrace_proc_waitfor_hook
)(p
);
2569 /* Return to both the parent and the child? */
2570 if (imgp
!= NULL
&& spawn_no_exec
) {
2572 * If the parent wants the pid, copy it out
2574 if (pid
!= USER_ADDR_NULL
)
2575 (void)suword(pid
, p
->p_pid
);
2579 * If we had an error, perform an internal reap ; this is
2580 * entirely safe, as we have a real process backing us.
2584 p
->p_listflag
|= P_LIST_DEADPARENT
;
2587 /* make sure no one else has killed it off... */
2588 if (p
->p_stat
!= SZOMB
&& p
->exit_thread
== NULL
) {
2589 p
->exit_thread
= current_thread();
2591 exit1(p
, 1, (int *)NULL
);
2592 if (exec_done
== FALSE
) {
2593 task_deallocate(get_threadtask(imgp
->ip_new_thread
));
2594 thread_deallocate(imgp
->ip_new_thread
);
2597 /* someone is doing it for us; just skip it */
2603 * Return to the child
2605 * Note: the image activator earlier dropped the
2606 * task/thread references to the newly spawned
2607 * process; this is OK, since we still have suspended
2608 * queue references on them, so we should be fine
2609 * with the delayed resume of the thread here.
2611 (void)thread_resume(imgp
->ip_new_thread
);
2625 * Parameters: uap->fname File name to exec
2626 * uap->argp Argument list
2627 * uap->envp Environment list
2629 * Returns: 0 Success
2630 * __mac_execve:EINVAL Invalid argument
2631 * __mac_execve:ENOTSUP Invalid argument
2632 * __mac_execve:EACCES Permission denied
2633 * __mac_execve:EINTR Interrupted function
2634 * __mac_execve:ENOMEM Not enough space
2635 * __mac_execve:EFAULT Bad address
2636 * __mac_execve:ENAMETOOLONG Filename too long
2637 * __mac_execve:ENOEXEC Executable file format error
2638 * __mac_execve:ETXTBSY Text file busy [misuse of error code]
2641 * TODO: Dynamic linker header address on stack is copied via suword()
2645 execve(proc_t p
, struct execve_args
*uap
, int32_t *retval
)
2647 struct __mac_execve_args muap
;
2650 memoryshot(VM_EXECVE
, DBG_FUNC_NONE
);
2652 muap
.fname
= uap
->fname
;
2653 muap
.argp
= uap
->argp
;
2654 muap
.envp
= uap
->envp
;
2655 muap
.mac_p
= USER_ADDR_NULL
;
2656 err
= __mac_execve(p
, &muap
, retval
);
2664 * Parameters: uap->fname File name to exec
2665 * uap->argp Argument list
2666 * uap->envp Environment list
2667 * uap->mac_p MAC label supplied by caller
2669 * Returns: 0 Success
2670 * EINVAL Invalid argument
2671 * ENOTSUP Not supported
2672 * ENOEXEC Executable file format error
2673 * exec_activate_image:EINVAL Invalid argument
2674 * exec_activate_image:EACCES Permission denied
2675 * exec_activate_image:EINTR Interrupted function
2676 * exec_activate_image:ENOMEM Not enough space
2677 * exec_activate_image:EFAULT Bad address
2678 * exec_activate_image:ENAMETOOLONG Filename too long
2679 * exec_activate_image:ENOEXEC Executable file format error
2680 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
2681 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
2682 * exec_activate_image:???
2683 * mac_execve_enter:???
2685 * TODO: Dynamic linker header address on stack is copied via suword()
2688 __mac_execve(proc_t p
, struct __mac_execve_args
*uap
, int32_t *retval
)
2691 struct image_params
*imgp
;
2692 struct vnode_attr
*vap
;
2693 struct vnode_attr
*origvap
;
2695 char alt_p_comm
[sizeof(p
->p_comm
)] = {0}; /* for PowerPC */
2696 int is_64
= IS_64BIT_PROCESS(p
);
2697 struct vfs_context context
;
2698 struct uthread
*uthread
;
2700 context
.vc_thread
= current_thread();
2701 context
.vc_ucred
= kauth_cred_proc_ref(p
); /* XXX must NOT be kauth_cred_get() */
2703 /* Allocate a big chunk for locals instead of using stack since these
2704 * structures a pretty big.
2706 MALLOC(bufp
, char *, (sizeof(*imgp
) + sizeof(*vap
) + sizeof(*origvap
)), M_TEMP
, M_WAITOK
| M_ZERO
);
2707 imgp
= (struct image_params
*) bufp
;
2710 goto exit_with_error
;
2712 vap
= (struct vnode_attr
*) (bufp
+ sizeof(*imgp
));
2713 origvap
= (struct vnode_attr
*) (bufp
+ sizeof(*imgp
) + sizeof(*vap
));
2715 /* Initialize the common data in the image_params structure */
2716 imgp
->ip_user_fname
= uap
->fname
;
2717 imgp
->ip_user_argv
= uap
->argp
;
2718 imgp
->ip_user_envv
= uap
->envp
;
2719 imgp
->ip_vattr
= vap
;
2720 imgp
->ip_origvattr
= origvap
;
2721 imgp
->ip_vfs_context
= &context
;
2722 imgp
->ip_flags
= (is_64
? IMGPF_WAS_64BIT
: IMGPF_NONE
) | ((p
->p_flag
& P_DISABLE_ASLR
) ? IMGPF_DISABLE_ASLR
: IMGPF_NONE
);
2723 imgp
->ip_p_comm
= alt_p_comm
; /* for PowerPC */
2724 imgp
->ip_seg
= (is_64
? UIO_USERSPACE64
: UIO_USERSPACE32
);
2725 imgp
->ip_mac_return
= 0;
2727 uthread
= get_bsdthread_info(current_thread());
2728 if (uthread
->uu_flag
& UT_VFORK
) {
2729 imgp
->ip_flags
|= IMGPF_VFORK_EXEC
;
2733 if (uap
->mac_p
!= USER_ADDR_NULL
) {
2734 error
= mac_execve_enter(uap
->mac_p
, imgp
);
2736 kauth_cred_unref(&context
.vc_ucred
);
2737 goto exit_with_error
;
2742 error
= exec_activate_image(imgp
);
2744 kauth_cred_unref(&context
.vc_ucred
);
2746 /* Image not claimed by any activator? */
2751 exec_resettextvp(p
, imgp
);
2752 error
= check_for_signature(p
, imgp
);
2754 if (imgp
->ip_vp
!= NULLVP
)
2755 vnode_put(imgp
->ip_vp
);
2756 if (imgp
->ip_scriptvp
!= NULLVP
)
2757 vnode_put(imgp
->ip_scriptvp
);
2758 if (imgp
->ip_strings
)
2759 execargs_free(imgp
);
2761 if (imgp
->ip_execlabelp
)
2762 mac_cred_label_free(imgp
->ip_execlabelp
);
2763 if (imgp
->ip_scriptlabelp
)
2764 mac_vnode_label_free(imgp
->ip_scriptlabelp
);
2767 /* Sever any extant thread affinity */
2768 thread_affinity_exec(current_thread());
2770 thread_t main_thread
= (imgp
->ip_new_thread
!= NULL
) ? imgp
->ip_new_thread
: current_thread();
2772 task_set_main_thread_qos(p
->task
, main_thread
);
2774 /* reset task importance */
2775 task_importance_reset(p
->task
);
2777 /* reset atm context from task */
2778 task_atm_reset(p
->task
);
2780 DTRACE_PROC(exec__success
);
2783 if ((dtrace_proc_waitfor_hook
= dtrace_proc_waitfor_exec_ptr
) != NULL
)
2784 (*dtrace_proc_waitfor_hook
)(p
);
2787 if (imgp
->ip_flags
& IMGPF_VFORK_EXEC
) {
2788 vfork_return(p
, retval
, p
->p_pid
);
2789 (void)thread_resume(imgp
->ip_new_thread
);
2792 DTRACE_PROC1(exec__failure
, int, error
);
2807 * Description: Copy a pointer in from user space to a user_addr_t in kernel
2808 * space, based on 32/64 bitness of the user space
2810 * Parameters: froma User space address
2811 * toptr Address of kernel space user_addr_t
2812 * ptr_size 4/8, based on 'froma' address space
2814 * Returns: 0 Success
2815 * EFAULT Bad 'froma'
2818 * *ptr_size Modified
2821 copyinptr(user_addr_t froma
, user_addr_t
*toptr
, int ptr_size
)
2825 if (ptr_size
== 4) {
2826 /* 64 bit value containing 32 bit address */
2829 error
= copyin(froma
, &i
, 4);
2830 *toptr
= CAST_USER_ADDR_T(i
); /* SAFE */
2832 error
= copyin(froma
, toptr
, 8);
2841 * Description: Copy a pointer out from a user_addr_t in kernel space to
2842 * user space, based on 32/64 bitness of the user space
2844 * Parameters: ua User space address to copy to
2845 * ptr Address of kernel space user_addr_t
2846 * ptr_size 4/8, based on 'ua' address space
2848 * Returns: 0 Success
2853 copyoutptr(user_addr_t ua
, user_addr_t ptr
, int ptr_size
)
2857 if (ptr_size
== 4) {
2858 /* 64 bit value containing 32 bit address */
2859 unsigned int i
= CAST_DOWN_EXPLICIT(unsigned int,ua
); /* SAFE */
2861 error
= copyout(&i
, ptr
, 4);
2863 error
= copyout(&ua
, ptr
, 8);
2870 * exec_copyout_strings
2872 * Copy out the strings segment to user space. The strings segment is put
2873 * on a preinitialized stack frame.
2875 * Parameters: struct image_params * the image parameter block
2876 * int * a pointer to the stack offset variable
2878 * Returns: 0 Success
2882 * (*stackp) The stack offset, modified
2884 * Note: The strings segment layout is backward, from the beginning
2885 * of the top of the stack to consume the minimal amount of
2886 * space possible; the returned stack pointer points to the
2887 * end of the area consumed (stacks grow downward).
2889 * argc is an int; arg[i] are pointers; env[i] are pointers;
2890 * the 0's are (void *)NULL's
2892 * The stack frame layout is:
2894 * +-------------+ <- p->user_stack
2935 * sp-> +-------------+
2937 * Although technically a part of the STRING AREA, we treat the PATH AREA as
2938 * a separate entity. This allows us to align the beginning of the PATH AREA
2939 * to a pointer boundary so that the exec_path, env[i], and argv[i] pointers
2940 * which preceed it on the stack are properly aligned.
2944 exec_copyout_strings(struct image_params
*imgp
, user_addr_t
*stackp
)
2946 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
2947 int ptr_size
= (imgp
->ip_flags
& IMGPF_IS_64BIT
) ? 8 : 4;
2949 void *ptr_buffer_start
, *ptr_buffer
;
2952 user_addr_t string_area
; /* *argv[], *env[] */
2953 user_addr_t ptr_area
; /* argv[], env[], applev[] */
2954 user_addr_t argc_area
; /* argc */
2959 struct copyout_desc
{
2963 user_addr_t
*dtrace_cookie
;
2965 boolean_t null_term
;
2968 .start_string
= imgp
->ip_startargv
,
2969 .count
= imgp
->ip_argc
,
2971 .dtrace_cookie
= &p
->p_dtrace_argv
,
2976 .start_string
= imgp
->ip_endargv
,
2977 .count
= imgp
->ip_envc
,
2979 .dtrace_cookie
= &p
->p_dtrace_envp
,
2984 .start_string
= imgp
->ip_strings
,
2987 .dtrace_cookie
= NULL
,
2992 .start_string
= imgp
->ip_endenvv
,
2993 .count
= imgp
->ip_applec
- 1, /* exec_path handled above */
2995 .dtrace_cookie
= NULL
,
3004 * All previous contributors to the string area
3005 * should have aligned their sub-area
3007 if (imgp
->ip_strspace
% ptr_size
!= 0) {
3012 /* Grow the stack down for the strings we've been building up */
3013 string_size
= imgp
->ip_strendp
- imgp
->ip_strings
;
3014 stack
-= string_size
;
3015 string_area
= stack
;
3018 * Need room for one pointer for each string, plus
3019 * one for the NULLs terminating the argv, envv, and apple areas.
3021 ptr_area_size
= (imgp
->ip_argc
+ imgp
->ip_envc
+ imgp
->ip_applec
+ 3) *
3023 stack
-= ptr_area_size
;
3026 /* We'll construct all the pointer arrays in our string buffer,
3027 * which we already know is aligned properly, and ip_argspace
3028 * was used to verify we have enough space.
3030 ptr_buffer_start
= ptr_buffer
= (void *)imgp
->ip_strendp
;
3033 * Need room for pointer-aligned argc slot.
3039 * Record the size of the arguments area so that sysctl_procargs()
3040 * can return the argument area without having to parse the arguments.
3043 p
->p_argc
= imgp
->ip_argc
;
3044 p
->p_argslen
= (int)(*stackp
- string_area
);
3047 /* Return the initial stack address: the location of argc */
3051 * Copy out the entire strings area.
3053 error
= copyout(imgp
->ip_strings
, string_area
,
3058 for (i
= 0; i
< sizeof(descriptors
)/sizeof(descriptors
[0]); i
++) {
3059 char *cur_string
= descriptors
[i
].start_string
;
3063 if (descriptors
[i
].dtrace_cookie
) {
3065 *descriptors
[i
].dtrace_cookie
= ptr_area
+ ((uintptr_t)ptr_buffer
- (uintptr_t)ptr_buffer_start
); /* dtrace convenience */
3068 #endif /* CONFIG_DTRACE */
3071 * For each segment (argv, envv, applev), copy as many pointers as requested
3072 * to our pointer buffer.
3074 for (j
= 0; j
< descriptors
[i
].count
; j
++) {
3075 user_addr_t cur_address
= string_area
+ (cur_string
- imgp
->ip_strings
);
3077 /* Copy out the pointer to the current string. Alignment has been verified */
3078 if (ptr_size
== 8) {
3079 *(uint64_t *)ptr_buffer
= (uint64_t)cur_address
;
3081 *(uint32_t *)ptr_buffer
= (uint32_t)cur_address
;
3084 ptr_buffer
= (void *)((uintptr_t)ptr_buffer
+ ptr_size
);
3085 cur_string
+= strlen(cur_string
) + 1; /* Only a NUL between strings in the same area */
3088 if (descriptors
[i
].null_term
) {
3089 if (ptr_size
== 8) {
3090 *(uint64_t *)ptr_buffer
= 0ULL;
3092 *(uint32_t *)ptr_buffer
= 0;
3095 ptr_buffer
= (void *)((uintptr_t)ptr_buffer
+ ptr_size
);
3100 * Copy out all our pointer arrays in bulk.
3102 error
= copyout(ptr_buffer_start
, ptr_area
,
3107 /* argc (int32, stored in a ptr_size area) */
3108 error
= copyoutptr((user_addr_t
)imgp
->ip_argc
, argc_area
, ptr_size
);
3118 * exec_extract_strings
3120 * Copy arguments and environment from user space into work area; we may
3121 * have already copied some early arguments into the work area, and if
3122 * so, any arguments opied in are appended to those already there.
3123 * This function is the primary manipulator of ip_argspace, since
3124 * these are the arguments the client of execve(2) knows about. After
3125 * each argv[]/envv[] string is copied, we charge the string length
3126 * and argv[]/envv[] pointer slot to ip_argspace, so that we can
3127 * full preflight the arg list size.
3129 * Parameters: struct image_params * the image parameter block
3131 * Returns: 0 Success
3135 * (imgp->ip_argc) Count of arguments, updated
3136 * (imgp->ip_envc) Count of environment strings, updated
3137 * (imgp->ip_argspace) Count of remaining of NCARGS
3138 * (imgp->ip_interp_buffer) Interpreter and args (mutated in place)
3141 * Note: The argument and environment vectors are user space pointers
3142 * to arrays of user space pointers.
3145 exec_extract_strings(struct image_params
*imgp
)
3148 int ptr_size
= (imgp
->ip_flags
& IMGPF_WAS_64BIT
) ? 8 : 4;
3149 int new_ptr_size
= (imgp
->ip_flags
& IMGPF_IS_64BIT
) ? 8 : 4;
3150 user_addr_t argv
= imgp
->ip_user_argv
;
3151 user_addr_t envv
= imgp
->ip_user_envv
;
3154 * Adjust space reserved for the path name by however much padding it
3155 * needs. Doing this here since we didn't know if this would be a 32-
3156 * or 64-bit process back in exec_save_path.
3158 while (imgp
->ip_strspace
% new_ptr_size
!= 0) {
3159 *imgp
->ip_strendp
++ = '\0';
3160 imgp
->ip_strspace
--;
3161 /* imgp->ip_argspace--; not counted towards exec args total */
3165 * From now on, we start attributing string space to ip_argspace
3167 imgp
->ip_startargv
= imgp
->ip_strendp
;
3170 if((imgp
->ip_flags
& IMGPF_INTERPRET
) != 0) {
3172 char *argstart
, *ch
;
3174 /* First, the arguments in the "#!" string are tokenized and extracted. */
3175 argstart
= imgp
->ip_interp_buffer
;
3178 while (*ch
&& !IS_WHITESPACE(*ch
)) {
3183 /* last argument, no need to NUL-terminate */
3184 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(argstart
), UIO_SYSSPACE
, TRUE
);
3189 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(argstart
), UIO_SYSSPACE
, TRUE
);
3192 * Find the next string. We know spaces at the end of the string have already
3196 while (IS_WHITESPACE(*argstart
)) {
3201 /* Error-check, regardless of whether this is the last interpreter arg or not */
3204 if (imgp
->ip_argspace
< new_ptr_size
) {
3208 imgp
->ip_argspace
-= new_ptr_size
; /* to hold argv[] entry */
3214 * If we are running an interpreter, replace the av[0] that was
3215 * passed to execve() with the path name that was
3216 * passed to execve() for interpreters which do not use the PATH
3217 * to locate their script arguments.
3219 error
= copyinptr(argv
, &arg
, ptr_size
);
3223 argv
+= ptr_size
; /* consume without using */
3227 if (imgp
->ip_interp_sugid_fd
!= -1) {
3228 char temp
[19]; /* "/dev/fd/" + 10 digits + NUL */
3229 snprintf(temp
, sizeof(temp
), "/dev/fd/%d", imgp
->ip_interp_sugid_fd
);
3230 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(temp
), UIO_SYSSPACE
, TRUE
);
3232 error
= exec_add_user_string(imgp
, imgp
->ip_user_fname
, imgp
->ip_seg
, TRUE
);
3237 if (imgp
->ip_argspace
< new_ptr_size
) {
3241 imgp
->ip_argspace
-= new_ptr_size
; /* to hold argv[] entry */
3245 while (argv
!= 0LL) {
3248 error
= copyinptr(argv
, &arg
, ptr_size
);
3261 error
= exec_add_user_string(imgp
, arg
, imgp
->ip_seg
, TRUE
);
3264 if (imgp
->ip_argspace
< new_ptr_size
) {
3268 imgp
->ip_argspace
-= new_ptr_size
; /* to hold argv[] entry */
3272 /* Save space for argv[] NULL terminator */
3273 if (imgp
->ip_argspace
< new_ptr_size
) {
3277 imgp
->ip_argspace
-= new_ptr_size
;
3279 /* Note where the args ends and env begins. */
3280 imgp
->ip_endargv
= imgp
->ip_strendp
;
3283 /* Now, get the environment */
3284 while (envv
!= 0LL) {
3287 error
= copyinptr(envv
, &env
, ptr_size
);
3298 error
= exec_add_user_string(imgp
, env
, imgp
->ip_seg
, TRUE
);
3301 if (imgp
->ip_argspace
< new_ptr_size
) {
3305 imgp
->ip_argspace
-= new_ptr_size
; /* to hold envv[] entry */
3309 /* Save space for envv[] NULL terminator */
3310 if (imgp
->ip_argspace
< new_ptr_size
) {
3314 imgp
->ip_argspace
-= new_ptr_size
;
3316 /* Align the tail of the combined argv+envv area */
3317 while (imgp
->ip_strspace
% new_ptr_size
!= 0) {
3318 if (imgp
->ip_argspace
< 1) {
3322 *imgp
->ip_strendp
++ = '\0';
3323 imgp
->ip_strspace
--;
3324 imgp
->ip_argspace
--;
3327 /* Note where the envv ends and applev begins. */
3328 imgp
->ip_endenvv
= imgp
->ip_strendp
;
3331 * From now on, we are no longer charging argument
3332 * space to ip_argspace.
3340 random_hex_str(char *str
, int len
, boolean_t embedNUL
)
3342 uint64_t low
, high
, value
;
3346 /* A 64-bit value will only take 16 characters, plus '0x' and NULL. */
3350 /* We need enough room for at least 1 digit */
3356 value
= high
<< 32 | low
;
3360 * Zero a byte to protect against C string vulnerabilities
3361 * e.g. for userland __stack_chk_guard.
3363 value
&= ~(0xffull
<< 8);
3368 for (idx
= 2; idx
< len
- 1; idx
++) {
3369 digit
= value
& 0xf;
3372 str
[idx
] = '0' + digit
;
3374 str
[idx
] = 'a' + (digit
- 10);
3381 * Libc has an 8-element array set up for stack guard values. It only fills
3382 * in one of those entries, and both gcc and llvm seem to use only a single
3383 * 8-byte guard. Until somebody needs more than an 8-byte guard value, don't
3384 * do the work to construct them.
3386 #define GUARD_VALUES 1
3387 #define GUARD_KEY "stack_guard="
3390 * System malloc needs some entropy when it is initialized.
3392 #define ENTROPY_VALUES 2
3393 #define ENTROPY_KEY "malloc_entropy="
3396 * System malloc engages nanozone for UIAPP.
3398 #define NANO_ENGAGE_KEY "MallocNanoZone=1"
3400 #define PFZ_KEY "pfz="
3401 extern user32_addr_t commpage_text32_location
;
3402 extern user64_addr_t commpage_text64_location
;
3404 * Build up the contents of the apple[] string vector
3407 exec_add_apple_strings(struct image_params
*imgp
)
3412 char guard_vec
[strlen(GUARD_KEY
) + 19 * GUARD_VALUES
+ 1];
3415 char entropy_vec
[strlen(ENTROPY_KEY
) + 19 * ENTROPY_VALUES
+ 1];
3417 char pfz_string
[strlen(PFZ_KEY
) + 16 + 4 +1];
3419 if( imgp
->ip_flags
& IMGPF_IS_64BIT
) {
3421 snprintf(pfz_string
, sizeof(pfz_string
),PFZ_KEY
"0x%llx",commpage_text64_location
);
3423 snprintf(pfz_string
, sizeof(pfz_string
),PFZ_KEY
"0x%x",commpage_text32_location
);
3426 /* exec_save_path stored the first string */
3427 imgp
->ip_applec
= 1;
3429 /* adding the pfz string */
3430 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(pfz_string
),UIO_SYSSPACE
,FALSE
);
3435 /* adding the NANO_ENGAGE_KEY key */
3436 if (imgp
->ip_px_sa
) {
3437 int proc_flags
= (((struct _posix_spawnattr
*) imgp
->ip_px_sa
)->psa_flags
);
3439 if ((proc_flags
& _POSIX_SPAWN_NANO_ALLOCATOR
) == _POSIX_SPAWN_NANO_ALLOCATOR
) {
3440 char uiapp_string
[strlen(NANO_ENGAGE_KEY
) + 1];
3442 snprintf(uiapp_string
, sizeof(uiapp_string
), NANO_ENGAGE_KEY
);
3443 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(uiapp_string
),UIO_SYSSPACE
,FALSE
);
3451 * Supply libc with a collection of random values to use when
3452 * implementing -fstack-protector.
3454 * (The first random string always contains an embedded NUL so that
3455 * __stack_chk_guard also protects against C string vulnerabilities)
3457 (void)strlcpy(guard_vec
, GUARD_KEY
, sizeof (guard_vec
));
3458 for (i
= 0; i
< GUARD_VALUES
; i
++) {
3459 random_hex_str(guard
, sizeof (guard
), i
== 0);
3461 (void)strlcat(guard_vec
, ",", sizeof (guard_vec
));
3462 (void)strlcat(guard_vec
, guard
, sizeof (guard_vec
));
3465 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(guard_vec
), UIO_SYSSPACE
, FALSE
);
3471 * Supply libc with entropy for system malloc.
3473 (void)strlcpy(entropy_vec
, ENTROPY_KEY
, sizeof(entropy_vec
));
3474 for (i
= 0; i
< ENTROPY_VALUES
; i
++) {
3475 random_hex_str(entropy
, sizeof (entropy
), FALSE
);
3477 (void)strlcat(entropy_vec
, ",", sizeof (entropy_vec
));
3478 (void)strlcat(entropy_vec
, entropy
, sizeof (entropy_vec
));
3481 error
= exec_add_user_string(imgp
, CAST_USER_ADDR_T(entropy_vec
), UIO_SYSSPACE
, FALSE
);
3486 /* Align the tail of the combined applev area */
3487 while (imgp
->ip_strspace
% new_ptr_size
!= 0) {
3488 *imgp
->ip_strendp
++ = '\0';
3489 imgp
->ip_strspace
--;
3496 #define unix_stack_size(p) (p->p_rlimit[RLIMIT_STACK].rlim_cur)
3499 * exec_check_permissions
3501 * Description: Verify that the file that is being attempted to be executed
3502 * is in fact allowed to be executed based on it POSIX file
3503 * permissions and other access control criteria
3505 * Parameters: struct image_params * the image parameter block
3507 * Returns: 0 Success
3508 * EACCES Permission denied
3509 * ENOEXEC Executable file format error
3510 * ETXTBSY Text file busy [misuse of error code]
3512 * vnode_authorize:???
3515 exec_check_permissions(struct image_params
*imgp
)
3517 struct vnode
*vp
= imgp
->ip_vp
;
3518 struct vnode_attr
*vap
= imgp
->ip_vattr
;
3519 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
3521 kauth_action_t action
;
3523 /* Only allow execution of regular files */
3524 if (!vnode_isreg(vp
))
3527 /* Get the file attributes that we will be using here and elsewhere */
3529 VATTR_WANTED(vap
, va_uid
);
3530 VATTR_WANTED(vap
, va_gid
);
3531 VATTR_WANTED(vap
, va_mode
);
3532 VATTR_WANTED(vap
, va_fsid
);
3533 VATTR_WANTED(vap
, va_fileid
);
3534 VATTR_WANTED(vap
, va_data_size
);
3535 if ((error
= vnode_getattr(vp
, vap
, imgp
->ip_vfs_context
)) != 0)
3539 * Ensure that at least one execute bit is on - otherwise root
3540 * will always succeed, and we don't want to happen unless the
3541 * file really is executable.
3543 if (!vfs_authopaque(vnode_mount(vp
)) && ((vap
->va_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)) == 0))
3546 /* Disallow zero length files */
3547 if (vap
->va_data_size
== 0)
3550 imgp
->ip_arch_offset
= (user_size_t
)0;
3551 imgp
->ip_arch_size
= vap
->va_data_size
;
3553 /* Disable setuid-ness for traced programs or if MNT_NOSUID */
3554 if ((vp
->v_mount
->mnt_flag
& MNT_NOSUID
) || (p
->p_lflag
& P_LTRACED
))
3555 vap
->va_mode
&= ~(VSUID
| VSGID
);
3558 * Disable _POSIX_SPAWN_ALLOW_DATA_EXEC and _POSIX_SPAWN_DISABLE_ASLR
3559 * flags for setuid/setgid binaries.
3561 if (vap
->va_mode
& (VSUID
| VSGID
))
3562 imgp
->ip_flags
&= ~(IMGPF_ALLOW_DATA_EXEC
| IMGPF_DISABLE_ASLR
);
3565 error
= mac_vnode_check_exec(imgp
->ip_vfs_context
, vp
, imgp
);
3570 /* Check for execute permission */
3571 action
= KAUTH_VNODE_EXECUTE
;
3572 /* Traced images must also be readable */
3573 if (p
->p_lflag
& P_LTRACED
)
3574 action
|= KAUTH_VNODE_READ_DATA
;
3575 if ((error
= vnode_authorize(vp
, NULL
, action
, imgp
->ip_vfs_context
)) != 0)
3579 /* Don't let it run if anyone had it open for writing */
3581 if (vp
->v_writecount
) {
3582 panic("going to return ETXTBSY %x", vp
);
3590 /* XXX May want to indicate to underlying FS that vnode is open */
3599 * Initially clear the P_SUGID in the process flags; if an SUGID process is
3600 * exec'ing a non-SUGID image, then this is the point of no return.
3602 * If the image being activated is SUGID, then replace the credential with a
3603 * copy, disable tracing (unless the tracing process is root), reset the
3604 * mach task port to revoke it, set the P_SUGID bit,
3606 * If the saved user and group ID will be changing, then make sure it happens
3607 * to a new credential, rather than a shared one.
3609 * Set the security token (this is probably obsolete, given that the token
3610 * should not technically be separate from the credential itself).
3612 * Parameters: struct image_params * the image parameter block
3614 * Returns: void No failure indication
3617 * <process credential> Potentially modified/replaced
3618 * <task port> Potentially revoked
3619 * <process flags> P_SUGID bit potentially modified
3620 * <security token> Potentially modified
3623 exec_handle_sugid(struct image_params
*imgp
)
3625 kauth_cred_t cred
= vfs_context_ucred(imgp
->ip_vfs_context
);
3626 proc_t p
= vfs_context_proc(imgp
->ip_vfs_context
);
3628 int leave_sugid_clear
= 0;
3629 int mac_reset_ipc
= 0;
3632 int mac_transition
, disjoint_cred
= 0;
3633 int label_update_return
= 0;
3636 * Determine whether a call to update the MAC label will result in the
3637 * credential changing.
3639 * Note: MAC policies which do not actually end up modifying
3640 * the label subsequently are strongly encouraged to
3641 * return 0 for this check, since a non-zero answer will
3642 * slow down the exec fast path for normal binaries.
3644 mac_transition
= mac_cred_check_label_update_execve(
3645 imgp
->ip_vfs_context
,
3647 imgp
->ip_arch_offset
,
3649 imgp
->ip_scriptlabelp
,
3650 imgp
->ip_execlabelp
,
3655 OSBitAndAtomic(~((uint32_t)P_SUGID
), &p
->p_flag
);
3658 * Order of the following is important; group checks must go last,
3659 * as we use the success of the 'ismember' check combined with the
3660 * failure of the explicit match to indicate that we will be setting
3661 * the egid of the process even though the new process did not
3662 * require VSUID/VSGID bits in order for it to set the new group as
3665 * Note: Technically, by this we are implying a call to
3666 * setegid() in the new process, rather than implying
3667 * it used its VSGID bit to set the effective group,
3668 * even though there is no code in that process to make
3671 if (((imgp
->ip_origvattr
->va_mode
& VSUID
) != 0 &&
3672 kauth_cred_getuid(cred
) != imgp
->ip_origvattr
->va_uid
) ||
3673 ((imgp
->ip_origvattr
->va_mode
& VSGID
) != 0 &&
3674 ((kauth_cred_ismember_gid(cred
, imgp
->ip_origvattr
->va_gid
, &leave_sugid_clear
) || !leave_sugid_clear
) ||
3675 (kauth_cred_getgid(cred
) != imgp
->ip_origvattr
->va_gid
)))) {
3678 /* label for MAC transition and neither VSUID nor VSGID */
3679 handle_mac_transition
:
3683 * Replace the credential with a copy of itself if euid or
3686 * Note: setuid binaries will automatically opt out of
3687 * group resolver participation as a side effect
3688 * of this operation. This is an intentional
3689 * part of the security model, which requires a
3690 * participating credential be established by
3691 * escalating privilege, setting up all other
3692 * aspects of the credential including whether
3693 * or not to participate in external group
3694 * membership resolution, then dropping their
3695 * effective privilege to that of the desired
3696 * final credential state.
3698 if (imgp
->ip_origvattr
->va_mode
& VSUID
) {
3699 p
->p_ucred
= kauth_cred_setresuid(p
->p_ucred
, KAUTH_UID_NONE
, imgp
->ip_origvattr
->va_uid
, imgp
->ip_origvattr
->va_uid
, KAUTH_UID_NONE
);
3700 /* update cred on proc */
3701 PROC_UPDATE_CREDS_ONPROC(p
);
3703 if (imgp
->ip_origvattr
->va_mode
& VSGID
) {
3704 p
->p_ucred
= kauth_cred_setresgid(p
->p_ucred
, KAUTH_GID_NONE
, imgp
->ip_origvattr
->va_gid
, imgp
->ip_origvattr
->va_gid
);
3705 /* update cred on proc */
3706 PROC_UPDATE_CREDS_ONPROC(p
);
3711 * If a policy has indicated that it will transition the label,
3712 * before making the call into the MAC policies, get a new
3713 * duplicate credential, so they can modify it without
3714 * modifying any others sharing it.
3716 if (mac_transition
) {
3717 kauth_proc_label_update_execve(p
,
3718 imgp
->ip_vfs_context
,
3720 imgp
->ip_arch_offset
,
3722 imgp
->ip_scriptlabelp
,
3723 imgp
->ip_execlabelp
,
3726 &disjoint_cred
, /* will be non zero if disjoint */
3727 &label_update_return
);
3729 if (disjoint_cred
) {
3731 * If updating the MAC label resulted in a
3732 * disjoint credential, flag that we need to
3733 * set the P_SUGID bit. This protects
3734 * against debuggers being attached by an
3735 * insufficiently privileged process onto the
3736 * result of a transition to a more privileged
3739 leave_sugid_clear
= 0;
3742 imgp
->ip_mac_return
= label_update_return
;
3745 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
);
3747 #endif /* CONFIG_MACF */
3750 * If 'leave_sugid_clear' is non-zero, then we passed the
3751 * VSUID and MACF checks, and successfully determined that
3752 * the previous cred was a member of the VSGID group, but
3753 * that it was not the default at the time of the execve,
3754 * and that the post-labelling credential was not disjoint.
3755 * So we don't set the P_SUGID or reset mach ports and fds
3756 * on the basis of simply running this code.
3758 if (mac_reset_ipc
|| !leave_sugid_clear
) {
3760 * Have mach reset the task and thread ports.
3761 * We don't want anyone who had the ports before
3762 * a setuid exec to be able to access/control the
3763 * task/thread after.
3765 ipc_task_reset(p
->task
);
3766 ipc_thread_reset((imgp
->ip_new_thread
!= NULL
) ?
3767 imgp
->ip_new_thread
: current_thread());
3770 if (!leave_sugid_clear
) {
3772 * Flag the process as setuid.
3774 OSBitOrAtomic(P_SUGID
, &p
->p_flag
);
3777 * Radar 2261856; setuid security hole fix
3778 * XXX For setuid processes, attempt to ensure that
3779 * stdin, stdout, and stderr are already allocated.
3780 * We do not want userland to accidentally allocate
3781 * descriptors in this range which has implied meaning
3784 for (i
= 0; i
< 3; i
++) {
3786 if (p
->p_fd
->fd_ofiles
[i
] != NULL
)
3790 * Do the kernel equivalent of
3793 * (void) open("/dev/null", O_RDONLY);
3795 * (void) open("/dev/null", O_WRONLY);
3798 struct fileproc
*fp
;
3801 struct nameidata
*ndp
= NULL
;
3808 if ((error
= falloc(p
,
3809 &fp
, &indx
, imgp
->ip_vfs_context
)) != 0)
3812 MALLOC(ndp
, struct nameidata
*, sizeof(*ndp
), M_TEMP
, M_WAITOK
| M_ZERO
);
3818 NDINIT(ndp
, LOOKUP
, OP_OPEN
, FOLLOW
, UIO_SYSSPACE
,
3819 CAST_USER_ADDR_T("/dev/null"),
3820 imgp
->ip_vfs_context
);
3822 if ((error
= vn_open(ndp
, flag
, 0)) != 0) {
3823 fp_free(p
, indx
, fp
);
3827 struct fileglob
*fg
= fp
->f_fglob
;
3830 fg
->fg_ops
= &vnops
;
3831 fg
->fg_data
= ndp
->ni_vp
;
3833 vnode_put(ndp
->ni_vp
);
3836 procfdtbl_releasefd(p
, indx
, NULL
);
3837 fp_drop(p
, indx
, fp
, 1);
3847 * We are here because we were told that the MAC label will
3848 * be transitioned, and the binary is not VSUID or VSGID; to
3849 * deal with this case, we could either duplicate a lot of
3850 * code, or we can indicate we want to default the P_SUGID
3851 * bit clear and jump back up.
3853 if (mac_transition
) {
3854 leave_sugid_clear
= 1;
3855 goto handle_mac_transition
;
3859 #endif /* CONFIG_MACF */
3862 * Implement the semantic where the effective user and group become
3863 * the saved user and group in exec'ed programs.
3865 p
->p_ucred
= kauth_cred_setsvuidgid(p
->p_ucred
, kauth_cred_getuid(p
->p_ucred
), kauth_cred_getgid(p
->p_ucred
));
3866 /* update cred on proc */
3867 PROC_UPDATE_CREDS_ONPROC(p
);
3869 /* Update the process' identity version and set the security token */
3871 set_security_token(p
);
3880 * Description: Set the user stack address for the process to the provided
3881 * address. If a custom stack was not set as a result of the
3882 * load process (i.e. as specified by the image file for the
3883 * executable), then allocate the stack in the provided map and
3884 * set up appropriate guard pages for enforcing administrative
3885 * limits on stack growth, if they end up being needed.
3887 * Parameters: p Process to set stack on
3888 * load_result Information from mach-o load commands
3889 * map Address map in which to allocate the new stack
3891 * Returns: KERN_SUCCESS Stack successfully created
3892 * !KERN_SUCCESS Mach failure code
3894 static kern_return_t
3895 create_unix_stack(vm_map_t map
, load_result_t
* load_result
,
3898 mach_vm_size_t size
, prot_size
;
3899 mach_vm_offset_t addr
, prot_addr
;
3902 mach_vm_address_t user_stack
= load_result
->user_stack
;
3905 p
->user_stack
= user_stack
;
3908 if (!load_result
->prog_allocated_stack
) {
3910 * Allocate enough space for the maximum stack size we
3911 * will ever authorize and an extra page to act as
3912 * a guard page for stack overflows. For default stacks,
3913 * vm_initial_limit_stack takes care of the extra guard page.
3914 * Otherwise we must allocate it ourselves.
3917 size
= mach_vm_round_page(load_result
->user_stack_size
);
3918 if (load_result
->prog_stack_size
)
3920 addr
= mach_vm_trunc_page(load_result
->user_stack
- size
);
3921 kr
= mach_vm_allocate(map
, &addr
, size
,
3922 VM_MAKE_TAG(VM_MEMORY_STACK
) |
3924 if (kr
!= KERN_SUCCESS
) {
3925 /* If can't allocate at default location, try anywhere */
3927 kr
= mach_vm_allocate(map
, &addr
, size
,
3928 VM_MAKE_TAG(VM_MEMORY_STACK
) |
3930 if (kr
!= KERN_SUCCESS
)
3933 user_stack
= addr
+ size
;
3934 load_result
->user_stack
= user_stack
;
3937 p
->user_stack
= user_stack
;
3942 * And prevent access to what's above the current stack
3943 * size limit for this process.
3946 if (load_result
->prog_stack_size
)
3947 prot_size
= PAGE_SIZE
;
3949 prot_size
= mach_vm_trunc_page(size
- unix_stack_size(p
));
3950 kr
= mach_vm_protect(map
,
3955 if (kr
!= KERN_SUCCESS
) {
3956 (void) mach_vm_deallocate(map
, addr
, size
);
3961 return KERN_SUCCESS
;
3964 #include <sys/reboot.h>
3966 static const char * init_programs
[] = {
3967 #if DEVELOPMENT || DEBUG
3968 "/usr/local/sbin/launchd.development",
3976 * Description: Load the "init" program; in most cases, this will be "launchd"
3978 * Parameters: p Process to call execve() to create
3979 * the "init" program
3983 * Notes: The process that is passed in is the first manufactured
3984 * process on the system, and gets here via bsd_ast() firing
3985 * for the first time. This is done to ensure that bsd_init()
3986 * has run to completion.
3989 load_init_program(proc_t p
)
3991 vm_offset_t init_addr
, addr
;
3997 const char *init_program_name
;
3998 struct execve_args init_exec_args
;
4000 init_addr
= VM_MIN_ADDRESS
;
4001 (void) vm_allocate(current_map(), &init_addr
, PAGE_SIZE
, VM_FLAGS_ANYWHERE
);
4005 for (i
= 0; i
< sizeof(init_programs
)/sizeof(init_programs
[0]); i
++) {
4007 init_program_name
= init_programs
[i
];
4012 * Copy out program name.
4014 (void) copyout(init_program_name
, CAST_USER_ADDR_T(addr
), strlen(init_program_name
)+1);
4016 argv
[argc
++] = (uint32_t)addr
;
4017 addr
+= strlen(init_program_name
)+1;
4018 addr
= (vm_offset_t
)ROUND_PTR(char, addr
);
4021 * Put out first (and only) argument, similarly.
4022 * Assumes everything fits in a page as allocated above.
4024 if (boothowto
& RB_SINGLE
) {
4025 const char *init_args
= "-s";
4027 copyout(init_args
, CAST_USER_ADDR_T(addr
), strlen(init_args
)+1);
4029 argv
[argc
++] = (uint32_t)addr
;
4030 addr
+= strlen(init_args
)+1;
4031 addr
= (vm_offset_t
)ROUND_PTR(char, addr
);
4035 * Null-end the argument list
4040 * Copy out the argument list.
4042 (void) copyout(argv
, CAST_USER_ADDR_T(addr
), sizeof(argv
));
4045 * Set up argument block for fake call to execve.
4047 init_exec_args
.fname
= CAST_USER_ADDR_T(argv
[0]);
4048 init_exec_args
.argp
= CAST_USER_ADDR_T((char **)addr
);
4049 init_exec_args
.envp
= CAST_USER_ADDR_T(0);
4052 * So that init task is set with uid,gid 0 token
4054 set_security_token(p
);
4056 error
= execve(p
, &init_exec_args
, retval
);
4061 panic("Process 1 exec of %s failed, errno %d", init_program_name
, error
);
4065 * load_return_to_errno
4067 * Description: Convert a load_return_t (Mach error) to an errno (BSD error)
4069 * Parameters: lrtn Mach error number
4071 * Returns: (int) BSD error number
4073 * EBADARCH Bad architecture
4074 * EBADMACHO Bad Mach object file
4075 * ESHLIBVERS Bad shared library version
4076 * ENOMEM Out of memory/resource shortage
4077 * EACCES Access denied
4078 * ENOENT Entry not found (usually "file does
4080 * EIO An I/O error occurred
4081 * EBADEXEC The executable is corrupt/unknown
4084 load_return_to_errno(load_return_t lrtn
)
4105 case LOAD_DECRYPTFAIL
:
4111 #include <mach/mach_types.h>
4112 #include <mach/vm_prot.h>
4113 #include <mach/semaphore.h>
4114 #include <mach/sync_policy.h>
4115 #include <kern/clock.h>
4116 #include <mach/kern_return.h>
4121 * Description: Allocate the block of memory used by the execve arguments.
4122 * At the same time, we allocate a page so that we can read in
4123 * the first page of the image.
4125 * Parameters: struct image_params * the image parameter block
4127 * Returns: 0 Success
4128 * EINVAL Invalid argument
4129 * EACCES Permission denied
4130 * EINTR Interrupted function
4131 * ENOMEM Not enough space
4133 * Notes: This is a temporary allocation into the kernel address space
4134 * to enable us to copy arguments in from user space. This is
4135 * necessitated by not mapping the process calling execve() into
4136 * the kernel address space during the execve() system call.
4138 * We assemble the argument and environment, etc., into this
4139 * region before copying it as a single block into the child
4140 * process address space (at the top or bottom of the stack,
4141 * depending on which way the stack grows; see the function
4142 * exec_copyout_strings() for details).
4144 * This ends up with a second (possibly unnecessary) copy compared
4145 * with assembing the data directly into the child address space,
4146 * instead, but since we cannot be guaranteed that the parent has
4147 * not modified its environment, we can't really know that it's
4148 * really a block there as well.
4152 static int execargs_waiters
= 0;
4153 lck_mtx_t
*execargs_cache_lock
;
4156 execargs_lock_lock(void) {
4157 lck_mtx_lock_spin(execargs_cache_lock
);
4161 execargs_lock_unlock(void) {
4162 lck_mtx_unlock(execargs_cache_lock
);
4165 static wait_result_t
4166 execargs_lock_sleep(void) {
4167 return(lck_mtx_sleep(execargs_cache_lock
, LCK_SLEEP_DEFAULT
, &execargs_free_count
, THREAD_INTERRUPTIBLE
));
4170 static kern_return_t
4171 execargs_purgeable_allocate(char **execarg_address
) {
4172 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
);
4173 assert(kr
== KERN_SUCCESS
);
4177 static kern_return_t
4178 execargs_purgeable_reference(void *execarg_address
) {
4179 int state
= VM_PURGABLE_NONVOLATILE
;
4180 kern_return_t kr
= vm_purgable_control(bsd_pageable_map
, (vm_offset_t
) execarg_address
, VM_PURGABLE_SET_STATE
, &state
);
4182 assert(kr
== KERN_SUCCESS
);
4186 static kern_return_t
4187 execargs_purgeable_volatilize(void *execarg_address
) {
4188 int state
= VM_PURGABLE_VOLATILE
| VM_PURGABLE_ORDERING_OBSOLETE
;
4190 kr
= vm_purgable_control(bsd_pageable_map
, (vm_offset_t
) execarg_address
, VM_PURGABLE_SET_STATE
, &state
);
4192 assert(kr
== KERN_SUCCESS
);
4198 execargs_wakeup_waiters(void) {
4199 thread_wakeup(&execargs_free_count
);
4203 execargs_alloc(struct image_params
*imgp
)
4207 int i
, cache_index
= -1;
4209 execargs_lock_lock();
4211 while (execargs_free_count
== 0) {
4213 res
= execargs_lock_sleep();
4215 if (res
!= THREAD_AWAKENED
) {
4216 execargs_lock_unlock();
4221 execargs_free_count
--;
4223 for (i
= 0; i
< execargs_cache_size
; i
++) {
4224 vm_offset_t element
= execargs_cache
[i
];
4227 imgp
->ip_strings
= (char *)(execargs_cache
[i
]);
4228 execargs_cache
[i
] = 0;
4233 assert(execargs_free_count
>= 0);
4235 execargs_lock_unlock();
4237 if (cache_index
== -1) {
4238 kret
= execargs_purgeable_allocate(&imgp
->ip_strings
);
4241 kret
= execargs_purgeable_reference(imgp
->ip_strings
);
4243 assert(kret
== KERN_SUCCESS
);
4244 if (kret
!= KERN_SUCCESS
) {
4248 /* last page used to read in file headers */
4249 imgp
->ip_vdata
= imgp
->ip_strings
+ ( NCARGS
+ PAGE_SIZE
);
4250 imgp
->ip_strendp
= imgp
->ip_strings
;
4251 imgp
->ip_argspace
= NCARGS
;
4252 imgp
->ip_strspace
= ( NCARGS
+ PAGE_SIZE
);
4260 * Description: Free the block of memory used by the execve arguments and the
4261 * first page of the executable by a previous call to the function
4264 * Parameters: struct image_params * the image parameter block
4266 * Returns: 0 Success
4267 * EINVAL Invalid argument
4268 * EINTR Oeration interrupted
4271 execargs_free(struct image_params
*imgp
)
4275 boolean_t needs_wakeup
= FALSE
;
4277 kret
= execargs_purgeable_volatilize(imgp
->ip_strings
);
4279 execargs_lock_lock();
4280 execargs_free_count
++;
4282 for (i
= 0; i
< execargs_cache_size
; i
++) {
4283 vm_offset_t element
= execargs_cache
[i
];
4285 execargs_cache
[i
] = (vm_offset_t
) imgp
->ip_strings
;
4286 imgp
->ip_strings
= NULL
;
4291 assert(imgp
->ip_strings
== NULL
);
4293 if (execargs_waiters
> 0)
4294 needs_wakeup
= TRUE
;
4296 execargs_lock_unlock();
4298 if (needs_wakeup
== TRUE
)
4299 execargs_wakeup_waiters();
4301 return ((kret
== KERN_SUCCESS
? 0 : EINVAL
));
4305 exec_resettextvp(proc_t p
, struct image_params
*imgp
)
4309 vnode_t tvp
= p
->p_textvp
;
4313 offset
= imgp
->ip_arch_offset
;
4316 panic("exec_resettextvp: expected valid vp");
4318 ret
= vnode_ref(vp
);
4322 p
->p_textoff
= offset
;
4324 p
->p_textvp
= NULLVP
; /* this is paranoia */
4329 if ( tvp
!= NULLVP
) {
4330 if (vnode_getwithref(tvp
) == 0) {
4339 * If the process is not signed or if it contains entitlements, we
4340 * need to communicate through the task_access_port to taskgated.
4342 * taskgated will provide a detached code signature if present, and
4343 * will enforce any restrictions on entitlements.
4347 taskgated_required(proc_t p
, boolean_t
*require_success
)
4353 if ((p
->p_csflags
& CS_VALID
) == 0) {
4354 *require_success
= FALSE
;
4358 error
= cs_entitlements_blob_get(p
, &blob
, &length
);
4359 if (error
== 0 && blob
!= NULL
) {
4361 * fatal on the desktop when entitlements are present,
4362 * unless we started in single-user mode
4364 if ((boothowto
& RB_SINGLE
) == 0)
4365 *require_success
= TRUE
;
4367 * Allow initproc to run without causing taskgated to launch
4369 if (p
== initproc
) {
4370 *require_success
= FALSE
;
4377 *require_success
= FALSE
;
4382 * __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__
4384 * Description: Waits for the userspace daemon to respond to the request
4385 * we made. Function declared non inline to be visible in
4386 * stackshots and spindumps as well as debugging.
4388 __attribute__((noinline
)) int
4389 __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port
, int32_t new_pid
)
4391 return find_code_signature(task_access_port
, new_pid
);
4395 check_for_signature(proc_t p
, struct image_params
*imgp
)
4397 mach_port_t port
= NULL
;
4398 kern_return_t kr
= KERN_FAILURE
;
4400 boolean_t unexpected_failure
= FALSE
;
4401 unsigned char hash
[SHA1_RESULTLEN
];
4402 boolean_t require_success
= FALSE
;
4403 int spawn
= (imgp
->ip_flags
& IMGPF_SPAWN
);
4404 int vfexec
= (imgp
->ip_flags
& IMGPF_VFORK_EXEC
);
4407 * Override inherited code signing flags with the
4408 * ones for the process that is being successfully
4412 p
->p_csflags
= imgp
->ip_csflags
;
4415 /* Set the switch_protect flag on the map */
4416 if(p
->p_csflags
& (CS_HARD
|CS_KILL
)) {
4417 vm_map_switch_protect(get_task_map(p
->task
), TRUE
);
4421 * image activation may be failed due to policy
4422 * which is unexpected but security framework does not
4423 * approve of exec, kill and return immediately.
4425 if (imgp
->ip_mac_return
!= 0) {
4426 error
= imgp
->ip_mac_return
;
4427 unexpected_failure
= TRUE
;
4431 /* check if callout to taskgated is needed */
4432 if (!taskgated_required(p
, &require_success
)) {
4437 kr
= task_get_task_access_port(p
->task
, &port
);
4438 if (KERN_SUCCESS
!= kr
|| !IPC_PORT_VALID(port
)) {
4440 if (require_success
)
4446 * taskgated returns KERN_SUCCESS if it has completed its work
4447 * and the exec should continue, KERN_FAILURE if the exec should
4448 * fail, or it may error out with different error code in an
4449 * event of mig failure (e.g. process was signalled during the
4450 * rpc call, taskgated died, mig server died etc.).
4453 kr
= __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(port
, p
->p_pid
);
4463 unexpected_failure
= TRUE
;
4467 /* Only do this if exec_resettextvp() did not fail */
4468 if (p
->p_textvp
!= NULLVP
) {
4470 * If there's a new code directory, mark this process
4473 if (0 == ubc_cs_getcdhash(p
->p_textvp
, p
->p_textoff
, hash
)) {
4475 p
->p_csflags
|= CS_VALID
;
4482 if (!unexpected_failure
)
4483 p
->p_csflags
|= CS_KILLED
;
4484 /* make very sure execution fails */
4485 if (vfexec
|| spawn
) {
4486 psignal_vfork(p
, p
->task
, imgp
->ip_new_thread
, SIGKILL
);
4489 psignal(p
, SIGKILL
);
4496 * Typically as soon as we start executing this process, the
4497 * first instruction will trigger a VM fault to bring the text
4498 * pages (as executable) into the address space, followed soon
4499 * thereafter by dyld data structures (for dynamic executable).
4500 * To optimize this, as well as improve support for hardware
4501 * debuggers that can only access resident pages present
4502 * in the process' page tables, we prefault some pages if
4503 * possible. Errors are non-fatal.
4505 static void exec_prefault_data(proc_t p __unused
, struct image_params
*imgp
, load_result_t
*load_result
)
4508 size_t expected_all_image_infos_size
;
4511 * Prefault executable or dyld entry point.
4513 vm_fault(current_map(),
4514 vm_map_trunc_page(load_result
->entry_point
,
4515 vm_map_page_mask(current_map())),
4516 VM_PROT_READ
| VM_PROT_EXECUTE
,
4518 THREAD_UNINT
, NULL
, 0);
4520 if (imgp
->ip_flags
& IMGPF_IS_64BIT
) {
4521 expected_all_image_infos_size
= sizeof(struct user64_dyld_all_image_infos
);
4523 expected_all_image_infos_size
= sizeof(struct user32_dyld_all_image_infos
);
4526 /* Decode dyld anchor structure from <mach-o/dyld_images.h> */
4527 if (load_result
->dynlinker
&&
4528 load_result
->all_image_info_addr
&&
4529 load_result
->all_image_info_size
>= expected_all_image_infos_size
) {
4531 struct user64_dyld_all_image_infos infos64
;
4532 struct user32_dyld_all_image_infos infos32
;
4536 * Pre-fault to avoid copyin() going through the trap handler
4537 * and recovery path.
4539 vm_fault(current_map(),
4540 vm_map_trunc_page(load_result
->all_image_info_addr
,
4541 vm_map_page_mask(current_map())),
4542 VM_PROT_READ
| VM_PROT_WRITE
,
4544 THREAD_UNINT
, NULL
, 0);
4545 if ((load_result
->all_image_info_addr
& PAGE_MASK
) + expected_all_image_infos_size
> PAGE_SIZE
) {
4546 /* all_image_infos straddles a page */
4547 vm_fault(current_map(),
4548 vm_map_trunc_page(load_result
->all_image_info_addr
+ expected_all_image_infos_size
- 1,
4549 vm_map_page_mask(current_map())),
4550 VM_PROT_READ
| VM_PROT_WRITE
,
4552 THREAD_UNINT
, NULL
, 0);
4555 ret
= copyin(load_result
->all_image_info_addr
,
4557 expected_all_image_infos_size
);
4558 if (ret
== 0 && all_image_infos
.infos32
.version
>= 9) {
4560 user_addr_t notification_address
;
4561 user_addr_t dyld_image_address
;
4562 user_addr_t dyld_version_address
;
4563 user_addr_t dyld_all_image_infos_address
;
4564 user_addr_t dyld_slide_amount
;
4566 if (imgp
->ip_flags
& IMGPF_IS_64BIT
) {
4567 notification_address
= all_image_infos
.infos64
.notification
;
4568 dyld_image_address
= all_image_infos
.infos64
.dyldImageLoadAddress
;
4569 dyld_version_address
= all_image_infos
.infos64
.dyldVersion
;
4570 dyld_all_image_infos_address
= all_image_infos
.infos64
.dyldAllImageInfosAddress
;
4572 notification_address
= all_image_infos
.infos32
.notification
;
4573 dyld_image_address
= all_image_infos
.infos32
.dyldImageLoadAddress
;
4574 dyld_version_address
= all_image_infos
.infos32
.dyldVersion
;
4575 dyld_all_image_infos_address
= all_image_infos
.infos32
.dyldAllImageInfosAddress
;
4579 * dyld statically sets up the all_image_infos in its Mach-O
4580 * binary at static link time, with pointers relative to its default
4581 * load address. Since ASLR might slide dyld before its first
4582 * instruction is executed, "dyld_slide_amount" tells us how far
4583 * dyld was loaded compared to its default expected load address.
4584 * All other pointers into dyld's image should be adjusted by this
4585 * amount. At some point later, dyld will fix up pointers to take
4586 * into account the slide, at which point the all_image_infos_address
4587 * field in the structure will match the runtime load address, and
4588 * "dyld_slide_amount" will be 0, if we were to consult it again.
4591 dyld_slide_amount
= load_result
->all_image_info_addr
- dyld_all_image_infos_address
;
4594 kprintf("exec_prefault: 0x%016llx 0x%08x 0x%016llx 0x%016llx 0x%016llx 0x%016llx\n",
4595 (uint64_t)load_result
->all_image_info_addr
,
4596 all_image_infos
.infos32
.version
,
4597 (uint64_t)notification_address
,
4598 (uint64_t)dyld_image_address
,
4599 (uint64_t)dyld_version_address
,
4600 (uint64_t)dyld_all_image_infos_address
);
4603 vm_fault(current_map(),
4604 vm_map_trunc_page(notification_address
+ dyld_slide_amount
,
4605 vm_map_page_mask(current_map())),
4606 VM_PROT_READ
| VM_PROT_EXECUTE
,
4608 THREAD_UNINT
, NULL
, 0);
4609 vm_fault(current_map(),
4610 vm_map_trunc_page(dyld_image_address
+ dyld_slide_amount
,
4611 vm_map_page_mask(current_map())),
4612 VM_PROT_READ
| VM_PROT_EXECUTE
,
4614 THREAD_UNINT
, NULL
, 0);
4615 vm_fault(current_map(),
4616 vm_map_trunc_page(dyld_version_address
+ dyld_slide_amount
,
4617 vm_map_page_mask(current_map())),
4620 THREAD_UNINT
, NULL
, 0);
4621 vm_fault(current_map(),
4622 vm_map_trunc_page(dyld_all_image_infos_address
+ dyld_slide_amount
,
4623 vm_map_page_mask(current_map())),
4624 VM_PROT_READ
| VM_PROT_WRITE
,
4626 THREAD_UNINT
, NULL
, 0);