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