#! @file on_windows.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the operations of `system` on Windows, over the functions of the #! system they are made of. #! #! The operations of `system` on Windows, over the functions of the system, #! which the program links as C functions, from `kernel32.dll` and, for waiting #! on a word, from the set of functions Windows keeps for that. They fail as the #! operations do everywhere, by giving the negated error number Linux would #! give, which `errno_of` makes of the system's own codes, so `error_of` reads #! them as it does on Linux. #! #! Paths and text are UTF-8 to the program and UTF-16 to the system, and are #! turned from one to the other here, a surrogate standing alone in a name #! becoming three bytes, as WTF-8 writes one, so a name read from the system #! reaches the same file again. A handle is the system's own, which fits 32 #! bits, with 0, 1, and 2 standing for the standard streams. Windows has no #! signals of its own: the console's Ctrl-C, Ctrl-Break, and closing are noted #! as `interrupt`, `quit`, and `hangup`, and logging off and shutting down as #! `terminate`, by the numbers Linux gives them, which `on_windows_x86_64.sakura` #! declares. import system::windows; module system when os == windows; const find_bytes: u64 = 592; # A WIN32_FIND_DATAW, whose name is 44 bytes in. const name_bytes: u64 = 1024; # A name of a directory, of at most 255 units, as UTF-8. #! A handle to an open file, pipe, or console, which only the system makes: the #! system's own, which fits 32 bits, or 0, 1, or 2, which stand for the #! standard streams the program was given. pub type fd = i32; #! The handle of the standard input. pub val fd::stdin := 0; #! The handle of the standard output. pub val fd::stdout := 1; #! The handle of the standard error. pub val fd::stderr := 2; #! The longest path the system takes, in bytes, with the zero it ends in. pub const path_limit: u64 = 32768; # The longest a path is that every function of the system takes as it is, in # units. A longer one is written as a path of the whole file system, which they # take up to `path_limit`. const long_path: u64 = 248; # The system's handle an fd stands for. def handle_of(which: fd): u64 { if which >= 0 && which <= 2 { return GetStdHandle(0xFFFFFFF6 - which as u32); } return (which as i64) as u64; } # The fd of a handle the system gave, or the failure where it gave none. def fd_of(handle: u64): i64 { if handle == invalid_handle || handle == 0 { return failed(); } return handle as i64; } # The failure the system says the call before failed with, as an error number. def failed(): i64 { return errno_of(GetLastError()); } # The error number Linux gives the failure a code of the system says, or, for a # code no number stands for, the code itself, past the numbers Linux gives, so # that `error_of` reads it as `other` and it is not lost. def errno_of(code: u32): i64 { return match code { 2, 3, 15, 53, 67, 161 => -2, 5, 1314, 1920 => -13, 80, 183 => -17, 267 => -20, 145 => -39, 6 => -9, 87, 123, 131, 1113 => -22, 206 => -36, 16, 32, 33, 148, 170 => -16, 19 => -30, 39, 112 => -28, 1295 => -122, 4 => -24, 17 => -18, 1921 => -40, 109, 232, 233 => -32, 1, 50, 120 => -95, 995 => -4, 1460 => -110, 132 => -29, 193 => -8, 8, 14 => -12, else => -(65536 + code as i64), }; } #! What a failure an operation gave means. #! @param code The negative number the operation gave. #! @returns The kind of failure, which is `other` for one no member names. pub def error_of(code: i64): io_error { return match -code { 2 => io_error::not_found, 1, 13 => io_error::permission_denied, 17 => io_error::already_exists, 20 => io_error::not_a_directory, 21 => io_error::is_a_directory, 39 => io_error::directory_not_empty, 9, 22 => io_error::invalid, 36 => io_error::name_too_long, 16, 26 => io_error::busy, 30 => io_error::read_only, 28, 122 => io_error::no_space, 23, 24 => io_error::too_many_open, 18 => io_error::cross_device, 40 => io_error::link_loop, 32 => io_error::broken_pipe, 38, 95 => io_error::unsupported, 4 => io_error::interrupted, else => io_error::other, }; } # Text as UTF-16, ending in a zero, as the system takes it, in memory of its own, # which is let go where it closes. struct wide_text : owning { var block: *mut u16; # The memory, which is null where none was taken. var units: *mut u16; # Where the text begins within it. } def wide_text::close(&mut this): void { if this.block != null { raw_release(this.block as *mut u8); this.block = null; this.units = null; } } # The character UTF-8 writes at a byte, as WTF-8 reads it, into `code`, giving # how many bytes it takes, or zero where none begins there. def decoded(text: strview, at: u64, code: &mut u32): u64 { val first := text[at] as u32; if first < 0x80 { code = first; return 1; } var length := 0u; var value: u32 = 0; if first >= 0xC2 && first <= 0xDF { length = 2; value = first & 0x1F; } else if first >= 0xE0 && first <= 0xEF { length = 3; value = first & 0x0F; } else if first >= 0xF0 && first <= 0xF4 { length = 4; value = first & 0x07; } else { return 0; } return 0 if at + length > text.length; for k in 1u..length { val next := text[at + k] as u32; return 0 if (next & 0xC0) != 0x80; value = (value << 6) | (next & 0x3F); } return 0 if (length == 3 && value < 0x800) || (length == 4 && (value < 0x10000 || value > 0x10FFFF)); code = value; return length; } # Writes UTF-8 as UTF-16, giving how many units it wrote, which are at most as # many as the bytes. Where `strict` asks, text holding a zero, or that is not # UTF-8, gives -22; otherwise a zero is written as it is, and a byte beginning # no character as U+FFFD. A surrogate standing alone, as WTF-8 writes one, is # written as itself. def utf16_of(text: strview, into: *mut u16, strict: bool): i64 { var at := 0u; var out := 0u; while at < text.length { var code: u32 = 0xFFFD; val length := decoded(text, at, &mut code); if strict && (length == 0 || code == 0) { return -22; } at += length == 0 ? 1 : length; if code >= 0x10000 { into[out] = (0xD800 | ((code - 0x10000) >> 10)) as u16; into[out + 1] = (0xDC00 | ((code - 0x10000) & 0x3FF)) as u16; out += 2; } else { into[out] = code as u16; out++; } } return out as i64; } # Writes UTF-16 as UTF-8, a surrogate standing alone as WTF-8 writes one, giving # how many bytes it wrote, or -34 where they do not fit. def narrow(units: *u16, count: u64, into: *mut u8, room: u64): i64 { var out := 0u; var at := 0u; while at < count { var code := units[at] as u32; at++; if code >= 0xD800 && code < 0xDC00 && at < count && units[at] >= 0xDC00 && units[at] < 0xE000 { code = 0x10000 + ((code - 0xD800) << 10) + (units[at] as u32 - 0xDC00); at++; } val bytes := code < 0x80 ? 1u : code < 0x800 ? 2u : code < 0x10000 ? 3u : 4u; if out + bytes > room { return -34; } if bytes == 1 { into[out] = code as u8; } else if bytes == 2 { into[out] = (0xC0 | (code >> 6)) as u8; into[out + 1] = (0x80 | (code & 0x3F)) as u8; } else if bytes == 3 { into[out] = (0xE0 | (code >> 12)) as u8; into[out + 1] = (0x80 | ((code >> 6) & 0x3F)) as u8; into[out + 2] = (0x80 | (code & 0x3F)) as u8; } else { into[out] = (0xF0 | (code >> 18)) as u8; into[out + 1] = (0x80 | ((code >> 12) & 0x3F)) as u8; into[out + 2] = (0x80 | ((code >> 6) & 0x3F)) as u8; into[out + 3] = (0x80 | (code & 0x3F)) as u8; } out += bytes; } return out as i64; } # How many units text the system wrote holds before the zero it ends in. def length_of(units: *u16): u64 { var length := 0u; while units[length] != 0 { length++; } return length; } # Writes text as the system takes it, giving zero, or -22 where it holds a zero # or is not UTF-8. def widen(text: strview, into: &mut wide_text): i64 { into.block = raw_allocate((text.length + 1) * 2) as *mut u16; into.units = into.block; val count := utf16_of(text, into.units, true); if count < 0 { return count; } into.units[count] = 0; return 0; } # Writes a path as the system takes it, giving zero, or -22 where it holds a # zero or is not UTF-8. A path too long for every function to take as it is, # and that names where it is from the root of a drive or a share, is written as # a path of the whole file system, `\\?\C:\…` or `\\?\UNC\server\…`, which # they take whole. The system then works out no `.` or `..` in it, so a path # holding one is left as it is. def wide_path(path: strview, into: &mut wide_text): i64 { # Room is kept before the text for what such a path begins with. into.block = raw_allocate((path.length + 9) * 2) as *mut u16; val text := into.block + 8; val count := utf16_of(path, text, true); if count < 0 { return count; } text[count] = 0; into.units = text; val length := count as u64; val drive := length >= 3 && text[1] == ':' as u16 && is_slash(text[2]); val shared := length >= 3 && is_slash(text[0]) && is_slash(text[1]) && text[2] != '?' as u16 && text[2] != '.' as u16; if length < long_path || !(drive || shared) || has_dots(text, length) { return 0; } for i in 0..length { if text[i] == '/' as u16 { text[i] = '\\' as u16; } } if drive { into.units = text - 4; put_units(into.units, "\\\\?\\"); } else { into.units = text - 6; put_units(into.units, "\\\\?\\UNC\\"); } return 0; } # Writes text of ASCII as units. def put_units(into: *mut u16, text: strview): void { for i in 0..text.length { into[i] = text[i] as u16; } } def is_slash(unit: u16): bool { return unit == '\\' as u16 || unit == '/' as u16; } # Whether a path holds a `.` or `..` between its slashes. def has_dots(units: *mut u16, length: u64): bool { var start := 0u; for i in 0..length + 1 { if i < length && !is_slash(units[i]) { continue; } val size := i - start; val dot := size >= 1 && units[start] == '.' as u16; if dot && (size == 1 || (size == 2 && units[start + 1] == '.' as u16)) { return true; } start = i + 1; } return false; } # Calls a function of the system on a path, giving zero where it succeeded, or # its failure. def on_path(path: strview, act: def(*u16): i32): i32 { var name: wide_text; val bad := wide_path(path, &mut name); if bad < 0 { return bad as i32; } if act(name.units as *u16) == 0 { return failed() as i32; } return 0; } # Whether a name the system takes is of a directory. def is_directory(name: *u16): bool { val attributes := GetFileAttributesW(name); return attributes != invalid_attributes && (attributes & directory) != 0; } #! Opens the file at a path. #! #! Another program, or this one, may read, write, rename, and remove the file #! while it is open, as POSIX lets it. A directory opens only to be read. #! @param path The path of the file to open. #! @param flags How to open the file. Without `write` or `append`, it is read. #! @param mode The permissions a file `create` makes is given, of which only #! whether the owner may write is kept: without it, the file is #! read only. #! @returns The handle of the opened file. pub def open(path: strview, flags: open_flags, mode: u32 = 0o666): fd { if (flags & 0xFFFFFFC0) != 0 { return -22 as fd; } val reads := (flags & open_flags::read) != 0; val appends := (flags & open_flags::append) != 0; val writes := (flags & open_flags::write) != 0 || appends; val creates := (flags & open_flags::create) != 0; val truncates := (flags & open_flags::truncate) != 0; val exclusive := (flags & open_flags::exclusive) != 0; # A file opened to append may only add to its end, so every write goes there, # whoever else writes it, unless it is emptied too, which writing does. var access: u32 = synchronize | read_attributes; if reads || !writes { access = access | generic_read; } if writes && (!appends || truncates) { access = access | generic_write; } if appends { access = access | append_data | write_attributes; } val disposition: u32 = creates ? (exclusive ? create_new : truncates ? create_always : open_always) : (truncates ? truncate_existing : open_existing); var attributes: u32 = creates && (mode & 0o200) == 0 ? readonly : normal; if !writes { attributes = attributes | backup_semantics; } var name: wide_text; val bad := wide_path(path, &mut name); if bad < 0 { return bad as fd; } val handle := CreateFileW(name.units as *u16, access, share_all, null, disposition, attributes, 0); if handle == invalid_handle { val why := GetLastError(); if why == error_access_denied && writes && is_directory(name.units as *u16) { return -21 as fd; } return errno_of(why) as fd; } return fd_of(handle) as fd; } #! Describes the file at a path, following a link the path ends in. #! @param path The path of the file to describe. #! @param out The description to fill. #! @returns Zero when the file was described. pub def stat(path: strview, out: &mut file_info): i32 { return described_at(path, true, out); } #! Describes the file at a path, or the link the path ends in, where it does. #! @param path The path of the file to describe. #! @param out The description to fill. #! @returns Zero when the file was described. pub def lstat(path: strview, out: &mut file_info): i32 { return described_at(path, false, out); } # Describes the file at a path, following a link it ends in where `follow` says. def described_at(path: strview, follow: bool, out: &mut file_info): i32 { var name: wide_text; val bad := wide_path(path, &mut name); if bad < 0 { return bad as i32; } val units := name.units as *u16; val flags: u32 = follow ? backup_semantics : backup_semantics | open_reparse_point; var handle := CreateFileW(units, read_attributes, share_all, null, open_existing, flags, 0); var why: u32 = handle == invalid_handle ? GetLastError() : 0; # An alias of an app of the system's store opens only as itself, and is the # program it starts. var aliased := false; if why == error_cant_access_file && follow { handle = CreateFileW(units, read_attributes, share_all, null, open_existing, flags | open_reparse_point, 0); why = handle == invalid_handle ? GetLastError() : 0; aliased = true; } # A file the system holds open for itself, as its paging file, is described by # its directory instead. if why == error_sharing_violation { return described_found(units, out); } if handle == invalid_handle { return errno_of(why) as i32; } val result := described(handle, !follow && !aliased, units, out); CloseHandle(handle); return result; } # Fills a description of an open file, as its handle gives it, of what a link # it is where `links` says to look, and of whether it runs by its name, where # that is given. def described(handle: u64, links: bool, name: *u16, out: &mut file_info): i32 { SetLastError(0); val kind := GetFileType(handle); if kind != disk_type { if kind == 0 && GetLastError() != 0 { return failed() as i32; } # A console, a pipe, or a device is no file the system describes. out.kind = file_kind::other; out.size = 0; out.permissions = 0o666; out.modified = 0; out.accessed = 0; return 0; } var info: file_information; if GetFileInformationByHandle(handle, &mut info) == 0 { return failed() as i32; } out.kind = (info.attributes & directory) != 0 ? file_kind::directory : file_kind::regular; if links && (info.attributes & reparse_point) != 0 && is_link(handle) { out.kind = file_kind::link; } out.size = ((info.size_high as u64) << 32) | info.size_low as u64; out.permissions = permissions_of(info.attributes, out.kind, name); out.modified = nanoseconds_of(&info.written); out.accessed = nanoseconds_of(&info.accessed); return 0; } # Describes a file by what its directory says of it, as `FindFirstFileExW` reads # it, for a file the system will not open even to describe. def described_found(name: *u16, out: &mut file_info): i32 { val data := raw_allocate(find_bytes); val find := FindFirstFileExW(name, 1, data, 0, null, 0); if find == invalid_handle { val why := failed(); raw_release(data); return why as i32; } FindClose(find); val attributes := *(data as *mut u32); out.kind = (attributes & directory) != 0 ? file_kind::directory : file_kind::regular; out.size = ((*((data + 28) as *mut u32) as u64) << 32) | *((data + 32) as *mut u32) as u64; out.permissions = permissions_of(attributes, out.kind, name); out.modified = nanoseconds_of(&*((data + 20) as *mut filetime)); out.accessed = nanoseconds_of(&*((data + 12) as *mut filetime)); raw_release(data); return 0; } # Whether an open file whose attributes say it is a reparse point is a link to # a file or a directory, rather than one of the other kinds the system keeps. def is_link(handle: u64): bool { var tag: u32[2]; if GetFileInformationByHandleEx(handle, 9, (&mut tag) as *mut u8, 8) == 0 { return false; } return tag[1] == symlink_tag || tag[1] == junction_tag; } # The permissions of a file, as Windows keeps them: readable by everyone, # writable by everyone unless it is read only, and runnable by everyone where it # is a directory, or its name says it is a program. def permissions_of(attributes: u32, kind: file_kind, name: *u16): u32 { if kind == file_kind::link { return 0o777; } var made: u32 = 0o444; if (attributes & readonly) == 0 { made = made | 0o222; } if kind == file_kind::directory || (name != null && runs(name)) { made = made | 0o111; } return made; } # Whether a name ends in what a program's does: `.exe` or `.com`, which the # system runs, or `.bat` or `.cmd`, which `cmd.exe` does. def runs(name: *u16): bool { val length := length_of(name); return length >= 4 && name[length - 4] == '.' as u16 && ( ends_as(name, length, "exe") || ends_as(name, length, "com") || ends_as(name, length, "bat") || ends_as(name, length, "cmd") ); } # Whether units end in ASCII, compared without regard to case. def ends_as(units: *u16, length: u64, ending: strview): bool { if length < ending.length { return false; } for i in 0..ending.length { var unit := units[length - ending.length + i]; if unit >= 'A' as u16 && unit <= 'Z' as u16 { unit = unit + 32; } if unit != ending[i] as u16 { return false; } } return true; } # A time of the system, in nanoseconds since 1970. def nanoseconds_of(time: &filetime): i64 { val ticks := (((time.high as u64) << 32) | time.low as u64) as i64; return (ticks - 116444736000000000) * 100; } # The attributes a file is given for permissions, which set only whether it is # read only: it is where the owner may not write. def attributes_with(attributes: u32, mode: u32): u32 { val made: u32 = (mode & 0o200) == 0 ? attributes | readonly : attributes & ~readonly; return made == 0 ? normal : made; } #! Sets the permissions of the file at a path, of which only whether the owner #! may write is kept: without it, the file is read only. #! @param path The path of the file. #! @param mode The permissions to give it. #! @returns Zero when they were set. pub def chmod(path: strview, mode: u32): i32 { var name: wide_text; val bad := wide_path(path, &mut name); if bad < 0 { return bad as i32; } val units := name.units as *u16; val attributes := GetFileAttributesW(units); if attributes == invalid_attributes || SetFileAttributesW(units, attributes_with(attributes, mode)) == 0 { return failed() as i32; } return 0; } #! Makes a directory. #! @param path The path of the directory, whose parent must exist. #! @param mode The permissions to give it, which Windows has no use for. #! @returns Zero when it was made. pub def mkdir(path: strview, mode: u32): i32 { return on_path(path, def(name: *u16): i32 => CreateDirectoryW(name, null)); } #! Removes an empty directory. #! @param path The path of the directory. #! @returns Zero when it was removed. One that holds anything gives -39, as on #! Linux, though Windows refuses first to remove a directory a program #! has open, as a program has the one it works in. pub def rmdir(path: strview): i32 { val result := on_path(path, def(name: *u16): i32 => RemoveDirectoryW(name)); if result == -16 && holds_names(path) { return -39; } return result; } # Whether a directory holds anything besides `.` and `..`. def holds_names(path: strview): bool { var stream: dir_stream; if opendir(path, &mut stream) != 0 { return false; } var entry: dir_entry; return stream.next(&mut entry) == 1; } #! Removes a file, or a link without what it leads to, but not a directory. A #! file that is read only is removed too, as POSIX removes one. #! @param path The path of the file. #! @returns Zero when it was removed. pub def unlink(path: strview): i32 { var name: wide_text; val bad := wide_path(path, &mut name); if bad < 0 { return bad as i32; } val units := name.units as *u16; if DeleteFileW(units) != 0 { return 0; } val why := GetLastError(); val attributes := GetFileAttributesW(units); if why != error_access_denied || attributes == invalid_attributes { return errno_of(why) as i32; } # A link to a directory is removed as a directory is, which removes the link. if (attributes & directory) != 0 { if (attributes & reparse_point) == 0 { return -21; } return RemoveDirectoryW(units) != 0 ? 0 : failed() as i32; } if (attributes & readonly) == 0 || SetFileAttributesW(units, attributes_with(attributes, 0o200)) == 0 { return errno_of(why) as i32; } if DeleteFileW(units) != 0 { return 0; } val again := failed(); SetFileAttributesW(units, attributes); return again as i32; } #! Moves a file or directory to another path, replacing a file there. #! @param from The path of what to move. #! @param to Where to move it, on the same volume. #! @returns Zero when it was moved. pub def rename(from: strview, to: strview): i32 { var target: wide_text; val bad := wide_path(to, &mut target); if bad < 0 { return bad as i32; } val at := target.units as *u16; return on_path(from, def(name: *u16): i32 => MoveFileExW(name, at, 1)); } #! Writes the path of the working directory, which is absolute, without a zero. #! @param into Where the path is written. #! @param length How many bytes there is room for, `path_limit` being enough #! for any the system keeps but those holding many characters #! beyond ASCII. #! @returns The number of bytes written, or -34 where they do not fit. pub def getcwd(into: *mut u8, length: u64): i64 { while true { val needed := GetCurrentDirectoryW(0, null); if needed == 0 { return failed(); } val units := raw_allocate(needed as u64 * 2) as *mut u16; val count := GetCurrentDirectoryW(needed, units); val why := count == 0 ? failed() : 0; # It may have changed, and grown, between the two calls. if count == 0 || count < needed { val written := count == 0 ? why : narrow(units as *u16, count as u64, into, length); raw_release(units as *mut u8); return written; } raw_release(units as *mut u8); } return 0; } #! Sets the working directory, which relative paths are taken from. #! @param path The path of the directory. #! @returns Zero when it was set. pub def chdir(path: strview): i32 { var name: wide_text; val bad := widen(path, &mut name); if bad < 0 { return bad as i32; } return SetCurrentDirectoryW(name.units as *u16) == 0 ? failed() as i32 : 0; } #! Reads from the file into a buffer, waiting until something arrives. A #! console is read as the characters typed, which are given as UTF-8, and a line #! beginning with Ctrl-Z ends what it gives, as a pipe ends once nothing more #! can be written to it. #! @param this The handle of the file to read. #! @param into Where the bytes read are written. #! @param length How many bytes there is room for. #! @returns The number of bytes read, which is zero at the end of the file, or #! a negative error number, which is `-4` where a signal the program #! handles ended the wait. pub def fd::read(&this, into: *mut u8, length: u64): i64 { val handle := handle_of(this); if is_console(handle) { return console_read(handle, into, length); } val asked: u32 = length > 0x7FFFFFFF ? 0x7FFFFFFF : length as u32; while true { var read: u32 = 0; if ReadFile(handle, into, asked, &mut read, null) != 0 { return read as i64; } # A pipe ends once every handle that writes it is closed. A read the system # gave up on for a signal ends where a handler ran, and is made again where # none did. val why := GetLastError(); if why == error_broken_pipe || why == error_handle_eof { return 0; } if why == error_invalid_function && is_directory_handle(handle) { return -21; } if why != error_operation_aborted || run_handlers() { return errno_of(why); } } return 0; } # Whether a handle is of a console, which is asked again where a signal ended # the asking, as a signal ends any call to the console. def is_console(handle: u64): bool { var mode: u32 = 0; while GetConsoleMode(handle, &mut mode) == 0 { if GetLastError() != error_operation_aborted { return false; } } return true; } # Whether an open file is a directory. def is_directory_handle(handle: u64): bool { var info: file_information; return GetFileInformationByHandle(handle, &mut info) != 0 && (info.attributes & directory) != 0; } #! Writes bytes to the file. A console is written the characters the bytes are #! as UTF-8, whichever code page it shows, and a character cut short at the end #! is held until the write that finishes it, being counted as written. #! #! Writing to a pipe nothing reads fails with -32, which is `broken_pipe`. #! Writing to the program's own output or error that way stops the program, #! quietly, as it does on Linux, unless the program handles, watches for, or #! ignores `signal::pipe`, which it is then sent instead. #! @param this The handle of the file to write. #! @param from Where the bytes to write begin. #! @param length How many bytes to write. #! @returns The number of bytes written, which may be fewer than asked. pub def fd::write(&this, from: *u8, length: u64): i64 { val handle := handle_of(this); var result: i64 = 0; if is_console(handle) { result = console_write(handle, from, length); } else { # A write the system gave up on for a signal, as it gives up the program's # waits for one, is made again, as on Linux, unless part of it was written. val asked: u32 = length > 0x7FFFFFFF ? 0x7FFFFFFF : length as u32; while true { var written: u32 = 0; if WriteFile(handle, from, asked, &mut written, null) != 0 { result = written as i64; break; } val why := GetLastError(); if why != error_operation_aborted || written > 0 { result = written > 0 ? written as i64 : errno_of(why); break; } } } val number := this as i64; val bit := 1u << (number_of(signal::pipe) as u64); if result == -32 && (((handled | noting) & bit) != 0 || number == 1 || number == 2) { _ = raise(signal::pipe); } return result; } #! Writes text to the file. #! @param this The handle of the file to write. #! @param text The text to write, which may be a literal, a view of one, or #! the text a `string` lends. #! @returns The number of bytes written, which may be fewer than asked. pub def fd::put(&this, text: strview): i64 { return this.write(text.data, text.length); } #! Moves the position in the file that reads and writes happen at. #! @param this The handle of the file to seek. #! @param offset The offset to move to. #! @param from Where the offset is measured from. #! @returns The new position from the start of the file, or -29 for a pipe, a #! console, or a device, which have none. pub def fd::seek(&this, offset: i64, from: whence): i64 { if from < 0 || from > 2 { return -22; } val handle := handle_of(this); SetLastError(0); val kind := GetFileType(handle); if kind != disk_type { return kind == 0 && GetLastError() != 0 ? failed() : -29; } var position: i64 = 0; if SetFilePointerEx(handle, offset, &mut position, from as u32) == 0 { return failed(); } return position; } #! Closes the file. Closing a standard stream leaves the program without it, so #! that using its handle fails with -9, which is `invalid`. #! @param this The handle of the file to close. #! @returns Zero when the file was closed. pub def fd::close(&this): i32 { if CloseHandle(handle_of(this)) == 0 { return failed() as i32; } val number := this as i64; if number >= 0 && number <= 2 { SetStdHandle(0xFFFFFFF6 - number as u32, 0); } return 0; } #! Describes the file. #! @param this The handle of the file to describe. #! @param out The description to fill. #! @returns Zero when the file was described. pub def fd::stat(&this, out: &mut file_info): i32 { val handle := handle_of(this); var path: u16[1024]; val units := (&mut path) as *mut u16; val length := GetFinalPathNameByHandleW(handle, units, 1024, 0); return described(handle, false, length == 0 || length >= 1024 ? null : units as *u16, out); } #! Sets the permissions of the file, of which only whether the owner may write #! is kept: without it, the file is read only. #! @param this The handle of the file. #! @param mode The permissions to give it. #! @returns Zero when they were set. pub def fd::chmod(&this, mode: u32): i32 { val handle := handle_of(this); var basic: basic_information; if GetFileInformationByHandleEx(handle, 0, (&mut basic) as *mut u8, basic_bytes as u32) == 0 { return failed() as i32; } # Times left zero are left as they are. var changed := basic_information { attributes = attributes_with(basic.attributes, mode) }; val at := (&mut changed) as *mut u8; if SetFileInformationByHandle(handle, 0, at, basic_bytes as u32) != 0 { return 0; } val why := GetLastError(); if why != error_access_denied { return errno_of(why) as i32; } # A handle that may not change what is written of the file is opened again # with one that may. val writing := ReOpenFile(handle, write_attributes, share_all, backup_semantics); if writing == invalid_handle { return failed() as i32; } val result := SetFileInformationByHandle(writing, 0, at, basic_bytes as u32) == 0 ? failed() as i32 : 0; CloseHandle(writing); return result; } #! A directory being read, one name at a time, which `opendir` starts and #! `close` ends. pub struct dir_stream : owning { var _find: u64; #! The search of the system, which is zero where it found nothing. var _data: *mut u8; #! What the search last found, then its name as UTF-8, which is null where not open. var _pending: bool; #! Whether what the search last found is yet to be read. } #! Starts reading the names a directory holds. #! @param path The path of the directory. #! @param into The stream to read them with, which `close` ends. #! @returns Zero when the directory was opened. pub def opendir(path: strview, into: &mut dir_stream): i32 { var pattern := string::from(path, nothing{}); val last := path.length == 0 ? '\\' : path[path.length - 1]; pattern.append(last == '\\' || last == '/' || last == ':' ? "*" : "\\*"); var name: wide_text; val bad := wide_path(pattern.view(), &mut name); if bad < 0 { return bad as i32; } val data := raw_allocate(find_bytes + name_bytes); val find := FindFirstFileExW(name.units as *u16, 1, data, 0, null, 2); if find == invalid_handle { # A directory holding nothing, not even `.`, as the root of an empty drive # does, is found holding nothing; a file is found missing, as is all past it. val why := GetLastError(); var plain: wide_text; val known := wide_path(path, &mut plain) == 0; val attributes := known ? GetFileAttributesW(plain.units as *u16) : invalid_attributes; val found := attributes != invalid_attributes; if !found || (attributes & directory) == 0 || why != error_file_not_found { raw_release(data); return found && (attributes & directory) == 0 ? -20 : errno_of(why) as i32; } into._find = 0; into._data = data; into._pending = false; return 0; } into._find = find; into._data = data; into._pending = true; return 0; } #! Reads the next name the directory holds, in no particular order, leaving out #! `.` and `..`. #! @param this The stream to read. #! @param out The entry to fill, whose name views the stream's own memory. #! @returns One when an entry was read, and zero once there are no more. pub def dir_stream::next(&mut this, out: &mut dir_entry): i32 { if this._data == null { return -9; } while true { if this._find == 0 { return 0; } if !this._pending && FindNextFileW(this._find, this._data) == 0 { val why := GetLastError(); return why == error_no_more_files ? 0 : errno_of(why) as i32; } this._pending = false; # A name is up to 260 units 44 bytes in, ending in a zero. val units := (this._data + 44) as *u16; var length := 0u; while length < 260 && units[length] != 0 { length++; } if units[0] == '.' as u16 && (length == 1 || (length == 2 && units[1] == '.' as u16)) { continue; } val text := this._data + find_bytes; val bytes := narrow(units, length, text, name_bytes); if bytes < 0 { return bytes as i32; } # What a reparse point is, a link or another kind, is 36 bytes in. val attributes := *(this._data as *mut u32); val tag := *((this._data + 36) as *mut u32); out.name = strview::over(text as *u8, bytes as u64); out.kind = (attributes & reparse_point) != 0 && (tag == symlink_tag || tag == junction_tag) ? file_kind::link : (attributes & directory) != 0 ? file_kind::directory : (attributes & device) != 0 ? file_kind::other : file_kind::regular; return 1; } return 0; } #! Stops reading the directory. Closing a stream that is not open does nothing. #! @param this The stream to close. pub def dir_stream::close(&mut this): void { if this._data == null { return; } if this._find != 0 { FindClose(this._find); } raw_release(this._data); this._data = null; } #! Would start a copy of the program going on from here, which Windows cannot #! do: `respawn` starts one from the start instead. #! @returns -38, which is `unsupported`. pub def fork(): i64 { return -38; } #! Starts a copy of the program from its start, as it was started: the same #! program, given the same command line, with the variables the program started #! with, and one more, which it can tell it is the copy by. It stands in for #! `fork`, which Windows lacks, as `std::testing` uses it. #! @param variable The variable added, as `NAME=value`, in place of any of #! the name the program has. #! @param input The handle the copy's standard input is given. #! @param output The handle its standard output is given. #! @param error The handle its standard error is given. #! @returns The number the system knows the copy by, which `wait` and `kill` #! take, or a negative error number. pub def respawn(variable: strview, input: fd, output: fd, error: fd): i64 { var program := wide_text { block = raw_allocate(path_limit * 2) as *mut u16 }; program.units = program.block; val length := GetModuleFileNameW(0, program.units, path_limit as u32); if length == 0 || length as u64 >= path_limit { return length == 0 ? failed() : -36; } # The command line is given again as it is, so nothing in it is quoted anew. val line := GetCommandLineW(); val count := length_of(line); var command := wide_text { block = raw_allocate((count + 1) * 2) as *mut u16 }; command.units = command.block; for i in 0..count + 1 { command.units[i] = line[i]; } var name_length := 0u; while name_length < variable.length && variable[name_length] != '=' { name_length++; } var entries := vector::::new(); for each in environment() { if !(each.length > name_length && each[name_length] == '=' && same_name(each, variable, name_length)) { entries.append(each); } } entries.append(variable); var block: wide_text; val bad := block_of(&mut entries, &mut block); if bad < 0 { return bad; } return started(program.units as *u16, command.units, block.units, null, input, output, error); } # Whether two variables have the same name of a length, which Windows compares # without regard to case. def same_name(a: strview, b: strview, length: u64): bool { for i in 0..length { if upper(a[i]) != upper(b[i]) { return false; } } return true; } def upper(byte: u8): u8 { return byte >= 'a' && byte <= 'z' ? byte - 32 : byte; } # A program `spawn` started, until `wait` finds it stopped: its number, the # handle the system gave of it, and the signal `kill` stopped it with, or zero. struct child_entry { var id: i64; var handle: u64; var killed: i32; } # The programs `spawn` started that are yet to be waited for, which a word # guards, as `std::io` guards the console, since any thread may start one or # wait for one: 0 where no thread holds it, 1 where one does, and 2 where others # may wait. var children: *mut child_entry; var child_count: u64; var child_room: u64; var children_held: atomic; def hold_children(): void { if children_held.exchange(1) != 0 { while children_held.exchange(2) != 0 { _ = futex_wait(((&mut children_held) as *mut atomic) as *mut u32, 2, -1); } } } def let_go_of_children(): void { if children_held.exchange(0) == 2 { _ = futex_wake(((&mut children_held) as *mut atomic) as *mut u32, 1); } } # Keeps a program started, until it is waited for. def remember(id: i64, handle: u64): void { hold_children(); if child_count == child_room { child_room = child_room == 0 ? 8 : child_room * 2; val bytes := child_room * size_of::(); val grown := children == null ? raw_allocate(bytes) : raw_resize(children as *mut u8, bytes); children = grown as *mut child_entry; } children[child_count] = child_entry { id = id, handle = handle, killed = 0 }; child_count++; let_go_of_children(); } #! Waits for a program that `spawn`, or a copy of the program that `respawn`, #! started to stop. #! @param child The number the system knows it by, or -1 for whichever of #! them stops first. #! @param status How it stopped: exited with its code, or, where `kill` #! stopped it, by that signal, and where the console's Ctrl-C #! did, by `interrupt`. #! @returns The number of the program that stopped, or a negative error number, #! which is `-10` where there is none to wait for, and `-4` where a #! signal the program handles ended the wait. pub def wait(child: i64, status: &mut process_status): i64 { while true { # Those waited on, at most 63, then the event of signals. var handles: u64[64]; var ids: i64[63]; var count := 0u; hold_children(); for i in 0..child_count { if (child == -1 || children[i].id == child) && count < 63 { handles[count] = children[i].handle; ids[count] = children[i].id; count++; } } let_go_of_children(); if count == 0 { return -10; } val event := interrupting(); val waited := event == 0 ? count : count + 1; handles[count] = event; val woke := WaitForMultipleObjects(waited as u32, (&handles) as *u64, 0, milliseconds_of(wait_slice)); if woke == wait_failed { return failed(); } # Another thread may have waited for the same program first, and forgotten # it, which leaves those still running to wait for. if (woke as u64) < count { val id := reaped(ids[woke as u64], status); if id != -10 { return id; } continue; } if run_handlers() { return -4; } } return 0; } # How a program of a number that stopped did, which forgets it, giving the # number, or -10 where no program of the number has stopped and is yet to be # waited for. def reaped(id: i64, status: &mut process_status): i64 { hold_children(); var index := child_count; for i in 0..child_count { if children[i].id == id { index = i; break; } } if index == child_count || WaitForSingleObject(children[index].handle, 0) != 0 { let_go_of_children(); return -10; } val handle := children[index].handle; val killed := children[index].killed; children[index] = children[child_count - 1]; child_count--; let_go_of_children(); var code: u32 = 0; _ = GetExitCodeProcess(handle, &mut code); CloseHandle(handle); status.exited = killed == 0 && code != control_c_exit; status.code = status.exited ? code as i32 : 0; status.signal = killed != 0 ? killed : status.exited ? 0 : number_of(signal::interrupt); return id; } #! Sends a signal to a process, which Windows can do only to stop one: `kill` #! and `terminate` stop it at once, as `TerminateProcess` does, with 128 more #! than the signal's number as its status. Any signal may be sent to the #! program itself, as `raise` sends it. #! @param process The number the system knows the process by, as `getpid` #! gives the program its own, and `spawn` the program a child's. #! @param sent The signal to send. #! @returns Zero when it was sent, and -95, which is `unsupported`, for another #! signal to another process. pub def kill(process: i64, sent: signal): i32 { if process == getpid() { return raise(sent); } if sent != signal::kill && sent != signal::terminate { return -95; } val code := (128 + number_of(sent)) as u32; hold_children(); for i in 0..child_count { if children[i].id != process { continue; } # One that has stopped already, or is stopping, which the system will not # stop again, but which is not yet waited for, is stopped. val handle := children[i].handle; var result: i32 = 0; if TerminateProcess(handle, code) != 0 { children[i].killed = number_of(sent); } else { val why := GetLastError(); result = WaitForSingleObject(handle, 1000) == 0 ? 0 : errno_of(why) as i32; } let_go_of_children(); return result; } let_go_of_children(); val handle := OpenProcess(process_terminate, 0, process as u32); if handle == 0 { val why := GetLastError(); return why == error_invalid_parameter ? -3 : errno_of(why) as i32; } val done := TerminateProcess(handle, code); val why := done == 0 ? GetLastError() : 0; CloseHandle(handle); return done == 0 ? errno_of(why) as i32 : 0; } #! Sends a signal to the program itself. A signal the program handles or #! watches for is noted before this returns, and its handler runs at the next #! safe point. One it ignores does nothing. Any other does what Linux does by #! default: `child`, `resume`, and `resized` nothing, `stop` and `suspend` #! nothing Windows can do, which gives -95, and the rest stop the program at #! once, `interrupt` with the status the console's Ctrl-C gives, and the others #! with 128 more than the signal's number. #! @param sent The signal to send. #! @returns Zero when it was sent. pub def raise(sent: signal): i32 { val number := number_of(sent); val bit := 1u << (number as u64); if ((handled | noting) & bit) != 0 { return catch_signal(number | (3 << 8)); } if (ignored & bit) != 0 { return 0; } if sent == signal::child || sent == signal::resume || sent == signal::resized { return 0; } if sent == signal::stop || sent == signal::suspend { return -95; } val code: u32 = sent == signal::interrupt ? control_c_exit : (128 + number) as u32; TerminateProcess(GetCurrentProcess(), code); return 0; } #! The number the system knows the program by. #! @returns The number, which `kill` takes. pub def getpid(): i64 { return GetCurrentProcessId() as i64; } #! Has the system throw a signal away when it comes, until `handle` or #! `restore` says otherwise. #! @param which The signal to ignore. #! @returns Zero when it is ignored. `kill` and `stop` cannot be, and neither #! can `child`, as on Linux: each gives -22, which is `invalid`. pub def ignore(which: signal): i32 { if which == signal::kill || which == signal::stop || which == signal::child { return -22; } return disposed(which, 1); } #! Has the system do what it does with a signal by default, as it did before the #! program said otherwise: for those the console sends, stopping the program. #! @param which The signal to restore. #! @returns Zero when it is restored. `kill` and `stop` have nothing to restore, #! and give -22, which is `invalid`. pub def restore(which: signal): i32 { if which == signal::kill || which == signal::stop { return -22; } return disposed(which, 2); } #! Handles a signal with a function, until `handle`, `ignore`, or `restore` says #! otherwise. The function runs at the program's next safe point once the #! signal comes, and before a wait the signal interrupts ends. A signal that #! comes again before its handler runs is handled once, and one that comes while #! a handler runs is handled once that handler returns. #! @tparam F The handler's type: a function, a lambda, or a functor. #! @param which The signal to handle. #! @param by What handles it, which the program then keeps until another #! handles the signal: a functor holding what it needs, or a #! closure sharing the locals where it was made, as one setting a #! flag the program's loop reads, while those locals last. #! @returns Zero when it is handled. `kill` and `stop` cannot be, and give -22, #! which is `invalid`. pub def handle(which: signal, by: F): i32 where F: invokable { if which == signal::kill || which == signal::stop { return -22; } # The handler is in place before the signal can come. val bit := 1u << (number_of(which) as u64); handlers[which as u64] = handler::new(move(&mut by)); handled = handled | bit; val result := catch_signal(number_of(which)); if result < 0 { handled = handled & ~bit; return result; } noting = noting & ~bit; ignored = ignored & ~bit; return result; } #! Has the system note a signal when it comes, for `watched` to give, until #! `handle`, `ignore`, or `restore` says otherwise. No handler runs, so a #! program that only watches for signals has no safe points, and asks itself #! whether one came, as a machine running a program does for that program. A #! wait the signal interrupts goes on. #! @param which The signal to watch for. #! @returns Zero when it is watched for. `kill` and `stop` cannot be, and give #! -22, which is `invalid`. pub def watch(which: signal): i32 { if which == signal::kill || which == signal::stop { return -22; } val bit := 1u << (number_of(which) as u64); val result := catch_signal(number_of(which)); if result < 0 { return result; } handled = handled & ~bit; noting = noting | bit; ignored = ignored & ~bit; return result; } #! The signals `watch` watches for that came since this last asked, which it #! forgets. #! @returns One bit each, by the system's number. pub def watched(): u64 { arrived = arrived | take_signals(); val came := arrived & noting; arrived = arrived & ~noting; return came; } #! Waits until a handler has run. A signal that came before the wait began is #! not missed: its handler runs, and the wait ends at once. Within a handler, #! where no other runs, it waits until a signal the program handles comes, whose #! handler runs once the one running returns. In any thread but the one the #! program began with, where no handler runs, it waits for good. pub def pause(): void { if !is_first_thread() { while true { Sleep(milliseconds_of(wait_slice)); } } # The event is set whenever a signal is noted, and only cleared as the # signals are taken, so none comes between finding none and the wait. val event := signal_event(); while !run_handlers() { if event == 0 { Sleep(10); } else { WaitForSingleObject(event, infinite); } if dispatching { break; } } } # The signals the program ignores, one bit each by number. var ignored: u64; # Has the system do with a signal what `catch_signal` does for an action: 1 to # throw it away, and 2 what the system does by default. Gives zero, or a # negative number. def disposed(which: signal, action: i32): i32 { val result := catch_signal(number_of(which) | (action << 8)); if result != 0 { return result; } val bit := 1u << (number_of(which) as u64); handled = handled & ~bit; noting = noting & ~bit; ignored = action == 1 ? ignored | bit : ignored & ~bit; return result; } # The thread the program began with, which runs the handlers, as it sets the # program's globals before `main`. var first_thread: u32 = GetCurrentThreadId(); # Whether the calling thread is the one the program began with. def is_first_thread(): bool { return GetCurrentThreadId() == first_thread; } # The event the system sets whenever it notes a signal, and clears as # `take_signals` takes them, once `catch_signal` has given it, or zero. var signal_event_handle: u64; #! The event the system sets whenever it notes a signal, and resets as signals #! are taken, which a wait waits on as well so that a signal the program handles #! ends it. It is a manual-reset event made the first time it is asked for, and #! kept while the program runs, or zero where the system gives none. A machine #! running a program gives it the same event, so the program's waits end on a #! signal as they do in an executable. #! @returns The event's handle, or zero. pub def signal_event(): u64 { if signal_event_handle == 0 { val given := catch_signal(number_of(signal::interrupt) | (4 << 8)); signal_event_handle = given > 0 ? given as u64 : 0; } return signal_event_handle; } # The event a wait waits on too, so that a signal the program handles ends it, # or zero where no handler would run: where the program handles none, where a # handler runs, or in a thread other than the one the program began with. def interrupting(): u64 { if handled == 0 || dispatching || !is_first_thread() { return 0; } return signal_event(); } # How many of the steady clock's ticks make a second, once asked for. var ticks_per_second: i64; #! Reads a clock. #! @param which The clock: the wall clock, or the steady one. #! @returns Nanoseconds: since 1970 began in UTC of the wall clock, which the #! system may set forward or back, and since a start that never moves #! of the steady one, which only ever grows. pub def clock(which: clock_kind): i64 { if which == clock_kind::wall { var now: filetime; GetSystemTimePreciseAsFileTime(&mut now); return nanoseconds_of(&now); } if ticks_per_second == 0 { var frequency: i64 = 0; QueryPerformanceFrequency(&mut frequency); ticks_per_second = frequency; } var count: i64 = 0; QueryPerformanceCounter(&mut count); return (count / ticks_per_second) * 1000000000 + (count % ticks_per_second) * 1000000000 / ticks_per_second; } # The steady clock's reading a length of time from now, or the furthest it reads. def deadline(nanoseconds: i64): i64 { val now := clock(clock_kind::steady); val most: i64 = 0x7FFFFFFFFFFFFFFF; return nanoseconds > most - now ? most : now + nanoseconds; } # Milliseconds a length of time in nanoseconds takes, rounded up, and short of # waiting for good. def milliseconds_of(nanoseconds: i64): u32 { val whole := nanoseconds / 1000000 + (nanoseconds % 1000000 != 0 ? 1 : 0); return whole >= 0xFFFFFFFE ? 0xFFFFFFFE : whole as u32; } # The longest a wait of the system lasts before it is begun again, so that a # thread waiting sees soon that another stopped the program, which ends few of # the waits of the system. const wait_slice: i64 = 100000000; #! Waits for a length of time, to well within a millisecond where the system #! has timers that fine, as Windows 10 has since its 1803 update. #! @param nanoseconds How long to wait, which is no time at all where it is #! not above zero. #! @returns Zero once the time has passed, or a negative error number, which is #! -4 where a signal the program handles ended the wait, once its #! handlers ran. A signal no handler ran for does not end the wait. pub def sleep(nanoseconds: i64): i32 { if nanoseconds <= 0 { return 0; } val until := deadline(nanoseconds); val timer := CreateWaitableTimerExW(null, null, 2, 0x1F0003); var result: i32 = 0; while true { val left := until - clock(clock_kind::steady); if left <= 0 { break; } # The timer is set in tenths of microseconds from now, as a negative number. val event := interrupting(); val slice := left < wait_slice ? left : wait_slice; var woke: u32 = 0; if timer != 0 { var handles: u64[2]; handles[0] = timer; handles[1] = event; val due: i64 = -((slice + 99) / 100); SetWaitableTimer(timer, &due, 0, null, null, 0); woke = WaitForMultipleObjects(event == 0 ? 1 : 2, (&handles) as *u64, 0, infinite); } else if event == 0 { Sleep(milliseconds_of(slice)); } else { woke = WaitForSingleObject(event, milliseconds_of(slice)) == 0 ? 1 : 0; } if woke == 1 && run_handlers() { result = -4; break; } } if timer != 0 { CloseHandle(timer); } return result; } # The longest a wait on a word lasts before the word is looked at again. const futex_slice: i64 = 100000000; #! Waits while a word holds what is expected, until another thread wakes those #! waiting on it, which every way of waiting for one another is built on. The #! word is read and the wait begun in one step, so a wake after the word changes #! is never missed. Only threads of one program wait on one another this way on #! Windows, not processes sharing memory. #! @param at The word. #! @param expected What the word holds to be waited on. #! @param timeout Nanoseconds to wait at most, or for ever where it is #! negative. #! @returns Zero where it was woken, which may be for no reason, or a negative #! error number: -11 where the word held something else, and -110 #! where the time ran out. pub def futex_wait(at: *mut u32, expected: u32, timeout: i64): i32 { if *at != expected { return -11; } # The wait is made of short ones, each of which looks at the word again. val until := timeout < 0 ? 0 : deadline(timeout); while true { var slice := futex_slice; if timeout >= 0 { val left := until - clock(clock_kind::steady); if left <= 0 { return -110; } slice = left < slice ? left : slice; } if WaitOnAddress(at, &expected, 4, milliseconds_of(slice)) != 0 { return 0; } val why := GetLastError(); if why != error_timeout { return errno_of(why) as i32; } } return 0; } #! Wakes threads waiting on a word. #! @param at The word. #! @param count How many to wake at most, of which Windows tells one from many. #! @returns Zero, since the system does not say how many it woke. pub def futex_wake(at: *mut u32, count: u32): i32 { if count == 1 { WakeByAddressSingle(at); } else if count > 1 { WakeByAddressAll(at); } return 0; } #! How many processors the program may run on, which is how many of its threads #! run at once. #! @returns How many, at least one. pub def cpu_count(): u32 { val all := GetActiveProcessorCount(0xFFFF); var mask: u64 = 0; var system: u64 = 0; if all <= 64 && GetProcessAffinityMask(GetCurrentProcess(), &mut mask, &mut system) != 0 && mask != 0 { var count: u32 = 0; while mask != 0 { mask = mask & (mask - 1); count++; } return count; } return all == 0 ? 1 : all; } #! The number the system knows the calling thread by. #! @returns The number. pub def thread_id(): u64 { return GetCurrentThreadId() as u64; } #! Lets the system run other threads before this one goes on. pub def yield_now(): void { SwitchToThread(); } #! The path of the device that reads as empty, and throws away what is written #! to it. pub val null_device: strview = "NUL"; #! Makes a pipe: what is written to one end is read from the other. Neither end #! is inherited by a program the program starts, unless `spawn` is asked to give #! it one. Writing to a pipe nothing reads fails with -32, which is #! `broken_pipe`, as Windows has no signal to stop the program with. #! @param reading Where the handle of the end that is read is written. #! @param writing Where the handle of the end that is written is written. #! @returns Zero when the pipe was made. pub def pipe(reading: &mut fd, writing: &mut fd): i32 { var read_end: u64 = 0; var write_end: u64 = 0; if CreatePipe(&mut read_end, &mut write_end, null, 65536) == 0 { return failed() as i32; } reading = (read_end as i64) as fd; writing = (write_end as i64) as fd; return 0; } #! Starts a program, which runs beside this one until it stops, and which `wait` #! waits for. #! #! The program is given the handles the request names as its standard streams, #! and inherits no other. Its command line is its arguments, quoted as the C #! runtime reads them back, so it is given each as it is. A batch file, whose #! name ends in `.bat` or `.cmd`, is run by `cmd.exe`, which reads its arguments #! in a way of its own: each is quoted where it needs to be, and one holding a #! `"`, a `%`, or a new line, which `cmd.exe` cannot be given unchanged, is not #! run. #! @param request What to start, and with what, all of which is copied before #! the program starts. #! @returns The number the system knows the started program by, which `wait` #! and `kill` take, or a negative error number: -2 where the program #! is not found, -13 where it may not be run, as it may not where it is #! no program, and -22 where a text the request holds has a zero in it, #! or a batch file is given an argument it cannot be. pub def spawn(request: &spawn_request): i64 { # A program named from where the child runs is found from there. var program := string::new(nothing{}); if request.directory.length != 0 && !is_rooted(request.program) { program.append(request.directory); val last := request.directory[request.directory.length - 1]; if last != '\\' && last != '/' { program.push('\\'); } } for i in 0..request.program.length { val byte := request.program[i]; program.push(byte == '/' ? '\\' : byte); } # cmd.exe takes a batch file's path from where the child runs, so it is given # the whole of it. made_whole(&mut program); var application := string::new(nothing{}); var line := string::new(nothing{}); if is_batch(program.view()) { var system: u16[260]; val length := GetSystemDirectoryW((&mut system) as *mut u16, 260); var bytes: u8[1024]; val written := length == 0 || length >= 260 ? -1 : narrow((&system) as *u16, length as u64, (&mut bytes) as *mut u8, 1024); if written < 0 { return length == 0 ? failed() : -36; } application.append(strview::over((&bytes) as *u8, written as u64)); application.append("\\cmd.exe"); # cmd.exe takes the quotes around the whole of what follows `/c` away, and # runs the rest. line.append("cmd.exe /d /e:ON /v:OFF /c \""); if !quote_for_cmd(&mut line, program.view(), true) { return -22; } for i in 1..request.arguments.length { line.push(' '); if !quote_for_cmd(&mut line, request.arguments[i], false) { return -22; } } line.push('"'); } else { application.append(program.view()); val first := request.arguments.length == 0 ? request.program : request.arguments[0]; if !quote_first(&mut line, first) { return -22; } for i in 1..request.arguments.length { line.push(' '); quote(&mut line, request.arguments[i]); } } var path: wide_text; var command: wide_text; var block: wide_text; var place: wide_text; var entries := vector::::new(); for each in request.environment { entries.append(each); } val bad := widen(application.view(), &mut path) < 0 || widen(line.view(), &mut command) < 0 || block_of(&mut entries, &mut block) < 0 || (request.directory.length != 0 && wide_path(request.directory, &mut place) < 0); if bad { return -22; } if length_of(command.units as *u16) >= 32767 { return -7; } # A directory that is missing, or is no directory, is found so before the # program is looked for. if request.directory.length != 0 { val attributes := GetFileAttributesW(place.units as *u16); if attributes == invalid_attributes { return failed(); } if (attributes & directory) == 0 { return -20; } } return started( path.units as *u16, command.units, block.units, request.directory.length == 0 ? null : place.units as *u16, request.input, request.output, request.error ); } # Makes a path absolute, taking it from the working directory as the system # does, where the system can. def made_whole(path: &mut string): void { var name: wide_text; if widen(path.view(), &mut name) < 0 { return; } val needed := GetFullPathNameW(name.units as *u16, 0, null, null); if needed == 0 { return; } var whole := wide_text { block = raw_allocate(needed as u64 * 2) as *mut u16 }; whole.units = whole.block; val count := GetFullPathNameW(name.units as *u16, needed, whole.units, null); if count == 0 || count >= needed { return; } val room := count as u64 * 3; val bytes := raw_allocate(room); val written := narrow(whole.units as *u16, count as u64, bytes, room); if written >= 0 { path.clear(); path.append(strview::over(bytes as *u8, written as u64)); } raw_release(bytes); } # Whether a path names where it is from a root, a drive, or a share, rather # than from the working directory. def is_rooted(path: strview): bool { return path.length > 0 && (path[0] == '\\' || path[0] == '/' || (path.length > 1 && path[1] == ':')); } # Whether a program is a batch file, which `cmd.exe` runs. def is_batch(program: strview): bool { if program.length < 4 || program[program.length - 4] != '.' { return false; } val ending := program.substr(program.length - 3, 3); return same_name(ending, "bat", 3) || same_name(ending, "cmd", 3); } # Writes what a program is called first on its command line, as the C runtime # reads it back: up to the next space, or within quotes, where it holds one or # is empty. A name holding a quote cannot be read back, and gives false. def quote_first(into: &mut string, text: strview): bool { var plain := text.length != 0; for i in 0..text.length { val byte := text[i]; if byte == '"' { return false; } if byte == ' ' || byte == '\t' { plain = false; } } if !plain { into.push('"'); } into.append(text); if !plain { into.push('"'); } return true; } # Writes an argument on a command line, as the C runtime reads it back: as it # is, or within quotes where it holds a space, a tab, a new line, or a quote, or # is empty, with a backslash before each quote it holds, and the backslashes # before that, and before the closing quote, doubled. def quote(into: &mut string, text: strview): void { var plain := text.length != 0; for i in 0..text.length { val byte := text[i]; if byte == ' ' || byte == '\t' || byte == '\n' || byte == 0x0B || byte == '"' { plain = false; } } if plain { into.append(text); return; } into.push('"'); var slashes := 0u; for i in 0..text.length { val byte := text[i]; if byte == '"' { for _ in 0..slashes + 1 { into.push('\\'); } } slashes = byte == '\\' ? slashes + 1 : 0; into.push(byte); } for _ in 0..slashes { into.push('\\'); } into.push('"'); } # Writes a batch file's path, or an argument of it, as `cmd.exe` reads it: within # quotes, where it takes everything as it is but a `%` or a `"`, unless it is # plain, or the path. One holding either, or a new line, cannot be given # unchanged, and gives false. Backslashes before the closing quote are doubled, # so a program the batch file gives the argument to reads that quote as closing. def quote_for_cmd(into: &mut string, text: strview, always: bool): bool { var plain := text.length != 0 && !always; for i in 0..text.length { val byte := text[i]; if byte == '"' || byte == '%' || byte == '\r' || byte == '\n' || byte == 0 { return false; } val letter := (byte >= 'a' && byte <= 'z') || (byte >= 'A' && byte <= 'Z') || (byte >= '0' && byte <= '9'); if !letter && byte < 0x80 && byte != '-' && byte != '_' && byte != '.' && byte != '\\' && byte != '/' && byte != ':' { plain = false; } } if plain { into.append(text); return true; } into.push('"'); into.append(text); var at := text.length; while at > 0 && text[at - 1] == '\\' { into.push('\\'); at--; } into.push('"'); return true; } # Writes variables as the system gives a program them: as UTF-16, each ending # in a zero, in the order of their names without regard to case, and a zero # after the last. Gives zero, or -22 where one holds a zero or is not UTF-8. def block_of(entries: &mut vector, into: &mut wide_text): i64 { val count := entries.length; for i in 1..count { var at := i; while at > 0 && name_order(entries[at - 1], entries[at]) > 0 { val swapped := strview::over(entries[at - 1].data, entries[at - 1].length); entries.set(at - 1, entries[at]); entries.set(at, swapped); at--; } } var size := 2u; for each in entries { size += each.length + 1; } into.block = raw_allocate(size * 2) as *mut u16; into.units = into.block; var out := 0u; for each in entries { val written := utf16_of(each, into.units + out, true); if written < 0 { return written; } out += written as u64; into.units[out] = 0; out++; } into.units[out] = 0; into.units[out + 1] = 0; return 0; } # How the names of two variables order, as Windows orders them: without regard # to case. def name_order(a: strview, b: strview): i64 { var i := 0u; while true { val ended_a := i >= a.length || a[i] == '='; val ended_b := i >= b.length || b[i] == '='; if ended_a || ended_b { return ended_a && ended_b ? 0 : ended_a ? -1 : 1; } val x := upper(a[i]); val y := upper(b[i]); if x != y { return x < y ? -1 : 1; } i++; } return 0; } # Starts a program from what the system takes: the path of the program, its # command line, its variables as `block_of` writes them, and where it runs, or # null for here, with the handles given as its standard streams, which are all # it inherits. Gives its number, keeping it for `wait`, or the negated error # number. def started( application: *u16, command: *mut u16, block: *mut u16, directory: *u16, input: fd, output: fd, error: fd ): i64 { # Each stream is a copy of its handle the program may inherit, made only for # it, and the program is told to inherit only those, so it inherits nothing # another thread is starting a program with. val ours := GetCurrentProcess(); var streams: fd[3]; streams[0] = input; streams[1] = output; streams[2] = error; var given: u64[3]; var copies: u64[3]; var count := 0u; for i in 0u..3u { val source := handle_of(streams[i]); var copy: u64 = 0; if source != 0 && source != invalid_handle && DuplicateHandle(ours, source, ours, &mut copy, 0, 1, same_access) != 0 { given[i] = copy; copies[count] = copy; count++; } } var info := startup_information { size = startup_bytes as u32, flags = use_std_handles }; info.standard_input = given[0]; info.standard_output = given[1]; info.standard_error = given[2]; var list: *mut u8 = null; var why: u32 = 0; if count > 0 { var size: u64 = 0; InitializeProcThreadAttributeList(null, 1, 0, &mut size); list = raw_allocate(size); if InitializeProcThreadAttributeList(list, 1, 0, &mut size) == 0 { why = GetLastError(); raw_release(list); list = null; } else if UpdateProcThreadAttribute(list, 0, handle_list, (&mut copies) as *mut u8, count * 8, null, null) == 0 { why = GetLastError(); } info.attributes = list; } var made: process_information; if why == 0 { val flags := unicode_block | extended_startup; val inherit: i32 = count > 0 ? 1 : 0; if CreateProcessW(application, command, null, null, inherit, flags, block, directory, &mut info, &mut made) == 0 { why = GetLastError(); } } if list != null { DeleteProcThreadAttributeList(list); raw_release(list); } for i in 0..count { CloseHandle(copies[i]); } if why != 0 { return why == error_bad_exe_format ? -13 : errno_of(why); } CloseHandle(made.thread); remember(made.process_id as i64, made.process); return made.process_id as i64; } #! Waits until one of the handles can be read, or has ended, for at most a #! while. A pipe is looked at again and again, a little longer apart each time it #! holds nothing, up to a hundredth of a second, since Windows cannot wait on one; #! anything else counts as ready. #! @param handles The handles to wait on. One that is negative is passed over, #! as one already read to its end may be. #! @param ready Where whether each can be read, or has ended, is written, at #! the index of its handle. #! @param wait The most milliseconds to wait, or -1 to wait for as long as #! it takes. #! @returns How many can be, 0 where the wait ran out, or a negative error #! number, which is -4 where a signal the program handles ended the #! wait. pub def poll(handles: span, ready: slice, wait: i64 = -1): i32 { if ready.length < handles.length { return -22; } val until := wait < 0 ? 0 : deadline(wait * 1000000); var resting: u32 = 0; while true { var count: i32 = 0; for i in 0..handles.length { ready[i] = false; if handles[i] < 0 { continue; } var available: u32 = 0; if PeekNamedPipe(handle_of(handles[i]), null, 0, null, &mut available, null) == 0 || available > 0 { ready[i] = true; count++; } } if count > 0 { return count; } # A wait with an end rests no longer than is left of it. var rest := resting; if wait >= 0 { val left := until - clock(clock_kind::steady); if left <= 0 { return 0; } val most := milliseconds_of(left); rest = most < rest ? most : rest; } val event := interrupting(); if event == 0 { Sleep(rest); } else if WaitForSingleObject(event, rest) == 0 && run_handlers() { return -4; } resting = resting < 10 ? resting + 1 : 10; } return 0; } # Views of the variables the program started with, once `environment` has made # them, which it keeps for as long as the program runs. var variables: span; var viewed: bool; #! The variables the program started with, each as `NAME=value`, including #! those whose name begins with `=`, which keep the working directory of each #! drive, and which a program it starts is given too. #! @returns Views of each, which are good for as long as the program runs, since #! nothing changes what they view. pub def environment(): span { if viewed { return variables; } # The system gives them as UTF-16, each ending in a zero, and a zero after. val block := GetEnvironmentStringsW(); var count := 0u; var units := 0u; while block != null && block[units] != 0 { units += length_of((block + units) as *u16) + 1; count++; } val views := raw_allocate(count * size_of::()) as *mut strview; val text := raw_allocate(units * 3 + 1); var at := 0u; var out := 0u; for i in 0..count { val length := length_of((block + at) as *u16); val bytes := narrow((block + at) as *u16, length, text + out, units * 3 + 1 - out); views[i] = strview::over((text + out) as *u8, bytes as u64); out += bytes as u64; at += length + 1; } if block != null { FreeEnvironmentStringsW(block); } variables = span::::over(views as *strview, count); viewed = true; return variables; } #! Writes the rule the zone the system is set to keeps its clocks by, as the #! `TZ` variable of POSIX writes one, as `6:005:00,M3.2.0/2:00:00,M11.1.0/2:00:00`, which `std::time` reads. #! Windows keeps no database of zones, so this is the zone the program keeps as #! the system's own there. #! @param into The text to write the rule to. #! @returns Whether the system says which zone it is set to. pub def zone_rule(into: &mut string): bool { var information: zone_information; if GetDynamicTimeZoneInformation(&mut information) == 0xFFFFFFFF { return false; } val usual := information.bias + information.standard_bias; put_zone_name(into, (&information.standard_name) as *u16, usual); put_behind(into, usual); # A rule giving the day of a year it changes is one of that year alone, which # no rule of POSIX says. val start := information.daylight_date; val end := information.standard_date; if information.no_daylight != 0 || start.month == 0 || end.month == 0 || start.year != 0 || end.year != 0 { return true; } val summer := information.bias + information.daylight_bias; put_zone_name(into, (&information.daylight_name) as *u16, summer); put_behind(into, summer); put_turning(into, &start); put_turning(into, &end); return true; } # Writes what a zone calls a time between `<` and `>`, leaving out either where # it holds them, or its offset where it calls it nothing. def put_zone_name(into: &mut string, units: *u16, behind: i32): void { var count := 0u; while count < 32 && units[count] != 0 { count++; } var text: u8[96]; val bytes := narrow(units, count, (&mut text) as *mut u8, 96); into.push('<'); var named := false; for i in 0..(bytes < 0 ? 0u : bytes as u64) { if text[i] != '<' && text[i] != '>' { into.push(text[i]); named = true; } } if !named { val ahead := -behind; into.append(ahead < 0 ? "-" : "+"); val size := ahead < 0 ? -ahead : ahead; into.append($"{size / 60}:{size % 60 < 10 ? "0" : ""}{size % 60}".view()); } into.push('>'); } # Writes how far behind UTC a time is, as the rule writes it, as `6:00` or # `-5:30`. def put_behind(into: &mut string, minutes: i32): void { val size := minutes < 0 ? -minutes : minutes; if minutes < 0 { into.push('-'); } into.append($"{size / 60}:{size % 60 < 10 ? "0" : ""}{size % 60}".view()); } # Writes when a change of the zone comes, as the rule writes it, as # `,M3.2.0/2:00:00`: the month, which of its weeks, the day of the week, and # the time of day, to the second, rounded. def put_turning(into: &mut string, date: &system_time): void { val time := date.hour as i64 * 3600 + date.minute as i64 * 60 + date.second as i64 + (date.millisecond >= 500 ? 1 : 0); val minute := time / 60 % 60; val second := time % 60; into.append($",M{date.month}.{date.day}.{date.day_of_week}/{time / 3600}:".view()); into.append($"{minute < 10 ? "0" : ""}{minute}:{second < 10 ? "0" : ""}{second}".view()); } # The bytes of a character cut short at the end of what was last written to a # console, which the next write to it finishes: for each of the program's own # output and error, and one for any other console. struct console_tail { var handle: u64; var count: u64; var bytes: u8[4]; } var tails: console_tail[3]; # How many bytes a character takes that a byte begins, as UTF-8 writes it, or # one for a byte beginning none. def sequence_length(byte: u8): u64 { if byte >= 0xC2 && byte <= 0xDF { return 2; } if byte >= 0xE0 && byte <= 0xEF { return 3; } if byte >= 0xF0 && byte <= 0xF4 { return 4; } return 1; } # How many bytes at the end of some begin a character they do not finish. def cut_short(from: *u8, length: u64): u64 { var at := length; while at > 0 && length - at < 3 && (from[at - 1] & 0xC0) == 0x80 { at--; } if at == 0 { return 0; } val begins := at - 1; return begins + sequence_length(from[begins]) > length ? length - begins : 0; } # Writes UTF-8 to a console as the characters it is, holding a character cut # short at the end until the next write finishes it. Gives how many bytes it # took, which is every one but where the console failed. def console_write(handle: u64, from: *u8, length: u64): i64 { val slot := handle == GetStdHandle(0xFFFFFFF5) ? 0u : handle == GetStdHandle(0xFFFFFFF4) ? 1u : 2u; if tails[slot].handle != handle { tails[slot] = console_tail { handle = handle }; } # A character the last write cut short is finished first, where this write # holds the rest of it. var done := 0u; if tails[slot].count > 0 { var joined: u8[4]; val held := tails[slot].count; for i in 0..held { joined[i] = tails[slot].bytes[i]; } val wanted := sequence_length(joined[0]); var count := held; while count < wanted && done < length && (from[done] & 0xC0) == 0x80 { joined[count] = from[done]; count++; done++; } if count < wanted && done == length { for i in held..count { tails[slot].bytes[i] = joined[i]; } tails[slot].count = count; return length as i64; } tails[slot].count = 0; val result := console_units(handle, strview::over((&joined) as *u8, count)); if result < 0 { return result; } } # What is left is written in pieces, none splitting a character, keeping a # character cut short at its end for the next write. val cut := cut_short(from + done, length - done); val end := length - cut; for i in 0..cut { tails[slot].bytes[i] = from[end + i]; } tails[slot].count = cut; while done < end { var piece := end - done < 4096 ? end - done : 4096; while piece < end - done && piece > 1 && (from[done + piece] & 0xC0) == 0x80 { piece--; } val result := console_units(handle, strview::over(from + done, piece)); if result < 0 { return done > 0 ? done as i64 : result; } done += piece; } return length as i64; } # Writes UTF-8 of at most 4096 bytes to a console as the characters it is, # giving zero, or the failure. def console_units(handle: u64, text: strview): i64 { var units: u16[4096]; val at := (&mut units) as *mut u16; val count := utf16_of(text, at, false) as u64; var done := 0u; while done < count { # A write the system gave up on for a signal is made again, as on Linux. var written: u32 = 0; if WriteConsoleW(handle, (at + done) as *u16, (count - done) as u32, &mut written, null) == 0 { val why := GetLastError(); if why != error_operation_aborted { return errno_of(why); } } done += written as u64; } return 0; } # What a read of the console gave as UTF-8 that there was no room for, which # the next read gives first. var console_pending: *mut u8; var pending_at: u64; var pending_end: u64; # The first half of a character a read of the console ended in, which the next # read finishes, or zero. var console_half: u16; # Units read from the console at a time. const console_units_read: u64 = 4096; # Reads what is typed at a console, as UTF-8. def console_read(handle: u64, into: *mut u8, length: u64): i64 { if length == 0 { return 0; } while pending_at == pending_end { # A character the last read cut short begins what this one gives. var units: u16[console_units_read]; var held: u32 = 0; if console_half != 0 { units[0] = console_half; held = 1; } var read: u32 = 0; SetLastError(0); val ok := ReadConsoleW(handle, ((&mut units) as *mut u16) + held, console_units_read as u32 - held, &mut read, null); val why := GetLastError(); if ok == 0 && why != error_operation_aborted { return errno_of(why); } # Ctrl-C ends a read with nothing, rather than ending the input, a moment # before the system notes the signal; the read is made again where no # handler ran. if read == 0 { if why != error_operation_aborted { return 0; } val event := interrupting(); if event != 0 { WaitForSingleObject(event, 100); } if run_handlers() { return -4; } continue; } # A line beginning with Ctrl-Z ends the input. if held == 0 && units[0] == 0x1A { return 0; } # A read that ends in the first half of a character, as a long line read in # parts may, keeps it for the next. read += held; console_half = 0; if units[read - 1] >= 0xD800 && units[read - 1] < 0xDC00 { console_half = units[read - 1]; read--; } if console_pending == null { console_pending = raw_allocate(console_units_read * 3); } pending_end = narrow((&units) as *u16, read as u64, console_pending, console_units_read * 3) as u64; pending_at = 0; } val count := length < pending_end - pending_at ? length : pending_end - pending_at; memcpy(into, console_pending + pending_at, count); pending_at += count; return count as i64; }