xur_

> module

std::re::pe

read, edit and build Windows PE files

use std::re::pe; feature re-image in the browser

std::re::pe reads Windows PE files (.exe, .dll, .sys) and builds or edits them.

PEFile is a file as it is on disk. Its headers are fields: dos_header, coff_header, optional_header and sections. Its methods parse the tables those headers point at.

ImageDef is an image that can be changed and written back out. Make one with ImageDef::new_dll, ImageDef::open, ImageDef::parse or PEFile.to_image_def(). It has the same header fields, and its sections are SectionHeap records whose data is the section's bytes.

Flags fields (section characteristics, file and DLL characteristics) are integers. The *_names functions turn them into flag names and the matching functions turn a list of names back into an integer. The names are those of the Windows SDK without their prefix, such as "CNT_CODE", "MEM_EXECUTE" and "MEM_READ". The enums SectionFlags, FileCharacteristics and DllCharacteristics name the same values.

Backed by pewter. For a PE or ELF file read by virtual address, see AnyImage in xur.std.re(7).

> functions

# dll_characteristics(names: list<str>) -> Result<u16, str>

Combine DLL characteristic names, such as "DYNAMIC_BASE" and "NX_COMPAT", into an integer.

# dll_characteristics_names(bits: u16) -> list<str>

The names of the DLL characteristics set in bits, for example in the optional header's dll_characteristics.

# file_characteristics(names: list<str>) -> Result<u16, str>

Combine COFF file characteristic names, such as "EXECUTABLE_IMAGE" and "FILE_DLL", into an integer.

# file_characteristics_names(bits: u16) -> list<str>

The names of the COFF file characteristics set in bits, for example in coff_header.characteristics.

# section_flags(names: list<str>) -> Result<u32, str>

Combine section characteristic names, such as ["CNT_CODE",\"MEM_EXECUTE",\"MEM_READ"], into the integer for a section header. An unknown name gives Err.

# section_flags_names(bits: u32) -> list<str>

The names of the section characteristics set in bits. The ALIGN_* values share bits, so an alignment can list more than one of them.

> types

┌ struct CoffFileHeader

At the beginning of an object file, or immediately after the signature of an image file, is a standard COFF file header in the following format. Note that the Windows loader limits the number of sections to 96.

machineImageFileMachineThe number that identifies the type of target machine.
number_of_sectionsu16The number of sections. This indicates the size of the section table, which immediately follows the headers.
date_time_stampu32The low 32 bits of the number of seconds since 00:00 January 1, 1970 (a C run-time time_t value), which indicates when the file was created.
pointer_to_symbol_tableu32The file offset of the COFF symbol table, or zero if no COFF symbol table is present. This value should be zero for an image because COFF debugging information is deprecated.
number_of_symbolsu32The number of entries in the symbol table. This data can be used to locate the string table, which immediately follows the symbol table. This value should be zero for an image because COFF debugging information is deprecated.
size_of_optional_headeru16The size of the optional header, which is required for executable files but not for object files. This value should be zero for an object file. For a description of the header format, see Optional Header (Image Only).
characteristicsImageFileCharacteristicsThe flags that indicate the attributes of the file. For specific flag values, see Characteristics.
┌ struct DataDirectories

All the possable data directories.

export_tableImageDataDirectoryThe export table address and size.
import_tableImageDataDirectoryThe import table address and size.
resource_tableImageDataDirectoryThe resource table address and size.
exception_tableImageDataDirectoryThe exception table address and size.
certificate_tableImageDataDirectoryThe attribute certificate table address and size.
base_relocation_tableImageDataDirectoryThe base relocation certificate table address and size.
debugImageDataDirectoryThe debug data starting address and size.
architectureImageDataDirectoryReserved, must be 0.
global_ptrImageDataDirectoryThe RVA of the value to be stored in the global pointer register. The size member of this structure must be set to zero.
tls_tableImageDataDirectoryThe thread local storage (TLS) table address and size.
load_config_tableImageDataDirectoryThe load configuration table address and size.
bound_importImageDataDirectoryThe bound import table address and size.
itaImageDataDirectoryThe import address table address and size.
delay_import_descriptorImageDataDirectoryThe delay import descriptor address and size.
clr_runtime_headerImageDataDirectoryThe CLR runtime header address and sizeclr_runtime.
reservedImageDataDirectoryReserved, must be zero.
┌ struct DllCharacteristics

An opaque value; see the functions that return it.

┌ struct ExportAddress

Each entry in the export address table is a field that uses one of two formats in the following table. If the address specified is not within the export section (as defined by the address and length that are indicated in the optional header), the field is an export RVA, which is an actual address in code or data. Otherwise, the field is a forwarder RVA, which names a symbol in another DLL.

0u32
┌ struct ExportDirectory

The export symbol information begins with the export directory table, which describes the remainder of the export symbol information. The export directory table contains address information that is used to resolve imports to the entry points within this image.

export_flagsu32Reserved, must be 0.
time_date_stampu32The time and date that the export data was created.
major_versionu16The major version number. The major and minor version numbers can be set by the user.
minor_versionu16The minor version number.
name_rvau32The address of the ASCII string that contains the name of the DLL. This address is relative to the image base.
ordinal_baseu32The starting ordinal number for exports in this image. This field specifies the starting ordinal number for the export address table. It is usually set to 1.
address_table_entriesu32The number of entries in the export address table.
number_of_name_pointersu32The number of entries in the name pointer table. This is also the number of entries in the ordinal table.
export_address_tableu32The address of the export address table, relative to the image base.
name_pointer_rvau32The address of the export name pointer table, relative to the image base. The table size is given by the Number of Name Pointers field.
ordinal_table_rvau32The address of the ordinal table, relative to the image base.
┌ struct ExportNamePointer

Pointer into the export name table. An export name is defined only if the export name pointer table contains a pointer to it.

0u32
┌ struct ExportOrtinal

Index into the export address table. Ordinals are biased by the Ordinal Base field of the export directory table. In other words, the ordinal base must be subtracted from the ordinals to obtain true indexes into the export address table.

0u16
┌ struct ExportTableDataDirectory
export_directory_tableExportDirectoryThe export directory table contains address information that is used to resolve imports to the entry points within this image.
export_address_tableTableThe export address table contains the address of exported entry points and exported data and absolutes. An ordinal number is used as an index into the export address table.
name_pointer_tableTableThe export name pointer table is an array of addresses (RVAs) into the export name table. The pointers are 32 bits each and are relative to the image base. The pointers are ordered lexically to allow binary searches.
export_ordinal_tableTableAn array of the ordinals that correspond to members of the name pointer table. The correspondence is by position; therefore, the name pointer table and the ordinal table must have the same number of members. Each ordinal is an index into the export address table.
export_name_tableTable
dll_namestrThe name of the DLL, from [`ExportDirectory::name_rva`].
┌ struct FileBytes
┌ struct FileCharacteristics

An opaque value; see the functions that return it.

┌ struct ImageDataDirectory

Each data directory gives the address and size of a table or string that Windows uses. These data directory entries are all loaded into memory so that the system can use them at run time. A data directory is an 8-byte field that has the following declaration:

virtual_addressu32The RVA of the table. The RVA is the address of the table relative to the base address of the image when the table is loaded.
sizeu32Size in bytes.
┌ struct ImageDef

An owned, editable PE image that can be written back to bytes.

dos_headerImageDosHeader
dos_stubbytesBytes between the DOS header and the PE signature.
coff_headerCoffFileHeader
optional_headerOptionalHeader
sectionsSectionDefinitions
overlaybytesData after the last section (e.g. the certificate table).
overlay_offsetusize
first_raw_offsetusize
createdbool
# ImageDef::new_dll(machine: ImageFileMachine) -> ImageDef

A new, empty DLL for machine: PE32+ for a 64-bit machine, PE32 otherwise.

# ImageDef::open(path: str) -> Result<ImageDef, str>

Read the PE file at path as an editable image.

# ImageDef::parse(data: bytes) -> Result<ImageDef, str>

Parse a PE file held in memory as an editable image.

# image_def.add_exports(dll_name: str, exports: list<(str, u32)>) -> Result<u32, str>

Build an export table naming the DLL dll_name in a new .edata section, exporting each (name,\rva) pair with ordinals from 1. Returns the table's RVA.

# image_def.add_imports(dll_name: str, symbols: list<str>) -> Result<u32, str>

Build an import table in a new .idata section that imports symbols by name from dll_name, so the loader loads that DLL too. Returns the table's RVA.

# image_def.add_section(name: str, flags: u32, data: bytes) -> u32

Append a section after the last one and return its RVA. flags are its characteristics; see section_flags().

# image_def.entry_point() -> u32

The entry point's RVA, from the optional header.

# image_def.exports() -> Result<Option<ExportTableDataDirectory>, str>

The export table, or None if the image has none.

# image_def.image_base() -> u64

The preferred load address, from the optional header.

# image_def.read_at_rva(rva: u32, len: usize) -> Option<bytes>

len bytes at relative virtual address rva, or None if they aren't all inside one section's data.

# image_def.section(name: str) -> Option<SectionHeap>

The section named name.

# image_def.set_entry_point(rva: u32)

Set the entry point's RVA.

# image_def.strip_certificate()

Remove the certificate table. Any edit invalidates the signature anyway.

# image_def.write() -> Result<bytes, str>

Serialize the image, recomputing header sizes, section offsets and the checksum.

# image_def.write_at_rva(rva: u32, data: bytes) -> Result<(), str>

Overwrite the bytes at rva with data. They must fit inside the data of the section holding rva.

┌ struct ImageDosHeader

This is the structure at the beginning of every PE file. It mainaly contains legacy MS-DOS header that are not relivant to modern windows. The field of importants is `e_lfanew`, witch points to the new windows header.

e_magicu16Magic number
e_cblpu16Bytes on last page of file
e_cpu16Pages in file
e_crlcu16Relocations
e_cparhdru16Size of header in paragraphs needed
e_minallocu16Minimum extra paragraphs needed
e_maxallocu16Maximum extra paragraphs needed
e_ssu16Initial (relative) SS value
e_spu16Initial SP value
e_csumu16Checksum
e_ipu16Initial IP value
e_csu16Initial (relative) CS value
e_lfarlcu16File address of relocation table
e_ovnou16Overlay number
e_reslist<u16>Reserved words
e_oemidu16OEM identifier (for e_oeminfo)
e_oeminfou16OEM information; e_oemid specific
e_res2list<u16>Reserved words
e_lfanewu32File address of new exe header
┌ enum ImageFileMachine
ImageFileMachine::UnknownThe content of this field is assumed to be applicable to any machine type
ImageFileMachine::AlphaAlpha AXP, 32-bit address space
ImageFileMachine::Alpha64Alpha 64, 64-bit address space
ImageFileMachine::Am33Matsushita AM33
ImageFileMachine::Amd64x64
ImageFileMachine::ArmARM little endian
ImageFileMachine::Arm64ARM64 little endian
ImageFileMachine::ArmNTARM Thumb-2 little endian
ImageFileMachine::EbcEFI byte code
ImageFileMachine::I386Intel 386 or later processors and compatible processors
ImageFileMachine::IA64Intel Itanium processor family
ImageFileMachine::LoongArchH32LoongArch 32-bit processor family
ImageFileMachine::LoongArch64LoongArch 64-bit processor family
ImageFileMachine::M32RMitsubishi M32R little endian
ImageFileMachine::Mips16MIPS16
ImageFileMachine::MipsFPUMIPS with FPU
ImageFileMachine::MipsFPU16MIPS16 with FPU
ImageFileMachine::PowerPCPower PC little endian
ImageFileMachine::PowerPCFPPower PC with floating point support
ImageFileMachine::R4000MIPS little endian
ImageFileMachine::RiscV32RISC-V 32-bit address space
ImageFileMachine::RiscV64RISC-V 64-bit address space
ImageFileMachine::RiscV128RISC-V 128-bit address space
ImageFileMachine::Sh3Hitachi SH3
ImageFileMachine::Sh4Hitachi SH4
ImageFileMachine::Sh5Hitachi Sh5
ImageFileMachine::ThumbThumb
ImageFileMachine::WceMipsV2MIPS little-endian WCE v2
ImageFileMachine::Other(u16)Other machine type
┌ struct ImportDirectoryTable
import_lookup_table_rvau32The RVA of the import lookup table. This table contains a name or ordinal for each import. (The name "Characteristics" is used in Winnt.h, but no longer describes this field.)
time_date_stampu32The stamp that is set to zero until the image is bound. After the image is bound, this field is set to the time/data stamp of the DLL.
fowarder_chainu32The index of the first forwarder reference.
name_rvau32The address of an ASCII string that contains the name of the DLL. This address is relative to the image base.
import_address_table_rvau32The RVA of the import address table. The contents of this table are identical to the contents of the import lookup table until the image is bound.
┌ struct ImportTableDataDirectory

The import directory table contains address information that is used to resolve fixup references to the entry points within a DLL image. The import directory table consists of an array of import directory entries, one entry for each DLL to which the image refers. The last directory entry is empty (filled with null values), which indicates the end of the directory table.

entriesTableThe import directory table contains address information that is used to resolve fixup references to the entry points within a DLL image. The import directory table consists of an array of import directory entries, one entry for each DLL to which the image refers. The last directory entry is empty (filled with null values), which indicates the end of the directory table.
┌ struct ImportTableDataDirectoryEntry

This is not how data is atcualy structered in the PE file. This groups the `import_directory_table` and `import_lookup_table` to the imoported dll.

import_directory_tableImportDirectoryTableThe import directory table consists of an array of import directory entries, one entry for each DLL to which the image refers.
dll_namestrfrom [`ImportDirectoryTable::name_rva`]
import_lookup_tableTableAn import lookup table is an array of 32-bit numbers for PE32 or an array of 64-bit numbers for PE32+. Each entry uses the bit-field format that is described in the following table. In this format, bit 31 is the most significant bit for PE32 and bit 63 is the most significant bit for PE32+. The collection of these entries describes all imports from a given DLL. The last entry is set to zero (NULL) to indicate the end of the table.
┌ enum ImportTableRow
ImportTableRow::Ordinal(u16)If this bit is set, import by ordinal. Otherwise, import by name. Bit is masked as 0x80000000 for PE32, 0x8000000000000000 for PE32+.
ImportTableRow::HintName(hint:u16,name_rva:u32,name:str)
┌ struct OptionalHeader

Every image file has an optional header that provides information to the loader. This header is optional in the sense that some files (specifically, object files) do not have it. For image files, this header is required. An object file can have an optional header, but generally this header has no function in an object file except to increase its size.

standard_fieldsOptionalHeaderStandardFieldsThe first eight fields of the optional header are standard fields that are defined for every implementation of COFF. These fields contain general information that is useful for loading and running an executable file. They are unchanged for the PE32+ format.
windows_specific_fieldsOptionalHeaderWindowsSpecificThe next 21 fields are an extension to the COFF optional header format. They contain additional information that is required by the linker and loader in Windows.
data_directoriesDataDirectoriesData directories in current PE32/PE32+ file. Each field in the [`DataDirectories`] struct wil be read/written sequentially up to [OptionalHeaderWindowsSpecific::number_of_rva_and_sizes](OptionalHeaderWindowsSpecific::number_of_rva_and_sizes).
┌ enum OptionalHeaderMagic

The optional header magic number determines whether an image is a PE32 or PE32+ executable. The most common number is 0x10B, which identifies it as a normal executable file. 0x107 identifies it as a ROM image, and 0x20B identifies it as a PE32+ executable.

OptionalHeaderMagic::PE32
OptionalHeaderMagic::PE32Plus
┌ struct OptionalHeaderStandardFields
magicOptionalHeaderMagicThe unsigned integer that identifies the state of the image file.
major_linker_versionu8The linker major version number.
minor_linker_versionu8The linker minor version number.
size_of_codeu32The size of the code (text) section, or the sum of all code sections if there are multiple sections.
size_of_initilized_datau32The size of the initialized data section, or the sum of all such sections if there are multiple data sections.
size_of_unitilized_datau32The size of the uninitialized data section (BSS), or the sum of all such sections if there are multiple BSS sections.
address_of_entry_pointu32The address of the entry point relative to the image base when the executable file is loaded into memory. For program images, this is the starting address. For device drivers, this is the address of the initialization function. An entry point is optional for DLLs. When no entry point is present, this field must be zero.
base_of_codeu32The address that is relative to the image base of the beginning-of-code section when it is loaded into memory.
base_of_dataOption<u32>PE32 contains this additional field, which is absent in PE32+, following BaseOfCode. The address that is relative to the image base of the beginning-of-data section when it is loaded into memory.
┌ enum OptionalHeaderWindowsSpecific

Holds the Optional Header Windows Specific fields for either PE32 or PE32+.

OptionalHeaderWindowsSpecific::PE32(OptionalHeaderWindowsSpecificFields)
OptionalHeaderWindowsSpecific::PE32Plus(OptionalHeaderWindowsSpecificFields)
┌ type OptionalHeaderWindowsSpecificFields32

These 21 fields are an extension to the COFF optional header format. They contain additional information that is required by the linker and loader in Windows.

┌ type OptionalHeaderWindowsSpecificFields64

These 21 fields are an extension to the COFF optional header format. They contain additional information that is required by the linker and loader in Windows.

┌ struct PEFile
dos_headerImageDosHeader
coff_headerCoffFileHeader
optional_headerOption<OptionalHeader>
sectionsSections
file_bytesFileBytes
# PEFile::open(path: str) -> Result<PEFile, str>

Read and parse the PE file at path.

# PEFile::parse(data: bytes) -> Result<PEFile, str>

Parse a PE file held in memory.

# p_e_file.certificates() -> Result<Option<CertificateDataDirectory>, str>

The Authenticode certificate table, or None if the file isn't signed.

# p_e_file.clr_header() -> Result<Option<ImageCor20Header>, str>

The CLR runtime header of a .NET assembly, or None for a native file.

# p_e_file.exceptions() -> Result<Option<ExceptionHandlerDataDirectory>, str>

The exception table (.pdata function entries), or None if the file has none.

# p_e_file.exports() -> Result<Option<ExportTableDataDirectory>, str>

The export table, or None if the file has none.

# p_e_file.imports() -> Result<Option<ImportTableDataDirectory>, str>

The import table, or None if the file has none.

# p_e_file.relocations() -> Result<Option<BaseRelocationDataDitectory>, str>

The base relocation table, or None if the file has none.

# p_e_file.resources() -> Result<Option<ResourceDataDirectory>, str>

The resource directory tree, or None if the file has none.

# p_e_file.section(name: str) -> Option<SectionRow>

The section named name, with its header and raw data.

# p_e_file.section_names() -> list<str>

The section names, in table order, such as ".text", without the padding of the 8-byte name field.

# p_e_file.to_image_def() -> ImageDef

An editable copy of the file.

┌ struct SectionDefinitions

Sections ordered by virtual address.

0list<SectionHeap>
┌ struct SectionFlags

An opaque value; see the functions that return it.

┌ struct SectionHeap
namestrNames longer than 8 bytes are truncated.
virtual_addressu32
virtual_sizeu32Leave as zero to use the data length.
characteristicsSectionFlags
databytes
┌ struct SectionRow
┌ struct SectionTableRow
namebytesAn 8-byte, null-padded UTF-8 encoded string. If the string is exactly 8 characters long, there is no terminating null. For longer names, this field contains a slash (/) that is followed by an ASCII representation of a decimal number that is an offset into the string table. Executable images do not use a string table and do not support section names longer than 8 characters. Long names in object files are truncated if they are emitted to an executable file.
virtual_sizeu32The total size of the section when loaded into memory. If this value is greater than SizeOfRawData, the section is zero-padded. This field is valid only for executable images and should be set to zero for object files.
virtual_addressu32For executable images, the address of the first byte of the section relative to the image base when the section is loaded into memory. For object files, this field is the address of the first byte before relocation is applied; for simplicity, compilers should set this to zero. Otherwise, it is an arbitrary value that is subtracted from offsets during relocation.
size_of_raw_datau32The size of the section (for object files) or the size of the initialized data on disk (for image files). For executable images, this must be a multiple of FileAlignment from the optional header. If this is less than VirtualSize, the remainder of the section is zero-filled. Because the SizeOfRawData field is rounded but the VirtualSize field is not, it is possible for SizeOfRawData to be greater than VirtualSize as well. When a section contains only uninitialized data, this field should be zero.
pointer_to_raw_datau32The file pointer to the first page of the section within the COFF file. For executable images, this must be a multiple of FileAlignment from the optional header. For object files, the value should be aligned on a 4-byte boundary for best performance. When a section contains only uninitialized data, this field should be zero.
pointer_to_relocationsu32The file pointer to the beginning of relocation entries for the section. This is set to zero for executable images or if there are no relocations.
pointer_to_line_numbersu32The file pointer to the beginning of line-number entries for the section. This is set to zero if there are no COFF line numbers. This value should be zero for an image because COFF debugging information is deprecated.
number_of_relocaionsu16The number of relocation entries for the section. This is set to zero for executable images.
number_of_line_numbersu16The number of line-number entries for the section. This value should be zero for an image because COFF debugging information is deprecated.
characteristicsSectionFlagsThe flags that describe the characteristics of the section.
┌ struct Sections

Sections with their ccorrisponding data

0Table

> examples

use std::io;
use std::re::pe;

fn main() -> Result<(), str> {
    let file = pe::PEFile::open("C:/Windows/System32/kernel32.dll")?;
    for name in file.section_names() {
        let section = file.section(name).unwrap();
        let flags = pe::section_flags_names(section.row.characteristics);
        io::println("{} {}", name, flags.join("|"));
    }
    Ok(())
}
use std::fs;
use std::re::pe;

fn main() -> Result<(), str> {
    let image = pe::ImageDef::open("game.dll")?;
    let flags = pe::section_flags(["CNT_CODE", "MEM_EXECUTE", "MEM_READ"])?;
    let rva = image.add_section(".hook", flags, b"\\xc3");
    image.strip_certificate();
    fs::write_bytes("game_patched.dll", image.write()?);
    Ok(())
}