Skip to content

Ensure utf16 string is created from aligned data #445

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 26, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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