From 600d372f587735d59c3d132ffe99e211911378bc Mon Sep 17 00:00:00 2001 From: Cuong Manh Le Date: Sat, 25 Feb 2023 16:32:15 +0700 Subject: [release-branch.go1.19] syscall: fix invalid unsafe.Pointer conversion on Windows This cherry-pick CL 471335 without using unsafe.{Add,Slice}. Fixes #58773 Change-Id: Ifa5c059ed5e358ed98aee7e83b95dd1806b535f7 Reviewed-on: https://go-review.googlesource.com/c/go/+/471335 Reviewed-by: Than McIntosh TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor Run-TryBot: Cuong Manh Le Reviewed-by: Bryan Mills Reviewed-on: https://go-review.googlesource.com/c/go/+/471935 Reviewed-by: Dmitri Shuralyov Auto-Submit: Dmitri Shuralyov --- src/syscall/env_windows.go | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/syscall/env_windows.go b/src/syscall/env_windows.go index 74b154ec15..c311706316 100644 --- a/src/syscall/env_windows.go +++ b/src/syscall/env_windows.go @@ -68,21 +68,25 @@ func Clearenv() { } func Environ() []string { - s, e := GetEnvironmentStrings() + envp, e := GetEnvironmentStrings() if e != nil { return nil } - defer FreeEnvironmentStrings(s) + defer FreeEnvironmentStrings(envp) + r := make([]string, 0, 50) // Empty with room to grow. - for from, i, p := 0, 0, (*[1 << 24]uint16)(unsafe.Pointer(s)); true; i++ { - if p[i] == 0 { - // empty string marks the end - if i <= from { - break - } - r = append(r, string(utf16.Decode(p[from:i]))) - from = i + 1 + const size = unsafe.Sizeof(*envp) + for *envp != 0 { // environment block ends with empty string + // find NUL terminator + end := unsafe.Pointer(envp) + for *(*uint16)(end) != 0 { + end = unsafe.Pointer(uintptr(end) + size) } + + n := (uintptr(end) - uintptr(unsafe.Pointer(envp))) / size + entry := (*[(1 << 30) - 1]uint16)(unsafe.Pointer(envp))[:n:n] + r = append(r, string(utf16.Decode(entry))) + envp = (*uint16)(unsafe.Pointer(uintptr(end) + size)) } return r } -- cgit v1.2.1