Compare commits

...
Author SHA1 Message Date
ates 044f036ea5 Implement 32-bit and 64-bit BSWAP in both CPU engines
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 10:57:26 +03:00
ates a533d8107e Test cross-format probe reports against fixture counts and offsets
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 10:16:45 +03:00
4 changed files with 205 additions and 9 deletions

No files matched your search

+14 -9
View File
@@ -276,16 +276,21 @@ impl<'a> Interpreter<'a> {
// HLT: Halt execution
0xF4 => Ok(Some(ExitReason::Halt)),
// SYSCALL: 0x0F 0x05
0x0F => {
let second = self.fetch_u8()?;
if second == 0x05 {
let syscall_num = self.cpu.get(Register::Rax);
Ok(Some(ExitReason::Syscall(syscall_num)))
} else {
Err(ExitReason::IllegalInstruction(second))
0x0F => match self.fetch_u8()? {
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
op @ 0xC8..=0xCF => {
let reg = Register::from_index((op & 7) | (u8::from(rex_b) << 3));
let value = self.cpu.get(reg);
let reversed = if rex_w {
value.swap_bytes()
} else {
u64::from((value as u32).swap_bytes())
};
self.cpu.set(reg, reversed);
Ok(None)
}
}
op => Err(ExitReason::IllegalInstruction(op)),
},
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
0xB8..=0xBF => {
+10
View File
@@ -1077,6 +1077,16 @@ impl DbtEngine {
cur_rip += 1;
match op2 {
// BSWAP r32/r64: the register is encoded in the opcode.
0xC8..=0xCF => {
insn_count += 1;
let reg = (op2 & 7) | (u8::from(rex_b) << 3);
let offset = u32::from(reg) * 8;
asm.ldr_uoff_64(X9, X19, offset);
// REV X9, X9 or REV W9, W9. A W write clears the upper half.
asm.emit(if rex_w { 0xdac0_0d29 } else { 0x5ac0_0929 });
asm.str_uoff_64(X9, X19, offset);
}
// Jcc rel32 (0x0F 0x80..=0x8F)
0x80..=0x8F => {
insn_count += 1;
+78
View File
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
fn check_bswap(native: bool) {
const ENTRY: u64 = 0x1000;
const INPUT: u64 = 0x1122_3344_5566_7788;
for reg in 0_u8..16 {
for width in [16, 32, 64] {
let wide = width == 64;
let mut code = Vec::new();
if width == 16 {
code.push(0x66);
}
let rex = 0x40 | (u8::from(wide) << 3) | (reg >> 3);
if rex != 0x40 {
code.push(rex);
}
code.extend([0x0f, 0xc8 + (reg & 7)]);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr.fill(0xdead_beef);
cpu.gpr[reg as usize] = INPUT;
cpu.flags = RFlags {
cf: wide,
zf: !wide,
sf: wide,
of: !wide,
};
let flags = cpu.flags;
let mut expected = cpu.gpr;
let result = if native {
DbtEngine::new(16 * 1024)
.unwrap()
.run(&mut cpu, &mut memory, 1)
} else {
Interpreter::new(cpu, &mut memory, 1).run()
};
if width == 16 {
assert!(matches!(
result.exit_reason,
ExitReason::IllegalInstruction(_)
));
assert_eq!(result.instructions_executed, 0);
} else {
assert_eq!(
result.exit_reason,
ExitReason::StepLimitExceeded,
"{code:02x?}"
);
assert_eq!(result.instructions_executed, 1);
assert_eq!(result.final_state.rip, ENTRY + code.len() as u64);
expected[reg as usize] = if wide {
0x8877_6655_4433_2211
} else {
0x8877_6655
};
}
assert_eq!(result.final_state.gpr, expected);
assert_eq!(result.final_state.flags, flags);
}
}
}
#[test]
fn interpreter_bswap() {
check_bswap(false);
}
#[test]
fn native_bswap() {
check_bswap(true);
}
+103
View File
@@ -259,3 +259,106 @@ fn probe_consumes_complete_c7_operands_even_when_native_support_is_missing() {
assert!(!records[1].is_supported_dbt);
}
}
#[test]
fn exported_reports_agree_across_fixtures_and_blocker_locations() {
let dir =
std::env::temp_dir().join(format!("xenora-report-consistency-{}", std::process::id()));
// (file offset, RVA) for a reachable instruction immediately after a MOV.
for (fixture, file_offset, rva, sections, imports) in [
(create_synthetic_probe_pe(), 0x209, 0x1009_u32, 1, 0),
(
include_bytes!("../../../fixtures/pe/trusted-runner.exe").to_vec(),
0x44e,
0x104e,
4,
1,
),
] {
assert_eq!(fixture[file_offset], 0xc3);
for padding in [None, Some(0), Some(1), Some(7)] {
let mut pe = fixture.clone();
let blocker = padding.map(|n| {
pe[file_offset..file_offset + n].fill(0x90);
pe[file_offset + n] = 0xcc;
rva + n as u32
});
run_probe_and_export(&pe, &dir, &ProbeConfig::default()).unwrap();
let read = |name| std::fs::read_to_string(dir.join(name)).unwrap();
let md = read("candidate_static_report.md");
let json = read("candidate_static_report.json");
let cpu = read("cpu_coverage.csv");
let import_csv = read("imports.csv");
std::fs::remove_dir_all(&dir).unwrap();
let json_field = |name: &str| {
let prefix = format!("\"{name}\": ");
json.lines()
.find_map(|line| line.trim().strip_prefix(&prefix))
.unwrap()
.trim_end_matches(',')
.trim_matches('"')
};
assert_eq!(json_field("sections_count"), sections.to_string());
assert!(
md.lines()
.any(|line| line == format!("## Sections Census ({sections})"))
);
assert_eq!(
md.lines()
.filter(|line| line.contains(" VirtualSize: "))
.count(),
sections
);
assert_eq!(json_field("total_imports"), imports.to_string());
assert!(
md.lines()
.any(|line| line == format!("- **Total Imported Thunks**: `{imports}`"))
);
assert_eq!(import_csv.lines().skip(1).count(), imports);
let expected = blocker.map(|addr| format!("0x{addr:08x}"));
assert_eq!(
json_field("first_unsupported_dbt_rva"),
expected.as_deref().unwrap_or("none")
);
let md_rvas: Vec<_> = md
.lines()
.filter_map(|line| {
line.strip_prefix("- **RVA**: `")?
.split_once('`')
.map(|(addr, _)| addr)
})
.collect();
assert_eq!(md_rvas, expected.iter().collect::<Vec<_>>());
// The first columns precede quoted fields. Read the support flags from
// the closing quote of the mnemonic, which can itself contain commas.
let mut unsupported = Vec::new();
let mut tail = Vec::new();
for row in cpu.lines().skip(1) {
let (addr, rest) = row.split_once(',').unwrap();
let (_, fields) = rest.split_once(",\"").unwrap();
let (bytes, mnemonic) = fields.split_once("\",\"").unwrap();
let (_, flags) = mnemonic.split_once("\",").unwrap();
if flags.split(',').next() == Some("false") {
unsupported.push(addr);
}
let address = u32::from_str_radix(addr.strip_prefix("0x").unwrap(), 16).unwrap();
if address >= rva {
tail.push((address, bytes));
}
}
assert_eq!(unsupported, expected.iter().collect::<Vec<_>>());
let mut expected_tail = Vec::new();
if let Some(end) = blocker {
expected_tail.extend((rva..end).map(|addr| (addr, "90")));
expected_tail.push((end, "cc"));
} else {
expected_tail.push((rva, "c3"));
}
assert_eq!(tail, expected_tail);
}
}
}