mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 22:50:44 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d9f46929a1 | ||
|
|
20d7b9ece4 | ||
|
|
d5fa319f56 | ||
|
|
f30e4af4eb | ||
|
|
714eaf49e2 | ||
|
|
721073169c | ||
|
|
007ad360e9 | ||
|
|
7d28fc89de |
No files matched your search
@@ -23,6 +23,7 @@ remains unsupported.
|
||||
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
|
||||
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
|
||||
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
|
||||
- Avoided resolver allocations for permitted guest data reads and writes contained in one mapping, preserving checked fallback for split spans and faults (#105).
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
@@ -132,6 +133,8 @@ 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.
|
||||
|
||||
@@ -71,6 +71,13 @@ 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",
|
||||
],
|
||||
_ => &[],
|
||||
}
|
||||
|
||||
@@ -148,6 +148,34 @@ 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
|
||||
|
||||
+613
-1
@@ -5,7 +5,7 @@
|
||||
//! Provides isolated, page-aligned guest virtual memory with permission checking
|
||||
//! (Read, Write, Execute) and bounds enforcement without host OS mapping tricks.
|
||||
|
||||
use std::fmt;
|
||||
use std::{fmt, ops::Range};
|
||||
|
||||
pub(crate) const ALLOCATION_GRANULARITY: u64 = 65_536;
|
||||
|
||||
@@ -520,14 +520,39 @@ impl GuestMemory {
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
if let Some((index, range)) = self.contiguous_region(address, src.len())
|
||||
&& self.regions[index].permissions.write
|
||||
{
|
||||
self.regions[index].data[range].copy_from_slice(src);
|
||||
return Ok(());
|
||||
}
|
||||
self.write_checked(address, src, Some("write"))
|
||||
}
|
||||
|
||||
/// Read raw bytes from guest memory at the specified address, checking permissions.
|
||||
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
|
||||
if let Some((index, range)) = self.contiguous_region(address, dst.len())
|
||||
&& self.regions[index].permissions.read
|
||||
{
|
||||
dst.copy_from_slice(&self.regions[index].data[range]);
|
||||
return Ok(());
|
||||
}
|
||||
self.read_checked(address, dst, Some("read"))
|
||||
}
|
||||
|
||||
// Only the first eligible mapping may supply the whole span. Otherwise
|
||||
// the checked resolver must preserve split-access and overlap priority.
|
||||
fn contiguous_region(&self, address: u64, len: usize) -> Option<(usize, Range<usize>)> {
|
||||
let (index, region) = self
|
||||
.regions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, region)| region.base + region.data.len() as u64 > address)?;
|
||||
let offset = usize::try_from(address.checked_sub(region.base)?).ok()?;
|
||||
let end = offset.checked_add(len)?;
|
||||
(end <= region.data.len()).then_some((index, offset..end))
|
||||
}
|
||||
|
||||
/// Read an instruction byte from guest memory, verifying execute permission.
|
||||
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
|
||||
address.checked_add(1).ok_or(MemoryError::Overflow)?;
|
||||
@@ -869,3 +894,590 @@ mod instruction_fetch_tests {
|
||||
assert_eq!(m.fetch_instruction_byte(BASE + 3), Ok(0x44));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod data_access_contract_tests {
|
||||
use super::{MemoryPermissions as P, *};
|
||||
const A: u64 = 0x10_0000;
|
||||
|
||||
#[test]
|
||||
fn data_permissions_are_independent_and_failed_reads_leave_output_untouched() {
|
||||
for bits in 0..8 {
|
||||
let p = P {
|
||||
read: bits & 1 != 0,
|
||||
write: bits & 2 != 0,
|
||||
execute: bits & 4 != 0,
|
||||
};
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 4, p, &[1, 2, 3, 4]).unwrap();
|
||||
let mut out = [0xee; 2];
|
||||
let read = m.read_bytes(A + 1, &mut out);
|
||||
assert_eq!(
|
||||
read,
|
||||
if p.read {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 1,
|
||||
required: "read",
|
||||
})
|
||||
}
|
||||
);
|
||||
assert_eq!(out, if p.read { [2, 3] } else { [0xee; 2] });
|
||||
let write = m.write_bytes(A + 1, &[0x55, 0x66]);
|
||||
assert_eq!(
|
||||
write,
|
||||
if p.write {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 1,
|
||||
required: "write",
|
||||
})
|
||||
}
|
||||
);
|
||||
let mut stored = [0; 4];
|
||||
m.read_checked(A, &mut stored, None).unwrap();
|
||||
assert_eq!(
|
||||
stored,
|
||||
if p.write {
|
||||
[1, 0x55, 0x66, 4]
|
||||
} else {
|
||||
[1, 2, 3, 4]
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_data_spans_keep_inclusive_ends_and_ignore_permissions() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0, P::NO_ACCESS).unwrap();
|
||||
m.map_region(A + 16, 3, P::NO_ACCESS).unwrap();
|
||||
m.map_region(u64::MAX, 0, P::NO_ACCESS).unwrap();
|
||||
for at in [A, A + 16, A + 17, A + 19, u64::MAX] {
|
||||
assert_eq!(m.read_bytes(at, &mut []), Ok(()));
|
||||
assert_eq!(m.write_bytes(at, &[]), Ok(()));
|
||||
}
|
||||
for at in [A - 1, A + 1, A + 15, A + 20] {
|
||||
assert_eq!(
|
||||
m.read_bytes(at, &mut []),
|
||||
Err(MemoryError::UnmappedAddress(at))
|
||||
);
|
||||
assert_eq!(
|
||||
m.write_bytes(at, &[]),
|
||||
Err(MemoryError::UnmappedAddress(at))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_address_overflow_precedes_permissions_and_preserves_output() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(u64::MAX - 3, 3, P::NO_ACCESS).unwrap();
|
||||
let mut out = [0xee; 2];
|
||||
assert_eq!(
|
||||
m.read_bytes(u64::MAX - 1, &mut out),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(out, [0xee; 2]);
|
||||
assert_eq!(
|
||||
m.write_bytes(u64::MAX - 1, &[1, 2]),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(
|
||||
m.read_bytes(u64::MAX, &mut out[..1]),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(m.write_bytes(u64::MAX, &[1]), Err(MemoryError::Overflow));
|
||||
assert_eq!(m.read_u16(u64::MAX - 1), Err(MemoryError::Overflow));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_data_accesses_keep_exact_fallback_errors_and_atomicity() {
|
||||
for (gap, right) in [
|
||||
(0, P::READ_WRITE),
|
||||
(0, P::READ_ONLY),
|
||||
(0, P::NO_ACCESS),
|
||||
(
|
||||
0,
|
||||
P {
|
||||
read: false,
|
||||
write: true,
|
||||
execute: false,
|
||||
},
|
||||
),
|
||||
(1, P::READ_WRITE),
|
||||
] {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 8, P::READ_WRITE, &[0, 1, 2, 3, 4, 5, 6, 7])
|
||||
.unwrap();
|
||||
let b = A + 8 + gap;
|
||||
m.map_region_with_data(b, 8, right, &[8, 9, 10, 11, 12, 13, 14, 15])
|
||||
.unwrap();
|
||||
let mut expected = m.clone();
|
||||
let mut actual_out = [0xee; 4];
|
||||
let mut expected_out = [0xee; 4];
|
||||
assert_eq!(
|
||||
m.read_bytes(A + 6, &mut actual_out),
|
||||
expected.read_checked(A + 6, &mut expected_out, Some("read"))
|
||||
);
|
||||
assert_eq!(actual_out, expected_out);
|
||||
assert_eq!(
|
||||
actual_out,
|
||||
if gap == 0 && right.read {
|
||||
[6, 7, 8, 9]
|
||||
} else {
|
||||
[0xee; 4]
|
||||
}
|
||||
);
|
||||
let bytes = [0xa0, 0xa1, 0xa2, 0xa3];
|
||||
assert_eq!(
|
||||
m.write_bytes(A + 6, &bytes),
|
||||
expected.write_checked(A + 6, &bytes, Some("write"))
|
||||
);
|
||||
let written = gap == 0 && right.write;
|
||||
assert_eq!(
|
||||
m.read_u64_bypass(A).unwrap().to_le_bytes(),
|
||||
if written {
|
||||
[0, 1, 2, 3, 4, 5, 0xa0, 0xa1]
|
||||
} else {
|
||||
[0, 1, 2, 3, 4, 5, 6, 7]
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
m.read_u64_bypass(b).unwrap().to_le_bytes(),
|
||||
if written {
|
||||
[0xa2, 0xa3, 10, 11, 12, 13, 14, 15]
|
||||
} else {
|
||||
[8, 9, 10, 11, 12, 13, 14, 15]
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_accesses_keep_first_mapping_priority_for_partial_overlaps() {
|
||||
const BASE: u64 = 0x0000_0003_0000_0000;
|
||||
for first in [P::READ_WRITE, P::READ_ONLY] {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(0x1000, 1, P::NO_ACCESS).unwrap();
|
||||
m.map_region_with_data(BASE, 4, first, &[1, 2, 3, 4])
|
||||
.unwrap();
|
||||
let empty = m.map_heap_allocation(PROCESS_HEAP, 0).unwrap();
|
||||
assert_eq!(empty, BASE);
|
||||
assert_eq!(
|
||||
m.resize_heap_allocation(PROCESS_HEAP, empty, 8, true),
|
||||
Ok(BASE)
|
||||
);
|
||||
let mut out = [0xee; 8];
|
||||
assert_eq!(m.read_bytes(BASE, &mut out), Ok(()));
|
||||
assert_eq!(out, [1, 2, 3, 4, 0, 0, 0, 0]);
|
||||
assert_eq!(m.read_u16(BASE), Ok(0x0201));
|
||||
let bytes = [0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7];
|
||||
let mut expected = m.clone();
|
||||
assert_eq!(
|
||||
m.write_bytes(BASE, &bytes),
|
||||
expected.write_checked(BASE, &bytes, Some("write"))
|
||||
);
|
||||
m.read_bytes(BASE, &mut out).unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
if first.write {
|
||||
bytes
|
||||
} else {
|
||||
[1, 2, 3, 4, 0, 0, 0, 0]
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_accesses_observe_writes_clones_release_and_remap() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 8, P::READ_WRITE, &[1; 8])
|
||||
.unwrap();
|
||||
let mut clone = m.clone();
|
||||
m.write_u64(A, 0x1122_3344_5566_7788).unwrap();
|
||||
clone.write_u32(A, 0xaabb_ccdd).unwrap();
|
||||
assert_eq!(m.read_u64(A), Ok(0x1122_3344_5566_7788));
|
||||
assert_eq!(clone.read_u64(A), Ok(0x0101_0101_aabb_ccdd));
|
||||
let b = m.map_virtual_allocation(0x4000, 2, P::READ_WRITE).unwrap();
|
||||
m.write_u16(b, 0x1234).unwrap();
|
||||
assert_eq!(m.read_u16(b), Ok(0x1234));
|
||||
assert!(m.release_virtual_allocation(b));
|
||||
assert_eq!(m.read_u16(b), Err(MemoryError::UnmappedAddress(b)));
|
||||
m.map_region_with_data(b, 2, P::READ_ONLY, &[0x56, 0x78])
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u16(b), Ok(0x7856));
|
||||
assert_eq!(
|
||||
m.write_u8(b, 0),
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: b,
|
||||
required: "write"
|
||||
})
|
||||
);
|
||||
assert_eq!(clone.read_u16(b), Err(MemoryError::UnmappedAddress(b)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod data_memory_bench {
|
||||
use super::{MemoryPermissions as P, *};
|
||||
use crate::{CpuState, DbtEngine, ExitReason, Register};
|
||||
use std::{hint::black_box, time::Instant};
|
||||
|
||||
const CODE: u64 = 0x1000;
|
||||
const VALUE: u64 = 0xffff_ff00;
|
||||
#[derive(Clone, Copy)]
|
||||
enum Kind {
|
||||
Registers,
|
||||
Counter,
|
||||
Sequential,
|
||||
Split,
|
||||
}
|
||||
|
||||
fn setting(name: &str, default: usize, maximum: usize) -> usize {
|
||||
let value = std::env::var(name).map_or(default, |s| s.parse().expect(name));
|
||||
assert!((1..=maximum).contains(&value), "invalid {name}");
|
||||
value
|
||||
}
|
||||
fn quantile(sorted: &[f64], fraction: f64) -> f64 {
|
||||
let rank = (sorted.len() - 1) as f64 * fraction;
|
||||
let lo = rank.floor() as usize;
|
||||
sorted[lo] + (sorted[rank.ceil() as usize] - sorted[lo]) * rank.fract()
|
||||
}
|
||||
fn guest(kind: Kind, iterations: usize, data: u64) -> (Vec<u8>, usize) {
|
||||
// MOV RCX, iterations; MOV RDX, VALUE (control) or RSI, data; XOR EAX,EAX.
|
||||
let registers = matches!(kind, Kind::Registers);
|
||||
let sequential = matches!(kind, Kind::Sequential);
|
||||
let mut code = vec![0x48, 0xb9];
|
||||
code.extend_from_slice(&(iterations as u64).to_le_bytes());
|
||||
code.extend_from_slice(&[0x48, if registers { 0xba } else { 0xbe }]);
|
||||
let target = if registers { VALUE } else { data };
|
||||
code.extend_from_slice(&target.to_le_bytes());
|
||||
code.extend_from_slice(&[0x31, 0xc0]);
|
||||
let per_iteration = if registers {
|
||||
// ADD RAX,RDX; ADD RDX,1; DEC RCX; JNZ -12.
|
||||
code.extend_from_slice(&[
|
||||
0x48, 0x01, 0xd0, 0x48, 0x83, 0xc2, 0x01, 0x48, 0xff, 0xc9, 0x75, 0xf4,
|
||||
]);
|
||||
4
|
||||
} else {
|
||||
// MOV RDX,[RSI]; ADD RAX,RDX; ADD RDX,1; MOV [RSI],RDX.
|
||||
code.extend_from_slice(&[
|
||||
0x48, 0x8b, 0x16, 0x48, 0x01, 0xd0, 0x48, 0x83, 0xc2, 0x01, 0x48, 0x89, 0x16,
|
||||
]);
|
||||
if sequential {
|
||||
code.extend_from_slice(&[0x48, 0x83, 0xc6, 0x08]); // ADD RSI,8.
|
||||
}
|
||||
// DEC RCX; JNZ -22 (sequential) or -18 (counter).
|
||||
let back = if sequential { 0xea } else { 0xee };
|
||||
code.extend_from_slice(&[0x48, 0xff, 0xc9, 0x75, back]);
|
||||
6 + usize::from(sequential)
|
||||
};
|
||||
code.push(0xf4); // HLT; three setup instructions and one halt.
|
||||
(code, iterations * per_iteration + 4)
|
||||
}
|
||||
|
||||
// Run identical source on the baseline and candidate with the same release profile.
|
||||
// Allocation counting is deliberately separate: instrumentation distorts these timings.
|
||||
#[test]
|
||||
#[ignore = "manual, correctness-gated warm DBT data-memory timing"]
|
||||
fn warm_data_memory_benchmark() {
|
||||
let samples = setting("XENORA_DATA_BENCH_SAMPLES", 31, 1001);
|
||||
let counter = setting("XENORA_DATA_BENCH_ITERS", 32768, 65536);
|
||||
let sequential = setting("XENORA_DATA_BENCH_STREAM_ITERS", 16384, 65536);
|
||||
for (label, kind, regions, last) in [
|
||||
("register-control", Kind::Registers, 4, false),
|
||||
("counter-front", Kind::Counter, 4, false),
|
||||
("counter-front-many", Kind::Counter, 64, false),
|
||||
("counter-first", Kind::Counter, 4, false),
|
||||
("counter-first-many", Kind::Counter, 64, false),
|
||||
("counter-third-many", Kind::Counter, 64, false),
|
||||
("counter-middle", Kind::Counter, 64, false),
|
||||
("counter-last", Kind::Counter, 64, true),
|
||||
("sequential-front", Kind::Sequential, 4, false),
|
||||
("sequential-front-many", Kind::Sequential, 64, false),
|
||||
("sequential-first", Kind::Sequential, 4, false),
|
||||
("sequential-first-many", Kind::Sequential, 64, false),
|
||||
("sequential-last", Kind::Sequential, 64, true),
|
||||
("split-counter-control", Kind::Split, 4, false),
|
||||
] {
|
||||
let iterations = if matches!(kind, Kind::Sequential) {
|
||||
sequential
|
||||
} else {
|
||||
counter
|
||||
};
|
||||
let code_address = if label.contains("-first") {
|
||||
0x8000_0000
|
||||
} else {
|
||||
CODE
|
||||
};
|
||||
let data = if last {
|
||||
0x4000_0000
|
||||
} else if label.contains("-third") {
|
||||
0x20_1000
|
||||
} else if label.contains("-middle") {
|
||||
0x23_f000
|
||||
} else {
|
||||
0x1_0000
|
||||
};
|
||||
let (code, expected_instructions) = guest(kind, iterations, data);
|
||||
let words = if matches!(kind, Kind::Sequential) {
|
||||
iterations
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let initial: Vec<u8> = (0..words)
|
||||
.flat_map(|i| (VALUE + i as u64).to_le_bytes())
|
||||
.collect();
|
||||
let increment = match kind {
|
||||
Kind::Registers => 0,
|
||||
Kind::Sequential => 1,
|
||||
_ => iterations as u64,
|
||||
};
|
||||
let expected: Vec<u8> = (0..words)
|
||||
.flat_map(|i| (VALUE + i as u64 + increment).to_le_bytes())
|
||||
.collect();
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(code_address, 4096, P::READ_EXECUTE, &code)
|
||||
.unwrap();
|
||||
let pieces = if matches!(kind, Kind::Split) {
|
||||
memory
|
||||
.map_region_with_data(data, 4, P::READ_WRITE, &initial[..4])
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(data + 4, 4, P::READ_WRITE, &initial[4..])
|
||||
.unwrap();
|
||||
2
|
||||
} else {
|
||||
memory
|
||||
.map_region_with_data(data, initial.len(), P::READ_WRITE, &initial)
|
||||
.unwrap();
|
||||
1
|
||||
};
|
||||
for i in 0..regions - pieces - 1 {
|
||||
memory
|
||||
.map_region(0x20_0000 + i as u64 * 8192, 4096, P::READ_ONLY)
|
||||
.unwrap();
|
||||
}
|
||||
let initial_cpu = CpuState::new(code_address, 0x8000_0000); // No stack instructions.
|
||||
let mut dbt = DbtEngine::new(1024 * 1024).unwrap();
|
||||
let mut readback = vec![0; initial.len()];
|
||||
let n = iterations as u64;
|
||||
let sum = n * VALUE + n * (n - 1) / 2;
|
||||
let mut timings = Vec::with_capacity(samples);
|
||||
let warmups = 5;
|
||||
for sample in 0..samples + warmups {
|
||||
memory.write_bytes(data, &initial).unwrap();
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let before = dbt.metrics;
|
||||
let started = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut memory, expected_instructions + 16));
|
||||
let elapsed = started.elapsed();
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt, "{label}");
|
||||
assert_eq!(
|
||||
result.instructions_executed, expected_instructions,
|
||||
"{label}"
|
||||
);
|
||||
let state = (
|
||||
cpu.get(Register::Rax),
|
||||
cpu.get(Register::Rdx),
|
||||
cpu.get(Register::Rcx),
|
||||
);
|
||||
assert_eq!(state, (sum, VALUE + n, 0), "{label}");
|
||||
memory.read_bytes(data, &mut readback).unwrap();
|
||||
assert_eq!(readback, expected, "{label}");
|
||||
assert_eq!(dbt.metrics.interpreter_fallbacks, 0, "{label}");
|
||||
if sample > 0 {
|
||||
let compiled = |m: crate::DbtMetrics| {
|
||||
(m.blocks_compiled, m.native_bytes_emitted, m.cache_misses)
|
||||
};
|
||||
assert_eq!(compiled(dbt.metrics), compiled(before), "{label}");
|
||||
if sample >= warmups {
|
||||
timings.push(elapsed.as_nanos() as f64 / n as f64);
|
||||
}
|
||||
} else {
|
||||
assert!(dbt.metrics.blocks_compiled > 0, "{label}");
|
||||
}
|
||||
}
|
||||
timings.sort_by(f64::total_cmp);
|
||||
println!(
|
||||
"warm-data label={label} regions={regions} iterations={iterations} samples={samples} warmups={warmups} instructions={expected_instructions} median_ns_per_iteration={:.3} p10={:.3} p90={:.3}",
|
||||
quantile(&timings, 0.5),
|
||||
quantile(&timings, 0.1),
|
||||
quantile(&timings, 0.9)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod mapping_group_contract_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn aliases_preserve_bytes_across_resize_relocation_and_release() {
|
||||
const BASE: u64 = 0x0000_0003_0000_0000;
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region(BASE - 16, 8, MemoryPermissions::READ_ONLY)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(BASE, 4, MemoryPermissions::READ_ONLY, &[1, 2, 3, 4])
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(BASE + 16, 8, MemoryPermissions::READ_ONLY)
|
||||
.unwrap();
|
||||
let heap = memory.create_private_heap(0).unwrap();
|
||||
assert_eq!(memory.map_heap_allocation(PROCESS_HEAP, 0), Ok(BASE));
|
||||
assert_eq!(memory.map_heap_allocation(heap, 0), Ok(BASE));
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(PROCESS_HEAP, BASE, 8, true),
|
||||
Err(MemoryError::AllocationFailed)
|
||||
);
|
||||
assert_eq!(memory.resize_heap_allocation(heap, BASE, 8, true), Ok(BASE));
|
||||
memory.write_bytes(BASE + 4, &[5, 6, 7, 8]).unwrap();
|
||||
assert_eq!(memory.read_u64(BASE), Ok(0x0807_0605_0403_0201));
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(heap, BASE, 32, true),
|
||||
Err(MemoryError::AllocationFailed)
|
||||
);
|
||||
let moved = memory
|
||||
.resize_heap_allocation(heap, BASE, 32, false)
|
||||
.unwrap();
|
||||
assert_ne!(moved, BASE);
|
||||
let mut bytes = [0xff; 32];
|
||||
memory.read_bytes(moved, &mut bytes).unwrap();
|
||||
let mut expected = [0; 32];
|
||||
expected[4..8].copy_from_slice(&[5, 6, 7, 8]);
|
||||
assert_eq!(bytes, expected);
|
||||
let mut failed = [0xff; 8];
|
||||
assert_eq!(
|
||||
memory.read_bytes(BASE, &mut failed),
|
||||
Err(MemoryError::UnmappedAddress(BASE + 4))
|
||||
);
|
||||
assert_eq!(failed, [0xff; 8]);
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(PROCESS_HEAP, BASE, 8, true),
|
||||
Ok(BASE)
|
||||
);
|
||||
assert_eq!(memory.read_u64(BASE), Ok(0x0403_0201));
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(PROCESS_HEAP, BASE, 2, true),
|
||||
Ok(BASE)
|
||||
);
|
||||
assert_eq!(memory.read_u16(BASE + 2), Ok(0x0403));
|
||||
assert!(memory.release_heap_allocation(PROCESS_HEAP, BASE));
|
||||
assert_eq!(memory.read_u32(BASE), Ok(0x0403_0201));
|
||||
assert_eq!(memory.read_u64(BASE - 16), Ok(0));
|
||||
assert_eq!(memory.read_u64(BASE + 16), Ok(0));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod bounds_access_contract_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn permitted_empty_spans_and_high_addresses_keep_exact_bounds() {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
u64::MAX - 8,
|
||||
8,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&[1, 2, 3, 4, 5, 6, 7, 8],
|
||||
)
|
||||
.unwrap();
|
||||
for at in [u64::MAX - 8, u64::MAX - 4, u64::MAX - 1, u64::MAX] {
|
||||
assert_eq!(memory.read_bytes(at, &mut []), Ok(()));
|
||||
assert_eq!(memory.write_bytes(at, &[]), Ok(()));
|
||||
}
|
||||
assert_eq!(memory.read_u64(u64::MAX - 8), Ok(0x0807_0605_0403_0201));
|
||||
assert_eq!(memory.read_u8(u64::MAX - 1), Ok(8));
|
||||
let mut failed = [0xee; 2];
|
||||
assert_eq!(
|
||||
memory.read_bytes(u64::MAX - 1, &mut failed),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(failed, [0xee; 2]);
|
||||
assert_eq!(
|
||||
memory.write_u16(u64::MAX - 1, 0xffff),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(memory.read_u64(u64::MAX - 7), Err(MemoryError::Overflow));
|
||||
assert_eq!(
|
||||
memory.write_u64(u64::MAX - 7, u64::MAX),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
memory.write_u8(u64::MAX - 1, 0x99).unwrap();
|
||||
let mut actual = [0; 8];
|
||||
memory.read_bytes(u64::MAX - 8, &mut actual).unwrap();
|
||||
assert_eq!(actual, [1, 2, 3, 4, 5, 6, 7, 0x99]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod mapping_search_contract_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_mapping_and_gap_keeps_its_bytes_across_table_sizes() {
|
||||
const BASE: u64 = 0x40_0000;
|
||||
for count in [0usize, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 32, 33] {
|
||||
let mut memory = GuestMemory::new();
|
||||
for index in (0..count).rev() {
|
||||
memory
|
||||
.map_region_with_data(
|
||||
BASE + index as u64 * 0x100,
|
||||
8,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&[(index + 1) as u8; 8],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
memory.read_u8(BASE - 1),
|
||||
Err(MemoryError::UnmappedAddress(BASE - 1))
|
||||
);
|
||||
if count == 0 {
|
||||
assert_eq!(
|
||||
memory.read_u8(BASE),
|
||||
Err(MemoryError::UnmappedAddress(BASE))
|
||||
);
|
||||
assert_eq!(
|
||||
memory.write_u8(BASE, 1),
|
||||
Err(MemoryError::UnmappedAddress(BASE))
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_bytes(BASE, &mut []),
|
||||
Err(MemoryError::UnmappedAddress(BASE))
|
||||
);
|
||||
}
|
||||
for index in 0..count {
|
||||
let address = BASE + index as u64 * 0x100;
|
||||
let mut actual = [0; 8];
|
||||
memory.read_bytes(address, &mut actual).unwrap();
|
||||
assert_eq!(actual, [(index + 1) as u8; 8]);
|
||||
let replacement = [0x80 + index as u8; 8];
|
||||
memory.write_bytes(address, &replacement).unwrap();
|
||||
memory.read_bytes(address, &mut actual).unwrap();
|
||||
assert_eq!(actual, replacement);
|
||||
assert_eq!(memory.read_bytes(address + 8, &mut []), Ok(()));
|
||||
assert_eq!(
|
||||
memory.read_u8(address + 8),
|
||||
Err(MemoryError::UnmappedAddress(address + 8))
|
||||
);
|
||||
let mut failed = [0xee; 2];
|
||||
assert_eq!(
|
||||
memory.read_bytes(address + 7, &mut failed),
|
||||
Err(MemoryError::UnmappedAddress(address + 8))
|
||||
);
|
||||
assert_eq!(failed, [0xee; 2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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; 20] = [
|
||||
pub static SERVICES: [ServiceMetadata; 23] = [
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "SetProcessPriorityBoost",
|
||||
@@ -185,6 +185,39 @@ pub static SERVICES: [ServiceMetadata; 20] = [
|
||||
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",
|
||||
@@ -367,6 +400,38 @@ 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)?;
|
||||
|
||||
@@ -641,6 +641,9 @@ 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,
|
||||
@@ -865,6 +868,42 @@ 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;
|
||||
|
||||
@@ -658,6 +658,122 @@ 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();
|
||||
|
||||
@@ -196,6 +196,24 @@ 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,14 +6,14 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
|
||||
|
||||
| Measure | Count |
|
||||
| --- | ---: |
|
||||
| Services with a declared ABI | 20 |
|
||||
| Generated adapters | 20 |
|
||||
| Unique handler implementations | 20 |
|
||||
| Services with a declared ABI | 23 |
|
||||
| Generated adapters | 23 |
|
||||
| Unique handler implementations | 23 |
|
||||
| Implemented | 7 |
|
||||
| Partial | 13 |
|
||||
| Stub | 0 |
|
||||
| Conformance-tested through guest dispatch | 20 |
|
||||
| API-set aliases (not services) | 20 |
|
||||
| Stub | 3 |
|
||||
| Conformance-tested through guest dispatch | 23 |
|
||||
| API-set aliases (not services) | 23 |
|
||||
| Independently accepted | 0 |
|
||||
|
||||
| Service | Signature | Status | Failure |
|
||||
@@ -34,6 +34,9 @@ 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 |
|
||||
|
||||
Reference in new issue
Block a user