846 lines
34 KiB
Plaintext
846 lines
34 KiB
Plaintext
#! @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();
|
||
|
|
}
|
||
|
|
}
|