Initial Commit
This commit is contained in:
782 files changed
+145156
No files matched your search
@@ -0,0 +1,245 @@
|
||||
# sakura::machine
|
||||
|
||||
`sakura::machine` is the virtual machine Sakura programs run on with
|
||||
`sakura run`. It runs the code `sakura::compiler` assembles for each function.
|
||||
It has its own stack of frames of words, the program's globals and data, and a
|
||||
heap of the blocks the program allocates and releases. Addresses are real ones,
|
||||
so a pointer reaches memory as it is, and the machine calls the system and C
|
||||
as an executable does. The compiler also runs it to compute constants while
|
||||
compiling.
|
||||
|
||||
## Using it
|
||||
|
||||
Require this repository, which exports each of the compiler's libraries, and name this
|
||||
one among a target's `deps` with the analyzer and the compiler, which it reads itself:
|
||||
|
||||
```yaml
|
||||
requires:
|
||||
- https://git.malunal.studio/sakura/std@v1.0.0
|
||||
- https://git.malunal.studio/sakura/sakurac@v1.0.0
|
||||
|
||||
targets:
|
||||
- name: app
|
||||
type: program
|
||||
deps: [sakura.analyzer, sakura.compiler, sakura.machine, std.io]
|
||||
```
|
||||
|
||||
Running a program as `sakura run` does:
|
||||
|
||||
```sakura
|
||||
import std::io;
|
||||
import sakura::analyzer;
|
||||
import sakura::compiler;
|
||||
import sakura::machine;
|
||||
|
||||
# Runs a program as `sakura run` does, and gives the status it ended with. Its
|
||||
# files are read, then `core` whole, then the modules of `system` and `std` that
|
||||
# they refer to, a round at a time. The program is checked, its constants
|
||||
# evaluated, and it is lowered, optimized, and run on the machine.
|
||||
def run(files: span<strview>, core: strview, system: strview, library: strview, args: span<strview>): i32 {
|
||||
var finder := resolver::new();
|
||||
finder.whole("core", core);
|
||||
finder.add_library("system", system);
|
||||
finder.add_library("std", library);
|
||||
var paths := vector::<string>::new();
|
||||
for each in files {
|
||||
paths.append(string::from(each, nothing {}));
|
||||
}
|
||||
paths.append(string::from(builtin_path, nothing {}));
|
||||
every_file(core, &mut paths);
|
||||
for &each in paths {
|
||||
finder.mark(each.span);
|
||||
}
|
||||
|
||||
var names := names::new();
|
||||
var notes := vector::<note>::new();
|
||||
var sources := vector::<source>::new();
|
||||
var syntaxes := vector::<syntax>::new();
|
||||
var roots := vector::<u32>::new();
|
||||
# The checker refers to each source and syntax, so there is room for every
|
||||
# file the libraries hold before any is read, and none moves.
|
||||
val room := paths.length + finder.files_held();
|
||||
sources.reserve(room);
|
||||
syntaxes.reserve(room);
|
||||
for i in 0..room {
|
||||
break if i == paths.length;
|
||||
val at := paths[i].span;
|
||||
sources.append(at == builtin_path ? source::from(at, builtin_text) : source::open(at));
|
||||
syntaxes.append(syntax::new());
|
||||
var lexing := lexer::new(sources.at(i), &mut names, &mut notes, i as u32);
|
||||
lexing.tokenize_all(syntaxes.at(i));
|
||||
var parsing := parser::new(syntaxes.at(i), &names, &mut notes, i as u32);
|
||||
roots.append(parsing.parse());
|
||||
finder.refer(syntaxes.at(i), &names, &mut paths); # Adds the files it refers to.
|
||||
}
|
||||
|
||||
var checker := checker::new(&mut names, &mut notes);
|
||||
for i in 0..paths.length {
|
||||
checker.add(sources.at(i), syntaxes.at(i), roots.at(i));
|
||||
}
|
||||
checker.check();
|
||||
var results := outcomes::new();
|
||||
if notes.length == 0 {
|
||||
results = evaluate(&mut checker);
|
||||
}
|
||||
for &each in notes {
|
||||
val held := &sources.at(each.file);
|
||||
val at := held.lines.place_of(each.offset);
|
||||
println($"{held.path}:{at.line}:{at.column}: {each.code}: {each.message(held)}");
|
||||
}
|
||||
return 2 if notes.length != 0;
|
||||
|
||||
var lowered := lowerer::new(&mut checker, lowering { level = 2 });
|
||||
lowered.evaluated = move(&mut results);
|
||||
lowered.compile();
|
||||
for &each in lowered.problems {
|
||||
println(each);
|
||||
}
|
||||
return 2 if lowered.problems.length != 0;
|
||||
lowered.drop_unreached_functions();
|
||||
|
||||
var running := interpreter::new(&mut lowered, interpreting { checks = false });
|
||||
val why := running.run(args);
|
||||
return running.status if why == halt::exited;
|
||||
if why != halt::none {
|
||||
var report := string::new(nothing {});
|
||||
running.report(why, &mut report);
|
||||
print(report);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
`core` is the folder beside the `sakura` executable, and `system` and `std`, the
|
||||
layer over the operating system and the standard library, are found as `sakurac` finds
|
||||
them. The program is checked for Linux unless the checker's
|
||||
`target` is given another system.
|
||||
|
||||
## Embedding it
|
||||
|
||||
A program embeds the machine to run code it compiles as it runs, as a game runs
|
||||
its scripts. It compiles as `run` above does, lowering what it calls besides
|
||||
`main`: every function, with `lowering::everything`, or those `main` gives the
|
||||
host as values, which are kept. It then begins the program and calls its
|
||||
functions itself, which call the host's own functions in turn:
|
||||
|
||||
```sakura
|
||||
# What the program calls the host by: a foreign declaration of a name, as C's
|
||||
# are declared, which the host provides.
|
||||
# extern module game when os == windows;
|
||||
# pub def spawn_at(x: f64, y: f64): u64;
|
||||
|
||||
def spawn_at(x: f64, y: f64): u64 { ... } # the host's own
|
||||
|
||||
var running := interpreter::new(&mut lowered, interpreting{ capture = true, steps = 10000000 });
|
||||
val given: cfn<def(f64, f64): u64> = spawn_at;
|
||||
running.provide("spawn_at", given as u64); # before `begin`, or after, which replaces it
|
||||
if running.begin() != halt::none { ... } # the C it calls found, the globals given their values
|
||||
|
||||
var args: u64[2] = [state, f64_bits(0.016)]; # a word each: integers, pointers, references, a float's f64 bits
|
||||
val why := running.call(update, args[:]); # or `call_value`, given a function value's two words
|
||||
if why != halt::none {
|
||||
var report := string::new(nothing {});
|
||||
running.report(why, &mut report); # the fault, and where each function was
|
||||
}
|
||||
val got := running.result(0); # the first word it returned
|
||||
val said := running.take_output(); # what it printed
|
||||
```
|
||||
|
||||
- **Calls**: `call` calls a function by its index among the program's, given
|
||||
the words of its parameters as a call passes them: a word for each integer,
|
||||
bool, pointer, and reference, an `f64` for each float, `f32`s too, the words
|
||||
of a value held in words, and the address of the bytes of one passed in
|
||||
memory, which is copied. A result held in memory is written where `call` is
|
||||
told; one held in words is `result`'s. A function value's first word is one
|
||||
more than its function, and its second what a closure uses, which
|
||||
`call_value` takes, so a program gives its host a function as a value.
|
||||
- **The host's functions**: `provide` gives a foreign declaration's name an
|
||||
address of the host's, found before any library's, which the program calls as
|
||||
it calls C, so a `cfn` of a function of the host's own is one. A host function
|
||||
may call back into the program: that call runs above the calls under way, and
|
||||
where it faults they stop too, as the host returns to them, the trace naming
|
||||
each. The machine calls C only where the system running it is Windows.
|
||||
- **Steps**: `interpreting::steps` stops `begin`, `run`, and each call the host
|
||||
makes once it takes that many steps, jumps and calls, with `step_limit`, as a
|
||||
program looping forever would; the next call has as many again.
|
||||
- **Output**: with `interpreting::capture`, what the program writes to its
|
||||
output and error is kept for `take_output`, on Windows through `WriteFile`
|
||||
and `WriteConsoleW` too.
|
||||
- **Memory**: the program and its host share their memory, so a host may lend
|
||||
the program its own data, as a pointer, and read what the program made. What
|
||||
the program allocates the machine releases as it closes, so the host keeps no
|
||||
block of the program's past it, and the program releases none of the host's.
|
||||
|
||||
`hearth::scripting`, of hearth, embeds the machine this way.
|
||||
|
||||
## What it holds
|
||||
|
||||
- **The machine**: `interpreter`, made of a lowered program and its
|
||||
`interpreting` options. `run` calls `main` with the arguments given, and
|
||||
`begin`, `call`, and `call_value` let a host call the program's functions
|
||||
itself. The result is a `halt`: how the program stopped, as by `exit` or a
|
||||
fault, with `status` holding its exit status.
|
||||
- `report` writes a fault and where each running function was, in the same
|
||||
form as an executable's fault report.
|
||||
- With `checks`, as `run --checks` asks, each read and write through a
|
||||
reference or pointer is checked, and `report_leaks` lists the blocks
|
||||
nothing reaches. Once the program starts a thread, `races.sakura` checks
|
||||
those reads and writes for races too, ordering the threads by vector
|
||||
clocks that starting a thread and atomics' orders move, as
|
||||
ThreadSanitizer does.
|
||||
- **Compiled code**: where the machine runs as an executable on Windows or
|
||||
Linux, as `sakurac` and a host embedding it do, `jit.sakura` compiles each
|
||||
function to x86-64 the first time it is called, through the encoder in
|
||||
`x86.sakura`, and runs that rather than interpreting it. It is interpreted instead while
|
||||
constants are evaluated, where memory is checked, and where
|
||||
`interpreting::interpret` asks, as `run --interpret` does.
|
||||
- Compiled code keeps the interpreter's frames, call records, and halts, so
|
||||
compiled and interpreted functions call each other, a fault's trace is the
|
||||
same, and a host's calls, C calling back, threads, and `steps` work as they
|
||||
do interpreted.
|
||||
- Each operation becomes the instructions doing its work. The words a
|
||||
function reads and writes most, loops weighing most, are held in registers
|
||||
over the code from where each is first used to where it is last: integers
|
||||
in `rsi`, `rdi`, `r13`, and `rbp`, and reals in `xmm6` to `xmm15`, a word
|
||||
every value of which is a single's held as the single, so `f32` arithmetic
|
||||
is the processor's arithmetic of singles.
|
||||
- Calls of compiled functions are calls of the processor. A call of C whose
|
||||
arguments and result are each a word calls C directly; other calls of C,
|
||||
and what the interpreter runs rarely, as formatting, allocating, and the
|
||||
system, call the machine's own `slow_op`, as the interpreter does, through
|
||||
code keeping `xmm6` to `xmm15`, which the machine's own code does not keep.
|
||||
- Steps are counted in a register, settled with what the host allows and a
|
||||
thread's turn as they run out and around calls of the machine's own code.
|
||||
- Where the system's stack of the thread running is within 128 KiB of its
|
||||
end, calls are interpreted, which take only the machine's stack.
|
||||
- On the benchmarks of `docs/performance.md`, compiled code runs integer and
|
||||
memory work within 1.0 to 1.5 times built code's time, and `f32` work
|
||||
within 2 to 4 times, where the interpreter takes 4 to 27 times.
|
||||
- **The heap**: the blocks the program allocates and releases. With checks,
|
||||
released blocks are held back a while, so a late use still finds them
|
||||
released.
|
||||
- **Threads**: each thread of the program is a thread of the system. They take
|
||||
turns running code, so they run at the same time but not in parallel.
|
||||
- **The system and C**: the program's system calls, its environment, and its
|
||||
signals, whose handlers run at the program's safe points. On Windows, it
|
||||
calls C through code it makes that follows Microsoft's x86-64 ABI.
|
||||
- **Constants**: `evaluate` runs the program that computes a checked
|
||||
program's constants, each constant once, before the ones that read it, and
|
||||
gives the `outcomes` that lowering takes.
|
||||
|
||||
## Testing
|
||||
|
||||
From the repository's root, `blossom test` runs them as `sakura.machine.tests`, or:
|
||||
|
||||
```sh
|
||||
sakurac run --lib sakura::analyzer=analyzer --lib sakura::compiler=compiler \
|
||||
--lib sakura::machine=machine tests/main.sakura tests/machine/*.sakura
|
||||
```
|
||||
|
||||
The tests are declared within the module. Each runs a small program, written
|
||||
over a small `core` of its own, and compares what it wrote and how it stopped
|
||||
with what is expected. `sakura.machine.native` runs the same tests built as an
|
||||
executable, where the machine compiles what it runs, and the corpus,
|
||||
`sakurac.corpus`, runs every program of `tests/programs` compiled so too.
|
||||
@@ -0,0 +1,65 @@
|
||||
#! @file atomics.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the atomics the machine works on the program's memory, with
|
||||
#! `core::atomic`, so that they are atomic where processes share the memory, as
|
||||
#! the program built as an executable's are. The machine runs one thread, so it
|
||||
#! works every order as `seq_cst`, which is never weaker than what is asked.
|
||||
|
||||
import sakura::compiler;
|
||||
module sakura::machine;
|
||||
|
||||
|
||||
#! Works an atomic operation on the integer at an address.
|
||||
#! @param address The address.
|
||||
#! @param operation The operation, as `atomic_` numbers them.
|
||||
#! @param imm The access and sign, as an `atomic` instruction holds them.
|
||||
#! @param a The first operand, of a store, an exchange, or a
|
||||
#! combining operation, or what a compare-exchange expects.
|
||||
#! @param b What a compare-exchange writes.
|
||||
#! @returns What the address held, as a word the machine holds the access as.
|
||||
pub def atomically(address: u64, operation: u32, imm: u64, a: u64, b: u64): u64 {
|
||||
val signed := atomic_signed(imm);
|
||||
return match atomic_access(imm) {
|
||||
access::i8, access::u8 => signed ? atomic_on::<i8>(address, operation, a, b) : atomic_on::<u8>(address, operation, a, b),
|
||||
access::i16, access::u16 => signed ? atomic_on::<i16>(address, operation, a, b) : atomic_on::<u16>(address, operation, a, b),
|
||||
access::i32, access::u32 => signed ? atomic_on::<i32>(address, operation, a, b) : atomic_on::<u32>(address, operation, a, b),
|
||||
else => signed ? atomic_on::<i64>(address, operation, a, b) : atomic_on::<u64>(address, operation, a, b)
|
||||
};
|
||||
}
|
||||
|
||||
# Works an atomic operation on the `T` at an address, giving what it held,
|
||||
# widened to a word by its sign, as the machine holds it.
|
||||
def atomic_on<T>(address: u64, operation: u32, a: u64, b: u64): u64 where T: integer, lockfree {
|
||||
val cell := address as *mut atomic<T>;
|
||||
var got: T = 0;
|
||||
if operation == atomic_load {
|
||||
got = cell[0].load();
|
||||
} else if operation == atomic_store {
|
||||
cell[0].store(a as T);
|
||||
} else if operation == atomic_exchange {
|
||||
got = cell[0].exchange(a as T);
|
||||
} else if operation == atomic_compare_exchange {
|
||||
match cell[0].compare_exchange(a as T, b as T) {
|
||||
value(held) => got = held;
|
||||
error(held) => got = held;
|
||||
}
|
||||
} else if operation == atomic_add {
|
||||
got = cell[0].fetch_add(a as T);
|
||||
} else if operation == atomic_sub {
|
||||
got = cell[0].fetch_sub(a as T);
|
||||
} else if operation == atomic_and {
|
||||
got = cell[0].fetch_and(a as T);
|
||||
} else if operation == atomic_or {
|
||||
got = cell[0].fetch_or(a as T);
|
||||
} else if operation == atomic_xor {
|
||||
got = cell[0].fetch_xor(a as T);
|
||||
} else if operation == atomic_min {
|
||||
got = cell[0].fetch_min(a as T);
|
||||
} else {
|
||||
got = cell[0].fetch_max(a as T);
|
||||
}
|
||||
return (got as i64) as u64;
|
||||
}
|
||||
@@ -0,0 +1,660 @@
|
||||
#! @file evaluation.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains constant evaluation, which runs while a program is checked: the
|
||||
#! checker asks for what only running gives, as a local constant, an array's
|
||||
#! length a function gives, the condition of an `if const`, or the text of a
|
||||
#! `compile_error`, and the program computing it is lowered and run in the
|
||||
#! machine there and then. One lowerer and one machine live through checking,
|
||||
#! so what one evaluation lowers is lowered once for all of them. Once the
|
||||
#! program checks, the global constants it reached that nothing asked for, but
|
||||
#! that it holds as data, are evaluated too.
|
||||
#!
|
||||
#! Each evaluation runs from its start. Reading a constant not yet evaluated
|
||||
#! stops it, so that constant is evaluated first and the run begins again. A
|
||||
#! constant keeps its value, and the memory it points into, which the program
|
||||
#! is given as data; what a run allocated and the value does not keep must have
|
||||
#! been released, since nothing of the program would hold it. What goes wrong is
|
||||
#! noted at what asked for it, as the checker notes what it finds.
|
||||
|
||||
import sakura::analyzer;
|
||||
import sakura::compiler;
|
||||
module sakura::machine;
|
||||
|
||||
|
||||
#! How far each evaluation got.
|
||||
enum progress : u8 {
|
||||
pending, #! Not run yet.
|
||||
running, #! Running, or waiting for another it reads.
|
||||
done, #! Done, its value kept.
|
||||
failed, #! Stopped, which was noted.
|
||||
}
|
||||
|
||||
#! How deeply constants may depend on one another, and values point into
|
||||
#! memory pointing into memory.
|
||||
const deepest_chain: u64 = 256;
|
||||
|
||||
#! The steps, as jumps and calls, each run of an evaluation may take.
|
||||
const evaluation_budget: u64 = 16777216;
|
||||
|
||||
#! What evaluates while a program is checked: a lowerer of the program
|
||||
#! evaluating and a machine running what it lowers, and what each evaluation
|
||||
#! worked out.
|
||||
pub struct compile_time : owning {
|
||||
var lowered: &mut lowerer; #! The lowerer of the program evaluating.
|
||||
var running: interpreter; #! The machine running it.
|
||||
var states: vector<progress>; #! How far each evaluation got.
|
||||
pub var outcomes: outcomes; #! What was worked out.
|
||||
}
|
||||
|
||||
#! Makes what evaluates while a program is checked.
|
||||
#! @param lowered The lowerer of the program evaluating, made of the checker.
|
||||
#! @returns What evaluates.
|
||||
pub def compile_time::new(lowered: &mut lowerer): compile_time {
|
||||
return compile_time {
|
||||
lowered = lowered,
|
||||
running = interpreter::new(lowered, interpreting { evaluating = true }),
|
||||
states = vector::<progress>::new(),
|
||||
outcomes = outcomes::new()
|
||||
};
|
||||
}
|
||||
|
||||
#! Gives back what the machine holds.
|
||||
#! @param this What evaluates.
|
||||
pub def compile_time::close(&mut this): void {
|
||||
this.running.close();
|
||||
this.states.close();
|
||||
}
|
||||
|
||||
#! Checks a program, evaluating what checking asks for as it goes, then the
|
||||
#! global constants it reached that the program holds as data.
|
||||
#! @param checker The checker, given the program's files.
|
||||
#! @param runs Whether the program may be run, which one whose files did
|
||||
#! not parse may not, so checking evaluates nothing.
|
||||
#! @returns What was worked out.
|
||||
#! @remarks The checker holds a function referring to what evaluates only while
|
||||
#! it checks, and is given none again before it ends, which its
|
||||
#! lifetime warning cannot see.
|
||||
@allow
|
||||
pub def check_evaluating(checker: &mut checker, runs: bool = true): outcomes {
|
||||
return checked_alone(checker) if !runs;
|
||||
var lowered := lowerer::new(checker, lowering { verify = true, evaluating = true });
|
||||
var timing := compile_time::new(&mut lowered);
|
||||
checker.evaluator = def(ask: &evaluation_ask, out: &mut evaluation_answer): void {
|
||||
timing.answer(ask, out);
|
||||
};
|
||||
checker.check();
|
||||
if !checker.failed {
|
||||
timing.finish();
|
||||
}
|
||||
checker.evaluator = nothing {};
|
||||
return move(&mut timing.outcomes);
|
||||
}
|
||||
|
||||
# Checks a program that is not run, which evaluates nothing.
|
||||
def checked_alone(checker: &mut checker): outcomes {
|
||||
checker.check();
|
||||
return outcomes::new();
|
||||
}
|
||||
|
||||
#! Works out what the checker asks for: lowers the program computing it, and
|
||||
#! what that calls, loads what is new into the machine, and runs it.
|
||||
#! @param this What evaluates.
|
||||
#! @param ask What is asked for.
|
||||
#! @param out Where the answer is written: the value, where it is one a
|
||||
#! constant holds, or the text, and whether a note was made of
|
||||
#! what went wrong.
|
||||
pub def compile_time::answer(&mut this, ask: &evaluation_ask, out: &mut evaluation_answer): void {
|
||||
val key := node_key(ask.table, ask.node);
|
||||
val index := this.lowered.evaluation_of(key, 0, ask.table, ask.node, ask.what == evaluation_kind::condition, ask.what == evaluation_kind::value);
|
||||
out.noted = true;
|
||||
val ran := this.run(index);
|
||||
return if !ran;
|
||||
|
||||
out.worked = true;
|
||||
out.noted = false;
|
||||
val held: evaluation = this.lowered.evaluations[index];
|
||||
if held.condition {
|
||||
out.scalar = true;
|
||||
out.value = constant::truth(this.outcomes.decisions.get(&key) is some(holds) && holds);
|
||||
} else if held.text {
|
||||
if this.outcomes.texts.get(&key) is some(&text) {
|
||||
out.text = string::copy_of(&text);
|
||||
}
|
||||
} else if this.lowered.is_scalar_type(held.kind) && this.outcomes.values.get(&key) is some(&value) {
|
||||
out.scalar = true;
|
||||
out.value = this.lowered.constant_of(value.bytes.span, held.kind);
|
||||
}
|
||||
}
|
||||
|
||||
#! Evaluates the global constants the program reached and nothing asked for,
|
||||
#! and the instances of those of generic types, whose values the program holds
|
||||
#! as data.
|
||||
#! @param this What evaluates.
|
||||
pub def compile_time::finish(&mut this): void {
|
||||
for id in 1..this.lowered.checker.decls.count {
|
||||
val decl := id as u32;
|
||||
continue if !this.lowered.checker.decls.has(decl, df::checked) || !this.lowered.needs_evaluation(decl);
|
||||
_ = this.run(this.lowered.evaluation_of(decl_key(decl), decl, 0, 0, false, false));
|
||||
}
|
||||
# So are the instances of constants of generic types, as local constants are.
|
||||
for i in 1..this.lowered.checker.instances.length {
|
||||
continue if !this.lowered.needs_instance_evaluation(i as u32);
|
||||
val held: instance = this.lowered.checker.instances[i];
|
||||
val node: u32 = this.lowered.checker.decls.nodes.p[held.decl];
|
||||
_ = this.run(this.lowered.evaluation_of(node_key(held.table, node), 0, held.table, node, false, false));
|
||||
}
|
||||
}
|
||||
|
||||
#! Lowers an evaluation and what it calls, loads what is new into the machine,
|
||||
#! and runs it, noting what goes wrong.
|
||||
#! @param this What evaluates.
|
||||
#! @param index The evaluation.
|
||||
#! @returns Whether it was worked out.
|
||||
def compile_time::run(&mut this, index: u32): bool {
|
||||
val problems := this.lowered.problems.length;
|
||||
this.lowered.drain();
|
||||
this.lowered.fill_retraits();
|
||||
this.lowered.drain();
|
||||
this.states.resize(this.lowered.evaluations.length);
|
||||
if this.lowered.problems.length != problems {
|
||||
# What checking what lowering reached found was noted where it was.
|
||||
if !this.lowered.checker.failed {
|
||||
for i in problems..this.lowered.problems.length {
|
||||
var text := string::from("Evaluating could not lower this program: ", nothing {});
|
||||
text.append(this.lowered.problems[i].span);
|
||||
this.lowered.report_evaluation(index, &mut text);
|
||||
}
|
||||
}
|
||||
this.states[index] = progress::failed;
|
||||
return false;
|
||||
}
|
||||
if !this.running.refresh() {
|
||||
var text := string::from("Evaluating holds more globals than the machine has room for while checking.", nothing {});
|
||||
this.lowered.report_evaluation(index, &mut text);
|
||||
this.states[index] = progress::failed;
|
||||
return false;
|
||||
}
|
||||
return this.running.evaluate_one(index, 0, &mut this.states, &mut this.outcomes);
|
||||
}
|
||||
|
||||
#! The constant a value of a number, `bool`, character, or enum is, from the
|
||||
#! bytes evaluating kept of it.
|
||||
#! @param this The compiler.
|
||||
#! @param bytes The bytes.
|
||||
#! @param kind Its type.
|
||||
#! @returns The constant.
|
||||
pub def lowerer::constant_of(&mut this, bytes: span<u8>, kind: u32): constant {
|
||||
var plain := this.checker.unalias(kind);
|
||||
if this.checker.named_kind(plain) == dk::enum_type {
|
||||
plain = this.checker.unalias(this.checker.decls.targets.p[this.checker.types.first_of(plain)]);
|
||||
}
|
||||
var raw: u64 = 0;
|
||||
val size := bytes.length < 8 ? bytes.length : 8;
|
||||
for i in 0..size {
|
||||
raw |= (bytes[i] as u64) << (8 * i as u64);
|
||||
}
|
||||
return constant::truth((raw & 0xFF) != 0) if this.checker.types.is_boolean(plain);
|
||||
if this.checker.types.is_float(plain) {
|
||||
if size == 4 {
|
||||
var narrow := raw as u32;
|
||||
return constant::real_of(((&mut narrow) as *mut f32)[0] as f64);
|
||||
}
|
||||
var wide := raw;
|
||||
return constant::real_of(((&mut wide) as *mut f64)[0]);
|
||||
}
|
||||
val signed := this.checker.types.is_signed(plain);
|
||||
if signed && size < 8 && size != 0 && (raw >> (8 * size as u64 - 1)) != 0 {
|
||||
raw |= ~((1u << (8 * size as u64)) - 1);
|
||||
}
|
||||
return constant::from_bits(raw, signed);
|
||||
}
|
||||
|
||||
#! Notes what went wrong evaluating, at the constant or condition.
|
||||
#! @param this The compiler of the program evaluating.
|
||||
#! @param index The evaluation, or `none` for none in particular.
|
||||
#! @param text What the note says.
|
||||
pub def lowerer::report_evaluation(&mut this, index: u32, text: &mut string): void {
|
||||
val saved := this.checker.at;
|
||||
var file: u32 = 0;
|
||||
var node: u32 = 0;
|
||||
if (index as u64) < this.evaluations.length {
|
||||
val held: evaluation = this.evaluations[index];
|
||||
if held.decl != 0 {
|
||||
file = this.checker.decls.files.p[held.decl];
|
||||
node = this.checker.decls.nodes.p[held.decl];
|
||||
} else {
|
||||
file = this.checker.tables.p[held.table].file;
|
||||
node = held.node;
|
||||
}
|
||||
}
|
||||
this.checker.at.instance = 0;
|
||||
this.checker.report_in(file, node, ec::constant, text.span);
|
||||
this.checker.at = saved;
|
||||
}
|
||||
|
||||
#! What a note names an evaluation as: a constant by its name, or the
|
||||
#! condition of `if const`.
|
||||
#! @param this The compiler.
|
||||
#! @param index The evaluation.
|
||||
#! @returns The name.
|
||||
def lowerer::evaluation_name(&mut this, index: u32): string {
|
||||
val held: evaluation = this.evaluations[index];
|
||||
return string::from("the condition of `if const`", nothing {}) if held.condition;
|
||||
return string::from("the text of `compile_error`", nothing {}) if held.text;
|
||||
return $"`{this.program.functions[held.function].name}`";
|
||||
}
|
||||
|
||||
#! Evaluates one constant or condition, evaluating first those its run stops
|
||||
#! at, and keeps what it worked out.
|
||||
#! @param this The machine.
|
||||
#! @param index The evaluation.
|
||||
#! @param depth How many evaluations wait for it.
|
||||
#! @param states How far each evaluation got.
|
||||
#! @param out Where what is worked out is kept.
|
||||
#! @returns Whether it was evaluated.
|
||||
def interpreter::evaluate_one(&mut this, index: u32, depth: u64, states: &mut vector<progress>, out: &mut outcomes): bool {
|
||||
val state: progress = states[index];
|
||||
return state == progress::done if state == progress::done || state == progress::failed;
|
||||
if depth > deepest_chain {
|
||||
var text := string::from("Constants depend on one another too deeply to evaluate.", nothing {});
|
||||
this.c.report_evaluation(index, &mut text);
|
||||
states[index] = progress::failed;
|
||||
return false;
|
||||
}
|
||||
|
||||
states[index] = progress::running;
|
||||
val held: evaluation = this.c.evaluations[index];
|
||||
var kept := evaluated {
|
||||
bytes = vector::<u8>::new(),
|
||||
addresses = vector::<kept_address>::new(),
|
||||
blocks = vector::<kept_block>::new()
|
||||
};
|
||||
while true {
|
||||
this.budget = evaluation_budget;
|
||||
val why := this.invoke(held.function, span::<u64>::blank());
|
||||
|
||||
# A run that finished keeps its value before anything is released, since
|
||||
# the memory the value points into is memory the run still holds.
|
||||
if why == halt::none && !held.condition {
|
||||
if !this.keep_value(index, &mut kept) {
|
||||
this.release_unkept();
|
||||
states[index] = progress::failed;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
# What a run allocated and its value does not keep, nothing of the program
|
||||
# holds once it is done.
|
||||
val leaked := this.release_unkept();
|
||||
if why == halt::none && leaked != 0 {
|
||||
var text := $"Evaluating {this.c.evaluation_name(index)} allocated memory it neither released nor kept, {leaked} block";
|
||||
text.append(leaked == 1 ? "" : "s");
|
||||
text.append(" of it, which only a running program could hold.");
|
||||
this.c.report_evaluation(index, &mut text);
|
||||
states[index] = progress::failed;
|
||||
return false;
|
||||
}
|
||||
break if why == halt::none;
|
||||
|
||||
# A constant it reads is evaluated first, then it runs again from its start.
|
||||
if why == halt::not_evaluated && (this.waiting as u64) < states.length {
|
||||
if states[this.waiting] == progress::running {
|
||||
var text := $"{this.c.evaluation_name(index)} depends on its own value, through the constants it reads.";
|
||||
this.c.report_evaluation(index, &mut text);
|
||||
states[index] = progress::failed;
|
||||
return false;
|
||||
}
|
||||
if !this.evaluate_one(this.waiting, depth + 1, states, out) {
|
||||
states[index] = progress::failed;
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
var text := $"Evaluating {this.c.evaluation_name(index)} stopped: {this.why_text(why)}";
|
||||
for &each in this.trace {
|
||||
text.append($"\n at {each.function} ({each.path}:{each.line}:{each.column})");
|
||||
}
|
||||
this.c.report_evaluation(index, &mut text);
|
||||
this.fault_text.clear();
|
||||
states[index] = progress::failed;
|
||||
return false;
|
||||
}
|
||||
|
||||
# A constant keeps its value, a condition whether it holds, and text what
|
||||
# it says, read through the memory its value kept.
|
||||
if held.condition {
|
||||
val word := ((this.globals as u64 + held.offset) as *u8)[0];
|
||||
out.decisions.set(held.key, word != 0);
|
||||
} else if held.text {
|
||||
out.texts.set(held.key, this.text_at(this.globals as u64 + held.offset, held.kind));
|
||||
} else {
|
||||
out.values.set(held.key, move(&mut kept));
|
||||
}
|
||||
this.ready[index] = true;
|
||||
states[index] = progress::done;
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The text a value holds, as a `strview` or a `string` does, copied from where
|
||||
#! its bytes are.
|
||||
#! @param this The machine.
|
||||
#! @param at Where the value is.
|
||||
#! @param kind Its type.
|
||||
#! @returns The text, or empty text where the value holds none.
|
||||
def interpreter::text_at(&mut this, at: u64, kind: u32): string {
|
||||
var made := string::new(nothing {});
|
||||
val layout := this.c.layout_of(kind);
|
||||
val shape := this.c.layout_at(layout);
|
||||
return made if !shape.texts;
|
||||
val begins := this.c.field_at(layout, shape.text);
|
||||
val many := this.c.field_at(layout, shape.text + 1);
|
||||
val data := ((at + begins.offset) as *u64)[0];
|
||||
if data != 0 {
|
||||
made.append(span::<u8>::over(data as *u8, ((at + many.offset) as *u64)[0]));
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Releases the blocks a run allocated that no value evaluated keeps.
|
||||
#! @param this The machine.
|
||||
#! @returns How many were released.
|
||||
def interpreter::release_unkept(&mut this): u64 {
|
||||
var gone := vector::<u64>::new();
|
||||
for &entry in this.blocks {
|
||||
if !this.kept.contains(&entry.key) {
|
||||
gone.append(entry.key);
|
||||
}
|
||||
}
|
||||
for &each in gone {
|
||||
this.release(each);
|
||||
}
|
||||
return gone.length;
|
||||
}
|
||||
|
||||
#! What keeping a value finds: the units of memory it reaches, the value first.
|
||||
struct keeping {
|
||||
var units: vector<kept_block>; #! The value, then each block of memory it points into.
|
||||
var bases: vector<u64>; #! Where each unit's memory was, so memory reached twice is kept once.
|
||||
var blocks: vector<bool>; #! Whether each unit is memory the run allocated.
|
||||
var failed: bool; #! Whether the value cannot be kept, which was noted.
|
||||
}
|
||||
|
||||
#! Keeps the value an evaluation computed: its bytes, laid out as its type is,
|
||||
#! with the memory it points into.
|
||||
#! @param this The machine.
|
||||
#! @param index The evaluation.
|
||||
#! @param out Where the value is kept.
|
||||
#! @returns Whether it could be, which a note says where it could not.
|
||||
def interpreter::keep_value(&mut this, index: u32, out: &mut evaluated): bool {
|
||||
val held: evaluation = this.c.evaluations[index];
|
||||
val layout := this.c.layout_of(held.kind);
|
||||
val size := this.c.layout_at(layout).size;
|
||||
var work := keeping {
|
||||
units = vector::<kept_block>::new(),
|
||||
bases = vector::<u64>::new(),
|
||||
blocks = vector::<bool>::new()
|
||||
};
|
||||
this.add_unit(&mut work, this.globals as u64 + held.offset, size, 0, false);
|
||||
this.walk(index, &mut work, 0, 0, layout, 0);
|
||||
return false if work.failed;
|
||||
|
||||
# Addresses name the blocks past the value, which is not one of them.
|
||||
for &mut unit in work.units {
|
||||
for &mut each in unit.addresses {
|
||||
if each.block != no_block && each.block != in_constant {
|
||||
each.block = each.block - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.bytes = move(&mut work.units[0].bytes);
|
||||
out.addresses = move(&mut work.units[0].addresses);
|
||||
out.blocks.clear();
|
||||
for u in 1..work.units.length {
|
||||
out.blocks.append(move(&mut work.units[u]));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Adds a unit holding a copy of memory.
|
||||
#! @param this The machine.
|
||||
#! @param work What keeping found so far.
|
||||
#! @param from Where the memory is.
|
||||
#! @param size How many bytes it holds.
|
||||
#! @param base Where it begins, so memory reached twice is kept once, or 0.
|
||||
#! @param block Whether it is memory the run allocated.
|
||||
#! @returns The unit's index.
|
||||
def interpreter::add_unit(&mut this, work: &mut keeping, from: u64, size: u64, base: u64, block: bool): u32 {
|
||||
var bytes := vector::<u8>::new();
|
||||
bytes.resize(size);
|
||||
if size != 0 {
|
||||
memcpy(bytes.slice.data, from as *u8, size);
|
||||
}
|
||||
work.units.append(kept_block { bytes = move(&mut bytes), addresses = vector::<kept_address>::new() });
|
||||
work.bases.append(base);
|
||||
work.blocks.append(block);
|
||||
return (work.units.length - 1) as u32;
|
||||
}
|
||||
|
||||
#! Notes that a value holds the address of memory only the compiler has.
|
||||
#! @param this The machine.
|
||||
#! @param index The evaluation.
|
||||
#! @param work What keeping found so far.
|
||||
def interpreter::escaped(&mut this, index: u32, work: &mut keeping): void {
|
||||
return if work.failed;
|
||||
work.failed = true;
|
||||
var text := this.c.evaluation_name(index);
|
||||
text.append(" holds the address of memory only the compiler has, such as a variable of the value being computed or memory already released, which goes away once it has run. A constant keeps the memory it allocated and still holds, and the bytes of text, which the program is given again.");
|
||||
this.c.report_evaluation(index, &mut text);
|
||||
}
|
||||
|
||||
#! Whether values of a layout hold addresses, so their bytes are walked rather
|
||||
#! than simply kept.
|
||||
#! @param this The machine.
|
||||
#! @param layout The layout.
|
||||
#! @param depth How deeply within values it is.
|
||||
#! @returns Whether they do.
|
||||
def interpreter::holds_addresses(&mut this, layout: u32, depth: u64): bool {
|
||||
return false if depth > deepest_chain;
|
||||
val shape := this.c.layout_at(layout);
|
||||
return match shape.kind {
|
||||
lk::pointer, lk::reference, lk::trait_reference, lk::function => true,
|
||||
lk::fixed => this.holds_addresses(shape.element - 1, depth + 1),
|
||||
lk::record, lk::variant => this.fields_hold_addresses(layout, &shape, depth),
|
||||
else => false
|
||||
};
|
||||
}
|
||||
|
||||
#! Whether any field of a struct or union holds addresses.
|
||||
#! @param this The machine.
|
||||
#! @param layout The layout.
|
||||
#! @param shape The layout itself.
|
||||
#! @param depth How deeply within values it is.
|
||||
#! @returns Whether any does.
|
||||
def interpreter::fields_hold_addresses(&mut this, layout: u32, shape: &layout, depth: u64): bool {
|
||||
for i in 0..shape.count {
|
||||
val field := this.c.field_at(layout, i as u32);
|
||||
return true if this.holds_addresses(field.layout, depth + 1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Walks bytes of a unit laid out as a layout, keeping the memory each address
|
||||
#! within them points into, and noting where each address is.
|
||||
#! @param this The machine.
|
||||
#! @param index The evaluation.
|
||||
#! @param work What keeping found so far.
|
||||
#! @param unit The unit.
|
||||
#! @param at Where the value is within it.
|
||||
#! @param layout The value's layout.
|
||||
#! @param depth How deeply within values it is.
|
||||
def interpreter::walk(&mut this, index: u32, work: &mut keeping, unit: u32, at: u64, layout: u32, depth: u64): void {
|
||||
return if work.failed;
|
||||
if depth > deepest_chain {
|
||||
work.failed = true;
|
||||
var text := string::from("The value points into memory that points into memory too deeply to keep.", nothing {});
|
||||
this.c.report_evaluation(index, &mut text);
|
||||
return;
|
||||
}
|
||||
|
||||
val shape := this.c.layout_at(layout);
|
||||
val bytes := work.units[unit].bytes.span.data;
|
||||
match shape.kind {
|
||||
lk::pointer, lk::reference => {
|
||||
val word := ((bytes as u64 + at) as *u64)[0];
|
||||
return if word == 0;
|
||||
var addend: u64 = 0;
|
||||
|
||||
# Another constant's value is data of the program already, so an address
|
||||
# into it is kept as one into that data, which keeps nothing more.
|
||||
var other: u32 = 0;
|
||||
if this.constant_at(index, word, &mut other, &mut addend) {
|
||||
val held: evaluation = this.c.evaluations[other];
|
||||
work.units[unit].addresses.append(kept_address {
|
||||
at = at, block = in_constant, addend = addend, decl = held.decl, table = held.table, node = held.node
|
||||
});
|
||||
return;
|
||||
}
|
||||
val target := this.promote(index, work, word, shape.element, depth, &mut addend);
|
||||
return if work.failed;
|
||||
work.units[unit].addresses.append(kept_address { at = at, block = target, addend = addend });
|
||||
}
|
||||
# A trait reference holds a vtable of the program evaluating, and a function
|
||||
# value a closure's locals, neither of which outlives the run.
|
||||
lk::trait_reference => this.escaped(index, work);
|
||||
lk::function => {
|
||||
val function := ((bytes as u64 + at) as *u64)[0];
|
||||
if ((bytes as u64 + at + word_size) as *u64)[0] != 0 {
|
||||
this.escaped(index, work);
|
||||
return;
|
||||
}
|
||||
return if function == 0 || function - 1 >= this.c.program.functions.length;
|
||||
val named := &this.c.program.functions[function - 1];
|
||||
var made := kept_address { at = at, block = no_block, decl = named.decl, instance = named.instance };
|
||||
if named.decl == 0 {
|
||||
made.table = named.table;
|
||||
made.node = named.node;
|
||||
made.file = named.file;
|
||||
}
|
||||
work.units[unit].addresses.append(made);
|
||||
}
|
||||
lk::fixed => {
|
||||
val size := this.c.layout_at(shape.element - 1).size;
|
||||
for i in 0..shape.count {
|
||||
this.walk(index, work, unit, at + i as u64 * size, shape.element - 1, depth + 1);
|
||||
}
|
||||
}
|
||||
lk::record => {
|
||||
for i in 0..shape.count {
|
||||
val field := this.c.field_at(layout, i as u32);
|
||||
this.walk(index, work, unit, at + field.offset, field.layout, depth + 1);
|
||||
}
|
||||
}
|
||||
lk::variant => {
|
||||
# A union holds the one its tag gives, and the bytes of the rest mean nothing.
|
||||
val tag := held_field(&shape, ((bytes as u64 + at) as *u64)[0]);
|
||||
if tag < shape.count as u64 {
|
||||
val field := this.c.field_at(layout, tag as u32);
|
||||
this.walk(index, work, unit, at + field.offset, field.layout, depth + 1);
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether an address points into the value of another constant, one evaluated
|
||||
#! already, giving which and how far into it, where it does. An address just
|
||||
#! past the end of one, as an empty view's may be, is of that one where no value
|
||||
#! holds it.
|
||||
#! @param this The machine.
|
||||
#! @param index The evaluation whose value holds the address.
|
||||
#! @param address The address.
|
||||
#! @param found Where the constant's evaluation is written.
|
||||
#! @param addend Where how far into its value the address points is written.
|
||||
#! @returns Whether it does.
|
||||
def interpreter::constant_at(&mut this, index: u32, address: u64, found: &mut u32, addend: &mut u64): bool {
|
||||
var past := false;
|
||||
for i in 0..this.c.evaluations.length {
|
||||
continue if i == index as u64 || !this.ready[i];
|
||||
val other: evaluation = this.c.evaluations[i];
|
||||
continue if other.condition;
|
||||
val base := this.globals as u64 + other.offset;
|
||||
val size := this.c.layout_at(this.c.layout_of(other.kind)).size;
|
||||
if address >= base && address < base + size {
|
||||
found = i as u32;
|
||||
addend = address - base;
|
||||
return true;
|
||||
}
|
||||
if !past && address == base + size && size != 0 {
|
||||
found = i as u32;
|
||||
addend = size;
|
||||
past = true;
|
||||
}
|
||||
}
|
||||
return past;
|
||||
}
|
||||
|
||||
#! Keeps the memory an address points into, giving the unit it became and how
|
||||
#! far into it the address points: memory the run allocated and still holds,
|
||||
#! which stays held for the rest of the evaluating, or the bytes of a datum.
|
||||
#! Memory anywhere else is the compiler's own, which is noted.
|
||||
#! @param this The machine.
|
||||
#! @param index The evaluation.
|
||||
#! @param work What keeping found so far.
|
||||
#! @param address The address.
|
||||
#! @param element One more than the layout of what it points at, or 0.
|
||||
#! @param depth How deeply within values it is.
|
||||
#! @param addend Where how far into the memory it points is written.
|
||||
#! @returns The unit.
|
||||
def interpreter::promote(&mut this, index: u32, work: &mut keeping, address: u64, element: u32, depth: u64, addend: &mut u64): u32 {
|
||||
var base: u64 = 0;
|
||||
var size: u64 = 0;
|
||||
var block := false;
|
||||
for &entry in this.blocks {
|
||||
if address >= entry.key && address < entry.key + entry.value + 1 {
|
||||
base = entry.key;
|
||||
size = entry.value;
|
||||
block = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !block {
|
||||
for i in 0..this.data.length {
|
||||
val data: u64 = this.data[i];
|
||||
val length := this.c.program.data[i].bytes.length;
|
||||
if address >= data && address < data + length {
|
||||
base = data;
|
||||
size = length == 0 ? 0 : length - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if base == 0 {
|
||||
this.escaped(index, work);
|
||||
return 0;
|
||||
}
|
||||
|
||||
addend = address - base;
|
||||
for u in 1..work.units.length {
|
||||
return u as u32 if work.bases[u] == base;
|
||||
}
|
||||
val unit := this.add_unit(work, base, size, base, block);
|
||||
if block {
|
||||
this.kept.set(base, true);
|
||||
}
|
||||
|
||||
# What the memory holds is read as a run of the elements the address gives,
|
||||
# since memory of no elements, as that of text, holds no addresses.
|
||||
return unit if element == 0;
|
||||
val shape := this.c.layout_at(element - 1);
|
||||
return unit if shape.size == 0 || !this.holds_addresses(element - 1, 0);
|
||||
var at: u64 = 0;
|
||||
while at + shape.size <= size && !work.failed {
|
||||
this.walk(index, work, unit, at, element - 1, depth + 1);
|
||||
at += shape.size;
|
||||
}
|
||||
return unit;
|
||||
}
|
||||
@@ -0,0 +1,846 @@
|
||||
#! @file foreign.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how the machine calls C, where the system running it is Windows, as
|
||||
#! the C machine calls C there: with Microsoft's ABI of x86-64. A program
|
||||
#! checked for Windows reaches the system through C, as `system` does there,
|
||||
#! so the machine must call C to run it.
|
||||
#!
|
||||
#! C only calls an address, so the machine makes code of its own that a call of
|
||||
#! C goes through: it loads the arguments the frame holds into the registers and
|
||||
#! the stack as the ABI wants, calls the C function, and keeps the result. The
|
||||
#! code is made once, in memory that is then only executed, and every signature
|
||||
#! is called through the one block of code, since Microsoft's ABI is positional:
|
||||
#! each of the first four arguments is loaded into both the integer register and
|
||||
#! the SSE register of its position, so a float or an integer is where C reads
|
||||
#! it either way.
|
||||
#!
|
||||
#! The libraries a program links are opened, and the C functions it calls by
|
||||
#! name found, before it runs, in the library their file's `extern import` names,
|
||||
#! or among what the machine's own process has where it names none. A library and a function
|
||||
#! that cannot be found stop the program before it starts, at the declaration.
|
||||
#!
|
||||
#! Other threads run while C does, which C may wait for, so the machine lets go
|
||||
#! of its turn around a call of C, as it does around a call of the system. Each
|
||||
#! thread keeps what the last C function it called left for `GetLastError`, since
|
||||
#! the machine's own work between a program's calls of C may leave another.
|
||||
|
||||
import std::containers;
|
||||
import std::io;
|
||||
import system;
|
||||
import sakura::compiler;
|
||||
import system::windows;
|
||||
|
||||
module sakura::machine;
|
||||
|
||||
|
||||
when os == windows {
|
||||
# How a call reads the arguments the frame holds and writes back the result.
|
||||
# Its words are at offsets the code a call goes through is written with, so
|
||||
# its layout is kept as it is: a word, then four words, then four words, then
|
||||
# a word, a word, and four words.
|
||||
struct c_call {
|
||||
var function: u64; #! The C function called.
|
||||
var integers: u64[4]; #! The argument of each position, as an integer.
|
||||
var floats: u64[4]; #! The argument of each position, as a float.
|
||||
var stack: u64; #! The arguments past the fourth, which the code copies to the stack.
|
||||
var words: u64; #! How many.
|
||||
var results: u64[4]; #! What C left in `rax`, `rdx`, `xmm0`, and `xmm1`.
|
||||
}
|
||||
|
||||
# The memory a call's stubs are committed in is read, written, then executed.
|
||||
const page_commit: u32 = 0x3000; #! `MEM_COMMIT | MEM_RESERVE`.
|
||||
const page_release: u32 = 0x8000; #! `MEM_RELEASE`.
|
||||
const page_write: u32 = 0x04; #! `PAGE_READWRITE`.
|
||||
const page_execute: u32 = 0x20; #! `PAGE_EXECUTE_READ`.
|
||||
|
||||
# The code a call of C goes through: it takes the arguments a `c_call` holds,
|
||||
# calls the C function at `function`, and writes the result back to `results`.
|
||||
# The pointer to the `c_call` is in `rcx`, as the first argument is. The
|
||||
# callee-saved registers Windows has C keep, `rbx`, `rsi`, and `rdi`, are kept,
|
||||
# and `rsi` and `rdi` copy the stack. The stack is aligned to 16 bytes, with
|
||||
# the 32 bytes C may keep its register arguments in left below the arguments.
|
||||
const call_stub_code: u8[137] = [
|
||||
0x55, 0x53, 0x56, 0x57, # push rbp; push rbx; push rsi; push rdi
|
||||
0x48, 0x89, 0xE5, # mov rbp, rsp
|
||||
0x48, 0x89, 0xCB, # mov rbx, rcx
|
||||
0x48, 0x8B, 0x4B, 0x50, # mov rcx, [rbx+80] ; words
|
||||
0x48, 0x89, 0xC8, # mov rax, rcx
|
||||
0x48, 0xC1, 0xE0, 0x03, # shl rax, 3
|
||||
0x48, 0x29, 0xC4, # sub rsp, rax
|
||||
0x48, 0x83, 0xE4, 0xF0, # and rsp, -16
|
||||
0x48, 0x8B, 0x73, 0x48, # mov rsi, [rbx+72] ; stack
|
||||
0x48, 0x89, 0xE7, # mov rdi, rsp
|
||||
0x48, 0xC1, 0xE1, 0x03, # shl rcx, 3
|
||||
0xF3, 0xA4, # rep movsb
|
||||
0x48, 0x83, 0xEC, 0x20, # sub rsp, 32 ; the bytes C may keep registers in
|
||||
0x48, 0x8B, 0x43, 0x28, 0x66, 0x48, 0x0F, 0x6E, 0xC0, # mov rax,[rbx+40]; movq xmm0, rax
|
||||
0x48, 0x8B, 0x43, 0x30, 0x66, 0x48, 0x0F, 0x6E, 0xC8, # mov rax,[rbx+48]; movq xmm1, rax
|
||||
0x48, 0x8B, 0x43, 0x38, 0x66, 0x48, 0x0F, 0x6E, 0xD0, # mov rax,[rbx+56]; movq xmm2, rax
|
||||
0x48, 0x8B, 0x43, 0x40, 0x66, 0x48, 0x0F, 0x6E, 0xD8, # mov rax,[rbx+64]; movq xmm3, rax
|
||||
0x48, 0x8B, 0x4B, 0x08, # mov rcx, [rbx+8]
|
||||
0x48, 0x8B, 0x53, 0x10, # mov rdx, [rbx+16]
|
||||
0x4C, 0x8B, 0x43, 0x18, # mov r8, [rbx+24]
|
||||
0x4C, 0x8B, 0x4B, 0x20, # mov r9, [rbx+32]
|
||||
0x4C, 0x8B, 0x1B, # mov r11, [rbx] ; function
|
||||
0x41, 0xFF, 0xD3, # call r11
|
||||
0x48, 0x89, 0x43, 0x58, # mov [rbx+88], rax
|
||||
0x48, 0x89, 0x53, 0x60, # mov [rbx+96], rdx
|
||||
0x66, 0x48, 0x0F, 0x7E, 0xC0, # movq rax, xmm0
|
||||
0x48, 0x89, 0x43, 0x68, # mov [rbx+104], rax
|
||||
0x66, 0x48, 0x0F, 0x7E, 0xC8, # movq rax, xmm1
|
||||
0x48, 0x89, 0x43, 0x70, # mov [rbx+112], rax
|
||||
0x48, 0x89, 0xEC, # mov rsp, rbp
|
||||
0x5F, 0x5E, 0x5B, 0x5D, # pop rdi; pop rsi; pop rbx; pop rbp
|
||||
0xC3 # ret
|
||||
];
|
||||
|
||||
# Writes text of ASCII, zero at its end, as C reads a name.
|
||||
# @param text The text.
|
||||
# @param into Where it is written, long enough for its bytes and a zero.
|
||||
def c_name(text: strview, into: *mut u8): void {
|
||||
for i in 0..text.length {
|
||||
into[i] = text[i];
|
||||
}
|
||||
into[text.length] = 0;
|
||||
}
|
||||
|
||||
# Writes text of UTF-8 as UTF-16, zero at its end, as C reads a wide name.
|
||||
# @param text The text.
|
||||
# @param into Where it is written.
|
||||
# @param cap How many units it holds.
|
||||
# @returns Whether it fit.
|
||||
def wide_name(text: strview, into: *mut u16, cap: i32): bool {
|
||||
val count := MultiByteToWideChar(65001, 0, text.data, text.length as i32, into, cap - 1);
|
||||
return false if count <= 0 || count >= cap;
|
||||
into[count as u64] = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
# Finds a C function among what the machine's own process has: what its
|
||||
# executable exports, then what each library loaded into it does. The library
|
||||
# beneath the rest, `ntdll`, has a part of C's own that programs never link, so
|
||||
# it is passed over.
|
||||
# @param name The function's name, zero at its end.
|
||||
# @returns Its address, or 0.
|
||||
def find_symbol(name: *u8): u64 {
|
||||
var found := GetProcAddress(GetModuleHandleW(null), name);
|
||||
return found if found != 0;
|
||||
|
||||
var wide: u16[16];
|
||||
val ntdll := wide_name("ntdll.dll", (&mut wide) as *mut u16, 16) ? GetModuleHandleW((&mut wide) as *u16) : 0;
|
||||
var modules: u64[512];
|
||||
var needed: u32 = 0;
|
||||
val process := GetCurrentProcess();
|
||||
if K32EnumProcessModules(process, (&mut modules) as *mut u64, 512 * 8, &mut needed) != 0 {
|
||||
var count := needed as u64 / 8;
|
||||
count = count < 512 ? count : 512;
|
||||
for i in 0..count {
|
||||
continue if modules[i] == ntdll;
|
||||
found = GetProcAddress(modules[i], name);
|
||||
break if found != 0;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
#! Finds each C function the program calls by name, before the program runs:
|
||||
#! among those the host provides, then in the library its file's `extern
|
||||
#! import` names, or among what the machine's own process has where it names
|
||||
#! none. The first that cannot be found stops the program, with a trace at its
|
||||
#! declaration.
|
||||
#! @param this The machine.
|
||||
#! @returns `none` where every one was found, `foreign_missing` where one was
|
||||
#! not, or `out_of_memory`.
|
||||
pub def interpreter::link_foreign(&mut this): halt {
|
||||
return halt::none if this.foreign_found;
|
||||
this.foreign_found = true;
|
||||
val count := this.c.program.linked.length;
|
||||
return halt::none if count == 0;
|
||||
|
||||
this.symbols.resize(count);
|
||||
this.libraries.resize(count);
|
||||
var name_buffer: u8[1024];
|
||||
var wide: u16[1024];
|
||||
val name_ptr := (&mut name_buffer) as *mut u8;
|
||||
val wide_ptr := (&mut wide) as *mut u16;
|
||||
var libraries := interner::<string>::new();
|
||||
var first_of := vector::<u64>::new(); # The first function of each library, by its ID.
|
||||
for i in 0..count {
|
||||
val entry := &this.c.program.linked[i];
|
||||
val name := this.c.checker.names.text(entry.name);
|
||||
c_name(name, name_ptr);
|
||||
|
||||
# What the host provides is found first, whatever library is named.
|
||||
val given := this.provided_address(name);
|
||||
val library := entry.library.span;
|
||||
if given != 0 {
|
||||
this.symbols[i] = given;
|
||||
} else if library.length == 0 {
|
||||
this.symbols[i] = find_symbol(name_ptr);
|
||||
} else {
|
||||
# A library already opened for an earlier function is shared.
|
||||
val id := libraries.intern_view(library) as u64;
|
||||
if id == first_of.length {
|
||||
first_of.append(i);
|
||||
}
|
||||
var handle: u64 = first_of[id] != i ? this.libraries[first_of[id]] : 0;
|
||||
if handle == 0 && wide_name(library, wide_ptr, 1024) {
|
||||
handle = LoadLibraryW(wide_ptr as *u16);
|
||||
this.libraries[i] = handle;
|
||||
}
|
||||
this.symbols[i] = handle != 0 ? GetProcAddress(handle, name_ptr) : 0;
|
||||
}
|
||||
if name == "VirtualAlloc" {
|
||||
this.maps_at = this.symbols[i];
|
||||
} else if name == "VirtualFree" {
|
||||
this.unmaps_at = this.symbols[i];
|
||||
} else if name == "WriteFile" {
|
||||
this.writes_at = this.symbols[i];
|
||||
} else if name == "WriteConsoleW" {
|
||||
this.console_writes_at = this.symbols[i];
|
||||
}
|
||||
continue if this.symbols[i] != 0;
|
||||
|
||||
# The function, or the library holding it, was not found.
|
||||
this.report_missing(entry.decl, name);
|
||||
return halt::foreign_missing;
|
||||
}
|
||||
return halt::none;
|
||||
}
|
||||
|
||||
# Records a one frame trace at a foreign declaration, where its function was
|
||||
# not found, as the C machine reports it.
|
||||
# @param this The machine.
|
||||
# @param decl The declaration.
|
||||
# @param name The function's name.
|
||||
def interpreter::report_missing(&mut this, decl: u32, name: strview): void {
|
||||
this.trace.clear();
|
||||
var made := trace_frame { function = string::from(name, nothing {}) };
|
||||
val file: u32 = this.c.checker.decls.files.p[decl];
|
||||
if (file as u64) < this.c.checker.units.length {
|
||||
val node: u32 = this.c.checker.decls.nodes.p[decl];
|
||||
val offset := this.c.node_offset(file, node);
|
||||
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;
|
||||
}
|
||||
this.trace.append(move(&mut made));
|
||||
}
|
||||
|
||||
# The head of the code C calls a function of the program through, up to the
|
||||
# machine and the function it is baked with: it keeps the frame, takes 96
|
||||
# bytes, and spills the four register arguments, integer and SSE, into the
|
||||
# words `machine_callback_entry` reads them from.
|
||||
const callback_head: u8[71] = [
|
||||
0x55, # push rbp
|
||||
0x48, 0x89, 0xE5, # mov rbp, rsp
|
||||
0x48, 0x81, 0xEC, 0x60, 0x00, 0x00, 0x00, # sub rsp, 96
|
||||
0x48, 0x89, 0x4C, 0x24, 0x20, # mov [rsp+32], rcx
|
||||
0x48, 0x89, 0x54, 0x24, 0x28, # mov [rsp+40], rdx
|
||||
0x4C, 0x89, 0x44, 0x24, 0x30, # mov [rsp+48], r8
|
||||
0x4C, 0x89, 0x4C, 0x24, 0x38, # mov [rsp+56], r9
|
||||
0x66, 0x48, 0x0F, 0x7E, 0xC0, 0x48, 0x89, 0x44, 0x24, 0x40, # movq rax,xmm0; mov [rsp+64],rax
|
||||
0x66, 0x48, 0x0F, 0x7E, 0xC8, 0x48, 0x89, 0x44, 0x24, 0x48, # movq rax,xmm1; mov [rsp+72],rax
|
||||
0x66, 0x48, 0x0F, 0x7E, 0xD0, 0x48, 0x89, 0x44, 0x24, 0x50, # movq rax,xmm2; mov [rsp+80],rax
|
||||
0x66, 0x48, 0x0F, 0x7E, 0xD8, 0x48, 0x89, 0x44, 0x24, 0x58 # movq rax,xmm3; mov [rsp+88],rax
|
||||
];
|
||||
|
||||
# The tail: `machine_callback_entry` is called with the machine, the function,
|
||||
# the registers, and the stack, then what it left where the registers were is
|
||||
# given back to C in `rax` and `xmm0`.
|
||||
const callback_tail: u8[19] = [
|
||||
0xFF, 0xD0, # call rax
|
||||
0x48, 0x8B, 0x44, 0x24, 0x40, # mov rax, [rsp+64]
|
||||
0x66, 0x48, 0x0F, 0x6E, 0xC0, # movq xmm0, rax
|
||||
0x48, 0x8B, 0x44, 0x24, 0x20, # mov rax, [rsp+32]
|
||||
0xC9, # leave
|
||||
0xC3 # ret
|
||||
];
|
||||
|
||||
# Adds the code C calls a function of the program through: the head, the
|
||||
# machine and the function baked in as `machine_callback_entry` takes them,
|
||||
# where the registers and the stack are, the entry's address, then the tail.
|
||||
# @param code The code made so far.
|
||||
# @param machine The machine running the program.
|
||||
# @param index The function.
|
||||
# @param entry The address of `machine_callback_entry`.
|
||||
def emit_callback(code: &mut byte_writer, machine: u64, index: u64, entry: u64): void {
|
||||
var head := callback_head;
|
||||
code.put(head[:]);
|
||||
code.byte(0x48); code.byte(0xB9); code.u64(machine); # mov rcx, machine
|
||||
code.byte(0x48); code.byte(0xBA); code.u64(index); # mov rdx, index
|
||||
code.byte(0x4C); code.byte(0x8D); code.byte(0x44); code.byte(0x24); code.byte(0x20); # lea r8, [rsp+32]
|
||||
code.byte(0x4C); code.byte(0x8D); code.byte(0x4D); code.byte(0x30); # lea r9, [rbp+48]
|
||||
code.byte(0x48); code.byte(0xB8); code.u64(entry); # mov rax, entry
|
||||
var tail := callback_tail;
|
||||
code.put(tail[:]);
|
||||
}
|
||||
|
||||
# Makes the code a call of C goes through, and the code C calls each function
|
||||
# of the program through, in memory that is then only executed, once it is
|
||||
# first needed.
|
||||
# @param this The machine.
|
||||
# @returns Whether it was made.
|
||||
def interpreter::make_stubs(&mut this): bool {
|
||||
return true if this.call_stub != 0;
|
||||
var code := byte_writer::new();
|
||||
var stub := call_stub_code;
|
||||
code.put(stub[:]);
|
||||
|
||||
val functions := this.c.program.functions.length;
|
||||
this.callbacks.resize(functions);
|
||||
val machine := this as *mut interpreter as u64;
|
||||
val entry := callback_entry_address();
|
||||
for i in 0..functions {
|
||||
continue if !this.c.program.functions[i].callback;
|
||||
this.callbacks[i] = code.length;
|
||||
emit_callback(&mut code, machine, i, entry);
|
||||
}
|
||||
|
||||
val size := round_up(code.length, 4096);
|
||||
val memory := VirtualAlloc(0, size, page_commit, page_write);
|
||||
if memory == 0 {
|
||||
code.close();
|
||||
return false;
|
||||
}
|
||||
memcpy(memory as *mut u8, code.span.data, code.length);
|
||||
code.close();
|
||||
var was: u32 = 0;
|
||||
if VirtualProtect(memory, size, page_execute, &mut was) == 0 {
|
||||
_ = VirtualFree(memory, 0, page_release);
|
||||
return false;
|
||||
}
|
||||
_ = FlushInstructionCache(GetCurrentProcess(), memory, size);
|
||||
this.call_stub = memory;
|
||||
this.foreign_memory = memory;
|
||||
this.foreign_size = size;
|
||||
for i in 0..functions {
|
||||
if this.c.program.functions[i].callback {
|
||||
this.callbacks[i] = this.callbacks[i] + memory;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Gives back the executable memory the stubs are in, and closes the libraries
|
||||
#! opened, unless a thread is left waiting in C, which would come back through
|
||||
#! the code and the library it called.
|
||||
#! @param this The machine.
|
||||
pub def interpreter::unlink_foreign(&mut this): void {
|
||||
return if this.threads != null;
|
||||
for i in 0..this.libraries.length {
|
||||
if this.libraries[i] != 0 {
|
||||
_ = FreeLibrary(this.libraries[i]);
|
||||
}
|
||||
}
|
||||
if this.foreign_memory != 0 {
|
||||
_ = VirtualFree(this.foreign_memory, 0, page_release);
|
||||
this.foreign_memory = 0;
|
||||
this.call_stub = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#! The address of a C function the program calls by name.
|
||||
#! @param this The machine.
|
||||
#! @param index The function among those the program links.
|
||||
#! @returns Its address, or 0.
|
||||
pub def interpreter::c_address(&mut this, index: u32): u64 {
|
||||
return (index as u64) < this.symbols.length ? this.symbols[index] : 0;
|
||||
}
|
||||
|
||||
#! The address C calls a function of the program through, which was given
|
||||
#! where a `cfn` is expected.
|
||||
#! @param this The machine.
|
||||
#! @param index The function.
|
||||
#! @returns Its address, or 0 where the code could not be made.
|
||||
pub def interpreter::callback_address(&mut this, index: u32): u64 {
|
||||
return 0 if !this.make_stubs();
|
||||
return (index as u64) < this.callbacks.length ? this.callbacks[index] : 0;
|
||||
}
|
||||
|
||||
# The address C calls `machine_callback_entry` through, which the code C calls
|
||||
# each function of the program through calls in turn.
|
||||
def callback_entry_address(): u64 {
|
||||
val entry: cfn<def(u64, u64, *mut u64, *mut u64): void> = machine_callback_entry;
|
||||
return entry as u64;
|
||||
}
|
||||
|
||||
#! Runs a function of the program that C calls, on the thread C calls it on,
|
||||
#! which is the one the program called C on. It is given as a `cfn`, so the
|
||||
#! machine's own compiler gives C the address of an entry calling it, and C
|
||||
#! reaches it the same whether the machine is built into an executable or run
|
||||
#! by another machine.
|
||||
#! @param machine The machine, as the code baked it in.
|
||||
#! @param index The function.
|
||||
#! @param registers The four register arguments, integer then SSE.
|
||||
#! @param stack The arguments past the fourth.
|
||||
def machine_callback_entry(machine: u64, index: u64, registers: *mut u64, stack: *mut u64): void {
|
||||
val running := machine as *mut interpreter;
|
||||
running[0].run_callback(index as u32, registers, stack);
|
||||
}
|
||||
|
||||
# Runs a function of the program C called, in a turn of the thread's, which C
|
||||
# called it without, as the C machine runs it: on the strand of the thread C
|
||||
# called it on, or, on a thread C started itself, that of the thread the
|
||||
# program began with, which the function leaves as it found it. The function
|
||||
# finds what C left for `GetLastError`, and C finds what the function's own
|
||||
# calls of C left once it returns. Where the program has no threads of its own
|
||||
# and is calling no C, nothing is there to run it on, which stops the program.
|
||||
# @param this The machine.
|
||||
# @param index The function.
|
||||
# @param registers The register arguments: four integers, then four floats.
|
||||
# @param stack The arguments past the fourth.
|
||||
def interpreter::run_callback(&mut this, index: u32, registers: *mut u64, stack: *mut u64): void {
|
||||
# A function that faulted already stopped the program, so no later one runs.
|
||||
return if this.foreign_fault != halt::none;
|
||||
val left := GetLastError();
|
||||
if this.threads == null && this.calling_c == 0 {
|
||||
system::fd::stderr.put($"sakura: runtime error: {halt::callback.describe()}\n");
|
||||
system::exit(1);
|
||||
}
|
||||
|
||||
val turns := this.threads != null;
|
||||
if turns {
|
||||
val stop := this.take_turn_on(system::thread_id());
|
||||
if stop != halt::none {
|
||||
this.foreign_fault = stop;
|
||||
this.pause();
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.last_error = left;
|
||||
this.called_back(index, registers, stack);
|
||||
val after := this.last_error;
|
||||
if turns {
|
||||
this.pause();
|
||||
}
|
||||
SetLastError(after);
|
||||
}
|
||||
|
||||
# Takes the turn for C calling a function of the program back on a thread of
|
||||
# the system, after every thread that asked before, then holds the strand of
|
||||
# the program's thread it is, or, where C started the thread itself, that of
|
||||
# the thread the program began with.
|
||||
# @param this The machine.
|
||||
# @param thread The number the system knows the thread by.
|
||||
# @returns `elsewhere` where the program stopped meanwhile, or `none`.
|
||||
def interpreter::take_turn_on(&mut this, thread: u64): halt {
|
||||
val shared := this.threads;
|
||||
val ticket := shared[0].next.fetch_add(1);
|
||||
while true {
|
||||
val now := shared[0].serving.load();
|
||||
if now == ticket {
|
||||
break;
|
||||
}
|
||||
_ = system::futex_wait(((&mut shared[0].serving) as *mut atomic<u32>) as *mut u32, now, -1);
|
||||
}
|
||||
var mine := shared[0].strands[0];
|
||||
for i in 0..shared[0].strands.length {
|
||||
if shared[0].strands[i][0].thread == thread {
|
||||
mine = shared[0].strands[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
this.restore(mine);
|
||||
return shared[0].stopped ? halt::elsewhere : halt::none;
|
||||
}
|
||||
|
||||
# Runs a function of the program C called, placing the arguments C passed into
|
||||
# its frame, and leaving its result where C reads it. A fault is kept, to stop
|
||||
# the program once C comes back.
|
||||
# @param this The machine.
|
||||
# @param index The function.
|
||||
# @param registers The register arguments: four integers, then four floats.
|
||||
# @param stack The arguments past the fourth.
|
||||
def interpreter::called_back(&mut this, index: u32, registers: *mut u64, stack: *mut u64): void {
|
||||
val held := this.routines[index];
|
||||
val frame := this.top as *mut u64;
|
||||
if this.top + held.frame > this.stack_end {
|
||||
if this.foreign_fault == halt::none {
|
||||
this.foreign_fault = halt::stack_overflow;
|
||||
}
|
||||
return;
|
||||
}
|
||||
memset(frame as *mut u8, 0, held.frame);
|
||||
|
||||
val signature := this.c.program.functions[index].signature;
|
||||
val sig := &this.c.program.signatures[signature];
|
||||
val result_shape := this.c.program.layouts[sig.result];
|
||||
val result_memory := in_memory(&result_shape);
|
||||
val returned_memory := result_memory && result_shape.size != 0;
|
||||
val result_hidden := result_memory && !micro_by_value(result_shape.size);
|
||||
|
||||
var position: u64 = result_hidden ? 1 : 0;
|
||||
for i in 0..sig.params.length {
|
||||
val shape := this.c.program.layouts[sig.params[i]];
|
||||
val slot := this.params[held.params as u64 + i];
|
||||
val sse := shape.kind == lk::floating;
|
||||
var eightbyte: u64 = 0;
|
||||
if position < 4 {
|
||||
eightbyte = sse ? registers[4 + position] : registers[position];
|
||||
} else {
|
||||
eightbyte = stack[position - 4];
|
||||
}
|
||||
this.store_param(&shape, frame as u64 + slot.offset, eightbyte);
|
||||
position++;
|
||||
}
|
||||
|
||||
# A result held in memory is written to a buffer, whose address a hidden
|
||||
# argument gave, or which the machine gives and reads the result from.
|
||||
var buffer: u64 = 0;
|
||||
var dst: u64 = 0;
|
||||
if returned_memory {
|
||||
buffer = result_hidden ? registers[0] : raw_allocate_zeroed(round_up(result_shape.size, 16)) as u64;
|
||||
dst = buffer;
|
||||
}
|
||||
|
||||
val saved_top := this.top;
|
||||
val base := this.calls.length;
|
||||
this.calls.append(call_record { function = index, fp = frame, back = 0, site = 0, results = none, dst = dst });
|
||||
this.top = frame as u64 + held.frame;
|
||||
# Called back within compiled code calling C, 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();
|
||||
}
|
||||
this.top = saved_top;
|
||||
|
||||
if why != halt::none {
|
||||
if this.foreign_fault == halt::none {
|
||||
this.foreign_fault = why;
|
||||
}
|
||||
if this.threads != null {
|
||||
this.stop_with(why);
|
||||
}
|
||||
if buffer != 0 && !result_hidden {
|
||||
raw_release(buffer as *mut u8);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if returned_memory {
|
||||
if result_hidden {
|
||||
registers[0] = buffer;
|
||||
} else {
|
||||
var out: u64 = 0;
|
||||
memcpy((&mut out) as *mut u8, buffer as *u8, result_shape.size);
|
||||
registers[0] = out;
|
||||
raw_release(buffer as *mut u8);
|
||||
}
|
||||
} else if result_shape.kind == lk::floating {
|
||||
registers[4] = result_shape.size == 4 ? narrow_single(this.results[0]) : this.results[0];
|
||||
} else if result_shape.kind != lk::empty {
|
||||
registers[0] = this.results[0];
|
||||
}
|
||||
}
|
||||
|
||||
# Writes an argument C passed into the frame of the function C called: an
|
||||
# aggregate's bytes, from the address a large one was passed by, or the value
|
||||
# of a smaller one, a scalar widened from its bits as the frame holds it, or a
|
||||
# reference's pointer.
|
||||
# @param this The machine.
|
||||
# @param shape The parameter's layout.
|
||||
# @param at Where it goes in the frame.
|
||||
# @param eightbyte What C passed.
|
||||
def interpreter::store_param(&mut this, shape: &layout, at: u64, eightbyte: u64): void {
|
||||
if in_memory(shape) {
|
||||
val size := shape.size;
|
||||
if micro_by_value(size) {
|
||||
var held := eightbyte;
|
||||
memcpy(at as *mut u8, (&mut held) as *u8, size);
|
||||
} else if eightbyte != 0 {
|
||||
memcpy(at as *mut u8, eightbyte as *u8, size);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if shape.kind == lk::floating && shape.size == 4 {
|
||||
var bits := eightbyte & 0xFFFFFFFF;
|
||||
val narrow := ((&mut bits) as *mut f32)[0];
|
||||
(at as *mut f64)[0] = narrow as f64;
|
||||
return;
|
||||
}
|
||||
(at as *mut u64)[0] = eightbyte;
|
||||
}
|
||||
|
||||
# The eightbyte a value held in a frame is passed to C as: the word the frame
|
||||
# holds, narrowed from a double where it is an `f32`, the bytes of an aggregate
|
||||
# as large as an integer read through its address, or the address of a copy of
|
||||
# a larger one, which the call frees.
|
||||
# @param this The machine.
|
||||
# @param shape The layout.
|
||||
# @param operand The word the frame holds.
|
||||
# @param copies Where the address of a copy made is kept, to free.
|
||||
# @returns The eightbyte.
|
||||
def interpreter::c_eightbyte(&mut this, shape: &layout, operand: u64, copies: &mut vector<u64>): u64 {
|
||||
if !in_memory(shape) {
|
||||
return narrow_single(operand) if shape.kind == lk::floating && shape.size == 4;
|
||||
return operand;
|
||||
}
|
||||
val size := shape.size;
|
||||
if micro_by_value(size) {
|
||||
var out: u64 = 0;
|
||||
if operand != 0 {
|
||||
memcpy((&mut out) as *mut u8, operand as *u8, size);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return 0 if operand == 0;
|
||||
val copy := raw_allocate(round_up(size, 16)) as u64;
|
||||
memcpy(copy as *mut u8, operand as *u8, size);
|
||||
copies.append(copy);
|
||||
return copy;
|
||||
}
|
||||
|
||||
# The bits of the `f32` a word holds as a double.
|
||||
# @param word The word.
|
||||
# @returns The bits.
|
||||
def narrow_single(word: u64): u64 {
|
||||
var held := word;
|
||||
val wide := ((&mut held) as *mut f64)[0];
|
||||
val narrow := wide as f32;
|
||||
var out: u64 = 0;
|
||||
((&mut out) as *mut f32)[0] = narrow;
|
||||
return out;
|
||||
}
|
||||
|
||||
# The word a frame holds a scalar C gave in as: a float widened from a single
|
||||
# to a double, an integer extended from its bits, which C leaves unspecified
|
||||
# past them, or the word as it is.
|
||||
# @param shape The result's layout.
|
||||
# @param c What C left.
|
||||
# @returns The word.
|
||||
def widen_result(shape: &layout, c: &c_call): u64 {
|
||||
if shape.kind == lk::floating {
|
||||
return c.results[2] if shape.size != 4;
|
||||
var bits := c.results[2] & 0xFFFFFFFF;
|
||||
val narrow := ((&mut bits) as *mut f32)[0];
|
||||
val wide := narrow as f64;
|
||||
var out: u64 = 0;
|
||||
((&mut out) as *mut f64)[0] = wide;
|
||||
return out;
|
||||
}
|
||||
var word := c.results[0];
|
||||
return word & 0xFF if shape.kind == lk::boolean;
|
||||
return word if shape.size >= 8 || shape.kind == lk::pointer || shape.kind == lk::reference;
|
||||
val bits := shape.size * 8;
|
||||
val mask := (1u << bits) - 1;
|
||||
word = word & mask;
|
||||
if shape.kind == lk::signed && (word >> (bits - 1)) != 0 {
|
||||
word = word | ~mask;
|
||||
}
|
||||
return word;
|
||||
}
|
||||
|
||||
#! Calls a C function with the arguments a frame holds, as Microsoft's ABI of
|
||||
#! x86-64 passes them, leaving its result where the frame keeps it. Other
|
||||
#! threads run while C does, so the machine lets go of its turn around the
|
||||
#! call, and keeps what C left for `GetLastError` across its own work.
|
||||
#! @param this The machine.
|
||||
#! @param code The code running.
|
||||
#! @param pc Where the call is.
|
||||
#! @param fp The frame.
|
||||
#! @returns Why it stopped, or `none`.
|
||||
pub def interpreter::call_foreign(&mut this, code: *u32, pc: u64, fp: *mut u64): halt {
|
||||
val signature := code[pc + 1];
|
||||
val argc := code[pc + 2] as u64;
|
||||
val base := pc + 3;
|
||||
val address := fp[code[base]];
|
||||
return halt::null_reference if address == 0;
|
||||
|
||||
val held := &this.c.program.signatures[signature];
|
||||
val result_shape := this.c.program.layouts[held.result];
|
||||
val result_memory := in_memory(&result_shape);
|
||||
val returned_memory := result_memory && result_shape.size != 0;
|
||||
val result_hidden := result_memory && !micro_by_value(result_shape.size);
|
||||
|
||||
var c := c_call { function = address };
|
||||
var stack: u64[64];
|
||||
var stack_count: u64 = 0;
|
||||
var copies := vector::<u64>::new();
|
||||
|
||||
var position: u64 = result_hidden ? 1 : 0;
|
||||
val dst := returned_memory ? fp[code[base + argc - 1]] : 0;
|
||||
if result_hidden {
|
||||
c.integers[0] = dst;
|
||||
}
|
||||
|
||||
var k: u64 = 1;
|
||||
for i in 0..held.params.length {
|
||||
val shape := this.c.program.layouts[held.params[i]];
|
||||
val operand := fp[code[base + k]];
|
||||
k += argument_words(&shape);
|
||||
val eightbyte := this.c_eightbyte(&shape, operand, &mut copies);
|
||||
if position < 4 {
|
||||
c.integers[position] = eightbyte;
|
||||
c.floats[position] = eightbyte;
|
||||
} else if stack_count < 64 {
|
||||
stack[stack_count] = eightbyte;
|
||||
stack_count++;
|
||||
}
|
||||
position++;
|
||||
}
|
||||
c.stack = (&mut stack) as *mut u64 as u64;
|
||||
c.words = stack_count;
|
||||
|
||||
# What the program writes to its output or error is kept rather than
|
||||
# written, where the machine is asked to, as it keeps what Linux's call
|
||||
# writes there.
|
||||
var after := halt::none;
|
||||
if !this.options.capture || !this.captured(&mut c) {
|
||||
if !this.make_stubs() {
|
||||
this.free_copies(&mut copies);
|
||||
return halt::out_of_memory;
|
||||
}
|
||||
val mine := this.strand;
|
||||
val saved := this.last_error;
|
||||
this.calling_c++;
|
||||
this.pause();
|
||||
SetLastError(saved);
|
||||
val stub := this.call_stub as cfn<def(u64): void>;
|
||||
stub((&mut c) as *mut c_call as u64);
|
||||
val error := GetLastError();
|
||||
after = this.resume(mine);
|
||||
this.calling_c--;
|
||||
this.last_error = error;
|
||||
}
|
||||
this.free_copies(&mut copies);
|
||||
|
||||
# A function C called back faulted, which the machine sees once C is back,
|
||||
# since it cannot leave C where it is.
|
||||
if this.foreign_fault != halt::none {
|
||||
val why := this.foreign_fault;
|
||||
this.foreign_fault = halt::none;
|
||||
return why;
|
||||
}
|
||||
return after if after != halt::none;
|
||||
if this.options.checks {
|
||||
this.note_foreign_mapping(&c);
|
||||
}
|
||||
|
||||
if returned_memory {
|
||||
if !result_hidden && dst != 0 {
|
||||
memcpy(dst as *mut u8, (&mut c.results[0]) as *u8, result_shape.size);
|
||||
}
|
||||
return halt::none;
|
||||
}
|
||||
if result_shape.kind != lk::empty {
|
||||
val resc := code[base + argc] as u64;
|
||||
if resc != 0 {
|
||||
fp[code[base + argc + 1]] = widen_result(&result_shape, &c);
|
||||
}
|
||||
}
|
||||
return halt::none;
|
||||
}
|
||||
|
||||
# Keeps what a call of `WriteFile` or `WriteConsoleW` writes to the
|
||||
# program's output or error, rather than calling it, as it succeeds: the
|
||||
# bytes, or the UTF-16 units as UTF-8, and how many were written where it's
|
||||
# asked.
|
||||
# @param this The machine.
|
||||
# @param c The call, its arguments ready.
|
||||
# @returns Whether it was kept.
|
||||
def interpreter::captured(&mut this, c: &mut c_call): bool {
|
||||
val console := c.function == this.console_writes_at;
|
||||
return false if c.function == 0 || (c.function != this.writes_at && !console);
|
||||
val handle := c.integers[0];
|
||||
return false if handle != GetStdHandle(0xFFFFFFF5) && handle != GetStdHandle(0xFFFFFFF4);
|
||||
val count := c.integers[2] & 0xFFFFFFFF;
|
||||
if console {
|
||||
val units := c.integers[1] as *u16;
|
||||
var i: u64 = 0;
|
||||
while i < count {
|
||||
var code := units[i] as u32;
|
||||
if code >= 0xD800 && code < 0xDC00 && i + 1 < count {
|
||||
code = 0x10000 + ((code - 0xD800) << 10) + (units[i + 1] as u32 - 0xDC00);
|
||||
i++;
|
||||
}
|
||||
this.output_code(code);
|
||||
i++;
|
||||
}
|
||||
} else {
|
||||
val bytes := c.integers[1] as *u8;
|
||||
for i in 0..count {
|
||||
this.output.append(bytes[i]);
|
||||
}
|
||||
}
|
||||
if c.integers[3] != 0 {
|
||||
(c.integers[3] as *mut u32)[0] = count as u32;
|
||||
}
|
||||
c.results[0] = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
# Keeps a code point written to the output, as UTF-8.
|
||||
def interpreter::output_code(&mut this, code: u32): void {
|
||||
if code < 0x80 {
|
||||
this.output.append(code as u8);
|
||||
} else if code < 0x800 {
|
||||
this.output.append((0xC0 | (code >> 6)) as u8);
|
||||
this.output.append((0x80 | (code & 0x3F)) as u8);
|
||||
} else if code < 0x10000 {
|
||||
this.output.append((0xE0 | (code >> 12)) as u8);
|
||||
this.output.append((0x80 | ((code >> 6) & 0x3F)) as u8);
|
||||
this.output.append((0x80 | (code & 0x3F)) as u8);
|
||||
} else {
|
||||
this.output.append((0xF0 | (code >> 18)) as u8);
|
||||
this.output.append((0x80 | ((code >> 12) & 0x3F)) as u8);
|
||||
this.output.append((0x80 | ((code >> 6) & 0x3F)) as u8);
|
||||
this.output.append((0x80 | (code & 0x3F)) as u8);
|
||||
}
|
||||
}
|
||||
|
||||
# Notes the memory a call of C maps or gives back, running with its memory
|
||||
# checked, as the call of Linux doing the same is noted: what `VirtualAlloc`
|
||||
# gives as what `mmap` does, and what `VirtualFree` releases, all that was
|
||||
# mapped from where it is given, as what `munmap` gives back.
|
||||
# @param this The machine.
|
||||
# @param c The call, made.
|
||||
def interpreter::note_foreign_mapping(&mut this, c: &c_call): void {
|
||||
if c.function == this.maps_at && c.results[0] != 0 {
|
||||
this.note_mapping(9, c.integers[0], c.integers[1], 0, c.results[0]);
|
||||
} else if c.function == this.unmaps_at && (c.results[0] & 0xFFFFFFFF) != 0 && (c.integers[2] & 0x8000) != 0 {
|
||||
val bytes := this.mapped_from(c.integers[0]);
|
||||
if bytes != 0 {
|
||||
this.note_mapping(11, c.integers[0], bytes, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# The bytes of the most memory the program mapped from an address, or 0 where
|
||||
# it mapped none from there.
|
||||
# @param this The machine.
|
||||
# @param at The address.
|
||||
# @returns The bytes.
|
||||
def interpreter::mapped_from(&mut this, at: u64): u64 {
|
||||
var most: u64 = 0;
|
||||
for i in 0..this.mapped.length / 2 {
|
||||
val first: u64 = this.mapped[2 * i];
|
||||
val size: u64 = this.mapped[2 * i + 1];
|
||||
if first == at && size > most {
|
||||
most = size;
|
||||
}
|
||||
}
|
||||
return most;
|
||||
}
|
||||
|
||||
# Frees the copies a call made of the aggregates it passed by address.
|
||||
# @param this The machine.
|
||||
# @param copies The addresses.
|
||||
def interpreter::free_copies(&mut this, copies: &mut vector<u64>): void {
|
||||
for &each in copies {
|
||||
val address: u64 = each;
|
||||
raw_release(address as *mut u8);
|
||||
}
|
||||
copies.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
#! @file format.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what the machine does with values as its layouts describe them:
|
||||
#! writes them as text, as interpolated strings ask, and compares them part by
|
||||
#! part, as `==` of a struct, union, or fixed array asks, each as
|
||||
#! `sources/machine.c` does.
|
||||
|
||||
import sakura::compiler;
|
||||
module sakura::machine;
|
||||
|
||||
|
||||
#! How deeply a value within values is written before `...` stands for the rest.
|
||||
const deepest: u64 = 8;
|
||||
|
||||
#! Adds bytes to the text being formatted.
|
||||
#! @param this The machine.
|
||||
#! @param address The first byte, or 0.
|
||||
#! @param length How many bytes.
|
||||
pub def interpreter::add_text(&mut this, address: u64, length: u64): void {
|
||||
return if this.depth == 0 || address == 0;
|
||||
val bytes := address as *u8;
|
||||
val top := this.depth - 1;
|
||||
for i in 0..length {
|
||||
this.texts[top].append(bytes[i]);
|
||||
}
|
||||
}
|
||||
|
||||
#! Adds text the machine wrote itself to the text being formatted.
|
||||
#! @param this The machine.
|
||||
#! @param text The text.
|
||||
pub def interpreter::add_view(&mut this, text: strview): void {
|
||||
return if this.depth == 0;
|
||||
val top := this.depth - 1;
|
||||
for &each in text {
|
||||
this.texts[top].append(each);
|
||||
}
|
||||
}
|
||||
|
||||
#! Begins text, which the texts made before keep the memory of.
|
||||
#! @param this The machine.
|
||||
pub def interpreter::begin_text(&mut this): void {
|
||||
if this.depth == this.texts.length {
|
||||
this.texts.append(vector::<u8>::new());
|
||||
} else {
|
||||
this.texts[this.depth].clear();
|
||||
}
|
||||
this.depth++;
|
||||
}
|
||||
|
||||
#! Ends the text being formatted, giving it in a block the program gives back.
|
||||
#! @param this The machine.
|
||||
#! @returns The block's first byte, or 0 where the text is empty.
|
||||
pub def interpreter::owned_text(&mut this): u64 {
|
||||
return 0 if this.depth == 0;
|
||||
this.depth--;
|
||||
val length := this.texts[this.depth].length;
|
||||
return 0 if length == 0;
|
||||
val made := this.allocate(length, false);
|
||||
memcpy(made as *mut u8, this.texts[this.depth].span.data, length);
|
||||
this.wrote(made, length);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Adds a value an instruction formats: the words it is, or the address of the
|
||||
#! memory holding it.
|
||||
#! @param this The machine.
|
||||
#! @param layout The value's layout.
|
||||
#! @param fp The frame.
|
||||
#! @param code The code.
|
||||
#! @param at Where the instruction's operand words begin.
|
||||
#! @param count How many there are.
|
||||
pub def interpreter::format_operands(&mut this, layout: u32, fp: *mut u64, code: *u32, at: u64, count: u64): void {
|
||||
val shape := this.c.layout_at(layout);
|
||||
if in_memory(&shape) {
|
||||
this.format(fp[code[at]], layout, false, 0);
|
||||
return;
|
||||
}
|
||||
var words: u64[3] = [0, 0, 0];
|
||||
for i in 0..count {
|
||||
break if i >= 3;
|
||||
words[i] = fp[code[at + i]];
|
||||
}
|
||||
this.format((&mut words) as *mut u64 as u64, layout, true, 0);
|
||||
}
|
||||
|
||||
#! Reads a scalar from memory as a frame holds it, widened to a word.
|
||||
#! @param at The address.
|
||||
#! @param how How it is read.
|
||||
#! @returns The word.
|
||||
pub def read_scalar(at: u64, how: access): u64 {
|
||||
return match how {
|
||||
access::i8 => ((at as *i8)[0] as i64) as u64,
|
||||
access::u8 => (at as *u8)[0] as u64,
|
||||
access::i16 => ((at as *i16)[0] as i64) as u64,
|
||||
access::u16 => (at as *u16)[0] as u64,
|
||||
access::i32 => ((at as *i32)[0] as i64) as u64,
|
||||
access::u32 => (at as *u32)[0] as u64,
|
||||
access::f32 => bits_of_real((at as *f32)[0] as f64),
|
||||
else => (at as *u64)[0]
|
||||
};
|
||||
}
|
||||
|
||||
#! Whether the machine's own code may read some of the program's memory for it,
|
||||
#! as formatting a value or comparing arrays does, running with its memory
|
||||
#! checked: the bytes are memory the program holds, and, where asked, were
|
||||
#! written. Where they are not, why the program stops is kept in `read_stop`,
|
||||
#! which the operation reading them stops with, and nothing more is read.
|
||||
#! @param this The machine.
|
||||
#! @param at The first byte.
|
||||
#! @param size How many.
|
||||
#! @param written Whether they must have been written too.
|
||||
#! @returns Whether they may be read.
|
||||
def interpreter::reads(&mut this, at: u64, size: u64, written: bool = true): bool {
|
||||
return true if !this.options.checks;
|
||||
return false if this.read_stop != halt::none;
|
||||
if at >= null_page && !this.checked_reach(at, 1, size) {
|
||||
this.read_stop = halt::invalid_access;
|
||||
} else if written && at >= null_page && this.unwritten_in(at, size) {
|
||||
this.read_stop = halt::unwritten;
|
||||
}
|
||||
return this.read_stop == halt::none;
|
||||
}
|
||||
|
||||
#! Why reading the program's memory for an operation stopped it, which is then
|
||||
#! forgotten, or `none`.
|
||||
#! @param this The machine.
|
||||
#! @returns Why.
|
||||
pub def interpreter::read_stopped(&mut this): halt {
|
||||
val why := this.read_stop;
|
||||
this.read_stop = halt::none;
|
||||
return why;
|
||||
}
|
||||
|
||||
#! Adds a value to the text being formatted, as its layout says it is written.
|
||||
#! @param this The machine.
|
||||
#! @param at Where the value is.
|
||||
#! @param layout Its layout.
|
||||
#! @param frame Whether it is held as a frame holds it, a scalar widened to a
|
||||
#! word, rather than as memory holds it.
|
||||
#! @param depth How deeply within values it is.
|
||||
pub def interpreter::format(&mut this, at: u64, layout: u32, frame: bool, depth: u64): void {
|
||||
if depth > deepest {
|
||||
this.add_view("...");
|
||||
return;
|
||||
}
|
||||
|
||||
val shape := this.c.layout_at(layout);
|
||||
# Each scalar is read where it is, so what is never written between fields
|
||||
# stops nothing.
|
||||
val scalar := shape.kind == lk::signed || shape.kind == lk::unsigned || shape.kind == lk::boolean
|
||||
|| shape.kind == lk::floating || shape.kind == lk::reference || shape.kind == lk::pointer
|
||||
|| shape.kind == lk::function || shape.kind == lk::trait_reference;
|
||||
return if !frame && scalar && !this.reads(at, shape.size);
|
||||
match shape.kind {
|
||||
lk::signed, lk::unsigned => {
|
||||
val value := frame ? (at as *u64)[0] : read_scalar(at, shape.how);
|
||||
# An enum is the name of the member of the value.
|
||||
for i in 0..shape.count {
|
||||
val member := this.c.field_at(layout, i as u32);
|
||||
if member.offset == value {
|
||||
this.add_view(this.c.checker.names.text(member.name));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if shape.kind == lk::signed {
|
||||
this.add_view($"{value as i64}");
|
||||
} else {
|
||||
this.add_view($"{value}");
|
||||
}
|
||||
}
|
||||
lk::boolean => {
|
||||
val value := frame ? (at as *u64)[0] : read_scalar(at, shape.how);
|
||||
this.add_view(value != 0 ? "true" : "false");
|
||||
}
|
||||
lk::floating => {
|
||||
val value := real_of(frame ? (at as *u64)[0] : read_scalar(at, shape.how));
|
||||
if shape.bits <= 32 {
|
||||
this.add_view($"{value as f32}");
|
||||
} else {
|
||||
this.add_view($"{value}");
|
||||
}
|
||||
}
|
||||
lk::fixed => {
|
||||
val element := shape.element - 1;
|
||||
val inner := this.c.layout_at(element);
|
||||
# A fixed array of bytes is the text it holds.
|
||||
if (inner.kind == lk::signed || inner.kind == lk::unsigned) && inner.size == 1 && inner.count == 0 {
|
||||
return if !frame && !this.reads(at, shape.count as u64);
|
||||
this.add_text(at, shape.count as u64);
|
||||
return;
|
||||
}
|
||||
this.add_view("[");
|
||||
for i in 0..shape.count {
|
||||
if i != 0 {
|
||||
this.add_view(", ");
|
||||
}
|
||||
this.format(at + i as u64 * inner.size, element, false, depth + 1);
|
||||
}
|
||||
this.add_view("]");
|
||||
}
|
||||
lk::reference => {
|
||||
val pointer := (at as *u64)[0];
|
||||
if pointer == 0 || shape.element == 0 {
|
||||
this.add_view("null");
|
||||
return;
|
||||
}
|
||||
this.format(pointer, shape.element - 1, false, depth + 1);
|
||||
}
|
||||
lk::trait_reference => {
|
||||
val pointer := (at as *u64)[0];
|
||||
val vtable := (at as *u64)[1];
|
||||
if pointer == 0 || vtable >= this.c.program.vtables.length {
|
||||
this.add_view("null");
|
||||
return;
|
||||
}
|
||||
this.format(pointer, this.c.program.vtables[vtable].layout, false, depth + 1);
|
||||
}
|
||||
lk::record => this.format_record(at, layout, &shape, depth);
|
||||
lk::pointer => {
|
||||
val address := (at as *u64)[0];
|
||||
if address == 0 {
|
||||
this.add_view("null");
|
||||
return;
|
||||
}
|
||||
this.add_view("0x");
|
||||
this.add_view(hex(address).span);
|
||||
}
|
||||
lk::function => {
|
||||
val index := (at as *u64)[0];
|
||||
if index == 0 {
|
||||
this.add_view("null");
|
||||
return;
|
||||
}
|
||||
if index - 1 >= this.c.program.functions.length {
|
||||
this.add_view("def ?");
|
||||
return;
|
||||
}
|
||||
this.add_view("def ");
|
||||
this.add_view(this.c.program.functions[index - 1].name.span);
|
||||
}
|
||||
lk::variant => {
|
||||
# A union is written as a struct holding the one field it holds.
|
||||
# Its first word, which says which field it holds, may hold bytes no
|
||||
# field wrote, so only that it is held is asked.
|
||||
return if !frame && !this.reads(at, 8, false);
|
||||
val tag := held_field(&shape, (at as *u64)[0]);
|
||||
if tag >= shape.count as u64 {
|
||||
this.add_view("?");
|
||||
return;
|
||||
}
|
||||
val field := this.c.field_at(layout, tag as u32);
|
||||
this.add_view(this.c.checker.names.text(shape.name));
|
||||
this.add_view("{");
|
||||
this.add_view(this.c.checker.names.text(field.name));
|
||||
this.add_view(" = ");
|
||||
this.format(at + field.offset, field.layout, false, depth + 1);
|
||||
this.add_view("}");
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
}
|
||||
|
||||
#! Adds a struct to the text being formatted: text as the bytes it holds, any
|
||||
#! other view as the elements it views, and the rest as its name and fields.
|
||||
#! @param this The machine.
|
||||
#! @param at Where it is.
|
||||
#! @param layout Its layout.
|
||||
#! @param shape The layout itself.
|
||||
#! @param depth How deeply within values it is.
|
||||
def interpreter::format_record(&mut this, at: u64, layout: u32, shape: &layout, depth: u64): void {
|
||||
if shape.texts || (shape.views && shape.viewed != 0) {
|
||||
val begins := this.c.field_at(layout, shape.text);
|
||||
val many := this.c.field_at(layout, shape.text + 1);
|
||||
return if !this.reads(at + begins.offset, 8) || !this.reads(at + many.offset, 8);
|
||||
val data := ((at + begins.offset) as *u64)[0];
|
||||
val length := data != 0 ? ((at + many.offset) as *u64)[0] : 0;
|
||||
if shape.texts {
|
||||
return if data != 0 && !this.reads(data, length);
|
||||
this.add_text(data, length);
|
||||
return;
|
||||
}
|
||||
val element := shape.viewed - 1;
|
||||
val size := this.c.layout_at(element).size;
|
||||
this.add_view("[");
|
||||
for i in 0..length {
|
||||
if i != 0 {
|
||||
this.add_view(", ");
|
||||
}
|
||||
this.format(data + i * size, element, false, depth + 1);
|
||||
}
|
||||
this.add_view("]");
|
||||
return;
|
||||
}
|
||||
|
||||
this.add_view(this.c.checker.names.text(shape.name));
|
||||
this.add_view("{");
|
||||
for i in 0..shape.count {
|
||||
val field := this.c.field_at(layout, i as u32);
|
||||
if i != 0 {
|
||||
this.add_view(", ");
|
||||
}
|
||||
val name := this.c.checker.names.text(field.name);
|
||||
if name.length != 0 {
|
||||
this.add_view(name);
|
||||
this.add_view(" = ");
|
||||
}
|
||||
this.format(at + field.offset, field.layout, false, depth + 1);
|
||||
}
|
||||
this.add_view("}");
|
||||
}
|
||||
|
||||
#! The hexadecimal digits of a word, without leading zeros.
|
||||
#! @param value The word.
|
||||
#! @returns The digits.
|
||||
def hex(value: u64): string {
|
||||
var made := string::new(nothing {});
|
||||
var shift: u64 = 64;
|
||||
var started := false;
|
||||
while shift > 0 {
|
||||
shift -= 4;
|
||||
val digit := (value >> shift) & 0xF;
|
||||
started = started || digit != 0 || shift == 0;
|
||||
continue if !started;
|
||||
made.push(digit < 10 ? ('0' + digit as u8) : ('a' + (digit - 10) as u8));
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Whether the values at two addresses are equal: fixed arrays of what holds
|
||||
#! no object by their bytes, and of anything else element by element, structs
|
||||
#! field by field, unions by the field held and then its value, floats as
|
||||
#! numbers, so `-0` equals `0` and `nan` equals nothing, and anything else by
|
||||
#! its bytes.
|
||||
#! @param this The machine.
|
||||
#! @param a Where one is.
|
||||
#! @param b Where the other is.
|
||||
#! @param layout Their layout.
|
||||
#! @param depth How deeply within values they are.
|
||||
#! @returns Whether they are equal.
|
||||
pub def interpreter::equal(&mut this, a: u64, b: u64, layout: u32, depth: u64): bool {
|
||||
val shape := this.c.layout_at(layout);
|
||||
# What is compared a byte at a time is read whole; a struct, union, or array
|
||||
# of them a field or element at a time, as below.
|
||||
if shape.kind != lk::record && shape.kind != lk::variant {
|
||||
val inner := shape.kind == lk::fixed ? this.c.layout_at(shape.element - 1) : shape;
|
||||
val whole := shape.kind != lk::fixed || inner.kind == lk::signed || inner.kind == lk::unsigned
|
||||
|| inner.kind == lk::boolean || inner.kind == lk::pointer;
|
||||
return false if whole && (!this.reads(a, shape.size) || !this.reads(b, shape.size));
|
||||
}
|
||||
match shape.kind {
|
||||
lk::floating => {
|
||||
val x := real_of(read_scalar(a, shape.how));
|
||||
val y := real_of(read_scalar(b, shape.how));
|
||||
return x == y;
|
||||
}
|
||||
lk::fixed => {
|
||||
val element := shape.element - 1;
|
||||
val inner := this.c.layout_at(element);
|
||||
# Elements that are integers, `bool`, or pointers are equal where their
|
||||
# bytes are; any other is compared as its type is.
|
||||
if inner.kind == lk::signed || inner.kind == lk::unsigned || inner.kind == lk::boolean || inner.kind == lk::pointer {
|
||||
return memcmp(a as *u8, b as *u8, shape.size) == 0;
|
||||
}
|
||||
for i in 0..shape.count {
|
||||
return false if !this.equal(a + i as u64 * inner.size, b + i as u64 * inner.size, element, depth + 1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
lk::record => {
|
||||
for i in 0..shape.count {
|
||||
val field := this.c.field_at(layout, i as u32);
|
||||
return false if !this.equal(a + field.offset, b + field.offset, field.layout, depth + 1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
lk::variant => {
|
||||
return false if !this.reads(a, 8, false) || !this.reads(b, 8, false);
|
||||
val tag := held_field(&shape, (a as *u64)[0]);
|
||||
return false if tag != held_field(&shape, (b as *u64)[0]) || tag >= shape.count as u64;
|
||||
val field := this.c.field_at(layout, tag as u32);
|
||||
return this.equal(a + field.offset, b + field.offset, field.layout, depth + 1);
|
||||
}
|
||||
else => return memcmp(a as *u8, b as *u8, shape.size) == 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,801 @@
|
||||
#! @file heap.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the memory a program holds: the blocks it allocates and gives back
|
||||
#! itself, as `raw_allocate` and `raw_release` do, which the machine knows by
|
||||
#! where each begins and how large it is, so a release of what is no block is
|
||||
#! found, and what a constant holds is told apart from what it may not keep.
|
||||
#!
|
||||
#! Running with its memory checked, as `run --checks` asks, the machine also
|
||||
#! stops at a read or write through a reference or pointer where the program
|
||||
#! holds no memory: in a block it released, which is held back a while before
|
||||
#! its memory is used again so a late use still finds it released, and in a
|
||||
#! stack past the frames in use. Where code of the program's own calls C, whose
|
||||
#! memory the machine does not know, only those, and memory the program mapped
|
||||
#! and gave back, stop it from then on. On Windows `system` is made of calls of
|
||||
#! C, and what those give only its own code reads, so its calls alone do not
|
||||
#! count. It stops at a read of memory nothing wrote, too: of a block
|
||||
#! `raw_allocate` gave, the bytes `raw_resize` added, and a variable
|
||||
#! `undefined`, until each byte is written, which a call of the system or of C
|
||||
#! given an address into the memory counts as doing. As the program ends, the
|
||||
#! blocks it still holds that nothing it keeps reaches are reported, with where
|
||||
#! each was allocated.
|
||||
|
||||
import sakura::analyzer;
|
||||
import sakura::compiler;
|
||||
import std::containers;
|
||||
module sakura::machine;
|
||||
|
||||
|
||||
#! Allocates a block the program gives back itself.
|
||||
#! @param this The machine.
|
||||
#! @param size The bytes it holds.
|
||||
#! @param cleared Whether it is zeroed, as `raw_allocate_zeroed` gives it,
|
||||
#! rather than holding what it may, as `raw_allocate` does.
|
||||
#! @returns Its first byte.
|
||||
pub def interpreter::allocate(&mut this, size: u64, cleared: bool): u64 {
|
||||
val bytes := size == 0 ? 1u : size;
|
||||
val made := (cleared ? raw_allocate_zeroed(bytes) : raw_allocate(bytes)) as u64;
|
||||
this.blocks.set(made, size);
|
||||
# Running with its memory checked, a block not cleared is never written, and
|
||||
# holds bytes no address is made of, so the blocks it reaches are the same
|
||||
# every run.
|
||||
if this.options.checks {
|
||||
this.index_block(made, size);
|
||||
if !cleared {
|
||||
memset(made as *mut u8, unwritten_byte, size);
|
||||
this.forget(made, size);
|
||||
}
|
||||
this.race_forget(made, size);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! What each byte of memory never written holds, running with memory checked:
|
||||
#! a word of them is no address the program holds.
|
||||
const unwritten_byte: u8 = 0xA5;
|
||||
|
||||
#! The bits of a page of `unwritten`, or null where none of its bytes is
|
||||
#! unwritten: those last looked for, as reads and writes keep to a page mostly,
|
||||
#! or else those the dictionary holds. Each page's bits stay where they are
|
||||
#! once made, however the dictionary grows.
|
||||
#! @param this The machine.
|
||||
#! @param page The page's number.
|
||||
#! @returns Its bits.
|
||||
def interpreter::bits_of(&mut this, page: u64): *mut u64 {
|
||||
return this.seen_bits if page == this.seen_page;
|
||||
this.seen_page = page;
|
||||
this.seen_bits = null;
|
||||
if this.unwritten.get(&page) is some(&bits) {
|
||||
this.seen_bits = bits.data;
|
||||
}
|
||||
return this.seen_bits;
|
||||
}
|
||||
|
||||
#! Marks bytes as never written, running with memory checked.
|
||||
#! @param this The machine.
|
||||
#! @param at The first.
|
||||
#! @param size How many.
|
||||
pub def interpreter::forget(&mut this, at: u64, size: u64): void {
|
||||
var from := at;
|
||||
val end := at + size;
|
||||
while from < end {
|
||||
val page := from / 4096;
|
||||
val stop := end < (page + 1) * 4096 ? end : (page + 1) * 4096;
|
||||
var bits := this.bits_of(page);
|
||||
if bits == null {
|
||||
var made := vector::<u64>::new();
|
||||
made.resize(64);
|
||||
bits = made.data;
|
||||
this.unwritten.set(page, move(&mut made));
|
||||
this.seen_bits = bits;
|
||||
}
|
||||
var byte := from - page * 4096;
|
||||
while byte < stop - page * 4096 {
|
||||
val word := byte / 64;
|
||||
val mask := word_mask(byte, stop - page * 4096);
|
||||
bits[word] = bits[word] | mask;
|
||||
byte = (word + 1) * 64;
|
||||
}
|
||||
from = stop;
|
||||
}
|
||||
}
|
||||
|
||||
#! The bits of a word of a page's bits that bytes from one up to another cover,
|
||||
#! within the word the first is in.
|
||||
#! @param byte The first byte, within its page.
|
||||
#! @param end The byte after the last, within the page.
|
||||
#! @returns The bits.
|
||||
def word_mask(byte: u64, end: u64): u64 {
|
||||
val word := byte / 64;
|
||||
val last := end - word * 64 < 64 ? end - word * 64 : 64u;
|
||||
val high := last == 64 ? 0xFFFFFFFFFFFFFFFFu : (1u << last) - 1;
|
||||
return high & ~((1u << (byte % 64)) - 1);
|
||||
}
|
||||
|
||||
#! Marks bytes as written, running with memory checked.
|
||||
#! @param this The machine.
|
||||
#! @param at The first.
|
||||
#! @param size How many.
|
||||
pub def interpreter::wrote(&mut this, at: u64, size: u64): void {
|
||||
return if this.unwritten.length == 0;
|
||||
# A read or a write is a word of bits mostly.
|
||||
val within := at % 64;
|
||||
if within + size <= 64 && size < 64 {
|
||||
val bits := this.bits_of(at / 4096);
|
||||
if bits != null {
|
||||
bits[at % 4096 / 64] = bits[at % 4096 / 64] & ~(((1u << size) - 1) << within);
|
||||
}
|
||||
return;
|
||||
}
|
||||
var from := at;
|
||||
val end := at + size;
|
||||
while from < end {
|
||||
val page := from / 4096;
|
||||
val stop := end < (page + 1) * 4096 ? end : (page + 1) * 4096;
|
||||
val bits := this.bits_of(page);
|
||||
if bits != null {
|
||||
var byte := from - page * 4096;
|
||||
while byte < stop - page * 4096 {
|
||||
val word := byte / 64;
|
||||
bits[word] = bits[word] & ~word_mask(byte, stop - page * 4096);
|
||||
byte = (word + 1) * 64;
|
||||
}
|
||||
}
|
||||
from = stop;
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether any of some bytes was never written, running with memory checked.
|
||||
#! @param this The machine.
|
||||
#! @param at The first.
|
||||
#! @param size How many.
|
||||
#! @returns Whether one was not.
|
||||
pub def interpreter::unwritten_in(&mut this, at: u64, size: u64): bool {
|
||||
return false if this.unwritten.length == 0;
|
||||
val within := at % 64;
|
||||
if within + size <= 64 && size < 64 {
|
||||
val bits := this.bits_of(at / 4096);
|
||||
return bits != null && (bits[at % 4096 / 64] & (((1u << size) - 1) << within)) != 0;
|
||||
}
|
||||
var from := at;
|
||||
val end := at + size;
|
||||
while from < end {
|
||||
val page := from / 4096;
|
||||
val stop := end < (page + 1) * 4096 ? end : (page + 1) * 4096;
|
||||
val bits := this.bits_of(page);
|
||||
if bits != null {
|
||||
var byte := from - page * 4096;
|
||||
while byte < stop - page * 4096 {
|
||||
val word := byte / 64;
|
||||
return true if (bits[word] & word_mask(byte, stop - page * 4096)) != 0;
|
||||
byte = (word + 1) * 64;
|
||||
}
|
||||
}
|
||||
from = stop;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Copies which of some bytes were never written to where they are copied,
|
||||
#! running with memory checked, as copying them copies what they hold: a copy
|
||||
#! is no read, so what was never written stays so where it went.
|
||||
#! @param this The machine.
|
||||
#! @param to Where the first is copied to.
|
||||
#! @param from The first.
|
||||
#! @param size How many.
|
||||
pub def interpreter::copy_unwritten(&mut this, to: u64, from: u64, size: u64): void {
|
||||
return if this.unwritten.length == 0;
|
||||
if !this.unwritten_in(from, size) {
|
||||
this.wrote(to, size);
|
||||
return;
|
||||
}
|
||||
# Byte by byte, from the end where the copy goes past where it comes from.
|
||||
for k in 0..size {
|
||||
val i := to > from ? size - 1 - k : k;
|
||||
if this.unwritten_in(from + i, 1) {
|
||||
this.forget(to + i, 1);
|
||||
} else {
|
||||
this.wrote(to + i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Marks the memory an address the system or C is given points into as
|
||||
#! written, running with memory checked, as what each writes there is not
|
||||
#! known: a block the program holds, whole, or the frames from the address on.
|
||||
#! @param this The machine.
|
||||
#! @param at The address.
|
||||
pub def interpreter::wrote_through(&mut this, at: u64): void {
|
||||
return if this.unwritten.length == 0 || at < null_page;
|
||||
if at >= this.stack as u64 && at < this.top {
|
||||
this.wrote(at, this.top - at);
|
||||
return;
|
||||
}
|
||||
val first := this.indexed_block(at);
|
||||
if first != 0 {
|
||||
this.wrote(first, this.blocks[first]);
|
||||
}
|
||||
}
|
||||
|
||||
#! Notes a block on each page it is over, to the byte past its end, running
|
||||
#! with its memory checked, so the block an address is within is found among
|
||||
#! those of its page.
|
||||
#! @param this The machine.
|
||||
#! @param address The block's first byte.
|
||||
#! @param size Its bytes.
|
||||
def interpreter::index_block(&mut this, address: u64, size: u64): void {
|
||||
for page in address / 4096..(address + size) / 4096 + 1 {
|
||||
if this.pages.contains(&page) {
|
||||
val held: &mut vector<u64> = this.pages[page];
|
||||
held.append(address);
|
||||
} else {
|
||||
var made := vector::<u64>::new();
|
||||
made.append(address);
|
||||
this.pages.set(page, move(&mut made));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Takes a block off the pages it is over, as it is released.
|
||||
#! @param this The machine.
|
||||
#! @param address The block's first byte.
|
||||
#! @param size Its bytes.
|
||||
def interpreter::unindex_block(&mut this, address: u64, size: u64): void {
|
||||
for page in address / 4096..(address + size) / 4096 + 1 {
|
||||
if this.pages.contains(&page) {
|
||||
val held: &mut vector<u64> = this.pages[page];
|
||||
for i in 0..held.length {
|
||||
if held[i] == address {
|
||||
held[i] = held.last;
|
||||
held.truncate();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! The block an address is within, to the byte past its end, among those of
|
||||
#! its page, running with its memory checked: one it is before the end of
|
||||
#! where an address is both the end of one and the start of the next.
|
||||
#! @param this The machine.
|
||||
#! @param at The address.
|
||||
#! @returns The block's first byte, or 0.
|
||||
def interpreter::indexed_block(&mut this, at: u64): u64 {
|
||||
var found: u64 = 0;
|
||||
if this.pages.get(&(at / 4096)) is some(&held) {
|
||||
for &each in held.span {
|
||||
val first: u64 = each;
|
||||
val size: u64 = this.blocks[first];
|
||||
if at >= first && at <= first + size {
|
||||
return first if at < first + size;
|
||||
found = first;
|
||||
}
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
#! Gives a block back.
|
||||
#! @param this The machine.
|
||||
#! @param address The block's first byte, or 0, which gives nothing back.
|
||||
#! @returns `invalid_release` where the address is no block the program holds.
|
||||
pub def interpreter::release(&mut this, address: u64): halt {
|
||||
return halt::none if address == 0;
|
||||
if !this.blocks.contains(&address) {
|
||||
return halt::invalid_release;
|
||||
}
|
||||
val size: u64 = this.blocks[address];
|
||||
this.blocks.remove(&address);
|
||||
this.kept.remove(&address);
|
||||
if this.options.checks {
|
||||
this.wrote(address, size);
|
||||
this.unindex_block(address, size);
|
||||
this.sites.remove(&address);
|
||||
this.hold_back(address, size);
|
||||
return halt::none;
|
||||
}
|
||||
raw_release(address as *mut u8);
|
||||
return halt::none;
|
||||
}
|
||||
|
||||
#! The bytes of released blocks held back at most, and how many.
|
||||
const held_back_bytes: u64 = 67108864;
|
||||
const held_back_most: u64 = 65536;
|
||||
|
||||
#! Holds a released block back from being used again, giving back the oldest
|
||||
#! held back where too many are.
|
||||
#! @param this The machine.
|
||||
#! @param address The block's first byte.
|
||||
#! @param size The bytes it holds.
|
||||
def interpreter::hold_back(&mut this, address: u64, size: u64): void {
|
||||
this.released.append(address);
|
||||
this.released_sizes.append(size);
|
||||
this.released_bytes += size;
|
||||
while this.released_bytes > held_back_bytes || this.released.length - this.released_from > held_back_most {
|
||||
val oldest: u64 = this.released[this.released_from];
|
||||
raw_release(oldest as *mut u8);
|
||||
this.released_bytes -= this.released_sizes[this.released_from];
|
||||
this.released_from++;
|
||||
}
|
||||
# The list is moved down once half of it is let go of.
|
||||
if this.released_from > 1024 && this.released_from * 2 > this.released.length {
|
||||
var kept := vector::<u64>::new();
|
||||
var sizes := vector::<u64>::new();
|
||||
for i in this.released_from..this.released.length {
|
||||
kept.append(this.released[i]);
|
||||
sizes.append(this.released_sizes[i]);
|
||||
}
|
||||
this.released = move(&mut kept);
|
||||
this.released_sizes = move(&mut sizes);
|
||||
this.released_from = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#! Notes where a block was allocated, running with its memory checked: the
|
||||
#! innermost frame of a function of the program's own rather than std's.
|
||||
#! @param this The machine.
|
||||
#! @param address The block's first byte.
|
||||
#! @param pc Where the code running is.
|
||||
pub def interpreter::note_site(&mut this, address: u64, pc: u64): void {
|
||||
return if address == 0;
|
||||
var i := this.calls.length;
|
||||
while i > 0 {
|
||||
i--;
|
||||
val function: u32 = this.calls.at(i).function;
|
||||
val at := i == this.calls.length - 1 ? pc : this.calls.at(i + 1).site;
|
||||
if !this.in_std_function(function) || i == 0 {
|
||||
this.sites.set(address, pair_key(function, at as u32));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Keeps the words of the frames the running thread has in use as the program
|
||||
#! ends by exiting, running with its memory checked, so that the leaks reported
|
||||
#! count them as reaching what they hold: neither a thread stopped as `main`
|
||||
#! returns nor one that exits releases what its locals hold.
|
||||
#! @param this The machine.
|
||||
pub def interpreter::keep_frames(&mut this): void {
|
||||
var at := this.stack as u64;
|
||||
while at + word_size <= this.top {
|
||||
this.ended.append((at as *u64)[0]);
|
||||
at += word_size;
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether a function is std's, or an anonymous function within one of std's.
|
||||
#! @param this The machine.
|
||||
#! @param function The function.
|
||||
#! @returns Whether it is.
|
||||
def interpreter::in_std_function(&mut this, function: u32): bool {
|
||||
val held := &this.c.program.functions[function];
|
||||
val decl := held.decl != 0 ? held.decl : held.outer;
|
||||
return decl != 0 && this.c.in_std(decl);
|
||||
}
|
||||
|
||||
#! Whether a function is `system`'s, or an anonymous function within one of
|
||||
#! `system`'s.
|
||||
#! @param this The machine.
|
||||
#! @param function The function.
|
||||
#! @returns Whether it is.
|
||||
def interpreter::in_system_function(&mut this, function: u32): bool {
|
||||
val held := &this.c.program.functions[function];
|
||||
val decl := held.decl != 0 ? held.decl : held.outer;
|
||||
return decl != 0 && this.in_system(decl);
|
||||
}
|
||||
|
||||
#! Whether the code at a place in a function is `system`'s: that of a function
|
||||
#! of `system`'s, or, in the code giving the globals their values, that giving
|
||||
#! one of `system`'s its value, as the file it is written in says.
|
||||
#! @param this The machine.
|
||||
#! @param function The function.
|
||||
#! @param pc Where in its code.
|
||||
#! @returns Whether it is.
|
||||
def interpreter::in_system_code(&mut this, function: u32, pc: u64): bool {
|
||||
return this.in_system_function(function) if function != this.c.program.init;
|
||||
var at: u64 = 0;
|
||||
for &mark in this.c.program.functions[function].compiled.lines {
|
||||
break if mark.pc as u64 > pc;
|
||||
at = mark.at;
|
||||
}
|
||||
# A file of `system`'s declares only what is `system`'s, so any declaration
|
||||
# of the file says whose the code is.
|
||||
if at != 0 {
|
||||
val file := pair_high(at) - 1;
|
||||
for decl in 1..this.c.checker.decls.count {
|
||||
continue if this.c.checker.decls.files.p[decl] != file || this.c.checker.decls.nodes.p[decl] == 0;
|
||||
return this.in_system(decl as u32);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Whether a declaration is `system`'s, which on Windows is made of calls of C
|
||||
#! whose memory only its own code reads.
|
||||
#! @param this The machine.
|
||||
#! @param decl The declaration.
|
||||
#! @returns Whether it is.
|
||||
def interpreter::in_system(&this, decl: u32): bool {
|
||||
var at: u32 = this.c.checker.decls.modules.p[decl];
|
||||
var steps := 0;
|
||||
while at != 0 && this.c.checker.modules.parents[at] != 0 && steps < 64 {
|
||||
at = this.c.checker.modules.parents[at];
|
||||
steps++;
|
||||
}
|
||||
return at != 0 && this.c.checker.modules.names[at] == word::system;
|
||||
}
|
||||
|
||||
#! Notes the memory a system call that succeeded maps or unmaps, running with
|
||||
#! its memory checked, which the program holds as it does a block: what `mmap`
|
||||
#! and `mremap` give, in whole pages, until `munmap` gives it back. Where the
|
||||
#! program calls C, which takes memory the machine does not know as C's, what
|
||||
#! it gave back is kept apart, so a late use still finds it given back.
|
||||
#! @param this The machine.
|
||||
#! @param number The call, as Linux numbers them.
|
||||
#! @param a Its first argument.
|
||||
#! @param b Its second.
|
||||
#! @param c Its third.
|
||||
#! @param result What it gave.
|
||||
pub def interpreter::note_mapping(&mut this, number: u64, a: u64, b: u64, c: u64, result: u64): void {
|
||||
if number == 9 {
|
||||
this.add_run(result, (b + 4095) / 4096 * 4096);
|
||||
} else if number == 11 {
|
||||
val size := (b + 4095) / 4096 * 4096;
|
||||
drop_runs(&mut this.mapped, a, size);
|
||||
if this.calls_c {
|
||||
drop_runs(&mut this.unmapped, a, size);
|
||||
insert_run(&mut this.unmapped, a, size);
|
||||
}
|
||||
} else if number == 25 {
|
||||
for i in 0..this.mapped.length / 2 {
|
||||
if this.mapped[2 * i] == a {
|
||||
this.mapped.remove_at(2 * i + 1);
|
||||
this.mapped.remove_at(2 * i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
this.add_run(result, (c + 4095) / 4096 * 4096);
|
||||
}
|
||||
}
|
||||
|
||||
#! Notes memory the program was given, running with its memory checked, among
|
||||
#! the runs kept in order of where each begins.
|
||||
#! @param this The machine.
|
||||
#! @param start Its first byte.
|
||||
#! @param size Its bytes.
|
||||
pub def interpreter::add_run(&mut this, start: u64, size: u64): void {
|
||||
insert_run(&mut this.mapped, start, size);
|
||||
}
|
||||
|
||||
#! Puts a run of memory among runs kept in order of where each begins.
|
||||
#! @param runs The runs, as pairs of where each begins and its bytes.
|
||||
#! @param start Its first byte.
|
||||
#! @param size Its bytes.
|
||||
def insert_run(runs: &mut vector<u64>, start: u64, size: u64): void {
|
||||
var at := runs.length;
|
||||
while at > 0 && runs[at - 2] > start {
|
||||
at -= 2;
|
||||
}
|
||||
runs.insert_at(at, size);
|
||||
runs.insert_at(at, start);
|
||||
}
|
||||
|
||||
#! Takes the runs of memory lying within some memory from runs kept in order of
|
||||
#! where each begins.
|
||||
#! @param runs The runs, as pairs of where each begins and its bytes.
|
||||
#! @param start The memory's first byte.
|
||||
#! @param size Its bytes.
|
||||
def drop_runs(runs: &mut vector<u64>, start: u64, size: u64): void {
|
||||
var i := 0u;
|
||||
while i < runs.length {
|
||||
val first: u64 = runs[i];
|
||||
val bytes: u64 = runs[i + 1];
|
||||
if first >= start && first + bytes <= start + size {
|
||||
runs.remove_at(i + 1);
|
||||
runs.remove_at(i);
|
||||
} else {
|
||||
i += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Of runs of memory, as pairs of where each begins and its bytes in order of
|
||||
#! where each begins, the one that may hold the address: the last beginning at
|
||||
#! or before it, or the count of runs where none does.
|
||||
#! @param runs The runs.
|
||||
#! @param at The address.
|
||||
#! @returns The run's index.
|
||||
def find_run(runs: &vector<u64>, at: u64): u64 {
|
||||
val count := runs.length / 2;
|
||||
var low: u64 = 0;
|
||||
var high := count;
|
||||
while low < high {
|
||||
val middle := (low + high) / 2;
|
||||
if runs[2 * middle] <= at {
|
||||
low = middle + 1;
|
||||
} else {
|
||||
high = middle;
|
||||
}
|
||||
}
|
||||
return low == 0 ? count : low - 1;
|
||||
}
|
||||
|
||||
#! Puts where each datum is and its bytes in order, running with its memory
|
||||
#! checked, so the one an address is within is found by halves.
|
||||
#! @param this The machine.
|
||||
def interpreter::order_data(&mut this): void {
|
||||
for i in 0..this.data.length {
|
||||
val data: u64 = this.data[i];
|
||||
this.data_runs.append(data);
|
||||
this.data_runs.append(this.c.program.data[i].bytes.length);
|
||||
}
|
||||
# In order of where each begins, two words at a time.
|
||||
for i in 1..this.data_runs.length / 2 {
|
||||
var j := i;
|
||||
while j > 0 && this.data_runs[2 * (j - 1)] > this.data_runs[2 * j] {
|
||||
val start: u64 = this.data_runs[2 * j];
|
||||
val size: u64 = this.data_runs[2 * j + 1];
|
||||
this.data_runs[2 * j] = this.data_runs[2 * (j - 1)];
|
||||
this.data_runs[2 * j + 1] = this.data_runs[2 * (j - 1) + 1];
|
||||
this.data_runs[2 * (j - 1)] = start;
|
||||
this.data_runs[2 * (j - 1) + 1] = size;
|
||||
j--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether elements from a pointer lie where the program may read and write
|
||||
#! them, running with its memory checked: in memory it holds or mapped, or,
|
||||
#! where it calls C, anywhere but in a block released and held back, in a stack
|
||||
#! past the frames in use, or in memory it mapped and gave back. That is so of
|
||||
#! code of the program's own only once it has called C, since on Windows
|
||||
#! `system` is made of calls of C, whose memory only `system`'s code reads.
|
||||
#! @param this The machine.
|
||||
#! @param pointer The first element.
|
||||
#! @param count How many.
|
||||
#! @param size The bytes of each.
|
||||
#! @returns Whether they do.
|
||||
pub def interpreter::checked_reach(&mut this, pointer: u64, count: u64, size: u64): bool {
|
||||
# Within the first page, the read or the write itself stops the program, as
|
||||
# one through null, as where memory is not checked.
|
||||
return true if pointer < null_page;
|
||||
return true if count == 0 || size == 0;
|
||||
val bytes := count * size;
|
||||
return false if bytes / count != size;
|
||||
var start: u64 = 0;
|
||||
val end := this.region(pointer, &mut start);
|
||||
return end - pointer >= bytes if end != 0;
|
||||
val run := find_run(&this.mapped, pointer);
|
||||
if run < this.mapped.length / 2 {
|
||||
val first: u64 = this.mapped[2 * run];
|
||||
val size: u64 = this.mapped[2 * run + 1];
|
||||
return first + size - pointer >= bytes if pointer < first + size;
|
||||
}
|
||||
return true if this.in_other_frames(pointer, bytes);
|
||||
for i in this.released_from..this.released.length {
|
||||
val first: u64 = this.released[i];
|
||||
return false if pointer >= first && pointer < first + this.released_sizes[i];
|
||||
}
|
||||
return false if this.in_stacks(pointer);
|
||||
val gone := find_run(&this.unmapped, pointer);
|
||||
if gone < this.unmapped.length / 2 {
|
||||
val first: u64 = this.unmapped[2 * gone];
|
||||
val size: u64 = this.unmapped[2 * gone + 1];
|
||||
return false if pointer < first + size;
|
||||
}
|
||||
return this.calls_c && (this.called_c || this.in_system_function(this.calls.last().function));
|
||||
}
|
||||
|
||||
#! Writes what blocks the program allocated it still holds that nothing it
|
||||
#! keeps reaches, as a run with its memory checked does once the program ends:
|
||||
#! those neither a global, nor the frames a thread had in use as the program
|
||||
#! exited, nor a block either reaches holds the address of, with where they were
|
||||
#! allocated, those of each place together.
|
||||
#! @param this The machine.
|
||||
#! @param out Where it is written.
|
||||
pub def interpreter::report_leaks(&mut this, out: &mut string): void {
|
||||
# The blocks, by where each begins, to find the one an address is within.
|
||||
var starts := vector::<u64>::new();
|
||||
for &entry in this.blocks {
|
||||
starts.append(entry.key);
|
||||
}
|
||||
starts.sort();
|
||||
|
||||
# The blocks the globals reach, and those they reach in turn.
|
||||
var reached := hashset::<u64>::new();
|
||||
var todo := vector::<u64>::new();
|
||||
this.reach_words(this.globals as u64, this.globals as u64 + this.c.program.globals, &starts, &mut reached, &mut todo);
|
||||
if this.ended.length != 0 {
|
||||
val words := (&this.ended[0]) as *u64 as u64;
|
||||
this.reach_words(words, words + this.ended.length * word_size, &starts, &mut reached, &mut todo);
|
||||
}
|
||||
while todo.length != 0 {
|
||||
val block: u64 = todo.last;
|
||||
todo.truncate();
|
||||
this.reach_words(block, block + this.blocks[block], &starts, &mut reached, &mut todo);
|
||||
}
|
||||
|
||||
# What is lost, by where it was allocated.
|
||||
var places := vector::<string>::new();
|
||||
var counts := vector::<u64>::new();
|
||||
var sizes := vector::<u64>::new();
|
||||
var blocks: u64 = 0;
|
||||
var bytes: u64 = 0;
|
||||
for &first in starts {
|
||||
continue if reached.contains(&first) || this.kept.contains(&first);
|
||||
val size: u64 = this.blocks[first];
|
||||
blocks++;
|
||||
bytes += size;
|
||||
var place := string::from("an unknown place", nothing {});
|
||||
if this.sites.get(&first) is some(site) {
|
||||
val frame := this.site_frame(pair_high(site), pair_low(site) as u64);
|
||||
place = $"{frame.function} ({frame.path}:{frame.line}:{frame.column})";
|
||||
}
|
||||
var found := places.length;
|
||||
for i in 0..places.length {
|
||||
if places[i].span == place.span {
|
||||
found = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if found == places.length {
|
||||
places.append(move(&mut place));
|
||||
counts.append(0);
|
||||
sizes.append(0);
|
||||
}
|
||||
counts[found] += 1;
|
||||
sizes[found] += size;
|
||||
}
|
||||
return if blocks == 0;
|
||||
|
||||
# The places in order, so the report reads the same each run.
|
||||
var order := vector::<u64>::new();
|
||||
for i in 0..places.length {
|
||||
order.append(i);
|
||||
}
|
||||
for i in 1..order.length {
|
||||
var j := i;
|
||||
while j > 0 && places[order[j - 1]].compare(places[order[j]].span) > 0 {
|
||||
val held: u64 = order[j];
|
||||
order[j] = order[j - 1];
|
||||
order[j - 1] = held;
|
||||
j--;
|
||||
}
|
||||
}
|
||||
val noun := blocks == 1 ? "block" : "blocks";
|
||||
out.append($"sakura: {blocks} {noun} the program allocated, {bytes} bytes, were never released, and nothing it keeps reaches them:\n");
|
||||
for &i in order {
|
||||
val count: u64 = counts[i];
|
||||
val each := count == 1 ? "block" : "blocks";
|
||||
out.append($" {count} {each}, {sizes[i]} bytes, allocated at {places[i]}\n");
|
||||
}
|
||||
}
|
||||
|
||||
#! Marks the blocks the words of memory hold the addresses of, or addresses
|
||||
#! within, which are to have their own words read.
|
||||
#! @param this The machine.
|
||||
#! @param from The first byte.
|
||||
#! @param to The byte past the last.
|
||||
#! @param starts Where each block begins, in order.
|
||||
#! @param reached The blocks marked.
|
||||
#! @param todo The blocks marked whose words are to be read.
|
||||
def interpreter::reach_words(&mut this, from: u64, to: u64, starts: &vector<u64>, reached: &mut hashset<u64>, todo: &mut vector<u64>): void {
|
||||
return if starts.length == 0;
|
||||
var at := (from + word_size - 1) / word_size * word_size;
|
||||
while at + word_size <= to {
|
||||
val word := (at as *u64)[0];
|
||||
at += word_size;
|
||||
continue if word < starts[0];
|
||||
val index := starts.span.upper_bound(&word);
|
||||
continue if index == 0;
|
||||
val first: u64 = starts[index - 1];
|
||||
continue if word >= first + (this.blocks[first] == 0 ? 1 : this.blocks[first]);
|
||||
if reached.insert(first) {
|
||||
todo.append(first);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Moves a block to one of another size, keeping what fits, and gives the old
|
||||
#! one back. Resizing no block allocates one.
|
||||
#! @param this The machine.
|
||||
#! @param address The block's first byte, or 0.
|
||||
#! @param size The bytes the new one holds.
|
||||
#! @returns The new block's first byte.
|
||||
pub def interpreter::resize(&mut this, address: u64, size: u64): u64 {
|
||||
return this.allocate(size, false) if address == 0;
|
||||
val had: u64 = this.blocks[address];
|
||||
val made := this.allocate(size, false);
|
||||
val kept := had < size ? had : size;
|
||||
memcpy(made as *mut u8, address as *u8, kept);
|
||||
if this.options.checks {
|
||||
this.copy_unwritten(made, address, kept);
|
||||
}
|
||||
this.release(address);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The memory the program holds an address within, while compiling: the
|
||||
#! globals, the frames in use, or a block, each up to the byte past its end.
|
||||
#! @param this The machine.
|
||||
#! @param at The address.
|
||||
#! @param start Where the memory begins is written here.
|
||||
#! @returns Where it ends, or 0 where the program holds no memory there.
|
||||
def interpreter::region(&mut this, at: u64, start: &mut u64): u64 {
|
||||
val globals := this.globals as u64;
|
||||
if at >= globals && at <= globals + this.c.program.globals {
|
||||
start = globals;
|
||||
return globals + this.c.program.globals;
|
||||
}
|
||||
if at >= this.stack as u64 && at <= this.top {
|
||||
start = this.stack as u64;
|
||||
return this.top;
|
||||
}
|
||||
if this.options.checks {
|
||||
val first := this.indexed_block(at);
|
||||
if first != 0 {
|
||||
start = first;
|
||||
return first + this.blocks[first];
|
||||
}
|
||||
} else {
|
||||
for &entry in this.blocks {
|
||||
if at >= entry.key && at <= entry.key + entry.value {
|
||||
start = entry.key;
|
||||
return entry.key + entry.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
if this.options.checks {
|
||||
val run := find_run(&this.data_runs, at);
|
||||
if run < this.data_runs.length / 2 && at <= this.data_runs[2 * run] + this.data_runs[2 * run + 1] {
|
||||
start = this.data_runs[2 * run];
|
||||
return start + this.data_runs[2 * run + 1];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
for i in 0..this.data.length {
|
||||
val data: u64 = this.data[i];
|
||||
val size := this.c.program.data[i].bytes.length;
|
||||
if at >= data && at <= data + size {
|
||||
start = data;
|
||||
return data + size;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Whether elements from a pointer lie in memory the program holds, as reading
|
||||
#! them while compiling asks.
|
||||
#! @param this The machine.
|
||||
#! @param pointer The first element.
|
||||
#! @param count How many.
|
||||
#! @param size The bytes of each.
|
||||
#! @returns Whether they do.
|
||||
pub def interpreter::reaches(&mut this, pointer: u64, count: u64, size: u64): bool {
|
||||
return false if pointer == 0;
|
||||
return true if count == 0;
|
||||
var start: u64 = 0;
|
||||
val end := this.region(pointer, &mut start);
|
||||
return false if end == 0;
|
||||
val bytes := count * size;
|
||||
return bytes / count == size && end - pointer >= bytes;
|
||||
}
|
||||
|
||||
#! Whether two pointers are within the same memory, which comparing or
|
||||
#! subtracting them while compiling asks, since where different memory is
|
||||
#! changes from one build to the next.
|
||||
#! @param this The machine.
|
||||
#! @param a One pointer.
|
||||
#! @param b The other.
|
||||
#! @returns Whether they are.
|
||||
pub def interpreter::same_memory(&mut this, a: u64, b: u64): bool {
|
||||
return true if a == b;
|
||||
return false if a == 0 || b == 0;
|
||||
var start: u64 = 0;
|
||||
val end := this.region(a, &mut start);
|
||||
return end != 0 && b >= start && b <= end;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+2621
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,938 @@
|
||||
#! @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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
#! @file races.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the race checker, which a run with its memory checked has once the
|
||||
#! program starts a thread: it stops the program where two threads reach the
|
||||
#! same memory, one of them writing it, and nothing orders the two, as
|
||||
#! ThreadSanitizer does.
|
||||
#!
|
||||
#! What orders them is what happened before: each thread has a clock of its own,
|
||||
#! and knows of each other thread's clock as far as what it saw of that thread,
|
||||
#! a vector of clocks. Starting a thread gives it what its starter knew; an
|
||||
#! atomic operation releasing gives what its thread knows to the address it
|
||||
#! writes, and one acquiring takes what the address was given, so a thread
|
||||
#! joining another, which waits for the other's `finished` with `acquire`, knows
|
||||
#! what the other did. A fence releases and acquires through one address of its
|
||||
#! own. A relaxed operation orders nothing.
|
||||
#!
|
||||
#! Of each word of memory read or written through a reference or pointer, the
|
||||
#! checker keeps its last write and the last two reads of different threads,
|
||||
#! each with the thread, its clock then, the bytes of the word, and where it
|
||||
#! was. A read races the last write of another thread the reader knows nothing
|
||||
#! of yet, and a write races that too and either read. Memory the program
|
||||
#! allocates anew forgets what was kept of it, as it holds nothing of before.
|
||||
#! What a thread's frame holds of its own is not watched, so only what threads
|
||||
#! reach of each other's frames through references is.
|
||||
|
||||
import std::containers;
|
||||
import sakura::compiler;
|
||||
module sakura::machine;
|
||||
|
||||
|
||||
#! A read or a write of a word, as the race checker keeps it.
|
||||
struct race_access {
|
||||
var thread: u32; #! One more than the thread's number, or 0 for none.
|
||||
var clock: u32; #! The thread's own clock then.
|
||||
var bytes: u8; #! The bytes of the word, a bit each, the lowest first.
|
||||
var function: u32; #! The function reaching it.
|
||||
var pc: u32; #! Where in its code.
|
||||
}
|
||||
|
||||
#! What the race checker keeps of a word: its last write, and the last reads of
|
||||
#! two threads.
|
||||
struct race_word {
|
||||
var wrote: race_access;
|
||||
var first: race_access;
|
||||
var second: race_access;
|
||||
}
|
||||
|
||||
#! What the race checker keeps of the program and of the thread running.
|
||||
struct race_checker : owning {
|
||||
var on: bool; #! Whether the program started a thread, running with memory checked.
|
||||
var threads: u32; #! How many threads were numbered.
|
||||
var thread: u32; #! The number of the thread running.
|
||||
var clock: vector<u32>; #! What the thread running knows of each thread's clock, its own among them.
|
||||
var words: dict<u64, race_word>; #! What was kept of each word, by its address.
|
||||
var syncs: dict<u64, u32>; #! The clocks each address an atomic operation released to was given, by where they are in `held`.
|
||||
var held: vector<vector<u32>>; #! Those clocks.
|
||||
var text: string; #! What the program stopping says, naming where the other access was.
|
||||
}
|
||||
|
||||
#! The address a fence releases and acquires through, which no memory has.
|
||||
const fence_address: u64 = 0;
|
||||
|
||||
#! Makes a checker, which checks nothing until the program starts a thread.
|
||||
#! @returns The checker.
|
||||
def race_checker::new(): race_checker {
|
||||
return race_checker {
|
||||
clock = vector::<u32>::new(),
|
||||
words = dict::<u64, race_word>::new(),
|
||||
syncs = dict::<u64, u32>::new(),
|
||||
held = vector::<vector<u32>>::new(),
|
||||
text = string::new(nothing {})
|
||||
};
|
||||
}
|
||||
|
||||
def race_checker::close(&mut this): void {
|
||||
this.clock.close();
|
||||
this.words.close();
|
||||
this.syncs.close();
|
||||
for i in 0..this.held.length {
|
||||
this.held[i].close();
|
||||
}
|
||||
this.held.close();
|
||||
this.text.close();
|
||||
}
|
||||
|
||||
#! What the thread running knows of a thread's clock.
|
||||
#! @param this The checker.
|
||||
#! @param thread The thread's number.
|
||||
#! @returns Its clock, or 0 where it knows nothing of it.
|
||||
def race_checker::knows(&this, thread: u32): u32 {
|
||||
return thread < this.clock.length as u32 ? this.clock[thread as u64] : 0;
|
||||
}
|
||||
|
||||
#! Takes what a clock knows into the thread running's: the later of each.
|
||||
#! @param this The checker.
|
||||
#! @param from The clock.
|
||||
def race_checker::join(&mut this, from: &vector<u32>): void {
|
||||
if this.clock.length < from.length {
|
||||
this.clock.resize(from.length, 0);
|
||||
}
|
||||
for i in 0..from.length {
|
||||
if from[i] > this.clock[i] {
|
||||
this.clock[i] = from[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether an access was made before what the thread running knows of, so it
|
||||
#! is ordered before the thread's own: it is the thread's own, or none.
|
||||
#! @param this The checker.
|
||||
#! @param made The access.
|
||||
#! @returns Whether it is.
|
||||
def race_checker::before(&this, made: &race_access): bool {
|
||||
return made.thread == 0 || made.thread - 1 == this.thread || made.clock <= this.knows(made.thread - 1);
|
||||
}
|
||||
|
||||
#! Begins checking as a thread starts another: the one running is numbered 0
|
||||
#! where it is the first to, and the one started is given what its starter
|
||||
#! knows, and a clock of its own. The starter's own clock moves on, so what it
|
||||
#! does after is not known to the one started.
|
||||
#! @param this The checker.
|
||||
#! @param into The started thread's strand.
|
||||
pub def interpreter::race_start(&mut this, into: *mut strand): void {
|
||||
return if !this.options.checks;
|
||||
val races := &mut this.races;
|
||||
if !races.on {
|
||||
races.on = true;
|
||||
races.threads = 1;
|
||||
races.thread = 0;
|
||||
races.clock.clear();
|
||||
races.clock.append(1);
|
||||
}
|
||||
val number := races.threads;
|
||||
races.threads++;
|
||||
into[0].racer = number;
|
||||
into[0].clock = vector::<u32>::new();
|
||||
into[0].clock.extend(races.clock.span);
|
||||
into[0].clock.resize(number as u64 + 1, 0);
|
||||
into[0].clock[number as u64] = 1;
|
||||
races.clock[races.thread as u64]++;
|
||||
}
|
||||
|
||||
#! What an atomic operation orders: where it acquires, the thread running takes
|
||||
#! what its address was given; where it releases, the address is given what the
|
||||
#! thread knows, and the thread's own clock moves on.
|
||||
#! @param this The machine.
|
||||
#! @param address The address, or anything for a fence.
|
||||
#! @param operation The operation, as `atomic_load` or `atomic_fence`.
|
||||
#! @param order Its order, as `core::order` numbers them.
|
||||
pub def interpreter::race_atomic(&mut this, address: u64, operation: u32, order: u64): void {
|
||||
return if !this.races.on;
|
||||
val at := operation == atomic_fence ? fence_address : address;
|
||||
val acquires := (order == order_acquire || order == order_acq_rel || order == order_seq_cst) && operation != atomic_store;
|
||||
val releases := (order == order_release || order == order_acq_rel || order == order_seq_cst) && operation != atomic_load;
|
||||
val races := &mut this.races;
|
||||
if acquires {
|
||||
if races.syncs.get(&at) is some(index) {
|
||||
races.join(&races.held[index as u64]);
|
||||
}
|
||||
}
|
||||
if releases {
|
||||
var index: u32 = 0;
|
||||
if races.syncs.get(&at) is some(found) {
|
||||
index = found;
|
||||
} else {
|
||||
index = races.held.length as u32;
|
||||
races.held.append(vector::<u32>::new());
|
||||
races.syncs.set(at, index);
|
||||
}
|
||||
val given := &mut races.held[index as u64];
|
||||
if given.length < races.clock.length {
|
||||
given.resize(races.clock.length, 0);
|
||||
}
|
||||
for i in 0..races.clock.length {
|
||||
if races.clock[i] > given[i] {
|
||||
given[i] = races.clock[i];
|
||||
}
|
||||
}
|
||||
races.clock[races.thread as u64]++;
|
||||
}
|
||||
}
|
||||
|
||||
#! Checks a read or a write through a reference or pointer against what other
|
||||
#! threads did of the words it reaches, then keeps it.
|
||||
#! @param this The machine.
|
||||
#! @param address The first byte.
|
||||
#! @param size How many bytes.
|
||||
#! @param writes Whether it writes.
|
||||
#! @param function The function reaching it.
|
||||
#! @param pc Where in its code.
|
||||
#! @returns `race` where it races another thread's, or `none`.
|
||||
pub def interpreter::race_access(&mut this, address: u64, size: u64, writes: bool, function: u32, pc: u64): halt {
|
||||
return halt::none if !this.races.on || size == 0;
|
||||
var word := address & ~7u;
|
||||
val end := address + size;
|
||||
while word < end {
|
||||
val from := address > word ? address - word : 0;
|
||||
val to := end < word + 8 ? end - word : 8;
|
||||
val bytes := (((1u << (to - from)) - 1) << from) as u8;
|
||||
val made := race_access {
|
||||
thread = this.races.thread + 1, clock = this.races.knows(this.races.thread), bytes = bytes,
|
||||
function = function, pc = pc as u32
|
||||
};
|
||||
val why := this.race_word(word, &made, writes);
|
||||
return why if why != halt::none;
|
||||
word += 8;
|
||||
}
|
||||
return halt::none;
|
||||
}
|
||||
|
||||
#! Checks an access of one word against what was kept of it, then keeps it.
|
||||
#! @param this The machine.
|
||||
#! @param word The word's address.
|
||||
#! @param made The access.
|
||||
#! @param writes Whether it writes.
|
||||
#! @returns `race` where it races another thread's, or `none`.
|
||||
def interpreter::race_word(&mut this, word: u64, made: &race_access, writes: bool): halt {
|
||||
var held := this.races.words.get_or(&word, race_word {});
|
||||
if (held.wrote.bytes & made.bytes) != 0 && !this.races.before(&held.wrote) {
|
||||
return this.raced(&held.wrote);
|
||||
}
|
||||
if writes {
|
||||
if (held.first.bytes & made.bytes) != 0 && !this.races.before(&held.first) {
|
||||
return this.raced(&held.first);
|
||||
}
|
||||
if (held.second.bytes & made.bytes) != 0 && !this.races.before(&held.second) {
|
||||
return this.raced(&held.second);
|
||||
}
|
||||
# What was kept is all ordered before it, so it alone is kept.
|
||||
held = race_word { wrote = made };
|
||||
} else if held.first.thread == made.thread || held.first.thread == 0 || this.races.before(&held.first) {
|
||||
held.first = made;
|
||||
} else if held.second.thread == made.thread || held.second.thread == 0 || this.races.before(&held.second) {
|
||||
held.second = made;
|
||||
} else {
|
||||
held.second = held.first;
|
||||
held.first = made;
|
||||
}
|
||||
this.races.words.set(word, held);
|
||||
return halt::none;
|
||||
}
|
||||
|
||||
#! Stops the program as it races another thread's access, saying where that
|
||||
#! access was.
|
||||
#! @param this The machine.
|
||||
#! @param other The other access.
|
||||
#! @returns `race`.
|
||||
def interpreter::raced(&mut this, other: &race_access): halt {
|
||||
val frame := this.site_frame(other.function, other.pc as u64);
|
||||
this.races.text = $"Threads raced: memory one wrote, another read or wrote, with nothing ordering the two. The other was in {frame.function} ({frame.path}:{frame.line}:{frame.column}).";
|
||||
return halt::race;
|
||||
}
|
||||
|
||||
#! Forgets what was kept of memory the program is given anew, as a block it
|
||||
#! allocates, which holds nothing of what was there before.
|
||||
#! @param this The machine.
|
||||
#! @param address The first byte.
|
||||
#! @param size How many.
|
||||
pub def interpreter::race_forget(&mut this, address: u64, size: u64): void {
|
||||
return if !this.races.on || this.races.words.length == 0;
|
||||
val first := address & ~7u;
|
||||
val end := address + size;
|
||||
# A large block is passed over by what was kept, rather than word by word.
|
||||
if size / 8 > this.races.words.length {
|
||||
var gone := vector::<u64>::new();
|
||||
for &entry in this.races.words {
|
||||
if entry.key >= first && entry.key < end {
|
||||
gone.append(entry.key);
|
||||
}
|
||||
}
|
||||
for &each in gone {
|
||||
this.races.words.remove(&each);
|
||||
}
|
||||
gone.close();
|
||||
return;
|
||||
}
|
||||
var word := first;
|
||||
while word < end {
|
||||
this.races.words.remove(&word);
|
||||
word += 8;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
#! @file system.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what a program asks of the system: its calls, which the machine
|
||||
#! makes as they are asked through `system::linux::syscall`, the variables it
|
||||
#! started with, and the signals it handles, which the machine has `system`
|
||||
#! note for it, so that the program's handlers run at its own safe points.
|
||||
|
||||
import system;
|
||||
module sakura::machine;
|
||||
|
||||
|
||||
#! The number of the call that writes.
|
||||
const call_write: u64 = 1;
|
||||
|
||||
#! Makes a system call a program asks for, failing as the kernel does, with
|
||||
#! the negated error number. What a program writes to its output or error is
|
||||
#! kept instead where the machine is asked to.
|
||||
#! @param number The call.
|
||||
#! @param a Its first argument.
|
||||
#! @param b Its second.
|
||||
#! @param c Its third.
|
||||
#! @param d Its fourth.
|
||||
#! @param e Its fifth.
|
||||
#! @param f Its sixth.
|
||||
#! @param running The machine.
|
||||
#! @returns What the call gives.
|
||||
pub def system_call(number: u64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64, running: &mut interpreter): u64 {
|
||||
if running.options.capture && number == call_write && (a == 1 || a == 2) {
|
||||
val bytes := b as *u8;
|
||||
for i in 0..c {
|
||||
running.output.append(bytes[i]);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
return host_call(number, a, b, c, d, e, f);
|
||||
}
|
||||
|
||||
when os == linux {
|
||||
# Makes the call, as the system running the machine is Linux.
|
||||
def host_call(number: u64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64): u64 {
|
||||
return system::linux::syscall(number as i64, a, b, c, d, e, f) as u64;
|
||||
}
|
||||
}
|
||||
|
||||
when os == windows {
|
||||
# Windows has no calls a program makes itself, so a program checked for it
|
||||
# calls C instead, as `system` does there. What a program writes to its
|
||||
# output or error through the call of Linux is written still, as the
|
||||
# machine's tests write it, and every other call fails as Linux fails one it
|
||||
# does not have.
|
||||
def host_call(number: u64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64): u64 {
|
||||
if number == call_write && (a == 1 || a == 2) {
|
||||
val to: system::fd = a == 1 ? system::fd::stdout : system::fd::stderr;
|
||||
return to.write(b as *u8, c) as u64;
|
||||
}
|
||||
return (-38 as i64) as u64;
|
||||
}
|
||||
}
|
||||
|
||||
#! Where the system put the variables the program started with: pointers to
|
||||
#! text ending in a zero, then a null pointer, made once.
|
||||
#! @param this The machine.
|
||||
#! @returns The address of the first pointer.
|
||||
pub def interpreter::environment(&mut this): u64 {
|
||||
return this.environ if this.environ != 0;
|
||||
val each := system::environment();
|
||||
val made := raw_allocate_zeroed((each.length + 1) * 8) as *mut u64;
|
||||
for i in 0..each.length {
|
||||
made[i] = each[i].data as u64;
|
||||
}
|
||||
this.environ = made as u64;
|
||||
|
||||
# Running with its memory checked, the program holds the pointers and the
|
||||
# text of each, to the zero ending it, as it does memory it mapped.
|
||||
if this.options.checks {
|
||||
this.add_run(made as u64, (each.length + 1) * 8);
|
||||
for i in 0..each.length {
|
||||
this.add_run(each[i].data as u64, each[i].length + 1);
|
||||
}
|
||||
}
|
||||
return this.environ;
|
||||
}
|
||||
|
||||
#! The signals that came since the program last asked, one bit each by the
|
||||
#! system's number, as `system` noted them for the machine.
|
||||
pub var noted_signals: u64;
|
||||
|
||||
#! Gathers the signals `system` noted for the machine since it last asked.
|
||||
#! @returns Whether any came that the program has not asked for.
|
||||
pub def signals_came(): bool {
|
||||
noted_signals = noted_signals | system::watched();
|
||||
return noted_signals != 0;
|
||||
}
|
||||
|
||||
when os == linux {
|
||||
#! Has a signal of the system's number noted when it comes, as a program asks.
|
||||
#! The machine asks itself whether one came, at the program's safe points, so
|
||||
#! no handler runs, and the machine's own code has no safe points.
|
||||
#! @param number The signal's number.
|
||||
#! @returns Zero, or the negated error number.
|
||||
pub def catch_signal(number: i64): i64 {
|
||||
return match system::signal_of(number) {
|
||||
some(which) => system::watch(which) as i64,
|
||||
else => -22
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
when os == windows {
|
||||
#! Has a signal of the system's number noted when it comes, thrown away, done
|
||||
#! as the system does by default, noted now, or gives the handle of the event
|
||||
#! the system sets where a signal is noted, as the bits above the number say,
|
||||
#! as a program asks. The machine asks the system running it to do each, so a
|
||||
#! signal reaches a program the machine runs as it does an executable, and a
|
||||
#! wait of the program's ends on one as the machine's own waits do. No handler
|
||||
#! of the machine's own runs, and the machine's own code has no safe points.
|
||||
#! @param number The signal's number, with what to do in the bits above it:
|
||||
#! 0 note it, 1 throw it away, 2 do as the system does, 3 note
|
||||
#! it now, 4 give the event's handle.
|
||||
#! @returns Zero, the event's handle, or the negated error number.
|
||||
pub def catch_signal(number: i64): i64 {
|
||||
val action := (number >> 8) & 0xFF;
|
||||
return match system::signal_of(number & 0xFF) {
|
||||
some(which) => match action {
|
||||
0 => system::watch(which) as i64,
|
||||
1 => system::ignore(which) as i64,
|
||||
2 => system::restore(which) as i64,
|
||||
3 => system::raise(which) as i64,
|
||||
4 => system::signal_event() as i64,
|
||||
else => -22
|
||||
},
|
||||
else => action == 4 ? system::signal_event() as i64 : -22
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
#! @file threads.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the threads of a program the machine runs, each a thread of the
|
||||
#! system the machine starts with `std::thread`. They take turns running
|
||||
#! bytecode, in the order they asked, so the machine and its heap are only ever
|
||||
#! used by one: a thread lets the next run as it waits in the system, and every
|
||||
#! few thousand steps where another waits. So threads run at the same time but
|
||||
#! not in parallel, while an executable's run in parallel; a program right in
|
||||
#! one is right in the other.
|
||||
#!
|
||||
#! What a thread has of its own, its stack, calls, texts being formatted, and
|
||||
#! trace, is a strand, which the machine holds while the thread has its turn,
|
||||
#! and the strand keeps while it has none.
|
||||
#!
|
||||
#! A thread that exits, or faults, stops the program: the others stop at their
|
||||
#! next turn, and a wait in the system ends within a tenth of a second while
|
||||
#! threads run, as the machine gives a futex's wait without a time one, so each
|
||||
#! sees it. A fault is reported with the trace of the thread that faulted.
|
||||
|
||||
import system;
|
||||
import std::thread;
|
||||
import std::time;
|
||||
import sakura::compiler;
|
||||
module sakura::machine;
|
||||
|
||||
|
||||
#! The steps a thread takes before it lets another waiting run.
|
||||
const turn_steps: u64 = 4096;
|
||||
|
||||
#! How long a wait in the system lasts at most while threads run, so a thread
|
||||
#! sees the program stop.
|
||||
const longest_wait: i64 = 100000000;
|
||||
|
||||
#! What a thread has of its own, which the machine holds while it has its turn.
|
||||
struct strand {
|
||||
var stack: *mut u8;
|
||||
var stack_end: u64;
|
||||
var top: u64;
|
||||
var calls: call_stack;
|
||||
var texts: vector<vector<u8>>;
|
||||
var depth: u64;
|
||||
var trace: vector<trace_frame>;
|
||||
var countdown: u64;
|
||||
var last_error: u32; #! The error the thread's last C call left, kept across the machine's own work.
|
||||
var thread: u64; #! The number the system knows the thread by, which C calling back on it finds its strand by.
|
||||
var active: bool; #! Whether the machine holds it.
|
||||
var function: u32; #! The function the thread runs, what its closure uses, and the context it is given.
|
||||
var environment: u64;
|
||||
var context: u64;
|
||||
var racer: u32; #! Its number, as the race checker knows it.
|
||||
var clock: vector<u32>; #! What it knows of each thread's clock, as the race checker keeps it.
|
||||
}
|
||||
|
||||
#! What a thread of the system is given to run a thread of the program: the
|
||||
#! machine, and the thread's strand.
|
||||
struct strand_start {
|
||||
var machine: *mut interpreter;
|
||||
var mine: *mut strand;
|
||||
}
|
||||
|
||||
#! What the threads of a program share, which the machine holds once one starts.
|
||||
struct threading {
|
||||
var next: atomic<u32>; #! Turns asked for.
|
||||
var serving: atomic<u32>; #! The turn being taken.
|
||||
var strands: vector<*mut strand>; #! Every thread's, the first's among them.
|
||||
var handles: vector<thread::handle<void>>; #! The threads of the system running them.
|
||||
var running: u64; #! Threads started and not yet ended.
|
||||
var stopped: bool; #! Whether the program stopped, exiting or faulting.
|
||||
var stop: halt; #! Why.
|
||||
var trace: vector<trace_frame>; #! Where the thread that faulted was.
|
||||
}
|
||||
|
||||
#! Starts a thread running a function value, given a context, a thread of the
|
||||
#! system taking turns with the others. The first thread started makes what
|
||||
#! they share, the thread running holding the turn.
|
||||
#! @param this The machine.
|
||||
#! @param function The function's index, one more than it.
|
||||
#! @param environment What a closure uses.
|
||||
#! @param context The word the function is given.
|
||||
#! @returns The thread's number, or a negative error number.
|
||||
pub def interpreter::start_thread(&mut this, function: u64, environment: u64, context: u64): i64 {
|
||||
if this.threads == null {
|
||||
val shared := raw_allocate_zeroed(size_of::<threading>()) as *mut threading;
|
||||
shared[0].strands = vector::<*mut strand>::new();
|
||||
shared[0].handles = vector::<thread::handle<void>>::new();
|
||||
shared[0].trace = vector::<trace_frame>::new();
|
||||
shared[0].next.store(1);
|
||||
val mine := raw_allocate_zeroed(size_of::<strand>()) as *mut strand;
|
||||
mine[0].active = true;
|
||||
when os == windows {
|
||||
mine[0].thread = system::thread_id();
|
||||
}
|
||||
shared[0].strands.append(mine);
|
||||
this.threads = shared;
|
||||
this.strand = mine;
|
||||
this.countdown = turn_steps;
|
||||
}
|
||||
|
||||
val shared := this.threads;
|
||||
val made := raw_allocate_zeroed(size_of::<strand>()) as *mut strand;
|
||||
# Its stack is cleared where the one the program began with is.
|
||||
val size := this.stack_end - this.stack as u64;
|
||||
made[0].stack = this.options.checks ? raw_allocate_zeroed(size) : raw_allocate(size);
|
||||
made[0].stack_end = made[0].stack as u64 + size;
|
||||
made[0].top = made[0].stack as u64;
|
||||
made[0].calls = call_stack::new();
|
||||
made[0].texts = vector::<vector<u8>>::new();
|
||||
made[0].trace = vector::<trace_frame>::new();
|
||||
made[0].countdown = turn_steps;
|
||||
made[0].function = (function - 1) as u32;
|
||||
made[0].environment = environment;
|
||||
made[0].context = context;
|
||||
this.race_start(made);
|
||||
shared[0].strands.append(made);
|
||||
shared[0].running++;
|
||||
|
||||
val given := strand_start { machine = this as *mut interpreter, mine = made };
|
||||
var started := thread::spawn_with(def(at: strand_start) { through(at.machine).thread_main(at.mine); }, given) else (e) {
|
||||
shared[0].strands.truncate();
|
||||
shared[0].running--;
|
||||
raw_release(made[0].stack);
|
||||
made[0].clock.close();
|
||||
raw_release(made as *mut u8);
|
||||
return -11;
|
||||
};
|
||||
val number := started.number() as i64;
|
||||
shared[0].handles.append(move(started));
|
||||
return number;
|
||||
}
|
||||
|
||||
#! What a thread of the system runs for a thread of the program: its function,
|
||||
#! in its turns. Where it stops the program, every thread sees it.
|
||||
#! @param this The machine.
|
||||
#! @param mine The thread's strand.
|
||||
def interpreter::thread_main(&mut this, mine: *mut strand): void {
|
||||
val shared := this.threads;
|
||||
when os == windows {
|
||||
mine[0].thread = system::thread_id();
|
||||
}
|
||||
this.take_turn(mine);
|
||||
if !shared[0].stopped {
|
||||
val ran := this.invoke_value(mine[0].function, mine[0].environment, mine[0].context);
|
||||
if ran != halt::none && ran != halt::elsewhere {
|
||||
this.stop_with(ran);
|
||||
}
|
||||
}
|
||||
# The thread is done: its strand goes, and the turn passes on.
|
||||
this.save(mine);
|
||||
for i in 0..shared[0].strands.length {
|
||||
if shared[0].strands[i] == mine {
|
||||
shared[0].strands.remove_at(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
shared[0].running--;
|
||||
this.give_turn();
|
||||
raw_release(mine[0].stack);
|
||||
mine[0].calls.close();
|
||||
for i in 0..mine[0].texts.length {
|
||||
mine[0].texts[i].close();
|
||||
}
|
||||
mine[0].texts.close();
|
||||
mine[0].trace.close();
|
||||
mine[0].clock.close();
|
||||
raw_release(mine as *mut u8);
|
||||
}
|
||||
|
||||
#! Calls a function value from the base of the stack, as a thread begins, and
|
||||
#! runs it until it returns.
|
||||
#! @param this The machine.
|
||||
#! @param index The function.
|
||||
#! @param environment What a closure uses.
|
||||
#! @param context The word it is given.
|
||||
#! @returns Why it stopped, or `none`.
|
||||
def interpreter::invoke_value(&mut this, index: u32, environment: u64, context: 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);
|
||||
# The context is the first parameter, where the function takes one.
|
||||
if held.frame >= word_size {
|
||||
fp[0] = context;
|
||||
}
|
||||
if held.closure {
|
||||
fp[held.env / word_size] = environment;
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
#! Says the program stopped, for why, where nothing stopped it before, keeping
|
||||
#! the trace of a fault.
|
||||
#! @param this The machine.
|
||||
#! @param why Why.
|
||||
def interpreter::stop_with(&mut this, why: halt): void {
|
||||
val shared := this.threads;
|
||||
return if shared[0].stopped;
|
||||
shared[0].stopped = true;
|
||||
shared[0].stop = why;
|
||||
if why != halt::exited {
|
||||
shared[0].trace = move(&mut this.trace);
|
||||
}
|
||||
}
|
||||
|
||||
#! Where a thread's run of steps ends: it lets another waiting run.
|
||||
#! @param this The machine.
|
||||
#! @returns `elsewhere` where the program stopped meanwhile, or `none`.
|
||||
def interpreter::next_turn(&mut this): halt {
|
||||
this.countdown = turn_steps;
|
||||
val shared := this.threads;
|
||||
return halt::elsewhere if shared[0].stopped;
|
||||
return halt::none if shared[0].next.load() - shared[0].serving.load() <= 1;
|
||||
val mine := this.strand;
|
||||
this.pause();
|
||||
return this.resume(mine);
|
||||
}
|
||||
|
||||
#! Ends a thread's turn, as it waits in the system or lets another run, keeping
|
||||
#! what it has of its own in its strand.
|
||||
#! @param this The machine.
|
||||
pub def interpreter::pause(&mut this): void {
|
||||
return if this.threads == null;
|
||||
this.save(this.strand);
|
||||
this.give_turn();
|
||||
}
|
||||
|
||||
#! Takes a thread's next turn.
|
||||
#! @param this The machine.
|
||||
#! @param mine The thread's strand.
|
||||
#! @returns `elsewhere` where the program stopped meanwhile, or `none`.
|
||||
pub def interpreter::resume(&mut this, mine: *mut strand): halt {
|
||||
return halt::none if this.threads == null;
|
||||
this.take_turn(mine);
|
||||
return this.threads[0].stopped ? halt::elsewhere : halt::none;
|
||||
}
|
||||
|
||||
# Waits for the turn, after every thread that asked before, then holds the
|
||||
# thread's strand.
|
||||
def interpreter::take_turn(&mut this, mine: *mut strand): void {
|
||||
val shared := this.threads;
|
||||
val ticket := shared[0].next.fetch_add(1);
|
||||
while true {
|
||||
val now := shared[0].serving.load();
|
||||
if now == ticket {
|
||||
break;
|
||||
}
|
||||
_ = system::futex_wait(((&mut shared[0].serving) as *mut atomic<u32>) as *mut u32, now, -1);
|
||||
}
|
||||
this.restore(mine);
|
||||
}
|
||||
|
||||
# Lets the thread that asked next have its turn.
|
||||
def interpreter::give_turn(&mut this): void {
|
||||
val shared := this.threads;
|
||||
_ = shared[0].serving.fetch_add(1);
|
||||
_ = system::futex_wake(((&mut shared[0].serving) as *mut atomic<u32>) as *mut u32, 0x7FFFFFFF);
|
||||
}
|
||||
|
||||
# Keeps what the thread running has of its own in its strand.
|
||||
def interpreter::save(&mut this, into: *mut strand): void {
|
||||
into[0].stack = this.stack;
|
||||
into[0].stack_end = this.stack_end;
|
||||
into[0].top = this.top;
|
||||
into[0].calls = move(&mut this.calls);
|
||||
into[0].texts = move(&mut this.texts);
|
||||
into[0].depth = this.depth;
|
||||
into[0].trace = move(&mut this.trace);
|
||||
into[0].countdown = this.countdown;
|
||||
into[0].last_error = this.last_error;
|
||||
into[0].racer = this.races.thread;
|
||||
into[0].clock = move(&mut this.races.clock);
|
||||
into[0].active = false;
|
||||
}
|
||||
|
||||
# Holds a thread's strand as the thread running's.
|
||||
def interpreter::restore(&mut this, from: *mut strand): void {
|
||||
this.stack = from[0].stack;
|
||||
this.stack_end = from[0].stack_end;
|
||||
this.top = from[0].top;
|
||||
this.calls = move(&mut from[0].calls);
|
||||
this.texts = move(&mut from[0].texts);
|
||||
this.depth = from[0].depth;
|
||||
this.trace = move(&mut from[0].trace);
|
||||
this.countdown = from[0].countdown;
|
||||
this.last_error = from[0].last_error;
|
||||
this.races.thread = from[0].racer;
|
||||
this.races.clock = move(&mut from[0].clock);
|
||||
this.strand = from;
|
||||
from[0].active = true;
|
||||
}
|
||||
|
||||
#! Whether bytes from an address lie within the frames another thread of the
|
||||
#! program is using, which a reference into another's locals may reach.
|
||||
#! @param this The machine.
|
||||
#! @param at The address.
|
||||
#! @param bytes How many bytes.
|
||||
#! @returns Whether they do.
|
||||
pub def interpreter::in_other_frames(&mut this, at: u64, bytes: u64): bool {
|
||||
return false if this.threads == null;
|
||||
val shared := this.threads;
|
||||
for i in 0..shared[0].strands.length {
|
||||
val each: *mut strand = shared[0].strands[i];
|
||||
continue if each == this.strand;
|
||||
return true if at >= each[0].stack as u64 && at <= each[0].top && each[0].top - at >= bytes;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Whether an address lies within the stack of any thread of the program.
|
||||
#! @param this The machine.
|
||||
#! @param at The address.
|
||||
#! @returns Whether it does.
|
||||
pub def interpreter::in_stacks(&mut this, at: u64): bool {
|
||||
return true if at >= this.stack as u64 && at < this.stack_end;
|
||||
return false if this.threads == null;
|
||||
val shared := this.threads;
|
||||
for i in 0..shared[0].strands.length {
|
||||
val each: *mut strand = shared[0].strands[i];
|
||||
return true if at >= each[0].stack as u64 && at < each[0].stack_end;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! In a copy of the program a thread made, which holds that thread alone, the
|
||||
#! other threads are gone.
|
||||
#! @param this The machine.
|
||||
pub def interpreter::forked(&mut this): void {
|
||||
return if this.threads == null;
|
||||
val shared := this.threads;
|
||||
var kept := vector::<*mut strand>::new();
|
||||
kept.append(this.strand);
|
||||
shared[0].strands = move(&mut kept);
|
||||
shared[0].running = 0;
|
||||
while shared[0].handles.length != 0 {
|
||||
# Their threads of the system are gone with the copy, so none is waited for.
|
||||
var gone := move(&mut shared[0].handles.last);
|
||||
val leaked := &mut vector::<thread::handle<void>>::new();
|
||||
leaked.append(move(&mut gone));
|
||||
shared[0].handles.truncate();
|
||||
}
|
||||
}
|
||||
|
||||
#! A wait in the system the machine makes for a thread: a futex's wait without a
|
||||
#! time lasts a tenth of a second at most while threads run, so the thread
|
||||
#! sees the program stop.
|
||||
#! @param this The machine.
|
||||
#! @param op The futex's operation.
|
||||
#! @param time Where the time it lasts is, or 0.
|
||||
#! @param into Where a time of the machine's own may be written.
|
||||
#! @returns Where the time is.
|
||||
pub def interpreter::wait_time(&mut this, op: u64, time: u64, into: *mut i64): u64 {
|
||||
return time if this.threads == null || (op & 0x7F) != 0 || time != 0;
|
||||
into[0] = 0;
|
||||
into[1] = longest_wait;
|
||||
return into as u64;
|
||||
}
|
||||
|
||||
#! Once the program's `main` returns, or the program stops, the threads still
|
||||
#! running stop too: each at its next turn. They are waited for, so nothing of
|
||||
#! the machine is used once it is gone, but for one that never comes back from
|
||||
#! the system. Gives why the program stopped, where a thread stopped it.
|
||||
#! @param this The machine.
|
||||
#! @param ran Why `main` stopped.
|
||||
#! @returns Why the program stopped.
|
||||
pub def interpreter::end_threads(&mut this, ran: halt): halt {
|
||||
return ran if this.threads == null;
|
||||
val shared := this.threads;
|
||||
var result := ran;
|
||||
if shared[0].stopped {
|
||||
result = shared[0].stop;
|
||||
if result != halt::exited {
|
||||
this.trace = move(&mut shared[0].trace);
|
||||
}
|
||||
} else {
|
||||
shared[0].stopped = true;
|
||||
shared[0].stop = ran == halt::none ? halt::exited : ran;
|
||||
}
|
||||
|
||||
val mine := this.strand;
|
||||
var tries := 0u;
|
||||
while shared[0].running > 0 && tries < 3000 {
|
||||
this.pause();
|
||||
time::sleep(time::milliseconds(1));
|
||||
_ = this.resume(mine);
|
||||
tries++;
|
||||
}
|
||||
if shared[0].running > 0 {
|
||||
return result;
|
||||
}
|
||||
# Every thread has ended, so joining each waits for no more than its end.
|
||||
shared[0].handles.close();
|
||||
shared[0].strands.close();
|
||||
shared[0].trace.close();
|
||||
mine[0].clock.close();
|
||||
raw_release(mine as *mut u8);
|
||||
raw_release(shared as *mut u8);
|
||||
this.threads = null;
|
||||
this.strand = null;
|
||||
this.countdown = 0;
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
#! @file x86.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the instructions of x86-64 that `jit.sakura` compiles functions to,
|
||||
#! each encoded into the bytes of the code being made: moves, arithmetic, and
|
||||
#! comparisons of words in registers and in memory, through a base register and
|
||||
#! a displacement; jumps and calls; and the SSE2 arithmetic of doubles. A
|
||||
#! register is its number in the encoding, so `r8` to `r15` set a REX bit.
|
||||
|
||||
module sakura::machine;
|
||||
|
||||
|
||||
# The general registers, numbered as the encoding numbers them.
|
||||
const rax: u8 = 0;
|
||||
const rcx: u8 = 1;
|
||||
const rdx: u8 = 2;
|
||||
const rbx: u8 = 3;
|
||||
const rsp: u8 = 4;
|
||||
const rbp: u8 = 5;
|
||||
const rsi: u8 = 6;
|
||||
const rdi: u8 = 7;
|
||||
const r8: u8 = 8;
|
||||
const r9: u8 = 9;
|
||||
const r10: u8 = 10;
|
||||
const r11: u8 = 11;
|
||||
const r12: u8 = 12;
|
||||
const r13: u8 = 13;
|
||||
const r14: u8 = 14;
|
||||
const r15: u8 = 15;
|
||||
|
||||
# The conditions of `jcc`, `setcc`, and `cmovcc`, as the encoding numbers them.
|
||||
const cc_b: u8 = 0x2; #! Below, unsigned.
|
||||
const cc_ae: u8 = 0x3; #! Above or equal, unsigned.
|
||||
const cc_e: u8 = 0x4; #! Equal.
|
||||
const cc_ne: u8 = 0x5; #! Not equal.
|
||||
const cc_be: u8 = 0x6; #! Below or equal, unsigned.
|
||||
const cc_a: u8 = 0x7; #! Above, unsigned.
|
||||
const cc_s: u8 = 0x8; #! Sign.
|
||||
const cc_p: u8 = 0xA; #! Parity, as an unordered comparison of reals sets.
|
||||
const cc_np: u8 = 0xB; #! No parity.
|
||||
const cc_l: u8 = 0xC; #! Less, signed.
|
||||
const cc_ge: u8 = 0xD; #! Greater or equal, signed.
|
||||
const cc_le: u8 = 0xE; #! Less or equal, signed.
|
||||
const cc_g: u8 = 0xF; #! Greater, signed.
|
||||
|
||||
# The extensions of the instructions of a register or memory and an immediate,
|
||||
# which pick the operation.
|
||||
const alu_add: u8 = 0;
|
||||
const alu_or: u8 = 1;
|
||||
const alu_and: u8 = 4;
|
||||
const alu_sub: u8 = 5;
|
||||
const alu_xor: u8 = 6;
|
||||
const alu_cmp: u8 = 7;
|
||||
|
||||
# The extensions of the shifts.
|
||||
const shift_left: u8 = 4;
|
||||
const shift_right: u8 = 5;
|
||||
const shift_arithmetic: u8 = 7;
|
||||
|
||||
#! The bytes of code being made.
|
||||
struct machine_code : owning {
|
||||
var bytes: vector<u8>;
|
||||
}
|
||||
|
||||
#! Empty code.
|
||||
#! @returns The code.
|
||||
def machine_code::new(): machine_code {
|
||||
return machine_code { bytes = vector::<u8>::new() };
|
||||
}
|
||||
|
||||
#! How many bytes the code has.
|
||||
val machine_code::length: u64 {
|
||||
get => this.bytes.length;
|
||||
}
|
||||
|
||||
def machine_code::close(&mut this): void {
|
||||
this.bytes.close();
|
||||
}
|
||||
|
||||
#! Adds a byte.
|
||||
def machine_code::byte(&mut this, value: u64): void {
|
||||
this.bytes.append(value as u8);
|
||||
}
|
||||
|
||||
#! Adds four bytes, the low first.
|
||||
def machine_code::u32(&mut this, value: u64): void {
|
||||
for i in 0..4u {
|
||||
this.bytes.append((value >> (8 * i)) as u8);
|
||||
}
|
||||
}
|
||||
|
||||
#! Adds eight bytes, the low first.
|
||||
def machine_code::u64(&mut this, value: u64): void {
|
||||
for i in 0..8u {
|
||||
this.bytes.append((value >> (8 * i)) as u8);
|
||||
}
|
||||
}
|
||||
|
||||
#! Writes four bytes over those at a place, the low first.
|
||||
def machine_code::patch32(&mut this, at: u64, value: u64): void {
|
||||
for i in 0..4u {
|
||||
this.bytes.set(at + i, (value >> (8 * i)) as u8);
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether a word is a 32-bit immediate's sign extension.
|
||||
def fits32(value: u64): bool {
|
||||
val signed := value as i64;
|
||||
return signed >= -2147483648 && signed <= 2147483647;
|
||||
}
|
||||
|
||||
#! Whether a word is an 8-bit immediate's sign extension.
|
||||
def fits8(value: u64): bool {
|
||||
val signed := value as i64;
|
||||
return signed >= -128 && signed <= 127;
|
||||
}
|
||||
|
||||
# The REX prefix: `w` for 64 bits, then the high bits of the register field, the
|
||||
# index, and the base. One is written where any is set, or where `byte` asks,
|
||||
# as reaching `spl` to `dil` as bytes does.
|
||||
def machine_code::rex(&mut this, w: bool, reg: u8, index: u8, base: u8, byte: bool): void {
|
||||
var made: u64 = 0x40;
|
||||
if w { made = made | 8; }
|
||||
if reg >= 8 { made = made | 4; }
|
||||
if index >= 8 { made = made | 2; }
|
||||
if base >= 8 { made = made | 1; }
|
||||
if made != 0x40 || (byte && (reg >= 4 || base >= 4)) {
|
||||
this.byte(made);
|
||||
}
|
||||
}
|
||||
|
||||
# The ModRM byte and what follows it for memory at a base and a displacement,
|
||||
# the register field `reg`: the shortest displacement, a SIB byte for `rsp` and
|
||||
# `r12`, and a displacement always for `rbp` and `r13`.
|
||||
def machine_code::memory(&mut this, reg: u8, base: u8, disp: u64): void {
|
||||
val r := (reg & 7) as u64;
|
||||
val b := (base & 7) as u64;
|
||||
if disp == 0 && b != 5 {
|
||||
this.byte((r << 3) | b);
|
||||
if b == 4 { this.byte(0x24); }
|
||||
} else if fits8(disp) {
|
||||
this.byte(0x40 | (r << 3) | b);
|
||||
if b == 4 { this.byte(0x24); }
|
||||
this.byte(disp & 0xFF);
|
||||
} else {
|
||||
this.byte(0x80 | (r << 3) | b);
|
||||
if b == 4 { this.byte(0x24); }
|
||||
this.u32(disp);
|
||||
}
|
||||
}
|
||||
|
||||
# The ModRM byte of two registers.
|
||||
def machine_code::registers(&mut this, reg: u8, rm: u8): void {
|
||||
this.byte(0xC0 | (((reg & 7) as u64) << 3) | (rm & 7) as u64);
|
||||
}
|
||||
|
||||
# An instruction of a register and memory: its prefix, if any, REX, its opcode
|
||||
# bytes, then the memory.
|
||||
def machine_code::op_mem(&mut this, prefix: u64, w: bool, opcode: u64, reg: u8, base: u8, disp: u64): void {
|
||||
if prefix != 0 { this.byte(prefix); }
|
||||
this.rex(w, reg, 0, base, false);
|
||||
if opcode > 0xFF { this.byte(opcode >> 8); }
|
||||
this.byte(opcode & 0xFF);
|
||||
this.memory(reg, base, disp);
|
||||
}
|
||||
|
||||
# An instruction of two registers, likewise.
|
||||
def machine_code::op_reg(&mut this, prefix: u64, w: bool, opcode: u64, reg: u8, rm: u8): void {
|
||||
if prefix != 0 { this.byte(prefix); }
|
||||
this.rex(w, reg, 0, rm, false);
|
||||
if opcode > 0xFF { this.byte(opcode >> 8); }
|
||||
this.byte(opcode & 0xFF);
|
||||
this.registers(reg, rm);
|
||||
}
|
||||
|
||||
#! `mov reg, [base + disp]`.
|
||||
def machine_code::load(&mut this, reg: u8, base: u8, disp: u64): void {
|
||||
this.op_mem(0, true, 0x8B, reg, base, disp);
|
||||
}
|
||||
|
||||
#! `mov [base + disp], reg`.
|
||||
def machine_code::store(&mut this, base: u8, disp: u64, reg: u8): void {
|
||||
this.op_mem(0, true, 0x89, reg, base, disp);
|
||||
}
|
||||
|
||||
#! `mov qword [base + disp], imm32`, sign extended.
|
||||
def machine_code::store_imm(&mut this, base: u8, disp: u64, imm: u64): void {
|
||||
this.op_mem(0, true, 0xC7, 0, base, disp);
|
||||
this.u32(imm);
|
||||
}
|
||||
|
||||
#! `mov to, from`.
|
||||
def machine_code::mov(&mut this, to: u8, from: u8): void {
|
||||
this.op_reg(0, true, 0x89, from, to);
|
||||
}
|
||||
|
||||
#! A word into a register, by the shortest encoding.
|
||||
def machine_code::mov_imm(&mut this, reg: u8, value: u64): void {
|
||||
if value <= 0xFFFFFFFF {
|
||||
this.rex(false, 0, 0, reg, false);
|
||||
this.byte(0xB8 + (reg & 7) as u64);
|
||||
this.u32(value);
|
||||
} else if fits32(value) {
|
||||
this.rex(true, 0, 0, reg, false);
|
||||
this.byte(0xC7);
|
||||
this.registers(0, reg);
|
||||
this.u32(value);
|
||||
} else {
|
||||
this.rex(true, 0, 0, reg, false);
|
||||
this.byte(0xB8 + (reg & 7) as u64);
|
||||
this.u64(value);
|
||||
}
|
||||
}
|
||||
|
||||
#! `mov rax, [address]`, of an address of 64 bits.
|
||||
def machine_code::load_rax_absolute(&mut this, address: u64): void {
|
||||
this.byte(0x48);
|
||||
this.byte(0xA1);
|
||||
this.u64(address);
|
||||
}
|
||||
|
||||
#! `lea reg, [base + disp]`.
|
||||
def machine_code::lea(&mut this, reg: u8, base: u8, disp: u64): void {
|
||||
this.op_mem(0, true, 0x8D, reg, base, disp);
|
||||
}
|
||||
|
||||
#! `lea reg, [base + index * 2^scale]`.
|
||||
def machine_code::lea_index(&mut this, reg: u8, base: u8, index: u8, scale: u64): void {
|
||||
this.rex(true, reg, index, base, false);
|
||||
this.byte(0x8D);
|
||||
if (base & 7) == 5 {
|
||||
this.byte(0x44 | (((reg & 7) as u64) << 3));
|
||||
this.byte((scale << 6) | (((index & 7) as u64) << 3) | (base & 7) as u64);
|
||||
this.byte(0);
|
||||
} else {
|
||||
this.byte(0x04 | (((reg & 7) as u64) << 3));
|
||||
this.byte((scale << 6) | (((index & 7) as u64) << 3) | (base & 7) as u64);
|
||||
}
|
||||
}
|
||||
|
||||
#! An arithmetic of two registers: `add`, `or`, `and`, `sub`, `xor`, or `cmp`, by
|
||||
#! its extension.
|
||||
def machine_code::alu(&mut this, ext: u8, to: u8, from: u8): void {
|
||||
this.op_reg(0, true, (ext as u64) * 8 + 1, from, to);
|
||||
}
|
||||
|
||||
#! An arithmetic of a register and memory, the register written.
|
||||
def machine_code::alu_mem(&mut this, ext: u8, reg: u8, base: u8, disp: u64): void {
|
||||
this.op_mem(0, true, (ext as u64) * 8 + 3, reg, base, disp);
|
||||
}
|
||||
|
||||
#! An arithmetic of a register and an immediate, sign extended from 32 bits.
|
||||
def machine_code::alu_imm(&mut this, ext: u8, reg: u8, imm: u64): void {
|
||||
this.rex(true, 0, 0, reg, false);
|
||||
if fits8(imm) {
|
||||
this.byte(0x83);
|
||||
this.registers(ext, reg);
|
||||
this.byte(imm & 0xFF);
|
||||
} else {
|
||||
this.byte(0x81);
|
||||
this.registers(ext, reg);
|
||||
this.u32(imm);
|
||||
}
|
||||
}
|
||||
|
||||
#! An arithmetic of memory and an immediate, sign extended from 32 bits.
|
||||
def machine_code::alu_mem_imm(&mut this, ext: u8, base: u8, disp: u64, imm: u64): void {
|
||||
if fits8(imm) {
|
||||
this.op_mem(0, true, 0x83, ext, base, disp);
|
||||
this.byte(imm & 0xFF);
|
||||
} else {
|
||||
this.op_mem(0, true, 0x81, ext, base, disp);
|
||||
this.u32(imm);
|
||||
}
|
||||
}
|
||||
|
||||
#! `test a, b`.
|
||||
def machine_code::test(&mut this, a: u8, b: u8): void {
|
||||
this.op_reg(0, true, 0x85, b, a);
|
||||
}
|
||||
|
||||
#! `test eax, eax`.
|
||||
def machine_code::test_status(&mut this): void {
|
||||
this.byte(0x85);
|
||||
this.byte(0xC0);
|
||||
}
|
||||
|
||||
#! `imul reg, from`.
|
||||
def machine_code::imul(&mut this, reg: u8, from: u8): void {
|
||||
this.op_reg(0, true, 0x0FAF, reg, from);
|
||||
}
|
||||
|
||||
#! `imul reg, [base + disp]`.
|
||||
def machine_code::imul_mem(&mut this, reg: u8, base: u8, disp: u64): void {
|
||||
this.op_mem(0, true, 0x0FAF, reg, base, disp);
|
||||
}
|
||||
|
||||
#! `imul reg, from, imm32`.
|
||||
def machine_code::imul_imm(&mut this, reg: u8, from: u8, imm: u64): void {
|
||||
this.op_reg(0, true, 0x69, reg, from);
|
||||
this.u32(imm);
|
||||
}
|
||||
|
||||
#! A shift of a register by `cl`.
|
||||
def machine_code::shift_cl(&mut this, ext: u8, reg: u8): void {
|
||||
this.op_reg(0, true, 0xD3, ext, reg);
|
||||
}
|
||||
|
||||
#! A shift of a register by an immediate.
|
||||
def machine_code::shift_imm(&mut this, ext: u8, reg: u8, count: u64): void {
|
||||
this.op_reg(0, true, 0xC1, ext, reg);
|
||||
this.byte(count & 0xFF);
|
||||
}
|
||||
|
||||
#! An operation of one register, `F7` and its extension: `not` 2, `neg` 3, `div`
|
||||
#! 6, and `idiv` 7.
|
||||
def machine_code::unary(&mut this, ext: u8, reg: u8): void {
|
||||
this.op_reg(0, true, 0xF7, ext, reg);
|
||||
}
|
||||
|
||||
#! `cqo`.
|
||||
def machine_code::cqo(&mut this): void {
|
||||
this.byte(0x48);
|
||||
this.byte(0x99);
|
||||
}
|
||||
|
||||
#! `setcc al`, then `movzx eax, al`.
|
||||
def machine_code::set_rax(&mut this, cc: u8): void {
|
||||
this.byte(0x0F);
|
||||
this.byte(0x90 + cc as u64);
|
||||
this.byte(0xC0);
|
||||
this.byte(0x0F);
|
||||
this.byte(0xB6);
|
||||
this.byte(0xC0);
|
||||
}
|
||||
|
||||
#! `setcc` of the low byte of `rax`, `rcx`, or `rdx`.
|
||||
def machine_code::set_low(&mut this, cc: u8, reg: u8): void {
|
||||
this.byte(0x0F);
|
||||
this.byte(0x90 + cc as u64);
|
||||
this.byte(0xC0 + reg as u64);
|
||||
}
|
||||
|
||||
#! `cmovcc to, from`.
|
||||
def machine_code::cmov(&mut this, cc: u8, to: u8, from: u8): void {
|
||||
this.op_reg(0, true, 0x0F40 + cc as u64, to, from);
|
||||
}
|
||||
|
||||
#! `btc reg, 63`, which turns a double's sign.
|
||||
def machine_code::flip_sign(&mut this, reg: u8): void {
|
||||
this.op_reg(0, true, 0x0FBA, 7, reg);
|
||||
this.byte(63);
|
||||
}
|
||||
|
||||
#! `popcnt`, `bsr`, or `bsf` of a register, by its second opcode byte.
|
||||
def machine_code::bits(&mut this, prefix: u64, opcode: u64, to: u8, from: u8): void {
|
||||
this.op_reg(prefix, true, 0x0F00 + opcode, to, from);
|
||||
}
|
||||
|
||||
#! `bswap reg`.
|
||||
def machine_code::bswap(&mut this, reg: u8): void {
|
||||
this.rex(true, 0, 0, reg, false);
|
||||
this.byte(0x0F);
|
||||
this.byte(0xC8 + (reg & 7) as u64);
|
||||
}
|
||||
|
||||
#! A load narrower than a word, by its opcode: `movzx` and `movsx` of bytes and
|
||||
#! halves, `mov` of 32 bits, which clears the high half, or `movsxd`.
|
||||
def machine_code::load_narrow(&mut this, opcode: u64, w: bool, reg: u8, base: u8, disp: u64): void {
|
||||
this.op_mem(0, w, opcode, reg, base, disp);
|
||||
}
|
||||
|
||||
#! A store of the low bytes of a register: 1, 2, or 4.
|
||||
def machine_code::store_narrow(&mut this, size: u64, base: u8, disp: u64, reg: u8): void {
|
||||
if size == 2 { this.byte(0x66); }
|
||||
this.rex(false, reg, 0, base, size == 1);
|
||||
this.byte(size == 1 ? 0x88 : 0x89);
|
||||
this.memory(reg, base, disp);
|
||||
}
|
||||
|
||||
#! A store of an immediate of 1, 2, or 4 bytes.
|
||||
def machine_code::store_narrow_imm(&mut this, size: u64, base: u8, disp: u64, imm: u64): void {
|
||||
if size == 2 { this.byte(0x66); }
|
||||
this.rex(false, 0, 0, base, false);
|
||||
this.byte(size == 1 ? 0xC6 : 0xC7);
|
||||
this.memory(0, base, disp);
|
||||
if size == 1 {
|
||||
this.byte(imm & 0xFF);
|
||||
} else if size == 2 {
|
||||
this.byte(imm & 0xFF);
|
||||
this.byte((imm >> 8) & 0xFF);
|
||||
} else {
|
||||
this.u32(imm);
|
||||
}
|
||||
}
|
||||
|
||||
#! An SSE instruction of an XMM register and memory: `movsd` loads with `F2 10`,
|
||||
#! stores with `F2 11`, and the arithmetic of doubles.
|
||||
def machine_code::sse_mem(&mut this, prefix: u64, opcode: u64, xmm: u8, base: u8, disp: u64): void {
|
||||
this.op_mem(prefix, false, 0x0F00 + opcode, xmm, base, disp);
|
||||
}
|
||||
|
||||
#! `movaps to, from`, copying the whole of an XMM register.
|
||||
def machine_code::movaps(&mut this, to: u8, from: u8): void {
|
||||
return if to == from;
|
||||
this.op_reg(0, false, 0x0F28, to, from);
|
||||
}
|
||||
|
||||
#! `movdqu [base + disp], xmm`, keeping the whole of a register.
|
||||
def machine_code::save_xmm(&mut this, base: u8, disp: u64, xmm: u8): void {
|
||||
this.op_mem(0xF3, false, 0x0F7F, xmm, base, disp);
|
||||
}
|
||||
|
||||
#! `movdqu xmm, [base + disp]`.
|
||||
def machine_code::restore_xmm(&mut this, xmm: u8, base: u8, disp: u64): void {
|
||||
this.op_mem(0xF3, false, 0x0F6F, xmm, base, disp);
|
||||
}
|
||||
|
||||
#! An SSE instruction of two XMM registers.
|
||||
def machine_code::sse_reg(&mut this, prefix: u64, opcode: u64, to: u8, from: u8): void {
|
||||
this.op_reg(prefix, false, 0x0F00 + opcode, to, from);
|
||||
}
|
||||
|
||||
#! `movq xmm, reg`.
|
||||
def machine_code::movq_to_xmm(&mut this, xmm: u8, reg: u8): void {
|
||||
this.op_reg(0x66, true, 0x0F6E, xmm, reg);
|
||||
}
|
||||
|
||||
#! `movq reg, xmm`.
|
||||
def machine_code::movq_from_xmm(&mut this, reg: u8, xmm: u8): void {
|
||||
this.op_reg(0x66, true, 0x0F7E, xmm, reg);
|
||||
}
|
||||
|
||||
#! `cvtsi2sd xmm, reg`.
|
||||
def machine_code::cvtsi2sd(&mut this, xmm: u8, reg: u8): void {
|
||||
this.op_reg(0xF2, true, 0x0F2A, xmm, reg);
|
||||
}
|
||||
|
||||
#! `cvttsd2si reg, xmm`.
|
||||
def machine_code::cvttsd2si(&mut this, reg: u8, xmm: u8): void {
|
||||
this.op_reg(0xF2, true, 0x0F2C, reg, xmm);
|
||||
}
|
||||
|
||||
#! `jcc rel32` to a place not yet known, giving where its displacement is.
|
||||
def machine_code::jcc(&mut this, cc: u8): u64 {
|
||||
this.byte(0x0F);
|
||||
this.byte(0x80 + cc as u64);
|
||||
val at := this.length;
|
||||
this.u32(0);
|
||||
return at;
|
||||
}
|
||||
|
||||
#! `jmp rel32` to a place not yet known, giving where its displacement is.
|
||||
def machine_code::jmp(&mut this): u64 {
|
||||
this.byte(0xE9);
|
||||
val at := this.length;
|
||||
this.u32(0);
|
||||
return at;
|
||||
}
|
||||
|
||||
#! Points the displacement of a jump at a place in the code.
|
||||
def machine_code::land(&mut this, at: u64, target: u64): void {
|
||||
this.patch32(at, (target - (at + 4)) & 0xFFFFFFFF);
|
||||
}
|
||||
|
||||
#! `call reg`.
|
||||
def machine_code::call_reg(&mut this, reg: u8): void {
|
||||
this.rex(false, 0, 0, reg, false);
|
||||
this.byte(0xFF);
|
||||
this.registers(2, reg);
|
||||
}
|
||||
|
||||
#! Calls a function at an address through `rax`.
|
||||
def machine_code::call_absolute(&mut this, address: u64): void {
|
||||
this.mov_imm(rax, address);
|
||||
this.call_reg(rax);
|
||||
}
|
||||
|
||||
#! `ret`.
|
||||
def machine_code::ret(&mut this): void {
|
||||
this.byte(0xC3);
|
||||
}
|
||||
|
||||
#! `push reg`.
|
||||
def machine_code::push(&mut this, reg: u8): void {
|
||||
if reg >= 8 { this.byte(0x41); }
|
||||
this.byte(0x50 + (reg & 7) as u64);
|
||||
}
|
||||
|
||||
#! `pop reg`.
|
||||
def machine_code::pop(&mut this, reg: u8): void {
|
||||
if reg >= 8 { this.byte(0x41); }
|
||||
this.byte(0x58 + (reg & 7) as u64);
|
||||
}
|
||||
Reference in new issue
Block a user