简体   繁体   中英

Why can I get the elf entry without the help of a base address?

I'm trying to get the kernel entry function in the UEFI bootloader and im so confused.

Why does this code work?

  int (*kmain)(void*) = (int(*)(void*)) (elf->entry);

this is what I link it with

gcc -no-pie -nostdlib -ffreestanding -e kmain -o kernel.elf kernel.o

I know it has something to do with -no-pie since without it wont work

elf->entry is a virtual address but since i am in the bootloader it references a physical address right?

How can the linker know what to set the entry to, without having access to ram? What if elf->entry is 0x4000, then it goes into the physical address 0x4000 but WHAT if physical address 0x4000 is already in use by something else?

Without -no-pie I had to do it with base + elf->entry where base is the start of the elf file, and that I can totally understand, but I cant understand how just elf->entry can be OK

The linker, as a rule, doesn't really care where in memory it places anything. It's primary job is to make sure that all memory references are consistent, no matter how memory is laid out. The purpose of a linker script is to tell the linker how to lay out the memory. If you don't provide a linker script, it will use its own defaults. In other words, the linker doesn't know or care whether you have something already loaded at 0x4000. It's your job to know how your memory is laid out, and to provide a linker script if you want it laid out in a specific way.

As for the -no-pie bit of the question, that comes down to how position-independent and non-position-independent executables are loaded. Your UEFI bootloader is, among other things, a loader. There is a flag in the executable telling the loader whether or not it's a PIE. If it's not, then the loader just has to use the exact addresses encoded in the file. In this case, the elf->entry pointer will be exactly correct. If it is a PIE, then the loader can place it at whatever memory address it likes, in which case the elf->entry pointer will be relative to the address at which the executable is loaded. That's why you need to use base + elf->entry when you don't provide the -no-pie flag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM