Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-26 10:02:47 -05:00
commit 253eca39ed
33 files changed
+7506

No files matched your search

+123
View File
@@ -0,0 +1,123 @@
#! @file debug.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains how an executable names its debugging information: the debug
#! directory's entries, each naming a record within the image, and the record
#! naming a PDB file, `RSDS`, by its GUID, its age, and its path, which a
#! debugger finds the file by and matches it with. A record names a file whose
#! GUID is only known once both are written, so the file is stamped with it
#! last. And the headers of an executable's sections, as a PDB file keeps them.
import std::io;
module binary::pe;
#! The kind of entry naming a PDB file, as CodeView's.
pub const debug_codeview: u32 = 2;
#! The bytes of an entry of the debug directory.
pub const debug_entry_bytes: u64 = 28;
#! Adds an entry to a debug directory, naming a record within the image. Where
#! the record is in the file is written as the file is.
#! @param out The directory.
#! @param kind The kind of record, as `debug_codeview`.
#! @param address Where the record is, past the image's base.
#! @param size The record's bytes.
pub def debug_entry(out: &mut byte_writer, kind: u32, address: u32, size: u32): void {
out.u32(0); # Its characteristics,
out.u32(0); # its time, as `stamp_codeview` writes it,
out.u16(0); # and no version.
out.u16(0);
out.u32(kind);
out.u32(size);
out.u32(address);
out.u32(0); # Where it is in the file.
}
#! The record naming a PDB file: `RSDS`, its GUID, as `stamp_codeview` writes
#! it, its age, and its path, ending with a zero.
#! @param age How many times the file was written for the executable.
#! @param path The file's path.
#! @returns The record.
pub def codeview_record(age: u32, path: strview): byte_writer {
var made := byte_writer::new();
made.put("RSDS");
made.zeros(16);
made.u32(age);
made.put_terminated(path);
return made;
}
#! Where in an executable's file an address past its base is, by the section
#! holding it, or 0 where none does.
#! @param file The file.
#! @param address The address.
#! @returns Where it is.
def file_offset_of(file: span<u8>, address: u64): u64 {
val pe := word_at(file, 0x3C, 4);
val count := word_at(file, pe + 6, 2);
val table := pe + 24 + word_at(file, pe + 20, 2);
for k in 0..count {
val at := table + 40 * k;
val begins := word_at(file, at + 12, 4);
val size := word_at(file, at + 8, 4);
if address >= begins && address < begins + size {
return word_at(file, at + 20, 4) + address - begins;
}
}
return 0;
}
# A word of a file, least significant byte first.
def word_at(file: span<u8>, at: u64, bytes: u64): u64 {
var made: u64 = 0;
for k in 0..bytes {
made = made | (file[at + k] as u64 << (8 * k));
}
return made;
}
#! Stamps an executable's file with the GUID of the PDB file it names, and a
#! word of it as the time of each entry naming one, once that file is written.
#! @param file The executable's file.
#! @param guid The PDB file's GUID.
#! @param stamp The word.
#! @returns Whether the file names a PDB file.
pub def stamp_codeview(file: &mut byte_writer, guid: u8[16], stamp: u32): bool {
val bytes := file.view();
val pe := word_at(bytes, 0x3C, 4);
val directory := pe + 24 + 112 + 8 * 6;
val address := word_at(bytes, directory, 4);
val size := word_at(bytes, directory + 4, 4);
return false if address == 0;
val first := file_offset_of(bytes, address);
return false if first == 0;
var named := false;
for k in 0..size / debug_entry_bytes {
val entry := first + debug_entry_bytes * k;
continue if word_at(file.view(), entry + 12, 4) != debug_codeview as u64;
file.set_u32(entry + 4, stamp);
val record := word_at(file.view(), entry + 24, 4);
for i in 0..16u {
file.set_byte(record + 4 + i, guid[i]);
}
named = true;
}
return named;
}
#! The headers of an executable's sections, as its file holds them, which a
#! PDB file keeps to place what it names.
#! @param file The file.
#! @returns The headers.
pub def section_headers(file: span<u8>): byte_writer {
val pe := word_at(file, 0x3C, 4);
val count := word_at(file, pe + 6, 2);
val table := pe + 24 + word_at(file, pe + 20, 2);
var made := byte_writer::new();
made.put(span::<u8>::over(file.data + table, 40 * count));
return made;
}
+310
View File
@@ -0,0 +1,310 @@
#! @file pe.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the writer of PE files: an x86-64 Windows executable, run in a
#! console unless another subsystem is given, loaded at the address it was
#! built for with nothing to relocate, so every section is at an address known
#! while building and the file holds each at the same offset from its start as
#! the section is from the image's. The tables the loader and debuggers read,
#! as the imports, are named by the data directories, each at an address within
#! a section. The functions are named in a COFF symbol table so debuggers and
#! disassemblers show them, and a section whose name is longer than eight
#! bytes, as debugging information names them, is named by where the name is
#! in the table of strings after the symbols.
import std::io;
module binary::pe;
#! The permissions of a section, numbered as ELF numbers a segment's, and
#! whether only debuggers read it, so the system may discard it once loaded.
pub const readable: u32 = 4;
pub const writable: u32 = 2;
pub const executable: u32 = 1;
pub const discardable: u32 = 8;
#! The bytes of the file headers, which the first section follows.
pub const headers_size: u64 = 0x1000;
# Sections are aligned to a page in memory and in the file alike, so each is at
# the same offset in both. The header of the image follows that of MS-DOS, then
# the optional header, then the section headers.
const page: u64 = 0x1000;
const signature_at: u64 = 0x40;
const file_header: u64 = 0x44;
const optional_header: u64 = 0x58;
const section_table: u64 = 0x148;
const section_bytes: u64 = 40;
const name_bytes: u64 = 8;
#! A section, loaded where it is placed, a page past the one before it.
pub struct section {
pub var name: strview; #! As `.text`, or longer, as debugging information names them.
pub var address: u64; #! Aligned to a page.
pub var data: span<u8>; #! What it holds.
pub var size: u64; #! How many bytes.
pub var flags: u32; #! As `readable`, `writable`, `executable`, and `discardable`.
}
#! Where a table the loader reads is, at an address within a section, or
#! nowhere where its address is 0.
pub struct directory {
pub var address: u64;
pub var size: u64;
}
#! A function, which debuggers and disassemblers show by name.
pub struct symbol {
pub var name: strview;
pub var address: u64;
}
#! An executable to write.
pub struct image {
pub var base: u64; #! Where it is loaded, below 2 GiB, as every address its code holds is.
pub var entry: u64;
pub var subsystem: u16 = 3; #! A console's, unless given.
pub var stack_reserve: u64; #! The bytes of the first thread's stack.
pub var stack_commit: u64;
pub var sections: vector<section>; #! In order of their addresses.
pub var imports: directory; #! The record of each library imported, then a record of zeros.
pub var exceptions: directory; #! The table of functions and how each unwinds.
pub var debug: directory; #! The records naming the executable's debugging information.
pub var iat: directory; #! The words the loader writes the addresses imported to.
pub var symbols: vector<symbol>; #! The functions, each within a section.
}
#! Makes an executable loaded at an address and starting at another, with
#! nothing in it yet.
#! @param base Where it is loaded.
#! @param entry Where it starts.
#! @returns The executable.
pub def image::new(base: u64, entry: u64): image {
return image {
base = base,
entry = entry,
sections = vector::<section>::new(),
imports = directory {},
exceptions = directory {},
debug = directory {},
iat = directory {},
symbols = vector::<symbol>::new()
};
}
#! Adds a section.
#! @param this The executable.
#! @param name Its name.
#! @param address Where it is loaded.
#! @param data What it holds.
#! @param size How many bytes.
#! @param flags Its permissions.
pub def image::section(&mut this, name: strview, address: u64, data: span<u8>, size: u64, flags: u32): void {
this.sections.append(section { name = name, address = address, data = data, size = size, flags = flags });
}
#! The end of a section, aligned to a page.
#! @param value Where it ends.
#! @returns The end.
def page_aligned(value: u64): u64 {
return (value + page - 1) / page * page;
}
#! Adds zeros up to a place, where the bytes end before it, so what is added
#! next begins there.
#! @param file The bytes.
#! @param at The place.
def pad_to(file: &mut byte_writer, at: u64): void {
if file.length < at {
file.zeros(at - file.length);
}
}
#! The eight bytes a name is held in, as a word, least significant byte first:
#! the name, padded with zeros, or, where it is longer, where it is in the table
#! of strings, which it is added to: a section's as `/` and the offset in
#! decimal, and a symbol's as four zero bytes and the offset.
#! @param strings The table of strings, whose first four bytes hold its size.
#! @param name The name.
#! @param of_symbol Whether it is a symbol's, rather than a section's.
#! @returns The bytes.
def name_word(strings: &mut byte_writer, name: strview, of_symbol: bool): u64 {
var word: u64 = 0;
if name.length <= name_bytes {
for i in 0..name.length {
word = word | (name[i] as u64 << (8 * i));
}
return word;
}
val offset := strings.length;
strings.put_terminated(name);
return offset << 32 if of_symbol;
var digits: u8[10];
var count: u64 = 0;
var left := offset;
while true {
digits[count] = ('0' as u64 + left % 10) as u8;
count++;
left = left / 10;
break if left == 0;
}
# Digits past the eighth byte are not held.
word = '/' as u64;
for i in 0..count {
break if i + 1 >= name_bytes;
word = word | (digits[count - 1 - i] as u64 << (8 * (i + 1)));
}
return word;
}
#! The characteristics of a section: code, or data, read, written, or only read
#! by debuggers.
#! @param flags Its permissions.
#! @returns The characteristics.
def characteristics(flags: u32): u64 {
return 0x60000020 if (flags & executable) != 0; # Code, executed and read.
var made: u64 = 0x40000040; # Data, read.
if (flags & writable) != 0 { made = made | 0x80000000; }
if (flags & discardable) != 0 { made = made | 0x02000000; }
return made;
}
#! The bytes of the file of the executable: the headers, each section's data
#! padded to a page, then the symbols and the table of strings, which the
#! loader does not read. The headers take the first page, written once what
#! they say is known.
#! @param this The executable.
#! @returns The bytes.
pub def image::file(&this): byte_writer {
var file := byte_writer::new();
file.zeros(headers_size);
var strings := byte_writer::new();
strings.u32(0);
# The sections holding nothing are left out, so no two share an address.
var numbers := vector::<u64>::new();
var raw := vector::<u64>::new();
var count: u64 = 0;
var offset := headers_size;
var end := this.base + headers_size;
var code: u64 = 0;
var code_size: u64 = 0;
var data_size: u64 = 0;
for &each in this.sections {
if each.size == 0 {
numbers.append(0);
raw.append(0);
continue;
}
val at := section_table + count * section_bytes;
val held := page_aligned(each.size);
count++;
numbers.append(count);
raw.append(offset);
file.set_u64(at, name_word(&mut strings, each.name, false));
file.set_u32(at + 8, each.size);
file.set_u32(at + 12, each.address - this.base);
file.set_u32(at + 16, held);
file.set_u32(at + 20, offset);
file.set_u32(at + 36, characteristics(each.flags));
pad_to(&mut file, offset);
file.put(each.data);
offset += held;
end = page_aligned(each.address + each.size);
if (each.flags & executable) != 0 {
code = code == 0 ? each.address : code;
code_size += held;
} else {
data_size += held;
}
}
pad_to(&mut file, offset);
# Each function is named within the section holding it, by its offset there.
val symbols := offset;
var symbol_count: u64 = 0;
for &named in this.symbols {
for i in 0..this.sections.length {
val each: section = this.sections[i];
continue if numbers[i] == 0 || named.address < each.address || named.address >= each.address + each.size;
file.u64(name_word(&mut strings, named.name, true));
file.u32(named.address - each.address);
file.u16(numbers[i]);
file.u16(0x20); # A function,
file.byte(2); # named outside the file.
file.byte(0);
symbol_count++;
break;
}
}
# The strings follow the symbols, where the file's header says the symbols
# are, even where there are none, as the names of sections may be among them.
val tabled := symbol_count != 0 || strings.length > 4;
strings.set_u32(0, strings.length);
if tabled {
file.put(strings.view());
}
# The header of MS-DOS, which only says where the header of the image is.
file.set_byte(0, 'M' as u8);
file.set_byte(1, 'Z' as u8);
file.set_u32(0x3C, signature_at);
file.set_u32(signature_at, ('P' as u64) | (('E' as u64) << 8));
val f := file_header;
file.set_u16(f, 0x8664); # x86-64,
file.set_u16(f + 2, count);
file.set_u32(f + 8, tabled ? symbols : 0);
file.set_u32(f + 12, symbol_count);
file.set_u16(f + 16, 0xF0);
# with nothing to relocate, an executable, and an address space larger than
# 2 GiB, which the runtime's memory reserves.
file.set_u16(f + 18, 0x0023);
val o := optional_header;
file.set_u16(o, 0x20B); # PE32+
file.set_u32(o + 4, code_size);
file.set_u32(o + 8, data_size);
file.set_u32(o + 16, this.entry - this.base);
file.set_u32(o + 20, code != 0 ? code - this.base : 0);
file.set_u64(o + 24, this.base);
file.set_u32(o + 32, page);
file.set_u32(o + 36, page);
file.set_u16(o + 40, 6); # Windows Vista and later.
file.set_u16(o + 48, 6);
file.set_u32(o + 56, end - this.base);
file.set_u32(o + 60, headers_size);
file.set_u16(o + 68, this.subsystem); # 3 runs it in a console.
# Its memory is executed only where it is code, and it is loaded where it was
# built for, which every address its code holds assumes: NX_COMPAT and
# TERMINAL_SERVER_AWARE, but not DYNAMIC_BASE.
file.set_u16(o + 70, 0x8100);
file.set_u64(o + 72, this.stack_reserve);
file.set_u64(o + 80, this.stack_commit);
file.set_u64(o + 88, 0x100000);
file.set_u64(o + 96, 0x1000);
file.set_u32(o + 108, 16);
# The data directories, by their numbers.
val directories: directory[4] = [this.imports, this.exceptions, this.debug, this.iat];
val indexes: u64[4] = [1, 3, 6, 12];
for k in 0..4u {
val each: directory = directories[k];
continue if each.address == 0;
file.set_u32(o + 112 + 8 * indexes[k], each.address - this.base);
file.set_u32(o + 116 + 8 * indexes[k], each.size);
}
# Each entry of the debug directory says where in the file its record is,
# which only the file's layout knows.
if this.debug.address != 0 {
val first := file_offset_of(file.view(), this.debug.address - this.base);
for k in 0..this.debug.size / debug_entry_bytes {
val entry := first + debug_entry_bytes * k;
val record := file_offset_of(file.view(), file.get_u32(entry + 20) as u64);
file.set_u32(entry + 24, record);
}
}
return file;
}
+212
View File
@@ -0,0 +1,212 @@
#! @file unwind.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the writer of how x86-64 code on Windows unwinds, which the system
#! reads to unwind a thread's stack past each function, as exceptions and
#! debuggers do: each function's record of how its prologue made its frame, as
#! `.xdata` holds them, and the table of each function's code and its record,
#! sorted by address, as `.pdata` holds it and the exception directory names.
#!
#! A record lists what the prologue did, each at the offset just past its
#! instruction, the latest first: registers pushed, bytes taken from the stack,
#! the frame register set, and registers saved in the frame. Unwinding past
#! the prologue undoes each in turn; within it, only those done yet.
import std::containers;
import std::io;
module binary::pe;
# What each code of a record does, in its low four bits.
const push_nonvolatile: u16 = 0;
const allocate_large: u16 = 1;
const allocate_small: u16 = 2;
const set_frame: u16 = 3;
const save_nonvolatile: u16 = 4;
const save_far: u16 = 5;
#! What a function's prologue did, as its record of unwinding says it.
pub struct unwind_info {
var codes: vector<u16>; #! Each code's slots, in the order the prologue did them.
var starts: vector<u64>; #! Where each code's slots begin.
var prologue: u8; #! The bytes of the prologue.
var register: u8; #! The frame register, or 0 for none.
var offset: u8; #! What the frame register points past the frame's base, in 16 bytes.
}
#! Makes the record of a prologue that did nothing, as a function that leaves
#! the stack as its caller left it has.
#! @returns The record.
pub def unwind_info::new(): unwind_info {
return unwind_info { codes = vector::<u16>::new(), starts = vector::<u64>::new(), prologue = 0, register = 0, offset = 0 };
}
# Adds a code done just before an offset, and its operand's slots after.
def unwind_info::code(&mut this, at: u8, op: u16, info: u16): void {
this.starts.append(this.codes.length);
this.codes.append(at as u16 | (op << 8) | (info << 12));
if at > this.prologue {
this.prologue = at;
}
}
#! The prologue pushed a register, just before an offset.
#! @param this The record.
#! @param at Where the push ends, from where the function begins.
#! @param register The register, as x86-64 numbers it: `rbp` is 5.
pub def unwind_info::pushed(&mut this, at: u8, register: u8): void {
this.code(at, push_nonvolatile, register as u16);
}
#! The prologue took bytes from the stack, just before an offset.
#! @param this The record.
#! @param at Where the instruction taking them ends.
#! @param bytes How many, a multiple of 8.
pub def unwind_info::allocated(&mut this, at: u8, bytes: u64): void {
if bytes <= 128 {
this.code(at, allocate_small, (bytes / 8 - 1) as u16);
} else if bytes <= 512 * 1024 - 8 {
this.code(at, allocate_large, 0);
this.codes.append((bytes / 8) as u16);
} else {
this.code(at, allocate_large, 1);
this.codes.append((bytes & 0xFFFF) as u16);
this.codes.append((bytes >> 16) as u16);
}
}
#! The prologue pointed a register at the frame, past its base by an offset,
#! just before an offset of the code. The frame is found from that register
#! from then on, however the stack moves.
#! @param this The record.
#! @param at Where the instruction ends.
#! @param register The register.
#! @param offset How far past the frame's base it points, a multiple of 16
#! up to 240.
pub def unwind_info::framed(&mut this, at: u8, register: u8, offset: u64): void {
this.code(at, set_frame, 0);
this.register = register;
this.offset = (offset / 16) as u8;
}
#! The prologue saved a register in the frame, just before an offset.
#! @param this The record.
#! @param at Where the instruction saving it ends.
#! @param register The register.
#! @param offset Where it is, past the frame's base, a multiple of 8.
pub def unwind_info::saved(&mut this, at: u8, register: u8, offset: u64): void {
if offset / 8 <= 0xFFFF {
this.code(at, save_nonvolatile, register as u16);
this.codes.append((offset / 8) as u16);
} else {
this.code(at, save_far, register as u16);
this.codes.append((offset & 0xFFFF) as u16);
this.codes.append((offset >> 16) as u16);
}
}
#! The record as `.xdata` holds it: version 1, the prologue's bytes, how many
#! slots its codes take, the frame register and its offset, then the codes,
#! the latest first, padded to an even number of slots.
#! @param this The record.
#! @returns The record's bytes.
pub def unwind_info::bytes(&this): byte_writer {
var made := byte_writer::new();
made.byte(1);
made.byte(this.prologue);
made.byte(this.codes.length as u8);
made.byte(this.register | (this.offset << 4));
var k := this.starts.length;
while k > 0 {
k--;
val end := k + 1 < this.starts.length ? this.starts[k + 1] : this.codes.length;
for s in this.starts[k]..end {
made.u16(this.codes[s]);
}
}
if this.codes.length % 2 != 0 {
made.u16(0);
}
return made;
}
#! The records of how functions unwind, as `.xdata` holds them, each once and
#! aligned to four bytes, however many functions share it.
pub struct unwind_table {
pub var bytes: byte_writer; #! The section's bytes.
var held: interner<string>; #! Each record, by its ID.
var at: vector<u32>; #! Where each is, by its ID.
}
#! Makes a table holding no records.
#! @returns The table.
pub def unwind_table::new(): unwind_table {
return unwind_table { bytes = byte_writer::new(), held = interner::<string>::new(), at = vector::<u32>::new() };
}
#! Where a record is in the table, adding it where it is new.
#! @param this The table.
#! @param info The record.
#! @returns Where it is, from where the table begins.
pub def unwind_table::add(&mut this, info: &unwind_info): u32 {
val made := info.bytes();
val id := this.held.intern_view(made.view());
if id < this.at.length {
return this.at[id];
}
this.bytes.align_to(4);
val at := this.bytes.length as u32;
this.bytes.put(made.view());
this.at.append(at);
return at;
}
#! A function's code and its record of unwinding, each as an address past the
#! image's base.
struct runtime_function {
var begin: u32;
var end: u32;
var unwind: u32;
}
#! The table of each function's code and its record of unwinding, as `.pdata`
#! holds it.
pub struct function_table {
var entries: vector<runtime_function>;
}
#! Makes a table naming no functions.
#! @returns The table.
pub def function_table::new(): function_table {
return function_table { entries = vector::<runtime_function>::new() };
}
#! Names a function's code, which no other's overlaps, and its record.
#! @param this The table.
#! @param begin Where its code begins, past the image's base.
#! @param end Where it ends.
#! @param unwind Where its record is, past the image's base.
pub def function_table::add(&mut this, begin: u32, end: u32, unwind: u32): void {
this.entries.append(runtime_function { begin = begin, end = end, unwind = unwind });
}
# Whether one function's code begins before another's.
def begins_before(a: &runtime_function, b: &runtime_function): bool {
return a.begin < b.begin;
}
#! The table as `.pdata` holds it, sorted by where each function begins.
#! @param this The table.
#! @returns Its bytes.
pub def function_table::bytes(&mut this): byte_writer {
this.entries.sort_by(begins_before);
var made := byte_writer::new();
for &each in this.entries {
made.u32(each.begin);
made.u32(each.end);
made.u32(each.unwind);
}
return made;
}