Files
sakurac/machine/machine.sakura
T

938 lines
41 KiB
Plaintext
Raw Normal View History

2026-10-26 10:14:11 -05:00
#! @file machine.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the machine, which runs a program's code, as the C machine does:
#! frames of words one after another on a stack of its own, globals, the
#! program's data, and memory the program gives back itself. Addresses are the machine's own, so what a program reads and
#! writes through a pointer is memory as it is.
#!
#! A fault stops the program, and the machine says where each function running
#! was, as the C machine does, so a fault reads the same in both.
import sakura::analyzer;
import sakura::compiler;
import std::containers;
module sakura::machine;
#! Why the machine stopped, numbered as the C machine numbers its errors.
pub enum halt : u32 {
none = 0, #! It did not stop.
no_main = 2, #! The program has no `main`.
unsupported = 3, #! The program does what this machine cannot.
out_of_bounds = 4, #! An index or slice was out of bounds.
null_reference = 5, #! A null reference was unwrapped.
division = 6, #! A number was divided by zero.
not_held = 7, #! A union did not hold the field read.
stack_overflow = 8, #! The stack overflowed.
unreachable = 9, #! A function ended without returning a value.
invalid_release = 11, #! Memory released was not allocated, or was already released.
not_member = 13, #! A value is not a member of its enum.
not_constant = 15, #! What was run does not run while compiling.
evaluation_limit = 16, #! Evaluating took too many steps.
not_evaluated = 17, #! A constant read is not evaluated yet.
invalid_access = 18, #! A pointer reaches memory the program does not hold.
address = 19, #! Pointers into different memory are compared or subtracted.
exited = 20, #! The program asked to stop.
aborted = 21, #! The program aborted.
foreign_missing = 22, #! A C function the program calls, or the library holding it, was not found.
callback = 23, #! C called a function of the program while the program was not calling C.
out_of_memory = 24, #! The system gave no memory.
elsewhere = 25, #! Another thread stopped the program, which says why.
faulted = 26, #! The program stopped itself, saying why, as `fault` does.
unwritten = 27, #! Memory was read before anything wrote it, running with memory checked.
step_limit = 28, #! A call took more steps than its host allowed it.
overflow = 29, #! Integer arithmetic gave what its type cannot hold, running checked as `--checks` asks.
race = 30, #! Two threads reached the same memory, one writing it, with nothing ordering them, running checked.
}
#! What a halt says, as the C machine says it.
#! @param this The halt.
#! @returns The sentence.
pub def halt::describe(&this): strview {
return match this {
halt::no_main => "Program has no `main` function.",
halt::unsupported => "Program uses a construct that cannot be compiled.",
halt::out_of_bounds => "Index or slice is out of bounds.",
halt::null_reference => "Null reference was unwrapped.",
halt::division => "Division by zero.",
halt::not_held => "Union does not hold the field that was read.",
halt::stack_overflow => "Stack overflowed.",
halt::unreachable => "Function ended without returning a value.",
halt::invalid_release => "Released memory that was not allocated, or was already released.",
halt::not_member => "Value is not a member of its enum.",
halt::not_constant => "Function does not run while compiling.",
halt::evaluation_limit => "Evaluation took too many steps, as an endless loop or recursion would.",
halt::not_evaluated => "Constant has not been evaluated yet.",
halt::invalid_access => "Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released.",
halt::address => "Pointers into different memory are compared or subtracted, which depends on where the memory is.",
halt::exited => "Program exited.",
halt::aborted => "Program aborted.",
halt::foreign_missing => "C function could not be found, nor the library holding it.",
halt::callback => "C called a function of the program while the program was not calling C.",
halt::out_of_memory => "Out of memory.",
halt::elsewhere => "Another thread stopped the program.",
halt::faulted => "Program faulted.",
halt::unwritten => "Memory was read before anything wrote it, as memory `raw_allocate` gives or a variable `undefined`.",
halt::step_limit => "Call took more steps than it was allowed, as an endless loop or recursion would.",
halt::overflow => "Integer arithmetic overflowed.",
halt::race => "Threads raced: memory one wrote, another read or wrote, with nothing ordering the two.",
else => "Unknown machine error"
};
}
#! The halt a number stands for, as a fault a program asks for names it.
#! @param code The number.
#! @returns The halt, or `unsupported` for a number no halt has.
pub def halt_of(code: u64): halt {
return match code {
3 => halt::unsupported, 4 => halt::out_of_bounds, 5 => halt::null_reference, 6 => halt::division,
7 => halt::not_held, 8 => halt::stack_overflow, 9 => halt::unreachable, 11 => halt::invalid_release,
13 => halt::not_member, 15 => halt::not_constant, 16 => halt::evaluation_limit,
17 => halt::not_evaluated, 18 => halt::invalid_access, 19 => halt::address, 21 => halt::aborted,
26 => halt::faulted, 29 => halt::overflow,
else => halt::unsupported
};
}
#! How a program is run.
pub struct interpreting {
pub var stack: u64; #! The bytes of the stack, or 0 for the default.
var evaluating: bool; #! Whether the program evaluates constants while compiling.
pub var capture: bool; #! Whether what the program writes to its output is kept rather than written, for `take_output`.
pub var checks: bool; #! Whether what references and pointers reach is checked, as `run --checks` asks, which the program's code must be lowered for.
pub var steps: u64; #! The steps, as jumps and calls, that `begin`, `run`, and each call the host makes may take before it stops with `step_limit`, or 0 for as many as it takes.
pub var interpret: bool; #! Whether every function is interpreted, none compiled to the processor's code as `jit.sakura` compiles them.
}
#! A function the host gives the program to call by name.
struct provided {
var name: string; #! The name a foreign declaration of the program gives it.
var address: u64; #! Where C calls it.
}
#! A function as the machine calls it.
pub struct routine {
var code: *u32; #! Its code.
var frame: u64; #! The bytes of its frame.
var cells: u64; #! Where its cells begin, the first of which are zeroed as it starts.
var zeroed: u64; #! Where the cells zeroed as it starts end.
var env: u64; #! Where a closure's environment is.
var params: u32; #! The first of its parameters in the machine's `params`.
var count: u32; #! How many parameters it takes.
var returned: u64; #! The bytes of the memory it returns, or 0.
var closure: bool; #! Whether its environment follows its parameters.
}
#! A call running.
pub struct call_record {
var function: u32; #! The function called.
var fp: *mut u64; #! Its frame.
var back: u64; #! Where the caller goes on.
var site: u64; #! Where the call is in the caller's code.
var results: u64; #! Where the caller's code lists the words its results go to, or `none`.
var dst: u64; #! Where a result held in memory is written.
}
#! The calls running, the innermost last. The machine's code pushes and pops
#! them, and so does the code `jit.sakura` compiles, which reaches the fields at
#! their offsets, so they stay in this order, a record 48 bytes.
pub struct call_stack : owning {
var data: *mut call_record = null; #! The records.
var used: u64; #! How many calls are running.
var capacity: u64; #! How many records fit before they move.
}
#! An empty stack of calls.
#! @returns The stack.
pub def call_stack::new(): call_stack {
return call_stack {};
}
#! How many calls are running.
pub val call_stack::length: u64 {
get => this.used;
}
#! Pushes a call.
#! @param this The stack.
#! @param record The call.
pub def call_stack::append(&mut this, record: call_record): void {
if this.used == this.capacity {
this.grow();
}
this.data[this.used] = record;
this.used++;
}
#! Makes room for twice as many records, at least 64.
#! @param this The stack.
pub def call_stack::grow(&mut this): void {
val wanted := this.capacity < 32 ? 64u : this.capacity * 2;
val made := raw_allocate(wanted * size_of::<call_record>()) as *mut call_record;
if this.data != null {
memcpy(made as *mut u8, this.data as *u8, this.used * size_of::<call_record>());
raw_release(this.data as *mut u8);
}
this.data = made;
this.capacity = wanted;
}
#! The innermost call.
#! @param this The stack, holding one at least.
#! @returns The call.
pub def call_stack::last(&this): call_record {
return this.data[this.used - 1];
}
#! A call, counting from the outermost.
#! @param this The stack.
#! @param index Which, below its length.
#! @returns The call.
pub def call_stack::at(&this, index: u64): call_record {
return this.data[index];
}
#! Pops the innermost call.
#! @param this The stack, holding one at least.
pub def call_stack::truncate(&mut this): void {
this.used--;
}
#! Pops every call.
#! @param this The stack.
pub def call_stack::clear(&mut this): void {
this.used = 0;
}
#! Gives back the records' memory.
#! @param this The stack.
pub def call_stack::close(&mut this): void {
if this.data != null {
raw_release(this.data as *mut u8);
}
this.data = null;
this.used = 0;
this.capacity = 0;
}
#! A function a trace names, and where it was.
pub struct trace_frame {
var function: string; #! Its name.
var path: strview; #! The file.
var line: u32; #! The line.
var column: u32; #! The column.
}
#! What stands for nothing where a place is wanted.
pub const none: u64 = 0xFFFFFFFFFFFFFFFF;
#! The bytes of the stack, unless asked otherwise.
pub const default_stack: u64 = 8388608;
#! The machine, which interprets the code of a program.
pub struct interpreter : owning {
var c: &mut lowerer; #! The compiler, whose program runs and whose checker knows the source.
var options: interpreting; #! How the program is run.
var routines: vector<routine>; #! Each function, as the machine calls it.
var unready: vector<u32>; #! The functions loaded before their code was made, as one an evaluation lowered within another's lowering, whose routines are made again once it is.
var params: vector<param_slot>; #! The parameters of every function, as runs `routines` say.
var stack: *mut u8; #! The frames.
var stack_end: u64; #! Where the stack ends.
var top: u64; #! Where the frames in use end.
var globals: *mut u8; #! The globals.
var globals_room: u64; #! How many bytes the globals have room for, which a machine evaluating while checking takes more of as evaluations are lowered.
var data: vector<u64>; #! Where each datum is.
var blocks: dict<u64, u64>; #! The memory the program gives back itself, and how large each is.
var kept: dict<u64, bool>; #! The blocks a constant evaluated holds, which stay to the end.
var sites: dict<u64, u64>; #! Running with its memory checked, where each block was allocated: the function and where in its code, by `pair_key`.
var released: vector<u64>; #! Running with its memory checked, the blocks released and held back from being used again, oldest first, from `released_from`.
var released_sizes: vector<u64>; #! How large each of them is.
var released_from: u64; #! The first of them still held back.
var released_bytes: u64; #! The bytes of those held back.
var calls_c: bool; #! Whether the program calls C, whose memory the machine does not know.
var called_c: bool = false; #! Whether code of the program's own, rather than `system`'s alone, calls C, which may give it memory of C's.
var pages: dict<u64, vector<u64>>; #! Running with its memory checked, the blocks over each page of 4096 bytes, by its number, which the block an address is within is found among.
var unwritten: dict<u64, vector<u64>>; #! Running with its memory checked, of each page of 4096 bytes holding any byte never written, by its number, which of its bytes are, a bit each.
var seen_page: u64 = 0xFFFFFFFFFFFFFFFF; #! The page whose bits of `unwritten` were last looked for.
var seen_bits: *mut u64 = null; #! Its bits, or null where it has none.
var read_stop: halt = halt::none; #! Why reading the program's memory for it, as formatting a value does, would stop it, running with memory checked.
var framed_unwritten: bool = false; #! Whether a variable `undefined` was marked never written, in a frame, so each frame begun clears what one before left.
var mapped: vector<u64>; #! Running with its memory checked, the memory the program was given rather than allocated, as pairs of where each begins and its bytes, in order of where each begins: what it mapped, the variables it started with, and its arguments.
var unmapped: vector<u64>; #! Running with its memory checked, where the program calls C, the memory it mapped and gave back, likewise, which it holds no longer, though the machine takes what it does not know as C's.
var data_runs: vector<u64>; #! Running with its memory checked, where each datum is and its bytes, likewise in order.
var ended: vector<u64>; #! Running with its memory checked, the words of the frames each thread had in use as the program ended by exiting, which the leaks reported count as reaching what they hold.
var calls: call_stack; #! The calls running, the innermost last.
var texts: vector<vector<u8>>; #! The texts being formatted, the innermost last, and those made before, whose memory is kept.
var depth: u64; #! How many texts are being formatted.
var results: u64[3]; #! The words the call the machine began returns.
var trace: vector<trace_frame>; #! Where each function was, where the program faulted.
var fault_text: string; #! What `fault` said, where the program stopped by it.
var races: race_checker; #! What the race checker keeps, running with memory checked once the program starts a thread.
pub var status: i32; #! What the program asked to exit with.
var output: vector<u8>; #! What the program wrote to its output, where it is kept.
var budget: u64; #! The steps an evaluation may still take.
var ready: vector<bool>; #! Whether each evaluation is done, while compiling.
var waiting: u32; #! The evaluation a run stopped at.
var environ: u64; #! The variables the program started with, as the system gives them.
var threads: *mut threading = null; #! What the program's threads share, once it starts one.
var strand: *mut strand = null; #! What the thread running has of its own, while threads run.
var countdown: u64 = 0; #! Steps until the running thread lets another run.
# Calling C, where the system running the machine is Windows. The libraries
# the program links are opened and the C functions it calls by name found
# before it runs; the code a call of C goes through, and that C calls each
# function of the program through, is made once C is first called, since C
# only calls an address. The code and the libraries are the machine's, shared
# by every thread, while the last error a C call left is each thread's own.
var foreign_found: bool = false; #! Whether the C functions were looked for.
var provided: vector<provided>; #! The functions the host gives the program, which are found before C's.
var symbols: vector<u64>; #! The address of each C function the program links.
var libraries: vector<u64>; #! The libraries opened, to close, or 0 where an earlier one shares it.
var call_stub: u64 = 0; #! The code a call of C goes through, or 0.
var callbacks: vector<u64>; #! The address C calls each function through, or 0 where it is none.
var foreign_memory: u64 = 0; #! The executable memory the stubs are in, or 0.
var foreign_size: u64 = 0; #! The bytes of it.
var last_error: u32 = 0; #! The error the last C call left, kept across the machine's own work.
var foreign_fault: halt = halt::none; #! Why a function C called stopped, until C comes back and the machine stops.
var calling_c: u64 = 0; #! How many calls of C are under way, which C may call back within.
var maps_at: u64 = 0; #! The address of `VirtualAlloc`, where the program calls it, whose memory a run with its memory checked holds as what `mmap` maps.
var unmaps_at: u64 = 0; #! The address of `VirtualFree`, likewise, which gives that memory back as `munmap` does.
var writes_at: u64 = 0; #! The address of `WriteFile`, where the program calls it, whose writes to the output and error a run that `capture`s keeps.
var console_writes_at: u64 = 0; #! The address of `WriteConsoleW`, likewise.
# Compiling functions to the processor's code, as `jit.sakura` does. Its code
# reads and writes the fields of the machine it names at their offsets.
var jit_on: bool = false; #! Whether functions are compiled as they are first called.
var jit_table: *mut u64 = null; #! Where each function's compiled code begins, or 0 where it has none.
var jit_tried: vector<bool>; #! Whether each function was compiled, or found not to compile.
var jit_chunks: vector<u64>; #! The executable memory the code is in: pairs, where each piece begins and its bytes.
var jit_used: u64 = 0; #! Where the next function's code goes, in the last chunk.
var jit_limit: u64 = 0; #! Where the last chunk ends.
var jit_stub: u64 = 0; #! The code a call of compiled code from the machine goes through.
var jit_at: jit_layout; #! Where compiled code finds the machine's fields, and the helpers it calls.
var jit_left: u64 = 0; #! The steps compiled code may take before it settles them, as its register holds them while it runs.
var jit_batch: u64 = 0; #! The steps it was given to take.
var jit_origin: u64 = 0; #! Where in its code a compiled function stopped, for the trace.
}
#! Makes a machine running a program lowered, made into the machine's code.
#! @param c The compiler, whose program runs.
#! @param options How it is run.
#! @returns The machine.
pub def interpreter::new(c: &mut lowerer, options: interpreting): interpreter {
c.assemble_all();
var made := interpreter {
c = c,
options = options,
routines = vector::<routine>::new(),
unready = vector::<u32>::new(),
params = vector::<param_slot>::new(),
data = vector::<u64>::new(),
blocks = dict::<u64, u64>::new(),
kept = dict::<u64, bool>::new(),
sites = dict::<u64, u64>::new(),
released = vector::<u64>::new(),
released_sizes = vector::<u64>::new(),
pages = dict::<u64, vector<u64>>::new(),
unwritten = dict::<u64, vector<u64>>::new(),
mapped = vector::<u64>::new(),
unmapped = vector::<u64>::new(),
data_runs = vector::<u64>::new(),
ended = vector::<u64>::new(),
calls = call_stack::new(),
texts = vector::<vector<u8>>::new(),
trace = vector::<trace_frame>::new(),
output = vector::<u8>::new(),
ready = vector::<bool>::new(),
provided = vector::<provided>::new(),
symbols = vector::<u64>::new(),
libraries = vector::<u64>::new(),
callbacks = vector::<u64>::new(),
jit_tried = vector::<bool>::new(),
jit_chunks = vector::<u64>::new(),
races = race_checker::new()
};
made.load();
made.jit_begin();
if options.checks {
made.order_data();
}
var called_back := false;
for &each in made.c.program.functions {
called_back = called_back || each.callback;
}
made.calls_c = made.c.program.linked.length != 0 || called_back;
# On Windows `system` is made of calls of C, whose memory only its own code
# reads, so the program's own code may hold memory of C's from the start only
# where it links C of its own, which its globals may call as they begin, or C
# calls a function of it back.
var called_c := called_back;
for &each in made.c.program.linked {
called_c = called_c || !made.in_system(each.decl);
}
made.called_c = called_c;
return made;
}
#! Lays out what the program runs with: each function as the machine calls it,
#! the stack, the globals, and the data, each address within which is written
#! as the machine placed what it points into.
#! @param this The machine.
def interpreter::load(&mut this): void {
for i in 0..this.c.program.functions.length {
val held := &this.c.program.functions[i];
val first := this.params.length as u32;
this.params.extend(held.compiled.params.span);
this.routines.append(routine {
code = held.compiled.code.span.data,
frame = held.compiled.frame,
cells = held.compiled.cells,
zeroed = held.compiled.zeroed,
env = held.compiled.env,
params = first,
count = held.compiled.params.length as u32,
returned = held.compiled.returned,
closure = held.closure
});
}
val size := this.options.stack != 0 ? this.options.stack : default_stack;
# Each frame clears what it reads before it writes, so the stack is not
# cleared first, but running with its memory checked: the frames in use are
# read whole as the program exits, for the blocks they reach, and a word of
# one nothing wrote, as the scratch word, holds no address.
this.stack = this.options.checks ? raw_allocate_zeroed(size) : raw_allocate(size);
this.stack_end = this.stack as u64 + size;
this.top = this.stack as u64;
# A machine evaluating while checking runs what each evaluation lowers, whose
# globals follow those before them, which stay where they are, since what it
# kept may point into them: it is given room for those first, and only the
# pages they reach are ever taken.
this.globals_room = this.c.program.globals + word_size;
if this.options.evaluating && this.globals_room < evaluating_room {
this.globals_room = evaluating_room;
}
this.globals = raw_allocate_zeroed(this.globals_room);
this.budget = evaluation_budget;
for i in 0..this.c.program.data.length {
val bytes := &this.c.program.data[i].bytes;
val made := raw_allocate(bytes.length + 16);
memset(made, 0, bytes.length + 16);
memcpy(made, bytes.span.data, bytes.length);
this.data.append(made as u64);
}
for i in 0..this.c.program.data.length {
val held := &this.c.program.data[i];
for &each in held.relocations {
val base: u64 = this.data[i];
val target: u64 = this.data[each.target];
val at := (base + each.at) as *mut u64;
at[0] = target + each.addend;
}
}
}
#! The room for globals a machine evaluating while checking is given.
const evaluating_room: u64 = 0x4000000;
#! Loads what the compiler lowered since the machine last loaded: each function
#! and each datum new since, as a machine evaluating while checking runs what
#! each evaluation lowers. The globals stay where they are.
#! @param this The machine.
#! @returns Whether the globals still fit their room.
pub def interpreter::refresh(&mut this): bool {
this.c.assemble_all();
var waiting := vector::<u32>::new();
for i in 0..this.unready.length {
val each: u32 = this.unready[i];
if this.c.program.functions[each].compiled.done {
this.routines[each] = this.routine_of(each);
} else {
waiting.append(each);
}
}
this.unready = move(&mut waiting);
for i in this.routines.length..this.c.program.functions.length {
this.routines.append(this.routine_of(i as u32));
if !this.c.program.functions[i].compiled.done {
this.unready.append(i as u32);
}
}
return false if this.c.program.globals + word_size > this.globals_room;
val from := this.data.length;
for i in from..this.c.program.data.length {
val bytes := &this.c.program.data[i].bytes;
val made := raw_allocate(bytes.length + 16);
memset(made, 0, bytes.length + 16);
memcpy(made, bytes.span.data, bytes.length);
this.data.append(made as u64);
}
for i in from..this.c.program.data.length {
val held := &this.c.program.data[i];
for &each in held.relocations {
val base: u64 = this.data[i];
val target: u64 = this.data[each.target];
val at := (base + each.at) as *mut u64;
at[0] = target + each.addend;
}
}
# C functions linked since are looked for with the rest, once one is called.
if this.symbols.length != this.c.program.linked.length {
this.foreign_found = false;
}
this.calls_c = this.calls_c || this.c.program.linked.length != 0;
this.ready.resize(this.c.evaluations.length);
return true;
}
#! A function as the machine calls it, its parameters added to those of every
#! function.
#! @param this The machine.
#! @param index The function.
#! @returns The routine.
def interpreter::routine_of(&mut this, index: u32): routine {
val held := &this.c.program.functions[index];
val first := this.params.length as u32;
this.params.extend(held.compiled.params.span);
return routine {
code = held.compiled.code.span.data,
frame = held.compiled.frame,
cells = held.compiled.cells,
zeroed = held.compiled.zeroed,
env = held.compiled.env,
params = first,
count = held.compiled.params.length as u32,
returned = held.compiled.returned,
closure = held.closure
};
}
#! Gives back everything the machine holds.
#! @param this The machine.
pub def interpreter::close(&mut this): void {
for &entry in this.blocks {
raw_release(entry.key as *mut u8);
}
this.blocks.clear();
for i in this.released_from..this.released.length {
val held: u64 = this.released[i];
raw_release(held as *mut u8);
}
this.released.clear();
this.released_sizes.clear();
this.pages.clear();
this.mapped.clear();
this.unmapped.clear();
this.data_runs.clear();
this.ended.clear();
for &each in this.data {
val address: u64 = each;
raw_release(address as *mut u8);
}
this.data.clear();
if this.stack != null {
raw_release(this.stack);
this.stack = null;
}
if this.globals != null {
raw_release(this.globals);
this.globals = null;
}
if this.environ != 0 {
raw_release(this.environ as *mut u8);
this.environ = 0;
}
this.jit_end();
when os == windows {
this.unlink_foreign();
}
this.races.close();
this.provided.close();
this.symbols.close();
this.libraries.close();
this.callbacks.close();
this.fault_text.close();
}
#! Begins the program without calling `main`: the C functions it calls, and
#! those the host provides, are found, and the globals given their values, as a
#! host calling the program's functions itself does once, before it calls any.
#! @param this The machine.
#! @returns Why it stopped, or `none` where the globals have their values.
pub def interpreter::begin(&mut this): halt {
this.trace.clear();
this.fault_text.clear();
this.status = 0;
when os == windows {
# The C functions the program calls are found before it runs, as the system
# running the machine, Windows, is reached through C.
val linked := this.link_foreign();
return linked if linked != halt::none;
}
memset(this.globals, 0, this.c.program.globals);
val preset := this.c.program.preset.span;
if preset.length != 0 {
memcpy(this.globals, preset.data, preset.length);
}
this.budget = this.options.steps;
return this.invoke(this.c.program.init, span::<u64>::blank());
}
#! Runs the program: the code giving the globals their values, then `main`,
#! given a view of each argument's text.
#! @param this The machine.
#! @param args The arguments.
#! @returns Why it stopped: `none` where `main` returned, and `exited` where it
#! asked to, with the status it asked for in `status`.
pub def interpreter::run(&mut this, args: span<strview>): halt {
val main := this.c.program.main;
if main == no_function {
this.trace.clear();
return halt::no_main;
}
val begun := this.begin();
return begun if begun != halt::none;
this.budget = this.options.steps;
# `main` is given a view of views of each argument's text, which the machine
# holds while the program runs.
var words := vector::<u64>::new();
var views := vector::<u64>::new();
if this.routines[main].count == 1 {
for &each in args {
views.append(each.data as u64);
views.append(each.length);
}
words.append(args.length == 0 ? 0 : views.span.data as u64);
words.append(args.length);
# Running with its memory checked, the program holds the views and the
# text of each, as it does memory the system gave it.
if this.options.checks && args.length != 0 {
this.add_run(views.span.data as u64, args.length * 16);
for &each in args {
this.add_run(each.data as u64, each.length);
}
}
}
return this.end_threads(this.invoke(main, words.span));
}
#! Calls a function from the base of the stack, given the bytes of its
#! parameters, and runs it until it returns.
#! @param this The machine.
#! @param index The function.
#! @param args The words of its parameters, as its frame holds them.
#! @returns Why it stopped, or `none`.
pub def interpreter::invoke(&mut this, index: u32, args: span<u64>): halt {
val held: routine = this.routines[index];
val fp := this.stack as *mut u64;
if this.stack as u64 + held.frame > this.stack_end {
return halt::stack_overflow;
}
memset(this.stack, 0, held.frame);
for i in 0..args.length {
fp[i] = args[i];
}
this.calls.clear();
this.depth = 0;
this.calls.append(call_record { function = index, fp = fp, back = 0, site = 0, results = none });
this.top = this.stack as u64 + held.frame;
return this.execute(0);
}
#! Calls a function of the program, as a host embedding the machine does once
#! the program has begun, and runs it until it returns. A call made while the
#! program is calling the host, as from within a function the host provided,
#! runs above the calls under way; where it faults, they stop too, as the host
#! returns to them, so the call the host made first gives the fault.
#! @param this The machine.
#! @param function The function.
#! @param args The words of its parameters, as a call passes them: a
#! word for each integer, bool, pointer, and reference, an
#! `f64` for each float, an `f32` as well, the words of a
#! value held in words, as a view's address and length, and
#! the address of the bytes of a value passed in memory.
#! @param result Where a result held in memory is written, or 0; one held
#! in words is given by `result`.
#! @returns Why it stopped, or `none` where it returned.
pub def interpreter::call(&mut this, function: u32, args: span<u64>, result: u64 = 0): halt {
return this.call_with(function, 0, args, result);
}
#! Calls a function value of the program, as `call` calls a function: its first
#! word is one more than the function, and its second what a closure uses.
#! @param this The machine.
#! @param function The function value's first word.
#! @param environment Its second.
#! @param args The words of its parameters, as `call` takes them.
#! @param result Where a result held in memory is written, or 0.
#! @returns Why it stopped, or `none` where it returned.
pub def interpreter::call_value(&mut this, function: u64, environment: u64, args: span<u64>, result: u64 = 0): halt {
return halt::null_reference if function == 0 || function > this.routines.length;
return this.call_with((function - 1) as u32, environment, args, result);
}
# Calls a function for the host, as `call` says, with what a closure uses.
def interpreter::call_with(&mut this, function: u32, environment: u64, args: span<u64>, result: u64): halt {
val base := this.calls.length;
if base == 0 {
this.trace.clear();
this.fault_text.clear();
this.depth = 0;
this.top = this.stack as u64;
this.budget = this.options.steps;
}
if (function as u64) >= this.routines.length {
return this.host_stop(base, halt::null_reference);
}
val held: routine = this.routines[function];
val frame := this.top as *mut u64;
if this.top + held.frame > this.stack_end {
return this.host_stop(base, halt::stack_overflow);
}
# A frame's words are written before they are read, so only its cells are
# zeroed, as a call within the program zeroes them, but where memory is
# checked, where none of it is left as another call left it.
if this.options.checks {
memset(frame as *mut u8, 0, held.frame);
} else if held.zeroed > held.cells {
memset((frame as u64 + held.cells) as *mut u8, 0, held.zeroed - held.cells);
}
var k: u64 = 0;
for p in 0..held.count {
val slot: param_slot = this.params[held.params as u64 + p as u64];
val words: u64 = slot.memory ? 1 : slot.words as u64;
if k + words > args.length {
return this.host_stop(base, halt::unsupported);
}
if slot.memory {
val source: u64 = args[k];
if source != 0 {
memcpy((frame as u64 + slot.offset) as *mut u8, source as *u8, slot.size);
}
} else {
for w in 0..words {
frame[slot.offset / word_size + w] = args[k + w];
}
}
k += words;
}
if held.closure {
frame[held.env / word_size] = environment;
}
this.calls.append(call_record { function = function, fp = frame, back = 0, site = 0, results = none, dst = held.returned != 0 ? result : 0 });
this.top = frame as u64 + held.frame;
# Made from within compiled code calling the host, the steps that code took
# are settled first, and it is given more after.
val within := this.jit_batch != 0;
if within {
this.jit_settle();
}
val why := this.execute(base);
if within {
this.jit_arm();
}
if why != halt::none && base != 0 && this.foreign_fault == halt::none {
this.foreign_fault = why;
}
return why;
}
# Stops a call the host made before it ran, which stops those under way where
# it was made within them.
def interpreter::host_stop(&mut this, base: u64, why: halt): halt {
if base != 0 && this.foreign_fault == halt::none {
this.foreign_fault = why;
}
return why;
}
#! A word of what the last call the host made returned, where it was held in
#! words: the first is the value of a scalar, and a view's address, the second
#! its length.
#! @param this The machine.
#! @param index Which word, below 3.
#! @returns The word.
pub def interpreter::result(&this, index: u64): u64 {
return index < 3 ? this.results[index] : 0;
}
#! Takes what the program wrote to its output and error since this was last
#! asked, where it runs with `capture`.
#! @param this The machine.
#! @returns The text.
pub def interpreter::take_output(&mut this): string {
var text := string::from(this.output.span, nothing {});
this.output.clear();
return text;
}
#! Gives the program a function of the host's to call: a foreign declaration of
#! that name, as a C function is declared, calls it, whatever library its file
#! names. The program calls it as C would, so the address is one C calls, as a
#! `cfn` of a function of the host's own is. Given after the program has begun,
#! it replaces what was found for the name. The machine calls C only where the
#! system running it is Windows.
#! @param this The machine.
#! @param name The name.
#! @param address Where C calls it.
pub def interpreter::provide(&mut this, name: strview, address: u64): void {
var found := false;
for &mut each in this.provided {
if each.name.span == name {
each.address = address;
found = true;
}
}
if !found {
this.provided.append(provided { name = string::from(name, nothing {}), address = address });
}
for i in 0..this.symbols.length {
if this.c.checker.names.text(this.c.program.linked[i].name) == name {
this.symbols[i] = address;
}
}
}
#! The address the host gave for a function the program calls by name, or 0.
#! @param this The machine.
#! @param name The name.
#! @returns The address.
pub def interpreter::provided_address(&this, name: strview): u64 {
for &each in this.provided {
return each.address if each.name.span == name;
}
return 0;
}
#! Records where each function running was, from the innermost out, then lets
#! go of every call. Where none is running, as where a call within them stopped
#! first and let go of them, what that one recorded is kept.
#! @param this The machine.
#! @param pc Where the innermost was.
pub def interpreter::record(&mut this, pc: u64): void {
if this.calls.length == 0 {
this.depth = 0;
this.top = this.stack as u64;
return;
}
this.trace.clear();
var i := this.calls.length;
while i > 0 {
i--;
val call: call_record = this.calls.at(i);
val at := i == this.calls.length - 1 ? pc : this.calls.at(i + 1).site;
this.frames_at(call.function, at);
}
this.calls.clear();
this.depth = 0;
this.top = this.stack as u64;
}
#! Records where a function's code was, as a trace names it: each function
#! inlined there, from the innermost out, where it was, then the function
#! itself, where the outermost was called.
#! @param this The machine.
#! @param function The function.
#! @param pc Where in its code.
def interpreter::frames_at(&mut this, function: u32, pc: u64): void {
val held := &this.c.program.functions[function];
var at: u64 = 0;
var site: u32 = 0;
for &mark in held.compiled.lines {
break if mark.pc as u64 > pc;
at = mark.at;
site = mark.site;
}
var steps := 0;
while site != 0 && site as u64 <= held.compiled.sites.length && steps < 1024 {
val inlined: inline_site = held.compiled.sites[site - 1];
this.trace.append(this.frame_at(inlined.function, at));
at = inlined.at;
site = inlined.parent;
steps++;
}
this.trace.append(this.frame_at(function, at));
}
#! The frame a block's allocation is reported at, of the code of a function
#! where it was made: the innermost function inlined there that is the
#! program's own rather than std's, or else the function itself.
#! @param this The machine.
#! @param function The function.
#! @param pc Where in its code.
#! @returns The frame.
pub def interpreter::site_frame(&mut this, function: u32, pc: u64): trace_frame {
var at: u64 = 0;
var site: u32 = 0;
for &mark in this.c.program.functions[function].compiled.lines {
break if mark.pc as u64 > pc;
at = mark.at;
site = mark.site;
}
var steps := 0;
while site != 0 && site as u64 <= this.c.program.functions[function].compiled.sites.length && steps < 1024 {
val inlined: inline_site = this.c.program.functions[function].compiled.sites[site - 1];
return this.frame_at(inlined.function, at) if !this.in_std_function(inlined.function);
at = inlined.at;
site = inlined.parent;
steps++;
}
return this.frame_at(function, at);
}
#! A frame of a trace: a function, and where in the source it was.
#! @param this The machine.
#! @param function The function.
#! @param at Where in the source: one more than the file, then the
#! byte, or 0 for where the function is declared.
#! @returns The frame.
def interpreter::frame_at(&mut this, function: u32, at: u64): trace_frame {
val held := &this.c.program.functions[function];
var file: u32 = held.file;
var offset: u32 = held.offset;
if at != 0 {
file = pair_high(at) - 1;
offset = pair_low(at);
}
var made := trace_frame { function = string::from(held.name.span, nothing {}) };
return made if file as u64 >= this.c.checker.units.length;
val source := &this.c.checker.units[file].source;
val place := source.lines.place_of(offset);
made.path = source.path;
made.line = place.line;
made.column = place.column;
return made;
}
#! What a halt says: the text `fault` was given, where it stopped the program,
#! where the other access was, where threads raced, and otherwise the halt's
#! own sentence.
#! @param this The machine.
#! @param why Why it stopped.
#! @returns The text.
pub def interpreter::why_text(&this, why: halt): strview {
return this.fault_text.span if why == halt::faulted && this.fault_text.length != 0;
return this.races.text.span if why == halt::race && this.races.text.length != 0;
return why.describe();
}
#! Writes why the program stopped, and the trace, as the C machine does.
#! @param this The machine.
#! @param why Why it stopped.
#! @param out Where it is written.
pub def interpreter::report(&this, why: halt, out: &mut string): void {
out.append("sakura: runtime error: ");
out.append(this.why_text(why));
out.append("\n");
for &each in this.trace {
out.append($" at {each.function} ({each.path}:{each.line}:{each.column})\n");
}
}