Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-12-06 13:37:43 -06:00
commit 7614e64138
20 files changed
+5193

No files matched your search

+9
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
.blossom
+15
View File
@@ -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.
+18
View File
@@ -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.
+64
View File
@@ -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.
+35
View File
@@ -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 <sorakatadzuma@gmail.com>
url: https://git.malunal.studio/sakura/system
+20
View File
@@ -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,
}
+99
View File
@@ -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.
}
+39
View File
@@ -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.
}
+26
View File
@@ -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;
+71
View File
@@ -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;
File diff suppressed because it is too large. Load diff
+52
View File
@@ -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<signal> {
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{},
};
}
File diff suppressed because it is too large. Load diff
+58
View File
@@ -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<signal> {
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{},
};
}
+262
View File
@@ -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<strview>;
#! The variables it is given, each as `NAME=value`.
pub var environment: span<strview>;
#! 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<def(signal): void>;
# 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;
}
+18
View File
@@ -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;
+270
View File
@@ -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;
+120
View File
@@ -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<strview>): 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<system::process_status> {
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::<i64>(text) is value(number) {
return number;
}
return 0;
}
}
+541
View File
@@ -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<io_error>): 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<u8>): result<u64, io_error> {
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<thread::handle<void>, 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);
}
}