Initial Commit
This commit is contained in:
782 files changed
+145156
No files matched your search
@@ -0,0 +1,231 @@
|
||||
#! @file abi.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what the runtime of an executable shares with the code the compiler
|
||||
#! generates: the intrinsics it calls the kernel and stops with, and the records
|
||||
#! the compiler writes the program's layouts, functions, and globals in.
|
||||
#!
|
||||
#! The runtime of executables made by `sakura build`, which is compiled into
|
||||
#! each of them. It is a library of its own, found beside the compiler as
|
||||
#! `core` is, and reads `core` alone. Each of its files says
|
||||
#! `when backend == native`, so it is no part of a program a machine runs,
|
||||
#! which does what it does itself. It formats no text itself, since that is
|
||||
#! what it does for the program, and works through pointers. Values may be
|
||||
#! allocated before `<globals>` runs, so the runtime's `val`s are numbers known
|
||||
#! while compiling, which globals begin with, and its `var`s begin as zeros and
|
||||
#! are set up on first use.
|
||||
|
||||
module runtime when backend == native;
|
||||
|
||||
#! The version of what the runtime shares with the code the compiler
|
||||
#! generates: the helpers it calls, the words of `state`, and the records it
|
||||
#! writes. A compiler builds only with a runtime of the ABI it calls, which
|
||||
#! changes whenever any of those does, so one of another release is refused
|
||||
#! rather than misread.
|
||||
pub const abi: u32 = 1;
|
||||
|
||||
#! Calls the kernel, giving the negated error number when the call fails.
|
||||
#! @param n The number of the system call.
|
||||
#! @param a Its first argument.
|
||||
#! @param b Its second argument.
|
||||
#! @param c Its third argument.
|
||||
#! @param d Its fourth argument.
|
||||
#! @param e Its fifth argument.
|
||||
#! @param f Its sixth argument.
|
||||
#! @returns What the kernel gives, which is the negated error number where the
|
||||
#! call fails.
|
||||
@intrinsic def syscall(n: i64, a: u64, b: u64, c: u64, d: u64, e: u64, f: u64): i64;
|
||||
|
||||
#! The frame of the calling function.
|
||||
#! @returns The frame's first byte.
|
||||
@intrinsic def frame(): *mut u8;
|
||||
|
||||
# The record of the running thread, which `gs` points at.
|
||||
@intrinsic def current(): *mut state;
|
||||
|
||||
# Starts a thread of the system on the record's stack, which runs `thread_main`
|
||||
# there, giving its number, or a negative error number.
|
||||
@intrinsic def clone_thread(record: *mut state): i64;
|
||||
|
||||
#! Stops the program with the error, reporting where it happened.
|
||||
#! @param code The error, as the machine numbers them.
|
||||
#! @remarks It does not return.
|
||||
@intrinsic def trap(code: i64): void;
|
||||
|
||||
#! An array of its parts, without copying them.
|
||||
|
||||
#! The image the executable was built with.
|
||||
#! @returns The image, which lives as long as the program does.
|
||||
@intrinsic def executable(): *image;
|
||||
|
||||
# The records an executable is built with, which `native/native.sakura` writes.
|
||||
# Every field is a word, so the compiler places them where the builder does, but
|
||||
# for those of the line tables, which are as narrow as what they hold allows.
|
||||
|
||||
struct layout {
|
||||
var kind: u64; #! A `layout_kind` of `sources/program.h`.
|
||||
var access: u64; #! An `access` of `sources/program.h`.
|
||||
var bits: u64;
|
||||
var size: u64;
|
||||
var align: u64;
|
||||
var frame: u64;
|
||||
var element: *layout; #! Of an array.
|
||||
var fields: *field;
|
||||
var count: u64;
|
||||
var flags: u64; #! `layout_niche`, `layout_texts`, and `layout_views`.
|
||||
var name: *u8;
|
||||
var name_length: u64;
|
||||
}
|
||||
|
||||
#! Set where a union is laid out without a tag: it holds its field of bytes where
|
||||
#! its first word is not null, and its empty one where it is.
|
||||
val layout_niche := 2u;
|
||||
|
||||
#! Set where the value is text, written as the bytes it holds rather than as its
|
||||
#! fields. The field saying where they begin is at `flags >> 8`, and the one
|
||||
#! saying how many there are is the field after it.
|
||||
val layout_texts := 4u;
|
||||
val layout_views := 8u;
|
||||
val layout_text_at := 8u;
|
||||
|
||||
struct field {
|
||||
var layout: *layout;
|
||||
var offset: u64;
|
||||
var name: *u8;
|
||||
var name_length: u64;
|
||||
}
|
||||
|
||||
# Where the code of a function from an offset on was written: the line and
|
||||
# column, the path among the image's, and one more than the site of the function
|
||||
# inlined there it was the code of, or 0.
|
||||
struct line {
|
||||
var offset: u32;
|
||||
var line: u32;
|
||||
var column: u16;
|
||||
var path: u16;
|
||||
var site: u32;
|
||||
}
|
||||
|
||||
# Where a function's code was inlined within another's: the function inlined,
|
||||
# where it was called, and one more than the site that call is within, or 0 for
|
||||
# the function's own code.
|
||||
struct site {
|
||||
var function: u32;
|
||||
var line: u32;
|
||||
var column: u16;
|
||||
var path: u16;
|
||||
var parent: u32;
|
||||
}
|
||||
|
||||
struct function {
|
||||
var start: u64;
|
||||
var end: u64;
|
||||
var name: *u8;
|
||||
var name_length: u64;
|
||||
var lines: *line;
|
||||
var line_count: u64;
|
||||
var runtime: u64; #! Whether it belongs to the runtime, which traces leave out.
|
||||
}
|
||||
|
||||
struct text {
|
||||
var bytes: *u8;
|
||||
var length: u64;
|
||||
}
|
||||
|
||||
# A thread's record, which `gs` points at in the thread, as `native/native.sakura`
|
||||
# lays it out: the first thread's is the executable's state, written by its start
|
||||
# before the runtime starts, which also holds what every thread shares, and every
|
||||
# other is mapped where the thread starts. The records are a list from the first.
|
||||
struct state {
|
||||
var shadow_base: *mut u8; #! The top of the stack, where frames begin.
|
||||
var shadow_limit: *mut u8; #! The lowest a frame may reach.
|
||||
var trap_frame: *mut u8; #! The bottom of the stack, past the limit, which a trap's report may use.
|
||||
var itself: *mut state; #! The record itself.
|
||||
var argc: u64; #! The arguments the program started with, in the first.
|
||||
var argv: *mut u64;
|
||||
var reporting: u64; #! Whether a trap is being reported, in the first.
|
||||
var c_top: u64;
|
||||
var c_frame: u64; #! Where the program called C last.
|
||||
var c_return: u64;
|
||||
var features: u64; #! The vector instructions the program uses, in the first.
|
||||
var signals: u64; #! The signals noted, in the first, and none in the others.
|
||||
var spare_word: u64;
|
||||
var next: *mut state; #! The next thread's record.
|
||||
var tid: u64; #! The system's number for the thread, cleared by the system as it ends.
|
||||
var cache: *mut block_cache; #! The blocks it takes and gives back without the lock, once there are threads.
|
||||
var builders: *mut builder; #! The text being formatted, innermost last.
|
||||
var builder_count: u64;
|
||||
var builder_capacity: u64;
|
||||
var body: def(*mut u8): void; #! The function the thread runs, and the context it is given.
|
||||
var context: *mut u8;
|
||||
var map: *mut u8; #! Where its stack is mapped, and its bytes.
|
||||
var map_size: u64;
|
||||
var spare_map: u64[2];
|
||||
var running: u64; #! 1 while it runs, and 0 once its function has returned.
|
||||
var spare: u64[5];
|
||||
}
|
||||
|
||||
struct image {
|
||||
var state: *mut state;
|
||||
var layouts: *layout;
|
||||
var layout_count: u64;
|
||||
var functions: *function;
|
||||
var function_count: u64;
|
||||
var texts: *text;
|
||||
var text_count: u64;
|
||||
var globals: *mut u8;
|
||||
var globals_size: u64;
|
||||
var spare_image: u64;
|
||||
var vtables: **layout; #! Of what each vtable's trait references refer to.
|
||||
var vtable_count: u64;
|
||||
var paths: *text; #! The paths the line tables name.
|
||||
var sites: *site; #! Where the functions inlined were, which the line tables name.
|
||||
}
|
||||
|
||||
# The texts of an image, where those before `text_out_of_memory` describe the
|
||||
# errors of `machine_error` in `include/malunal/sakura.h` by their codes.
|
||||
val error_aborted: i64 = 21; # `MACHINE_ERROR_ABORTED`, what `abort` reports with.
|
||||
val error_faulted: i64 = 26; # What `fault` reports with, before the text it was given.
|
||||
val text_out_of_memory := 31u;
|
||||
val text_prefix := 32u; # `sakura: runtime error: `
|
||||
val text_at := 33u; # ` at `
|
||||
val text_open := 34u; # ` (`
|
||||
val text_colon := 35u; # `:`
|
||||
val text_close := 36u; # `)` and a new line
|
||||
val text_newline := 37u;
|
||||
|
||||
# Errors the runtime traps with, the codes of `machine_error`.
|
||||
val error_out_of_bounds: i64 = 4;
|
||||
val error_null_reference: i64 = 5;
|
||||
val error_division: i64 = 6;
|
||||
val error_invalid_release: i64 = 11;
|
||||
val error_invalid_alignment: i64 = 14;
|
||||
val error_out_of_memory: i64 = 31;
|
||||
|
||||
# The layout kinds of `sources/program.h`.
|
||||
val kind_void := 0u;
|
||||
val kind_int := 1u;
|
||||
val kind_uint := 2u;
|
||||
val kind_float := 3u;
|
||||
val kind_bool := 4u;
|
||||
val kind_reference := 5u;
|
||||
val kind_trait := 6u;
|
||||
val kind_fixed := 7u;
|
||||
val kind_struct := 8u;
|
||||
val kind_union := 9u;
|
||||
val kind_function := 10u;
|
||||
val kind_pointer := 11u;
|
||||
|
||||
# The accesses of `sources/program.h`.
|
||||
val access_i8 := 0u;
|
||||
val access_u8 := 1u;
|
||||
val access_i16 := 2u;
|
||||
val access_u16 := 3u;
|
||||
val access_i32 := 4u;
|
||||
val access_u32 := 5u;
|
||||
val access_i64 := 6u;
|
||||
val access_f32 := 7u;
|
||||
val access_f64 := 8u;
|
||||
val access_bytes := 9u;
|
||||
@@ -0,0 +1,592 @@
|
||||
#! @file float.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how an executable formats a float, as the virtual machine does.
|
||||
#!
|
||||
#! Formats a float as `machine__format_float` of `sources/machine.c` does with
|
||||
#! the C library: whole numbers below 1e15 as integers, and otherwise the
|
||||
#! shortest `%.*g` text, from 1 to 17 digits, that reads back as the same value.
|
||||
#! The digits are exact, from arithmetic on big integers, rounded half to even
|
||||
#! as `printf` rounds them, and reading back rounds to the nearest double as
|
||||
#! `strtod` does.
|
||||
|
||||
module runtime when backend == native;
|
||||
|
||||
# Big integers are words in memory: their number of limbs, then the limbs, each
|
||||
# holding 32 bits from the least significant.
|
||||
val limbs := 128u;
|
||||
val limb := 4294967296u;
|
||||
|
||||
var big_n: *mut u64;
|
||||
var big_d: *mut u64;
|
||||
var big_c: *mut u64;
|
||||
var big_t: *mut u64;
|
||||
var big_u: *mut u64; # The midpoint above the value, scaled as it is.
|
||||
var big_l: *mut u64; # The midpoint below it.
|
||||
var big_m: *mut u64; # A margin around the midpoints, for single precision.
|
||||
var big_q: *mut u64;
|
||||
|
||||
# Room for rounding a decimal exactly, apart from the digits being checked.
|
||||
var exact_n: *mut u64;
|
||||
var exact_d: *mut u64;
|
||||
var exact_c: *mut u64;
|
||||
var exact_t: *mut u64;
|
||||
|
||||
# The digits of the value, which are 18 so any precision can be rounded, and
|
||||
# whether any digit after them would not be zero.
|
||||
var digits: *mut u8;
|
||||
var sticky: bool;
|
||||
|
||||
var float_bits: u64;
|
||||
|
||||
def big(): *mut u64 {
|
||||
return acquire((limbs + 1) * 8) as *mut u64;
|
||||
}
|
||||
|
||||
def big_trim(a: *mut u64): void {
|
||||
while a[0] > 0 && a[a[0]] == 0 {
|
||||
a[0] = a[0] - 1;
|
||||
}
|
||||
}
|
||||
|
||||
def big_set(a: *mut u64, value: u64): void {
|
||||
a[0] = 2;
|
||||
a[1] = value % limb;
|
||||
a[2] = value / limb;
|
||||
big_trim(a);
|
||||
}
|
||||
|
||||
def big_copy(a: *mut u64, b: *mut u64): void {
|
||||
for i in 0..b[0] + 1 {
|
||||
a[i] = b[i];
|
||||
}
|
||||
}
|
||||
|
||||
def big_mul_small(a: *mut u64, factor: u64): void {
|
||||
var carry := 0u;
|
||||
for i in 1..a[0] + 1 {
|
||||
val product := a[i] * factor + carry;
|
||||
a[i] = product % limb;
|
||||
carry = product / limb;
|
||||
}
|
||||
while carry > 0 {
|
||||
a[0] = a[0] + 1;
|
||||
a[a[0]] = carry % limb;
|
||||
carry = carry / limb;
|
||||
}
|
||||
}
|
||||
|
||||
def big_mul_ten(a: *mut u64, power: u64): void {
|
||||
var left := power;
|
||||
while left >= 9 {
|
||||
big_mul_small(a, 1000000000);
|
||||
left = left - 9;
|
||||
}
|
||||
while left > 0 {
|
||||
big_mul_small(a, 10);
|
||||
left--;
|
||||
}
|
||||
}
|
||||
|
||||
def big_shl(a: *mut u64, bits: u64): void {
|
||||
if a[0] == 0 {
|
||||
return;
|
||||
}
|
||||
val words := bits / 32;
|
||||
val shift := bits % 32;
|
||||
var i := a[0] + words + 1;
|
||||
while i > words {
|
||||
val index := i - words;
|
||||
val high := index <= a[0] ? a[index] : 0;
|
||||
val low := index - 1 >= 1 && index - 1 <= a[0] ? a[index - 1] : 0;
|
||||
a[i] = shift == 0 ? high : ((high << shift) | (low >> (32 - shift))) % limb;
|
||||
i--;
|
||||
}
|
||||
while i > 0 {
|
||||
a[i] = 0;
|
||||
i--;
|
||||
}
|
||||
a[0] = a[0] + words + 1;
|
||||
big_trim(a);
|
||||
}
|
||||
|
||||
def big_shr1(a: *mut u64): void {
|
||||
for i in 1..a[0] + 1 {
|
||||
val high := i < a[0] ? a[i + 1] : 0;
|
||||
a[i] = (a[i] >> 1) | ((high & 1) << 31);
|
||||
}
|
||||
big_trim(a);
|
||||
}
|
||||
|
||||
def big_compare(a: *mut u64, b: *mut u64): i64 {
|
||||
if a[0] != b[0] {
|
||||
return a[0] < b[0] ? -1 : 1;
|
||||
}
|
||||
var i := a[0];
|
||||
while i > 0 {
|
||||
if a[i] != b[i] {
|
||||
return a[i] < b[i] ? -1 : 1;
|
||||
}
|
||||
i--;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
# Subtracts `b` from `a`, which is at least `b`.
|
||||
def big_sub(a: *mut u64, b: *mut u64): void {
|
||||
var borrow := 0u;
|
||||
for i in 1..a[0] + 1 {
|
||||
val take := (i <= b[0] ? b[i] : 0) + borrow;
|
||||
if a[i] >= take {
|
||||
a[i] = a[i] - take;
|
||||
borrow = 0;
|
||||
}
|
||||
else {
|
||||
a[i] = a[i] + limb - take;
|
||||
borrow = 1;
|
||||
}
|
||||
}
|
||||
big_trim(a);
|
||||
}
|
||||
|
||||
def big_bits(a: *mut u64): u64 {
|
||||
if a[0] == 0 {
|
||||
return 0;
|
||||
}
|
||||
var top := a[a[0]];
|
||||
var count := (a[0] - 1) * 32;
|
||||
while top > 0 {
|
||||
count++;
|
||||
top = top >> 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
def bits_of(value: f64): u64 {
|
||||
((&mut float_bits) as *mut f64)[0] = value;
|
||||
return float_bits;
|
||||
}
|
||||
|
||||
def float_of(bits: u64): f64 {
|
||||
float_bits = bits;
|
||||
return ((&mut float_bits) as *mut f64)[0];
|
||||
}
|
||||
|
||||
def start_float(): void {
|
||||
if big_n != null {
|
||||
return;
|
||||
}
|
||||
big_n = big();
|
||||
big_d = big();
|
||||
big_c = big();
|
||||
big_t = big();
|
||||
big_u = big();
|
||||
big_l = big();
|
||||
big_m = big();
|
||||
big_q = big();
|
||||
exact_n = big();
|
||||
exact_d = big();
|
||||
exact_c = big();
|
||||
exact_t = big();
|
||||
digits = acquire(32);
|
||||
}
|
||||
|
||||
# Writes the first 18 digits of a positive finite value, `n` units of two to
|
||||
# `unit`, giving the decimal exponent of the first, so the value is `0.d1d2...`
|
||||
# times ten to it plus one. The midpoints `u` and `l` and the margin `m`, in the
|
||||
# same units, are scaled with the value, so they compare with it as it is written.
|
||||
def decimal_digits(unit: i64, binary: i64): i64 {
|
||||
big_set(big_d, 1);
|
||||
if unit >= 0 {
|
||||
big_shl(big_n, unit as u64);
|
||||
big_shl(big_u, unit as u64);
|
||||
big_shl(big_l, unit as u64);
|
||||
big_shl(big_m, unit as u64);
|
||||
}
|
||||
else {
|
||||
big_shl(big_d, (0 - unit) as u64);
|
||||
}
|
||||
|
||||
# An estimate of the decimal exponent, corrected so `1 <= n / d < 10`.
|
||||
var power := ((binary as f64) * 0.30102999566398114) as i64;
|
||||
if (binary as f64) * 0.30102999566398114 < power as f64 {
|
||||
power--;
|
||||
}
|
||||
if power >= 0 {
|
||||
big_mul_ten(big_d, power as u64);
|
||||
}
|
||||
else {
|
||||
scale_value(0 - power);
|
||||
}
|
||||
|
||||
while big_compare(big_n, big_d) < 0 {
|
||||
scale_value(1);
|
||||
power--;
|
||||
}
|
||||
big_copy(big_t, big_d);
|
||||
big_mul_small(big_t, 10);
|
||||
while big_compare(big_n, big_t) >= 0 {
|
||||
big_mul_small(big_d, 10);
|
||||
big_copy(big_t, big_d);
|
||||
big_mul_small(big_t, 10);
|
||||
power++;
|
||||
}
|
||||
|
||||
big_copy(big_t, big_n);
|
||||
for i in 0..18 {
|
||||
var digit: u8 = 0;
|
||||
while big_compare(big_t, big_d) >= 0 {
|
||||
big_sub(big_t, big_d);
|
||||
digit++;
|
||||
}
|
||||
digits[i] = digit;
|
||||
big_mul_small(big_t, 10);
|
||||
}
|
||||
sticky = big_t[0] != 0;
|
||||
return power;
|
||||
}
|
||||
|
||||
# Multiplies the value, its midpoints, and the margin by a power of ten.
|
||||
def scale_value(power: i64): void {
|
||||
big_mul_ten(big_n, power as u64);
|
||||
big_mul_ten(big_u, power as u64);
|
||||
big_mul_ten(big_l, power as u64);
|
||||
big_mul_ten(big_m, power as u64);
|
||||
}
|
||||
|
||||
# Rounds the digits to a precision half to even, into `rounded`, giving whether
|
||||
# they carried into a new first digit.
|
||||
var rounded: *mut u8;
|
||||
|
||||
def round_digits(precision: u64): bool {
|
||||
for i in 0..precision {
|
||||
rounded[i] = digits[i];
|
||||
}
|
||||
|
||||
val next := digits[precision];
|
||||
var rest := sticky;
|
||||
for i in precision + 1..18 {
|
||||
rest = rest || digits[i] != 0;
|
||||
}
|
||||
val up := next > 5 || (next == 5 && (rest || rounded[precision - 1] % 2 == 1));
|
||||
if !up {
|
||||
return false;
|
||||
}
|
||||
|
||||
var i := precision;
|
||||
while i > 0 {
|
||||
i--;
|
||||
if rounded[i] < 9 {
|
||||
rounded[i] = rounded[i] + 1;
|
||||
return false;
|
||||
}
|
||||
rounded[i] = 0;
|
||||
}
|
||||
rounded[0] = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
# The double nearest the decimal `0.r1r2...rp` times ten to `power` plus one,
|
||||
# rounding half to even as `strtod` does.
|
||||
def nearest_double(precision: u64, power: i64): f64 {
|
||||
big_set(exact_n, 0);
|
||||
for i in 0..precision {
|
||||
big_mul_small(exact_n, 10);
|
||||
val add := exact_c;
|
||||
big_set(add, rounded[i] as u64);
|
||||
add_into(exact_n, add);
|
||||
}
|
||||
big_set(exact_d, 1);
|
||||
val scale := power - (precision as i64) + 1;
|
||||
if scale >= 0 {
|
||||
big_mul_ten(exact_n, scale as u64);
|
||||
}
|
||||
else {
|
||||
big_mul_ten(exact_d, (0 - scale) as u64);
|
||||
}
|
||||
|
||||
# The binary exponent puts 53 bits in the quotient, unless it would pass the
|
||||
# least exponent, which leaves a subnormal with fewer.
|
||||
var binary := big_bits(exact_n) as i64 - big_bits(exact_d) as i64 - 53;
|
||||
if binary < -1074 {
|
||||
binary = -1074;
|
||||
}
|
||||
while true {
|
||||
big_copy(exact_t, exact_d);
|
||||
if binary >= 0 {
|
||||
big_shl(exact_t, binary as u64);
|
||||
}
|
||||
val numerator := exact_c;
|
||||
big_copy(numerator, exact_n);
|
||||
if binary < 0 {
|
||||
big_shl(numerator, (0 - binary) as u64);
|
||||
}
|
||||
|
||||
# The quotient must be below 2^53, and at least 2^52 unless subnormal.
|
||||
val top := big();
|
||||
big_copy(top, exact_t);
|
||||
big_shl(top, 53);
|
||||
if big_compare(numerator, top) >= 0 {
|
||||
dispose(top as *mut u8, (limbs + 1) * 8);
|
||||
binary++;
|
||||
continue;
|
||||
}
|
||||
big_shr1(top);
|
||||
if big_compare(numerator, top) < 0 && binary > -1074 {
|
||||
dispose(top as *mut u8, (limbs + 1) * 8);
|
||||
binary--;
|
||||
continue;
|
||||
}
|
||||
|
||||
# Divides a bit at a time, then rounds by the remainder.
|
||||
big_shl(top, 1);
|
||||
var quotient := 0u;
|
||||
for i in 0..53 {
|
||||
big_shr1(top);
|
||||
quotient = quotient * 2;
|
||||
if big_compare(numerator, top) >= 0 {
|
||||
big_sub(numerator, top);
|
||||
quotient++;
|
||||
}
|
||||
}
|
||||
big_shl(numerator, 1);
|
||||
val order := big_compare(numerator, exact_t);
|
||||
dispose(top as *mut u8, (limbs + 1) * 8);
|
||||
if order > 0 || (order == 0 && quotient % 2 == 1) {
|
||||
quotient++;
|
||||
}
|
||||
if quotient == 9007199254740992 {
|
||||
quotient = 4503599627370496;
|
||||
binary++;
|
||||
}
|
||||
|
||||
if quotient < 4503599627370496 {
|
||||
return float_of(quotient);
|
||||
}
|
||||
val biased := binary + 1075;
|
||||
if biased >= 2047 {
|
||||
return float_of(0x7FF0000000000000);
|
||||
}
|
||||
return float_of(((biased as u64) << 52) | (quotient - 4503599627370496));
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
def add_into(a: *mut u64, b: *mut u64): void {
|
||||
var carry := 0u;
|
||||
var i := 1u;
|
||||
while i <= a[0] || i <= b[0] || carry > 0 {
|
||||
val sum := (i <= a[0] ? a[i] : 0) + (i <= b[0] ? b[i] : 0) + carry;
|
||||
a[i] = sum % limb;
|
||||
carry = sum / limb;
|
||||
if i > a[0] {
|
||||
a[0] = i;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
big_trim(a);
|
||||
}
|
||||
|
||||
# Writes the rounded digits in the style `%g` chooses for the precision and the
|
||||
# decimal exponent, without trailing zeros.
|
||||
def put_general(into: *mut builder, precision: u64, power: i64): void {
|
||||
var used := precision;
|
||||
while used > 1 && rounded[used - 1] == 0 {
|
||||
used--;
|
||||
}
|
||||
|
||||
if power < (precision as i64) && power >= -4 {
|
||||
if power < 0 {
|
||||
put(into, '0');
|
||||
put(into, '.');
|
||||
for i in 0..(0 - power - 1) as u64 {
|
||||
put(into, '0');
|
||||
}
|
||||
for i in 0..used {
|
||||
put(into, '0' + rounded[i]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
val whole := power as u64 + 1;
|
||||
for i in 0..whole {
|
||||
put(into, i < used ? '0' + rounded[i] : '0');
|
||||
}
|
||||
if used > whole {
|
||||
put(into, '.');
|
||||
for i in whole..used {
|
||||
put(into, '0' + rounded[i]);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
put(into, '0' + rounded[0]);
|
||||
if used > 1 {
|
||||
put(into, '.');
|
||||
for i in 1..used {
|
||||
put(into, '0' + rounded[i]);
|
||||
}
|
||||
}
|
||||
put(into, 'e');
|
||||
put(into, power < 0 ? '-' : '+');
|
||||
val magnitude := power < 0 ? (0 - power) as u64 : power as u64;
|
||||
if magnitude < 10 {
|
||||
put(into, '0');
|
||||
}
|
||||
put_unsigned(into, magnitude);
|
||||
}
|
||||
|
||||
def put_float(into: *mut builder, value: f64, single: bool): void {
|
||||
if value != value {
|
||||
put(into, 'n');
|
||||
put(into, 'a');
|
||||
put(into, 'n');
|
||||
return;
|
||||
}
|
||||
|
||||
val bits := bits_of(value);
|
||||
val sign := (bits >> 63) != 0;
|
||||
val field := (bits >> 52) & 2047;
|
||||
if field == 2047 {
|
||||
if sign {
|
||||
put(into, '-');
|
||||
}
|
||||
put(into, 'i');
|
||||
put(into, 'n');
|
||||
put(into, 'f');
|
||||
return;
|
||||
}
|
||||
|
||||
# Whole numbers are written without an exponent while they are exact.
|
||||
if value > -1000000000000000.0 && value < 1000000000000000.0 && value == (value as i64) as f64 {
|
||||
if sign && value == 0.0 {
|
||||
put(into, '-');
|
||||
}
|
||||
put_signed(into, value as i64);
|
||||
return;
|
||||
}
|
||||
|
||||
start_float();
|
||||
if rounded == null {
|
||||
rounded = acquire(32);
|
||||
}
|
||||
if sign {
|
||||
put(into, '-');
|
||||
}
|
||||
|
||||
# The value in units a quarter of its gap, with the midpoints to the values
|
||||
# beside it, where the one below is nearer at a power of two. A single is
|
||||
# measured in its own gaps, with a margin of the gaps of doubles beside it.
|
||||
val magnitude := float_of(bits & 0x7FFFFFFFFFFFFFFF);
|
||||
var unit: i64 = 0;
|
||||
var binary: i64 = 0;
|
||||
var even: bool = false;
|
||||
if single {
|
||||
((&mut float_bits) as *mut f32)[0] = magnitude as f32;
|
||||
val narrow := float_bits & 0xFFFFFFFF;
|
||||
val exponent := (narrow >> 23) & 255;
|
||||
val mantissa := exponent == 0 ? narrow & 0x7FFFFF : (narrow & 0x7FFFFF) | 0x800000;
|
||||
val scale := exponent == 0 ? -149 : (exponent as i64) - 150;
|
||||
big_set(big_n, mantissa);
|
||||
big_shl(big_n, 30);
|
||||
big_set(big_u, mantissa * 2 + 1);
|
||||
big_shl(big_u, 29);
|
||||
big_set(big_l, mantissa == 0x800000 && exponent > 1 ? mantissa * 4 - 1 : mantissa * 2 - 1);
|
||||
big_shl(big_l, mantissa == 0x800000 && exponent > 1 ? 28 : 29);
|
||||
big_set(big_m, 2);
|
||||
unit = scale - 30;
|
||||
binary = scale + big_bits(big_n) as i64 - 31;
|
||||
even = mantissa % 2 == 0;
|
||||
}
|
||||
else {
|
||||
val mantissa := field == 0 ? bits & 0xFFFFFFFFFFFFF : (bits & 0xFFFFFFFFFFFFF) | 0x10000000000000;
|
||||
val scale := field == 0 ? -1074 : (field as i64) - 1075;
|
||||
big_set(big_n, mantissa * 4);
|
||||
big_set(big_u, mantissa * 4 + 2);
|
||||
big_set(big_l, mantissa == 0x10000000000000 && field > 1 ? mantissa * 4 - 1 : mantissa * 4 - 2);
|
||||
big_set(big_m, 0);
|
||||
unit = scale - 2;
|
||||
binary = scale + big_bits(big_n) as i64 - 3;
|
||||
even = mantissa % 2 == 0;
|
||||
}
|
||||
val power := decimal_digits(unit, binary);
|
||||
|
||||
# The shortest precision whose digits read back as the value: those strictly
|
||||
# between the midpoints, or on one when ties go to the value, being even.
|
||||
var precision := 1u;
|
||||
while precision <= 17 {
|
||||
val carried := round_digits(precision);
|
||||
val shifted := carried ? power + 1 : power;
|
||||
var digits_value := 0u;
|
||||
for i in 0..precision {
|
||||
digits_value = digits_value * 10 + rounded[i] as u64;
|
||||
}
|
||||
if carried {
|
||||
digits_value = digits_value * 10;
|
||||
}
|
||||
big_set(big_q, digits_value);
|
||||
big_copy(big_t, big_d);
|
||||
big_mul_u64(big_t, big_q);
|
||||
|
||||
val above := big_compare(big_t, big_u);
|
||||
val below := big_compare(big_t, big_l);
|
||||
var same := (above < 0 || (above == 0 && even)) && (below > 0 || (below == 0 && even));
|
||||
|
||||
# A single reads back through a double, whose rounding matters near a midpoint.
|
||||
if single && !(above < 0 && below > 0 && clear_of_midpoints()) && !(above > 0 || below < 0) || single && near_outside() {
|
||||
val back := nearest_double(precision, shifted);
|
||||
same = (back as f32) == (magnitude as f32);
|
||||
}
|
||||
|
||||
if same || precision == 17 {
|
||||
put_general(into, precision, shifted);
|
||||
return;
|
||||
}
|
||||
|
||||
big_mul_small(big_u, 10);
|
||||
big_mul_small(big_l, 10);
|
||||
big_mul_small(big_m, 10);
|
||||
precision++;
|
||||
}
|
||||
}
|
||||
|
||||
# Whether the candidate in `t` is inside the midpoints by more than the margin.
|
||||
def clear_of_midpoints(): bool {
|
||||
big_copy(big_c, big_t);
|
||||
add_into(big_c, big_m);
|
||||
if big_compare(big_c, big_u) >= 0 {
|
||||
return false;
|
||||
}
|
||||
big_copy(big_c, big_l);
|
||||
add_into(big_c, big_m);
|
||||
return big_compare(big_t, big_c) > 0;
|
||||
}
|
||||
|
||||
# Whether the candidate in `t` is outside the midpoints, but within the margin.
|
||||
def near_outside(): bool {
|
||||
big_copy(big_c, big_u);
|
||||
add_into(big_c, big_m);
|
||||
if big_compare(big_t, big_u) > 0 && big_compare(big_t, big_c) <= 0 {
|
||||
return true;
|
||||
}
|
||||
big_copy(big_c, big_t);
|
||||
add_into(big_c, big_m);
|
||||
return big_compare(big_t, big_l) < 0 && big_compare(big_c, big_l) >= 0;
|
||||
}
|
||||
|
||||
# Multiplies by a number of at most 64 bits, held in `factor`.
|
||||
def big_mul_u64(a: *mut u64, factor: *mut u64): void {
|
||||
if factor[0] <= 1 {
|
||||
big_mul_small(a, factor[0] == 0 ? 0 : factor[1]);
|
||||
big_trim(a);
|
||||
return;
|
||||
}
|
||||
big_copy(big_c, a);
|
||||
big_mul_small(a, factor[1]);
|
||||
big_mul_small(big_c, factor[2]);
|
||||
big_shl(big_c, 32);
|
||||
add_into(a, big_c);
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
#! @file format.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how an executable builds the text of an interpolation.
|
||||
#!
|
||||
#! Interpolation builds text in builders of memory the runtime manages, as
|
||||
#! `machine__format` of `sources/machine.c` does, then makes a string of it.
|
||||
|
||||
module runtime when backend == native;
|
||||
|
||||
struct builder {
|
||||
var data: *mut u8;
|
||||
var length: u64;
|
||||
var capacity: u64;
|
||||
}
|
||||
|
||||
val format_depth := 8u;
|
||||
|
||||
|
||||
def append(into: *mut builder, bytes: *u8, length: u64): void {
|
||||
if (*into).length + length > (*into).capacity {
|
||||
var capacity := (*into).capacity == 0 ? 64 : (*into).capacity;
|
||||
while capacity < (*into).length + length {
|
||||
capacity = capacity * 2;
|
||||
}
|
||||
val grown := acquire(capacity);
|
||||
copy_bytes(grown, (*into).data, (*into).length);
|
||||
dispose((*into).data, (*into).capacity);
|
||||
(*into).data = grown;
|
||||
(*into).capacity = capacity;
|
||||
}
|
||||
copy_bytes((*into).data + (*into).length, bytes, length);
|
||||
(*into).length = (*into).length + length;
|
||||
}
|
||||
|
||||
def put(into: *mut builder, byte: u8): void {
|
||||
if (*into).length == (*into).capacity {
|
||||
val capacity := (*into).capacity == 0 ? 64 : (*into).capacity * 2;
|
||||
val grown := acquire(capacity);
|
||||
copy_bytes(grown, (*into).data, (*into).length);
|
||||
dispose((*into).data, (*into).capacity);
|
||||
(*into).data = grown;
|
||||
(*into).capacity = capacity;
|
||||
}
|
||||
(*into).data[(*into).length] = byte;
|
||||
(*into).length = (*into).length + 1;
|
||||
}
|
||||
|
||||
def put_text(into: *mut builder, index: u64): void {
|
||||
val text := (*executable()).texts + index;
|
||||
append(into, (*text).bytes, (*text).length);
|
||||
}
|
||||
|
||||
def put_unsigned(into: *mut builder, value: u64): void {
|
||||
var power := 1u;
|
||||
while value / power >= 10 {
|
||||
power = power * 10;
|
||||
}
|
||||
while power > 0 {
|
||||
put(into, ('0' + value / power % 10) as u8);
|
||||
power = power / 10;
|
||||
}
|
||||
}
|
||||
|
||||
def put_signed(into: *mut builder, value: i64): void {
|
||||
if value < 0 {
|
||||
put(into, '-');
|
||||
put_unsigned(into, 0 - (value as u64));
|
||||
return;
|
||||
}
|
||||
put_unsigned(into, value as u64);
|
||||
}
|
||||
|
||||
def put_hex(into: *mut builder, value: u64): void {
|
||||
put(into, '0');
|
||||
put(into, 'x');
|
||||
var shift := 60u;
|
||||
while shift > 0 && (value >> shift) == 0 {
|
||||
shift = shift - 4;
|
||||
}
|
||||
while true {
|
||||
val digit := (value >> shift) & 15;
|
||||
put(into, (digit < 10 ? '0' + digit : 'a' + digit - 10) as u8);
|
||||
if shift == 0 {
|
||||
break;
|
||||
}
|
||||
shift = shift - 4;
|
||||
}
|
||||
}
|
||||
|
||||
def put_word(into: *mut builder, text: *u8, length: u64): void {
|
||||
append(into, text, length);
|
||||
}
|
||||
|
||||
def put_name(into: *mut builder, name: *u8, length: u64): void {
|
||||
append(into, name, length);
|
||||
}
|
||||
|
||||
# Writes `true`, `false`, `null`, and the other words formatting uses, a byte at a time.
|
||||
def put_true(into: *mut builder): void {
|
||||
put(into, 't');
|
||||
put(into, 'r');
|
||||
put(into, 'u');
|
||||
put(into, 'e');
|
||||
}
|
||||
|
||||
def put_false(into: *mut builder): void {
|
||||
put(into, 'f');
|
||||
put(into, 'a');
|
||||
put(into, 'l');
|
||||
put(into, 's');
|
||||
put(into, 'e');
|
||||
}
|
||||
|
||||
def put_null(into: *mut builder): void {
|
||||
put(into, 'n');
|
||||
put(into, 'u');
|
||||
put(into, 'l');
|
||||
put(into, 'l');
|
||||
}
|
||||
|
||||
def put_separator(into: *mut builder): void {
|
||||
put(into, ',');
|
||||
put(into, ' ');
|
||||
}
|
||||
|
||||
def put_value(into: *mut builder, at: *mut u8, kind: *layout, frame: bool, depth: u64): void {
|
||||
if depth > format_depth {
|
||||
put(into, '.');
|
||||
put(into, '.');
|
||||
put(into, '.');
|
||||
return;
|
||||
}
|
||||
|
||||
val info := executable();
|
||||
if (*kind).kind == kind_int || (*kind).kind == kind_uint || (*kind).kind == kind_bool {
|
||||
# A scalar in memory is read as wide as it is there, as a whole word past
|
||||
# it may not be memory at all.
|
||||
var value: u64 = 0;
|
||||
if frame {
|
||||
value = word(at);
|
||||
} else {
|
||||
read_scalar((&mut scalar_scratch) as *mut u8, at, (*kind).access);
|
||||
value = scalar_scratch;
|
||||
}
|
||||
# An enum is the name of the member of the value.
|
||||
for i in 0..(*kind).count {
|
||||
val member := (*kind).fields + i;
|
||||
if (*member).offset == value {
|
||||
append(into, (*member).name, (*member).name_length);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (*kind).kind == kind_bool {
|
||||
if value != 0 {
|
||||
put_true(into);
|
||||
}
|
||||
else {
|
||||
put_false(into);
|
||||
}
|
||||
}
|
||||
else if (*kind).kind == kind_int {
|
||||
put_signed(into, value as i64);
|
||||
}
|
||||
else {
|
||||
put_unsigned(into, value);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (*kind).kind == kind_float {
|
||||
var value := (at as *mut f64)[0];
|
||||
if !frame {
|
||||
read_scalar((&mut scalar_scratch) as *mut u8, at, (*kind).access);
|
||||
value = ((&mut scalar_scratch) as *mut f64)[0];
|
||||
}
|
||||
put_float(into, value, (*kind).bits <= 32);
|
||||
return;
|
||||
}
|
||||
|
||||
# A fixed array holds its elements where it is, and prints as they do.
|
||||
if (*kind).kind == kind_fixed {
|
||||
val element := (*kind).element;
|
||||
if ((*element).kind == kind_int || (*element).kind == kind_uint) && (*element).size == 1 && (*element).count == 0 {
|
||||
append(into, at, (*kind).count);
|
||||
return;
|
||||
}
|
||||
|
||||
put(into, '[');
|
||||
for i in 0..(*kind).count {
|
||||
if i > 0 {
|
||||
put_separator(into);
|
||||
}
|
||||
put_value(into, at + i * (*element).size, element, false, depth + 1);
|
||||
}
|
||||
put(into, ']');
|
||||
return;
|
||||
}
|
||||
|
||||
if (*kind).kind == kind_reference || (*kind).kind == kind_trait {
|
||||
val pointer := resolved_pointer(at);
|
||||
if (*kind).kind == kind_trait {
|
||||
val vtable := word(at + 8);
|
||||
if pointer == null || vtable >= (*info).vtable_count {
|
||||
put_null(into);
|
||||
return;
|
||||
}
|
||||
put_value(into, pointer, (*info).vtables[vtable], false, depth + 1);
|
||||
return;
|
||||
}
|
||||
if pointer == null || (*kind).element == null {
|
||||
put_null(into);
|
||||
return;
|
||||
}
|
||||
put_value(into, pointer, (*kind).element, false, depth + 1);
|
||||
return;
|
||||
}
|
||||
|
||||
if (*kind).kind == kind_struct {
|
||||
# Text is written as the bytes it holds, not as where they are and how many.
|
||||
if ((*kind).flags & layout_texts) != 0 {
|
||||
val index := (*kind).flags >> layout_text_at;
|
||||
val begins := (*kind).fields + index;
|
||||
val counts := (*kind).fields + index + 1;
|
||||
val data := word(at + (*begins).offset) as *u8;
|
||||
val length := word(at + (*counts).offset);
|
||||
if data != null && length > 0 {
|
||||
append(into, data, length);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
# Any other view is written as the elements it views, as an array of them is.
|
||||
if ((*kind).flags & layout_views) != 0 {
|
||||
val index := (*kind).flags >> layout_text_at;
|
||||
val begins := (*kind).fields + index;
|
||||
val counts := (*kind).fields + index + 1;
|
||||
val data := word(at + (*begins).offset) as *mut u8;
|
||||
val length := data != null ? word(at + (*counts).offset) : 0;
|
||||
val element := (*kind).element;
|
||||
put(into, '[');
|
||||
for i in 0..length {
|
||||
if i > 0 {
|
||||
put_separator(into);
|
||||
}
|
||||
put_value(into, data + i * (*element).size, element, false, depth + 1);
|
||||
}
|
||||
put(into, ']');
|
||||
return;
|
||||
}
|
||||
|
||||
append(into, (*kind).name, (*kind).name_length);
|
||||
put(into, '{');
|
||||
for i in 0..(*kind).count {
|
||||
val field := (*kind).fields + i;
|
||||
if i > 0 {
|
||||
put_separator(into);
|
||||
}
|
||||
if (*field).name_length > 0 {
|
||||
append(into, (*field).name, (*field).name_length);
|
||||
put(into, ' ');
|
||||
put(into, '=');
|
||||
put(into, ' ');
|
||||
}
|
||||
put_value(into, at + (*field).offset, (*field).layout, false, depth + 1);
|
||||
}
|
||||
put(into, '}');
|
||||
return;
|
||||
}
|
||||
|
||||
if (*kind).kind == kind_function {
|
||||
val index := word(at);
|
||||
if index == 0 {
|
||||
put_null(into);
|
||||
return;
|
||||
}
|
||||
put(into, 'd');
|
||||
put(into, 'e');
|
||||
put(into, 'f');
|
||||
put(into, ' ');
|
||||
if index - 1 >= (*info).function_count {
|
||||
put(into, '?');
|
||||
return;
|
||||
}
|
||||
val function := (*info).functions + (index - 1);
|
||||
append(into, (*function).name, (*function).name_length);
|
||||
return;
|
||||
}
|
||||
|
||||
# A union is written as a struct holding the one field it holds.
|
||||
if (*kind).kind == kind_union {
|
||||
val tag := held_field(at, kind);
|
||||
if tag >= (*kind).count {
|
||||
put(into, '?');
|
||||
return;
|
||||
}
|
||||
val field := (*kind).fields + tag;
|
||||
append(into, (*kind).name, (*kind).name_length);
|
||||
put(into, '{');
|
||||
append(into, (*field).name, (*field).name_length);
|
||||
put(into, ' ');
|
||||
put(into, '=');
|
||||
put(into, ' ');
|
||||
put_value(into, at + (*field).offset, (*field).layout, false, depth + 1);
|
||||
put(into, '}');
|
||||
return;
|
||||
}
|
||||
|
||||
if (*kind).kind == kind_pointer {
|
||||
val address := word(at);
|
||||
if address == 0 {
|
||||
put_null(into);
|
||||
return;
|
||||
}
|
||||
put_hex(into, address);
|
||||
}
|
||||
}
|
||||
|
||||
# Room to read a scalar or a reference into, since the runtime takes no references to its locals.
|
||||
struct scratch {
|
||||
var first: u64;
|
||||
var second: u64;
|
||||
}
|
||||
|
||||
var scalar_scratch: u64;
|
||||
var reference_scratch: scratch;
|
||||
|
||||
# The pointer a reference holds.
|
||||
def resolved_pointer(at: *mut u8): *mut u8 {
|
||||
return word(at) as *mut u8;
|
||||
}
|
||||
|
||||
#! `OP_FORMAT`: begins a string, in the running thread's builders.
|
||||
def format_begin(): void {
|
||||
if threaded {
|
||||
hold();
|
||||
}
|
||||
val me := current();
|
||||
if (*me).builder_count == (*me).builder_capacity {
|
||||
val capacity := (*me).builder_capacity == 0 ? 8 : (*me).builder_capacity * 2;
|
||||
val grown := acquire(capacity * size_of_builder()) as *mut builder;
|
||||
copy_bytes(grown as *mut u8, (*me).builders as *mut u8, (*me).builder_count * size_of_builder());
|
||||
dispose((*me).builders as *mut u8, (*me).builder_capacity * size_of_builder());
|
||||
(*me).builders = grown;
|
||||
(*me).builder_capacity = capacity;
|
||||
}
|
||||
(*((*me).builders + (*me).builder_count)).length = 0;
|
||||
(*me).builder_count++;
|
||||
if threaded {
|
||||
let_go();
|
||||
}
|
||||
}
|
||||
|
||||
def size_of_builder(): u64 {
|
||||
return size_of::<builder>();
|
||||
}
|
||||
|
||||
# The builder the running thread appends to.
|
||||
def innermost(): *mut builder {
|
||||
val me := current();
|
||||
return (*me).builders + ((*me).builder_count - 1);
|
||||
}
|
||||
|
||||
#! `OP_FORMAT_TEXT`: appends constant text.
|
||||
#! @param bytes The first byte of the text.
|
||||
#! @param length How many bytes it holds.
|
||||
def format_text(bytes: *mut u8, length: u64): void {
|
||||
if threaded {
|
||||
hold();
|
||||
}
|
||||
append(innermost(), bytes, length);
|
||||
if threaded {
|
||||
let_go();
|
||||
}
|
||||
}
|
||||
|
||||
#! `OP_FORMAT_VALUE`: appends a value in its frame representation.
|
||||
#! @param at The value, in its frame representation.
|
||||
#! @param kind The layout of its type, which says how it is written.
|
||||
def format_value(at: *mut u8, kind: *layout): void {
|
||||
if threaded {
|
||||
hold();
|
||||
}
|
||||
put_value(innermost(), at, kind, true, 0);
|
||||
if threaded {
|
||||
let_go();
|
||||
}
|
||||
}
|
||||
|
||||
#! `OP_FORMAT_OWNED`: hands the text over in memory the program manages itself,
|
||||
#! as where it begins and how many bytes it holds, which is what a `string` owns
|
||||
#! and gives back where its scope ends. Its block is not cleared, as every byte
|
||||
#! of it is written.
|
||||
#! @param dst The slot of the `string` to fill: its first word takes where the
|
||||
#! text begins, and its second how many bytes it holds.
|
||||
def format_owned(dst: *mut u8): void {
|
||||
if threaded {
|
||||
hold();
|
||||
}
|
||||
val me := current();
|
||||
(*me).builder_count--;
|
||||
val done := (*me).builders + (*me).builder_count;
|
||||
val data := (*done).length > 0 ? allocate((*done).length) : null;
|
||||
copy_bytes(data, (*done).data, (*done).length);
|
||||
|
||||
val words := dst as *mut u64;
|
||||
words[0] = data as u64;
|
||||
words[1] = (*done).length;
|
||||
if threaded {
|
||||
let_go();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#! @file linux_x86_64.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the numbers of the system calls the runtime makes on Linux, on
|
||||
#! x86-64.
|
||||
#!
|
||||
#! What the runtime needs to know of Linux on x86-64: the numbers of the system
|
||||
#! calls it makes. Another platform declares these names in a section of its
|
||||
#! own.
|
||||
|
||||
module runtime when backend == native && os == linux && arch == x86_64;
|
||||
|
||||
val call_write: i64 = 1;
|
||||
val call_mmap: i64 = 9;
|
||||
val call_mprotect: i64 = 10;
|
||||
val call_munmap: i64 = 11;
|
||||
val call_mremap: i64 = 25;
|
||||
val call_exit_group: i64 = 231;
|
||||
@@ -0,0 +1,899 @@
|
||||
#! @file memory.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how an executable acquires memory from the kernel and gives it back:
|
||||
#! the blocks `raw_allocate` takes, and those the runtime keeps for itself.
|
||||
#!
|
||||
#! Memory comes from the kernel in chunks, carved into blocks of classes of
|
||||
#! sizes from 16 bytes to 256 KiB, which are reused once disposed. Larger
|
||||
#! blocks are mapped on their own, and some given back are kept to be reused,
|
||||
#! as `map_large` says. Chunks are opened one after another in a region of
|
||||
#! address space reserved at once, so whether memory lies in a chunk is a
|
||||
#! comparison. What is acquired is zeroed where it is asked to be: memory fresh
|
||||
#! from the kernel already is, and a block reused is cleared for as many bytes
|
||||
#! as were asked for.
|
||||
#!
|
||||
#! Once a program has threads, each takes and gives back the blocks it carves
|
||||
#! from a cache of its own, without the lock every thread shares, as
|
||||
#! `block_cache` says; and what the kernel is asked, mapping and unmapping
|
||||
#! large blocks, and what costs as much, copying and clearing them, is done
|
||||
#! without the lock too, so a thread allocating never waits on another's
|
||||
#! system call.
|
||||
|
||||
import runtime::win32;
|
||||
|
||||
module runtime when backend == native;
|
||||
|
||||
val chunk_size := 1048576u;
|
||||
val region_size := 68719476736u; # 64 GiB of address space, which takes no memory until opened.
|
||||
val largest := 262144u; # The largest block carved from a chunk.
|
||||
const small_largest := 2048u; # The largest block whose class `class_by_size` holds.
|
||||
const small_classes := 19u; # The classes of blocks up to `small_largest`.
|
||||
val classes := 47u;
|
||||
|
||||
var chunk: *mut u8; # Where the next block is carved.
|
||||
var chunk_left: u64; # The bytes open after it.
|
||||
var free_lists: *mut *mut u8;
|
||||
|
||||
# The region chunks are opened in: where it begins, where its open chunks end,
|
||||
# and where it ends. A region that fills is followed by another, and where each
|
||||
# before it begins and its chunks end are kept, in memory of their own.
|
||||
var region_low: u64;
|
||||
var region_high: u64;
|
||||
var region_end: u64;
|
||||
var old_regions: *mut u64;
|
||||
var old_count: u64;
|
||||
var old_capacity: u64;
|
||||
|
||||
def word(at: *u8): u64 {
|
||||
return (at as *u64)[0];
|
||||
}
|
||||
|
||||
def set_word(at: *mut u8, value: u64): void {
|
||||
(at as *mut u64)[0] = value;
|
||||
}
|
||||
module runtime when backend == native && os == linux;
|
||||
def map(size: u64): *mut u8 {
|
||||
val address := syscall(call_mmap, 0, size, 3, 0x22, 0xFFFFFFFFFFFFFFFF, 0);
|
||||
if address < 0 {
|
||||
trap(31);
|
||||
}
|
||||
return address as *mut u8;
|
||||
}
|
||||
|
||||
def unmap(address: *mut u8, size: u64): void {
|
||||
syscall(call_munmap, address as u64, size, 0, 0, 0, 0);
|
||||
}
|
||||
module runtime when backend == native;
|
||||
def pages(size: u64): u64 {
|
||||
return (size + 4095) / 4096 * 4096;
|
||||
}
|
||||
|
||||
# Classes step by 16 bytes up to 256, then double up to 2048, then step by a
|
||||
# quarter of each power of 2 up to `largest`, so no block of those is more
|
||||
# than a quarter larger than what it holds.
|
||||
def class_of(size: u64): u64 {
|
||||
if size <= 256 {
|
||||
return size == 0 ? 0 : (size + 15) / 16 - 1;
|
||||
}
|
||||
if size <= 512 {
|
||||
return 16;
|
||||
}
|
||||
if size <= small_largest {
|
||||
return size <= 1024 ? 17 : 18;
|
||||
}
|
||||
val below := size - 1;
|
||||
val top := 63 - leading_zeros::<u64>(below) as u64;
|
||||
return small_classes + (top - 11) * 4 + ((below >> (top - 2)) & 3);
|
||||
}
|
||||
|
||||
def class_size(class: u64): u64 {
|
||||
if class < 16 {
|
||||
return (class + 1) * 16;
|
||||
}
|
||||
if class < small_classes {
|
||||
return 512u << (class - 16);
|
||||
}
|
||||
val past := class - small_classes;
|
||||
return (5 + (past & 3)) << (9 + past / 4);
|
||||
}
|
||||
|
||||
# The class of each size up to `small_largest`, by `(size + 15) / 16`, and the
|
||||
# size of each class, worked out while compiling. Classes begin and end at
|
||||
# multiples of 16 bytes, so the sizes that round up to the same multiple share
|
||||
# a class.
|
||||
const class_by_size: u8[129] = make_class_by_size();
|
||||
const size_of_class: u64[47] = make_size_of_class();
|
||||
|
||||
# The class of a block of the size, at most `largest`.
|
||||
def class_for(size: u64): u64 {
|
||||
return size <= small_largest ? class_by_size[(size + 15) >> 4] as u64 : class_of(size);
|
||||
}
|
||||
|
||||
const def make_class_by_size(): u8[129] {
|
||||
var made: u8[129];
|
||||
for each in 0..129 {
|
||||
made[each] = class_of((each * 16) as u64) as u8;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
const def make_size_of_class(): u64[47] {
|
||||
var made: u64[47];
|
||||
for each in 0..47 {
|
||||
made[each] = class_size(each as u64);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# The shift that leaves the bits of a hash a set of the capacity is indexed by,
|
||||
# which is a power of 2.
|
||||
def shift_for(capacity: u64): u64 {
|
||||
var shift := 64u;
|
||||
var rest := capacity;
|
||||
while rest > 1 {
|
||||
rest = rest >> 1;
|
||||
shift--;
|
||||
}
|
||||
return shift;
|
||||
}
|
||||
|
||||
# Where a probe for the address begins in a set indexed by the bits `shift` leaves:
|
||||
# the top bits of the address times the golden ratio, which spreads addresses that
|
||||
# differ in any bits across the set. It is one expression, so it is inlined.
|
||||
def hash(address: u64, shift: u64): u64 {
|
||||
return (address * 0x9E3779B97F4A7C15) >> shift;
|
||||
}
|
||||
|
||||
# Carves every size up to 16 bytes, so each block is aligned for any value.
|
||||
def carve(wanted: u64): *mut u8 {
|
||||
val size := (wanted + 15) / 16 * 16;
|
||||
if chunk_left < size {
|
||||
open_chunk();
|
||||
}
|
||||
val block := chunk;
|
||||
chunk = chunk + size;
|
||||
chunk_left = chunk_left - size;
|
||||
return block;
|
||||
}
|
||||
module runtime when backend == native && os == linux;
|
||||
# Opens the chunk after the last, which what is left of the last runs on into,
|
||||
# or the first of a new region where this one is full.
|
||||
def open_chunk(): void {
|
||||
if region_high + chunk_size > region_end {
|
||||
reserve();
|
||||
chunk = region_high as *mut u8;
|
||||
chunk_left = 0;
|
||||
}
|
||||
if syscall(call_mprotect, region_high, chunk_size, 3, 0, 0, 0) < 0 {
|
||||
trap(error_out_of_memory);
|
||||
}
|
||||
region_high = region_high + chunk_size;
|
||||
chunk_left = chunk_left + chunk_size;
|
||||
}
|
||||
|
||||
# Reserves a region without access, so it takes no memory until chunks are opened
|
||||
# in it: as large as the system allows, down to a chunk. The region before it is
|
||||
# kept, for `in_chunk`.
|
||||
def reserve(): void {
|
||||
if region_low != 0 {
|
||||
keep_region();
|
||||
}
|
||||
|
||||
var size := region_size;
|
||||
while size >= chunk_size {
|
||||
val address := syscall(call_mmap, 0, size, 0, 0x4022, 0xFFFFFFFFFFFFFFFF, 0);
|
||||
if address >= 0 {
|
||||
region_low = address as u64;
|
||||
region_high = address as u64;
|
||||
region_end = address as u64 + size;
|
||||
return;
|
||||
}
|
||||
size = size / 2;
|
||||
}
|
||||
trap(error_out_of_memory);
|
||||
}
|
||||
module runtime when backend == native;
|
||||
def keep_region(): void {
|
||||
if old_count == old_capacity {
|
||||
val capacity := old_capacity == 0 ? 256u : old_capacity * 2;
|
||||
val grown := map(pages(capacity * 16)) as *mut u64;
|
||||
for i in 0..old_count * 2 {
|
||||
grown[i] = old_regions[i];
|
||||
}
|
||||
if old_regions != null {
|
||||
unmap(old_regions as *mut u8, pages(old_capacity * 16));
|
||||
}
|
||||
old_regions = grown;
|
||||
old_capacity = capacity;
|
||||
}
|
||||
old_regions[2 * old_count] = region_low;
|
||||
old_regions[2 * old_count + 1] = region_high;
|
||||
old_count++;
|
||||
}
|
||||
|
||||
# Zeroes the words that hold the first `size` bytes of memory aligned to 8 bytes,
|
||||
# which may run past `size` to the end of its word. Every block is a whole number
|
||||
# of words, so that is still within it. `memset` does so sixteen bytes at a time
|
||||
# where vectors are held in registers.
|
||||
def clear(at: *mut u8, size: u64): void {
|
||||
memset(at, 0, (size + 7) & ~7u);
|
||||
}
|
||||
|
||||
# Copies bytes that may overlap, as `memmove` does, which `memcpy` does, sixteen
|
||||
# bytes at a time where vectors are held in registers.
|
||||
def copy_bytes(dst: *mut u8, src: *u8, size: u64): void {
|
||||
memcpy(dst, src, size);
|
||||
}
|
||||
|
||||
def compare_bytes(a: *u8, b: *u8, size: u64): i64 {
|
||||
return 0 if size == 0;
|
||||
return memcmp(a, b, size);
|
||||
}
|
||||
|
||||
#! The bytes acquired for memory of the size, rounded to its class or to pages.
|
||||
#! @param size The number of bytes asked for.
|
||||
#! @returns The bytes that many takes: the size of its class, or whole pages for
|
||||
#! a large block.
|
||||
def acquired(size: u64): u64 {
|
||||
return size > largest ? pages(size) : size_of_class[class_for(size)];
|
||||
}
|
||||
|
||||
#! Acquires zeroed memory of at least the size.
|
||||
#! @param size The number of bytes asked for.
|
||||
#! @returns The first byte of the memory, a block of its class or pages of their
|
||||
#! own.
|
||||
def acquire(size: u64): *mut u8 {
|
||||
if size > largest {
|
||||
return map_large(pages(size), true);
|
||||
}
|
||||
return take(class_for(size), size);
|
||||
}
|
||||
|
||||
#! Takes memory of a class: a block disposed of, which holds what it held but
|
||||
#! for the bytes asked to be cleared, or one carved fresh, which the kernel
|
||||
#! zeroed.
|
||||
#! @param class The class.
|
||||
#! @param cleared How many of its first bytes a block reused is cleared for.
|
||||
#! @returns The first byte of the memory.
|
||||
def take(class: u64, cleared: u64): *mut u8 {
|
||||
if free_lists == null {
|
||||
free_lists = carve(classes * 8) as *mut *mut u8;
|
||||
}
|
||||
|
||||
val found := free_lists[class];
|
||||
if found != null {
|
||||
free_lists[class] = (found as *mut *mut u8)[0];
|
||||
if cleared != 0 {
|
||||
clear(found, cleared);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
return carve(size_of_class[class]);
|
||||
}
|
||||
|
||||
#! Disposes of memory acquired with the size.
|
||||
#! @param at The first byte of the memory, or `null`, which does nothing.
|
||||
#! @param size The number of bytes it was acquired with.
|
||||
def dispose(at: *mut u8, size: u64): void {
|
||||
if at == null {
|
||||
return;
|
||||
}
|
||||
if size > largest {
|
||||
unmap_large(at, pages(size));
|
||||
return;
|
||||
}
|
||||
|
||||
val class := class_for(size);
|
||||
(at as *mut *mut u8)[0] = free_lists[class];
|
||||
free_lists[class] = at;
|
||||
}
|
||||
|
||||
|
||||
# Large memory given back is kept to be handed out again, rather than unmapped,
|
||||
# as mapping memory and touching its pages for the first time costs far more
|
||||
# than clearing it: up to `kept_most` pieces, of `kept_bytes_most` bytes in
|
||||
# all, each of `kept_largest` bytes at most, past which clearing it costs more
|
||||
# than it saves. Each is kept by where it is and how many bytes it is, and
|
||||
# handed out for as many bytes alone. The list is read and written holding the
|
||||
# lock; what's taken from it is cleared after letting go.
|
||||
val kept_most := 64u;
|
||||
val kept_bytes_most := 33554432u;
|
||||
val kept_largest := 1048576u;
|
||||
var kept_at: u64[64];
|
||||
var kept_size: u64[64];
|
||||
var kept_count: u64;
|
||||
var kept_bytes: u64;
|
||||
|
||||
# Memory of a number of bytes that was kept, taken from those kept, or null
|
||||
# where none was.
|
||||
def take_kept(size: u64): *mut u8 {
|
||||
for i in 0..kept_count {
|
||||
if kept_size[i] == size {
|
||||
val at := kept_at[i] as *mut u8;
|
||||
kept_count--;
|
||||
kept_at[i] = kept_at[kept_count];
|
||||
kept_size[i] = kept_size[kept_count];
|
||||
kept_bytes = kept_bytes - size;
|
||||
return at;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
# Keeps memory given back where there is room, giving whether it was kept,
|
||||
# else it's for the caller to unmap.
|
||||
def keep_large(at: *mut u8, size: u64): bool {
|
||||
if size > kept_largest || kept_count >= kept_most || kept_bytes + size > kept_bytes_most {
|
||||
return false;
|
||||
}
|
||||
kept_at[kept_count] = at as u64;
|
||||
kept_size[kept_count] = size;
|
||||
kept_count++;
|
||||
kept_bytes = kept_bytes + size;
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Maps memory of a number of bytes, which the kernel zeroed, or hands out
|
||||
#! memory of as many that was kept.
|
||||
#! @param size The number of bytes, a whole number of pages.
|
||||
#! @param cleared Whether memory kept is cleared, as memory mapped is zeroed.
|
||||
#! @returns The first byte of the memory.
|
||||
def map_large(size: u64, cleared: bool): *mut u8 {
|
||||
val at := take_kept(size);
|
||||
if at == null {
|
||||
return map(size);
|
||||
}
|
||||
if cleared {
|
||||
clear(at, size);
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
#! Gives back memory `map_large` gave, keeping it where there is room.
|
||||
#! @param at The first byte of the memory.
|
||||
#! @param size The number of bytes it was given with.
|
||||
def unmap_large(at: *mut u8, size: u64): void {
|
||||
if !keep_large(at, size) {
|
||||
unmap(at, size);
|
||||
}
|
||||
}
|
||||
|
||||
# Whether memory lies within a chunk: the newest region's open chunks, or those of
|
||||
# a region before it.
|
||||
def in_chunk(at: *mut u8): bool {
|
||||
val address := at as u64;
|
||||
if address - region_low < region_high - region_low {
|
||||
return true;
|
||||
}
|
||||
for i in 0..old_count {
|
||||
val low := old_regions[2 * i];
|
||||
if address - low < old_regions[2 * i + 1] - low {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
# Blocks the program allocates and releases itself, each a header of its size and
|
||||
# mark followed by its data. A live block's mark is made from its header's
|
||||
# address, and releasing it takes the mark away, so a pointer never allocated or
|
||||
# already released is recognized. A small block is carved from a chunk, so its
|
||||
# header is safe to read wherever the pointer is within one; a large block is
|
||||
# mapped on its own, and found in a set of the large blocks. Every block's data
|
||||
# starts a multiple of 16 bytes into its memory, so it is aligned to 16 bytes as
|
||||
# the memory is, which is wider than any type needs.
|
||||
#
|
||||
# The set is probed linearly. A block released leaves a tombstone where it was,
|
||||
# unless nothing was ever placed past it, and a block allocated takes the first
|
||||
# tombstone or empty slot it meets.
|
||||
|
||||
struct block {
|
||||
var size: u64; #! The bytes of its data, all of the memory after the header.
|
||||
var mark: u64; #! Made from its address while it is live, and 0 once released.
|
||||
}
|
||||
|
||||
val block_header := 16u; # The size and mark before every block's data.
|
||||
val tombstone := 1u;
|
||||
|
||||
var block_set: *mut *mut block; # Of the large blocks.
|
||||
var block_capacity: u64;
|
||||
var block_used: u64; # Slots holding blocks or tombstones.
|
||||
var block_shift: u64; # What `hash` shifts by for the set.
|
||||
var large_count: u64; # Large blocks that are live.
|
||||
|
||||
# What a live block's mark is its address mixed with.
|
||||
val live_key := 0x6E69616C70657669u;
|
||||
|
||||
# The slot holding the block, or the empty slot that ends its probe where the set
|
||||
# does not hold it.
|
||||
def block_slot(found: *mut block): u64 {
|
||||
val mask := block_capacity - 1;
|
||||
var i := hash(found as u64, block_shift);
|
||||
while block_set[i] != null && block_set[i] != found {
|
||||
i = (i + 1) & mask;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
# The slot a block the set does not hold goes in: the first tombstone or empty
|
||||
# slot of its probe.
|
||||
def open_slot(made: *mut block): u64 {
|
||||
val mask := block_capacity - 1;
|
||||
var i := hash(made as u64, block_shift);
|
||||
while block_set[i] != null && block_set[i] != tombstone as *mut block {
|
||||
i = (i + 1) & mask;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
# Makes room for one more large block, building the set again at a quarter full
|
||||
# from the blocks it holds once blocks and tombstones fill half of it.
|
||||
def block_room(): void {
|
||||
if block_capacity > 0 && (block_used + 1) * 2 <= block_capacity {
|
||||
return;
|
||||
}
|
||||
|
||||
var capacity := 64u;
|
||||
while capacity < (large_count + 1) * 4 {
|
||||
capacity = capacity * 2;
|
||||
}
|
||||
|
||||
val before := block_set;
|
||||
val had := block_capacity;
|
||||
block_set = acquire(capacity * 8) as *mut *mut block;
|
||||
block_capacity = capacity;
|
||||
block_shift = shift_for(capacity);
|
||||
block_used = large_count;
|
||||
for i in 0..had {
|
||||
val each := before[i];
|
||||
if each != null && each != tombstone as *mut block {
|
||||
block_set[block_slot(each)] = each;
|
||||
}
|
||||
}
|
||||
dispose(before as *mut u8, had * 8);
|
||||
}
|
||||
|
||||
# Takes the block at the slot out of the set. Where the slot after it is empty, no
|
||||
# probe goes on past it, so it and the tombstones before it are emptied instead.
|
||||
def unset(slot: u64): void {
|
||||
val mask := block_capacity - 1;
|
||||
if block_set[(slot + 1) & mask] != null {
|
||||
block_set[slot] = tombstone as *mut block;
|
||||
return;
|
||||
}
|
||||
|
||||
var i := slot;
|
||||
block_set[i] = null;
|
||||
block_used--;
|
||||
i = (i + mask) & mask;
|
||||
while block_set[i] == tombstone as *mut block {
|
||||
block_set[i] = null;
|
||||
block_used--;
|
||||
i = (i + mask) & mask;
|
||||
}
|
||||
}
|
||||
|
||||
# Puts a large block in the set.
|
||||
def remember_large(made: *mut block): void {
|
||||
block_room();
|
||||
val slot := open_slot(made);
|
||||
if block_set[slot] == null {
|
||||
block_used++;
|
||||
}
|
||||
block_set[slot] = made;
|
||||
large_count++;
|
||||
}
|
||||
|
||||
# The live block whose data begins at `data`, stopping the program where there is
|
||||
# none: a pointer never allocated, already released, or within a block.
|
||||
def block_of(data: *mut u8): *mut block {
|
||||
if (data as u64) % 16 != 0 || (data as u64) < block_header {
|
||||
trap(error_invalid_release);
|
||||
}
|
||||
val found := (data - block_header) as *mut block;
|
||||
if !in_chunk(found as *mut u8) {
|
||||
if block_capacity == 0 || block_set[block_slot(found)] != found {
|
||||
trap(error_invalid_release);
|
||||
}
|
||||
}
|
||||
if ((*found).mark ^ (found as u64)) != live_key {
|
||||
trap(error_invalid_release);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
#! Allocates a zeroed block for `core::raw_allocate_zeroed`, as the machine does.
|
||||
#! @param size The number of bytes asked for.
|
||||
#! @returns The first byte of the block, after its header.
|
||||
#! @remarks A size no block can hold stops the program with `out of memory`.
|
||||
def allocate_zeroed(size: u64): *mut u8 {
|
||||
return allocate_cleared(size, true);
|
||||
}
|
||||
|
||||
#! Allocates a block for `core::raw_allocate`, which is not cleared.
|
||||
#! @param size The number of bytes asked for.
|
||||
#! @returns The first byte of the block, after its header.
|
||||
#! @remarks A size no block can hold stops the program with `out of memory`.
|
||||
def allocate(size: u64): *mut u8 {
|
||||
return allocate_cleared(size, false);
|
||||
}
|
||||
|
||||
# `allocate_zeroed` and `allocate`: a block too large to carve mapped on its
|
||||
# own; else, once the program has threads, one of the running thread's cache;
|
||||
# else one carved, or taken from those disposed of.
|
||||
def allocate_cleared(size: u64, cleared: bool): *mut u8 {
|
||||
if size > largest - block_header {
|
||||
return allocate_large(size, cleared);
|
||||
}
|
||||
if threaded {
|
||||
return cached_allocate(size, cleared);
|
||||
}
|
||||
hold();
|
||||
val made := allocate_held(size, cleared);
|
||||
let_go();
|
||||
return made;
|
||||
}
|
||||
|
||||
# Each thread's own free blocks of each class, once the program has threads,
|
||||
# which it takes and gives back without the lock: as many as `cache_room`
|
||||
# says of a class, past which half go back to the lists every thread shares,
|
||||
# and as many as `fill_cache` says taken from those at once where it has none.
|
||||
# A thread's blocks go back to the lists as it ends.
|
||||
struct block_cache {
|
||||
var heads: u64[47]; # The first block of each class, whose first word holds the next's address.
|
||||
var counts: u64[47]; # How many blocks each class has.
|
||||
}
|
||||
|
||||
val cache_most := 64u;
|
||||
val cache_batch := 16u;
|
||||
val cache_bytes_most := 262144u;
|
||||
|
||||
# How many blocks of a class a thread's cache holds before it gives half back:
|
||||
# `cache_most` of a small class, and of a larger as many as `cache_bytes_most`
|
||||
# bytes hold, but never fewer than 2.
|
||||
def cache_room(class: u64): u64 {
|
||||
if class < small_classes {
|
||||
return cache_most;
|
||||
}
|
||||
val fits := cache_bytes_most / size_of_class[class];
|
||||
if fits < 2 {
|
||||
return 2;
|
||||
}
|
||||
return fits > cache_most ? cache_most : fits;
|
||||
}
|
||||
|
||||
# Fills a thread's cache of a class it has none of from the lists every thread
|
||||
# shares, holding the lock: `cache_batch` blocks of a small class, carving what
|
||||
# the lists lack; of a larger, as many as half its room, but carving only one
|
||||
# where the lists have none, as what's carved is never given back to the
|
||||
# kernel.
|
||||
def fill_cache(held: *mut block_cache, class: u64): void {
|
||||
hold();
|
||||
val batch := class < small_classes ? cache_batch : cache_room(class) / 2;
|
||||
var taken: u64 = 0;
|
||||
while taken < batch {
|
||||
if taken > 0 && class >= small_classes && free_lists[class] == null {
|
||||
break;
|
||||
}
|
||||
val each := take(class, 0);
|
||||
set_word(each, held[0].heads[class]);
|
||||
held[0].heads[class] = each as u64;
|
||||
taken++;
|
||||
}
|
||||
held[0].counts[class] = taken;
|
||||
let_go();
|
||||
}
|
||||
|
||||
# The running thread's cache, made where it has none.
|
||||
def own_cache(): *mut block_cache {
|
||||
val me := current();
|
||||
var held := (*me).cache;
|
||||
if held == null {
|
||||
hold();
|
||||
held = acquire(size_of::<block_cache>()) as *mut block_cache;
|
||||
let_go();
|
||||
(*me).cache = held;
|
||||
}
|
||||
return held;
|
||||
}
|
||||
|
||||
# Allocates a block no larger than `largest` from the running thread's cache,
|
||||
# filling it from the lists every thread shares, under the lock, where it has
|
||||
# none of the class. A small block is cleared whole where it's to be, and a
|
||||
# larger as far as it's asked for.
|
||||
def cached_allocate(size: u64, cleared: bool): *mut u8 {
|
||||
val wanted := block_header + size;
|
||||
val class := class_for(wanted);
|
||||
val held := own_cache();
|
||||
if held[0].counts[class] == 0 {
|
||||
fill_cache(held, class);
|
||||
}
|
||||
|
||||
val made := held[0].heads[class] as *mut block;
|
||||
held[0].heads[class] = word(made as *u8);
|
||||
held[0].counts[class] -= 1;
|
||||
val total: u64 = size_of_class[class];
|
||||
if cleared {
|
||||
clear(made as *mut u8, class < small_classes ? total : wanted);
|
||||
}
|
||||
(*made).size = total - block_header;
|
||||
(*made).mark = (made as u64) ^ live_key;
|
||||
return (made as *mut u8) + block_header;
|
||||
}
|
||||
|
||||
# Gives a live block of the newest region's chunks back to the running thread's
|
||||
# cache, handing half of its class back to the lists every thread shares, under
|
||||
# the lock, past its `cache_room`. Gives false for any other pointer, which
|
||||
# `release` looks at under the lock. The region's bounds are read without
|
||||
# the lock, the end first: another thread opening a chunk only moves the end
|
||||
# past blocks the bounds read do not hold, and one reserving a region sets its
|
||||
# start before its end.
|
||||
def cached_release(data: *mut u8): bool {
|
||||
val address := data as u64;
|
||||
if address % 16 != 0 || address < block_header {
|
||||
return false;
|
||||
}
|
||||
val found := (data - block_header) as *mut block;
|
||||
val high := region_high;
|
||||
val low := region_low;
|
||||
if high < low || found as u64 - low >= high - low {
|
||||
return false;
|
||||
}
|
||||
if ((*found).mark ^ (found as u64)) != live_key {
|
||||
return false;
|
||||
}
|
||||
|
||||
val class := class_for(block_header + (*found).size);
|
||||
val held := own_cache();
|
||||
val room := cache_room(class);
|
||||
(*found).mark = 0;
|
||||
set_word(found as *mut u8, held[0].heads[class]);
|
||||
held[0].heads[class] = found as u64;
|
||||
held[0].counts[class] += 1;
|
||||
if held[0].counts[class] > room {
|
||||
hold();
|
||||
while held[0].counts[class] > room / 2 {
|
||||
val each := held[0].heads[class] as *mut u8;
|
||||
held[0].heads[class] = word(each);
|
||||
held[0].counts[class] -= 1;
|
||||
(each as *mut *mut u8)[0] = free_lists[class];
|
||||
free_lists[class] = each;
|
||||
}
|
||||
let_go();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# Gives a thread's cached blocks, and its cache, back to the lists every thread
|
||||
# shares, as it ends, holding the lock.
|
||||
def flush_cache(me: *mut state): void {
|
||||
val held := (*me).cache;
|
||||
if held == null {
|
||||
return;
|
||||
}
|
||||
for class in 0..classes {
|
||||
while held[0].counts[class] != 0 {
|
||||
val each := held[0].heads[class] as *mut u8;
|
||||
held[0].heads[class] = word(each);
|
||||
held[0].counts[class] -= 1;
|
||||
(each as *mut *mut u8)[0] = free_lists[class];
|
||||
free_lists[class] = each;
|
||||
}
|
||||
}
|
||||
dispose(held as *mut u8, size_of::<block_cache>());
|
||||
(*me).cache = null;
|
||||
}
|
||||
|
||||
# A block no larger than `largest`, carved or taken from those disposed of,
|
||||
# holding the lock around the runtime's memory: a small block cleared whole
|
||||
# where it's to be, and a larger as far as it's asked for.
|
||||
def allocate_held(size: u64, cleared: bool): *mut u8 {
|
||||
val wanted := block_header + size;
|
||||
val class := class_for(wanted);
|
||||
val total: u64 = size_of_class[class];
|
||||
val made := take(class, cleared ? (class < small_classes ? total : wanted) : 0) as *mut block;
|
||||
(*made).size = total - block_header;
|
||||
(*made).mark = (made as u64) ^ live_key;
|
||||
return (made as *mut u8) + block_header;
|
||||
}
|
||||
|
||||
# A block too large to carve: memory of as many pages that was kept, cleared
|
||||
# as far as it's asked for where it's to be, or else mapped, which the kernel
|
||||
# zeroed; taken from those kept and remembered among the large blocks holding
|
||||
# the lock, but mapped and cleared without it.
|
||||
def allocate_large(size: u64, cleared: bool): *mut u8 {
|
||||
if size > 0xFFFFFFFFFFFFFFFF - block_header - 4095 {
|
||||
trap(error_out_of_memory);
|
||||
}
|
||||
val total := pages(block_header + size);
|
||||
hold();
|
||||
var at := take_kept(total);
|
||||
let_go();
|
||||
if at == null {
|
||||
at = map(total);
|
||||
}
|
||||
else {
|
||||
if cleared {
|
||||
clear(at, block_header + size);
|
||||
}
|
||||
}
|
||||
|
||||
val made := at as *mut block;
|
||||
(*made).size = total - block_header;
|
||||
(*made).mark = (made as u64) ^ live_key;
|
||||
hold();
|
||||
remember_large(made);
|
||||
let_go();
|
||||
return at + block_header;
|
||||
}
|
||||
|
||||
#! Releases a block for `core::raw_release`, stopping the program where the
|
||||
#! pointer is not that of a live block. A large block not kept is unmapped
|
||||
#! after letting go of the lock.
|
||||
#! @param data The first byte of the block, or `null`, which does nothing.
|
||||
def release(data: *mut u8): void {
|
||||
if data == null {
|
||||
return;
|
||||
}
|
||||
if threaded && cached_release(data) {
|
||||
return;
|
||||
}
|
||||
hold();
|
||||
val found := block_of(data);
|
||||
val total := block_header + (*found).size;
|
||||
var unmapping := false;
|
||||
(*found).mark = 0;
|
||||
if total > largest {
|
||||
unset(block_slot(found));
|
||||
large_count--;
|
||||
unmapping = !keep_large(found as *mut u8, total);
|
||||
}
|
||||
else {
|
||||
dispose(found as *mut u8, total);
|
||||
}
|
||||
let_go();
|
||||
if unmapping {
|
||||
unmap(found as *mut u8, total);
|
||||
}
|
||||
}
|
||||
|
||||
# The bytes of data of the live block whose data begins at `data`: read
|
||||
# without the lock where the block lies among the newest region's chunks, as
|
||||
# `cached_release` reads it, else found holding the lock, stopping the program
|
||||
# where there's none.
|
||||
def live_size(data: *mut u8): u64 {
|
||||
if threaded {
|
||||
val address := data as u64;
|
||||
if address % 16 == 0 && address >= block_header {
|
||||
val found := (data - block_header) as *mut block;
|
||||
val high := region_high;
|
||||
val low := region_low;
|
||||
if high >= low && found as u64 - low < high - low && ((*found).mark ^ (found as u64)) == live_key {
|
||||
return (*found).size;
|
||||
}
|
||||
}
|
||||
}
|
||||
hold();
|
||||
val size := (*block_of(data)).size;
|
||||
let_go();
|
||||
return size;
|
||||
}
|
||||
|
||||
#! Moves a block to one of another size for `core::raw_resize`. A block whose
|
||||
#! memory is already of the size keeps its place, and on Linux a large block
|
||||
#! grown larger is remapped where it is, or moved by the kernel, rather than
|
||||
#! copied. Else a block is allocated, copied into, and the old one released, as
|
||||
#! `allocate` and `release` do, so what's copied is copied without the lock.
|
||||
#! @param data The first byte of the block, or `null` to allocate one.
|
||||
#! @param size The number of bytes the new block holds.
|
||||
#! @returns The first byte of the new block, which holds what the old one did,
|
||||
#! as far as it reaches, and may hold anything past that.
|
||||
def resize(data: *mut u8, size: u64): *mut u8 {
|
||||
if data == null {
|
||||
return allocate(size);
|
||||
}
|
||||
if size > 0xFFFFFFFFFFFFFFFF - block_header - 4095 {
|
||||
trap(error_out_of_memory);
|
||||
}
|
||||
|
||||
val had := live_size(data);
|
||||
val before := block_header + had;
|
||||
val total := acquired(block_header + size);
|
||||
if total == before {
|
||||
return data;
|
||||
}
|
||||
if total > largest && before > largest && total > before {
|
||||
val moved := remap_large(data, before, total);
|
||||
if moved != null {
|
||||
return moved;
|
||||
}
|
||||
}
|
||||
|
||||
val grown := allocate(size);
|
||||
copy_bytes(grown, data, had < size ? had : size);
|
||||
release(data);
|
||||
return grown;
|
||||
}
|
||||
module runtime when backend == native && os == linux;
|
||||
# A large block grown larger, remapped where it is or moved by the kernel,
|
||||
# holding the lock around the runtime's memory: it keeps its place among the
|
||||
# blocks, under its new address.
|
||||
def remap_large(data: *mut u8, before: u64, total: u64): *mut u8 {
|
||||
hold();
|
||||
val found := block_of(data);
|
||||
val moved := syscall(call_mremap, found as u64, before, total, 1, 0, 0);
|
||||
if moved < 0 {
|
||||
trap(error_out_of_memory);
|
||||
}
|
||||
unset(block_slot(found));
|
||||
large_count--;
|
||||
val made := moved as u64 as *mut block;
|
||||
(*made).size = total - block_header;
|
||||
(*made).mark = (made as u64) ^ live_key;
|
||||
remember_large(made);
|
||||
let_go();
|
||||
return (made as *mut u8) + block_header;
|
||||
}
|
||||
|
||||
module runtime when backend == native && os == windows;
|
||||
|
||||
# Windows maps memory in parts of 64 KiB, which takes no more memory than a page
|
||||
# where less is used, and gives back only all of what it mapped at once, as every
|
||||
# call of `unmap` does.
|
||||
def map(size: u64): *mut u8 {
|
||||
val address := VirtualAlloc(0, size, 0x3000, 0x04);
|
||||
if address == 0 {
|
||||
trap(31);
|
||||
}
|
||||
return address as *mut u8;
|
||||
}
|
||||
|
||||
def unmap(address: *mut u8, size: u64): void {
|
||||
VirtualFree(address as u64, 0, 0x8000);
|
||||
}
|
||||
|
||||
# Opens the chunk after the last, committing it, or the first of a new region
|
||||
# where this one is full. Windows counts what is committed against the memory it
|
||||
# has, so a chunk it cannot commit is the program running out of memory.
|
||||
def open_chunk(): void {
|
||||
if region_high + chunk_size > region_end {
|
||||
reserve();
|
||||
chunk = region_high as *mut u8;
|
||||
chunk_left = 0;
|
||||
}
|
||||
if VirtualAlloc(region_high, chunk_size, 0x1000, 0x04) == 0 {
|
||||
trap(error_out_of_memory);
|
||||
}
|
||||
region_high = region_high + chunk_size;
|
||||
chunk_left = chunk_left + chunk_size;
|
||||
}
|
||||
|
||||
# Reserves a region without access, as on Linux, down to a chunk.
|
||||
def reserve(): void {
|
||||
if region_low != 0 {
|
||||
keep_region();
|
||||
}
|
||||
|
||||
var size := region_size;
|
||||
while size >= chunk_size {
|
||||
val address := VirtualAlloc(0, size, 0x2000, 0x01);
|
||||
if address != 0 {
|
||||
region_low = address;
|
||||
region_high = address;
|
||||
region_end = address + size;
|
||||
return;
|
||||
}
|
||||
size = size / 2;
|
||||
}
|
||||
trap(error_out_of_memory);
|
||||
}
|
||||
|
||||
# Windows cannot move what it mapped elsewhere, so a large block grows as a
|
||||
# small one does, copied, as null says.
|
||||
def remap_large(data: *mut u8, before: u64, total: u64): *mut u8 {
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
#! @file start.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how an executable starts and stops: the arguments it gives `main`,
|
||||
#! exiting, and the report a fault gives.
|
||||
|
||||
import runtime::win32;
|
||||
|
||||
module runtime when backend == native;
|
||||
|
||||
#! Writes a view of the text of each argument into a slot, for `main`, leaving
|
||||
#! out the path of the executable, as the machine gives only those after it.
|
||||
#!
|
||||
#! A view owns nothing, so each one views the text the system left on the stack
|
||||
#! rather than a copy of it, and the run of views is a block the program keeps
|
||||
#! for as long as it runs.
|
||||
#! @param out The slot the view of the views is written to.
|
||||
def arguments(out: *mut u8): void {
|
||||
val info := executable();
|
||||
val argc := (*(*info).state).argc > 0 ? (*(*info).state).argc - 1 : 0;
|
||||
val argv := (*(*info).state).argv + 1;
|
||||
|
||||
val views := argc > 0 ? acquire(argc * 16) : null;
|
||||
for i in 0..argc {
|
||||
val text := argv[i] as *mut u8;
|
||||
var length := 0u;
|
||||
while text[length] != 0 {
|
||||
length++;
|
||||
}
|
||||
|
||||
val view := (views + i * 16) as *mut u64;
|
||||
view[0] = text as u64;
|
||||
view[1] = length;
|
||||
}
|
||||
|
||||
val slot := out as *mut u64;
|
||||
slot[0] = views as u64;
|
||||
slot[1] = argc;
|
||||
}
|
||||
|
||||
#! The vector instructions the program uses, of those the processor running it
|
||||
#! has, which the entry found by asking it as it started, one bit each: all of
|
||||
#! them, but where the variable `SAKURA_CPU` names fewer, only those, so the
|
||||
#! program runs as it would on a processor without the rest. It names them
|
||||
#! joined by `+`: `sse2`, `ssse3`, `sse4.1`, `sse4.2`, `avx`, `avx2`, `fma`,
|
||||
#! `popcnt`, `lzcnt`, `bmi1`, and `avx512`, or a level of x86-64, `x86-64`,
|
||||
#! `x86-64-v2`, `x86-64-v3`, or `x86-64-v4`, for those it has. SSE2 is every x86-64 processor's, so always
|
||||
#! kept.
|
||||
#! @param found The instruction sets the processor has.
|
||||
#! @returns Those the program uses.
|
||||
def processor(found: u64): u64 {
|
||||
val info := executable();
|
||||
val argc := (*(*info).state).argc;
|
||||
var at := (*(*info).state).argv + argc + 1;
|
||||
while at[0] != 0 {
|
||||
val text := at[0] as *u8;
|
||||
if named_at(text, 11, "SAKURA_CPU=") {
|
||||
return found & processor_named(text + 11);
|
||||
}
|
||||
at = at + 1;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
# The instruction sets `SAKURA_CPU` names, from its value.
|
||||
def processor_named(text: *u8): u64 {
|
||||
var allowed: u64 = 0x01;
|
||||
var start: u64 = 0;
|
||||
var i: u64 = 0;
|
||||
while true {
|
||||
val c := text[i];
|
||||
if c == 0 || c == '+' as u8 {
|
||||
val name := text + start;
|
||||
val length := i - start;
|
||||
if named_at(name, length, "ssse3") { allowed = allowed | 0x02; }
|
||||
if named_at(name, length, "sse4.1") { allowed = allowed | 0x04; }
|
||||
if named_at(name, length, "sse4.2") { allowed = allowed | 0x08; }
|
||||
if named_at(name, length, "avx") { allowed = allowed | 0x10; }
|
||||
if named_at(name, length, "avx2") { allowed = allowed | 0x20; }
|
||||
if named_at(name, length, "fma") { allowed = allowed | 0x40; }
|
||||
if named_at(name, length, "popcnt") { allowed = allowed | 0x80; }
|
||||
if named_at(name, length, "lzcnt") { allowed = allowed | 0x100; }
|
||||
if named_at(name, length, "bmi1") { allowed = allowed | 0x200; }
|
||||
if named_at(name, length, "avx512") { allowed = allowed | 0x400; }
|
||||
if named_at(name, length, "x86-64-v2") { allowed = allowed | 0x8F; }
|
||||
if named_at(name, length, "x86-64-v3") { allowed = allowed | 0x3FF; }
|
||||
if named_at(name, length, "x86-64-v4") { allowed = allowed | 0x7FF; }
|
||||
break if c == 0;
|
||||
start = i + 1;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return allowed;
|
||||
}
|
||||
|
||||
# Whether bytes are a name.
|
||||
def named_at(bytes: *u8, length: u64, name: strview): bool {
|
||||
return false if length != name.length;
|
||||
for k in 0..length {
|
||||
return false if bytes[k] != name[k];
|
||||
}
|
||||
return true;
|
||||
}
|
||||
module runtime when backend == native && os == linux;
|
||||
# Retries a system call interrupted by a signal.
|
||||
def retried(n: i64, a: u64, b: u64, c: u64): i64 {
|
||||
while true {
|
||||
val result := syscall(n, a, b, c, 0, 0, 0);
|
||||
if result != -4 {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
def write_all(file: u64, data: *u8, length: u64): void {
|
||||
var written := 0u;
|
||||
while written < length {
|
||||
val count := retried(call_write, file, (data + written) as u64, length - written);
|
||||
if count <= 0 {
|
||||
return;
|
||||
}
|
||||
written = written + count as u64;
|
||||
}
|
||||
}
|
||||
module runtime when backend == native;
|
||||
# The function whose code holds an address, or null.
|
||||
def function_at(address: u64): *function {
|
||||
val info := executable();
|
||||
for i in 0..(*info).function_count {
|
||||
val each := (*info).functions + i;
|
||||
if address >= (*each).start && address < (*each).end {
|
||||
return each;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
# Writes ` at name (path:line:column)` for an address within a function, unless
|
||||
# the function belongs to the runtime.
|
||||
def put_frame(into: *mut builder, address: u64): void {
|
||||
val found := function_at(address);
|
||||
if found == null || (*found).runtime != 0 || (*found).line_count == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
var line := (*found).lines;
|
||||
for i in 1..(*found).line_count {
|
||||
val next := (*found).lines + i;
|
||||
if (*next).offset as u64 > address - (*found).start {
|
||||
break;
|
||||
}
|
||||
line = next;
|
||||
}
|
||||
|
||||
# Code inlined names the function it came from, where it is, then each function
|
||||
# it was called within, where it was called, out to the function itself.
|
||||
val info := executable();
|
||||
val path := (*info).paths + (*line).path as u64;
|
||||
if (*line).site == 0 {
|
||||
put_place(into, (*found).name, (*found).name_length, (*path).bytes, (*path).length, (*line).line as u64, (*line).column as u64);
|
||||
return;
|
||||
}
|
||||
var site := (*info).sites + ((*line).site - 1) as u64;
|
||||
val inlined := (*info).functions + (*site).function as u64;
|
||||
put_place(into, (*inlined).name, (*inlined).name_length, (*path).bytes, (*path).length, (*line).line as u64, (*line).column as u64);
|
||||
while true {
|
||||
val called := (*info).paths + (*site).path as u64;
|
||||
var within := found;
|
||||
val parent := (*site).parent;
|
||||
if parent != 0 {
|
||||
within = (*info).functions + (*((*info).sites + (parent - 1) as u64)).function as u64;
|
||||
}
|
||||
put_place(into, (*within).name, (*within).name_length, (*called).bytes, (*called).length, (*site).line as u64, (*site).column as u64);
|
||||
break if parent == 0;
|
||||
site = (*info).sites + (parent - 1) as u64;
|
||||
}
|
||||
}
|
||||
|
||||
# Writes one frame of a trace: ` at name (path:line:column)`.
|
||||
def put_place(into: *mut builder, name: *u8, name_length: u64, path: *u8, path_length: u64, line: u64, column: u64): void {
|
||||
put_text(into, text_at);
|
||||
append(into, name, name_length);
|
||||
put_text(into, text_open);
|
||||
append(into, path, path_length);
|
||||
put_text(into, text_colon);
|
||||
put_unsigned(into, line);
|
||||
put_text(into, text_colon);
|
||||
put_unsigned(into, column);
|
||||
put_text(into, text_close);
|
||||
}
|
||||
module runtime when backend == native && os == linux;
|
||||
#! Stops the program with a status, having run everything asked of it.
|
||||
#! @param code The status to stop with.
|
||||
def exit(code: i64): void {
|
||||
syscall(call_exit_group, code as u64, 0, 0, 0, 0, 0);
|
||||
}
|
||||
module runtime when backend == native;
|
||||
#! Stops the program at once, reporting the functions that were running.
|
||||
#!
|
||||
#! The report is the one every fault gives, so an abort reads like any other way
|
||||
#! the program stops, and exits with the same status.
|
||||
def abort(): void {
|
||||
trap(error_aborted);
|
||||
}
|
||||
|
||||
# The text `fault` was given, which the report of its trap gives.
|
||||
var fault_data: *u8;
|
||||
var fault_length: u64;
|
||||
|
||||
#! Stops the program at once, reporting the text given, then the functions that
|
||||
#! were running, as every fault does.
|
||||
#! @param data The text's bytes.
|
||||
#! @param length How many there are.
|
||||
def fault(data: *u8, length: u64): void {
|
||||
# The lock is kept to the end, so a thread faulting beside it waits rather
|
||||
# than changing the text.
|
||||
hold();
|
||||
fault_data = data;
|
||||
fault_length = length;
|
||||
trap(error_faulted);
|
||||
}
|
||||
module runtime when backend == native && os == linux;
|
||||
#! Reports a trap and exits with 1: its error, then the functions it happened
|
||||
#! in, from the address the trap was called from and the chain of frame
|
||||
#! pointers.
|
||||
#! @param code The error, as the machine numbers them.
|
||||
#! @param address The address the trap was called from, in the function that
|
||||
#! faulted.
|
||||
#! @param chain The frame pointer of that function, whose saved frame
|
||||
#! pointers and return addresses lead to each caller.
|
||||
#! @remarks It does not return.
|
||||
def fail(code: i64, address: u64, chain: *mut u64): void {
|
||||
hold();
|
||||
val report := acquire(size_of::<builder>()) as *mut builder;
|
||||
put_text(report, text_prefix);
|
||||
if code == error_faulted && fault_data != null {
|
||||
append(report, fault_data, fault_length);
|
||||
} else {
|
||||
put_text(report, code >= 0 && code < 31 ? code as u64 : text_out_of_memory);
|
||||
}
|
||||
put_text(report, text_newline);
|
||||
|
||||
# A stack overflow is found entering the function called, so its caller is first.
|
||||
if code != 8 {
|
||||
put_frame(report, address - 1);
|
||||
}
|
||||
var each := chain;
|
||||
while each != null {
|
||||
put_frame(report, each[1] - 1);
|
||||
each = each[0] as *mut u64;
|
||||
}
|
||||
|
||||
write_all(2, (*report).data, (*report).length);
|
||||
syscall(call_exit_group, 1, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
module runtime when backend == native && os == windows;
|
||||
|
||||
# Writes to the standard output or error, a file `file` numbers as Linux does:
|
||||
# to a console as the text it is, and elsewhere as its bytes.
|
||||
def write_all(file: u64, data: *u8, length: u64): void {
|
||||
val handle := GetStdHandle((0xFFFFFFF6 - file) as u32);
|
||||
var mode: u32 = 0;
|
||||
if GetConsoleMode(handle, &mut mode) != 0 && write_console(handle, data, length) {
|
||||
return;
|
||||
}
|
||||
var written := 0u;
|
||||
while written < length {
|
||||
val left := length - written;
|
||||
val asked: u32 = left > 0x40000000 ? 0x40000000 : left as u32;
|
||||
var count: u32 = 0;
|
||||
if WriteFile(handle, data + written, asked, &mut count, null) == 0 || count == 0 {
|
||||
return;
|
||||
}
|
||||
written = written + count as u64;
|
||||
}
|
||||
}
|
||||
|
||||
#! Stops the program with a status, having run everything asked of it.
|
||||
#! @param code The status to stop with.
|
||||
def exit(code: i64): void {
|
||||
ExitProcess(code as u32);
|
||||
}
|
||||
|
||||
#! Reports a trap and exits with 1, as on Linux.
|
||||
#! @param code The error, as the machine numbers them.
|
||||
#! @param address The address the trap was called from, in the function that
|
||||
#! faulted.
|
||||
#! @param chain The frame pointer of that function, whose saved frame
|
||||
#! pointers and return addresses lead to each caller.
|
||||
#! @remarks It does not return.
|
||||
def fail(code: i64, address: u64, chain: *mut u64): void {
|
||||
hold();
|
||||
val report := acquire(size_of::<builder>()) as *mut builder;
|
||||
put_text(report, text_prefix);
|
||||
if code == error_faulted && fault_data != null {
|
||||
append(report, fault_data, fault_length);
|
||||
} else {
|
||||
put_text(report, code >= 0 && code < 31 ? code as u64 : text_out_of_memory);
|
||||
}
|
||||
put_text(report, text_newline);
|
||||
|
||||
# A stack overflow is found entering the function called, so its caller is first.
|
||||
if code != 8 {
|
||||
put_frame(report, address - 1);
|
||||
}
|
||||
var each := chain;
|
||||
while each != null {
|
||||
put_frame(report, each[1] - 1);
|
||||
each = each[0] as *mut u64;
|
||||
}
|
||||
|
||||
write_all(2, (*report).data, (*report).length);
|
||||
ExitProcess(1);
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
#! @file threads.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the threads of an executable: starting one with stacks of its own,
|
||||
#! ending it, and the lock every thread takes around the runtime's memory.
|
||||
#!
|
||||
#! Each thread has a record, which `gs` points at in it, holding its stack's
|
||||
#! bounds, its text being formatted, and the function it runs. The first
|
||||
#! thread's is the executable's state, and the records are a list from it.
|
||||
#! Until the program starts a thread, nothing here takes a lock.
|
||||
|
||||
import runtime::win32;
|
||||
|
||||
module runtime when backend == native;
|
||||
|
||||
|
||||
# Whether the program started a thread, after which the runtime's memory is
|
||||
# locked.
|
||||
var threaded: bool;
|
||||
|
||||
# The lock around the runtime's memory: its word, 0 where no thread holds it, 1
|
||||
# where one does, and 2 where others may wait, and the thread holding it, which may
|
||||
# take it again, as allocating while formatting does.
|
||||
var lock_word: atomic<u32>;
|
||||
var lock_owner: u64;
|
||||
var lock_depth: u64;
|
||||
|
||||
# The bytes of a record.
|
||||
val record_bytes := 256u;
|
||||
|
||||
# The stack past a thread's limit, reserved for reporting a trap, as
|
||||
# `native/native.sakura` reserves it.
|
||||
val stack_reserve := 262144u;
|
||||
module runtime when backend == native && os == linux;
|
||||
val call_getpid: i64 = 39;
|
||||
val call_clone_exit: i64 = 60;
|
||||
val call_rt_sigprocmask: i64 = 14;
|
||||
val call_tgkill: i64 = 234;
|
||||
val call_futex: i64 = 202;
|
||||
|
||||
#! Takes the lock around the runtime's memory, once the program has threads.
|
||||
def hold(): void {
|
||||
return if !threaded;
|
||||
val me := current() as u64;
|
||||
if lock_owner == me {
|
||||
lock_depth++;
|
||||
return;
|
||||
}
|
||||
if lock_word.exchange(1) != 0 {
|
||||
while lock_word.exchange(2) != 0 {
|
||||
syscall(call_futex, lock_address(), 0, 2, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
lock_owner = me;
|
||||
lock_depth = 1;
|
||||
}
|
||||
|
||||
#! Lets go of the lock around the runtime's memory.
|
||||
def let_go(): void {
|
||||
return if !threaded;
|
||||
lock_depth--;
|
||||
return if lock_depth != 0;
|
||||
lock_owner = 0;
|
||||
if lock_word.exchange(0) == 2 {
|
||||
syscall(call_futex, lock_address(), 1, 1, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
def lock_address(): u64 {
|
||||
return ((&mut lock_word) as *mut atomic<u32>) as u64;
|
||||
}
|
||||
|
||||
#! `op::start`: starts a thread running a function, with a stack of its own as
|
||||
#! large as the first thread's.
|
||||
#! @param body The function, two words, then the context it is given, a word.
|
||||
#! @returns The thread's number, or a negative error number.
|
||||
def start_thread(body: *mut u8): i64 {
|
||||
threaded = true;
|
||||
hold();
|
||||
reap();
|
||||
val first := (*executable()).state;
|
||||
val size := (*first).shadow_base as u64 - (*first).trap_frame as u64;
|
||||
val record := mapped(record_bytes) as *mut state;
|
||||
val stack := mapped(size);
|
||||
if record == null || stack == null {
|
||||
unmapped(record as *mut u8, record_bytes);
|
||||
unmapped(stack, size);
|
||||
let_go();
|
||||
return -12;
|
||||
}
|
||||
|
||||
(*record).itself = record;
|
||||
(*record).trap_frame = stack;
|
||||
(*record).shadow_limit = stack + stack_reserve;
|
||||
(*record).shadow_base = stack + size;
|
||||
(*record).map = stack;
|
||||
(*record).map_size = size;
|
||||
(*record).running = 1;
|
||||
copy_bytes((&mut record[0].body) as *mut u8, body, 24);
|
||||
(*record).next = (*first).next;
|
||||
(*first).next = record;
|
||||
|
||||
# Every signal is blocked while it starts, so the thread begins with them blocked,
|
||||
# and takes those it does once `gs` holds its record.
|
||||
var all: u64 = 0xFFFFFFFFFFFFFFFF;
|
||||
var kept: u64 = 0;
|
||||
syscall(call_rt_sigprocmask, 2, ((&mut all) as *mut u64) as u64, ((&mut kept) as *mut u64) as u64, 8, 0, 0);
|
||||
val number := clone_thread(record);
|
||||
syscall(call_rt_sigprocmask, 2, ((&mut kept) as *mut u64) as u64, 0, 8, 0, 0);
|
||||
if number < 0 {
|
||||
(*first).next = (*record).next;
|
||||
unmapped(record as *mut u8, record_bytes);
|
||||
unmapped(stack, size);
|
||||
}
|
||||
let_go();
|
||||
return number;
|
||||
}
|
||||
|
||||
#! What a thread runs, on its own stack: its function, then the end of it. The
|
||||
#! system clears its number once it has ended, and its stack is unmapped after.
|
||||
def thread_main(): void {
|
||||
val me := current();
|
||||
(*me).body((*me).context);
|
||||
hold();
|
||||
flush_cache(me);
|
||||
if (*me).builders != null {
|
||||
dispose((*me).builders as *mut u8, (*me).builder_capacity * size_of::<builder>());
|
||||
}
|
||||
(*me).running = 0;
|
||||
let_go();
|
||||
syscall(call_clone_exit, 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
# Unmaps the records and stacks of threads the system has ended.
|
||||
def reap(): void {
|
||||
val first := (*executable()).state;
|
||||
var link := first;
|
||||
while (*link).next != null {
|
||||
val each := (*link).next;
|
||||
if (*each).running == 0 && (*each).tid == 0 {
|
||||
(*link).next = (*each).next;
|
||||
unmapped((*each).map, (*each).map_size);
|
||||
unmapped(each as *mut u8, record_bytes);
|
||||
continue;
|
||||
}
|
||||
link = each;
|
||||
}
|
||||
}
|
||||
|
||||
# Maps memory, giving null where there is none.
|
||||
def mapped(size: u64): *mut u8 {
|
||||
val address := syscall(call_mmap, 0, size, 3, 0x4022, 0xFFFFFFFFFFFFFFFF, 0);
|
||||
return address < 0 ? null : address as *mut u8;
|
||||
}
|
||||
|
||||
def unmapped(address: *mut u8, size: u64): void {
|
||||
if address != null {
|
||||
syscall(call_munmap, address as u64, size, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
module runtime when backend == native && os == windows;
|
||||
|
||||
# On Windows each thread runs on a stack of the system's, which the system
|
||||
# reserves, commits as it grows, and frees as the thread ends, and the record's
|
||||
# word for its stack holds the thread's handle instead. The lock's word is
|
||||
# waited on as Linux waits on a futex.
|
||||
|
||||
#! Takes the lock around the runtime's memory, once the program has threads.
|
||||
def hold(): void {
|
||||
return if !threaded;
|
||||
val me := current() as u64;
|
||||
if lock_owner == me {
|
||||
lock_depth++;
|
||||
return;
|
||||
}
|
||||
if lock_word.exchange(1) != 0 {
|
||||
var contended: u32 = 2;
|
||||
while lock_word.exchange(2) != 0 {
|
||||
WaitOnAddress(lock_address() as *mut u32, &contended, 4, 0xFFFFFFFF);
|
||||
}
|
||||
}
|
||||
lock_owner = me;
|
||||
lock_depth = 1;
|
||||
}
|
||||
|
||||
#! Lets go of the lock around the runtime's memory.
|
||||
def let_go(): void {
|
||||
return if !threaded;
|
||||
lock_depth--;
|
||||
return if lock_depth != 0;
|
||||
lock_owner = 0;
|
||||
if lock_word.exchange(0) == 2 {
|
||||
WakeByAddressSingle(lock_address() as *mut u32);
|
||||
}
|
||||
}
|
||||
|
||||
def lock_address(): u64 {
|
||||
return ((&mut lock_word) as *mut atomic<u32>) as u64;
|
||||
}
|
||||
|
||||
#! `op::start`: starts a thread running a function, on a stack the system makes
|
||||
#! it, as large as the first thread's.
|
||||
#! @param body The function, two words, then the context it is given, a word.
|
||||
#! @returns The thread's number, or a negative error number.
|
||||
def start_thread(body: *mut u8): i64 {
|
||||
threaded = true;
|
||||
hold();
|
||||
reap();
|
||||
val first := (*executable()).state;
|
||||
|
||||
# The thread runs on a stack the system makes it, as large as the first
|
||||
# thread's.
|
||||
val size := (*first).shadow_base as u64 - (*first).trap_frame as u64;
|
||||
val record := mapped(record_bytes) as *mut state;
|
||||
if record == null {
|
||||
let_go();
|
||||
return -12;
|
||||
}
|
||||
|
||||
(*record).itself = record;
|
||||
(*record).map_size = size; # The system reserves its stack this large.
|
||||
(*record).running = 1;
|
||||
copy_bytes((&mut record[0].body) as *mut u8, body, 24);
|
||||
(*record).next = (*first).next;
|
||||
(*first).next = record;
|
||||
|
||||
val number := clone_thread(record);
|
||||
if number < 0 {
|
||||
(*first).next = (*record).next;
|
||||
unmapped(record as *mut u8, record_bytes);
|
||||
}
|
||||
let_go();
|
||||
return number;
|
||||
}
|
||||
|
||||
#! What a thread runs, on the stack the system made it: its function, then the
|
||||
#! end of it, after which it returns to `beginning`, which ends the thread. The
|
||||
#! system then signals its handle, and its record is unmapped after.
|
||||
def thread_main(): void {
|
||||
val me := current();
|
||||
(*me).body((*me).context);
|
||||
hold();
|
||||
flush_cache(me);
|
||||
if (*me).builders != null {
|
||||
dispose((*me).builders as *mut u8, (*me).builder_capacity * size_of::<builder>());
|
||||
}
|
||||
(*me).running = 0;
|
||||
let_go();
|
||||
}
|
||||
|
||||
# Unmaps the records of threads the system has ended, closing their handles; the
|
||||
# system frees their stacks itself.
|
||||
def reap(): void {
|
||||
val first := (*executable()).state;
|
||||
var link := first;
|
||||
while (*link).next != null {
|
||||
val each := (*link).next;
|
||||
val handle := (*each).spare_map[0];
|
||||
if (*each).running == 0 && WaitForSingleObject(handle, 0) == 0 {
|
||||
(*link).next = (*each).next;
|
||||
CloseHandle(handle);
|
||||
unmapped(each as *mut u8, record_bytes);
|
||||
continue;
|
||||
}
|
||||
link = each;
|
||||
}
|
||||
}
|
||||
|
||||
# Maps zeroed memory, giving null where there is none.
|
||||
def mapped(size: u64): *mut u8 {
|
||||
return VirtualAlloc(0, size, 0x3000, 0x04) as *mut u8;
|
||||
}
|
||||
|
||||
def unmapped(address: *mut u8, size: u64): void {
|
||||
if address != null {
|
||||
VirtualFree(address as u64, 0, 0x8000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
#! @file values.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the operations the code an executable is compiled to calls on
|
||||
#! values.
|
||||
#!
|
||||
#! The operations generated code calls on values, ports of those of
|
||||
#! `sources/machine.c`. Values are in their frame representation in slots, and
|
||||
#! in their memory representation within fixed arrays, structs, and objects.
|
||||
|
||||
module runtime when backend == native;
|
||||
|
||||
# Reads a scalar in memory as its frame representation.
|
||||
def read_scalar(dst: *mut u8, at: *mut u8, access: u64): void {
|
||||
if access == access_i8 {
|
||||
set_word(dst, (at as *mut i8)[0] as u64);
|
||||
}
|
||||
else if access == access_u8 {
|
||||
set_word(dst, at[0] as u64);
|
||||
}
|
||||
else if access == access_i16 {
|
||||
set_word(dst, (at as *mut i16)[0] as u64);
|
||||
}
|
||||
else if access == access_u16 {
|
||||
set_word(dst, (at as *mut u16)[0] as u64);
|
||||
}
|
||||
else if access == access_i32 {
|
||||
set_word(dst, (at as *mut i32)[0] as u64);
|
||||
}
|
||||
else if access == access_u32 {
|
||||
set_word(dst, (at as *mut u32)[0] as u64);
|
||||
}
|
||||
else if access == access_f32 {
|
||||
(dst as *mut f64)[0] = (at as *mut f32)[0] as f64;
|
||||
}
|
||||
else {
|
||||
set_word(dst, word(at));
|
||||
}
|
||||
}
|
||||
|
||||
# Writes a scalar in its frame representation to memory.
|
||||
def write_scalar(at: *mut u8, src: *mut u8, access: u64): void {
|
||||
if access == access_i8 || access == access_u8 {
|
||||
at[0] = word(src) as u8;
|
||||
}
|
||||
else if access == access_i16 || access == access_u16 {
|
||||
(at as *mut u16)[0] = word(src) as u16;
|
||||
}
|
||||
else if access == access_i32 || access == access_u32 {
|
||||
(at as *mut u32)[0] = word(src) as u32;
|
||||
}
|
||||
else if access == access_f32 {
|
||||
(at as *mut f32)[0] = (src as *mut f64)[0] as f32;
|
||||
}
|
||||
else {
|
||||
set_word(at, word(src));
|
||||
}
|
||||
}
|
||||
|
||||
# The field a union holds, by its index: its tag, or of one laid out without a
|
||||
# tag, its field of bytes where its first word is not null, and its empty one
|
||||
# where it is.
|
||||
def held_field(at: *mut u8, kind: *layout): u64 {
|
||||
val first := word(at);
|
||||
return first if ((*kind).flags & layout_niche) == 0;
|
||||
val first_empty := (*(*(*kind).fields).layout).size == 0;
|
||||
return (first != 0) == first_empty ? 1 : 0;
|
||||
}
|
||||
|
||||
# Whether values are equal: fixed arrays element by element, structs field by
|
||||
# field, and unions by variant and then value.
|
||||
def equal_values(a: *mut u8, b: *mut u8, kind: *layout): bool {
|
||||
if (*kind).kind == kind_float {
|
||||
if (*kind).access == access_f32 {
|
||||
return (a as *mut f32)[0] == (b as *mut f32)[0];
|
||||
}
|
||||
return (a as *mut f64)[0] == (b as *mut f64)[0];
|
||||
}
|
||||
|
||||
if (*kind).kind == kind_fixed {
|
||||
val element := (*kind).element;
|
||||
val plain := (*element).kind;
|
||||
if plain == kind_int || plain == kind_uint || plain == kind_bool || plain == kind_pointer {
|
||||
return compare_bytes(a, b, (*kind).size) == 0;
|
||||
}
|
||||
for i in 0..(*kind).count {
|
||||
if !equal_values(a + i * (*element).size, b + i * (*element).size, element) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (*kind).kind == kind_struct {
|
||||
for i in 0..(*kind).count {
|
||||
val field := (*kind).fields + i;
|
||||
if !equal_values(a + (*field).offset, b + (*field).offset, (*field).layout) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (*kind).kind == kind_union {
|
||||
val tag := held_field(a, kind);
|
||||
if tag != held_field(b, kind) || tag >= (*kind).count {
|
||||
return false;
|
||||
}
|
||||
val field := (*kind).fields + tag;
|
||||
return equal_values(a + (*field).offset, b + (*field).offset, (*field).layout);
|
||||
}
|
||||
|
||||
return compare_bytes(a, b, (*kind).size) == 0;
|
||||
}
|
||||
|
||||
# The helpers generated code calls.
|
||||
|
||||
#! `OP_EQUAL`: whether the values are equal.
|
||||
#! @param a One value, in its frame representation.
|
||||
#! @param b The other.
|
||||
#! @param kind The layout of their type.
|
||||
#! @returns Whether they are equal, as `==` compares them.
|
||||
def equal(a: *mut u8, b: *mut u8, kind: *layout): bool {
|
||||
return equal_values(a, b, kind);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
#! @file kernel32.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `runtime::win32`: the functions of `kernel32.dll` the runtime calls,
|
||||
#! as C functions the executable imports. The runtime declares its own, rather
|
||||
#! than read `system::windows`, since it ships with the compiler and reads
|
||||
#! `core` alone, and `system` is a package of its own. A program that reads
|
||||
#! both imports each function once, as an executable names a function a library
|
||||
#! is named for twice once. The functions Windows keeps for waiting on a word
|
||||
#! are in `waits.sakura`, since a file names one library on Windows.
|
||||
|
||||
extern import "kernel32.dll" when os == windows;
|
||||
|
||||
extern module runtime::win32 when os == windows;
|
||||
|
||||
pub def GetStdHandle(which: u32): u64;
|
||||
pub def CloseHandle(handle: u64): i32;
|
||||
pub def GetConsoleMode(handle: u64, mode: &mut u32): i32;
|
||||
pub def WaitForSingleObject(handle: u64, milliseconds: u32): u32;
|
||||
pub def GetCommandLineW(): *u16;
|
||||
pub def GetEnvironmentStringsW(): *mut u16;
|
||||
pub def FreeEnvironmentStringsW(block: *mut u16): i32;
|
||||
pub def ExitProcess(code: u32): void;
|
||||
pub def SetErrorMode(mode: u32): u32;
|
||||
|
||||
pub def WriteFile(
|
||||
handle: u64,
|
||||
from: *u8,
|
||||
length: u32,
|
||||
written: &mut u32,
|
||||
overlapped: *mut u8
|
||||
): i32;
|
||||
|
||||
pub def WriteConsoleW(
|
||||
handle: u64,
|
||||
from: *u16,
|
||||
length: u32,
|
||||
written: &mut u32,
|
||||
reserved: *mut u8
|
||||
): i32;
|
||||
|
||||
pub def VirtualAlloc(
|
||||
address: u64,
|
||||
size: u64,
|
||||
kind: u32,
|
||||
protection: u32
|
||||
): u64;
|
||||
|
||||
pub def VirtualFree(
|
||||
address: u64,
|
||||
size: u64,
|
||||
kind: u32
|
||||
): i32;
|
||||
|
||||
pub def MultiByteToWideChar(
|
||||
page: u32,
|
||||
flags: u32,
|
||||
bytes: *u8,
|
||||
count: i32,
|
||||
units: *mut u16,
|
||||
room: i32
|
||||
): i32;
|
||||
|
||||
pub def WideCharToMultiByte(
|
||||
page: u32,
|
||||
flags: u32,
|
||||
wide: *u16,
|
||||
count: i32,
|
||||
into: *mut u8,
|
||||
size: i32,
|
||||
fallback: *u8,
|
||||
used: *mut i32
|
||||
): i32;
|
||||
@@ -0,0 +1,20 @@
|
||||
#! @file waits.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the functions Windows keeps for waiting on a word, of
|
||||
#! `runtime::win32`, which the runtime's threads wait and wake with. They are a
|
||||
#! library of their own, and a file names one library on Windows.
|
||||
|
||||
extern import "api-ms-win-core-synch-l1-2-0.dll" when os == windows;
|
||||
|
||||
extern module runtime::win32 when os == windows;
|
||||
|
||||
pub def WaitOnAddress(
|
||||
at: *mut u32,
|
||||
compare: &u32,
|
||||
size: u64,
|
||||
milliseconds: u32
|
||||
): i32;
|
||||
pub def WakeByAddressSingle(at: *mut u32): void;
|
||||
@@ -0,0 +1,213 @@
|
||||
#! @file windows.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what the runtime needs of Windows: the functions of the system it
|
||||
#! calls, and how an executable finds the arguments and variables it started
|
||||
#! with.
|
||||
#!
|
||||
#! Windows has no system calls a program makes itself. The runtime calls the
|
||||
#! functions of kernel32 instead, as C functions the executable imports, and
|
||||
#! those of the library Windows names for the waits on an address, which
|
||||
#! `runtime::win32` declares. The other files of the runtime declare their
|
||||
#! functions that call the system once for each system, in sections of their
|
||||
#! own.
|
||||
|
||||
import runtime::win32;
|
||||
|
||||
module runtime when backend == native && os == windows;
|
||||
|
||||
|
||||
# What the functions of the system are given is written where they are called,
|
||||
# as numbers, since `system_start` and what it calls run before the globals,
|
||||
# constants among them, are set: UTF-8's code page is 65001, memory is
|
||||
# committed with 0x1000, reserved with 0x2000, and released with 0x8000, and it
|
||||
# is read and written with 0x04, or not at all with 0x01.
|
||||
|
||||
#! Finds the arguments and variables the program started with, before anything
|
||||
#! else runs, as Linux leaves them on the first thread's stack: views of their
|
||||
#! texts in a run of words, the arguments, a zero, the variables, and a zero,
|
||||
#! which the state's `argv` points at and whose arguments its `argc` counts.
|
||||
#! Windows gives them in UTF-16, the arguments as one line, so they are
|
||||
#! converted to UTF-8, and the line split as Microsoft's C library splits it.
|
||||
#! Every block is mapped and kept for as long as the program runs.
|
||||
#! @remarks It runs before the globals are set, and before a trap could be
|
||||
#! reported, so it exits with 2 where there is no memory, as the start
|
||||
#! does.
|
||||
def system_start(): void {
|
||||
# A failure of the program nothing reports ends it, as one would on Linux,
|
||||
# rather than asking the user what to do: SEM_FAILCRITICALERRORS,
|
||||
# SEM_NOGPFAULTERRORBOX, and SEM_NOOPENFILEERRORBOX.
|
||||
SetErrorMode(0x8003);
|
||||
|
||||
val line := GetCommandLineW();
|
||||
var units := 0u;
|
||||
while line[units] != 0 {
|
||||
units++;
|
||||
}
|
||||
val line_room := units * 3 + 1;
|
||||
val line_text := start_map(line_room);
|
||||
var length := 0u;
|
||||
if units > 0 {
|
||||
length = WideCharToMultiByte(65001, 0, line, units as i32, line_text, line_room as i32, null, null) as u64;
|
||||
}
|
||||
# Splitting gives no more bytes than the line has, and a zero after each argument.
|
||||
val arguments := start_map(2 * length + 2);
|
||||
val argc := split_arguments(line_text, arguments);
|
||||
|
||||
# The variables end at an empty one, and those Windows keeps of each drive,
|
||||
# named from `=`, are left out.
|
||||
val block := GetEnvironmentStringsW();
|
||||
var total := 0u;
|
||||
while block != null && (block[total] != 0 || block[total + 1] != 0) {
|
||||
total++;
|
||||
}
|
||||
val variables_room := total * 3 + 2;
|
||||
val variables := start_map(variables_room);
|
||||
var bytes := 0u;
|
||||
if total > 0 {
|
||||
bytes = WideCharToMultiByte(65001, 0, block, (total + 1) as i32, variables, variables_room as i32, null, null) as u64;
|
||||
}
|
||||
if block != null {
|
||||
FreeEnvironmentStringsW(block);
|
||||
}
|
||||
var envc := 0u;
|
||||
var at := 0u;
|
||||
while at < bytes && variables[at] != 0 {
|
||||
if variables[at] != '=' as u8 {
|
||||
envc++;
|
||||
}
|
||||
while variables[at] != 0 {
|
||||
at++;
|
||||
}
|
||||
at++;
|
||||
}
|
||||
|
||||
val words := start_map((argc + envc + 2) * 8) as *mut u64;
|
||||
var word := 0u;
|
||||
at = 0;
|
||||
for i in 0..argc {
|
||||
words[word] = (arguments + at) as u64;
|
||||
word++;
|
||||
while arguments[at] != 0 {
|
||||
at++;
|
||||
}
|
||||
at++;
|
||||
}
|
||||
word++;
|
||||
at = 0;
|
||||
while at < bytes && variables[at] != 0 {
|
||||
if variables[at] != '=' as u8 {
|
||||
words[word] = (variables + at) as u64;
|
||||
word++;
|
||||
}
|
||||
while variables[at] != 0 {
|
||||
at++;
|
||||
}
|
||||
at++;
|
||||
}
|
||||
|
||||
val first := (*executable()).state;
|
||||
(*first).argc = argc;
|
||||
(*first).argv = words;
|
||||
}
|
||||
|
||||
# Maps zeroed memory for `system_start`, exiting with 2 where there is none.
|
||||
def start_map(size: u64): *mut u8 {
|
||||
val address := VirtualAlloc(0, size, 0x3000, 0x04);
|
||||
if address == 0 {
|
||||
ExitProcess(2);
|
||||
}
|
||||
return address as *mut u8;
|
||||
}
|
||||
|
||||
# Splits a command line into arguments as Microsoft's C library does, writing
|
||||
# each into `into`, which is zeroed, with a zero after it, and gives how many
|
||||
# there are. The path of the program ends at the first space or tab outside
|
||||
# quotes, and quotes only begin and end the parts of it within them. In each
|
||||
# argument after it, quotes do too, but within quotes two are one, and
|
||||
# backslashes are themselves but before a quote, where each two are one, and
|
||||
# one left over makes the quote one.
|
||||
def split_arguments(line: *u8, into: *mut u8): u64 {
|
||||
var at := 0u;
|
||||
var out := 0u;
|
||||
var quoted := false;
|
||||
while line[at] != 0 && (quoted || (line[at] != ' ' as u8 && line[at] != '\t' as u8)) {
|
||||
if line[at] == '"' as u8 {
|
||||
quoted = !quoted;
|
||||
} else {
|
||||
into[out] = line[at];
|
||||
out++;
|
||||
}
|
||||
at++;
|
||||
}
|
||||
out++;
|
||||
var count := 1u;
|
||||
|
||||
quoted = false;
|
||||
while true {
|
||||
while line[at] == ' ' as u8 || line[at] == '\t' as u8 {
|
||||
at++;
|
||||
}
|
||||
break if line[at] == 0;
|
||||
while true {
|
||||
var kept := true;
|
||||
var backslash := 0u;
|
||||
while line[at] == '\\' as u8 {
|
||||
at++;
|
||||
backslash++;
|
||||
}
|
||||
if line[at] == '"' as u8 {
|
||||
if backslash % 2 == 0 {
|
||||
if quoted && line[at + 1] == '"' as u8 {
|
||||
at++;
|
||||
} else {
|
||||
kept = false;
|
||||
quoted = !quoted;
|
||||
}
|
||||
}
|
||||
backslash = backslash / 2;
|
||||
}
|
||||
while backslash > 0 {
|
||||
into[out] = '\\' as u8;
|
||||
out++;
|
||||
backslash--;
|
||||
}
|
||||
break if line[at] == 0 || (!quoted && (line[at] == ' ' as u8 || line[at] == '\t' as u8));
|
||||
if kept {
|
||||
into[out] = line[at];
|
||||
out++;
|
||||
}
|
||||
at++;
|
||||
}
|
||||
out++;
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
# Writes text to a console, which takes UTF-16, converting it a part at a time
|
||||
# in memory of its own, or giving up where there is none, and gives whether it
|
||||
# did.
|
||||
def write_console(handle: u64, data: *u8, length: u64): bool {
|
||||
val part := 16384u;
|
||||
val units := VirtualAlloc(0, part * 2, 0x3000, 0x04) as *mut u16;
|
||||
return false if units == null;
|
||||
var at := 0u;
|
||||
while at < length {
|
||||
# A part ends before the bytes after the first of a character, never within it.
|
||||
var end := length - at > part ? at + part : length;
|
||||
while end < length && end > at && (data[end] & 0xC0) == 0x80 {
|
||||
end--;
|
||||
}
|
||||
val count := MultiByteToWideChar(65001, 0, data + at, (end - at) as i32, units, part as i32);
|
||||
var done: u32 = 0;
|
||||
if count <= 0 || WriteConsoleW(handle, units, count as u32, &mut done, null) == 0 {
|
||||
break;
|
||||
}
|
||||
at = end;
|
||||
}
|
||||
VirtualFree(units as u64, 0, 0x8000);
|
||||
return true;
|
||||
}
|
||||
Reference in new issue
Block a user