Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-11-10 09:45:43 -06:00
commit 8b72f6a52b
33 files changed
+7510

No files matched your search

+481
View File
@@ -0,0 +1,481 @@
#! @file elf.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the writer of ELF files: an executable of segments loaded at fixed
#! addresses, x86-64's unless another machine is given, with a section
#! describing each, the functions named in a symbol table so debuggers and
#! disassemblers show them, sections held but not loaded, as notes and
#! debugging information are, 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 link
#! to that file is written with.
import std::io;
module binary::elf;
#! The permissions of a segment.
pub const readable: u32 = 4;
pub const writable: u32 = 2;
pub const executable: u32 = 1;
# The sizes of the file header, a program header, a section header, and a
# symbol.
const header_bytes: u64 = 64;
const program_bytes: u64 = 56;
const section_bytes: u64 = 64;
const symbol_bytes: u64 = 24;
#! The types of sections: those a file holds but does not load, as notes, and
#! those a file describing an executable's segments places where they are.
pub enum section_kind : u32 {
progbits = 1, #! Bytes of the program's own meaning.
note = 7, #! Notes, as the one naming a build.
nobits = 8, #! Bytes the file does not hold.
}
#! The flags of a section of strings, each ending with a zero, which a linker
#! may merge.
pub const merge: u64 = 0x10;
pub const strings: u64 = 0x20;
#! The bytes of a note naming a build, by a hash of what it loads.
pub const build_id_bytes: u64 = 20;
#! A loaded segment, which is also described by a section of its name.
pub struct segment {
pub var name: strview; #! Of its section, as `.text`.
pub var address: u64;
pub var offset: u64; #! In the file, which is the address less a whole number of pages.
pub var data: span<u8>; #! What it holds.
pub var size: u64; #! Of what the file holds of it.
pub var flags: u32; #! As `readable`, `writable`, and `executable`.
pub var headers: bool; #! Whether it begins with the file's headers, before its data.
}
#! A function, which debuggers and disassemblers show by name.
pub struct symbol {
pub var name: strview;
pub var address: u64;
pub var size: u64;
}
#! A section the file holds but does not load, as a note.
pub struct section {
pub var name: strview;
pub var kind: section_kind;
pub var data: byte_writer;
pub var align: u64;
pub var flags: u64; #! As `merge` and `strings`.
pub var entry: u64; #! The bytes of each entry, where it holds entries of a size.
}
#! A section's header.
struct header {
var name: u64; #! Where its name begins in the table of section names.
var kind: u64;
var flags: u64;
var address: u64;
var offset: u64; #! In the file.
var size: u64;
var link: u64;
var info: u64;
var align: u64;
var entry: u64; #! The bytes of each entry, where it holds entries of a size.
}
#! What makes an executable dynamically linked: the path of the loader the
#! system runs it with, and the dynamic section telling the loader what to load
#! and where to write the addresses it finds, each at an address within its
#! first segment.
pub struct linking {
pub var interpreter: u64;
pub var interpreter_size: u64;
pub var section: u64;
pub var section_size: u64;
pub var strings: u64; #! The names the loader reads, which the symbols name into.
pub var strings_size: u64;
pub var symbols: u64;
pub var symbols_size: u64;
}
#! An executable to write.
pub struct image {
pub var entry: u64;
pub var machine: u16 = 62; #! As ELF numbers it: x86-64 unless given.
pub var segments: vector<segment>;
pub var symbols: vector<symbol>;
pub var sections: vector<section>; #! Those held but not loaded.
pub var linked: bool; #! Whether it is dynamically linked, by `dynamic`.
pub var dynamic: linking;
pub var described: bool; #! Whether the file only describes the segments, as debugging information does, holding none of them.
}
# The program headers a dynamically linked executable has beside its segments:
# those of the headers themselves, the loader, and the dynamic section.
const dynamic_headers: u64 = 3;
#! The bytes of an executable's headers, which its first segment begins with.
#! @param segments How many segments it has.
#! @param dynamic Whether it is dynamically linked.
#! @returns How many.
pub def headers_size(segments: u64, dynamic: bool): u64 {
return header_bytes + (segments + (dynamic ? dynamic_headers : 0)) * program_bytes;
}
#! Makes an executable starting at an address, with nothing in it yet.
#! @param entry The address.
#! @returns The executable.
pub def image::new(entry: u64): image {
return image {
entry = entry,
segments = vector::<segment>::new(),
symbols = vector::<symbol>::new(),
sections = vector::<section>::new(),
dynamic = linking {}
};
}
#! Adds a segment.
#! @param this The executable.
#! @param name The name of its section.
#! @param address Where it is loaded.
#! @param offset Where it is in the file.
#! @param data What it holds.
#! @param size How many bytes.
#! @param flags Its permissions.
#! @param headers Whether it begins with the file's headers.
pub def image::segment(
&mut this,
name: strview,
address: u64,
offset: u64,
data: span<u8>,
size: u64,
flags: u32,
headers: bool
): void {
this.segments.append(segment {
name = name, address = address, offset = offset, data = data, size = size, flags = flags, headers = headers
});
}
#! Adds the note naming the build by hashes of each segment's address, size,
#! and bytes, which differ wherever the code or what it loads does.
#! @param this The executable.
pub def image::build_id(&mut this): void {
val seeds: u64[3] = [14695981039346656037, 0x9E3779B97F4A7C15, 0xC2B2AE3D27D4EB4F];
# A word at a time, the last few bytes as a word of their own.
var hashes: u64[3] = seeds;
for &each in this.segments {
val words: u64[3] = [each.address, each.size, each.size];
for k in 0..3u {
for h in 0..3u {
hashes[h] = (hashes[h] ^ words[k]) * 1099511628211;
}
}
val data := each.data.data;
val whole := each.size / 8;
for i in 0..whole {
val word: u64 = *((data + 8 * i) as *u64);
hashes[0] = (hashes[0] ^ word) * 1099511628211;
hashes[1] = (hashes[1] ^ word) * 1099511628213;
hashes[2] = (hashes[2] ^ word) * 1099511628215;
}
var rest: u64 = 0;
for i in 8 * whole..each.size {
rest = rest | (data[i] as u64 << (8 * (i - 8 * whole)));
}
for h in 0..3u {
hashes[h] = (hashes[h] ^ rest) * 1099511628211;
}
}
for h in 0..3u {
hashes[h] = hashes[h] ^ (hashes[h] >> 29);
}
# The hashes are the description, its first 20 bytes.
var note := byte_writer::new();
note.u32(4); # The size of the name,
note.u32(build_id_bytes); # of the description,
note.u32(3); # and the type, a GNU build ID.
note.put_terminated("GNU");
note.u64(hashes[0]);
note.u64(hashes[1]);
note.u32(hashes[2]);
this.sections.append(section {
name = ".note.gnu.build-id", kind = section_kind::note, data = byte_writer::move_of(&mut note), align = 4, flags = 0, entry = 0
});
}
#! A place rounded up to a multiple of an alignment.
#! @param value The place.
#! @param align The alignment, a power of two.
#! @returns The place.
def aligned(value: u64, align: u64): u64 {
return (value + align - 1) & ~(align - 1);
}
#! 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);
}
}
#! Adds a name to a table of names, giving where it begins.
#! @param table The table.
#! @param name The name.
#! @returns Where.
def add_name(table: &mut byte_writer, name: strview): u64 {
val at := table.length;
table.put_terminated(name);
return at;
}
#! Adds a program header of a part of a loaded segment, at the offset in the
#! file its address is at.
#! @param this The executable.
#! @param file The file's bytes.
#! @param kind Its type.
#! @param address Where the part is loaded.
#! @param size How many bytes it takes.
#! @param headers The bytes of the file's headers.
def image::part(&this, file: &mut byte_writer, kind: u64, address: u64, size: u64, headers: u64): void {
var offset: u64 = 0;
for &each in this.segments {
val reach := each.size + (each.headers ? headers : 0);
if address >= each.address && address < each.address + reach {
offset = each.offset + (address - each.address);
}
}
put_program(file, kind, readable as u64, offset, address, size, size, 8);
}
#! Adds a program header.
#! @param file The file's bytes.
#! @param kind Its type.
#! @param flags How what it describes may be used.
#! @param offset Where what it describes is in the file.
#! @param address Where it is loaded.
#! @param stored How many bytes of it the file holds.
#! @param size How many bytes it takes once loaded.
#! @param align What its address and offset are aligned to.
def put_program(file: &mut byte_writer, kind: u64, flags: u64, offset: u64, address: u64, stored: u64, size: u64, align: u64): void {
file.u32(kind);
file.u32(flags);
file.u64(offset);
file.u64(address); # Where it is loaded, virtually,
file.u64(address); # and physically.
file.u64(stored);
file.u64(size);
file.u64(align);
}
#! Adds a section header.
#! @param file The file's bytes.
#! @param made The header.
def put_section(file: &mut byte_writer, made: header): void {
file.u32(made.name);
file.u32(made.kind);
file.u64(made.flags);
file.u64(made.address);
file.u64(made.offset);
file.u64(made.size);
file.u32(made.link);
file.u32(made.info);
file.u64(made.align);
file.u64(made.entry);
}
#! The bytes of the file of the executable, in the order the file holds them:
#! the headers, the segments, the symbols, the sections held, and the section
#! headers, which the file header says where they are once they are placed.
#! Where it only describes the segments, it places the sections describing them
#! where the executable's are, holds none of their bytes, and describes the
#! segments as the executable's headers do: debuggers match the two files by
#! them.
#! @param this The executable.
#! @returns The bytes.
pub def image::file(&this): byte_writer {
val segment_count := this.segments.length;
val described := this.described;
val headers := headers_size(segment_count, this.linked);
val linked := this.linked && !described;
val programs := segment_count + (linked ? dynamic_headers : 0);
# A dynamically linked executable's loaded parts are named too, for readelf.
val extra: u64 = linked ? 4 : 0;
val count := segment_count + extra + this.sections.length + 4;
var file := byte_writer::new();
# The file header, of an executable of its machine.
val ident: u8[8] = [0x7F, 'E' as u8, 'L' as u8, 'F' as u8, 2, 1, 1, 0];
file.put(ident[:]);
file.zeros(8);
file.u16(2);
file.u16(this.machine);
file.u32(1);
file.u64(this.entry);
file.u64(header_bytes);
val sections_at := file.length;
file.u64(0);
file.u32(0);
file.u16(header_bytes);
file.u16(program_bytes);
file.u16(programs);
file.u16(section_bytes);
file.u16(count);
file.u16(count - 1);
# The program headers. A dynamically linked executable names where its
# headers are and the loader before any segment is loaded, and its dynamic
# section after.
if linked {
this.part(&mut file, 6, this.segments[0].address + header_bytes, programs * program_bytes, headers);
this.part(&mut file, 3, this.dynamic.interpreter, this.dynamic.interpreter_size, headers);
}
for &each in this.segments {
val size := each.size + (each.headers ? headers : 0);
put_program(&mut file, 1, each.flags as u64, each.offset, each.address, described ? 0 : size, size, 0x1000);
}
if linked {
this.part(&mut file, 2, this.dynamic.section, this.dynamic.section_size, headers);
}
# The segments, in order of their offsets, the one holding the headers placing
# its data after them.
var end := file.length;
for &each in this.segments {
continue if described;
val begins := each.offset + (each.headers ? headers : 0);
pad_to(&mut file, begins);
file.put(each.data);
if begins + each.size > end {
end = begins + each.size;
}
}
# The symbol table, beginning with the null symbol, then its names.
var strings := byte_writer::new();
add_name(&mut strings, "");
val symtab := aligned(end, 8);
var text_section: u64 = 0;
for s in 0..segment_count {
if (this.segments[s].flags & executable) != 0 {
text_section = s + 1;
}
}
pad_to(&mut file, symtab);
file.zeros(symbol_bytes);
for &each in this.symbols {
file.u32(add_name(&mut strings, each.name));
file.byte(0x12); # A global function,
file.byte(0);
file.u16(text_section); # within the code.
file.u64(each.address);
file.u64(each.size);
}
val symtab_size := (this.symbols.length + 1) * symbol_bytes;
val strtab := file.length;
file.put(strings.span);
# The sections held but not loaded, each where its alignment allows.
var placed := vector::<u64>::new();
for &each in this.sections {
placed.append(file.align_to(each.align > 0 ? each.align : 1));
file.put(each.data.span);
}
# Section names, then the sections: the null one, one per segment, those
# held, and the tables.
var names := byte_writer::new();
add_name(&mut names, "");
var segment_names := vector::<u64>::new();
for &each in this.segments {
segment_names.append(add_name(&mut names, each.name));
}
val part_names: strview[4] = [".interp", ".dynstr", ".dynsym", ".dynamic"];
var extra_names := vector::<u64>::new();
for i in 0..extra {
extra_names.append(add_name(&mut names, part_names[i]));
}
var held_names := vector::<u64>::new();
for &each in this.sections {
held_names.append(add_name(&mut names, each.name));
}
val symtab_name := add_name(&mut names, ".symtab");
val strtab_name := add_name(&mut names, ".strtab");
val shstrtab_name := add_name(&mut names, ".shstrtab");
val shstrtab := file.length;
file.put(names.span);
val sections := file.align_to(8);
file.set_u64(sections_at, sections);
file.zeros(section_bytes);
for s in 0..segment_count {
val each: segment = this.segments[s];
val skip := each.headers ? headers : 0;
var flags: u64 = 2;
if (each.flags & writable) != 0 { flags = flags | 1; }
if (each.flags & executable) != 0 { flags = flags | 4; }
put_section(&mut file, header {
name = segment_names[s], kind = described ? 8 : 1, flags = flags, # NOBITS, or PROGBITS.
address = each.address + skip, offset = described ? header_bytes : each.offset + skip,
size = each.size, align = 16
});
}
for i in 0..extra {
val addresses: u64[4] = [this.dynamic.interpreter, this.dynamic.strings, this.dynamic.symbols, this.dynamic.section];
val sizes: u64[4] = [this.dynamic.interpreter_size, this.dynamic.strings_size, this.dynamic.symbols_size, this.dynamic.section_size];
val types: u64[4] = [1, 3, 11, 6];
val entries: u64[4] = [0, 0, 24, 16];
put_section(&mut file, header {
name = extra_names[i], kind = types[i], flags = 2, address = addresses[i],
offset = addresses[i] - this.segments[0].address, size = sizes[i],
link = i >= 2 ? segment_count + 2 : 0, info = i == 2 ? 1 : 0, align = 8, entry = entries[i]
});
}
for h in 0..this.sections.length {
val each: &section = &this.sections[h];
put_section(&mut file, header {
name = held_names[h], kind = each.kind as u64, flags = each.flags, offset = placed[h],
size = each.data.length, align = each.align, entry = each.entry
});
}
put_section(&mut file, header {
name = symtab_name, kind = 2, offset = symtab, size = symtab_size,
link = segment_count + extra + this.sections.length + 2, info = 1, align = 8, entry = symbol_bytes
});
put_section(&mut file, header {
name = strtab_name, kind = 3, offset = strtab, size = strings.length, align = 1
});
put_section(&mut file, header {
name = shstrtab_name, kind = 3, offset = shstrtab, size = names.length, align = 1
});
return file;
}
#! The checksum `.gnu_debuglink` gives with the name of a file of debugging
#! information: CRC-32, as zlib computes it.
#! @param bytes The file's bytes.
#! @returns The checksum.
pub def crc32(bytes: span<u8>): u32 {
var table: u32[256];
for n in 0..256u {
var c := n as u32;
for _ in 0..8u {
c = (c & 1) != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1;
}
table[n] = c;
}
var sum: u32 = 0xFFFFFFFF;
for &each in bytes {
sum = table[((sum ^ each as u32) & 0xFF) as u64] ^ (sum >> 8);
}
return sum ^ 0xFFFFFFFF;
}