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 size_t segsz = region->flen;
14 size_t segoff = offset - region->foff;
16 if (segoff >= segsz) {
20 struct v_file* file = region->mfile;
21 size_t rdlen = MIN(segsz - segoff, PG_SIZE);
23 if (rdlen == PG_SIZE) {
24 // This is because we want to exploit any optimization on read_page
25 return file->ops->read_page(file->inode, pg, PG_SIZE, offset);
27 return file->ops->read(file->inode, pg, rdlen, offset);
32 elf_map_segment(struct ld_param* ldparam,
33 struct v_file* elfile,
34 struct elf32_phdr* phdr)
37 if ((phdr->p_flags & PF_R)) {
40 if ((phdr->p_flags & PF_W)) {
43 if ((phdr->p_flags & PF_X)) {
47 struct mm_region* seg_reg;
48 struct mmap_param param = { .vms_mnt = ldparam->vms_mnt,
49 .pvms = &ldparam->proc->mm,
51 .offset = phdr->p_offset,
52 .mlen = ROUNDUP(phdr->p_memsz, PG_SIZE),
53 .flen = phdr->p_filesz,
54 .flags = MAP_FIXED | MAP_PRIVATE,
55 .type = REGION_TYPE_CODE };
57 int status = mem_map(NULL, &seg_reg, PG_ALIGN(phdr->p_va), elfile, ¶m);
60 seg_reg->init_page = __elf_populate_mapped;
62 size_t next_addr = phdr->p_memsz + phdr->p_va;
63 ldparam->info.end = MAX(ldparam->info.end, ROUNDUP(next_addr, PG_SIZE));
64 ldparam->info.mem_sz += phdr->p_memsz;
71 elf_setup_mapping(struct ld_param* ldparam,
72 struct v_file* elfile,
73 struct elf32_ehdr* ehdr)
76 size_t tbl_sz = ehdr->e_phnum * SIZE_PHDR;
77 struct elf32_phdr* phdrs = valloc(tbl_sz);
84 tbl_sz = 1 << ILOG2(tbl_sz);
85 phdrs = elfile->ops->read(elfile->inode, phdrs, tbl_sz, ehdr->e_phoff);
87 if (PG_ALIGN(phdrs[0].p_va) != USER_START) {
92 size_t entries = tbl_sz / SIZE_PHDR;
93 for (size_t i = 0; i < entries; i++) {
94 struct elf32_phdr* phdr = &phdrs[i];
96 if (phdr->p_type == PT_LOAD) {
97 if (phdr->p_align == PG_SIZE) {
98 status = elf_map_segment(ldparam, elfile, phdr);
100 // surprising alignment!
104 // TODO process other types of segments
107 // errno in the middle of mapping restructuring, it is impossible
109 ldparam->status |= LD_STAT_FKUP;
120 elf_load(struct ld_param* ldparam, struct v_file* elfile)
122 struct elf32_ehdr* ehdr = valloc(SIZE_EHDR);
123 int status = elfile->ops->read(elfile->inode, ehdr, SIZE_EHDR, 0);
129 if (!elf_check_exec(ehdr)) {
134 if ((status = elf_setup_mapping(ldparam, elfile, ehdr))) {
138 ldparam->info.ehdr_out = *ehdr;