allocator: AllocatorThread-safe.
Used for:
Io.Future and Io.Group closures.mutex: Io.Mutex = .initcond: Io.Condition = .initrun_queue: std.SinglyLinkedList = .{}join_requested: bool = falsestack_size: usizewait_group: WaitGroup = .initAll threads are spawned detached; this is how we wait until they all exit.
async_limit: Io.Limitconcurrent_limit: Io.Limit = .unlimitedcpu_count_error: ?std.Thread.CpuCountErrorError from calling std.Thread.getCpuCount in init.
busy_count: usize = 0Number of threads that are unavailable to take tasks. To calculate available count, subtract this from either async_limit or concurrent_limit.
worker_threads: std.atomic.Value(?*Thread)pid: Pid = .unknownhave_signal_handler: boolold_sig_io: if (have_sig_io) posix.Sigaction else voidold_sig_pipe: if (have_sig_pipe) posix.Sigaction else voiduse_sendfile: UseSendfile = .defaultuse_copy_file_range: UseCopyFileRange = .defaultuse_fcopyfile: UseFcopyfile = .defaultuse_fchmodat2: UseFchmodat2 = .defaultdisable_memory_mapping: boolstderr_writer: File.Writer = .{ .io = undefined, .interface = File.Writer.initInterface(&.{}), .file = if (is_windows) undefined else .stderr(), .mode = .streaming, }stderr_mode: Io.Terminal.Mode = .no_colorstderr_writer_initialized: bool = falsestderr_mutex: Io.Mutex = .initstderr_mutex_locker: std.Thread.Id = Thread.invalid_idstderr_mutex_lock_count: usize = 0argv0: Argv0environ_initialized: boolProtected by mutex. Determines whether environ has been memoized based on process_environ.
environ: Environdl: Dl = .initnull_file: NullFile = .{}random_file: RandomFile = .{}pipe_file: PipeFile = .{}csprng: Csprng = .uninitializedsystem_basic_information: SystemBasicInformation = .{}Happens to be the same number that matches maximum number of handles that NtWaitForMultipleObjects accepts. We use this value also for poll() on posix systems.
There are multiple kernel bugs being worked around with retries.
Statically initialize such that calls to Io.VTable.concurrent will fail with error.ConcurrencyUnavailable.
When initialized this way:
deinit is safe, but unnecessary to call.In general, the application is responsible for choosing the Io implementation and library code should accept an Io parameter rather than accessing this declaration. Most code should avoid referencing this declaration entirely.
However, in some cases such as debugging, it is desirable to hardcode a reference to this Io implementation.
This instance does not support concurrency or cancelation.
This is either usize or u32. Since, either is fine, let's use the same addBuf function for both writing to a file and sending network messages.
Darwin XNU 7195.50.7.100.1 introduced __ulock_wait2 and migrated code paths (notably pthread_cond_t) towards it: https://github.com/apple/darwin-xnu/commit/d4061fb0260b3ed486147341b72468f836ed6c8f#diff-08f993cc40af475663274687b7c326cc6c3031e0db3ac8de7b24624610616be6
This XNU version appears to correspond to 11.0.1: https://kernelshaman.blogspot.com/2021/01/building-xnu-for-macos-big-sur-1101.html
ulock_wait() uses 32-bit micro-second timeouts where 0 = INFINITE or no-timeout ulock_wait2() uses 64-bit nano-second timeouts (with the same convention)
Errors that can occur between fork() and execv()
The API on NetBSD and Illumos sucks and can unpark spuriously (well, it can't, but signals cause an indistinguishable unblock, and libpthread really likes to leave unparks pending). As such, on these targets only, we need to pass around a flag to track whether a thread is "actually" being unparked.
The type passed into unpark for the thread ID. You'd think this was just a std.Thread.Id, but it seems that someone at Microsoft forgot how big their TIDs are supposed to be.
pub fn assert(ok: bool) voidInvokes detectable illegal behavior when ok is false.
In debug and safe modes, calls to this function are always generated, and the unreachable statement triggers a panic.
In fast and small modes, calls to this function are optimized away, and in fact the optimizer is able to use the assertion in its heuristics.
Inside a test block, it is best to use the testing module rather than this function, because this function may not detect a test failure in fast and small mode. Outside of a test block, this assert function is the correct function to use.
pub fn waitForApcOrAlert() voidpub fn init(/// Must be threadsafe. Only used for the following functions: /// * `Io.VTable.async` /// * `Io.VTable.concurrent` /// * `Io.VTable.groupAsync` /// * `Io.VTable.groupConcurrent` /// If these functions are avoided, then `Allocator.failing` may be passed /// here. gpa: Allocator, options: InitOptions) ThreadedRelated:
pub fn setAsyncLimit(t: *Threaded, new_limit: Io.Limit) voidpub fn deinit(t: *Threaded) voidfn join(t: *Threaded) voidfn worker(t: *Threaded) voidpub fn io(t: *Threaded) Iofn crashHandler(userdata: ?*anyopaque) voidfn async(userdata: ?*anyopaque, result: []u8, result_alignment: Alignment, context: []const u8, context_alignment: Alignment, start: *const fn(context: *const anyopaque, result: *anyopaque) void) ?*Io.AnyFuturefn concurrent(userdata: ?*anyopaque, result_len: usize, result_alignment: Alignment, context: []const u8, context_alignment: Alignment, start: *const fn(context: *const anyopaque, result: *anyopaque) void) Io.ConcurrentError!*Io.AnyFuturefn groupAsync(userdata: ?*anyopaque, type_erased: *Io.Group, context: []const u8, context_alignment: Alignment, start: *const fn(context: *const anyopaque) void) voidfn groupAsyncEager(start: *const fn(context: *const anyopaque) void, context: *const anyopaque) voidfn groupConcurrent(userdata: ?*anyopaque, type_erased: *Io.Group, context: []const u8, context_alignment: Alignment, start: *const fn(context: *const anyopaque) void) Io.ConcurrentError!voidfn groupAwait(userdata: ?*anyopaque, type_erased: *Io.Group, initial_token: *anyopaque) Io.Cancelable!voidfn groupCancel(userdata: ?*anyopaque, type_erased: *Io.Group, initial_token: *anyopaque) voidfn recancel(userdata: ?*anyopaque) voidfn recancelInner() voidfn swapCancelProtection(userdata: ?*anyopaque, new: Io.CancelProtection) Io.CancelProtectionfn checkCancel(userdata: ?*anyopaque) Io.Cancelable!voidfn await(userdata: ?*anyopaque, any_future: *Io.AnyFuture, result: []u8, result_alignment: Alignment) voidfn cancel(userdata: ?*anyopaque, any_future: *Io.AnyFuture, result: []u8, result_alignment: Alignment) voidfn futexWait(userdata: ?*anyopaque, ptr: *const u32, expected: u32, timeout: Io.Timeout) Io.Cancelable!voidfn futexWaitUncancelable(userdata: ?*anyopaque, ptr: *const u32, expected: u32) voidfn futexWake(userdata: ?*anyopaque, ptr: *const u32, max_waiters: u32) voidfn operate(userdata: ?*anyopaque, operation: Io.Operation) Io.Cancelable!Io.Operation.Resultfn batchAwaitAsync(userdata: ?*anyopaque, b: *Io.Batch) Io.Cancelable!voidfn batchAwaitConcurrent(userdata: ?*anyopaque, b: *Io.Batch, timeout: Io.Timeout) Io.Batch.AwaitConcurrentError!voidfn batchCancel(userdata: ?*anyopaque, b: *Io.Batch) voidfn batchCompleteBlockingWindows(b: *Io.Batch, operation_userdata: *WindowsBatchOperationUserdata, result: Io.Operation.Result) voidfn batchApc(apc_context: ?*anyopaque, iosb: *windows.IO_STATUS_BLOCK, _: windows.ULONG) align(apc_align) callconv(.winapi) voidfn batchDrainSubmittedWindows(t: *Threaded, b: *Io.Batch, concurrency: bool) (Io.ConcurrentError || Io.Cancelable)!voidIf concurrency is false, error.ConcurrencyUnavailable is unreachable.
fn windowsWriteBuffer(header: []const u8, data: []const []const u8, splat: usize) []const u8Since Windows only supports writing one contiguous buffer, returns the first one, while also limiting it to a length representable by 32-bit unsigned integer.
fn submitComplete(ring: []u32, complete_tail: *Io.Batch.RingIndex, op: u32) voidfn dirCreateDirPosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirError!voidfn dirCreateDirWasi(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirError!voidfn dirCreateDirWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirError!voidfn dirCreateDirPath(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirPathError!Dir.CreatePathStatusfn dirCreateDirPathOpenPosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions, options: Dir.OpenOptions) Dir.CreateDirPathOpenError!Dirfn dirCreateDirPathOpenWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions, options: Dir.OpenOptions) Dir.CreateDirPathOpenError!Dirfn dirCreateDirPathOpenWasi(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions, options: Dir.OpenOptions) Dir.CreateDirPathOpenError!Dirfn dirStat(userdata: ?*anyopaque, dir: Dir) Dir.StatError!Dir.Statfn dirStatFileLinux(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.StatFileOptions) Dir.StatFileError!File.Statfn dirStatFilePosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.StatFileOptions) Dir.StatFileError!File.Statfn posixStatFile(dir_fd: posix.fd_t, sub_path: [: 0]const u8, flags: u32) Dir.StatFileError!File.Statfn dirStatFileWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.StatFileOptions) Dir.StatFileError!File.Statfn dirStatFileWasi(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.StatFileOptions) Dir.StatFileError!File.Statfn filePathKind(t: *Threaded, dir: Dir, sub_path: []const u8) !File.Kindfn fileLength(userdata: ?*anyopaque, file: File) File.LengthError!u64fn fileStatPosix(userdata: ?*anyopaque, file: File) File.StatError!File.Statfn fileStatLinux(userdata: ?*anyopaque, file: File) File.StatError!File.Statfn fileStatWindows(userdata: ?*anyopaque, file: File) File.StatError!File.Statfn systemBasicInformation(t: *Threaded) ?*const windows.SYSTEM.BASIC_INFORMATIONfn fileStatWasi(userdata: ?*anyopaque, file: File) File.StatError!File.Statfn dirAccessPosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.AccessOptions) Dir.AccessError!voidfn dirAccessWasi(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.AccessOptions) Dir.AccessError!voidfn dirAccessWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.AccessOptions) Dir.AccessError!voidfn dirCreateFilePosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.CreateFileOptions) File.OpenError!Filefn dirCreateFileWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, flags: Dir.CreateFileOptions) File.OpenError!Filefn dirCreateFileWasi(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, flags: Dir.CreateFileOptions) File.OpenError!Filefn dirCreateFileAtomic(userdata: ?*anyopaque, dir: Dir, dest_path: []const u8, options: Dir.CreateFileAtomicOptions) Dir.CreateFileAtomicError!File.Atomicfn atomicFileInit(t_io: Io, dest_basename: []const u8, permissions: File.Permissions, dir: Dir, close_dir_on_deinit: bool) Dir.CreateFileAtomicError!File.Atomicfn dirOpenFilePosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.OpenFileOptions) File.OpenError!Filefn dirOpenFileWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, flags: Dir.OpenFileOptions) File.OpenError!Filepub fn dirOpenFileWtf16(dir_handle: ?windows.HANDLE, sub_path_w: []const u16, flags: Dir.OpenFileOptions) File.OpenError!Filefn dirOpenFileWasi(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, flags: Dir.OpenFileOptions) File.OpenError!Filefn dirOpenDirPosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.OpenOptions) Dir.OpenError!DirThis function is also used for WASI when libc is linked.
fn dirOpenDirHaiku(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.OpenOptions) Dir.OpenError!Dirpub fn dirOpenDirWindows(dir: Dir, sub_path_w: []const u16, options: Dir.OpenOptions) Dir.OpenError!Dirfn dirClose(userdata: ?*anyopaque, dirs: []const Dir) voidfn dirReadLinux(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usizefn dirReadDarwin(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usizefn dirReadBsd(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usizefn dirReadIllumos(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usizefn dirReadHaiku(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usizefn dirReadWindows(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usizefn dirReadWasi(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usizefn dirReadUnimplemented(userdata: ?*anyopaque, dir_reader: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usizefn dirRealPathFileWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, out_buffer: []u8) Dir.RealPathFileError!usizefn realPathWindows(h_file: windows.HANDLE, out_buffer: []u8) File.RealPathError!usizefn realPathWindowsBuf(h_file: windows.HANDLE, out_buffer: []u8, wtf16_buffer: []u16) File.RealPathError!usizepub fn GetFinalPathNameByHandle(hFile: windows.HANDLE, fmt: GetFinalPathNameByHandleFormat, out_buffer: []u16) GetFinalPathNameByHandleError![]u16Returns canonical (normalized) path of handle. Use GetFinalPathNameByHandleFormat to specify whether the path is meant to include NT or DOS volume name (e.g., \Device\HarddiskVolume0\foo.txt versus C:\foo.txt). If DOS volume name format is selected, note that this function does not prepend \\?\ prefix to the resultant path.
fn mountmgrIsVolumeName(name: []const u16) boolEquivalent to the MOUNTMGR_IS_VOLUME_NAME macro in mountmgr.h
pub fn QueryObjectName(handle: windows.HANDLE, out_buffer: []u16) QueryObjectNameError![]u16pub fn wToPrefixedFileW(dir: ?windows.HANDLE, path: [: 0]const u16, options: Wtf16ToPrefixedFileWOptions) Wtf16ToPrefixedFileWError!WindowsPathSpaceConverts the path to WTF16, null-terminated. If the path contains any namespace prefix, or is anything but a relative path (rooted, drive relative, etc) the result will have the NT-style prefix \??\.
Similar to RtlDosPathNameToNtPathName_U with a few differences:
dir if it is non-null, or the CWD if it is null.fn getLocalDevicePathType(comptime T: type, path: []const T) LocalDevicePathTypeOnly relevant for Win32 -> NT path conversion. Asserts path is of type Dir.path.Win32PathType.local_device.
pub fn sliceToPrefixedFileW(dir: ?windows.HANDLE, path: []const u8, options: Wtf16ToPrefixedFileWOptions) Wtf8ToPrefixedFileWError!WindowsPathSpaceSame as wToPrefixedFileW but accepts a WTF-8 encoded path. https://wtf-8.codeberg.page/
fn dirRealPathFilePosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, out_buffer: []u8) Dir.RealPathFileError!usizefn dirRealPathPosix(userdata: ?*anyopaque, dir: Dir, out_buffer: []u8) Dir.RealPathError!usizefn dirRealPathWindows(userdata: ?*anyopaque, dir: Dir, out_buffer: []u8) Dir.RealPathError!usizefn fileRealPathWindows(userdata: ?*anyopaque, file: File, out_buffer: []u8) File.RealPathError!usizefn fileRealPathPosix(userdata: ?*anyopaque, file: File, out_buffer: []u8) File.RealPathError!usizefn realPathPosix(fd: posix.fd_t, out_buffer: []u8) File.RealPathError!usizefn fileHardLink(userdata: ?*anyopaque, file: File, new_dir: Dir, new_sub_path: []const u8, options: File.HardLinkOptions) File.HardLinkError!voidfn linkat(old_dir: posix.fd_t, old_path: [*: 0]const u8, new_dir: posix.fd_t, new_path: [*: 0]const u8, flags: u32) File.HardLinkError!voidfn dirDeleteFileWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteFileError!voidfn dirDeleteFileWasi(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteFileError!voidfn dirDeleteFilePosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteFileError!voidfn dirDeleteDirWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteDirError!voidfn dirDeleteWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, remove_dir: bool) (Dir.DeleteDirError || Dir.DeleteFileError)!voidfn dirDeleteDirWasi(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteDirError!voidfn dirDeleteDirPosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteDirError!voidfn dirRenameWindows(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenameError!voidfn dirRenamePreserve(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenamePreserveError!voidfn dirRenameWindowsInner(old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8, replace_if_exists: bool) Dir.RenamePreserveError!voidfn dirRenameWasi(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenameError!voidfn dirRenamePosix(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenameError!voidfn dirRenamePreserveDarwin(old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenamePreserveError!voidfn dirRenamePreserveLinux(old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenamePreserveError!voidfn renameat(old_dir: posix.fd_t, old_sub_path: [*: 0]const u8, new_dir: posix.fd_t, new_sub_path: [*: 0]const u8) Dir.RenameError!voidfn dirSymLinkWindows(userdata: ?*anyopaque, dir: Dir, target_path: []const u8, sym_link_path: []const u8, flags: Dir.SymLinkFlags) Dir.SymLinkError!voidfn dirSymLinkWasi(userdata: ?*anyopaque, dir: Dir, target_path: []const u8, sym_link_path: []const u8, flags: Dir.SymLinkFlags) Dir.SymLinkError!voidfn dirSymLinkPosix(userdata: ?*anyopaque, dir: Dir, target_path: []const u8, sym_link_path: []const u8, flags: Dir.SymLinkFlags) Dir.SymLinkError!voidfn dirReadLink(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usizefn dirReadLinkWindows(dir: Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usizefn parseReadLinkPath(path: []const u16, is_relative: bool, out_buffer: []u16) errorfn dirReadLinkWasi(dir: Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usizefn dirReadLinkPosix(dir: Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usizefn dirSetPermissionsWindows(userdata: ?*anyopaque, dir: Dir, permissions: Dir.Permissions) Dir.SetPermissionsError!voidfn dirSetPermissionsPosix(userdata: ?*anyopaque, dir: Dir, permissions: Dir.Permissions) Dir.SetPermissionsError!voidfn dirSetFilePermissions(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions, options: Dir.SetFilePermissionsOptions) Dir.SetFilePermissionsError!voidfn posixFchmodat(t: *Threaded, dir_fd: posix.fd_t, path: [*: 0]const u8, mode: posix.mode_t, flags: u32) Dir.SetFilePermissionsError!voidfn fchmodatFallback(dir_fd: posix.fd_t, path: [*: 0]const u8, mode: posix.mode_t) Dir.SetFilePermissionsError!voidfn dirSetOwnerUnsupported(userdata: ?*anyopaque, dir: Dir, owner: ?File.Uid, group: ?File.Gid) Dir.SetOwnerError!voidfn dirSetOwnerPosix(userdata: ?*anyopaque, dir: Dir, owner: ?File.Uid, group: ?File.Gid) Dir.SetOwnerError!voidfn posixFchown(fd: posix.fd_t, uid: posix.uid_t, gid: posix.gid_t) File.SetOwnerError!voidfn dirSetFileOwner(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, owner: ?File.Uid, group: ?File.Gid, options: Dir.SetFileOwnerOptions) Dir.SetFileOwnerError!voidfn fileSyncWindows(userdata: ?*anyopaque, file: File) File.SyncError!voidfn fileSyncPosix(userdata: ?*anyopaque, file: File) File.SyncError!voidfn fileSyncWasi(userdata: ?*anyopaque, file: File) File.SyncError!voidfn fileIsTty(userdata: ?*anyopaque, file: File) Io.Cancelable!boolfn isTty(file: File) Io.Cancelable!boolfn fileEnableAnsiEscapeCodes(userdata: ?*anyopaque, file: File) File.EnableAnsiEscapeCodesError!voidfn fileSupportsAnsiEscapeCodes(userdata: ?*anyopaque, file: File) Io.Cancelable!boolfn supportsAnsiEscapeCodes(t: *Threaded, file: File) Io.Cancelable!boolfn isCygwinPty(file: File) Io.Cancelable!boolfn fileSetLength(userdata: ?*anyopaque, file: File, length: u64) File.SetLengthError!voidfn fileSetOwner(userdata: ?*anyopaque, file: File, owner: ?File.Uid, group: ?File.Gid) File.SetOwnerError!voidfn fileSetPermissions(userdata: ?*anyopaque, file: File, permissions: File.Permissions) File.SetPermissionsError!voidfn setPermissionsPosix(fd: posix.fd_t, mode: posix.mode_t) File.SetPermissionsError!voidfn dirSetTimestamps(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.SetTimestampsOptions) Dir.SetTimestampsError!voidfn fileSetTimestamps(userdata: ?*anyopaque, file: File, options: File.SetTimestampsOptions) File.SetTimestampsError!voidfn fileLock(userdata: ?*anyopaque, file: File, lock: File.Lock) File.LockError!voidfn fileTryLock(userdata: ?*anyopaque, file: File, lock: File.Lock) File.LockError!boolfn fileUnlock(userdata: ?*anyopaque, file: File) voidfn fileDowngradeLock(userdata: ?*anyopaque, file: File) File.DowngradeLockError!voidfn dirOpenDirWasi(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.OpenOptions) Dir.OpenError!Dirfn dirHardLink(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8, options: Dir.HardLinkOptions) Dir.HardLinkError!voidfn fileClose(userdata: ?*anyopaque, files: []const File) voidfn fileReadStreaming(userdata: ?*anyopaque, file: File, data: []const []u8) File.ReadStreamingError!usizefn fileReadStreamingPosix(file: File, data: []const []u8) File.ReadStreamingError!usizefn fileReadStreamingWindows(file: File, data: []const []u8) File.ReadStreamingError!usizefn flagApc(userdata: ?*anyopaque, _: *windows.IO_STATUS_BLOCK, _: windows.ULONG) align(apc_align) callconv(.winapi) voidfn ntReadFileResult(io_status_block: *const windows.IO_STATUS_BLOCK) !usizefn ntWriteFileResult(io_status_block: *const windows.IO_STATUS_BLOCK) !usizefn fileReadPositionalPosix(file: File, data: []const []u8, offset: u64) File.ReadPositionalError!usizefn fileReadPositional(userdata: ?*anyopaque, file: File, data: []const []u8, offset: u64) File.ReadPositionalError!usizefn fileReadPositionalWindows(file: File, data: []const []u8, offset: u64) File.ReadPositionalError!usizefn readFilePositionalWindows(file: File, buffer: []u8, offset: u64) File.ReadPositionalError!usizefn fileSeekBy(userdata: ?*anyopaque, file: File, offset: i64) File.SeekError!voidfn fileSeekTo(userdata: ?*anyopaque, file: File, offset: u64) File.SeekError!voidfn posixSeekTo(fd: posix.fd_t, offset: u64) File.SeekError!voidfn processExecutableOpen(userdata: ?*anyopaque, flags: Dir.OpenFileOptions) process.OpenExecutableError!Filefn processExecutablePath(userdata: ?*anyopaque, out_buffer: []u8) process.ExecutablePathError!usizefn fileWritePositional(userdata: ?*anyopaque, file: File, header: []const u8, data: []const []const u8, splat: usize, offset: u64) File.WritePositionalError!usizefn writeFilePositionalWindows(file: File, buffer: []const u8, offset: u64) File.WritePositionalError!usizefn fileWriteStreaming(userdata: ?*anyopaque, file: File, header: []const u8, data: []const []const u8, splat: usize) File.Writer.Error!usizefn fileWriteStreamingWindows(file: File, buffer: []const u8) File.Writer.Error!usizefn fileWriteFileStreaming(userdata: ?*anyopaque, file: File, header: []const u8, file_reader: *File.Reader, limit: Io.Limit) File.Writer.WriteFileError!usizefn netWriteFile(userdata: ?*anyopaque, socket_handle: net.Socket.Handle, header: []const u8, file_reader: *File.Reader, limit: Io.Limit) net.Stream.Writer.WriteFileError!usizefn fileWriteFilePositional(userdata: ?*anyopaque, file: File, header: []const u8, file_reader: *File.Reader, limit: Io.Limit, offset: u64) File.WriteFilePositionalError!usizefn nowPosix(clock: Io.Clock) Io.Timestampfn now(userdata: ?*anyopaque, clock: Io.Clock) Io.Timestampfn clockResolution(userdata: ?*anyopaque, clock: Io.Clock) Io.Clock.ResolutionError!Io.Durationfn clockResolutionPosix(clock: Io.Clock) Io.Clock.ResolutionError!Io.Durationfn nowWindows(clock: Io.Clock) Io.Timestampfn nowWasi(clock: Io.Clock) Io.Timestampfn sleep(userdata: ?*anyopaque, timeout: Io.Timeout) Io.Cancelable!voidfn sleepPosix(timeout: Io.Timeout) Io.Cancelable!voidfn sleepWasi(t: *Threaded, timeout: Io.Timeout) Io.Cancelable!voidfn sleepNanosleep(t: *Threaded, timeout: Io.Timeout) Io.Cancelable!voidfn netListenIpPosix(userdata: ?*anyopaque, address: *const IpAddress, options: IpAddress.ListenOptions) IpAddress.ListenError!net.Socketfn netListenIpWindows(userdata: ?*anyopaque, address: *const IpAddress, options: IpAddress.ListenOptions) IpAddress.ListenError!net.Socketfn netListenUnixPosix(userdata: ?*anyopaque, address: *const net.UnixAddress, options: net.UnixAddress.ListenOptions) net.UnixAddress.ListenError!net.Socket.Handlefn netListenUnixWindows(userdata: ?*anyopaque, address: *const net.UnixAddress, options: net.UnixAddress.ListenOptions) net.UnixAddress.ListenError!net.Socket.Handlefn posixBindUnix(fd: posix.socket_t, addr: *const posix.sockaddr, addr_len: posix.socklen_t) !voidfn posixBind(socket_fd: posix.socket_t, addr: *const posix.sockaddr, addr_len: posix.socklen_t) !voidfn posixConnect(socket_fd: posix.socket_t, addr: *const posix.sockaddr, addr_len: posix.socklen_t) !voidfn posixConnectUnix(fd: posix.socket_t, addr: *const posix.sockaddr, addr_len: posix.socklen_t) !voidfn posixGetSockName(socket_fd: posix.fd_t, addr: *posix.sockaddr, addr_len: *posix.socklen_t) !voidfn setSocketOptionPosix(fd: posix.fd_t, level: i32, opt_name: u32, option: u32) !voidfn setSocketOptionAfd(socket: net.Socket.Handle, level: i32, opt_name: u32, opt_val: anytype) !voidfn socketOptionAfd(socket: net.Socket.Handle, mode: windows.AFD.SOCKOPT_INFO.Mode, level: i32, opt_name: u32, opt_val: []u8) !voidfn netConnectIpPosix(userdata: ?*anyopaque, address: *const IpAddress, options: IpAddress.ConnectOptions) IpAddress.ConnectError!net.Socketfn netConnectIpWindows(userdata: ?*anyopaque, address: *const IpAddress, options: IpAddress.ConnectOptions) IpAddress.ConnectError!net.Socketfn netConnectUnixPosix(userdata: ?*anyopaque, address: *const net.UnixAddress) net.UnixAddress.ConnectError!net.Socket.Handlefn netConnectUnixWindows(userdata: ?*anyopaque, address: *const net.UnixAddress) net.UnixAddress.ConnectError!net.Socket.Handlefn netBindIpPosix(userdata: ?*anyopaque, address: *const IpAddress, options: IpAddress.BindOptions) IpAddress.BindError!net.Socketfn netBindIpWindows(userdata: ?*anyopaque, address: *const IpAddress, options: IpAddress.BindOptions) IpAddress.BindError!net.Socketfn openSocketPosix(family: posix.sa_family_t, options: IpAddress.BindOptions) errorfn setCloexec(fd: posix.fd_t) errorfn netSocketCreatePair(userdata: ?*anyopaque, options: net.Socket.CreatePairOptions) net.Socket.CreatePairError![2]net.Socketfn openSocketAfd(family: ws2_32.ADDRESS_FAMILY, options: IpAddress.BindOptions) !net.Socket.Handlefn bindSocketIpAfd(socket_handle: net.Socket.Handle, address: *const IpAddress, mode: windows.AFD.BIND_INFO.MODE) !IpAddressfn bindSocketUnixAfd(socket_handle: net.Socket.Handle, address: *const net.UnixAddress) !voidfn netAcceptPosix(userdata: ?*anyopaque, listen_fd: net.Socket.Handle, options: net.Server.AcceptOptions) net.Server.AcceptError!net.Socketfn netAcceptWindows(userdata: ?*anyopaque, listen_handle: net.Socket.Handle, options: net.Server.AcceptOptions) net.Server.AcceptError!net.Socketfn deferAcceptAfd(t: *Threaded, listen_handle: net.Socket.Handle, info: windows.AFD.LISTEN_RESPONSE_INFO) voidfn netRead(socket_handle: net.Socket.Handle, data: [][]u8) net.Stream.Reader.Error!usizefn netReadPosix(fd: net.Socket.Handle, data: [][]u8) net.Stream.Reader.Error!usizefn netReadWindows(socket_handle: net.Socket.Handle, data: [][]u8) net.Stream.Reader.Error!usizefn netSendOneWindows(t: *Threaded, socket_handle: net.Socket.Handle, message: *net.OutgoingMessage, flags: net.SendFlags) net.Socket.SendError!voidfn netSendOnePosix(t: *Threaded, socket_handle: net.Socket.Handle, message: *net.OutgoingMessage, flags: u32) (net.Socket.SendError || errorfn netSendManyPosix(socket_handle: net.Socket.Handle, messages: []net.OutgoingMessage, flags: u32) (net.Socket.SendError || errorfn netReceivePosix(socket_handle: net.Socket.Handle, message: *net.IncomingMessage, data_buffer: []u8, flags: net.ReceiveFlags, nonblocking: bool) (net.Socket.ReceiveError || errorfn netReceiveOneWindows(t: *Threaded, socket_handle: net.Socket.Handle, message: *net.IncomingMessage, data_buffer: []u8, flags: net.ReceiveFlags) net.Socket.ReceiveError!voidfn netWritePosix(fd: net.Socket.Handle, header: []const u8, data: []const []const u8, splat: usize) net.Stream.Writer.Error!usizefn netWriteWindows(handle: net.Socket.Handle, header: []const u8, data: []const []const u8, splat: usize) net.Stream.Writer.Error!usizefn addAfdBuf(comptime mutability: windows.AFD.Mutability, iovecs: []windows.AFD.WSABUF(mutability), len: *u32, bytes: switch(mutability)fn addBuf(v: []posix.iovec_const, i: *iovlen_t, bytes: []const u8) voidfn netClose(userdata: ?*anyopaque, sockets: []const net.Socket) voidfn netShutdownPosix(userdata: ?*anyopaque, handle: net.Socket.Handle, how: net.ShutdownHow) net.ShutdownError!voidfn netShutdownWindows(userdata: ?*anyopaque, handle: net.Socket.Handle, how: net.ShutdownHow) net.ShutdownError!voidfn netInterfaceNameResolve(userdata: ?*anyopaque, name: *const net.Interface.Name) net.Interface.Name.ResolveError!net.Interfacefn netInterfaceName(userdata: ?*anyopaque, interface: net.Interface) net.Interface.NameError!net.Interface.Namefn netLookup(userdata: ?*anyopaque, host_name: HostName, resolved: *Io.Queue(HostName.LookupResult), options: HostName.LookupOptions) net.HostName.LookupError!voidfn netLookupFallible(t: *Threaded, host_name: HostName, resolved: *Io.Queue(HostName.LookupResult), options: HostName.LookupOptions) (net.HostName.LookupError || Io.QueueClosedError)!voidfn lockStderr(userdata: ?*anyopaque, terminal_mode: ?Io.Terminal.Mode) Io.Cancelable!Io.LockedStderrfn tryLockStderr(userdata: ?*anyopaque, terminal_mode: ?Io.Terminal.Mode) Io.Cancelable!?Io.LockedStderrfn initLockedStderr(t: *Threaded, terminal_mode: ?Io.Terminal.Mode) Io.Cancelable!Io.LockedStderrfn unlockStderr(userdata: ?*anyopaque) voidfn processCurrentPath(userdata: ?*anyopaque, buffer: []u8) process.CurrentPathError!usizefn processSetCurrentDir(userdata: ?*anyopaque, dir: Dir) process.SetCurrentDirError!voidfn processSetCurrentPath(userdata: ?*anyopaque, path: []const u8) process.SetCurrentPathError!voidpub fn posixAddressFamily(a: *const IpAddress) posix.sa_family_tpub fn addressFromPosix(posix_address: *const PosixAddress) IpAddresspub fn addressToPosix(a: *const IpAddress, storage: *PosixAddress) posix.socklen_tfn addressUnixToPosix(a: *const net.UnixAddress, storage: *UnixAddress) posix.socklen_tfn address4FromPosix(in: *const posix.sockaddr.in) net.Ip4Addressfn address6FromPosix(in6: *const posix.sockaddr.in6) net.Ip6Addressfn address4ToPosix(a: net.Ip4Address) posix.sockaddr.infn address6ToPosix(a: *const net.Ip6Address) posix.sockaddr.in6pub fn errnoBug(err: posix.E) Io.UnexpectedErrorpub fn recoverableOsBugDetected() voidpub fn clockToPosix(clock: Io.Clock) posix.clockid_tfn clockToWasi(clock: Io.Clock) std.os.wasi.clockid_tpub fn statFromLinux(stx: *const std.os.linux.Statx) Io.UnexpectedError!File.Statpub fn statxKind(stx_mode: u16) File.Kindpub fn statFromPosix(st: *const posix.Stat) File.Statfn statFromWasi(st: *const std.os.wasi.filestat_t) File.Statpub fn timestampFromPosix(timespec: *const posix.timespec) Io.Timestamppub fn nanosecondsFromPosix(timespec: *const posix.timespec) i96fn timestampToPosix(nanoseconds: i96) posix.timespecpub fn setTimestampToPosix(set_ts: File.SetTimestamp) posix.timespecpub fn pathToPosix(file_path: []const u8, buffer: *[posix.PATH_MAX]u8) Dir.PathNameError![: 0]u8fn lookupDnsSearch(t: *Threaded, host_name: HostName, resolved: *Io.Queue(HostName.LookupResult), options: HostName.LookupOptions) (HostName.LookupError || Io.QueueClosedError)!voidfn lookupDns(t: *Threaded, lookup_canon_name: []const u8, rc: *const HostName.ResolvConf, resolved: *Io.Queue(HostName.LookupResult), options: HostName.LookupOptions) (HostName.LookupError || Io.QueueClosedError)!voidfn lookupHosts(t: *Threaded, host_name: HostName, resolved: *Io.Queue(HostName.LookupResult), options: HostName.LookupOptions) !voidfn lookupHostsReader(t: *Threaded, host_name: HostName, resolved: *Io.Queue(HostName.LookupResult), options: HostName.LookupOptions, reader: *Io.Reader) errorfn writeResolutionQuery(q: *[280]u8, op: u4, dname: []const u8, class: u8, ty: HostName.DnsRecord, entropy: [2]u8) usizeWrites DNS resolution query packet data to w; at most 280 bytes.
fn copyCanon(canonical_name_buffer: ?*[HostName.max_len]u8, name: []const u8) ?HostNamefn doNothingSignalHandler(_: posix.SIG) callconv(.c) voidfn scanEnviron(t: *Threaded) voidfn processReplace(userdata: ?*anyopaque, options: process.ReplaceOptions) process.ReplaceErrorfn processReplacePath(userdata: ?*anyopaque, dir: Dir, options: process.ReplaceOptions) process.ReplaceErrorfn processSpawnPath(userdata: ?*anyopaque, dir: Dir, options: process.SpawnOptions) process.SpawnError!process.Childfn processSpawnUnsupported(userdata: ?*anyopaque, options: process.SpawnOptions) process.SpawnError!process.Childfn spawnPosix(t: *Threaded, options: process.SpawnOptions) process.SpawnError!Spawnedfn getDevNullFd(t: *Threaded) !posix.fd_tfn processSpawnPosix(userdata: ?*anyopaque, options: process.SpawnOptions) process.SpawnError!process.Childfn childWait(userdata: ?*anyopaque, child: *process.Child) process.Child.WaitError!process.Child.Termfn childKill(userdata: ?*anyopaque, child: *process.Child) voidfn childKillWindows(t: *Threaded, child: *process.Child, exit_code: windows.UINT) !voidfn childWaitWindows(child: *process.Child) process.Child.WaitError!process.Child.Termfn childCleanupWindows(child: *process.Child) voidfn childWaitPosix(child: *process.Child) process.Child.WaitError!process.Child.Termpub fn statusToTerm(status: u32) process.Child.Termfn childKillPosix(child: *process.Child) !voidfn childCleanupPosix(child: *process.Child) voidfn forkBail(fd: posix.fd_t, err: ForkBailError) noreturnChild of fork calls this to report an error to the fork parent. Then the child exits.
fn writeIntFd(fd: posix.fd_t, value: ErrInt) !voidfn readIntFd(fd: posix.fd_t) !ErrIntfn destroyPipe(pipe: [2]posix.fd_t) voidfn setUpChildIo(stdio: process.SpawnOptions.StdIo, pipe_fd: i32, std_fileno: i32, dev_null_fd: i32) !voidfn processSpawnWindows(userdata: ?*anyopaque, options: process.SpawnOptions) process.SpawnError!process.Childfn inheritFile() windows.HANDLEfn getCngDevice(t: *Threaded) Io.RandomSecureError!windows.HANDLEfn getNulDevice(t: *Threaded) !windows.HANDLEfn getNamedPipeDevice(t: *Threaded) !windows.HANDLEfn windowsCreateProcessPathExt(arena: Allocator, dir_buf: *std.ArrayList(u16), app_buf: *std.ArrayList(u16), pathext: [: 0]const u16, cmd_line_cache: *WindowsCommandLineCache, env_block: ?process.Environ.WindowsBlock, cwd_ptr: ?[*: 0]u16, flags: windows.CreateProcessFlags, lpStartupInfo: *windows.STARTUPINFOW, lpProcessInformation: *windows.PROCESS.INFORMATION) !voidExpects app_buf to contain exactly the app name, and dir_buf to contain exactly the dir path. After return, app_buf will always contain exactly the app name and dir_buf will always contain exactly the dir path. Note: app_buf should not contain any leading path separators. Note: If the dir is the cwd, dir_buf should be empty (len = 0).
fn windowsCreateProcess(app_name: [*: 0]u16, cmd_line: [*: 0]u16, env_block: ?process.Environ.WindowsBlock, cwd_ptr: ?[*: 0]u16, flags: windows.CreateProcessFlags, lpStartupInfo: *windows.STARTUPINFOW, lpProcessInformation: *windows.PROCESS.INFORMATION) !voidfn windowsCreateProcessSupportsExtension(ext: []const u16) ?process.WindowsExtensionCase-insensitive WTF-16 lookup
fn argvToScriptCommandLineWindows(allocator: Allocator, /// Path to the `.bat`/`.cmd` script. If this path is relative, it is assumed to be relative to the CWD. /// The script must have been verified to exist at this path before calling this function. script_path: []const u16, /// Arguments, not including the script name itself. Expected to be encoded as WTF-8. script_args: []const []const u8) ArgvToScriptCommandLineError![: 0]u16Serializes argv to a Windows command-line string that uses cmd.exe /c and cmd.exe-specific escaping rules. The caller owns the returned slice.
Escapes argv using the suggested mitigation against arbitrary command execution from: https://flatt.tech/research/posts/batbadbut-you-cant-securely-execute-commands-on-windows/
The return of this function will look like cmd.exe /d /e:ON /v:OFF /c "<escaped command line>" and should be used as the lpCommandLine of CreateProcessW, while the return of WindowsCommandLineCache.cmdExePath should be used as lpApplicationName.
Should only be used when spawning .bat/.cmd scripts, see argvToCommandLineWindows otherwise. The .bat/.cmd file must be known to both have the .bat/.cmd extension and exist on the filesystem.
fn argvToCommandLineWindows(allocator: Allocator, argv: []const []const u8) ArgvToCommandLineError![: 0]u16Serializes argv to a Windows command-line string suitable for passing to a child process and parsing by the CommandLineToArgvW algorithm. The caller owns the returned slice.
To avoid arbitrary command execution, this function should not be used when spawning .bat/.cmd scripts. https://flatt.tech/research/posts/batbadbut-you-cant-securely-execute-commands-on-windows/
When executing .bat/.cmd scripts, use argvToScriptCommandLineWindows instead.
fn testArgvToCommandLineWindows(argv: []const []const u8, expected_cmd_line: []const u8) !voidfn posixExecv(arg0_expand: process.ArgExpansion, file: [*: 0]const u8, child_argv: [*: null]?[*: 0]const u8, env_block: process.Environ.PosixBlock, PATH: []const u8) process.ReplaceErrorpub fn posixExecvPath(path: [*: 0]const u8, child_argv: [*: null]const ?[*: 0]const u8, env_block: process.Environ.PosixBlock) process.ReplaceErrorThis function ignores PATH environment variable.
pub fn windowsCreatePipe(t: *Threaded, options: CreatePipeOptions) ![2]windows.HANDLEfn progressParentFile(userdata: ?*anyopaque) std.Progress.ParentFileError!Filepub fn environString(t: *Threaded, comptime name: []const u8) ?[: 0]const u8fn random(userdata: ?*anyopaque, buffer: []u8) voidfn randomMainThread(t: *Threaded, buffer: []u8) voidpub fn fallbackSeed(aslr_addr: ?*anyopaque, seed: *[Csprng.seed_len]u8) voidfn fallbackSeedPosix(seed: *[Csprng.seed_len]u8) voidfn fallbackSeedWindows(seed: *[Csprng.seed_len]u8) voidfn fallbackSeedWasi(seed: *[Csprng.seed_len]u8) voidfn randomSecure(userdata: ?*anyopaque, buffer: []u8) Io.RandomSecureError!voidfn getRandomFd(t: *Threaded) Io.RandomSecureError!posix.fd_tfn timeoutToWindowsInterval(timeout: Io.Timeout) ?windows.LARGE_INTEGERfn setUnparkFlag(f: *UnparkFlag) voidMust be called before unpark. After this function is called, the thread may be unparked at any time, so the caller must not reference values on its stack.
fn getParkTid() ParkTidfn destroyParkSem(_: ?*anyopaque) callconv(.c) voidfn park(timeout: Io.Timeout, /// This value has no semantic effect, but may allow the OS to optimize the operation. addr_hint: ?*const anyopaque, unpark_flag: if(need_unpark_flag) *UnparkFlag else void) errorfn unpark(tids: []const UnparkTid, addr_hint: ?*const anyopaque) voidaddr_hint has no semantic effect, but may allow the OS to optimize this operation.
pub fn pipe2(flags: posix.O) PipeError![2]posix.fd_tpub fn dup2(old_fd: posix.fd_t, new_fd: posix.fd_t) DupError!voidpub fn fchdir(fd: posix.fd_t) FchdirError!voidpub fn chdir(dir_path: []const u8) ChdirError!voidfn fileMemoryMapCreate(userdata: ?*anyopaque, file: File, options: File.MemoryMap.CreateOptions) File.MemoryMap.CreateError!File.MemoryMapfn createFileMap(file: File, protection: std.process.MemoryProtection, offset: u64, populate: bool, len: usize) CreateFileMapError!File.MemoryMapfn fileMemoryMapDestroy(userdata: ?*anyopaque, mm: *File.MemoryMap) voidfn fileMemoryMapSetLength(userdata: ?*anyopaque, mm: *File.MemoryMap, new_len: usize) File.MemoryMap.SetLengthError!voidfn fileMemoryMapRead(userdata: ?*anyopaque, mm: *File.MemoryMap) File.ReadPositionalError!voidfn fileMemoryMapWrite(userdata: ?*anyopaque, mm: *File.MemoryMap) File.WritePositionalError!voidfn mmSyncRead(file: File, memory: []u8, offset: u64) File.ReadPositionalError!voidfn mmSyncWrite(file: File, memory: []u8, offset: u64) File.WritePositionalError!voidfn deviceIoControl(o: *const Io.Operation.DeviceIoControl) Io.Cancelable!Io.Operation.DeviceIoControl.Resultfn eventWait(event: *Io.Event) voidSame as Io.Event.wait but avoids the VTable.
fn eventSet(event: *Io.Event) voidSame as Io.Event.set but avoids the VTable.
fn condBroadcast(cond: *Io.Condition) voidSame as Io.Condition.broadcast but avoids the VTable.
fn condSignal(cond: *Io.Condition) voidSame as Io.Condition.signal but avoids the VTable.
fn condWait(cond: *Io.Condition, mutex: *Io.Mutex) voidSame as Io.Condition.waitUncancelable but avoids the VTable.
pub fn mutexLock(m: *Io.Mutex) voidSame as Io.Mutex.lockUncancelable but avoids the VTable.
pub fn mutexUnlock(m: *Io.Mutex) voidSame as Io.Mutex.unlock but avoids the VTable.
fn OpenFile(sub_path_w: []const u16, options: OpenFileOptions) OpenError!windows.HANDLETODO: inline this logic everywhere and delete this function
pub fn closeFd(fd: posix.fd_t) void1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257const Threaded = @This();
const builtin = @import("builtin");
const native_os = builtin.os.tag;
const is_windows = native_os == .windows;
const is_darwin = native_os.isDarwin();
const is_debug = builtin.mode == .debug;
const std = @import("../std.zig");
const Io = std.Io;
const net = std.Io.net;
const File = std.Io.File;
const Dir = std.Io.Dir;
const HostName = net.HostName;
const IpAddress = net.IpAddress;
const process = std.process;
const Allocator = std.mem.Allocator;
const Alignment = std.mem.Alignment;
const assert = std.debug.assert;
const posix = std.posix;
const windows = std.os.windows;
const ws2_32 = windows.ws2_32;
/// Thread-safe.
///
/// Used for:
/// * allocating `Io.Future` and `Io.Group` closures.
/// * formatting spawning child processes
/// * scanning environment variables on some targets
/// * memory-mapping when mmap or equivalent is not available
allocator: Allocator,
mutex: Io.Mutex = .init,
cond: Io.Condition = .init,
run_queue: std.SinglyLinkedList = .{},
join_requested: bool = false,
stack_size: usize,
/// All threads are spawned detached; this is how we wait until they all exit.
wait_group: WaitGroup = .init,
async_limit: Io.Limit,
concurrent_limit: Io.Limit = .unlimited,
/// Error from calling `std.Thread.getCpuCount` in `init`.
cpu_count_error: ?std.Thread.CpuCountError,
/// Number of threads that are unavailable to take tasks. To calculate
/// available count, subtract this from either `async_limit` or
/// `concurrent_limit`.
busy_count: usize = 0,
worker_threads: std.atomic.Value(?*Thread),
pid: Pid = .unknown,
have_signal_handler: bool,
old_sig_io: if (have_sig_io) posix.Sigaction else void,
old_sig_pipe: if (have_sig_pipe) posix.Sigaction else void,
use_sendfile: UseSendfile = .default,
use_copy_file_range: UseCopyFileRange = .default,
use_fcopyfile: UseFcopyfile = .default,
use_fchmodat2: UseFchmodat2 = .default,
disable_memory_mapping: bool,
stderr_writer: File.Writer = .{
.io = undefined,
.interface = File.Writer.initInterface(&.{}),
.file = if (is_windows) undefined else .stderr(),
.mode = .streaming,
},
stderr_mode: Io.Terminal.Mode = .no_color,
stderr_writer_initialized: bool = false,
stderr_mutex: Io.Mutex = .init,
stderr_mutex_locker: std.Thread.Id = Thread.invalid_id,
stderr_mutex_lock_count: usize = 0,
argv0: Argv0,
/// Protected by `mutex`. Determines whether `environ` has been
/// memoized based on `process_environ`.
environ_initialized: bool,
environ: Environ,
dl: Dl = .init,
null_file: NullFile = .{},
random_file: RandomFile = .{},
pipe_file: PipeFile = .{},
csprng: Csprng = .uninitialized,
system_basic_information: SystemBasicInformation = .{},
const SystemBasicInformation = if (!is_windows) struct {} else struct {
buffer: windows.SYSTEM.BASIC_INFORMATION = undefined,
initialized: std.atomic.Value(bool) = .{ .raw = false },
};
const Dl = switch (native_os) {
.windows => struct {
iphlpapi_dll: std.atomic.Value(?*anyopaque),
ConvertInterfaceNameToLuidW: std.atomic.Value(?*const fn (
InterfaceName: [*:0]const windows.WCHAR,
InterfaceLuid: *windows.NET.LUID,
) callconv(.winapi) windows.Win32Error),
ConvertInterfaceLuidToIndex: std.atomic.Value(?*const fn (
InterfaceLuid: *const windows.NET.LUID,
InterfaceIndex: *windows.NET.IFINDEX,
) callconv(.winapi) windows.Win32Error),
ConvertInterfaceIndexToLuid: std.atomic.Value(?*const fn (
InterfaceIndex: std.os.windows.NET.IFINDEX,
InterfaceLuid: *std.os.windows.NET.LUID,
) callconv(.winapi) windows.Win32Error),
ConvertInterfaceLuidToNameW: std.atomic.Value(?*const fn (
InterfaceLuid: *const std.os.windows.NET.LUID,
InterfaceName: std.os.windows.PWSTR,
Length: std.os.windows.SIZE_T,
) callconv(.winapi) std.os.windows.Win32Error),
dnsapi_dll: std.atomic.Value(?*anyopaque),
DnsQueryEx: std.atomic.Value(?*const fn (
pQueryRequest: *const windows.DNS.QUERY.REQUEST,
pQueryResults: *windows.DNS.QUERY.RESULT,
pCancelHandle: ?*windows.DNS.QUERY.CANCEL,
) callconv(.winapi) windows.DNS.STATUS),
//DnsCancelQuery: std.atomic.Value(?*const fn (
// pCancelHandle: *const windows.DNS.QUERY.CANCEL,
//) callconv(.winapi) windows.DNS.STATUS),
DnsFree: std.atomic.Value(?*const fn (
pRecordList: ?*anyopaque,
FreeType: windows.DNS.FREE_TYPE,
) callconv(.winapi) void),
const init: Dl = .{
.iphlpapi_dll = .init(null),
.ConvertInterfaceNameToLuidW = .init(null),
.ConvertInterfaceLuidToIndex = .init(null),
.ConvertInterfaceIndexToLuid = .init(null),
.ConvertInterfaceLuidToNameW = .init(null),
.dnsapi_dll = .init(null),
.DnsQueryEx = .init(null),
//.DnsCancelQuery = .init(null),
.DnsFree = .init(null),
};
fn deinit(dl: *Dl) void {
if (dl.iphlpapi_dll.raw) |iphlpapi_dll| switch (windows.ntdll.LdrUnloadDll(iphlpapi_dll)) {
.SUCCESS => {},
else => |status| windows.unexpectedStatus(status) catch {},
};
dl.* = .init;
}
},
else => struct {
const init: Dl = .{};
fn deinit(_: Dl) void {}
},
};
pub const Csprng = struct {
rng: std.Random.DefaultCsprng,
pub const uninitialized: Csprng = .{ .rng = .{
.state = undefined,
.offset = std.math.maxInt(usize),
} };
pub const seed_len = std.Random.DefaultCsprng.secret_seed_length;
pub fn isInitialized(c: *const Csprng) bool {
return c.rng.offset != std.math.maxInt(usize);
}
};
pub const Argv0 = switch (native_os) {
.openbsd, .haiku => struct {
value: ?[*:0]const u8,
pub const empty: Argv0 = .{ .value = null };
pub fn init(args: process.Args) Argv0 {
return .{ .value = args.vector[0] };
}
},
else => struct {
pub const empty: Argv0 = .{};
pub fn init(args: process.Args) Argv0 {
_ = args;
return .{};
}
},
};
pub const Environ = struct {
/// Unmodified data directly from the OS.
process_environ: process.Environ,
/// Protected by `mutex`. Memoized based on `process_environ`. Tracks whether the
/// environment variables are present, ignoring their value.
exist: Exist = .{},
/// Protected by `mutex`. Memoized based on `process_environ`.
string: String = .{},
/// ZIG_PROGRESS
zig_progress_file: std.Progress.ParentFileError!File = error.EnvironmentVariableMissing,
/// Protected by `mutex`. Tracks the problem, if any, that occurred when
/// trying to scan environment variables.
///
/// Errors are only possible on WASI.
err: ?Error = null,
pub const empty: Environ = .{ .process_environ = .empty };
pub const Error = Allocator.Error || Io.UnexpectedError;
pub const Exist = struct {
NO_COLOR: bool = false,
CLICOLOR_FORCE: bool = false,
};
pub const String = switch (native_os) {
.windows, .wasi => struct {},
else => struct {
PATH: ?[:0]const u8 = null,
DEBUGINFOD_CACHE_PATH: ?[:0]const u8 = null,
XDG_CACHE_HOME: ?[:0]const u8 = null,
HOME: ?[:0]const u8 = null,
TERM: ?[:0]const u8 = null,
},
};
pub fn scan(environ: *Environ, allocator: Allocator) void {
if (is_windows) {
// This value expires with any call that modifies the environment,
// which is outside of this Io implementation's control, so references
// must be short-lived.
const peb = windows.peb();
assert(windows.ntdll.RtlEnterCriticalSection(peb.FastPebLock) == .SUCCESS);
defer assert(windows.ntdll.RtlLeaveCriticalSection(peb.FastPebLock) == .SUCCESS);
const ptr = peb.ProcessParameters.Environment;
var i: usize = 0;
while (ptr[i] != 0) {
// There are some special environment variables that start with =,
// so we need a special case to not treat = as a key/value separator
// if it's the first character.
// https://devblogs.microsoft.com/oldnewthing/20100506-00/?p=14133
const key_start = i;
if (ptr[i] == '=') i += 1;
while (ptr[i] != 0 and ptr[i] != '=') : (i += 1) {}
const key_w = ptr[key_start..i];
const value_start = i + 1;
while (ptr[i] != 0) : (i += 1) {} // skip over '=' and value
const value_w = ptr[value_start..i];
i += 1; // skip over null byte
if (windows.eqlIgnoreCaseWtf16(key_w, &.{ 'N', 'O', '_', 'C', 'O', 'L', 'O', 'R' })) {
environ.exist.NO_COLOR = true;
} else if (windows.eqlIgnoreCaseWtf16(key_w, &.{ 'C', 'L', 'I', 'C', 'O', 'L', 'O', 'R', '_', 'F', 'O', 'R', 'C', 'E' })) {
environ.exist.CLICOLOR_FORCE = true;
} else if (windows.eqlIgnoreCaseWtf16(key_w, &.{ 'Z', 'I', 'G', '_', 'P', 'R', 'O', 'G', 'R', 'E', 'S', 'S' })) {
environ.zig_progress_file = file: {
var value_buf: [std.fmt.count("{d}", .{std.math.maxInt(usize)})]u8 = undefined;
const len = std.unicode.calcWtf8Len(value_w);
if (len > value_buf.len) break :file error.UnrecognizedFormat;
assert(std.unicode.wtf16LeToWtf8(&value_buf, value_w) == len);
break :file .{
.handle = @ptrFromInt(std.fmt.parseInt(usize, value_buf[0..len], 10) catch
break :file error.UnrecognizedFormat),
.flags = .{ .nonblocking = true },
};
};
}
comptime assert(@sizeOf(String) == 0);
}
} else if (native_os == .wasi and !builtin.link_libc) {
var environ_size: usize = undefined;
var environ_buf_size: usize = undefined;
switch (std.os.wasi.environ_sizes_get(&environ_size, &environ_buf_size)) {
.SUCCESS => {},
else => |err| {
environ.err = posix.unexpectedErrno(err);
return;
},
}
if (environ_size == 0) return;
const wasi_environ = allocator.alloc([*:0]u8, environ_size) catch |err| {
environ.err = err;
return;
};
defer allocator.free(wasi_environ);
const wasi_environ_buf = allocator.alloc(u8, environ_buf_size) catch |err| {
environ.err = err;
return;
};
defer allocator.free(wasi_environ_buf);
switch (std.os.wasi.environ_get(wasi_environ.ptr, wasi_environ_buf.ptr)) {
.SUCCESS => {},
else => |err| {
environ.err = posix.unexpectedErrno(err);
return;
},
}
for (wasi_environ) |env| {
const pair = std.mem.sliceTo(env, 0);
var parts = std.mem.splitScalar(u8, pair, '=');
const key = parts.first();
if (std.mem.eql(u8, key, "NO_COLOR")) {
environ.exist.NO_COLOR = true;
} else if (std.mem.eql(u8, key, "CLICOLOR_FORCE")) {
environ.exist.CLICOLOR_FORCE = true;
}
comptime assert(@sizeOf(String) == 0);
}
} else {
for (environ.process_environ.block.slice) |opt_entry| {
const entry = opt_entry.?;
var entry_i: usize = 0;
while (entry[entry_i] != 0 and entry[entry_i] != '=') : (entry_i += 1) {}
const key = entry[0..entry_i];
var end_i: usize = entry_i;
while (entry[end_i] != 0) : (end_i += 1) {}
const value = entry[entry_i + 1 .. end_i :0];
if (std.mem.eql(u8, key, "NO_COLOR")) {
environ.exist.NO_COLOR = true;
} else if (std.mem.eql(u8, key, "CLICOLOR_FORCE")) {
environ.exist.CLICOLOR_FORCE = true;
} else if (std.mem.eql(u8, key, "ZIG_PROGRESS")) {
environ.zig_progress_file = file: {
break :file .{
.handle = std.fmt.parseInt(u31, value, 10) catch
break :file error.UnrecognizedFormat,
.flags = .{ .nonblocking = true },
};
};
} else inline for (@typeInfo(String).@"struct".field_names) |field_name| {
if (std.mem.eql(u8, key, field_name)) @field(environ.string, field_name) = value;
}
}
}
}
};
pub const NullFile = switch (native_os) {
.windows => struct {
handle: ?windows.HANDLE = null,
fn deinit(this: *@This()) void {
if (this.handle) |handle| {
windows.CloseHandle(handle);
this.handle = null;
}
}
},
.wasi, .ios, .tvos, .visionos, .watchos => struct {
fn deinit(this: @This()) void {
_ = this;
}
},
else => struct {
fd: posix.fd_t = -1,
fn deinit(this: *@This()) void {
if (this.fd >= 0) {
closeFd(this.fd);
this.fd = -1;
}
}
},
};
pub const RandomFile = switch (native_os) {
.windows => NullFile,
else => if (use_dev_urandom) NullFile else struct {
fn deinit(this: @This()) void {
_ = this;
}
},
};
pub const PipeFile = switch (native_os) {
.windows => struct {
handle: ?windows.HANDLE = null,
fn deinit(this: *@This()) void {
if (this.handle) |handle| {
windows.CloseHandle(handle);
this.handle = null;
}
}
},
else => struct {
fn deinit(this: @This()) void {
_ = this;
}
},
};
pub const Pid = if (native_os == .linux) enum(posix.pid_t) {
unknown = 0,
_,
} else enum(u0) { unknown = 0 };
pub const UseSendfile = if (have_sendfile) enum {
enabled,
disabled,
pub const default: UseSendfile = .enabled;
} else enum {
disabled,
pub const default: UseSendfile = .disabled;
};
pub const UseCopyFileRange = if (have_copy_file_range) enum {
enabled,
disabled,
pub const default: UseCopyFileRange = .enabled;
} else enum {
disabled,
pub const default: UseCopyFileRange = .disabled;
};
pub const UseFcopyfile = if (have_fcopyfile) enum {
enabled,
disabled,
pub const default: UseFcopyfile = .enabled;
} else enum {
disabled,
pub const default: UseFcopyfile = .disabled;
};
pub const UseFchmodat2 = if (have_fchmodat2 and !have_fchmodat_flags) enum {
enabled,
disabled,
pub const default: UseFchmodat2 = .enabled;
} else enum {
disabled,
pub const default: UseFchmodat2 = .disabled;
};
pub const apc_align = @max(default_fn_align, 2);
const default_fn_align = switch (builtin.mode) {
.debug, .safe, .fast => switch (builtin.cpu.arch) {
else => |arch| @compileError("Unsupported architecture: " ++ @tagName(arch)),
.arm, .thumb => 4,
.aarch64, .x86, .x86_64 => 16,
},
.small => 1,
};
const Runnable = struct {
node: std.SinglyLinkedList.Node,
startFn: *const fn (*Runnable, *Thread, *Threaded) void,
};
const Group = struct {
ptr: *Io.Group,
/// Returns a correctly-typed pointer to the `Io.Group.token` field.
///
/// The status indicates how many pending tasks are in the group, whether the group has been
/// canceled, and whether the group has been awaited.
///
/// Note that the zero value of `Status` intentionally represents the initial group state (empty
/// with no awaiters). This is a requirement of `Io.Group`.
fn status(g: Group) *std.atomic.Value(Status) {
return @ptrCast(&g.ptr.token);
}
/// Returns a correctly-typed pointer to the `Io.Group.state` field. The double-pointer here is
/// intentional, because the `state` field itself stores a pointer, and this function returns a
/// pointer to that field.
///
/// On completion of the whole group, if `status` indicates that there is an awaiter, the last
/// task must increment this `u32` and do a futex wake on it to signal that awaiter.
fn awaiter(g: Group) **std.atomic.Value(u32) {
return @ptrCast(&g.ptr.state);
}
const Status = packed struct(usize) {
num_running: @Int(.unsigned, @bitSizeOf(usize) - 2),
have_awaiter: bool,
canceled: bool,
};
const Task = struct {
runnable: Runnable,
group: *Io.Group,
func: *const fn (context: *const anyopaque) void,
context_alignment: Alignment,
alloc_len: usize,
/// `Task.runnable.node` is `undefined` in the created `Task`.
fn create(
gpa: Allocator,
group: Group,
context: []const u8,
context_alignment: Alignment,
func: *const fn (context: *const anyopaque) void,
) Allocator.Error!*Task {
const max_context_misalignment = context_alignment.toByteUnits() -| @alignOf(Task);
const worst_case_context_offset = context_alignment.forward(@sizeOf(Task) + max_context_misalignment);
const alloc_len = worst_case_context_offset + context.len;
const task: *Task = @ptrCast(@alignCast(try gpa.alignedAlloc(u8, .of(Task), alloc_len)));
errdefer comptime unreachable;
task.* = .{
.runnable = .{
.node = undefined,
.startFn = &start,
},
.group = group.ptr,
.func = func,
.context_alignment = context_alignment,
.alloc_len = alloc_len,
};
@memcpy(task.contextPointer()[0..context.len], context);
return task;
}
fn destroy(task: *Task, gpa: Allocator) void {
const base: [*]align(@alignOf(Task)) u8 = @ptrCast(task);
gpa.free(base[0..task.alloc_len]);
}
fn contextPointer(task: *Task) [*]u8 {
const base: [*]u8 = @ptrCast(task);
const offset = task.context_alignment.forward(@intFromPtr(base) + @sizeOf(Task)) - @intFromPtr(base);
return base + offset;
}
fn start(r: *Runnable, thread: *Thread, t: *Threaded) void {
const task: *Task = @fieldParentPtr("runnable", r);
const group: Group = .{ .ptr = task.group };
// This would be a simple store, but it's upgraded to an RMW so we can use `.acquire` to
// enforce the ordering between this and the `group.status().load` below. Paired with
// the `.release` rmw on `Thread.status` in `cancelThreads`, this creates a StoreLoad
// barrier which guarantees that when a group is canceled, either we see the cancelation
// in the group status, or the canceler sees our thread status so can directly notify us
// of the cancelation.
_ = thread.status.swap(.{
.cancelation = .none,
.awaitable = .fromGroup(group.ptr),
}, .acquire);
if (group.status().load(.monotonic).canceled) {
thread.status.store(.{
.cancelation = .canceling,
.awaitable = .fromGroup(group.ptr),
}, .monotonic);
}
task.func(task.contextPointer());
thread.status.store(.{ .cancelation = .none, .awaitable = .null }, .monotonic);
const old_status = group.status().fetchSub(.{
.num_running = 1,
.have_awaiter = false,
.canceled = false,
}, .acq_rel); // acquire `group.awaiter()`, release task results
assert(old_status.num_running > 0);
if (old_status.have_awaiter and old_status.num_running == 1) {
const to_signal = group.awaiter().*;
// `awaiter` should only be modified by us. For another thread to see `num_running`
// drop to 0 after this point would indicate that another task started up, meaning
// `async`/`cancel` was racing with awaited group completion.
group.awaiter().* = undefined;
_ = to_signal.fetchAdd(1, .release); // release results
Thread.futexWake(&to_signal.raw, 1);
}
// Task completed. Self-destruct sequence initiated.
task.destroy(t.allocator);
}
};
/// Assumes the caller has already atomically updated the group status to indicate cancelation,
/// and notifies any already-running threads of this cancelation.
fn cancelThreads(g: Group, t: *Threaded) bool {
var any_blocked = false;
var it = t.worker_threads.load(.acquire); // acquire `Thread` values
while (it) |thread| : (it = thread.next) {
// This non-mutating RMW exists for ordering reasons: see comment in `Group.Task.start` for reasons.
_ = thread.status.fetchOr(.{ .cancelation = @fromBackingInt(@intCast(0)), .awaitable = .null }, .release);
if (thread.cancelAwaitable(.fromGroup(g.ptr))) any_blocked = true;
}
return any_blocked;
}
/// Uses `Thread.signalCanceledSyscall` to signal any threads which are still blocked in a
/// syscall for this group and have not observed a cancelation request yet. Returns `true` if
/// more signals may be necessary, in which case the caller must call this again after a delay.
fn signalAllCanceledSyscalls(g: Group, t: *Threaded) bool {
var any_signaled = false;
var it = t.worker_threads.load(.acquire); // acquire `Thread` values
while (it) |thread| : (it = thread.next) {
if (thread.signalCanceledSyscall(t, .fromGroup(g.ptr))) any_signaled = true;
}
return any_signaled;
}
/// The caller has canceled `g`. Inform any threads working on that group of the cancelation if
/// necessary, and wait for `g` to finish (indicated by `num_completed` being incremented from 0
/// to 1), while sending regular signals to threads if necessary for them to unblock from any
/// cancelable syscalls.
///
/// `skip_signals` means it is already known that no threads are currently working on the group
/// so no notifications or signals are necessary.
fn waitForCancelWithSignaling(
g: Group,
t: *Threaded,
num_completed: *std.atomic.Value(u32),
skip_signals: bool,
) void {
var need_signal: bool = !skip_signals and g.cancelThreads(t);
var timeout_ns: u64 = 1 << 10;
while (true) {
need_signal = need_signal and g.signalAllCanceledSyscalls(t);
Thread.futexWaitUncancelable(&num_completed.raw, 0, if (need_signal) timeout_ns else null);
switch (num_completed.load(.acquire)) { // acquire task results
0 => {},
1 => break,
else => unreachable,
}
timeout_ns <<|= 1;
}
}
};
/// Trailing data:
/// 1. context
/// 2. result
const Future = struct {
runnable: Runnable,
func: *const fn (context: *const anyopaque, result: *anyopaque) void,
status: std.atomic.Value(Status),
/// On completion, increment this `u32` and do a futex wake on it.
awaiter: *std.atomic.Value(u32),
context_alignment: Alignment,
result_offset: usize,
alloc_len: usize,
const Status = packed struct(usize) {
/// The values of this enum are chosen so that await/cancel can just OR with 0b01 and 0b11
/// respectively. That *does* clobber `.done`, but that's actually fine, because if the tag
/// is `.done` then only the awaiter is referencing this `Future` anyway.
tag: enum(u2) {
/// The future is queued or running (depending on whether `thread` is set).
pending = 0b00,
/// Like `pending`, but the future is being awaited. `Future.awaiter` is populated.
pending_awaited = 0b01,
/// Like `pending`, but the future is being canceled. `Future.awaiter` is populated.
pending_canceled = 0b11,
/// The future has already completed. `thread` is `.null`, unless the future terminated
/// with an acknowledged cancel request, in which case `thread` is `.all_ones`.
done = 0b10,
},
/// When the future begins execution, this is atomically updated from `null` to the thread running the
/// `Future`, so that cancelation knows which thread to cancel.
thread: Thread.PackedPtr,
};
/// `Future.runnable.node` is `undefined` in the created `Future`.
fn create(
gpa: Allocator,
result_len: usize,
result_alignment: Alignment,
context: []const u8,
context_alignment: Alignment,
func: *const fn (context: *const anyopaque, result: *anyopaque) void,
) Allocator.Error!*Future {
const max_context_misalignment = context_alignment.toByteUnits() -| @alignOf(Future);
const worst_case_context_offset = context_alignment.forward(@sizeOf(Future) + max_context_misalignment);
const worst_case_result_offset = result_alignment.forward(worst_case_context_offset + context.len);
const alloc_len = worst_case_result_offset + result_len;
const future: *Future = @ptrCast(@alignCast(try gpa.alignedAlloc(u8, .of(Future), alloc_len)));
errdefer comptime unreachable;
const actual_context_addr = context_alignment.forward(@intFromPtr(future) + @sizeOf(Future));
const actual_result_addr = result_alignment.forward(actual_context_addr + context.len);
const actual_result_offset = actual_result_addr - @intFromPtr(future);
future.* = .{
.runnable = .{
.node = undefined,
.startFn = &start,
},
.func = func,
.status = .init(.{
.tag = .pending,
.thread = .null,
}),
.awaiter = undefined,
.context_alignment = context_alignment,
.result_offset = actual_result_offset,
.alloc_len = alloc_len,
};
@memcpy(future.contextPointer()[0..context.len], context);
return future;
}
fn destroy(future: *Future, gpa: Allocator) void {
const base: [*]align(@alignOf(Future)) u8 = @ptrCast(future);
gpa.free(base[0..future.alloc_len]);
}
fn resultPointer(future: *Future) [*]u8 {
const base: [*]u8 = @ptrCast(future);
return base + future.result_offset;
}
fn contextPointer(future: *Future) [*]u8 {
const base: [*]u8 = @ptrCast(future);
const context_offset = future.context_alignment.forward(@intFromPtr(future) + @sizeOf(Future)) - @intFromPtr(future);
return base + context_offset;
}
fn start(r: *Runnable, thread: *Thread, t: *Threaded) void {
_ = t;
const future: *Future = @fieldParentPtr("runnable", r);
thread.status.store(.{
.cancelation = .none,
.awaitable = .fromFuture(future),
}, .monotonic);
{
const old_status = future.status.fetchOr(.{
.tag = .pending,
.thread = .pack(thread),
}, .release);
assert(old_status.thread == .null);
switch (old_status.tag) {
.pending, .pending_awaited => {},
.pending_canceled => thread.status.store(.{
.cancelation = .canceling,
.awaitable = .fromFuture(future),
}, .monotonic),
.done => unreachable,
}
}
future.func(future.contextPointer(), future.resultPointer());
const had_acknowledged_cancel = switch (thread.status.load(.monotonic).cancelation) {
.none, .canceling => false,
.canceled => true,
.parked => unreachable,
.blocked => unreachable,
.blocked_alertable => unreachable,
.blocked_alertable_canceling => unreachable,
.blocked_canceling => unreachable,
};
thread.status.store(.{ .cancelation = .none, .awaitable = .null }, .monotonic);
const old_status = future.status.swap(.{
.tag = .done,
.thread = if (had_acknowledged_cancel) .all_ones else .null,
}, .acq_rel); // acquire `future.awaiter`, release results
switch (old_status.tag) {
.pending => {},
.pending_awaited, .pending_canceled => {
const to_signal = future.awaiter;
_ = to_signal.fetchAdd(1, .release); // release results
Thread.futexWake(&to_signal.raw, 1);
},
.done => unreachable,
}
}
/// The caller has canceled `future`. `thread` is the thread currently running that future.
/// Inform `thread` of the cancelation if necessary, and wait for `future` to finish (indicated
/// by `num_completed` being incremented from 0 to 1), while sending regular signals to `thread`
/// if necessary for it to unblock from a cancelable syscall.
fn waitForCancelWithSignaling(
future: *Future,
t: *Threaded,
num_completed: *std.atomic.Value(u32),
thread: ?*Thread,
) void {
var need_signal: bool = if (thread) |th| th.cancelAwaitable(.fromFuture(future)) else false;
var timeout_ns: u64 = 1 << 10;
while (true) {
need_signal = need_signal and thread.?.signalCanceledSyscall(t, .fromFuture(future));
Thread.futexWaitUncancelable(&num_completed.raw, 0, if (need_signal) timeout_ns else null);
switch (num_completed.load(.acquire)) { // acquire task results
0 => {},
1 => break,
else => unreachable,
}
timeout_ns <<|= 1;
}
}
};
/// A sequence of (ptr_bit_width - 3) bits which uniquely identifies a group or future. The bits are
/// the MSBs of the `*Io.Group` or `*Future`. These things do not necessarily have 3 zero bits at
/// the end (they are pointer-aligned, so on 32-bit targets only have 2), but because they both have
/// a *size* of at least 8 bytes, no two groups/futures in memory at the same time will have the
/// same value for all of these bits. In other words, given a group/future pointer, the next group
/// or future must be at least 8 bytes later, so its address will have a different value for one of
/// the top (ptr_bit_width - 3) bits.
const AwaitableId = enum(@Int(.unsigned, @bitSizeOf(usize) - 3)) {
comptime {
assert(@sizeOf(Future) >= 8);
assert(@sizeOf(Io.Group) >= 8);
}
null = 0,
all_ones = std.math.maxInt(@Int(.unsigned, @bitSizeOf(usize) - 3)),
_,
const Split = packed struct(usize) { low: u3, high: AwaitableId };
fn fromGroup(g: *Io.Group) AwaitableId {
const split: Split = @bitCast(@intFromPtr(g));
return split.high;
}
fn fromFuture(f: *Future) AwaitableId {
const split: Split = @bitCast(@intFromPtr(f));
return split.high;
}
};
const Thread = struct {
next: ?*Thread,
id: std.Thread.Id,
handle: Handle,
status: std.atomic.Value(Status),
cancel_protection: Io.CancelProtection,
/// Always released when `Status.cancelation` is set to `.parked`.
futex_waiter: if (use_parking_futex) ?*parking_futex.Waiter else ?noreturn,
unpark_flag: UnparkFlag,
park_tid: if (ParkTid == std.Thread.Id) void else ParkTid,
csprng: Csprng,
const Handle = Handle: {
if (std.Thread.use_pthreads) break :Handle std.c.pthread_t;
if (is_windows) break :Handle windows.HANDLE;
break :Handle void;
};
const Status = packed struct(usize) {
/// The specific values of these enum fields are chosen to simplify the implementation of
/// the transformations we need to apply to this state.
cancelation: enum(u3) {
/// The thread has not yet been canceled, and is not in a cancelable operation.
/// To request cancelation, just set the status to `.canceling`.
none = 0b000,
/// The thread is parked in a cancelable futex wait or sleep.
/// Only applicable if `use_parking_futex` or `use_parking_sleep`.
/// To request cancelation, set the status to `.canceling` and unpark the thread.
/// To unpark for another reason (futex wake), set the status to `.none` and unpark the thread.
parked = 0b001,
/// The thread is blocked in a cancelable system call.
/// To request cancelation, set the status to `.blocked_canceling` and repeatedly interrupt the system call until the status changes.
blocked = 0b011,
/// Windows-only: the thread is blocked in an alertable wait via
/// `NtDelayExecution`. To request cancelation, set the status to
/// `blocked_alertable_canceling` and repeatedly alert the thread
/// until the status changes.
blocked_alertable = 0b010,
/// The thread has an outstanding cancelation request but is not in a cancelable operation.
/// When it acknowledges the cancelation, it will set the status to `.canceled`.
canceling = 0b110,
/// The thread has received and acknowledged a cancelation request.
/// If `recancel` is called, the status will revert to `.canceling`, but otherwise, the status
/// will not change for the remainder of this task's execution.
canceled = 0b111,
/// The thread is blocked in a cancelable system call, and is being
/// canceled. The thread which triggered the cancelation will send
/// signals to this thread until its status changes.
blocked_canceling = 0b101,
/// Windows-only: the thread is blocked in an alertable wait via
/// `NtDelayExecution`, and is being canceled. The thread which
/// triggered the cancelation will send signals to this thread
/// until its status changes.
blocked_alertable_canceling = 0b100,
},
/// We cannot turn this value back into a pointer. Instead, it exists so that a task can be
/// canceled by a cmpxchg on thread status: if it is running the task we want to cancel,
/// then update the `cancelation` field.
awaitable: AwaitableId,
};
const SignaleeId = if (std.Thread.use_pthreads) std.c.pthread_t else std.Thread.Id;
threadlocal var current: ?*Thread = null;
/// A value that does not alias any other thread id.
const invalid_id: std.Thread.Id = std.math.maxInt(std.Thread.Id);
fn currentId() std.Thread.Id {
return if (current) |t| t.id else std.Thread.getCurrentId();
}
/// The thread is neither in a syscall nor entering one, but we want to check for cancelation
/// anyway. If there is a pending cancel request, acknowledge it and return `error.Canceled`.
fn checkCancel() Io.Cancelable!void {
const thread = Thread.current orelse return;
switch (thread.cancel_protection) {
.blocked => return,
.unblocked => {},
}
// Here, unlike `Syscall.checkCancel`, it's not particularly likely that we're canceled, so
// it seems preferable to do a cheap atomic load and, in the unlikely case, a separate store
// to acknowledge. Besides, the state transitions we need here can't be done with one atomic
// OR/AND/XOR on `Status.cancelation`, so we don't actually have any other option.
const status = thread.status.load(.monotonic);
switch (status.cancelation) {
.parked => unreachable,
.blocked => unreachable,
.blocked_alertable => unreachable,
.blocked_alertable_canceling => unreachable,
.blocked_canceling => unreachable,
.none, .canceled => {},
.canceling => {
thread.status.store(.{
.cancelation = .canceled,
.awaitable = status.awaitable,
}, .monotonic);
return error.Canceled;
},
}
}
fn futexWaitUncancelable(ptr: *const u32, expect: u32, timeout_ns: ?u64) void {
return Thread.futexWaitInner(ptr, expect, true, timeout_ns) catch unreachable;
}
fn futexWait(ptr: *const u32, expect: u32, timeout_ns: ?u64) Io.Cancelable!void {
return Thread.futexWaitInner(ptr, expect, false, timeout_ns);
}
fn futexWaitInner(ptr: *const u32, expect: u32, uncancelable: bool, timeout_ns: ?u64) Io.Cancelable!void {
@branchHint(.cold);
if (builtin.single_threaded) unreachable; // nobody would ever wake us
if (use_parking_futex) {
return parking_futex.wait(
ptr,
expect,
uncancelable,
if (timeout_ns) |ns| .{ .duration = .{
.raw = .fromNanoseconds(ns),
.clock = .boot,
} } else .none,
);
} else if (builtin.cpu.arch.isWasm()) {
comptime assert(builtin.cpu.has(.wasm, .atomics));
// TODO implement cancelation for WASM futex waits by signaling the futex
if (!uncancelable) try Thread.checkCancel();
const to: i64 = if (timeout_ns) |ns| std.math.cast(i64, ns) orelse std.math.maxInt(i64) else -1;
const signed_expect: i32 = @bitCast(expect);
const result = asm volatile (
\\local.get %[ptr]
\\local.get %[expected]
\\local.get %[timeout]
\\memory.atomic.wait32 0
\\local.set %[ret]
: [ret] "=r" (-> u32),
: [ptr] "r" (ptr),
[expected] "r" (signed_expect),
[timeout] "r" (to),
);
switch (result) {
0 => {}, // ok
1 => {}, // expected != loaded
2 => {}, // timeout
else => assert(!is_debug),
}
} else switch (native_os) {
.linux => {
const linux = std.os.linux;
var ts_buffer: linux.timespec = undefined;
const ts: ?*linux.timespec = if (timeout_ns) |ns| ts: {
ts_buffer = timestampToPosix(ns);
break :ts &ts_buffer;
} else null;
const syscall: Syscall = if (uncancelable) .{ .thread = null } else try .start();
const rc = linux.futex_4arg(ptr, .{ .cmd = .WAIT, .private = true }, expect, ts);
syscall.finish();
switch (linux.errno(rc)) {
.SUCCESS => {}, // notified by `wake()`
.INTR => {}, // caller's responsibility to retry
.AGAIN => {}, // ptr.* != expect
.INVAL => {}, // possibly timeout overflow
.TIMEDOUT => {},
.FAULT => recoverableOsBugDetected(), // ptr was invalid
else => recoverableOsBugDetected(),
}
},
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
const c = std.c;
const flags: c.UL = .{
.op = .COMPARE_AND_WAIT,
.NO_ERRNO = true,
};
const syscall: Syscall = if (uncancelable) .{ .thread = null } else try .start();
const status = switch (darwin_supports_ulock_wait2) {
true => c.__ulock_wait2(flags, ptr, expect, ns: {
const ns = timeout_ns orelse break :ns 0;
if (ns == 0) break :ns 1;
break :ns ns;
}, 0),
false => c.__ulock_wait(flags, ptr, expect, us: {
const ns = timeout_ns orelse break :us 0;
const us = std.math.lossyCast(u32, ns / std.time.ns_per_us);
if (us == 0) break :us 1;
break :us us;
}),
};
syscall.finish();
if (status >= 0) return;
switch (@as(c.E, @fromBackingInt(@intCast(-status)))) {
.INTR => {}, // spurious wake
// Address of the futex was paged out. This is unlikely, but possible in theory, and
// pthread/libdispatch on darwin bother to handle it. In this case we'll return
// without waiting, but the caller should retry anyway.
.FAULT => {},
.TIMEDOUT => {}, // timeout
else => recoverableOsBugDetected(),
}
},
.freebsd => {
const flags = @backingInt(std.c.UMTX_OP.WAIT_UINT_PRIVATE);
var tm_size: usize = 0;
var tm: std.c._umtx_time = undefined;
var tm_ptr: ?*const std.c._umtx_time = null;
if (timeout_ns) |ns| {
tm_ptr = &tm;
tm_size = @sizeOf(@TypeOf(tm));
tm.flags = 0; // use relative time not UMTX_ABSTIME
tm.clockid = .MONOTONIC;
tm.timeout = timestampToPosix(ns);
}
const syscall: Syscall = if (uncancelable) .{ .thread = null } else try .start();
const rc = std.c._umtx_op(@intFromPtr(ptr), flags, @as(c_ulong, expect), tm_size, @intFromPtr(tm_ptr));
syscall.finish();
if (is_debug) switch (posix.errno(rc)) {
.SUCCESS => {},
.FAULT => unreachable, // one of the args points to invalid memory
.INVAL => unreachable, // arguments should be correct
.TIMEDOUT => {}, // timeout
.INTR => {}, // spurious wake
else => unreachable,
};
},
.openbsd => {
var tm: std.c.timespec = undefined;
var tm_ptr: ?*const std.c.timespec = null;
if (timeout_ns) |ns| {
tm_ptr = &tm;
tm = timestampToPosix(ns);
}
const syscall: Syscall = if (uncancelable) .{ .thread = null } else try .start();
const rc = std.c.futex(
ptr,
std.c.FUTEX.WAIT | std.c.FUTEX.PRIVATE_FLAG,
@as(c_int, @bitCast(expect)),
tm_ptr,
null, // uaddr2 is ignored
);
syscall.finish();
if (is_debug) switch (posix.errno(rc)) {
.SUCCESS => {},
.NOSYS => unreachable, // constant op known good value
.AGAIN => {}, // contents of uaddr != val
.INVAL => unreachable, // invalid timeout
.TIMEDOUT => {}, // timeout
.INTR => {}, // a signal arrived
.CANCELED => {}, // a signal arrived and SA_RESTART was set
else => unreachable,
};
},
.dragonfly => {
var timeout_us: c_int = undefined;
if (timeout_ns) |ns| {
timeout_us = std.math.cast(c_int, ns / std.time.ns_per_us) orelse std.math.maxInt(c_int);
} else {
timeout_us = 0;
}
const syscall: Syscall = if (uncancelable) .{ .thread = null } else try .start();
const rc = std.c.umtx_sleep(@ptrCast(ptr), @bitCast(expect), timeout_us);
syscall.finish();
if (is_debug) switch (std.posix.errno(rc)) {
.SUCCESS => {},
.BUSY => {}, // ptr != expect
.AGAIN => {}, // maybe timed out, or paged out, or hit 2s kernel refresh
.INTR => {}, // spurious wake
.INVAL => unreachable, // invalid timeout
else => unreachable,
};
},
else => @compileError("unimplemented: futexWait"),
}
}
fn futexWake(ptr: *const u32, max_waiters: u32) void {
@branchHint(.cold);
assert(max_waiters != 0);
if (builtin.single_threaded) return; // nothing to wake up
if (use_parking_futex) {
return parking_futex.wake(ptr, max_waiters);
} else if (builtin.cpu.arch.isWasm()) {
comptime assert(builtin.cpu.has(.wasm, .atomics));
const woken_count = asm volatile (
\\local.get %[ptr]
\\local.get %[waiters]
\\memory.atomic.notify 0
\\local.set %[ret]
: [ret] "=r" (-> u32),
: [ptr] "r" (ptr),
[waiters] "r" (max_waiters),
);
_ = woken_count; // can be 0 when linker flag 'shared-memory' is not enabled
} else switch (native_os) {
.linux => {
const linux = std.os.linux;
switch (linux.errno(linux.futex_3arg(
ptr,
.{ .cmd = .WAKE, .private = true },
@min(max_waiters, std.math.maxInt(i32)),
))) {
.SUCCESS => return, // successful wake up
.INVAL => return, // invalid futex_wait() on ptr done elsewhere
.FAULT => return, // pointer became invalid while doing the wake
else => return recoverableOsBugDetected(), // deadlock due to operating system bug
}
},
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
const c = std.c;
const flags: c.UL = .{
.op = .COMPARE_AND_WAIT,
.NO_ERRNO = true,
.WAKE_ALL = max_waiters > 1,
};
while (true) {
const status = c.__ulock_wake(flags, ptr, 0);
if (status >= 0) return;
switch (@as(c.E, @fromBackingInt(@intCast(-status)))) {
.INTR, .CANCELED => continue, // spurious wake()
.FAULT => unreachable, // __ulock_wake doesn't generate EFAULT according to darwin pthread_cond_t
.NOENT => return, // nothing was woken up
.ALREADY => unreachable, // only for UL.Op.WAKE_THREAD
else => unreachable, // deadlock due to operating system bug
}
}
},
.freebsd => {
const rc = std.c._umtx_op(
@intFromPtr(ptr),
@backingInt(std.c.UMTX_OP.WAKE_PRIVATE),
@as(c_ulong, @min(max_waiters, std.math.maxInt(c_int))),
0, // there is no timeout struct
0, // there is no timeout struct pointer
);
switch (posix.errno(rc)) {
.SUCCESS => {},
.FAULT => {}, // it's ok if the ptr doesn't point to valid memory
.INVAL => unreachable, // arguments should be correct
else => unreachable, // deadlock due to operating system bug
}
},
.openbsd => {
const rc = std.c.futex(
ptr,
std.c.FUTEX.WAKE | std.c.FUTEX.PRIVATE_FLAG,
@min(max_waiters, std.math.maxInt(c_int)),
null, // timeout is ignored
null, // uaddr2 is ignored
);
assert(rc >= 0);
},
.dragonfly => {
// will generally return 0 unless the address is bad
_ = std.c.umtx_wakeup(
@ptrCast(ptr),
@min(max_waiters, std.math.maxInt(c_int)),
);
},
else => @compileError("unimplemented: futexWake"),
}
}
/// Cancels `thread` if it is working on `awaitable`.
///
/// It is possible that `thread` gets canceled by this function, but is blocked in a syscall. In
/// that case, the thread may need to be sent a signal to interrupt the call. This function will
/// return `true` to indicate this, in which case the caller must call `signalCanceledSyscall`.
fn cancelAwaitable(thread: *Thread, awaitable: AwaitableId) bool {
var status = thread.status.load(.monotonic);
while (true) {
if (status.awaitable != awaitable) return false; // thread is working on something else
status = switch (status.cancelation) {
.none => thread.status.cmpxchgWeak(
.{ .cancelation = .none, .awaitable = awaitable },
.{ .cancelation = .canceling, .awaitable = awaitable },
.monotonic,
.monotonic,
) orelse return false,
.parked => thread.status.cmpxchgWeak(
.{ .cancelation = .parked, .awaitable = awaitable },
.{ .cancelation = .canceling, .awaitable = awaitable },
.acquire, // acquire `thread.futex_waiter`
.monotonic,
) orelse {
if (!use_parking_futex and !use_parking_sleep) unreachable;
if (thread.futex_waiter) |futex_waiter| {
parking_futex.removeCanceledWaiter(futex_waiter);
}
if (need_unpark_flag) setUnparkFlag(&thread.unpark_flag);
unpark(&.{if (ParkTid == std.Thread.Id) thread.id else thread.park_tid}, null);
return false;
},
.blocked => thread.status.cmpxchgWeak(
.{ .cancelation = .blocked, .awaitable = awaitable },
.{ .cancelation = .blocked_canceling, .awaitable = awaitable },
.monotonic,
.monotonic,
) orelse return true,
.blocked_alertable => thread.status.cmpxchgWeak(
.{ .cancelation = .blocked_alertable, .awaitable = awaitable },
.{ .cancelation = .blocked_alertable_canceling, .awaitable = awaitable },
.monotonic,
.monotonic,
) orelse {
if (!is_windows) unreachable;
return true;
},
.canceling, .canceled => {
// This can happen when the task start raced with the cancelation, so the thread
// saw the cancelation on the future/group *and* we are trying to signal the
// thread here.
return false;
},
.blocked_canceling => unreachable, // `awaitable` has not been canceled before now
.blocked_alertable_canceling => unreachable, // `awaitable` has not been canceled before now
};
}
}
/// Sends a signal to `thread` if it is still blocked in a syscall (i.e. has not yet observed
/// the cancelation request from `cancelAwaitable`).
///
/// Unfortunately, the signal could arrive before the syscall actually starts, so the interrupt
/// is missed. To handle this, we may need to send multiple signals. As such, if this function
/// returns `true`, then it should be called again after a short delay to send another signal if
/// the thread is still blocked. For the implementation, `Future.waitForCancelWithSignaling` and
/// `Group.waitForCancelWithSignaling`: they use exponential backoff starting at a 1us delay and
/// doubling each call. In practice, it is rare to send more than one signal.
fn signalCanceledSyscall(thread: *Thread, t: *Threaded, awaitable: AwaitableId) bool {
const status = thread.status.load(.monotonic);
if (status.awaitable != awaitable) {
// The thread has moved on and is working on something totally different.
return false;
}
// The thread ID and/or handle can be read non-atomically because they never change and were
// released by the store that made `thread` available to us.
switch (status.cancelation) {
.blocked_canceling => if (std.Thread.use_pthreads) {
return switch (std.c.pthread_kill(thread.handle, .IO)) {
0 => true,
else => false,
};
} else switch (native_os) {
.linux => {
const pid: posix.pid_t = pid: {
const cached_pid = @atomicLoad(Pid, &t.pid, .monotonic);
if (cached_pid != .unknown) break :pid @backingInt(cached_pid);
const pid = std.os.linux.getpid();
@atomicStore(Pid, &t.pid, @fromBackingInt(@intCast(pid)), .monotonic);
break :pid pid;
};
return switch (std.os.linux.tgkill(pid, @bitCast(thread.id), .IO)) {
0 => true,
else => false,
};
},
.windows => {
var iosb: windows.IO_STATUS_BLOCK = undefined;
return switch (windows.ntdll.NtCancelSynchronousIoFile(thread.handle, null, &iosb)) {
.NOT_FOUND => true, // this might mean the operation hasn't started yet
.SUCCESS => false, // the OS confirmed that our cancelation worked
else => false,
};
},
else => return false,
},
.blocked_alertable_canceling => {
if (!is_windows) unreachable;
return switch (windows.ntdll.NtAlertThread(thread.handle)) {
.SUCCESS => true,
else => false,
};
},
else => {
// The thread is working on `awaitable`, but no longer needs signaling (they already
// woke up and saw the cancelation).
return false;
},
}
}
/// Like a `*Thread`, but 2 bits smaller than a pointer (because the LSBs are always 0 due to
/// alignment) so that those two bits can be used in a `packed struct`.
const PackedPtr = enum(@Int(.unsigned, @bitSizeOf(usize) - 2)) {
null = 0,
all_ones = std.math.maxInt(@Int(.unsigned, @bitSizeOf(usize) - 2)),
_,
const Split = packed struct(usize) { low: u2, high: PackedPtr };
fn pack(ptr: *Thread) PackedPtr {
const split: Split = @bitCast(@intFromPtr(ptr));
assert(split.low == 0);
return split.high;
}
fn unpack(ptr: PackedPtr) ?*Thread {
const split: Split = .{ .low = 0, .high = ptr };
return @ptrFromInt(@as(usize, @bitCast(split)));
}
};
};
const Syscall = struct {
thread: ?*Thread,
/// Marks entry to a syscall region. This should be tightly scoped around the actual syscall
/// to minimize races. The syscall must be marked as "finished" by `checkCancel`, `finish`,
/// or one of the wrappers of `finish`.
fn start() Io.Cancelable!Syscall {
const thread = Thread.current orelse return .{ .thread = null };
switch (thread.cancel_protection) {
.blocked => return .{ .thread = null },
.unblocked => {},
}
switch (thread.status.fetchOr(.{
.cancelation = @fromBackingInt(@intCast(0b011)),
.awaitable = .null,
}, .monotonic).cancelation) {
.parked => unreachable,
.blocked => unreachable,
.blocked_alertable => unreachable,
.blocked_alertable_canceling => unreachable,
.blocked_canceling => unreachable,
.none => return .{ .thread = thread }, // new status is `.blocked`
.canceling => return error.Canceled, // new status is `.canceled`
.canceled => return .{ .thread = null }, // new status is `.canceled` (unchanged)
}
}
/// Checks whether this syscall has been canceled. This should be called when a syscall is
/// interrupted through a mechanism which may indicate cancelation, or may be spurious. If
/// the syscall was canceled, it is finished and `error.Canceled` is returned. Otherwise,
/// the syscall is not marked finished, and the caller should retry.
fn checkCancel(s: Syscall) Io.Cancelable!void {
const thread = s.thread orelse return;
switch (thread.status.fetchOr(.{
.cancelation = @fromBackingInt(@intCast(0b010)),
.awaitable = .null,
}, .monotonic).cancelation) {
.none => unreachable,
.parked => unreachable,
.blocked_alertable => unreachable,
.blocked_alertable_canceling => unreachable,
.canceling => unreachable,
.canceled => unreachable,
.blocked => {}, // new status is `.blocked` (unchanged)
.blocked_canceling => return error.Canceled, // new status is `.canceled`
}
}
/// Marks this syscall as finished.
fn finish(s: Syscall) void {
const thread = s.thread orelse return;
switch (thread.status.fetchXor(.{
.cancelation = @fromBackingInt(@intCast(0b011)),
.awaitable = .null,
}, .monotonic).cancelation) {
.none => unreachable,
.parked => unreachable,
.blocked_alertable => unreachable,
.blocked_alertable_canceling => unreachable,
.canceling => unreachable,
.canceled => unreachable,
.blocked => {}, // new status is `.none`
.blocked_canceling => {}, // new status is `.canceling`
}
}
/// Indicates instead of `NtCancelSynchronousIoFile` we need to use
/// `NtAlertThread` to interrupt the wait.
///
/// Windows only, called from blocked state only.
fn toAlertable(s: Syscall) Io.Cancelable!AlertableSyscall {
comptime assert(is_windows);
const thread = s.thread orelse return .{ .thread = null };
var prev = thread.status.load(.monotonic);
while (true) prev = switch (prev.cancelation) {
.none => unreachable,
.parked => unreachable,
.blocked_alertable => unreachable,
.blocked_alertable_canceling => unreachable,
.canceling => unreachable,
.canceled => unreachable,
.blocked => thread.status.cmpxchgWeak(prev, .{
.cancelation = .blocked_alertable,
.awaitable = prev.awaitable,
}, .monotonic, .monotonic) orelse return .{ .thread = thread },
.blocked_canceling => thread.status.cmpxchgWeak(prev, .{
.cancelation = .canceled,
.awaitable = prev.awaitable,
}, .monotonic, .monotonic) orelse return error.Canceled,
};
}
/// Convenience wrapper which calls `finish`, then returns `err`.
fn fail(s: Syscall, err: anytype) @TypeOf(err) {
s.finish();
return err;
}
/// Convenience wrapper which calls `finish`, then calls `Threaded.errnoBug`.
fn errnoBug(s: Syscall, err: posix.E) Io.UnexpectedError {
@branchHint(.cold);
s.finish();
return Threaded.errnoBug(err);
}
/// Convenience wrapper which calls `finish`, then calls `posix.unexpectedErrno`.
fn unexpectedErrno(s: Syscall, err: posix.E) Io.UnexpectedError {
@branchHint(.cold);
s.finish();
return posix.unexpectedErrno(err);
}
/// Convenience wrapper which calls `finish`, then calls `windows.statusBug`.
fn ntstatusBug(s: Syscall, status: windows.NTSTATUS) Io.UnexpectedError {
@branchHint(.cold);
s.finish();
return windows.statusBug(status);
}
/// Convenience wrapper which calls `finish`, then calls `windows.unexpectedStatus`.
fn unexpectedNtstatus(s: Syscall, status: windows.NTSTATUS) Io.UnexpectedError {
@branchHint(.cold);
s.finish();
return windows.unexpectedStatus(status);
}
};
const AlertableSyscall = struct {
thread: ?*Thread,
comptime {
assert(is_windows);
}
fn start() Io.Cancelable!AlertableSyscall {
const thread = Thread.current orelse return .{ .thread = null };
switch (thread.cancel_protection) {
.blocked => return .{ .thread = null },
.unblocked => {},
}
const old_status = thread.status.fetchOr(.{
.cancelation = @fromBackingInt(@intCast(0b010)),
.awaitable = .null,
}, .monotonic);
switch (old_status.cancelation) {
.parked => unreachable,
.blocked => unreachable,
.blocked_alertable => unreachable,
.blocked_canceling => unreachable,
.blocked_alertable_canceling => unreachable,
.none => return .{ .thread = thread }, // new status is `.blocked_alertable`
.canceling => {
// Status is unchanged (still `.canceling`)---change to `.canceled` before return.
thread.status.store(.{ .cancelation = .canceled, .awaitable = old_status.awaitable }, .monotonic);
return error.Canceled;
},
.canceled => return .{ .thread = null }, // new status is `.canceled` (unchanged)
}
}
fn checkCancel(s: AlertableSyscall) Io.Cancelable!void {
comptime assert(is_windows);
const thread = s.thread orelse return;
const old_status = thread.status.fetchOr(.{
.cancelation = @fromBackingInt(@intCast(0b010)),
.awaitable = .null,
}, .monotonic);
switch (old_status.cancelation) {
.none => unreachable,
.parked => unreachable,
.blocked => unreachable,
.blocked_canceling => unreachable,
.canceling => unreachable,
.canceled => unreachable,
.blocked_alertable => {}, // new status is `.blocked_alertable` (unchanged)
.blocked_alertable_canceling => {
// New status is `.canceling`---change to `.canceled` before return.
thread.status.store(.{ .cancelation = .canceled, .awaitable = old_status.awaitable }, .monotonic);
return error.Canceled;
},
}
}
fn finish(s: AlertableSyscall) void {
comptime assert(is_windows);
const thread = s.thread orelse return;
switch (thread.status.fetchXor(.{
.cancelation = @fromBackingInt(@intCast(0b010)),
.awaitable = .null,
}, .monotonic).cancelation) {
.none => unreachable,
.parked => unreachable,
.blocked => unreachable,
.blocked_canceling => unreachable,
.canceling => unreachable,
.canceled => unreachable,
.blocked_alertable => {}, // new status is `.none`
.blocked_alertable_canceling => {}, // new status is `.canceling`
}
}
fn fail(s: AlertableSyscall, err: anytype) @TypeOf(err) {
s.finish();
return err;
}
fn ntstatusBug(s: AlertableSyscall, status: windows.NTSTATUS) Io.UnexpectedError {
@branchHint(.cold);
s.finish();
return windows.statusBug(status);
}
fn unexpectedNtstatus(s: AlertableSyscall, status: windows.NTSTATUS) Io.UnexpectedError {
@branchHint(.cold);
s.finish();
return windows.unexpectedStatus(status);
}
};
pub fn waitForApcOrAlert() void {
const infinite_timeout: windows.LARGE_INTEGER = std.math.minInt(windows.LARGE_INTEGER);
_ = windows.ntdll.NtDelayExecution(.TRUE, &infinite_timeout);
}
pub const max_iovecs_len = 8;
pub const splat_buffer_size = 64;
/// Happens to be the same number that matches maximum number of handles that
/// NtWaitForMultipleObjects accepts. We use this value also for poll() on
/// posix systems.
const poll_buffer_len = 64;
pub const default_PATH = "/usr/local/bin:/bin:/usr/bin";
/// There are multiple kernel bugs being worked around with retries.
const max_windows_kernel_bug_retries = 13;
comptime {
if (@TypeOf(posix.IOV_MAX) != void) assert(max_iovecs_len <= posix.IOV_MAX);
}
pub const InitOptions = struct {
/// Affects how many bytes are memory-mapped for threads.
stack_size: usize = std.Thread.SpawnConfig.default_stack_size,
/// Maximum thread pool size (excluding main thread) when dispatching async
/// tasks. Until this limit, calls to `Io.async` when all threads are busy will
/// cause a new thread to be spawned and permanently added to the pool. After
/// this limit, calls to `Io.async` when all threads are busy run the task
/// immediately.
///
/// Defaults to one less than the number of logical CPU cores.
///
/// Protected by `Threaded.mutex` once the I/O instance is already in use. See
/// `setAsyncLimit`.
async_limit: ?Io.Limit = null,
/// Maximum thread pool size (excluding main thread) for dispatching concurrent
/// tasks. Until this limit, calls to `Io.concurrent` will increase the thread
/// pool size.
///
/// After this number, calls to `Io.concurrent` return `error.ConcurrencyUnavailable`.
concurrent_limit: Io.Limit = .unlimited,
/// Affects the following operations:
/// * `processExecutablePath` on OpenBSD and Haiku.
argv0: Argv0 = .empty,
/// Affects the following operations:
/// * `fileIsTty`
/// * `processExecutablePath` on OpenBSD and Haiku (observes "PATH").
/// * `processSpawn`, `processSpawnPath`, `processReplace`, `processReplacePath`
environ: process.Environ = .empty,
/// If set to `true`, `File.MemoryMap` APIs will always take the fallback path.
disable_memory_mapping: bool = false,
};
/// Related:
/// * `init_single_threaded`
pub fn init(
/// Must be threadsafe. Only used for the following functions:
/// * `Io.VTable.async`
/// * `Io.VTable.concurrent`
/// * `Io.VTable.groupAsync`
/// * `Io.VTable.groupConcurrent`
/// If these functions are avoided, then `Allocator.failing` may be passed
/// here.
gpa: Allocator,
options: InitOptions,
) Threaded {
if (builtin.single_threaded) return .{
.allocator = gpa,
.stack_size = options.stack_size,
.async_limit = options.async_limit orelse init_single_threaded.async_limit,
.cpu_count_error = init_single_threaded.cpu_count_error,
.concurrent_limit = options.concurrent_limit,
.old_sig_io = undefined,
.old_sig_pipe = undefined,
.have_signal_handler = init_single_threaded.have_signal_handler,
.argv0 = options.argv0,
.environ_initialized = options.environ.block.isEmpty(),
.environ = .{ .process_environ = options.environ },
.worker_threads = init_single_threaded.worker_threads,
.disable_memory_mapping = options.disable_memory_mapping,
};
const cpu_count = std.Thread.getCpuCount();
var t: Threaded = .{
.allocator = gpa,
.stack_size = options.stack_size,
.async_limit = options.async_limit orelse if (cpu_count) |n| .limited(n - 1) else |_| .nothing,
.concurrent_limit = options.concurrent_limit,
.cpu_count_error = if (cpu_count) |_| null else |e| e,
.old_sig_io = undefined,
.old_sig_pipe = undefined,
.have_signal_handler = false,
.argv0 = options.argv0,
.environ_initialized = options.environ.block.isEmpty(),
.environ = .{ .process_environ = options.environ },
.worker_threads = .init(null),
.disable_memory_mapping = options.disable_memory_mapping,
};
if (posix.Sigaction != void) {
// This causes sending `posix.SIG.IO` to thread to interrupt blocking
// syscalls, returning `posix.E.INTR`.
const act: posix.Sigaction = .{
.handler = .{ .handler = doNothingSignalHandler },
.mask = posix.sigemptyset(),
.flags = 0,
};
if (have_sig_io) posix.sigaction(.IO, &act, &t.old_sig_io);
if (have_sig_pipe) posix.sigaction(.PIPE, &act, &t.old_sig_pipe);
t.have_signal_handler = true;
}
return t;
}
/// Statically initialize such that calls to `Io.VTable.concurrent` will fail
/// with `error.ConcurrencyUnavailable`.
///
/// When initialized this way:
/// * cancel requests have no effect.
/// * `deinit` is safe, but unnecessary to call.
pub const init_single_threaded: Threaded = init: {
const env_block: process.Environ.Block = if (is_windows) .global else .empty;
break :init .{
.allocator = .failing,
.stack_size = std.Thread.SpawnConfig.default_stack_size,
.async_limit = .nothing,
.cpu_count_error = null,
.concurrent_limit = .nothing,
.old_sig_io = undefined,
.old_sig_pipe = undefined,
.have_signal_handler = false,
.argv0 = .empty,
.environ_initialized = env_block.isEmpty(),
.environ = .{ .process_environ = .{ .block = env_block } },
.worker_threads = .init(null),
.disable_memory_mapping = false,
};
};
var global_single_threaded_instance: Threaded = .init_single_threaded;
/// In general, the application is responsible for choosing the `Io`
/// implementation and library code should accept an `Io` parameter rather than
/// accessing this declaration. Most code should avoid referencing this
/// declaration entirely.
///
/// However, in some cases such as debugging, it is desirable to hardcode a
/// reference to this `Io` implementation.
///
/// This instance does not support concurrency or cancelation.
pub const global_single_threaded: *Threaded = &global_single_threaded_instance;
pub fn setAsyncLimit(t: *Threaded, new_limit: Io.Limit) void {
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
t.async_limit = new_limit;
}
pub fn deinit(t: *Threaded) void {
t.join();
if (posix.Sigaction != void and t.have_signal_handler) {
if (have_sig_io) posix.sigaction(.IO, &t.old_sig_io, null);
if (have_sig_pipe) posix.sigaction(.PIPE, &t.old_sig_pipe, null);
}
t.dl.deinit();
t.null_file.deinit();
t.random_file.deinit();
t.pipe_file.deinit();
t.* = undefined;
}
fn join(t: *Threaded) void {
if (builtin.single_threaded) return;
{
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
t.join_requested = true;
}
condBroadcast(&t.cond);
t.wait_group.wait();
}
fn worker(t: *Threaded) void {
var thread: Thread = .{
.next = undefined,
.id = std.Thread.getCurrentId(),
.handle = handle: {
if (std.Thread.use_pthreads) break :handle std.c.pthread_self();
if (is_windows) break :handle undefined; // populated below
},
.status = .init(.{
.cancelation = .none,
.awaitable = .null,
}),
.cancel_protection = .unblocked,
.futex_waiter = undefined,
.unpark_flag = unpark_flag_init,
.park_tid = if (ParkTid == std.Thread.Id) {} else getParkTid(),
.csprng = .uninitialized,
};
Thread.current = &thread;
if (is_windows) {
assert(windows.ntdll.NtOpenThread(
&thread.handle,
.{
.SPECIFIC = .{
.THREAD = .{
.TERMINATE = true, // for `NtCancelSynchronousIoFile`
.ALERT = true, // for `NtAlertThread`
},
},
},
&.{ .ObjectName = null },
&windows.teb().ClientId,
) == .SUCCESS);
}
defer if (is_windows) {
windows.CloseHandle(thread.handle);
};
{
var head = t.worker_threads.load(.monotonic);
while (true) {
thread.next = head;
head = t.worker_threads.cmpxchgWeak(
head,
&thread,
.release,
.monotonic,
) orelse break;
}
}
defer t.wait_group.finish();
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
while (true) {
while (t.run_queue.popFirst()) |runnable_node| {
mutexUnlock(&t.mutex);
thread.cancel_protection = .unblocked;
const runnable: *Runnable = @fieldParentPtr("node", runnable_node);
runnable.startFn(runnable, &thread, t);
mutexLock(&t.mutex);
t.busy_count -= 1;
}
if (t.join_requested) break;
condWait(&t.cond, &t.mutex);
}
}
pub fn io(t: *Threaded) Io {
return .{
.userdata = t,
.vtable = &.{
.crashHandler = crashHandler,
.async = async,
.concurrent = concurrent,
.await = await,
.cancel = cancel,
.groupAsync = groupAsync,
.groupConcurrent = groupConcurrent,
.groupAwait = groupAwait,
.groupCancel = groupCancel,
.recancel = recancel,
.swapCancelProtection = swapCancelProtection,
.checkCancel = checkCancel,
.futexWait = futexWait,
.futexWaitUncancelable = futexWaitUncancelable,
.futexWake = futexWake,
.operate = operate,
.batchAwaitAsync = batchAwaitAsync,
.batchAwaitConcurrent = batchAwaitConcurrent,
.batchCancel = batchCancel,
.dirCreateDir = dirCreateDir,
.dirCreateDirPath = dirCreateDirPath,
.dirCreateDirPathOpen = dirCreateDirPathOpen,
.dirStat = dirStat,
.dirStatFile = dirStatFile,
.dirAccess = dirAccess,
.dirCreateFile = dirCreateFile,
.dirCreateFileAtomic = dirCreateFileAtomic,
.dirOpenFile = dirOpenFile,
.dirOpenDir = dirOpenDir,
.dirClose = dirClose,
.dirRead = dirRead,
.dirRealPath = dirRealPath,
.dirRealPathFile = dirRealPathFile,
.dirDeleteFile = dirDeleteFile,
.dirDeleteDir = dirDeleteDir,
.dirRename = dirRename,
.dirRenamePreserve = dirRenamePreserve,
.dirSymLink = dirSymLink,
.dirReadLink = dirReadLink,
.dirSetOwner = dirSetOwner,
.dirSetFileOwner = dirSetFileOwner,
.dirSetPermissions = dirSetPermissions,
.dirSetFilePermissions = dirSetFilePermissions,
.dirSetTimestamps = dirSetTimestamps,
.dirHardLink = dirHardLink,
.fileStat = fileStat,
.fileLength = fileLength,
.fileClose = fileClose,
.fileWritePositional = fileWritePositional,
.fileWriteFileStreaming = fileWriteFileStreaming,
.fileWriteFilePositional = fileWriteFilePositional,
.fileReadPositional = fileReadPositional,
.fileSeekBy = fileSeekBy,
.fileSeekTo = fileSeekTo,
.fileSync = fileSync,
.fileIsTty = fileIsTty,
.fileEnableAnsiEscapeCodes = fileEnableAnsiEscapeCodes,
.fileSupportsAnsiEscapeCodes = fileSupportsAnsiEscapeCodes,
.fileSetLength = fileSetLength,
.fileSetOwner = fileSetOwner,
.fileSetPermissions = fileSetPermissions,
.fileSetTimestamps = fileSetTimestamps,
.fileLock = fileLock,
.fileTryLock = fileTryLock,
.fileUnlock = fileUnlock,
.fileDowngradeLock = fileDowngradeLock,
.fileRealPath = fileRealPath,
.fileHardLink = fileHardLink,
.fileMemoryMapCreate = fileMemoryMapCreate,
.fileMemoryMapDestroy = fileMemoryMapDestroy,
.fileMemoryMapSetLength = fileMemoryMapSetLength,
.fileMemoryMapRead = fileMemoryMapRead,
.fileMemoryMapWrite = fileMemoryMapWrite,
.processExecutableOpen = processExecutableOpen,
.processExecutablePath = processExecutablePath,
.lockStderr = lockStderr,
.tryLockStderr = tryLockStderr,
.unlockStderr = unlockStderr,
.processCurrentPath = processCurrentPath,
.processSetCurrentDir = processSetCurrentDir,
.processSetCurrentPath = processSetCurrentPath,
.processReplace = processReplace,
.processReplacePath = processReplacePath,
.processSpawn = processSpawn,
.processSpawnPath = processSpawnPath,
.childWait = childWait,
.childKill = childKill,
.progressParentFile = progressParentFile,
.now = now,
.clockResolution = clockResolution,
.sleep = sleep,
.random = random,
.randomSecure = randomSecure,
.netListenIp = switch (native_os) {
.windows => netListenIpWindows,
else => netListenIpPosix,
},
.netListenUnix = switch (native_os) {
.windows => netListenUnixWindows,
else => netListenUnixPosix,
},
.netAccept = switch (native_os) {
.windows => netAcceptWindows,
else => netAcceptPosix,
},
.netBindIp = switch (native_os) {
.windows => netBindIpWindows,
else => netBindIpPosix,
},
.netConnectIp = switch (native_os) {
.windows => netConnectIpWindows,
else => netConnectIpPosix,
},
.netConnectUnix = switch (native_os) {
.windows => netConnectUnixWindows,
else => netConnectUnixPosix,
},
.netSocketCreatePair = netSocketCreatePair,
.netClose = netClose,
.netShutdown = switch (native_os) {
.windows => netShutdownWindows,
else => netShutdownPosix,
},
.netWriteFile = netWriteFile,
.netInterfaceNameResolve = netInterfaceNameResolve,
.netInterfaceName = netInterfaceName,
.netLookup = netLookup,
},
};
}
pub const socket_flags_unsupported = is_darwin or native_os == .haiku;
const have_accept4 = !socket_flags_unsupported;
const have_flock_open_flags = @hasField(posix.O, "EXLOCK");
const have_networking = std.options.networking and native_os != .wasi;
const have_flock = @TypeOf(posix.system.flock) != void;
const have_sendmmsg = native_os == .linux;
const have_futex = switch (builtin.cpu.arch) {
.wasm32, .wasm64 => builtin.cpu.has(.wasm, .atomics),
else => true,
};
const have_preadv = switch (native_os) {
.windows, .haiku => false,
else => true,
};
const have_sig_io = posix.SIG != void and @hasField(posix.SIG, "IO");
const have_sig_pipe = posix.SIG != void and @hasField(posix.SIG, "PIPE");
const have_sendfile = if (builtin.link_libc) @TypeOf(std.c.sendfile) != void else native_os == .linux;
const have_copy_file_range = switch (native_os) {
.linux, .freebsd => true,
else => false,
};
const have_fcopyfile = is_darwin;
const have_fchmodat2 = native_os == .linux and
(builtin.os.isAtLeast(.linux, .{ .major = 6, .minor = 6, .patch = 0 }) orelse true) and
(builtin.abi.isAndroid() or !std.c.versionCheck(.{ .major = 2, .minor = 32, .patch = 0 }));
const have_fchmodat_flags = native_os != .linux or
(!builtin.abi.isAndroid() and std.c.versionCheck(.{ .major = 2, .minor = 32, .patch = 0 }));
const have_fchown = switch (native_os) {
.wasi, .windows => false,
else => true,
};
const have_fchmod = switch (native_os) {
.windows => false,
.wasi => builtin.link_libc,
else => true,
};
const have_waitid = switch (native_os) {
.linux => @hasField(std.os.linux.SYS, "waitid"),
else => false,
};
const have_wait4 = switch (native_os) {
.linux => @hasField(std.os.linux.SYS, "wait4"),
.dragonfly, .freebsd, .netbsd, .openbsd, .illumos, .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => true,
else => false,
};
const have_mmap = switch (native_os) {
.wasi, .windows => false,
else => true,
};
const have_poll = switch (native_os) {
.wasi, .windows => false,
else => true,
};
const open_sym = if (posix.lfs64_abi) posix.system.open64 else posix.system.open;
const openat_sym = if (posix.lfs64_abi) posix.system.openat64 else posix.system.openat;
const fstat_sym = if (posix.lfs64_abi) posix.system.fstat64 else posix.system.fstat;
const fstatat_sym = if (posix.lfs64_abi) posix.system.fstatat64 else posix.system.fstatat;
const lseek_sym = if (posix.lfs64_abi) posix.system.lseek64 else posix.system.lseek;
const preadv_sym = if (posix.lfs64_abi) posix.system.preadv64 else posix.system.preadv;
const pread_sym = if (posix.lfs64_abi) posix.system.pread64 else posix.system.pread;
const ftruncate_sym = if (posix.lfs64_abi) posix.system.ftruncate64 else posix.system.ftruncate;
const pwritev_sym = if (posix.lfs64_abi) posix.system.pwritev64 else posix.system.pwritev;
const pwrite_sym = if (posix.lfs64_abi) posix.system.pwrite64 else posix.system.pwrite;
const sendfile_sym = if (posix.lfs64_abi) posix.system.sendfile64 else posix.system.sendfile;
const mmap_sym = if (posix.lfs64_abi) posix.system.mmap64 else posix.system.mmap;
const linux_copy_file_range_use_c = std.c.versionCheck(if (builtin.abi.isAndroid()) .{
.major = 34,
.minor = 0,
.patch = 0,
} else .{
.major = 2,
.minor = 27,
.patch = 0,
});
const linux_copy_file_range_sys = if (linux_copy_file_range_use_c) std.c else std.os.linux;
const statx_use_c = std.c.versionCheck(if (builtin.abi.isAndroid())
.{ .major = 30, .minor = 0, .patch = 0 }
else
.{ .major = 2, .minor = 28, .patch = 0 });
const use_libc_getrandom = std.c.versionCheck(if (builtin.abi.isAndroid()) .{
.major = 28,
.minor = 0,
.patch = 0,
} else .{
.major = 2,
.minor = 25,
.patch = 0,
});
const use_dev_urandom = @TypeOf(posix.system.getrandom) == void and native_os == .linux;
fn crashHandler(userdata: ?*anyopaque) void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const thread = Thread.current orelse return;
thread.status.store(.{ .cancelation = .canceled, .awaitable = .null }, .monotonic);
thread.cancel_protection = .blocked;
}
fn async(
userdata: ?*anyopaque,
result: []u8,
result_alignment: Alignment,
context: []const u8,
context_alignment: Alignment,
start: *const fn (context: *const anyopaque, result: *anyopaque) void,
) ?*Io.AnyFuture {
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (builtin.single_threaded) {
start(context.ptr, result.ptr);
return null;
}
const gpa = t.allocator;
const future = Future.create(gpa, result.len, result_alignment, context, context_alignment, start) catch |err| switch (err) {
error.OutOfMemory => {
start(context.ptr, result.ptr);
return null;
},
};
mutexLock(&t.mutex);
const busy_count = t.busy_count;
if (busy_count >= @backingInt(t.async_limit)) {
mutexUnlock(&t.mutex);
future.destroy(gpa);
start(context.ptr, result.ptr);
return null;
}
t.busy_count = busy_count + 1;
const pool_size = t.wait_group.value();
if (pool_size - busy_count == 0) {
t.wait_group.start();
const thread = std.Thread.spawn(.{ .stack_size = t.stack_size }, worker, .{t}) catch {
t.wait_group.finish();
t.busy_count = busy_count;
mutexUnlock(&t.mutex);
future.destroy(gpa);
start(context.ptr, result.ptr);
return null;
};
thread.detach();
}
t.run_queue.prepend(&future.runnable.node);
mutexUnlock(&t.mutex);
condSignal(&t.cond);
return @ptrCast(future);
}
fn concurrent(
userdata: ?*anyopaque,
result_len: usize,
result_alignment: Alignment,
context: []const u8,
context_alignment: Alignment,
start: *const fn (context: *const anyopaque, result: *anyopaque) void,
) Io.ConcurrentError!*Io.AnyFuture {
if (builtin.single_threaded) return error.ConcurrencyUnavailable;
const t: *Threaded = @ptrCast(@alignCast(userdata));
const gpa = t.allocator;
const future = Future.create(gpa, result_len, result_alignment, context, context_alignment, start) catch |err| switch (err) {
error.OutOfMemory => return error.ConcurrencyUnavailable,
};
errdefer future.destroy(gpa);
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
const busy_count = t.busy_count;
if (busy_count >= @backingInt(t.concurrent_limit))
return error.ConcurrencyUnavailable;
t.busy_count = busy_count + 1;
errdefer t.busy_count = busy_count;
const pool_size = t.wait_group.value();
if (pool_size - busy_count == 0) {
t.wait_group.start();
errdefer t.wait_group.finish();
const thread = std.Thread.spawn(.{ .stack_size = t.stack_size }, worker, .{t}) catch
return error.ConcurrencyUnavailable;
thread.detach();
}
t.run_queue.prepend(&future.runnable.node);
condSignal(&t.cond);
return @ptrCast(future);
}
fn groupAsync(
userdata: ?*anyopaque,
type_erased: *Io.Group,
context: []const u8,
context_alignment: Alignment,
start: *const fn (context: *const anyopaque) void,
) void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const g: Group = .{ .ptr = type_erased };
if (builtin.single_threaded) return groupAsyncEager(start, context.ptr);
const gpa = t.allocator;
const task = Group.Task.create(gpa, g, context, context_alignment, start) catch |err| switch (err) {
error.OutOfMemory => return groupAsyncEager(start, context.ptr),
};
mutexLock(&t.mutex);
const busy_count = t.busy_count;
if (busy_count >= @backingInt(t.async_limit)) {
mutexUnlock(&t.mutex);
task.destroy(gpa);
return groupAsyncEager(start, context.ptr);
}
t.busy_count = busy_count + 1;
const pool_size = t.wait_group.value();
if (pool_size - busy_count == 0) {
t.wait_group.start();
const thread = std.Thread.spawn(.{ .stack_size = t.stack_size }, worker, .{t}) catch {
t.wait_group.finish();
t.busy_count = busy_count;
mutexUnlock(&t.mutex);
task.destroy(gpa);
return groupAsyncEager(start, context.ptr);
};
thread.detach();
}
// TODO: if this logic is changed to be lock-free, this `fetchAdd` must be released by the queue
// prepend so that the task doesn't finish without observing this and try to decrement the count
// below zero.
_ = g.status().fetchAdd(.{
.num_running = 1,
.have_awaiter = false,
.canceled = false,
}, .monotonic);
t.run_queue.prepend(&task.runnable.node);
mutexUnlock(&t.mutex);
condSignal(&t.cond);
}
fn groupAsyncEager(
start: *const fn (context: *const anyopaque) void,
context: *const anyopaque,
) void {
start(context);
}
fn groupConcurrent(
userdata: ?*anyopaque,
type_erased: *Io.Group,
context: []const u8,
context_alignment: Alignment,
start: *const fn (context: *const anyopaque) void,
) Io.ConcurrentError!void {
if (builtin.single_threaded) return error.ConcurrencyUnavailable;
const t: *Threaded = @ptrCast(@alignCast(userdata));
const g: Group = .{ .ptr = type_erased };
const gpa = t.allocator;
const task = Group.Task.create(gpa, g, context, context_alignment, start) catch |err| switch (err) {
error.OutOfMemory => return error.ConcurrencyUnavailable,
};
errdefer task.destroy(gpa);
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
const busy_count = t.busy_count;
if (busy_count >= @backingInt(t.concurrent_limit))
return error.ConcurrencyUnavailable;
t.busy_count = busy_count + 1;
errdefer t.busy_count = busy_count;
const pool_size = t.wait_group.value();
if (pool_size - busy_count == 0) {
t.wait_group.start();
errdefer t.wait_group.finish();
const thread = std.Thread.spawn(.{ .stack_size = t.stack_size }, worker, .{t}) catch
return error.ConcurrencyUnavailable;
thread.detach();
}
// TODO: if this logic is changed to be lock-free, this `fetchAdd` must be released by the queue
// prepend so that the task doesn't finish without observing this and try to decrement the count
// below zero.
_ = g.status().fetchAdd(.{
.num_running = 1,
.have_awaiter = false,
.canceled = false,
}, .monotonic);
t.run_queue.prepend(&task.runnable.node);
condSignal(&t.cond);
}
fn groupAwait(userdata: ?*anyopaque, type_erased: *Io.Group, initial_token: *anyopaque) Io.Cancelable!void {
_ = initial_token; // we need to load `token` *after* the group finishes
if (builtin.single_threaded) unreachable; // nothing to await
const t: *Threaded = @ptrCast(@alignCast(userdata));
const g: Group = .{ .ptr = type_erased };
var num_completed: std.atomic.Value(u32) = .init(0);
g.awaiter().* = &num_completed;
const pre_await_status = g.status().fetchOr(.{
.num_running = 0,
.have_awaiter = true,
.canceled = false,
}, .acq_rel); // acquire results if complete; release `g.awaiter()`
assert(!pre_await_status.have_awaiter);
assert(!pre_await_status.canceled);
if (pre_await_status.num_running == 0) {
// Already done. Since the group is finished, it's illegal to spawn more tasks in it
// until we return, so we can access `g.status()` non-atomically.
g.status().raw.have_awaiter = false;
return;
}
while (Thread.futexWait(&num_completed.raw, 0, null)) {
switch (num_completed.load(.acquire)) { // acquire task results
0 => continue,
1 => break,
else => unreachable, // group was reused before `await` returned
}
} else |err| switch (err) {
error.Canceled => {
const pre_cancel_status = g.status().fetchOr(.{
.num_running = 0,
.have_awaiter = false,
.canceled = true,
}, .acq_rel); // acquire results if complete; release `g.awaiter()`
assert(pre_cancel_status.have_awaiter);
assert(!pre_cancel_status.canceled);
// Even if `pre_cancel_status.num_running == 0`, we still need to wait for the signal,
// because in that case the last member of the group is already trying to modify it.
// However, if we know everything is done, we *can* skip signaling blocked threads.
const skip_signals = pre_cancel_status.num_running == 0;
g.waitForCancelWithSignaling(t, &num_completed, skip_signals);
// The group is finished, so it's illegal to spawn more tasks in it until we return, so
// we can access `g.status()` non-atomically.
g.status().raw.canceled = false;
g.status().raw.have_awaiter = false;
return error.Canceled;
},
}
// The group is finished, so it's illegal to spawn more tasks in it until we return, so
// we can access `g.status()` non-atomically.
g.status().raw.have_awaiter = false;
}
fn groupCancel(userdata: ?*anyopaque, type_erased: *Io.Group, initial_token: *anyopaque) void {
_ = initial_token;
if (builtin.single_threaded) unreachable; // nothing to cancel
const t: *Threaded = @ptrCast(@alignCast(userdata));
const g: Group = .{ .ptr = type_erased };
var num_completed: std.atomic.Value(u32) = .init(0);
g.awaiter().* = &num_completed;
const pre_cancel_status = g.status().fetchOr(.{
.num_running = 0,
.have_awaiter = true,
.canceled = true,
}, .acq_rel); // acquire results if complete; release `g.awaiter()`
assert(!pre_cancel_status.have_awaiter);
assert(!pre_cancel_status.canceled);
if (pre_cancel_status.num_running == 0) {
// Already done. Since the group is finished, it's illegal to spawn more tasks in it
// until we return, so we can access `g.status()` non-atomically.
g.status().raw.have_awaiter = false;
g.status().raw.canceled = false;
return;
}
g.waitForCancelWithSignaling(t, &num_completed, false);
g.status().raw = .{ .num_running = 0, .have_awaiter = false, .canceled = false };
}
fn recancel(userdata: ?*anyopaque) void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
recancelInner();
}
fn recancelInner() void {
const thread = Thread.current.?; // called `recancel` but was not canceled
switch (thread.status.fetchXor(.{
.cancelation = @fromBackingInt(@intCast(0b001)),
.awaitable = .null,
}, .monotonic).cancelation) {
.canceled => {},
.none => unreachable, // called `recancel` but was not canceled
.canceling => unreachable, // called `recancel` but cancelation was already pending
.parked => unreachable,
.blocked => unreachable,
.blocked_alertable => unreachable,
.blocked_alertable_canceling => unreachable,
.blocked_canceling => unreachable,
}
}
fn swapCancelProtection(userdata: ?*anyopaque, new: Io.CancelProtection) Io.CancelProtection {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const thread = Thread.current orelse return .unblocked;
const old = thread.cancel_protection;
thread.cancel_protection = new;
return old;
}
fn checkCancel(userdata: ?*anyopaque) Io.Cancelable!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
return Thread.checkCancel();
}
fn await(
userdata: ?*anyopaque,
any_future: *Io.AnyFuture,
result: []u8,
result_alignment: Alignment,
) void {
_ = result_alignment;
if (builtin.single_threaded) unreachable; // nothing to await
const t: *Threaded = @ptrCast(@alignCast(userdata));
const future: *Future = @ptrCast(@alignCast(any_future));
var num_completed: std.atomic.Value(u32) = .init(0);
future.awaiter = &num_completed;
const pre_await_status = future.status.fetchOr(.{
.tag = .pending_awaited,
.thread = .null,
}, .acq_rel); // acquire results if complete; release `future.awaiter`
switch (pre_await_status.tag) {
.pending => while (Thread.futexWait(&num_completed.raw, 0, null)) {
switch (num_completed.load(.acquire)) { // acquire task results
0 => continue,
1 => break,
else => unreachable, // group was reused before `await` returned
}
} else |err| switch (err) {
error.Canceled => {
const pre_cancel_status = future.status.fetchOr(.{
.tag = .pending_canceled,
.thread = .null,
}, .acq_rel); // acquire results if complete; release `future.awaiter`
const done_status = switch (pre_cancel_status.tag) {
.pending => unreachable, // invalid state: we already awaited
.pending_awaited => done_status: {
const working_thread = pre_cancel_status.thread.unpack();
future.waitForCancelWithSignaling(t, &num_completed, @alignCast(working_thread));
break :done_status future.status.load(.monotonic);
},
.pending_canceled => unreachable, // `await` raced with `cancel`
.done => done_status: {
// The task just finished, but we still need to wait for the signal, because the
// task thread already figured out that they need to update `future.awaiter`.
future.waitForCancelWithSignaling(t, &num_completed, null);
// Also, we have clobbered `future.status.tag` to `.pending_canceled`, but that's
// not actually a problem for the logic below.
break :done_status pre_cancel_status;
},
};
// If the future did not acknowledge the cancelation, we need to mark it outstanding
// for us. Because `done_status.tag == .done`, the information about whether there
// was an acknowledged cancelation is encoded in `done_status.thread`.
assert(done_status.tag == .done);
switch (done_status.thread) {
.null => recancelInner(), // cancelation was not acknowledged, so it's ours
.all_ones => {}, // cancelation was acknowledged, so it was this task's job to propagate it
_ => unreachable,
}
},
},
.pending_awaited => unreachable, // `await` raced with `await`
.pending_canceled => unreachable, // `await` raced with `cancel`
.done => {},
}
@memcpy(result, future.resultPointer());
future.destroy(t.allocator);
}
fn cancel(
userdata: ?*anyopaque,
any_future: *Io.AnyFuture,
result: []u8,
result_alignment: Alignment,
) void {
_ = result_alignment;
if (builtin.single_threaded) unreachable; // nothing to cancel
const t: *Threaded = @ptrCast(@alignCast(userdata));
const future: *Future = @ptrCast(@alignCast(any_future));
var num_completed: std.atomic.Value(u32) = .init(0);
future.awaiter = &num_completed;
const pre_cancel_status = future.status.fetchOr(.{
.tag = .pending_canceled,
.thread = .null,
}, .acq_rel); // acquire results if complete; release `future.awaiter`
switch (pre_cancel_status.tag) {
.pending => {
const working_thread = pre_cancel_status.thread.unpack();
future.waitForCancelWithSignaling(t, &num_completed, @alignCast(working_thread));
},
.pending_awaited => unreachable, // `await` raced with `await`
.pending_canceled => unreachable, // `await` raced with `cancel`
.done => {},
}
@memcpy(result, future.resultPointer());
future.destroy(t.allocator);
}
fn futexWait(userdata: ?*anyopaque, ptr: *const u32, expected: u32, timeout: Io.Timeout) Io.Cancelable!void {
if (builtin.single_threaded) {
assert(timeout != .none); // Deadlock.
return;
}
const t: *Threaded = @ptrCast(@alignCast(userdata));
const t_io = io(t);
const timeout_ns: ?u64 = ns: {
const d = timeout.toDurationFromNow(t_io) orelse break :ns null;
break :ns std.math.lossyCast(u64, d.raw.toNanoseconds());
};
return Thread.futexWait(ptr, expected, timeout_ns);
}
fn futexWaitUncancelable(userdata: ?*anyopaque, ptr: *const u32, expected: u32) void {
if (builtin.single_threaded) unreachable; // Deadlock.
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
Thread.futexWaitUncancelable(ptr, expected, null);
}
fn futexWake(userdata: ?*anyopaque, ptr: *const u32, max_waiters: u32) void {
if (builtin.single_threaded) return; // Nothing to wake up.
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
Thread.futexWake(ptr, max_waiters);
}
fn operate(userdata: ?*anyopaque, operation: Io.Operation) Io.Cancelable!Io.Operation.Result {
const t: *Threaded = @ptrCast(@alignCast(userdata));
switch (operation) {
.file_read_streaming => |o| return .{
.file_read_streaming = fileReadStreaming(t, o.file, o.data) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| e,
},
},
.file_write_streaming => |o| return .{
.file_write_streaming = fileWriteStreaming(t, o.file, o.header, o.data, o.splat) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| e,
},
},
.device_io_control => |*o| return .{ .device_io_control = try deviceIoControl(o) },
.net_receive => |*o| return .{ .net_receive = o: {
if (!have_networking) break :o .{ error.NetworkDown, 0 };
if (is_windows) break :o netReceiveWindows(t, o.socket_handle, o.message_buffer, o.data_buffer, o.flags);
netReceivePosix(o.socket_handle, &o.message_buffer[0], o.data_buffer, o.flags, false) catch |err| switch (err) {
error.Canceled => |e| return e,
error.WouldBlock => unreachable,
else => |e| break :o .{ e, 0 },
};
break :o .{ null, 1 };
} },
.net_send => |*o| return .{
.net_send = o: {
if (!have_networking) break :o .{ error.NetworkDown, 0 };
if (is_windows) break :o netSendWindows(t, o.socket_handle, o.messages, o.flags);
const send_err, const sent = netSendPosix(t, o.socket_handle, o.messages, o.flags, false);
if (send_err) |err| switch (err) {
error.Canceled => |e| if (sent == 0) {
return e;
} else {
// Leave the `error.Canceled` for later, but don't try to send any more messages.
recancelInner();
break :o .{ null, sent };
},
error.WouldBlock => unreachable,
else => |e| break :o .{ e, sent },
};
break :o .{ null, sent };
},
},
.net_read => |o| return .{
.net_read = netRead(o.socket_handle, o.data) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| e,
},
},
.net_write => |o| return .{
.net_write = (if (is_windows)
netWriteWindows(o.socket_handle, o.header, o.data, o.splat)
else
netWritePosix(o.socket_handle, o.header, o.data, o.splat)) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| e,
},
},
}
}
fn batchAwaitAsync(userdata: ?*anyopaque, b: *Io.Batch) Io.Cancelable!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (is_windows) {
batchDrainSubmittedWindows(t, b, false) catch |err| switch (err) {
error.ConcurrencyUnavailable => unreachable, // passed concurrency=false
else => |e| return e,
};
const alertable_syscall = try AlertableSyscall.start();
while (b.pending.head != .none and b.completed.head == .none) waitForApcOrAlert();
alertable_syscall.finish();
return;
}
if (have_poll) {
var poll_buffer: [poll_buffer_len]posix.pollfd = undefined;
var poll_len: u32 = 0;
{
var index = b.submitted.head;
while (index != .none and poll_len < poll_buffer_len) {
const submission = &b.storage[index.toIndex()].submission;
switch (submission.operation) {
.file_read_streaming => |o| {
poll_buffer[poll_len] = .{
.fd = o.file.handle,
.events = posix.POLL.IN | posix.POLL.ERR,
};
poll_len += 1;
},
.file_write_streaming => |o| {
poll_buffer[poll_len] = .{
.fd = o.file.handle,
.events = posix.POLL.OUT | posix.POLL.ERR,
};
poll_len += 1;
},
.device_io_control => |o| {
poll_buffer[poll_len] = .{
.fd = o.file.handle,
.events = posix.POLL.OUT | posix.POLL.IN | posix.POLL.ERR,
};
poll_len += 1;
},
.net_receive => |*o| {
poll_buffer[poll_len] = .{
.fd = o.socket_handle,
.events = posix.POLL.IN | posix.POLL.ERR,
};
poll_len += 1;
},
.net_send => |*o| {
poll_buffer[poll_len] = .{
.fd = o.socket_handle,
.events = posix.POLL.OUT | posix.POLL.ERR,
};
poll_len += 1;
},
.net_read => |o| {
poll_buffer[poll_len] = .{
.fd = o.socket_handle,
.events = posix.POLL.IN | posix.POLL.ERR,
};
poll_len += 1;
},
.net_write => |o| {
poll_buffer[poll_len] = .{
.fd = o.socket_handle,
.events = posix.POLL.OUT | posix.POLL.ERR,
};
poll_len += 1;
},
}
index = submission.node.next;
}
}
switch (poll_len) {
0 => return,
1 => {},
else => while (true) {
const timeout_ms: i32 = t: {
if (b.completed.head != .none) {
// It is legal to call batchWait with already completed
// operations in the ring. In such case, we need to avoid
// blocking in the poll syscall, but we can still take this
// opportunity to find additional ready operations.
break :t 0;
}
break :t std.math.maxInt(i32);
};
const syscall = try Syscall.start();
const rc = posix.system.poll(&poll_buffer, poll_len, timeout_ms);
syscall.finish();
switch (posix.errno(rc)) {
.SUCCESS => {
if (rc == 0) {
if (b.completed.head != .none) {
// Since there are already completions available in the
// queue, this is neither a timeout nor a case for
// retrying.
return;
}
continue;
}
var prev_index: Io.Operation.OptionalIndex = .none;
var index = b.submitted.head;
for (poll_buffer[0..poll_len]) |poll_entry| {
const storage = &b.storage[index.toIndex()];
const submission = &storage.submission;
const next_index = submission.node.next;
if (poll_entry.revents != 0) {
const result = try operate(t, submission.operation);
switch (prev_index) {
.none => b.submitted.head = next_index,
else => b.storage[prev_index.toIndex()].submission.node.next = next_index,
}
if (next_index == .none) b.submitted.tail = prev_index;
switch (b.completed.tail) {
.none => b.completed.head = index,
else => |tail_index| b.storage[tail_index.toIndex()].completion.node.next = index,
}
storage.* = .{ .completion = .{ .node = .{ .next = .none }, .result = result } };
b.completed.tail = index;
} else prev_index = index;
index = next_index;
}
assert(index == .none);
return;
},
.INTR => continue,
else => break,
}
},
}
}
var tail_index = b.completed.tail;
defer b.completed.tail = tail_index;
var index = b.submitted.head;
errdefer b.submitted.head = index;
while (index != .none) {
const storage = &b.storage[index.toIndex()];
const submission = &storage.submission;
const next_index = submission.node.next;
const result = try operate(t, submission.operation);
switch (tail_index) {
.none => b.completed.head = index,
else => b.storage[tail_index.toIndex()].completion.node.next = index,
}
storage.* = .{ .completion = .{ .node = .{ .next = .none }, .result = result } };
tail_index = index;
index = next_index;
}
b.submitted = .{ .head = .none, .tail = .none };
}
fn batchAwaitConcurrent(userdata: ?*anyopaque, b: *Io.Batch, timeout: Io.Timeout) Io.Batch.AwaitConcurrentError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (is_windows) {
const deadline: ?Io.Clock.Timestamp = timeout.toTimestamp(io(t));
try batchDrainSubmittedWindows(t, b, true);
while (b.pending.head != .none and b.completed.head == .none) {
var delay_interval: windows.LARGE_INTEGER = interval: {
const d = deadline orelse break :interval std.math.minInt(windows.LARGE_INTEGER);
break :interval timeoutToWindowsInterval(.{ .deadline = d }).?;
};
const alertable_syscall = try AlertableSyscall.start();
const delay_rc = windows.ntdll.NtDelayExecution(.TRUE, &delay_interval);
alertable_syscall.finish();
switch (delay_rc) {
.SUCCESS, .TIMEOUT => {
// The thread woke due to the timeout. Although spurious
// timeouts are OK, when no deadline is passed we must not
// return `error.Timeout`.
if (timeout != .none and b.completed.head == .none) return error.Timeout;
},
else => {},
}
}
return;
}
if (native_os == .wasi) {
// TODO call poll_oneoff
return error.ConcurrencyUnavailable;
}
if (!have_poll) return error.ConcurrencyUnavailable;
var poll_buffer: [poll_buffer_len]posix.pollfd = undefined;
var poll_storage: struct {
gpa: Allocator,
batch: *Io.Batch,
slice: []posix.pollfd,
len: u32,
fn add(storage: *@This(), fd: File.Handle, events: @FieldType(posix.pollfd, "events")) Io.ConcurrentError!void {
const len = storage.len;
if (len == poll_buffer_len) {
const slice: []posix.pollfd = if (storage.batch.userdata) |batch_userdata|
@as([*]posix.pollfd, @ptrCast(@alignCast(batch_userdata)))[0..storage.batch.storage.len]
else allocation: {
const allocation = storage.gpa.alloc(posix.pollfd, storage.batch.storage.len) catch
return error.ConcurrencyUnavailable;
storage.batch.userdata = allocation.ptr;
break :allocation allocation;
};
@memcpy(slice[0..poll_buffer_len], storage.slice);
storage.slice = slice;
}
storage.slice[len] = .{
.fd = fd,
.events = events,
};
storage.len = len + 1;
}
} = .{ .gpa = t.allocator, .batch = b, .slice = &poll_buffer, .len = 0 };
{
var index = b.submitted.head;
while (index != .none) {
const storage = &b.storage[index.toIndex()];
const submission = storage.submission;
switch (submission.operation) {
.file_read_streaming => |o| try poll_storage.add(o.file.handle, posix.POLL.IN | posix.POLL.ERR),
.file_write_streaming => |o| try poll_storage.add(o.file.handle, posix.POLL.OUT | posix.POLL.ERR),
.device_io_control => |o| try poll_storage.add(o.file.handle, posix.POLL.IN | posix.POLL.OUT | posix.POLL.ERR),
.net_receive => |*o| nb: {
var data_i: usize = 0;
const result: Io.Operation.Result = .{ .net_receive = for (o.message_buffer, 0..) |*msg, msg_i| {
const remaining_data_buffer = o.data_buffer[data_i..];
netReceivePosix(o.socket_handle, msg, remaining_data_buffer, o.flags, true) catch |err| switch (err) {
error.Canceled => |e| return e,
error.WouldBlock => {
if (msg_i != 0) break .{ null, msg_i };
try poll_storage.add(o.socket_handle, posix.POLL.IN | posix.POLL.ERR);
break :nb;
},
else => |e| break .{ e, 0 },
};
data_i += msg.data.len;
} else .{ null, o.message_buffer.len } };
switch (b.completed.tail) {
.none => b.completed.head = index,
else => |tail_index| b.storage[tail_index.toIndex()].completion.node.next = index,
}
storage.* = .{ .completion = .{ .node = .{ .next = .none }, .result = result } };
b.completed.tail = index;
},
.net_send => |*o| nb: {
const result: Io.Operation.Result = .{
.net_send = o: {
const send_err, const sent = netSendPosix(t, o.socket_handle, o.messages, o.flags, true);
if (send_err) |err| switch (err) {
error.Canceled => |e| if (sent == 0) {
return e;
} else {
// Leave the `error.Canceled` for later, but don't try to send any more messages.
recancelInner();
break :o .{ null, sent };
},
error.WouldBlock => {
if (sent != 0) break :o .{ null, sent };
try poll_storage.add(o.socket_handle, posix.POLL.OUT | posix.POLL.ERR);
break :nb;
},
else => |e| break :o .{ e, sent },
};
break :o .{ null, sent };
},
};
switch (b.completed.tail) {
.none => b.completed.head = index,
else => |tail_index| b.storage[tail_index.toIndex()].completion.node.next = index,
}
storage.* = .{ .completion = .{ .node = .{ .next = .none }, .result = result } };
b.completed.tail = index;
},
.net_read => |o| try poll_storage.add(o.socket_handle, posix.POLL.IN | posix.POLL.ERR),
.net_write => |o| try poll_storage.add(o.socket_handle, posix.POLL.OUT | posix.POLL.ERR),
}
index = submission.node.next;
}
}
switch (poll_storage.len) {
0 => return,
1 => if (timeout == .none and b.completed.head == .none) {
const index = b.submitted.head;
const storage = &b.storage[index.toIndex()];
const result = try operate(t, storage.submission.operation);
b.submitted = .{ .head = .none, .tail = .none };
switch (b.completed.tail) {
.none => b.completed.head = index,
else => |tail_index| b.storage[tail_index.toIndex()].completion.node.next = index,
}
storage.* = .{ .completion = .{ .node = .{ .next = .none }, .result = result } };
b.completed.tail = index;
return;
},
else => {},
}
const t_io = io(t);
const deadline = timeout.toTimestamp(t_io);
while (true) {
const timeout_ms: i32 = t: {
if (b.completed.head != .none) {
// It is legal to call batchWait with already completed
// operations in the ring. In such case, we need to avoid
// blocking in the poll syscall, but we can still take this
// opportunity to find additional ready operations.
break :t 0;
}
const d = deadline orelse break :t -1;
const duration = d.durationFromNow(t_io);
break :t @min(@max(0, duration.raw.toMilliseconds()), std.math.maxInt(i32));
};
const syscall = try Syscall.start();
const rc = posix.system.poll(poll_storage.slice.ptr, poll_storage.len, timeout_ms);
syscall.finish();
switch (posix.errno(rc)) {
.SUCCESS => {
if (rc == 0) {
if (b.completed.head != .none) {
// Since there are already completions available in the
// queue, this is neither a timeout nor a case for
// retrying.
return;
}
// Although spurious timeouts are OK, when no deadline is
// passed we must not return `error.Timeout`.
if (deadline == null) continue;
return error.Timeout;
}
var prev_index: Io.Operation.OptionalIndex = .none;
var index = b.submitted.head;
for (poll_storage.slice[0..poll_storage.len]) |poll_entry| {
const submission = &b.storage[index.toIndex()].submission;
const next_index = submission.node.next;
if (poll_entry.revents != 0) {
const result = try operate(t, submission.operation);
switch (prev_index) {
.none => b.submitted.head = next_index,
else => b.storage[prev_index.toIndex()].submission.node.next = next_index,
}
if (next_index == .none) b.submitted.tail = prev_index;
switch (b.completed.tail) {
.none => b.completed.head = index,
else => |tail_index| b.storage[tail_index.toIndex()].completion.node.next = index,
}
b.completed.tail = index;
b.storage[index.toIndex()] = .{ .completion = .{
.node = .{ .next = .none },
.result = result,
} };
} else prev_index = index;
index = next_index;
}
assert(index == .none);
return;
},
.INTR => continue,
else => return error.ConcurrencyUnavailable,
}
}
}
const WindowsBatchOperationUserdata = extern struct {
file: windows.HANDLE,
iosb: windows.IO_STATUS_BLOCK,
const Erased = Io.Operation.Storage.Pending.Userdata;
comptime {
assert(@sizeOf(WindowsBatchOperationUserdata) <= @sizeOf(Erased));
}
fn toErased(userdata: *WindowsBatchOperationUserdata) *Erased {
return @ptrCast(userdata);
}
fn fromErased(erased: *Erased) *WindowsBatchOperationUserdata {
return @ptrCast(erased);
}
};
fn batchCancel(userdata: ?*anyopaque, b: *Io.Batch) void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (is_windows) {
if (b.pending.head == .none) return;
waitForApcOrAlert();
var index = b.pending.head;
while (index != .none) {
const pending = &b.storage[index.toIndex()].pending;
const operation_userdata: *WindowsBatchOperationUserdata = .fromErased(&pending.userdata);
var cancel_iosb: windows.IO_STATUS_BLOCK = undefined;
_ = windows.ntdll.NtCancelIoFileEx(operation_userdata.file, &operation_userdata.iosb, &cancel_iosb);
index = pending.node.next;
}
while (b.pending.head != .none) waitForApcOrAlert();
} else if (b.userdata) |batch_userdata| {
const poll_storage: [*]posix.pollfd = @ptrCast(@alignCast(batch_userdata));
t.allocator.free(poll_storage[0..b.storage.len]);
b.userdata = null;
}
}
fn batchCompleteBlockingWindows(
b: *Io.Batch,
operation_userdata: *WindowsBatchOperationUserdata,
result: Io.Operation.Result,
) void {
const erased_userdata = operation_userdata.toErased();
const pending: *Io.Operation.Storage.Pending = @fieldParentPtr("userdata", erased_userdata);
switch (pending.node.prev) {
.none => b.pending.head = pending.node.next,
else => |prev_index| b.storage[prev_index.toIndex()].pending.node.next = pending.node.next,
}
switch (pending.node.next) {
.none => b.pending.tail = pending.node.prev,
else => |next_index| b.storage[next_index.toIndex()].pending.node.prev = pending.node.prev,
}
const storage: *Io.Operation.Storage = @fieldParentPtr("pending", pending);
const index: Io.Operation.OptionalIndex = .fromIndex(storage - b.storage.ptr);
switch (b.completed.tail) {
.none => b.completed.head = index,
else => |tail_index| b.storage[tail_index.toIndex()].completion.node.next = index,
}
b.completed.tail = index;
storage.* = .{ .completion = .{ .node = .{ .next = .none }, .result = result } };
}
fn batchApc(
apc_context: ?*anyopaque,
iosb: *windows.IO_STATUS_BLOCK,
_: windows.ULONG,
) align(apc_align) callconv(.winapi) void {
const b: *Io.Batch = @ptrCast(@alignCast(apc_context));
const operation_userdata: *WindowsBatchOperationUserdata = @fieldParentPtr("iosb", iosb);
const erased_userdata = operation_userdata.toErased();
const pending: *Io.Operation.Storage.Pending = @fieldParentPtr("userdata", erased_userdata);
switch (pending.node.prev) {
.none => b.pending.head = pending.node.next,
else => |prev_index| b.storage[prev_index.toIndex()].pending.node.next = pending.node.next,
}
switch (pending.node.next) {
.none => b.pending.tail = pending.node.prev,
else => |next_index| b.storage[next_index.toIndex()].pending.node.prev = pending.node.prev,
}
const storage: *Io.Operation.Storage = @fieldParentPtr("pending", pending);
const index: Io.Operation.OptionalIndex = .fromIndex(storage - b.storage.ptr);
switch (iosb.u.Status) {
.CANCELLED => {
const tail_index = b.unused.tail;
switch (tail_index) {
.none => b.unused.head = index,
else => b.storage[tail_index.toIndex()].unused.next = index,
}
storage.* = .{ .unused = .{ .prev = tail_index, .next = .none } };
b.unused.tail = index;
},
else => {
switch (b.completed.tail) {
.none => b.completed.head = index,
else => |tail_index| b.storage[tail_index.toIndex()].completion.node.next = index,
}
b.completed.tail = index;
const result: Io.Operation.Result = switch (pending.tag) {
.file_read_streaming => .{ .file_read_streaming = ntReadFileResult(iosb) },
.file_write_streaming => .{ .file_write_streaming = ntWriteFileResult(iosb) },
.device_io_control => .{ .device_io_control = iosb.* },
.net_receive => unreachable,
.net_send => unreachable,
.net_read => unreachable,
.net_write => unreachable,
};
storage.* = .{ .completion = .{ .node = .{ .next = .none }, .result = result } };
},
}
}
/// If `concurrency` is false, `error.ConcurrencyUnavailable` is unreachable.
fn batchDrainSubmittedWindows(t: *Threaded, b: *Io.Batch, concurrency: bool) (Io.ConcurrentError || Io.Cancelable)!void {
var index = b.submitted.head;
errdefer b.submitted.head = index;
while (index != .none) {
const storage = &b.storage[index.toIndex()];
const submission = storage.submission;
storage.* = .{ .pending = .{
.node = .{ .prev = b.pending.tail, .next = .none },
.tag = submission.operation,
.userdata = undefined,
} };
switch (b.pending.tail) {
.none => b.pending.head = index,
else => |tail_index| b.storage[tail_index.toIndex()].pending.node.next = index,
}
b.pending.tail = index;
const operation_userdata: *WindowsBatchOperationUserdata = .fromErased(&storage.pending.userdata);
errdefer {
operation_userdata.iosb = .{ .u = .{ .Status = .CANCELLED }, .Information = undefined };
batchApc(b, &operation_userdata.iosb, 0);
}
switch (submission.operation) {
.file_read_streaming => |o| o: {
var data_index: usize = 0;
while (o.data.len - data_index != 0 and o.data[data_index].len == 0) data_index += 1;
if (o.data.len - data_index == 0) {
operation_userdata.iosb = .{ .u = .{ .Status = .SUCCESS }, .Information = 0 };
batchApc(b, &operation_userdata.iosb, 0);
break :o;
}
const buffer = o.data[data_index];
const short_buffer_len = std.math.lossyCast(u32, buffer.len);
if (o.file.flags.nonblocking) {
operation_userdata.file = o.file.handle;
switch (windows.ntdll.NtReadFile(
o.file.handle,
null, // event
&batchApc,
b,
&operation_userdata.iosb,
buffer.ptr,
short_buffer_len,
null, // byte offset
null, // key
)) {
.PENDING, .SUCCESS => {},
.CANCELLED => unreachable,
else => |status| {
operation_userdata.iosb.u.Status = status;
batchApc(b, &operation_userdata.iosb, 0);
},
}
} else {
if (concurrency) return error.ConcurrencyUnavailable;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtReadFile(
o.file.handle,
null, // event
null, // APC routine
null, // APC context
&operation_userdata.iosb,
buffer.ptr,
short_buffer_len,
null, // byte offset
null, // key
)) {
.PENDING => unreachable, // unrecoverable: wrong File nonblocking flag
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => |status| {
syscall.finish();
operation_userdata.iosb.u.Status = status;
batchApc(b, &operation_userdata.iosb, 0);
break;
},
};
}
},
.file_write_streaming => |o| o: {
const buffer = windowsWriteBuffer(o.header, o.data, o.splat);
if (buffer.len == 0) {
operation_userdata.iosb = .{ .u = .{ .Status = .SUCCESS }, .Information = 0 };
batchApc(b, &operation_userdata.iosb, 0);
break :o;
}
if (o.file.flags.nonblocking) {
operation_userdata.file = o.file.handle;
switch (windows.ntdll.NtWriteFile(
o.file.handle,
null, // event
&batchApc,
b,
&operation_userdata.iosb,
buffer.ptr,
@intCast(buffer.len),
null, // byte offset
null, // key
)) {
.PENDING, .SUCCESS => {},
.CANCELLED => unreachable,
else => |status| {
operation_userdata.iosb.u.Status = status;
batchApc(b, &operation_userdata.iosb, 0);
},
}
} else {
if (concurrency) return error.ConcurrencyUnavailable;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtWriteFile(
o.file.handle,
null, // event
null, // APC routine
null, // APC context
&operation_userdata.iosb,
buffer.ptr,
@intCast(buffer.len),
null, // byte offset
null, // key
)) {
.PENDING => unreachable, // unrecoverable: wrong File nonblocking flag
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => |status| {
syscall.finish();
operation_userdata.iosb.u.Status = status;
batchApc(b, &operation_userdata.iosb, 0);
break;
},
};
}
},
.device_io_control => |o| {
const NtControlFile = switch (o.code.DeviceType) {
.FILE_SYSTEM, .NAMED_PIPE => &windows.ntdll.NtFsControlFile,
else => &windows.ntdll.NtDeviceIoControlFile,
};
if (o.file.flags.nonblocking) {
operation_userdata.file = o.file.handle;
switch (NtControlFile(
o.file.handle,
null, // event
&batchApc,
b,
&operation_userdata.iosb,
o.code,
if (o.in.len > 0) o.in.ptr else null,
@intCast(o.in.len),
if (o.out.len > 0) o.out.ptr else null,
@intCast(o.out.len),
)) {
.PENDING, .SUCCESS => {},
.CANCELLED => unreachable,
else => |status| {
operation_userdata.iosb.u.Status = status;
batchApc(b, &operation_userdata.iosb, 0);
},
}
} else {
if (concurrency) return error.ConcurrencyUnavailable;
const syscall: Syscall = try .start();
while (true) switch (NtControlFile(
o.file.handle,
null, // event
null, // APC routine
null, // APC context
&operation_userdata.iosb,
o.code,
if (o.in.len > 0) o.in.ptr else null,
@intCast(o.in.len),
if (o.out.len > 0) o.out.ptr else null,
@intCast(o.out.len),
)) {
.PENDING => unreachable, // unrecoverable: wrong File nonblocking flag
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => |status| {
syscall.finish();
operation_userdata.iosb.u.Status = status;
batchApc(b, &operation_userdata.iosb, 0);
break;
},
};
}
},
.net_receive => |*o| {
// TODO integrate with overlapped I/O or equivalent to avoid this error
if (concurrency) return error.ConcurrencyUnavailable;
batchCompleteBlockingWindows(b, operation_userdata, .{
.net_receive = netReceiveWindows(t, o.socket_handle, o.message_buffer, o.data_buffer, o.flags),
});
},
.net_send => |*o| {
// TODO integrate with overlapped I/O or equivalent to avoid this error
if (concurrency) return error.ConcurrencyUnavailable;
batchCompleteBlockingWindows(b, operation_userdata, .{
.net_send = netSendWindows(t, o.socket_handle, o.messages, o.flags),
});
},
.net_read => |*o| {
// TODO integrate with overlapped I/O or equivalent to avoid this error
if (concurrency) return error.ConcurrencyUnavailable;
batchCompleteBlockingWindows(b, operation_userdata, .{
.net_read = netRead(o.socket_handle, o.data) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| e,
},
});
},
.net_write => |*o| {
// TODO integrate with overlapped I/O or equivalent to avoid this error
if (concurrency) return error.ConcurrencyUnavailable;
batchCompleteBlockingWindows(b, operation_userdata, .{
.net_write = netWriteWindows(o.socket_handle, o.header, o.data, o.splat) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| e,
},
});
},
}
index = submission.node.next;
}
b.submitted = .{ .head = .none, .tail = .none };
}
/// Since Windows only supports writing one contiguous buffer, returns the
/// first one, while also limiting it to a length representable by 32-bit
/// unsigned integer.
fn windowsWriteBuffer(header: []const u8, data: []const []const u8, splat: usize) []const u8 {
const buffer = b: {
if (header.len != 0) break :b header;
for (data[0 .. data.len - 1]) |buffer| {
if (buffer.len != 0) break :b buffer;
}
if (splat == 0) return &.{};
break :b data[data.len - 1];
};
return buffer[0..std.math.lossyCast(u32, buffer.len)];
}
fn submitComplete(ring: []u32, complete_tail: *Io.Batch.RingIndex, op: u32) void {
const ct = complete_tail.*;
const len: u31 = @intCast(ring.len);
ring[ct.index(len)] = op;
complete_tail.* = ct.next(len);
}
const dirCreateDir = switch (native_os) {
.windows => dirCreateDirWindows,
.wasi => dirCreateDirWasi,
else => dirCreateDirPosix,
};
fn dirCreateDirPosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.mkdirat(dir.handle, sub_path_posix, permissions.toMode()))) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.ACCES => return syscall.fail(error.AccessDenied),
.PERM => return syscall.fail(error.PermissionDenied),
.DQUOT => return syscall.fail(error.DiskQuota),
.EXIST => return syscall.fail(error.PathAlreadyExists),
.LOOP => return syscall.fail(error.SymLinkLoop),
.MLINK => return syscall.fail(error.LinkQuotaExceeded),
.NAMETOOLONG => return syscall.fail(error.NameTooLong),
.NOENT => return syscall.fail(error.FileNotFound),
.NOMEM => return syscall.fail(error.SystemResources),
.NOSPC => return syscall.fail(error.NoSpaceLeft),
.NOTDIR => return syscall.fail(error.NotDir),
.ROFS => return syscall.fail(error.ReadOnlyFileSystem),
// dragonfly: when dir_fd is unlinked from filesystem
.NOTCONN => return syscall.fail(error.FileNotFound),
.ILSEQ => return syscall.fail(error.BadPathName),
.BADF => |err| return syscall.errnoBug(err), // File descriptor used after closed.
.FAULT => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
fn dirCreateDirWasi(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirError!void {
if (builtin.link_libc) return dirCreateDirPosix(userdata, dir, sub_path, permissions);
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const syscall: Syscall = try .start();
while (true) {
switch (std.os.wasi.path_create_directory(dir.handle, sub_path.ptr, sub_path.len)) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.PERM => return error.PermissionDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.FAULT => |err| return errnoBug(err),
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.ROFS => return error.ReadOnlyFileSystem,
.NOTCAPABLE => return error.AccessDenied,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirCreateDirWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
_ = permissions; // TODO use this value
const sub_path_w = try sliceToPrefixedFileW(dir.handle, sub_path, .{});
const attr: windows.OBJECT.ATTRIBUTES = .{
.RootDirectory = if (Dir.path.isAbsoluteWindowsWtf16(sub_path_w.span())) null else dir.handle,
.Attributes = .{ .INHERIT = false },
.ObjectName = @constCast(&windows.UNICODE_STRING.init(sub_path_w.span())),
.SecurityDescriptor = null,
.SecurityQualityOfService = null,
};
var sub_dir_handle: windows.HANDLE = undefined;
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var attempt: u5 = 0;
var syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtCreateFile(
&sub_dir_handle,
.{
.GENERIC = .{ .READ = true },
.STANDARD = .{ .SYNCHRONIZE = true },
},
&attr,
&io_status_block,
null,
.{ .NORMAL = true },
.VALID_FLAGS,
.CREATE,
.{
.DIRECTORY_FILE = true,
.NON_DIRECTORY_FILE = false,
.IO = .SYNCHRONOUS_NONALERT,
.OPEN_REPARSE_POINT = false,
},
null,
0,
)) {
.SUCCESS => {
syscall.finish();
windows.CloseHandle(sub_dir_handle);
return;
},
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.SHARING_VIOLATION => {
// This occurs if the file attempting to be opened is a running
// executable. However, there's a kernel bug: the error may be
// incorrectly returned for an indeterminate amount of time
// after an executable file is closed. Here we work around the
// kernel bug with retry attempts.
syscall.finish();
if (max_windows_kernel_bug_retries - attempt == 0) return error.Unexpected;
try parking_sleep.sleep(.{ .duration = .{
.raw = .fromMilliseconds((@as(u32, 1) << attempt) >> 1),
.clock = .awake,
} });
attempt += 1;
syscall = try .start();
continue;
},
.DELETE_PENDING => {
// This error means that there *was* a file in this location on
// the file system, but it was deleted. However, the OS is not
// finished with the deletion operation, and so this CreateFile
// call has failed. There is not really a sane way to handle
// this other than retrying the creation after the OS finishes
// the deletion.
syscall.finish();
if (max_windows_kernel_bug_retries - attempt == 0) return error.Unexpected;
try parking_sleep.sleep(.{ .duration = .{
.raw = .fromMilliseconds((@as(u32, 1) << attempt) >> 1),
.clock = .awake,
} });
attempt += 1;
syscall = try .start();
continue;
},
.OBJECT_NAME_INVALID => return syscall.fail(error.BadPathName),
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.BAD_NETWORK_PATH => return syscall.fail(error.NetworkNotFound), // \\server was not found
.BAD_NETWORK_NAME => return syscall.fail(error.NetworkNotFound), // \\server was found but \\server\share wasn't
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.OBJECT_NAME_COLLISION => return syscall.fail(error.PathAlreadyExists),
.NOT_A_DIRECTORY => return syscall.fail(error.NotDir),
.USER_MAPPED_FILE => return syscall.fail(error.AccessDenied),
.INVALID_PARAMETER => |status| return syscall.ntstatusBug(status),
.OBJECT_PATH_SYNTAX_BAD => |status| return syscall.ntstatusBug(status),
.INVALID_HANDLE => |status| return syscall.ntstatusBug(status),
else => |status| return syscall.unexpectedNtstatus(status),
};
}
fn dirCreateDirPath(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
permissions: Dir.Permissions,
) Dir.CreateDirPathError!Dir.CreatePathStatus {
const t: *Threaded = @ptrCast(@alignCast(userdata));
var it = Dir.path.componentIterator(sub_path);
var status: Dir.CreatePathStatus = .existed;
var component = it.last() orelse return error.BadPathName;
while (true) {
if (dirCreateDir(t, dir, component.path, permissions)) |_| {
status = .created;
} else |err| switch (err) {
error.PathAlreadyExists => {
// It is important to return an error if it's not a directory
// because otherwise a dangling symlink could cause an infinite
// loop.
const kind = try filePathKind(t, dir, component.path);
if (kind != .directory) return error.NotDir;
},
error.FileNotFound => |e| {
component = it.previous() orelse return e;
continue;
},
else => |e| return e,
}
component = it.next() orelse return status;
}
}
const dirCreateDirPathOpen = switch (native_os) {
.windows => dirCreateDirPathOpenWindows,
.wasi => dirCreateDirPathOpenWasi,
else => dirCreateDirPathOpenPosix,
};
fn dirCreateDirPathOpenPosix(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
permissions: Dir.Permissions,
options: Dir.OpenOptions,
) Dir.CreateDirPathOpenError!Dir {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const t_io = io(t);
return dirOpenDirPosix(t, dir, sub_path, options) catch |err| switch (err) {
error.FileNotFound => {
_ = try dir.createDirPathStatus(t_io, sub_path, permissions);
return dirOpenDirPosix(t, dir, sub_path, options);
},
else => |e| return e,
};
}
fn dirCreateDirPathOpenWindows(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
permissions: Dir.Permissions,
options: Dir.OpenOptions,
) Dir.CreateDirPathOpenError!Dir {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const w = windows;
_ = permissions; // TODO apply these permissions
var it = Dir.path.componentIterator(sub_path);
// If there are no components in the path, then create a dummy component with the full path.
var component: Dir.path.NativeComponentIterator.Component = it.last() orelse .{
.name = "",
.path = sub_path,
};
components: while (true) {
const sub_path_w = try sliceToPrefixedFileW(dir.handle, component.path, .{});
const attr: windows.OBJECT.ATTRIBUTES = .{
.RootDirectory = if (Dir.path.isAbsoluteWindowsWtf16(sub_path_w.span())) null else dir.handle,
.ObjectName = @constCast(&sub_path_w.string()),
};
const is_last = it.peekNext() == null;
var result: Dir = .{ .handle = undefined };
var iosb: w.IO_STATUS_BLOCK = undefined;
const syscall: Syscall = try .start();
while (true) switch (w.ntdll.NtCreateFile(
&result.handle,
.{
.SPECIFIC = .{ .FILE_DIRECTORY = .{
.LIST = options.iterate,
.READ_EA = true,
.READ_ATTRIBUTES = true,
.TRAVERSE = true,
} },
.STANDARD = .{
.RIGHTS = .READ,
.SYNCHRONIZE = true,
},
},
&attr,
&iosb,
null,
.{ .NORMAL = true },
.VALID_FLAGS,
if (is_last) .OPEN_IF else .CREATE,
.{
.DIRECTORY_FILE = true,
.IO = .SYNCHRONOUS_NONALERT,
.OPEN_FOR_BACKUP_INTENT = true,
.OPEN_REPARSE_POINT = !options.follow_symlinks,
},
null,
0,
)) {
.SUCCESS => {
syscall.finish();
component = it.next() orelse return result;
w.CloseHandle(result.handle);
continue :components;
},
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.OBJECT_NAME_INVALID => return syscall.fail(error.BadPathName),
.OBJECT_NAME_COLLISION => {
syscall.finish();
assert(!is_last);
// stat the file and return an error if it's not a directory
// this is important because otherwise a dangling symlink
// could cause an infinite loop
const fstat = try dirStatFileWindows(t, dir, component.path, .{
.follow_symlinks = options.follow_symlinks,
});
if (fstat.kind != .directory) return error.NotDir;
component = it.next().?;
continue :components;
},
.OBJECT_NAME_NOT_FOUND,
.OBJECT_PATH_NOT_FOUND,
=> {
syscall.finish();
component = it.previous() orelse return error.FileNotFound;
continue :components;
},
.NOT_A_DIRECTORY => return syscall.fail(error.NotDir),
// This can happen if the directory has 'List folder contents' permission set to 'Deny'
// and the directory is trying to be opened for iteration.
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.DISK_FULL => return syscall.fail(error.NoSpaceLeft),
.INVALID_PARAMETER => |s| return syscall.ntstatusBug(s),
else => |s| return syscall.unexpectedNtstatus(s),
};
}
}
fn dirCreateDirPathOpenWasi(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
permissions: Dir.Permissions,
options: Dir.OpenOptions,
) Dir.CreateDirPathOpenError!Dir {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const t_io = io(t);
return dirOpenDirWasi(t, dir, sub_path, options) catch |err| switch (err) {
error.FileNotFound => {
_ = try dir.createDirPathStatus(t_io, sub_path, permissions);
return dirOpenDirWasi(t, dir, sub_path, options);
},
else => |e| return e,
};
}
fn dirStat(userdata: ?*anyopaque, dir: Dir) Dir.StatError!Dir.Stat {
const t: *Threaded = @ptrCast(@alignCast(userdata));
return fileStat(t, .{
.handle = dir.handle,
.flags = .{ .nonblocking = false },
});
}
const dirStatFile = switch (native_os) {
.linux => dirStatFileLinux,
.windows => dirStatFileWindows,
.wasi => dirStatFileWasi,
else => dirStatFilePosix,
};
fn dirStatFileLinux(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.StatFileOptions,
) Dir.StatFileError!File.Stat {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const linux = std.os.linux;
const sys = if (statx_use_c) std.c else std.os.linux;
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const flags: u32 = linux.AT.NO_AUTOMOUNT |
@as(u32, if (!options.follow_symlinks) linux.AT.SYMLINK_NOFOLLOW else 0);
const syscall: Syscall = try .start();
while (true) {
var statx = std.mem.zeroes(linux.Statx);
switch (sys.errno(sys.statx(dir.handle, sub_path_posix, flags, linux_statx_request, &statx))) {
.SUCCESS => {
syscall.finish();
return statFromLinux(&statx);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => |err| return errnoBug(err), // Handled by pathToPosix() above.
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirStatFilePosix(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.StatFileOptions,
) Dir.StatFileError!File.Stat {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const flags: u32 = if (!options.follow_symlinks) posix.AT.SYMLINK_NOFOLLOW else 0;
return posixStatFile(dir.handle, sub_path_posix, flags);
}
fn posixStatFile(dir_fd: posix.fd_t, sub_path: [:0]const u8, flags: u32) Dir.StatFileError!File.Stat {
const syscall: Syscall = try .start();
while (true) {
var stat = std.mem.zeroes(posix.Stat);
switch (posix.errno(fstatat_sym(dir_fd, sub_path, &stat, flags))) {
.SUCCESS => {
syscall.finish();
return statFromPosix(&stat);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.INVAL => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.FAULT => |err| return errnoBug(err),
.NAMETOOLONG => return error.NameTooLong,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.FileNotFound,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirStatFileWindows(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.StatFileOptions,
) Dir.StatFileError!File.Stat {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const file = try dirOpenFileWindows(t, dir, sub_path, .{
.follow_symlinks = options.follow_symlinks,
});
defer windows.CloseHandle(file.handle);
return fileStatWindows(t, file);
}
fn dirStatFileWasi(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.StatFileOptions,
) Dir.StatFileError!File.Stat {
if (builtin.link_libc) return dirStatFilePosix(userdata, dir, sub_path, options);
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const wasi = std.os.wasi;
const flags: wasi.lookupflags_t = .{
.SYMLINK_FOLLOW = options.follow_symlinks,
};
var stat: wasi.filestat_t = undefined;
const syscall: Syscall = try .start();
while (true) {
switch (wasi.path_filestat_get(dir.handle, flags, sub_path.ptr, sub_path.len, &stat)) {
.SUCCESS => {
syscall.finish();
return statFromWasi(&stat);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.INVAL => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
.FAULT => |err| return errnoBug(err),
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.FileNotFound,
.NOTCAPABLE => return error.AccessDenied,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn filePathKind(t: *Threaded, dir: Dir, sub_path: []const u8) !File.Kind {
if (native_os == .linux) {
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const linux = std.os.linux;
const syscall: Syscall = try .start();
while (true) {
var statx = std.mem.zeroes(linux.Statx);
switch (linux.errno(linux.statx(
dir.handle,
sub_path_posix,
linux.AT.NO_AUTOMOUNT | linux.AT.SYMLINK_NOFOLLOW,
.{ .TYPE = true },
&statx,
))) {
.SUCCESS => {
syscall.finish();
if (!statx.mask.TYPE) return error.Unexpected;
return statxKind(statx.mode);
},
.INTR => {
try syscall.checkCancel();
continue;
},
.NOMEM => return syscall.fail(error.SystemResources),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
const stat = try dirStatFile(t, dir, sub_path, .{ .follow_symlinks = false });
return stat.kind;
}
fn fileLength(userdata: ?*anyopaque, file: File) File.LengthError!u64 {
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (native_os == .linux) {
const linux = std.os.linux;
const syscall: Syscall = try .start();
while (true) {
var statx = std.mem.zeroes(linux.Statx);
switch (linux.errno(linux.statx(file.handle, "", linux.AT.EMPTY_PATH, .{ .SIZE = true }, &statx))) {
.SUCCESS => {
syscall.finish();
if (!statx.mask.SIZE) return error.Unexpected;
return statx.size;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.LOOP => |err| return errnoBug(err),
.NAMETOOLONG => |err| return errnoBug(err),
.NOENT => |err| return errnoBug(err),
.NOMEM => return error.SystemResources,
.NOTDIR => |err| return errnoBug(err),
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
} else if (is_windows) {
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var info: windows.FILE.STANDARD_INFORMATION = undefined;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtQueryInformationFile(
file.handle,
&io_status_block,
&info,
@sizeOf(windows.FILE.STANDARD_INFORMATION),
.Standard,
)) {
.SUCCESS => break syscall.finish(),
.INVALID_PARAMETER => |err| return syscall.ntstatusBug(err),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => |s| return syscall.unexpectedNtstatus(s),
};
return @as(u64, @bitCast(info.EndOfFile));
}
const stat = try fileStat(t, file);
return stat.size;
}
const fileStat = switch (native_os) {
.linux => fileStatLinux,
.windows => fileStatWindows,
.wasi => fileStatWasi,
else => fileStatPosix,
};
fn fileStatPosix(userdata: ?*anyopaque, file: File) File.StatError!File.Stat {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (posix.Stat == void) return error.Streaming;
const syscall: Syscall = try .start();
while (true) {
var stat = std.mem.zeroes(posix.Stat);
switch (posix.errno(fstat_sym(file.handle, &stat))) {
.SUCCESS => {
syscall.finish();
return statFromPosix(&stat);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.INVAL => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn fileStatLinux(userdata: ?*anyopaque, file: File) File.StatError!File.Stat {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const linux = std.os.linux;
const sys = if (statx_use_c) std.c else std.os.linux;
const syscall: Syscall = try .start();
while (true) {
var statx = std.mem.zeroes(linux.Statx);
switch (sys.errno(sys.statx(file.handle, "", linux.AT.EMPTY_PATH, linux_statx_request, &statx))) {
.SUCCESS => {
syscall.finish();
return statFromLinux(&statx);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.LOOP => |err| return errnoBug(err),
.NAMETOOLONG => |err| return errnoBug(err),
.NOENT => |err| return errnoBug(err),
.NOMEM => return error.SystemResources,
.NOTDIR => |err| return errnoBug(err),
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn fileStatWindows(userdata: ?*anyopaque, file: File) File.StatError!File.Stat {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const block_size: u32 = if (t.systemBasicInformation()) |sbi|
@intCast(@max(sbi.PageSize, sbi.AllocationGranularity))
else
std.heap.page_size_max;
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var info: windows.FILE.ALL_INFORMATION = undefined;
{
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtQueryInformationFile(
file.handle,
&io_status_block,
&info,
@sizeOf(windows.FILE.ALL_INFORMATION),
.All,
)) {
.SUCCESS => break syscall.finish(),
// Buffer overflow here indicates that there is more information available than was able to be stored in the buffer
// size provided. This is treated as success because the type of variable-length information that this would be relevant for
// (name, volume name, etc) we don't care about.
.BUFFER_OVERFLOW => break syscall.finish(),
.INVALID_PARAMETER => |err| return syscall.ntstatusBug(err),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => |s| return syscall.unexpectedNtstatus(s),
};
}
return .{
.inode = info.InternalInformation.IndexNumber,
.size = @as(u64, @bitCast(info.StandardInformation.EndOfFile)),
.permissions = .default_file,
.kind = if (info.BasicInformation.FileAttributes.REPARSE_POINT) reparse_point: {
var tag_info: windows.FILE.ATTRIBUTE_TAG_INFO = undefined;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtQueryInformationFile(
file.handle,
&io_status_block,
&tag_info,
@sizeOf(windows.FILE.ATTRIBUTE_TAG_INFO),
.AttributeTag,
)) {
.SUCCESS => break syscall.finish(),
// INFO_LENGTH_MISMATCH and ACCESS_DENIED are the only documented possible errors
// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/d295752f-ce89-4b98-8553-266d37c84f0e
.INFO_LENGTH_MISMATCH => |err| return syscall.ntstatusBug(err),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => |s| return syscall.unexpectedNtstatus(s),
};
if (tag_info.ReparseTag.IsSurrogate) break :reparse_point .sym_link;
// Unknown reparse point
break :reparse_point .unknown;
} else if (info.BasicInformation.FileAttributes.DIRECTORY)
.directory
else
.file,
.atime = windows.fromSysTime(info.BasicInformation.LastAccessTime),
.mtime = windows.fromSysTime(info.BasicInformation.LastWriteTime),
.ctime = windows.fromSysTime(info.BasicInformation.ChangeTime),
.nlink = info.StandardInformation.NumberOfLinks,
.block_size = block_size,
};
}
fn systemBasicInformation(t: *Threaded) ?*const windows.SYSTEM.BASIC_INFORMATION {
if (!t.system_basic_information.initialized.load(.acquire)) {
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
switch (windows.ntdll.NtQuerySystemInformation(
.Basic,
&t.system_basic_information.buffer,
@sizeOf(windows.SYSTEM.BASIC_INFORMATION),
null,
)) {
.SUCCESS => {},
else => return null,
}
t.system_basic_information.initialized.store(true, .release);
}
return &t.system_basic_information.buffer;
}
fn fileStatWasi(userdata: ?*anyopaque, file: File) File.StatError!File.Stat {
if (builtin.link_libc) return fileStatPosix(userdata, file);
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const syscall: Syscall = try .start();
while (true) {
var stat: std.os.wasi.filestat_t = undefined;
switch (std.os.wasi.fd_filestat_get(file.handle, &stat)) {
.SUCCESS => {
syscall.finish();
return statFromWasi(&stat);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.INVAL => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
const dirAccess = switch (native_os) {
.windows => dirAccessWindows,
.wasi => dirAccessWasi,
else => dirAccessPosix,
};
fn dirAccessPosix(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.AccessOptions,
) Dir.AccessError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const flags: u32 = @as(u32, if (!options.follow_symlinks) posix.AT.SYMLINK_NOFOLLOW else 0);
const mode: u32 =
@as(u32, if (options.read) posix.R_OK else 0) |
@as(u32, if (options.write) posix.W_OK else 0) |
@as(u32, if (options.execute) posix.X_OK else 0);
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.faccessat(dir.handle, sub_path_posix, mode, flags))) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
.LOOP => return error.SymLinkLoop,
.TXTBSY => return error.FileBusy,
.NOTDIR => return error.FileNotFound,
.NOENT => return error.FileNotFound,
.NAMETOOLONG => return error.NameTooLong,
.INVAL => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.IO => return error.InputOutput,
.NOMEM => return error.SystemResources,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirAccessWasi(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.AccessOptions,
) Dir.AccessError!void {
if (builtin.link_libc) return dirAccessPosix(userdata, dir, sub_path, options);
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const wasi = std.os.wasi;
const flags: wasi.lookupflags_t = .{
.SYMLINK_FOLLOW = options.follow_symlinks,
};
var stat: wasi.filestat_t = undefined;
const syscall: Syscall = try .start();
while (true) {
switch (wasi.path_filestat_get(dir.handle, flags, sub_path.ptr, sub_path.len, &stat)) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.INVAL => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
.FAULT => |err| return errnoBug(err),
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.FileNotFound,
.NOTCAPABLE => return error.AccessDenied,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
if (!options.read and !options.write and !options.execute)
return;
var directory: wasi.fdstat_t = undefined;
if (wasi.fd_fdstat_get(dir.handle, &directory) != .SUCCESS)
return error.AccessDenied;
var rights: wasi.rights_t = .{};
if (options.read) {
if (stat.filetype == .DIRECTORY) {
rights.FD_READDIR = true;
} else {
rights.FD_READ = true;
}
}
if (options.write)
rights.FD_WRITE = true;
// No validation for execution.
// https://github.com/ziglang/zig/issues/18882
const rights_int: u64 = @bitCast(rights);
const inheriting_int: u64 = @bitCast(directory.fs_rights_inheriting);
if ((rights_int & inheriting_int) != rights_int)
return error.AccessDenied;
}
fn dirAccessWindows(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.AccessOptions,
) Dir.AccessError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
_ = options; // TODO
if (std.mem.eql(u8, sub_path, ".") or std.mem.eql(u8, sub_path, "..")) return;
const sub_path_w = try sliceToPrefixedFileW(dir.handle, sub_path, .{});
const attr: windows.OBJECT.ATTRIBUTES = .{
.RootDirectory = if (Dir.path.isAbsoluteWindowsWtf16(sub_path_w.span())) null else dir.handle,
.ObjectName = @constCast(&sub_path_w.string()),
};
var basic_info: windows.FILE.BASIC_INFORMATION = undefined;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtQueryAttributesFile(&attr, &basic_info)) {
.SUCCESS => return syscall.finish(),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_NAME_INVALID => |err| return syscall.ntstatusBug(err),
.INVALID_PARAMETER => |err| return syscall.ntstatusBug(err),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.OBJECT_PATH_SYNTAX_BAD => |err| return syscall.ntstatusBug(err),
else => |rc| return syscall.unexpectedNtstatus(rc),
};
}
const dirCreateFile = switch (native_os) {
.windows => dirCreateFileWindows,
.wasi => dirCreateFileWasi,
else => dirCreateFilePosix,
};
fn dirCreateFilePosix(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.CreateFileOptions,
) File.OpenError!File {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
var flags: posix.O = .{
.ACCMODE = if (options.read) .RDWR else .WRONLY,
.CREAT = true,
.TRUNC = options.truncate,
.EXCL = options.exclusive,
};
if (@hasField(posix.O, "LARGEFILE")) flags.LARGEFILE = true;
if (@hasField(posix.O, "CLOEXEC")) flags.CLOEXEC = true;
if (@hasField(posix.O, "RESOLVE_BENEATH")) flags.RESOLVE_BENEATH = options.resolve_beneath;
// Use the O locking flags if the os supports them to acquire the lock
// atomically. Note that the NONBLOCK flag is removed after the openat()
// call is successful.
if (have_flock_open_flags) switch (options.lock) {
.none => {},
.shared => {
flags.SHLOCK = true;
flags.NONBLOCK = options.lock_nonblocking;
},
.exclusive => {
flags.EXLOCK = true;
flags.NONBLOCK = options.lock_nonblocking;
},
};
const fd: posix.fd_t = fd: {
const syscall: Syscall = try .start();
while (true) {
const rc = openat_sym(dir.handle, sub_path_posix, flags, options.permissions.toMode());
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
break :fd @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.FAULT => |err| return errnoBug(err),
.INVAL => return error.BadPathName,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.ACCES => return error.AccessDenied,
.FBIG => return error.FileTooBig,
.OVERFLOW => return error.FileTooBig,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.SRCH => return error.FileNotFound, // Linux when accessing procfs.
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.EXIST => return error.PathAlreadyExists,
.BUSY => return error.DeviceBusy,
.OPNOTSUPP => return error.FileLocksUnsupported,
.AGAIN => return error.WouldBlock,
.TXTBSY => return error.FileBusy,
.NXIO => return error.NoDevice,
.ROFS => return error.ReadOnlyFileSystem,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
};
errdefer closeFd(fd);
if (have_flock and !have_flock_open_flags and options.lock != .none) {
const lock_nonblocking: i32 = if (options.lock_nonblocking) posix.LOCK.NB else 0;
const lock_flags = switch (options.lock) {
.none => unreachable,
.shared => posix.LOCK.SH | lock_nonblocking,
.exclusive => posix.LOCK.EX | lock_nonblocking,
};
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.flock(fd, lock_flags))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.INVAL => |err| return errnoBug(err), // invalid parameters
.NOLCK => return error.SystemResources,
.AGAIN => return error.WouldBlock,
.OPNOTSUPP => return error.FileLocksUnsupported,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
if (have_flock_open_flags and options.lock_nonblocking) {
var fl_flags: usize = fl: {
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.fcntl(fd, posix.F.GETFL, @as(usize, 0));
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
break :fl @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |err| {
syscall.finish();
return posix.unexpectedErrno(err);
},
}
}
};
fl_flags &= ~@as(usize, 1 << @bitOffsetOf(posix.O, "NONBLOCK"));
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.fcntl(fd, posix.F.SETFL, fl_flags))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |err| {
syscall.finish();
return posix.unexpectedErrno(err);
},
}
}
}
return .{
.handle = fd,
.flags = .{ .nonblocking = false },
};
}
fn dirCreateFileWindows(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
flags: Dir.CreateFileOptions,
) File.OpenError!File {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (std.mem.eql(u8, sub_path, ".")) return error.IsDir;
if (std.mem.eql(u8, sub_path, "..")) return error.IsDir;
const sub_path_w = try sliceToPrefixedFileW(dir.handle, sub_path, .{});
const attr: windows.OBJECT.ATTRIBUTES = .{
.RootDirectory = if (Dir.path.isAbsoluteWindowsWtf16(sub_path_w.span())) null else dir.handle,
.ObjectName = @constCast(&sub_path_w.string()),
};
const create_disposition: windows.FILE.CREATE_DISPOSITION = if (flags.exclusive)
.CREATE
else if (flags.truncate)
.OVERWRITE_IF
else
.OPEN_IF;
const access_mask: windows.ACCESS_MASK = .{
.STANDARD = .{ .SYNCHRONIZE = true },
.GENERIC = .{
.WRITE = true,
.READ = flags.read,
},
};
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var attempt: u5 = 0;
var handle: windows.HANDLE = undefined;
var syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtCreateFile(
&handle,
access_mask,
&attr,
&io_status_block,
null,
.{ .NORMAL = true },
.VALID_FLAGS, // share access
create_disposition,
.{
.NON_DIRECTORY_FILE = true,
.IO = .SYNCHRONOUS_NONALERT,
},
null,
0,
)) {
.SUCCESS => {
syscall.finish();
break;
},
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.SHARING_VIOLATION => {
// This occurs if the file attempting to be opened is a running
// executable. However, there's a kernel bug: the error may be
// incorrectly returned for an indeterminate amount of time
// after an executable file is closed. Here we work around the
// kernel bug with retry attempts.
syscall.finish();
if (max_windows_kernel_bug_retries - attempt == 0) return error.FileBusy;
try parking_sleep.sleep(.{ .duration = .{
.raw = .fromMilliseconds((@as(u32, 1) << attempt) >> 1),
.clock = .awake,
} });
attempt += 1;
syscall = try .start();
continue;
},
.DELETE_PENDING => {
// This error means that there *was* a file in this location on
// the file system, but it was deleted. However, the OS is not
// finished with the deletion operation, and so this CreateFile
// call has failed. Here, we simulate the kernel bug being
// fixed by sleeping and retrying until the error goes away.
syscall.finish();
if (max_windows_kernel_bug_retries - attempt == 0) return error.FileBusy;
try parking_sleep.sleep(.{ .duration = .{
.raw = .fromMilliseconds((@as(u32, 1) << attempt) >> 1),
.clock = .awake,
} });
attempt += 1;
syscall = try .start();
continue;
},
.OBJECT_NAME_INVALID => return syscall.fail(error.BadPathName),
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.BAD_NETWORK_PATH => return syscall.fail(error.NetworkNotFound), // \\server was not found
.BAD_NETWORK_NAME => return syscall.fail(error.NetworkNotFound), // \\server was found but \\server\share wasn't
.NO_MEDIA_IN_DEVICE => return syscall.fail(error.NoDevice),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.PIPE_BUSY => return syscall.fail(error.PipeBusy),
.PIPE_NOT_AVAILABLE => return syscall.fail(error.NoDevice),
.OBJECT_NAME_COLLISION => return syscall.fail(error.PathAlreadyExists),
.FILE_IS_A_DIRECTORY => return syscall.fail(error.IsDir),
.NOT_A_DIRECTORY => return syscall.fail(error.NotDir),
.USER_MAPPED_FILE => return syscall.fail(error.AccessDenied),
.VIRUS_INFECTED, .VIRUS_DELETED => return syscall.fail(error.AntivirusInterference),
.DISK_FULL => return syscall.fail(error.NoSpaceLeft),
.INVALID_PARAMETER => |status| return syscall.ntstatusBug(status),
.OBJECT_PATH_SYNTAX_BAD => |status| return syscall.ntstatusBug(status),
.INVALID_HANDLE => |status| return syscall.ntstatusBug(status),
else => |status| return syscall.unexpectedNtstatus(status),
};
errdefer windows.CloseHandle(handle);
const exclusive = switch (flags.lock) {
.none => return .{
.handle = handle,
.flags = .{ .nonblocking = false },
},
.shared => false,
.exclusive => true,
};
syscall = try .start();
while (true) switch (windows.ntdll.NtLockFile(
handle,
null,
null,
null,
&io_status_block,
&windows_lock_range_off,
&windows_lock_range_len,
null,
.fromBool(flags.lock_nonblocking),
.fromBool(exclusive),
)) {
.SUCCESS => {
syscall.finish();
return .{
.handle = handle,
.flags = .{ .nonblocking = false },
};
},
.INSUFFICIENT_RESOURCES => return syscall.fail(error.SystemResources),
.LOCK_NOT_GRANTED => return syscall.fail(error.WouldBlock),
.ACCESS_VIOLATION => |err| return syscall.ntstatusBug(err), // bad io_status_block pointer
else => |status| return syscall.unexpectedNtstatus(status),
};
}
fn dirCreateFileWasi(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
flags: Dir.CreateFileOptions,
) File.OpenError!File {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const wasi = std.os.wasi;
const lookup_flags: wasi.lookupflags_t = .{};
const oflags: wasi.oflags_t = .{
.CREAT = true,
.TRUNC = flags.truncate,
.EXCL = flags.exclusive,
};
const fdflags: wasi.fdflags_t = .{};
const base: wasi.rights_t = .{
.FD_READ = flags.read,
.FD_WRITE = true,
.FD_DATASYNC = true,
.FD_SEEK = true,
.FD_TELL = true,
.FD_FDSTAT_SET_FLAGS = true,
.FD_SYNC = true,
.FD_ALLOCATE = true,
.FD_ADVISE = true,
.FD_FILESTAT_SET_TIMES = true,
.FD_FILESTAT_SET_SIZE = true,
.FD_FILESTAT_GET = true,
// POLL_FD_READWRITE only grants extra rights if the corresponding FD_READ and/or
// FD_WRITE is also set.
.POLL_FD_READWRITE = true,
};
const inheriting: wasi.rights_t = .{};
var fd: posix.fd_t = undefined;
const syscall: Syscall = try .start();
while (true) {
switch (wasi.path_open(dir.handle, lookup_flags, sub_path.ptr, sub_path.len, oflags, base, inheriting, fdflags, &fd)) {
.SUCCESS => {
syscall.finish();
return .{
.handle = fd,
.flags = .{ .nonblocking = false },
};
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.FAULT => |err| return errnoBug(err),
.INVAL => return error.BadPathName,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.ACCES => return error.AccessDenied,
.FBIG => return error.FileTooBig,
.OVERFLOW => return error.FileTooBig,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.EXIST => return error.PathAlreadyExists,
.BUSY => return error.DeviceBusy,
.NOTCAPABLE => return error.AccessDenied,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirCreateFileAtomic(
userdata: ?*anyopaque,
dir: Dir,
dest_path: []const u8,
options: Dir.CreateFileAtomicOptions,
) Dir.CreateFileAtomicError!File.Atomic {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const t_io = io(t);
// Linux has O_TMPFILE, but linkat() does not support AT_REPLACE, so it's
// useless when we have to make up a bogus path name to do the rename()
// anyway.
if (native_os == .linux and !options.replace) tmpfile: {
const flags: posix.O = if (@hasField(posix.O, "TMPFILE")) .{
.ACCMODE = .RDWR,
.TMPFILE = true,
.DIRECTORY = true,
.CLOEXEC = true,
} else if (@hasField(posix.O, "TMPFILE0") and !@hasField(posix.O, "TMPFILE2")) .{
.ACCMODE = .RDWR,
.TMPFILE0 = true,
.TMPFILE1 = true,
.DIRECTORY = true,
.CLOEXEC = true,
} else break :tmpfile;
const dest_dirname = Dir.path.dirname(dest_path);
if (dest_dirname) |dirname| {
// This has a nice side effect of preemptively triggering EISDIR or
// ENOENT, avoiding the ambiguity below.
if (options.make_path) dir.createDirPath(t_io, dirname) catch |err| switch (err) {
// None of these make sense in this context.
error.IsDir,
error.Streaming,
error.DiskQuota,
error.PathAlreadyExists,
error.LinkQuotaExceeded,
error.PipeBusy,
error.FileTooBig,
error.DeviceBusy,
error.FileLocksUnsupported,
error.FileBusy,
=> return error.Unexpected,
else => |e| return e,
};
}
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(dest_dirname orelse ".", &path_buffer);
const syscall: Syscall = try .start();
while (true) {
const rc = openat_sym(dir.handle, sub_path_posix, flags, options.permissions.toMode());
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
return .{
.file = .{
.handle = @intCast(rc),
.flags = .{ .nonblocking = false },
},
.file_basename_hex = 0,
.dest_sub_path = dest_path,
.file_open = true,
.file_exists = false,
.close_dir_on_deinit = false,
.dir = dir,
};
},
.INTR => {
try syscall.checkCancel();
continue;
},
.ISDIR, .NOENT, .OPNOTSUPP => {
// Ambiguous error code. It might mean the file system
// does not support O_TMPFILE. Therefore, we must fall
// back to not using O_TMPFILE.
syscall.finish();
break :tmpfile;
},
.INVAL => return syscall.fail(error.BadPathName),
.ACCES => return syscall.fail(error.AccessDenied),
.LOOP => return syscall.fail(error.SymLinkLoop),
.MFILE => return syscall.fail(error.ProcessFdQuotaExceeded),
.NAMETOOLONG => return syscall.fail(error.NameTooLong),
.NFILE => return syscall.fail(error.SystemFdQuotaExceeded),
.NODEV => return syscall.fail(error.NoDevice),
.NOMEM => return syscall.fail(error.SystemResources),
.NOSPC => return syscall.fail(error.NoSpaceLeft),
.NOTDIR => return syscall.fail(error.NotDir),
.PERM => return syscall.fail(error.PermissionDenied),
.AGAIN => return syscall.fail(error.WouldBlock),
.NXIO => return syscall.fail(error.NoDevice),
.ILSEQ => return syscall.fail(error.BadPathName),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
if (Dir.path.dirname(dest_path)) |dirname| {
const new_dir = if (options.make_path)
dir.createDirPathOpen(t_io, dirname, .{}) catch |err| switch (err) {
// None of these make sense in this context.
error.IsDir,
error.Streaming,
error.DiskQuota,
error.PathAlreadyExists,
error.LinkQuotaExceeded,
error.PipeBusy,
error.FileTooBig,
error.FileLocksUnsupported,
error.DeviceBusy,
=> return error.Unexpected,
else => |e| return e,
}
else
try dir.openDir(t_io, dirname, .{});
return atomicFileInit(t_io, Dir.path.basename(dest_path), options.permissions, new_dir, true);
}
return atomicFileInit(t_io, dest_path, options.permissions, dir, false);
}
fn atomicFileInit(
t_io: Io,
dest_basename: []const u8,
permissions: File.Permissions,
dir: Dir,
close_dir_on_deinit: bool,
) Dir.CreateFileAtomicError!File.Atomic {
while (true) {
var random_integer: u64 = undefined;
t_io.random(@ptrCast(&random_integer));
const tmp_sub_path = std.fmt.hex(random_integer);
const file = dir.createFile(t_io, &tmp_sub_path, .{
.permissions = permissions,
.exclusive = true,
}) catch |err| switch (err) {
error.PathAlreadyExists => continue,
error.DeviceBusy => continue,
error.FileBusy => continue,
error.IsDir => return error.Unexpected, // No path components.
error.FileTooBig => return error.Unexpected, // Creating, not opening.
error.FileLocksUnsupported => return error.Unexpected, // Not asking for locks.
error.PipeBusy => return error.Unexpected, // Not opening a pipe.
else => |e| return e,
};
return .{
.file = file,
.file_basename_hex = random_integer,
.dest_sub_path = dest_basename,
.file_open = true,
.file_exists = true,
.close_dir_on_deinit = close_dir_on_deinit,
.dir = dir,
};
}
}
const dirOpenFile = switch (native_os) {
.windows => dirOpenFileWindows,
.wasi => dirOpenFileWasi,
else => dirOpenFilePosix,
};
fn dirOpenFilePosix(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.OpenFileOptions,
) File.OpenError!File {
const t: *Threaded = @ptrCast(@alignCast(userdata));
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
var flags: posix.O = switch (native_os) {
.wasi => .{
.read = options.mode != .write_only,
.write = options.mode != .read_only,
.NOFOLLOW = !options.follow_symlinks,
},
else => .{
.ACCMODE = switch (options.mode) {
.read_only => .RDONLY,
.write_only => .WRONLY,
.read_write => .RDWR,
},
.NOFOLLOW = !options.follow_symlinks,
},
};
if (@hasField(posix.O, "CLOEXEC")) flags.CLOEXEC = true;
if (@hasField(posix.O, "LARGEFILE")) flags.LARGEFILE = true;
if (@hasField(posix.O, "NOCTTY")) flags.NOCTTY = !options.allow_ctty;
if (@hasField(posix.O, "PATH")) flags.PATH = options.path_only;
if (@hasField(posix.O, "RESOLVE_BENEATH")) flags.RESOLVE_BENEATH = options.resolve_beneath;
// Use the O locking options if the os supports them to acquire the lock
// atomically. Note that the NONBLOCK flag is removed after the openat()
// call is successful.
if (have_flock_open_flags) switch (options.lock) {
.none => {},
.shared => {
flags.SHLOCK = true;
flags.NONBLOCK = options.lock_nonblocking;
},
.exclusive => {
flags.EXLOCK = true;
flags.NONBLOCK = options.lock_nonblocking;
},
};
const mode: posix.mode_t = 0;
const fd: posix.fd_t = fd: {
const syscall: Syscall = try .start();
while (true) {
const rc = openat_sym(dir.handle, sub_path_posix, flags, mode);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
break :fd @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.FAULT => |err| return errnoBug(err),
.INVAL => return error.BadPathName,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.ACCES => return error.AccessDenied,
.FBIG => return error.FileTooBig,
.OVERFLOW => return error.FileTooBig,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.SRCH => return error.FileNotFound, // Linux when opening procfs files.
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.EXIST => return error.PathAlreadyExists,
.BUSY => return error.DeviceBusy,
.OPNOTSUPP => return error.FileLocksUnsupported,
.AGAIN => return error.WouldBlock,
.TXTBSY => return error.FileBusy,
.NXIO => return error.NoDevice,
.ROFS => return error.ReadOnlyFileSystem,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
};
errdefer closeFd(fd);
if (!options.allow_directory) {
const is_dir = is_dir: {
const stat = fileStat(t, .{
.handle = fd,
.flags = .{ .nonblocking = false },
}) catch |err| switch (err) {
// The directory-ness is either unknown or unknowable
error.Streaming => break :is_dir false,
else => |e| return e,
};
break :is_dir stat.kind == .directory;
};
if (is_dir) return error.IsDir;
}
if (have_flock and !have_flock_open_flags and options.lock != .none) {
const lock_nonblocking: i32 = if (options.lock_nonblocking) posix.LOCK.NB else 0;
const lock_flags = switch (options.lock) {
.none => unreachable,
.shared => posix.LOCK.SH | lock_nonblocking,
.exclusive => posix.LOCK.EX | lock_nonblocking,
};
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.flock(fd, lock_flags))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.INVAL => |err| return errnoBug(err), // invalid parameters
.NOLCK => return error.SystemResources,
.AGAIN => return error.WouldBlock,
.OPNOTSUPP => return error.FileLocksUnsupported,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
if (have_flock_open_flags and options.lock_nonblocking) {
var fl_flags: usize = fl: {
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.fcntl(fd, posix.F.GETFL, @as(usize, 0));
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
break :fl @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |err| {
syscall.finish();
return posix.unexpectedErrno(err);
},
}
}
};
fl_flags &= ~@as(usize, 1 << @bitOffsetOf(posix.O, "NONBLOCK"));
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.fcntl(fd, posix.F.SETFL, fl_flags))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |err| {
syscall.finish();
return posix.unexpectedErrno(err);
},
}
}
}
return .{
.handle = fd,
.flags = .{ .nonblocking = false },
};
}
fn dirOpenFileWindows(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
flags: Dir.OpenFileOptions,
) File.OpenError!File {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const sub_path_w_array = try sliceToPrefixedFileW(dir.handle, sub_path, .{});
const sub_path_w = sub_path_w_array.span();
const dir_handle = if (Dir.path.isAbsoluteWindowsWtf16(sub_path_w)) null else dir.handle;
return dirOpenFileWtf16(dir_handle, sub_path_w, flags);
}
pub fn dirOpenFileWtf16(
dir_handle: ?windows.HANDLE,
sub_path_w: []const u16,
flags: Dir.OpenFileOptions,
) File.OpenError!File {
const allow_directory = flags.allow_directory and !flags.isWrite();
if (!allow_directory and std.mem.eql(u16, sub_path_w, &.{'.'})) return error.IsDir;
if (!allow_directory and std.mem.eql(u16, sub_path_w, &.{ '.', '.' })) return error.IsDir;
const w = windows;
var io_status_block: w.IO_STATUS_BLOCK = undefined;
var attempt: u5 = 0;
var syscall: Syscall = try .start();
const handle = while (true) {
var result: w.HANDLE = undefined;
switch (w.ntdll.NtCreateFile(
&result,
.{
.STANDARD = .{ .SYNCHRONIZE = true },
.GENERIC = .{
.READ = flags.isRead(),
.WRITE = flags.isWrite(),
},
},
&.{
.RootDirectory = dir_handle,
.ObjectName = @constCast(&w.UNICODE_STRING.init(sub_path_w)),
},
&io_status_block,
null,
.{ .NORMAL = true },
.VALID_FLAGS,
.OPEN,
.{
.IO = .SYNCHRONOUS_NONALERT,
.NON_DIRECTORY_FILE = !allow_directory,
.OPEN_REPARSE_POINT = !flags.follow_symlinks,
},
null,
0,
)) {
.SUCCESS => {
syscall.finish();
break result;
},
.OBJECT_NAME_INVALID => return syscall.fail(error.BadPathName),
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.BAD_NETWORK_PATH => return syscall.fail(error.NetworkNotFound), // \\server was not found
.BAD_NETWORK_NAME => return syscall.fail(error.NetworkNotFound), // \\server was found but \\server\share wasn't
.NO_MEDIA_IN_DEVICE => return syscall.fail(error.NoDevice),
.INVALID_PARAMETER => |err| return syscall.ntstatusBug(err),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.SHARING_VIOLATION => {
// This occurs if the file attempting to be opened is a running
// executable. However, there's a kernel bug: the error may be
// incorrectly returned for an indeterminate amount of time
// after an executable file is closed. Here we work around the
// kernel bug with retry attempts.
syscall.finish();
if (max_windows_kernel_bug_retries - attempt == 0) return error.FileBusy;
try parking_sleep.sleep(.{ .duration = .{
.raw = .fromMilliseconds((@as(u32, 1) << attempt) >> 1),
.clock = .awake,
} });
attempt += 1;
syscall = try .start();
continue;
},
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.PIPE_BUSY => return syscall.fail(error.PipeBusy),
.PIPE_NOT_AVAILABLE => return syscall.fail(error.NoDevice),
.OBJECT_PATH_SYNTAX_BAD => |err| return syscall.ntstatusBug(err),
.OBJECT_NAME_COLLISION => return syscall.fail(error.PathAlreadyExists),
.FILE_IS_A_DIRECTORY => return syscall.fail(error.IsDir),
.NOT_A_DIRECTORY => return syscall.fail(error.NotDir),
.USER_MAPPED_FILE => return syscall.fail(error.AccessDenied),
.INVALID_HANDLE => |err| return syscall.ntstatusBug(err),
.DELETE_PENDING => {
// This error means that there *was* a file in this location on
// the file system, but it was deleted. However, the OS is not
// finished with the deletion operation, and so this CreateFile
// call has failed. Here, we simulate the kernel bug being
// fixed by sleeping and retrying until the error goes away.
syscall.finish();
if (max_windows_kernel_bug_retries - attempt == 0) return error.FileBusy;
try parking_sleep.sleep(.{ .duration = .{
.raw = .fromMilliseconds((@as(u32, 1) << attempt) >> 1),
.clock = .awake,
} });
attempt += 1;
syscall = try .start();
continue;
},
.VIRUS_INFECTED, .VIRUS_DELETED => return syscall.fail(error.AntivirusInterference),
else => |rc| return syscall.unexpectedNtstatus(rc),
}
};
errdefer w.CloseHandle(handle);
const exclusive = switch (flags.lock) {
.none => return .{
.handle = handle,
.flags = .{ .nonblocking = false },
},
.shared => false,
.exclusive => true,
};
syscall = try .start();
while (true) switch (w.ntdll.NtLockFile(
handle,
null,
null,
null,
&io_status_block,
&windows_lock_range_off,
&windows_lock_range_len,
null,
.fromBool(flags.lock_nonblocking),
.fromBool(exclusive),
)) {
.SUCCESS => break syscall.finish(),
.INSUFFICIENT_RESOURCES => return syscall.fail(error.SystemResources),
.LOCK_NOT_GRANTED => return syscall.fail(error.WouldBlock),
.ACCESS_VIOLATION => |err| return syscall.ntstatusBug(err), // bad io_status_block pointer
else => |status| return syscall.unexpectedNtstatus(status),
};
return .{
.handle = handle,
.flags = .{ .nonblocking = false },
};
}
fn dirOpenFileWasi(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
flags: Dir.OpenFileOptions,
) File.OpenError!File {
if (builtin.link_libc) return dirOpenFilePosix(userdata, dir, sub_path, flags);
const t: *Threaded = @ptrCast(@alignCast(userdata));
const wasi = std.os.wasi;
var base: std.os.wasi.rights_t = .{};
// POLL_FD_READWRITE only grants extra rights if the corresponding FD_READ and/or FD_WRITE
// is also set.
if (flags.isRead()) {
base.FD_READ = true;
base.FD_TELL = true;
base.FD_SEEK = true;
base.FD_FILESTAT_GET = true;
base.POLL_FD_READWRITE = true;
}
if (flags.isWrite()) {
base.FD_WRITE = true;
base.FD_TELL = true;
base.FD_SEEK = true;
base.FD_DATASYNC = true;
base.FD_FDSTAT_SET_FLAGS = true;
base.FD_SYNC = true;
base.FD_ALLOCATE = true;
base.FD_ADVISE = true;
base.FD_FILESTAT_SET_TIMES = true;
base.FD_FILESTAT_SET_SIZE = true;
base.POLL_FD_READWRITE = true;
}
const lookup_flags: wasi.lookupflags_t = .{};
const oflags: wasi.oflags_t = .{};
const inheriting: wasi.rights_t = .{};
const fdflags: wasi.fdflags_t = .{};
var fd: posix.fd_t = undefined;
const syscall: Syscall = try .start();
while (true) {
switch (wasi.path_open(dir.handle, lookup_flags, sub_path.ptr, sub_path.len, oflags, base, inheriting, fdflags, &fd)) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.FAULT => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.ACCES => return error.AccessDenied,
.FBIG => return error.FileTooBig,
.OVERFLOW => return error.FileTooBig,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.BUSY => return error.DeviceBusy,
.NOTCAPABLE => return error.AccessDenied,
.NAMETOOLONG => return error.NameTooLong,
.INVAL => return error.BadPathName,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
errdefer closeFd(fd);
if (!flags.allow_directory) {
const is_dir = is_dir: {
const stat = fileStat(t, .{ .handle = fd, .flags = .{ .nonblocking = false } }) catch |err| switch (err) {
// The directory-ness is either unknown or unknowable
error.Streaming => break :is_dir false,
else => |e| return e,
};
break :is_dir stat.kind == .directory;
};
if (is_dir) return error.IsDir;
}
return .{
.handle = fd,
.flags = .{ .nonblocking = false },
};
}
const dirOpenDir = switch (native_os) {
.wasi => dirOpenDirWasi,
.haiku => dirOpenDirHaiku,
else => dirOpenDirPosix,
};
/// This function is also used for WASI when libc is linked.
fn dirOpenDirPosix(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.OpenOptions,
) Dir.OpenError!Dir {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) {
const sub_path_w = try sliceToPrefixedFileW(dir.handle, sub_path, .{});
return dirOpenDirWindows(dir, sub_path_w.span(), options);
}
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
var flags: posix.O = switch (native_os) {
.wasi => .{
.read = true,
.NOFOLLOW = !options.follow_symlinks,
.DIRECTORY = true,
},
else => .{
.ACCMODE = .RDONLY,
.NOFOLLOW = !options.follow_symlinks,
.DIRECTORY = true,
.CLOEXEC = true,
},
};
if (@hasField(posix.O, "PATH") and !options.iterate)
flags.PATH = true;
const mode: posix.mode_t = 0;
const syscall: Syscall = try .start();
while (true) {
const rc = openat_sym(dir.handle, sub_path_posix, flags, mode);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
return .{ .handle = @intCast(rc) };
},
.INTR => {
try syscall.checkCancel();
continue;
},
.INVAL => return syscall.fail(error.BadPathName),
.ACCES => return syscall.fail(error.AccessDenied),
.LOOP => return syscall.fail(error.SymLinkLoop),
.MFILE => return syscall.fail(error.ProcessFdQuotaExceeded),
.NAMETOOLONG => return syscall.fail(error.NameTooLong),
.NFILE => return syscall.fail(error.SystemFdQuotaExceeded),
.NODEV => return syscall.fail(error.NoDevice),
.NOENT => return syscall.fail(error.FileNotFound),
.NOMEM => return syscall.fail(error.SystemResources),
.NOTDIR => return syscall.fail(error.NotDir),
.PERM => return syscall.fail(error.PermissionDenied),
.NXIO => return syscall.fail(error.NoDevice),
.ILSEQ => return syscall.fail(error.BadPathName),
.FAULT => |err| return syscall.errnoBug(err),
.BADF => |err| return syscall.errnoBug(err), // File descriptor used after closed.
.BUSY => |err| return syscall.errnoBug(err), // O_EXCL not passed
else => |err| return syscall.unexpectedErrno(err),
}
}
}
fn dirOpenDirHaiku(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.OpenOptions,
) Dir.OpenError!Dir {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
_ = options;
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system._kern_open_dir(dir.handle, sub_path_posix);
if (rc >= 0) {
syscall.finish();
return .{ .handle = rc };
}
switch (@as(posix.E, @fromBackingInt(@intCast(rc)))) {
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.ACCES => return error.AccessDenied,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.BUSY => |err| return errnoBug(err),
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
pub fn dirOpenDirWindows(
dir: Dir,
sub_path_w: []const u16,
options: Dir.OpenOptions,
) Dir.OpenError!Dir {
const w = windows;
var io_status_block: w.IO_STATUS_BLOCK = undefined;
var result: Dir = .{ .handle = undefined };
const attr: w.OBJECT.ATTRIBUTES = .{
.RootDirectory = if (Dir.path.isAbsoluteWindowsWtf16(sub_path_w)) null else dir.handle,
.ObjectName = @constCast(&w.UNICODE_STRING.init(sub_path_w)),
};
const syscall: Syscall = try .start();
while (true) switch (w.ntdll.NtCreateFile(
&result.handle,
// TODO remove some of these flags if options.access_sub_paths is false
.{
.SPECIFIC = .{ .FILE_DIRECTORY = .{
.LIST = options.iterate,
.READ_EA = true,
.TRAVERSE = true,
.READ_ATTRIBUTES = true,
} },
.STANDARD = .{
.RIGHTS = .READ,
.SYNCHRONIZE = true,
},
},
&attr,
&io_status_block,
null,
.{ .NORMAL = true },
.VALID_FLAGS,
.OPEN,
.{
.DIRECTORY_FILE = true,
.IO = .SYNCHRONOUS_NONALERT,
.OPEN_FOR_BACKUP_INTENT = true,
.OPEN_REPARSE_POINT = !options.follow_symlinks,
},
null,
0,
)) {
.SUCCESS => {
syscall.finish();
return result;
},
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.OBJECT_NAME_INVALID => return syscall.fail(error.BadPathName),
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_NAME_COLLISION => |err| return w.statusBug(err),
.OBJECT_PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.NOT_A_DIRECTORY => return syscall.fail(error.NotDir),
// This can happen if the directory has 'List folder contents' permission set to 'Deny'
// and the directory is trying to be opened for iteration.
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.INVALID_PARAMETER => |err| return syscall.ntstatusBug(err),
else => |rc| return syscall.unexpectedNtstatus(rc),
};
}
fn dirClose(userdata: ?*anyopaque, dirs: []const Dir) void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
for (dirs) |dir| {
if (is_windows) {
windows.CloseHandle(dir.handle);
} else {
closeFd(dir.handle);
}
}
}
const dirRead = switch (native_os) {
.linux => dirReadLinux,
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => dirReadDarwin,
.freebsd, .netbsd, .dragonfly, .openbsd => dirReadBsd,
.illumos => dirReadIllumos,
.haiku => dirReadHaiku,
.windows => dirReadWindows,
.wasi => dirReadWasi,
else => dirReadUnimplemented,
};
fn dirReadLinux(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usize {
const linux = std.os.linux;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var buffer_index: usize = 0;
while (buffer.len - buffer_index != 0) {
if (dr.end - dr.index == 0) {
// Refill the buffer, unless we've already created references to
// buffered data.
if (buffer_index != 0) break;
if (dr.state == .reset) {
posixSeekTo(dr.dir.handle, 0) catch |err| switch (err) {
error.Unseekable => return error.Unexpected,
else => |e| return e,
};
dr.state = .reading;
}
const syscall: Syscall = try .start();
const n = while (true) {
const rc = linux.getdents64(dr.dir.handle, dr.buffer.ptr, @min(dr.buffer.len, std.math.maxInt(c_uint)));
switch (linux.errno(rc)) {
.SUCCESS => {
syscall.finish();
break rc;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // Dir is invalid or was opened without iteration ability.
.FAULT => |err| return errnoBug(err),
.NOTDIR => |err| return errnoBug(err),
// To be consistent across platforms, iteration
// ends if the directory being iterated is deleted
// during iteration. This matches the behavior of
// non-Linux, non-WASI UNIX platforms.
.NOENT => {
dr.state = .finished;
return 0;
},
// This can occur when reading /proc/$PID/net, or
// if the provided buffer is too small. Neither
// scenario is intended to be handled by this API.
.INVAL => return error.Unexpected,
.ACCES => return error.AccessDenied, // Lacking permission to iterate this directory.
else => |err| return posix.unexpectedErrno(err),
}
},
}
};
if (n == 0) {
dr.state = .finished;
return 0;
}
dr.index = 0;
dr.end = n;
}
// Linux aligns the header by padding after the null byte of the name
// to align the next entry. This means we can find the end of the name
// by looking at only the 8 bytes before the next record. However since
// file names are usually short it's better to keep the machine code
// simpler.
//
// Furthermore, I observed qemu user mode to not align this struct, so
// this code makes the conservative choice to not assume alignment.
const linux_entry: *align(1) linux.dirent64 = @ptrCast(&dr.buffer[dr.index]);
const next_index = dr.index + linux_entry.reclen;
dr.index = next_index;
const name_ptr: [*]u8 = &linux_entry.name;
const padded_name = name_ptr[0 .. linux_entry.reclen - @offsetOf(linux.dirent64, "name")];
const name_len = std.mem.findScalar(u8, padded_name, 0).?;
const name = name_ptr[0..name_len :0];
if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue;
const entry_kind: File.Kind = switch (linux_entry.type) {
linux.DT.BLK => .block_device,
linux.DT.CHR => .character_device,
linux.DT.DIR => .directory,
linux.DT.FIFO => .named_pipe,
linux.DT.LNK => .sym_link,
linux.DT.REG => .file,
linux.DT.SOCK => .unix_domain_socket,
else => .unknown,
};
buffer[buffer_index] = .{
.name = name,
.kind = entry_kind,
.inode = linux_entry.ino,
};
buffer_index += 1;
}
return buffer_index;
}
fn dirReadDarwin(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const Header = extern struct {
seek: i64,
};
const header: *Header = @ptrCast(dr.buffer.ptr);
const header_end: usize = @sizeOf(Header);
if (dr.index < header_end) {
// Initialize header.
dr.index = header_end;
dr.end = header_end;
header.* = .{ .seek = 0 };
}
var buffer_index: usize = 0;
while (buffer.len - buffer_index != 0) {
if (dr.end - dr.index == 0) {
// Refill the buffer, unless we've already created references to
// buffered data.
if (buffer_index != 0) break;
if (dr.state == .reset) {
posixSeekTo(dr.dir.handle, 0) catch |err| switch (err) {
error.Unseekable => return error.Unexpected,
else => |e| return e,
};
dr.state = .reading;
}
const dents_buffer = dr.buffer[header_end..];
const syscall: Syscall = try .start();
const n: usize = while (true) {
const rc = posix.system.getdirentries(dr.dir.handle, dents_buffer.ptr, dents_buffer.len, &header.seek);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
break @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // Dir is invalid or was opened without iteration ability.
.FAULT => |err| return errnoBug(err),
.NOTDIR => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
else => |err| return posix.unexpectedErrno(err),
}
},
}
};
if (n == 0) {
dr.state = .finished;
return 0;
}
dr.index = header_end;
dr.end = header_end + n;
}
const darwin_entry = @as(*align(1) posix.system.dirent, @ptrCast(&dr.buffer[dr.index]));
const next_index = dr.index + darwin_entry.reclen;
dr.index = next_index;
const name = @as([*]u8, @ptrCast(&darwin_entry.name))[0..darwin_entry.namlen];
if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..") or (darwin_entry.ino == 0))
continue;
const entry_kind: File.Kind = switch (darwin_entry.type) {
posix.DT.BLK => .block_device,
posix.DT.CHR => .character_device,
posix.DT.DIR => .directory,
posix.DT.FIFO => .named_pipe,
posix.DT.LNK => .sym_link,
posix.DT.REG => .file,
posix.DT.SOCK => .unix_domain_socket,
posix.DT.WHT => .whiteout,
else => .unknown,
};
buffer[buffer_index] = .{
.name = name,
.kind = entry_kind,
.inode = darwin_entry.ino,
};
buffer_index += 1;
}
return buffer_index;
}
fn dirReadBsd(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var buffer_index: usize = 0;
while (buffer.len - buffer_index != 0) {
if (dr.end - dr.index == 0) {
// Refill the buffer, unless we've already created references to
// buffered data.
if (buffer_index != 0) break;
if (dr.state == .reset) {
posixSeekTo(dr.dir.handle, 0) catch |err| switch (err) {
error.Unseekable => return error.Unexpected,
else => |e| return e,
};
dr.state = .reading;
}
const syscall: Syscall = try .start();
const n: usize = while (true) {
const rc = posix.system.getdents(dr.dir.handle, dr.buffer.ptr, dr.buffer.len);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
break @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // Dir is invalid or was opened without iteration ability
.FAULT => |err| return errnoBug(err),
.NOTDIR => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
// Introduced in freebsd 13.2: directory unlinked
// but still open. To be consistent, iteration ends
// if the directory being iterated is deleted
// during iteration.
.NOENT => {
dr.state = .finished;
return 0;
},
else => |err| return posix.unexpectedErrno(err),
}
},
}
};
if (n == 0) {
dr.state = .finished;
return 0;
}
dr.index = 0;
dr.end = n;
}
const bsd_entry = @as(*align(1) posix.system.dirent, @ptrCast(&dr.buffer[dr.index]));
const next_index = dr.index +
if (@hasField(posix.system.dirent, "reclen")) bsd_entry.reclen else bsd_entry.reclen();
dr.index = next_index;
const name = @as([*]u8, @ptrCast(&bsd_entry.name))[0..bsd_entry.namlen];
const skip_zero_fileno = switch (native_os) {
// fileno=0 is used to mark invalid entries or deleted files.
.openbsd, .netbsd => true,
else => false,
};
if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..") or
(skip_zero_fileno and bsd_entry.fileno == 0))
{
continue;
}
const entry_kind: File.Kind = switch (bsd_entry.type) {
posix.DT.BLK => .block_device,
posix.DT.CHR => .character_device,
posix.DT.DIR => .directory,
posix.DT.FIFO => .named_pipe,
posix.DT.LNK => .sym_link,
posix.DT.REG => .file,
posix.DT.SOCK => .unix_domain_socket,
posix.DT.WHT => .whiteout,
else => .unknown,
};
buffer[buffer_index] = .{
.name = name,
.kind = entry_kind,
.inode = bsd_entry.fileno,
};
buffer_index += 1;
}
return buffer_index;
}
fn dirReadIllumos(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var buffer_index: usize = 0;
while (buffer.len - buffer_index != 0) {
if (dr.end - dr.index == 0) {
// Refill the buffer, unless we've already created references to
// buffered data.
if (buffer_index != 0) break;
if (dr.state == .reset) {
posixSeekTo(dr.dir.handle, 0) catch |err| switch (err) {
error.Unseekable => return error.Unexpected,
else => |e| return e,
};
dr.state = .reading;
}
const syscall: Syscall = try .start();
const n: usize = while (true) {
const rc = posix.system.getdents(dr.dir.handle, dr.buffer.ptr, dr.buffer.len);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
break rc;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // Dir is invalid or was opened without iteration ability
.FAULT => |err| return errnoBug(err),
.NOTDIR => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
else => |err| return posix.unexpectedErrno(err),
}
},
}
};
if (n == 0) {
dr.state = .finished;
return 0;
}
dr.index = 0;
dr.end = n;
}
const entry = @as(*align(1) posix.system.dirent, @ptrCast(&dr.buffer[dr.index]));
const next_index = dr.index + entry.reclen;
dr.index = next_index;
const name = std.mem.sliceTo(@as([*:0]u8, @ptrCast(&entry.name)), 0);
if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue;
// illumos dirent doesn't expose type, so we have to call stat to get it.
const stat = try posixStatFile(dr.dir.handle, name, posix.AT.SYMLINK_NOFOLLOW);
buffer[buffer_index] = .{
.name = name,
.kind = stat.kind,
.inode = entry.ino,
};
buffer_index += 1;
}
return buffer_index;
}
fn dirReadHaiku(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var buffer_index: usize = 0;
while (buffer.len - buffer_index != 0) {
if (dr.end - dr.index == 0) {
// Refill the buffer, unless we've already created references to
// buffered data.
if (buffer_index != 0) break;
if (dr.state == .reset) {
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system._kern_rewind_dir(dr.dir.handle);
switch (@as(posix.E, @fromBackingInt(@intCast(@min(rc, 0))))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
dr.state = .reading;
}
const syscall: Syscall = try .start();
const n: usize = while (true) {
const rc = posix.system._kern_read_dir(dr.dir.handle, dr.buffer.ptr, dr.buffer.len, @truncate(dr.buffer.len / @sizeOf(posix.system.DirEnt)));
switch (@as(posix.E, @fromBackingInt(@intCast(@min(rc, 0))))) {
.SUCCESS => {
syscall.finish();
break @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
else => |err| return posix.unexpectedErrno(err),
}
},
}
};
if (n == 0) {
dr.state = .finished;
return 0;
}
dr.index = 0;
// _kern_read_dir returns entry count, but Dir.Reader is designed for byte count
dr.end = 0;
var i: usize = 0;
while (i < n) : (i += 1) {
const entry = @as(*align(1) posix.system.DirEnt, @ptrCast(&dr.buffer[dr.end]));
dr.end += entry.reclen;
}
}
const entry = @as(*align(1) posix.system.DirEnt, @ptrCast(&dr.buffer[dr.index]));
const next_index = dr.index + entry.reclen;
dr.index = next_index;
const name = std.mem.sliceTo(@as([*:0]u8, @ptrCast(&entry.name)), 0);
if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..") or entry.ino == 0) continue;
// haiku dirent doesn't expose type, so we have to call stat to get it.
var stat: std.c.Stat = undefined;
{
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system._kern_read_stat(dr.dir.handle, name, false, &stat, @sizeOf(std.c.Stat));
switch (@as(posix.E, @fromBackingInt(@intCast(@min(rc, 0))))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
const entry_kind: File.Kind = switch (stat.mode & posix.S.IFMT) {
posix.S.IFBLK => .block_device,
posix.S.IFCHR => .character_device,
posix.S.IFDIR => .directory,
posix.S.IFIFO => .named_pipe,
posix.S.IFLNK => .sym_link,
posix.S.IFREG => .file,
else => .unknown,
};
buffer[buffer_index] = .{
.name = name,
.kind = entry_kind,
.inode = entry.ino,
};
buffer_index += 1;
}
return buffer_index;
}
fn dirReadWindows(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const w = windows;
// We want to be able to use the `dr.buffer` for both the NtQueryDirectoryFile call (which
// returns WTF-16 names) *and* as a buffer for storing those WTF-16 names as WTF-8 to be able
// to return them in `Dir.Entry.name`. However, the problem that needs to be overcome in order to do
// that is that each WTF-16 code unit can be encoded as a maximum of 3 WTF-8 bytes, which means
// that it's not guaranteed that the memory used for the WTF-16 name will be sufficient
// for the WTF-8 encoding of the same name (for example, € is encoded as one WTF-16 code unit,
// [2 bytes] but encoded in WTF-8 as 3 bytes).
//
// The approach taken here is to "reserve" enough space in the `dr.buffer` to ensure that
// at least one entry with the maximum possible WTF-8 name length can be stored without clobbering
// any entries that follow it. That is, we determine how much space is needed to allow that,
// and then only provide the remaining portion of `dr.buffer` to the NtQueryDirectoryFile
// call. The WTF-16 names can then be safely converted using the full `dr.buffer` slice, making
// sure that each name can only potentially overwrite the data of its own entry.
//
// The worst case, where an entry's name is both the maximum length of a component and
// made up entirely of code points that are encoded as one WTF-16 code unit/three WTF-8 bytes,
// would therefore look like the diagram below, and only one entry would be able to be returned:
//
// | reserved | remaining unreserved buffer |
// | entry 1 | entry 2 | ... |
// | wtf-8 name of entry 1 |
//
// However, in the average case we will be able to store more than one WTF-8 name at a time in the
// available buffer and therefore we will be able to populate more than one `Dir.Entry` at a time.
// That might look something like this (where name 1, name 2, etc are the converted WTF-8 names):
//
// | reserved | remaining unreserved buffer |
// | entry 1 | entry 2 | ... |
// | name 1 | name 2 | name 3 | name 4 | ... |
//
// Note: More than the minimum amount of space could be reserved to make the "worst case"
// less likely, but since the worst-case also requires a maximum length component to matter,
// it's unlikely for it to become a problem in normal scenarios even if all names on the filesystem
// are made up of non-ASCII characters that have the "one WTF-16 code unit <-> three WTF-8 bytes"
// property (e.g. code points >= U+0800 and <= U+FFFF), as it's unlikely for a significant
// number of components to be maximum length.
// We need `3 * NAME_MAX` bytes to store a max-length component as WTF-8 safely.
// Because needing to store a max-length component depends on a `FileName` *with* the maximum
// component length, we know that the corresponding populated `FILE_BOTH_DIR_INFORMATION` will
// be of size `@sizeOf(w.FILE_BOTH_DIR_INFORMATION) + 2 * NAME_MAX` bytes, so we only need to
// reserve enough to get us to up to having `3 * NAME_MAX` bytes available when taking into account
// that we have the ability to write over top of the reserved memory + the full footprint of that
// particular `FILE_BOTH_DIR_INFORMATION`.
const max_info_len = @sizeOf(w.FILE_BOTH_DIR_INFORMATION) + w.NAME_MAX * 2;
const info_align = @alignOf(w.FILE_BOTH_DIR_INFORMATION);
const reserve_needed = std.mem.alignForward(usize, Dir.max_name_bytes, info_align) - max_info_len;
const unreserved_start = std.mem.alignForward(usize, reserve_needed, info_align);
const unreserved_buffer = dr.buffer[unreserved_start..];
// This is enforced by `Dir.Reader`
assert(unreserved_buffer.len >= max_info_len);
var name_index: usize = 0;
var buffer_index: usize = 0;
while (buffer.len - buffer_index != 0) {
if (dr.end - dr.index == 0) {
// Refill the buffer, unless we've already created references to
// buffered data.
if (buffer_index != 0) break;
var io_status_block: w.IO_STATUS_BLOCK = undefined;
const syscall: Syscall = try .start();
const rc = while (true) switch (w.ntdll.NtQueryDirectoryFile(
dr.dir.handle,
null,
null,
null,
&io_status_block,
unreserved_buffer.ptr,
std.math.lossyCast(w.ULONG, unreserved_buffer.len),
.BothDirectory,
.FALSE,
null,
.fromBool(dr.state == .reset),
)) {
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => |rc| {
syscall.finish();
break rc;
},
};
dr.state = .reading;
if (io_status_block.Information == 0) {
dr.state = .finished;
return 0;
}
dr.index = 0;
dr.end = io_status_block.Information;
switch (rc) {
.SUCCESS => {},
.ACCESS_DENIED => return error.AccessDenied, // Double-check that the Dir was opened with iteration ability
else => return w.unexpectedStatus(rc),
}
}
// While the official API docs guarantee FILE_BOTH_DIR_INFORMATION to be aligned properly
// this may not always be the case (e.g. due to faulty VM/sandboxing tools)
const dir_info: *align(2) w.FILE_BOTH_DIR_INFORMATION = @ptrCast(@alignCast(&unreserved_buffer[dr.index]));
const backtrack_index = dr.index;
if (dir_info.NextEntryOffset != 0) {
dr.index += dir_info.NextEntryOffset;
} else {
dr.index = dr.end;
}
const name_wtf16le = @as([*]u16, @ptrCast(&dir_info.FileName))[0 .. dir_info.FileNameLength / 2];
if (std.mem.eql(u16, name_wtf16le, &[_]u16{'.'}) or std.mem.eql(u16, name_wtf16le, &[_]u16{ '.', '.' })) {
continue;
}
// Read any relevant information from the `dir_info` now since it's possible the WTF-8
// name will overwrite it.
const kind: File.Kind = blk: {
const attrs = dir_info.FileAttributes;
if (attrs.REPARSE_POINT) break :blk .sym_link;
if (attrs.DIRECTORY) break :blk .directory;
break :blk .file;
};
const inode: File.INode = dir_info.FileIndex;
// If there's no more space for WTF-8 names without bleeding over into
// the remaining unprocessed entries, then backtrack and return what we have so far.
if (name_index + std.unicode.calcWtf8Len(name_wtf16le) > unreserved_start + dr.index) {
// We should always be able to fit at least one entry into the buffer no matter what
assert(buffer_index != 0);
dr.index = backtrack_index;
break;
}
const name_buf = dr.buffer[name_index..];
const name_wtf8_len = std.unicode.wtf16LeToWtf8(name_buf, name_wtf16le);
const name_wtf8 = name_buf[0..name_wtf8_len];
name_index += name_wtf8_len;
buffer[buffer_index] = .{
.name = name_wtf8,
.kind = kind,
.inode = inode,
};
buffer_index += 1;
}
return buffer_index;
}
fn dirReadWasi(userdata: ?*anyopaque, dr: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usize {
// We intentinally use fd_readdir even when linked with libc, since its
// implementation is exactly the same as below, and we avoid the code
// complexity here.
const wasi = std.os.wasi;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const Header = extern struct {
cookie: u64,
};
const header: *align(@alignOf(usize)) Header = @ptrCast(dr.buffer.ptr);
const header_end: usize = @sizeOf(Header);
if (dr.index < header_end) {
// Initialize header.
dr.index = header_end;
dr.end = header_end;
header.* = .{ .cookie = wasi.DIRCOOKIE_START };
}
var buffer_index: usize = 0;
while (buffer.len - buffer_index != 0) {
// According to the WASI spec, the last entry might be truncated, so we
// need to check if the remaining buffer contains the whole dirent.
if (dr.end - dr.index < @sizeOf(wasi.dirent_t)) {
// Refill the buffer, unless we've already created references to
// buffered data.
if (buffer_index != 0) break;
if (dr.state == .reset) {
header.* = .{ .cookie = wasi.DIRCOOKIE_START };
dr.state = .reading;
}
const dents_buffer = dr.buffer[header_end..];
var n: usize = undefined;
const syscall: Syscall = try .start();
while (true) {
switch (wasi.fd_readdir(dr.dir.handle, dents_buffer.ptr, dents_buffer.len, header.cookie, &n)) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // Dir is invalid or was opened without iteration ability.
.FAULT => |err| return errnoBug(err),
.NOTDIR => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
// To be consistent across platforms, iteration
// ends if the directory being iterated is deleted
// during iteration. This matches the behavior of
// non-Linux, non-WASI UNIX platforms.
.NOENT => {
dr.state = .finished;
return 0;
},
.NOTCAPABLE => return error.AccessDenied,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
if (n == 0) {
dr.state = .finished;
return 0;
}
dr.index = header_end;
dr.end = header_end + n;
}
const entry: *align(1) wasi.dirent_t = @ptrCast(&dr.buffer[dr.index]);
const entry_size = @sizeOf(wasi.dirent_t);
const name_index = dr.index + entry_size;
if (name_index + entry.namlen > dr.end) {
// This case, the name is truncated, so we need to call readdir to store the entire name.
dr.end = dr.index; // Force fd_readdir in the next loop.
continue;
}
const name = dr.buffer[name_index..][0..entry.namlen];
const next_index = name_index + entry.namlen;
dr.index = next_index;
header.cookie = entry.next;
if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, ".."))
continue;
const entry_kind: File.Kind = switch (entry.type) {
.BLOCK_DEVICE => .block_device,
.CHARACTER_DEVICE => .character_device,
.DIRECTORY => .directory,
.SYMBOLIC_LINK => .sym_link,
.REGULAR_FILE => .file,
.SOCKET_STREAM, .SOCKET_DGRAM => .unix_domain_socket,
else => .unknown,
};
buffer[buffer_index] = .{
.name = name,
.kind = entry_kind,
.inode = entry.ino,
};
buffer_index += 1;
}
return buffer_index;
}
fn dirReadUnimplemented(userdata: ?*anyopaque, dir_reader: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usize {
_ = userdata;
_ = dir_reader;
_ = buffer;
return error.Unexpected;
}
const dirRealPathFile = switch (native_os) {
.windows => dirRealPathFileWindows,
else => dirRealPathFilePosix,
};
fn dirRealPathFileWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, out_buffer: []u8) Dir.RealPathFileError!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var path_name_w = try sliceToPrefixedFileW(dir.handle, sub_path, .{});
const h_file = handle: {
if (OpenFile(path_name_w.span(), .{
.dir = dir.handle,
.access_mask = .{
.GENERIC = .{ .READ = true },
.STANDARD = .{ .SYNCHRONIZE = true },
},
.creation = .OPEN,
.filter = .any,
})) |handle| {
break :handle handle;
} else |err| switch (err) {
error.WouldBlock => unreachable,
else => |e| return e,
}
};
defer windows.CloseHandle(h_file);
// We can re-use the path buffer for the WTF-16 representation since
// we don't need the prefixed path anymore
return realPathWindowsBuf(h_file, out_buffer, &path_name_w.data);
}
fn realPathWindows(h_file: windows.HANDLE, out_buffer: []u8) File.RealPathError!usize {
var wide_buf: [windows.PATH_MAX_WIDE]u16 = undefined;
return realPathWindowsBuf(h_file, out_buffer, &wide_buf);
}
fn realPathWindowsBuf(h_file: windows.HANDLE, out_buffer: []u8, wtf16_buffer: []u16) File.RealPathError!usize {
const wide_slice = try GetFinalPathNameByHandle(h_file, .{}, wtf16_buffer);
const len = std.unicode.calcWtf8Len(wide_slice);
if (len > out_buffer.len)
return error.NameTooLong;
return std.unicode.wtf16LeToWtf8(out_buffer, wide_slice);
}
/// Specifies how to format volume path in the result of `GetFinalPathNameByHandle`.
/// Defaults to DOS volume names.
pub const GetFinalPathNameByHandleFormat = struct {
volume_name: enum {
/// Format as DOS volume name
Dos,
/// Format as NT volume name
Nt,
} = .Dos,
};
pub const GetFinalPathNameByHandleError = error{
AccessDenied,
FileNotFound,
NameTooLong,
/// The volume does not contain a recognized file system. File system
/// drivers might not be loaded, or the volume may be corrupt.
UnrecognizedVolume,
} || Io.Cancelable || Io.UnexpectedError;
/// Returns canonical (normalized) path of handle.
/// Use `GetFinalPathNameByHandleFormat` to specify whether the path is meant to include
/// NT or DOS volume name (e.g., `\Device\HarddiskVolume0\foo.txt` versus `C:\foo.txt`).
/// If DOS volume name format is selected, note that this function does *not* prepend
/// `\\?\` prefix to the resultant path.
pub fn GetFinalPathNameByHandle(
hFile: windows.HANDLE,
fmt: GetFinalPathNameByHandleFormat,
out_buffer: []u16,
) GetFinalPathNameByHandleError![]u16 {
const final_path = QueryObjectName(hFile, out_buffer) catch |err| switch (err) {
// we assume InvalidHandle is close enough to FileNotFound in semantics
// to not further complicate the error set
error.InvalidHandle => return error.FileNotFound,
else => |e| return e,
};
switch (fmt.volume_name) {
.Nt => {
// the returned path is already in .Nt format
return final_path;
},
.Dos => {
// parse the string to separate volume path from file path
const device_prefix = std.unicode.utf8ToUtf16LeStringLiteral("\\Device\\");
// We aren't entirely sure of the structure of the path returned by
// QueryObjectName in all contexts/environments.
// This code is written to cover the various cases that have
// been encountered and solved appropriately. But note that there's
// no easy way to verify that they have all been tackled!
// (Unless you, the reader knows of one then please do action that!)
if (!std.mem.startsWith(u16, final_path, device_prefix)) {
// Wine seems to return NT namespaced paths starting with \??\ from QueryObjectName
// (e.g. `\??\Z:\some\path\to\a\file.txt`), in which case we can just strip the
// prefix to turn it into an absolute path.
// https://github.com/ziglang/zig/issues/26029
// https://bugs.winehq.org/show_bug.cgi?id=39569
return windows.ntToWin32Namespace(final_path, out_buffer) catch |err| switch (err) {
error.NotNtPath => return error.Unexpected,
error.NameTooLong => |e| return e,
};
}
const file_path_begin_index = std.mem.findPos(u16, final_path, device_prefix.len, &[_]u16{'\\'}) orelse unreachable;
const volume_name_u16 = final_path[0..file_path_begin_index];
const device_name_u16 = volume_name_u16[device_prefix.len..];
const file_name_u16 = final_path[file_path_begin_index..];
// MUP is Multiple UNC Provider, and indicates that the path is a UNC
// path. In this case, the canonical UNC path can be gotten by just
// dropping the \Device\Mup\ and making sure the path begins with \\
if (std.mem.eql(u16, device_name_u16, std.unicode.utf8ToUtf16LeStringLiteral("Mup"))) {
out_buffer[0] = '\\';
@memmove(out_buffer[1..][0..file_name_u16.len], file_name_u16);
return out_buffer[0 .. 1 + file_name_u16.len];
}
// Get DOS volume name. DOS volume names are actually symbolic link objects to the
// actual NT volume. For example:
// (NT) \Device\HarddiskVolume4 => (DOS) \DosDevices\C: == (DOS) C:
const MIN_SIZE = @sizeOf(windows.MOUNTMGR_MOUNT_POINT) + windows.MAX_PATH;
// We initialize the input buffer to all zeros for convenience since
// `DeviceIoControl` with `IOCTL_MOUNTMGR_QUERY_POINTS` expects this.
var input_buf: [MIN_SIZE]u8 align(@alignOf(windows.MOUNTMGR_MOUNT_POINT)) = @splat(0);
var output_buf: [MIN_SIZE * 4]u8 align(@alignOf(windows.MOUNTMGR_MOUNT_POINTS)) = undefined;
// This surprising path is a filesystem path to the mount manager on Windows.
// Source: https://stackoverflow.com/questions/3012828/using-ioctl-mountmgr-query-points
// This is the NT namespaced version of \\.\MountPointManager
const mgmt_path_u16 = std.unicode.utf8ToUtf16LeStringLiteral("\\??\\MountPointManager");
const mgmt_handle = OpenFile(mgmt_path_u16, .{
.access_mask = .{ .STANDARD = .{ .SYNCHRONIZE = true } },
.creation = .OPEN,
}) catch |err| switch (err) {
error.IsDir => return error.Unexpected,
error.NotDir => return error.Unexpected,
error.NoDevice => return error.Unexpected,
error.AccessDenied => return error.Unexpected,
error.PipeBusy => return error.Unexpected,
error.FileBusy => return error.Unexpected,
error.PathAlreadyExists => return error.Unexpected,
error.WouldBlock => return error.Unexpected,
error.NetworkNotFound => return error.Unexpected,
error.AntivirusInterference => return error.Unexpected,
error.BadPathName => return error.Unexpected,
else => |e| return e,
};
defer windows.CloseHandle(mgmt_handle);
var input_struct: *windows.MOUNTMGR_MOUNT_POINT = @ptrCast(&input_buf[0]);
input_struct.DeviceNameOffset = @sizeOf(windows.MOUNTMGR_MOUNT_POINT);
input_struct.DeviceNameLength = @intCast(volume_name_u16.len * 2);
@memcpy(input_buf[@sizeOf(windows.MOUNTMGR_MOUNT_POINT)..][0 .. volume_name_u16.len * 2], @as([*]const u8, @ptrCast(volume_name_u16.ptr)));
switch ((try deviceIoControl(&.{
.file = .{ .handle = mgmt_handle, .flags = .{ .nonblocking = false } },
.code = windows.IOCTL.MOUNTMGR.QUERY_POINTS,
.in = &input_buf,
.out = &output_buf,
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
else => |status| return windows.unexpectedStatus(status),
}
const mount_points_struct: *const windows.MOUNTMGR_MOUNT_POINTS = @ptrCast(&output_buf[0]);
const mount_points = @as(
[*]const windows.MOUNTMGR_MOUNT_POINT,
@ptrCast(&mount_points_struct.MountPoints[0]),
)[0..mount_points_struct.NumberOfMountPoints];
for (mount_points) |mount_point| {
const symlink = @as(
[*]const u16,
@ptrCast(@alignCast(&output_buf[mount_point.SymbolicLinkNameOffset])),
)[0 .. mount_point.SymbolicLinkNameLength / 2];
// Look for `\DosDevices\` prefix. We don't really care if there are more than one symlinks
// with traditional DOS drive letters, so pick the first one available.
var prefix_buf = std.unicode.utf8ToUtf16LeStringLiteral("\\DosDevices\\");
const prefix = prefix_buf[0..prefix_buf.len];
if (std.mem.startsWith(u16, symlink, prefix)) {
const drive_letter = symlink[prefix.len..];
if (out_buffer.len < drive_letter.len + file_name_u16.len) return error.NameTooLong;
@memcpy(out_buffer[0..drive_letter.len], drive_letter);
@memmove(out_buffer[drive_letter.len..][0..file_name_u16.len], file_name_u16);
const total_len = drive_letter.len + file_name_u16.len;
// Validate that DOS does not contain any spurious nul bytes.
assert(std.mem.findScalar(u16, out_buffer[0..total_len], 0) == null);
return out_buffer[0..total_len];
} else if (mountmgrIsVolumeName(symlink)) {
// If the symlink is a volume GUID like \??\Volume{383da0b0-717f-41b6-8c36-00500992b58d},
// then it is a volume mounted as a path rather than a drive letter. We need to
// query the mount manager again to get the DOS path for the volume.
// 49 is the maximum length accepted by mountmgrIsVolumeName
const vol_input_size = @sizeOf(windows.MOUNTMGR_TARGET_NAME) + (49 * 2);
var vol_input_buf: [vol_input_size]u8 align(@alignOf(windows.MOUNTMGR_TARGET_NAME)) = @splat(0);
// Note: If the path exceeds MAX_PATH, the Disk Management GUI doesn't accept the full path,
// and instead if must be specified using a shortened form (e.g. C:\FOO~1\BAR~1\<...>).
// However, just to be sure we can handle any path length, we use PATH_MAX_WIDE here.
const min_output_size = @sizeOf(windows.MOUNTMGR_VOLUME_PATHS) + (windows.PATH_MAX_WIDE * 2);
var vol_output_buf: [min_output_size]u8 align(@alignOf(windows.MOUNTMGR_VOLUME_PATHS)) = undefined;
var vol_input_struct: *windows.MOUNTMGR_TARGET_NAME = @ptrCast(&vol_input_buf[0]);
vol_input_struct.DeviceNameLength = @intCast(symlink.len * 2);
@memcpy(@as([*]windows.WCHAR, &vol_input_struct.DeviceName)[0..symlink.len], symlink);
switch ((try deviceIoControl(&.{
.file = .{ .handle = mgmt_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.MOUNTMGR.QUERY_DOS_VOLUME_PATH,
.in = &vol_input_buf,
.out = &vol_output_buf,
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.UNRECOGNIZED_VOLUME => return error.UnrecognizedVolume,
else => |status| return windows.unexpectedStatus(status),
}
const volume_paths_struct: *const windows.MOUNTMGR_VOLUME_PATHS = @ptrCast(&vol_output_buf[0]);
const volume_path = std.mem.sliceTo(@as(
[*]const u16,
&volume_paths_struct.MultiSz,
)[0 .. volume_paths_struct.MultiSzLength / 2], 0);
if (out_buffer.len < volume_path.len + file_name_u16.len) return error.NameTooLong;
// `out_buffer` currently contains the memory of `file_name_u16`, so it can overlap with where
// we want to place the filename before returning. Here are the possible overlapping cases:
//
// out_buffer: [filename]
// dest: [___(a)___] [___(b)___]
//
// In the case of (a), we need to copy forwards, and in the case of (b) we need
// to copy backwards. We also need to do this before copying the volume path because
// it could overwrite the file_name_u16 memory.
const file_name_dest = out_buffer[volume_path.len..][0..file_name_u16.len];
@memmove(file_name_dest, file_name_u16);
@memcpy(out_buffer[0..volume_path.len], volume_path);
const total_len = volume_path.len + file_name_u16.len;
// Validate that DOS does not contain any spurious nul bytes.
assert(std.mem.findScalar(u16, out_buffer[0..total_len], 0) == null);
return out_buffer[0..total_len];
}
}
// If we've ended up here, then something went wrong/is corrupted in the OS,
// so error out!
return error.FileNotFound;
},
}
}
test GetFinalPathNameByHandle {
if (builtin.os.tag != .windows)
return;
//any file will do
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const handle = tmp.dir.handle;
var buffer: [windows.PATH_MAX_WIDE]u16 = undefined;
//check with sufficient size
const nt_path = try GetFinalPathNameByHandle(handle, .{ .volume_name = .Nt }, &buffer);
_ = try GetFinalPathNameByHandle(handle, .{ .volume_name = .Dos }, &buffer);
const required_len_in_u16 = nt_path.len + @divExact(@intFromPtr(nt_path.ptr) - @intFromPtr(&buffer), 2) + 1;
//check with insufficient size
try std.testing.expectError(error.NameTooLong, GetFinalPathNameByHandle(handle, .{ .volume_name = .Nt }, buffer[0 .. required_len_in_u16 - 1]));
try std.testing.expectError(error.NameTooLong, GetFinalPathNameByHandle(handle, .{ .volume_name = .Dos }, buffer[0 .. required_len_in_u16 - 1]));
//check with exactly-sufficient size
_ = try GetFinalPathNameByHandle(handle, .{ .volume_name = .Nt }, buffer[0..required_len_in_u16]);
_ = try GetFinalPathNameByHandle(handle, .{ .volume_name = .Dos }, buffer[0..required_len_in_u16]);
}
/// Equivalent to the MOUNTMGR_IS_VOLUME_NAME macro in mountmgr.h
fn mountmgrIsVolumeName(name: []const u16) bool {
return (name.len == 48 or (name.len == 49 and name[48] == std.mem.nativeToLittle(u16, '\\'))) and
name[0] == std.mem.nativeToLittle(u16, '\\') and
(name[1] == std.mem.nativeToLittle(u16, '?') or name[1] == std.mem.nativeToLittle(u16, '\\')) and
name[2] == std.mem.nativeToLittle(u16, '?') and
name[3] == std.mem.nativeToLittle(u16, '\\') and
std.mem.startsWith(u16, name[4..], std.unicode.utf8ToUtf16LeStringLiteral("Volume{")) and
name[19] == std.mem.nativeToLittle(u16, '-') and
name[24] == std.mem.nativeToLittle(u16, '-') and
name[29] == std.mem.nativeToLittle(u16, '-') and
name[34] == std.mem.nativeToLittle(u16, '-') and
name[47] == std.mem.nativeToLittle(u16, '}');
}
test mountmgrIsVolumeName {
@setEvalBranchQuota(2000);
const L = std.unicode.utf8ToUtf16LeStringLiteral;
try std.testing.expect(mountmgrIsVolumeName(L("\\\\?\\Volume{383da0b0-717f-41b6-8c36-00500992b58d}")));
try std.testing.expect(mountmgrIsVolumeName(L("\\??\\Volume{383da0b0-717f-41b6-8c36-00500992b58d}")));
try std.testing.expect(mountmgrIsVolumeName(L("\\\\?\\Volume{383da0b0-717f-41b6-8c36-00500992b58d}\\")));
try std.testing.expect(mountmgrIsVolumeName(L("\\??\\Volume{383da0b0-717f-41b6-8c36-00500992b58d}\\")));
try std.testing.expect(!mountmgrIsVolumeName(L("\\\\.\\Volume{383da0b0-717f-41b6-8c36-00500992b58d}")));
try std.testing.expect(!mountmgrIsVolumeName(L("\\??\\Volume{383da0b0-717f-41b6-8c36-00500992b58d}\\foo")));
try std.testing.expect(!mountmgrIsVolumeName(L("\\??\\Volume{383da0b0-717f-41b6-8c36-00500992b58}")));
}
pub const QueryObjectNameError = error{
AccessDenied,
InvalidHandle,
NameTooLong,
Unexpected,
};
pub fn QueryObjectName(handle: windows.HANDLE, out_buffer: []u16) QueryObjectNameError![]u16 {
const out_buffer_aligned = std.mem.alignInSlice(out_buffer, @alignOf(windows.OBJECT.NAME_INFORMATION)) orelse return error.NameTooLong;
const info: *windows.OBJECT.NAME_INFORMATION = @ptrCast(out_buffer_aligned);
// buffer size is specified in bytes
const out_buffer_len = std.math.cast(windows.ULONG, out_buffer_aligned.len * 2) orelse std.math.maxInt(windows.ULONG);
// last argument would return the length required for full_buffer, not exposed here
return switch (windows.ntdll.NtQueryObject(handle, .Name, info, out_buffer_len, null)) {
.SUCCESS => {
// info.Name from ObQueryNameString is documented to be empty if the object
// was "unnamed", not sure if this can happen for file handles
return if (info.Name.isEmpty()) error.Unexpected else info.Name.slice();
},
.ACCESS_DENIED => error.AccessDenied,
.INVALID_HANDLE => error.InvalidHandle,
// triggered when the buffer is too small for the OBJECT_NAME_INFORMATION object (.INFO_LENGTH_MISMATCH),
// or if the buffer is too small for the file path returned (.BUFFER_OVERFLOW, .BUFFER_TOO_SMALL)
.INFO_LENGTH_MISMATCH, .BUFFER_OVERFLOW, .BUFFER_TOO_SMALL => error.NameTooLong,
else => |e| windows.unexpectedStatus(e),
};
}
test QueryObjectName {
if (builtin.os.tag != .windows)
return;
//any file will do; canonicalization works on NTFS junctions and symlinks, hardlinks remain separate paths.
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const handle = tmp.dir.handle;
var out_buffer: [windows.PATH_MAX_WIDE]u16 = undefined;
const result_path = try QueryObjectName(handle, &out_buffer);
const required_len_in_u16 = result_path.len + @divExact(@intFromPtr(result_path.ptr) - @intFromPtr(&out_buffer), 2) + 1;
//insufficient size
try std.testing.expectError(error.NameTooLong, QueryObjectName(handle, out_buffer[0 .. required_len_in_u16 - 1]));
//exactly-sufficient size
_ = try QueryObjectName(handle, out_buffer[0..required_len_in_u16]);
}
const Wtf16ToPrefixedFileWError = error{
AccessDenied,
FileNotFound,
} || Dir.PathNameError || Io.Cancelable || Io.UnexpectedError;
const Wtf16ToPrefixedFileWOptions = struct {
allow_relative: bool = true,
};
/// Converts the `path` to WTF16, null-terminated. If the path contains any
/// namespace prefix, or is anything but a relative path (rooted, drive relative,
/// etc) the result will have the NT-style prefix `\??\`.
///
/// Similar to RtlDosPathNameToNtPathName_U with a few differences:
/// - Does not allocate on the heap.
/// - Relative paths are kept as relative unless they contain too many ..
/// components, in which case they are resolved against the `dir` if it
/// is non-null, or the CWD if it is null.
/// - Special case device names like COM1, NUL, etc are not handled specially (TODO)
/// - . and space are not stripped from the end of relative paths (potential TODO)
pub fn wToPrefixedFileW(dir: ?windows.HANDLE, path: [:0]const u16, options: Wtf16ToPrefixedFileWOptions) Wtf16ToPrefixedFileWError!WindowsPathSpace {
const nt_prefix = [_]u16{ '\\', '?', '?', '\\' };
if (windows.hasCommonNtPrefix(u16, path)) {
// TODO: Figure out a way to design an API that can avoid the copy for NT,
// since it is always returned fully unmodified.
var path_space: WindowsPathSpace = undefined;
path_space.data[0..nt_prefix.len].* = nt_prefix;
const len_after_prefix = path.len - nt_prefix.len;
@memcpy(path_space.data[nt_prefix.len..][0..len_after_prefix], path[nt_prefix.len..]);
path_space.len = path.len;
path_space.data[path_space.len] = 0;
return path_space;
} else {
const path_type = Dir.path.getWin32PathType(u16, path);
var path_space: WindowsPathSpace = undefined;
if (path_type == .local_device) switch (getLocalDevicePathType(u16, path)) {
.verbatim => {
path_space.data[0..nt_prefix.len].* = nt_prefix;
const len_after_prefix = path.len - nt_prefix.len;
@memcpy(path_space.data[nt_prefix.len..][0..len_after_prefix], path[nt_prefix.len..]);
path_space.len = path.len;
path_space.data[path_space.len] = 0;
return path_space;
},
.local_device, .fake_verbatim => {
const path_byte_len = windows.ntdll.RtlGetFullPathName_U(
path.ptr,
path_space.data.len * 2,
&path_space.data,
null,
);
if (path_byte_len == 0) {
// TODO: This may not be the right error
return error.BadPathName;
} else if (path_byte_len / 2 > path_space.data.len) {
return error.NameTooLong;
}
path_space.len = path_byte_len / 2;
// Both prefixes will be normalized but retained, so all
// we need to do now is replace them with the NT prefix
path_space.data[0..nt_prefix.len].* = nt_prefix;
return path_space;
},
};
if (options.allow_relative and path_type == .relative) relative: {
// TODO: Handle special case device names like COM1, AUX, NUL, CONIN$, CONOUT$, etc.
// See https://googleprojectzero.blogspot.com/2016/02/the-definitive-guide-on-win32-to-nt.html
// TODO: Potentially strip all trailing . and space characters from the
// end of the path. This is something that both RtlDosPathNameToNtPathName_U
// and RtlGetFullPathName_U do. Technically, trailing . and spaces
// are allowed, but such paths may not interact well with Windows (i.e.
// files with these paths can't be deleted from explorer.exe, etc).
// This could be something that normalizePath may want to do.
@memcpy(path_space.data[0..path.len], path);
// Try to normalize, but if we get too many parent directories,
// then we need to start over and use RtlGetFullPathName_U instead.
path_space.len = windows.normalizePath(u16, path_space.data[0..path.len]) catch |err| switch (err) {
error.TooManyParentDirs => break :relative,
};
path_space.data[path_space.len] = 0;
return path_space;
}
// We now know we are going to return an absolute NT path, so
// we can unconditionally prefix it with the NT prefix.
path_space.data[0..nt_prefix.len].* = nt_prefix;
if (path_type == .root_local_device) {
// `\\.` and `\\?` always get converted to `\??\` exactly, so
// we can just stop here
path_space.len = nt_prefix.len;
path_space.data[path_space.len] = 0;
return path_space;
}
const path_buf_offset = switch (path_type) {
// UNC paths will always start with `\\`. However, we want to
// end up with something like `\??\UNC\server\share`, so to get
// RtlGetFullPathName to write into the spot we want the `server`
// part to end up, we need to provide an offset such that
// the `\\` part gets written where the `C\` of `UNC\` will be
// in the final NT path.
.unc_absolute => nt_prefix.len + 2,
else => nt_prefix.len,
};
const buf_len: u32 = @intCast(path_space.data.len - path_buf_offset);
const path_to_get: [:0]const u16 = path_to_get: {
// If dir is null, then we don't need to bother with GetFinalPathNameByHandle because
// RtlGetFullPathName_U will resolve relative paths against the CWD for us.
if (path_type != .relative or dir == null) {
break :path_to_get path;
}
// We can also skip GetFinalPathNameByHandle if the handle matches
// the handle returned by Io.Dir.cwd()
if (dir.? == Io.Dir.cwd().handle) {
break :path_to_get path;
}
// At this point, we know we have a relative path that had too many
// `..` components to be resolved by normalizePath, so we need to
// convert it into an absolute path and let RtlGetFullPathName_U
// canonicalize it. We do this by getting the path of the `dir`
// and appending the relative path to it.
var dir_path_buf: [windows.PATH_MAX_WIDE:0]u16 = undefined;
const dir_path = GetFinalPathNameByHandle(dir.?, .{}, &dir_path_buf) catch |err| switch (err) {
// This mapping is not correct; it is actually expected
// that calling GetFinalPathNameByHandle might return
// error.UnrecognizedVolume, and in fact has been observed
// in the wild. The problem is that wToPrefixedFileW was
// never intended to make *any* OS syscall APIs. It's only
// supposed to convert a string to one that is eligible to
// be used in the ntdll syscalls.
//
// To solve this, this function needs to no longer call
// GetFinalPathNameByHandle under any conditions, or the
// calling function needs to get reworked to not need to
// call this function.
//
// This may involve making breaking API changes.
error.UnrecognizedVolume => return error.Unexpected,
else => |e| return e,
};
if (dir_path.len + 1 + path.len > windows.PATH_MAX_WIDE) {
return error.NameTooLong;
}
// We don't have to worry about potentially doubling up path separators
// here since RtlGetFullPathName_U will handle canonicalizing it.
dir_path_buf[dir_path.len] = '\\';
@memcpy(dir_path_buf[dir_path.len + 1 ..][0..path.len], path);
const full_len = dir_path.len + 1 + path.len;
dir_path_buf[full_len] = 0;
break :path_to_get dir_path_buf[0..full_len :0];
};
const path_byte_len = windows.ntdll.RtlGetFullPathName_U(
path_to_get.ptr,
buf_len * 2,
path_space.data[path_buf_offset..].ptr,
null,
);
if (path_byte_len == 0) {
// TODO: This may not be the right error
return error.BadPathName;
} else if (path_byte_len / 2 > buf_len) {
return error.NameTooLong;
}
path_space.len = path_buf_offset + (path_byte_len / 2);
if (path_type == .unc_absolute) {
// Now add in the UNC, the `C` should overwrite the first `\` of the
// FullPathName, ultimately resulting in `\??\UNC\<the rest of the path>`
assert(path_space.data[path_buf_offset] == '\\');
assert(path_space.data[path_buf_offset + 1] == '\\');
const unc = [_]u16{ 'U', 'N', 'C' };
path_space.data[nt_prefix.len..][0..unc.len].* = unc;
}
return path_space;
}
}
const LocalDevicePathType = enum {
/// `\\.\` (path separators can be `\` or `/`)
local_device,
/// `\\?\`
/// When converted to an NT path, everything past the prefix is left
/// untouched and `\\?\` is replaced by `\??\`.
verbatim,
/// `\\?\` without all path separators being `\`.
/// This seems to be recognized as a prefix, but the 'verbatim' aspect
/// is not respected (i.e. if `//?/C:/foo` is converted to an NT path,
/// it will become `\??\C:\foo` [it will be canonicalized and the //?/ won't
/// be treated as part of the final path])
fake_verbatim,
};
/// Only relevant for Win32 -> NT path conversion.
/// Asserts `path` is of type `Dir.path.Win32PathType.local_device`.
fn getLocalDevicePathType(comptime T: type, path: []const T) LocalDevicePathType {
if (std.debug.runtime_safety) {
assert(Dir.path.getWin32PathType(T, path) == .local_device);
}
const backslash = std.mem.nativeToLittle(T, '\\');
const all_backslash = path[0] == backslash and
path[1] == backslash and
path[3] == backslash;
return switch (path[2]) {
std.mem.nativeToLittle(T, '?') => if (all_backslash) .verbatim else .fake_verbatim,
std.mem.nativeToLittle(T, '.') => .local_device,
else => unreachable,
};
}
pub const Wtf8ToPrefixedFileWError = Wtf16ToPrefixedFileWError;
/// Same as `wToPrefixedFileW` but accepts a WTF-8 encoded path.
/// https://wtf-8.codeberg.page/
pub fn sliceToPrefixedFileW(dir: ?windows.HANDLE, path: []const u8, options: Wtf16ToPrefixedFileWOptions) Wtf8ToPrefixedFileWError!WindowsPathSpace {
var temp_path: WindowsPathSpace = undefined;
temp_path.len = std.unicode.wtf8ToWtf16Le(&temp_path.data, path) catch |err| switch (err) {
error.InvalidWtf8 => return error.BadPathName,
};
temp_path.data[temp_path.len] = 0;
return wToPrefixedFileW(dir, temp_path.span(), options);
}
pub const WindowsPathSpace = struct {
data: [windows.PATH_MAX_WIDE:0]u16,
len: usize,
pub fn span(wps: *const WindowsPathSpace) [:0]const u16 {
return wps.data[0..wps.len :0];
}
pub fn string(wps: *const WindowsPathSpace) windows.UNICODE_STRING {
return .init(wps.span());
}
};
fn dirRealPathFilePosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, out_buffer: []u8) Dir.RealPathFileError!usize {
if (native_os == .wasi) return error.OperationUnsupported;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
if (builtin.link_libc and dir.handle == posix.AT.FDCWD) {
if (out_buffer.len < posix.PATH_MAX) return error.NameTooLong;
const syscall: Syscall = try .start();
while (true) {
if (std.c.realpath(sub_path_posix, out_buffer.ptr)) |redundant_pointer| {
syscall.finish();
assert(redundant_pointer == out_buffer.ptr);
return std.mem.findScalar(u8, out_buffer, 0) orelse out_buffer.len;
}
const err: posix.E = @fromBackingInt(@intCast(std.c._errno().*));
if (err == .INTR) {
try syscall.checkCancel();
continue;
}
syscall.finish();
switch (err) {
.INVAL => return errnoBug(err),
.BADF => return errnoBug(err),
.FAULT => return errnoBug(err),
.ACCES => return error.AccessDenied,
.NOENT => return error.FileNotFound,
.OPNOTSUPP => return error.OperationUnsupported,
.NOTDIR => return error.NotDir,
.NAMETOOLONG => return error.NameTooLong,
.LOOP => return error.SymLinkLoop,
.IO => return error.InputOutput,
else => return posix.unexpectedErrno(err),
}
}
}
var flags: posix.O = .{};
if (@hasField(posix.O, "NONBLOCK")) flags.NONBLOCK = true;
if (@hasField(posix.O, "CLOEXEC")) flags.CLOEXEC = true;
if (@hasField(posix.O, "PATH")) flags.PATH = true;
const mode: posix.mode_t = 0;
const syscall: Syscall = try .start();
const fd: posix.fd_t = while (true) {
const rc = openat_sym(dir.handle, sub_path_posix, flags, mode);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
break @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.FAULT => |err| return errnoBug(err),
.INVAL => return error.BadPathName,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.ACCES => return error.AccessDenied,
.FBIG => return error.FileTooBig,
.OVERFLOW => return error.FileTooBig,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.SRCH => return error.FileNotFound, // Linux when accessing procfs.
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.EXIST => return error.PathAlreadyExists,
.BUSY => return error.DeviceBusy,
.NXIO => return error.NoDevice,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
};
defer closeFd(fd);
return realPathPosix(fd, out_buffer);
}
const dirRealPath = switch (native_os) {
.windows => dirRealPathWindows,
else => dirRealPathPosix,
};
fn dirRealPathPosix(userdata: ?*anyopaque, dir: Dir, out_buffer: []u8) Dir.RealPathError!usize {
if (native_os == .wasi) return error.OperationUnsupported;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
return realPathPosix(dir.handle, out_buffer);
}
fn dirRealPathWindows(userdata: ?*anyopaque, dir: Dir, out_buffer: []u8) Dir.RealPathError!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
return realPathWindows(dir.handle, out_buffer);
}
const fileRealPath = switch (native_os) {
.windows => fileRealPathWindows,
else => fileRealPathPosix,
};
fn fileRealPathWindows(userdata: ?*anyopaque, file: File, out_buffer: []u8) File.RealPathError!usize {
if (native_os == .wasi) return error.OperationUnsupported;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
return realPathWindows(file.handle, out_buffer);
}
fn fileRealPathPosix(userdata: ?*anyopaque, file: File, out_buffer: []u8) File.RealPathError!usize {
if (native_os == .wasi) return error.OperationUnsupported;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
return realPathPosix(file.handle, out_buffer);
}
fn realPathPosix(fd: posix.fd_t, out_buffer: []u8) File.RealPathError!usize {
switch (native_os) {
.dragonfly, .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
var sufficient_buffer: [posix.PATH_MAX]u8 = undefined;
@memset(&sufficient_buffer, 0);
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.fcntl(fd, posix.F.GETPATH, &sufficient_buffer))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.BADF => return error.FileNotFound,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NameTooLong,
.RANGE => return error.NameTooLong,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
const n = std.mem.findScalar(u8, &sufficient_buffer, 0) orelse sufficient_buffer.len;
if (n > out_buffer.len) return error.NameTooLong;
@memcpy(out_buffer[0..n], sufficient_buffer[0..n]);
return n;
},
.linux, .serenity, .illumos => {
var procfs_buf: ["/proc/self/path/-2147483648\x00".len]u8 = undefined;
const template = if (native_os == .illumos) "/proc/self/path/{d}" else "/proc/self/fd/{d}";
const proc_path = std.mem.printSentinel(&procfs_buf, template, .{fd}, 0) catch unreachable;
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.readlink(proc_path, out_buffer.ptr, out_buffer.len);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
const len: usize = @bitCast(rc);
return len;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.FAULT => |err| return errnoBug(err),
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
.ILSEQ => |err| return errnoBug(err),
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
},
.freebsd => {
var k_file: std.c.kinfo_file = undefined;
k_file.structsize = std.c.KINFO_FILE_SIZE;
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(std.c.fcntl(fd, std.c.F.KINFO, @intFromPtr(&k_file)))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.BADF => {
syscall.finish();
return error.FileNotFound;
},
else => |err| {
syscall.finish();
return posix.unexpectedErrno(err);
},
}
}
const len = std.mem.findScalar(u8, &k_file.path, 0) orelse k_file.path.len;
if (len == 0) return error.NameTooLong;
@memcpy(out_buffer[0..len], k_file.path[0..len]);
return len;
},
else => return error.OperationUnsupported,
}
comptime unreachable;
}
fn fileHardLink(
userdata: ?*anyopaque,
file: File,
new_dir: Dir,
new_sub_path: []const u8,
options: File.HardLinkOptions,
) File.HardLinkError!void {
_ = userdata;
if (native_os != .linux) return error.OperationUnsupported;
var new_path_buffer: [posix.PATH_MAX]u8 = undefined;
const new_sub_path_posix = try pathToPosix(new_sub_path, &new_path_buffer);
const flags: u32 = if (options.follow_symlinks)
posix.AT.SYMLINK_FOLLOW | posix.AT.EMPTY_PATH
else
posix.AT.EMPTY_PATH;
return linkat(file.handle, "", new_dir.handle, new_sub_path_posix, flags) catch |err| switch (err) {
error.FileNotFound => {
if (options.follow_symlinks) return error.FileNotFound;
var proc_buf: ["/proc/self/fd/-2147483648\x00".len]u8 = undefined;
const proc_path = std.mem.printSentinel(&proc_buf, "/proc/self/fd/{d}", .{file.handle}, 0) catch
unreachable;
return linkat(posix.AT.FDCWD, proc_path, new_dir.handle, new_sub_path_posix, posix.AT.SYMLINK_FOLLOW);
},
else => |e| return e,
};
}
fn linkat(
old_dir: posix.fd_t,
old_path: [*:0]const u8,
new_dir: posix.fd_t,
new_path: [*:0]const u8,
flags: u32,
) File.HardLinkError!void {
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.linkat(old_dir, old_path, new_dir, new_path, flags))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
.ACCES => return syscall.fail(error.AccessDenied),
.DQUOT => return syscall.fail(error.DiskQuota),
.EXIST => return syscall.fail(error.PathAlreadyExists),
.IO => return syscall.fail(error.HardwareFailure),
.LOOP => return syscall.fail(error.SymLinkLoop),
.MLINK => return syscall.fail(error.LinkQuotaExceeded),
.NAMETOOLONG => return syscall.fail(error.NameTooLong),
.NOENT => return syscall.fail(error.FileNotFound),
.NOMEM => return syscall.fail(error.SystemResources),
.NOSPC => return syscall.fail(error.NoSpaceLeft),
.NOTDIR => return syscall.fail(error.NotDir),
.PERM => return syscall.fail(error.PermissionDenied),
.ROFS => return syscall.fail(error.ReadOnlyFileSystem),
.XDEV => return syscall.fail(error.CrossDevice),
.ILSEQ => return syscall.fail(error.BadPathName),
.FAULT => |err| return syscall.errnoBug(err),
.INVAL => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
const dirDeleteFile = switch (native_os) {
.windows => dirDeleteFileWindows,
.wasi => dirDeleteFileWasi,
else => dirDeleteFilePosix,
};
fn dirDeleteFileWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteFileError!void {
return dirDeleteWindows(userdata, dir, sub_path, false) catch |err| switch (err) {
error.DirNotEmpty => unreachable,
else => |e| return e,
};
}
fn dirDeleteFileWasi(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteFileError!void {
if (builtin.link_libc) return dirDeleteFilePosix(userdata, dir, sub_path);
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const wasi = std.os.wasi;
const syscall: Syscall = try .start();
while (true) {
const res = wasi.path_unlink_file(dir.handle, sub_path.ptr, sub_path.len);
switch (res) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.ACCES, .PERM => |e| {
const original_error: Dir.DeleteFileError = switch (e) {
.ACCES => error.AccessDenied,
.PERM => error.PermissionDenied,
else => unreachable,
};
var stat: wasi.filestat_t = undefined;
while (true) {
try syscall.checkCancel();
switch (wasi.path_filestat_get(dir.handle, .{}, sub_path.ptr, sub_path.len, &stat)) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => continue,
else => {
syscall.finish();
return original_error;
},
}
}
if (stat.filetype == .DIRECTORY)
return error.IsDir
else
return original_error;
},
else => |e| {
syscall.finish();
switch (e) {
.BUSY => return error.FileBusy,
.FAULT => |err| return errnoBug(err),
.IO => return error.FileSystem,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.ROFS => return error.ReadOnlyFileSystem,
.NOTCAPABLE => return error.AccessDenied,
.ILSEQ => return error.BadPathName,
.INVAL => |err| return errnoBug(err), // invalid flags, or pathname has . as last component
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirDeleteFilePosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteFileError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.unlinkat(dir.handle, sub_path_posix, 0))) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
// Some systems return permission errors when trying to delete a
// directory, so we need to handle that case specifically and
// translate the error.
.PERM => switch (native_os) {
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos, .freebsd, .netbsd, .dragonfly, .openbsd, .illumos => {
// Don't follow symlinks to match unlinkat (which acts on symlinks rather than follows them).
var st = std.mem.zeroes(posix.Stat);
while (true) {
try syscall.checkCancel();
switch (posix.errno(fstatat_sym(dir.handle, sub_path_posix, &st, posix.AT.SYMLINK_NOFOLLOW))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => continue,
else => {
syscall.finish();
return error.PermissionDenied;
},
}
}
const is_dir = st.mode & posix.S.IFMT == posix.S.IFDIR;
if (is_dir)
return error.IsDir
else
return error.PermissionDenied;
},
else => {
syscall.finish();
return error.PermissionDenied;
},
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.BUSY => return error.FileBusy,
.FAULT => |err| return errnoBug(err),
.IO => return error.FileSystem,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.ROFS => return error.ReadOnlyFileSystem,
.EXIST => |err| return errnoBug(err),
.NOTEMPTY => |err| return errnoBug(err), // Not passing AT.REMOVEDIR
.ILSEQ => return error.BadPathName,
.INVAL => |err| return errnoBug(err), // invalid flags, or pathname has . as last component
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
const dirDeleteDir = switch (native_os) {
.windows => dirDeleteDirWindows,
.wasi => dirDeleteDirWasi,
else => dirDeleteDirPosix,
};
fn dirDeleteDirWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteDirError!void {
return dirDeleteWindows(userdata, dir, sub_path, true) catch |err| switch (err) {
error.IsDir => unreachable,
else => |e| return e,
};
}
fn dirDeleteWindows(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, remove_dir: bool) (Dir.DeleteDirError || Dir.DeleteFileError)!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const w = windows;
if (std.mem.eql(u8, sub_path, "..")) {
// Can't remove the parent directory with an open handle.
return error.FileBusy;
}
var sub_path_w = try sliceToPrefixedFileW(dir.handle, sub_path, .{});
if (std.mem.eql(u8, sub_path, ".")) {
// Windows does not recognize this, but it does work with empty string.
sub_path_w.len = 0;
}
const attr: w.OBJECT.ATTRIBUTES = .{
.RootDirectory = if (Dir.path.isAbsoluteWindowsWtf16(sub_path_w.span())) null else dir.handle,
.ObjectName = @constCast(&sub_path_w.string()),
};
var io_status_block: w.IO_STATUS_BLOCK = undefined;
var tmp_handle: w.HANDLE = undefined;
{
const syscall: Syscall = try .start();
while (true) switch (w.ntdll.NtCreateFile(
&tmp_handle,
.{ .STANDARD = .{
.RIGHTS = .{ .DELETE = true },
.SYNCHRONIZE = true,
} },
&attr,
&io_status_block,
null,
.{},
.VALID_FLAGS,
.OPEN,
.{
.DIRECTORY_FILE = remove_dir,
.IO = .SYNCHRONOUS_NONALERT,
.NON_DIRECTORY_FILE = !remove_dir,
.OPEN_REPARSE_POINT = true, // would we ever want to delete the target instead?
},
null,
0,
)) {
.SUCCESS => break syscall.finish(),
.OBJECT_NAME_INVALID => |err| return syscall.ntstatusBug(err),
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.BAD_NETWORK_PATH => return syscall.fail(error.NetworkNotFound), // \\server was not found
.BAD_NETWORK_NAME => return syscall.fail(error.NetworkNotFound), // \\server was found but \\server\share wasn't
.INVALID_PARAMETER => |err| return syscall.ntstatusBug(err),
.FILE_IS_A_DIRECTORY => return syscall.fail(error.IsDir),
.NOT_A_DIRECTORY => return syscall.fail(error.NotDir),
.SHARING_VIOLATION => return syscall.fail(error.FileBusy),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.DELETE_PENDING => return syscall.finish(),
else => |rc| return syscall.unexpectedNtstatus(rc),
};
}
defer w.CloseHandle(tmp_handle);
// FileDispositionInformationEx has varying levels of support:
// - FILE_DISPOSITION_INFORMATION_EX requires >= win10_rs1
// (INVALID_INFO_CLASS is returned if not supported)
// - Requires the NTFS filesystem
// (on filesystems like FAT32, INVALID_PARAMETER is returned)
// - FILE_DISPOSITION_POSIX_SEMANTICS requires >= win10_rs1
// - FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE requires >= win10_rs5
// (NOT_SUPPORTED is returned if a flag is unsupported)
//
// The strategy here is just to try using FileDispositionInformationEx and fall back to
// FileDispositionInformation if the return value lets us know that some aspect of it is not supported.
const rc = rc: {
// Deletion with posix semantics if the filesystem supports it.
var info: w.FILE.DISPOSITION.INFORMATION.EX = .{ .Flags = .{
.DELETE = true,
.POSIX_SEMANTICS = true,
.IGNORE_READONLY_ATTRIBUTE = true,
} };
const syscall: Syscall = try .start();
while (true) switch (w.ntdll.NtSetInformationFile(
tmp_handle,
&io_status_block,
&info,
@sizeOf(w.FILE.DISPOSITION.INFORMATION.EX),
.DispositionEx,
)) {
.CANCELLED => {
try syscall.checkCancel();
continue;
},
// The filesystem does not support FileDispositionInformationEx
.INVALID_PARAMETER,
// The operating system does not support FileDispositionInformationEx
.INVALID_INFO_CLASS,
// The operating system does not support one of the flags
.NOT_SUPPORTED,
=> break, // use fallback path below; `syscall` still active
// For all other statuses, fall down to the switch below to handle them.
else => |rc| {
syscall.finish();
break :rc rc;
},
};
// Deletion with file pending semantics, which requires waiting or moving
// files to get them removed (from here).
var file_dispo: w.FILE.DISPOSITION.INFORMATION = .{ .DeleteFile = .TRUE };
while (true) switch (w.ntdll.NtSetInformationFile(
tmp_handle,
&io_status_block,
&file_dispo,
@sizeOf(w.FILE.DISPOSITION.INFORMATION),
.Disposition,
)) {
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => |rc| {
syscall.finish();
break :rc rc;
},
};
};
switch (rc) {
.SUCCESS => {},
.DIRECTORY_NOT_EMPTY => return error.DirNotEmpty,
.INVALID_PARAMETER => |err| return w.statusBug(err),
.CANNOT_DELETE => return error.AccessDenied,
.MEDIA_WRITE_PROTECTED => return error.AccessDenied,
.ACCESS_DENIED => return error.AccessDenied,
else => return w.unexpectedStatus(rc),
}
}
fn dirDeleteDirWasi(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteDirError!void {
if (builtin.link_libc) return dirDeleteDirPosix(userdata, dir, sub_path);
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const syscall: Syscall = try .start();
while (true) {
const res = std.os.wasi.path_remove_directory(dir.handle, sub_path.ptr, sub_path.len);
switch (res) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.BUSY => return error.FileBusy,
.FAULT => |err| return errnoBug(err),
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.ROFS => return error.ReadOnlyFileSystem,
.NOTEMPTY => return error.DirNotEmpty,
.NOTCAPABLE => return error.AccessDenied,
.ILSEQ => return error.BadPathName,
.INVAL => |err| return errnoBug(err), // invalid flags, or pathname has . as last component
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirDeleteDirPosix(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteDirError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.unlinkat(dir.handle, sub_path_posix, posix.AT.REMOVEDIR))) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.BUSY => return error.FileBusy,
.FAULT => |err| return errnoBug(err),
.IO => return error.FileSystem,
.ISDIR => |err| return errnoBug(err),
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.ROFS => return error.ReadOnlyFileSystem,
.EXIST => |err| return errnoBug(err),
.NOTEMPTY => return error.DirNotEmpty,
.ILSEQ => return error.BadPathName,
.INVAL => |err| return errnoBug(err), // invalid flags, or pathname has . as last component
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
const dirRename = switch (native_os) {
.windows => dirRenameWindows,
.wasi => dirRenameWasi,
else => dirRenamePosix,
};
fn dirRenameWindows(
userdata: ?*anyopaque,
old_dir: Dir,
old_sub_path: []const u8,
new_dir: Dir,
new_sub_path: []const u8,
) Dir.RenameError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
return dirRenameWindowsInner(old_dir, old_sub_path, new_dir, new_sub_path, true) catch |err| switch (err) {
error.PathAlreadyExists => return error.Unexpected,
error.OperationUnsupported => return error.Unexpected,
else => |e| return e,
};
}
fn dirRenamePreserve(
userdata: ?*anyopaque,
old_dir: Dir,
old_sub_path: []const u8,
new_dir: Dir,
new_sub_path: []const u8,
) Dir.RenamePreserveError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (is_windows) return dirRenameWindowsInner(old_dir, old_sub_path, new_dir, new_sub_path, false);
if (is_darwin) return dirRenamePreserveDarwin(old_dir, old_sub_path, new_dir, new_sub_path);
if (native_os == .linux) return dirRenamePreserveLinux(old_dir, old_sub_path, new_dir, new_sub_path);
// Make a hard link then delete the original.
try dirHardLink(t, old_dir, old_sub_path, new_dir, new_sub_path, .{ .follow_symlinks = false });
const prev = swapCancelProtection(t, .blocked);
defer _ = swapCancelProtection(t, prev);
dirDeleteFile(t, old_dir, old_sub_path) catch {};
}
fn dirRenameWindowsInner(
old_dir: Dir,
old_sub_path: []const u8,
new_dir: Dir,
new_sub_path: []const u8,
replace_if_exists: bool,
) Dir.RenamePreserveError!void {
const w = windows;
const old_path_w_buf = try sliceToPrefixedFileW(old_dir.handle, old_sub_path, .{});
const old_path_w = old_path_w_buf.span();
const new_path_w_buf = try sliceToPrefixedFileW(new_dir.handle, new_sub_path, .{});
const new_path_w = new_path_w_buf.span();
const src_fd = src_fd: {
if (OpenFile(old_path_w, .{
.dir = old_dir.handle,
.access_mask = .{
.GENERIC = .{ .WRITE = true },
.STANDARD = .{
.RIGHTS = .{ .DELETE = true },
.SYNCHRONIZE = true,
},
},
.creation = .OPEN,
.filter = .any, // This function is supposed to rename both files and directories.
.follow_symlinks = false,
})) |handle| {
break :src_fd handle;
} else |err| switch (err) {
error.WouldBlock => unreachable, // Not possible without `.share_access_nonblocking = true`.
else => |e| return e,
}
};
defer w.CloseHandle(src_fd);
var rc: w.NTSTATUS = undefined;
// FileRenameInformationEx has varying levels of support:
// - FILE_RENAME_INFORMATION_EX requires >= win10_rs1
// (INVALID_INFO_CLASS is returned if not supported)
// - Requires the NTFS filesystem
// (on filesystems like FAT32, INVALID_PARAMETER is returned)
// - FILE_RENAME_POSIX_SEMANTICS requires >= win10_rs1
// - FILE_RENAME_IGNORE_READONLY_ATTRIBUTE requires >= win10_rs5
// (NOT_SUPPORTED is returned if a flag is unsupported)
//
// The strategy here is just to try using FileRenameInformationEx and fall back to
// FileRenameInformation if the return value lets us know that some aspect of it is not supported.
const need_fallback = need_fallback: {
var rename_info: w.FILE.RENAME_INFORMATION = .init(.{
.Flags = .{
.REPLACE_IF_EXISTS = replace_if_exists,
.POSIX_SEMANTICS = true,
.IGNORE_READONLY_ATTRIBUTE = true,
},
.RootDirectory = if (Dir.path.isAbsoluteWindowsWtf16(new_path_w)) null else new_dir.handle,
.FileName = new_path_w,
});
var io_status_block: w.IO_STATUS_BLOCK = undefined;
const rename_info_buf = rename_info.toBuffer();
rc = w.ntdll.NtSetInformationFile(
src_fd,
&io_status_block,
rename_info_buf.ptr,
@intCast(rename_info_buf.len),
.RenameEx,
);
switch (rc) {
.SUCCESS => return,
// The filesystem does not support FileDispositionInformationEx
.INVALID_PARAMETER,
// The operating system does not support FileDispositionInformationEx
.INVALID_INFO_CLASS,
// The operating system does not support one of the flags
.NOT_SUPPORTED,
=> break :need_fallback true,
// For all other statuses, fall down to the switch below to handle them.
else => break :need_fallback false,
}
};
if (need_fallback) {
var rename_info: w.FILE.RENAME_INFORMATION = .init(.{
.Flags = .{ .REPLACE_IF_EXISTS = replace_if_exists },
.RootDirectory = if (Dir.path.isAbsoluteWindowsWtf16(new_path_w)) null else new_dir.handle,
.FileName = new_path_w,
});
var io_status_block: w.IO_STATUS_BLOCK = undefined;
const rename_info_buf = rename_info.toBuffer();
rc = w.ntdll.NtSetInformationFile(
src_fd,
&io_status_block,
rename_info_buf.ptr,
@intCast(rename_info_buf.len),
.Rename,
);
}
switch (rc) {
.SUCCESS => {},
.INVALID_HANDLE => |err| return w.statusBug(err),
.INVALID_PARAMETER => |err| return w.statusBug(err),
.OBJECT_PATH_SYNTAX_BAD => |err| return w.statusBug(err),
.ACCESS_DENIED => return error.AccessDenied,
.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
.OBJECT_PATH_NOT_FOUND => return error.FileNotFound,
.NOT_SAME_DEVICE => return error.CrossDevice,
.OBJECT_NAME_COLLISION => return error.PathAlreadyExists,
.DIRECTORY_NOT_EMPTY => return error.DirNotEmpty,
.FILE_IS_A_DIRECTORY => return error.IsDir,
.NOT_A_DIRECTORY => return error.NotDir,
else => return w.unexpectedStatus(rc),
}
}
fn dirRenameWasi(
userdata: ?*anyopaque,
old_dir: Dir,
old_sub_path: []const u8,
new_dir: Dir,
new_sub_path: []const u8,
) Dir.RenameError!void {
if (builtin.link_libc) return dirRenamePosix(userdata, old_dir, old_sub_path, new_dir, new_sub_path);
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const syscall: Syscall = try .start();
while (true) {
switch (std.os.wasi.path_rename(old_dir.handle, old_sub_path.ptr, old_sub_path.len, new_dir.handle, new_sub_path.ptr, new_sub_path.len)) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.BUSY => return error.FileBusy,
.DQUOT => return error.DiskQuota,
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.EXIST => return error.DirNotEmpty,
.NOTEMPTY => return error.DirNotEmpty,
.ROFS => return error.ReadOnlyFileSystem,
.XDEV => return error.CrossDevice,
.NOTCAPABLE => return error.AccessDenied,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirRenamePosix(
userdata: ?*anyopaque,
old_dir: Dir,
old_sub_path: []const u8,
new_dir: Dir,
new_sub_path: []const u8,
) Dir.RenameError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var old_path_buffer: [posix.PATH_MAX]u8 = undefined;
var new_path_buffer: [posix.PATH_MAX]u8 = undefined;
const old_sub_path_posix = try pathToPosix(old_sub_path, &old_path_buffer);
const new_sub_path_posix = try pathToPosix(new_sub_path, &new_path_buffer);
return renameat(old_dir.handle, old_sub_path_posix, new_dir.handle, new_sub_path_posix);
}
fn dirRenamePreserveDarwin(
old_dir: Dir,
old_sub_path: []const u8,
new_dir: Dir,
new_sub_path: []const u8,
) Dir.RenamePreserveError!void {
var old_path_buffer: [posix.PATH_MAX]u8 = undefined;
var new_path_buffer: [posix.PATH_MAX]u8 = undefined;
const old_sub_path_posix = try pathToPosix(old_sub_path, &old_path_buffer);
const new_sub_path_posix = try pathToPosix(new_sub_path, &new_path_buffer);
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(std.c.renameatx_np(
old_dir.handle,
old_sub_path_posix,
new_dir.handle,
new_sub_path_posix,
.{ .EXCL = true },
))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.INVAL => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err),
.BADF => |err| return syscall.errnoBug(err),
.ISDIR => |err| return syscall.errnoBug(err),
.NOTEMPTY => |err| return syscall.errnoBug(err),
.OPNOTSUPP => return syscall.fail(error.OperationUnsupported),
.IO => return syscall.fail(error.HardwareFailure),
.DEADLK => return syscall.fail(error.AccessDenied),
.ACCES => return syscall.fail(error.AccessDenied),
.DQUOT => return syscall.fail(error.DiskQuota),
.EXIST => return syscall.fail(error.PathAlreadyExists),
.LOOP => return syscall.fail(error.LinkQuotaExceeded),
.NAMETOOLONG => return syscall.fail(error.NameTooLong),
.NOENT => return syscall.fail(error.FileNotFound),
.NOSPC => return syscall.fail(error.NoSpaceLeft),
.NOTDIR => return syscall.fail(error.NotDir),
.PERM => return syscall.fail(error.PermissionDenied),
.ROFS => return syscall.fail(error.ReadOnlyFileSystem),
.XDEV => return syscall.fail(error.CrossDevice),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
fn dirRenamePreserveLinux(
old_dir: Dir,
old_sub_path: []const u8,
new_dir: Dir,
new_sub_path: []const u8,
) Dir.RenamePreserveError!void {
const linux = std.os.linux;
var old_path_buffer: [linux.PATH_MAX]u8 = undefined;
var new_path_buffer: [linux.PATH_MAX]u8 = undefined;
const old_sub_path_posix = try pathToPosix(old_sub_path, &old_path_buffer);
const new_sub_path_posix = try pathToPosix(new_sub_path, &new_path_buffer);
const syscall: Syscall = try .start();
while (true) switch (linux.errno(linux.renameat2(
old_dir.handle,
old_sub_path_posix,
new_dir.handle,
new_sub_path_posix,
.{ .NOREPLACE = true },
))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
.ACCES => return syscall.fail(error.AccessDenied),
.PERM => return syscall.fail(error.PermissionDenied),
.BUSY => return syscall.fail(error.FileBusy),
.DQUOT => return syscall.fail(error.DiskQuota),
.ISDIR => return syscall.fail(error.IsDir),
.LOOP => return syscall.fail(error.SymLinkLoop),
.MLINK => return syscall.fail(error.LinkQuotaExceeded),
.NAMETOOLONG => return syscall.fail(error.NameTooLong),
.NOENT => return syscall.fail(error.FileNotFound),
.NOTDIR => return syscall.fail(error.NotDir),
.NOMEM => return syscall.fail(error.SystemResources),
.NOSPC => return syscall.fail(error.NoSpaceLeft),
.EXIST => return syscall.fail(error.PathAlreadyExists),
.NOTEMPTY => return syscall.fail(error.DirNotEmpty),
.ROFS => return syscall.fail(error.ReadOnlyFileSystem),
.XDEV => return syscall.fail(error.CrossDevice),
.ILSEQ => return syscall.fail(error.BadPathName),
.FAULT => |err| return syscall.errnoBug(err),
.INVAL => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
};
}
fn renameat(
old_dir: posix.fd_t,
old_sub_path: [*:0]const u8,
new_dir: posix.fd_t,
new_sub_path: [*:0]const u8,
) Dir.RenameError!void {
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.renameat(old_dir, old_sub_path, new_dir, new_sub_path))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
.ACCES => return syscall.fail(error.AccessDenied),
.PERM => return syscall.fail(error.PermissionDenied),
.BUSY => return syscall.fail(error.FileBusy),
.DQUOT => return syscall.fail(error.DiskQuota),
.ISDIR => return syscall.fail(error.IsDir),
.IO => return syscall.fail(error.HardwareFailure),
.LOOP => return syscall.fail(error.SymLinkLoop),
.MLINK => return syscall.fail(error.LinkQuotaExceeded),
.NAMETOOLONG => return syscall.fail(error.NameTooLong),
.NOENT => return syscall.fail(error.FileNotFound),
.NOTDIR => return syscall.fail(error.NotDir),
.NOMEM => return syscall.fail(error.SystemResources),
.NOSPC => return syscall.fail(error.NoSpaceLeft),
.EXIST => return syscall.fail(error.DirNotEmpty),
.NOTEMPTY => return syscall.fail(error.DirNotEmpty),
.ROFS => return syscall.fail(error.ReadOnlyFileSystem),
.XDEV => return syscall.fail(error.CrossDevice),
.ILSEQ => return syscall.fail(error.BadPathName),
.FAULT => |err| return syscall.errnoBug(err),
.INVAL => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
};
}
const dirSymLink = switch (native_os) {
.windows => dirSymLinkWindows,
.wasi => dirSymLinkWasi,
else => dirSymLinkPosix,
};
fn dirSymLinkWindows(
userdata: ?*anyopaque,
dir: Dir,
target_path: []const u8,
sym_link_path: []const u8,
flags: Dir.SymLinkFlags,
) Dir.SymLinkError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const w = windows;
// Target path does not use sliceToPrefixedFileW because certain paths
// are handled differently when creating a symlink than they would be
// when converting to an NT namespaced path.
var target_path_w: WindowsPathSpace = undefined;
target_path_w.len = try w.wtf8ToWtf16Le(&target_path_w.data, target_path);
target_path_w.data[target_path_w.len] = 0;
// However, we need to canonicalize any path separators to `\`, since if
// the target path is relative, then it must use `\` as the path separator.
std.mem.replaceScalar(
u16,
target_path_w.data[0..target_path_w.len],
std.mem.nativeToLittle(u16, '/'),
std.mem.nativeToLittle(u16, '\\'),
);
const sym_link_path_w = try sliceToPrefixedFileW(dir.handle, sym_link_path, .{});
const SYMLINK_DATA = extern struct {
ReparseTag: w.IO_REPARSE_TAG,
ReparseDataLength: w.USHORT,
Reserved: w.USHORT,
SubstituteNameOffset: w.USHORT,
SubstituteNameLength: w.USHORT,
PrintNameOffset: w.USHORT,
PrintNameLength: w.USHORT,
Flags: w.ULONG,
};
const symlink_handle = handle: {
if (OpenFile(sym_link_path_w.span(), .{
.access_mask = .{
.GENERIC = .{ .READ = true, .WRITE = true },
.STANDARD = .{ .SYNCHRONIZE = true },
},
.dir = dir.handle,
.creation = .CREATE,
.filter = if (flags.is_directory) .dir_only else .non_directory_only,
})) |handle| {
break :handle handle;
} else |err| switch (err) {
error.IsDir => return error.PathAlreadyExists,
error.NotDir => return error.Unexpected,
error.WouldBlock => return error.Unexpected,
error.PipeBusy => return error.Unexpected,
error.FileBusy => return error.Unexpected,
error.NoDevice => return error.Unexpected,
error.AntivirusInterference => return error.Unexpected,
else => |e| return e,
}
};
defer w.CloseHandle(symlink_handle);
// Relevant portions of the documentation:
// > Relative links are specified using the following conventions:
// > - Root relative—for example, "\Windows\System32" resolves to "current drive:\Windows\System32".
// > - Current working directory–relative—for example, if the current working directory is
// > C:\Windows\System32, "C:File.txt" resolves to "C:\Windows\System32\File.txt".
// > Note: If you specify a current working directory–relative link, it is created as an absolute
// > link, due to the way the current working directory is processed based on the user and the thread.
// https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsymboliclinkw
var is_target_absolute = false;
const final_target_path = target_path: {
if (w.hasCommonNtPrefix(u16, target_path_w.span())) {
// Already an NT path, no need to do anything to it
break :target_path target_path_w.span();
} else {
switch (Dir.path.getWin32PathType(u16, target_path_w.span())) {
// Rooted paths need to avoid getting put through wToPrefixedFileW
// (and they are treated as relative in this context)
// Note: It seems that rooted paths in symbolic links are relative to
// the drive that the symbolic exists on, not to the CWD's drive.
// So, if the symlink is on C:\ and the CWD is on D:\,
// it will still resolve the path relative to the root of
// the C:\ drive.
.rooted => break :target_path target_path_w.span(),
// Keep relative paths relative, but anything else needs to get NT-prefixed.
else => if (!Dir.path.isAbsoluteWindowsWtf16(target_path_w.span()))
break :target_path target_path_w.span(),
}
}
var prefixed_target_path = try wToPrefixedFileW(dir.handle, target_path_w.span(), .{});
// We do this after prefixing to ensure that drive-relative paths are treated as absolute
is_target_absolute = Dir.path.isAbsoluteWindowsWtf16(prefixed_target_path.span());
break :target_path prefixed_target_path.span();
};
// prepare reparse data buffer
var buffer: [w.MAXIMUM_REPARSE_DATA_BUFFER_SIZE]u8 = undefined;
const buf_len = @sizeOf(SYMLINK_DATA) + final_target_path.len * 4;
const header_len = @sizeOf(w.ULONG) + @sizeOf(w.USHORT) * 2;
const target_is_absolute = Dir.path.isAbsoluteWindowsWtf16(final_target_path);
const symlink_data: SYMLINK_DATA = .{
.ReparseTag = .SYMLINK,
.ReparseDataLength = @intCast(buf_len - header_len),
.Reserved = 0,
.SubstituteNameOffset = @intCast(final_target_path.len * 2),
.SubstituteNameLength = @intCast(final_target_path.len * 2),
.PrintNameOffset = 0,
.PrintNameLength = @intCast(final_target_path.len * 2),
.Flags = if (!target_is_absolute) w.SYMLINK_FLAG_RELATIVE else 0,
};
@memcpy(buffer[0..@sizeOf(SYMLINK_DATA)], std.mem.asBytes(&symlink_data));
@memcpy(buffer[@sizeOf(SYMLINK_DATA)..][0 .. final_target_path.len * 2], @as([*]const u8, @ptrCast(final_target_path)));
const paths_start = @sizeOf(SYMLINK_DATA) + final_target_path.len * 2;
@memcpy(buffer[paths_start..][0 .. final_target_path.len * 2], @as([*]const u8, @ptrCast(final_target_path)));
switch ((try deviceIoControl(&.{
.file = .{ .handle = symlink_handle, .flags = .{ .nonblocking = false } },
.code = .SET_REPARSE_POINT,
.in = buffer[0..buf_len],
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
.PRIVILEGE_NOT_HELD => return error.PermissionDenied,
.ACCESS_DENIED => return error.AccessDenied,
.INVALID_DEVICE_REQUEST => return error.FileSystem,
else => |status| return w.unexpectedStatus(status),
}
}
fn dirSymLinkWasi(
userdata: ?*anyopaque,
dir: Dir,
target_path: []const u8,
sym_link_path: []const u8,
flags: Dir.SymLinkFlags,
) Dir.SymLinkError!void {
if (builtin.link_libc) return dirSymLinkPosix(userdata, dir, target_path, sym_link_path, flags);
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const syscall: Syscall = try .start();
while (true) {
switch (std.os.wasi.path_symlink(target_path.ptr, target_path.len, dir.handle, sym_link_path.ptr, sym_link_path.len)) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.ROFS => return error.ReadOnlyFileSystem,
.NOTCAPABLE => return error.AccessDenied,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirSymLinkPosix(
userdata: ?*anyopaque,
dir: Dir,
target_path: []const u8,
sym_link_path: []const u8,
flags: Dir.SymLinkFlags,
) Dir.SymLinkError!void {
_ = flags;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var target_path_buffer: [posix.PATH_MAX]u8 = undefined;
var sym_link_path_buffer: [posix.PATH_MAX]u8 = undefined;
const target_path_posix = try pathToPosix(target_path, &target_path_buffer);
const sym_link_path_posix = try pathToPosix(sym_link_path, &sym_link_path_buffer);
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.symlinkat(target_path_posix, dir.handle, sym_link_path_posix))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.ROFS => return error.ReadOnlyFileSystem,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirReadLink(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
switch (native_os) {
.windows => return dirReadLinkWindows(dir, sub_path, buffer),
.wasi => return dirReadLinkWasi(dir, sub_path, buffer),
else => return dirReadLinkPosix(dir, sub_path, buffer),
}
}
fn dirReadLinkWindows(dir: Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usize {
// This gets used once for `sub_path` and then reused again temporarily
// before converting back to `buffer`.
var sub_path_w = try sliceToPrefixedFileW(dir.handle, sub_path, .{});
const attr: windows.OBJECT.ATTRIBUTES = .{
.RootDirectory = if (Dir.path.isAbsoluteWindowsWtf16(sub_path_w.span())) null else dir.handle,
.ObjectName = @constCast(&sub_path_w.string()),
};
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var result_handle: windows.HANDLE = undefined;
var attempt: u5 = 0;
var syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtCreateFile(
&result_handle,
.{
.SPECIFIC = .{ .FILE = .{
.READ_ATTRIBUTES = true,
} },
.STANDARD = .{ .SYNCHRONIZE = true },
},
&attr,
&io_status_block,
null,
.{ .NORMAL = true },
.VALID_FLAGS,
.OPEN,
.{
.DIRECTORY_FILE = false,
.NON_DIRECTORY_FILE = false,
.IO = .SYNCHRONOUS_NONALERT,
.OPEN_REPARSE_POINT = true,
},
null,
0,
)) {
.SUCCESS => {
syscall.finish();
break;
},
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.SHARING_VIOLATION => {
// This occurs if the file attempting to be opened is a running
// executable. However, there's a kernel bug: the error may be
// incorrectly returned for an indeterminate amount of time
// after an executable file is closed. Here we work around the
// kernel bug with retry attempts.
syscall.finish();
if (max_windows_kernel_bug_retries - attempt == 0) return error.FileBusy;
try parking_sleep.sleep(.{ .duration = .{
.raw = .fromMilliseconds((@as(u32, 1) << attempt) >> 1),
.clock = .awake,
} });
attempt += 1;
syscall = try .start();
continue;
},
.DELETE_PENDING => {
// This error means that there *was* a file in this location on
// the file system, but it was deleted. However, the OS is not
// finished with the deletion operation, and so this CreateFile
// call has failed. Here, we simulate the kernel bug being
// fixed by sleeping and retrying until the error goes away.
syscall.finish();
if (max_windows_kernel_bug_retries - attempt == 0) return error.FileBusy;
try parking_sleep.sleep(.{ .duration = .{
.raw = .fromMilliseconds((@as(u32, 1) << attempt) >> 1),
.clock = .awake,
} });
attempt += 1;
syscall = try .start();
continue;
},
.OBJECT_NAME_INVALID => return syscall.fail(error.BadPathName),
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.BAD_NETWORK_PATH => return syscall.fail(error.NetworkNotFound), // \\server was not found
.BAD_NETWORK_NAME => return syscall.fail(error.NetworkNotFound), // \\server was found but \\server\share wasn't
.NO_MEDIA_IN_DEVICE => return syscall.fail(error.FileNotFound),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.PIPE_BUSY => return syscall.fail(error.AccessDenied),
.PIPE_NOT_AVAILABLE => return syscall.fail(error.FileNotFound),
.USER_MAPPED_FILE => return syscall.fail(error.AccessDenied),
.VIRUS_INFECTED, .VIRUS_DELETED => return syscall.fail(error.AntivirusInterference),
.INVALID_PARAMETER => |status| return syscall.ntstatusBug(status),
.OBJECT_PATH_SYNTAX_BAD => |status| return syscall.ntstatusBug(status),
.INVALID_HANDLE => |status| return syscall.ntstatusBug(status),
else => |status| return syscall.unexpectedNtstatus(status),
};
defer windows.CloseHandle(result_handle);
var reparse_buf: [windows.MAXIMUM_REPARSE_DATA_BUFFER_SIZE]u8 align(@alignOf(windows.REPARSE_DATA_BUFFER)) = undefined;
switch ((try deviceIoControl(&.{
.file = .{ .handle = result_handle, .flags = .{ .nonblocking = false } },
.code = .GET_REPARSE_POINT,
.out = &reparse_buf,
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.NOT_A_REPARSE_POINT => return error.NotLink,
else => |status| return windows.unexpectedStatus(status),
}
const reparse_struct: *const windows.REPARSE_DATA_BUFFER = @ptrCast(@alignCast(&reparse_buf));
const IoReparseTagInt = @typeInfo(windows.IO_REPARSE_TAG).@"struct".backing_integer.?;
const result_w = switch (@as(IoReparseTagInt, @bitCast(reparse_struct.ReparseTag))) {
@as(IoReparseTagInt, @bitCast(windows.IO_REPARSE_TAG.SYMLINK)) => r: {
const buf: *const windows.SYMBOLIC_LINK_REPARSE_BUFFER = @ptrCast(@alignCast(&reparse_struct.DataBuffer[0]));
const offset = buf.SubstituteNameOffset >> 1;
const len = buf.SubstituteNameLength >> 1;
const path_buf = @as([*]const u16, &buf.PathBuffer);
const is_relative = buf.Flags & windows.SYMLINK_FLAG_RELATIVE != 0;
break :r try parseReadLinkPath(path_buf[offset..][0..len], is_relative, &sub_path_w.data);
},
@as(IoReparseTagInt, @bitCast(windows.IO_REPARSE_TAG.MOUNT_POINT)) => r: {
const buf: *const windows.MOUNT_POINT_REPARSE_BUFFER = @ptrCast(@alignCast(&reparse_struct.DataBuffer[0]));
const offset = buf.SubstituteNameOffset >> 1;
const len = buf.SubstituteNameLength >> 1;
const path_buf = @as([*]const u16, &buf.PathBuffer);
break :r try parseReadLinkPath(path_buf[offset..][0..len], false, &sub_path_w.data);
},
else => return error.UnsupportedReparsePointType,
};
const len = std.unicode.calcWtf8Len(result_w);
if (len > buffer.len) return error.NameTooLong;
return std.unicode.wtf16LeToWtf8(buffer, result_w);
}
fn parseReadLinkPath(path: []const u16, is_relative: bool, out_buffer: []u16) error{NameTooLong}![]u16 {
path: {
if (is_relative) break :path;
return windows.ntToWin32Namespace(path, out_buffer) catch |err| switch (err) {
error.NameTooLong => |e| return e,
error.NotNtPath => break :path,
};
}
if (out_buffer.len < path.len) return error.NameTooLong;
const dest = out_buffer[0..path.len];
@memcpy(dest, path);
return dest;
}
fn dirReadLinkWasi(dir: Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usize {
if (builtin.link_libc) return dirReadLinkPosix(dir, sub_path, buffer);
var n: usize = undefined;
const syscall: Syscall = try .start();
while (true) {
switch (std.os.wasi.path_readlink(dir.handle, sub_path.ptr, sub_path.len, buffer.ptr, buffer.len, &n)) {
.SUCCESS => {
syscall.finish();
return n;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.FAULT => |err| return errnoBug(err),
.INVAL => return error.NotLink,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
.NOTCAPABLE => return error.AccessDenied,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirReadLinkPosix(dir: Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usize {
var sub_path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &sub_path_buffer);
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.readlinkat(dir.handle, sub_path_posix, buffer.ptr, buffer.len);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
const len: usize = @bitCast(rc);
return len;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.FAULT => |err| return errnoBug(err),
.INVAL => return error.NotLink,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
const dirSetPermissions = switch (native_os) {
.windows => dirSetPermissionsWindows,
else => dirSetPermissionsPosix,
};
fn dirSetPermissionsWindows(userdata: ?*anyopaque, dir: Dir, permissions: Dir.Permissions) Dir.SetPermissionsError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
_ = dir;
_ = permissions;
@panic("TODO implement dirSetPermissionsWindows");
}
fn dirSetPermissionsPosix(userdata: ?*anyopaque, dir: Dir, permissions: Dir.Permissions) Dir.SetPermissionsError!void {
if (@sizeOf(Dir.Permissions) == 0) return;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
return setPermissionsPosix(dir.handle, permissions.toMode());
}
fn dirSetFilePermissions(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
permissions: Dir.Permissions,
options: Dir.SetFilePermissionsOptions,
) Dir.SetFilePermissionsError!void {
if (@sizeOf(Dir.Permissions) == 0) return;
if (is_windows) @panic("TODO implement dirSetFilePermissions windows");
const t: *Threaded = @ptrCast(@alignCast(userdata));
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const mode = permissions.toMode();
const flags: u32 = if (!options.follow_symlinks) posix.AT.SYMLINK_NOFOLLOW else 0;
return posixFchmodat(t, dir.handle, sub_path_posix, mode, flags);
}
fn posixFchmodat(
t: *Threaded,
dir_fd: posix.fd_t,
path: [*:0]const u8,
mode: posix.mode_t,
flags: u32,
) Dir.SetFilePermissionsError!void {
// No special handling for linux is needed if we can use the libc fallback
// or `flags` is empty. Glibc only added the fallback in 2.32.
if (have_fchmodat_flags or flags == 0) {
const syscall: Syscall = try .start();
while (true) {
const rc = if (have_fchmodat_flags or builtin.link_libc)
posix.system.fchmodat(dir_fd, path, mode, flags)
else
posix.system.fchmodat(dir_fd, path, mode);
switch (posix.errno(rc)) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.OPNOTSUPP => return error.OperationUnsupported,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
if (@atomicLoad(UseFchmodat2, &t.use_fchmodat2, .monotonic) == .disabled)
return fchmodatFallback(dir_fd, path, mode);
comptime assert(native_os == .linux);
const syscall: Syscall = try .start();
while (true) {
switch (std.os.linux.errno(std.os.linux.fchmodat2(dir_fd, path, mode, flags))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.FileNotFound,
.OPNOTSUPP => return error.OperationUnsupported,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
.NOSYS => {
@atomicStore(UseFchmodat2, &t.use_fchmodat2, .disabled, .monotonic);
return fchmodatFallback(dir_fd, path, mode);
},
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn fchmodatFallback(
dir_fd: posix.fd_t,
path: [*:0]const u8,
mode: posix.mode_t,
) Dir.SetFilePermissionsError!void {
comptime assert(native_os == .linux);
// Fallback to changing permissions using procfs:
//
// 1. Open `path` as a `PATH` descriptor.
// 2. Stat the fd and check if it isn't a symbolic link.
// 3. Generate the procfs reference to the fd via `/proc/self/fd/{fd}`.
// 4. Pass the procfs path to `chmod` with the `mode`.
const path_fd: posix.fd_t = fd: {
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.openat(dir_fd, path, .{
.PATH = true,
.NOFOLLOW = true,
.CLOEXEC = true,
}, @as(posix.mode_t, 0));
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
break :fd @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
};
defer closeFd(path_fd);
const path_mode = mode: {
const sys = if (statx_use_c) std.c else std.os.linux;
const syscall: Syscall = try .start();
while (true) {
var statx = std.mem.zeroes(std.os.linux.Statx);
switch (sys.errno(sys.statx(path_fd, "", posix.AT.EMPTY_PATH, .{ .TYPE = true }, &statx))) {
.SUCCESS => {
syscall.finish();
if (!statx.mask.TYPE) return error.Unexpected;
break :mode statx.mode;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.LOOP => return error.SymLinkLoop,
.NOMEM => return error.SystemResources,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
};
// Even though we only wanted TYPE, the kernel can still fill in the additional bits.
if ((path_mode & posix.S.IFMT) == posix.S.IFLNK)
return error.OperationUnsupported;
var procfs_buf: ["/proc/self/fd/-2147483648\x00".len]u8 = undefined;
const proc_path = std.mem.printSentinel(&procfs_buf, "/proc/self/fd/{d}", .{path_fd}, 0) catch unreachable;
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.chmod(proc_path, mode))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.NOENT => return error.OperationUnsupported, // procfs not mounted.
.BADF => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.FileNotFound,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
const dirSetOwner = switch (native_os) {
.windows => dirSetOwnerUnsupported,
else => dirSetOwnerPosix,
};
fn dirSetOwnerUnsupported(userdata: ?*anyopaque, dir: Dir, owner: ?File.Uid, group: ?File.Gid) Dir.SetOwnerError!void {
_ = userdata;
_ = dir;
_ = owner;
_ = group;
return error.Unexpected;
}
fn dirSetOwnerPosix(userdata: ?*anyopaque, dir: Dir, owner: ?File.Uid, group: ?File.Gid) Dir.SetOwnerError!void {
if (!have_fchown) return error.Unexpected; // Unsupported OS, don't call this function.
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const uid = owner orelse ~@as(posix.uid_t, 0);
const gid = group orelse ~@as(posix.gid_t, 0);
return posixFchown(dir.handle, uid, gid);
}
fn posixFchown(fd: posix.fd_t, uid: posix.uid_t, gid: posix.gid_t) File.SetOwnerError!void {
comptime assert(have_fchown);
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.fchown(fd, uid, gid))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // likely fd refers to directory opened without `Dir.OpenOptions.iterate`
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.FileNotFound,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirSetFileOwner(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
owner: ?File.Uid,
group: ?File.Gid,
options: Dir.SetFileOwnerOptions,
) Dir.SetFileOwnerError!void {
if (!have_fchown) return error.Unexpected; // Unsupported OS, don't call this function.
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
_ = dir;
_ = sub_path_posix;
_ = owner;
_ = group;
_ = options;
@panic("TODO implement dirSetFileOwner");
}
const fileSync = switch (native_os) {
.windows => fileSyncWindows,
.wasi => fileSyncWasi,
else => fileSyncPosix,
};
fn fileSyncWindows(userdata: ?*anyopaque, file: File) File.SyncError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
const syscall: Syscall = try .start();
while (true) {
switch (windows.ntdll.NtFlushBuffersFile(file.handle, &io_status_block)) {
.SUCCESS => break syscall.finish(),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.INVALID_HANDLE => unreachable,
.ACCESS_DENIED => return syscall.fail(error.AccessDenied), // a sync was performed but the system couldn't update the access time
.UNEXPECTED_NETWORK_ERROR => return syscall.fail(error.InputOutput),
else => |status| return syscall.unexpectedNtstatus(status),
}
}
}
fn fileSyncPosix(userdata: ?*anyopaque, file: File) File.SyncError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.fsync(file.handle))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ROFS => |err| return errnoBug(err),
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.DQUOT => return error.DiskQuota,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn fileSyncWasi(userdata: ?*anyopaque, file: File) File.SyncError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const syscall: Syscall = try .start();
while (true) {
switch (std.os.wasi.fd_sync(file.handle)) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ROFS => |err| return errnoBug(err),
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.DQUOT => return error.DiskQuota,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn fileIsTty(userdata: ?*anyopaque, file: File) Io.Cancelable!bool {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
return isTty(file);
}
fn isTty(file: File) Io.Cancelable!bool {
if (is_windows) {
var get_console_mode = windows.CONSOLE.USER_IO.GET_MODE;
switch ((try deviceIoControl(&.{
.file = .{
.handle = windows.peb().ProcessParameters.ConsoleHandle,
.flags = .{ .nonblocking = false },
},
.code = windows.IOCTL.CONDRV.ISSUE_USER_IO,
.in = @ptrCast(&get_console_mode.request(file, 0, .{}, 0, .{})),
})).u.Status) {
.SUCCESS => return true,
.CANCELLED => unreachable,
.INVALID_HANDLE => return isCygwinPty(file),
else => return false,
}
}
if (builtin.link_libc) {
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.isatty(file.handle);
switch (posix.errno(rc - 1)) {
.SUCCESS => {
syscall.finish();
return true;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => {
syscall.finish();
return false;
},
}
}
}
if (native_os == .wasi) {
var statbuf: std.os.wasi.fdstat_t = undefined;
const err = std.os.wasi.fd_fdstat_get(file.handle, &statbuf);
if (err != .SUCCESS)
return false;
// A tty is a character device that we can't seek or tell on.
if (statbuf.fs_filetype != .CHARACTER_DEVICE)
return false;
if (statbuf.fs_rights_base.FD_SEEK or statbuf.fs_rights_base.FD_TELL)
return false;
return true;
}
if (native_os == .linux) {
const linux = std.os.linux;
const syscall: Syscall = try .start();
while (true) {
var wsz: posix.winsize = undefined;
const fd: usize = @bitCast(@as(isize, file.handle));
const rc = linux.syscall3(.ioctl, fd, linux.T.IOCGWINSZ, @intFromPtr(&wsz));
switch (linux.errno(rc)) {
.SUCCESS => {
syscall.finish();
return true;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => {
syscall.finish();
return false;
},
}
}
}
@compileError("unimplemented");
}
fn fileEnableAnsiEscapeCodes(userdata: ?*anyopaque, file: File) File.EnableAnsiEscapeCodesError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (!is_windows) return if (!try supportsAnsiEscapeCodes(t, file)) error.NotTerminalDevice;
// For Windows Terminal, VT Sequences processing is enabled by default.
const console: File = .{
.handle = windows.peb().ProcessParameters.ConsoleHandle,
.flags = .{ .nonblocking = false },
};
var get_console_mode = windows.CONSOLE.USER_IO.GET_MODE;
switch ((try deviceIoControl(&.{
.file = console,
.code = windows.IOCTL.CONDRV.ISSUE_USER_IO,
.in = @ptrCast(&get_console_mode.request(file, 0, .{}, 0, .{})),
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.INVALID_HANDLE => return if (!try isCygwinPty(file)) error.NotTerminalDevice,
else => return error.NotTerminalDevice,
}
if (get_console_mode.Data & windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0) return;
// For Windows Console, VT Sequences processing support was added in Windows 10 build 14361, but disabled by default.
// https://devblogs.microsoft.com/commandline/tmux-support-arrives-for-bash-on-ubuntu-on-windows/
//
// Note: In Microsoft's example for enabling virtual terminal processing, it
// shows attempting to enable `DISABLE_NEWLINE_AUTO_RETURN` as well:
// https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#example-of-enabling-virtual-terminal-processing
// This is avoided because in the old Windows Console, that flag causes \n (as opposed to \r\n)
// to behave unexpectedly (the cursor moves down 1 row but remains on the same column).
// Additionally, the default console mode in Windows Terminal does not have
// `DISABLE_NEWLINE_AUTO_RETURN` set, so by only enabling `ENABLE_VIRTUAL_TERMINAL_PROCESSING`
// we end up matching the mode of Windows Terminal.
var set_console_mode = windows.CONSOLE.USER_IO.SET_MODE(
get_console_mode.Data | windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING,
);
switch ((try deviceIoControl(&.{
.file = console,
.code = windows.IOCTL.CONDRV.ISSUE_USER_IO,
.in = @ptrCast(&set_console_mode.request(file, 0, .{}, 0, .{})),
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
else => |status| return windows.unexpectedStatus(status),
}
}
fn fileSupportsAnsiEscapeCodes(userdata: ?*anyopaque, file: File) Io.Cancelable!bool {
const t: *Threaded = @ptrCast(@alignCast(userdata));
return supportsAnsiEscapeCodes(t, file);
}
fn supportsAnsiEscapeCodes(t: *Threaded, file: File) Io.Cancelable!bool {
if (is_windows) {
var get_console_mode = windows.CONSOLE.USER_IO.GET_MODE;
return switch ((try deviceIoControl(&.{
.file = .{
.handle = windows.peb().ProcessParameters.ConsoleHandle,
.flags = .{ .nonblocking = false },
},
.code = windows.IOCTL.CONDRV.ISSUE_USER_IO,
.in = @ptrCast(&get_console_mode.request(file, 0, .{}, 0, .{})),
})).u.Status) {
.SUCCESS => get_console_mode.Data & windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0,
.CANCELLED => unreachable,
.INVALID_HANDLE => isCygwinPty(file),
else => false,
};
}
if (native_os == .wasi) {
// WASI sanitizes stdout when fd is a tty so ANSI escape codes
// will not be interpreted as actual cursor commands, and
// stderr is always sanitized.
return false;
}
if (try isTty(file)) {
if (file.handle == posix.STDOUT_FILENO or file.handle == posix.STDERR_FILENO) {
t.scanEnviron();
if (t.environ.string.TERM) |term| {
if (std.mem.eql(u8, term, "dumb")) {
return false;
}
}
}
return true;
}
return false;
}
fn isCygwinPty(file: File) Io.Cancelable!bool {
if (!is_windows) return false;
const handle = file.handle;
// If this is a MSYS2/cygwin pty, then it will be a named pipe with a name in one of these formats:
// msys-[...]-ptyN-[...]
// cygwin-[...]-ptyN-[...]
//
// Example: msys-1888ae32e00d56aa-pty0-to-master
// First, just check that the handle is a named pipe.
// This allows us to avoid the more costly NtQueryInformationFile call
// for handles that aren't named pipes.
{
var io_status: windows.IO_STATUS_BLOCK = undefined;
var device_info: windows.FILE.FS_DEVICE_INFORMATION = undefined;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtQueryVolumeInformationFile(
handle,
&io_status,
&device_info,
@sizeOf(windows.FILE.FS_DEVICE_INFORMATION),
.Device,
)) {
.SUCCESS => break syscall.finish(),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => {
syscall.finish();
return false;
},
};
if (device_info.DeviceType.FileDevice != .NAMED_PIPE) return false;
}
const name_bytes_offset = @offsetOf(windows.FILE.NAME_INFORMATION, "FileName");
// `NAME_MAX` UTF-16 code units (2 bytes each)
// This buffer may not be long enough to handle *all* possible paths
// (PATH_MAX_WIDE would be necessary for that), but because we only care
// about certain paths and we know they must be within a reasonable length,
// we can use this smaller buffer and just return false on any error from
// NtQueryInformationFile.
const num_name_bytes = windows.MAX_PATH * 2;
var name_info_bytes: [name_bytes_offset + num_name_bytes]u8 align(@alignOf(windows.FILE.NAME_INFORMATION)) = @splat(0);
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtQueryInformationFile(
handle,
&io_status_block,
&name_info_bytes,
@intCast(name_info_bytes.len),
.Name,
)) {
.SUCCESS => break syscall.finish(),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.INVALID_PARAMETER => unreachable,
else => {
syscall.finish();
return false;
},
};
const name_info: *const windows.FILE.NAME_INFORMATION = @ptrCast(&name_info_bytes);
const name_bytes = name_info_bytes[name_bytes_offset .. name_bytes_offset + name_info.FileNameLength];
const name_wide = std.mem.bytesAsSlice(u16, name_bytes);
// The name we get from NtQueryInformationFile will be prefixed with a '\', e.g. \msys-1888ae32e00d56aa-pty0-to-master
return (std.mem.startsWith(u16, name_wide, &[_]u16{ '\\', 'm', 's', 'y', 's', '-' }) or
std.mem.startsWith(u16, name_wide, &[_]u16{ '\\', 'c', 'y', 'g', 'w', 'i', 'n', '-' })) and
std.mem.find(u16, name_wide, &[_]u16{ '-', 'p', 't', 'y' }) != null;
}
fn fileSetLength(userdata: ?*anyopaque, file: File, length: u64) File.SetLengthError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const signed_len: i64 = @bitCast(length);
if (signed_len < 0) return error.FileTooBig; // Avoid ambiguous EINVAL errors.
if (is_windows) {
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var eof_info: windows.FILE.END_OF_FILE_INFORMATION = .{
.EndOfFile = signed_len,
};
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtSetInformationFile(
file.handle,
&io_status_block,
&eof_info,
@sizeOf(windows.FILE.END_OF_FILE_INFORMATION),
.EndOfFile,
)) {
.SUCCESS => return syscall.finish(),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.INVALID_HANDLE => |err| return syscall.ntstatusBug(err), // Handle not open for writing.
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.USER_MAPPED_FILE => return syscall.fail(error.AccessDenied),
.INVALID_PARAMETER => return syscall.fail(error.FileTooBig),
else => |status| return syscall.unexpectedNtstatus(status),
};
}
if (native_os == .wasi and !builtin.link_libc) {
const syscall: Syscall = try .start();
while (true) {
switch (std.os.wasi.fd_filestat_set_size(file.handle, length)) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.PERM => return error.PermissionDenied,
.TXTBSY => return error.FileBusy,
.BADF => |err| return errnoBug(err), // Handle not open for writing
.INVAL => return error.NonResizable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(ftruncate_sym(file.handle, signed_len))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.PERM => return error.PermissionDenied,
.TXTBSY => return error.FileBusy,
.BADF => |err| return errnoBug(err), // Handle not open for writing.
.INVAL => return error.NonResizable, // This is returned for /dev/null for example.
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn fileSetOwner(userdata: ?*anyopaque, file: File, owner: ?File.Uid, group: ?File.Gid) File.SetOwnerError!void {
if (!have_fchown) return error.Unexpected; // Unsupported OS, don't call this function.
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const uid = owner orelse ~@as(posix.uid_t, 0);
const gid = group orelse ~@as(posix.gid_t, 0);
return posixFchown(file.handle, uid, gid);
}
fn fileSetPermissions(userdata: ?*anyopaque, file: File, permissions: File.Permissions) File.SetPermissionsError!void {
if (@sizeOf(File.Permissions) == 0) return;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
switch (native_os) {
.windows => {
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var info: windows.FILE.BASIC_INFORMATION = .{
.CreationTime = 0,
.LastAccessTime = 0,
.LastWriteTime = 0,
.ChangeTime = 0,
.FileAttributes = permissions.toAttributes(),
};
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtSetInformationFile(
file.handle,
&io_status_block,
&info,
@sizeOf(windows.FILE.BASIC_INFORMATION),
.Basic,
)) {
.SUCCESS => return syscall.finish(),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.INVALID_HANDLE => |err| return syscall.ntstatusBug(err),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
else => |status| return syscall.unexpectedNtstatus(status),
};
},
.wasi => return error.Unexpected, // Unsupported OS.
else => return setPermissionsPosix(file.handle, permissions.toMode()),
}
}
fn setPermissionsPosix(fd: posix.fd_t, mode: posix.mode_t) File.SetPermissionsError!void {
comptime assert(have_fchmod);
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.fchmod(fd, mode))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.FileNotFound,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirSetTimestamps(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.SetTimestampsOptions,
) Dir.SetTimestampsError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) {
@panic("TODO implement dirSetTimestamps windows");
}
if (native_os == .wasi and !builtin.link_libc) {
@panic("TODO implement dirSetTimestamps wasi");
}
var times_buffer: [2]posix.timespec = undefined;
const times = if (options.modify_timestamp == .now and options.access_timestamp == .now) null else p: {
times_buffer = .{
setTimestampToPosix(options.access_timestamp),
setTimestampToPosix(options.modify_timestamp),
};
break :p ×_buffer;
};
const flags: u32 = if (!options.follow_symlinks) posix.AT.SYMLINK_NOFOLLOW else 0;
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const sub_path_posix = try pathToPosix(sub_path, &path_buffer);
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.utimensat(dir.handle, sub_path_posix, times, flags))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
.BADF => |err| return syscall.errnoBug(err), // always a race condition
.FAULT => |err| return syscall.errnoBug(err),
.INVAL => |err| return syscall.errnoBug(err),
.ACCES => return syscall.fail(error.AccessDenied),
.PERM => return syscall.fail(error.PermissionDenied),
.ROFS => return syscall.fail(error.ReadOnlyFileSystem),
else => |err| return syscall.unexpectedErrno(err),
};
}
fn fileSetTimestamps(
userdata: ?*anyopaque,
file: File,
options: File.SetTimestampsOptions,
) File.SetTimestampsError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) {
const now_sys = if (options.access_timestamp == .now or options.modify_timestamp == .now)
windows.ntdll.RtlGetSystemTimePrecise()
else
undefined;
var iosb: windows.IO_STATUS_BLOCK = undefined;
var info: windows.FILE.BASIC_INFORMATION = .{
.CreationTime = 0,
.LastAccessTime = switch (options.access_timestamp) {
.unchanged => 0,
.now => now_sys,
.new => |ts| windows.toSysTime(ts),
},
.LastWriteTime = switch (options.modify_timestamp) {
.unchanged => 0,
.now => now_sys,
.new => |ts| windows.toSysTime(ts),
},
.ChangeTime = 0,
.FileAttributes = .{},
};
var syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtSetInformationFile(
file.handle,
&iosb,
&info,
@sizeOf(windows.FILE.BASIC_INFORMATION),
.Basic,
)) {
.SUCCESS => return syscall.finish(),
.CANCELLED => try syscall.checkCancel(),
else => |status| return syscall.unexpectedNtstatus(status),
};
}
if (native_os == .wasi and !builtin.link_libc) {
var atime: std.os.wasi.timestamp_t = 0;
var mtime: std.os.wasi.timestamp_t = 0;
var flags: std.os.wasi.fstflags_t = .{};
switch (options.access_timestamp) {
.unchanged => {},
.now => flags.ATIM_NOW = true,
.new => |ts| {
atime = timestampToPosix(ts.nanoseconds).toTimestamp();
flags.ATIM = true;
},
}
switch (options.modify_timestamp) {
.unchanged => {},
.now => flags.MTIM_NOW = true,
.new => |ts| {
mtime = timestampToPosix(ts.nanoseconds).toTimestamp();
flags.MTIM = true;
},
}
const syscall: Syscall = try .start();
while (true) switch (std.os.wasi.fd_filestat_set_times(file.handle, atime, mtime, flags)) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
.BADF => |err| return syscall.errnoBug(err), // File descriptor use-after-free.
.FAULT => |err| return syscall.errnoBug(err),
.INVAL => |err| return syscall.errnoBug(err),
.ACCES => return syscall.fail(error.AccessDenied),
.PERM => return syscall.fail(error.PermissionDenied),
.ROFS => return syscall.fail(error.ReadOnlyFileSystem),
else => |err| return syscall.unexpectedErrno(err),
};
}
var times_buffer: [2]posix.timespec = undefined;
const times = if (options.modify_timestamp == .now and options.access_timestamp == .now) null else p: {
times_buffer = .{
setTimestampToPosix(options.access_timestamp),
setTimestampToPosix(options.modify_timestamp),
};
break :p ×_buffer;
};
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.futimens(file.handle, times))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
.BADF => |err| return syscall.errnoBug(err), // always a race condition
.FAULT => |err| return syscall.errnoBug(err),
.INVAL => |err| return syscall.errnoBug(err),
.ACCES => return syscall.fail(error.AccessDenied),
.PERM => return syscall.fail(error.PermissionDenied),
.ROFS => return syscall.fail(error.ReadOnlyFileSystem),
else => |err| return syscall.unexpectedErrno(err),
};
}
const windows_lock_range_off: windows.LARGE_INTEGER = 0;
const windows_lock_range_len: windows.LARGE_INTEGER = 1;
fn fileLock(userdata: ?*anyopaque, file: File, lock: File.Lock) File.LockError!void {
if (native_os == .wasi) return error.FileLocksUnsupported;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) {
const exclusive = switch (lock) {
.none => {
// To match the non-Windows behavior, unlock
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
while (true) switch (windows.ntdll.NtUnlockFile(
file.handle,
&io_status_block,
&windows_lock_range_off,
&windows_lock_range_len,
0,
)) {
.SUCCESS => return,
.CANCELLED => continue,
.RANGE_NOT_LOCKED => return,
.ACCESS_VIOLATION => |err| return windows.statusBug(err), // bad io_status_block pointer
else => |status| return windows.unexpectedStatus(status),
};
},
.shared => false,
.exclusive => true,
};
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtLockFile(
file.handle,
null,
null,
null,
&io_status_block,
&windows_lock_range_off,
&windows_lock_range_len,
null,
.FALSE,
.fromBool(exclusive),
)) {
.SUCCESS => return syscall.finish(),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.INSUFFICIENT_RESOURCES => return syscall.fail(error.SystemResources),
.LOCK_NOT_GRANTED => |err| return syscall.ntstatusBug(err), // passed FailImmediately=false
.ACCESS_VIOLATION => |err| return syscall.ntstatusBug(err), // bad io_status_block pointer
else => |status| return syscall.unexpectedNtstatus(status),
};
}
const operation: i32 = switch (lock) {
.none => posix.LOCK.UN,
.shared => posix.LOCK.SH,
.exclusive => posix.LOCK.EX,
};
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.flock(file.handle, operation))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err), // invalid parameters
.NOLCK => return error.SystemResources,
.AGAIN => |err| return errnoBug(err),
.OPNOTSUPP => return error.FileLocksUnsupported,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn fileTryLock(userdata: ?*anyopaque, file: File, lock: File.Lock) File.LockError!bool {
if (native_os == .wasi) return error.FileLocksUnsupported;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) {
const exclusive = switch (lock) {
.none => {
// To match the non-Windows behavior, unlock
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
while (true) switch (windows.ntdll.NtUnlockFile(
file.handle,
&io_status_block,
&windows_lock_range_off,
&windows_lock_range_len,
0,
)) {
.SUCCESS => return true,
.CANCELLED => continue,
.RANGE_NOT_LOCKED => return false,
.ACCESS_VIOLATION => |err| return windows.statusBug(err), // bad io_status_block pointer
else => |status| return windows.unexpectedStatus(status),
};
},
.shared => false,
.exclusive => true,
};
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtLockFile(
file.handle,
null,
null,
null,
&io_status_block,
&windows_lock_range_off,
&windows_lock_range_len,
null,
.TRUE,
.fromBool(exclusive),
)) {
.SUCCESS => {
syscall.finish();
return true;
},
.LOCK_NOT_GRANTED => {
syscall.finish();
return false;
},
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.INSUFFICIENT_RESOURCES => return syscall.fail(error.SystemResources),
.ACCESS_VIOLATION => |err| return syscall.ntstatusBug(err), // bad io_status_block pointer
else => |status| return syscall.unexpectedNtstatus(status),
};
}
const operation: i32 = switch (lock) {
.none => posix.LOCK.UN,
.shared => posix.LOCK.SH | posix.LOCK.NB,
.exclusive => posix.LOCK.EX | posix.LOCK.NB,
};
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.flock(file.handle, operation))) {
.SUCCESS => {
syscall.finish();
return true;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.AGAIN => {
syscall.finish();
return false;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err), // invalid parameters
.NOLCK => return error.SystemResources,
.OPNOTSUPP => return error.FileLocksUnsupported,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn fileUnlock(userdata: ?*anyopaque, file: File) void {
if (native_os == .wasi) return;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) {
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
while (true) switch (windows.ntdll.NtUnlockFile(
file.handle,
&io_status_block,
&windows_lock_range_off,
&windows_lock_range_len,
0,
)) {
.SUCCESS => return,
.CANCELLED => continue,
.RANGE_NOT_LOCKED => if (is_debug) unreachable else return, // Function asserts unlocked.
.ACCESS_VIOLATION => if (is_debug) unreachable else return, // bad io_status_block pointer
else => if (is_debug) unreachable else return, // Resource deallocation must succeed.
};
}
while (true) {
switch (posix.errno(posix.system.flock(file.handle, posix.LOCK.UN))) {
.SUCCESS => return,
.CANCELED, .INTR => continue,
.AGAIN => return assert(!is_debug), // unlocking can't block
.BADF => return assert(!is_debug), // File descriptor used after closed.
.INVAL => return assert(!is_debug), // invalid parameters
.NOLCK => return assert(!is_debug), // Resource deallocation.
.OPNOTSUPP => return assert(!is_debug), // We already got the lock.
else => return assert(!is_debug), // Resource deallocation must succeed.
}
}
}
fn fileDowngradeLock(userdata: ?*anyopaque, file: File) File.DowngradeLockError!void {
if (native_os == .wasi) return;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) {
// On Windows it works like a semaphore + exclusivity flag. To
// implement this function, we first obtain another lock in shared
// mode. This changes the exclusivity flag, but increments the
// semaphore to 2. So we follow up with an NtUnlockFile which
// decrements the semaphore but does not modify the exclusivity flag.
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtLockFile(
file.handle,
null,
null,
null,
&io_status_block,
&windows_lock_range_off,
&windows_lock_range_len,
null,
.TRUE,
.FALSE,
)) {
.SUCCESS => break syscall.finish(),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.INSUFFICIENT_RESOURCES => |err| return syscall.ntstatusBug(err),
.LOCK_NOT_GRANTED => |err| return syscall.ntstatusBug(err), // File was not locked in exclusive mode.
.ACCESS_VIOLATION => |err| return syscall.ntstatusBug(err), // bad io_status_block pointer
else => |status| return syscall.unexpectedNtstatus(status),
};
while (true) switch (windows.ntdll.NtUnlockFile(
file.handle,
&io_status_block,
&windows_lock_range_off,
&windows_lock_range_len,
0,
)) {
.SUCCESS => return,
.CANCELLED => continue,
.RANGE_NOT_LOCKED => if (is_debug) unreachable else return, // File was not locked.
.ACCESS_VIOLATION => if (is_debug) unreachable else return, // bad io_status_block pointer
else => if (is_debug) unreachable else return, // Resource deallocation must succeed.
};
}
const operation = posix.LOCK.SH | posix.LOCK.NB;
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.flock(file.handle, operation))) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.AGAIN => |err| return errnoBug(err), // File was not locked in exclusive mode.
.BADF => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err), // invalid parameters
.NOLCK => |err| return errnoBug(err), // Lock already obtained.
.OPNOTSUPP => |err| return errnoBug(err), // Lock already obtained.
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirOpenDirWasi(
userdata: ?*anyopaque,
dir: Dir,
sub_path: []const u8,
options: Dir.OpenOptions,
) Dir.OpenError!Dir {
if (builtin.link_libc) return dirOpenDirPosix(userdata, dir, sub_path, options);
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const wasi = std.os.wasi;
var base: std.os.wasi.rights_t = .{
.FD_FILESTAT_GET = true,
.FD_FDSTAT_SET_FLAGS = true,
.FD_FILESTAT_SET_TIMES = true,
};
if (options.access_sub_paths) {
base.FD_READDIR = true;
base.PATH_CREATE_DIRECTORY = true;
base.PATH_CREATE_FILE = true;
base.PATH_LINK_SOURCE = true;
base.PATH_LINK_TARGET = true;
base.PATH_OPEN = true;
base.PATH_READLINK = true;
base.PATH_RENAME_SOURCE = true;
base.PATH_RENAME_TARGET = true;
base.PATH_FILESTAT_GET = true;
base.PATH_FILESTAT_SET_SIZE = true;
base.PATH_FILESTAT_SET_TIMES = true;
base.PATH_SYMLINK = true;
base.PATH_REMOVE_DIRECTORY = true;
base.PATH_UNLINK_FILE = true;
}
const lookup_flags: wasi.lookupflags_t = .{ .SYMLINK_FOLLOW = options.follow_symlinks };
const oflags: wasi.oflags_t = .{ .DIRECTORY = true };
const fdflags: wasi.fdflags_t = .{};
var fd: posix.fd_t = undefined;
const syscall: Syscall = try .start();
while (true) {
switch (wasi.path_open(dir.handle, lookup_flags, sub_path.ptr, sub_path.len, oflags, base, base, fdflags, &fd)) {
.SUCCESS => {
syscall.finish();
return .{ .handle = fd };
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.FAULT => |err| return errnoBug(err),
.INVAL => return error.BadPathName,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.ACCES => return error.AccessDenied,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.NOTCAPABLE => return error.AccessDenied,
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn dirHardLink(
userdata: ?*anyopaque,
old_dir: Dir,
old_sub_path: []const u8,
new_dir: Dir,
new_sub_path: []const u8,
options: Dir.HardLinkOptions,
) Dir.HardLinkError!void {
if (is_windows) return error.OperationUnsupported;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (native_os == .wasi and !builtin.link_libc) {
const flags: std.os.wasi.lookupflags_t = .{
.SYMLINK_FOLLOW = options.follow_symlinks,
};
const syscall: Syscall = try .start();
while (true) {
switch (std.os.wasi.path_link(
old_dir.handle,
flags,
old_sub_path.ptr,
old_sub_path.len,
new_dir.handle,
new_sub_path.ptr,
new_sub_path.len,
)) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.FAULT => |err| return errnoBug(err),
.IO => return error.HardwareFailure,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
.XDEV => return error.CrossDevice,
.INVAL => |err| return errnoBug(err),
.ILSEQ => return error.BadPathName,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
var old_path_buffer: [posix.PATH_MAX]u8 = undefined;
var new_path_buffer: [posix.PATH_MAX]u8 = undefined;
const old_sub_path_posix = try pathToPosix(old_sub_path, &old_path_buffer);
const new_sub_path_posix = try pathToPosix(new_sub_path, &new_path_buffer);
const flags: u32 = if (options.follow_symlinks) posix.AT.SYMLINK_FOLLOW else 0;
return linkat(old_dir.handle, old_sub_path_posix, new_dir.handle, new_sub_path_posix, flags);
}
fn fileClose(userdata: ?*anyopaque, files: []const File) void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
for (files) |file| {
if (is_windows) {
windows.CloseHandle(file.handle);
} else {
closeFd(file.handle);
}
}
}
fn fileReadStreaming(userdata: ?*anyopaque, file: File, data: []const []u8) File.ReadStreamingError!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) return fileReadStreamingWindows(file, data);
return fileReadStreamingPosix(file, data);
}
fn fileReadStreamingPosix(file: File, data: []const []u8) File.ReadStreamingError!usize {
var iovecs_buffer: [max_iovecs_len]posix.iovec = undefined;
var i: usize = 0;
for (data) |buf| {
if (iovecs_buffer.len - i == 0) break;
if (buf.len != 0) {
iovecs_buffer[i] = .{ .base = buf.ptr, .len = buf.len };
i += 1;
}
}
if (i == 0) return 0;
const dest = iovecs_buffer[0..i];
assert(dest[0].len > 0);
if (native_os == .wasi and !builtin.link_libc) {
const syscall: Syscall = try .start();
while (true) {
var nread: usize = undefined;
switch (std.os.wasi.fd_read(file.handle, dest.ptr, dest.len, &nread)) {
.SUCCESS => {
syscall.finish();
if (nread == 0) return error.EndOfStream;
return nread;
},
.INTR, .TIMEDOUT => {
try syscall.checkCancel();
continue;
},
.BADF => return syscall.fail(error.IsDir), // File operation on directory.
.IO => return syscall.fail(error.InputOutput),
.ISDIR => return syscall.fail(error.IsDir),
.NOBUFS => return syscall.fail(error.SystemResources),
.NOMEM => return syscall.fail(error.SystemResources),
.NOTCONN => return syscall.fail(error.SocketUnconnected),
.CONNRESET => return syscall.fail(error.ConnectionResetByPeer),
.NOTCAPABLE => return syscall.fail(error.AccessDenied),
.INVAL => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.readv(file.handle, dest.ptr, @intCast(dest.len));
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
if (rc == 0) return error.EndOfStream;
return @intCast(rc);
},
.INTR, .TIMEDOUT => {
try syscall.checkCancel();
continue;
},
.BADF => {
syscall.finish();
if (native_os == .wasi) return error.IsDir; // File operation on directory.
return error.NotOpenForReading;
},
.AGAIN => return syscall.fail(error.WouldBlock),
.IO => return syscall.fail(error.InputOutput),
.ISDIR => return syscall.fail(error.IsDir),
.NOBUFS => return syscall.fail(error.SystemResources),
.NOMEM => return syscall.fail(error.SystemResources),
.NOTCONN => return syscall.fail(error.SocketUnconnected),
.CONNRESET => return syscall.fail(error.ConnectionResetByPeer),
.INVAL => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
fn fileReadStreamingWindows(file: File, data: []const []u8) File.ReadStreamingError!usize {
var iosb: windows.IO_STATUS_BLOCK = undefined;
var index: usize = 0;
while (data.len - index != 0 and data[index].len == 0) index += 1;
if (data.len - index == 0) return 0;
const buffer = data[index];
const short_buffer_len = std.math.lossyCast(u32, buffer.len);
if (file.flags.nonblocking) {
var done: bool = false;
switch (windows.ntdll.NtReadFile(
file.handle,
null, // event
flagApc,
&done, // APC context
&iosb,
buffer.ptr,
short_buffer_len,
null, // byte offset
null, // key
)) {
// We must wait for the APC routine.
.PENDING, .SUCCESS => while (!done) {
// Once we get here we must not return from the function until the
// operation completes, thereby releasing reference to the iosb.
const alertable_syscall = AlertableSyscall.start() catch |err| switch (err) {
error.Canceled => |e| {
var cancel_iosb: windows.IO_STATUS_BLOCK = undefined;
_ = windows.ntdll.NtCancelIoFileEx(file.handle, &iosb, &cancel_iosb);
while (!done) waitForApcOrAlert();
return e;
},
};
waitForApcOrAlert();
alertable_syscall.finish();
},
else => |status| iosb.u.Status = status,
}
} else {
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtReadFile(
file.handle,
null, // event
null, // APC routine
null, // APC context
&iosb,
buffer.ptr,
short_buffer_len,
null, // byte offset
null, // key
)) {
.PENDING => unreachable, // unrecoverable: wrong File nonblocking flag
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => |status| {
syscall.finish();
iosb.u.Status = status;
break;
},
};
}
return ntReadFileResult(&iosb);
}
fn flagApc(userdata: ?*anyopaque, _: *windows.IO_STATUS_BLOCK, _: windows.ULONG) align(apc_align) callconv(.winapi) void {
const flag: *bool = @ptrCast(userdata);
flag.* = true;
}
fn ntReadFileResult(io_status_block: *const windows.IO_STATUS_BLOCK) !usize {
switch (io_status_block.u.Status) {
.PENDING => unreachable,
.CANCELLED => unreachable,
.SUCCESS => return io_status_block.Information,
.END_OF_FILE, .PIPE_BROKEN => return error.EndOfStream,
.INVALID_HANDLE => return error.NotOpenForReading,
.INVALID_DEVICE_REQUEST => return error.IsDir,
.FILE_LOCK_CONFLICT => return error.LockViolation,
.ACCESS_DENIED => return error.AccessDenied,
else => |status| return windows.unexpectedStatus(status),
}
}
fn ntWriteFileResult(io_status_block: *const windows.IO_STATUS_BLOCK) !usize {
switch (io_status_block.u.Status) {
.PENDING => unreachable,
.CANCELLED => unreachable,
.SUCCESS => return io_status_block.Information,
.INVALID_USER_BUFFER => return error.SystemResources,
.NO_MEMORY => return error.SystemResources,
.QUOTA_EXCEEDED => return error.SystemResources,
.PIPE_BROKEN => return error.BrokenPipe,
.INVALID_HANDLE => return error.NotOpenForWriting,
.FILE_LOCK_CONFLICT => return error.LockViolation,
.ACCESS_DENIED => return error.AccessDenied,
.WORKING_SET_QUOTA => return error.SystemResources,
.DISK_FULL => return error.NoSpaceLeft,
else => |status| return windows.unexpectedStatus(status),
}
}
fn fileReadPositionalPosix(file: File, data: []const []u8, offset: u64) File.ReadPositionalError!usize {
var iovecs_buffer: [max_iovecs_len]posix.iovec = undefined;
var i: usize = 0;
for (data) |buf| {
if (iovecs_buffer.len - i == 0) break;
if (buf.len != 0) {
iovecs_buffer[i] = .{ .base = buf.ptr, .len = buf.len };
i += 1;
}
}
if (i == 0) return 0;
const dest = iovecs_buffer[0..i];
assert(dest[0].len > 0);
if (native_os == .wasi and !builtin.link_libc) {
const syscall: Syscall = try .start();
while (true) {
var nread: usize = undefined;
switch (std.os.wasi.fd_pread(file.handle, dest.ptr, dest.len, offset, &nread)) {
.SUCCESS => {
syscall.finish();
return nread;
},
.INTR, .TIMEDOUT => {
try syscall.checkCancel();
continue;
},
.NOTCONN => |err| return syscall.errnoBug(err), // not a socket
.CONNRESET => |err| return syscall.errnoBug(err), // not a socket
.INVAL => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err), // segmentation fault
.AGAIN => |err| return syscall.errnoBug(err),
.IO => return syscall.fail(error.InputOutput),
.ISDIR => return syscall.fail(error.IsDir),
.BADF => return syscall.fail(error.IsDir),
.NOBUFS => return syscall.fail(error.SystemResources),
.NOMEM => return syscall.fail(error.SystemResources),
.NXIO => return syscall.fail(error.Unseekable),
.SPIPE => return syscall.fail(error.Unseekable),
.OVERFLOW => return syscall.fail(error.Unseekable),
.NOTCAPABLE => return syscall.fail(error.AccessDenied),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
if (have_preadv) {
const syscall: Syscall = try .start();
while (true) {
const rc = if (native_os == .haiku)
posix.system.readv_pos(file.handle, @bitCast(offset), dest.ptr, @intCast(dest.len))
else
preadv_sym(file.handle, dest.ptr, @intCast(dest.len), @bitCast(offset));
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
return @bitCast(rc);
},
.INTR, .TIMEDOUT => {
try syscall.checkCancel();
continue;
},
.NXIO => return syscall.fail(error.Unseekable),
.SPIPE => return syscall.fail(error.Unseekable),
.OVERFLOW => return syscall.fail(error.Unseekable),
.NOBUFS => return syscall.fail(error.SystemResources),
.NOMEM => return syscall.fail(error.SystemResources),
.AGAIN => return syscall.fail(error.WouldBlock),
.IO => return syscall.fail(error.InputOutput),
.ISDIR => return syscall.fail(error.IsDir),
.NOTCONN => |err| return syscall.errnoBug(err), // not a socket
.CONNRESET => |err| return syscall.errnoBug(err), // not a socket
.INVAL => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err),
.BADF => {
syscall.finish();
if (native_os == .wasi) return error.IsDir; // File operation on directory.
return error.NotOpenForReading;
},
else => |err| return syscall.unexpectedErrno(err),
}
}
}
const syscall: Syscall = try .start();
while (true) {
const rc = pread_sym(file.handle, dest[0].base, @intCast(dest[0].len), @bitCast(offset));
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
return @bitCast(rc);
},
.INTR, .TIMEDOUT => {
try syscall.checkCancel();
continue;
},
.NXIO => return syscall.fail(error.Unseekable),
.SPIPE => return syscall.fail(error.Unseekable),
.OVERFLOW => return syscall.fail(error.Unseekable),
.NOBUFS => return syscall.fail(error.SystemResources),
.NOMEM => return syscall.fail(error.SystemResources),
.AGAIN => return syscall.fail(error.WouldBlock),
.IO => return syscall.fail(error.InputOutput),
.ISDIR => return syscall.fail(error.IsDir),
.NOTCONN => |err| return syscall.errnoBug(err), // not a socket
.CONNRESET => |err| return syscall.errnoBug(err), // not a socket
.INVAL => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err),
.BADF => {
syscall.finish();
if (native_os == .wasi) return error.IsDir; // File operation on directory.
return error.NotOpenForReading;
},
else => |err| return syscall.unexpectedErrno(err),
}
}
}
fn fileReadPositional(userdata: ?*anyopaque, file: File, data: []const []u8, offset: u64) File.ReadPositionalError!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) return fileReadPositionalWindows(file, data, offset);
return fileReadPositionalPosix(file, data, offset);
}
fn fileReadPositionalWindows(file: File, data: []const []u8, offset: u64) File.ReadPositionalError!usize {
var index: usize = 0;
while (index < data.len and data[index].len == 0) index += 1;
if (index == data.len) return 0;
const buffer = data[index];
return readFilePositionalWindows(file, buffer, offset);
}
fn readFilePositionalWindows(file: File, buffer: []u8, offset: u64) File.ReadPositionalError!usize {
var iosb: windows.IO_STATUS_BLOCK = undefined;
const short_buffer_len = std.math.lossyCast(u32, buffer.len);
const signed_offset: windows.LARGE_INTEGER = @intCast(offset);
if (file.flags.nonblocking) {
var done: bool = false;
switch (windows.ntdll.NtReadFile(
file.handle,
null, // event
flagApc,
&done, // APC context
&iosb,
buffer.ptr,
short_buffer_len,
&signed_offset,
null, // key
)) {
// We must wait for the APC routine.
.PENDING, .SUCCESS => while (!done) {
// Once we get here we must not return from the function until the
// operation completes, thereby releasing reference to the iosb.
const alertable_syscall = AlertableSyscall.start() catch |err| switch (err) {
error.Canceled => |e| {
var cancel_iosb: windows.IO_STATUS_BLOCK = undefined;
_ = windows.ntdll.NtCancelIoFileEx(file.handle, &iosb, &cancel_iosb);
while (!done) waitForApcOrAlert();
return e;
},
};
waitForApcOrAlert();
alertable_syscall.finish();
},
else => |status| iosb.u.Status = status,
}
} else {
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtReadFile(
file.handle,
null, // event
null, // APC routine
null, // APC context
&iosb,
buffer.ptr,
short_buffer_len,
&signed_offset,
null, // key
)) {
.PENDING => unreachable, // unrecoverable: wrong File nonblocking flag
.CANCELLED => try syscall.checkCancel(),
else => |status| {
syscall.finish();
iosb.u.Status = status;
break;
},
};
}
return ntReadFileResult(&iosb) catch |err| switch (err) {
error.EndOfStream => 0,
else => |e| e,
};
}
fn fileSeekBy(userdata: ?*anyopaque, file: File, offset: i64) File.SeekError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) {
var iosb: windows.IO_STATUS_BLOCK = undefined;
var info: windows.FILE.POSITION_INFORMATION = undefined;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtQueryInformationFile(
file.handle,
&iosb,
&info,
@sizeOf(windows.FILE.POSITION_INFORMATION),
.Position,
)) {
.SUCCESS => break,
.CANCELLED => try syscall.checkCancel(),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.PIPE_NOT_AVAILABLE => return syscall.fail(error.Unseekable),
else => |status| return syscall.unexpectedNtstatus(status),
};
info.CurrentByteOffset = @bitCast((if (offset >= 0) std.math.add(
u64,
@bitCast(info.CurrentByteOffset),
@intCast(offset),
) else std.math.sub(
u64,
@bitCast(info.CurrentByteOffset),
@intCast(-offset),
)) catch |err| switch (err) {
error.Overflow => return syscall.fail(error.Unseekable),
});
while (true) switch (windows.ntdll.NtSetInformationFile(
file.handle,
&iosb,
&info,
@sizeOf(windows.FILE.POSITION_INFORMATION),
.Position,
)) {
.SUCCESS => return syscall.finish(),
.CANCELLED => try syscall.checkCancel(),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.PIPE_NOT_AVAILABLE => return syscall.fail(error.Unseekable),
else => |status| return syscall.unexpectedNtstatus(status),
};
}
if (native_os == .wasi and !builtin.link_libc) {
var new_offset: std.os.wasi.filesize_t = undefined;
const syscall: Syscall = try .start();
while (true) {
switch (std.os.wasi.fd_seek(file.handle, offset, .CUR, &new_offset)) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
if (posix.SEEK == void) return error.Unseekable;
if (native_os == .linux and !builtin.link_libc and @sizeOf(posix.system.syscall_arg_t) == 4) {
var result: i64 = undefined;
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.llseek(file.handle, offset, &result, posix.SEEK.CUR))) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(lseek_sym(file.handle, offset, posix.SEEK.CUR))) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn fileSeekTo(userdata: ?*anyopaque, file: File, offset: u64) File.SeekError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) {
var iosb: windows.IO_STATUS_BLOCK = undefined;
var info: windows.FILE.POSITION_INFORMATION = .{ .CurrentByteOffset = @bitCast(offset) };
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtSetInformationFile(
file.handle,
&iosb,
&info,
@sizeOf(windows.FILE.POSITION_INFORMATION),
.Position,
)) {
.SUCCESS => return syscall.finish(),
.CANCELLED => try syscall.checkCancel(),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.PIPE_NOT_AVAILABLE => return syscall.fail(error.Unseekable),
else => |status| return syscall.unexpectedNtstatus(status),
};
}
if (native_os == .wasi and !builtin.link_libc) {
const syscall: Syscall = try .start();
while (true) {
var new_offset: std.os.wasi.filesize_t = undefined;
switch (std.os.wasi.fd_seek(file.handle, @bitCast(offset), .SET, &new_offset)) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
if (posix.SEEK == void) return error.Unseekable;
return posixSeekTo(file.handle, offset);
}
fn posixSeekTo(fd: posix.fd_t, offset: u64) File.SeekError!void {
if (native_os == .linux and !builtin.link_libc and @sizeOf(posix.system.syscall_arg_t) == 4) {
const syscall: Syscall = try .start();
while (true) {
var result: i64 = undefined;
switch (posix.errno(posix.system.llseek(fd, @bitCast(offset), &result, posix.SEEK.SET))) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(lseek_sym(fd, @bitCast(offset), posix.SEEK.SET))) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn processExecutableOpen(userdata: ?*anyopaque, flags: Dir.OpenFileOptions) process.OpenExecutableError!File {
const t: *Threaded = @ptrCast(@alignCast(userdata));
switch (native_os) {
.wasi => return error.OperationUnsupported,
.linux, .serenity => return dirOpenFilePosix(t, .{ .handle = posix.AT.FDCWD }, "/proc/self/exe", flags),
.windows => {
// If ImagePathName is a symlink, then it will contain the path of the symlink,
// not the path that the symlink points to. However, because we are opening
// the file, we can let the openFileW call follow the symlink for us.
const image_path_name = windows.peb().ProcessParameters.ImagePathName.sliceZ();
const prefixed_path_w = try wToPrefixedFileW(null, image_path_name, .{});
return dirOpenFileWtf16(null, prefixed_path_w.span(), flags);
},
.driverkit,
.ios,
.maccatalyst,
.macos,
.tvos,
.visionos,
.watchos,
=> {
// _NSGetExecutablePath() returns a path that might be a symlink to
// the executable. Here it does not matter since we open it.
var symlink_path_buf: [posix.PATH_MAX + 1]u8 = undefined;
var n: u32 = symlink_path_buf.len;
const rc = std.c._NSGetExecutablePath(&symlink_path_buf, &n);
if (rc != 0) return error.NameTooLong;
const symlink_path = std.mem.sliceTo(&symlink_path_buf, 0);
return dirOpenFilePosix(t, .cwd(), symlink_path, flags);
},
else => {
var buffer: [Dir.max_path_bytes]u8 = undefined;
const n = try processExecutablePath(t, &buffer);
buffer[n] = 0;
const executable_path = buffer[0..n :0];
return dirOpenFilePosix(t, .cwd(), executable_path, flags);
},
}
}
fn processExecutablePath(userdata: ?*anyopaque, out_buffer: []u8) process.ExecutablePathError!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
switch (native_os) {
.driverkit,
.ios,
.maccatalyst,
.macos,
.tvos,
.visionos,
.watchos,
=> {
// _NSGetExecutablePath() returns a path that might be a symlink to
// the executable.
var symlink_path_buf: [posix.PATH_MAX + 1]u8 = undefined;
var n: u32 = symlink_path_buf.len;
const rc = std.c._NSGetExecutablePath(&symlink_path_buf, &n);
if (rc != 0) return error.NameTooLong;
const symlink_path = std.mem.sliceTo(&symlink_path_buf, 0);
return Io.Dir.realPathFileAbsolute(io(t), symlink_path, out_buffer) catch |err| switch (err) {
error.NetworkNotFound => unreachable, // Windows-only
error.FileBusy => unreachable, // Windows-only
else => |e| return e,
};
},
.linux, .serenity => return Io.Dir.readLinkAbsolute(io(t), "/proc/self/exe", out_buffer) catch |err| switch (err) {
error.UnsupportedReparsePointType => unreachable, // Windows-only
error.NetworkNotFound => unreachable, // Windows-only
error.FileBusy => unreachable, // Windows-only
else => |e| return e,
},
.illumos => return Io.Dir.readLinkAbsolute(io(t), "/proc/self/path/a.out", out_buffer) catch |err| switch (err) {
error.UnsupportedReparsePointType => unreachable, // Windows-only
error.NetworkNotFound => unreachable, // Windows-only
error.FileBusy => unreachable, // Windows-only
else => |e| return e,
},
.freebsd, .dragonfly => {
var mib: [4]c_int = .{ posix.CTL.KERN, posix.KERN.PROC, posix.KERN.PROC_PATHNAME, -1 };
var out_len: usize = out_buffer.len;
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.sysctl(&mib, mib.len, out_buffer.ptr, &out_len, null, 0))) {
.SUCCESS => {
syscall.finish();
return out_len - 1; // discard terminating NUL
},
.INTR => {
try syscall.checkCancel();
continue;
},
.PERM => return syscall.fail(error.PermissionDenied),
.NOMEM => return syscall.fail(error.SystemResources),
.FAULT => |err| return syscall.errnoBug(err),
.NOENT => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
};
},
.netbsd => {
var mib = [4]c_int{ posix.CTL.KERN, posix.KERN.PROC_ARGS, -1, posix.KERN.PROC_PATHNAME };
var out_len: usize = out_buffer.len;
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.sysctl(&mib, mib.len, out_buffer.ptr, &out_len, null, 0))) {
.SUCCESS => {
syscall.finish();
return out_len - 1; // discard terminating NUL
},
.INTR => {
try syscall.checkCancel();
continue;
},
.PERM => return syscall.fail(error.PermissionDenied),
.NOMEM => return syscall.fail(error.SystemResources),
.FAULT => |err| return syscall.errnoBug(err),
.NOENT => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
}
}
},
.openbsd, .haiku => {
// The best we can do on these operating systems is check based on
// the first process argument.
const argv0 = std.mem.span(t.argv0.value orelse return error.OperationUnsupported);
if (std.mem.findScalar(u8, argv0, '/') != null) {
// argv[0] is a path (relative or absolute): use realpath(3) directly
var resolved_buf: [std.c.PATH_MAX]u8 = undefined;
const syscall: Syscall = try .start();
while (true) {
if (std.c.realpath(argv0, &resolved_buf)) |p| {
assert(p == &resolved_buf);
break syscall.finish();
} else switch (@as(std.c.E, @fromBackingInt(@intCast(std.c._errno().*)))) {
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.INVAL => |err| return errnoBug(err), // the pathname argument is a null pointer
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => |err| return errnoBug(err), // sufficient storage space is unavailable for allocation
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
const resolved = std.mem.sliceTo(&resolved_buf, 0);
if (resolved.len > out_buffer.len)
return error.NameTooLong;
@memcpy(out_buffer[0..resolved.len], resolved);
return resolved.len;
} else if (argv0.len != 0) {
// argv[0] is not empty (and not a path): search PATH
t.scanEnviron();
const PATH = t.environ.string.PATH orelse return error.FileNotFound;
var it = std.mem.tokenizeScalar(u8, PATH, ':');
it: while (it.next()) |dir| {
var resolved_path_buf: [std.c.PATH_MAX]u8 = undefined;
const resolved_path = std.mem.printSentinel(&resolved_path_buf, "{s}/{s}", .{
dir, argv0,
}, 0) catch continue;
var resolved_buf: [std.c.PATH_MAX]u8 = undefined;
const syscall: Syscall = try .start();
while (true) {
if (std.c.realpath(resolved_path, &resolved_buf)) |p| {
assert(p == &resolved_buf);
break syscall.finish();
} else switch (@as(std.c.E, @fromBackingInt(@intCast(std.c._errno().*)))) {
.INTR => {
try syscall.checkCancel();
continue;
},
.NAMETOOLONG => {
syscall.finish();
return error.NameTooLong;
},
.NOMEM => {
syscall.finish();
return error.SystemResources;
},
.IO => {
syscall.finish();
return error.InputOutput;
},
.ACCES, .LOOP, .NOENT, .NOTDIR => {
syscall.finish();
continue :it;
},
else => |err| {
syscall.finish();
return posix.unexpectedErrno(err);
},
}
}
const resolved = std.mem.sliceTo(&resolved_buf, 0);
if (resolved.len > out_buffer.len)
return error.NameTooLong;
@memcpy(out_buffer[0..resolved.len], resolved);
return resolved.len;
}
}
return error.FileNotFound;
},
.windows => {
// If ImagePathName is a symlink, then it will contain the path of the
// symlink, not the path that the symlink points to. We want the path
// that the symlink points to, though, so we need to get the realpath.
var path_name_w_buf = try wToPrefixedFileW(
null,
windows.peb().ProcessParameters.ImagePathName.sliceZ(),
.{},
);
const h_file = handle: {
if (OpenFile(path_name_w_buf.span(), .{
.dir = null,
.access_mask = .{
.GENERIC = .{ .READ = true },
.STANDARD = .{ .SYNCHRONIZE = true },
},
.creation = .OPEN,
.filter = .any,
})) |handle| {
break :handle handle;
} else |err| switch (err) {
error.WouldBlock => unreachable,
error.FileBusy => unreachable,
else => |e| return e,
}
};
defer windows.CloseHandle(h_file);
const wide_slice = try GetFinalPathNameByHandle(h_file, .{}, &path_name_w_buf.data);
const len = std.unicode.calcWtf8Len(wide_slice);
if (len > out_buffer.len)
return error.NameTooLong;
const end_index = std.unicode.wtf16LeToWtf8(out_buffer, wide_slice);
return end_index;
},
else => return error.OperationUnsupported,
}
}
fn fileWritePositional(
userdata: ?*anyopaque,
file: File,
header: []const u8,
data: []const []const u8,
splat: usize,
offset: u64,
) File.WritePositionalError!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) {
if (header.len != 0) {
return writeFilePositionalWindows(file, header, offset);
}
for (data[0 .. data.len - 1]) |buf| {
if (buf.len == 0) continue;
return writeFilePositionalWindows(file, buf, offset);
}
const pattern = data[data.len - 1];
if (pattern.len == 0 or splat == 0) return 0;
return writeFilePositionalWindows(file, pattern, offset);
}
var iovecs: [max_iovecs_len]posix.iovec_const = undefined;
var iovlen: iovlen_t = 0;
addBuf(&iovecs, &iovlen, header);
for (data[0 .. data.len - 1]) |bytes| addBuf(&iovecs, &iovlen, bytes);
const pattern = data[data.len - 1];
var splat_backup_buffer: [splat_buffer_size]u8 = undefined;
if (iovecs.len - iovlen != 0) switch (splat) {
0 => {},
1 => addBuf(&iovecs, &iovlen, pattern),
else => switch (pattern.len) {
0 => {},
1 => {
const splat_buffer = &splat_backup_buffer;
const memset_len = @min(splat_buffer.len, splat);
const buf = splat_buffer[0..memset_len];
@memset(buf, pattern[0]);
addBuf(&iovecs, &iovlen, buf);
var remaining_splat = splat - buf.len;
while (remaining_splat > splat_buffer.len and iovecs.len - iovlen != 0) {
assert(buf.len == splat_buffer.len);
addBuf(&iovecs, &iovlen, splat_buffer);
remaining_splat -= splat_buffer.len;
}
addBuf(&iovecs, &iovlen, splat_buffer[0..@min(remaining_splat, splat_buffer.len)]);
},
else => for (0..@min(splat, iovecs.len - iovlen)) |_| {
addBuf(&iovecs, &iovlen, pattern);
},
},
};
if (iovlen == 0) return 0;
if (native_os == .wasi and !builtin.link_libc) {
var n_written: usize = undefined;
const syscall: Syscall = try .start();
while (true) {
switch (std.os.wasi.fd_pwrite(file.handle, &iovecs, iovlen, offset, &n_written)) {
.SUCCESS => {
syscall.finish();
return n_written;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.INVAL => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.AGAIN => |err| return errnoBug(err),
.BADF => return error.NotOpenForWriting,
.DESTADDRREQ => |err| return errnoBug(err), // `connect` was never called.
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.PermissionDenied,
.PIPE => return error.BrokenPipe,
.NOTCAPABLE => return error.AccessDenied,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
const syscall: Syscall = try .start();
while (true) {
const rc = if (native_os == .haiku)
posix.system.writev_pos(file.handle, @bitCast(offset), &iovecs, @intCast(iovlen))
else
pwritev_sym(file.handle, &iovecs, @intCast(iovlen), @bitCast(offset));
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
return @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
.INVAL => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err),
.DESTADDRREQ => |err| return syscall.errnoBug(err), // `connect` was never called.
.CONNRESET => |err| return syscall.errnoBug(err), // Not a socket handle.
.BADF => return syscall.fail(error.NotOpenForWriting),
.AGAIN => return syscall.fail(error.WouldBlock),
.DQUOT => return syscall.fail(error.DiskQuota),
.FBIG => return syscall.fail(error.FileTooBig),
.IO => return syscall.fail(error.InputOutput),
.NOSPC => return syscall.fail(error.NoSpaceLeft),
.PERM => return syscall.fail(error.PermissionDenied),
.PIPE => return syscall.fail(error.BrokenPipe),
.BUSY => return syscall.fail(error.DeviceBusy),
.TXTBSY => return syscall.fail(error.FileBusy),
.NXIO => return syscall.fail(error.Unseekable),
.SPIPE => return syscall.fail(error.Unseekable),
.OVERFLOW => return syscall.fail(error.Unseekable),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
fn writeFilePositionalWindows(file: File, buffer: []const u8, offset: u64) File.WritePositionalError!usize {
assert(buffer.len != 0);
var iosb: windows.IO_STATUS_BLOCK = undefined;
const short_buffer_len = std.math.lossyCast(u32, buffer.len);
const signed_offset: windows.LARGE_INTEGER = @intCast(offset);
if (file.flags.nonblocking) {
var done: bool = false;
switch (windows.ntdll.NtWriteFile(
file.handle,
null, // event
flagApc,
&done, // APC context
&iosb,
buffer.ptr,
short_buffer_len,
&signed_offset,
null, // key
)) {
// We must wait for the APC routine.
.PENDING, .SUCCESS => while (!done) {
// Once we get here we must not return from the function until the
// operation completes, thereby releasing reference to the iosb.
const alertable_syscall = AlertableSyscall.start() catch |err| switch (err) {
error.Canceled => |e| {
var cancel_iosb: windows.IO_STATUS_BLOCK = undefined;
_ = windows.ntdll.NtCancelIoFileEx(file.handle, &iosb, &cancel_iosb);
while (!done) waitForApcOrAlert();
return e;
},
};
waitForApcOrAlert();
alertable_syscall.finish();
},
else => |status| iosb.u.Status = status,
}
} else {
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtWriteFile(
file.handle,
null, // event
null, // APC routine
null, // APC context
&iosb,
buffer.ptr,
short_buffer_len,
&signed_offset,
null, // key
)) {
.PENDING => unreachable, // unrecoverable: wrong File nonblocking flag
.CANCELLED => try syscall.checkCancel(),
else => |status| {
syscall.finish();
iosb.u.Status = status;
return ntWriteFileResult(&iosb);
},
};
}
return ntWriteFileResult(&iosb);
}
fn fileWriteStreaming(
userdata: ?*anyopaque,
file: File,
header: []const u8,
data: []const []const u8,
splat: usize,
) File.Writer.Error!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) {
const buffer = windowsWriteBuffer(header, data, splat);
if (buffer.len == 0) return 0;
return fileWriteStreamingWindows(file, buffer);
}
var iovecs: [max_iovecs_len]posix.iovec_const = undefined;
var iovlen: iovlen_t = 0;
addBuf(&iovecs, &iovlen, header);
for (data[0 .. data.len - 1]) |bytes| addBuf(&iovecs, &iovlen, bytes);
const pattern = data[data.len - 1];
var splat_backup_buffer: [splat_buffer_size]u8 = undefined;
if (iovecs.len - iovlen != 0) switch (splat) {
0 => {},
1 => addBuf(&iovecs, &iovlen, pattern),
else => switch (pattern.len) {
0 => {},
1 => {
const splat_buffer = &splat_backup_buffer;
const memset_len = @min(splat_buffer.len, splat);
const buf = splat_buffer[0..memset_len];
@memset(buf, pattern[0]);
addBuf(&iovecs, &iovlen, buf);
var remaining_splat = splat - buf.len;
while (remaining_splat > splat_buffer.len and iovecs.len - iovlen != 0) {
assert(buf.len == splat_buffer.len);
addBuf(&iovecs, &iovlen, splat_buffer);
remaining_splat -= splat_buffer.len;
}
addBuf(&iovecs, &iovlen, splat_buffer[0..@min(remaining_splat, splat_buffer.len)]);
},
else => for (0..@min(splat, iovecs.len - iovlen)) |_| {
addBuf(&iovecs, &iovlen, pattern);
},
},
};
if (iovlen == 0) return 0;
if (native_os == .wasi and !builtin.link_libc) {
var n_written: usize = undefined;
const syscall: Syscall = try .start();
while (true) {
switch (std.os.wasi.fd_write(file.handle, &iovecs, iovlen, &n_written)) {
.SUCCESS => {
syscall.finish();
return n_written;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.INVAL => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.AGAIN => |err| return errnoBug(err),
.BADF => return error.NotOpenForWriting, // can be a race condition.
.DESTADDRREQ => |err| return errnoBug(err), // `connect` was never called.
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.PermissionDenied,
.PIPE => return error.BrokenPipe,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.writev(file.handle, &iovecs, @intCast(iovlen));
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
return @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.INVAL => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.AGAIN => return error.WouldBlock,
.BADF => return error.NotOpenForWriting, // Can be a race condition.
.DESTADDRREQ => |err| return errnoBug(err), // `connect` was never called.
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.PermissionDenied,
.PIPE => return error.BrokenPipe,
.CONNRESET => |err| return errnoBug(err), // Not a socket handle.
.BUSY => return error.DeviceBusy,
.ACCES => return error.AccessDenied,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn fileWriteStreamingWindows(file: File, buffer: []const u8) File.Writer.Error!usize {
assert(buffer.len != 0);
var iosb: windows.IO_STATUS_BLOCK = undefined;
if (file.flags.nonblocking) {
var done: bool = false;
switch (windows.ntdll.NtWriteFile(
file.handle,
null, // event
flagApc,
&done, // APC context
&iosb,
buffer.ptr,
@intCast(buffer.len),
null, // byte offset
null, // key
)) {
// We must wait for the APC routine.
.PENDING, .SUCCESS => while (!done) {
// Once we get here we must not return from the function until the
// operation completes, thereby releasing reference to io_status_block.
const alertable_syscall = AlertableSyscall.start() catch |err| switch (err) {
error.Canceled => |e| {
var cancel_iosb: windows.IO_STATUS_BLOCK = undefined;
_ = windows.ntdll.NtCancelIoFileEx(file.handle, &iosb, &cancel_iosb);
while (!done) waitForApcOrAlert();
return e;
},
};
waitForApcOrAlert();
alertable_syscall.finish();
},
else => |status| iosb.u.Status = status,
}
} else {
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtWriteFile(
file.handle,
null, // event
null, // APC routine
null, // APC context
&iosb,
buffer.ptr,
@intCast(buffer.len),
null, // byte offset
null, // key
)) {
.PENDING => unreachable, // unrecoverable: wrong File nonblocking flag
.CANCELLED => try syscall.checkCancel(),
else => |status| {
syscall.finish();
iosb.u.Status = status;
break;
},
};
}
return ntWriteFileResult(&iosb);
}
fn fileWriteFileStreaming(
userdata: ?*anyopaque,
file: File,
header: []const u8,
file_reader: *File.Reader,
limit: Io.Limit,
) File.Writer.WriteFileError!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const reader_buffered = file_reader.interface.buffered();
if (reader_buffered.len >= @backingInt(limit)) {
const n = try fileWriteStreaming(t, file, header, &.{limit.slice(reader_buffered)}, 1);
file_reader.interface.toss(n -| header.len);
return n;
}
const file_limit = @backingInt(limit) - reader_buffered.len;
const out_fd = file.handle;
const in_fd = file_reader.file.handle;
if (file_reader.size) |size| {
if (size - file_reader.pos == 0) {
if (reader_buffered.len != 0) {
const n = try fileWriteStreaming(t, file, header, &.{limit.slice(reader_buffered)}, 1);
file_reader.interface.toss(n -| header.len);
return n;
} else {
return error.EndOfStream;
}
}
}
if (native_os == .freebsd) sf: {
// Try using sendfile on FreeBSD.
if (@atomicLoad(UseSendfile, &t.use_sendfile, .monotonic) == .disabled) break :sf;
const offset = std.math.cast(std.c.off_t, file_reader.pos) orelse break :sf;
var hdtr_data: std.c.sf_hdtr = undefined;
var headers: [2]posix.iovec_const = undefined;
var headers_i: u8 = 0;
if (header.len != 0) {
headers[headers_i] = .{ .base = header.ptr, .len = header.len };
headers_i += 1;
}
if (reader_buffered.len != 0) {
headers[headers_i] = .{ .base = reader_buffered.ptr, .len = reader_buffered.len };
headers_i += 1;
}
const hdtr: ?*std.c.sf_hdtr = if (headers_i == 0) null else b: {
hdtr_data = .{
.headers = &headers,
.hdr_cnt = headers_i,
.trailers = null,
.trl_cnt = 0,
};
break :b &hdtr_data;
};
var sbytes: std.c.off_t = 0;
const nbytes: usize = @min(file_limit, std.math.maxInt(usize));
const flags = 0;
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(std.c.sendfile(in_fd, out_fd, offset, nbytes, hdtr, &sbytes, flags))) {
.SUCCESS => {
syscall.finish();
break;
},
.INVAL, .OPNOTSUPP, .NOTSOCK, .NOSYS => {
// Give calling code chance to observe before trying
// something else.
syscall.finish();
@atomicStore(UseSendfile, &t.use_sendfile, .disabled, .monotonic);
return 0;
},
.INTR, .BUSY => {
if (sbytes == 0) {
try syscall.checkCancel();
continue;
} else {
// Even if we are being canceled, there have been side
// effects, so it is better to report those side
// effects to the caller.
syscall.finish();
break;
}
},
.AGAIN => {
syscall.finish();
if (sbytes == 0) return error.WouldBlock;
break;
},
else => |e| {
syscall.finish();
assert(error.Unexpected == switch (e) {
.NOTCONN => return error.BrokenPipe,
.IO => return error.InputOutput,
.PIPE => return error.BrokenPipe,
.NOBUFS => return error.SystemResources,
.BADF => |err| errnoBug(err),
.FAULT => |err| errnoBug(err),
else => |err| posix.unexpectedErrno(err),
});
// Give calling code chance to observe the error before trying
// something else.
@atomicStore(UseSendfile, &t.use_sendfile, .disabled, .monotonic);
return 0;
},
}
}
if (sbytes == 0) {
file_reader.size = file_reader.pos;
return error.EndOfStream;
}
const ubytes: usize = @intCast(sbytes);
file_reader.interface.toss(ubytes -| header.len);
return ubytes;
}
if (is_darwin) sf: {
// Try using sendfile on macOS.
if (@atomicLoad(UseSendfile, &t.use_sendfile, .monotonic) == .disabled) break :sf;
const offset = std.math.cast(std.c.off_t, file_reader.pos) orelse break :sf;
var hdtr_data: std.c.sf_hdtr = undefined;
var headers: [2]posix.iovec_const = undefined;
var headers_i: u8 = 0;
if (header.len != 0) {
headers[headers_i] = .{ .base = header.ptr, .len = header.len };
headers_i += 1;
}
if (reader_buffered.len != 0) {
headers[headers_i] = .{ .base = reader_buffered.ptr, .len = reader_buffered.len };
headers_i += 1;
}
const hdtr: ?*std.c.sf_hdtr = if (headers_i == 0) null else b: {
hdtr_data = .{
.headers = &headers,
.hdr_cnt = headers_i,
.trailers = null,
.trl_cnt = 0,
};
break :b &hdtr_data;
};
const max_count = std.math.maxInt(i32); // Avoid EINVAL.
var len: std.c.off_t = @min(file_limit, max_count);
const flags = 0;
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(std.c.sendfile(in_fd, out_fd, offset, &len, hdtr, flags))) {
.SUCCESS => {
syscall.finish();
break;
},
.OPNOTSUPP, .NOTSOCK, .NOSYS => {
// Give calling code chance to observe before trying
// something else.
syscall.finish();
@atomicStore(UseSendfile, &t.use_sendfile, .disabled, .monotonic);
return 0;
},
.INTR => {
if (len == 0) {
try syscall.checkCancel();
continue;
} else {
// Even if we are being canceled, there have been side
// effects, so it is better to report those side
// effects to the caller.
syscall.finish();
break;
}
},
.AGAIN => {
syscall.finish();
if (len == 0) return error.WouldBlock;
break;
},
else => |e| {
syscall.finish();
assert(error.Unexpected == switch (e) {
.NOTCONN => return error.BrokenPipe,
.IO => return error.InputOutput,
.PIPE => return error.BrokenPipe,
.BADF => |err| errnoBug(err),
.FAULT => |err| errnoBug(err),
.INVAL => |err| errnoBug(err),
else => |err| posix.unexpectedErrno(err),
});
// Give calling code chance to observe the error before trying
// something else.
@atomicStore(UseSendfile, &t.use_sendfile, .disabled, .monotonic);
return 0;
},
}
}
if (len == 0) {
file_reader.size = file_reader.pos;
return error.EndOfStream;
}
const u_len: usize = @bitCast(len);
file_reader.interface.toss(u_len -| header.len);
return u_len;
}
if (native_os == .linux) sf: {
// Try using sendfile on Linux.
if (@atomicLoad(UseSendfile, &t.use_sendfile, .monotonic) == .disabled) break :sf;
// Linux sendfile does not support headers.
if (header.len != 0 or reader_buffered.len != 0) {
const n = try fileWriteStreaming(t, file, header, &.{limit.slice(reader_buffered)}, 1);
file_reader.interface.toss(n -| header.len);
return n;
}
const max_count = 0x7ffff000; // Avoid EINVAL.
var off: std.os.linux.off_t = undefined;
const off_ptr: ?*std.os.linux.off_t, const count: usize = switch (file_reader.mode) {
.positional => o: {
const size = file_reader.getSize() catch |err| switch (err) {
error.Canceled => |e| return e,
else => break :sf,
};
off = std.math.cast(std.os.linux.off_t, file_reader.pos) orelse return error.ReadFailed;
break :o .{ &off, @min(@backingInt(limit), size - file_reader.pos, max_count) };
},
.streaming => .{ null, limit.minInt(max_count) },
.streaming_simple, .positional_simple => break :sf,
.failure => return error.ReadFailed,
};
const syscall: Syscall = try .start();
const n: usize = while (true) {
const rc = sendfile_sym(out_fd, in_fd, off_ptr, count);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
break @intCast(rc);
},
.NOSYS, .INVAL => {
// Give calling code chance to observe before trying
// something else.
syscall.finish();
@atomicStore(UseSendfile, &t.use_sendfile, .disabled, .monotonic);
return 0;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
assert(error.Unexpected == switch (e) {
.NOTCONN => return error.BrokenPipe, // `out_fd` is an unconnected socket
.AGAIN => return error.WouldBlock,
.IO => return error.InputOutput,
.PIPE => return error.BrokenPipe,
.NOMEM => return error.SystemResources,
.NXIO, .SPIPE => {
file_reader.mode = file_reader.mode.toStreaming();
const pos = file_reader.pos;
if (pos != 0) {
file_reader.pos = 0;
file_reader.seekBy(@intCast(pos)) catch {
file_reader.mode = .failure;
return error.ReadFailed;
};
}
return 0;
},
.BADF => |err| errnoBug(err), // Always a race condition.
.FAULT => |err| errnoBug(err), // Segmentation fault.
.OVERFLOW => |err| errnoBug(err), // We avoid passing too large of a `count`.
else => |err| posix.unexpectedErrno(err),
});
// Give calling code chance to observe the error before trying
// something else.
@atomicStore(UseSendfile, &t.use_sendfile, .disabled, .monotonic);
return 0;
},
}
};
if (n == 0) {
file_reader.size = file_reader.pos;
return error.EndOfStream;
}
file_reader.pos += n;
return n;
}
if (have_copy_file_range) cfr: {
if (@atomicLoad(UseCopyFileRange, &t.use_copy_file_range, .monotonic) == .disabled) break :cfr;
if (header.len != 0 or reader_buffered.len != 0) {
const n = try fileWriteStreaming(t, file, header, &.{limit.slice(reader_buffered)}, 1);
file_reader.interface.toss(n -| header.len);
return n;
}
var len: usize = @backingInt(limit);
var off_in: i64 = undefined;
const off_in_ptr: ?*i64 = switch (file_reader.mode) {
.positional_simple, .streaming_simple => return error.Unimplemented,
.positional => p: {
len = @min(len, std.math.maxInt(usize) - file_reader.pos);
off_in = @intCast(file_reader.pos);
break :p &off_in;
},
.streaming => null,
.failure => return error.ReadFailed,
};
const n: usize = switch (native_os) {
.linux => n: {
const syscall: Syscall = try .start();
while (true) {
const rc = linux_copy_file_range_sys.copy_file_range(in_fd, off_in_ptr, out_fd, null, len, 0);
switch (linux_copy_file_range_sys.errno(rc)) {
.SUCCESS => {
syscall.finish();
break :n @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
.OPNOTSUPP, .INVAL, .NOSYS => {
// Give calling code chance to observe before trying
// something else.
syscall.finish();
@atomicStore(UseCopyFileRange, &t.use_copy_file_range, .disabled, .monotonic);
return 0;
},
else => |e| {
syscall.finish();
assert(error.Unexpected == switch (e) {
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.OVERFLOW => |err| errnoBug(err), // We avoid passing too large a count.
.PERM => return error.PermissionDenied,
.BUSY => return error.DeviceBusy,
.TXTBSY => return error.FileBusy,
// copy_file_range can still work but not on
// this pair of file descriptors.
.XDEV => return error.Unimplemented,
.ISDIR => |err| errnoBug(err),
.BADF => |err| errnoBug(err),
else => |err| posix.unexpectedErrno(err),
});
@atomicStore(UseCopyFileRange, &t.use_copy_file_range, .disabled, .monotonic);
return 0;
},
}
}
},
.freebsd => n: {
const syscall: Syscall = try .start();
while (true) {
const rc = std.c.copy_file_range(in_fd, off_in_ptr, out_fd, null, @backingInt(limit), 0);
switch (std.c.errno(rc)) {
.SUCCESS => {
syscall.finish();
break :n @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
.OPNOTSUPP, .INVAL, .NOSYS => {
// Give calling code chance to observe before trying
// something else.
syscall.finish();
@atomicStore(UseCopyFileRange, &t.use_copy_file_range, .disabled, .monotonic);
return 0;
},
else => |e| {
syscall.finish();
assert(error.Unexpected == switch (e) {
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.INTEGRITY => return error.CorruptedData,
.NOSPC => return error.NoSpaceLeft,
.ISDIR => |err| errnoBug(err),
.BADF => |err| errnoBug(err),
else => |err| posix.unexpectedErrno(err),
});
@atomicStore(UseCopyFileRange, &t.use_copy_file_range, .disabled, .monotonic);
return 0;
},
}
}
},
else => comptime unreachable,
};
if (n == 0) {
file_reader.size = file_reader.pos;
return error.EndOfStream;
}
file_reader.pos += n;
return n;
}
return error.Unimplemented;
}
fn netWriteFile(
userdata: ?*anyopaque,
socket_handle: net.Socket.Handle,
header: []const u8,
file_reader: *File.Reader,
limit: Io.Limit,
) net.Stream.Writer.WriteFileError!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
_ = socket_handle;
_ = header;
_ = file_reader;
_ = limit;
// TODO implement netWriteFile
return error.Unimplemented;
}
fn fileWriteFilePositional(
userdata: ?*anyopaque,
file: File,
header: []const u8,
file_reader: *File.Reader,
limit: Io.Limit,
offset: u64,
) File.WriteFilePositionalError!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const reader_buffered = file_reader.interface.buffered();
if (reader_buffered.len >= @backingInt(limit)) {
const n = try fileWritePositional(t, file, header, &.{limit.slice(reader_buffered)}, 1, offset);
file_reader.interface.toss(n -| header.len);
return n;
}
const out_fd = file.handle;
const in_fd = file_reader.file.handle;
if (file_reader.size) |size| {
if (size - file_reader.pos == 0) {
if (reader_buffered.len != 0) {
const n = try fileWritePositional(t, file, header, &.{limit.slice(reader_buffered)}, 1, offset);
file_reader.interface.toss(n -| header.len);
return n;
} else {
return error.EndOfStream;
}
}
}
if (have_copy_file_range) cfr: {
if (@atomicLoad(UseCopyFileRange, &t.use_copy_file_range, .monotonic) == .disabled) break :cfr;
if (header.len != 0 or reader_buffered.len != 0) {
const n = try fileWritePositional(t, file, header, &.{limit.slice(reader_buffered)}, 1, offset);
file_reader.interface.toss(n -| header.len);
return n;
}
var len: usize = @min(@backingInt(limit), std.math.maxInt(usize) - offset);
var off_in: i64 = undefined;
const off_in_ptr: ?*i64 = switch (file_reader.mode) {
.positional_simple, .streaming_simple => return error.Unimplemented,
.positional => p: {
len = @min(len, std.math.maxInt(usize) - file_reader.pos);
off_in = @intCast(file_reader.pos);
break :p &off_in;
},
.streaming => null,
.failure => return error.ReadFailed,
};
var off_out: i64 = @intCast(offset);
const n: usize = switch (native_os) {
.linux => n: {
const syscall: Syscall = try .start();
while (true) {
const rc = linux_copy_file_range_sys.copy_file_range(in_fd, off_in_ptr, out_fd, &off_out, len, 0);
switch (linux_copy_file_range_sys.errno(rc)) {
.SUCCESS => {
syscall.finish();
break :n @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
.OPNOTSUPP, .INVAL, .NOSYS => {
// Give calling code chance to observe before trying
// something else.
syscall.finish();
@atomicStore(UseCopyFileRange, &t.use_copy_file_range, .disabled, .monotonic);
return 0;
},
else => |e| {
syscall.finish();
assert(error.Unexpected == switch (e) {
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.OVERFLOW => |err| errnoBug(err), // We avoid passing too large a count.
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.PERM => return error.PermissionDenied,
.TXTBSY => return error.FileBusy,
// copy_file_range can still work but not on
// this pair of file descriptors.
.XDEV => return error.Unimplemented,
.ISDIR => |err| errnoBug(err),
.BADF => |err| errnoBug(err),
else => |err| posix.unexpectedErrno(err),
});
@atomicStore(UseCopyFileRange, &t.use_copy_file_range, .disabled, .monotonic);
return 0;
},
}
}
},
.freebsd => n: {
const syscall: Syscall = try .start();
while (true) {
const rc = std.c.copy_file_range(in_fd, off_in_ptr, out_fd, &off_out, @backingInt(limit), 0);
switch (std.c.errno(rc)) {
.SUCCESS => {
syscall.finish();
break :n @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
.OPNOTSUPP, .INVAL, .NOSYS => {
// Give calling code chance to observe before trying
// something else.
syscall.finish();
@atomicStore(UseCopyFileRange, &t.use_copy_file_range, .disabled, .monotonic);
return 0;
},
else => |e| {
syscall.finish();
assert(error.Unexpected == switch (e) {
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.INTEGRITY => return error.CorruptedData,
.NOSPC => return error.NoSpaceLeft,
.OVERFLOW => return error.Unseekable,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.ISDIR => |err| errnoBug(err),
.BADF => |err| errnoBug(err),
else => |err| posix.unexpectedErrno(err),
});
@atomicStore(UseCopyFileRange, &t.use_copy_file_range, .disabled, .monotonic);
return 0;
},
}
}
},
else => comptime unreachable,
};
if (n == 0) {
file_reader.size = file_reader.pos;
return error.EndOfStream;
}
file_reader.pos += n;
return n;
}
if (is_darwin) fcf: {
if (@atomicLoad(UseFcopyfile, &t.use_fcopyfile, .monotonic) == .disabled) break :fcf;
if (file_reader.pos != 0) break :fcf;
if (offset != 0) break :fcf;
if (limit != .unlimited) break :fcf;
const size = file_reader.getSize() catch |err| switch (err) {
error.Canceled => |e| return e,
else => break :fcf,
};
if (header.len != 0 or reader_buffered.len != 0) {
const n = try fileWritePositional(t, file, header, &.{limit.slice(reader_buffered)}, 1, offset);
file_reader.interface.toss(n -| header.len);
return n;
}
const syscall: Syscall = try .start();
while (true) {
const rc = std.c.fcopyfile(in_fd, out_fd, null, .{ .DATA = true });
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.OPNOTSUPP => {
// Give calling code chance to observe before trying
// something else.
syscall.finish();
@atomicStore(UseFcopyfile, &t.use_fcopyfile, .disabled, .monotonic);
return 0;
},
else => |e| {
syscall.finish();
assert(error.Unexpected == switch (e) {
.NOMEM => return error.SystemResources,
.INVAL => |err| errnoBug(err),
else => |err| posix.unexpectedErrno(err),
});
return 0;
},
}
}
file_reader.pos = size;
return size;
}
return error.Unimplemented;
}
fn nowPosix(clock: Io.Clock) Io.Timestamp {
const clock_id: posix.clockid_t = clockToPosix(clock);
var timespec: posix.timespec = undefined;
switch (posix.errno(posix.system.clock_gettime(clock_id, ×pec))) {
.SUCCESS => return timestampFromPosix(×pec),
else => return .zero,
}
}
fn now(userdata: ?*anyopaque, clock: Io.Clock) Io.Timestamp {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
return switch (native_os) {
.windows => nowWindows(clock),
.wasi => nowWasi(clock),
else => nowPosix(clock),
};
}
fn clockResolution(userdata: ?*anyopaque, clock: Io.Clock) Io.Clock.ResolutionError!Io.Duration {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
return switch (native_os) {
.windows => switch (clock) {
.awake, .boot, .real => {
// We don't need to cache QPF as it's internally just a memory read to KUSER_SHARED_DATA
// (a read-only page of info updated and mapped by the kernel to all processes):
// https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-kuser_shared_data
// https://www.geoffchappell.com/studies/windows/km/ntoskrnl/inc/api/ntexapi_x/kuser_shared_data/index.htm
var qpf: windows.LARGE_INTEGER = undefined;
if (!windows.ntdll.RtlQueryPerformanceFrequency(&qpf).toBool()) {
recoverableOsBugDetected();
return .zero;
}
// 10Mhz (1 qpc tick every 100ns) is a common enough QPF value that we can optimize on it.
// https://github.com/microsoft/STL/blob/785143a0c73f030238ef618890fd4d6ae2b3a3a0/stl/inc/chrono#L694-L701
const common_qpf = 10_000_000;
if (qpf == common_qpf) return .fromNanoseconds(std.time.ns_per_s / common_qpf);
// Convert to ns using fixed point.
const scale = @as(u64, std.time.ns_per_s << 32) / @as(u32, @intCast(qpf));
const result = scale >> 32;
return .fromNanoseconds(result);
},
.cpu_process, .cpu_thread => return error.ClockUnavailable,
},
.wasi => {
if (builtin.link_libc) return clockResolutionPosix(clock);
var ns: std.os.wasi.timestamp_t = undefined;
return switch (std.os.wasi.clock_res_get(clockToWasi(clock), &ns)) {
.SUCCESS => .fromNanoseconds(ns),
.INVAL => return error.ClockUnavailable,
else => |err| return posix.unexpectedErrno(err),
};
},
else => return clockResolutionPosix(clock),
};
}
fn clockResolutionPosix(clock: Io.Clock) Io.Clock.ResolutionError!Io.Duration {
const clock_id: posix.clockid_t = clockToPosix(clock);
var timespec: posix.timespec = undefined;
return switch (posix.errno(posix.system.clock_getres(clock_id, ×pec))) {
.SUCCESS => .fromNanoseconds(nanosecondsFromPosix(×pec)),
.INVAL => return error.ClockUnavailable,
else => |err| return posix.unexpectedErrno(err),
};
}
fn nowWindows(clock: Io.Clock) Io.Timestamp {
switch (clock) {
.real => {
// RtlGetSystemTimePrecise() has a granularity of 100 nanoseconds
// and uses the NTFS/Windows epoch, which is 1601-01-01.
const epoch_ns = std.time.epoch.windows * std.time.ns_per_s;
return .{ .nanoseconds = @as(i96, windows.ntdll.RtlGetSystemTimePrecise()) * 100 + epoch_ns };
},
.awake, .boot => {
// We don't need to cache QPF as it's internally just a memory read to KUSER_SHARED_DATA
// (a read-only page of info updated and mapped by the kernel to all processes):
// https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-kuser_shared_data
// https://www.geoffchappell.com/studies/windows/km/ntoskrnl/inc/api/ntexapi_x/kuser_shared_data/index.htm
const qpf: u64 = qpf: {
var qpf: windows.LARGE_INTEGER = undefined;
assert(windows.ntdll.RtlQueryPerformanceFrequency(&qpf).toBool());
break :qpf @bitCast(qpf);
};
// QPC on windows doesn't fail on >= XP/2000 and includes time suspended.
const qpc: u64 = qpc: {
var qpc: windows.LARGE_INTEGER = undefined;
assert(windows.ntdll.RtlQueryPerformanceCounter(&qpc).toBool());
break :qpc @bitCast(qpc);
};
// 10Mhz (1 qpc tick every 100ns) is a common enough QPF value that we can optimize on it.
// https://github.com/microsoft/STL/blob/785143a0c73f030238ef618890fd4d6ae2b3a3a0/stl/inc/chrono#L694-L701
const common_qpf = 10_000_000;
if (qpf == common_qpf) return .{ .nanoseconds = qpc * (std.time.ns_per_s / common_qpf) };
// Convert to ns using fixed point.
const scale = @as(u64, std.time.ns_per_s << 32) / @as(u32, @intCast(qpf));
const result = (@as(u96, qpc) * scale) >> 32;
return .{ .nanoseconds = @intCast(result) };
},
.cpu_process => {
const handle = windows.GetCurrentProcess();
var times: windows.KERNEL_USER_TIMES = undefined;
// https://github.com/reactos/reactos/blob/master/ntoskrnl/ps/query.c#L442-L485
if (windows.ntdll.NtQueryInformationProcess(
handle,
.Times,
×,
@sizeOf(windows.KERNEL_USER_TIMES),
null,
) != .SUCCESS) return .zero;
const sum = @as(i96, times.UserTime) + @as(i96, times.KernelTime);
return .{ .nanoseconds = sum * 100 };
},
.cpu_thread => {
const handle = windows.GetCurrentThread();
var times: windows.KERNEL_USER_TIMES = undefined;
// https://github.com/reactos/reactos/blob/master/ntoskrnl/ps/query.c#L2971-L3019
if (windows.ntdll.NtQueryInformationThread(
handle,
.Times,
×,
@sizeOf(windows.KERNEL_USER_TIMES),
null,
) != .SUCCESS) return .zero;
const sum = @as(i96, times.UserTime) + @as(i96, times.KernelTime);
return .{ .nanoseconds = sum * 100 };
},
}
}
fn nowWasi(clock: Io.Clock) Io.Timestamp {
var ns: std.os.wasi.timestamp_t = undefined;
const err = std.os.wasi.clock_time_get(clockToWasi(clock), 1, &ns);
if (err != .SUCCESS) return .zero;
return .fromNanoseconds(ns);
}
fn sleep(userdata: ?*anyopaque, timeout: Io.Timeout) Io.Cancelable!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (use_parking_sleep) return parking_sleep.sleep(timeout);
if (native_os == .wasi) return sleepWasi(t, timeout);
if (@TypeOf(posix.system.clock_nanosleep) != void) return sleepPosix(timeout);
return sleepNanosleep(t, timeout);
}
fn sleepPosix(timeout: Io.Timeout) Io.Cancelable!void {
const clock_id: posix.clockid_t = clockToPosix(switch (timeout) {
.none => .awake,
.duration => |d| d.clock,
.deadline => |d| d.clock,
});
const deadline_nanoseconds: i96 = switch (timeout) {
.none => std.math.maxInt(i96),
.duration => |duration| duration.raw.nanoseconds,
.deadline => |deadline| deadline.raw.nanoseconds,
};
var timespec: posix.timespec = timestampToPosix(deadline_nanoseconds);
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.clock_nanosleep(clock_id, .{ .ABSTIME = switch (timeout) {
.none, .duration => false,
.deadline => true,
} }, ×pec, ×pec);
// POSIX-standard libc clock_nanosleep() returns *positive* errno values directly
switch (if (builtin.link_libc) @as(posix.E, @fromBackingInt(@intCast(rc))) else posix.errno(rc)) {
.INTR => {
try syscall.checkCancel();
continue;
},
// Handles SUCCESS as well as clock not available and unexpected
// errors. The user had a chance to check clock resolution before
// getting here, which would have reported 0, making this a legal
// amount of time to sleep.
else => {
syscall.finish();
return;
},
}
}
}
fn sleepWasi(t: *Threaded, timeout: Io.Timeout) Io.Cancelable!void {
const t_io = io(t);
const w = std.os.wasi;
const clock: w.subscription_clock_t = if (timeout.toDurationFromNow(t_io)) |d| .{
.id = clockToWasi(d.clock),
.timeout = std.math.lossyCast(u64, d.raw.nanoseconds),
.precision = 0,
.flags = 0,
} else .{
.id = .MONOTONIC,
.timeout = std.math.maxInt(u64),
.precision = 0,
.flags = 0,
};
const in: w.subscription_t = .{
.userdata = 0,
.u = .{
.tag = .CLOCK,
.u = .{ .clock = clock },
},
};
var event: w.event_t = undefined;
var nevents: usize = undefined;
const syscall: Syscall = try .start();
_ = w.poll_oneoff(&in, &event, 1, &nevents);
syscall.finish();
}
fn sleepNanosleep(t: *Threaded, timeout: Io.Timeout) Io.Cancelable!void {
const t_io = io(t);
const sec_type = @typeInfo(posix.timespec).@"struct".field_types[0];
const nsec_type = @typeInfo(posix.timespec).@"struct".field_types[1];
var timespec: posix.timespec = t: {
const d = timeout.toDurationFromNow(t_io) orelse break :t .{
.sec = std.math.maxInt(sec_type),
.nsec = std.math.maxInt(nsec_type),
};
break :t timestampToPosix(d.raw.toNanoseconds());
};
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.nanosleep(×pec, ×pec))) {
.INTR => {
try syscall.checkCancel();
continue;
},
// This prong handles success as well as unexpected errors.
else => return syscall.finish(),
}
}
}
fn netListenIpPosix(
userdata: ?*anyopaque,
address: *const IpAddress,
options: IpAddress.ListenOptions,
) IpAddress.ListenError!net.Socket {
if (!have_networking) return error.NetworkDown;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const family = posixAddressFamily(address);
const socket_fd = try openSocketPosix(family, .{ .mode = options.mode, .protocol = options.protocol });
errdefer closeFd(socket_fd);
if (options.reuse_address) {
try setSocketOptionPosix(socket_fd, posix.SOL.SOCKET, posix.SO.REUSEADDR, 1);
if (@hasDecl(posix.SO, "REUSEPORT"))
try setSocketOptionPosix(socket_fd, posix.SOL.SOCKET, posix.SO.REUSEPORT, 1);
}
var storage: PosixAddress = undefined;
var addr_len = addressToPosix(address, &storage);
try posixBind(socket_fd, &storage.any, addr_len);
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.listen(socket_fd, options.kernel_backlog))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.ADDRINUSE => return syscall.fail(error.AddressInUse),
.BADF => |err| return syscall.errnoBug(err), // File descriptor used after closed.
else => |err| return syscall.unexpectedErrno(err),
}
}
try posixGetSockName(socket_fd, &storage.any, &addr_len);
return .{ .handle = socket_fd, .address = addressFromPosix(&storage) };
}
fn netListenIpWindows(
userdata: ?*anyopaque,
address: *const IpAddress,
options: IpAddress.ListenOptions,
) IpAddress.ListenError!net.Socket {
if (!have_networking) return error.NetworkDown;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const family = posixAddressFamily(address);
const socket_handle = try openSocketAfd(family, .{ .mode = options.mode, .protocol = options.protocol });
errdefer windows.CloseHandle(socket_handle);
if (options.reuse_address) try setSocketOptionAfd(socket_handle, ws2_32.SOL.SOCKET, ws2_32.SO.REUSEADDR, true);
const bound_address = try bindSocketIpAfd(socket_handle, address, .Passive);
switch ((try deviceIoControl(&.{
.file = .{ .handle = socket_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.START_LISTEN,
.in = @ptrCast(&windows.AFD.LISTEN_INFO{
.UseSAN = .FALSE,
.MaximumConnectionQueue = options.kernel_backlog,
.UseDelayedAcceptance = .FALSE,
}),
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
else => |status| return windows.unexpectedStatus(status),
}
return .{ .handle = socket_handle, .address = bound_address };
}
fn netListenUnixPosix(
userdata: ?*anyopaque,
address: *const net.UnixAddress,
options: net.UnixAddress.ListenOptions,
) net.UnixAddress.ListenError!net.Socket.Handle {
if (!net.has_unix_sockets) return error.AddressFamilyUnsupported;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const socket_fd = openSocketPosix(posix.AF.UNIX, .{ .mode = .stream }) catch |err| switch (err) {
error.ProtocolUnsupportedBySystem => return error.AddressFamilyUnsupported,
error.ProtocolUnsupportedByAddressFamily => return error.AddressFamilyUnsupported,
error.SocketModeUnsupported => return error.AddressFamilyUnsupported,
error.OptionUnsupported => return error.Unexpected,
else => |e| return e,
};
errdefer closeFd(socket_fd);
var storage: UnixAddress = undefined;
const addr_len = addressUnixToPosix(address, &storage);
try posixBindUnix(socket_fd, &storage.any, addr_len);
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.listen(socket_fd, options.kernel_backlog))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.ADDRINUSE => return syscall.fail(error.AddressInUse),
.BADF => |err| return syscall.errnoBug(err), // File descriptor used after closed.
else => |err| return syscall.unexpectedErrno(err),
}
}
return socket_fd;
}
fn netListenUnixWindows(
userdata: ?*anyopaque,
address: *const net.UnixAddress,
options: net.UnixAddress.ListenOptions,
) net.UnixAddress.ListenError!net.Socket.Handle {
if (!net.has_unix_sockets) return error.AddressFamilyUnsupported;
if (!have_networking) return error.NetworkDown;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const is_abstract = address.isAbstract();
const wps = if (!is_abstract) sliceToPrefixedFileW(null, address.path, .{
.allow_relative = false,
}) catch |err| switch (err) {
error.NameTooLong, error.BadPathName => return error.AddressUnavailable,
else => |e| return e,
} else undefined;
const socket_handle = openSocketAfd(ws2_32.AF.UNIX, .{ .mode = .stream }) catch |err| switch (err) {
error.ProtocolUnsupportedByAddressFamily => return error.AddressFamilyUnsupported,
else => |e| return e,
};
errdefer windows.CloseHandle(socket_handle);
if (!is_abstract) try socketOptionAfd(socket_handle, .special, 0, ws2_32.SO.UNIX_PATH, @constCast(
@as([]const u8, @ptrCast(&windows.AFD.SOCKOPT_INFO.UNIX_PATH{
.Path = wps.data,
}))[0 .. @offsetOf(windows.AFD.SOCKOPT_INFO.UNIX_PATH, "Path") + @sizeOf(windows.WCHAR) * wps.len],
));
try bindSocketUnixAfd(socket_handle, address);
switch ((try deviceIoControl(&.{
.file = .{ .handle = socket_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.START_LISTEN,
.in = @ptrCast(&windows.AFD.LISTEN_INFO{
.UseSAN = .FALSE,
.MaximumConnectionQueue = options.kernel_backlog,
.UseDelayedAcceptance = .FALSE,
}),
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
else => |status| return windows.unexpectedStatus(status),
}
return socket_handle;
}
fn posixBindUnix(
fd: posix.socket_t,
addr: *const posix.sockaddr,
addr_len: posix.socklen_t,
) !void {
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.bind(fd, addr, addr_len))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.ADDRINUSE => return error.AddressInUse,
.AFNOSUPPORT => return error.AddressFamilyUnsupported,
.ADDRNOTAVAIL => return error.AddressUnavailable,
.NOMEM => return error.SystemResources,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.ROFS => return error.ReadOnlyFileSystem,
.PERM => return error.PermissionDenied,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.INVAL => |err| return errnoBug(err), // invalid parameters
.NOTSOCK => |err| return errnoBug(err), // invalid `sockfd`
.FAULT => |err| return errnoBug(err), // invalid `addr` pointer
.NAMETOOLONG => |err| return errnoBug(err),
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn posixBind(
socket_fd: posix.socket_t,
addr: *const posix.sockaddr,
addr_len: posix.socklen_t,
) !void {
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.bind(socket_fd, addr, addr_len))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => return error.AccessDenied,
.ADDRINUSE => return error.AddressInUse,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.INVAL => |err| return errnoBug(err), // invalid parameters
.NOTSOCK => |err| return errnoBug(err), // invalid `sockfd`
.AFNOSUPPORT => return error.AddressFamilyUnsupported,
.ADDRNOTAVAIL => return error.AddressUnavailable,
.FAULT => |err| return errnoBug(err), // invalid `addr` pointer
.NOMEM => return error.SystemResources,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn posixConnect(
socket_fd: posix.socket_t,
addr: *const posix.sockaddr,
addr_len: posix.socklen_t,
) !void {
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.connect(socket_fd, addr, addr_len))) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.ADDRNOTAVAIL => return syscall.fail(error.AddressUnavailable),
.AFNOSUPPORT => return syscall.fail(error.AddressFamilyUnsupported),
.AGAIN, .INPROGRESS => return syscall.fail(error.WouldBlock),
.ALREADY => return syscall.fail(error.ConnectionPending),
.CONNREFUSED => return syscall.fail(error.ConnectionRefused),
.CONNRESET => return syscall.fail(error.ConnectionResetByPeer),
.HOSTUNREACH => return syscall.fail(error.HostUnreachable),
.NETUNREACH => return syscall.fail(error.NetworkUnreachable),
.TIMEDOUT => return syscall.fail(error.Timeout),
.ACCES => return syscall.fail(error.AccessDenied),
.NETDOWN => return syscall.fail(error.NetworkDown),
.BADF => |err| return syscall.errnoBug(err), // File descriptor used after closed.
.CONNABORTED => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err),
.ISCONN => |err| return syscall.errnoBug(err),
.NOENT => |err| return syscall.errnoBug(err),
.NOTSOCK => |err| return syscall.errnoBug(err),
.PERM => |err| return syscall.errnoBug(err),
.PROTOTYPE => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
};
}
fn posixConnectUnix(
fd: posix.socket_t,
addr: *const posix.sockaddr,
addr_len: posix.socklen_t,
) !void {
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.connect(fd, addr, addr_len))) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.AFNOSUPPORT => return error.AddressFamilyUnsupported,
.AGAIN => return error.WouldBlock,
.INPROGRESS => return error.WouldBlock,
.ACCES => return error.AccessDenied,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.ROFS => return error.ReadOnlyFileSystem,
.PERM => return error.PermissionDenied,
.CONNREFUSED => return error.ConnectionRefused,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.CONNABORTED => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.ISCONN => |err| return errnoBug(err),
.NOTSOCK => |err| return errnoBug(err),
.PROTOTYPE => |err| return errnoBug(err),
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn posixGetSockName(
socket_fd: posix.fd_t,
addr: *posix.sockaddr,
addr_len: *posix.socklen_t,
) !void {
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.getsockname(socket_fd, addr, addr_len))) {
.SUCCESS => {
syscall.finish();
break;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.FAULT => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err), // invalid parameters
.NOTSOCK => |err| return errnoBug(err), // always a race condition
.NOBUFS => return error.SystemResources,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn setSocketOptionPosix(fd: posix.fd_t, level: i32, opt_name: u32, option: u32) !void {
const o: []const u8 = @ptrCast(&option);
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.setsockopt(fd, level, opt_name, o.ptr, @intCast(o.len)))) {
.SUCCESS => {
syscall.finish();
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.NOTSOCK => |err| return errnoBug(err),
.INVAL => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn setSocketOptionAfd(socket: net.Socket.Handle, level: i32, opt_name: u32, opt_val: anytype) !void {
try socketOptionAfd(socket, .set, level, opt_name, @ptrCast(@constCast(&opt_val)));
}
fn socketOptionAfd(socket: net.Socket.Handle, mode: windows.AFD.SOCKOPT_INFO.Mode, level: i32, opt_name: u32, opt_val: []u8) !void {
switch ((try deviceIoControl(&.{
.file = .{ .handle = socket, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.SOCKOPT,
.in = @ptrCast(&windows.AFD.SOCKOPT_INFO{
.mode = mode,
.level = level,
.optname = opt_name,
.optval = opt_val.ptr,
.optlen = opt_val.len,
}),
})).u.Status) {
.SUCCESS => return,
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
else => |status| return windows.unexpectedStatus(status),
}
}
fn netConnectIpPosix(
userdata: ?*anyopaque,
address: *const IpAddress,
options: IpAddress.ConnectOptions,
) IpAddress.ConnectError!net.Socket {
if (!have_networking) return error.NetworkDown;
if (options.timeout != .none) @panic("TODO implement netConnectIpPosix with timeout");
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const family = posixAddressFamily(address);
const socket_fd = try openSocketPosix(family, .{ .mode = options.mode, .protocol = options.protocol });
errdefer closeFd(socket_fd);
var storage: PosixAddress = undefined;
var addr_len = addressToPosix(address, &storage);
try posixConnect(socket_fd, &storage.any, addr_len);
try posixGetSockName(socket_fd, &storage.any, &addr_len);
return .{ .handle = socket_fd, .address = addressFromPosix(&storage) };
}
fn netConnectIpWindows(
userdata: ?*anyopaque,
address: *const IpAddress,
options: IpAddress.ConnectOptions,
) IpAddress.ConnectError!net.Socket {
if (!have_networking) return error.NetworkDown;
if (options.timeout != .none) @panic("TODO implement netConnectIpWindows with timeout");
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const family = posixAddressFamily(address);
const socket_handle = try openSocketAfd(family, .{ .mode = options.mode, .protocol = options.protocol });
errdefer windows.CloseHandle(socket_handle);
try setSocketOptionAfd(socket_handle, ws2_32.SOL.SOCKET, ws2_32.SO.REUSE_UNICASTPORT, true);
const bound_address = bindSocketIpAfd(socket_handle, &switch (address.*) {
.ip4 => .{ .ip4 = .unspecified(0) },
.ip6 => .{ .ip6 = .unspecified(0) },
}, .Active) catch |err| switch (err) {
error.AddressInUse => return error.Unexpected,
else => |e| return e,
};
const Storage = extern struct { Reserved0: [3]usize = @splat(0), Address: PosixAddress };
var storage: Storage = .{ .Address = undefined };
const addr_len = addressToPosix(address, &storage.Address);
switch ((try deviceIoControl(&.{
.file = .{ .handle = socket_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.CONNECT,
.in = @as([]const u8, @ptrCast(&storage))[0 .. @offsetOf(Storage, "Address") + addr_len],
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
.CONNECTION_REFUSED => return error.ConnectionRefused,
else => |status| return windows.unexpectedStatus(status),
}
return .{ .handle = socket_handle, .address = bound_address };
}
fn netConnectUnixPosix(
userdata: ?*anyopaque,
address: *const net.UnixAddress,
) net.UnixAddress.ConnectError!net.Socket.Handle {
if (!net.has_unix_sockets) return error.AddressFamilyUnsupported;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const socket_fd = openSocketPosix(posix.AF.UNIX, .{ .mode = .stream }) catch |err| switch (err) {
error.ProtocolUnsupportedByAddressFamily => return error.AddressFamilyUnsupported,
error.OptionUnsupported => return error.Unexpected,
else => |e| return e,
};
errdefer closeFd(socket_fd);
var storage: UnixAddress = undefined;
const addr_len = addressUnixToPosix(address, &storage);
try posixConnectUnix(socket_fd, &storage.any, addr_len);
return socket_fd;
}
fn netConnectUnixWindows(
userdata: ?*anyopaque,
address: *const net.UnixAddress,
) net.UnixAddress.ConnectError!net.Socket.Handle {
if (!net.has_unix_sockets) return error.AddressFamilyUnsupported;
if (!have_networking) return error.NetworkDown;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const is_abstract = address.isAbstract();
const wps = if (!is_abstract) sliceToPrefixedFileW(null, address.path, .{
.allow_relative = false,
}) catch |err| switch (err) {
error.NameTooLong, error.BadPathName => return error.FileNotFound,
else => |e| return e,
} else undefined;
const socket_handle = openSocketAfd(ws2_32.AF.UNIX, .{ .mode = .stream }) catch |err| switch (err) {
error.ProtocolUnsupportedByAddressFamily => return error.AddressFamilyUnsupported,
else => |e| return e,
};
errdefer windows.CloseHandle(socket_handle);
if (!is_abstract) try socketOptionAfd(socket_handle, .special, 0, ws2_32.SO.UNIX_PATH, @constCast(
@as([]const u8, @ptrCast(&windows.AFD.SOCKOPT_INFO.UNIX_PATH{
.Path = wps.data,
}))[0 .. @offsetOf(windows.AFD.SOCKOPT_INFO.UNIX_PATH, "Path") + @sizeOf(windows.WCHAR) * wps.len],
));
bindSocketUnixAfd(socket_handle, &(net.UnixAddress.init("") catch |err| switch (err) {
error.NameTooLong => unreachable,
})) catch |err| switch (err) {
error.AddressInUse => return error.Unexpected,
else => |e| return e,
};
const Storage = extern struct { Reserved0: [3]usize = @splat(0), Address: UnixAddress };
var storage: Storage = .{ .Address = undefined };
const addr_len = addressUnixToPosix(address, &storage.Address);
switch ((try deviceIoControl(&.{
.file = .{ .handle = socket_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.CONNECT,
.in = @as([]const u8, @ptrCast(&storage))[0 .. @offsetOf(Storage, "Address") + addr_len],
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
else => |status| return windows.unexpectedStatus(status),
}
return socket_handle;
}
fn netBindIpPosix(
userdata: ?*anyopaque,
address: *const IpAddress,
options: IpAddress.BindOptions,
) IpAddress.BindError!net.Socket {
if (!have_networking) return error.NetworkDown;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const family = posixAddressFamily(address);
const socket_fd = try openSocketPosix(family, options);
errdefer closeFd(socket_fd);
var storage: PosixAddress = undefined;
var addr_len = addressToPosix(address, &storage);
try posixBind(socket_fd, &storage.any, addr_len);
if (options.allow_broadcast) try setSocketOptionPosix(socket_fd, std.posix.SOL.SOCKET, std.posix.SO.BROADCAST, 1);
try posixGetSockName(socket_fd, &storage.any, &addr_len);
return .{ .handle = socket_fd, .address = addressFromPosix(&storage) };
}
fn netBindIpWindows(
userdata: ?*anyopaque,
address: *const IpAddress,
options: IpAddress.BindOptions,
) IpAddress.BindError!net.Socket {
if (!have_networking) return error.NetworkDown;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const family = posixAddressFamily(address);
const socket_handle = try openSocketAfd(family, options);
errdefer windows.CloseHandle(socket_handle);
const bound_address = try bindSocketIpAfd(socket_handle, address, .Active);
if (options.allow_broadcast) try setSocketOptionAfd(socket_handle, ws2_32.SOL.SOCKET, ws2_32.SO.BROADCAST, true);
return .{ .handle = socket_handle, .address = bound_address };
}
fn openSocketPosix(
family: posix.sa_family_t,
options: IpAddress.BindOptions,
) error{
AddressFamilyUnsupported,
ProtocolUnsupportedBySystem,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
SystemResources,
ProtocolUnsupportedByAddressFamily,
SocketModeUnsupported,
OptionUnsupported,
Unexpected,
Canceled,
}!posix.socket_t {
const mode, const protocol = try posixSocketModeProtocol(family, options.mode, options.protocol);
const flags: u32 = mode | if (socket_flags_unsupported) 0 else posix.SOCK.CLOEXEC;
const syscall: Syscall = try .start();
const socket_fd = while (true) {
const rc = posix.system.socket(family, flags, protocol);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
const fd: posix.fd_t = @intCast(rc);
errdefer closeFd(fd);
if (socket_flags_unsupported) try setCloexec(fd);
break fd;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.AFNOSUPPORT => return syscall.fail(error.AddressFamilyUnsupported),
.INVAL => return syscall.fail(error.ProtocolUnsupportedBySystem),
.MFILE => return syscall.fail(error.ProcessFdQuotaExceeded),
.NFILE => return syscall.fail(error.SystemFdQuotaExceeded),
.NOBUFS => return syscall.fail(error.SystemResources),
.NOMEM => return syscall.fail(error.SystemResources),
.PROTONOSUPPORT => return syscall.fail(error.ProtocolUnsupportedByAddressFamily),
.PROTOTYPE => return syscall.fail(error.SocketModeUnsupported),
else => |err| return syscall.unexpectedErrno(err),
}
};
errdefer closeFd(socket_fd);
if (options.ip6_only) |ip6_only| {
if (posix.IPV6 == void) return error.OptionUnsupported;
try setSocketOptionPosix(socket_fd, posix.IPPROTO.IPV6, posix.IPV6.V6ONLY, @intFromBool(ip6_only));
}
return socket_fd;
}
fn setCloexec(fd: posix.fd_t) error{ Canceled, Unexpected }!void {
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.fcntl(fd, posix.F.SETFD, @as(usize, posix.FD_CLOEXEC)))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |err| return syscall.unexpectedErrno(err),
};
}
fn netSocketCreatePair(
userdata: ?*anyopaque,
options: net.Socket.CreatePairOptions,
) net.Socket.CreatePairError![2]net.Socket {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (!have_networking) return error.OperationUnsupported;
if (@TypeOf(posix.system.socketpair) == void) return error.OperationUnsupported;
if (native_os == .haiku) @panic("TODO");
const family: posix.sa_family_t = switch (options.family) {
.ip4 => posix.AF.INET,
.ip6 => posix.AF.INET6,
};
const mode, const protocol = try posixSocketModeProtocol(family, options.mode, options.protocol);
const flags: u32 = mode | if (socket_flags_unsupported) 0 else posix.SOCK.CLOEXEC;
var sockets: [2]posix.socket_t = undefined;
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.socketpair(family, flags, protocol, &sockets))) {
.SUCCESS => {
syscall.finish();
errdefer {
closeFd(sockets[0]);
closeFd(sockets[1]);
}
if (socket_flags_unsupported) {
try setCloexec(sockets[0]);
try setCloexec(sockets[1]);
}
var storages: [2]PosixAddress = undefined;
var addr_lens: [2]posix.socklen_t = .{ @sizeOf(PosixAddress), @sizeOf(PosixAddress) };
try posixGetSockName(sockets[0], &storages[0].any, &addr_lens[0]);
try posixGetSockName(sockets[1], &storages[1].any, &addr_lens[1]);
return .{
.{ .handle = sockets[0], .address = addressFromPosix(&storages[0]) },
.{ .handle = sockets[1], .address = addressFromPosix(&storages[1]) },
};
},
.INTR => {
try syscall.checkCancel();
continue;
},
.ACCES => return syscall.fail(error.AccessDenied),
.AFNOSUPPORT => return syscall.fail(error.AddressFamilyUnsupported),
.INVAL => return syscall.fail(error.ProtocolUnsupportedBySystem),
.MFILE => return syscall.fail(error.ProcessFdQuotaExceeded),
.NFILE => return syscall.fail(error.SystemFdQuotaExceeded),
.NOBUFS => return syscall.fail(error.SystemResources),
.NOMEM => return syscall.fail(error.SystemResources),
.PROTONOSUPPORT => return syscall.fail(error.ProtocolUnsupportedByAddressFamily),
.PROTOTYPE => return syscall.fail(error.SocketModeUnsupported),
else => |err| return syscall.unexpectedErrno(err),
};
}
fn openSocketAfd(family: ws2_32.ADDRESS_FAMILY, options: IpAddress.BindOptions) !net.Socket.Handle {
const mode, const protocol = try posixSocketModeProtocol(family, options.mode, options.protocol);
var handle: windows.HANDLE = undefined;
var iosb: windows.IO_STATUS_BLOCK = undefined;
var syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtCreateFile(
&handle,
.{
.STANDARD = .{ .RIGHTS = .{ .WRITE_DAC = true }, .SYNCHRONIZE = true },
.GENERIC = .{ .WRITE = true, .READ = true },
},
&.{
.ObjectName = @constCast(&windows.UNICODE_STRING.init(
windows.AFD.DEVICE_NAME ++ .{ '\\', 'E', 'n', 'd', 'p', 'o', 'i', 'n', 't' },
)),
},
&iosb,
null,
.{},
.{ .READ = true, .WRITE = true },
.OPEN_IF,
.{ .IO = .ASYNCHRONOUS },
&windows.AFD.OPEN_PACKET.FULL_EA_INFORMATION{ .Value = .{
.EndpointType = .{
.CONNECTIONLESS = switch (options.mode) {
.stream, .seqpacket, .rdm => false,
.dgram, .raw => true,
},
.MESSAGEMODE = options.mode != .stream,
.RAW = options.mode == .raw,
},
.GroupID = 0,
.AddressFamily = family,
.SocketType = @bitCast(mode),
.Protocol = @bitCast(protocol),
.TransportDeviceNameLength = 0,
.TransportDeviceName = undefined,
} },
@sizeOf(windows.AFD.OPEN_PACKET.FULL_EA_INFORMATION),
)) {
.SUCCESS => {
syscall.finish();
return handle;
},
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.PROTOCOL_NOT_SUPPORTED => return syscall.fail(error.AddressFamilyUnsupported),
.NO_SUCH_FILE => return syscall.fail(error.ProtocolUnsupportedByAddressFamily),
else => |status| return syscall.unexpectedNtstatus(status),
};
}
fn bindSocketIpAfd(socket_handle: net.Socket.Handle, address: *const IpAddress, mode: windows.AFD.BIND_INFO.MODE) !IpAddress {
const Storage = extern struct { Info: windows.AFD.BIND_INFO, Address: PosixAddress };
var storage: Storage = .{ .Info = .{ .Mode = mode }, .Address = undefined };
const addr_len = addressToPosix(address, &storage.Address);
switch ((try deviceIoControl(&.{
.file = .{ .handle = socket_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.BIND,
.in = @as([]const u8, @ptrCast(&storage))[0 .. @offsetOf(Storage, "Address") + addr_len],
.out = @as([]u8, @ptrCast(&storage.Address))[0..addr_len],
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
.SHARING_VIOLATION => return error.AddressInUse,
else => |status| return windows.unexpectedStatus(status),
}
return addressFromPosix(&storage.Address);
}
fn bindSocketUnixAfd(socket_handle: net.Socket.Handle, address: *const net.UnixAddress) !void {
const Storage = extern struct { Info: windows.AFD.BIND_INFO, Address: UnixAddress };
var storage: Storage = .{ .Info = .{ .Mode = .Unix }, .Address = undefined };
const addr_len = addressUnixToPosix(address, &storage.Address);
switch ((try deviceIoControl(&.{
.file = .{ .handle = socket_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.BIND,
.in = @as([]const u8, @ptrCast(&storage))[0 .. @offsetOf(Storage, "Address") + addr_len],
.out = @ptrCast(&storage.Address),
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
.ADDRESS_ALREADY_EXISTS => return error.AddressInUse,
else => |status| return windows.unexpectedStatus(status),
}
}
fn netAcceptPosix(userdata: ?*anyopaque, listen_fd: net.Socket.Handle, options: net.Server.AcceptOptions) net.Server.AcceptError!net.Socket {
if (!have_networking) return error.NetworkDown;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
options;
var storage: PosixAddress = undefined;
var addr_len: posix.socklen_t = @sizeOf(PosixAddress);
const syscall: Syscall = try .start();
const fd = while (true) {
const rc = if (have_accept4)
posix.system.accept4(listen_fd, &storage.any, &addr_len, posix.SOCK.CLOEXEC)
else
posix.system.accept(listen_fd, &storage.any, &addr_len);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
const fd: posix.fd_t = @intCast(rc);
errdefer closeFd(fd);
if (!have_accept4) try setCloexec(fd);
break fd;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.AGAIN => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.CONNABORTED => return error.ConnectionAborted,
.FAULT => |err| return errnoBug(err),
.INVAL => return error.SocketNotListening,
.NOTSOCK => |err| return errnoBug(err),
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.OPNOTSUPP => |err| return errnoBug(err),
.PROTO => return error.ProtocolFailure,
.PERM => return error.BlockedByFirewall,
else => |err| return posix.unexpectedErrno(err),
}
},
}
};
return .{ .handle = fd, .address = addressFromPosix(&storage) };
}
fn netAcceptWindows(userdata: ?*anyopaque, listen_handle: net.Socket.Handle, options: net.Server.AcceptOptions) net.Server.AcceptError!net.Socket {
if (!have_networking) return error.NetworkDown;
const t: *Threaded = @ptrCast(@alignCast(userdata));
const Storage = extern struct {
Info: windows.AFD.LISTEN_RESPONSE_INFO,
RemoteAddress: extern union { posix: PosixAddress, unix: UnixAddress },
};
var storage: Storage = undefined;
switch ((try deviceIoControl(&.{
.file = .{ .handle = listen_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.WAIT_FOR_LISTEN,
.out = @ptrCast(&storage),
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
else => |status| return windows.unexpectedStatus(status),
}
errdefer t.deferAcceptAfd(listen_handle, storage.Info);
const accept_handle = openSocketAfd(
storage.RemoteAddress.posix.any.family,
.{ .mode = options.mode, .protocol = options.protocol },
) catch |err| switch (err) {
error.AddressFamilyUnsupported => return error.Unexpected,
error.ProtocolUnsupportedByAddressFamily => return error.Unexpected,
else => |e| return e,
};
errdefer windows.CloseHandle(accept_handle);
switch ((try deviceIoControl(&.{
.file = .{ .handle = listen_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.ACCEPT,
.in = @ptrCast(&windows.AFD.ACCEPT_INFO{
.UseSAN = .FALSE,
.Sequence = storage.Info.Sequence,
.AcceptHandle = accept_handle,
}),
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
else => |status| return windows.unexpectedStatus(status),
}
return .{ .handle = accept_handle, .address = addressFromPosix(&storage.RemoteAddress.posix) };
}
fn deferAcceptAfd(t: *Threaded, listen_handle: net.Socket.Handle, info: windows.AFD.LISTEN_RESPONSE_INFO) void {
const cancel_protection = swapCancelProtection(t, .blocked);
defer _ = swapCancelProtection(t, cancel_protection);
switch ((deviceIoControl(&.{
.file = .{ .handle = listen_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.DEFER_ACCEPT,
.in = @ptrCast(&windows.AFD.DEFER_ACCEPT_INFO{
.Sequence = info.Sequence,
.Reject = .FALSE,
}),
}) catch |err| switch (err) {
error.Canceled => unreachable, // blocked
}).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
else => |status| windows.unexpectedStatus(status) catch {},
}
}
fn netRead(socket_handle: net.Socket.Handle, data: [][]u8) net.Stream.Reader.Error!usize {
if (!have_networking) return error.NetworkDown;
if (is_windows) return netReadWindows(socket_handle, data);
return netReadPosix(socket_handle, data);
}
fn netReadPosix(fd: net.Socket.Handle, data: [][]u8) net.Stream.Reader.Error!usize {
var iovecs_buffer: [max_iovecs_len]posix.iovec = undefined;
var i: usize = 0;
for (data) |buf| {
if (iovecs_buffer.len - i == 0) break;
if (buf.len != 0) {
iovecs_buffer[i] = .{ .base = buf.ptr, .len = buf.len };
i += 1;
}
}
const dest = iovecs_buffer[0..i];
assert(dest[0].len > 0);
if (native_os == .wasi and !builtin.link_libc) {
const syscall: Syscall = try .start();
while (true) {
var n: usize = undefined;
switch (std.os.wasi.fd_read(fd, dest.ptr, dest.len, &n)) {
.SUCCESS => {
syscall.finish();
return n;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.INVAL => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.AGAIN => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTCONN => return error.SocketUnconnected,
.CONNRESET => return error.ConnectionResetByPeer,
.TIMEDOUT => return error.ConnectionTimedOut,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.readv(fd, dest.ptr, @intCast(dest.len));
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
return @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.INVAL => |err| return errnoBug(err),
.FAULT => |err| return errnoBug(err),
.AGAIN => |err| return errnoBug(err),
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTCONN => return error.SocketUnconnected,
.CONNRESET => return error.ConnectionResetByPeer,
.TIMEDOUT => return error.ConnectionTimedOut,
.PIPE => return error.SocketUnconnected,
.NETDOWN => return error.NetworkDown,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn netReadWindows(socket_handle: net.Socket.Handle, data: [][]u8) net.Stream.Reader.Error!usize {
var iovecs: [max_iovecs_len]windows.AFD.WSABUF(.@"var") = undefined;
var len: u32 = 0;
for (data) |buf| {
if (iovecs.len - len == 0) break;
addAfdBuf(.@"var", &iovecs, &len, buf);
}
const iosb = try deviceIoControl(&.{
.file = .{ .handle = socket_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.RECEIVE,
.in = @ptrCast(&windows.AFD.RECV_INFO{
.BufferArray = &iovecs,
.BufferCount = len,
.AfdFlags = .{ .NO_FAST_IO = true, .OVERLAPPED = true },
.TdiFlags = .{ .NORMAL = true },
}),
});
switch (iosb.u.Status) {
.SUCCESS => return iosb.Information,
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
.CONNECTION_RESET, .REMOTE_DISCONNECT => return error.ConnectionResetByPeer,
.IO_TIMEOUT => return error.ConnectionTimedOut,
else => |status| return windows.unexpectedStatus(status),
}
}
fn netSendPosix(
t: *Threaded,
socket_handle: net.Socket.Handle,
messages: []net.OutgoingMessage,
flags: net.SendFlags,
nonblocking: bool,
) struct { ?(net.Socket.SendError || error{WouldBlock}), usize } {
if (!have_networking) return .{ error.NetworkDown, 0 };
const posix_flags: u32 =
@as(u32, if (@hasDecl(posix.MSG, "CONFIRM") and flags.confirm) posix.MSG.CONFIRM else 0) |
@as(u32, if (@hasDecl(posix.MSG, "DONTROUTE") and flags.dont_route) posix.MSG.DONTROUTE else 0) |
@as(u32, if (@hasDecl(posix.MSG, "EOR") and flags.eor) posix.MSG.EOR else 0) |
@as(u32, if (@hasDecl(posix.MSG, "OOB") and flags.oob) posix.MSG.OOB else 0) |
@as(u32, if (@hasDecl(posix.MSG, "FASTOPEN") and flags.fastopen) posix.MSG.FASTOPEN else 0) |
@as(u32, if (@hasDecl(posix.MSG, "DONTWAIT") and nonblocking) posix.MSG.DONTWAIT else 0) |
posix.MSG.NOSIGNAL;
var i: usize = 0;
while (messages.len - i != 0) {
if (have_sendmmsg) {
i += netSendManyPosix(socket_handle, messages[i..], posix_flags) catch |err| return .{ err, i };
continue;
}
t.netSendOnePosix(socket_handle, &messages[i], posix_flags) catch |err| return .{ err, i };
i += 1;
}
return .{ null, i };
}
fn netSendWindows(
t: *Threaded,
socket_handle: net.Socket.Handle,
messages: []net.OutgoingMessage,
flags: net.SendFlags,
) struct { ?net.Socket.SendError, usize } {
if (!have_networking) return .{ error.NetworkDown, 0 };
for (messages, 0..) |*m, i| {
t.netSendOneWindows(socket_handle, m, flags) catch |err| return .{ err, i };
}
return .{ null, messages.len };
}
fn netSendOneWindows(
t: *Threaded,
socket_handle: net.Socket.Handle,
message: *net.OutgoingMessage,
flags: net.SendFlags,
) net.Socket.SendError!void {
_ = t;
_ = flags;
const iovecs: [1]windows.AFD.WSABUF(.@"const") = .{.{
.buf = message.data_ptr,
.len = std.math.cast(std.os.windows.ULONG, message.data_len) orelse
return error.MessageOversize,
}};
var storage: PosixAddress = undefined;
const addr_len = addressToPosix(message.address, &storage);
switch ((try deviceIoControl(&.{
.file = .{ .handle = socket_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.SEND_DATAGRAM,
.in = @ptrCast(&windows.AFD.SEND_DATAGRAM_INFO{
.BufferArray = &iovecs,
.BufferCount = iovecs.len,
.AfdFlags = .{ .NO_FAST_IO = true, .OVERLAPPED = true },
.TdiRequest = undefined,
.TdiConnInfo = .{
.UserDataLength = undefined,
.UserData = undefined,
.OptionsLength = undefined,
.Options = undefined,
.RemoteAddressLength = @bitCast(addr_len),
.RemoteAddress = &storage,
},
}),
})).u.Status) {
.SUCCESS => return,
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
else => |status| return windows.unexpectedStatus(status),
}
}
fn netSendOnePosix(
t: *Threaded,
socket_handle: net.Socket.Handle,
message: *net.OutgoingMessage,
flags: u32,
) (net.Socket.SendError || error{WouldBlock})!void {
_ = t;
var addr: PosixAddress = undefined;
var iovec: posix.iovec_const = .{ .base = @constCast(message.data_ptr), .len = message.data_len };
const msg: posix.msghdr_const = .{
.name = &addr.any,
.namelen = addressToPosix(message.address, &addr),
.iov = (&iovec)[0..1],
.iovlen = 1,
// OS returns EINVAL if this pointer is invalid even if controllen is zero.
.control = if (message.control.len == 0) null else @constCast(message.control.ptr),
.controllen = @intCast(message.control.len),
.flags = 0,
};
var syscall: if (is_windows) AlertableSyscall else Syscall = try .start();
while (true) {
const rc = posix.system.sendmsg(socket_handle, &msg, flags);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
message.data_len = @intCast(rc);
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.ACCES => return syscall.fail(error.AccessDenied),
.AGAIN => return syscall.fail(error.WouldBlock),
.ALREADY => return syscall.fail(error.FastOpenAlreadyInProgress),
.CONNRESET => return syscall.fail(error.ConnectionResetByPeer),
.MSGSIZE => return syscall.fail(error.MessageOversize),
.NOBUFS => return syscall.fail(error.SystemResources),
.NOMEM => return syscall.fail(error.SystemResources),
.PIPE => return syscall.fail(error.SocketUnconnected),
.AFNOSUPPORT => return syscall.fail(error.AddressFamilyUnsupported),
.HOSTUNREACH => return syscall.fail(error.HostUnreachable),
.NETUNREACH => return syscall.fail(error.NetworkUnreachable),
.NOTCONN => return syscall.fail(error.SocketUnconnected),
.TIMEDOUT => return syscall.fail(error.ConnectionTimedOut),
.NETDOWN => return syscall.fail(error.NetworkDown),
.BADF => |err| return syscall.errnoBug(err), // File descriptor used after closed.
.DESTADDRREQ => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err),
.INVAL => |err| return syscall.errnoBug(err),
.ISCONN => |err| return syscall.errnoBug(err),
.NOTSOCK => |err| return syscall.errnoBug(err),
.OPNOTSUPP => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
fn netSendManyPosix(
socket_handle: net.Socket.Handle,
messages: []net.OutgoingMessage,
flags: u32,
) (net.Socket.SendError || error{WouldBlock})!usize {
var msg_buffer: [64]posix.system.mmsghdr = undefined;
var addr_buffer: [msg_buffer.len]PosixAddress = undefined;
var iovecs_buffer: [msg_buffer.len]posix.iovec = undefined;
const min_len: usize = @min(messages.len, msg_buffer.len);
const clamped_messages = messages[0..min_len];
const clamped_msgs = (&msg_buffer)[0..min_len];
const clamped_addrs = (&addr_buffer)[0..min_len];
const clamped_iovecs = (&iovecs_buffer)[0..min_len];
for (clamped_messages, clamped_msgs, clamped_addrs, clamped_iovecs) |*message, *msg, *addr, *iovec| {
iovec.* = .{ .base = @constCast(message.data_ptr), .len = message.data_len };
msg.* = .{
.hdr = .{
.name = &addr.any,
.namelen = addressToPosix(message.address, addr),
.iov = iovec[0..1],
.iovlen = 1,
.control = @constCast(message.control.ptr),
.controllen = message.control.len,
.flags = 0,
},
.len = undefined, // Populated by calling sendmmsg below.
};
}
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.sendmmsg(socket_handle, clamped_msgs.ptr, @intCast(clamped_msgs.len), flags);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
const n: usize = @intCast(rc);
for (clamped_messages[0..n], clamped_msgs[0..n]) |*message, *msg| {
message.data_len = msg.len;
}
return n;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.ACCES => return syscall.fail(error.AccessDenied),
.AGAIN => return syscall.fail(error.WouldBlock),
.ALREADY => return syscall.fail(error.FastOpenAlreadyInProgress),
.CONNRESET => return syscall.fail(error.ConnectionResetByPeer),
.MSGSIZE => return syscall.fail(error.MessageOversize),
.NOBUFS => return syscall.fail(error.SystemResources),
.NOMEM => return syscall.fail(error.SystemResources),
.PIPE => return syscall.fail(error.SocketUnconnected),
.AFNOSUPPORT => return syscall.fail(error.AddressFamilyUnsupported),
.HOSTUNREACH => return syscall.fail(error.HostUnreachable),
.NETUNREACH => return syscall.fail(error.NetworkUnreachable),
.NOTCONN => return syscall.fail(error.SocketUnconnected),
.TIMEDOUT => return syscall.fail(error.ConnectionTimedOut),
.NETDOWN => return syscall.fail(error.NetworkDown),
.BADF => |err| return syscall.errnoBug(err), // File descriptor used after closed.
.DESTADDRREQ => |err| return syscall.errnoBug(err), // The socket is not connection-mode, and no peer address is set.
.FAULT => |err| return syscall.errnoBug(err), // An invalid user space address was specified for an argument.
.INVAL => |err| return syscall.errnoBug(err), // Invalid argument passed.
.ISCONN => |err| return syscall.errnoBug(err), // connection-mode socket was connected already but a recipient was specified
.NOTSOCK => |err| return syscall.errnoBug(err), // The file descriptor sockfd does not refer to a socket.
.OPNOTSUPP => |err| return syscall.errnoBug(err), // Some bit in the flags argument is inappropriate for the socket type.
else => |err| return syscall.unexpectedErrno(err),
}
}
}
fn netReceivePosix(
socket_handle: net.Socket.Handle,
message: *net.IncomingMessage,
data_buffer: []u8,
flags: net.ReceiveFlags,
nonblocking: bool,
) (net.Socket.ReceiveError || error{WouldBlock})!void {
// recvmmsg is useless, here's why:
// * [timeout bug](https://bugzilla.kernel.org/show_bug.cgi?id=75371)
// * it wants iovecs for each message but we have a better API: one data
// buffer to handle all the messages. The better API cannot be lowered to
// the split vectors though because reducing the buffer size might make
// some messages unreceivable.
const posix_flags: u32 =
@as(u32, if (flags.oob) posix.MSG.OOB else 0) |
@as(u32, if (flags.peek) posix.MSG.PEEK else 0) |
@as(u32, if (flags.trunc) posix.MSG.TRUNC else 0) |
posix.MSG.NOSIGNAL |
@as(u32, if (nonblocking) posix.MSG.DONTWAIT else 0);
var storage: PosixAddress = undefined;
var iov: posix.iovec = .{ .base = data_buffer.ptr, .len = data_buffer.len };
var msg: posix.msghdr = .{
.name = &storage.any,
.namelen = @sizeOf(PosixAddress),
.iov = (&iov)[0..1],
.iovlen = 1,
.control = message.control.ptr,
.controllen = @intCast(message.control.len),
.flags = undefined,
};
const syscall = try Syscall.start();
while (true) {
const rc = posix.system.recvmsg(socket_handle, &msg, posix_flags);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
const data = data_buffer[0..@intCast(rc)];
message.* = .{
.from = addressFromPosix(&storage),
.data = data,
.control = if (msg.control) |ptr| @as([*]u8, @ptrCast(ptr))[0..msg.controllen] else message.control,
.flags = .{
.eor = (msg.flags & posix.MSG.EOR) != 0,
.trunc = (msg.flags & posix.MSG.TRUNC) != 0,
.ctrunc = (msg.flags & posix.MSG.CTRUNC) != 0,
.oob = (msg.flags & posix.MSG.OOB) != 0,
.errqueue = if (@hasDecl(posix.MSG, "ERRQUEUE")) (msg.flags & posix.MSG.ERRQUEUE) != 0 else false,
},
};
return;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.NFILE => return syscall.fail(error.SystemFdQuotaExceeded),
.MFILE => return syscall.fail(error.ProcessFdQuotaExceeded),
.NOBUFS => return syscall.fail(error.SystemResources),
.NOMEM => return syscall.fail(error.SystemResources),
.NOTCONN => return syscall.fail(error.SocketUnconnected),
.MSGSIZE => return syscall.fail(error.MessageOversize),
.PIPE => return syscall.fail(error.SocketUnconnected),
.CONNRESET => return syscall.fail(error.ConnectionResetByPeer),
.TIMEDOUT => return syscall.fail(error.ConnectionTimedOut),
.NETDOWN => return syscall.fail(error.NetworkDown),
.AGAIN => return syscall.fail(error.WouldBlock),
.BADF => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err),
.INVAL => |err| return syscall.errnoBug(err),
.NOTSOCK => |err| return syscall.errnoBug(err),
.OPNOTSUPP => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
fn netReceiveWindows(
t: *Threaded,
socket_handle: net.Socket.Handle,
message_buffer: []net.IncomingMessage,
data_buffer: []u8,
flags: net.ReceiveFlags,
) struct { ?net.Socket.ReceiveError, usize } {
t.netReceiveOneWindows(socket_handle, &message_buffer[0], data_buffer, flags) catch |err|
return .{ err, 0 };
return .{ null, 1 };
}
fn netReceiveOneWindows(
t: *Threaded,
socket_handle: net.Socket.Handle,
message: *net.IncomingMessage,
data_buffer: []u8,
flags: net.ReceiveFlags,
) net.Socket.ReceiveError!void {
if (!have_networking) return error.NetworkDown;
_ = t;
const iovecs: [1]windows.AFD.WSABUF(.@"var") = .{.{
.buf = data_buffer.ptr,
.len = std.math.cast(std.os.windows.ULONG, data_buffer.len) orelse return error.MessageOversize,
}};
var storage: PosixAddress = undefined;
var addr_len: windows.ULONG = @sizeOf(PosixAddress);
const iosb = try deviceIoControl(&.{
.file = .{ .handle = socket_handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.RECEIVE_DATAGRAM,
.in = @ptrCast(&windows.AFD.RECV_DATAGRAM_INFO{
.BufferArray = &iovecs,
.BufferCount = iovecs.len,
.AfdFlags = .{ .NO_FAST_IO = true, .OVERLAPPED = true },
.TdiFlags = .{ .NORMAL = !flags.oob, .EXPEDITED = flags.oob, .PEEK = flags.peek },
.Address = &storage,
.AddressLength = &addr_len,
}),
});
switch (iosb.u.Status) {
.SUCCESS, .RECEIVE_EXPEDITED => |status| message.* = .{
.from = addressFromPosix(&storage),
.data = data_buffer[0..iosb.Information],
.control = &.{},
.flags = .{
.eor = false,
.trunc = false,
.ctrunc = false,
.oob = switch (status) {
else => unreachable,
.SUCCESS, .RECEIVE_PARTIAL, .BUFFER_OVERFLOW => false,
.RECEIVE_EXPEDITED, .RECEIVE_PARTIAL_EXPEDITED => true,
},
.errqueue = false,
},
},
.RECEIVE_PARTIAL,
.RECEIVE_PARTIAL_EXPEDITED,
=> |status| return windows.unexpectedStatus(status), // TdiFlags.PARTIAL = false
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
.BUFFER_OVERFLOW => return error.MessageOversize,
.PORT_UNREACHABLE => return error.PortUnreachable,
else => |status| return windows.unexpectedStatus(status),
}
}
fn netWritePosix(
fd: net.Socket.Handle,
header: []const u8,
data: []const []const u8,
splat: usize,
) net.Stream.Writer.Error!usize {
if (!have_networking) return error.NetworkDown;
var iovecs: [max_iovecs_len]posix.iovec_const = undefined;
var msg: posix.msghdr_const = .{
.name = null,
.namelen = 0,
.iov = &iovecs,
.iovlen = 0,
.control = null,
.controllen = 0,
.flags = 0,
};
addBuf(&iovecs, &msg.iovlen, header);
for (data[0 .. data.len - 1]) |bytes| addBuf(&iovecs, &msg.iovlen, bytes);
const pattern = data[data.len - 1];
var splat_backup_buffer: [splat_buffer_size]u8 = undefined;
if (iovecs.len - msg.iovlen != 0) switch (splat) {
0 => {},
1 => addBuf(&iovecs, &msg.iovlen, pattern),
else => switch (pattern.len) {
0 => {},
1 => {
const splat_buffer = &splat_backup_buffer;
const memset_len = @min(splat_buffer.len, splat);
const buf = splat_buffer[0..memset_len];
@memset(buf, pattern[0]);
addBuf(&iovecs, &msg.iovlen, buf);
var remaining_splat = splat - buf.len;
while (remaining_splat > splat_buffer.len and iovecs.len - msg.iovlen != 0) {
assert(buf.len == splat_buffer.len);
addBuf(&iovecs, &msg.iovlen, splat_buffer);
remaining_splat -= splat_buffer.len;
}
addBuf(&iovecs, &msg.iovlen, splat_buffer[0..@min(remaining_splat, splat_buffer.len)]);
},
else => for (0..@min(splat, iovecs.len - msg.iovlen)) |_| {
addBuf(&iovecs, &msg.iovlen, pattern);
},
},
};
const flags = posix.MSG.NOSIGNAL;
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.sendmsg(fd, &msg, flags);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
return @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.ACCES => |err| return errnoBug(err),
.AGAIN => |err| return errnoBug(err),
.ALREADY => return error.FastOpenAlreadyInProgress,
.BADF => |err| return errnoBug(err), // File descriptor used after closed.
.CONNRESET => return error.ConnectionResetByPeer,
.DESTADDRREQ => |err| return errnoBug(err), // The socket is not connection-mode, and no peer address is set.
.FAULT => |err| return errnoBug(err), // An invalid user space address was specified for an argument.
.INVAL => |err| return errnoBug(err), // Invalid argument passed.
.ISCONN => |err| return errnoBug(err), // connection-mode socket was connected already but a recipient was specified
.MSGSIZE => |err| return errnoBug(err),
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTSOCK => |err| return errnoBug(err), // The file descriptor sockfd does not refer to a socket.
.OPNOTSUPP => |err| return errnoBug(err), // Some bit in the flags argument is inappropriate for the socket type.
.PIPE => return error.SocketUnconnected,
.AFNOSUPPORT => return error.AddressFamilyUnsupported,
.HOSTUNREACH => return error.HostUnreachable,
.NETUNREACH => return error.NetworkUnreachable,
.NOTCONN => return error.SocketUnconnected,
.TIMEDOUT => return error.ConnectionTimedOut,
.NETDOWN => return error.NetworkDown,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn netWriteWindows(
handle: net.Socket.Handle,
header: []const u8,
data: []const []const u8,
splat: usize,
) net.Stream.Writer.Error!usize {
if (!have_networking) return error.NetworkDown;
var iovecs: [max_iovecs_len]windows.AFD.WSABUF(.@"const") = undefined;
var len: u32 = 0;
addAfdBuf(.@"const", &iovecs, &len, header);
for (data[0 .. data.len - 1]) |bytes| addAfdBuf(.@"const", &iovecs, &len, bytes);
const pattern = data[data.len - 1];
var backup_buffer: [64]u8 = undefined;
if (iovecs.len - len != 0) switch (splat) {
0 => {},
1 => addAfdBuf(.@"const", &iovecs, &len, pattern),
else => switch (pattern.len) {
0 => {},
1 => {
const splat_buffer = &backup_buffer;
const memset_len = @min(splat_buffer.len, splat);
const buf = splat_buffer[0..memset_len];
@memset(buf, pattern[0]);
addAfdBuf(.@"const", &iovecs, &len, buf);
var remaining_splat = splat - buf.len;
while (remaining_splat > splat_buffer.len and len < iovecs.len) {
addAfdBuf(.@"const", &iovecs, &len, splat_buffer);
remaining_splat -= splat_buffer.len;
}
addAfdBuf(.@"const", &iovecs, &len, splat_buffer[0..@min(remaining_splat, splat_buffer.len)]);
},
else => for (0..@min(splat, iovecs.len - len)) |_| {
addAfdBuf(.@"const", &iovecs, &len, pattern);
},
},
};
const iosb = try deviceIoControl(&.{
.file = .{ .handle = handle, .flags = .{ .nonblocking = true } },
.code = windows.IOCTL.AFD.SEND,
.in = @ptrCast(&windows.AFD.SEND_INFO{
.BufferArray = &iovecs,
.BufferCount = len,
.AfdFlags = .{ .NO_FAST_IO = true, .OVERLAPPED = true },
.TdiFlags = .{},
}),
});
switch (iosb.u.Status) {
.SUCCESS => return iosb.Information,
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
.CONNECTION_RESET, .REMOTE_DISCONNECT => return error.ConnectionResetByPeer,
.IO_TIMEOUT => return error.ConnectionTimedOut,
else => |status| return windows.unexpectedStatus(status),
}
}
fn addAfdBuf(
comptime mutability: windows.AFD.Mutability,
iovecs: []windows.AFD.WSABUF(mutability),
len: *u32,
bytes: switch (mutability) {
.@"const" => []const u8,
.@"var" => []u8,
},
) void {
if (bytes.len == 0) return;
const cap = std.math.maxInt(u32);
var remaining = bytes;
while (remaining.len > cap) {
if (iovecs.len - len.* == 0) return;
iovecs[len.*] = .{ .buf = remaining.ptr, .len = cap };
len.* += 1;
remaining = remaining[cap..];
} else {
@branchHint(.likely);
if (iovecs.len - len.* == 0) return;
iovecs[len.*] = .{ .buf = remaining.ptr, .len = @intCast(remaining.len) };
len.* += 1;
}
}
/// This is either usize or u32. Since, either is fine, let's use the same
/// `addBuf` function for both writing to a file and sending network messages.
const iovlen_t = switch (native_os) {
.wasi => u32,
else => @FieldType(posix.msghdr_const, "iovlen"),
};
fn addBuf(v: []posix.iovec_const, i: *iovlen_t, bytes: []const u8) void {
// OS checks ptr addr before length so zero length vectors must be omitted.
if (bytes.len == 0) return;
if (v.len - i.* == 0) return;
v[i.*] = .{ .base = bytes.ptr, .len = bytes.len };
i.* += 1;
}
fn netClose(userdata: ?*anyopaque, sockets: []const net.Socket) void {
if (!have_networking) unreachable;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
for (sockets) |socket| switch (native_os) {
.windows => windows.CloseHandle(socket.handle),
else => closeFd(socket.handle),
};
}
fn netShutdownPosix(userdata: ?*anyopaque, handle: net.Socket.Handle, how: net.ShutdownHow) net.ShutdownError!void {
if (!have_networking) return error.NetworkDown;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const posix_how: i32 = switch (how) {
.recv => posix.SHUT.RD,
.send => posix.SHUT.WR,
.both => posix.SHUT.RDWR,
};
const syscall: Syscall = try .start();
while (true) {
switch (posix.errno(posix.system.shutdown(handle, posix_how))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
switch (e) {
.BADF, .NOTSOCK, .INVAL => |err| return errnoBug(err),
.NOTCONN => return error.SocketUnconnected,
.NOBUFS => return error.SystemResources,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
}
fn netShutdownWindows(userdata: ?*anyopaque, handle: net.Socket.Handle, how: net.ShutdownHow) net.ShutdownError!void {
if (!have_networking) return error.NetworkDown;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
// shutdown does not support apcs at all
switch ((try deviceIoControl(&.{
.file = .{ .handle = handle, .flags = .{ .nonblocking = false } },
.code = windows.IOCTL.AFD.PARTIAL_DISCONNECT,
.in = @ptrCast(&windows.AFD.PARTIAL_DISCONNECT_INFO{
.DisconnectMode = .{ .SEND = how != .recv, .RECEIVE = how != .send },
.Timeout = -1,
}),
})).u.Status) {
.SUCCESS => {},
.CANCELLED => unreachable,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
else => |status| return windows.unexpectedStatus(status),
}
}
fn netInterfaceNameResolve(
userdata: ?*anyopaque,
name: *const net.Interface.Name,
) net.Interface.Name.ResolveError!net.Interface {
if (!have_networking) return error.InterfaceNotFound;
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (native_os == .linux) {
const sock_fd = openSocketPosix(posix.AF.UNIX, .{ .mode = .dgram }) catch |err| switch (err) {
error.ProcessFdQuotaExceeded => return error.SystemResources,
error.SystemFdQuotaExceeded => return error.SystemResources,
error.AddressFamilyUnsupported => return error.Unexpected,
error.ProtocolUnsupportedBySystem => return error.Unexpected,
error.ProtocolUnsupportedByAddressFamily => return error.Unexpected,
error.SocketModeUnsupported => return error.Unexpected,
error.OptionUnsupported => return error.Unexpected,
else => |e| return e,
};
defer closeFd(sock_fd);
var ifr: posix.ifreq = .{
.ifrn = .{ .name = @bitCast(name.bytes) },
.ifru = undefined,
};
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.ioctl(sock_fd, posix.SIOCGIFINDEX, @intFromPtr(&ifr)))) {
.SUCCESS => {
syscall.finish();
return .{ .index = @bitCast(ifr.ifru.ivalue) };
},
.INTR => {
try syscall.checkCancel();
continue;
},
.NODEV => return syscall.fail(error.InterfaceNotFound),
else => |err| return syscall.unexpectedErrno(err),
};
}
if (is_windows) {
var ConvertInterfaceNameToLuidW = t.dl.ConvertInterfaceNameToLuidW.load(.acquire);
var ConvertInterfaceLuidToIndex = t.dl.ConvertInterfaceLuidToIndex.load(.acquire);
if (ConvertInterfaceNameToLuidW == null or ConvertInterfaceLuidToIndex == null) {
const iphlpapi_dll = t.dl.iphlpapi_dll.load(.acquire) orelse iphlpapi_dll: {
try Thread.checkCancel();
var iphlpapi_dll: *anyopaque = undefined;
switch (windows.ntdll.LdrLoadDll(null, null, &.init(
&.{ 'I', 'P', 'H', 'L', 'P', 'A', 'P', 'I', '.', 'D', 'L', 'L' },
), &iphlpapi_dll)) {
.SUCCESS => {},
.DLL_NOT_FOUND => return error.Unexpected,
else => |status| return windows.unexpectedStatus(status),
}
const handle = t.dl.iphlpapi_dll.cmpxchgStrong(null, iphlpapi_dll, .release, .monotonic) orelse
break :iphlpapi_dll iphlpapi_dll;
switch (windows.ntdll.LdrUnloadDll(iphlpapi_dll)) {
.SUCCESS => break :iphlpapi_dll handle.?,
else => |status| return windows.unexpectedStatus(status),
}
};
switch (windows.ntdll.LdrGetProcedureAddress(iphlpapi_dll, &.init(
&.{
'C', 'o', 'n', 'v', 'e', 'r', 't', 'I', 'n', 't', 'e', 'r', 'f', 'a', 'c', 'e',
'N', 'a', 'm', 'e', 'T', 'o', 'L', 'u', 'i', 'd', 'W',
},
), 0, @ptrCast(&ConvertInterfaceNameToLuidW))) {
.SUCCESS => t.dl.ConvertInterfaceNameToLuidW.store(ConvertInterfaceNameToLuidW, .release),
else => |status| return windows.unexpectedStatus(status),
}
switch (windows.ntdll.LdrGetProcedureAddress(iphlpapi_dll, &.init(
&.{
'C', 'o', 'n', 'v', 'e', 'r', 't', 'I', 'n', 't', 'e', 'r', 'f', 'a', 'c', 'e',
'L', 'u', 'i', 'd', 'T', 'o', 'I', 'n', 'd', 'e', 'x',
},
), 0, @ptrCast(&ConvertInterfaceLuidToIndex))) {
.SUCCESS => t.dl.ConvertInterfaceLuidToIndex.store(ConvertInterfaceLuidToIndex, .release),
else => |status| return windows.unexpectedStatus(status),
}
}
try Thread.checkCancel();
var name_w: [net.Interface.Name.max_len:0]windows.WCHAR = undefined;
name_w[
std.unicode.wtf8ToWtf16Le(&name_w, name.toSlice()) catch |err| switch (err) {
error.InvalidWtf8 => return error.InterfaceNotFound,
}
] = 0;
var luid: windows.NET.LUID = undefined;
switch (ConvertInterfaceNameToLuidW.?(&name_w, &luid)) {
.SUCCESS => {},
.INVALID_NAME => return error.InterfaceNotFound,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
var index: windows.NET.IFINDEX = undefined;
switch (ConvertInterfaceLuidToIndex.?(&luid, &index)) {
.SUCCESS => {},
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
return .{ .index = @backingInt(index) };
}
if (builtin.link_libc) {
try Thread.checkCancel();
const index = std.c.if_nametoindex(&name.bytes);
if (index == 0) return error.InterfaceNotFound;
return .{ .index = @bitCast(index) };
}
@panic("unimplemented");
}
fn netInterfaceName(userdata: ?*anyopaque, interface: net.Interface) net.Interface.NameError!net.Interface.Name {
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (native_os == .linux) {
try Thread.checkCancel();
@panic("TODO implement netInterfaceName for linux");
}
if (is_windows) {
var ConvertInterfaceIndexToLuid = t.dl.ConvertInterfaceIndexToLuid.load(.acquire);
var ConvertInterfaceLuidToNameW = t.dl.ConvertInterfaceLuidToNameW.load(.acquire);
if (ConvertInterfaceIndexToLuid == null or ConvertInterfaceLuidToNameW == null) {
const iphlpapi_dll = t.dl.iphlpapi_dll.load(.acquire) orelse iphlpapi_dll: {
try Thread.checkCancel();
var iphlpapi_dll: *anyopaque = undefined;
switch (windows.ntdll.LdrLoadDll(null, null, &.init(
&.{ 'I', 'P', 'H', 'L', 'P', 'A', 'P', 'I', '.', 'D', 'L', 'L' },
), &iphlpapi_dll)) {
.SUCCESS => {},
.DLL_NOT_FOUND => return error.Unexpected,
else => |status| return windows.unexpectedStatus(status),
}
const handle = t.dl.iphlpapi_dll.cmpxchgStrong(null, iphlpapi_dll, .release, .monotonic) orelse
break :iphlpapi_dll iphlpapi_dll;
switch (windows.ntdll.LdrUnloadDll(iphlpapi_dll)) {
.SUCCESS => break :iphlpapi_dll handle.?,
else => |status| return windows.unexpectedStatus(status),
}
};
switch (windows.ntdll.LdrGetProcedureAddress(iphlpapi_dll, &.init(
&.{
'C', 'o', 'n', 'v', 'e', 'r', 't', 'I', 'n', 't', 'e', 'r', 'f', 'a', 'c', 'e',
'I', 'n', 'd', 'e', 'x', 'T', 'o', 'L', 'u', 'i', 'd',
},
), 0, @ptrCast(&ConvertInterfaceIndexToLuid))) {
.SUCCESS => t.dl.ConvertInterfaceIndexToLuid.store(ConvertInterfaceIndexToLuid, .release),
else => |status| return windows.unexpectedStatus(status),
}
switch (windows.ntdll.LdrGetProcedureAddress(iphlpapi_dll, &.init(
&.{
'C', 'o', 'n', 'v', 'e', 'r', 't', 'I', 'n', 't', 'e', 'r', 'f', 'a', 'c', 'e',
'L', 'u', 'i', 'd', 'T', 'o', 'N', 'a', 'm', 'e', 'W',
},
), 0, @ptrCast(&ConvertInterfaceLuidToNameW))) {
.SUCCESS => t.dl.ConvertInterfaceLuidToNameW.store(ConvertInterfaceLuidToNameW, .release),
else => |status| return windows.unexpectedStatus(status),
}
}
try Thread.checkCancel();
var luid: windows.NET.LUID = undefined;
switch (ConvertInterfaceIndexToLuid.?(@fromBackingInt(@intCast(interface.index)), &luid)) {
.SUCCESS => {},
.FILE_NOT_FOUND => return error.InterfaceNotFound,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
var name_w: [net.Interface.Name.max_len:0]windows.WCHAR = undefined;
switch (ConvertInterfaceLuidToNameW.?(&luid, &name_w, name_w.len)) {
.SUCCESS => {},
.INVALID_PARAMETER => unreachable,
.NOT_ENOUGH_MEMORY => return error.NameTooLong,
else => |err| return windows.unexpectedError(err),
}
var name: [3 * net.Interface.Name.max_len]u8 = undefined;
return .fromSlice(name[0..std.unicode.wtf16LeToWtf8(&name, std.mem.sliceTo(&name_w, 0))]);
}
if (builtin.link_libc) {
try Thread.checkCancel();
@panic("TODO implement netInterfaceName for libc");
}
@panic("unimplemented");
}
fn netLookup(
userdata: ?*anyopaque,
host_name: HostName,
resolved: *Io.Queue(HostName.LookupResult),
options: HostName.LookupOptions,
) net.HostName.LookupError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
defer resolved.close(io(t));
t.netLookupFallible(host_name, resolved, options) catch |err| switch (err) {
error.Closed => unreachable, // `resolved` must not be closed until `netLookup` returns
else => |e| return e,
};
}
fn netLookupFallible(
t: *Threaded,
host_name: HostName,
resolved: *Io.Queue(HostName.LookupResult),
options: HostName.LookupOptions,
) (net.HostName.LookupError || Io.QueueClosedError)!void {
if (!have_networking) return error.NetworkDown;
const t_io = t.io();
const name = host_name.bytes;
assert(name.len <= HostName.max_len);
// On Linux, glibc provides getaddrinfo_a which is capable of supporting our semantics.
// However, musl's POSIX-compliant getaddrinfo is not, so we bypass it.
const is_glibc = builtin.link_libc and builtin.target.isGnuLibC();
if (is_glibc) {
// TODO use getaddrinfo_a / gai_cancel
}
// On Linux, we have to go through glibc because of the Name Service Switch feature.
const non_glibc_linux = native_os == .linux and !is_glibc;
if (non_glibc_linux or is_windows) {
if (IpAddress.parseIp6(name, options.port)) |addr| {
if (options.family == .ip4) return error.UnknownHostName;
if (copyCanon(options.canonical_name_buffer, name)) |canon| {
try resolved.putAll(t_io, &.{
.{ .address = addr },
.{ .canonical_name = canon },
});
} else {
try resolved.putOne(t_io, .{ .address = addr });
}
return;
} else |_| {}
if (IpAddress.parseIp4(name, options.port)) |addr| {
if (options.family == .ip6) return error.UnknownHostName;
if (copyCanon(options.canonical_name_buffer, name)) |canon| {
try resolved.putAll(t_io, &.{
.{ .address = addr },
.{ .canonical_name = canon },
});
} else {
try resolved.putOne(t_io, .{ .address = addr });
}
return;
} else |_| {}
if (t.lookupHosts(host_name, resolved, options)) return else |err| switch (err) {
error.UnknownHostName => {},
else => |e| return e,
}
// RFC 6761 Section 6.3.3
// Name resolution APIs and libraries SHOULD recognize
// localhost names as special and SHOULD always return the IP
// loopback address for address queries and negative responses
// for all other query types.
// Check for equal to "localhost(.)" or ends in ".localhost(.)"
const localhost = if (name[name.len - 1] == '.') "localhost." else "localhost";
if (std.mem.endsWith(u8, name, localhost) and
(name.len == localhost.len or name[name.len - localhost.len - 1] == '.'))
{
var results_buffer: [3]HostName.LookupResult = undefined;
var results_index: usize = 0;
if (options.family != .ip4) {
results_buffer[results_index] = .{ .address = .{ .ip6 = .loopback(options.port) } };
results_index += 1;
}
if (options.family != .ip6) {
results_buffer[results_index] = .{ .address = .{ .ip4 = .loopback(options.port) } };
results_index += 1;
}
if (options.canonical_name_buffer) |buf| {
const canon_name = "localhost";
const canon_name_dest = buf[0..canon_name.len];
canon_name_dest.* = canon_name.*;
results_buffer[results_index] = .{ .canonical_name = .{ .bytes = canon_name_dest } };
results_index += 1;
}
try resolved.putAll(t_io, results_buffer[0..results_index]);
return;
}
if (native_os == .linux) return t.lookupDnsSearch(host_name, resolved, options);
comptime assert(is_windows);
var DnsQueryEx = t.dl.DnsQueryEx.load(.acquire);
//var DnsCancelQuery = t.dl.DnsCancelQuery.load(.acquire);
var DnsFree = t.dl.DnsFree.load(.acquire);
if (DnsQueryEx == null or
//DnsCancelQuery == null or
DnsFree == null)
{
const dnsapi_dll = t.dl.dnsapi_dll.load(.acquire) orelse dnsapi_dll: {
try Thread.checkCancel();
var dnsapi_dll: *anyopaque = undefined;
switch (windows.ntdll.LdrLoadDll(null, null, &.init(
&.{ 'd', 'n', 's', 'a', 'p', 'i', '.', 'd', 'l', 'l' },
), &dnsapi_dll)) {
.SUCCESS => {},
.DLL_NOT_FOUND => return error.Unexpected,
else => |status| return windows.unexpectedStatus(status),
}
const handle = t.dl.dnsapi_dll.cmpxchgStrong(null, dnsapi_dll, .release, .monotonic) orelse
break :dnsapi_dll dnsapi_dll;
switch (windows.ntdll.LdrUnloadDll(dnsapi_dll)) {
.SUCCESS => break :dnsapi_dll handle.?,
else => |status| return windows.unexpectedStatus(status),
}
};
switch (windows.ntdll.LdrGetProcedureAddress(dnsapi_dll, &.init(
&.{ 'D', 'n', 's', 'Q', 'u', 'e', 'r', 'y', 'E', 'x' },
), 0, @ptrCast(&DnsQueryEx))) {
.SUCCESS => t.dl.DnsQueryEx.store(DnsQueryEx, .release),
else => |status| return windows.unexpectedStatus(status),
}
//switch (windows.ntdll.LdrGetProcedureAddress(dnsapi_dll, &.init(
// &.{ 'D', 'n', 's', 'C', 'a', 'n', 'c', 'e', 'l', 'Q', 'u', 'e', 'r', 'y' },
//), 0, @ptrCast(&DnsCancelQuery))) {
// .SUCCESS => t.dl.DnsCancelQuery.store(DnsCancelQuery, .release),
// else => |status| return windows.unexpectedStatus(status),
//}
switch (windows.ntdll.LdrGetProcedureAddress(dnsapi_dll, &.init(
&.{ 'D', 'n', 's', 'F', 'r', 'e', 'e' },
), 0, @ptrCast(&DnsFree))) {
.SUCCESS => t.dl.DnsFree.store(DnsFree, .release),
else => |status| return windows.unexpectedStatus(status),
}
}
try Thread.checkCancel();
const current_thread = Thread.current;
var lookup_dns: LookupDnsWindows = .{
.threaded = t,
.thread = if (current_thread) |thread| thread.handle else undefined,
.resolved = resolved,
.options = options,
.results = .{
.Version = 1,
.QueryStatus = undefined,
.QueryOptions = undefined,
.pQueryRecords = undefined,
.Reserved = undefined,
},
.done = false,
};
var host_name_w: [HostName.max_len:0]windows.WCHAR = undefined;
host_name_w[
std.unicode.wtf8ToWtf16Le(&host_name_w, name) catch |err| switch (err) {
error.InvalidWtf8 => return error.UnknownHostName,
}
] = 0;
//var cancel_token: windows.DNS.QUERY.CANCEL = undefined;
// Workaround various bugs by attempting a synchronous non-wire query first
switch (DnsQueryEx.?(&.{
.Version = 1,
.QueryName = &host_name_w,
.QueryType = if (options.family == .ip4) .A else .AAAA,
.QueryOptions = .{
.NO_WIRE_QUERY = true,
.NO_HOSTS_FILE = true, // handled above
.ADDRCONFIG = true,
.DUAL_ADDR = options.family == null,
},
}, &lookup_dns.results, null)) {
.SUCCESS => try lookup_dns.completedFallible(),
// We must wait for the APC routine.
.DNS_REQUEST_PENDING => unreachable, // `pQueryCompletionCallback` was `null`
.DNS_ERROR_RECORD_DOES_NOT_EXIST => switch (DnsQueryEx.?(&.{
.Version = 1,
.QueryName = &host_name_w,
.QueryType = if (options.family == .ip4) .A else .AAAA,
.QueryOptions = .{
.NO_HOSTS_FILE = true, // handled above
.ADDRCONFIG = true,
.DUAL_ADDR = options.family == null,
.MULTICAST_WAIT = true,
},
.pQueryCompletionCallback = if (current_thread) |_| &LookupDnsWindows.completed else null,
}, &lookup_dns.results,
//&cancel_token,
null)) {
.SUCCESS => try lookup_dns.completedFallible(),
// We must wait for the APC routine.
.DNS_REQUEST_PENDING => {
assert(current_thread != null); // `pQueryCompletionCallback` was `null`
while (!@atomicLoad(bool, &lookup_dns.done, .acquire)) {
// Once we get here we must not return from the function until the
// operation completes, thereby releasing references to `host_name_w`,
// `lookup_dns.results`, and `cancel_token`.
const alertable_syscall = AlertableSyscall.start() catch |err| switch (err) {
error.Canceled => |e| {
//_ = DnsCancelQuery.?(&cancel_token);
while (!@atomicLoad(bool, &lookup_dns.done, .acquire)) waitForApcOrAlert();
return e;
},
};
waitForApcOrAlert();
alertable_syscall.finish();
}
},
else => |status| lookup_dns.results.QueryStatus = status,
},
else => |status| lookup_dns.results.QueryStatus = status,
}
switch (lookup_dns.results.QueryStatus) {
.SUCCESS => return,
.DNS_REQUEST_PENDING => unreachable, // already handled
.INVALID_NAME,
.DNS_ERROR_RCODE_NAME_ERROR,
.DNS_INFO_NO_RECORDS,
.DNS_ERROR_INVALID_NAME_CHAR,
.DNS_ERROR_RECORD_DOES_NOT_EXIST,
=> return error.UnknownHostName,
.TIMEOUT => return error.NameServerFailure,
else => |err| return windows.unexpectedError(err),
}
}
if (native_os == .openbsd) {
// TODO use getaddrinfo_async / asr_abort
}
if (native_os == .freebsd) {
// TODO use dnsres_getaddrinfo
}
if (is_darwin) {
// TODO use CFHostStartInfoResolution / CFHostCancelInfoResolution
}
if (builtin.link_libc) {
// This operating system lacks a way to resolve asynchronously. We are
// stuck with getaddrinfo.
var name_buffer: [HostName.max_len:0]u8 = undefined;
@memcpy(name_buffer[0..name.len], name);
name_buffer[name.len] = 0;
const name_c = name_buffer[0..name.len :0];
var port_buffer: [8]u8 = undefined;
const port_c = std.mem.printSentinel(&port_buffer, "{d}", .{options.port}, 0) catch unreachable;
const family: i32 = if (options.family) |f| switch (f) {
.ip4 => posix.AF.INET,
.ip6 => posix.AF.INET6,
} else posix.AF.UNSPEC;
const hints: posix.addrinfo = .{
.flags = .{ .CANONNAME = options.canonical_name_buffer != null, .NUMERICSERV = true },
.family = family,
.socktype = posix.SOCK.STREAM,
.protocol = posix.IPPROTO.TCP,
.canonname = null,
.addr = null,
.addrlen = 0,
.next = null,
};
var res: ?*posix.addrinfo = null;
const syscall: Syscall = try .start();
while (true) {
switch (posix.system.getaddrinfo(name_c.ptr, port_c.ptr, &hints, &res)) {
@as(posix.system.EAI, @fromBackingInt(@intCast(0))) => {
syscall.finish();
break;
},
.SYSTEM => switch (posix.errno(-1)) {
.INTR => {
try syscall.checkCancel();
continue;
},
else => |e| {
syscall.finish();
return posix.unexpectedErrno(e);
},
},
else => |e| {
syscall.finish();
switch (e) {
.ADDRFAMILY => return error.AddressFamilyUnsupported,
.AGAIN => return error.NameServerFailure,
.FAIL => return error.NameServerFailure,
.FAMILY => return error.AddressFamilyUnsupported,
.MEMORY => return error.SystemResources,
.NODATA => return error.UnknownHostName,
.NONAME => return error.UnknownHostName,
else => return error.Unexpected,
}
},
}
}
defer if (res) |some| posix.system.freeaddrinfo(some);
var it = res;
var canon_name: ?[*:0]const u8 = null;
while (it) |info| : (it = info.next) {
const addr = info.addr orelse continue;
try resolved.putOne(t_io, .{ .address = addressFromPosix(@alignCast(@fieldParentPtr("any", addr))) });
if (info.canonname) |n| {
if (canon_name == null) {
canon_name = n;
}
}
}
if (canon_name) |n| {
if (copyCanon(options.canonical_name_buffer, std.mem.sliceTo(n, 0))) |canon| {
try resolved.putOne(t_io, .{ .canonical_name = canon });
}
}
return;
}
return error.OptionUnsupported;
}
fn lockStderr(userdata: ?*anyopaque, terminal_mode: ?Io.Terminal.Mode) Io.Cancelable!Io.LockedStderr {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const current_thread_id = Thread.currentId();
if (@atomicLoad(std.Thread.Id, &t.stderr_mutex_locker, .unordered) != current_thread_id) {
mutexLock(&t.stderr_mutex);
assert(t.stderr_mutex_lock_count == 0);
@atomicStore(std.Thread.Id, &t.stderr_mutex_locker, current_thread_id, .unordered);
}
t.stderr_mutex_lock_count += 1;
return initLockedStderr(t, terminal_mode);
}
fn tryLockStderr(userdata: ?*anyopaque, terminal_mode: ?Io.Terminal.Mode) Io.Cancelable!?Io.LockedStderr {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const current_thread_id = Thread.currentId();
if (@atomicLoad(std.Thread.Id, &t.stderr_mutex_locker, .unordered) != current_thread_id) {
if (!t.stderr_mutex.tryLock()) return null;
assert(t.stderr_mutex_lock_count == 0);
@atomicStore(std.Thread.Id, &t.stderr_mutex_locker, current_thread_id, .unordered);
}
t.stderr_mutex_lock_count += 1;
return try initLockedStderr(t, terminal_mode);
}
fn initLockedStderr(t: *Threaded, terminal_mode: ?Io.Terminal.Mode) Io.Cancelable!Io.LockedStderr {
if (!t.stderr_writer_initialized) {
const io_t = io(t);
if (is_windows) t.stderr_writer.file = .stderr();
t.stderr_writer.io = io_t;
t.stderr_writer_initialized = true;
t.scanEnviron();
const NO_COLOR = t.environ.exist.NO_COLOR;
const CLICOLOR_FORCE = t.environ.exist.CLICOLOR_FORCE;
t.stderr_mode = terminal_mode orelse try .detect(io_t, t.stderr_writer.file, NO_COLOR, CLICOLOR_FORCE);
}
return .{
.file_writer = &t.stderr_writer,
.terminal_mode = terminal_mode orelse t.stderr_mode,
};
}
fn unlockStderr(userdata: ?*anyopaque) void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (t.stderr_writer.err == null) t.stderr_writer.interface.flush() catch {};
if (t.stderr_writer.err) |err| {
switch (err) {
error.Canceled => recancelInner(),
else => {},
}
t.stderr_writer.err = null;
}
t.stderr_writer.interface.end = 0;
t.stderr_writer.interface.buffer = &.{};
t.stderr_mutex_lock_count -= 1;
if (t.stderr_mutex_lock_count == 0) {
@atomicStore(std.Thread.Id, &t.stderr_mutex_locker, Thread.invalid_id, .unordered);
mutexUnlock(&t.stderr_mutex);
}
}
fn processCurrentPath(userdata: ?*anyopaque, buffer: []u8) process.CurrentPathError!usize {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (is_windows) {
var wtf16le_buf: [windows.PATH_MAX_WIDE:0]u16 = undefined;
const n = windows.ntdll.RtlGetCurrentDirectory_U(wtf16le_buf.len * 2 + 2, &wtf16le_buf) / 2;
if (n == 0) return error.Unexpected;
assert(n <= wtf16le_buf.len);
const wtf16le_slice = wtf16le_buf[0..n];
var end_index: usize = 0;
var it = std.unicode.Wtf16LeIterator.init(wtf16le_slice);
while (it.nextCodepoint()) |codepoint| {
const seq_len = std.unicode.utf8CodepointSequenceLength(codepoint) catch unreachable;
if (end_index + seq_len >= buffer.len)
return error.NameTooLong;
end_index += std.unicode.wtf8Encode(codepoint, buffer[end_index..]) catch unreachable;
}
return end_index;
} else if (native_os == .wasi and !builtin.link_libc) {
if (buffer.len == 0) return error.NameTooLong;
buffer[0] = '.';
return 1;
}
const err: posix.E = if (builtin.link_libc) err: {
const c_err = if (std.c.getcwd(buffer.ptr, buffer.len)) |_| 0 else std.c._errno().*;
break :err @fromBackingInt(@intCast(c_err));
} else err: {
break :err posix.errno(posix.system.getcwd(buffer.ptr, buffer.len));
};
switch (err) {
.SUCCESS => return std.mem.findScalar(u8, buffer, 0).?,
.NOENT => return error.CurrentDirUnlinked,
.RANGE => return error.NameTooLong,
.FAULT => |e| return errnoBug(e),
.INVAL => |e| return errnoBug(e),
else => return posix.unexpectedErrno(err),
}
}
fn processSetCurrentDir(userdata: ?*anyopaque, dir: Dir) process.SetCurrentDirError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (native_os == .wasi) return error.OperationUnsupported;
if (is_windows) {
var dir_path_buf: [windows.PATH_MAX_WIDE]u16 = undefined;
const dir_path = try GetFinalPathNameByHandle(dir.handle, .{}, &dir_path_buf);
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.RtlSetCurrentDirectory_U(&.init(dir_path))) {
.SUCCESS => return syscall.finish(),
.OBJECT_NAME_INVALID => return syscall.fail(error.BadPathName),
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.NO_MEDIA_IN_DEVICE => return syscall.fail(error.NoDevice),
.INVALID_PARAMETER => |err| return syscall.ntstatusBug(err),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.OBJECT_PATH_SYNTAX_BAD => |err| return syscall.ntstatusBug(err),
.NOT_A_DIRECTORY => return syscall.fail(error.NotDir),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => |status| return syscall.unexpectedNtstatus(status),
};
}
return fchdir(dir.handle);
}
fn processSetCurrentPath(userdata: ?*anyopaque, path: []const u8) process.SetCurrentPathError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
if (native_os == .wasi) return error.OperationUnsupported;
if (is_windows) {
var path_w_buf: [windows.PATH_MAX_WIDE]u16 = undefined;
const len = std.unicode.calcWtf16LeLen(path) catch return error.InvalidWtf8;
if (len > path_w_buf.len) return error.NameTooLong;
const path_w_len = std.unicode.wtf8ToWtf16Le(&path_w_buf, path) catch |err| switch (err) {
error.InvalidWtf8 => unreachable, // already validated
};
const path_w = path_w_buf[0..path_w_len];
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.RtlSetCurrentDirectory_U(&.init(path_w))) {
.SUCCESS => return syscall.finish(),
.OBJECT_NAME_INVALID => return syscall.fail(error.BadPathName),
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.NO_MEDIA_IN_DEVICE => return syscall.fail(error.NoDevice),
.INVALID_PARAMETER => |err| return syscall.ntstatusBug(err),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.OBJECT_PATH_SYNTAX_BAD => |err| return syscall.ntstatusBug(err),
.NOT_A_DIRECTORY => return syscall.fail(error.NotDir),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => |status| return syscall.unexpectedNtstatus(status),
};
}
return chdir(path);
}
pub const PosixAddress = extern union {
any: posix.sockaddr,
in: posix.sockaddr.in,
in6: posix.sockaddr.in6,
};
const UnixAddress = extern union {
any: posix.sockaddr,
un: posix.sockaddr.un,
};
pub fn posixAddressFamily(a: *const IpAddress) posix.sa_family_t {
return switch (a.*) {
.ip4 => posix.AF.INET,
.ip6 => posix.AF.INET6,
};
}
pub fn addressFromPosix(posix_address: *const PosixAddress) IpAddress {
return switch (posix_address.any.family) {
posix.AF.INET => .{ .ip4 = address4FromPosix(&posix_address.in) },
posix.AF.INET6 => .{ .ip6 = address6FromPosix(&posix_address.in6) },
else => .{ .ip4 = .loopback(0) },
};
}
pub fn addressToPosix(a: *const IpAddress, storage: *PosixAddress) posix.socklen_t {
return switch (a.*) {
.ip4 => |ip4| {
storage.in = address4ToPosix(ip4);
return @sizeOf(posix.sockaddr.in);
},
.ip6 => |*ip6| {
storage.in6 = address6ToPosix(ip6);
return @sizeOf(posix.sockaddr.in6);
},
};
}
fn addressUnixToPosix(a: *const net.UnixAddress, storage: *UnixAddress) posix.socklen_t {
storage.un.family = posix.AF.UNIX;
var path_len = switch (native_os) {
.windows => @min(a.path.len, storage.un.path.len),
else => a.path.len,
};
// With the AFD API, `sockaddr.un` is purely informational, so
// use a suffix which is usually the most relevant part of a path.
@memcpy(storage.un.path[0..path_len], a.path[a.path.len - path_len ..]);
if (storage.un.path.len - path_len > 0) {
@branchHint(.likely);
storage.un.path[path_len] = 0;
path_len += 1;
}
switch (native_os) {
.windows => {
if (storage.un.path[0] == 0) @memset(storage.un.path[path_len..], 0);
return @sizeOf(posix.sockaddr.un);
},
else => return @intCast(@offsetOf(posix.sockaddr.un, "path") + path_len),
}
}
fn address4FromPosix(in: *const posix.sockaddr.in) net.Ip4Address {
// The network byte order address in `in.addr` is already the byte order we want.
const addr_bytes: *const [4]u8 = @ptrCast(&in.addr);
return .{
.port = std.mem.bigToNative(u16, in.port),
.bytes = addr_bytes.*,
};
}
fn address6FromPosix(in6: *const posix.sockaddr.in6) net.Ip6Address {
return .{
.port = std.mem.bigToNative(u16, in6.port),
.bytes = in6.addr,
.flow = in6.flowinfo,
.interface = .{ .index = in6.scope_id },
};
}
fn address4ToPosix(a: net.Ip4Address) posix.sockaddr.in {
// The byte order of `a.bytes` is already equivalent to a network byte order address.
const addr_raw: *align(1) const u32 = @ptrCast(&a.bytes);
return .{
.port = std.mem.nativeToBig(u16, a.port),
.addr = addr_raw.*,
};
}
fn address6ToPosix(a: *const net.Ip6Address) posix.sockaddr.in6 {
return .{
.port = std.mem.nativeToBig(u16, a.port),
.flowinfo = a.flow,
.addr = a.bytes,
.scope_id = a.interface.index,
};
}
pub fn errnoBug(err: posix.E) Io.UnexpectedError {
if (is_debug) std.debug.panic("programmer bug caused syscall error: {t}", .{err});
return error.Unexpected;
}
pub fn posixSocketModeProtocol(family: posix.sa_family_t, mode: net.Socket.Mode, protocol: ?net.Protocol) !struct { u32, u32 } {
return .{
switch (mode) {
.stream => posix.SOCK.STREAM,
.dgram => posix.SOCK.DGRAM,
.seqpacket => posix.SOCK.SEQPACKET,
.raw => posix.SOCK.RAW,
.rdm => if (@hasDecl(posix.SOCK, "RDM")) posix.SOCK.RDM else return error.OptionUnsupported,
},
if (protocol) |p| @backingInt(p) else if (is_windows) switch (family) {
posix.AF.UNIX => switch (mode) {
.stream => 0,
else => return error.ProtocolUnsupportedByAddressFamily,
},
posix.AF.INET, posix.AF.INET6 => @backingInt(@as(net.Protocol, switch (mode) {
.stream => .tcp,
.dgram => .udp,
else => return error.ProtocolUnsupportedByAddressFamily,
})),
else => return error.ProtocolUnsupportedByAddressFamily,
} else 0,
};
}
pub fn recoverableOsBugDetected() void {
if (is_debug) unreachable;
}
pub fn clockToPosix(clock: Io.Clock) posix.clockid_t {
return switch (clock) {
.real => posix.CLOCK.REALTIME,
.awake => switch (native_os) {
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => posix.CLOCK.UPTIME_RAW,
else => posix.CLOCK.MONOTONIC,
},
.boot => switch (native_os) {
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => posix.CLOCK.MONOTONIC_RAW,
// On freebsd derivatives, use MONOTONIC_FAST as currently there's
// no precision tradeoff.
.freebsd, .dragonfly => posix.CLOCK.MONOTONIC_FAST,
// On linux, use BOOTTIME instead of MONOTONIC as it ticks while
// suspended.
.linux => posix.CLOCK.BOOTTIME,
// On other posix systems, MONOTONIC is generally the fastest and
// ticks while suspended.
else => posix.CLOCK.MONOTONIC,
},
.cpu_process => posix.CLOCK.PROCESS_CPUTIME_ID,
.cpu_thread => posix.CLOCK.THREAD_CPUTIME_ID,
};
}
fn clockToWasi(clock: Io.Clock) std.os.wasi.clockid_t {
return switch (clock) {
.real => .REALTIME,
.awake => .MONOTONIC,
.boot => .MONOTONIC,
.cpu_process => .PROCESS_CPUTIME_ID,
.cpu_thread => .THREAD_CPUTIME_ID,
};
}
pub const linux_statx_request: std.os.linux.STATX = .{
.TYPE = true,
.MODE = true,
.ATIME = true,
.MTIME = true,
.CTIME = true,
.INO = true,
.SIZE = true,
.NLINK = true,
.BLOCKS = true,
};
pub const linux_statx_check: std.os.linux.STATX = .{
.TYPE = true,
.MODE = true,
.ATIME = false,
.MTIME = true,
.CTIME = true,
.INO = true,
.SIZE = true,
.NLINK = true,
.BLOCKS = false,
};
pub fn statFromLinux(stx: *const std.os.linux.Statx) Io.UnexpectedError!File.Stat {
const actual_mask_int: u32 = @bitCast(stx.mask);
const wanted_mask_int: u32 = @bitCast(linux_statx_check);
if ((actual_mask_int | wanted_mask_int) != actual_mask_int) return error.Unexpected;
return .{
.inode = stx.ino,
.nlink = stx.nlink,
.size = stx.size,
.permissions = .fromMode(stx.mode),
.kind = statxKind(stx.mode),
.atime = if (!stx.mask.ATIME) null else .{
.nanoseconds = @intCast(@as(i128, stx.atime.sec) * std.time.ns_per_s + stx.atime.nsec),
},
.mtime = .{ .nanoseconds = @intCast(@as(i128, stx.mtime.sec) * std.time.ns_per_s + stx.mtime.nsec) },
.ctime = .{ .nanoseconds = @intCast(@as(i128, stx.ctime.sec) * std.time.ns_per_s + stx.ctime.nsec) },
.block_size = if (stx.mask.BLOCKS) stx.blksize else 1,
};
}
pub fn statxKind(stx_mode: u16) File.Kind {
return switch (stx_mode & std.os.linux.S.IFMT) {
std.os.linux.S.IFDIR => .directory,
std.os.linux.S.IFCHR => .character_device,
std.os.linux.S.IFBLK => .block_device,
std.os.linux.S.IFREG => .file,
std.os.linux.S.IFIFO => .named_pipe,
std.os.linux.S.IFLNK => .sym_link,
std.os.linux.S.IFSOCK => .unix_domain_socket,
else => .unknown,
};
}
pub fn statFromPosix(st: *const posix.Stat) File.Stat {
const atime = st.atime();
const mtime = st.mtime();
const ctime = st.ctime();
return .{
.inode = st.ino,
.nlink = st.nlink,
.size = @bitCast(st.size),
.permissions = .fromMode(st.mode),
.kind = k: {
const m = st.mode & posix.S.IFMT;
switch (m) {
posix.S.IFBLK => break :k .block_device,
posix.S.IFCHR => break :k .character_device,
posix.S.IFDIR => break :k .directory,
posix.S.IFIFO => break :k .named_pipe,
posix.S.IFLNK => break :k .sym_link,
posix.S.IFREG => break :k .file,
posix.S.IFSOCK => break :k .unix_domain_socket,
else => {},
}
if (native_os == .illumos) switch (m) {
posix.S.IFDOOR => break :k .door,
posix.S.IFPORT => break :k .event_port,
else => {},
};
break :k .unknown;
},
.atime = timestampFromPosix(&atime),
.mtime = timestampFromPosix(&mtime),
.ctime = timestampFromPosix(&ctime),
.block_size = @intCast(st.blksize),
};
}
fn statFromWasi(st: *const std.os.wasi.filestat_t) File.Stat {
return .{
.inode = st.ino,
.nlink = st.nlink,
.size = @bitCast(st.size),
.permissions = .default_file,
.kind = switch (st.filetype) {
.BLOCK_DEVICE => .block_device,
.CHARACTER_DEVICE => .character_device,
.DIRECTORY => .directory,
.SYMBOLIC_LINK => .sym_link,
.REGULAR_FILE => .file,
.SOCKET_STREAM, .SOCKET_DGRAM => .unix_domain_socket,
else => .unknown,
},
.atime = .fromNanoseconds(st.atim),
.mtime = .fromNanoseconds(st.mtim),
.ctime = .fromNanoseconds(st.ctim),
.block_size = 1,
};
}
pub fn timestampFromPosix(timespec: *const posix.timespec) Io.Timestamp {
return .{ .nanoseconds = nanosecondsFromPosix(timespec) };
}
pub fn nanosecondsFromPosix(timespec: *const posix.timespec) i96 {
return @intCast(@as(i128, timespec.sec) * std.time.ns_per_s + timespec.nsec);
}
fn timestampToPosix(nanoseconds: i96) posix.timespec {
return .{
.sec = @intCast(@divFloor(nanoseconds, std.time.ns_per_s)),
.nsec = @intCast(@mod(nanoseconds, std.time.ns_per_s)),
};
}
pub fn setTimestampToPosix(set_ts: File.SetTimestamp) posix.timespec {
return switch (set_ts) {
.unchanged => posix.UTIME.OMIT,
.now => posix.UTIME.NOW,
.new => |t| timestampToPosix(t.nanoseconds),
};
}
pub fn pathToPosix(file_path: []const u8, buffer: *[posix.PATH_MAX]u8) Dir.PathNameError![:0]u8 {
if (std.mem.containsAtLeastScalar(u8, file_path, 0, 1)) return error.BadPathName;
// >= rather than > to make room for the null byte
if (file_path.len >= buffer.len) return error.NameTooLong;
@memcpy(buffer[0..file_path.len], file_path);
buffer[file_path.len] = 0;
return buffer[0..file_path.len :0];
}
fn lookupDnsSearch(
t: *Threaded,
host_name: HostName,
resolved: *Io.Queue(HostName.LookupResult),
options: HostName.LookupOptions,
) (HostName.LookupError || Io.QueueClosedError)!void {
const t_io = io(t);
const rc = HostName.ResolvConf.init(t_io) catch return error.ResolvConfParseFailed;
// Count dots, suppress search when >=ndots or name ends in
// a dot, which is an explicit request for global scope.
const dots = std.mem.countScalar(u8, host_name.bytes, '.');
const search_len = if (dots >= rc.ndots or std.mem.endsWith(u8, host_name.bytes, ".")) 0 else rc.search_len;
const search = rc.search_buffer[0..search_len];
var canon_name = host_name.bytes;
// Strip final dot for canon, fail if multiple trailing dots.
if (std.mem.endsWith(u8, canon_name, ".")) canon_name.len -= 1;
if (std.mem.endsWith(u8, canon_name, ".")) return error.UnknownHostName;
// Name with search domain appended is set up in `canon_name`. This
// both provides the desired default canonical name (if the requested
// name is not a CNAME record) and serves as a buffer for passing the
// full requested name to `lookupDns`.
var local_buf: [HostName.max_len]u8 = undefined;
const canon_buf = options.canonical_name_buffer orelse &local_buf;
@memcpy(canon_buf[0..canon_name.len], canon_name);
canon_buf[canon_name.len] = '.';
var it = std.mem.tokenizeAny(u8, search, " \t");
while (it.next()) |token| {
@memcpy(canon_buf[canon_name.len + 1 ..][0..token.len], token);
const lookup_canon_name = canon_buf[0 .. canon_name.len + 1 + token.len];
if (t.lookupDns(lookup_canon_name, &rc, resolved, options)) |result| {
return result;
} else |err| switch (err) {
error.UnknownHostName, error.NoAddressReturned => continue,
else => |e| return e,
}
}
const lookup_canon_name = canon_buf[0..canon_name.len];
return t.lookupDns(lookup_canon_name, &rc, resolved, options);
}
fn lookupDns(
t: *Threaded,
lookup_canon_name: []const u8,
rc: *const HostName.ResolvConf,
resolved: *Io.Queue(HostName.LookupResult),
options: HostName.LookupOptions,
) (HostName.LookupError || Io.QueueClosedError)!void {
const t_io = io(t);
const family_records: [2]struct { af: IpAddress.Family, rr: HostName.DnsRecord } = .{
.{ .af = .ip6, .rr = .A },
.{ .af = .ip4, .rr = .AAAA },
};
var query_buffers: [2][280]u8 = undefined;
var answer_buffer: [2 * 512]u8 = undefined;
var queries_buffer: [2][]const u8 = undefined;
var answers_buffer: [2][]const u8 = undefined;
var nq: usize = 0;
var answer_buffer_i: usize = 0;
for (family_records) |fr| {
if (options.family != fr.af) {
var entropy: [2]u8 = undefined;
random(t, &entropy);
const len = writeResolutionQuery(&query_buffers[nq], 0, lookup_canon_name, 1, fr.rr, entropy);
queries_buffer[nq] = query_buffers[nq][0..len];
nq += 1;
}
}
var ip4_mapped_buffer: [HostName.ResolvConf.max_nameservers]IpAddress = undefined;
const ip4_mapped = ip4_mapped_buffer[0..rc.nameservers_len];
var any_ip6 = false;
for (rc.nameservers(), ip4_mapped) |*ns, *m| {
m.* = .{ .ip6 = .fromAny(ns.*) };
any_ip6 = any_ip6 or ns.* == .ip6;
}
var socket = s: {
if (any_ip6) ip6: {
const ip6_addr: IpAddress = .{ .ip6 = .unspecified(0) };
const socket = ip6_addr.bind(t_io, .{ .ip6_only = false, .mode = .dgram }) catch |err| switch (err) {
error.AddressFamilyUnsupported => break :ip6,
else => |e| return e,
};
break :s socket;
}
any_ip6 = false;
const ip4_addr: IpAddress = .{ .ip4 = .unspecified(0) };
const socket = try ip4_addr.bind(t_io, .{ .mode = .dgram });
break :s socket;
};
defer socket.close(t_io);
const mapped_nameservers = if (any_ip6) ip4_mapped else rc.nameservers();
const queries = queries_buffer[0..nq];
const answers = answers_buffer[0..queries.len];
var answers_remaining = answers.len;
for (answers) |*answer| answer.len = 0;
// boot clock is chosen because time the computer is suspended should count
// against time spent waiting for external messages to arrive.
const clock: Io.Clock = .boot;
var now_ts = clock.now(t_io);
const final_ts = now_ts.addDuration(.fromSeconds(rc.timeout_seconds));
const attempt_duration: Io.Duration = .{
.nanoseconds = (std.time.ns_per_s / rc.attempts) * @as(i96, rc.timeout_seconds),
};
send: while (now_ts.nanoseconds < final_ts.nanoseconds) : (now_ts = clock.now(t_io)) {
const timeout: Io.Timeout = .{ .deadline = .{
.raw = now_ts.addDuration(attempt_duration),
.clock = clock,
} };
const max_messages = queries_buffer.len * HostName.ResolvConf.max_nameservers;
{
var message_buffer: [max_messages]net.OutgoingMessage = undefined;
var message_i: usize = 0;
for (queries, answers) |query, *answer| {
if (answer.len != 0) continue;
for (mapped_nameservers) |*ns| {
message_buffer[message_i] = .{
.address = ns,
.data_ptr = query.ptr,
.data_len = query.len,
};
message_i += 1;
}
}
const send_err, _ = socket.sendManyTimeout(t_io, message_buffer[0..message_i], .{}, timeout);
if (send_err) |err| switch (err) {
error.Canceled => |e| return e,
error.Timeout => continue :send,
else => {},
};
}
while (true) {
var message_buffer: [max_messages]net.IncomingMessage = @splat(.init);
const buf = answer_buffer[answer_buffer_i..];
const recv_err, const recv_n = socket.receiveManyTimeout(t_io, &message_buffer, buf, .{}, timeout);
for (message_buffer[0..recv_n]) |*received_message| {
const reply = received_message.data;
// Ignore non-identifiable packets.
if (reply.len < 4) continue;
// Ignore replies from addresses we didn't send to.
const ns = for (mapped_nameservers) |*ns| {
if (received_message.from.eql(ns)) break ns;
} else {
continue;
};
// Find which query this answer goes with, if any.
const query, const answer = for (queries, answers) |query, *answer| {
if (reply[0] == query[0] and reply[1] == query[1]) break .{ query, answer };
} else {
continue;
};
if (answer.len != 0) continue;
// Only accept positive or negative responses; retry immediately on
// server failure, and ignore all other codes such as refusal.
switch (reply[3] & 15) {
0, 3 => {
answer.* = reply;
answer_buffer_i += reply.len;
answers_remaining -= 1;
if (answer_buffer.len - answer_buffer_i == 0) break :send;
if (answers_remaining == 0) break :send;
},
2 => {
socket.sendTimeout(t_io, ns, query, timeout) catch |err| switch (err) {
error.Canceled => |e| return e,
error.Timeout => continue :send,
else => {},
};
continue;
},
else => continue,
}
}
if (recv_err) |err| switch (err) {
error.Canceled => |e| return e,
error.Timeout => continue :send,
else => continue,
};
}
} else {
return error.NameServerFailure;
}
var addresses_len: usize = 0;
var canonical_name: ?HostName = null;
for (answers) |answer| {
var it = HostName.DnsResponse.init(answer) catch {
// Here we could potentially add diagnostics to the results queue.
continue;
};
while (it.next() catch {
// Here we could potentially add diagnostics to the results queue.
continue;
}) |record| switch (record.rr) {
.A => {
const data = record.packet[record.data_off..][0..record.data_len];
if (data.len != 4) return error.InvalidDnsARecord;
try resolved.putOne(t_io, .{ .address = .{ .ip4 = .{
.bytes = data[0..4].*,
.port = options.port,
} } });
addresses_len += 1;
},
.AAAA => {
const data = record.packet[record.data_off..][0..record.data_len];
if (data.len != 16) return error.InvalidDnsAAAARecord;
try resolved.putOne(t_io, .{ .address = .{ .ip6 = .{
.bytes = data[0..16].*,
.port = options.port,
} } });
addresses_len += 1;
},
.CNAME => {
if (options.canonical_name_buffer) |buf| {
_, canonical_name = HostName.expand(
record.packet,
record.data_off,
buf,
) catch return error.InvalidDnsCnameRecord;
}
},
_ => continue,
};
}
if (options.canonical_name_buffer != null) {
try resolved.putOne(t_io, .{
.canonical_name = canonical_name orelse .{ .bytes = lookup_canon_name },
});
}
if (addresses_len == 0) return error.NoAddressReturned;
}
fn lookupHosts(
t: *Threaded,
host_name: HostName,
resolved: *Io.Queue(HostName.LookupResult),
options: HostName.LookupOptions,
) !void {
const path_w = if (is_windows) path_w: {
var path_w_buf: [windows.PATH_MAX_WIDE:0]u16 = undefined;
const system_dir = windows.getSystemDirectoryWtf16Le();
const suffix = [_]u16{
'\\', 'd', 'r', 'i', 'v', 'e', 'r', 's', '\\', 'e', 't', 'c', '\\', 'h', 'o', 's', 't', 's',
};
@memcpy(path_w_buf[0..system_dir.len], system_dir);
@memcpy(path_w_buf[system_dir.len..][0..suffix.len], &suffix);
path_w_buf[system_dir.len + suffix.len] = 0;
break :path_w wToPrefixedFileW(null, &path_w_buf, .{}) catch |err| switch (err) {
error.FileNotFound,
error.AccessDenied,
=> return error.UnknownHostName,
error.Canceled => |e| return e,
else => {
// Here we could add more detailed diagnostics to the results queue.
return error.DetectingNetworkConfigurationFailed;
},
};
};
const file = (if (is_windows)
dirOpenFileWtf16(null, path_w.span(), .{})
else
dirOpenFile(t, .cwd(), "/etc/hosts", .{})) catch |err| switch (err) {
error.FileNotFound,
error.NotDir,
error.AccessDenied,
=> return error.UnknownHostName,
error.Canceled => |e| return e,
else => {
// Here we could add more detailed diagnostics to the results queue.
return error.DetectingNetworkConfigurationFailed;
},
};
defer fileClose(t, &.{file});
var line_buf: [512]u8 = undefined;
var file_reader = file.reader(t.io(), &line_buf);
return t.lookupHostsReader(host_name, resolved, options, &file_reader.interface) catch |err| switch (err) {
error.ReadFailed => switch (file_reader.err.?) {
error.Canceled => |e| return e,
else => {
// Here we could add more detailed diagnostics to the results queue.
return error.DetectingNetworkConfigurationFailed;
},
},
error.Canceled,
error.Closed,
error.UnknownHostName,
=> |e| return e,
};
}
fn lookupHostsReader(
t: *Threaded,
host_name: HostName,
resolved: *Io.Queue(HostName.LookupResult),
options: HostName.LookupOptions,
reader: *Io.Reader,
) error{ ReadFailed, Canceled, UnknownHostName, Closed }!void {
const t_io = io(t);
var addresses_len: usize = 0;
var canonical_name: ?HostName = null;
while (true) {
const line = reader.takeDelimiterExclusive('\n') catch |err| switch (err) {
error.StreamTooLong => {
// Skip lines that are too long.
_ = reader.discardDelimiterInclusive('\n') catch |er| switch (er) {
error.EndOfStream => break,
error.ReadFailed => |e| return e,
};
continue;
},
error.ReadFailed => |e| return e,
error.EndOfStream => break,
};
reader.toss(@min(1, reader.bufferedLen()));
var split_it = std.mem.splitScalar(u8, if (is_windows and std.mem.endsWith(u8, line, "\r"))
line[0 .. line.len - 1]
else
line, '#');
const no_comment_line = split_it.first();
var line_it = std.mem.tokenizeAny(u8, no_comment_line, " \t");
const ip_text = line_it.next() orelse continue;
var first_name_text: ?[]const u8 = null;
while (line_it.next()) |name_text| {
if (std.ascii.eqlIgnoreCase(name_text, host_name.bytes)) {
if (first_name_text == null) first_name_text = name_text;
break;
}
} else continue;
if (canonical_name == null) {
if (options.canonical_name_buffer) |buf| {
if (HostName.init(first_name_text.?)) |name_text| {
if (name_text.bytes.len <= buf.len) {
const canonical_name_dest = buf[0..name_text.bytes.len];
@memcpy(canonical_name_dest, name_text.bytes);
canonical_name = .{ .bytes = canonical_name_dest };
}
} else |_| {}
}
}
if (options.family != .ip6) {
if (IpAddress.parseIp4(ip_text, options.port)) |addr| {
try resolved.putOne(t_io, .{ .address = addr });
addresses_len += 1;
} else |_| {}
}
if (options.family != .ip4) {
if (IpAddress.parseIp6(ip_text, options.port)) |addr| {
try resolved.putOne(t_io, .{ .address = addr });
addresses_len += 1;
} else |_| {}
}
}
if (canonical_name) |canon_name| try resolved.putOne(t_io, .{ .canonical_name = canon_name });
if (addresses_len == 0) return error.UnknownHostName;
}
/// Writes DNS resolution query packet data to `w`; at most 280 bytes.
fn writeResolutionQuery(q: *[280]u8, op: u4, dname: []const u8, class: u8, ty: HostName.DnsRecord, entropy: [2]u8) usize {
// This implementation is ported from musl libc.
// A more idiomatic "ziggy" implementation would be welcome.
var name = dname;
if (std.mem.endsWith(u8, name, ".")) name.len -= 1;
assert(name.len <= 253);
const n = 17 + name.len + @intFromBool(name.len != 0);
// Construct query template - ID will be filled later
q[0..2].* = entropy;
@memset(q[2..n], 0);
q[2] = @as(u8, op) * 8 + 1;
q[5] = 1;
@memcpy(q[13..][0..name.len], name);
var i: usize = 13;
var j: usize = undefined;
while (q[i] != 0) : (i = j + 1) {
j = i;
while (q[j] != 0 and q[j] != '.') : (j += 1) {}
// TODO determine the circumstances for this and whether or
// not this should be an error.
if (j - i - 1 > 62) unreachable;
q[i - 1] = @intCast(j - i);
}
q[i + 1] = @backingInt(ty);
q[i + 3] = class;
return n;
}
const LookupDnsWindows = struct {
threaded: *Threaded,
thread: Thread.Handle,
resolved: *Io.Queue(HostName.LookupResult),
options: HostName.LookupOptions,
results: windows.DNS.QUERY.RESULT,
done: bool,
fn completed(
pQueryContext: ?*anyopaque,
pQueryResults: *windows.DNS.QUERY.RESULT,
) callconv(.winapi) void {
_ = pQueryContext;
const lookup_dns: *LookupDnsWindows = @fieldParentPtr("results", pQueryResults);
lookup_dns.completedFallible() catch |err| switch (err) {
error.Closed => unreachable, // `resolved` must not be closed until `netLookup` returns
error.Canceled => unreachable, // called from an uncancelable thread
};
@atomicStore(bool, &lookup_dns.done, true, .release);
_ = windows.ntdll.NtAlertThread(lookup_dns.thread);
}
fn completedFallible(lookup_dns: *LookupDnsWindows) (Io.QueueClosedError || Io.Cancelable)!void {
assert(!lookup_dns.done);
const t = lookup_dns.threaded;
defer t.dl.DnsFree.raw.?(lookup_dns.results.pQueryRecords, .RecordList);
if (lookup_dns.results.QueryStatus != .SUCCESS) return;
const t_io = t.io();
var record_it = lookup_dns.results.pQueryRecords;
while (record_it) |record| : (record_it = record.pNext) switch (record.wType) {
else => {},
.A => try lookup_dns.resolved.putOne(t_io, .{
.address = .{ .ip4 = .{ .bytes = record.Data.A, .port = lookup_dns.options.port } },
}),
.AAAA => {
const ip6: net.Ip6Address = .{
.bytes = record.Data.AAAA,
.port = lookup_dns.options.port,
};
try lookup_dns.resolved.putOne(t_io, .{
.address = if (lookup_dns.options.family) |_| .{ .ip6 = ip6 } else .fromIp6(ip6),
});
},
};
if (lookup_dns.results.pQueryRecords) |record| {
if (lookup_dns.options.canonical_name_buffer) |buf| {
const name_wtf16 = std.mem.span(
@as([*:0]const windows.WCHAR, @ptrCast(@alignCast(record.pName))),
);
const len = std.unicode.wtf16LeToWtf8(buf, name_wtf16);
try lookup_dns.resolved.putOne(t_io, .{
.canonical_name = .{ .bytes = buf[0..len] },
});
}
}
}
};
fn copyCanon(canonical_name_buffer: ?*[HostName.max_len]u8, name: []const u8) ?HostName {
const buf = canonical_name_buffer orelse return null;
const dest = buf[0..name.len];
@memcpy(dest, name);
return .{ .bytes = dest };
}
/// Darwin XNU 7195.50.7.100.1 introduced __ulock_wait2 and migrated code paths (notably pthread_cond_t) towards it:
/// https://github.com/apple/darwin-xnu/commit/d4061fb0260b3ed486147341b72468f836ed6c8f#diff-08f993cc40af475663274687b7c326cc6c3031e0db3ac8de7b24624610616be6
///
/// This XNU version appears to correspond to 11.0.1:
/// https://kernelshaman.blogspot.com/2021/01/building-xnu-for-macos-big-sur-1101.html
///
/// ulock_wait() uses 32-bit micro-second timeouts where 0 = INFINITE or no-timeout
/// ulock_wait2() uses 64-bit nano-second timeouts (with the same convention)
const darwin_supports_ulock_wait2 = builtin.os.version_range.semver.min.major >= 11;
fn doNothingSignalHandler(_: posix.SIG) callconv(.c) void {}
const WindowsEnvironStrings = struct {
PATH: ?[:0]const u16 = null,
PATHEXT: ?[:0]const u16 = null,
fn scan() WindowsEnvironStrings {
const peb = windows.peb();
assert(windows.ntdll.RtlEnterCriticalSection(peb.FastPebLock) == .SUCCESS);
defer assert(windows.ntdll.RtlLeaveCriticalSection(peb.FastPebLock) == .SUCCESS);
const ptr = peb.ProcessParameters.Environment;
var result: WindowsEnvironStrings = .{};
var i: usize = 0;
while (ptr[i] != 0) {
const key_start = i;
// There are some special environment variables that start with =,
// so we need a special case to not treat = as a key/value separator
// if it's the first character.
// https://devblogs.microsoft.com/oldnewthing/20100506-00/?p=14133
if (ptr[key_start] == '=') i += 1;
while (ptr[i] != 0 and ptr[i] != '=') : (i += 1) {}
const key_w = ptr[key_start..i];
if (ptr[i] == '=') i += 1;
const value_start = i;
while (ptr[i] != 0) : (i += 1) {}
const value_w = ptr[value_start..i :0];
i += 1; // skip over null byte
inline for (@typeInfo(WindowsEnvironStrings).@"struct".field_names) |field_name| {
const field_name_w = comptime std.unicode.wtf8ToWtf16LeStringLiteral(field_name);
if (windows.eqlIgnoreCaseWtf16(key_w, field_name_w)) @field(result, field_name) = value_w;
}
}
return result;
}
};
fn scanEnviron(t: *Threaded) void {
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
if (t.environ_initialized) return;
t.environ.scan(t.allocator);
t.environ_initialized = true;
}
fn processReplace(userdata: ?*anyopaque, options: process.ReplaceOptions) process.ReplaceError {
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (!process.can_replace) return error.OperationUnsupported;
t.scanEnviron(); // for PATH
const PATH = t.environ.string.PATH orelse default_PATH;
var arena_allocator = std.heap.ArenaAllocator.init(t.allocator);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
const argv_buf = try arena.allocSentinel(?[*:0]const u8, options.argv.len, null);
for (options.argv, 0..) |arg, i| argv_buf[i] = (try arena.dupeSentinel(u8, arg, 0)).ptr;
const env_block = env_block: {
const prog_fd: i32 = -1;
if (options.environ_map) |environ_map| break :env_block try environ_map.createPosixBlock(arena, .{
.zig_progress_fd = prog_fd,
});
break :env_block try t.environ.process_environ.createPosixBlock(arena, .{
.zig_progress_fd = prog_fd,
});
};
return posixExecv(options.expand_arg0, argv_buf.ptr[0].?, argv_buf.ptr, env_block, PATH);
}
fn processReplacePath(userdata: ?*anyopaque, dir: Dir, options: process.ReplaceOptions) process.ReplaceError {
if (!process.can_replace) return error.OperationUnsupported;
_ = userdata;
_ = dir;
_ = options;
@panic("TODO processReplacePath");
}
fn processSpawnPath(userdata: ?*anyopaque, dir: Dir, options: process.SpawnOptions) process.SpawnError!process.Child {
if (!process.can_spawn) return error.OperationUnsupported;
_ = userdata;
_ = dir;
_ = options;
@panic("TODO processSpawnPath");
}
const processSpawn = switch (native_os) {
.wasi, .emscripten, .ios, .tvos, .visionos, .watchos => processSpawnUnsupported,
.windows => processSpawnWindows,
else => processSpawnPosix,
};
fn processSpawnUnsupported(userdata: ?*anyopaque, options: process.SpawnOptions) process.SpawnError!process.Child {
_ = userdata;
_ = options;
return error.OperationUnsupported;
}
const Spawned = struct {
pid: posix.pid_t,
err_fd: posix.fd_t,
stdin: ?File,
stdout: ?File,
stderr: ?File,
};
fn spawnPosix(t: *Threaded, options: process.SpawnOptions) process.SpawnError!Spawned {
// The child process does need to access (one end of) these pipes. However,
// we must initially set CLOEXEC to avoid a race condition. If another thread
// is racing to spawn a different child process, we don't want it to inherit
// these FDs in any scenario; that would mean that, for instance, calls to
// `poll` from the parent would not report the child's stdout as closing when
// expected, since the other child may retain a reference to the write end of
// the pipe. So, we create the pipes with CLOEXEC initially. After fork, we
// need to do something in the new child to make sure we preserve the reference
// we want. We could use `fcntl` to remove CLOEXEC from the FD, but as it
// turns out, we `dup2` everything anyway, so there's no need!
const pipe_flags: posix.O = .{ .CLOEXEC = true };
const stdin_pipe = if (options.stdin == .pipe) try pipe2(pipe_flags) else undefined;
errdefer if (options.stdin == .pipe) {
destroyPipe(stdin_pipe);
};
const stdout_pipe = if (options.stdout == .pipe) try pipe2(pipe_flags) else undefined;
errdefer if (options.stdout == .pipe) {
destroyPipe(stdout_pipe);
};
const stderr_pipe = if (options.stderr == .pipe) try pipe2(pipe_flags) else undefined;
errdefer if (options.stderr == .pipe) {
destroyPipe(stderr_pipe);
};
const any_ignore = (options.stdin == .ignore or options.stdout == .ignore or options.stderr == .ignore);
const dev_null_fd = if (any_ignore) try getDevNullFd(t) else undefined;
const prog_pipe: [2]posix.fd_t = if (options.progress_node.index != .none) pipe: {
// We use CLOEXEC for the same reason as in `pipe_flags`.
const pipe = try pipe2(.{ .NONBLOCK = true, .CLOEXEC = true });
switch (native_os) {
.linux => _ = posix.system.fcntl(pipe[0], posix.F.SETPIPE_SZ, @as(u32, std.Progress.max_packet_len * 2)),
else => {},
}
break :pipe pipe;
} else .{ -1, -1 };
errdefer destroyPipe(prog_pipe);
var arena_allocator = std.heap.ArenaAllocator.init(t.allocator);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
// The POSIX standard does not allow malloc() between fork() and execve(),
// and this allocator may be a libc allocator.
// I have personally observed the child process deadlocking when it tries
// to call malloc() due to a heap allocation between fork() and execve(),
// in musl v1.1.24.
// Additionally, we want to reduce the number of possible ways things
// can fail between fork() and execve().
// Therefore, we do all the allocation for the execve() before the fork().
// This means we must do the null-termination of argv and env vars here.
const argv_buf = try arena.allocSentinel(?[*:0]const u8, options.argv.len, null);
for (options.argv, 0..) |arg, i| argv_buf[i] = (try arena.dupeSentinel(u8, arg, 0)).ptr;
const prog_fileno = 3;
comptime assert(@max(posix.STDIN_FILENO, posix.STDOUT_FILENO, posix.STDERR_FILENO) + 1 == prog_fileno);
const env_block = env_block: {
const prog_fd: i32 = if (prog_pipe[1] == -1) -1 else prog_fileno;
if (options.environ_map) |environ_map| break :env_block try environ_map.createPosixBlock(arena, .{
.zig_progress_fd = prog_fd,
});
break :env_block try t.environ.process_environ.createPosixBlock(arena, .{
.zig_progress_fd = prog_fd,
});
};
// This pipe communicates to the parent errors in the child between `fork` and `execvpe`.
// It is closed by the child (via CLOEXEC) without writing if `execvpe` succeeds.
const err_pipe = try pipe2(.{ .CLOEXEC = true });
errdefer destroyPipe(err_pipe);
t.scanEnviron(); // for PATH
const PATH = t.environ.string.PATH orelse default_PATH;
const pid_result: posix.pid_t = fork: {
const rc = posix.system.fork();
switch (posix.errno(rc)) {
.SUCCESS => break :fork @intCast(rc),
.AGAIN => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOSYS => return error.OperationUnsupported,
else => |err| return posix.unexpectedErrno(err),
}
};
if (pid_result == 0) {
defer comptime unreachable; // We are the child.
if (Thread.current) |current_thread| current_thread.cancel_protection = .blocked;
const ep1 = err_pipe[1];
setUpChildIo(options.stdin, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) catch |err| forkBail(ep1, err);
setUpChildIo(options.stdout, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) catch |err| forkBail(ep1, err);
setUpChildIo(options.stderr, stderr_pipe[1], posix.STDERR_FILENO, dev_null_fd) catch |err| forkBail(ep1, err);
switch (options.cwd) {
.inherit => {},
.dir => |cwd| {
fchdir(cwd.handle) catch |err| forkBail(ep1, err);
},
.path => |cwd| {
chdir(cwd) catch |err| forkBail(ep1, err);
},
}
// Must happen after fchdir above, the cwd file descriptor might be
// equal to prog_fileno and be clobbered by this dup2 call.
if (prog_pipe[1] != -1) dup2(prog_pipe[1], prog_fileno) catch |err| forkBail(ep1, err);
if (options.gid) |gid| {
switch (posix.errno(posix.system.setregid(gid, gid))) {
.SUCCESS => {},
.AGAIN => forkBail(ep1, error.ResourceLimitReached),
.INVAL => forkBail(ep1, error.InvalidUserId),
.PERM => forkBail(ep1, error.PermissionDenied),
else => forkBail(ep1, error.Unexpected),
}
}
if (options.uid) |uid| {
switch (posix.errno(posix.system.setreuid(uid, uid))) {
.SUCCESS => {},
.AGAIN => forkBail(ep1, error.ResourceLimitReached),
.INVAL => forkBail(ep1, error.InvalidUserId),
.PERM => forkBail(ep1, error.PermissionDenied),
else => forkBail(ep1, error.Unexpected),
}
}
if (options.pgid) |pid| {
switch (posix.errno(posix.system.setpgid(0, pid))) {
.SUCCESS => {},
.ACCES => forkBail(ep1, error.ProcessAlreadyExec),
.INVAL => forkBail(ep1, error.InvalidProcessGroupId),
.PERM => forkBail(ep1, error.PermissionDenied),
else => forkBail(ep1, error.Unexpected),
}
}
if (options.start_suspended) {
switch (posix.errno(posix.system.kill(0, .STOP))) {
.SUCCESS => {},
.PERM => forkBail(ep1, error.PermissionDenied),
else => forkBail(ep1, error.Unexpected),
}
}
const err = posixExecv(options.expand_arg0, argv_buf.ptr[0].?, argv_buf.ptr, env_block, PATH);
forkBail(ep1, err);
}
const pid: posix.pid_t = @intCast(pid_result); // We are the parent.
errdefer comptime unreachable; // The child is forked; we must not error from now on
closeFd(err_pipe[1]); // make sure only the child holds the write end open
if (options.stdin == .pipe) closeFd(stdin_pipe[0]);
if (options.stdout == .pipe) closeFd(stdout_pipe[1]);
if (options.stderr == .pipe) closeFd(stderr_pipe[1]);
if (prog_pipe[1] != -1) closeFd(prog_pipe[1]);
options.progress_node.setIpcFile(t, .{ .handle = prog_pipe[0], .flags = .{ .nonblocking = true } });
return .{
.pid = pid,
.err_fd = err_pipe[0],
.stdin = switch (options.stdin) {
.pipe => .{ .handle = stdin_pipe[1], .flags = .{ .nonblocking = false } },
else => null,
},
.stdout = switch (options.stdout) {
.pipe => .{ .handle = stdout_pipe[0], .flags = .{ .nonblocking = false } },
else => null,
},
.stderr = switch (options.stderr) {
.pipe => .{ .handle = stderr_pipe[0], .flags = .{ .nonblocking = false } },
else => null,
},
};
}
fn getDevNullFd(t: *Threaded) !posix.fd_t {
{
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
if (t.null_file.fd != -1) return t.null_file.fd;
}
const mode: u32 = 0;
const syscall: Syscall = try .start();
while (true) {
const rc = open_sym("/dev/null", .{ .ACCMODE = .RDWR }, mode);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
const fresh_fd: posix.fd_t = @intCast(rc);
mutexLock(&t.mutex); // Another thread might have won the race.
defer mutexUnlock(&t.mutex);
if (t.null_file.fd != -1) {
closeFd(fresh_fd);
return t.null_file.fd;
} else {
t.null_file.fd = fresh_fd;
return fresh_fd;
}
},
.INTR => {
try syscall.checkCancel();
continue;
},
.ACCES => return syscall.fail(error.AccessDenied),
.MFILE => return syscall.fail(error.ProcessFdQuotaExceeded),
.NFILE => return syscall.fail(error.SystemFdQuotaExceeded),
.NODEV => return syscall.fail(error.NoDevice),
.NOENT => return syscall.fail(error.FileNotFound),
.NOMEM => return syscall.fail(error.SystemResources),
.PERM => return syscall.fail(error.PermissionDenied),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
fn processSpawnPosix(userdata: ?*anyopaque, options: process.SpawnOptions) process.SpawnError!process.Child {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const spawned = try spawnPosix(t, options);
defer closeFd(spawned.err_fd);
// Wait for the child to report any errors in or before `execvpe`.
if (readIntFd(spawned.err_fd)) |child_err_int| {
const child_err: process.SpawnError = @errorCast(@errorFromInt(child_err_int));
return child_err;
} else |read_err| switch (read_err) {
error.EndOfStream => {
// Write end closed by CLOEXEC at the time of the `execvpe` call,
// indicating success.
},
else => {
// Problem reading the error from the error reporting pipe. We
// don't know if the child is alive or dead. Better to assume it is
// alive so the resource does not risk being leaked.
},
}
return .{
.id = spawned.pid,
.thread_handle = {},
.stdin = spawned.stdin,
.stdout = spawned.stdout,
.stderr = spawned.stderr,
.request_resource_usage_statistics = options.request_resource_usage_statistics,
};
}
fn childWait(userdata: ?*anyopaque, child: *process.Child) process.Child.WaitError!process.Child.Term {
if (native_os == .wasi) unreachable;
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
switch (native_os) {
.windows => return childWaitWindows(child),
else => return childWaitPosix(child),
}
}
fn childKill(userdata: ?*anyopaque, child: *process.Child) void {
if (native_os == .wasi) unreachable;
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (is_windows) {
childKillWindows(t, child, 1) catch childCleanupWindows(child);
} else {
childKillPosix(child) catch {};
childCleanupPosix(child);
}
}
fn childKillWindows(t: *Threaded, child: *process.Child, exit_code: windows.UINT) !void {
_ = t; // TODO cancelation
const handle = child.id.?;
_ = windows.ntdll.RtlReportSilentProcessExit(handle, @fromBackingInt(@intCast(exit_code)));
switch (windows.ntdll.NtTerminateProcess(handle, @fromBackingInt(@intCast(exit_code)))) {
.SUCCESS, .PROCESS_IS_TERMINATING => {
_ = windows.ntdll.NtWaitForSingleObject(handle, .FALSE, null);
childCleanupWindows(child);
},
.ACCESS_DENIED => {
// Usually when TerminateProcess triggers a ACCESS_DENIED error, it
// indicates that the process has already exited, but there may be
// some rare edge cases where our process handle no longer has the
// PROCESS_TERMINATE access right, so let's do another check to make
// sure the process is really no longer running:
const minimal_timeout: windows.LARGE_INTEGER = -1;
return switch (windows.ntdll.NtWaitForSingleObject(handle, .FALSE, &minimal_timeout)) {
windows.NTSTATUS.WAIT_0 => error.AlreadyTerminated,
else => error.AccessDenied,
};
},
else => |status| return windows.unexpectedStatus(status),
}
}
fn childWaitWindows(child: *process.Child) process.Child.WaitError!process.Child.Term {
const handle = child.id.?;
const alertable_syscall: AlertableSyscall = try .start();
while (true) switch (windows.ntdll.NtWaitForSingleObject(handle, .TRUE, null)) {
windows.NTSTATUS.WAIT_0 => break alertable_syscall.finish(),
.USER_APC, .ALERTED, .TIMEOUT => {
try alertable_syscall.checkCancel();
continue;
},
else => |status| return alertable_syscall.unexpectedNtstatus(status),
};
var info: windows.PROCESS.BASIC_INFORMATION = undefined;
const term: process.Child.Term = switch (windows.ntdll.NtQueryInformationProcess(
handle,
.BasicInformation,
&info,
@sizeOf(windows.PROCESS.BASIC_INFORMATION),
null,
)) {
.SUCCESS => .{ .exited = @as(u8, @truncate(@backingInt(info.ExitStatus))) },
else => .{ .unknown = 0 },
};
childCleanupWindows(child);
return term;
}
fn childCleanupWindows(child: *process.Child) void {
const handle = child.id orelse return;
if (child.request_resource_usage_statistics) {
var vmc: windows.PROCESS.VM_COUNTERS = undefined;
switch (windows.ntdll.NtQueryInformationProcess(
handle,
.VmCounters,
&vmc,
@sizeOf(windows.PROCESS.VM_COUNTERS),
null,
)) {
.SUCCESS => child.resource_usage_statistics.rusage = vmc,
else => child.resource_usage_statistics.rusage = null,
}
}
windows.CloseHandle(handle);
child.id = null;
windows.CloseHandle(child.thread_handle);
child.thread_handle = undefined;
if (child.stdin) |stdin| {
windows.CloseHandle(stdin.handle);
child.stdin = null;
}
if (child.stdout) |stdout| {
windows.CloseHandle(stdout.handle);
child.stdout = null;
}
if (child.stderr) |stderr| {
windows.CloseHandle(stderr.handle);
child.stderr = null;
}
}
fn childWaitPosix(child: *process.Child) process.Child.WaitError!process.Child.Term {
defer childCleanupPosix(child);
const pid = child.id.?;
var ru: posix.rusage = undefined;
const ru_ptr = if (child.request_resource_usage_statistics) &ru else null;
if (have_wait4) {
var status: if (builtin.link_libc) c_int else i32 = undefined;
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.wait4(pid, &status, 0, ru_ptr))) {
.SUCCESS => {
syscall.finish();
if (ru_ptr) |p| child.resource_usage_statistics.rusage = p.*;
return statusToTerm(@bitCast(status));
},
.INTR => {
try syscall.checkCancel();
continue;
},
.CHILD => |err| return syscall.errnoBug(err), // Double-free.
else => |err| return syscall.unexpectedErrno(err),
};
}
if (have_waitid) {
const linux = std.os.linux; // Bypass libc which has the wrong signature.
var info: linux.siginfo_t = undefined;
const syscall: Syscall = try .start();
while (true) switch (linux.errno(linux.waitid(.PID, pid, &info, linux.W.EXITED, ru_ptr))) {
.SUCCESS => {
syscall.finish();
if (ru_ptr) |p| child.resource_usage_statistics.rusage = p.*;
const status: u32 = @bitCast(info.fields.common.second.sigchld.status);
const code: linux.CLD = @fromBackingInt(@intCast(info.code));
return switch (code) {
.EXITED => .{ .exited = @truncate(status) },
.KILLED, .DUMPED => .{ .signal = @fromBackingInt(@intCast(status)) },
.TRAPPED, .STOPPED => .{ .stopped = @fromBackingInt(@intCast(status)) },
_, .CONTINUED => .{ .unknown = status },
};
},
.INTR => {
try syscall.checkCancel();
continue;
},
.CHILD => |err| return syscall.errnoBug(err), // Double-free.
else => |err| return syscall.unexpectedErrno(err),
};
}
var status: if (builtin.link_libc) c_int else i32 = undefined;
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.waitpid(pid, &status, 0))) {
.SUCCESS => {
syscall.finish();
return statusToTerm(@bitCast(status));
},
.INTR => {
try syscall.checkCancel();
continue;
},
.CHILD => |err| return syscall.errnoBug(err), // Double-free.
else => |err| return syscall.unexpectedErrno(err),
};
}
pub fn statusToTerm(status: u32) process.Child.Term {
return if (posix.W.IFEXITED(status))
.{ .exited = posix.W.EXITSTATUS(status) }
else if (posix.W.IFSIGNALED(status))
.{ .signal = posix.W.TERMSIG(status) }
else if (posix.W.IFSTOPPED(status))
.{ .stopped = posix.W.STOPSIG(status) }
else
.{ .unknown = status };
}
fn childKillPosix(child: *process.Child) !void {
// Entire function body is intentionally uncancelable.
const pid = child.id.?;
while (true) switch (posix.errno(posix.system.kill(pid, .TERM))) {
.SUCCESS => break,
.INTR => continue,
.PERM => return error.PermissionDenied,
.INVAL => |err| return errnoBug(err),
.SRCH => |err| return errnoBug(err),
else => |err| return posix.unexpectedErrno(err),
};
if (have_wait4) {
var status: if (builtin.link_libc) c_int else i32 = undefined;
while (true) switch (posix.errno(posix.system.wait4(pid, &status, 0, null))) {
.SUCCESS => return,
.INTR => continue,
.CHILD => |err| return errnoBug(err), // Double-free.
else => |err| return posix.unexpectedErrno(err),
};
}
if (have_waitid) {
const linux = std.os.linux; // Bypass libc which has the wrong signature.
var info: linux.siginfo_t = undefined;
while (true) switch (linux.errno(linux.waitid(.PID, pid, &info, linux.W.EXITED, null))) {
.SUCCESS => return,
.INTR => continue,
.CHILD => |err| return errnoBug(err), // Double-free.
else => |err| return posix.unexpectedErrno(err),
};
}
var status: if (builtin.link_libc) c_int else i32 = undefined;
while (true) switch (posix.errno(posix.system.waitpid(pid, &status, 0))) {
.SUCCESS => return,
.INTR => continue,
.CHILD => |err| return errnoBug(err), // Double-free.
else => |err| return posix.unexpectedErrno(err),
};
}
fn childCleanupPosix(child: *process.Child) void {
if (child.stdin) |stdin| {
closeFd(stdin.handle);
child.stdin = null;
}
if (child.stdout) |stdout| {
closeFd(stdout.handle);
child.stdout = null;
}
if (child.stderr) |stderr| {
closeFd(stderr.handle);
child.stderr = null;
}
child.id = null;
}
/// Errors that can occur between fork() and execv()
const ForkBailError = process.SpawnError || process.ReplaceError;
/// Child of fork calls this to report an error to the fork parent. Then the
/// child exits.
fn forkBail(fd: posix.fd_t, err: ForkBailError) noreturn {
writeIntFd(fd, @as(ErrInt, @intFromError(err))) catch {};
// If we're linking libc, some naughty applications may have registered atexit handlers
// which we really do not want to run in the fork child. I caught LLVM doing this and
// it caused a deadlock instead of doing an exit syscall. In the words of Avril Lavigne,
// "Why'd you have to go and make things so complicated?"
if (builtin.link_libc) {
// The `_exit` function does nothing but make the exit syscall, unlike `exit`.
std.c._exit(1);
} else if (native_os == .linux and !builtin.single_threaded) {
std.os.linux.exit_group(1);
} else {
posix.system.exit(1);
}
}
fn writeIntFd(fd: posix.fd_t, value: ErrInt) !void {
var buffer: [8]u8 = undefined;
std.mem.writeInt(u64, &buffer, value, .little);
// Skip the cancel mechanism.
var i: usize = 0;
while (true) {
const rc = posix.system.write(fd, buffer[i..].ptr, buffer.len - i);
switch (posix.errno(rc)) {
.SUCCESS => {
const n: usize = @intCast(rc);
i += n;
if (buffer.len - i == 0) return;
},
.INTR => continue,
else => return error.SystemResources,
}
}
}
fn readIntFd(fd: posix.fd_t) !ErrInt {
var buffer: [8]u8 = undefined;
var i: usize = 0;
while (true) {
const rc = posix.system.read(fd, buffer[i..].ptr, buffer.len - i);
switch (posix.errno(rc)) {
.SUCCESS => {
const n: usize = @intCast(rc);
if (n == 0) break;
i += n;
continue;
},
.INTR => continue,
else => |err| return posix.unexpectedErrno(err),
}
}
if (buffer.len - i != 0) return error.EndOfStream;
return @intCast(std.mem.readInt(u64, &buffer, .little));
}
const ErrInt = @Int(.unsigned, @sizeOf(anyerror) * 8);
fn destroyPipe(pipe: [2]posix.fd_t) void {
if (pipe[0] != -1) closeFd(pipe[0]);
if (pipe[0] != pipe[1]) closeFd(pipe[1]);
}
fn setUpChildIo(stdio: process.SpawnOptions.StdIo, pipe_fd: i32, std_fileno: i32, dev_null_fd: i32) !void {
switch (stdio) {
.pipe => try dup2(pipe_fd, std_fileno),
.close => closeFd(std_fileno),
.inherit => {},
.ignore => try dup2(dev_null_fd, std_fileno),
.file => |file| try dup2(file.handle, std_fileno),
}
}
fn processSpawnWindows(userdata: ?*anyopaque, options: process.SpawnOptions) process.SpawnError!process.Child {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const any_ignore =
options.stdin == .ignore or
options.stdout == .ignore or
options.stderr == .ignore;
const nul_handle = if (any_ignore) try getNulDevice(t) else undefined;
const any_inherit =
options.stdin == .inherit or
options.stdout == .inherit or
options.stderr == .inherit;
const peb = if (any_inherit) windows.peb() else undefined;
const stdin_pipe = if (options.stdin == .pipe) try t.windowsCreatePipe(.{
.server = .{ .attributes = .{ .INHERIT = false }, .mode = .{ .IO = .SYNCHRONOUS_NONALERT } },
.client = .{ .attributes = .{ .INHERIT = true }, .mode = .{ .IO = .SYNCHRONOUS_NONALERT } },
.outbound = true,
}) else undefined;
errdefer if (options.stdin == .pipe) for (stdin_pipe) |handle| windows.CloseHandle(handle);
const stdout_pipe = if (options.stdout == .pipe) try t.windowsCreatePipe(.{
.server = .{ .attributes = .{ .INHERIT = false }, .mode = .{ .IO = .ASYNCHRONOUS } },
.client = .{ .attributes = .{ .INHERIT = true }, .mode = .{ .IO = .SYNCHRONOUS_NONALERT } },
.inbound = true,
}) else undefined;
errdefer if (options.stdout == .pipe) for (stdout_pipe) |handle| windows.CloseHandle(handle);
const stderr_pipe = if (options.stderr == .pipe) try t.windowsCreatePipe(.{
.server = .{ .attributes = .{ .INHERIT = false }, .mode = .{ .IO = .ASYNCHRONOUS } },
.client = .{ .attributes = .{ .INHERIT = true }, .mode = .{ .IO = .SYNCHRONOUS_NONALERT } },
.inbound = true,
}) else undefined;
errdefer if (options.stderr == .pipe) for (stderr_pipe) |handle| windows.CloseHandle(handle);
const prog_pipe = if (options.progress_node.index != .none) try t.windowsCreatePipe(.{
.server = .{ .attributes = .{ .INHERIT = false }, .mode = .{ .IO = .ASYNCHRONOUS } },
.client = .{ .attributes = .{ .INHERIT = true }, .mode = .{ .IO = .ASYNCHRONOUS } },
.inbound = true,
.quota = std.Progress.max_packet_len * 2,
}) else undefined;
errdefer if (options.progress_node.index != .none) for (prog_pipe) |handle| windows.CloseHandle(handle);
var siStartInfo: windows.STARTUPINFOW = .{
.cb = @sizeOf(windows.STARTUPINFOW),
.dwFlags = windows.STARTF_USESTDHANDLES,
.hStdInput = switch (options.stdin) {
.inherit => peb.ProcessParameters.hStdInput,
.file => |file| try OpenFile(&.{}, .{
.access_mask = .{
.STANDARD = .{ .SYNCHRONIZE = true },
.GENERIC = .{ .READ = true },
},
.dir = file.handle,
.sa = &.{
.nLength = @sizeOf(windows.SECURITY_ATTRIBUTES),
.lpSecurityDescriptor = null,
.bInheritHandle = .TRUE,
},
.creation = .OPEN,
}),
.ignore => nul_handle,
.pipe => stdin_pipe[1],
.close => null,
},
.hStdOutput = switch (options.stdout) {
.inherit => peb.ProcessParameters.hStdOutput,
.file => |file| try OpenFile(&.{}, .{
.access_mask = .{
.STANDARD = .{ .SYNCHRONIZE = true },
.GENERIC = .{ .WRITE = true },
},
.dir = file.handle,
.sa = &.{
.nLength = @sizeOf(windows.SECURITY_ATTRIBUTES),
.lpSecurityDescriptor = null,
.bInheritHandle = .TRUE,
},
.creation = .OPEN,
}),
.ignore => nul_handle,
.pipe => stdout_pipe[1],
.close => null,
},
.hStdError = switch (options.stderr) {
.inherit => peb.ProcessParameters.hStdError,
.file => |file| try OpenFile(&.{}, .{
.access_mask = .{
.STANDARD = .{ .SYNCHRONIZE = true },
.GENERIC = .{ .WRITE = true },
},
.dir = file.handle,
.sa = &.{
.nLength = @sizeOf(windows.SECURITY_ATTRIBUTES),
.lpSecurityDescriptor = null,
.bInheritHandle = .TRUE,
},
.creation = .OPEN,
}),
.ignore => nul_handle,
.pipe => stderr_pipe[1],
.close => null,
},
.lpReserved = null,
.lpDesktop = null,
.lpTitle = null,
.dwX = 0,
.dwY = 0,
.dwXSize = 0,
.dwYSize = 0,
.dwXCountChars = 0,
.dwYCountChars = 0,
.dwFillAttribute = 0,
.wShowWindow = 0,
.cbReserved2 = 0,
.lpReserved2 = null,
};
var piProcInfo: windows.PROCESS.INFORMATION = undefined;
var arena_allocator = std.heap.ArenaAllocator.init(t.allocator);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
const cwd_w = cwd_w: {
switch (options.cwd) {
.inherit => break :cwd_w null,
.dir => |cwd_dir| {
var dir_path_buffer = try arena.alloc(u16, windows.PATH_MAX_WIDE + 1);
const dir_path = try GetFinalPathNameByHandle(
cwd_dir.handle,
.{},
dir_path_buffer[0..windows.PATH_MAX_WIDE],
);
dir_path_buffer[dir_path.len] = 0;
// Shrink the allocation down to just the path buffer + sentinel
dir_path_buffer = try arena.realloc(dir_path_buffer, dir_path.len + 1);
break :cwd_w dir_path_buffer[0..dir_path.len :0];
},
.path => |cwd| {
break :cwd_w try std.unicode.wtf8ToWtf16LeAllocZ(arena, cwd);
},
}
};
const cwd_w_ptr = if (cwd_w) |cwd| cwd.ptr else null;
const env_block = env_block: {
const prog_handle = if (options.progress_node.index != .none)
prog_pipe[1]
else
windows.INVALID_HANDLE_VALUE;
if (options.environ_map) |environ_map| break :env_block try environ_map.createWindowsBlock(arena, .{
.zig_progress_handle = prog_handle,
});
break :env_block try t.environ.process_environ.createWindowsBlock(arena, .{
.zig_progress_handle = if (options.progress_node.index != .none) prog_pipe[1] else windows.INVALID_HANDLE_VALUE,
});
};
const app_name_wtf8 = options.argv[0];
const app_name_is_absolute = Dir.path.isAbsolute(app_name_wtf8);
// The cwd provided by options is in effect when choosing the executable
// path to match POSIX semantics.
const cwd_path_w = x: {
// If the app name is absolute, then we need to use its dirname as the cwd
if (app_name_is_absolute) {
const dir = Dir.path.dirname(app_name_wtf8).?;
break :x try std.unicode.wtf8ToWtf16LeAllocZ(arena, dir);
} else if (cwd_w) |cwd| {
break :x cwd;
} else {
break :x &[_:0]u16{}; // empty for cwd
}
};
// If the app name has more than just a filename, then we need to separate
// that into the basename and dirname and use the dirname as an addition to
// the cwd path. This is because NtQueryDirectoryFile cannot accept
// FileName params with path separators.
const app_basename_wtf8 = Dir.path.basename(app_name_wtf8);
// If the app name is absolute, then the cwd will already have the app's dirname in it,
// so only populate app_dirname if app name is a relative path with > 0 path separators.
const maybe_app_dirname_wtf8 = if (!app_name_is_absolute) Dir.path.dirname(app_name_wtf8) else null;
const app_dirname_w: ?[:0]u16 = x: {
if (maybe_app_dirname_wtf8) |app_dirname_wtf8| {
break :x try std.unicode.wtf8ToWtf16LeAllocZ(arena, app_dirname_wtf8);
}
break :x null;
};
const app_name_w = try std.unicode.wtf8ToWtf16LeAllocZ(arena, app_basename_wtf8);
const flags: windows.CreateProcessFlags = .{
.create_suspended = options.start_suspended,
.create_unicode_environment = true,
.create_no_window = options.create_no_window,
};
run: {
// We have to scan each time because the PEB environment pointer is not stable.
const env_strings: WindowsEnvironStrings = .scan();
const PATH = env_strings.PATH orelse &[_:0]u16{};
const PATHEXT = env_strings.PATHEXT orelse &[_:0]u16{};
// In case the command ends up being a .bat/.cmd script, we need to escape things using the cmd.exe rules
// and invoke cmd.exe ourselves in order to mitigate arbitrary command execution from maliciously
// constructed arguments.
//
// We'll need to wait until we're actually trying to run the command to know for sure
// if the resolved command has the `.bat` or `.cmd` extension, so we defer actually
// serializing the command line until we determine how it should be serialized.
var cmd_line_cache = WindowsCommandLineCache.init(arena, options.argv);
var app_buf: std.ArrayList(u16) = .empty;
try app_buf.appendSlice(arena, app_name_w);
var dir_buf: std.ArrayList(u16) = .empty;
if (cwd_path_w.len > 0) {
try dir_buf.appendSlice(arena, cwd_path_w);
}
if (app_dirname_w) |app_dir| {
if (dir_buf.items.len > 0) try dir_buf.append(arena, Dir.path.sep);
try dir_buf.appendSlice(arena, app_dir);
}
windowsCreateProcessPathExt(
arena,
&dir_buf,
&app_buf,
PATHEXT,
&cmd_line_cache,
env_block,
cwd_w_ptr,
flags,
&siStartInfo,
&piProcInfo,
) catch |no_path_err| {
const original_err = switch (no_path_err) {
// argv[0] contains unsupported characters that will never resolve to a valid exe.
error.InvalidArg0 => return error.FileNotFound,
error.FileNotFound, error.InvalidExe, error.AccessDenied => |e| e,
error.UnrecoverableInvalidExe => return error.InvalidExe,
else => |e| return e,
};
// If the app name had path separators, that disallows PATH searching,
// and there's no need to search the PATH if the app name is absolute.
// We still search the path if the cwd is absolute because of the
// "cwd provided by options is in effect when choosing the executable path
// to match posix semantics" behavior--we don't want to skip searching
// the PATH just because we were trying to set the cwd of the child process.
if (app_dirname_w != null or app_name_is_absolute) {
return original_err;
}
var it = std.mem.tokenizeScalar(u16, PATH, ';');
while (it.next()) |search_path| {
dir_buf.clearRetainingCapacity();
try dir_buf.appendSlice(arena, search_path);
if (windowsCreateProcessPathExt(
arena,
&dir_buf,
&app_buf,
PATHEXT,
&cmd_line_cache,
env_block,
cwd_w_ptr,
flags,
&siStartInfo,
&piProcInfo,
)) {
break :run;
} else |err| switch (err) {
// argv[0] contains unsupported characters that will never resolve to a valid exe.
error.InvalidArg0 => return error.FileNotFound,
error.FileNotFound, error.AccessDenied, error.InvalidExe => continue,
error.UnrecoverableInvalidExe => return error.InvalidExe,
else => |e| return e,
}
} else {
return original_err;
}
};
}
if (options.progress_node.index != .none) {
windows.CloseHandle(prog_pipe[1]);
options.progress_node.setIpcFile(t, .{ .handle = prog_pipe[0], .flags = .{ .nonblocking = true } });
}
return .{
.id = piProcInfo.hProcess,
.thread_handle = piProcInfo.hThread,
.stdin = stdin: switch (options.stdin) {
.file => {
windows.CloseHandle(siStartInfo.hStdInput.?);
break :stdin null;
},
.pipe => {
windows.CloseHandle(stdin_pipe[1]);
break :stdin .{ .handle = stdin_pipe[0], .flags = .{ .nonblocking = false } };
},
else => null,
},
.stdout = stdout: switch (options.stdout) {
.file => {
windows.CloseHandle(siStartInfo.hStdOutput.?);
break :stdout null;
},
.pipe => {
windows.CloseHandle(stdout_pipe[1]);
break :stdout .{ .handle = stdout_pipe[0], .flags = .{ .nonblocking = true } };
},
else => null,
},
.stderr = stderr: switch (options.stderr) {
.file => {
windows.CloseHandle(siStartInfo.hStdError.?);
break :stderr null;
},
.pipe => {
windows.CloseHandle(stderr_pipe[1]);
break :stderr .{ .handle = stderr_pipe[0], .flags = .{ .nonblocking = true } };
},
else => null,
},
.request_resource_usage_statistics = options.request_resource_usage_statistics,
};
}
fn inheritFile() windows.HANDLE {}
fn getCngDevice(t: *Threaded) Io.RandomSecureError!windows.HANDLE {
{
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
if (t.random_file.handle) |handle| return handle;
}
var fresh_handle: windows.HANDLE = undefined;
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtOpenFile(
&fresh_handle,
.{
.STANDARD = .{ .SYNCHRONIZE = true },
.SPECIFIC = .{ .FILE = .{ .READ_DATA = true } },
},
&.{ .ObjectName = @constCast(&windows.UNICODE_STRING.init(
&.{ '\\', 'D', 'e', 'v', 'i', 'c', 'e', '\\', 'C', 'N', 'G' },
)) },
&io_status_block,
.VALID_FLAGS,
.{ .IO = .SYNCHRONOUS_NONALERT },
)) {
.SUCCESS => {
syscall.finish();
mutexLock(&t.mutex); // Another thread might have won the race.
defer mutexUnlock(&t.mutex);
if (t.random_file.handle) |prev_handle| {
windows.CloseHandle(fresh_handle);
return prev_handle;
} else {
t.random_file.handle = fresh_handle;
return fresh_handle;
}
},
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.EntropyUnavailable), // Observed on wine 10.0
else => return syscall.fail(error.EntropyUnavailable),
};
}
fn getNulDevice(t: *Threaded) !windows.HANDLE {
{
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
if (t.null_file.handle) |handle| return handle;
}
var fresh_handle: windows.HANDLE = undefined;
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtOpenFile(
&fresh_handle,
.{
.STANDARD = .{ .SYNCHRONIZE = true },
.SPECIFIC = .{ .FILE = .{ .READ_DATA = true, .WRITE_DATA = true } },
},
&.{
.Attributes = .{ .INHERIT = true },
.ObjectName = @constCast(&windows.UNICODE_STRING.init(
&.{ '\\', 'D', 'e', 'v', 'i', 'c', 'e', '\\', 'N', 'u', 'l', 'l' },
)),
},
&io_status_block,
.VALID_FLAGS,
.{ .IO = .SYNCHRONOUS_NONALERT },
)) {
.SUCCESS => {
syscall.finish();
mutexLock(&t.mutex); // Another thread might have won the race.
defer mutexUnlock(&t.mutex);
if (t.null_file.handle) |prev_handle| {
windows.CloseHandle(fresh_handle);
return prev_handle;
} else {
t.null_file.handle = fresh_handle;
return fresh_handle;
}
},
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.INVALID_PARAMETER => |status| return syscall.ntstatusBug(status),
.OBJECT_PATH_SYNTAX_BAD => |status| return syscall.ntstatusBug(status),
.INVALID_HANDLE => |status| return syscall.ntstatusBug(status),
.OBJECT_NAME_INVALID => return syscall.fail(error.BadPathName),
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.NO_MEDIA_IN_DEVICE => return syscall.fail(error.NoDevice),
.SHARING_VIOLATION => return syscall.fail(error.AccessDenied),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.PIPE_NOT_AVAILABLE => return syscall.fail(error.NoDevice),
.FILE_IS_A_DIRECTORY => return syscall.fail(error.IsDir),
.NOT_A_DIRECTORY => return syscall.fail(error.NotDir),
.USER_MAPPED_FILE => return syscall.fail(error.AccessDenied),
else => |status| return syscall.unexpectedNtstatus(status),
};
}
fn getNamedPipeDevice(t: *Threaded) !windows.HANDLE {
{
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
if (t.pipe_file.handle) |handle| return handle;
}
var fresh_handle: windows.HANDLE = undefined;
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtOpenFile(
&fresh_handle,
.{ .STANDARD = .{ .SYNCHRONIZE = true } },
&.{
.ObjectName = @constCast(&windows.UNICODE_STRING.init(
&.{ '\\', 'D', 'e', 'v', 'i', 'c', 'e', '\\', 'N', 'a', 'm', 'e', 'd', 'P', 'i', 'p', 'e', '\\' },
)),
},
&io_status_block,
.VALID_FLAGS,
.{ .IO = .SYNCHRONOUS_NONALERT },
)) {
.SUCCESS => {
syscall.finish();
mutexLock(&t.mutex); // Another thread might have won the race.
defer mutexUnlock(&t.mutex);
if (t.pipe_file.handle) |prev_handle| {
windows.CloseHandle(fresh_handle);
return prev_handle;
} else {
t.pipe_file.handle = fresh_handle;
return fresh_handle;
}
},
.DELETE_PENDING => {
// This error means that there *was* a file in this location on
// the file system, but it was deleted. However, the OS is not
// finished with the deletion operation, and so this CreateFile
// call has failed. There is not really a sane way to handle
// this other than retrying the creation after the OS finishes
// the deletion.
syscall.finish();
try parking_sleep.sleep(.{ .duration = .{
.raw = .fromMilliseconds(1),
.clock = .awake,
} });
syscall = try .start();
continue;
},
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.INVALID_PARAMETER => |status| return syscall.ntstatusBug(status),
.OBJECT_PATH_SYNTAX_BAD => |status| return syscall.ntstatusBug(status),
.INVALID_HANDLE => |status| return syscall.ntstatusBug(status),
.OBJECT_NAME_INVALID => return syscall.fail(error.BadPathName),
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.NO_MEDIA_IN_DEVICE => return syscall.fail(error.NoDevice),
.SHARING_VIOLATION => return syscall.fail(error.AccessDenied),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.PIPE_NOT_AVAILABLE => return syscall.fail(error.NoDevice),
.FILE_IS_A_DIRECTORY => return syscall.fail(error.IsDir),
.NOT_A_DIRECTORY => return syscall.fail(error.NotDir),
.USER_MAPPED_FILE => return syscall.fail(error.AccessDenied),
else => |status| return syscall.unexpectedNtstatus(status),
};
}
/// Expects `app_buf` to contain exactly the app name, and `dir_buf` to contain exactly the dir path.
/// After return, `app_buf` will always contain exactly the app name and `dir_buf` will always contain exactly the dir path.
/// Note: `app_buf` should not contain any leading path separators.
/// Note: If the dir is the cwd, dir_buf should be empty (len = 0).
fn windowsCreateProcessPathExt(
arena: Allocator,
dir_buf: *std.ArrayList(u16),
app_buf: *std.ArrayList(u16),
pathext: [:0]const u16,
cmd_line_cache: *WindowsCommandLineCache,
env_block: ?process.Environ.WindowsBlock,
cwd_ptr: ?[*:0]u16,
flags: windows.CreateProcessFlags,
lpStartupInfo: *windows.STARTUPINFOW,
lpProcessInformation: *windows.PROCESS.INFORMATION,
) !void {
const app_name_len = app_buf.items.len;
const dir_path_len = dir_buf.items.len;
if (app_name_len == 0) return error.FileNotFound;
defer app_buf.shrinkRetainingCapacity(app_name_len);
defer dir_buf.shrinkRetainingCapacity(dir_path_len);
// The name of the game here is to avoid CreateProcessW calls at all costs,
// and only ever try calling it when we have a real candidate for execution.
// Secondarily, we want to minimize the number of syscalls used when checking
// for each PATHEXT-appended version of the app name.
//
// An overview of the technique used:
// - Open the search directory for iteration (either cwd or a path from PATH)
// - Use NtQueryDirectoryFile with a wildcard filename of `<app name>*` to
// check if anything that could possibly match either the unappended version
// of the app name or any of the versions with a PATHEXT value appended exists.
// - If the wildcard NtQueryDirectoryFile call found nothing, we can exit early
// without needing to use PATHEXT at all.
//
// This allows us to use a <open dir, NtQueryDirectoryFile, close dir> sequence
// for any directory that doesn't contain any possible matches, instead of having
// to use a separate look up for each individual filename combination (unappended +
// each PATHEXT appended). For directories where the wildcard *does* match something,
// we iterate the matches and take note of any that are either the unappended version,
// or a version with a supported PATHEXT appended. We then try calling CreateProcessW
// with the found versions in the appropriate order.
const dir = dir: {
// needs to be null-terminated
try dir_buf.append(arena, 0);
defer dir_buf.shrinkRetainingCapacity(dir_path_len);
const dir_path_z = dir_buf.items[0 .. dir_buf.items.len - 1 :0];
const prefixed_path = try wToPrefixedFileW(null, dir_path_z, .{});
break :dir dirOpenDirWindows(.cwd(), prefixed_path.span(), .{
.iterate = true,
}) catch |err| switch (err) {
// These errors must not be ignored because they should not be able
// to affect which file is chosen to execute. Also `error.Canceled`
// must never be swallowed.
error.Canceled,
error.SystemResources,
error.Unexpected,
error.ProcessFdQuotaExceeded,
error.SystemFdQuotaExceeded,
=> |e| return e,
error.AccessDenied,
error.PermissionDenied,
error.SymLinkLoop,
error.FileNotFound,
error.NotDir,
error.NoDevice,
error.NetworkNotFound,
error.NameTooLong,
error.BadPathName,
=> return error.FileNotFound,
};
};
defer windows.CloseHandle(dir.handle);
// Add wildcard and null-terminator
try app_buf.append(arena, '*');
try app_buf.append(arena, 0);
const app_name_wildcard = app_buf.items[0 .. app_buf.items.len - 1 :0];
// This 2048 is arbitrary, we just want it to be large enough to get multiple FILE_DIRECTORY_INFORMATION entries
// returned per NtQueryDirectoryFile call.
var file_information_buf: [2048]u8 align(@alignOf(windows.FILE_DIRECTORY_INFORMATION)) = undefined;
const file_info_maximum_single_entry_size = @sizeOf(windows.FILE_DIRECTORY_INFORMATION) + (windows.NAME_MAX * 2);
if (file_information_buf.len < file_info_maximum_single_entry_size) {
@compileError("file_information_buf must be large enough to contain at least one maximum size FILE_DIRECTORY_INFORMATION entry");
}
var io_status: windows.IO_STATUS_BLOCK = undefined;
const num_supported_pathext = @typeInfo(process.WindowsExtension).@"enum".field_names.len;
var pathext_seen: [num_supported_pathext]bool = @splat(false);
var any_pathext_seen = false;
var unappended_exists = false;
// Fully iterate the wildcard matches via NtQueryDirectoryFile and take note of all versions
// of the app_name we should try to spawn.
// Note: This is necessary because the order of the files returned is filesystem-dependent:
// On NTFS, `blah.exe*` will always return `blah.exe` first if it exists.
// On FAT32, it's possible for something like `blah.exe.obj` to be returned first.
while (true) {
// If we get nothing with the wildcard, then we can just bail out
// as we know appending PATHEXT will not yield anything.
switch (windows.ntdll.NtQueryDirectoryFile(
dir.handle,
null,
null,
null,
&io_status,
&file_information_buf,
file_information_buf.len,
.Directory,
.FALSE, // single result
&.init(app_name_wildcard),
.FALSE, // restart iteration
)) {
.SUCCESS => {},
.NO_SUCH_FILE => return error.FileNotFound,
.NO_MORE_FILES => break,
.ACCESS_DENIED => return error.AccessDenied,
else => |status| return windows.unexpectedStatus(status),
}
// According to the docs, this can only happen if there is not enough room in the
// buffer to write at least one complete FILE_DIRECTORY_INFORMATION entry.
// Therefore, this condition should not be possible to hit with the buffer size we use.
std.debug.assert(io_status.Information != 0);
var it = windows.FileInformationIterator(windows.FILE_DIRECTORY_INFORMATION){ .buf = &file_information_buf };
while (it.next()) |info| {
// Skip directories
if (info.FileAttributes.DIRECTORY) continue;
const filename = @as([*]u16, @ptrCast(&info.FileName))[0 .. info.FileNameLength / 2];
// Because all results start with the app_name since we're using the wildcard `app_name*`,
// if the length is equal to app_name then this is an exact match
if (filename.len == app_name_len) {
// Note: We can't break early here because it's possible that the unappended version
// fails to spawn, in which case we still want to try the PATHEXT appended versions.
unappended_exists = true;
} else if (windowsCreateProcessSupportsExtension(filename[app_name_len..])) |pathext_ext| {
pathext_seen[@backingInt(pathext_ext)] = true;
any_pathext_seen = true;
}
}
}
const unappended_err = unappended: {
if (unappended_exists) {
if (dir_path_len != 0) switch (dir_buf.items[dir_buf.items.len - 1]) {
'/', '\\' => {},
else => try dir_buf.append(arena, Dir.path.sep),
};
try dir_buf.appendSlice(arena, app_buf.items[0..app_name_len]);
try dir_buf.append(arena, 0);
const full_app_name = dir_buf.items[0 .. dir_buf.items.len - 1 :0];
const is_bat_or_cmd = bat_or_cmd: {
const app_name = app_buf.items[0..app_name_len];
const ext_start = std.mem.findScalarLast(u16, app_name, '.') orelse break :bat_or_cmd false;
const ext = app_name[ext_start..];
const ext_enum = windowsCreateProcessSupportsExtension(ext) orelse break :bat_or_cmd false;
switch (ext_enum) {
.cmd, .bat => break :bat_or_cmd true,
else => break :bat_or_cmd false,
}
};
const cmd_line_w = if (is_bat_or_cmd)
try cmd_line_cache.scriptCommandLine(full_app_name)
else
try cmd_line_cache.commandLine();
const app_name_w = if (is_bat_or_cmd)
try cmd_line_cache.cmdExePath()
else
full_app_name;
if (windowsCreateProcess(
app_name_w.ptr,
cmd_line_w.ptr,
env_block,
cwd_ptr,
flags,
lpStartupInfo,
lpProcessInformation,
)) |_| {
return;
} else |err| switch (err) {
error.FileNotFound,
error.AccessDenied,
=> break :unappended err,
error.InvalidExe => {
// On InvalidExe, if the extension of the app name is .exe then
// it's treated as an unrecoverable error. Otherwise, it'll be
// skipped as normal.
const app_name = app_buf.items[0..app_name_len];
const ext_start = std.mem.findScalarLast(u16, app_name, '.') orelse break :unappended err;
const ext = app_name[ext_start..];
if (windows.eqlIgnoreCaseWtf16(ext, std.unicode.utf8ToUtf16LeStringLiteral(".EXE"))) {
return error.UnrecoverableInvalidExe;
}
break :unappended err;
},
else => return err,
}
}
break :unappended error.FileNotFound;
};
if (!any_pathext_seen) return unappended_err;
// Now try any PATHEXT appended versions that we've seen
var ext_it = std.mem.tokenizeScalar(u16, pathext, ';');
while (ext_it.next()) |ext| {
const ext_enum = windowsCreateProcessSupportsExtension(ext) orelse continue;
if (!pathext_seen[@backingInt(ext_enum)]) continue;
dir_buf.shrinkRetainingCapacity(dir_path_len);
if (dir_path_len != 0) switch (dir_buf.items[dir_buf.items.len - 1]) {
'/', '\\' => {},
else => try dir_buf.append(arena, Dir.path.sep),
};
try dir_buf.appendSlice(arena, app_buf.items[0..app_name_len]);
try dir_buf.appendSlice(arena, ext);
try dir_buf.append(arena, 0);
const full_app_name = dir_buf.items[0 .. dir_buf.items.len - 1 :0];
const is_bat_or_cmd = switch (ext_enum) {
.cmd, .bat => true,
else => false,
};
const cmd_line_w = if (is_bat_or_cmd)
try cmd_line_cache.scriptCommandLine(full_app_name)
else
try cmd_line_cache.commandLine();
const app_name_w = if (is_bat_or_cmd)
try cmd_line_cache.cmdExePath()
else
full_app_name;
if (windowsCreateProcess(app_name_w.ptr, cmd_line_w.ptr, env_block, cwd_ptr, flags, lpStartupInfo, lpProcessInformation)) |_| {
return;
} else |err| switch (err) {
error.FileNotFound => continue,
error.AccessDenied => continue,
error.InvalidExe => {
// On InvalidExe, if the extension of the app name is .exe then
// it's treated as an unrecoverable error. Otherwise, it'll be
// skipped as normal.
if (windows.eqlIgnoreCaseWtf16(ext, std.unicode.utf8ToUtf16LeStringLiteral(".EXE"))) {
return error.UnrecoverableInvalidExe;
}
continue;
},
else => return err,
}
}
return unappended_err;
}
fn windowsCreateProcess(
app_name: [*:0]u16,
cmd_line: [*:0]u16,
env_block: ?process.Environ.WindowsBlock,
cwd_ptr: ?[*:0]u16,
flags: windows.CreateProcessFlags,
lpStartupInfo: *windows.STARTUPINFOW,
lpProcessInformation: *windows.PROCESS.INFORMATION,
) !void {
const syscall: Syscall = try .start();
while (true) {
if (windows.kernel32.CreateProcessW(
app_name,
cmd_line,
null,
null,
.TRUE,
flags,
if (env_block) |block| block.slice.ptr else null,
cwd_ptr,
lpStartupInfo,
lpProcessInformation,
).toBool()) {
return syscall.finish();
} else switch (windows.GetLastError()) {
.INVALID_PARAMETER => unreachable,
.OPERATION_ABORTED => {
try syscall.checkCancel();
continue;
},
.FILE_NOT_FOUND => return syscall.fail(error.FileNotFound),
.PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.DIRECTORY => return syscall.fail(error.FileNotFound),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.INVALID_NAME => return syscall.fail(error.InvalidName),
.FILENAME_EXCED_RANGE => return syscall.fail(error.NameTooLong),
.SHARING_VIOLATION => return syscall.fail(error.FileBusy),
.COMMITMENT_LIMIT => return syscall.fail(error.SystemResources),
// These are all the system errors that are mapped to ENOEXEC by
// the undocumented _dosmaperr (old CRT) or __acrt_errno_map_os_error
// (newer CRT) functions. Their code can be found in crt/src/dosmap.c (old SDK)
// or urt/misc/errno.cpp (newer SDK) in the Windows SDK.
.BAD_FORMAT,
.INVALID_STARTING_CODESEG, // MIN_EXEC_ERROR in errno.cpp
.INVALID_STACKSEG,
.INVALID_MODULETYPE,
.INVALID_EXE_SIGNATURE,
.EXE_MARKED_INVALID,
.BAD_EXE_FORMAT,
.ITERATED_DATA_EXCEEDS_64k,
.INVALID_MINALLOCSIZE,
.DYNLINK_FROM_INVALID_RING,
.IOPL_NOT_ENABLED,
.INVALID_SEGDPL,
.AUTODATASEG_EXCEEDS_64k,
.RING2SEG_MUST_BE_MOVABLE,
.RELOC_CHAIN_XEEDS_SEGLIM,
.INFLOOP_IN_RELOC_CHAIN, // MAX_EXEC_ERROR in errno.cpp
// This one is not mapped to ENOEXEC but it is possible, for example
// when calling CreateProcessW on a plain text file with a .exe extension
.EXE_MACHINE_TYPE_MISMATCH,
=> return syscall.fail(error.InvalidExe),
else => |err| {
syscall.finish();
return windows.unexpectedError(err);
},
}
}
}
/// Case-insensitive WTF-16 lookup
fn windowsCreateProcessSupportsExtension(ext: []const u16) ?process.WindowsExtension {
comptime {
// Ensures keeping this function in sync with the enum.
const field_names = @typeInfo(process.WindowsExtension).@"enum".field_names;
assert(field_names.len == 4);
assert(@backingInt(process.WindowsExtension.bat) == 0);
assert(@backingInt(process.WindowsExtension.cmd) == 1);
assert(@backingInt(process.WindowsExtension.com) == 2);
assert(@backingInt(process.WindowsExtension.exe) == 3);
}
if (ext.len != 4) return null;
const State = enum {
start,
dot,
b,
ba,
c,
cm,
co,
e,
ex,
};
var state: State = .start;
for (ext) |c| switch (state) {
.start => switch (c) {
'.' => state = .dot,
else => return null,
},
.dot => switch (c) {
'b', 'B' => state = .b,
'c', 'C' => state = .c,
'e', 'E' => state = .e,
else => return null,
},
.b => switch (c) {
'a', 'A' => state = .ba,
else => return null,
},
.c => switch (c) {
'm', 'M' => state = .cm,
'o', 'O' => state = .co,
else => return null,
},
.e => switch (c) {
'x', 'X' => state = .ex,
else => return null,
},
.ba => switch (c) {
't', 'T' => return .bat,
else => return null,
},
.cm => switch (c) {
'd', 'D' => return .cmd,
else => return null,
},
.co => switch (c) {
'm', 'M' => return .com,
else => return null,
},
.ex => switch (c) {
'e', 'E' => return .exe,
else => return null,
},
};
return null;
}
test windowsCreateProcessSupportsExtension {
try std.testing.expectEqual(process.WindowsExtension.exe, windowsCreateProcessSupportsExtension(&[_]u16{ '.', 'e', 'X', 'e' }).?);
try std.testing.expect(windowsCreateProcessSupportsExtension(&[_]u16{ '.', 'e', 'X', 'e', 'c' }) == null);
}
/// Serializes argv into a WTF-16 encoded command-line string for use with CreateProcessW.
///
/// Serialization is done on-demand and the result is cached in order to allow for:
/// - Only serializing the particular type of command line needed (`.bat`/`.cmd`
/// command line serialization is different from `.exe`/etc)
/// - Reusing the serialized command lines if necessary (i.e. if the execution
/// of a command fails and the PATH is going to be continued to be searched
/// for more candidates)
const WindowsCommandLineCache = struct {
cmd_line: ?[:0]u16 = null,
script_cmd_line: ?[:0]u16 = null,
cmd_exe_path: ?[:0]u16 = null,
argv: []const []const u8,
allocator: Allocator,
fn init(allocator: Allocator, argv: []const []const u8) WindowsCommandLineCache {
return .{
.allocator = allocator,
.argv = argv,
};
}
fn deinit(self: *WindowsCommandLineCache) void {
if (self.cmd_line) |cmd_line| self.allocator.free(cmd_line);
if (self.script_cmd_line) |script_cmd_line| self.allocator.free(script_cmd_line);
if (self.cmd_exe_path) |cmd_exe_path| self.allocator.free(cmd_exe_path);
}
fn commandLine(self: *WindowsCommandLineCache) ![:0]u16 {
if (self.cmd_line == null) {
self.cmd_line = try argvToCommandLineWindows(self.allocator, self.argv);
}
return self.cmd_line.?;
}
/// Not cached, since the path to the batch script will change during PATH searching.
/// `script_path` should be as qualified as possible, e.g. if the PATH is being searched,
/// then script_path should include both the search path and the script filename
/// (this allows avoiding cmd.exe having to search the PATH again).
fn scriptCommandLine(self: *WindowsCommandLineCache, script_path: []const u16) ![:0]u16 {
if (self.script_cmd_line) |v| self.allocator.free(v);
self.script_cmd_line = try argvToScriptCommandLineWindows(
self.allocator,
script_path,
self.argv[1..],
);
return self.script_cmd_line.?;
}
fn cmdExePath(self: *WindowsCommandLineCache) Allocator.Error![:0]u16 {
if (self.cmd_exe_path == null) {
// Remove trailing slash from system directory path; we'll re-add it below
const system_dir = std.mem.trimEnd(u16, windows.getSystemDirectoryWtf16Le(), &.{ '/', '\\' });
const suffix = std.unicode.utf8ToUtf16LeStringLiteral("\\cmd.exe");
const buf = try self.allocator.allocSentinel(u16, system_dir.len + suffix.len, 0);
errdefer comptime unreachable;
@memcpy(buf[0..system_dir.len], system_dir);
@memcpy(buf[system_dir.len..], suffix);
self.cmd_exe_path = buf;
}
return self.cmd_exe_path.?;
}
};
const ArgvToScriptCommandLineError = error{
OutOfMemory,
InvalidWtf8,
/// NUL (U+0000), LF (U+000A), CR (U+000D) are not allowed
/// within arguments when executing a `.bat`/`.cmd` script.
/// - NUL/LF signifiies end of arguments, so anything afterwards
/// would be lost after execution.
/// - CR is stripped by `cmd.exe`, so any CR codepoints
/// would be lost after execution.
InvalidBatchScriptArg,
};
/// Serializes `argv` to a Windows command-line string that uses `cmd.exe /c` and `cmd.exe`-specific
/// escaping rules. The caller owns the returned slice.
///
/// Escapes `argv` using the suggested mitigation against arbitrary command execution from:
/// https://flatt.tech/research/posts/batbadbut-you-cant-securely-execute-commands-on-windows/
///
/// The return of this function will look like
/// `cmd.exe /d /e:ON /v:OFF /c "<escaped command line>"`
/// and should be used as the `lpCommandLine` of `CreateProcessW`, while the return of
/// `WindowsCommandLineCache.cmdExePath` should be used as `lpApplicationName`.
///
/// Should only be used when spawning `.bat`/`.cmd` scripts, see `argvToCommandLineWindows` otherwise.
/// The `.bat`/`.cmd` file must be known to both have the `.bat`/`.cmd` extension and exist on the filesystem.
fn argvToScriptCommandLineWindows(
allocator: Allocator,
/// Path to the `.bat`/`.cmd` script. If this path is relative, it is assumed to be relative to the CWD.
/// The script must have been verified to exist at this path before calling this function.
script_path: []const u16,
/// Arguments, not including the script name itself. Expected to be encoded as WTF-8.
script_args: []const []const u8,
) ArgvToScriptCommandLineError![:0]u16 {
var buf = try std.array_list.Managed(u8).initCapacity(allocator, 64);
defer buf.deinit();
// `/d` disables execution of AutoRun commands.
// `/e:ON` and `/v:OFF` are needed for BatBadBut mitigation:
// > If delayed expansion is enabled via the registry value DelayedExpansion,
// > it must be disabled by explicitly calling cmd.exe with the /V:OFF option.
// > Escaping for % requires the command extension to be enabled.
// > If it’s disabled via the registry value EnableExtensions, it must be enabled with the /E:ON option.
// https://flatt.tech/research/posts/batbadbut-you-cant-securely-execute-commands-on-windows/
buf.appendSliceAssumeCapacity("cmd.exe /d /e:ON /v:OFF /c \"");
// Always quote the path to the script arg
buf.appendAssumeCapacity('"');
// We always want the path to the batch script to include a path separator in order to
// avoid cmd.exe searching the PATH for the script. This is not part of the arbitrary
// command execution mitigation, we just know exactly what script we want to execute
// at this point, and potentially making cmd.exe re-find it is unnecessary.
//
// If the script path does not have a path separator, then we know its relative to CWD and
// we can just put `.\` in the front.
if (std.mem.findAny(u16, script_path, &[_]u16{
std.mem.nativeToLittle(u16, '\\'), std.mem.nativeToLittle(u16, '/'),
}) == null) {
try buf.appendSlice(".\\");
}
// Note that we don't do any escaping/mitigations for this argument, since the relevant
// characters (", %, etc) are illegal in file paths and this function should only be called
// with script paths that have been verified to exist.
try std.unicode.wtf16LeToWtf8ArrayList(&buf, script_path);
buf.appendAssumeCapacity('"');
for (script_args) |arg| {
// Literal carriage returns get stripped when run through cmd.exe
// and NUL/newlines act as 'end of command.' Because of this, it's basically
// always a mistake to include these characters in argv, so it's
// an error condition in order to ensure that the return of this
// function can always roundtrip through cmd.exe.
if (std.mem.findAny(u8, arg, "\x00\r\n") != null) {
return error.InvalidBatchScriptArg;
}
// Separate args with a space.
try buf.append(' ');
// Need to quote if the argument is empty (otherwise the arg would just be lost)
// or if the last character is a `\`, since then something like "%~2" in a .bat
// script would cause the closing " to be escaped which we don't want.
var needs_quotes = arg.len == 0 or arg[arg.len - 1] == '\\';
if (!needs_quotes) {
for (arg) |c| {
switch (c) {
// Known good characters that don't need to be quoted
'A'...'Z', 'a'...'z', '0'...'9', '#', '$', '*', '+', '-', '.', '/', ':', '?', '@', '\\', '_' => {},
// When in doubt, quote
else => {
needs_quotes = true;
break;
},
}
}
}
if (needs_quotes) {
try buf.append('"');
}
var backslashes: usize = 0;
for (arg) |c| {
switch (c) {
'\\' => {
backslashes += 1;
},
'"' => {
try buf.appendNTimes('\\', backslashes);
try buf.append('"');
backslashes = 0;
},
// Replace `%` with `%%cd:~,%`.
//
// cmd.exe allows extracting a substring from an environment
// variable with the syntax: `%foo:~<start_index>,<end_index>%`.
// Therefore, `%cd:~,%` will always expand to an empty string
// since both the start and end index are blank, and it is assumed
// that `%cd%` is always available since it is a built-in variable
// that corresponds to the current directory.
//
// This means that replacing `%foo%` with `%%cd:~,%foo%%cd:~,%`
// will stop `%foo%` from being expanded and *after* expansion
// we'll still be left with `%foo%` (the literal string).
'%' => {
// the trailing `%` is appended outside the switch
try buf.appendSlice("%%cd:~,");
backslashes = 0;
},
else => {
backslashes = 0;
},
}
try buf.append(c);
}
if (needs_quotes) {
try buf.appendNTimes('\\', backslashes);
try buf.append('"');
}
}
try buf.append('"');
return try std.unicode.wtf8ToWtf16LeAllocZ(allocator, buf.items);
}
const ArgvToCommandLineError = error{ OutOfMemory, InvalidWtf8, InvalidArg0 };
/// Serializes `argv` to a Windows command-line string suitable for passing to a child process and
/// parsing by the `CommandLineToArgvW` algorithm. The caller owns the returned slice.
///
/// To avoid arbitrary command execution, this function should not be used when spawning `.bat`/`.cmd` scripts.
/// https://flatt.tech/research/posts/batbadbut-you-cant-securely-execute-commands-on-windows/
///
/// When executing `.bat`/`.cmd` scripts, use `argvToScriptCommandLineWindows` instead.
fn argvToCommandLineWindows(
allocator: Allocator,
argv: []const []const u8,
) ArgvToCommandLineError![:0]u16 {
var buf = std.array_list.Managed(u8).init(allocator);
defer buf.deinit();
if (argv.len != 0) {
const arg0 = argv[0];
// The first argument must be quoted if it contains spaces or ASCII control characters
// (excluding DEL). It also follows special quoting rules where backslashes have no special
// interpretation, which makes it impossible to pass certain first arguments containing
// double quotes to a child process without characters from the first argument leaking into
// subsequent ones (which could have security implications).
//
// Empty arguments technically don't need quotes, but we quote them anyway for maximum
// compatibility with different implementations of the 'CommandLineToArgvW' algorithm.
//
// Double quotes are illegal in paths on Windows, so for the sake of simplicity we reject
// all first arguments containing double quotes, even ones that we could theoretically
// serialize in unquoted form.
var needs_quotes = arg0.len == 0;
for (arg0) |c| {
if (c <= ' ') {
needs_quotes = true;
} else if (c == '"') {
return error.InvalidArg0;
}
}
if (needs_quotes) {
try buf.append('"');
try buf.appendSlice(arg0);
try buf.append('"');
} else {
try buf.appendSlice(arg0);
}
for (argv[1..]) |arg| {
try buf.append(' ');
// Subsequent arguments must be quoted if they contain spaces, tabs or double quotes,
// or if they are empty. For simplicity and for maximum compatibility with different
// implementations of the 'CommandLineToArgvW' algorithm, we also quote all ASCII
// control characters (again, excluding DEL).
needs_quotes = for (arg) |c| {
if (c <= ' ' or c == '"') {
break true;
}
} else arg.len == 0;
if (!needs_quotes) {
try buf.appendSlice(arg);
continue;
}
try buf.append('"');
var backslash_count: usize = 0;
for (arg) |byte| {
switch (byte) {
'\\' => {
backslash_count += 1;
},
'"' => {
try buf.appendNTimes('\\', backslash_count * 2 + 1);
try buf.append('"');
backslash_count = 0;
},
else => {
try buf.appendNTimes('\\', backslash_count);
try buf.append(byte);
backslash_count = 0;
},
}
}
try buf.appendNTimes('\\', backslash_count * 2);
try buf.append('"');
}
}
return try std.unicode.wtf8ToWtf16LeAllocZ(allocator, buf.items);
}
test argvToCommandLineWindows {
const t = testArgvToCommandLineWindows;
try t(&.{
\\C:\Program Files\zig\zig.exe
,
\\run
,
\\.\src\main.zig
,
\\-target
,
\\x86_64-windows-gnu
,
\\-O
,
\\safe
,
\\--
,
\\--emoji=🗿
,
\\--eval=new Regex("Dwayne \"The Rock\" Johnson")
,
},
\\"C:\Program Files\zig\zig.exe" run .\src\main.zig -target x86_64-windows-gnu -O safe -- --emoji=🗿 "--eval=new Regex(\"Dwayne \\\"The Rock\\\" Johnson\")"
);
try t(&.{}, "");
try t(&.{""}, "\"\"");
try t(&.{" "}, "\" \"");
try t(&.{"\t"}, "\"\t\"");
try t(&.{"\x07"}, "\"\x07\"");
try t(&.{"🦎"}, "🦎");
try t(
&.{ "zig", "aa aa", "bb\tbb", "cc\ncc", "dd\r\ndd", "ee\x7Fee" },
"zig \"aa aa\" \"bb\tbb\" \"cc\ncc\" \"dd\r\ndd\" ee\x7Fee",
);
try t(
&.{ "\\\\foo bar\\foo bar\\", "\\\\zig zag\\zig zag\\" },
"\"\\\\foo bar\\foo bar\\\" \"\\\\zig zag\\zig zag\\\\\"",
);
try std.testing.expectError(
error.InvalidArg0,
argvToCommandLineWindows(std.testing.allocator, &.{"\"quotes\"quotes\""}),
);
try std.testing.expectError(
error.InvalidArg0,
argvToCommandLineWindows(std.testing.allocator, &.{"quotes\"quotes"}),
);
try std.testing.expectError(
error.InvalidArg0,
argvToCommandLineWindows(std.testing.allocator, &.{"q u o t e s \" q u o t e s"}),
);
}
fn testArgvToCommandLineWindows(argv: []const []const u8, expected_cmd_line: []const u8) !void {
const cmd_line_w = try argvToCommandLineWindows(std.testing.allocator, argv);
defer std.testing.allocator.free(cmd_line_w);
const cmd_line = try std.unicode.wtf16LeToWtf8Alloc(std.testing.allocator, cmd_line_w);
defer std.testing.allocator.free(cmd_line);
try std.testing.expectEqualStrings(expected_cmd_line, cmd_line);
}
fn posixExecv(
arg0_expand: process.ArgExpansion,
file: [*:0]const u8,
child_argv: [*:null]?[*:0]const u8,
env_block: process.Environ.PosixBlock,
PATH: []const u8,
) process.ReplaceError {
const file_slice = std.mem.sliceTo(file, 0);
if (std.mem.findScalar(u8, file_slice, '/') != null) return posixExecvPath(file, child_argv, env_block);
// Use of PATH_MAX here is valid as the path_buf will be passed
// directly to the operating system in posixExecvPath.
var path_buf: [posix.PATH_MAX]u8 = undefined;
var it = std.mem.tokenizeScalar(u8, PATH, ':');
var seen_eacces = false;
var err: process.ReplaceError = error.FileNotFound;
// In case of expanding arg0 we must put it back if we return with an error.
const prev_arg0 = child_argv[0];
defer switch (arg0_expand) {
.expand => child_argv[0] = prev_arg0,
.no_expand => {},
};
while (it.next()) |search_path| {
const path_len = search_path.len + file_slice.len + 1;
if (path_buf.len < path_len + 1) return error.NameTooLong;
@memcpy(path_buf[0..search_path.len], search_path);
path_buf[search_path.len] = '/';
@memcpy(path_buf[search_path.len + 1 ..][0..file_slice.len], file_slice);
path_buf[path_len] = 0;
const full_path = path_buf[0..path_len :0].ptr;
switch (arg0_expand) {
.expand => child_argv[0] = full_path,
.no_expand => {},
}
err = posixExecvPath(full_path, child_argv, env_block);
switch (err) {
error.AccessDenied => seen_eacces = true,
error.FileNotFound, error.NotDir => {},
else => |e| return e,
}
}
if (seen_eacces) return error.AccessDenied;
return err;
}
/// This function ignores PATH environment variable.
pub fn posixExecvPath(
path: [*:0]const u8,
child_argv: [*:null]const ?[*:0]const u8,
env_block: process.Environ.PosixBlock,
) process.ReplaceError {
try Thread.checkCancel();
switch (posix.errno(posix.system.execve(path, child_argv, env_block.slice.ptr))) {
.FAULT => |err| return errnoBug(err), // Bad pointer parameter.
.@"2BIG" => return error.SystemResources,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.INVAL => return error.InvalidExe,
.NOEXEC => return error.InvalidExe,
.IO => return error.FileSystem,
.LOOP => return error.FileSystem,
.ISDIR => return error.IsDir,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.TXTBSY => return error.FileBusy,
else => |err| switch (native_os) {
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => switch (err) {
.BADEXEC => return error.InvalidExe,
.BADARCH => return error.InvalidExe,
else => return posix.unexpectedErrno(err),
},
.linux => switch (err) {
.LIBBAD => return error.InvalidExe,
else => return posix.unexpectedErrno(err),
},
else => return posix.unexpectedErrno(err),
},
}
}
pub const CreatePipeOptions = struct {
server: End,
client: End,
inbound: bool = false,
outbound: bool = false,
maximum_instances: u32 = 1,
quota: u32 = 4096,
default_timeout: windows.LARGE_INTEGER = -120 * std.time.ns_per_s / 100,
pub const End = struct {
attributes: windows.OBJECT.ATTRIBUTES.Flags = .{},
mode: windows.FILE.MODE,
};
};
pub fn windowsCreatePipe(t: *Threaded, options: CreatePipeOptions) ![2]windows.HANDLE {
const named_pipe_device = try t.getNamedPipeDevice();
const server_handle = server_handle: {
var handle: windows.HANDLE = undefined;
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtCreateNamedPipeFile(
&handle,
.{
.SPECIFIC = .{ .FILE_PIPE = .{
.READ_DATA = options.inbound,
.WRITE_DATA = options.outbound,
.WRITE_ATTRIBUTES = true,
} },
.STANDARD = .{ .SYNCHRONIZE = true },
},
&.{
.RootDirectory = named_pipe_device,
.Attributes = options.server.attributes,
},
&io_status_block,
.{ .READ = true, .WRITE = true },
.CREATE,
options.server.mode,
.{ .TYPE = .BYTE_STREAM },
.{ .MODE = .BYTE_STREAM },
.{ .OPERATION = .QUEUE },
options.maximum_instances,
if (options.inbound) options.quota else 0,
if (options.outbound) options.quota else 0,
&options.default_timeout,
)) {
.SUCCESS => break syscall.finish(),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.INVALID_PARAMETER => |status| return syscall.ntstatusBug(status),
.INSUFFICIENT_RESOURCES => return syscall.fail(error.SystemResources),
else => |status| return syscall.unexpectedNtstatus(status),
};
break :server_handle handle;
};
errdefer windows.CloseHandle(server_handle);
const client_handle = client_handle: {
var handle: windows.HANDLE = undefined;
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
const syscall: Syscall = try .start();
while (true) switch (windows.ntdll.NtOpenFile(
&handle,
.{
.SPECIFIC = .{ .FILE_PIPE = .{
.READ_DATA = options.outbound,
.WRITE_DATA = options.inbound,
.WRITE_ATTRIBUTES = true,
} },
.STANDARD = .{ .SYNCHRONIZE = true },
},
&.{
.RootDirectory = server_handle,
.Attributes = options.client.attributes,
},
&io_status_block,
.{ .READ = true, .WRITE = true },
options.client.mode,
)) {
.SUCCESS => break syscall.finish(),
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.INVALID_PARAMETER => |status| return syscall.ntstatusBug(status),
.INSUFFICIENT_RESOURCES => return syscall.fail(error.SystemResources),
else => |status| return syscall.unexpectedNtstatus(status),
};
break :client_handle handle;
};
errdefer windows.CloseHandle(client_handle);
return .{ server_handle, client_handle };
}
fn progressParentFile(userdata: ?*anyopaque) std.Progress.ParentFileError!File {
const t: *Threaded = @ptrCast(@alignCast(userdata));
t.scanEnviron();
return t.environ.zig_progress_file;
}
pub fn environString(t: *Threaded, comptime name: []const u8) ?[:0]const u8 {
t.scanEnviron();
return @field(t.environ.string, name);
}
fn random(userdata: ?*anyopaque, buffer: []u8) void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const thread = Thread.current orelse return randomMainThread(t, buffer);
if (!thread.csprng.isInitialized()) {
@branchHint(.unlikely);
var seed: [Csprng.seed_len]u8 = undefined;
randomMainThread(t, &seed);
thread.csprng.rng = .init(seed);
}
thread.csprng.rng.fill(buffer);
}
fn randomMainThread(t: *Threaded, buffer: []u8) void {
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
if (!t.csprng.isInitialized()) {
@branchHint(.unlikely);
var seed: [Csprng.seed_len]u8 = undefined;
{
mutexUnlock(&t.mutex);
defer mutexLock(&t.mutex);
const prev = swapCancelProtection(t, .blocked);
defer _ = swapCancelProtection(t, prev);
randomSecure(t, &seed) catch |err| switch (err) {
error.Canceled => unreachable,
error.EntropyUnavailable => fallbackSeed(t, &seed),
};
}
t.csprng.rng = .init(seed);
}
t.csprng.rng.fill(buffer);
}
pub fn fallbackSeed(aslr_addr: ?*anyopaque, seed: *[Csprng.seed_len]u8) void {
@memset(seed, 0);
std.mem.writeInt(usize, seed[seed.len - @sizeOf(usize) ..][0..@sizeOf(usize)], @intFromPtr(aslr_addr), .native);
const fallbackSeedImpl = switch (native_os) {
.windows => fallbackSeedWindows,
.wasi => if (builtin.link_libc) fallbackSeedPosix else fallbackSeedWasi,
else => fallbackSeedPosix,
};
fallbackSeedImpl(seed);
}
fn fallbackSeedPosix(seed: *[Csprng.seed_len]u8) void {
std.mem.writeInt(posix.pid_t, seed[0..@sizeOf(posix.pid_t)], posix.system.getpid(), .native);
const i_1 = @sizeOf(posix.pid_t);
var ts: posix.timespec = undefined;
const Sec = @TypeOf(ts.sec);
const Nsec = @TypeOf(ts.nsec);
const i_2 = i_1 + @sizeOf(Sec);
switch (posix.errno(posix.system.clock_gettime(.REALTIME, &ts))) {
.SUCCESS => {
std.mem.writeInt(Sec, seed[i_1..][0..@sizeOf(Sec)], ts.sec, .native);
std.mem.writeInt(Nsec, seed[i_2..][0..@sizeOf(Nsec)], ts.nsec, .native);
},
else => {},
}
}
fn fallbackSeedWindows(seed: *[Csprng.seed_len]u8) void {
var pc: windows.LARGE_INTEGER = undefined;
_ = windows.ntdll.RtlQueryPerformanceCounter(&pc);
std.mem.writeInt(windows.LARGE_INTEGER, seed[0..@sizeOf(windows.LARGE_INTEGER)], pc, .native);
}
fn fallbackSeedWasi(seed: *[Csprng.seed_len]u8) void {
var ts: std.os.wasi.timestamp_t = undefined;
if (std.os.wasi.clock_time_get(.REALTIME, 1, &ts) == .SUCCESS) {
std.mem.writeInt(std.os.wasi.timestamp_t, seed[0..@sizeOf(std.os.wasi.timestamp_t)], ts, .native);
}
}
fn randomSecure(userdata: ?*anyopaque, buffer: []u8) Io.RandomSecureError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
if (is_windows) {
if (buffer.len == 0) return;
// ProcessPrng from bcryptprimitives.dll has the following properties:
// * introduces a dependency on bcryptprimitives.dll, which apparently
// runs a test suite every time it is loaded
// * heap allocates a 48-byte buffer, handling failure by returning NO_MEMORY in a BOOL
// despite the function being documented to always return TRUE
// * reads from "\\Device\\CNG" which then seeds a per-CPU AES CSPRNG
// Therefore, that function is avoided in favor of using the device directly.
const cng_device = try getCngDevice(t);
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var i: usize = 0;
const syscall: Syscall = try .start();
while (true) {
const remaining_len = std.math.lossyCast(u32, buffer.len - i);
switch (windows.ntdll.NtDeviceIoControlFile(
cng_device,
null,
null,
null,
&io_status_block,
windows.IOCTL.KSEC.GEN_RANDOM,
null,
0,
buffer[i..].ptr,
remaining_len,
)) {
.SUCCESS => {
i += remaining_len;
if (buffer.len - i == 0) {
return syscall.finish();
} else {
try syscall.checkCancel();
continue;
}
},
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => return syscall.fail(error.EntropyUnavailable),
}
}
}
if (builtin.link_libc and @TypeOf(posix.system.arc4random_buf) != void) {
if (buffer.len == 0) return;
posix.system.arc4random_buf(buffer.ptr, buffer.len);
return;
}
if (native_os == .wasi) {
if (buffer.len == 0) return;
const syscall: Syscall = try .start();
while (true) switch (std.os.wasi.random_get(buffer.ptr, buffer.len)) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
else => return syscall.fail(error.EntropyUnavailable),
};
}
if (@TypeOf(posix.system.getrandom) != void) {
const getrandom = if (use_libc_getrandom) std.c.getrandom else std.os.linux.getrandom;
var i: usize = 0;
const syscall: Syscall = try .start();
while (buffer.len - i != 0) {
const buf = buffer[i..];
const rc = getrandom(buf.ptr, buf.len, 0);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
const n: usize = @intCast(rc);
i += n;
continue;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => return syscall.fail(error.EntropyUnavailable),
}
}
return;
}
if (native_os == .emscripten) {
if (buffer.len == 0) return;
const err = posix.errno(std.c.getentropy(buffer.ptr, buffer.len));
switch (err) {
.SUCCESS => return,
else => return error.EntropyUnavailable,
}
}
if (native_os == .linux) {
comptime assert(use_dev_urandom);
const urandom_fd = try getRandomFd(t);
var i: usize = 0;
while (buffer.len - i != 0) {
const syscall: Syscall = try .start();
const rc = posix.system.read(urandom_fd, buffer[i..].ptr, buffer.len - i);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
const n: usize = @intCast(rc);
if (n == 0) return error.EntropyUnavailable;
i += n;
continue;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => return syscall.fail(error.EntropyUnavailable),
}
}
}
return error.EntropyUnavailable;
}
fn getRandomFd(t: *Threaded) Io.RandomSecureError!posix.fd_t {
{
mutexLock(&t.mutex);
defer mutexUnlock(&t.mutex);
if (t.random_file.fd == -2) return error.EntropyUnavailable;
if (t.random_file.fd != -1) return t.random_file.fd;
}
const mode: posix.mode_t = 0;
const fd: posix.fd_t = fd: {
const syscall: Syscall = try .start();
while (true) {
const rc = openat_sym(posix.AT.FDCWD, "/dev/urandom", .{
.ACCMODE = .RDONLY,
.CLOEXEC = true,
}, mode);
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
break :fd @intCast(rc);
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => return syscall.fail(error.EntropyUnavailable),
}
}
};
errdefer closeFd(fd);
switch (native_os) {
.linux => {
const sys = if (statx_use_c) std.c else std.os.linux;
const syscall: Syscall = try .start();
while (true) {
var statx = std.mem.zeroes(std.os.linux.Statx);
switch (sys.errno(sys.statx(fd, "", std.os.linux.AT.EMPTY_PATH, .{ .TYPE = true }, &statx))) {
.SUCCESS => {
syscall.finish();
if (!statx.mask.TYPE) return error.EntropyUnavailable;
mutexLock(&t.mutex); // Another thread might have won the race.
defer mutexUnlock(&t.mutex);
if (t.random_file.fd >= 0) {
closeFd(fd);
return t.random_file.fd;
} else if (!posix.S.ISCHR(statx.mode)) {
t.random_file.fd = -2;
return error.EntropyUnavailable;
} else {
t.random_file.fd = fd;
return fd;
}
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => return syscall.fail(error.EntropyUnavailable),
}
}
},
else => {
const syscall: Syscall = try .start();
while (true) {
var stat = std.mem.zeroes(posix.Stat);
switch (posix.errno(fstat_sym(fd, &stat))) {
.SUCCESS => {
syscall.finish();
mutexLock(&t.mutex); // Another thread might have won the race.
defer mutexUnlock(&t.mutex);
if (t.random_file.fd >= 0) {
closeFd(fd);
return t.random_file.fd;
} else if (!posix.S.ISCHR(stat.mode)) {
t.random_file.fd = -2;
return error.EntropyUnavailable;
} else {
t.random_file.fd = fd;
return fd;
}
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => return syscall.fail(error.EntropyUnavailable),
}
}
},
}
}
test {
_ = @import("Threaded/test.zig");
}
const use_parking_futex = switch (native_os) {
.windows => true, // RtlWaitOnAddress is a userland implementation anyway
.netbsd => true, // NetBSD has `futex(2)`, but it's historically been quite buggy. TODO: evaluate whether it's okay to use now.
.illumos => true, // Illumos has no futex mechanism
.haiku => true, // Haiku has no futex mechanism
else => false,
};
const use_parking_sleep = switch (native_os) {
// On Windows, we can implement sleep either with `NtDelayExecution` (which is how `SleepEx` in
// kernel32 works) or `NtWaitForAlertByThreadId` (thread parking). We're already using the
// latter for futex, so we may as well use it for sleeping too, to maximise code reuse. I'm
// also more confident that it will always correctly handle the cancelation race (so "unpark"
// before "park" causes "park" to return immediately): it *seems* like alertable sleeps paired
// with `NtAlertThread` do actually do this too, but there could be some caveat (e.g. it might
// fail under some specific condition), whereas `NtWaitForAlertByThreadId` must reliably trigger
// this behavior because `RtlWaitOnAddress` relies on it.
.windows => true,
// These targets have `_lwp_park`, which is superior to POSIX nanosleep because it has a better
// cancelation mechanism.
.netbsd,
.illumos,
=> true,
else => false,
};
const parking_futex = struct {
comptime {
assert(use_parking_futex);
}
const Bucket = struct {
/// Used as a fast check for `wake` to avoid having to acquire `mutex` to discover there are no
/// waiters. It is important for `wait` to increment this *before* checking the futex value to
/// avoid a race.
num_waiters: std.atomic.Value(u32),
/// Protects `waiters`.
mutex: ParkingMutex,
waiters: std.DoublyLinkedList,
/// Prevent false sharing between buckets.
_: void align(std.atomic.cache_line) = {},
const init: Bucket = .{ .num_waiters = .init(0), .mutex = .init, .waiters = .{} };
};
const Waiter = struct {
node: std.DoublyLinkedList.Node,
address: usize,
tid: ParkTid,
/// `thread_status.cancelation` is `.parked` while the thread is waiting. The single thread
/// which atomically updates it (to `.none` or `.canceling`) is responsible for:
///
/// * Removing the `Waiter` from `Bucket.waiters`
/// * Decrementing `Bucket.num_waiters`
/// * Unparking the thread (*after* the above, so that the `Waiter` does not go out of scope
/// while it is still in the `Bucket`).
thread_status: *std.atomic.Value(Thread.Status),
unpark_flag: if (need_unpark_flag) *UnparkFlag else void,
};
fn bucketForAddress(address: usize) *Bucket {
const global = struct {
/// Length must be a power of two. The longer this array, the less likely contention is
/// between different futexes. This length seems like it'll provide a reasonable balance
/// between contention and memory usage: assuming a 128-byte `Bucket` (due to cache line
/// alignment), this uses 32 KiB of memory.
var buckets: [256]Bucket = @splat(.init);
};
// Here we use Fibonacci hashing: the golden ratio can be used to evenly redistribute input
// values across a range, giving a poor, but extremely quick to compute, hash.
// This literal is the rounded value of '2^64 / phi' (where 'phi' is the golden ratio). The
// shift then converts it to '2^b / phi', where 'b' is the pointer bit width.
const fibonacci_multiplier = 0x9E3779B97F4A7C15 >> (64 - @bitSizeOf(usize));
const hashed = address *% fibonacci_multiplier;
comptime assert(std.math.isPowerOfTwo(global.buckets.len));
// The high bits of `hashed` have better entropy than the low bits.
const index = hashed >> (@bitSizeOf(usize) - @ctz(global.buckets.len));
return &global.buckets[index];
}
fn wait(ptr: *const u32, expect: u32, uncancelable: bool, timeout: Io.Timeout) Io.Cancelable!void {
const bucket = bucketForAddress(@intFromPtr(ptr));
// Put the threadlocal access outside of the critical section.
const opt_thread = Thread.current;
const self_tid = getParkTid();
var waiter: Waiter = .{
.node = undefined, // populated by list append
.address = @intFromPtr(ptr),
.tid = self_tid,
.thread_status = undefined, // populated in critical section
.unpark_flag = undefined, // populated in critical section
};
var status_buf: std.atomic.Value(Thread.Status) = undefined;
var unpark_flag_buf: UnparkFlag = unpark_flag_init;
{
bucket.mutex.lock();
defer bucket.mutex.unlock();
_ = bucket.num_waiters.fetchAdd(1, .acquire);
if (@atomicLoad(u32, ptr, .monotonic) != expect) {
assert(bucket.num_waiters.fetchSub(1, .monotonic) > 0);
return;
}
// This is in the critical section to avoid marking the thread as parked until we're
// certain that we're actually going to park.
waiter.thread_status, waiter.unpark_flag = status: {
cancelable: {
if (uncancelable) break :cancelable;
const thread = opt_thread orelse break :cancelable;
switch (thread.cancel_protection) {
.blocked => break :cancelable,
.unblocked => {},
}
thread.futex_waiter = &waiter;
const old_status = thread.status.fetchOr(
.{ .cancelation = @fromBackingInt(@intCast(0b001)), .awaitable = .null },
.release, // release `thread.futex_waiter`
);
switch (old_status.cancelation) {
.none => {}, // status is now `.parked`
.canceling => {
// status is now `.canceled`
assert(bucket.num_waiters.fetchSub(1, .monotonic) > 0);
return error.Canceled;
},
.canceled => break :cancelable, // status is still `.canceled`
.parked => unreachable,
.blocked => unreachable,
.blocked_alertable => unreachable,
.blocked_alertable_canceling => unreachable,
.blocked_canceling => unreachable,
}
// We could now be unparked for a cancelation at any time!
break :status .{ &thread.status, if (need_unpark_flag) &thread.unpark_flag };
}
// This is an uncancelable wait, so just use `status_buf`. Note that the value of
// `status_buf.awaitable` is irrelevant because this is only visible to futex code,
// while only cancelation cares about `awaitable`.
status_buf.raw = .{ .cancelation = .parked, .awaitable = .null };
break :status .{ &status_buf, if (need_unpark_flag) &unpark_flag_buf };
};
bucket.waiters.append(&waiter.node);
}
if (park(timeout, ptr, waiter.unpark_flag)) {
// We were unparked by either `wake` or cancelation, so our current status is either
// `.none` or `.canceling`. In either case, they've already removed `waiter` from
// `bucket`, so we have nothing more to do!
} else |err| switch (err) {
error.Timeout => {
// We're not out of the woods yet: an unpark could race with the timeout.
const old_status = waiter.thread_status.fetchAnd(
.{ .cancelation = @fromBackingInt(@intCast(0b110)), .awaitable = .all_ones },
.monotonic,
);
switch (old_status.cancelation) {
.parked => {
// No race. It is our responsibility to remove `waiter` from `bucket`.
// New status is `.none`.
bucket.mutex.lock();
defer bucket.mutex.unlock();
bucket.waiters.remove(&waiter.node);
assert(bucket.num_waiters.fetchSub(1, .monotonic) > 0);
},
.none, .canceling => {
// Race condition: the timeout was reached, then `wake` or a canceler tried
// to unpark us. Whoever did that will remove us from `bucket`. Wait for
// that (and drop the unpark request in doing so).
// New status is `.none` or `.canceling` respectively.
park(.none, ptr, waiter.unpark_flag) catch |e| switch (e) {
error.Timeout => unreachable,
};
},
.canceled => unreachable,
.blocked => unreachable,
.blocked_alertable => unreachable,
.blocked_canceling => unreachable,
.blocked_alertable_canceling => unreachable,
}
},
}
}
fn wake(ptr: *const u32, max_waiters: u32) void {
if (max_waiters == 0) return;
const bucket = bucketForAddress(@intFromPtr(ptr));
// To ensure the store to `ptr` is ordered before this check, we effectively want a `.release`
// load, but that doesn't exist in the C11 memory model, so emulate it with a non-mutating rmw.
if (bucket.num_waiters.fetchAdd(0, .release) == 0) {
@branchHint(.likely);
return; // no waiters
}
// Waiters removed from the linked list under the mutex so we can unpark their threads outside
// of the critical section. This forms a singly-linked list of waiters using `Waiter.node.next`.
var waking_head: ?*std.DoublyLinkedList.Node = null;
{
bucket.mutex.lock();
defer bucket.mutex.unlock();
var num_removed: u32 = 0;
var it = bucket.waiters.first;
while (num_removed < max_waiters) {
const waiter: *Waiter = @fieldParentPtr("node", it orelse break);
it = waiter.node.next;
if (waiter.address != @intFromPtr(ptr)) continue;
const old_status = waiter.thread_status.fetchAnd(
.{ .cancelation = @fromBackingInt(@intCast(0b110)), .awaitable = .all_ones },
.monotonic,
);
switch (old_status.cancelation) {
.parked => {}, // state updated to `.none`
.none => continue, // race with timeout; they are about to lock `bucket.mutex` and remove themselves from the bucket
.canceling => continue, // race with a canceler who hasn't called `removeCanceledWaiter` yet
.canceled => unreachable,
.blocked => unreachable,
.blocked_alertable => unreachable,
.blocked_alertable_canceling => unreachable,
.blocked_canceling => unreachable,
}
// We're waking this waiter. Remove them from the bucket and add them to our local list.
bucket.waiters.remove(&waiter.node);
waiter.node.next = waking_head;
waking_head = &waiter.node;
num_removed += 1;
}
_ = bucket.num_waiters.fetchSub(num_removed, .monotonic);
}
var unpark_buf: [128]UnparkTid = undefined;
var unpark_len: usize = 0;
// Finally, unpark the threads.
while (waking_head) |node| {
waking_head = node.next;
const waiter: *Waiter = @fieldParentPtr("node", node);
unpark_buf[unpark_len] = waiter.tid;
if (need_unpark_flag) setUnparkFlag(waiter.unpark_flag);
unpark_len += 1;
if (unpark_len == unpark_buf.len) {
unpark(&unpark_buf, ptr);
unpark_len = 0;
}
}
if (unpark_len > 0) {
unpark(unpark_buf[0..unpark_len], ptr);
}
}
fn removeCanceledWaiter(waiter: *Waiter) void {
const bucket = bucketForAddress(waiter.address);
bucket.mutex.lock();
defer bucket.mutex.unlock();
bucket.waiters.remove(&waiter.node);
assert(bucket.num_waiters.fetchSub(1, .monotonic) > 0);
}
};
const parking_sleep = struct {
comptime {
assert(use_parking_sleep);
}
fn sleep(timeout: Io.Timeout) Io.Cancelable!void {
const opt_thread = Thread.current;
cancelable: {
const thread = opt_thread orelse break :cancelable;
switch (thread.cancel_protection) {
.blocked => break :cancelable,
.unblocked => {},
}
thread.futex_waiter = null;
{
const old_status = thread.status.fetchOr(
.{ .cancelation = @fromBackingInt(@intCast(0b001)), .awaitable = .null },
.release, // release `thread.futex_waiter`
);
switch (old_status.cancelation) {
.none => {}, // status is now `.parked`
.canceling => return error.Canceled, // status is now `.canceled`
.canceled => break :cancelable, // status is still `.canceled`
.parked => unreachable,
.blocked => unreachable,
.blocked_alertable => unreachable,
.blocked_alertable_canceling => unreachable,
.blocked_canceling => unreachable,
}
}
if (park(timeout, null, if (need_unpark_flag) &thread.unpark_flag)) {
// The only reason this could possibly happen is cancelation.
const old_status = thread.status.load(.monotonic);
assert(old_status.cancelation == .canceling);
thread.status.store(
.{ .cancelation = .canceled, .awaitable = old_status.awaitable },
.monotonic,
);
return error.Canceled;
} else |err| switch (err) {
error.Timeout => {
// We're not out of the woods yet: an unpark could race with the timeout.
const old_status = thread.status.fetchAnd(
.{ .cancelation = @fromBackingInt(@intCast(0b110)), .awaitable = .all_ones },
.monotonic,
);
switch (old_status.cancelation) {
.parked => return, // No race; new status is `.none`
.canceling => {
// Race condition: the timeout was reached, then someone tried to unpark
// us for a cancelation. Whoever did that will have called `unpark`, so
// drop that unpark request by waiting for it.
// Status is still `.canceling`.
park(.none, null, if (need_unpark_flag) &thread.unpark_flag) catch |e| switch (e) {
error.Timeout => unreachable,
};
return;
},
.none => unreachable,
.canceled => unreachable,
.blocked => unreachable,
.blocked_alertable => unreachable,
.blocked_canceling => unreachable,
.blocked_alertable_canceling => unreachable,
}
},
}
}
// Uncancelable sleep; we expect not to be manually unparked.
// On systems where parking the thread requires a one-time setup operation (e.g. creating a
// semaphore), we need to ensure that setup is done before we call `park`.
_ = getParkTid();
var dummy_flag: UnparkFlag = unpark_flag_init;
if (park(timeout, null, if (need_unpark_flag) &dummy_flag)) {
unreachable; // unexpected unpark
} else |err| switch (err) {
error.Timeout => return,
}
}
};
const ParkingMutex = struct {
state: std.atomic.Value(State),
const init: ParkingMutex = .{ .state = .init(.unlocked) };
comptime {
assert(use_parking_futex);
}
const State = enum(usize) {
unlocked = 1,
/// This value is intentionally 0 so that `waiter` returns `null`.
locked_once = 0,
/// Contended; value is a `*Waiter`.
_,
/// Returns the head of the waiter list. Illegal to call if `s == .unlocked`.
fn waiter(s: State) ?*Waiter {
return @ptrFromInt(@backingInt(s));
}
/// Returns a locked state where `w` is contending the lock.
/// If `w` is `null`, returns `.locked_once`.
fn fromWaiter(w: ?*Waiter) State {
return @fromBackingInt(@intCast(@intFromPtr(w)));
}
};
const Waiter = struct {
unpark_flag: UnparkFlag,
/// Never modified once the `Waiter` is in the linked list.
next: ?*Waiter,
/// Never modified once the `Waiter` is in the linked list.
tid: ParkTid,
};
fn lock(m: *ParkingMutex) void {
state: switch (State.unlocked) { // assume 'unlocked' to optimize for uncontended case
.unlocked => continue :state m.state.cmpxchgWeak(
.unlocked,
.locked_once,
.acquire, // acquire lock
.monotonic,
) orelse {
@branchHint(.likely);
return;
},
.locked_once, _ => |last_state| {
const old_waiter = last_state.waiter();
const self_tid = getParkTid();
var waiter: Waiter = .{
.next = old_waiter,
.unpark_flag = unpark_flag_init,
.tid = self_tid,
};
if (m.state.cmpxchgWeak(
.fromWaiter(old_waiter),
.fromWaiter(&waiter),
.release, // release `waiter`
.monotonic,
)) |new_state| {
continue :state new_state;
}
// We're now in the list of waiters---park until we're given the lock.
park(.none, m, if (need_unpark_flag) &waiter.unpark_flag) catch |err| switch (err) {
error.Timeout => unreachable,
};
return;
},
}
}
fn unlock(m: *ParkingMutex) void {
state: switch (State.locked_once) { // assume 'locked_once' to optimize for uncontended case
.unlocked => unreachable, // we hold the lock
.locked_once => continue :state m.state.cmpxchgWeak(
.locked_once,
.unlocked,
.release, // release lock
.acquire, // acquire any `Waiter` memory
) orelse {
@branchHint(.likely);
return;
},
_ => |last_state| {
// The logic here does not have ABA problems, and does some accesses non-atomically,
// because `Waiter.next` is owned by the lock holder (that's us!) once the waiter is
// in the linked list, up until we unpark the waiter.
// Run through the waiter list to the end to ensure fairness. This is obviously not
// ideal, but it shouldn't be a big deal in practice provided the critical section
// is fairly small (so we won't get too many threads contending the mutex at once).
// There's a *chance* we could get away with a LIFO queue for our use case, but I
// don't wanna risk that.
var parent: ?*Waiter = null;
var waiter: *Waiter = last_state.waiter().?;
while (waiter.next) |next| {
parent = waiter;
waiter = next;
}
// `waiter` is next in line for the lock. Remove them from the list.
if (parent) |p| {
assert(p.next == waiter);
p.next = null;
} else {
// We're waking the last waiter, so clear the list head.
if (m.state.cmpxchgWeak(
.fromWaiter(last_state.waiter().?),
.locked_once,
.acquire,
.acquire, // acquire any new `Waiter` memory
)) |new_state| {
continue :state new_state;
}
}
// Now we're ready to actually hand the lock over to them.
const tid = waiter.tid; // load before the unpark below potentially invalidates `waiter`
if (need_unpark_flag) setUnparkFlag(&waiter.unpark_flag);
unpark(&.{tid}, m);
return;
},
}
}
};
fn timeoutToWindowsInterval(timeout: Io.Timeout) ?windows.LARGE_INTEGER {
// ntdll only supports two combinations:
// * real-time (`.real`) sleeps with absolute deadlines
// * monotonic (`.awake`/`.boot`) sleeps with relative durations
const clock = switch (timeout) {
.none => return null,
.duration => |d| d.clock,
.deadline => |d| d.clock,
};
switch (clock) {
.cpu_process, .cpu_thread => unreachable, // cannot sleep for CPU time
.real => {
const deadline = switch (timeout) {
.none => unreachable,
.duration => |d| nowWindows(clock).addDuration(d.raw),
.deadline => |d| d.raw,
};
const epoch_ns = std.time.epoch.windows * std.time.ns_per_s;
return @intCast(@max(@divTrunc(deadline.nanoseconds - epoch_ns, 100), 0));
},
.awake, .boot => {
const duration = switch (timeout) {
.none => unreachable,
.duration => |d| d.raw,
.deadline => |d| nowWindows(clock).durationTo(d.raw),
};
return @intCast(@min(@divTrunc(-duration.nanoseconds, 100), -1));
},
}
}
/// The API on NetBSD and Illumos sucks and can unpark spuriously (well, it *can't*, but signals
/// cause an indistinguishable unblock, and libpthread really likes to leave unparks pending).
/// As such, on these targets only, we need to pass around a flag to track whether a thread is
/// "actually" being unparked.
const need_unpark_flag = switch (native_os) {
.netbsd, .illumos => true,
else => false,
};
const UnparkFlag = if (need_unpark_flag) std.atomic.Value(bool) else void;
const unpark_flag_init: UnparkFlag = if (need_unpark_flag) .init(false);
/// Must be called before `unpark`. After this function is called, the thread may be unparked at any
/// time, so the caller must not reference values on its stack.
fn setUnparkFlag(f: *UnparkFlag) void {
f.store(true, .release);
}
/// The type passed into `unpark` for the thread ID. You'd think this was just a `std.Thread.Id`,
/// but it seems that someone at Microsoft forgot how big their TIDs are supposed to be.
const UnparkTid = switch (native_os) {
.windows => usize,
else => ParkTid,
};
const ParkTid = switch (native_os) {
.haiku => std.c.sem_id,
else => std.Thread.Id,
};
threadlocal var park_sem: std.c.sem_id = -1;
fn getParkTid() ParkTid {
switch (native_os) {
.haiku => {
if (park_sem == -1) {
park_sem = std.c._kern_create_sem(0, null);
if (park_sem < 0) @panic("_kern_create_sem failed");
_ = std.c.on_exit_thread(destroyParkSem, null);
}
return park_sem;
},
else => {
return if (Thread.current) |thread| thread.id else std.Thread.getCurrentId();
},
}
}
fn destroyParkSem(_: ?*anyopaque) callconv(.c) void {
_ = std.c._kern_delete_sem(park_sem);
}
fn park(
timeout: Io.Timeout,
/// This value has no semantic effect, but may allow the OS to optimize the operation.
addr_hint: ?*const anyopaque,
unpark_flag: if (need_unpark_flag) *UnparkFlag else void,
) error{Timeout}!void {
comptime assert(use_parking_futex or use_parking_sleep);
switch (native_os) {
.windows => {
const raw_timeout = timeoutToWindowsInterval(timeout);
// `RtlWaitOnAddress` passes the futex address in as the first argument to this call,
// but it's unclear what that actually does, especially since `NtAlertThreadByThreadId`
// does *not* accept the address so the kernel can't really be using it as a hint. An
// old Microsoft blog post discusses a more traditional futex-like mechanism in the
// kernel which definitely isn't how `RtlWaitOnAddress` works today:
//
// https://devblogs.microsoft.com/oldnewthing/20160826-00/?p=94185
//
// ...so it's possible this argument is simply a remnant which no longer does anything
// (perhaps the implementation changed during development but someone forgot to remove
// this parameter). However, to err on the side of caution, let's match the behavior of
// `RtlWaitOnAddress` and pass the pointer, in case the kernel ever does something
// stupid such as trying to dereference it.
switch (windows.ntdll.NtWaitForAlertByThreadId(
addr_hint,
if (raw_timeout) |*t| t else null,
)) {
.ALERTED => return,
.TIMEOUT => return error.Timeout,
else => unreachable,
}
},
.netbsd => {
var ts_buf: posix.timespec = undefined;
const ts: ?*posix.timespec, const abstime: bool, const clock_real: bool = switch (timeout) {
.none => .{ null, false, false },
.deadline => |timestamp| timeout: {
ts_buf = timestampToPosix(timestamp.raw.nanoseconds);
break :timeout .{ &ts_buf, true, timestamp.clock == .real };
},
.duration => |duration| timeout: {
ts_buf = timestampToPosix(duration.raw.nanoseconds);
break :timeout .{ &ts_buf, false, duration.clock == .real };
},
};
// It's okay to pass the same timeout in a loop. If it's a duration, the OS actually
// writes the remaining time into the buffer when the syscall returns.
while (!unpark_flag.swap(false, .acquire)) {
switch (posix.errno(std.c._lwp_park(
if (clock_real) .REALTIME else .MONOTONIC,
.{ .ABSTIME = abstime },
ts,
0,
addr_hint,
null,
))) {
.SUCCESS, .ALREADY, .INTR => {},
.TIMEDOUT => return error.Timeout,
.INVAL => unreachable,
.SRCH => unreachable,
else => unreachable,
}
}
},
.illumos => @panic("TODO: illumos lwp_park"),
.haiku => {
const timeout_flags: u32, const timeout_us = switch (timeout) {
.none => .{ 0, 0 },
.deadline => |deadline| .{
if (deadline.clock == .real) std.c.B_ABSOLUTE_TIMEOUT | std.c.B_TIMEOUT_REAL_TIME_BASE else std.c.B_ABSOLUTE_TIMEOUT,
deadline.raw.toMicroseconds(),
},
.duration => |duration| .{
if (duration.clock == .real) std.c.B_ABSOLUTE_TIMEOUT | std.c.B_TIMEOUT_REAL_TIME_BASE else std.c.B_ABSOLUTE_TIMEOUT,
nowPosix(duration.clock).addDuration(duration.raw).toMicroseconds(),
},
};
while (true) {
switch (std.c._kern_acquire_sem_etc(park_sem, 1, timeout_flags, timeout_us)) {
0 => return,
std.c.E.B_TIMED_OUT => return error.Timeout,
std.c.E.B_INTERRUPTED => {},
else => unreachable,
}
}
},
else => comptime unreachable,
}
}
/// `addr_hint` has no semantic effect, but may allow the OS to optimize this operation.
fn unpark(tids: []const UnparkTid, addr_hint: ?*const anyopaque) void {
comptime assert(use_parking_futex or use_parking_sleep);
switch (native_os) {
.windows => {
// TODO: this condition is currently disabled because mingw-w64 does not contain this
// symbol. Once it's added, enable this check to use the new bulk API where possible.
if (false and (builtin.os.version_range.windows.isAtLeast(.win11_dt) orelse false)) {
_ = windows.ntdll.NtAlertMultipleThreadByThreadId(tids.ptr, @intCast(tids.len), null, null);
} else {
for (tids) |tid| {
_ = windows.ntdll.NtAlertThreadByThreadId(@intCast(tid));
}
}
},
.netbsd => {
switch (posix.errno(std.c._lwp_unpark_all(@ptrCast(tids.ptr), tids.len, addr_hint))) {
.SUCCESS => return,
// For errors, fall through to a loop over `tids`, though this is only expected to
// be possible for ENOMEM (even that is questionable) and ESRCH (see comment below).
.SRCH => {},
.FAULT => recoverableOsBugDetected(),
.INVAL => recoverableOsBugDetected(),
.NOMEM => {},
else => recoverableOsBugDetected(),
}
for (tids) |tid| {
switch (posix.errno(std.c._lwp_unpark(@bitCast(tid), addr_hint))) {
.SUCCESS => {},
.SRCH => {
// This can happen in a rare race: the thread might have been spuriously
// unparked, so already observed the changing status, and from there have
// exited. That's okay, because the thread has woken up like we wanted.
},
else => recoverableOsBugDetected(),
}
}
},
.illumos => @panic("TODO: illumos lwp_unpark"),
.haiku => {
for (tids) |tid| {
switch (std.c._kern_release_sem_etc(tid, 1, 0)) {
0 => {},
else => recoverableOsBugDetected(),
}
}
},
else => comptime unreachable,
}
}
pub const PipeError = error{
SystemFdQuotaExceeded,
ProcessFdQuotaExceeded,
} || Io.UnexpectedError;
pub fn pipe2(flags: posix.O) PipeError![2]posix.fd_t {
var fds: [2]posix.fd_t = undefined;
if (@TypeOf(posix.system.pipe2) != void) {
switch (posix.errno(posix.system.pipe2(&fds, flags))) {
.SUCCESS => return fds,
.INVAL => |err| return errnoBug(err), // Invalid flags
.NFILE => return error.SystemFdQuotaExceeded,
.MFILE => return error.ProcessFdQuotaExceeded,
else => |err| return posix.unexpectedErrno(err),
}
}
switch (posix.errno(posix.system.pipe(&fds))) {
.SUCCESS => {},
.NFILE => return error.SystemFdQuotaExceeded,
.MFILE => return error.ProcessFdQuotaExceeded,
else => |err| return posix.unexpectedErrno(err),
}
errdefer {
closeFd(fds[0]);
closeFd(fds[1]);
}
// https://github.com/ziglang/zig/issues/18882
if (@as(u32, @bitCast(flags)) == 0) return fds;
// CLOEXEC is special, it's a file descriptor flag and must be set using
// F.SETFD.
if (flags.CLOEXEC) for (fds) |fd| {
switch (posix.errno(posix.system.fcntl(fd, posix.F.SETFD, @as(u32, posix.FD_CLOEXEC)))) {
.SUCCESS => {},
else => |err| return posix.unexpectedErrno(err),
}
};
const new_flags: u32 = f: {
var new_flags = flags;
new_flags.CLOEXEC = false;
break :f @bitCast(new_flags);
};
// Set every other flag affecting the file status using F.SETFL.
if (new_flags != 0) for (fds) |fd| {
switch (posix.errno(posix.system.fcntl(fd, posix.F.SETFL, new_flags))) {
.SUCCESS => {},
.INVAL => |err| return errnoBug(err),
else => |err| return posix.unexpectedErrno(err),
}
};
return fds;
}
pub const DupError = error{
ProcessFdQuotaExceeded,
SystemResources,
} || Io.UnexpectedError || Io.Cancelable;
pub fn dup2(old_fd: posix.fd_t, new_fd: posix.fd_t) DupError!void {
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.dup2(old_fd, new_fd))) {
.SUCCESS => return syscall.finish(),
.BUSY, .INTR => {
try syscall.checkCancel();
continue;
},
.INVAL => |err| return syscall.errnoBug(err), // invalid parameters
.BADF => |err| return syscall.errnoBug(err), // use after free
.MFILE => return syscall.fail(error.ProcessFdQuotaExceeded),
.NOMEM => return syscall.fail(error.SystemResources),
else => |err| return syscall.unexpectedErrno(err),
};
}
pub const FchdirError = error{
AccessDenied,
NotDir,
FileSystem,
} || Io.Cancelable || Io.UnexpectedError;
pub fn fchdir(fd: posix.fd_t) FchdirError!void {
if (fd == posix.AT.FDCWD) return;
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.fchdir(fd))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
.ACCES => return syscall.fail(error.AccessDenied),
.NOTDIR => return syscall.fail(error.NotDir),
.IO => return syscall.fail(error.FileSystem),
.BADF => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
};
}
pub const ChdirError = error{
AccessDenied,
FileSystem,
SymLinkLoop,
NameTooLong,
FileNotFound,
SystemResources,
NotDir,
BadPathName,
} || Io.Cancelable || Io.UnexpectedError;
pub fn chdir(dir_path: []const u8) ChdirError!void {
var path_buffer: [posix.PATH_MAX]u8 = undefined;
const dir_path_posix = try pathToPosix(dir_path, &path_buffer);
const syscall: Syscall = try .start();
while (true) switch (posix.errno(posix.system.chdir(dir_path_posix))) {
.SUCCESS => return syscall.finish(),
.INTR => {
try syscall.checkCancel();
continue;
},
.ACCES => return syscall.fail(error.AccessDenied),
.IO => return syscall.fail(error.FileSystem),
.LOOP => return syscall.fail(error.SymLinkLoop),
.NAMETOOLONG => return syscall.fail(error.NameTooLong),
.NOENT => return syscall.fail(error.FileNotFound),
.NOMEM => return syscall.fail(error.SystemResources),
.NOTDIR => return syscall.fail(error.NotDir),
.ILSEQ => return syscall.fail(error.BadPathName),
.FAULT => |err| return syscall.errnoBug(err),
else => |err| return syscall.unexpectedErrno(err),
};
}
fn fileMemoryMapCreate(
userdata: ?*anyopaque,
file: File,
options: File.MemoryMap.CreateOptions,
) File.MemoryMap.CreateError!File.MemoryMap {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const offset = options.offset;
const len = options.len;
if (!t.disable_memory_mapping) {
if (createFileMap(file, options.protection, offset, options.populate, len)) |result| {
return result;
} else |err| switch (err) {
error.Unseekable, error.Canceled, error.AccessDenied => |e| return e,
error.OperationUnsupported => {},
else => {
if (builtin.mode == .debug)
std.log.warn("memory mapping failed with {t}, falling back to file operations", .{err});
},
}
}
const gpa = t.allocator;
const page_size = std.heap.pageSize();
const alignment: Alignment = .fromByteUnits(page_size);
const memory = m: {
const ptr = gpa.rawAlloc(len, alignment, @returnAddress()) orelse return error.OutOfMemory;
break :m ptr[0..len];
};
errdefer gpa.rawFree(memory, alignment, @returnAddress());
if (!options.undefined_contents) try mmSyncRead(file, memory, offset);
return .{
.file = file,
.offset = offset,
.memory = @alignCast(memory),
.section = null,
};
}
const CreateFileMapError = error{
/// MaximumSize is greater than the system-defined maximum for sections, or
/// greater than the specified file and the section is not writable.
SectionOversize,
/// A file descriptor refers to a non-regular file. Or a file mapping was requested,
/// but the file descriptor is not open for reading. Or `MAP.SHARED` was requested
/// and `PROT_WRITE` is set, but the file descriptor is not open in `RDWR` mode.
/// Or `PROT_WRITE` is set, but the file is append-only.
AccessDenied,
/// The `prot` argument asks for `PROT_EXEC` but the mapped area belongs to a file on
/// a filesystem that was mounted no-exec.
PermissionDenied,
FileBusy,
LockedMemoryLimitExceeded,
OperationUnsupported,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
OutOfMemory,
MappingAlreadyExists,
Unseekable,
LockViolation,
} || Io.Cancelable || Io.UnexpectedError;
fn createFileMap(
file: File,
protection: std.process.MemoryProtection,
offset: u64,
populate: bool,
len: usize,
) CreateFileMapError!File.MemoryMap {
if (is_windows) {
try Thread.checkCancel();
var section = windows.INVALID_HANDLE_VALUE;
const section_size: windows.LARGE_INTEGER = @intCast(len);
const page = windows.PAGE.fromProtection(protection) orelse return error.AccessDenied;
switch (windows.ntdll.NtCreateSection(
§ion,
.{
.SPECIFIC = .{ .SECTION = .{
.QUERY = true,
.MAP_WRITE = protection.write,
.MAP_READ = protection.read,
.MAP_EXECUTE = protection.execute,
.EXTEND_SIZE = true,
} },
.STANDARD = .{ .RIGHTS = .REQUIRED },
},
null,
§ion_size,
page,
.{ .COMMIT = populate },
file.handle,
)) {
.SUCCESS => {},
.FILE_LOCK_CONFLICT => return error.LockViolation,
.INVALID_FILE_FOR_SECTION => return error.OperationUnsupported,
.ACCESS_DENIED => return error.AccessDenied,
.SECTION_TOO_BIG => return error.SectionOversize,
else => |status| return windows.unexpectedStatus(status),
}
var contents_ptr: ?[*]align(std.heap.page_size_min) u8 = null;
var contents_len = len;
switch (windows.ntdll.NtMapViewOfSection(
section,
windows.current_process,
@ptrCast(&contents_ptr),
null,
0,
null,
&contents_len,
.Unmap,
.{},
page,
)) {
.SUCCESS => {},
.CONFLICTING_ADDRESSES => return error.MappingAlreadyExists,
.SECTION_PROTECTION => return error.PermissionDenied,
.ACCESS_DENIED => return error.AccessDenied,
.INVALID_VIEW_SIZE => |status| return windows.statusBug(status),
else => |status| return windows.unexpectedStatus(status),
}
if (builtin.mode == .debug) {
const page_size = std.heap.pageSize();
const alignment: Alignment = .fromByteUnits(page_size);
assert(contents_len == alignment.forward(len));
}
return .{
.file = file,
.offset = offset,
.memory = contents_ptr.?[0..len],
.section = section,
};
} else if (have_mmap) {
const prot: posix.PROT = .{
.READ = protection.read,
.WRITE = protection.write,
.EXEC = protection.execute,
};
const flags: posix.MAP = switch (native_os) {
.linux => .{
.TYPE = .SHARED_VALIDATE,
.POPULATE = populate,
},
else => .{
.TYPE = .SHARED,
},
};
const page_align = std.heap.page_size_min;
const contents = while (true) {
const syscall: Syscall = try .start();
const casted_offset = std.math.cast(i64, offset) orelse return error.Unseekable;
const rc = mmap_sym(null, len, prot, flags, file.handle, casted_offset);
syscall.finish();
const err: posix.E = if (builtin.link_libc) e: {
if (rc != std.c.MAP_FAILED) {
break @as([*]align(page_align) u8, @ptrCast(@alignCast(rc)))[0..len];
}
break :e @fromBackingInt(@intCast(posix.system._errno().*));
} else e: {
const err = posix.errno(rc);
if (err == .SUCCESS) {
break @as([*]align(page_align) u8, @ptrFromInt(rc))[0..len];
}
break :e err;
};
switch (err) {
.SUCCESS => unreachable,
.INTR => continue,
.ACCES => return error.AccessDenied,
.AGAIN => return error.LockedMemoryLimitExceeded,
.EXIST => return error.MappingAlreadyExists,
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.OperationUnsupported,
.NOMEM => return error.OutOfMemory,
.PERM => return error.PermissionDenied,
.TXTBSY => return error.FileBusy,
.OVERFLOW => return error.Unseekable,
.BADF => return errnoBug(err), // Always a race condition.
.INVAL => return errnoBug(err), // Invalid parameters to mmap()
.OPNOTSUPP => return errnoBug(err), // Bad flags with MAP.SHARED_VALIDATE on Linux.
else => return posix.unexpectedErrno(err),
}
};
return .{
.file = file,
.offset = offset,
.memory = contents,
.section = {},
};
}
return error.OperationUnsupported;
}
fn fileMemoryMapDestroy(userdata: ?*anyopaque, mm: *File.MemoryMap) void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const memory = mm.memory;
if (mm.section) |section| switch (native_os) {
.windows => {
if (section == windows.INVALID_HANDLE_VALUE) return;
_ = windows.ntdll.NtUnmapViewOfSection(windows.current_process, memory.ptr);
windows.CloseHandle(section);
},
.wasi => unreachable,
else => {
if (memory.len == 0) return;
switch (posix.errno(posix.system.munmap(memory.ptr, memory.len))) {
.SUCCESS => {},
else => |e| {
if (builtin.mode == .debug)
std.log.err("failed to unmap {d} bytes at {*}: {t}", .{ memory.len, memory.ptr, e });
},
}
},
} else {
const gpa = t.allocator;
gpa.rawFree(memory, .fromByteUnits(std.heap.pageSize()), @returnAddress());
}
mm.* = undefined;
}
fn fileMemoryMapSetLength(
userdata: ?*anyopaque,
mm: *File.MemoryMap,
new_len: usize,
) File.MemoryMap.SetLengthError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
const page_size = std.heap.pageSize();
const alignment: Alignment = .fromByteUnits(page_size);
const page_align = std.heap.page_size_min;
const old_memory = mm.memory;
if (mm.section) |section| {
_ = section;
if (alignment.forward(new_len) == alignment.forward(old_memory.len)) {
mm.memory.len = new_len;
return;
}
switch (native_os) {
.wasi => unreachable,
.linux => {
const flags: posix.MREMAP = .{ .MAYMOVE = true };
const addr_hint: ?[*]const u8 = null;
const new_memory = while (true) {
const syscall: Syscall = try .start();
const rc = posix.system.mremap(old_memory.ptr, old_memory.len, new_len, flags, addr_hint);
syscall.finish();
const err: posix.E = if (builtin.link_libc) e: {
if (rc != std.c.MAP_FAILED) break @as([*]align(page_align) u8, @ptrCast(@alignCast(rc)))[0..new_len];
break :e @fromBackingInt(@intCast(posix.system._errno().*));
} else e: {
const err = posix.errno(rc);
if (err == .SUCCESS) break @as([*]align(page_align) u8, @ptrFromInt(rc))[0..new_len];
break :e err;
};
switch (err) {
.SUCCESS => unreachable,
.INTR => continue,
.AGAIN => return error.LockedMemoryLimitExceeded,
.NOMEM => return error.OutOfMemory,
.INVAL => return errnoBug(err),
.FAULT => return errnoBug(err),
else => return posix.unexpectedErrno(err),
}
};
mm.memory = new_memory;
return;
},
else => return error.OperationUnsupported,
}
} else {
const gpa = t.allocator;
if (gpa.rawRemap(old_memory, alignment, new_len, @returnAddress())) |new_ptr| {
mm.memory = @alignCast(new_ptr[0..new_len]);
} else {
const new_ptr: [*]align(page_align) u8 = @alignCast(
gpa.rawAlloc(new_len, alignment, @returnAddress()) orelse return error.OutOfMemory,
);
const copy_len = @min(new_len, old_memory.len);
@memcpy(new_ptr[0..copy_len], old_memory[0..copy_len]);
mm.memory = new_ptr[0..new_len];
gpa.rawFree(old_memory, alignment, @returnAddress());
}
}
}
fn fileMemoryMapRead(userdata: ?*anyopaque, mm: *File.MemoryMap) File.ReadPositionalError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const section = mm.section orelse return mmSyncRead(mm.file, mm.memory, mm.offset);
_ = section;
}
fn fileMemoryMapWrite(userdata: ?*anyopaque, mm: *File.MemoryMap) File.WritePositionalError!void {
const t: *Threaded = @ptrCast(@alignCast(userdata));
_ = t;
const section = mm.section orelse return mmSyncWrite(mm.file, mm.memory, mm.offset);
_ = section;
}
fn mmSyncRead(file: File, memory: []u8, offset: u64) File.ReadPositionalError!void {
if (is_windows) {
var i: usize = 0;
while (true) {
const buf = memory[i..];
if (buf.len == 0) break;
const n = try readFilePositionalWindows(file, buf, offset + i);
if (n == 0) {
@memset(memory[i..], 0);
break;
}
i += n;
}
} else if (native_os == .wasi and !builtin.link_libc) {
var i: usize = 0;
const syscall: Syscall = try .start();
while (true) {
const buf = memory[i..];
if (buf.len == 0) {
syscall.finish();
break;
}
var n: usize = undefined;
const vec: std.os.wasi.iovec_t = .{ .base = buf.ptr, .len = buf.len };
switch (std.os.wasi.fd_pread(file.handle, (&vec)[0..1], 1, offset + i, &n)) {
.SUCCESS => {
if (n == 0) {
syscall.finish();
@memset(memory[i..], 0);
break;
}
i += n;
try syscall.checkCancel();
continue;
},
.INTR, .TIMEDOUT => {
try syscall.checkCancel();
continue;
},
.NOTCONN => |err| return syscall.errnoBug(err), // not a socket
.CONNRESET => |err| return syscall.errnoBug(err), // not a socket
.BADF => |err| return syscall.errnoBug(err), // use after free
.INVAL => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err), // segmentation fault
.AGAIN => |err| return syscall.errnoBug(err),
.IO => return syscall.fail(error.InputOutput),
.ISDIR => return syscall.fail(error.IsDir),
.NOBUFS => return syscall.fail(error.SystemResources),
.NOMEM => return syscall.fail(error.SystemResources),
.NXIO => return syscall.fail(error.Unseekable),
.SPIPE => return syscall.fail(error.Unseekable),
.OVERFLOW => return syscall.fail(error.Unseekable),
.NOTCAPABLE => return syscall.fail(error.AccessDenied),
else => |err| return syscall.unexpectedErrno(err),
}
}
} else {
var i: usize = 0;
const syscall: Syscall = try .start();
while (true) {
const buf = memory[i..];
if (buf.len == 0) {
syscall.finish();
break;
}
const rc = pread_sym(file.handle, buf.ptr, buf.len, @intCast(offset + i));
switch (posix.errno(rc)) {
.SUCCESS => {
const n: usize = @intCast(rc);
if (n == 0) {
syscall.finish();
@memset(memory[i..], 0);
break;
}
i += n;
try syscall.checkCancel();
continue;
},
.INTR, .TIMEDOUT => {
try syscall.checkCancel();
continue;
},
.NXIO => return syscall.fail(error.Unseekable),
.SPIPE => return syscall.fail(error.Unseekable),
.OVERFLOW => return syscall.fail(error.Unseekable),
.NOBUFS => return syscall.fail(error.SystemResources),
.NOMEM => return syscall.fail(error.SystemResources),
.AGAIN => return syscall.fail(error.WouldBlock),
.IO => return syscall.fail(error.InputOutput),
.ISDIR => return syscall.fail(error.IsDir),
.NOTCONN => |err| return syscall.errnoBug(err), // not a socket
.CONNRESET => |err| return syscall.errnoBug(err), // not a socket
.INVAL => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err),
.BADF => |err| return syscall.errnoBug(err), // use after free
else => |err| return syscall.unexpectedErrno(err),
}
}
}
}
fn mmSyncWrite(file: File, memory: []u8, offset: u64) File.WritePositionalError!void {
if (is_windows) {
var i: usize = 0;
while (true) {
const buf = memory[i..];
if (buf.len == 0) break;
i += try writeFilePositionalWindows(file, memory[i..], offset + i);
}
} else if (native_os == .wasi and !builtin.link_libc) {
var i: usize = 0;
var n: usize = undefined;
const syscall: Syscall = try .start();
while (true) {
const buf = memory[i..];
if (buf.len == 0) {
syscall.finish();
break;
}
const iovec: std.os.wasi.ciovec_t = .{ .base = buf.ptr, .len = buf.len };
switch (std.os.wasi.fd_pwrite(file.handle, (&iovec)[0..1], 1, offset + i, &n)) {
.SUCCESS => {
i += n;
try syscall.checkCancel();
continue;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.DQUOT => return syscall.fail(error.DiskQuota),
.FBIG => return syscall.fail(error.FileTooBig),
.IO => return syscall.fail(error.InputOutput),
.NOSPC => return syscall.fail(error.NoSpaceLeft),
.PERM => return syscall.fail(error.PermissionDenied),
.PIPE => return syscall.fail(error.BrokenPipe),
.NOTCAPABLE => return syscall.fail(error.AccessDenied),
.NXIO => return syscall.fail(error.Unseekable),
.SPIPE => return syscall.fail(error.Unseekable),
.OVERFLOW => return syscall.fail(error.Unseekable),
.INVAL => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err),
.AGAIN => |err| return syscall.errnoBug(err),
.BADF => |err| return syscall.errnoBug(err), // use after free
.DESTADDRREQ => |err| return syscall.errnoBug(err), // not a socket
else => |err| return syscall.unexpectedErrno(err),
}
}
} else {
var i: usize = 0;
const syscall: Syscall = try .start();
while (true) {
const buf = memory[i..];
if (buf.len == 0) {
syscall.finish();
break;
}
const rc = pwrite_sym(file.handle, buf.ptr, buf.len, @intCast(offset + i));
switch (posix.errno(rc)) {
.SUCCESS => {
const n: usize = @bitCast(rc);
i += n;
try syscall.checkCancel();
continue;
},
.INTR => {
try syscall.checkCancel();
continue;
},
.INVAL => |err| return syscall.errnoBug(err),
.FAULT => |err| return syscall.errnoBug(err),
.DESTADDRREQ => |err| return syscall.errnoBug(err), // not a socket
.CONNRESET => |err| return syscall.errnoBug(err), // not a socket
.BADF => return syscall.fail(error.NotOpenForWriting),
.AGAIN => return syscall.fail(error.WouldBlock),
.DQUOT => return syscall.fail(error.DiskQuota),
.FBIG => return syscall.fail(error.FileTooBig),
.IO => return syscall.fail(error.InputOutput),
.NOSPC => return syscall.fail(error.NoSpaceLeft),
.PERM => return syscall.fail(error.PermissionDenied),
.PIPE => return syscall.fail(error.BrokenPipe),
.BUSY => return syscall.fail(error.DeviceBusy),
.TXTBSY => return syscall.fail(error.FileBusy),
.NXIO => return syscall.fail(error.Unseekable),
.SPIPE => return syscall.fail(error.Unseekable),
.OVERFLOW => return syscall.fail(error.Unseekable),
else => |err| return syscall.unexpectedErrno(err),
}
}
}
}
fn deviceIoControl(o: *const Io.Operation.DeviceIoControl) Io.Cancelable!Io.Operation.DeviceIoControl.Result {
if (is_windows) {
const NtControlFile = switch (o.code.DeviceType) {
.FILE_SYSTEM, .NAMED_PIPE => &windows.ntdll.NtFsControlFile,
else => &windows.ntdll.NtDeviceIoControlFile,
};
var iosb: windows.IO_STATUS_BLOCK = undefined;
if (o.file.flags.nonblocking) {
var done: bool = false;
switch (NtControlFile(
o.file.handle,
null, // event
flagApc,
&done, // APC context
&iosb,
o.code,
if (o.in.len > 0) o.in.ptr else null,
@intCast(o.in.len),
if (o.out.len > 0) o.out.ptr else null,
@intCast(o.out.len),
)) {
// We must wait for the APC routine.
.PENDING, .SUCCESS => while (!done) {
// Once we get here we must not return from the function until the
// operation completes, thereby releasing reference to io_status_block.
const alertable_syscall = AlertableSyscall.start() catch |err| switch (err) {
error.Canceled => |e| {
var cancel_iosb: windows.IO_STATUS_BLOCK = undefined;
_ = windows.ntdll.NtCancelIoFileEx(o.file.handle, &iosb, &cancel_iosb);
while (!done) waitForApcOrAlert();
return e;
},
};
waitForApcOrAlert();
alertable_syscall.finish();
},
else => |status| iosb.u.Status = status,
}
} else {
const syscall: Syscall = try .start();
while (true) switch (NtControlFile(
o.file.handle,
null, // event
null, // APC routine
null, // APC context
&iosb,
o.code,
if (o.in.len > 0) o.in.ptr else null,
@intCast(o.in.len),
if (o.out.len > 0) o.out.ptr else null,
@intCast(o.out.len),
)) {
.PENDING => unreachable, // unrecoverable: wrong asynchronous flag
.CANCELLED => {
try syscall.checkCancel();
continue;
},
else => |status| {
syscall.finish();
iosb.u.Status = status;
break;
},
};
}
return iosb;
} else {
const syscall: Syscall = try .start();
while (true) {
const rc = posix.system.ioctl(o.file.handle, @bitCast(o.code), @intFromPtr(o.arg));
switch (posix.errno(rc)) {
.SUCCESS => {
syscall.finish();
if (@TypeOf(rc) == usize) return @bitCast(@as(u32, @truncate(rc)));
return rc;
},
.INTR => {
try syscall.checkCancel();
continue;
},
else => |err| {
syscall.finish();
return -@as(i32, @backingInt(err));
},
}
}
}
}
const WaitGroup = struct {
state: std.atomic.Value(usize),
event: Io.Event,
const init: WaitGroup = .{ .state = .{ .raw = 0 }, .event = .unset };
const is_waiting: usize = 1 << 0;
const one_pending: usize = 1 << 1;
fn start(wg: *WaitGroup) void {
const prev_state = wg.state.fetchAdd(one_pending, .monotonic);
assert((prev_state / one_pending) < (std.math.maxInt(usize) / one_pending));
}
fn value(wg: *WaitGroup) usize {
return wg.state.load(.monotonic) / one_pending;
}
fn wait(wg: *WaitGroup) void {
const prev_state = wg.state.fetchAdd(is_waiting, .acquire);
assert(prev_state & is_waiting == 0);
if ((prev_state / one_pending) > 0) eventWait(&wg.event);
}
fn finish(wg: *WaitGroup) void {
const state = wg.state.fetchSub(one_pending, .acq_rel);
assert((state / one_pending) > 0);
if (state == (one_pending | is_waiting)) {
eventSet(&wg.event);
}
}
};
/// Same as `Io.Event.wait` but avoids the VTable.
fn eventWait(event: *Io.Event) void {
if (@cmpxchgStrong(Io.Event, event, .unset, .waiting, .acquire, .acquire)) |prev| switch (prev) {
.unset => unreachable,
.waiting => {},
.is_set => return,
};
while (true) {
Thread.futexWaitUncancelable(@ptrCast(event), @backingInt(Io.Event.waiting), null);
switch (@atomicLoad(Io.Event, event, .acquire)) {
.unset => unreachable, // `reset` called before pending `wait` returned
.waiting => continue,
.is_set => return,
}
}
}
/// Same as `Io.Event.set` but avoids the VTable.
fn eventSet(event: *Io.Event) void {
switch (@atomicRmw(Io.Event, event, .Xchg, .is_set, .release)) {
.unset, .is_set => {},
.waiting => Thread.futexWake(@ptrCast(event), std.math.maxInt(u32)),
}
}
/// Same as `Io.Condition.broadcast` but avoids the VTable.
fn condBroadcast(cond: *Io.Condition) void {
var prev_state = cond.state.load(.monotonic);
while (prev_state.waiters > prev_state.signals) {
@branchHint(.unlikely);
prev_state = cond.state.cmpxchgWeak(prev_state, .{
.waiters = prev_state.waiters,
.signals = prev_state.waiters,
}, .release, .monotonic) orelse {
// Update the epoch to tell the waiting threads that there are new signals for them.
// Note that a waiting thread could miss a take if *exactly* (1<<32)-1 wakes happen
// between it observing the epoch and sleeping on it, but this is extraordinarily
// unlikely due to the precise number of calls required.
_ = cond.epoch.fetchAdd(1, .release); // `.release` to ensure ordered after `state` update
Thread.futexWake(&cond.epoch.raw, prev_state.waiters - prev_state.signals);
return;
};
}
}
/// Same as `Io.Condition.signal` but avoids the VTable.
fn condSignal(cond: *Io.Condition) void {
var prev_state = cond.state.load(.monotonic);
while (prev_state.waiters > prev_state.signals) {
@branchHint(.unlikely);
prev_state = cond.state.cmpxchgWeak(prev_state, .{
.waiters = prev_state.waiters,
.signals = prev_state.signals + 1,
}, .release, .monotonic) orelse {
// Update the epoch to tell the waiting threads that there are new signals for them.
// Note that a waiting thread could miss a take if *exactly* (1<<32)-1 wakes happen
// between it observing the epoch and sleeping on it, but this is extraordinarily
// unlikely due to the precise number of calls required.
_ = cond.epoch.fetchAdd(1, .release); // `.release` to ensure ordered after `state` update
Thread.futexWake(&cond.epoch.raw, 1);
return;
};
}
}
/// Same as `Io.Condition.waitUncancelable` but avoids the VTable.
fn condWait(cond: *Io.Condition, mutex: *Io.Mutex) void {
var epoch = cond.epoch.load(.acquire); // `.acquire` to ensure ordered before state load
{
const prev_state = cond.state.fetchAdd(.{ .waiters = 1, .signals = 0 }, .monotonic);
assert(prev_state.waiters < std.math.maxInt(u16)); // overflow caused by too many waiters
}
mutexUnlock(mutex);
defer mutexLock(mutex);
while (true) {
Thread.futexWaitUncancelable(&cond.epoch.raw, epoch, null);
epoch = cond.epoch.load(.acquire); // `.acquire` to ensure ordered before `state` laod
var prev_state = cond.state.load(.monotonic);
while (prev_state.signals > 0) {
prev_state = cond.state.cmpxchgWeak(prev_state, .{
.waiters = prev_state.waiters - 1,
.signals = prev_state.signals - 1,
}, .acquire, .monotonic) orelse {
// We successfully consumed a signal.
return;
};
}
}
}
/// Same as `Io.Mutex.lockUncancelable` but avoids the VTable.
pub fn mutexLock(m: *Io.Mutex) void {
const initial_state = m.state.cmpxchgStrong(
.unlocked,
.locked_once,
.acquire,
.monotonic,
) orelse {
@branchHint(.likely);
return;
};
if (initial_state == .contended) {
Thread.futexWaitUncancelable(@ptrCast(&m.state.raw), @backingInt(Io.Mutex.State.contended), null);
}
while (m.state.swap(.contended, .acquire) != .unlocked) {
Thread.futexWaitUncancelable(@ptrCast(&m.state.raw), @backingInt(Io.Mutex.State.contended), null);
}
}
/// Same as `Io.Mutex.unlock` but avoids the VTable.
pub fn mutexUnlock(m: *Io.Mutex) void {
switch (m.state.swap(.unlocked, .release)) {
.unlocked => unreachable,
.locked_once => {},
.contended => {
@branchHint(.unlikely);
Thread.futexWake(@ptrCast(&m.state.raw), 1);
},
}
}
const OpenError = error{
IsDir,
NotDir,
FileNotFound,
NoDevice,
AccessDenied,
PipeBusy,
PathAlreadyExists,
WouldBlock,
NetworkNotFound,
AntivirusInterference,
FileBusy,
} || Dir.PathNameError || Io.Cancelable || Io.UnexpectedError;
const OpenFileOptions = struct {
access_mask: windows.ACCESS_MASK,
dir: ?windows.HANDLE = null,
sa: ?*const windows.SECURITY_ATTRIBUTES = null,
share_access: windows.FILE.SHARE = .VALID_FLAGS,
creation: windows.FILE.CREATE_DISPOSITION,
filter: Filter = .non_directory_only,
/// If false, tries to open path as a reparse point without dereferencing it.
/// Defaults to true.
follow_symlinks: bool = true,
pub const Filter = enum {
/// Causes `OpenFile` to return `error.IsDir` if the opened handle would be a directory.
non_directory_only,
/// Causes `OpenFile` to return `error.NotDir` if the opened handle is not a directory.
dir_only,
/// `OpenFile` does not discriminate between opening files and directories.
any,
};
};
/// TODO: inline this logic everywhere and delete this function
fn OpenFile(sub_path_w: []const u16, options: OpenFileOptions) OpenError!windows.HANDLE {
if (std.mem.eql(u16, sub_path_w, &.{'.'}) and options.filter == .non_directory_only) {
return error.IsDir;
}
if (std.mem.eql(u16, sub_path_w, &.{ '.', '.' }) and options.filter == .non_directory_only) {
return error.IsDir;
}
var result: windows.HANDLE = undefined;
const attr: windows.OBJECT.ATTRIBUTES = .{
.RootDirectory = if (Dir.path.isAbsoluteWindowsWtf16(sub_path_w)) null else options.dir,
.Attributes = .{ .INHERIT = if (options.sa) |sa| sa.bInheritHandle.toBool() else false },
.ObjectName = @constCast(&windows.UNICODE_STRING.init(sub_path_w)),
.SecurityDescriptor = if (options.sa) |ptr| ptr.lpSecurityDescriptor else null,
};
var iosb: windows.IO_STATUS_BLOCK = undefined;
var attempt: u5 = 0;
var syscall: Syscall = try .start();
while (true) {
switch (windows.ntdll.NtCreateFile(
&result,
options.access_mask,
&attr,
&iosb,
null,
.{ .NORMAL = true },
options.share_access,
options.creation,
.{
.DIRECTORY_FILE = options.filter == .dir_only,
.NON_DIRECTORY_FILE = options.filter == .non_directory_only,
.IO = .SYNCHRONOUS_NONALERT,
.OPEN_REPARSE_POINT = !options.follow_symlinks,
},
null,
0,
)) {
.SUCCESS => {
syscall.finish();
return result;
},
.CANCELLED => {
try syscall.checkCancel();
continue;
},
.SHARING_VIOLATION => {
// This occurs if the file attempting to be opened is a running
// executable. However, there's a kernel bug: the error may be
// incorrectly returned for an indeterminate amount of time
// after an executable file is closed. Here we work around the
// kernel bug with retry attempts.
syscall.finish();
if (max_windows_kernel_bug_retries - attempt == 0) return error.FileBusy;
try parking_sleep.sleep(.{ .duration = .{
.raw = .fromMilliseconds((@as(u32, 1) << attempt) >> 1),
.clock = .awake,
} });
attempt += 1;
syscall = try .start();
continue;
},
.DELETE_PENDING => {
// This error means that there *was* a file in this location on
// the file system, but it was deleted. However, the OS is not
// finished with the deletion operation, and so this CreateFile
// call has failed. There is not really a sane way to handle
// this other than retrying the creation after the OS finishes
// the deletion.
syscall.finish();
if (max_windows_kernel_bug_retries - attempt == 0) return error.FileBusy;
try parking_sleep.sleep(.{ .duration = .{
.raw = .fromMilliseconds((@as(u32, 1) << attempt) >> 1),
.clock = .awake,
} });
attempt += 1;
syscall = try .start();
continue;
},
.OBJECT_NAME_INVALID => return syscall.fail(error.BadPathName),
.OBJECT_NAME_NOT_FOUND => return syscall.fail(error.FileNotFound),
.OBJECT_PATH_NOT_FOUND => return syscall.fail(error.FileNotFound),
.BAD_NETWORK_PATH => return syscall.fail(error.NetworkNotFound), // \\server was not found
.BAD_NETWORK_NAME => return syscall.fail(error.NetworkNotFound), // \\server was found but \\server\share wasn't
.NO_MEDIA_IN_DEVICE => return syscall.fail(error.NoDevice),
.ACCESS_DENIED => return syscall.fail(error.AccessDenied),
.PIPE_BUSY => return syscall.fail(error.PipeBusy),
.PIPE_NOT_AVAILABLE => return syscall.fail(error.NoDevice),
.OBJECT_NAME_COLLISION => return syscall.fail(error.PathAlreadyExists),
.FILE_IS_A_DIRECTORY => return syscall.fail(error.IsDir),
.NOT_A_DIRECTORY => return syscall.fail(error.NotDir),
.USER_MAPPED_FILE => return syscall.fail(error.AccessDenied),
.VIRUS_INFECTED, .VIRUS_DELETED => return syscall.fail(error.AntivirusInterference),
.INVALID_PARAMETER => |status| return syscall.ntstatusBug(status),
.OBJECT_PATH_SYNTAX_BAD => |status| return syscall.ntstatusBug(status),
.INVALID_HANDLE => |status| return syscall.ntstatusBug(status),
else => |status| return syscall.unexpectedNtstatus(status),
}
}
}
pub fn closeFd(fd: posix.fd_t) void {
if (native_os == .wasi and !builtin.link_libc) {
switch (std.os.wasi.fd_close(fd)) {
.SUCCESS, .INTR => {},
.BADF => recoverableOsBugDetected(), // use after free
else => recoverableOsBugDetected(), // unexpected failure
}
} else switch (posix.errno(posix.system.close(fd))) {
.SUCCESS, .INTR => {}, // INTR still a success, see https://github.com/ziglang/zig/issues/2425
.BADF => recoverableOsBugDetected(), // use after free
else => recoverableOsBugDetected(), // unexpected failure
}
}