#! @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, as `subsystem_windows` runs one #! in windows of its own with no console, 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 subsystems an executable runs in: in windows of its own, with no console, #! or in a console, which Windows opens for it where it's started without one. pub const subsystem_windows: u16 = 2; pub const subsystem_console: u16 = 3; #! 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; #! 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 = subsystem_console; #! 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
; #! In order of their addresses. pub var imports: directory; #! The record of each library imported, then a record of zeros. pub var resources: directory; #! The tree of its resources, as `resources::bytes` writes it. 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; #! 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::
::new(), imports = directory {}, resources = directory {}, exceptions = directory {}, debug = directory {}, iat = directory {}, symbols = vector::::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, 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::::new(); var raw := vector::::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.span); } # 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, 2 in windows. # 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[5] = [this.imports, this.resources, this.exceptions, this.debug, this.iat]; val indexes: u64[5] = [1, 2, 3, 6, 12]; for k in 0..5u { 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.span, 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.span, file.get_u32(entry + 20) as u64); file.set_u32(entry + 24, record); } } return file; }