//go:build windows package paths import ( "syscall" "unsafe" ) // This file supplies the optional, best-effort Windows known-folder // lookup mentioned in windows.go: it is only ever consulted when an // environment variable (APPDATA/LOCALAPPDATA/PROGRAMDATA) is not set and // this process is actually running on Windows (not merely simulating it // via WithPlatform, which never sets nativeKnownFolder's caller // condition to true on a non-Windows GOOS build in the first place). // // It calls SHGetKnownFolderPath directly via syscall rather than adding // a dependency (e.g. golang.org/x/sys/windows), per AGENTS.md's "as few // external dependencies as possible" guidance -- this is the one place // in the module that needs it. var ( knownFolderRoaming = syscall.GUID{Data1: 0x3EB685DB, Data2: 0x65F9, Data3: 0x4CF6, Data4: [8]byte{0xA0, 0x3A, 0xE3, 0xEF, 0x65, 0x72, 0x9F, 0x3D}} knownFolderLocal = syscall.GUID{Data1: 0xF1B32785, Data2: 0x6FBA, Data3: 0x4FCF, Data4: [8]byte{0x9D, 0x55, 0x7B, 0x8E, 0x7F, 0x15, 0x70, 0x91}} knownFolderProgData = syscall.GUID{Data1: 0x62AB5D82, Data2: 0xFDC1, Data3: 0x4DC3, Data4: [8]byte{0xA9, 0xDD, 0x07, 0x0D, 0x1D, 0x49, 0x5D, 0x97}} ) func init() { nativeKnownFolder = lookupKnownFolder } func lookupKnownFolder(envVar string) (string, bool) { var guid *syscall.GUID switch envVar { case "APPDATA": guid = &knownFolderRoaming case "LOCALAPPDATA": guid = &knownFolderLocal case "PROGRAMDATA": guid = &knownFolderProgData default: return "", false } shell32 := syscall.NewLazyDLL("shell32.dll") proc := shell32.NewProc("SHGetKnownFolderPath") if proc.Find() != nil { return "", false } ole32 := syscall.NewLazyDLL("ole32.dll") coTaskMemFree := ole32.NewProc("CoTaskMemFree") var pathPtr uintptr ret, _, _ := proc.Call( uintptr(unsafe.Pointer(guid)), 0, // dwFlags 0, // hToken (current user) uintptr(unsafe.Pointer(&pathPtr)), ) if ret != 0 || pathPtr == 0 { return "", false } defer coTaskMemFree.Call(pathPtr) // Manually walk the UTF-16, NUL-terminated string CoTaskMemFree owns. // `go vet` flags this uintptr->Pointer conversion (unsafeptr): pathPtr // is a raw address handed back by the syscall, not derived from a Go // pointer, so vet cannot prove it safe -- this is the same accepted, // unavoidable pattern the standard syscall package itself uses for // manual Windows API interop without golang.org/x/sys/windows. base := unsafe.Pointer(pathPtr) //nolint:unsafeptr var chars []uint16 for i := 0; ; i++ { c := *(*uint16)(unsafe.Add(base, i*2)) if c == 0 { break } chars = append(chars, c) } return syscall.UTF16ToString(chars), true }