From 7614e6413871b07b9e18d302b83bd4e90ef1088a Mon Sep 17 00:00:00 2001 From: SoraKatadzuma Date: Sun, 6 Dec 2026 13:08:13 -0600 Subject: [PATCH] Initial Commit --- .editorconfig | 9 + .gitignore | 1 + CHANGELOG.md | 15 + LICENSE | 18 + README.md | 64 + blossomfile | 35 + system/clock.sakura | 20 + system/files.sakura | 99 ++ system/io_error.sakura | 39 + system/linux/linux.sakura | 26 + system/linux/x86_64.sakura | 71 + system/on_linux.sakura | 1016 +++++++++++++ system/on_linux_x86_64.sakura | 52 + system/on_windows.sakura | 2459 +++++++++++++++++++++++++++++++ system/on_windows_x86_64.sakura | 58 + system/system.sakura | 262 ++++ system/windows/waits.sakura | 18 + system/windows/windows.sakura | 270 ++++ tests/main.sakura | 120 ++ tests/signals.sakura | 541 +++++++ 20 files changed, 5193 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 blossomfile create mode 100644 system/clock.sakura create mode 100644 system/files.sakura create mode 100644 system/io_error.sakura create mode 100644 system/linux/linux.sakura create mode 100644 system/linux/x86_64.sakura create mode 100644 system/on_linux.sakura create mode 100644 system/on_linux_x86_64.sakura create mode 100644 system/on_windows.sakura create mode 100644 system/on_windows_x86_64.sakura create mode 100644 system/system.sakura create mode 100644 system/windows/waits.sakura create mode 100644 system/windows/windows.sakura create mode 100644 tests/main.sakura create mode 100644 tests/signals.sakura diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c6c8b36 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cfecb95 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.blossom diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..3cc3473 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +Each version's changes, newest first. Versions follow [semantic +versioning](https://semver.org). + +## Unreleased + +- `system` is a package of its own, moved from the compiler's repository, + where it shipped beside `sakurac` as `core` and the runtime do. blossom gives + it to a program as it gives any library, as `--lib system=DIR`, and std + requires it, so a program reading std reads it too. Its tests, those of + signals, moved with it from the compiler's `tests/core`. +- Where `system` and the compiler must agree, as on `handle` and `dispatch`, + which the compiler calls, `when compiler >= ...` chooses what each release of + the compiler understands, since `system` is no longer released with it. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b8bae39 --- /dev/null +++ b/LICENSE @@ -0,0 +1,18 @@ +MIT License + +Copyright (c) 2026 Malunal Studios, LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..28e052b --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# system + +The layer of the Sakura programming language beneath its standard library that +talks to the operating system, and the only one that knows which system it +runs on. [std](https://git.malunal.studio/sakura/std)'s `std::io` is written +once over it, for every system, and is what programs use; this layer is for +what `std::io` doesn't cover. + +It reads `core` alone, which ships with the compiler, +[sakurac](https://git.malunal.studio/sakura/sakurac), and is versioned apart +from both. + +| Module | What it holds | +| --- | --- | +| `system` | Files and directories, who may use them, processes, signals, clocks, threads, and `io_error`, why an operation failed: the same operations on every system | +| `system::linux` | Linux's system calls, each declared once | +| `system::windows` | The functions of `kernel32.dll`, each declared once | + +## Using it + +A program reading std reads `system` too, since std requires it: blossom gives +it to `sakurac` as `--lib system=DIR`, as it gives any library. A project +reading it directly requires it as any package and lists it in its `deps`: + +```yaml +requires: +- https://git.malunal.studio/sakura/system@v1.0.0 + +targets: +- name: tool + type: program + deps: [system] +``` + +Without blossom, `sakurac` is given it the same way, as +`--lib system=DIR`, or finds it in the `share/sakura` folder nearest above +itself, where `blossom install` puts it. + +## Supporting another system + +Each system implements the same operations in a section of its own, as +`on_linux.sakura` and `on_windows.sakura` do, with the numbers that differ by +processor in another, as `on_linux_x86_64.sakura`. Another system is supported +by writing those two, with the same names and signatures, and nothing above +this layer changes. `system.sakura` lists the operations each system provides. + +## The compiler + +The compiler relies on two things of `system` by name: `system::handle`, whose +signals `system::dispatch` handles, which the compiler calls where nothing +written does, and the system calls, whose memory the machine tracks as a +checked program runs. A change to either is chosen by the compiler's version, +as `when compiler >= 1.2.0 { ... }`, so each release of the compiler reads the +`system` it understands. + +## Tests + +``` +blossom test +``` + +runs `system.tests`, the tests of signals, with std's repository beside this +one. Each test runs in a copy of the program, so what one does with a signal is +its own. diff --git a/blossomfile b/blossomfile new file mode 100644 index 0000000..d9c9602 --- /dev/null +++ b/blossomfile @@ -0,0 +1,35 @@ +name: system +gpid: sakura +semv: 1.0.0 + +# std, for the tests alone, by its folder beside this one until `system` is +# released: `system` itself reads `core` alone, so a project requiring it never +# reads std through it. +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 + +# The layer beneath std that talks to the operating system: one library, the +# module `system`, in the folder of its name, with `system::linux` and +# `system::windows` within it. +targets: +- name: system + type: library + root: ./system + +# Its tests, built and run as an executable, each in a copy of the program, so +# what one does with a signal is its own. +tests: +- name: system.tests + type: program + runs: native + deps: [system, std.io, std.process, std.testing, std.thread] + srcs: [tests/*.sakura] + +exports: +- system + +package: + lic: MIT + desc: The layer of Sakura beneath its standard library that talks to the operating system. + auth: John Christman + url: https://git.malunal.studio/sakura/system diff --git a/system/clock.sakura b/system/clock.sakura new file mode 100644 index 0000000..a4091dc --- /dev/null +++ b/system/clock.sakura @@ -0,0 +1,20 @@ +#! @file clock.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the kinds of clock a system keeps, which `system` reads on each +#! system and `std::time` gives as moments. + +module system; + + +#! A clock a system keeps, which `system::clock` reads. +pub enum clock_kind: u8 { + #! The time of day, since 1970 began in UTC. The system sets it, so it may go + #! forward or back, as when it is corrected over a network. + wall, + #! A clock that only ever goes forward, from a start that means nothing, which + #! is what measures how long something took. + steady, +} diff --git a/system/files.sakura b/system/files.sakura new file mode 100644 index 0000000..c6674c3 --- /dev/null +++ b/system/files.sakura @@ -0,0 +1,99 @@ +#! @file files.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what `system` and `std::io` above it both speak of files in: what +#! kind of file something is, who may do what with it, how one is opened, where +#! a seek is measured from, and what is known of one. They are the system's, so +#! `system` names them without reaching up into the layer above it. + +module system; + +#! What kind of file a path names. +pub enum file_kind: u8 { + other, #! A device, a pipe, a socket, or anything else. + regular, #! A file that holds bytes. + directory, #! A directory, which holds other files. + link, #! A link to another path, which is only seen where links are not followed. +} + +#! Who may do what with a file: read it, write it, or run it, each for its +#! owner, its group, and everyone else, as nine bits. +#! +#! These are the bits POSIX systems keep for every file, written in octal as +#! `0o644`, and they are given and taken as those systems keep them. Those +#! systems may also set three more, the set-user, set-group, and sticky bits, +#! which are kept as they are. +#! +#! Windows keeps less: a file is read only or it is not, and whether it runs is +#! decided by its name. There, permissions read as readable by everyone, +#! writable by everyone unless the file is read only, and runnable by everyone +#! for a directory or a program. Setting them looks only at whether the owner +#! may write, which clears or sets the file's read-only attribute. So +#! `is_read_only` and `with_read_only` mean the same on every system. +pub type permissions = u32; + +pub val permissions::owner_read := 0o400; #! The owner may read it. +pub val permissions::owner_write := 0o200; #! The owner may write it. +pub val permissions::owner_execute := 0o100; #! The owner may run it, or search it where it is a directory. +pub val permissions::group_read := 0o040; #! Its group may read it. +pub val permissions::group_write := 0o020; #! Its group may write it. +pub val permissions::group_execute := 0o010; #! Its group may run it, or search it. +pub val permissions::others_read := 0o004; #! Everyone else may read it. +pub val permissions::others_write := 0o002; #! Everyone else may write it. +pub val permissions::others_execute := 0o001; #! Everyone else may run it, or search it. + +#! What a new file is given, less what the system's mask of the program takes +#! away, as `0o644` from the usual mask of `0o022`. +pub val permissions::default_file := 0o666; + +#! What a new directory is given, less what the system's mask takes away. +pub val permissions::default_directory := 0o777; + +#! Whether no one may write the file. +#! @param this The permissions to read. +#! @returns Whether none of the three write bits is set. +pub val permissions::is_read_only: bool { + get => (this & 0o222) == 0; +} + +#! Makes permissions that are read only, or that let the owner write. +#! @param this The permissions to start from. +#! @param read_only Whether no one may write the file. +#! @returns The permissions without any write bit when read only, and otherwise +#! with the owner's write bit added, leaving who else may write as it +#! was. +pub def permissions::with_read_only(&this, read_only: bool): permissions { + if read_only { + return this & 0o7555; + } + return this | 0o200; +} + +#! How a file is opened, combined with `|`. A file opened without `write` or +#! `append` is opened for reading. +pub type open_flags = u32; + +pub val open_flags::read := 1; #! The file is read. +pub val open_flags::write := 2; #! The file is written. +pub val open_flags::create := 4; #! The file is made where there is none, as `write` needs. +pub val open_flags::truncate := 8; #! What the file held is thrown away. +pub val open_flags::append := 16; #! Every write goes at the end; this implies `write`. +pub val open_flags::exclusive := 32; #! With `create`, opening fails where the file exists. + +#! Where an offset to seek to is measured from. +pub type whence = i32; + +pub val whence::start := 0; #! The start of the file. +pub val whence::current := 1; #! Where the next read or write happens. +pub val whence::end := 2; #! The end of the file. + +#! What is known of a file. +pub struct file_info { + pub var kind: file_kind; #! A file, a directory, a link, or another kind. + pub var size: u64; #! In bytes. A directory's size means what its system says. + pub var permissions: permissions; #! Who may read, write, and run it. + pub var modified: i64; #! When its bytes last changed, in nanoseconds since 1970. + pub var accessed: i64; #! When it was last read, in nanoseconds since 1970. +} diff --git a/system/io_error.sakura b/system/io_error.sakura new file mode 100644 index 0000000..f21c03b --- /dev/null +++ b/system/io_error.sakura @@ -0,0 +1,39 @@ +#! @file io_error.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains why reading or writing a stream, or an operation on a file, failed, +#! which `system` reports, and `std::io`'s streams give. + +module system; + +#! Why an operation on a file, a directory, or the working directory failed. +#! +#! Every operating system reports its failures by numbers of its own, and +#! `system::error_of` turns them into these, so the same failure is the same +#! member everywhere. A failure the members do not name is `other`, and +#! `unexpected_end` is one `std::io` finds itself, never the system. Only a +#! program that handles a signal is ever `interrupted`, and only in a wait for +#! something to arrive: a read, or a wait for a child, which it can try again. +pub enum io_error: u8 { + other, #! A failure none of the other members names. + not_found, #! Nothing is at the path, or a directory on the way to it is missing. + permission_denied, #! The program may not do this to the file. + already_exists, #! Something is already at the path. + not_a_directory, #! A directory was needed, and the path names something else. + is_a_directory, #! A file was needed, and the path names a directory. + directory_not_empty, #! The directory still holds something. + invalid, #! A path, handle, or argument the operation cannot take. + name_too_long, #! The path, or a name within it, is longer than the system takes. + busy, #! The file is in use in a way that stops this. + read_only, #! The file system holding the file is read only. + no_space, #! The device, or the user's share of it, is full. + too_many_open, #! The program, or the system, has as many files open as it may. + cross_device, #! A file cannot be renamed onto another device. + link_loop, #! Following the links in the path went around in a circle. + broken_pipe, #! What was written to has nothing reading it any more. + unsupported, #! The system does not do this. + unexpected_end, #! The input ended before all that was asked for was read. + interrupted, #! A signal the program handles came, ending the wait early. +} diff --git a/system/linux/linux.sakura b/system/linux/linux.sakura new file mode 100644 index 0000000..919a11d --- /dev/null +++ b/system/linux/linux.sakura @@ -0,0 +1,26 @@ +#! @file linux.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `system::linux`: what Linux gives a program, declared once for std +#! and anything else that reaches the system itself. A program reaches Linux by +#! system calls, whose numbers and the layouts of what they read and write +#! differ by processor, so each processor's are in a file of its own, as +#! `x86_64.sakura`. + + +module system::linux when os == linux; + +#! Makes a system call, as the operations here do. Its numbers, and what it +#! reads and writes, are the system's, and differ by processor. +#! @param n The number of the call. +#! @param a Its first argument. +#! @param b Its second. +#! @param c Its third. +#! @param d Its fourth. +#! @param e Its fifth. +#! @param f Its sixth. +#! @returns What the call gives, or the negated error number where it fails. +@intrinsic +pub def syscall(n: i64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64): i64; diff --git a/system/linux/x86_64.sakura b/system/linux/x86_64.sakura new file mode 100644 index 0000000..a79ff99 --- /dev/null +++ b/system/linux/x86_64.sakura @@ -0,0 +1,71 @@ +#! @file x86_64.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what `system::linux` gives of Linux on x86-64. +#! +#! What a program needs to know of Linux on x86-64: the numbers of the system +#! calls it makes, the flags that differ by processor, and +#! where `stat` writes what `file_info` is read from. + + +module system::linux when os == linux && arch == x86_64; + +pub val call_read: i64 = 0; +pub val call_write: i64 = 1; +pub val call_open: i64 = 2; +pub val call_close: i64 = 3; +pub val call_stat: i64 = 4; +pub val call_fstat: i64 = 5; +pub val call_lstat: i64 = 6; +pub val call_poll: i64 = 7; +pub val call_lseek: i64 = 8; +pub val call_mmap: i64 = 9; +pub val call_munmap: i64 = 11; +pub val call_rt_sigaction: i64 = 13; +pub val call_rt_sigprocmask: i64 = 14; +pub val call_dup2: i64 = 33; +pub val call_nanosleep: i64 = 35; +pub val call_getpid: i64 = 39; +pub val call_fork: i64 = 57; +pub val call_execve: i64 = 59; +pub val call_wait4: i64 = 61; +pub val call_kill: i64 = 62; +pub val call_fcntl: i64 = 72; +pub val call_getcwd: i64 = 79; +pub val call_chdir: i64 = 80; +pub val call_rename: i64 = 82; +pub val call_mkdir: i64 = 83; +pub val call_rmdir: i64 = 84; +pub val call_unlink: i64 = 87; +pub val call_chmod: i64 = 90; +pub val call_fchmod: i64 = 91; +pub val call_sched_yield: i64 = 24; +pub val call_rt_sigsuspend: i64 = 130; +pub val call_gettid: i64 = 186; +pub val call_futex: i64 = 202; +pub val call_sched_getaffinity: i64 = 204; +pub val call_getdents64: i64 = 217; +pub val call_clock_gettime: i64 = 228; +pub val call_exit_group: i64 = 231; +pub val call_newfstatat: i64 = 262; +pub val call_pipe2: i64 = 293; + +pub val open_directory := 0x10000u; + +pub const stat_bytes: u64 = 144; +pub val stat_mode := 24u; +pub val stat_size := 48u; +pub val stat_accessed := 72u; # Seconds, then nanoseconds. +pub val stat_modified := 88u; # Seconds, then nanoseconds. + +# What `fcntl` is asked: a copy of a handle at the lowest free number from +# another up, or the handle's flags, of which only close-on-exec is set. +pub val f_dupfd := 0u; +pub val f_setfd := 2u; + +# How `rt_sigprocmask` changes the signals held off: adding some, or setting +# all of them. +pub val sig_block := 0u; +pub val sig_setmask := 2u; diff --git a/system/on_linux.sakura b/system/on_linux.sakura new file mode 100644 index 0000000..f90aab8 --- /dev/null +++ b/system/on_linux.sakura @@ -0,0 +1,1016 @@ +#! @file on_linux.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the operations of `system` on Linux, over the system calls they +#! are made of. +#! +#! The operations of `system` on Linux, over the system calls they are made +#! of, which fail by giving the negated error number, as the operations do. The +#! calls are made through `system::linux`, which declares their numbers, and +#! where `stat` writes what `file_info` is read from, for each processor. + +import system::linux; + +module system when os == linux; + + +#! A handle to an open file or directory, which only the system makes. +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 = 4096; + +# Bytes read of a directory at a time. +const listing_bytes: u64 = 16384; + +#! Opens the file at a path. +#! @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, less the mask. +#! @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 writes := (flags & (open_flags::write | open_flags::append)) != 0; + var native: u64 = writes ? (reads ? 2 : 1) : 0; + native = native | 0x80000; + if (flags & open_flags::create) != 0 { + native = native | 0x40; + } + if (flags & open_flags::truncate) != 0 { + native = native | 0x200; + } + if (flags & open_flags::append) != 0 { + native = native | 0x400; + } + if (flags & open_flags::exclusive) != 0 { + native = native | 0x80; + } + return on_path(call_open, path, native, mode) 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 { + var status: u8[stat_bytes]; + val at := (&mut status) as *mut u8; + return described(on_path(call_stat, path, at as u64, 0), at, 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 { + var status: u8[stat_bytes]; + val at := (&mut status) as *mut u8; + return described(on_path(call_lstat, path, at as u64, 0), at, out); +} + +#! Sets the permissions of the file at a path. +#! @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 { + return on_path(call_chmod, path, mode, 0) as i32; +} + +#! Makes a directory. +#! @param path The path of the directory, whose parent must exist. +#! @param mode The permissions to give it, less the mask. +#! @returns Zero when it was made. +pub def mkdir(path: strview, mode: u32): i32 { + return on_path(call_mkdir, path, mode, 0) as i32; +} + +#! Removes an empty directory. +#! @param path The path of the directory. +#! @returns Zero when it was removed. +pub def rmdir(path: strview): i32 { + return on_path(call_rmdir, path, 0, 0) as i32; +} + +#! Removes a file, or a link without what it leads to, but not a directory. +#! @param path The path of the file. +#! @returns Zero when it was removed. +pub def unlink(path: strview): i32 { + return on_path(call_unlink, path, 0, 0) 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. +#! @returns Zero when it was moved. +pub def rename(from: strview, to: strview): i32 { + var target: u8[path_limit]; + val at := (&mut target) as *mut u8; + val bad := terminate(to, at); + if bad < 0 { + return bad as i32; + } + return on_path(call_rename, from, at as u64, 0) as i32; +} + +#! 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. +#! @returns The number of bytes written. +pub def getcwd(into: *mut u8, length: u64): i64 { + val result := syscall(call_getcwd, into as u64, length, 0, 0, 0, 0); + return result < 0 ? result : result - 1; +} + +#! 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 { + return on_path(call_chdir, path, 0, 0) as i32; +} + +#! Reads from the file into a buffer, waiting until something arrives. +#! @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 { + return waited(call_read, (this as i64) as u64, into as u64, length); +} + +#! Writes bytes to the file. +#! +#! Writing to a pipe nothing reads fails with -32, which is `broken_pipe`, once +#! the program has made a pipe, as `pipe` says. Writing to the program's own +#! output or error still stops the program, quietly, as it would have before. +#! @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 := this as i64; + val result := retried(call_write, handle as u64, from as u64, length); + if result == -32 && quieted && (handle == 1 || handle == 2) { + _ = restore(signal::pipe); + _ = 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. +pub def fd::seek(&this, offset: i64, from: whence): i64 { + if from < 0 || from > 2 { + return -22; + } + return syscall(call_lseek, (this as i64) as u64, offset as u64, from as u64, 0, 0, 0); +} + +#! Closes the file. +#! @param this The handle of the file to close. +#! @returns Zero when the file was closed. +pub def fd::close(&this): i32 { + val result := syscall(call_close, (this as i64) as u64, 0, 0, 0, 0, 0); + return result < 0 ? result as i32 : 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 { + var status: u8[stat_bytes]; + val at := (&mut status) as *mut u8; + return described(syscall(call_fstat, (this as i64) as u64, at as u64, 0, 0, 0, 0), at, out); +} + +#! Sets the permissions of the file. +#! @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 { + return syscall(call_fchmod, (this as i64) as u64, mode as u64, 0, 0, 0, 0) as i32; +} + +#! A directory being read, one name at a time, which `opendir` starts and +#! `close` ends. +pub struct dir_stream : owning { + var _handle: fd; + var _buffer: *mut u8; #! What `getdents64` last wrote, which is null where not open. + var _filled: u64; + var _at: u64; +} + +#! 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 { + val handle := on_path(call_open, path, open_directory | 0x80000, 0); + if handle < 0 { + return handle as i32; + } + + into._handle = handle as fd; + into._buffer = raw_allocate(listing_bytes); + into._filled = 0; + into._at = 0; + 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._buffer == null { + return -9; + } + + while true { + if this._at >= this._filled { + val handle := (this._handle as i64) as u64; + val count := retried(call_getdents64, handle, this._buffer as u64, listing_bytes); + if count <= 0 { + return count as i32; + } + this._filled = count as u64; + this._at = 0; + } + + # A record holds its file's number, an offset, its own length, the kind, and + # the name, which ends in a zero. + val record := this._buffer + this._at; + this._at += (*((record + 16) as *mut u16)) as u64; + val name := record + 19; + var length := 0u; + while name[length] != 0 { + length++; + } + if name[0] == '.' && (length == 1 || (length == 2 && name[1] == '.')) { + continue; + } + + out.name = strview::over(name, length); + out.kind = this.kind_of(record[18], name); + 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._buffer == null { + return; + } + + syscall(call_close, (this._handle as i64) as u64, 0, 0, 0, 0, 0); + raw_release(this._buffer); + this._buffer = null; +} + +# The kind a record gives, asking the file itself where the file system does not +# say, as some do not. +def dir_stream::kind_of(&this, kind: u8, name: *mut u8): file_kind { + if kind == 4 { return file_kind::directory; } + if kind == 8 { return file_kind::regular; } + if kind == 10 { return file_kind::link; } + if kind != 0 { return file_kind::other; } + + var status: u8[stat_bytes]; + val at := (&mut status) as *mut u8; + val handle := (this._handle as i64) as u64; + if syscall(call_newfstatat, handle, name as u64, at as u64, 0x100, 0, 0) < 0 { + return file_kind::other; + } + return kind_of_mode(*((at + stat_mode) as *mut u32)); +} + +#! 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, + }; +} + +#! Starts a copy of the program, which goes on from here as the program does, +#! with memory of its own, so nothing either changes reaches the other. +#! @returns Zero in the copy, and in the program the number the copy is known +#! by, which `wait` takes, or a negative error number when no copy +#! started. +pub def fork(): i64 { + return syscall(call_fork, 0, 0, 0, 0, 0, 0); +} + +#! Waits for a copy of the program that `fork` started to stop. +#! @param child The number `fork` gave the program for the copy, or -1 for +#! whichever of its copies stops first. +#! @param status How the copy stopped. +#! @returns The number of the copy that stopped, or a negative error number, +#! which is `-4` where a signal the program handles ended the wait. +pub def wait(child: i64, status: &mut process_status): i64 { + val raw := raw_allocate_zeroed(4) as *mut i32; + val result := waited(call_wait4, child as u64, raw as u64, 0); + val word := raw[0]; + raw_release(raw as *mut u8); + if result < 0 { + return result; + } + + status.exited = (word & 0x7F) == 0; + status.code = (word >> 8) & 0xFF; + status.signal = word & 0x7F; + return result; +} + +#! Sends a signal to a process. +#! @param process The number the system knows the process by, as `getpid` +#! gives the program its own, and `fork` the program a copy's. +#! @param sent The signal to send. +#! @returns Zero when it was sent. +pub def kill(process: i64, sent: signal): i32 { + return syscall(call_kill, process as u64, number_of(sent) as u64, 0, 0, 0, 0) as i32; +} + +#! Sends a signal to the program itself. A signal the program handles is noted +#! before this returns, and its handler runs at the next safe point. +#! @param sent The signal to send. +#! @returns Zero when it was sent. +pub def raise(sent: signal): i32 { + return kill(getpid(), sent); +} + +#! The number the system knows the program by. +#! @returns The number, which `kill` takes. +pub def getpid(): i64 { + return syscall(call_getpid, 0, 0, 0, 0, 0, 0); +} + +#! 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`, since the system would then throw away how each child +#! stopped, which `wait` gives: 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 most, stopping the program. +#! @param which The signal to restore. +#! @returns Zero when it is restored. +pub def restore(which: signal): i32 { + return disposed(which, 0); +} + +#! 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; + quieted = quieted && which != signal::pipe; + 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; + quieted = quieted && which != signal::pipe; + 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. +pub def pause(): void { + # The signals handled are held off, so that none comes between finding none + # waiting and the wait, which lets them come and waits in one step. The + # system's set of signals has a bit for each number less one. + var held: u64 = handled >> 1; + var before: u64 = 0; + val holding := (&mut held) as *mut u64; + val kept := (&mut before) as *mut u64; + syscall(call_rt_sigprocmask, sig_block, holding as u64, kept as u64, 8, 0, 0); + while !run_handlers() { + syscall(call_rt_sigsuspend, kept as u64, 8, 0, 0, 0, 0); + if dispatching { + break; + } + } + syscall(call_rt_sigprocmask, sig_setmask, kept as u64, 0, 8, 0, 0); +} + +#! 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 { + # The system's `CLOCK_REALTIME` is 0, and its `CLOCK_MONOTONIC` 1. It writes + # seconds, then nanoseconds. + var spec: i64[2]; + val at := (&mut spec) as *mut i64; + syscall(call_clock_gettime, which == clock_kind::wall ? 0 : 1, at as u64, 0, 0, 0, 0); + return spec[0] * 1000000000 + spec[1]; +} + +#! Waits for a length of time. +#! @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 only interrupts the wait, +#! which goes on for what is left. +pub def sleep(nanoseconds: i64): i32 { + if nanoseconds <= 0 { + return 0; + } + + # The system takes seconds, then nanoseconds, and writes what is left of a + # wait a signal interrupts. + var wanted: i64[2]; + var left: i64[2]; + wanted[0] = nanoseconds / 1000000000; + wanted[1] = nanoseconds % 1000000000; + val asking := (&mut wanted) as *mut i64; + val unwaited := (&mut left) as *mut i64; + while true { + val result := syscall(call_nanosleep, asking as u64, unwaited as u64, 0, 0, 0, 0); + if result != -4 { + return result as i32; + } + if run_handlers() { + return -4; + } + wanted[0] = left[0]; + wanted[1] = left[1]; + } + return 0; +} + +#! Waits while a word holds what is expected, until another thread or process +#! 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. +#! @param at The word, which processes sharing the memory share too. +#! @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, -110 where the +#! time ran out, and -4 where a signal interrupted it. +pub def futex_wait(at: *mut u32, expected: u32, timeout: i64): i32 { + # The system takes a length of time as seconds, then nanoseconds, or none. + var spec: i64[2]; + spec[0] = timeout / 1000000000; + spec[1] = timeout % 1000000000; + val length: u64 = timeout < 0 ? 0 : ((&mut spec) as *mut i64) as u64; + return syscall(call_futex, at as u64, futex_op_wait, expected as u64, length, 0, 0) as i32; +} + +#! Wakes threads or processes waiting on a word. +#! @param at The word. +#! @param count How many to wake at most. +#! @returns How many it woke, or a negative error number. +pub def futex_wake(at: *mut u32, count: u32): i32 { + return syscall(call_futex, at as u64, futex_op_wake, count as u64, 0, 0, 0) as i32; +} + +# The operations of `futex` the program asks for: waiting and waking, shared with +# other processes mapping the memory, so a word in such memory serves them too. +val futex_op_wait := 0u; +val futex_op_wake := 1u; + +#! 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 { + # The system writes a set of processors, one bit each, giving its bytes. + var set: u64[16]; + val written := syscall(call_sched_getaffinity, 0, 128, ((&mut set) as *mut u64) as u64, 0, 0, 0); + if written <= 0 { + return 1; + } + var count: u32 = 0; + for i in 0..(written as u64 / 8) { + var word: u64 = set[i]; + while word != 0 { + word = word & (word - 1); + count++; + } + } + return count == 0 ? 1 : count; +} + +#! The number the system knows the calling thread by, which is the program's +#! own number in the thread it began with. +#! @returns The number. +pub def thread_id(): u64 { + return syscall(call_gettid, 0, 0, 0, 0, 0, 0) as u64; +} + +#! Lets the system run other threads before this one goes on. +pub def yield_now(): void { + syscall(call_sched_yield, 0, 0, 0, 0, 0, 0); +} + +# Whether the calling thread is the one the program began with, whose number is +# the program's. +def is_first_thread(): bool { + return thread_id() == getpid() as u64; +} + +# Sets what the system does with a signal: 0 for its default, and 1 to throw it +# away, giving zero, or the negated error number. +def disposed(which: signal, action: u64): i32 { + var act: u64[4]; + val at := (&mut act) as *mut u64; + at[0] = action; + val result := syscall(call_rt_sigaction, number_of(which) as u64, at as u64, 0, 8, 0, 0) as i32; + 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; + quieted = quieted && which != signal::pipe; + return result; +} + +# The signals the program ignores, one bit each by number, which a program it +# starts is given at their defaults. +var ignored: u64; + +# Whether std ignores `pipe`, which it does once the program makes a pipe where +# the program has neither handled nor ignored the signal itself. +var quieted: bool; + +# Has the system ignore `pipe`, so that writing to a pipe nothing reads fails +# rather than stopping the program, where the program has said nothing of the +# signal itself. +def quiet_broken_pipes(): void { + val bit := 1u << (number_of(signal::pipe) as u64); + if quieted || ((handled | ignored) & bit) != 0 { + return; + } + if disposed(signal::pipe, 1) == 0 { + quieted = true; + } +} + +#! The path of the device that reads as empty, and throws away what is written +#! to it. +pub val null_device: strview = "/dev/null"; + +#! 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 then fails with -32, which is `broken_pipe`, +#! rather than stopping the program, as the system would by default. The first +#! pipe has the system ignore `signal::pipe`, where the program has neither +#! handled nor ignored it itself, and `fd::write` still stops the program where +#! its own output or error is what nothing reads. +#! @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 ends: i32[2]; + val at := (&mut ends) as *mut i32; + val made := syscall(call_pipe2, at as u64, 0x80000, 0, 0, 0, 0); + if made < 0 { + return made as i32; + } + + quiet_broken_pipes(); + reading = ends[0]; + writing = ends[1]; + 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. The signals this program ignores are put back at their +#! defaults for it, and those it handles go back to theirs by themselves. +#! @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, and -22 where a text the +#! request holds has a zero in it. +pub def spawn(request: &spawn_request): i64 { + var laid: spawn_block; + if !laid.lay_out(request) { + return -22; + } + + # The copy that becomes the program writes why where it cannot. Both ends close + # on `execve`, so nothing comes through where the program starts. + var ends: i32[2]; + val at := (&mut ends) as *mut i32; + val piped := syscall(call_pipe2, at as u64, 0x80000, 0, 0, 0, 0); + if piped < 0 { + raw_release(laid.block); + return piped; + } + + val child := syscall(call_fork, 0, 0, 0, 0, 0, 0); + if child == 0 { + become(request, &laid, ends[1]); + } + + syscall(call_close, ends[1] as u64, 0, 0, 0, 0, 0); + raw_release(laid.block); + var code: i32 = 0; + val read := child < 0 ? 0 : retried(call_read, ends[0] as u64, ((&mut code) as *mut i32) as u64, 4); + syscall(call_close, ends[0] as u64, 0, 0, 0, 0, 0); + if child < 0 || read != 4 { + return child; + } + + # The copy has stopped, and is waited for so that it leaves nothing behind. + var word: i32 = 0; + retried(call_wait4, child as u64, ((&mut word) as *mut i32) as u64, 0); + return -(code as i64); +} + +#! Waits until one of the handles can be read, or has ended, for at most a +#! while. +#! @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; + } + + # Each entry is a handle, then what is waited for and what came, as two halves + # of a word. Only reading is waited for, and an end or a failure comes anyway. + val entries := raw_allocate(handles.length * 8) as *mut i32; + for i in 0..handles.length { + entries[2 * i] = handles[i]; + entries[2 * i + 1] = 1; + } + val result := waited(call_poll, entries as u64, handles.length, (wait < 0 ? -1 : wait) as u64); + val came := entries as *mut i16; + for i in 0..handles.length { + ready[i] = result > 0 && came[4 * i + 3] != 0; + } + raw_release(entries as *mut u8); + return result as i32; +} + +# Where the system put the variables the program started with: pointers to text +# ending in a zero, then a null pointer. +@intrinsic +def environ(): **u8; + +# 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`. +#! @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; + } + + val each := environ(); + var count := 0u; + while each != null && each[count] != null { + count++; + } + val views := raw_allocate(count * size_of::()) as *mut strview; + for i in 0..count { + val text := each[i]; + var length := 0u; + while text[length] != 0 { + length++; + } + views[i] = strview::over(text, length); + } + + variables = span::::over(views as *strview, count); + viewed = true; + return variables; +} + +# What `spawn` copies a request into before the program starts: one block +# holding the runs of pointers `execve` takes, each ending in null, then each +# text, ending in a zero. +struct spawn_block { + var block: *mut u8; + var path: *mut u8; + var arguments: *mut u64; + var environment: *mut u64; + var directory: *mut u8; # Null where the request names none. +} + +# Copies a request into a block of its own, giving whether it could, which it +# cannot where a text holds a zero. +def spawn_block::lay_out(&mut this, request: &spawn_request): bool { + val arguments := request.arguments.length; + val variables := request.environment.length; + var size := (arguments + variables + 2) * 8 + request.program.length + request.directory.length + 2; + for i in 0..arguments { + size += request.arguments[i].length + 1; + } + for i in 0..variables { + size += request.environment[i].length + 1; + } + + this.block = raw_allocate_zeroed(size); + this.arguments = this.block as *mut u64; + this.environment = this.arguments + arguments + 1; + var at := (this.environment + variables + 1) as *mut u8; + this.path = at; + at = copied(request.program, at); + for i in 0..arguments { + this.arguments[i] = at as u64; + at = at == null ? null : copied(request.arguments[i], at); + } + for i in 0..variables { + this.environment[i] = at as u64; + at = at == null ? null : copied(request.environment[i], at); + } + this.arguments[arguments] = 0; + this.environment[variables] = 0; + this.directory = request.directory.length == 0 ? null : at; + if at != null && request.directory.length != 0 { + at = copied(request.directory, at); + } + + if at == null { + raw_release(this.block); + return false; + } + return true; +} + +# Copies text, then a zero, giving where the copy ends, or null where the text +# holds a zero itself. +def copied(text: strview, into: *mut u8): *mut u8 { + if into == null { + return null; + } + for i in 0..text.length { + if text.data[i] == 0 { + return null; + } + } + memcpy(into, text.data, text.length); + into[text.length] = 0; + return into + text.length + 1; +} + +# Becomes the program the request names, in the copy `spawn` started, making +# only system calls, so the copy changes nothing it shares with the program. +# Where it cannot, it writes why to `report`, and exits with 127, which runs +# nothing the program asked to be run as it stops. +def become(request: &spawn_request, laid: &spawn_block, report: i32): void { + # A handle below 3 not already where it goes would be overwritten by moving + # another there, so each is moved above them first. + var handles: i64[3]; + handles[0] = request.input as i64; + handles[1] = request.output as i64; + handles[2] = request.error as i64; + for i in 0u..3u { + if handles[i] >= 0 && handles[i] < 3 && handles[i] != i as i64 { + handles[i] = syscall(call_fcntl, handles[i] as u64, f_dupfd, 3, 0, 0, 0); + } + } + for i in 0u..3u { + if handles[i] == i as i64 { + syscall(call_fcntl, i, f_setfd, 0, 0, 0, 0); + continue; + } + syscall(call_dup2, handles[i] as u64, i, 0, 0, 0, 0); + } + + # Ignored signals stay ignored across `execve`, so each goes back to its + # default, and none is held off. + var act: u64[4]; + val default := (&mut act) as *mut u64; + for number in 1u..64u { + if ((ignored >> number) & 1) != 0 { + syscall(call_rt_sigaction, number, default as u64, 0, 8, 0, 0); + } + } + syscall(call_rt_sigprocmask, sig_setmask, default as u64, 0, 8, 0, 0); + + var failed: i64 = 0; + if laid.directory != null { + failed = syscall(call_chdir, laid.directory as u64, 0, 0, 0, 0, 0); + } + if failed >= 0 { + failed = syscall(call_execve, laid.path as u64, laid.arguments as u64, laid.environment as u64, 0, 0, 0); + } + + var code: i32 = (-failed) as i32; + syscall(call_write, report as u64, ((&mut code) as *mut i32) as u64, 4, 0, 0, 0); + syscall(call_exit_group, 127, 0, 0, 0, 0, 0); +} + +# Makes a system call on a path, with two more arguments, giving what it gives. +def on_path(n: i64, path: strview, b: u64, c: u64): i64 { + var text: u8[path_limit]; + val at := (&mut text) as *mut u8; + val bad := terminate(path, at); + if bad < 0 { + return bad; + } + return retried(n, at as u64, b, c); +} + +# Copies a path into `into`, then a zero, as the system calls read paths. Gives +# zero, or the negated error number where the path is too long or holds a zero. +def terminate(path: strview, into: *mut u8): i64 { + if path.length >= path_limit { + return -36; + } + for i in 0..path.length { + if path.data[i] == 0 { + return -22; + } + } + + memcpy(into, path.data, path.length); + into[path.length] = 0; + return 0; +} + +# Retries a system call interrupted by a signal, as everything that does not +# wait for something to arrive is, so that it is never left half done. The +# handlers run at the program's next safe point. +def retried(n: i64, a: u64, b: u64, c: u64): i64 { + while true { + val result := syscall(n, a, b, c, 0, 0, 0); + if result != -4 { + return result; + } + } + return 0; +} + +# Makes a system call that waits for something to arrive. Where a signal the +# program handles interrupts it, the handlers run, and the wait ends, giving -4; +# where none ran, as within a handler, it waits again. +def waited(n: i64, a: u64, b: u64, c: u64): i64 { + while true { + val result := syscall(n, a, b, c, 0, 0, 0); + if result != -4 || run_handlers() { + return result; + } + } + return 0; +} + +# Fills a description from what `stat` wrote, where the call that wrote it, which +# gave `result`, succeeded. Gives zero, or that call's failure. +def described(result: i64, status: *mut u8, out: &mut file_info): i32 { + if result < 0 { + return result as i32; + } + + val mode := *((status + stat_mode) as *mut u32); + val size := *((status + stat_size) as *mut i64); + out.kind = kind_of_mode(mode); + out.size = size < 0 ? 0 : size as u64; + out.permissions = mode & 0o7777; + out.modified = nanoseconds(status + stat_modified); + out.accessed = nanoseconds(status + stat_accessed); + return 0; +} + +# A time `stat` wrote, as seconds then nanoseconds, in nanoseconds. +def nanoseconds(at: *mut u8): i64 { + val words := at as *mut i64; + return words[0] * 1000000000 + words[1]; +} + +def kind_of_mode(mode: u32): file_kind { + val kind := mode & 0xF000; + if kind == 0x8000 { return file_kind::regular; } + if kind == 0x4000 { return file_kind::directory; } + if kind == 0xA000 { return file_kind::link; } + return file_kind::other; +} diff --git a/system/on_linux_x86_64.sakura b/system/on_linux_x86_64.sakura new file mode 100644 index 0000000..13ba774 --- /dev/null +++ b/system/on_linux_x86_64.sakura @@ -0,0 +1,52 @@ +#! @file on_linux_x86_64.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the numbers Linux gives the signals `system` names, on x86-64. + + +module system when os == linux && arch == x86_64; + +# The number Linux gives a signal on x86-64. +def number_of(which: signal): i32 { + return match which { + hangup => 1, + interrupt => 2, + quit => 3, + kill => 9, + user1 => 10, + user2 => 12, + pipe => 13, + alarm => 14, + terminate => 15, + child => 17, + resume => 18, + stop => 19, + suspend => 20, + resized => 28, + }; +} + +#! The signal Linux gives a number on x86-64, where it is one `signal` names. +#! @param number The number. +#! @returns The signal, or nothing. +pub def signal_of(number: i64): maybe { + return match number { + 1 => signal::hangup, + 2 => signal::interrupt, + 3 => signal::quit, + 9 => signal::kill, + 10 => signal::user1, + 12 => signal::user2, + 13 => signal::pipe, + 14 => signal::alarm, + 15 => signal::terminate, + 17 => signal::child, + 18 => signal::resume, + 19 => signal::stop, + 20 => signal::suspend, + 28 => signal::resized, + else => nothing{}, + }; +} diff --git a/system/on_windows.sakura b/system/on_windows.sakura new file mode 100644 index 0000000..5e088aa --- /dev/null +++ b/system/on_windows.sakura @@ -0,0 +1,2459 @@ +#! @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.span, &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: by +# whichever thread asks first, any of them as many, so it's atomic. +var ticks_per_second: atomic; + +#! 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); + } + + var frequency := ticks_per_second.load(); + if frequency == 0 { + QueryPerformanceFrequency(&mut frequency); + ticks_per_second.store(frequency); + } + var count: i64 = 0; + QueryPerformanceCounter(&mut count); + return (count / frequency) * 1000000000 + (count % frequency) * 1000000000 / frequency; +} + +# 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. A console program started by one with no console window, as a program +#! built `--windowed` is, is given a console no one sees, so no window opens for +#! it; started by one with a console, it shares that console. +#! @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.span) { + 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.span, 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.span); + 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.span, &mut path) < 0 || widen(line.span, &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.span, &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. Where this program has no console window, as one built `--windowed` +# has none, a console program it starts is given a console no one sees, rather +# than one Windows would open on the screen for it; where it has one, the +# program shares it, as before. A program of windows of its own is started as +# it would be either way. +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 { + var flags := unicode_block | extended_startup; + if GetConsoleWindow() == 0 { + flags = flags | create_no_window; + } + 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}".span); + } + 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}".span); +} + +# 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}:".span); + into.append($"{minute < 10 ? "0" : ""}{minute}:{second < 10 ? "0" : ""}{second}".span); +} + +# 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; +} diff --git a/system/on_windows_x86_64.sakura b/system/on_windows_x86_64.sakura new file mode 100644 index 0000000..ee27041 --- /dev/null +++ b/system/on_windows_x86_64.sakura @@ -0,0 +1,58 @@ +#! @file on_windows_x86_64.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains what `system` needs to know of Windows on x86-64. +#! +#! What `system` needs to know of Windows on x86-64: the numbers of the +#! signals. Windows numbers none of its own, so they are Linux's on x86-64, +#! which keeps the bits `watched` gives, and the numbers `signal_of` takes, the +#! same on both. + + +module system when os == windows && arch == x86_64; + +# The number a signal is given, as Linux gives it on x86-64. +def number_of(which: signal): i32 { + return match which { + hangup => 1, + interrupt => 2, + quit => 3, + kill => 9, + user1 => 10, + user2 => 12, + pipe => 13, + alarm => 14, + terminate => 15, + child => 17, + resume => 18, + stop => 19, + suspend => 20, + resized => 28, + }; +} + +#! The signal a number is given to, as Linux gives it on x86-64, where it is +#! one `signal` names. +#! @param number The number. +#! @returns The signal, or nothing. +pub def signal_of(number: i64): maybe { + return match number { + 1 => signal::hangup, + 2 => signal::interrupt, + 3 => signal::quit, + 9 => signal::kill, + 10 => signal::user1, + 12 => signal::user2, + 13 => signal::pipe, + 14 => signal::alarm, + 15 => signal::terminate, + 17 => signal::child, + 18 => signal::resume, + 19 => signal::stop, + 20 => signal::suspend, + 28 => signal::resized, + else => nothing{}, + }; +} diff --git a/system/system.sakura b/system/system.sakura new file mode 100644 index 0000000..85dad00 --- /dev/null +++ b/system/system.sakura @@ -0,0 +1,262 @@ +#! @file system.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `system`, the layer of the standard library that talks to the +#! operating system, as each system provides it, and what every system shares: a +#! directory's entries, how a copy of the program stopped, and stopping the +#! program. +#! +#! The layer of the standard library that talks to the operating system, and the +#! only one that knows which system it runs on. `std::io` is written once over +#! it, for every system, and is what programs use; this layer is for what +#! `std::io` does not cover. +#! +#! Each system implements the same operations in a section of its own, as +#! `linux.sakura` and `windows.sakura` do, with the numbers that differ by +#! processor in another, as `linux_x86_64.sakura`. Another system is supported +#! by writing those two, with the same names and signatures, and nothing above +#! this layer changes, but where the system cannot do what Linux does: as +#! Windows cannot `fork`, `std::testing` says with `when` what it does there +#! instead. +#! +#! The operations are thin: they take paths as text, as `path::view` gives it, +#! and fail by giving a negative number, the error number Linux would give, +#! which another system makes of its own, and which `error_of` turns into an +#! `io_error`. Each system provides: +#! +#! ``` +#! fd its handle to an open file, with fd::stdin, stdout, +#! and stderr, and `path_limit`, the longest path it takes +#! open(path, flags, mode) opens a file, as `open_flags` say, creating it with +#! the permissions `mode` gives where it is made +#! fd::read, write, put, seek, close, stat, chmod +#! stat, lstat describes the file at a path, following a link at +#! the end of it or not, into a `file_info` +#! chmod sets the permissions of the file at a path +#! mkdir, rmdir, unlink makes a directory, removes an empty one, removes a file +#! rename moves a file to another path, replacing a file there +#! getcwd, chdir reads and sets the working directory +#! dir_stream, opendir reads the names a directory holds, with their kinds +#! error_of what a failure means, as an `io_error` +#! fork, wait starts a copy of the program and waits for it, +#! which Windows starts from the start, by `respawn` +#! pipe, spawn, poll makes a pipe, starts another program, and waits, +#! for at most a while, until one of several handles +#! can be read +#! environment, null_device the variables the program started with, and the +#! path of the device that holds nothing +#! kill, raise, getpid sends a signal to a process, or to the program +#! itself, and gives the program's own number +#! ignore, restore, handle has the system throw a signal away, do what it +#! does by default, or note it for a handler +#! pause waits until a handler has run +#! clock, sleep reads the wall clock or the steady one, and waits +#! for a length of time +#! futex_wait, futex_wake waits while a word holds a value, and wakes those +#! waiting on it, which threads, and on Linux processes +#! sharing memory, wait for one another with +#! cpu_count, thread_id, how many processors the program may run on, the +#! yield_now calling thread's number, and letting others run +#! ``` +#! +#! Windows also provides `respawn`, which starts a copy of the program from its +#! start, and `zone_rule`, the rule of the zone the system is set to, since it +#! keeps no files of zones. +#! +#! What every system shares of signals is here: the `signal` each is, and the +#! handlers. A handler never runs in the middle of whatever the program was +#! doing, as C's does. The system's own handler only notes that the signal came, +#! and the program's runs at its next safe point: where one of the program's own +#! functions begins, or a pass of one of its loops, in a program that handles a +#! signal somewhere. A wait the signal interrupts runs the handlers too, then +#! ends, failing with `io_error::interrupted`. So a handler may do anything a +#! function may, and never finds a container, a string, or a writer of std in +#! the middle of a change. + + +module system; + +#! How a copy of the program that `fork` started stopped, or a program `spawn` +#! started, as `wait` gives it. +pub struct process_status { + pub var exited: bool; #! Whether it stopped by exiting, with `code`, rather than by a signal. + pub var code: i32; #! The status it exited with. + pub var signal: i32; #! The signal that stopped it, when it did not exit. +} + +#! What `spawn` starts a program with, all of which it copies before the program +#! starts. +pub struct spawn_request { + #! The path of the program, which is found already. + pub var program: strview; + #! What the program is given, the first being what it is called. + pub var arguments: span; + #! The variables it is given, each as `NAME=value`. + pub var environment: span; + #! Where it runs, or empty for where this program runs. + pub var directory: strview; + #! The handle its standard input is given. + pub var input: fd; + #! The handle its standard output is given. + pub var output: fd; + #! The handle its standard error is given. + pub var error: fd; +} + +#! A name a directory holds, as `dir_stream::next` gives it. +pub struct dir_entry { + pub var name: strview; #! Only good until the next entry is read. + pub var kind: file_kind; #! What the name is itself, not what a link there leads to. +} + +#! Stops the program with a status, having run everything asked of it. +#! +#! Whatever the program has written is written, and nothing it has yet to do is +#! done. A status of zero says the program did what it was asked to. +#! @param code The status to stop with, which Linux reads as a byte, and +#! Windows whole. +@intrinsic +pub def exit(code: i32): void; + +#! Stops the program at once, reporting where it was. +#! +#! This is for a program that has found something it cannot go on from. It is +#! not graceful: the report names the functions that were running, and the +#! status is the one every other fault gives. +@intrinsic +pub def abort(): void; + +#! Starts a thread of the system running a function given a context, which the +#! backend makes: a thread of the virtual machine, or of an executable with +#! stacks of its own. `std::thread` starts threads with it. +#! @param body The function the thread runs. +#! @param context What the function is given. +#! @returns The thread's number, or a negative error number. A program +#! evaluating a constant starts none. +@intrinsic +pub def start(body: def(*mut u8): void, context: *mut u8): i64; + +#! A signal the system, or another program, sends a program. +#! +#! The members are the same on every system, which numbers them in its own way. +#! Faults are not among them: reading through a null pointer, dividing by zero, +#! and the like stop the program with a report, since a fault is a mistake of +#! the program that no handler can put right. +pub enum signal: u8 { + #! SIGHUP: the terminal went away. By custom, a server reads its settings + #! again. + hangup, + #! SIGINT: Ctrl-C. + interrupt, + #! SIGQUIT: Ctrl-\. + quit, + #! SIGKILL: the program stops at once. It cannot be handled or ignored. + kill, + #! SIGUSR1: whatever the programs sending and receiving it agree on. + user1, + #! SIGUSR2: the same. + user2, + #! SIGPIPE: the program wrote to a pipe nothing reads. + pipe, + #! SIGALRM: a timer ran out. + alarm, + #! SIGTERM: the program is asked to stop. + terminate, + #! SIGCHLD: a child stopped, or was paused or resumed. + child, + #! SIGCONT: the program goes on after being paused. + resume, + #! SIGSTOP: the program is paused. It cannot be handled or ignored. + stop, + #! SIGTSTP: Ctrl-Z, asking the program to pause. + suspend, + #! SIGWINCH: the terminal changed size. + resized, +} + +#! A function that handles a signal, given the signal it handles, which it owns, +#! as a functor holding what it needs: whatever it was given as. +pub type handler = function; + +# How many members `signal` has. +const signal_count: u64 = 14; + +# The handler of each signal, by member, which holds nothing where none was +# given, and which signals the program handles, one bit each by the system's +# number. +var handlers: handler[signal_count]; +var handled: u64; + +# The signals the program watches for rather than handles, one bit each by the +# system's number, and the signals taken from the system that neither `watched` +# nor the handlers have yet. +var noting: u64; +var arrived: u64; + +# Whether a handler is running, so that another runs only once it returns. +var dispatching: bool; + +# Has the system note a signal of its number when it comes, rather than doing +# what it would, and end the waits the signal interrupts rather than go on with +# them. Gives zero, or a negative number. +@intrinsic +def catch_signal(number: i32): i32; + +# Gives the signals noted since they were last asked for, one bit each by the +# system's number, and forgets them in the same step. +@intrinsic +def take_signals(): u64; + +# Runs the handlers of the signals that have come. Safe points call this, which +# std's own code has none of. +def dispatch(): void { + _ = run_handlers(); +} + +# Runs the handler of each signal that has come, in the order of the system's +# numbers, until none has, giving whether any ran. Within a handler it runs +# none, so the signals that come while one runs are handled once it returns. A +# signal that came before the program stopped handling it is passed over. +# Handlers run in the thread the program began with, as each system's +# `is_first_thread` finds it, so a wait another thread's signal ended runs none. +def run_handlers(): bool { + if dispatching || !is_first_thread() { + return false; + } + + dispatching = true; + var ran := false; + while true { + arrived = arrived | take_signals(); + val waiting := arrived & ~noting; + arrived = arrived & noting; + if waiting == 0 { + break; + } + + # A handler may stop the program handling a signal that came with its own. + for number in 0u..64u { + if (((waiting & handled) >> number) & 1) == 0 { + continue; + } + val which := signal_of(number as i64) else { continue; }; + + # A handler is taken from its place while it runs, so one handling its own + # signal anew replaces it without closing what runs. It goes back where + # nothing replaced it, and closes where something did. + var by := move(&mut handlers[which as u64]); + if !by.holds() { + continue; + } + by(which); + ran = true; + if !handlers[which as u64].holds() { + handlers[which as u64] = move(&mut by); + } + } + } + dispatching = false; + return ran; +} diff --git a/system/windows/waits.sakura b/system/windows/waits.sakura new file mode 100644 index 0000000..d9c921f --- /dev/null +++ b/system/windows/waits.sakura @@ -0,0 +1,18 @@ +#! @file waits.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains the functions Windows keeps for waiting on a word, of +#! `system::windows`, which `system` and the runtime wait and wake with. They are +#! a library of their own, and a file names one library on Windows. + +extern import "api-ms-win-core-synch-l1-2-0.dll" when os == windows; + +extern module system::windows when os == windows; + +pub def WaitOnAddress( + at: *mut u32, compare: &u32, size: u64, milliseconds: u32 +): i32; +pub def WakeByAddressSingle(at: *mut u32): void; +pub def WakeByAddressAll(at: *mut u32): void; diff --git a/system/windows/windows.sakura b/system/windows/windows.sakura new file mode 100644 index 0000000..c89c942 --- /dev/null +++ b/system/windows/windows.sakura @@ -0,0 +1,270 @@ +#! @file windows.sakura +#! @author John Christman (sorakatadzuma@gmail.com) +#! @copyright Malunal Studios, LLC. +#! @license MIT +#! +#! Contains `system::windows`: what Windows gives a program, declared once for +#! std, its runtime, and anything else that reaches the system itself. These are +#! the functions of `kernel32.dll`, the structs they take, as C lays them out, +#! and the numbers they are asked for and give. The functions Windows keeps for +#! waiting on a word are in `waits.sakura`, a library of their own. + + +extern import "kernel32.dll" when os == windows; + +extern module system::windows when os == windows; + +pub def GetLastError(): u32; +pub def SetLastError(code: u32): void; +pub def GetStdHandle(which: u32): u64; +pub def SetStdHandle(which: u32, handle: u64): i32; +pub def CloseHandle(handle: u64): i32; +pub def DuplicateHandle( + from_process: u64, handle: u64, to_process: u64, made: &mut u64, access: u32, inherit: i32, options: u32 +): i32; +pub def CreateFileW( + name: *u16, access: u32, share: u32, security: *mut u8, disposition: u32, flags: u32, model: u64 +): u64; +pub def ReOpenFile(handle: u64, access: u32, share: u32, flags: u32): u64; +pub def ReadFile( + handle: u64, into: *mut u8, length: u32, read: &mut u32, overlapped: *mut u8 +): i32; +pub def WriteFile( + handle: u64, from: *u8, length: u32, written: &mut u32, overlapped: *mut u8 +): i32; +pub def SetFilePointerEx(handle: u64, distance: i64, position: &mut i64, method: u32): i32; +pub def GetFileType(handle: u64): u32; +pub def GetFileInformationByHandle(handle: u64, info: &mut file_information): i32; +pub def GetFileInformationByHandleEx(handle: u64, class: u32, info: *mut u8, size: u32): i32; +pub def SetFileInformationByHandle(handle: u64, class: u32, info: *mut u8, size: u32): i32; +pub def GetFinalPathNameByHandleW(handle: u64, into: *mut u16, length: u32, flags: u32): u32; +pub def GetFileAttributesW(name: *u16): u32; +pub def SetFileAttributesW(name: *u16, attributes: u32): i32; +pub def CreateDirectoryW(name: *u16, security: *mut u8): i32; +pub def RemoveDirectoryW(name: *u16): i32; +pub def DeleteFileW(name: *u16): i32; +pub def MoveFileExW(from: *u16, to: *u16, flags: u32): i32; +pub def GetCurrentDirectoryW(length: u32, into: *mut u16): u32; +pub def SetCurrentDirectoryW(name: *u16): i32; +pub def GetFullPathNameW(name: *u16, length: u32, into: *mut u16, part: *mut u8): u32; +pub def FindFirstFileExW( + name: *u16, level: u32, data: *mut u8, search: u32, filter: *mut u8, flags: u32 +): u64; +pub def FindNextFileW(find: u64, data: *mut u8): i32; +pub def FindClose(find: u64): i32; +pub def GetConsoleMode(handle: u64, mode: &mut u32): i32; +pub def GetConsoleWindow(): u64; +pub def WriteConsoleW( + handle: u64, from: *u16, length: u32, written: &mut u32, reserved: *mut u8 +): i32; +pub def ReadConsoleW( + handle: u64, into: *mut u16, length: u32, read: &mut u32, control: *mut u8 +): i32; +pub def CreatePipe(reading: &mut u64, writing: &mut u64, security: *mut u8, size: u32): i32; +pub def PeekNamedPipe( + handle: u64, into: *mut u8, length: u32, read: *mut u32, available: &mut u32, left: *mut u32 +): i32; +pub def GetCurrentProcess(): u64; +pub def GetCurrentProcessId(): u32; +pub def GetCurrentThreadId(): u32; +pub def GetModuleFileNameW(library: u64, into: *mut u16, length: u32): u32; +pub def GetCommandLineW(): *u16; +pub def GetSystemDirectoryW(into: *mut u16, length: u32): u32; +pub def CreateProcessW( + application: *u16, command: *mut u16, process_security: *mut u8, thread_security: *mut u8, inherit: i32, + flags: u32, environment: *mut u16, directory: *u16, startup: &mut startup_information, + information: &mut process_information +): i32; +pub def InitializeProcThreadAttributeList( + list: *mut u8, count: u32, flags: u32, size: &mut u64 +): i32; +pub def UpdateProcThreadAttribute( + list: *mut u8, flags: u32, attribute: u64, value: *mut u8, size: u64, previous: *mut u8, returned: *mut u64 +): i32; +pub def DeleteProcThreadAttributeList(list: *mut u8): void; +pub def OpenProcess(access: u32, inherit: i32, process: u32): u64; +pub def TerminateProcess(process: u64, code: u32): i32; +pub def GetExitCodeProcess(process: u64, code: &mut u32): i32; +pub def WaitForSingleObject(handle: u64, milliseconds: u32): u32; +pub def WaitForMultipleObjects(count: u32, handles: *u64, all: i32, milliseconds: u32): u32; +pub def CreateWaitableTimerExW(security: *mut u8, name: *u16, flags: u32, access: u32): u64; +pub def SetWaitableTimer( + timer: u64, due: &i64, period: i32, routine: *mut u8, argument: *mut u8, wake: i32 +): i32; +pub def Sleep(milliseconds: u32): void; +pub def SwitchToThread(): i32; +pub def GetActiveProcessorCount(group: u16): u32; +pub def GetProcessAffinityMask(process: u64, mask: &mut u64, system: &mut u64): i32; +pub def GetEnvironmentStringsW(): *mut u16; +pub def FreeEnvironmentStringsW(block: *mut u16): i32; +pub def GetSystemTimePreciseAsFileTime(time: &mut filetime): void; +pub def QueryPerformanceCounter(count: &mut i64): i32; +pub def QueryPerformanceFrequency(frequency: &mut i64): i32; +pub def GetDynamicTimeZoneInformation(into: &mut zone_information): u32; +pub def VirtualAlloc(address: u64, size: u64, kind: u32, protection: u32): u64; +pub def VirtualFree(address: u64, size: u64, kind: u32): i32; +pub def MultiByteToWideChar(page: u32, flags: u32, bytes: *u8, count: i32, + units: *mut u16, room: i32): i32; +pub def WideCharToMultiByte( + page: u32, flags: u32, wide: *u16, count: i32, into: *mut u8, size: i32, fallback: *u8, used: *mut i32 +): i32; +pub def ExitProcess(code: u32): void; +pub def SetErrorMode(mode: u32): u32; +pub def OpenThread(access: u32, inherit: i32, id: u32): u64; +pub def SuspendThread(thread: u64): u32; +pub def ResumeThread(thread: u64): u32; +pub def GetThreadContext(thread: u64, context: *mut u64): i32; +pub def VirtualProtect(at: u64, size: u64, protect: u32, was: &mut u32): i32; +pub def FlushInstructionCache(process: u64, at: u64, size: u64): i32; +pub def LoadLibraryW(name: *u16): u64; +pub def FreeLibrary(handle: u64): i32; +pub def GetProcAddress(handle: u64, name: *u8): u64; +pub def GetModuleHandleW(name: *u16): u64; +pub def K32EnumProcessModules(process: u64, into: *mut u64, size: u32, needed: &mut u32): i32; +pub def CreateJobObjectW(security: *mut u8, name: *u16): u64; +pub def SetInformationJobObject(job: u64, kind: u32, information: *mut u8, length: u32): i32; +pub def AssignProcessToJobObject(job: u64, process: u64): i32; + +# What the system's functions are asked for, and what they give. +pub val invalid_handle: u64 = 0xFFFFFFFFFFFFFFFF; +pub val invalid_attributes: u32 = 0xFFFFFFFF; +pub val infinite: u32 = 0xFFFFFFFF; +pub val wait_failed: u32 = 0xFFFFFFFF; +pub val generic_read: u32 = 0x80000000; +pub val generic_write: u32 = 0x40000000; +pub val append_data: u32 = 0x4; +pub val read_attributes: u32 = 0x80; +pub val write_attributes: u32 = 0x100; +pub val synchronize: u32 = 0x100000; +pub val share_all: u32 = 7; # Others may read, write, rename, and remove it. +pub val create_new: u32 = 1; +pub val create_always: u32 = 2; +pub val open_existing: u32 = 3; +pub val open_always: u32 = 4; +pub val truncate_existing: u32 = 5; +pub val backup_semantics: u32 = 0x02000000; # Lets a directory be opened. +pub val open_reparse_point: u32 = 0x00200000; # Opens a link rather than what it leads to. +pub val readonly: u32 = 0x1; +pub val directory: u32 = 0x10; +pub val device: u32 = 0x40; +pub val normal: u32 = 0x80; +pub val reparse_point: u32 = 0x400; +pub val symlink_tag: u32 = 0xA000000C; +pub val junction_tag: u32 = 0xA0000003; +pub val disk_type: u32 = 1; +pub val use_std_handles: u32 = 0x100; +pub val unicode_block: u32 = 0x400; +pub val extended_startup: u32 = 0x80000; +pub val create_no_window: u32 = 0x08000000; # A console program started gets a console no one sees. +pub val handle_list: u64 = 0x20002; +pub val same_access: u32 = 2; +pub val process_terminate: u32 = 1; +pub val control_c_exit: u32 = 0xC000013A; # What a program the console's Ctrl-C stopped exits with. + +# The codes of failures the operations look for themselves. +pub val error_file_not_found: u32 = 2; +pub val error_path_not_found: u32 = 3; +pub val error_access_denied: u32 = 5; +pub val error_invalid_function: u32 = 1; +pub val error_sharing_violation: u32 = 32; +pub val error_handle_eof: u32 = 38; +pub val error_invalid_parameter: u32 = 87; +pub val error_broken_pipe: u32 = 109; +pub val error_no_more_files: u32 = 18; +pub val error_bad_exe_format: u32 = 193; +pub val error_operation_aborted: u32 = 995; +pub val error_timeout: u32 = 1460; +pub val error_cant_access_file: u32 = 1920; + +# A time of the system, in tenths of microseconds since 1601 began, as two +# halves. +pub struct filetime { + pub var low: u32; + pub var high: u32; +} + +# What `GetFileInformationByHandle` describes a file with. +pub struct file_information { + pub var attributes: u32; + pub var created: filetime; + pub var accessed: filetime; + pub var written: filetime; + pub var volume: u32; + pub var size_high: u32; + pub var size_low: u32; + pub var links: u32; + pub var index_high: u32; + pub var index_low: u32; +} + +# What `SetFileInformationByHandle` sets a file's attributes with, leaving each +# time that is zero as it is. +pub struct basic_information { + pub var created: i64; + pub var accessed: i64; + pub var written: i64; + pub var changed: i64; + pub var attributes: u32; +} + +# What a program is started with: its window, which a program of the console +# has none of, its standard streams, and a list of what more it is given. +pub struct startup_information { + pub var size: u32; + pub var reserved: *mut u16; + pub var desktop: *mut u16; + pub var title: *mut u16; + pub var x: u32; + pub var y: u32; + pub var width: u32; + pub var height: u32; + pub var columns: u32; + pub var rows: u32; + pub var fill: u32; + pub var flags: u32; + pub var show: u16; + pub var extra_size: u16; + pub var extra: *mut u8; + pub var standard_input: u64; + pub var standard_output: u64; + pub var standard_error: u64; + pub var attributes: *mut u8; +} + +# What `CreateProcessW` gives of a program it started. +pub struct process_information { + pub var process: u64; + pub var thread: u64; + pub var process_id: u32; + pub var thread_id: u32; +} + +# A date and time of the system, as a zone's changes are given. +pub struct system_time { + pub var year: u16; + pub var month: u16; + pub var day_of_week: u16; + pub var day: u16; # Of a change, which of the month's weeks, 5 being its last. + pub var hour: u16; + pub var minute: u16; + pub var second: u16; + pub var millisecond: u16; +} + +# The zone the system is set to, as `GetDynamicTimeZoneInformation` gives it: +# minutes behind UTC, and what it calls its usual and its summer time, how far +# each is from that, and when each begins. +pub struct zone_information { + pub var bias: i32; + pub var standard_name: u16[32]; + pub var standard_date: system_time; + pub var standard_bias: i32; + pub var daylight_name: u16[32]; + pub var daylight_date: system_time; + pub var daylight_bias: i32; + pub var key_name: u16[128]; + pub var no_daylight: u8; +} + +pub const startup_bytes: u64 = 112; +pub const basic_bytes: u64 = 40; diff --git a/tests/main.sakura b/tests/main.sakura new file mode 100644 index 0000000..0f9618e --- /dev/null +++ b/tests/main.sakura @@ -0,0 +1,120 @@ +# Runs the tests of `system`, from the root of the repository, with the +# standard library's repository beside this one. `blossom test` runs them as +# `system.tests`, or: +# +# sakurac run --lib system=system --lib std=../std tests/*.sakura +# +# Add `-- --only TEXT` to run those whose name holds the text. Each test runs +# in a copy of the program, so what one does with a signal is its own. +import std::io; +import std::process; +import system; +import std::testing; + +def main(args: span): void { + exit(tester::run(args)); +} + +# Whether running the function stops the program. It runs in a copy of the +# program that writes nothing, so that this one goes on and the report of the +# stop is not mixed into the tests'. +def stops(run: def(): void): bool { + when os == windows { + val stopped := copied(run); + return !(stopped.exited && stopped.code == 0); + } + val child := fork(); + if child == 0 { + val out: fd = fd::stdout; + val err: fd = fd::stderr; + out.close(); + err.close(); + run(); + exit(0); + } + var status: process_status; + return wait(child, &mut status) >= 0 && !(status.exited && status.code == 0); +} + +# Windows cannot copy a program as it runs, as `system::fork` does, so what the +# tests run in a copy of their own runs there in a copy started again, as +# `std::testing` starts the copy each test runs in. +when os == windows { + # The variable a copy is given, listing how the copies before it stopped. + val copy_variable: strview = "SAKURA_TEST_COPY"; + + # How many functions `copied` has been asked to run, in this program or a + # copy, and how the copies running each stopped, as `exited,code,signal;` + # each. + var copies_asked: u64 = 0; + var copies_seen: string = string::new(nothing {}); + + # Runs a function in a copy of the program, giving how the copy stopped. The + # copy runs the test that asked again, writing nothing, and is told how each + # copy before it stopped, which it gives where it is asked for them, so it + # goes the way the test went here, though a check that fails asks again. It + # runs the function asked for after them, then exits with zero. + def copied(run: def(): void): system::process_status { + copies_asked++; + if process::variable(copy_variable) is some(given) { + if replayed(given, copies_asked) is some(status) { + return status; + } + run(); + system::exit(0); + } + val status := copy_quietly(); + copies_seen.append( + $"{status.exited ? 1 : 0},{status.code},{status.signal};".span + ); + return status; + } + + # Starts a copy of the program writing nothing, told how the copies before it + # stopped, and gives how it stopped. + def copy_quietly(): system::process_status { + var device := path::parse(system::null_device) else (_) { + return system::process_status {}; + }; + var quiet := io::file::open(&device, open_flags::write) else (_) { + return system::process_status {}; + }; + val copy := system::respawn( + $"{copy_variable}={copies_seen.span}".span, + system::fd::stdin, + quiet.handle, + quiet.handle + ); + var status := system::process_status { exited = true, code = -1 }; + if copy > 0 { + _ = system::wait(copy, &mut status); + } + return status; + } + + # How the copy running the function asked for at a count stopped, as a + # copy's variable lists it, or nothing for the one after those it lists. + def replayed(given: strview, count: u64): maybe { + var seen := 0u; + for entry in given.split(';') { + continue if entry.length == 0; + seen++; + continue if seen != count; + val parts := entry.split(',').to_vector(); + return system::process_status { + exited = parts[0] == "1", + code = number_in(parts[1]) as i32, + signal = number_in(parts[2]) as i32 + }; + } + return nothing {}; + } + + # The integer text says, or zero where it says none. + def number_in(text: strview): i64 { + if integer::parse::(text) is value(number) { + return number; + } + return 0; + } +} diff --git a/tests/signals.sakura b/tests/signals.sakura new file mode 100644 index 0000000..1a2eb3b --- /dev/null +++ b/tests/signals.sakura @@ -0,0 +1,541 @@ +# Tests of signals: sending them, ignoring them, putting back what the system does +# with them, handling them, at the program's safe points and where a wait is +# interrupted, and watching for them. Each test runs in a copy of the program, so what one handles is its +# own. Windows sends a program no signal from another, so there a thread, or a +# copy of the program, sends what another program does on Linux. +import std::io; +import std::process; +import system; +import std::testing; +import std::thread; + +# A function of the program's own, which begins with a safe point. +def safe_point(): void {} + +when os == linux { + # Runs a copy of the program that puts back what the system does with a signal, + # then sends it to itself, giving the signal that stopped the copy, or zero where + # the copy went on and exited. + def raised_in_copy(sent: system::signal): i32 { + val copy := system::fork(); + if copy == 0 { + _ = system::restore(sent); + _ = system::raise(sent); + safe_point(); + system::exit(0); + } + + var status: system::process_status; + _ = system::wait(copy, &mut status); + return status.exited ? 0 : status.signal; + } + + # The signals the system says the program does something with, one bit each by + # number less one: those it handles, where `named` is `SigCgt`, or ignores, where + # it is `SigIgn`. + def dispositions(named: strview): u64 { + var at := path::parse("/proc/self/status") else (_) { return 0; }; + val text := io::read_file(&at) else (_) { return 0; }; + for line in text.span.split('\n') { + if !line.starts_with(named) || line.length < 16 { + continue; + } + + val hex := line.substr(line.length - 16, 16); + var bits: u64 = 0; + for i in 0..hex.length { + val digit := hex[i] >= 'a' ? (hex[i] - 'a') as u64 + 10 : (hex[i] - '0') as u64; + bits = bits * 16 + digit; + } + return bits; + } + return 0; + } + + # Waits until a process is in a state, as `/proc` gives it: `S` where it sleeps, + # as it does waiting in the system, so a signal sent to it then interrupts the + # wait, and `T` where it is paused. Gives whether it was. + def reaches(process: i64, state: u8): bool { + var at := path::parse($"/proc/{process}/stat") else (_) { return false; }; + for tries in 0..1000000 { + val text := io::read_file(&at) else (_) { return false; }; + val view := text.span; + var end := view.length; + while end > 0 && view[end - 1] != ')' { + end--; + } + if end + 1 < view.length && view[end + 1] == state { + return true; + } + } + return false; + } + + # Starts a copy of the program that sends it a signal once it sleeps, then waits + # to be stopped, giving the copy's number. + def signalled_once_asleep(sent: system::signal): i64 { + val program := system::getpid(); + val copy := system::fork(); + if copy == 0 { + _ = system::restore(sent); + if reaches(program, 'S') { + _ = system::kill(program, sent); + } + system::pause(); + system::exit(0); + } + return copy; + } +} + +# Whether a read failed because a signal ended its wait. +def is_interrupted(error: maybe): bool { + if error is some(why) { + return why == io_error::interrupted; + } + return false; +} + +# A stream that gives its text in two parts, failing between them as a read does +# that a signal the program handles interrupts. +struct halting : readable { + var first: strview; + var rest: strview; + var halted: bool; +} + +def halting::read(&mut this, into: slice): result { + if this.first.length > 0 { + return this.first.read(into); + } + if !this.halted { + this.halted = true; + return io_error::interrupted; + } + return this.rest.read(into); +} + +when os == linux { + @test def signals_have_the_numbers_of_the_system(t: &mut tester): void { + # Those a program may handle are noted by the system under their numbers, and + # each handler is given the signal that came. Each is restored after, so that + # `child` interrupts no wait below. + val members: system::signal[12] = [ + system::signal::hangup, system::signal::interrupt, system::signal::quit, system::signal::user1, + system::signal::user2, system::signal::pipe, system::signal::alarm, system::signal::terminate, + system::signal::child, system::signal::resume, system::signal::suspend, system::signal::resized + ]; + val numbers: u64[12] = [1, 2, 3, 10, 12, 13, 14, 15, 17, 18, 20, 28]; + var came := system::signal::kill; + for i in 0..members.length { + t.expects(system::handle(members[i], def(s: system::signal) { came = s; }) == 0); + t.expects(((dispositions("SigCgt") >> (numbers[i] - 1)) & 1) == 1); + t.expects(system::raise(members[i]) == 0); + safe_point(); + t.expects(came == members[i]); + t.expects(system::restore(members[i]) == 0); + t.expects(((dispositions("SigCgt") >> (numbers[i] - 1)) & 1) == 0); + } + + # What stops a program by default stops a copy with its number. + t.expects(raised_in_copy(system::signal::hangup) == 1); + t.expects(raised_in_copy(system::signal::interrupt) == 2); + t.expects(raised_in_copy(system::signal::kill) == 9); + t.expects(raised_in_copy(system::signal::user1) == 10); + t.expects(raised_in_copy(system::signal::user2) == 12); + t.expects(raised_in_copy(system::signal::pipe) == 13); + t.expects(raised_in_copy(system::signal::alarm) == 14); + t.expects(raised_in_copy(system::signal::terminate) == 15); + + # `stop` pauses a copy, and `resume` lets it go on. + val copy := system::fork(); + if copy == 0 { + _ = system::raise(system::signal::stop); + system::exit(5); + } + t.expects(reaches(copy, 'T')); + _ = system::kill(copy, system::signal::resume); + var status: system::process_status; + _ = system::wait(copy, &mut status); + t.expects(status.exited && status.code == 5); + } + + @test def ignored_signals_do_nothing_until_restored(t: &mut tester): void { + t.expects(system::ignore(system::signal::user1) == 0); + t.expects(((dispositions("SigIgn") >> 9) & 1) == 1); + t.expects(system::raise(system::signal::user1) == 0); + safe_point(); + + t.expects(system::restore(system::signal::user1) == 0); + t.expects(((dispositions("SigIgn") >> 9) & 1) == 0); + t.expects(raised_in_copy(system::signal::user1) == 10); + + # Restoring a handled signal stops its handler running. + var count := 0; + t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0); + t.expects(system::ignore(system::signal::user2) == 0); + t.expects(system::raise(system::signal::user2) == 0); + safe_point(); + t.expects(count == 0 && ((dispositions("SigCgt") >> 11) & 1) == 0); + } +} + +@test def kill_and_stop_cannot_be_handled_nor_child_ignored(t: &mut tester): void { + val nothing_done := def(s: system::signal) {}; + t.expects(system::error_of(system::handle(system::signal::kill, nothing_done)) == io_error::invalid); + t.expects(system::error_of(system::handle(system::signal::stop, nothing_done)) == io_error::invalid); + t.expects(system::error_of(system::ignore(system::signal::kill)) == io_error::invalid); + t.expects(system::error_of(system::ignore(system::signal::stop)) == io_error::invalid); + t.expects(system::error_of(system::ignore(system::signal::child)) == io_error::invalid); +} + +when os == linux { + @test def signals_watched_for_wait_to_be_asked_for(t: &mut tester): void { + t.expects(system::watch(system::signal::user1) == 0); + t.expects(((dispositions("SigCgt") >> 9) & 1) == 1); + t.expects(system::watched() == 0); + _ = system::raise(system::signal::user1); + safe_point(); + t.expects(system::watched() == 1u << 10); + t.expects(system::watched() == 0); + + # A handled signal is not given, and one watched for waits while the handlers + # run. + var count := 0; + t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0); + _ = system::raise(system::signal::user1); + _ = system::raise(system::signal::user2); + safe_point(); + t.expects(count == 1); + t.expects(system::watched() == 1u << 10); + + # Handling a signal watched for stops it being watched for. + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + _ = system::raise(system::signal::user1); + safe_point(); + t.expects(count == 2 && system::watched() == 0); + t.expects(system::error_of(system::watch(system::signal::kill)) == io_error::invalid); + t.expects(system::error_of(system::watch(system::signal::stop)) == io_error::invalid); + } +} + +@test def handlers_run_at_the_next_safe_point(t: &mut tester): void { + var count := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + _ = system::raise(system::signal::user1); + t.expects(count == 0); + safe_point(); + t.expects(count == 1); + + # Signals that come together are handled once each. + _ = system::raise(system::signal::user1); + _ = system::raise(system::signal::user1); + safe_point(); + t.expects(count == 2); + + # A loop of the program's own runs the handler as it goes round. + var stopping := false; + t.expects(system::handle(system::signal::user2, def(s: system::signal) { stopping = true; }) == 0); + _ = system::raise(system::signal::user2); + var passes := 0; + while !stopping { + passes++; + } + t.expects(passes == 1); +} + +when os == linux { + @test def a_loop_calling_nothing_is_ended_by_its_safe_points(t: &mut tester): void { + var flag := false; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { flag = true; }) == 0); + val program := system::getpid(); + val copy := system::fork(); + if copy == 0 { + _ = system::kill(program, system::signal::user1); + system::exit(0); + } + + while !flag {} + var status: system::process_status; + _ = system::wait(copy, &mut status); + t.expects(flag && status.exited); + } +} + +@test def vectors_held_across_a_safe_point_keep_their_lanes(t: &mut tester): void { + # The handler works vectors of its own, in the registers the loop holds its + # sums in, which the safe point keeps whole for it: 16 bytes, and 32 where the + # loop's code has AVX. + var ran := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { + var noise := f32x8::splat(-1.0); + var bytes := u32x4::splat(7); + for _ in 0..4 { + noise = noise * noise + f32x8::splat(3.0); + bytes = bytes * bytes; + } + if noise.sum() > 0.0 && bytes.sum() != 0 { + ran++; + } + }) == 0); + # Raised before the loop, which calls nothing, so the handler runs at its + # first pass's safe point, the sums in registers. + _ = system::raise(system::signal::user1); + var narrow := u32x4::splat(0); + var wide := f32x8::splat(0.0); + for i in 0..100u { + narrow = narrow + u32x4::splat(i as u32); + wide = wide + f32x8::splat(1.0); + } + t.expects(ran == 1 && narrow.sum() == 4 * 4950 && wide.sum() == 800.0); +} + +@test def handlers_do_not_nest(t: &mut tester): void { + var depth := 0; + var deepest := 0; + var runs := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { + depth++; + runs++; + deepest = depth > deepest ? depth : deepest; + if runs == 1 { + _ = system::raise(system::signal::user1); + safe_point(); + } + depth--; + }) == 0); + + _ = system::raise(system::signal::user1); + safe_point(); + t.expects(runs == 2 && deepest == 1); +} + +when os == linux { + @test def a_wait_a_handler_interrupts_fails_with_interrupted(t: &mut tester): void { + var count := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + val copy := signalled_once_asleep(system::signal::user1); + + # The handler has run by the time the wait ends. + var status: system::process_status; + val waited := system::wait(copy, &mut status); + t.expects(system::error_of(waited) == io_error::interrupted && count == 1); + + _ = system::kill(copy, system::signal::kill); + t.expects(system::wait(copy, &mut status) == copy && !status.exited && status.signal == 9); + } + + @test def pause_returns_once_a_handler_has_run(t: &mut tester): void { + var count := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + + # A signal sent just before is not missed. + _ = system::raise(system::signal::user1); + system::pause(); + t.expects(count == 1); + + # One sent while it waits ends the wait. + val copy := signalled_once_asleep(system::signal::user1); + system::pause(); + t.expects(count == 2); + + var status: system::process_status; + _ = system::kill(copy, system::signal::kill); + _ = system::wait(copy, &mut status); + } + + @test def exit_in_a_handler_stops_the_program(t: &mut tester): void { + val copy := system::fork(); + if copy == 0 { + _ = system::handle(system::signal::user1, def(s: system::signal) { system::exit(7); }); + _ = system::raise(system::signal::user1); + safe_point(); + system::exit(0); + } + + var status: system::process_status; + _ = system::wait(copy, &mut status); + t.expects(status.exited && status.code == 7); + } +} + +@test def a_reader_keeps_what_a_signal_cut_short(t: &mut tester): void { + # A line cut short is given whole by the next read. + var lines := io::reader_of(halting { first = "hel", rest = "lo\nworld" }); + t.expects(lines.read_line() is none && is_interrupted(lines.error)); + val line := lines.read_line() else { t.expects(false); return; }; + t.expects(line.span == "hello" && lines.error is none); + val last := lines.read_line() else { t.expects(false); return; }; + t.expects(last.span == "world"); + + # So are bytes asked for, and the rest of the input. + var bytes := io::reader_of(halting { first = "0123", rest = "456789" }); + t.expects(bytes.read_exactly(6) is error); + val six := bytes.read_exactly(6) else (_) { t.expects(false); return; }; + t.expects(six.span == "012345"); + + var rest := io::reader_of(halting { first = "ab", rest = "cd" }); + t.expects(rest.read_all() is error); + val all := rest.read_all() else (_) { t.expects(false); return; }; + t.expects(all.span == "abcd"); +} + +when os == windows { + # Runs a copy of the program that puts back what the system does with a signal, + # then sends it to itself, giving the signal that stopped the copy, or zero where + # the copy went on and exited. Windows stops a program by a signal's default with + # 128 more than its number, or by `interrupt` as the console's Ctrl-C does, which + # is the signal itself. + def raised_in_copy(sent: system::signal): i32 { + val status := copied(def() { + _ = system::restore(sent); + _ = system::raise(sent); + safe_point(); + }); + if !status.exited { + return status.signal; + } + return status.code > 128 && status.code < 192 ? status.code - 128 : 0; + } + + # Starts a thread that sends the program a signal once a little time has passed. + # The thread is given the signal, which it owns, since it outlives this call. + def sent_soon(sent: system::signal): result, io_error> { + return thread::spawn_with(def(which: system::signal) { + _ = system::sleep(50000000); + _ = system::raise(which); + }, sent); + } + + @test def signals_have_the_numbers_of_the_system(t: &mut tester): void { + # Those a program may handle are noted under their numbers, and each handler + # is given the signal that came. + val members: system::signal[12] = [ + system::signal::hangup, system::signal::interrupt, system::signal::quit, system::signal::user1, + system::signal::user2, system::signal::pipe, system::signal::alarm, system::signal::terminate, + system::signal::child, system::signal::resume, system::signal::suspend, system::signal::resized + ]; + val numbers: u64[12] = [1, 2, 3, 10, 12, 13, 14, 15, 17, 18, 20, 28]; + var came := system::signal::kill; + for i in 0..members.length { + t.expects(system::handle(members[i], def(s: system::signal) { came = s; }) == 0); + t.expects(system::raise(members[i]) == 0); + safe_point(); + t.expects(came == members[i]); + t.expects(system::watch(members[i]) == 0 && system::raise(members[i]) == 0); + t.expects(system::watched() == 1u << numbers[i]); + t.expects(system::restore(members[i]) == 0); + } + + # What stops a program by default stops a copy with its number. + t.expects(raised_in_copy(system::signal::hangup) == 1); + t.expects(raised_in_copy(system::signal::interrupt) == 2); + t.expects(raised_in_copy(system::signal::kill) == 9); + t.expects(raised_in_copy(system::signal::user1) == 10); + t.expects(raised_in_copy(system::signal::user2) == 12); + t.expects(raised_in_copy(system::signal::pipe) == 13); + t.expects(raised_in_copy(system::signal::alarm) == 14); + t.expects(raised_in_copy(system::signal::terminate) == 15); + + # Windows cannot pause a program. + t.expects(system::error_of(system::raise(system::signal::stop)) == io_error::unsupported); + } + + @test def ignored_signals_do_nothing_until_restored(t: &mut tester): void { + t.expects(system::ignore(system::signal::user1) == 0); + t.expects(system::raise(system::signal::user1) == 0); + safe_point(); + + t.expects(system::restore(system::signal::user1) == 0); + t.expects(raised_in_copy(system::signal::user1) == 10); + + # Restoring a handled signal stops its handler running. + var count := 0; + t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0); + t.expects(system::ignore(system::signal::user2) == 0); + t.expects(system::raise(system::signal::user2) == 0); + safe_point(); + t.expects(count == 0); + } + + @test def signals_watched_for_wait_to_be_asked_for(t: &mut tester): void { + t.expects(system::watch(system::signal::user1) == 0); + t.expects(system::watched() == 0); + _ = system::raise(system::signal::user1); + safe_point(); + t.expects(system::watched() == 1u << 10); + t.expects(system::watched() == 0); + + # A handled signal is not given, and one watched for waits while the handlers + # run. + var count := 0; + t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0); + _ = system::raise(system::signal::user1); + _ = system::raise(system::signal::user2); + safe_point(); + t.expects(count == 1); + t.expects(system::watched() == 1u << 10); + + # Handling a signal watched for stops it being watched for. + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + _ = system::raise(system::signal::user1); + safe_point(); + t.expects(count == 2 && system::watched() == 0); + t.expects(system::error_of(system::watch(system::signal::kill)) == io_error::invalid); + t.expects(system::error_of(system::watch(system::signal::stop)) == io_error::invalid); + } + + @test def a_loop_calling_nothing_is_ended_by_its_safe_points(t: &mut tester): void { + var flag := false; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { flag = true; }) == 0); + var sender := sent_soon(system::signal::user1) else (_) { t.expects(false); return; }; + while !flag {} + sender.close(); + t.expects(flag); + } + + @test def a_wait_a_handler_interrupts_fails_with_interrupted(t: &mut tester): void { + var count := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + var pinger := process::command::new("ping"); + pinger.arguments(["-n", "30", "127.0.0.1"]); + pinger.output(process::stdio::none); + var running := pinger.spawn() else (_) { t.expects(false); return; }; + var sender := sent_soon(system::signal::user1) else (_) { t.expects(false); return; }; + + # The handler has run by the time the wait ends. + var status: system::process_status; + val waited := system::wait(running.id as i64, &mut status); + t.expects(system::error_of(waited) == io_error::interrupted && count == 1); + sender.close(); + + t.expects(running.kill() is value); + val stopped := running.wait() else (_) { t.expects(false); return; }; + t.expects(stopped == process::status { signaled = 9 }); + } + + @test def pause_returns_once_a_handler_has_run(t: &mut tester): void { + var count := 0; + t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0); + + # A signal sent just before is not missed. + _ = system::raise(system::signal::user1); + system::pause(); + t.expects(count == 1); + + # One sent while it waits ends the wait. + var sender := sent_soon(system::signal::user1) else (_) { t.expects(false); return; }; + system::pause(); + t.expects(count == 2); + sender.close(); + } + + @test def exit_in_a_handler_stops_the_program(t: &mut tester): void { + val status := copied(def() { + _ = system::handle(system::signal::user1, def(s: system::signal) { system::exit(7); }); + _ = system::raise(system::signal::user1); + safe_point(); + }); + t.expects(status.exited && status.code == 7); + } +}