Compare commits

...
Author SHA1 Message Date
ates 829a94fa2f bx-cli: print clwb VEH traps : 0 when no CLWB records exist
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:47:28 +03:00
ates a8c4dbb77e Report sampled CLWB bounds and guest crashes in bx-cli trace
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:08:33 +03:00
Ateş d8b83818c1 Merge pull request #430 from MacosPorters/track-a/409-veh-clwb-crash-log
[M1-A2] Cover CLWB addressing and log unhandled guest exceptions
2026-11-26 18:01:49 +03:00
ates 0a2544cd51 Merge main and address review feedback on REX decoding, crash write isolation, and marker constant
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:01:41 +03:00
Ateş 0082d16b1e Merge pull request #424 from MacosPorters/track-b/411-xmem-core
[M1-B1] Enforce xmem title memory budgets
2026-11-26 17:19:59 +03:00
ates 4c7f1c5aff Merge main, sanitize console memory attributes in XMemVirtualAlloc, and zero larger stats tail
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 17:19:52 +03:00
Ateş d72350c854 Merge pull request #426 from MacosPorters/track-b/413-xcrdapi-dstorage
[M1-B3] Exercise asynchronous storage through XCRDAPI
2026-11-26 17:17:27 +03:00
ates 134eee3a28 Cover CLWB addressing and log unhandled guest exceptions
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:13:12 +03:00
ates 19c240edd5 Enforce xmem title memory budgets
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 09:38:59 +03:00
10 changed files with 664 additions and 107 deletions

No files matched your search

+3
View File
@@ -10,6 +10,8 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- Added structured unhandled exception logging with module-relative addresses and x64 registers, and expanded the CLWB conformance test to require six traps across ModRM, SIB, REX and RIP-relative operands (#409).
- Enforced the configured title memory cap for default heap allocations and virtual commits in `xmem.dll`. Added working-set accounting and a synthetic fixture for alignment, commit overlap, decommit, release, and memory transfer (#411).
- Added a BetterXen-only DirectStorage conformance interface for asynchronous uncompressed file and memory transfers, status arrays, and completion events in `XCRDAPI.dll` (#413).
- Implemented offline `xgameruntime.dll` task queues and async completion, local user handles, synthetic game-license queries, console identity, and bottle-local storage (#418). Added a synthetic conformance executable for Lockhart and Anaconda launches. Only the marked conformance title receives an active synthetic SKU. The build also produces an unmarked control with the same executable name. Queue shutdown delivers accepted callbacks, and bottle-local storage is keyed by executable path.
- `xg_xs.dll` computes linear 2D layouts for `R8G8B8A8` and BC1 through BC7 (`XGCreateTextureComputer`, `XGSuggestSwizzleMode`, and COM `IXGTextureAddressComputer`). Row pitch uses the public D3D12 256-byte alignment and each subresource is placed on the public 512-byte alignment. `GetResourceLayout` reports that aligned allocation span in `total_bytes` (512 for a 1x1 RGBA8 texture) and a separate D3D12-style `copy_end` on each footprint (4 for that same texture). Sizes are overflow-checked, null pointers return `E_POINTER`, and copies stay inside the caller buffers. `SW_64KB_S`, `SW_64KB_D`, and `SW_64KB_R` return `E_NOTIMPL` and write no address. Synthetic `test_xg_xs.exe` checks hand-computed mip offsets, alignment, refcounts, and a byte-identical copy round trip. This is not an Xbox hardware result (#415).
@@ -66,6 +68,7 @@ remains unsupported.
- 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
- `bx-cli trace` reports the highest sampled CLWB total as a lower bound, labels counterless CLWB records as samples, and lists unhandled exceptions with their code, module base, RVA, and RIP (#438).
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
+39 -1
View File
@@ -153,6 +153,16 @@ fn cmd_probe(path: &str) -> ExitCode {
ExitCode::SUCCESS
}
fn format_clwb_line(clwb_events: usize, clwb_trap_lower_bound: Option<u64>) -> String {
if let Some(lower_bound) = clwb_trap_lower_bound {
format!("clwb VEH traps : at least {lower_bound} (sampled)")
} else if clwb_events == 0 {
"clwb VEH traps : 0".to_string()
} else {
format!("clwb VEH samples : {clwb_events}")
}
}
fn cmd_trace(path: &str) -> ExitCode {
let text = match fs::read_to_string(path) {
Ok(s) => s,
@@ -163,8 +173,26 @@ fn cmd_trace(path: &str) -> ExitCode {
};
let summary = summarize_jsonl(&text);
println!("Trace events : {}", summary.total_lines);
println!("clwb VEH traps : {}", summary.clwb_events);
println!(
"{}",
format_clwb_line(summary.clwb_events, summary.clwb_trap_lower_bound)
);
println!("ADX illegal ops : {}", summary.adx_errors);
if !summary.unhandled_exceptions.is_empty() {
println!(
"\nUnhandled exceptions ({}):",
summary.unhandled_exceptions.len()
);
for crash in summary.unhandled_exceptions {
println!(
" code={} module_base={} + RVA={} RIP={}",
crash.exception_code.as_deref().unwrap_or("unknown"),
crash.module_base.as_deref().unwrap_or("unknown"),
crash.rva.as_deref().unwrap_or("unknown"),
crash.rip.as_deref().unwrap_or("unknown"),
);
}
}
if !summary.unimpl_apis.is_empty() {
println!("\nUnimplemented APIs:");
for (api, count) in summary.unimpl_apis {
@@ -414,4 +442,14 @@ mod tests {
"Z:\\tmp\\bx-test.jsonl"
);
}
#[test]
fn formats_clwb_summary_lines() {
assert_eq!(format_clwb_line(0, None), "clwb VEH traps : 0");
assert_eq!(format_clwb_line(2, None), "clwb VEH samples : 2");
assert_eq!(
format_clwb_line(3, Some(4)),
"clwb VEH traps : at least 4 (sampled)"
);
}
}
+93 -3
View File
@@ -1,20 +1,32 @@
//! Track A / F: Structured JSONL shim trace aggregator.
//!
//! Summarizes `bx_runtime_veh.dll` logs (stub API calls, unimplemented COM vtable
//! slots, `clwb` traps, and ADX illegal-instruction tripwires) so tracks can prioritize
//! the exact next blocking API.
//! slots, `clwb` traps, ADX illegal-instruction tripwires, and unhandled exceptions)
//! so tracks can identify guest failures and missing APIs.
use std::collections::BTreeMap;
#[derive(Debug, Default, PartialEq, Eq)]
pub struct TraceSummary {
pub total_lines: usize,
/// Number of `clwb_trapped` records in the log.
pub clwb_events: usize,
/// Highest cumulative counter in the sampled CLWB records, if available.
pub clwb_trap_lower_bound: Option<u64>,
pub adx_errors: usize,
pub unhandled_exceptions: Vec<UnhandledException>,
pub unimpl_apis: BTreeMap<String, usize>,
pub unimpl_vtables: BTreeMap<String, usize>,
}
#[derive(Debug, PartialEq, Eq)]
pub struct UnhandledException {
pub exception_code: Option<String>,
pub module_base: Option<String>,
pub rva: Option<String>,
pub rip: Option<String>,
}
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let needle = format!("\"{key}\":\"");
let start = line.find(&needle)? + needle.len();
@@ -34,8 +46,23 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
let event = extract_json_str(trimmed, "event").unwrap_or("");
let detail = extract_json_str(trimmed, "detail").unwrap_or("");
match event {
"clwb_trapped" => summary.clwb_events += 1,
"clwb_trapped" => {
summary.clwb_events += 1;
let sample = detail
.split_ascii_whitespace()
.find_map(|field| field.strip_prefix("total_traps="))
.and_then(|count| count.parse::<u64>().ok());
summary.clwb_trap_lower_bound = summary.clwb_trap_lower_bound.max(sample);
}
"adx_illegal_instruction" => summary.adx_errors += 1,
"unhandled_exception" => {
summary.unhandled_exceptions.push(UnhandledException {
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
});
}
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
"unimpl_vtable" => {
*summary
@@ -64,7 +91,9 @@ mod tests {
let s = summarize_jsonl(sample);
assert_eq!(s.total_lines, 4);
assert_eq!(s.clwb_events, 1);
assert_eq!(s.clwb_trap_lower_bound, Some(1));
assert_eq!(s.adx_errors, 0);
assert!(s.unhandled_exceptions.is_empty());
assert_eq!(
s.unimpl_apis.get("d3d12_xs.dll!D3D12XboxCreateDevice"),
Some(&2)
@@ -75,4 +104,65 @@ mod tests {
Some(&1)
);
}
#[test]
fn uses_highest_counter_from_sampled_clwb_records() {
for (actual_traps, records, expected_bound) in [
(1, &[1][..], 1),
(6, &[1, 4, 2], 4),
(100, &[1, 2, 4, 8, 16, 32, 64], 64),
] {
let mut log = String::new();
for counter in records {
log.push_str(&format!(
"{{\"event\":\"clwb_trapped\",\"detail\":\"rip=0x1000 len=4 total_traps={counter}\"}}\n"
));
}
let summary = summarize_jsonl(&log);
assert_eq!(summary.clwb_events, records.len(), "{actual_traps} traps");
assert_eq!(
summary.clwb_trap_lower_bound,
Some(expected_bound),
"{actual_traps} traps"
);
}
}
#[test]
fn preserves_clwb_record_count_without_valid_counters() {
let summary = summarize_jsonl(
r#"{"event":"clwb_trapped","detail":"rip=0x1000 len=4"}
{"event":"clwb_trapped","detail":"rip=0x1000 len=4 total_traps=invalid"}
{"event":"unimpl_api","detail":"total_traps=100"}"#,
);
assert_eq!(summary.clwb_events, 2);
assert_eq!(summary.clwb_trap_lower_bound, None);
}
#[test]
fn collects_unhandled_exceptions_in_log_order() {
let log = r#"
{"ts_ms":16,"tid":1,"level":"ERROR","sub":"runtime_veh","event":"unhandled_exception","exception_code":"0xc0000005","module_base":"0x0000000140000000","rva":"0x0000000000001234","rip":"0x0000000140001234","rsp":"0x000000000021fd80","registers":{"rax":"0x0123456789abcdef","rbx":"0x0000000000000000","rcx":"0x0000000000000000","rdx":"0x0000000000000000","rsi":"0x0000000000000000","rdi":"0x0000000000000000","rbp":"0x0000000000000000","r8":"0x0000000000000000","r9":"0x0000000000000000","r10":"0x0000000000000000","r11":"0x0000000000000000","r12":"0x0000000000000000","r13":"0x0000000000000000","r14":"0x0000000000000000","r15":"0x0000000000000000"}}
{"ts_ms":20,"tid":1,"level":"ERROR","sub":"runtime_veh","event":"unhandled_exception","exception_code":"0xc000001d","module_base":"0x0000000000000000","rva":"0x0000000000000000","rip":"0x0000000000410000","rsp":"0x000000000021fd80","registers":{}}
"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.total_lines, 2);
assert_eq!(
summary.unhandled_exceptions,
[
UnhandledException {
exception_code: Some("0xc0000005".into()),
module_base: Some("0x0000000140000000".into()),
rva: Some("0x0000000000001234".into()),
rip: Some("0x0000000140001234".into()),
},
UnhandledException {
exception_code: Some("0xc000001d".into()),
module_base: Some("0x0000000000000000".into()),
rva: Some("0x0000000000000000".into()),
rip: Some("0x0000000000410000".into()),
},
]
);
}
}
+122 -59
View File
@@ -13,6 +13,9 @@ CRITICAL_SECTION g_log_lock;
bool g_log_lock_ready = false;
HANDLE g_log_handle = INVALID_HANDLE_VALUE;
PVOID g_veh_handle = nullptr;
LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = nullptr;
std::atomic_flag g_crash_logged{};
std::atomic<bool> g_crash_in_flight{false};
std::atomic<uint64_t> g_clwb_traps{0};
bx_runtime_config_t g_config = {
BX_ABI_VERSION,
@@ -26,6 +29,11 @@ bx_runtime_config_t g_config = {
};
void write_log_line(const char* line, size_t len) {
// Pause regular logging while a terminal crash record is being emitted so
// background threads cannot interleave with the unlocked crash WriteFile.
if (g_crash_in_flight.load(std::memory_order_acquire)) {
return;
}
if (g_log_lock_ready) {
EnterCriticalSection(&g_log_lock);
}
@@ -45,90 +53,135 @@ void write_log_line(const char* line, size_t len) {
}
}
/*
* Decode an x86-64 `clwb m8` instruction at `ip`.
* Encoding: [legacy prefixes] 0x66 [REX 0x40..0x4F] 0x0F 0xAE /6 (mod != 3).
* Returns total instruction length in bytes, or 0 if `ip` is not `clwb`.
*/
size_t decode_clwb_length(const uint8_t* ip) {
constexpr size_t kMaxInstructionLength = 15;
size_t read_instruction(uint64_t rip, uint8_t (&bytes)[kMaxInstructionLength]) {
HANDLE process = GetCurrentProcess();
if (ReadProcessMemory(process, reinterpret_cast<LPCVOID>(rip),
bytes, sizeof(bytes), nullptr)) {
return sizeof(bytes);
}
// A short instruction can end immediately before an inaccessible page.
size_t size = 0;
while (size < sizeof(bytes) &&
ReadProcessMemory(process, reinterpret_cast<LPCVOID>(rip + size),
&bytes[size], 1, nullptr)) {
++size;
}
return size;
}
// CLWB is 66 0F AE /6 with a memory operand. The address-size override
// selects 32-bit addressing but leaves the ModRM/SIB displacement lengths intact.
size_t decode_clwb_length(const uint8_t* ip, size_t size) {
size_t idx = 0;
bool has_66 = false;
bool has_addr_override = false;
while (idx < 6) {
uint8_t b = ip[idx];
if (b == 0x66) {
while (idx < size) {
const uint8_t byte = ip[idx];
if (byte == 0x66) {
has_66 = true;
idx++;
} else if (b == 0x67) {
has_addr_override = true;
idx++;
} else if (b == 0x26 || b == 0x2E || b == 0x36 || b == 0x3E || b == 0x64 || b == 0x65) {
idx++;
} else {
} else if (byte != 0x67 && byte != 0x26 && byte != 0x2E &&
byte != 0x36 && byte != 0x3E && byte != 0x64 && byte != 0x65) {
break;
}
}
(void)has_addr_override;
if (!has_66) {
return 0;
++idx;
}
if ((ip[idx] & 0xF0) == 0x40) {
idx++; /* Optional REX prefix */
// x86-64 allows at most one REX prefix immediately before the opcode.
if (idx < size && (ip[idx] & 0xF0) == 0x40) {
++idx;
}
if (ip[idx] != 0x0F || ip[idx + 1] != 0xAE) {
if (!has_66 || size - idx < 3 || ip[idx] != 0x0F || ip[idx + 1] != 0xAE) {
return 0;
}
idx += 2;
uint8_t modrm = ip[idx++];
uint8_t mod = (modrm >> 6) & 0x3;
uint8_t reg = (modrm >> 3) & 0x7;
uint8_t rm = modrm & 0x7;
/* `clwb` requires memory operand (mod != 3) and opcode extension /6. */
const uint8_t modrm = ip[idx++];
const uint8_t mod = modrm >> 6;
const uint8_t reg = (modrm >> 3) & 7;
const uint8_t rm = modrm & 7;
if (mod == 3 || reg != 6) {
return 0;
}
uint8_t base = rm;
if (rm == 4) {
uint8_t sib = ip[idx++];
if (mod == 0 && (sib & 0x7) == 5) {
idx += 4; /* disp32 with no base */
if (idx == size) {
return 0;
}
} else if (mod == 0 && rm == 5) {
idx += 4; /* RIP-relative disp32 */
base = ip[idx++] & 7;
}
if (mod == 1) {
idx += 1; /* disp8 */
} else if (mod == 2) {
idx += 4; /* disp32 */
idx += 1;
} else if (mod == 2 || (mod == 0 && base == 5)) {
idx += 4;
}
return idx;
return idx <= size ? idx : 0;
}
bool is_adx_opcode(const uint8_t* ip) {
bool is_adx_opcode(const uint8_t* ip, size_t size) {
size_t idx = 0;
bool has_66_or_f3 = false;
while (idx < 4) {
if (ip[idx] == 0x66 || ip[idx] == 0xF3) {
has_66_or_f3 = true;
idx++;
} else {
break;
}
while (idx < size && (ip[idx] == 0x66 || ip[idx] == 0xF3)) {
++idx;
}
if (!has_66_or_f3) {
if (idx == 0) {
return false;
}
if ((ip[idx] & 0xF0) == 0x40) {
idx++;
if (idx < size && (ip[idx] & 0xF0) == 0x40) {
++idx;
}
return ip[idx] == 0x0F && ip[idx + 1] == 0x38 && ip[idx + 2] == 0xF6;
// Require the 3-byte ADCX/ADOX opcode (0F 38 F6) plus at least 1 ModRM byte.
return size - idx >= 4 && ip[idx] == 0x0F && ip[idx + 1] == 0x38 && ip[idx + 2] == 0xF6;
}
LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) {
// Wine can invoke the top-level filter again for the same terminal fault.
if (ep && ep->ExceptionRecord && ep->ContextRecord &&
!g_crash_logged.test_and_set(std::memory_order_relaxed)) {
g_crash_in_flight.store(true, std::memory_order_release);
const CONTEXT& ctx = *ep->ContextRecord;
MEMORY_BASIC_INFORMATION region{};
unsigned long long module_base = 0;
if (VirtualQuery(reinterpret_cast<LPCVOID>(ctx.Rip), &region, sizeof(region)) &&
region.Type == MEM_IMAGE) {
module_base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
char line[1024];
int length = std::snprintf(
line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"ERROR\",\"sub\":\"runtime_veh\","
"\"event\":\"unhandled_exception\",\"exception_code\":\"0x%08lx\","
"\"module_base\":\"0x%016llx\",\"rva\":\"0x%016llx\","
"\"rip\":\"0x%016llx\",\"rsp\":\"0x%016llx\","
"\"registers\":{\"rax\":\"0x%016llx\",\"rbx\":\"0x%016llx\","
"\"rcx\":\"0x%016llx\",\"rdx\":\"0x%016llx\",\"rsi\":\"0x%016llx\","
"\"rdi\":\"0x%016llx\",\"rbp\":\"0x%016llx\",\"r8\":\"0x%016llx\","
"\"r9\":\"0x%016llx\",\"r10\":\"0x%016llx\",\"r11\":\"0x%016llx\","
"\"r12\":\"0x%016llx\",\"r13\":\"0x%016llx\",\"r14\":\"0x%016llx\","
"\"r15\":\"0x%016llx\"}}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
ep->ExceptionRecord->ExceptionCode, module_base,
module_base ? ctx.Rip - module_base : 0ULL, ctx.Rip, ctx.Rsp,
ctx.Rax, ctx.Rbx, ctx.Rcx, ctx.Rdx, ctx.Rsi, ctx.Rdi, ctx.Rbp,
ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15);
// A crashed thread may already own the regular logger's lock.
HANDLE output = g_log_handle != INVALID_HANDLE_VALUE
? g_log_handle : GetStdHandle(STD_ERROR_HANDLE);
if (length > 0 && length < static_cast<int>(sizeof(line)) &&
output && output != INVALID_HANDLE_VALUE) {
DWORD written = 0;
WriteFile(output, line, static_cast<DWORD>(length), &written, nullptr);
}
}
const LONG disposition = g_previous_filter ? g_previous_filter(ep) : EXCEPTION_CONTINUE_SEARCH;
if (disposition == EXCEPTION_CONTINUE_EXECUTION) {
g_crash_in_flight.store(false, std::memory_order_release);
g_crash_logged.clear(std::memory_order_relaxed);
}
return disposition;
}
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
@@ -139,9 +192,10 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
return EXCEPTION_CONTINUE_SEARCH;
}
auto* ip = reinterpret_cast<const uint8_t*>(ep->ContextRecord->Rip);
uint8_t ip[kMaxInstructionLength]{};
const size_t size = read_instruction(ep->ContextRecord->Rip, ip);
if (g_config.enable_clwb_veh) {
size_t len = decode_clwb_length(ip);
size_t len = decode_clwb_length(ip, size);
if (len > 0) {
uint64_t count = g_clwb_traps.fetch_add(1, std::memory_order_relaxed) + 1;
if (count == 1 || (count & (count - 1)) == 0) {
@@ -158,7 +212,7 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
}
}
if (g_config.enable_adx_tripwire && is_adx_opcode(ip)) {
if (g_config.enable_adx_tripwire && is_adx_opcode(ip, size)) {
char msg[160];
std::snprintf(msg, sizeof(msg),
"rip=0x%016llx bytes=%02x %02x %02x %02x %02x",
@@ -262,9 +316,18 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
if (reason == DLL_PROCESS_ATTACH) {
init_config_and_logging();
bx_veh_install();
g_previous_filter = SetUnhandledExceptionFilter(log_unhandled_exception);
bx_log_emit(BX_LOG_INFO, "runtime_veh", "attached",
g_config.profile == BX_PROFILE_ANACONDA ? "profile=anaconda" : "profile=lockhart");
} else if (reason == DLL_PROCESS_DETACH) {
// Restore g_previous_filter only when our filter is still the active
// top-level filter; if the guest installed its own filter after attach,
// put the guest filter back unchanged. (The frozen .def has no separate
// uninstall export, so detach performs this bounded pointer swap.)
const auto current_filter = SetUnhandledExceptionFilter(g_previous_filter);
if (current_filter != log_unhandled_exception) {
SetUnhandledExceptionFilter(current_filter);
}
if (g_veh_handle) {
RemoveVectoredExceptionHandler(g_veh_handle);
g_veh_handle = nullptr;
+252 -35
View File
@@ -1,30 +1,130 @@
#include <windows.h>
#include <atomic>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <mutex>
#include <utility>
#include "bx_config.h"
#include "bx_log.h"
#include "bx_xmem_internal.h"
/*
* Track B (M1-B1 / M1-B2): Starter implementation of xmem.dll.
* Provides working default heap & virtual allocations so dependent DLLs can link
* and load immediately; Track B issues expand physical/scatter page mapping,
* __XMemAllocationHooks__ dispatch, and Lockhart working-set enforcement.
*/
namespace {
std::atomic<uint64_t> g_committed_virtual{0};
std::atomic<uint64_t> g_allocated_physical{0};
std::atomic<uint64_t> g_peak_committed{0};
constexpr SIZE_T heap_alignment = 64;
void record_alloc(uint64_t bytes) {
uint64_t cur = g_committed_virtual.fetch_add(bytes) + bytes;
uint64_t peak = g_peak_committed.load();
while (cur > peak && !g_peak_committed.compare_exchange_weak(peak, cur)) {}
struct VirtualCommit {
uintptr_t begin;
uintptr_t end;
PVOID allocation_base;
};
// The shim build disables exceptions. Grow the table before committing pages
// so a bookkeeping allocation failure leaves the Win32 allocation untouched.
struct CommitTable {
VirtualCommit* entries = nullptr;
size_t count = 0;
size_t capacity = 0;
CommitTable() = default;
CommitTable(const CommitTable&) = delete;
CommitTable& operator=(const CommitTable&) = delete;
~CommitTable() { std::free(entries); }
VirtualCommit* begin() const { return entries; }
VirtualCommit* end() const { return count ? entries + count : entries; }
bool append(VirtualCommit commit) {
if (count == capacity) {
const size_t max_entries = std::numeric_limits<size_t>::max() / sizeof(commit);
if (capacity > max_entries / 2) return false;
const size_t next_capacity = capacity ? capacity * 2 : 8;
auto* next = static_cast<VirtualCommit*>(
std::realloc(entries, next_capacity * sizeof(commit)));
if (!next) return false;
entries = next;
capacity = next_capacity;
}
entries[count++] = commit;
return true;
}
void swap(CommitTable& other) {
std::swap(entries, other.entries);
std::swap(count, other.count);
std::swap(capacity, other.capacity);
}
};
std::mutex usage_lock;
CommitTable virtual_commits;
uint64_t heap_bytes = 0;
uint64_t virtual_bytes = 0;
uint64_t peak_bytes = 0;
uint64_t title_limit() {
const auto* config = bx_get_runtime_config();
return config ? config->title_memory_limit_bytes : (8ULL << 30);
}
bool can_commit(uint64_t bytes) {
const uint64_t limit = title_limit();
const uint64_t used = heap_bytes + virtual_bytes;
return used <= limit && bytes <= limit - used;
}
void update_peak() {
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes);
}
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
return reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
// The export table has no XMemVirtualFree. Reconcile tracked ranges with
// Win32 when the guest releases or decommits pages using VirtualFree.
bool refresh_virtual_commits() {
CommitTable live;
uint64_t bytes = 0;
for (const auto& commit : virtual_commits) {
uintptr_t cursor = commit.begin;
while (cursor < commit.end) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<PVOID>(cursor), &region, sizeof(region))) {
break;
}
const uintptr_t end = std::min(commit.end, region_end(region));
if (end <= cursor) break;
if (region.State == MEM_COMMIT && region.AllocationBase == commit.allocation_base) {
if (!live.append({cursor, end, commit.allocation_base})) return false;
bytes += end - cursor;
}
cursor = end;
}
}
virtual_commits.swap(live);
virtual_bytes = bytes;
return true;
}
void report_unsupported_host_hooks() {
static const bool reported = [] {
if (GetProcAddress(GetModuleHandleW(nullptr), "__XMemAllocationHooks__")) {
BX_STUB_LOG("xmem.dll", "__XMemAllocationHooks__");
}
return true;
}();
(void)reported;
}
SIZE_T page_size() {
static const SIZE_T size = [] {
SYSTEM_INFO info{};
GetSystemInfo(&info);
return info.dwPageSize;
}();
return size;
}
} // namespace
@@ -32,20 +132,46 @@ extern "C" {
PVOID WINAPI XMemAllocDefault(SIZE_T size, uint64_t /*attributes*/) {
if (size == 0) size = 16;
void* p = _aligned_malloc(size, 64);
if (p) record_alloc(size);
return p;
if (size > std::numeric_limits<SIZE_T>::max() - heap_alignment) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
std::lock_guard guard(usage_lock);
if (!can_commit(size) && (!refresh_virtual_commits() || !can_commit(size))) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
auto* allocation = static_cast<unsigned char*>(_aligned_malloc(size + heap_alignment, heap_alignment));
if (!allocation) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
std::memcpy(allocation, &size, sizeof(size));
heap_bytes += size;
update_peak();
return allocation + heap_alignment;
}
VOID WINAPI XMemFreeDefault(PVOID address, uint64_t /*attributes*/) {
if (address) _aligned_free(address);
if (!address) return;
auto* allocation = static_cast<unsigned char*>(address) - heap_alignment;
SIZE_T size;
std::memcpy(&size, allocation, sizeof(size));
std::lock_guard guard(usage_lock);
_aligned_free(allocation);
heap_bytes -= size;
}
PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes) {
report_unsupported_host_hooks();
return XMemAllocDefault(size, attributes);
}
VOID WINAPI XMemFree(PVOID address, uint64_t attributes) {
report_unsupported_host_hooks();
XMemFreeDefault(address, attributes);
}
@@ -53,11 +179,89 @@ PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWOR
/* Strip console-only high bits before forwarding to standard Win32 VirtualAlloc. */
DWORD win_alloc = alloc_type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET | MEM_TOP_DOWN);
if (win_alloc == 0) win_alloc = MEM_COMMIT | MEM_RESERVE;
DWORD win_prot = protect & 0xFFu;
if (win_prot == 0) win_prot = PAGE_READWRITE;
void* p = VirtualAlloc(address, size, win_alloc, win_prot);
if (p && (win_alloc & MEM_COMMIT)) record_alloc(size);
return p;
/* Console callers may pass multi-bit Xbox memory attributes (e.g. 0x21) in arg 4;
* valid Win32 base page protections are a single power-of-two bit in 0x01..0x80. */
DWORD low_prot = protect & 0xFFu;
DWORD win_prot = (low_prot != 0 && (low_prot & (low_prot - 1)) == 0)
? (protect & (0xFFu | PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE))
: PAGE_READWRITE;
/* MEM_RESET combined with MEM_COMMIT is rejected by Win32 VirtualAlloc, so returning
* early here cannot commit pages outside the working-set budget. */
if (!(win_alloc & MEM_COMMIT) || (win_alloc & MEM_RESET)) {
return VirtualAlloc(address, size, win_alloc, win_prot);
}
const uintptr_t requested = reinterpret_cast<uintptr_t>(address);
const SIZE_T page = page_size();
// Explicit reservations round down to allocation granularity.
SIZE_T alignment = page;
if (win_alloc & MEM_RESERVE) {
SYSTEM_INFO info{};
GetSystemInfo(&info);
alignment = info.dwAllocationGranularity;
}
const uintptr_t begin = requested - requested % alignment;
constexpr uintptr_t max_address = std::numeric_limits<uintptr_t>::max();
if (!size || requested > max_address - (page - 1)
|| size > max_address - requested - (page - 1)) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
const uintptr_t end = (requested + size + page - 1) & ~(page - 1);
std::lock_guard guard(usage_lock);
if (!refresh_virtual_commits()) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
CommitTable next;
for (const auto& commit : virtual_commits) {
if (!next.append(commit)) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
}
uint64_t charge = end - begin;
uintptr_t cursor = begin;
if (address && !(win_alloc & MEM_RESERVE)) {
for (const auto& commit : virtual_commits) {
if (commit.end <= cursor) continue;
if (commit.begin >= end) break;
if (cursor < commit.begin && !next.append({cursor, commit.begin, nullptr})) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
const uintptr_t overlap_end = std::min(end, commit.end);
charge -= overlap_end - std::max(cursor, commit.begin);
cursor = overlap_end;
}
}
if ((cursor < end && !next.append({cursor, end, nullptr})) || !can_commit(charge)) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
PVOID allocation = VirtualAlloc(address, size, win_alloc, win_prot);
if (!allocation || next.count == virtual_commits.count) return allocation;
MEMORY_BASIC_INFORMATION region{};
// A successful commit establishes a region containing the returned address.
VirtualQuery(allocation, &region, sizeof(region));
const uintptr_t relocation = address ? 0 : reinterpret_cast<uintptr_t>(allocation);
for (size_t i = virtual_commits.count; i < next.count; ++i) {
next.entries[i].begin += relocation;
next.entries[i].end += relocation;
next.entries[i].allocation_base = region.AllocationBase;
}
std::sort(next.begin(), next.end(), [](const auto& lhs, const auto& rhs) {
return lhs.begin < rhs.begin;
});
virtual_commits.swap(next);
virtual_bytes += charge;
update_peak();
return allocation;
}
SIZE_T WINAPI XMemVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buf, SIZE_T len) {
@@ -88,16 +292,28 @@ PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID /*base*/, SIZE_T /*num_pages*/, u
}
BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t /*flags*/) {
if (!dst || !src) return FALSE;
std::memcpy(dst, src, bytes);
if (bytes == 0) return TRUE;
if (!dst || !src) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
std::memmove(dst, src, bytes);
return TRUE;
}
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
BX_STUB_LOG("xmem.dll", "XMemGetWorkingSetStatistics");
if (out_stats && stats_size > 0) {
std::memset(out_stats, 0, stats_size);
if (!out_stats || stats_size < sizeof(bx_xmem_stats_t)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
std::lock_guard guard(usage_lock);
if (!refresh_virtual_commits()) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, 0, peak_bytes};
std::memset(out_stats, 0, stats_size);
std::memcpy(out_stats, &stats, sizeof(stats));
return TRUE;
}
@@ -111,11 +327,12 @@ int bx_xmem_query_region(uint64_t /*va*/, bx_xmem_region_info_t* /*out_info*/) {
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats) {
if (!out_stats) return;
const bx_runtime_config_t* cfg = bx_get_runtime_config();
out_stats->title_limit_bytes = cfg ? cfg->title_memory_limit_bytes : (8ULL << 30);
out_stats->committed_virtual_bytes = g_committed_virtual.load();
out_stats->allocated_physical_bytes = g_allocated_physical.load();
out_stats->peak_committed_bytes = g_peak_committed.load();
if (!XMemGetWorkingSetStatistics(out_stats, sizeof(*out_stats))) {
// The internal ABI has no error return. Preserve the most recent
// accounting snapshot if refreshing it runs out of bookkeeping memory.
std::lock_guard guard(usage_lock);
*out_stats = {title_limit(), heap_bytes + virtual_bytes, 0, peak_bytes};
}
}
} // extern "C"
@@ -2,3 +2,6 @@ add_executable(test_veh_clwb main.cpp)
target_include_directories(test_veh_clwb PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_compile_options(test_veh_clwb PRIVATE -mavx2 -mfma)
target_link_libraries(test_veh_clwb PRIVATE bx_runtime_veh xmem kernel32)
add_executable(test_veh_unhandled main_unhandled.cpp)
target_link_libraries(test_veh_unhandled PRIVATE bx_runtime_veh kernel32)
+19 -9
View File
@@ -29,15 +29,25 @@ int main() {
}
}
/* 2. Verify clwb trapping via bx_runtime_veh.dll (both legacy and REX forms) */
alignas(64) uint8_t buf[128] = {0x42};
uint64_t before = bx_veh_get_clwb_trap_count();
__asm__ volatile("clwb (%0)" :: "r"(buf) : "memory");
__asm__ volatile("clwb 64(%0)" :: "r"(buf) : "memory");
uint64_t after = bx_veh_get_clwb_trap_count();
std::printf("clwb traps observed: %llu -> %llu\n",
static_cast<unsigned long long>(before),
static_cast<unsigned long long>(after));
// Fixed registers ensure the assembler emits the intended ModRM/REX forms.
alignas(64) uint8_t buf[512] = {0x42};
const uint64_t before = bx_veh_get_clwb_trap_count();
__asm__ volatile(
"clwb (%%rax)\n\t"
"clwb 64(%%rax)\n\t"
"clwb 256(%%rax)\n\t"
"mov %%rax, %%r8\n\t"
"clwb (%%r8)\n\t"
"clwb 64(%%rax,%%rcx,4)\n\t"
"clwb (%%rip)"
:: "a"(buf), "c"(8) : "r8", "memory");
const uint64_t delta = bx_veh_get_clwb_trap_count() - before;
if (delta != 6) {
std::fprintf(stderr, "FAIL: expected 6 CLWB traps, observed %llu\n",
static_cast<unsigned long long>(delta));
return 4;
}
std::printf("CLWB traps observed: %llu\n", static_cast<unsigned long long>(delta));
/* 3. Verify basic XMem allocation + transfer + stats contract */
void* src = XMemAlloc(4096, 0);
@@ -0,0 +1,16 @@
#include <windows.h>
#include <cstdint>
extern "C" uint64_t bx_veh_get_clwb_trap_count(void);
// Run in its own process. The launcher should report failure and the trace
// should contain a single unhandled_exception with RAX set to the marker.
int main() {
SetErrorMode(SEM_NOGPFAULTERRORBOX);
// Keep a static import on bx_runtime_veh.dll so its DLL_PROCESS_ATTACH filter is installed.
volatile uint64_t attached_traps = bx_veh_get_clwb_trap_count();
(void)attached_traps;
constexpr uint64_t marker = 0x123456789abcdef0ULL;
__asm__ volatile("ud2" :: "a"(marker) : "memory");
return 1;
}
@@ -0,0 +1,3 @@
add_executable(test_xmem main.cpp)
target_include_directories(test_xmem PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_link_libraries(test_xmem PRIVATE xmem bx_runtime_veh kernel32)
+114
View File
@@ -0,0 +1,114 @@
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include "bx_log.h"
#include "bx_xmem_internal.h"
extern "C" {
PVOID WINAPI XMemAlloc(SIZE_T, uint64_t);
PVOID WINAPI XMemAllocDefault(SIZE_T, uint64_t);
VOID WINAPI XMemFree(PVOID, uint64_t);
VOID WINAPI XMemFreeDefault(PVOID, uint64_t);
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, DWORD);
SIZE_T WINAPI XMemVirtualQuery(LPCVOID, PMEMORY_BASIC_INFORMATION, SIZE_T);
BOOL WINAPI XMemTransferMemory(PVOID, LPCVOID, SIZE_T, uint64_t);
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
BOOL WINAPI XMemIsToolsMemAvailable();
}
#define CHECK(condition) \
do { \
if (!(condition)) { \
std::fprintf(stderr, "xmem:%d: %s (Win32 error %lu)\n", __LINE__, \
#condition, static_cast<unsigned long>(GetLastError())); \
return 1; \
} \
} while (false)
int main() {
SYSTEM_INFO sys{};
GetSystemInfo(&sys);
const SIZE_T page = sys.dwPageSize;
const auto* config = bx_get_runtime_config();
bx_xmem_stats_t stats{};
CHECK(config && XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
char profile[16]{};
GetEnvironmentVariableA("BX_PROFILE", profile, sizeof(profile));
const uint64_t expected_limit = std::strcmp(profile, "anaconda") == 0
? 13500ULL * 1024 * 1024
: 8ULL * 1024 * 1024 * 1024;
CHECK(stats.title_limit_bytes == expected_limit);
CHECK(stats.title_limit_bytes == config->title_memory_limit_bytes);
CHECK(stats.committed_virtual_bytes == 0 && stats.allocated_physical_bytes == 0);
CHECK(!XMemIsToolsMemAvailable());
CHECK(!XMemGetWorkingSetStatistics(&stats, sizeof(stats) - 1));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
unsigned char large_stats[sizeof(bx_xmem_stats_t) + 16];
std::memset(large_stats, 0xCC, sizeof(large_stats));
CHECK(XMemGetWorkingSetStatistics(large_stats, sizeof(large_stats)));
for (size_t i = sizeof(bx_xmem_stats_t); i < sizeof(large_stats); ++i) {
CHECK(large_stats[i] == 0);
}
auto* ordinary = XMemAlloc(73, 0);
auto* empty = XMemAllocDefault(0, 0);
CHECK(ordinary && empty);
CHECK(reinterpret_cast<uintptr_t>(ordinary) % 64 == 0);
CHECK(reinterpret_cast<uintptr_t>(empty) % 64 == 0);
bx_xmem_get_internal_stats(&stats);
CHECK(stats.committed_virtual_bytes == 89);
// The existing heap charge should reject requests at the full cap
// without allocating gigabytes on the test host.
CHECK(!XMemAllocDefault(stats.title_limit_bytes, 0));
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
CHECK(!XMemVirtualAlloc(nullptr, stats.title_limit_bytes,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
XMemFreeDefault(empty, 0);
XMemFree(ordinary, 0);
auto* reserved = static_cast<unsigned char*>(
XMemVirtualAlloc(nullptr, page * 3, MEM_RESERVE, PAGE_READWRITE));
CHECK(reserved && reinterpret_cast<uintptr_t>(reserved) % page == 0);
CHECK(XMemVirtualAlloc(reserved, page * 2, MEM_COMMIT, PAGE_READWRITE) == reserved);
CHECK(XMemVirtualAlloc(reserved + page + 1, page * 2 - 1, MEM_COMMIT, PAGE_READWRITE)
== reserved + page);
MEMORY_BASIC_INFORMATION region{};
CHECK(XMemVirtualQuery(reserved + page, &region, sizeof(region)) == sizeof(region));
CHECK(region.AllocationBase == reserved && region.State == MEM_COMMIT);
CHECK(region.Protect == PAGE_READWRITE && region.RegionSize == page * 2);
constexpr char sample[] = "betterxen";
CHECK(XMemTransferMemory(reserved, sample, sizeof(sample), 0));
CHECK(XMemTransferMemory(reserved + 1, reserved, sizeof(sample), 0));
CHECK(std::memcmp(reserved + 1, sample, sizeof(sample)) == 0);
bx_xmem_get_internal_stats(&stats);
CHECK(stats.committed_virtual_bytes == page * 3 && stats.peak_committed_bytes == page * 3);
CHECK(VirtualFree(reserved + page, page, MEM_DECOMMIT));
bx_xmem_get_internal_stats(&stats);
CHECK(stats.committed_virtual_bytes == page * 2 && stats.peak_committed_bytes == page * 3);
CHECK(VirtualFree(reserved, 0, MEM_RELEASE));
bx_xmem_get_internal_stats(&stats);
CHECK(stats.committed_virtual_bytes == 0 && stats.peak_committed_bytes == page * 3);
// Console callers pass multi-bit attributes (e.g. 0x21) in arg 4 and high bits in alloc_type.
auto* console_res = static_cast<unsigned char*>(
XMemVirtualAlloc(nullptr, page * 2, MEM_RESERVE | 0x20400000u, 0x21u));
CHECK(console_res != nullptr);
CHECK(XMemVirtualAlloc(console_res, page, MEM_COMMIT, 0x21u) == console_res);
console_res[0] = 0x5Au;
CHECK(console_res[0] == 0x5Au);
CHECK(VirtualFree(console_res, 0, MEM_RELEASE));
bx_xmem_get_internal_stats(&stats);
CHECK(stats.committed_virtual_bytes == 0);
std::puts("test_xmem: passed");
}