From b174b45bede7da57fd944fdf5082a87dd473994c Mon Sep 17 00:00:00 2001 From: zachdoxsee Date: Tue, 24 Nov 2026 16:12:59 +0100 Subject: [PATCH] loader: report delay-loaded PE imports in the static probe (#244) Read the PE32+ delay-load directory (data directory 13) with a bounded parser and list each delay-loaded import in imports.csv, marked by a new import_table column. Ordinary totals and missing_imports.csv are unchanged; the JSON report counts delayed slots and DLLs separately and carries a diagnostic for truncated, out-of-range or unsupported tables. Adds an original fixture with ordinary and delayed imports, generated by fixtures/pe/delay-imports.py and cross-checked with llvm-readobj. Signed-off-by: zachdoxsee --- CHANGELOG.md | 1 + crates/loader/src/import_table.rs | 98 +++++- crates/loader/src/probe.rs | 134 +++++++-- crates/loader/tests/probe_delay_imports.rs | 333 +++++++++++++++++++++ docs/interfaces.md | 35 ++- fixtures/pe/delay-imports.exe | Bin 0 -> 3072 bytes fixtures/pe/delay-imports.py | 125 ++++++++ 7 files changed, 686 insertions(+), 40 deletions(-) create mode 100644 crates/loader/tests/probe_delay_imports.rs create mode 100644 fixtures/pe/delay-imports.exe create mode 100644 fixtures/pe/delay-imports.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 992036a..a617031 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Added +- Added delay-loaded imports to the static PE probe (#244). `xenora probe --mode static` now reads the PE32+ delay-load directory and lists each delay-loaded import in `imports.csv` with its DLL, symbol or ordinal, and delay import address table slot. A new `import_table` column, inserted after `iat_rva`, marks every row `ordinary` or `delayed`; `import_kind` stays the last column. The existing totals and `missing_imports.csv` still cover ordinary imports only, and the JSON report adds `delayed_imports`, `delayed_imported_dlls_count` and `delay_import_error`. A truncated or out-of-range table, a reserved attribute bit, a missing name table and the earlier virtual-address descriptor form are each reported with the entries read before them. Inspection stays static: nothing is bound or executed. Covered by an original fixture (`fixtures/pe/delay-imports.exe`, generated by `fixtures/pe/delay-imports.py`) whose imports were cross-checked locally with `llvm-readobj --coff-imports` from LLVM 23.1.6; awaiting independent review. - Added the sixteen gfx1030 SOPK integer forms through the semantic registry: `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, `s_addk_i32` and `s_mulk_i32` (AMD guide sections 12.2 and 13.1.2), with SDST s0-s105 only and SIMM16 sign-extended (zero-extended for the unsigned compares). The registry gained the operand rules `sopk_sgpr` and `sopk_compare` and the operations `mov` and `cmov`; the decoder and the scalar translation fold them like SOP2 and SOPC. An independent guide-derived oracle (`tests/validation/tests/sopk.rs`, 4,184 cases and 398 rejections on both CPU interpreters and native Metal), an LLVM-assembled fixture `scalar-immediate.s` with IR and MSL goldens, and the LLVM three-way decoder check cover them (part of #215). - Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). The decoder and translator still reject these forms, and native Metal agreement is not yet shown. Part of #215. - Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215). diff --git a/crates/loader/src/import_table.rs b/crates/loader/src/import_table.rs index bcab819..3f09b38 100644 --- a/crates/loader/src/import_table.rs +++ b/crates/loader/src/import_table.rs @@ -3,6 +3,10 @@ //! Bounded parser for the PE32+ import directory (Microsoft PE format, //! "The .idata Section"). Binding and static inspection both use it, so they //! agree on which imports an image has and how they are named. +//! +//! Static inspection also reads the delay-load directory ("Delay-Load Import +//! Tables (Image Only)"). Binding does not: the PE format leaves those imports +//! to a delay-load helper that runs inside the image on first use. use std::fmt; @@ -14,6 +18,9 @@ pub const MAX_IMPORTS: usize = 65_536; pub const MAX_NAME_LEN: usize = 4096; const DESCRIPTOR_LEN: u32 = 20; +const DELAY_DESCRIPTOR_LEN: u32 = 32; +/// Delay-load attribute bit 0: the descriptor's address fields are RVAs. +const DELAY_RVA_BASED: u32 = 1; const ORDINAL_FLAG: u64 = 1 << 63; /// How an import names its target. A symbol that happens to be spelled like an @@ -56,6 +63,19 @@ pub enum ImportTableError { ReservedBits { rva: u32, }, + /// The delay-load descriptor at this RVA sets reserved attribute bits. + DelayReservedBits { + rva: u32, + }, + /// The delay-load descriptor at this RVA has `RvaBased` clear, the earlier + /// form whose address fields are virtual addresses. It is not read. + DelayVirtualAddresses { + rva: u32, + }, + /// The delay-load descriptor at this RVA has no import name table. + DelayNamesMissing { + rva: u32, + }, TooManyDescriptors, TooManyImports, } @@ -63,7 +83,10 @@ pub enum ImportTableError { impl fmt::Display for ImportTableError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::OutOfBounds { rva } => write!(f, "import data at RVA 0x{rva:08x} is truncated"), + Self::OutOfBounds { rva } => write!( + f, + "import data at RVA 0x{rva:08x} is truncated or outside the section data" + ), Self::MalformedName { rva } => write!(f, "malformed import name at RVA 0x{rva:08x}"), Self::ReservedBits { rva } => { write!( @@ -71,6 +94,18 @@ impl fmt::Display for ImportTableError { "reserved bits set in the import lookup at RVA 0x{rva:08x}" ) } + Self::DelayReservedBits { rva } => write!( + f, + "reserved attribute bits set in the delay-load descriptor at RVA 0x{rva:08x}" + ), + Self::DelayVirtualAddresses { rva } => write!( + f, + "delay-load descriptor at RVA 0x{rva:08x} holds virtual addresses, not RVAs, and is not read" + ), + Self::DelayNamesMissing { rva } => write!( + f, + "delay-load descriptor at RVA 0x{rva:08x} has no import name table" + ), Self::TooManyDescriptors => write!(f, "more than {MAX_DESCRIPTORS} import descriptors"), Self::TooManyImports => write!(f, "more than {MAX_IMPORTS} imported symbols"), } @@ -159,7 +194,7 @@ fn collect Option>( return Ok(()); } let module = reader.name(name_rva)?; - collect_symbols(reader, &module, lookup_rva, address_rva, entries)?; + collect_symbols(reader, &module, lookup_rva, address_rva, false, entries)?; descriptor = descriptor .checked_add(DESCRIPTOR_LEN) .ok_or(ImportTableError::OutOfBounds { rva: descriptor })?; @@ -167,11 +202,66 @@ fn collect Option>( Err(ImportTableError::TooManyDescriptors) } +/// Parse the delay-load directory at `directory_rva`. +/// +/// Each entry's `iat_rva` is its slot in the delay import address table. +/// Returns every import before the first problem, and the problem. +pub fn parse_delay_imports( + bytes: &[u8], + directory_rva: u32, + rva_to_offset: impl Fn(u32) -> Option, +) -> (Vec, Option) { + let reader = Reader { + bytes, + rva_to_offset, + }; + let mut entries = Vec::new(); + let error = collect_delayed(&reader, directory_rva, &mut entries).err(); + (entries, error) +} + +fn collect_delayed Option>( + reader: &Reader<'_, F>, + directory_rva: u32, + entries: &mut Vec, +) -> Result<(), ImportTableError> { + let mut descriptor = directory_rva; + for _ in 0..MAX_DESCRIPTORS { + // Reading the whole descriptor also proves its field RVAs do not overflow. + let fields = reader.array::<{ DELAY_DESCRIPTOR_LEN as usize }>(descriptor)?; + // The table ends with an empty descriptor. + if fields == [0; DELAY_DESCRIPTOR_LEN as usize] { + return Ok(()); + } + let attributes = reader.u32(descriptor)?; + if attributes & !DELAY_RVA_BASED != 0 { + return Err(ImportTableError::DelayReservedBits { rva: descriptor }); + } + if attributes & DELAY_RVA_BASED == 0 { + return Err(ImportTableError::DelayVirtualAddresses { rva: descriptor }); + } + let name_rva = reader.u32(descriptor + 4)?; + let address_rva = reader.u32(descriptor + 12)?; + let names_rva = reader.u32(descriptor + 16)?; + // The address table holds thunk addresses, so it cannot stand in for names. + if names_rva == 0 { + return Err(ImportTableError::DelayNamesMissing { rva: descriptor }); + } + let module = reader.name(name_rva)?; + collect_symbols(reader, &module, names_rva, address_rva, true, entries)?; + descriptor = descriptor + .checked_add(DELAY_DESCRIPTOR_LEN) + .ok_or(ImportTableError::OutOfBounds { rva: descriptor })?; + } + Err(ImportTableError::TooManyDescriptors) +} + fn collect_symbols Option>( reader: &Reader<'_, F>, module: &str, lookup_rva: u32, address_rva: u32, + slots_on_disk: bool, entries: &mut Vec, ) -> Result<(), ImportTableError> { // Without a lookup table the address table holds the same entries on disk. @@ -194,6 +284,10 @@ fn collect_symbols Option>( return Err(ImportTableError::TooManyImports); } let iat_rva = at(address_rva)?; + if slots_on_disk { + // A delay-load slot starts out holding its thunk's address. + reader.array::<8>(iat_rva)?; + } let name = if value & ORDINAL_FLAG != 0 { let ordinal = value & !ORDINAL_FLAG; ImportName::Ordinal( diff --git a/crates/loader/src/probe.rs b/crates/loader/src/probe.rs index 0ec2400..9a84c14 100644 --- a/crates/loader/src/probe.rs +++ b/crates/loader/src/probe.rs @@ -11,7 +11,9 @@ //! startup blockers. use crate::dbt::{is_native, is_translatable}; -use crate::import_table::{ImportName, ImportTableError, parse_imports}; +use crate::import_table::{ + ImportEntry, ImportName, ImportTableError, parse_delay_imports, parse_imports, +}; use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::MemoryPermissions; use crate::pe::{IMAGE_FILE_MACHINE_AMD64, PE32_PLUS_MAGIC, ParsedPe, PeError, PeSection}; @@ -678,6 +680,11 @@ pub struct ProbeReport { pub imports: Vec, /// Why the import table could not be read to its end. pub import_error: Option, + /// Delay-loaded imports before the first malformed entry, if any. Binding + /// does not resolve them, so `imports` and its totals leave them out. + pub delayed_imports: Vec, + /// Why the delay-load import tables could not be read to their end. + pub delay_import_error: Option, pub instruction_records: Vec, pub first_unsupported_dbt_insn: Option, } @@ -822,6 +829,23 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result= 224 + && u32::from_le_bytes( + bytes[opt_offset + 108..opt_offset + 112] + .try_into() + .unwrap(), + ) > 13 + { + u32::from_le_bytes( + bytes[opt_offset + 216..opt_offset + 220] + .try_into() + .unwrap(), + ) + } else { + 0 + }; let section_table_offset = opt_offset + size_of_optional_header; let section_header_size = 40; @@ -960,35 +984,40 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result = entries - .into_iter() - .map(|entry| { - let binding = registry.resolve(&entry.module, &entry.name); - ImportedSymbol { - category: ProbeReport::categorize_dll(&entry.module), - dll: entry.module, - symbol: entry.name.to_string(), - import_name: entry.name, - iat_rva: entry.iat_rva, - is_supported: binding.is_some(), - service_status: binding.map(|service| service.status), - canonical_module: binding.map(|service| service.module.clone()), - canonical_symbol: binding.map(|service| service.symbol.clone()), - } - }) - .collect(); + let (delayed_entries, delay_import_error) = if delay_dir_rva == 0 { + (Vec::new(), None) + } else { + parse_delay_imports(bytes, delay_dir_rva, backed_offset) + }; + let describe = |entry: ImportEntry| { + let binding = registry.resolve(&entry.module, &entry.name); + ImportedSymbol { + category: ProbeReport::categorize_dll(&entry.module), + dll: entry.module, + symbol: entry.name.to_string(), + import_name: entry.name, + iat_rva: entry.iat_rva, + is_supported: binding.is_some(), + service_status: binding.map(|service| service.status), + canonical_module: binding.map(|service| service.module.clone()), + canonical_symbol: binding.map(|service| service.symbol.clone()), + } + }; + let imports: Vec = entries.into_iter().map(&describe).collect(); + let delayed_imports: Vec = delayed_entries.into_iter().map(&describe).collect(); // 4. Control-Flow-Aware Static Disassembly // @@ -1124,6 +1153,8 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result>( // 1. imports.csv let mut imports_csv = String::from( - "module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding,import_kind\n", + "module,symbol_or_ordinal,iat_rva,import_table,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding,import_kind\n", ); let mut missing_csv = String::from("module,symbol_or_ordinal,iat_rva,import_kind\n"); let mut modules = BTreeSet::new(); @@ -1186,7 +1217,7 @@ pub fn run_probe_and_export>( let canonical = canonical.replace('"', "\"\""); let _ = writeln!( imports_csv, - "{key},{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding},{import_kind}", + "{key},ordinary,{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding},{import_kind}", imp.category, imp.is_supported ); if !imp.is_supported { @@ -1194,6 +1225,34 @@ pub fn run_probe_and_export>( missing += 1; } } + // Delay-loaded imports follow the ordinary rows. Binding does not resolve + // them, so they stay out of every ordinary total, the startup clusters and + // `missing_imports.csv`. + let mut delayed_modules = BTreeSet::new(); + for imp in &report.delayed_imports { + delayed_modules.insert(imp.dll.to_ascii_lowercase()); + let is_ordinal = matches!(imp.import_name, ImportName::Ordinal(_)); + let import_kind = if is_ordinal { "ordinal" } else { "name" }; + let module = imp.dll.replace('"', "\"\""); + let symbol = imp.symbol.replace('"', "\"\""); + let canonical = imp.canonical_module.as_deref().unwrap_or(""); + let is_alias = imp.canonical_module.is_some() && !imp.dll.eq_ignore_ascii_case(canonical); + let canonical = canonical.replace('"', "\"\""); + let (priority, cluster) = imp.startup_priority(); + let _ = writeln!( + imports_csv, + "\"{module}\",\"{symbol}\",0x{:08x},delayed,{},{},{},{is_alias},\"{canonical}\",{priority},{cluster},false,{import_kind}", + imp.iat_rva, + imp.category, + imp.is_supported, + imp.coverage_label() + ); + } + let delayed_slots = report.delayed_imports.len(); + let delayed_dlls = delayed_modules.len(); + let delay_error = report + .delay_import_error + .map_or_else(|| "none".to_string(), |error| error.to_string()); fs::write(out.join("imports.csv"), imports_csv)?; fs::write(out.join("missing_imports.csv"), missing_csv)?; @@ -1250,6 +1309,9 @@ pub fn run_probe_and_export>( "stub_slots": {stubs}, "recognized_unsupported_slots": {unsupported}, "missing_handler_slots": {unknown}, + "delayed_imports": {delayed_slots}, + "delayed_imported_dlls_count": {delayed_dlls}, + "delay_import_error": "{delay_error}", "total_relocations": {}, "dir64_relocations": {}, "tls_callbacks_count": {}, @@ -1381,6 +1443,16 @@ pub fn run_probe_and_export>( "- **Import table is malformed**: {error}. Only the imports before it are listed, and binding refuses the image.\n" ); } + let _ = writeln!( + md, + "- **Delay-Loaded Import Slots**: `{delayed_slots}` across `{delayed_dlls}` DLLs. They are marked `delayed` in `imports.csv` and are not part of the counts above or of `missing_imports.csv`: binding does not resolve them, and the PE format leaves them to the image's delay-load helper.\n" + ); + if let Some(error) = &report.delay_import_error { + let _ = writeln!( + md, + "- **Delay-load import table is malformed**: {error}. Only the delay-loaded imports before it are listed.\n" + ); + } if trusted_runner_slots > 0 { let _ = writeln!( md, @@ -1425,6 +1497,12 @@ pub fn run_probe_and_export>( distinct_imports.len(), unique_symbols.len() ); + if delayed_slots > 0 { + let _ = writeln!( + matrix, + "\nThe delay-load import tables contain {delayed_slots} more slots across {delayed_dlls} DLLs. They are not counted in this document." + ); + } let _ = writeln!( matrix, "\nRegistered slots include {implemented} implemented, {partial} partial, and {stubs} stubs. They reference {} canonical registered services through {aliases} alias slots. The {missing} unresolved slots include {unsupported} explicitly tracked unsupported APIs and {unknown} other missing handlers.", diff --git a/crates/loader/tests/probe_delay_imports.rs b/crates/loader/tests/probe_delay_imports.rs new file mode 100644 index 0000000..7309b20 --- /dev/null +++ b/crates/loader/tests/probe_delay_imports.rs @@ -0,0 +1,333 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Static probe reports for delay-loaded PE imports. +//! +//! The expected names and slot RVAs are read off the layout that +//! `fixtures/pe/delay-imports.py` writes, not from the parser. +//! `llvm-readobj --coff-imports` from LLVM 23.1.6 lists the same imports in +//! the same order, with the address tables at RVA 0x2050, 0x3000 and 0x3020. + +use std::collections::BTreeMap; +use xenora_loader::import_table::{ImportTableError, parse_delay_imports}; +use xenora_loader::probe::{ + ImportedSymbol, ProbeConfig, ProbeReport, probe_pe_bytes, run_probe_and_export, +}; + +const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/delay-imports.exe"); + +/// DLL, symbol or ordinal, and import address table slot RVA. +type Row = (&'static str, &'static str, u32); + +const ORDINARY: [Row; 2] = [ + ("fixture-ordinary.dll", "OrdinaryByName", 0x2050), + ("fixture-ordinary.dll", "Ordinal#3", 0x2058), +]; +const DELAYED: [Row; 3] = [ + ("fixture-delay-a.dll", "DelayedAlpha", 0x3000), + ("fixture-delay-a.dll", "Ordinal#7", 0x3008), + ("fixture-delay-b.dll", "DelayedBeta", 0x3020), +]; + +// File offsets in the fixture. +const NUMBER_OF_RVA_AND_SIZES: usize = 0x98 + 108; +const DELAY_DIRECTORY_ENTRY: usize = 0x98 + 216; +const RDATA_RAW_SIZE: usize = 0x188 + 40 + 16; +/// The delay-load directory is at RVA 0x2200; `.rdata` maps RVA 0x2000 to 0x600. +const FIRST_DESCRIPTOR: usize = 0x800; +const SECOND_DESCRIPTOR: usize = 0x820; + +fn rows(imports: &[ImportedSymbol]) -> Vec<(&str, &str, u32)> { + imports + .iter() + .map(|import| (import.dll.as_str(), import.symbol.as_str(), import.iat_rva)) + .collect() +} + +fn put(pe: &mut [u8], offset: usize, value: u32) { + pe[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} + +/// Probe `pe` and return the report with the text files it exports. +fn export(pe: &[u8], name: &str) -> (ProbeReport, BTreeMap<&'static str, String>) { + let dir = + std::env::temp_dir().join(format!("xenora-probe-delay-{name}-{}", std::process::id())); + let report = run_probe_and_export(pe, &dir, &ProbeConfig::default()).unwrap(); + let files = [ + "imports.csv", + "missing_imports.csv", + "candidate_static_report.json", + "candidate_static_report.md", + "runtime_gap_matrix.md", + ] + .into_iter() + .map(|file| (file, std::fs::read_to_string(dir.join(file)).unwrap())) + .collect(); + std::fs::remove_dir_all(dir).unwrap(); + (report, files) +} + +fn json_field(json: &str, name: &str) -> String { + let prefix = format!("\"{name}\": "); + json.lines() + .find_map(|line| line.trim().strip_prefix(&prefix)) + .unwrap_or_else(|| panic!("no {name} in the JSON report")) + .trim_end_matches(',') + .trim_matches('"') + .to_string() +} + +#[test] +fn ordinary_and_delayed_imports_are_reported_apart() { + let (report, files) = export(FIXTURE, "fixture"); + + assert_eq!(rows(&report.imports), ORDINARY); + assert_eq!(rows(&report.delayed_imports), DELAYED); + assert_eq!(report.import_error, None); + assert_eq!(report.delay_import_error, None); + + let mut lines = files["imports.csv"].lines(); + let header = lines.next().unwrap(); + assert!(header.starts_with("module,symbol_or_ordinal,iat_rva,import_table,")); + assert!(header.ends_with(",import_kind")); + let columns = header.split(',').count(); + // The first four columns and the last one of every row. + let listed: Vec = lines + .map(|line| { + let fields: Vec<&str> = line.split(',').collect(); + assert_eq!(fields.len(), columns, "{line}"); + format!("{},{}", fields[..4].join(","), fields[columns - 1]) + }) + .collect(); + assert_eq!( + listed, + [ + "\"fixture-ordinary.dll\",\"OrdinaryByName\",0x00002050,ordinary,name", + "\"fixture-ordinary.dll\",\"Ordinal#3\",0x00002058,ordinary,ordinal", + "\"fixture-delay-a.dll\",\"DelayedAlpha\",0x00003000,delayed,name", + "\"fixture-delay-a.dll\",\"Ordinal#7\",0x00003008,delayed,ordinal", + "\"fixture-delay-b.dll\",\"DelayedBeta\",0x00003020,delayed,name", + ] + ); + + // Neither fixture DLL has a handler, so both ordinary imports are missing. + // The delayed ones are not the binder's to resolve and stay off its list. + assert_eq!( + files["missing_imports.csv"].lines().collect::>(), + [ + "module,symbol_or_ordinal,iat_rva,import_kind", + "\"fixture-ordinary.dll\",\"OrdinaryByName\",0x00002050,name", + "\"fixture-ordinary.dll\",\"Ordinal#3\",0x00002058,ordinal", + ] + ); + + let json = &files["candidate_static_report.json"]; + for (name, expected) in [ + ("total_imports", "2"), + ("imported_dlls_count", "1"), + ("unresolved_imports", "2"), + ("distinct_import_keys", "2"), + ("delayed_imports", "3"), + ("delayed_imported_dlls_count", "2"), + ("delay_import_error", "none"), + ] { + assert_eq!(json_field(json, name), expected, "{name}"); + } + + let md = &files["candidate_static_report.md"]; + assert!(md.contains("- **Total Imported Thunks**: `2`")); + assert!(md.contains("- **Delay-Loaded Import Slots**: `3` across `2` DLLs.")); + assert!(!md.contains("Delay-load import table is malformed")); + assert!( + files["runtime_gap_matrix.md"] + .contains("The delay-load import tables contain 3 more slots across 2 DLLs.") + ); +} + +#[test] +fn inspection_decodes_the_entry_point_and_follows_no_delay_slot() { + let report = probe_pe_bytes(FIXTURE, &ProbeConfig::default()).unwrap(); + + // The entry point is a lone RET at RVA 0x1000. The three delay-load slots + // hold the addresses of INT3 stubs at 0x1010, 0x1018 and 0x1020. Reaching + // one would mean the probe followed a slot, so none may be decoded. + let decoded: Vec<(u32, &[u8])> = report + .instruction_records + .iter() + .map(|record| (record.rva, record.bytes.as_slice())) + .collect(); + assert_eq!(decoded, [(0x1000, &[0xc3][..])]); +} + +#[test] +fn image_without_a_delay_directory_keeps_its_ordinary_imports() { + // `fixtures/pe/trusted-runner.py` writes one import, `xenora.dll!fixture_draw`, + // with its slot at RVA 0x2040 and no delay import descriptor. + let runner = include_bytes!("../../../fixtures/pe/trusted-runner.exe"); + let (report, files) = export(runner, "runner"); + assert_eq!( + rows(&report.imports), + [("xenora.dll", "fixture_draw", 0x2040)] + ); + assert_eq!(report.import_error, None); + assert!(report.delayed_imports.is_empty()); + assert_eq!(report.delay_import_error, None); + + let listed: Vec<&str> = files["imports.csv"].lines().skip(1).collect(); + assert_eq!(listed.len(), 1); + assert!(listed[0].starts_with("\"xenora.dll\",\"fixture_draw\",0x00002040,ordinary,")); + let json = &files["candidate_static_report.json"]; + assert_eq!(json_field(json, "total_imports"), "1"); + assert_eq!(json_field(json, "imported_dlls_count"), "1"); + assert_eq!(json_field(json, "delayed_imports"), "0"); + assert_eq!(json_field(json, "delayed_imported_dlls_count"), "0"); + assert_eq!(json_field(json, "delay_import_error"), "none"); + assert!(!files["runtime_gap_matrix.md"].contains("delay-load")); +} + +#[test] +fn delay_directory_beyond_the_declared_count_is_not_read() { + // With 13 data directories the header has no delay import descriptor, so + // the bytes at its offset mean nothing. + let mut pe = FIXTURE.to_vec(); + put(&mut pe, NUMBER_OF_RVA_AND_SIZES, 13); + let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap(); + assert_eq!(rows(&report.imports), ORDINARY); + assert!(report.delayed_imports.is_empty()); + assert_eq!(report.delay_import_error, None); +} + +#[test] +fn malformed_delay_tables_are_diagnosed_and_ordinary_imports_kept() { + type Case = ( + &'static str, + fn(&mut Vec), + usize, + ImportTableError, + &'static str, + ); + // (name, damage, delayed imports still listed, error, message) + let cases: [Case; 9] = [ + ( + "directory-out-of-range", + |pe| put(pe, DELAY_DIRECTORY_ENTRY, 0x9000), + 0, + ImportTableError::OutOfBounds { rva: 0x9000 }, + "import data at RVA 0x00009000 is truncated or outside the section data", + ), + ( + // `.rdata` keeps 0x230 bytes: the first descriptor and half the second. + "section-data-ends-inside-descriptor", + |pe| put(pe, RDATA_RAW_SIZE, 0x230), + 2, + ImportTableError::OutOfBounds { rva: 0x2220 }, + "import data at RVA 0x00002220 is truncated or outside the section data", + ), + ( + // The file ends where `.data` and its address tables would begin. + "file-ends-before-address-table", + |pe| pe.truncate(0xa00), + 0, + ImportTableError::OutOfBounds { rva: 0x3000 }, + "import data at RVA 0x00003000 is truncated or outside the section data", + ), + ( + "name-table-out-of-range", + |pe| put(pe, FIRST_DESCRIPTOR + 16, 0x9000), + 0, + ImportTableError::OutOfBounds { rva: 0x9000 }, + "import data at RVA 0x00009000 is truncated or outside the section data", + ), + ( + "address-table-out-of-range", + |pe| put(pe, SECOND_DESCRIPTOR + 12, 0x9000), + 2, + ImportTableError::OutOfBounds { rva: 0x9000 }, + "import data at RVA 0x00009000 is truncated or outside the section data", + ), + ( + "dll-name-out-of-range", + |pe| put(pe, SECOND_DESCRIPTOR + 4, 0x9000), + 2, + ImportTableError::MalformedName { rva: 0x9000 }, + "malformed import name at RVA 0x00009000", + ), + ( + "name-table-missing", + |pe| put(pe, SECOND_DESCRIPTOR + 16, 0), + 2, + ImportTableError::DelayNamesMissing { rva: 0x2220 }, + "delay-load descriptor at RVA 0x00002220 has no import name table", + ), + ( + "reserved-attribute-bit", + |pe| put(pe, FIRST_DESCRIPTOR, 3), + 0, + ImportTableError::DelayReservedBits { rva: 0x2200 }, + "reserved attribute bits set in the delay-load descriptor at RVA 0x00002200", + ), + ( + "virtual-address-form", + |pe| put(pe, SECOND_DESCRIPTOR, 0), + 2, + ImportTableError::DelayVirtualAddresses { rva: 0x2220 }, + "delay-load descriptor at RVA 0x00002220 holds virtual addresses, not RVAs, and is not read", + ), + ]; + + for (name, damage, listed, error, message) in cases { + let mut pe = FIXTURE.to_vec(); + damage(&mut pe); + let (report, files) = export(&pe, name); + + assert_eq!(rows(&report.imports), ORDINARY, "{name}"); + assert_eq!(report.import_error, None, "{name}"); + assert_eq!(rows(&report.delayed_imports), DELAYED[..listed], "{name}"); + assert_eq!(report.delay_import_error, Some(error), "{name}"); + assert_eq!(error.to_string(), message, "{name}"); + + let json = &files["candidate_static_report.json"]; + assert_eq!(json_field(json, "total_imports"), "2", "{name}"); + assert_eq!( + json_field(json, "delayed_imports"), + listed.to_string(), + "{name}" + ); + assert_eq!(json_field(json, "delay_import_error"), message, "{name}"); + assert!( + files["candidate_static_report.md"].contains(&format!( + "- **Delay-load import table is malformed**: {message}. Only the delay-loaded imports before it are listed." + )), + "{name}" + ); + } +} + +#[test] +fn endless_delay_table_is_refused() { + // Every descriptor RVA maps onto the same 32 bytes, so the table never + // reaches its empty entry. The descriptor names module "a" at RVA 0x1000 + // and an empty name table at RVA 0x2000. + let mut bytes = vec![0u8; 48]; + put(&mut bytes, 0, 1); + put(&mut bytes, 4, 0x1000); + put(&mut bytes, 12, 0x3000); + put(&mut bytes, 16, 0x2000); + bytes[32] = b'a'; + let (imports, error) = parse_delay_imports(&bytes, 0x10_0000, |rva| match rva { + 0x1000..0x1002 => Some(32 + (rva - 0x1000) as usize), + 0x2000..0x2008 => Some(40 + (rva - 0x2000) as usize), + 0x10_0000.. => Some((rva % 32) as usize), + _ => None, + }); + assert!(imports.is_empty()); + assert_eq!(error, Some(ImportTableError::TooManyDescriptors)); +} + +#[test] +fn probe_never_panics_on_a_truncated_delay_fixture() { + for len in 1..=FIXTURE.len() { + // The probe may reject the file or report unreadable imports, but it + // must not panic. + let _ = probe_pe_bytes(&FIXTURE[..len], &ProbeConfig::default()); + } +} diff --git a/docs/interfaces.md b/docs/interfaces.md index 417b08f..5aa77a5 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -69,16 +69,31 @@ storage, invokes its callbacks and runs the entry point. The fixture entry point uses a Win64-aligned stack and terminates with HLT. The result includes the loaded guest memory and the entry execution outcome. -`xenora probe --mode static` inventories ordinary PE imports without guest -execution. `missing_imports.csv` lists unresolved keys with their import address -table relative virtual addresses. The full inventory records whether each key is registered, its implementation -status, and the canonical module behind API-set aliases. Runtime-loaded modules -and services require separate analysis. The coverage matrix groups unresolved -imports by shared startup prerequisites. Static imports do not reveal call -order. The JSON report counts import slots, DLL and symbol keys, distinct -names with DLL-scoped ordinals, and canonical registered handlers separately. -The unresolved total includes explicitly tracked unsupported APIs and other -missing handlers. Existing stubs remain visible in the full inventory. +`xenora probe --mode static` inventories ordinary and delay-loaded PE imports +without guest execution. `missing_imports.csv` lists unresolved ordinary keys +with their import address table relative virtual addresses. The full inventory, +`imports.csv`, marks each entry `ordinary` or `delayed` in its `import_table` +column and records whether each key is registered, its implementation +status, and the canonical module behind API-set aliases. Modules and services +loaded by other means at run time require separate analysis. The coverage matrix +groups unresolved ordinary imports by shared startup prerequisites. Static +imports do not reveal call order. The JSON report counts import slots, DLL and +symbol keys, distinct names with DLL-scoped ordinals, and canonical registered +handlers separately. The unresolved total includes explicitly tracked +unsupported APIs and other missing handlers. Existing stubs remain visible in +the full inventory. + +Delay-loaded imports come from the PE32+ delay-load directory, data directory +13 in Microsoft's PE format. The probe reports each one with its DLL, symbol or +ordinal, and slot in the delay import address table, after the ordinary rows. +Binding does not resolve them: the PE format leaves that to a delay-load helper +inside the image. The totals above and `missing_imports.csv` therefore cover +ordinary imports only, and the JSON report counts delayed slots and DLLs in +`delayed_imports` and `delayed_imported_dlls_count`. The probe reads descriptors +whose `RvaBased` attribute is set. A truncated or out-of-range table, a reserved +attribute bit, a missing name table or the earlier virtual-address descriptor +form is reported in `delay_import_error` and in the Markdown report, together +with the entries read before it. The synthetic process registry supports the current-process pseudo handle and its process ID. The priority boost setter and getter record and query a guest diff --git a/fixtures/pe/delay-imports.exe b/fixtures/pe/delay-imports.exe new file mode 100644 index 0000000000000000000000000000000000000000..86ba611ccc5ac00707852b04770c662ac025968b GIT binary patch literal 3072 zcmeHJu};H440Qp41WU$@2P`a&@(G~=i3P~a#8r2QN&%uMNX?dsxu1l@%E#~tJSTS~ zxd@P|EQMHgZNF!`c{f~oc|&Vkx%Ol;7@rfVm+b~X_Cd#Vu!V$u*H9iJJ5e;@Z_dG6 z+D3|i@4#W$iq@*z&H{Do7R5t?=!E0I77HSucODVla&#=n^)hFSH5+YKhiw%Y4KgKj z34}EQsN$D+)UXJjz_eBSLV&z?AKtQv=(Saj=|4PyH%Ifksom(bjpZLXflxF;QsjJ3 z{bVb{n;W}ydw=8a7R&rO)6=I+Egof71S(0oJFX2gE3V{&?sCId>0!NduMVaCg_Xf= zZKHjDr4w09W$*F3{Jh5#o$;hrr%8Ix_ju0?KhxDU-=hZxCfFB3YsBvec1Jh!F|Z48 f0`5CJ=+QR#1U#?)KjoX~N)g}SZr@mM<_UZPsk%SV literal 0 HcmV?d00001 diff --git a/fixtures/pe/delay-imports.py b/fixtures/pe/delay-imports.py new file mode 100644 index 0000000..6eef4a9 --- /dev/null +++ b/fixtures/pe/delay-imports.py @@ -0,0 +1,125 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Generate the original PE32+ delay-load import fixture without an x86 toolchain. + +The image has one ordinary import DLL and two delay-loaded DLLs, each with a +named import and one of them with an import by ordinal. It follows Microsoft's +PE format specification ("The .idata Section" and "Delay-Load Import Tables +(Image Only)"). It is for static inspection: the entry point returns at once and +nothing calls an import. +""" + +import argparse +from pathlib import Path +from struct import pack_into + +BASE = 0x140000000 +TEXT, RDATA, DATA = 0x1000, 0x2000, 0x3000 +# File offset of each section's data, after the 0x400-byte headers. +RAW = {TEXT: 0x400, RDATA: 0x600, DATA: 0xA00} +ORDINAL = 1 << 63 + +# Ordinary imports, in .rdata. +IMPORT_DIRECTORY = RDATA +LOOKUP, IAT = RDATA + 0x30, RDATA + 0x50 +ORDINARY_DLL, ORDINARY_NAME = RDATA + 0x70, RDATA + 0x90 + +# Delay-load names and name tables, in .rdata before their directory so that a +# file cut inside the directory still holds everything the first entry names. +NAMES_A, NAMES_B = RDATA + 0x100, RDATA + 0x118 +DELAY_DLL_A, DELAY_DLL_B = RDATA + 0x130, RDATA + 0x150 +DELAY_NAME_A, DELAY_NAME_B = RDATA + 0x170, RDATA + 0x190 +DELAY_DIRECTORY = RDATA + 0x200 + +# Delay-load address tables and module handles, in writable .data. +DELAY_IAT_A, DELAY_IAT_B = DATA, DATA + 0x20 +HANDLE_A, HANDLE_B = DATA + 0x40, DATA + 0x48 + +# Each delay-load address slot starts out pointing at its own stub. +STUBS = (TEXT + 0x10, TEXT + 0x18, TEXT + 0x20) + + +def fixture(): + data = bytearray(0xC00) + + def offset(rva): + section = rva & ~0xFFF + return RAW[section] + rva - section + + def put(rva, layout, *values): + pack_into(layout, data, offset(rva), *values) + + def text(rva, value): + data[offset(rva):offset(rva) + len(value) + 1] = value + b"\0" + + data[:2] = b"MZ" + pack_into("