Skip to content

Commit 1ffbd38

Browse files
authored
Use a hardcoded constant instead of calling OpenProcessToken.
Now that Win 7 support is dropped, we can resurrect rust-lang#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 4451777 commit 1ffbd38

File tree

1 file changed

+8
-14
lines changed
  • library/std/src/sys/windows

1 file changed

+8
-14
lines changed

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

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -320,22 +320,16 @@ pub fn temp_dir() -> PathBuf {
320320

321321
#[cfg(not(target_vendor = "uwp"))]
322322
fn home_dir_crt() -> Option<PathBuf> {
323-
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.
328-
use crate::sys::handle::Handle;
329-
330-
let me = c::GetCurrentProcess();
331-
let mut token = ptr::null_mut();
332-
if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 {
333-
return None;
334-
}
335-
let _handle = Handle::from_raw_handle(token);
323+
// Defined in processthreadsapi.h.
324+
const CURRENT_PROCESS_TOKEN: usize = -4isize as usize;
325+
336326
super::fill_utf16_buf(
337327
|buf, mut sz| {
338-
match c::GetUserProfileDirectoryW(token, buf, &mut sz) {
328+
match c::GetUserProfileDirectoryW(
329+
ptr::from_exposed_addr_mut(CURRENT_PROCESS_TOKEN),
330+
buf,
331+
&mut sz,
332+
) {
339333
0 if api::get_last_error().code != c::ERROR_INSUFFICIENT_BUFFER => 0,
340334
0 => sz,
341335
_ => sz - 1, // sz includes the null terminator

0 commit comments

Comments
 (0)