|
| 1 | +//! Example triggering a undef exception. |
| 2 | +
|
| 3 | +#![no_std] |
| 4 | +#![no_main] |
| 5 | + |
| 6 | +use core::sync::atomic::{AtomicU32, Ordering}; |
| 7 | +use semihosting::println; |
| 8 | + |
| 9 | +// pull in our start-up code |
| 10 | +use versatileab as _; |
| 11 | + |
| 12 | +static COUNTER: AtomicU32 = AtomicU32::new(0); |
| 13 | + |
| 14 | +/// The entry-point to the Rust application. |
| 15 | +/// |
| 16 | +/// It is called by the start-up. |
| 17 | +#[no_mangle] |
| 18 | +pub extern "C" fn kmain() -> ! { |
| 19 | + println!("Hello, this is a undef exception example"); |
| 20 | + |
| 21 | + unsafe { |
| 22 | + // trigger an Undefined exception, from T32 (Thumb) mode |
| 23 | + udf_from_t32(); |
| 24 | + } |
| 25 | + |
| 26 | + // this should be impossible because returning from the fault handler will |
| 27 | + // immediately trigger the fault again. |
| 28 | + |
| 29 | + unreachable!("should never be here!"); |
| 30 | +} |
| 31 | + |
| 32 | +// These functions are written in assembly |
| 33 | +extern "C" { |
| 34 | + fn udf_from_t32(); |
| 35 | +} |
| 36 | + |
| 37 | +core::arch::global_asm!( |
| 38 | + r#" |
| 39 | + // fn udf_from_t32(); |
| 40 | + .thumb |
| 41 | + .global udf_from_t32 |
| 42 | + .type udf_from_t32, %function |
| 43 | + udf_from_t32: |
| 44 | + udf #0 |
| 45 | + bx lr |
| 46 | + .size udf_from_t32, . - udf_from_t32 |
| 47 | +"# |
| 48 | +); |
| 49 | + |
| 50 | +#[unsafe(no_mangle)] |
| 51 | +unsafe extern "C" fn _prefetch_handler(_addr: usize) { |
| 52 | + panic!("unexpected undefined exception"); |
| 53 | +} |
| 54 | + |
| 55 | +#[unsafe(no_mangle)] |
| 56 | +unsafe extern "C" fn _undefined_handler(addr: usize) { |
| 57 | + println!("undefined abort occurred"); |
| 58 | + |
| 59 | + if (addr + 1) == udf_from_t32 as usize { |
| 60 | + // note that thumb functions have their LSB set, despite always being a |
| 61 | + // multiple of two - that's how the CPU knows they are written in T32 |
| 62 | + // machine code. |
| 63 | + println!("caught udf_from_t32"); |
| 64 | + } else { |
| 65 | + println!( |
| 66 | + "Bad fault address {:08x} is not {:08x}", |
| 67 | + addr, udf_from_t32 as usize |
| 68 | + ); |
| 69 | + } |
| 70 | + |
| 71 | + if COUNTER.fetch_add(1, Ordering::Relaxed) == 1 { |
| 72 | + // we've faulted twice - time to quit |
| 73 | + semihosting::process::exit(0); |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +#[unsafe(no_mangle)] |
| 78 | +unsafe extern "C" fn _abort_handler(_addr: usize) { |
| 79 | + panic!("unexpected abort exception"); |
| 80 | +} |
0 commit comments