rtt-target icon indicating copy to clipboard operation
rtt-target copied to clipboard

Eliminate some simple unsafe operations

Open tgross35 opened this issue 1 year ago • 4 comments

Replace pointer methods with slice copies and a transmute with into

tgross35 avatar Mar 06 '23 19:03 tgross35

Did you test this on target? :)

Yatekii avatar Mar 06 '23 20:03 Yatekii

This week I have no target with me :(

I did do a unit tests https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=80b5d3b9bc4063e43f01b4adf4269707 but testing on hardware would be better of course

tgross35 avatar Mar 06 '23 22:03 tgross35

I think the ptr::copy_nonoverlapping was meant to try to persuade the compiler to never optimize the writes in any way, but I guess the real way to do that would be to use ptr::write_volatile for that (too bad we still don't have volatile_copy_nonoverlapping_memory)

mvirkkunen avatar Mar 06 '23 22:03 mvirkkunen

Hm, does the fence not provide sufficient guarantees there?

A volatile memcpy would work (with the bonus of zip being limited to the shorter of the two buffer lengths):

const ID_VAL: &[u8] = b"SEGGER RTT";
debug_assert!(ID_VAL.len() <= id.len());
for (src, dest) in ID_VAL.iter().zip(id.iter_mut()) {
    unsafe { ptr::write_volatile(dest, *src) };
}

copy_from_slice is just a wrapper around copy_nonoverlapping fwiw

https://github.com/rust-lang/rust/blob/f63ccaf25f74151a5d8ce057904cd944074b01d2/library/core/src/slice/mod.rs#L3354-L3356

tgross35 avatar Mar 06 '23 22:03 tgross35