Skip to content

Commit 93ae33a

Browse files
committed
Add enter_unprivileged() function
This adds a function to switch to program stack and unprivileged mode. Fixes #583
1 parent d55d343 commit 93ae33a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

cortex-m/src/asm.rs

+30
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,36 @@ pub unsafe fn semihosting_syscall(mut nr: u32, arg: u32) -> u32 {
244244
nr
245245
}
246246

247+
/// Switch to unprivileged mode.
248+
///
249+
/// Sets CONTROL.SPSEL (setting the program stack to be the active
250+
/// stack) and CONTROL.nPRIV (setting unprivileged mode), updates the
251+
/// program stack pointer to the address in `psp`, then jumps to the
252+
/// address in `entry`.
253+
///
254+
/// # Safety
255+
///
256+
/// `psp` and `entry` must point to valid stack memory and executable
257+
/// code, respectively.
258+
#[cfg(cortex_m)]
259+
#[inline(always)]
260+
fn enter_unprivileged(psp: &u32, entry: fn() -> !) -> ! {
261+
unsafe {
262+
asm!(
263+
"mrs {tmp}, CONTROL",
264+
"orr {tmp}, #2",
265+
"msr PSP, {psp}",
266+
"msr CONTROL, {tmp}",
267+
"isb",
268+
"bx {ent}",
269+
tmp = in(reg) 0,
270+
psp = in(reg) psp,
271+
ent = in(reg) entry,
272+
options(noreturn, nomem, nostack)
273+
);
274+
}
275+
}
276+
247277
/// Bootstrap.
248278
///
249279
/// Clears CONTROL.SPSEL (setting the main stack to be the active stack),

0 commit comments

Comments
 (0)