1 // Copyright 2010 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.
5 // +build aix darwin dragonfly freebsd linux nacl netbsd openbsd solaris
7 // Unix environment variables.
14 // envOnce guards initialization by copyenv, which populates env.
17 // envLock guards env and envs.
20 // env maps from an environment variable to its first occurrence in envs.
23 // envs is provided by the runtime. elements are expected to
24 // be of the form "key=value". An empty string means deleted
25 // (or a duplicate to be ignored).
26 envs
[]string = runtime_envs()
29 func runtime_envs() []string // in package runtime
31 // setenv_c and unsetenv_c are provided by the runtime but are no-ops
32 // if cgo isn't loaded.
33 func setenv_c(k
, v
string)
34 func unsetenv_c(k
string)
37 env
= make(map[string]int)
38 for i
, s
:= range envs
{
39 for j
:= 0; j
< len(s
); j
++ {
42 if _
, ok
:= env
[key
]; !ok
{
43 env
[key
] = i
// first mention of key
45 // Clear duplicate keys. This permits Unsetenv to
46 // safely delete only the first item without
47 // worrying about unshadowing a later one,
48 // which might be a security problem.
57 func Unsetenv(key
string) error
{
61 defer envLock
.Unlock()
63 if i
, ok
:= env
[key
]; ok
{
71 func Getenv(key
string) (value
string, found
bool) {
78 defer envLock
.RUnlock()
85 for i
:= 0; i
< len(s
); i
++ {
93 func Setenv(key
, value
string) error
{
98 for i
:= 0; i
< len(key
); i
++ {
99 if key
[i
] == '=' || key
[i
] == 0 {
103 for i
:= 0; i
< len(value
); i
++ {
110 defer envLock
.Unlock()
113 kv
:= key
+ "=" + value
118 envs
= append(envs
, kv
)
126 envOnce
.Do(copyenv
) // prevent copyenv in Getenv/Setenv
129 defer envLock
.Unlock()
134 env
= make(map[string]int)
138 func Environ() []string {
141 defer envLock
.RUnlock()
142 a
:= make([]string, 0, len(envs
))
143 for _
, env
:= range envs
{