| 1 |
// Copyright 2020 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
//go:build windows |
| 6 |
|
| 7 |
package execenv |
| 8 |
|
| 9 |
import ( |
| 10 |
"internal/syscall/windows" |
| 11 |
"syscall" |
| 12 |
"unicode/utf16" |
| 13 |
"unsafe" |
| 14 |
) |
| 15 |
|
| 16 |
// Default will return the default environment |
| 17 |
// variables based on the process attributes |
| 18 |
// provided. |
| 19 |
// |
| 20 |
// If the process attributes contain a token, then |
| 21 |
// the environment variables will be sourced from |
| 22 |
// the defaults for that user token, otherwise they |
| 23 |
// will be sourced from syscall.Environ(). |
| 24 |
func Default(sys *syscall.SysProcAttr) (env []string, err error) { |
| 25 |
if sys == nil || sys.Token == 0 { |
| 26 |
return syscall.Environ(), nil |
| 27 |
} |
| 28 |
var block *uint16 |
| 29 |
err = windows.CreateEnvironmentBlock(&block, sys.Token, false) |
| 30 |
if err != nil { |
| 31 |
return nil, err |
| 32 |
} |
| 33 |
defer windows.DestroyEnvironmentBlock(block) |
| 34 |
blockp := uintptr(unsafe.Pointer(block)) |
| 35 |
for { |
| 36 |
|
| 37 |
// find NUL terminator |
| 38 |
end := unsafe.Pointer(blockp) |
| 39 |
for *(*uint16)(end) != 0 { |
| 40 |
end = unsafe.Pointer(uintptr(end) + 2) |
| 41 |
} |
| 42 |
|
| 43 |
n := (uintptr(end) - uintptr(unsafe.Pointer(blockp))) / 2 |
| 44 |
if n == 0 { |
| 45 |
// environment block ends with empty string |
| 46 |
break |
| 47 |
} |
| 48 |
|
| 49 |
entry := (*[(1 << 30) - 1]uint16)(unsafe.Pointer(blockp))[:n:n] |
| 50 |
env = append(env, string(utf16.Decode(entry))) |
| 51 |
blockp += 2 * (uintptr(len(entry)) + 1) |
| 52 |
} |
| 53 |
return |
| 54 |
} |