]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_exec.c
zfs: merge openzfs/zfs@ec64fdb93 (master) into main
[FreeBSD/FreeBSD.git] / sys / kern / kern_exec.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1993, David Greenman
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include "opt_capsicum.h"
33 #include "opt_hwpmc_hooks.h"
34 #include "opt_ktrace.h"
35 #include "opt_vm.h"
36
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/acct.h>
40 #include <sys/asan.h>
41 #include <sys/capsicum.h>
42 #include <sys/compressor.h>
43 #include <sys/eventhandler.h>
44 #include <sys/exec.h>
45 #include <sys/fcntl.h>
46 #include <sys/filedesc.h>
47 #include <sys/imgact.h>
48 #include <sys/imgact_elf.h>
49 #include <sys/kernel.h>
50 #include <sys/lock.h>
51 #include <sys/malloc.h>
52 #include <sys/mman.h>
53 #include <sys/mount.h>
54 #include <sys/mutex.h>
55 #include <sys/namei.h>
56 #include <sys/priv.h>
57 #include <sys/proc.h>
58 #include <sys/ptrace.h>
59 #include <sys/reg.h>
60 #include <sys/resourcevar.h>
61 #include <sys/rwlock.h>
62 #include <sys/sched.h>
63 #include <sys/sdt.h>
64 #include <sys/sf_buf.h>
65 #include <sys/shm.h>
66 #include <sys/signalvar.h>
67 #include <sys/smp.h>
68 #include <sys/stat.h>
69 #include <sys/syscallsubr.h>
70 #include <sys/sysctl.h>
71 #include <sys/sysent.h>
72 #include <sys/sysproto.h>
73 #include <sys/timers.h>
74 #include <sys/umtxvar.h>
75 #include <sys/vnode.h>
76 #include <sys/wait.h>
77 #ifdef KTRACE
78 #include <sys/ktrace.h>
79 #endif
80
81 #include <vm/vm.h>
82 #include <vm/vm_param.h>
83 #include <vm/pmap.h>
84 #include <vm/vm_page.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_kern.h>
87 #include <vm/vm_extern.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_pager.h>
90
91 #ifdef  HWPMC_HOOKS
92 #include <sys/pmckern.h>
93 #endif
94
95 #include <security/audit/audit.h>
96 #include <security/mac/mac_framework.h>
97
98 #ifdef KDTRACE_HOOKS
99 #include <sys/dtrace_bsd.h>
100 dtrace_execexit_func_t  dtrace_fasttrap_exec;
101 #endif
102
103 SDT_PROVIDER_DECLARE(proc);
104 SDT_PROBE_DEFINE1(proc, , , exec, "char *");
105 SDT_PROBE_DEFINE1(proc, , , exec__failure, "int");
106 SDT_PROBE_DEFINE1(proc, , , exec__success, "char *");
107
108 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
109
110 int coredump_pack_fileinfo = 1;
111 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_fileinfo, CTLFLAG_RWTUN,
112     &coredump_pack_fileinfo, 0,
113     "Enable file path packing in 'procstat -f' coredump notes");
114
115 int coredump_pack_vmmapinfo = 1;
116 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_vmmapinfo, CTLFLAG_RWTUN,
117     &coredump_pack_vmmapinfo, 0,
118     "Enable file path packing in 'procstat -v' coredump notes");
119
120 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
121 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
122 static int sysctl_kern_stacktop(SYSCTL_HANDLER_ARGS);
123 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
124 static int do_execve(struct thread *td, struct image_args *args,
125     struct mac *mac_p, struct vmspace *oldvmspace);
126
127 /* XXX This should be vm_size_t. */
128 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD|
129     CTLFLAG_CAPRD|CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_ps_strings, "LU",
130     "Location of process' ps_strings structure");
131
132 /* XXX This should be vm_size_t. */
133 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD|
134     CTLFLAG_CAPRD|CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_usrstack, "LU",
135     "Top of process stack");
136
137 SYSCTL_PROC(_kern, KERN_STACKTOP, stacktop, CTLTYPE_ULONG | CTLFLAG_RD |
138     CTLFLAG_CAPRD | CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_stacktop, "LU",
139     "Top of process stack with stack gap.");
140
141 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD|CTLFLAG_MPSAFE,
142     NULL, 0, sysctl_kern_stackprot, "I",
143     "Stack memory permissions");
144
145 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
146 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW, 
147     &ps_arg_cache_limit, 0,
148     "Process' command line characters cache limit");
149
150 static int disallow_high_osrel;
151 SYSCTL_INT(_kern, OID_AUTO, disallow_high_osrel, CTLFLAG_RW,
152     &disallow_high_osrel, 0,
153     "Disallow execution of binaries built for higher version of the world");
154
155 static int map_at_zero = 0;
156 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RWTUN, &map_at_zero, 0,
157     "Permit processes to map an object at virtual address 0.");
158
159 static int core_dump_can_intr = 1;
160 SYSCTL_INT(_kern, OID_AUTO, core_dump_can_intr, CTLFLAG_RWTUN,
161     &core_dump_can_intr, 0,
162     "Core dumping interruptible with SIGKILL");
163
164 static int
165 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
166 {
167         struct proc *p;
168         int error;
169
170         p = curproc;
171 #ifdef SCTL_MASK32
172         if (req->flags & SCTL_MASK32) {
173                 unsigned int val;
174                 val = (unsigned int)p->p_sysent->sv_psstrings;
175                 error = SYSCTL_OUT(req, &val, sizeof(val));
176         } else
177 #endif
178                 error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
179                    sizeof(p->p_sysent->sv_psstrings));
180         return error;
181 }
182
183 static int
184 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
185 {
186         struct proc *p;
187         int error;
188
189         p = curproc;
190 #ifdef SCTL_MASK32
191         if (req->flags & SCTL_MASK32) {
192                 unsigned int val;
193                 val = (unsigned int)p->p_sysent->sv_usrstack;
194                 error = SYSCTL_OUT(req, &val, sizeof(val));
195         } else
196 #endif
197                 error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
198                     sizeof(p->p_sysent->sv_usrstack));
199         return (error);
200 }
201
202 static int
203 sysctl_kern_stacktop(SYSCTL_HANDLER_ARGS)
204 {
205         vm_offset_t stacktop;
206         struct proc *p;
207         int error;
208
209         p = curproc;
210 #ifdef SCTL_MASK32
211         if (req->flags & SCTL_MASK32) {
212                 unsigned int val;
213
214                 val = (unsigned int)(p->p_sysent->sv_usrstack -
215                     p->p_vmspace->vm_stkgap);
216                 error = SYSCTL_OUT(req, &val, sizeof(val));
217         } else
218 #endif
219         {
220                 stacktop = p->p_sysent->sv_usrstack - p->p_vmspace->vm_stkgap;
221                 error = SYSCTL_OUT(req, &stacktop, sizeof(stacktop));
222         }
223         return (error);
224 }
225
226 static int
227 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
228 {
229         struct proc *p;
230
231         p = curproc;
232         return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
233             sizeof(p->p_sysent->sv_stackprot)));
234 }
235
236 /*
237  * Each of the items is a pointer to a `const struct execsw', hence the
238  * double pointer here.
239  */
240 static const struct execsw **execsw;
241
242 #ifndef _SYS_SYSPROTO_H_
243 struct execve_args {
244         char    *fname; 
245         char    **argv;
246         char    **envv; 
247 };
248 #endif
249
250 int
251 sys_execve(struct thread *td, struct execve_args *uap)
252 {
253         struct image_args args;
254         struct vmspace *oldvmspace;
255         int error;
256
257         error = pre_execve(td, &oldvmspace);
258         if (error != 0)
259                 return (error);
260         error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
261             uap->argv, uap->envv);
262         if (error == 0)
263                 error = kern_execve(td, &args, NULL, oldvmspace);
264         post_execve(td, error, oldvmspace);
265         AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
266         return (error);
267 }
268
269 #ifndef _SYS_SYSPROTO_H_
270 struct fexecve_args {
271         int     fd;
272         char    **argv;
273         char    **envv;
274 };
275 #endif
276 int
277 sys_fexecve(struct thread *td, struct fexecve_args *uap)
278 {
279         struct image_args args;
280         struct vmspace *oldvmspace;
281         int error;
282
283         error = pre_execve(td, &oldvmspace);
284         if (error != 0)
285                 return (error);
286         error = exec_copyin_args(&args, NULL, UIO_SYSSPACE,
287             uap->argv, uap->envv);
288         if (error == 0) {
289                 args.fd = uap->fd;
290                 error = kern_execve(td, &args, NULL, oldvmspace);
291         }
292         post_execve(td, error, oldvmspace);
293         AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
294         return (error);
295 }
296
297 #ifndef _SYS_SYSPROTO_H_
298 struct __mac_execve_args {
299         char    *fname;
300         char    **argv;
301         char    **envv;
302         struct mac      *mac_p;
303 };
304 #endif
305
306 int
307 sys___mac_execve(struct thread *td, struct __mac_execve_args *uap)
308 {
309 #ifdef MAC
310         struct image_args args;
311         struct vmspace *oldvmspace;
312         int error;
313
314         error = pre_execve(td, &oldvmspace);
315         if (error != 0)
316                 return (error);
317         error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
318             uap->argv, uap->envv);
319         if (error == 0)
320                 error = kern_execve(td, &args, uap->mac_p, oldvmspace);
321         post_execve(td, error, oldvmspace);
322         AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
323         return (error);
324 #else
325         return (ENOSYS);
326 #endif
327 }
328
329 int
330 pre_execve(struct thread *td, struct vmspace **oldvmspace)
331 {
332         struct proc *p;
333         int error;
334
335         KASSERT(td == curthread, ("non-current thread %p", td));
336         error = 0;
337         p = td->td_proc;
338         if ((p->p_flag & P_HADTHREADS) != 0) {
339                 PROC_LOCK(p);
340                 if (thread_single(p, SINGLE_BOUNDARY) != 0)
341                         error = ERESTART;
342                 PROC_UNLOCK(p);
343         }
344         KASSERT(error != 0 || (td->td_pflags & TDP_EXECVMSPC) == 0,
345             ("nested execve"));
346         *oldvmspace = p->p_vmspace;
347         return (error);
348 }
349
350 void
351 post_execve(struct thread *td, int error, struct vmspace *oldvmspace)
352 {
353         struct proc *p;
354
355         KASSERT(td == curthread, ("non-current thread %p", td));
356         p = td->td_proc;
357         if ((p->p_flag & P_HADTHREADS) != 0) {
358                 PROC_LOCK(p);
359                 /*
360                  * If success, we upgrade to SINGLE_EXIT state to
361                  * force other threads to suicide.
362                  */
363                 if (error == EJUSTRETURN)
364                         thread_single(p, SINGLE_EXIT);
365                 else
366                         thread_single_end(p, SINGLE_BOUNDARY);
367                 PROC_UNLOCK(p);
368         }
369         exec_cleanup(td, oldvmspace);
370 }
371
372 /*
373  * kern_execve() has the astonishing property of not always returning to
374  * the caller.  If sufficiently bad things happen during the call to
375  * do_execve(), it can end up calling exit1(); as a result, callers must
376  * avoid doing anything which they might need to undo (e.g., allocating
377  * memory).
378  */
379 int
380 kern_execve(struct thread *td, struct image_args *args, struct mac *mac_p,
381     struct vmspace *oldvmspace)
382 {
383
384         TSEXEC(td->td_proc->p_pid, args->begin_argv);
385         AUDIT_ARG_ARGV(args->begin_argv, args->argc,
386             exec_args_get_begin_envv(args) - args->begin_argv);
387         AUDIT_ARG_ENVV(exec_args_get_begin_envv(args), args->envc,
388             args->endp - exec_args_get_begin_envv(args));
389         return (do_execve(td, args, mac_p, oldvmspace));
390 }
391
392 static void
393 execve_nosetid(struct image_params *imgp)
394 {
395         imgp->credential_setid = false;
396         if (imgp->newcred != NULL) {
397                 crfree(imgp->newcred);
398                 imgp->newcred = NULL;
399         }
400 }
401
402 /*
403  * In-kernel implementation of execve().  All arguments are assumed to be
404  * userspace pointers from the passed thread.
405  */
406 static int
407 do_execve(struct thread *td, struct image_args *args, struct mac *mac_p,
408     struct vmspace *oldvmspace)
409 {
410         struct proc *p = td->td_proc;
411         struct nameidata nd;
412         struct ucred *oldcred;
413         struct uidinfo *euip = NULL;
414         uintptr_t stack_base;
415         struct image_params image_params, *imgp;
416         struct vattr attr;
417         int (*img_first)(struct image_params *);
418         struct pargs *oldargs = NULL, *newargs = NULL;
419         struct sigacts *oldsigacts = NULL, *newsigacts = NULL;
420 #ifdef KTRACE
421         struct ktr_io_params *kiop;
422 #endif
423         struct vnode *oldtextvp = NULL, *newtextvp;
424         int credential_changing;
425 #ifdef MAC
426         struct label *interpvplabel = NULL;
427         int will_transition;
428 #endif
429 #ifdef HWPMC_HOOKS
430         struct pmckern_procexec pe;
431 #endif
432         int error, i, orig_osrel;
433         uint32_t orig_fctl0;
434         Elf_Brandinfo *orig_brandinfo;
435         static const char fexecv_proc_title[] = "(fexecv)";
436
437         imgp = &image_params;
438 #ifdef KTRACE
439         kiop = NULL;
440 #endif
441
442         /*
443          * Lock the process and set the P_INEXEC flag to indicate that
444          * it should be left alone until we're done here.  This is
445          * necessary to avoid race conditions - e.g. in ptrace() -
446          * that might allow a local user to illicitly obtain elevated
447          * privileges.
448          */
449         PROC_LOCK(p);
450         KASSERT((p->p_flag & P_INEXEC) == 0,
451             ("%s(): process already has P_INEXEC flag", __func__));
452         p->p_flag |= P_INEXEC;
453         PROC_UNLOCK(p);
454
455         /*
456          * Initialize part of the common data
457          */
458         bzero(imgp, sizeof(*imgp));
459         imgp->proc = p;
460         imgp->attr = &attr;
461         imgp->args = args;
462         oldcred = p->p_ucred;
463         orig_osrel = p->p_osrel;
464         orig_fctl0 = p->p_fctl0;
465         orig_brandinfo = p->p_elf_brandinfo;
466
467 #ifdef MAC
468         error = mac_execve_enter(imgp, mac_p);
469         if (error)
470                 goto exec_fail;
471 #endif
472
473         /*
474          * Translate the file name. namei() returns a vnode pointer
475          *      in ni_vp among other things.
476          *
477          * XXXAUDIT: It would be desirable to also audit the name of the
478          * interpreter if this is an interpreted binary.
479          */
480         if (args->fname != NULL) {
481                 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | LOCKSHARED | FOLLOW |
482                     SAVENAME | AUDITVNODE1, UIO_SYSSPACE, args->fname, td);
483         }
484
485         SDT_PROBE1(proc, , , exec, args->fname);
486
487 interpret:
488         if (args->fname != NULL) {
489 #ifdef CAPABILITY_MODE
490                 /*
491                  * While capability mode can't reach this point via direct
492                  * path arguments to execve(), we also don't allow
493                  * interpreters to be used in capability mode (for now).
494                  * Catch indirect lookups and return a permissions error.
495                  */
496                 if (IN_CAPABILITY_MODE(td)) {
497                         error = ECAPMODE;
498                         goto exec_fail;
499                 }
500 #endif
501                 error = namei(&nd);
502                 if (error)
503                         goto exec_fail;
504
505                 newtextvp = nd.ni_vp;
506                 imgp->vp = newtextvp;
507         } else {
508                 AUDIT_ARG_FD(args->fd);
509                 /*
510                  * Descriptors opened only with O_EXEC or O_RDONLY are allowed.
511                  */
512                 error = fgetvp_exec(td, args->fd, &cap_fexecve_rights, &newtextvp);
513                 if (error)
514                         goto exec_fail;
515                 vn_lock(newtextvp, LK_SHARED | LK_RETRY);
516                 AUDIT_ARG_VNODE1(newtextvp);
517                 imgp->vp = newtextvp;
518         }
519
520         /*
521          * Check file permissions.  Also 'opens' file and sets its vnode to
522          * text mode.
523          */
524         error = exec_check_permissions(imgp);
525         if (error)
526                 goto exec_fail_dealloc;
527
528         imgp->object = imgp->vp->v_object;
529         if (imgp->object != NULL)
530                 vm_object_reference(imgp->object);
531
532         error = exec_map_first_page(imgp);
533         if (error)
534                 goto exec_fail_dealloc;
535
536         imgp->proc->p_osrel = 0;
537         imgp->proc->p_fctl0 = 0;
538         imgp->proc->p_elf_brandinfo = NULL;
539
540         /*
541          * Implement image setuid/setgid.
542          *
543          * Determine new credentials before attempting image activators
544          * so that it can be used by process_exec handlers to determine
545          * credential/setid changes.
546          *
547          * Don't honor setuid/setgid if the filesystem prohibits it or if
548          * the process is being traced.
549          *
550          * We disable setuid/setgid/etc in capability mode on the basis
551          * that most setugid applications are not written with that
552          * environment in mind, and will therefore almost certainly operate
553          * incorrectly. In principle there's no reason that setugid
554          * applications might not be useful in capability mode, so we may want
555          * to reconsider this conservative design choice in the future.
556          *
557          * XXXMAC: For the time being, use NOSUID to also prohibit
558          * transitions on the file system.
559          */
560         credential_changing = 0;
561         credential_changing |= (attr.va_mode & S_ISUID) &&
562             oldcred->cr_uid != attr.va_uid;
563         credential_changing |= (attr.va_mode & S_ISGID) &&
564             oldcred->cr_gid != attr.va_gid;
565 #ifdef MAC
566         will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
567             interpvplabel, imgp);
568         credential_changing |= will_transition;
569 #endif
570
571         /* Don't inherit PROC_PDEATHSIG_CTL value if setuid/setgid. */
572         if (credential_changing)
573                 imgp->proc->p_pdeathsig = 0;
574
575         if (credential_changing &&
576 #ifdef CAPABILITY_MODE
577             ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) &&
578 #endif
579             (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
580             (p->p_flag & P_TRACED) == 0) {
581                 imgp->credential_setid = true;
582                 VOP_UNLOCK(imgp->vp);
583                 imgp->newcred = crdup(oldcred);
584                 if (attr.va_mode & S_ISUID) {
585                         euip = uifind(attr.va_uid);
586                         change_euid(imgp->newcred, euip);
587                 }
588                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
589                 if (attr.va_mode & S_ISGID)
590                         change_egid(imgp->newcred, attr.va_gid);
591                 /*
592                  * Implement correct POSIX saved-id behavior.
593                  *
594                  * XXXMAC: Note that the current logic will save the
595                  * uid and gid if a MAC domain transition occurs, even
596                  * though maybe it shouldn't.
597                  */
598                 change_svuid(imgp->newcred, imgp->newcred->cr_uid);
599                 change_svgid(imgp->newcred, imgp->newcred->cr_gid);
600         } else {
601                 /*
602                  * Implement correct POSIX saved-id behavior.
603                  *
604                  * XXX: It's not clear that the existing behavior is
605                  * POSIX-compliant.  A number of sources indicate that the
606                  * saved uid/gid should only be updated if the new ruid is
607                  * not equal to the old ruid, or the new euid is not equal
608                  * to the old euid and the new euid is not equal to the old
609                  * ruid.  The FreeBSD code always updates the saved uid/gid.
610                  * Also, this code uses the new (replaced) euid and egid as
611                  * the source, which may or may not be the right ones to use.
612                  */
613                 if (oldcred->cr_svuid != oldcred->cr_uid ||
614                     oldcred->cr_svgid != oldcred->cr_gid) {
615                         VOP_UNLOCK(imgp->vp);
616                         imgp->newcred = crdup(oldcred);
617                         vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
618                         change_svuid(imgp->newcred, imgp->newcred->cr_uid);
619                         change_svgid(imgp->newcred, imgp->newcred->cr_gid);
620                 }
621         }
622         /* The new credentials are installed into the process later. */
623
624         /*
625          * Do the best to calculate the full path to the image file.
626          */
627         if (args->fname != NULL && args->fname[0] == '/')
628                 imgp->execpath = args->fname;
629         else {
630                 VOP_UNLOCK(imgp->vp);
631                 if (vn_fullpath(imgp->vp, &imgp->execpath, &imgp->freepath) != 0)
632                         imgp->execpath = args->fname;
633                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
634         }
635
636         /*
637          *      If the current process has a special image activator it
638          *      wants to try first, call it.   For example, emulating shell
639          *      scripts differently.
640          */
641         error = -1;
642         if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
643                 error = img_first(imgp);
644
645         /*
646          *      Loop through the list of image activators, calling each one.
647          *      An activator returns -1 if there is no match, 0 on success,
648          *      and an error otherwise.
649          */
650         for (i = 0; error == -1 && execsw[i]; ++i) {
651                 if (execsw[i]->ex_imgact == NULL ||
652                     execsw[i]->ex_imgact == img_first) {
653                         continue;
654                 }
655                 error = (*execsw[i]->ex_imgact)(imgp);
656         }
657
658         if (error) {
659                 if (error == -1)
660                         error = ENOEXEC;
661                 goto exec_fail_dealloc;
662         }
663
664         /*
665          * Special interpreter operation, cleanup and loop up to try to
666          * activate the interpreter.
667          */
668         if (imgp->interpreted) {
669                 exec_unmap_first_page(imgp);
670                 /*
671                  * The text reference needs to be removed for scripts.
672                  * There is a short period before we determine that
673                  * something is a script where text reference is active.
674                  * The vnode lock is held over this entire period
675                  * so nothing should illegitimately be blocked.
676                  */
677                 MPASS(imgp->textset);
678                 VOP_UNSET_TEXT_CHECKED(newtextvp);
679                 imgp->textset = false;
680                 /* free name buffer and old vnode */
681                 if (args->fname != NULL)
682                         NDFREE(&nd, NDF_ONLY_PNBUF);
683 #ifdef MAC
684                 mac_execve_interpreter_enter(newtextvp, &interpvplabel);
685 #endif
686                 if (imgp->opened) {
687                         VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td);
688                         imgp->opened = 0;
689                 }
690                 vput(newtextvp);
691                 vm_object_deallocate(imgp->object);
692                 imgp->object = NULL;
693                 execve_nosetid(imgp);
694                 imgp->execpath = NULL;
695                 free(imgp->freepath, M_TEMP);
696                 imgp->freepath = NULL;
697                 /* set new name to that of the interpreter */
698                 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | LOCKSHARED | FOLLOW |
699                     SAVENAME, UIO_SYSSPACE, imgp->interpreter_name, td);
700                 args->fname = imgp->interpreter_name;
701                 goto interpret;
702         }
703
704         /*
705          * NB: We unlock the vnode here because it is believed that none
706          * of the sv_copyout_strings/sv_fixup operations require the vnode.
707          */
708         VOP_UNLOCK(imgp->vp);
709
710         if (disallow_high_osrel &&
711             P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) {
712                 error = ENOEXEC;
713                 uprintf("Osrel %d for image %s too high\n", p->p_osrel,
714                     imgp->execpath != NULL ? imgp->execpath : "<unresolved>");
715                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
716                 goto exec_fail_dealloc;
717         }
718
719         /*
720          * Copy out strings (args and env) and initialize stack base.
721          */
722         error = (*p->p_sysent->sv_copyout_strings)(imgp, &stack_base);
723         if (error != 0) {
724                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
725                 goto exec_fail_dealloc;
726         }
727
728         /*
729          * Stack setup.
730          */
731         error = (*p->p_sysent->sv_fixup)(&stack_base, imgp);
732         if (error != 0) {
733                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
734                 goto exec_fail_dealloc;
735         }
736
737         /*
738          * For security and other reasons, the file descriptor table cannot be
739          * shared after an exec.
740          */
741         fdunshare(td);
742         pdunshare(td);
743         /* close files on exec */
744         fdcloseexec(td);
745
746         /*
747          * Malloc things before we need locks.
748          */
749         i = exec_args_get_begin_envv(imgp->args) - imgp->args->begin_argv;
750         /* Cache arguments if they fit inside our allowance */
751         if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
752                 newargs = pargs_alloc(i);
753                 bcopy(imgp->args->begin_argv, newargs->ar_args, i);
754         }
755
756         /*
757          * For security and other reasons, signal handlers cannot
758          * be shared after an exec. The new process gets a copy of the old
759          * handlers. In execsigs(), the new process will have its signals
760          * reset.
761          */
762         if (sigacts_shared(p->p_sigacts)) {
763                 oldsigacts = p->p_sigacts;
764                 newsigacts = sigacts_alloc();
765                 sigacts_copy(newsigacts, oldsigacts);
766         }
767
768         vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
769
770         PROC_LOCK(p);
771         if (oldsigacts)
772                 p->p_sigacts = newsigacts;
773         /* Stop profiling */
774         stopprofclock(p);
775
776         /* reset caught signals */
777         execsigs(p);
778
779         /* name this process - nameiexec(p, ndp) */
780         bzero(p->p_comm, sizeof(p->p_comm));
781         if (args->fname)
782                 bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
783                     min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
784         else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0)
785                 bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
786         bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
787 #ifdef KTR
788         sched_clear_tdname(td);
789 #endif
790
791         /*
792          * mark as execed, wakeup the process that vforked (if any) and tell
793          * it that it now has its own resources back
794          */
795         p->p_flag |= P_EXEC;
796         if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
797                 p->p_flag2 &= ~P2_NOTRACE;
798         if ((p->p_flag2 & P2_STKGAP_DISABLE_EXEC) == 0)
799                 p->p_flag2 &= ~P2_STKGAP_DISABLE;
800         if (p->p_flag & P_PPWAIT) {
801                 p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
802                 cv_broadcast(&p->p_pwait);
803                 /* STOPs are no longer ignored, arrange for AST */
804                 signotify(td);
805         }
806
807         if ((imgp->sysent->sv_setid_allowed != NULL &&
808             !(*imgp->sysent->sv_setid_allowed)(td, imgp)) ||
809             (p->p_flag2 & P2_NO_NEW_PRIVS) != 0)
810                 execve_nosetid(imgp);
811
812         /*
813          * Implement image setuid/setgid installation.
814          */
815         if (imgp->credential_setid) {
816                 /*
817                  * Turn off syscall tracing for set-id programs, except for
818                  * root.  Record any set-id flags first to make sure that
819                  * we do not regain any tracing during a possible block.
820                  */
821                 setsugid(p);
822 #ifdef KTRACE
823                 kiop = ktrprocexec(p);
824 #endif
825                 /*
826                  * Close any file descriptors 0..2 that reference procfs,
827                  * then make sure file descriptors 0..2 are in use.
828                  *
829                  * Both fdsetugidsafety() and fdcheckstd() may call functions
830                  * taking sleepable locks, so temporarily drop our locks.
831                  */
832                 PROC_UNLOCK(p);
833                 VOP_UNLOCK(imgp->vp);
834                 fdsetugidsafety(td);
835                 error = fdcheckstd(td);
836                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
837                 if (error != 0)
838                         goto exec_fail_dealloc;
839                 PROC_LOCK(p);
840 #ifdef MAC
841                 if (will_transition) {
842                         mac_vnode_execve_transition(oldcred, imgp->newcred,
843                             imgp->vp, interpvplabel, imgp);
844                 }
845 #endif
846         } else {
847                 if (oldcred->cr_uid == oldcred->cr_ruid &&
848                     oldcred->cr_gid == oldcred->cr_rgid)
849                         p->p_flag &= ~P_SUGID;
850         }
851         /*
852          * Set the new credentials.
853          */
854         if (imgp->newcred != NULL) {
855                 proc_set_cred(p, imgp->newcred);
856                 crfree(oldcred);
857                 oldcred = NULL;
858         }
859
860         /*
861          * Store the vp for use in procfs.  This vnode was referenced by namei
862          * or fgetvp_exec.
863          */
864         oldtextvp = p->p_textvp;
865         p->p_textvp = newtextvp;
866
867 #ifdef KDTRACE_HOOKS
868         /*
869          * Tell the DTrace fasttrap provider about the exec if it
870          * has declared an interest.
871          */
872         if (dtrace_fasttrap_exec)
873                 dtrace_fasttrap_exec(p);
874 #endif
875
876         /*
877          * Notify others that we exec'd, and clear the P_INEXEC flag
878          * as we're now a bona fide freshly-execed process.
879          */
880         KNOTE_LOCKED(p->p_klist, NOTE_EXEC);
881         p->p_flag &= ~P_INEXEC;
882
883         /* clear "fork but no exec" flag, as we _are_ execing */
884         p->p_acflag &= ~AFORK;
885
886         /*
887          * Free any previous argument cache and replace it with
888          * the new argument cache, if any.
889          */
890         oldargs = p->p_args;
891         p->p_args = newargs;
892         newargs = NULL;
893
894         PROC_UNLOCK(p);
895
896 #ifdef  HWPMC_HOOKS
897         /*
898          * Check if system-wide sampling is in effect or if the
899          * current process is using PMCs.  If so, do exec() time
900          * processing.  This processing needs to happen AFTER the
901          * P_INEXEC flag is cleared.
902          */
903         if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
904                 VOP_UNLOCK(imgp->vp);
905                 pe.pm_credentialschanged = credential_changing;
906                 pe.pm_entryaddr = imgp->entry_addr;
907
908                 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
909                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
910         }
911 #endif
912
913         /* Set values passed into the program in registers. */
914         (*p->p_sysent->sv_setregs)(td, imgp, stack_base);
915
916         VOP_MMAPPED(imgp->vp);
917
918         SDT_PROBE1(proc, , , exec__success, args->fname);
919
920 exec_fail_dealloc:
921         if (error != 0) {
922                 p->p_osrel = orig_osrel;
923                 p->p_fctl0 = orig_fctl0;
924                 p->p_elf_brandinfo = orig_brandinfo;
925         }
926
927         if (imgp->firstpage != NULL)
928                 exec_unmap_first_page(imgp);
929
930         if (imgp->vp != NULL) {
931                 if (args->fname)
932                         NDFREE(&nd, NDF_ONLY_PNBUF);
933                 if (imgp->opened)
934                         VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
935                 if (imgp->textset)
936                         VOP_UNSET_TEXT_CHECKED(imgp->vp);
937                 if (error != 0)
938                         vput(imgp->vp);
939                 else
940                         VOP_UNLOCK(imgp->vp);
941         }
942
943         if (imgp->object != NULL)
944                 vm_object_deallocate(imgp->object);
945
946         free(imgp->freepath, M_TEMP);
947
948         if (error == 0) {
949                 if (p->p_ptevents & PTRACE_EXEC) {
950                         PROC_LOCK(p);
951                         if (p->p_ptevents & PTRACE_EXEC)
952                                 td->td_dbgflags |= TDB_EXEC;
953                         PROC_UNLOCK(p);
954                 }
955         } else {
956 exec_fail:
957                 /* we're done here, clear P_INEXEC */
958                 PROC_LOCK(p);
959                 p->p_flag &= ~P_INEXEC;
960                 PROC_UNLOCK(p);
961
962                 SDT_PROBE1(proc, , , exec__failure, error);
963         }
964
965         if (imgp->newcred != NULL && oldcred != NULL)
966                 crfree(imgp->newcred);
967
968 #ifdef MAC
969         mac_execve_exit(imgp);
970         mac_execve_interpreter_exit(interpvplabel);
971 #endif
972         exec_free_args(args);
973
974         /*
975          * Handle deferred decrement of ref counts.
976          */
977         if (oldtextvp != NULL)
978                 vrele(oldtextvp);
979 #ifdef KTRACE
980         ktr_io_params_free(kiop);
981 #endif
982         pargs_drop(oldargs);
983         pargs_drop(newargs);
984         if (oldsigacts != NULL)
985                 sigacts_free(oldsigacts);
986         if (euip != NULL)
987                 uifree(euip);
988
989         if (error && imgp->vmspace_destroyed) {
990                 /* sorry, no more process anymore. exit gracefully */
991                 exec_cleanup(td, oldvmspace);
992                 exit1(td, 0, SIGABRT);
993                 /* NOT REACHED */
994         }
995
996 #ifdef KTRACE
997         if (error == 0)
998                 ktrprocctor(p);
999 #endif
1000
1001         /*
1002          * We don't want cpu_set_syscall_retval() to overwrite any of
1003          * the register values put in place by exec_setregs().
1004          * Implementations of cpu_set_syscall_retval() will leave
1005          * registers unmodified when returning EJUSTRETURN.
1006          */
1007         return (error == 0 ? EJUSTRETURN : error);
1008 }
1009
1010 void
1011 exec_cleanup(struct thread *td, struct vmspace *oldvmspace)
1012 {
1013         if ((td->td_pflags & TDP_EXECVMSPC) != 0) {
1014                 KASSERT(td->td_proc->p_vmspace != oldvmspace,
1015                     ("oldvmspace still used"));
1016                 vmspace_free(oldvmspace);
1017                 td->td_pflags &= ~TDP_EXECVMSPC;
1018         }
1019 }
1020
1021 int
1022 exec_map_first_page(struct image_params *imgp)
1023 {
1024         vm_object_t object;
1025         vm_page_t m;
1026         int error;
1027
1028         if (imgp->firstpage != NULL)
1029                 exec_unmap_first_page(imgp);
1030
1031         object = imgp->vp->v_object;
1032         if (object == NULL)
1033                 return (EACCES);
1034 #if VM_NRESERVLEVEL > 0
1035         if ((object->flags & OBJ_COLORED) == 0) {
1036                 VM_OBJECT_WLOCK(object);
1037                 vm_object_color(object, 0);
1038                 VM_OBJECT_WUNLOCK(object);
1039         }
1040 #endif
1041         error = vm_page_grab_valid_unlocked(&m, object, 0,
1042             VM_ALLOC_COUNT(VM_INITIAL_PAGEIN) |
1043             VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
1044
1045         if (error != VM_PAGER_OK)
1046                 return (EIO);
1047         imgp->firstpage = sf_buf_alloc(m, 0);
1048         imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
1049
1050         return (0);
1051 }
1052
1053 void
1054 exec_unmap_first_page(struct image_params *imgp)
1055 {
1056         vm_page_t m;
1057
1058         if (imgp->firstpage != NULL) {
1059                 m = sf_buf_page(imgp->firstpage);
1060                 sf_buf_free(imgp->firstpage);
1061                 imgp->firstpage = NULL;
1062                 vm_page_unwire(m, PQ_ACTIVE);
1063         }
1064 }
1065
1066 void
1067 exec_onexec_old(struct thread *td)
1068 {
1069         sigfastblock_clear(td);
1070         umtx_exec(td->td_proc);
1071 }
1072
1073 /*
1074  * Destroy old address space, and allocate a new stack.
1075  *      The new stack is only sgrowsiz large because it is grown
1076  *      automatically on a page fault.
1077  */
1078 int
1079 exec_new_vmspace(struct image_params *imgp, struct sysentvec *sv)
1080 {
1081         int error;
1082         struct proc *p = imgp->proc;
1083         struct vmspace *vmspace = p->p_vmspace;
1084         struct thread *td = curthread;
1085         vm_object_t obj;
1086         struct rlimit rlim_stack;
1087         vm_offset_t sv_minuser, stack_addr;
1088         vm_map_t map;
1089         vm_prot_t stack_prot;
1090         u_long ssiz;
1091
1092         imgp->vmspace_destroyed = 1;
1093         imgp->sysent = sv;
1094
1095         if (p->p_sysent->sv_onexec_old != NULL)
1096                 p->p_sysent->sv_onexec_old(td);
1097         itimers_exec(p);
1098
1099         EVENTHANDLER_DIRECT_INVOKE(process_exec, p, imgp);
1100
1101         /*
1102          * Blow away entire process VM, if address space not shared,
1103          * otherwise, create a new VM space so that other threads are
1104          * not disrupted
1105          */
1106         map = &vmspace->vm_map;
1107         if (map_at_zero)
1108                 sv_minuser = sv->sv_minuser;
1109         else
1110                 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1111         if (refcount_load(&vmspace->vm_refcnt) == 1 &&
1112             vm_map_min(map) == sv_minuser &&
1113             vm_map_max(map) == sv->sv_maxuser &&
1114             cpu_exec_vmspace_reuse(p, map)) {
1115                 shmexit(vmspace);
1116                 pmap_remove_pages(vmspace_pmap(vmspace));
1117                 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1118                 /*
1119                  * An exec terminates mlockall(MCL_FUTURE).
1120                  * ASLR and W^X states must be re-evaluated.
1121                  */
1122                 vm_map_lock(map);
1123                 vm_map_modflags(map, 0, MAP_WIREFUTURE | MAP_ASLR |
1124                     MAP_ASLR_IGNSTART | MAP_WXORX);
1125                 vm_map_unlock(map);
1126         } else {
1127                 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1128                 if (error)
1129                         return (error);
1130                 vmspace = p->p_vmspace;
1131                 map = &vmspace->vm_map;
1132         }
1133         map->flags |= imgp->map_flags;
1134
1135         /* Map a shared page */
1136         obj = sv->sv_shared_page_obj;
1137         if (obj != NULL) {
1138                 vm_object_reference(obj);
1139                 error = vm_map_fixed(map, obj, 0,
1140                     sv->sv_shared_page_base, sv->sv_shared_page_len,
1141                     VM_PROT_READ | VM_PROT_EXECUTE,
1142                     VM_PROT_READ | VM_PROT_EXECUTE,
1143                     MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1144                 if (error != KERN_SUCCESS) {
1145                         vm_object_deallocate(obj);
1146                         return (vm_mmap_to_errno(error));
1147                 }
1148         }
1149
1150         /* Allocate a new stack */
1151         if (imgp->stack_sz != 0) {
1152                 ssiz = trunc_page(imgp->stack_sz);
1153                 PROC_LOCK(p);
1154                 lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1155                 PROC_UNLOCK(p);
1156                 if (ssiz > rlim_stack.rlim_max)
1157                         ssiz = rlim_stack.rlim_max;
1158                 if (ssiz > rlim_stack.rlim_cur) {
1159                         rlim_stack.rlim_cur = ssiz;
1160                         kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1161                 }
1162         } else if (sv->sv_maxssiz != NULL) {
1163                 ssiz = *sv->sv_maxssiz;
1164         } else {
1165                 ssiz = maxssiz;
1166         }
1167         imgp->eff_stack_sz = lim_cur(curthread, RLIMIT_STACK);
1168         if (ssiz < imgp->eff_stack_sz)
1169                 imgp->eff_stack_sz = ssiz;
1170         stack_addr = sv->sv_usrstack - ssiz;
1171         stack_prot = obj != NULL && imgp->stack_prot != 0 ?
1172             imgp->stack_prot : sv->sv_stackprot;
1173         error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz, stack_prot,
1174             VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1175         if (error != KERN_SUCCESS) {
1176                 uprintf("exec_new_vmspace: mapping stack size %#jx prot %#x "
1177                     "failed mach error %d errno %d\n", (uintmax_t)ssiz,
1178                     stack_prot, error, vm_mmap_to_errno(error));
1179                 return (vm_mmap_to_errno(error));
1180         }
1181         vmspace->vm_stkgap = 0;
1182
1183         /*
1184          * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1185          * are still used to enforce the stack rlimit on the process stack.
1186          */
1187         vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1188         vmspace->vm_maxsaddr = (char *)stack_addr;
1189
1190         return (sv->sv_onexec != NULL ? sv->sv_onexec(p, imgp) : 0);
1191 }
1192
1193 /*
1194  * Copy out argument and environment strings from the old process address
1195  * space into the temporary string buffer.
1196  */
1197 int
1198 exec_copyin_args(struct image_args *args, const char *fname,
1199     enum uio_seg segflg, char **argv, char **envv)
1200 {
1201         u_long arg, env;
1202         int error;
1203
1204         bzero(args, sizeof(*args));
1205         if (argv == NULL)
1206                 return (EFAULT);
1207
1208         /*
1209          * Allocate demand-paged memory for the file name, argument, and
1210          * environment strings.
1211          */
1212         error = exec_alloc_args(args);
1213         if (error != 0)
1214                 return (error);
1215
1216         /*
1217          * Copy the file name.
1218          */
1219         error = exec_args_add_fname(args, fname, segflg);
1220         if (error != 0)
1221                 goto err_exit;
1222
1223         /*
1224          * extract arguments first
1225          */
1226         for (;;) {
1227                 error = fueword(argv++, &arg);
1228                 if (error == -1) {
1229                         error = EFAULT;
1230                         goto err_exit;
1231                 }
1232                 if (arg == 0)
1233                         break;
1234                 error = exec_args_add_arg(args, (char *)(uintptr_t)arg,
1235                     UIO_USERSPACE);
1236                 if (error != 0)
1237                         goto err_exit;
1238         }
1239
1240         /*
1241          * extract environment strings
1242          */
1243         if (envv) {
1244                 for (;;) {
1245                         error = fueword(envv++, &env);
1246                         if (error == -1) {
1247                                 error = EFAULT;
1248                                 goto err_exit;
1249                         }
1250                         if (env == 0)
1251                                 break;
1252                         error = exec_args_add_env(args,
1253                             (char *)(uintptr_t)env, UIO_USERSPACE);
1254                         if (error != 0)
1255                                 goto err_exit;
1256                 }
1257         }
1258
1259         return (0);
1260
1261 err_exit:
1262         exec_free_args(args);
1263         return (error);
1264 }
1265
1266 struct exec_args_kva {
1267         vm_offset_t addr;
1268         u_int gen;
1269         SLIST_ENTRY(exec_args_kva) next;
1270 };
1271
1272 DPCPU_DEFINE_STATIC(struct exec_args_kva *, exec_args_kva);
1273
1274 static SLIST_HEAD(, exec_args_kva) exec_args_kva_freelist;
1275 static struct mtx exec_args_kva_mtx;
1276 static u_int exec_args_gen;
1277
1278 static void
1279 exec_prealloc_args_kva(void *arg __unused)
1280 {
1281         struct exec_args_kva *argkva;
1282         u_int i;
1283
1284         SLIST_INIT(&exec_args_kva_freelist);
1285         mtx_init(&exec_args_kva_mtx, "exec args kva", NULL, MTX_DEF);
1286         for (i = 0; i < exec_map_entries; i++) {
1287                 argkva = malloc(sizeof(*argkva), M_PARGS, M_WAITOK);
1288                 argkva->addr = kmap_alloc_wait(exec_map, exec_map_entry_size);
1289                 argkva->gen = exec_args_gen;
1290                 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1291         }
1292 }
1293 SYSINIT(exec_args_kva, SI_SUB_EXEC, SI_ORDER_ANY, exec_prealloc_args_kva, NULL);
1294
1295 static vm_offset_t
1296 exec_alloc_args_kva(void **cookie)
1297 {
1298         struct exec_args_kva *argkva;
1299
1300         argkva = (void *)atomic_readandclear_ptr(
1301             (uintptr_t *)DPCPU_PTR(exec_args_kva));
1302         if (argkva == NULL) {
1303                 mtx_lock(&exec_args_kva_mtx);
1304                 while ((argkva = SLIST_FIRST(&exec_args_kva_freelist)) == NULL)
1305                         (void)mtx_sleep(&exec_args_kva_freelist,
1306                             &exec_args_kva_mtx, 0, "execkva", 0);
1307                 SLIST_REMOVE_HEAD(&exec_args_kva_freelist, next);
1308                 mtx_unlock(&exec_args_kva_mtx);
1309         }
1310         kasan_mark((void *)argkva->addr, exec_map_entry_size,
1311             exec_map_entry_size, 0);
1312         *(struct exec_args_kva **)cookie = argkva;
1313         return (argkva->addr);
1314 }
1315
1316 static void
1317 exec_release_args_kva(struct exec_args_kva *argkva, u_int gen)
1318 {
1319         vm_offset_t base;
1320
1321         base = argkva->addr;
1322         kasan_mark((void *)argkva->addr, 0, exec_map_entry_size,
1323             KASAN_EXEC_ARGS_FREED);
1324         if (argkva->gen != gen) {
1325                 (void)vm_map_madvise(exec_map, base, base + exec_map_entry_size,
1326                     MADV_FREE);
1327                 argkva->gen = gen;
1328         }
1329         if (!atomic_cmpset_ptr((uintptr_t *)DPCPU_PTR(exec_args_kva),
1330             (uintptr_t)NULL, (uintptr_t)argkva)) {
1331                 mtx_lock(&exec_args_kva_mtx);
1332                 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1333                 wakeup_one(&exec_args_kva_freelist);
1334                 mtx_unlock(&exec_args_kva_mtx);
1335         }
1336 }
1337
1338 static void
1339 exec_free_args_kva(void *cookie)
1340 {
1341
1342         exec_release_args_kva(cookie, exec_args_gen);
1343 }
1344
1345 static void
1346 exec_args_kva_lowmem(void *arg __unused)
1347 {
1348         SLIST_HEAD(, exec_args_kva) head;
1349         struct exec_args_kva *argkva;
1350         u_int gen;
1351         int i;
1352
1353         gen = atomic_fetchadd_int(&exec_args_gen, 1) + 1;
1354
1355         /*
1356          * Force an madvise of each KVA range. Any currently allocated ranges
1357          * will have MADV_FREE applied once they are freed.
1358          */
1359         SLIST_INIT(&head);
1360         mtx_lock(&exec_args_kva_mtx);
1361         SLIST_SWAP(&head, &exec_args_kva_freelist, exec_args_kva);
1362         mtx_unlock(&exec_args_kva_mtx);
1363         while ((argkva = SLIST_FIRST(&head)) != NULL) {
1364                 SLIST_REMOVE_HEAD(&head, next);
1365                 exec_release_args_kva(argkva, gen);
1366         }
1367
1368         CPU_FOREACH(i) {
1369                 argkva = (void *)atomic_readandclear_ptr(
1370                     (uintptr_t *)DPCPU_ID_PTR(i, exec_args_kva));
1371                 if (argkva != NULL)
1372                         exec_release_args_kva(argkva, gen);
1373         }
1374 }
1375 EVENTHANDLER_DEFINE(vm_lowmem, exec_args_kva_lowmem, NULL,
1376     EVENTHANDLER_PRI_ANY);
1377
1378 /*
1379  * Allocate temporary demand-paged, zero-filled memory for the file name,
1380  * argument, and environment strings.
1381  */
1382 int
1383 exec_alloc_args(struct image_args *args)
1384 {
1385
1386         args->buf = (char *)exec_alloc_args_kva(&args->bufkva);
1387         return (0);
1388 }
1389
1390 void
1391 exec_free_args(struct image_args *args)
1392 {
1393
1394         if (args->buf != NULL) {
1395                 exec_free_args_kva(args->bufkva);
1396                 args->buf = NULL;
1397         }
1398         if (args->fname_buf != NULL) {
1399                 free(args->fname_buf, M_TEMP);
1400                 args->fname_buf = NULL;
1401         }
1402 }
1403
1404 /*
1405  * A set to functions to fill struct image args.
1406  *
1407  * NOTE: exec_args_add_fname() must be called (possibly with a NULL
1408  * fname) before the other functions.  All exec_args_add_arg() calls must
1409  * be made before any exec_args_add_env() calls.  exec_args_adjust_args()
1410  * may be called any time after exec_args_add_fname().
1411  *
1412  * exec_args_add_fname() - install path to be executed
1413  * exec_args_add_arg() - append an argument string
1414  * exec_args_add_env() - append an env string
1415  * exec_args_adjust_args() - adjust location of the argument list to
1416  *                           allow new arguments to be prepended
1417  */
1418 int
1419 exec_args_add_fname(struct image_args *args, const char *fname,
1420     enum uio_seg segflg)
1421 {
1422         int error;
1423         size_t length;
1424
1425         KASSERT(args->fname == NULL, ("fname already appended"));
1426         KASSERT(args->endp == NULL, ("already appending to args"));
1427
1428         if (fname != NULL) {
1429                 args->fname = args->buf;
1430                 error = segflg == UIO_SYSSPACE ?
1431                     copystr(fname, args->fname, PATH_MAX, &length) :
1432                     copyinstr(fname, args->fname, PATH_MAX, &length);
1433                 if (error != 0)
1434                         return (error == ENAMETOOLONG ? E2BIG : error);
1435         } else
1436                 length = 0;
1437
1438         /* Set up for _arg_*()/_env_*() */
1439         args->endp = args->buf + length;
1440         /* begin_argv must be set and kept updated */
1441         args->begin_argv = args->endp;
1442         KASSERT(exec_map_entry_size - length >= ARG_MAX,
1443             ("too little space remaining for arguments %zu < %zu",
1444             exec_map_entry_size - length, (size_t)ARG_MAX));
1445         args->stringspace = ARG_MAX;
1446
1447         return (0);
1448 }
1449
1450 static int
1451 exec_args_add_str(struct image_args *args, const char *str,
1452     enum uio_seg segflg, int *countp)
1453 {
1454         int error;
1455         size_t length;
1456
1457         KASSERT(args->endp != NULL, ("endp not initialized"));
1458         KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1459
1460         error = (segflg == UIO_SYSSPACE) ?
1461             copystr(str, args->endp, args->stringspace, &length) :
1462             copyinstr(str, args->endp, args->stringspace, &length);
1463         if (error != 0)
1464                 return (error == ENAMETOOLONG ? E2BIG : error);
1465         args->stringspace -= length;
1466         args->endp += length;
1467         (*countp)++;
1468
1469         return (0);
1470 }
1471
1472 int
1473 exec_args_add_arg(struct image_args *args, const char *argp,
1474     enum uio_seg segflg)
1475 {
1476
1477         KASSERT(args->envc == 0, ("appending args after env"));
1478
1479         return (exec_args_add_str(args, argp, segflg, &args->argc));
1480 }
1481
1482 int
1483 exec_args_add_env(struct image_args *args, const char *envp,
1484     enum uio_seg segflg)
1485 {
1486
1487         if (args->envc == 0)
1488                 args->begin_envv = args->endp;
1489
1490         return (exec_args_add_str(args, envp, segflg, &args->envc));
1491 }
1492
1493 int
1494 exec_args_adjust_args(struct image_args *args, size_t consume, ssize_t extend)
1495 {
1496         ssize_t offset;
1497
1498         KASSERT(args->endp != NULL, ("endp not initialized"));
1499         KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1500
1501         offset = extend - consume;
1502         if (args->stringspace < offset)
1503                 return (E2BIG);
1504         memmove(args->begin_argv + extend, args->begin_argv + consume,
1505             args->endp - args->begin_argv + consume);
1506         if (args->envc > 0)
1507                 args->begin_envv += offset;
1508         args->endp += offset;
1509         args->stringspace -= offset;
1510         return (0);
1511 }
1512
1513 char *
1514 exec_args_get_begin_envv(struct image_args *args)
1515 {
1516
1517         KASSERT(args->endp != NULL, ("endp not initialized"));
1518
1519         if (args->envc > 0)
1520                 return (args->begin_envv);
1521         return (args->endp);
1522 }
1523
1524 void
1525 exec_stackgap(struct image_params *imgp, uintptr_t *dp)
1526 {
1527         struct proc *p = imgp->proc;
1528
1529         if (imgp->sysent->sv_stackgap == NULL ||
1530             (p->p_fctl0 & (NT_FREEBSD_FCTL_ASLR_DISABLE |
1531             NT_FREEBSD_FCTL_ASG_DISABLE)) != 0 ||
1532             (imgp->map_flags & MAP_ASLR) == 0) {
1533                 p->p_vmspace->vm_stkgap = 0;
1534                 return;
1535         }
1536         p->p_vmspace->vm_stkgap = imgp->sysent->sv_stackgap(imgp, dp);
1537 }
1538
1539 /*
1540  * Copy strings out to the new process address space, constructing new arg
1541  * and env vector tables. Return a pointer to the base so that it can be used
1542  * as the initial stack pointer.
1543  */
1544 int
1545 exec_copyout_strings(struct image_params *imgp, uintptr_t *stack_base)
1546 {
1547         int argc, envc;
1548         char **vectp;
1549         char *stringp;
1550         uintptr_t destp, ustringp;
1551         struct ps_strings *arginfo;
1552         struct proc *p;
1553         size_t execpath_len;
1554         int error, szsigcode, szps;
1555         char canary[sizeof(long) * 8];
1556
1557         szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
1558         /*
1559          * Calculate string base and vector table pointers.
1560          * Also deal with signal trampoline code for this exec type.
1561          */
1562         if (imgp->execpath != NULL && imgp->auxargs != NULL)
1563                 execpath_len = strlen(imgp->execpath) + 1;
1564         else
1565                 execpath_len = 0;
1566         p = imgp->proc;
1567         szsigcode = 0;
1568         arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1569         imgp->ps_strings = arginfo;
1570         if (p->p_sysent->sv_sigcode_base == 0) {
1571                 if (p->p_sysent->sv_szsigcode != NULL)
1572                         szsigcode = *(p->p_sysent->sv_szsigcode);
1573         }
1574         destp = (uintptr_t)arginfo;
1575
1576         /*
1577          * install sigcode
1578          */
1579         if (szsigcode != 0) {
1580                 destp -= szsigcode;
1581                 destp = rounddown2(destp, sizeof(void *));
1582                 error = copyout(p->p_sysent->sv_sigcode, (void *)destp,
1583                     szsigcode);
1584                 if (error != 0)
1585                         return (error);
1586         }
1587
1588         /*
1589          * Copy the image path for the rtld.
1590          */
1591         if (execpath_len != 0) {
1592                 destp -= execpath_len;
1593                 destp = rounddown2(destp, sizeof(void *));
1594                 imgp->execpathp = (void *)destp;
1595                 error = copyout(imgp->execpath, imgp->execpathp, execpath_len);
1596                 if (error != 0)
1597                         return (error);
1598         }
1599
1600         /*
1601          * Prepare the canary for SSP.
1602          */
1603         arc4rand(canary, sizeof(canary), 0);
1604         destp -= sizeof(canary);
1605         imgp->canary = (void *)destp;
1606         error = copyout(canary, imgp->canary, sizeof(canary));
1607         if (error != 0)
1608                 return (error);
1609         imgp->canarylen = sizeof(canary);
1610
1611         /*
1612          * Prepare the pagesizes array.
1613          */
1614         destp -= szps;
1615         destp = rounddown2(destp, sizeof(void *));
1616         imgp->pagesizes = (void *)destp;
1617         error = copyout(pagesizes, imgp->pagesizes, szps);
1618         if (error != 0)
1619                 return (error);
1620         imgp->pagesizeslen = szps;
1621
1622         /*
1623          * Allocate room for the argument and environment strings.
1624          */
1625         destp -= ARG_MAX - imgp->args->stringspace;
1626         destp = rounddown2(destp, sizeof(void *));
1627         ustringp = destp;
1628
1629         exec_stackgap(imgp, &destp);
1630
1631         if (imgp->auxargs) {
1632                 /*
1633                  * Allocate room on the stack for the ELF auxargs
1634                  * array.  It has up to AT_COUNT entries.
1635                  */
1636                 destp -= AT_COUNT * sizeof(Elf_Auxinfo);
1637                 destp = rounddown2(destp, sizeof(void *));
1638         }
1639
1640         vectp = (char **)destp;
1641
1642         /*
1643          * Allocate room for the argv[] and env vectors including the
1644          * terminating NULL pointers.
1645          */
1646         vectp -= imgp->args->argc + 1 + imgp->args->envc + 1;
1647
1648         /*
1649          * vectp also becomes our initial stack base
1650          */
1651         *stack_base = (uintptr_t)vectp;
1652
1653         stringp = imgp->args->begin_argv;
1654         argc = imgp->args->argc;
1655         envc = imgp->args->envc;
1656
1657         /*
1658          * Copy out strings - arguments and environment.
1659          */
1660         error = copyout(stringp, (void *)ustringp,
1661             ARG_MAX - imgp->args->stringspace);
1662         if (error != 0)
1663                 return (error);
1664
1665         /*
1666          * Fill in "ps_strings" struct for ps, w, etc.
1667          */
1668         imgp->argv = vectp;
1669         if (suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp) != 0 ||
1670             suword32(&arginfo->ps_nargvstr, argc) != 0)
1671                 return (EFAULT);
1672
1673         /*
1674          * Fill in argument portion of vector table.
1675          */
1676         for (; argc > 0; --argc) {
1677                 if (suword(vectp++, ustringp) != 0)
1678                         return (EFAULT);
1679                 while (*stringp++ != 0)
1680                         ustringp++;
1681                 ustringp++;
1682         }
1683
1684         /* a null vector table pointer separates the argp's from the envp's */
1685         if (suword(vectp++, 0) != 0)
1686                 return (EFAULT);
1687
1688         imgp->envv = vectp;
1689         if (suword(&arginfo->ps_envstr, (long)(intptr_t)vectp) != 0 ||
1690             suword32(&arginfo->ps_nenvstr, envc) != 0)
1691                 return (EFAULT);
1692
1693         /*
1694          * Fill in environment portion of vector table.
1695          */
1696         for (; envc > 0; --envc) {
1697                 if (suword(vectp++, ustringp) != 0)
1698                         return (EFAULT);
1699                 while (*stringp++ != 0)
1700                         ustringp++;
1701                 ustringp++;
1702         }
1703
1704         /* end of vector table is a null pointer */
1705         if (suword(vectp, 0) != 0)
1706                 return (EFAULT);
1707
1708         if (imgp->auxargs) {
1709                 vectp++;
1710                 error = imgp->sysent->sv_copyout_auxargs(imgp,
1711                     (uintptr_t)vectp);
1712                 if (error != 0)
1713                         return (error);
1714         }
1715
1716         return (0);
1717 }
1718
1719 /*
1720  * Check permissions of file to execute.
1721  *      Called with imgp->vp locked.
1722  *      Return 0 for success or error code on failure.
1723  */
1724 int
1725 exec_check_permissions(struct image_params *imgp)
1726 {
1727         struct vnode *vp = imgp->vp;
1728         struct vattr *attr = imgp->attr;
1729         struct thread *td;
1730         int error;
1731
1732         td = curthread;
1733
1734         /* Get file attributes */
1735         error = VOP_GETATTR(vp, attr, td->td_ucred);
1736         if (error)
1737                 return (error);
1738
1739 #ifdef MAC
1740         error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1741         if (error)
1742                 return (error);
1743 #endif
1744
1745         /*
1746          * 1) Check if file execution is disabled for the filesystem that
1747          *    this file resides on.
1748          * 2) Ensure that at least one execute bit is on. Otherwise, a
1749          *    privileged user will always succeed, and we don't want this
1750          *    to happen unless the file really is executable.
1751          * 3) Ensure that the file is a regular file.
1752          */
1753         if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1754             (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1755             (attr->va_type != VREG))
1756                 return (EACCES);
1757
1758         /*
1759          * Zero length files can't be exec'd
1760          */
1761         if (attr->va_size == 0)
1762                 return (ENOEXEC);
1763
1764         /*
1765          *  Check for execute permission to file based on current credentials.
1766          */
1767         error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1768         if (error)
1769                 return (error);
1770
1771         /*
1772          * Check number of open-for-writes on the file and deny execution
1773          * if there are any.
1774          *
1775          * Add a text reference now so no one can write to the
1776          * executable while we're activating it.
1777          *
1778          * Remember if this was set before and unset it in case this is not
1779          * actually an executable image.
1780          */
1781         error = VOP_SET_TEXT(vp);
1782         if (error != 0)
1783                 return (error);
1784         imgp->textset = true;
1785
1786         /*
1787          * Call filesystem specific open routine (which does nothing in the
1788          * general case).
1789          */
1790         error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1791         if (error == 0)
1792                 imgp->opened = 1;
1793         return (error);
1794 }
1795
1796 /*
1797  * Exec handler registration
1798  */
1799 int
1800 exec_register(const struct execsw *execsw_arg)
1801 {
1802         const struct execsw **es, **xs, **newexecsw;
1803         u_int count = 2;        /* New slot and trailing NULL */
1804
1805         if (execsw)
1806                 for (es = execsw; *es; es++)
1807                         count++;
1808         newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1809         xs = newexecsw;
1810         if (execsw)
1811                 for (es = execsw; *es; es++)
1812                         *xs++ = *es;
1813         *xs++ = execsw_arg;
1814         *xs = NULL;
1815         if (execsw)
1816                 free(execsw, M_TEMP);
1817         execsw = newexecsw;
1818         return (0);
1819 }
1820
1821 int
1822 exec_unregister(const struct execsw *execsw_arg)
1823 {
1824         const struct execsw **es, **xs, **newexecsw;
1825         int count = 1;
1826
1827         if (execsw == NULL)
1828                 panic("unregister with no handlers left?\n");
1829
1830         for (es = execsw; *es; es++) {
1831                 if (*es == execsw_arg)
1832                         break;
1833         }
1834         if (*es == NULL)
1835                 return (ENOENT);
1836         for (es = execsw; *es; es++)
1837                 if (*es != execsw_arg)
1838                         count++;
1839         newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1840         xs = newexecsw;
1841         for (es = execsw; *es; es++)
1842                 if (*es != execsw_arg)
1843                         *xs++ = *es;
1844         *xs = NULL;
1845         if (execsw)
1846                 free(execsw, M_TEMP);
1847         execsw = newexecsw;
1848         return (0);
1849 }
1850
1851 /*
1852  * Write out a core segment to the compression stream.
1853  */
1854 static int
1855 compress_chunk(struct coredump_params *cp, char *base, char *buf, size_t len)
1856 {
1857         size_t chunk_len;
1858         int error;
1859
1860         while (len > 0) {
1861                 chunk_len = MIN(len, CORE_BUF_SIZE);
1862
1863                 /*
1864                  * We can get EFAULT error here.
1865                  * In that case zero out the current chunk of the segment.
1866                  */
1867                 error = copyin(base, buf, chunk_len);
1868                 if (error != 0)
1869                         bzero(buf, chunk_len);
1870                 error = compressor_write(cp->comp, buf, chunk_len);
1871                 if (error != 0)
1872                         break;
1873                 base += chunk_len;
1874                 len -= chunk_len;
1875         }
1876         return (error);
1877 }
1878
1879 int
1880 core_write(struct coredump_params *cp, const void *base, size_t len,
1881     off_t offset, enum uio_seg seg, size_t *resid)
1882 {
1883
1884         return (vn_rdwr_inchunks(UIO_WRITE, cp->vp, __DECONST(void *, base),
1885             len, offset, seg, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
1886             cp->active_cred, cp->file_cred, resid, cp->td));
1887 }
1888
1889 int
1890 core_output(char *base, size_t len, off_t offset, struct coredump_params *cp,
1891     void *tmpbuf)
1892 {
1893         vm_map_t map;
1894         struct mount *mp;
1895         size_t resid, runlen;
1896         int error;
1897         bool success;
1898
1899         KASSERT((uintptr_t)base % PAGE_SIZE == 0,
1900             ("%s: user address %p is not page-aligned", __func__, base));
1901
1902         if (cp->comp != NULL)
1903                 return (compress_chunk(cp, base, tmpbuf, len));
1904
1905         map = &cp->td->td_proc->p_vmspace->vm_map;
1906         for (; len > 0; base += runlen, offset += runlen, len -= runlen) {
1907                 /*
1908                  * Attempt to page in all virtual pages in the range.  If a
1909                  * virtual page is not backed by the pager, it is represented as
1910                  * a hole in the file.  This can occur with zero-filled
1911                  * anonymous memory or truncated files, for example.
1912                  */
1913                 for (runlen = 0; runlen < len; runlen += PAGE_SIZE) {
1914                         if (core_dump_can_intr && curproc_sigkilled())
1915                                 return (EINTR);
1916                         error = vm_fault(map, (uintptr_t)base + runlen,
1917                             VM_PROT_READ, VM_FAULT_NOFILL, NULL);
1918                         if (runlen == 0)
1919                                 success = error == KERN_SUCCESS;
1920                         else if ((error == KERN_SUCCESS) != success)
1921                                 break;
1922                 }
1923
1924                 if (success) {
1925                         error = core_write(cp, base, runlen, offset,
1926                             UIO_USERSPACE, &resid);
1927                         if (error != 0) {
1928                                 if (error != EFAULT)
1929                                         break;
1930
1931                                 /*
1932                                  * EFAULT may be returned if the user mapping
1933                                  * could not be accessed, e.g., because a mapped
1934                                  * file has been truncated.  Skip the page if no
1935                                  * progress was made, to protect against a
1936                                  * hypothetical scenario where vm_fault() was
1937                                  * successful but core_write() returns EFAULT
1938                                  * anyway.
1939                                  */
1940                                 runlen -= resid;
1941                                 if (runlen == 0) {
1942                                         success = false;
1943                                         runlen = PAGE_SIZE;
1944                                 }
1945                         }
1946                 }
1947                 if (!success) {
1948                         error = vn_start_write(cp->vp, &mp, V_WAIT);
1949                         if (error != 0)
1950                                 break;
1951                         vn_lock(cp->vp, LK_EXCLUSIVE | LK_RETRY);
1952                         error = vn_truncate_locked(cp->vp, offset + runlen,
1953                             false, cp->td->td_ucred);
1954                         VOP_UNLOCK(cp->vp);
1955                         vn_finished_write(mp);
1956                         if (error != 0)
1957                                 break;
1958                 }
1959         }
1960         return (error);
1961 }
1962
1963 /*
1964  * Drain into a core file.
1965  */
1966 int
1967 sbuf_drain_core_output(void *arg, const char *data, int len)
1968 {
1969         struct coredump_params *cp;
1970         struct proc *p;
1971         int error, locked;
1972
1973         cp = arg;
1974         p = cp->td->td_proc;
1975
1976         /*
1977          * Some kern_proc out routines that print to this sbuf may
1978          * call us with the process lock held. Draining with the
1979          * non-sleepable lock held is unsafe. The lock is needed for
1980          * those routines when dumping a live process. In our case we
1981          * can safely release the lock before draining and acquire
1982          * again after.
1983          */
1984         locked = PROC_LOCKED(p);
1985         if (locked)
1986                 PROC_UNLOCK(p);
1987         if (cp->comp != NULL)
1988                 error = compressor_write(cp->comp, __DECONST(char *, data), len);
1989         else
1990                 error = core_write(cp, __DECONST(void *, data), len, cp->offset,
1991                     UIO_SYSSPACE, NULL);
1992         if (locked)
1993                 PROC_LOCK(p);
1994         if (error != 0)
1995                 return (-error);
1996         cp->offset += len;
1997         return (len);
1998 }