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