]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/kern_exec.c
2d722a51b28282a5735dd1d2fe501890f58d8998
[apple/xnu.git] / bsd / kern / kern_exec.c
1 /*
2 * Copyright (c) 2000-2004 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
11 *
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
18 * under the License.
19 *
20 * @APPLE_LICENSE_HEADER_END@
21 */
22 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
23 /*
24 * Mach Operating System
25 * Copyright (c) 1987 Carnegie-Mellon University
26 * All rights reserved. The CMU software License Agreement specifies
27 * the terms and conditions for use and redistribution.
28 */
29
30 #include <cputypes.h>
31
32 /*-
33 * Copyright (c) 1982, 1986, 1991, 1993
34 * The Regents of the University of California. All rights reserved.
35 * (c) UNIX System Laboratories, Inc.
36 * All or some portions of this file are derived from material licensed
37 * to the University of California by American Telephone and Telegraph
38 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
39 * the permission of UNIX System Laboratories, Inc.
40 *
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
43 * are met:
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
49 * 3. All advertising materials mentioning features or use of this software
50 * must display the following acknowledgement:
51 * This product includes software developed by the University of
52 * California, Berkeley and its contributors.
53 * 4. Neither the name of the University nor the names of its contributors
54 * may be used to endorse or promote products derived from this software
55 * without specific prior written permission.
56 *
57 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
58 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
59 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
60 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
61 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
62 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
63 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
64 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
65 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67 * SUCH DAMAGE.
68 *
69 * from: @(#)kern_exec.c 8.1 (Berkeley) 6/10/93
70 */
71 #include <machine/reg.h>
72
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/filedesc.h>
76 #include <sys/kernel.h>
77 #include <sys/proc_internal.h>
78 #include <sys/kauth.h>
79 #include <sys/user.h>
80 #include <sys/socketvar.h>
81 #include <sys/malloc.h>
82 #include <sys/namei.h>
83 #include <sys/mount_internal.h>
84 #include <sys/vnode_internal.h>
85 #include <sys/file_internal.h>
86 #include <sys/stat.h>
87 #include <sys/uio_internal.h>
88 #include <sys/acct.h>
89 #include <sys/exec.h>
90 #include <sys/kdebug.h>
91 #include <sys/signal.h>
92 #include <sys/aio_kern.h>
93 #include <sys/sysproto.h>
94 #include <sys/shm_internal.h> /* shmexec() */
95 #include <sys/ubc_internal.h> /* ubc_map() */
96
97 #include <bsm/audit_kernel.h>
98
99 #include <mach/mach_types.h>
100 #include <mach/task.h>
101 #include <mach/thread_act.h>
102 #include <mach/vm_map.h>
103 #include <mach/mach_vm.h>
104 #include <mach/vm_param.h>
105
106 #include <vm/vm_map.h>
107 #include <vm/vm_kern.h>
108 #include <vm/vm_pager.h>
109 #include <vm/vm_kern.h>
110 #include <vm/task_working_set.h>
111 #include <vm/vm_shared_memory_server.h>
112
113 /*
114 * Mach things for which prototypes are unavailable from Mach headers
115 */
116 void ipc_task_reset(
117 task_t task);
118
119 extern struct savearea *get_user_regs(thread_t);
120
121
122 #include <kern/thread.h>
123 #include <kern/task.h>
124 #include <kern/ast.h>
125 #include <kern/mach_loader.h>
126 #include <mach-o/fat.h>
127 #include <mach-o/loader.h>
128 #include <machine/vmparam.h>
129 #if KTRACE
130 #include <sys/ktrace.h>
131 #endif
132 #include <sys/imgact.h>
133
134
135 /*
136 * SIZE_MAXPTR The maximum size of a user space pointer, in bytes
137 * SIZE_IMG_STRSPACE The available string space, minus two pointers; we
138 * define it interms of the maximum, since we don't
139 * know the pointer size going in, until after we've
140 * parsed the executable image.
141 */
142 #define SIZE_MAXPTR 8 /* 64 bits */
143 #define SIZE_IMG_STRSPACE (NCARGS - 2 * SIZE_MAXPTR)
144
145 int app_profile = 0;
146
147 extern vm_map_t bsd_pageable_map;
148 extern struct fileops vnops;
149
150 #define ROUND_PTR(type, addr) \
151 (type *)( ( (unsigned)(addr) + 16 - 1) \
152 & ~(16 - 1) )
153
154 struct image_params; /* Forward */
155 static int exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp);
156 static int load_return_to_errno(load_return_t lrtn);
157 static int execargs_alloc(struct image_params *imgp);
158 static int execargs_free(struct image_params *imgp);
159 static int exec_check_permissions(struct image_params *imgp);
160 static int exec_extract_strings(struct image_params *imgp);
161 static int exec_handle_sugid(struct image_params *imgp);
162 static int sugid_scripts = 0;
163 SYSCTL_INT (_kern, OID_AUTO, sugid_scripts, CTLFLAG_RW, &sugid_scripts, 0, "");
164 static kern_return_t create_unix_stack(vm_map_t map, user_addr_t user_stack,
165 int customstack, struct proc *p);
166 static int copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size);
167
168 /* XXX forward; should be in headers, but can't be for one reason or another */
169 extern void vfork_return(thread_t th_act,
170 struct proc * p,
171 struct proc *p2,
172 register_t *retval);
173
174 /*
175 * exec_add_string
176 *
177 * Add the requested string to the string space area.
178 *
179 * Parameters; struct image_params * image parameter block
180 * user_addr_t string to add to strings area
181 * uio_seg segment where string is located
182 *
183 * Returns: 0 Success
184 * !0 Failure errno from copyinstr()
185 *
186 * Implicit returns:
187 * (imgp->ip_strendp) updated location of next add, if any
188 * (imgp->ip_strspace) updated byte count of space remaining
189 */
190 static int
191 exec_add_string(struct image_params *imgp, user_addr_t str, /*uio_seg*/int seg)
192 {
193 int error = 0;
194
195 do {
196 size_t len = 0;
197 if (imgp->ip_strspace <= 0) {
198 error = E2BIG;
199 break;
200 }
201 if (IS_UIO_SYS_SPACE(seg)) {
202 char *kstr = CAST_DOWN(char *,str); /* SAFE */
203 error = copystr(kstr, imgp->ip_strendp, imgp->ip_strspace, &len);
204 } else {
205 error = copyinstr(str, imgp->ip_strendp, imgp->ip_strspace,
206 &len);
207 }
208 imgp->ip_strendp += len;
209 imgp->ip_strspace -= len;
210 } while (error == ENAMETOOLONG);
211
212 return error;
213 }
214
215 /*
216 * exec_save_path
217 *
218 * To support new app package launching for Mac OS X, the dyld needs the
219 * first argument to execve() stored on the user stack.
220 *
221 * Save the executable path name at the top of the strings area and set
222 * the argument vector pointer to the location following that to indicate
223 * the start of the argument and environment tuples, setting the remaining
224 * string space count to the size of the string area minus the path length
225 * and a reserve for two pointers.
226 *
227 * Parameters; struct image_params * image parameter block
228 * char * path used to invoke program
229 * uio_seg segment where path is located
230 *
231 * Returns: int 0 Success
232 * !0 Failure: error number
233 * Implicit returns:
234 * (imgp->ip_strings) saved path
235 * (imgp->ip_strspace) space remaining in ip_strings
236 * (imgp->ip_argv) beginning of argument list
237 * (imgp->ip_strendp) start of remaining copy area
238 *
239 * Note: We have to do this before the initial namei() since in the
240 * path contains symbolic links, namei() will overwrite the
241 * original path buffer contents. If the last symbolic link
242 * resolved was a relative pathname, we would lose the original
243 * "path", which could be an absolute pathname. This might be
244 * unacceptable for dyld.
245 */
246 static int
247 exec_save_path(struct image_params *imgp, user_addr_t path, /*uio_seg*/int seg)
248 {
249 int error;
250 size_t len;
251 char *kpath = CAST_DOWN(char *,path); /* SAFE */
252
253 imgp->ip_strendp = imgp->ip_strings;
254 imgp->ip_strspace = SIZE_IMG_STRSPACE;
255
256 len = MIN(MAXPATHLEN, imgp->ip_strspace);
257
258 switch( seg) {
259 case UIO_USERSPACE32:
260 case UIO_USERSPACE64: /* Same for copyin()... */
261 error = copyinstr(path, imgp->ip_strings, len, &len);
262 break;
263 case UIO_SYSSPACE32:
264 error = copystr(kpath, imgp->ip_strings, len, &len);
265 break;
266 default:
267 error = EFAULT;
268 break;
269 }
270
271 if (!error) {
272 imgp->ip_strendp += len;
273 imgp->ip_strspace -= len;
274 imgp->ip_argv = imgp->ip_strendp;
275 }
276
277 return(error);
278 }
279
280 #ifdef IMGPF_POWERPC
281 /*
282 * exec_powerpc32_imgact
283 *
284 * Implicitly invoke the PowerPC handler for a byte-swapped image magic
285 * number. This may happen either as a result of an attempt to invoke a
286 * PowerPC image directly, or indirectly as the interpreter used in an
287 * interpreter script.
288 *
289 * Parameters; struct image_params * image parameter block
290 *
291 * Returns: -1 not an PowerPC image (keep looking)
292 * -3 Success: exec_archhandler_ppc: relookup
293 * >0 Failure: exec_archhandler_ppc: error number
294 *
295 * Note: This image activator does not handle the case of a direct
296 * invocation of the exec_archhandler_ppc, since in that case, the
297 * exec_archhandler_ppc itself is not a PowerPC binary; instead,
298 * binary image activators must recognize the exec_archhandler_ppc;
299 * This is managed in exec_check_permissions().
300 *
301 * Note: This image activator is limited to 32 bit powerpc images;
302 * if support for 64 bit powerpc images is desired, it would
303 * be more in line with this design to write a separate 64 bit
304 * image activator.
305 */
306 static int
307 exec_powerpc32_imgact(struct image_params *imgp)
308 {
309 struct mach_header *mach_header = (struct mach_header *)imgp->ip_vdata;
310 int error;
311 size_t len = 0;
312
313 /*
314 * Make sure it's a PowerPC binary. If we've already redirected
315 * from an interpreted file once, don't do it again.
316 */
317 if (mach_header->magic != MH_CIGAM)
318 return (-1);
319
320 /* If there is no exec_archhandler_ppc, we can't run it */
321 if (exec_archhandler_ppc.path[0] == 0)
322 return (EBADARCH);
323
324 /*
325 * The PowerPC flag will be set by the exec_check_permissions()
326 * call anyway; however, we set this flag here so that the relookup
327 * in execve() does not follow symbolic links, as a side effect.
328 */
329 imgp->ip_flags |= IMGPF_POWERPC;
330
331 /* impute an interpreter */
332 error = copystr(exec_archhandler_ppc.path, imgp->ip_interp_name,
333 IMG_SHSIZE, &len);
334 if (error)
335 return (error);
336
337 /*
338 * provide a replacement string for p->p_comm; we have to use an
339 * an alternate buffer for this, rather than replacing it directly,
340 * since the exec may fail and return to the parent. In that case,
341 * we would have erroneously changed the parent p->p_comm instead.
342 */
343 strncpy(imgp->ip_p_comm, imgp->ip_ndp->ni_cnd.cn_nameptr, MAXCOMLEN);
344 imgp->ip_p_comm[MAXCOMLEN] = '\0';
345
346 return (-3);
347 }
348 #endif /* IMGPF_POWERPC */
349
350
351 /*
352 * exec_shell_imgact
353 *
354 * Image activator for interpreter scripts. If the image begins with the
355 * characters "#!", then it is an interpreter script. Verify that we are
356 * not already executing in PowerPC mode, and that the length of the script
357 * line indicating the interpreter is not in excess of the maximum allowed
358 * size. If this is the case, then break out the arguments, if any, which
359 * are separated by white space, and copy them into the argument save area
360 * as if they were provided on the command line before all other arguments.
361 * The line ends when we encounter a comment character ('#') or newline.
362 *
363 * Parameters; struct image_params * image parameter block
364 *
365 * Returns: -1 not an interpreter (keep looking)
366 * -3 Success: interpreter: relookup
367 * >0 Failure: interpreter: error number
368 *
369 * A return value other than -1 indicates subsequent image activators should
370 * not be given the opportunity to attempt to activate the image.
371 */
372 static int
373 exec_shell_imgact(struct image_params *imgp)
374 {
375 char *vdata = imgp->ip_vdata;
376 char *ihp;
377 char *line_endp;
378 char *interp;
379
380 /*
381 * Make sure it's a shell script. If we've already redirected
382 * from an interpreted file once, don't do it again.
383 *
384 * Note: We disallow PowerPC, since the expectation is that we
385 * may run a PowerPC interpreter, but not an interpret a PowerPC
386 * image. This is consistent with historical behaviour.
387 */
388 if (vdata[0] != '#' ||
389 vdata[1] != '!' ||
390 (imgp->ip_flags & IMGPF_INTERPRET) != 0) {
391 return (-1);
392 }
393
394 #ifdef IMGPF_POWERPC
395 if ((imgp->ip_flags & IMGPF_POWERPC) != 0)
396 return (EBADARCH);
397 #endif /* IMGPF_POWERPC */
398
399 imgp->ip_flags |= IMGPF_INTERPRET;
400
401 /* Check to see if SUGID scripts are permitted. If they aren't then
402 * clear the SUGID bits.
403 * imgp->ip_vattr is known to be valid.
404 */
405 if (sugid_scripts == 0) {
406 imgp->ip_origvattr->va_mode &= ~(VSUID | VSGID);
407 }
408
409 /* Find the nominal end of the interpreter line */
410 for( ihp = &vdata[2]; *ihp != '\n' && *ihp != '#'; ihp++) {
411 if (ihp >= &vdata[IMG_SHSIZE])
412 return (ENOEXEC);
413 }
414
415 line_endp = ihp;
416 ihp = &vdata[2];
417 /* Skip over leading spaces - until the interpreter name */
418 while ( ihp < line_endp && ((*ihp == ' ') || (*ihp == '\t')))
419 ihp++;
420
421 /*
422 * Find the last non-whitespace character before the end of line or
423 * the beginning of a comment; this is our new end of line.
424 */
425 for (;line_endp > ihp && ((*line_endp == ' ') || (*line_endp == '\t')); line_endp--)
426 continue;
427
428 /* Empty? */
429 if (line_endp == ihp)
430 return (ENOEXEC);
431
432 /* copy the interpreter name */
433 interp = imgp->ip_interp_name;
434 while ((ihp < line_endp) && (*ihp != ' ') && (*ihp != '\t'))
435 *interp++ = *ihp++;
436 *interp = '\0';
437
438 exec_save_path(imgp, CAST_USER_ADDR_T(imgp->ip_interp_name),
439 UIO_SYSSPACE32);
440
441 ihp = &vdata[2];
442 while (ihp < line_endp) {
443 /* Skip leading whitespace before each argument */
444 while ((*ihp == ' ') || (*ihp == '\t'))
445 ihp++;
446
447 if (ihp >= line_endp)
448 break;
449
450 /* We have an argument; copy it */
451 while ((ihp < line_endp) && (*ihp != ' ') && (*ihp != '\t')) {
452 *imgp->ip_strendp++ = *ihp++;
453 imgp->ip_strspace--;
454 }
455 *imgp->ip_strendp++ = 0;
456 imgp->ip_strspace--;
457 imgp->ip_argc++;
458 }
459
460 return (-3);
461 }
462
463
464
465 /*
466 * exec_fat_imgact
467 *
468 * Image activator for fat 1.0 binaries. If the binary is fat, then we
469 * need to select an image from it internally, and make that the image
470 * we are going to attempt to execute. At present, this consists of
471 * reloading the first page for the image with a first page from the
472 * offset location indicated by the fat header.
473 *
474 * Important: This image activator is byte order neutral.
475 *
476 * Note: If we find an encapsulated binary, we make no assertions
477 * about its validity; instead, we leave that up to a rescan
478 * for an activator to claim it, and, if it is claimed by one,
479 * that activator is responsible for determining validity.
480 */
481 static int
482 exec_fat_imgact(struct image_params *imgp)
483 {
484 struct proc *p = vfs_context_proc(imgp->ip_vfs_context);
485 kauth_cred_t cred = p->p_ucred;
486 struct fat_header *fat_header = (struct fat_header *)imgp->ip_vdata;
487 struct fat_arch fat_arch;
488 int resid, error;
489 load_return_t lret;
490
491 /* Make sure it's a fat binary */
492 if ((fat_header->magic != FAT_MAGIC) &&
493 (fat_header->magic != FAT_CIGAM)) {
494 error = -1;
495 goto bad;
496 }
497
498 /* Look up our preferred architecture in the fat file. */
499 lret = fatfile_getarch_affinity(imgp->ip_vp,
500 (vm_offset_t)fat_header,
501 &fat_arch,
502 (p->p_flag & P_AFFINITY));
503 if (lret != LOAD_SUCCESS) {
504 error = load_return_to_errno(lret);
505 goto bad;
506 }
507
508 /* Read the Mach-O header out of it */
509 error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata,
510 PAGE_SIZE, fat_arch.offset,
511 UIO_SYSSPACE32, (IO_UNIT|IO_NODELOCKED),
512 cred, &resid, p);
513 if (error) {
514 goto bad;
515 }
516
517 /* Did we read a complete header? */
518 if (resid) {
519 error = EBADEXEC;
520 goto bad;
521 }
522
523 /* Success. Indicate we have identified an encapsulated binary */
524 error = -2;
525 imgp->ip_arch_offset = (user_size_t)fat_arch.offset;
526 imgp->ip_arch_size = (user_size_t)fat_arch.size;
527
528 bad:
529 return (error);
530 }
531
532 /*
533 * exec_mach_imgact
534 *
535 * Image activator for mach-o 1.0 binaries.
536 *
537 * Important: This image activator is NOT byte order neutral.
538 */
539 static int
540 exec_mach_imgact(struct image_params *imgp)
541 {
542 struct mach_header *mach_header = (struct mach_header *)imgp->ip_vdata;
543 kauth_cred_t cred = vfs_context_ucred(imgp->ip_vfs_context);
544 struct proc *p = vfs_context_proc(imgp->ip_vfs_context);
545 int error = 0;
546 int vfexec = 0;
547 task_t task;
548 task_t new_task;
549 thread_t thread;
550 struct uthread *uthread;
551 vm_map_t old_map = VM_MAP_NULL;
552 vm_map_t map;
553 boolean_t clean_regions = FALSE;
554 load_return_t lret;
555 load_result_t load_result;
556 shared_region_mapping_t shared_region, initial_region;
557 #ifdef IMGPF_POWERPC
558 int powerpcParent, powerpcImage;
559 #endif /* IMGPF_POWERPC */
560
561 /*
562 * make sure it's a Mach-O 1.0 or Mach-O 2.0 binary; the difference
563 * is a reserved field on the end, so for the most part, we can
564 * treat them as if they were identical.
565 */
566 if ((mach_header->magic != MH_MAGIC) &&
567 (mach_header->magic != MH_MAGIC_64)) {
568 error = -1;
569 goto bad;
570 }
571
572 task = current_task();
573 thread = current_thread();
574 uthread = get_bsdthread_info(thread);
575
576 if (uthread->uu_flag & UT_VFORK)
577 vfexec = 1; /* Mark in exec */
578
579 if ((mach_header->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64)
580 imgp->ip_flags |= IMGPF_IS_64BIT;
581
582 if (!grade_binary(mach_header->cputype, mach_header->cpusubtype)) {
583 error = EBADARCH;
584 goto bad;
585 }
586
587 /*
588 * Copy in arguments/environment from the old process, if the
589 * vector is non-NULL (i.e. exec is not being called from
590 * load_init_program(), as a special case, at system startup).
591 */
592 if (imgp->ip_user_argv != 0LL) {
593 error = exec_extract_strings(imgp);
594 if (error)
595 goto bad;
596 }
597
598 /*
599 * Hack for binary compatability; put three NULs on the end of the
600 * string area, and round it up to the next word boundary. This
601 * ensures padding with NULs to the boundary.
602 */
603 imgp->ip_strendp[0] = 0;
604 imgp->ip_strendp[1] = 0;
605 imgp->ip_strendp[2] = 0;
606 imgp->ip_strendp += (((imgp->ip_strendp - imgp->ip_strings) + NBPW-1) & ~(NBPW-1));
607
608 #ifdef IMGPF_POWERPC
609 /*
610 * XXX
611 *
612 * Should be factored out; this is here because we might be getting
613 * invoked this way as the result of a shell script, and the check
614 * in exec_check_permissions() is not interior to the jump back up
615 * to the "encapsulated_binary:" label in execve().
616 */
617 if (imgp->ip_vattr->va_fsid == exec_archhandler_ppc.fsid &&
618 imgp->ip_vattr->va_fileid == (uint64_t)((u_long)exec_archhandler_ppc.fileid)) {
619 imgp->ip_flags |= IMGPF_POWERPC;
620 }
621 #endif /* IMGPF_POWERPC */
622
623 if (vfexec) {
624 kern_return_t result;
625
626 result = task_create_internal(task, FALSE, (imgp->ip_flags & IMGPF_IS_64BIT), &new_task);
627 if (result != KERN_SUCCESS)
628 printf("execve: task_create failed. Code: 0x%x\n", result);
629 p->task = new_task;
630 set_bsdtask_info(new_task, p);
631 if (p->p_nice != 0)
632 resetpriority(p);
633 map = get_task_map(new_task);
634
635 if (imgp->ip_flags & IMGPF_IS_64BIT)
636 vm_map_set_64bit(map);
637 else
638 vm_map_set_32bit(map);
639
640 result = thread_create(new_task, &imgp->ip_vfork_thread);
641 if (result != KERN_SUCCESS)
642 printf("execve: thread_create failed. Code: 0x%x\n", result);
643 /* reset local idea of task, thread, uthread */
644 task = new_task;
645 thread = imgp->ip_vfork_thread;
646 uthread = get_bsdthread_info(thread);
647 } else {
648 map = VM_MAP_NULL;
649 }
650
651 /*
652 * We set these flags here; this is OK, since if we fail after
653 * this point, we have already destroyed the parent process anyway.
654 */
655 if (imgp->ip_flags & IMGPF_IS_64BIT) {
656 task_set_64bit(task, TRUE);
657 p->p_flag |= P_LP64;
658 } else {
659 task_set_64bit(task, FALSE);
660 p->p_flag &= ~P_LP64;
661 }
662
663 /*
664 * Load the Mach-O file.
665 */
666 /* LP64 - remove following "if" statement after osfmk/vm/task_working_set.c */
667 if((imgp->ip_flags & IMGPF_IS_64BIT) == 0)
668 if(imgp->ip_tws_cache_name) {
669 tws_handle_startup_file(task, kauth_cred_getuid(cred),
670 imgp->ip_tws_cache_name, imgp->ip_vp, &clean_regions);
671 }
672
673 vm_get_shared_region(task, &initial_region);
674
675 #ifdef IMGPF_POWERPC
676 /*
677 * If we are transitioning to/from powerpc, then we need to do extra
678 * work here.
679 */
680 powerpcParent = (p->p_flag & P_TRANSLATED) ? 1 : 0;
681 powerpcImage = (imgp->ip_flags & IMGPF_POWERPC) ? 1 : 0;
682
683 if (powerpcParent ^ powerpcImage) {
684 cpu_type_t cpu = (powerpcImage ? CPU_TYPE_POWERPC : cpu_type());
685 struct vnode *rootDir = p->p_fd->fd_rdir;
686
687 shared_region = lookup_default_shared_region((int)rootDir, cpu);
688 if (shared_region == NULL) {
689 shared_region_mapping_t old_region;
690 shared_region_mapping_t new_region;
691 vm_get_shared_region(current_task(), &old_region);
692 /* grrrr... this sets current_task(), not task
693 * -- they're different (usually)
694 */
695 shared_file_boot_time_init((int)rootDir,cpu);
696 if ( current_task() != task ) {
697 vm_get_shared_region(current_task(),&new_region);
698 vm_set_shared_region(task,new_region);
699 vm_set_shared_region(current_task(),old_region);
700 }
701 } else {
702 vm_set_shared_region(task, shared_region);
703 }
704 shared_region_mapping_dealloc(initial_region);
705 } else
706 #endif /* IMGPF_POWERPC */
707
708 {
709 struct shared_region_task_mappings map_info;
710 shared_region_mapping_t next;
711
712 shared_region_mapping_info(initial_region,
713 &map_info.text_region,
714 &map_info.text_size,
715 &map_info.data_region,
716 &map_info.data_size,
717 &map_info.region_mappings,
718 &map_info.client_base,
719 &map_info.alternate_base,
720 &map_info.alternate_next,
721 &map_info.fs_base,
722 &map_info.system,
723 &map_info.flags,
724 &next);
725 if (map_info.flags & SHARED_REGION_STANDALONE) {
726 /*
727 * We were using a private shared region.
728 * Try and get back to a system-wide shared region
729 * with matching "fs_base" (for chroot) and "system"
730 * (for CPU type).
731 */
732 shared_region = lookup_default_shared_region(
733 map_info.fs_base,
734 map_info.system);
735 if (shared_region == NULL) {
736 /*
737 * No system-wide default regions, stick to
738 * our private region...
739 */
740 } else {
741 SHARED_REGION_TRACE(
742 SHARED_REGION_TRACE_INFO,
743 ("shared_region: %p [%d(%s)] "
744 "exec(\"%s\"): "
745 "moving from private %p[%x,%x,%x] "
746 "to default %p\n",
747 current_thread(),
748 p->p_pid, p->p_comm,
749 (imgp->ip_p_comm[0] ?
750 imgp->ip_p_comm :
751 imgp->ip_ndp->ni_cnd.cn_nameptr),
752 initial_region,
753 map_info.fs_base,
754 map_info.system,
755 map_info.flags,
756 shared_region));
757 vm_set_shared_region(task, shared_region);
758 shared_region_mapping_dealloc(initial_region);
759 }
760 }
761 }
762
763 /*
764 * NOTE: An error after this point indicates we have potentially
765 * destroyed or overwrote some process state while attempting an
766 * execve() following a vfork(), which is an unrecoverable condition.
767 */
768
769 /*
770 * We reset the task to 64-bit (or not) here. It may have picked up
771 * a new map, and we need that to reflect its true 64-bit nature.
772 */
773
774 task_set_64bit(task,
775 ((imgp->ip_flags & IMGPF_IS_64BIT) == IMGPF_IS_64BIT));
776
777 /*
778 * Actually load the image file we previously decided to load.
779 */
780 lret = load_machfile(imgp, mach_header, thread, map, clean_regions, &load_result);
781
782 if (lret != LOAD_SUCCESS) {
783 error = load_return_to_errno(lret);
784 goto badtoolate;
785 }
786
787 /* load_machfile() maps the vnode */
788 (void)ubc_map(imgp->ip_vp, PROT_EXEC);
789
790 /*
791 * deal with set[ug]id.
792 */
793 error = exec_handle_sugid(imgp);
794
795 KNOTE(&p->p_klist, NOTE_EXEC);
796
797 if (!vfexec && (p->p_flag & P_TRACED))
798 psignal(p, SIGTRAP);
799
800 if (error) {
801 goto badtoolate;
802 }
803 vnode_put(imgp->ip_vp);
804 imgp->ip_vp = NULL;
805
806 if (load_result.unixproc &&
807 create_unix_stack(get_task_map(task),
808 load_result.user_stack, load_result.customstack, p)) {
809 error = load_return_to_errno(LOAD_NOSPACE);
810 goto badtoolate;
811 }
812
813 if (vfexec) {
814 old_map = vm_map_switch(get_task_map(task));
815 }
816
817 if (load_result.unixproc) {
818 user_addr_t ap;
819
820 /*
821 * Copy the strings area out into the new process address
822 * space.
823 */
824 ap = p->user_stack;
825 error = exec_copyout_strings(imgp, &ap);
826 if (error) {
827 if (vfexec)
828 vm_map_switch(old_map);
829 goto badtoolate;
830 }
831 /* Set the stack */
832 thread_setuserstack(thread, ap);
833 }
834
835 if (load_result.dynlinker) {
836 uint64_t ap;
837
838 /* Adjust the stack */
839 if (imgp->ip_flags & IMGPF_IS_64BIT) {
840 ap = thread_adjuserstack(thread, -8);
841 error = copyoutptr(load_result.mach_header, ap, 8);
842 } else {
843 ap = thread_adjuserstack(thread, -4);
844 error = suword(ap, load_result.mach_header);
845 }
846 if (error) {
847 if (vfexec)
848 vm_map_switch(old_map);
849 goto badtoolate;
850 }
851 }
852
853 if (vfexec) {
854 vm_map_switch(old_map);
855 }
856 /* Set the entry point */
857 thread_setentrypoint(thread, load_result.entry_point);
858
859 /* Stop profiling */
860 stopprofclock(p);
861
862 /*
863 * Reset signal state.
864 */
865 execsigs(p, thread);
866
867 /*
868 * Close file descriptors
869 * which specify close-on-exec.
870 */
871 fdexec(p);
872
873 /*
874 * need to cancel async IO requests that can be cancelled and wait for those
875 * already active. MAY BLOCK!
876 */
877 _aio_exec( p );
878
879 /* FIXME: Till vmspace inherit is fixed: */
880 if (!vfexec && p->vm_shm)
881 shmexec(p);
882 /* Clean up the semaphores */
883 semexit(p);
884
885 /*
886 * Remember file name for accounting.
887 */
888 p->p_acflag &= ~AFORK;
889 /* If the translated name isn't NULL, then we want to use
890 * that translated name as the name we show as the "real" name.
891 * Otherwise, use the name passed into exec.
892 */
893 if (0 != imgp->ip_p_comm[0]) {
894 bcopy((caddr_t)imgp->ip_p_comm, (caddr_t)p->p_comm,
895 sizeof(p->p_comm));
896 } else {
897 if (imgp->ip_ndp->ni_cnd.cn_namelen > MAXCOMLEN)
898 imgp->ip_ndp->ni_cnd.cn_namelen = MAXCOMLEN;
899 bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_comm,
900 (unsigned)imgp->ip_ndp->ni_cnd.cn_namelen);
901 p->p_comm[imgp->ip_ndp->ni_cnd.cn_namelen] = '\0';
902 }
903
904 if (kdebug_enable) {
905 long dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4;
906
907 /*
908 * Collect the pathname for tracing
909 */
910 kdbg_trace_string(p, &dbg_arg1, &dbg_arg2, &dbg_arg3, &dbg_arg4);
911
912 if (vfexec)
913 {
914 KERNEL_DEBUG_CONSTANT1((TRACEDBG_CODE(DBG_TRACE_DATA, 2)) | DBG_FUNC_NONE,
915 p->p_pid ,0,0,0, (unsigned int)thread);
916 KERNEL_DEBUG_CONSTANT1((TRACEDBG_CODE(DBG_TRACE_STRING, 2)) | DBG_FUNC_NONE,
917 dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4, (unsigned int)thread);
918 }
919 else
920 {
921 KERNEL_DEBUG_CONSTANT((TRACEDBG_CODE(DBG_TRACE_DATA, 2)) | DBG_FUNC_NONE,
922 p->p_pid ,0,0,0,0);
923 KERNEL_DEBUG_CONSTANT((TRACEDBG_CODE(DBG_TRACE_STRING, 2)) | DBG_FUNC_NONE,
924 dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4, 0);
925 }
926 }
927
928 #ifdef IMGPF_POWERPC
929 /*
930 * Mark the process as powerpc or not. If powerpc, set the affinity
931 * flag, which will be used for grading binaries in future exec's
932 * from the process.
933 */
934 if (((imgp->ip_flags & IMGPF_POWERPC) != 0))
935 p->p_flag |= P_TRANSLATED;
936 else
937 #endif /* IMGPF_POWERPC */
938 p->p_flag &= ~P_TRANSLATED;
939 p->p_flag &= ~P_AFFINITY;
940
941 /*
942 * mark as execed, wakeup the process that vforked (if any) and tell
943 * it that it now has it's own resources back
944 */
945 p->p_flag |= P_EXEC;
946 if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
947 p->p_flag &= ~P_PPWAIT;
948 wakeup((caddr_t)p->p_pptr);
949 }
950
951 if (vfexec && (p->p_flag & P_TRACED)) {
952 psignal_vfork(p, new_task, thread, SIGTRAP);
953 }
954
955 badtoolate:
956 if (vfexec) {
957 task_deallocate(new_task);
958 thread_deallocate(thread);
959 if (error)
960 error = 0;
961 }
962
963 bad:
964 return(error);
965 }
966
967
968
969
970 /*
971 * Our image activator table; this is the table of the image types we are
972 * capable of loading. We list them in order of preference to ensure the
973 * fastest image load speed.
974 *
975 * XXX hardcoded, for now; should use linker sets
976 */
977 struct execsw {
978 int (*ex_imgact)(struct image_params *);
979 const char *ex_name;
980 } execsw[] = {
981 { exec_mach_imgact, "Mach-o Binary" },
982 { exec_fat_imgact, "Fat Binary" },
983 #ifdef IMGPF_POWERPC
984 { exec_powerpc32_imgact, "PowerPC binary" },
985 #endif /* IMGPF_POWERPC */
986 { exec_shell_imgact, "Interpreter Script" },
987 { NULL, NULL}
988 };
989
990
991 /*
992 * TODO: Dynamic linker header address on stack is copied via suword()
993 */
994 /* ARGSUSED */
995 int
996 execve(struct proc *p, struct execve_args *uap, register_t *retval)
997 {
998 kauth_cred_t cred = p->p_ucred;
999 struct image_params image_params, *imgp;
1000 struct vnode_attr va;
1001 struct vnode_attr origva;
1002 struct nameidata nd;
1003 struct uthread *uthread;
1004 int i;
1005 int resid, error;
1006 task_t task;
1007 int numthreads;
1008 int vfexec=0;
1009 int once = 1; /* save SGUID-ness for interpreted files */
1010 char alt_p_comm[sizeof(p->p_comm)] = {0}; /* for PowerPC */
1011 int is_64 = IS_64BIT_PROCESS(p);
1012 int seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32);
1013 struct vfs_context context;
1014
1015 context.vc_proc = p;
1016 context.vc_ucred = p->p_ucred; /* XXX must NOT be kauth_cred_get() */
1017
1018
1019 imgp = &image_params;
1020
1021 /* Initialize the common data in the image_params structure */
1022 bzero(imgp, sizeof(*imgp));
1023 imgp->ip_user_fname = uap->fname;
1024 imgp->ip_user_argv = uap->argp;
1025 imgp->ip_user_envv = uap->envp;
1026 imgp->ip_vattr = &va;
1027 imgp->ip_origvattr = &origva;
1028 imgp->ip_vfs_context = &context;
1029 imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT : IMGPF_NONE);
1030 imgp->ip_tws_cache_name = NULL;
1031 imgp->ip_p_comm = alt_p_comm; /* for PowerPC */
1032
1033 /*
1034 * XXXAUDIT: Currently, we only audit the pathname of the binary.
1035 * There may also be poor interaction with dyld.
1036 */
1037
1038 task = current_task();
1039 uthread = get_bsdthread_info(current_thread());
1040
1041 if (uthread->uu_flag & UT_VFORK) {
1042 vfexec = 1; /* Mark in exec */
1043 } else {
1044 if (task != kernel_task) {
1045 numthreads = get_task_numacts(task);
1046 if (numthreads <= 0 )
1047 return(EINVAL);
1048 if (numthreads > 1) {
1049 return(ENOTSUP);
1050 }
1051 }
1052 }
1053
1054 error = execargs_alloc(imgp);
1055 if (error)
1056 return(error);
1057
1058 /*
1059 * XXXAUDIT: Note: the double copyin introduces an audit
1060 * race. To correct this race, we must use a single
1061 * copyin(), e.g. by passing a flag to namei to indicate an
1062 * external path buffer is being used.
1063 */
1064 error = exec_save_path(imgp, uap->fname, seg);
1065 if (error) {
1066 execargs_free(imgp);
1067 return(error);
1068 }
1069
1070 /*
1071 * No app profiles under chroot
1072 */
1073 if((p->p_fd->fd_rdir == NULLVP) && (app_profile != 0)) {
1074
1075 /* grab the name of the file out of its path */
1076 /* we will need this for lookup within the */
1077 /* name file */
1078 /* Scan backwards for the first '/' or start of string */
1079 imgp->ip_tws_cache_name = imgp->ip_strendp;
1080 while (imgp->ip_tws_cache_name[0] != '/') {
1081 if(imgp->ip_tws_cache_name == imgp->ip_strings) {
1082 imgp->ip_tws_cache_name--;
1083 break;
1084 }
1085 imgp->ip_tws_cache_name--;
1086 }
1087 imgp->ip_tws_cache_name++;
1088 }
1089 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNPATH1,
1090 seg, uap->fname, imgp->ip_vfs_context);
1091
1092 again:
1093 error = namei(&nd);
1094 if (error)
1095 goto bad;
1096 imgp->ip_ndp = &nd; /* successful namei(); call nameidone() later */
1097 imgp->ip_vp = nd.ni_vp; /* if set, need to vnode_put() at some point */
1098
1099 error = exec_check_permissions(imgp);
1100 if (error)
1101 goto bad;
1102
1103 /* Copy; avoid invocation of an interpreter overwriting the original */
1104 if (once) {
1105 once = 0;
1106 origva = va;
1107 }
1108
1109 error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata, PAGE_SIZE, 0,
1110 UIO_SYSSPACE32, IO_NODELOCKED, cred, &resid, p);
1111 if (error)
1112 goto bad;
1113
1114 encapsulated_binary:
1115 error = -1;
1116 for(i = 0; error == -1 && execsw[i].ex_imgact != NULL; i++) {
1117
1118 error = (*execsw[i].ex_imgact)(imgp);
1119
1120 switch (error) {
1121 /* case -1: not claimed: continue */
1122 case -2: /* Encapsulated binary */
1123 goto encapsulated_binary;
1124
1125 case -3: /* Interpreter */
1126 vnode_put(imgp->ip_vp);
1127 imgp->ip_vp = NULL; /* already put */
1128 nd.ni_cnd.cn_nameiop = LOOKUP;
1129 nd.ni_cnd.cn_flags = (nd.ni_cnd.cn_flags & HASBUF) |
1130 (FOLLOW | LOCKLEAF);
1131
1132 #ifdef IMGPF_POWERPC
1133 /*
1134 * PowerPC does not follow symlinks because the
1135 * code which sets exec_archhandler_ppc.fsid and
1136 * exec_archhandler_ppc.fileid doesn't follow them.
1137 */
1138 if (imgp->ip_flags & IMGPF_POWERPC)
1139 nd.ni_cnd.cn_flags &= ~FOLLOW;
1140 #endif /* IMGPF_POWERPC */
1141
1142 nd.ni_segflg = UIO_SYSSPACE32;
1143 nd.ni_dirp = CAST_USER_ADDR_T(imgp->ip_interp_name);
1144 goto again;
1145
1146 default:
1147 break;
1148 }
1149 }
1150
1151 /* call out to allow 3rd party notification of exec.
1152 * Ignore result of kauth_authorize_fileop call.
1153 */
1154 if (error == 0 && kauth_authorize_fileop_has_listeners()) {
1155 kauth_authorize_fileop(vfs_context_ucred(&context), KAUTH_FILEOP_EXEC,
1156 (uintptr_t)nd.ni_vp, 0);
1157 }
1158
1159 /* Image not claimed by any activator? */
1160 if (error == -1)
1161 error = ENOEXEC;
1162
1163 bad:
1164 if (imgp->ip_ndp)
1165 nameidone(imgp->ip_ndp);
1166 if (imgp->ip_vp)
1167 vnode_put(imgp->ip_vp);
1168 if (imgp->ip_strings)
1169 execargs_free(imgp);
1170 if (!error && vfexec) {
1171 vfork_return(current_thread(), p->p_pptr, p, retval);
1172 (void)thread_resume(imgp->ip_vfork_thread);
1173 return(0);
1174 }
1175 return(error);
1176 }
1177
1178
1179 static int
1180 copyinptr(user_addr_t froma, user_addr_t *toptr, int ptr_size)
1181 {
1182 int error;
1183
1184 if (ptr_size == 4) {
1185 /* 64 bit value containing 32 bit address */
1186 unsigned int i;
1187
1188 error = copyin(froma, &i, 4);
1189 *toptr = CAST_USER_ADDR_T(i); /* SAFE */
1190 } else {
1191 error = copyin(froma, toptr, 8);
1192 }
1193 return (error);
1194 }
1195
1196
1197 static int
1198 copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size)
1199 {
1200 int error;
1201
1202 if (ptr_size == 4) {
1203 /* 64 bit value containing 32 bit address */
1204 unsigned int i = CAST_DOWN(unsigned int,ua); /* SAFE */
1205
1206 error = copyout(&i, ptr, 4);
1207 } else {
1208 error = copyout(&ua, ptr, 8);
1209 }
1210 return (error);
1211 }
1212
1213
1214 /*
1215 * exec_copyout_strings
1216 *
1217 * Copy out the strings segment to user space. The strings segment is put
1218 * on a preinitialized stack frame.
1219 *
1220 * Parameters: struct image_params * the image parameter block
1221 * int * a pointer to the stack offset variable
1222 *
1223 * Returns: 0 Success
1224 * !0 Faiure: errno
1225 *
1226 * Implicit returns:
1227 * (*stackp) The stack offset, modified
1228 *
1229 * Note: The strings segment layout is backward, from the beginning
1230 * of the top of the stack to consume the minimal amount of
1231 * space possible; the returned stack pointer points to the
1232 * end of the area consumed (stacks grow upward).
1233 *
1234 * argc is an int; arg[i] are pointers; env[i] are pointers;
1235 * exec_path is a pointer; the 0's are (void *)NULL's
1236 *
1237 * The stack frame layout is:
1238 *
1239 * +-------------+
1240 * sp-> | argc |
1241 * +-------------+
1242 * | arg[0] |
1243 * +-------------+
1244 * :
1245 * :
1246 * +-------------+
1247 * | arg[argc-1] |
1248 * +-------------+
1249 * | 0 |
1250 * +-------------+
1251 * | env[0] |
1252 * +-------------+
1253 * :
1254 * :
1255 * +-------------+
1256 * | env[n] |
1257 * +-------------+
1258 * | 0 |
1259 * +-------------+
1260 * | exec_path | In MacOS X PR2 Beaker2E the path passed to exec() is
1261 * +-------------+ passed on the stack just after the trailing 0 of the
1262 * | 0 | the envp[] array as a pointer to a string.
1263 * +-------------+
1264 * | PATH AREA |
1265 * +-------------+
1266 * | STRING AREA |
1267 * :
1268 * :
1269 * | | <- p->user_stack
1270 * +-------------+
1271 *
1272 * Although technically a part of the STRING AREA, we treat the PATH AREA as
1273 * a separate entity. This allows us to align the beginning of the PATH AREA
1274 * to a pointer boundary so that the exec_path, env[i], and argv[i] pointers
1275 * which preceed it on the stack are properly aligned.
1276 *
1277 * TODO: argc copied with suword(), which takes a 64 bit address
1278 */
1279 static int
1280 exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp)
1281 {
1282 struct proc *p = vfs_context_proc(imgp->ip_vfs_context);
1283 int ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT) ? 8 : 4;
1284 char *argv = imgp->ip_argv; /* modifiable copy of argv */
1285 user_addr_t string_area; /* *argv[], *env[] */
1286 user_addr_t path_area; /* package launch path */
1287 user_addr_t ptr_area; /* argv[], env[], exec_path */
1288 user_addr_t stack;
1289 int stringc = imgp->ip_argc + imgp->ip_envc;
1290 int len;
1291 int error;
1292 int strspace;
1293
1294 stack = *stackp;
1295
1296 unsigned patharea_len = imgp->ip_argv - imgp->ip_strings;
1297 int envc_add = 0;
1298
1299 #ifdef IMGPF_POWERPC
1300 /*
1301 * oah750 expects /usr/lib/dyld\0 as the start of the program name.
1302 * It also expects to have a certain environment variable set to 0.
1303 * 50 bytes for each to ensure we have enough space without having
1304 * to count every byte.
1305 */
1306 char *progname, *envvar;
1307 char progname_str[] = "/usr/lib/dyld";
1308 char envvar_str[] = "OAH750_CFG_FU_STACK_SIZE=0";
1309
1310 if (imgp->ip_flags & IMGPF_POWERPC) {
1311 progname = progname_str;
1312 envvar = envvar_str;
1313 patharea_len += strlen(progname) + strlen(envvar) + 2;
1314 envc_add = 1;
1315 }
1316 #endif /* IMGPF_POWERPC */
1317 /*
1318 * Set up pointers to the beginning of the string area, the beginning
1319 * of the path area, and the beginning of the pointer area (actually,
1320 * the location of argc, an int, which may be smaller than a pointer,
1321 * but we use ptr_size worth of space for it, for alignment).
1322 */
1323 string_area = stack - (((imgp->ip_strendp - imgp->ip_strings) + ptr_size-1) & ~(ptr_size-1)) - ptr_size;
1324 path_area = string_area - ((patharea_len + ptr_size-1) & ~(ptr_size-1));
1325 ptr_area = path_area - ((imgp->ip_argc + imgp->ip_envc + 4 + envc_add) * ptr_size) - ptr_size /*argc*/;
1326
1327 /* Return the initial stack address: the location of argc */
1328 *stackp = ptr_area;
1329
1330 /*
1331 * Record the size of the arguments area so that sysctl_procargs()
1332 * can return the argument area without having to parse the arguments.
1333 */
1334 p->p_argc = imgp->ip_argc;
1335 p->p_argslen = (int)(stack - path_area);
1336
1337
1338 /*
1339 * Support for new app package launching for Mac OS X allocates
1340 * the "path" at the begining of the imgp->ip_strings buffer.
1341 * copy it just before the string area.
1342 */
1343 len = 0;
1344 #ifdef IMGPF_POWERPC
1345 if (imgp->ip_flags & IMGPF_POWERPC) {
1346 error = copyoutstr(progname, path_area,
1347 patharea_len,
1348 (size_t *)&len);
1349 if (error)
1350 goto bad;
1351 error = copyoutstr(imgp->ip_strings, path_area + strlen(progname) + 1,
1352 patharea_len,
1353 (size_t *)&len);
1354 } else
1355 #endif /* IMGPF_POWERPC */
1356 error = copyoutstr(imgp->ip_strings, path_area,
1357 patharea_len,
1358 (size_t *)&len);
1359 if (error)
1360 goto bad;
1361
1362
1363 /* Save a NULL pointer below it */
1364 (void)copyoutptr(0LL, path_area - ptr_size, ptr_size);
1365
1366 /* Save the pointer to "path" just below it */
1367 (void)copyoutptr(path_area, path_area - 2*ptr_size, ptr_size);
1368
1369 /*
1370 * ptr_size for 2 NULL one each ofter arg[argc -1] and env[n]
1371 * ptr_size for argc
1372 * skip over saved path, ptr_size for pointer to path,
1373 * and ptr_size for the NULL after pointer to path.
1374 */
1375
1376 /* argc (int32, stored in a ptr_size area) */
1377 (void)suword(ptr_area, imgp->ip_argc);
1378 ptr_area += sizeof(int);
1379 /* pad to ptr_size, if 64 bit image, to ensure user stack alignment */
1380 if (imgp->ip_flags & IMGPF_IS_64BIT) {
1381 (void)suword(ptr_area, 0); /* int, not long: ignored */
1382 ptr_area += sizeof(int);
1383 }
1384
1385
1386 /*
1387 * We use (string_area - path_area) here rather than the more
1388 * intuitive (imgp->ip_argv - imgp->ip_strings) because we are
1389 * interested in the length of the PATH_AREA in user space,
1390 * rather than the actual length of the execution path, since
1391 * it includes alignment padding of the PATH_AREA + STRING_AREA
1392 * to a ptr_size boundary.
1393 */
1394 strspace = SIZE_IMG_STRSPACE - (string_area - path_area);
1395 for (;;) {
1396 if (stringc == imgp->ip_envc) {
1397 /* argv[n] = NULL */
1398 (void)copyoutptr(0LL, ptr_area, ptr_size);
1399 ptr_area += ptr_size;
1400 #ifdef IMGPF_POWERPC
1401 if (envc_add) {
1402 (void)copyoutptr(string_area, ptr_area, ptr_size);
1403
1404 do {
1405 if (strspace <= 0) {
1406 error = E2BIG;
1407 break;
1408 }
1409 error = copyoutstr(envvar, string_area,
1410 (unsigned)strspace,
1411 (size_t *)&len);
1412 string_area += len;
1413 envvar += len;
1414 strspace -= len;
1415 } while (error == ENAMETOOLONG);
1416 if (error == EFAULT || error == E2BIG)
1417 break;
1418 ptr_area += ptr_size;
1419 }
1420 #endif /* IMGPF_POWERPC */
1421 }
1422 if (--stringc < 0)
1423 break;
1424
1425 /* pointer: argv[n]/env[n] */
1426 (void)copyoutptr(string_area, ptr_area, ptr_size);
1427
1428 /* string : argv[n][]/env[n][] */
1429 do {
1430 if (strspace <= 0) {
1431 error = E2BIG;
1432 break;
1433 }
1434 error = copyoutstr(argv, string_area,
1435 (unsigned)strspace,
1436 (size_t *)&len);
1437 string_area += len;
1438 argv += len;
1439 strspace -= len;
1440 } while (error == ENAMETOOLONG);
1441 if (error == EFAULT || error == E2BIG)
1442 break; /* bad stack - user's problem */
1443 ptr_area += ptr_size;
1444 }
1445 /* env[n] = NULL */
1446 (void)copyoutptr(0LL, ptr_area, ptr_size);
1447
1448 bad:
1449 return(error);
1450 }
1451
1452
1453 /*
1454 * exec_extract_strings
1455 *
1456 * Copy arguments and environment from user space into work area; we may
1457 * have already copied some early arguments into the work area, and if
1458 * so, any arguments opied in are appended to those already there.
1459 *
1460 * Parameters: struct image_params * the image parameter block
1461 *
1462 * Returns: 0 Success
1463 * !0 Failure: errno
1464 *
1465 * Implicit returns;
1466 * (imgp->ip_argc) Count of arguments, updated
1467 * (imgp->ip_envc) Count of environment strings, updated
1468 *
1469 *
1470 * Notes: The argument and environment vectors are user space pointers
1471 * to arrays of user space pointers.
1472 */
1473 static int
1474 exec_extract_strings(struct image_params *imgp)
1475 {
1476 int error = 0;
1477 struct proc *p = vfs_context_proc(imgp->ip_vfs_context);
1478 int seg = (IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32);
1479 int ptr_size = (imgp->ip_flags & IMGPF_WAS_64BIT) ? 8 : 4;
1480 user_addr_t argv = imgp->ip_user_argv;
1481 user_addr_t envv = imgp->ip_user_envv;
1482
1483 /* Now, get rest of arguments */
1484
1485 /*
1486 * If we are running an interpreter, replace the av[0] that was
1487 * passed to execve() with the fully qualified path name that was
1488 * passed to execve() for interpreters which do not use the PATH
1489 * to locate their script arguments.
1490 */
1491 if((imgp->ip_flags & IMGPF_INTERPRET) != 0 && argv != 0LL) {
1492 user_addr_t arg;
1493
1494 error = copyinptr(argv, &arg, ptr_size);
1495 if (error)
1496 goto bad;
1497 if (arg != 0LL && arg != (user_addr_t)-1) {
1498 argv += ptr_size;
1499 error = exec_add_string(imgp, imgp->ip_user_fname, seg);
1500 if (error)
1501 goto bad;
1502 imgp->ip_argc++;
1503 }
1504 }
1505
1506 while (argv != 0LL) {
1507 user_addr_t arg;
1508
1509 error = copyinptr(argv, &arg, ptr_size);
1510 if (error)
1511 goto bad;
1512
1513 argv += ptr_size;
1514 if (arg == 0LL) {
1515 break;
1516 } else if (arg == (user_addr_t)-1) {
1517 /* Um... why would it be -1? */
1518 error = EFAULT;
1519 goto bad;
1520 }
1521 /*
1522 * av[n...] = arg[n]
1523 */
1524 error = exec_add_string(imgp, arg, seg);
1525 if (error)
1526 goto bad;
1527 imgp->ip_argc++;
1528 }
1529
1530 /* Now, get the environment */
1531 while (envv != 0LL) {
1532 user_addr_t env;
1533
1534 error = copyinptr(envv, &env, ptr_size);
1535 if (error)
1536 goto bad;
1537
1538 envv += ptr_size;
1539 if (env == 0LL) {
1540 break;
1541 } else if (env == (user_addr_t)-1) {
1542 error = EFAULT;
1543 goto bad;
1544 }
1545 /*
1546 * av[n...] = env[n]
1547 */
1548 error = exec_add_string(imgp, env, seg);
1549 if (error)
1550 goto bad;
1551 imgp->ip_envc++;
1552 }
1553 bad:
1554 return error;
1555 }
1556
1557
1558 #define unix_stack_size(p) (p->p_rlimit[RLIMIT_STACK].rlim_cur)
1559
1560 static int
1561 exec_check_permissions(struct image_params *imgp)
1562 {
1563 struct vnode *vp = imgp->ip_vp;
1564 struct vnode_attr *vap = imgp->ip_vattr;
1565 struct proc *p = vfs_context_proc(imgp->ip_vfs_context);
1566 int error;
1567 kauth_action_t action;
1568
1569 /* Only allow execution of regular files */
1570 if (!vnode_isreg(vp))
1571 return (EACCES);
1572
1573 /* Get the file attributes that we will be using here and elsewhere */
1574 VATTR_INIT(vap);
1575 VATTR_WANTED(vap, va_uid);
1576 VATTR_WANTED(vap, va_gid);
1577 VATTR_WANTED(vap, va_mode);
1578 VATTR_WANTED(vap, va_fsid);
1579 VATTR_WANTED(vap, va_fileid);
1580 VATTR_WANTED(vap, va_data_size);
1581 if ((error = vnode_getattr(vp, vap, imgp->ip_vfs_context)) != 0)
1582 return (error);
1583
1584 /*
1585 * Ensure that at least one execute bit is on - otherwise root
1586 * will always succeed, and we don't want to happen unless the
1587 * file really is executable.
1588 */
1589 if ((vap->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0)
1590 return (EACCES);
1591
1592 /* Disallow zero length files */
1593 if (vap->va_data_size == 0)
1594 return (ENOEXEC);
1595
1596 imgp->ip_arch_offset = (user_size_t)0;
1597 imgp->ip_arch_size = vap->va_data_size;
1598
1599 /* Disable setuid-ness for traced programs or if MNT_NOSUID */
1600 if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_flag & P_TRACED))
1601 vap->va_mode &= ~(VSUID | VSGID);
1602
1603 /* Check for execute permission */
1604 action = KAUTH_VNODE_EXECUTE;
1605 /* Traced images must also be readable */
1606 if (p->p_flag & P_TRACED)
1607 action |= KAUTH_VNODE_READ_DATA;
1608 if ((error = vnode_authorize(vp, NULL, action, imgp->ip_vfs_context)) != 0)
1609 return (error);
1610
1611 /* Don't let it run if anyone had it open for writing */
1612 if (vp->v_writecount)
1613 return (ETXTBSY);
1614
1615 #ifdef IMGPF_POWERPC
1616 /*
1617 * If the file we are about to attempt to load is the exec_handler_ppc,
1618 * which is determined by matching the vattr fields against previously
1619 * cached values, then we set the PowerPC environment flag.
1620 */
1621 if (vap->va_fsid == exec_archhandler_ppc.fsid &&
1622 vap->va_fileid == (uint64_t)((u_long)exec_archhandler_ppc.fileid)) {
1623 imgp->ip_flags |= IMGPF_POWERPC;
1624 }
1625 #endif /* IMGPF_POWERPC */
1626
1627 /* XXX May want to indicate to underlying FS that vnode is open */
1628
1629 return (error);
1630 }
1631
1632 /*
1633 * exec_handle_sugid
1634 *
1635 * Initially clear the P_SUGID in the process flags; if an SUGID process is
1636 * exec'ing a non-SUGID image, then this is the point of no return.
1637 *
1638 * If the image being activated is SUGI, then replace the credential with a
1639 * copy, disable tracing (unless the tracing process is root), reset the
1640 * mach task port to revoke it, set the P_SUGID bit,
1641 *
1642 * If the saved user and group ID will be changing, then make sure it happens
1643 * to a new credential, rather than a shared one.
1644 *
1645 * Set the security token (this is probably obsolete, given that the token
1646 * should not technically be separate from the credential itself).
1647 *
1648 * Parameters: struct image_params * the image parameter block
1649 *
1650 * Returns: void No failure indication
1651 *
1652 * Implicit returns:
1653 * <process credential> Potentially modified/replaced
1654 * <task port> Potentially revoked
1655 * <process flags> P_SUGID bit potentially modified
1656 * <security token> Potentially modified
1657 */
1658 static int
1659 exec_handle_sugid(struct image_params *imgp)
1660 {
1661 kauth_cred_t cred = vfs_context_ucred(imgp->ip_vfs_context);
1662 struct proc *p = vfs_context_proc(imgp->ip_vfs_context);
1663 int i;
1664 int error = 0;
1665 static struct vnode *dev_null = NULLVP;
1666
1667 p->p_flag &= ~P_SUGID;
1668
1669 if (((imgp->ip_origvattr->va_mode & VSUID) != 0 &&
1670 kauth_cred_getuid(cred) != imgp->ip_origvattr->va_uid) ||
1671 ((imgp->ip_origvattr->va_mode & VSGID) != 0 &&
1672 cred->cr_gid != imgp->ip_origvattr->va_gid)) {
1673 #if KTRACE
1674 /*
1675 * If process is being ktraced, turn off - unless
1676 * root set it.
1677 */
1678 if (p->p_tracep && !(p->p_traceflag & KTRFAC_ROOT)) {
1679 struct vnode *tvp = p->p_tracep;
1680 p->p_tracep = NULL;
1681 p->p_traceflag = 0;
1682 vnode_rele(tvp);
1683 }
1684 #endif
1685 /*
1686 * Replace the credential with a copy of itself if euid or egid change.
1687 */
1688 if (imgp->ip_origvattr->va_mode & VSUID) {
1689 p->p_ucred = kauth_cred_seteuid(p->p_ucred, imgp->ip_origvattr->va_uid);
1690 }
1691 if (imgp->ip_origvattr->va_mode & VSGID) {
1692 p->p_ucred = kauth_cred_setegid(p->p_ucred, imgp->ip_origvattr->va_gid);
1693 }
1694
1695 /*
1696 * Have mach reset the task port. We don't want
1697 * anyone who had the task port before a setuid
1698 * exec to be able to access/control the task
1699 * after.
1700 */
1701 if (current_task() == p->task)
1702 ipc_task_reset(p->task);
1703
1704 p->p_flag |= P_SUGID;
1705
1706 /* Cache the vnode for /dev/null the first time around */
1707 if (dev_null == NULLVP) {
1708 struct nameidata nd1;
1709
1710 NDINIT(&nd1, LOOKUP, FOLLOW, UIO_SYSSPACE32,
1711 CAST_USER_ADDR_T("/dev/null"),
1712 imgp->ip_vfs_context);
1713
1714 if ((error = vn_open(&nd1, FREAD, 0)) == 0) {
1715 dev_null = nd1.ni_vp;
1716 /*
1717 * vn_open returns with both a use_count
1718 * and an io_count on the found vnode
1719 * drop the io_count, but keep the use_count
1720 */
1721 vnode_put(nd1.ni_vp);
1722 }
1723 }
1724
1725 /* Radar 2261856; setuid security hole fix */
1726 /* Patch from OpenBSD: A. Ramesh */
1727 /*
1728 * XXX For setuid processes, attempt to ensure that
1729 * stdin, stdout, and stderr are already allocated.
1730 * We do not want userland to accidentally allocate
1731 * descriptors in this range which has implied meaning
1732 * to libc.
1733 */
1734 if (dev_null != NULLVP) {
1735 for (i = 0; i < 3; i++) {
1736 struct fileproc *fp;
1737 int indx;
1738
1739 if (p->p_fd->fd_ofiles[i] != NULL)
1740 continue;
1741
1742 if ((error = falloc(p, &fp, &indx)) != 0)
1743 continue;
1744
1745 if ((error = vnode_ref_ext(dev_null, FREAD)) != 0) {
1746 fp_free(p, indx, fp);
1747 break;
1748 }
1749
1750 fp->f_fglob->fg_flag = FREAD;
1751 fp->f_fglob->fg_type = DTYPE_VNODE;
1752 fp->f_fglob->fg_ops = &vnops;
1753 fp->f_fglob->fg_data = (caddr_t)dev_null;
1754
1755 proc_fdlock(p);
1756 *fdflags(p, indx) &= ~UF_RESERVED;
1757 fp_drop(p, indx, fp, 1);
1758 proc_fdunlock(p);
1759 }
1760 /*
1761 * for now we need to drop the reference immediately
1762 * since we don't have any mechanism in place to
1763 * release it before starting to unmount "/dev"
1764 * during a reboot/shutdown
1765 */
1766 vnode_rele(dev_null);
1767 dev_null = NULLVP;
1768 }
1769 }
1770
1771 /*
1772 * Implement the semantic where the effective user and group become
1773 * the saved user and group in exec'ed programs.
1774 */
1775 p->p_ucred = kauth_cred_setsvuidgid(p->p_ucred, kauth_cred_getuid(p->p_ucred), p->p_ucred->cr_gid);
1776
1777 /* XXX Obsolete; security token should not be separate from cred */
1778 set_security_token(p);
1779
1780 return(error);
1781 }
1782
1783 static kern_return_t
1784 create_unix_stack(vm_map_t map, user_addr_t user_stack, int customstack,
1785 struct proc *p)
1786 {
1787 mach_vm_size_t size;
1788 mach_vm_offset_t addr;
1789
1790 p->user_stack = user_stack;
1791 if (!customstack) {
1792 size = mach_vm_round_page(unix_stack_size(p));
1793 addr = mach_vm_trunc_page(user_stack - size);
1794 return (mach_vm_allocate(map, &addr, size,
1795 VM_MAKE_TAG(VM_MEMORY_STACK) |
1796 VM_FLAGS_FIXED));
1797 } else
1798 return(KERN_SUCCESS);
1799 }
1800
1801 #include <sys/reboot.h>
1802
1803 static char init_program_name[128] = "/sbin/launchd";
1804 static const char * other_init = "/sbin/mach_init";
1805
1806 char init_args[128] = "";
1807
1808 struct execve_args init_exec_args;
1809 int init_attempts = 0;
1810
1811
1812 void
1813 load_init_program(struct proc *p)
1814 {
1815 vm_offset_t init_addr;
1816 char *argv[3];
1817 int error;
1818 register_t retval[2];
1819
1820 error = 0;
1821
1822 /* init_args are copied in string form directly from bootstrap */
1823
1824 do {
1825 if (boothowto & RB_INITNAME) {
1826 printf("init program? ");
1827 #if FIXME /* [ */
1828 gets(init_program_name, init_program_name);
1829 #endif /* FIXME ] */
1830 }
1831
1832 if (error && ((boothowto & RB_INITNAME) == 0) &&
1833 (init_attempts == 1)) {
1834 printf("Load of %s, errno %d, trying %s\n",
1835 init_program_name, error, other_init);
1836 error = 0;
1837 bcopy(other_init, init_program_name,
1838 sizeof(other_init));
1839 }
1840
1841 init_attempts++;
1842
1843 if (error) {
1844 printf("Load of %s failed, errno %d\n",
1845 init_program_name, error);
1846 error = 0;
1847 boothowto |= RB_INITNAME;
1848 continue;
1849 }
1850
1851 /*
1852 * Copy out program name.
1853 */
1854
1855 init_addr = VM_MIN_ADDRESS;
1856 (void) vm_allocate(current_map(), &init_addr,
1857 PAGE_SIZE, VM_FLAGS_ANYWHERE);
1858 if (init_addr == 0)
1859 init_addr++;
1860
1861 (void) copyout((caddr_t) init_program_name,
1862 CAST_USER_ADDR_T(init_addr),
1863 (unsigned) sizeof(init_program_name)+1);
1864
1865 argv[0] = (char *) init_addr;
1866 init_addr += sizeof(init_program_name);
1867 init_addr = (vm_offset_t)ROUND_PTR(char, init_addr);
1868
1869 /*
1870 * Put out first (and only) argument, similarly.
1871 * Assumes everything fits in a page as allocated
1872 * above.
1873 */
1874
1875 (void) copyout((caddr_t) init_args,
1876 CAST_USER_ADDR_T(init_addr),
1877 (unsigned) sizeof(init_args));
1878
1879 argv[1] = (char *) init_addr;
1880 init_addr += sizeof(init_args);
1881 init_addr = (vm_offset_t)ROUND_PTR(char, init_addr);
1882
1883 /*
1884 * Null-end the argument list
1885 */
1886
1887 argv[2] = (char *) 0;
1888
1889 /*
1890 * Copy out the argument list.
1891 */
1892
1893 (void) copyout((caddr_t) argv,
1894 CAST_USER_ADDR_T(init_addr),
1895 (unsigned) sizeof(argv));
1896
1897 /*
1898 * Set up argument block for fake call to execve.
1899 */
1900
1901 init_exec_args.fname = CAST_USER_ADDR_T(argv[0]);
1902 init_exec_args.argp = CAST_USER_ADDR_T((char **)init_addr);
1903 init_exec_args.envp = CAST_USER_ADDR_T(0);
1904
1905 /* So that mach_init task
1906 * is set with uid,gid 0 token
1907 */
1908 set_security_token(p);
1909
1910 error = execve(p,&init_exec_args,retval);
1911 } while (error);
1912 }
1913
1914 /*
1915 * Convert a load_return_t to an errno.
1916 */
1917 static int
1918 load_return_to_errno(load_return_t lrtn)
1919 {
1920 switch (lrtn) {
1921 case LOAD_SUCCESS:
1922 return 0;
1923 case LOAD_BADARCH:
1924 return EBADARCH;
1925 case LOAD_BADMACHO:
1926 return EBADMACHO;
1927 case LOAD_SHLIB:
1928 return ESHLIBVERS;
1929 case LOAD_NOSPACE:
1930 case LOAD_RESOURCE:
1931 return ENOMEM;
1932 case LOAD_PROTECT:
1933 return EACCES;
1934 case LOAD_ENOENT:
1935 return ENOENT;
1936 case LOAD_IOERROR:
1937 return EIO;
1938 case LOAD_FAILURE:
1939 default:
1940 return EBADEXEC;
1941 }
1942 }
1943
1944 #include <mach/mach_types.h>
1945 #include <mach/vm_prot.h>
1946 #include <mach/semaphore.h>
1947 #include <mach/sync_policy.h>
1948 #include <kern/clock.h>
1949 #include <mach/kern_return.h>
1950
1951 extern semaphore_t execve_semaphore;
1952
1953 /*
1954 * The block of memory used by the execve arguments. At the same time,
1955 * we allocate a page so that we can read in the first page of the image.
1956 */
1957 static int
1958 execargs_alloc(struct image_params *imgp)
1959 {
1960 kern_return_t kret;
1961
1962 kret = semaphore_wait(execve_semaphore);
1963 if (kret != KERN_SUCCESS)
1964 switch (kret) {
1965 default:
1966 return (EINVAL);
1967 case KERN_INVALID_ADDRESS:
1968 case KERN_PROTECTION_FAILURE:
1969 return (EACCES);
1970 case KERN_ABORTED:
1971 case KERN_OPERATION_TIMED_OUT:
1972 return (EINTR);
1973 }
1974
1975 kret = kmem_alloc_pageable(bsd_pageable_map, (vm_offset_t *)&imgp->ip_strings, NCARGS + PAGE_SIZE);
1976 imgp->ip_vdata = imgp->ip_strings + NCARGS;
1977 if (kret != KERN_SUCCESS) {
1978 semaphore_signal(execve_semaphore);
1979 return (ENOMEM);
1980 }
1981 return (0);
1982 }
1983
1984 static int
1985 execargs_free(struct image_params *imgp)
1986 {
1987 kern_return_t kret;
1988
1989 kmem_free(bsd_pageable_map, (vm_offset_t)imgp->ip_strings, NCARGS + PAGE_SIZE);
1990 imgp->ip_strings = NULL;
1991
1992 kret = semaphore_signal(execve_semaphore);
1993 switch (kret) {
1994 case KERN_INVALID_ADDRESS:
1995 case KERN_PROTECTION_FAILURE:
1996 return (EINVAL);
1997 case KERN_ABORTED:
1998 case KERN_OPERATION_TIMED_OUT:
1999 return (EINTR);
2000 case KERN_SUCCESS:
2001 return(0);
2002 default:
2003 return (EINVAL);
2004 }
2005 }