Loading ELF with mmap()
Posted: Thu Jun 09, 2022 12:17 pm
Hello,
Currently, my OS loads elf files like this: where ph is the current program header it's loading, and fd is the executable's file descriptor.
I would like to do something more like this though: but I don't know how to deal with alignment issues.
mmap() will truncate addresses to page boundaries, and the program header might not align that way (e.g. the data section of my test program requests 0x1e74).
The other issue is that I'd pass memsz to mmap() so that it allocates a region large enough, but then it might over-read from the backing file, since memsz can be larger than filesz in the program header.
How should I deal with this? Or should I just keep doing it by allocating anonymous memory and reading the file into it.
I'm not really bothered about remaining POSIX compatible, so if someone has a completely different solution that's neater, I'll happily accept/adapt it.
Thanks,
Barry
Currently, my OS loads elf files like this:
Code: Select all
mmap(ph.address, ph.memsz, ph.flags, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
lseek(fd, ph.offset, SEEK_SET);
read(fd, ph.address, ph.filesz);
I would like to do something more like this though:
Code: Select all
mmap(ph.address, ph.memsz, ph.flags, MAP_PRIVATE, fd, ph.offset);
mmap() will truncate addresses to page boundaries, and the program header might not align that way (e.g. the data section of my test program requests 0x1e74).
The other issue is that I'd pass memsz to mmap() so that it allocates a region large enough, but then it might over-read from the backing file, since memsz can be larger than filesz in the program header.
How should I deal with this? Or should I just keep doing it by allocating anonymous memory and reading the file into it.
I'm not really bothered about remaining POSIX compatible, so if someone has a completely different solution that's neater, I'll happily accept/adapt it.
Thanks,
Barry