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

2

6

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?

Soutane answered 31/3, 2015 at 1:6 Comment(0)
C
6

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
}
Champlin answered 31/3, 2015 at 1:49 Comment(0)
J
5

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

Japan answered 31/3, 2015 at 1:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.