Initial Commit
This commit is contained in:
33 files changed
+7510
No files matched your search
@@ -0,0 +1,330 @@
|
||||
# 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`](#binaryamd64) | AMD64's instructions, x86-64's | `amd64/` |
|
||||
| [`binary::elf`](#binaryelf) | ELF files, Linux's executables | `elf/` |
|
||||
| [`binary::dwarf`](#binarydwarf) | DWARF 5, Linux's debugging information | `dwarf/` |
|
||||
| [`binary::pe`](#binarype) | PE files, Windows' executables | `pe/` |
|
||||
| [`binary::pdb`](#binarypdb) | 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:
|
||||
|
||||
```yaml
|
||||
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.
|
||||
|
||||
```sakura
|
||||
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`
|
||||
(`rax` to `r15`), the conditions `cc`, two-operand arithmetic `alu`, `shift`,
|
||||
`unary`, and scalar SSE arithmetic `sse`. SSE registers are numbers of their
|
||||
own, `xmm1` being 1.
|
||||
- **Operands in memory**: `at(base, disp)`, `indexed(base, index, scale,
|
||||
disp)`, `absolute(address)`, and, through `gs`, `own(offset)` and
|
||||
`own_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_paddb` and
|
||||
the rest), written with SSE's encodings or, where `avx` is set, VEX's.
|
||||
- **Jumps and calls**: `jmp`, `jcc`, and `call` give where their displacement
|
||||
is; `land` aims one at the code written next and `patch` at any offset.
|
||||
`fixup_list` keeps 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.
|
||||
|
||||
```sakura
|
||||
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`, the `sections` it holds but doesn't load, and, where it is
|
||||
dynamically linked (`linked`), where the loader's records are (`linking`).
|
||||
`segment` adds a segment, `build_id` adds the note naming the build by hashes
|
||||
of what it loads, and `file` gives the file's bytes. An image that is
|
||||
`described` only 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`, and `executable`. The first may begin with
|
||||
the file's headers, `headers_size` of them.
|
||||
- **`section`**: a name, its kind (`section_kind::progbits`, `note`, or
|
||||
`nobits`), its bytes, alignment, flags (`merge`, `strings`), and the bytes of
|
||||
each entry where it holds entries of a size.
|
||||
- **`crc32`**: the checksum `.gnu_debuglink` names 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.
|
||||
|
||||
```sakura
|
||||
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.span);
|
||||
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**: `uleb` and `sleb`; `abbreviation`; `string_table`, each string
|
||||
once, by its offset; `begin_unit` and `begin_lists`, whose lengths
|
||||
`byte_writer::end_length` writes.
|
||||
- **Lines**: `line_program`, a sequence at a time, its rows written as the
|
||||
changes from one to the next, and `write_line_table`, its header naming the
|
||||
directories and files.
|
||||
- **Frames**: `begin_cie`, `begin_fde`, and `end_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`, and
|
||||
`cfa_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.
|
||||
|
||||
```sakura
|
||||
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.span, 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.span, 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, its `sections`, its `symbols`, and the
|
||||
data directories the loader and debuggers read: `imports`, `exceptions`,
|
||||
`debug`, and `iat`. `section` adds a section and `file` gives 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`, and `discardable`, as debugging
|
||||
information is.
|
||||
- **Unwinding**: `unwind_info` lists what a prologue did, each at the offset
|
||||
past its instruction: `pushed`, `allocated`, `framed`, and `saved`, written
|
||||
the latest first, as Windows reads them. `unwind_table` holds the records,
|
||||
each once, as `.xdata` does, and `function_table` each function's code and
|
||||
record, sorted, as `.pdata` does.
|
||||
- **The PDB file**: `debug_entry` adds an entry to the debug directory, whose
|
||||
place in the file `image::file` writes, and `codeview_record` the record
|
||||
naming the file, `RSDS`. Once the PDB file is written, `stamp_codeview`
|
||||
writes its GUID into the executable's file, and `section_headers` gives 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.
|
||||
|
||||
```sakura
|
||||
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>::blank());
|
||||
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.span);
|
||||
pdb::subsection(&mut subsections, pdb::debug_s_file_checksums, checksums.bytes.span);
|
||||
|
||||
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. Its `types` and `ids`, each a `type_table`; its
|
||||
`names`, the table of strings lines name files in; the `sections` of 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`). `file` lays the streams out in an MSF file
|
||||
and names it by the MD5 of what it holds, which `guid` and `signature` then
|
||||
give.
|
||||
- **Types**: `type_table` holds 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`, `fields` of a `field_list` (going on in another
|
||||
record where one can't hold it), and `function_id`. The simple types are
|
||||
`t_void`, `t_int4`, and the rest, and `t_64p` makes a pointer of one.
|
||||
- **Symbols**: `symbol_stream` writes 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`, and `through_register`. A scope's
|
||||
record names where it ends once `end` ends it.
|
||||
- **Lines**: `file_checksums`, `function_lines`, and `inlinee_lines`, each the
|
||||
contents of a subsection `subsection` writes, and `annotations`, 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:
|
||||
|
||||
```sh
|
||||
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's
|
||||
`llvm-pdbutil`, which reads every stream of them, and `llvm-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>`, whose `root` is its folder;
|
||||
- its tests in `tests/<name>/`, run as a test of their own with
|
||||
`tests/main.sakura`;
|
||||
- a line among the blossomfile's `exports`, and a row in the table above.
|
||||
|
||||
## License
|
||||
|
||||
MIT. See [LICENSE](LICENSE).
|
||||
Reference in new issue
Block a user