Compare commits

..
Author SHA1 Message Date
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 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
4 changed files with 185 additions and 371 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(
+30 -116
View File
@@ -466,12 +466,6 @@ 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);
@@ -728,72 +722,6 @@ 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,
@@ -833,49 +761,6 @@ 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()?;
@@ -947,7 +832,36 @@ impl<'a> Interpreter<'a> {
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
}
Ok(effective_addr)
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)
}
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
-247
View File
@@ -462,250 +462,3 @@ 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);
}