Files
sakurac/server/system.sakura
T

715 lines
26 KiB
Plaintext
Raw Normal View History

2026-10-26 10:14:11 -05:00
#! @file system.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what the server asks of the system beyond what `system` gives:
#! making a process the leader of a group of its own, sending what it writes
#! nowhere, and the path of the executable running, which `sakura` also finds
#! the standard library by, with waiting on a handle for a while, the time, and
#! reading and writing whole messages over the pipes between its processes. The
#! calls are those of Linux on x86-64, and on Windows the functions of the
#! system, where the server also starts its processes itself, and spells each
#! path one way, since Windows spells a file many.
import std::io;
import std::process;
import system;
import system::windows;
import sakura::analyzer;
module sakura::server;
when os == linux {
# The numbers of the calls made here, as Linux gives them on x86-64.
val call_dup2: i64 = 33;
val call_readlink: i64 = 89;
val call_setpgid: i64 = 109;
#! Sends what the process writes to its standard output nowhere, so that only
#! the server, which answers the client, ever writes to it.
pub def quiet_output(): void {
val nowhere := system::open(system::null_device, open_flags::write);
return if nowhere < 0;
system::linux::syscall(call_dup2, nowhere as u64, 1, 0, 0, 0, 0);
nowhere.close();
}
#! Makes the process the leader of a group of its own, which the processes it
#! starts belong to, so they are all stopped at once.
pub def lead_group(): void {
system::linux::syscall(call_setpgid, 0, 0, 0, 0, 0, 0);
}
#! The path of the executable running.
#! @returns The path, or empty text where the system does not say.
pub def executable_path(): string {
val link: strview = "/proc/self/exe";
var name: u8[16];
for i in 0..link.length {
name[i] = link[i];
}
name[link.length] = 0;
var text: u8[4096];
val from := (&mut name) as *mut u8;
val into := (&mut text) as *mut u8;
val length := system::linux::syscall(call_readlink, from as u64, into as u64, 4095, 0, 0, 0);
return string::new(nothing {}) if length <= 0;
return string::from(span::<u8>::over(into as *u8, length as u64), nothing {});
}
}
when os == windows {
# What `GetStdHandle` and `SetStdHandle` take for the standard output.
val standard_output: u32 = 0xFFFFFFF5;
# What they take for the standard error.
val standard_error: u32 = 0xFFFFFFF4;
# What the other functions of the system are given, and give.
val invalid_handle: u64 = 0xFFFFFFFFFFFFFFFF;
val infinite: u32 = 0xFFFFFFFF;
val utf8_page: u32 = 65001;
val same_access: u32 = 2;
val use_std_handles: u32 = 0x100;
val handle_list: u64 = 0x20002;
val suspended: u32 = 0x4;
val extended_startup: u32 = 0x80000;
val no_window: u32 = 0x08000000;
val extended_limits: u32 = 9; # The limits of a job object, JOBOBJECT_EXTENDED_LIMIT_INFORMATION.
val kill_on_close: u64 = 0x2000; # Its processes are stopped once the last handle of it is closed.
val basic_find: u32 = 1; # Finding a file without its short name.
# The most units of UTF-16 a path of the system holds, with the zero it ends
# in.
val wide_limit: u64 = 32768;
# The job object every process the server starts is put in, which stops them
# all once the server ends, however it ends, or 0 before the first starts.
var processes: u64;
# The system's handle a handle of `system` stands for, which gives the
# standard streams as 0, 1, and 2.
def system_handle(handle: system::fd): u64 {
return handle >= 0 && handle <= 2 ? GetStdHandle(0xFFFFFFF6 - handle as u32) : (handle as i64) as u64;
}
#! Sends what the process writes to its standard output nowhere, so that only
#! the server, which answers the client, ever writes to it. The handle of
#! nowhere is the standard output from then on, so it stays open.
pub def quiet_output(): void {
val nowhere := system::open(system::null_device, open_flags::write);
return if nowhere < 0;
SetStdHandle(standard_output, system_handle(nowhere));
}
#! The path of the executable running, in UTF-8.
#! @returns The path, or empty text where the system does not say.
pub def executable_path(): string {
var wide: u16[4096];
var text: u8[16384];
val units := (&mut wide) as *mut u16;
val into := (&mut text) as *mut u8;
val count := GetModuleFileNameW(0, units, 4096);
return string::new(nothing {}) if count == 0 || count >= 4096;
val length := WideCharToMultiByte(utf8_page, 0, units as *u16, count as i32, into, 16384, null, null);
return string::new(nothing {}) if length <= 0;
return string::from(span::<u8>::over(into as *u8, length as u64), nothing {});
}
#! Takes the standard output the process was given, which the server reads
#! its answers from, and sends anything else written there nowhere, as
#! `quiet_output` does.
#! @returns The handle of the output it was given.
pub def take_output(): system::fd {
val given := GetStdHandle(standard_output);
quiet_output();
return (given as i64) as system::fd;
}
#! Starts a process of the server's, which on Windows is this program started
#! again, as `PROGRAM lsp ROLE`, since Windows cannot start a copy of the
#! server. It is given the handles as its standard input and output, and the
#! server's standard error as its own, which reaches the editor's log, and it
#! inherits nothing else, so it never holds the connection to the client open.
#! No console is made for it, as the server has none under an editor, and it
#! is put in a job object before it runs, which stops it once the server
#! ends, however that is.
#! @param role What it is to be, as `--worker`.
#! @param input The handle it reads.
#! @param output The handle it writes.
#! @returns The process, as the system's handle of it, or 0 where it could not
#! be started.
pub def start_process(role: strview, input: system::fd, output: system::fd): i64 {
if processes == 0 {
processes = CreateJobObjectW(null, null);
if processes != 0 {
# JOBOBJECT_EXTENDED_LIMIT_INFORMATION, whose flags are 16 bytes in.
var limits: u64[18];
limits[2] = kill_on_close;
SetInformationJobObject(processes, extended_limits, (&mut limits) as *mut u8, 144);
}
}
# `"PROGRAM" lsp ROLE`, which Windows may write into while it starts it.
var program: u16[32768];
val length := GetModuleFileNameW(0, (&mut program) as *mut u16, wide_limit as u32) as u64;
return 0 if length == 0 || length >= wide_limit;
var command: u16[32800];
var at: u64 = 0;
command[at] = '"' as u16;
at++;
for i in 0..length {
command[at] = program[i];
at++;
}
val rest := $"\" lsp {role}";
for i in 0..rest.length {
command[at] = rest[i] as u16;
at++;
}
command[at] = 0;
# Each handle it is given is a copy made for it to inherit, and it is told to
# inherit only those.
val ours := GetCurrentProcess();
var given: u64[3];
given[0] = system_handle(input);
given[1] = system_handle(output);
given[2] = GetStdHandle(standard_error);
var copies: u64[3];
var count: u64 = 0;
for i in 0u..3u {
var copy: u64 = 0;
if given[i] != 0 && given[i] != invalid_handle && DuplicateHandle(ours, given[i], ours, &mut copy, 0, 1, same_access) != 0 {
copies[count] = copy;
count++;
}
given[i] = copy;
}
var size: u64 = 0;
var list: u64[32];
InitializeProcThreadAttributeList(null, 1, 0, &mut size);
val listed := size <= 256 && InitializeProcThreadAttributeList((&mut list) as *mut u8, 1, 0, &mut size) != 0;
var startup := startup_information { size = 112, flags = use_std_handles };
startup.standard_input = given[0];
startup.standard_output = given[1];
startup.standard_error = given[2];
startup.attributes = (&mut list) as *mut u8;
var made: process_information;
val started := listed && given[0] != 0 && given[1] != 0
&& UpdateProcThreadAttribute((&mut list) as *mut u8, 0, handle_list, (&mut copies) as *mut u8, count * 8, null, null) != 0
&& CreateProcessW(
(&program) as *u16, (&mut command) as *mut u16, null, null, 1, no_window | suspended | extended_startup,
null, null, &mut startup, &mut made
) != 0;
if listed {
DeleteProcThreadAttributeList((&mut list) as *mut u8);
}
for i in 0..count {
CloseHandle(copies[i]);
}
return 0 if !started;
# It starts suspended, so it is in the job object before it can do anything.
if processes != 0 {
AssignProcessToJobObject(processes, made.process);
}
ResumeThread(made.thread);
CloseHandle(made.thread);
return made.process as i64;
}
#! Waits for a process the server started to end, until a moment passes, when
#! it is stopped, and lets go of it.
#! @param process The process, as `start_process` gives it.
#! @param deadline The moment it is stopped, as `now_ms` gives it, or 0 to
#! stop it at once.
#! @param code Where the status it exited with is written, which is the
#! code of the exception where one ended it.
#! @returns Whether it ended before it was stopped.
pub def end_process(process: i64, deadline: i64, code: &mut u32): bool {
val handle := process as u64;
val left := deadline - now_ms();
val ended := WaitForSingleObject(handle, left > 0 ? left as u32 : 0) == 0;
if !ended {
TerminateProcess(handle, 1);
WaitForSingleObject(handle, infinite);
}
code = 1;
GetExitCodeProcess(handle, code);
CloseHandle(handle);
return ended;
}
#! The one spelling of a path that paths are compared by, since Windows spells
#! a file many ways: absolute, without `.` and `..`, with `/` between names,
#! the letter of its drive upper case, and each name that exists spelled as
#! its directory spells it, which turns a short name, as `PROGRA~1`, into the
#! long one, and gives each letter its case on disk. A share is
#! `//server/share/...`, the server's name lower case, as a URI spells it. It
#! ends in `/` only where it is the root of a drive. Links are not followed,
#! so a path stays within the folder the editor named it by.
#! @param given The path.
#! @returns The path, or nothing where the system takes it for none.
pub def canonical_path(given: strview): maybe<string> {
return nothing {} if given.length == 0 || given.length >= wide_limit;
var wide: u16[32768];
var whole: u16[32768];
var spelled: u16[32768];
val named := (&mut wide) as *mut u16;
val full := (&mut whole) as *mut u16;
val out := (&mut spelled) as *mut u16;
val units := MultiByteToWideChar(utf8_page, 0, given.data, given.length as i32, named, 32767);
return nothing {} if units <= 0;
named[units as u64] = 0;
val length := GetFullPathNameW(named as *u16, wide_limit as u32, full, null) as u64;
return nothing {} if length == 0 || length >= wide_limit;
# `\\?\D:\x` and `\\?\UNC\server\share` are taken as `D:\x` and
# `\\server\share`.
var start: u64 = 0;
if begins_with(full as *u16, length, 0, "\\\\?\\UNC\\") {
start = 6;
full[6] = '\\' as u16;
} else if begins_with(full as *u16, length, 0, "\\\\?\\") && is_wide_drive(full as *u16, length, 4) {
start = 4;
}
# The root, `D:\` or `\\server\share\`, is not looked up.
var root := start;
val shared := begins_with(full as *u16, length, start, "\\\\");
if is_wide_drive(full as *u16, length, start) {
root = start + (start + 2 < length && full[start + 2] == '\\' as u16 ? 3 : 2);
} else if shared {
var names := 0;
root = start + 2;
while root < length && names < 2 {
if full[root] == '\\' as u16 {
names++;
}
root++;
}
}
var made: u64 = 0;
for i in start..root {
out[made] = full[i];
made++;
}
# The server's name is lower case, as a URI spells it.
if shared {
var i: u64 = 2;
while i < made && out[i] != '\\' as u16 {
if out[i] >= 'A' as u16 && out[i] <= 'Z' as u16 {
out[i] = out[i] + 32;
}
i++;
}
}
# Past a name that does not exist, the rest is kept as it is given. A name
# with a wildcard would be looked up as a pattern, so it is not looked up.
var found := true;
var entry: u64[74];
var at := root;
while at < length {
var end := at;
while end < length && full[end] != '\\' as u16 {
end++;
}
if end > at {
found = found && !has_wildcard(full as *u16, at, end) && find_entry(full as *u16, end, (&mut entry) as *mut u8);
if made > 0 && out[made - 1] != '\\' as u16 {
out[made] = '\\' as u16;
made++;
}
# The name found is 44 bytes into what `FindFirstFileExW` writes.
val name := ((&entry) as *u8 + 44) as *u16;
var count := end - at;
if found {
count = 0;
while count < 260 && name[count] != 0 {
count++;
}
}
return nothing {} if made + count >= wide_limit;
for i in 0..count {
out[made] = found ? name[i] : full[at + i];
made++;
}
}
at = end + 1;
}
for i in 0..made {
if out[i] == '\\' as u16 {
out[i] = '/' as u16;
}
}
if is_wide_drive(out as *u16, made, 0) && out[0] >= 'a' as u16 {
out[0] = out[0] - 32;
}
while made > 1 && out[made - 1] == '/' as u16 && !(made == 3 && is_wide_drive(out as *u16, made, 0)) {
made--;
}
var bytes: u8[98304];
val written := WideCharToMultiByte(utf8_page, 0, out as *u16, made as i32, (&mut bytes) as *mut u8, 98304, null, null);
return nothing {} if written <= 0;
return string::from(strview::over((&bytes) as *u8, written as u64), nothing {});
}
# Whether the units of UTF-16 from an index on begin with ASCII text.
def begins_with(units: *u16, length: u64, at: u64, text: strview): bool {
return false if at + text.length > length;
for i in 0..text.length {
return false if units[at + i] != text[i] as u16;
}
return true;
}
# Whether the units of UTF-16 from an index on begin with the letter of a
# drive and its colon, as `C:`.
def is_wide_drive(units: *u16, length: u64, at: u64): bool {
return false if at + 2 > length;
val letter := units[at];
val is_letter := (letter >= 'a' as u16 && letter <= 'z' as u16) || (letter >= 'A' as u16 && letter <= 'Z' as u16);
return is_letter && units[at + 1] == ':' as u16;
}
# Whether a name, between two indexes of a path, holds what `FindFirstFileExW`
# takes as a wildcard.
def has_wildcard(units: *u16, from: u64, to: u64): bool {
for i in from..to {
val unit := units[i];
return true if unit == '*' as u16 || unit == '?' as u16 || unit == '<' as u16 || unit == '>' as u16
|| unit == '"' as u16;
}
return false;
}
# Finds the entry the first units of a path name in its directory, writing it
# as `FindFirstFileExW` gives it. A path too long for the functions of the
# system to take as it is is looked up as a path of the whole file system,
# `\\?\D:\x` or `\\?\UNC\server\share\x`.
def find_entry(units: *u16, length: u64, entry: *mut u8): bool {
var path: u16[32800];
val named := (&mut path) as *mut u16;
var at: u64 = 0;
var from: u64 = 0;
if length >= 248 && !begins_with(units, length, 0, "\\\\?\\") {
val shared := begins_with(units, length, 0, "\\\\");
val prefix: strview = shared ? "\\\\?\\UNC" : "\\\\?\\";
for i in 0..prefix.length {
named[at] = prefix[i] as u16;
at++;
}
from = shared ? 1 : 0;
}
for i in from..length {
named[at] = units[i];
at++;
}
named[at] = 0;
val find := FindFirstFileExW(named as *u16, basic_find, entry, 0, null, 0);
return false if find == invalid_handle;
FindClose(find);
return true;
}
}
#! Milliseconds since a moment the system chose, which only ever grow.
#! @returns The time.
pub def now_ms(): i64 {
return system::clock(clock_kind::steady) / 1000000;
}
#! Waits until a handle can be read, or has ended, for at most a while, as
#! `system::poll` waits. On Windows, where it looks at a pipe again and again,
#! waiting for as long as it takes is left to the read that follows instead,
#! which waits without waking until something arrives.
#! @param handle The handle.
#! @param wait The most milliseconds to wait, or -1 to wait for as long as
#! it takes.
#! @returns More than 0 where it can be read, 0 where the wait ran out, and a
#! negative error number where it failed.
pub def wait_readable(handle: system::fd, wait: i64): i64 {
when os == windows {
return 1 if wait < 0;
}
var handles: system::fd[1];
var ready: bool[1];
handles[0] = handle;
val watched := span::<system::fd>::over((&handles) as *system::fd, 1);
return system::poll(watched, slice::<bool>::over((&mut ready) as *mut bool, 1), wait) as i64;
}
#! Writes the whole of the text to a handle.
#! @param handle The handle.
#! @param text The text.
#! @returns Whether all of it was written, which it is not where the other end
#! is gone.
pub def put_all(handle: system::fd, text: strview): bool {
var written: u64 = 0;
while written < text.length {
val size := handle.write(text.data + written, text.length - written);
if size == -4 {
continue;
}
return false if size <= 0;
written += size as u64;
}
return true;
}
#! Writes a number to a handle, as the eight bytes it is held in.
#! @param handle The handle.
#! @param value The number.
#! @returns Whether it was written.
pub def put_size(handle: system::fd, value: u64): bool {
var held := value;
return put_all(handle, strview::over((&held) as *u8, 8));
}
#! Writes text to a handle, as its length and then its bytes.
#! @param handle The handle.
#! @param text The text.
#! @returns Whether it was written.
pub def put_text(handle: system::fd, text: strview): bool {
return put_size(handle, text.length) && put_all(handle, text);
}
#! Reads as many bytes as asked from a handle into the text, waiting until they
#! arrive, or until a moment passes.
#! @param handle The handle.
#! @param into Where the bytes are appended.
#! @param length How many bytes to read.
#! @param deadline The moment to stop waiting, as `now_ms` gives it, or 0 to
#! wait for as long as it takes.
#! @returns Whether they all arrived.
pub def get_all(handle: system::fd, into: &mut string, length: u64, deadline: i64): bool {
var chunk: u8[16384];
var left := length;
while left != 0 {
if deadline != 0 {
val wait := deadline - now_ms();
return false if wait <= 0;
val ready := wait_readable(handle, wait);
if ready == -4 {
continue;
}
return false if ready <= 0;
}
val asked: u64 = left < 16384 ? left : 16384;
val size := handle.read((&mut chunk) as *mut u8, asked);
if size == -4 {
continue;
}
return false if size <= 0;
into.append(strview::over((&chunk) as *u8, size as u64));
left -= size as u64;
}
return true;
}
#! Reads a number from a handle, as `put_size` writes one.
#! @param handle The handle.
#! @param out Where the number is written.
#! @param deadline The moment to stop waiting, or 0.
#! @returns Whether it arrived.
pub def get_size(handle: system::fd, out: &mut u64, deadline: i64): bool {
var bytes := string::new(nothing {});
return false if !get_all(handle, &mut bytes, 8, deadline);
out = *(bytes.view().data as *u64);
return true;
}
#! Reads text from a handle, as `put_text` writes it.
#! @param handle The handle.
#! @param out Where the text is written.
#! @param deadline The moment to stop waiting, or 0.
#! @returns Whether it arrived.
pub def get_text(handle: system::fd, out: &mut string, deadline: i64): bool {
var length: u64 = 0;
return false if !get_size(handle, &mut length, deadline);
out.clear();
return get_all(handle, out, length, deadline);
}
#! Reads everything a handle gives until it ends.
#! @param handle The handle.
#! @param into Where it is appended.
pub def get_rest(handle: system::fd, into: &mut string): void {
var chunk: u8[16384];
while true {
val size := handle.read((&mut chunk) as *mut u8, 16384);
if size == -4 {
continue;
}
break if size <= 0;
into.append(strview::over((&chunk) as *u8, size as u64));
}
}
#! Reads everything a handle gives until it ends, or until a moment passes.
#! @param handle The handle.
#! @param into Where it is appended.
#! @param deadline The moment to stop waiting, as `now_ms` gives it.
#! @returns Whether it ended before the moment passed.
pub def get_until(handle: system::fd, into: &mut string, deadline: i64): bool {
var chunk: u8[16384];
while true {
val wait := deadline - now_ms();
return false if wait <= 0;
val ready := wait_readable(handle, wait);
if ready == -4 {
continue;
}
return true if ready < 0;
return false if ready == 0;
val size := handle.read((&mut chunk) as *mut u8, 16384);
if size == -4 {
continue;
}
return true if size <= 0;
into.append(strview::over((&chunk) as *u8, size as u64));
}
return true;
}
#! Waits for a process the server started to stop, and says how.
#! @param process The process.
#! @param status How it stopped.
#! @returns Whether it was waited for.
pub def reap(process: i64, status: &mut system::process_status): bool {
while true {
val result := system::wait(process, status);
return result >= 0 if result != -4;
}
return false;
}
#! Reads the whole of a file.
#! @param at The file's path.
#! @param out Where its text is written.
#! @returns Whether it was read.
pub def read_text(at: strview, out: &mut string): bool {
var found := path::parse(at) else (_) { return false; };
var text := io::read_file(&found) else (_) { return false; };
out = move(&mut text);
return true;
}
#! The folder of a library the compiler brings with it, as `core`: the one of
#! the name beside its executable, or in the nearest folder above that holds
#! one, so a compiler built anywhere within a repository finds the
#! repository's. No option or variable names it.
#! @param name The folder's name.
#! @returns Its path, or empty where there is none.
pub def toolchain_folder(name: strview): string {
val whole := executable_path();
var end := whole.length;
while end > 0 {
end--;
continue if whole[end] != '/' && !(is_windows && whole[end] == '\\');
var tried := $"{whole.view().substr(0, end)}/{name}";
return tried if is_folder(tried.view());
}
return string::new(nothing {});
}
#! The standard library the compiler finds, as `--lib` would give it, where no
#! `--lib` names `std` itself: a `std` folder beside the executable or in the
#! nearest folder above it that holds one, as `core` is found, and otherwise
#! each of std's libraries in the `share/sakura` folder nearest above it, where
#! `blossom install` puts them, as `std.io` gives `std::io`. No option or
#! variable names it.
#! @param given The libraries `--lib` names, each as `NAME=DIR`.
#! @returns Each library found, as `NAME=DIR`, in the order of their names:
#! none where `--lib` names `std`, or where none is found.
pub def found_std(given: span<strview>): vector<string> {
var found := vector::<string>::new();
for each in given {
return found if each.starts_with("std=");
}
val tree := toolchain_folder("std");
if tree.length != 0 {
found.append($"std={tree}");
return found;
}
val shelf := toolchain_folder("share/sakura");
return found if shelf.length == 0;
val at := path::parse(shelf.view()) else (_) { return found; };
var listing := io::directory::open(&at) else (_) { return found; };
var names := vector::<string>::new();
while listing.next() is some(each) {
continue if each.name != "std" && !each.name.starts_with("std.");
continue if !is_folder($"{shelf}/{each.name}".view());
names.append(string::from(each.name, nothing {}));
}
names.sort_by(def(a: &string, b: &string): bool { return a.view().compare(b.view()) < 0; });
for &name in names {
var named := string::new(nothing {});
for byte in name.view() {
if byte == '.' {
named.append("::");
} else {
named.push(byte);
}
}
found.append($"{named}={shelf}/{name}");
}
return found;
}
#! Whether a path names a folder, following a link it ends in.
#! @param at The path.
#! @returns Whether it does.
pub def is_folder(at: strview): bool {
var found := path::parse(at) else (_) { return false; };
val info := io::info(&found) else (_) { return false; };
return info.kind == file_kind::directory;
}
when os == linux {
# Whether the system spells paths with `\` as well as `/`.
val is_windows: bool = false;
}
when os == windows {
# Whether the system spells paths with `\` as well as `/`.
val is_windows: bool = true;
}
#! The file the declarations of the types the syntax makes are shown from, which
#! the compiler holds as text rather than in a file: written once, where the
#! user's files of the moment are kept, so going to `string` opens it. Editing
#! it changes nothing, since no check reads it.
#! @returns Its path, or empty where it could not be written.
pub def builtin_document(): string {
var folder := string::new(nothing {});
when os == windows {
if process::variable("LOCALAPPDATA") is some(at) {
folder = $"{at}/sakura";
}
} else {
if process::variable("XDG_CACHE_HOME") is some(at) {
folder = $"{at}/sakura";
} else if process::variable("HOME") is some(at) {
folder = $"{at}/.cache/sakura";
}
}
return string::new(nothing {}) if folder.length == 0;
var made := $"{folder}/built-in.sakura";
var held := string::new(nothing {});
return made if read_text(made.view(), &mut held) && held.view() == builtin_text;
var at := path::parse(folder.view()) else (_) { return string::new(nothing {}); };
_ = io::create_directories(&at);
var file := path::parse(made.view()) else (_) { return string::new(nothing {}); };
return io::write_file(&file, builtin_text) is value(_) ? move(&mut made) : string::new(nothing {});
}