xref: /dragonfly/sys/kern/imgact_elf.c (revision 3f625015)
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.50 2007/02/25 23:17:12 corecode 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 				      VM_MAPTYPE_NORMAL,
311 				      prot, 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_MAPTYPE_NORMAL,
345 					VM_PROT_ALL, VM_PROT_ALL,
346 					0);
347 		vm_map_unlock(&vmspace->vm_map);
348 		vm_map_entry_release(count);
349 		if (rv != KERN_SUCCESS) {
350 			return EINVAL;
351 		}
352 	}
353 
354 	if (copy_len != 0) {
355 		vm_object_reference(object);
356 		rv = vm_map_find(&exec_map,
357 				 object,
358 				 trunc_page(offset + filsz),
359 				 &data_buf,
360 				 PAGE_SIZE,
361 				 TRUE,
362 				 VM_MAPTYPE_NORMAL,
363 				 VM_PROT_READ, VM_PROT_ALL,
364 				 MAP_COPY_ON_WRITE | MAP_PREFAULT_PARTIAL);
365 		if (rv != KERN_SUCCESS) {
366 			vm_object_deallocate(object);
367 			return EINVAL;
368 		}
369 
370 		/* send the page fragment to user space */
371 		error = copyout((caddr_t)data_buf, (caddr_t)map_addr, copy_len);
372 		vm_map_remove(&exec_map, data_buf, data_buf + PAGE_SIZE);
373 		if (error) {
374 			return (error);
375 		}
376 	}
377 
378 	/*
379 	 * set it to the specified protection
380 	 */
381 	vm_map_protect(&vmspace->vm_map, map_addr, map_addr + map_len,  prot,
382 		       FALSE);
383 
384 	return error;
385 }
386 
387 /*
388  * Load the file "file" into memory.  It may be either a shared object
389  * or an executable.
390  *
391  * The "addr" reference parameter is in/out.  On entry, it specifies
392  * the address where a shared object should be loaded.  If the file is
393  * an executable, this value is ignored.  On exit, "addr" specifies
394  * where the file was actually loaded.
395  *
396  * The "entry" reference parameter is out only.  On exit, it specifies
397  * the entry point for the loaded file.
398  */
399 static int
400 elf_load_file(struct proc *p, const char *file, u_long *addr, u_long *entry)
401 {
402 	struct {
403 		struct nlookupdata nd;
404 		struct vattr attr;
405 		struct image_params image_params;
406 	} *tempdata;
407 	const Elf_Ehdr *hdr = NULL;
408 	const Elf_Phdr *phdr = NULL;
409 	struct nlookupdata *nd;
410 	struct vmspace *vmspace = p->p_vmspace;
411 	struct vattr *attr;
412 	struct image_params *imgp;
413 	vm_prot_t prot;
414 	u_long rbase;
415 	u_long base_addr = 0;
416 	int error, i, numsegs;
417 
418 	tempdata = kmalloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
419 	nd = &tempdata->nd;
420 	attr = &tempdata->attr;
421 	imgp = &tempdata->image_params;
422 
423 	/*
424 	 * Initialize part of the common data
425 	 */
426 	imgp->proc = p;
427 	imgp->attr = attr;
428 	imgp->firstpage = NULL;
429 	imgp->image_header = NULL;
430 	imgp->vp = NULL;
431 
432 	error = nlookup_init(nd, file, UIO_SYSSPACE, NLC_FOLLOW);
433 	if (error == 0)
434 		error = nlookup(nd);
435 	if (error == 0)
436 		error = cache_vget(&nd->nl_nch, nd->nl_cred, LK_EXCLUSIVE, &imgp->vp);
437 	nlookup_done(nd);
438 	if (error)
439 		goto fail;
440 
441 	/*
442 	 * Check permissions, modes, uid, etc on the file, and "open" it.
443 	 */
444 	error = exec_check_permissions(imgp);
445 	if (error) {
446 		vn_unlock(imgp->vp);
447 		goto fail;
448 	}
449 
450 	error = exec_map_first_page(imgp);
451 	/*
452 	 * Also make certain that the interpreter stays the same, so set
453 	 * its VTEXT flag, too.
454 	 */
455 	if (error == 0)
456 		imgp->vp->v_flag |= VTEXT;
457 	vn_unlock(imgp->vp);
458 	if (error)
459                 goto fail;
460 
461 	hdr = (const Elf_Ehdr *)imgp->image_header;
462 	if ((error = elf_check_header(hdr)) != 0)
463 		goto fail;
464 	if (hdr->e_type == ET_DYN)
465 		rbase = *addr;
466 	else if (hdr->e_type == ET_EXEC)
467 		rbase = 0;
468 	else {
469 		error = ENOEXEC;
470 		goto fail;
471 	}
472 
473 	/* Only support headers that fit within first page for now
474 	 * (multiplication of two Elf_Half fields will not overflow) */
475 	if ((hdr->e_phoff > PAGE_SIZE) ||
476 	    (hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE - hdr->e_phoff) {
477 		error = ENOEXEC;
478 		goto fail;
479 	}
480 
481 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
482 
483 	for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
484 		if (phdr[i].p_type == PT_LOAD) {	/* Loadable segment */
485 			prot = 0;
486 			if (phdr[i].p_flags & PF_X)
487   				prot |= VM_PROT_EXECUTE;
488 			if (phdr[i].p_flags & PF_W)
489   				prot |= VM_PROT_WRITE;
490 			if (phdr[i].p_flags & PF_R)
491   				prot |= VM_PROT_READ;
492 
493 			error = elf_load_section(
494 				    p, vmspace, imgp->vp,
495 				    phdr[i].p_offset,
496 				    (caddr_t)phdr[i].p_vaddr +
497 				    rbase,
498 				    phdr[i].p_memsz,
499 				    phdr[i].p_filesz, prot);
500 			if (error != 0)
501 				goto fail;
502 			/*
503 			 * Establish the base address if this is the
504 			 * first segment.
505 			 */
506 			if (numsegs == 0)
507   				base_addr = trunc_page(phdr[i].p_vaddr + rbase);
508 			numsegs++;
509 		}
510 	}
511 	*addr = base_addr;
512 	*entry=(unsigned long)hdr->e_entry + rbase;
513 
514 fail:
515 	if (imgp->firstpage)
516 		exec_unmap_first_page(imgp);
517 	if (imgp->vp) {
518 		vrele(imgp->vp);
519 		imgp->vp = NULL;
520 	}
521 	kfree(tempdata, M_TEMP);
522 
523 	return error;
524 }
525 
526 /*
527  * non static, as it can be overridden by start_init()
528  */
529 int fallback_elf_brand = -1;
530 SYSCTL_INT(_kern, OID_AUTO, fallback_elf_brand, CTLFLAG_RW,
531 		&fallback_elf_brand, -1,
532 		"ELF brand of last resort");
533 
534 static int
535 exec_elf_imgact(struct image_params *imgp)
536 {
537 	const Elf_Ehdr *hdr = (const Elf_Ehdr *) imgp->image_header;
538 	const Elf_Phdr *phdr;
539 	Elf_Auxargs *elf_auxargs = NULL;
540 	struct vmspace *vmspace;
541 	vm_prot_t prot;
542 	u_long text_size = 0, data_size = 0, total_size = 0;
543 	u_long text_addr = 0, data_addr = 0;
544 	u_long seg_size, seg_addr;
545 	u_long addr, entry = 0, proghdr = 0;
546 	int error, i;
547 	const char *interp = NULL;
548 	const Elf_Note *abi_note = NULL;
549 	Elf_Brandinfo *brand_info;
550 	char *path;
551 
552 	error = 0;
553 
554 	/*
555 	 * Do we have a valid ELF header ?
556 	 */
557 	if (elf_check_header(hdr) != 0 || hdr->e_type != ET_EXEC)
558 		return -1;
559 
560 	/*
561 	 * From here on down, we return an errno, not -1, as we've
562 	 * detected an ELF file.
563 	 */
564 
565 	if ((hdr->e_phoff > PAGE_SIZE) ||
566 	    (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
567 		/* Only support headers in first page for now */
568 		return ENOEXEC;
569 	}
570 	phdr = (const Elf_Phdr*)(imgp->image_header + hdr->e_phoff);
571 
572 	/*
573 	 * From this point on, we may have resources that need to be freed.
574 	 */
575 
576 	exec_new_vmspace(imgp, NULL);
577 
578 	/*
579 	 * Yeah, I'm paranoid.  There is every reason in the world to get
580 	 * VTEXT now since from here on out, there are places we can have
581 	 * a context switch.  Better safe than sorry; I really don't want
582 	 * the file to change while it's being loaded.
583 	 */
584 	vsetflags(imgp->vp, VTEXT);
585 
586 	vmspace = imgp->proc->p_vmspace;
587 
588 	for (i = 0; i < hdr->e_phnum; i++) {
589 		switch(phdr[i].p_type) {
590 
591 		case PT_LOAD:	/* Loadable segment */
592 			prot = 0;
593 			if (phdr[i].p_flags & PF_X)
594   				prot |= VM_PROT_EXECUTE;
595 			if (phdr[i].p_flags & PF_W)
596   				prot |= VM_PROT_WRITE;
597 			if (phdr[i].p_flags & PF_R)
598   				prot |= VM_PROT_READ;
599 
600 			if ((error = elf_load_section(imgp->proc,
601 						     vmspace, imgp->vp,
602   						     phdr[i].p_offset,
603   						     (caddr_t)phdr[i].p_vaddr,
604   						     phdr[i].p_memsz,
605   						     phdr[i].p_filesz, prot)) != 0)
606   				goto fail;
607 
608 			/*
609 			 * If this segment contains the program headers,
610 			 * remember their virtual address for the AT_PHDR
611 			 * aux entry. Static binaries don't usually include
612 			 * a PT_PHDR entry.
613 			 */
614 			if (phdr[i].p_offset == 0 &&
615 			    hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
616 				<= phdr[i].p_filesz)
617 				proghdr = phdr[i].p_vaddr + hdr->e_phoff;
618 
619 			seg_addr = trunc_page(phdr[i].p_vaddr);
620 			seg_size = round_page(phdr[i].p_memsz +
621 				phdr[i].p_vaddr - seg_addr);
622 
623 			/*
624 			 * Is this .text or .data?  We can't use
625 			 * VM_PROT_WRITE or VM_PROT_EXEC, it breaks the
626 			 * alpha terribly and possibly does other bad
627 			 * things so we stick to the old way of figuring
628 			 * it out:  If the segment contains the program
629 			 * entry point, it's a text segment, otherwise it
630 			 * is a data segment.
631 			 *
632 			 * Note that obreak() assumes that data_addr +
633 			 * data_size == end of data load area, and the ELF
634 			 * file format expects segments to be sorted by
635 			 * address.  If multiple data segments exist, the
636 			 * last one will be used.
637 			 */
638 			if (hdr->e_entry >= phdr[i].p_vaddr &&
639 			    hdr->e_entry < (phdr[i].p_vaddr +
640 			    phdr[i].p_memsz)) {
641 				text_size = seg_size;
642 				text_addr = seg_addr;
643 				entry = (u_long)hdr->e_entry;
644 			} else {
645 				data_size = seg_size;
646 				data_addr = seg_addr;
647 			}
648 			total_size += seg_size;
649 
650 			/*
651 			 * Check limits.  It should be safe to check the
652 			 * limits after loading the segment since we do
653 			 * not actually fault in all the segment's pages.
654 			 */
655 			if (data_size >
656 			    imgp->proc->p_rlimit[RLIMIT_DATA].rlim_cur ||
657 			    text_size > maxtsiz ||
658 			    total_size >
659 			    imgp->proc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
660 				error = ENOMEM;
661 				goto fail;
662 			}
663 			break;
664 	  	case PT_INTERP:	/* Path to interpreter */
665 			if (phdr[i].p_filesz > MAXPATHLEN ||
666 			    phdr[i].p_offset + phdr[i].p_filesz > PAGE_SIZE) {
667 				error = ENOEXEC;
668 				goto fail;
669 			}
670 			interp = imgp->image_header + phdr[i].p_offset;
671 			break;
672 		case PT_NOTE:	/* Check for .note.ABI-tag */
673 		{
674 			const Elf_Note *tmp_note;
675 			/* XXX handle anything outside the first page */
676 			if (phdr[i].p_offset + phdr[i].p_filesz > PAGE_SIZE)
677 				continue;
678 			if (phdr[i].p_filesz < sizeof(Elf_Note))
679 				continue; /* ENOEXEC? */
680 			tmp_note = (const Elf_Note *)(imgp->image_header + phdr[i].p_offset);
681 			if (tmp_note->n_type != 1)
682 				continue;
683 			if (tmp_note->n_namesz + sizeof(Elf_Note) +
684 			    tmp_note->n_descsz > phdr[i].p_filesz)
685 				continue; /* ENOEXEC? */
686 			abi_note = tmp_note;
687 		}
688 			break;
689 		case PT_PHDR: 	/* Program header table info */
690 			proghdr = phdr[i].p_vaddr;
691 			break;
692 		default:
693 			break;
694 		}
695 	}
696 
697 	vmspace->vm_tsize = text_size >> PAGE_SHIFT;
698 	vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
699 	vmspace->vm_dsize = data_size >> PAGE_SHIFT;
700 	vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
701 
702 	addr = ELF_RTLD_ADDR(vmspace);
703 
704 	imgp->entry_addr = entry;
705 
706 	brand_info = NULL;
707 
708 	/* We support three types of branding -- (1) the ELF EI_OSABI field
709 	 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
710 	 * branding w/in the ELF header, and (3) path of the `interp_path'
711 	 * field.  We should also look for an ".note.ABI-tag" ELF section now
712 	 * in all Linux ELF binaries, FreeBSD 4.1+, and some NetBSD ones.
713 	 */
714 
715 	/* If the executable has a brand, search for it in the brand list. */
716 	if (brand_info == NULL && hdr->e_ident[EI_OSABI] != ELFOSABI_NONE) {
717 		for (i = 0;  i < MAX_BRANDS;  i++) {
718 			Elf_Brandinfo *bi = elf_brand_list[i];
719 
720 			if (bi != NULL &&
721 			    (hdr->e_ident[EI_OSABI] == bi->brand
722 			    || 0 ==
723 			    strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
724 			    bi->compat_3_brand, strlen(bi->compat_3_brand)))) {
725 				brand_info = bi;
726 				break;
727 			}
728 		}
729 	}
730 
731 	/* Search for a recognized ABI. */
732 	if (brand_info == NULL && abi_note != NULL) {
733 		for (i = 0; i < MAX_BRANDS; i++) {
734 			Elf_Brandinfo *bi = elf_brand_list[i];
735 
736 			if (bi != NULL && bi->match_abi_note != NULL &&
737 			    (*bi->match_abi_note)(abi_note)) {
738 				brand_info = bi;
739 				break;
740 			}
741 		}
742 	}
743 
744 	/*
745 	 * ELFOSABI_NONE == ELFOSABI_SYSV, so a SYSV binary misses all
746 	 * checks so far, since it is neither branded nor does it have
747 	 * an ABI note.  If the EI_OSABI field is ELFOSABI_NONE, assume
748 	 * it is svr4 and look for an entry in the elf_brand_list with
749 	 * match_abi_note == NULL.
750 	 */
751 	if (brand_info == NULL && hdr->e_ident[EI_OSABI] == ELFOSABI_NONE) {
752 		for (i = 0; i < MAX_BRANDS; i++) {
753 			Elf_Brandinfo *bi = elf_brand_list[i];
754 
755 			if (bi != NULL && bi->match_abi_note == NULL &&
756 			    ELFOSABI_SYSV == bi->brand) {
757 				brand_info = bi;
758 				break;
759 			}
760 		}
761 	}
762 
763 	/* Lacking a recognized ABI, search for a recognized interpreter. */
764 	if (brand_info == NULL && interp != NULL) {
765 		for (i = 0;  i < MAX_BRANDS;  i++) {
766 			Elf_Brandinfo *bi = elf_brand_list[i];
767 
768 			if (bi != NULL &&
769 			    strcmp(interp, bi->interp_path) == 0) {
770 				brand_info = bi;
771 				break;
772 			}
773 		}
774 	}
775 
776 	/* Lacking a recognized interpreter, try the default brand */
777 	if (brand_info == NULL) {
778 		for (i = 0; i < MAX_BRANDS; i++) {
779 			Elf_Brandinfo *bi = elf_brand_list[i];
780 
781 			if (bi != NULL && fallback_elf_brand == bi->brand) {
782 				brand_info = bi;
783 				break;
784 			}
785 		}
786 	}
787 
788 	if (brand_info == NULL) {
789 		uprintf("ELF binary type \"%u\" not known.\n",
790 		    hdr->e_ident[EI_OSABI]);
791 		error = ENOEXEC;
792 		goto fail;
793 	}
794 
795 	imgp->proc->p_sysent = brand_info->sysvec;
796 	if (interp != NULL) {
797 		path = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
798 	        ksnprintf(path, MAXPATHLEN, "%s%s",
799 			 brand_info->emul_path, interp);
800 		if ((error = elf_load_file(imgp->proc, path, &addr,
801 					   &imgp->entry_addr)) != 0) {
802 		        if ((error = elf_load_file(imgp->proc, interp, &addr,
803 						   &imgp->entry_addr)) != 0) {
804 			        uprintf("ELF interpreter %s not found\n", path);
805 				kfree(path, M_TEMP);
806 				goto fail;
807 			}
808                 }
809 		kfree(path, M_TEMP);
810 	}
811 
812 	/*
813 	 * Construct auxargs table (used by the fixup routine)
814 	 */
815 	elf_auxargs = kmalloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
816 	elf_auxargs->execfd = -1;
817 	elf_auxargs->phdr = proghdr;
818 	elf_auxargs->phent = hdr->e_phentsize;
819 	elf_auxargs->phnum = hdr->e_phnum;
820 	elf_auxargs->pagesz = PAGE_SIZE;
821 	elf_auxargs->base = addr;
822 	elf_auxargs->flags = 0;
823 	elf_auxargs->entry = entry;
824 	elf_auxargs->trace = elf_trace;
825 
826 	imgp->auxargs = elf_auxargs;
827 	imgp->interpreted = 0;
828 
829 fail:
830 	return error;
831 }
832 
833 static int
834 elf_freebsd_fixup(register_t **stack_base, struct image_params *imgp)
835 {
836 	Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
837 	register_t *pos;
838 
839 	pos = *stack_base + (imgp->args->argc + imgp->args->envc + 2);
840 
841 	if (args->trace) {
842 		AUXARGS_ENTRY(pos, AT_DEBUG, 1);
843 	}
844 	if (args->execfd != -1) {
845 		AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
846 	}
847 	AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
848 	AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
849 	AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
850 	AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
851 	AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
852 	AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
853 	AUXARGS_ENTRY(pos, AT_BASE, args->base);
854 	AUXARGS_ENTRY(pos, AT_NULL, 0);
855 
856 	kfree(imgp->auxargs, M_TEMP);
857 	imgp->auxargs = NULL;
858 
859 	(*stack_base)--;
860 	suword(*stack_base, (long) imgp->args->argc);
861 	return 0;
862 }
863 
864 /*
865  * Code for generating ELF core dumps.
866  */
867 
868 typedef int (*segment_callback) (vm_map_entry_t, void *);
869 
870 /* Closure for cb_put_phdr(). */
871 struct phdr_closure {
872 	Elf_Phdr *phdr;		/* Program header to fill in (incremented) */
873 	Elf_Phdr *phdr_max;	/* Pointer bound for error check */
874 	Elf_Off offset;		/* Offset of segment in core file */
875 };
876 
877 /* Closure for cb_size_segment(). */
878 struct sseg_closure {
879 	int count;		/* Count of writable segments. */
880 	size_t vsize;		/* Total size of all writable segments. */
881 };
882 
883 /* Closure for cb_put_fp(). */
884 struct fp_closure {
885 	struct vn_hdr *vnh;
886 	struct vn_hdr *vnh_max;
887 	int count;
888 	struct stat *sb;
889 };
890 
891 typedef struct elf_buf {
892 	char	*buf;
893 	size_t	off;
894 	size_t	off_max;
895 } *elf_buf_t;
896 
897 static void *target_reserve(elf_buf_t target, size_t bytes, int *error);
898 
899 static int cb_put_phdr (vm_map_entry_t, void *);
900 static int cb_size_segment (vm_map_entry_t, void *);
901 static int cb_fpcount_segment(vm_map_entry_t, void *);
902 static int cb_put_fp(vm_map_entry_t, void *);
903 
904 
905 static int each_segment (struct proc *, segment_callback, void *, int);
906 static int elf_corehdr (struct lwp *, int, struct file *, struct ucred *,
907 			int, elf_buf_t);
908 static int elf_puthdr (struct lwp *, elf_buf_t, const prstatus_t *,
909 			const prfpregset_t *, const prpsinfo_t *, int);
910 static int elf_putnote (elf_buf_t, const char *, int, const void *, size_t);
911 
912 static int elf_putsigs(struct lwp *, elf_buf_t);
913 static int elf_puttextvp(struct proc *, elf_buf_t);
914 static int elf_putfiles(struct proc *, elf_buf_t);
915 
916 extern int osreldate;
917 
918 int
919 elf_coredump(struct lwp *lp, int sig, struct vnode *vp, off_t limit)
920 {
921 	struct file *fp;
922 	int error;
923 
924 	if ((error = falloc(NULL, &fp, NULL)) != 0)
925 		return (error);
926 	fsetcred(fp, lp->lwp_proc->p_ucred);
927 
928 	/*
929 	 * XXX fixme.
930 	 */
931 	fp->f_type = DTYPE_VNODE;
932 	fp->f_flag = O_CREAT|O_WRONLY|O_NOFOLLOW;
933 	fp->f_ops = &vnode_fileops;
934 	fp->f_data = vp;
935 	vn_unlock(vp);
936 
937 	error = generic_elf_coredump(lp, sig, fp, limit);
938 
939 	fp->f_type = 0;
940 	fp->f_flag = 0;
941 	fp->f_ops = &badfileops;
942 	fp->f_data = NULL;
943 	fdrop(fp);
944 	return (error);
945 }
946 
947 int
948 generic_elf_coredump(struct lwp *lp, int sig, struct file *fp, off_t limit)
949 {
950 	struct proc *p = lp->lwp_proc;
951 	struct ucred *cred = p->p_ucred;
952 	int error = 0;
953 	struct sseg_closure seginfo;
954 	struct elf_buf target;
955 
956 	if (!fp)
957 		kprintf("can't dump core - null fp\n");
958 
959 	/*
960 	 * Size the program segments
961 	 */
962 	seginfo.count = 0;
963 	seginfo.vsize = 0;
964 	each_segment(p, cb_size_segment, &seginfo, 1);
965 
966 	/*
967 	 * Calculate the size of the core file header area by making
968 	 * a dry run of generating it.  Nothing is written, but the
969 	 * size is calculated.
970 	 */
971 	bzero(&target, sizeof(target));
972 	elf_puthdr(lp, &target, NULL, NULL, NULL, seginfo.count);
973 
974 	if (target.off + seginfo.vsize >= limit)
975 		return (EFAULT);
976 
977 	/*
978 	 * Allocate memory for building the header, fill it up,
979 	 * and write it out.
980 	 */
981 	target.off_max = target.off;
982 	target.off = 0;
983 	target.buf = kmalloc(target.off_max, M_TEMP, M_WAITOK|M_ZERO);
984 
985 	if (target.buf == NULL)
986 		return EINVAL;
987 	error = elf_corehdr(lp, sig, fp, cred, seginfo.count, &target);
988 
989 	/* Write the contents of all of the writable segments. */
990 	if (error == 0) {
991 		Elf_Phdr *php;
992 		int i;
993 		int nbytes;
994 
995 		php = (Elf_Phdr *)(target.buf + sizeof(Elf_Ehdr)) + 1;
996 		for (i = 0; i < seginfo.count; i++) {
997 			error = fp_write(fp, (caddr_t)php->p_vaddr,
998 					php->p_filesz, &nbytes, UIO_USERSPACE);
999 			if (error != 0)
1000 				break;
1001 			php++;
1002 		}
1003 	}
1004 	kfree(target.buf, M_TEMP);
1005 
1006 	return error;
1007 }
1008 
1009 /*
1010  * A callback for each_segment() to write out the segment's
1011  * program header entry.
1012  */
1013 static int
1014 cb_put_phdr(vm_map_entry_t entry, void *closure)
1015 {
1016 	struct phdr_closure *phc = closure;
1017 	Elf_Phdr *phdr = phc->phdr;
1018 
1019 	if (phc->phdr == phc->phdr_max)
1020 		return EINVAL;
1021 
1022 	phc->offset = round_page(phc->offset);
1023 
1024 	phdr->p_type = PT_LOAD;
1025 	phdr->p_offset = phc->offset;
1026 	phdr->p_vaddr = entry->start;
1027 	phdr->p_paddr = 0;
1028 	phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1029 	phdr->p_align = PAGE_SIZE;
1030 	phdr->p_flags = 0;
1031 	if (entry->protection & VM_PROT_READ)
1032 		phdr->p_flags |= PF_R;
1033 	if (entry->protection & VM_PROT_WRITE)
1034 		phdr->p_flags |= PF_W;
1035 	if (entry->protection & VM_PROT_EXECUTE)
1036 		phdr->p_flags |= PF_X;
1037 
1038 	phc->offset += phdr->p_filesz;
1039 	++phc->phdr;
1040 	return 0;
1041 }
1042 
1043 /*
1044  * A callback for each_writable_segment() to gather information about
1045  * the number of segments and their total size.
1046  */
1047 static int
1048 cb_size_segment(vm_map_entry_t entry, void *closure)
1049 {
1050 	struct sseg_closure *ssc = closure;
1051 
1052 	++ssc->count;
1053 	ssc->vsize += entry->end - entry->start;
1054 	return 0;
1055 }
1056 
1057 /*
1058  * A callback for each_segment() to gather information about
1059  * the number of text segments.
1060  */
1061 static int
1062 cb_fpcount_segment(vm_map_entry_t entry, void *closure)
1063 {
1064 	int *count = closure;
1065 	struct vnode *vp;
1066 
1067 	if (entry->object.vm_object->type == OBJT_VNODE) {
1068 		vp = (struct vnode *)entry->object.vm_object->handle;
1069 		if ((vp->v_flag & VCKPT) && curproc->p_textvp == vp)
1070 			return 0;
1071 		++*count;
1072 	}
1073 	return 0;
1074 }
1075 
1076 static int
1077 cb_put_fp(vm_map_entry_t entry, void *closure)
1078 {
1079 	struct fp_closure *fpc = closure;
1080 	struct vn_hdr *vnh = fpc->vnh;
1081 	Elf_Phdr *phdr = &vnh->vnh_phdr;
1082 	struct vnode *vp;
1083 	int error;
1084 
1085 	/*
1086 	 * If an entry represents a vnode then write out a file handle.
1087 	 *
1088 	 * If we are checkpointing a checkpoint-restored program we do
1089 	 * NOT record the filehandle for the old checkpoint vnode (which
1090 	 * is mapped all over the place).  Instead we rely on the fact
1091 	 * that a checkpoint-restored program does not mmap() the checkpt
1092 	 * vnode NOCORE, so its contents will be written out to the
1093 	 * new checkpoint file.  This is necessary because the 'old'
1094 	 * checkpoint file is typically destroyed when a new one is created
1095 	 * and thus cannot be used to restore the new checkpoint.
1096 	 *
1097 	 * Theoretically we could create a chain of checkpoint files and
1098 	 * operate the checkpointing operation kinda like an incremental
1099 	 * checkpoint, but a checkpoint restore would then likely wind up
1100 	 * referencing many prior checkpoint files and that is a bit over
1101 	 * the top for the purpose of the checkpoint API.
1102 	 */
1103 	if (entry->object.vm_object->type == OBJT_VNODE) {
1104 		vp = (struct vnode *)entry->object.vm_object->handle;
1105 		if ((vp->v_flag & VCKPT) && curproc->p_textvp == vp)
1106 			return 0;
1107 		if (vnh == fpc->vnh_max)
1108 			return EINVAL;
1109 
1110 		if (vp->v_mount)
1111 			vnh->vnh_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1112 		error = VFS_VPTOFH(vp, &vnh->vnh_fh.fh_fid);
1113 		if (error) {
1114 			char *freepath, *fullpath;
1115 
1116 			if (vn_fullpath(curproc, vp, &fullpath, &freepath)) {
1117 				kprintf("Warning: coredump, error %d: cannot store file handle for vnode %p\n", error, vp);
1118 			} else {
1119 				kprintf("Warning: coredump, error %d: cannot store file handle for %s\n", error, fullpath);
1120 				kfree(freepath, M_TEMP);
1121 			}
1122 			error = 0;
1123 		}
1124 
1125 		phdr->p_type = PT_LOAD;
1126 		phdr->p_offset = 0;        /* not written to core */
1127 		phdr->p_vaddr = entry->start;
1128 		phdr->p_paddr = 0;
1129 		phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1130 		phdr->p_align = PAGE_SIZE;
1131 		phdr->p_flags = 0;
1132 		if (entry->protection & VM_PROT_READ)
1133 			phdr->p_flags |= PF_R;
1134 		if (entry->protection & VM_PROT_WRITE)
1135 			phdr->p_flags |= PF_W;
1136 		if (entry->protection & VM_PROT_EXECUTE)
1137 			phdr->p_flags |= PF_X;
1138 		++fpc->vnh;
1139 		++fpc->count;
1140 	}
1141 	return 0;
1142 }
1143 
1144 /*
1145  * For each writable segment in the process's memory map, call the given
1146  * function with a pointer to the map entry and some arbitrary
1147  * caller-supplied data.
1148  */
1149 static int
1150 each_segment(struct proc *p, segment_callback func, void *closure, int writable)
1151 {
1152 	int error = 0;
1153 	vm_map_t map = &p->p_vmspace->vm_map;
1154 	vm_map_entry_t entry;
1155 
1156 	for (entry = map->header.next; error == 0 && entry != &map->header;
1157 	    entry = entry->next) {
1158 		vm_object_t obj;
1159 
1160 		/*
1161 		 * Don't dump inaccessible mappings, deal with legacy
1162 		 * coredump mode.
1163 		 *
1164 		 * Note that read-only segments related to the elf binary
1165 		 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1166 		 * need to arbitrarily ignore such segments.
1167 		 */
1168 		if (elf_legacy_coredump) {
1169 			if (writable && (entry->protection & VM_PROT_RW) != VM_PROT_RW)
1170 				continue;
1171 		} else {
1172 			if (writable && (entry->protection & VM_PROT_ALL) == 0)
1173 				continue;
1174 		}
1175 
1176 		/*
1177 		 * Dont include memory segment in the coredump if
1178 		 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1179 		 * madvise(2).
1180 		 *
1181 		 * Currently we only dump normal VM object maps.  We do
1182 		 * not dump submaps or virtual page tables.
1183 		 */
1184 		if (writable && (entry->eflags & MAP_ENTRY_NOCOREDUMP))
1185 			continue;
1186 		if (entry->maptype != VM_MAPTYPE_NORMAL)
1187 			continue;
1188 		if ((obj = entry->object.vm_object) == NULL)
1189 			continue;
1190 
1191 		/* Find the deepest backing object. */
1192 		while (obj->backing_object != NULL)
1193 			obj = obj->backing_object;
1194 
1195 		/* Ignore memory-mapped devices and such things. */
1196 		if (obj->type != OBJT_DEFAULT &&
1197 		    obj->type != OBJT_SWAP &&
1198 		    obj->type != OBJT_VNODE)
1199 			continue;
1200 
1201 		error = (*func)(entry, closure);
1202 	}
1203 	return error;
1204 }
1205 
1206 static
1207 void *
1208 target_reserve(elf_buf_t target, size_t bytes, int *error)
1209 {
1210     void *res = NULL;
1211 
1212     if (target->buf) {
1213 	    if (target->off + bytes > target->off_max)
1214 		    *error = EINVAL;
1215 	    else
1216 		    res = target->buf + target->off;
1217     }
1218     target->off += bytes;
1219     return (res);
1220 }
1221 
1222 /*
1223  * Write the core file header to the file, including padding up to
1224  * the page boundary.
1225  */
1226 static int
1227 elf_corehdr(struct lwp *lp, int sig, struct file *fp, struct ucred *cred, int numsegs,
1228 	    elf_buf_t target)
1229 {
1230 	/* XXX lwp handle more than one lwp */
1231 	struct proc *p = lp->lwp_proc;
1232 	struct {
1233 		prstatus_t status;
1234 		prfpregset_t fpregset;
1235 		prpsinfo_t psinfo;
1236 	} *tempdata;
1237 	int error;
1238 	prstatus_t *status;
1239 	prfpregset_t *fpregset;
1240 	prpsinfo_t *psinfo;
1241 	int nbytes;
1242 
1243 	tempdata = kmalloc(sizeof(*tempdata), M_TEMP, M_ZERO | M_WAITOK);
1244 	status = &tempdata->status;
1245 	fpregset = &tempdata->fpregset;
1246 	psinfo = &tempdata->psinfo;
1247 
1248 	/* Gather the information for the header. */
1249 	status->pr_version = PRSTATUS_VERSION;
1250 	status->pr_statussz = sizeof(prstatus_t);
1251 	status->pr_gregsetsz = sizeof(gregset_t);
1252 	status->pr_fpregsetsz = sizeof(fpregset_t);
1253 	status->pr_osreldate = osreldate;
1254 	status->pr_cursig = sig;
1255 	status->pr_pid = p->p_pid;
1256 	fill_regs(lp, &status->pr_reg);
1257 
1258 	fill_fpregs(lp, fpregset);
1259 
1260 	psinfo->pr_version = PRPSINFO_VERSION;
1261 	psinfo->pr_psinfosz = sizeof(prpsinfo_t);
1262 	strncpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname) - 1);
1263 
1264 	/* XXX - We don't fill in the command line arguments properly yet. */
1265 	strncpy(psinfo->pr_psargs, p->p_comm, PRARGSZ);
1266 
1267 	/* Fill in the header. */
1268 	error = elf_puthdr(lp, target, status, fpregset, psinfo, numsegs);
1269 
1270 	kfree(tempdata, M_TEMP);
1271 
1272 	/* Write it to the core file. */
1273 	if (error == 0) {
1274 		error = fp_write(fp, target->buf, target->off, &nbytes,
1275 				 UIO_SYSSPACE);
1276 	}
1277 	return error;
1278 }
1279 
1280 static int
1281 elf_puthdr(struct lwp *lp, elf_buf_t target, const prstatus_t *status,
1282 	const prfpregset_t *fpregset, const prpsinfo_t *psinfo, int numsegs)
1283 {
1284 	struct proc *p = lp->lwp_proc;
1285 	int error = 0;
1286 	size_t phoff;
1287 	size_t noteoff;
1288 	size_t notesz;
1289 	Elf_Ehdr *ehdr;
1290 	Elf_Phdr *phdr;
1291 
1292 	ehdr = target_reserve(target, sizeof(Elf_Ehdr), &error);
1293 
1294 	phoff = target->off;
1295 	phdr = target_reserve(target, (numsegs + 1) * sizeof(Elf_Phdr), &error);
1296 
1297 	noteoff = target->off;
1298 	if (error == 0) {
1299 		error = elf_putnote(target, "FreeBSD", NT_PRSTATUS,
1300 					status, sizeof *status);
1301 	}
1302 	if (error == 0) {
1303 		error = elf_putnote(target, "FreeBSD", NT_FPREGSET,
1304 					fpregset, sizeof *fpregset);
1305 	}
1306 	if (error == 0) {
1307 		error = elf_putnote(target, "FreeBSD", NT_PRPSINFO,
1308 					psinfo, sizeof *psinfo);
1309 	}
1310 	notesz = target->off - noteoff;
1311 
1312 	/*
1313 	 * put extra cruft for dumping process state here
1314 	 *  - we really want it be before all the program
1315 	 *    mappings
1316 	 *  - we just need to update the offset accordingly
1317 	 *    and GDB will be none the wiser.
1318 	 */
1319 	if (error == 0)
1320 		error = elf_puttextvp(p, target);
1321 	if (error == 0)
1322 		error = elf_putsigs(lp, target);
1323 	if (error == 0)
1324 		error = elf_putfiles(p, target);
1325 
1326 	/*
1327 	 * Align up to a page boundary for the program segments.  The
1328 	 * actual data will be written to the outptu file, not to elf_buf_t,
1329 	 * so we do not have to do any further bounds checking.
1330 	 */
1331 	target->off = round_page(target->off);
1332 	if (error == 0 && ehdr != NULL) {
1333 		/*
1334 		 * Fill in the ELF header.
1335 		 */
1336 		ehdr->e_ident[EI_MAG0] = ELFMAG0;
1337 		ehdr->e_ident[EI_MAG1] = ELFMAG1;
1338 		ehdr->e_ident[EI_MAG2] = ELFMAG2;
1339 		ehdr->e_ident[EI_MAG3] = ELFMAG3;
1340 		ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1341 		ehdr->e_ident[EI_DATA] = ELF_DATA;
1342 		ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1343 		ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1344 		ehdr->e_ident[EI_ABIVERSION] = 0;
1345 		ehdr->e_ident[EI_PAD] = 0;
1346 		ehdr->e_type = ET_CORE;
1347 		ehdr->e_machine = ELF_ARCH;
1348 		ehdr->e_version = EV_CURRENT;
1349 		ehdr->e_entry = 0;
1350 		ehdr->e_phoff = phoff;
1351 		ehdr->e_flags = 0;
1352 		ehdr->e_ehsize = sizeof(Elf_Ehdr);
1353 		ehdr->e_phentsize = sizeof(Elf_Phdr);
1354 		ehdr->e_phnum = numsegs + 1;
1355 		ehdr->e_shentsize = sizeof(Elf_Shdr);
1356 		ehdr->e_shnum = 0;
1357 		ehdr->e_shstrndx = SHN_UNDEF;
1358 	}
1359 	if (error == 0 && phdr != NULL) {
1360 		/*
1361 		 * Fill in the program header entries.
1362 		 */
1363 		struct phdr_closure phc;
1364 
1365 		/* The note segement. */
1366 		phdr->p_type = PT_NOTE;
1367 		phdr->p_offset = noteoff;
1368 		phdr->p_vaddr = 0;
1369 		phdr->p_paddr = 0;
1370 		phdr->p_filesz = notesz;
1371 		phdr->p_memsz = 0;
1372 		phdr->p_flags = 0;
1373 		phdr->p_align = 0;
1374 		++phdr;
1375 
1376 		/* All the writable segments from the program. */
1377 		phc.phdr = phdr;
1378 		phc.phdr_max = phdr + numsegs;
1379 		phc.offset = target->off;
1380 		each_segment(p, cb_put_phdr, &phc, 1);
1381 	}
1382 	return (error);
1383 }
1384 
1385 static int
1386 elf_putnote(elf_buf_t target, const char *name, int type,
1387 	    const void *desc, size_t descsz)
1388 {
1389 	int error = 0;
1390 	char *dst;
1391 	Elf_Note note;
1392 
1393 	note.n_namesz = strlen(name) + 1;
1394 	note.n_descsz = descsz;
1395 	note.n_type = type;
1396 	dst = target_reserve(target, sizeof(note), &error);
1397 	if (dst != NULL)
1398 		bcopy(&note, dst, sizeof note);
1399 	dst = target_reserve(target, note.n_namesz, &error);
1400 	if (dst != NULL)
1401 		bcopy(name, dst, note.n_namesz);
1402 	target->off = roundup2(target->off, sizeof(Elf_Size));
1403 	dst = target_reserve(target, note.n_descsz, &error);
1404 	if (dst != NULL)
1405 		bcopy(desc, dst, note.n_descsz);
1406 	target->off = roundup2(target->off, sizeof(Elf_Size));
1407 	return(error);
1408 }
1409 
1410 
1411 static int
1412 elf_putsigs(struct lwp *lp, elf_buf_t target)
1413 {
1414 	/* XXX lwp handle more than one lwp */
1415 	struct proc *p = lp->lwp_proc;
1416 	int error = 0;
1417 	struct ckpt_siginfo *csi;
1418 
1419 	csi = target_reserve(target, sizeof(struct ckpt_siginfo), &error);
1420 	if (csi) {
1421 		csi->csi_ckptpisz = sizeof(struct ckpt_siginfo);
1422 		bcopy(p->p_sigacts, &csi->csi_sigacts, sizeof(*p->p_sigacts));
1423 		bcopy(&p->p_realtimer, &csi->csi_itimerval, sizeof(struct itimerval));
1424 		bcopy(&lp->lwp_sigmask, &csi->csi_sigmask,
1425 			sizeof(sigset_t));
1426 		csi->csi_sigparent = p->p_sigparent;
1427 	}
1428 	return(error);
1429 }
1430 
1431 static int
1432 elf_putfiles(struct proc *p, elf_buf_t target)
1433 {
1434 	int error = 0;
1435 	int i;
1436 	struct ckpt_filehdr *cfh = NULL;
1437 	struct ckpt_fileinfo *cfi;
1438 	struct file *fp;
1439 	struct vnode *vp;
1440 	/*
1441 	 * the duplicated loop is gross, but it was the only way
1442 	 * to eliminate uninitialized variable warnings
1443 	 */
1444 	cfh = target_reserve(target, sizeof(struct ckpt_filehdr), &error);
1445 	if (cfh) {
1446 		cfh->cfh_nfiles = 0;
1447 	}
1448 
1449 	/*
1450 	 * ignore STDIN/STDERR/STDOUT.
1451 	 */
1452 	for (i = 3; error == 0 && i < p->p_fd->fd_nfiles; i++) {
1453 		fp = holdfp(p->p_fd, i, -1);
1454 		if (fp == NULL)
1455 			continue;
1456 		/*
1457 		 * XXX Only checkpoint vnodes for now.
1458 		 */
1459 		if (fp->f_type != DTYPE_VNODE) {
1460 			fdrop(fp);
1461 			continue;
1462 		}
1463 		cfi = target_reserve(target, sizeof(struct ckpt_fileinfo),
1464 					&error);
1465 		if (cfi == NULL) {
1466 			fdrop(fp);
1467 			continue;
1468 		}
1469 		cfi->cfi_index = -1;
1470 		cfi->cfi_type = fp->f_type;
1471 		cfi->cfi_flags = fp->f_flag;
1472 		cfi->cfi_offset = fp->f_offset;
1473 		/* f_count and f_msgcount should not be saved/restored */
1474 		/* XXX save cred info */
1475 
1476 		switch(fp->f_type) {
1477 		case DTYPE_VNODE:
1478 			vp = (struct vnode *)fp->f_data;
1479 			/*
1480 			 * it looks like a bug in ptrace is marking
1481 			 * a non-vnode as a vnode - until we find the
1482 			 * root cause this will at least prevent
1483 			 * further panics from truss
1484 			 */
1485 			if (vp == NULL || vp->v_mount == NULL)
1486 				break;
1487 			cfh->cfh_nfiles++;
1488 			cfi->cfi_index = i;
1489 			cfi->cfi_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1490 			error = VFS_VPTOFH(vp, &cfi->cfi_fh.fh_fid);
1491 			break;
1492 		default:
1493 			break;
1494 		}
1495 		fdrop(fp);
1496 	}
1497 	return(error);
1498 }
1499 
1500 static int
1501 elf_puttextvp(struct proc *p, elf_buf_t target)
1502 {
1503 	int error = 0;
1504 	int *vn_count;
1505 	struct fp_closure fpc;
1506 	struct ckpt_vminfo *vminfo;
1507 
1508 	vminfo = target_reserve(target, sizeof(struct ckpt_vminfo), &error);
1509 	if (vminfo != NULL) {
1510 		vminfo->cvm_dsize = p->p_vmspace->vm_dsize;
1511 		vminfo->cvm_tsize = p->p_vmspace->vm_tsize;
1512 		vminfo->cvm_daddr = p->p_vmspace->vm_daddr;
1513 		vminfo->cvm_taddr = p->p_vmspace->vm_taddr;
1514 	}
1515 
1516 	fpc.count = 0;
1517 	vn_count = target_reserve(target, sizeof(int), &error);
1518 	if (target->buf != NULL) {
1519 		fpc.vnh = (struct vn_hdr *)(target->buf + target->off);
1520 		fpc.vnh_max = fpc.vnh +
1521 			(target->off_max - target->off) / sizeof(struct vn_hdr);
1522 		error = each_segment(p, cb_put_fp, &fpc, 0);
1523 		if (vn_count)
1524 			*vn_count = fpc.count;
1525 	} else {
1526 		error = each_segment(p, cb_fpcount_segment, &fpc.count, 0);
1527 	}
1528 	target->off += fpc.count * sizeof(struct vn_hdr);
1529 	return(error);
1530 }
1531 
1532 
1533 /*
1534  * Tell kern_execve.c about it, with a little help from the linker.
1535  */
1536 static struct execsw elf_execsw = {exec_elf_imgact, "ELF"};
1537 EXEC_SET_ORDERED(elf, elf_execsw, SI_ORDER_FIRST);
1538