From 5f360abdc795ad7467699cc7dddd5b3a5558dcdf Mon Sep 17 00:00:00 2001 From: Julian Schindel Date: Wed, 29 Apr 2026 21:55:06 +0200 Subject: [PATCH] arch: replace `as ` casts with safer alternatives `as` casts can change mutability, which quickly leads to undefined behavior. Signed-off-by: Julian Schindel --- arch/src/x86_64/mptable.rs | 3 ++- arch/src/x86_64/smbios.rs | 3 ++- arch/src/x86_64/tdx/mod.rs | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/arch/src/x86_64/mptable.rs b/arch/src/x86_64/mptable.rs index c31c9e411..203d55fa2 100644 --- a/arch/src/x86_64/mptable.rs +++ b/arch/src/x86_64/mptable.rs @@ -101,8 +101,9 @@ const CPU_FEATURE_APIC: u32 = 0x200; const CPU_FEATURE_FPU: u32 = 0x001; fn compute_checksum(v: &T) -> u8 { + let v: *const T = v; // SAFETY: we are only reading the bytes within the size of the `T` reference `v`. - let v_slice = unsafe { slice::from_raw_parts(v as *const T as *const u8, mem::size_of::()) }; + let v_slice = unsafe { slice::from_raw_parts(v.cast(), mem::size_of::()) }; let mut checksum: u8 = 0; for i in v_slice.iter() { checksum = checksum.wrapping_add(*i); diff --git a/arch/src/x86_64/smbios.rs b/arch/src/x86_64/smbios.rs index b9db0fcb9..6f1139888 100644 --- a/arch/src/x86_64/smbios.rs +++ b/arch/src/x86_64/smbios.rs @@ -49,8 +49,9 @@ const PCI_SUPPORTED: u64 = 1 << 7; const IS_VIRTUAL_MACHINE: u8 = 1 << 4; fn compute_checksum(v: &T) -> u8 { + let v: *const T = v; // SAFETY: we are only reading the bytes within the size of the `T` reference `v`. - let v_slice = unsafe { slice::from_raw_parts(v as *const T as *const u8, mem::size_of::()) }; + let v_slice = unsafe { slice::from_raw_parts(v.cast(), mem::size_of::()) }; let mut checksum: u8 = 0; for i in v_slice.iter() { checksum = checksum.wrapping_add(*i); diff --git a/arch/src/x86_64/tdx/mod.rs b/arch/src/x86_64/tdx/mod.rs index a6ce96aae..53e004c5b 100644 --- a/arch/src/x86_64/tdx/mod.rs +++ b/arch/src/x86_64/tdx/mod.rs @@ -163,7 +163,7 @@ pub fn parse_tdvf_sections(file: &mut File) -> Result<(Vec, bool), // SAFETY: we read exactly the size of the descriptor header file.read_exact(unsafe { std::slice::from_raw_parts_mut( - &mut descriptor as *mut _ as *mut u8, + (&raw mut descriptor).cast(), std::mem::size_of::(), ) }) @@ -190,7 +190,7 @@ pub fn parse_tdvf_sections(file: &mut File) -> Result<(Vec, bool), // SAFETY: we read exactly the advertised sections file.read_exact(unsafe { std::slice::from_raw_parts_mut( - sections.as_mut_ptr() as *mut u8, + sections.as_mut_ptr().cast(), descriptor.num_sections as usize * std::mem::size_of::(), ) })