Skip to content

Commit b4ef954

Browse files
authored
Ensure utf16 string is created from aligned data (#445)
1 parent 256538e commit b4ef954

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

crates/winmd/src/parsed/blob.rs

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -78,13 +78,22 @@ impl Blob {
7878
}
7979

8080
pub fn read_utf16(&self) -> String {
81-
let bytes = self.reader.files[self.file_index as usize].bytes[self.offset..].as_ptr();
82-
unsafe {
83-
String::from_utf16(std::slice::from_raw_parts(
84-
bytes as *const u16,
85-
self.size / 2,
86-
))
87-
.unwrap()
81+
let bytes = &self.reader.files[self.file_index as usize].bytes[self.offset..];
82+
if bytes.as_ptr().align_offset(std::mem::align_of::<u16>()) > 0 {
83+
let bytes = bytes
84+
.chunks_exact(2)
85+
.take(self.size / 2)
86+
.map(|chunk| u16::from_le_bytes(chunk.try_into().unwrap()))
87+
.collect::<Vec<u16>>();
88+
String::from_utf16(&bytes).unwrap()
89+
} else {
90+
assert!(
91+
bytes.len() >= self.size,
92+
"Attempt to read from end of memory"
93+
);
94+
let bytes =
95+
unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const u16, self.size / 2) };
96+
String::from_utf16(bytes).unwrap()
8897
}
8998
}
9099

0 commit comments

Comments
 (0)