imgact_elf.c revision 81799
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: head/sys/kern/imgact_elf.c 81799 2001-08-16 20:16:20Z peter $
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
75static int elf_check_header __P((const Elf_Ehdr *hdr));
76static int elf_freebsd_fixup __P((register_t **stack_base,
77    struct image_params *imgp));
78static int elf_load_file __P((struct proc *p, const char *file, u_long *addr,
79    u_long *entry));
80static 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));
84static int exec_elf_imgact __P((struct image_params *imgp));
85
86static int elf_trace = 0;
87SYSCTL_INT(_debug, OID_AUTO, elf_trace, CTLFLAG_RW, &elf_trace, 0, "");
88
89struct 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
109static Elf_Brandinfo freebsd_brand_info = {
110						ELFOSABI_FREEBSD,
111						"FreeBSD",
112						"",
113						"/usr/libexec/ld-elf.so.1",
114						&elf_freebsd_sysvec
115					  };
116static Elf_Brandinfo *elf_brand_list[MAX_BRANDS] = {
117							&freebsd_brand_info,
118							NULL, NULL, NULL,
119							NULL, NULL, NULL, NULL
120						    };
121
122int
123elf_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
138int
139elf_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
154int
155elf_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
172static int
173elf_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
190static int
191elf_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 */
326static int
327elf_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
444fail:
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 */
461int fallback_elf_brand = -1;
462SYSCTL_INT(_kern, OID_AUTO, fallback_elf_brand, CTLFLAG_RW,
463		&fallback_elf_brand, -1,
464		"ELF brand of last resort");
465
466static int
467exec_elf_imgact(struct image_params *imgp)
468{
469	const Elf_Ehdr *hdr = (const Elf_Ehdr *) imgp->image_header;
470	const Elf_Phdr *phdr;
471	Elf_Auxargs *elf_auxargs = NULL;
472	struct vmspace *vmspace;
473	vm_prot_t prot;
474	u_long text_size = 0, data_size = 0;
475	u_long text_addr = 0, data_addr = 0;
476	u_long addr, entry = 0, proghdr = 0;
477	int error, i;
478	const char *interp = NULL;
479	Elf_Brandinfo *brand_info;
480	char *path;
481
482	GIANT_REQUIRED;
483
484	/*
485	 * Do we have a valid ELF header ?
486	 */
487	if (elf_check_header(hdr) != 0 || hdr->e_type != ET_EXEC)
488		return -1;
489
490	/*
491	 * From here on down, we return an errno, not -1, as we've
492	 * detected an ELF file.
493	 */
494
495	if ((hdr->e_phoff > PAGE_SIZE) ||
496	    (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
497		/* Only support headers in first page for now */
498		return ENOEXEC;
499	}
500	phdr = (const Elf_Phdr*)(imgp->image_header + hdr->e_phoff);
501
502	/*
503	 * From this point on, we may have resources that need to be freed.
504	 */
505
506	/*
507	 * Yeah, I'm paranoid.  There is every reason in the world to get
508	 * VTEXT now since from here on out, there are places we can have
509	 * a context switch.  Better safe than sorry; I really don't want
510	 * the file to change while it's being loaded.
511	 */
512	mtx_lock(&imgp->vp->v_interlock);
513	imgp->vp->v_flag |= VTEXT;
514	mtx_unlock(&imgp->vp->v_interlock);
515
516	if ((error = exec_extract_strings(imgp)) != 0)
517		goto fail;
518
519	exec_new_vmspace(imgp);
520
521	vmspace = imgp->proc->p_vmspace;
522
523	for (i = 0; i < hdr->e_phnum; i++) {
524		switch(phdr[i].p_type) {
525
526		case PT_LOAD:	/* Loadable segment */
527			prot = 0;
528			if (phdr[i].p_flags & PF_X)
529  				prot |= VM_PROT_EXECUTE;
530			if (phdr[i].p_flags & PF_W)
531  				prot |= VM_PROT_WRITE;
532			if (phdr[i].p_flags & PF_R)
533  				prot |= VM_PROT_READ;
534
535			if ((error = elf_load_section(imgp->proc,
536						     vmspace, imgp->vp,
537  						     phdr[i].p_offset,
538  						     (caddr_t)phdr[i].p_vaddr,
539  						     phdr[i].p_memsz,
540  						     phdr[i].p_filesz, prot)) != 0)
541  				goto fail;
542
543			/*
544			 * Is this .text or .data ??
545			 *
546			 * We only handle one each of those yet XXX
547			 */
548			if (hdr->e_entry >= phdr[i].p_vaddr &&
549			hdr->e_entry <(phdr[i].p_vaddr+phdr[i].p_memsz)) {
550  				text_addr = trunc_page(phdr[i].p_vaddr);
551  				text_size = round_page(phdr[i].p_memsz +
552						       phdr[i].p_vaddr -
553						       text_addr);
554				entry = (u_long)hdr->e_entry;
555			} else {
556  				data_addr = trunc_page(phdr[i].p_vaddr);
557  				data_size = round_page(phdr[i].p_memsz +
558						       phdr[i].p_vaddr -
559						       data_addr);
560			}
561			break;
562	  	case PT_INTERP:	/* Path to interpreter */
563			if (phdr[i].p_filesz > MAXPATHLEN ||
564			    phdr[i].p_offset + phdr[i].p_filesz > PAGE_SIZE) {
565				error = ENOEXEC;
566				goto fail;
567			}
568			interp = imgp->image_header + phdr[i].p_offset;
569			break;
570		case PT_PHDR: 	/* Program header table info */
571			proghdr = phdr[i].p_vaddr;
572			break;
573		default:
574			break;
575		}
576	}
577
578	vmspace->vm_tsize = text_size >> PAGE_SHIFT;
579	vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
580	vmspace->vm_dsize = data_size >> PAGE_SHIFT;
581	vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
582
583	addr = ELF_RTLD_ADDR(vmspace);
584
585	imgp->entry_addr = entry;
586
587	brand_info = NULL;
588
589	/* We support three types of branding -- (1) the ELF EI_OSABI field
590	 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
591	 * branding w/in the ELF header, and (3) path of the `interp_path'
592	 * field.  We should also look for an ".note.ABI-tag" ELF section now
593	 * in all Linux ELF binaries, FreeBSD 4.1+, and some NetBSD ones.
594	 */
595
596	/* If the executable has a brand, search for it in the brand list. */
597	if (brand_info == NULL) {
598		for (i = 0;  i < MAX_BRANDS;  i++) {
599			Elf_Brandinfo *bi = elf_brand_list[i];
600
601			if (bi != NULL &&
602			    (hdr->e_ident[EI_OSABI] == bi->brand
603			    || 0 ==
604			    strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
605			    bi->compat_3_brand, strlen(bi->compat_3_brand)))) {
606				brand_info = bi;
607				break;
608			}
609		}
610	}
611
612	/* Lacking a known brand, search for a recognized interpreter. */
613	if (brand_info == NULL && interp != NULL) {
614		for (i = 0;  i < MAX_BRANDS;  i++) {
615			Elf_Brandinfo *bi = elf_brand_list[i];
616
617			if (bi != NULL &&
618			    strcmp(interp, bi->interp_path) == 0) {
619				brand_info = bi;
620				break;
621			}
622		}
623	}
624
625	/* Lacking a recognized interpreter, try the default brand */
626	if (brand_info == NULL) {
627		for (i = 0; i < MAX_BRANDS; i++) {
628			Elf_Brandinfo *bi = elf_brand_list[i];
629
630			if (bi != NULL && fallback_elf_brand == bi->brand) {
631				brand_info = bi;
632				break;
633			}
634		}
635	}
636
637	if (brand_info == NULL) {
638		uprintf("ELF binary type \"%u\" not known.\n",
639		    hdr->e_ident[EI_OSABI]);
640		error = ENOEXEC;
641		goto fail;
642	}
643
644	imgp->proc->p_sysent = brand_info->sysvec;
645	if (interp != NULL) {
646		path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
647	        snprintf(path, sizeof(path), "%s%s",
648			 brand_info->emul_path, interp);
649		if ((error = elf_load_file(imgp->proc, path, &addr,
650					   &imgp->entry_addr)) != 0) {
651		        if ((error = elf_load_file(imgp->proc, interp, &addr,
652						   &imgp->entry_addr)) != 0) {
653			        uprintf("ELF interpreter %s not found\n", path);
654				free(path, M_TEMP);
655				goto fail;
656			}
657                }
658		free(path, M_TEMP);
659	}
660
661	/*
662	 * Construct auxargs table (used by the fixup routine)
663	 */
664	elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
665	elf_auxargs->execfd = -1;
666	elf_auxargs->phdr = proghdr;
667	elf_auxargs->phent = hdr->e_phentsize;
668	elf_auxargs->phnum = hdr->e_phnum;
669	elf_auxargs->pagesz = PAGE_SIZE;
670	elf_auxargs->base = addr;
671	elf_auxargs->flags = 0;
672	elf_auxargs->entry = entry;
673	elf_auxargs->trace = elf_trace;
674
675	imgp->auxargs = elf_auxargs;
676	imgp->interpreted = 0;
677
678fail:
679	return error;
680}
681
682static int
683elf_freebsd_fixup(register_t **stack_base, struct image_params *imgp)
684{
685	Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
686	register_t *pos;
687
688	pos = *stack_base + (imgp->argc + imgp->envc + 2);
689
690	if (args->trace) {
691		AUXARGS_ENTRY(pos, AT_DEBUG, 1);
692	}
693	if (args->execfd != -1) {
694		AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
695	}
696	AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
697	AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
698	AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
699	AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
700	AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
701	AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
702	AUXARGS_ENTRY(pos, AT_BASE, args->base);
703	AUXARGS_ENTRY(pos, AT_NULL, 0);
704
705	free(imgp->auxargs, M_TEMP);
706	imgp->auxargs = NULL;
707
708	(*stack_base)--;
709	suword(*stack_base, (long) imgp->argc);
710	return 0;
711}
712
713/*
714 * Code for generating ELF core dumps.
715 */
716
717typedef void (*segment_callback) __P((vm_map_entry_t, void *));
718
719/* Closure for cb_put_phdr(). */
720struct phdr_closure {
721	Elf_Phdr *phdr;		/* Program header to fill in */
722	Elf_Off offset;		/* Offset of segment in core file */
723};
724
725/* Closure for cb_size_segment(). */
726struct sseg_closure {
727	int count;		/* Count of writable segments. */
728	size_t size;		/* Total size of all writable segments. */
729};
730
731static void cb_put_phdr __P((vm_map_entry_t, void *));
732static void cb_size_segment __P((vm_map_entry_t, void *));
733static void each_writable_segment __P((struct proc *, segment_callback,
734    void *));
735static int elf_corehdr __P((struct proc *, struct vnode *, struct ucred *,
736    int, void *, size_t));
737static void elf_puthdr __P((struct proc *, void *, size_t *,
738    const prstatus_t *, const prfpregset_t *, const prpsinfo_t *, int));
739static void elf_putnote __P((void *, size_t *, const char *, int,
740    const void *, size_t));
741
742extern int osreldate;
743
744int
745elf_coredump(p, vp, limit)
746	register struct proc *p;
747	register struct vnode *vp;
748	off_t limit;
749{
750	register struct ucred *cred = p->p_ucred;
751	int error = 0;
752	struct sseg_closure seginfo;
753	void *hdr;
754	size_t hdrsize;
755
756	/* Size the program segments. */
757	seginfo.count = 0;
758	seginfo.size = 0;
759	each_writable_segment(p, cb_size_segment, &seginfo);
760
761	/*
762	 * Calculate the size of the core file header area by making
763	 * a dry run of generating it.  Nothing is written, but the
764	 * size is calculated.
765	 */
766	hdrsize = 0;
767	elf_puthdr((struct proc *)NULL, (void *)NULL, &hdrsize,
768	    (const prstatus_t *)NULL, (const prfpregset_t *)NULL,
769	    (const prpsinfo_t *)NULL, seginfo.count);
770
771	if (hdrsize + seginfo.size >= limit)
772		return (EFAULT);
773
774	/*
775	 * Allocate memory for building the header, fill it up,
776	 * and write it out.
777	 */
778	hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
779	if (hdr == NULL) {
780		return EINVAL;
781	}
782	error = elf_corehdr(p, vp, cred, seginfo.count, hdr, hdrsize);
783
784	/* Write the contents of all of the writable segments. */
785	if (error == 0) {
786		Elf_Phdr *php;
787		off_t offset;
788		int i;
789
790		php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
791		offset = hdrsize;
792		for (i = 0;  i < seginfo.count;  i++) {
793			error = vn_rdwr(UIO_WRITE, vp, (caddr_t)php->p_vaddr,
794			    php->p_filesz, offset, UIO_USERSPACE,
795			    IO_NODELOCKED|IO_UNIT, cred, (int *)NULL, p);
796			if (error != 0)
797				break;
798			offset += php->p_filesz;
799			php++;
800		}
801	}
802	free(hdr, M_TEMP);
803
804	return error;
805}
806
807/*
808 * A callback for each_writable_segment() to write out the segment's
809 * program header entry.
810 */
811static void
812cb_put_phdr(entry, closure)
813	vm_map_entry_t entry;
814	void *closure;
815{
816	struct phdr_closure *phc = (struct phdr_closure *)closure;
817	Elf_Phdr *phdr = phc->phdr;
818
819	phc->offset = round_page(phc->offset);
820
821	phdr->p_type = PT_LOAD;
822	phdr->p_offset = phc->offset;
823	phdr->p_vaddr = entry->start;
824	phdr->p_paddr = 0;
825	phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
826	phdr->p_align = PAGE_SIZE;
827	phdr->p_flags = 0;
828	if (entry->protection & VM_PROT_READ)
829		phdr->p_flags |= PF_R;
830	if (entry->protection & VM_PROT_WRITE)
831		phdr->p_flags |= PF_W;
832	if (entry->protection & VM_PROT_EXECUTE)
833		phdr->p_flags |= PF_X;
834
835	phc->offset += phdr->p_filesz;
836	phc->phdr++;
837}
838
839/*
840 * A callback for each_writable_segment() to gather information about
841 * the number of segments and their total size.
842 */
843static void
844cb_size_segment(entry, closure)
845	vm_map_entry_t entry;
846	void *closure;
847{
848	struct sseg_closure *ssc = (struct sseg_closure *)closure;
849
850	ssc->count++;
851	ssc->size += entry->end - entry->start;
852}
853
854/*
855 * For each writable segment in the process's memory map, call the given
856 * function with a pointer to the map entry and some arbitrary
857 * caller-supplied data.
858 */
859static void
860each_writable_segment(p, func, closure)
861	struct proc *p;
862	segment_callback func;
863	void *closure;
864{
865	vm_map_t map = &p->p_vmspace->vm_map;
866	vm_map_entry_t entry;
867
868	for (entry = map->header.next;  entry != &map->header;
869	    entry = entry->next) {
870		vm_object_t obj;
871
872		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) ||
873		    (entry->protection & (VM_PROT_READ|VM_PROT_WRITE)) !=
874		    (VM_PROT_READ|VM_PROT_WRITE))
875			continue;
876
877		/*
878		** Dont include memory segment in the coredump if
879		** MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
880		** madvise(2).
881		*/
882		if (entry->eflags & MAP_ENTRY_NOCOREDUMP)
883			continue;
884
885		if ((obj = entry->object.vm_object) == NULL)
886			continue;
887
888		/* Find the deepest backing object. */
889		while (obj->backing_object != NULL)
890			obj = obj->backing_object;
891
892		/* Ignore memory-mapped devices and such things. */
893		if (obj->type != OBJT_DEFAULT &&
894		    obj->type != OBJT_SWAP &&
895		    obj->type != OBJT_VNODE)
896			continue;
897
898		(*func)(entry, closure);
899	}
900}
901
902/*
903 * Write the core file header to the file, including padding up to
904 * the page boundary.
905 */
906static int
907elf_corehdr(p, vp, cred, numsegs, hdr, hdrsize)
908	struct proc *p;
909	struct vnode *vp;
910	struct ucred *cred;
911	int numsegs;
912	size_t hdrsize;
913	void *hdr;
914{
915	struct {
916		prstatus_t status;
917		prfpregset_t fpregset;
918		prpsinfo_t psinfo;
919	} *tempdata;
920	size_t off;
921	prstatus_t *status;
922	prfpregset_t *fpregset;
923	prpsinfo_t *psinfo;
924
925	tempdata = malloc(sizeof(*tempdata), M_TEMP, M_ZERO);
926	status = &tempdata->status;
927	fpregset = &tempdata->fpregset;
928	psinfo = &tempdata->psinfo;
929
930	/* Gather the information for the header. */
931	status->pr_version = PRSTATUS_VERSION;
932	status->pr_statussz = sizeof(prstatus_t);
933	status->pr_gregsetsz = sizeof(gregset_t);
934	status->pr_fpregsetsz = sizeof(fpregset_t);
935	status->pr_osreldate = osreldate;
936	status->pr_cursig = p->p_sig;
937	status->pr_pid = p->p_pid;
938	fill_regs(p, &status->pr_reg);
939
940	fill_fpregs(p, fpregset);
941
942	psinfo->pr_version = PRPSINFO_VERSION;
943	psinfo->pr_psinfosz = sizeof(prpsinfo_t);
944	strncpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname) - 1);
945
946	/* XXX - We don't fill in the command line arguments properly yet. */
947	strncpy(psinfo->pr_psargs, p->p_comm, PRARGSZ);
948
949	/* Fill in the header. */
950	bzero(hdr, hdrsize);
951	off = 0;
952	elf_puthdr(p, hdr, &off, status, fpregset, psinfo, numsegs);
953
954	free(tempdata, M_TEMP);
955
956	/* Write it to the core file. */
957	return vn_rdwr(UIO_WRITE, vp, hdr, hdrsize, (off_t)0,
958	    UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT, cred, NULL, p);
959}
960
961static void
962elf_puthdr(struct proc *p, void *dst, size_t *off, const prstatus_t *status,
963    const prfpregset_t *fpregset, const prpsinfo_t *psinfo, int numsegs)
964{
965	size_t ehoff;
966	size_t phoff;
967	size_t noteoff;
968	size_t notesz;
969
970	ehoff = *off;
971	*off += sizeof(Elf_Ehdr);
972
973	phoff = *off;
974	*off += (numsegs + 1) * sizeof(Elf_Phdr);
975
976	noteoff = *off;
977	elf_putnote(dst, off, "FreeBSD", NT_PRSTATUS, status,
978	    sizeof *status);
979	elf_putnote(dst, off, "FreeBSD", NT_FPREGSET, fpregset,
980	    sizeof *fpregset);
981	elf_putnote(dst, off, "FreeBSD", NT_PRPSINFO, psinfo,
982	    sizeof *psinfo);
983	notesz = *off - noteoff;
984
985	/* Align up to a page boundary for the program segments. */
986	*off = round_page(*off);
987
988	if (dst != NULL) {
989		Elf_Ehdr *ehdr;
990		Elf_Phdr *phdr;
991		struct phdr_closure phc;
992
993		/*
994		 * Fill in the ELF header.
995		 */
996		ehdr = (Elf_Ehdr *)((char *)dst + ehoff);
997		ehdr->e_ident[EI_MAG0] = ELFMAG0;
998		ehdr->e_ident[EI_MAG1] = ELFMAG1;
999		ehdr->e_ident[EI_MAG2] = ELFMAG2;
1000		ehdr->e_ident[EI_MAG3] = ELFMAG3;
1001		ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1002		ehdr->e_ident[EI_DATA] = ELF_DATA;
1003		ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1004		ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1005		ehdr->e_ident[EI_ABIVERSION] = 0;
1006		ehdr->e_ident[EI_PAD] = 0;
1007		ehdr->e_type = ET_CORE;
1008		ehdr->e_machine = ELF_ARCH;
1009		ehdr->e_version = EV_CURRENT;
1010		ehdr->e_entry = 0;
1011		ehdr->e_phoff = phoff;
1012		ehdr->e_flags = 0;
1013		ehdr->e_ehsize = sizeof(Elf_Ehdr);
1014		ehdr->e_phentsize = sizeof(Elf_Phdr);
1015		ehdr->e_phnum = numsegs + 1;
1016		ehdr->e_shentsize = sizeof(Elf_Shdr);
1017		ehdr->e_shnum = 0;
1018		ehdr->e_shstrndx = SHN_UNDEF;
1019
1020		/*
1021		 * Fill in the program header entries.
1022		 */
1023		phdr = (Elf_Phdr *)((char *)dst + phoff);
1024
1025		/* The note segement. */
1026		phdr->p_type = PT_NOTE;
1027		phdr->p_offset = noteoff;
1028		phdr->p_vaddr = 0;
1029		phdr->p_paddr = 0;
1030		phdr->p_filesz = notesz;
1031		phdr->p_memsz = 0;
1032		phdr->p_flags = 0;
1033		phdr->p_align = 0;
1034		phdr++;
1035
1036		/* All the writable segments from the program. */
1037		phc.phdr = phdr;
1038		phc.offset = *off;
1039		each_writable_segment(p, cb_put_phdr, &phc);
1040	}
1041}
1042
1043static void
1044elf_putnote(void *dst, size_t *off, const char *name, int type,
1045    const void *desc, size_t descsz)
1046{
1047	Elf_Note note;
1048
1049	note.n_namesz = strlen(name) + 1;
1050	note.n_descsz = descsz;
1051	note.n_type = type;
1052	if (dst != NULL)
1053		bcopy(&note, (char *)dst + *off, sizeof note);
1054	*off += sizeof note;
1055	if (dst != NULL)
1056		bcopy(name, (char *)dst + *off, note.n_namesz);
1057	*off += roundup2(note.n_namesz, sizeof(Elf_Size));
1058	if (dst != NULL)
1059		bcopy(desc, (char *)dst + *off, note.n_descsz);
1060	*off += roundup2(note.n_descsz, sizeof(Elf_Size));
1061}
1062
1063/*
1064 * Tell kern_execve.c about it, with a little help from the linker.
1065 */
1066static struct execsw elf_execsw = {exec_elf_imgact, "ELF"};
1067EXEC_SET(elf, elf_execsw);
1068