Commit 7cc4526d authored by David Brown's avatar David Brown Committed by David Brown
Browse files

sim: unsafe cleanup

Cleanup some of the unsafe usage in mcuboot-sys.  In one case, add a
safety comment to the function documentation.  In the other, move the
unsafe to a narrower scope, reducing the number of instances of unsafe
needed.  From clippy suggestions.

Signed-off-by: default avatarDavid Brown <david.brown@linaro.org>
parent fc8e3c5b
Loading
Loading
Loading
Loading
+10 −3
Changes for sim/mcuboot-sys/src/api.rs: 10 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -94,20 +94,27 @@ thread_local! {
    pub static SIM_CTX: RefCell<CSimContextPtr> = RefCell::new(CSimContextPtr::new());
}

// Set the flash device to be used by the simulation.  The pointer is unsafely stashed away.
pub unsafe fn set_flash(dev_id: u8, dev: &mut dyn Flash) {
/// Set the flash device to be used by the simulation.  The pointer is unsafely stashed away.
///
/// # Safety
///
/// This uses mem::transmute to stash a Rust pointer into a C value to
/// retrieve later.  It should be safe to use this.
pub fn set_flash(dev_id: u8, dev: &mut dyn Flash) {
    THREAD_CTX.with(|ctx| {
        ctx.borrow_mut().flash_params.insert(dev_id, FlashParamsStruct {
            align: dev.align() as u16,
            erased_val: dev.erased_val(),
        });
        unsafe {
            let dev: &'static mut dyn Flash = mem::transmute(dev);
            ctx.borrow_mut().flash_map.insert(
                dev_id, FlashPtr{ptr: dev as *mut dyn Flash});
        }
    });
}

pub unsafe fn clear_flash(dev_id: u8) {
pub fn clear_flash(dev_id: u8) {
    THREAD_CTX.with(|ctx| {
        ctx.borrow_mut().flash_map.remove(&dev_id);
    });
+1 −5
Changes for sim/mcuboot-sys/src/c.rs: 1 added line, 5 removed lines.
Original line number Diff line number Diff line
@@ -13,11 +13,9 @@ use crate::api;
/// Invoke the bootloader on this flash device.
pub fn boot_go(multiflash: &mut SimMultiFlash, areadesc: &AreaDesc,
               counter: Option<&mut i32>, catch_asserts: bool) -> (i32, u8) {
    unsafe {
    for (&dev_id, flash) in multiflash.iter_mut() {
        api::set_flash(dev_id, flash);
    }
    }
    let mut sim_ctx = api::CSimContext {
        flash_counter: match counter {
            None => 0,
@@ -33,11 +31,9 @@ pub fn boot_go(multiflash: &mut SimMultiFlash, areadesc: &AreaDesc,
    };
    let asserts = sim_ctx.c_asserts;
    counter.map(|c| *c = sim_ctx.flash_counter);
    unsafe {
        for (&dev_id, _) in multiflash {
    for &dev_id in multiflash.keys() {
        api::clear_flash(dev_id);
    }
    };
    (result, asserts)
}