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