Unleashed v1.4
[unleashed.git] / kernel / os / exec.c
blob645fcc482a0c6ca3f6e6a7c3a83489ce5bea8386
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
23 * Copyright (c) 1988, 2010, Oracle and/or its affiliates. All rights reserved.
26 /* Copyright (c) 1988 AT&T */
27 /* All Rights Reserved */
29 * Copyright 2017 Joyent, Inc.
32 #include <sys/types.h>
33 #include <sys/param.h>
34 #include <sys/sysmacros.h>
35 #include <sys/systm.h>
36 #include <sys/signal.h>
37 #include <sys/cred_impl.h>
38 #include <sys/policy.h>
39 #include <sys/user.h>
40 #include <sys/errno.h>
41 #include <sys/file.h>
42 #include <sys/vfs.h>
43 #include <sys/vnode.h>
44 #include <sys/mman.h>
45 #include <sys/acct.h>
46 #include <sys/cpuvar.h>
47 #include <sys/proc.h>
48 #include <sys/cmn_err.h>
49 #include <sys/debug.h>
50 #include <sys/pathname.h>
51 #include <sys/vm.h>
52 #include <sys/lgrp.h>
53 #include <sys/vtrace.h>
54 #include <sys/exec.h>
55 #include <sys/exechdr.h>
56 #include <sys/kmem.h>
57 #include <sys/prsystm.h>
58 #include <sys/modctl.h>
59 #include <sys/vmparam.h>
60 #include <sys/door.h>
61 #include <sys/schedctl.h>
62 #include <sys/utrap.h>
63 #include <sys/systeminfo.h>
64 #include <sys/stack.h>
65 #include <sys/rctl.h>
66 #include <sys/dtrace.h>
67 #include <sys/lwpchan_impl.h>
68 #include <sys/pool.h>
69 #include <sys/sdt.h>
70 #include <sys/brand.h>
71 #include <sys/klpd.h>
72 #include <sys/random.h>
74 #include <vm/hat.h>
75 #include <vm/anon.h>
76 #include <vm/as.h>
77 #include <vm/seg.h>
78 #include <vm/seg_vn.h>
79 #include <vm/seg_hole.h>
81 #define PRIV_RESET 0x01 /* needs to reset privs */
82 #define PRIV_SETID 0x02 /* needs to change uids */
83 #define PRIV_SETUGID 0x04 /* is setuid/setgid/forced privs */
84 #define PRIV_INCREASE 0x08 /* child runs with more privs */
85 #define PRIV_FORCED 0x20 /* has forced privileges */
87 static int execsetid(struct vnode *, struct vattr *, uid_t *, uid_t *,
88 priv_set_t *, cred_t *, const char *);
89 static int hold_execsw(struct execsw *);
91 uint_t auxv_hwcap = 0; /* auxv AT_SUN_HWCAP value; determined on the fly */
92 uint_t auxv_hwcap_2 = 0; /* AT_SUN_HWCAP2 */
93 #if defined(_SYSCALL32_IMPL)
94 uint_t auxv_hwcap32 = 0; /* 32-bit version of auxv_hwcap */
95 uint_t auxv_hwcap32_2 = 0; /* 32-bit version of auxv_hwcap2 */
96 #endif
98 #define PSUIDFLAGS (SNOCD|SUGID)
101 * These are consumed within the specific exec modules, but are defined here
102 * because
104 * 1) The exec modules are unloadable, which would make this near useless.
106 * 2) We want them to be common across all of them, should more than ELF come
107 * to support them.
109 * All must be powers of 2.
111 size_t aslr_max_brk_skew = 16 * 1024 * 1024; /* 16MB */
112 #pragma weak exec_stackgap = aslr_max_stack_skew /* Old, compatible name */
113 size_t aslr_max_stack_skew = 64 * 1024; /* 64KB */
116 * Size of guard segment for 64-bit processes and minimum size it can be shrunk
117 * to in the case of grow() operations. These are kept as variables in case
118 * they need to be tuned in an emergency.
120 size_t stack_guard_seg_sz = 256 * 1024 * 1024;
121 size_t stack_guard_min_sz = 64 * 1024 * 1024;
124 * exece() - system call wrapper around exec_common()
127 exece(const char *fname, const char **argp, const char **envp)
129 int error;
131 error = exec_common(fname, argp, envp, EBA_NONE);
132 return (error ? (set_errno(error)) : 0);
136 exec_common(const char *fname, const char **argp, const char **envp,
137 int brand_action)
139 vnode_t *vp = NULL, *dir = NULL, *tmpvp = NULL;
140 proc_t *p = ttoproc(curthread);
141 klwp_t *lwp = ttolwp(curthread);
142 struct user *up = PTOU(p);
143 long execsz; /* temporary count of exec size */
144 int i;
145 int error;
146 char exec_file[MAXCOMLEN+1];
147 struct pathname pn;
148 struct pathname resolvepn;
149 struct uarg args;
150 struct execa ua;
151 k_sigset_t savedmask;
152 lwpdir_t *lwpdir = NULL;
153 tidhash_t *tidhash;
154 lwpdir_t *old_lwpdir = NULL;
155 uint_t old_lwpdir_sz;
156 tidhash_t *old_tidhash;
157 uint_t old_tidhash_sz;
158 ret_tidhash_t *ret_tidhash;
159 lwpent_t *lep;
160 boolean_t brandme = B_FALSE;
163 * exec() is not supported for the /proc agent lwp.
165 if (curthread == p->p_agenttp)
166 return (ENOTSUP);
168 if (brand_action != EBA_NONE) {
170 * Brand actions are not supported for processes that are not
171 * running in a branded zone.
173 if (!ZONE_IS_BRANDED(p->p_zone))
174 return (ENOTSUP);
176 if (brand_action == EBA_NATIVE) {
177 /* Only branded processes can be unbranded */
178 if (!PROC_IS_BRANDED(p))
179 return (ENOTSUP);
180 } else {
181 /* Only unbranded processes can be branded */
182 if (PROC_IS_BRANDED(p))
183 return (ENOTSUP);
184 brandme = B_TRUE;
186 } else {
188 * If this is a native zone, or if the process is already
189 * branded, then we don't need to do anything. If this is
190 * a native process in a branded zone, we need to brand the
191 * process as it exec()s the new binary.
193 if (ZONE_IS_BRANDED(p->p_zone) && !PROC_IS_BRANDED(p))
194 brandme = B_TRUE;
198 * Inform /proc that an exec() has started.
199 * Hold signals that are ignored by default so that we will
200 * not be interrupted by a signal that will be ignored after
201 * successful completion of gexec().
203 mutex_enter(&p->p_lock);
204 prexecstart();
205 schedctl_finish_sigblock(curthread);
206 savedmask = curthread->t_hold;
207 sigorset(&curthread->t_hold, &ignoredefault);
208 mutex_exit(&p->p_lock);
211 * Look up path name and remember last component for later.
212 * To help coreadm expand its %d token, we attempt to save
213 * the directory containing the executable in p_execdir. The
214 * first call to lookuppn() may fail and return EINVAL because
215 * dirvpp is non-NULL. In that case, we make a second call to
216 * lookuppn() with dirvpp set to NULL; p_execdir will be NULL,
217 * but coreadm is allowed to expand %d to the empty string and
218 * there are other cases in which that failure may occur.
220 if ((error = pn_get((char *)fname, UIO_USERSPACE, &pn)) != 0)
221 goto out;
222 pn_alloc(&resolvepn);
223 if ((error = lookuppn(&pn, &resolvepn, FOLLOW, &dir, &vp)) != 0) {
224 pn_free(&resolvepn);
225 pn_free(&pn);
226 if (error != EINVAL)
227 goto out;
229 dir = NULL;
230 if ((error = pn_get((char *)fname, UIO_USERSPACE, &pn)) != 0)
231 goto out;
232 pn_alloc(&resolvepn);
233 if ((error = lookuppn(&pn, &resolvepn, FOLLOW, NULLVPP,
234 &vp)) != 0) {
235 pn_free(&resolvepn);
236 pn_free(&pn);
237 goto out;
240 if (vp == NULL) {
241 if (dir != NULL)
242 VN_RELE(dir);
243 error = ENOENT;
244 pn_free(&resolvepn);
245 pn_free(&pn);
246 goto out;
249 if ((error = secpolicy_basic_exec(CRED(), vp)) != 0) {
250 if (dir != NULL)
251 VN_RELE(dir);
252 pn_free(&resolvepn);
253 pn_free(&pn);
254 VN_RELE(vp);
255 goto out;
259 * We do not allow executing files in attribute directories.
260 * We test this by determining whether the resolved path
261 * contains a "/" when we're in an attribute directory;
262 * only if the pathname does not contain a "/" the resolved path
263 * points to a file in the current working (attribute) directory.
265 if ((p->p_user.u_cdir->v_flag & V_XATTRDIR) != 0 &&
266 strchr(resolvepn.pn_path, '/') == NULL) {
267 if (dir != NULL)
268 VN_RELE(dir);
269 error = EACCES;
270 pn_free(&resolvepn);
271 pn_free(&pn);
272 VN_RELE(vp);
273 goto out;
276 bzero(exec_file, MAXCOMLEN+1);
277 (void) strncpy(exec_file, pn.pn_path, MAXCOMLEN);
278 bzero(&args, sizeof (args));
279 args.pathname = resolvepn.pn_path;
280 /* don't free resolvepn until we are done with args */
281 pn_free(&pn);
284 * If we're running in a profile shell, then call pfexecd.
286 if ((CR_FLAGS(p->p_cred) & PRIV_PFEXEC) != 0) {
287 error = pfexec_call(p->p_cred, &resolvepn, &args.pfcred,
288 &args.scrubenv);
290 /* Returning errno in case we're not allowed to execute. */
291 if (error > 0) {
292 if (dir != NULL)
293 VN_RELE(dir);
294 pn_free(&resolvepn);
295 VN_RELE(vp);
296 goto out;
299 /* Don't change the credentials when using old ptrace. */
300 if (args.pfcred != NULL &&
301 (p->p_proc_flag & P_PR_PTRACE) != 0) {
302 crfree(args.pfcred);
303 args.pfcred = NULL;
304 args.scrubenv = B_FALSE;
309 * Specific exec handlers, or policies determined via
310 * /etc/system may override the historical default.
312 args.stk_prot = PROT_ZFOD;
313 args.dat_prot = PROT_ZFOD;
315 CPU_STATS_ADD_K(sys, sysexec, 1);
316 DTRACE_PROC1(exec, char *, args.pathname);
318 ua.fname = fname;
319 ua.argp = argp;
320 ua.envp = envp;
322 /* If necessary, brand this process before we start the exec. */
323 if (brandme)
324 brand_setbrand(p);
326 if ((error = gexec(&vp, &ua, &args, NULL, 0, &execsz,
327 exec_file, p->p_cred, brand_action)) != 0) {
328 if (brandme)
329 brand_clearbrand(p, B_FALSE);
330 VN_RELE(vp);
331 if (dir != NULL)
332 VN_RELE(dir);
333 pn_free(&resolvepn);
334 goto fail;
338 * Free floating point registers (sun4u only)
340 ASSERT(lwp != NULL);
341 lwp_freeregs(lwp, 1);
344 * Free thread and process context ops.
346 if (curthread->t_ctx)
347 freectx(curthread, 1);
348 if (p->p_pctx)
349 freepctx(p, 1);
352 * Remember file name for accounting; clear any cached DTrace predicate.
354 up->u_acflag &= ~AFORK;
355 bcopy(exec_file, up->u_comm, MAXCOMLEN+1);
356 curthread->t_predcache = 0;
359 * Clear contract template state
361 lwp_ctmpl_clear(lwp);
364 * Save the directory in which we found the executable for expanding
365 * the %d token used in core file patterns.
367 mutex_enter(&p->p_lock);
368 tmpvp = p->p_execdir;
369 p->p_execdir = dir;
370 if (p->p_execdir != NULL)
371 VN_HOLD(p->p_execdir);
372 mutex_exit(&p->p_lock);
374 if (tmpvp != NULL)
375 VN_RELE(tmpvp);
378 * Reset stack state to the user stack, clear set of signals
379 * caught on the signal stack, and reset list of signals that
380 * restart system calls; the new program's environment should
381 * not be affected by detritus from the old program. Any
382 * pending held signals remain held, so don't clear t_hold.
384 mutex_enter(&p->p_lock);
385 lwp->lwp_oldcontext = 0;
386 lwp->lwp_ustack = 0;
387 lwp->lwp_old_stk_ctl = 0;
388 sigemptyset(&up->u_signodefer);
389 sigemptyset(&up->u_sigonstack);
390 sigemptyset(&up->u_sigresethand);
391 lwp->lwp_sigaltstack.ss_sp = 0;
392 lwp->lwp_sigaltstack.ss_size = 0;
393 lwp->lwp_sigaltstack.ss_flags = SS_DISABLE;
396 * Make saved resource limit == current resource limit.
398 for (i = 0; i < RLIM_NLIMITS; i++) {
399 /*CONSTCOND*/
400 if (RLIM_SAVED(i)) {
401 (void) rctl_rlimit_get(rctlproc_legacy[i], p,
402 &up->u_saved_rlimit[i]);
407 * If the action was to catch the signal, then the action
408 * must be reset to SIG_DFL.
410 sigdefault(p);
411 p->p_flag &= ~(SNOWAIT|SJCTL);
412 p->p_flag |= (SEXECED|SMSACCT|SMSFORK);
413 up->u_signal[SIGCLD - 1] = SIG_DFL;
416 * Delete the dot4 sigqueues/signotifies.
418 sigqfree(p);
420 mutex_exit(&p->p_lock);
422 mutex_enter(&p->p_pflock);
423 p->p_prof.pr_base = NULL;
424 p->p_prof.pr_size = 0;
425 p->p_prof.pr_off = 0;
426 p->p_prof.pr_scale = 0;
427 p->p_prof.pr_samples = 0;
428 mutex_exit(&p->p_pflock);
430 ASSERT(curthread->t_schedctl == NULL);
434 * Close all close-on-exec files.
436 close_exec(P_FINFO(p));
437 TRACE_2(TR_FAC_PROC, TR_PROC_EXEC, "proc_exec:p %p up %p", p, up);
439 /* Unbrand ourself if necessary. */
440 if (PROC_IS_BRANDED(p) && (brand_action == EBA_NATIVE))
441 brand_clearbrand(p, B_FALSE);
443 setregs(&args);
445 /* Mark this as an executable vnode */
446 mutex_enter(&vp->v_lock);
447 vp->v_flag |= VVMEXEC;
448 mutex_exit(&vp->v_lock);
450 VN_RELE(vp);
451 if (dir != NULL)
452 VN_RELE(dir);
453 pn_free(&resolvepn);
456 * Allocate a new lwp directory and lwpid hash table if necessary.
458 if (curthread->t_tid != 1 || p->p_lwpdir_sz != 2) {
459 lwpdir = kmem_zalloc(2 * sizeof (lwpdir_t), KM_SLEEP);
460 lwpdir->ld_next = lwpdir + 1;
461 tidhash = kmem_zalloc(2 * sizeof (tidhash_t), KM_SLEEP);
462 if (p->p_lwpdir != NULL)
463 lep = p->p_lwpdir[curthread->t_dslot].ld_entry;
464 else
465 lep = kmem_zalloc(sizeof (*lep), KM_SLEEP);
468 if (PROC_IS_BRANDED(p))
469 BROP(p)->b_exec();
471 mutex_enter(&p->p_lock);
472 prbarrier(p);
475 * Reset lwp id to the default value of 1.
476 * This is a single-threaded process now
477 * and lwp #1 is lwp_wait()able by default.
478 * The t_unpark flag should not be inherited.
480 ASSERT(p->p_lwpcnt == 1 && p->p_zombcnt == 0);
481 curthread->t_tid = 1;
482 kpreempt_disable();
483 ASSERT(curthread->t_lpl != NULL);
484 p->p_t1_lgrpid = curthread->t_lpl->lpl_lgrpid;
485 kpreempt_enable();
486 if (p->p_tr_lgrpid != LGRP_NONE && p->p_tr_lgrpid != p->p_t1_lgrpid) {
487 lgrp_update_trthr_migrations(1);
489 curthread->t_unpark = 0;
490 curthread->t_proc_flag |= TP_TWAIT;
491 curthread->t_proc_flag &= ~TP_DAEMON; /* daemons shouldn't exec */
492 p->p_lwpdaemon = 0; /* but oh well ... */
493 p->p_lwpid = 1;
496 * Install the newly-allocated lwp directory and lwpid hash table
497 * and insert the current thread into the new hash table.
499 if (lwpdir != NULL) {
500 old_lwpdir = p->p_lwpdir;
501 old_lwpdir_sz = p->p_lwpdir_sz;
502 old_tidhash = p->p_tidhash;
503 old_tidhash_sz = p->p_tidhash_sz;
504 p->p_lwpdir = p->p_lwpfree = lwpdir;
505 p->p_lwpdir_sz = 2;
506 lep->le_thread = curthread;
507 lep->le_lwpid = curthread->t_tid;
508 lep->le_start = curthread->t_start;
509 lwp_hash_in(p, lep, tidhash, 2, 0);
510 p->p_tidhash = tidhash;
511 p->p_tidhash_sz = 2;
513 ret_tidhash = p->p_ret_tidhash;
514 p->p_ret_tidhash = NULL;
517 * Restore the saved signal mask and
518 * inform /proc that the exec() has finished.
520 curthread->t_hold = savedmask;
521 prexecend();
522 mutex_exit(&p->p_lock);
523 if (old_lwpdir) {
524 kmem_free(old_lwpdir, old_lwpdir_sz * sizeof (lwpdir_t));
525 kmem_free(old_tidhash, old_tidhash_sz * sizeof (tidhash_t));
527 while (ret_tidhash != NULL) {
528 ret_tidhash_t *next = ret_tidhash->rth_next;
529 kmem_free(ret_tidhash->rth_tidhash,
530 ret_tidhash->rth_tidhash_sz * sizeof (tidhash_t));
531 kmem_free(ret_tidhash, sizeof (*ret_tidhash));
532 ret_tidhash = next;
535 ASSERT(error == 0);
536 DTRACE_PROC(exec__success);
537 return (0);
539 fail:
540 DTRACE_PROC1(exec__failure, int, error);
541 out: /* error return */
542 mutex_enter(&p->p_lock);
543 curthread->t_hold = savedmask;
544 prexecend();
545 mutex_exit(&p->p_lock);
546 ASSERT(error != 0);
547 return (error);
552 * Perform generic exec duties and switchout to object-file specific
553 * handler.
556 gexec(
557 struct vnode **vpp,
558 struct execa *uap,
559 struct uarg *args,
560 struct intpdata *idatap,
561 int level,
562 long *execsz,
563 caddr_t exec_file,
564 struct cred *cred,
565 int brand_action)
567 struct vnode *vp, *execvp = NULL;
568 proc_t *pp = ttoproc(curthread);
569 struct execsw *eswp;
570 int error = 0;
571 int suidflags = 0;
572 ssize_t resid;
573 uid_t uid, gid;
574 struct vattr vattr;
575 char magbuf[MAGIC_BYTES];
576 int setid;
577 cred_t *oldcred, *newcred = NULL;
578 int privflags = 0;
579 int setidfl;
580 priv_set_t fset;
581 secflagset_t old_secflags;
583 secflags_copy(&old_secflags, &pp->p_secflags.psf_effective);
586 * If the SNOCD or SUGID flag is set, turn it off and remember the
587 * previous setting so we can restore it if we encounter an error.
589 if (level == 0 && (pp->p_flag & PSUIDFLAGS)) {
590 mutex_enter(&pp->p_lock);
591 suidflags = pp->p_flag & PSUIDFLAGS;
592 pp->p_flag &= ~PSUIDFLAGS;
593 mutex_exit(&pp->p_lock);
596 if ((error = execpermissions(*vpp, &vattr, args)) != 0)
597 goto bad_noclose;
599 /* need to open vnode for stateful file systems */
600 if ((error = fop_open(vpp, FREAD, CRED(), NULL)) != 0)
601 goto bad_noclose;
602 vp = *vpp;
605 * Note: to support binary compatibility with SunOS a.out
606 * executables, we read in the first four bytes, as the
607 * magic number is in bytes 2-3.
609 if (error = vn_rdwr(UIO_READ, vp, magbuf, sizeof (magbuf),
610 0, UIO_SYSSPACE, 0, 0, CRED(), &resid))
611 goto bad;
612 if (resid != 0)
613 goto bad;
615 if ((eswp = findexec_by_hdr(magbuf)) == NULL)
616 goto bad;
618 if (level == 0 &&
619 (privflags = execsetid(vp, &vattr, &uid, &gid, &fset,
620 args->pfcred == NULL ? cred : args->pfcred, args->pathname)) != 0) {
622 /* Pfcred is a credential with a ref count of 1 */
624 if (args->pfcred != NULL) {
625 privflags |= PRIV_INCREASE|PRIV_RESET;
626 newcred = cred = args->pfcred;
627 } else {
628 newcred = cred = crdup(cred);
631 /* If we can, drop the PA bit */
632 if ((privflags & PRIV_RESET) != 0)
633 priv_adjust_PA(cred);
635 if (privflags & PRIV_SETID) {
636 cred->cr_uid = uid;
637 cred->cr_gid = gid;
638 cred->cr_suid = uid;
639 cred->cr_sgid = gid;
643 * Implement the privilege updates:
645 * Restrict with L:
647 * I' = I & L
649 * E' = P' = (I' + F) & A
651 * But if running under ptrace, we cap I and F with P.
653 if ((privflags & (PRIV_RESET|PRIV_FORCED)) != 0) {
654 if ((privflags & PRIV_INCREASE) != 0 &&
655 (pp->p_proc_flag & P_PR_PTRACE) != 0) {
656 priv_intersect(&CR_OPPRIV(cred),
657 &CR_IPRIV(cred));
658 priv_intersect(&CR_OPPRIV(cred), &fset);
660 priv_intersect(&CR_LPRIV(cred), &CR_IPRIV(cred));
661 CR_EPRIV(cred) = CR_PPRIV(cred) = CR_IPRIV(cred);
662 if (privflags & PRIV_FORCED) {
663 priv_set_PA(cred);
664 priv_union(&fset, &CR_EPRIV(cred));
665 priv_union(&fset, &CR_PPRIV(cred));
667 priv_adjust_PA(cred);
669 } else if (level == 0 && args->pfcred != NULL) {
670 newcred = cred = args->pfcred;
671 privflags |= PRIV_INCREASE;
672 /* pfcred is not forced to adhere to these settings */
673 priv_intersect(&CR_LPRIV(cred), &CR_IPRIV(cred));
674 CR_EPRIV(cred) = CR_PPRIV(cred) = CR_IPRIV(cred);
675 priv_adjust_PA(cred);
678 /* The new image gets the inheritable secflags as its secflags */
679 secflags_promote(pp);
681 /* SunOS 4.x buy-back */
682 if ((vp->v_vfsp->vfs_flag & VFS_NOSETUID) &&
683 (vattr.va_mode & (VSUID|VSGID))) {
684 char path[MAXNAMELEN];
685 refstr_t *mntpt = NULL;
686 int ret = -1;
688 bzero(path, sizeof (path));
689 zone_hold(pp->p_zone);
691 ret = vnodetopath(pp->p_zone->zone_rootvp, vp, path,
692 sizeof (path), cred);
694 /* fallback to mountpoint if a path can't be found */
695 if ((ret != 0) || (ret == 0 && path[0] == '\0'))
696 mntpt = vfs_getmntpoint(vp->v_vfsp);
698 if (mntpt == NULL)
699 zcmn_err(pp->p_zone->zone_id, CE_NOTE,
700 "!uid %d: setuid execution not allowed, "
701 "file=%s", cred->cr_uid, path);
702 else
703 zcmn_err(pp->p_zone->zone_id, CE_NOTE,
704 "!uid %d: setuid execution not allowed, "
705 "fs=%s, file=%s", cred->cr_uid,
706 ZONE_PATH_TRANSLATE(refstr_value(mntpt),
707 pp->p_zone), exec_file);
709 if (!INGLOBALZONE(pp)) {
710 /* zone_rootpath always has trailing / */
711 if (mntpt == NULL)
712 cmn_err(CE_NOTE, "!zone: %s, uid: %d "
713 "setuid execution not allowed, file=%s%s",
714 pp->p_zone->zone_name, cred->cr_uid,
715 pp->p_zone->zone_rootpath, path + 1);
716 else
717 cmn_err(CE_NOTE, "!zone: %s, uid: %d "
718 "setuid execution not allowed, fs=%s, "
719 "file=%s", pp->p_zone->zone_name,
720 cred->cr_uid, refstr_value(mntpt),
721 exec_file);
724 if (mntpt != NULL)
725 refstr_rele(mntpt);
727 zone_rele(pp->p_zone);
731 * execsetid() told us whether or not we had to change the
732 * credentials of the process. In privflags, it told us
733 * whether we gained any privileges or executed a set-uid executable.
735 setid = (privflags & (PRIV_SETUGID|PRIV_INCREASE|PRIV_FORCED));
738 * Use /etc/system variable to determine if the stack
739 * should be marked as executable by default.
741 if ((noexec_user_stack != 0) ||
742 secflag_enabled(pp, PROC_SEC_NOEXECSTACK))
743 args->stk_prot &= ~PROT_EXEC;
745 args->execswp = eswp; /* Save execsw pointer in uarg for exec_func */
746 args->ex_vp = vp;
749 * Traditionally, the setid flags told the sub processes whether
750 * the file just executed was set-uid or set-gid; this caused
751 * some confusion as the 'setid' flag did not match the SUGID
752 * process flag which is only set when the uids/gids do not match.
753 * A script set-gid/set-uid to the real uid/gid would start with
754 * /dev/fd/X but an executable would happily trust LD_LIBRARY_PATH.
755 * Now we flag those cases where the calling process cannot
756 * be trusted to influence the newly exec'ed process, either
757 * because it runs with more privileges or when the uids/gids
758 * do in fact not match.
759 * This also makes the runtime linker agree with the on exec
760 * values of SNOCD and SUGID.
762 setidfl = 0;
763 if (cred->cr_uid != cred->cr_ruid || (cred->cr_rgid != cred->cr_gid &&
764 !supgroupmember(cred->cr_gid, cred))) {
765 setidfl |= EXECSETID_UGIDS;
767 if (setid & PRIV_SETUGID)
768 setidfl |= EXECSETID_SETID;
769 if (setid & PRIV_FORCED)
770 setidfl |= EXECSETID_PRIVS;
772 execvp = pp->p_exec;
773 if (execvp)
774 VN_HOLD(execvp);
776 error = (*eswp->exec_func)(vp, uap, args, idatap, level, execsz,
777 setidfl, exec_file, cred, brand_action);
778 rw_exit(eswp->exec_lock);
779 if (error != 0) {
780 if (execvp)
781 VN_RELE(execvp);
783 * If this process's p_exec has been set to the vp of
784 * the executable by exec_func, we will return without
785 * calling fop_close because proc_exit will close it
786 * on exit.
788 if (pp->p_exec == vp)
789 goto bad_noclose;
790 else
791 goto bad;
794 if (level == 0) {
795 uid_t oruid;
797 if (execvp != NULL) {
799 * Close the previous executable only if we are
800 * at level 0.
802 (void) fop_close(execvp, FREAD, 1, 0,
803 cred, NULL);
806 mutex_enter(&pp->p_crlock);
808 oruid = pp->p_cred->cr_ruid;
810 if (newcred != NULL) {
812 * Free the old credentials, and set the new ones.
813 * Do this for both the process and the (single) thread.
815 crfree(pp->p_cred);
816 pp->p_cred = cred; /* cred already held for proc */
817 crhold(cred); /* hold new cred for thread */
819 * DTrace accesses t_cred in probe context. t_cred
820 * must always be either NULL, or point to a valid,
821 * allocated cred structure.
823 oldcred = curthread->t_cred;
824 curthread->t_cred = cred;
825 crfree(oldcred);
827 if (priv_basic_test >= 0 &&
828 !PRIV_ISMEMBER(&CR_IPRIV(newcred),
829 priv_basic_test)) {
830 pid_t pid = pp->p_pid;
831 char *fn = PTOU(pp)->u_comm;
833 cmn_err(CE_WARN, "%s[%d]: exec: basic_test "
834 "privilege removed from E/I", fn, pid);
838 * On emerging from a successful exec(), the saved
839 * uid and gid equal the effective uid and gid.
841 cred->cr_suid = cred->cr_uid;
842 cred->cr_sgid = cred->cr_gid;
845 * If the real and effective ids do not match, this
846 * is a setuid process that should not dump core.
847 * The group comparison is tricky; we prevent the code
848 * from flagging SNOCD when executing with an effective gid
849 * which is a supplementary group.
851 if (cred->cr_ruid != cred->cr_uid ||
852 (cred->cr_rgid != cred->cr_gid &&
853 !supgroupmember(cred->cr_gid, cred)) ||
854 (privflags & PRIV_INCREASE) != 0)
855 suidflags = PSUIDFLAGS;
856 else
857 suidflags = 0;
859 mutex_exit(&pp->p_crlock);
860 if (newcred != NULL && oruid != newcred->cr_ruid) {
861 /* Note that the process remains in the same zone. */
862 mutex_enter(&pidlock);
863 upcount_dec(oruid, crgetzoneid(newcred));
864 upcount_inc(newcred->cr_ruid, crgetzoneid(newcred));
865 mutex_exit(&pidlock);
867 if (suidflags) {
868 mutex_enter(&pp->p_lock);
869 pp->p_flag |= suidflags;
870 mutex_exit(&pp->p_lock);
872 if (setid && (pp->p_proc_flag & P_PR_PTRACE) == 0) {
874 * If process is traced via /proc, arrange to
875 * invalidate the associated /proc vnode.
877 if (pp->p_plist || (pp->p_proc_flag & P_PR_TRACE))
878 args->traceinval = 1;
880 if (pp->p_proc_flag & P_PR_PTRACE)
881 psignal(pp, SIGTRAP);
882 if (args->traceinval)
883 prinvalidate(&pp->p_user);
885 if (execvp)
886 VN_RELE(execvp);
887 return (0);
889 bad:
890 (void) fop_close(vp, FREAD, 1, 0, cred, NULL);
892 bad_noclose:
893 if (newcred != NULL)
894 crfree(newcred);
895 if (error == 0)
896 error = ENOEXEC;
898 mutex_enter(&pp->p_lock);
899 if (suidflags) {
900 pp->p_flag |= suidflags;
903 * Restore the effective secflags, to maintain the invariant they
904 * never change for a given process
906 secflags_copy(&pp->p_secflags.psf_effective, &old_secflags);
907 mutex_exit(&pp->p_lock);
909 return (error);
912 extern char *execswnames[];
914 struct execsw *
915 allocate_execsw(char *name, char *magic, size_t magic_size)
917 int i, j;
918 char *ename;
919 char *magicp;
921 mutex_enter(&execsw_lock);
922 for (i = 0; i < nexectype; i++) {
923 if (execswnames[i] == NULL) {
924 ename = kmem_alloc(strlen(name) + 1, KM_SLEEP);
925 (void) strcpy(ename, name);
926 execswnames[i] = ename;
928 * Set the magic number last so that we
929 * don't need to hold the execsw_lock in
930 * findexectype().
932 magicp = kmem_alloc(magic_size, KM_SLEEP);
933 for (j = 0; j < magic_size; j++)
934 magicp[j] = magic[j];
935 execsw[i].exec_magic = magicp;
936 mutex_exit(&execsw_lock);
937 return (&execsw[i]);
940 mutex_exit(&execsw_lock);
941 return (NULL);
945 * Find the exec switch table entry with the corresponding magic string.
947 struct execsw *
948 findexecsw(char *magic)
950 struct execsw *eswp;
952 for (eswp = execsw; eswp < &execsw[nexectype]; eswp++) {
953 ASSERT(eswp->exec_maglen <= MAGIC_BYTES);
954 if (magic && eswp->exec_maglen != 0 &&
955 bcmp(magic, eswp->exec_magic, eswp->exec_maglen) == 0)
956 return (eswp);
958 return (NULL);
962 * Find the execsw[] index for the given exec header string by looking for the
963 * magic string at a specified offset and length for each kind of executable
964 * file format until one matches. If no execsw[] entry is found, try to
965 * autoload a module for this magic string.
967 struct execsw *
968 findexec_by_hdr(char *header)
970 struct execsw *eswp;
972 for (eswp = execsw; eswp < &execsw[nexectype]; eswp++) {
973 ASSERT(eswp->exec_maglen <= MAGIC_BYTES);
974 if (header && eswp->exec_maglen != 0 &&
975 bcmp(&header[eswp->exec_magoff], eswp->exec_magic,
976 eswp->exec_maglen) == 0) {
977 if (hold_execsw(eswp) != 0)
978 return (NULL);
979 return (eswp);
982 return (NULL); /* couldn't find the type */
986 * Find the execsw[] index for the given magic string. If no execsw[] entry
987 * is found, try to autoload a module for this magic string.
989 struct execsw *
990 findexec_by_magic(char *magic)
992 struct execsw *eswp;
994 for (eswp = execsw; eswp < &execsw[nexectype]; eswp++) {
995 ASSERT(eswp->exec_maglen <= MAGIC_BYTES);
996 if (magic && eswp->exec_maglen != 0 &&
997 bcmp(magic, eswp->exec_magic, eswp->exec_maglen) == 0) {
998 if (hold_execsw(eswp) != 0)
999 return (NULL);
1000 return (eswp);
1003 return (NULL); /* couldn't find the type */
1006 static int
1007 hold_execsw(struct execsw *eswp)
1009 char *name;
1011 rw_enter(eswp->exec_lock, RW_READER);
1012 while (!LOADED_EXEC(eswp)) {
1013 rw_exit(eswp->exec_lock);
1014 name = execswnames[eswp-execsw];
1015 ASSERT(name);
1016 if (modload("exec", name) == -1)
1017 return (-1);
1018 rw_enter(eswp->exec_lock, RW_READER);
1020 return (0);
1023 static int
1024 execsetid(struct vnode *vp, struct vattr *vattrp, uid_t *uidp, uid_t *gidp,
1025 priv_set_t *fset, cred_t *cr, const char *pathname)
1027 proc_t *pp = ttoproc(curthread);
1028 uid_t uid, gid;
1029 int privflags = 0;
1032 * Remember credentials.
1034 uid = cr->cr_uid;
1035 gid = cr->cr_gid;
1037 /* Will try to reset the PRIV_AWARE bit later. */
1038 if ((CR_FLAGS(cr) & (PRIV_AWARE|PRIV_AWARE_INHERIT)) == PRIV_AWARE)
1039 privflags |= PRIV_RESET;
1041 if ((vp->v_vfsp->vfs_flag & VFS_NOSETUID) == 0) {
1043 * If it's a set-uid root program we perform the
1044 * forced privilege look-aside. This has three possible
1045 * outcomes:
1046 * no look aside information -> treat as before
1047 * look aside in Limit set -> apply forced privs
1048 * look aside not in Limit set -> ignore set-uid root
1050 * Ordinary set-uid root execution only allowed if the limit
1051 * set holds all unsafe privileges.
1053 if (vattrp->va_mode & VSUID) {
1054 if (vattrp->va_uid == 0) {
1055 int res = get_forced_privs(cr, pathname, fset);
1057 switch (res) {
1058 case -1:
1059 if (priv_issubset(&priv_unsafe,
1060 &CR_LPRIV(cr))) {
1061 uid = vattrp->va_uid;
1062 privflags |= PRIV_SETUGID;
1064 break;
1065 case 0:
1066 privflags |= PRIV_FORCED|PRIV_INCREASE;
1067 break;
1068 default:
1069 break;
1071 } else {
1072 uid = vattrp->va_uid;
1073 privflags |= PRIV_SETUGID;
1076 if (vattrp->va_mode & VSGID) {
1077 gid = vattrp->va_gid;
1078 privflags |= PRIV_SETUGID;
1083 * Do we need to change our credential anyway?
1084 * This is the case when E != I or P != I, as
1085 * we need to do the assignments (with F empty and A full)
1086 * Or when I is not a subset of L; in that case we need to
1087 * enforce L.
1089 * I' = L & I
1091 * E' = P' = (I' + F) & A
1092 * or
1093 * E' = P' = I'
1095 if (!priv_isequalset(&CR_EPRIV(cr), &CR_IPRIV(cr)) ||
1096 !priv_issubset(&CR_IPRIV(cr), &CR_LPRIV(cr)) ||
1097 !priv_isequalset(&CR_PPRIV(cr), &CR_IPRIV(cr)))
1098 privflags |= PRIV_RESET;
1100 /* Child has more privileges than parent */
1101 if (!priv_issubset(&CR_IPRIV(cr), &CR_PPRIV(cr)))
1102 privflags |= PRIV_INCREASE;
1105 * Set setuid/setgid protections if no ptrace() compatibility.
1106 * For privileged processes, honor setuid/setgid even in
1107 * the presence of ptrace() compatibility.
1109 if (((pp->p_proc_flag & P_PR_PTRACE) == 0 ||
1110 PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, (uid == 0))) &&
1111 (cr->cr_uid != uid ||
1112 cr->cr_gid != gid ||
1113 cr->cr_suid != uid ||
1114 cr->cr_sgid != gid)) {
1115 *uidp = uid;
1116 *gidp = gid;
1117 privflags |= PRIV_SETID;
1119 return (privflags);
1123 execpermissions(struct vnode *vp, struct vattr *vattrp, struct uarg *args)
1125 int error;
1126 proc_t *p = ttoproc(curthread);
1128 vattrp->va_mask = VATTR_MODE | VATTR_UID | VATTR_GID | VATTR_SIZE;
1129 if (error = fop_getattr(vp, vattrp, ATTR_EXEC, p->p_cred, NULL))
1130 return (error);
1132 * Check the access mode.
1133 * If VPROC, ask /proc if the file is an object file.
1135 if ((error = fop_access(vp, VEXEC, 0, p->p_cred, NULL)) != 0 ||
1136 !(vp->v_type == VREG || (vp->v_type == VPROC && pr_isobject(vp))) ||
1137 (vp->v_vfsp->vfs_flag & VFS_NOEXEC) != 0 ||
1138 (vattrp->va_mode & (VEXEC|(VEXEC>>3)|(VEXEC>>6))) == 0) {
1139 if (error == 0)
1140 error = EACCES;
1141 return (error);
1144 if ((p->p_plist || (p->p_proc_flag & (P_PR_PTRACE|P_PR_TRACE))) &&
1145 (error = fop_access(vp, VREAD, 0, p->p_cred, NULL))) {
1147 * If process is under ptrace(2) compatibility,
1148 * fail the exec(2).
1150 if (p->p_proc_flag & P_PR_PTRACE)
1151 goto bad;
1153 * Process is traced via /proc.
1154 * Arrange to invalidate the /proc vnode.
1156 args->traceinval = 1;
1158 return (0);
1159 bad:
1160 if (error == 0)
1161 error = ENOEXEC;
1162 return (error);
1166 * Map a section of an executable file into the user's
1167 * address space.
1170 execmap(struct vnode *vp, caddr_t addr, size_t len, size_t zfodlen,
1171 off_t offset, int prot, int page, uint_t szc)
1173 int error = 0;
1174 off_t oldoffset;
1175 caddr_t zfodbase, oldaddr;
1176 size_t end, oldlen;
1177 size_t zfoddiff;
1178 label_t ljb;
1179 proc_t *p = ttoproc(curthread);
1181 oldaddr = addr;
1182 addr = (caddr_t)((uintptr_t)addr & (uintptr_t)PAGEMASK);
1183 if (len) {
1184 oldlen = len;
1185 len += ((size_t)oldaddr - (size_t)addr);
1186 oldoffset = offset;
1187 offset = (off_t)((uintptr_t)offset & PAGEMASK);
1188 if (page) {
1189 spgcnt_t prefltmem, availm, npages;
1190 int preread;
1191 uint_t mflag = MAP_PRIVATE | MAP_FIXED;
1193 if ((prot & (PROT_WRITE | PROT_EXEC)) == PROT_EXEC) {
1194 mflag |= MAP_TEXT;
1195 } else {
1196 mflag |= MAP_INITDATA;
1199 if (valid_usr_range(addr, len, prot, p->p_as,
1200 p->p_as->a_userlimit) != RANGE_OKAY) {
1201 error = ENOMEM;
1202 goto bad;
1204 if (error = fop_map(vp, (offset_t)offset,
1205 p->p_as, &addr, len, prot, PROT_ALL,
1206 mflag, CRED(), NULL))
1207 goto bad;
1210 * If the segment can fit, then we prefault
1211 * the entire segment in. This is based on the
1212 * model that says the best working set of a
1213 * small program is all of its pages.
1215 npages = (spgcnt_t)btopr(len);
1216 prefltmem = freemem - desfree;
1217 preread =
1218 (npages < prefltmem && len < PGTHRESH) ? 1 : 0;
1221 * If we aren't prefaulting the segment,
1222 * increment "deficit", if necessary to ensure
1223 * that pages will become available when this
1224 * process starts executing.
1226 availm = freemem - lotsfree;
1227 if (preread == 0 && npages > availm &&
1228 deficit < lotsfree) {
1229 deficit += MIN((pgcnt_t)(npages - availm),
1230 lotsfree - deficit);
1233 if (preread) {
1234 TRACE_2(TR_FAC_PROC, TR_EXECMAP_PREREAD,
1235 "execmap preread:freemem %d size %lu",
1236 freemem, len);
1237 (void) as_fault(p->p_as->a_hat, p->p_as,
1238 (caddr_t)addr, len, F_INVAL, S_READ);
1240 } else {
1241 if (valid_usr_range(addr, len, prot, p->p_as,
1242 p->p_as->a_userlimit) != RANGE_OKAY) {
1243 error = ENOMEM;
1244 goto bad;
1247 if (error = as_map(p->p_as, addr, len,
1248 segvn_create, zfod_argsp))
1249 goto bad;
1251 * Read in the segment in one big chunk.
1253 if (error = vn_rdwr(UIO_READ, vp, (caddr_t)oldaddr,
1254 oldlen, (offset_t)oldoffset, UIO_USERSPACE, 0,
1255 0, CRED(), NULL))
1256 goto bad;
1258 * Now set protections.
1260 if (prot != PROT_ZFOD) {
1261 (void) as_setprot(p->p_as, (caddr_t)addr,
1262 len, prot);
1267 if (zfodlen) {
1268 struct as *as = curproc->p_as;
1269 struct seg *seg;
1270 uint_t zprot = 0;
1272 end = (size_t)addr + len;
1273 zfodbase = (caddr_t)roundup(end, PAGESIZE);
1274 zfoddiff = (uintptr_t)zfodbase - end;
1275 if (zfoddiff) {
1277 * Before we go to zero the remaining space on the last
1278 * page, make sure we have write permission.
1280 * Normal illumos binaries don't even hit the case
1281 * where we have to change permission on the last page
1282 * since their protection is typically either
1283 * PROT_USER | PROT_WRITE | PROT_READ
1284 * or
1285 * PROT_ZFOD (same as PROT_ALL).
1287 * We need to be careful how we zero-fill the last page
1288 * if the segment protection does not include
1289 * PROT_WRITE. Using as_setprot() can cause the VM
1290 * segment code to call segvn_vpage(), which must
1291 * allocate a page struct for each page in the segment.
1292 * If we have a very large segment, this may fail, so
1293 * we have to check for that, even though we ignore
1294 * other return values from as_setprot.
1297 AS_LOCK_ENTER(as, RW_READER);
1298 seg = as_segat(curproc->p_as, (caddr_t)end);
1299 if (seg != NULL)
1300 (void) segop_getprot(seg, (caddr_t)end,
1301 zfoddiff - 1, &zprot);
1302 AS_LOCK_EXIT(as);
1304 if (seg != NULL && (zprot & PROT_WRITE) == 0) {
1305 if (as_setprot(as, (caddr_t)end, zfoddiff - 1,
1306 zprot | PROT_WRITE) == ENOMEM) {
1307 error = ENOMEM;
1308 goto bad;
1312 if (on_fault(&ljb)) {
1313 no_fault();
1314 if (seg != NULL && (zprot & PROT_WRITE) == 0)
1315 (void) as_setprot(as, (caddr_t)end,
1316 zfoddiff - 1, zprot);
1317 error = EFAULT;
1318 goto bad;
1320 uzero((void *)end, zfoddiff);
1321 no_fault();
1322 if (seg != NULL && (zprot & PROT_WRITE) == 0)
1323 (void) as_setprot(as, (caddr_t)end,
1324 zfoddiff - 1, zprot);
1326 if (zfodlen > zfoddiff) {
1327 struct segvn_crargs crargs =
1328 SEGVN_ZFOD_ARGS(PROT_ZFOD, PROT_ALL);
1330 zfodlen -= zfoddiff;
1331 if (valid_usr_range(zfodbase, zfodlen, prot, p->p_as,
1332 p->p_as->a_userlimit) != RANGE_OKAY) {
1333 error = ENOMEM;
1334 goto bad;
1336 if (szc > 0) {
1338 * ASSERT alignment because the mapelfexec()
1339 * caller for the szc > 0 case extended zfod
1340 * so it's end is pgsz aligned.
1342 size_t pgsz = page_get_pagesize(szc);
1343 ASSERT(IS_P2ALIGNED(zfodbase + zfodlen, pgsz));
1345 if (IS_P2ALIGNED(zfodbase, pgsz)) {
1346 crargs.szc = szc;
1347 } else {
1348 crargs.szc = AS_MAP_HEAP;
1350 } else {
1351 crargs.szc = AS_MAP_NO_LPOOB;
1353 if (error = as_map(p->p_as, (caddr_t)zfodbase,
1354 zfodlen, segvn_create, &crargs))
1355 goto bad;
1356 if (prot != PROT_ZFOD) {
1357 (void) as_setprot(p->p_as, (caddr_t)zfodbase,
1358 zfodlen, prot);
1362 return (0);
1363 bad:
1364 return (error);
1367 void
1368 setexecenv(struct execenv *ep)
1370 proc_t *p = ttoproc(curthread);
1371 klwp_t *lwp = ttolwp(curthread);
1372 struct vnode *vp;
1374 p->p_bssbase = ep->ex_bssbase;
1375 p->p_brkbase = ep->ex_brkbase;
1376 p->p_brksize = ep->ex_brksize;
1377 if (p->p_exec)
1378 VN_RELE(p->p_exec); /* out with the old */
1379 vp = p->p_exec = ep->ex_vp;
1380 if (vp != NULL)
1381 VN_HOLD(vp); /* in with the new */
1383 lwp->lwp_sigaltstack.ss_sp = 0;
1384 lwp->lwp_sigaltstack.ss_size = 0;
1385 lwp->lwp_sigaltstack.ss_flags = SS_DISABLE;
1389 execopen(struct vnode **vpp, int *fdp)
1391 struct vnode *vp = *vpp;
1392 file_t *fp;
1393 int error = 0;
1394 int filemode = FREAD;
1396 VN_HOLD(vp); /* open reference */
1397 if (error = falloc(NULL, filemode, &fp, fdp)) {
1398 VN_RELE(vp);
1399 *fdp = -1; /* just in case falloc changed value */
1400 return (error);
1402 if (error = fop_open(&vp, filemode, CRED(), NULL)) {
1403 VN_RELE(vp);
1404 setf(*fdp, NULL);
1405 unfalloc(fp);
1406 *fdp = -1;
1407 return (error);
1409 *vpp = vp; /* vnode should not have changed */
1410 fp->f_vnode = vp;
1411 mutex_exit(&fp->f_tlock);
1412 setf(*fdp, fp);
1413 return (0);
1417 execclose(int fd)
1419 return (closeandsetf(fd, NULL));
1424 * noexec stub function.
1426 /*ARGSUSED*/
1428 noexec(
1429 struct vnode *vp,
1430 struct execa *uap,
1431 struct uarg *args,
1432 struct intpdata *idatap,
1433 int level,
1434 long *execsz,
1435 int setid,
1436 caddr_t exec_file,
1437 struct cred *cred)
1439 cmn_err(CE_WARN, "missing exec capability for %s", uap->fname);
1440 return (ENOEXEC);
1444 * Support routines for building a user stack.
1446 * execve(path, argv, envp) must construct a new stack with the specified
1447 * arguments and environment variables (see exec_args() for a description
1448 * of the user stack layout). To do this, we copy the arguments and
1449 * environment variables from the old user address space into the kernel,
1450 * free the old as, create the new as, and copy our buffered information
1451 * to the new stack. Our kernel buffer has the following structure:
1453 * +-----------------------+ <--- stk_base + stk_size
1454 * | string offsets |
1455 * +-----------------------+ <--- stk_offp
1456 * | |
1457 * | STK_AVAIL() space |
1458 * | |
1459 * +-----------------------+ <--- stk_strp
1460 * | strings |
1461 * +-----------------------+ <--- stk_base
1463 * When we add a string, we store the string's contents (including the null
1464 * terminator) at stk_strp, and we store the offset of the string relative to
1465 * stk_base at --stk_offp. At strings are added, stk_strp increases and
1466 * stk_offp decreases. The amount of space remaining, STK_AVAIL(), is just
1467 * the difference between these pointers. If we run out of space, we return
1468 * an error and exec_args() starts all over again with a buffer twice as large.
1469 * When we're all done, the kernel buffer looks like this:
1471 * +-----------------------+ <--- stk_base + stk_size
1472 * | argv[0] offset |
1473 * +-----------------------+
1474 * | ... |
1475 * +-----------------------+
1476 * | argv[argc-1] offset |
1477 * +-----------------------+
1478 * | envp[0] offset |
1479 * +-----------------------+
1480 * | ... |
1481 * +-----------------------+
1482 * | envp[envc-1] offset |
1483 * +-----------------------+
1484 * | AT_SUN_PLATFORM offset|
1485 * +-----------------------+
1486 * | AT_SUN_EXECNAME offset|
1487 * +-----------------------+ <--- stk_offp
1488 * | |
1489 * | STK_AVAIL() space |
1490 * | |
1491 * +-----------------------+ <--- stk_strp
1492 * | AT_SUN_EXECNAME offset|
1493 * +-----------------------+
1494 * | AT_SUN_PLATFORM offset|
1495 * +-----------------------+
1496 * | envp[envc-1] string |
1497 * +-----------------------+
1498 * | ... |
1499 * +-----------------------+
1500 * | envp[0] string |
1501 * +-----------------------+
1502 * | argv[argc-1] string |
1503 * +-----------------------+
1504 * | ... |
1505 * +-----------------------+
1506 * | argv[0] string |
1507 * +-----------------------+ <--- stk_base
1510 #define STK_AVAIL(args) ((char *)(args)->stk_offp - (args)->stk_strp)
1513 * Add a string to the stack.
1515 static int
1516 stk_add(uarg_t *args, const char *sp, enum uio_seg segflg)
1518 int error;
1519 size_t len;
1521 if (STK_AVAIL(args) < sizeof (int))
1522 return (E2BIG);
1523 *--args->stk_offp = args->stk_strp - args->stk_base;
1525 if (segflg == UIO_USERSPACE) {
1526 error = copyinstr(sp, args->stk_strp, STK_AVAIL(args), &len);
1527 if (error != 0)
1528 return (error);
1529 } else {
1530 len = strlen(sp) + 1;
1531 if (len > STK_AVAIL(args))
1532 return (E2BIG);
1533 bcopy(sp, args->stk_strp, len);
1536 args->stk_strp += len;
1538 return (0);
1541 static int
1542 stk_getptr(uarg_t *args, char *src, char **dst)
1544 int error;
1546 if (args->from_model == DATAMODEL_NATIVE) {
1547 ulong_t ptr;
1548 error = fulword(src, &ptr);
1549 *dst = (caddr_t)ptr;
1550 } else {
1551 uint32_t ptr;
1552 error = fuword32(src, &ptr);
1553 *dst = (caddr_t)(uintptr_t)ptr;
1555 return (error);
1558 static int
1559 stk_putptr(uarg_t *args, char *addr, char *value)
1561 if (args->to_model == DATAMODEL_NATIVE)
1562 return (sulword(addr, (ulong_t)value));
1563 else
1564 return (suword32(addr, (uint32_t)(uintptr_t)value));
1567 static int
1568 stk_copyin(execa_t *uap, uarg_t *args, intpdata_t *intp, void **auxvpp)
1570 char *sp;
1571 int argc, error;
1572 int argv_empty = 0;
1573 size_t ptrsize = args->from_ptrsize;
1574 size_t size, pad;
1575 char *argv = (char *)uap->argp;
1576 char *envp = (char *)uap->envp;
1579 * Copy interpreter's name and argument to argv[0] and argv[1].
1580 * In the rare case that we have nested interpreters then those names
1581 * and arguments are also copied to the subsequent slots in argv.
1583 if (intp != NULL && intp->intp_name[0] != NULL) {
1584 int i;
1586 for (i = 0; i < INTP_MAXDEPTH; i++) {
1587 if (intp->intp_name[i] == NULL)
1588 break;
1589 error = stk_add(args, intp->intp_name[i], UIO_SYSSPACE);
1590 if (error != 0)
1591 return (error);
1592 if (intp->intp_arg[i] != NULL) {
1593 error = stk_add(args, intp->intp_arg[i],
1594 UIO_SYSSPACE);
1595 if (error != 0)
1596 return (error);
1600 if (args->fname != NULL)
1601 error = stk_add(args, args->fname, UIO_SYSSPACE);
1602 else
1603 error = stk_add(args, uap->fname, UIO_USERSPACE);
1604 if (error)
1605 return (error);
1608 * Check for an empty argv[].
1610 if (stk_getptr(args, argv, &sp))
1611 return (EFAULT);
1612 if (sp == NULL)
1613 argv_empty = 1;
1615 argv += ptrsize; /* ignore original argv[0] */
1618 if (argv_empty == 0) {
1620 * Add argv[] strings to the stack.
1622 for (;;) {
1623 if (stk_getptr(args, argv, &sp))
1624 return (EFAULT);
1625 if (sp == NULL)
1626 break;
1627 if ((error = stk_add(args, sp, UIO_USERSPACE)) != 0)
1628 return (error);
1629 argv += ptrsize;
1632 argc = (int *)(args->stk_base + args->stk_size) - args->stk_offp;
1633 args->arglen = args->stk_strp - args->stk_base;
1636 * Add environ[] strings to the stack.
1638 if (envp != NULL) {
1639 for (;;) {
1640 char *tmp = args->stk_strp;
1641 if (stk_getptr(args, envp, &sp))
1642 return (EFAULT);
1643 if (sp == NULL)
1644 break;
1645 if ((error = stk_add(args, sp, UIO_USERSPACE)) != 0)
1646 return (error);
1647 if (args->scrubenv && strncmp(tmp, "LD_", 3) == 0) {
1648 /* Undo the copied string */
1649 args->stk_strp = tmp;
1650 *(args->stk_offp++) = 0;
1652 envp += ptrsize;
1655 args->na = (int *)(args->stk_base + args->stk_size) - args->stk_offp;
1656 args->ne = args->na - argc;
1659 * Add AT_SUN_PLATFORM, AT_SUN_EXECNAME, AT_SUN_BRANDNAME, and
1660 * AT_SUN_EMULATOR strings to the stack.
1662 if (auxvpp != NULL && *auxvpp != NULL) {
1663 if ((error = stk_add(args, platform, UIO_SYSSPACE)) != 0)
1664 return (error);
1665 if ((error = stk_add(args, args->pathname, UIO_SYSSPACE)) != 0)
1666 return (error);
1667 if (args->brandname != NULL &&
1668 (error = stk_add(args, args->brandname, UIO_SYSSPACE)) != 0)
1669 return (error);
1670 if (args->emulator != NULL &&
1671 (error = stk_add(args, args->emulator, UIO_SYSSPACE)) != 0)
1672 return (error);
1676 * Compute the size of the stack. This includes all the pointers,
1677 * the space reserved for the aux vector, and all the strings.
1678 * The total number of pointers is args->na (which is argc + envc)
1679 * plus 4 more: (1) a pointer's worth of space for argc; (2) the NULL
1680 * after the last argument (i.e. argv[argc]); (3) the NULL after the
1681 * last environment variable (i.e. envp[envc]); and (4) the NULL after
1682 * all the strings, at the very top of the stack.
1684 size = (args->na + 4) * args->to_ptrsize + args->auxsize +
1685 (args->stk_strp - args->stk_base);
1688 * Pad the string section with zeroes to align the stack size.
1690 pad = P2NPHASE(size, args->stk_align);
1692 if (STK_AVAIL(args) < pad)
1693 return (E2BIG);
1695 args->usrstack_size = size + pad;
1697 while (pad-- != 0)
1698 *args->stk_strp++ = 0;
1700 args->nc = args->stk_strp - args->stk_base;
1702 return (0);
1705 static int
1706 stk_copyout(uarg_t *args, char *usrstack, void **auxvpp, user_t *up)
1708 size_t ptrsize = args->to_ptrsize;
1709 ssize_t pslen;
1710 char *kstrp = args->stk_base;
1711 char *ustrp = usrstack - args->nc - ptrsize;
1712 char *usp = usrstack - args->usrstack_size;
1713 int *offp = (int *)(args->stk_base + args->stk_size);
1714 int envc = args->ne;
1715 int argc = args->na - envc;
1716 int i;
1719 * Record argc for /proc.
1721 up->u_argc = argc;
1724 * Put argc on the stack. Note that even though it's an int,
1725 * it always consumes ptrsize bytes (for alignment).
1727 if (stk_putptr(args, usp, (char *)(uintptr_t)argc))
1728 return (-1);
1731 * Add argc space (ptrsize) to usp and record argv for /proc.
1733 up->u_argv = (uintptr_t)(usp += ptrsize);
1736 * Put the argv[] pointers on the stack.
1738 for (i = 0; i < argc; i++, usp += ptrsize)
1739 if (stk_putptr(args, usp, &ustrp[*--offp]))
1740 return (-1);
1743 * Copy arguments to u_psargs.
1745 pslen = MIN(args->arglen, PSARGSZ) - 1;
1746 for (i = 0; i < pslen; i++)
1747 up->u_psargs[i] = (kstrp[i] == '\0' ? ' ' : kstrp[i]);
1748 while (i < PSARGSZ)
1749 up->u_psargs[i++] = '\0';
1752 * Add space for argv[]'s NULL terminator (ptrsize) to usp and
1753 * record envp for /proc.
1755 up->u_envp = (uintptr_t)(usp += ptrsize);
1758 * Put the envp[] pointers on the stack.
1760 for (i = 0; i < envc; i++, usp += ptrsize)
1761 if (stk_putptr(args, usp, &ustrp[*--offp]))
1762 return (-1);
1765 * Add space for envp[]'s NULL terminator (ptrsize) to usp and
1766 * remember where the stack ends, which is also where auxv begins.
1768 args->stackend = usp += ptrsize;
1771 * Put all the argv[], envp[], and auxv strings on the stack.
1773 if (copyout(args->stk_base, ustrp, args->nc))
1774 return (-1);
1777 * Fill in the aux vector now that we know the user stack addresses
1778 * for the AT_SUN_PLATFORM, AT_SUN_EXECNAME, AT_SUN_BRANDNAME and
1779 * AT_SUN_EMULATOR strings.
1781 if (auxvpp != NULL && *auxvpp != NULL) {
1782 if (args->to_model == DATAMODEL_NATIVE) {
1783 auxv_t **a = (auxv_t **)auxvpp;
1784 ADDAUX(*a, AT_SUN_PLATFORM, (long)&ustrp[*--offp])
1785 ADDAUX(*a, AT_SUN_EXECNAME, (long)&ustrp[*--offp])
1786 if (args->brandname != NULL)
1787 ADDAUX(*a,
1788 AT_SUN_BRANDNAME, (long)&ustrp[*--offp])
1789 if (args->emulator != NULL)
1790 ADDAUX(*a,
1791 AT_SUN_EMULATOR, (long)&ustrp[*--offp])
1792 } else {
1793 auxv32_t **a = (auxv32_t **)auxvpp;
1794 ADDAUX(*a,
1795 AT_SUN_PLATFORM, (int)(uintptr_t)&ustrp[*--offp])
1796 ADDAUX(*a,
1797 AT_SUN_EXECNAME, (int)(uintptr_t)&ustrp[*--offp])
1798 if (args->brandname != NULL)
1799 ADDAUX(*a, AT_SUN_BRANDNAME,
1800 (int)(uintptr_t)&ustrp[*--offp])
1801 if (args->emulator != NULL)
1802 ADDAUX(*a, AT_SUN_EMULATOR,
1803 (int)(uintptr_t)&ustrp[*--offp])
1807 return (0);
1811 * Though the actual stack base is constant, slew the %sp by a random aligned
1812 * amount in [0,aslr_max_stack_skew). Mostly, this makes life slightly more
1813 * complicated for buffer overflows hoping to overwrite the return address.
1815 * On some platforms this helps avoid cache thrashing when identical processes
1816 * simultaneously share caches that don't provide enough associativity
1817 * (e.g. sun4v systems). In this case stack slewing makes the same hot stack
1818 * variables in different processes live in different cache sets increasing
1819 * effective associativity.
1821 size_t
1822 exec_get_spslew(void)
1824 #ifdef sun4v
1825 static uint_t sp_color_stride = 16;
1826 static uint_t sp_color_mask = 0x1f;
1827 static uint_t sp_current_color = (uint_t)-1;
1828 #endif
1829 size_t off;
1831 ASSERT(ISP2(aslr_max_stack_skew));
1833 if ((aslr_max_stack_skew == 0) ||
1834 !secflag_enabled(curproc, PROC_SEC_ASLR)) {
1835 #ifdef sun4v
1836 uint_t spcolor = atomic_inc_32_nv(&sp_current_color);
1837 return ((size_t)((spcolor & sp_color_mask) *
1838 SA(sp_color_stride)));
1839 #else
1840 return (0);
1841 #endif
1844 (void) random_get_pseudo_bytes((uint8_t *)&off, sizeof (off));
1845 return (SA(P2PHASE(off, aslr_max_stack_skew)));
1849 * Initialize a new user stack with the specified arguments and environment.
1850 * The initial user stack layout is as follows:
1852 * User Stack
1853 * +---------------+
1854 * | |
1855 * | stack guard |
1856 * | (64-bit only) |
1857 * | |
1858 * +...............+ <--- stack limit (base - curproc->p_stk_ctl)
1859 * . .
1860 * . .
1861 * . .
1862 * +---------------+ <--- curproc->p_usrstack
1863 * | |
1864 * | slew |
1865 * | |
1866 * +---------------+
1867 * | NULL |
1868 * +---------------+
1869 * | |
1870 * | auxv strings |
1871 * | |
1872 * +---------------+
1873 * | |
1874 * | envp strings |
1875 * | |
1876 * +---------------+
1877 * | |
1878 * | argv strings |
1879 * | |
1880 * +---------------+ <--- ustrp
1881 * | |
1882 * | aux vector |
1883 * | |
1884 * +---------------+ <--- auxv
1885 * | NULL |
1886 * +---------------+
1887 * | envp[envc-1] |
1888 * +---------------+
1889 * | ... |
1890 * +---------------+
1891 * | envp[0] |
1892 * +---------------+ <--- envp[]
1893 * | NULL |
1894 * +---------------+
1895 * | argv[argc-1] |
1896 * +---------------+
1897 * | ... |
1898 * +---------------+
1899 * | argv[0] |
1900 * +---------------+ <--- argv[]
1901 * | argc |
1902 * +---------------+ <--- stack base
1904 * In 64-bit processes, a stack guard segment is allocated at the address
1905 * immediately below where the stack limit ends. This protects new library
1906 * mappings (such as the linker) from being placed in relatively dangerous
1907 * proximity to the stack.
1910 exec_args(execa_t *uap, uarg_t *args, intpdata_t *intp, void **auxvpp)
1912 size_t size;
1913 int error;
1914 proc_t *p = ttoproc(curthread);
1915 user_t *up = PTOU(p);
1916 char *usrstack;
1917 rctl_entity_p_t e;
1918 struct as *as;
1919 extern int use_stk_lpg;
1920 size_t sp_slew;
1921 #if defined(_LP64)
1922 const size_t sg_sz = (stack_guard_seg_sz & PAGEMASK);
1923 #endif /* defined(_LP64) */
1925 args->from_model = p->p_model;
1926 if (p->p_model == DATAMODEL_NATIVE) {
1927 args->from_ptrsize = sizeof (long);
1928 } else {
1929 args->from_ptrsize = sizeof (int32_t);
1932 if (args->to_model == DATAMODEL_NATIVE) {
1933 args->to_ptrsize = sizeof (long);
1934 args->ncargs = NCARGS;
1935 args->stk_align = STACK_ALIGN;
1936 if (args->addr32)
1937 usrstack = (char *)USRSTACK64_32;
1938 else
1939 usrstack = (char *)USRSTACK;
1940 } else {
1941 args->to_ptrsize = sizeof (int32_t);
1942 args->ncargs = NCARGS32;
1943 args->stk_align = STACK_ALIGN32;
1944 usrstack = (char *)USRSTACK32;
1947 ASSERT(P2PHASE((uintptr_t)usrstack, args->stk_align) == 0);
1950 for (size = PAGESIZE; ; size *= 2) {
1951 args->stk_size = size;
1952 args->stk_base = kmem_alloc(size, KM_SLEEP);
1953 args->stk_strp = args->stk_base;
1954 args->stk_offp = (int *)(args->stk_base + size);
1955 error = stk_copyin(uap, args, intp, auxvpp);
1956 if (error == 0)
1957 break;
1958 kmem_free(args->stk_base, size);
1959 if (error != E2BIG && error != ENAMETOOLONG)
1960 return (error);
1961 if (size >= args->ncargs)
1962 return (E2BIG);
1965 size = args->usrstack_size;
1967 ASSERT(error == 0);
1968 ASSERT(P2PHASE(size, args->stk_align) == 0);
1969 ASSERT((ssize_t)STK_AVAIL(args) >= 0);
1971 if (size > args->ncargs) {
1972 kmem_free(args->stk_base, args->stk_size);
1973 return (E2BIG);
1977 * Leave only the current lwp and force the other lwps to exit.
1978 * If another lwp beat us to the punch by calling exit(), bail out.
1980 if ((error = exitlwps(0)) != 0) {
1981 kmem_free(args->stk_base, args->stk_size);
1982 return (error);
1986 * Revoke any doors created by the process.
1988 if (p->p_door_list)
1989 door_exit();
1992 * Release schedctl data structures.
1994 if (p->p_pagep)
1995 schedctl_proc_cleanup();
1998 * Clean up any DTrace helpers for the process.
2000 if (p->p_dtrace_helpers != NULL) {
2001 ASSERT(dtrace_helpers_cleanup != NULL);
2002 (*dtrace_helpers_cleanup)(p);
2005 mutex_enter(&p->p_lock);
2007 * Cleanup the DTrace provider associated with this process.
2009 if (p->p_dtrace_probes) {
2010 ASSERT(dtrace_fasttrap_exec_ptr != NULL);
2011 dtrace_fasttrap_exec_ptr(p);
2013 mutex_exit(&p->p_lock);
2016 * discard the lwpchan cache.
2018 if (p->p_lcp != NULL)
2019 lwpchan_destroy_cache(1);
2022 * Delete the POSIX timers.
2024 if (p->p_itimer != NULL)
2025 timer_exit();
2028 * Delete the ITIMER_REALPROF interval timer.
2029 * The other ITIMER_* interval timers are specified
2030 * to be inherited across exec().
2032 delete_itimer_realprof();
2035 * Ensure that we don't change resource associations while we
2036 * change address spaces.
2038 mutex_enter(&p->p_lock);
2039 pool_barrier_enter();
2040 mutex_exit(&p->p_lock);
2043 * Destroy the old address space and create a new one.
2044 * From here on, any errors are fatal to the exec()ing process.
2045 * On error we return -1, which means the caller must SIGKILL
2046 * the process.
2048 relvm();
2050 mutex_enter(&p->p_lock);
2051 pool_barrier_exit();
2052 mutex_exit(&p->p_lock);
2054 up->u_execsw = args->execswp;
2056 p->p_brkbase = NULL;
2057 p->p_brksize = 0;
2058 p->p_brkpageszc = 0;
2059 p->p_stksize = 0;
2060 p->p_stkpageszc = 0;
2061 p->p_stkg_start = 0;
2062 p->p_stkg_end = 0;
2063 p->p_model = args->to_model;
2064 p->p_usrstack = usrstack;
2065 p->p_stkprot = args->stk_prot;
2066 p->p_datprot = args->dat_prot;
2069 * Reset resource controls such that all controls are again active as
2070 * well as appropriate to the potentially new address model for the
2071 * process.
2073 e.rcep_p.proc = p;
2074 e.rcep_t = RCENTITY_PROCESS;
2075 rctl_set_reset(p->p_rctls, p, &e);
2077 /* Too early to call map_pgsz for the heap */
2078 if (use_stk_lpg) {
2079 p->p_stkpageszc = page_szc(map_pgsz(MAPPGSZ_STK, p, 0, 0, 0));
2082 mutex_enter(&p->p_lock);
2083 p->p_flag |= SAUTOLPG; /* kernel controls page sizes */
2084 mutex_exit(&p->p_lock);
2086 sp_slew = exec_get_spslew();
2087 ASSERT(P2PHASE(sp_slew, args->stk_align) == 0);
2088 /* Be certain we don't underflow */
2089 VERIFY((curproc->p_usrstack - (size + sp_slew)) < curproc->p_usrstack);
2090 exec_set_sp(size + sp_slew);
2092 as = as_alloc();
2093 p->p_as = as;
2094 as->a_proc = p;
2095 if (p->p_model == DATAMODEL_ILP32 || args->addr32)
2096 as->a_userlimit = (caddr_t)USERLIMIT32;
2097 (void) hat_setup(as->a_hat, HAT_ALLOC);
2098 hat_join_srd(as->a_hat, args->ex_vp);
2100 /* Write out the contents of the new stack. */
2101 error = stk_copyout(args, usrstack - sp_slew, auxvpp, up);
2102 kmem_free(args->stk_base, args->stk_size);
2104 #if defined(_LP64)
2105 /* Add stack guard segment (if needed) after successful copyout */
2106 if (error == 0 && p->p_model == DATAMODEL_LP64 && sg_sz != 0) {
2107 seghole_crargs_t sca;
2108 caddr_t addr_end = (caddr_t)(((uintptr_t)usrstack -
2109 p->p_stk_ctl) & PAGEMASK);
2110 caddr_t addr_start = addr_end - sg_sz;
2112 DTRACE_PROBE4(stack__guard__chk, proc_t *, p,
2113 caddr_t, addr_start, caddr_t, addr_end, size_t, sg_sz);
2115 if (addr_end >= usrstack || addr_start >= addr_end ||
2116 valid_usr_range(addr_start, sg_sz, PROT_NONE, as,
2117 as->a_userlimit) != RANGE_OKAY) {
2118 return (E2BIG);
2121 /* Create un-mappable area in AS with seg_hole */
2122 sca.name = "stack_guard";
2123 error = as_map(as, addr_start, sg_sz, seghole_create, &sca);
2124 if (error == 0) {
2125 p->p_stkg_start = (uintptr_t)addr_start;
2126 p->p_stkg_end = (uintptr_t)addr_start + sg_sz;
2129 #endif /* defined(_LP64) */
2131 return (error);