Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux - why is the program break pointer (brk/sbrk) different each time a program is run?

Tags:

c

linux

gcc

sbrk

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?

like image 242
Chris Vig Avatar asked Mar 31 '15 01:03

Chris Vig


2 Answers

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
}
like image 90
teppic Avatar answered Oct 23 '22 19:10

teppic


Yes there is randomistion. Known as Address Space Layout Randomisation (ASLR). http://en.wikipedia.org/wiki/Address_space_layout_randomization

like image 44
kaylum Avatar answered Oct 23 '22 19:10

kaylum