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