Windows v0.1.0
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
| Module | Covers |
|---|---|
Types | Handle, ModuleHandle, Bool, Dword, WideChar, NtStatus, FileTime, SystemTime, and InvalidHandleValue |
Constants | the code pages and the file-creation dispositions |
Kernel | the Kernel32 entry points, including the A forms kept for compatibility |
File | the Unicode W file, directory and console entry points, with the access, share and move flags |
Memory | VirtualAlloc, VirtualFree, VirtualProtect, VirtualLock, and the state and protection flags |
Entropy | BCryptGenRandom behind a GetRandom that either fills the buffer or fails |
Clock | QueryPerformanceCounter, QueryPerformanceFrequency, the precise wall clock, and the epoch conversion |
Shell | CommandLineToArgvW, which splits the command line into arguments the way the C runtime does |
Synch | WaitOnAddress, WakeByAddressSingle and WakeByAddressAll, from the synchronization API set |
ProcessControl | CreateProcessW and its structures, CreatePipe, handle inheritance, GetExitCodeProcess, TerminateProcess and SetEnvironmentVariableW |
TimeZone | GetTimeZoneInformation, TimeZoneInformation and TimeZoneRuleDate |
Winsock | WSAStartup, 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
| Name | Summary |
|---|---|
CodePage | The CodePage values exposed by this package. |
CreationDisposition | The CreationDisposition values exposed by this package. |
SecurityAttributes | The SECURITY_ATTRIBUTES a pipe or file is created with: here only whether its handle is inheritable. |
StartupInfo | The STARTUPINFOW a new process is started with; this package fills in its standard handles. |
ProcessInformation | The PROCESS_INFORMATION CreateProcessW fills in: the new process and its first thread. |
TimeZoneRuleDate | When a time-zone rule takes effect, in the layout of SYSTEMTIME but read as a rule, not a date. |
TimeZoneInformation | Win32's TIME_ZONE_INFORMATION: a zone's offsets and when its daylight time starts and ends. |
Handle | An opaque kernel object reference. |
ModuleHandle | A module reference, as LoadLibraryW returns one. |
Bool | Win32's BOOL: a 32-bit integer where zero is false and anything else is true. |
Dword | Win32's DWORD: a 32-bit unsigned integer. |
WideChar | A UTF-16 code unit, which is what every *W entry point takes. |
NtStatus | An NTSTATUS: the status code the native and cryptographic interfaces report with. |
FileTime | Win32's FILETIME: a count of 100-nanosecond ticks since the start of 1601, UTC. |
SystemTime | Win32's SYSTEMTIME: a broken-down date and time, one field per component. |
Win32FindDataA | Win32's WIN32_FIND_DATAA: one directory entry, as FindFirstFileA and FindNextFileA fill it. |
SystemInfo | What GetSystemInfo reports about the machine. |
WsaData | Room for a WSADATA, which WSAStartup fills and nothing here reads. |
AddressInfo | Winsock's addrinfo: one result of getaddrinfo, linked to the next. |
WsaPollFd | WSAPOLLFD: one socket WSAPoll watches, the events wanted, and the events it reports. |
Functions
| Name | Summary |
|---|---|
QueryPerformanceCounter | Reads the monotonic performance counter. |
QueryPerformanceFrequency | Reads how many performance-counter ticks make one second. |
GetSystemTimePreciseAsFileTime | Reads the current wall-clock time at the highest resolution the system offers. |
GetSystemTimeAsFileTime | Reads the current wall-clock time at the system tick's resolution. |
FileTimeTicks | The whole 64-bit value a FileTime splits across two fields. |
GetRandom | Fills length bytes of buffer with unpredictable bytes. |
CreateFileW | Creates or opens a file or device, taking a UTF-16 path. |
FindFirstFileW | Begins a directory enumeration matching a UTF-16 pattern. |
FindNextFileW | Continues a directory enumeration; fails with ERROR_NO_MORE_FILES at its end. |
CreateHardLinkW | Creates a hard link: a second name for an existing file's contents. |
CreateSymbolicLinkW | Creates a symbolic link; returns a BOOLEAN, so only the low byte is meaningful. |
GetFileInformationByHandle | Fills a BY_HANDLE_FILE_INFORMATION record for an open handle. |
SetFileTime | Sets the creation, last-access and last-write times of an open handle. |
GetFinalPathNameByHandleW | Writes the final, resolved path of an open handle: symbolic links followed, short names expanded, case as the filesystem stores it. |
GetTempPathW | Writes the path of the directory designated for temporary files. |
DeleteFileW | Deletes a file, taking a UTF-16 path. |
MoveFileExW | Moves or renames a file or directory, taking UTF-16 paths. |
CopyFileW | Copies a file, taking UTF-16 paths. |
CreateDirectoryW | Creates a directory, taking a UTF-16 path. |
RemoveDirectoryW | Removes an empty directory, taking a UTF-16 path. |
GetFileAttributesW | Reads a file's attributes, taking a UTF-16 path. |
SetFileAttributesW | Sets a file's attributes, taking a UTF-16 path. |
GetCurrentDirectoryW | Reads the current directory into a UTF-16 buffer. |
SetCurrentDirectoryW | Sets the current directory, taking a UTF-16 path. |
FlushFileBuffers | Flushes a file handle's writes to the device. |
SetEndOfFile | Sets the size of a file to the handle's current position. |
WriteConsoleW | Writes a character string to a console screen buffer beginning at the current cursor location. |
ReadConsoleW | Reads UTF-16 from a console input buffer. |
AllocConsole | Allocates a new console for the calling process. |
Beep | Generates simple tones on the speaker. |
CloseHandle | Closes an open object handle. |
CopyFileA | Copies an existing file to a new file. |
CreateDirectoryA | Creates a new directory. |
CreateFileA | Creates or opens a file or I/O device. |
DeleteFileA | Deletes an existing file. |
ExitProcess | Ends the calling process and all its threads. |
FindClose | Closes a file search handle opened by the FindFirstFile, FindFirstFileEx, FindFirstFileNameW,. |
FindFirstFileA | Searches a directory for a file or subdirectory with a name that matches a specific name (or partial name if wildcards are used). |
FindNextFileA | Continues a file search from a previous call to the FindFirstFile, FindFirstFileEx, or FindFirstFileTransacted functions. |
FreeLibrary | Frees the loaded dynamic-link library (DLL) module and, if necessary, decrements its reference count. |
GetConsoleMode | Retrieves the current input or output mode of a console screen buffer. |
GetCommandLineW | Retrieves the command line the process was started with, as one string. |
GetModuleFileNameW | Retrieves the full path of the file a module was loaded from; a null module is the process's executable. |
GetCurrentDirectoryA | Retrieves the current directory. |
GetEnvironmentStringsW | Copies the calling process's environment block. |
GetCurrentProcessId | Retrieves the process identifier of the calling process. |
GetActiveProcessorCount | Retrieves the number of active processors in a processor group, or in all of them. |
GetCurrentThreadId | Retrieves the thread identifier of the calling thread. |
GetFileAttributesA | Retrieves file attributes. |
GetFileSizeEx | Retrieves the size of the specified file. |
GetSystemInfo | Reads what the system reports about the machine, including its page size. |
GetLastError | Retrieves the calling thread's last-error code value. |
GetLocalTime | Retrieves the current local date and time. |
GetProcAddress | Retrieves the address of an exported symbol. |
GetProcessHeap | Retrieves a handle to the default heap of the calling process. |
GetStdHandle | Retrieves a handle to the specified standard device (standard input, standard output, or standard error). |
GetSystemTime | Retrieves the current system date and time in Coordinated Universal Time (UTC) format. |
GetTickCount64 | Retrieves the number of milliseconds that have elapsed since the system was started. |
HeapAlloc | Allocates a block of memory from a heap. |
HeapFree | Frees a memory block allocated from a heap by the HeapAlloc or HeapReAlloc function. |
HeapReAlloc | Reallocates a block of memory from a heap. |
LoadLibraryA | Loads a DLL into the calling process. |
MoveFileA | Moves an existing file or directory. |
MultiByteToWideChar | Maps a character string to a UTF-16 wide character string. |
ReadConsoleA | Reads characters from a console input buffer. |
ReadFile | Reads data from the specified file or input/output (I/O) device. |
RemoveDirectoryA | Deletes an existing empty directory. |
RtlCompareMemory | Compares two blocks of memory and returns the number of bytes that match until the first difference. |
RtlCopyMemory | Copies a block of memory from one location to another. |
RtlFillMemory | Fills a block of memory with the specified fill value. |
RtlZeroMemory | Fills a block of memory with zeros, given a pointer to the block and the length in bytes. |
SetCurrentDirectoryA | Changes the current directory. |
SetFileAttributesA | Sets file attributes. |
SetFilePointerEx | Moves the file pointer of the specified file. |
CreateThread | Creates a thread to execute within the virtual address space of the calling process. |
Sleep | Suspends the execution of the current thread until the time-out interval elapses. |
SwitchToThread | Causes the calling thread to yield execution to another thread that is ready to run. |
WaitForSingleObject | Waits until the specified object is in the signaled state or the time-out interval elapses. |
WideCharToMultiByte | Converts UTF-16 text to another code page. |
WriteConsoleA | Writes a character string to a console screen buffer beginning at the current cursor location. |
WriteFile | Writes data to the specified file or input/output (I/O) device. |
VirtualAlloc | Reserves, commits, or changes the state of a region of pages. |
VirtualFree | Releases, decommits, or both, a region of pages. |
VirtualProtect | Changes the protection on a region of committed pages. |
VirtualLock | Locks a region into physical memory so it is never written to the page file. |
VirtualUnlock | Unlocks a region previously locked into physical memory. |
CreateProcessW | Starts a program as a new process. |
GetExitCodeProcess | Reads a process's exit code, or STILL_ACTIVE while it runs. |
TerminateProcess | Ends a process and all its threads. |
CreatePipe | Creates an anonymous pipe. |
SetHandleInformation | Changes a handle's flags, such as whether it is inherited. |
DuplicateHandle | Duplicates a handle, here into the same process with different inheritance. |
GetCurrentProcess | Returns a pseudo-handle for the calling process, which needs no closing. |
SetEnvironmentVariableW | Sets or removes an environment variable of the calling process. |
CommandLineToArgvW | Splits a command line into arguments the way the C runtime does. |
WaitOnAddress | Waits for the value at an address to change. |
WakeByAddressSingle | Wakes one thread waiting on an address. |
WakeByAddressAll | Wakes every thread waiting on an address. |
GetTimeZoneInformation | Reads the system's current time zone. |
WSAStartup | Starts Winsock for this process. |
WSAGetLastError | The calling thread's last Winsock error. |
socket | Opens a socket. |
connect | Connects a socket to address. |
bind | Gives a socket its local address. |
listen | Makes a bound stream socket accept connections. |
accept | Accepts a waiting connection. |
sendto | Sends bytes on a socket, to address when it is not connected. |
recvfrom | Receives bytes from a socket, and where they came from. |
closesocket | Closes a socket. |
shutdown | Ends one or both directions of a connection. |
setsockopt | Sets a socket option. |
getsockname | Reads a socket's local address. |
getpeername | Reads the address of a connected socket's peer. |
getaddrinfo | Looks up the addresses of a host and service. |
freeaddrinfo | Frees the results of getaddrinfo. |
ioctlsocket | Sets a socket's mode, such as non-blocking with FIONBIO. |
WSAPoll | Waits until one of count sockets is ready or timeout milliseconds pass, filling each one's returned. |
Constants
| Name | Summary |
|---|---|
FileTimeTicksPerSecond | How many FileTime ticks make one second. |
FileTimeToUnixEpochSeconds | Seconds between the FileTime epoch of 1601 and the Unix epoch of 1970. |
ALL_PROCESSOR_GROUPS | ALL_PROCESSOR_GROUPS: asks GetActiveProcessorCount about every processor group at once. |
STACK_SIZE_PARAM_IS_A_RESERVATION | STACK_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. |
INFINITE | INFINITE: a wait with no time-out. |
BCRYPT_USE_SYSTEM_PREFERRED_RNG | BCRYPT_USE_SYSTEM_PREFERRED_RNG: draw from the system's preferred generator rather than a named algorithm. |
STATUS_SUCCESS | STATUS_SUCCESS: the status an NtStatus-reporting call gives when it worked. |
ERROR_SUCCESS | ERROR_SUCCESS: the operation succeeded, which is the value GetLastError reports when nothing has failed. |
ERROR_FILE_NOT_FOUND | ERROR_FILE_NOT_FOUND: the named file does not exist. |
ERROR_PATH_NOT_FOUND | ERROR_PATH_NOT_FOUND: a directory along the path does not exist. |
ERROR_ACCESS_DENIED | ERROR_ACCESS_DENIED: the caller does not have the rights the operation needs. |
ERROR_INVALID_HANDLE | ERROR_INVALID_HANDLE: the handle is not one this operation can use. |
ERROR_NOT_ENOUGH_MEMORY | ERROR_NOT_ENOUGH_MEMORY: not enough storage to complete the operation. |
ERROR_OUTOFMEMORY | ERROR_OUTOFMEMORY: not enough storage to complete the operation. |
ERROR_NOT_SUPPORTED | ERROR_NOT_SUPPORTED: the operation is not supported on this object or this system. |
ERROR_FILE_EXISTS | ERROR_FILE_EXISTS: the file already exists, and the call was told not to replace it. |
ERROR_INVALID_PARAMETER | ERROR_INVALID_PARAMETER: an argument is not valid. |
ERROR_DISK_FULL | ERROR_DISK_FULL: the volume has no room left. |
ERROR_PRIVILEGE_NOT_HELD | ERROR_PRIVILEGE_NOT_HELD: the account lacks a privilege the operation requires. |
ERROR_NO_MORE_FILES | ERROR_NO_MORE_FILES: a directory enumeration has handed over its last entry. |
ERROR_ALREADY_EXISTS | ERROR_ALREADY_EXISTS: the object already exists. |
ERROR_INVALID_ADDRESS | ERROR_INVALID_ADDRESS: the address is not one the operation can use. |
ERROR_COMMITMENT_LIMIT | ERROR_COMMITMENT_LIMIT: the system's commit limit is reached, so nothing more can be backed. |
GENERIC_READ | GENERIC_READ: the handle may read. |
GENERIC_WRITE | GENERIC_WRITE: the handle may write. |
FILE_APPEND_DATA | FILE_APPEND_DATA: the handle may append, and only append. |
FILE_SHARE_READ | FILE_SHARE_READ: other openers may read while this handle is open. |
FILE_SHARE_WRITE | FILE_SHARE_WRITE: other openers may write while this handle is open. |
FILE_SHARE_DELETE | FILE_SHARE_DELETE: the file may be renamed or deleted while this handle is open. |
FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_NORMAL: no attributes beyond being an ordinary file. |
FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_READONLY: the file may not be opened for writing or deleted. |
FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DIRECTORY: the name is a directory. |
FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_REPARSE_POINT: the name carries a reparse point, which is what a symbolic link is. |
INVALID_FILE_ATTRIBUTES | INVALID_FILE_ATTRIBUTES: what GetFileAttributesW returns when it could not answer. |
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_BACKUP_SEMANTICS: let CreateFileW open a directory. |
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_OPEN_REPARSE_POINT: open the symbolic link itself rather than what it points at. |
FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_DELETE_ON_CLOSE: remove the file when its last handle closes. |
FILE_FLAG_WRITE_THROUGH | FILE_FLAG_WRITE_THROUGH: writes reach the device before the call returns. |
SYMBOLIC_LINK_FLAG_DIRECTORY | SYMBOLIC_LINK_FLAG_DIRECTORY: the link's target is a directory. |
SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE: let a Developer Mode machine create the link without the privilege older systems demand. |
MOVEFILE_REPLACE_EXISTING | MOVEFILE_REPLACE_EXISTING: let the move overwrite an existing target. |
MOVEFILE_WRITE_THROUGH | MOVEFILE_WRITE_THROUGH: do not return until the move has reached the disk. |
MEM_COMMIT | MEM_COMMIT: back the range with storage. |
MEM_RESERVE | MEM_RESERVE: take the address space without backing it. |
MEM_RESET | MEM_RESET: the contents are no longer of interest and need not be written to the page file. |
MEM_RELEASE | MEM_RELEASE: give back the whole reservation, which VirtualFree requires a size of zero for. |
MEM_DECOMMIT | MEM_DECOMMIT: take back the storage but keep the reservation. |
PAGE_NOACCESS | PAGE_NOACCESS: the pages may not be touched at all. |
PAGE_READONLY | PAGE_READONLY: the pages may be read. |
PAGE_READWRITE | PAGE_READWRITE: the pages may be read and written. |
PAGE_EXECUTE | PAGE_EXECUTE: the pages may be executed. |
PAGE_EXECUTE_READ | PAGE_EXECUTE_READ: the pages may be executed and read. |
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READWRITE: the pages may be executed, read and written. |
PAGE_GUARD | PAGE_GUARD: the next touch raises a one-shot guard exception and then clears the flag. |
STARTF_USESTDHANDLES | STARTF_USESTDHANDLES: the standard handles in StartupInfo are the child's. |
CREATE_UNICODE_ENVIRONMENT | CREATE_UNICODE_ENVIRONMENT: the environment block is UTF-16. |
HANDLE_FLAG_INHERIT | HANDLE_FLAG_INHERIT: the handle is inherited by child processes. |
DUPLICATE_SAME_ACCESS | DUPLICATE_SAME_ACCESS: a duplicated handle has the access of the original. |
WAIT_TIMEOUT | WAIT_TIMEOUT: a wait ended because its time ran out. |
ERROR_BROKEN_PIPE | ERROR_BROKEN_PIPE: the other end of the pipe was closed. |
InvalidHandleValue | The value a handle-returning call reports failure with. |
StdInputHandle | The public StdInputHandle value. |
StdOutputHandle | The public StdOutputHandle value. |
StdErrorHandle | The public StdErrorHandle value. |
AF_INET | AF_INET: the IPv4 address family. |
AF_INET6 | AF_INET6: the IPv6 address family. |
SOCK_STREAM | SOCK_STREAM: a connected byte stream. |
SOCK_DGRAM | SOCK_DGRAM: individual datagrams. |
SOL_SOCKET | SOL_SOCKET: the level of the options every socket has. |
SO_RCVTIMEO | SO_RCVTIMEO: how long a receive waits, in milliseconds. |
SO_SNDTIMEO | SO_SNDTIMEO: how long a send waits, in milliseconds. |
IPPROTO_TCP | IPPROTO_TCP: the level of TCP's options. |
TCP_NODELAY | TCP_NODELAY: send small writes at once rather than gathering them. |
IPPROTO_IPV6 | IPPROTO_IPV6: the level of IPv6's options. |
IPV6_V6ONLY | IPV6_V6ONLY: accept only IPv6 on an IPv6 socket. |
INVALID_SOCKET | INVALID_SOCKET: what a call that makes a socket returns on failure. |
FIONBIO | FIONBIO: the ioctlsocket command that turns a socket's non-blocking mode on or off. |
POLLRDNORM | POLLRDNORM: WSAPoll reports a socket with data to read, or a connection to accept. |
POLLWRNORM | POLLWRNORM: WSAPoll reports a socket a write would not wait on. |
POLLERR | POLLERR: the socket has an error pending; always reported. |
POLLHUP | POLLHUP: the connection was closed; always reported. |
POLLNVAL | POLLNVAL: the socket is not valid; always reported. |