Files
binary/pe/resources.sakura
2026-11-13 21:37:35 -06:00

597 lines
21 KiB
Plaintext

#! @file resources.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the writer of an executable's resources, what the system and its
#! shell read of a program without running it: `resources`, each resource by
#! its type, its number, and its language, as `.rsrc` holds them and the
#! resource directory names them; `icon_group`, an icon's images, of PNG files
#! or icon files, as Explorer shows the program and `LoadImageW` finds its icon
#! by the number of the group; and `version_resource`, what the file's
#! properties say of it: its name, its version, and its file's name. And
#! `find_resource`, which finds a resource in an executable's file again.
#!
#! The section is a tree: a directory of the types, each naming a directory of
#! that type's numbers, each naming a directory of its languages, each naming
#! an entry, which says where the resource's bytes are, by their address past
#! the image's base, and how many there are. Every resource is named by a
#! number, not a name.
import std::io;
module binary::pe;
#! The types of resources, as Windows numbers them.
pub const resource_icon: u32 = 3; #! One image of an icon.
pub const resource_icon_group: u32 = 14; #! An icon: its images, by their numbers.
pub const resource_version: u32 = 16; #! What the file's properties say of the program.
pub const resource_manifest: u32 = 24; #! The manifest the loader reads.
#! The language of a resource written in none.
pub const language_neutral: u32 = 0;
#! English as the United States speaks it, which version information is
#! written in.
pub const language_english: u32 = 0x409;
#! The most pixels an icon's image is wide or tall.
pub const icon_most: u32 = 256;
# The bit of a directory's entry naming another directory, rather than a
# resource's entry.
const subdirectory: u64 = 0x80000000;
# A resource, its bytes where they are among the others'.
struct resource_entry {
var kind: u32;
var id: u32;
var language: u32;
var at: u64;
var size: u64;
}
#! An executable's resources, each by its type, its number, and its language,
#! as `.rsrc` holds them.
pub struct resources {
var entries: vector<resource_entry>;
var data: byte_writer; # Each resource's bytes, each aligned to eight.
}
#! Makes resources holding none.
#! @returns The resources.
pub def resources::new(): resources {
return resources { entries = vector::<resource_entry>::new(), data = byte_writer::new() };
}
#! How many resources there are.
pub val resources::length: u64 {
get => this.entries.length;
}
#! Whether there are none, so the executable needs no section of them.
pub val resources::empty: bool {
get => this.entries.length == 0;
}
#! Adds a resource, its bytes copied, in place of one of the same type, number,
#! and language.
#! @param this The resources.
#! @param kind Its type, as `resource_icon`.
#! @param id Its number.
#! @param language Its language, as `language_neutral`.
#! @param bytes What it holds.
pub def resources::add(&mut this, kind: u32, id: u32, language: u32, bytes: span<u8>): void {
var same := this.entries.length;
for i in 0..this.entries.length {
val each := &this.entries[i];
if each.kind == kind && each.id == id && each.language == language {
same = i;
}
}
if same < this.entries.length {
this.entries.remove_at(same);
}
this.data.align_to(8);
val at := this.data.length;
this.data.put(bytes);
this.entries.append(resource_entry { kind = kind, id = id, language = language, at = at, size = bytes.length });
}
#! The number past every resource of a type's, which the next of them takes.
#! @param this The resources.
#! @param kind The type.
#! @returns The number, 1 where the type has none.
pub def resources::next_id(&this, kind: u32): u32 {
var most: u32 = 0;
for &each in this.entries {
if each.kind == kind && each.id > most {
most = each.id;
}
}
return most + 1;
}
#! Adds an icon: each of its images a resource of `resource_icon`, numbered
#! past those there are, and the group naming them, which `LoadImageW` finds the
#! icon by, and Explorer shows the program by where it is the first group.
#! @param this The resources.
#! @param group The icon's images.
#! @param id The group's number, 1 for the program's own icon.
#! @param language Its language.
pub def resources::add_icon(&mut this, group: &icon_group, id: u32, language: u32): void {
var directory := byte_writer::new();
directory.u16(0);
directory.u16(1);
directory.u16(group.images.length);
for &each in group.images {
val number := this.next_id(resource_icon);
this.add(resource_icon, number, language, span::<u8>::over(group.data.span.data + each.at, each.size));
directory.byte((each.width % 256) as u8);
directory.byte((each.height % 256) as u8);
directory.byte(each.colors);
directory.byte(0);
directory.u16(each.planes);
directory.u16(each.bits);
directory.u32(each.size);
directory.u16(number);
}
this.add(resource_icon_group, id, language, directory.span);
}
#! The resources as `.rsrc` holds them, at an address: the directory of their
#! types, then each type's directory of its numbers, then each number's of its
#! languages, each in order, then the entry of each resource, naming its bytes
#! by their address, then the bytes.
#! @param this The resources.
#! @param address Where the section is, past the image's base.
#! @returns The section's bytes, which the resource directory names whole.
pub def resources::bytes(&this, address: u64): byte_writer {
val order := this.sorted();
# Where in `order` each type's resources begin, and each number's.
var kinds := vector::<u64>::new();
var names := vector::<u64>::new();
for k in 0..order.length {
val each := &this.entries[order[k]];
if k == 0 || this.entries[order[k - 1]].kind != each.kind {
kinds.append(k);
names.append(k);
} else if this.entries[order[k - 1]].id != each.id {
names.append(k);
}
}
# Where each directory is, from where the section begins: the types', then
# each type's, then each number's, then the resources' entries.
var at := 16 + 8 * kinds.length;
var kind_at := vector::<u64>::new();
for i in 0..kinds.length {
kind_at.append(at);
at += 16 + 8 * names_within(&kinds, &names, i, order.length);
}
var name_at := vector::<u64>::new();
for j in 0..names.length {
name_at.append(at);
at += 16 + 8 * (run_end(&names, j, order.length) - names[j]);
}
val entries_at := at;
at += 16 * order.length;
val data_at := (at + 7) / 8 * 8;
var made := byte_writer::new();
directory_header(&mut made, kinds.length);
for i in 0..kinds.length {
made.u32(this.entries[order[kinds[i]]].kind);
made.u32(kind_at[i] | subdirectory);
}
for i in 0..kinds.length {
val end := run_end(&kinds, i, order.length);
directory_header(&mut made, names_within(&kinds, &names, i, order.length));
for j in 0..names.length {
continue if names[j] < kinds[i] || names[j] >= end;
made.u32(this.entries[order[names[j]]].id);
made.u32(name_at[j] | subdirectory);
}
}
for j in 0..names.length {
val end := run_end(&names, j, order.length);
directory_header(&mut made, end - names[j]);
for k in names[j]..end {
made.u32(this.entries[order[k]].language);
made.u32(entries_at + 16 * k);
}
}
for k in 0..order.length {
val each := &this.entries[order[k]];
made.u32(address + data_at + each.at);
made.u32(each.size);
made.u32(0); # Its code page,
made.u32(0); # and nothing.
}
made.zeros(data_at - made.length);
made.put(this.data.span);
return made;
}
# The places of the resources, in order of their types, then their numbers,
# then their languages.
def resources::sorted(&this): vector<u64> {
var order := vector::<u64>::new();
for k in 0..this.entries.length {
var at := order.length;
while at > 0 && comes_after(&this.entries[order[at - 1]], &this.entries[k]) {
at--;
}
order.insert_at(at, k);
}
return order;
}
# Whether a resource comes after another in the tree.
def comes_after(a: &resource_entry, b: &resource_entry): bool {
return a.kind > b.kind if a.kind != b.kind;
return a.id > b.id if a.id != b.id;
return a.language > b.language;
}
# Where a run of places ends: where the next begins, or at the end.
def run_end(starts: &vector<u64>, i: u64, count: u64): u64 {
return i + 1 < starts.length ? starts[i + 1] : count;
}
# How many numbers a type has, of those beginning within its run.
def names_within(kinds: &vector<u64>, names: &vector<u64>, i: u64, count: u64): u64 {
val end := run_end(kinds, i, count);
var found: u64 = 0;
for &each in names {
if each >= kinds[i] && each < end {
found++;
}
}
return found;
}
# A directory's header: no characteristics, time, or version, no entries named
# by text, and how many are named by numbers.
def directory_header(out: &mut byte_writer, numbered: u64): void {
out.u32(0);
out.u32(0);
out.u16(0);
out.u16(0);
out.u16(0);
out.u16(numbered);
}
# Icons.
#! What a file given as an icon is, as `icon_group::add` finds it.
pub enum icon_read: u8 {
added, #! A PNG or an icon file, whose images were added.
too_large, #! A PNG wider or taller than an icon's image may be, `icon_most`, left out.
unknown, #! Neither a PNG nor an icon file.
broken, #! A PNG cut short, or an icon file whose images aren't where it says.
}
# An image of an icon: its size, as an icon's directory says it, and where its
# bytes are among the group's.
struct icon_image {
var width: u32;
var height: u32;
var colors: u8;
var planes: u16;
var bits: u16;
var at: u64;
var size: u64;
}
#! The images of an icon, each a PNG, or a bitmap as an icon file holds one,
#! which `resources::add_icon` adds.
pub struct icon_group {
var images: vector<icon_image>;
var data: byte_writer;
}
#! Makes an icon of no images.
#! @returns The icon.
pub def icon_group::new(): icon_group {
return icon_group { images = vector::<icon_image>::new(), data = byte_writer::new() };
}
#! How many images it has.
pub val icon_group::length: u64 {
get => this.images.length;
}
#! Whether it has none.
pub val icon_group::empty: bool {
get => this.images.length == 0;
}
#! Adds the images of a file: a PNG, whole, as Windows has read an icon's
#! images since Vista, its size as its header says it; or each image of an icon
#! file, a `.ico`.
#! @param this The icon.
#! @param file The file's bytes.
#! @returns What the file was, and whether its images were added.
pub def icon_group::add(&mut this, file: span<u8>): icon_read {
if is_png(file) {
return icon_read::broken if file.length < 24 || !same_text(file, 12, "IHDR");
val width := big_word(file, 16);
val height := big_word(file, 20);
return icon_read::broken if width == 0 || height == 0;
return icon_read::too_large if width > icon_most as u64 || height > icon_most as u64;
this.add_image(width as u32, height as u32, 0, 1, 32, file);
return icon_read::added;
}
return icon_read::unknown if file.length < 6 || word_at(file, 0, 2) != 0 || word_at(file, 2, 2) != 1;
val count := word_at(file, 4, 2);
return icon_read::broken if count == 0 || file.length < 6 + 16 * count;
for k in 0..count {
val entry := 6 + 16 * k;
val size := word_at(file, entry + 8, 4);
val at := word_at(file, entry + 12, 4);
return icon_read::broken if size == 0 || at + size > file.length;
}
for k in 0..count {
val entry := 6 + 16 * k;
val width := file[entry] as u32;
val height := file[entry + 1] as u32;
val size := word_at(file, entry + 8, 4);
val at := word_at(file, entry + 12, 4);
this.add_image(
width == 0 ? icon_most : width, height == 0 ? icon_most : height, file[entry + 2],
word_at(file, entry + 4, 2) as u16, word_at(file, entry + 6, 2) as u16,
span::<u8>::over(file.data + at, size)
);
}
return icon_read::added;
}
# Adds an image, its bytes copied.
def icon_group::add_image(&mut this, width: u32, height: u32, colors: u8, planes: u16, bits: u16, bytes: span<u8>): void {
this.data.align_to(8);
val at := this.data.length;
this.data.put(bytes);
this.images.append(icon_image {
width = width, height = height, colors = colors, planes = planes, bits = bits, at = at, size = bytes.length
});
}
#! Whether a file is a PNG, by its first eight bytes.
#! @param file The file.
#! @returns Whether it is.
pub def is_png(file: span<u8>): bool {
val signature: u8[8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
return false if file.length < 8;
for k in 0..8u {
return false if file[k] != signature[k];
}
return true;
}
#! The size of a PNG, as its header says it.
#! @param file The file.
#! @returns Its width and height, or zeros where it is no PNG or is cut short.
pub def png_size(file: span<u8>): u32[2] {
var made: u32[2];
return made if !is_png(file) || file.length < 24 || !same_text(file, 12, "IHDR");
made[0] = big_word(file, 16) as u32;
made[1] = big_word(file, 20) as u32;
return made;
}
# A word of four bytes, the most significant first, as PNG writes them.
def big_word(file: span<u8>, at: u64): u64 {
return (file[at] as u64 << 24) | (file[at + 1] as u64 << 16) | (file[at + 2] as u64 << 8) | file[at + 3] as u64;
}
# Whether bytes of a file at a place are text.
def same_text(file: span<u8>, at: u64, text: strview): bool {
return false if at + text.length > file.length;
for k in 0..text.length {
return false if file[at + k] != text[k];
}
return true;
}
# What the file's properties say.
#! What the file's properties say of an executable, as `VS_VERSIONINFO` holds
#! it: its version, as four numbers, the first three of `version` and 0, marked
#! a prerelease where `version` has a `-`; then, in English, its description and
#! its product, `title`, or its file's name without its ending where there's
#! none, its version as written, where there's one, its file's name, and that
#! name without its ending, as its internal name.
#! @param title What it's called, as `Hearth`.
#! @param version Its version, as `1.2.0` or `1.2.0-alpha`, or empty.
#! @param file_name Its file's name, as `hearth.exe`.
#! @returns The resource's bytes, which `resources::add` takes as
#! `resource_version` number 1, in `language_english`.
pub def version_resource(title: strview, version: strview, file_name: strview): byte_writer {
var stem := file_name;
for k in 0..file_name.length {
if file_name[file_name.length - 1 - k] == '.' {
stem = file_name.substr(0, file_name.length - 1 - k);
break;
}
}
val named := title.length != 0 ? title : stem;
val numbers := version_numbers(version);
var made := byte_writer::new();
val root := begin_block(&mut made, "VS_VERSION_INFO", 52, false);
made.u32(0xFEEF04BD); # Its signature,
made.u32(0x00010000); # the struct's version,
made.u32((numbers[0] << 16) | numbers[1]); # the file's version,
made.u32(numbers[2] << 16);
made.u32((numbers[0] << 16) | numbers[1]); # the product's,
made.u32(numbers[2] << 16);
made.u32(0x3F); # the flags that mean anything,
made.u32(version.find("-") is some ? 2u : 0u); # a prerelease's,
made.u32(0x00040004); # for Windows NT,
made.u32(1); # a program,
made.u32(0);
made.u32(0); # and no date.
made.u32(0);
made.align_to(4);
val strings := begin_block(&mut made, "StringFileInfo", 0, true);
val table := begin_block(&mut made, "040904B0", 0, true);
string_value(&mut made, "FileDescription", named);
if version.length != 0 {
string_value(&mut made, "FileVersion", version);
}
string_value(&mut made, "InternalName", stem);
string_value(&mut made, "OriginalFilename", file_name);
string_value(&mut made, "ProductName", named);
if version.length != 0 {
string_value(&mut made, "ProductVersion", version);
}
end_block(&mut made, table);
end_block(&mut made, strings);
made.align_to(4);
val vars := begin_block(&mut made, "VarFileInfo", 0, true);
val translation := begin_block(&mut made, "Translation", 4, false);
made.u16(0x0409); # English,
made.u16(0x04B0); # in UTF-16.
end_block(&mut made, translation);
end_block(&mut made, vars);
end_block(&mut made, root);
return made;
}
# The first three numbers of a version, each at most 65535, and 0 for each it
# lacks.
def version_numbers(version: strview): u64[3] {
var made: u64[3];
var at: u64 = 0;
for part in 0..3u {
if part > 0 {
break if at >= version.length || version[at] != '.';
at++;
}
var value: u64 = 0;
while at < version.length && version[at] >= '0' as u8 && version[at] <= '9' as u8 {
value = value * 10 + (version[at] - '0' as u8) as u64;
if value > 0xFFFF {
value = 0xFFFF;
}
at++;
}
made[part] = value;
}
return made;
}
# Begins a block of version information: its length, written as it ends, the
# length of its value, whether that value is text, and its key, then zeros to
# four bytes. Gives where it begins.
def begin_block(out: &mut byte_writer, key: strview, value_length: u64, text: bool): u64 {
val at := out.length;
out.u16(0);
out.u16(value_length);
out.u16(text ? 1u : 0u);
put_utf16(out, key);
out.align_to(4);
return at;
}
# Ends a block, writing its length, which holds every block within it.
def end_block(out: &mut byte_writer, at: u64): void {
out.set_u16(at, out.length - at);
}
# A block of text, its key and its value, the value's length in characters of
# UTF-16 with its zero.
def string_value(out: &mut byte_writer, key: strview, value: strview): void {
out.align_to(4);
var units := byte_writer::new();
put_utf16(&mut units, value);
val at := begin_block(out, key, units.length / 2, true);
out.put(units.span);
end_block(out, at);
}
#! Writes text as UTF-16, the least significant byte first, as Windows holds
#! text, each character of its UTF-8, then a zero. A byte that begins no
#! character is written as U+FFFD.
#! @param out Where it's written.
#! @param text The text.
pub def put_utf16(out: &mut byte_writer, text: strview): void {
var at: u64 = 0;
while at < text.length {
val first := text[at] as u64;
var code: u64 = 0xFFFD;
var length: u64 = 1;
if first < 0x80 {
code = first;
} else if first >= 0xF0 && first < 0xF8 && at + 3 < text.length {
code = ((first & 7) << 18) | ((text[at + 1] as u64 & 0x3F) << 12) | ((text[at + 2] as u64 & 0x3F) << 6) | (text[at + 3] as u64 & 0x3F);
length = 4;
} else if first >= 0xE0 && first < 0xF0 && at + 2 < text.length {
code = ((first & 0xF) << 12) | ((text[at + 1] as u64 & 0x3F) << 6) | (text[at + 2] as u64 & 0x3F);
length = 3;
} else if first >= 0xC0 && first < 0xE0 && at + 1 < text.length {
code = ((first & 0x1F) << 6) | (text[at + 1] as u64 & 0x3F);
length = 2;
}
if code >= 0x10000 {
val past := code - 0x10000;
out.u16(0xD800 | (past >> 10));
out.u16(0xDC00 | (past & 0x3FF));
} else {
out.u16(code);
}
at += length;
}
out.u16(0);
}
# Reading.
#! Finds a resource in an executable's file: by its type and number, in the
#! first of its languages.
#! @param file The executable's file.
#! @param kind The type, as `resource_icon_group`.
#! @param id The number.
#! @returns Its bytes, within the file, or nothing where the file has none.
pub def find_resource(file: span<u8>, kind: u32, id: u32): maybe<span<u8>> {
return nothing {} if file.length < 0x40;
val pe := word_at(file, 0x3C, 4);
val directory := pe + 24 + 112 + 8 * 2;
return nothing {} if directory + 8 > file.length;
val address := word_at(file, directory, 4);
return nothing {} if address == 0;
val base := file_offset_of(file, address);
return nothing {} if base == 0;
val types := entry_named(file, base, base, kind as u64) else { return nothing {}; };
val names := entry_named(file, base, types, id as u64) else { return nothing {}; };
return nothing {} if names + 24 > file.length || word_at(file, names + 14, 2) == 0;
val entry := word_at(file, names + 20, 4);
return nothing {} if (entry & subdirectory) != 0;
val at := base + entry;
return nothing {} if at + 16 > file.length;
val data := file_offset_of(file, word_at(file, at, 4));
val size := word_at(file, at + 4, 4);
return nothing {} if data == 0 || data + size > file.length;
return span::<u8>::over(file.data + data, size);
}
# Where, in a file, the directory a directory's entry of a number names is, or
# nothing where it has no such entry.
def entry_named(file: span<u8>, base: u64, at: u64, id: u64): maybe<u64> {
return nothing {} if at + 16 > file.length;
val count := word_at(file, at + 12, 2) + word_at(file, at + 14, 2);
for k in 0..count {
val entry := at + 16 + 8 * k;
return nothing {} if entry + 8 > file.length;
continue if word_at(file, entry, 4) != id;
val offset := word_at(file, entry + 4, 4);
return nothing {} if (offset & subdirectory) == 0;
return base + (offset & ~subdirectory);
}
return nothing {};
}