I understand that the program break is the highest virtual memory address that the Linux OS has allocated for a process, and therefore marks the highest address of the heap. You can get the address of the program break by calling sbrk( 0 ).
When I create the following trivial program, I get different results each time it's run:
#define _BSD_SOURCE
#include <stdio.h>
#include <unistd.h>
int main()
{
printf( "system break: %p\n", sbrk( 0 ) );
return 0;
}
For example, on my PC:
$ ./sbrk
system break: 0x81fc000
$ ./sbrk
system break: 0x9bce000
$ ./sbrk
system break: 0x97a6000
My understanding was that the heap is allocated immediately above the BSS section in virtual memory - I guess I was expecting that it would always have the same initial value for a trivial program like this. Is there some randomization or something in where the program break is initially positioned? If not, why is it different each time I run the program?
By default the kernel will randomise the initial point, though this feature can be disabled. This is the code that is run (for x86, in arch/x86/kernel/process.c):
unsigned long arch_randomize_brk(struct mm_struct *mm)
{
unsigned long range_end = mm->brk + 0x02000000;
return randomize_range(mm->brk, range_end, 0) ? : mm->brk;
}
Additionally, in this function from the ELF binary loader (fs/binfmt_elf.c), you can see the function called:
if ((current->flags & PF_RANDOMIZE) && (randomize_va_space > 1)) {
current->mm->brk = current->mm->start_brk =
arch_randomize_brk(current->mm);
#ifdef CONFIG_COMPAT_BRK
current->brk_randomized = 1;
#endif
}
Yes there is randomistion. Known as Address Space Layout Randomisation (ASLR). http://en.wikipedia.org/wiki/Address_space_layout_randomization
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With