Skip to content

Commit

Permalink
internal/syscall/execenv: refactor handling env variables
Browse files Browse the repository at this point in the history
Discover while working on CL 471335.

Change-Id: I006077a5aa93cafb7be47813ab0c4714bb00d774
Reviewed-on: https://go-review.googlesource.com/c/go/+/471435
Reviewed-by: Than McIntosh <thanm@google.com>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Run-TryBot: Cuong Manh Le <cuong.manhle.vn@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Bryan Mills <bcmills@google.com>
  • Loading branch information
cuonglm authored and pull[bot] committed Aug 22, 2023
1 parent 5d2f685 commit 8a49745
Showing 1 changed file with 9 additions and 15 deletions.
24 changes: 9 additions & 15 deletions src/internal/syscall/execenv/execenv_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,30 +25,24 @@ func Default(sys *syscall.SysProcAttr) (env []string, err error) {
if sys == nil || sys.Token == 0 {
return syscall.Environ(), nil
}
var block *uint16
err = windows.CreateEnvironmentBlock(&block, sys.Token, false)
var blockp *uint16
err = windows.CreateEnvironmentBlock(&blockp, sys.Token, false)
if err != nil {
return nil, err
}
defer windows.DestroyEnvironmentBlock(block)
blockp := uintptr(unsafe.Pointer(block))
for {
defer windows.DestroyEnvironmentBlock(blockp)

const size = unsafe.Sizeof(*blockp)
for *blockp != 0 { // environment block ends with empty string
// find NUL terminator
end := unsafe.Pointer(blockp)
end := unsafe.Add(unsafe.Pointer(blockp), size)
for *(*uint16)(end) != 0 {
end = unsafe.Pointer(uintptr(end) + 2)
end = unsafe.Add(end, size)
}

n := (uintptr(end) - uintptr(unsafe.Pointer(blockp))) / 2
if n == 0 {
// environment block ends with empty string
break
}

entry := (*[(1 << 30) - 1]uint16)(unsafe.Pointer(blockp))[:n:n]
entry := unsafe.Slice(blockp, (uintptr(end)-uintptr(unsafe.Pointer(blockp)))/2)
env = append(env, string(utf16.Decode(entry)))
blockp += 2 * (uintptr(len(entry)) + 1)
blockp = (*uint16)(unsafe.Add(end, size))
}
return
}

0 comments on commit 8a49745

Please sign in to comment.