#! @file windows.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains what an executable for Windows needs beyond the code generation it #! shares with one for Linux: the records the loader reads to import the #! functions of the system and of the libraries the program names, the start #! the system runs it at, the handler of faults and the one of the console's #! events, the code `catch_signal` and a thread begin at, and the writer of the #! PE file. #! #! Windows has no system calls a program makes itself. The generated code calls #! the functions of kernel32 instead, as C functions the executable imports, #! and finds each thread's record through a slot of the system's record of the #! thread, which `gs` points at, rather than through `gs` itself, which Windows #! keeps for its own. import std::containers; import std::io; import sakura::compiler; import binary::amd64; import binary::elf; import binary::pe; module sakura::native; #! The functions of the system the generated code calls, all of kernel32, each #! given a word of the table of addresses the loader writes. pub enum system_import : u8 { tls_alloc, get_current_thread_id, virtual_alloc, get_current_thread_stack_limits, exit_process, add_vectored_exception_handler, set_console_ctrl_handler, create_event, set_event, reset_event, close_handle, open_thread, cancel_synchronous_io, sleep, get_std_handle, write_file, create_thread, count, } pub const system_tls_alloc: system_import = system_import::tls_alloc; pub const system_get_current_thread_id: system_import = system_import::get_current_thread_id; pub const system_virtual_alloc: system_import = system_import::virtual_alloc; pub const system_stack_limits: system_import = system_import::get_current_thread_stack_limits; pub const system_exit_process: system_import = system_import::exit_process; pub const system_add_veh: system_import = system_import::add_vectored_exception_handler; pub const system_set_console_ctrl_handler: system_import = system_import::set_console_ctrl_handler; pub const system_create_event: system_import = system_import::create_event; pub const system_set_event: system_import = system_import::set_event; pub const system_reset_event: system_import = system_import::reset_event; pub const system_close_handle: system_import = system_import::close_handle; pub const system_open_thread: system_import = system_import::open_thread; pub const system_cancel_synchronous_io: system_import = system_import::cancel_synchronous_io; pub const system_sleep: system_import = system_import::sleep; pub const system_get_std_handle: system_import = system_import::get_std_handle; pub const system_write_file: system_import = system_import::write_file; pub const system_create_thread: system_import = system_import::create_thread; #! The name of each function of the system the generated code calls. const system_import_names: strview[17] = [ "TlsAlloc", "GetCurrentThreadId", "VirtualAlloc", "GetCurrentThreadStackLimits", "ExitProcess", "AddVectoredExceptionHandler", "SetConsoleCtrlHandler", "CreateEventW", "SetEvent", "ResetEvent", "CloseHandle", "OpenThread", "CancelSynchronousIo", "Sleep", "GetStdHandle", "WriteFile", "CreateThread" ]; #! The library the functions of the system are imported from. const kernel32: strview = "kernel32.dll"; #! The numbers of the signals the console's events stand for, which are those #! Linux gives them: Ctrl-C interrupts, Ctrl-Break quits, the console closing #! hangs up, and the user leaving or the system shutting down terminates. const signal_hangup: u64 = 1; const signal_interrupt: u64 = 2; const signal_quit: u64 = 3; const signal_terminate: u64 = 15; #! What `catch_signal` is asked to do with a signal, above its number: note it #! when it comes, throw it away, do with it what the system does by default, #! note it now, or give the event set where a signal is noted. const catch_note: i64 = 0; const catch_ignore: i64 = 1; const catch_default: i64 = 2; const catch_now: i64 = 3; const catch_event: i64 = 4; #! Calls a function the code imports of the system, as C is called on Windows: #! with `rsp` aligned to 16 bytes and the 32 bytes above it, which C may keep #! its arguments in, the caller's. Its arguments are placed by the caller. #! @param this The building. #! @param which The function. pub def building::call_system(&mut this, which: system_import): void { this.text.load(8, false, reg::rax, amd64::absolute(this.got + 8 * this.imports_at[which as u64] as u64)); this.text.call_reg(reg::rax); } #! Moves `rsp` down by some bytes, touching each page it passes in turn, as #! Windows grows a thread's stack only into the page past the last it touched. #! @param this The building. #! @param bytes The bytes. pub def building::descend(&mut this, bytes: u64): void { var left := bytes; while left > page_size { this.text.alu_imm(alu::sub, reg::rsp, page_size as i32); this.text.alu_mem_imm(alu::bor, at(reg::rsp, 0), 0); left -= page_size; } if left != 0 { this.text.alu_imm(alu::sub, reg::rsp, left as i32); } } #! Exits with 2 where a step of the start did not hold. #! @param this The building. #! @param condition The condition that holds where it did. def building::exit_unless(&mut this, condition: cc): void { val holds := this.text.jcc(condition); this.text.mov_imm(reg::rcx, 2); this.call_system(system_exit_process); this.text.land(holds); } #! Whether a name holds only ASCII, which the loader finds a library by whatever #! the code page is. #! @param name The name. #! @returns Whether it does. def ascii_only(name: strview): bool { for i in 0..name.length { return false if name[i] >= 0x80; } return true; } #! The RVA of a place in the image, which every record the loader reads names #! parts of the image by. #! @param this The building. #! @param at The offset within the read-only image. #! @returns The address past the image's base. def building::rva(&this, at: u64): u64 { return this.rodata_base + at - base_address; } #! Appends what the loader reads to the image: the name of each function #! imported, the name of each library, a table naming each library's functions #! as its words of the table of addresses will, and the record of each library, #! then a record of zeros. The functions are the system's the code calls, then #! the C functions it names, each library's words together and a word of zeros #! after them, where a function a library is named for twice has one. #! @param this The building. def building::imports(&mut this): void { val program := &this.c.program; val system := system_import::count as u64; val linked := program.linked.length; val total := system + linked; # Each entry's library and name, of those named. A system import is of # kernel32, and a C function of the library its file's `extern import` names. Each library # is found by its name in lower case, as Windows names files whatever the # case of their letters, and kept as it was first named. var library_of := vector::::new(); var name_of := vector::::new(); var folded := interner::::new(); var distinct := vector::::new(); var decl_of := vector::::new(); var word_of := vector::::new(); for e in 0..total { word_of.append(never as u64); var library := kernel32; var name := strview::empty(); var decl: u32 = 0; if e < system { name = system_import_names[e]; } else if this.slots[e - system] != never { library = program.linked[e - system].library.view(); name = this.c.checker.names.text(program.linked[e - system].name); decl = program.linked[e - system].decl; } else { library_of.append(never as u64); name_of.append(name); decl_of.append(0); continue; } val lowered := library.lower(); val found := folded.intern_view(lowered.view()) as u64; if found == distinct.length { distinct.append(library); } library_of.append(found); name_of.append(name); decl_of.append(decl); } # Each library's words of the table of addresses, with a terminator after, # and the hint and name of each function, shared where a library names one # twice. var word: u64 = 0; var functions := interner::::new(); var words := vector::::new(); # The word of each function of the library, by its ID. this.import_firsts.resize(distinct.length); for l in 0..distinct.length { this.import_firsts[l] = word; functions.clear(); words.clear(); for e in 0..total { continue if library_of[e] != l; val id := functions.intern_view(name_of[e]) as u64; if id < words.length { word_of[e] = words[id]; continue; } val at := this.rodata.align_to(2); this.rodata.u16(0); this.rodata.put_terminated(name_of[e]); this.import_names.append(this.rva(at)); words.append(word); word_of[e] = word; word++; } this.import_names.append(0); word++; } this.import_words = word; this.library_count = distinct.length; # The name of each library, noting one the loader could not find. var named := vector::::new(); for l in 0..distinct.length { if !ascii_only(distinct[l]) { var decl: u32 = 0; for e in system..total { if library_of[e] == l { decl = decl_of[e]; break; } } this.problem_at(decl, "Windows finds the libraries of an executable by names of the code page of the system, which cannot hold this one."); } val at := this.bytes(distinct[l]); this.rodata.byte(0); named.append(this.rva(at)); } # The table naming each function, which the import directory reads and the # table of addresses begins as, until the loader writes each one's address. val table := this.words(this.import_words); for w in 0..this.import_words { this.rodata.set_u64(table + 8 * w, this.import_names[w]); } # The record of each library: where its names are, where its addresses go, # patched once the table of addresses is placed, and its name. A record of # zeros ends them. this.rodata.align_to(4); this.descriptors = this.rodata.length; for l in 0..distinct.length { this.rodata.u32(this.rva(table + 8 * this.import_firsts[l])); this.rodata.u32(0); this.rodata.u32(0); this.rodata.u32(named[l]); this.rodata.u32(0); } for _ in 0..5u { this.rodata.u32(0); } # Each entry's word, as the generated code reads it: a system import by its # own number, and a C function where its slot was. this.imports_at.resize(system); for e in 0..total { if e < system { this.imports_at[e] = word_of[e] as u32; } else if this.slots[e - system] != never { this.slots[e - system] = word_of[e] as u32; } } } #! Tells the loader the word each library's addresses are written to, once the #! table of addresses is placed. #! @param this The building. def building::relocate_imports(&mut this): void { for l in 0..this.library_count { this.rodata.set_u32(this.descriptors + 20 * l + 16, this.got + 8 * this.import_firsts[l] - base_address); } } # The start. #! Writes `_start` for Windows, which the system calls on the first thread's #! stack. The native code runs on that stack, the size the file asks, as on #! Linux it runs on one it maps, and a frame larger than a page is grown a page #! at a time so the system commits each. It takes a #! slot of the system's record of each thread for the thread's own record, #! making the first thread's the state, finds where the stack ends, and has #! `runtime::system_start` find the arguments and variables before the #! program runs, then exits with 0. The system's calls are made with `rsp` #! aligned to 16 bytes past the 32 they may use, and two words above those, #! which the stack's limits are asked into. #! @param this The building. def building::entry_windows(&mut this): void { this.start = this.text.length; this.text.alu_imm(alu::sub, reg::rsp, 56); # The slot is one of the first 64, which the system's record holds itself. this.call_system(system_tls_alloc); this.text.extend(4, false, reg::rax, reg::rax); this.text.alu_imm(alu::cmp, reg::rax, tls_count as i32); this.exit_unless(cc::below); this.text.shift_imm(shift::shl, reg::rax, 3); this.text.alu_imm(alu::add, reg::rax, tls_slots as i32); this.text.store(8, amd64::absolute(this.state_address(state_own)), reg::rax); this.text.mov_imm(reg::rcx, this.state_address(0)); this.text.store(8, own_at(reg::rax), reg::rcx); this.text.store(8, amd64::absolute(this.state_address(state_itself)), reg::rcx); this.text.store_imm(amd64::absolute(this.state_address(state_running)), 1); this.call_system(system_get_current_thread_id); this.text.extend(4, false, reg::rax, reg::rax); this.text.store(8, amd64::absolute(this.state_address(state_tid)), reg::rax); # The vector instructions the processor has, kept until `processor` filters them. this.probe(); this.text.store(8, amd64::absolute(this.state_address(state_features)), reg::rax); # The stack the system made it: its top is where frames begin, and the # reserve past the limit, which a trap's report runs in, is at its low end. this.text.lea(reg::rcx, at(reg::rsp, 32)); this.text.lea(reg::rdx, at(reg::rsp, 40)); this.call_system(system_stack_limits); this.text.load(8, false, reg::rax, at(reg::rsp, 32)); this.text.store(8, amd64::absolute(this.state_address(state_trap_frame)), reg::rax); this.text.alu_imm(alu::add, reg::rax, (stack_reserve + 65536) as i32); this.text.store(8, amd64::absolute(this.state_address(state_limit)), reg::rax); this.text.load(8, false, reg::rax, at(reg::rsp, 40)); this.text.store(8, amd64::absolute(this.state_address(state_base)), reg::rax); # Faults of the program are reported as traps, by the first handler of # exceptions. `rsp` keeps the 32 bytes above it the start reserved, which the # call may keep its arguments in. this.text.mov_imm(reg::rcx, 1); this.text.mov_imm(reg::rdx, this.text_base + this.faults); this.call_system(system_add_veh); this.text.mov_imm(reg::rbp, 0); # The arguments and variables, found as the system gives them, before the # globals, since a trap before them could not be reported. this.call_to(this.system_start_function); # The vector instructions the program uses, of those the processor has. this.text.load(8, false, gprs[0], amd64::absolute(this.state_address(state_features))); 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::rcx, 0); this.call_system(system_exit_process); this.text.ud2(); this.entry_end = this.text.length; } # The handlers. #! Writes the code the signal handlers and the threads begin at, after the trap #! stub, which Windows and C call, so each keeps what C keeps, `rsi` and `rdi` #! among them, and uses only `rax`, `rcx`, `rdx`, `r8`, `r9`, and its own stack. #! @param this The building. def building::windows_handlers(&mut this): void { this.fault_handler(); this.signalled_handler(); this.console_handler(); this.catching_handler(); this.stranger_handler(); this.beginning_handler(); } #! Writes the first handler of exceptions, which Windows calls with the context #! of the fault in `rcx`. A fault of the program's code on a thread of the #! program, where no trap is being reported, is reported as the test would have #! been: the thread goes on at the trap stub, as though the instruction faulting #! called it, with the chain of `rbp` it was in. Those faults are an access #! within the first page, which is null reached through, and a division by #! zero. Anything else is left to the next handler, and ends the process where #! none handles it. #! @param this The building. def building::fault_handler(&mut this): void { this.faults = this.text.length; this.text.load(8, false, reg::rax, at(reg::rcx, 0)); # ExceptionRecord this.text.load(4, false, reg::rdx, at(reg::rax, 0)); # ExceptionCode this.text.mov_imm(reg::r9, fault::division as u64); this.text.mov_imm(reg::r8, 0xC0000094); # EXCEPTION_INT_DIVIDE_BY_ZERO this.text.alu(alu::cmp, reg::rdx, reg::r8); val division := this.text.jcc(cc::equal); this.text.mov_imm(reg::r9, fault::null_reference as u64); this.text.mov_imm(reg::r8, 0xC0000005); # EXCEPTION_ACCESS_VIOLATION this.text.alu(alu::cmp, reg::rdx, reg::r8); val other := this.text.jcc(cc::not_equal); this.text.load(8, false, reg::rdx, at(reg::rax, 0x28)); # The address accessed. this.text.alu_imm(alu::cmp, reg::rdx, null_page as i32); val elsewhere := this.text.jcc(cc::above_equal); this.text.land(division); this.text.load(8, false, reg::r8, at(reg::rcx, 8)); # ContextRecord this.text.load(8, false, reg::rax, at(reg::r8, 0xF8)); # Rip 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); # mov ecx, imm32 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); this.own_record(reg::rcx); this.text.test(reg::rcx, reg::rcx); val unknown := this.text.jcc(cc::equal); this.text.alu_mem_imm(alu::cmp, at(reg::rcx, (8 * state_reporting) as i32), 0); val reporting := this.text.jcc(cc::not_equal); # The fault is made to look as though the faulting instruction called the # trap stub, which reads the address it was called from off the stack. this.text.lea(reg::rdx, at(reg::rax, 1)); this.text.load(8, false, reg::rcx, at(reg::r8, 0x98)); # Rsp this.text.alu_imm(alu::sub, reg::rcx, 8); this.text.store(8, at(reg::rcx, 0), reg::rdx); # Rip + 1, as a call pushes it this.text.store(8, at(reg::r8, 0x98), reg::rcx); # Rsp = below it this.text.store(8, at(reg::r8, 0xB0), reg::r9); # Rdi = the fault this.text.mov_imm(reg::rax, this.text_base + this.trap_stub); this.text.store(8, at(reg::r8, 0xF8), reg::rax); # Rip = trap stub this.text.mov_imm(reg::rax, 0xFFFFFFFFFFFFFFFF); # EXCEPTION_CONTINUE_EXECUTION this.text.ret(); this.text.land(other); this.text.land(elsewhere); this.text.land(before); this.text.land(after); this.text.land(unknown); this.text.land(reporting); this.text.mov_imm(reg::rax, 0); # EXCEPTION_CONTINUE_SEARCH this.text.ret(); } #! Writes the code that notes a signal the program handles, by its number in #! `rcx`, as one bit of a word of the state, which the first thread's safe #! points test, setting the event where there is one, which a wait waits on. #! Where another thread notes it, what the first thread reads or writes in the #! system ends, as a signal ends it on Linux. #! @param this The building. def building::signalled_handler(&mut this): void { this.signalled = this.text.length; this.text.alu_imm(alu::sub, reg::rsp, 40); 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.load(8, false, reg::rcx, amd64::absolute(this.state_address(state_signalled))); this.text.test(reg::rcx, reg::rcx); val unasked := this.text.jcc(cc::equal); this.call_system(system_set_event); this.text.land(unasked); this.call_system(system_get_current_thread_id); this.text.extend(4, false, reg::rax, reg::rax); this.text.alu_load(alu::cmp, reg::rax, amd64::absolute(this.state_address(state_tid))); val itself := this.text.jcc(cc::equal); this.text.mov_imm(reg::rcx, 1); # THREAD_TERMINATE this.text.mov_imm(reg::rdx, 0); this.text.load(8, false, reg::r8, amd64::absolute(this.state_address(state_tid))); this.call_system(system_open_thread); this.text.test(reg::rax, reg::rax); val unopened := this.text.jcc(cc::equal); this.text.store(8, at(reg::rsp, 32), reg::rax); this.text.mov(reg::rcx, reg::rax); this.call_system(system_cancel_synchronous_io); this.text.load(8, false, reg::rcx, at(reg::rsp, 32)); this.call_system(system_close_handle); this.text.land(itself); this.text.land(unopened); this.text.alu_imm(alu::add, reg::rsp, 40); this.text.ret(); } #! Writes the console's handler, which Windows calls for each event in `ecx`, #! on a thread of its own with no record, so it reads only the state. The #! signal the event stands for is noted where the program catches it, and #! thrown away where it ignores it, which returns true; otherwise the next #! handler, the system's, ends the process. The console closing or the user #! leaving ends it anyway once this returns, so the program's handler runs, and #! it exits, meanwhile. #! @param this The building. def building::console_handler(&mut this): void { val events: u64[5] = [0, 1, 2, 5, 6]; val numbers: u64[5] = [signal_interrupt, signal_quit, signal_hangup, signal_terminate, signal_terminate]; this.noting = this.text.length; this.text.alu_imm(alu::sub, reg::rsp, 40); this.text.extend(4, false, reg::rcx, reg::rcx); var mapped: u64[5]; for i in 0..5u { this.text.mov_imm(reg::rdx, numbers[i]); this.text.alu_imm(alu::cmp, reg::rcx, events[i] as i32); mapped[i] = this.text.jcc(cc::equal); } val unmapped := this.text.jmp(); for i in 0..5u { this.text.land(mapped[i]); } # The bit of a signal caught in `rax`, and of one ignored in `r8`. this.text.load(8, false, reg::rax, amd64::absolute(this.state_address(state_disposed))); this.text.lea(reg::rcx, at(reg::rdx, 32)); this.text.mov(reg::r8, reg::rax); this.text.shift_cl(shift::shr, reg::r8); this.text.alu_imm(alu::band, reg::r8, 1); val ignored := this.text.jcc(cc::not_equal); this.text.mov(reg::rcx, reg::rdx); this.text.shift_cl(shift::shr, reg::rax); this.text.alu_imm(alu::band, reg::rax, 1); val uncaught := this.text.jcc(cc::equal); this.text.store(8, at(reg::rsp, 32), reg::rdx); this.text.mov(reg::rcx, reg::rdx); this.text.patch(this.text.call(), this.signalled); this.text.load(8, false, reg::rdx, at(reg::rsp, 32)); this.text.alu_imm(alu::cmp, reg::rdx, signal_hangup as i32); val closing := this.text.jcc(cc::equal); this.text.alu_imm(alu::cmp, reg::rdx, signal_terminate as i32); val staying := this.text.jcc(cc::not_equal); this.text.land(closing); this.text.mov_imm(reg::rcx, 10000); # The VM's wait while closing. this.call_system(system_sleep); this.text.land(staying); this.text.land(ignored); this.text.mov_imm(reg::rax, 1); val answered := this.text.jmp(); this.text.land(unmapped); this.text.land(uncaught); this.text.mov_imm(reg::rax, 0); this.text.land(answered); this.text.alu_imm(alu::add, reg::rsp, 40); this.text.ret(); } #! Writes what `catch_signal` calls, with what it is asked in `rcx`: a signal's #! number, and above it what to do. It gives in `rax` zero, the event set where #! a signal is noted where that is asked for, or a negative number: -22 for a #! number of no signal or an action not known, and -12 where the system has no #! event to give. The console's handler is set once a signal is first caught or #! ignored. #! @param this The building. def building::catching_handler(&mut this): void { val event := amd64::absolute(this.state_address(state_signalled)); val disposed := amd64::absolute(this.state_address(state_disposed)); this.catching = this.text.length; this.text.alu_imm(alu::sub, reg::rsp, 56); this.text.extend(4, true, reg::rcx, reg::rcx); this.text.mov(reg::rdx, reg::rcx); this.text.shift_imm(shift::sar, reg::rdx, 8); this.text.alu_imm(alu::band, reg::rcx, 0xFF); this.text.alu_imm(alu::cmp, reg::rdx, catch_event as i32); val signal := this.text.jcc(cc::not_equal); # The event, made once it is first asked for and kept while the process runs. # Where two threads make one at once, the one kept first is given to both. this.text.load(8, false, reg::rax, event); this.text.test(reg::rax, reg::rax); val made := this.text.jcc(cc::not_equal); this.text.mov_imm(reg::rcx, 0); this.text.mov_imm(reg::rdx, 1); # Reset only by the program. this.text.mov_imm(reg::r8, 0); this.text.mov_imm(reg::r9, 0); this.call_system(system_create_event); this.text.test(reg::rax, reg::rax); val created := this.text.jcc(cc::not_equal); this.text.mov_imm(reg::rax, (-12) as i64 as u64); val none := this.text.jmp(); this.text.land(created); this.text.store(8, at(reg::rsp, 32), reg::rax); this.text.mov(reg::rcx, reg::rax); this.text.mov_imm(reg::rax, 0); this.text.lock_cmpxchg(8, event, reg::rcx); val raced := this.text.jcc(cc::not_equal); this.text.mov(reg::rax, reg::rcx); val kept := this.text.jmp(); this.text.land(raced); this.text.store(8, at(reg::rsp, 40), reg::rax); this.text.load(8, false, reg::rcx, at(reg::rsp, 32)); this.call_system(system_close_handle); this.text.load(8, false, reg::rax, at(reg::rsp, 40)); val lost := this.text.jmp(); this.text.land(signal); this.text.lea(reg::rax, at(reg::rcx, -1)); this.text.alu_imm(alu::cmp, reg::rax, 62); val no_signal := this.text.jcc(cc::above); this.text.alu_imm(alu::cmp, reg::rdx, catch_now as i32); val no_action := this.text.jcc(cc::above); val now := this.text.jcc(cc::equal); # The bit of a signal caught in `r8`, and of one ignored in `r9`, or none # where the number is past those of the console's events. this.text.mov_imm(reg::r8, 0); this.text.alu_imm(alu::cmp, reg::rcx, 32); val past := this.text.jcc(cc::above_equal); this.text.mov_imm(reg::r8, 1); this.text.shift_cl(shift::shl, reg::r8); this.text.land(past); this.text.mov(reg::r9, reg::r8); this.text.shift_imm(shift::shl, reg::r9, 32); this.text.alu_imm(alu::cmp, reg::rdx, catch_ignore as i32); val ignoring := this.text.jcc(cc::equal); this.text.alu_imm(alu::cmp, reg::rdx, catch_default as i32); val defaulting := this.text.jcc(cc::equal); this.text.mov(reg::rax, reg::r9); this.text.unary(unary::bnot, reg::rax); this.text.lock(); this.text.alu_store(alu::band, disposed, reg::rax); this.text.lock(); this.text.alu_store(alu::bor, disposed, reg::r8); # A process may start with Ctrl-C ignored, which catching it undoes. this.text.alu_imm(alu::cmp, reg::rcx, signal_interrupt as i32); val caught := this.text.jcc(cc::not_equal); this.text.mov_imm(reg::rcx, 0); this.text.mov_imm(reg::rdx, 0); this.call_system(system_set_console_ctrl_handler); val heeded := this.text.jmp(); this.text.land(ignoring); this.text.mov(reg::rax, reg::r8); this.text.unary(unary::bnot, reg::rax); this.text.lock(); this.text.alu_store(alu::band, disposed, reg::rax); this.text.lock(); this.text.alu_store(alu::bor, disposed, reg::r9); # The handler is set by the first to set the lowest bit. this.text.land(caught); this.text.land(heeded); this.text.load(8, false, reg::rax, disposed); val again := this.text.length; this.text.mov(reg::rcx, reg::rax); this.text.alu_imm(alu::band, reg::rcx, 1); val set := this.text.jcc(cc::not_equal); this.text.lea(reg::rcx, at(reg::rax, 1)); this.text.lock_cmpxchg(8, disposed, reg::rcx); this.text.patch(this.text.jcc(cc::not_equal), again); this.text.mov_imm(reg::rcx, this.text_base + this.noting); this.text.mov_imm(reg::rdx, 1); this.call_system(system_set_console_ctrl_handler); this.text.land(set); this.text.mov_imm(reg::rax, 0); val handled := this.text.jmp(); this.text.land(defaulting); this.text.mov(reg::rax, reg::r8); this.text.alu(alu::bor, reg::rax, reg::r9); this.text.unary(unary::bnot, reg::rax); this.text.lock(); this.text.alu_store(alu::band, disposed, reg::rax); this.text.mov_imm(reg::rax, 0); val restored := this.text.jmp(); this.text.land(now); this.text.patch(this.text.call(), this.signalled); this.text.mov_imm(reg::rax, 0); val noted := this.text.jmp(); this.text.land(no_signal); this.text.land(no_action); this.text.mov_imm(reg::rax, (-22) as i64 as u64); this.text.land(made); this.text.land(none); this.text.land(kept); this.text.land(lost); this.text.land(handled); this.text.land(restored); this.text.land(noted); this.text.alu_imm(alu::add, reg::rsp, 56); this.text.ret(); } #! Writes what a callback on a thread the program never started reports #! through: the machine's text for a callback it cannot run, to the standard #! error, then it ends the process with 1. #! @param this The building. def building::stranger_handler(&mut this): void { # The prefix `sakura: runtime error: `, the description of the callback error, # and a new line, as the image holds its texts. val report: u64[3] = [32, 23, 37]; this.stranger = this.text.length; this.text.alu_imm(alu::band, reg::rsp, -16); this.text.alu_imm(alu::sub, reg::rsp, 64); this.text.mov_imm(reg::rcx, 0xFFFFFFF4); # STD_ERROR_HANDLE this.call_system(system_get_std_handle); this.text.store(8, at(reg::rsp, 48), reg::rax); for i in 0..3u { val text := this.texts_at + 16 * report[i]; this.text.load(8, false, reg::rcx, at(reg::rsp, 48)); this.text.load(8, false, reg::rdx, amd64::absolute(this.rodata_base + text)); this.text.load(8, false, reg::r8, amd64::absolute(this.rodata_base + text + 8)); this.text.lea(reg::r9, at(reg::rsp, 40)); this.text.store_imm(at(reg::rsp, 32), 0); this.call_system(system_write_file); } this.text.mov_imm(reg::rcx, 1); this.call_system(system_exit_process); this.text.ud2(); } #! Writes where a thread the program starts begins, as Windows begins one, with #! its record in `rcx`. It runs on the stack the system made it, as the first #! thread runs on the one the file asked. It points the thread's slot at the #! record, finds where its stack ends, as the start does, runs #! `runtime::thread_main` with no frame before it, and ends by returning. #! @param this The building. def building::beginning_handler(&mut this): void { val kept: reg[8] = [reg::rbp, reg::rbx, reg::rsi, reg::rdi, reg::r12, reg::r13, reg::r14, reg::r15]; this.beginning = this.text.length; for k in 0..8u { this.text.push(kept[k]); } this.text.alu_imm(alu::sub, reg::rsp, 56); this.text.mov(reg::r15, reg::rcx); this.text.load(8, false, reg::rax, amd64::absolute(this.state_address(state_own))); this.text.store(8, own_at(reg::rax), reg::r15); # The stack grows down from its high end to its low; the reserve past the # limit, which a trap's report runs in, is at the low end. this.text.lea(reg::rcx, at(reg::rsp, 32)); this.text.lea(reg::rdx, at(reg::rsp, 40)); this.call_system(system_stack_limits); this.text.load(8, false, reg::rax, at(reg::rsp, 32)); this.text.store(8, at(reg::r15, (8 * state_trap_frame) as i32), reg::rax); this.text.alu_imm(alu::add, reg::rax, (stack_reserve + 65536) as i32); this.text.store(8, at(reg::r15, (8 * state_limit) as i32), reg::rax); this.text.load(8, false, reg::rax, at(reg::rsp, 40)); this.text.store(8, at(reg::r15, (8 * state_base) as i32), reg::rax); this.text.mov_imm(reg::rbp, 0); this.call_to(this.helper_of(helper::thread_main)); this.text.alu_imm(alu::add, reg::rsp, 56); for k in 0..8u { this.text.pop(kept[8 - 1 - k]); } this.text.mov_imm(reg::rax, 0); this.text.ret(); } #! `clone`: a thread of the system, which runs `beginning` with the record. The #! system makes its stack, which it reserves as large as the first thread's and #! commits as it grows, and writes its number in the record. The thread's #! handle, which reaping it waits on, is kept in the record. The record #! and `rsp` are kept in `rsi` and `rdi`, which C keeps on Windows. #! @param this The selector. #! @param index The instruction. #! @param held The instruction. def selector::clone_thread_windows(&mut this, index: u32, held: &inst): void { val record := this.word_reg(this.body.arg(index, 0), index, reg::rdx); this.b.text.mov(reg::rsi, record); this.b.text.mov(reg::rdi, reg::rsp); this.b.text.alu_imm(alu::band, reg::rsp, -16); this.b.text.alu_imm(alu::sub, reg::rsp, 48); this.b.text.mov_imm(reg::rcx, 0); this.b.text.load(8, false, reg::rdx, at(reg::rsi, (8 * state_map_size) as i32)); # The bytes of stack to reserve. this.b.text.mov_imm(reg::r8, this.b.text_base + this.b.beginning); this.b.text.mov(reg::r9, reg::rsi); this.b.text.store_imm(at(reg::rsp, 32), 0x10000); # STACK_SIZE_PARAM_IS_A_RESERVATION this.b.text.lea(reg::rax, at(reg::rsi, (8 * state_tid) as i32)); this.b.text.store(8, at(reg::rsp, 40), reg::rax); this.b.call_system(system_create_thread); this.b.text.mov(reg::rsp, reg::rdi); this.b.text.test(reg::rax, reg::rax); val failed := this.b.text.jcc(cc::equal); this.b.text.store(8, at(reg::rsi, (8 * state_handle) as i32), reg::rax); this.b.text.load(8, false, reg::rax, at(reg::rsi, (8 * state_tid) as i32)); val started := this.b.text.jmp(); this.b.text.land(failed); this.b.text.mov_imm(reg::rax, (-11) as i64 as u64); # EAGAIN, the VM's default. this.b.text.land(started); this.put(held.result, reg::rax); } # The file. #! Writes the executable as a PE file: its sections, then how each function #! unwinds, which the system reads to unwind a thread's stack, as exceptions #! and debuggers do. Where debugging information is asked for, the executable #! names the PDB file written beside it, which Windows' debuggers read, and #! holds the DWARF other debuggers read, in sections the system loads but only #! debuggers read. #! @param this The building. #! @param data The bytes of the data segment, the globals and the table of #! addresses among the zeros. def building::write_pe(&mut this, data: span): void { var image := pe::image::new(base_address, this.text_base + this.start); image.stack_reserve = 4 * this.stack + 0x100000; image.stack_commit = 0x10000; image.imports = pe::directory { address = this.rodata_base + this.descriptors, size = 20 * (this.library_count + 1) }; image.iat = pe::directory { address = this.got, size = this.import_words * 8 }; val parts := this.loaded_parts(data); for k in 0..4u { val part: loaded_part = parts[k]; image.section(part.name, part.address, part.data, part.size, part.flags); } # How each function unwinds: the records, then the table naming each # function's, which the exception directory names, each a page past the last. var address := round_up(this.late_base + this.late.length, page_size); var unwinding := pe::unwind_table::new(); var functions := pe::function_table::new(); this.unwind_functions(&mut unwinding, &mut functions, address); image.section(".xdata", address, unwinding.bytes.view(), unwinding.bytes.length, pe::readable); address = round_up(address + unwinding.bytes.length, page_size); val table := functions.bytes(); image.section(".pdata", address, table.view(), table.length, pe::readable); image.exceptions = pe::directory { address = address, size = table.length }; address = round_up(address + table.length, page_size); if !this.options.debug { val bytes := this.pe_file(&mut image); this.write_executable(bytes.view()); return; } # The debug directory naming the PDB file, by its path and, once the file is # written, its GUID, then the DWARF; the writers holding them live until the # file is written. val directory := build_directory(); val pdb_path := pdb_path_of(this.options.output, directory.view()); val record := pe::codeview_record(1, pdb_path.view()); var named := byte_writer::new(); pe::debug_entry(&mut named, pe::debug_codeview, (address + pe::debug_entry_bytes - base_address) as u32, record.length as u32); named.put(record.view()); image.section(".buildid", address, named.view(), named.length, pe::readable); image.debug = pe::directory { address = address, size = pe::debug_entry_bytes }; address = round_up(address + named.length, page_size); var described := write_dwarf(this, directory.view()); for k in 0..debug_names.length { address = this.embed_section(&mut image, debug_names[k], address, described.section(k)); } var bytes := this.pe_file(&mut image); if !describe_pdb(this, &mut bytes, pdb_path.view(), directory.view()) { this.problem($"The debugging information could not be written to {pdb_path}."); return; } this.write_executable(bytes.view()); } #! Adds a section of debugging information at an address, giving where the next #! would begin. #! @param this The building. #! @param image The executable. #! @param name The section's name. #! @param address Where it is loaded. #! @param part Its bytes. #! @returns Where a section after it would begin. def building::embed_section(&this, image: &mut pe::image, name: strview, address: u64, part: &byte_writer): u64 { image.section(name, address, part.view(), part.length, pe::readable | pe::discardable); return round_up(address + part.length, page_size); } #! The bytes of a PE executable, its functions named. #! @param this The building. #! @param image The executable. #! @returns The bytes. def building::pe_file(&this, image: &mut pe::image): byte_writer { var named := vector::::new(); this.name_code(&mut named); for &each in named { image.symbols.append(pe::symbol { name = each.name, address = each.address }); } return image.file(); } #! Writes an executable's bytes to its file. #! @param this The building. #! @param bytes The bytes. def building::write_executable(&mut this, bytes: span): void { if !write_bytes(this.options.output, bytes, 0o755) { this.problem($"The executable could not be written to {this.options.output}."); } } # Unwinding. #! The register `rbp`, as unwinding numbers it. const unwind_rbp: u8 = 5; #! Whether code at an offset is `sub rsp, BYTES`, as a handler's prologue is. #! @param this The building. #! @param at The offset, within the code. #! @param bytes The bytes taken, below 128. #! @returns Whether it is. def building::takes_stack(&this, at: u64, bytes: u64): bool { val code := &this.text.bytes; return code.get_byte(at) == 0x48 && code.get_byte(at + 1) == 0x83 && code.get_byte(at + 2) == 0xEC && code.get_byte(at + 3) as u64 == bytes; } #! Adds a piece of code's record of unwinding, and names it in the table. #! @param this The building. #! @param unwinding The records. #! @param functions The table. #! @param xdata Where the records are. #! @param begin Where the code begins, within the code. #! @param end Where it ends. #! @param info Its record. def building::unwinds(&this, unwinding: &mut pe::unwind_table, functions: &mut pe::function_table, xdata: u64, begin: u64, end: u64, info: &pe::unwind_info): void { val at := unwinding.add(info); val code := this.text_base - base_address; functions.add((code + begin) as u32, (code + end) as u32, (xdata - base_address + at as u64) as u32); } #! Writes how each piece of code that moves the stack unwinds: every function, #! which pushes `rbp`, points it at its frame, then pushes the registers it #! saves; the trap stub, which makes its frame as a function does; and the #! start and the handlers Windows calls, which take bytes of the stack or push #! the registers C keeps. A function's frame is found from `rbp` however the #! stack moves within it. Its saved registers are below where `rbp` points, so #! the record says `rbp` points past the frame's base, by as many bytes as #! hold them, taken as the frame was made, which unwinding gives back before #! popping `rbp`. Code whose bytes are not those this describes is left #! undescribed. #! @param this The building. #! @param unwinding The records, added. #! @param functions The table, added. #! @param xdata Where the records are loaded. def building::unwind_functions(&this, unwinding: &mut pe::unwind_table, functions: &mut pe::function_table, xdata: u64): void { val code := &this.text.bytes; val framed := this.trap_framed - this.trap_stub; val based := this.trap_based - this.trap_stub; if based < 256 { var stub := pe::unwind_info::new(); stub.pushed(framed as u8, unwind_rbp); stub.framed(based as u8, unwind_rbp, 0); this.unwinds(unwinding, functions, xdata, this.trap_stub, this.faults, &stub); } # The handlers taking bytes of the stack, each until the next begins, and # the start. val begins: u64[4] = [this.signalled, this.noting, this.catching, this.start]; val endings: u64[4] = [this.noting, this.catching, this.stranger, this.entry_end]; val taken: u64[4] = [40, 40, 56, 56]; for k in 0..4u { continue if !this.takes_stack(begins[k], taken[k]); var handler := pe::unwind_info::new(); handler.allocated(4, taken[k]); this.unwinds(unwinding, functions, xdata, begins[k], endings[k], &handler); } # Where a thread begins pushes the registers C keeps, then takes bytes. val kept: u8[8] = [5, 3, 6, 7, 12, 13, 14, 15]; var beginning := pe::unwind_info::new(); var at := this.beginning; var pushes := true; for k in 0..8u { val wide := kept[k] >= 8; if wide { pushes = pushes && code.get_byte(at) == 0x41; at++; } pushes = pushes && code.get_byte(at) == 0x50 + (kept[k] & 7); at++; beginning.pushed((at - this.beginning) as u8, kept[k]); } if pushes && this.takes_stack(at, 56) { beginning.allocated((at + 4 - this.beginning) as u8, 56); this.unwinds(unwinding, functions, xdata, this.beginning, this.overflow_stub, &beginning); } for i in 0..this.c.program.functions.length { val start := this.starts[i]; continue if start == this.missing || this.ends[i] <= start; val saved_at := this.debug.saved_at[i] as u64; continue if saved_at > 255 || code.get_byte(start) != 0x55 || code.get_byte(start + 1) != 0x48 || code.get_byte(start + 2) != 0x89 || code.get_byte(start + 3) != 0xE5; # The registers saved, in the order they were pushed, the last ending where # the saving does. val saves := this.debug.saves[i]; var registers: u8[5]; var count: u64 = 0; for &r in kept_gprs { if (saves & (1u << r as u64) as u32) != 0 { registers[count] = r as u8; count++; } } var ends: u64[5]; var pushed := saved_at; var k := count; while k > 0 { k--; ends[k] = pushed; pushed -= registers[k] >= 8 ? 2 : 1; } val below := 16 * ((count + 1) / 2); var info := pe::unwind_info::new(); info.pushed(1, unwind_rbp); if below != 0 { info.allocated(4, below); } info.framed(4, unwind_rbp, below); for s in 0..count { info.saved(ends[s] as u8, registers[s], below - 8 * (s + 1)); } this.unwinds(unwinding, functions, xdata, start, this.ends[i], &info); } }