mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 03:39:52 +00:00
Merge remote-tracking branch 'origin/main' into task/215-smov
This commit is contained in:
commit
5b894777ce
9 files changed
+878
-43
No files matched your search
@@ -16,6 +16,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`. The table is bounded by the directory's declared size, which must hold the empty descriptor that ends it, and each descriptor's DLL name, import address table and import name table must be present and start in section data. A table that breaks these rules, is truncated, sets a reserved attribute bit or uses the earlier virtual-address descriptor form is reported with the entries read before the problem. `xenora imports sync` leaves delayed rows out of its backlog. 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).
|
||||
|
||||
@@ -454,10 +454,16 @@ fn run_imports_sync(
|
||||
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
|
||||
let mut lines = csv_text.lines();
|
||||
let has_import_kind = lines
|
||||
.next()
|
||||
.is_some_and(|header| header.ends_with(",import_kind"));
|
||||
let header = lines.next().unwrap_or_default();
|
||||
let has_import_kind = header.ends_with(",import_kind");
|
||||
// Binding does not resolve delay-loaded imports, so the backlog omits them.
|
||||
let table_column = header
|
||||
.split(',')
|
||||
.position(|column| column == "import_table");
|
||||
for line in lines {
|
||||
if table_column.and_then(|index| line.split(',').nth(index)) == Some("delayed") {
|
||||
continue;
|
||||
}
|
||||
// Format: "module","symbol",0xRVA,category,registered,status,is_alias,"canonical",priority,cluster
|
||||
// We re-query the live registry rather than trusting cached status.
|
||||
let fields: Vec<&str> = line.splitn(10, ',').collect();
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! `xenora imports sync` over a probe report that lists delay-loaded imports.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn backlog_leaves_out_delay_loaded_imports() {
|
||||
// `fixtures/pe/delay-imports.py` writes two ordinary imports from
|
||||
// `fixture-ordinary.dll` and three delay-loaded ones from two other DLLs.
|
||||
let fixture = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/delay-imports.exe"
|
||||
);
|
||||
let report = std::env::temp_dir().join(format!("xenora-sync-delayed-{}", std::process::id()));
|
||||
let xenora = |arguments: &[&str]| {
|
||||
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
|
||||
.args(arguments)
|
||||
.arg("--report")
|
||||
.arg(&report)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "{arguments:?}");
|
||||
};
|
||||
xenora(&["probe", "--pe", fixture]);
|
||||
xenora(&["imports", "sync"]);
|
||||
let listed = std::fs::read_to_string(report.join("imports.csv")).unwrap();
|
||||
let backlog = std::fs::read_to_string(report.join("import_backlog.md")).unwrap();
|
||||
std::fs::remove_dir_all(report).unwrap();
|
||||
|
||||
assert_eq!(listed.matches(",delayed,").count(), 3);
|
||||
assert!(backlog.contains("| **Total** | 2 |"), "{backlog}");
|
||||
assert!(backlog.contains("fixture-ordinary.dll"), "{backlog}");
|
||||
assert!(!backlog.contains("fixture-delay"), "{backlog}");
|
||||
}
|
||||
@@ -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
|
||||
@@ -42,6 +49,24 @@ pub struct ImportEntry {
|
||||
pub iat_rva: u32,
|
||||
}
|
||||
|
||||
/// A delay-load descriptor field that must hold an RVA.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DelayField {
|
||||
DllName,
|
||||
AddressTable,
|
||||
NameTable,
|
||||
}
|
||||
|
||||
impl fmt::Display for DelayField {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::DllName => "DLL name",
|
||||
Self::AddressTable => "import address table",
|
||||
Self::NameTable => "import name table",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ImportTableError {
|
||||
/// A structure at this RVA is not fully backed by section data.
|
||||
@@ -56,6 +81,25 @@ 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 leaves a required field zero.
|
||||
DelayFieldMissing {
|
||||
rva: u32,
|
||||
field: DelayField,
|
||||
},
|
||||
/// The declared delay-load directory ends at this RVA before its empty
|
||||
/// descriptor.
|
||||
DelayDirectoryEnd {
|
||||
rva: u32,
|
||||
},
|
||||
TooManyDescriptors,
|
||||
TooManyImports,
|
||||
}
|
||||
@@ -63,7 +107,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 +118,21 @@ 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::DelayFieldMissing { rva, field } => {
|
||||
write!(f, "delay-load descriptor at RVA 0x{rva:08x} has no {field}")
|
||||
}
|
||||
Self::DelayDirectoryEnd { rva } => write!(
|
||||
f,
|
||||
"delay-load directory ends at RVA 0x{rva:08x} before its empty descriptor"
|
||||
),
|
||||
Self::TooManyDescriptors => write!(f, "more than {MAX_DESCRIPTORS} import descriptors"),
|
||||
Self::TooManyImports => write!(f, "more than {MAX_IMPORTS} imported symbols"),
|
||||
}
|
||||
@@ -159,7 +221,7 @@ fn collect<F: Fn(u32) -> Option<usize>>(
|
||||
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 +229,88 @@ fn collect<F: Fn(u32) -> Option<usize>>(
|
||||
Err(ImportTableError::TooManyDescriptors)
|
||||
}
|
||||
|
||||
/// Parse the delay-load directory of `directory_size` bytes at `directory_rva`.
|
||||
///
|
||||
/// Only descriptors that lie wholly inside the declared directory are read,
|
||||
/// and the directory must hold the empty descriptor that ends the table.
|
||||
/// 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,
|
||||
directory_size: u32,
|
||||
rva_to_offset: impl Fn(u32) -> Option<usize>,
|
||||
) -> (Vec<ImportEntry>, Option<ImportTableError>) {
|
||||
let reader = Reader {
|
||||
bytes,
|
||||
rva_to_offset,
|
||||
};
|
||||
let mut entries = Vec::new();
|
||||
let error = collect_delayed(&reader, directory_rva, directory_size, &mut entries).err();
|
||||
(entries, error)
|
||||
}
|
||||
|
||||
fn collect_delayed<F: Fn(u32) -> Option<usize>>(
|
||||
reader: &Reader<'_, F>,
|
||||
directory_rva: u32,
|
||||
directory_size: u32,
|
||||
entries: &mut Vec<ImportEntry>,
|
||||
) -> Result<(), ImportTableError> {
|
||||
let end = directory_rva
|
||||
.checked_add(directory_size)
|
||||
.ok_or(ImportTableError::OutOfBounds { rva: directory_rva })?;
|
||||
let mut descriptor = directory_rva;
|
||||
for _ in 0..MAX_DESCRIPTORS {
|
||||
if end - descriptor < DELAY_DESCRIPTOR_LEN {
|
||||
return Err(ImportTableError::DelayDirectoryEnd { rva: end });
|
||||
}
|
||||
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)?;
|
||||
// All three are required. The address table holds thunk addresses, so
|
||||
// it cannot stand in for a missing name table.
|
||||
for (field, rva) in [
|
||||
(DelayField::DllName, name_rva),
|
||||
(DelayField::AddressTable, address_rva),
|
||||
(DelayField::NameTable, names_rva),
|
||||
] {
|
||||
if rva == 0 {
|
||||
return Err(ImportTableError::DelayFieldMissing {
|
||||
rva: descriptor,
|
||||
field,
|
||||
});
|
||||
}
|
||||
}
|
||||
// Each must also start in section data, whether or not an import uses it.
|
||||
reader.array::<1>(name_rva)?;
|
||||
reader.array::<8>(address_rva)?;
|
||||
reader.array::<8>(names_rva)?;
|
||||
let module = reader.name(name_rva)?;
|
||||
collect_symbols(reader, &module, names_rva, address_rva, true, entries)?;
|
||||
// The declared end bounds this sum.
|
||||
descriptor += DELAY_DESCRIPTOR_LEN;
|
||||
}
|
||||
Err(ImportTableError::TooManyDescriptors)
|
||||
}
|
||||
|
||||
fn collect_symbols<F: Fn(u32) -> Option<usize>>(
|
||||
reader: &Reader<'_, F>,
|
||||
module: &str,
|
||||
lookup_rva: u32,
|
||||
address_rva: u32,
|
||||
slots_on_disk: bool,
|
||||
entries: &mut Vec<ImportEntry>,
|
||||
) -> Result<(), ImportTableError> {
|
||||
// Without a lookup table the address table holds the same entries on disk.
|
||||
@@ -194,6 +333,10 @@ fn collect_symbols<F: Fn(u32) -> Option<usize>>(
|
||||
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(
|
||||
|
||||
+113
-28
@@ -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<ImportedSymbol>,
|
||||
/// Why the import table could not be read to its end.
|
||||
pub import_error: Option<ImportTableError>,
|
||||
/// 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<ImportedSymbol>,
|
||||
/// Why the delay-load import tables could not be read to their end.
|
||||
pub delay_import_error: Option<ImportTableError>,
|
||||
pub instruction_records: Vec<InstructionRecord>,
|
||||
pub first_unsupported_dbt_insn: Option<InstructionRecord>,
|
||||
}
|
||||
@@ -822,6 +829,30 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// The delay import descriptor is data directory 13. It exists only when
|
||||
// NumberOfRvaAndSizes covers it.
|
||||
let (delay_dir_rva, delay_dir_size) = if size_of_optional_header >= 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(),
|
||||
),
|
||||
u32::from_le_bytes(
|
||||
bytes[opt_offset + 220..opt_offset + 224]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
(0, 0)
|
||||
};
|
||||
|
||||
let section_table_offset = opt_offset + size_of_optional_header;
|
||||
let section_header_size = 40;
|
||||
@@ -960,35 +991,40 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
// Binding accepts only bytes backed by section data; match it exactly.
|
||||
let backed_offset = |rva: u32| {
|
||||
sections.iter().find_map(|section| {
|
||||
let offset = rva.checked_sub(section.virtual_address)?;
|
||||
(offset < section.raw_data_size)
|
||||
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
|
||||
})
|
||||
};
|
||||
let (entries, import_error) = if import_dir_rva == 0 {
|
||||
(Vec::new(), None)
|
||||
} else {
|
||||
// Binding accepts only bytes backed by section data; match it exactly.
|
||||
parse_imports(bytes, import_dir_rva, |rva| {
|
||||
sections.iter().find_map(|section| {
|
||||
let offset = rva.checked_sub(section.virtual_address)?;
|
||||
(offset < section.raw_data_size)
|
||||
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
|
||||
})
|
||||
})
|
||||
parse_imports(bytes, import_dir_rva, backed_offset)
|
||||
};
|
||||
let imports: Vec<ImportedSymbol> = 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, delay_dir_size, 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<ImportedSymbol> = entries.into_iter().map(&describe).collect();
|
||||
let delayed_imports: Vec<ImportedSymbol> = delayed_entries.into_iter().map(&describe).collect();
|
||||
|
||||
// 4. Control-Flow-Aware Static Disassembly
|
||||
//
|
||||
@@ -1124,6 +1160,8 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
tls,
|
||||
imports,
|
||||
import_error,
|
||||
delayed_imports,
|
||||
delay_import_error,
|
||||
instruction_records,
|
||||
first_unsupported_dbt_insn,
|
||||
})
|
||||
@@ -1142,7 +1180,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
|
||||
// 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 +1224,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
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 +1232,34 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
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 +1316,9 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
"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 +1450,16 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
"- **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 +1504,12 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
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.",
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
// 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::{DelayField, 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 DELAY_DIRECTORY_SIZE: usize = DELAY_DIRECTORY_ENTRY + 4;
|
||||
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<String> = 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::<Vec<_>>(),
|
||||
[
|
||||
"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<u8>),
|
||||
usize,
|
||||
ImportTableError,
|
||||
&'static str,
|
||||
);
|
||||
// (name, damage, delayed imports still listed, error, message)
|
||||
let cases: [Case; 13] = [
|
||||
(
|
||||
"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",
|
||||
),
|
||||
(
|
||||
// The second DLL's name table becomes the empty entry that ends the
|
||||
// first one, at RVA 0x2110, so no import reads the address table.
|
||||
"address-table-out-of-range-without-imports",
|
||||
|pe| {
|
||||
put(pe, SECOND_DESCRIPTOR + 16, 0x2110);
|
||||
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::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// RVA 0x2028 is zero padding after the ordinary import directory.
|
||||
"dll-name-empty",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0x2028),
|
||||
2,
|
||||
ImportTableError::MalformedName { rva: 0x2028 },
|
||||
"malformed import name at RVA 0x00002028",
|
||||
),
|
||||
(
|
||||
"dll-name-missing",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0),
|
||||
2,
|
||||
ImportTableError::DelayFieldMissing {
|
||||
rva: 0x2220,
|
||||
field: DelayField::DllName,
|
||||
},
|
||||
"delay-load descriptor at RVA 0x00002220 has no DLL name",
|
||||
),
|
||||
(
|
||||
"address-table-missing",
|
||||
|pe| put(pe, FIRST_DESCRIPTOR + 12, 0),
|
||||
0,
|
||||
ImportTableError::DelayFieldMissing {
|
||||
rva: 0x2200,
|
||||
field: DelayField::AddressTable,
|
||||
},
|
||||
"delay-load descriptor at RVA 0x00002200 has no import address table",
|
||||
),
|
||||
(
|
||||
"name-table-missing",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 16, 0),
|
||||
2,
|
||||
ImportTableError::DelayFieldMissing {
|
||||
rva: 0x2220,
|
||||
field: DelayField::NameTable,
|
||||
},
|
||||
"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 declared_directory_size_bounds_the_table() {
|
||||
// The fixture declares 96 bytes at RVA 0x2200: two descriptors and the
|
||||
// empty one. A descriptor counts only if the declared size holds all of
|
||||
// it, and the size must reach the empty descriptor.
|
||||
let end = |rva| Some(ImportTableError::DelayDirectoryEnd { rva });
|
||||
for (size, listed, error) in [
|
||||
(0, 0, end(0x2200)),
|
||||
(31, 0, end(0x221f)),
|
||||
(32, 2, end(0x2220)),
|
||||
(63, 2, end(0x223f)),
|
||||
(64, 3, end(0x2240)),
|
||||
(95, 3, end(0x225f)),
|
||||
(96, 3, None),
|
||||
(97, 3, None),
|
||||
(0x1000, 3, None),
|
||||
// The directory would run past the end of the address space.
|
||||
(
|
||||
u32::MAX,
|
||||
0,
|
||||
Some(ImportTableError::OutOfBounds { rva: 0x2200 }),
|
||||
),
|
||||
] {
|
||||
let mut pe = FIXTURE.to_vec();
|
||||
put(&mut pe, DELAY_DIRECTORY_SIZE, size);
|
||||
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
|
||||
assert_eq!(rows(&report.imports), ORDINARY, "size {size}");
|
||||
assert_eq!(
|
||||
rows(&report.delayed_imports),
|
||||
DELAYED[..listed],
|
||||
"size {size}"
|
||||
);
|
||||
assert_eq!(report.delay_import_error, error, "size {size}");
|
||||
}
|
||||
assert_eq!(
|
||||
ImportTableError::DelayDirectoryEnd { rva: 0x2240 }.to_string(),
|
||||
"delay-load directory ends at RVA 0x00002240 before its empty descriptor"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endless_delay_table_is_refused() {
|
||||
// Every descriptor RVA maps onto the same 32 bytes, so the table never
|
||||
// reaches its empty entry within the megabyte it declares. The descriptor
|
||||
// names module "a" at RVA 0x1000, an empty name table at RVA 0x2000 and an
|
||||
// address table at RVA 0x3000.
|
||||
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, 0x10_0000, |rva| match rva {
|
||||
0x1000..0x1002 => Some(32 + (rva - 0x1000) as usize),
|
||||
0x2000..0x2008 => Some(40 + (rva - 0x2000) as usize),
|
||||
0x3000..0x3008 => Some(40 + (rva - 0x3000) 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());
|
||||
}
|
||||
}
|
||||
+31
-10
@@ -69,16 +69,37 @@ 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`. `xenora imports sync`
|
||||
leaves delayed rows out of its backlog for the same reason.
|
||||
|
||||
The probe reads only descriptors that lie wholly inside the directory's
|
||||
declared size, and expects that size to hold the empty descriptor that ends the
|
||||
table. It reads descriptors whose `RvaBased` attribute is set, and requires each
|
||||
one's DLL name, import address table and import name table to be present and to
|
||||
start in section data. A table that breaks one of these rules, sets a reserved
|
||||
attribute bit, is truncated, or uses 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
|
||||
|
||||
Binary file not shown.
@@ -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("<I", data, 0x3C, 0x80)
|
||||
data[0x80:0x84] = b"PE\0\0"
|
||||
# AMD64, three sections, 240-byte optional header; relocations stripped,
|
||||
# executable, large-address-aware.
|
||||
pack_into("<HHIIIHH", data, 0x84, 0x8664, 3, 0, 0, 0, 240, 0x23)
|
||||
opt = 0x98
|
||||
pack_into("<H", data, opt, 0x20B)
|
||||
pack_into("<III", data, opt + 4, 0x200, 0x600, 0)
|
||||
pack_into("<IIQII", data, opt + 16, TEXT, TEXT, BASE, 0x1000, 0x200)
|
||||
pack_into("<HHHHHH", data, opt + 40, 6, 0, 0, 0, 6, 0)
|
||||
pack_into("<II", data, opt + 56, 0x4000, 0x400)
|
||||
# Console subsystem; NX compatible at a fixed base.
|
||||
pack_into("<HH", data, opt + 68, 3, 0x100)
|
||||
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
|
||||
# Import table, import address table and delay import descriptor.
|
||||
for index, rva, size in (
|
||||
(1, IMPORT_DIRECTORY, 40),
|
||||
(12, IAT, 24),
|
||||
(13, DELAY_DIRECTORY, 96),
|
||||
):
|
||||
pack_into("<II", data, opt + 112 + index * 8, rva, size)
|
||||
|
||||
sections = (
|
||||
(b".text", TEXT, 0x200, 0x60000020),
|
||||
(b".rdata", RDATA, 0x400, 0x40000040),
|
||||
(b".data", DATA, 0x200, 0xC0000040),
|
||||
)
|
||||
for index, (name, rva, size, characteristics) in enumerate(sections):
|
||||
pack_into(
|
||||
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, size, rva,
|
||||
size, offset(rva), 0, 0, 0, 0, characteristics,
|
||||
)
|
||||
|
||||
# Entry returns. The stubs are INT3 because the fixture is never run.
|
||||
data[offset(TEXT)] = 0xC3
|
||||
for stub in STUBS:
|
||||
data[offset(stub)] = 0xCC
|
||||
|
||||
# One ordinary DLL: a named import and ordinal 3.
|
||||
put(IMPORT_DIRECTORY, "<IIIII", LOOKUP, 0, 0, ORDINARY_DLL, IAT)
|
||||
for table in (LOOKUP, IAT):
|
||||
put(table, "<QQQ", ORDINARY_NAME, ORDINAL | 3, 0)
|
||||
text(ORDINARY_DLL, b"fixture-ordinary.dll")
|
||||
text(ORDINARY_NAME + 2, b"OrdinaryByName")
|
||||
|
||||
# Two delay-loaded DLLs. Attributes bit 0 marks the fields as RVAs.
|
||||
put(DELAY_DIRECTORY, "<IIIIIIII",
|
||||
1, DELAY_DLL_A, HANDLE_A, DELAY_IAT_A, NAMES_A, 0, 0, 0)
|
||||
put(DELAY_DIRECTORY + 32, "<IIIIIIII",
|
||||
1, DELAY_DLL_B, HANDLE_B, DELAY_IAT_B, NAMES_B, 0, 0, 0)
|
||||
put(NAMES_A, "<QQQ", DELAY_NAME_A, ORDINAL | 7, 0)
|
||||
put(NAMES_B, "<QQ", DELAY_NAME_B, 0)
|
||||
text(DELAY_DLL_A, b"fixture-delay-a.dll")
|
||||
text(DELAY_DLL_B, b"fixture-delay-b.dll")
|
||||
text(DELAY_NAME_A + 2, b"DelayedAlpha")
|
||||
text(DELAY_NAME_B + 2, b"DelayedBeta")
|
||||
put(DELAY_IAT_A, "<QQQ", BASE + STUBS[0], BASE + STUBS[1], 0)
|
||||
put(DELAY_IAT_B, "<QQ", BASE + STUBS[2], 0)
|
||||
return data
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
path = Path(__file__).with_suffix(".exe")
|
||||
if args.check:
|
||||
if path.read_bytes() != fixture():
|
||||
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
|
||||
else:
|
||||
path.write_bytes(fixture())
|
||||
Reference in new issue
Block a user