Static variables are not initialized to zero in code

I've got the following:

    #[repr(transparent)]
    pub struct AtomicBitmap64(AtomicU64);

    impl AtomicBitmap64 {
        pub const fn new() -> Self {
            AtomicBitmap64(AtomicU64::new(0))
        }

        pub fn set_bit(&self, n: u8) -> bool {
            let b: u64 = 1 << (n as u64);
            self.0.fetch_or(b, Ordering::AcqRel) & b != 0
        }

        pub fn clear_bit(&self, n: u8) -> bool {
            let b: u64 = 1 << (n as u64);
            self.0.fetch_and(!b, Ordering::AcqRel) & b != 0
        }

        pub fn invert_bit(&self, n: u8) -> bool {
            let b: u64 = 1 << (n as u64);
            self.0.fetch_xor(b, Ordering::AcqRel) & b != 0
        }
    }

Then, somewhere in code, I have a static variable initialized:

static MY_BITMAP: AtomicBitmap64 = AtomicBitmap64::new();

When I disassemble the resulting image, I see the static in .bss section, but it is never initialized to 0 in code. Am I doing anything wrong? Do I need to initialize the whole .bss section manually? (If yes, then how to do it properly)?

The .bss section is automatically zero-initialized by the OS. You shouldn't need to do that manually.

I build for bare metal, the flat binary runs without underlying OS.

Which hardware/platform are you developing for? The Embedonomicon mentions that for ARM Cortext-M bare metal applications, a linker script is responsible for initializing sections, like this. (I'm no expert with embedded Rust, though…)

2 Likes

I develop for AArch64 (Cortex-A72). I first build ELF object, and then objcopy -O binary to produce the final binary image. I see there's in fact zero-initialized .bss section in ELF object, which gets truncated by objcopy. I will check the link you provided, thanks!

1 Like

Yep, looks like this is exactly what I needed. Thanks

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.