#! @file native.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the building of executables: the image the runtime reads, the code #! of every function, the stubs a trap and a fault are reported through, the #! entry the system starts the program at, and the file, a static x86-64 Linux #! executable loaded at a fixed address as four segments: #! #! read the file headers, then the image the runtime reads #! read, write the state of the runtime and the program's globals, zeroed #! read, execute the stubs, `_start`, then every function #! read the line tables of the functions #! #! Frames are on the stack, each below the caller's return address and frame #! pointer, so a trap reports where it happened by walking the chain of `rbp`. #! A function saves the registers a call keeps that it uses in its frame. The #! runtime, the module `runtime` of the library found beside the compiler, is #! compiled into each executable as the rest of the program is. import std::containers; import std::io; import std::thread; import sakura::analyzer; import sakura::compiler; import binary::amd64; import binary::elf; import binary::pe; module sakura::native; #! The functions of `runtime` the generated code calls. pub enum helper : u8 { fail, #! Reports a trap, given its error, where, and the chain of frames. arguments, #! Writes the arguments of `main`. allocate_zeroed, #! Allocates a zeroed block. allocate, #! Allocates a block not cleared. release, #! Releases a block. resize, #! Resizes a block. equal, #! Whether values are equal. format_begin, #! Begins text. format_text, #! Adds bytes to text. format_value, #! Adds a value to text. format_owned, #! Takes the text made. exit, #! Exits with a status. abort, #! Stops the program, reporting where. fault, #! Stops the program, reporting why and where. processor, #! The vector instructions the program may use, of those the processor has. start_thread, #! Starts a thread running a function. thread_main, #! What a thread runs on its own stack. count, #! How many there are; no helper itself. } #! The version of what the generated code shares with the runtime: the #! helpers, the words of `state`, and the records the compiler writes. It #! changes whenever any of them does, and a runtime says which it implements #! as `runtime::abi`. pub const runtime_abi: u32 = 1; #! The name of each helper, as `runtime` declares it, and how many #! parameters it takes. const helper_names: strview[17] = [ "fail", "arguments", "allocate_zeroed", "allocate", "release", "resize", "equal", "format_begin", "format_text", "format_value", "format_owned", "exit", "abort", "fault", "processor", "start_thread", "thread_main" ]; const helper_arities: u32[17] = [3, 1, 1, 1, 1, 2, 3, 0, 2, 2, 1, 1, 0, 2, 1, 1, 0]; # The words of the runtime's state, as `runtime::state` declares them, # and those the code keeps after them. pub const state_base: u64 = 0; #! The top of the stack, where frames begin. pub const state_limit: u64 = 1; #! The lowest a frame may reach. pub const state_trap_frame: u64 = 2; #! The bottom of the stack, past the limit, which a trap's report may use. pub const state_itself: u64 = 3; #! The record itself. pub const state_argc: u64 = 4; #! The arguments the program started with. pub const state_argv: u64 = 5; pub const state_reporting: u64 = 6; #! Whether a trap is being reported, which another trap ends at once. pub const state_c_top: u64 = 7; pub const state_c_frame: u64 = 8; pub const state_c_return: u64 = 9; pub const state_features: u64 = 10; #! The vector instructions the program may use, as the processor running it has them. pub const state_signals: u64 = 11; #! The signals the program handles that came since it last asked, one bit each; only the first thread's notes them. pub const state_own: u64 = 12; #! On Windows, where the slot of the system's record of the thread holds the thread's own record: `0x1480 + 8 * TlsAlloc()`. # Threads, each of which has a record of these words, which `gs` points at in it: # the first thread's is the state, and holds what they all share. pub const state_next: u64 = 13; #! The next thread's record. pub const state_tid: u64 = 14; #! The system's number for the thread, which the system clears as it ends. pub const state_body: u64 = 19; #! Two words: the function the thread runs, then a word: the context it is given. pub const state_map: u64 = 22; #! Where the thread's stack is mapped, and its bytes. pub const state_map_size: u64 = 23; pub const state_handle: u64 = 24; #! On Windows, the thread's handle, which reaping it waits on. pub const state_saved: u64 = 25; #! On Windows, where the stack the system started the thread on was, which it ends on. pub const state_running: u64 = 26; #! 1 while the thread runs. pub const state_signalled: u64 = 29; #! On Windows, of the first: the event the handler sets when it notes a signal, which a wait waits on, or 0. pub const state_disposed: u64 = 30; #! On Windows, of the first: a signal caught in a bit, one ignored in the bit 32 above it, and the console's handler being set in bit 0. pub const state_words: u64 = 32; #! The slots the system's record of a thread holds its own slots in, as the base #! `gs` points at, which the chosen slot is `8 *` its index past. pub const tls_slots: u64 = 0x1480; pub const tls_count: u64 = 64; #! The memory of a word of the running thread's own record. On Linux `gs` #! points at it, so a word is at the offset through `gs`. On Windows `gs` #! points at the system's record of the thread, a slot of which the start #! chose for the thread's own record, so it is read from the slot into `rcx` #! first, which no instruction keeps anything in across another. #! @param this The building. #! @param word The word. #! @returns The memory. pub def building::own_word(&mut this, word: u64): mem { if !this.options.windows { return own(8 * word); } this.own_record(reg::rcx); return at(reg::rcx, (8 * word) as i32); } #! Loads the address of the running thread's own record, on Windows, from the #! slot of the system's record of the thread the state names. #! @param this The building. #! @param into The register, which is 0 on a thread the program never started. pub def building::own_record(&mut this, into: reg): void { this.text.load(8, false, into, amd64::absolute(this.state_address(state_own))); this.text.load(8, false, into, own_at(into)); } #! Where the executable is loaded, and the size of a page. pub const base_address: u64 = 0x400000; pub const page_size: u64 = 0x1000; #! Bytes of the stack past its limit, which a trap's report runs in. pub const stack_reserve: u64 = 262144; #! The bytes of the stack, unless asked otherwise. pub const default_stack: u64 = 33554432; #! How many texts the image holds: the descriptions of the machine's errors by #! their codes, then the fragments of a report. const text_count: u64 = 38; #! What a vtable's slot names where it names its function itself. const direct_method: u64 = 0xFFFFFFFFFFFFFFFF; #! Where in a function's code the code from a place in the source begins. pub struct line_row { var offset: u64; #! From where the function begins. var at: u64; #! Where in the source: one more than the file, then the byte, or 0 for the function's declaration. var site: u32; #! One more than the inline site it is in, or 0. } #! How an executable is built. pub struct build_options { pub var output: strview; #! The file it is written to. pub var verify: bool; #! Whether where each function's values were placed is checked, by replaying it. var stack: u64; #! The bytes of its stack, or 0 for the default. pub var debug: bool; #! Whether its debugging information is written too, to OUTPUT.petal. pub var windows: bool; #! Whether it is built for Windows, rather than Linux. pub var threads: u32; #! How many threads place the values of functions at once, beside the one selecting their code; 0 or 1 for that one alone. # What a Windows executable shows itself by, which one for Linux holds none # of: a desktop entry beside it names its icon there. pub var icons: span; #! The bytes of each PNG or icon file its icon's images are, each PNG at most 256 pixels each way. pub var title: strview; #! What its properties call it, or empty for its file's name. pub var semv: strview; #! The version its properties give, as `1.2.0`, or empty. pub var windowed: bool; #! Whether it runs in windows of its own, with no console. } #! What building an executable keeps. pub struct building { var c: &mut lowerer; #! The program, lowered and optimized. var options: build_options; var problems: vector; #! What could not be built. var rodata: byte_writer; #! The image, after the file headers. var text: assembly; #! The code. var late: byte_writer; #! The line tables. var rodata_base: u64; var data_base: u64; var data_size: u64; var text_base: u64; var late_base: u64; var globals: u64; #! Where the globals are. var got: u64; #! Where the words holding the addresses of C functions are. var slots: vector; #! The word of each C function the code names, or `never`. var linked_count: u64; #! How many C functions the code names, each given a word. var dynamic: bool; #! Whether the executable calls C, so the system's loader runs it. var dynamic_parts: elf::linking; #! Where what the loader reads is. var relocations: u64; #! Within the image, where the loader is told of each word. var entries: vector; #! Of each function C calls, the code C calls it through. # Windows: the functions imported, and the records the loader reads. var imports_at: vector; #! Of each of the backend's own system imports, its word in the table of addresses. var import_names: vector; #! Of each word of the table of addresses, where its function's name is, which the loader overwrites, or 0 for a library's terminator. var import_firsts: vector; #! Of each library, its first word in the table of addresses. var descriptors: u64; #! Within the image, the record of each library imported. var library_count: u64; #! How many libraries are imported. var import_words: u64; #! Words in the table of addresses, each library's and a terminator. # Where records are, as addresses, or offsets within the image. var image_address: u64; var image_at: u64; var texts_at: u64; var layouts_at: u64; var function_table: u64; #! The address of each function, by index, as a function value holds it less one. var vtable_table: u64; #! The address of each vtable's methods. var records_at: u64; var callbacks_at: u64; var data_at: vector; #! Of each datum. var vtable_methods: vector; #! Of each vtable's methods. var retraits_at: vector; #! Of each map between traits' vtables. var callback_slots: vector; #! Of each function C calls, its word among the callbacks', or `never`. var helpers: u32[17]; #! The function of each helper. var system_start_function: u32; #! On Windows, `runtime::system_start`, which the start runs before the globals. var runtime: vector; #! Whether each function is the runtime's, which traces leave out. var starts: vector; #! Where each function's code begins in the text. var ends: vector; #! Where it ends. var calls: fixup_list; #! Each call or jump to a function, by where its displacement is, and the function. var methods: vector; #! The code each vtable's slot names, by vtable then slot. var rows: vector; #! Each function's rows of its line table, one after another. var row_first: vector; #! Where each function's rows begin in `rows`. var debug: debugging; #! What debugging information needs, where it is written. # Code every function shares. var trap_stub: u64; var trap_framed: u64; #! Where the trap stub has pushed `rbp`, var trap_based: u64; #! and where it has made its frame. var faults: u64; var restorer: u64; var noting: u64; # Windows only. var signalled: u64; #! Where a signal the program handles is noted, by its number in `rcx`. var catching: u64; #! What `catch_signal` calls, with what it is asked in `rcx`. var stranger: u64; #! What a callback on a thread the program never started reports through. var beginning: u64; #! Where a thread the program starts begins, with its record in `rcx`. var overflow_stub: u64; var missing: u64; #! What a function never lowered begins at. var missing_method: u64; #! What a slot of a vtable no function fills names. var safe_point: u64; #! The code a safe point calls where a signal came, once written, or `never`. var start: u64; var entry_end: u64; #! Where `_start` ends. var code_end: u64; #! Where the fault handler's comparison with the end of the code is. var stack: u64; } #! Builds an executable of a program, lowered and optimized, writing it to its #! file. #! @param c The program. #! @param options How it is built. #! @returns What could not be built, which is nothing where it was written. pub def build_executable(c: &mut lowerer, options: build_options): vector { var b := building { c = c, options = options, problems = vector::::new(), rodata = byte_writer::new(), text = assembly::new(), late = byte_writer::new(), data_at = vector::::new(), vtable_methods = vector::::new(), retraits_at = vector::::new(), callback_slots = vector::::new(), slots = vector::::new(), entries = vector::::new(), imports_at = vector::::new(), import_names = vector::::new(), import_firsts = vector::::new(), runtime = vector::::new(), starts = vector::::new(), ends = vector::::new(), calls = fixup_list::new(nothing {}), methods = vector::::new(), rows = vector::::new(), row_first = vector::::new(), debug = debugging::new(), stack = options.stack != 0 ? round_up(options.stack, page_size) : default_stack, safe_point = never as u64 }; b.prepare(); if b.problems.length != 0 { return move(&mut b.problems); } # The image and the data are placed before the code, which refers to them. val headers := options.windows ? pe::headers_size : elf::headers_size(4, b.dynamic); b.rodata_base = base_address + headers; b.image(); if options.windows { b.imports(); } else if b.dynamic { b.dynamic_records(); } b.data_base = round_up(b.rodata_base + b.rodata.length, page_size); b.globals = b.data_base + state_words * 8; b.got = b.globals + round_up(b.c.program.globals, 8); b.data_size = b.got - b.data_base + (options.windows ? b.import_words : b.linked_count) * 8; if options.windows { # The loader finds each library by its descriptor, whose words it fills from # the table of addresses once that is placed. b.relocate_imports(); } else { for i in 0..b.linked_count { b.rodata.set_u64(b.relocations + 24 * i, b.got + 8 * i); } } b.text_base = round_up(b.data_base + b.data_size, page_size); b.image_address = b.rodata_base + b.image_at; b.rodata.set_u64(b.image_at, b.data_base); b.rodata.set_u64(b.image_at + 7 * 8, b.globals); b.shared_code(); if options.windows { b.entry_windows(); } else { b.entry(); } val count := b.c.program.functions.length; b.starts.resize(count); b.ends.resize(count); b.row_first.resize(count + 1); # How each prologue saves registers is noted for Windows, whose executables # say how each function unwinds, as well as for debugging information. if options.debug || options.windows { b.debug.resize(count); } if options.debug { b.lay_out_variables(); } b.select_all(count); b.row_first[count] = b.rows.length as u32; if options.debug { b.debug.return_first[count] = b.debug.returns.length as u32; b.debug.variable_first[count] = b.debug.variables.length as u32; } b.adapters(); b.entries.resize(count); for i in 0..count { if b.callback_slots[i] != never { b.entries[i] = b.callback_entry(i as u32); } } b.calls.resolve(&mut b.text, b.starts.span); b.text.set_u32(b.code_end, b.text_base + b.text.length); b.late_base = round_up(b.text_base + b.text.length, page_size); b.places(); if b.problems.length == 0 { b.write(); } return move(&mut b.problems); } #! Works out the layout of each variable of each function, which debugging #! information names its type by. It is done once the image is written, so the #! layouts it makes leave the image as it is without debugging information. #! @param this The building. def building::lay_out_variables(&mut this): void { for f in 0..this.c.program.functions.length { for v in 0..this.c.program.functions[f].body.variables.length { val kind: u32 = this.c.program.functions[f].body.variables[v].kind; val layout := this.c.layout_of(kind); this.c.program.functions[f].body.variables[v].layout = layout; } } } #! Notes what could not be built. #! @param this The building. #! @param what What, said in words. def building::problem(&mut this, what: strview): void { this.problems.append(string::from(what, nothing {})); } # Preparing. #! Whether a declaration is the runtime's, of the module `runtime`. #! @param this The building. #! @param decl The declaration. #! @returns Whether it is. def building::in_runtime(&this, decl: u32): bool { return false if decl == 0; val owner: u32 = this.c.checker.decls.modules.p[decl]; return owner != 0 && this.c.checker.modules.parents[owner] == 0 && this.c.checker.names.text(this.c.checker.modules.names[owner]) == "runtime"; } #! Whether the runtime implements the ABI the compiler calls, as its `abi` #! says, noting a problem where it doesn't. #! @param this The building. #! @param runtime The module `runtime`. #! @returns Whether it does. def building::runtime_fits(&mut this, runtime: u32): bool { val name := this.c.checker.names.intern(&"abi"); val decl := this.c.checker.modules.decl(runtime, name); var held := constant {}; val known := decl != 0 && this.c.checker.decl_value(decl, &mut held); return true if known && !held.negative && held.magnitude == runtime_abi as u64; var text := string::from("The runtime ", nothing {}); if known { val said := $"implements ABI {held.magnitude}"; text.append(said.span); } else { text.append("declares no `abi`"); } val calls := $", and this compiler calls ABI {runtime_abi}: "; text.append(calls.span); text.append("give it the runtime of its release, by `--lib runtime=DIR`."); this.problem(text.span); return false; } #! Finds the runtime's helpers, which every function lowered calls, and lowers #! them where nothing else made them. #! @param this The building. def building::prepare(&mut this): void { if this.c.program.main == no_function { this.problem("Program has no `main` function."); return; } val runtime := this.c.checker.modules.find(0, this.c.checker.names.intern(&"runtime")); if runtime == 0 { this.problem("The program has no runtime: no `--lib runtime=DIR` names one, and no `runtime` folder is beside the compiler or above it."); return; } return if !this.runtime_fits(runtime); for h in 0..helper::count as u64 { val decl := this.c.checker.modules.decl(runtime, this.c.checker.names.intern(&helper_names[h])); if decl == 0 || this.c.checker.decls.kinds.p[decl] != dk::function { this.problem($"Declare `runtime::{helper_names[h]}`, taking {helper_arities[h]} parameters."); continue; } this.helpers[h] = this.c.function_of(decl, 0); } # The start on Windows runs this before the globals, to find the arguments. if this.options.windows { val decl := this.c.checker.modules.decl(runtime, this.c.checker.names.intern(&"system_start")); if decl == 0 || this.c.checker.decls.kinds.p[decl] != dk::function { this.problem("Declare `runtime::system_start`, taking 0 parameters."); } else { this.system_start_function = this.c.function_of(decl, 0); } } return if this.problems.length != 0; # The helpers are called by name, so none is dropped, nor inlined away. for h in 0..helper::count as u64 { this.c.program.functions[this.helpers[h]].taken = true; } if this.options.windows { this.c.program.functions[this.system_start_function].taken = true; } this.c.drain(); this.c.optimize(); this.c.drop_unreached_functions(); for k in 0..this.c.problems.length { this.problems.append(string::copy_of(&this.c.problems[k])); } val count := this.c.program.functions.length; this.runtime.resize(count); for i in 0..count { this.runtime[i] = this.in_runtime(this.c.program.functions[i].decl); } # Only the C functions the code names are linked, each from the libraries its # file names, since an executable has nothing else to find them in. val linked := this.c.program.linked.length; this.slots.resize(linked, never); for i in 0..count { val function := &this.c.program.functions[i]; continue if !function.lowered; var walk := function.body.walk_all(); while walk.more() { val held: inst = function.body.insts[walk.next()]; if held.kind == op::c_address && this.slots[held.aux] == never { this.slots[held.aux] = (linked + 1) as u32; } } } for l in 0..linked { continue if this.slots[l] == never; if this.c.program.linked[l].library.length == 0 { val decl: u32 = this.c.program.linked[l].decl; this.problem_at(decl, "An executable finds a C function in a library its file names with `extern import`, and this file names none."); continue; } this.slots[l] = this.linked_count as u32; this.linked_count++; } this.dynamic = this.linked_count != 0; } #! Notes what could not be built at a declaration. #! @param this The building. #! @param decl The declaration. #! @param what What, said in words. def building::problem_at(&mut this, decl: u32, what: strview): void { val file: u32 = this.c.checker.decls.files.p[decl]; val node: u32 = this.c.checker.decls.nodes.p[decl]; val held := &this.c.checker.units[file].source; val syntax := &this.c.checker.units[file].syntax; val offset := syntax.token_offsets[syntax.node_tokens[node]]; val place := held.lines.place_of(offset); this.problems.append($"{held.path}:{place.line}:{place.column}: {what}"); } #! The function of a helper. #! @param this The building. #! @param which The helper. #! @returns The function. pub def building::helper_of(&this, which: helper): u32 { return this.helpers[which as u64]; } # The image. #! Adds zeroed words to the image, giving where they begin. #! @param this The building. #! @param count How many. #! @returns Where they begin. def building::words(&mut this, count: u64): u64 { val at := this.rodata.align_to(8); for _ in 0..count { this.rodata.u64(0); } return at; } #! Adds bytes to the image, giving where they begin. #! @param this The building. #! @param data The bytes. #! @returns Where they begin. def building::bytes(&mut this, data: strview): u64 { val at := this.rodata.length; this.rodata.put(data); return at; } #! The address of a layout's record. #! @param this The building. #! @param index The layout. #! @returns The address. pub def building::layout_address(&this, index: u32): u64 { return this.rodata_base + this.layouts_at + 12 * 8 * index as u64; } #! The address of a datum. #! @param this The building. #! @param index The datum. #! @returns The address. pub def building::datum_address(&this, index: u32): u64 { return this.rodata_base + this.data_at[index]; } #! The bytes of a datum, but for the zero after them. #! @param this The building. #! @param index The datum. #! @returns How many. pub def building::datum_length(&this, index: u32): u64 { val length := this.c.program.data[index].bytes.length; return length == 0 ? 0 : length - 1; } #! The address of a word of the runtime's state. #! @param this The building. #! @param word The word. #! @returns The address. pub def building::state_address(&this, word: u64): u64 { return this.data_base + 8 * word; } #! The address of a map between traits' vtables. #! @param this The building. #! @param map The map. #! @returns The address. pub def building::retrait_address(&this, map: u32): u64 { return this.rodata_base + this.retraits_at[map]; } #! How many vtables a map between traits' vtables maps. #! @param this The building. #! @param map The map. #! @returns How many. pub def building::retrait_count(&this, map: u32): u64 { return this.c.program.retraits[map].vtables.length; } #! The address of the word holding the address C calls a function through. #! @param this The building. #! @param function The function. #! @returns The address. pub def building::callback_word(&this, function: u32): u64 { return this.rodata_base + this.callbacks_at + 8 * this.callback_slots[function] as u64; } #! The address of the word the loader writes the address of a C function to. #! @param this The building. #! @param linked The C function. #! @returns The address. pub def building::got_word(&this, linked: u32): u64 { return this.got + 8 * this.slots[linked] as u64; } #! The text of a description of an error of the machine, by its code, as the #! image holds them for the runtime's reports. #! @param code The code. #! @returns The text. def error_text(code: u64): strview { return match code { 0 => "Machine input was null.", 1 => "Context was not checked successfully.", 2 => "Program has no `main` function.", 3 => "Program uses a construct that cannot be compiled.", 4 => "Index or slice is out of bounds.", 5 => "Null reference was unwrapped.", 6 => "Division by zero.", 7 => "Union does not hold the field that was read.", 8 => "Stack overflowed.", 9 => "Function ended without returning a value.", 10 => "Machine was not initialized.", 11 => "Released memory that was not allocated, or was already released.", 12 => "Context was checked for a target other than this machine.", 13 => "Value is not a member of its enum.", 14 => "Alignment of an allocation is not a power of two.", 15 => "Function does not run while compiling.", 16 => "Evaluation took too many steps, as an endless loop or recursion would.", 17 => "Constant has not been evaluated yet.", 18 => "Pointer reaches memory the program does not hold, as past the end of what it points into, or memory released.", 19 => "Pointers into different memory are compared or subtracted, which depends on where the memory is.", 20 => "Program exited.", 21 => "Program aborted.", 22 => "C function could not be found, nor the library holding it.", 23 => "C called a function of the program while the program was not calling C.", 26 => "Program faulted.", 29 => "Integer arithmetic overflowed.", 31 => "Allocator out of memory", 32 => "sakura: runtime error: ", 33 => " at ", 34 => " (", 35 => ":", 36 => ")\n", 37 => "\n", else => "" }; } #! Writes the records of the image that do not depend on where code is: the #! texts, the layouts, the data, and room for the tables of functions and #! vtables, filled once the code is placed. #! @param this The building. def building::image(&mut this): void { val program := &this.c.program; this.image_at = this.words(14); # Texts: where each begins, and how long it is. this.texts_at = this.words(2 * text_count); for i in 0..text_count { val text := error_text(i); val at := this.bytes(text); this.rodata.set_u64(this.texts_at + 16 * i, this.rodata_base + at); this.rodata.set_u64(this.texts_at + 16 * i + 8, text.length); } # Layouts, whose records come first, so they can refer to each other. val layout_count := program.layouts.length; this.layouts_at = this.words(12 * layout_count); for i in 0..layout_count { val shape: layout = program.layouts[i]; val record := this.layouts_at + 12 * 8 * i; val named := shape.kind != lk::fixed && shape.count != 0; val enum_like := shape.kind == lk::signed || shape.kind == lk::unsigned || shape.kind == lk::boolean; val fields := named ? this.words(4 * shape.count as u64) : 0; for f in 0..(named ? shape.count : 0) { val field: slot_field = program.fields[shape.fields as u64 + f as u64]; val name := this.c.checker.names.text(field.name); val name_at := this.bytes(name); val at := fields + 32 * f as u64; this.rodata.set_u64(at, enum_like ? 0 : this.layout_address(field.layout)); this.rodata.set_u64(at + 8, field.offset); this.rodata.set_u64(at + 16, this.rodata_base + name_at); this.rodata.set_u64(at + 24, name.length); } val name := shape.name != 0 ? this.c.checker.names.text(shape.name) : ""; val name_at := this.bytes(name); val inner: u32 = shape.element != 0 ? shape.element : shape.viewed; var flags: u64 = 0; if shape.niche != 0 { flags = flags | 2; } if shape.texts { flags = flags | 4; } if shape.views { flags = flags | 8; } if shape.texts || shape.views { flags = flags | (shape.text as u64 << 8); } val values: u64[12] = [ shape.kind as u64, shape.how as u64, shape.bits as u64, shape.size, shape.align, shape.frame, inner != 0 ? this.layout_address(inner - 1) : 0, named ? this.rodata_base + fields : 0, shape.count as u64, flags, this.rodata_base + name_at, name.length ]; for v in 0..12u { this.rodata.set_u64(record + 8 * v, values[v]); } } # The data, then where they hold each other's addresses. this.data_at.resize(program.data.length); for i in 0..program.data.length { val align: u64 = program.data[i].align; this.rodata.align_to(align > 1 ? align : 1); this.data_at[i] = this.rodata.length; this.rodata.put(program.data[i].bytes.span); } for i in 0..program.data.length { for &each in program.data[i].relocations { this.rodata.set_u64(this.data_at[i] + each.at, this.datum_address(each.target) + each.addend); } } # The tables of functions and vtables, known once the code is placed. val count := program.functions.length; this.function_table = this.rodata_base + this.words(count); val vtables := program.vtables.length; this.vtable_table = this.rodata_base + this.words(vtables); this.vtable_methods.resize(vtables); for v in 0..vtables { this.vtable_methods[v] = this.words(program.vtables[v].functions.length); this.rodata.set_u64(this.vtable_table - this.rodata_base + 8 * v, this.rodata_base + this.vtable_methods[v]); } # The records of the functions, whose names are known now and places later. this.records_at = this.words(7 * count); for i in 0..count { val name := program.functions[i].name.span; val at := this.bytes(name); val record := this.records_at + 56 * i; this.rodata.set_u64(record + 16, this.rodata_base + at); this.rodata.set_u64(record + 24, name.length); this.rodata.set_u64(record + 48, this.runtime[i] ? 1 : 0); } # The vtable each vtable becomes as a reference to its trait converts. this.retraits_at.resize(program.retraits.length); for i in 0..program.retraits.length { val held := &program.retraits[i]; this.retraits_at[i] = this.words(held.vtables.length); for v in 0..held.vtables.length { this.rodata.set_u64(this.retraits_at[i] + 8 * v, held.vtables[v] as u64); } } # The layout of what each vtable's references refer to, for formatting. val vtable_layouts := this.words(vtables); for v in 0..vtables { this.rodata.set_u64(vtable_layouts + 8 * v, this.layout_address(program.vtables[v].layout)); } # A word for each function C calls, holding the address C calls it through. this.callback_slots.resize(count); var callbacks: u32 = 0; for i in 0..count { this.callback_slots[i] = never; if program.functions[i].callback && program.functions[i].lowered { this.callback_slots[i] = callbacks; callbacks++; } } this.callbacks_at = this.words(callbacks as u64); val image: u64[12] = [ 0, this.rodata_base + this.layouts_at, layout_count, this.rodata_base + this.records_at, count, this.rodata_base + this.texts_at, text_count, 0, program.globals, 0, this.rodata_base + vtable_layouts, vtables ]; for v in 0..12u { this.rodata.set_u64(this.image_at + 8 * v, image[v]); } } #! The loader a dynamically linked executable is run by. const interpreter: strview = "/lib64/ld-linux-x86-64.so.2"; #! Adds what the loader of a dynamically linked executable reads to the image: #! its path, the names of the libraries and C functions, the symbols naming the #! functions, a table for finding symbols the executable defines, which holds #! none, the relocations writing each function's address to its word, and the #! dynamic section pointing at all of them. Every address is written before the #! program runs, so none is looked up late. #! @param this The building. def building::dynamic_records(&mut this): void { val program := &this.c.program; val path_at := this.bytes(interpreter); this.rodata.byte(0); # Names: each library once, as the first function whose file names it names # it, so the loader looks for each function in all of them. val strings := this.rodata.length; this.rodata.byte(0); var name_at := vector::::new(); name_at.resize(program.linked.length); var libraries := interner::::new(); var needed := vector::::new(); # Where the name of each library is, by its ID. for l in 0..program.linked.length { continue if this.slots[l] == never; for &each in program.linked[l].libraries { val library := each.span; if libraries.intern_view(library) == needed.length { needed.append(this.rodata.length - strings); this.bytes(library); this.rodata.byte(0); } } name_at[l] = this.rodata.length - strings; this.bytes(this.c.checker.names.text(program.linked[l].name)); this.rodata.byte(0); } val strings_size := this.rodata.length - strings; val count := this.linked_count + 1; val symbols := this.words(3 * count); for l in 0..program.linked.length { continue if this.slots[l] == never; val at := symbols + 24 * (this.slots[l] as u64 + 1); this.rodata.set_u32(at, name_at[l]); this.rodata.set_byte(at + 4, 0x12); # A global function, defined elsewhere. } # One bucket, which no symbol the executable defines is in. val hash := this.words((2 + 1 + count + 1) / 2); this.rodata.set_u32(hash, 1); this.rodata.set_u32(hash + 4, count); this.relocations = this.words(3 * this.linked_count); for l in 0..program.linked.length { continue if this.slots[l] == never; val slot := this.slots[l] as u64; this.rodata.set_u64(this.relocations + 24 * slot + 8, ((slot + 1) << 32) | 6); } val section := this.words(0); for &each in needed { this.rodata.u64(1); this.rodata.u64(each); } val entries: u64[24] = [ 4, this.rodata_base + hash, 5, this.rodata_base + strings, 6, this.rodata_base + symbols, 10, strings_size, 11, 24, 7, this.rodata_base + this.relocations, 8, this.linked_count * 24, 9, 24, 24, 0, 30, 8, 0x6FFFFFFB, 1, 0, 0 ]; for i in 0..24u { this.rodata.u64(entries[i]); } this.dynamic_parts = elf::linking { interpreter = this.rodata_base + path_at, interpreter_size = interpreter.length + 1, section = this.rodata_base + section, section_size = this.rodata.length - section, strings = this.rodata_base + strings, strings_size = strings_size, symbols = this.rodata_base + symbols, symbols_size = count * 24 }; } # Shared code. #! Calls a function, patched once every function is placed. #! @param this The building. #! @param function The function. pub def building::call_to(&mut this, function: u32): void { this.calls.add(this.text.call(), function); } #! Jumps to a function, patched once every function is placed. #! @param this The building. #! @param function The function. def building::jump_to_function(&mut this, function: u32): void { this.calls.add(this.text.jmp(), function); } #! Jumps where a condition holds to code already written. #! @param this The building. #! @param condition The condition. #! @param target Where the code is in the text. pub def building::patch_jcc(&mut this, condition: cc, target: u64): void { this.text.patch(this.text.jcc(condition), target); } #! Writes the code every function shares: the trap stub, the handler of faults #! of the program, the code the kernel returns from signals through, the #! handler noting signals the program handles, and the stubs of a stack #! overflowing, a function never lowered, and a vtable's slot no function #! fills. #! @param this The building. def building::shared_code(&mut this): void { # The trap stub is called with the error in `rdi`. It reports through # `runtime::fail`, given the address it was called from and the chain # of `rbp` before it, in the stack past the limit, which the limit moves # down to the stack's end for. A trap while reporting one exits at once. # It makes a frame of its own, as a function does, so a debugger stopped in # the report unwinds through it to where the trap was, and aligns `rsp` to # 16 bytes, which a function calling nothing need not keep it to. this.trap_stub = this.text.length; this.text.mov(gprs[2], reg::rbp); this.text.push(reg::rbp); this.trap_framed = this.text.length; this.text.mov(reg::rbp, reg::rsp); this.trap_based = this.text.length; this.text.alu_imm(alu::band, reg::rsp, -16); this.text.load(8, false, reg::rsi, at(reg::rbp, 8)); this.text.alu_mem_imm(alu::cmp, amd64::absolute(this.state_address(state_reporting)), 0); val first := this.text.jcc(cc::equal); if this.options.windows { # Windows has no system calls: a trap while reporting one ends through `ExitProcess`. this.text.mov_imm(reg::rcx, 1); this.call_system(system_exit_process); } else { this.text.mov_imm(reg::rax, 231); this.text.mov_imm(reg::rdi, 1); this.text.syscall(); } this.text.land(first); this.text.store_imm(amd64::absolute(this.state_address(state_reporting)), 1); val trap_frame := this.own_word(state_trap_frame); this.text.load(8, false, reg::rax, trap_frame); val limit := this.own_word(state_limit); this.text.store(8, limit, reg::rax); this.call_to(this.helper_of(helper::fail)); this.text.ud2(); if this.options.windows { this.windows_handlers(); this.shared_stubs(); return; } # Reading or writing through a null pointer faults at the page the kernel # never maps, and dividing by zero faults too, so the code reads through # pointers and divides without testing them, and the fault is reported as the # test would have been: from the instruction faulting, with the chain of `rbp` # it was in. The kernel gives the signal's number in `edi`: `SIGFPE`, 8, is a # division, where the kernel sent it, and `SIGSEGV` is null where the address # is in the first page. A fault anywhere else, or of code that is not the # program's, takes back the kernel's own handling of the signal and faults # again. this.faults = this.text.length; this.text.mov_imm(reg::r8, fault::null_reference as u64); this.text.alu_imm(alu::cmp, reg::rdi, 8); val segv := this.text.jcc(cc::not_equal); this.text.load(4, true, reg::rax, at(reg::rsi, 8)); this.text.alu_imm(alu::cmp, reg::rax, 0); val sent := this.text.jcc(cc::less_equal); this.text.mov_imm(reg::r8, fault::division as u64); val division := this.text.jmp(); this.text.land(segv); this.text.load(8, false, reg::rax, at(reg::rsi, 16)); this.text.alu_imm(alu::cmp, reg::rax, null_page as i32); val elsewhere := this.text.jcc(cc::above_equal); this.text.land(division); this.text.load(8, false, reg::rax, at(reg::rdx, 168)); this.text.mov_imm(reg::rcx, this.text_base); this.text.alu(alu::cmp, reg::rax, reg::rcx); val before := this.text.jcc(cc::below); this.text.byte(0xB9); this.code_end = this.text.length; this.text.u32(0); this.text.alu(alu::cmp, reg::rax, reg::rcx); val after := this.text.jcc(cc::above_equal); # The fault is made to look as though the faulting instruction called the # trap stub. this.text.load(8, false, reg::rbp, at(reg::rdx, 120)); this.text.lea(reg::rsi, at(reg::rax, 1)); this.text.alu_imm(alu::band, reg::rsp, -16); this.text.push(reg::rsi); this.text.mov(reg::rdi, reg::r8); this.text.patch(this.text.jmp(), this.trap_stub); this.text.land(sent); this.text.land(elsewhere); this.text.land(before); this.text.land(after); this.text.alu_imm(alu::sub, reg::rsp, 32); for at_byte in 0..4u { this.text.store_imm(at(reg::rsp, (8 * at_byte) as i32), 0); } this.text.mov_imm(reg::rax, 13); this.text.mov(reg::rsi, reg::rsp); this.text.mov_imm(reg::rdx, 0); this.text.mov_imm(reg::r10, 8); this.text.syscall(); this.text.alu_imm(alu::add, reg::rsp, 32); this.text.ret(); this.restorer = this.text.length; this.text.mov_imm(reg::rax, 15); this.text.syscall(); # A signal the program handles is only noted, as one bit of a word of the # state, and handled at the program's next safe point. The kernel gives the # number in `edi`, and puts every register back as the handler returns # through the restorer. this.noting = this.text.length; this.text.mov(reg::rcx, reg::rdi); this.text.mov_imm(reg::rax, 1); this.text.shift_cl(shift::shl, reg::rax); this.text.lock(); this.text.alu_store(alu::bor, amd64::absolute(this.state_address(state_signals)), reg::rax); this.text.ret(); this.shared_stubs(); } #! Writes the stubs every function shares after the signal handlers: a stack #! overflowing, a function never lowered, a vtable's slot no function fills, #! and the code a safe point calls. #! @param this The building. def building::shared_stubs(&mut this): void { # A stack overflowing is found entering the function called, whose frame # pointer leads to its caller, which the report names first. this.overflow_stub = this.text.length; this.text.mov_imm(reg::rdi, 8); this.text.patch(this.text.call(), this.trap_stub); this.missing = this.text.length; this.text.ud2(); # A slot no function fills reports the caller's call, whose return address # the trap stub takes. this.missing_method = this.text.length; this.text.mov_imm(reg::rdi, fault::null_reference as u64); this.text.patch(this.text.jmp(), this.trap_stub); if this.c.dispatch != no_function { this.safe_point_routine(this.c.dispatch); } } #! Writes the code a safe point calls where a signal the program handles came: #! it makes a frame, so a trace walks out through the safe point's function, #! keeps every register on the stack, and calls the function running the #! handlers. The vector registers are kept #! whole: 32 bytes each where the processor has AVX, and 16 otherwise. #! @param this The building. #! @param function The function running the handlers. def building::safe_point_routine(&mut this, function: u32): void { this.safe_point = this.text.length; this.text.push(reg::rbp); this.text.mov(reg::rbp, reg::rsp); for k in 0..gpr_count { this.text.push(gprs[k]); } val kept: u64 = 32 * 11 + 8; this.text.alu_imm(alu::sub, reg::rsp, kept as i32); this.vector_registers(true); this.call_to(function); this.vector_registers(false); this.text.alu_imm(alu::add, reg::rsp, kept as i32); for k in 0..gpr_count { this.text.pop(gprs[gpr_count - 1 - k]); } this.text.pop(reg::rbp); this.text.ret(); } #! Keeps the vector registers values are held in on the stack, or gives them #! back what was kept: 32 bytes each where the processor has AVX, and 16 #! otherwise. #! @param this The building. #! @param store Whether they are kept, rather than given back. def building::vector_registers(&mut this, store: bool): void { this.text.load(8, false, reg::rax, amd64::absolute(this.state_address(state_features))); this.text.alu_imm(alu::band, reg::rax, cpu_avx as i32); val narrow := this.text.jcc(cc::equal); for k in 0..11u { val slot := at(reg::rsp, (32 * k) as i32); if store { this.text.vex_mem(vec_movdqu_store, true, xmms[k] as u32, slot); } else { this.text.vex_mem(vec_movdqu_load, true, xmms[k] as u32, slot); } } val done := this.text.jmp(); this.text.land(narrow); for k in 0..11u { val slot := at(reg::rsp, (32 * k) as i32); if store { this.text.packed_mem(vec_movdqu_store, xmms[k] as u32, slot); } else { this.text.packed_mem(vec_movdqu_load, xmms[k] as u32, slot); } } this.text.land(done); } #! Maps memory with `mmap`, leaving its address in `rax`, and exiting with 2 #! where there is none. #! @param this The building. #! @param size The bytes. def building::map(&mut this, size: u64): void { this.text.mov_imm(reg::rax, 9); this.text.mov_imm(reg::rdi, 0); this.text.mov_imm(reg::rsi, size); this.text.mov_imm(reg::rdx, 3); this.text.mov_imm(reg::r10, 0x4022); this.text.mov_imm(reg::r8, 0xFFFFFFFFFFFFFFFF); this.text.mov_imm(reg::r9, 0); this.text.syscall(); this.text.mov_imm(reg::rcx, 0xFFFFFFFFFFFFF001); this.text.alu(alu::cmp, reg::rax, reg::rcx); val mapped := this.text.jcc(cc::below); this.text.mov_imm(reg::rax, 231); this.text.mov_imm(reg::rdi, 2); this.text.syscall(); this.text.land(mapped); } #! Writes `_start`: it maps the stack, keeps the arguments, takes the faults of #! the program, runs ``, then `main` with the arguments, then exits #! with 0. #! @param this The building. def building::entry(&mut this): void { this.start = this.text.length; this.text.mov(reg::r14, reg::rsp); # The first thread's record is the state, which `gs` points at, as each # thread's points at its own. this.text.mov_imm(reg::rax, 158); this.text.mov_imm(reg::rdi, 0x1001); this.text.mov_imm(reg::rsi, this.state_address(0)); this.text.syscall(); this.text.mov_imm(reg::rax, this.state_address(0)); this.text.store(8, amd64::absolute(this.state_address(state_itself)), reg::rax); this.text.store_imm(amd64::absolute(this.state_address(state_running)), 1); this.text.mov_imm(reg::rax, 186); this.text.syscall(); this.text.store(8, amd64::absolute(this.state_address(state_tid)), reg::rax); this.map(this.stack + stack_reserve); this.text.store(8, amd64::absolute(this.state_address(state_trap_frame)), reg::rax); this.text.lea(reg::rcx, at(reg::rax, stack_reserve as i32)); this.text.store(8, amd64::absolute(this.state_address(state_limit)), reg::rcx); this.text.mov_imm(reg::rcx, this.stack + stack_reserve); this.text.alu(alu::add, reg::rax, reg::rcx); this.text.store(8, amd64::absolute(this.state_address(state_base)), reg::rax); this.text.mov(reg::rsp, reg::rax); this.text.load(8, false, reg::rax, at(reg::r14, 0)); this.text.store(8, amd64::absolute(this.state_address(state_argc)), reg::rax); this.text.lea(reg::rax, at(reg::r14, 8)); this.text.store(8, amd64::absolute(this.state_address(state_argv)), reg::rax); this.text.mov_imm(reg::rbp, 0); # Faults of the program are reported as traps: `rt_sigaction` of `SIGSEGV` # and of `SIGFPE`, given the handler with its information and the code the # kernel returns through. this.text.alu_imm(alu::sub, reg::rsp, 32); this.text.mov_imm(reg::rax, this.text_base + this.faults); this.text.store(8, at(reg::rsp, 0), reg::rax); this.text.mov_imm(reg::rax, 0x04000004); this.text.store(8, at(reg::rsp, 8), reg::rax); this.text.mov_imm(reg::rax, this.text_base + this.restorer); this.text.store(8, at(reg::rsp, 16), reg::rax); this.text.store_imm(at(reg::rsp, 24), 0); for signal in [11u, 8u] { this.text.mov_imm(reg::rax, 13); this.text.mov_imm(reg::rdi, signal); this.text.mov(reg::rsi, reg::rsp); this.text.mov_imm(reg::rdx, 0); this.text.mov_imm(reg::r10, 8); this.text.syscall(); } this.text.alu_imm(alu::add, reg::rsp, 32); # The vector instructions the processor has, of which the runtime says which # the program uses, before anything may use them. this.probe(); this.text.mov(gprs[0], reg::rax); this.call_to(this.helper_of(helper::processor)); this.text.store(8, amd64::absolute(this.state_address(state_features)), reg::rax); this.run_main(); this.text.mov_imm(reg::rax, 231); this.text.mov_imm(reg::rdi, 0); this.text.syscall(); this.entry_end = this.text.length; } #! Runs the globals of the program, then `main`, giving it the arguments where #! it takes them. The entry has found which vector instructions the program #! uses, so this is the same whichever system it runs on. #! @param this The building. def building::run_main(&mut this): void { val program := &this.c.program; this.call_to(program.init); val main := program.main; val signature: u32 = program.functions[main].signature; # The arguments are a view, which `main` takes as the address of the copy it # makes, as any parameter held in memory, or as its two words. if program.signatures[signature].params.length == 1 { val shape: layout = program.layouts[program.signatures[signature].params[0]]; this.text.alu_imm(alu::sub, reg::rsp, 16); this.text.mov(gprs[0], reg::rsp); this.call_to(this.helper_of(helper::arguments)); if in_memory(&shape) { this.text.mov(gprs[0], reg::rsp); } else { this.text.load(8, false, gprs[0], at(reg::rsp, 0)); this.text.load(8, false, gprs[1], at(reg::rsp, 8)); } } this.call_to(main); } #! Asks the processor which vector instructions it has, into `rax`, one bit each #! as `cpu_sse2` and the rest name them: what `cpuid`'s first two leaves say, #! with `popcnt`; BMI1 from the seventh leaf, where there is one, and `lzcnt` #! from the extended leaf `0x80000001`; and AVX and what needs it only where the #! system keeps the registers' upper halves too, as `xgetbv` says where #! `OSXSAVE` lets it be asked, AVX2 from the seventh leaf; and AVX-512's F, DQ, #! BW, and VL, from the seventh leaf too, where it also keeps the mask registers #! and all 512 bits of the 32. #! @param this The building. def building::probe(&mut this): void { this.text.mov_imm(reg::rax, 0); this.text.mov_imm(reg::rcx, 0); this.text.cpuid(); this.text.mov(reg::r10, reg::rax); this.text.mov_imm(reg::rax, 1); this.text.mov_imm(reg::rcx, 0); this.text.cpuid(); this.text.mov(reg::r8, reg::rcx); this.text.mov_imm(reg::r9, cpu_sse2); this.feature(reg::r8, 9, cpu_ssse3); this.feature(reg::r8, 19, cpu_sse41); this.feature(reg::r8, 20, cpu_sse42); this.feature(reg::r8, 23, cpu_popcnt); # The seventh leaf's `ebx`, kept in `r11`, or nothing where there is none. this.text.mov_imm(reg::r11, 0); this.text.alu_imm(alu::cmp, reg::r10, 7); val no_leaf := this.text.jcc(cc::below); this.text.mov_imm(reg::rax, 7); this.text.mov_imm(reg::rcx, 0); this.text.cpuid(); this.text.mov(reg::r11, reg::rbx); this.feature(reg::r11, 3, cpu_bmi1); this.text.land(no_leaf); this.text.mov_imm(reg::rax, 0x80000000); this.text.mov_imm(reg::rcx, 0); this.text.cpuid(); this.text.mov_imm(reg::rcx, 0x80000001); this.text.alu(alu::cmp, reg::rax, reg::rcx); val no_extended := this.text.jcc(cc::below); this.text.mov_imm(reg::rax, 0x80000001); this.text.mov_imm(reg::rcx, 0); this.text.cpuid(); this.feature(reg::rcx, 5, cpu_lzcnt); this.text.land(no_extended); this.text.mov(reg::rax, reg::r8); this.text.alu_imm(alu::band, reg::rax, 0x18000000); this.text.alu_imm(alu::cmp, reg::rax, 0x18000000); val no_avx := this.text.jcc(cc::not_equal); this.text.mov_imm(reg::rcx, 0); this.text.xgetbv(); this.text.mov(reg::r10, reg::rax); this.text.alu_imm(alu::band, reg::rax, 6); this.text.alu_imm(alu::cmp, reg::rax, 6); val no_state := this.text.jcc(cc::not_equal); this.text.alu_imm(alu::bor, reg::r9, cpu_avx as i32); this.feature(reg::r8, 12, cpu_fma); this.feature(reg::r11, 5, cpu_avx2); # The mask registers and the upper bits of all 32, then F, DQ, BW, and VL, # bits 16, 17, 30, and 31, compared in a register, as an immediate of them # would be widened with its sign. this.text.mov(reg::rax, reg::r10); this.text.alu_imm(alu::band, reg::rax, 0xE0); this.text.alu_imm(alu::cmp, reg::rax, 0xE0); val no_wide_state := this.text.jcc(cc::not_equal); this.text.mov_imm(reg::rcx, 0xC0030000); this.text.mov(reg::rax, reg::r11); this.text.alu(alu::band, reg::rax, reg::rcx); this.text.alu(alu::cmp, reg::rax, reg::rcx); val no_wide := this.text.jcc(cc::not_equal); this.text.alu_imm(alu::bor, reg::r9, cpu_avx512 as i32); this.text.land(no_wide); this.text.land(no_wide_state); this.text.land(no_avx); this.text.land(no_state); this.text.mov(reg::rax, reg::r9); } #! Adds an instruction set to those `r9` holds where a bit of a register is set. #! @param this The building. #! @param from The register. #! @param bit The bit. #! @param which The instruction set's bit. def building::feature(&mut this, from: reg, bit: u32, which: u64): void { this.text.mov(reg::rax, from); this.text.alu_imm(alu::band, reg::rax, (1u << bit as u64) as i32); val absent := this.text.jcc(cc::equal); this.text.alu_imm(alu::bor, reg::r9, which as i32); this.text.land(absent); } # Functions. #! How many words a function is called with: each word of its parameters, the #! address of each held in memory, and a closure's environment. #! @param this The building. #! @param function The function. #! @param memory Where whether each word is the address of one held in #! memory is written. #! @param sizes Where the bytes of each held in memory are written. #! @returns How many. def building::incoming(&this, function: u32, memory: &mut vector, sizes: &mut vector): u64 { val held := &this.c.program.functions[function]; val signature := &this.c.program.signatures[held.signature]; for &each in signature.params { val shape: layout = this.c.program.layouts[each]; if in_memory(&shape) { memory.append(true); sizes.append(shape.size); continue; } for _ in 0..word_count(&shape) { memory.append(false); sizes.append(0); } } if held.closure { memory.append(false); sizes.append(0); } return memory.length; } #! Selects the code of every function, in order. Where the options ask for #! more threads than one, the others place the values of the functions after #! the one whose code is being selected, as placing reads only the function's #! code and what selecting leaves as it is, each into an arena of its own, #! which is given back once the code is selected. #! @param this The building. #! @param count How many functions there are. def building::select_all(&mut this, count: u64): void { val helpers := crew_for(count, this.options.threads); if helpers == 0 { for i in 0..count { this.select_function(i as u32); } return; } # The arenas placing takes from wait in `free` while none uses them. A thread # takes one before it takes a function, so the function the selecting waits # for always has one, and gives it back where no function is left. The # selecting gives each back once the code it held the placing of is chosen, # which also says how far ahead of it the placing goes. val arenas := 2 * helpers; var slots := vector::::new(); slots.resize(count); var flags := vector::::new(); flags.resize(count); var gate := thread::mutex::>::new(move(&mut flags)); var placed := thread::condition::new(); var free := thread::channel::::new(0); for k in 0..arenas { _ = free.send(helpers + k); } var next := atomic::::new(0); val building := &mut this; gather_crew(helpers, helpers + arenas); var started := vector::>::new(); for k in 0..helpers { var made := thread::spawn_with::(def(place: u32): void { join_crew(place); while free.receive() is some(arena) { val index := next.fetch_add(1); if index >= count { _ = free.send(arena); return; } if !building.c.program.functions[index].lowered { _ = free.send(arena); continue; } take_scratch_from(place, arena); slots[index].made = building.place_function(index as u32); slots[index].arena = arena; take_scratch_from(place, place); var held := gate.lock(); held.value()[index] = true; placed.notify_all(); } }, k) else (_) { break; }; started.append(move(&mut made)); } for i in 0..count { val index := i as u32; if started.length == 0 { this.select_function(index); continue; } this.begin_function(index); continue if !this.c.program.functions[i].lowered; wait_placed(&mut gate, &mut placed, i); val point := mark_scratch(); this.select_placed(index, &mut slots[i].made); release_scratch(point); close(&mut slots[i].made); crew_arena(slots[i].arena).reset(); _ = free.send(slots[i].arena); } free.close(); for &mut handle in started { handle.join(); } dismiss_crew(); } #! Waits until the values of a function are placed. #! @param gate Whether each function's values are placed. #! @param placed What is notified where one's are. #! @param index The function. def wait_placed(gate: &mut thread::mutex>, placed: &mut thread::condition, index: u64): void { var held := gate.lock(); while !held.value()[index] { placed.wait(&mut held); } } #! What placing the values of a function made, while its code waits to be #! selected. struct placed_slot { var made: placed_function; #! What placing made. var arena: u32; #! The crew's arena it was made in, which is given back once the code is selected. } #! What placing the values of a function makes, which selecting its code reads. struct placed_function { var memory: vector; #! Whether each word it is called with is the address of a parameter held in memory. var sizes: vector; #! The bytes of each one held in memory. var placed: placing; #! Where each of its values is. var found: vector; #! What replaying the placing found wrong, where the options ask for it. } #! Notes where what is noted of a function begins, before its code is selected. #! @param this The building. #! @param index The function. def building::begin_function(&mut this, index: u32): void { this.row_first[index] = this.rows.length as u32; if this.options.debug { this.debug.return_first[index] = this.debug.returns.length as u32; this.debug.variable_first[index] = this.debug.variables.length as u32; } if !this.c.program.functions[index].lowered { this.starts[index] = this.missing; this.ends[index] = this.missing; } } #! Selects the code of a function, or points it at the shared stop where it #! was never lowered. #! @param this The building. #! @param index The function. def building::select_function(&mut this, index: u32): void { this.begin_function(index); return if !this.c.program.functions[index].lowered; val point := mark_scratch(); var made := this.place_function(index); this.select_placed(index, &mut made); release_scratch(point); } #! Places the values of a function, in scratch memory, replaying where it #! placed them where the options ask for it. It reads only the function's code #! and what building leaves as it is while selecting, so it may be done on any #! thread. #! @param this The building. #! @param index The function. #! @returns What placing made. def building::place_function(&this, index: u32): placed_function { var memory := vector::::new(scratch()); var sizes := vector::::new(scratch()); this.incoming(index, &mut memory, &mut sizes); val body := &this.c.program.functions[index].body; var placed := place_values(body, memory.span); var found := this.options.verify ? check_placing(body, &placed) : vector::::new(); return placed_function { memory = move(&mut memory), sizes = move(&mut sizes), placed = move(&mut placed), found = move(&mut found) }; } #! Selects the code of a function whose values are placed. #! @param this The building. #! @param index The function. #! @param made What placing its values made, whose placing it takes. def building::select_placed(&mut this, index: u32, made: &mut placed_function): void { for &each in made.found { this.problems.append($"{this.c.program.functions[index].name}: {each}"); } # Each function begins at a multiple of 16 bytes, as the processor fetches # code, so how fast its loops run doesn't hang on the sizes of the functions # before it. What lies between is never run. while this.text.length % 16 != 0 { this.text.byte(0xCC); } val body := &this.c.program.functions[index].body; val leaf := made.placed.clobbers.length == 0; var chosen := selector { b = this, body = body, p = move(&mut made.placed), index = index, start = this.text.length, cells = vector::::new(scratch()), copies = vector::::new(scratch()), labels = vector::::new(scratch()), jumps = fixup_list::new(scratch()), traps = vector::::new(scratch()), safe_points = vector::::new(scratch()), tables = vector::::new(scratch()), addresses = vector::::new(scratch()), stub_spans = vector::::new(scratch()), pads = vector::::new(scratch()), constants = vector::::new(scratch()), constant_uses = vector::::new(scratch()), entries = vector::::new(scratch()), upper_parts = vector::::new(scratch()), framed = vector::::new(scratch()), single = vector::::new(scratch()), works = vector::::new(scratch()), last_at = 0xFFFFFFFFFFFFFFFF, returned = body.returned as u64, leaf = leaf }; chosen.select(made.memory.span, made.sizes.span); } #! Selects the code of the function: its prologue, its blocks, and its stubs. #! @param this The selector. #! @param memory Whether each word it is called with is the address of a #! parameter held in memory. #! @param sizes The bytes of each one held in memory. def selector::select(&mut this, memory: span, sizes: span): void { this.find_singles(); for k in 0..this.p.order.length { var walk := this.body.walk(this.p.order[k]); while walk.more() { val stacked := this.stacked_words(walk.next()); if stacked > this.out_words { this.out_words = stacked; } } } this.find_saved(); this.lay_frame(memory, sizes); this.tails = this.b.c.level >= 2 && this.frame_held(); this.b.starts[this.index] = this.start; # Every displacement the function's code is given is noted, for `relax`. this.calls_first = this.b.calls.length; this.b.text.fixups.clear(); this.b.text.logging = true; # The prologue is the line the function is declared on. val function := &this.b.c.program.functions[this.index]; this.mark(pair_key(function.file + 1, function.offset), 0); # A function with a version for x86-64-v3 goes to it first, where the # processor has its instructions, which the version writes with VEX. if function.version != 0 { this.b.text.load(8, false, reg::rax, amd64::absolute(this.b.state_address(state_features))); this.b.text.alu_imm(alu::band, reg::rax, cpu_v3 as i32); this.b.text.alu_imm(alu::cmp, reg::rax, cpu_v3 as i32); this.b.calls.add(this.b.text.jcc(cc::equal), function.version - 1); } this.b.text.avx = this.body.wide; this.find_upper_parts(); this.prologue(memory, sizes); # Where each instruction's code begins and ends, which the scopes of the # variables debugging information shows are found by. val describing := this.b.options.debug; var spans := vector::::new(scratch()); if describing { this.b.debug.bodies[this.index] = (this.b.text.length - this.start) as u32; if this.body.variables.length != 0 { spans.resize(2 * this.body.insts.length); } } this.labels.resize(this.body.blocks.length); for k in 0..this.p.order.length { val block: u32 = this.p.order[k]; val next: u32 = k + 1 < this.p.order.length ? this.p.order[k + 1] : never; if k > 0 && this.dispatches(block) { this.pad_head(); } this.labels[block] = this.b.text.length; var walk := this.body.walk(block); while walk.more() { val at := walk.next(); # A return a call jumped in place of is not reached. continue if at == this.tailed; val held: inst = this.body.insts[at]; val from := this.b.text.length - this.start; this.gap(this.p.slots[at]); if !this.p.folded[at] { this.mark(held.at, held.site); if held.kind.ends() { this.ending(at, &held, next); } else { this.emit(at, &held); } } if spans.length != 0 { spans[2 * at as u64] = from as u32; spans[2 * at as u64 + 1] = (this.b.text.length - this.start) as u32; } } } this.stubs(); this.b.text.avx = false; this.jumps.resolve(&mut this.b.text, this.labels.span); this.b.text.logging = false; this.relax(&mut spans); this.write_tables(); this.write_constants(); this.b.ends[this.index] = this.b.text.length; if spans.length != 0 { this.place_variables(spans.span); } } #! Writes the code each vtable's slot names: the function, or code moving the #! words after a plain reference's down one, where the vtable passes itself as #! the second, or giving a trait's default the vtable it addresses. #! @param this The building. def building::adapters(&mut this): void { val program := &this.c.program; for v in 0..program.vtables.length { for m in 0..program.vtables[v].functions.length { val function: u32 = program.vtables[v].functions[m]; if function == no_function { this.methods.append(this.missing_method); continue; } if !program.functions[function].lowered { this.methods.append(this.missing); continue; } val signature := &program.signatures[program.functions[function].signature]; val first: layout = program.layouts[signature.params[0]]; if first.kind == lk::trait_reference { val owner: u32 = program.vtables[v].owners[m]; if owner == v as u32 { this.methods.append(direct_method); continue; } this.methods.append(this.text.length); this.text.mov_imm(gprs[1], owner as u64); this.jump_to_function(function); continue; } # The words after the reference move down one, over the vtable. this.methods.append(this.text.length); var memory := vector::::new(); var sizes := vector::::new(); val words := this.incoming(function, &mut memory, &mut sizes); for j in 1..words { val from := j + 1; if j < arg_count && from < arg_count { this.text.mov(gprs[j], gprs[from]); } else if j < arg_count { this.text.load(8, false, gprs[j], at(reg::rsp, (8 + 8 * (from - arg_count)) as i32)); } else { this.text.load(8, false, reg::rax, at(reg::rsp, (8 + 8 * (from - arg_count)) as i32)); this.text.store(8, at(reg::rsp, (8 + 8 * (j - arg_count)) as i32), reg::rax); } } this.jump_to_function(function); } } } # Placing. #! Writes what depends on where the code is: the tables of functions and #! vtables, the functions' records, and their line tables. #! @param this The building. def building::places(&mut this): void { val program := &this.c.program; val count := program.functions.length; for i in 0..count { val start: u64 = this.text_base + this.starts[i]; this.rodata.set_u64(this.function_table - this.rodata_base + 8 * i, start); val record := this.records_at + 56 * i; this.rodata.set_u64(record, start); this.rodata.set_u64(record + 8, this.text_base + this.ends[i]); } var k: u64 = 0; for v in 0..program.vtables.length { for m in 0..program.vtables[v].functions.length { var code: u64 = this.methods[k]; if code == direct_method { code = this.starts[program.vtables[v].functions[m]]; } this.rodata.set_u64(this.vtable_methods[v] + 8 * m, this.text_base + code); k++; } } for i in 0..count { val slot: u32 = this.callback_slots[i]; continue if slot == never; this.rodata.set_u64(this.callbacks_at + 8 * slot as u64, this.text_base + this.entries[i]); } this.line_tables(); } #! Where in the source a place is: its file, and its line and column, from one #! more than the file and the byte, or the function's declaration for 0. #! @param this The building. #! @param function The function. #! @param at The place. #! @param file Where the file is written. #! @returns Its line and column. def building::source_of(&this, function: u32, at: u64, file: &mut u32): sakura::analyzer::place { var byte := pair_low(at); if at == 0 { file = this.c.program.functions[function].file; byte = this.c.program.functions[function].offset; } else { file = pair_high(at) - 1; } return this.c.checker.units[file].source.lines.place_of(byte); } #! Writes the line table of every function into the line tables: a row for each #! place its code changes where in the source it is from, each naming its path #! among the image's and the site of the function inlined there, then the sites #! of every function, and the paths. Each function's record and the image point #! at them. #! @param this The building. def building::line_tables(&mut this): void { val program := &this.c.program; # The path of each file, numbered as rows name them, and the first site of each # function among them all. var path_ids := vector::::new(); path_ids.resize(this.c.checker.units.length); var files := vector::::new(); var site_first := vector::::new(); var total_sites: u32 = 0; for i in 0..program.functions.length { site_first.append(total_sites); continue if this.row_first[i] == this.row_first[i + 1]; total_sites += program.functions[i].body.sites.length as u32; } for i in 0..program.functions.length { val first: u32 = this.row_first[i]; val last: u32 = this.row_first[i + 1]; continue if first == last; val table := this.late.align_to(8); for r in first..last { val row: line_row = this.rows[r as u64]; var file: u32 = 0; val place := this.source_of(i as u32, row.at, &mut file); this.late.u32(row.offset); this.late.u32(place.line as u64); this.late.u16(place.column > 0xFFFF ? 0xFFFF : place.column as u64); this.late.u16(numbered(&mut path_ids, &mut files, file) as u64); this.late.u32(row.site != 0 ? site_first[i] as u64 + row.site as u64 : 0); } val record := this.records_at + 56 * i; this.rodata.set_u64(record + 32, this.late_base + table); this.rodata.set_u64(record + 40, (last - first) as u64); } # Each site of a function inlined: the function, where it was called, and the # site that call is within, which the trace walks out through. val sites_at := this.late.align_to(8); for i in 0..program.functions.length { continue if this.row_first[i] == this.row_first[i + 1]; for &each in program.functions[i].body.sites { var file: u32 = 0; val place := this.source_of(i as u32, each.at, &mut file); this.late.u32(each.function as u64); this.late.u32(place.line as u64); this.late.u16(place.column > 0xFFFF ? 0xFFFF : place.column as u64); this.late.u16(numbered(&mut path_ids, &mut files, file) as u64); this.late.u32(each.parent != 0 ? site_first[i] as u64 + each.parent as u64 : 0); } } # The paths, each its text then where it is and how long. var texts := vector::::new(); for &file in files { val path := this.c.checker.units[file].source.path; texts.append(this.late.length); this.late.put(path); } val paths_at := this.late.align_to(8); for k in 0..files.length { this.late.u64(this.late_base + texts[k]); this.late.u64(this.c.checker.units[files[k]].source.path.length); } this.rodata.set_u64(this.image_at + 12 * 8, this.late_base + paths_at); this.rodata.set_u64(this.image_at + 13 * 8, this.late_base + sites_at); } #! The number of a file's path among those the line tables name, given one where #! it has none yet. #! @param ids One more than the number of each file's path, or 0. #! @param files The file of each number. #! @param file The file. #! @returns The number. def numbered(ids: &mut vector, files: &mut vector, file: u32): u32 { if ids[file] == 0 { files.append(file); ids[file] = files.length as u32; } return ids[file] - 1; } # Writing. #! A part of the image an executable loads: a segment of an ELF file, or a #! section of a PE file. struct loaded_part { var name: strview; #! Of its section, as `.text`. var address: u64; #! Where its bytes are loaded. var data: span; #! What it holds. var size: u64; #! How many bytes. var flags: u32; #! Its permissions, which ELF and PE number alike. } #! The parts of the image an executable loads, in the order they are loaded: #! the image only read, the data, the code, and the line tables. #! @param this The building. #! @param data The bytes of the data. #! @returns The parts. def building::loaded_parts(&this, data: span): loaded_part[4] { return [ loaded_part { name = ".rodata", address = this.rodata_base, data = this.rodata.span, size = this.rodata.length, flags = elf::readable }, loaded_part { name = ".data", address = this.data_base, data = data, size = this.data_size, flags = elf::readable | elf::writable }, loaded_part { name = ".text", address = this.text_base, data = this.text.bytes.span, size = this.text.length, flags = elf::readable | elf::executable }, loaded_part { name = ".lines", address = this.late_base, data = this.late.span, size = this.late.length, flags = elf::readable } ]; } #! Names the code, as debuggers and disassemblers show it: `_start`, the trap #! stub, and each function placed, each by where it begins and how many bytes #! it takes. #! @param this The building. #! @param symbols Where the names are added. def building::name_code(&this, symbols: &mut vector): void { symbols.append(elf::symbol { name = "_start", address = this.text_base + this.start, size = this.entry_end - this.start }); symbols.append(elf::symbol { name = "", address = this.text_base + this.trap_stub, size = this.start - this.trap_stub }); for i in 0..this.c.program.functions.length { continue if this.starts[i] == this.missing; symbols.append(elf::symbol { name = this.c.program.functions[i].name.span, address = this.text_base + this.starts[i], size = this.ends[i] - this.starts[i] }); } } #! Writes the executable: its segments, its symbols, and a note naming its #! build. #! @param this The building. def building::write(&mut this): void { # The data is zeros, but for the bytes the globals begin with. var zeros := byte_writer::new(); zeros.zeros(this.data_size); val preset := this.c.program.preset.span; if preset.length != 0 { memcpy(zeros.slice.data + (this.globals - this.data_base), preset.data, preset.length); } if this.options.windows { # The words of the functions imported hold where their names are until the # loader writes their addresses. for w in 0..this.import_words { zeros.set_u64(this.got - this.data_base + 8 * w, this.import_names[w]); } this.write_pe(zeros.span); return; } val headers := elf::headers_size(4, this.dynamic); val data_offset := round_up(headers + this.rodata.length, page_size); val text_offset := round_up(data_offset + this.data_size, page_size); val late_offset := round_up(text_offset + this.text.length, page_size); var image := elf::image::new(this.text_base + this.start); if this.dynamic { image.dynamic = this.dynamic_parts; image.linked = true; } # The first segment begins with the file's headers, before the image. val parts := this.loaded_parts(zeros.span); val offsets: u64[4] = [0, data_offset, text_offset, late_offset]; for k in 0..4u { val part: loaded_part = parts[k]; image.segment(part.name, k == 0 ? base_address : part.address, offsets[k], part.data, part.size, part.flags, k == 0); } this.name_code(&mut image.symbols); image.build_id(); if this.options.debug && !describe_build(this, &mut image) { this.problem($"The debugging information could not be written to {this.options.output}.petal."); return; } val bytes := image.file(); val written := write_bytes(this.options.output, bytes.span, 0o755); if !written { this.problem($"The executable could not be written to {this.options.output}."); } }