Files
WT-Offline/tools/src/wtotools/pe/image.py
T
N0VAN0M4LY 89aa5198c3 build(repo): restore build tools and define the workspace layout
Restore the reviewed pack, PE, and patch tooling. Specify a TypeScript
build pipeline, a type-preserving BLK codec, and a configurable loopback
port selected at launch. Document the package boundaries.
2026-11-24 00:19:04 +08:00

78 lines
2.7 KiB
Python

"""Address mapping, sections and function ranges of a PE image held in memory.
Addresses are RVAs (relative to the image base) unless a name says otherwise.
The view never modifies the bytes it was built from.
"""
from __future__ import annotations
import bisect
import struct
from dataclasses import dataclass
from functools import cached_property
import pefile
_EXCEPTION_DIRECTORY = 3
@dataclass(frozen=True)
class Section:
name: str
rva: int
virtual_size: int
raw_offset: int
raw_size: int
def contains_rva(self, rva: int) -> bool:
return self.rva <= rva < self.rva + max(self.virtual_size, self.raw_size)
class PeImage:
def __init__(self, data: bytes):
self.data = data
self._pe = pefile.PE(data=data, fast_load=True)
self.image_base = self._pe.OPTIONAL_HEADER.ImageBase
self.sections = [
Section(s.Name.rstrip(b"\0").decode(), s.VirtualAddress, s.Misc_VirtualSize, s.PointerToRawData, s.SizeOfRawData)
for s in self._pe.sections
]
def section(self, name: str) -> Section:
for section in self.sections:
if section.name == name:
return section
raise KeyError(f"no section {name}")
def section_of(self, rva: int) -> Section:
for section in self.sections:
if section.contains_rva(rva):
return section
raise ValueError(f"RVA {rva:#x} is outside every section")
def file_offset(self, rva: int) -> int:
section = self.section_of(rva)
if rva - section.rva >= section.raw_size:
raise ValueError(f"RVA {rva:#x} has no file bytes (uninitialised data)")
return rva - section.rva + section.raw_offset
def read(self, rva: int, size: int) -> bytes:
offset = self.file_offset(rva)
return self.data[offset:offset + size]
def section_bytes(self, name: str) -> bytes:
section = self.section(name)
return self.data[section.raw_offset:section.raw_offset + min(section.virtual_size, section.raw_size)]
@cached_property
def functions(self) -> list[tuple[int, int]]:
"""(begin, end) RVA pairs from the exception directory, sorted by begin."""
directory = self._pe.OPTIONAL_HEADER.DATA_DIRECTORY[_EXCEPTION_DIRECTORY]
raw = self.read(directory.VirtualAddress, directory.Size)
return sorted((begin, end) for begin, end, _unwind in struct.iter_unpack("<III", raw))
def function_containing(self, rva: int) -> tuple[int, int] | None:
index = bisect.bisect_right(self.functions, (rva, 1 << 32)) - 1
if index >= 0 and self.functions[index][0] <= rva < self.functions[index][1]:
return self.functions[index]
return None