From c939c85a2bda054534f5554522324b003100ee02 Mon Sep 17 00:00:00 2001 From: George Tokmaji Date: Sun, 30 Aug 2026 21:27:06 +0200 Subject: [PATCH] Fix UB due to null pointers passed to std::slice::from_raw_parts{,-mut} if an empty unicode string has a null pointer as buffer --- src/unicode_string/str.rs | 6 +++++- src/unicode_string/strmut.rs | 7 ++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/unicode_string/str.rs b/src/unicode_string/str.rs index ea44ed2..7d14161 100644 --- a/src/unicode_string/str.rs +++ b/src/unicode_string/str.rs @@ -33,7 +33,11 @@ impl<'a> NtUnicodeStr<'a> { /// Returns a slice to the raw [`u16`] codepoints of the string. pub fn as_slice(&self) -> &'a [u16] { - unsafe { slice::from_raw_parts(self.raw.buffer, self.len_in_elements()) } + if self.raw.buffer.is_null() { + &[] + } else { + unsafe { slice::from_raw_parts(self.raw.buffer, self.len_in_elements()) } + } } /// Returns a [`U16Str`] reference for this string. diff --git a/src/unicode_string/strmut.rs b/src/unicode_string/strmut.rs index 950f2cf..52f8332 100644 --- a/src/unicode_string/strmut.rs +++ b/src/unicode_string/strmut.rs @@ -33,7 +33,12 @@ impl<'a> NtUnicodeStrMut<'a> { /// Returns a mutable slice to the raw `u16` codepoints of the string. pub fn as_mut_slice(&mut self) -> &'a mut [u16] { - unsafe { slice::from_raw_parts_mut(self.raw.buffer, self.len_in_elements()) } + if self.raw.buffer.is_null() { + &mut [] + } + else { + unsafe { slice::from_raw_parts_mut(self.raw.buffer, self.len_in_elements()) } + } } /// Returns a mutable [`U16Str`] reference for this string.