Skip to content

Commit 4071938

Browse files
committed
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.
1 parent bccb9bb commit 4071938

File tree

1 file changed

+26
-5
lines changed
  • library/std/src/sys/pal/windows

1 file changed

+26
-5
lines changed

library/std/src/sys/pal/windows/os.rs

+26-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! Implementation of `std::os` functionality for Windows.
22
3+
#![cfg_attr(bootstrap, allow(unexpected_cfgs))]
34
#![allow(nonstandard_style)]
45

56
#[cfg(test)]
@@ -318,13 +319,33 @@ pub fn temp_dir() -> PathBuf {
318319
super::fill_utf16_buf(|buf, sz| unsafe { c::GetTempPath2W(sz, buf) }, super::os2path).unwrap()
319320
}
320321

321-
#[cfg(not(target_vendor = "uwp"))]
322+
#[cfg(all(not(target_vendor = "uwp"), not(target_vendor = "win7")))]
323+
fn home_dir_crt() -> Option<PathBuf> {
324+
unsafe {
325+
// Defined in processthreadsapi.h.
326+
const CURRENT_PROCESS_TOKEN: usize = -4_isize as usize;
327+
328+
super::fill_utf16_buf(
329+
|buf, mut sz| {
330+
match c::GetUserProfileDirectoryW(
331+
ptr::invalid_mut(CURRENT_PROCESS_TOKEN),
332+
buf,
333+
&mut sz,
334+
) {
335+
0 if api::get_last_error().code != c::ERROR_INSUFFICIENT_BUFFER => 0,
336+
0 => sz,
337+
_ => sz - 1, // sz includes the null terminator
338+
}
339+
},
340+
super::os2path,
341+
)
342+
.ok()
343+
}
344+
}
345+
346+
#[cfg(target_vendor = "win7")]
322347
fn home_dir_crt() -> Option<PathBuf> {
323348
unsafe {
324-
// The magic constant -4 can be used as the token passed to GetUserProfileDirectoryW below
325-
// instead of us having to go through these multiple steps to get a token. However this is
326-
// not implemented on Windows 7, only Windows 8 and up. When we drop support for Windows 7
327-
// we can simplify this code. See #90144 for details.
328349
use crate::sys::handle::Handle;
329350

330351
let me = c::GetCurrentProcess();

0 commit comments

Comments
 (0)