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 5fa0d6a
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions crates/winmd/src/parsed/blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,19 @@ 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 5fa0d6a

Please sign in to comment.