mihe wrote:The second stage keeps growing, and I just copy a lump amount of sectors from the disk containing the loader and kernel concatenated, so this way I just find where it is in every run. I guess I could align the loader and the kernel properly when concatenating the files to a well-known position, but I wanted to do that combing function to practice asm and learn a bit. Regards.
Or you could use the linker script to define an ABS label at the end of your loader (which will be the start for your kernel).
About ELF parsing, that's not that hard. If you want an example, take a look at my bootloader:
- the UEFI version (written in C) is straightforward, easy to read:
https://gitlab.com/bztsrc/bootboot/blob ... ot.c#L1084
- the BIOS version (written in ASM) does the same, but it's a bit harder to read:
https://gitlab.com/bztsrc/bootboot/blob ... .asm#L1582
Because I load the kernel dynamically, I have core.ptr (in C) and esi (in ASM) to point to the kernel. The steps required are as follows:
1. Check magic bytes to see if it's a valid executable binary for the architecture (I also allow to have "OS/Z" as magic instead of ELF magic, you won't need that part)
2. You have to iterate on the Program Headers looking for segments which have "loadable" flag set. Each segment have to be loaded/mapped at it's p_vaddr
3. There are at least two segments: text (for the program code) and data. Data segment has different file size and memsize. The difference must be zerod out by the ELF loader, as that's the BSS (for example data segment's memsize is 4096, but it's file size is 256. That means only the first 256 bytes are initialized and stored in the ELF, the rest must be zerod out).
4. Entry point is at a fixed offset in the ELF header (which is not a file offset, but a memory address according to the text segment's p_vaddr)
What can be tricky is, that the text segment by default does not contain the ELF header and the Program Headers. That means you have to copy the file contents from the ELF into their final poisition (due to alignment issues, text offset is for example at 0xE8 in the file, but expected to start at a page aligned address in memory). With a special linker script, you can include the ELF headers in the text segment, and with that both file offset and memory address will share the same alignment. For example:
Code: Select all
PHDRS
{
text PT_LOAD FILEHDR PHDRS;
}
Cheers,
bzt