Source file src/internal/syscall/windows/registry/key.go

     1  // Copyright 2015 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 registry provides access to the Windows registry.
     8  //
     9  // Here is a simple example, opening a registry key and reading a string value from it.
    10  //
    11  //	k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
    12  //	if err != nil {
    13  //		log.Fatal(err)
    14  //	}
    15  //	defer k.Close()
    16  //
    17  //	s, _, err := k.GetStringValue("SystemRoot")
    18  //	if err != nil {
    19  //		log.Fatal(err)
    20  //	}
    21  //	fmt.Printf("Windows system root is %q\n", s)
    22  //
    23  // NOTE: This package is a copy of golang.org/x/sys/windows/registry
    24  // with KeyInfo.ModTime removed to prevent dependency cycles.
    25  package registry
    26  
    27  import (
    28  	"runtime"
    29  	"syscall"
    30  )
    31  
    32  const (
    33  	// Registry key security and access rights.
    34  	// See https://learn.microsoft.com/en-us/windows/win32/sysinfo/registry-key-security-and-access-rights
    35  	// for details.
    36  	ALL_ACCESS         = 0xf003f
    37  	CREATE_LINK        = 0x00020
    38  	CREATE_SUB_KEY     = 0x00004
    39  	ENUMERATE_SUB_KEYS = 0x00008
    40  	EXECUTE            = 0x20019
    41  	NOTIFY             = 0x00010
    42  	QUERY_VALUE        = 0x00001
    43  	READ               = 0x20019
    44  	SET_VALUE          = 0x00002
    45  	WOW64_32KEY        = 0x00200
    46  	WOW64_64KEY        = 0x00100
    47  	WRITE              = 0x20006
    48  )
    49  
    50  // Key is a handle to an open Windows registry key.
    51  // Keys can be obtained by calling OpenKey; there are
    52  // also some predefined root keys such as CURRENT_USER.
    53  // Keys can be used directly in the Windows API.
    54  type Key syscall.Handle
    55  
    56  const (
    57  	// Windows defines some predefined root keys that are always open.
    58  	// An application can use these keys as entry points to the registry.
    59  	// Normally these keys are used in OpenKey to open new keys,
    60  	// but they can also be used anywhere a Key is required.
    61  	CLASSES_ROOT   = Key(syscall.HKEY_CLASSES_ROOT)
    62  	CURRENT_USER   = Key(syscall.HKEY_CURRENT_USER)
    63  	LOCAL_MACHINE  = Key(syscall.HKEY_LOCAL_MACHINE)
    64  	USERS          = Key(syscall.HKEY_USERS)
    65  	CURRENT_CONFIG = Key(syscall.HKEY_CURRENT_CONFIG)
    66  )
    67  
    68  // Close closes open key k.
    69  func (k Key) Close() error {
    70  	return syscall.RegCloseKey(syscall.Handle(k))
    71  }
    72  
    73  // OpenKey opens a new key with path name relative to key k.
    74  // It accepts any open key, including CURRENT_USER and others,
    75  // and returns the new key and an error.
    76  // The access parameter specifies desired access rights to the
    77  // key to be opened.
    78  func OpenKey(k Key, path string, access uint32) (Key, error) {
    79  	p, err := syscall.UTF16PtrFromString(path)
    80  	if err != nil {
    81  		return 0, err
    82  	}
    83  	var subkey syscall.Handle
    84  	err = syscall.RegOpenKeyEx(syscall.Handle(k), p, 0, access, &subkey)
    85  	if err != nil {
    86  		return 0, err
    87  	}
    88  	return Key(subkey), nil
    89  }
    90  
    91  // ReadSubKeyNames returns the names of subkeys of key k.
    92  func (k Key) ReadSubKeyNames() ([]string, error) {
    93  	// RegEnumKeyEx must be called repeatedly and to completion.
    94  	// During this time, this goroutine cannot migrate away from
    95  	// its current thread. See #49320.
    96  	runtime.LockOSThread()
    97  	defer runtime.UnlockOSThread()
    98  
    99  	names := make([]string, 0)
   100  	// Registry key size limit is 255 bytes and described there:
   101  	// https://learn.microsoft.com/en-us/windows/win32/sysinfo/registry-element-size-limits
   102  	buf := make([]uint16, 256) //plus extra room for terminating zero byte
   103  loopItems:
   104  	for i := uint32(0); ; i++ {
   105  		l := uint32(len(buf))
   106  		for {
   107  			err := syscall.RegEnumKeyEx(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil)
   108  			if err == nil {
   109  				break
   110  			}
   111  			if err == syscall.ERROR_MORE_DATA {
   112  				// Double buffer size and try again.
   113  				l = uint32(2 * len(buf))
   114  				buf = make([]uint16, l)
   115  				continue
   116  			}
   117  			if err == _ERROR_NO_MORE_ITEMS {
   118  				break loopItems
   119  			}
   120  			return names, err
   121  		}
   122  		names = append(names, syscall.UTF16ToString(buf[:l]))
   123  	}
   124  	return names, nil
   125  }
   126  
   127  // CreateKey creates a key named path under open key k.
   128  // CreateKey returns the new key and a boolean flag that reports
   129  // whether the key already existed.
   130  // The access parameter specifies the access rights for the key
   131  // to be created.
   132  func CreateKey(k Key, path string, access uint32) (newk Key, openedExisting bool, err error) {
   133  	var h syscall.Handle
   134  	var d uint32
   135  	err = regCreateKeyEx(syscall.Handle(k), syscall.StringToUTF16Ptr(path),
   136  		0, nil, _REG_OPTION_NON_VOLATILE, access, nil, &h, &d)
   137  	if err != nil {
   138  		return 0, false, err
   139  	}
   140  	return Key(h), d == _REG_OPENED_EXISTING_KEY, nil
   141  }
   142  
   143  // DeleteKey deletes the subkey path of key k and its values.
   144  func DeleteKey(k Key, path string) error {
   145  	return regDeleteKey(syscall.Handle(k), syscall.StringToUTF16Ptr(path))
   146  }
   147  
   148  // A KeyInfo describes the statistics of a key. It is returned by Stat.
   149  type KeyInfo struct {
   150  	SubKeyCount     uint32
   151  	MaxSubKeyLen    uint32 // size of the key's subkey with the longest name, in Unicode characters, not including the terminating zero byte
   152  	ValueCount      uint32
   153  	MaxValueNameLen uint32 // size of the key's longest value name, in Unicode characters, not including the terminating zero byte
   154  	MaxValueLen     uint32 // longest data component among the key's values, in bytes
   155  	lastWriteTime   syscall.Filetime
   156  }
   157  
   158  // Stat retrieves information about the open key k.
   159  func (k Key) Stat() (*KeyInfo, error) {
   160  	var ki KeyInfo
   161  	err := syscall.RegQueryInfoKey(syscall.Handle(k), nil, nil, nil,
   162  		&ki.SubKeyCount, &ki.MaxSubKeyLen, nil, &ki.ValueCount,
   163  		&ki.MaxValueNameLen, &ki.MaxValueLen, nil, &ki.lastWriteTime)
   164  	if err != nil {
   165  		return nil, err
   166  	}
   167  	return &ki, nil
   168  }
   169  

View as plain text