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