xref: /freebsd/sys/kern/imgact_elf.c (revision 0fddbf874719b9bd50cf66ac26d1140bb3f2be69)
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 withough 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  * $FreeBSD$
31  */
32 
33 #include "opt_rlimit.h"
34 
35 #include <sys/param.h>
36 #include <sys/exec.h>
37 #include <sys/fcntl.h>
38 #include <sys/imgact.h>
39 #include <sys/imgact_elf.h>
40 #include <sys/kernel.h>
41 #include <sys/lock.h>
42 #include <sys/malloc.h>
43 #include <sys/mutex.h>
44 #include <sys/mman.h>
45 #include <sys/namei.h>
46 #include <sys/pioctl.h>
47 #include <sys/proc.h>
48 #include <sys/procfs.h>
49 #include <sys/resourcevar.h>
50 #include <sys/systm.h>
51 #include <sys/signalvar.h>
52 #include <sys/stat.h>
53 #include <sys/sx.h>
54 #include <sys/syscall.h>
55 #include <sys/sysctl.h>
56 #include <sys/sysent.h>
57 #include <sys/vnode.h>
58 
59 #include <vm/vm.h>
60 #include <vm/vm_kern.h>
61 #include <vm/vm_param.h>
62 #include <vm/pmap.h>
63 #include <vm/vm_map.h>
64 #include <vm/vm_object.h>
65 #include <vm/vm_extern.h>
66 
67 #include <machine/elf.h>
68 #include <machine/md_var.h>
69 
70 #define OLD_EI_BRAND	8
71 
72 __ElfType(Brandinfo);
73 __ElfType(Auxargs);
74 
75 static int elf_check_header __P((const Elf_Ehdr *hdr));
76 static int elf_freebsd_fixup __P((register_t **stack_base,
77     struct image_params *imgp));
78 static int elf_load_file __P((struct proc *p, const char *file, u_long *addr,
79     u_long *entry));
80 static int elf_load_section __P((struct proc *p,
81     struct vmspace *vmspace, struct vnode *vp,
82     vm_offset_t offset, caddr_t vmaddr, size_t memsz, size_t filsz,
83     vm_prot_t prot));
84 static int exec_elf_imgact __P((struct image_params *imgp));
85 
86 static int elf_trace = 0;
87 SYSCTL_INT(_debug, OID_AUTO, elf_trace, CTLFLAG_RW, &elf_trace, 0, "");
88 
89 struct sysentvec elf_freebsd_sysvec = {
90         SYS_MAXSYSCALL,
91         sysent,
92         0,
93         0,
94         0,
95         0,
96         0,
97         0,
98         elf_freebsd_fixup,
99         sendsig,
100         sigcode,
101         &szsigcode,
102         0,
103 	"FreeBSD ELF",
104 	elf_coredump,
105 	NULL,
106 	MINSIGSTKSZ
107 };
108 
109 static Elf_Brandinfo freebsd_brand_info = {
110 						ELFOSABI_FREEBSD,
111 						"FreeBSD",
112 						"",
113 						"/usr/libexec/ld-elf.so.1",
114 						&elf_freebsd_sysvec
115 					  };
116 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS] = {
117 							&freebsd_brand_info,
118 							NULL, NULL, NULL,
119 							NULL, NULL, NULL, NULL
120 						    };
121 
122 int
123 elf_insert_brand_entry(Elf_Brandinfo *entry)
124 {
125 	int i;
126 
127 	for (i=1; i<MAX_BRANDS; i++) {
128 		if (elf_brand_list[i] == NULL) {
129 			elf_brand_list[i] = entry;
130 			break;
131 		}
132 	}
133 	if (i == MAX_BRANDS)
134 		return -1;
135 	return 0;
136 }
137 
138 int
139 elf_remove_brand_entry(Elf_Brandinfo *entry)
140 {
141 	int i;
142 
143 	for (i=1; i<MAX_BRANDS; i++) {
144 		if (elf_brand_list[i] == entry) {
145 			elf_brand_list[i] = NULL;
146 			break;
147 		}
148 	}
149 	if (i == MAX_BRANDS)
150 		return -1;
151 	return 0;
152 }
153 
154 int
155 elf_brand_inuse(Elf_Brandinfo *entry)
156 {
157 	struct proc *p;
158 	int rval = FALSE;
159 
160 	sx_slock(&allproc_lock);
161 	LIST_FOREACH(p, &allproc, p_list) {
162 		if (p->p_sysent == entry->sysvec) {
163 			rval = TRUE;
164 			break;
165 		}
166 	}
167 	sx_sunlock(&allproc_lock);
168 
169 	return (rval);
170 }
171 
172 static int
173 elf_check_header(const Elf_Ehdr *hdr)
174 {
175 	if (!IS_ELF(*hdr) ||
176 	    hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
177 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
178 	    hdr->e_ident[EI_VERSION] != EV_CURRENT)
179 		return ENOEXEC;
180 
181 	if (!ELF_MACHINE_OK(hdr->e_machine))
182 		return ENOEXEC;
183 
184 	if (hdr->e_version != ELF_TARG_VER)
185 		return ENOEXEC;
186 
187 	return 0;
188 }
189 
190 static int
191 elf_load_section(struct proc *p, struct vmspace *vmspace, struct vnode *vp, vm_offset_t offset, caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot)
192 {
193 	size_t map_len;
194 	vm_offset_t map_addr;
195 	int error, rv;
196 	size_t copy_len;
197 	vm_object_t object;
198 	vm_offset_t file_addr;
199 	vm_offset_t data_buf = 0;
200 
201 	GIANT_REQUIRED;
202 
203 	VOP_GETVOBJECT(vp, &object);
204 	error = 0;
205 
206 	/*
207 	 * It's necessary to fail if the filsz + offset taken from the
208 	 * header is greater than the actual file pager object's size.
209 	 * If we were to allow this, then the vm_map_find() below would
210 	 * walk right off the end of the file object and into the ether.
211 	 *
212 	 * While I'm here, might as well check for something else that
213 	 * is invalid: filsz cannot be greater than memsz.
214 	 */
215 	if ((off_t)filsz + offset > object->un_pager.vnp.vnp_size ||
216 	    filsz > memsz) {
217 		uprintf("elf_load_section: truncated ELF file\n");
218 		return (ENOEXEC);
219 	}
220 
221 	map_addr = trunc_page((vm_offset_t)vmaddr);
222 	file_addr = trunc_page(offset);
223 
224 	/*
225 	 * We have two choices.  We can either clear the data in the last page
226 	 * of an oversized mapping, or we can start the anon mapping a page
227 	 * early and copy the initialized data into that first page.  We
228 	 * choose the second..
229 	 */
230 	if (memsz > filsz)
231 		map_len = trunc_page(offset+filsz) - file_addr;
232 	else
233 		map_len = round_page(offset+filsz) - file_addr;
234 
235 	if (map_len != 0) {
236 		vm_object_reference(object);
237 		vm_map_lock(&vmspace->vm_map);
238 		rv = vm_map_insert(&vmspace->vm_map,
239 				      object,
240 				      file_addr,	/* file offset */
241 				      map_addr,		/* virtual start */
242 				      map_addr + map_len,/* virtual end */
243 				      prot,
244 				      VM_PROT_ALL,
245 				      MAP_COPY_ON_WRITE | MAP_PREFAULT);
246 		vm_map_unlock(&vmspace->vm_map);
247 		if (rv != KERN_SUCCESS) {
248 			vm_object_deallocate(object);
249 			return EINVAL;
250 		}
251 
252 		/* we can stop now if we've covered it all */
253 		if (memsz == filsz) {
254 			return 0;
255 		}
256 	}
257 
258 
259 	/*
260 	 * We have to get the remaining bit of the file into the first part
261 	 * of the oversized map segment.  This is normally because the .data
262 	 * segment in the file is extended to provide bss.  It's a neat idea
263 	 * to try and save a page, but it's a pain in the behind to implement.
264 	 */
265 	copy_len = (offset + filsz) - trunc_page(offset + filsz);
266 	map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
267 	map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
268 
269 	/* This had damn well better be true! */
270         if (map_len != 0) {
271 		vm_map_lock(&vmspace->vm_map);
272 		rv = vm_map_insert(&vmspace->vm_map, NULL, 0,
273 					map_addr, map_addr + map_len,
274 					VM_PROT_ALL, VM_PROT_ALL, 0);
275 		vm_map_unlock(&vmspace->vm_map);
276 		if (rv != KERN_SUCCESS) {
277 			return EINVAL;
278 		}
279 	}
280 
281 	if (copy_len != 0) {
282 		vm_object_reference(object);
283 		rv = vm_map_find(exec_map,
284 				 object,
285 				 trunc_page(offset + filsz),
286 				 &data_buf,
287 				 PAGE_SIZE,
288 				 TRUE,
289 				 VM_PROT_READ,
290 				 VM_PROT_ALL,
291 				 MAP_COPY_ON_WRITE | MAP_PREFAULT_PARTIAL);
292 		if (rv != KERN_SUCCESS) {
293 			vm_object_deallocate(object);
294 			return EINVAL;
295 		}
296 
297 		/* send the page fragment to user space */
298 		error = copyout((caddr_t)data_buf, (caddr_t)map_addr, copy_len);
299 		vm_map_remove(exec_map, data_buf, data_buf + PAGE_SIZE);
300 		if (error) {
301 			return (error);
302 		}
303 	}
304 
305 	/*
306 	 * set it to the specified protection
307 	 */
308 	vm_map_protect(&vmspace->vm_map, map_addr, map_addr + map_len,  prot,
309 		       FALSE);
310 
311 	return error;
312 }
313 
314 /*
315  * Load the file "file" into memory.  It may be either a shared object
316  * or an executable.
317  *
318  * The "addr" reference parameter is in/out.  On entry, it specifies
319  * the address where a shared object should be loaded.  If the file is
320  * an executable, this value is ignored.  On exit, "addr" specifies
321  * where the file was actually loaded.
322  *
323  * The "entry" reference parameter is out only.  On exit, it specifies
324  * the entry point for the loaded file.
325  */
326 static int
327 elf_load_file(struct proc *p, const char *file, u_long *addr, u_long *entry)
328 {
329 	struct {
330 		struct nameidata nd;
331 		struct vattr attr;
332 		struct image_params image_params;
333 	} *tempdata;
334 	const Elf_Ehdr *hdr = NULL;
335 	const Elf_Phdr *phdr = NULL;
336 	struct nameidata *nd;
337 	struct vmspace *vmspace = p->p_vmspace;
338 	struct vattr *attr;
339 	struct image_params *imgp;
340 	vm_prot_t prot;
341 	u_long rbase;
342 	u_long base_addr = 0;
343 	int error, i, numsegs;
344 
345 	tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
346 	nd = &tempdata->nd;
347 	attr = &tempdata->attr;
348 	imgp = &tempdata->image_params;
349 
350 	/*
351 	 * Initialize part of the common data
352 	 */
353 	imgp->proc = p;
354 	imgp->uap = NULL;
355 	imgp->attr = attr;
356 	imgp->firstpage = NULL;
357 	imgp->image_header = (char *)kmem_alloc_wait(exec_map, PAGE_SIZE);
358 
359 	if (imgp->image_header == NULL) {
360 		nd->ni_vp = NULL;
361 		error = ENOMEM;
362 		goto fail;
363 	}
364 
365         NDINIT(nd, LOOKUP, LOCKLEAF|FOLLOW, UIO_SYSSPACE, file, p);
366 
367 	if ((error = namei(nd)) != 0) {
368 		nd->ni_vp = NULL;
369 		goto fail;
370 	}
371 	NDFREE(nd, NDF_ONLY_PNBUF);
372 	imgp->vp = nd->ni_vp;
373 
374 	/*
375 	 * Check permissions, modes, uid, etc on the file, and "open" it.
376 	 */
377 	error = exec_check_permissions(imgp);
378 	if (error) {
379 		VOP_UNLOCK(nd->ni_vp, 0, p);
380 		goto fail;
381 	}
382 
383 	error = exec_map_first_page(imgp);
384 	/*
385 	 * Also make certain that the interpreter stays the same, so set
386 	 * its VTEXT flag, too.
387 	 */
388 	if (error == 0)
389 		nd->ni_vp->v_flag |= VTEXT;
390 	VOP_UNLOCK(nd->ni_vp, 0, p);
391 	if (error)
392                 goto fail;
393 
394 	hdr = (const Elf_Ehdr *)imgp->image_header;
395 	if ((error = elf_check_header(hdr)) != 0)
396 		goto fail;
397 	if (hdr->e_type == ET_DYN)
398 		rbase = *addr;
399 	else if (hdr->e_type == ET_EXEC)
400 		rbase = 0;
401 	else {
402 		error = ENOEXEC;
403 		goto fail;
404 	}
405 
406 	/* Only support headers that fit within first page for now */
407 	if ((hdr->e_phoff > PAGE_SIZE) ||
408 	    (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
409 		error = ENOEXEC;
410 		goto fail;
411 	}
412 
413 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
414 
415 	for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
416 		if (phdr[i].p_type == PT_LOAD) {	/* Loadable segment */
417 			prot = 0;
418 			if (phdr[i].p_flags & PF_X)
419   				prot |= VM_PROT_EXECUTE;
420 			if (phdr[i].p_flags & PF_W)
421   				prot |= VM_PROT_WRITE;
422 			if (phdr[i].p_flags & PF_R)
423   				prot |= VM_PROT_READ;
424 
425 			if ((error = elf_load_section(p, vmspace, nd->ni_vp,
426   						     phdr[i].p_offset,
427   						     (caddr_t)phdr[i].p_vaddr +
428 							rbase,
429   						     phdr[i].p_memsz,
430   						     phdr[i].p_filesz, prot)) != 0)
431 				goto fail;
432 			/*
433 			 * Establish the base address if this is the
434 			 * first segment.
435 			 */
436 			if (numsegs == 0)
437   				base_addr = trunc_page(phdr[i].p_vaddr + rbase);
438 			numsegs++;
439 		}
440 	}
441 	*addr = base_addr;
442 	*entry=(unsigned long)hdr->e_entry + rbase;
443 
444 fail:
445 	if (imgp->firstpage)
446 		exec_unmap_first_page(imgp);
447 	if (imgp->image_header)
448 		kmem_free_wakeup(exec_map, (vm_offset_t)imgp->image_header,
449 			PAGE_SIZE);
450 	if (nd->ni_vp)
451 		vrele(nd->ni_vp);
452 
453 	free(tempdata, M_TEMP);
454 
455 	return error;
456 }
457 
458 /*
459  * non static, as it can be overridden by start_init()
460  */
461 #ifdef __ia64__
462 int fallback_elf_brand = ELFOSABI_FREEBSD;
463 #else
464 int fallback_elf_brand = -1;
465 #endif
466 SYSCTL_INT(_kern, OID_AUTO, fallback_elf_brand, CTLFLAG_RW,
467 		&fallback_elf_brand, -1,
468 		"ELF brand of last resort");
469 
470 static int
471 exec_elf_imgact(struct image_params *imgp)
472 {
473 	const Elf_Ehdr *hdr = (const Elf_Ehdr *) imgp->image_header;
474 	const Elf_Phdr *phdr;
475 	Elf_Auxargs *elf_auxargs = NULL;
476 	struct vmspace *vmspace;
477 	vm_prot_t prot;
478 	u_long text_size = 0, data_size = 0;
479 	u_long text_addr = 0, data_addr = 0;
480 	u_long addr, entry = 0, proghdr = 0;
481 	int error, i;
482 	const char *interp = NULL;
483 	Elf_Brandinfo *brand_info;
484 	char *path;
485 
486 	GIANT_REQUIRED;
487 
488 	/*
489 	 * Do we have a valid ELF header ?
490 	 */
491 	if (elf_check_header(hdr) != 0 || hdr->e_type != ET_EXEC)
492 		return -1;
493 
494 	/*
495 	 * From here on down, we return an errno, not -1, as we've
496 	 * detected an ELF file.
497 	 */
498 
499 	if ((hdr->e_phoff > PAGE_SIZE) ||
500 	    (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
501 		/* Only support headers in first page for now */
502 		return ENOEXEC;
503 	}
504 	phdr = (const Elf_Phdr*)(imgp->image_header + hdr->e_phoff);
505 
506 	/*
507 	 * From this point on, we may have resources that need to be freed.
508 	 */
509 
510 	/*
511 	 * Yeah, I'm paranoid.  There is every reason in the world to get
512 	 * VTEXT now since from here on out, there are places we can have
513 	 * a context switch.  Better safe than sorry; I really don't want
514 	 * the file to change while it's being loaded.
515 	 */
516 	mtx_lock(&imgp->vp->v_interlock);
517 	imgp->vp->v_flag |= VTEXT;
518 	mtx_unlock(&imgp->vp->v_interlock);
519 
520 	if ((error = exec_extract_strings(imgp)) != 0)
521 		goto fail;
522 
523 	exec_new_vmspace(imgp);
524 
525 	vmspace = imgp->proc->p_vmspace;
526 
527 	for (i = 0; i < hdr->e_phnum; i++) {
528 		switch(phdr[i].p_type) {
529 
530 		case PT_LOAD:	/* Loadable segment */
531 			prot = 0;
532 			if (phdr[i].p_flags & PF_X)
533   				prot |= VM_PROT_EXECUTE;
534 			if (phdr[i].p_flags & PF_W)
535   				prot |= VM_PROT_WRITE;
536 			if (phdr[i].p_flags & PF_R)
537   				prot |= VM_PROT_READ;
538 
539 			if ((error = elf_load_section(imgp->proc,
540 						     vmspace, imgp->vp,
541   						     phdr[i].p_offset,
542   						     (caddr_t)phdr[i].p_vaddr,
543   						     phdr[i].p_memsz,
544   						     phdr[i].p_filesz, prot)) != 0)
545   				goto fail;
546 
547 			/*
548 			 * Is this .text or .data ??
549 			 *
550 			 * We only handle one each of those yet XXX
551 			 */
552 			if (hdr->e_entry >= phdr[i].p_vaddr &&
553 			hdr->e_entry <(phdr[i].p_vaddr+phdr[i].p_memsz)) {
554   				text_addr = trunc_page(phdr[i].p_vaddr);
555   				text_size = round_page(phdr[i].p_memsz +
556 						       phdr[i].p_vaddr -
557 						       text_addr);
558 				entry = (u_long)hdr->e_entry;
559 			} else {
560   				data_addr = trunc_page(phdr[i].p_vaddr);
561   				data_size = round_page(phdr[i].p_memsz +
562 						       phdr[i].p_vaddr -
563 						       data_addr);
564 			}
565 			break;
566 	  	case PT_INTERP:	/* Path to interpreter */
567 			if (phdr[i].p_filesz > MAXPATHLEN ||
568 			    phdr[i].p_offset + phdr[i].p_filesz > PAGE_SIZE) {
569 				error = ENOEXEC;
570 				goto fail;
571 			}
572 			interp = imgp->image_header + phdr[i].p_offset;
573 			break;
574 		case PT_PHDR: 	/* Program header table info */
575 			proghdr = phdr[i].p_vaddr;
576 			break;
577 		default:
578 			break;
579 		}
580 	}
581 
582 	vmspace->vm_tsize = text_size >> PAGE_SHIFT;
583 	vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
584 	vmspace->vm_dsize = data_size >> PAGE_SHIFT;
585 	vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
586 
587 	addr = ELF_RTLD_ADDR(vmspace);
588 
589 	imgp->entry_addr = entry;
590 
591 	brand_info = NULL;
592 
593 	/* We support three types of branding -- (1) the ELF EI_OSABI field
594 	 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
595 	 * branding w/in the ELF header, and (3) path of the `interp_path'
596 	 * field.  We should also look for an ".note.ABI-tag" ELF section now
597 	 * in all Linux ELF binaries, FreeBSD 4.1+, and some NetBSD ones.
598 	 */
599 
600 	/* If the executable has a brand, search for it in the brand list. */
601 	if (brand_info == NULL) {
602 		for (i = 0;  i < MAX_BRANDS;  i++) {
603 			Elf_Brandinfo *bi = elf_brand_list[i];
604 
605 			if (bi != NULL &&
606 			    (hdr->e_ident[EI_OSABI] == bi->brand
607 			    || 0 ==
608 			    strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
609 			    bi->compat_3_brand, strlen(bi->compat_3_brand)))) {
610 				brand_info = bi;
611 				break;
612 			}
613 		}
614 	}
615 
616 	/* Lacking a known brand, search for a recognized interpreter. */
617 	if (brand_info == NULL && interp != NULL) {
618 		for (i = 0;  i < MAX_BRANDS;  i++) {
619 			Elf_Brandinfo *bi = elf_brand_list[i];
620 
621 			if (bi != NULL &&
622 			    strcmp(interp, bi->interp_path) == 0) {
623 				brand_info = bi;
624 				break;
625 			}
626 		}
627 	}
628 
629 	/* Lacking a recognized interpreter, try the default brand */
630 	if (brand_info == NULL) {
631 		for (i = 0; i < MAX_BRANDS; i++) {
632 			Elf_Brandinfo *bi = elf_brand_list[i];
633 
634 			if (bi != NULL && fallback_elf_brand == bi->brand) {
635 				brand_info = bi;
636 				break;
637 			}
638 		}
639 	}
640 
641 	if (brand_info == NULL) {
642 		uprintf("ELF binary type \"%u\" not known.\n",
643 		    hdr->e_ident[EI_OSABI]);
644 		error = ENOEXEC;
645 		goto fail;
646 	}
647 
648 	imgp->proc->p_sysent = brand_info->sysvec;
649 	if (interp != NULL) {
650 		path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
651 	        snprintf(path, MAXPATHLEN, "%s%s",
652 			 brand_info->emul_path, interp);
653 		if ((error = elf_load_file(imgp->proc, path, &addr,
654 					   &imgp->entry_addr)) != 0) {
655 		        if ((error = elf_load_file(imgp->proc, interp, &addr,
656 						   &imgp->entry_addr)) != 0) {
657 			        uprintf("ELF interpreter %s not found\n", path);
658 				free(path, M_TEMP);
659 				goto fail;
660 			}
661                 }
662 		free(path, M_TEMP);
663 	}
664 
665 	/*
666 	 * Construct auxargs table (used by the fixup routine)
667 	 */
668 	elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
669 	elf_auxargs->execfd = -1;
670 	elf_auxargs->phdr = proghdr;
671 	elf_auxargs->phent = hdr->e_phentsize;
672 	elf_auxargs->phnum = hdr->e_phnum;
673 	elf_auxargs->pagesz = PAGE_SIZE;
674 	elf_auxargs->base = addr;
675 	elf_auxargs->flags = 0;
676 	elf_auxargs->entry = entry;
677 	elf_auxargs->trace = elf_trace;
678 
679 	imgp->auxargs = elf_auxargs;
680 	imgp->interpreted = 0;
681 
682 fail:
683 	return error;
684 }
685 
686 static int
687 elf_freebsd_fixup(register_t **stack_base, struct image_params *imgp)
688 {
689 	Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
690 	register_t *pos;
691 
692 	pos = *stack_base + (imgp->argc + imgp->envc + 2);
693 
694 	if (args->trace) {
695 		AUXARGS_ENTRY(pos, AT_DEBUG, 1);
696 	}
697 	if (args->execfd != -1) {
698 		AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
699 	}
700 	AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
701 	AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
702 	AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
703 	AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
704 	AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
705 	AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
706 	AUXARGS_ENTRY(pos, AT_BASE, args->base);
707 	AUXARGS_ENTRY(pos, AT_NULL, 0);
708 
709 	free(imgp->auxargs, M_TEMP);
710 	imgp->auxargs = NULL;
711 
712 	(*stack_base)--;
713 	suword(*stack_base, (long) imgp->argc);
714 	return 0;
715 }
716 
717 /*
718  * Code for generating ELF core dumps.
719  */
720 
721 typedef void (*segment_callback) __P((vm_map_entry_t, void *));
722 
723 /* Closure for cb_put_phdr(). */
724 struct phdr_closure {
725 	Elf_Phdr *phdr;		/* Program header to fill in */
726 	Elf_Off offset;		/* Offset of segment in core file */
727 };
728 
729 /* Closure for cb_size_segment(). */
730 struct sseg_closure {
731 	int count;		/* Count of writable segments. */
732 	size_t size;		/* Total size of all writable segments. */
733 };
734 
735 static void cb_put_phdr __P((vm_map_entry_t, void *));
736 static void cb_size_segment __P((vm_map_entry_t, void *));
737 static void each_writable_segment __P((struct proc *, segment_callback,
738     void *));
739 static int elf_corehdr __P((struct proc *, struct vnode *, struct ucred *,
740     int, void *, size_t));
741 static void elf_puthdr __P((struct proc *, void *, size_t *,
742     const prstatus_t *, const prfpregset_t *, const prpsinfo_t *, int));
743 static void elf_putnote __P((void *, size_t *, const char *, int,
744     const void *, size_t));
745 
746 extern int osreldate;
747 
748 int
749 elf_coredump(p, vp, limit)
750 	register struct proc *p;
751 	register struct vnode *vp;
752 	off_t limit;
753 {
754 	register struct ucred *cred = p->p_ucred;
755 	int error = 0;
756 	struct sseg_closure seginfo;
757 	void *hdr;
758 	size_t hdrsize;
759 
760 	/* Size the program segments. */
761 	seginfo.count = 0;
762 	seginfo.size = 0;
763 	each_writable_segment(p, cb_size_segment, &seginfo);
764 
765 	/*
766 	 * Calculate the size of the core file header area by making
767 	 * a dry run of generating it.  Nothing is written, but the
768 	 * size is calculated.
769 	 */
770 	hdrsize = 0;
771 	elf_puthdr((struct proc *)NULL, (void *)NULL, &hdrsize,
772 	    (const prstatus_t *)NULL, (const prfpregset_t *)NULL,
773 	    (const prpsinfo_t *)NULL, seginfo.count);
774 
775 	if (hdrsize + seginfo.size >= limit)
776 		return (EFAULT);
777 
778 	/*
779 	 * Allocate memory for building the header, fill it up,
780 	 * and write it out.
781 	 */
782 	hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
783 	if (hdr == NULL) {
784 		return EINVAL;
785 	}
786 	error = elf_corehdr(p, vp, cred, seginfo.count, hdr, hdrsize);
787 
788 	/* Write the contents of all of the writable segments. */
789 	if (error == 0) {
790 		Elf_Phdr *php;
791 		off_t offset;
792 		int i;
793 
794 		php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
795 		offset = hdrsize;
796 		for (i = 0;  i < seginfo.count;  i++) {
797 			error = vn_rdwr(UIO_WRITE, vp, (caddr_t)php->p_vaddr,
798 			    php->p_filesz, offset, UIO_USERSPACE,
799 			    IO_NODELOCKED|IO_UNIT, cred, (int *)NULL, p);
800 			if (error != 0)
801 				break;
802 			offset += php->p_filesz;
803 			php++;
804 		}
805 	}
806 	free(hdr, M_TEMP);
807 
808 	return error;
809 }
810 
811 /*
812  * A callback for each_writable_segment() to write out the segment's
813  * program header entry.
814  */
815 static void
816 cb_put_phdr(entry, closure)
817 	vm_map_entry_t entry;
818 	void *closure;
819 {
820 	struct phdr_closure *phc = (struct phdr_closure *)closure;
821 	Elf_Phdr *phdr = phc->phdr;
822 
823 	phc->offset = round_page(phc->offset);
824 
825 	phdr->p_type = PT_LOAD;
826 	phdr->p_offset = phc->offset;
827 	phdr->p_vaddr = entry->start;
828 	phdr->p_paddr = 0;
829 	phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
830 	phdr->p_align = PAGE_SIZE;
831 	phdr->p_flags = 0;
832 	if (entry->protection & VM_PROT_READ)
833 		phdr->p_flags |= PF_R;
834 	if (entry->protection & VM_PROT_WRITE)
835 		phdr->p_flags |= PF_W;
836 	if (entry->protection & VM_PROT_EXECUTE)
837 		phdr->p_flags |= PF_X;
838 
839 	phc->offset += phdr->p_filesz;
840 	phc->phdr++;
841 }
842 
843 /*
844  * A callback for each_writable_segment() to gather information about
845  * the number of segments and their total size.
846  */
847 static void
848 cb_size_segment(entry, closure)
849 	vm_map_entry_t entry;
850 	void *closure;
851 {
852 	struct sseg_closure *ssc = (struct sseg_closure *)closure;
853 
854 	ssc->count++;
855 	ssc->size += entry->end - entry->start;
856 }
857 
858 /*
859  * For each writable segment in the process's memory map, call the given
860  * function with a pointer to the map entry and some arbitrary
861  * caller-supplied data.
862  */
863 static void
864 each_writable_segment(p, func, closure)
865 	struct proc *p;
866 	segment_callback func;
867 	void *closure;
868 {
869 	vm_map_t map = &p->p_vmspace->vm_map;
870 	vm_map_entry_t entry;
871 
872 	for (entry = map->header.next;  entry != &map->header;
873 	    entry = entry->next) {
874 		vm_object_t obj;
875 
876 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) ||
877 		    (entry->protection & (VM_PROT_READ|VM_PROT_WRITE)) !=
878 		    (VM_PROT_READ|VM_PROT_WRITE))
879 			continue;
880 
881 		/*
882 		** Dont include memory segment in the coredump if
883 		** MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
884 		** madvise(2).
885 		*/
886 		if (entry->eflags & MAP_ENTRY_NOCOREDUMP)
887 			continue;
888 
889 		if ((obj = entry->object.vm_object) == NULL)
890 			continue;
891 
892 		/* Find the deepest backing object. */
893 		while (obj->backing_object != NULL)
894 			obj = obj->backing_object;
895 
896 		/* Ignore memory-mapped devices and such things. */
897 		if (obj->type != OBJT_DEFAULT &&
898 		    obj->type != OBJT_SWAP &&
899 		    obj->type != OBJT_VNODE)
900 			continue;
901 
902 		(*func)(entry, closure);
903 	}
904 }
905 
906 /*
907  * Write the core file header to the file, including padding up to
908  * the page boundary.
909  */
910 static int
911 elf_corehdr(p, vp, cred, numsegs, hdr, hdrsize)
912 	struct proc *p;
913 	struct vnode *vp;
914 	struct ucred *cred;
915 	int numsegs;
916 	size_t hdrsize;
917 	void *hdr;
918 {
919 	struct {
920 		prstatus_t status;
921 		prfpregset_t fpregset;
922 		prpsinfo_t psinfo;
923 	} *tempdata;
924 	size_t off;
925 	prstatus_t *status;
926 	prfpregset_t *fpregset;
927 	prpsinfo_t *psinfo;
928 
929 	tempdata = malloc(sizeof(*tempdata), M_TEMP, M_ZERO | M_WAITOK);
930 	status = &tempdata->status;
931 	fpregset = &tempdata->fpregset;
932 	psinfo = &tempdata->psinfo;
933 
934 	/* Gather the information for the header. */
935 	status->pr_version = PRSTATUS_VERSION;
936 	status->pr_statussz = sizeof(prstatus_t);
937 	status->pr_gregsetsz = sizeof(gregset_t);
938 	status->pr_fpregsetsz = sizeof(fpregset_t);
939 	status->pr_osreldate = osreldate;
940 	status->pr_cursig = p->p_sig;
941 	status->pr_pid = p->p_pid;
942 	fill_regs(p, &status->pr_reg);
943 
944 	fill_fpregs(p, fpregset);
945 
946 	psinfo->pr_version = PRPSINFO_VERSION;
947 	psinfo->pr_psinfosz = sizeof(prpsinfo_t);
948 	strncpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname) - 1);
949 
950 	/* XXX - We don't fill in the command line arguments properly yet. */
951 	strncpy(psinfo->pr_psargs, p->p_comm, PRARGSZ);
952 
953 	/* Fill in the header. */
954 	bzero(hdr, hdrsize);
955 	off = 0;
956 	elf_puthdr(p, hdr, &off, status, fpregset, psinfo, numsegs);
957 
958 	free(tempdata, M_TEMP);
959 
960 	/* Write it to the core file. */
961 	return vn_rdwr(UIO_WRITE, vp, hdr, hdrsize, (off_t)0,
962 	    UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT, cred, NULL, p);
963 }
964 
965 static void
966 elf_puthdr(struct proc *p, void *dst, size_t *off, const prstatus_t *status,
967     const prfpregset_t *fpregset, const prpsinfo_t *psinfo, int numsegs)
968 {
969 	size_t ehoff;
970 	size_t phoff;
971 	size_t noteoff;
972 	size_t notesz;
973 
974 	ehoff = *off;
975 	*off += sizeof(Elf_Ehdr);
976 
977 	phoff = *off;
978 	*off += (numsegs + 1) * sizeof(Elf_Phdr);
979 
980 	noteoff = *off;
981 	elf_putnote(dst, off, "FreeBSD", NT_PRSTATUS, status,
982 	    sizeof *status);
983 	elf_putnote(dst, off, "FreeBSD", NT_FPREGSET, fpregset,
984 	    sizeof *fpregset);
985 	elf_putnote(dst, off, "FreeBSD", NT_PRPSINFO, psinfo,
986 	    sizeof *psinfo);
987 	notesz = *off - noteoff;
988 
989 	/* Align up to a page boundary for the program segments. */
990 	*off = round_page(*off);
991 
992 	if (dst != NULL) {
993 		Elf_Ehdr *ehdr;
994 		Elf_Phdr *phdr;
995 		struct phdr_closure phc;
996 
997 		/*
998 		 * Fill in the ELF header.
999 		 */
1000 		ehdr = (Elf_Ehdr *)((char *)dst + ehoff);
1001 		ehdr->e_ident[EI_MAG0] = ELFMAG0;
1002 		ehdr->e_ident[EI_MAG1] = ELFMAG1;
1003 		ehdr->e_ident[EI_MAG2] = ELFMAG2;
1004 		ehdr->e_ident[EI_MAG3] = ELFMAG3;
1005 		ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1006 		ehdr->e_ident[EI_DATA] = ELF_DATA;
1007 		ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1008 		ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1009 		ehdr->e_ident[EI_ABIVERSION] = 0;
1010 		ehdr->e_ident[EI_PAD] = 0;
1011 		ehdr->e_type = ET_CORE;
1012 		ehdr->e_machine = ELF_ARCH;
1013 		ehdr->e_version = EV_CURRENT;
1014 		ehdr->e_entry = 0;
1015 		ehdr->e_phoff = phoff;
1016 		ehdr->e_flags = 0;
1017 		ehdr->e_ehsize = sizeof(Elf_Ehdr);
1018 		ehdr->e_phentsize = sizeof(Elf_Phdr);
1019 		ehdr->e_phnum = numsegs + 1;
1020 		ehdr->e_shentsize = sizeof(Elf_Shdr);
1021 		ehdr->e_shnum = 0;
1022 		ehdr->e_shstrndx = SHN_UNDEF;
1023 
1024 		/*
1025 		 * Fill in the program header entries.
1026 		 */
1027 		phdr = (Elf_Phdr *)((char *)dst + phoff);
1028 
1029 		/* The note segement. */
1030 		phdr->p_type = PT_NOTE;
1031 		phdr->p_offset = noteoff;
1032 		phdr->p_vaddr = 0;
1033 		phdr->p_paddr = 0;
1034 		phdr->p_filesz = notesz;
1035 		phdr->p_memsz = 0;
1036 		phdr->p_flags = 0;
1037 		phdr->p_align = 0;
1038 		phdr++;
1039 
1040 		/* All the writable segments from the program. */
1041 		phc.phdr = phdr;
1042 		phc.offset = *off;
1043 		each_writable_segment(p, cb_put_phdr, &phc);
1044 	}
1045 }
1046 
1047 static void
1048 elf_putnote(void *dst, size_t *off, const char *name, int type,
1049     const void *desc, size_t descsz)
1050 {
1051 	Elf_Note note;
1052 
1053 	note.n_namesz = strlen(name) + 1;
1054 	note.n_descsz = descsz;
1055 	note.n_type = type;
1056 	if (dst != NULL)
1057 		bcopy(&note, (char *)dst + *off, sizeof note);
1058 	*off += sizeof note;
1059 	if (dst != NULL)
1060 		bcopy(name, (char *)dst + *off, note.n_namesz);
1061 	*off += roundup2(note.n_namesz, sizeof(Elf_Size));
1062 	if (dst != NULL)
1063 		bcopy(desc, (char *)dst + *off, note.n_descsz);
1064 	*off += roundup2(note.n_descsz, sizeof(Elf_Size));
1065 }
1066 
1067 /*
1068  * Tell kern_execve.c about it, with a little help from the linker.
1069  */
1070 static struct execsw elf_execsw = {exec_elf_imgact, "ELF"};
1071 EXEC_SET(elf, elf_execsw);
1072