diff --git a/src/internal/syscall/windows/security_windows.go b/src/internal/syscall/windows/security_windows.go index 95694c368a..e528744caa 100644 --- a/src/internal/syscall/windows/security_windows.go +++ b/src/internal/syscall/windows/security_windows.go @@ -156,3 +156,22 @@ type UserInfo4 struct { // //go:linkname GetSystemDirectory func GetSystemDirectory() string // Implemented in runtime package. + +// GetUserName retrieves the user name of the current thread +// in the specified format. +func GetUserName(format uint32) (string, error) { + n := uint32(50) + for { + b := make([]uint16, n) + e := syscall.GetUserNameEx(format, &b[0], &n) + if e == nil { + return syscall.UTF16ToString(b[:n]), nil + } + if e != syscall.ERROR_MORE_DATA { + return "", e + } + if n <= uint32(len(b)) { + return "", e + } + } +} diff --git a/src/os/user/lookup_windows.go b/src/os/user/lookup_windows.go index f259269a53..edecac703a 100644 --- a/src/os/user/lookup_windows.go +++ b/src/os/user/lookup_windows.go @@ -232,12 +232,24 @@ func current() (*User, error) { if e != nil { return e } - username, domain, e := lookupUsernameAndDomain(u.User.Sid) + username, e := windows.GetUserName(syscall.NameSamCompatible) if e != nil { return e } - usr, e = newUser(uid, gid, dir, username, domain) - return e + displayName, e := windows.GetUserName(syscall.NameDisplay) + if e != nil { + // Historically, the username is used as fallback + // when the display name can't be retrieved. + displayName = username + } + usr = &User{ + Uid: uid, + Gid: gid, + Username: username, + Name: displayName, + HomeDir: dir, + } + return nil }) return usr, err } diff --git a/src/os/user/user_test.go b/src/os/user/user_test.go index fa597b78ec..31486aed03 100644 --- a/src/os/user/user_test.go +++ b/src/os/user/user_test.go @@ -45,8 +45,9 @@ func TestCurrent(t *testing.T) { } func BenchmarkCurrent(b *testing.B) { + // Benchmark current instead of Current because Current caches the result. for i := 0; i < b.N; i++ { - Current() + current() } }