Files
sakurac/system/on_linux.sakura
T
2026-11-19 04:54:17 -06:00

1017 lines
35 KiB
Plaintext

#! @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<F>(which: signal, by: F): i32 where F: invokable<def(signal): void> {
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<fd>, ready: slice<bool>, 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<strview>;
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<strview> {
if viewed {
return variables;
}
val each := environ();
var count := 0u;
while each != null && each[count] != null {
count++;
}
val views := raw_allocate(count * size_of::<strview>()) 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::<strview>::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;
}