Search code examples
embeddedruststartupbare-metal

How do I write Rust code that places globals / statics in a populated BSS segment?


I'm experimenting with programming bare-metal embedded systems in Rust. One of the things that is typically done in C startup code is zero-initializing the BSS segment for any global or static uninitialized variables.

However, in Rust, I can't figure out how to create any global or static uninitialized variables (even using unsafe code). In other words, I can't figure out how to write any Rust code so the compiler will populate the BSS segment with something.

I tried...

static BSS_Data: i32 = unsafe { core::mem::uninitialized() };

....but the compiler rejected it.

Is there any way to write Rust code (unsafe or otherwise) that will result in a populated BSS segment? Is the BSS segment guaranteed to always be empty in any program written entirely in Rust?


Solution

  • The purpose of the .bss segment is to speed up initialization of all static storage duration variables with value zero. But also to save NVM, since it doesn't make sense to save x bytes all with the value 0 in flash and then copy them to RAM one by one.

    The solution to your problem might be to declare a static variable and explicitly initialize it to zero. Because all variables with static storage duration that are initialized to value zero end up in .bss.

    As a side-effect of this, all uninitialized static storage duration variables also end up in .bss too. Because in C (and in languages derived from/inspired by C) there is a requirement that if a variable with static storage duration is not initialized explicitly by the programmer, it must be initialized to value zero.

    For example this is formally specified in the C11 standard 6.7.9:

    If an object that has static or thread storage duration is not initialized explicitly, then:
    — if it has pointer type, it is initialized to a null pointer;
    — if it has arithmetic type, it is initialized to (positive or unsigned) zero;


    Pseudo code example of how .data and .bss initialization will differ.

    More info of the different memory types and where different kind of variables end up in an embedded system.