Source file src/syscall/env_windows.go

     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  
     5  // Windows environment variables.
     6  
     7  package syscall
     8  
     9  import (
    10  	"unicode/utf16"
    11  	"unsafe"
    12  )
    13  
    14  func Getenv(key string) (value string, found bool) {
    15  	keyp, err := UTF16PtrFromString(key)
    16  	if err != nil {
    17  		return "", false
    18  	}
    19  	n := uint32(100)
    20  	for {
    21  		b := make([]uint16, n)
    22  		n, err = GetEnvironmentVariable(keyp, &b[0], uint32(len(b)))
    23  		if n == 0 && err == ERROR_ENVVAR_NOT_FOUND {
    24  			return "", false
    25  		}
    26  		if n <= uint32(len(b)) {
    27  			return string(utf16.Decode(b[:n])), true
    28  		}
    29  	}
    30  }
    31  
    32  func Setenv(key, value string) error {
    33  	v, err := UTF16PtrFromString(value)
    34  	if err != nil {
    35  		return err
    36  	}
    37  	keyp, err := UTF16PtrFromString(key)
    38  	if err != nil {
    39  		return err
    40  	}
    41  	e := SetEnvironmentVariable(keyp, v)
    42  	if e != nil {
    43  		return e
    44  	}
    45  	runtimeSetenv(key, value)
    46  	return nil
    47  }
    48  
    49  func Unsetenv(key string) error {
    50  	keyp, err := UTF16PtrFromString(key)
    51  	if err != nil {
    52  		return err
    53  	}
    54  	e := SetEnvironmentVariable(keyp, nil)
    55  	if e != nil {
    56  		return e
    57  	}
    58  	runtimeUnsetenv(key)
    59  	return nil
    60  }
    61  
    62  func Clearenv() {
    63  	for _, s := range Environ() {
    64  		// Environment variables can begin with =
    65  		// so start looking for the separator = at j=1.
    66  		// https://blogs.msdn.com/b/oldnewthing/archive/2010/05/06/10008132.aspx
    67  		for j := 1; j < len(s); j++ {
    68  			if s[j] == '=' {
    69  				Unsetenv(s[0:j])
    70  				break
    71  			}
    72  		}
    73  	}
    74  }
    75  
    76  func Environ() []string {
    77  	envp, e := GetEnvironmentStrings()
    78  	if e != nil {
    79  		return nil
    80  	}
    81  	defer FreeEnvironmentStrings(envp)
    82  
    83  	r := make([]string, 0, 50) // Empty with room to grow.
    84  	const size = unsafe.Sizeof(*envp)
    85  	for *envp != 0 { // environment block ends with empty string
    86  		// find NUL terminator
    87  		end := unsafe.Pointer(envp)
    88  		for *(*uint16)(end) != 0 {
    89  			end = unsafe.Add(end, size)
    90  		}
    91  
    92  		entry := unsafe.Slice(envp, (uintptr(end)-uintptr(unsafe.Pointer(envp)))/size)
    93  		r = append(r, string(utf16.Decode(entry)))
    94  		envp = (*uint16)(unsafe.Add(end, size))
    95  	}
    96  	return r
    97  }
    98  

View as plain text