xref: /freebsd/sys/kern/imgact_elf.c (revision b7c60aadbbd5c846a250c05791fe7406d6d78bf4)
1 /*-
2  * Copyright (c) 2000 David O'Brien
3  * Copyright (c) 1995-1996 Søren Schmidt
4  * Copyright (c) 1996 Peter Wemm
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer
12  *    in this position and unchanged.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include "opt_capsicum.h"
35 #include "opt_compat.h"
36 #include "opt_core.h"
37 
38 #include <sys/param.h>
39 #include <sys/capability.h>
40 #include <sys/exec.h>
41 #include <sys/fcntl.h>
42 #include <sys/imgact.h>
43 #include <sys/imgact_elf.h>
44 #include <sys/kernel.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/mount.h>
48 #include <sys/mutex.h>
49 #include <sys/mman.h>
50 #include <sys/namei.h>
51 #include <sys/pioctl.h>
52 #include <sys/proc.h>
53 #include <sys/procfs.h>
54 #include <sys/racct.h>
55 #include <sys/resourcevar.h>
56 #include <sys/sf_buf.h>
57 #include <sys/smp.h>
58 #include <sys/systm.h>
59 #include <sys/signalvar.h>
60 #include <sys/stat.h>
61 #include <sys/sx.h>
62 #include <sys/syscall.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysent.h>
65 #include <sys/vnode.h>
66 #include <sys/syslog.h>
67 #include <sys/eventhandler.h>
68 
69 #include <net/zlib.h>
70 
71 #include <vm/vm.h>
72 #include <vm/vm_kern.h>
73 #include <vm/vm_param.h>
74 #include <vm/pmap.h>
75 #include <vm/vm_map.h>
76 #include <vm/vm_object.h>
77 #include <vm/vm_extern.h>
78 
79 #include <machine/elf.h>
80 #include <machine/md_var.h>
81 
82 #define OLD_EI_BRAND	8
83 
84 static int __elfN(check_header)(const Elf_Ehdr *hdr);
85 static Elf_Brandinfo *__elfN(get_brandinfo)(struct image_params *imgp,
86     const char *interp, int32_t *osrel);
87 static int __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
88     u_long *entry, size_t pagesize);
89 static int __elfN(load_section)(struct image_params *imgp, vm_offset_t offset,
90     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot,
91     size_t pagesize);
92 static int __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp);
93 static boolean_t __elfN(freebsd_trans_osrel)(const Elf_Note *note,
94     int32_t *osrel);
95 static boolean_t kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel);
96 static boolean_t __elfN(check_note)(struct image_params *imgp,
97     Elf_Brandnote *checknote, int32_t *osrel);
98 static vm_prot_t __elfN(trans_prot)(Elf_Word);
99 static Elf_Word __elfN(untrans_prot)(vm_prot_t);
100 
101 SYSCTL_NODE(_kern, OID_AUTO, __CONCAT(elf, __ELF_WORD_SIZE), CTLFLAG_RW, 0,
102     "");
103 
104 #ifdef COMPRESS_USER_CORES
105 static int compress_core(gzFile, char *, char *, unsigned int,
106     struct thread * td);
107 #define CORE_BUF_SIZE	(16 * 1024)
108 #endif
109 
110 int __elfN(fallback_brand) = -1;
111 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
112     fallback_brand, CTLFLAG_RW, &__elfN(fallback_brand), 0,
113     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) " brand of last resort");
114 TUNABLE_INT("kern.elf" __XSTRING(__ELF_WORD_SIZE) ".fallback_brand",
115     &__elfN(fallback_brand));
116 
117 static int elf_legacy_coredump = 0;
118 SYSCTL_INT(_debug, OID_AUTO, __elfN(legacy_coredump), CTLFLAG_RW,
119     &elf_legacy_coredump, 0, "");
120 
121 int __elfN(nxstack) =
122 #if defined(__amd64__) || defined(__powerpc64__) /* both 64 and 32 bit */
123 	1;
124 #else
125 	0;
126 #endif
127 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
128     nxstack, CTLFLAG_RW, &__elfN(nxstack), 0,
129     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": enable non-executable stack");
130 
131 #if __ELF_WORD_SIZE == 32
132 #if defined(__amd64__) || defined(__ia64__)
133 int i386_read_exec = 0;
134 SYSCTL_INT(_kern_elf32, OID_AUTO, read_exec, CTLFLAG_RW, &i386_read_exec, 0,
135     "enable execution from readable segments");
136 #endif
137 #endif
138 
139 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
140 
141 #define	trunc_page_ps(va, ps)	((va) & ~(ps - 1))
142 #define	round_page_ps(va, ps)	(((va) + (ps - 1)) & ~(ps - 1))
143 #define	aligned(a, t)	(trunc_page_ps((u_long)(a), sizeof(t)) == (u_long)(a))
144 
145 static const char FREEBSD_ABI_VENDOR[] = "FreeBSD";
146 
147 Elf_Brandnote __elfN(freebsd_brandnote) = {
148 	.hdr.n_namesz	= sizeof(FREEBSD_ABI_VENDOR),
149 	.hdr.n_descsz	= sizeof(int32_t),
150 	.hdr.n_type	= 1,
151 	.vendor		= FREEBSD_ABI_VENDOR,
152 	.flags		= BN_TRANSLATE_OSREL,
153 	.trans_osrel	= __elfN(freebsd_trans_osrel)
154 };
155 
156 static boolean_t
157 __elfN(freebsd_trans_osrel)(const Elf_Note *note, int32_t *osrel)
158 {
159 	uintptr_t p;
160 
161 	p = (uintptr_t)(note + 1);
162 	p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
163 	*osrel = *(const int32_t *)(p);
164 
165 	return (TRUE);
166 }
167 
168 static const char GNU_ABI_VENDOR[] = "GNU";
169 static int GNU_KFREEBSD_ABI_DESC = 3;
170 
171 Elf_Brandnote __elfN(kfreebsd_brandnote) = {
172 	.hdr.n_namesz	= sizeof(GNU_ABI_VENDOR),
173 	.hdr.n_descsz	= 16,	/* XXX at least 16 */
174 	.hdr.n_type	= 1,
175 	.vendor		= GNU_ABI_VENDOR,
176 	.flags		= BN_TRANSLATE_OSREL,
177 	.trans_osrel	= kfreebsd_trans_osrel
178 };
179 
180 static boolean_t
181 kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel)
182 {
183 	const Elf32_Word *desc;
184 	uintptr_t p;
185 
186 	p = (uintptr_t)(note + 1);
187 	p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
188 
189 	desc = (const Elf32_Word *)p;
190 	if (desc[0] != GNU_KFREEBSD_ABI_DESC)
191 		return (FALSE);
192 
193 	/*
194 	 * Debian GNU/kFreeBSD embed the earliest compatible kernel version
195 	 * (__FreeBSD_version: <major><two digit minor>Rxx) in the LSB way.
196 	 */
197 	*osrel = desc[1] * 100000 + desc[2] * 1000 + desc[3];
198 
199 	return (TRUE);
200 }
201 
202 int
203 __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
204 {
205 	int i;
206 
207 	for (i = 0; i < MAX_BRANDS; i++) {
208 		if (elf_brand_list[i] == NULL) {
209 			elf_brand_list[i] = entry;
210 			break;
211 		}
212 	}
213 	if (i == MAX_BRANDS) {
214 		printf("WARNING: %s: could not insert brandinfo entry: %p\n",
215 			__func__, entry);
216 		return (-1);
217 	}
218 	return (0);
219 }
220 
221 int
222 __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
223 {
224 	int i;
225 
226 	for (i = 0; i < MAX_BRANDS; i++) {
227 		if (elf_brand_list[i] == entry) {
228 			elf_brand_list[i] = NULL;
229 			break;
230 		}
231 	}
232 	if (i == MAX_BRANDS)
233 		return (-1);
234 	return (0);
235 }
236 
237 int
238 __elfN(brand_inuse)(Elf_Brandinfo *entry)
239 {
240 	struct proc *p;
241 	int rval = FALSE;
242 
243 	sx_slock(&allproc_lock);
244 	FOREACH_PROC_IN_SYSTEM(p) {
245 		if (p->p_sysent == entry->sysvec) {
246 			rval = TRUE;
247 			break;
248 		}
249 	}
250 	sx_sunlock(&allproc_lock);
251 
252 	return (rval);
253 }
254 
255 static Elf_Brandinfo *
256 __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
257     int32_t *osrel)
258 {
259 	const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
260 	Elf_Brandinfo *bi;
261 	boolean_t ret;
262 	int i;
263 
264 	/*
265 	 * We support four types of branding -- (1) the ELF EI_OSABI field
266 	 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
267 	 * branding w/in the ELF header, (3) path of the `interp_path'
268 	 * field, and (4) the ".note.ABI-tag" ELF section.
269 	 */
270 
271 	/* Look for an ".note.ABI-tag" ELF section */
272 	for (i = 0; i < MAX_BRANDS; i++) {
273 		bi = elf_brand_list[i];
274 		if (bi == NULL)
275 			continue;
276 		if (hdr->e_machine == bi->machine && (bi->flags &
277 		    (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
278 			ret = __elfN(check_note)(imgp, bi->brand_note, osrel);
279 			if (ret)
280 				return (bi);
281 		}
282 	}
283 
284 	/* If the executable has a brand, search for it in the brand list. */
285 	for (i = 0; i < MAX_BRANDS; i++) {
286 		bi = elf_brand_list[i];
287 		if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
288 			continue;
289 		if (hdr->e_machine == bi->machine &&
290 		    (hdr->e_ident[EI_OSABI] == bi->brand ||
291 		    strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
292 		    bi->compat_3_brand, strlen(bi->compat_3_brand)) == 0))
293 			return (bi);
294 	}
295 
296 	/* Lacking a known brand, search for a recognized interpreter. */
297 	if (interp != NULL) {
298 		for (i = 0; i < MAX_BRANDS; i++) {
299 			bi = elf_brand_list[i];
300 			if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
301 				continue;
302 			if (hdr->e_machine == bi->machine &&
303 			    strcmp(interp, bi->interp_path) == 0)
304 				return (bi);
305 		}
306 	}
307 
308 	/* Lacking a recognized interpreter, try the default brand */
309 	for (i = 0; i < MAX_BRANDS; i++) {
310 		bi = elf_brand_list[i];
311 		if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
312 			continue;
313 		if (hdr->e_machine == bi->machine &&
314 		    __elfN(fallback_brand) == bi->brand)
315 			return (bi);
316 	}
317 	return (NULL);
318 }
319 
320 static int
321 __elfN(check_header)(const Elf_Ehdr *hdr)
322 {
323 	Elf_Brandinfo *bi;
324 	int i;
325 
326 	if (!IS_ELF(*hdr) ||
327 	    hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
328 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
329 	    hdr->e_ident[EI_VERSION] != EV_CURRENT ||
330 	    hdr->e_phentsize != sizeof(Elf_Phdr) ||
331 	    hdr->e_version != ELF_TARG_VER)
332 		return (ENOEXEC);
333 
334 	/*
335 	 * Make sure we have at least one brand for this machine.
336 	 */
337 
338 	for (i = 0; i < MAX_BRANDS; i++) {
339 		bi = elf_brand_list[i];
340 		if (bi != NULL && bi->machine == hdr->e_machine)
341 			break;
342 	}
343 	if (i == MAX_BRANDS)
344 		return (ENOEXEC);
345 
346 	return (0);
347 }
348 
349 static int
350 __elfN(map_partial)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
351     vm_offset_t start, vm_offset_t end, vm_prot_t prot)
352 {
353 	struct sf_buf *sf;
354 	int error;
355 	vm_offset_t off;
356 
357 	/*
358 	 * Create the page if it doesn't exist yet. Ignore errors.
359 	 */
360 	vm_map_lock(map);
361 	vm_map_insert(map, NULL, 0, trunc_page(start), round_page(end),
362 	    VM_PROT_ALL, VM_PROT_ALL, 0);
363 	vm_map_unlock(map);
364 
365 	/*
366 	 * Find the page from the underlying object.
367 	 */
368 	if (object) {
369 		sf = vm_imgact_map_page(object, offset);
370 		if (sf == NULL)
371 			return (KERN_FAILURE);
372 		off = offset - trunc_page(offset);
373 		error = copyout((caddr_t)sf_buf_kva(sf) + off, (caddr_t)start,
374 		    end - start);
375 		vm_imgact_unmap_page(sf);
376 		if (error) {
377 			return (KERN_FAILURE);
378 		}
379 	}
380 
381 	return (KERN_SUCCESS);
382 }
383 
384 static int
385 __elfN(map_insert)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
386     vm_offset_t start, vm_offset_t end, vm_prot_t prot, int cow)
387 {
388 	struct sf_buf *sf;
389 	vm_offset_t off;
390 	vm_size_t sz;
391 	int error, rv;
392 
393 	if (start != trunc_page(start)) {
394 		rv = __elfN(map_partial)(map, object, offset, start,
395 		    round_page(start), prot);
396 		if (rv)
397 			return (rv);
398 		offset += round_page(start) - start;
399 		start = round_page(start);
400 	}
401 	if (end != round_page(end)) {
402 		rv = __elfN(map_partial)(map, object, offset +
403 		    trunc_page(end) - start, trunc_page(end), end, prot);
404 		if (rv)
405 			return (rv);
406 		end = trunc_page(end);
407 	}
408 	if (end > start) {
409 		if (offset & PAGE_MASK) {
410 			/*
411 			 * The mapping is not page aligned. This means we have
412 			 * to copy the data. Sigh.
413 			 */
414 			rv = vm_map_find(map, NULL, 0, &start, end - start,
415 			    FALSE, prot | VM_PROT_WRITE, VM_PROT_ALL, 0);
416 			if (rv)
417 				return (rv);
418 			if (object == NULL)
419 				return (KERN_SUCCESS);
420 			for (; start < end; start += sz) {
421 				sf = vm_imgact_map_page(object, offset);
422 				if (sf == NULL)
423 					return (KERN_FAILURE);
424 				off = offset - trunc_page(offset);
425 				sz = end - start;
426 				if (sz > PAGE_SIZE - off)
427 					sz = PAGE_SIZE - off;
428 				error = copyout((caddr_t)sf_buf_kva(sf) + off,
429 				    (caddr_t)start, sz);
430 				vm_imgact_unmap_page(sf);
431 				if (error) {
432 					return (KERN_FAILURE);
433 				}
434 				offset += sz;
435 			}
436 			rv = KERN_SUCCESS;
437 		} else {
438 			vm_object_reference(object);
439 			vm_map_lock(map);
440 			rv = vm_map_insert(map, object, offset, start, end,
441 			    prot, VM_PROT_ALL, cow);
442 			vm_map_unlock(map);
443 			if (rv != KERN_SUCCESS)
444 				vm_object_deallocate(object);
445 		}
446 		return (rv);
447 	} else {
448 		return (KERN_SUCCESS);
449 	}
450 }
451 
452 static int
453 __elfN(load_section)(struct image_params *imgp, vm_offset_t offset,
454     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot,
455     size_t pagesize)
456 {
457 	struct sf_buf *sf;
458 	size_t map_len;
459 	vm_map_t map;
460 	vm_object_t object;
461 	vm_offset_t map_addr;
462 	int error, rv, cow;
463 	size_t copy_len;
464 	vm_offset_t file_addr;
465 
466 	/*
467 	 * It's necessary to fail if the filsz + offset taken from the
468 	 * header is greater than the actual file pager object's size.
469 	 * If we were to allow this, then the vm_map_find() below would
470 	 * walk right off the end of the file object and into the ether.
471 	 *
472 	 * While I'm here, might as well check for something else that
473 	 * is invalid: filsz cannot be greater than memsz.
474 	 */
475 	if ((off_t)filsz + offset > imgp->attr->va_size || filsz > memsz) {
476 		uprintf("elf_load_section: truncated ELF file\n");
477 		return (ENOEXEC);
478 	}
479 
480 	object = imgp->object;
481 	map = &imgp->proc->p_vmspace->vm_map;
482 	map_addr = trunc_page_ps((vm_offset_t)vmaddr, pagesize);
483 	file_addr = trunc_page_ps(offset, pagesize);
484 
485 	/*
486 	 * We have two choices.  We can either clear the data in the last page
487 	 * of an oversized mapping, or we can start the anon mapping a page
488 	 * early and copy the initialized data into that first page.  We
489 	 * choose the second..
490 	 */
491 	if (memsz > filsz)
492 		map_len = trunc_page_ps(offset + filsz, pagesize) - file_addr;
493 	else
494 		map_len = round_page_ps(offset + filsz, pagesize) - file_addr;
495 
496 	if (map_len != 0) {
497 		/* cow flags: don't dump readonly sections in core */
498 		cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
499 		    (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
500 
501 		rv = __elfN(map_insert)(map,
502 				      object,
503 				      file_addr,	/* file offset */
504 				      map_addr,		/* virtual start */
505 				      map_addr + map_len,/* virtual end */
506 				      prot,
507 				      cow);
508 		if (rv != KERN_SUCCESS)
509 			return (EINVAL);
510 
511 		/* we can stop now if we've covered it all */
512 		if (memsz == filsz) {
513 			return (0);
514 		}
515 	}
516 
517 
518 	/*
519 	 * We have to get the remaining bit of the file into the first part
520 	 * of the oversized map segment.  This is normally because the .data
521 	 * segment in the file is extended to provide bss.  It's a neat idea
522 	 * to try and save a page, but it's a pain in the behind to implement.
523 	 */
524 	copy_len = (offset + filsz) - trunc_page_ps(offset + filsz, pagesize);
525 	map_addr = trunc_page_ps((vm_offset_t)vmaddr + filsz, pagesize);
526 	map_len = round_page_ps((vm_offset_t)vmaddr + memsz, pagesize) -
527 	    map_addr;
528 
529 	/* This had damn well better be true! */
530 	if (map_len != 0) {
531 		rv = __elfN(map_insert)(map, NULL, 0, map_addr, map_addr +
532 		    map_len, VM_PROT_ALL, 0);
533 		if (rv != KERN_SUCCESS) {
534 			return (EINVAL);
535 		}
536 	}
537 
538 	if (copy_len != 0) {
539 		vm_offset_t off;
540 
541 		sf = vm_imgact_map_page(object, offset + filsz);
542 		if (sf == NULL)
543 			return (EIO);
544 
545 		/* send the page fragment to user space */
546 		off = trunc_page_ps(offset + filsz, pagesize) -
547 		    trunc_page(offset + filsz);
548 		error = copyout((caddr_t)sf_buf_kva(sf) + off,
549 		    (caddr_t)map_addr, copy_len);
550 		vm_imgact_unmap_page(sf);
551 		if (error) {
552 			return (error);
553 		}
554 	}
555 
556 	/*
557 	 * set it to the specified protection.
558 	 * XXX had better undo the damage from pasting over the cracks here!
559 	 */
560 	vm_map_protect(map, trunc_page(map_addr), round_page(map_addr +
561 	    map_len), prot, FALSE);
562 
563 	return (0);
564 }
565 
566 /*
567  * Load the file "file" into memory.  It may be either a shared object
568  * or an executable.
569  *
570  * The "addr" reference parameter is in/out.  On entry, it specifies
571  * the address where a shared object should be loaded.  If the file is
572  * an executable, this value is ignored.  On exit, "addr" specifies
573  * where the file was actually loaded.
574  *
575  * The "entry" reference parameter is out only.  On exit, it specifies
576  * the entry point for the loaded file.
577  */
578 static int
579 __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
580 	u_long *entry, size_t pagesize)
581 {
582 	struct {
583 		struct nameidata nd;
584 		struct vattr attr;
585 		struct image_params image_params;
586 	} *tempdata;
587 	const Elf_Ehdr *hdr = NULL;
588 	const Elf_Phdr *phdr = NULL;
589 	struct nameidata *nd;
590 	struct vattr *attr;
591 	struct image_params *imgp;
592 	vm_prot_t prot;
593 	u_long rbase;
594 	u_long base_addr = 0;
595 	int vfslocked, error, i, numsegs;
596 
597 #ifdef CAPABILITY_MODE
598 	/*
599 	 * XXXJA: This check can go away once we are sufficiently confident
600 	 * that the checks in namei() are correct.
601 	 */
602 	if (IN_CAPABILITY_MODE(curthread))
603 		return (ECAPMODE);
604 #endif
605 
606 	tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
607 	nd = &tempdata->nd;
608 	attr = &tempdata->attr;
609 	imgp = &tempdata->image_params;
610 
611 	/*
612 	 * Initialize part of the common data
613 	 */
614 	imgp->proc = p;
615 	imgp->attr = attr;
616 	imgp->firstpage = NULL;
617 	imgp->image_header = NULL;
618 	imgp->object = NULL;
619 	imgp->execlabel = NULL;
620 
621 	NDINIT(nd, LOOKUP, MPSAFE|LOCKLEAF|FOLLOW, UIO_SYSSPACE, file,
622 	    curthread);
623 	vfslocked = 0;
624 	if ((error = namei(nd)) != 0) {
625 		nd->ni_vp = NULL;
626 		goto fail;
627 	}
628 	vfslocked = NDHASGIANT(nd);
629 	NDFREE(nd, NDF_ONLY_PNBUF);
630 	imgp->vp = nd->ni_vp;
631 
632 	/*
633 	 * Check permissions, modes, uid, etc on the file, and "open" it.
634 	 */
635 	error = exec_check_permissions(imgp);
636 	if (error)
637 		goto fail;
638 
639 	error = exec_map_first_page(imgp);
640 	if (error)
641 		goto fail;
642 
643 	/*
644 	 * Also make certain that the interpreter stays the same, so set
645 	 * its VV_TEXT flag, too.
646 	 */
647 	nd->ni_vp->v_vflag |= VV_TEXT;
648 
649 	imgp->object = nd->ni_vp->v_object;
650 
651 	hdr = (const Elf_Ehdr *)imgp->image_header;
652 	if ((error = __elfN(check_header)(hdr)) != 0)
653 		goto fail;
654 	if (hdr->e_type == ET_DYN)
655 		rbase = *addr;
656 	else if (hdr->e_type == ET_EXEC)
657 		rbase = 0;
658 	else {
659 		error = ENOEXEC;
660 		goto fail;
661 	}
662 
663 	/* Only support headers that fit within first page for now      */
664 	/*    (multiplication of two Elf_Half fields will not overflow) */
665 	if ((hdr->e_phoff > PAGE_SIZE) ||
666 	    (hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE - hdr->e_phoff) {
667 		error = ENOEXEC;
668 		goto fail;
669 	}
670 
671 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
672 	if (!aligned(phdr, Elf_Addr)) {
673 		error = ENOEXEC;
674 		goto fail;
675 	}
676 
677 	for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
678 		if (phdr[i].p_type == PT_LOAD && phdr[i].p_memsz != 0) {
679 			/* Loadable segment */
680 			prot = __elfN(trans_prot)(phdr[i].p_flags);
681 			error = __elfN(load_section)(imgp, phdr[i].p_offset,
682 			    (caddr_t)(uintptr_t)phdr[i].p_vaddr + rbase,
683 			    phdr[i].p_memsz, phdr[i].p_filesz, prot, pagesize);
684 			if (error != 0)
685 				goto fail;
686 			/*
687 			 * Establish the base address if this is the
688 			 * first segment.
689 			 */
690 			if (numsegs == 0)
691   				base_addr = trunc_page(phdr[i].p_vaddr +
692 				    rbase);
693 			numsegs++;
694 		}
695 	}
696 	*addr = base_addr;
697 	*entry = (unsigned long)hdr->e_entry + rbase;
698 
699 fail:
700 	if (imgp->firstpage)
701 		exec_unmap_first_page(imgp);
702 
703 	if (nd->ni_vp)
704 		vput(nd->ni_vp);
705 
706 	VFS_UNLOCK_GIANT(vfslocked);
707 	free(tempdata, M_TEMP);
708 
709 	return (error);
710 }
711 
712 static int
713 __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp)
714 {
715 	const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
716 	const Elf_Phdr *phdr;
717 	Elf_Auxargs *elf_auxargs;
718 	struct vmspace *vmspace;
719 	vm_prot_t prot;
720 	u_long text_size = 0, data_size = 0, total_size = 0;
721 	u_long text_addr = 0, data_addr = 0;
722 	u_long seg_size, seg_addr;
723 	u_long addr, baddr, et_dyn_addr, entry = 0, proghdr = 0;
724 	int32_t osrel = 0;
725 	int error = 0, i, n;
726 	const char *interp = NULL, *newinterp = NULL;
727 	Elf_Brandinfo *brand_info;
728 	char *path;
729 	struct sysentvec *sv;
730 
731 	/*
732 	 * Do we have a valid ELF header ?
733 	 *
734 	 * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later
735 	 * if particular brand doesn't support it.
736 	 */
737 	if (__elfN(check_header)(hdr) != 0 ||
738 	    (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
739 		return (-1);
740 
741 	/*
742 	 * From here on down, we return an errno, not -1, as we've
743 	 * detected an ELF file.
744 	 */
745 
746 	if ((hdr->e_phoff > PAGE_SIZE) ||
747 	    (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
748 		/* Only support headers in first page for now */
749 		return (ENOEXEC);
750 	}
751 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
752 	if (!aligned(phdr, Elf_Addr))
753 		return (ENOEXEC);
754 	n = 0;
755 	baddr = 0;
756 	for (i = 0; i < hdr->e_phnum; i++) {
757 		switch (phdr[i].p_type) {
758 		case PT_LOAD:
759 			if (n == 0)
760 				baddr = phdr[i].p_vaddr;
761 			n++;
762 			break;
763 		case PT_INTERP:
764 			/* Path to interpreter */
765 			if (phdr[i].p_filesz > MAXPATHLEN ||
766 			    phdr[i].p_offset + phdr[i].p_filesz > PAGE_SIZE)
767 				return (ENOEXEC);
768 			interp = imgp->image_header + phdr[i].p_offset;
769 			break;
770 		case PT_GNU_STACK:
771 			if (__elfN(nxstack))
772 				imgp->stack_prot =
773 				    __elfN(trans_prot)(phdr[i].p_flags);
774 			break;
775 		}
776 	}
777 
778 	brand_info = __elfN(get_brandinfo)(imgp, interp, &osrel);
779 	if (brand_info == NULL) {
780 		uprintf("ELF binary type \"%u\" not known.\n",
781 		    hdr->e_ident[EI_OSABI]);
782 		return (ENOEXEC);
783 	}
784 	if (hdr->e_type == ET_DYN) {
785 		if ((brand_info->flags & BI_CAN_EXEC_DYN) == 0)
786 			return (ENOEXEC);
787 		/*
788 		 * Honour the base load address from the dso if it is
789 		 * non-zero for some reason.
790 		 */
791 		if (baddr == 0)
792 			et_dyn_addr = ET_DYN_LOAD_ADDR;
793 		else
794 			et_dyn_addr = 0;
795 	} else
796 		et_dyn_addr = 0;
797 	sv = brand_info->sysvec;
798 	if (interp != NULL && brand_info->interp_newpath != NULL)
799 		newinterp = brand_info->interp_newpath;
800 
801 	/*
802 	 * Avoid a possible deadlock if the current address space is destroyed
803 	 * and that address space maps the locked vnode.  In the common case,
804 	 * the locked vnode's v_usecount is decremented but remains greater
805 	 * than zero.  Consequently, the vnode lock is not needed by vrele().
806 	 * However, in cases where the vnode lock is external, such as nullfs,
807 	 * v_usecount may become zero.
808 	 *
809 	 * The VV_TEXT flag prevents modifications to the executable while
810 	 * the vnode is unlocked.
811 	 */
812 	VOP_UNLOCK(imgp->vp, 0);
813 
814 	error = exec_new_vmspace(imgp, sv);
815 	imgp->proc->p_sysent = sv;
816 
817 	vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
818 	if (error)
819 		return (error);
820 
821 	for (i = 0; i < hdr->e_phnum; i++) {
822 		switch (phdr[i].p_type) {
823 		case PT_LOAD:	/* Loadable segment */
824 			if (phdr[i].p_memsz == 0)
825 				break;
826 			prot = __elfN(trans_prot)(phdr[i].p_flags);
827 
828 #if defined(__ia64__) && __ELF_WORD_SIZE == 32 && defined(IA32_ME_HARDER)
829 			/*
830 			 * Some x86 binaries assume read == executable,
831 			 * notably the M3 runtime and therefore cvsup
832 			 */
833 			if (prot & VM_PROT_READ)
834 				prot |= VM_PROT_EXECUTE;
835 #endif
836 
837 			error = __elfN(load_section)(imgp, phdr[i].p_offset,
838 			    (caddr_t)(uintptr_t)phdr[i].p_vaddr + et_dyn_addr,
839 			    phdr[i].p_memsz, phdr[i].p_filesz, prot,
840 			    sv->sv_pagesize);
841 			if (error != 0)
842 				return (error);
843 
844 			/*
845 			 * If this segment contains the program headers,
846 			 * remember their virtual address for the AT_PHDR
847 			 * aux entry. Static binaries don't usually include
848 			 * a PT_PHDR entry.
849 			 */
850 			if (phdr[i].p_offset == 0 &&
851 			    hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
852 				<= phdr[i].p_filesz)
853 				proghdr = phdr[i].p_vaddr + hdr->e_phoff +
854 				    et_dyn_addr;
855 
856 			seg_addr = trunc_page(phdr[i].p_vaddr + et_dyn_addr);
857 			seg_size = round_page(phdr[i].p_memsz +
858 			    phdr[i].p_vaddr + et_dyn_addr - seg_addr);
859 
860 			/*
861 			 * Make the largest executable segment the official
862 			 * text segment and all others data.
863 			 *
864 			 * Note that obreak() assumes that data_addr +
865 			 * data_size == end of data load area, and the ELF
866 			 * file format expects segments to be sorted by
867 			 * address.  If multiple data segments exist, the
868 			 * last one will be used.
869 			 */
870 
871 			if (phdr[i].p_flags & PF_X && text_size < seg_size) {
872 				text_size = seg_size;
873 				text_addr = seg_addr;
874 			} else {
875 				data_size = seg_size;
876 				data_addr = seg_addr;
877 			}
878 			total_size += seg_size;
879 			break;
880 		case PT_PHDR: 	/* Program header table info */
881 			proghdr = phdr[i].p_vaddr + et_dyn_addr;
882 			break;
883 		default:
884 			break;
885 		}
886 	}
887 
888 	if (data_addr == 0 && data_size == 0) {
889 		data_addr = text_addr;
890 		data_size = text_size;
891 	}
892 
893 	entry = (u_long)hdr->e_entry + et_dyn_addr;
894 
895 	/*
896 	 * Check limits.  It should be safe to check the
897 	 * limits after loading the segments since we do
898 	 * not actually fault in all the segments pages.
899 	 */
900 	PROC_LOCK(imgp->proc);
901 	if (data_size > lim_cur(imgp->proc, RLIMIT_DATA) ||
902 	    text_size > maxtsiz ||
903 	    total_size > lim_cur(imgp->proc, RLIMIT_VMEM) ||
904 	    racct_set(imgp->proc, RACCT_DATA, data_size) != 0 ||
905 	    racct_set(imgp->proc, RACCT_VMEM, total_size) != 0) {
906 		PROC_UNLOCK(imgp->proc);
907 		return (ENOMEM);
908 	}
909 
910 	vmspace = imgp->proc->p_vmspace;
911 	vmspace->vm_tsize = text_size >> PAGE_SHIFT;
912 	vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
913 	vmspace->vm_dsize = data_size >> PAGE_SHIFT;
914 	vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
915 
916 	/*
917 	 * We load the dynamic linker where a userland call
918 	 * to mmap(0, ...) would put it.  The rationale behind this
919 	 * calculation is that it leaves room for the heap to grow to
920 	 * its maximum allowed size.
921 	 */
922 	addr = round_page((vm_offset_t)vmspace->vm_daddr + lim_max(imgp->proc,
923 	    RLIMIT_DATA));
924 	PROC_UNLOCK(imgp->proc);
925 
926 	imgp->entry_addr = entry;
927 
928 	if (interp != NULL) {
929 		int have_interp = FALSE;
930 		VOP_UNLOCK(imgp->vp, 0);
931 		if (brand_info->emul_path != NULL &&
932 		    brand_info->emul_path[0] != '\0') {
933 			path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
934 			snprintf(path, MAXPATHLEN, "%s%s",
935 			    brand_info->emul_path, interp);
936 			error = __elfN(load_file)(imgp->proc, path, &addr,
937 			    &imgp->entry_addr, sv->sv_pagesize);
938 			free(path, M_TEMP);
939 			if (error == 0)
940 				have_interp = TRUE;
941 		}
942 		if (!have_interp && newinterp != NULL) {
943 			error = __elfN(load_file)(imgp->proc, newinterp, &addr,
944 			    &imgp->entry_addr, sv->sv_pagesize);
945 			if (error == 0)
946 				have_interp = TRUE;
947 		}
948 		if (!have_interp) {
949 			error = __elfN(load_file)(imgp->proc, interp, &addr,
950 			    &imgp->entry_addr, sv->sv_pagesize);
951 		}
952 		vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
953 		if (error != 0) {
954 			uprintf("ELF interpreter %s not found\n", interp);
955 			return (error);
956 		}
957 	} else
958 		addr = et_dyn_addr;
959 
960 	/*
961 	 * Construct auxargs table (used by the fixup routine)
962 	 */
963 	elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
964 	elf_auxargs->execfd = -1;
965 	elf_auxargs->phdr = proghdr;
966 	elf_auxargs->phent = hdr->e_phentsize;
967 	elf_auxargs->phnum = hdr->e_phnum;
968 	elf_auxargs->pagesz = PAGE_SIZE;
969 	elf_auxargs->base = addr;
970 	elf_auxargs->flags = 0;
971 	elf_auxargs->entry = entry;
972 
973 	imgp->auxargs = elf_auxargs;
974 	imgp->interpreted = 0;
975 	imgp->reloc_base = addr;
976 	imgp->proc->p_osrel = osrel;
977 
978 	return (error);
979 }
980 
981 #define	suword __CONCAT(suword, __ELF_WORD_SIZE)
982 
983 int
984 __elfN(freebsd_fixup)(register_t **stack_base, struct image_params *imgp)
985 {
986 	Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
987 	Elf_Addr *base;
988 	Elf_Addr *pos;
989 
990 	base = (Elf_Addr *)*stack_base;
991 	pos = base + (imgp->args->argc + imgp->args->envc + 2);
992 
993 	if (args->execfd != -1)
994 		AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
995 	AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
996 	AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
997 	AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
998 	AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
999 	AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
1000 	AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
1001 	AUXARGS_ENTRY(pos, AT_BASE, args->base);
1002 	if (imgp->execpathp != 0)
1003 		AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp);
1004 	AUXARGS_ENTRY(pos, AT_OSRELDATE, osreldate);
1005 	if (imgp->canary != 0) {
1006 		AUXARGS_ENTRY(pos, AT_CANARY, imgp->canary);
1007 		AUXARGS_ENTRY(pos, AT_CANARYLEN, imgp->canarylen);
1008 	}
1009 	AUXARGS_ENTRY(pos, AT_NCPUS, mp_ncpus);
1010 	if (imgp->pagesizes != 0) {
1011 		AUXARGS_ENTRY(pos, AT_PAGESIZES, imgp->pagesizes);
1012 		AUXARGS_ENTRY(pos, AT_PAGESIZESLEN, imgp->pagesizeslen);
1013 	}
1014 	AUXARGS_ENTRY(pos, AT_STACKPROT, imgp->sysent->sv_shared_page_obj
1015 	    != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1016 	    imgp->sysent->sv_stackprot);
1017 	AUXARGS_ENTRY(pos, AT_NULL, 0);
1018 
1019 	free(imgp->auxargs, M_TEMP);
1020 	imgp->auxargs = NULL;
1021 
1022 	base--;
1023 	suword(base, (long)imgp->args->argc);
1024 	*stack_base = (register_t *)base;
1025 	return (0);
1026 }
1027 
1028 /*
1029  * Code for generating ELF core dumps.
1030  */
1031 
1032 typedef void (*segment_callback)(vm_map_entry_t, void *);
1033 
1034 /* Closure for cb_put_phdr(). */
1035 struct phdr_closure {
1036 	Elf_Phdr *phdr;		/* Program header to fill in */
1037 	Elf_Off offset;		/* Offset of segment in core file */
1038 };
1039 
1040 /* Closure for cb_size_segment(). */
1041 struct sseg_closure {
1042 	int count;		/* Count of writable segments. */
1043 	size_t size;		/* Total size of all writable segments. */
1044 };
1045 
1046 static void cb_put_phdr(vm_map_entry_t, void *);
1047 static void cb_size_segment(vm_map_entry_t, void *);
1048 static void each_writable_segment(struct thread *, segment_callback, void *);
1049 static int __elfN(corehdr)(struct thread *, struct vnode *, struct ucred *,
1050     int, void *, size_t, gzFile);
1051 static void __elfN(puthdr)(struct thread *, void *, size_t *, int);
1052 static void __elfN(putnote)(void *, size_t *, const char *, int,
1053     const void *, size_t);
1054 
1055 #ifdef COMPRESS_USER_CORES
1056 extern int compress_user_cores;
1057 extern int compress_user_cores_gzlevel;
1058 #endif
1059 
1060 static int
1061 core_output(struct vnode *vp, void *base, size_t len, off_t offset,
1062     struct ucred *active_cred, struct ucred *file_cred,
1063     struct thread *td, char *core_buf, gzFile gzfile) {
1064 
1065 	int error;
1066 	if (gzfile) {
1067 #ifdef COMPRESS_USER_CORES
1068 		error = compress_core(gzfile, base, core_buf, len, td);
1069 #else
1070 		panic("shouldn't be here");
1071 #endif
1072 	} else {
1073 		error = vn_rdwr_inchunks(UIO_WRITE, vp, base, len, offset,
1074 		    UIO_USERSPACE, IO_UNIT | IO_DIRECT, active_cred, file_cred,
1075 		    NULL, td);
1076 	}
1077 	return (error);
1078 }
1079 
1080 int
1081 __elfN(coredump)(struct thread *td, struct vnode *vp, off_t limit, int flags)
1082 {
1083 	struct ucred *cred = td->td_ucred;
1084 	int error = 0;
1085 	struct sseg_closure seginfo;
1086 	void *hdr;
1087 	size_t hdrsize;
1088 
1089 	gzFile gzfile = Z_NULL;
1090 	char *core_buf = NULL;
1091 #ifdef COMPRESS_USER_CORES
1092 	char gzopen_flags[8];
1093 	char *p;
1094 	int doing_compress = flags & IMGACT_CORE_COMPRESS;
1095 #endif
1096 
1097 	hdr = NULL;
1098 
1099 #ifdef COMPRESS_USER_CORES
1100         if (doing_compress) {
1101                 p = gzopen_flags;
1102                 *p++ = 'w';
1103                 if (compress_user_cores_gzlevel >= 0 &&
1104                     compress_user_cores_gzlevel <= 9)
1105                         *p++ = '0' + compress_user_cores_gzlevel;
1106                 *p = 0;
1107                 gzfile = gz_open("", gzopen_flags, vp);
1108                 if (gzfile == Z_NULL) {
1109                         error = EFAULT;
1110                         goto done;
1111                 }
1112                 core_buf = malloc(CORE_BUF_SIZE, M_TEMP, M_WAITOK | M_ZERO);
1113                 if (!core_buf) {
1114                         error = ENOMEM;
1115                         goto done;
1116                 }
1117         }
1118 #endif
1119 
1120 	/* Size the program segments. */
1121 	seginfo.count = 0;
1122 	seginfo.size = 0;
1123 	each_writable_segment(td, cb_size_segment, &seginfo);
1124 
1125 	/*
1126 	 * Calculate the size of the core file header area by making
1127 	 * a dry run of generating it.  Nothing is written, but the
1128 	 * size is calculated.
1129 	 */
1130 	hdrsize = 0;
1131 	__elfN(puthdr)(td, (void *)NULL, &hdrsize, seginfo.count);
1132 
1133 #ifdef RACCT
1134 	PROC_LOCK(td->td_proc);
1135 	error = racct_add(td->td_proc, RACCT_CORE, hdrsize + seginfo.size);
1136 	PROC_UNLOCK(td->td_proc);
1137 	if (error != 0) {
1138 		error = EFAULT;
1139 		goto done;
1140 	}
1141 #endif
1142 	if (hdrsize + seginfo.size >= limit) {
1143 		error = EFAULT;
1144 		goto done;
1145 	}
1146 
1147 	/*
1148 	 * Allocate memory for building the header, fill it up,
1149 	 * and write it out.
1150 	 */
1151 	hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
1152 	if (hdr == NULL) {
1153 		error = EINVAL;
1154 		goto done;
1155 	}
1156 	error = __elfN(corehdr)(td, vp, cred, seginfo.count, hdr, hdrsize,
1157 	    gzfile);
1158 
1159 	/* Write the contents of all of the writable segments. */
1160 	if (error == 0) {
1161 		Elf_Phdr *php;
1162 		off_t offset;
1163 		int i;
1164 
1165 		php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
1166 		offset = hdrsize;
1167 		for (i = 0; i < seginfo.count; i++) {
1168 			error = core_output(vp, (caddr_t)(uintptr_t)php->p_vaddr,
1169 			    php->p_filesz, offset, cred, NOCRED, curthread, core_buf, gzfile);
1170 			if (error != 0)
1171 				break;
1172 			offset += php->p_filesz;
1173 			php++;
1174 		}
1175 	}
1176 	if (error) {
1177 		log(LOG_WARNING,
1178 		    "Failed to write core file for process %s (error %d)\n",
1179 		    curproc->p_comm, error);
1180 	}
1181 
1182 done:
1183 #ifdef COMPRESS_USER_CORES
1184 	if (core_buf)
1185 		free(core_buf, M_TEMP);
1186 	if (gzfile)
1187 		gzclose(gzfile);
1188 #endif
1189 
1190 	free(hdr, M_TEMP);
1191 
1192 	return (error);
1193 }
1194 
1195 /*
1196  * A callback for each_writable_segment() to write out the segment's
1197  * program header entry.
1198  */
1199 static void
1200 cb_put_phdr(entry, closure)
1201 	vm_map_entry_t entry;
1202 	void *closure;
1203 {
1204 	struct phdr_closure *phc = (struct phdr_closure *)closure;
1205 	Elf_Phdr *phdr = phc->phdr;
1206 
1207 	phc->offset = round_page(phc->offset);
1208 
1209 	phdr->p_type = PT_LOAD;
1210 	phdr->p_offset = phc->offset;
1211 	phdr->p_vaddr = entry->start;
1212 	phdr->p_paddr = 0;
1213 	phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1214 	phdr->p_align = PAGE_SIZE;
1215 	phdr->p_flags = __elfN(untrans_prot)(entry->protection);
1216 
1217 	phc->offset += phdr->p_filesz;
1218 	phc->phdr++;
1219 }
1220 
1221 /*
1222  * A callback for each_writable_segment() to gather information about
1223  * the number of segments and their total size.
1224  */
1225 static void
1226 cb_size_segment(entry, closure)
1227 	vm_map_entry_t entry;
1228 	void *closure;
1229 {
1230 	struct sseg_closure *ssc = (struct sseg_closure *)closure;
1231 
1232 	ssc->count++;
1233 	ssc->size += entry->end - entry->start;
1234 }
1235 
1236 /*
1237  * For each writable segment in the process's memory map, call the given
1238  * function with a pointer to the map entry and some arbitrary
1239  * caller-supplied data.
1240  */
1241 static void
1242 each_writable_segment(td, func, closure)
1243 	struct thread *td;
1244 	segment_callback func;
1245 	void *closure;
1246 {
1247 	struct proc *p = td->td_proc;
1248 	vm_map_t map = &p->p_vmspace->vm_map;
1249 	vm_map_entry_t entry;
1250 	vm_object_t backing_object, object;
1251 	boolean_t ignore_entry;
1252 
1253 	vm_map_lock_read(map);
1254 	for (entry = map->header.next; entry != &map->header;
1255 	    entry = entry->next) {
1256 		/*
1257 		 * Don't dump inaccessible mappings, deal with legacy
1258 		 * coredump mode.
1259 		 *
1260 		 * Note that read-only segments related to the elf binary
1261 		 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1262 		 * need to arbitrarily ignore such segments.
1263 		 */
1264 		if (elf_legacy_coredump) {
1265 			if ((entry->protection & VM_PROT_RW) != VM_PROT_RW)
1266 				continue;
1267 		} else {
1268 			if ((entry->protection & VM_PROT_ALL) == 0)
1269 				continue;
1270 		}
1271 
1272 		/*
1273 		 * Dont include memory segment in the coredump if
1274 		 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1275 		 * madvise(2).  Do not dump submaps (i.e. parts of the
1276 		 * kernel map).
1277 		 */
1278 		if (entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
1279 			continue;
1280 
1281 		if ((object = entry->object.vm_object) == NULL)
1282 			continue;
1283 
1284 		/* Ignore memory-mapped devices and such things. */
1285 		VM_OBJECT_LOCK(object);
1286 		while ((backing_object = object->backing_object) != NULL) {
1287 			VM_OBJECT_LOCK(backing_object);
1288 			VM_OBJECT_UNLOCK(object);
1289 			object = backing_object;
1290 		}
1291 		ignore_entry = object->type != OBJT_DEFAULT &&
1292 		    object->type != OBJT_SWAP && object->type != OBJT_VNODE;
1293 		VM_OBJECT_UNLOCK(object);
1294 		if (ignore_entry)
1295 			continue;
1296 
1297 		(*func)(entry, closure);
1298 	}
1299 	vm_map_unlock_read(map);
1300 }
1301 
1302 /*
1303  * Write the core file header to the file, including padding up to
1304  * the page boundary.
1305  */
1306 static int
1307 __elfN(corehdr)(td, vp, cred, numsegs, hdr, hdrsize, gzfile)
1308 	struct thread *td;
1309 	struct vnode *vp;
1310 	struct ucred *cred;
1311 	int numsegs;
1312 	size_t hdrsize;
1313 	void *hdr;
1314 	gzFile gzfile;
1315 {
1316 	size_t off;
1317 
1318 	/* Fill in the header. */
1319 	bzero(hdr, hdrsize);
1320 	off = 0;
1321 	__elfN(puthdr)(td, hdr, &off, numsegs);
1322 
1323 	if (!gzfile) {
1324 		/* Write it to the core file. */
1325 		return (vn_rdwr_inchunks(UIO_WRITE, vp, hdr, hdrsize, (off_t)0,
1326 			UIO_SYSSPACE, IO_UNIT | IO_DIRECT, cred, NOCRED, NULL,
1327 			td));
1328 	} else {
1329 #ifdef COMPRESS_USER_CORES
1330 		if (gzwrite(gzfile, hdr, hdrsize) != hdrsize) {
1331 			log(LOG_WARNING,
1332 			    "Failed to compress core file header for process"
1333 			    " %s.\n", curproc->p_comm);
1334 			return (EFAULT);
1335 		}
1336 		else {
1337 			return (0);
1338 		}
1339 #else
1340 		panic("shouldn't be here");
1341 #endif
1342 	}
1343 }
1344 
1345 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1346 #include <compat/freebsd32/freebsd32.h>
1347 
1348 typedef struct prstatus32 elf_prstatus_t;
1349 typedef struct prpsinfo32 elf_prpsinfo_t;
1350 typedef struct fpreg32 elf_prfpregset_t;
1351 typedef struct fpreg32 elf_fpregset_t;
1352 typedef struct reg32 elf_gregset_t;
1353 typedef struct thrmisc32 elf_thrmisc_t;
1354 #else
1355 typedef prstatus_t elf_prstatus_t;
1356 typedef prpsinfo_t elf_prpsinfo_t;
1357 typedef prfpregset_t elf_prfpregset_t;
1358 typedef prfpregset_t elf_fpregset_t;
1359 typedef gregset_t elf_gregset_t;
1360 typedef thrmisc_t elf_thrmisc_t;
1361 #endif
1362 
1363 static void
1364 __elfN(puthdr)(struct thread *td, void *dst, size_t *off, int numsegs)
1365 {
1366 	struct {
1367 		elf_prstatus_t status;
1368 		elf_prfpregset_t fpregset;
1369 		elf_prpsinfo_t psinfo;
1370 		elf_thrmisc_t thrmisc;
1371 	} *tempdata;
1372 	elf_prstatus_t *status;
1373 	elf_prfpregset_t *fpregset;
1374 	elf_prpsinfo_t *psinfo;
1375 	elf_thrmisc_t *thrmisc;
1376 	struct proc *p;
1377 	struct thread *thr;
1378 	size_t ehoff, noteoff, notesz, phoff;
1379 
1380 	p = td->td_proc;
1381 
1382 	ehoff = *off;
1383 	*off += sizeof(Elf_Ehdr);
1384 
1385 	phoff = *off;
1386 	*off += (numsegs + 1) * sizeof(Elf_Phdr);
1387 
1388 	noteoff = *off;
1389 	/*
1390 	 * Don't allocate space for the notes if we're just calculating
1391 	 * the size of the header. We also don't collect the data.
1392 	 */
1393 	if (dst != NULL) {
1394 		tempdata = malloc(sizeof(*tempdata), M_TEMP, M_ZERO|M_WAITOK);
1395 		status = &tempdata->status;
1396 		fpregset = &tempdata->fpregset;
1397 		psinfo = &tempdata->psinfo;
1398 		thrmisc = &tempdata->thrmisc;
1399 	} else {
1400 		tempdata = NULL;
1401 		status = NULL;
1402 		fpregset = NULL;
1403 		psinfo = NULL;
1404 		thrmisc = NULL;
1405 	}
1406 
1407 	if (dst != NULL) {
1408 		psinfo->pr_version = PRPSINFO_VERSION;
1409 		psinfo->pr_psinfosz = sizeof(elf_prpsinfo_t);
1410 		strlcpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname));
1411 		/*
1412 		 * XXX - We don't fill in the command line arguments properly
1413 		 * yet.
1414 		 */
1415 		strlcpy(psinfo->pr_psargs, p->p_comm,
1416 		    sizeof(psinfo->pr_psargs));
1417 	}
1418 	__elfN(putnote)(dst, off, "FreeBSD", NT_PRPSINFO, psinfo,
1419 	    sizeof *psinfo);
1420 
1421 	/*
1422 	 * To have the debugger select the right thread (LWP) as the initial
1423 	 * thread, we dump the state of the thread passed to us in td first.
1424 	 * This is the thread that causes the core dump and thus likely to
1425 	 * be the right thread one wants to have selected in the debugger.
1426 	 */
1427 	thr = td;
1428 	while (thr != NULL) {
1429 		if (dst != NULL) {
1430 			status->pr_version = PRSTATUS_VERSION;
1431 			status->pr_statussz = sizeof(elf_prstatus_t);
1432 			status->pr_gregsetsz = sizeof(elf_gregset_t);
1433 			status->pr_fpregsetsz = sizeof(elf_fpregset_t);
1434 			status->pr_osreldate = osreldate;
1435 			status->pr_cursig = p->p_sig;
1436 			status->pr_pid = thr->td_tid;
1437 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1438 			fill_regs32(thr, &status->pr_reg);
1439 			fill_fpregs32(thr, fpregset);
1440 #else
1441 			fill_regs(thr, &status->pr_reg);
1442 			fill_fpregs(thr, fpregset);
1443 #endif
1444 			memset(&thrmisc->_pad, 0, sizeof (thrmisc->_pad));
1445 			strcpy(thrmisc->pr_tname, thr->td_name);
1446 		}
1447 		__elfN(putnote)(dst, off, "FreeBSD", NT_PRSTATUS, status,
1448 		    sizeof *status);
1449 		__elfN(putnote)(dst, off, "FreeBSD", NT_FPREGSET, fpregset,
1450 		    sizeof *fpregset);
1451 		__elfN(putnote)(dst, off, "FreeBSD", NT_THRMISC, thrmisc,
1452 		    sizeof *thrmisc);
1453 		/*
1454 		 * Allow for MD specific notes, as well as any MD
1455 		 * specific preparations for writing MI notes.
1456 		 */
1457 		__elfN(dump_thread)(thr, dst, off);
1458 
1459 		thr = (thr == td) ? TAILQ_FIRST(&p->p_threads) :
1460 		    TAILQ_NEXT(thr, td_plist);
1461 		if (thr == td)
1462 			thr = TAILQ_NEXT(thr, td_plist);
1463 	}
1464 
1465 	notesz = *off - noteoff;
1466 
1467 	if (dst != NULL)
1468 		free(tempdata, M_TEMP);
1469 
1470 	/* Align up to a page boundary for the program segments. */
1471 	*off = round_page(*off);
1472 
1473 	if (dst != NULL) {
1474 		Elf_Ehdr *ehdr;
1475 		Elf_Phdr *phdr;
1476 		struct phdr_closure phc;
1477 
1478 		/*
1479 		 * Fill in the ELF header.
1480 		 */
1481 		ehdr = (Elf_Ehdr *)((char *)dst + ehoff);
1482 		ehdr->e_ident[EI_MAG0] = ELFMAG0;
1483 		ehdr->e_ident[EI_MAG1] = ELFMAG1;
1484 		ehdr->e_ident[EI_MAG2] = ELFMAG2;
1485 		ehdr->e_ident[EI_MAG3] = ELFMAG3;
1486 		ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1487 		ehdr->e_ident[EI_DATA] = ELF_DATA;
1488 		ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1489 		ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1490 		ehdr->e_ident[EI_ABIVERSION] = 0;
1491 		ehdr->e_ident[EI_PAD] = 0;
1492 		ehdr->e_type = ET_CORE;
1493 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1494 		ehdr->e_machine = ELF_ARCH32;
1495 #else
1496 		ehdr->e_machine = ELF_ARCH;
1497 #endif
1498 		ehdr->e_version = EV_CURRENT;
1499 		ehdr->e_entry = 0;
1500 		ehdr->e_phoff = phoff;
1501 		ehdr->e_flags = 0;
1502 		ehdr->e_ehsize = sizeof(Elf_Ehdr);
1503 		ehdr->e_phentsize = sizeof(Elf_Phdr);
1504 		ehdr->e_phnum = numsegs + 1;
1505 		ehdr->e_shentsize = sizeof(Elf_Shdr);
1506 		ehdr->e_shnum = 0;
1507 		ehdr->e_shstrndx = SHN_UNDEF;
1508 
1509 		/*
1510 		 * Fill in the program header entries.
1511 		 */
1512 		phdr = (Elf_Phdr *)((char *)dst + phoff);
1513 
1514 		/* The note segement. */
1515 		phdr->p_type = PT_NOTE;
1516 		phdr->p_offset = noteoff;
1517 		phdr->p_vaddr = 0;
1518 		phdr->p_paddr = 0;
1519 		phdr->p_filesz = notesz;
1520 		phdr->p_memsz = 0;
1521 		phdr->p_flags = 0;
1522 		phdr->p_align = 0;
1523 		phdr++;
1524 
1525 		/* All the writable segments from the program. */
1526 		phc.phdr = phdr;
1527 		phc.offset = *off;
1528 		each_writable_segment(td, cb_put_phdr, &phc);
1529 	}
1530 }
1531 
1532 static void
1533 __elfN(putnote)(void *dst, size_t *off, const char *name, int type,
1534     const void *desc, size_t descsz)
1535 {
1536 	Elf_Note note;
1537 
1538 	note.n_namesz = strlen(name) + 1;
1539 	note.n_descsz = descsz;
1540 	note.n_type = type;
1541 	if (dst != NULL)
1542 		bcopy(&note, (char *)dst + *off, sizeof note);
1543 	*off += sizeof note;
1544 	if (dst != NULL)
1545 		bcopy(name, (char *)dst + *off, note.n_namesz);
1546 	*off += roundup2(note.n_namesz, sizeof(Elf_Size));
1547 	if (dst != NULL)
1548 		bcopy(desc, (char *)dst + *off, note.n_descsz);
1549 	*off += roundup2(note.n_descsz, sizeof(Elf_Size));
1550 }
1551 
1552 /*
1553  * Try to find the appropriate ABI-note section for checknote,
1554  * fetch the osreldate for binary from the ELF OSABI-note. Only the
1555  * first page of the image is searched, the same as for headers.
1556  */
1557 static boolean_t
1558 __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *checknote,
1559     int32_t *osrel)
1560 {
1561 	const Elf_Note *note, *note0, *note_end;
1562 	const Elf_Phdr *phdr, *pnote;
1563 	const Elf_Ehdr *hdr;
1564 	const char *note_name;
1565 	int i;
1566 
1567 	pnote = NULL;
1568 	hdr = (const Elf_Ehdr *)imgp->image_header;
1569 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
1570 
1571 	for (i = 0; i < hdr->e_phnum; i++) {
1572 		if (phdr[i].p_type == PT_NOTE) {
1573 			pnote = &phdr[i];
1574 			break;
1575 		}
1576 	}
1577 
1578 	if (pnote == NULL || pnote->p_offset >= PAGE_SIZE ||
1579 	    pnote->p_offset + pnote->p_filesz >= PAGE_SIZE)
1580 		return (FALSE);
1581 
1582 	note = note0 = (const Elf_Note *)(imgp->image_header + pnote->p_offset);
1583 	note_end = (const Elf_Note *)(imgp->image_header +
1584 	    pnote->p_offset + pnote->p_filesz);
1585 	for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
1586 		if (!aligned(note, Elf32_Addr))
1587 			return (FALSE);
1588 		if (note->n_namesz != checknote->hdr.n_namesz ||
1589 		    note->n_descsz != checknote->hdr.n_descsz ||
1590 		    note->n_type != checknote->hdr.n_type)
1591 			goto nextnote;
1592 		note_name = (const char *)(note + 1);
1593 		if (strncmp(checknote->vendor, note_name,
1594 		    checknote->hdr.n_namesz) != 0)
1595 			goto nextnote;
1596 
1597 		/*
1598 		 * Fetch the osreldate for binary
1599 		 * from the ELF OSABI-note if necessary.
1600 		 */
1601 		if ((checknote->flags & BN_TRANSLATE_OSREL) != 0 &&
1602 		    checknote->trans_osrel != NULL)
1603 			return (checknote->trans_osrel(note, osrel));
1604 		return (TRUE);
1605 
1606 nextnote:
1607 		note = (const Elf_Note *)((const char *)(note + 1) +
1608 		    roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1609 		    roundup2(note->n_descsz, sizeof(Elf32_Addr)));
1610 	}
1611 
1612 	return (FALSE);
1613 }
1614 
1615 /*
1616  * Tell kern_execve.c about it, with a little help from the linker.
1617  */
1618 static struct execsw __elfN(execsw) = {
1619 	__CONCAT(exec_, __elfN(imgact)),
1620 	__XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
1621 };
1622 EXEC_SET(__CONCAT(elf, __ELF_WORD_SIZE), __elfN(execsw));
1623 
1624 #ifdef COMPRESS_USER_CORES
1625 /*
1626  * Compress and write out a core segment for a user process.
1627  *
1628  * 'inbuf' is the starting address of a VM segment in the process' address
1629  * space that is to be compressed and written out to the core file.  'dest_buf'
1630  * is a buffer in the kernel's address space.  The segment is copied from
1631  * 'inbuf' to 'dest_buf' first before being processed by the compression
1632  * routine gzwrite().  This copying is necessary because the content of the VM
1633  * segment may change between the compression pass and the crc-computation pass
1634  * in gzwrite().  This is because realtime threads may preempt the UNIX kernel.
1635  */
1636 static int
1637 compress_core (gzFile file, char *inbuf, char *dest_buf, unsigned int len,
1638     struct thread *td)
1639 {
1640 	int len_compressed;
1641 	int error = 0;
1642 	unsigned int chunk_len;
1643 
1644 	while (len) {
1645 		chunk_len = (len > CORE_BUF_SIZE) ? CORE_BUF_SIZE : len;
1646 		copyin(inbuf, dest_buf, chunk_len);
1647 		len_compressed = gzwrite(file, dest_buf, chunk_len);
1648 
1649 		EVENTHANDLER_INVOKE(app_coredump_progress, td, len_compressed);
1650 
1651 		if ((unsigned int)len_compressed != chunk_len) {
1652 			log(LOG_WARNING,
1653 			    "compress_core: length mismatch (0x%x returned, "
1654 			    "0x%x expected)\n", len_compressed, chunk_len);
1655 			EVENTHANDLER_INVOKE(app_coredump_error, td,
1656 			    "compress_core: length mismatch %x -> %x",
1657 			    chunk_len, len_compressed);
1658 			error = EFAULT;
1659 			break;
1660 		}
1661 		inbuf += chunk_len;
1662 		len -= chunk_len;
1663 		maybe_yield();
1664 	}
1665 
1666 	return (error);
1667 }
1668 #endif /* COMPRESS_USER_CORES */
1669 
1670 static vm_prot_t
1671 __elfN(trans_prot)(Elf_Word flags)
1672 {
1673 	vm_prot_t prot;
1674 
1675 	prot = 0;
1676 	if (flags & PF_X)
1677 		prot |= VM_PROT_EXECUTE;
1678 	if (flags & PF_W)
1679 		prot |= VM_PROT_WRITE;
1680 	if (flags & PF_R)
1681 		prot |= VM_PROT_READ;
1682 #if __ELF_WORD_SIZE == 32
1683 #if defined(__amd64__) || defined(__ia64__)
1684 	if (i386_read_exec && (flags & PF_R))
1685 		prot |= VM_PROT_EXECUTE;
1686 #endif
1687 #endif
1688 	return (prot);
1689 }
1690 
1691 static Elf_Word
1692 __elfN(untrans_prot)(vm_prot_t prot)
1693 {
1694 	Elf_Word flags;
1695 
1696 	flags = 0;
1697 	if (prot & VM_PROT_EXECUTE)
1698 		flags |= PF_X;
1699 	if (prot & VM_PROT_READ)
1700 		flags |= PF_R;
1701 	if (prot & VM_PROT_WRITE)
1702 		flags |= PF_W;
1703 	return (flags);
1704 }
1705