mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 11:00:43 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
044f036ea5 | ||
|
|
a533d8107e | ||
|
|
60f4f38da1 |
No files matched your search
@@ -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 => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -89,6 +89,14 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
pc += 1;
|
||||
}
|
||||
|
||||
// Recognize the operand-size override for C7 without changing how the
|
||||
// probe classifies prefixes on unrelated opcodes.
|
||||
let operand_override =
|
||||
b0 == 0x66 && matches!(slice.get(pc..), Some([0xc7, ..] | [0x40..=0x4f, 0xc7, ..]));
|
||||
if operand_override {
|
||||
b0 = slice[pc];
|
||||
pc += 1;
|
||||
}
|
||||
let mut rex_w = false;
|
||||
let mut op = b0;
|
||||
|
||||
@@ -142,6 +150,51 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
is_interp = true;
|
||||
fall_through = false;
|
||||
}
|
||||
0xC7 => {
|
||||
if let Some(&modrm) = slice.get(pc) {
|
||||
pc += 1;
|
||||
let mode = modrm >> 6;
|
||||
let rm = modrm & 7;
|
||||
if modrm & 0x38 != 0 {
|
||||
mnemonic = format!("unsupported c7 extension (modrm 0x{modrm:02x})");
|
||||
notes = "unknown instruction boundary".into();
|
||||
fall_through = false;
|
||||
} else {
|
||||
pc += modrm_extra_len(modrm, slice, pc);
|
||||
let imm16 = operand_override && !rex_w;
|
||||
let imm_len = if imm16 { 2 } else { 4 };
|
||||
if let Some(imm) = slice.get(pc..pc + imm_len) {
|
||||
pc += imm_len;
|
||||
let (width, value) = if imm16 {
|
||||
(16, i32::from(i16::from_le_bytes(imm.try_into().unwrap())))
|
||||
} else {
|
||||
(
|
||||
if rex_w { 64 } else { 32 },
|
||||
i32::from_le_bytes(imm.try_into().unwrap()),
|
||||
)
|
||||
};
|
||||
mnemonic = format!("mov r/m{width}, {value} (modrm 0x{modrm:02x})");
|
||||
// The native C7 memory path always writes eight bytes and
|
||||
// does not apply segment bases or decode a SIB byte.
|
||||
is_dbt = mode == 3
|
||||
|| (mode == 0 && rm != 4 && rex_w && !matches!(slice[0], 0x64 | 0x65));
|
||||
is_dbt &= !operand_override;
|
||||
if !is_dbt {
|
||||
notes = "MOV immediate operand form lacks native semantics".into();
|
||||
}
|
||||
} else {
|
||||
pc = slice.len();
|
||||
fall_through = false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fall_through = false;
|
||||
}
|
||||
if mnemonic.is_empty() {
|
||||
mnemonic = "truncated c7".into();
|
||||
notes = "incomplete MOV immediate encoding".into();
|
||||
}
|
||||
}
|
||||
0xC2 => {
|
||||
// RETN imm16
|
||||
if pc + 2 <= slice.len() {
|
||||
@@ -443,8 +496,10 @@ fn modrm_extra_len(modrm: u8, slice: &[u8], after_modrm: usize) -> usize {
|
||||
extra += 1; // disp8
|
||||
} else if mode == 2 {
|
||||
extra += 4; // disp32
|
||||
} else if mode == 0 && rm == 5 {
|
||||
extra += 4; // RIP-relative disp32
|
||||
} else if mode == 0
|
||||
&& (rm == 5 || (rm == 4 && slice.get(after_modrm).is_some_and(|sib| sib & 7 == 5)))
|
||||
{
|
||||
extra += 4; // RIP-relative or SIB with no base
|
||||
}
|
||||
// Clamp to what's actually available
|
||||
extra.min(slice.len().saturating_sub(after_modrm))
|
||||
@@ -1048,7 +1103,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\n",
|
||||
"module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding\n",
|
||||
);
|
||||
let mut missing_csv = String::from("module,symbol_or_ordinal,iat_rva\n");
|
||||
let mut modules = BTreeSet::new();
|
||||
@@ -1058,6 +1113,9 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
let mut counts = BTreeMap::<&str, usize>::new();
|
||||
let mut clusters = BTreeMap::<(u8, &str), (usize, usize)>::new();
|
||||
let mut aliases = 0;
|
||||
// The runner admits exactly these bytes and installs a private draw handler.
|
||||
let trusted_fixture = bytes == include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
let mut trusted_runner_slots = 0;
|
||||
let mut missing = 0;
|
||||
for imp in &report.imports {
|
||||
let module_key = imp.dll.to_ascii_lowercase();
|
||||
@@ -1071,6 +1129,10 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
let module = imp.dll.replace('"', "\"\"");
|
||||
let symbol = imp.symbol.replace('"', "\"\"");
|
||||
let key = format!("\"{module}\",\"{symbol}\",0x{:08x}", imp.iat_rva);
|
||||
let trusted_binding = trusted_fixture
|
||||
&& imp.dll.eq_ignore_ascii_case("xenora.dll")
|
||||
&& imp.symbol == "fixture_draw";
|
||||
trusted_runner_slots += usize::from(trusted_binding);
|
||||
let status = imp.coverage_label();
|
||||
let canonical = imp.canonical_module.as_deref().unwrap_or("");
|
||||
let is_alias = imp.canonical_module.is_some() && !imp.dll.eq_ignore_ascii_case(canonical);
|
||||
@@ -1086,7 +1148,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}",
|
||||
"{key},{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding}",
|
||||
imp.category, imp.is_supported
|
||||
);
|
||||
if !imp.is_supported {
|
||||
@@ -1140,6 +1202,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
"total_imports": {},
|
||||
"imported_dlls_count": {},
|
||||
"unresolved_imports": {},
|
||||
"trusted_runner_binding_slots": {trusted_runner_slots},
|
||||
"distinct_import_keys": {},
|
||||
"distinct_symbol_names_and_scoped_ordinals": {},
|
||||
"canonical_registered_services": {},
|
||||
@@ -1207,7 +1270,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
let _ = writeln!(md, "- **Section Alignment**: `4096` bytes");
|
||||
let _ = writeln!(md, "- **File Alignment**: `512` bytes\n");
|
||||
|
||||
let _ = writeln!(md, "## Sections Census (10)");
|
||||
let _ = writeln!(md, "## Sections Census ({})", report.parsed.sections.len());
|
||||
for s in &report.parsed.sections {
|
||||
let _ = writeln!(
|
||||
md,
|
||||
@@ -1274,6 +1337,13 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
"- **Unresolved standard import thunks**: `{missing}`. See `missing_imports.csv`. A registered handler may be a stub.\n"
|
||||
);
|
||||
|
||||
if trusted_runner_slots > 0 {
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"The trusted runner supplies `xenora.dll!fixture_draw` for this fixture. The standard registry counts above exclude that private handler.\n"
|
||||
);
|
||||
}
|
||||
|
||||
let _ = writeln!(md, "## First Static DBT Blocker");
|
||||
if let Some(insn) = &report.first_unsupported_dbt_insn {
|
||||
let hex_bytes = insn
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -199,3 +199,166 @@ fn probe_distinguishes_aliases_from_unavailable_services() {
|
||||
assert!(json.contains("\"recognized_unsupported_slots\": 1"));
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trusted_runner_callback_and_report_match_the_fixture() {
|
||||
let pe = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
let path = std::env::temp_dir().join(format!("xenora-probe-trusted-{}", std::process::id()));
|
||||
let report = run_probe_and_export(pe, &path, &ProbeConfig::default()).unwrap();
|
||||
let read = |name| std::fs::read_to_string(path.join(name)).unwrap();
|
||||
let md = read("candidate_static_report.md");
|
||||
let json = read("candidate_static_report.json");
|
||||
let imports = read("imports.csv");
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
|
||||
let callback: Vec<_> = report
|
||||
.instruction_records
|
||||
.iter()
|
||||
.filter(|i| i.rva >= 0x1040)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
callback.iter().map(|i| i.rva).collect::<Vec<_>>(),
|
||||
[0x1040, 0x1047, 0x104e]
|
||||
);
|
||||
assert_eq!(callback[1].bytes, [0x48, 0xc7, 0, 17, 0, 0, 0]);
|
||||
assert!(callback[1].is_supported_dbt);
|
||||
assert!(!callback[1].is_supported_interp);
|
||||
assert!(report.first_unsupported_dbt_insn.is_none());
|
||||
assert!(md.contains("Sections Census (4)"));
|
||||
assert!(json.contains("\"sections_count\": 4"));
|
||||
assert!(!report.imports[0].is_supported);
|
||||
assert!(
|
||||
imports
|
||||
.lines()
|
||||
.any(|line| line.contains("fixture_draw") && line.ends_with(",true"))
|
||||
);
|
||||
assert!(json.contains("\"trusted_runner_binding_slots\": 1"));
|
||||
assert!(json.contains("\"unresolved_imports\": 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_consumes_complete_c7_operands_even_when_native_support_is_missing() {
|
||||
for (encoding, supported) in [
|
||||
(&[0x48, 0xc7, 0x05, 0, 0, 0, 0, 17, 0, 0, 0][..], true),
|
||||
(&[0xc7, 0xc0, 17, 0, 0, 0], true),
|
||||
(&[0x66, 0xc7, 0xc0, 17, 0], false),
|
||||
(&[0xc7, 0x00, 17, 0, 0, 0], false),
|
||||
(&[0x48, 0xc7, 0x40, 4, 17, 0, 0, 0], false),
|
||||
(&[0x48, 0xc7, 0x04, 0x25, 0, 0, 0, 0, 17, 0, 0, 0], false),
|
||||
] {
|
||||
let mut pe = create_synthetic_probe_pe();
|
||||
let end = 0x200 + encoding.len();
|
||||
pe[0x200..end].copy_from_slice(encoding);
|
||||
pe[end] = 0xcc;
|
||||
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
|
||||
let records = report.instruction_records;
|
||||
assert_eq!(records.len(), 2);
|
||||
assert_eq!(records[0].bytes, encoding);
|
||||
assert_eq!(records[0].is_supported_dbt, supported);
|
||||
assert_eq!(records[1].rva, 0x1000 + encoding.len() as u32);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user