From b2ba7383b089a3045db75b44d2e7cb691ddd3286 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Tue, 5 Apr 2022 08:52:10 -0700 Subject: [PATCH] windows: procinfo: extra defensive coding around reading proc info Might possibly help with #1699 --- procinfo/src/windows.rs | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/procinfo/src/windows.rs b/procinfo/src/windows.rs index 449028f36..46f0430b7 100644 --- a/procinfo/src/windows.rs +++ b/procinfo/src/windows.rs @@ -254,22 +254,40 @@ impl ProcHandle { } /// Copies a sized WSTR from the address in the process - fn read_process_wchar(&self, ptr: LPVOID, size: usize) -> Option> { - let mut buf = vec![0u16; size / 2]; + fn read_process_wchar(&self, ptr: LPVOID, byte_size: usize) -> Option> { + let mut buf = vec![0u16; byte_size / 2]; + let mut bytes_read = 0; let res = unsafe { ReadProcessMemory( self.0, ptr as _, buf.as_mut_ptr() as _, - size, - std::ptr::null_mut(), + byte_size, + &mut bytes_read, ) }; if res == 0 { return None; } + // In the unlikely event that we have a short read, + // truncate the buffer to fit. + let wide_chars_read = bytes_read / 2; + buf.resize(wide_chars_read, 0); + + // Ensure that it is NUL terminated + match buf.iter().position(|&c| c == 0) { + Some(n) => { + // Truncate to include existing NUL but no later chars + buf.resize(n + 1, 0); + } + None => { + // Add a NUL + buf.push(0); + } + } + Some(buf) }