]> git.saurik.com Git - apple/xnu.git/blame - bsd/kern/kern_exec.c
xnu-3789.1.32.tar.gz
[apple/xnu.git] / bsd / kern / kern_exec.c
CommitLineData
1c79356b 1/*
39037602 2 * Copyright (c) 2000-2013 Apple Inc. All rights reserved.
5d5c5d0d 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
1c79356b 5 *
2d21ac55
A
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
8f6c56a5 14 *
2d21ac55
A
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
8f6c56a5 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b
A
27 */
28/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29/*
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.
34 */
35
1c79356b
A
36/*-
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.
44 *
45 * Redistribution and use in source and binary forms, with or without
46 * modification, are permitted provided that the following conditions
47 * are met:
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.
60 *
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
71 * SUCH DAMAGE.
72 *
73 * from: @(#)kern_exec.c 8.1 (Berkeley) 6/10/93
74 */
2d21ac55
A
75/*
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,
79 * Version 2.0.
80 */
1c79356b 81#include <machine/reg.h>
316670eb 82#include <machine/cpu_capabilities.h>
1c79356b
A
83
84#include <sys/param.h>
85#include <sys/systm.h>
86#include <sys/filedesc.h>
87#include <sys/kernel.h>
91447636
A
88#include <sys/proc_internal.h>
89#include <sys/kauth.h>
1c79356b 90#include <sys/user.h>
1c79356b
A
91#include <sys/socketvar.h>
92#include <sys/malloc.h>
93#include <sys/namei.h>
91447636
A
94#include <sys/mount_internal.h>
95#include <sys/vnode_internal.h>
96#include <sys/file_internal.h>
1c79356b 97#include <sys/stat.h>
91447636 98#include <sys/uio_internal.h>
1c79356b
A
99#include <sys/acct.h>
100#include <sys/exec.h>
101#include <sys/kdebug.h>
102#include <sys/signal.h>
55e303ae 103#include <sys/aio_kern.h>
91447636 104#include <sys/sysproto.h>
490019cf 105#include <sys/persona.h>
39037602 106#include <sys/reason.h>
2d21ac55 107#if SYSV_SHM
91447636 108#include <sys/shm_internal.h> /* shmexec() */
2d21ac55 109#endif
91447636 110#include <sys/ubc_internal.h> /* ubc_map() */
2d21ac55
A
111#include <sys/spawn.h>
112#include <sys/spawn_internal.h>
39236c6e 113#include <sys/process_policy.h>
2d21ac55 114#include <sys/codesign.h>
39037602 115#include <sys/random.h>
b0d623f7 116#include <crypto/sha1.h>
1c79356b 117
39236c6e
A
118#include <libkern/libkern.h>
119
b0d623f7 120#include <security/audit/audit.h>
e5568f75 121
2d21ac55
A
122#include <ipc/ipc_types.h>
123
91447636 124#include <mach/mach_types.h>
b0d623f7 125#include <mach/port.h>
91447636 126#include <mach/task.h>
b0d623f7 127#include <mach/task_access.h>
91447636
A
128#include <mach/thread_act.h>
129#include <mach/vm_map.h>
130#include <mach/mach_vm.h>
1c79356b
A
131#include <mach/vm_param.h>
132
b0d623f7
A
133#include <kern/sched_prim.h> /* thread_wakeup() */
134#include <kern/affinity.h>
135#include <kern/assert.h>
316670eb 136#include <kern/task.h>
fe8ab488 137#include <kern/coalition.h>
39037602 138#include <kern/policy_internal.h>
490019cf 139#include <kern/kalloc.h>
b0d623f7 140
2d21ac55
A
141#if CONFIG_MACF
142#include <security/mac.h>
143#include <security/mac_mach_internal.h>
144#endif
145
1c79356b
A
146#include <vm/vm_map.h>
147#include <vm/vm_kern.h>
2d21ac55 148#include <vm/vm_protos.h>
91447636 149#include <vm/vm_kern.h>
316670eb 150#include <vm/vm_fault.h>
39236c6e 151#include <vm/vm_pageout.h>
316670eb
A
152
153#include <kdp/kdp_dyld.h>
2d21ac55 154
6d2010ae 155#include <machine/pal_routines.h>
b0d623f7 156
316670eb
A
157#include <pexpert/pexpert.h>
158
159#if CONFIG_MEMORYSTATUS
160#include <sys/kern_memorystatus.h>
161#endif
162
2d21ac55
A
163#if CONFIG_DTRACE
164/* Do not include dtrace.h, it redefines kmem_[alloc/free] */
39037602 165extern void dtrace_proc_exec(proc_t);
fe8ab488 166extern void (*dtrace_proc_waitfor_exec_ptr)(proc_t);
2d21ac55 167
fe8ab488
A
168/*
169 * Since dtrace_proc_waitfor_exec_ptr can be added/removed in dtrace_subr.c,
170 * we will store its value before actually calling it.
171 */
172static void (*dtrace_proc_waitfor_hook)(proc_t) = NULL;
173
2d21ac55
A
174#include <sys/dtrace_ptss.h>
175#endif
176
177/* support for child creation in exec after vfork */
3e170ce0 178thread_t fork_create_child(task_t parent_task, coalition_t *parent_coalition, proc_t child_proc, int inherit_memory, int is64bit);
2d21ac55 179void vfork_exit(proc_t p, int rv);
316670eb 180extern void proc_apply_task_networkbg_internal(proc_t, thread_t);
1c79356b 181
91447636
A
182/*
183 * Mach things for which prototypes are unavailable from Mach headers
184 */
185void ipc_task_reset(
186 task_t task);
6601e61a
A
187void ipc_thread_reset(
188 thread_t thread);
2d21ac55
A
189kern_return_t ipc_object_copyin(
190 ipc_space_t space,
191 mach_port_name_t name,
192 mach_msg_type_name_t msgt_name,
193 ipc_object_t *objectp);
194void ipc_port_release_send(ipc_port_t);
91447636 195
fe8ab488
A
196#if DEVELOPMENT || DEBUG
197void task_importance_update_owner_info(task_t);
198#endif
199
91447636
A
200extern struct savearea *get_user_regs(thread_t);
201
fe8ab488 202__attribute__((noinline)) int __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port, int32_t new_pid);
91447636 203
1c79356b
A
204#include <kern/thread.h>
205#include <kern/task.h>
1c79356b
A
206#include <kern/ast.h>
207#include <kern/mach_loader.h>
b0d623f7 208#include <kern/mach_fat.h>
1c79356b
A
209#include <mach-o/fat.h>
210#include <mach-o/loader.h>
211#include <machine/vmparam.h>
91447636
A
212#include <sys/imgact.h>
213
2d21ac55
A
214#include <sys/sdt.h>
215
91447636 216
2d21ac55
A
217/*
218 * EAI_ITERLIMIT The maximum number of times to iterate an image
219 * activator in exec_activate_image() before treating
220 * it as malformed/corrupt.
221 */
c18c124e 222#define EAI_ITERLIMIT 3
1c79356b 223
6d2010ae
A
224/*
225 * For #! interpreter parsing
226 */
227#define IS_WHITESPACE(ch) ((ch == ' ') || (ch == '\t'))
228#define IS_EOL(ch) ((ch == '#') || (ch == '\n'))
229
1c79356b 230extern vm_map_t bsd_pageable_map;
39236c6e 231extern const struct fileops vnops;
1c79356b 232
3e170ce0
A
233#define USER_ADDR_ALIGN(addr, val) \
234 ( ( (user_addr_t)(addr) + (val) - 1) \
235 & ~((val) - 1) )
1c79356b 236
91447636 237struct image_params; /* Forward */
2d21ac55 238static int exec_activate_image(struct image_params *imgp);
91447636 239static int exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp);
1c79356b 240static int load_return_to_errno(load_return_t lrtn);
91447636
A
241static int execargs_alloc(struct image_params *imgp);
242static int execargs_free(struct image_params *imgp);
243static int exec_check_permissions(struct image_params *imgp);
244static int exec_extract_strings(struct image_params *imgp);
39037602 245static int exec_add_apple_strings(struct image_params *imgp, const load_result_t *load_result);
91447636 246static int exec_handle_sugid(struct image_params *imgp);
a3d08fcd 247static int sugid_scripts = 0;
6d2010ae 248SYSCTL_INT (_kern, OID_AUTO, sugid_scripts, CTLFLAG_RW | CTLFLAG_LOCKED, &sugid_scripts, 0, "");
316670eb 249static kern_return_t create_unix_stack(vm_map_t map, load_result_t* load_result, proc_t p);
91447636 250static int copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size);
2d21ac55 251static void exec_resettextvp(proc_t, struct image_params *);
b0d623f7 252static int check_for_signature(proc_t, struct image_params *);
316670eb 253static void exec_prefault_data(proc_t, struct image_params *, load_result_t *);
39037602 254static errno_t exec_handle_port_actions(struct image_params *imgp, boolean_t * portwatch_present, ipc_port_t * portwatch_ports);
3e170ce0 255static errno_t exec_handle_spawnattr_policy(proc_t p, int psa_apptype, uint64_t psa_qos_clamp, uint64_t psa_darwin_role,
fe8ab488 256 ipc_port_t * portwatch_ports, int portwatch_count);
1c79356b 257
55e303ae 258/*
6d2010ae 259 * exec_add_user_string
91447636
A
260 *
261 * Add the requested string to the string space area.
262 *
263 * Parameters; struct image_params * image parameter block
264 * user_addr_t string to add to strings area
6d2010ae
A
265 * int segment from which string comes
266 * boolean_t TRUE if string contributes to NCARGS
91447636
A
267 *
268 * Returns: 0 Success
269 * !0 Failure errno from copyinstr()
270 *
271 * Implicit returns:
272 * (imgp->ip_strendp) updated location of next add, if any
273 * (imgp->ip_strspace) updated byte count of space remaining
6d2010ae 274 * (imgp->ip_argspace) updated byte count of space in NCARGS
55e303ae 275 */
91447636 276static int
6d2010ae 277exec_add_user_string(struct image_params *imgp, user_addr_t str, int seg, boolean_t is_ncargs)
91447636 278{
6d2010ae
A
279 int error = 0;
280
281 do {
282 size_t len = 0;
283 int space;
284
285 if (is_ncargs)
286 space = imgp->ip_argspace; /* by definition smaller than ip_strspace */
287 else
288 space = imgp->ip_strspace;
289
290 if (space <= 0) {
55e303ae
A
291 error = E2BIG;
292 break;
293 }
6d2010ae
A
294
295 if (!UIO_SEG_IS_USER_SPACE(seg)) {
91447636 296 char *kstr = CAST_DOWN(char *,str); /* SAFE */
6d2010ae 297 error = copystr(kstr, imgp->ip_strendp, space, &len);
55e303ae 298 } else {
6d2010ae 299 error = copyinstr(str, imgp->ip_strendp, space, &len);
55e303ae 300 }
6d2010ae 301
91447636
A
302 imgp->ip_strendp += len;
303 imgp->ip_strspace -= len;
6d2010ae
A
304 if (is_ncargs)
305 imgp->ip_argspace -= len;
306
55e303ae 307 } while (error == ENAMETOOLONG);
6d2010ae 308
55e303ae
A
309 return error;
310}
311
3e170ce0
A
312/*
313 * dyld is now passed the executable path as a getenv-like variable
314 * in the same fashion as the stack_guard and malloc_entropy keys.
315 */
316#define EXECUTABLE_KEY "executable_path="
317
91447636
A
318/*
319 * exec_save_path
320 *
321 * To support new app package launching for Mac OS X, the dyld needs the
322 * first argument to execve() stored on the user stack.
323 *
6d2010ae 324 * Save the executable path name at the bottom of the strings area and set
91447636
A
325 * the argument vector pointer to the location following that to indicate
326 * the start of the argument and environment tuples, setting the remaining
6d2010ae 327 * string space count to the size of the string area minus the path length.
91447636
A
328 *
329 * Parameters; struct image_params * image parameter block
330 * char * path used to invoke program
2d21ac55 331 * int segment from which path comes
91447636
A
332 *
333 * Returns: int 0 Success
2d21ac55
A
334 * EFAULT Bad address
335 * copy[in]str:EFAULT Bad address
336 * copy[in]str:ENAMETOOLONG Filename too long
337 *
91447636
A
338 * Implicit returns:
339 * (imgp->ip_strings) saved path
340 * (imgp->ip_strspace) space remaining in ip_strings
91447636 341 * (imgp->ip_strendp) start of remaining copy area
6d2010ae
A
342 * (imgp->ip_argspace) space remaining of NCARGS
343 * (imgp->ip_applec) Initial applev[0]
91447636
A
344 *
345 * Note: We have to do this before the initial namei() since in the
346 * path contains symbolic links, namei() will overwrite the
347 * original path buffer contents. If the last symbolic link
348 * resolved was a relative pathname, we would lose the original
349 * "path", which could be an absolute pathname. This might be
350 * unacceptable for dyld.
351 */
352static int
3e170ce0 353exec_save_path(struct image_params *imgp, user_addr_t path, int seg, const char **excpath)
1c79356b 354{
91447636 355 int error;
3e170ce0 356 size_t len;
6d2010ae 357 char *kpath;
91447636 358
3e170ce0
A
359 // imgp->ip_strings can come out of a cache, so we need to obliterate the
360 // old path.
361 memset(imgp->ip_strings, '\0', strlen(EXECUTABLE_KEY) + MAXPATHLEN);
362
91447636
A
363 len = MIN(MAXPATHLEN, imgp->ip_strspace);
364
2d21ac55 365 switch(seg) {
91447636
A
366 case UIO_USERSPACE32:
367 case UIO_USERSPACE64: /* Same for copyin()... */
3e170ce0 368 error = copyinstr(path, imgp->ip_strings + strlen(EXECUTABLE_KEY), len, &len);
91447636 369 break;
b0d623f7 370 case UIO_SYSSPACE:
6d2010ae 371 kpath = CAST_DOWN(char *,path); /* SAFE */
3e170ce0 372 error = copystr(kpath, imgp->ip_strings + strlen(EXECUTABLE_KEY), len, &len);
91447636
A
373 break;
374 default:
375 error = EFAULT;
376 break;
377 }
378
379 if (!error) {
3e170ce0
A
380 bcopy(EXECUTABLE_KEY, imgp->ip_strings, strlen(EXECUTABLE_KEY));
381 len += strlen(EXECUTABLE_KEY);
382
91447636
A
383 imgp->ip_strendp += len;
384 imgp->ip_strspace -= len;
3e170ce0
A
385
386 if (excpath) {
387 *excpath = imgp->ip_strings + strlen(EXECUTABLE_KEY);
388 }
91447636
A
389 }
390
391 return(error);
392}
393
6d2010ae
A
394/*
395 * exec_reset_save_path
396 *
397 * If we detect a shell script, we need to reset the string area
398 * state so that the interpreter can be saved onto the stack.
399
400 * Parameters; struct image_params * image parameter block
401 *
402 * Returns: int 0 Success
403 *
404 * Implicit returns:
405 * (imgp->ip_strings) saved path
406 * (imgp->ip_strspace) space remaining in ip_strings
407 * (imgp->ip_strendp) start of remaining copy area
408 * (imgp->ip_argspace) space remaining of NCARGS
409 *
410 */
411static int
412exec_reset_save_path(struct image_params *imgp)
413{
414 imgp->ip_strendp = imgp->ip_strings;
415 imgp->ip_argspace = NCARGS;
416 imgp->ip_strspace = ( NCARGS + PAGE_SIZE );
417
418 return (0);
419}
420
91447636
A
421/*
422 * exec_shell_imgact
423 *
c18c124e
A
424 * Image activator for interpreter scripts. If the image begins with
425 * the characters "#!", then it is an interpreter script. Verify the
426 * length of the script line indicating the interpreter is not in
427 * excess of the maximum allowed size. If this is the case, then
428 * break out the arguments, if any, which are separated by white
429 * space, and copy them into the argument save area as if they were
430 * provided on the command line before all other arguments. The line
431 * ends when we encounter a comment character ('#') or newline.
91447636
A
432 *
433 * Parameters; struct image_params * image parameter block
434 *
435 * Returns: -1 not an interpreter (keep looking)
436 * -3 Success: interpreter: relookup
437 * >0 Failure: interpreter: error number
438 *
439 * A return value other than -1 indicates subsequent image activators should
440 * not be given the opportunity to attempt to activate the image.
441 */
442static int
443exec_shell_imgact(struct image_params *imgp)
444{
445 char *vdata = imgp->ip_vdata;
446 char *ihp;
6d2010ae 447 char *line_startp, *line_endp;
91447636 448 char *interp;
2d21ac55
A
449 proc_t p;
450 struct fileproc *fp;
451 int fd;
452 int error;
91447636
A
453
454 /*
455 * Make sure it's a shell script. If we've already redirected
456 * from an interpreted file once, don't do it again.
55e303ae 457 */
91447636
A
458 if (vdata[0] != '#' ||
459 vdata[1] != '!' ||
460 (imgp->ip_flags & IMGPF_INTERPRET) != 0) {
461 return (-1);
462 }
463
c18c124e
A
464 if (imgp->ip_origcputype != 0) {
465 /* Fat header previously matched, don't allow shell script inside */
466 return (-1);
467 }
468
91447636 469 imgp->ip_flags |= IMGPF_INTERPRET;
6d2010ae
A
470 imgp->ip_interp_sugid_fd = -1;
471 imgp->ip_interp_buffer[0] = '\0';
91447636 472
6d2010ae 473 /* Check to see if SUGID scripts are permitted. If they aren't then
91447636
A
474 * clear the SUGID bits.
475 * imgp->ip_vattr is known to be valid.
6d2010ae
A
476 */
477 if (sugid_scripts == 0) {
478 imgp->ip_origvattr->va_mode &= ~(VSUID | VSGID);
91447636
A
479 }
480
6d2010ae
A
481 /* Try to find the first non-whitespace character */
482 for( ihp = &vdata[2]; ihp < &vdata[IMG_SHSIZE]; ihp++ ) {
483 if (IS_EOL(*ihp)) {
484 /* Did not find interpreter, "#!\n" */
91447636 485 return (ENOEXEC);
6d2010ae
A
486 } else if (IS_WHITESPACE(*ihp)) {
487 /* Whitespace, like "#! /bin/sh\n", keep going. */
488 } else {
489 /* Found start of interpreter */
490 break;
491 }
91447636
A
492 }
493
6d2010ae
A
494 if (ihp == &vdata[IMG_SHSIZE]) {
495 /* All whitespace, like "#! " */
496 return (ENOEXEC);
497 }
91447636 498
6d2010ae
A
499 line_startp = ihp;
500
501 /* Try to find the end of the interpreter+args string */
502 for ( ; ihp < &vdata[IMG_SHSIZE]; ihp++ ) {
503 if (IS_EOL(*ihp)) {
504 /* Got it */
505 break;
506 } else {
507 /* Still part of interpreter or args */
508 }
509 }
91447636 510
6d2010ae
A
511 if (ihp == &vdata[IMG_SHSIZE]) {
512 /* A long line, like "#! blah blah blah" without end */
91447636 513 return (ENOEXEC);
6d2010ae
A
514 }
515
516 /* Backtrack until we find the last non-whitespace */
517 while (IS_EOL(*ihp) || IS_WHITESPACE(*ihp)) {
518 ihp--;
519 }
520
521 /* The character after the last non-whitespace is our logical end of line */
522 line_endp = ihp + 1;
523
524 /*
525 * Now we have pointers to the usable part of:
526 *
527 * "#! /usr/bin/int first second third \n"
528 * ^ line_startp ^ line_endp
529 */
91447636
A
530
531 /* copy the interpreter name */
6d2010ae
A
532 interp = imgp->ip_interp_buffer;
533 for ( ihp = line_startp; (ihp < line_endp) && !IS_WHITESPACE(*ihp); ihp++)
534 *interp++ = *ihp;
91447636
A
535 *interp = '\0';
536
6d2010ae
A
537 exec_reset_save_path(imgp);
538 exec_save_path(imgp, CAST_USER_ADDR_T(imgp->ip_interp_buffer),
3e170ce0 539 UIO_SYSSPACE, NULL);
91447636 540
6d2010ae
A
541 /* Copy the entire interpreter + args for later processing into argv[] */
542 interp = imgp->ip_interp_buffer;
543 for ( ihp = line_startp; (ihp < line_endp); ihp++)
544 *interp++ = *ihp;
545 *interp = '\0';
91447636 546
2d21ac55
A
547 /*
548 * If we have a SUID oder SGID script, create a file descriptor
549 * from the vnode and pass /dev/fd/%d instead of the actual
550 * path name so that the script does not get opened twice
551 */
552 if (imgp->ip_origvattr->va_mode & (VSUID | VSGID)) {
553 p = vfs_context_proc(imgp->ip_vfs_context);
554 error = falloc(p, &fp, &fd, imgp->ip_vfs_context);
555 if (error)
556 return(error);
557
558 fp->f_fglob->fg_flag = FREAD;
2d21ac55
A
559 fp->f_fglob->fg_ops = &vnops;
560 fp->f_fglob->fg_data = (caddr_t)imgp->ip_vp;
561
562 proc_fdlock(p);
563 procfdtbl_releasefd(p, fd, NULL);
564 fp_drop(p, fd, fp, 1);
565 proc_fdunlock(p);
566 vnode_ref(imgp->ip_vp);
567
6d2010ae 568 imgp->ip_interp_sugid_fd = fd;
2d21ac55
A
569 }
570
91447636
A
571 return (-3);
572}
573
574
575
576/*
577 * exec_fat_imgact
578 *
579 * Image activator for fat 1.0 binaries. If the binary is fat, then we
580 * need to select an image from it internally, and make that the image
581 * we are going to attempt to execute. At present, this consists of
582 * reloading the first page for the image with a first page from the
583 * offset location indicated by the fat header.
584 *
2d21ac55
A
585 * Parameters; struct image_params * image parameter block
586 *
587 * Returns: -1 not a fat binary (keep looking)
588 * -2 Success: encapsulated binary: reread
589 * >0 Failure: error number
590 *
91447636
A
591 * Important: This image activator is byte order neutral.
592 *
2d21ac55
A
593 * Note: A return value other than -1 indicates subsequent image
594 * activators should not be given the opportunity to attempt
595 * to activate the image.
596 *
597 * If we find an encapsulated binary, we make no assertions
91447636
A
598 * about its validity; instead, we leave that up to a rescan
599 * for an activator to claim it, and, if it is claimed by one,
600 * that activator is responsible for determining validity.
601 */
602static int
603exec_fat_imgact(struct image_params *imgp)
604{
2d21ac55 605 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
0c530ab8 606 kauth_cred_t cred = kauth_cred_proc_ref(p);
91447636 607 struct fat_header *fat_header = (struct fat_header *)imgp->ip_vdata;
2d21ac55 608 struct _posix_spawnattr *psa = NULL;
91447636
A
609 struct fat_arch fat_arch;
610 int resid, error;
611 load_return_t lret;
612
c18c124e
A
613 if (imgp->ip_origcputype != 0) {
614 /* Fat header previously matched, don't allow another fat file inside */
615 return (-1);
616 }
617
91447636 618 /* Make sure it's a fat binary */
c18c124e
A
619 if (OSSwapBigToHostInt32(fat_header->magic) != FAT_MAGIC) {
620 error = -1; /* not claimed */
91447636
A
621 goto bad;
622 }
623
c18c124e
A
624 /* imgp->ip_vdata has PAGE_SIZE, zerofilled if the file is smaller */
625 lret = fatfile_validate_fatarches((vm_offset_t)fat_header, PAGE_SIZE);
626 if (lret != LOAD_SUCCESS) {
627 error = load_return_to_errno(lret);
628 goto bad;
fe8ab488 629 }
fe8ab488 630
2d21ac55
A
631 /* If posix_spawn binprefs exist, respect those prefs. */
632 psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
633 if (psa != NULL && psa->psa_binprefs[0] != 0) {
c18c124e 634 uint32_t pr = 0;
04b8595b 635
2d21ac55
A
636 /* Check each preference listed against all arches in header */
637 for (pr = 0; pr < NBINPREFS; pr++) {
638 cpu_type_t pref = psa->psa_binprefs[pr];
639 if (pref == 0) {
640 /* No suitable arch in the pref list */
641 error = EBADARCH;
642 goto bad;
643 }
644
645 if (pref == CPU_TYPE_ANY) {
646 /* Fall through to regular grading */
c18c124e 647 goto regular_grading;
2d21ac55
A
648 }
649
c18c124e
A
650 lret = fatfile_getbestarch_for_cputype(pref,
651 (vm_offset_t)fat_header,
652 PAGE_SIZE,
653 &fat_arch);
654 if (lret == LOAD_SUCCESS) {
655 goto use_arch;
2d21ac55
A
656 }
657 }
c18c124e
A
658
659 /* Requested binary preference was not honored */
660 error = EBADEXEC;
661 goto bad;
2d21ac55
A
662 }
663
c18c124e 664regular_grading:
91447636 665 /* Look up our preferred architecture in the fat file. */
c18c124e
A
666 lret = fatfile_getbestarch((vm_offset_t)fat_header,
667 PAGE_SIZE,
668 &fat_arch);
91447636
A
669 if (lret != LOAD_SUCCESS) {
670 error = load_return_to_errno(lret);
671 goto bad;
672 }
673
2d21ac55
A
674use_arch:
675 /* Read the Mach-O header out of fat_arch */
91447636
A
676 error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata,
677 PAGE_SIZE, fat_arch.offset,
b0d623f7 678 UIO_SYSSPACE, (IO_UNIT|IO_NODELOCKED),
91447636
A
679 cred, &resid, p);
680 if (error) {
681 goto bad;
682 }
683
91447636 684 if (resid) {
c18c124e 685 memset(imgp->ip_vdata + (PAGE_SIZE - resid), 0x0, resid);
91447636
A
686 }
687
688 /* Success. Indicate we have identified an encapsulated binary */
689 error = -2;
690 imgp->ip_arch_offset = (user_size_t)fat_arch.offset;
691 imgp->ip_arch_size = (user_size_t)fat_arch.size;
c18c124e
A
692 imgp->ip_origcputype = fat_arch.cputype;
693 imgp->ip_origcpusubtype = fat_arch.cpusubtype;
91447636
A
694
695bad:
0c530ab8 696 kauth_cred_unref(&cred);
91447636
A
697 return (error);
698}
699
490019cf 700static int
39037602 701activate_exec_state(task_t task, proc_t p, thread_t thread, load_result_t *result)
490019cf
A
702{
703 int ret;
704
39037602
A
705 task_set_dyld_info(task, MACH_VM_MIN_ADDRESS, 0);
706 if (result->is64bit) {
707 task_set_64bit(task, TRUE);
708 OSBitOrAtomic(P_LP64, &p->p_flag);
709 } else {
710 task_set_64bit(task, FALSE);
711 OSBitAndAtomic(~((uint32_t)P_LP64), &p->p_flag);
712 }
713
490019cf
A
714 ret = thread_state_initialize(thread);
715 if (ret != KERN_SUCCESS) {
716 return ret;
717 }
718
490019cf
A
719 if (result->threadstate) {
720 uint32_t *ts = result->threadstate;
721 uint32_t total_size = result->threadstate_sz;
722
723 while (total_size > 0) {
724 uint32_t flavor = *ts++;
725 uint32_t size = *ts++;
726
727 ret = thread_setstatus(thread, flavor, (thread_state_t)ts, size);
728 if (ret) {
729 return ret;
730 }
731 ts += size;
732 total_size -= (size + 2) * sizeof(uint32_t);
733 }
734 }
735
736 thread_setentrypoint(thread, result->entry_point);
737
738 return KERN_SUCCESS;
739}
740
741
39037602
A
742/*
743 * Set p->p_comm and p->p_name to the name passed to exec
744 */
745static void
746set_proc_name(struct image_params *imgp, proc_t p)
747{
748 int p_name_len = sizeof(p->p_name) - 1;
749
750 if (imgp->ip_ndp->ni_cnd.cn_namelen > p_name_len) {
751 imgp->ip_ndp->ni_cnd.cn_namelen = p_name_len;
752 }
753
754 bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_name,
755 (unsigned)imgp->ip_ndp->ni_cnd.cn_namelen);
756 p->p_name[imgp->ip_ndp->ni_cnd.cn_namelen] = '\0';
757
758 if (imgp->ip_ndp->ni_cnd.cn_namelen > MAXCOMLEN) {
759 imgp->ip_ndp->ni_cnd.cn_namelen = MAXCOMLEN;
760 }
761
762 bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_comm,
763 (unsigned)imgp->ip_ndp->ni_cnd.cn_namelen);
764 p->p_comm[imgp->ip_ndp->ni_cnd.cn_namelen] = '\0';
765}
766
91447636
A
767/*
768 * exec_mach_imgact
769 *
770 * Image activator for mach-o 1.0 binaries.
771 *
2d21ac55
A
772 * Parameters; struct image_params * image parameter block
773 *
774 * Returns: -1 not a fat binary (keep looking)
775 * -2 Success: encapsulated binary: reread
776 * >0 Failure: error number
777 * EBADARCH Mach-o binary, but with an unrecognized
778 * architecture
779 * ENOMEM No memory for child process after -
780 * can only happen after vfork()
781 *
91447636 782 * Important: This image activator is NOT byte order neutral.
2d21ac55
A
783 *
784 * Note: A return value other than -1 indicates subsequent image
785 * activators should not be given the opportunity to attempt
786 * to activate the image.
787 *
788 * TODO: More gracefully handle failures after vfork
91447636
A
789 */
790static int
791exec_mach_imgact(struct image_params *imgp)
792{
793 struct mach_header *mach_header = (struct mach_header *)imgp->ip_vdata;
2d21ac55 794 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
91447636 795 int error = 0;
91447636 796 task_t task;
2d21ac55 797 task_t new_task = NULL; /* protected by vfexec */
91447636 798 thread_t thread;
1c79356b 799 struct uthread *uthread;
91447636 800 vm_map_t old_map = VM_MAP_NULL;
0b4e3aa0 801 vm_map_t map;
91447636
A
802 load_return_t lret;
803 load_result_t load_result;
2d21ac55 804 struct _posix_spawnattr *psa = NULL;
fe8ab488
A
805 int spawn = (imgp->ip_flags & IMGPF_SPAWN);
806 int vfexec = (imgp->ip_flags & IMGPF_VFORK_EXEC);
39037602 807 os_reason_t exec_failure_reason = OS_REASON_NULL;
2d21ac55 808
91447636
A
809 /*
810 * make sure it's a Mach-O 1.0 or Mach-O 2.0 binary; the difference
811 * is a reserved field on the end, so for the most part, we can
316670eb
A
812 * treat them as if they were identical. Reverse-endian Mach-O
813 * binaries are recognized but not compatible.
814 */
815 if ((mach_header->magic == MH_CIGAM) ||
816 (mach_header->magic == MH_CIGAM_64)) {
817 error = EBADARCH;
818 goto bad;
819 }
820
91447636
A
821 if ((mach_header->magic != MH_MAGIC) &&
822 (mach_header->magic != MH_MAGIC_64)) {
2d21ac55
A
823 error = -1;
824 goto bad;
825 }
826
c18c124e 827 if (mach_header->filetype != MH_EXECUTE) {
2d21ac55 828 error = -1;
91447636
A
829 goto bad;
830 }
831
c18c124e
A
832 if (imgp->ip_origcputype != 0) {
833 /* Fat header previously had an idea about this thin file */
834 if (imgp->ip_origcputype != mach_header->cputype ||
835 imgp->ip_origcpusubtype != mach_header->cpusubtype) {
836 error = EBADARCH;
837 goto bad;
838 }
839 } else {
2d21ac55
A
840 imgp->ip_origcputype = mach_header->cputype;
841 imgp->ip_origcpusubtype = mach_header->cpusubtype;
842 }
843
91447636
A
844 task = current_task();
845 thread = current_thread();
846 uthread = get_bsdthread_info(thread);
847
91447636
A
848 if ((mach_header->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64)
849 imgp->ip_flags |= IMGPF_IS_64BIT;
850
2d21ac55
A
851 /* If posix_spawn binprefs exist, respect those prefs. */
852 psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
853 if (psa != NULL && psa->psa_binprefs[0] != 0) {
854 int pr = 0;
855 for (pr = 0; pr < NBINPREFS; pr++) {
856 cpu_type_t pref = psa->psa_binprefs[pr];
857 if (pref == 0) {
858 /* No suitable arch in the pref list */
859 error = EBADARCH;
860 goto bad;
861 }
862
863 if (pref == CPU_TYPE_ANY) {
864 /* Jump to regular grading */
865 goto grade;
866 }
867
868 if (pref == imgp->ip_origcputype) {
869 /* We have a match! */
870 goto grade;
871 }
872 }
91447636
A
873 error = EBADARCH;
874 goto bad;
875 }
2d21ac55 876grade:
39236c6e 877 if (!grade_binary(imgp->ip_origcputype, imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK)) {
2d21ac55
A
878 error = EBADARCH;
879 goto bad;
91447636
A
880 }
881
2d21ac55
A
882 /* Copy in arguments/environment from the old process */
883 error = exec_extract_strings(imgp);
884 if (error)
885 goto bad;
886
6d2010ae
A
887 AUDIT_ARG(argv, imgp->ip_startargv, imgp->ip_argc,
888 imgp->ip_endargv - imgp->ip_startargv);
889 AUDIT_ARG(envv, imgp->ip_endargv, imgp->ip_envc,
890 imgp->ip_endenvv - imgp->ip_endargv);
91447636 891
b0d623f7
A
892 /*
893 * We are being called to activate an image subsequent to a vfork()
894 * operation; in this case, we know that our task, thread, and
6d2010ae 895 * uthread are actually those of our parent, and our proc, which we
b0d623f7
A
896 * obtained indirectly from the image_params vfs_context_t, is the
897 * new child process.
898 */
899 if (vfexec || spawn) {
900 if (vfexec) {
3e170ce0 901 imgp->ip_new_thread = fork_create_child(task, NULL, p, FALSE, (imgp->ip_flags & IMGPF_IS_64BIT));
b0d623f7
A
902 if (imgp->ip_new_thread == NULL) {
903 error = ENOMEM;
904 goto bad;
905 }
2d21ac55 906 }
b0d623f7 907
2d21ac55 908 /* reset local idea of thread, uthread, task */
b0d623f7 909 thread = imgp->ip_new_thread;
91447636 910 uthread = get_bsdthread_info(thread);
2d21ac55
A
911 task = new_task = get_threadtask(thread);
912 map = get_task_map(task);
91447636
A
913 } else {
914 map = VM_MAP_NULL;
915 }
916
91447636
A
917 /*
918 * Load the Mach-O file.
b0d623f7 919 *
91447636 920 * NOTE: An error after this point indicates we have potentially
6d2010ae 921 * destroyed or overwritten some process state while attempting an
91447636 922 * execve() following a vfork(), which is an unrecoverable condition.
fe8ab488
A
923 * We send the new process an immediate SIGKILL to avoid it executing
924 * any instructions in the mutated address space. For true spawns,
925 * this is not the case, and "too late" is still not too late to
926 * return an error code to the parent process.
91447636
A
927 */
928
91447636
A
929 /*
930 * Actually load the image file we previously decided to load.
931 */
490019cf 932 lret = load_machfile(imgp, mach_header, thread, &map, &load_result);
91447636
A
933 if (lret != LOAD_SUCCESS) {
934 error = load_return_to_errno(lret);
39037602
A
935
936 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
937 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO, 0, 0);
938 if (lret == LOAD_BADMACHO_UPX) {
939 /* set anything that might be useful in the crash report */
940 set_proc_name(imgp, p);
941
942 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_UPX);
943 exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
944 exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE;
945 } else {
946 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO);
947 }
948
91447636
A
949 goto badtoolate;
950 }
951
fe8ab488
A
952 proc_lock(p);
953 p->p_cputype = imgp->ip_origcputype;
954 p->p_cpusubtype = imgp->ip_origcpusubtype;
955 proc_unlock(p);
956
490019cf 957 vm_map_set_user_wire_limit(map, p->p_rlimit[RLIMIT_MEMLOCK].rlim_cur);
2d21ac55
A
958
959 /*
960 * Set code-signing flags if this binary is signed, or if parent has
961 * requested them on exec.
962 */
963 if (load_result.csflags & CS_VALID) {
39236c6e 964 imgp->ip_csflags |= load_result.csflags &
39037602
A
965 (CS_VALID|CS_SIGNED|
966 CS_HARD|CS_KILL|CS_RESTRICT|CS_ENFORCEMENT|CS_REQUIRE_LV|
967 CS_ENTITLEMENTS_VALIDATED|CS_DYLD_PLATFORM|
968 CS_ENTITLEMENT_FLAGS|
39236c6e 969 CS_EXEC_SET_HARD|CS_EXEC_SET_KILL|CS_EXEC_SET_ENFORCEMENT);
2d21ac55
A
970 } else {
971 imgp->ip_csflags &= ~CS_VALID;
972 }
973
974 if (p->p_csflags & CS_EXEC_SET_HARD)
975 imgp->ip_csflags |= CS_HARD;
976 if (p->p_csflags & CS_EXEC_SET_KILL)
977 imgp->ip_csflags |= CS_KILL;
39236c6e
A
978 if (p->p_csflags & CS_EXEC_SET_ENFORCEMENT)
979 imgp->ip_csflags |= CS_ENFORCEMENT;
fe8ab488
A
980 if (p->p_csflags & CS_EXEC_SET_INSTALLER)
981 imgp->ip_csflags |= CS_INSTALLER;
2d21ac55 982
2d21ac55
A
983 /*
984 * Set up the system reserved areas in the new address space.
985 */
39037602 986 vm_map_exec(map, task, load_result.is64bit, (void *)p->p_fd->fd_rdir, cpu_type());
490019cf 987
0c530ab8 988 /*
6d2010ae 989 * Close file descriptors which specify close-on-exec.
6601e61a 990 */
6d2010ae 991 fdexec(p, psa != NULL ? psa->psa_flags : 0);
91447636
A
992
993 /*
994 * deal with set[ug]id.
995 */
996 error = exec_handle_sugid(imgp);
fe8ab488 997 if (error) {
490019cf
A
998 if (spawn || !vfexec) {
999 vm_map_deallocate(map);
1000 }
39037602
A
1001
1002 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1003 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_SUGID_FAILURE, 0, 0);
1004 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SUGID_FAILURE);
fe8ab488 1005 goto badtoolate;
490019cf
A
1006 }
1007
1008 /*
1009 * Commit to new map.
1010 *
1011 * Swap the new map for the old, which consumes our new map reference but
1012 * each leaves us responsible for the old_map reference. That lets us get
1013 * off the pmap associated with it, and then we can release it.
1014 */
1015 if (!vfexec) {
1016 old_map = swap_task_map(task, thread, map, !spawn);
1017 vm_map_deallocate(old_map);
1018 }
1019
39037602 1020 lret = activate_exec_state(task, p, thread, &load_result);
490019cf 1021 if (lret != KERN_SUCCESS) {
39037602
A
1022
1023 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1024 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_ACTV_THREADSTATE, 0, 0);
1025 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_ACTV_THREADSTATE);
490019cf
A
1026 goto badtoolate;
1027 }
fe8ab488
A
1028
1029 /*
1030 * deal with voucher on exec-calling thread.
1031 */
1032 if (imgp->ip_new_thread == NULL)
1033 thread_set_mach_voucher(current_thread(), IPC_VOUCHER_NULL);
91447636 1034
b0d623f7
A
1035 /* Make sure we won't interrupt ourself signalling a partial process */
1036 if (!vfexec && !spawn && (p->p_lflag & P_LTRACED))
91447636
A
1037 psignal(p, SIGTRAP);
1038
91447636
A
1039 if (load_result.unixproc &&
1040 create_unix_stack(get_task_map(task),
316670eb 1041 &load_result,
2d21ac55 1042 p) != KERN_SUCCESS) {
91447636 1043 error = load_return_to_errno(LOAD_NOSPACE);
39037602
A
1044
1045 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1046 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_STACK_ALLOC, 0, 0);
1047 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_STACK_ALLOC);
1048 goto badtoolate;
1049 }
1050
1051 error = exec_add_apple_strings(imgp, &load_result);
1052 if (error) {
1053
1054 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1055 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_APPLE_STRING_INIT, 0, 0);
1056 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_APPLE_STRING_INIT);
91447636
A
1057 goto badtoolate;
1058 }
1059
b0d623f7 1060 if (vfexec || spawn) {
91447636
A
1061 old_map = vm_map_switch(get_task_map(task));
1062 }
1063
1064 if (load_result.unixproc) {
1065 user_addr_t ap;
1066
1067 /*
1068 * Copy the strings area out into the new process address
1069 * space.
1070 */
1071 ap = p->user_stack;
1072 error = exec_copyout_strings(imgp, &ap);
1073 if (error) {
b0d623f7 1074 if (vfexec || spawn)
91447636 1075 vm_map_switch(old_map);
39037602
A
1076
1077 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1078 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_STRINGS, 0, 0);
1079 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_STRINGS);
91447636
A
1080 goto badtoolate;
1081 }
1082 /* Set the stack */
1083 thread_setuserstack(thread, ap);
1084 }
490019cf 1085
91447636
A
1086 if (load_result.dynlinker) {
1087 uint64_t ap;
6d2010ae 1088 int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
91447636
A
1089
1090 /* Adjust the stack */
6d2010ae
A
1091 ap = thread_adjuserstack(thread, -new_ptr_size);
1092 error = copyoutptr(load_result.mach_header, ap, new_ptr_size);
1093
0c530ab8 1094 if (error) {
fe8ab488
A
1095 if (vfexec || spawn)
1096 vm_map_switch(old_map);
39037602
A
1097
1098 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1099 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_DYNLINKER, 0, 0);
1100 exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_DYNLINKER);
0c530ab8 1101 goto badtoolate;
91447636 1102 }
b0d623f7
A
1103 task_set_dyld_info(task, load_result.all_image_info_addr,
1104 load_result.all_image_info_size);
91447636
A
1105 }
1106
316670eb
A
1107 /* Avoid immediate VM faults back into kernel */
1108 exec_prefault_data(p, imgp, &load_result);
1109
b0d623f7 1110 if (vfexec || spawn) {
91447636
A
1111 vm_map_switch(old_map);
1112 }
91447636
A
1113
1114 /* Stop profiling */
1115 stopprofclock(p);
1116
1117 /*
1118 * Reset signal state.
1119 */
1120 execsigs(p, thread);
1121
91447636
A
1122 /*
1123 * need to cancel async IO requests that can be cancelled and wait for those
1124 * already active. MAY BLOCK!
1125 */
1126 _aio_exec( p );
1127
2d21ac55 1128#if SYSV_SHM
91447636
A
1129 /* FIXME: Till vmspace inherit is fixed: */
1130 if (!vfexec && p->vm_shm)
1131 shmexec(p);
2d21ac55
A
1132#endif
1133#if SYSV_SEM
91447636
A
1134 /* Clean up the semaphores */
1135 semexit(p);
2d21ac55 1136#endif
91447636
A
1137
1138 /*
1139 * Remember file name for accounting.
1140 */
1141 p->p_acflag &= ~AFORK;
3e170ce0 1142
39037602
A
1143 set_proc_name(imgp, p);
1144
1145#if CONFIG_SECLUDED_MEMORY
1146 if (secluded_for_apps) {
1147 if (strncmp(p->p_name,
1148 "Camera",
1149 sizeof (p->p_name)) == 0 ||
1150#if 00
1151 strncmp(p->p_name,
1152 "camerad",
1153 sizeof (p->p_name)) == 0 ||
1154#endif
1155 strncmp(p->p_name,
1156 "testCamera",
1157 sizeof (p->p_name)) == 0) {
1158 task_set_could_use_secluded_mem(p->task, TRUE);
1159 } else {
1160 task_set_could_use_secluded_mem(p->task, FALSE);
1161 }
1162 if (strncmp(p->p_name,
1163 "mediaserverd",
1164 sizeof (p->p_name)) == 0) {
1165 task_set_could_also_use_secluded_mem(p->task, TRUE);
1166 }
1167 }
1168#endif /* CONFIG_SECLUDED_MEMORY */
55e303ae 1169
6d2010ae
A
1170 pal_dbg_set_task_name( p->task );
1171
fe8ab488
A
1172#if DEVELOPMENT || DEBUG
1173 /*
1174 * Update the pid an proc name for importance base if any
1175 */
1176 task_importance_update_owner_info(p->task);
1177#endif
1178
b0d623f7
A
1179 memcpy(&p->p_uuid[0], &load_result.uuid[0], sizeof(p->p_uuid));
1180
2d21ac55 1181#if CONFIG_DTRACE
39037602 1182 dtrace_proc_exec(p);
2d21ac55
A
1183#endif
1184
0c530ab8 1185 if (kdebug_enable) {
2d21ac55
A
1186 long dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4;
1187
1188 /*
1189 * Collect the pathname for tracing
1190 */
1191 kdbg_trace_string(p, &dbg_arg1, &dbg_arg2, &dbg_arg3, &dbg_arg4);
1192
b0d623f7 1193 if (vfexec || spawn) {
04b8595b 1194 KERNEL_DEBUG_CONSTANT1(TRACE_DATA_EXEC | DBG_FUNC_NONE,
b0d623f7 1195 p->p_pid ,0,0,0, (uintptr_t)thread_tid(thread));
04b8595b 1196 KERNEL_DEBUG_CONSTANT1(TRACE_STRING_EXEC | DBG_FUNC_NONE,
b0d623f7 1197 dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4, (uintptr_t)thread_tid(thread));
2d21ac55 1198 } else {
04b8595b 1199 KERNEL_DEBUG_CONSTANT(TRACE_DATA_EXEC | DBG_FUNC_NONE,
2d21ac55 1200 p->p_pid ,0,0,0,0);
04b8595b 1201 KERNEL_DEBUG_CONSTANT(TRACE_STRING_EXEC | DBG_FUNC_NONE,
2d21ac55
A
1202 dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4, 0);
1203 }
91447636
A
1204 }
1205
2d21ac55
A
1206 /*
1207 * If posix_spawned with the START_SUSPENDED flag, stop the
1208 * process before it runs.
1209 */
1210 if (imgp->ip_px_sa != NULL) {
1211 psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
1212 if (psa->psa_flags & POSIX_SPAWN_START_SUSPENDED) {
1213 proc_lock(p);
1214 p->p_stat = SSTOP;
1215 proc_unlock(p);
3e170ce0 1216 (void) task_suspend_internal(p->task);
2d21ac55 1217 }
39236c6e 1218 }
316670eb 1219
91447636
A
1220 /*
1221 * mark as execed, wakeup the process that vforked (if any) and tell
b0d623f7 1222 * it that it now has its own resources back
91447636 1223 */
b0d623f7
A
1224 OSBitOrAtomic(P_EXEC, &p->p_flag);
1225 proc_resetregister(p);
2d21ac55
A
1226 if (p->p_pptr && (p->p_lflag & P_LPPWAIT)) {
1227 proc_lock(p);
1228 p->p_lflag &= ~P_LPPWAIT;
1229 proc_unlock(p);
91447636
A
1230 wakeup((caddr_t)p->p_pptr);
1231 }
1232
b0d623f7
A
1233 /*
1234 * Pay for our earlier safety; deliver the delayed signals from
1235 * the incomplete vfexec process now that it's complete.
1236 */
2d21ac55 1237 if (vfexec && (p->p_lflag & P_LTRACED)) {
91447636
A
1238 psignal_vfork(p, new_task, thread, SIGTRAP);
1239 }
1240
fe8ab488
A
1241 goto done;
1242
91447636 1243badtoolate:
fe8ab488
A
1244 /* Don't allow child process to execute any instructions */
1245 if (!spawn) {
1246 if (vfexec) {
39037602
A
1247 assert(exec_failure_reason != OS_REASON_NULL);
1248 psignal_vfork_with_reason(p, new_task, thread, SIGKILL, exec_failure_reason);
1249 exec_failure_reason = OS_REASON_NULL;
fe8ab488 1250 } else {
39037602
A
1251 assert(exec_failure_reason != OS_REASON_NULL);
1252 psignal_with_reason(p, SIGKILL, exec_failure_reason);
1253 exec_failure_reason = OS_REASON_NULL;
fe8ab488 1254 }
593a1d5f 1255
fe8ab488
A
1256 /* We can't stop this system call at this point, so just pretend we succeeded */
1257 error = 0;
39037602
A
1258 } else {
1259 os_reason_free(exec_failure_reason);
1260 exec_failure_reason = OS_REASON_NULL;
fe8ab488
A
1261 }
1262
1263done:
1264 if (!spawn) {
1265 /* notify only if it has not failed due to FP Key error */
1266 if ((p->p_lflag & P_LTERM_DECRYPTFAIL) == 0)
1267 proc_knote(p, NOTE_EXEC);
1268 }
1269
1270 /* Drop extra references for cases where we don't expect the caller to clean up */
1271 if (vfexec || (spawn && error == 0)) {
91447636
A
1272 task_deallocate(new_task);
1273 thread_deallocate(thread);
91447636
A
1274 }
1275
490019cf
A
1276 if (load_result.threadstate) {
1277 kfree(load_result.threadstate, load_result.threadstate_sz);
1278 load_result.threadstate = NULL;
1279 }
1280
91447636 1281bad:
39037602
A
1282 /* If we hit this, we likely would have leaked an exit reason */
1283 assert(exec_failure_reason == OS_REASON_NULL);
91447636
A
1284 return(error);
1285}
1286
1287
1288
1289
1290/*
1291 * Our image activator table; this is the table of the image types we are
1292 * capable of loading. We list them in order of preference to ensure the
1293 * fastest image load speed.
1294 *
1295 * XXX hardcoded, for now; should use linker sets
1296 */
1297struct execsw {
1298 int (*ex_imgact)(struct image_params *);
1299 const char *ex_name;
1300} execsw[] = {
1301 { exec_mach_imgact, "Mach-o Binary" },
1302 { exec_fat_imgact, "Fat Binary" },
1303 { exec_shell_imgact, "Interpreter Script" },
1304 { NULL, NULL}
1305};
1306
1307
1308/*
2d21ac55
A
1309 * exec_activate_image
1310 *
1311 * Description: Iterate through the available image activators, and activate
1312 * the image associated with the imgp structure. We start with
1313 * the
1314 *
1315 * Parameters: struct image_params * Image parameter block
1316 *
1317 * Returns: 0 Success
1318 * EBADEXEC The executable is corrupt/unknown
1319 * execargs_alloc:EINVAL Invalid argument
1320 * execargs_alloc:EACCES Permission denied
1321 * execargs_alloc:EINTR Interrupted function
1322 * execargs_alloc:ENOMEM Not enough space
1323 * exec_save_path:EFAULT Bad address
1324 * exec_save_path:ENAMETOOLONG Filename too long
1325 * exec_check_permissions:EACCES Permission denied
1326 * exec_check_permissions:ENOEXEC Executable file format error
1327 * exec_check_permissions:ETXTBSY Text file busy [misuse of error code]
1328 * exec_check_permissions:???
1329 * namei:???
1330 * vn_rdwr:??? [anything vn_rdwr can return]
1331 * <ex_imgact>:??? [anything an imgact can return]
490019cf 1332 * EDEADLK Process is being terminated
91447636 1333 */
2d21ac55
A
1334static int
1335exec_activate_image(struct image_params *imgp)
91447636 1336{
fe8ab488 1337 struct nameidata *ndp = NULL;
3e170ce0 1338 const char *excpath;
2d21ac55
A
1339 int error;
1340 int resid;
91447636 1341 int once = 1; /* save SGUID-ness for interpreted files */
2d21ac55 1342 int i;
c18c124e 1343 int itercount = 0;
593a1d5f 1344 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
1c79356b 1345
91447636 1346 error = execargs_alloc(imgp);
2d21ac55 1347 if (error)
39236c6e 1348 goto bad_notrans;
2d21ac55 1349
3e170ce0 1350 error = exec_save_path(imgp, imgp->ip_user_fname, imgp->ip_seg, &excpath);
55e303ae 1351 if (error) {
593a1d5f 1352 goto bad_notrans;
55e303ae 1353 }
91447636 1354
3e170ce0
A
1355 /* Use excpath, which contains the copyin-ed exec path */
1356 DTRACE_PROC1(exec, uintptr_t, excpath);
2d21ac55 1357
fe8ab488
A
1358 MALLOC(ndp, struct nameidata *, sizeof(*ndp), M_TEMP, M_WAITOK | M_ZERO);
1359 if (ndp == NULL) {
1360 error = ENOMEM;
1361 goto bad_notrans;
1362 }
1363
1364 NDINIT(ndp, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF | AUDITVNPATH1,
3e170ce0 1365 UIO_SYSSPACE, CAST_USER_ADDR_T(excpath), imgp->ip_vfs_context);
55e303ae 1366
91447636 1367again:
fe8ab488 1368 error = namei(ndp);
55e303ae 1369 if (error)
593a1d5f 1370 goto bad_notrans;
fe8ab488
A
1371 imgp->ip_ndp = ndp; /* successful namei(); call nameidone() later */
1372 imgp->ip_vp = ndp->ni_vp; /* if set, need to vnode_put() at some point */
1c79356b 1373
6d2010ae
A
1374 /*
1375 * Before we start the transition from binary A to binary B, make
1376 * sure another thread hasn't started exiting the process. We grab
1377 * the proc lock to check p_lflag initially, and the transition
1378 * mechanism ensures that the value doesn't change after we release
1379 * the lock.
1380 */
1381 proc_lock(p);
1382 if (p->p_lflag & P_LEXIT) {
490019cf 1383 error = EDEADLK;
6d2010ae
A
1384 proc_unlock(p);
1385 goto bad_notrans;
1386 }
fe8ab488 1387 error = proc_transstart(p, 1, 0);
6d2010ae 1388 proc_unlock(p);
b0d623f7
A
1389 if (error)
1390 goto bad_notrans;
593a1d5f 1391
91447636
A
1392 error = exec_check_permissions(imgp);
1393 if (error)
1c79356b 1394 goto bad;
1c79356b 1395
91447636
A
1396 /* Copy; avoid invocation of an interpreter overwriting the original */
1397 if (once) {
1398 once = 0;
2d21ac55 1399 *imgp->ip_origvattr = *imgp->ip_vattr;
91447636 1400 }
1c79356b 1401
91447636 1402 error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata, PAGE_SIZE, 0,
b0d623f7 1403 UIO_SYSSPACE, IO_NODELOCKED,
2d21ac55
A
1404 vfs_context_ucred(imgp->ip_vfs_context),
1405 &resid, vfs_context_proc(imgp->ip_vfs_context));
1c79356b
A
1406 if (error)
1407 goto bad;
c18c124e
A
1408
1409 if (resid) {
1410 memset(imgp->ip_vdata + (PAGE_SIZE - resid), 0x0, resid);
1411 }
1412
91447636 1413encapsulated_binary:
2d21ac55 1414 /* Limit the number of iterations we will attempt on each binary */
c18c124e 1415 if (++itercount > EAI_ITERLIMIT) {
2d21ac55
A
1416 error = EBADEXEC;
1417 goto bad;
1418 }
91447636
A
1419 error = -1;
1420 for(i = 0; error == -1 && execsw[i].ex_imgact != NULL; i++) {
1c79356b 1421
91447636 1422 error = (*execsw[i].ex_imgact)(imgp);
1c79356b 1423
91447636
A
1424 switch (error) {
1425 /* case -1: not claimed: continue */
c18c124e 1426 case -2: /* Encapsulated binary, imgp->ip_XXX set for next iteration */
91447636 1427 goto encapsulated_binary;
1c79356b 1428
91447636 1429 case -3: /* Interpreter */
2d21ac55
A
1430#if CONFIG_MACF
1431 /*
1432 * Copy the script label for later use. Note that
1433 * the label can be different when the script is
1434 * actually read by the interpreter.
1435 */
1436 if (imgp->ip_scriptlabelp)
1437 mac_vnode_label_free(imgp->ip_scriptlabelp);
1438 imgp->ip_scriptlabelp = mac_vnode_label_alloc();
1439 if (imgp->ip_scriptlabelp == NULL) {
1440 error = ENOMEM;
1441 break;
1442 }
1443 mac_vnode_label_copy(imgp->ip_vp->v_label,
b0d623f7 1444 imgp->ip_scriptlabelp);
39236c6e
A
1445
1446 /*
1447 * Take a ref of the script vnode for later use.
1448 */
1449 if (imgp->ip_scriptvp)
1450 vnode_put(imgp->ip_scriptvp);
1451 if (vnode_getwithref(imgp->ip_vp) == 0)
1452 imgp->ip_scriptvp = imgp->ip_vp;
2d21ac55 1453#endif
6d2010ae 1454
fe8ab488 1455 nameidone(ndp);
6d2010ae 1456
91447636
A
1457 vnode_put(imgp->ip_vp);
1458 imgp->ip_vp = NULL; /* already put */
6d2010ae
A
1459 imgp->ip_ndp = NULL; /* already nameidone */
1460
3e170ce0 1461 /* Use excpath, which exec_shell_imgact reset to the interpreter */
fe8ab488 1462 NDINIT(ndp, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF,
3e170ce0 1463 UIO_SYSSPACE, CAST_USER_ADDR_T(excpath), imgp->ip_vfs_context);
1c79356b 1464
593a1d5f 1465 proc_transend(p, 0);
91447636
A
1466 goto again;
1467
1468 default:
1469 break;
1470 }
1471 }
2d21ac55
A
1472
1473 /*
1474 * Call out to allow 3rd party notification of exec.
91447636
A
1475 * Ignore result of kauth_authorize_fileop call.
1476 */
1477 if (error == 0 && kauth_authorize_fileop_has_listeners()) {
2d21ac55
A
1478 kauth_authorize_fileop(vfs_context_ucred(imgp->ip_vfs_context),
1479 KAUTH_FILEOP_EXEC,
fe8ab488 1480 (uintptr_t)ndp->ni_vp, 0);
91447636 1481 }
91447636 1482
490019cf
A
1483 if (error == 0) {
1484 /*
1485 * Reset atm context from task
1486 */
1487 task_atm_reset(p->task);
1488
1489 /*
1490 * Reset old bank context from task
1491 */
1492 task_bank_reset(p->task);
1493 }
91447636 1494bad:
593a1d5f
A
1495 proc_transend(p, 0);
1496
1497bad_notrans:
91447636
A
1498 if (imgp->ip_strings)
1499 execargs_free(imgp);
2d21ac55
A
1500 if (imgp->ip_ndp)
1501 nameidone(imgp->ip_ndp);
fe8ab488
A
1502 if (ndp)
1503 FREE(ndp, M_TEMP);
91447636 1504
2d21ac55
A
1505 return (error);
1506}
91447636 1507
39236c6e
A
1508
1509/*
fe8ab488 1510 * exec_handle_spawnattr_policy
39236c6e 1511 *
fe8ab488 1512 * Description: Decode and apply the posix_spawn apptype, qos clamp, and watchport ports to the task.
39236c6e
A
1513 *
1514 * Parameters: proc_t p process to apply attributes to
1515 * int psa_apptype posix spawn attribute apptype
1516 *
1517 * Returns: 0 Success
1518 */
1519static errno_t
3e170ce0 1520exec_handle_spawnattr_policy(proc_t p, int psa_apptype, uint64_t psa_qos_clamp, uint64_t psa_darwin_role,
fe8ab488 1521 ipc_port_t * portwatch_ports, int portwatch_count)
39236c6e 1522{
fe8ab488
A
1523 int apptype = TASK_APPTYPE_NONE;
1524 int qos_clamp = THREAD_QOS_UNSPECIFIED;
3e170ce0 1525 int role = TASK_UNSPECIFIED;
fe8ab488 1526
39236c6e 1527 if ((psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK) != 0) {
39236c6e
A
1528 int proctype = psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK;
1529
1530 switch(proctype) {
1531 case POSIX_SPAWN_PROC_TYPE_DAEMON_INTERACTIVE:
1532 apptype = TASK_APPTYPE_DAEMON_INTERACTIVE;
1533 break;
1534 case POSIX_SPAWN_PROC_TYPE_DAEMON_STANDARD:
1535 apptype = TASK_APPTYPE_DAEMON_STANDARD;
1536 break;
1537 case POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE:
1538 apptype = TASK_APPTYPE_DAEMON_ADAPTIVE;
1539 break;
1540 case POSIX_SPAWN_PROC_TYPE_DAEMON_BACKGROUND:
1541 apptype = TASK_APPTYPE_DAEMON_BACKGROUND;
1542 break;
1543 case POSIX_SPAWN_PROC_TYPE_APP_DEFAULT:
1544 apptype = TASK_APPTYPE_APP_DEFAULT;
1545 break;
1546 case POSIX_SPAWN_PROC_TYPE_APP_TAL:
1547 apptype = TASK_APPTYPE_APP_TAL;
1548 break;
1549 default:
1550 apptype = TASK_APPTYPE_NONE;
fe8ab488 1551 /* TODO: Should an invalid value here fail the spawn? */
39236c6e
A
1552 break;
1553 }
fe8ab488 1554 }
39236c6e 1555
fe8ab488
A
1556 if (psa_qos_clamp != POSIX_SPAWN_PROC_CLAMP_NONE) {
1557 switch (psa_qos_clamp) {
1558 case POSIX_SPAWN_PROC_CLAMP_UTILITY:
1559 qos_clamp = THREAD_QOS_UTILITY;
1560 break;
1561 case POSIX_SPAWN_PROC_CLAMP_BACKGROUND:
1562 qos_clamp = THREAD_QOS_BACKGROUND;
1563 break;
1564 case POSIX_SPAWN_PROC_CLAMP_MAINTENANCE:
1565 qos_clamp = THREAD_QOS_MAINTENANCE;
1566 break;
1567 default:
1568 qos_clamp = THREAD_QOS_UNSPECIFIED;
1569 /* TODO: Should an invalid value here fail the spawn? */
1570 break;
1571 }
1572 }
39236c6e 1573
3e170ce0
A
1574 if (psa_darwin_role != PRIO_DARWIN_ROLE_DEFAULT) {
1575 proc_darwin_role_to_task_role(psa_darwin_role, &role);
1576 }
1577
1578 if (apptype != TASK_APPTYPE_NONE ||
1579 qos_clamp != THREAD_QOS_UNSPECIFIED ||
1580 role != TASK_UNSPECIFIED) {
1581 proc_set_task_spawnpolicy(p->task, apptype, qos_clamp, role,
fe8ab488 1582 portwatch_ports, portwatch_count);
39236c6e
A
1583 }
1584
1585 return (0);
1586}
1587
1588
2d21ac55
A
1589/*
1590 * exec_handle_port_actions
1591 *
1592 * Description: Go through the _posix_port_actions_t contents,
b0d623f7
A
1593 * calling task_set_special_port, task_set_exception_ports
1594 * and/or audit_session_spawnjoin for the current task.
2d21ac55
A
1595 *
1596 * Parameters: struct image_params * Image parameter block
1597 *
1598 * Returns: 0 Success
6d2010ae 1599 * EINVAL Failure
b0d623f7 1600 * ENOTSUP Illegal posix_spawn attr flag was set
2d21ac55 1601 */
6d2010ae 1602static errno_t
39037602
A
1603exec_handle_port_actions(struct image_params *imgp, boolean_t * portwatch_present,
1604 ipc_port_t * portwatch_ports)
91447636 1605{
2d21ac55
A
1606 _posix_spawn_port_actions_t pacts = imgp->ip_px_spa;
1607 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
1608 _ps_port_action_t *act = NULL;
1609 task_t task = p->task;
1610 ipc_port_t port = NULL;
316670eb 1611 errno_t ret = 0;
2d21ac55 1612 int i;
39037602 1613 kern_return_t kr;
91447636 1614
fe8ab488 1615 *portwatch_present = FALSE;
39236c6e 1616
2d21ac55
A
1617 for (i = 0; i < pacts->pspa_count; i++) {
1618 act = &pacts->pspa_actions[i];
91447636 1619
39037602
A
1620 if (MACH_PORT_VALID(act->new_port)) {
1621 kr = ipc_object_copyin(get_task_ipcspace(current_task()),
1622 act->new_port, MACH_MSG_TYPE_COPY_SEND,
1623 (ipc_object_t *) &port);
1624
1625 if (kr != KERN_SUCCESS) {
1626 ret = EINVAL;
1627 goto done;
1628 }
1629 } else {
1630 /* it's NULL or DEAD */
1631 port = CAST_MACH_NAME_TO_PORT(act->new_port);
39236c6e 1632 }
1c79356b 1633
2d21ac55 1634 switch (act->port_type) {
316670eb 1635 case PSPA_SPECIAL:
39037602
A
1636 kr = task_set_special_port(task, act->which, port);
1637
1638 if (kr != KERN_SUCCESS)
316670eb
A
1639 ret = EINVAL;
1640 break;
1641
1642 case PSPA_EXCEPTION:
39037602
A
1643 kr = task_set_exception_ports(task, act->mask, port,
1644 act->behavior, act->flavor);
1645 if (kr != KERN_SUCCESS)
316670eb
A
1646 ret = EINVAL;
1647 break;
b0d623f7 1648#if CONFIG_AUDIT
316670eb
A
1649 case PSPA_AU_SESSION:
1650 ret = audit_session_spawnjoin(p, port);
1651 break;
b0d623f7 1652#endif
39236c6e 1653 case PSPA_IMP_WATCHPORTS:
39037602 1654 if (portwatch_ports != NULL && IPC_PORT_VALID(port)) {
fe8ab488 1655 *portwatch_present = TRUE;
39236c6e
A
1656 /* hold on to this till end of spawn */
1657 portwatch_ports[i] = port;
39037602 1658 } else {
39236c6e 1659 ipc_port_release_send(port);
39037602
A
1660 }
1661
39236c6e 1662 break;
316670eb
A
1663 default:
1664 ret = EINVAL;
1665 break;
2d21ac55 1666 }
316670eb 1667
39037602
A
1668 if (ret) {
1669 /* action failed, so release port resources */
2d21ac55 1670 ipc_port_release_send(port);
316670eb 1671 break;
2d21ac55
A
1672 }
1673 }
1674
39236c6e
A
1675done:
1676 if (0 != ret)
1677 DTRACE_PROC1(spawn__port__failure, mach_port_name_t, act->new_port);
316670eb 1678 return (ret);
2d21ac55
A
1679}
1680
1681/*
1682 * exec_handle_file_actions
1683 *
1684 * Description: Go through the _posix_file_actions_t contents applying the
1685 * open, close, and dup2 operations to the open file table for
1686 * the current process.
1687 *
1688 * Parameters: struct image_params * Image parameter block
1689 *
1690 * Returns: 0 Success
1691 * ???
1692 *
1693 * Note: Actions are applied in the order specified, with the credential
1694 * of the parent process. This is done to permit the parent
1695 * process to utilize POSIX_SPAWN_RESETIDS to drop privilege in
1696 * the child following operations the child may in fact not be
1697 * normally permitted to perform.
1698 */
1699static int
6d2010ae 1700exec_handle_file_actions(struct image_params *imgp, short psa_flags)
2d21ac55
A
1701{
1702 int error = 0;
1703 int action;
1704 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
1705 _posix_spawn_file_actions_t px_sfap = imgp->ip_px_sfa;
b0d623f7 1706 int ival[2]; /* dummy retval for system calls) */
2d21ac55
A
1707
1708 for (action = 0; action < px_sfap->psfa_act_count; action++) {
1709 _psfa_action_t *psfa = &px_sfap->psfa_act_acts[ action];
1710
1711 switch(psfa->psfaa_type) {
1712 case PSFA_OPEN: {
1713 /*
1714 * Open is different, in that it requires the use of
1715 * a path argument, which is normally copied in from
1716 * user space; because of this, we have to support an
1717 * open from kernel space that passes an address space
6d2010ae 1718 * context of UIO_SYSSPACE, and casts the address
2d21ac55
A
1719 * argument to a user_addr_t.
1720 */
fe8ab488
A
1721 char *bufp = NULL;
1722 struct vnode_attr *vap;
1723 struct nameidata *ndp;
2d21ac55
A
1724 int mode = psfa->psfaa_openargs.psfao_mode;
1725 struct dup2_args dup2a;
1726 struct close_nocancel_args ca;
1727 int origfd;
1728
fe8ab488
A
1729 MALLOC(bufp, char *, sizeof(*vap) + sizeof(*ndp), M_TEMP, M_WAITOK | M_ZERO);
1730 if (bufp == NULL) {
1731 error = ENOMEM;
1732 break;
1733 }
1734
1735 vap = (struct vnode_attr *) bufp;
1736 ndp = (struct nameidata *) (bufp + sizeof(*vap));
1737
1738 VATTR_INIT(vap);
2d21ac55
A
1739 /* Mask off all but regular access permissions */
1740 mode = ((mode &~ p->p_fd->fd_cmask) & ALLPERMS) & ~S_ISTXT;
fe8ab488 1741 VATTR_SET(vap, va_mode, mode & ACCESSPERMS);
2d21ac55 1742
fe8ab488 1743 NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW | AUDITVNPATH1, UIO_SYSSPACE,
2d21ac55
A
1744 CAST_USER_ADDR_T(psfa->psfaa_openargs.psfao_path),
1745 imgp->ip_vfs_context);
1746
1747 error = open1(imgp->ip_vfs_context,
fe8ab488 1748 ndp,
2d21ac55 1749 psfa->psfaa_openargs.psfao_oflag,
fe8ab488 1750 vap,
39236c6e 1751 fileproc_alloc_init, NULL,
2d21ac55
A
1752 ival);
1753
fe8ab488
A
1754 FREE(bufp, M_TEMP);
1755
2d21ac55
A
1756 /*
1757 * If there's an error, or we get the right fd by
6d2010ae
A
1758 * accident, then drop out here. This is easier than
1759 * reworking all the open code to preallocate fd
2d21ac55
A
1760 * slots, and internally taking one as an argument.
1761 */
1762 if (error || ival[0] == psfa->psfaa_filedes)
1763 break;
1764
1765 origfd = ival[0];
1766 /*
1767 * If we didn't fall out from an error, we ended up
1768 * with the wrong fd; so now we've got to try to dup2
1769 * it to the right one.
1770 */
1771 dup2a.from = origfd;
1772 dup2a.to = psfa->psfaa_filedes;
1773
1774 /*
1775 * The dup2() system call implementation sets
1776 * ival to newfd in the success case, but we
1777 * can ignore that, since if we didn't get the
1778 * fd we wanted, the error will stop us.
1779 */
1780 error = dup2(p, &dup2a, ival);
1781 if (error)
1782 break;
1783
1784 /*
1785 * Finally, close the original fd.
1786 */
1787 ca.fd = origfd;
1788
1789 error = close_nocancel(p, &ca, ival);
1790 }
1791 break;
1792
1793 case PSFA_DUP2: {
1794 struct dup2_args dup2a;
1795
1796 dup2a.from = psfa->psfaa_filedes;
1797 dup2a.to = psfa->psfaa_openargs.psfao_oflag;
1798
1799 /*
1800 * The dup2() system call implementation sets
1801 * ival to newfd in the success case, but we
1802 * can ignore that, since if we didn't get the
1803 * fd we wanted, the error will stop us.
1804 */
1805 error = dup2(p, &dup2a, ival);
1806 }
1807 break;
1808
1809 case PSFA_CLOSE: {
1810 struct close_nocancel_args ca;
1811
1812 ca.fd = psfa->psfaa_filedes;
1813
1814 error = close_nocancel(p, &ca, ival);
1815 }
1816 break;
1817
6d2010ae 1818 case PSFA_INHERIT: {
39236c6e 1819 struct fcntl_nocancel_args fcntla;
6d2010ae
A
1820
1821 /*
1822 * Check to see if the descriptor exists, and
1823 * ensure it's -not- marked as close-on-exec.
39236c6e
A
1824 *
1825 * Attempting to "inherit" a guarded fd will
1826 * result in a error.
6d2010ae 1827 */
39236c6e
A
1828 fcntla.fd = psfa->psfaa_filedes;
1829 fcntla.cmd = F_GETFD;
1830 if ((error = fcntl_nocancel(p, &fcntla, ival)) != 0)
1831 break;
1832
1833 if ((ival[0] & FD_CLOEXEC) == FD_CLOEXEC) {
1834 fcntla.fd = psfa->psfaa_filedes;
1835 fcntla.cmd = F_SETFD;
1836 fcntla.arg = ival[0] & ~FD_CLOEXEC;
1837 error = fcntl_nocancel(p, &fcntla, ival);
6d2010ae 1838 }
39236c6e 1839
6d2010ae
A
1840 }
1841 break;
1842
2d21ac55
A
1843 default:
1844 error = EINVAL;
1845 break;
1846 }
6d2010ae 1847
2d21ac55 1848 /* All file actions failures are considered fatal, per POSIX */
6d2010ae 1849
39236c6e
A
1850 if (error) {
1851 if (PSFA_OPEN == psfa->psfaa_type) {
1852 DTRACE_PROC1(spawn__open__failure, uintptr_t,
1853 psfa->psfaa_openargs.psfao_path);
1854 } else {
1855 DTRACE_PROC1(spawn__fd__failure, int, psfa->psfaa_filedes);
1856 }
2d21ac55 1857 break;
39236c6e 1858 }
2d21ac55
A
1859 }
1860
6d2010ae
A
1861 if (error != 0 || (psa_flags & POSIX_SPAWN_CLOEXEC_DEFAULT) == 0)
1862 return (error);
1863
1864 /*
1865 * If POSIX_SPAWN_CLOEXEC_DEFAULT is set, behave (during
1866 * this spawn only) as if "close on exec" is the default
1867 * disposition of all pre-existing file descriptors. In this case,
1868 * the list of file descriptors mentioned in the file actions
1869 * are the only ones that can be inherited, so mark them now.
1870 *
1871 * The actual closing part comes later, in fdexec().
1872 */
1873 proc_fdlock(p);
1874 for (action = 0; action < px_sfap->psfa_act_count; action++) {
1875 _psfa_action_t *psfa = &px_sfap->psfa_act_acts[action];
1876 int fd = psfa->psfaa_filedes;
1877
1878 switch (psfa->psfaa_type) {
1879 case PSFA_DUP2:
1880 fd = psfa->psfaa_openargs.psfao_oflag;
1881 /*FALLTHROUGH*/
1882 case PSFA_OPEN:
1883 case PSFA_INHERIT:
1884 *fdflags(p, fd) |= UF_INHERIT;
1885 break;
1886
1887 case PSFA_CLOSE:
1888 break;
1889 }
1890 }
1891 proc_fdunlock(p);
1892
1893 return (0);
2d21ac55
A
1894}
1895
39236c6e
A
1896#if CONFIG_MACF
1897/*
1898 * exec_spawnattr_getmacpolicyinfo
1899 */
1900void *
1901exec_spawnattr_getmacpolicyinfo(const void *macextensions, const char *policyname, size_t *lenp)
1902{
1903 const struct _posix_spawn_mac_policy_extensions *psmx = macextensions;
1904 int i;
1905
1906 if (psmx == NULL)
1907 return NULL;
1908
1909 for (i = 0; i < psmx->psmx_count; i++) {
1910 const _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i];
1911 if (strncmp(extension->policyname, policyname, sizeof(extension->policyname)) == 0) {
1912 if (lenp != NULL)
1913 *lenp = extension->datalen;
1914 return extension->datap;
1915 }
1916 }
1917
1918 if (lenp != NULL)
1919 *lenp = 0;
1920 return NULL;
1921}
1922
1923static int
1924spawn_copyin_macpolicyinfo(const struct user__posix_spawn_args_desc *px_args, _posix_spawn_mac_policy_extensions_t *psmxp)
1925{
1926 _posix_spawn_mac_policy_extensions_t psmx = NULL;
1927 int error = 0;
1928 int copycnt = 0;
1929 int i = 0;
1930
1931 *psmxp = NULL;
1932
1933 if (px_args->mac_extensions_size < PS_MAC_EXTENSIONS_SIZE(1) ||
1934 px_args->mac_extensions_size > PAGE_SIZE) {
1935 error = EINVAL;
1936 goto bad;
1937 }
1938
1939 MALLOC(psmx, _posix_spawn_mac_policy_extensions_t, px_args->mac_extensions_size, M_TEMP, M_WAITOK);
1940 if ((error = copyin(px_args->mac_extensions, psmx, px_args->mac_extensions_size)) != 0)
1941 goto bad;
1942
1943 if (PS_MAC_EXTENSIONS_SIZE(psmx->psmx_count) > px_args->mac_extensions_size) {
1944 error = EINVAL;
1945 goto bad;
1946 }
1947
1948 for (i = 0; i < psmx->psmx_count; i++) {
1949 _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i];
1950 if (extension->datalen == 0 || extension->datalen > PAGE_SIZE) {
1951 error = EINVAL;
1952 goto bad;
1953 }
1954 }
1955
1956 for (copycnt = 0; copycnt < psmx->psmx_count; copycnt++) {
1957 _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[copycnt];
1958 void *data = NULL;
1959
1960 MALLOC(data, void *, extension->datalen, M_TEMP, M_WAITOK);
1961 if ((error = copyin(extension->data, data, extension->datalen)) != 0) {
1962 FREE(data, M_TEMP);
1963 goto bad;
1964 }
1965 extension->datap = data;
1966 }
1967
1968 *psmxp = psmx;
1969 return 0;
1970
1971bad:
1972 if (psmx != NULL) {
1973 for (i = 0; i < copycnt; i++)
1974 FREE(psmx->psmx_extensions[i].datap, M_TEMP);
1975 FREE(psmx, M_TEMP);
1976 }
1977 return error;
1978}
1979
1980static void
1981spawn_free_macpolicyinfo(_posix_spawn_mac_policy_extensions_t psmx)
1982{
1983 int i;
1984
1985 if (psmx == NULL)
1986 return;
1987 for (i = 0; i < psmx->psmx_count; i++)
1988 FREE(psmx->psmx_extensions[i].datap, M_TEMP);
1989 FREE(psmx, M_TEMP);
1990}
1991#endif /* CONFIG_MACF */
2d21ac55 1992
3e170ce0
A
1993#if CONFIG_COALITIONS
1994static inline void spawn_coalitions_release_all(coalition_t coal[COALITION_NUM_TYPES])
1995{
1996 for (int c = 0; c < COALITION_NUM_TYPES; c++) {
1997 if (coal[c]) {
1998 coalition_remove_active(coal[c]);
1999 coalition_release(coal[c]);
2000 }
2001 }
2002}
2003#endif
2004
490019cf
A
2005#if CONFIG_PERSONAS
2006static int spawn_validate_persona(struct _posix_spawn_persona_info *px_persona)
2007{
2008 int error = 0;
2009 struct persona *persona = NULL;
2010 int verify = px_persona->pspi_flags & POSIX_SPAWN_PERSONA_FLAGS_VERIFY;
2011
2012 /*
2013 * TODO: rdar://problem/19981151
2014 * Add entitlement check!
2015 */
2016 if (!kauth_cred_issuser(kauth_cred_get()))
2017 return EPERM;
2018
2019 persona = persona_lookup(px_persona->pspi_id);
2020 if (!persona) {
2021 error = ESRCH;
2022 goto out;
2023 }
2024
2025 if (verify) {
2026 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_UID) {
2027 if (px_persona->pspi_uid != persona_get_uid(persona)) {
2028 error = EINVAL;
2029 goto out;
2030 }
2031 }
2032 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GID) {
2033 if (px_persona->pspi_gid != persona_get_gid(persona)) {
2034 error = EINVAL;
2035 goto out;
2036 }
2037 }
2038 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GROUPS) {
2039 int ngroups = 0;
2040 gid_t groups[NGROUPS_MAX];
2041
2042 if (persona_get_groups(persona, &ngroups, groups,
2043 px_persona->pspi_ngroups) != 0) {
2044 error = EINVAL;
2045 goto out;
2046 }
2047 if (ngroups != (int)px_persona->pspi_ngroups) {
2048 error = EINVAL;
2049 goto out;
2050 }
2051 while (ngroups--) {
2052 if (px_persona->pspi_groups[ngroups] != groups[ngroups]) {
2053 error = EINVAL;
2054 goto out;
2055 }
2056 }
2057 if (px_persona->pspi_gmuid != persona_get_gmuid(persona)) {
2058 error = EINVAL;
2059 goto out;
2060 }
2061 }
2062 }
2063
2064out:
2065 if (persona)
2066 persona_put(persona);
2067
2068 return error;
2069}
2070
2071static int spawn_persona_adopt(proc_t p, struct _posix_spawn_persona_info *px_persona)
2072{
2073 int ret;
2074 kauth_cred_t cred;
2075 struct persona *persona = NULL;
2076 int override = !!(px_persona->pspi_flags & POSIX_SPAWN_PERSONA_FLAGS_OVERRIDE);
2077
2078 if (!override)
2079 return persona_proc_adopt_id(p, px_persona->pspi_id, NULL);
2080
2081 /*
2082 * we want to spawn into the given persona, but we want to override
2083 * the kauth with a different UID/GID combo
2084 */
2085 persona = persona_lookup(px_persona->pspi_id);
2086 if (!persona)
2087 return ESRCH;
2088
2089 cred = persona_get_cred(persona);
2090 if (!cred) {
2091 ret = EINVAL;
2092 goto out;
2093 }
2094
2095 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_UID) {
2096 cred = kauth_cred_setresuid(cred,
2097 px_persona->pspi_uid,
2098 px_persona->pspi_uid,
2099 px_persona->pspi_uid,
2100 KAUTH_UID_NONE);
2101 }
2102
2103 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GID) {
2104 cred = kauth_cred_setresgid(cred,
2105 px_persona->pspi_gid,
2106 px_persona->pspi_gid,
2107 px_persona->pspi_gid);
2108 }
2109
2110 if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GROUPS) {
2111 cred = kauth_cred_setgroups(cred,
2112 px_persona->pspi_groups,
2113 px_persona->pspi_ngroups,
2114 px_persona->pspi_gmuid);
2115 }
2116
2117 ret = persona_proc_adopt(p, persona, cred);
2118
2119out:
2120 persona_put(persona);
2121 return ret;
2122}
2123#endif
2124
3e170ce0
A
2125void
2126proc_set_return_wait(proc_t p)
2127{
2128 proc_lock(p);
2129 p->p_lflag |= P_LRETURNWAIT;
2130 proc_unlock(p);
2131}
2132
2133void
2134proc_clear_return_wait(proc_t p, thread_t child_thread)
2135{
2136 proc_lock(p);
2137
2138 p->p_lflag &= ~P_LRETURNWAIT;
2139 if (p->p_lflag & P_LRETURNWAITER) {
2140 wakeup(&p->p_lflag);
2141 }
2142
2143 proc_unlock(p);
2144
2145 (void)thread_resume(child_thread);
2146}
2147
2148void
2149proc_wait_to_return()
2150{
2151 proc_t p;
2152
2153 p = current_proc();
2154 proc_lock(p);
2155
2156 if (p->p_lflag & P_LRETURNWAIT) {
2157 p->p_lflag |= P_LRETURNWAITER;
2158 do {
2159 msleep(&p->p_lflag, &p->p_mlock, 0,
2160 "thread_check_setup_complete", NULL);
2161 } while (p->p_lflag & P_LRETURNWAIT);
2162 p->p_lflag &= ~P_LRETURNWAITER;
2163 }
2164
2165 proc_unlock(p);
2166 thread_bootstrap_return();
2167}
2168
2d21ac55
A
2169/*
2170 * posix_spawn
2171 *
2172 * Parameters: uap->pid Pointer to pid return area
2173 * uap->fname File name to exec
2174 * uap->argp Argument list
2175 * uap->envp Environment list
2176 *
2177 * Returns: 0 Success
2178 * EINVAL Invalid argument
2179 * ENOTSUP Not supported
2180 * ENOEXEC Executable file format error
2181 * exec_activate_image:EINVAL Invalid argument
2182 * exec_activate_image:EACCES Permission denied
2183 * exec_activate_image:EINTR Interrupted function
2184 * exec_activate_image:ENOMEM Not enough space
2185 * exec_activate_image:EFAULT Bad address
2186 * exec_activate_image:ENAMETOOLONG Filename too long
2187 * exec_activate_image:ENOEXEC Executable file format error
2188 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
2189 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
2190 * exec_activate_image:???
2191 * mac_execve_enter:???
2192 *
b0d623f7 2193 * TODO: Expect to need __mac_posix_spawn() at some point...
2d21ac55
A
2194 * Handle posix_spawnattr_t
2195 * Handle posix_spawn_file_actions_t
2196 */
2197int
b0d623f7 2198posix_spawn(proc_t ap, struct posix_spawn_args *uap, int32_t *retval)
2d21ac55
A
2199{
2200 proc_t p = ap; /* quiet bogus GCC vfork() warning */
4a3eedf9 2201 user_addr_t pid = uap->pid;
b0d623f7
A
2202 int ival[2]; /* dummy retval for setpgid() */
2203 char *bufp = NULL;
2204 struct image_params *imgp;
2205 struct vnode_attr *vap;
2206 struct vnode_attr *origvap;
2d21ac55
A
2207 struct uthread *uthread = 0; /* compiler complains if not set to 0*/
2208 int error, sig;
2d21ac55 2209 int is_64 = IS_64BIT_PROCESS(p);
2d21ac55
A
2210 struct vfs_context context;
2211 struct user__posix_spawn_args_desc px_args;
2212 struct _posix_spawnattr px_sa;
2213 _posix_spawn_file_actions_t px_sfap = NULL;
2214 _posix_spawn_port_actions_t px_spap = NULL;
b0d623f7
A
2215 struct __kern_sigaction vec;
2216 boolean_t spawn_no_exec = FALSE;
6d2010ae
A
2217 boolean_t proc_transit_set = TRUE;
2218 boolean_t exec_done = FALSE;
fe8ab488 2219 int portwatch_count = 0;
39236c6e
A
2220 ipc_port_t * portwatch_ports = NULL;
2221 vm_size_t px_sa_offset = offsetof(struct _posix_spawnattr, psa_ports);
490019cf
A
2222#if CONFIG_PERSONAS
2223 struct _posix_spawn_persona_info *px_persona = NULL;
2224#endif
2d21ac55 2225
b0d623f7
A
2226 /*
2227 * Allocate a big chunk for locals instead of using stack since these
6d2010ae 2228 * structures are pretty big.
b0d623f7
A
2229 */
2230 MALLOC(bufp, char *, (sizeof(*imgp) + sizeof(*vap) + sizeof(*origvap)), M_TEMP, M_WAITOK | M_ZERO);
2231 imgp = (struct image_params *) bufp;
2232 if (bufp == NULL) {
2233 error = ENOMEM;
2234 goto bad;
2235 }
2236 vap = (struct vnode_attr *) (bufp + sizeof(*imgp));
2237 origvap = (struct vnode_attr *) (bufp + sizeof(*imgp) + sizeof(*vap));
2d21ac55
A
2238
2239 /* Initialize the common data in the image_params structure */
2d21ac55
A
2240 imgp->ip_user_fname = uap->path;
2241 imgp->ip_user_argv = uap->argv;
2242 imgp->ip_user_envv = uap->envp;
b0d623f7
A
2243 imgp->ip_vattr = vap;
2244 imgp->ip_origvattr = origvap;
2d21ac55
A
2245 imgp->ip_vfs_context = &context;
2246 imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT : IMGPF_NONE);
2d21ac55 2247 imgp->ip_seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32);
fe8ab488 2248 imgp->ip_mac_return = 0;
490019cf 2249 imgp->ip_px_persona = NULL;
39037602 2250 imgp->ip_cs_error = OS_REASON_NULL;
2d21ac55
A
2251
2252 if (uap->adesc != USER_ADDR_NULL) {
2253 if(is_64) {
2254 error = copyin(uap->adesc, &px_args, sizeof(px_args));
2255 } else {
b0d623f7 2256 struct user32__posix_spawn_args_desc px_args32;
2d21ac55
A
2257
2258 error = copyin(uap->adesc, &px_args32, sizeof(px_args32));
2259
2260 /*
2261 * Convert arguments descriptor from external 32 bit
2262 * representation to internal 64 bit representation
2263 */
2264 px_args.attr_size = px_args32.attr_size;
2265 px_args.attrp = CAST_USER_ADDR_T(px_args32.attrp);
2266 px_args.file_actions_size = px_args32.file_actions_size;
2267 px_args.file_actions = CAST_USER_ADDR_T(px_args32.file_actions);
2268 px_args.port_actions_size = px_args32.port_actions_size;
2269 px_args.port_actions = CAST_USER_ADDR_T(px_args32.port_actions);
39236c6e
A
2270 px_args.mac_extensions_size = px_args32.mac_extensions_size;
2271 px_args.mac_extensions = CAST_USER_ADDR_T(px_args32.mac_extensions);
3e170ce0
A
2272 px_args.coal_info_size = px_args32.coal_info_size;
2273 px_args.coal_info = CAST_USER_ADDR_T(px_args32.coal_info);
490019cf
A
2274 px_args.persona_info_size = px_args32.persona_info_size;
2275 px_args.persona_info = CAST_USER_ADDR_T(px_args32.persona_info);
2d21ac55
A
2276 }
2277 if (error)
2278 goto bad;
2279
2280 if (px_args.attr_size != 0) {
2281 /*
39236c6e
A
2282 * We are not copying the port_actions pointer,
2283 * because we already have it from px_args.
fe8ab488 2284 * This is a bit fragile: <rdar://problem/16427422>
2d21ac55 2285 */
39236c6e
A
2286
2287 if ((error = copyin(px_args.attrp, &px_sa, px_sa_offset) != 0))
2d21ac55 2288 goto bad;
39236c6e
A
2289
2290 bzero( (void *)( (unsigned long) &px_sa + px_sa_offset), sizeof(px_sa) - px_sa_offset );
2d21ac55
A
2291
2292 imgp->ip_px_sa = &px_sa;
2293 }
2294 if (px_args.file_actions_size != 0) {
2295 /* Limit file_actions to allowed number of open files */
2296 int maxfa = (p->p_limit ? p->p_rlimit[RLIMIT_NOFILE].rlim_cur : NOFILE);
2297 if (px_args.file_actions_size < PSF_ACTIONS_SIZE(1) ||
2298 px_args.file_actions_size > PSF_ACTIONS_SIZE(maxfa)) {
2299 error = EINVAL;
2300 goto bad;
2301 }
2302 MALLOC(px_sfap, _posix_spawn_file_actions_t, px_args.file_actions_size, M_TEMP, M_WAITOK);
2303 if (px_sfap == NULL) {
2304 error = ENOMEM;
2305 goto bad;
2306 }
2307 imgp->ip_px_sfa = px_sfap;
2308
2309 if ((error = copyin(px_args.file_actions, px_sfap,
2310 px_args.file_actions_size)) != 0)
2311 goto bad;
39236c6e
A
2312
2313 /* Verify that the action count matches the struct size */
2314 if (PSF_ACTIONS_SIZE(px_sfap->psfa_act_count) != px_args.file_actions_size) {
2315 error = EINVAL;
2316 goto bad;
2317 }
2d21ac55
A
2318 }
2319 if (px_args.port_actions_size != 0) {
2320 /* Limit port_actions to one page of data */
2321 if (px_args.port_actions_size < PS_PORT_ACTIONS_SIZE(1) ||
2322 px_args.port_actions_size > PAGE_SIZE) {
2323 error = EINVAL;
2324 goto bad;
2325 }
2326
2327 MALLOC(px_spap, _posix_spawn_port_actions_t,
2328 px_args.port_actions_size, M_TEMP, M_WAITOK);
2329 if (px_spap == NULL) {
2330 error = ENOMEM;
2331 goto bad;
2332 }
2333 imgp->ip_px_spa = px_spap;
2334
2335 if ((error = copyin(px_args.port_actions, px_spap,
2336 px_args.port_actions_size)) != 0)
2337 goto bad;
39236c6e
A
2338
2339 /* Verify that the action count matches the struct size */
2340 if (PS_PORT_ACTIONS_SIZE(px_spap->pspa_count) != px_args.port_actions_size) {
2341 error = EINVAL;
2342 goto bad;
2343 }
2344 }
490019cf
A
2345#if CONFIG_PERSONAS
2346 /* copy in the persona info */
2347 if (px_args.persona_info_size != 0 && px_args.persona_info != 0) {
2348 /* for now, we need the exact same struct in user space */
2349 if (px_args.persona_info_size != sizeof(*px_persona)) {
2350 error = ERANGE;
2351 goto bad;
2352 }
3e170ce0 2353
490019cf
A
2354 MALLOC(px_persona, struct _posix_spawn_persona_info *, px_args.persona_info_size, M_TEMP, M_WAITOK|M_ZERO);
2355 if (px_persona == NULL) {
2356 error = ENOMEM;
2357 goto bad;
2358 }
2359 imgp->ip_px_persona = px_persona;
2360
2361 if ((error = copyin(px_args.persona_info, px_persona,
2362 px_args.persona_info_size)) != 0)
2363 goto bad;
2364 if ((error = spawn_validate_persona(px_persona)) != 0)
2365 goto bad;
2366 }
2367#endif
39236c6e
A
2368#if CONFIG_MACF
2369 if (px_args.mac_extensions_size != 0) {
2370 if ((error = spawn_copyin_macpolicyinfo(&px_args, (_posix_spawn_mac_policy_extensions_t *)&imgp->ip_px_smpx)) != 0)
2371 goto bad;
2d21ac55 2372 }
39236c6e 2373#endif /* CONFIG_MACF */
2d21ac55
A
2374 }
2375
b0d623f7
A
2376 /* set uthread to parent */
2377 uthread = get_bsdthread_info(current_thread());
2378
2379 /*
2380 * <rdar://6640530>; this does not result in a behaviour change
2381 * relative to Leopard, so there should not be any existing code
2382 * which depends on it.
2383 */
2384 if (uthread->uu_flag & UT_VFORK) {
2385 error = EINVAL;
2386 goto bad;
2387 }
2388
2389 /*
6d2010ae 2390 * If we don't have the extension flag that turns "posix_spawn()"
b0d623f7
A
2391 * into "execve() with options", then we will be creating a new
2392 * process which does not inherit memory from the parent process,
2393 * which is one of the most expensive things about using fork()
2394 * and execve().
2395 */
2d21ac55 2396 if (imgp->ip_px_sa == NULL || !(px_sa.psa_flags & POSIX_SPAWN_SETEXEC)){
fe8ab488 2397
3e170ce0
A
2398 /* Set the new task's coalition, if it is requested. */
2399 coalition_t coal[COALITION_NUM_TYPES] = { COALITION_NULL };
fe8ab488 2400#if CONFIG_COALITIONS
3e170ce0
A
2401 int i, ncoals;
2402 kern_return_t kr = KERN_SUCCESS;
2403 struct _posix_spawn_coalition_info coal_info;
2404 int coal_role[COALITION_NUM_TYPES];
2405
2406 if (imgp->ip_px_sa == NULL || !px_args.coal_info)
2407 goto do_fork1;
2408
2409 memset(&coal_info, 0, sizeof(coal_info));
2410
2411 if (px_args.coal_info_size > sizeof(coal_info))
2412 px_args.coal_info_size = sizeof(coal_info);
2413 error = copyin(px_args.coal_info,
2414 &coal_info, px_args.coal_info_size);
2415 if (error != 0)
2416 goto bad;
2417
2418 ncoals = 0;
2419 for (i = 0; i < COALITION_NUM_TYPES; i++) {
2420 uint64_t cid = coal_info.psci_info[i].psci_id;
fe8ab488 2421 if (cid != 0) {
3e170ce0
A
2422 /*
2423 * don't allow tasks which are not in a
2424 * privileged coalition to spawn processes
2425 * into coalitions other than their own
2426 */
2427 if (!task_is_in_privileged_coalition(p->task, i)) {
2428 coal_dbg("ERROR: %d not in privilegd "
2429 "coalition of type %d",
2430 p->p_pid, i);
2431 spawn_coalitions_release_all(coal);
2432 error = EPERM;
2433 goto bad;
2434 }
2435
2436 coal_dbg("searching for coalition id:%llu", cid);
2437 /*
2438 * take a reference and activation on the
2439 * coalition to guard against free-while-spawn
2440 * races
2441 */
2442 coal[i] = coalition_find_and_activate_by_id(cid);
2443 if (coal[i] == COALITION_NULL) {
2444 coal_dbg("could not find coalition id:%llu "
2445 "(perhaps it has been terminated or reaped)", cid);
2446 /*
2447 * release any other coalition's we
2448 * may have a reference to
2449 */
2450 spawn_coalitions_release_all(coal);
fe8ab488
A
2451 error = ESRCH;
2452 goto bad;
2453 }
3e170ce0
A
2454 if (coalition_type(coal[i]) != i) {
2455 coal_dbg("coalition with id:%lld is not of type:%d"
2456 " (it's type:%d)", cid, i, coalition_type(coal[i]));
2457 error = ESRCH;
2458 goto bad;
2459 }
2460 coal_role[i] = coal_info.psci_info[i].psci_role;
2461 ncoals++;
fe8ab488
A
2462 }
2463 }
3e170ce0
A
2464 if (ncoals < COALITION_NUM_TYPES) {
2465 /*
2466 * If the user is attempting to spawn into a subset of
2467 * the known coalition types, then make sure they have
2468 * _at_least_ specified a resource coalition. If not,
2469 * the following fork1() call will implicitly force an
2470 * inheritance from 'p' and won't actually spawn the
2471 * new task into the coalitions the user specified.
2472 * (also the call to coalitions_set_roles will panic)
2473 */
2474 if (coal[COALITION_TYPE_RESOURCE] == COALITION_NULL) {
2475 spawn_coalitions_release_all(coal);
2476 error = EINVAL;
2477 goto bad;
2478 }
2479 }
2480do_fork1:
fe8ab488
A
2481#endif /* CONFIG_COALITIONS */
2482
490019cf
A
2483 /*
2484 * note that this will implicitly inherit the
2485 * caller's persona (if it exists)
2486 */
fe8ab488
A
2487 error = fork1(p, &imgp->ip_new_thread, PROC_CREATE_SPAWN, coal);
2488
fe8ab488 2489#if CONFIG_COALITIONS
3e170ce0
A
2490 /* set the roles of this task within each given coalition */
2491 if (error == 0) {
2492 kr = coalitions_set_roles(coal, get_threadtask(imgp->ip_new_thread), coal_role);
2493 if (kr != KERN_SUCCESS)
2494 error = EINVAL;
2495 }
2496
2497 /* drop our references and activations - fork1() now holds them */
2498 spawn_coalitions_release_all(coal);
fe8ab488 2499#endif /* CONFIG_COALITIONS */
3e170ce0 2500 if (error != 0) {
2d21ac55 2501 goto bad;
fe8ab488 2502 }
b0d623f7
A
2503 imgp->ip_flags |= IMGPF_SPAWN; /* spawn w/o exec */
2504 spawn_no_exec = TRUE; /* used in later tests */
fe8ab488 2505
490019cf
A
2506#if CONFIG_PERSONAS
2507 /*
2508 * If the parent isn't in a persona (launchd), and
2509 * hasn't specified a new persona for the process,
2510 * then we'll put the process into the system persona
2511 *
2512 * TODO: this will have to be re-worked because as of
2513 * now, without any launchd adoption, the resulting
2514 * xpcproxy process will not have sufficient
2515 * privileges to setuid/gid.
2516 */
2517#if 0
2518 if (!proc_has_persona(p) && imgp->ip_px_persona == NULL) {
2519 MALLOC(px_persona, struct _posix_spawn_persona_info *,
2520 sizeof(*px_persona), M_TEMP, M_WAITOK|M_ZERO);
2521 if (px_persona == NULL) {
2522 error = ENOMEM;
2523 goto bad;
2524 }
2525 px_persona->pspi_id = persona_get_id(g_system_persona);
2526 imgp->ip_px_persona = px_persona;
2527 }
2528#endif /* 0 */
2529#endif /* CONFIG_PERSONAS */
2d21ac55
A
2530 }
2531
fe8ab488 2532 if (spawn_no_exec) {
b0d623f7 2533 p = (proc_t)get_bsdthreadtask_info(imgp->ip_new_thread);
fe8ab488
A
2534
2535 /*
2536 * We had to wait until this point before firing the
2537 * proc:::create probe, otherwise p would not point to the
2538 * child process.
2539 */
2540 DTRACE_PROC1(create, proc_t, p);
2541 }
6d2010ae 2542 assert(p != NULL);
2d21ac55 2543
b0d623f7 2544 /* By default, the thread everyone plays with is the parent */
2d21ac55
A
2545 context.vc_thread = current_thread();
2546 context.vc_ucred = p->p_ucred; /* XXX must NOT be kauth_cred_get() */
2547
b0d623f7
A
2548 /*
2549 * However, if we're not in the setexec case, redirect the context
2550 * to the newly created process instead
2551 */
2552 if (spawn_no_exec)
2553 context.vc_thread = imgp->ip_new_thread;
2554
2d21ac55
A
2555 /*
2556 * Post fdcopy(), pre exec_handle_sugid() - this is where we want
2557 * to handle the file_actions. Since vfork() also ends up setting
2558 * us into the parent process group, and saved off the signal flags,
2559 * this is also where we want to handle the spawn flags.
2560 */
6d2010ae 2561
2d21ac55 2562 /* Has spawn file actions? */
6d2010ae
A
2563 if (imgp->ip_px_sfa != NULL) {
2564 /*
2565 * The POSIX_SPAWN_CLOEXEC_DEFAULT flag
2566 * is handled in exec_handle_file_actions().
2567 */
2568 if ((error = exec_handle_file_actions(imgp,
2569 imgp->ip_px_sa != NULL ? px_sa.psa_flags : 0)) != 0)
2570 goto bad;
2d21ac55
A
2571 }
2572
2573 /* Has spawn port actions? */
39236c6e
A
2574 if (imgp->ip_px_spa != NULL) {
2575 boolean_t is_adaptive = FALSE;
fe8ab488 2576 boolean_t portwatch_present = FALSE;
39236c6e
A
2577
2578 /* Will this process become adaptive? The apptype isn't ready yet, so we can't look there. */
2579 if (imgp->ip_px_sa != NULL && px_sa.psa_apptype == POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE)
2580 is_adaptive = TRUE;
2581
2582 /*
2583 * portwatch only:
2584 * Allocate a place to store the ports we want to bind to the new task
2585 * We can't bind them until after the apptype is set.
b0d623f7 2586 */
39236c6e
A
2587 if (px_spap->pspa_count != 0 && is_adaptive) {
2588 portwatch_count = px_spap->pspa_count;
2589 MALLOC(portwatch_ports, ipc_port_t *, (sizeof(ipc_port_t) * portwatch_count), M_TEMP, M_WAITOK | M_ZERO);
2590 } else {
2591 portwatch_ports = NULL;
2592 }
2593
39037602 2594 if ((error = exec_handle_port_actions(imgp, &portwatch_present, portwatch_ports)) != 0)
2d21ac55 2595 goto bad;
fe8ab488
A
2596
2597 if (portwatch_present == FALSE && portwatch_ports != NULL) {
2598 FREE(portwatch_ports, M_TEMP);
2599 portwatch_ports = NULL;
2600 portwatch_count = 0;
2601 }
2d21ac55
A
2602 }
2603
2604 /* Has spawn attr? */
2605 if (imgp->ip_px_sa != NULL) {
b0d623f7
A
2606 /*
2607 * Set the process group ID of the child process; this has
2608 * to happen before the image activation.
2609 */
2d21ac55
A
2610 if (px_sa.psa_flags & POSIX_SPAWN_SETPGROUP) {
2611 struct setpgid_args spga;
2612 spga.pid = p->p_pid;
2613 spga.pgid = px_sa.psa_pgroup;
2614 /*
2615 * Effectively, call setpgid() system call; works
2616 * because there are no pointer arguments.
2617 */
2618 if((error = setpgid(p, &spga, ival)) != 0)
2619 goto bad;
2620 }
b0d623f7 2621
2d21ac55
A
2622 /*
2623 * Reset UID/GID to parent's RUID/RGID; This works only
2624 * because the operation occurs *after* the vfork() and
2625 * before the call to exec_handle_sugid() by the image
b0d623f7
A
2626 * activator called from exec_activate_image(). POSIX
2627 * requires that any setuid/setgid bits on the process
2628 * image will take precedence over the spawn attributes
2629 * (re)setting them.
2d21ac55 2630 *
39037602
A
2631 * Modifications to p_ucred must be guarded using the
2632 * proc's ucred lock. This prevents others from accessing
2633 * a garbage credential.
2d21ac55 2634 */
39037602
A
2635 while (px_sa.psa_flags & POSIX_SPAWN_RESETIDS) {
2636 kauth_cred_t my_cred = kauth_cred_proc_ref(p);
6d2010ae 2637 kauth_cred_t my_new_cred = kauth_cred_setuidgid(my_cred, kauth_cred_getruid(my_cred), kauth_cred_getrgid(my_cred));
39037602
A
2638
2639 if (my_cred == my_new_cred) {
2640 kauth_cred_unref(&my_cred);
2641 break;
2642 }
2643
2644 /* update cred on proc */
2645 proc_ucred_lock(p);
2646
2647 if (p->p_ucred != my_cred) {
2648 proc_ucred_unlock(p);
2649 kauth_cred_unref(&my_new_cred);
2650 continue;
6d2010ae 2651 }
39037602
A
2652
2653 /* donate cred reference on my_new_cred to p->p_ucred */
2654 p->p_ucred = my_new_cred;
2655 PROC_UPDATE_CREDS_ONPROC(p);
2656 proc_ucred_unlock(p);
2657
2658 /* drop additional reference that was taken on the previous cred */
2659 kauth_cred_unref(&my_cred);
2d21ac55 2660 }
6d2010ae 2661
490019cf
A
2662#if CONFIG_PERSONAS
2663 if (spawn_no_exec && imgp->ip_px_persona != NULL) {
2664 /*
2665 * If we were asked to spawn a process into a new persona,
2666 * do the credential switch now (which may override the UID/GID
2667 * inherit done just above). It's important to do this switch
2668 * before image activation both for reasons stated above, and
2669 * to ensure that the new persona has access to the image/file
2670 * being executed.
2671 */
2672 error = spawn_persona_adopt(p, imgp->ip_px_persona);
2673 if (error != 0)
2674 goto bad;
2675 }
2676#endif /* CONFIG_PERSONAS */
3e170ce0 2677#if !SECURE_KERNEL
6d2010ae
A
2678 /*
2679 * Disable ASLR for the spawned process.
3e170ce0
A
2680 *
2681 * But only do so if we are not embedded + RELEASE.
2682 * While embedded allows for a boot-arg (-disable_aslr)
2683 * to deal with this (which itself is only honored on
2684 * DEVELOPMENT or DEBUG builds of xnu), it is often
2685 * useful or necessary to disable ASLR on a per-process
2686 * basis for unit testing and debugging.
39236c6e 2687 */
6d2010ae
A
2688 if (px_sa.psa_flags & _POSIX_SPAWN_DISABLE_ASLR)
2689 OSBitOrAtomic(P_DISABLE_ASLR, &p->p_flag);
3e170ce0 2690#endif /* !SECURE_KERNEL */
6d2010ae
A
2691
2692 /*
2693 * Forcibly disallow execution from data pages for the spawned process
2694 * even if it would otherwise be permitted by the architecture default.
2695 */
2696 if (px_sa.psa_flags & _POSIX_SPAWN_ALLOW_DATA_EXEC)
2697 imgp->ip_flags |= IMGPF_ALLOW_DATA_EXEC;
b0d623f7
A
2698 }
2699
6d2010ae
A
2700 /*
2701 * Disable ASLR during image activation. This occurs either if the
2702 * _POSIX_SPAWN_DISABLE_ASLR attribute was found above or if
2703 * P_DISABLE_ASLR was inherited from the parent process.
2704 */
2705 if (p->p_flag & P_DISABLE_ASLR)
2706 imgp->ip_flags |= IMGPF_DISABLE_ASLR;
2707
b0d623f7
A
2708 /*
2709 * Clear transition flag so we won't hang if exec_activate_image() causes
2710 * an automount (and launchd does a proc sysctl to service it).
2711 *
2712 * <rdar://problem/6848672>, <rdar://problem/5959568>.
2713 */
2714 if (spawn_no_exec) {
2715 proc_transend(p, 0);
6d2010ae 2716 proc_transit_set = 0;
b0d623f7
A
2717 }
2718
2719#if MAC_SPAWN /* XXX */
2720 if (uap->mac_p != USER_ADDR_NULL) {
2721 error = mac_execve_enter(uap->mac_p, imgp);
2722 if (error)
2723 goto bad;
2724 }
2725#endif
2726
2727 /*
2728 * Activate the image
2729 */
2730 error = exec_activate_image(imgp);
fe8ab488 2731
6d2010ae
A
2732 if (error == 0) {
2733 /* process completed the exec */
2734 exec_done = TRUE;
2735 } else if (error == -1) {
2736 /* Image not claimed by any activator? */
b0d623f7 2737 error = ENOEXEC;
6d2010ae 2738 }
b0d623f7
A
2739
2740 /*
2741 * If we have a spawn attr, and it contains signal related flags,
2742 * the we need to process them in the "context" of the new child
2743 * process, so we have to process it following image activation,
2744 * prior to making the thread runnable in user space. This is
2745 * necessitated by some signal information being per-thread rather
2746 * than per-process, and we don't have the new allocation in hand
2747 * until after the image is activated.
2748 */
2749 if (!error && imgp->ip_px_sa != NULL) {
2750 thread_t child_thread = current_thread();
2751 uthread_t child_uthread = uthread;
2752
2753 /*
2754 * If we created a new child thread, then the thread and
2755 * uthread are different than the current ones; otherwise,
2756 * we leave them, since we are in the exec case instead.
2757 */
2758 if (spawn_no_exec) {
2759 child_thread = imgp->ip_new_thread;
2760 child_uthread = get_bsdthread_info(child_thread);
2761 }
2762
2d21ac55
A
2763 /*
2764 * Mask a list of signals, instead of them being unmasked, if
2765 * they were unmasked in the parent; note that some signals
2766 * are not maskable.
2767 */
2768 if (px_sa.psa_flags & POSIX_SPAWN_SETSIGMASK)
b0d623f7 2769 child_uthread->uu_sigmask = (px_sa.psa_sigmask & ~sigcantmask);
2d21ac55
A
2770 /*
2771 * Default a list of signals instead of ignoring them, if
b0d623f7
A
2772 * they were ignored in the parent. Note that we pass
2773 * spawn_no_exec to setsigvec() to indicate that we called
2774 * fork1() and therefore do not need to call proc_signalstart()
2775 * internally.
2d21ac55
A
2776 */
2777 if (px_sa.psa_flags & POSIX_SPAWN_SETSIGDEF) {
2778 vec.sa_handler = SIG_DFL;
2779 vec.sa_tramp = 0;
2780 vec.sa_mask = 0;
2781 vec.sa_flags = 0;
39037602
A
2782 for (sig = 1; sig < NSIG; sig++)
2783 if (px_sa.psa_sigdefault & (1 << (sig-1))) {
2784 error = setsigvec(p, child_thread, sig, &vec, spawn_no_exec);
2d21ac55
A
2785 }
2786 }
316670eb
A
2787
2788 /*
2789 * Activate the CPU usage monitor, if requested. This is done via a task-wide, per-thread CPU
2790 * usage limit, which will generate a resource exceeded exception if any one thread exceeds the
2791 * limit.
2792 *
2793 * Userland gives us interval in seconds, and the kernel SPI expects nanoseconds.
2794 */
2795 if (px_sa.psa_cpumonitor_percent != 0) {
39236c6e
A
2796 /*
2797 * Always treat a CPU monitor activation coming from spawn as entitled. Requiring
2798 * an entitlement to configure the monitor a certain way seems silly, since
2799 * whomever is turning it on could just as easily choose not to do so.
39236c6e 2800 */
316670eb
A
2801 error = proc_set_task_ruse_cpu(p->task,
2802 TASK_POLICY_RESOURCE_ATTRIBUTE_NOTIFY_EXC,
3e170ce0
A
2803 px_sa.psa_cpumonitor_percent,
2804 px_sa.psa_cpumonitor_interval * NSEC_PER_SEC,
39236c6e 2805 0, TRUE);
316670eb 2806 }
2d21ac55
A
2807 }
2808
b0d623f7 2809bad:
39236c6e 2810
b0d623f7 2811 if (error == 0) {
316670eb 2812 /* reset delay idle sleep status if set */
316670eb
A
2813 if ((p->p_flag & P_DELAYIDLESLEEP) == P_DELAYIDLESLEEP)
2814 OSBitAndAtomic(~((uint32_t)P_DELAYIDLESLEEP), &p->p_flag);
b0d623f7
A
2815 /* upon successful spawn, re/set the proc control state */
2816 if (imgp->ip_px_sa != NULL) {
2817 switch (px_sa.psa_pcontrol) {
2818 case POSIX_SPAWN_PCONTROL_THROTTLE:
2819 p->p_pcaction = P_PCTHROTTLE;
2820 break;
2821 case POSIX_SPAWN_PCONTROL_SUSPEND:
2822 p->p_pcaction = P_PCSUSP;
2823 break;
2824 case POSIX_SPAWN_PCONTROL_KILL:
2825 p->p_pcaction = P_PCKILL;
2826 break;
2827 case POSIX_SPAWN_PCONTROL_NONE:
2828 default:
2829 p->p_pcaction = 0;
2830 break;
2831 };
2d21ac55 2832 }
b0d623f7 2833 exec_resettextvp(p, imgp);
316670eb 2834
39037602 2835#if CONFIG_MEMORYSTATUS
316670eb 2836 /* Has jetsam attributes? */
39236c6e 2837 if (imgp->ip_px_sa != NULL && (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_SET)) {
3e170ce0
A
2838 /*
2839 * With 2-level high-water-mark support, POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND is no
2840 * longer relevant, as background limits are described via the inactive limit slots.
2841 * At the kernel layer, the flag is ignored.
2842 *
2843 * That said, however, if the POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND is passed in,
2844 * we attempt to mimic previous behavior by forcing the BG limit data into the
2845 * inactive/non-fatal mode and force the active slots to hold system_wide/fatal mode.
2846 * The kernel layer will flag this mapping.
2847 */
2848 if (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND) {
2849 memorystatus_update(p, px_sa.psa_priority, 0,
2850 (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY),
2851 TRUE,
2852 -1, TRUE,
2853 px_sa.psa_memlimit_inactive, FALSE,
2854 (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND));
2855 } else {
2856 memorystatus_update(p, px_sa.psa_priority, 0,
2857 (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY),
2858 TRUE,
2859 px_sa.psa_memlimit_active,
2860 (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_MEMLIMIT_ACTIVE_FATAL),
2861 px_sa.psa_memlimit_inactive,
2862 (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_MEMLIMIT_INACTIVE_FATAL),
2863 (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND));
2864 }
2865
316670eb 2866 }
39037602 2867#endif /* CONFIG_MEMORYSTATUS */
2d21ac55
A
2868 }
2869
b0d623f7
A
2870 /*
2871 * If we successfully called fork1(), we always need to do this;
2872 * we identify this case by noting the IMGPF_SPAWN flag. This is
2873 * because we come back from that call with signals blocked in the
2874 * child, and we have to unblock them, but we want to wait until
2875 * after we've performed any spawn actions. This has to happen
2876 * before check_for_signature(), which uses psignal.
2877 */
2878 if (spawn_no_exec) {
6d2010ae
A
2879 if (proc_transit_set)
2880 proc_transend(p, 0);
2881
b0d623f7
A
2882 /*
2883 * Drop the signal lock on the child which was taken on our
2884 * behalf by forkproc()/cloneproc() to prevent signals being
2885 * received by the child in a partially constructed state.
2886 */
2887 proc_signalend(p, 0);
2888
2889 /* flag the 'fork' has occurred */
2890 proc_knote(p->p_pptr, NOTE_FORK | p->p_pid);
2891 /* then flag exec has occurred */
39236c6e
A
2892 /* notify only if it has not failed due to FP Key error */
2893 if ((p->p_lflag & P_LTERM_DECRYPTFAIL) == 0)
2894 proc_knote(p, NOTE_EXEC);
04b8595b 2895 } else if (error == 0) {
fe8ab488
A
2896 /* reset the importance attribute from our previous life */
2897 task_importance_reset(p->task);
490019cf 2898 }
fe8ab488 2899
490019cf
A
2900 if (error == 0) {
2901 /*
2902 * We need to initialize the bank context behind the protection of
2903 * the proc_trans lock to prevent a race with exit. We can't do this during
2904 * exec_activate_image because task_bank_init checks entitlements that
2905 * aren't loaded until subsequent calls (including exec_resettextvp).
2906 */
2907 error = proc_transstart(p, 0, 0);
2908
2909 if (error == 0) {
2910 task_bank_init(p->task);
2911 proc_transend(p, 0);
2912 }
fe8ab488
A
2913 }
2914
490019cf 2915
fe8ab488
A
2916 /*
2917 * Apply the spawnattr policy, apptype (which primes the task for importance donation),
2918 * and bind any portwatch ports to the new task.
2919 * This must be done after the exec so that the child's thread is ready,
2920 * and after the in transit state has been released, because priority is
2921 * dropped here so we need to be prepared for a potentially long preemption interval
2922 *
2923 * TODO: Consider splitting this up into separate phases
2924 */
2925 if (error == 0 && imgp->ip_px_sa != NULL) {
2926 struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
2927
3e170ce0 2928 exec_handle_spawnattr_policy(p, psa->psa_apptype, psa->psa_qos_clamp, psa->psa_darwin_role,
fe8ab488
A
2929 portwatch_ports, portwatch_count);
2930 }
2931
2932 /* Apply the main thread qos */
2933 if (error == 0) {
2934 thread_t main_thread = (imgp->ip_new_thread != NULL) ? imgp->ip_new_thread : current_thread();
2935
2936 task_set_main_thread_qos(p->task, main_thread);
2937 }
2938
2939 /*
2940 * Release any ports we kept around for binding to the new task
2941 * We need to release the rights even if the posix_spawn has failed.
2942 */
2943 if (portwatch_ports != NULL) {
2944 for (int i = 0; i < portwatch_count; i++) {
2945 ipc_port_t port = NULL;
2946 if ((port = portwatch_ports[i]) != NULL) {
2947 ipc_port_release_send(port);
2948 }
2949 }
2950 FREE(portwatch_ports, M_TEMP);
2951 portwatch_ports = NULL;
2952 portwatch_count = 0;
2d21ac55 2953 }
2d21ac55 2954
b0d623f7
A
2955 /*
2956 * We have to delay operations which might throw a signal until after
2957 * the signals have been unblocked; however, we want that to happen
2958 * after exec_resettextvp() so that the textvp is correct when they
2959 * fire.
2960 */
2d21ac55 2961 if (error == 0) {
b0d623f7
A
2962 error = check_for_signature(p, imgp);
2963
2964 /*
2965 * Pay for our earlier safety; deliver the delayed signals from
2966 * the incomplete spawn process now that it's complete.
2967 */
2968 if (imgp != NULL && spawn_no_exec && (p->p_lflag & P_LTRACED)) {
2969 psignal_vfork(p, p->task, imgp->ip_new_thread, SIGTRAP);
2970 }
39037602
A
2971
2972 if (error == 0 && !spawn_no_exec)
2973 KDBG(BSDDBG_CODE(DBG_BSD_PROC,BSD_PROC_EXEC),
2974 p->p_pid);
b0d623f7
A
2975 }
2976
2d21ac55 2977
b0d623f7
A
2978 if (imgp != NULL) {
2979 if (imgp->ip_vp)
2980 vnode_put(imgp->ip_vp);
39236c6e
A
2981 if (imgp->ip_scriptvp)
2982 vnode_put(imgp->ip_scriptvp);
b0d623f7
A
2983 if (imgp->ip_strings)
2984 execargs_free(imgp);
2985 if (imgp->ip_px_sfa != NULL)
2986 FREE(imgp->ip_px_sfa, M_TEMP);
2987 if (imgp->ip_px_spa != NULL)
2988 FREE(imgp->ip_px_spa, M_TEMP);
490019cf
A
2989#if CONFIG_PERSONAS
2990 if (imgp->ip_px_persona != NULL)
2991 FREE(imgp->ip_px_persona, M_TEMP);
2992#endif
2d21ac55 2993#if CONFIG_MACF
39236c6e
A
2994 if (imgp->ip_px_smpx != NULL)
2995 spawn_free_macpolicyinfo(imgp->ip_px_smpx);
b0d623f7
A
2996 if (imgp->ip_execlabelp)
2997 mac_cred_label_free(imgp->ip_execlabelp);
2998 if (imgp->ip_scriptlabelp)
2999 mac_vnode_label_free(imgp->ip_scriptlabelp);
39037602
A
3000 if (imgp->ip_cs_error != OS_REASON_NULL) {
3001 os_reason_free(imgp->ip_cs_error);
3002 imgp->ip_cs_error = OS_REASON_NULL;
3003 }
2d21ac55 3004#endif
b0d623f7
A
3005 }
3006
39236c6e
A
3007#if CONFIG_DTRACE
3008 if (spawn_no_exec) {
3009 /*
3010 * In the original DTrace reference implementation,
3011 * posix_spawn() was a libc routine that just
3012 * did vfork(2) then exec(2). Thus the proc::: probes
3013 * are very fork/exec oriented. The details of this
3014 * in-kernel implementation of posix_spawn() is different
3015 * (while producing the same process-observable effects)
3016 * particularly w.r.t. errors, and which thread/process
3017 * is constructing what on behalf of whom.
3018 */
3019 if (error) {
3020 DTRACE_PROC1(spawn__failure, int, error);
3021 } else {
3022 DTRACE_PROC(spawn__success);
3023 /*
3024 * Some DTrace scripts, e.g. newproc.d in
3025 * /usr/bin, rely on the the 'exec-success'
3026 * probe being fired in the child after the
3027 * new process image has been constructed
3028 * in order to determine the associated pid.
3029 *
3030 * So, even though the parent built the image
3031 * here, for compatibility, mark the new thread
3032 * so 'exec-success' fires on it as it leaves
3033 * the kernel.
3034 */
3035 dtrace_thread_didexec(imgp->ip_new_thread);
3036 }
b0d623f7 3037 } else {
39236c6e
A
3038 if (error) {
3039 DTRACE_PROC1(exec__failure, int, error);
3040 } else {
3041 DTRACE_PROC(exec__success);
3042 }
b0d623f7 3043 }
fe8ab488
A
3044
3045 if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL)
3046 (*dtrace_proc_waitfor_hook)(p);
39236c6e 3047#endif
b0d623f7
A
3048
3049 /* Return to both the parent and the child? */
3050 if (imgp != NULL && spawn_no_exec) {
2d21ac55 3051 /*
2d21ac55
A
3052 * If the parent wants the pid, copy it out
3053 */
4a3eedf9
A
3054 if (pid != USER_ADDR_NULL)
3055 (void)suword(pid, p->p_pid);
2d21ac55 3056 retval[0] = error;
2d21ac55 3057
2d21ac55 3058 /*
b0d623f7
A
3059 * If we had an error, perform an internal reap ; this is
3060 * entirely safe, as we have a real process backing us.
2d21ac55 3061 */
b0d623f7
A
3062 if (error) {
3063 proc_list_lock();
3064 p->p_listflag |= P_LIST_DEADPARENT;
3065 proc_list_unlock();
3066 proc_lock(p);
3067 /* make sure no one else has killed it off... */
3068 if (p->p_stat != SZOMB && p->exit_thread == NULL) {
3069 p->exit_thread = current_thread();
3070 proc_unlock(p);
3071 exit1(p, 1, (int *)NULL);
3e170ce0 3072 proc_clear_return_wait(p, imgp->ip_new_thread);
6d2010ae
A
3073 if (exec_done == FALSE) {
3074 task_deallocate(get_threadtask(imgp->ip_new_thread));
3075 thread_deallocate(imgp->ip_new_thread);
3076 }
b0d623f7
A
3077 } else {
3078 /* someone is doing it for us; just skip it */
3079 proc_unlock(p);
3e170ce0 3080 proc_clear_return_wait(p, imgp->ip_new_thread);
b0d623f7
A
3081 }
3082 } else {
2d21ac55 3083
b0d623f7 3084 /*
39236c6e 3085 * Return to the child
b0d623f7
A
3086 *
3087 * Note: the image activator earlier dropped the
3088 * task/thread references to the newly spawned
3089 * process; this is OK, since we still have suspended
3090 * queue references on them, so we should be fine
3091 * with the delayed resume of the thread here.
3092 */
3e170ce0 3093 proc_clear_return_wait(p, imgp->ip_new_thread);
b0d623f7
A
3094 }
3095 }
3096 if (bufp != NULL) {
3097 FREE(bufp, M_TEMP);
3098 }
3099
2d21ac55
A
3100 return(error);
3101}
3102
3103
3104/*
3105 * execve
3106 *
3107 * Parameters: uap->fname File name to exec
3108 * uap->argp Argument list
3109 * uap->envp Environment list
3110 *
3111 * Returns: 0 Success
3112 * __mac_execve:EINVAL Invalid argument
3113 * __mac_execve:ENOTSUP Invalid argument
3114 * __mac_execve:EACCES Permission denied
3115 * __mac_execve:EINTR Interrupted function
3116 * __mac_execve:ENOMEM Not enough space
3117 * __mac_execve:EFAULT Bad address
3118 * __mac_execve:ENAMETOOLONG Filename too long
3119 * __mac_execve:ENOEXEC Executable file format error
3120 * __mac_execve:ETXTBSY Text file busy [misuse of error code]
3121 * __mac_execve:???
3122 *
3123 * TODO: Dynamic linker header address on stack is copied via suword()
3124 */
3125/* ARGSUSED */
3126int
b0d623f7 3127execve(proc_t p, struct execve_args *uap, int32_t *retval)
2d21ac55
A
3128{
3129 struct __mac_execve_args muap;
3130 int err;
3131
39236c6e
A
3132 memoryshot(VM_EXECVE, DBG_FUNC_NONE);
3133
2d21ac55
A
3134 muap.fname = uap->fname;
3135 muap.argp = uap->argp;
3136 muap.envp = uap->envp;
3137 muap.mac_p = USER_ADDR_NULL;
3138 err = __mac_execve(p, &muap, retval);
3139
3140 return(err);
3141}
3142
3143/*
3144 * __mac_execve
3145 *
3146 * Parameters: uap->fname File name to exec
3147 * uap->argp Argument list
3148 * uap->envp Environment list
3149 * uap->mac_p MAC label supplied by caller
3150 *
3151 * Returns: 0 Success
3152 * EINVAL Invalid argument
3153 * ENOTSUP Not supported
3154 * ENOEXEC Executable file format error
3155 * exec_activate_image:EINVAL Invalid argument
3156 * exec_activate_image:EACCES Permission denied
3157 * exec_activate_image:EINTR Interrupted function
3158 * exec_activate_image:ENOMEM Not enough space
3159 * exec_activate_image:EFAULT Bad address
3160 * exec_activate_image:ENAMETOOLONG Filename too long
3161 * exec_activate_image:ENOEXEC Executable file format error
3162 * exec_activate_image:ETXTBSY Text file busy [misuse of error code]
3163 * exec_activate_image:EBADEXEC The executable is corrupt/unknown
3164 * exec_activate_image:???
3165 * mac_execve_enter:???
3166 *
3167 * TODO: Dynamic linker header address on stack is copied via suword()
3168 */
3169int
b0d623f7 3170__mac_execve(proc_t p, struct __mac_execve_args *uap, int32_t *retval)
2d21ac55 3171{
b0d623f7
A
3172 char *bufp = NULL;
3173 struct image_params *imgp;
3174 struct vnode_attr *vap;
3175 struct vnode_attr *origvap;
2d21ac55 3176 int error;
2d21ac55
A
3177 int is_64 = IS_64BIT_PROCESS(p);
3178 struct vfs_context context;
fe8ab488 3179 struct uthread *uthread;
2d21ac55
A
3180
3181 context.vc_thread = current_thread();
3182 context.vc_ucred = kauth_cred_proc_ref(p); /* XXX must NOT be kauth_cred_get() */
3183
b0d623f7
A
3184 /* Allocate a big chunk for locals instead of using stack since these
3185 * structures a pretty big.
3186 */
3187 MALLOC(bufp, char *, (sizeof(*imgp) + sizeof(*vap) + sizeof(*origvap)), M_TEMP, M_WAITOK | M_ZERO);
3188 imgp = (struct image_params *) bufp;
3189 if (bufp == NULL) {
3190 error = ENOMEM;
3191 goto exit_with_error;
3192 }
3193 vap = (struct vnode_attr *) (bufp + sizeof(*imgp));
3194 origvap = (struct vnode_attr *) (bufp + sizeof(*imgp) + sizeof(*vap));
3195
2d21ac55 3196 /* Initialize the common data in the image_params structure */
2d21ac55
A
3197 imgp->ip_user_fname = uap->fname;
3198 imgp->ip_user_argv = uap->argp;
3199 imgp->ip_user_envv = uap->envp;
b0d623f7
A
3200 imgp->ip_vattr = vap;
3201 imgp->ip_origvattr = origvap;
2d21ac55 3202 imgp->ip_vfs_context = &context;
6d2010ae 3203 imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT : IMGPF_NONE) | ((p->p_flag & P_DISABLE_ASLR) ? IMGPF_DISABLE_ASLR : IMGPF_NONE);
2d21ac55 3204 imgp->ip_seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32);
fe8ab488 3205 imgp->ip_mac_return = 0;
39037602 3206 imgp->ip_cs_error = OS_REASON_NULL;
fe8ab488
A
3207
3208 uthread = get_bsdthread_info(current_thread());
3209 if (uthread->uu_flag & UT_VFORK) {
3210 imgp->ip_flags |= IMGPF_VFORK_EXEC;
3211 }
2d21ac55 3212
2d21ac55
A
3213#if CONFIG_MACF
3214 if (uap->mac_p != USER_ADDR_NULL) {
3215 error = mac_execve_enter(uap->mac_p, imgp);
3216 if (error) {
3217 kauth_cred_unref(&context.vc_ucred);
b0d623f7 3218 goto exit_with_error;
2d21ac55
A
3219 }
3220 }
3221#endif
3222
2d21ac55 3223 error = exec_activate_image(imgp);
2d21ac55
A
3224
3225 kauth_cred_unref(&context.vc_ucred);
3226
3227 /* Image not claimed by any activator? */
3228 if (error == -1)
3229 error = ENOEXEC;
3230
3231 if (error == 0) {
3232 exec_resettextvp(p, imgp);
b0d623f7 3233 error = check_for_signature(p, imgp);
2d21ac55
A
3234 }
3235 if (imgp->ip_vp != NULLVP)
3236 vnode_put(imgp->ip_vp);
39236c6e
A
3237 if (imgp->ip_scriptvp != NULLVP)
3238 vnode_put(imgp->ip_scriptvp);
2d21ac55
A
3239 if (imgp->ip_strings)
3240 execargs_free(imgp);
3241#if CONFIG_MACF
3242 if (imgp->ip_execlabelp)
3243 mac_cred_label_free(imgp->ip_execlabelp);
3244 if (imgp->ip_scriptlabelp)
3245 mac_vnode_label_free(imgp->ip_scriptlabelp);
3246#endif
39037602
A
3247 if (imgp->ip_cs_error != OS_REASON_NULL) {
3248 os_reason_free(imgp->ip_cs_error);
3249 imgp->ip_cs_error = OS_REASON_NULL;
3250 }
490019cf
A
3251
3252 if (!error) {
3253 /*
3254 * We need to initialize the bank context behind the protection of
3255 * the proc_trans lock to prevent a race with exit. We can't do this during
3256 * exec_activate_image because task_bank_init checks entitlements that
3257 * aren't loaded until subsequent calls (including exec_resettextvp).
3258 */
3259 error = proc_transstart(p, 0, 0);
3260
3261 if (!error) {
3262 task_bank_init(p->task);
3263 proc_transend(p, 0);
3264 }
3265 }
3266
2d21ac55 3267 if (!error) {
b0d623f7
A
3268 /* Sever any extant thread affinity */
3269 thread_affinity_exec(current_thread());
3270
490019cf 3271 thread_t main_thread = (imgp->ip_new_thread != NULL) ? imgp->ip_new_thread : current_thread();
fe8ab488
A
3272
3273 task_set_main_thread_qos(p->task, main_thread);
3274
3275 /* reset task importance */
3276 task_importance_reset(p->task);
3277
b0d623f7 3278 DTRACE_PROC(exec__success);
fe8ab488
A
3279
3280#if CONFIG_DTRACE
3281 if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL)
3282 (*dtrace_proc_waitfor_hook)(p);
3283#endif
3284
3285 if (imgp->ip_flags & IMGPF_VFORK_EXEC) {
2d21ac55 3286 vfork_return(p, retval, p->p_pid);
3e170ce0 3287 proc_clear_return_wait(p, imgp->ip_new_thread);
2d21ac55
A
3288 }
3289 } else {
3290 DTRACE_PROC1(exec__failure, int, error);
3291 }
b0d623f7
A
3292
3293exit_with_error:
3294 if (bufp != NULL) {
3295 FREE(bufp, M_TEMP);
3296 }
2d21ac55
A
3297
3298 return(error);
3299}
3300
3301
3302/*
3303 * copyinptr
3304 *
3305 * Description: Copy a pointer in from user space to a user_addr_t in kernel
3306 * space, based on 32/64 bitness of the user space
3307 *
3308 * Parameters: froma User space address
3309 * toptr Address of kernel space user_addr_t
3310 * ptr_size 4/8, based on 'froma' address space
3311 *
3312 * Returns: 0 Success
3313 * EFAULT Bad 'froma'
3314 *
3315 * Implicit returns:
3316 * *ptr_size Modified
3317 */
3318static int
3319copyinptr(user_addr_t froma, user_addr_t *toptr, int ptr_size)
3320{
3321 int error;
3322
3323 if (ptr_size == 4) {
3324 /* 64 bit value containing 32 bit address */
3325 unsigned int i;
3326
3327 error = copyin(froma, &i, 4);
3328 *toptr = CAST_USER_ADDR_T(i); /* SAFE */
3329 } else {
3330 error = copyin(froma, toptr, 8);
3331 }
3332 return (error);
3333}
3334
3335
3336/*
3337 * copyoutptr
3338 *
3339 * Description: Copy a pointer out from a user_addr_t in kernel space to
3340 * user space, based on 32/64 bitness of the user space
3341 *
3342 * Parameters: ua User space address to copy to
3343 * ptr Address of kernel space user_addr_t
3344 * ptr_size 4/8, based on 'ua' address space
3345 *
3346 * Returns: 0 Success
3347 * EFAULT Bad 'ua'
3348 *
2d21ac55
A
3349 */
3350static int
3351copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size)
3352{
91447636 3353 int error;
1c79356b 3354
91447636
A
3355 if (ptr_size == 4) {
3356 /* 64 bit value containing 32 bit address */
b0d623f7 3357 unsigned int i = CAST_DOWN_EXPLICIT(unsigned int,ua); /* SAFE */
91447636
A
3358
3359 error = copyout(&i, ptr, 4);
3360 } else {
3361 error = copyout(&ua, ptr, 8);
1c79356b 3362 }
91447636
A
3363 return (error);
3364}
3365
3366
3367/*
3368 * exec_copyout_strings
3369 *
3370 * Copy out the strings segment to user space. The strings segment is put
3371 * on a preinitialized stack frame.
3372 *
3373 * Parameters: struct image_params * the image parameter block
3374 * int * a pointer to the stack offset variable
3375 *
3376 * Returns: 0 Success
3377 * !0 Faiure: errno
3378 *
3379 * Implicit returns:
3380 * (*stackp) The stack offset, modified
3381 *
3382 * Note: The strings segment layout is backward, from the beginning
3383 * of the top of the stack to consume the minimal amount of
3384 * space possible; the returned stack pointer points to the
6d2010ae 3385 * end of the area consumed (stacks grow downward).
91447636
A
3386 *
3387 * argc is an int; arg[i] are pointers; env[i] are pointers;
6d2010ae 3388 * the 0's are (void *)NULL's
91447636
A
3389 *
3390 * The stack frame layout is:
3391 *
6d2010ae
A
3392 * +-------------+ <- p->user_stack
3393 * | 16b |
3394 * +-------------+
3395 * | STRING AREA |
3396 * | : |
3397 * | : |
3398 * | : |
3399 * +- -- -- -- --+
3400 * | PATH AREA |
3401 * +-------------+
3402 * | 0 |
3403 * +-------------+
3404 * | applev[n] |
3405 * +-------------+
3406 * :
3407 * :
3408 * +-------------+
3409 * | applev[1] |
3410 * +-------------+
3411 * | exec_path / |
3412 * | applev[0] |
3413 * +-------------+
3414 * | 0 |
3415 * +-------------+
3416 * | env[n] |
3417 * +-------------+
3418 * :
3419 * :
3420 * +-------------+
3421 * | env[0] |
3422 * +-------------+
3423 * | 0 |
3424 * +-------------+
3425 * | arg[argc-1] |
3426 * +-------------+
3427 * :
3428 * :
3429 * +-------------+
3430 * | arg[0] |
3431 * +-------------+
3432 * | argc |
3433 * sp-> +-------------+
91447636
A
3434 *
3435 * Although technically a part of the STRING AREA, we treat the PATH AREA as
3436 * a separate entity. This allows us to align the beginning of the PATH AREA
3437 * to a pointer boundary so that the exec_path, env[i], and argv[i] pointers
3438 * which preceed it on the stack are properly aligned.
91447636 3439 */
6d2010ae 3440
91447636
A
3441static int
3442exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp)
3443{
2d21ac55 3444 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
91447636 3445 int ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
6d2010ae
A
3446 int ptr_area_size;
3447 void *ptr_buffer_start, *ptr_buffer;
3448 int string_size;
3449
91447636 3450 user_addr_t string_area; /* *argv[], *env[] */
6d2010ae
A
3451 user_addr_t ptr_area; /* argv[], env[], applev[] */
3452 user_addr_t argc_area; /* argc */
91447636 3453 user_addr_t stack;
91447636 3454 int error;
6d2010ae
A
3455
3456 unsigned i;
3457 struct copyout_desc {
3458 char *start_string;
3459 int count;
3460#if CONFIG_DTRACE
3461 user_addr_t *dtrace_cookie;
3462#endif
3463 boolean_t null_term;
3464 } descriptors[] = {
3465 {
3466 .start_string = imgp->ip_startargv,
3467 .count = imgp->ip_argc,
3468#if CONFIG_DTRACE
3469 .dtrace_cookie = &p->p_dtrace_argv,
3470#endif
3471 .null_term = TRUE
3472 },
3473 {
3474 .start_string = imgp->ip_endargv,
3475 .count = imgp->ip_envc,
3476#if CONFIG_DTRACE
3477 .dtrace_cookie = &p->p_dtrace_envp,
3478#endif
3479 .null_term = TRUE
3480 },
3481 {
3482 .start_string = imgp->ip_strings,
3483 .count = 1,
3484#if CONFIG_DTRACE
3485 .dtrace_cookie = NULL,
3486#endif
3487 .null_term = FALSE
3488 },
3489 {
3490 .start_string = imgp->ip_endenvv,
3491 .count = imgp->ip_applec - 1, /* exec_path handled above */
3492#if CONFIG_DTRACE
3493 .dtrace_cookie = NULL,
3494#endif
3495 .null_term = TRUE
3496 }
3497 };
91447636
A
3498
3499 stack = *stackp;
3500
3501 /*
6d2010ae
A
3502 * All previous contributors to the string area
3503 * should have aligned their sub-area
91447636 3504 */
6d2010ae
A
3505 if (imgp->ip_strspace % ptr_size != 0) {
3506 error = EINVAL;
3507 goto bad;
3508 }
91447636 3509
6d2010ae
A
3510 /* Grow the stack down for the strings we've been building up */
3511 string_size = imgp->ip_strendp - imgp->ip_strings;
3512 stack -= string_size;
3513 string_area = stack;
3514
3515 /*
3516 * Need room for one pointer for each string, plus
3517 * one for the NULLs terminating the argv, envv, and apple areas.
3518 */
3519 ptr_area_size = (imgp->ip_argc + imgp->ip_envc + imgp->ip_applec + 3) *
3520 ptr_size;
3521 stack -= ptr_area_size;
3522 ptr_area = stack;
3523
3524 /* We'll construct all the pointer arrays in our string buffer,
3525 * which we already know is aligned properly, and ip_argspace
3526 * was used to verify we have enough space.
3527 */
3528 ptr_buffer_start = ptr_buffer = (void *)imgp->ip_strendp;
3529
3530 /*
3531 * Need room for pointer-aligned argc slot.
3532 */
3533 stack -= ptr_size;
3534 argc_area = stack;
1c79356b
A
3535
3536 /*
91447636
A
3537 * Record the size of the arguments area so that sysctl_procargs()
3538 * can return the argument area without having to parse the arguments.
1c79356b 3539 */
2d21ac55 3540 proc_lock(p);
91447636 3541 p->p_argc = imgp->ip_argc;
6d2010ae 3542 p->p_argslen = (int)(*stackp - string_area);
2d21ac55 3543 proc_unlock(p);
91447636 3544
6d2010ae
A
3545 /* Return the initial stack address: the location of argc */
3546 *stackp = stack;
91447636 3547
1c79356b 3548 /*
6d2010ae
A
3549 * Copy out the entire strings area.
3550 */
3551 error = copyout(imgp->ip_strings, string_area,
3552 string_size);
91447636
A
3553 if (error)
3554 goto bad;
3555
6d2010ae
A
3556 for (i = 0; i < sizeof(descriptors)/sizeof(descriptors[0]); i++) {
3557 char *cur_string = descriptors[i].start_string;
3558 int j;
91447636 3559
2d21ac55 3560#if CONFIG_DTRACE
6d2010ae
A
3561 if (descriptors[i].dtrace_cookie) {
3562 proc_lock(p);
3563 *descriptors[i].dtrace_cookie = ptr_area + ((uintptr_t)ptr_buffer - (uintptr_t)ptr_buffer_start); /* dtrace convenience */
3564 proc_unlock(p);
3565 }
2d21ac55 3566#endif /* CONFIG_DTRACE */
91447636 3567
6d2010ae
A
3568 /*
3569 * For each segment (argv, envv, applev), copy as many pointers as requested
3570 * to our pointer buffer.
3571 */
3572 for (j = 0; j < descriptors[i].count; j++) {
3573 user_addr_t cur_address = string_area + (cur_string - imgp->ip_strings);
3574
3575 /* Copy out the pointer to the current string. Alignment has been verified */
3576 if (ptr_size == 8) {
3577 *(uint64_t *)ptr_buffer = (uint64_t)cur_address;
3578 } else {
3579 *(uint32_t *)ptr_buffer = (uint32_t)cur_address;
3580 }
3581
3582 ptr_buffer = (void *)((uintptr_t)ptr_buffer + ptr_size);
3583 cur_string += strlen(cur_string) + 1; /* Only a NUL between strings in the same area */
91447636 3584 }
91447636 3585
6d2010ae
A
3586 if (descriptors[i].null_term) {
3587 if (ptr_size == 8) {
3588 *(uint64_t *)ptr_buffer = 0ULL;
3589 } else {
3590 *(uint32_t *)ptr_buffer = 0;
91447636 3591 }
6d2010ae
A
3592
3593 ptr_buffer = (void *)((uintptr_t)ptr_buffer + ptr_size);
3594 }
3595 }
3596
3597 /*
3598 * Copy out all our pointer arrays in bulk.
3599 */
3600 error = copyout(ptr_buffer_start, ptr_area,
3601 ptr_area_size);
3602 if (error)
3603 goto bad;
3604
3605 /* argc (int32, stored in a ptr_size area) */
3606 error = copyoutptr((user_addr_t)imgp->ip_argc, argc_area, ptr_size);
3607 if (error)
3608 goto bad;
91447636
A
3609
3610bad:
3611 return(error);
3612}
3613
3614
3615/*
3616 * exec_extract_strings
3617 *
3618 * Copy arguments and environment from user space into work area; we may
3619 * have already copied some early arguments into the work area, and if
3620 * so, any arguments opied in are appended to those already there.
6d2010ae
A
3621 * This function is the primary manipulator of ip_argspace, since
3622 * these are the arguments the client of execve(2) knows about. After
3623 * each argv[]/envv[] string is copied, we charge the string length
3624 * and argv[]/envv[] pointer slot to ip_argspace, so that we can
3625 * full preflight the arg list size.
91447636
A
3626 *
3627 * Parameters: struct image_params * the image parameter block
3628 *
3629 * Returns: 0 Success
3630 * !0 Failure: errno
3631 *
3632 * Implicit returns;
3633 * (imgp->ip_argc) Count of arguments, updated
3634 * (imgp->ip_envc) Count of environment strings, updated
6d2010ae
A
3635 * (imgp->ip_argspace) Count of remaining of NCARGS
3636 * (imgp->ip_interp_buffer) Interpreter and args (mutated in place)
91447636
A
3637 *
3638 *
2d21ac55 3639 * Note: The argument and environment vectors are user space pointers
91447636
A
3640 * to arrays of user space pointers.
3641 */
3642static int
3643exec_extract_strings(struct image_params *imgp)
3644{
3645 int error = 0;
91447636 3646 int ptr_size = (imgp->ip_flags & IMGPF_WAS_64BIT) ? 8 : 4;
6d2010ae 3647 int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
91447636
A
3648 user_addr_t argv = imgp->ip_user_argv;
3649 user_addr_t envv = imgp->ip_user_envv;
3650
b0d623f7
A
3651 /*
3652 * Adjust space reserved for the path name by however much padding it
3653 * needs. Doing this here since we didn't know if this would be a 32-
3654 * or 64-bit process back in exec_save_path.
3655 */
6d2010ae
A
3656 while (imgp->ip_strspace % new_ptr_size != 0) {
3657 *imgp->ip_strendp++ = '\0';
3658 imgp->ip_strspace--;
3659 /* imgp->ip_argspace--; not counted towards exec args total */
3660 }
b0d623f7 3661
1c79356b 3662 /*
6d2010ae 3663 * From now on, we start attributing string space to ip_argspace
1c79356b 3664 */
6d2010ae
A
3665 imgp->ip_startargv = imgp->ip_strendp;
3666 imgp->ip_argc = 0;
3667
3668 if((imgp->ip_flags & IMGPF_INTERPRET) != 0) {
91447636 3669 user_addr_t arg;
6d2010ae
A
3670 char *argstart, *ch;
3671
3672 /* First, the arguments in the "#!" string are tokenized and extracted. */
3673 argstart = imgp->ip_interp_buffer;
3674 while (argstart) {
3675 ch = argstart;
3676 while (*ch && !IS_WHITESPACE(*ch)) {
3677 ch++;
3678 }
91447636 3679
6d2010ae
A
3680 if (*ch == '\0') {
3681 /* last argument, no need to NUL-terminate */
3682 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(argstart), UIO_SYSSPACE, TRUE);
3683 argstart = NULL;
3684 } else {
3685 /* NUL-terminate */
3686 *ch = '\0';
3687 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(argstart), UIO_SYSSPACE, TRUE);
3688
3689 /*
3690 * Find the next string. We know spaces at the end of the string have already
3691 * been stripped.
3692 */
3693 argstart = ch + 1;
3694 while (IS_WHITESPACE(*argstart)) {
3695 argstart++;
3696 }
3697 }
3698
3699 /* Error-check, regardless of whether this is the last interpreter arg or not */
91447636
A
3700 if (error)
3701 goto bad;
6d2010ae
A
3702 if (imgp->ip_argspace < new_ptr_size) {
3703 error = E2BIG;
3704 goto bad;
3705 }
3706 imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
91447636 3707 imgp->ip_argc++;
1c79356b 3708 }
6d2010ae
A
3709
3710 if (argv != 0LL) {
3711 /*
3712 * If we are running an interpreter, replace the av[0] that was
3713 * passed to execve() with the path name that was
3714 * passed to execve() for interpreters which do not use the PATH
3715 * to locate their script arguments.
3716 */
3717 error = copyinptr(argv, &arg, ptr_size);
3718 if (error)
3719 goto bad;
3720 if (arg != 0LL) {
3721 argv += ptr_size; /* consume without using */
3722 }
3723 }
3724
3725 if (imgp->ip_interp_sugid_fd != -1) {
3726 char temp[19]; /* "/dev/fd/" + 10 digits + NUL */
3727 snprintf(temp, sizeof(temp), "/dev/fd/%d", imgp->ip_interp_sugid_fd);
3728 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(temp), UIO_SYSSPACE, TRUE);
3729 } else {
3730 error = exec_add_user_string(imgp, imgp->ip_user_fname, imgp->ip_seg, TRUE);
3731 }
3732
3733 if (error)
3734 goto bad;
3735 if (imgp->ip_argspace < new_ptr_size) {
3736 error = E2BIG;
3737 goto bad;
3738 }
3739 imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
3740 imgp->ip_argc++;
91447636 3741 }
1c79356b 3742
91447636
A
3743 while (argv != 0LL) {
3744 user_addr_t arg;
3745
3746 error = copyinptr(argv, &arg, ptr_size);
3747 if (error)
1c79356b 3748 goto bad;
1c79356b 3749
91447636
A
3750 if (arg == 0LL) {
3751 break;
1c79356b 3752 }
6d2010ae
A
3753
3754 argv += ptr_size;
3755
91447636
A
3756 /*
3757 * av[n...] = arg[n]
3758 */
6d2010ae 3759 error = exec_add_user_string(imgp, arg, imgp->ip_seg, TRUE);
91447636
A
3760 if (error)
3761 goto bad;
6d2010ae
A
3762 if (imgp->ip_argspace < new_ptr_size) {
3763 error = E2BIG;
3764 goto bad;
3765 }
3766 imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
91447636
A
3767 imgp->ip_argc++;
3768 }
6d2010ae
A
3769
3770 /* Save space for argv[] NULL terminator */
3771 if (imgp->ip_argspace < new_ptr_size) {
3772 error = E2BIG;
3773 goto bad;
3774 }
3775 imgp->ip_argspace -= new_ptr_size;
b0d623f7 3776
6d2010ae
A
3777 /* Note where the args ends and env begins. */
3778 imgp->ip_endargv = imgp->ip_strendp;
3779 imgp->ip_envc = 0;
91447636
A
3780
3781 /* Now, get the environment */
3782 while (envv != 0LL) {
3783 user_addr_t env;
3784
3785 error = copyinptr(envv, &env, ptr_size);
3786 if (error)
3787 goto bad;
1c79356b 3788
91447636
A
3789 envv += ptr_size;
3790 if (env == 0LL) {
3791 break;
1c79356b 3792 }
1c79356b 3793 /*
91447636
A
3794 * av[n...] = env[n]
3795 */
6d2010ae 3796 error = exec_add_user_string(imgp, env, imgp->ip_seg, TRUE);
91447636 3797 if (error)
55e303ae 3798 goto bad;
6d2010ae
A
3799 if (imgp->ip_argspace < new_ptr_size) {
3800 error = E2BIG;
3801 goto bad;
3802 }
3803 imgp->ip_argspace -= new_ptr_size; /* to hold envv[] entry */
91447636 3804 imgp->ip_envc++;
55e303ae 3805 }
6d2010ae
A
3806
3807 /* Save space for envv[] NULL terminator */
3808 if (imgp->ip_argspace < new_ptr_size) {
3809 error = E2BIG;
3810 goto bad;
3811 }
3812 imgp->ip_argspace -= new_ptr_size;
3813
3814 /* Align the tail of the combined argv+envv area */
3815 while (imgp->ip_strspace % new_ptr_size != 0) {
3816 if (imgp->ip_argspace < 1) {
3817 error = E2BIG;
3818 goto bad;
3819 }
3820 *imgp->ip_strendp++ = '\0';
3821 imgp->ip_strspace--;
3822 imgp->ip_argspace--;
3823 }
3824
3825 /* Note where the envv ends and applev begins. */
3826 imgp->ip_endenvv = imgp->ip_strendp;
3827
3828 /*
3829 * From now on, we are no longer charging argument
3830 * space to ip_argspace.
3831 */
3832
91447636
A
3833bad:
3834 return error;
3835}
55e303ae 3836
6d2010ae
A
3837/*
3838 * Libc has an 8-element array set up for stack guard values. It only fills
3839 * in one of those entries, and both gcc and llvm seem to use only a single
3840 * 8-byte guard. Until somebody needs more than an 8-byte guard value, don't
3841 * do the work to construct them.
3842 */
3843#define GUARD_VALUES 1
3844#define GUARD_KEY "stack_guard="
3845
3846/*
3847 * System malloc needs some entropy when it is initialized.
3848 */
3849#define ENTROPY_VALUES 2
3850#define ENTROPY_KEY "malloc_entropy="
3851
39236c6e
A
3852/*
3853 * System malloc engages nanozone for UIAPP.
3854 */
3855#define NANO_ENGAGE_KEY "MallocNanoZone=1"
3856
316670eb
A
3857#define PFZ_KEY "pfz="
3858extern user32_addr_t commpage_text32_location;
3859extern user64_addr_t commpage_text64_location;
39037602
A
3860
3861#define MAIN_STACK_VALUES 4
3862#define MAIN_STACK_KEY "main_stack="
3863
3864#define HEX_STR_LEN 18 // 64-bit hex value "0x0123456701234567"
3865
6d2010ae 3866static int
39037602
A
3867exec_add_entropy_key(struct image_params *imgp,
3868 const char *key,
3869 int values,
3870 boolean_t embedNUL)
6d2010ae 3871{
39037602
A
3872 const int limit = 8;
3873 uint64_t entropy[limit];
3874 char str[strlen(key) + (HEX_STR_LEN + 1) * limit + 1];
3875 if (values > limit) {
3876 values = limit;
3877 }
6d2010ae 3878
39037602 3879 read_random(entropy, sizeof(entropy[0]) * values);
6d2010ae 3880
39037602
A
3881 if (embedNUL) {
3882 entropy[0] &= ~(0xffull << 8);
3883 }
3884
3885 int len = snprintf(str, sizeof(str), "%s0x%llx", key, entropy[0]);
3886 int remaining = sizeof(str) - len;
3887 for (int i = 1; i < values && remaining > 0; ++i) {
3888 int start = sizeof(str) - remaining;
3889 len = snprintf(&str[start], remaining, ",0x%llx", entropy[i]);
3890 remaining -= len;
316670eb
A
3891 }
3892
39037602
A
3893 return exec_add_user_string(imgp, CAST_USER_ADDR_T(str), UIO_SYSSPACE, FALSE);
3894}
3895
3896/*
3897 * Build up the contents of the apple[] string vector
3898 */
3899static int
3900exec_add_apple_strings(struct image_params *imgp,
3901 const load_result_t *load_result)
3902{
3903 int error;
3904 int img_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
3905
6d2010ae
A
3906 /* exec_save_path stored the first string */
3907 imgp->ip_applec = 1;
3908
316670eb 3909 /* adding the pfz string */
39037602
A
3910 {
3911 char pfz_string[strlen(PFZ_KEY) + HEX_STR_LEN + 1];
3912
3913 if (img_ptr_size == 8) {
3914 snprintf(pfz_string, sizeof(pfz_string), PFZ_KEY "0x%llx", commpage_text64_location);
3915 } else {
3916 snprintf(pfz_string, sizeof(pfz_string), PFZ_KEY "0x%x", commpage_text32_location);
3917 }
3918 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(pfz_string), UIO_SYSSPACE, FALSE);
3919 if (error) {
3920 goto bad;
3921 }
3922 imgp->ip_applec++;
3923 }
316670eb 3924
39236c6e
A
3925 /* adding the NANO_ENGAGE_KEY key */
3926 if (imgp->ip_px_sa) {
fe8ab488 3927 int proc_flags = (((struct _posix_spawnattr *) imgp->ip_px_sa)->psa_flags);
39236c6e 3928
fe8ab488 3929 if ((proc_flags & _POSIX_SPAWN_NANO_ALLOCATOR) == _POSIX_SPAWN_NANO_ALLOCATOR) {
39037602
A
3930 const char *nano_string = NANO_ENGAGE_KEY;
3931 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(nano_string), UIO_SYSSPACE, FALSE);
3932 if (error){
fe8ab488 3933 goto bad;
39037602 3934 }
fe8ab488
A
3935 imgp->ip_applec++;
3936 }
39236c6e
A
3937 }
3938
6d2010ae
A
3939 /*
3940 * Supply libc with a collection of random values to use when
3941 * implementing -fstack-protector.
39236c6e
A
3942 *
3943 * (The first random string always contains an embedded NUL so that
3944 * __stack_chk_guard also protects against C string vulnerabilities)
6d2010ae 3945 */
39037602
A
3946 error = exec_add_entropy_key(imgp, GUARD_KEY, GUARD_VALUES, TRUE);
3947 if (error) {
6d2010ae 3948 goto bad;
39037602 3949 }
6d2010ae
A
3950 imgp->ip_applec++;
3951
3952 /*
3953 * Supply libc with entropy for system malloc.
3954 */
39037602
A
3955 error = exec_add_entropy_key(imgp, ENTROPY_KEY, ENTROPY_VALUES, FALSE);
3956 if (error) {
6d2010ae 3957 goto bad;
39037602 3958 }
6d2010ae
A
3959 imgp->ip_applec++;
3960
39037602
A
3961 /*
3962 * Add MAIN_STACK_KEY: Supplies the address and size of the main thread's
3963 * stack if it was allocated by the kernel.
3964 *
3965 * The guard page is not included in this stack size as libpthread
3966 * expects to add it back in after receiving this value.
3967 */
3968 if (load_result->unixproc) {
3969 char stack_string[strlen(MAIN_STACK_KEY) + (HEX_STR_LEN + 1) * MAIN_STACK_VALUES + 1];
3970 snprintf(stack_string, sizeof(stack_string),
3971 MAIN_STACK_KEY "0x%llx,0x%llx,0x%llx,0x%llx",
3972 (uint64_t)load_result->user_stack,
3973 (uint64_t)load_result->user_stack_size,
3974 (uint64_t)load_result->user_stack_alloc,
3975 (uint64_t)load_result->user_stack_alloc_size);
3976 error = exec_add_user_string(imgp, CAST_USER_ADDR_T(stack_string), UIO_SYSSPACE, FALSE);
3977 if (error) {
3978 goto bad;
3979 }
3980 imgp->ip_applec++;
3981 }
3982
6d2010ae 3983 /* Align the tail of the combined applev area */
39037602 3984 while (imgp->ip_strspace % img_ptr_size != 0) {
6d2010ae
A
3985 *imgp->ip_strendp++ = '\0';
3986 imgp->ip_strspace--;
3987 }
3988
3989bad:
3990 return error;
3991}
55e303ae 3992
91447636 3993#define unix_stack_size(p) (p->p_rlimit[RLIMIT_STACK].rlim_cur)
55e303ae 3994
2d21ac55
A
3995/*
3996 * exec_check_permissions
3997 *
6d2010ae 3998 * Description: Verify that the file that is being attempted to be executed
2d21ac55
A
3999 * is in fact allowed to be executed based on it POSIX file
4000 * permissions and other access control criteria
4001 *
4002 * Parameters: struct image_params * the image parameter block
4003 *
4004 * Returns: 0 Success
4005 * EACCES Permission denied
4006 * ENOEXEC Executable file format error
4007 * ETXTBSY Text file busy [misuse of error code]
4008 * vnode_getattr:???
4009 * vnode_authorize:???
4010 */
91447636
A
4011static int
4012exec_check_permissions(struct image_params *imgp)
4013{
4014 struct vnode *vp = imgp->ip_vp;
4015 struct vnode_attr *vap = imgp->ip_vattr;
2d21ac55 4016 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
91447636
A
4017 int error;
4018 kauth_action_t action;
55e303ae 4019
91447636
A
4020 /* Only allow execution of regular files */
4021 if (!vnode_isreg(vp))
4022 return (EACCES);
4023
4024 /* Get the file attributes that we will be using here and elsewhere */
4025 VATTR_INIT(vap);
4026 VATTR_WANTED(vap, va_uid);
4027 VATTR_WANTED(vap, va_gid);
4028 VATTR_WANTED(vap, va_mode);
4029 VATTR_WANTED(vap, va_fsid);
4030 VATTR_WANTED(vap, va_fileid);
4031 VATTR_WANTED(vap, va_data_size);
4032 if ((error = vnode_getattr(vp, vap, imgp->ip_vfs_context)) != 0)
4033 return (error);
55e303ae 4034
91447636
A
4035 /*
4036 * Ensure that at least one execute bit is on - otherwise root
4037 * will always succeed, and we don't want to happen unless the
4038 * file really is executable.
4039 */
6d2010ae 4040 if (!vfs_authopaque(vnode_mount(vp)) && ((vap->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0))
91447636 4041 return (EACCES);
55e303ae 4042
91447636
A
4043 /* Disallow zero length files */
4044 if (vap->va_data_size == 0)
4045 return (ENOEXEC);
55e303ae 4046
91447636
A
4047 imgp->ip_arch_offset = (user_size_t)0;
4048 imgp->ip_arch_size = vap->va_data_size;
0b4e3aa0 4049
91447636 4050 /* Disable setuid-ness for traced programs or if MNT_NOSUID */
b0d623f7 4051 if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_lflag & P_LTRACED))
91447636 4052 vap->va_mode &= ~(VSUID | VSGID);
2d21ac55 4053
39236c6e
A
4054 /*
4055 * Disable _POSIX_SPAWN_ALLOW_DATA_EXEC and _POSIX_SPAWN_DISABLE_ASLR
4056 * flags for setuid/setgid binaries.
4057 */
4058 if (vap->va_mode & (VSUID | VSGID))
4059 imgp->ip_flags &= ~(IMGPF_ALLOW_DATA_EXEC | IMGPF_DISABLE_ASLR);
4060
2d21ac55
A
4061#if CONFIG_MACF
4062 error = mac_vnode_check_exec(imgp->ip_vfs_context, vp, imgp);
4063 if (error)
4064 return (error);
4065#endif
91447636
A
4066
4067 /* Check for execute permission */
4068 action = KAUTH_VNODE_EXECUTE;
4069 /* Traced images must also be readable */
2d21ac55 4070 if (p->p_lflag & P_LTRACED)
91447636
A
4071 action |= KAUTH_VNODE_READ_DATA;
4072 if ((error = vnode_authorize(vp, NULL, action, imgp->ip_vfs_context)) != 0)
4073 return (error);
1c79356b 4074
2d21ac55 4075#if 0
91447636 4076 /* Don't let it run if anyone had it open for writing */
2d21ac55
A
4077 vnode_lock(vp);
4078 if (vp->v_writecount) {
4079 panic("going to return ETXTBSY %x", vp);
4080 vnode_unlock(vp);
91447636 4081 return (ETXTBSY);
2d21ac55
A
4082 }
4083 vnode_unlock(vp);
4084#endif
4085
de355530 4086
91447636 4087 /* XXX May want to indicate to underlying FS that vnode is open */
1c79356b 4088
91447636
A
4089 return (error);
4090}
4091
2d21ac55 4092
91447636
A
4093/*
4094 * exec_handle_sugid
4095 *
4096 * Initially clear the P_SUGID in the process flags; if an SUGID process is
4097 * exec'ing a non-SUGID image, then this is the point of no return.
4098 *
2d21ac55 4099 * If the image being activated is SUGID, then replace the credential with a
91447636
A
4100 * copy, disable tracing (unless the tracing process is root), reset the
4101 * mach task port to revoke it, set the P_SUGID bit,
4102 *
4103 * If the saved user and group ID will be changing, then make sure it happens
4104 * to a new credential, rather than a shared one.
4105 *
4106 * Set the security token (this is probably obsolete, given that the token
4107 * should not technically be separate from the credential itself).
4108 *
4109 * Parameters: struct image_params * the image parameter block
4110 *
4111 * Returns: void No failure indication
4112 *
4113 * Implicit returns:
4114 * <process credential> Potentially modified/replaced
4115 * <task port> Potentially revoked
4116 * <process flags> P_SUGID bit potentially modified
4117 * <security token> Potentially modified
4118 */
4119static int
4120exec_handle_sugid(struct image_params *imgp)
4121{
2d21ac55 4122 proc_t p = vfs_context_proc(imgp->ip_vfs_context);
39037602
A
4123 kauth_cred_t cred = vfs_context_ucred(imgp->ip_vfs_context);
4124 kauth_cred_t my_cred, my_new_cred;
91447636 4125 int i;
c910b4d9 4126 int leave_sugid_clear = 0;
fe8ab488 4127 int mac_reset_ipc = 0;
91447636 4128 int error = 0;
2d21ac55 4129#if CONFIG_MACF
fe8ab488
A
4130 int mac_transition, disjoint_cred = 0;
4131 int label_update_return = 0;
c910b4d9
A
4132
4133 /*
4134 * Determine whether a call to update the MAC label will result in the
4135 * credential changing.
4136 *
4137 * Note: MAC policies which do not actually end up modifying
4138 * the label subsequently are strongly encouraged to
4139 * return 0 for this check, since a non-zero answer will
4140 * slow down the exec fast path for normal binaries.
4141 */
4142 mac_transition = mac_cred_check_label_update_execve(
4143 imgp->ip_vfs_context,
4144 imgp->ip_vp,
fe8ab488 4145 imgp->ip_arch_offset,
39236c6e 4146 imgp->ip_scriptvp,
c910b4d9 4147 imgp->ip_scriptlabelp,
39236c6e
A
4148 imgp->ip_execlabelp,
4149 p,
4150 imgp->ip_px_smpx);
2d21ac55 4151#endif
1c79356b 4152
b0d623f7 4153 OSBitAndAtomic(~((uint32_t)P_SUGID), &p->p_flag);
91447636 4154
2d21ac55
A
4155 /*
4156 * Order of the following is important; group checks must go last,
c910b4d9 4157 * as we use the success of the 'ismember' check combined with the
2d21ac55
A
4158 * failure of the explicit match to indicate that we will be setting
4159 * the egid of the process even though the new process did not
4160 * require VSUID/VSGID bits in order for it to set the new group as
4161 * its egid.
4162 *
4163 * Note: Technically, by this we are implying a call to
4164 * setegid() in the new process, rather than implying
4165 * it used its VSGID bit to set the effective group,
4166 * even though there is no code in that process to make
4167 * such a call.
4168 */
91447636
A
4169 if (((imgp->ip_origvattr->va_mode & VSUID) != 0 &&
4170 kauth_cred_getuid(cred) != imgp->ip_origvattr->va_uid) ||
4171 ((imgp->ip_origvattr->va_mode & VSGID) != 0 &&
c910b4d9 4172 ((kauth_cred_ismember_gid(cred, imgp->ip_origvattr->va_gid, &leave_sugid_clear) || !leave_sugid_clear) ||
6d2010ae 4173 (kauth_cred_getgid(cred) != imgp->ip_origvattr->va_gid)))) {
2d21ac55 4174
c910b4d9
A
4175#if CONFIG_MACF
4176/* label for MAC transition and neither VSUID nor VSGID */
4177handle_mac_transition:
4178#endif
4179
1c79356b 4180 /*
2d21ac55
A
4181 * Replace the credential with a copy of itself if euid or
4182 * egid change.
4183 *
4184 * Note: setuid binaries will automatically opt out of
4185 * group resolver participation as a side effect
4186 * of this operation. This is an intentional
4187 * part of the security model, which requires a
4188 * participating credential be established by
4189 * escalating privilege, setting up all other
4190 * aspects of the credential including whether
4191 * or not to participate in external group
4192 * membership resolution, then dropping their
4193 * effective privilege to that of the desired
4194 * final credential state.
39037602
A
4195 *
4196 * Modifications to p_ucred must be guarded using the
4197 * proc's ucred lock. This prevents others from accessing
4198 * a garbage credential.
91447636 4199 */
39037602
A
4200 while (imgp->ip_origvattr->va_mode & VSUID) {
4201 my_cred = kauth_cred_proc_ref(p);
4202 my_new_cred = kauth_cred_setresuid(my_cred, KAUTH_UID_NONE, imgp->ip_origvattr->va_uid, imgp->ip_origvattr->va_uid, KAUTH_UID_NONE);
4203
4204 if (my_new_cred == my_cred) {
4205 kauth_cred_unref(&my_cred);
4206 break;
4207 }
4208
6d2010ae 4209 /* update cred on proc */
39037602
A
4210 proc_ucred_lock(p);
4211
4212 if (p->p_ucred != my_cred) {
4213 proc_ucred_unlock(p);
4214 kauth_cred_unref(&my_new_cred);
4215 continue;
4216 }
4217
4218 /* donate cred reference on my_new_cred to p->p_ucred */
4219 p->p_ucred = my_new_cred;
6d2010ae 4220 PROC_UPDATE_CREDS_ONPROC(p);
39037602
A
4221 proc_ucred_unlock(p);
4222
4223 /* drop additional reference that was taken on the previous cred */
4224 kauth_cred_unref(&my_cred);
4225
4226 break;
91447636 4227 }
39037602
A
4228
4229 while (imgp->ip_origvattr->va_mode & VSGID) {
4230 my_cred = kauth_cred_proc_ref(p);
4231 my_new_cred = kauth_cred_setresgid(my_cred, KAUTH_GID_NONE, imgp->ip_origvattr->va_gid, imgp->ip_origvattr->va_gid);
4232
4233 if (my_new_cred == my_cred) {
4234 kauth_cred_unref(&my_cred);
4235 break;
4236 }
4237
6d2010ae 4238 /* update cred on proc */
39037602
A
4239 proc_ucred_lock(p);
4240
4241 if (p->p_ucred != my_cred) {
4242 proc_ucred_unlock(p);
4243 kauth_cred_unref(&my_new_cred);
4244 continue;
4245 }
4246
4247 /* donate cred reference on my_new_cred to p->p_ucred */
4248 p->p_ucred = my_new_cred;
6d2010ae 4249 PROC_UPDATE_CREDS_ONPROC(p);
39037602
A
4250 proc_ucred_unlock(p);
4251
4252 /* drop additional reference that was taken on the previous cred */
4253 kauth_cred_unref(&my_cred);
4254
4255 break;
91447636 4256 }
1c79356b 4257
2d21ac55
A
4258#if CONFIG_MACF
4259 /*
c910b4d9
A
4260 * If a policy has indicated that it will transition the label,
4261 * before making the call into the MAC policies, get a new
2d21ac55
A
4262 * duplicate credential, so they can modify it without
4263 * modifying any others sharing it.
4264 */
c910b4d9 4265 if (mac_transition) {
490019cf
A
4266 /*
4267 * This hook may generate upcalls that require
4268 * importance donation from the kernel.
4269 * (23925818)
4270 */
4271 thread_t thread = current_thread();
4272 thread_enable_send_importance(thread, TRUE);
fe8ab488 4273 kauth_proc_label_update_execve(p,
c910b4d9
A
4274 imgp->ip_vfs_context,
4275 imgp->ip_vp,
fe8ab488 4276 imgp->ip_arch_offset,
39236c6e 4277 imgp->ip_scriptvp,
c910b4d9 4278 imgp->ip_scriptlabelp,
39236c6e 4279 imgp->ip_execlabelp,
fe8ab488
A
4280 &imgp->ip_csflags,
4281 imgp->ip_px_smpx,
4282 &disjoint_cred, /* will be non zero if disjoint */
4283 &label_update_return);
490019cf 4284 thread_enable_send_importance(thread, FALSE);
fe8ab488
A
4285
4286 if (disjoint_cred) {
c910b4d9
A
4287 /*
4288 * If updating the MAC label resulted in a
4289 * disjoint credential, flag that we need to
4290 * set the P_SUGID bit. This protects
4291 * against debuggers being attached by an
4292 * insufficiently privileged process onto the
4293 * result of a transition to a more privileged
4294 * credential.
4295 */
4296 leave_sugid_clear = 0;
4297 }
fe8ab488
A
4298
4299 imgp->ip_mac_return = label_update_return;
2d21ac55 4300 }
fe8ab488
A
4301
4302 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);
4303
c910b4d9
A
4304#endif /* CONFIG_MACF */
4305
2d21ac55 4306 /*
c910b4d9
A
4307 * If 'leave_sugid_clear' is non-zero, then we passed the
4308 * VSUID and MACF checks, and successfully determined that
4309 * the previous cred was a member of the VSGID group, but
4310 * that it was not the default at the time of the execve,
4311 * and that the post-labelling credential was not disjoint.
39236c6e
A
4312 * So we don't set the P_SUGID or reset mach ports and fds
4313 * on the basis of simply running this code.
1c79356b 4314 */
fe8ab488 4315 if (mac_reset_ipc || !leave_sugid_clear) {
39236c6e 4316 /*
fe8ab488
A
4317 * Have mach reset the task and thread ports.
4318 * We don't want anyone who had the ports before
4319 * a setuid exec to be able to access/control the
4320 * task/thread after.
4321 */
39236c6e
A
4322 ipc_task_reset(p->task);
4323 ipc_thread_reset((imgp->ip_new_thread != NULL) ?
4324 imgp->ip_new_thread : current_thread());
fe8ab488 4325 }
91447636 4326
fe8ab488 4327 if (!leave_sugid_clear) {
39236c6e
A
4328 /*
4329 * Flag the process as setuid.
4330 */
4331 OSBitOrAtomic(P_SUGID, &p->p_flag);
1c79356b 4332
ebb1b9f4 4333 /*
39236c6e
A
4334 * Radar 2261856; setuid security hole fix
4335 * XXX For setuid processes, attempt to ensure that
4336 * stdin, stdout, and stderr are already allocated.
4337 * We do not want userland to accidentally allocate
4338 * descriptors in this range which has implied meaning
4339 * to libc.
ebb1b9f4 4340 */
39236c6e
A
4341 for (i = 0; i < 3; i++) {
4342
4343 if (p->p_fd->fd_ofiles[i] != NULL)
4344 continue;
4345
4346 /*
4347 * Do the kernel equivalent of
4348 *
4349 * if i == 0
4350 * (void) open("/dev/null", O_RDONLY);
4351 * else
4352 * (void) open("/dev/null", O_WRONLY);
4353 */
91447636 4354
39236c6e
A
4355 struct fileproc *fp;
4356 int indx;
4357 int flag;
fe8ab488 4358 struct nameidata *ndp = NULL;
1c79356b 4359
39236c6e
A
4360 if (i == 0)
4361 flag = FREAD;
4362 else
4363 flag = FWRITE;
ebb1b9f4 4364
39236c6e
A
4365 if ((error = falloc(p,
4366 &fp, &indx, imgp->ip_vfs_context)) != 0)
4367 continue;
ebb1b9f4 4368
fe8ab488
A
4369 MALLOC(ndp, struct nameidata *, sizeof(*ndp), M_TEMP, M_WAITOK | M_ZERO);
4370 if (ndp == NULL) {
39037602 4371 fp_free(p, indx, fp);
fe8ab488
A
4372 error = ENOMEM;
4373 break;
4374 }
ebb1b9f4 4375
fe8ab488 4376 NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW, UIO_SYSSPACE,
39236c6e
A
4377 CAST_USER_ADDR_T("/dev/null"),
4378 imgp->ip_vfs_context);
ebb1b9f4 4379
fe8ab488 4380 if ((error = vn_open(ndp, flag, 0)) != 0) {
39236c6e 4381 fp_free(p, indx, fp);
39037602 4382 FREE(ndp, M_TEMP);
39236c6e
A
4383 break;
4384 }
ebb1b9f4 4385
39236c6e 4386 struct fileglob *fg = fp->f_fglob;
ebb1b9f4 4387
39236c6e
A
4388 fg->fg_flag = flag;
4389 fg->fg_ops = &vnops;
fe8ab488 4390 fg->fg_data = ndp->ni_vp;
ebb1b9f4 4391
fe8ab488 4392 vnode_put(ndp->ni_vp);
39236c6e
A
4393
4394 proc_fdlock(p);
4395 procfdtbl_releasefd(p, indx, NULL);
4396 fp_drop(p, indx, fp, 1);
4397 proc_fdunlock(p);
fe8ab488
A
4398
4399 FREE(ndp, M_TEMP);
39236c6e 4400 }
1c79356b 4401 }
1c79356b 4402 }
c910b4d9
A
4403#if CONFIG_MACF
4404 else {
4405 /*
4406 * We are here because we were told that the MAC label will
4407 * be transitioned, and the binary is not VSUID or VSGID; to
4408 * deal with this case, we could either duplicate a lot of
4409 * code, or we can indicate we want to default the P_SUGID
4410 * bit clear and jump back up.
4411 */
4412 if (mac_transition) {
4413 leave_sugid_clear = 1;
4414 goto handle_mac_transition;
4415 }
4416 }
fe8ab488 4417
c910b4d9 4418#endif /* CONFIG_MACF */
1c79356b
A
4419
4420 /*
91447636
A
4421 * Implement the semantic where the effective user and group become
4422 * the saved user and group in exec'ed programs.
39037602
A
4423 *
4424 * Modifications to p_ucred must be guarded using the
4425 * proc's ucred lock. This prevents others from accessing
4426 * a garbage credential.
1c79356b 4427 */
39037602
A
4428 for (;;) {
4429 my_cred = kauth_cred_proc_ref(p);
4430 my_new_cred = kauth_cred_setsvuidgid(my_cred, kauth_cred_getuid(my_cred), kauth_cred_getgid(my_cred));
4431
4432 if (my_new_cred == my_cred) {
4433 kauth_cred_unref(&my_cred);
4434 break;
4435 }
4436
4437 /* update cred on proc */
4438 proc_ucred_lock(p);
4439
4440 if (p->p_ucred != my_cred) {
4441 proc_ucred_unlock(p);
4442 kauth_cred_unref(&my_new_cred);
4443 continue;
4444 }
4445
4446 /* donate cred reference on my_new_cred to p->p_ucred */
4447 p->p_ucred = my_new_cred;
4448 PROC_UPDATE_CREDS_ONPROC(p);
4449 proc_ucred_unlock(p);
4450
4451 /* drop additional reference that was taken on the previous cred */
4452 kauth_cred_unref(&my_cred);
4453
4454 break;
4455 }
4456
4457
593a1d5f
A
4458 /* Update the process' identity version and set the security token */
4459 p->p_idversion++;
91447636 4460 set_security_token(p);
0b4e3aa0 4461
1c79356b
A
4462 return(error);
4463}
4464
2d21ac55
A
4465
4466/*
4467 * create_unix_stack
4468 *
4469 * Description: Set the user stack address for the process to the provided
4470 * address. If a custom stack was not set as a result of the
4471 * load process (i.e. as specified by the image file for the
4472 * executable), then allocate the stack in the provided map and
4473 * set up appropriate guard pages for enforcing administrative
4474 * limits on stack growth, if they end up being needed.
4475 *
4476 * Parameters: p Process to set stack on
316670eb
A
4477 * load_result Information from mach-o load commands
4478 * map Address map in which to allocate the new stack
2d21ac55
A
4479 *
4480 * Returns: KERN_SUCCESS Stack successfully created
4481 * !KERN_SUCCESS Mach failure code
4482 */
91447636 4483static kern_return_t
316670eb 4484create_unix_stack(vm_map_t map, load_result_t* load_result,
2d21ac55 4485 proc_t p)
1c79356b 4486{
2d21ac55
A
4487 mach_vm_size_t size, prot_size;
4488 mach_vm_offset_t addr, prot_addr;
4489 kern_return_t kr;
1c79356b 4490
316670eb
A
4491 mach_vm_address_t user_stack = load_result->user_stack;
4492
2d21ac55 4493 proc_lock(p);
91447636 4494 p->user_stack = user_stack;
2d21ac55
A
4495 proc_unlock(p);
4496
39037602 4497 if (load_result->user_stack_alloc_size > 0) {
2d21ac55
A
4498 /*
4499 * Allocate enough space for the maximum stack size we
4500 * will ever authorize and an extra page to act as
316670eb
A
4501 * a guard page for stack overflows. For default stacks,
4502 * vm_initial_limit_stack takes care of the extra guard page.
4503 * Otherwise we must allocate it ourselves.
2d21ac55 4504 */
39037602
A
4505 if (mach_vm_round_page_overflow(load_result->user_stack_alloc_size, &size)) {
4506 return KERN_INVALID_ARGUMENT;
4507 }
316670eb 4508 addr = mach_vm_trunc_page(load_result->user_stack - size);
2d21ac55 4509 kr = mach_vm_allocate(map, &addr, size,
39037602
A
4510 VM_MAKE_TAG(VM_MEMORY_STACK) |
4511 VM_FLAGS_FIXED);
2d21ac55 4512 if (kr != KERN_SUCCESS) {
39037602 4513 // Can't allocate at default location, try anywhere
316670eb
A
4514 addr = 0;
4515 kr = mach_vm_allocate(map, &addr, size,
39037602
A
4516 VM_MAKE_TAG(VM_MEMORY_STACK) |
4517 VM_FLAGS_ANYWHERE);
4518 if (kr != KERN_SUCCESS) {
316670eb 4519 return kr;
39037602 4520 }
316670eb
A
4521
4522 user_stack = addr + size;
4523 load_result->user_stack = user_stack;
4524
4525 proc_lock(p);
4526 p->user_stack = user_stack;
4527 proc_unlock(p);
2d21ac55 4528 }
316670eb 4529
39037602
A
4530 load_result->user_stack_alloc = addr;
4531
2d21ac55
A
4532 /*
4533 * And prevent access to what's above the current stack
4534 * size limit for this process.
4535 */
39037602
A
4536 if (load_result->user_stack_size == 0) {
4537 load_result->user_stack_size = unix_stack_size(p);
4538 prot_size = mach_vm_trunc_page(size - load_result->user_stack_size);
4539 } else {
316670eb 4540 prot_size = PAGE_SIZE;
39037602
A
4541 }
4542
4543 prot_addr = addr;
2d21ac55 4544 kr = mach_vm_protect(map,
39037602
A
4545 prot_addr,
4546 prot_size,
4547 FALSE,
4548 VM_PROT_NONE);
2d21ac55 4549 if (kr != KERN_SUCCESS) {
39037602 4550 (void)mach_vm_deallocate(map, addr, size);
2d21ac55
A
4551 return kr;
4552 }
4553 }
316670eb 4554
2d21ac55 4555 return KERN_SUCCESS;
1c79356b
A
4556}
4557
4558#include <sys/reboot.h>
4559
3e170ce0
A
4560/*
4561 * load_init_program_at_path
4562 *
4563 * Description: Load the "init" program; in most cases, this will be "launchd"
4564 *
4565 * Parameters: p Process to call execve() to create
4566 * the "init" program
4567 * scratch_addr Page in p, scratch space
4568 * path NULL terminated path
4569 *
4570 * Returns: KERN_SUCCESS Success
4571 * !KERN_SUCCESS See execve/mac_execve for error codes
4572 *
4573 * Notes: The process that is passed in is the first manufactured
4574 * process on the system, and gets here via bsd_ast() firing
4575 * for the first time. This is done to ensure that bsd_init()
4576 * has run to completion.
4577 *
39037602
A
4578 * The address map of the first manufactured process matches the
4579 * word width of the kernel. Once the self-exec completes, the
4580 * initproc might be different.
3e170ce0
A
4581 */
4582static int
4583load_init_program_at_path(proc_t p, user_addr_t scratch_addr, const char* path)
4584{
3e170ce0 4585 int retval[2];
39037602 4586 int error;
3e170ce0 4587 struct execve_args init_exec_args;
39037602 4588 user_addr_t argv0 = USER_ADDR_NULL, argv1 = USER_ADDR_NULL;
3e170ce0
A
4589
4590 /*
4591 * Validate inputs and pre-conditions
4592 */
4593 assert(p);
4594 assert(scratch_addr);
4595 assert(path);
4596
3e170ce0
A
4597 /*
4598 * Copy out program name.
4599 */
4600 size_t path_length = strlen(path) + 1;
39037602
A
4601 argv0 = scratch_addr;
4602 error = copyout(path, argv0, path_length);
4603 if (error)
4604 return error;
3e170ce0 4605
39037602 4606 scratch_addr = USER_ADDR_ALIGN(scratch_addr + path_length, sizeof(user_addr_t));
3e170ce0
A
4607
4608 /*
4609 * Put out first (and only) argument, similarly.
4610 * Assumes everything fits in a page as allocated above.
4611 */
4612 if (boothowto & RB_SINGLE) {
4613 const char *init_args = "-s";
4614 size_t init_args_length = strlen(init_args)+1;
4615
39037602
A
4616 argv1 = scratch_addr;
4617 error = copyout(init_args, argv1, init_args_length);
4618 if (error)
4619 return error;
3e170ce0 4620
39037602 4621 scratch_addr = USER_ADDR_ALIGN(scratch_addr + init_args_length, sizeof(user_addr_t));
3e170ce0
A
4622 }
4623
39037602
A
4624 if (proc_is64bit(p)) {
4625 user64_addr_t argv64bit[3];
4626
4627 argv64bit[0] = argv0;
4628 argv64bit[1] = argv1;
4629 argv64bit[2] = USER_ADDR_NULL;
4630
4631 error = copyout(argv64bit, scratch_addr, sizeof(argv64bit));
4632 if (error)
4633 return error;
4634 } else {
4635 user32_addr_t argv32bit[3];
4636
4637 argv32bit[0] = (user32_addr_t)argv0;
4638 argv32bit[1] = (user32_addr_t)argv1;
4639 argv32bit[2] = USER_ADDR_NULL;
4640
4641 error = copyout(argv32bit, scratch_addr, sizeof(argv32bit));
4642 if (error)
4643 return error;
4644 }
3e170ce0
A
4645
4646 /*
4647 * Set up argument block for fake call to execve.
4648 */
39037602 4649 init_exec_args.fname = argv0;
3e170ce0
A
4650 init_exec_args.argp = scratch_addr;
4651 init_exec_args.envp = USER_ADDR_NULL;
4652
4653 /*
4654 * So that init task is set with uid,gid 0 token
4655 */
4656 set_security_token(p);
4657
4658 return execve(p, &init_exec_args, retval);
4659}
4660
fe8ab488 4661static const char * init_programs[] = {
3e170ce0
A
4662#if DEBUG
4663 "/usr/local/sbin/launchd.debug",
4664#endif
fe8ab488
A
4665#if DEVELOPMENT || DEBUG
4666 "/usr/local/sbin/launchd.development",
4667#endif
4668 "/sbin/launchd",
4669};
1c79356b 4670
2d21ac55
A
4671/*
4672 * load_init_program
4673 *
4674 * Description: Load the "init" program; in most cases, this will be "launchd"
4675 *
4676 * Parameters: p Process to call execve() to create
4677 * the "init" program
4678 *
4679 * Returns: (void)
4680 *
4681 * Notes: The process that is passed in is the first manufactured
4682 * process on the system, and gets here via bsd_ast() firing
4683 * for the first time. This is done to ensure that bsd_init()
4684 * has run to completion.
3e170ce0
A
4685 *
4686 * In DEBUG & DEVELOPMENT builds, the launchdsuffix boot-arg
4687 * may be used to select a specific launchd executable. As with
4688 * the kcsuffix boot-arg, setting launchdsuffix to "" or "release"
4689 * will force /sbin/launchd to be selected.
4690 *
3e170ce0
A
4691 * Search order by build:
4692 *
4693 * DEBUG DEVELOPMENT RELEASE PATH
4694 * ----------------------------------------------------------------------------------
4695 * 1 1 NA /usr/local/sbin/launchd.$LAUNCHDSUFFIX
4696 * 2 NA NA /usr/local/sbin/launchd.debug
4697 * 3 2 NA /usr/local/sbin/launchd.development
4698 * 4 3 1 /sbin/launchd
2d21ac55 4699 */
1c79356b 4700void
2d21ac55 4701load_init_program(proc_t p)
1c79356b 4702{
3e170ce0
A
4703 uint32_t i;
4704 int error;
39037602
A
4705 vm_map_t map = current_map();
4706 mach_vm_offset_t scratch_addr = 0;
4707 mach_vm_size_t map_page_size = vm_map_page_size(map);
1c79356b 4708
39037602 4709 (void) mach_vm_allocate(map, &scratch_addr, map_page_size, VM_FLAGS_ANYWHERE);
3e170ce0
A
4710#if CONFIG_MEMORYSTATUS && CONFIG_JETSAM
4711 (void) memorystatus_init_at_boot_snapshot();
4712#endif /* CONFIG_MEMORYSTATUS && CONFIG_JETSAM */
4713
4714#if DEBUG || DEVELOPMENT
4715 /* Check for boot-arg suffix first */
4716 char launchd_suffix[64];
4717 if (PE_parse_boot_argn("launchdsuffix", launchd_suffix, sizeof(launchd_suffix))) {
4718 char launchd_path[128];
4719 boolean_t is_release_suffix = ((launchd_suffix[0] == 0) ||
4720 (strcmp(launchd_suffix, "release") == 0));
4721
4722 if (is_release_suffix) {
39037602 4723 error = load_init_program_at_path(p, (user_addr_t)scratch_addr, "/sbin/launchd");
3e170ce0
A
4724 if (!error)
4725 return;
4726
4727 panic("Process 1 exec of launchd.release failed, errno %d", error);
4728 } else {
4729 strlcpy(launchd_path, "/usr/local/sbin/launchd.", sizeof(launchd_path));
4730 strlcat(launchd_path, launchd_suffix, sizeof(launchd_path));
1c79356b 4731
3e170ce0
A
4732 /* All the error data is lost in the loop below, don't
4733 * attempt to save it. */
39037602 4734 if (!load_init_program_at_path(p, (user_addr_t)scratch_addr, launchd_path)) {
3e170ce0
A
4735 return;
4736 }
fe8ab488 4737 }
3e170ce0
A
4738 }
4739#endif
1c79356b 4740
3e170ce0
A
4741 error = ENOENT;
4742 for (i = 0; i < sizeof(init_programs)/sizeof(init_programs[0]); i++) {
39037602 4743 error = load_init_program_at_path(p, (user_addr_t)scratch_addr, init_programs[i]);
fe8ab488
A
4744 if (!error)
4745 return;
4746 }
4747
3e170ce0 4748 panic("Process 1 exec of %s failed, errno %d", ((i == 0) ? "<null>" : init_programs[i-1]), error);
1c79356b
A
4749}
4750
4751/*
2d21ac55
A
4752 * load_return_to_errno
4753 *
4754 * Description: Convert a load_return_t (Mach error) to an errno (BSD error)
4755 *
4756 * Parameters: lrtn Mach error number
4757 *
4758 * Returns: (int) BSD error number
4759 * 0 Success
4760 * EBADARCH Bad architecture
4761 * EBADMACHO Bad Mach object file
4762 * ESHLIBVERS Bad shared library version
4763 * ENOMEM Out of memory/resource shortage
4764 * EACCES Access denied
4765 * ENOENT Entry not found (usually "file does
4766 * does not exist")
4767 * EIO An I/O error occurred
4768 * EBADEXEC The executable is corrupt/unknown
1c79356b
A
4769 */
4770static int
4771load_return_to_errno(load_return_t lrtn)
4772{
4773 switch (lrtn) {
2d21ac55
A
4774 case LOAD_SUCCESS:
4775 return 0;
4776 case LOAD_BADARCH:
4777 return EBADARCH;
4778 case LOAD_BADMACHO:
39037602 4779 case LOAD_BADMACHO_UPX:
2d21ac55
A
4780 return EBADMACHO;
4781 case LOAD_SHLIB:
4782 return ESHLIBVERS;
4783 case LOAD_NOSPACE:
4784 case LOAD_RESOURCE:
4785 return ENOMEM;
4786 case LOAD_PROTECT:
4787 return EACCES;
4788 case LOAD_ENOENT:
4789 return ENOENT;
4790 case LOAD_IOERROR:
4791 return EIO;
4792 case LOAD_FAILURE:
39236c6e 4793 case LOAD_DECRYPTFAIL:
2d21ac55
A
4794 default:
4795 return EBADEXEC;
1c79356b
A
4796 }
4797}
4798
765c9de3
A
4799#include <mach/mach_types.h>
4800#include <mach/vm_prot.h>
4801#include <mach/semaphore.h>
4802#include <mach/sync_policy.h>
4803#include <kern/clock.h>
4804#include <mach/kern_return.h>
4805
91447636 4806/*
2d21ac55
A
4807 * execargs_alloc
4808 *
4809 * Description: Allocate the block of memory used by the execve arguments.
4810 * At the same time, we allocate a page so that we can read in
4811 * the first page of the image.
4812 *
4813 * Parameters: struct image_params * the image parameter block
4814 *
4815 * Returns: 0 Success
4816 * EINVAL Invalid argument
4817 * EACCES Permission denied
4818 * EINTR Interrupted function
4819 * ENOMEM Not enough space
4820 *
4821 * Notes: This is a temporary allocation into the kernel address space
4822 * to enable us to copy arguments in from user space. This is
4823 * necessitated by not mapping the process calling execve() into
4824 * the kernel address space during the execve() system call.
4825 *
4826 * We assemble the argument and environment, etc., into this
4827 * region before copying it as a single block into the child
4828 * process address space (at the top or bottom of the stack,
4829 * depending on which way the stack grows; see the function
4830 * exec_copyout_strings() for details).
4831 *
4832 * This ends up with a second (possibly unnecessary) copy compared
4833 * with assembing the data directly into the child address space,
4834 * instead, but since we cannot be guaranteed that the parent has
4835 * not modified its environment, we can't really know that it's
4836 * really a block there as well.
91447636 4837 */
b0d623f7
A
4838
4839
4840static int execargs_waiters = 0;
4841lck_mtx_t *execargs_cache_lock;
4842
4843static void
4844execargs_lock_lock(void) {
4845 lck_mtx_lock_spin(execargs_cache_lock);
4846}
4847
4848static void
4849execargs_lock_unlock(void) {
4850 lck_mtx_unlock(execargs_cache_lock);
4851}
4852
39236c6e 4853static wait_result_t
b0d623f7 4854execargs_lock_sleep(void) {
39236c6e 4855 return(lck_mtx_sleep(execargs_cache_lock, LCK_SLEEP_DEFAULT, &execargs_free_count, THREAD_INTERRUPTIBLE));
b0d623f7
A
4856}
4857
4858static kern_return_t
4859execargs_purgeable_allocate(char **execarg_address) {
6d2010ae 4860 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);
b0d623f7
A
4861 assert(kr == KERN_SUCCESS);
4862 return kr;
4863}
4864
4865static kern_return_t
4866execargs_purgeable_reference(void *execarg_address) {
4867 int state = VM_PURGABLE_NONVOLATILE;
4868 kern_return_t kr = vm_purgable_control(bsd_pageable_map, (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state);
4869
4870 assert(kr == KERN_SUCCESS);
4871 return kr;
4872}
4873
4874static kern_return_t
4875execargs_purgeable_volatilize(void *execarg_address) {
4876 int state = VM_PURGABLE_VOLATILE | VM_PURGABLE_ORDERING_OBSOLETE;
4877 kern_return_t kr;
4878 kr = vm_purgable_control(bsd_pageable_map, (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state);
4879
4880 assert(kr == KERN_SUCCESS);
4881
4882 return kr;
4883}
4884
4885static void
4886execargs_wakeup_waiters(void) {
4887 thread_wakeup(&execargs_free_count);
4888}
4889
765c9de3 4890static int
91447636 4891execargs_alloc(struct image_params *imgp)
765c9de3
A
4892{
4893 kern_return_t kret;
39236c6e 4894 wait_result_t res;
b0d623f7 4895 int i, cache_index = -1;
765c9de3 4896
b0d623f7
A
4897 execargs_lock_lock();
4898
4899 while (execargs_free_count == 0) {
4900 execargs_waiters++;
39236c6e 4901 res = execargs_lock_sleep();
b0d623f7 4902 execargs_waiters--;
39236c6e
A
4903 if (res != THREAD_AWAKENED) {
4904 execargs_lock_unlock();
4905 return (EINTR);
4906 }
b0d623f7
A
4907 }
4908
4909 execargs_free_count--;
4910
4911 for (i = 0; i < execargs_cache_size; i++) {
4912 vm_offset_t element = execargs_cache[i];
4913 if (element) {
4914 cache_index = i;
4915 imgp->ip_strings = (char *)(execargs_cache[i]);
4916 execargs_cache[i] = 0;
4917 break;
765c9de3 4918 }
b0d623f7 4919 }
765c9de3 4920
b0d623f7
A
4921 assert(execargs_free_count >= 0);
4922
4923 execargs_lock_unlock();
4924
4925 if (cache_index == -1) {
4926 kret = execargs_purgeable_allocate(&imgp->ip_strings);
4927 }
4928 else
4929 kret = execargs_purgeable_reference(imgp->ip_strings);
4930
4931 assert(kret == KERN_SUCCESS);
55e303ae 4932 if (kret != KERN_SUCCESS) {
765c9de3 4933 return (ENOMEM);
55e303ae 4934 }
b0d623f7 4935
6d2010ae
A
4936 /* last page used to read in file headers */
4937 imgp->ip_vdata = imgp->ip_strings + ( NCARGS + PAGE_SIZE );
4938 imgp->ip_strendp = imgp->ip_strings;
4939 imgp->ip_argspace = NCARGS;
4940 imgp->ip_strspace = ( NCARGS + PAGE_SIZE );
b0d623f7 4941
765c9de3
A
4942 return (0);
4943}
4944
2d21ac55
A
4945/*
4946 * execargs_free
4947 *
4948 * Description: Free the block of memory used by the execve arguments and the
4949 * first page of the executable by a previous call to the function
4950 * execargs_alloc().
4951 *
4952 * Parameters: struct image_params * the image parameter block
4953 *
4954 * Returns: 0 Success
4955 * EINVAL Invalid argument
4956 * EINTR Oeration interrupted
4957 */
765c9de3 4958static int
91447636 4959execargs_free(struct image_params *imgp)
765c9de3
A
4960{
4961 kern_return_t kret;
b0d623f7
A
4962 int i;
4963 boolean_t needs_wakeup = FALSE;
4964
4965 kret = execargs_purgeable_volatilize(imgp->ip_strings);
765c9de3 4966
b0d623f7
A
4967 execargs_lock_lock();
4968 execargs_free_count++;
4969
4970 for (i = 0; i < execargs_cache_size; i++) {
4971 vm_offset_t element = execargs_cache[i];
4972 if (element == 0) {
4973 execargs_cache[i] = (vm_offset_t) imgp->ip_strings;
4974 imgp->ip_strings = NULL;
4975 break;
4976 }
765c9de3 4977 }
b0d623f7
A
4978
4979 assert(imgp->ip_strings == NULL);
4980
4981 if (execargs_waiters > 0)
4982 needs_wakeup = TRUE;
4983
4984 execargs_lock_unlock();
4985
4986 if (needs_wakeup == TRUE)
4987 execargs_wakeup_waiters();
4988
4989 return ((kret == KERN_SUCCESS ? 0 : EINVAL));
765c9de3 4990}
2d21ac55
A
4991
4992static void
4993exec_resettextvp(proc_t p, struct image_params *imgp)
4994{
4995 vnode_t vp;
4996 off_t offset;
4997 vnode_t tvp = p->p_textvp;
4998 int ret;
4999
5000 vp = imgp->ip_vp;
5001 offset = imgp->ip_arch_offset;
5002
5003 if (vp == NULLVP)
5004 panic("exec_resettextvp: expected valid vp");
5005
5006 ret = vnode_ref(vp);
5007 proc_lock(p);
5008 if (ret == 0) {
5009 p->p_textvp = vp;
5010 p->p_textoff = offset;
5011 } else {
5012 p->p_textvp = NULLVP; /* this is paranoia */
5013 p->p_textoff = 0;
5014 }
5015 proc_unlock(p);
5016
5017 if ( tvp != NULLVP) {
5018 if (vnode_getwithref(tvp) == 0) {
5019 vnode_rele(tvp);
5020 vnode_put(tvp);
5021 }
5022 }
5023
5024}
5025
39236c6e
A
5026/*
5027 * If the process is not signed or if it contains entitlements, we
5028 * need to communicate through the task_access_port to taskgated.
5029 *
5030 * taskgated will provide a detached code signature if present, and
5031 * will enforce any restrictions on entitlements.
5032 */
5033
5034static boolean_t
5035taskgated_required(proc_t p, boolean_t *require_success)
5036{
5037 size_t length;
5038 void *blob;
5039 int error;
5040
3e170ce0
A
5041 if (cs_debug > 2)
5042 csvnode_print_debug(p->p_textvp);
5043
5044 const int can_skip_taskgated = csproc_get_platform_binary(p) && !csproc_get_platform_path(p);
5045 if (can_skip_taskgated) {
5046 if (cs_debug) printf("taskgated not required for: %s\n", p->p_name);
5047 *require_success = FALSE;
5048 return FALSE;
5049 }
5050
39236c6e
A
5051 if ((p->p_csflags & CS_VALID) == 0) {
5052 *require_success = FALSE;
5053 return TRUE;
5054 }
5055
5056 error = cs_entitlements_blob_get(p, &blob, &length);
5057 if (error == 0 && blob != NULL) {
fe8ab488
A
5058 /*
5059 * fatal on the desktop when entitlements are present,
5060 * unless we started in single-user mode
5061 */
5062 if ((boothowto & RB_SINGLE) == 0)
5063 *require_success = TRUE;
5064 /*
5065 * Allow initproc to run without causing taskgated to launch
5066 */
5067 if (p == initproc) {
5068 *require_success = FALSE;
5069 return FALSE;
5070 }
5071
3e170ce0
A
5072 if (cs_debug) printf("taskgated required for: %s\n", p->p_name);
5073
39236c6e
A
5074 return TRUE;
5075 }
5076
5077 *require_success = FALSE;
3e170ce0 5078 return FALSE;
39236c6e
A
5079}
5080
fe8ab488
A
5081/*
5082 * __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__
5083 *
5084 * Description: Waits for the userspace daemon to respond to the request
5085 * we made. Function declared non inline to be visible in
5086 * stackshots and spindumps as well as debugging.
5087 */
5088__attribute__((noinline)) int
5089__EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port, int32_t new_pid)
5090{
5091 return find_code_signature(task_access_port, new_pid);
5092}
39236c6e
A
5093
5094static int
b0d623f7
A
5095check_for_signature(proc_t p, struct image_params *imgp)
5096{
5097 mach_port_t port = NULL;
6d2010ae
A
5098 kern_return_t kr = KERN_FAILURE;
5099 int error = EACCES;
39236c6e 5100 boolean_t unexpected_failure = FALSE;
b0d623f7 5101 unsigned char hash[SHA1_RESULTLEN];
39236c6e 5102 boolean_t require_success = FALSE;
fe8ab488
A
5103 int spawn = (imgp->ip_flags & IMGPF_SPAWN);
5104 int vfexec = (imgp->ip_flags & IMGPF_VFORK_EXEC);
39037602 5105 os_reason_t signature_failure_reason = OS_REASON_NULL;
b0d623f7
A
5106
5107 /*
5108 * Override inherited code signing flags with the
5109 * ones for the process that is being successfully
5110 * loaded
5111 */
5112 proc_lock(p);
5113 p->p_csflags = imgp->ip_csflags;
5114 proc_unlock(p);
5115
5116 /* Set the switch_protect flag on the map */
5117 if(p->p_csflags & (CS_HARD|CS_KILL)) {
5118 vm_map_switch_protect(get_task_map(p->task), TRUE);
5119 }
fe8ab488
A
5120
5121 /*
5122 * image activation may be failed due to policy
5123 * which is unexpected but security framework does not
5124 * approve of exec, kill and return immediately.
5125 */
5126 if (imgp->ip_mac_return != 0) {
39037602
A
5127
5128 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
5129 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY, 0, 0);
5130 signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY);
fe8ab488
A
5131 error = imgp->ip_mac_return;
5132 unexpected_failure = TRUE;
5133 goto done;
5134 }
b0d623f7 5135
39037602
A
5136 if (imgp->ip_cs_error != OS_REASON_NULL) {
5137 signature_failure_reason = imgp->ip_cs_error;
5138 imgp->ip_cs_error = OS_REASON_NULL;
5139 error = EACCES;
5140 goto done;
5141 }
5142
39236c6e
A
5143 /* check if callout to taskgated is needed */
5144 if (!taskgated_required(p, &require_success)) {
6d2010ae
A
5145 error = 0;
5146 goto done;
5147 }
5148
5149 kr = task_get_task_access_port(p->task, &port);
5150 if (KERN_SUCCESS != kr || !IPC_PORT_VALID(port)) {
5151 error = 0;
39037602
A
5152 if (require_success) {
5153 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
5154 p->p_pid, OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT, 0, 0);
5155 signature_failure_reason = os_reason_create(OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT);
6d2010ae 5156 error = EACCES;
39037602 5157 }
6d2010ae
A
5158 goto done;
5159 }
5160
39236c6e
A
5161 /*
5162 * taskgated returns KERN_SUCCESS if it has completed its work
5163 * and the exec should continue, KERN_FAILURE if the exec should
5164 * fail, or it may error out with different error code in an
5165 * event of mig failure (e.g. process was signalled during the
5166 * rpc call, taskgated died, mig server died etc.).
5167 */
5168
fe8ab488 5169 kr = __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(port, p->p_pid);
39236c6e
A
5170 switch (kr) {
5171 case KERN_SUCCESS:
5172 error = 0;
5173 break;
5174 case KERN_FAILURE:
6d2010ae 5175 error = EACCES;
39037602
A
5176
5177 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
5178 p->p_pid, OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG, 0, 0);
5179 signature_failure_reason = os_reason_create(OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG);
6d2010ae 5180 goto done;
39236c6e
A
5181 default:
5182 error = EACCES;
39037602
A
5183
5184 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
5185 p->p_pid, OS_REASON_EXEC, EXEC_EXIT_REASON_TASKGATED_OTHER, 0, 0);
5186 signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_TASKGATED_OTHER);
39236c6e
A
5187 unexpected_failure = TRUE;
5188 goto done;
6d2010ae
A
5189 }
5190
5191 /* Only do this if exec_resettextvp() did not fail */
5192 if (p->p_textvp != NULLVP) {
5193 /*
5194 * If there's a new code directory, mark this process
5195 * as signed.
5196 */
5197 if (0 == ubc_cs_getcdhash(p->p_textvp, p->p_textoff, hash)) {
5198 proc_lock(p);
5199 p->p_csflags |= CS_VALID;
5200 proc_unlock(p);
b0d623f7
A
5201 }
5202 }
5203
6d2010ae 5204done:
39236c6e
A
5205 if (0 != error) {
5206 if (!unexpected_failure)
5207 p->p_csflags |= CS_KILLED;
6d2010ae 5208 /* make very sure execution fails */
fe8ab488 5209 if (vfexec || spawn) {
39037602
A
5210 assert(signature_failure_reason != OS_REASON_NULL);
5211 psignal_vfork_with_reason(p, p->task, imgp->ip_new_thread,
5212 SIGKILL, signature_failure_reason);
5213 signature_failure_reason = OS_REASON_NULL;
fe8ab488
A
5214 error = 0;
5215 } else {
39037602
A
5216 assert(signature_failure_reason != OS_REASON_NULL);
5217 psignal_with_reason(p, SIGKILL, signature_failure_reason);
5218 signature_failure_reason = OS_REASON_NULL;
fe8ab488 5219 }
39236c6e 5220 }
39037602
A
5221
5222 /* If we hit this, we likely would have leaked an exit reason */
5223 assert(signature_failure_reason == OS_REASON_NULL);
6d2010ae 5224 return error;
b0d623f7
A
5225}
5226
316670eb
A
5227/*
5228 * Typically as soon as we start executing this process, the
5229 * first instruction will trigger a VM fault to bring the text
5230 * pages (as executable) into the address space, followed soon
5231 * thereafter by dyld data structures (for dynamic executable).
5232 * To optimize this, as well as improve support for hardware
5233 * debuggers that can only access resident pages present
5234 * in the process' page tables, we prefault some pages if
5235 * possible. Errors are non-fatal.
5236 */
5237static void exec_prefault_data(proc_t p __unused, struct image_params *imgp, load_result_t *load_result)
5238{
5239 int ret;
5240 size_t expected_all_image_infos_size;
5241
5242 /*
5243 * Prefault executable or dyld entry point.
5244 */
39236c6e
A
5245 vm_fault(current_map(),
5246 vm_map_trunc_page(load_result->entry_point,
5247 vm_map_page_mask(current_map())),
5248 VM_PROT_READ | VM_PROT_EXECUTE,
5249 FALSE,
5250 THREAD_UNINT, NULL, 0);
316670eb
A
5251
5252 if (imgp->ip_flags & IMGPF_IS_64BIT) {
5253 expected_all_image_infos_size = sizeof(struct user64_dyld_all_image_infos);
5254 } else {
5255 expected_all_image_infos_size = sizeof(struct user32_dyld_all_image_infos);
5256 }
5257
5258 /* Decode dyld anchor structure from <mach-o/dyld_images.h> */
5259 if (load_result->dynlinker &&
5260 load_result->all_image_info_addr &&
5261 load_result->all_image_info_size >= expected_all_image_infos_size) {
5262 union {
5263 struct user64_dyld_all_image_infos infos64;
5264 struct user32_dyld_all_image_infos infos32;
5265 } all_image_infos;
5266
5267 /*
5268 * Pre-fault to avoid copyin() going through the trap handler
5269 * and recovery path.
5270 */
39236c6e
A
5271 vm_fault(current_map(),
5272 vm_map_trunc_page(load_result->all_image_info_addr,
5273 vm_map_page_mask(current_map())),
5274 VM_PROT_READ | VM_PROT_WRITE,
5275 FALSE,
5276 THREAD_UNINT, NULL, 0);
316670eb
A
5277 if ((load_result->all_image_info_addr & PAGE_MASK) + expected_all_image_infos_size > PAGE_SIZE) {
5278 /* all_image_infos straddles a page */
39236c6e
A
5279 vm_fault(current_map(),
5280 vm_map_trunc_page(load_result->all_image_info_addr + expected_all_image_infos_size - 1,
5281 vm_map_page_mask(current_map())),
5282 VM_PROT_READ | VM_PROT_WRITE,
5283 FALSE,
5284 THREAD_UNINT, NULL, 0);
316670eb
A
5285 }
5286
5287 ret = copyin(load_result->all_image_info_addr,
5288 &all_image_infos,
5289 expected_all_image_infos_size);
5290 if (ret == 0 && all_image_infos.infos32.version >= 9) {
5291
5292 user_addr_t notification_address;
5293 user_addr_t dyld_image_address;
5294 user_addr_t dyld_version_address;
5295 user_addr_t dyld_all_image_infos_address;
5296 user_addr_t dyld_slide_amount;
5297
5298 if (imgp->ip_flags & IMGPF_IS_64BIT) {
5299 notification_address = all_image_infos.infos64.notification;
5300 dyld_image_address = all_image_infos.infos64.dyldImageLoadAddress;
5301 dyld_version_address = all_image_infos.infos64.dyldVersion;
5302 dyld_all_image_infos_address = all_image_infos.infos64.dyldAllImageInfosAddress;
5303 } else {
5304 notification_address = all_image_infos.infos32.notification;
5305 dyld_image_address = all_image_infos.infos32.dyldImageLoadAddress;
5306 dyld_version_address = all_image_infos.infos32.dyldVersion;
5307 dyld_all_image_infos_address = all_image_infos.infos32.dyldAllImageInfosAddress;
5308 }
5309
5310 /*
5311 * dyld statically sets up the all_image_infos in its Mach-O
5312 * binary at static link time, with pointers relative to its default
5313 * load address. Since ASLR might slide dyld before its first
5314 * instruction is executed, "dyld_slide_amount" tells us how far
5315 * dyld was loaded compared to its default expected load address.
5316 * All other pointers into dyld's image should be adjusted by this
5317 * amount. At some point later, dyld will fix up pointers to take
5318 * into account the slide, at which point the all_image_infos_address
5319 * field in the structure will match the runtime load address, and
5320 * "dyld_slide_amount" will be 0, if we were to consult it again.
5321 */
5322
5323 dyld_slide_amount = load_result->all_image_info_addr - dyld_all_image_infos_address;
5324
5325#if 0
5326 kprintf("exec_prefault: 0x%016llx 0x%08x 0x%016llx 0x%016llx 0x%016llx 0x%016llx\n",
5327 (uint64_t)load_result->all_image_info_addr,
5328 all_image_infos.infos32.version,
5329 (uint64_t)notification_address,
5330 (uint64_t)dyld_image_address,
5331 (uint64_t)dyld_version_address,
5332 (uint64_t)dyld_all_image_infos_address);
5333#endif
5334
39236c6e
A
5335 vm_fault(current_map(),
5336 vm_map_trunc_page(notification_address + dyld_slide_amount,
5337 vm_map_page_mask(current_map())),
5338 VM_PROT_READ | VM_PROT_EXECUTE,
5339 FALSE,
5340 THREAD_UNINT, NULL, 0);
5341 vm_fault(current_map(),
5342 vm_map_trunc_page(dyld_image_address + dyld_slide_amount,
5343 vm_map_page_mask(current_map())),
5344 VM_PROT_READ | VM_PROT_EXECUTE,
5345 FALSE,
5346 THREAD_UNINT, NULL, 0);
5347 vm_fault(current_map(),
5348 vm_map_trunc_page(dyld_version_address + dyld_slide_amount,
5349 vm_map_page_mask(current_map())),
5350 VM_PROT_READ,
5351 FALSE,
5352 THREAD_UNINT, NULL, 0);
5353 vm_fault(current_map(),
5354 vm_map_trunc_page(dyld_all_image_infos_address + dyld_slide_amount,
5355 vm_map_page_mask(current_map())),
5356 VM_PROT_READ | VM_PROT_WRITE,
5357 FALSE,
5358 THREAD_UNINT, NULL, 0);
316670eb
A
5359 }
5360 }
5361}