]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/imgact_elf.c
Update libucl to latest version
[FreeBSD/FreeBSD.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
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33
34 #include "opt_capsicum.h"
35 #include "opt_compat.h"
36 #include "opt_core.h"
37
38 #include <sys/param.h>
39 #include <sys/capsicum.h>
40 #include <sys/exec.h>
41 #include <sys/fcntl.h>
42 #include <sys/imgact.h>
43 #include <sys/imgact_elf.h>
44 #include <sys/kernel.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/mount.h>
48 #include <sys/mman.h>
49 #include <sys/namei.h>
50 #include <sys/pioctl.h>
51 #include <sys/proc.h>
52 #include <sys/procfs.h>
53 #include <sys/racct.h>
54 #include <sys/resourcevar.h>
55 #include <sys/rwlock.h>
56 #include <sys/sbuf.h>
57 #include <sys/sf_buf.h>
58 #include <sys/smp.h>
59 #include <sys/systm.h>
60 #include <sys/signalvar.h>
61 #include <sys/stat.h>
62 #include <sys/sx.h>
63 #include <sys/syscall.h>
64 #include <sys/sysctl.h>
65 #include <sys/sysent.h>
66 #include <sys/vnode.h>
67 #include <sys/syslog.h>
68 #include <sys/eventhandler.h>
69 #include <sys/user.h>
70
71 #include <net/zlib.h>
72
73 #include <vm/vm.h>
74 #include <vm/vm_kern.h>
75 #include <vm/vm_param.h>
76 #include <vm/pmap.h>
77 #include <vm/vm_map.h>
78 #include <vm/vm_object.h>
79 #include <vm/vm_extern.h>
80
81 #include <machine/elf.h>
82 #include <machine/md_var.h>
83
84 #define ELF_NOTE_ROUNDSIZE      4
85 #define OLD_EI_BRAND    8
86
87 static int __elfN(check_header)(const Elf_Ehdr *hdr);
88 static Elf_Brandinfo *__elfN(get_brandinfo)(struct image_params *imgp,
89     const char *interp, int interp_name_len, int32_t *osrel);
90 static int __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
91     u_long *entry, size_t pagesize);
92 static int __elfN(load_section)(struct image_params *imgp, vm_offset_t offset,
93     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot,
94     size_t pagesize);
95 static int __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp);
96 static boolean_t __elfN(freebsd_trans_osrel)(const Elf_Note *note,
97     int32_t *osrel);
98 static boolean_t kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel);
99 static boolean_t __elfN(check_note)(struct image_params *imgp,
100     Elf_Brandnote *checknote, int32_t *osrel);
101 static vm_prot_t __elfN(trans_prot)(Elf_Word);
102 static Elf_Word __elfN(untrans_prot)(vm_prot_t);
103
104 SYSCTL_NODE(_kern, OID_AUTO, __CONCAT(elf, __ELF_WORD_SIZE), CTLFLAG_RW, 0,
105     "");
106
107 #ifdef COMPRESS_USER_CORES
108 static int compress_core(gzFile, char *, char *, unsigned int,
109     struct thread * td);
110 #endif
111 #define CORE_BUF_SIZE   (16 * 1024)
112
113 int __elfN(fallback_brand) = -1;
114 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
115     fallback_brand, CTLFLAG_RWTUN, &__elfN(fallback_brand), 0,
116     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) " brand of last resort");
117
118 static int elf_legacy_coredump = 0;
119 SYSCTL_INT(_debug, OID_AUTO, __elfN(legacy_coredump), CTLFLAG_RW, 
120     &elf_legacy_coredump, 0, "");
121
122 int __elfN(nxstack) =
123 #if defined(__amd64__) || defined(__powerpc64__) /* both 64 and 32 bit */
124         1;
125 #else
126         0;
127 #endif
128 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
129     nxstack, CTLFLAG_RW, &__elfN(nxstack), 0,
130     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": enable non-executable stack");
131
132 #if __ELF_WORD_SIZE == 32
133 #if defined(__amd64__)
134 int i386_read_exec = 0;
135 SYSCTL_INT(_kern_elf32, OID_AUTO, read_exec, CTLFLAG_RW, &i386_read_exec, 0,
136     "enable execution from readable segments");
137 #endif
138 #endif
139
140 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
141
142 #define trunc_page_ps(va, ps)   ((va) & ~(ps - 1))
143 #define round_page_ps(va, ps)   (((va) + (ps - 1)) & ~(ps - 1))
144 #define aligned(a, t)   (trunc_page_ps((u_long)(a), sizeof(t)) == (u_long)(a))
145
146 static const char FREEBSD_ABI_VENDOR[] = "FreeBSD";
147
148 Elf_Brandnote __elfN(freebsd_brandnote) = {
149         .hdr.n_namesz   = sizeof(FREEBSD_ABI_VENDOR),
150         .hdr.n_descsz   = sizeof(int32_t),
151         .hdr.n_type     = 1,
152         .vendor         = FREEBSD_ABI_VENDOR,
153         .flags          = BN_TRANSLATE_OSREL,
154         .trans_osrel    = __elfN(freebsd_trans_osrel)
155 };
156
157 static boolean_t
158 __elfN(freebsd_trans_osrel)(const Elf_Note *note, int32_t *osrel)
159 {
160         uintptr_t p;
161
162         p = (uintptr_t)(note + 1);
163         p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
164         *osrel = *(const int32_t *)(p);
165
166         return (TRUE);
167 }
168
169 static const char GNU_ABI_VENDOR[] = "GNU";
170 static int GNU_KFREEBSD_ABI_DESC = 3;
171
172 Elf_Brandnote __elfN(kfreebsd_brandnote) = {
173         .hdr.n_namesz   = sizeof(GNU_ABI_VENDOR),
174         .hdr.n_descsz   = 16,   /* XXX at least 16 */
175         .hdr.n_type     = 1,
176         .vendor         = GNU_ABI_VENDOR,
177         .flags          = BN_TRANSLATE_OSREL,
178         .trans_osrel    = kfreebsd_trans_osrel
179 };
180
181 static boolean_t
182 kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel)
183 {
184         const Elf32_Word *desc;
185         uintptr_t p;
186
187         p = (uintptr_t)(note + 1);
188         p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
189
190         desc = (const Elf32_Word *)p;
191         if (desc[0] != GNU_KFREEBSD_ABI_DESC)
192                 return (FALSE);
193
194         /*
195          * Debian GNU/kFreeBSD embed the earliest compatible kernel version
196          * (__FreeBSD_version: <major><two digit minor>Rxx) in the LSB way.
197          */
198         *osrel = desc[1] * 100000 + desc[2] * 1000 + desc[3];
199
200         return (TRUE);
201 }
202
203 int
204 __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
205 {
206         int i;
207
208         for (i = 0; i < MAX_BRANDS; i++) {
209                 if (elf_brand_list[i] == NULL) {
210                         elf_brand_list[i] = entry;
211                         break;
212                 }
213         }
214         if (i == MAX_BRANDS) {
215                 printf("WARNING: %s: could not insert brandinfo entry: %p\n",
216                         __func__, entry);
217                 return (-1);
218         }
219         return (0);
220 }
221
222 int
223 __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
224 {
225         int i;
226
227         for (i = 0; i < MAX_BRANDS; i++) {
228                 if (elf_brand_list[i] == entry) {
229                         elf_brand_list[i] = NULL;
230                         break;
231                 }
232         }
233         if (i == MAX_BRANDS)
234                 return (-1);
235         return (0);
236 }
237
238 int
239 __elfN(brand_inuse)(Elf_Brandinfo *entry)
240 {
241         struct proc *p;
242         int rval = FALSE;
243
244         sx_slock(&allproc_lock);
245         FOREACH_PROC_IN_SYSTEM(p) {
246                 if (p->p_sysent == entry->sysvec) {
247                         rval = TRUE;
248                         break;
249                 }
250         }
251         sx_sunlock(&allproc_lock);
252
253         return (rval);
254 }
255
256 static Elf_Brandinfo *
257 __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
258     int interp_name_len, int32_t *osrel)
259 {
260         const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
261         Elf_Brandinfo *bi;
262         boolean_t ret;
263         int i;
264
265         /*
266          * We support four types of branding -- (1) the ELF EI_OSABI field
267          * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
268          * branding w/in the ELF header, (3) path of the `interp_path'
269          * field, and (4) the ".note.ABI-tag" ELF section.
270          */
271
272         /* Look for an ".note.ABI-tag" ELF section */
273         for (i = 0; i < MAX_BRANDS; i++) {
274                 bi = elf_brand_list[i];
275                 if (bi == NULL)
276                         continue;
277                 if (hdr->e_machine == bi->machine && (bi->flags &
278                     (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
279                         ret = __elfN(check_note)(imgp, bi->brand_note, osrel);
280                         if (ret)
281                                 return (bi);
282                 }
283         }
284
285         /* If the executable has a brand, search for it in the brand list. */
286         for (i = 0; i < MAX_BRANDS; i++) {
287                 bi = elf_brand_list[i];
288                 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
289                         continue;
290                 if (hdr->e_machine == bi->machine &&
291                     (hdr->e_ident[EI_OSABI] == bi->brand ||
292                     strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
293                     bi->compat_3_brand, strlen(bi->compat_3_brand)) == 0))
294                         return (bi);
295         }
296
297         /* No known brand, see if the header is recognized by any brand */
298         for (i = 0; i < MAX_BRANDS; i++) {
299                 bi = elf_brand_list[i];
300                 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY ||
301                     bi->header_supported == NULL)
302                         continue;
303                 if (hdr->e_machine == bi->machine) {
304                         ret = bi->header_supported(imgp);
305                         if (ret)
306                                 return (bi);
307                 }
308         }
309
310         /* Lacking a known brand, search for a recognized interpreter. */
311         if (interp != NULL) {
312                 for (i = 0; i < MAX_BRANDS; i++) {
313                         bi = elf_brand_list[i];
314                         if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
315                                 continue;
316                         if (hdr->e_machine == bi->machine &&
317                             /* ELF image p_filesz includes terminating zero */
318                             strlen(bi->interp_path) + 1 == interp_name_len &&
319                             strncmp(interp, bi->interp_path, interp_name_len)
320                             == 0)
321                                 return (bi);
322                 }
323         }
324
325         /* Lacking a recognized interpreter, try the default brand */
326         for (i = 0; i < MAX_BRANDS; i++) {
327                 bi = elf_brand_list[i];
328                 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
329                         continue;
330                 if (hdr->e_machine == bi->machine &&
331                     __elfN(fallback_brand) == bi->brand)
332                         return (bi);
333         }
334         return (NULL);
335 }
336
337 static int
338 __elfN(check_header)(const Elf_Ehdr *hdr)
339 {
340         Elf_Brandinfo *bi;
341         int i;
342
343         if (!IS_ELF(*hdr) ||
344             hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
345             hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
346             hdr->e_ident[EI_VERSION] != EV_CURRENT ||
347             hdr->e_phentsize != sizeof(Elf_Phdr) ||
348             hdr->e_version != ELF_TARG_VER)
349                 return (ENOEXEC);
350
351         /*
352          * Make sure we have at least one brand for this machine.
353          */
354
355         for (i = 0; i < MAX_BRANDS; i++) {
356                 bi = elf_brand_list[i];
357                 if (bi != NULL && bi->machine == hdr->e_machine)
358                         break;
359         }
360         if (i == MAX_BRANDS)
361                 return (ENOEXEC);
362
363         return (0);
364 }
365
366 static int
367 __elfN(map_partial)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
368     vm_offset_t start, vm_offset_t end, vm_prot_t prot)
369 {
370         struct sf_buf *sf;
371         int error;
372         vm_offset_t off;
373
374         /*
375          * Create the page if it doesn't exist yet. Ignore errors.
376          */
377         vm_map_lock(map);
378         vm_map_insert(map, NULL, 0, trunc_page(start), round_page(end),
379             VM_PROT_ALL, VM_PROT_ALL, 0);
380         vm_map_unlock(map);
381
382         /*
383          * Find the page from the underlying object.
384          */
385         if (object) {
386                 sf = vm_imgact_map_page(object, offset);
387                 if (sf == NULL)
388                         return (KERN_FAILURE);
389                 off = offset - trunc_page(offset);
390                 error = copyout((caddr_t)sf_buf_kva(sf) + off, (caddr_t)start,
391                     end - start);
392                 vm_imgact_unmap_page(sf);
393                 if (error) {
394                         return (KERN_FAILURE);
395                 }
396         }
397
398         return (KERN_SUCCESS);
399 }
400
401 static int
402 __elfN(map_insert)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
403     vm_offset_t start, vm_offset_t end, vm_prot_t prot, int cow)
404 {
405         struct sf_buf *sf;
406         vm_offset_t off;
407         vm_size_t sz;
408         int error, rv;
409
410         if (start != trunc_page(start)) {
411                 rv = __elfN(map_partial)(map, object, offset, start,
412                     round_page(start), prot);
413                 if (rv)
414                         return (rv);
415                 offset += round_page(start) - start;
416                 start = round_page(start);
417         }
418         if (end != round_page(end)) {
419                 rv = __elfN(map_partial)(map, object, offset +
420                     trunc_page(end) - start, trunc_page(end), end, prot);
421                 if (rv)
422                         return (rv);
423                 end = trunc_page(end);
424         }
425         if (end > start) {
426                 if (offset & PAGE_MASK) {
427                         /*
428                          * The mapping is not page aligned. This means we have
429                          * to copy the data. Sigh.
430                          */
431                         rv = vm_map_find(map, NULL, 0, &start, end - start, 0,
432                             VMFS_NO_SPACE, prot | VM_PROT_WRITE, VM_PROT_ALL,
433                             0);
434                         if (rv)
435                                 return (rv);
436                         if (object == NULL)
437                                 return (KERN_SUCCESS);
438                         for (; start < end; start += sz) {
439                                 sf = vm_imgact_map_page(object, offset);
440                                 if (sf == NULL)
441                                         return (KERN_FAILURE);
442                                 off = offset - trunc_page(offset);
443                                 sz = end - start;
444                                 if (sz > PAGE_SIZE - off)
445                                         sz = PAGE_SIZE - off;
446                                 error = copyout((caddr_t)sf_buf_kva(sf) + off,
447                                     (caddr_t)start, sz);
448                                 vm_imgact_unmap_page(sf);
449                                 if (error) {
450                                         return (KERN_FAILURE);
451                                 }
452                                 offset += sz;
453                         }
454                         rv = KERN_SUCCESS;
455                 } else {
456                         vm_object_reference(object);
457                         vm_map_lock(map);
458                         rv = vm_map_insert(map, object, offset, start, end,
459                             prot, VM_PROT_ALL, cow);
460                         vm_map_unlock(map);
461                         if (rv != KERN_SUCCESS)
462                                 vm_object_deallocate(object);
463                 }
464                 return (rv);
465         } else {
466                 return (KERN_SUCCESS);
467         }
468 }
469
470 static int
471 __elfN(load_section)(struct image_params *imgp, vm_offset_t offset,
472     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot,
473     size_t pagesize)
474 {
475         struct sf_buf *sf;
476         size_t map_len;
477         vm_map_t map;
478         vm_object_t object;
479         vm_offset_t map_addr;
480         int error, rv, cow;
481         size_t copy_len;
482         vm_offset_t file_addr;
483
484         /*
485          * It's necessary to fail if the filsz + offset taken from the
486          * header is greater than the actual file pager object's size.
487          * If we were to allow this, then the vm_map_find() below would
488          * walk right off the end of the file object and into the ether.
489          *
490          * While I'm here, might as well check for something else that
491          * is invalid: filsz cannot be greater than memsz.
492          */
493         if ((off_t)filsz + offset > imgp->attr->va_size || filsz > memsz) {
494                 uprintf("elf_load_section: truncated ELF file\n");
495                 return (ENOEXEC);
496         }
497
498         object = imgp->object;
499         map = &imgp->proc->p_vmspace->vm_map;
500         map_addr = trunc_page_ps((vm_offset_t)vmaddr, pagesize);
501         file_addr = trunc_page_ps(offset, pagesize);
502
503         /*
504          * We have two choices.  We can either clear the data in the last page
505          * of an oversized mapping, or we can start the anon mapping a page
506          * early and copy the initialized data into that first page.  We
507          * choose the second..
508          */
509         if (memsz > filsz)
510                 map_len = trunc_page_ps(offset + filsz, pagesize) - file_addr;
511         else
512                 map_len = round_page_ps(offset + filsz, pagesize) - file_addr;
513
514         if (map_len != 0) {
515                 /* cow flags: don't dump readonly sections in core */
516                 cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
517                     (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
518
519                 rv = __elfN(map_insert)(map,
520                                       object,
521                                       file_addr,        /* file offset */
522                                       map_addr,         /* virtual start */
523                                       map_addr + map_len,/* virtual end */
524                                       prot,
525                                       cow);
526                 if (rv != KERN_SUCCESS)
527                         return (EINVAL);
528
529                 /* we can stop now if we've covered it all */
530                 if (memsz == filsz) {
531                         return (0);
532                 }
533         }
534
535
536         /*
537          * We have to get the remaining bit of the file into the first part
538          * of the oversized map segment.  This is normally because the .data
539          * segment in the file is extended to provide bss.  It's a neat idea
540          * to try and save a page, but it's a pain in the behind to implement.
541          */
542         copy_len = (offset + filsz) - trunc_page_ps(offset + filsz, pagesize);
543         map_addr = trunc_page_ps((vm_offset_t)vmaddr + filsz, pagesize);
544         map_len = round_page_ps((vm_offset_t)vmaddr + memsz, pagesize) -
545             map_addr;
546
547         /* This had damn well better be true! */
548         if (map_len != 0) {
549                 rv = __elfN(map_insert)(map, NULL, 0, map_addr, map_addr +
550                     map_len, VM_PROT_ALL, 0);
551                 if (rv != KERN_SUCCESS) {
552                         return (EINVAL);
553                 }
554         }
555
556         if (copy_len != 0) {
557                 vm_offset_t off;
558
559                 sf = vm_imgact_map_page(object, offset + filsz);
560                 if (sf == NULL)
561                         return (EIO);
562
563                 /* send the page fragment to user space */
564                 off = trunc_page_ps(offset + filsz, pagesize) -
565                     trunc_page(offset + filsz);
566                 error = copyout((caddr_t)sf_buf_kva(sf) + off,
567                     (caddr_t)map_addr, copy_len);
568                 vm_imgact_unmap_page(sf);
569                 if (error) {
570                         return (error);
571                 }
572         }
573
574         /*
575          * set it to the specified protection.
576          * XXX had better undo the damage from pasting over the cracks here!
577          */
578         vm_map_protect(map, trunc_page(map_addr), round_page(map_addr +
579             map_len), prot, FALSE);
580
581         return (0);
582 }
583
584 /*
585  * Load the file "file" into memory.  It may be either a shared object
586  * or an executable.
587  *
588  * The "addr" reference parameter is in/out.  On entry, it specifies
589  * the address where a shared object should be loaded.  If the file is
590  * an executable, this value is ignored.  On exit, "addr" specifies
591  * where the file was actually loaded.
592  *
593  * The "entry" reference parameter is out only.  On exit, it specifies
594  * the entry point for the loaded file.
595  */
596 static int
597 __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
598         u_long *entry, size_t pagesize)
599 {
600         struct {
601                 struct nameidata nd;
602                 struct vattr attr;
603                 struct image_params image_params;
604         } *tempdata;
605         const Elf_Ehdr *hdr = NULL;
606         const Elf_Phdr *phdr = NULL;
607         struct nameidata *nd;
608         struct vattr *attr;
609         struct image_params *imgp;
610         vm_prot_t prot;
611         u_long rbase;
612         u_long base_addr = 0;
613         int error, i, numsegs;
614
615 #ifdef CAPABILITY_MODE
616         /*
617          * XXXJA: This check can go away once we are sufficiently confident
618          * that the checks in namei() are correct.
619          */
620         if (IN_CAPABILITY_MODE(curthread))
621                 return (ECAPMODE);
622 #endif
623
624         tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
625         nd = &tempdata->nd;
626         attr = &tempdata->attr;
627         imgp = &tempdata->image_params;
628
629         /*
630          * Initialize part of the common data
631          */
632         imgp->proc = p;
633         imgp->attr = attr;
634         imgp->firstpage = NULL;
635         imgp->image_header = NULL;
636         imgp->object = NULL;
637         imgp->execlabel = NULL;
638
639         NDINIT(nd, LOOKUP, LOCKLEAF | FOLLOW, UIO_SYSSPACE, file, curthread);
640         if ((error = namei(nd)) != 0) {
641                 nd->ni_vp = NULL;
642                 goto fail;
643         }
644         NDFREE(nd, NDF_ONLY_PNBUF);
645         imgp->vp = nd->ni_vp;
646
647         /*
648          * Check permissions, modes, uid, etc on the file, and "open" it.
649          */
650         error = exec_check_permissions(imgp);
651         if (error)
652                 goto fail;
653
654         error = exec_map_first_page(imgp);
655         if (error)
656                 goto fail;
657
658         /*
659          * Also make certain that the interpreter stays the same, so set
660          * its VV_TEXT flag, too.
661          */
662         VOP_SET_TEXT(nd->ni_vp);
663
664         imgp->object = nd->ni_vp->v_object;
665
666         hdr = (const Elf_Ehdr *)imgp->image_header;
667         if ((error = __elfN(check_header)(hdr)) != 0)
668                 goto fail;
669         if (hdr->e_type == ET_DYN)
670                 rbase = *addr;
671         else if (hdr->e_type == ET_EXEC)
672                 rbase = 0;
673         else {
674                 error = ENOEXEC;
675                 goto fail;
676         }
677
678         /* Only support headers that fit within first page for now      */
679         if ((hdr->e_phoff > PAGE_SIZE) ||
680             (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
681                 error = ENOEXEC;
682                 goto fail;
683         }
684
685         phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
686         if (!aligned(phdr, Elf_Addr)) {
687                 error = ENOEXEC;
688                 goto fail;
689         }
690
691         for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
692                 if (phdr[i].p_type == PT_LOAD && phdr[i].p_memsz != 0) {
693                         /* Loadable segment */
694                         prot = __elfN(trans_prot)(phdr[i].p_flags);
695                         error = __elfN(load_section)(imgp, phdr[i].p_offset,
696                             (caddr_t)(uintptr_t)phdr[i].p_vaddr + rbase,
697                             phdr[i].p_memsz, phdr[i].p_filesz, prot, pagesize);
698                         if (error != 0)
699                                 goto fail;
700                         /*
701                          * Establish the base address if this is the
702                          * first segment.
703                          */
704                         if (numsegs == 0)
705                                 base_addr = trunc_page(phdr[i].p_vaddr +
706                                     rbase);
707                         numsegs++;
708                 }
709         }
710         *addr = base_addr;
711         *entry = (unsigned long)hdr->e_entry + rbase;
712
713 fail:
714         if (imgp->firstpage)
715                 exec_unmap_first_page(imgp);
716
717         if (nd->ni_vp)
718                 vput(nd->ni_vp);
719
720         free(tempdata, M_TEMP);
721
722         return (error);
723 }
724
725 static int
726 __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp)
727 {
728         const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
729         const Elf_Phdr *phdr;
730         Elf_Auxargs *elf_auxargs;
731         struct vmspace *vmspace;
732         vm_prot_t prot;
733         u_long text_size = 0, data_size = 0, total_size = 0;
734         u_long text_addr = 0, data_addr = 0;
735         u_long seg_size, seg_addr;
736         u_long addr, baddr, et_dyn_addr, entry = 0, proghdr = 0;
737         int32_t osrel = 0;
738         int error = 0, i, n, interp_name_len = 0;
739         const char *interp = NULL, *newinterp = NULL;
740         Elf_Brandinfo *brand_info;
741         char *path;
742         struct sysentvec *sv;
743
744         /*
745          * Do we have a valid ELF header ?
746          *
747          * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later
748          * if particular brand doesn't support it.
749          */
750         if (__elfN(check_header)(hdr) != 0 ||
751             (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
752                 return (-1);
753
754         /*
755          * From here on down, we return an errno, not -1, as we've
756          * detected an ELF file.
757          */
758
759         if ((hdr->e_phoff > PAGE_SIZE) ||
760             (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
761                 /* Only support headers in first page for now */
762                 return (ENOEXEC);
763         }
764         phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
765         if (!aligned(phdr, Elf_Addr))
766                 return (ENOEXEC);
767         n = 0;
768         baddr = 0;
769         for (i = 0; i < hdr->e_phnum; i++) {
770                 switch (phdr[i].p_type) {
771                 case PT_LOAD:
772                         if (n == 0)
773                                 baddr = phdr[i].p_vaddr;
774                         n++;
775                         break;
776                 case PT_INTERP:
777                         /* Path to interpreter */
778                         if (phdr[i].p_filesz > MAXPATHLEN ||
779                             phdr[i].p_offset > PAGE_SIZE ||
780                             phdr[i].p_filesz > PAGE_SIZE - phdr[i].p_offset)
781                                 return (ENOEXEC);
782                         interp = imgp->image_header + phdr[i].p_offset;
783                         interp_name_len = phdr[i].p_filesz;
784                         break;
785                 case PT_GNU_STACK:
786                         if (__elfN(nxstack))
787                                 imgp->stack_prot =
788                                     __elfN(trans_prot)(phdr[i].p_flags);
789                         break;
790                 }
791         }
792
793         brand_info = __elfN(get_brandinfo)(imgp, interp, interp_name_len,
794             &osrel);
795         if (brand_info == NULL) {
796                 uprintf("ELF binary type \"%u\" not known.\n",
797                     hdr->e_ident[EI_OSABI]);
798                 return (ENOEXEC);
799         }
800         if (hdr->e_type == ET_DYN) {
801                 if ((brand_info->flags & BI_CAN_EXEC_DYN) == 0)
802                         return (ENOEXEC);
803                 /*
804                  * Honour the base load address from the dso if it is
805                  * non-zero for some reason.
806                  */
807                 if (baddr == 0)
808                         et_dyn_addr = ET_DYN_LOAD_ADDR;
809                 else
810                         et_dyn_addr = 0;
811         } else
812                 et_dyn_addr = 0;
813         sv = brand_info->sysvec;
814         if (interp != NULL && brand_info->interp_newpath != NULL)
815                 newinterp = brand_info->interp_newpath;
816
817         /*
818          * Avoid a possible deadlock if the current address space is destroyed
819          * and that address space maps the locked vnode.  In the common case,
820          * the locked vnode's v_usecount is decremented but remains greater
821          * than zero.  Consequently, the vnode lock is not needed by vrele().
822          * However, in cases where the vnode lock is external, such as nullfs,
823          * v_usecount may become zero.
824          *
825          * The VV_TEXT flag prevents modifications to the executable while
826          * the vnode is unlocked.
827          */
828         VOP_UNLOCK(imgp->vp, 0);
829
830         error = exec_new_vmspace(imgp, sv);
831         imgp->proc->p_sysent = sv;
832
833         vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
834         if (error)
835                 return (error);
836
837         for (i = 0; i < hdr->e_phnum; i++) {
838                 switch (phdr[i].p_type) {
839                 case PT_LOAD:   /* Loadable segment */
840                         if (phdr[i].p_memsz == 0)
841                                 break;
842                         prot = __elfN(trans_prot)(phdr[i].p_flags);
843                         error = __elfN(load_section)(imgp, phdr[i].p_offset,
844                             (caddr_t)(uintptr_t)phdr[i].p_vaddr + et_dyn_addr,
845                             phdr[i].p_memsz, phdr[i].p_filesz, prot,
846                             sv->sv_pagesize);
847                         if (error != 0)
848                                 return (error);
849
850                         /*
851                          * If this segment contains the program headers,
852                          * remember their virtual address for the AT_PHDR
853                          * aux entry. Static binaries don't usually include
854                          * a PT_PHDR entry.
855                          */
856                         if (phdr[i].p_offset == 0 &&
857                             hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
858                                 <= phdr[i].p_filesz)
859                                 proghdr = phdr[i].p_vaddr + hdr->e_phoff +
860                                     et_dyn_addr;
861
862                         seg_addr = trunc_page(phdr[i].p_vaddr + et_dyn_addr);
863                         seg_size = round_page(phdr[i].p_memsz +
864                             phdr[i].p_vaddr + et_dyn_addr - seg_addr);
865
866                         /*
867                          * Make the largest executable segment the official
868                          * text segment and all others data.
869                          *
870                          * Note that obreak() assumes that data_addr + 
871                          * data_size == end of data load area, and the ELF
872                          * file format expects segments to be sorted by
873                          * address.  If multiple data segments exist, the
874                          * last one will be used.
875                          */
876
877                         if (phdr[i].p_flags & PF_X && text_size < seg_size) {
878                                 text_size = seg_size;
879                                 text_addr = seg_addr;
880                         } else {
881                                 data_size = seg_size;
882                                 data_addr = seg_addr;
883                         }
884                         total_size += seg_size;
885                         break;
886                 case PT_PHDR:   /* Program header table info */
887                         proghdr = phdr[i].p_vaddr + et_dyn_addr;
888                         break;
889                 default:
890                         break;
891                 }
892         }
893         
894         if (data_addr == 0 && data_size == 0) {
895                 data_addr = text_addr;
896                 data_size = text_size;
897         }
898
899         entry = (u_long)hdr->e_entry + et_dyn_addr;
900
901         /*
902          * Check limits.  It should be safe to check the
903          * limits after loading the segments since we do
904          * not actually fault in all the segments pages.
905          */
906         PROC_LOCK(imgp->proc);
907         if (data_size > lim_cur(imgp->proc, RLIMIT_DATA) ||
908             text_size > maxtsiz ||
909             total_size > lim_cur(imgp->proc, RLIMIT_VMEM) ||
910             racct_set(imgp->proc, RACCT_DATA, data_size) != 0 ||
911             racct_set(imgp->proc, RACCT_VMEM, total_size) != 0) {
912                 PROC_UNLOCK(imgp->proc);
913                 return (ENOMEM);
914         }
915
916         vmspace = imgp->proc->p_vmspace;
917         vmspace->vm_tsize = text_size >> PAGE_SHIFT;
918         vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
919         vmspace->vm_dsize = data_size >> PAGE_SHIFT;
920         vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
921
922         /*
923          * We load the dynamic linker where a userland call
924          * to mmap(0, ...) would put it.  The rationale behind this
925          * calculation is that it leaves room for the heap to grow to
926          * its maximum allowed size.
927          */
928         addr = round_page((vm_offset_t)vmspace->vm_daddr + lim_max(imgp->proc,
929             RLIMIT_DATA));
930         PROC_UNLOCK(imgp->proc);
931
932         imgp->entry_addr = entry;
933
934         if (interp != NULL) {
935                 int have_interp = FALSE;
936                 VOP_UNLOCK(imgp->vp, 0);
937                 if (brand_info->emul_path != NULL &&
938                     brand_info->emul_path[0] != '\0') {
939                         path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
940                         snprintf(path, MAXPATHLEN, "%s%s",
941                             brand_info->emul_path, interp);
942                         error = __elfN(load_file)(imgp->proc, path, &addr,
943                             &imgp->entry_addr, sv->sv_pagesize);
944                         free(path, M_TEMP);
945                         if (error == 0)
946                                 have_interp = TRUE;
947                 }
948                 if (!have_interp && newinterp != NULL) {
949                         error = __elfN(load_file)(imgp->proc, newinterp, &addr,
950                             &imgp->entry_addr, sv->sv_pagesize);
951                         if (error == 0)
952                                 have_interp = TRUE;
953                 }
954                 if (!have_interp) {
955                         error = __elfN(load_file)(imgp->proc, interp, &addr,
956                             &imgp->entry_addr, sv->sv_pagesize);
957                 }
958                 vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
959                 if (error != 0) {
960                         uprintf("ELF interpreter %s not found\n", interp);
961                         return (error);
962                 }
963         } else
964                 addr = et_dyn_addr;
965
966         /*
967          * Construct auxargs table (used by the fixup routine)
968          */
969         elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
970         elf_auxargs->execfd = -1;
971         elf_auxargs->phdr = proghdr;
972         elf_auxargs->phent = hdr->e_phentsize;
973         elf_auxargs->phnum = hdr->e_phnum;
974         elf_auxargs->pagesz = PAGE_SIZE;
975         elf_auxargs->base = addr;
976         elf_auxargs->flags = 0;
977         elf_auxargs->entry = entry;
978
979         imgp->auxargs = elf_auxargs;
980         imgp->interpreted = 0;
981         imgp->reloc_base = addr;
982         imgp->proc->p_osrel = osrel;
983
984         return (error);
985 }
986
987 #define suword __CONCAT(suword, __ELF_WORD_SIZE)
988
989 int
990 __elfN(freebsd_fixup)(register_t **stack_base, struct image_params *imgp)
991 {
992         Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
993         Elf_Addr *base;
994         Elf_Addr *pos;
995
996         base = (Elf_Addr *)*stack_base;
997         pos = base + (imgp->args->argc + imgp->args->envc + 2);
998
999         if (args->execfd != -1)
1000                 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
1001         AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
1002         AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
1003         AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
1004         AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
1005         AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
1006         AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
1007         AUXARGS_ENTRY(pos, AT_BASE, args->base);
1008         if (imgp->execpathp != 0)
1009                 AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp);
1010         AUXARGS_ENTRY(pos, AT_OSRELDATE, osreldate);
1011         if (imgp->canary != 0) {
1012                 AUXARGS_ENTRY(pos, AT_CANARY, imgp->canary);
1013                 AUXARGS_ENTRY(pos, AT_CANARYLEN, imgp->canarylen);
1014         }
1015         AUXARGS_ENTRY(pos, AT_NCPUS, mp_ncpus);
1016         if (imgp->pagesizes != 0) {
1017                 AUXARGS_ENTRY(pos, AT_PAGESIZES, imgp->pagesizes);
1018                 AUXARGS_ENTRY(pos, AT_PAGESIZESLEN, imgp->pagesizeslen);
1019         }
1020         if (imgp->sysent->sv_timekeep_base != 0) {
1021                 AUXARGS_ENTRY(pos, AT_TIMEKEEP,
1022                     imgp->sysent->sv_timekeep_base);
1023         }
1024         AUXARGS_ENTRY(pos, AT_STACKPROT, imgp->sysent->sv_shared_page_obj
1025             != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1026             imgp->sysent->sv_stackprot);
1027         AUXARGS_ENTRY(pos, AT_NULL, 0);
1028
1029         free(imgp->auxargs, M_TEMP);
1030         imgp->auxargs = NULL;
1031
1032         base--;
1033         suword(base, (long)imgp->args->argc);
1034         *stack_base = (register_t *)base;
1035         return (0);
1036 }
1037
1038 /*
1039  * Code for generating ELF core dumps.
1040  */
1041
1042 typedef void (*segment_callback)(vm_map_entry_t, void *);
1043
1044 /* Closure for cb_put_phdr(). */
1045 struct phdr_closure {
1046         Elf_Phdr *phdr;         /* Program header to fill in */
1047         Elf_Off offset;         /* Offset of segment in core file */
1048 };
1049
1050 /* Closure for cb_size_segment(). */
1051 struct sseg_closure {
1052         int count;              /* Count of writable segments. */
1053         size_t size;            /* Total size of all writable segments. */
1054 };
1055
1056 typedef void (*outfunc_t)(void *, struct sbuf *, size_t *);
1057
1058 struct note_info {
1059         int             type;           /* Note type. */
1060         outfunc_t       outfunc;        /* Output function. */
1061         void            *outarg;        /* Argument for the output function. */
1062         size_t          outsize;        /* Output size. */
1063         TAILQ_ENTRY(note_info) link;    /* Link to the next note info. */
1064 };
1065
1066 TAILQ_HEAD(note_info_list, note_info);
1067
1068 static void cb_put_phdr(vm_map_entry_t, void *);
1069 static void cb_size_segment(vm_map_entry_t, void *);
1070 static void each_writable_segment(struct thread *, segment_callback, void *);
1071 static int __elfN(corehdr)(struct thread *, struct vnode *, struct ucred *,
1072     int, void *, size_t, struct note_info_list *, size_t, gzFile);
1073 static void __elfN(prepare_notes)(struct thread *, struct note_info_list *,
1074     size_t *);
1075 static void __elfN(puthdr)(struct thread *, void *, size_t, int, size_t);
1076 static void __elfN(putnote)(struct note_info *, struct sbuf *);
1077 static size_t register_note(struct note_info_list *, int, outfunc_t, void *);
1078 static int sbuf_drain_core_output(void *, const char *, int);
1079 static int sbuf_drain_count(void *arg, const char *data, int len);
1080
1081 static void __elfN(note_fpregset)(void *, struct sbuf *, size_t *);
1082 static void __elfN(note_prpsinfo)(void *, struct sbuf *, size_t *);
1083 static void __elfN(note_prstatus)(void *, struct sbuf *, size_t *);
1084 static void __elfN(note_threadmd)(void *, struct sbuf *, size_t *);
1085 static void __elfN(note_thrmisc)(void *, struct sbuf *, size_t *);
1086 static void __elfN(note_procstat_auxv)(void *, struct sbuf *, size_t *);
1087 static void __elfN(note_procstat_proc)(void *, struct sbuf *, size_t *);
1088 static void __elfN(note_procstat_psstrings)(void *, struct sbuf *, size_t *);
1089 static void note_procstat_files(void *, struct sbuf *, size_t *);
1090 static void note_procstat_groups(void *, struct sbuf *, size_t *);
1091 static void note_procstat_osrel(void *, struct sbuf *, size_t *);
1092 static void note_procstat_rlimit(void *, struct sbuf *, size_t *);
1093 static void note_procstat_umask(void *, struct sbuf *, size_t *);
1094 static void note_procstat_vmmap(void *, struct sbuf *, size_t *);
1095
1096 #ifdef COMPRESS_USER_CORES
1097 extern int compress_user_cores;
1098 extern int compress_user_cores_gzlevel;
1099 #endif
1100
1101 static int
1102 core_output(struct vnode *vp, void *base, size_t len, off_t offset,
1103     struct ucred *active_cred, struct ucred *file_cred,
1104     struct thread *td, char *core_buf, gzFile gzfile) {
1105
1106         int error;
1107         if (gzfile) {
1108 #ifdef COMPRESS_USER_CORES
1109                 error = compress_core(gzfile, base, core_buf, len, td);
1110 #else
1111                 panic("shouldn't be here");
1112 #endif
1113         } else {
1114                 error = vn_rdwr_inchunks(UIO_WRITE, vp, base, len, offset,
1115                     UIO_USERSPACE, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
1116                     active_cred, file_cred, NULL, td);
1117         }
1118         return (error);
1119 }
1120
1121 /* Coredump output parameters for sbuf drain routine. */
1122 struct sbuf_drain_core_params {
1123         off_t           offset;
1124         struct ucred    *active_cred;
1125         struct ucred    *file_cred;
1126         struct thread   *td;
1127         struct vnode    *vp;
1128 #ifdef COMPRESS_USER_CORES
1129         gzFile          gzfile;
1130 #endif
1131 };
1132
1133 /*
1134  * Drain into a core file.
1135  */
1136 static int
1137 sbuf_drain_core_output(void *arg, const char *data, int len)
1138 {
1139         struct sbuf_drain_core_params *p;
1140         int error, locked;
1141
1142         p = (struct sbuf_drain_core_params *)arg;
1143
1144         /*
1145          * Some kern_proc out routines that print to this sbuf may
1146          * call us with the process lock held. Draining with the
1147          * non-sleepable lock held is unsafe. The lock is needed for
1148          * those routines when dumping a live process. In our case we
1149          * can safely release the lock before draining and acquire
1150          * again after.
1151          */
1152         locked = PROC_LOCKED(p->td->td_proc);
1153         if (locked)
1154                 PROC_UNLOCK(p->td->td_proc);
1155 #ifdef COMPRESS_USER_CORES
1156         if (p->gzfile != Z_NULL)
1157                 error = compress_core(p->gzfile, NULL, __DECONST(char *, data),
1158                     len, p->td);
1159         else
1160 #endif
1161                 error = vn_rdwr_inchunks(UIO_WRITE, p->vp,
1162                     __DECONST(void *, data), len, p->offset, UIO_SYSSPACE,
1163                     IO_UNIT | IO_DIRECT | IO_RANGELOCKED, p->active_cred,
1164                     p->file_cred, NULL, p->td);
1165         if (locked)
1166                 PROC_LOCK(p->td->td_proc);
1167         if (error != 0)
1168                 return (-error);
1169         p->offset += len;
1170         return (len);
1171 }
1172
1173 /*
1174  * Drain into a counter.
1175  */
1176 static int
1177 sbuf_drain_count(void *arg, const char *data __unused, int len)
1178 {
1179         size_t *sizep;
1180
1181         sizep = (size_t *)arg;
1182         *sizep += len;
1183         return (len);
1184 }
1185
1186 int
1187 __elfN(coredump)(struct thread *td, struct vnode *vp, off_t limit, int flags)
1188 {
1189         struct ucred *cred = td->td_ucred;
1190         int error = 0;
1191         struct sseg_closure seginfo;
1192         struct note_info_list notelst;
1193         struct note_info *ninfo;
1194         void *hdr;
1195         size_t hdrsize, notesz, coresize;
1196
1197         gzFile gzfile = Z_NULL;
1198         char *core_buf = NULL;
1199 #ifdef COMPRESS_USER_CORES
1200         char gzopen_flags[8];
1201         char *p;
1202         int doing_compress = flags & IMGACT_CORE_COMPRESS;
1203 #endif
1204
1205         hdr = NULL;
1206         TAILQ_INIT(&notelst);
1207
1208 #ifdef COMPRESS_USER_CORES
1209         if (doing_compress) {
1210                 p = gzopen_flags;
1211                 *p++ = 'w';
1212                 if (compress_user_cores_gzlevel >= 0 &&
1213                     compress_user_cores_gzlevel <= 9)
1214                         *p++ = '0' + compress_user_cores_gzlevel;
1215                 *p = 0;
1216                 gzfile = gz_open("", gzopen_flags, vp);
1217                 if (gzfile == Z_NULL) {
1218                         error = EFAULT;
1219                         goto done;
1220                 }
1221                 core_buf = malloc(CORE_BUF_SIZE, M_TEMP, M_WAITOK | M_ZERO);
1222                 if (!core_buf) {
1223                         error = ENOMEM;
1224                         goto done;
1225                 }
1226         }
1227 #endif
1228
1229         /* Size the program segments. */
1230         seginfo.count = 0;
1231         seginfo.size = 0;
1232         each_writable_segment(td, cb_size_segment, &seginfo);
1233
1234         /*
1235          * Collect info about the core file header area.
1236          */
1237         hdrsize = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * (1 + seginfo.count);
1238         __elfN(prepare_notes)(td, &notelst, &notesz);
1239         coresize = round_page(hdrsize + notesz) + seginfo.size;
1240
1241 #ifdef RACCT
1242         PROC_LOCK(td->td_proc);
1243         error = racct_add(td->td_proc, RACCT_CORE, coresize);
1244         PROC_UNLOCK(td->td_proc);
1245         if (error != 0) {
1246                 error = EFAULT;
1247                 goto done;
1248         }
1249 #endif
1250         if (coresize >= limit) {
1251                 error = EFAULT;
1252                 goto done;
1253         }
1254
1255         /*
1256          * Allocate memory for building the header, fill it up,
1257          * and write it out following the notes.
1258          */
1259         hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
1260         if (hdr == NULL) {
1261                 error = EINVAL;
1262                 goto done;
1263         }
1264         error = __elfN(corehdr)(td, vp, cred, seginfo.count, hdr, hdrsize,
1265             &notelst, notesz, gzfile);
1266
1267         /* Write the contents of all of the writable segments. */
1268         if (error == 0) {
1269                 Elf_Phdr *php;
1270                 off_t offset;
1271                 int i;
1272
1273                 php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
1274                 offset = round_page(hdrsize + notesz);
1275                 for (i = 0; i < seginfo.count; i++) {
1276                         error = core_output(vp, (caddr_t)(uintptr_t)php->p_vaddr,
1277                             php->p_filesz, offset, cred, NOCRED, curthread, core_buf, gzfile);
1278                         if (error != 0)
1279                                 break;
1280                         offset += php->p_filesz;
1281                         php++;
1282                 }
1283         }
1284         if (error) {
1285                 log(LOG_WARNING,
1286                     "Failed to write core file for process %s (error %d)\n",
1287                     curproc->p_comm, error);
1288         }
1289
1290 done:
1291 #ifdef COMPRESS_USER_CORES
1292         if (core_buf)
1293                 free(core_buf, M_TEMP);
1294         if (gzfile)
1295                 gzclose(gzfile);
1296 #endif
1297         while ((ninfo = TAILQ_FIRST(&notelst)) != NULL) {
1298                 TAILQ_REMOVE(&notelst, ninfo, link);
1299                 free(ninfo, M_TEMP);
1300         }
1301         if (hdr != NULL)
1302                 free(hdr, M_TEMP);
1303
1304         return (error);
1305 }
1306
1307 /*
1308  * A callback for each_writable_segment() to write out the segment's
1309  * program header entry.
1310  */
1311 static void
1312 cb_put_phdr(entry, closure)
1313         vm_map_entry_t entry;
1314         void *closure;
1315 {
1316         struct phdr_closure *phc = (struct phdr_closure *)closure;
1317         Elf_Phdr *phdr = phc->phdr;
1318
1319         phc->offset = round_page(phc->offset);
1320
1321         phdr->p_type = PT_LOAD;
1322         phdr->p_offset = phc->offset;
1323         phdr->p_vaddr = entry->start;
1324         phdr->p_paddr = 0;
1325         phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1326         phdr->p_align = PAGE_SIZE;
1327         phdr->p_flags = __elfN(untrans_prot)(entry->protection);
1328
1329         phc->offset += phdr->p_filesz;
1330         phc->phdr++;
1331 }
1332
1333 /*
1334  * A callback for each_writable_segment() to gather information about
1335  * the number of segments and their total size.
1336  */
1337 static void
1338 cb_size_segment(entry, closure)
1339         vm_map_entry_t entry;
1340         void *closure;
1341 {
1342         struct sseg_closure *ssc = (struct sseg_closure *)closure;
1343
1344         ssc->count++;
1345         ssc->size += entry->end - entry->start;
1346 }
1347
1348 /*
1349  * For each writable segment in the process's memory map, call the given
1350  * function with a pointer to the map entry and some arbitrary
1351  * caller-supplied data.
1352  */
1353 static void
1354 each_writable_segment(td, func, closure)
1355         struct thread *td;
1356         segment_callback func;
1357         void *closure;
1358 {
1359         struct proc *p = td->td_proc;
1360         vm_map_t map = &p->p_vmspace->vm_map;
1361         vm_map_entry_t entry;
1362         vm_object_t backing_object, object;
1363         boolean_t ignore_entry;
1364
1365         vm_map_lock_read(map);
1366         for (entry = map->header.next; entry != &map->header;
1367             entry = entry->next) {
1368                 /*
1369                  * Don't dump inaccessible mappings, deal with legacy
1370                  * coredump mode.
1371                  *
1372                  * Note that read-only segments related to the elf binary
1373                  * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1374                  * need to arbitrarily ignore such segments.
1375                  */
1376                 if (elf_legacy_coredump) {
1377                         if ((entry->protection & VM_PROT_RW) != VM_PROT_RW)
1378                                 continue;
1379                 } else {
1380                         if ((entry->protection & VM_PROT_ALL) == 0)
1381                                 continue;
1382                 }
1383
1384                 /*
1385                  * Dont include memory segment in the coredump if
1386                  * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1387                  * madvise(2).  Do not dump submaps (i.e. parts of the
1388                  * kernel map).
1389                  */
1390                 if (entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
1391                         continue;
1392
1393                 if ((object = entry->object.vm_object) == NULL)
1394                         continue;
1395
1396                 /* Ignore memory-mapped devices and such things. */
1397                 VM_OBJECT_RLOCK(object);
1398                 while ((backing_object = object->backing_object) != NULL) {
1399                         VM_OBJECT_RLOCK(backing_object);
1400                         VM_OBJECT_RUNLOCK(object);
1401                         object = backing_object;
1402                 }
1403                 ignore_entry = object->type != OBJT_DEFAULT &&
1404                     object->type != OBJT_SWAP && object->type != OBJT_VNODE;
1405                 VM_OBJECT_RUNLOCK(object);
1406                 if (ignore_entry)
1407                         continue;
1408
1409                 (*func)(entry, closure);
1410         }
1411         vm_map_unlock_read(map);
1412 }
1413
1414 /*
1415  * Write the core file header to the file, including padding up to
1416  * the page boundary.
1417  */
1418 static int
1419 __elfN(corehdr)(struct thread *td, struct vnode *vp, struct ucred *cred,
1420     int numsegs, void *hdr, size_t hdrsize, struct note_info_list *notelst,
1421     size_t notesz, gzFile gzfile)
1422 {
1423         struct sbuf_drain_core_params params;
1424         struct note_info *ninfo;
1425         struct sbuf *sb;
1426         int error;
1427
1428         /* Fill in the header. */
1429         bzero(hdr, hdrsize);
1430         __elfN(puthdr)(td, hdr, hdrsize, numsegs, notesz);
1431
1432         params.offset = 0;
1433         params.active_cred = cred;
1434         params.file_cred = NOCRED;
1435         params.td = td;
1436         params.vp = vp;
1437 #ifdef COMPRESS_USER_CORES
1438         params.gzfile = gzfile;
1439 #endif
1440         sb = sbuf_new(NULL, NULL, CORE_BUF_SIZE, SBUF_FIXEDLEN);
1441         sbuf_set_drain(sb, sbuf_drain_core_output, &params);
1442         sbuf_start_section(sb, NULL);
1443         sbuf_bcat(sb, hdr, hdrsize);
1444         TAILQ_FOREACH(ninfo, notelst, link)
1445             __elfN(putnote)(ninfo, sb);
1446         /* Align up to a page boundary for the program segments. */
1447         sbuf_end_section(sb, -1, PAGE_SIZE, 0);
1448         error = sbuf_finish(sb);
1449         sbuf_delete(sb);
1450
1451         return (error);
1452 }
1453
1454 static void
1455 __elfN(prepare_notes)(struct thread *td, struct note_info_list *list,
1456     size_t *sizep)
1457 {
1458         struct proc *p;
1459         struct thread *thr;
1460         size_t size;
1461
1462         p = td->td_proc;
1463         size = 0;
1464
1465         size += register_note(list, NT_PRPSINFO, __elfN(note_prpsinfo), p);
1466
1467         /*
1468          * To have the debugger select the right thread (LWP) as the initial
1469          * thread, we dump the state of the thread passed to us in td first.
1470          * This is the thread that causes the core dump and thus likely to
1471          * be the right thread one wants to have selected in the debugger.
1472          */
1473         thr = td;
1474         while (thr != NULL) {
1475                 size += register_note(list, NT_PRSTATUS,
1476                     __elfN(note_prstatus), thr);
1477                 size += register_note(list, NT_FPREGSET,
1478                     __elfN(note_fpregset), thr);
1479                 size += register_note(list, NT_THRMISC,
1480                     __elfN(note_thrmisc), thr);
1481                 size += register_note(list, -1,
1482                     __elfN(note_threadmd), thr);
1483
1484                 thr = (thr == td) ? TAILQ_FIRST(&p->p_threads) :
1485                     TAILQ_NEXT(thr, td_plist);
1486                 if (thr == td)
1487                         thr = TAILQ_NEXT(thr, td_plist);
1488         }
1489
1490         size += register_note(list, NT_PROCSTAT_PROC,
1491             __elfN(note_procstat_proc), p);
1492         size += register_note(list, NT_PROCSTAT_FILES,
1493             note_procstat_files, p);
1494         size += register_note(list, NT_PROCSTAT_VMMAP,
1495             note_procstat_vmmap, p);
1496         size += register_note(list, NT_PROCSTAT_GROUPS,
1497             note_procstat_groups, p);
1498         size += register_note(list, NT_PROCSTAT_UMASK,
1499             note_procstat_umask, p);
1500         size += register_note(list, NT_PROCSTAT_RLIMIT,
1501             note_procstat_rlimit, p);
1502         size += register_note(list, NT_PROCSTAT_OSREL,
1503             note_procstat_osrel, p);
1504         size += register_note(list, NT_PROCSTAT_PSSTRINGS,
1505             __elfN(note_procstat_psstrings), p);
1506         size += register_note(list, NT_PROCSTAT_AUXV,
1507             __elfN(note_procstat_auxv), p);
1508
1509         *sizep = size;
1510 }
1511
1512 static void
1513 __elfN(puthdr)(struct thread *td, void *hdr, size_t hdrsize, int numsegs,
1514     size_t notesz)
1515 {
1516         Elf_Ehdr *ehdr;
1517         Elf_Phdr *phdr;
1518         struct phdr_closure phc;
1519
1520         ehdr = (Elf_Ehdr *)hdr;
1521         phdr = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr));
1522
1523         ehdr->e_ident[EI_MAG0] = ELFMAG0;
1524         ehdr->e_ident[EI_MAG1] = ELFMAG1;
1525         ehdr->e_ident[EI_MAG2] = ELFMAG2;
1526         ehdr->e_ident[EI_MAG3] = ELFMAG3;
1527         ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1528         ehdr->e_ident[EI_DATA] = ELF_DATA;
1529         ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1530         ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1531         ehdr->e_ident[EI_ABIVERSION] = 0;
1532         ehdr->e_ident[EI_PAD] = 0;
1533         ehdr->e_type = ET_CORE;
1534 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1535         ehdr->e_machine = ELF_ARCH32;
1536 #else
1537         ehdr->e_machine = ELF_ARCH;
1538 #endif
1539         ehdr->e_version = EV_CURRENT;
1540         ehdr->e_entry = 0;
1541         ehdr->e_phoff = sizeof(Elf_Ehdr);
1542         ehdr->e_flags = 0;
1543         ehdr->e_ehsize = sizeof(Elf_Ehdr);
1544         ehdr->e_phentsize = sizeof(Elf_Phdr);
1545         ehdr->e_phnum = numsegs + 1;
1546         ehdr->e_shentsize = sizeof(Elf_Shdr);
1547         ehdr->e_shnum = 0;
1548         ehdr->e_shstrndx = SHN_UNDEF;
1549
1550         /*
1551          * Fill in the program header entries.
1552          */
1553
1554         /* The note segement. */
1555         phdr->p_type = PT_NOTE;
1556         phdr->p_offset = hdrsize;
1557         phdr->p_vaddr = 0;
1558         phdr->p_paddr = 0;
1559         phdr->p_filesz = notesz;
1560         phdr->p_memsz = 0;
1561         phdr->p_flags = PF_R;
1562         phdr->p_align = ELF_NOTE_ROUNDSIZE;
1563         phdr++;
1564
1565         /* All the writable segments from the program. */
1566         phc.phdr = phdr;
1567         phc.offset = round_page(hdrsize + notesz);
1568         each_writable_segment(td, cb_put_phdr, &phc);
1569 }
1570
1571 static size_t
1572 register_note(struct note_info_list *list, int type, outfunc_t out, void *arg)
1573 {
1574         struct note_info *ninfo;
1575         size_t size, notesize;
1576
1577         size = 0;
1578         out(arg, NULL, &size);
1579         ninfo = malloc(sizeof(*ninfo), M_TEMP, M_ZERO | M_WAITOK);
1580         ninfo->type = type;
1581         ninfo->outfunc = out;
1582         ninfo->outarg = arg;
1583         ninfo->outsize = size;
1584         TAILQ_INSERT_TAIL(list, ninfo, link);
1585
1586         if (type == -1)
1587                 return (size);
1588
1589         notesize = sizeof(Elf_Note) +           /* note header */
1590             roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
1591                                                 /* note name */
1592             roundup2(size, ELF_NOTE_ROUNDSIZE); /* note description */
1593
1594         return (notesize);
1595 }
1596
1597 static size_t
1598 append_note_data(const void *src, void *dst, size_t len)
1599 {
1600         size_t padded_len;
1601
1602         padded_len = roundup2(len, ELF_NOTE_ROUNDSIZE);
1603         if (dst != NULL) {
1604                 bcopy(src, dst, len);
1605                 bzero((char *)dst + len, padded_len - len);
1606         }
1607         return (padded_len);
1608 }
1609
1610 size_t
1611 __elfN(populate_note)(int type, void *src, void *dst, size_t size, void **descp)
1612 {
1613         Elf_Note *note;
1614         char *buf;
1615         size_t notesize;
1616
1617         buf = dst;
1618         if (buf != NULL) {
1619                 note = (Elf_Note *)buf;
1620                 note->n_namesz = sizeof(FREEBSD_ABI_VENDOR);
1621                 note->n_descsz = size;
1622                 note->n_type = type;
1623                 buf += sizeof(*note);
1624                 buf += append_note_data(FREEBSD_ABI_VENDOR, buf,
1625                     sizeof(FREEBSD_ABI_VENDOR));
1626                 append_note_data(src, buf, size);
1627                 if (descp != NULL)
1628                         *descp = buf;
1629         }
1630
1631         notesize = sizeof(Elf_Note) +           /* note header */
1632             roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
1633                                                 /* note name */
1634             roundup2(size, ELF_NOTE_ROUNDSIZE); /* note description */
1635
1636         return (notesize);
1637 }
1638
1639 static void
1640 __elfN(putnote)(struct note_info *ninfo, struct sbuf *sb)
1641 {
1642         Elf_Note note;
1643         ssize_t old_len;
1644
1645         if (ninfo->type == -1) {
1646                 ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
1647                 return;
1648         }
1649
1650         note.n_namesz = sizeof(FREEBSD_ABI_VENDOR);
1651         note.n_descsz = ninfo->outsize;
1652         note.n_type = ninfo->type;
1653
1654         sbuf_bcat(sb, &note, sizeof(note));
1655         sbuf_start_section(sb, &old_len);
1656         sbuf_bcat(sb, FREEBSD_ABI_VENDOR, sizeof(FREEBSD_ABI_VENDOR));
1657         sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
1658         if (note.n_descsz == 0)
1659                 return;
1660         sbuf_start_section(sb, &old_len);
1661         ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
1662         sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
1663 }
1664
1665 /*
1666  * Miscellaneous note out functions.
1667  */
1668
1669 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1670 #include <compat/freebsd32/freebsd32.h>
1671
1672 typedef struct prstatus32 elf_prstatus_t;
1673 typedef struct prpsinfo32 elf_prpsinfo_t;
1674 typedef struct fpreg32 elf_prfpregset_t;
1675 typedef struct fpreg32 elf_fpregset_t;
1676 typedef struct reg32 elf_gregset_t;
1677 typedef struct thrmisc32 elf_thrmisc_t;
1678 #define ELF_KERN_PROC_MASK      KERN_PROC_MASK32
1679 typedef struct kinfo_proc32 elf_kinfo_proc_t;
1680 typedef uint32_t elf_ps_strings_t;
1681 #else
1682 typedef prstatus_t elf_prstatus_t;
1683 typedef prpsinfo_t elf_prpsinfo_t;
1684 typedef prfpregset_t elf_prfpregset_t;
1685 typedef prfpregset_t elf_fpregset_t;
1686 typedef gregset_t elf_gregset_t;
1687 typedef thrmisc_t elf_thrmisc_t;
1688 #define ELF_KERN_PROC_MASK      0
1689 typedef struct kinfo_proc elf_kinfo_proc_t;
1690 typedef vm_offset_t elf_ps_strings_t;
1691 #endif
1692
1693 static void
1694 __elfN(note_prpsinfo)(void *arg, struct sbuf *sb, size_t *sizep)
1695 {
1696         struct proc *p;
1697         elf_prpsinfo_t *psinfo;
1698
1699         p = (struct proc *)arg;
1700         if (sb != NULL) {
1701                 KASSERT(*sizep == sizeof(*psinfo), ("invalid size"));
1702                 psinfo = malloc(sizeof(*psinfo), M_TEMP, M_ZERO | M_WAITOK);
1703                 psinfo->pr_version = PRPSINFO_VERSION;
1704                 psinfo->pr_psinfosz = sizeof(elf_prpsinfo_t);
1705                 strlcpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname));
1706                 /*
1707                  * XXX - We don't fill in the command line arguments properly
1708                  * yet.
1709                  */
1710                 strlcpy(psinfo->pr_psargs, p->p_comm,
1711                     sizeof(psinfo->pr_psargs));
1712
1713                 sbuf_bcat(sb, psinfo, sizeof(*psinfo));
1714                 free(psinfo, M_TEMP);
1715         }
1716         *sizep = sizeof(*psinfo);
1717 }
1718
1719 static void
1720 __elfN(note_prstatus)(void *arg, struct sbuf *sb, size_t *sizep)
1721 {
1722         struct thread *td;
1723         elf_prstatus_t *status;
1724
1725         td = (struct thread *)arg;
1726         if (sb != NULL) {
1727                 KASSERT(*sizep == sizeof(*status), ("invalid size"));
1728                 status = malloc(sizeof(*status), M_TEMP, M_ZERO | M_WAITOK);
1729                 status->pr_version = PRSTATUS_VERSION;
1730                 status->pr_statussz = sizeof(elf_prstatus_t);
1731                 status->pr_gregsetsz = sizeof(elf_gregset_t);
1732                 status->pr_fpregsetsz = sizeof(elf_fpregset_t);
1733                 status->pr_osreldate = osreldate;
1734                 status->pr_cursig = td->td_proc->p_sig;
1735                 status->pr_pid = td->td_tid;
1736 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1737                 fill_regs32(td, &status->pr_reg);
1738 #else
1739                 fill_regs(td, &status->pr_reg);
1740 #endif
1741                 sbuf_bcat(sb, status, sizeof(*status));
1742                 free(status, M_TEMP);
1743         }
1744         *sizep = sizeof(*status);
1745 }
1746
1747 static void
1748 __elfN(note_fpregset)(void *arg, struct sbuf *sb, size_t *sizep)
1749 {
1750         struct thread *td;
1751         elf_prfpregset_t *fpregset;
1752
1753         td = (struct thread *)arg;
1754         if (sb != NULL) {
1755                 KASSERT(*sizep == sizeof(*fpregset), ("invalid size"));
1756                 fpregset = malloc(sizeof(*fpregset), M_TEMP, M_ZERO | M_WAITOK);
1757 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1758                 fill_fpregs32(td, fpregset);
1759 #else
1760                 fill_fpregs(td, fpregset);
1761 #endif
1762                 sbuf_bcat(sb, fpregset, sizeof(*fpregset));
1763                 free(fpregset, M_TEMP);
1764         }
1765         *sizep = sizeof(*fpregset);
1766 }
1767
1768 static void
1769 __elfN(note_thrmisc)(void *arg, struct sbuf *sb, size_t *sizep)
1770 {
1771         struct thread *td;
1772         elf_thrmisc_t thrmisc;
1773
1774         td = (struct thread *)arg;
1775         if (sb != NULL) {
1776                 KASSERT(*sizep == sizeof(thrmisc), ("invalid size"));
1777                 bzero(&thrmisc._pad, sizeof(thrmisc._pad));
1778                 strcpy(thrmisc.pr_tname, td->td_name);
1779                 sbuf_bcat(sb, &thrmisc, sizeof(thrmisc));
1780         }
1781         *sizep = sizeof(thrmisc);
1782 }
1783
1784 /*
1785  * Allow for MD specific notes, as well as any MD
1786  * specific preparations for writing MI notes.
1787  */
1788 static void
1789 __elfN(note_threadmd)(void *arg, struct sbuf *sb, size_t *sizep)
1790 {
1791         struct thread *td;
1792         void *buf;
1793         size_t size;
1794
1795         td = (struct thread *)arg;
1796         size = *sizep;
1797         if (size != 0 && sb != NULL)
1798                 buf = malloc(size, M_TEMP, M_ZERO | M_WAITOK);
1799         else
1800                 buf = NULL;
1801         size = 0;
1802         __elfN(dump_thread)(td, buf, &size);
1803         KASSERT(sb == NULL || *sizep == size, ("invalid size"));
1804         if (size != 0 && sb != NULL)
1805                 sbuf_bcat(sb, buf, size);
1806         free(buf, M_TEMP);
1807         *sizep = size;
1808 }
1809
1810 #ifdef KINFO_PROC_SIZE
1811 CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
1812 #endif
1813
1814 static void
1815 __elfN(note_procstat_proc)(void *arg, struct sbuf *sb, size_t *sizep)
1816 {
1817         struct proc *p;
1818         size_t size;
1819         int structsize;
1820
1821         p = (struct proc *)arg;
1822         size = sizeof(structsize) + p->p_numthreads *
1823             sizeof(elf_kinfo_proc_t);
1824
1825         if (sb != NULL) {
1826                 KASSERT(*sizep == size, ("invalid size"));
1827                 structsize = sizeof(elf_kinfo_proc_t);
1828                 sbuf_bcat(sb, &structsize, sizeof(structsize));
1829                 sx_slock(&proctree_lock);
1830                 PROC_LOCK(p);
1831                 kern_proc_out(p, sb, ELF_KERN_PROC_MASK);
1832                 sx_sunlock(&proctree_lock);
1833         }
1834         *sizep = size;
1835 }
1836
1837 #ifdef KINFO_FILE_SIZE
1838 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
1839 #endif
1840
1841 static void
1842 note_procstat_files(void *arg, struct sbuf *sb, size_t *sizep)
1843 {
1844         struct proc *p;
1845         size_t size;
1846         int structsize;
1847
1848         p = (struct proc *)arg;
1849         if (sb == NULL) {
1850                 size = 0;
1851                 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
1852                 sbuf_set_drain(sb, sbuf_drain_count, &size);
1853                 sbuf_bcat(sb, &structsize, sizeof(structsize));
1854                 PROC_LOCK(p);
1855                 kern_proc_filedesc_out(p, sb, -1);
1856                 sbuf_finish(sb);
1857                 sbuf_delete(sb);
1858                 *sizep = size;
1859         } else {
1860                 structsize = sizeof(struct kinfo_file);
1861                 sbuf_bcat(sb, &structsize, sizeof(structsize));
1862                 PROC_LOCK(p);
1863                 kern_proc_filedesc_out(p, sb, -1);
1864         }
1865 }
1866
1867 #ifdef KINFO_VMENTRY_SIZE
1868 CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
1869 #endif
1870
1871 static void
1872 note_procstat_vmmap(void *arg, struct sbuf *sb, size_t *sizep)
1873 {
1874         struct proc *p;
1875         size_t size;
1876         int structsize;
1877
1878         p = (struct proc *)arg;
1879         if (sb == NULL) {
1880                 size = 0;
1881                 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
1882                 sbuf_set_drain(sb, sbuf_drain_count, &size);
1883                 sbuf_bcat(sb, &structsize, sizeof(structsize));
1884                 PROC_LOCK(p);
1885                 kern_proc_vmmap_out(p, sb);
1886                 sbuf_finish(sb);
1887                 sbuf_delete(sb);
1888                 *sizep = size;
1889         } else {
1890                 structsize = sizeof(struct kinfo_vmentry);
1891                 sbuf_bcat(sb, &structsize, sizeof(structsize));
1892                 PROC_LOCK(p);
1893                 kern_proc_vmmap_out(p, sb);
1894         }
1895 }
1896
1897 static void
1898 note_procstat_groups(void *arg, struct sbuf *sb, size_t *sizep)
1899 {
1900         struct proc *p;
1901         size_t size;
1902         int structsize;
1903
1904         p = (struct proc *)arg;
1905         size = sizeof(structsize) + p->p_ucred->cr_ngroups * sizeof(gid_t);
1906         if (sb != NULL) {
1907                 KASSERT(*sizep == size, ("invalid size"));
1908                 structsize = sizeof(gid_t);
1909                 sbuf_bcat(sb, &structsize, sizeof(structsize));
1910                 sbuf_bcat(sb, p->p_ucred->cr_groups, p->p_ucred->cr_ngroups *
1911                     sizeof(gid_t));
1912         }
1913         *sizep = size;
1914 }
1915
1916 static void
1917 note_procstat_umask(void *arg, struct sbuf *sb, size_t *sizep)
1918 {
1919         struct proc *p;
1920         size_t size;
1921         int structsize;
1922
1923         p = (struct proc *)arg;
1924         size = sizeof(structsize) + sizeof(p->p_fd->fd_cmask);
1925         if (sb != NULL) {
1926                 KASSERT(*sizep == size, ("invalid size"));
1927                 structsize = sizeof(p->p_fd->fd_cmask);
1928                 sbuf_bcat(sb, &structsize, sizeof(structsize));
1929                 sbuf_bcat(sb, &p->p_fd->fd_cmask, sizeof(p->p_fd->fd_cmask));
1930         }
1931         *sizep = size;
1932 }
1933
1934 static void
1935 note_procstat_rlimit(void *arg, struct sbuf *sb, size_t *sizep)
1936 {
1937         struct proc *p;
1938         struct rlimit rlim[RLIM_NLIMITS];
1939         size_t size;
1940         int structsize, i;
1941
1942         p = (struct proc *)arg;
1943         size = sizeof(structsize) + sizeof(rlim);
1944         if (sb != NULL) {
1945                 KASSERT(*sizep == size, ("invalid size"));
1946                 structsize = sizeof(rlim);
1947                 sbuf_bcat(sb, &structsize, sizeof(structsize));
1948                 PROC_LOCK(p);
1949                 for (i = 0; i < RLIM_NLIMITS; i++)
1950                         lim_rlimit(p, i, &rlim[i]);
1951                 PROC_UNLOCK(p);
1952                 sbuf_bcat(sb, rlim, sizeof(rlim));
1953         }
1954         *sizep = size;
1955 }
1956
1957 static void
1958 note_procstat_osrel(void *arg, struct sbuf *sb, size_t *sizep)
1959 {
1960         struct proc *p;
1961         size_t size;
1962         int structsize;
1963
1964         p = (struct proc *)arg;
1965         size = sizeof(structsize) + sizeof(p->p_osrel);
1966         if (sb != NULL) {
1967                 KASSERT(*sizep == size, ("invalid size"));
1968                 structsize = sizeof(p->p_osrel);
1969                 sbuf_bcat(sb, &structsize, sizeof(structsize));
1970                 sbuf_bcat(sb, &p->p_osrel, sizeof(p->p_osrel));
1971         }
1972         *sizep = size;
1973 }
1974
1975 static void
1976 __elfN(note_procstat_psstrings)(void *arg, struct sbuf *sb, size_t *sizep)
1977 {
1978         struct proc *p;
1979         elf_ps_strings_t ps_strings;
1980         size_t size;
1981         int structsize;
1982
1983         p = (struct proc *)arg;
1984         size = sizeof(structsize) + sizeof(ps_strings);
1985         if (sb != NULL) {
1986                 KASSERT(*sizep == size, ("invalid size"));
1987                 structsize = sizeof(ps_strings);
1988 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1989                 ps_strings = PTROUT(p->p_sysent->sv_psstrings);
1990 #else
1991                 ps_strings = p->p_sysent->sv_psstrings;
1992 #endif
1993                 sbuf_bcat(sb, &structsize, sizeof(structsize));
1994                 sbuf_bcat(sb, &ps_strings, sizeof(ps_strings));
1995         }
1996         *sizep = size;
1997 }
1998
1999 static void
2000 __elfN(note_procstat_auxv)(void *arg, struct sbuf *sb, size_t *sizep)
2001 {
2002         struct proc *p;
2003         size_t size;
2004         int structsize;
2005
2006         p = (struct proc *)arg;
2007         if (sb == NULL) {
2008                 size = 0;
2009                 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2010                 sbuf_set_drain(sb, sbuf_drain_count, &size);
2011                 sbuf_bcat(sb, &structsize, sizeof(structsize));
2012                 PHOLD(p);
2013                 proc_getauxv(curthread, p, sb);
2014                 PRELE(p);
2015                 sbuf_finish(sb);
2016                 sbuf_delete(sb);
2017                 *sizep = size;
2018         } else {
2019                 structsize = sizeof(Elf_Auxinfo);
2020                 sbuf_bcat(sb, &structsize, sizeof(structsize));
2021                 PHOLD(p);
2022                 proc_getauxv(curthread, p, sb);
2023                 PRELE(p);
2024         }
2025 }
2026
2027 static boolean_t
2028 __elfN(parse_notes)(struct image_params *imgp, Elf_Brandnote *checknote,
2029     int32_t *osrel, const Elf_Phdr *pnote)
2030 {
2031         const Elf_Note *note, *note0, *note_end;
2032         const char *note_name;
2033         int i;
2034
2035         if (pnote == NULL || pnote->p_offset > PAGE_SIZE ||
2036             pnote->p_filesz > PAGE_SIZE - pnote->p_offset)
2037                 return (FALSE);
2038
2039         note = note0 = (const Elf_Note *)(imgp->image_header + pnote->p_offset);
2040         note_end = (const Elf_Note *)(imgp->image_header +
2041             pnote->p_offset + pnote->p_filesz);
2042         for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
2043                 if (!aligned(note, Elf32_Addr) || (const char *)note_end -
2044                     (const char *)note < sizeof(Elf_Note))
2045                         return (FALSE);
2046                 if (note->n_namesz != checknote->hdr.n_namesz ||
2047                     note->n_descsz != checknote->hdr.n_descsz ||
2048                     note->n_type != checknote->hdr.n_type)
2049                         goto nextnote;
2050                 note_name = (const char *)(note + 1);
2051                 if (note_name + checknote->hdr.n_namesz >=
2052                     (const char *)note_end || strncmp(checknote->vendor,
2053                     note_name, checknote->hdr.n_namesz) != 0)
2054                         goto nextnote;
2055
2056                 /*
2057                  * Fetch the osreldate for binary
2058                  * from the ELF OSABI-note if necessary.
2059                  */
2060                 if ((checknote->flags & BN_TRANSLATE_OSREL) != 0 &&
2061                     checknote->trans_osrel != NULL)
2062                         return (checknote->trans_osrel(note, osrel));
2063                 return (TRUE);
2064
2065 nextnote:
2066                 note = (const Elf_Note *)((const char *)(note + 1) +
2067                     roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE) +
2068                     roundup2(note->n_descsz, ELF_NOTE_ROUNDSIZE));
2069         }
2070
2071         return (FALSE);
2072 }
2073
2074 /*
2075  * Try to find the appropriate ABI-note section for checknote,
2076  * fetch the osreldate for binary from the ELF OSABI-note. Only the
2077  * first page of the image is searched, the same as for headers.
2078  */
2079 static boolean_t
2080 __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *checknote,
2081     int32_t *osrel)
2082 {
2083         const Elf_Phdr *phdr;
2084         const Elf_Ehdr *hdr;
2085         int i;
2086
2087         hdr = (const Elf_Ehdr *)imgp->image_header;
2088         phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
2089
2090         for (i = 0; i < hdr->e_phnum; i++) {
2091                 if (phdr[i].p_type == PT_NOTE &&
2092                     __elfN(parse_notes)(imgp, checknote, osrel, &phdr[i]))
2093                         return (TRUE);
2094         }
2095         return (FALSE);
2096
2097 }
2098
2099 /*
2100  * Tell kern_execve.c about it, with a little help from the linker.
2101  */
2102 static struct execsw __elfN(execsw) = {
2103         __CONCAT(exec_, __elfN(imgact)),
2104         __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
2105 };
2106 EXEC_SET(__CONCAT(elf, __ELF_WORD_SIZE), __elfN(execsw));
2107
2108 #ifdef COMPRESS_USER_CORES
2109 /*
2110  * Compress and write out a core segment for a user process.
2111  *
2112  * 'inbuf' is the starting address of a VM segment in the process' address
2113  * space that is to be compressed and written out to the core file.  'dest_buf'
2114  * is a buffer in the kernel's address space.  The segment is copied from 
2115  * 'inbuf' to 'dest_buf' first before being processed by the compression
2116  * routine gzwrite().  This copying is necessary because the content of the VM
2117  * segment may change between the compression pass and the crc-computation pass
2118  * in gzwrite().  This is because realtime threads may preempt the UNIX kernel.
2119  *
2120  * If inbuf is NULL it is assumed that data is already copied to 'dest_buf'.
2121  */
2122 static int
2123 compress_core (gzFile file, char *inbuf, char *dest_buf, unsigned int len,
2124     struct thread *td)
2125 {
2126         int len_compressed;
2127         int error = 0;
2128         unsigned int chunk_len;
2129
2130         while (len) {
2131                 if (inbuf != NULL) {
2132                         chunk_len = (len > CORE_BUF_SIZE) ? CORE_BUF_SIZE : len;
2133                         copyin(inbuf, dest_buf, chunk_len);
2134                         inbuf += chunk_len;
2135                 } else {
2136                         chunk_len = len;
2137                 }
2138                 len_compressed = gzwrite(file, dest_buf, chunk_len);
2139
2140                 EVENTHANDLER_INVOKE(app_coredump_progress, td, len_compressed);
2141
2142                 if ((unsigned int)len_compressed != chunk_len) {
2143                         log(LOG_WARNING,
2144                             "compress_core: length mismatch (0x%x returned, "
2145                             "0x%x expected)\n", len_compressed, chunk_len);
2146                         EVENTHANDLER_INVOKE(app_coredump_error, td,
2147                             "compress_core: length mismatch %x -> %x",
2148                             chunk_len, len_compressed);
2149                         error = EFAULT;
2150                         break;
2151                 }
2152                 len -= chunk_len;
2153                 maybe_yield();
2154         }
2155
2156         return (error);
2157 }
2158 #endif /* COMPRESS_USER_CORES */
2159
2160 static vm_prot_t
2161 __elfN(trans_prot)(Elf_Word flags)
2162 {
2163         vm_prot_t prot;
2164
2165         prot = 0;
2166         if (flags & PF_X)
2167                 prot |= VM_PROT_EXECUTE;
2168         if (flags & PF_W)
2169                 prot |= VM_PROT_WRITE;
2170         if (flags & PF_R)
2171                 prot |= VM_PROT_READ;
2172 #if __ELF_WORD_SIZE == 32
2173 #if defined(__amd64__)
2174         if (i386_read_exec && (flags & PF_R))
2175                 prot |= VM_PROT_EXECUTE;
2176 #endif
2177 #endif
2178         return (prot);
2179 }
2180
2181 static Elf_Word
2182 __elfN(untrans_prot)(vm_prot_t prot)
2183 {
2184         Elf_Word flags;
2185
2186         flags = 0;
2187         if (prot & VM_PROT_EXECUTE)
2188                 flags |= PF_X;
2189         if (prot & VM_PROT_READ)
2190                 flags |= PF_R;
2191         if (prot & VM_PROT_WRITE)
2192                 flags |= PF_W;
2193         return (flags);
2194 }