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