From 1b46db2c4ef12e31a99166307aca2a29d28829e8 Mon Sep 17 00:00:00 2001 From: marquezini Date: Mon, 23 Nov 2026 23:39:38 -0300 Subject: [PATCH] Kernel: GetModuleFileName of a title image into a null buffer A slice may not start at null, even an empty one, so asking for a title image's name with (NULL, 0) was undefined behaviour; a debug build aborted the process. A null buffer is now no buffer: nothing is written, 0 is returned and the last error is ERROR_INSUFFICIENT_BUFFER. (cherry picked from commit c000581df2cf12aaadfe49025f9abba8b5993c8e) --- crates/victory-hle/src/modules/kernel.rs | 37 +++++++++++++++++++----- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index d1604cc..83ce323 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -52,10 +52,7 @@ pub extern "system" fn GetModuleFileNameW(module: *mut c_void, out: *mut u16, si return host::get_module_file_name_w(module, out, size); }; let wide: Vec = path.encode_utf16().collect(); - // SAFETY: the title passes a buffer of `size` characters. - copy_truncated(&wide, unsafe { - std::slice::from_raw_parts_mut(out, size as usize) - }) + copy_truncated(&wide, title_buffer(out, size)) } /// See [`GetModuleFileNameW`]. @@ -63,10 +60,18 @@ pub extern "system" fn GetModuleFileNameA(module: *mut c_void, out: *mut u8, siz let Some(path) = title_path(module) else { return host::get_module_file_name_a(module, out, size); }; - // SAFETY: the title passes a buffer of `size` bytes. - copy_truncated(path.as_bytes(), unsafe { - std::slice::from_raw_parts_mut(out, size as usize) - }) + copy_truncated(path.as_bytes(), title_buffer(out, size)) +} + +/// The title's buffer of `size` elements; none for a null pointer (a slice +/// may not start at null, even an empty one, so `(NULL, 0)` would be +/// undefined behaviour). +fn title_buffer<'a, T>(out: *mut T, size: u32) -> &'a mut [T] { + if out.is_null() { + return &mut []; + } + // SAFETY: the title passes a buffer of `size` elements. + unsafe { std::slice::from_raw_parts_mut(out, size as usize) } } fn title_path(module: *mut c_void) -> Option { @@ -760,4 +765,20 @@ mod tests { assert!(!runtime.is_null()); assert_eq!(GetModuleHandleW(w("XGameRuntime.dll").as_ptr()), runtime); } + + /// No buffer: nothing written, the error says it was too small. + #[test] + fn a_title_image_name_into_no_buffer() { + let base = 0x7300_0000_0000; + runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe")); + let module = base as *mut c_void; + assert_eq!(GetModuleFileNameW(module, std::ptr::null_mut(), 0), 0); + assert_eq!(GetModuleFileNameA(module, std::ptr::null_mut(), 0), 0); + #[cfg(windows)] + { + // SAFETY: reads this thread's last error. + let last = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + assert_eq!(last, ERROR_INSUFFICIENT_BUFFER); + } + } }