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