Compare commits

..
Author SHA1 Message Date
atharvranjan b9e6a9d365 Synchronize PR #274 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:12 -06:00
atharvranjan e755ee94ed Merge pull request #264 from MacosPorters/archive/pull/340/head
benchmarks: measure gfx1030 metadata identification
2026-11-24 21:57:34 -06:00
atharvranjan e289318132 Merge pull request #267 from MacosPorters/archive/pull/359/head
loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148)
2026-11-24 21:49:39 -06:00
atharvranjan f685b54e32 Merge pull request #268 from MacosPorters/archive/pull/369/head
loader: add Win64 service ABI preservation tests (#201)
2026-11-24 21:48:28 -06:00
atharvranjan 0690a3ecb4 Merge pull request #284 from MacosPorters/archive/pull/422/head
loader: copy mid-size TLS templates into the zeroed block (#111)
2026-11-24 21:48:22 -06:00
atharvranjan 7286989296 Merge pull request #270 from MacosPorters/archive/pull/374/head
Fix ARM64 variable shift register encoding
2026-11-24 21:47:03 -06:00
22 changed files with 561 additions and 1617 deletions

No files matched your search

-5
View File
@@ -50,8 +50,6 @@ remains unsupported.
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
- LAHF and SAHF run in both engines, and guest CPUID reports them in leaf `8000_0001h`, ECX bit 0 (#387; Intel SDM Vol. 2A LAHF, Vol. 2B SAHF). The DBT runs them through the shared semantics. The four known answers from #155 that both engines refused are now verified, with twelve more cases, and the independent reference in `tests/x86_integer.rs` covers both instructions.
- LOOP, LOOPE, LOOPNE and JRCXZ run in both engines (#396; Intel SDM Vol. 2A, LOOP/LOOPcc and Jcc). The count is RCX; the address-size prefix stays rejected, so JECXZ and the ECX-counted forms are still refused. The DBT runs them through the shared semantics and ends its block at each. The three known answers from #155 that both engines refused are now verified, with eleven more cases, and `tests/cpu_loop.rs` checks a loop that spans translated blocks against a step-by-step model for every count, ZF match point and step budget.
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
@@ -94,7 +92,6 @@ remains unsupported.
- Added 985 LLVM-assembled integer instructions with a bit-level reference that reads only their assembly text, compared with the interpreter and the DBT over 47,280 states, plus 4,000 random instruction sequences compared between the engines.
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
- Added MOVZX, MOVSX (0F B6/B7/BE/BF) and MOVSXD (63) for register and checked memory operands in the interpreter and the native DBT, with exact lengths in the static probe (parts of #65, #66, #67, #68 and #117; awaiting independent review). Covered: 16-, 32- and 64-bit destinations, AH/CH/DH/BH without REX, FS/GS bases and RIP-relative operands. Other 0x66 forms are rejected instead of running at the wrong width. Known-answer encodings come from the LLVM assembler; MOV immediates (B8-BF) have regressions proving they are never read as sign extensions.
- Added FNINIT (`DB E3`), the one instruction a C program built with the mingw-w64 runtime needs that the decoder refused (#378, part of Gate A2). Guest state gains the x87 control, status and tag words in `CpuState::x87`, and FNINIT sets them to the Intel SDM values `037F`, `0` and `FFFF`. Both engines run the shared semantics; nothing is lowered to ARM64 and the host's floating-point state is never touched. The registry gains a form key, `rm`, that pins a register-only form to one ModRM byte, because the other bytes of `DB /4` are different instructions. No other x87 instruction exists: FNSTCW, FLDCW, FNCLEX, FWAIT and all x87 arithmetic stay rejected, there are no x87 data registers, nothing can read the three words back, and CPUID still reports no FPU. Nine SDM-derived cases in `cpu_known_answers.rs`, whose harness now starts every case with the three words away from their reset values and requires every other instruction to keep them, one assembled fixture checked by the text-only reference in `x86_integer.rs`, and a sweep of every ModRM byte under opcodes `D8` to `DF` in both engines cover it. Not compared with x86 hardware; awaiting independent review.
- Added Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
- Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues.
@@ -153,8 +150,6 @@ remains unsupported.
- Added the synthetic default process heap with allocation, size queries, and release.
- Added `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` as `stub` services so that a C program built with the mingw-w64 runtime can bind its imports (#388, part of Gate A2). Such a program imports all three and does not call them on a normal run; without them the loader refused it before its entry point. A call to any of them stops the guest with the runtime-limit fault (`IllegalInstruction(0xFE)`) and writes nothing, so a program that needs one stops there and cannot run on with a made-up result. No page protection is changed, no region is described and no exception is dispatched. The service generator's API-set table gains `api-ms-win-crt-private-l1-1-0.dll` for `ucrtbase.dll`, which is inferred and not taken from a document that names it. Two tests in `runtime_services.rs` call the stubs from guest code and check how they resolve. Not compared with Windows; awaiting independent review.
- Added Win64 signatures for wide-string length and comparison and overlapping byte moves to the import catalog.
- Added guest CRT wide-string length and comparison using Windows 16-bit code units.
-7
View File
@@ -71,13 +71,6 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
"api-ms-win-crt-filesystem-l1-1-0.dll",
"api-ms-win-crt-locale-l1-1-0.dll",
"api-ms-win-crt-environment-l1-1-0.dll",
// The API set a program built with the mingw-w64 UCRT runtime
// imports `memcpy` and `__C_specific_handler` from. That it
// forwards to ucrtbase.dll is inferred from its name and from
// Microsoft's "Universal CRT deployment" page, which says the
// Universal CRT ships as ucrtbase.dll plus `api-ms-win-*.dll`
// forwarders. No document naming this set was found.
"api-ms-win-crt-private-l1-1-0.dll",
],
_ => &[],
}
+4 -12
View File
@@ -7,9 +7,9 @@
differs. Never writes.
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
forms sharing an opcode, operand constraints that contradict each other, a
fixed r/m field on a form that could take memory, LOCK on a form that cannot
write memory, and flags declared both written and undefined. Standard library only (Python 3.11+).
forms sharing an opcode, operand constraints that contradict each other, LOCK
on a form that cannot write memory, and flags declared both written and
undefined. Standard library only (Python 3.11+).
"""
import sys
@@ -27,7 +27,7 @@ RUST = HERE / "src/x86_table.rs"
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
"memory_only", "register_only", "rm", "no_rex_b", "unaligned", "lock"}
"memory_only", "register_only", "no_rex_b", "unaligned", "lock"}
GROUP_KEYS = {"map", "opcodes", "digits"}
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
@@ -169,13 +169,6 @@ def load(text):
fail(f"{where}: memory_only and register_only contradict")
if (form.get("memory_only") or form.get("register_only")) and not modrm:
fail(f"{where}: operand restriction without ModRM")
form.setdefault("rm", None)
if form["rm"] is not None:
# bool is an int in Python; `rm = true` is not a field value.
if type(form["rm"]) is not int or not 0 <= form["rm"] <= 7:
fail(f"{where}: rm must be a ModRM r/m field value 0-7")
if not form.get("register_only") or form["digit"] is None:
fail(f"{where}: a fixed r/m field needs register_only and a digit")
sourced = form["enc"] in XMM_RM or form["enc"] == "xmm_gpr_imm"
if sourced != bool(form["src"]) and form["enc"] not in ("reg_rm", "rm"):
fail(f"{where}: source size does not match the encoding")
@@ -280,7 +273,6 @@ def generate(operations, forms):
f"source: {SRCS[form['src']]}, has_modrm: {str(ENCS[form['enc']][1]).lower()}, "
f"memory_only: {str(bool(form.get('memory_only'))).lower()}, "
f"register_only: {str(bool(form.get('register_only'))).lower()}, "
f"fixed_rm: {'None' if form['rm'] is None else 'Some(%d)' % form['rm']}, "
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
f"unaligned: {str(bool(form.get('unaligned'))).lower()}, "
f"lockable: {str(bool(form.get('lock'))).lower()} }},")
-28
View File
@@ -148,34 +148,6 @@ service kernel32.dll VirtualFree(address: ptr, size: u64, kind: u32) -> bool32
ref memoryapi.h VirtualFree
test virtual_memory_is_mapped_released_and_bounded
# Stubs. A program built with the mingw-w64 runtime imports these three and
# does not call them on a normal run. They exist so that its imports bind. A
# call stops the guest with the runtime-limit fault and changes nothing.
service kernel32.dll VirtualProtect(address: ptr, size: u64, protect: u32, old: out<4>) -> bool32
handler virtual_protect
status stub
alias api-ms-win-core-memory-l1-1-0.dll
fails always: stops the guest with the runtime-limit fault; no protection changes
ref memoryapi.h VirtualProtect
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
service kernel32.dll VirtualQuery(address: ptr, information: out<48>, length: u64) -> u64
handler virtual_query
status stub
alias api-ms-win-core-memory-l1-1-0.dll
fails always: stops the guest with the runtime-limit fault; nothing is written
ref memoryapi.h VirtualQuery
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
service ucrtbase.dll __C_specific_handler(record: ptr, frame: ptr, context: ptr, dispatcher: ptr) -> i32
handler c_specific_handler
status stub
alias api-ms-win-crt-private-l1-1-0.dll
fails always: stops the guest with the runtime-limit fault; no exception is dispatched
ref Microsoft Learn, x64 exception handling, language-specific handler
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
service ucrtbase.dll sqrt(x: f64) -> f64
handler sqrt
status partial
+2 -52
View File
@@ -85,36 +85,6 @@ impl Default for Mxcsr {
}
}
/// x87 FPU control, status and tag words.
///
/// FNINIT is the only instruction that writes them and nothing reads them yet.
/// The x87 data registers and every other x87 instruction are not modelled.
/// The host's floating-point state is never involved.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct X87State {
pub control: u16,
pub status: u16,
pub tag: u16,
}
impl X87State {
/// What FINIT and FNINIT set (Intel SDM Vol. 2A, "FINIT/FNINIT"; Vol. 1,
/// 8.1.3 to 8.1.7): every exception masked, 64-bit precision, round to
/// nearest; no flag, top of stack 0; every register tagged empty.
pub const INIT: Self = Self {
control: 0x037F,
status: 0,
tag: 0xFFFF,
};
}
impl Default for X87State {
fn default() -> Self {
Self::INIT
}
}
/// x86-64 CPU state. Native DBT accesses the general registers and RIP by offset.
#[repr(C)]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -129,9 +99,6 @@ pub struct CpuState {
pub mxcsr: Mxcsr,
/// Direction flag: string instructions step RSI and RDI down when set.
pub df: bool,
/// Starts as FNINIT leaves it. The value an operating system gives a new
/// thread is not modelled.
pub x87: X87State,
}
impl CpuState {
@@ -147,7 +114,6 @@ impl CpuState {
xmm: [0; 16],
mxcsr: Mxcsr::default(),
df: false,
x87: X87State::INIT,
}
}
@@ -164,8 +130,6 @@ impl CpuState {
pub const CPUID_CMOV: u32 = 1 << 15;
/// CPUID leaf 1, ECX: POPCNT.
pub const CPUID_POPCNT: u32 = 1 << 23;
/// CPUID leaf 0x8000_0001, ECX: LAHF and SAHF in 64-bit mode.
pub const CPUID_LAHF_SAHF: u32 = 1;
/// CPUID leaf 0x8000_0001, ECX: LZCNT.
pub const CPUID_LZCNT: u32 = 1 << 5;
/// CPUID leaf 0x8000_0001, EDX: 64-bit mode.
@@ -186,7 +150,7 @@ pub fn cpuid(leaf: u32, _subleaf: u32) -> [u32; 4] {
1 => [0, 0, CPUID_POPCNT, CPUID_CMOV],
// Highest extended leaf.
0x8000_0000 => [0x8000_0001, 0, 0, 0],
0x8000_0001 => [0, 0, CPUID_LAHF_SAHF | CPUID_LZCNT, CPUID_LONG_MODE],
0x8000_0001 => [0, 0, CPUID_LZCNT, CPUID_LONG_MODE],
_ => [0; 4],
}
}
@@ -248,21 +212,7 @@ impl std::error::Error for ExitReason {}
#[cfg(test)]
mod layout_tests {
use super::{CpuState, RFlags, Register, X87State};
/// Intel SDM Vol. 2A, "FINIT/FNINIT", Operation.
#[test]
fn a_new_guest_starts_with_the_x87_words_fninit_sets() {
let init = X87State {
control: 0x037F,
status: 0,
tag: 0xFFFF,
};
assert_eq!(X87State::INIT, init);
assert_eq!(X87State::default(), init);
assert_eq!(CpuState::default().x87, init);
assert_eq!(CpuState::new(0x1000, 0x2000).x87, init);
}
use super::{CpuState, RFlags, Register};
/// The native translator addresses guest registers and RIP by raw byte
/// offset. Keep these assertions next to the struct so a layout change
+1 -66
View File
@@ -8,7 +8,7 @@ use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata};
use crate::services::{ServicesState, handlers};
use std::sync::Arc;
pub static SERVICES: [ServiceMetadata; 23] = [
pub static SERVICES: [ServiceMetadata; 20] = [
ServiceMetadata {
library: "kernel32.dll",
symbol: "SetProcessPriorityBoost",
@@ -185,39 +185,6 @@ pub static SERVICES: [ServiceMetadata; 23] = [
reference: "memoryapi.h VirtualFree",
tests: &["virtual_memory_is_mapped_released_and_bounded"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "VirtualProtect",
parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "protect", kind: "u32" }, Parameter { name: "old", kind: "out<4>" }],
result: "bool32",
status: ServiceStatus::Stub,
aliases: &["api-ms-win-core-memory-l1-1-0.dll"],
failure: "always: stops the guest with the runtime-limit fault; no protection changes",
reference: "memoryapi.h VirtualProtect",
tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "VirtualQuery",
parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "information", kind: "out<48>" }, Parameter { name: "length", kind: "u64" }],
result: "u64",
status: ServiceStatus::Stub,
aliases: &["api-ms-win-core-memory-l1-1-0.dll"],
failure: "always: stops the guest with the runtime-limit fault; nothing is written",
reference: "memoryapi.h VirtualQuery",
tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__C_specific_handler",
parameters: &[Parameter { name: "record", kind: "ptr" }, Parameter { name: "frame", kind: "ptr" }, Parameter { name: "context", kind: "ptr" }, Parameter { name: "dispatcher", kind: "ptr" }],
result: "i32",
status: ServiceStatus::Stub,
aliases: &["api-ms-win-crt-private-l1-1-0.dll"],
failure: "always: stops the guest with the runtime-limit fault; no exception is dispatched",
reference: "Microsoft Learn, x64 exception handling, language-specific handler",
tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "sqrt",
@@ -400,38 +367,6 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "VirtualProtect", ServiceStatus::Stub, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.u64(1)?;
let a2 = call.u32(2)?;
let a3 = call.out::<4>(3)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: bool = handlers::virtual_protect(&mut context, a0, a1, a2, a3)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "VirtualQuery", ServiceStatus::Stub, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.out::<48>(1)?;
let a2 = call.u64(2)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::virtual_query(&mut context, a0, a1, a2)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__C_specific_handler", ServiceStatus::Stub, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.u64(1)?;
let a2 = call.u64(2)?;
let a3 = call.u64(3)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: i32 = handlers::c_specific_handler(&mut context, a0, a1, a2, a3)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "sqrt", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.f64(0)?;
-39
View File
@@ -722,9 +722,6 @@ pub(crate) mod handlers {
type Outcome<T> = Result<T, ExitReason>;
/// The exit for a request the runtime does not model.
const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
pub fn set_process_priority_boost(
context: &mut ServiceContext<'_>,
process: u64,
@@ -949,42 +946,6 @@ pub(crate) mod handlers {
Ok(true)
}
// Stubs (#388). A program built with the mingw-w64 runtime imports these
// three and does not call them on a normal run: the first two serve its
// runtime pseudo-relocations and the third is the language handler Windows
// calls while dispatching a structured exception. None is modelled, so a
// call stops the guest with the runtime-limit fault. Returning a made-up
// result would let the program run on with wrong state.
pub fn virtual_protect(
_: &mut ServiceContext<'_>,
_address: u64,
_size: u64,
_protect: u32,
_old: OutPtr<4>,
) -> Outcome<bool> {
Err(RUNTIME_LIMIT)
}
pub fn virtual_query(
_: &mut ServiceContext<'_>,
_address: u64,
_information: OutPtr<48>,
_length: u64,
) -> Outcome<u64> {
Err(RUNTIME_LIMIT)
}
pub fn c_specific_handler(
_: &mut ServiceContext<'_>,
_record: u64,
_frame: u64,
_context: u64,
_dispatcher: u64,
) -> Outcome<i32> {
Err(RUNTIME_LIMIT)
}
/// The guest MXCSR is not visible to a service, so results use the default
/// rounding and raise no guest flags; the registry marks them partial.
const DEFAULT_MXCSR: u32 = crate::cpu::Mxcsr::RESET;
+1 -4
View File
@@ -48,9 +48,6 @@ pub struct Form {
pub has_modrm: bool,
pub memory_only: bool,
pub register_only: bool,
/// The only ModRM r/m field value the form accepts. Set only on
/// register-only forms, so such a form matches exactly one ModRM byte.
pub fixed_rm: Option<u8>,
pub no_rex_b: bool,
/// A 16-byte memory operand may have any alignment.
pub unaligned: bool,
@@ -429,7 +426,7 @@ pub fn decode<E>(
reg = register((modrm >> 3) & 7, rex_r, size);
let mode = modrm >> 6;
if mode == 3 {
if form.memory_only || form.fixed_rm.is_some_and(|field| field != modrm & 7) {
if form.memory_only {
return Err(DecodeError::Unsupported(opcode));
}
rm = Some(RmOperand::Reg(register(modrm & 7, rex_b, rm_size)));
+1 -49
View File
@@ -10,7 +10,7 @@
//! the state unchanged. Flags that the architecture leaves undefined keep their
//! previous value, which is permitted but not something guests may rely on.
use crate::cpu::{CpuState, ExitReason, RFlags, Register, X87State, cpuid};
use crate::cpu::{CpuState, ExitReason, RFlags, Register, cpuid};
use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
use crate::x86_simd;
@@ -690,26 +690,6 @@ pub fn execute(
next = insn.imm;
}
}
// The count is RCX, decremented without changing any flag; LOOPE and
// LOOPNE also test ZF (Intel SDM Vol. 2A, LOOP/LOOPcc).
Op::Loop | Op::Loope | Op::Loopne => {
let count = cpu.gpr[RCX].wrapping_sub(1);
cpu.gpr[RCX] = count;
let zf_holds = match insn.op {
Op::Loope => cpu.flags.zf,
Op::Loopne => !cpu.flags.zf,
_ => true,
};
if count != 0 && zf_holds {
next = insn.imm;
}
}
// JRCXZ reads RCX and changes nothing (Intel SDM Vol. 2A, Jcc).
Op::Jrcxz => {
if cpu.gpr[RCX] == 0 {
next = insn.imm;
}
}
Op::Ret => {
let sp = cpu.gpr[RSP];
next = read_mem(memory, sp, 8)?;
@@ -720,12 +700,6 @@ pub fn execute(
// instruction starts, on one host thread, so guest accesses are already
// totally ordered and a fence has nothing further to enforce.
Op::Lfence | Op::Mfence | Op::Sfence => {}
// The control, status and tag words take their initial values. The
// no-wait form checks no pending exception, and the data registers,
// which Xenora does not model, are left alone and only tagged empty
// (Intel SDM Vol. 2A, "FINIT/FNINIT"). FNINIT also clears the x87
// instruction and data pointers and last opcode, which are not modelled.
Op::Fninit => cpu.x87 = X87State::INIT,
Op::Cpuid => {
// The leaf is EAX and the subleaf ECX. Each result is a 32-bit
// register write, so the upper halves are cleared.
@@ -768,28 +742,6 @@ pub fn execute(
Op::Clc => cpu.flags.cf = false,
Op::Stc => cpu.flags.cf = true,
Op::Cmc => cpu.flags.cf = !cpu.flags.cf,
// AH = SF:ZF:0:AF:0:PF:1:CF (Intel SDM Vol. 2A, LAHF).
Op::Lahf => {
let f = cpu.flags;
let ah = u64::from(f.sf) << 7
| u64::from(f.zf) << 6
| u64::from(f.af) << 4
| u64::from(f.pf) << 2
| 1 << 1
| u64::from(f.cf);
cpu.gpr[RAX] = cpu.gpr[RAX] & !0xFF00 | ah << 8;
}
// SF, ZF, AF, PF and CF from AH bits 7, 6, 4, 2 and 0; OF is
// unchanged (Intel SDM Vol. 2B, SAHF).
Op::Sahf => {
let ah = (cpu.gpr[RAX] >> 8) as u8;
let flags = &mut cpu.flags;
flags.sf = ah & 0x80 != 0;
flags.zf = ah & 0x40 != 0;
flags.af = ah & 0x10 != 0;
flags.pf = ah & 0x04 != 0;
flags.cf = ah & 0x01 != 0;
}
Op::Hlt => {
cpu.rip = next;
return Ok(Some(ExitReason::Halt));
File diff suppressed because it is too large. Load diff
+8 -17
View File
@@ -13,8 +13,8 @@
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
use xenora_loader::cpu::{
CPUID_CMOV, CPUID_LAHF_SAHF, CPUID_LONG_MODE, CPUID_LZCNT, CPUID_POPCNT, CpuState, ExitReason,
Interpreter, RFlags, cpuid,
CPUID_CMOV, CPUID_LONG_MODE, CPUID_LZCNT, CPUID_POPCNT, CpuState, ExitReason, Interpreter,
RFlags, cpuid,
};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
@@ -79,9 +79,9 @@ fn every_leaf_returns_its_documented_values() {
(1, 0xFFFF_FFFF, [0, 0, 0x0080_0000, 0x0000_8000]),
// Highest extended leaf.
(0x8000_0000, 0, [0x8000_0001, 0, 0, 0]),
// LAHF/SAHF is ECX bit 0, LZCNT ECX bit 5 and long mode EDX bit 29.
(0x8000_0001, 0, [0, 0, 0x0000_0021, 0x2000_0000]),
(0x8000_0001, 7, [0, 0, 0x0000_0021, 0x2000_0000]),
// LZCNT is ECX bit 5 and long mode is EDX bit 29.
(0x8000_0001, 0, [0, 0, 0x0000_0020, 0x2000_0000]),
(0x8000_0001, 7, [0, 0, 0x0000_0020, 0x2000_0000]),
// Everything else, above or between the highest leaves, is zeros.
(2, 0, [0; 4]),
(4, 0, [0; 4]),
@@ -129,14 +129,8 @@ fn every_leaf_returns_its_documented_values() {
.collect();
assert_eq!(vendor, b"Xenora guest");
assert_eq!(
(
CPUID_POPCNT,
CPUID_CMOV,
CPUID_LAHF_SAHF,
CPUID_LZCNT,
CPUID_LONG_MODE
),
(1 << 23, 1 << 15, 1, 1 << 5, 1 << 29)
(CPUID_POPCNT, CPUID_CMOV, CPUID_LZCNT, CPUID_LONG_MODE),
(1 << 23, 1 << 15, 1 << 5, 1 << 29)
);
}
@@ -195,10 +189,6 @@ fn reported_features_have_all_their_instructions_in_the_fixtures() {
decodable(&format!("{name} {high}, {}", memory(bits)));
}
}
// LAHF and SAHF have one form each and no operands.
assert_ne!(cpuid(0x8000_0001, 0)[ECX] & CPUID_LAHF_SAHF, 0);
decodable("lahf");
decodable("sahf");
// Long mode: 64-bit operands and the registers only it has.
assert_ne!(cpuid(0x8000_0001, 0)[EDX] & CPUID_LONG_MODE, 0);
decodable("add r9, r12");
@@ -242,6 +232,7 @@ fn unreported_features_each_have_an_instruction_that_is_refused() {
("RDSEED", 7, EBX, 18, &[0x0F, 0xC7, 0xF8]), // rdseed eax
("ADX", 7, EBX, 19, &[0x66, 0x0F, 0x38, 0xF6, 0xC1]), // adcx eax, ecx
("SHA", 7, EBX, 29, &[0x0F, 0x38, 0xC9, 0xC1]), // sha1msg1 xmm0, xmm1
("LAHF/SAHF", 0x8000_0001, ECX, 0, &[0x9F]), // lahf
("PREFETCHW", 0x8000_0001, ECX, 8, &[0x0F, 0x0D, 0x0E]), // prefetchw [rsi]
("SYSCALL/SYSRET", 0x8000_0001, EDX, 11, &[0x48, 0x0F, 0x07]), // sysretq
("RDTSCP", 0x8000_0001, EDX, 27, &[0x0F, 0x01, 0xF9]), // rdtscp
+8 -91
View File
@@ -41,8 +41,6 @@
//! `f=*` and `keep=` require the initial value. A case without `f=` on the
//! left runs with all flags clear and again with all flags set.
//! * `mx=` is MXCSR; `mx=~20:1b88` ignores the bits in `20`. `=?` ignores a value.
//! * `fcw=`, `fsw=` and `ftw=` are the x87 control, status and tag words. Every
//! case starts with all three away from their FNINIT values.
//! * Symbols: `D` writable data, `U` the unmapped page after it, `R` read-only
//! data, `S` stack, `C` code, `FSB` and `GSB` segment bases.
//! * Faults: `DE`, `GP`, `UD`, `XM`, and page faults `PFR`, `PFW`, `PFX` with
@@ -52,7 +50,7 @@
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Mxcsr, RFlags, X87State};
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Mxcsr, RFlags};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
use xenora_loader::x86_decode::decode;
@@ -600,15 +598,6 @@ const FLAG_MOVES: &str = r"
SDM 2A LAHF
lahf: rax=8877665544332211 f=CPASO => rax=8877665544339711 f=*
lahf_zero: rax=8877665544332211 f=Z => rax=8877665544334211 f=*
lahf_carry_only: rax=ffffffffffffffff f=C => rax=ffffffffffff03ff f=*
lahf_parity_only: rax=ffffffffffffffff f=P => rax=ffffffffffff06ff f=*
lahf_adjust_only: rax=ffffffffffffffff f=A => rax=ffffffffffff12ff f=*
lahf_sign_only: rax=ffffffffffffffff f=S => rax=ffffffffffff82ff f=*
lahf_does_not_store_of: rax=ffffffffffffffff f=O => rax=ffffffffffff02ff f=*
@ rex.w lahf
489f
SDM 2A LAHF; 2A 2.2.1.2
lahf_rex_w_changes_nothing: rax=ffffffffffffffff f=CO => rax=ffffffffffff03ff f=*
@ sahf; lahf
9e 9f
SDM 2B SAHF
@@ -617,12 +606,6 @@ sahf_ignores_bits_1_3_5: rax=ff00 f=O => rax=d700 f=CPAZSO
9e
SDM 2B SAHF
sahf_clear_keeps_of: rax=2800 f=OC => f=cpazsO
sahf_carry_only: rax=100 f=O => f=CpazsO
sahf_parity_only: rax=400 f=O => f=cPazsO
sahf_adjust_only: rax=1000 f=O => f=cpAzsO
sahf_zero_only: rax=4000 f=O => f=cpaZsO
sahf_sign_only: rax=8000 f=O => f=cpazSO
sahf_reads_only_ah: rax=ffffffffffff00ff f=CPAZS => f=cpazso
@ stc
f9
SDM 2B STC
@@ -1099,8 +1082,6 @@ cmov_all_unsigned_below_signed_greater: rax=1 rbx=80000000 => rcx=1 r8=1 r9=0 r1
b800000000 e305 b801000000 90
SDM 2A Jcc
jrcxz_tests_all_64_bits: rcx=100000000 => rax=1 f=*
jrcxz_sees_bit_63: rcx=8000000000000000 => rax=1 f=*
jrcxz_taken_at_zero_keeps_rcx: rcx=0 => rax=0 rcx=0 f=*
@ mov eax, 0; jecxz 1f; mov eax, 1; 1: nop
b800000000 67e305 b801000000 90
SDM 2A Jcc
@@ -1113,24 +1094,6 @@ loop_decrements_rcx_without_flags: rax=0 rcx=3 => rax=3 rcx=0 f=*
488d4001 e0fa
SDM 2A LOOP
loopne_stops_on_zero_flag: rax=0 rcx=5 f=Z => rax=1 rcx=4 f=*
@ mov eax, 0; loop 1f; mov eax, 1; 1: nop
b800000000 e205 b801000000 90
SDM 2A LOOP
loop_from_zero_wraps_and_branches: rcx=0 => rax=0 rcx=ffffffffffffffff f=*
loop_at_one_falls_through: rcx=1 => rax=1 rcx=0 f=*
loop_counts_all_64_bits: rcx=100000000 => rax=0 rcx=ffffffff f=*
@ mov eax, 0; loope 1f; mov eax, 1; 1: nop
b800000000 e105 b801000000 90
SDM 2A LOOP
loope_taken_with_zf: rcx=2 f=Z => rax=0 rcx=1 f=*
loope_not_taken_without_zf: rcx=2 f=CPASO => rax=1 rcx=1 f=*
loope_count_expires_with_zf: rcx=1 f=Z => rax=1 rcx=0 f=*
@ mov eax, 0; loopne 1f; mov eax, 1; 1: nop
b800000000 e005 b801000000 90
SDM 2A LOOP
loopne_taken_without_zf: rcx=2 f=CPASO => rax=0 rcx=1 f=*
loopne_not_taken_with_zf: rcx=2 f=Z => rax=1 rcx=1 f=*
loopne_count_expires_without_zf: rcx=1 => rax=1 rcx=0 f=*
";
const STACK_AND_CALLS: &str = r"
@@ -1570,36 +1533,6 @@ fences_change_no_register_or_flag: rax=1122334455667788 rbx=99aabbccddeeff00 =>
fences_ignore_the_rm_field: rax=1122334455667788 => f=*
";
/// FNINIT, the only x87 instruction (#378). The three words it sets are all the
/// x87 state there is: no data register, pointer or last opcode is modelled, and
/// nothing can read the words back yet, so the cases look at guest state.
const X87_INIT: &str = r"
@ fninit
dbe3
SDM 2A FINIT/FNINIT (Operation); 1 8.1.5 (control word 037FH); 1 8.1.7 (tag FFFFH)
fninit_sets_control_status_and_tag: fcw=0040 fsw=3a41 ftw=0000 => fcw=037f fsw=0 ftw=ffff f=*
fninit_from_every_bit_set: fcw=ffff fsw=ffff ftw=0000 => fcw=037f fsw=0 ftw=ffff f=*
fninit_from_every_bit_clear: fcw=0 fsw=0 ftw=0 => fcw=037f fsw=0 ftw=ffff f=*
fninit_twice_is_the_same: fcw=037f fsw=0 ftw=ffff => fcw=037f fsw=0 ftw=ffff f=*
fninit_from_the_harness_default: => fcw=037f fsw=0 ftw=ffff f=*
@ fninit
dbe3
SDM 2A FINIT/FNINIT (the x87 words only; Flags Affected: C0 to C3 cleared, which are status-word bits)
fninit_keeps_registers_flags_xmm_and_mxcsr: rax=1122334455667788 rbx=99aabbccddeeff00 x3=q:0123456789abcdef,fedcba9876543210 mx=5fbf => fcw=037f fsw=0 ftw=ffff f=*
@ mov [rdi], rax; fninit; mov rbx, [rdi]
488907 dbe3 488b1f
SDM 2A FINIT/FNINIT
fninit_touches_no_memory: rdi=D rax=1122334455667788 m0=0000000000000000 => rbx=1122334455667788 m0=8877665544332211 fcw=037f fsw=0 ftw=ffff f=*
@ fninit; add al, bl
dbe3 00d8
SDM 2A FINIT/FNINIT; 2A ADD
fninit_then_integer_code_runs_on: rax=7f rbx=1 => rax=80 fcw=037f fsw=0 ftw=ffff f=cpAzSO
@ add al, bl
00d8
SDM 2A ADD (no x87 state is named)
integer_code_keeps_the_x87_words: rax=7f rbx=1 fcw=1a2b fsw=3c4d ftw=5e6f => rax=80 f=cpAzSO
";
const MEMORY_FAULTS: &str = r"
@ mov r8d, 1; add al, bl; mov rcx, [rsi]; mov r9d, 2
41b801000000 00d8 !488b0e 41b902000000
@@ -2954,7 +2887,6 @@ const GROUPS: &[(&str, &str)] = &[
("fs_gs", FS_GS),
("decoding", DECODING),
("fences", FENCES),
("x87_init", X87_INIT),
("memory_faults", MEMORY_FAULTS),
("straddling_fault_address", STRADDLING_FAULT_ADDRESS),
("noncanonical_address", NONCANONICAL_ADDRESS),
@@ -3002,11 +2934,16 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("haddps_hsubpd_addsubps", 0),
("insertps_zero_mask", 0),
("jecxz_tests_low_32_bits", 1),
("jrcxz_tests_all_64_bits", 1),
("lahf", 0),
("lahf_zero", 0),
("lea64_addr32_truncates_effective_address", 0),
("lock_btc_memory", 0),
("lodsd_zero_extends", 1),
("lodsd_zero_extends_df_clear", 0),
("lodsw_preserves_upper48", 1),
("loop_decrements_rcx_without_flags", 1),
("loopne_stops_on_zero_flag", 1),
("maskmovdqu_selects_bytes", 0),
("mov_moffs64_load", 0),
("mov_moffs8_store", 0),
@@ -3048,6 +2985,8 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("roundps_uses_mxcsr_rc", 0),
("roundsd_suppress_precision", 0),
("roundss_imm_modes", 0),
("sahf_clear_keeps_of", 0),
("sahf_ignores_bits_1_3_5", 0),
];
// ---------------------------------------------------------------------------
@@ -3292,13 +3231,6 @@ fn initial_cpu() -> CpuState {
}
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
// None of the three is what FNINIT sets, so a reset is always visible and
// an instruction that wrongly resets one is caught by any case.
cpu.x87 = X87State {
control: 0x0c40,
status: 0x2b05,
tag: 0x5a5a,
};
cpu
}
@@ -3359,13 +3291,6 @@ fn apply(text: &str, expected: &mut Expected) {
expected.cpu.rip = value(data);
} else if key == "gsbase" {
expected.cpu.gs_base = value(data);
} else if let Some(word) = match key {
"fcw" => Some(&mut expected.cpu.x87.control),
"fsw" => Some(&mut expected.cpu.x87.status),
"ftw" => Some(&mut expected.cpu.x87.tag),
_ => None,
} {
*word = u16::try_from(value(data)).expect("a 16-bit x87 word");
} else if key == "mx" {
if data == "?" {
expected.mxcsr_mask = 0;
@@ -3600,9 +3525,6 @@ fn check(case: &Case, engine: Engine, initial_flags: u8) -> Result<(), String> {
if (cpu.fs_base, cpu.gs_base) != (want.cpu.fs_base, want.cpu.gs_base) {
text.push_str(" segment base changed;");
}
if cpu.x87 != want.cpu.x87 {
let _ = write!(text, " x87={:04x?} want {:04x?};", cpu.x87, want.cpu.x87);
}
let memory_text = Image::store(&memory).differences(&want.image);
if !memory_text.is_empty() {
let _ = write!(text, " memory{memory_text};");
@@ -3745,11 +3667,6 @@ fn fences() {
check_group(FENCES);
}
#[test]
fn x87_init() {
check_group(X87_INIT);
}
#[test]
fn memory_faults() {
check_group(MEMORY_FAULTS);
-261
View File
@@ -1,261 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! LOOP, LOOPE, LOOPNE and JRCXZ (issue #396).
//!
//! Expected results come from a step-by-step model written from the operation
//! sections of the Intel SDM Vol. 2A for LOOP/LOOPcc and Jcc. The model never
//! decodes or calls the production semantics. Encodings were assembled with
//! `clang -target x86_64-apple-macos` and read with `objdump`. Nothing was
//! compared with x86 hardware.
//!
//! In 64-bit mode with the default address size the count is RCX. LOOP
//! decrements it without changing a flag and branches while the result is not
//! zero; LOOPE also needs ZF set and LOOPNE ZF clear. JRCXZ branches when RCX is
//! zero and changes nothing.
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
const ENTRY: u64 = 0x1000;
const RAX: usize = 0;
const RCX: usize = 1;
const RBX: usize = 3;
const RDI: usize = 7;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Kind {
Loop,
Loope,
Loopne,
}
impl Kind {
fn opcode(self) -> u8 {
match self {
Kind::Loopne => 0xE0,
Kind::Loope => 0xE1,
Kind::Loop => 0xE2,
}
}
}
/// ```text
/// top: inc rbx 48 ff c3
/// cmp rbx, rdi 48 39 fb
/// jmp next eb 00 ; ends a translated block
/// next: loop/loope/loopne top
/// hlt f4
/// ```
fn loop_program(kind: Kind) -> Vec<u8> {
vec![
0x48,
0xFF,
0xC3,
0x48,
0x39,
0xFB,
0xEB,
0x00,
kind.opcode(),
0xF6,
0xF4,
]
}
/// Start of each instruction of [`loop_program`], and the end of HLT.
const OFFSETS: [u64; 6] = [0, 3, 6, 8, 10, 11];
fn image(code: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
}
/// The interpreter and the DBT, each from its own copy of the state. The DBT
/// result carries the state it left in its own copy.
fn both(cpu: &CpuState, code: &[u8], budget: usize) -> [(&'static str, ExecutionResult); 2] {
let mut interpreted = image(code);
let result = Interpreter::new(cpu.clone(), &mut interpreted, budget).run();
let mut translated = image(code);
let mut state = cpu.clone();
let mut native = DbtEngine::new(64 * 1024)
.unwrap()
.run(&mut state, &mut translated, budget);
native.final_state = state;
[("interpreter", result), ("DBT", native)]
}
/// What the model predicts after at most `budget` instructions.
#[derive(Debug, PartialEq, Eq)]
struct Outcome {
exit: ExitReason,
executed: usize,
rip: u64,
rcx: u64,
rbx: u64,
zf: bool,
}
fn model(kind: Kind, rcx: u64, rbx: u64, rdi: u64, zf: bool, budget: usize) -> Outcome {
let (mut rcx, mut rbx, mut zf) = (rcx, rbx, zf);
let mut at = 0;
let mut executed = 0;
while executed < budget {
executed += 1;
at = match at {
// INC writes ZF too (Intel SDM Vol. 2A, INC).
0 => {
rbx = rbx.wrapping_add(1);
zf = rbx == 0;
1
}
1 => {
zf = rbx == rdi;
2
}
2 => 3,
3 => {
rcx = rcx.wrapping_sub(1);
let condition = match kind {
Kind::Loop => true,
Kind::Loope => zf,
Kind::Loopne => !zf,
};
if rcx != 0 && condition { 0 } else { 4 }
}
_ => {
return Outcome {
exit: ExitReason::Halt,
executed,
rip: ENTRY + OFFSETS[5],
rcx,
rbx,
zf,
};
}
};
}
Outcome {
exit: ExitReason::StepLimitExceeded,
executed,
rip: ENTRY + OFFSETS[at],
rcx,
rbx,
zf,
}
}
#[test]
fn loops_match_the_model_for_every_count_match_point_and_budget() {
let mut checked = 0;
for kind in [Kind::Loop, Kind::Loope, Kind::Loopne] {
let code = loop_program(kind);
for rcx in [0, 1, 2, 3, 5, 0x1_0000_0000] {
// RDI is the value of RBX after the iteration whose CMP sets ZF;
// 0 never matches within these counts.
for rdi in [0, 1, 2, 3, 4] {
for zf in [false, true] {
// Budgets that stop before, inside and after the loop.
for budget in [1, 3, 4, 5, 8, 9, 11, 13, 22, 200] {
let wanted = model(kind, rcx, 0, rdi, zf, budget);
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RCX] = rcx;
cpu.gpr[RDI] = rdi;
cpu.flags.zf = zf;
for (engine, result) in both(&cpu, &code, budget) {
let state = &result.final_state;
let found = Outcome {
exit: result.exit_reason,
executed: result.instructions_executed,
rip: state.rip,
rcx: state.gpr[RCX],
rbx: state.gpr[RBX],
zf: state.flags.zf,
};
assert_eq!(
found, wanted,
"{kind:?} rcx={rcx:#x} rdi={rdi} zf={zf} budget={budget} on the {engine}"
);
checked += 1;
}
}
}
}
}
}
assert_eq!(checked, 3 * 6 * 5 * 2 * 10 * 2);
}
/// ```text
/// mov eax, 7 b8 07 00 00 00
/// jrcxz done e3 05
/// mov eax, 1 b8 01 00 00 00
/// done: hlt f4
/// ```
#[test]
fn jrcxz_branches_only_on_a_zero_rcx_and_changes_nothing() {
let code = [
0xB8, 0x07, 0x00, 0x00, 0x00, 0xE3, 0x05, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xF4,
];
let mut values = vec![0, 1, u64::MAX];
values.extend((0..64).map(|bit| 1u64 << bit));
for rcx in values {
for flags in [RFlags::default(), all_flags()] {
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RCX] = rcx;
cpu.flags = flags;
let mut wanted = cpu.clone();
wanted.gpr[RAX] = if rcx == 0 { 7 } else { 1 };
wanted.rip = ENTRY + code.len() as u64;
for (engine, result) in both(&cpu, &code, 8) {
assert_eq!(
result.exit_reason,
ExitReason::Halt,
"rcx={rcx:#x} {engine}"
);
let executed = if rcx == 0 { 3 } else { 4 };
assert_eq!(
result.instructions_executed, executed,
"rcx={rcx:#x} {engine}"
);
assert_eq!(result.final_state, wanted, "rcx={rcx:#x} {engine}");
}
}
}
}
/// LOOP from RCX = 0 wraps to 2^64 - 1 and branches. With a budget the loop
/// stops early, and both engines agree on the whole state.
#[test]
fn loop_from_zero_wraps_and_keeps_every_flag() {
let code = loop_program(Kind::Loop);
for flags in [RFlags::default(), all_flags()] {
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RDI] = 1;
cpu.flags = flags;
let [(_, interpreted), (_, translated)] = both(&cpu, &code, 4);
assert_eq!(interpreted.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(interpreted.final_state.gpr[RCX], u64::MAX);
assert_eq!(interpreted.final_state.rip, ENTRY);
// INC and CMP set the flags; LOOP leaves them as CMP left them.
let after_cmp = model(Kind::Loop, 0, 0, 1, flags.zf, 2).zf;
assert_eq!(interpreted.final_state.flags.zf, after_cmp);
assert_eq!(interpreted.final_state, translated.final_state);
assert_eq!(interpreted.exit_reason, translated.exit_reason);
}
}
fn all_flags() -> RFlags {
RFlags {
cf: true,
zf: true,
sf: true,
of: true,
pf: true,
af: true,
}
}
-116
View File
@@ -659,122 +659,6 @@ fn virtual_memory_is_mapped_released_and_bounded() {
assert_eq!(guest.call("VirtualFree", &[address, 0, RELEASE]), 0);
}
/// `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` are stubs: a
/// hosted C program imports them and does not call them on a normal run. A
/// call stops the guest with the runtime-limit fault. The service writes
/// nothing: not the output buffers, not a result, not the last-error value.
#[test]
fn memory_and_exception_stubs_stop_the_guest_and_change_nothing() {
let mut guest = Guest::new();
const READ_WRITE: u64 = 0x04;
const LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
let scratch: Vec<u8> = (0..0x100).map(|index| index as u8 ^ 0xA5).collect();
guest.memory.write_bytes(SCRATCH, &scratch).unwrap();
guest.call("SetLastError", &[0x1234]);
for (symbol, args) in [
// The scratch page, read-write as it already is, with the old
// protection going to the scratch page too.
(
"VirtualProtect",
[SCRATCH, 0x100, READ_WRITE, SCRATCH + 0x80],
),
("VirtualProtect", [0, 0, 0, 0]),
// A full MEMORY_BASIC_INFORMATION, 48 bytes, about a mapped address.
("VirtualQuery", [SCRATCH, SCRATCH + 0x40, 48, 0]),
("VirtualQuery", [0, 0, 0, 0]),
(
"__C_specific_handler",
[SCRATCH, STACK_TOP, SCRATCH + 0x40, SCRATCH + 0x80],
),
("__C_specific_handler", [0, 0, 0, 0]),
] {
let (cpu, exit) = guest.run(symbol, &args);
assert_eq!(exit, LIMIT, "{symbol} {args:x?}");
// Every general register but the stack pointer is as the caller left
// it: no result in RAX, no argument register cleared.
for (index, value) in cpu.gpr.iter().enumerate() {
let argument = [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
.iter()
.position(|register| *register as usize == index);
let wanted = match argument {
Some(position) => args[position],
None => 0x0101_0101_0101_0101 * (index as u64 + 1),
};
if index != Register::Rsp as usize {
assert_eq!(*value, wanted, "{symbol} register {index}");
}
}
assert_eq!(cpu.xmm[..4], guest.xmm, "{symbol}");
let mut after = vec![0; scratch.len()];
guest.memory.read_bytes(SCRATCH, &mut after).unwrap();
assert_eq!(after, scratch, "{symbol} {args:x?}");
}
// The stopped calls recorded no error, and the guest still runs.
assert_eq!(guest.last_error(), 0x1234);
// The scratch page kept its protection: it is still writable.
guest.memory.write_u8(SCRATCH, 1).unwrap();
}
/// The three stubs resolve by the module and symbol pairs a program built
/// with mingw-w64 14.0.0 (UCRT) imports them by, and say they are stubs.
#[test]
fn memory_and_exception_stubs_bind_and_are_declared_stubs() {
let (registry, _) = standard(0);
let named = |name: &str| ImportName::Name(name.to_owned());
for (module, symbol, canonical) in [
("KERNEL32.dll", "VirtualProtect", "kernel32.dll"),
("KERNEL32.dll", "VirtualQuery", "kernel32.dll"),
(
"api-ms-win-core-memory-l1-1-0.dll",
"VirtualProtect",
"kernel32.dll",
),
(
"api-ms-win-core-memory-l1-1-0.dll",
"VirtualQuery",
"kernel32.dll",
),
(
"api-ms-win-crt-private-l1-1-0.dll",
"__C_specific_handler",
"ucrtbase.dll",
),
] {
let service = registry
.resolve(module, &named(symbol))
.unwrap_or_else(|| panic!("{module}!{symbol}"));
let target = registry.resolve(canonical, &named(symbol)).unwrap();
assert!(std::ptr::eq(service, target), "{module}!{symbol}");
assert_eq!(service.status, ServiceStatus::Stub, "{symbol}");
}
// The real services beside them are not stubs, and the API sets forward
// only the symbols listed for them.
let alloc = registry
.resolve("kernel32.dll", &named("VirtualAlloc"))
.unwrap();
assert_eq!(alloc.status, ServiceStatus::Partial);
for (module, symbol) in [
("api-ms-win-crt-private-l1-1-0.dll", "VirtualProtect"),
("api-ms-win-core-memory-l1-1-0.dll", "__C_specific_handler"),
("kernel32.dll", "__C_specific_handler"),
] {
assert!(
registry.resolve(module, &named(symbol)).is_none(),
"{module}!{symbol}"
);
}
let stubs: Vec<&str> = SERVICES
.iter()
.filter(|service| service.status == ServiceStatus::Stub)
.map(|service| service.symbol)
.collect();
assert_eq!(
stubs,
["VirtualProtect", "VirtualQuery", "__C_specific_handler"]
);
}
#[test]
fn floating_arguments_and_results_use_xmm_registers() {
let mut guest = Guest::new();
+2 -2
View File
@@ -102,8 +102,8 @@ def cases():
out += [f"{op} ah, bl", f"{op} cl, dh", f"{op} {mem(8)}, ch"]
out += ["mov ah, bl", "mov dl, ch", "mov bh, 0x21", "xchg ah, bl", "mov sil, dil",
"movabs r15, 0x8877665544332211", "mov rcx, -2", "bswap ebx", "bswap r9",
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "lahf", "sahf",
"nop", "cpuid", "nop dword ptr [rax + 8]", "pause", "lfence", "mfence", "sfence", "fninit",
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop", "cpuid",
"nop dword ptr [rax + 8]", "pause", "lfence", "mfence", "sfence",
f"movnti {mem(32)}, ebx", f"movnti {mem(64)}, rbx",
f"movnti {mem(32)}, r9d", f"movnti {mem(64)}, r14", "push r9", "push rbx", "push -5", "push 0x12345678",
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
-3
View File
@@ -1185,8 +1185,6 @@ b7 21 | mov bh, 0x21
f8 | clc
f9 | stc
f5 | cmc
9f | lahf
9e | sahf
90 | nop
0f a2 | cpuid
0f 1f 40 08 | nop dword ptr [rax + 8]
@@ -1194,7 +1192,6 @@ f3 90 | pause
0f ae e8 | lfence
0f ae f0 | mfence
0f ae f8 | sfence
db e3 | fninit
0f c3 5c be 10 | movnti dword ptr [rsi + 4*rdi + 16], ebx
48 0f c3 5c be 10 | movnti qword ptr [rsi + 4*rdi + 16], rbx
44 0f c3 4c be 10 | movnti dword ptr [rsi + 4*rdi + 16], r9d
+4 -140
View File
@@ -11,7 +11,7 @@
//! but the interpreter and the DBT must still agree on the complete state.
use std::collections::{BTreeMap, BTreeSet};
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags, X87State};
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
use xenora_loader::x86_decode::decode;
@@ -67,8 +67,6 @@ struct Machine {
/// Stack qwords at STACK_TOP - 8 and STACK_TOP.
pushed: u64,
top: u64,
/// x87 control, status and tag words.
x87: [u16; 3],
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -331,11 +329,6 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
bits,
high: false,
};
let ah = Place::Reg {
index: RAX,
bits: 8,
high: true,
};
if let Some(code) = name.strip_prefix("cmov") {
let value = read(
@@ -794,46 +787,18 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
m.flags.cf = !m.flags.cf;
Outcome::Done(none)
}
// AH bits 7 to 0 are SF, ZF, 0, AF, 0, PF, 1 and CF; OF has no bit.
"lahf" => {
let f = m.flags;
let bits = [f.cf, true, f.pf, false, f.af, false, f.zf, f.sf];
let value = (0..8)
.filter(|&index| bits[index])
.map(|index| 1u128 << index)
.sum();
write(m, ah, value);
Outcome::Done(none)
}
"sahf" => {
let value = read(m, ah, 8);
m.flags.cf = bit(value, 0);
m.flags.pf = bit(value, 2);
m.flags.af = bit(value, 4);
m.flags.zf = bit(value, 6);
m.flags.sf = bit(value, 7);
Outcome::Done(none)
}
// The fences order memory accesses and compute nothing.
"nop" | "pause" | "lfence" | "mfence" | "sfence" => Outcome::Done(none),
"fninit" => {
// Intel SDM Vol. 2A, "FINIT/FNINIT", Operation: FPUControlWord :=
// 037FH, FPUStatusWord := 0, FPUTagWord := FFFFH. Nothing else here
// is x87 state.
m.x87 = [0x037F, 0, 0xFFFF];
Outcome::Done(none)
}
"cpuid" => {
// Xenora's guest CPUID contract, restated: the vendor "Xenora guest"
// and the five features whose every instruction exists, CMOV and
// POPCNT in leaf 1, LAHF/SAHF, LZCNT and long mode in leaf
// 0x8000_0001.
// and the four features whose every instruction exists, CMOV and
// POPCNT in leaf 1, LZCNT and long mode in leaf 0x8000_0001.
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
let values = match m.gpr[RAX] as u32 {
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
1 => [0, 0, 1 << 23, 1 << 15],
0x8000_0000 => [0x8000_0001, 0, 0, 0],
0x8000_0001 => [0, 0, 1 | 1 << 5, 1 << 29],
0x8000_0001 => [0, 0, 1 << 5, 1 << 29],
_ => [0; 4],
};
// EAX, EBX, ECX and EDX, each zero-extended.
@@ -933,8 +898,6 @@ impl Random {
operand: self.value(),
pushed: self.next(),
top: self.value(),
// Any bit pattern: nothing interprets these words.
x87: [self.next() as u16, self.next() as u16, self.next() as u16],
}
}
}
@@ -963,12 +926,6 @@ fn load(machine: &Machine, code: &[u8]) -> (CpuState, GuestMemory) {
pf: f.pf,
af: f.af,
};
let [control, status, tag] = machine.x87;
cpu.x87 = X87State {
control,
status,
tag,
};
(cpu, memory)
}
@@ -1027,13 +984,6 @@ fn every_fixture_instruction_matches_the_reference_in_both_engines() {
"{text}"
);
assert_eq!(state.rip, ENTRY + case.code.len() as u64, "{text}");
let x87 = state.x87;
assert_eq!(
[x87.control, x87.status, x87.tag],
expected.x87,
"{text}: x87 words from {:04x?}",
machine.x87
);
if !undefined.destination {
assert_eq!(state.gpr, expected.gpr, "{text} from {cpu:x?}");
assert_eq!(
@@ -1093,10 +1043,6 @@ fn every_declared_form_is_executed_by_a_fixture() {
let separate = [
Op::Ldmxcsr,
Op::Jcc,
Op::Loop,
Op::Loope,
Op::Loopne,
Op::Jrcxz,
Op::Jmp,
Op::Call,
Op::Ret,
@@ -1343,12 +1289,6 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
&[0x0F, 0xC3, 0xC1], // movnti with a register destination
&[0x66, 0x0F, 0xC3, 0x06], // 66 with movnti
&[0x0F, 0xA3, 0x06], // bt [rsi], eax
&[0x9B], // fwait
&[0x9B, 0xDB, 0xE3], // finit: fwait, then fninit
&[0x66, 0xDB, 0xE3], // 66 with fninit
&[0xF3, 0xDB, 0xE3], // F3 with fninit
&[0xF2, 0xDB, 0xE3], // F2 with fninit
&[0xF0, 0xDB, 0xE3], // lock fninit
&[0xC6, 0xC8, 0x01], // C6 /1
&[0xFF, 0xF8], // FF /7
&[0xFE, 0xD0], // FE /2
@@ -1381,81 +1321,6 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
}
}
/// FNINIT (DB E3) is the only x87 instruction. Every other ModRM byte under the
/// eight x87 escape opcodes, D8 to DF, stops both engines and changes nothing.
/// That includes FNINIT's neighbours of the same digit, such as FNCLEX (DB E2),
/// and the memory forms of that digit.
#[test]
fn fninit_is_the_only_x87_encoding_accepted() {
let machine = Random(7).machine();
assert_ne!(
machine.x87,
[0x037F, 0, 0xFFFF],
"the reset must be visible"
);
let mut accepted = Vec::new();
for opcode in 0xD8..=0xDF_u8 {
for modrm in 0..=0xFF_u8 {
// The padding is a SIB byte and displacement for the memory forms.
let code = [opcode, modrm, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90];
for native in [false, true] {
let (mut cpu, mut memory) = load(&machine, &code);
let before = cpu.clone();
let data = bytes(&memory);
let result = if native {
DbtEngine::new(16 * 1024)
.unwrap()
.run(&mut cpu, &mut memory, 1)
} else {
Interpreter::new(cpu, &mut memory, 1).run()
};
let what = format!("{opcode:02X} {modrm:02X}, native {native}");
assert_eq!(bytes(&memory), data, "{what}");
if matches!(result.exit_reason, ExitReason::IllegalInstruction(_)) {
assert_eq!(result.final_state, before, "{what}");
continue;
}
accepted.push((opcode, modrm, native));
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded, "{what}");
// Only RIP and the three x87 words may differ.
let mut wanted = before;
wanted.rip = ENTRY + 2;
wanted.x87 = X87State {
control: 0x037F,
status: 0,
tag: 0xFFFF,
};
assert_eq!(result.final_state, wanted, "{what}");
}
}
}
assert_eq!(accepted, [(0xDB, 0xE3, false), (0xDB, 0xE3, true)]);
}
/// A local rule, pinned so it cannot change unnoticed: a segment override or a
/// REX prefix before FNINIT is accepted and has no effect, as the decoder
/// treats them before any form without operands. It is not derived from a
/// manual statement. The prefixes that are refused are in
/// `undeclared_and_ambiguous_encodings_are_rejected`.
#[test]
fn prefixes_accepted_before_fninit_have_no_effect() {
let machine = Random(11).machine();
for prefix in [0x2E_u8, 0x64, 0x65, 0x40, 0x41, 0x48, 0x4F] {
let code = [prefix, 0xDB, 0xE3, 0x90];
let (cpu, _) = load(&machine, &code);
let mut wanted = cpu;
wanted.rip = ENTRY + 3;
wanted.x87 = X87State {
control: 0x037F,
status: 0,
tag: 0xFFFF,
};
let (state, exit, _) = run_both(&machine, &code, 1);
assert_eq!(exit, ExitReason::StepLimitExceeded, "{prefix:02X}");
assert_eq!(state, wanted, "{prefix:02X}");
}
}
#[test]
fn raw_syscalls_are_refused_by_the_dbt_only() {
let machine = Random(9).machine();
@@ -1582,7 +1447,6 @@ fn bit_scans_and_bit_tests_follow_the_architecture() {
operand: 0,
pushed: 0,
top: STACK_TOP,
x87: [0x037F, 0, 0xFFFF],
}
}
-65
View File
@@ -16,9 +16,6 @@
# lock = true accepts the LOCK prefix (F0) when the ModRM operand is memory.
# Every other use of LOCK is rejected, as the architecture's #UD.
#
# rm = N requires the ModRM r/m field to be N. It needs register_only, so the
# form matches exactly one ModRM byte. At most one form per opcode and digit.
#
# prefix is a mandatory prefix: "66", "f3" or "f2". SSE forms use size x (XMM)
# and give the ModRM operand width in src: x = 16 bytes, q = 8, d = 4, w = 2.
# A 16-byte memory operand must be aligned unless unaligned = true.
@@ -93,11 +90,6 @@ leave = { ref = "sdm LEAVE" }
call = { terminator = true, ref = "sdm CALL" }
jmp = { terminator = true, ref = "sdm JMP" }
jcc = { reads = "cf zf sf of pf", terminator = true, ref = "sdm Jcc" }
# The count is RCX: the address-size prefix that would select ECX is rejected.
loopne = { reads = "zf", terminator = true, ref = "sdm LOOP/LOOPcc" }
loope = { reads = "zf", terminator = true, ref = "sdm LOOP/LOOPcc" }
loop = { terminator = true, ref = "sdm LOOP/LOOPcc" }
jrcxz = { terminator = true, ref = "sdm Jcc" }
ret = { terminator = true, ref = "sdm RET" }
nop = { ref = "sdm NOP" }
hlt = { terminator = true, ref = "sdm HLT" }
@@ -105,14 +97,9 @@ syscall = { terminator = true, ref = "sdm SYSCALL" }
clc = { writes = "cf", ref = "sdm CLC" }
stc = { writes = "cf", ref = "sdm STC" }
cmc = { reads = "cf", writes = "cf", ref = "sdm CMC" }
# AH holds SF, ZF, AF, PF and CF; valid in 64-bit mode when CPUID
# 8000_0001h ECX bit 0 is set.
lahf = { reads = "cf zf sf pf af", ref = "sdm LAHF" }
sahf = { writes = "cf zf sf pf af", ref = "sdm SAHF" }
cpuid = { ref = "sdm CPUID" }
cld = { ref = "sdm CLD" }
std = { ref = "sdm STD" }
fninit = { ref = "sdm FINIT/FNINIT" }
# A REP form repeats by leaving RIP on itself, so these end a translated block.
movs = { terminator = true, ref = "sdm MOVS/MOVSB/MOVSW/MOVSD/MOVSQ" }
stos = { terminator = true, ref = "sdm STOS/STOSB/STOSW/STOSD/STOSQ" }
@@ -525,18 +512,6 @@ opcode = 0x99
enc = "none"
size = "v"
[[form]]
op = "sahf"
opcode = 0x9E
enc = "none"
size = "n"
[[form]]
op = "lahf"
opcode = 0x9F
enc = "none"
size = "n"
[[form]]
op = "mov"
opcode = 0xB0
@@ -588,34 +563,6 @@ opcode = 0xC9
enc = "none"
size = "q"
[[form]]
op = "loopne"
opcode = 0xE0
enc = "rel"
size = "n"
imm = "rel8"
[[form]]
op = "loope"
opcode = 0xE1
enc = "rel"
size = "n"
imm = "rel8"
[[form]]
op = "loop"
opcode = 0xE2
enc = "rel"
size = "n"
imm = "rel8"
[[form]]
op = "jrcxz"
opcode = 0xE3
enc = "rel"
size = "n"
imm = "rel8"
[[form]]
op = "call"
opcode = 0xE8
@@ -725,18 +672,6 @@ opcode = 0xFD
enc = "none"
size = "n"
# FNINIT is DB E3 and nothing else: the other register bytes of digit 4 are
# different instructions (DB E2 is FNCLEX) and the memory forms are not x87
# initialisation at all. No other x87 form is declared.
[[form]]
op = "fninit"
opcode = 0xDB
digit = 4
enc = "rm_unread"
size = "n"
register_only = true
rm = 3
[[form]]
op = "movzx"
map = "0f"
+5 -20
View File
@@ -5,14 +5,14 @@ The static PE probe, the interpreter and the native ARM64 dynamic binary transla
| Part | File | Role |
| --- | --- | --- |
| Registry | `crates/loader/x86/instructions.toml` | Opcode map, opcode, ModRM digit, operand encoding, size, immediate, flag effects and public reference. Data only. |
| Generator | `crates/loader/generate_x86.py` | `validate`, `generate` and `--check`. Rejects overlapping encodings, opcodes that are prefixes, contradictory operand rules, a fixed r/m field on a form that could take memory, unknown vocabulary and flags both written and undefined. |
| Generator | `crates/loader/generate_x86.py` | `validate`, `generate` and `--check`. Rejects overlapping encodings, opcodes that are prefixes, contradictory operand rules, unknown vocabulary and flags both written and undefined. |
| Tables | `crates/loader/src/x86_table.rs` | Generated static tables. No metadata is parsed at run time. |
| Semantics | `crates/loader/src/x86_exec.rs`, `x86_simd.rs`, `x86_float.rs`, `softfloat.rs` | Rust primitives for integer, vector and floating-point forms. Every instruction is all-or-nothing. |
| Lowering | `crates/loader/src/dbt.rs` | ARM64 for the forms `is_native` accepts. Every other form calls the shared semantics and is counted in `DbtMetrics::interpreter_fallbacks`. |
## Adding a form
1. Add the form, and its operation if new, to the registry with an Intel SDM or AMD APM reference. A form that is one exact ModRM byte, not a whole digit, takes `register_only = true` and `rm = N`.
1. Add the form, and its operation if new, to the registry with an Intel SDM or AMD APM reference.
2. Run `python3 crates/loader/generate_x86.py generate`.
3. Implement the operation in `x86_exec.rs`. Leave flags the manuals call undefined unchanged.
4. Add assembly text to `crates/loader/tests/x86/assemble.py`, run it with `generate`, and extend the reference in `tests/x86_integer.rs` or `tests/x86_vector.rs`. A declared form without a fixture fails `every_declared_form_is_executed_by_a_fixture`.
@@ -68,21 +68,6 @@ MFENCE, LFENCE and SFENCE (`0F AE` with a register ModRM byte and digit 6, 5 or
This holds only while guest threads do not run on several host threads. ARM64 orders memory more weakly than x86, so an engine that ran guest threads in parallel would have to restore x86's ordering for ordinary accesses and give the fences a real effect. Nothing here provides or tests that. `tests/cpu_known_answers.rs` holds the single-thread cases: a store, a fence and a later load in program order, and no change to any other state. None of it has been compared with x86 hardware.
## x87 state and FNINIT
FNINIT (`DB E3`) is the only x87 instruction. It exists because the mingw-w64 C runtime runs it once before `main`, in `_fpreset`, and a program built with that runtime could not start without it.
`CpuState::x87` holds the control, status and tag words. FNINIT sets them to the values the Intel SDM gives (Vol. 2A, "FINIT/FNINIT"): control `037F` (every exception masked, 64-bit precision, round to nearest), status `0` and tag `FFFF` (every register empty). It changes nothing else, and both engines run the same shared code for it; nothing is lowered to ARM64. The host's floating-point state is never read or written.
What this does not include:
- **No other x87 instruction.** FNSTCW, FLDCW, FNCLEX, FWAIT (so FINIT, which is `9B DB E3`), every load, store and arithmetic form stay rejected. Nothing can read the three words back, so today they are only visible to a host that inspects `CpuState`.
- **No data registers.** FNINIT leaves them unchanged on a real processor and tags them empty; Xenora has none. The x87 instruction and data pointers and the last opcode, which FNINIT also clears, are not modelled either.
- **No operating-system start value.** A new `CpuState` holds the FNINIT values. An operating system may start a thread with a different control word, which is not modelled.
- **CPUID still reports no FPU.** One instruction of the feature is not the feature.
The registry key `rm = 3` makes the form match that one ModRM byte. The other register bytes of `DB /4` are different instructions (`DB E2` is FNCLEX), so the form cannot ignore the r/m field the way the fences do. `fninit_is_the_only_x87_encoding_accepted` in `tests/x86_integer.rs` tries every ModRM byte under the eight x87 opcodes, `D8` to `DF`, in both engines. A segment override or REX prefix before FNINIT is accepted and has no effect, as for other forms without operands. `prefixes_accepted_before_fninit_have_no_effect` pins that as a local rule; it was not derived from a manual statement. The 0x66, F2, F3 and LOCK prefixes are refused. Nothing here has been compared with x86 hardware.
## String instructions
MOVS and STOS exist for 8-, 16-, 32- and 64-bit elements, alone and with REP (F3), together with the direction flag and CLD and STD. `CpuState::df` holds the flag. It is not one of the six status flags the registry tracks.
@@ -104,12 +89,12 @@ CPUID (`0F A2`) returns a fixed table that never reads the host. It describes a
| 0 | 1, the highest basic leaf | `Xeno` | `uest` | `ra g` |
| 1 | 0 | 0 | POPCNT (bit 23) | CMOV (bit 15) |
| 0x8000_0000 | 0x8000_0001, the highest extended leaf | 0 | 0 | 0 |
| 0x8000_0001 | 0 | 0 | LAHF/SAHF (bit 0), LZCNT (bit 5) | long mode (bit 29) |
| 0x8000_0001 | 0 | 0 | LZCNT (bit 5) | long mode (bit 29) |
| any other | 0 | 0 | 0 | 0 |
A feature bit is set only when every instruction of that feature is implemented. That is stricter than "some of it works", and it has consequences:
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MASKMOVDQU, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU is not reported although FNINIT exists. MMX, FXSAVE, CMPXCHG8B, the time-stamp counter and SYSRET are absent too.
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MASKMOVDQU, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU, MMX, FXSAVE, CMPXCHG8B, the time-stamp counter, LAHF and SYSRET are absent too.
- The table is therefore truthful about BetterXen, not plausible as hardware: every real 64-bit processor reports the FPU and SSE2. A guest that tests a bit before using a feature avoids it; a guest that assumes SSE2 because it runs in 64-bit mode still gets every form that exists and an illegal-instruction exit for one that does not.
- A leaf that is not listed returns zeros, whatever the subleaf. Intel processors answer a leaf above the highest basic one with that leaf's data instead; software is expected to read the highest leaf first.
@@ -119,4 +104,4 @@ A feature bit is set only when every instruction of that feature is implemented.
## Rejected on purpose
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, LODS, CMPS, SCAS, REPE and REPNE, every x87 instruction except FNINIT, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B and CMPXCHG16B. The DBT also refuses raw SYSCALL.
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B and CMPXCHG16B. The DBT also refuses raw SYSCALL.
-18
View File
@@ -222,24 +222,6 @@ References include Microsoft's
[virtual allocation](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc),
and [virtual release](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualfree) contracts.
### Stubs a hosted C program binds
`VirtualProtect`, `VirtualQuery` and `__C_specific_handler` are declared
`stub` in the typed registry (`docs/runtime/services.md`). A C program built
with the mingw-w64 runtime imports all three and does not call them on a
normal run: the first two serve its runtime pseudo-relocations, and the third
is the language handler Windows calls while dispatching a structured
exception. They exist so that such a program's imports bind.
A call to any of them stops the guest with the runtime-limit fault
(`IllegalInstruction(0xFE)`). The service writes nothing: no output buffer, no
result and no last-error value. It does not return a made-up success or a
failure code Windows would not give, so a program that needs one of them
stops at that call. Nothing here changes a page protection, describes a
region or dispatches an exception; each needs work the runtime does not have
yet (regions that can be split, translated-code invalidation for executable
pages, recorded allocation bases, exception dispatch).
### CRT strings and byte memory
The standard registry provides `strlen` and `strnlen` under UCRT and the CRT
+6 -9
View File
@@ -6,14 +6,14 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
| Measure | Count |
| --- | ---: |
| Services with a declared ABI | 23 |
| Generated adapters | 23 |
| Unique handler implementations | 23 |
| Services with a declared ABI | 20 |
| Generated adapters | 20 |
| Unique handler implementations | 20 |
| Implemented | 7 |
| Partial | 13 |
| Stub | 3 |
| Conformance-tested through guest dispatch | 23 |
| API-set aliases (not services) | 23 |
| Stub | 0 |
| Conformance-tested through guest dispatch | 20 |
| API-set aliases (not services) | 20 |
| Independently accepted | 0 |
| Service | Signature | Status | Failure |
@@ -34,9 +34,6 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
| `kernel32.dll!SetLastError` | `(code: u32) -> void` | partial | never |
| `kernel32.dll!VirtualAlloc` | `(address: ptr, size: u64, kind: u32, protect: u32) -> ptr` | partial | 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY |
| `kernel32.dll!VirtualFree` | `(address: ptr, size: u64, kind: u32) -> bool32` | partial | 0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS |
| `kernel32.dll!VirtualProtect` | `(address: ptr, size: u64, protect: u32, old: out<4>) -> bool32` | stub | always: stops the guest with the runtime-limit fault; no protection changes |
| `kernel32.dll!VirtualQuery` | `(address: ptr, information: out<48>, length: u64) -> u64` | stub | always: stops the guest with the runtime-limit fault; nothing is written |
| `ucrtbase.dll!__C_specific_handler` | `(record: ptr, frame: ptr, context: ptr, dispatcher: ptr) -> i32` | stub | always: stops the guest with the runtime-limit fault; no exception is dispatched |
| `ucrtbase.dll!sqrt` | `(x: f64) -> f64` | partial | NaN for a negative argument; errno is not set |
| `ucrtbase.dll!sqrtf` | `(x: f32) -> f32` | partial | NaN for a negative argument; errno is not set |
| `ucrtbase.dll!fabs` | `(x: f64) -> f64` | implemented | never |
-23
View File
@@ -75,29 +75,6 @@ class GenerateX86(unittest.TestCase):
self.rejects(self.form('op = "mov"\nopcode = 0xD7\nenc = "reg_rm"\nsize = "v"\nlock = true'), message)
self.rejects(self.form('op = "xadd"\nopcode = 0xD7\nenc = "rm_reg"\nsize = "v"\nregister_only = true\nlock = true'), message)
def test_a_fixed_rm_field_needs_a_register_only_digit_form(self):
base = 'op = "nop"\nopcode = 0xD9\nenc = "rm_unread"\nsize = "n"\n'
message = "needs register_only and a digit"
self.rejects(self.form(base + "digit = 0\nrm = 3"), message)
self.rejects(self.form(base + "digit = 0\nmemory_only = true\nrm = 3"), message)
self.rejects(self.form(base + "register_only = true\nrm = 3"), message)
for value in ("8", "-1", "true", '"3"'):
self.rejects(self.form(base + f"digit = 0\nregister_only = true\nrm = {value}"), "r/m field value 0-7")
# A second form on the same opcode and digit is an overlap, whatever its r/m field.
self.rejects(self.form('op = "nop"\nopcode = 0xDB\ndigit = 4\nenc = "rm_unread"\nsize = "n"\n'
"register_only = true\nrm = 2"), "overlapping")
# The valid shape loads, and the key reaches the generated table.
operations, forms = generate_x86.load(self.form(base + "digit = 0\nregister_only = true\nrm = 7"))
self.assertEqual([f["rm"] for f in forms if f["map"] == "1" and f["opcode"] == 0xD9], [7])
self.assertIn("register_only: true, fixed_rm: Some(7),", generate_x86.generate(operations, forms))
def test_fninit_is_the_only_form_with_a_fixed_rm_field_and_the_only_x87_form(self):
_, forms = generate_x86.load(REGISTRY)
fixed = [(f["op"], f["map"], f["opcode"], f["digit"], f["rm"]) for f in forms if f["rm"] is not None]
self.assertEqual(fixed, [("fninit", "1", 0xDB, 4, 3)])
x87 = [f["op"] for f in forms if f["map"] == "1" and 0xD8 <= f["opcode"] <= 0xDF]
self.assertEqual(x87, ["fninit"])
def test_only_xadd_and_cmpxchg_are_lockable(self):
_, forms = generate_x86.load(REGISTRY)
self.assertEqual({form["op"] for form in forms if form.get("lock")}, {"cmpxchg", "xadd"})