std: Use read_unaligned for reading DWARF

This commit is contained in:
Jubilee Young 2024-07-15 20:18:56 -07:00
parent 24d2ac0b56
commit 8dafc5c819

View File

@ -17,32 +17,30 @@ pub struct DwarfReader {
pub ptr: *const u8, pub ptr: *const u8,
} }
#[repr(C, packed)] #[deny(unsafe_op_in_unsafe_fn)]
struct Unaligned<T>(T);
impl DwarfReader { impl DwarfReader {
pub fn new(ptr: *const u8) -> DwarfReader { pub fn new(ptr: *const u8) -> DwarfReader {
DwarfReader { ptr } DwarfReader { ptr }
} }
// DWARF streams are packed, so e.g., a u32 would not necessarily be aligned /// Read a type T and then bump the pointer by that amount.
// on a 4-byte boundary. This may cause problems on platforms with strict ///
// alignment requirements. By wrapping data in a "packed" struct, we are /// DWARF streams are "packed", so all types must be read at align 1.
// telling the backend to generate "misalignment-safe" code.
pub unsafe fn read<T: Copy>(&mut self) -> T { pub unsafe fn read<T: Copy>(&mut self) -> T {
let Unaligned(result) = *(self.ptr as *const Unaligned<T>); unsafe {
self.ptr = self.ptr.add(mem::size_of::<T>()); let result = self.ptr.cast::<T>().read_unaligned();
result self.ptr = self.ptr.byte_add(mem::size_of::<T>());
result
}
} }
// ULEB128 and SLEB128 encodings are defined in Section 7.6 - "Variable /// ULEB128 and SLEB128 encodings are defined in Section 7.6 - "Variable Length Data".
// Length Data".
pub unsafe fn read_uleb128(&mut self) -> u64 { pub unsafe fn read_uleb128(&mut self) -> u64 {
let mut shift: usize = 0; let mut shift: usize = 0;
let mut result: u64 = 0; let mut result: u64 = 0;
let mut byte: u8; let mut byte: u8;
loop { loop {
byte = self.read::<u8>(); byte = unsafe { self.read::<u8>() };
result |= ((byte & 0x7F) as u64) << shift; result |= ((byte & 0x7F) as u64) << shift;
shift += 7; shift += 7;
if byte & 0x80 == 0 { if byte & 0x80 == 0 {
@ -57,7 +55,7 @@ pub unsafe fn read_sleb128(&mut self) -> i64 {
let mut result: u64 = 0; let mut result: u64 = 0;
let mut byte: u8; let mut byte: u8;
loop { loop {
byte = self.read::<u8>(); byte = unsafe { self.read::<u8>() };
result |= ((byte & 0x7F) as u64) << shift; result |= ((byte & 0x7F) as u64) << shift;
shift += 7; shift += 7;
if byte & 0x80 == 0 { if byte & 0x80 == 0 {