kernel - Add /dev/upmap and /dev/kpmap and sys/upmap.h
[dragonfly.git] / sys / kern / imgact_elf.c
1 /*-
2  * Copyright (c) 2000 David O'Brien
3  * Copyright (c) 1995-1996 Søren Schmidt
4  * Copyright (c) 1996 Peter Wemm
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  *    in this position and unchanged.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * $FreeBSD: src/sys/kern/imgact_elf.c,v 1.73.2.13 2002/12/28 19:49:41 dillon Exp $
31  */
32
33 #include <sys/param.h>
34 #include <sys/exec.h>
35 #include <sys/fcntl.h>
36 #include <sys/file.h>
37 #include <sys/imgact.h>
38 #include <sys/imgact_elf.h>
39 #include <sys/kernel.h>
40 #include <sys/malloc.h>
41 #include <sys/mman.h>
42 #include <sys/systm.h>
43 #include <sys/proc.h>
44 #include <sys/nlookup.h>
45 #include <sys/pioctl.h>
46 #include <sys/procfs.h>
47 #include <sys/resourcevar.h>
48 #include <sys/signalvar.h>
49 #include <sys/stat.h>
50 #include <sys/syscall.h>
51 #include <sys/sysctl.h>
52 #include <sys/sysent.h>
53 #include <sys/vnode.h>
54 #include <sys/eventhandler.h>
55
56 #include <cpu/lwbuf.h>
57
58 #include <vm/vm.h>
59 #include <vm/vm_kern.h>
60 #include <vm/vm_param.h>
61 #include <vm/pmap.h>
62 #include <sys/lock.h>
63 #include <vm/vm_map.h>
64 #include <vm/vm_object.h>
65 #include <vm/vm_extern.h>
66
67 #include <machine/elf.h>
68 #include <machine/md_var.h>
69 #include <sys/mount.h>
70 #include <sys/ckpt.h>
71
72 #define OLD_EI_BRAND    8
73 #define truncps(va,ps)  ((va) & ~(ps - 1))
74 #define aligned(a,t)    (truncps((u_long)(a), sizeof(t)) == (u_long)(a))
75
76 static int __elfN(check_header)(const Elf_Ehdr *hdr);
77 static Elf_Brandinfo *__elfN(get_brandinfo)(struct image_params *imgp,
78     const char *interp, int32_t *osrel);
79 static int __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
80     u_long *entry);
81 static int __elfN(load_section)(struct proc *p,
82     struct vmspace *vmspace, struct vnode *vp,
83     vm_offset_t offset, caddr_t vmaddr, size_t memsz, size_t filsz,
84     vm_prot_t prot);
85 static int __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp);
86 static boolean_t __elfN(bsd_trans_osrel)(const Elf_Note *note,
87     int32_t *osrel);
88 static boolean_t __elfN(check_note)(struct image_params *imgp,
89     Elf_Brandnote *checknote, int32_t *osrel);
90 static vm_prot_t __elfN(trans_prot)(Elf_Word);
91 static Elf_Word __elfN(untrans_prot)(vm_prot_t);
92 static boolean_t check_PT_NOTE(struct image_params *imgp,
93     Elf_Brandnote *checknote, int32_t *osrel, const Elf_Phdr * pnote);
94 static boolean_t extract_interpreter(struct image_params *imgp,
95     const Elf_Phdr *pinterpreter, char *data);
96
97 static int elf_legacy_coredump = 0;
98 static int __elfN(fallback_brand) = -1;
99 #if defined(__x86_64__)
100 SYSCTL_NODE(_kern, OID_AUTO, elf64, CTLFLAG_RW, 0, "");
101 SYSCTL_INT(_debug, OID_AUTO, elf64_legacy_coredump, CTLFLAG_RW,
102     &elf_legacy_coredump, 0, "legacy coredump mode");
103 SYSCTL_INT(_kern_elf64, OID_AUTO, fallback_brand, CTLFLAG_RW,
104     &elf64_fallback_brand, 0, "ELF64 brand of last resort");
105 TUNABLE_INT("kern.elf64.fallback_brand", &elf64_fallback_brand);
106 #else /* i386 assumed */
107 SYSCTL_NODE(_kern, OID_AUTO, elf32, CTLFLAG_RW, 0, "");
108 SYSCTL_INT(_debug, OID_AUTO, elf32_legacy_coredump, CTLFLAG_RW,
109     &elf_legacy_coredump, 0, "legacy coredump mode");
110 SYSCTL_INT(_kern_elf32, OID_AUTO, fallback_brand, CTLFLAG_RW,
111     &elf32_fallback_brand, 0, "ELF32 brand of last resort");
112 TUNABLE_INT("kern.elf32.fallback_brand", &elf32_fallback_brand);
113 #endif
114
115 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
116
117 static const char DRAGONFLY_ABI_VENDOR[] = "DragonFly";
118 static const char FREEBSD_ABI_VENDOR[]   = "FreeBSD";
119
120 Elf_Brandnote __elfN(dragonfly_brandnote) = {
121         .hdr.n_namesz   = sizeof(DRAGONFLY_ABI_VENDOR),
122         .hdr.n_descsz   = sizeof(int32_t),
123         .hdr.n_type     = 1,
124         .vendor         = DRAGONFLY_ABI_VENDOR,
125         .flags          = BN_TRANSLATE_OSREL,
126         .trans_osrel    = __elfN(bsd_trans_osrel),
127 };
128
129 Elf_Brandnote __elfN(freebsd_brandnote) = {
130         .hdr.n_namesz   = sizeof(FREEBSD_ABI_VENDOR),
131         .hdr.n_descsz   = sizeof(int32_t),
132         .hdr.n_type     = 1,
133         .vendor         = FREEBSD_ABI_VENDOR,
134         .flags          = BN_TRANSLATE_OSREL,
135         .trans_osrel    = __elfN(bsd_trans_osrel),
136 };
137
138 int
139 __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
140 {
141         int i;
142
143         for (i = 0; i < MAX_BRANDS; i++) {
144                 if (elf_brand_list[i] == NULL) {
145                         elf_brand_list[i] = entry;
146                         break;
147                 }
148         }
149         if (i == MAX_BRANDS) {
150                 uprintf("WARNING: %s: could not insert brandinfo entry: %p\n",
151                         __func__, entry);
152                 return (-1);
153         }
154         return (0);
155 }
156
157 int
158 __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
159 {
160         int i;
161
162         for (i = 0; i < MAX_BRANDS; i++) {
163                 if (elf_brand_list[i] == entry) {
164                         elf_brand_list[i] = NULL;
165                         break;
166                 }
167         }
168         if (i == MAX_BRANDS)
169                 return (-1);
170         return (0);
171 }
172
173 /*
174  * Check if an elf brand is being used anywhere in the system.
175  *
176  * Used by the linux emulation module unloader.  This isn't safe from
177  * races.
178  */
179 struct elf_brand_inuse_info {
180         int rval;
181         Elf_Brandinfo *entry;
182 };
183
184 static int elf_brand_inuse_callback(struct proc *p, void *data);
185
186 int
187 __elfN(brand_inuse)(Elf_Brandinfo *entry)
188 {
189         struct elf_brand_inuse_info info;
190
191         info.rval = FALSE;
192         info.entry = entry;
193         allproc_scan(elf_brand_inuse_callback, &info);
194         return (info.rval);
195 }
196
197 static
198 int
199 elf_brand_inuse_callback(struct proc *p, void *data)
200 {
201         struct elf_brand_inuse_info *info = data;
202
203         if (p->p_sysent == info->entry->sysvec) {
204                 info->rval = TRUE;
205                 return (-1);
206         }
207         return (0);
208 }
209
210 static int
211 __elfN(check_header)(const Elf_Ehdr *hdr)
212 {
213         Elf_Brandinfo *bi;
214         int i;
215
216         if (!IS_ELF(*hdr) ||
217             hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
218             hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
219             hdr->e_ident[EI_VERSION] != EV_CURRENT ||
220             hdr->e_phentsize != sizeof(Elf_Phdr) ||
221             hdr->e_ehsize != sizeof(Elf_Ehdr) ||
222             hdr->e_version != ELF_TARG_VER)
223                 return (ENOEXEC);
224
225         /*
226          * Make sure we have at least one brand for this machine.
227          */
228
229         for (i = 0; i < MAX_BRANDS; i++) {
230                 bi = elf_brand_list[i];
231                 if (bi != NULL && bi->machine == hdr->e_machine)
232                         break;
233         }
234         if (i == MAX_BRANDS)
235                 return (ENOEXEC);
236
237         return (0);
238 }
239
240 static int
241 __elfN(load_section)(struct proc *p, struct vmspace *vmspace, struct vnode *vp,
242                  vm_offset_t offset, caddr_t vmaddr, size_t memsz,
243                  size_t filsz, vm_prot_t prot)
244 {
245         size_t map_len;
246         vm_offset_t map_addr;
247         int error, rv, cow;
248         int count;
249         int shared;
250         size_t copy_len;
251         vm_object_t object;
252         vm_offset_t file_addr;
253
254         object = vp->v_object;
255         error = 0;
256
257         /*
258          * In most cases we will be able to use a shared lock on the
259          * object we are inserting into the map.  The lock will be
260          * upgraded in situations where new VM pages must be allocated.
261          */
262         vm_object_hold_shared(object);
263         shared = 1;
264
265         /*
266          * It's necessary to fail if the filsz + offset taken from the
267          * header is greater than the actual file pager object's size.
268          * If we were to allow this, then the vm_map_find() below would
269          * walk right off the end of the file object and into the ether.
270          *
271          * While I'm here, might as well check for something else that
272          * is invalid: filsz cannot be greater than memsz.
273          */
274         if ((off_t)filsz + offset > vp->v_filesize || filsz > memsz) {
275                 uprintf("elf_load_section: truncated ELF file\n");
276                 vm_object_drop(object);
277                 return (ENOEXEC);
278         }
279
280         map_addr = trunc_page((vm_offset_t)vmaddr);
281         file_addr = trunc_page(offset);
282
283         /*
284          * We have two choices.  We can either clear the data in the last page
285          * of an oversized mapping, or we can start the anon mapping a page
286          * early and copy the initialized data into that first page.  We
287          * choose the second..
288          */
289         if (memsz > filsz)
290                 map_len = trunc_page(offset+filsz) - file_addr;
291         else
292                 map_len = round_page(offset+filsz) - file_addr;
293
294         if (map_len != 0) {
295                 vm_object_reference_locked(object);
296
297                 /* cow flags: don't dump readonly sections in core */
298                 cow = MAP_COPY_ON_WRITE | MAP_PREFAULT;
299                 if ((prot & VM_PROT_WRITE) == 0)
300                         cow |= MAP_DISABLE_COREDUMP;
301                 if (shared == 0)
302                         cow |= MAP_PREFAULT_RELOCK;
303
304                 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
305                 vm_map_lock(&vmspace->vm_map);
306                 rv = vm_map_insert(&vmspace->vm_map, &count,
307                                       object, NULL,
308                                       file_addr,        /* file offset */
309                                       map_addr,         /* virtual start */
310                                       map_addr + map_len,/* virtual end */
311                                       VM_MAPTYPE_NORMAL,
312                                       prot, VM_PROT_ALL,
313                                       cow);
314                 vm_map_unlock(&vmspace->vm_map);
315                 vm_map_entry_release(count);
316
317                 /*
318                  * NOTE: Object must have a hold ref when calling
319                  * vm_object_deallocate().
320                  */
321                 if (rv != KERN_SUCCESS) {
322                         vm_object_drop(object);
323                         vm_object_deallocate(object);
324                         return (EINVAL);
325                 }
326
327                 /* we can stop now if we've covered it all */
328                 if (memsz == filsz) {
329                         vm_object_drop(object);
330                         return (0);
331                 }
332         }
333
334         /*
335          * We have to get the remaining bit of the file into the first part
336          * of the oversized map segment.  This is normally because the .data
337          * segment in the file is extended to provide bss.  It's a neat idea
338          * to try and save a page, but it's a pain in the behind to implement.
339          */
340         copy_len = (offset + filsz) - trunc_page(offset + filsz);
341         map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
342         map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
343
344         /* This had damn well better be true! */
345         if (map_len != 0) {
346                 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
347                 vm_map_lock(&vmspace->vm_map);
348                 rv = vm_map_insert(&vmspace->vm_map, &count,
349                                         NULL, NULL,
350                                         0,
351                                         map_addr,
352                                         map_addr + map_len,
353                                         VM_MAPTYPE_NORMAL,
354                                         VM_PROT_ALL, VM_PROT_ALL,
355                                         0);
356                 vm_map_unlock(&vmspace->vm_map);
357                 vm_map_entry_release(count);
358                 if (rv != KERN_SUCCESS) {
359                         vm_object_drop(object);
360                         return (EINVAL);
361                 }
362         }
363
364         if (copy_len != 0) {
365                 struct lwbuf *lwb;
366                 struct lwbuf lwb_cache;
367                 vm_page_t m;
368
369                 m = vm_fault_object_page(object, trunc_page(offset + filsz),
370                                          VM_PROT_READ, 0, &shared, &error);
371                 vm_object_drop(object);
372                 if (m) {
373                         lwb = lwbuf_alloc(m, &lwb_cache);
374                         error = copyout((caddr_t)lwbuf_kva(lwb),
375                                         (caddr_t)map_addr, copy_len);
376                         lwbuf_free(lwb);
377                         vm_page_unhold(m);
378                 }
379         } else {
380                 vm_object_drop(object);
381         }
382
383         /*
384          * set it to the specified protection
385          */
386         if (error == 0) {
387                 vm_map_protect(&vmspace->vm_map,
388                                map_addr, map_addr + map_len,
389                                prot, FALSE);
390         }
391         return (error);
392 }
393
394 /*
395  * Load the file "file" into memory.  It may be either a shared object
396  * or an executable.
397  *
398  * The "addr" reference parameter is in/out.  On entry, it specifies
399  * the address where a shared object should be loaded.  If the file is
400  * an executable, this value is ignored.  On exit, "addr" specifies
401  * where the file was actually loaded.
402  *
403  * The "entry" reference parameter is out only.  On exit, it specifies
404  * the entry point for the loaded file.
405  */
406 static int
407 __elfN(load_file)(struct proc *p, const char *file, u_long *addr, u_long *entry)
408 {
409         struct {
410                 struct nlookupdata nd;
411                 struct vattr attr;
412                 struct image_params image_params;
413         } *tempdata;
414         const Elf_Ehdr *hdr = NULL;
415         const Elf_Phdr *phdr = NULL;
416         struct nlookupdata *nd;
417         struct vmspace *vmspace = p->p_vmspace;
418         struct vattr *attr;
419         struct image_params *imgp;
420         struct mount *topmnt;
421         vm_prot_t prot;
422         u_long rbase;
423         u_long base_addr = 0;
424         int error, i, numsegs;
425
426         tempdata = kmalloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
427         nd = &tempdata->nd;
428         attr = &tempdata->attr;
429         imgp = &tempdata->image_params;
430
431         /*
432          * Initialize part of the common data
433          */
434         imgp->proc = p;
435         imgp->attr = attr;
436         imgp->firstpage = NULL;
437         imgp->image_header = NULL;
438         imgp->vp = NULL;
439
440         error = nlookup_init(nd, file, UIO_SYSSPACE, NLC_FOLLOW);
441         if (error == 0)
442                 error = nlookup(nd);
443         if (error == 0)
444                 error = cache_vget(&nd->nl_nch, nd->nl_cred,
445                                    LK_SHARED, &imgp->vp);
446         topmnt = nd->nl_nch.mount;
447         nlookup_done(nd);
448         if (error)
449                 goto fail;
450
451         /*
452          * Check permissions, modes, uid, etc on the file, and "open" it.
453          */
454         error = exec_check_permissions(imgp, topmnt);
455         if (error) {
456                 vn_unlock(imgp->vp);
457                 goto fail;
458         }
459
460         error = exec_map_first_page(imgp);
461         /*
462          * Also make certain that the interpreter stays the same, so set
463          * its VTEXT flag, too.
464          */
465         if (error == 0)
466                 vsetflags(imgp->vp, VTEXT);
467         vn_unlock(imgp->vp);
468         if (error)
469                 goto fail;
470
471         hdr = (const Elf_Ehdr *)imgp->image_header;
472         if ((error = __elfN(check_header)(hdr)) != 0)
473                 goto fail;
474         if (hdr->e_type == ET_DYN)
475                 rbase = *addr;
476         else if (hdr->e_type == ET_EXEC)
477                 rbase = 0;
478         else {
479                 error = ENOEXEC;
480                 goto fail;
481         }
482
483         /* Only support headers that fit within first page for now      */
484         /*    (multiplication of two Elf_Half fields will not overflow) */
485         if ((hdr->e_phoff > PAGE_SIZE) ||
486             (hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE - hdr->e_phoff) {
487                 error = ENOEXEC;
488                 goto fail;
489         }
490
491         phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
492         if (!aligned(phdr, Elf_Addr)) {
493                 error = ENOEXEC;
494                 goto fail;
495         }
496
497         for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
498                 if (phdr[i].p_type == PT_LOAD && phdr[i].p_memsz != 0) {
499                         /* Loadable segment */
500                         prot = __elfN(trans_prot)(phdr[i].p_flags);
501                         error = __elfN(load_section)(
502                                     p, vmspace, imgp->vp,
503                                     phdr[i].p_offset,
504                                     (caddr_t)phdr[i].p_vaddr +
505                                     rbase,
506                                     phdr[i].p_memsz,
507                                     phdr[i].p_filesz, prot);
508                         if (error != 0)
509                                 goto fail;
510                         /*
511                          * Establish the base address if this is the
512                          * first segment.
513                          */
514                         if (numsegs == 0)
515                                 base_addr = trunc_page(phdr[i].p_vaddr + rbase);
516                         numsegs++;
517                 }
518         }
519         *addr = base_addr;
520         *entry = (unsigned long)hdr->e_entry + rbase;
521
522 fail:
523         if (imgp->firstpage)
524                 exec_unmap_first_page(imgp);
525         if (imgp->vp) {
526                 vrele(imgp->vp);
527                 imgp->vp = NULL;
528         }
529         kfree(tempdata, M_TEMP);
530
531         return (error);
532 }
533
534 static Elf_Brandinfo *
535 __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
536     int32_t *osrel)
537 {
538         const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
539         Elf_Brandinfo *bi;
540         boolean_t ret;
541         int i;
542
543         /* We support four types of branding -- (1) the ELF EI_OSABI field
544          * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
545          * branding within the ELF header, (3) path of the `interp_path' field,
546          * and (4) the ".note.ABI-tag" ELF section.
547          */
548
549         /* Look for an ".note.ABI-tag" ELF section */
550         for (i = 0; i < MAX_BRANDS; i++) {
551                 bi = elf_brand_list[i];
552
553                 if (bi == NULL)
554                         continue;
555                 if (hdr->e_machine == bi->machine && (bi->flags &
556                     (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
557                         ret = __elfN(check_note)(imgp, bi->brand_note, osrel);
558                         if (ret)
559                                 return (bi);
560                 }
561         }
562
563         /* If the executable has a brand, search for it in the brand list. */
564         for (i = 0;  i < MAX_BRANDS;  i++) {
565                 bi = elf_brand_list[i];
566
567                 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
568                         continue;
569                 if (hdr->e_machine == bi->machine &&
570                     (hdr->e_ident[EI_OSABI] == bi->brand ||
571                     strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
572                     bi->compat_3_brand, strlen(bi->compat_3_brand)) == 0))
573                         return (bi);
574         }
575
576         /* Lacking a known brand, search for a recognized interpreter. */
577         if (interp != NULL) {
578                 for (i = 0;  i < MAX_BRANDS;  i++) {
579                         bi = elf_brand_list[i];
580
581                         if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
582                                 continue;
583                         if (hdr->e_machine == bi->machine &&
584                             strcmp(interp, bi->interp_path) == 0)
585                                 return (bi);
586                 }
587         }
588
589         /* Lacking a recognized interpreter, try the default brand */
590         for (i = 0; i < MAX_BRANDS; i++) {
591                 bi = elf_brand_list[i];
592
593                 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
594                         continue;
595                 if (hdr->e_machine == bi->machine &&
596                     __elfN(fallback_brand) == bi->brand)
597                         return (bi);
598         }
599         return (NULL);
600 }
601
602 static int
603 __CONCAT(exec_,__elfN(imgact))(struct image_params *imgp)
604 {
605         const Elf_Ehdr *hdr = (const Elf_Ehdr *) imgp->image_header;
606         const Elf_Phdr *phdr;
607         Elf_Auxargs *elf_auxargs;
608         struct vmspace *vmspace;
609         vm_prot_t prot;
610         u_long text_size = 0, data_size = 0, total_size = 0;
611         u_long text_addr = 0, data_addr = 0;
612         u_long seg_size, seg_addr;
613         u_long addr, baddr, et_dyn_addr, entry = 0, proghdr = 0;
614         int32_t osrel = 0;
615         int error = 0, i, n;
616         boolean_t failure;
617         char *interp = NULL;
618         const char *newinterp = NULL;
619         Elf_Brandinfo *brand_info;
620         char *path;
621
622         /*
623          * Do we have a valid ELF header ?
624          *
625          * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later if a particular
626          * brand doesn't support it.  Both DragonFly platforms do by default.
627          */
628         if (__elfN(check_header)(hdr) != 0 ||
629             (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
630                 return (-1);
631
632         /*
633          * From here on down, we return an errno, not -1, as we've
634          * detected an ELF file.
635          */
636
637         if ((hdr->e_phoff > PAGE_SIZE) ||
638             (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
639                 /* Only support headers in first page for now */
640                 return (ENOEXEC);
641         }
642         phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
643         if (!aligned(phdr, Elf_Addr))
644                 return (ENOEXEC);
645         n = 0;
646         baddr = 0;
647         for (i = 0; i < hdr->e_phnum; i++) {
648                 if (phdr[i].p_type == PT_LOAD) {
649                         if (n == 0)
650                                 baddr = phdr[i].p_vaddr;
651                         n++;
652                         continue;
653                 }
654                 if (phdr[i].p_type == PT_INTERP) {
655                         /*
656                          * If interp is already defined there are more than
657                          * one PT_INTERP program headers present.  Take only
658                          * the first one and ignore the rest.
659                          */
660                         if (interp != NULL)
661                                 continue;
662
663                         if (phdr[i].p_filesz == 0 ||
664                             phdr[i].p_filesz > PAGE_SIZE ||
665                             phdr[i].p_filesz > MAXPATHLEN)
666                                 return (ENOEXEC);
667
668                         interp = kmalloc(phdr[i].p_filesz, M_TEMP, M_WAITOK);
669                         failure = extract_interpreter(imgp, &phdr[i], interp);
670                         if (failure) {
671                                 kfree(interp, M_TEMP);
672                                 return (ENOEXEC);
673                         }
674                         continue;
675                 }
676         }
677         
678         brand_info = __elfN(get_brandinfo)(imgp, interp, &osrel);
679         if (brand_info == NULL) {
680                 uprintf("ELF binary type \"%u\" not known.\n",
681                     hdr->e_ident[EI_OSABI]);
682                 if (interp != NULL)
683                         kfree(interp, M_TEMP);
684                 return (ENOEXEC);
685         }
686         if (hdr->e_type == ET_DYN) {
687                 if ((brand_info->flags & BI_CAN_EXEC_DYN) == 0) {
688                         if (interp != NULL)
689                                 kfree(interp, M_TEMP);
690                         return (ENOEXEC);
691                 }
692                 /*
693                  * Honour the base load address from the dso if it is
694                  * non-zero for some reason.
695                  */
696                 if (baddr == 0)
697                         et_dyn_addr = ET_DYN_LOAD_ADDR;
698                 else
699                         et_dyn_addr = 0;
700         } else
701                 et_dyn_addr = 0;
702
703         if (interp != NULL && brand_info->interp_newpath != NULL)
704                 newinterp = brand_info->interp_newpath;
705
706         exec_new_vmspace(imgp, NULL);
707
708         /*
709          * Yeah, I'm paranoid.  There is every reason in the world to get
710          * VTEXT now since from here on out, there are places we can have
711          * a context switch.  Better safe than sorry; I really don't want
712          * the file to change while it's being loaded.
713          */
714         vsetflags(imgp->vp, VTEXT);
715
716         vmspace = imgp->proc->p_vmspace;
717
718         for (i = 0; i < hdr->e_phnum; i++) {
719                 switch (phdr[i].p_type) {
720                 case PT_LOAD:   /* Loadable segment */
721                         if (phdr[i].p_memsz == 0)
722                                 break;
723                         prot = __elfN(trans_prot)(phdr[i].p_flags);
724
725                         if ((error = __elfN(load_section)(
726                                         imgp->proc,
727                                         vmspace,
728                                         imgp->vp,
729                                         phdr[i].p_offset,
730                                         (caddr_t)phdr[i].p_vaddr + et_dyn_addr,
731                                         phdr[i].p_memsz,
732                                         phdr[i].p_filesz,
733                                         prot)) != 0) {
734                                 if (interp != NULL)
735                                         kfree (interp, M_TEMP);
736                                 return (error);
737                         }
738
739                         /*
740                          * If this segment contains the program headers,
741                          * remember their virtual address for the AT_PHDR
742                          * aux entry. Static binaries don't usually include
743                          * a PT_PHDR entry.
744                          */
745                         if (phdr[i].p_offset == 0 &&
746                             hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
747                                 <= phdr[i].p_filesz)
748                                 proghdr = phdr[i].p_vaddr + hdr->e_phoff +
749                                     et_dyn_addr;
750
751                         seg_addr = trunc_page(phdr[i].p_vaddr + et_dyn_addr);
752                         seg_size = round_page(phdr[i].p_memsz +
753                             phdr[i].p_vaddr + et_dyn_addr - seg_addr);
754
755                         /*
756                          * Is this .text or .data?  We can't use
757                          * VM_PROT_WRITE or VM_PROT_EXEC, it breaks the
758                          * alpha terribly and possibly does other bad
759                          * things so we stick to the old way of figuring
760                          * it out:  If the segment contains the program
761                          * entry point, it's a text segment, otherwise it
762                          * is a data segment.
763                          *
764                          * Note that obreak() assumes that data_addr + 
765                          * data_size == end of data load area, and the ELF
766                          * file format expects segments to be sorted by
767                          * address.  If multiple data segments exist, the
768                          * last one will be used.
769                          */
770                         if (hdr->e_entry >= phdr[i].p_vaddr &&
771                             hdr->e_entry < (phdr[i].p_vaddr +
772                             phdr[i].p_memsz)) {
773                                 text_size = seg_size;
774                                 text_addr = seg_addr;
775                                 entry = (u_long)hdr->e_entry + et_dyn_addr;
776                         } else {
777                                 data_size = seg_size;
778                                 data_addr = seg_addr;
779                         }
780                         total_size += seg_size;
781
782                         /*
783                          * Check limits.  It should be safe to check the
784                          * limits after loading the segment since we do
785                          * not actually fault in all the segment's pages.
786                          */
787                         if (data_size >
788                             imgp->proc->p_rlimit[RLIMIT_DATA].rlim_cur ||
789                             text_size > maxtsiz ||
790                             total_size >
791                             imgp->proc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
792                                 if (interp != NULL)
793                                         kfree(interp, M_TEMP);
794                                 error = ENOMEM;
795                                 return (error);
796                         }
797                         break;
798                 case PT_PHDR:   /* Program header table info */
799                         proghdr = phdr[i].p_vaddr + et_dyn_addr;
800                         break;
801                 default:
802                         break;
803                 }
804         }
805
806         vmspace->vm_tsize = text_size >> PAGE_SHIFT;
807         vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
808         vmspace->vm_dsize = data_size >> PAGE_SHIFT;
809         vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
810
811         addr = ELF_RTLD_ADDR(vmspace);
812
813         imgp->entry_addr = entry;
814
815         imgp->proc->p_sysent = brand_info->sysvec;
816         EVENTHANDLER_INVOKE(process_exec, imgp);
817
818         if (interp != NULL) {
819                 int have_interp = FALSE;
820                 if (brand_info->emul_path != NULL &&
821                     brand_info->emul_path[0] != '\0') {
822                         path = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
823                         ksnprintf(path, MAXPATHLEN, "%s%s",
824                             brand_info->emul_path, interp);
825                         error = __elfN(load_file)(imgp->proc, path, &addr,
826                             &imgp->entry_addr);
827                         kfree(path, M_TEMP);
828                         if (error == 0)
829                                 have_interp = TRUE;
830                 }
831                 if (!have_interp && newinterp != NULL) {
832                         error = __elfN(load_file)(imgp->proc, newinterp,
833                             &addr, &imgp->entry_addr);
834                         if (error == 0)
835                                 have_interp = TRUE;
836                 }
837                 if (!have_interp) {
838                         error = __elfN(load_file)(imgp->proc, interp, &addr,
839                             &imgp->entry_addr);
840                 }
841                 if (error != 0) {
842                         uprintf("ELF interpreter %s not found\n", interp);
843                         kfree(interp, M_TEMP);
844                         return (error);
845                 }
846                 kfree(interp, M_TEMP);
847         } else
848                 addr = et_dyn_addr;
849
850         /*
851          * Construct auxargs table (used by the fixup routine)
852          */
853         elf_auxargs = kmalloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
854         elf_auxargs->execfd = -1;
855         elf_auxargs->phdr = proghdr;
856         elf_auxargs->phent = hdr->e_phentsize;
857         elf_auxargs->phnum = hdr->e_phnum;
858         elf_auxargs->pagesz = PAGE_SIZE;
859         elf_auxargs->base = addr;
860         elf_auxargs->flags = 0;
861         elf_auxargs->entry = entry;
862
863         imgp->auxargs = elf_auxargs;
864         imgp->interpreted = 0;
865         imgp->proc->p_osrel = osrel;
866
867         return (error);
868 }
869
870 int
871 __elfN(dragonfly_fixup)(register_t **stack_base, struct image_params *imgp)
872 {
873         Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
874         Elf_Addr *base;
875         Elf_Addr *pos;
876
877         base = (Elf_Addr *)*stack_base;
878         pos = base + (imgp->args->argc + imgp->args->envc + 2);
879
880         if (args->execfd != -1)
881                 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
882         AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
883         AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
884         AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
885         AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
886         AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
887         AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
888         AUXARGS_ENTRY(pos, AT_BASE, args->base);
889         if (imgp->execpathp != 0)
890                 AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp);
891         AUXARGS_ENTRY(pos, AT_OSRELDATE, osreldate);
892         AUXARGS_ENTRY(pos, AT_NULL, 0);
893
894         kfree(imgp->auxargs, M_TEMP);
895         imgp->auxargs = NULL;
896
897         base--;
898         suword(base, (long)imgp->args->argc);
899         *stack_base = (register_t *)base;
900         return (0);
901 }
902
903 /*
904  * Code for generating ELF core dumps.
905  */
906
907 typedef int (*segment_callback)(vm_map_entry_t, void *);
908
909 /* Closure for cb_put_phdr(). */
910 struct phdr_closure {
911         Elf_Phdr *phdr;         /* Program header to fill in (incremented) */
912         Elf_Phdr *phdr_max;     /* Pointer bound for error check */
913         Elf_Off offset;         /* Offset of segment in core file */
914 };
915
916 /* Closure for cb_size_segment(). */
917 struct sseg_closure {
918         int count;              /* Count of writable segments. */
919         size_t vsize;           /* Total size of all writable segments. */
920 };
921
922 /* Closure for cb_put_fp(). */
923 struct fp_closure {
924         struct vn_hdr *vnh;
925         struct vn_hdr *vnh_max;
926         int count;
927         struct stat *sb;
928 };
929
930 typedef struct elf_buf {
931         char    *buf;
932         size_t  off;
933         size_t  off_max;
934 } *elf_buf_t;
935
936 static void *target_reserve(elf_buf_t target, size_t bytes, int *error);
937
938 static int cb_put_phdr (vm_map_entry_t, void *);
939 static int cb_size_segment (vm_map_entry_t, void *);
940 static int cb_fpcount_segment(vm_map_entry_t, void *);
941 static int cb_put_fp(vm_map_entry_t, void *);
942
943
944 static int each_segment (struct proc *, segment_callback, void *, int);
945 static int __elfN(corehdr)(struct lwp *, int, struct file *, struct ucred *,
946                         int, elf_buf_t);
947 enum putmode { WRITE, DRYRUN };
948 static int __elfN(puthdr)(struct lwp *, elf_buf_t, int sig, enum putmode,
949                         int, struct file *);
950 static int elf_putallnotes(struct lwp *, elf_buf_t, int, enum putmode);
951 static int __elfN(putnote)(elf_buf_t, const char *, int, const void *, size_t);
952
953 static int elf_putsigs(struct lwp *, elf_buf_t);
954 static int elf_puttextvp(struct proc *, elf_buf_t);
955 static int elf_putfiles(struct proc *, elf_buf_t, struct file *);
956
957 int
958 __elfN(coredump)(struct lwp *lp, int sig, struct vnode *vp, off_t limit)
959 {
960         struct file *fp; 
961         int error;
962
963         if ((error = falloc(NULL, &fp, NULL)) != 0)
964                 return (error);
965         fsetcred(fp, lp->lwp_proc->p_ucred);
966
967         /*
968          * XXX fixme.
969          */
970         fp->f_type = DTYPE_VNODE;
971         fp->f_flag = O_CREAT|O_WRONLY|O_NOFOLLOW;
972         fp->f_ops = &vnode_fileops;
973         fp->f_data = vp;
974         
975         error = generic_elf_coredump(lp, sig, fp, limit);
976
977         fp->f_type = 0;
978         fp->f_flag = 0;
979         fp->f_ops = &badfileops;
980         fp->f_data = NULL;
981         fdrop(fp);
982         return (error);
983 }
984
985 int
986 generic_elf_coredump(struct lwp *lp, int sig, struct file *fp, off_t limit)
987 {
988         struct proc *p = lp->lwp_proc;
989         struct ucred *cred = p->p_ucred;
990         int error = 0;
991         struct sseg_closure seginfo;
992         struct elf_buf target;
993
994         if (!fp)
995                 kprintf("can't dump core - null fp\n");
996
997         /*
998          * Size the program segments
999          */
1000         seginfo.count = 0;
1001         seginfo.vsize = 0;
1002         each_segment(p, cb_size_segment, &seginfo, 1);
1003
1004         /*
1005          * Calculate the size of the core file header area by making
1006          * a dry run of generating it.  Nothing is written, but the
1007          * size is calculated.
1008          */
1009         bzero(&target, sizeof(target));
1010         __elfN(puthdr)(lp, &target, sig, DRYRUN, seginfo.count, fp);
1011
1012         if (target.off + seginfo.vsize >= limit)
1013                 return (EFAULT);
1014
1015         /*
1016          * Allocate memory for building the header, fill it up,
1017          * and write it out.
1018          */
1019         target.off_max = target.off;
1020         target.off = 0;
1021         target.buf = kmalloc(target.off_max, M_TEMP, M_WAITOK|M_ZERO);
1022
1023         error = __elfN(corehdr)(lp, sig, fp, cred, seginfo.count, &target);
1024
1025         /* Write the contents of all of the writable segments. */
1026         if (error == 0) {
1027                 Elf_Phdr *php;
1028                 int i;
1029                 ssize_t nbytes;
1030
1031                 php = (Elf_Phdr *)(target.buf + sizeof(Elf_Ehdr)) + 1;
1032                 for (i = 0; i < seginfo.count; i++) {
1033                         error = fp_write(fp, (caddr_t)php->p_vaddr,
1034                                         php->p_filesz, &nbytes, UIO_USERSPACE);
1035                         if (error != 0)
1036                                 break;
1037                         php++;
1038                 }
1039         }
1040         kfree(target.buf, M_TEMP);
1041         
1042         return (error);
1043 }
1044
1045 /*
1046  * A callback for each_segment() to write out the segment's
1047  * program header entry.
1048  */
1049 static int
1050 cb_put_phdr(vm_map_entry_t entry, void *closure)
1051 {
1052         struct phdr_closure *phc = closure;
1053         Elf_Phdr *phdr = phc->phdr;
1054
1055         if (phc->phdr == phc->phdr_max)
1056                 return (EINVAL);
1057
1058         phc->offset = round_page(phc->offset);
1059
1060         phdr->p_type = PT_LOAD;
1061         phdr->p_offset = phc->offset;
1062         phdr->p_vaddr = entry->start;
1063         phdr->p_paddr = 0;
1064         phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1065         phdr->p_align = PAGE_SIZE;
1066         phdr->p_flags = __elfN(untrans_prot)(entry->protection);
1067
1068         phc->offset += phdr->p_filesz;
1069         ++phc->phdr;
1070         return (0);
1071 }
1072
1073 /*
1074  * A callback for each_writable_segment() to gather information about
1075  * the number of segments and their total size.
1076  */
1077 static int
1078 cb_size_segment(vm_map_entry_t entry, void *closure)
1079 {
1080         struct sseg_closure *ssc = closure;
1081
1082         ++ssc->count;
1083         ssc->vsize += entry->end - entry->start;
1084         return (0);
1085 }
1086
1087 /*
1088  * A callback for each_segment() to gather information about
1089  * the number of text segments.
1090  */
1091 static int
1092 cb_fpcount_segment(vm_map_entry_t entry, void *closure)
1093 {
1094         int *count = closure;
1095         struct vnode *vp;
1096
1097         if (entry->object.vm_object->type == OBJT_VNODE) {
1098                 vp = (struct vnode *)entry->object.vm_object->handle;
1099                 if ((vp->v_flag & VCKPT) && curproc->p_textvp == vp)
1100                         return (0);
1101                 ++*count;
1102         }
1103         return (0);
1104 }
1105
1106 static int
1107 cb_put_fp(vm_map_entry_t entry, void *closure) 
1108 {
1109         struct fp_closure *fpc = closure;
1110         struct vn_hdr *vnh = fpc->vnh;
1111         Elf_Phdr *phdr = &vnh->vnh_phdr;
1112         struct vnode *vp;
1113         int error;
1114
1115         /*
1116          * If an entry represents a vnode then write out a file handle.
1117          *
1118          * If we are checkpointing a checkpoint-restored program we do
1119          * NOT record the filehandle for the old checkpoint vnode (which
1120          * is mapped all over the place).  Instead we rely on the fact
1121          * that a checkpoint-restored program does not mmap() the checkpt
1122          * vnode NOCORE, so its contents will be written out to the
1123          * new checkpoint file.  This is necessary because the 'old'
1124          * checkpoint file is typically destroyed when a new one is created
1125          * and thus cannot be used to restore the new checkpoint.
1126          *
1127          * Theoretically we could create a chain of checkpoint files and
1128          * operate the checkpointing operation kinda like an incremental
1129          * checkpoint, but a checkpoint restore would then likely wind up
1130          * referencing many prior checkpoint files and that is a bit over
1131          * the top for the purpose of the checkpoint API.
1132          */
1133         if (entry->object.vm_object->type == OBJT_VNODE) {
1134                 vp = (struct vnode *)entry->object.vm_object->handle;
1135                 if ((vp->v_flag & VCKPT) && curproc->p_textvp == vp)
1136                         return (0);
1137                 if (vnh == fpc->vnh_max)
1138                         return (EINVAL);
1139
1140                 if (vp->v_mount)
1141                         vnh->vnh_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1142                 error = VFS_VPTOFH(vp, &vnh->vnh_fh.fh_fid);
1143                 if (error) {
1144                         char *freepath, *fullpath;
1145
1146                         if (vn_fullpath(curproc, vp, &fullpath, &freepath, 0)) {
1147                                 kprintf("Warning: coredump, error %d: cannot store file handle for vnode %p\n", error, vp);
1148                         } else {
1149                                 kprintf("Warning: coredump, error %d: cannot store file handle for %s\n", error, fullpath);
1150                                 kfree(freepath, M_TEMP);
1151                         }
1152                         error = 0;
1153                 }
1154
1155                 phdr->p_type = PT_LOAD;
1156                 phdr->p_offset = 0;        /* not written to core */
1157                 phdr->p_vaddr = entry->start;
1158                 phdr->p_paddr = 0;
1159                 phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1160                 phdr->p_align = PAGE_SIZE;
1161                 phdr->p_flags = 0;
1162                 if (entry->protection & VM_PROT_READ)
1163                         phdr->p_flags |= PF_R;
1164                 if (entry->protection & VM_PROT_WRITE)
1165                         phdr->p_flags |= PF_W;
1166                 if (entry->protection & VM_PROT_EXECUTE)
1167                         phdr->p_flags |= PF_X;
1168                 ++fpc->vnh;
1169                 ++fpc->count;
1170         }
1171         return (0);
1172 }
1173
1174 /*
1175  * For each writable segment in the process's memory map, call the given
1176  * function with a pointer to the map entry and some arbitrary
1177  * caller-supplied data.
1178  */
1179 static int
1180 each_segment(struct proc *p, segment_callback func, void *closure, int writable)
1181 {
1182         int error = 0;
1183         vm_map_t map = &p->p_vmspace->vm_map;
1184         vm_map_entry_t entry;
1185
1186         for (entry = map->header.next; error == 0 && entry != &map->header;
1187             entry = entry->next) {
1188                 vm_object_t obj;
1189                 vm_object_t lobj;
1190                 vm_object_t tobj;
1191
1192                 /*
1193                  * Don't dump inaccessible mappings, deal with legacy
1194                  * coredump mode.
1195                  *
1196                  * Note that read-only segments related to the elf binary
1197                  * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1198                  * need to arbitrarily ignore such segments.
1199                  */
1200                 if (elf_legacy_coredump) {
1201                         if (writable && (entry->protection & VM_PROT_RW) != VM_PROT_RW)
1202                                 continue;
1203                 } else {
1204                         if (writable && (entry->protection & VM_PROT_ALL) == 0)
1205                                 continue;
1206                 }
1207
1208                 /*
1209                  * Dont include memory segment in the coredump if
1210                  * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1211                  * madvise(2).
1212                  *
1213                  * Currently we only dump normal VM object maps.  We do
1214                  * not dump submaps or virtual page tables.
1215                  */
1216                 if (writable && (entry->eflags & MAP_ENTRY_NOCOREDUMP))
1217                         continue;
1218                 if (entry->maptype != VM_MAPTYPE_NORMAL)
1219                         continue;
1220                 if ((obj = entry->object.vm_object) == NULL)
1221                         continue;
1222
1223                 /*
1224                  * Find the bottom-most object, leaving the base object
1225                  * and the bottom-most object held (but only one hold
1226                  * if they happen to be the same).
1227                  */
1228                 vm_object_hold_shared(obj);
1229
1230                 lobj = obj;
1231                 while (lobj && (tobj = lobj->backing_object) != NULL) {
1232                         KKASSERT(tobj != obj);
1233                         vm_object_hold_shared(tobj);
1234                         if (tobj == lobj->backing_object) {
1235                                 if (lobj != obj) {
1236                                         vm_object_lock_swap();
1237                                         vm_object_drop(lobj);
1238                                 }
1239                                 lobj = tobj;
1240                         } else {
1241                                 vm_object_drop(tobj);
1242                         }
1243                 }
1244
1245                 /*
1246                  * The callback only applies to default, swap, or vnode
1247                  * objects.  Other types of objects such as memory-mapped
1248                  * devices are ignored.
1249                  */
1250                 if (lobj->type == OBJT_DEFAULT || lobj->type == OBJT_SWAP ||
1251                     lobj->type == OBJT_VNODE) {
1252                         error = (*func)(entry, closure);
1253                 }
1254                 if (lobj != obj)
1255                         vm_object_drop(lobj);
1256                 vm_object_drop(obj);
1257         }
1258         return (error);
1259 }
1260
1261 static
1262 void *
1263 target_reserve(elf_buf_t target, size_t bytes, int *error)
1264 {
1265     void *res = NULL;
1266
1267     if (target->buf) {
1268             if (target->off + bytes > target->off_max)
1269                     *error = EINVAL;
1270             else
1271                     res = target->buf + target->off;
1272     }
1273     target->off += bytes;
1274     return (res);
1275 }
1276
1277 /*
1278  * Write the core file header to the file, including padding up to
1279  * the page boundary.
1280  */
1281 static int
1282 __elfN(corehdr)(struct lwp *lp, int sig, struct file *fp, struct ucred *cred,
1283             int numsegs, elf_buf_t target)
1284 {
1285         int error;
1286         ssize_t nbytes;
1287
1288         /*
1289          * Fill in the header.  The fp is passed so we can detect and flag
1290          * a checkpoint file pointer within the core file itself, because
1291          * it may not be restored from the same file handle.
1292          */
1293         error = __elfN(puthdr)(lp, target, sig, WRITE, numsegs, fp);
1294
1295         /* Write it to the core file. */
1296         if (error == 0) {
1297                 error = fp_write(fp, target->buf, target->off, &nbytes,
1298                                  UIO_SYSSPACE);
1299         }
1300         return (error);
1301 }
1302
1303 static int
1304 __elfN(puthdr)(struct lwp *lp, elf_buf_t target, int sig, enum putmode mode,
1305     int numsegs, struct file *fp)
1306 {
1307         struct proc *p = lp->lwp_proc;
1308         int error = 0;
1309         size_t phoff;
1310         size_t noteoff;
1311         size_t notesz;
1312         Elf_Ehdr *ehdr;
1313         Elf_Phdr *phdr;
1314
1315         ehdr = target_reserve(target, sizeof(Elf_Ehdr), &error);
1316
1317         phoff = target->off;
1318         phdr = target_reserve(target, (numsegs + 1) * sizeof(Elf_Phdr), &error);
1319
1320         noteoff = target->off;
1321         if (error == 0)
1322                 elf_putallnotes(lp, target, sig, mode);
1323         notesz = target->off - noteoff;
1324
1325         /*
1326          * put extra cruft for dumping process state here 
1327          *  - we really want it be before all the program 
1328          *    mappings
1329          *  - we just need to update the offset accordingly
1330          *    and GDB will be none the wiser.
1331          */
1332         if (error == 0)
1333                 error = elf_puttextvp(p, target);
1334         if (error == 0)
1335                 error = elf_putsigs(lp, target);
1336         if (error == 0)
1337                 error = elf_putfiles(p, target, fp);
1338
1339         /*
1340          * Align up to a page boundary for the program segments.  The
1341          * actual data will be written to the outptu file, not to elf_buf_t,
1342          * so we do not have to do any further bounds checking.
1343          */
1344         target->off = round_page(target->off);
1345         if (error == 0 && ehdr != NULL) {
1346                 /*
1347                  * Fill in the ELF header.
1348                  */
1349                 ehdr->e_ident[EI_MAG0] = ELFMAG0;
1350                 ehdr->e_ident[EI_MAG1] = ELFMAG1;
1351                 ehdr->e_ident[EI_MAG2] = ELFMAG2;
1352                 ehdr->e_ident[EI_MAG3] = ELFMAG3;
1353                 ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1354                 ehdr->e_ident[EI_DATA] = ELF_DATA;
1355                 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1356                 ehdr->e_ident[EI_OSABI] = ELFOSABI_NONE;
1357                 ehdr->e_ident[EI_ABIVERSION] = 0;
1358                 ehdr->e_ident[EI_PAD] = 0;
1359                 ehdr->e_type = ET_CORE;
1360                 ehdr->e_machine = ELF_ARCH;
1361                 ehdr->e_version = EV_CURRENT;
1362                 ehdr->e_entry = 0;
1363                 ehdr->e_phoff = phoff;
1364                 ehdr->e_flags = 0;
1365                 ehdr->e_ehsize = sizeof(Elf_Ehdr);
1366                 ehdr->e_phentsize = sizeof(Elf_Phdr);
1367                 ehdr->e_phnum = numsegs + 1;
1368                 ehdr->e_shentsize = sizeof(Elf_Shdr);
1369                 ehdr->e_shnum = 0;
1370                 ehdr->e_shstrndx = SHN_UNDEF;
1371         }
1372         if (error == 0 && phdr != NULL) {
1373                 /*
1374                  * Fill in the program header entries.
1375                  */
1376                 struct phdr_closure phc;
1377
1378                 /* The note segement. */
1379                 phdr->p_type = PT_NOTE;
1380                 phdr->p_offset = noteoff;
1381                 phdr->p_vaddr = 0;
1382                 phdr->p_paddr = 0;
1383                 phdr->p_filesz = notesz;
1384                 phdr->p_memsz = 0;
1385                 phdr->p_flags = 0;
1386                 phdr->p_align = 0;
1387                 ++phdr;
1388
1389                 /* All the writable segments from the program. */
1390                 phc.phdr = phdr;
1391                 phc.phdr_max = phdr + numsegs;
1392                 phc.offset = target->off;
1393                 each_segment(p, cb_put_phdr, &phc, 1);
1394         }
1395         return (error);
1396 }
1397
1398 /*
1399  * Append core dump notes to target ELF buffer or simply update target size
1400  * if dryrun selected.
1401  */
1402 static int
1403 elf_putallnotes(struct lwp *corelp, elf_buf_t target, int sig,
1404     enum putmode mode)
1405 {
1406         struct proc *p = corelp->lwp_proc;
1407         int error;
1408         struct {
1409                 prstatus_t status;
1410                 prfpregset_t fpregs;
1411                 prpsinfo_t psinfo;
1412         } *tmpdata;
1413         prstatus_t *status;
1414         prfpregset_t *fpregs;
1415         prpsinfo_t *psinfo;
1416         struct lwp *lp;
1417
1418         /*
1419          * Allocate temporary storage for notes on heap to avoid stack overflow.
1420          */
1421         if (mode != DRYRUN) {
1422                 tmpdata = kmalloc(sizeof(*tmpdata), M_TEMP, M_ZERO | M_WAITOK);
1423                 status = &tmpdata->status;
1424                 fpregs = &tmpdata->fpregs;
1425                 psinfo = &tmpdata->psinfo;
1426         } else {
1427                 tmpdata = NULL;
1428                 status = NULL;
1429                 fpregs = NULL;
1430                 psinfo = NULL;
1431         }
1432
1433         /*
1434          * Append LWP-agnostic note.
1435          */
1436         if (mode != DRYRUN) {
1437                 psinfo->pr_version = PRPSINFO_VERSION;
1438                 psinfo->pr_psinfosz = sizeof(prpsinfo_t);
1439                 strlcpy(psinfo->pr_fname, p->p_comm,
1440                         sizeof(psinfo->pr_fname));
1441                 /*
1442                  * XXX - We don't fill in the command line arguments
1443                  * properly yet.
1444                  */
1445                 strlcpy(psinfo->pr_psargs, p->p_comm,
1446                         sizeof(psinfo->pr_psargs));
1447         }
1448         error =
1449             __elfN(putnote)(target, "CORE", NT_PRPSINFO, psinfo, sizeof *psinfo);
1450         if (error)
1451                 goto exit;
1452
1453         /*
1454          * Append first note for LWP that triggered core so that it is
1455          * the selected one when the debugger starts.
1456          */
1457         if (mode != DRYRUN) {
1458                 status->pr_version = PRSTATUS_VERSION;
1459                 status->pr_statussz = sizeof(prstatus_t);
1460                 status->pr_gregsetsz = sizeof(gregset_t);
1461                 status->pr_fpregsetsz = sizeof(fpregset_t);
1462                 status->pr_osreldate = osreldate;
1463                 status->pr_cursig = sig;
1464                 /*
1465                  * XXX GDB needs unique pr_pid for each LWP and does not
1466                  * not support pr_pid==0 but lwp_tid can be 0, so hack unique
1467                  * value.
1468                  */
1469                 status->pr_pid = corelp->lwp_tid;
1470                 fill_regs(corelp, &status->pr_reg);
1471                 fill_fpregs(corelp, fpregs);
1472         }
1473         error =
1474             __elfN(putnote)(target, "CORE", NT_PRSTATUS, status, sizeof *status);
1475         if (error)
1476                 goto exit;
1477         error =
1478             __elfN(putnote)(target, "CORE", NT_FPREGSET, fpregs, sizeof *fpregs);
1479         if (error)
1480                 goto exit;
1481
1482         /*
1483          * Then append notes for other LWPs.
1484          */
1485         FOREACH_LWP_IN_PROC(lp, p) {
1486                 if (lp == corelp)
1487                         continue;
1488                 /* skip lwps being created */
1489                 if (lp->lwp_thread == NULL)
1490                         continue;
1491                 if (mode != DRYRUN) {
1492                         status->pr_pid = lp->lwp_tid;
1493                         fill_regs(lp, &status->pr_reg);
1494                         fill_fpregs(lp, fpregs);
1495                 }
1496                 error = __elfN(putnote)(target, "CORE", NT_PRSTATUS,
1497                                         status, sizeof *status);
1498                 if (error)
1499                         goto exit;
1500                 error = __elfN(putnote)(target, "CORE", NT_FPREGSET,
1501                                         fpregs, sizeof *fpregs);
1502                 if (error)
1503                         goto exit;
1504         }
1505
1506 exit:
1507         if (tmpdata != NULL)
1508                 kfree(tmpdata, M_TEMP);
1509         return (error);
1510 }
1511
1512 /*
1513  * Generate a note sub-structure.
1514  *
1515  * NOTE: 4-byte alignment.
1516  */
1517 static int
1518 __elfN(putnote)(elf_buf_t target, const char *name, int type,
1519             const void *desc, size_t descsz)
1520 {
1521         int error = 0;
1522         char *dst;
1523         Elf_Note note;
1524
1525         note.n_namesz = strlen(name) + 1;
1526         note.n_descsz = descsz;
1527         note.n_type = type;
1528         dst = target_reserve(target, sizeof(note), &error);
1529         if (dst != NULL)
1530                 bcopy(&note, dst, sizeof note);
1531         dst = target_reserve(target, note.n_namesz, &error);
1532         if (dst != NULL)
1533                 bcopy(name, dst, note.n_namesz);
1534         target->off = roundup2(target->off, sizeof(Elf_Word));
1535         dst = target_reserve(target, note.n_descsz, &error);
1536         if (dst != NULL)
1537                 bcopy(desc, dst, note.n_descsz);
1538         target->off = roundup2(target->off, sizeof(Elf_Word));
1539         return (error);
1540 }
1541
1542
1543 static int
1544 elf_putsigs(struct lwp *lp, elf_buf_t target)
1545 {
1546         /* XXX lwp handle more than one lwp */
1547         struct proc *p = lp->lwp_proc;
1548         int error = 0;
1549         struct ckpt_siginfo *csi;
1550
1551         csi = target_reserve(target, sizeof(struct ckpt_siginfo), &error);
1552         if (csi) {
1553                 csi->csi_ckptpisz = sizeof(struct ckpt_siginfo);
1554                 bcopy(p->p_sigacts, &csi->csi_sigacts, sizeof(*p->p_sigacts));
1555                 bcopy(&p->p_realtimer, &csi->csi_itimerval, sizeof(struct itimerval));
1556                 bcopy(&lp->lwp_sigmask, &csi->csi_sigmask,
1557                         sizeof(sigset_t));
1558                 csi->csi_sigparent = p->p_sigparent;
1559         }
1560         return (error);
1561 }
1562
1563 static int
1564 elf_putfiles(struct proc *p, elf_buf_t target, struct file *ckfp)
1565 {
1566         int error = 0;
1567         int i;
1568         struct ckpt_filehdr *cfh = NULL;
1569         struct ckpt_fileinfo *cfi;
1570         struct file *fp;        
1571         struct vnode *vp;
1572         /*
1573          * the duplicated loop is gross, but it was the only way
1574          * to eliminate uninitialized variable warnings 
1575          */
1576         cfh = target_reserve(target, sizeof(struct ckpt_filehdr), &error);
1577         if (cfh) {
1578                 cfh->cfh_nfiles = 0;            
1579         }
1580
1581         /*
1582          * ignore STDIN/STDERR/STDOUT.
1583          */
1584         for (i = 3; error == 0 && i < p->p_fd->fd_nfiles; i++) {
1585                 fp = holdfp(p->p_fd, i, -1);
1586                 if (fp == NULL)
1587                         continue;
1588                 /* 
1589                  * XXX Only checkpoint vnodes for now.
1590                  */
1591                 if (fp->f_type != DTYPE_VNODE) {
1592                         fdrop(fp);
1593                         continue;
1594                 }
1595                 cfi = target_reserve(target, sizeof(struct ckpt_fileinfo),
1596                                         &error);
1597                 if (cfi == NULL) {
1598                         fdrop(fp);
1599                         continue;
1600                 }
1601                 cfi->cfi_index = -1;
1602                 cfi->cfi_type = fp->f_type;
1603                 cfi->cfi_flags = fp->f_flag;
1604                 cfi->cfi_offset = fp->f_offset;
1605                 cfi->cfi_ckflags = 0;
1606
1607                 if (fp == ckfp)
1608                         cfi->cfi_ckflags |= CKFIF_ISCKPTFD;
1609                 /* f_count and f_msgcount should not be saved/restored */
1610                 /* XXX save cred info */
1611
1612                 switch(fp->f_type) {
1613                 case DTYPE_VNODE:
1614                         vp = (struct vnode *)fp->f_data;
1615                         /*
1616                          * it looks like a bug in ptrace is marking 
1617                          * a non-vnode as a vnode - until we find the 
1618                          * root cause this will at least prevent
1619                          * further panics from truss
1620                          */
1621                         if (vp == NULL || vp->v_mount == NULL)
1622                                 break;
1623                         cfh->cfh_nfiles++;
1624                         cfi->cfi_index = i;
1625                         cfi->cfi_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1626                         error = VFS_VPTOFH(vp, &cfi->cfi_fh.fh_fid);
1627                         break;
1628                 default:
1629                         break;
1630                 }
1631                 fdrop(fp);
1632         }
1633         return (error);
1634 }
1635
1636 static int
1637 elf_puttextvp(struct proc *p, elf_buf_t target)
1638 {
1639         int error = 0;
1640         int *vn_count;
1641         struct fp_closure fpc;
1642         struct ckpt_vminfo *vminfo;
1643
1644         vminfo = target_reserve(target, sizeof(struct ckpt_vminfo), &error);
1645         if (vminfo != NULL) {
1646                 vminfo->cvm_dsize = p->p_vmspace->vm_dsize;
1647                 vminfo->cvm_tsize = p->p_vmspace->vm_tsize;
1648                 vminfo->cvm_daddr = p->p_vmspace->vm_daddr;
1649                 vminfo->cvm_taddr = p->p_vmspace->vm_taddr;
1650         }
1651
1652         fpc.count = 0;
1653         vn_count = target_reserve(target, sizeof(int), &error);
1654         if (target->buf != NULL) {
1655                 fpc.vnh = (struct vn_hdr *)(target->buf + target->off);
1656                 fpc.vnh_max = fpc.vnh + 
1657                         (target->off_max - target->off) / sizeof(struct vn_hdr);
1658                 error = each_segment(p, cb_put_fp, &fpc, 0);
1659                 if (vn_count)
1660                         *vn_count = fpc.count;
1661         } else {
1662                 error = each_segment(p, cb_fpcount_segment, &fpc.count, 0);
1663         }
1664         target->off += fpc.count * sizeof(struct vn_hdr);
1665         return (error);
1666 }
1667
1668 /*
1669  * Try to find the appropriate ABI-note section for checknote,
1670  * The entire image is searched if necessary, not only the first page.
1671  */
1672 static boolean_t
1673 __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *checknote,
1674     int32_t *osrel)
1675 {
1676         boolean_t valid_note_found;
1677         const Elf_Phdr *phdr, *pnote;
1678         const Elf_Ehdr *hdr;
1679         int i;
1680
1681         valid_note_found = FALSE;
1682         hdr = (const Elf_Ehdr *)imgp->image_header;
1683         phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
1684
1685         for (i = 0; i < hdr->e_phnum; i++) {
1686                 if (phdr[i].p_type == PT_NOTE) {
1687                         pnote = &phdr[i];
1688                         valid_note_found = check_PT_NOTE (imgp, checknote,
1689                                 osrel, pnote);
1690                         if (valid_note_found)
1691                                 break;
1692                 }
1693         }
1694         return valid_note_found;
1695 }
1696
1697 /*
1698  * Be careful not to create new overflow conditions when checking
1699  * for overflow.
1700  */
1701 static boolean_t
1702 note_overflow(const Elf_Note *note, size_t maxsize)
1703 {
1704         if (sizeof(*note) > maxsize)
1705                 return TRUE;
1706         if (note->n_namesz > maxsize - sizeof(*note))
1707                 return TRUE;
1708         return FALSE;
1709 }
1710
1711 static boolean_t
1712 hdr_overflow(__ElfN(Off) off_beg, __ElfN(Size) size)
1713 {
1714         __ElfN(Off) off_end;
1715
1716         off_end = off_beg + size;
1717         if (off_end < off_beg)
1718                 return TRUE;
1719         return FALSE;
1720 }
1721
1722 static boolean_t
1723 check_PT_NOTE(struct image_params *imgp, Elf_Brandnote *checknote,
1724               int32_t *osrel, const Elf_Phdr * pnote)
1725 {
1726         boolean_t limited_to_first_page;
1727         boolean_t found = FALSE;
1728         const Elf_Note *note, *note0, *note_end;
1729         const char *note_name;
1730         __ElfN(Off) noteloc, firstloc;
1731         __ElfN(Size) notesz, firstlen, endbyte;
1732         struct lwbuf *lwb;
1733         struct lwbuf lwb_cache;
1734         const char *page;
1735         char *data = NULL;
1736         int n;
1737
1738         if (hdr_overflow(pnote->p_offset, pnote->p_filesz))
1739                 return (FALSE);
1740         notesz = pnote->p_filesz;
1741         noteloc = pnote->p_offset;
1742         endbyte = noteloc + notesz;
1743         limited_to_first_page = noteloc < PAGE_SIZE && endbyte < PAGE_SIZE;
1744
1745         if (limited_to_first_page) {
1746                 note = (const Elf_Note *)(imgp->image_header + noteloc);
1747                 note_end = (const Elf_Note *)(imgp->image_header + endbyte);
1748                 note0 = note;
1749         } else {
1750                 firstloc = noteloc & PAGE_MASK;
1751                 firstlen = PAGE_SIZE - firstloc;
1752                 if (notesz < sizeof(Elf_Note) || notesz > PAGE_SIZE)
1753                         return (FALSE);
1754
1755                 lwb = &lwb_cache;
1756                 if (exec_map_page(imgp, noteloc >> PAGE_SHIFT, &lwb, &page))
1757                         return (FALSE);
1758                 if (firstlen < notesz) {         /* crosses page boundary */
1759                         data = kmalloc(notesz, M_TEMP, M_WAITOK);
1760                         bcopy(page + firstloc, data, firstlen);
1761
1762                         exec_unmap_page(lwb);
1763                         lwb = &lwb_cache;
1764                         if (exec_map_page(imgp, (noteloc >> PAGE_SHIFT) + 1,
1765                                 &lwb, &page)) {
1766                                 kfree(data, M_TEMP);
1767                                 return (FALSE);
1768                         }
1769                         bcopy(page, data + firstlen, notesz - firstlen);
1770                         note = note0 = (const Elf_Note *)(data);
1771                         note_end = (const Elf_Note *)(data + notesz);
1772                 } else {
1773                         note = note0 = (const Elf_Note *)(page + firstloc);
1774                         note_end = (const Elf_Note *)(page + firstloc +
1775                                 firstlen);
1776                 }
1777         }
1778
1779         for (n = 0; n < 100 && note >= note0 && note < note_end; n++) {
1780                 if (!aligned(note, Elf32_Addr))
1781                         break;
1782                 if (note_overflow(note, (const char *)note_end -
1783                                         (const char *)note)) {
1784                         break;
1785                 }
1786                 note_name = (const char *)(note + 1);
1787
1788                 if (note->n_namesz == checknote->hdr.n_namesz
1789                     && note->n_descsz == checknote->hdr.n_descsz
1790                     && note->n_type == checknote->hdr.n_type
1791                     && (strncmp(checknote->vendor, note_name,
1792                         checknote->hdr.n_namesz) == 0)) {
1793                         /* Fetch osreldata from ABI.note-tag */
1794                         if ((checknote->flags & BN_TRANSLATE_OSREL) != 0 &&
1795                             checknote->trans_osrel != NULL)
1796                                 checknote->trans_osrel(note, osrel);
1797                         found = TRUE;
1798                         break;
1799                 }
1800                 note = (const Elf_Note *)((const char *)(note + 1) +
1801                     roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1802                     roundup2(note->n_descsz, sizeof(Elf32_Addr)));
1803         }
1804
1805         if (!limited_to_first_page) {
1806                 if (data != NULL)
1807                         kfree(data, M_TEMP);
1808                 exec_unmap_page(lwb);
1809         }
1810         return (found);
1811 }
1812
1813 /*
1814  * The interpreter program header may be located beyond the first page, so
1815  * regardless of its location, a copy of the interpreter path is created so
1816  * that it may be safely referenced by the calling function in all case.  The
1817  * memory is allocated by calling function, and the copying is done here.
1818  */
1819 static boolean_t
1820 extract_interpreter(struct image_params *imgp, const Elf_Phdr *pinterpreter,
1821                     char *data)
1822 {
1823         boolean_t limited_to_first_page;
1824         const boolean_t result_success = FALSE;
1825         const boolean_t result_failure = TRUE;
1826         __ElfN(Off) pathloc, firstloc;
1827         __ElfN(Size) pathsz, firstlen, endbyte;
1828         struct lwbuf *lwb;
1829         struct lwbuf lwb_cache;
1830         const char *page;
1831
1832         if (hdr_overflow(pinterpreter->p_offset, pinterpreter->p_filesz))
1833                 return (result_failure);
1834         pathsz  = pinterpreter->p_filesz;
1835         pathloc = pinterpreter->p_offset;
1836         endbyte = pathloc + pathsz;
1837
1838         limited_to_first_page = pathloc < PAGE_SIZE && endbyte < PAGE_SIZE;
1839         if (limited_to_first_page) {
1840                 bcopy(imgp->image_header + pathloc, data, pathsz);
1841                 return (result_success);
1842         }
1843
1844         firstloc = pathloc & PAGE_MASK;
1845         firstlen = PAGE_SIZE - firstloc;
1846
1847         lwb = &lwb_cache;
1848         if (exec_map_page(imgp, pathloc >> PAGE_SHIFT, &lwb, &page))
1849                 return (result_failure);
1850
1851         if (firstlen < pathsz) {         /* crosses page boundary */
1852                 bcopy(page + firstloc, data, firstlen);
1853
1854                 exec_unmap_page(lwb);
1855                 lwb = &lwb_cache;
1856                 if (exec_map_page(imgp, (pathloc >> PAGE_SHIFT) + 1, &lwb,
1857                         &page))
1858                         return (result_failure);
1859                 bcopy(page, data + firstlen, pathsz - firstlen);
1860         } else
1861                 bcopy(page + firstloc, data, pathsz);
1862
1863         exec_unmap_page(lwb);
1864         return (result_success);
1865 }
1866
1867 static boolean_t
1868 __elfN(bsd_trans_osrel)(const Elf_Note *note, int32_t *osrel)
1869 {
1870         uintptr_t p;
1871
1872         p = (uintptr_t)(note + 1);
1873         p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1874         *osrel = *(const int32_t *)(p);
1875
1876         return (TRUE);
1877 }
1878
1879 /*
1880  * Tell kern_execve.c about it, with a little help from the linker.
1881  */
1882 #if defined(__x86_64__)
1883 static struct execsw elf_execsw = {exec_elf64_imgact, "ELF64"};
1884 EXEC_SET_ORDERED(elf64, elf_execsw, SI_ORDER_FIRST);
1885 #else /* i386 assumed */
1886 static struct execsw elf_execsw = {exec_elf32_imgact, "ELF32"};
1887 EXEC_SET_ORDERED(elf32, elf_execsw, SI_ORDER_FIRST);
1888 #endif
1889
1890 static vm_prot_t
1891 __elfN(trans_prot)(Elf_Word flags)
1892 {
1893         vm_prot_t prot;
1894
1895         prot = 0;
1896         if (flags & PF_X)
1897                 prot |= VM_PROT_EXECUTE;
1898         if (flags & PF_W)
1899                 prot |= VM_PROT_WRITE;
1900         if (flags & PF_R)
1901                 prot |= VM_PROT_READ;
1902         return (prot);
1903 }
1904
1905 static Elf_Word
1906 __elfN(untrans_prot)(vm_prot_t prot)
1907 {
1908         Elf_Word flags;
1909
1910         flags = 0;
1911         if (prot & VM_PROT_EXECUTE)
1912                 flags |= PF_X;
1913         if (prot & VM_PROT_READ)
1914                 flags |= PF_R;
1915         if (prot & VM_PROT_WRITE)
1916                 flags |= PF_W;
1917         return (flags);
1918 }