Release build works but Debug build fails

Hi! As @trembel mentioned you might be better off posting in the Embedded Rust matrix chat, but I can briefly answer some of your questions:

The cortex-m crate provides intrinsics like MSR which are not (yet) in core::arch, but since inline assembly is not yet on stable, it provides a precompiled binary object file which contains those intrinsics as function calls and is linked in to your final build at link time. For a normal debug release, the linker doesn't try to inline those function calls, and optimisations that might remove stack usage are not enabled. That means that the function call may modify the stack pointer and then try to use the stack, which obviously causes immediate issues. With the inline_asm feature, the intrinsics are emitted directly in your function, so there's no extra function call. However, since you then call unwrap() after changing the stack pointer, which is also a function call, you can run into the same problem.

I recommend making JUMP a non-option local variable so you don't need to unwrap it at all:

        // Get new stack pointer and jump address
        let sp = core::ptr::read_volatile(0 as *const u32);
        let rv = core::ptr::read_volatile(4 as *const u32);
        let bootloader: extern "C" fn() = core::mem::transmute(rv);

        // Write new stack pointer to MSP and call into bootloader
        cortex_m::register::msp::write(sp);
        bootloader();

You might also try enabling LTO in your debug builds:

[profile.debug]
codegen-units = 1
incremental = false
debug = true
lto = true

But overall, I suggest just using release builds for embedded development, as generally debug builds are very bloated and often won't even fit in flash, or cause timing issues which waste debugging time. It's not ideal as debugging is then much more annoying of course.

You're not the first person to run into trouble trying to jump to a bootloader like this, hopefully the new inline assembly coming soon will make it a bit easier.

There's no issue with your compiler versions.

1 Like