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