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