Skip to content

Commit

Permalink
Merge pull request #247 from rtbo/fix_246
Browse files Browse the repository at this point in the history
dereferencing through `copy_nonoverlapping`
  • Loading branch information
rtbo authored Dec 4, 2023
2 parents d2314cd + 1e8c33d commit c5411cd
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
7 changes: 5 additions & 2 deletions build/cg/struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1622,7 +1622,10 @@ impl CodeGen {
" let ptr = self.wire_ptr().add(offset) as *const {};",
q_rs_typ
)?;
writeln!(out, " let val = *ptr as u32;")?;
writeln!(
out,
" let val = base::value_from_ptr(ptr) as u32;"
)?;
writeln!(
out,
" std::mem::transmute::<u32, {}>(val)",
Expand Down Expand Up @@ -1711,7 +1714,7 @@ impl CodeGen {
cg::ind(3),
q_rs_typ
)?;
writeln!(out, " *ptr")?;
writeln!(out, "{}base::value_from_ptr(ptr)", cg::ind(3),)?;
writeln!(out, " }}")?;
writeln!(out, " }}")?;
}
Expand Down
11 changes: 11 additions & 0 deletions src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1750,6 +1750,17 @@ pub(crate) fn align_pad(base: usize, align: usize) -> usize {
(-base & (align - 1)) as usize
}

/// Get a value from a pointer, using ptr::copy_nonoverlapping to avoid alignment issues
///
/// # Safety
/// The pointer must point to a valid `T` value
#[inline]
pub(crate) unsafe fn value_from_ptr<T>(ptr: *const T) -> T {
let mut val = mem::MaybeUninit::<T>::uninit();
ptr::copy_nonoverlapping(ptr, val.as_mut_ptr(), 1);
val.assume_init()
}

#[test]
fn test_align_pad() {
// align 1
Expand Down

0 comments on commit c5411cd

Please sign in to comment.