> module
std::re::pe
read, edit and build Windows PE files
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
Combine DLL characteristic names, such as "DYNAMIC_BASE" and "NX_COMPAT", into an integer.
The names of the DLL characteristics set in bits, for example in the optional header's dll_characteristics.
Combine COFF file characteristic names, such as "EXECUTABLE_IMAGE" and "FILE_DLL", into an integer.
The names of the COFF file characteristics set in bits, for example in coff_header.characteristics.
Combine section characteristic names, such as ["CNT_CODE",\"MEM_EXECUTE",\"MEM_READ"], into the integer for a section header. An unknown name gives Err.
> types
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.
| machine | ImageFileMachine | The number that identifies the type of target machine. |
| number_of_sections | u16 | The number of sections. This indicates the size of the section table, which immediately follows the headers. |
| date_time_stamp | u32 | The 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_table | u32 | The 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_symbols | u32 | The 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_header | u16 | The 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). |
| characteristics | ImageFileCharacteristics | The flags that indicate the attributes of the file. For specific flag values, see Characteristics. |
All the possable data directories.
| export_table | ImageDataDirectory | The export table address and size. |
| import_table | ImageDataDirectory | The import table address and size. |
| resource_table | ImageDataDirectory | The resource table address and size. |
| exception_table | ImageDataDirectory | The exception table address and size. |
| certificate_table | ImageDataDirectory | The attribute certificate table address and size. |
| base_relocation_table | ImageDataDirectory | The base relocation certificate table address and size. |
| debug | ImageDataDirectory | The debug data starting address and size. |
| architecture | ImageDataDirectory | Reserved, must be 0. |
| global_ptr | ImageDataDirectory | The RVA of the value to be stored in the global pointer register. The size member of this structure must be set to zero. |
| tls_table | ImageDataDirectory | The thread local storage (TLS) table address and size. |
| load_config_table | ImageDataDirectory | The load configuration table address and size. |
| bound_import | ImageDataDirectory | The bound import table address and size. |
| ita | ImageDataDirectory | The import address table address and size. |
| delay_import_descriptor | ImageDataDirectory | The delay import descriptor address and size. |
| clr_runtime_header | ImageDataDirectory | The CLR runtime header address and sizeclr_runtime. |
| reserved | ImageDataDirectory | Reserved, must be zero. |
An opaque value; see the functions that return it.
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.
| 0 | u32 |
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_flags | u32 | Reserved, must be 0. |
| time_date_stamp | u32 | The time and date that the export data was created. |
| major_version | u16 | The major version number. The major and minor version numbers can be set by the user. |
| minor_version | u16 | The minor version number. |
| name_rva | u32 | The address of the ASCII string that contains the name of the DLL. This address is relative to the image base. |
| ordinal_base | u32 | The 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_entries | u32 | The number of entries in the export address table. |
| number_of_name_pointers | u32 | The number of entries in the name pointer table. This is also the number of entries in the ordinal table. |
| export_address_table | u32 | The address of the export address table, relative to the image base. |
| name_pointer_rva | u32 | The 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_rva | u32 | The address of the ordinal table, relative to the image base. |
Pointer into the export name table. An export name is defined only if the export name pointer table contains a pointer to it.
| 0 | u32 |
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.
| 0 | u16 |
| export_directory_table | ExportDirectory | The export directory table contains address information that is used to resolve imports to the entry points within this image. |
| export_address_table | Table | The 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_table | Table | The 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_table | Table | An 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_table | Table | |
| dll_name | str | The name of the DLL, from [`ExportDirectory::name_rva`]. |
An opaque value; see the functions that return it.
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_address | u32 | The 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. |
| size | u32 | Size in bytes. |
An owned, editable PE image that can be written back to bytes.
| dos_header | ImageDosHeader | |
| dos_stub | bytes | Bytes between the DOS header and the PE signature. |
| coff_header | CoffFileHeader | |
| optional_header | OptionalHeader | |
| sections | SectionDefinitions | |
| overlay | bytes | Data after the last section (e.g. the certificate table). |
| overlay_offset | usize | |
| first_raw_offset | usize | |
| created | bool |
ImageDef::new_dll(machine: ImageFileMachine) -> ImageDefA new, empty DLL for machine: PE32+ for a 64-bit machine, PE32 otherwise.
Parse a PE file held in memory as an editable image.
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.
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.
Append a section after the last one and return its RVA. flags are its characteristics; see section_flags().
image_def.exports() -> Result<Option<ExportTableDataDirectory>, str>The export table, or None if the image has none.
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.strip_certificate()Remove the certificate table. Any edit invalidates the signature anyway.
Serialize the image, recomputing header sizes, section offsets and the checksum.
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_magic | u16 | Magic number |
| e_cblp | u16 | Bytes on last page of file |
| e_cp | u16 | Pages in file |
| e_crlc | u16 | Relocations |
| e_cparhdr | u16 | Size of header in paragraphs needed |
| e_minalloc | u16 | Minimum extra paragraphs needed |
| e_maxalloc | u16 | Maximum extra paragraphs needed |
| e_ss | u16 | Initial (relative) SS value |
| e_sp | u16 | Initial SP value |
| e_csum | u16 | Checksum |
| e_ip | u16 | Initial IP value |
| e_cs | u16 | Initial (relative) CS value |
| e_lfarlc | u16 | File address of relocation table |
| e_ovno | u16 | Overlay number |
| e_res | list<u16> | Reserved words |
| e_oemid | u16 | OEM identifier (for e_oeminfo) |
| e_oeminfo | u16 | OEM information; e_oemid specific |
| e_res2 | list<u16> | Reserved words |
| e_lfanew | u32 | File address of new exe header |
| ImageFileMachine::Unknown | The content of this field is assumed to be applicable to any machine type |
| ImageFileMachine::Alpha | Alpha AXP, 32-bit address space |
| ImageFileMachine::Alpha64 | Alpha 64, 64-bit address space |
| ImageFileMachine::Am33 | Matsushita AM33 |
| ImageFileMachine::Amd64 | x64 |
| ImageFileMachine::Arm | ARM little endian |
| ImageFileMachine::Arm64 | ARM64 little endian |
| ImageFileMachine::ArmNT | ARM Thumb-2 little endian |
| ImageFileMachine::Ebc | EFI byte code |
| ImageFileMachine::I386 | Intel 386 or later processors and compatible processors |
| ImageFileMachine::IA64 | Intel Itanium processor family |
| ImageFileMachine::LoongArchH32 | LoongArch 32-bit processor family |
| ImageFileMachine::LoongArch64 | LoongArch 64-bit processor family |
| ImageFileMachine::M32R | Mitsubishi M32R little endian |
| ImageFileMachine::Mips16 | MIPS16 |
| ImageFileMachine::MipsFPU | MIPS with FPU |
| ImageFileMachine::MipsFPU16 | MIPS16 with FPU |
| ImageFileMachine::PowerPC | Power PC little endian |
| ImageFileMachine::PowerPCFP | Power PC with floating point support |
| ImageFileMachine::R4000 | MIPS little endian |
| ImageFileMachine::RiscV32 | RISC-V 32-bit address space |
| ImageFileMachine::RiscV64 | RISC-V 64-bit address space |
| ImageFileMachine::RiscV128 | RISC-V 128-bit address space |
| ImageFileMachine::Sh3 | Hitachi SH3 |
| ImageFileMachine::Sh4 | Hitachi SH4 |
| ImageFileMachine::Sh5 | Hitachi Sh5 |
| ImageFileMachine::Thumb | Thumb |
| ImageFileMachine::WceMipsV2 | MIPS little-endian WCE v2 |
| ImageFileMachine::Other(u16) | Other machine type |
| import_lookup_table_rva | u32 | The 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_stamp | u32 | The 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_chain | u32 | The index of the first forwarder reference. |
| name_rva | u32 | The address of an ASCII string that contains the name of the DLL. This address is relative to the image base. |
| import_address_table_rva | u32 | The 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. |
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.
| entries | Table | 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. |
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_table | ImportDirectoryTable | The import directory table consists of an array of import directory entries, one entry for each DLL to which the image refers. |
| dll_name | str | from [`ImportDirectoryTable::name_rva`] |
| import_lookup_table | Table | An 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. |
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_fields | OptionalHeaderStandardFields | The 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_fields | OptionalHeaderWindowsSpecific | The 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_directories | DataDirectories | Data 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). |
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 |
| magic | OptionalHeaderMagic | The unsigned integer that identifies the state of the image file. |
| major_linker_version | u8 | The linker major version number. |
| minor_linker_version | u8 | The linker minor version number. |
| size_of_code | u32 | The size of the code (text) section, or the sum of all code sections if there are multiple sections. |
| size_of_initilized_data | u32 | The size of the initialized data section, or the sum of all such sections if there are multiple data sections. |
| size_of_unitilized_data | u32 | The size of the uninitialized data section (BSS), or the sum of all such sections if there are multiple BSS sections. |
| address_of_entry_point | u32 | The 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_code | u32 | The address that is relative to the image base of the beginning-of-code section when it is loaded into memory. |
| base_of_data | Option<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. |
Holds the Optional Header Windows Specific fields for either PE32 or PE32+.
| OptionalHeaderWindowsSpecific::PE32(OptionalHeaderWindowsSpecificFields) | |
| OptionalHeaderWindowsSpecific::PE32Plus(OptionalHeaderWindowsSpecificFields) |
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.
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.
| dos_header | ImageDosHeader | |
| coff_header | CoffFileHeader | |
| optional_header | Option<OptionalHeader> | |
| sections | Sections | |
| file_bytes | FileBytes |
The Authenticode certificate table, or None if the file isn't signed.
The CLR runtime header of a .NET assembly, or None for a native file.
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.
The base relocation table, or None if the file has none.
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.
The section names, in table order, such as ".text", without the padding of the 8-byte name field.
Sections ordered by virtual address.
| 0 | list<SectionHeap> |
An opaque value; see the functions that return it.
| name | str | Names longer than 8 bytes are truncated. |
| virtual_address | u32 | |
| virtual_size | u32 | Leave as zero to use the data length. |
| characteristics | SectionFlags | |
| data | bytes |
| row | SectionTableRow | |
| data | bytes |
| name | bytes | An 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_size | u32 | The 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_address | u32 | For 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_data | u32 | The 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_data | u32 | The 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_relocations | u32 | The 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_numbers | u32 | The 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_relocaions | u16 | The number of relocation entries for the section. This is set to zero for executable images. |
| number_of_line_numbers | u16 | The number of line-number entries for the section. This value should be zero for an image because COFF debugging information is deprecated. |
| characteristics | SectionFlags | The flags that describe the characteristics of the section. |
Sections with their ccorrisponding data
| 0 | Table |
> 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(())
}