binary
The libraries Sakura writes executables with: the instructions of a machine,
the files an operating system loads, and the debugging information debuggers
read. Each is a library of its own, reading only std:
| Library | Writes | Folder |
|---|---|---|
binary::amd64 |
AMD64's instructions, x86-64's | amd64/ |
binary::elf |
ELF files, Linux's executables | elf/ |
binary::dwarf |
DWARF 5, Linux's debugging information | dwarf/ |
binary::pe |
PE files, Windows' executables | pe/ |
binary::pdb |
PDB files, Windows' debugging information | pdb/ |
The Sakura compiler writes its Linux executables with amd64, elf, and
dwarf, and its Windows executables with amd64, pe, and pdb.
Using it
Require the repository once in your blossomfile, and name among a target's
deps only the libraries it reads:
requires:
- https://git.malunal.studio/sakura/std@v1.0.0
- https://git.malunal.studio/sakura/binary@v1.0.0
targets:
- name: app
type: program
deps: [binary.amd64, binary.elf, std.io]
Each is imported by its own name, as import binary::elf;, and written by its
last, as elf::image.
binary::amd64
Encodes AMD64's instructions. assembly writes each instruction's bytes one
after another, as an assembler does, and aims the jumps and calls it writes
once their targets are known.
import binary::amd64;
# A function returning 42 where its argument in `rdi` is zero, else 7.
def answer(): assembly {
var code := assembly::new();
code.push(reg::rbp);
code.mov(reg::rbp, reg::rsp);
code.mov_imm(reg::rax, 7);
code.test(reg::rdi, reg::rdi);
val skip := code.jcc(cc::not_equal);
code.mov_imm(reg::rax, 42);
code.land(skip);
code.leave();
code.ret();
return code; # Its bytes are `code.bytes`.
}
- Registers and operations, numbered as the hardware numbers them:
reg(raxtor15), the conditionscc, two-operand arithmeticalu,shift,unary, and scalar SSE arithmeticsse. SSE registers are numbers of their own,xmm1being 1. - Operands in memory:
at(base, disp),indexed(base, index, scale, disp),absolute(address), and, throughgs,own(offset)andown_at(base). assembly: moves, loads, and stores of each width; arithmetic, comparisons, shifts, multiplication, and division; atomics (lock,xchg,lock_xadd,lock_cmpxchg,mfence); calls and jumps through registers and memory; string instructions; SSE's scalar instructions; and vector instructions, each a word naming its opcode, map, and prefix (vec_paddband the rest), written with SSE's encodings or, whereavxis set, VEX's.- Jumps and calls:
jmp,jcc, andcallgive where their displacement is;landaims one at the code written next andpatchat any offset.fixup_listkeeps the displacements of calls to code placed later.
std::io declares an absolute too, so a file importing both writes
amd64::absolute.
binary::elf
Writes ELF files: an executable of segments loaded at fixed addresses, x86-64's
unless another machine is given, each described by a section of its name, with
its functions named in a symbol table so debuggers and disassemblers show them,
sections it holds but doesn't load, as notes and debugging information, and the
note naming its build. It also writes the file of an executable's debugging
information, which describes the executable's segments without holding them,
and gives the checksum a .gnu_debuglink names that file with.
import std::io;
import binary::elf;
# An executable of the code given, loaded with the file's headers at 4 MiB.
def executable(code: span<u8>): byte_writer {
val headers := elf::headers_size(1, false);
var image := elf::image::new(0x400000 + headers);
image.segment(".text", 0x400000, 0, code, code.length, elf::readable | elf::executable, true);
image.symbols.append(elf::symbol { name = "_start", address = 0x400000 + headers, size = code.length });
image.build_id();
return image.file();
}
image: its entry,machine(62, x86-64, unless given),segments,symbols, thesectionsit holds but doesn't load, and, where it is dynamically linked (linked), where the loader's records are (linking).segmentadds a segment,build_idadds the note naming the build by hashes of what it loads, andfilegives the file's bytes. An image that isdescribedonly describes its segments, as a file of debugging information does, holding none of them.segment: a name, an address, its offset in the file, its bytes, and its permissions,readable,writable, andexecutable. The first may begin with the file's headers,headers_sizeof them.section: a name, its kind (section_kind::progbits,note, ornobits), its bytes, alignment, flags (merge,strings), and the bytes of each entry where it holds entries of a size.crc32: the checksum.gnu_debuglinknames a file with, as zlib computes it.
binary::dwarf
Writes DWARF 5. It holds DWARF's numbers, as its standard names them, and the encodings its sections are made of: numbers in bytes of seven bits, abbreviations, tables of strings, the headers of units and of lists, line programs and the table naming their files, and the descriptions of how frames unwind. What a compiler says of its program, its types, functions, and variables, is its own.
import std::io;
import binary::dwarf;
# A line program of one function's code at an address, its prologue three
# bytes, and the table naming its file.
def lines(address: u64, size: u64): byte_writer {
var program := dwarf::line_program::new();
program.begin(address);
program.row(0, 1, 2, 1, false);
program.row(3, 1, 3, 5, true);
program.end(size);
var strings := dwarf::string_table::new();
var table := byte_writer::new();
val paths: strview[1] = ["main.sakura"];
dwarf::write_line_table(&mut table, "/src", paths[:], &mut strings, program.bytes.view());
return table; # `.debug_line`, whose names are `strings.bytes`, `.debug_line_str`.
}
- Numbers: the tags of entries (
dw_tag_*), their attributes (dw_at_*) and forms (dw_form_*), the encodings of base types (dw_ate_*), the operations of expressions (dw_op_*), the entries of lists (dw_lle_*,dw_rle_*), the instructions of frames (dw_cfa_*) and of line programs (dw_lns_*,dw_lne_*), and x86-64's registers as its System V ABI numbers them (amd64_registers,amd64_xmm0,amd64_rbp,amd64_rsp,amd64_return_address). - Encodings:
ulebandsleb;abbreviation;string_table, each string once, by its offset;begin_unitandbegin_lists, whose lengthsbyte_writer::end_lengthwrites. - Lines:
line_program, a sequence at a time, its rows written as the changes from one to the next, andwrite_line_table, its header naming the directories and files. - Frames:
begin_cie,begin_fde, andend_entry, and the instructions:cfa_advance,cfa_def_cfa,cfa_def_cfa_offset,cfa_def_cfa_register,cfa_offset,cfa_same_value,cfa_remember_state, andcfa_restore_state.
binary::pe
Writes PE files: an x86-64 executable run in a console unless another subsystem is given, loaded at the address it was built for with nothing to relocate, its sections each a page past the last, the tables the loader and debuggers read named by the data directories, and its functions named in a COFF symbol table. It also writes how each function unwinds, which Windows reads to unwind a thread's stack, and the debug directory naming a PDB file, stamped with that file's GUID once it is written.
import std::io;
import binary::pe;
# An executable of the code given at 4 MiB plus a page, which pushes `rbp` and
# points it at its frame, so it unwinds through `rbp` however its stack moves.
def executable(code: span<u8>): byte_writer {
var image := pe::image::new(0x400000, 0x401000);
image.stack_reserve = 0x100000;
image.stack_commit = 0x1000;
image.section(".text", 0x401000, code, code.length, pe::readable | pe::executable);
var info := pe::unwind_info::new();
info.pushed(1, 5); # push rbp
info.framed(4, 5, 0); # mov rbp, rsp
var records := pe::unwind_table::new();
val record := records.add(&info);
image.section(".xdata", 0x402000, records.bytes.view(), records.bytes.length, pe::readable);
var functions := pe::function_table::new();
functions.add(0x1000, (0x1000 + code.length) as u32, 0x2000 + record);
val table := functions.bytes();
image.section(".pdata", 0x403000, table.view(), table.length, pe::readable);
image.exceptions = pe::directory { address = 0x403000, size = table.length };
return image.file();
}
image: its base and entry,subsystem(3, a console, unless given), the bytes of the first thread's stack, itssections, itssymbols, and the data directories the loader and debuggers read:imports,exceptions,debug, andiat.sectionadds a section andfilegives the file's bytes. A section holding nothing is left out, and one whose name is longer than eight bytes is named in the table of strings.section: a name, an address, its bytes, and its permissions:readable,writable,executable, anddiscardable, as debugging information is.- Unwinding:
unwind_infolists what a prologue did, each at the offset past its instruction:pushed,allocated,framed, andsaved, written the latest first, as Windows reads them.unwind_tableholds the records, each once, as.xdatadoes, andfunction_tableeach function's code and record, sorted, as.pdatadoes. - The PDB file:
debug_entryadds an entry to the debug directory, whose place in the fileimage::filewrites, andcodeview_recordthe record naming the file,RSDS. Once the PDB file is written,stamp_codeviewwrites its GUID into the executable's file, andsection_headersgives the headers a PDB file keeps.
binary::pdb
Writes PDB files as Microsoft's linker writes them for an executable of x86-64: CodeView's types and symbols, each module's lines and the functions inlined into its code, the globals and publics a debugger finds a name by, all held in an MSF file's streams. The file is named by a GUID made from what it holds, so the same build writes the same file.
import std::io;
import binary::pdb;
# A PDB file naming one function, `main`, 16 bytes of code at the start of the
# image's second section, whose headers are given, from line 3 of its file.
def describe(sections: span<u8>): pdb::writer {
var file := pdb::writer::new();
file.sections.put(sections);
val arguments := file.types.arguments(span::<u32>::empty());
val procedure := file.types.procedure(pdb::t_void, arguments, 0);
var symbols := pdb::symbol_stream::new();
symbols.object_name("main.obj");
val at := symbols.procedure(true, "main", procedure, 2, 0, 16, 4, 15, pdb::proc_has_frame_pointer);
symbols.end();
var checksums := pdb::file_checksums::new();
val source := checksums.file(file.names.offset_of("/src/main.c"));
var lines := pdb::function_lines::new(2, 0, 16);
lines.line(source, 0, 3, 1);
lines.finish();
var subsections := byte_writer::new();
pdb::subsection(&mut subsections, pdb::debug_s_lines, lines.bytes.view());
pdb::subsection(&mut subsections, pdb::debug_s_file_checksums, checksums.bytes.view());
val files: strview[1] = ["/src/main.c"];
val ours := file.add_module("main.obj", "main.obj", &mut symbols.bytes, &mut subsections, files[:]);
file.contribute(ours, 2, 0, 16, 0x60000020);
file.public("main", 2, 0, pdb::public_function | pdb::public_code);
file.procedure("main", ours, at, true);
return file; # `file.file()` gives its bytes, then `file.guid` names it.
}
The executable names the file by its path, GUID, and age in its debug
directory, which binary::pe's codeview_record and stamp_codeview write.
writer: the file. Itstypesandids, each atype_table; itsnames, the table of strings lines name files in; thesectionsof the image, as their headers are; its modules (add_module), the parts of sections each is (contribute), its publics (public), and its globals naming procedures (procedure).filelays the streams out in an MSF file and names it by the MD5 of what it holds, whichguidandsignaturethen give.- Types:
type_tableholds records, each once but functions' IDs, hashed as Microsoft's tools hash them, so a struct's declaration is found to its definition:pointer,array,arguments,procedure,structure,union_of,enumeration,fieldsof afield_list(going on in another record where one can't hold it), andfunction_id. The simple types aret_void,t_int4, and the rest, andt_64pmakes a pointer of one. - Symbols:
symbol_streamwrites a module's symbols: its name and compiler, procedures, their frames, blocks, inline sites, and locals with where each is over which code:in_register,in_frame,in_frame_throughout,part_in_register, andthrough_register. A scope's record names where it ends onceendends it. - Lines:
file_checksums,function_lines, andinlinee_lines, each the contents of a subsectionsubsectionwrites, andannotations, the parts of a procedure's code an inline site is and the line of each. - Numbers: the kinds of records and symbols (
lf_*,s_*), and x86-64's registers as CodeView numbers them (amd64_register,amd64_xmm).
Writing the file
Each library gives bytes and leaves writing them to a file to you, as a compiler writing over an executable that is running has its own way to.
Testing
From the repository's root, with blossom test, which runs each library's
tests as a program of its own, or one library's, as amd64's:
sakurac run --lib binary::amd64=amd64 tests/main.sakura tests/amd64/*.sakura
amd64: each instruction's expected bytes were written by GNU as from the Intel syntax beside it.pdb: the files the Sakura compiler writes with it were checked with LLVM'sllvm-pdbutil, which reads every stream of them, andllvm-symbolizer, whose functions, files, lines, and inlined frames from the PDB file match those from the executable's DWARF.
Adding a library
An architecture or a format, as aarch64 or Mach-O, is a folder of its own
beside the others, with:
- its files, each
module binary::<name>;; - a target in the blossomfile,
binary.<name>, whoserootis its folder; - its tests in
tests/<name>/, run as a test of their own withtests/main.sakura; - a line among the blossomfile's
exports, and a row in the table above.
License
MIT. See LICENSE.