or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cpu.mdexecabs.mdindex.mdplan9.mdunix.mdwindows.md
tile.json

windows.mddocs/

golang.org/x/sys/windows

Package windows contains an interface to the low-level operating system primitives for Windows.

Package Information

  • Import Path: golang.org/x/sys/windows
  • Version: v0.38.0
  • Purpose: Low-level Windows system calls and OS primitives

Overview

Package windows provides a direct interface to the low-level Windows operating system primitives. It wraps the Windows API and provides Go-friendly access to system calls, handles, security descriptors, and other Windows-specific functionality.

The primary use of this package is inside other packages that provide a more portable interface to the system, such as os, time, and net. Use those packages rather than this one if you can.

These calls return err == nil to indicate success; otherwise err represents an operating system error describing the failure and holds a value of type syscall.Errno.

Core Imports

import "golang.org/x/sys/windows"

Constants

The windows package exports thousands of Windows-specific constants. Major categories are documented below.

###EVENT LOG Constants

const (
    EVENTLOG_SUCCESS          = 0
    EVENTLOG_ERROR_TYPE       = 1
    EVENTLOG_WARNING_TYPE     = 2
    EVENTLOG_INFORMATION_TYPE = 4
    EVENTLOG_AUDIT_SUCCESS    = 8
    EVENTLOG_AUDIT_FAILURE    = 16
)

Memory Management Constants

const (
    MEM_COMMIT      = 0x00001000
    MEM_RESERVE     = 0x00002000
    MEM_DECOMMIT    = 0x00004000
    MEM_RELEASE     = 0x00008000
    MEM_RESET       = 0x00080000
    MEM_TOP_DOWN    = 0x00100000
    MEM_WRITE_WATCH = 0x00200000
    MEM_PHYSICAL    = 0x00400000
    MEM_RESET_UNDO  = 0x01000000
    MEM_LARGE_PAGES = 0x20000000
)

Page Protection Constants

const (
    PAGE_NOACCESS          = 0x00000001
    PAGE_READONLY          = 0x00000002
    PAGE_READWRITE         = 0x00000004
    PAGE_WRITECOPY         = 0x00000008
    PAGE_EXECUTE           = 0x00000010
    PAGE_EXECUTE_READ      = 0x00000020
    PAGE_EXECUTE_READWRITE = 0x00000040
    PAGE_EXECUTE_WRITECOPY = 0x00000080
    PAGE_GUARD             = 0x00000100
    PAGE_NOCACHE           = 0x00000200
    PAGE_WRITECOMBINE      = 0x00000400
)

SID Types

const (
    SidTypeUser = 1 + iota
    SidTypeGroup
    SidTypeDomain
    SidTypeAlias
    SidTypeWellKnownGroup
    SidTypeDeletedAccount
    SidTypeInvalid
    SidTypeUnknown
    SidTypeComputer
    SidTypeLabel
)

Security RIDs

const (
    SECURITY_NULL_RID                   = 0
    SECURITY_WORLD_RID                  = 0
    SECURITY_LOCAL_RID                  = 0
    SECURITY_CREATOR_OWNER_RID          = 0
    SECURITY_CREATOR_GROUP_RID          = 1
    SECURITY_DIALUP_RID                 = 1
    SECURITY_NETWORK_RID                = 2
    SECURITY_BATCH_RID                  = 3
    SECURITY_INTERACTIVE_RID            = 4
    SECURITY_LOGON_IDS_RID              = 5
    SECURITY_SERVICE_RID                = 6
    SECURITY_LOCAL_SYSTEM_RID           = 18
    SECURITY_BUILTIN_DOMAIN_RID         = 32
    SECURITY_PRINCIPAL_SELF_RID         = 10
    SECURITY_AUTHENTICATED_USER_RID     = 0xb
    SECURITY_RESTRICTED_CODE_RID        = 0xc
)

Token Access Rights

const (
    TOKEN_ASSIGN_PRIMARY = 1 << iota
    TOKEN_DUPLICATE
    TOKEN_IMPERSONATE
    TOKEN_QUERY
    TOKEN_QUERY_SOURCE
    TOKEN_ADJUST_PRIVILEGES
    TOKEN_ADJUST_GROUPS
    TOKEN_ADJUST_DEFAULT
    TOKEN_ADJUST_SESSIONID

    TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED |
        TOKEN_ASSIGN_PRIMARY |
        TOKEN_DUPLICATE |
        TOKEN_IMPERSONATE |
        TOKEN_QUERY |
        TOKEN_QUERY_SOURCE |
        TOKEN_ADJUST_PRIVILEGES |
        TOKEN_ADJUST_GROUPS |
        TOKEN_ADJUST_DEFAULT |
        TOKEN_ADJUST_SESSIONID
    TOKEN_READ  = STANDARD_RIGHTS_READ | TOKEN_QUERY
    TOKEN_WRITE = STANDARD_RIGHTS_WRITE |
        TOKEN_ADJUST_PRIVILEGES |
        TOKEN_ADJUST_GROUPS |
        TOKEN_ADJUST_DEFAULT
    TOKEN_EXECUTE = STANDARD_RIGHTS_EXECUTE
)

The package contains thousands of additional constants for file operations, process management, security, networking, registry operations, services, and much more. Refer to the Windows API documentation for specific constant values.

Functions

The windows package provides 701 functions for low-level Windows operations. Major categories are documented below with key functions.

File Operations

func CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error)
func DeleteFile(path *uint16) (err error)
func ReadFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error)
func WriteFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error)
func SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error)
func FlushFileBuffers(handle Handle) (err error)
func GetFileType(filehandle Handle) (n uint32, err error)
func SetEndOfFile(handle Handle) (err error)
func GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error)
func GetFinalPathNameByHandle(file Handle, filePath *uint16, filePathSize uint32, flags uint32) (n uint32, err error)
func FindFirstFile(name *uint16, data *Win32finddata) (handle Handle, err error)
func FindNextFile(handle Handle, data *Win32finddata) (err error)
func FindClose(handle Handle) (err error)
func GetFileAttributes(name *uint16) (attrs uint32, err error)
func SetFileAttributes(name *uint16, attrs uint32) (err error)
func GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error)
func MoveFile(from *uint16, to *uint16) (err error)
func MoveFileEx(from *uint16, to *uint16, flags uint32) (err error)
func LockFileEx(file Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)
func UnlockFileEx(file Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)

Directory Operations

func CreateDirectory(path *uint16, sa *SecurityAttributes) (err error)
func RemoveDirectory(path *uint16) (err error)
func GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error)
func SetCurrentDirectory(path *uint16) (err error)
func GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error)
func GetTempPath(buflen uint32, buf *uint16) (n uint32, err error)

Handle Management

func CloseHandle(handle Handle) (err error)
func DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error)
func GetHandleInformation(handle Handle, flags *uint32) (err error)
func SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error)

Process Management

func CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error)
func CreateProcessAsUser(token Token, appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error)
func OpenProcess(desiredAccess uint32, inheritHandle bool, processId uint32) (handle Handle, err error)
func TerminateProcess(handle Handle, exitcode uint32) (err error)
func GetExitCodeProcess(handle Handle, exitcode *uint32) (err error)
func GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error)
func GetProcessId(process Handle) (id uint32, err error)
func GetCurrentProcess() (pseudoHandle Handle)
func GetCurrentProcessId() (pid uint32)
func WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error)
func WaitForMultipleObjects(handles []Handle, waitAll bool, waitMilliseconds uint32) (event uint32, err error)
func ExitProcess(exitcode uint32)
func ResumeThread(thread Handle) (ret uint32, err error)
func SuspendThread(thread Handle) (ret uint32, err error)
func GetCurrentThread() (pseudoHandle Handle)
func GetCurrentThreadId() (id uint32)
func SetThreadPriority(thread Handle, priority int32) (err error)
func SetProcessPriorityBoost(process Handle, disable bool) (err error)
func Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error)
func Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error)
func Thread32First(snapshot Handle, threadEntry *ThreadEntry32) (err error)
func Thread32Next(snapshot Handle, threadEntry *ThreadEntry32) (err error)

Job Objects

func CreateJobObject(jobAttr *SecurityAttributes, name *uint16) (handle Handle, err error)
func AssignProcessToJobObject(job Handle, process Handle) (err error)
func QueryInformationJobObject(job Handle, infoclass uint32, info uintptr, infolength uint32, retlen *uint32) (err error)
func SetInformationJobObject(job Handle, infoclass uint32, info uintptr, infolength uint32) (err error)
func TerminateJobObject(job Handle, exitCode uint32) (err error)

Thread Management

func CreateThread(threadAttributes *SecurityAttributes, stackSize uint32, startAddress uintptr, parameter uintptr, creationFlags uint32, threadId *uint32) (handle Handle, err error)
func OpenThread(desiredAccess uint32, inheritHandle bool, threadId uint32) (handle Handle, err error)
func GetThreadContext(thread Handle, context *Context) (err error)
func SetThreadContext(thread Handle, context *Context) (err error)

Memory Management

func VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error)
func VirtualFree(address uintptr, size uintptr, freetype uint32) (err error)
func VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error)
func VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error)
func VirtualAllocEx(process Handle, address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error)
func VirtualFreeEx(process Handle, address uintptr, size uintptr, freetype uint32) (err error)
func VirtualProtectEx(process Handle, address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error)
func VirtualQueryEx(process Handle, address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error)
func ReadProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesRead *uintptr) (err error)
func WriteProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesWritten *uintptr) (err error)
func FlushInstructionCache(process Handle, addr uintptr, size uintptr) (err error)

File Mapping

func CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error)
func OpenFileMapping(access uint32, inheritHandle bool, name *uint16) (handle Handle, err error)
func MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error)
func UnmapViewOfFile(addr uintptr) (err error)
func FlushViewOfFile(addr uintptr, length uintptr) (err error)

Synchronization

func CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error)
func CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error)
func OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error)
func SetEvent(event Handle) (err error)
func ResetEvent(event Handle) (err error)
func PulseEvent(event Handle) (err error)
func CreateMutex(mutexAttrs *SecurityAttributes, initialOwner bool, name *uint16) (handle Handle, err error)
func CreateMutexEx(mutexAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error)
func OpenMutex(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error)
func ReleaseMutex(mutex Handle) (err error)
func CreateSemaphore(semaphoreAttributes *SecurityAttributes, initialCount int32, maximumCount int32, name *uint16) (handle Handle, err error)
func OpenSemaphore(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error)
func ReleaseSemaphore(semaphore Handle, releaseCount int32, previousCount *int32) (err error)

Named Pipes

func CreateNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *SecurityAttributes) (handle Handle, err error)
func ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error)
func DisconnectNamedPipe(pipe Handle) (err error)
func CallNamedPipe(pipeName *uint16, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesRead *uint32, timeout uint32) (err error)
func WaitNamedPipe(pipeName *uint16, timeout uint32) (err error)
func TransactNamedPipe(pipe Handle, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesRead *uint32, overlapped *Overlapped) (err error)
func PeekNamedPipe(pipe Handle, buf *byte, bufSize uint32, bytesRead *uint32, totalBytesAvail *uint32, bytesLeftThisMessage *uint32) (err error)
func GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error)

Anonymous Pipes

func CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error)

I/O Completion Ports

func CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uintptr, threadcnt uint32) (handle Handle, err error)
func GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uintptr, overlapped **Overlapped, timeout uint32) (err error)
func PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uintptr, overlapped *Overlapped) (err error)

Overlapped I/O

func GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error)
func CancelIo(s Handle) (err error)
func CancelIoEx(s Handle, o *Overlapped) (err error)

Security and Access Control

func OpenProcessToken(process Handle, access uint32, token *Token) (err error)
func OpenThreadToken(thread Handle, access uint32, openAsSelf bool, token *Token) (err error)
func GetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error)
func SetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32) (err error)
func AdjustTokenPrivileges(token Token, disableAllPrivileges bool, newstate *Tokenprivileges, buflen uint32, prevstate *Tokenprivileges, returnlen *uint32) (err error)
func AdjustTokenGroups(token Token, resetToDefault bool, newstate *Tokengroups, buflen uint32, prevstate *Tokengroups, returnlen *uint32) (err error)
func DuplicateToken(existingToken Token, impersonationLevel uint32, duplicateToken *Token) (err error)
func DuplicateTokenEx(existingToken Token, desiredAccess uint32, tokenAttributes *SecurityAttributes, impersonationLevel uint32, tokenType uint32, newToken *Token) (err error)
func SetThreadToken(thread *Handle, token Token) (err error)
func ImpersonateSelf(impersonationlevel uint32) (err error)
func RevertToSelf() (err error)
func LookupPrivilegeValue(systemname *uint16, name *uint16, luid *LUID) (err error)
func LookupPrivilegeName(systemname *uint16, luid *LUID, buf *uint16, size *uint32) (err error)
func LookupPrivilegeDisplay Name(systemname *uint16, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error)

SID Management

func AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error)
func FreeSid(sid *SID) (err error)
func CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error)
func GetLengthSid(sid *SID) (len uint32)
func GetSidIdentifierAuthority(sid *SID) (authority *SidIdentifierAuthority)
func GetSidSubAuthority(sid *SID, index uint32) (subAuthority *uint32)
func GetSidSubAuthorityCount(sid *SID) (count *uint8)
func IsValidSid(sid *SID) (isValid bool)
func EqualSid(sid1 *SID, sid2 *SID) (isEqual bool)
func ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error)
func ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error)
func CreateWellKnownSid(sidType WELL_KNOWN_SID_TYPE) (*SID, error)
func CreateWellKnownDomainSid(sidType WELL_KNOWN_SID_TYPE, domainSid *SID) (*SID, error)
func LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error)
func LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error)

ACL Management

func InitializeAcl(acl *ACL, aclLength uint32, aclRevision uint32) (err error)
func AddAccessAllowedAce(acl *ACL, aclRevision uint32, accessMask uint32, sid *SID) (err error)
func AddAccessAllowedAceEx(acl *ACL, aclRevision uint32, aceFlags uint32, accessMask uint32, sid *SID) (err error)
func AddAccessDeniedAce(acl *ACL, aclRevision uint32, accessMask uint32, sid *SID) (err error)
func AddAccessDeniedAceEx(acl *ACL, aclRevision uint32, aceFlags uint32, accessMask uint32, sid *SID) (err error)
func GetAce(acl *ACL, aceIndex uint32, pAce **byte) (err error)
func DeleteAce(acl *ACL, aceIndex uint32) (err error)
func GetAclInformation(acl *ACL, information *byte, informationLength uint32, informationClass uint32) (err error)
func ACLFromEntries(explicitEntries []EXPLICIT_ACCESS, mergedACL *ACL) (acl *ACL, err error)

Security Descriptors

func InitializeSecurityDescriptor(sd *SECURITY_DESCRIPTOR, revision uint32) (err error)
func GetSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner **SID, ownerDefaulted *bool) (err error)
func SetSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner *SID, ownerDefaulted bool) (err error)
func GetSecurityDescriptorGroup(sd *SECURITY_DESCRIPTOR, group **SID, groupDefaulted *bool) (err error)
func SetSecurityDescriptorGroup(sd *SECURITY_DESCRIPTOR, group *SID, groupDefaulted bool) (err error)
func GetSecurityDescriptorDacl(sd *SECURITY_DESCRIPTOR, daclPresent *bool, dacl **ACL, daclDefaulted *bool) (err error)
func SetSecurityDescriptorDacl(sd *SECURITY_DESCRIPTOR, daclPresent bool, dacl *ACL, daclDefaulted bool) (err error)
func GetSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent *bool, sacl **ACL, saclDefaulted *bool) (err error)
func SetSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent bool, sacl *ACL, saclDefaulted bool) (err error)
func BuildSecurityDescriptor(owner *TRUSTEE, group *TRUSTEE, accessEntries []EXPLICIT_ACCESS, auditEntries []EXPLICIT_ACCESS, mergedSecurityDescriptor *SECURITY_DESCRIPTOR) (sd *SECURITY_DESCRIPTOR, err error)
func GetNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, secInfo SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (err error)
func SetNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, secInfo SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) (err error)
func GetSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, secInfo SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (err error)
func SetSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, secInfo SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) (err error)

Registry Operations

func RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error)
func RegCloseKey(key Handle) (regerrno error)
func RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error)
func RegSetValueEx(key Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, buflen uint32) (regerrno error)
func RegCreateKeyEx(key Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desiredAccess uint32, sa *SecurityAttributes, result *Handle, disposition *uint32) (regerrno error)
func RegDeleteKey(key Handle, subkey *uint16) (regerrno error)
func RegDeleteValue(key Handle, name *uint16) (regerrno error)
func RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error)
func RegEnumValue(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error)
func RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error)

Service Control Manager

func OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle Handle, err error)
func CloseServiceHandle(handle Handle) (err error)
func CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access uint32, srvType uint32, startType uint32, errCtl uint32, pathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16) (handle Handle, err error)
func OpenService(mgr Handle, serviceName *uint16, access uint32) (handle Handle, err error)
func DeleteService(service Handle) (err error)
func StartService(service Handle, numArgs uint32, argVectors **uint16) (err error)
func ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err error)
func QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error)
func QueryServiceStatusEx(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error)
func QueryServiceConfig(service Handle, serviceConfig *QUERY_SERVICE_CONFIG, bufSize uint32, bytesNeeded *uint32) (err error)
func ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, errorControl uint32, binaryPathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16, displayName *uint16) (err error)
func ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error)
func EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serviceState uint32, services *byte, bufSize uint32, bytesNeeded *uint32, servicesReturned *uint32, resumeHandle *uint32, groupName *uint16) (err error)
func NotifyServiceStatusChange(service Handle, notifyMask uint32, notifier *SERVICE_NOTIFY) (ret error)
func QueryServiceDynamicInformation(service Handle, infoLevel uint32, dynamicInfo unsafe.Pointer) (err error)

Event Logging

func RegisterEventSource(uncServerName *uint16, sourceName *uint16) (handle Handle, err error)
func DeregisterEventSource(handle Handle) (err error)
func ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrSId uintptr, numStrings uint16, dataSize uint32, strings **uint16, rawData *byte) (err error)
func OpenEventLog(uncServerName *uint16, sourceName *uint16) (handle Handle, err error)
func ReadEventLog(eventlog Handle, readFlags uint32, recordOffset uint32, buffer *byte, numberOfBytesToRead uint32, bytesRead *uint32, minNumberOfBytesNeeded *uint32) (err error)
func ClearEventLog(eventlog Handle, backupFileName *uint16) (err error)

System Information

func GetVersion() (ver uint32, err error)
func GetSystemInfo(sysinfo *SystemInfo)
func GetNativeSystemInfo(sysinfo *SystemInfo)
func GetSystemDirectory(dir *uint16, dirLen uint32) (len uint32, err error)
func GetWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error)
func GetSystemWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error)
func GetComputerName(buf *uint16, n *uint32) (err error)
func GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error)
func SetComputerName(name *uint16) (err error)
func ComputerName() (name string, err error)
func GetTickCount() (ms uint32)
func GetTickCount64() (ms uint64)
func GetSystemTimeAsFileTime(time *Filetime)
func GetSystemTime(time *Systemtime)
func SetSystemTime(time *Systemtime) (err error)
func GetLocalTime(time *Systemtime)
func SetLocalTime(time *Systemtime) (err error)
func SystemTimeToFileTime(st *Systemtime, ft *Filetime) (err error)
func FileTimeToSystemTime(ft *Filetime, st *Systemtime) (err error)
func FileTimeToLocalFileTime(ft *Filetime, lft *Filetime) (err error)
func LocalFileTimeToFileTime(lft *Filetime, ft *Filetime) (err error)

Time Zone

func GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error)
func SetTimeZoneInformation(tzi *Timezoneinformation) (err error)
func GetDynamicTimeZoneInformation(dtzi *DynamicTimezoneinformation) (rc uint32, err error)
func SetDynamicTimeZoneInformation(dtzi *DynamicTimezoneinformation) (err error)

Environment Variables

func GetEnvironmentStrings() (envs *uint16, err error)
func FreeEnvironmentStrings(envs *uint16) (err error)
func GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error)
func SetEnvironmentVariable(name *uint16, value *uint16) (err error)
func ExpandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error)
func CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) (err error)
func DestroyEnvironmentBlock(block *uint16) (err error)

DLL Management

func LoadLibrary(libname string) (handle Handle, err error)
func LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error)
func FreeLibrary(handle Handle) (err error)
func GetProcAddress(module Handle, procname string) (proc uintptr, err error)
func GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, err error)
func GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error)
func AddDllDirectory(path *uint16) (cookie uintptr, err error)
func RemoveDllDirectory(cookie uintptr) (err error)
func SetDllDirectory(path string) (err error)
func SetDefaultDllDirectories(directoryFlags uint32) (err error)

Console Operations

func AllocConsole() (err error)
func FreeConsole() (err error)
func GetConsoleMode(console Handle, mode *uint32) (err error)
func SetConsoleMode(console Handle, mode uint32) (err error)
func GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error)
func SetConsoleCursorPosition(console Handle, position Coord) (err error)
func SetConsoleTitle(title *uint16) (err error)
func GetConsoleTitle(title *uint16, size uint32) (n uint32, err error)
func ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error)
func WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error)
func CreatePseudoConsole(size Coord, in Handle, out Handle, flags uint32, pconsole *Handle) error
func ResizePseudoConsole(pconsole Handle, size Coord) error
func ClosePseudoConsole(console Handle)

COM Operations

func CoInitializeEx(reserved uintptr, coInit uint32) (ret error)
func CoUninitialize()
func CoTaskMemFree(address unsafe.Pointer)
func CoGetObject(name *uint16, bindOpts *BIND_OPTS3, guid *GUID, functionTable **uintptr) (ret error)
func StringFromGUID2(rguid *GUID, lpsz *uint16, cchMax int32) (chars int32)
func CLSIDFromString(lpsz *uint16, pclsid *GUID) (ret error)

Networking (WinSock)

func WSAStartup(verreq uint16, data *WSAData) (sockerr error)
func WSACleanup() (err error)
func WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error)
func Socket(af int32, typ int32, protocol int32) (handle Handle, err error)
func Bind(fd Handle, sa Sockaddr) (err error)
func Connect(fd Handle, sa Sockaddr) (err error)
func Listen(s Handle, backlog int32) (err error)
func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error)
func AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error)
func ConnectEx(fd Handle, sa Sockaddr, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) error
func GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32)
func Getsockname(fd Handle, rsa *RawSockaddrAny, addrlen *int32) (err error)
func Getpeername(fd Handle, rsa *RawSockaddrAny, addrlen *int32) (err error)
func Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error)
func Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error)
func Shutdown(s Handle, how int32) (err error)
func Closesocket(s Handle) (err error)
func Send(s Handle, buf []byte, flags int32) (err error)
func SendTo(s Handle, buf []byte, flags int32, to Sockaddr) (err error)
func Recvfrom(fd Handle, buf []byte, flags int32) (n int, from Sockaddr, err error)
func Sendmsg(fd Handle, p, oob []byte, to Sockaddr, flags int) (err error)
func WSASocket(af int32, typ int32, protocol int32, protoInfo *WSAProtocolInfo, group uint32, flags uint32) (handle Handle, err error)
func WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error)
func WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error)
func WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error)
func WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32, overlapped *Overlapped, croutine *byte) (err error)

Certificate Management

func CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error)
func CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error)
func CertCloseStore(store Handle, flags uint32) (err error)
func CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error)
func CertFindCertificateInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevCertContext *CertContext) (cert *CertContext, err error)
func CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error)
func CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error)
func CertFreeCertificateChain(ctx *CertChainContext)
func CertFreeCertificateContext(ctx *CertContext) (err error)
func CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error)
func CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error)
func CertDeleteCertificateFromStore(certContext *CertContext) (err error)
func CertGetNameString(certContext *CertContext, nameType uint32, flags uint32, typePara unsafe.Pointer, name *uint16, size uint32) (chars uint32)

Cryptography

func CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error)
func CryptReleaseContext(provhandle Handle, flags uint32) (err error)
func CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error)
func CryptProtectData(dataIn *DataBlob, name *uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error)
func CryptUnprotectData(dataIn *DataBlob, name **uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error)
func CryptDecodeObject(encodingType uint32, structType *byte, encodedBytes *byte, lenEncodedBytes uint32, flags uint32, decoded unsafe.Pointer, decodedLen *uint32) (err error)
func CryptQueryObject(objectType uint32, object unsafe.Pointer, expectedContentTypeFlags uint32, expectedFormatTypeFlags uint32, flags uint32, msgAndCertEncodingType *uint32, contentType *uint32, formatType *uint32, certStore *Handle, msg *Handle, context *unsafe.Pointer) (err error)

Serial Port Communications

func SetCommState(handle Handle, dcb *DCB) (err error)
func GetCommState(handle Handle, dcb *DCB) (err error)
func SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error)
func GetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error)
func SetCommMask(handle Handle, evtMask uint32) (err error)
func GetCommMask(handle Handle, evtMask *uint32) (err error)
func WaitCommEvent(handle Handle, evtMask *uint32, overlapped *Overlapped) (err error)
func SetCommBreak(handle Handle) (err error)
func ClearCommBreak(handle Handle) (err error)
func ClearCommError(handle Handle, lpErrors *uint32, lpStat *ComStat) (err error)
func SetupComm(handle Handle, dwInQueue uint32, dwOutQueue uint32) (err error)
func PurgeComm(handle Handle, flags uint32) (err error)
func FlushFileBuffers(handle Handle) (err error)
func EscapeCommFunction(handle Handle, function uint32) (err error)
func GetCommModemStatus(handle Handle, modeStat *uint32) (err error)

Device Management

func DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error)
func CM_Get_DevNode_Status(status *uint32, problemNumber *uint32, devInst DEVINST, flags uint32) error
func CM_Get_Device_Interface_List(deviceID string, interfaceClass *GUID, flags uint32) ([]string, error)

Network Management

func NetUserAdd(serverName *uint16, level uint32, buf *byte, parmErr *uint32) (neterr error)
func NetUserDel(serverName *uint16, userName *uint16) (neterr error)
func NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error)
func NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error)
func NetApiBufferFree(buf *byte) (neterr error)

IP Helper

func GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error)
func GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error)
func GetIfEntry(pIfRow *MibIfRow) (errcode error)
func GetIfTable(pIfTable *MibIfTable, pdwSize *uint32, bOrder bool) (errcode error)
func GetIpAddrTable(pIpAddrTable *MibIpAddrTable, pdwSize *uint32, bOrder bool) (errcode error)
func NotifyIpInterfaceChange(family uint16, callback uintptr, callerContext uintptr, initialNotification bool, notificationHandle *Handle) (ret error)
func CancelMibChangeNotify2(notificationHandle Handle) (errcode error)

Volume Management

func GetVolumeInformation(rootPathName *uint16, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error)
func GetVolumePathName(fileName *uint16, volumePathName *uint16, bufferLength uint32) (err error)
func GetLogicalDrives() (drivesBitMask uint32, err error)
func GetLogicalDriveStrings(bufferLength uint32, buffer *uint16) (n uint32, err error)
func GetDriveType(rootPathName *uint16) (driveType uint32)
func GetDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailableToCaller *uint64, totalNumberOfBytes *uint64, totalNumberOfFreeBytes *uint64) (err error)
func SetVolumeLabel(rootPathName *uint16, volumeName *uint16) (err error)
func SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err error)
func DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error)
func FindFirstVolume(volumeName *uint16, bufferLength uint32) (handle Handle, err error)
func FindNextVolume(findVolume Handle, volumeName *uint16, bufferLength uint32) (err error)
func FindVolumeClose(findVolume Handle) (err error)
func FindFirstVolumeMountPoint(rootPathName *uint16, volumeMountPoint *uint16, bufferLength uint32) (handle Handle, err error)
func FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uint16, bufferLength uint32) (err error)
func FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error)

Link Operations

func CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error)
func CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error)
func DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err error)
func QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint32, err error)

Snapshot/Debugging

func CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error)
func Module32First(snapshot Handle, moduleEntry *ModuleEntry32) (err error)
func Module32Next(snapshot Handle, moduleEntry *ModuleEntry32) (err error)

String Conversion Utilities

func UTF16FromString(s string) ([]uint16, error)
func UTF16ToString(s []uint16) string
func UTF16PtrFromString(s string) (*uint16, error)
func UTF16PtrToString(p *uint16) string
func StringToUTF16(s string) []uint16
func StringToUTF16Ptr(s string) *uint16
func BytePtrFromString(s string) (*byte, error)
func BytePtrToString(p *byte) string
func ByteSliceFromString(s string) ([]byte, error)
func ByteSliceToString(s []byte) string

Command Line Parsing

func CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error)
func ComposeCommandLine(args []string) string
func DecomposeCommandLine(commandLine string) ([]string, error)

DNS Operations

func DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error)
func DnsRecordListFree(rl *DNSRecord, freetype uint32)
func DnsNameCompare(name1 *uint16, name2 *uint16) (same bool)

Miscellaneous

func Chdir(path string) (err error)
func Chmod(path string, mode uint32) (err error)
func Chown(path string, uid int, gid int) (err error)
func Clearenv()
func Close(fd Handle) (err error)
func CloseOnExec(fd Handle)
func Environ() []string
func Getenv(key string) (value string, found bool)
func Setenv(key, value string) error
func Unsetenv(key string) error
func Getpagesize() int
func GetSystemTime AsFileTime(time *Filetime)
func NewCallback(fn interface{}) uintptr
func NewCallbackCDecl(fn interface{}) uintptr

Types

The windows package provides 255 types for Windows programming. Major types are documented below.

Basic Types

type Errno uintptr

Errno is the Windows error number.

Methods:

func (e Errno) Error() string
func (e Errno) Is(target error) bool
func (e Errno) Temporary() bool
func (e Errno) Timeout() bool

Handle Types

type Handle uintptr

Handle represents a Windows HANDLE.

Constants:

const (
    InvalidHandle = ^Handle(0)
    
    // Standard handles
    STD_INPUT_HANDLE  = -10
    STD_OUTPUT_HANDLE = -11
    STD_ERROR_HANDLE  = -12
)

Methods:

func (h Handle) Close() error

Token

type Token Handle

Token represents an access token handle.

Methods:

func (t Token) Close() error
func (t Token) GetTokenUser() (*Tokenuser, error)
func (t Token) GetTokenGroups() (*Tokengroups, error)
func (t Token) GetTokenPrimaryGroup() (*Tokenprimarygroup, error)
func (t Token) GetTokenPrivileges() (*Tokenprivileges, error)
func (t Token) GetUserProfileDirectory() (string, error)

SID (Security Identifier)

type SID struct{}

Methods:

func (sid *SID) String() (string, error)
func (sid *SID) Len() int
func (sid *SID) Copy() (*SID, error)
func (sid *SID) IdentifierAuthority() SidIdentifierAuthority
func (sid *SID) SubAuthorityCount() uint8
func (sid *SID) SubAuthority(idx uint32) (uint32, error)
func (sid *SID) IsValid() bool
func (sid *SID) Equals(sid2 *SID) bool
func (sid *SID) IsWellKnown(sidType WELL_KNOWN_SID_TYPE) bool
func (sid *SID) LookupAccount(system string) (account, domain string, accType uint32, err error)

ACL (Access Control List)

type ACL struct {
    AclRevision byte
    Sbz1        byte
    AclSize     uint16
    AceCount    uint16
    Sbz2        uint16
}

SECURITY_DESCRIPTOR

type SECURITY_DESCRIPTOR struct {
    Revision byte
    Sbz1     byte
    Control  SECURITY_DESCRIPTOR_CONTROL
    Owner    *SID
    Group    *SID
    Sacl     *ACL
    Dacl     *ACL
}

SecurityAttributes

type SecurityAttributes struct {
    Length             uint32
    SecurityDescriptor *SECURITY_DESCRIPTOR
    InheritHandle      uint32
}

Process and Thread Structures

type ProcessInformation struct {
    Process   Handle
    Thread    Handle
    ProcessId uint32
    ThreadId  uint32
}

type StartupInfo struct {
    Cb              uint32
    _               *uint16
    Desktop         *uint16
    Title           *uint16
    X               uint32
    Y               uint32
    XSize           uint32
    YSize           uint32
    XCountChars     uint32
    YCountChars     uint32
    FillAttribute   uint32
    Flags           uint32
    ShowWindow      uint16
    _               uint16
    _               *byte
    StdInput        Handle
    StdOutput       Handle
    StdErr          Handle
}

type ProcessEntry32 struct {
    Size              uint32
    CntUsage          uint32
    ProcessID         uint32
    DefaultHeapID     uintptr
    ModuleID          uint32
    CntThreads        uint32
    ParentProcessID   uint32
    PriClassBase      int32
    Flags             uint32
    ExeFile           [MAX_PATH]uint16
}

type ThreadEntry32 struct {
    Size           uint32
    CntUsage       uint32
    ThreadID       uint32
    OwnerProcessID uint32
    BasePri        int32
    DeltaPri       int32
    Flags          uint32
}

type ModuleEntry32 struct {
    Size         uint32
    ModuleID     uint32
    ProcessID    uint32
    GlblcntUsage uint32
    ProccntUsage uint32
    ModBaseAddr  uintptr
    ModBaseSize  uint32
    ModuleHandle Handle
    Module       [MAX_MODULE_NAME32 + 1]uint16
    ExePath      [MAX_PATH]uint16
}

File Structures

type Win32finddata struct {
    FileAttributes    uint32
    CreationTime      Filetime
    LastAccessTime    Filetime
    LastWriteTime     Filetime
    FileSizeHigh      uint32
    FileSizeLow       uint32
    Reserved0         uint32
    Reserved1         uint32
    FileName          [MAX_PATH]uint16
    AlternateFileName [14]uint16
}

type ByHandleFileInformation struct {
    FileAttributes     uint32
    CreationTime       Filetime
    LastAccessTime     Filetime
    LastWriteTime      Filetime
    VolumeSerialNumber uint32
    FileSizeHigh       uint32
    FileSizeLow        uint32
    NumberOfLinks      uint32
    FileIndexHigh      uint32
    FileIndexLow       uint32
}

Time Structures

type Filetime struct {
    LowDateTime  uint32
    HighDateTime uint32
}

type Systemtime struct {
    Year         uint16
    Month        uint16
    DayOfWeek    uint16
    Day          uint16
    Hour         uint16
    Minute       uint16
    Second       uint16
    Milliseconds uint16
}

type Timezoneinformation struct {
    Bias         int32
    StandardName [32]uint16
    StandardDate Systemtime
    StandardBias int32
    DaylightName [32]uint16
    DaylightDate Systemtime
    DaylightBias int32
}

type DynamicTimezoneinformation struct {
    Bias                        int32
    StandardName                [32]uint16
    StandardDate                Systemtime
    StandardBias                int32
    DaylightName                [32]uint16
    DaylightDate                Systemtime
    DaylightBias                int32
    TimeZoneKeyName             [128]uint16
    DynamicDaylightTimeDisabled bool
}

Overlapped I/O

type Overlapped struct {
    Internal     uintptr
    InternalHigh uintptr
    Offset       uint32
    OffsetHigh   uint32
    HEvent       Handle
}

Memory Information

type MemoryBasicInformation struct {
    BaseAddress       uintptr
    AllocationBase    uintptr
    AllocationProtect uint32
    RegionSize        uintptr
    State             uint32
    Protect           uint32
    Type              uint32
}

System Information

type SystemInfo struct {
    ProcessorArchitecture     uint16
    Reserved                  uint16
    PageSize                  uint32
    MinimumApplicationAddress uintptr
    MaximumApplicationAddress uintptr
    ActiveProcessorMask       uintptr
    NumberOfProcessors        uint32
    ProcessorType             uint32
    AllocationGranularity     uint32
    ProcessorLevel            uint16
    ProcessorRevision         uint16
}

Registry Types

type RegistryValueKind uint32

const (
    NONE                       RegistryValueKind = 0
    SZ                         RegistryValueKind = 1
    EXPAND_SZ                  RegistryValueKind = 2
    BINARY                     RegistryValueKind = 3
    DWORD                      RegistryValueKind = 4
    DWORD_BIG_ENDIAN          RegistryValueKind = 5
    LINK                       RegistryValueKind = 6
    MULTI_SZ                   RegistryValueKind = 7
    RESOURCE_LIST              RegistryValueKind = 8
    FULL_RESOURCE_DESCRIPTOR   RegistryValueKind = 9
    RESOURCE_REQUIREMENTS_LIST RegistryValueKind = 10
    QWORD                      RegistryValueKind = 11
)

Service Structures

type SERVICE_STATUS struct {
    ServiceType             uint32
    CurrentState            uint32
    ControlsAccepted        uint32
    Win32ExitCode           uint32
    ServiceSpecificExitCode uint32
    CheckPoint              uint32
    WaitHint                uint32
}

type SERVICE_TABLE_ENTRY struct {
    ServiceName *uint16
    ServiceProc uintptr
}

type QUERY_SERVICE_CONFIG struct {
    ServiceType      uint32
    StartType        uint32
    ErrorControl     uint32
    BinaryPathName   *uint16
    LoadOrderGroup   *uint16
    TagId            uint32
    Dependencies     *uint16
    ServiceStartName *uint16
    DisplayName      *uint16
}

Token Structures

type Tokenuser struct {
    User SIDAndAttributes
}

type Tokenprimarygroup struct {
    PrimaryGroup *SID
}

type Tokengroups struct {
    GroupCount uint32
    Groups     [1]SIDAndAttributes
}

type Tokenprivileges struct {
    PrivilegeCount uint32
    Privileges     [1]LUIDAndAttributes
}

type SIDAndAttributes struct {
    Sid        *SID
    Attributes uint32
}

type LUIDAndAttributes struct {
    Luid       LUID
    Attributes uint32
}

type LUID struct {
    LowPart  uint32
    HighPart int32
}

Console Structures

type ConsoleScreenBufferInfo struct {
    Size              Coord
    CursorPosition    Coord
    Attributes        uint16
    Window            SmallRect
    MaximumWindowSize Coord
}

type Coord struct {
    X int16
    Y int16
}

type SmallRect struct {
    Left   int16
    Top    int16
    Right  int16
    Bottom int16
}

Network Structures

type WSAData struct {
    Version      uint16
    HighVersion  uint16
    Description  [WSADESCRIPTION_LEN + 1]byte
    SystemStatus [WSASYS_STATUS_LEN + 1]byte
    MaxSockets   uint16
    MaxUdpDg     uint16
    VendorInfo   *byte
}

type WSABuf struct {
    Len uint32
    Buf *byte
}

type Sockaddr interface {
    sockaddr() (ptr unsafe.Pointer, len int32, err error)
}

type SockaddrInet4 struct {
    Port int
    Addr [4]byte
}

type SockaddrInet6 struct {
    Port   int
    ZoneId uint32
    Addr   [16]byte
}

type RawSockaddrAny struct {
    Addr RawSockaddr
    Pad  [96]byte
}

type RawSockaddr struct {
    Family uint16
    Data   [14]byte
}

IP Helper Structures

type IpAdapterInfo struct {
    Next                *IpAdapterInfo
    ComboIndex          uint32
    AdapterName         [MAX_ADAPTER_NAME_LENGTH + 4]byte
    Description         [MAX_ADAPTER_DESCRIPTION_LENGTH + 4]byte
    AddressLength       uint32
    Address             [MAX_ADAPTER_ADDRESS_LENGTH]byte
    Index               uint32
    Type                uint32
    DhcpEnabled         uint32
    CurrentIpAddress    *IpAddrString
    IpAddressList       IpAddrString
    GatewayList         IpAddrString
    DhcpServer          IpAddrString
    HaveWins            bool
    PrimaryWinsServer   IpAddrString
    SecondaryWinsServer IpAddrString
    LeaseObtained       int64
    LeaseExpires        int64
}

type IpAdapterAddresses struct {
    Length                uint32
    IfIndex               uint32
    Next                  *IpAdapterAddresses
    AdapterName           *byte
    FirstUnicastAddress   *IpAdapterUnicastAddress
    FirstAnycastAddress   *IpAdapterAnycastAddress
    FirstMulticastAddress *IpAdapterMulticastAddress
    FirstDnsServerAddress *IpAdapterDnsServerAdapter
    DnsSuffix             *uint16
    Description           *uint16
    FriendlyName          *uint16
    PhysicalAddress       [MAX_ADAPTER_ADDRESS_LENGTH]byte
    PhysicalAddressLength uint32
    Flags                 uint32
    Mtu                   uint32
    IfType                uint32
    OperStatus            uint32
    // ... additional fields
}

Certificate Structures

type CertContext struct {
    EncodingType uint32
    EncodedCert  *byte
    Length       uint32
    CertInfo     *CertInfo
    Store        Handle
}

type CertChainContext struct {
    Size                       uint32
    TrustStatus                CertTrustStatus
    ChainCount                 uint32
    Chains                     **CertSimpleChain
    LowerQualityChainCount     uint32
    LowerQualityChains         **CertChainContext
    HasRevocationFreshnessTime uint32
    RevocationFreshnessTime    uint32
}

type CertInfo struct {
    Version              uint32
    SerialNumber         CryptIntegerBlob
    SignatureAlgorithm   CryptAlgorithmIdentifier
    Issuer               CertNameBlob
    NotBefore            Filetime
    NotAfter             Filetime
    Subject              CertNameBlob
    SubjectPublicKeyInfo CertPublicKeyInfo
    IssuerUniqueId       CryptBitBlob
    SubjectUniqueId      CryptBitBlob
    CountExtensions      uint32
    Extensions           *CertExtension
}

type CertChainPolicyPara struct {
    Size            uint32
    Flags           uint32
    ExtraPolicyPara unsafe.Pointer
}

type CertChainPolicyStatus struct {
    Size              uint32
    Error             uint32
    ChainIndex        uint32
    ElementIndex      uint32
    ExtraPolicyStatus unsafe.Pointer
}

Cryptography Structures

type DataBlob struct {
    Size uint32
    Data *byte
}

type CryptProtectPromptStruct struct {
    Size        uint32
    PromptFlags uint32
    HwndApp     HWND
    Prompt      *uint16
}

Serial Communication

type DCB struct {
    DCBlength uint32
    BaudRate  uint32
    Flags     uint32
    wReserved uint16
    XonLim    uint16
    XoffLim   uint16
    ByteSize  byte
    Parity    byte
    StopBits  byte
    XonChar   byte
    XoffChar  byte
    ErrorChar byte
    EofChar   byte
    EvtChar   byte
    wReserved1 uint16
}

type CommTimeouts struct {
    ReadIntervalTimeout         uint32
    ReadTotalTimeoutMultiplier  uint32
    ReadTotalTimeoutConstant    uint32
    WriteTotalTimeoutMultiplier uint32
    WriteTotalTimeoutConstant   uint32
}

type ComStat struct {
    Flags   uint32
    CBInQue uint32
    CBOutQue uint32
}

COM Structures

type GUID struct {
    Data1 uint32
    Data2 uint16
    Data3 uint16
    Data4 [8]byte
}

type BIND_OPTS3 struct {
    CbStruct              uint32
    GrfFlags              uint32
    GrfMode               uint32
    TickCountDeadline     uint32
    TrackFlags            uint32
    ClassContext          uint32
    Locale                uint32
    ServerInfo            *COSERVERINFO
    Hwnd                  HWND
}

DNS Structures

type DNSRecord struct {
    Next     *DNSRecord
    Name     *uint16
    Type     uint16
    Length   uint16
    Dw       uint32
    Ttl      uint32
    Reserved uint32
    Data     [40]byte
}

Device Management

type DEVINST uint32

Well-Known SID Type

type WELL_KNOWN_SID_TYPE uint32

const (
    WinNullSid                                    = 0
    WinWorldSid                                   = 1
    WinLocalSid                                   = 2
    WinCreatorOwnerSid                            = 3
    WinCreatorGroupSid                            = 4
    // ... hundreds more
)

Trustee

type TRUSTEE struct {
    MultipleTrustee          *TRUSTEE
    MultipleTrusteeOperation MULTIPLE_TRUSTEE_OPERATION
    TrusteeForm              TRUSTEE_FORM
    TrusteeType              TRUSTEE_TYPE
    Name                     *uint16
}

type EXPLICIT_ACCESS struct {
    AccessPermissions uint32
    AccessMode        ACCESS_MODE
    Inheritance       uint32
    Trustee           TRUSTEE
}

Security Information

type SECURITY_INFORMATION uint32

const (
    OWNER_SECURITY_INFORMATION            = 0x00000001
    GROUP_SECURITY_INFORMATION            = 0x00000002
    DACL_SECURITY_INFORMATION             = 0x00000004
    SACL_SECURITY_INFORMATION             = 0x00000008
    LABEL_SECURITY_INFORMATION            = 0x00000010
    ATTRIBUTE_SECURITY_INFORMATION        = 0x00000020
    SCOPE_SECURITY_INFORMATION            = 0x00000040
    BACKUP_SECURITY_INFORMATION           = 0x00010000
    PROTECTED_DACL_SECURITY_INFORMATION   = 0x80000000
    PROTECTED_SACL_SECURITY_INFORMATION   = 0x40000000
    UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000
    UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000
)

Object Type

type SE_OBJECT_TYPE uint32

const (
    SE_UNKNOWN_OBJECT_TYPE         = 0
    SE_FILE_OBJECT                 = 1
    SE_SERVICE                     = 2
    SE_PRINTER                     = 3
    SE_REGISTRY_KEY                = 4
    SE_LMSHARE                     = 5
    SE_KERNEL_OBJECT               = 6
    SE_WINDOW_OBJECT               = 7
    SE_DS_OBJECT                   = 8
    SE_DS_OBJECT_ALL               = 9
    SE_PROVIDER_DEFINED_OBJECT     = 10
    SE_WMIGUID_OBJECT              = 11
    SE_REGISTRY_WOW64_32KEY        = 12
    SE_REGISTRY_WOW64_64KEY        = 13
)

Usage Examples

Creating a File

package main

import (
    "fmt"
    "log"
    "unsafe"

    "golang.org/x/sys/windows"
)

func main() {
    filename, err := windows.UTF16PtrFromString("test.txt")
    if err != nil {
        log.Fatal(err)
    }

    handle, err := windows.CreateFile(
        filename,
        windows.GENERIC_READ|windows.GENERIC_WRITE,
        0,
        nil,
        windows.CREATE_ALWAYS,
        windows.FILE_ATTRIBUTE_NORMAL,
        0,
    )
    if err != nil {
        log.Fatal(err)
    }
    defer windows.CloseHandle(handle)

    data := []byte("Hello, Windows!")
    var written uint32
    err = windows.WriteFile(handle, data, &written, nil)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Wrote %d bytes\n", written)
}

Getting Current User

package main

import (
    "fmt"
    "log"

    "golang.org/x/sys/windows"
)

func main() {
    token, err := windows.OpenCurrentProcessToken()
    if err != nil {
        log.Fatal(err)
    }
    defer token.Close()

    user, err := token.GetTokenUser()
    if err != nil {
        log.Fatal(err)
    }

    account, domain, _, err := user.User.Sid.LookupAccount("")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("User: %s\\%s\n", domain, account)
}

Working with Services

package main

import (
    "fmt"
    "log"

    "golang.org/x/sys/windows"
    "golang.org/x/sys/windows/svc"
    "golang.org/x/sys/windows/svc/mgr"
)

func main() {
    m, err := mgr.Connect()
    if err != nil {
        log.Fatal(err)
    }
    defer m.Disconnect()

    s, err := m.OpenService("W32Time")
    if err != nil {
        log.Fatal(err)
    }
    defer s.Close()

    status, err := s.Query()
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Service state: %v\n", status.State)
}

Registry Operations

package main

import (
    "fmt"
    "log"

    "golang.org/x/sys/windows/registry"
)

func main() {
    // Open registry key
    k, err := registry.OpenKey(
        registry.LOCAL_MACHINE,
        `SOFTWARE\Microsoft\Windows\CurrentVersion`,
        registry.QUERY_VALUE,
    )
    if err != nil {
        log.Fatal(err)
    }
    defer k.Close()

    // Read string value
    val, _, err := k.GetStringValue("ProgramFilesDir")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Program Files: %s\n", val)
}

Named Pipe Server

package main

import (
    "log"
    "unsafe"

    "golang.org/x/sys/windows"
)

func main() {
    name, _ := windows.UTF16PtrFromString(`\\.\pipe\testpipe`)

    pipe, err := windows.CreateNamedPipe(
        name,
        windows.PIPE_ACCESS_DUPLEX,
        windows.PIPE_TYPE_BYTE|windows.PIPE_READMODE_BYTE|windows.PIPE_WAIT,
        1,
        4096,
        4096,
        0,
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }
    defer windows.CloseHandle(pipe)

    log.Println("Waiting for client...")
    
    err = windows.ConnectNamedPipe(pipe, nil)
    if err != nil {
        log.Fatal(err)
    }

    log.Println("Client connected")

    buf := make([]byte, 1024)
    var read uint32
    err = windows.ReadFile(pipe, buf, &read, nil)
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Received: %s\n", buf[:read])
}

Process Creation

package main

import (
    "log"
    "unsafe"

    "golang.org/x/sys/windows"
)

func main() {
    appName, _ := windows.UTF16PtrFromString("notepad.exe")

    var si windows.StartupInfo
    var pi windows.ProcessInformation
    si.Cb = uint32(unsafe.Sizeof(si))

    err := windows.CreateProcess(
        appName,
        nil,
        nil,
        nil,
        false,
        0,
        nil,
        nil,
        &si,
        &pi,
    )
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Started process %d\n", pi.ProcessId)

    windows.CloseHandle(pi.Process)
    windows.CloseHandle(pi.Thread)
}

Best Practices

  1. Error Handling: Always check errors from Windows API calls. Many functions return error codes that need proper handling.

  2. Handle Management: Always close handles when done using CloseHandle or the type-specific Close method. Use defer for automatic cleanup.

  3. String Conversion: Use UTF16PtrFromString and UTF16ToString for converting between Go strings and Windows UTF-16 strings.

  4. Security: Be careful with security descriptors, ACLs, and tokens. Improper use can create security vulnerabilities.

  5. Memory Management: Windows API often requires pre-allocated buffers. Always allocate sufficient space and check return values.

  6. Overlapped I/O: For asynchronous operations, properly initialize and manage Overlapped structures.

Common Pitfalls

  1. Forgetting to Close Handles: Leaked handles can exhaust system resources.

  2. Buffer Size Errors: Many Windows APIs require correct buffer sizes. Always check and handle ERROR_INSUFFICIENT_BUFFER.

  3. String Encoding: Windows uses UTF-16. Always convert Go strings properly using the provided utility functions.

  4. Security Context: Many operations require specific privileges or security contexts.

  5. Platform-Specific Code: Code using windows package is Windows-specific. Use build tags when needed.

Related Packages

  • golang.org/x/sys/windows/svc - Windows service control
  • golang.org/x/sys/windows/registry - Windows registry access
  • golang.org/x/sys/unix - Unix equivalent
  • golang.org/x/sys/cpu - CPU feature detection
  • os - Higher-level file and process operations
  • net - Higher-level networking

Additional Resources

  • Windows API Documentation
  • Go Windows Programming