Question

Can I change the default virtual address(ph_vaddr) in the elf to 0x0. will this allow access to null pointer?? or the kernel does not allow to load at address 0?

I just want to know that if I change the p_vaddr of some section say .text to 0x0, does linux allow this? Is there some constraint that virtual address can start only after some value? Whenever I was trying to set .text vaddr using ld --section-start anywhere between 0 to 9999 it was getting killed. I want to know what is going on??

Was it helpful?

Solution

Can I change the default virtual address(ph_vaddr) in the elf to 0x0.

Yes, that is in fact how PIE (position independent) executables are usually linked.

echo "int main() { return 0; }" | gcc -xc - -fPIE -pie -o a.out
readelf -l a.out | grep LOAD | head -1

LOAD           0x0000000000000000 0x0000000000000000 0x0000000000000000

Note: above makes an executable that is of type ET_DYN.

will this allow access to null pointer?

No. When the kernel discovers that the .e_type == ET_DYN for the executable, it will relocate all of its segments elsewhere.

You can also make an executable of type ET_EXEC with .p_vaddr == 0, like so:

echo "int main() { return 0; }" | gcc -xc - -o a.out -Wl,-Ttext=0
readelf -l a.out | grep LOAD | head -1
  LOAD           0x0000000000200000 0x0000000000000000 0x0000000000000000

The kernel will refuse to run it:

./a.out
Killed

OTHER TIPS

You could mmap(2) with MAP_FIXED a segment starting at (void*)0 but I don't think you should.

I have no idea if changing the virtual address in elf(5) would do the equivalent. Are you speaking of p_vaddr for some segment?

Actually, you should really not use the NULL address in application code on Linux, especially if some of that code is coded in C, because the NULL pointer has a very special meaning, including to the compiler. In particular, some optimizations are done based on the fact that NULL is not dereferencable.

It is well known that GCC does optimize, for instance,

 x = *p;
 if (!p) goto wasnull;

into just x= *p; because if phas been dereferenced it cannot be NULL; And GCC is right in doing that optimization for application code (not for free-standing one).

Also the kernel is usually doing Address Space Layout Randomization.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top