How to write risc-v trap handler in rust?

fn trap_handler() {
    unsafe{
       ...
       asm!( "mret"); 
    }
}
pub extern "C" fn _start() -> ! {
    /* set mtvec  */
    type FnPtr = fn();
    let th: FnPtr = trap_handler;
    unsafe{
        asm!("csrw mtvec, {}", in(reg) th);
    }
}

Objdump:

80000030 <trap_handler>:
80000030: fc010113 addi sp,sp,-64
80000034: 10013537 lui a0,0x10013
80000140: 30200073 mret
80000144: 04010113 addi sp,sp,64 => skipped
80000148: 00008067 ret

As observed above, rust compiler treats this as a normal function and returns with ret. However, trap handler in RISC-V returns with mret in machine mode causing the stack pointer to mis-align. How should this be fixed?

no need for inline assembly. use the riscv-rt crate. see:

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.