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