From 40719384e1da64776d0ee67a84ffdfacc67816b0 Mon Sep 17 00:00:00 2001 From: Steven Date: Sat, 16 Dec 2023 19:29:45 -0500 Subject: [PATCH 1/2] Use a hardcoded constant instead of calling OpenProcessToken. Now that Win 7 support is dropped, we can resurrect #90144. GetCurrentProcessToken is defined in processthreadsapi.h as: FORCEINLINE HANDLE GetCurrentProcessToken ( VOID ) { return (HANDLE)(LONG_PTR) -4; } Since it's very unlikely that this constant will ever change, let's just use it instead of making calls to get the same information. --- library/std/src/sys/pal/windows/os.rs | 31 ++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/library/std/src/sys/pal/windows/os.rs b/library/std/src/sys/pal/windows/os.rs index 829dd5eb97ac2..58163f7a73faf 100644 --- a/library/std/src/sys/pal/windows/os.rs +++ b/library/std/src/sys/pal/windows/os.rs @@ -1,5 +1,6 @@ //! Implementation of `std::os` functionality for Windows. +#![cfg_attr(bootstrap, allow(unexpected_cfgs))] #![allow(nonstandard_style)] #[cfg(test)] @@ -318,13 +319,33 @@ pub fn temp_dir() -> PathBuf { super::fill_utf16_buf(|buf, sz| unsafe { c::GetTempPath2W(sz, buf) }, super::os2path).unwrap() } -#[cfg(not(target_vendor = "uwp"))] +#[cfg(all(not(target_vendor = "uwp"), not(target_vendor = "win7")))] +fn home_dir_crt() -> Option { + unsafe { + // Defined in processthreadsapi.h. + const CURRENT_PROCESS_TOKEN: usize = -4_isize as usize; + + super::fill_utf16_buf( + |buf, mut sz| { + match c::GetUserProfileDirectoryW( + ptr::invalid_mut(CURRENT_PROCESS_TOKEN), + buf, + &mut sz, + ) { + 0 if api::get_last_error().code != c::ERROR_INSUFFICIENT_BUFFER => 0, + 0 => sz, + _ => sz - 1, // sz includes the null terminator + } + }, + super::os2path, + ) + .ok() + } +} + +#[cfg(target_vendor = "win7")] fn home_dir_crt() -> Option { unsafe { - // The magic constant -4 can be used as the token passed to GetUserProfileDirectoryW below - // instead of us having to go through these multiple steps to get a token. However this is - // not implemented on Windows 7, only Windows 8 and up. When we drop support for Windows 7 - // we can simplify this code. See #90144 for details. use crate::sys::handle::Handle; let me = c::GetCurrentProcess(); From 3b63edeb9999b5b29826f018b2eabe702bee4e97 Mon Sep 17 00:00:00 2001 From: Steven Date: Fri, 16 Feb 2024 23:55:58 +0000 Subject: [PATCH 2/2] Remove cfg_attr --- library/std/src/sys/pal/windows/os.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/library/std/src/sys/pal/windows/os.rs b/library/std/src/sys/pal/windows/os.rs index 58163f7a73faf..73cb2db8b79e5 100644 --- a/library/std/src/sys/pal/windows/os.rs +++ b/library/std/src/sys/pal/windows/os.rs @@ -1,6 +1,5 @@ //! Implementation of `std::os` functionality for Windows. -#![cfg_attr(bootstrap, allow(unexpected_cfgs))] #![allow(nonstandard_style)] #[cfg(test)]