Skip to content

Commit

Permalink
Ensure utf16 string is created from aligned data
Browse files Browse the repository at this point in the history
  • Loading branch information
rylev committed Jan 25, 2021
1 parent 256538e commit 4ef2112
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions crates/winmd/src/parsed/blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,22 @@ impl Blob {
}

pub fn read_utf16(&self) -> String {
let bytes = self.reader.files[self.file_index as usize].bytes[self.offset..].as_ptr();
unsafe {
String::from_utf16(std::slice::from_raw_parts(
bytes as *const u16,
self.size / 2,
))
.unwrap()
let bytes = &self.reader.files[self.file_index as usize].bytes[self.offset..];
if bytes.as_ptr().align_offset(std::mem::align_of::<u16>()) > 0 {
let bytes = bytes
.chunks_exact(2)
.take(self.size / 2)
.map(|chunk| u16::from_le_bytes(chunk.try_into().unwrap()))
.collect::<Vec<u16>>();
String::from_utf16(&bytes).unwrap()
} else {
assert!(
bytes.len() >= self.size,
"Attempt to read from end of memory"
);
let bytes =
unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const u16, self.size / 2) };
String::from_utf16(bytes).unwrap()
}
}

Expand Down

0 comments on commit 4ef2112

Please sign in to comment.