Compare commits

...
Author SHA1 Message Date
Swastick Chowdhury c4d0b6c000 loader: stop the static probe panicking on truncated PE names (#270)
`probe_pe_bytes` panicked on a truncated PE instead of returning an error or
reporting the import as unreadable.

The cause was in `crates/loader/src/probe.rs`. `rva_to_offset` maps an RVA to
a file offset using the section header, so on a truncated file the computed
offset can point past the end of the buffer. The loop that finds the
terminating NUL then stopped at `bytes.len()`, leaving `no > end`, and the
slice `bytes[no..end]` panicked with "range start index 1632 out of range for
slice of length 1556".

Fix both name reads:

- `rva_to_offset` now returns `None` when the computed offset is at or past
  the end of the file, because such an offset is not readable. This applies to
  every caller, so the relocation, TLS, thunk and disassembly paths are
  covered by the same rule.
- A new `read_c_string` helper reads a NUL-terminated string and returns
  `None` when the string starts outside the buffer. It replaces the
  hand-written scan in the DLL-name read and in the symbol-name read, which
  also had an unchecked `ho + 2` for the two-byte import hint.

A name that cannot be read is reported as `UNKNOWN.dll` or `UNKNOWN_SYM`,
which is what the probe already did when the RVA did not resolve at all. The
probe stays read-only and still performs no guest execution.

Add a regression test that truncates the in-repo `fixtures/pe/trusted-runner.exe`
at every length from 1 to the file size and asserts that `probe_pe_bytes`
never panics. The reported range was 1,556 to 1,665 bytes; the sweep covers
the whole file, so it also covers the other name and thunk reads that the
report noted might share the pattern. The test fails against the unmodified
probe with the reported panic and passes with this change.

Closes #270

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:57:26 +05:30
Ranveer Soni 3bdc43d3ad Merge pull request #281 from Swastickc/task/66-movsx-movzx
loader: implement MOVZX and MOVSX in the interpreter (#66)
2026-11-24 17:47:21 +05:30
Ranveer Soni fa434d7174 Merge pull request #282 from Swastickc/task/279-native-app-gate5
app: persistent GPU resources, dynamic texture updates, and resource retirement (#279)
2026-11-24 17:46:43 +05:30
Ranveer Soni ed657ad802 Merge pull request #280 from Swastickc/task/72-segment-override
loader: add the FS and GS segment base to RIP-relative operands in the DBT (#72)
2026-11-24 17:46:25 +05:30
Ranveer Soni b49ec43ddc Merge branch 'main' into task/72-segment-override 2026-11-24 17:46:11 +05:30
Ranveer Soni d00c787544 Merge pull request #283 from Swastickc/task/65-movsx-dest-width
loader: clear the upper half of a 32-bit MOVSX destination (#65)
2026-11-24 17:45:40 +05:30
Swastick Chowdhury f6dfe58695 loader: implement MOVZX and MOVSX in the interpreter (#66)
The native DBT translator implements the four extension opcodes MOVZX r32/r64,
r/m8 (0F B6), MOVZX r32/r64, r/m16 (0F B7), MOVSX r32/r64, r/m8 (0F BE) and
MOVSX r32/r64, r/m16 (0F BF), with both register and memory source operands.
The interpreter implemented none of them: its 0x0F handler covered only SYSCALL
(0F 05) and BSWAP (0F C8..CF), so any of the four opcodes exited with
IllegalInstruction and the two execution paths accepted different instruction
sets for the same bytes.

Implement them in the interpreter:

- The source width follows the opcode, so 0F B6 and 0F BE read one byte and
  0F B7 and 0F BF read one word.
- The destination width follows REX.W. Without REX.W the destination is 32
  bits and its upper half is cleared; with REX.W it is 64 bits.
- MOVZX zero-extends, so both destination widths hold the same value.
- MOVSX sign-extends to the destination width, so a 32-bit destination keeps
  the sign in bits 31:0 with the upper half cleared, while a 64-bit
  destination keeps the sign extension across all 64 bits.

The effective-address computation shared by the memory forms of MOV,
MOVZX and MOVSX is extracted into an `effective_address` method so both
instruction families use one implementation. That is a pure refactor: the
address computation itself is unchanged.

Add six regression tests in crates/loader/tests/bootstrap.rs covering the
register and the memory source forms independently, both destination widths,
and the sign-extension boundary values. Every encoding was produced by LLVM
23.1.6 llvm-mc -show-encoding and the expected values follow the Intel SDM
rules for MOVZX and MOVSX.

All six tests fail against the unmodified interpreter and pass with this
change.

A related defect in the native DBT translator was found while writing these
tests: its MOVSX paths sign-extend to 64 bits unconditionally, so a 32-bit
destination keeps the sign extension in bits 63:32 instead of having them
cleared. That belongs to #65, which permits the translator files, and is
reported there rather than fixed here.

Closes #66

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:37:02 +05:30
Swastick Chowdhury b12aa502a2 loader: add the FS and GS segment base to RIP-relative operands in the DBT (#72)
The native DBT translator computed the RIP-relative address and passed it
straight to the memory helper, without adding the FS or GS segment base. The
non-RIP-relative path went through emit_effective_address, which does add it,
so the two paths in the same translator disagreed with each other, and the
interpreter in crates/loader/src/cpu.rs disagreed with both.

Per the Intel SDM Volume 3A, section 3.4.4, "When FS and GS segment overrides
are used in 64-bit mode, their respective base addresses are used in the
linear address calculation: (FS or GS).base + index + displacement", and the
AMD64 Architecture Programmer's Manual Volume 1, section 2.2.3.3, "Use of the
FS or GS prefix causes their respective segment bases to be added to the
effective address calculation." The base is added for every addressing form,
so the RIP-relative form needs it too.

The segment base is a runtime guest value, so it cannot be folded into the
translation-time immediate. The addition is factored into emit_segment_base,
which reads the base from the guest CPU state at run time, and is now called
from the RIP-relative MOV paths as well as from emit_effective_address.

Add six regression tests in the dbt test module:

- fs_segment_override_adds_the_fs_base_to_the_address: a segment-relative
  store and load land at the FS base plus the displacement, not at the bare
  displacement.
- gs_segment_override_adds_the_gs_base_to_the_address: the GS base is used,
  and a distinct FS base is left untouched.
- rip_relative_segment_override_adds_the_segment_base: the RIP-relative form
  adds the segment base. This test fails without the fix.
- segment_relative_access_to_an_unmapped_address_faults: a segment-relative
  access outside the mapped regions faults and reports the segment-adjusted
  address.
- interpreter_and_native_dbt_agree_on_segment_relative_addressing: the same
  program runs through the interpreter and the native DBT and produces the same
  state and the same memory writes.
- redundant_fs_and_gs_overrides_are_handled_the_same_by_both_paths: an
  instruction carrying both an FS and a GS override is architecturally
  undefined, so this pins the local rule that both paths prefer GS and that
  they agree with each other.

Every encoding was produced by LLVM 23.1.6 llvm-mc -show-encoding, and the
expected addresses were derived from the SDM rule above.

Closes #72

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:36:38 +05:30
Swastick Chowdhury 20780eab24 loader: clear the upper half of a 32-bit MOVSX destination (#65)
The native DBT translator sign-extended to 64 bits unconditionally and stored
the full 64-bit result, so a 32-bit MOVSX destination kept the sign extension
in bits 63:32 instead of having them cleared.

Before, both MOVSX paths did this:

    asm.sxtb_64(X9, X9);   // or sxth_64
    asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8);

`sxtb_64` is `SBFM Xd, Xn, #0, #7`, which sign-extends the byte to 64 bits,
and `str_uoff_64` writes all 64 bits of the destination register.

That is correct for the REX.W form `movsbq rax, bl`, but the Intel SDM
requires a 32-bit result for the 32-bit destination form `movsbl eax, bl`. The
translator therefore left `rax = 0xFFFFFFFFFFFFFFFF` where the architecture
requires `rax = 0x00000000FFFFFFFF`.

Select the sign-extension width from REX.W:

- REX.W set: keep the 64-bit extension, which is already correct.
- REX.W clear: sign-extend to 32 bits, which also clears bits 63:32 of the
  destination because the 32-bit form writes a W register.

This needs two new assembler instructions, `sxtb_32` and `sxth_32`, which are
the 32-bit forms of the existing `sxtb_64` and `sxth_64`:

    sxtb_32: SBFM Wd, Wn, #0, #7   (0x13001c00)
    sxth_32: SBFM Wd, Wn, #0, #15  (0x13003c00)

Both encodings were confirmed against LLVM 23.1.6 `llvm-mc -triple=aarch64
-show-encoding`.

The MOVZX paths are unchanged: a zero extension produces the same value at
both destination widths, because the 32-bit form already clears the upper half.

Add three regression tests in the dbt test module covering the register and
memory source forms and the byte and word sources, each at both destination
widths. Every encoding was produced by LLVM 23.1.6 llvm-mc -show-encoding and
the expected values follow the Intel SDM rules for MOVSX.

All three tests fail against the unmodified translator and pass with this
change.

Closes #65

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:35:49 +05:30
6 changed files with 574 additions and 56 deletions

No files matched your search

+16
View File
@@ -183,11 +183,27 @@ impl Arm64Assembler {
self.emit(0x93401c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
}
/// SXTB (32-bit/sign-extended): SXTB Wd, Wn (SBFM Wd, Wn, #0, #7)
///
/// Writing the 32-bit destination form clears bits 63:32 of the
/// destination register, which is what a 32-bit x86 destination requires.
pub fn sxtb_32(&mut self, wd: u8, wn: u8) {
self.emit(0x13001c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
}
/// SXTH (64-bit/sign-extended): SXTH Xd, Wn (SBFM Xd, Xn, #0, #15)
pub fn sxth_64(&mut self, xd: u8, wn: u8) {
self.emit(0x93403c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
}
/// SXTH (32-bit/sign-extended): SXTH Wd, Wn (SBFM Wd, Wn, #0, #15)
///
/// Writing the 32-bit destination form clears bits 63:32 of the
/// destination register, which is what a 32-bit x86 destination requires.
pub fn sxth_32(&mut self, wd: u8, wn: u8) {
self.emit(0x13003c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
}
/// ADD (extended/shifted register, 32-bit): ADD Wd, Wn, Wm
pub fn add_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
self.emit(
+116 -30
View File
@@ -466,6 +466,12 @@ impl<'a> Interpreter<'a> {
0x0F => match self.fetch_u8()? {
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
// MOVZX r32/r64, r/m8 (0xB6), MOVZX r32/r64, r/m16 (0xB7),
// MOVSX r32/r64, r/m8 (0xBE), MOVSX r32/r64, r/m16 (0xBF).
op @ (0xB6 | 0xB7 | 0xBE | 0xBF) => {
let modrm = self.fetch_u8()?;
self.execute_mov_ext(modrm, &prefixes, op)
}
op @ 0xC8..=0xCF => {
let reg = Register::from_index((op & 7) | (u8::from(prefixes.rex_b) << 3));
let value = self.cpu.get(reg);
@@ -722,6 +728,72 @@ impl<'a> Interpreter<'a> {
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
}
/// Execute a MOVZX or MOVSX extension instruction.
///
/// `op` is the second opcode byte: `0xB6` extends a byte, `0xB7` extends
/// a word, `0xBE` sign-extends a byte and `0xBF` sign-extends a word.
///
/// The source width follows the opcode and the destination width follows
/// REX.W: without REX.W the destination is 32 bits and its upper half is
/// cleared, and with REX.W it is 64 bits. MOVSX sign-extends to the
/// destination width, so a 32-bit destination keeps the sign in bits
/// 31:0 and a zeroed upper half, while a 64-bit destination keeps the
/// sign extension across all 64 bits.
fn execute_mov_ext(
&mut self,
modrm: u8,
prefixes: &Prefixes,
op: u8,
) -> Result<Option<ExitReason>, ExitReason> {
let mode = (modrm >> 6) & 3;
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let is_word = op == 0xB7 || op == 0xBF;
let is_signed = op == 0xBE || op == 0xBF;
let source = if mode == 3 {
// Register source: only the low 8 or 16 bits are read.
let value = self.cpu.get(Register::from_index(rm_idx));
if is_word {
value as u16 as u64
} else {
value as u8 as u64
}
} else {
let address = self.effective_address(modrm, prefixes)?;
if is_word {
self.memory
.read_u16(address)
.map_err(ExitReason::MemoryFault)? as u64
} else {
self.memory
.read_u8(address)
.map_err(ExitReason::MemoryFault)? as u64
}
};
let extended = if is_signed {
if is_word {
source as u16 as i16 as i64 as u64
} else {
source as u8 as i8 as i64 as u64
}
} else {
source
};
// A 32-bit destination holds a 32-bit result, so its upper half is
// cleared; a 64-bit destination keeps the full extension.
let result = if prefixes.rex_w {
extended
} else {
extended as u32 as u64
};
self.cpu.set(reg, result);
Ok(None)
}
fn execute_mov_rm(
&mut self,
modrm: u8,
@@ -761,6 +833,49 @@ impl<'a> Interpreter<'a> {
}
// Memory operand [rm + disp] or SIB
let effective_addr = self.effective_address(modrm, prefixes)?;
if is_load {
// Load from memory to reg
if prefixes.rex_w {
let val = self
.memory
.read_u64(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val);
} else {
let val = self
.memory
.read_u32(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val as u64);
}
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if prefixes.rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
} else {
self.memory
.write_u32(effective_addr, val as u32)
.map_err(ExitReason::MemoryFault)?;
}
}
Ok(None)
}
/// Compute the effective address of a memory operand.
///
/// Consumes the SIB byte and the displacement from the instruction
/// stream. The FS or GS segment base is added when the corresponding
/// segment override prefix is present.
fn effective_address(&mut self, modrm: u8, prefixes: &Prefixes) -> Result<u64, ExitReason> {
let mode = (modrm >> 6) & 3;
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let (base_val, disp): (u64, i64) = if (rm_idx & 7) == 4 {
// SIB byte follows ModR/M
let sib = self.fetch_u8()?;
@@ -832,36 +947,7 @@ impl<'a> Interpreter<'a> {
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
}
if is_load {
// Load from memory to reg
if prefixes.rex_w {
let val = self
.memory
.read_u64(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val);
} else {
let val = self
.memory
.read_u32(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val as u64);
}
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if prefixes.rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
} else {
self.memory
.write_u32(effective_addr, val as u32)
.map_err(ExitReason::MemoryFault)?;
}
}
Ok(None)
Ok(effective_addr)
}
fn update_flags_logic(&mut self, val: u64, is_64: bool) {
+139 -8
View File
@@ -765,6 +765,7 @@ impl DbtEngine {
// MOV reg, [RIP + disp32]
asm.mov_reg_64(X0, X20);
asm.load_imm_64(X1, target_ea);
Self::emit_segment_base(asm, seg_gs, seg_fs);
let helper_fn = read_u64_helper as *const () as u64;
asm.load_imm_64(X4, helper_fn);
asm.blr(X4);
@@ -778,6 +779,7 @@ impl DbtEngine {
asm.ldr_uoff_64(X2, X19, (reg_idx as u32) * 8);
asm.mov_reg_64(X0, X20);
asm.load_imm_64(X1, target_ea);
Self::emit_segment_base(asm, seg_gs, seg_fs);
let helper_fn = write_u64_helper as *const () as u64;
asm.load_imm_64(X4, helper_fn);
asm.blr(X4);
@@ -1245,7 +1247,13 @@ impl DbtEngine {
if mode == 3 {
asm.ldr_uoff_64(X9, X19, (rm_idx as u32) * 8);
asm.sxtb_64(X9, X9);
if rex_w {
asm.sxtb_64(X9, X9);
} else {
// A 32-bit destination holds a 32-bit
// result, so the upper half is cleared.
asm.sxtb_32(X9, X9);
}
asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8);
} else {
Self::emit_effective_address(
@@ -1265,7 +1273,13 @@ impl DbtEngine {
asm.load_imm_64(X4, helper_fn);
asm.blr(X4);
emit_fault_guard(asm, &mut fault_guards, insn_count - 1, insn_rip);
asm.sxtb_64(X0, X0);
if rex_w {
asm.sxtb_64(X0, X0);
} else {
// A 32-bit destination holds a 32-bit
// result, so the upper half is cleared.
asm.sxtb_32(X0, X0);
}
asm.str_uoff_64(X0, X19, (reg_idx as u32) * 8);
}
}
@@ -1283,7 +1297,13 @@ impl DbtEngine {
if mode == 3 {
asm.ldr_uoff_64(X9, X19, (rm_idx as u32) * 8);
asm.sxth_64(X9, X9);
if rex_w {
asm.sxth_64(X9, X9);
} else {
// A 32-bit destination holds a 32-bit
// result, so the upper half is cleared.
asm.sxth_32(X9, X9);
}
asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8);
} else {
Self::emit_effective_address(
@@ -1303,7 +1323,13 @@ impl DbtEngine {
asm.load_imm_64(X4, helper_fn);
asm.blr(X4);
emit_fault_guard(asm, &mut fault_guards, insn_count - 1, insn_rip);
asm.sxth_64(X0, X0);
if rex_w {
asm.sxth_64(X0, X0);
} else {
// A 32-bit destination holds a 32-bit
// result, so the upper half is cleared.
asm.sxth_32(X0, X0);
}
asm.str_uoff_64(X0, X19, (reg_idx as u32) * 8);
}
}
@@ -1453,17 +1479,36 @@ impl DbtEngine {
}
}
Self::emit_segment_base(asm, seg_gs, seg_fs);
Ok(())
}
/// Add the FS or GS segment base to the effective address held in X1.
///
/// In 64-bit mode an FS or GS segment override adds the segment base to
/// the effective address, so the linear address is
/// `(FS or GS).base + base + (scale * index) + displacement`
/// (Intel SDM Volume 3A, section 3.4.4; AMD64 Architecture Programmer's
/// Manual Volume 1, section 2.2.3.3).
///
/// The base is a runtime guest value, so it is read from the guest CPU
/// state rather than folded into the translated address.
///
/// When both FS and GS overrides are present the encoding is
/// architecturally undefined (Intel SDM Volume 2: "The effect of redundant
/// prefixes ... is undefined"), so this uses a fixed local rule of
/// preferring GS. The interpreter applies the same rule.
fn emit_segment_base(asm: &mut Arm64Assembler, seg_gs: bool, seg_fs: bool) {
if seg_gs {
// Add CpuState.gs_base (offset 16*8 + 8 + 8 = 144) to X1
// CpuState.gs_base (offset 16*8 + 8 + 8 = 144) to X1
asm.ldr_uoff_64(X9, X19, 144);
asm.add_reg_64(X1, X1, X9);
} else if seg_fs {
// Add CpuState.fs_base (offset 16*8 + 8 + 8 + 8 = 152) to X1
// CpuState.fs_base (offset 16*8 + 8 + 8 + 8 = 152) to X1
asm.ldr_uoff_64(X9, X19, 152);
asm.add_reg_64(X1, X1, X9);
}
Ok(())
}
fn emit_set_exit_reason(asm: &mut Arm64Assembler, code: u32, next_rip: u64) {
@@ -1781,6 +1826,92 @@ mod tests {
assert_eq!(memory.read_u64(STORED_ADDR).unwrap(), STORED_VALUE);
}
/// A 32-bit MOVSX destination holds a 32-bit result, so the upper half of
/// the register must be cleared.
///
/// The encodings are `movsbl eax, bl` (0F BE C3) and
/// `movsbq rdx, bl` (48 0F BE D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`. With `bl = 0xFF` the 32-bit destination holds
/// 0x00000000ffffffff while the 64-bit destination holds the sign
/// extension across all 64 bits.
///
/// Per Intel SDM Volume 1, "Address Calculations in 64-Bit Mode": "32-bit
/// operands generate a 32-bit result, zero-extended to a 64-bit result in
/// the destination general-purpose register."
#[test]
fn movsx_to_a_32_bit_destination_clears_the_upper_half() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
// movsbl eax, bl (0F BE C3)
// movsbq rdx, bl (48 0F BE D3)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBE, 0xC3]);
code.extend_from_slice(&[0x48, 0x0F, 0xBE, 0xD3]);
code.push(0xF4); // hlt
let (mut engine, mut cpu, mut memory) = fixture(&code);
cpu.set(Register::Rbx, u64::MAX);
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// A 32-bit MOVSX destination from a 16-bit source also holds a 32-bit
/// result.
///
/// The encodings are `movswl eax, bx` (0F BF C3) and
/// `movswq rdx, bx` (48 0F BF D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn movsx_from_a_word_to_a_32_bit_destination_clears_the_upper_half() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
// movswl eax, bx (0F BF C3)
// movswq rdx, bx (48 0F BF D3)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBF, 0xC3]);
code.extend_from_slice(&[0x48, 0x0F, 0xBF, 0xD3]);
code.push(0xF4); // hlt
let (mut engine, mut cpu, mut memory) = fixture(&code);
cpu.set(Register::Rbx, u64::MAX);
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// The same 32-bit destination rule applies to the memory source forms.
///
/// The encodings are `movsbl eax, byte [rdi]` (0F BE 07) and
/// `movsbq rdx, byte [rdi]` (48 0F BE 17), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn movsx_from_memory_to_a_32_bit_destination_clears_the_upper_half() {
// mov rdi, 0x4000 (48 BF <imm64>)
// movsbl eax, byte [rdi] (0F BE 07)
// movsbq rdx, byte [rdi] (48 0F BE 17)
let mut code = vec![0x48, 0xBF];
code.extend_from_slice(&0x4000u64.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBE, 0x07]);
code.extend_from_slice(&[0x48, 0x0F, 0xBE, 0x17]);
code.push(0xF4); // hlt
let (mut engine, mut cpu, mut memory) = fixture(&code);
memory
.map_region(0x4000, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory.write_u8(0x4000, 0xFF).unwrap();
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
#[test]
fn indirect_call_target_fault_leaves_guest_stack_unchanged() {
// call qword ptr [rip + 0x1000]; hlt. The IAT slot is outside the
+38 -18
View File
@@ -791,17 +791,42 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
});
}
// Map an RVA to a file offset.
//
// The offset is derived from the section header, so on a truncated file it
// can point past the end of the buffer. Such an offset is not readable, so
// it is reported as unmapped rather than returned and sliced later.
let rva_to_offset = |rva: u32| -> Option<usize> {
for sec in &sections {
let max_span = std::cmp::max(sec.virtual_size, sec.raw_data_size);
if rva >= sec.virtual_address && rva < sec.virtual_address.saturating_add(max_span) {
let off_in_sec = (rva - sec.virtual_address) as usize;
return Some(sec.raw_data_ptr as usize + off_in_sec);
let off = sec.raw_data_ptr as usize + off_in_sec;
if off >= bytes.len() {
return None;
}
return Some(off);
}
}
None
};
// Read a NUL-terminated string that starts at `start`.
//
// Returns `None` when the string starts outside the buffer or is not
// terminated, so a truncated file yields an unreadable name instead of a
// slice that panics.
let read_c_string = |start: usize| -> Option<String> {
if start >= bytes.len() {
return None;
}
let mut end = start;
while end < bytes.len() && bytes[end] != 0 {
end += 1;
}
Some(String::from_utf8_lossy(&bytes[start..end]).into_owned())
};
// 1. Relocations Census
let mut relocations = RelocationCensus {
total_entries: 0,
@@ -895,14 +920,11 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
}
desc_off += 20;
let dll_name = if let Some(no) = rva_to_offset(name_rva) {
let mut end = no;
while end < bytes.len() && bytes[end] != 0 {
end += 1;
}
String::from_utf8_lossy(&bytes[no..end]).into_owned()
} else {
"UNKNOWN.dll".to_string()
let dll_name = match rva_to_offset(name_rva).and_then(read_c_string) {
Some(name) => name,
// The name is outside the file or is not NUL-terminated
// within it, which a truncated file can cause.
None => "UNKNOWN.dll".to_string(),
};
let category = ProbeReport::categorize_dll(&dll_name);
@@ -925,15 +947,13 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
format!("Ordinal#{}", val & 0xFFFF)
} else {
let hint_rva = (val & 0x7FFF_FFFF) as u32;
if let Some(ho) = rva_to_offset(hint_rva) {
let str_start = ho + 2;
let mut str_end = str_start;
while str_end < bytes.len() && bytes[str_end] != 0 {
str_end += 1;
}
String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned()
} else {
"UNKNOWN_SYM".to_string()
// The hint is two bytes, so the name starts after it.
match rva_to_offset(hint_rva)
.and_then(|ho| ho.checked_add(2))
.and_then(read_c_string)
{
Some(name) => name,
None => "UNKNOWN_SYM".to_string(),
}
};
+247
View File
@@ -462,3 +462,250 @@ fn test_sib_index_field_100b_without_rex_x_means_no_index() {
0x1234_5678_9abc_def0
);
}
/// Build a guest program that loads `value` into `rdi` and then runs `body`.
///
/// `mov rdi, imm64` is 48 BF <imm64>.
fn program_with_rdi(value: u64, body: &[u8]) -> Vec<u8> {
let mut code = vec![0x48, 0xBF];
code.extend_from_slice(&value.to_le_bytes());
code.extend_from_slice(body);
code.push(0xF4); // hlt
code
}
/// Run `code` on the interpreter and return the final state and exit reason.
fn run_interpreter(code: &[u8]) -> (CpuState, ExitReason) {
let pe_bytes = build_synthetic_pe32_plus(code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
(result.final_state, result.exit_reason)
}
/// MOVZX with a register source, for both destination widths.
///
/// The encodings are `movzbl eax, bl` (0F B6 C3) and
/// `movzbq rdx, bl` (48 0F B6 D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`. A zero extension always produces a zero-extended
/// value, so the 32-bit form clears the upper half of rax while the 64-bit
/// form produces the same 64-bit value.
#[test]
fn test_movzx_register_source_zero_extends() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xB6, 0xC3]); // movzbl eax, bl
code.extend_from_slice(&[0x48, 0x0F, 0xB6, 0xD3]); // movzbq rdx, bl
code.push(0xF4); // hlt
let (state, reason) = run_interpreter(&code);
assert_eq!(reason, ExitReason::Halt);
// The 32-bit destination holds a zero-extended byte: 0x00000000000000ff.
assert_eq!(state.get(Register::Rax), 0x0000_0000_0000_00ff);
// The 64-bit destination holds the same zero-extended value.
assert_eq!(state.get(Register::Rdx), 0x0000_0000_0000_00ff);
}
/// MOVSX with a register source, for both destination widths.
///
/// The encodings are `movsbl eax, bl` (0F BE C3) and
/// `movsbq rdx, bl` (48 0F BE D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`. A sign extension reaches the destination width,
/// so the 32-bit form keeps the sign in bits 31:0 and clears the upper half,
/// while the 64-bit form sign-extends across all 64 bits.
#[test]
fn test_movsx_register_source_sign_extends_to_the_destination_width() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBE, 0xC3]); // movsbl eax, bl
code.extend_from_slice(&[0x48, 0x0F, 0xBE, 0xD3]); // movsbq rdx, bl
code.push(0xF4); // hlt
let (state, reason) = run_interpreter(&code);
assert_eq!(reason, ExitReason::Halt);
// The 32-bit destination holds 0xffffffff and its upper half is cleared.
assert_eq!(state.get(Register::Rax), 0x0000_0000_ffff_ffff);
// The 64-bit destination keeps the sign extension across all 64 bits.
assert_eq!(state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// MOVSX from a 16-bit source sign-extends to the destination width.
///
/// The encodings are `movswl eax, bx` (0F BF C3) and
/// `movswq rdx, bx` (48 0F BF D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn test_movsx_word_register_source_sign_extends() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBF, 0xC3]); // movswl eax, bx
code.extend_from_slice(&[0x48, 0x0F, 0xBF, 0xD3]); // movswq rdx, bx
code.push(0xF4); // hlt
let (state, reason) = run_interpreter(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// MOVZX with a memory source reads only the low byte of the operand.
///
/// The encodings are `movzbl eax, byte [rdi]` (0F B6 07) and
/// `movzbq rdx, byte [rdi]` (48 0F B6 17), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn test_movzx_memory_source_reads_one_byte() {
// mov rdi, DATA_BASE (48 BF <imm64>)
// movzbl eax, byte [rdi] (0F B6 07)
// movzbq rdx, byte [rdi] (48 0F B6 17)
let code = program_with_rdi(DATA_BASE, &[0x0F, 0xB6, 0x07, 0x48, 0x0F, 0xB6, 0x17]);
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
// The byte at the source address has the high bit set, so a sign
// extension would produce a negative value and a zero extension must not.
loaded
.memory
.write_u8(DATA_BASE, 0xFF)
.expect("source byte");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_0000_00ff);
assert_eq!(result.final_state.get(Register::Rdx), 0x0000_0000_0000_00ff);
}
/// MOVSX with a memory source sign-extends the byte that was read.
///
/// The encodings are `movsbl eax, byte [rdi]` (0F BE 07) and
/// `movsbq rdx, byte [rdi]` (48 0F BE 17), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn test_movsx_memory_source_sign_extends() {
// mov rdi, DATA_BASE (48 BF <imm64>)
// movsbl eax, byte [rdi] (0F BE 07)
// movsbq rdx, byte [rdi] (48 0F BE 17)
let code = program_with_rdi(DATA_BASE, &[0x0F, 0xBE, 0x07, 0x48, 0x0F, 0xBE, 0x17]);
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
loaded
.memory
.write_u8(DATA_BASE, 0xFF)
.expect("source byte");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
// The 32-bit destination holds 0xffffffff with the upper half cleared.
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
// The 64-bit destination keeps the sign extension across all 64 bits.
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// The interpreter must implement the same extension opcodes as the native
/// DBT translator.
///
/// The program exercises all four opcodes with both a register and a memory
/// source, and both destination widths:
///
/// - `movzbl eax, bl` (0F B6 C3), `movzbq rdx, bl` (48 0F B6 D3)
/// - `movswl eax, bx` (0F BF C3), `movswq rdx, bx` (48 0F BF D3)
/// - `movzbl eax, byte [rdi]` (0F B6 07), `movzbq rdx, byte [rdi]`
/// (48 0F B6 17)
/// - `movsbl eax, byte [rdi]` (0F BE 07), `movsbq rdx, byte [rdi]`
/// (48 0F BE 17)
///
/// All encodings were produced by LLVM 23.1.6 `llvm-mc -show-encoding`.
///
/// The expected values follow the Intel SDM rules for MOVZX and MOVSX: MOVZX
/// always zero-extends, and MOVSX sign-extends to the destination width, so a
/// 32-bit destination keeps the sign in bits 31:0 and clears the upper half
/// while a 64-bit destination keeps the sign extension across all 64 bits.
#[test]
fn test_interpreter_implements_the_extension_opcodes() {
let code = program_with_rdi(
DATA_BASE,
&[
0x0F, 0xB6, 0xC3, // movzbl eax, bl
0x48, 0x0F, 0xB6, 0xD3, // movzbq rdx, bl
0x0F, 0xBF, 0xC3, // movswl eax, bx
0x48, 0x0F, 0xBF, 0xD3, // movswq rdx, bx
0x0F, 0xB6, 0x07, // movzbl eax, byte [rdi]
0x48, 0x0F, 0xB6, 0x17, // movzbq rdx, byte [rdi]
0x0F, 0xBE, 0x07, // movsbl eax, byte [rdi]
0x48, 0x0F, 0xBE, 0x17, // movsbq rdx, byte [rdi]
],
);
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
// The bytes at the source address have the high bit set and clear, so a
// sign extension and a zero extension give different results.
loaded
.memory
.write_u8(DATA_BASE, 0xFF)
.expect("source byte");
loaded
.memory
.write_u8(DATA_BASE + 1, 0x7F)
.expect("source byte");
let mut cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
// rbx and rsi hold the register-source values.
cpu.set(Register::Rbx, u64::MAX);
cpu.set(Register::Rsi, 0x0000_0000_0000_7FFF);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
// The last write to rax is the 32-bit sign extension of the byte 0xFF.
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
// The last write to rdx is the 64-bit sign extension of the same byte.
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
+18
View File
@@ -0,0 +1,18 @@
use xenora_loader::probe::{ProbeConfig, probe_pe_bytes};
/// The static probe must never panic on a truncated PE.
///
/// The fixture is truncated across its whole length, which covers the range
/// where the import directory and the import names overlap the end of the
/// file, and every other range where a name or thunk read computed from the
/// section header can run past the buffer.
#[test]
fn probe_never_panics_on_truncated_input() {
let pe = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
for len in 1..=pe.len() {
let truncated = &pe[..len];
// The probe may reject the file or report it with unreadable
// imports, but it must not panic.
let _ = probe_pe_bytes(truncated, &ProbeConfig::default());
}
}