Skip to content

Hard fault on debug compilation #583

Open
@kevinbube

Description

@kevinbube

Hello all,
I am experimenting with an STM32F303 and try to enter unprivileged mode with program stack pointer set. I use the following minimal example:

#![no_std]
#![no_main]

use panic_halt as _;
use cortex_m_rt::entry;
use cortex_m_semihosting::hprintln;
use stm32f3xx_hal::prelude::*;
                    
#[entry]
fn entry() -> ! {
    extern "C" {
        static _user_stack_start: u32;
    }

    // set unprivileged stack
    unsafe {
        let stack_addr = &_user_stack_start as *const u32 as u32;
        cortex_m::register::psp::write(stack_addr)
    };
    
    let mut ctrl_reg = cortex_m::register::control::read();
    ctrl_reg.set_npriv(cortex_m::register::control::Npriv::Unprivileged);
    ctrl_reg.set_spsel(cortex_m::register::control::Spsel::Psp);

    // enter unprivileged mode
    unsafe { cortex_m::register::control::write(ctrl_reg) };

    main();
}

fn main() -> ! {
    hprintln!("hello");

    loop {}
}

On a debug build this causes a hard fault at control::write(). On release build it works fine. I guess this is because the compiler does not inline the call on debug and the function crashes on return as it fails to pop the return address from the stack, which changed from MSP to PSP.

Maybe #[inline(always)] is necessary for control::write()?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions