]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/kern/kern_exec.c
MFC r245457:
[FreeBSD/stable/8.git] / sys / kern / kern_exec.c
1 /*-
2  * Copyright (c) 1993, David Greenman
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include "opt_hwpmc_hooks.h"
31 #include "opt_kdtrace.h"
32 #include "opt_ktrace.h"
33 #include "opt_vm.h"
34
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/eventhandler.h>
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/sysproto.h>
41 #include <sys/signalvar.h>
42 #include <sys/kernel.h>
43 #include <sys/mount.h>
44 #include <sys/filedesc.h>
45 #include <sys/fcntl.h>
46 #include <sys/acct.h>
47 #include <sys/exec.h>
48 #include <sys/imgact.h>
49 #include <sys/imgact_elf.h>
50 #include <sys/wait.h>
51 #include <sys/malloc.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/pioctl.h>
55 #include <sys/namei.h>
56 #include <sys/resourcevar.h>
57 #include <sys/sched.h>
58 #include <sys/sdt.h>
59 #include <sys/sf_buf.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/sysent.h>
62 #include <sys/shm.h>
63 #include <sys/sysctl.h>
64 #include <sys/vnode.h>
65 #include <sys/stat.h>
66 #ifdef KTRACE
67 #include <sys/ktrace.h>
68 #endif
69
70 #include <vm/vm.h>
71 #include <vm/vm_param.h>
72 #include <vm/pmap.h>
73 #include <vm/vm_page.h>
74 #include <vm/vm_map.h>
75 #include <vm/vm_kern.h>
76 #include <vm/vm_extern.h>
77 #include <vm/vm_object.h>
78 #include <vm/vm_pager.h>
79
80 #ifdef  HWPMC_HOOKS
81 #include <sys/pmckern.h>
82 #endif
83
84 #include <machine/reg.h>
85
86 #include <security/audit/audit.h>
87 #include <security/mac/mac_framework.h>
88
89 #ifdef KDTRACE_HOOKS
90 #include <sys/dtrace_bsd.h>
91 dtrace_execexit_func_t  dtrace_fasttrap_exec;
92 #endif
93
94 SDT_PROVIDER_DECLARE(proc);
95 SDT_PROBE_DEFINE(proc, kernel, , exec, exec);
96 SDT_PROBE_ARGTYPE(proc, kernel, , exec, 0, "char *");
97 SDT_PROBE_DEFINE(proc, kernel, , exec_failure, exec-failure);
98 SDT_PROBE_ARGTYPE(proc, kernel, , exec_failure, 0, "int");
99 SDT_PROBE_DEFINE(proc, kernel, , exec_success, exec-success);
100 SDT_PROBE_ARGTYPE(proc, kernel, , exec_success, 0, "char *");
101
102 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
103
104 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
105 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
106 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
107 static int do_execve(struct thread *td, struct image_args *args,
108     struct mac *mac_p);
109 static void exec_free_args(struct image_args *);
110
111 /* XXX This should be vm_size_t. */
112 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD,
113     NULL, 0, sysctl_kern_ps_strings, "LU", "");
114
115 /* XXX This should be vm_size_t. */
116 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD,
117     NULL, 0, sysctl_kern_usrstack, "LU", "");
118
119 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD,
120     NULL, 0, sysctl_kern_stackprot, "I", "");
121
122 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
123 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW, 
124     &ps_arg_cache_limit, 0, "");
125
126 static int map_at_zero = 0;
127 TUNABLE_INT("security.bsd.map_at_zero", &map_at_zero);
128 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RW, &map_at_zero, 0,
129     "Permit processes to map an object at virtual address 0.");
130
131 static int
132 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
133 {
134         struct proc *p;
135         int error;
136
137         p = curproc;
138 #ifdef SCTL_MASK32
139         if (req->flags & SCTL_MASK32) {
140                 unsigned int val;
141                 val = (unsigned int)p->p_sysent->sv_psstrings;
142                 error = SYSCTL_OUT(req, &val, sizeof(val));
143         } else
144 #endif
145                 error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
146                    sizeof(p->p_sysent->sv_psstrings));
147         return error;
148 }
149
150 static int
151 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
152 {
153         struct proc *p;
154         int error;
155
156         p = curproc;
157 #ifdef SCTL_MASK32
158         if (req->flags & SCTL_MASK32) {
159                 unsigned int val;
160                 val = (unsigned int)p->p_sysent->sv_usrstack;
161                 error = SYSCTL_OUT(req, &val, sizeof(val));
162         } else
163 #endif
164                 error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
165                     sizeof(p->p_sysent->sv_usrstack));
166         return error;
167 }
168
169 static int
170 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
171 {
172         struct proc *p;
173
174         p = curproc;
175         return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
176             sizeof(p->p_sysent->sv_stackprot)));
177 }
178
179 /*
180  * Each of the items is a pointer to a `const struct execsw', hence the
181  * double pointer here.
182  */
183 static const struct execsw **execsw;
184
185 #ifndef _SYS_SYSPROTO_H_
186 struct execve_args {
187         char    *fname; 
188         char    **argv;
189         char    **envv; 
190 };
191 #endif
192
193 int
194 execve(td, uap)
195         struct thread *td;
196         struct execve_args /* {
197                 char *fname;
198                 char **argv;
199                 char **envv;
200         } */ *uap;
201 {
202         int error;
203         struct image_args args;
204
205         error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
206             uap->argv, uap->envv);
207         if (error == 0)
208                 error = kern_execve(td, &args, NULL);
209         return (error);
210 }
211
212 #ifndef _SYS_SYSPROTO_H_
213 struct fexecve_args {
214         int     fd;
215         char    **argv;
216         char    **envv;
217 }
218 #endif
219 int
220 fexecve(struct thread *td, struct fexecve_args *uap)
221 {
222         int error;
223         struct image_args args;
224
225         error = exec_copyin_args(&args, NULL, UIO_SYSSPACE,
226             uap->argv, uap->envv);
227         if (error == 0) {
228                 args.fd = uap->fd;
229                 error = kern_execve(td, &args, NULL);
230         }
231         return (error);
232 }
233
234 #ifndef _SYS_SYSPROTO_H_
235 struct __mac_execve_args {
236         char    *fname;
237         char    **argv;
238         char    **envv;
239         struct mac      *mac_p;
240 };
241 #endif
242
243 int
244 __mac_execve(td, uap)
245         struct thread *td;
246         struct __mac_execve_args /* {
247                 char *fname;
248                 char **argv;
249                 char **envv;
250                 struct mac *mac_p;
251         } */ *uap;
252 {
253 #ifdef MAC
254         int error;
255         struct image_args args;
256
257         error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
258             uap->argv, uap->envv);
259         if (error == 0)
260                 error = kern_execve(td, &args, uap->mac_p);
261         return (error);
262 #else
263         return (ENOSYS);
264 #endif
265 }
266
267 /*
268  * XXX: kern_execve has the astonishing property of not always returning to
269  * the caller.  If sufficiently bad things happen during the call to
270  * do_execve(), it can end up calling exit1(); as a result, callers must
271  * avoid doing anything which they might need to undo (e.g., allocating
272  * memory).
273  */
274 int
275 kern_execve(td, args, mac_p)
276         struct thread *td;
277         struct image_args *args;
278         struct mac *mac_p;
279 {
280         struct proc *p = td->td_proc;
281         int error;
282
283         AUDIT_ARG_ARGV(args->begin_argv, args->argc,
284             args->begin_envv - args->begin_argv);
285         AUDIT_ARG_ENVV(args->begin_envv, args->envc,
286             args->endp - args->begin_envv);
287         if (p->p_flag & P_HADTHREADS) {
288                 PROC_LOCK(p);
289                 if (thread_single(SINGLE_BOUNDARY)) {
290                         PROC_UNLOCK(p);
291                         exec_free_args(args);
292                         return (ERESTART);      /* Try again later. */
293                 }
294                 PROC_UNLOCK(p);
295         }
296
297         error = do_execve(td, args, mac_p);
298
299         if (p->p_flag & P_HADTHREADS) {
300                 PROC_LOCK(p);
301                 /*
302                  * If success, we upgrade to SINGLE_EXIT state to
303                  * force other threads to suicide.
304                  */
305                 if (error == 0)
306                         thread_single(SINGLE_EXIT);
307                 else
308                         thread_single_end();
309                 PROC_UNLOCK(p);
310         }
311
312         return (error);
313 }
314
315 /*
316  * In-kernel implementation of execve().  All arguments are assumed to be
317  * userspace pointers from the passed thread.
318  */
319 static int
320 do_execve(td, args, mac_p)
321         struct thread *td;
322         struct image_args *args;
323         struct mac *mac_p;
324 {
325         struct proc *p = td->td_proc;
326         struct nameidata nd;
327         struct ucred *newcred = NULL, *oldcred;
328         struct uidinfo *euip;
329         register_t *stack_base;
330         int error, i;
331         struct image_params image_params, *imgp;
332         struct vattr attr;
333         int (*img_first)(struct image_params *);
334         struct pargs *oldargs = NULL, *newargs = NULL;
335         struct sigacts *oldsigacts, *newsigacts;
336 #ifdef KTRACE
337         struct vnode *tracevp = NULL;
338         struct ucred *tracecred = NULL;
339 #endif
340         struct vnode *textvp = NULL, *binvp = NULL;
341         int credential_changing;
342         int vfslocked;
343         int textset;
344 #ifdef MAC
345         struct label *interpvplabel = NULL;
346         int will_transition;
347 #endif
348 #ifdef HWPMC_HOOKS
349         struct pmckern_procexec pe;
350 #endif
351         static const char fexecv_proc_title[] = "(fexecv)";
352
353         vfslocked = 0;
354         imgp = &image_params;
355
356         /*
357          * Lock the process and set the P_INEXEC flag to indicate that
358          * it should be left alone until we're done here.  This is
359          * necessary to avoid race conditions - e.g. in ptrace() -
360          * that might allow a local user to illicitly obtain elevated
361          * privileges.
362          */
363         PROC_LOCK(p);
364         KASSERT((p->p_flag & P_INEXEC) == 0,
365             ("%s(): process already has P_INEXEC flag", __func__));
366         p->p_flag |= P_INEXEC;
367         PROC_UNLOCK(p);
368
369         /*
370          * Initialize part of the common data
371          */
372         imgp->proc = p;
373         imgp->execlabel = NULL;
374         imgp->attr = &attr;
375         imgp->entry_addr = 0;
376         imgp->vmspace_destroyed = 0;
377         imgp->interpreted = 0;
378         imgp->opened = 0;
379         imgp->interpreter_name = args->buf + PATH_MAX + ARG_MAX;
380         imgp->auxargs = NULL;
381         imgp->vp = NULL;
382         imgp->object = NULL;
383         imgp->firstpage = NULL;
384         imgp->ps_strings = 0;
385         imgp->auxarg_size = 0;
386         imgp->args = args;
387         imgp->execpath = imgp->freepath = NULL;
388         imgp->execpathp = 0;
389
390 #ifdef MAC
391         error = mac_execve_enter(imgp, mac_p);
392         if (error)
393                 goto exec_fail;
394 #endif
395
396         imgp->image_header = NULL;
397
398         /*
399          * Translate the file name. namei() returns a vnode pointer
400          *      in ni_vp amoung other things.
401          *
402          * XXXAUDIT: It would be desirable to also audit the name of the
403          * interpreter if this is an interpreted binary.
404          */
405         if (args->fname != NULL) {
406                 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | FOLLOW | SAVENAME
407                     | MPSAFE | AUDITVNODE1, UIO_SYSSPACE, args->fname, td);
408         }
409
410         SDT_PROBE(proc, kernel, , exec, args->fname, 0, 0, 0, 0 );
411
412 interpret:
413         if (args->fname != NULL) {
414                 error = namei(&nd);
415                 if (error)
416                         goto exec_fail;
417
418                 vfslocked = NDHASGIANT(&nd);
419                 binvp  = nd.ni_vp;
420                 imgp->vp = binvp;
421         } else {
422                 AUDIT_ARG_FD(args->fd);
423                 error = fgetvp(td, args->fd, &binvp);
424                 if (error)
425                         goto exec_fail;
426                 vfslocked = VFS_LOCK_GIANT(binvp->v_mount);
427                 vn_lock(binvp, LK_EXCLUSIVE | LK_RETRY);
428                 AUDIT_ARG_VNODE1(binvp);
429                 imgp->vp = binvp;
430         }
431
432         /*
433          * Check file permissions (also 'opens' file)
434          */
435         error = exec_check_permissions(imgp);
436         if (error)
437                 goto exec_fail_dealloc;
438
439         imgp->object = imgp->vp->v_object;
440         if (imgp->object != NULL)
441                 vm_object_reference(imgp->object);
442
443         /*
444          * Set VV_TEXT now so no one can write to the executable while we're
445          * activating it.
446          *
447          * Remember if this was set before and unset it in case this is not
448          * actually an executable image.
449          */
450         textset = imgp->vp->v_vflag & VV_TEXT;
451         imgp->vp->v_vflag |= VV_TEXT;
452
453         error = exec_map_first_page(imgp);
454         if (error)
455                 goto exec_fail_dealloc;
456
457         imgp->proc->p_osrel = 0;
458         /*
459          *      If the current process has a special image activator it
460          *      wants to try first, call it.   For example, emulating shell
461          *      scripts differently.
462          */
463         error = -1;
464         if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
465                 error = img_first(imgp);
466
467         /*
468          *      Loop through the list of image activators, calling each one.
469          *      An activator returns -1 if there is no match, 0 on success,
470          *      and an error otherwise.
471          */
472         for (i = 0; error == -1 && execsw[i]; ++i) {
473                 if (execsw[i]->ex_imgact == NULL ||
474                     execsw[i]->ex_imgact == img_first) {
475                         continue;
476                 }
477                 error = (*execsw[i]->ex_imgact)(imgp);
478         }
479
480         if (error) {
481                 if (error == -1) {
482                         if (textset == 0)
483                                 imgp->vp->v_vflag &= ~VV_TEXT;
484                         error = ENOEXEC;
485                 }
486                 goto exec_fail_dealloc;
487         }
488
489         /*
490          * Special interpreter operation, cleanup and loop up to try to
491          * activate the interpreter.
492          */
493         if (imgp->interpreted) {
494                 exec_unmap_first_page(imgp);
495                 /*
496                  * VV_TEXT needs to be unset for scripts.  There is a short
497                  * period before we determine that something is a script where
498                  * VV_TEXT will be set. The vnode lock is held over this
499                  * entire period so nothing should illegitimately be blocked.
500                  */
501                 imgp->vp->v_vflag &= ~VV_TEXT;
502                 /* free name buffer and old vnode */
503                 if (args->fname != NULL)
504                         NDFREE(&nd, NDF_ONLY_PNBUF);
505 #ifdef MAC
506                 mac_execve_interpreter_enter(binvp, &interpvplabel);
507 #endif
508                 if (imgp->opened) {
509                         VOP_CLOSE(binvp, FREAD, td->td_ucred, td);
510                         imgp->opened = 0;
511                 }
512                 vput(binvp);
513                 vm_object_deallocate(imgp->object);
514                 imgp->object = NULL;
515                 VFS_UNLOCK_GIANT(vfslocked);
516                 vfslocked = 0;
517                 /* set new name to that of the interpreter */
518                 NDINIT(&nd, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME | MPSAFE,
519                     UIO_SYSSPACE, imgp->interpreter_name, td);
520                 args->fname = imgp->interpreter_name;
521                 goto interpret;
522         }
523
524         /*
525          * NB: We unlock the vnode here because it is believed that none
526          * of the sv_copyout_strings/sv_fixup operations require the vnode.
527          */
528         VOP_UNLOCK(imgp->vp, 0);
529
530         /*
531          * Do the best to calculate the full path to the image file.
532          */
533         if (imgp->auxargs != NULL &&
534             ((args->fname != NULL && args->fname[0] == '/') ||
535              vn_fullpath(td, imgp->vp, &imgp->execpath, &imgp->freepath) != 0))
536                 imgp->execpath = args->fname;
537
538         /*
539          * Copy out strings (args and env) and initialize stack base
540          */
541         if (p->p_sysent->sv_copyout_strings)
542                 stack_base = (*p->p_sysent->sv_copyout_strings)(imgp);
543         else
544                 stack_base = exec_copyout_strings(imgp);
545
546         /*
547          * If custom stack fixup routine present for this process
548          * let it do the stack setup.
549          * Else stuff argument count as first item on stack
550          */
551         if (p->p_sysent->sv_fixup != NULL)
552                 (*p->p_sysent->sv_fixup)(&stack_base, imgp);
553         else
554                 suword(--stack_base, imgp->args->argc);
555
556         /*
557          * For security and other reasons, the file descriptor table cannot
558          * be shared after an exec.
559          */
560         fdunshare(p, td);
561
562         /*
563          * Malloc things before we need locks.
564          */
565         newcred = crget();
566         euip = uifind(attr.va_uid);
567         i = imgp->args->begin_envv - imgp->args->begin_argv;
568         /* Cache arguments if they fit inside our allowance */
569         if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
570                 newargs = pargs_alloc(i);
571                 bcopy(imgp->args->begin_argv, newargs->ar_args, i);
572         }
573
574         /* close files on exec */
575         fdcloseexec(td);
576         vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
577
578         /* Get a reference to the vnode prior to locking the proc */
579         VREF(binvp);
580
581         /*
582          * For security and other reasons, signal handlers cannot
583          * be shared after an exec. The new process gets a copy of the old
584          * handlers. In execsigs(), the new process will have its signals
585          * reset.
586          */
587         PROC_LOCK(p);
588         oldcred = crcopysafe(p, newcred);
589         if (sigacts_shared(p->p_sigacts)) {
590                 oldsigacts = p->p_sigacts;
591                 PROC_UNLOCK(p);
592                 newsigacts = sigacts_alloc();
593                 sigacts_copy(newsigacts, oldsigacts);
594                 PROC_LOCK(p);
595                 p->p_sigacts = newsigacts;
596         } else
597                 oldsigacts = NULL;
598
599         /* Stop profiling */
600         stopprofclock(p);
601
602         /* reset caught signals */
603         execsigs(p);
604
605         /* name this process - nameiexec(p, ndp) */
606         bzero(p->p_comm, sizeof(p->p_comm));
607         if (args->fname)
608                 bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
609                     min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
610         else if (vn_commname(binvp, p->p_comm, sizeof(p->p_comm)) != 0)
611                 bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
612         bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
613 #ifdef KTR
614         sched_clear_tdname(td);
615 #endif
616
617         /*
618          * mark as execed, wakeup the process that vforked (if any) and tell
619          * it that it now has its own resources back
620          */
621         p->p_flag |= P_EXEC;
622         if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
623                 p->p_flag &= ~P_PPWAIT;
624                 cv_broadcast(&p->p_pwait);
625         }
626
627         /*
628          * Implement image setuid/setgid.
629          *
630          * Don't honor setuid/setgid if the filesystem prohibits it or if
631          * the process is being traced.
632          *
633          * XXXMAC: For the time being, use NOSUID to also prohibit
634          * transitions on the file system.
635          */
636         credential_changing = 0;
637         credential_changing |= (attr.va_mode & S_ISUID) && oldcred->cr_uid !=
638             attr.va_uid;
639         credential_changing |= (attr.va_mode & S_ISGID) && oldcred->cr_gid !=
640             attr.va_gid;
641 #ifdef MAC
642         will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
643             interpvplabel, imgp);
644         credential_changing |= will_transition;
645 #endif
646
647         if (credential_changing &&
648             (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
649             (p->p_flag & P_TRACED) == 0) {
650                 /*
651                  * Turn off syscall tracing for set-id programs, except for
652                  * root.  Record any set-id flags first to make sure that
653                  * we do not regain any tracing during a possible block.
654                  */
655                 setsugid(p);
656
657 #ifdef KTRACE
658                 if (p->p_tracecred != NULL &&
659                     priv_check_cred(p->p_tracecred, PRIV_DEBUG_DIFFCRED, 0))
660                         ktrprocexec(p, &tracecred, &tracevp);
661 #endif
662                 /*
663                  * Close any file descriptors 0..2 that reference procfs,
664                  * then make sure file descriptors 0..2 are in use.
665                  *
666                  * setugidsafety() may call closef() and then pfind()
667                  * which may grab the process lock.
668                  * fdcheckstd() may call falloc() which may block to
669                  * allocate memory, so temporarily drop the process lock.
670                  */
671                 PROC_UNLOCK(p);
672                 VOP_UNLOCK(imgp->vp, 0);
673                 setugidsafety(td);
674                 error = fdcheckstd(td);
675                 vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
676                 if (error != 0)
677                         goto done1;
678                 PROC_LOCK(p);
679                 /*
680                  * Set the new credentials.
681                  */
682                 if (attr.va_mode & S_ISUID)
683                         change_euid(newcred, euip);
684                 if (attr.va_mode & S_ISGID)
685                         change_egid(newcred, attr.va_gid);
686 #ifdef MAC
687                 if (will_transition) {
688                         mac_vnode_execve_transition(oldcred, newcred, imgp->vp,
689                             interpvplabel, imgp);
690                 }
691 #endif
692                 /*
693                  * Implement correct POSIX saved-id behavior.
694                  *
695                  * XXXMAC: Note that the current logic will save the
696                  * uid and gid if a MAC domain transition occurs, even
697                  * though maybe it shouldn't.
698                  */
699                 change_svuid(newcred, newcred->cr_uid);
700                 change_svgid(newcred, newcred->cr_gid);
701                 p->p_ucred = newcred;
702                 newcred = NULL;
703         } else {
704                 if (oldcred->cr_uid == oldcred->cr_ruid &&
705                     oldcred->cr_gid == oldcred->cr_rgid)
706                         p->p_flag &= ~P_SUGID;
707                 /*
708                  * Implement correct POSIX saved-id behavior.
709                  *
710                  * XXX: It's not clear that the existing behavior is
711                  * POSIX-compliant.  A number of sources indicate that the
712                  * saved uid/gid should only be updated if the new ruid is
713                  * not equal to the old ruid, or the new euid is not equal
714                  * to the old euid and the new euid is not equal to the old
715                  * ruid.  The FreeBSD code always updates the saved uid/gid.
716                  * Also, this code uses the new (replaced) euid and egid as
717                  * the source, which may or may not be the right ones to use.
718                  */
719                 if (oldcred->cr_svuid != oldcred->cr_uid ||
720                     oldcred->cr_svgid != oldcred->cr_gid) {
721                         change_svuid(newcred, newcred->cr_uid);
722                         change_svgid(newcred, newcred->cr_gid);
723                         p->p_ucred = newcred;
724                         newcred = NULL;
725                 }
726         }
727
728         /*
729          * Store the vp for use in procfs.  This vnode was referenced prior
730          * to locking the proc lock.
731          */
732         textvp = p->p_textvp;
733         p->p_textvp = binvp;
734
735 #ifdef KDTRACE_HOOKS
736         /*
737          * Tell the DTrace fasttrap provider about the exec if it
738          * has declared an interest.
739          */
740         if (dtrace_fasttrap_exec)
741                 dtrace_fasttrap_exec(p);
742 #endif
743
744         /*
745          * Notify others that we exec'd, and clear the P_INEXEC flag
746          * as we're now a bona fide freshly-execed process.
747          */
748         KNOTE_LOCKED(&p->p_klist, NOTE_EXEC);
749         p->p_flag &= ~P_INEXEC;
750
751         /* clear "fork but no exec" flag, as we _are_ execing */
752         p->p_acflag &= ~AFORK;
753
754         /*
755          * Free any previous argument cache and replace it with
756          * the new argument cache, if any.
757          */
758         oldargs = p->p_args;
759         p->p_args = newargs;
760         newargs = NULL;
761
762 #ifdef  HWPMC_HOOKS
763         /*
764          * Check if system-wide sampling is in effect or if the
765          * current process is using PMCs.  If so, do exec() time
766          * processing.  This processing needs to happen AFTER the
767          * P_INEXEC flag is cleared.
768          *
769          * The proc lock needs to be released before taking the PMC
770          * SX.
771          */
772         if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
773                 PROC_UNLOCK(p);
774                 VOP_UNLOCK(imgp->vp, 0);
775                 pe.pm_credentialschanged = credential_changing;
776                 pe.pm_entryaddr = imgp->entry_addr;
777
778                 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
779                 vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
780         } else
781                 PROC_UNLOCK(p);
782 #else  /* !HWPMC_HOOKS */
783         PROC_UNLOCK(p);
784 #endif
785
786         /* Set values passed into the program in registers. */
787         if (p->p_sysent->sv_setregs)
788                 (*p->p_sysent->sv_setregs)(td, imgp->entry_addr,
789                     (u_long)(uintptr_t)stack_base, imgp->ps_strings);
790         else
791                 exec_setregs(td, imgp->entry_addr,
792                     (u_long)(uintptr_t)stack_base, imgp->ps_strings);
793
794         vfs_mark_atime(imgp->vp, td->td_ucred);
795
796         SDT_PROBE(proc, kernel, , exec_success, args->fname, 0, 0, 0, 0);
797
798 done1:
799         /*
800          * Free any resources malloc'd earlier that we didn't use.
801          */
802         uifree(euip);
803         if (newcred == NULL)
804                 crfree(oldcred);
805         else
806                 crfree(newcred);
807         VOP_UNLOCK(imgp->vp, 0);
808
809         /*
810          * Handle deferred decrement of ref counts.
811          */
812         if (textvp != NULL) {
813                 int tvfslocked;
814
815                 tvfslocked = VFS_LOCK_GIANT(textvp->v_mount);
816                 vrele(textvp);
817                 VFS_UNLOCK_GIANT(tvfslocked);
818         }
819         if (binvp && error != 0)
820                 vrele(binvp);
821 #ifdef KTRACE
822         if (tracevp != NULL) {
823                 int tvfslocked;
824
825                 tvfslocked = VFS_LOCK_GIANT(tracevp->v_mount);
826                 vrele(tracevp);
827                 VFS_UNLOCK_GIANT(tvfslocked);
828         }
829         if (tracecred != NULL)
830                 crfree(tracecred);
831 #endif
832         vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
833         pargs_drop(oldargs);
834         pargs_drop(newargs);
835         if (oldsigacts != NULL)
836                 sigacts_free(oldsigacts);
837
838 exec_fail_dealloc:
839
840         /*
841          * free various allocated resources
842          */
843         if (imgp->firstpage != NULL)
844                 exec_unmap_first_page(imgp);
845
846         if (imgp->vp != NULL) {
847                 if (args->fname)
848                         NDFREE(&nd, NDF_ONLY_PNBUF);
849                 if (imgp->opened)
850                         VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
851                 vput(imgp->vp);
852         }
853
854         if (imgp->object != NULL)
855                 vm_object_deallocate(imgp->object);
856
857         free(imgp->freepath, M_TEMP);
858
859         if (error == 0) {
860                 PROC_LOCK(p);
861                 td->td_dbgflags |= TDB_EXEC;
862                 PROC_UNLOCK(p);
863
864                 /*
865                  * Stop the process here if its stop event mask has
866                  * the S_EXEC bit set.
867                  */
868                 STOPEVENT(p, S_EXEC, 0);
869                 goto done2;
870         }
871
872 exec_fail:
873         /* we're done here, clear P_INEXEC */
874         PROC_LOCK(p);
875         p->p_flag &= ~P_INEXEC;
876         PROC_UNLOCK(p);
877
878         SDT_PROBE(proc, kernel, , exec_failure, error, 0, 0, 0, 0);
879
880 done2:
881 #ifdef MAC
882         mac_execve_exit(imgp);
883         mac_execve_interpreter_exit(interpvplabel);
884 #endif
885         VFS_UNLOCK_GIANT(vfslocked);
886         exec_free_args(args);
887
888         if (error && imgp->vmspace_destroyed) {
889                 /* sorry, no more process anymore. exit gracefully */
890                 exit1(td, W_EXITCODE(0, SIGABRT));
891                 /* NOT REACHED */
892         }
893
894 #ifdef KTRACE
895         if (error == 0)
896                 ktrprocctor(p);
897 #endif
898
899         return (error);
900 }
901
902 int
903 exec_map_first_page(imgp)
904         struct image_params *imgp;
905 {
906         int rv, i;
907         int initial_pagein;
908         vm_page_t ma[VM_INITIAL_PAGEIN];
909         vm_object_t object;
910
911         if (imgp->firstpage != NULL)
912                 exec_unmap_first_page(imgp);
913
914         object = imgp->vp->v_object;
915         if (object == NULL)
916                 return (EACCES);
917         VM_OBJECT_LOCK(object);
918 #if VM_NRESERVLEVEL > 0
919         if ((object->flags & OBJ_COLORED) == 0) {
920                 object->flags |= OBJ_COLORED;
921                 object->pg_color = 0;
922         }
923 #endif
924         ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
925         if (ma[0]->valid != VM_PAGE_BITS_ALL) {
926                 initial_pagein = VM_INITIAL_PAGEIN;
927                 if (initial_pagein > object->size)
928                         initial_pagein = object->size;
929                 for (i = 1; i < initial_pagein; i++) {
930                         if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
931                                 if (ma[i]->valid)
932                                         break;
933                                 if ((ma[i]->oflags & VPO_BUSY) || ma[i]->busy)
934                                         break;
935                                 vm_page_busy(ma[i]);
936                         } else {
937                                 ma[i] = vm_page_alloc(object, i,
938                                     VM_ALLOC_NORMAL | VM_ALLOC_IFNOTCACHED);
939                                 if (ma[i] == NULL)
940                                         break;
941                         }
942                 }
943                 initial_pagein = i;
944                 rv = vm_pager_get_pages(object, ma, initial_pagein, 0);
945                 ma[0] = vm_page_lookup(object, 0);
946                 if ((rv != VM_PAGER_OK) || (ma[0] == NULL)) {
947                         if (ma[0]) {
948                                 vm_page_lock_queues();
949                                 vm_page_free(ma[0]);
950                                 vm_page_unlock_queues();
951                         }
952                         VM_OBJECT_UNLOCK(object);
953                         return (EIO);
954                 }
955         }
956         vm_page_lock_queues();
957         vm_page_hold(ma[0]);
958         vm_page_unlock_queues();
959         vm_page_wakeup(ma[0]);
960         VM_OBJECT_UNLOCK(object);
961
962         imgp->firstpage = sf_buf_alloc(ma[0], 0);
963         imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
964
965         return (0);
966 }
967
968 void
969 exec_unmap_first_page(imgp)
970         struct image_params *imgp;
971 {
972         vm_page_t m;
973
974         if (imgp->firstpage != NULL) {
975                 m = sf_buf_page(imgp->firstpage);
976                 sf_buf_free(imgp->firstpage);
977                 imgp->firstpage = NULL;
978                 vm_page_lock_queues();
979                 vm_page_unhold(m);
980                 vm_page_unlock_queues();
981         }
982 }
983
984 /*
985  * Destroy old address space, and allocate a new stack
986  *      The new stack is only SGROWSIZ large because it is grown
987  *      automatically in trap.c.
988  */
989 int
990 exec_new_vmspace(imgp, sv)
991         struct image_params *imgp;
992         struct sysentvec *sv;
993 {
994         int error;
995         struct proc *p = imgp->proc;
996         struct vmspace *vmspace = p->p_vmspace;
997         vm_offset_t sv_minuser, stack_addr;
998         vm_map_t map;
999         u_long ssiz;
1000
1001         imgp->vmspace_destroyed = 1;
1002         imgp->sysent = sv;
1003
1004         /* May be called with Giant held */
1005         EVENTHANDLER_INVOKE(process_exec, p, imgp);
1006
1007         /*
1008          * Blow away entire process VM, if address space not shared,
1009          * otherwise, create a new VM space so that other threads are
1010          * not disrupted
1011          */
1012         map = &vmspace->vm_map;
1013         if (map_at_zero)
1014                 sv_minuser = sv->sv_minuser;
1015         else
1016                 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1017         if (vmspace->vm_refcnt == 1 && vm_map_min(map) == sv_minuser &&
1018             vm_map_max(map) == sv->sv_maxuser) {
1019                 shmexit(vmspace);
1020                 pmap_remove_pages(vmspace_pmap(vmspace));
1021                 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1022         } else {
1023                 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1024                 if (error)
1025                         return (error);
1026                 vmspace = p->p_vmspace;
1027                 map = &vmspace->vm_map;
1028         }
1029
1030         /* Allocate a new stack */
1031         if (sv->sv_maxssiz != NULL)
1032                 ssiz = *sv->sv_maxssiz;
1033         else
1034                 ssiz = maxssiz;
1035         stack_addr = sv->sv_usrstack - ssiz;
1036         error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1037             sv->sv_stackprot, VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1038         if (error)
1039                 return (error);
1040
1041 #ifdef __ia64__
1042         /* Allocate a new register stack */
1043         stack_addr = IA64_BACKINGSTORE;
1044         error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1045             sv->sv_stackprot, VM_PROT_ALL, MAP_STACK_GROWS_UP);
1046         if (error)
1047                 return (error);
1048 #endif
1049
1050         /* vm_ssize and vm_maxsaddr are somewhat antiquated concepts in the
1051          * VM_STACK case, but they are still used to monitor the size of the
1052          * process stack so we can check the stack rlimit.
1053          */
1054         vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1055         vmspace->vm_maxsaddr = (char *)sv->sv_usrstack - ssiz;
1056
1057         return (0);
1058 }
1059
1060 /*
1061  * Copy out argument and environment strings from the old process address
1062  * space into the temporary string buffer.
1063  */
1064 int
1065 exec_copyin_args(struct image_args *args, char *fname,
1066     enum uio_seg segflg, char **argv, char **envv)
1067 {
1068         char *argp, *envp;
1069         int error;
1070         size_t length;
1071
1072         bzero(args, sizeof(*args));
1073         if (argv == NULL)
1074                 return (EFAULT);
1075         /*
1076          * Allocate temporary demand zeroed space for argument and
1077          *      environment strings:
1078          *
1079          * o ARG_MAX for argument and environment;
1080          * o MAXSHELLCMDLEN for the name of interpreters.
1081          */
1082         args->buf = (char *) kmem_alloc_wait(exec_map,
1083             PATH_MAX + ARG_MAX + MAXSHELLCMDLEN);
1084         if (args->buf == NULL)
1085                 return (ENOMEM);
1086         args->begin_argv = args->buf;
1087         args->endp = args->begin_argv;
1088         args->stringspace = ARG_MAX;
1089         /*
1090          * Copy the file name.
1091          */
1092         if (fname != NULL) {
1093                 args->fname = args->buf + ARG_MAX;
1094                 error = (segflg == UIO_SYSSPACE) ?
1095                     copystr(fname, args->fname, PATH_MAX, &length) :
1096                     copyinstr(fname, args->fname, PATH_MAX, &length);
1097                 if (error != 0)
1098                         goto err_exit;
1099         } else
1100                 args->fname = NULL;
1101
1102         /*
1103          * extract arguments first
1104          */
1105         while ((argp = (caddr_t) (intptr_t) fuword(argv++))) {
1106                 if (argp == (caddr_t) -1) {
1107                         error = EFAULT;
1108                         goto err_exit;
1109                 }
1110                 if ((error = copyinstr(argp, args->endp,
1111                     args->stringspace, &length))) {
1112                         if (error == ENAMETOOLONG) 
1113                                 error = E2BIG;
1114                         goto err_exit;
1115                 }
1116                 args->stringspace -= length;
1117                 args->endp += length;
1118                 args->argc++;
1119         }
1120
1121         args->begin_envv = args->endp;
1122
1123         /*
1124          * extract environment strings
1125          */
1126         if (envv) {
1127                 while ((envp = (caddr_t)(intptr_t)fuword(envv++))) {
1128                         if (envp == (caddr_t)-1) {
1129                                 error = EFAULT;
1130                                 goto err_exit;
1131                         }
1132                         if ((error = copyinstr(envp, args->endp,
1133                             args->stringspace, &length))) {
1134                                 if (error == ENAMETOOLONG)
1135                                         error = E2BIG;
1136                                 goto err_exit;
1137                         }
1138                         args->stringspace -= length;
1139                         args->endp += length;
1140                         args->envc++;
1141                 }
1142         }
1143
1144         return (0);
1145
1146 err_exit:
1147         exec_free_args(args);
1148         return (error);
1149 }
1150
1151 static void
1152 exec_free_args(struct image_args *args)
1153 {
1154
1155         if (args->buf) {
1156                 kmem_free_wakeup(exec_map, (vm_offset_t)args->buf,
1157                     PATH_MAX + ARG_MAX + MAXSHELLCMDLEN);
1158                 args->buf = NULL;
1159         }
1160 }
1161
1162 /*
1163  * Copy strings out to the new process address space, constructing new arg
1164  * and env vector tables. Return a pointer to the base so that it can be used
1165  * as the initial stack pointer.
1166  */
1167 register_t *
1168 exec_copyout_strings(imgp)
1169         struct image_params *imgp;
1170 {
1171         int argc, envc;
1172         char **vectp;
1173         char *stringp, *destp;
1174         register_t *stack_base;
1175         struct ps_strings *arginfo;
1176         struct proc *p;
1177         size_t execpath_len;
1178         int szsigcode;
1179
1180         /*
1181          * Calculate string base and vector table pointers.
1182          * Also deal with signal trampoline code for this exec type.
1183          */
1184         if (imgp->execpath != NULL && imgp->auxargs != NULL)
1185                 execpath_len = strlen(imgp->execpath) + 1;
1186         else
1187                 execpath_len = 0;
1188         p = imgp->proc;
1189         szsigcode = 0;
1190         arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1191         if (p->p_sysent->sv_szsigcode != NULL)
1192                 szsigcode = *(p->p_sysent->sv_szsigcode);
1193         destp = (caddr_t)arginfo - szsigcode - SPARE_USRSPACE -
1194             roundup(execpath_len, sizeof(char *)) -
1195             roundup((ARG_MAX - imgp->args->stringspace), sizeof(char *));
1196
1197         /*
1198          * install sigcode
1199          */
1200         if (szsigcode)
1201                 copyout(p->p_sysent->sv_sigcode, ((caddr_t)arginfo -
1202                     szsigcode), szsigcode);
1203
1204         /*
1205          * Copy the image path for the rtld.
1206          */
1207         if (execpath_len != 0) {
1208                 imgp->execpathp = (uintptr_t)arginfo - szsigcode - execpath_len;
1209                 copyout(imgp->execpath, (void *)imgp->execpathp,
1210                     execpath_len);
1211         }
1212
1213         /*
1214          * If we have a valid auxargs ptr, prepare some room
1215          * on the stack.
1216          */
1217         if (imgp->auxargs) {
1218                 /*
1219                  * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
1220                  * lower compatibility.
1221                  */
1222                 imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size :
1223                     (AT_COUNT * 2);
1224                 /*
1225                  * The '+ 2' is for the null pointers at the end of each of
1226                  * the arg and env vector sets,and imgp->auxarg_size is room
1227                  * for argument of Runtime loader.
1228                  */
1229                 vectp = (char **)(destp - (imgp->args->argc +
1230                     imgp->args->envc + 2 + imgp->auxarg_size + execpath_len) *
1231                     sizeof(char *));
1232         } else {
1233                 /*
1234                  * The '+ 2' is for the null pointers at the end of each of
1235                  * the arg and env vector sets
1236                  */
1237                 vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc + 2) *
1238                     sizeof(char *));
1239         }
1240
1241         /*
1242          * vectp also becomes our initial stack base
1243          */
1244         stack_base = (register_t *)vectp;
1245
1246         stringp = imgp->args->begin_argv;
1247         argc = imgp->args->argc;
1248         envc = imgp->args->envc;
1249
1250         /*
1251          * Copy out strings - arguments and environment.
1252          */
1253         copyout(stringp, destp, ARG_MAX - imgp->args->stringspace);
1254
1255         /*
1256          * Fill in "ps_strings" struct for ps, w, etc.
1257          */
1258         suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
1259         suword(&arginfo->ps_nargvstr, argc);
1260
1261         /*
1262          * Fill in argument portion of vector table.
1263          */
1264         for (; argc > 0; --argc) {
1265                 suword(vectp++, (long)(intptr_t)destp);
1266                 while (*stringp++ != 0)
1267                         destp++;
1268                 destp++;
1269         }
1270
1271         /* a null vector table pointer separates the argp's from the envp's */
1272         suword(vectp++, 0);
1273
1274         suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
1275         suword(&arginfo->ps_nenvstr, envc);
1276
1277         /*
1278          * Fill in environment portion of vector table.
1279          */
1280         for (; envc > 0; --envc) {
1281                 suword(vectp++, (long)(intptr_t)destp);
1282                 while (*stringp++ != 0)
1283                         destp++;
1284                 destp++;
1285         }
1286
1287         /* end of vector table is a null pointer */
1288         suword(vectp, 0);
1289
1290         return (stack_base);
1291 }
1292
1293 /*
1294  * Check permissions of file to execute.
1295  *      Called with imgp->vp locked.
1296  *      Return 0 for success or error code on failure.
1297  */
1298 int
1299 exec_check_permissions(imgp)
1300         struct image_params *imgp;
1301 {
1302         struct vnode *vp = imgp->vp;
1303         struct vattr *attr = imgp->attr;
1304         struct thread *td;
1305         int error;
1306
1307         td = curthread;
1308
1309         /* Get file attributes */
1310         error = VOP_GETATTR(vp, attr, td->td_ucred);
1311         if (error)
1312                 return (error);
1313
1314 #ifdef MAC
1315         error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1316         if (error)
1317                 return (error);
1318 #endif
1319         
1320         /*
1321          * 1) Check if file execution is disabled for the filesystem that this
1322          *      file resides on.
1323          * 2) Insure that at least one execute bit is on - otherwise root
1324          *      will always succeed, and we don't want to happen unless the
1325          *      file really is executable.
1326          * 3) Insure that the file is a regular file.
1327          */
1328         if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1329             ((attr->va_mode & 0111) == 0) ||
1330             (attr->va_type != VREG))
1331                 return (EACCES);
1332
1333         /*
1334          * Zero length files can't be exec'd
1335          */
1336         if (attr->va_size == 0)
1337                 return (ENOEXEC);
1338
1339         /*
1340          *  Check for execute permission to file based on current credentials.
1341          */
1342         error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1343         if (error)
1344                 return (error);
1345
1346         /*
1347          * Check number of open-for-writes on the file and deny execution
1348          * if there are any.
1349          */
1350         if (vp->v_writecount)
1351                 return (ETXTBSY);
1352
1353         /*
1354          * Call filesystem specific open routine (which does nothing in the
1355          * general case).
1356          */
1357         error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1358         if (error == 0)
1359                 imgp->opened = 1;
1360         return (error);
1361 }
1362
1363 /*
1364  * Exec handler registration
1365  */
1366 int
1367 exec_register(execsw_arg)
1368         const struct execsw *execsw_arg;
1369 {
1370         const struct execsw **es, **xs, **newexecsw;
1371         int count = 2;  /* New slot and trailing NULL */
1372
1373         if (execsw)
1374                 for (es = execsw; *es; es++)
1375                         count++;
1376         newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1377         if (newexecsw == NULL)
1378                 return (ENOMEM);
1379         xs = newexecsw;
1380         if (execsw)
1381                 for (es = execsw; *es; es++)
1382                         *xs++ = *es;
1383         *xs++ = execsw_arg;
1384         *xs = NULL;
1385         if (execsw)
1386                 free(execsw, M_TEMP);
1387         execsw = newexecsw;
1388         return (0);
1389 }
1390
1391 int
1392 exec_unregister(execsw_arg)
1393         const struct execsw *execsw_arg;
1394 {
1395         const struct execsw **es, **xs, **newexecsw;
1396         int count = 1;
1397
1398         if (execsw == NULL)
1399                 panic("unregister with no handlers left?\n");
1400
1401         for (es = execsw; *es; es++) {
1402                 if (*es == execsw_arg)
1403                         break;
1404         }
1405         if (*es == NULL)
1406                 return (ENOENT);
1407         for (es = execsw; *es; es++)
1408                 if (*es != execsw_arg)
1409                         count++;
1410         newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1411         if (newexecsw == NULL)
1412                 return (ENOMEM);
1413         xs = newexecsw;
1414         for (es = execsw; *es; es++)
1415                 if (*es != execsw_arg)
1416                         *xs++ = *es;
1417         *xs = NULL;
1418         if (execsw)
1419                 free(execsw, M_TEMP);
1420         execsw = newexecsw;
1421         return (0);
1422 }