env_unix.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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.
  4. // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
  5. // Unix environment variables.
  6. package unix
  7. import "sync"
  8. var (
  9. // envOnce guards initialization by copyenv, which populates env.
  10. envOnce sync.Once
  11. // envLock guards env and envs.
  12. envLock sync.RWMutex
  13. // env maps from an environment variable to its first occurrence in envs.
  14. env map[string]int
  15. // envs is provided by the runtime. elements are expected to be
  16. // of the form "key=value".
  17. envs []string
  18. )
  19. // setenv_c is provided by the runtime, but is a no-op if cgo isn't
  20. // loaded.
  21. func setenv_c(k, v string)
  22. func copyenv() {
  23. env = make(map[string]int)
  24. for i, s := range envs {
  25. for j := 0; j < len(s); j++ {
  26. if s[j] == '=' {
  27. key := s[:j]
  28. if _, ok := env[key]; !ok {
  29. env[key] = i
  30. }
  31. break
  32. }
  33. }
  34. }
  35. }
  36. func Getenv(key string) (value string, found bool) {
  37. envOnce.Do(copyenv)
  38. if len(key) == 0 {
  39. return "", false
  40. }
  41. envLock.RLock()
  42. defer envLock.RUnlock()
  43. i, ok := env[key]
  44. if !ok {
  45. return "", false
  46. }
  47. s := envs[i]
  48. for i := 0; i < len(s); i++ {
  49. if s[i] == '=' {
  50. return s[i+1:], true
  51. }
  52. }
  53. return "", false
  54. }
  55. func Setenv(key, value string) error {
  56. envOnce.Do(copyenv)
  57. if len(key) == 0 {
  58. return EINVAL
  59. }
  60. for i := 0; i < len(key); i++ {
  61. if key[i] == '=' || key[i] == 0 {
  62. return EINVAL
  63. }
  64. }
  65. for i := 0; i < len(value); i++ {
  66. if value[i] == 0 {
  67. return EINVAL
  68. }
  69. }
  70. envLock.Lock()
  71. defer envLock.Unlock()
  72. i, ok := env[key]
  73. kv := key + "=" + value
  74. if ok {
  75. envs[i] = kv
  76. } else {
  77. i = len(envs)
  78. envs = append(envs, kv)
  79. }
  80. env[key] = i
  81. setenv_c(key, value)
  82. return nil
  83. }
  84. func Clearenv() {
  85. envOnce.Do(copyenv) // prevent copyenv in Getenv/Setenv
  86. envLock.Lock()
  87. defer envLock.Unlock()
  88. env = make(map[string]int)
  89. envs = []string{}
  90. // TODO(bradfitz): pass through to C
  91. }
  92. func Environ() []string {
  93. envOnce.Do(copyenv)
  94. envLock.RLock()
  95. defer envLock.RUnlock()
  96. a := make([]string, len(envs))
  97. copy(a, envs)
  98. return a
  99. }