1 #include <lunaix/common.h>
2 #include <lunaix/elf.h>
5 #include <lunaix/mm/mmap.h>
6 #include <lunaix/mm/valloc.h>
7 #include <lunaix/mm/vmm.h>
8 #include <lunaix/spike.h>
11 __elf_populate_mapped(struct mm_region* region, void* pg, off_t offset)
13 struct elf32_phdr* phdr = (struct elf32_phdr*)region->data;
14 size_t segsz = phdr->p_filesz;
15 size_t segoff = offset - phdr->p_offset;
17 if (segoff >= segsz) {
21 struct v_file* file = region->mfile;
22 size_t rdlen = MIN(segsz - segoff, PG_SIZE);
24 if (rdlen == PG_SIZE) {
25 // This is because we want to exploit any optimization on read_page
26 return file->ops->read_page(file->inode, pg, PG_SIZE, offset);
28 return file->ops->read(file->inode, pg, rdlen, offset);
33 __elf_destruct_mapped(struct mm_region* region)
39 elf_map_segment(struct ld_param* ldparam,
40 struct v_file* elfile,
41 struct elf32_phdr* phdr)
44 if ((phdr->p_flags & PF_R)) {
47 if ((phdr->p_flags & PF_W)) {
50 if ((phdr->p_flags & PF_X)) {
54 struct mm_region* seg_reg;
55 struct mmap_param param = { .vms_mnt = ldparam->vms_mnt,
56 .regions = &ldparam->proc->mm.regions,
58 .offset = phdr->p_offset,
59 .length = ROUNDUP(phdr->p_memsz, PG_SIZE),
61 MAP_FIXED | MAP_PRIVATE | REGION_TYPE_CODE };
63 int status = mem_map(NULL, &seg_reg, PG_ALIGN(phdr->p_va), elfile, ¶m);
66 struct elf32_phdr* phdr_ = valloc(sizeof(SIZE_PHDR));
70 seg_reg->init_page = __elf_populate_mapped;
71 seg_reg->destruct_region = __elf_destruct_mapped;
78 elf_setup_mapping(struct ld_param* ldparam,
79 struct v_file* elfile,
80 struct elf32_ehdr* ehdr)
83 size_t tbl_sz = ehdr->e_phnum * SIZE_PHDR;
84 struct elf32_phdr* phdrs = valloc(tbl_sz);
91 tbl_sz = 1 << ILOG2(tbl_sz);
92 phdrs = elfile->ops->read(elfile->inode, phdrs, tbl_sz, ehdr->e_phoff);
94 size_t entries = tbl_sz / SIZE_PHDR;
95 for (size_t i = 0; i < entries; i++) {
96 struct elf32_phdr* phdr = &phdrs[i];
98 if (phdr->p_type == PT_LOAD) {
99 status = elf_map_segment(ldparam, elfile, phdr);
101 // TODO process other types of segments
104 ldparam->status |= LD_STAT_FKUP;
115 elf_load(struct ld_param* ldparam, struct v_file* elfile)
117 struct elf32_ehdr* ehdr = valloc(SIZE_EHDR);
118 int status = elfile->ops->read(elfile->inode, ehdr, SIZE_EHDR, 0);
124 if (!elf_check_exec(ehdr)) {
129 if ((status = elf_setup_mapping(ldparam, elfile, ehdr))) {
133 ldparam->ehdr_out = *ehdr;