Search code examples
ldcortex-mlinker-scripts

How can I make an empty section with GNU ld?


I'm working on a cortex-m3 chip. The stack space was reserved in the source code with an uninitialized array on the bss section. The linker script I used is as follows:

MEMORY
{
    FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 256k
    SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 64k
}

SECTIONS {
    .text : {
        KEEP(*(.isr_vector))
        *(.text*)
        *(.rodata*)
        __text_end = .;
    } >FLASH

    .data : {
        __data_start = .;
        *(.data*)
        __data_end = .;
    } >SRAM AT>FLASH

    .bss : {
        __bss_start = .;
        *(.bss*)
        __bss_end = .;
    } >SRAM
}

I'm trying to allocate a section for the stack in the beginning of the SRAM region so that i could detect stack overflow with usage fault.

I added a section named .stack:

SECTIONS {
    .text : {
        :
    } >FLASH

    .stack : {
        __stack_size = 4k;
        __stack_start = .;
        . = . + __stack_size;
        . = ALIGN(8);         /* cortex-m3 uses full-descending stack aligned with 8 bytes */
        __stack_end = .;
    } >SRAM

    .data : {
        :
    } >SRAM AT>FLASH

    .bss : {
        :
    } >SRAM
}

Linking is done without any error or warning, but the problem is that __stack_end is not on the SRAM region but on the FLASH region.

I know I can use a separate section given with __attribute__((section("name"))) but I think it would be better if I can deal with it in the linker script.

How can I make an empty section on SRAM region?


Solution

  • Just split the RAM area in two:

    MEMORY
    {
        FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 256k
        SRAM_STACK (rwx) : ORIGIN = 0x20000000, LENGTH = 4k
        SRAM (rwx) : ORIGIN = 0x20001000, LENGTH = 60k
    }
    SECTIONS {
    .text : {
        KEEP(*(.isr_vector))
        *(.text*)
        *(.rodata*)
        __text_end = .;
    } >FLASH
    
    .data : {
         __data_start = .;
        *(.data*)
        __data_end = .;
    } >SRAM AT>FLASH
    
    .bss : {
        __bss_start = .;
        *(.bss*)
        __bss_end = .;
    } >SRAM
    
    .stack : {
        __stack_size = 4k;
        __stack_start = .;
        . = . + __stack_size;
        . = ALIGN(8);         /* cortex-m3 uses full-descending stack aligned with 8 bytes */
        __stack_end = .;
    } >SRAM_STACK
    
    }