xref: /dragonfly/sys/kern/imgact_elf.c (revision fe76c4fb)
1 /*-
2  * Copyright (c) 1995-1996 S�ren Schmidt
3  * Copyright (c) 1996 Peter Wemm
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer
11  *    in this position and unchanged.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software withough specific prior written permission
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  * $FreeBSD: src/sys/kern/imgact_elf.c,v 1.73.2.13 2002/12/28 19:49:41 dillon Exp $
30  * $DragonFly: src/sys/kern/imgact_elf.c,v 1.39 2006/05/25 04:17:09 dillon Exp $
31  */
32 
33 #include <sys/param.h>
34 #include <sys/exec.h>
35 #include <sys/fcntl.h>
36 #include <sys/file.h>
37 #include <sys/imgact.h>
38 #include <sys/imgact_elf.h>
39 #include <sys/kernel.h>
40 #include <sys/malloc.h>
41 #include <sys/mman.h>
42 #include <sys/systm.h>
43 #include <sys/proc.h>
44 #include <sys/nlookup.h>
45 #include <sys/pioctl.h>
46 #include <sys/procfs.h>
47 #include <sys/resourcevar.h>
48 #include <sys/signalvar.h>
49 #include <sys/stat.h>
50 #include <sys/syscall.h>
51 #include <sys/sysctl.h>
52 #include <sys/sysent.h>
53 #include <sys/vnode.h>
54 
55 #include <vm/vm.h>
56 #include <vm/vm_kern.h>
57 #include <vm/vm_param.h>
58 #include <vm/pmap.h>
59 #include <sys/lock.h>
60 #include <vm/vm_map.h>
61 #include <vm/vm_object.h>
62 #include <vm/vm_extern.h>
63 
64 #include <machine/elf.h>
65 #include <machine/md_var.h>
66 #include <sys/mount.h>
67 #include <sys/ckpt.h>
68 #define OLD_EI_BRAND	8
69 
70 __ElfType(Brandinfo);
71 __ElfType(Auxargs);
72 
73 static int elf_check_header (const Elf_Ehdr *hdr);
74 static int elf_freebsd_fixup (register_t **stack_base,
75     struct image_params *imgp);
76 static int elf_load_file (struct proc *p, const char *file, u_long *addr,
77     u_long *entry);
78 static int elf_load_section (struct proc *p,
79     struct vmspace *vmspace, struct vnode *vp,
80     vm_offset_t offset, caddr_t vmaddr, size_t memsz, size_t filsz,
81     vm_prot_t prot);
82 static int exec_elf_imgact (struct image_params *imgp);
83 
84 static int elf_trace = 0;
85 SYSCTL_INT(_debug, OID_AUTO, elf_trace, CTLFLAG_RW, &elf_trace, 0, "");
86 static int elf_legacy_coredump = 0;
87 SYSCTL_INT(_debug, OID_AUTO, elf_legacy_coredump, CTLFLAG_RW,
88     &elf_legacy_coredump, 0, "");
89 
90 static int dragonfly_match_abi_note(const Elf_Note *);
91 static int freebsd_match_abi_note(const Elf_Note *);
92 
93 static struct sysentvec elf_freebsd_sysvec = {
94         SYS_MAXSYSCALL,
95         sysent,
96         -1,
97         0,
98         0,
99         0,
100         0,
101         0,
102         elf_freebsd_fixup,
103         sendsig,
104         sigcode,
105         &szsigcode,
106         0,
107 	"FreeBSD ELF",
108 	elf_coredump,
109 	NULL,
110 	MINSIGSTKSZ
111 };
112 
113 static Elf_Brandinfo freebsd_brand_info = {
114 						ELFOSABI_FREEBSD,
115 						"FreeBSD",
116 						freebsd_match_abi_note,
117 						"",
118 						"/usr/libexec/ld-elf.so.1",
119 						&elf_freebsd_sysvec
120 					  };
121 
122 static Elf_Brandinfo dragonfly_brand_info = {
123 						ELFOSABI_NONE,
124 						"DragonFly",
125 						dragonfly_match_abi_note,
126 						"",
127 						"/usr/libexec/ld-elf.so.2",
128 						&elf_freebsd_sysvec
129 					  };
130 
131 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS] = {
132 							&dragonfly_brand_info,
133 							&freebsd_brand_info,
134 							NULL, NULL, NULL,
135 							NULL, NULL, NULL
136 						    };
137 
138 static int
139 freebsd_match_abi_note(const Elf_Note *abi_note)
140 {
141 	const char *abi_name = (const char *)
142 	    ((const uint8_t *)abi_note + sizeof(*abi_note));
143 
144 	if (abi_note->n_namesz != sizeof("FreeBSD"))
145 		return(FALSE);
146 	if (memcmp(abi_name, "FreeBSD", sizeof("FreeBSD")))
147 		return(FALSE);
148 	return(TRUE);
149 }
150 
151 static int
152 dragonfly_match_abi_note(const Elf_Note *abi_note)
153 {
154 	const char *abi_name = (const char *)
155 	    ((const uint8_t *)abi_note + sizeof(*abi_note));
156 
157 	if (abi_note->n_namesz != sizeof("DragonFly"))
158 		return(FALSE);
159 	if (memcmp(abi_name, "DragonFly", sizeof("DragonFly")))
160 		return(FALSE);
161 	return(TRUE);
162 }
163 
164 int
165 elf_insert_brand_entry(Elf_Brandinfo *entry)
166 {
167 	int i;
168 
169 	for (i=1; i<MAX_BRANDS; i++) {
170 		if (elf_brand_list[i] == NULL) {
171 			elf_brand_list[i] = entry;
172 			break;
173 		}
174 	}
175 	if (i == MAX_BRANDS)
176 		return -1;
177 	return 0;
178 }
179 
180 int
181 elf_remove_brand_entry(Elf_Brandinfo *entry)
182 {
183 	int i;
184 
185 	for (i=1; i<MAX_BRANDS; i++) {
186 		if (elf_brand_list[i] == entry) {
187 			elf_brand_list[i] = NULL;
188 			break;
189 		}
190 	}
191 	if (i == MAX_BRANDS)
192 		return -1;
193 	return 0;
194 }
195 
196 /*
197  * Check if an elf brand is being used anywhere in the system.
198  *
199  * Used by the linux emulatino module unloader.  This isn't safe from
200  * races.
201  */
202 struct elf_brand_inuse_info {
203 	int rval;
204 	Elf_Brandinfo *entry;
205 };
206 
207 static int elf_brand_inuse_callback(struct proc *p, void *data);
208 
209 int
210 elf_brand_inuse(Elf_Brandinfo *entry)
211 {
212 	struct elf_brand_inuse_info info;
213 
214 	info.rval = FALSE;
215 	info.entry = entry;
216 	allproc_scan(elf_brand_inuse_callback, entry);
217 	return (info.rval);
218 }
219 
220 static
221 int
222 elf_brand_inuse_callback(struct proc *p, void *data)
223 {
224 	struct elf_brand_inuse_info *info = data;
225 
226 	if (p->p_sysent == info->entry->sysvec) {
227 		info->rval = TRUE;
228 		return(-1);
229 	}
230 	return(0);
231 }
232 
233 static int
234 elf_check_header(const Elf_Ehdr *hdr)
235 {
236 	if (!IS_ELF(*hdr) ||
237 	    hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
238 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
239 	    hdr->e_ident[EI_VERSION] != EV_CURRENT ||
240 	    hdr->e_phentsize != sizeof(Elf_Phdr) ||
241 	    hdr->e_ehsize != sizeof(Elf_Ehdr) ||
242 	    hdr->e_version != ELF_TARG_VER)
243 		return ENOEXEC;
244 
245 	if (!ELF_MACHINE_OK(hdr->e_machine))
246 		return ENOEXEC;
247 
248 	return 0;
249 }
250 
251 static int
252 elf_load_section(struct proc *p, struct vmspace *vmspace, struct vnode *vp,
253 		 vm_offset_t offset, caddr_t vmaddr, size_t memsz,
254 		 size_t filsz, vm_prot_t prot)
255 {
256 	size_t map_len;
257 	vm_offset_t map_addr;
258 	int error, rv, cow;
259 	int count;
260 	size_t copy_len;
261 	vm_object_t object;
262 	vm_offset_t file_addr;
263 	vm_offset_t data_buf = 0;
264 
265 	object = vp->v_object;
266 	error = 0;
267 
268 	/*
269 	 * It's necessary to fail if the filsz + offset taken from the
270 	 * header is greater than the actual file pager object's size.
271 	 * If we were to allow this, then the vm_map_find() below would
272 	 * walk right off the end of the file object and into the ether.
273 	 *
274 	 * While I'm here, might as well check for something else that
275 	 * is invalid: filsz cannot be greater than memsz.
276 	 */
277 	if ((off_t)filsz + offset > vp->v_filesize || filsz > memsz) {
278 		uprintf("elf_load_section: truncated ELF file\n");
279 		return (ENOEXEC);
280 	}
281 
282 	map_addr = trunc_page((vm_offset_t)vmaddr);
283 	file_addr = trunc_page(offset);
284 
285 	/*
286 	 * We have two choices.  We can either clear the data in the last page
287 	 * of an oversized mapping, or we can start the anon mapping a page
288 	 * early and copy the initialized data into that first page.  We
289 	 * choose the second..
290 	 */
291 	if (memsz > filsz)
292 		map_len = trunc_page(offset+filsz) - file_addr;
293 	else
294 		map_len = round_page(offset+filsz) - file_addr;
295 
296 	if (map_len != 0) {
297 		vm_object_reference(object);
298 
299 		/* cow flags: don't dump readonly sections in core */
300 		cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
301 		    (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
302 
303 		count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
304 		vm_map_lock(&vmspace->vm_map);
305 		rv = vm_map_insert(&vmspace->vm_map, &count,
306 				      object,
307 				      file_addr,	/* file offset */
308 				      map_addr,		/* virtual start */
309 				      map_addr + map_len,/* virtual end */
310 				      prot,
311 				      VM_PROT_ALL,
312 				      cow);
313 		vm_map_unlock(&vmspace->vm_map);
314 		vm_map_entry_release(count);
315 		if (rv != KERN_SUCCESS) {
316 			vm_object_deallocate(object);
317 			return EINVAL;
318 		}
319 
320 		/* we can stop now if we've covered it all */
321 		if (memsz == filsz) {
322 			return 0;
323 		}
324 	}
325 
326 
327 	/*
328 	 * We have to get the remaining bit of the file into the first part
329 	 * of the oversized map segment.  This is normally because the .data
330 	 * segment in the file is extended to provide bss.  It's a neat idea
331 	 * to try and save a page, but it's a pain in the behind to implement.
332 	 */
333 	copy_len = (offset + filsz) - trunc_page(offset + filsz);
334 	map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
335 	map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
336 
337 	/* This had damn well better be true! */
338         if (map_len != 0) {
339 		count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
340 		vm_map_lock(&vmspace->vm_map);
341 		rv = vm_map_insert(&vmspace->vm_map, &count,
342 					NULL, 0,
343 					map_addr, map_addr + map_len,
344 					VM_PROT_ALL, VM_PROT_ALL, 0);
345 		vm_map_unlock(&vmspace->vm_map);
346 		vm_map_entry_release(count);
347 		if (rv != KERN_SUCCESS) {
348 			return EINVAL;
349 		}
350 	}
351 
352 	if (copy_len != 0) {
353 		vm_object_reference(object);
354 		rv = vm_map_find(exec_map,
355 				 object,
356 				 trunc_page(offset + filsz),
357 				 &data_buf,
358 				 PAGE_SIZE,
359 				 TRUE,
360 				 VM_PROT_READ,
361 				 VM_PROT_ALL,
362 				 MAP_COPY_ON_WRITE | MAP_PREFAULT_PARTIAL);
363 		if (rv != KERN_SUCCESS) {
364 			vm_object_deallocate(object);
365 			return EINVAL;
366 		}
367 
368 		/* send the page fragment to user space */
369 		error = copyout((caddr_t)data_buf, (caddr_t)map_addr, copy_len);
370 		vm_map_remove(exec_map, data_buf, data_buf + PAGE_SIZE);
371 		if (error) {
372 			return (error);
373 		}
374 	}
375 
376 	/*
377 	 * set it to the specified protection
378 	 */
379 	vm_map_protect(&vmspace->vm_map, map_addr, map_addr + map_len,  prot,
380 		       FALSE);
381 
382 	return error;
383 }
384 
385 /*
386  * Load the file "file" into memory.  It may be either a shared object
387  * or an executable.
388  *
389  * The "addr" reference parameter is in/out.  On entry, it specifies
390  * the address where a shared object should be loaded.  If the file is
391  * an executable, this value is ignored.  On exit, "addr" specifies
392  * where the file was actually loaded.
393  *
394  * The "entry" reference parameter is out only.  On exit, it specifies
395  * the entry point for the loaded file.
396  */
397 static int
398 elf_load_file(struct proc *p, const char *file, u_long *addr, u_long *entry)
399 {
400 	struct {
401 		struct nlookupdata nd;
402 		struct vattr attr;
403 		struct image_params image_params;
404 	} *tempdata;
405 	const Elf_Ehdr *hdr = NULL;
406 	const Elf_Phdr *phdr = NULL;
407 	struct nlookupdata *nd;
408 	struct vmspace *vmspace = p->p_vmspace;
409 	struct vattr *attr;
410 	struct image_params *imgp;
411 	vm_prot_t prot;
412 	u_long rbase;
413 	u_long base_addr = 0;
414 	int error, i, numsegs;
415 
416 	tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
417 	nd = &tempdata->nd;
418 	attr = &tempdata->attr;
419 	imgp = &tempdata->image_params;
420 
421 	/*
422 	 * Initialize part of the common data
423 	 */
424 	imgp->proc = p;
425 	imgp->attr = attr;
426 	imgp->firstpage = NULL;
427 	imgp->image_header = NULL;
428 	imgp->vp = NULL;
429 
430 	error = nlookup_init(nd, file, UIO_SYSSPACE, NLC_FOLLOW);
431 	if (error == 0)
432 		error = nlookup(nd);
433 	if (error == 0)
434 		error = cache_vget(nd->nl_ncp, nd->nl_cred, LK_EXCLUSIVE, &imgp->vp);
435 	nlookup_done(nd);
436 	if (error)
437 		goto fail;
438 
439 	/*
440 	 * Check permissions, modes, uid, etc on the file, and "open" it.
441 	 */
442 	error = exec_check_permissions(imgp);
443 	if (error) {
444 		VOP_UNLOCK(imgp->vp, 0);
445 		goto fail;
446 	}
447 
448 	error = exec_map_first_page(imgp);
449 	/*
450 	 * Also make certain that the interpreter stays the same, so set
451 	 * its VTEXT flag, too.
452 	 */
453 	if (error == 0)
454 		imgp->vp->v_flag |= VTEXT;
455 	VOP_UNLOCK(imgp->vp, 0);
456 	if (error)
457                 goto fail;
458 
459 	hdr = (const Elf_Ehdr *)imgp->image_header;
460 	if ((error = elf_check_header(hdr)) != 0)
461 		goto fail;
462 	if (hdr->e_type == ET_DYN)
463 		rbase = *addr;
464 	else if (hdr->e_type == ET_EXEC)
465 		rbase = 0;
466 	else {
467 		error = ENOEXEC;
468 		goto fail;
469 	}
470 
471 	/* Only support headers that fit within first page for now
472 	 * (multiplication of two Elf_Half fields will not overflow) */
473 	if ((hdr->e_phoff > PAGE_SIZE) ||
474 	    (hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE - hdr->e_phoff) {
475 		error = ENOEXEC;
476 		goto fail;
477 	}
478 
479 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
480 
481 	for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
482 		if (phdr[i].p_type == PT_LOAD) {	/* Loadable segment */
483 			prot = 0;
484 			if (phdr[i].p_flags & PF_X)
485   				prot |= VM_PROT_EXECUTE;
486 			if (phdr[i].p_flags & PF_W)
487   				prot |= VM_PROT_WRITE;
488 			if (phdr[i].p_flags & PF_R)
489   				prot |= VM_PROT_READ;
490 
491 			error = elf_load_section(
492 				    p, vmspace, imgp->vp,
493 				    phdr[i].p_offset,
494 				    (caddr_t)phdr[i].p_vaddr +
495 				    rbase,
496 				    phdr[i].p_memsz,
497 				    phdr[i].p_filesz, prot);
498 			if (error != 0)
499 				goto fail;
500 			/*
501 			 * Establish the base address if this is the
502 			 * first segment.
503 			 */
504 			if (numsegs == 0)
505   				base_addr = trunc_page(phdr[i].p_vaddr + rbase);
506 			numsegs++;
507 		}
508 	}
509 	*addr = base_addr;
510 	*entry=(unsigned long)hdr->e_entry + rbase;
511 
512 fail:
513 	if (imgp->firstpage)
514 		exec_unmap_first_page(imgp);
515 	if (imgp->vp) {
516 		vrele(imgp->vp);
517 		imgp->vp = NULL;
518 	}
519 	free(tempdata, M_TEMP);
520 
521 	return error;
522 }
523 
524 /*
525  * non static, as it can be overridden by start_init()
526  */
527 int fallback_elf_brand = -1;
528 SYSCTL_INT(_kern, OID_AUTO, fallback_elf_brand, CTLFLAG_RW,
529 		&fallback_elf_brand, -1,
530 		"ELF brand of last resort");
531 
532 static int
533 exec_elf_imgact(struct image_params *imgp)
534 {
535 	const Elf_Ehdr *hdr = (const Elf_Ehdr *) imgp->image_header;
536 	const Elf_Phdr *phdr;
537 	Elf_Auxargs *elf_auxargs = NULL;
538 	struct vmspace *vmspace;
539 	vm_prot_t prot;
540 	u_long text_size = 0, data_size = 0, total_size = 0;
541 	u_long text_addr = 0, data_addr = 0;
542 	u_long seg_size, seg_addr;
543 	u_long addr, entry = 0, proghdr = 0;
544 	int error, i;
545 	const char *interp = NULL;
546 	const Elf_Note *abi_note = NULL;
547 	Elf_Brandinfo *brand_info;
548 	char *path;
549 
550 	error = 0;
551 
552 	/*
553 	 * Do we have a valid ELF header ?
554 	 */
555 	if (elf_check_header(hdr) != 0 || hdr->e_type != ET_EXEC)
556 		return -1;
557 
558 	/*
559 	 * From here on down, we return an errno, not -1, as we've
560 	 * detected an ELF file.
561 	 */
562 
563 	if ((hdr->e_phoff > PAGE_SIZE) ||
564 	    (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
565 		/* Only support headers in first page for now */
566 		return ENOEXEC;
567 	}
568 	phdr = (const Elf_Phdr*)(imgp->image_header + hdr->e_phoff);
569 
570 	/*
571 	 * From this point on, we may have resources that need to be freed.
572 	 */
573 
574 	exec_new_vmspace(imgp, NULL);
575 
576 	/*
577 	 * Yeah, I'm paranoid.  There is every reason in the world to get
578 	 * VTEXT now since from here on out, there are places we can have
579 	 * a context switch.  Better safe than sorry; I really don't want
580 	 * the file to change while it's being loaded.
581 	 */
582 	vsetflags(imgp->vp, VTEXT);
583 
584 	vmspace = imgp->proc->p_vmspace;
585 
586 	for (i = 0; i < hdr->e_phnum; i++) {
587 		switch(phdr[i].p_type) {
588 
589 		case PT_LOAD:	/* Loadable segment */
590 			prot = 0;
591 			if (phdr[i].p_flags & PF_X)
592   				prot |= VM_PROT_EXECUTE;
593 			if (phdr[i].p_flags & PF_W)
594   				prot |= VM_PROT_WRITE;
595 			if (phdr[i].p_flags & PF_R)
596   				prot |= VM_PROT_READ;
597 
598 			if ((error = elf_load_section(imgp->proc,
599 						     vmspace, imgp->vp,
600   						     phdr[i].p_offset,
601   						     (caddr_t)phdr[i].p_vaddr,
602   						     phdr[i].p_memsz,
603   						     phdr[i].p_filesz, prot)) != 0)
604   				goto fail;
605 
606 			/*
607 			 * If this segment contains the program headers,
608 			 * remember their virtual address for the AT_PHDR
609 			 * aux entry. Static binaries don't usually include
610 			 * a PT_PHDR entry.
611 			 */
612 			if (phdr[i].p_offset == 0 &&
613 			    hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
614 				<= phdr[i].p_filesz)
615 				proghdr = phdr[i].p_vaddr + hdr->e_phoff;
616 
617 			seg_addr = trunc_page(phdr[i].p_vaddr);
618 			seg_size = round_page(phdr[i].p_memsz +
619 				phdr[i].p_vaddr - seg_addr);
620 
621 			/*
622 			 * Is this .text or .data?  We can't use
623 			 * VM_PROT_WRITE or VM_PROT_EXEC, it breaks the
624 			 * alpha terribly and possibly does other bad
625 			 * things so we stick to the old way of figuring
626 			 * it out:  If the segment contains the program
627 			 * entry point, it's a text segment, otherwise it
628 			 * is a data segment.
629 			 *
630 			 * Note that obreak() assumes that data_addr +
631 			 * data_size == end of data load area, and the ELF
632 			 * file format expects segments to be sorted by
633 			 * address.  If multiple data segments exist, the
634 			 * last one will be used.
635 			 */
636 			if (hdr->e_entry >= phdr[i].p_vaddr &&
637 			    hdr->e_entry < (phdr[i].p_vaddr +
638 			    phdr[i].p_memsz)) {
639 				text_size = seg_size;
640 				text_addr = seg_addr;
641 				entry = (u_long)hdr->e_entry;
642 			} else {
643 				data_size = seg_size;
644 				data_addr = seg_addr;
645 			}
646 			total_size += seg_size;
647 
648 			/*
649 			 * Check limits.  It should be safe to check the
650 			 * limits after loading the segment since we do
651 			 * not actually fault in all the segment's pages.
652 			 */
653 			if (data_size >
654 			    imgp->proc->p_rlimit[RLIMIT_DATA].rlim_cur ||
655 			    text_size > maxtsiz ||
656 			    total_size >
657 			    imgp->proc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
658 				error = ENOMEM;
659 				goto fail;
660 			}
661 			break;
662 	  	case PT_INTERP:	/* Path to interpreter */
663 			if (phdr[i].p_filesz > MAXPATHLEN ||
664 			    phdr[i].p_offset + phdr[i].p_filesz > PAGE_SIZE) {
665 				error = ENOEXEC;
666 				goto fail;
667 			}
668 			interp = imgp->image_header + phdr[i].p_offset;
669 			break;
670 		case PT_NOTE:	/* Check for .note.ABI-tag */
671 		{
672 			const Elf_Note *tmp_note;
673 			/* XXX handle anything outside the first page */
674 			if (phdr[i].p_offset + phdr[i].p_filesz > PAGE_SIZE)
675 				continue;
676 			if (phdr[i].p_filesz < sizeof(Elf_Note))
677 				continue; /* ENOEXEC? */
678 			tmp_note = (const Elf_Note *)(imgp->image_header + phdr[i].p_offset);
679 			if (tmp_note->n_type != 1)
680 				continue;
681 			if (tmp_note->n_namesz + sizeof(Elf_Note) +
682 			    tmp_note->n_descsz > phdr[i].p_filesz)
683 				continue; /* ENOEXEC? */
684 			abi_note = tmp_note;
685 		}
686 			break;
687 		case PT_PHDR: 	/* Program header table info */
688 			proghdr = phdr[i].p_vaddr;
689 			break;
690 		default:
691 			break;
692 		}
693 	}
694 
695 	vmspace->vm_tsize = text_size >> PAGE_SHIFT;
696 	vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
697 	vmspace->vm_dsize = data_size >> PAGE_SHIFT;
698 	vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
699 
700 	addr = ELF_RTLD_ADDR(vmspace);
701 
702 	imgp->entry_addr = entry;
703 
704 	brand_info = NULL;
705 
706 	/* We support three types of branding -- (1) the ELF EI_OSABI field
707 	 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
708 	 * branding w/in the ELF header, and (3) path of the `interp_path'
709 	 * field.  We should also look for an ".note.ABI-tag" ELF section now
710 	 * in all Linux ELF binaries, FreeBSD 4.1+, and some NetBSD ones.
711 	 */
712 
713 	/* If the executable has a brand, search for it in the brand list. */
714 	if (brand_info == NULL && hdr->e_ident[EI_OSABI] != ELFOSABI_NONE) {
715 		for (i = 0;  i < MAX_BRANDS;  i++) {
716 			Elf_Brandinfo *bi = elf_brand_list[i];
717 
718 			if (bi != NULL &&
719 			    (hdr->e_ident[EI_OSABI] == bi->brand
720 			    || 0 ==
721 			    strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
722 			    bi->compat_3_brand, strlen(bi->compat_3_brand)))) {
723 				brand_info = bi;
724 				break;
725 			}
726 		}
727 	}
728 
729 	/* Search for a recognized ABI. */
730 	if (brand_info == NULL && abi_note != NULL) {
731 		for (i = 0; i < MAX_BRANDS; i++) {
732 			Elf_Brandinfo *bi = elf_brand_list[i];
733 
734 			if (bi != NULL && bi->match_abi_note != NULL &&
735 			    (*bi->match_abi_note)(abi_note)) {
736 				brand_info = bi;
737 				break;
738 			}
739 		}
740 	}
741 
742 	/*
743 	 * ELFOSABI_NONE == ELFOSABI_SYSV, so a SYSV binary misses all
744 	 * checks so far, since it is neither branded nor does it have
745 	 * an ABI note.  If the EI_OSABI field is ELFOSABI_NONE, assume
746 	 * it is svr4 and look for an entry in the elf_brand_list with
747 	 * match_abi_note == NULL.
748 	 */
749 	if (brand_info == NULL && hdr->e_ident[EI_OSABI] == ELFOSABI_NONE) {
750 		for (i = 0; i < MAX_BRANDS; i++) {
751 			Elf_Brandinfo *bi = elf_brand_list[i];
752 
753 			if (bi != NULL && bi->match_abi_note == NULL &&
754 			    ELFOSABI_SYSV == bi->brand) {
755 				brand_info = bi;
756 				break;
757 			}
758 		}
759 	}
760 
761 	/* Lacking a recognized ABI, search for a recognized interpreter. */
762 	if (brand_info == NULL && interp != NULL) {
763 		for (i = 0;  i < MAX_BRANDS;  i++) {
764 			Elf_Brandinfo *bi = elf_brand_list[i];
765 
766 			if (bi != NULL &&
767 			    strcmp(interp, bi->interp_path) == 0) {
768 				brand_info = bi;
769 				break;
770 			}
771 		}
772 	}
773 
774 	/* Lacking a recognized interpreter, try the default brand */
775 	if (brand_info == NULL) {
776 		for (i = 0; i < MAX_BRANDS; i++) {
777 			Elf_Brandinfo *bi = elf_brand_list[i];
778 
779 			if (bi != NULL && fallback_elf_brand == bi->brand) {
780 				brand_info = bi;
781 				break;
782 			}
783 		}
784 	}
785 
786 	if (brand_info == NULL) {
787 		uprintf("ELF binary type \"%u\" not known.\n",
788 		    hdr->e_ident[EI_OSABI]);
789 		error = ENOEXEC;
790 		goto fail;
791 	}
792 
793 	imgp->proc->p_sysent = brand_info->sysvec;
794 	if (interp != NULL) {
795 		path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
796 	        snprintf(path, MAXPATHLEN, "%s%s",
797 			 brand_info->emul_path, interp);
798 		if ((error = elf_load_file(imgp->proc, path, &addr,
799 					   &imgp->entry_addr)) != 0) {
800 		        if ((error = elf_load_file(imgp->proc, interp, &addr,
801 						   &imgp->entry_addr)) != 0) {
802 			        uprintf("ELF interpreter %s not found\n", path);
803 				free(path, M_TEMP);
804 				goto fail;
805 			}
806                 }
807 		free(path, M_TEMP);
808 	}
809 
810 	/*
811 	 * Construct auxargs table (used by the fixup routine)
812 	 */
813 	elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
814 	elf_auxargs->execfd = -1;
815 	elf_auxargs->phdr = proghdr;
816 	elf_auxargs->phent = hdr->e_phentsize;
817 	elf_auxargs->phnum = hdr->e_phnum;
818 	elf_auxargs->pagesz = PAGE_SIZE;
819 	elf_auxargs->base = addr;
820 	elf_auxargs->flags = 0;
821 	elf_auxargs->entry = entry;
822 	elf_auxargs->trace = elf_trace;
823 
824 	imgp->auxargs = elf_auxargs;
825 	imgp->interpreted = 0;
826 
827 fail:
828 	return error;
829 }
830 
831 static int
832 elf_freebsd_fixup(register_t **stack_base, struct image_params *imgp)
833 {
834 	Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
835 	register_t *pos;
836 
837 	pos = *stack_base + (imgp->args->argc + imgp->args->envc + 2);
838 
839 	if (args->trace) {
840 		AUXARGS_ENTRY(pos, AT_DEBUG, 1);
841 	}
842 	if (args->execfd != -1) {
843 		AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
844 	}
845 	AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
846 	AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
847 	AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
848 	AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
849 	AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
850 	AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
851 	AUXARGS_ENTRY(pos, AT_BASE, args->base);
852 	AUXARGS_ENTRY(pos, AT_NULL, 0);
853 
854 	free(imgp->auxargs, M_TEMP);
855 	imgp->auxargs = NULL;
856 
857 	(*stack_base)--;
858 	suword(*stack_base, (long) imgp->args->argc);
859 	return 0;
860 }
861 
862 /*
863  * Code for generating ELF core dumps.
864  */
865 
866 typedef int (*segment_callback) (vm_map_entry_t, void *);
867 
868 /* Closure for cb_put_phdr(). */
869 struct phdr_closure {
870 	Elf_Phdr *phdr;		/* Program header to fill in (incremented) */
871 	Elf_Phdr *phdr_max;	/* Pointer bound for error check */
872 	Elf_Off offset;		/* Offset of segment in core file */
873 };
874 
875 /* Closure for cb_size_segment(). */
876 struct sseg_closure {
877 	int count;		/* Count of writable segments. */
878 	size_t vsize;		/* Total size of all writable segments. */
879 };
880 
881 /* Closure for cb_put_fp(). */
882 struct fp_closure {
883 	struct vn_hdr *vnh;
884 	struct vn_hdr *vnh_max;
885 	int count;
886 	struct stat *sb;
887 };
888 
889 typedef struct elf_buf {
890 	char	*buf;
891 	size_t	off;
892 	size_t	off_max;
893 } *elf_buf_t;
894 
895 static void *target_reserve(elf_buf_t target, size_t bytes, int *error);
896 
897 static int cb_put_phdr (vm_map_entry_t, void *);
898 static int cb_size_segment (vm_map_entry_t, void *);
899 static int cb_fpcount_segment(vm_map_entry_t, void *);
900 static int cb_put_fp(vm_map_entry_t, void *);
901 
902 
903 static int each_segment (struct proc *, segment_callback, void *, int);
904 static int elf_corehdr (struct proc *, struct file *, struct ucred *,
905 			int, elf_buf_t);
906 static int elf_puthdr (struct proc *, elf_buf_t, const prstatus_t *,
907 			const prfpregset_t *, const prpsinfo_t *, int);
908 static int elf_putnote (elf_buf_t, const char *, int, const void *, size_t);
909 
910 static int elf_putsigs(struct proc *, elf_buf_t);
911 static int elf_puttextvp(struct proc *, elf_buf_t);
912 static int elf_putfiles(struct proc *, elf_buf_t);
913 
914 extern int osreldate;
915 
916 int
917 elf_coredump(struct proc *p, struct vnode *vp, off_t limit)
918 {
919 	struct file *fp;
920 	int error;
921 
922 	if ((error = falloc(NULL, &fp, NULL)) != 0)
923 		return (error);
924 	fsetcred(fp, p->p_ucred);
925 
926 	/*
927 	 * XXX fixme.
928 	 */
929 	fp->f_type = DTYPE_VNODE;
930 	fp->f_flag = O_CREAT|O_WRONLY|O_NOFOLLOW;
931 	fp->f_ops = &vnode_fileops;
932 	fp->f_data = vp;
933 	VOP_UNLOCK(vp, 0);
934 
935 	error = generic_elf_coredump(p, fp, limit);
936 
937 	fp->f_type = 0;
938 	fp->f_flag = 0;
939 	fp->f_ops = &badfileops;
940 	fp->f_data = NULL;
941 	fdrop(fp);
942 	return (error);
943 }
944 
945 int
946 generic_elf_coredump(struct proc *p, struct file *fp, off_t limit)
947 {
948 	struct ucred *cred = p->p_ucred;
949 	int error = 0;
950 	struct sseg_closure seginfo;
951 	struct elf_buf target;
952 
953 	if (!fp)
954 		printf("can't dump core - null fp\n");
955 
956 	/*
957 	 * Size the program segments
958 	 */
959 	seginfo.count = 0;
960 	seginfo.vsize = 0;
961 	each_segment(p, cb_size_segment, &seginfo, 1);
962 
963 	/*
964 	 * Calculate the size of the core file header area by making
965 	 * a dry run of generating it.  Nothing is written, but the
966 	 * size is calculated.
967 	 */
968 	bzero(&target, sizeof(target));
969 	elf_puthdr(p, &target, NULL, NULL, NULL, seginfo.count);
970 
971 	if (target.off + seginfo.vsize >= limit)
972 		return (EFAULT);
973 
974 	/*
975 	 * Allocate memory for building the header, fill it up,
976 	 * and write it out.
977 	 */
978 	target.off_max = target.off;
979 	target.off = 0;
980 	target.buf = malloc(target.off_max, M_TEMP, M_WAITOK|M_ZERO);
981 
982 	if (target.buf == NULL)
983 		return EINVAL;
984 	error = elf_corehdr(p, fp, cred, seginfo.count, &target);
985 
986 	/* Write the contents of all of the writable segments. */
987 	if (error == 0) {
988 		Elf_Phdr *php;
989 		int i;
990 		int nbytes;
991 
992 		php = (Elf_Phdr *)(target.buf + sizeof(Elf_Ehdr)) + 1;
993 		for (i = 0; i < seginfo.count; i++) {
994 			error = fp_write(fp, (caddr_t)php->p_vaddr,
995 					php->p_filesz, &nbytes);
996 			if (error != 0)
997 				break;
998 			php++;
999 		}
1000 	}
1001 	free(target.buf, M_TEMP);
1002 
1003 	return error;
1004 }
1005 
1006 /*
1007  * A callback for each_segment() to write out the segment's
1008  * program header entry.
1009  */
1010 static int
1011 cb_put_phdr(vm_map_entry_t entry, void *closure)
1012 {
1013 	struct phdr_closure *phc = closure;
1014 	Elf_Phdr *phdr = phc->phdr;
1015 
1016 	if (phc->phdr == phc->phdr_max)
1017 		return EINVAL;
1018 
1019 	phc->offset = round_page(phc->offset);
1020 
1021 	phdr->p_type = PT_LOAD;
1022 	phdr->p_offset = phc->offset;
1023 	phdr->p_vaddr = entry->start;
1024 	phdr->p_paddr = 0;
1025 	phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1026 	phdr->p_align = PAGE_SIZE;
1027 	phdr->p_flags = 0;
1028 	if (entry->protection & VM_PROT_READ)
1029 		phdr->p_flags |= PF_R;
1030 	if (entry->protection & VM_PROT_WRITE)
1031 		phdr->p_flags |= PF_W;
1032 	if (entry->protection & VM_PROT_EXECUTE)
1033 		phdr->p_flags |= PF_X;
1034 
1035 	phc->offset += phdr->p_filesz;
1036 	++phc->phdr;
1037 	return 0;
1038 }
1039 
1040 /*
1041  * A callback for each_writable_segment() to gather information about
1042  * the number of segments and their total size.
1043  */
1044 static int
1045 cb_size_segment(vm_map_entry_t entry, void *closure)
1046 {
1047 	struct sseg_closure *ssc = closure;
1048 
1049 	++ssc->count;
1050 	ssc->vsize += entry->end - entry->start;
1051 	return 0;
1052 }
1053 
1054 /*
1055  * A callback for each_segment() to gather information about
1056  * the number of text segments.
1057  */
1058 static int
1059 cb_fpcount_segment(vm_map_entry_t entry, void *closure)
1060 {
1061 	int *count = closure;
1062 	struct vnode *vp;
1063 
1064 	if (entry->object.vm_object->type == OBJT_VNODE) {
1065 		vp = (struct vnode *)entry->object.vm_object->handle;
1066 		if ((vp->v_flag & VCKPT) && curproc->p_textvp == vp)
1067 			return 0;
1068 		++*count;
1069 	}
1070 	return 0;
1071 }
1072 
1073 static int
1074 cb_put_fp(vm_map_entry_t entry, void *closure)
1075 {
1076 	struct fp_closure *fpc = closure;
1077 	struct vn_hdr *vnh = fpc->vnh;
1078 	Elf_Phdr *phdr = &vnh->vnh_phdr;
1079 	struct vnode *vp;
1080 	int error;
1081 
1082 	/*
1083 	 * If an entry represents a vnode then write out a file handle.
1084 	 *
1085 	 * If we are checkpointing a checkpoint-restored program we do
1086 	 * NOT record the filehandle for the old checkpoint vnode (which
1087 	 * is mapped all over the place).  Instead we rely on the fact
1088 	 * that a checkpoint-restored program does not mmap() the checkpt
1089 	 * vnode NOCORE, so its contents will be written out to the
1090 	 * new checkpoint file.  This is necessary because the 'old'
1091 	 * checkpoint file is typically destroyed when a new one is created
1092 	 * and thus cannot be used to restore the new checkpoint.
1093 	 *
1094 	 * Theoretically we could create a chain of checkpoint files and
1095 	 * operate the checkpointing operation kinda like an incremental
1096 	 * checkpoint, but a checkpoint restore would then likely wind up
1097 	 * referencing many prior checkpoint files and that is a bit over
1098 	 * the top for the purpose of the checkpoint API.
1099 	 */
1100 	if (entry->object.vm_object->type == OBJT_VNODE) {
1101 		vp = (struct vnode *)entry->object.vm_object->handle;
1102 		if ((vp->v_flag & VCKPT) && curproc->p_textvp == vp)
1103 			return 0;
1104 		if (vnh == fpc->vnh_max)
1105 			return EINVAL;
1106 
1107 		if (vp->v_mount)
1108 			vnh->vnh_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1109 		error = VFS_VPTOFH(vp, &vnh->vnh_fh.fh_fid);
1110 		if (error) {
1111 			char *freepath, *fullpath;
1112 
1113 			if (vn_fullpath(curproc, vp, &fullpath, &freepath)) {
1114 				printf("Warning: coredump, error %d: cannot store file handle for vnode %p\n", error, vp);
1115 			} else {
1116 				printf("Warning: coredump, error %d: cannot store file handle for %s\n", error, fullpath);
1117 				free(freepath, M_TEMP);
1118 			}
1119 			error = 0;
1120 		}
1121 
1122 		phdr->p_type = PT_LOAD;
1123 		phdr->p_offset = 0;        /* not written to core */
1124 		phdr->p_vaddr = entry->start;
1125 		phdr->p_paddr = 0;
1126 		phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1127 		phdr->p_align = PAGE_SIZE;
1128 		phdr->p_flags = 0;
1129 		if (entry->protection & VM_PROT_READ)
1130 			phdr->p_flags |= PF_R;
1131 		if (entry->protection & VM_PROT_WRITE)
1132 			phdr->p_flags |= PF_W;
1133 		if (entry->protection & VM_PROT_EXECUTE)
1134 			phdr->p_flags |= PF_X;
1135 		++fpc->vnh;
1136 		++fpc->count;
1137 	}
1138 	return 0;
1139 }
1140 
1141 /*
1142  * For each writable segment in the process's memory map, call the given
1143  * function with a pointer to the map entry and some arbitrary
1144  * caller-supplied data.
1145  */
1146 static int
1147 each_segment(struct proc *p, segment_callback func, void *closure, int writable)
1148 {
1149 	int error = 0;
1150 	vm_map_t map = &p->p_vmspace->vm_map;
1151 	vm_map_entry_t entry;
1152 
1153 	for (entry = map->header.next; error == 0 && entry != &map->header;
1154 	    entry = entry->next) {
1155 		vm_object_t obj;
1156 
1157 		/*
1158 		 * Don't dump inaccessible mappings, deal with legacy
1159 		 * coredump mode.
1160 		 *
1161 		 * Note that read-only segments related to the elf binary
1162 		 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1163 		 * need to arbitrarily ignore such segments.
1164 		 */
1165 		if (elf_legacy_coredump) {
1166 			if (writable && (entry->protection & VM_PROT_RW) != VM_PROT_RW)
1167 				continue;
1168 		} else {
1169 			if (writable && (entry->protection & VM_PROT_ALL) == 0)
1170 				continue;
1171 		}
1172 
1173 		/*
1174 		 * Dont include memory segment in the coredump if
1175 		 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1176 		 * madvise(2).  Do not dump submaps (i.e. parts of the
1177 		 * kernel map).
1178 		 */
1179 		if (writable && entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
1180 			continue;
1181 
1182 		if ((obj = entry->object.vm_object) == NULL)
1183 			continue;
1184 
1185 		/* Find the deepest backing object. */
1186 		while (obj->backing_object != NULL)
1187 			obj = obj->backing_object;
1188 
1189 		/* Ignore memory-mapped devices and such things. */
1190 		if (obj->type != OBJT_DEFAULT &&
1191 		    obj->type != OBJT_SWAP &&
1192 		    obj->type != OBJT_VNODE)
1193 			continue;
1194 
1195 		error = (*func)(entry, closure);
1196 	}
1197 	return error;
1198 }
1199 
1200 static
1201 void *
1202 target_reserve(elf_buf_t target, size_t bytes, int *error)
1203 {
1204     void *res = NULL;
1205 
1206     if (target->buf) {
1207 	    if (target->off + bytes > target->off_max)
1208 		    *error = EINVAL;
1209 	    else
1210 		    res = target->buf + target->off;
1211     }
1212     target->off += bytes;
1213     return (res);
1214 }
1215 
1216 /*
1217  * Write the core file header to the file, including padding up to
1218  * the page boundary.
1219  */
1220 static int
1221 elf_corehdr(struct proc *p, struct file *fp, struct ucred *cred, int numsegs,
1222 	    elf_buf_t target)
1223 {
1224 	struct {
1225 		prstatus_t status;
1226 		prfpregset_t fpregset;
1227 		prpsinfo_t psinfo;
1228 	} *tempdata;
1229 	int error;
1230 	prstatus_t *status;
1231 	prfpregset_t *fpregset;
1232 	prpsinfo_t *psinfo;
1233 	int nbytes;
1234 	tempdata = malloc(sizeof(*tempdata), M_TEMP, M_ZERO | M_WAITOK);
1235 	status = &tempdata->status;
1236 	fpregset = &tempdata->fpregset;
1237 	psinfo = &tempdata->psinfo;
1238 
1239 	/* Gather the information for the header. */
1240 	status->pr_version = PRSTATUS_VERSION;
1241 	status->pr_statussz = sizeof(prstatus_t);
1242 	status->pr_gregsetsz = sizeof(gregset_t);
1243 	status->pr_fpregsetsz = sizeof(fpregset_t);
1244 	status->pr_osreldate = osreldate;
1245 	status->pr_cursig = p->p_sig;
1246 	status->pr_pid = p->p_pid;
1247 	fill_regs(&p->p_lwp, &status->pr_reg);
1248 
1249 	fill_fpregs(&p->p_lwp, fpregset);
1250 
1251 	psinfo->pr_version = PRPSINFO_VERSION;
1252 	psinfo->pr_psinfosz = sizeof(prpsinfo_t);
1253 	strncpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname) - 1);
1254 
1255 	/* XXX - We don't fill in the command line arguments properly yet. */
1256 	strncpy(psinfo->pr_psargs, p->p_comm, PRARGSZ);
1257 
1258 	/* Fill in the header. */
1259 	error = elf_puthdr(p, target, status, fpregset, psinfo, numsegs);
1260 
1261 	free(tempdata, M_TEMP);
1262 
1263 	/* Write it to the core file. */
1264 	if (error == 0)
1265 		error = fp_write(fp, target->buf, target->off, &nbytes);
1266 	return error;
1267 }
1268 
1269 static int
1270 elf_puthdr(struct proc *p, elf_buf_t target, const prstatus_t *status,
1271 	const prfpregset_t *fpregset, const prpsinfo_t *psinfo, int numsegs)
1272 {
1273 	int error = 0;
1274 	size_t phoff;
1275 	size_t noteoff;
1276 	size_t notesz;
1277 	Elf_Ehdr *ehdr;
1278 	Elf_Phdr *phdr;
1279 
1280 	ehdr = target_reserve(target, sizeof(Elf_Ehdr), &error);
1281 
1282 	phoff = target->off;
1283 	phdr = target_reserve(target, (numsegs + 1) * sizeof(Elf_Phdr), &error);
1284 
1285 	noteoff = target->off;
1286 	if (error == 0) {
1287 		error = elf_putnote(target, "FreeBSD", NT_PRSTATUS,
1288 					status, sizeof *status);
1289 	}
1290 	if (error == 0) {
1291 		error = elf_putnote(target, "FreeBSD", NT_FPREGSET,
1292 					fpregset, sizeof *fpregset);
1293 	}
1294 	if (error == 0) {
1295 		error = elf_putnote(target, "FreeBSD", NT_PRPSINFO,
1296 					psinfo, sizeof *psinfo);
1297 	}
1298 	notesz = target->off - noteoff;
1299 
1300 	/*
1301 	 * put extra cruft for dumping process state here
1302 	 *  - we really want it be before all the program
1303 	 *    mappings
1304 	 *  - we just need to update the offset accordingly
1305 	 *    and GDB will be none the wiser.
1306 	 */
1307 	if (error == 0)
1308 		error = elf_puttextvp(p, target);
1309 	if (error == 0)
1310 		error = elf_putsigs(p, target);
1311 	if (error == 0)
1312 		error = elf_putfiles(p, target);
1313 
1314 	/*
1315 	 * Align up to a page boundary for the program segments.  The
1316 	 * actual data will be written to the outptu file, not to elf_buf_t,
1317 	 * so we do not have to do any further bounds checking.
1318 	 */
1319 	target->off = round_page(target->off);
1320 	if (error == 0 && ehdr != NULL) {
1321 		/*
1322 		 * Fill in the ELF header.
1323 		 */
1324 		ehdr->e_ident[EI_MAG0] = ELFMAG0;
1325 		ehdr->e_ident[EI_MAG1] = ELFMAG1;
1326 		ehdr->e_ident[EI_MAG2] = ELFMAG2;
1327 		ehdr->e_ident[EI_MAG3] = ELFMAG3;
1328 		ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1329 		ehdr->e_ident[EI_DATA] = ELF_DATA;
1330 		ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1331 		ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1332 		ehdr->e_ident[EI_ABIVERSION] = 0;
1333 		ehdr->e_ident[EI_PAD] = 0;
1334 		ehdr->e_type = ET_CORE;
1335 		ehdr->e_machine = ELF_ARCH;
1336 		ehdr->e_version = EV_CURRENT;
1337 		ehdr->e_entry = 0;
1338 		ehdr->e_phoff = phoff;
1339 		ehdr->e_flags = 0;
1340 		ehdr->e_ehsize = sizeof(Elf_Ehdr);
1341 		ehdr->e_phentsize = sizeof(Elf_Phdr);
1342 		ehdr->e_phnum = numsegs + 1;
1343 		ehdr->e_shentsize = sizeof(Elf_Shdr);
1344 		ehdr->e_shnum = 0;
1345 		ehdr->e_shstrndx = SHN_UNDEF;
1346 	}
1347 	if (error == 0 && phdr != NULL) {
1348 		/*
1349 		 * Fill in the program header entries.
1350 		 */
1351 		struct phdr_closure phc;
1352 
1353 		/* The note segement. */
1354 		phdr->p_type = PT_NOTE;
1355 		phdr->p_offset = noteoff;
1356 		phdr->p_vaddr = 0;
1357 		phdr->p_paddr = 0;
1358 		phdr->p_filesz = notesz;
1359 		phdr->p_memsz = 0;
1360 		phdr->p_flags = 0;
1361 		phdr->p_align = 0;
1362 		++phdr;
1363 
1364 		/* All the writable segments from the program. */
1365 		phc.phdr = phdr;
1366 		phc.phdr_max = phdr + numsegs;
1367 		phc.offset = target->off;
1368 		each_segment(p, cb_put_phdr, &phc, 1);
1369 	}
1370 	return (error);
1371 }
1372 
1373 static int
1374 elf_putnote(elf_buf_t target, const char *name, int type,
1375 	    const void *desc, size_t descsz)
1376 {
1377 	int error = 0;
1378 	char *dst;
1379 	Elf_Note note;
1380 
1381 	note.n_namesz = strlen(name) + 1;
1382 	note.n_descsz = descsz;
1383 	note.n_type = type;
1384 	dst = target_reserve(target, sizeof(note), &error);
1385 	if (dst != NULL)
1386 		bcopy(&note, dst, sizeof note);
1387 	dst = target_reserve(target, note.n_namesz, &error);
1388 	if (dst != NULL)
1389 		bcopy(name, dst, note.n_namesz);
1390 	target->off = roundup2(target->off, sizeof(Elf_Size));
1391 	dst = target_reserve(target, note.n_descsz, &error);
1392 	if (dst != NULL)
1393 		bcopy(desc, dst, note.n_descsz);
1394 	target->off = roundup2(target->off, sizeof(Elf_Size));
1395 	return(error);
1396 }
1397 
1398 
1399 static int
1400 elf_putsigs(struct proc *p, elf_buf_t target)
1401 {
1402 	int error = 0;
1403 	struct ckpt_siginfo *csi;
1404 
1405 	csi = target_reserve(target, sizeof(struct ckpt_siginfo), &error);
1406 	if (csi) {
1407 		csi->csi_ckptpisz = sizeof(struct ckpt_siginfo);
1408 		bcopy(p->p_procsig, &csi->csi_procsig, sizeof(struct procsig));
1409 		bcopy(p->p_procsig->ps_sigacts, &csi->csi_sigacts, sizeof(struct sigacts));
1410 		bcopy(&p->p_realtimer, &csi->csi_itimerval, sizeof(struct itimerval));
1411 		bcopy(&p->p_sigmask, &csi->csi_sigmask, sizeof(sigset_t));
1412 		csi->csi_sigparent = p->p_sigparent;
1413 	}
1414 	return(error);
1415 }
1416 
1417 static int
1418 elf_putfiles(struct proc *p, elf_buf_t target)
1419 {
1420 	int error = 0;
1421 	int i;
1422 	struct ckpt_filehdr *cfh = NULL;
1423 	struct ckpt_fileinfo *cfi;
1424 	struct file *fp;
1425 	struct vnode *vp;
1426 	/*
1427 	 * the duplicated loop is gross, but it was the only way
1428 	 * to eliminate uninitialized variable warnings
1429 	 */
1430 	cfh = target_reserve(target, sizeof(struct ckpt_filehdr), &error);
1431 	if (cfh) {
1432 		cfh->cfh_nfiles = 0;
1433 	}
1434 
1435 	/*
1436 	 * ignore STDIN/STDERR/STDOUT.
1437 	 */
1438 	for (i = 3; error == 0 && i < p->p_fd->fd_nfiles; i++) {
1439 		fp = holdfp(p->p_fd, i, -1);
1440 		if (fp == NULL)
1441 			continue;
1442 		/*
1443 		 * XXX Only checkpoint vnodes for now.
1444 		 */
1445 		if (fp->f_type != DTYPE_VNODE) {
1446 			fdrop(fp);
1447 			continue;
1448 		}
1449 		cfi = target_reserve(target, sizeof(struct ckpt_fileinfo),
1450 					&error);
1451 		if (cfi == NULL) {
1452 			fdrop(fp);
1453 			continue;
1454 		}
1455 		cfi->cfi_index = -1;
1456 		cfi->cfi_type = fp->f_type;
1457 		cfi->cfi_flags = fp->f_flag;
1458 		cfi->cfi_offset = fp->f_offset;
1459 		/* f_count and f_msgcount should not be saved/restored */
1460 		/* XXX save cred info */
1461 
1462 		switch(fp->f_type) {
1463 		case DTYPE_VNODE:
1464 			vp = (struct vnode *)fp->f_data;
1465 			/*
1466 			 * it looks like a bug in ptrace is marking
1467 			 * a non-vnode as a vnode - until we find the
1468 			 * root cause this will at least prevent
1469 			 * further panics from truss
1470 			 */
1471 			if (vp == NULL || vp->v_mount == NULL)
1472 				break;
1473 			cfh->cfh_nfiles++;
1474 			cfi->cfi_index = i;
1475 			cfi->cfi_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1476 			error = VFS_VPTOFH(vp, &cfi->cfi_fh.fh_fid);
1477 			break;
1478 		default:
1479 			break;
1480 		}
1481 		fdrop(fp);
1482 	}
1483 	return(error);
1484 }
1485 
1486 static int
1487 elf_puttextvp(struct proc *p, elf_buf_t target)
1488 {
1489 	int error = 0;
1490 	int *vn_count;
1491 	struct fp_closure fpc;
1492 	struct ckpt_vminfo *vminfo;
1493 
1494 	vminfo = target_reserve(target, sizeof(struct ckpt_vminfo), &error);
1495 	if (vminfo != NULL) {
1496 		vminfo->cvm_dsize = p->p_vmspace->vm_dsize;
1497 		vminfo->cvm_tsize = p->p_vmspace->vm_tsize;
1498 		vminfo->cvm_daddr = p->p_vmspace->vm_daddr;
1499 		vminfo->cvm_taddr = p->p_vmspace->vm_taddr;
1500 	}
1501 
1502 	fpc.count = 0;
1503 	vn_count = target_reserve(target, sizeof(int), &error);
1504 	if (target->buf != NULL) {
1505 		fpc.vnh = (struct vn_hdr *)(target->buf + target->off);
1506 		fpc.vnh_max = fpc.vnh +
1507 			(target->off_max - target->off) / sizeof(struct vn_hdr);
1508 		error = each_segment(p, cb_put_fp, &fpc, 0);
1509 		if (vn_count)
1510 			*vn_count = fpc.count;
1511 	} else {
1512 		error = each_segment(p, cb_fpcount_segment, &fpc.count, 0);
1513 	}
1514 	target->off += fpc.count * sizeof(struct vn_hdr);
1515 	return(error);
1516 }
1517 
1518 
1519 /*
1520  * Tell kern_execve.c about it, with a little help from the linker.
1521  */
1522 static struct execsw elf_execsw = {exec_elf_imgact, "ELF"};
1523 EXEC_SET_ORDERED(elf, elf_execsw, SI_ORDER_FIRST);
1524