Windows v0.1.0

Source
Windows platform bindings

Installation

Add Windows to the [Dependencies] table of your package's Rux.toml:

[Dependencies]
Windows = { Namespace = "Rux", Version = "0.1.0" }

Standard packages are declared by hand: the registry does not serve them, so rux add Rux/Windows cannot add them.

Guide

Windows platform bindings: Win32 declarations linked straight against Kernel32.dll, with no C runtime in between.

What it provides

ModuleCovers
TypesHandle, ModuleHandle, Bool, Dword, WideChar, NtStatus, FileTime, SystemTime, and InvalidHandleValue
Constantsthe code pages and the file-creation dispositions
Kernelthe Kernel32 entry points, including the A forms kept for compatibility
Filethe Unicode W file, directory and console entry points, with the access, share and move flags
MemoryVirtualAlloc, VirtualFree, VirtualProtect, VirtualLock, and the state and protection flags
EntropyBCryptGenRandom behind a GetRandom that either fills the buffer or fails
ClockQueryPerformanceCounter, QueryPerformanceFrequency, the precise wall clock, and the epoch conversion
ShellCommandLineToArgvW, which splits the command line into arguments the way the C runtime does
SynchWaitOnAddress, WakeByAddressSingle and WakeByAddressAll, from the synchronization API set
ProcessControlCreateProcessW and its structures, CreatePipe, handle inheritance, GetExitCodeProcess, TerminateProcess and SetEnvironmentVariableW
TimeZoneGetTimeZoneInformation, TimeZoneInformation and TimeZoneRuleDate
WinsockWSAStartup, WSAGetLastError, the Ws2_32 socket calls, ioctlsocket with FIONBIO, WSAPoll with WsaPollFd and the POLL* flags, getaddrinfo and freeaddrinfo, WsaData, AddressInfo and the socket constants

The module names describe where each declaration comes from; they are not part of an import path.

Prefer the W entry points. The A forms convert through the process code page, which cannot express every name a file system can hold and differs between machines — so a path that works on one system fails on another for reasons the program cannot see. A path is text a user or a file system chose, not text the program chose. The A forms stay declared because existing callers use them, and each is now marked.

Two failure sentinels, and they are not the same. A handle-returning call reports InvalidHandleValue, which is -1 cast to a pointer; a memory-returning call reports null; and GetFileAttributesW reports a third value again, INVALID_FILE_ATTRIBUTES. Testing a handle against null, or an allocation against InvalidHandleValue, reads a failure as a success. BCryptGenRandom reports none of them — it returns an NTSTATUS, which GetLastError knows nothing about, so GetRandom's boolean is the only thing a caller may read after it. A successful draw leaves whatever Win32 code was already standing exactly where it was.

CloseHandle(InvalidHandleValue) succeeds. (HANDLE)-1 is the current process's pseudo-handle, not an invalid one, and closing a pseudo-handle is a no-op that reports success — where closing null or an arbitrary number fails with ERROR_INVALID_HANDLE. A cleanup path that closes the sentinel defensively is therefore not caught by its return value; it silently does nothing. This is asserted in Tests/Packages/Windows/Failures, because it is not what the name suggests.

Windows separates reserving address space from committing storage to it, which no other supported system does. A reserved page may not be touched; committing is what makes it usable. MEM_RELEASE requires a size of zero and the exact base address the reservation returned. Releasing a reservation twice fails, with ERROR_INVALID_ADDRESS, where POSIX's munmap on an already-unmapped range succeeds — so code that treats a double release as harmless is portable in one direction only.

What is tested

Tests/Packages/Windows/Failures covers the three sentinels, the Win32 code each kind of failure leaves behind, the different codes the virtual allocator and the heap give for the same impossible size, the release rules, and the NTSTATUS domain staying clear of GetLastError. Tests/Packages/Windows/Platform covers the reserve-then-commit split, protection, the entropy source and the clocks; Tests/Packages/Windows/Constants covers the enumerated values. Tests/Unit/PlatformBindingContractTests.cpp additionally checks, on any host, that the sentinels differ, that every ERROR_ constant holds its published value, and that no two of them share a number.

Unlike the three POSIX packages, all of this runs where it is developed, so every number in it was read out of a running program rather than out of documentation.

Values and pointers

Win32 records such as FileTime and SystemTime are structural values and copy by value. Package-owned inspection helpers borrow them, so call FileTimeTicks(stamp) with the value itself. Imported Win32 declarations retain raw pointers for handles, optional arguments, buffers, and OS-owned addresses because null and sentinel values are part of those contracts. A raw handle or pointer never transfers ownership automatically; close or release it with the matching Win32 function.

Platform

Windows only. Guard use behind a compile-time check, so a build for another target never resolves these declarations:

import Core::{ #target };

when #target.os == .Windows {
    import Windows::{ GetStdHandle, StdOutputHandle, WriteConsoleA };
}

Index

Types

NameSummary
CodePageThe CodePage values exposed by this package.
CreationDispositionThe CreationDisposition values exposed by this package.
SecurityAttributesThe SECURITY_ATTRIBUTES a pipe or file is created with: here only whether its handle is inheritable.
StartupInfoThe STARTUPINFOW a new process is started with; this package fills in its standard handles.
ProcessInformationThe PROCESS_INFORMATION CreateProcessW fills in: the new process and its first thread.
TimeZoneRuleDateWhen a time-zone rule takes effect, in the layout of SYSTEMTIME but read as a rule, not a date.
TimeZoneInformationWin32's TIME_ZONE_INFORMATION: a zone's offsets and when its daylight time starts and ends.
HandleAn opaque kernel object reference.
ModuleHandleA module reference, as LoadLibraryW returns one.
BoolWin32's BOOL: a 32-bit integer where zero is false and anything else is true.
DwordWin32's DWORD: a 32-bit unsigned integer.
WideCharA UTF-16 code unit, which is what every *W entry point takes.
NtStatusAn NTSTATUS: the status code the native and cryptographic interfaces report with.
FileTimeWin32's FILETIME: a count of 100-nanosecond ticks since the start of 1601, UTC.
SystemTimeWin32's SYSTEMTIME: a broken-down date and time, one field per component.
Win32FindDataAWin32's WIN32_FIND_DATAA: one directory entry, as FindFirstFileA and FindNextFileA fill it.
SystemInfoWhat GetSystemInfo reports about the machine.
WsaDataRoom for a WSADATA, which WSAStartup fills and nothing here reads.
AddressInfoWinsock's addrinfo: one result of getaddrinfo, linked to the next.
WsaPollFdWSAPOLLFD: one socket WSAPoll watches, the events wanted, and the events it reports.

Functions

NameSummary
QueryPerformanceCounterReads the monotonic performance counter.
QueryPerformanceFrequencyReads how many performance-counter ticks make one second.
GetSystemTimePreciseAsFileTimeReads the current wall-clock time at the highest resolution the system offers.
GetSystemTimeAsFileTimeReads the current wall-clock time at the system tick's resolution.
FileTimeTicksThe whole 64-bit value a FileTime splits across two fields.
GetRandomFills length bytes of buffer with unpredictable bytes.
CreateFileWCreates or opens a file or device, taking a UTF-16 path.
FindFirstFileWBegins a directory enumeration matching a UTF-16 pattern.
FindNextFileWContinues a directory enumeration; fails with ERROR_NO_MORE_FILES at its end.
CreateHardLinkWCreates a hard link: a second name for an existing file's contents.
CreateSymbolicLinkWCreates a symbolic link; returns a BOOLEAN, so only the low byte is meaningful.
GetFileInformationByHandleFills a BY_HANDLE_FILE_INFORMATION record for an open handle.
SetFileTimeSets the creation, last-access and last-write times of an open handle.
GetFinalPathNameByHandleWWrites the final, resolved path of an open handle: symbolic links followed, short names expanded, case as the filesystem stores it.
GetTempPathWWrites the path of the directory designated for temporary files.
DeleteFileWDeletes a file, taking a UTF-16 path.
MoveFileExWMoves or renames a file or directory, taking UTF-16 paths.
CopyFileWCopies a file, taking UTF-16 paths.
CreateDirectoryWCreates a directory, taking a UTF-16 path.
RemoveDirectoryWRemoves an empty directory, taking a UTF-16 path.
GetFileAttributesWReads a file's attributes, taking a UTF-16 path.
SetFileAttributesWSets a file's attributes, taking a UTF-16 path.
GetCurrentDirectoryWReads the current directory into a UTF-16 buffer.
SetCurrentDirectoryWSets the current directory, taking a UTF-16 path.
FlushFileBuffersFlushes a file handle's writes to the device.
SetEndOfFileSets the size of a file to the handle's current position.
WriteConsoleWWrites a character string to a console screen buffer beginning at the current cursor location.
ReadConsoleWReads UTF-16 from a console input buffer.
AllocConsoleAllocates a new console for the calling process.
BeepGenerates simple tones on the speaker.
CloseHandleCloses an open object handle.
CopyFileACopies an existing file to a new file.
CreateDirectoryACreates a new directory.
CreateFileACreates or opens a file or I/O device.
DeleteFileADeletes an existing file.
ExitProcessEnds the calling process and all its threads.
FindCloseCloses a file search handle opened by the FindFirstFile, FindFirstFileEx, FindFirstFileNameW,.
FindFirstFileASearches a directory for a file or subdirectory with a name that matches a specific name (or partial name if wildcards are used).
FindNextFileAContinues a file search from a previous call to the FindFirstFile, FindFirstFileEx, or FindFirstFileTransacted functions.
FreeLibraryFrees the loaded dynamic-link library (DLL) module and, if necessary, decrements its reference count.
GetConsoleModeRetrieves the current input or output mode of a console screen buffer.
GetCommandLineWRetrieves the command line the process was started with, as one string.
GetModuleFileNameWRetrieves the full path of the file a module was loaded from; a null module is the process's executable.
GetCurrentDirectoryARetrieves the current directory.
GetEnvironmentStringsWCopies the calling process's environment block.
GetCurrentProcessIdRetrieves the process identifier of the calling process.
GetActiveProcessorCountRetrieves the number of active processors in a processor group, or in all of them.
GetCurrentThreadIdRetrieves the thread identifier of the calling thread.
GetFileAttributesARetrieves file attributes.
GetFileSizeExRetrieves the size of the specified file.
GetSystemInfoReads what the system reports about the machine, including its page size.
GetLastErrorRetrieves the calling thread's last-error code value.
GetLocalTimeRetrieves the current local date and time.
GetProcAddressRetrieves the address of an exported symbol.
GetProcessHeapRetrieves a handle to the default heap of the calling process.
GetStdHandleRetrieves a handle to the specified standard device (standard input, standard output, or standard error).
GetSystemTimeRetrieves the current system date and time in Coordinated Universal Time (UTC) format.
GetTickCount64Retrieves the number of milliseconds that have elapsed since the system was started.
HeapAllocAllocates a block of memory from a heap.
HeapFreeFrees a memory block allocated from a heap by the HeapAlloc or HeapReAlloc function.
HeapReAllocReallocates a block of memory from a heap.
LoadLibraryALoads a DLL into the calling process.
MoveFileAMoves an existing file or directory.
MultiByteToWideCharMaps a character string to a UTF-16 wide character string.
ReadConsoleAReads characters from a console input buffer.
ReadFileReads data from the specified file or input/output (I/O) device.
RemoveDirectoryADeletes an existing empty directory.
RtlCompareMemoryCompares two blocks of memory and returns the number of bytes that match until the first difference.
RtlCopyMemoryCopies a block of memory from one location to another.
RtlFillMemoryFills a block of memory with the specified fill value.
RtlZeroMemoryFills a block of memory with zeros, given a pointer to the block and the length in bytes.
SetCurrentDirectoryAChanges the current directory.
SetFileAttributesASets file attributes.
SetFilePointerExMoves the file pointer of the specified file.
CreateThreadCreates a thread to execute within the virtual address space of the calling process.
SleepSuspends the execution of the current thread until the time-out interval elapses.
SwitchToThreadCauses the calling thread to yield execution to another thread that is ready to run.
WaitForSingleObjectWaits until the specified object is in the signaled state or the time-out interval elapses.
WideCharToMultiByteConverts UTF-16 text to another code page.
WriteConsoleAWrites a character string to a console screen buffer beginning at the current cursor location.
WriteFileWrites data to the specified file or input/output (I/O) device.
VirtualAllocReserves, commits, or changes the state of a region of pages.
VirtualFreeReleases, decommits, or both, a region of pages.
VirtualProtectChanges the protection on a region of committed pages.
VirtualLockLocks a region into physical memory so it is never written to the page file.
VirtualUnlockUnlocks a region previously locked into physical memory.
CreateProcessWStarts a program as a new process.
GetExitCodeProcessReads a process's exit code, or STILL_ACTIVE while it runs.
TerminateProcessEnds a process and all its threads.
CreatePipeCreates an anonymous pipe.
SetHandleInformationChanges a handle's flags, such as whether it is inherited.
DuplicateHandleDuplicates a handle, here into the same process with different inheritance.
GetCurrentProcessReturns a pseudo-handle for the calling process, which needs no closing.
SetEnvironmentVariableWSets or removes an environment variable of the calling process.
CommandLineToArgvWSplits a command line into arguments the way the C runtime does.
WaitOnAddressWaits for the value at an address to change.
WakeByAddressSingleWakes one thread waiting on an address.
WakeByAddressAllWakes every thread waiting on an address.
GetTimeZoneInformationReads the system's current time zone.
WSAStartupStarts Winsock for this process.
WSAGetLastErrorThe calling thread's last Winsock error.
socketOpens a socket.
connectConnects a socket to address.
bindGives a socket its local address.
listenMakes a bound stream socket accept connections.
acceptAccepts a waiting connection.
sendtoSends bytes on a socket, to address when it is not connected.
recvfromReceives bytes from a socket, and where they came from.
closesocketCloses a socket.
shutdownEnds one or both directions of a connection.
setsockoptSets a socket option.
getsocknameReads a socket's local address.
getpeernameReads the address of a connected socket's peer.
getaddrinfoLooks up the addresses of a host and service.
freeaddrinfoFrees the results of getaddrinfo.
ioctlsocketSets a socket's mode, such as non-blocking with FIONBIO.
WSAPollWaits until one of count sockets is ready or timeout milliseconds pass, filling each one's returned.

Constants

NameSummary
FileTimeTicksPerSecondHow many FileTime ticks make one second.
FileTimeToUnixEpochSecondsSeconds between the FileTime epoch of 1601 and the Unix epoch of 1970.
ALL_PROCESSOR_GROUPSALL_PROCESSOR_GROUPS: asks GetActiveProcessorCount about every processor group at once.
STACK_SIZE_PARAM_IS_A_RESERVATIONSTACK_SIZE_PARAM_IS_A_RESERVATION: CreateThread takes its stack size as the space to reserve rather than to commit, which is what a stack size usually means.
INFINITEINFINITE: a wait with no time-out.
BCRYPT_USE_SYSTEM_PREFERRED_RNGBCRYPT_USE_SYSTEM_PREFERRED_RNG: draw from the system's preferred generator rather than a named algorithm.
STATUS_SUCCESSSTATUS_SUCCESS: the status an NtStatus-reporting call gives when it worked.
ERROR_SUCCESSERROR_SUCCESS: the operation succeeded, which is the value GetLastError reports when nothing has failed.
ERROR_FILE_NOT_FOUNDERROR_FILE_NOT_FOUND: the named file does not exist.
ERROR_PATH_NOT_FOUNDERROR_PATH_NOT_FOUND: a directory along the path does not exist.
ERROR_ACCESS_DENIEDERROR_ACCESS_DENIED: the caller does not have the rights the operation needs.
ERROR_INVALID_HANDLEERROR_INVALID_HANDLE: the handle is not one this operation can use.
ERROR_NOT_ENOUGH_MEMORYERROR_NOT_ENOUGH_MEMORY: not enough storage to complete the operation.
ERROR_OUTOFMEMORYERROR_OUTOFMEMORY: not enough storage to complete the operation.
ERROR_NOT_SUPPORTEDERROR_NOT_SUPPORTED: the operation is not supported on this object or this system.
ERROR_FILE_EXISTSERROR_FILE_EXISTS: the file already exists, and the call was told not to replace it.
ERROR_INVALID_PARAMETERERROR_INVALID_PARAMETER: an argument is not valid.
ERROR_DISK_FULLERROR_DISK_FULL: the volume has no room left.
ERROR_PRIVILEGE_NOT_HELDERROR_PRIVILEGE_NOT_HELD: the account lacks a privilege the operation requires.
ERROR_NO_MORE_FILESERROR_NO_MORE_FILES: a directory enumeration has handed over its last entry.
ERROR_ALREADY_EXISTSERROR_ALREADY_EXISTS: the object already exists.
ERROR_INVALID_ADDRESSERROR_INVALID_ADDRESS: the address is not one the operation can use.
ERROR_COMMITMENT_LIMITERROR_COMMITMENT_LIMIT: the system's commit limit is reached, so nothing more can be backed.
GENERIC_READGENERIC_READ: the handle may read.
GENERIC_WRITEGENERIC_WRITE: the handle may write.
FILE_APPEND_DATAFILE_APPEND_DATA: the handle may append, and only append.
FILE_SHARE_READFILE_SHARE_READ: other openers may read while this handle is open.
FILE_SHARE_WRITEFILE_SHARE_WRITE: other openers may write while this handle is open.
FILE_SHARE_DELETEFILE_SHARE_DELETE: the file may be renamed or deleted while this handle is open.
FILE_ATTRIBUTE_NORMALFILE_ATTRIBUTE_NORMAL: no attributes beyond being an ordinary file.
FILE_ATTRIBUTE_READONLYFILE_ATTRIBUTE_READONLY: the file may not be opened for writing or deleted.
FILE_ATTRIBUTE_DIRECTORYFILE_ATTRIBUTE_DIRECTORY: the name is a directory.
FILE_ATTRIBUTE_REPARSE_POINTFILE_ATTRIBUTE_REPARSE_POINT: the name carries a reparse point, which is what a symbolic link is.
INVALID_FILE_ATTRIBUTESINVALID_FILE_ATTRIBUTES: what GetFileAttributesW returns when it could not answer.
FILE_FLAG_BACKUP_SEMANTICSFILE_FLAG_BACKUP_SEMANTICS: let CreateFileW open a directory.
FILE_FLAG_OPEN_REPARSE_POINTFILE_FLAG_OPEN_REPARSE_POINT: open the symbolic link itself rather than what it points at.
FILE_FLAG_DELETE_ON_CLOSEFILE_FLAG_DELETE_ON_CLOSE: remove the file when its last handle closes.
FILE_FLAG_WRITE_THROUGHFILE_FLAG_WRITE_THROUGH: writes reach the device before the call returns.
SYMBOLIC_LINK_FLAG_DIRECTORYSYMBOLIC_LINK_FLAG_DIRECTORY: the link's target is a directory.
SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATESYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE: let a Developer Mode machine create the link without the privilege older systems demand.
MOVEFILE_REPLACE_EXISTINGMOVEFILE_REPLACE_EXISTING: let the move overwrite an existing target.
MOVEFILE_WRITE_THROUGHMOVEFILE_WRITE_THROUGH: do not return until the move has reached the disk.
MEM_COMMITMEM_COMMIT: back the range with storage.
MEM_RESERVEMEM_RESERVE: take the address space without backing it.
MEM_RESETMEM_RESET: the contents are no longer of interest and need not be written to the page file.
MEM_RELEASEMEM_RELEASE: give back the whole reservation, which VirtualFree requires a size of zero for.
MEM_DECOMMITMEM_DECOMMIT: take back the storage but keep the reservation.
PAGE_NOACCESSPAGE_NOACCESS: the pages may not be touched at all.
PAGE_READONLYPAGE_READONLY: the pages may be read.
PAGE_READWRITEPAGE_READWRITE: the pages may be read and written.
PAGE_EXECUTEPAGE_EXECUTE: the pages may be executed.
PAGE_EXECUTE_READPAGE_EXECUTE_READ: the pages may be executed and read.
PAGE_EXECUTE_READWRITEPAGE_EXECUTE_READWRITE: the pages may be executed, read and written.
PAGE_GUARDPAGE_GUARD: the next touch raises a one-shot guard exception and then clears the flag.
STARTF_USESTDHANDLESSTARTF_USESTDHANDLES: the standard handles in StartupInfo are the child's.
CREATE_UNICODE_ENVIRONMENTCREATE_UNICODE_ENVIRONMENT: the environment block is UTF-16.
HANDLE_FLAG_INHERITHANDLE_FLAG_INHERIT: the handle is inherited by child processes.
DUPLICATE_SAME_ACCESSDUPLICATE_SAME_ACCESS: a duplicated handle has the access of the original.
WAIT_TIMEOUTWAIT_TIMEOUT: a wait ended because its time ran out.
ERROR_BROKEN_PIPEERROR_BROKEN_PIPE: the other end of the pipe was closed.
InvalidHandleValueThe value a handle-returning call reports failure with.
StdInputHandleThe public StdInputHandle value.
StdOutputHandleThe public StdOutputHandle value.
StdErrorHandleThe public StdErrorHandle value.
AF_INETAF_INET: the IPv4 address family.
AF_INET6AF_INET6: the IPv6 address family.
SOCK_STREAMSOCK_STREAM: a connected byte stream.
SOCK_DGRAMSOCK_DGRAM: individual datagrams.
SOL_SOCKETSOL_SOCKET: the level of the options every socket has.
SO_RCVTIMEOSO_RCVTIMEO: how long a receive waits, in milliseconds.
SO_SNDTIMEOSO_SNDTIMEO: how long a send waits, in milliseconds.
IPPROTO_TCPIPPROTO_TCP: the level of TCP's options.
TCP_NODELAYTCP_NODELAY: send small writes at once rather than gathering them.
IPPROTO_IPV6IPPROTO_IPV6: the level of IPv6's options.
IPV6_V6ONLYIPV6_V6ONLY: accept only IPv6 on an IPv6 socket.
INVALID_SOCKETINVALID_SOCKET: what a call that makes a socket returns on failure.
FIONBIOFIONBIO: the ioctlsocket command that turns a socket's non-blocking mode on or off.
POLLRDNORMPOLLRDNORM: WSAPoll reports a socket with data to read, or a connection to accept.
POLLWRNORMPOLLWRNORM: WSAPoll reports a socket a write would not wait on.
POLLERRPOLLERR: the socket has an error pending; always reported.
POLLHUPPOLLHUP: the connection was closed; always reported.
POLLNVALPOLLNVAL: the socket is not valid; always reported.