loader, cli: bound delay-load tables by their declared size (#244)

Address review on the delay-import probe change:

- Read only descriptors inside the delay import directory's declared
  size, and require that size to hold the terminating empty descriptor.
- Require each descriptor's DLL name, import address table and import
  name table to be present and to start in section data, with a
  diagnostic naming the missing field.
- Leave delayed rows out of the xenora imports sync backlog, so its
  totals stay ordinary-only.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
This commit is contained in:
zachdoxsee committed 2026-11-24 16:28:02 +01:00
1 parent b174b45bed
commit db40a1307d
7 files changed
+226 -37

No files matched your search

+1 -1
View File
@@ -15,7 +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 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).
+9 -3
View File
@@ -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();
+35
View File
@@ -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}");
}
+62 -13
View File
@@ -49,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.
@@ -72,8 +90,14 @@ pub enum ImportTableError {
DelayVirtualAddresses {
rva: u32,
},
/// The delay-load descriptor at this RVA has no import name table.
DelayNamesMissing {
/// 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,
@@ -102,9 +126,12 @@ impl fmt::Display for ImportTableError {
f,
"delay-load descriptor at RVA 0x{rva:08x} holds virtual addresses, not RVAs, and is not read"
),
Self::DelayNamesMissing { rva } => write!(
Self::DelayFieldMissing { rva, field } => {
write!(f, "delay-load descriptor at RVA 0x{rva:08x} has no {field}")
}
Self::DelayDirectoryEnd { rva } => write!(
f,
"delay-load descriptor at RVA 0x{rva:08x} has no import name table"
"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"),
@@ -202,13 +229,16 @@ fn collect<F: Fn(u32) -> Option<usize>>(
Err(ImportTableError::TooManyDescriptors)
}
/// Parse the delay-load directory at `directory_rva`.
/// 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 {
@@ -216,18 +246,24 @@ pub fn parse_delay_imports(
rva_to_offset,
};
let mut entries = Vec::new();
let error = collect_delayed(&reader, directory_rva, &mut entries).err();
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 {
// Reading the whole descriptor also proves its field RVAs do not overflow.
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] {
@@ -243,15 +279,28 @@ fn collect_delayed<F: Fn(u32) -> Option<usize>>(
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 });
// 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)?;
descriptor = descriptor
.checked_add(DELAY_DESCRIPTOR_LEN)
.ok_or(ImportTableError::OutOfBounds { rva: descriptor })?;
// The declared end bounds this sum.
descriptor += DELAY_DESCRIPTOR_LEN;
}
Err(ImportTableError::TooManyDescriptors)
}
+14 -7
View File
@@ -831,20 +831,27 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
};
// The delay import descriptor is data directory 13. It exists only when
// NumberOfRvaAndSizes covers it.
let delay_dir_rva = if size_of_optional_header >= 224
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 + 216..opt_offset + 220]
.try_into()
.unwrap(),
),
u32::from_le_bytes(
bytes[opt_offset + 220..opt_offset + 224]
.try_into()
.unwrap(),
),
)
} else {
0
(0, 0)
};
let section_table_offset = opt_offset + size_of_optional_header;
@@ -1000,7 +1007,7 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
let (delayed_entries, delay_import_error) = if delay_dir_rva == 0 {
(Vec::new(), None)
} else {
parse_delay_imports(bytes, delay_dir_rva, backed_offset)
parse_delay_imports(bytes, delay_dir_rva, delay_dir_size, backed_offset)
};
let describe = |entry: ImportEntry| {
let binding = registry.resolve(&entry.module, &entry.name);
+94 -8
View File
@@ -8,7 +8,7 @@
//! 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::import_table::{DelayField, ImportTableError, parse_delay_imports};
use xenora_loader::probe::{
ImportedSymbol, ProbeConfig, ProbeReport, probe_pe_bytes, run_probe_and_export,
};
@@ -31,6 +31,7 @@ const DELAYED: [Row; 3] = [
// 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;
@@ -206,7 +207,7 @@ fn malformed_delay_tables_are_diagnosed_and_ordinary_imports_kept() {
&'static str,
);
// (name, damage, delayed imports still listed, error, message)
let cases: [Case; 9] = [
let cases: [Case; 13] = [
(
"directory-out-of-range",
|pe| put(pe, DELAY_DIRECTORY_ENTRY, 0x9000),
@@ -244,18 +245,61 @@ fn malformed_delay_tables_are_diagnosed_and_ordinary_imports_kept() {
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::MalformedName { rva: 0x9000 },
"malformed import name at RVA 0x00009000",
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::DelayNamesMissing { rva: 0x2220 },
ImportTableError::DelayFieldMissing {
rva: 0x2220,
field: DelayField::NameTable,
},
"delay-load descriptor at RVA 0x00002220 has no import name table",
),
(
@@ -302,20 +346,62 @@ fn malformed_delay_tables_are_diagnosed_and_ordinary_imports_kept() {
}
}
#[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. The descriptor names module "a" at RVA 0x1000
// and an empty name table at RVA 0x2000.
// 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, |rva| match rva {
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,
});
+11 -5
View File
@@ -89,11 +89,17 @@ 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.
`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