Compare commits

...
Author SHA1 Message Date
ates 4cb858e6f5 docs: the working method is in effect; point to the ladder issue
#662 is merged, so the working method no longer says 'proposed'. It
names the pinned ladder issue (#663) and notes that the starting queue
was filed as #664-#680.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:49:50 +03:00
Ateş b36e397681 Merge pull request #638 from MacosPorters/track-f/637-console-shader-abi
[M2-F17] docs: console compute shader entry ABI observed from the Series X|S compiler
2026-11-29 11:48:27 +03:00
ates 5bc4ff5cf4 Merge remote-tracking branch 'origin/main' into fix-638
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 11:48:08 +03:00
Ateş 5e204bd883 Merge pull request #662 from MacosPorters/docs/game-ladder-roadmap
[Process] Stage-based roadmap and the blocker queue: what an agent does when told "work"
2026-11-29 11:47:11 +03:00
Ateş 5c2e2c9b63 Merge pull request #659 from MacosPorters/track-a/bringup-veh-diagnostics
[M2-A] runtime_veh: opt-in fault context, watches, breakpoints and sampler
2026-11-29 11:36:16 +03:00
ates 77dd9ffef3 Merge remote-tracking branch 'origin/main' into fix-659 2026-11-29 11:35:25 +03:00
Ateş abecde1c39 Merge pull request #635 from MacosPorters/track-a/634-veh-breakpoint
[M2-A16] runtime_veh: record breakpoints and assertion failures a guest crash reporter hides
2026-11-29 11:35:09 +03:00
ates e532fc56ba Merge remote-tracking branch 'origin/main' into fix-635
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 11:22:18 +03:00
ates 04148f77f8 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 07:06:54 +03:00
ates 5a6e786850 docs: console shader ABI review fixes: provenance, class U, NewBE scope
Review on #638:
- a Provenance section records the maintainer's statement that
  Microsoft's authorization covers publishing these derived observations,
  that the material is never committed, and that only a contributor with
  the same authorization can reproduce them;
- CLAIM-XBOX-CS-ENTRY-ABI moves from class A to U (no public source
  establishes it; not yet independently reproduced), names the NewBE
  backend, root buffer descriptors, and the exact host and tool versions;
- the page, changelog and index are scoped to the PIX/NewBE path; the ACO
  comparison cites #650, where it is recorded, instead of #647, and D2 is
  told the ABI is a candidate, not accepted;
- word 3 is decoded from the public GFX10 layout for both 0x11014fac and
  0x31016fac (FORMAT 20/22, OOB_SELECT 1/3), which also explains why the
  record count -1 disables the bounds check;
- eleven probes, not ten; table buffer descriptors 32 bytes apart;
  STRIDE bits 29:16; D3DMetal 4.0b3 named (3.0 not measured); wave64 as
  the default with no declared wave size; odd-SGPR alignment, the
  overflow threshold and ACCC-only output listed as open.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:06:54 +03:00
ates 34f744aa5d CHANGELOG: runtime_veh diagnostic hardening and fixture
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:04:44 +03:00
ates afc093ee54 Merge remote-tracking branch 'origin/track-a/634-veh-breakpoint' into track-a/bringup-veh-diagnostics 2026-11-29 07:03:55 +03:00
ates 224586917f runtime_veh, bx-cli trace: breakpoint record follow-ups from review
From the reviews on #635 (none blocking):
- log_breakpoint saves and restores the thread's last-error value, so a
  resumed first-chance exception leaves the guest's error state as it was
  (test_veh_breakpoint checks it; it fails without the restore);
- past the cap the counter is not advanced again, so it cannot wrap;
- bx-telemetry parses the record's address and bx-cli trace prints it,
  which locates a breakpoint outside any image (module ?);
- the cap note appears when any record reached the cap, not only the
  last line, since threads or processes can write records out of order.

Deduplicating repeated sites stays with #651.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:03:36 +03:00
ates 2af3e7d10a Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 07:02:00 +03:00
ates 17e2e2a835 runtime_veh: review fixes for the opt-in diagnostics; a fixture for them
Review on #659:
1. the AV context spec is scanned without strtok (no shared cursor
   across faulting threads);
2. every VirtualProtect is checked: a watch or range watch that cannot
   unprotect a page disarms, logs diagnostic_disarmed and passes the
   access violation on instead of looping; failed re-protection, code
   byte restores and int3 re-insertion are logged and disarm;
3. AV context and sampler lines use bounded appends (no length past the
   buffer), JSON-escape the spec and module names, and take module names
   through GetModuleFileNameW and UTF-8;
4. helper threads check a stop flag; detach disarms every diagnostic
   (pages, code bytes, TLS) without waiting, and keeps the log handle and
   lock alive while any helper was started;
5. BX_VEH_AV_CONTEXT/AV_ALL are read once at attach, so with them unset
   an access violation costs nothing;
6. bx-cli lets the named BX_VEH_* switches through its isolated guest
   environment (DIAGNOSTIC_ENV_ALLOWLIST), with a unit test that other
   variables and secrets still do not pass;
7. test_veh_diagnostics runs each mode in a child process (the switches
   are read at attach) and checks the log: no records when off; 16 capped
   av_context records from 4 threads, valid JSON with the spec escaped;
   a non-ASCII module name in UTF-8; one watched write with its value,
   and a failed protection change that disarms and reaches the guest; two
   code hits with a safe string argument; sampler records and a clean
   exit. 21 checks pass; the previous runtime_veh fails 6 of them.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:01:31 +03:00
ates f7748387da runtime_veh: opt-in fault context, watches, breakpoints and sampler
All off by default: BX_VEH_AV_CONTEXT / BX_VEH_AV_ALL log an access
violation's memory type, protection, allocation base and unwound stack;
BX_VEH_WATCH and BX_VEH_WATCH_RANGE watch writes to an address, a range
or a pointer chain; BX_VEH_HIT sets software code breakpoints that log
registers and string arguments; BX_VEH_SAMPLE samples every thread.
They were used to find the target build's startup blockers.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
jelly013 84f4370227 Merge main into track-f/637-console-shader-abi
Resolve the CHANGELOG.md conflict under Added by keeping both sides.

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-28 17:28:14 +01:00
ates 79e1906c27 docs: note that the console ABI probes describe the NewBE compiler path (#637)
The ACO compiler that emits ACCC containers generates different code for
the same HLSL; its root-buffer descriptor word 3 differs (#647).

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 19:01:10 +03:00
ates d65c12f6a9 Merge origin/main into track-a/634-veh-breakpoint
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 19:01:07 +03:00
ates 3f2f2732ed Merge origin/main into track-a/634-veh-breakpoint
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 17:49:29 +03:00
ates 7c807d8b3a runtime_veh: address jelly013's review of breakpoint logging
- Say precisely which guest handlers run after bx_veh_handler: the top-level filter and vectored handlers the guest registers last.
- Write module names as UTF-8 via GetModuleFileNameW and WideCharToMultiByte, so a non-ASCII name cannot make the JSONL line invalid.
- bx-telemetry parses record/limit, and bx-cli trace notes when the per-process cap was reached.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 17:49:28 +03:00
ates ca2ad143f9 docs: record the console compute shader entry ABI (#637)
Add the compute entry conventions observed from Microsoft's Series X|S
HLSL compiler, used under Microsoft's authorization, on eleven
project-authored probes: wave64 code, root data from s4 in parameter
order, the root-data address in s0:s1 on overflow, IDs after the root
data, inline root buffer descriptors without bounds, table descriptor
sizes and per-load binding metadata. Register roles are marked as
inferences. CLAIM-XBOX-CS-ENTRY-ABI (class A) records the measurement.
No compiler output, binary or documentation text is included.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:25:54 +03:00
ates 0b474941f0 runtime_veh: record breakpoints a guest crash reporter hides (#634)
A guest with its own crash reporter replaces the top-level filter
installed at attach, so its assertions never reached
unhandled_exception. The vectored handler, which runs before any guest
handler, now records EXCEPTION_BREAKPOINT and STATUS_ASSERTION_FAILURE
as breakpoint_exception records with module name, base and RVA. They
are first-chance, handling is unchanged, and at most 16 are written per
process. bx-telemetry parses them and bx-cli trace lists them.

test_veh_breakpoint replaces the top-level filter, resumes from its own
vectored handler and checks the records against the RVA of a labelled
int3 site; it fails against the previous bx_runtime_veh.dll.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:26:19 +03:00
12 changed files with 1741 additions and 7 deletions

No files matched your search

+10
View File
@@ -23,6 +23,16 @@ remains unsupported.
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
### Added
- `docs/research/console-shader-abi.md` and `CLAIM-XBOX-CS-ENTRY-ABI` (class U, not yet independently reproduced): the compute shader entry ABI observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler, used under Microsoft's authorization, on eleven project-authored probes. Compute code is wave64. Root data starts at `s4` in root-parameter order: one SGPR per constant, two per root descriptor address, one per 32-bit table pointer. The thread-group IDs follow the root data, and `s0:s1` holds the root-data address when it overflows. Root buffer descriptors are built inline with no effective bounds check, table buffer descriptors are 32 bytes apart (samplers 16), and the compiler reports the HLSL binding of each descriptor load. No compiler output, binary or documentation text is in the repository. Register roles are inferences, and the ACCC container layout remains unknown.
- Opt-in diagnostics in `bx_runtime_veh.dll`, all off by default:
- an access-violation context with the memory type and the faulting thread's stack (`BX_VEH_AV_CONTEXT`, `BX_VEH_AV_ALL`);
- software write watches over one address, a range or a pointer chain (`BX_VEH_WATCH`, `BX_VEH_WATCH_RANGE`);
- software code breakpoints that log string arguments (`BX_VEH_HIT`, `BX_VEH_HIT_ALL`);
- an all-threads sampling profiler (`BX_VEH_SAMPLE`).
Records are bounded, JSON-escaped and UTF-8. A protection change that fails disarms the diagnostic, which is logged, and the guest gets its exception. Detach disarms everything. With the switches unset, nothing runs. `bx-cli run` lets these named switches through its isolated guest environment. `test_veh_diagnostics` covers every mode.
- `bx_runtime_veh.dll` records breakpoints (`0x80000003`) and assertion failures (`0xC0000420`) from its vectored handler as `breakpoint_exception` JSONL records with the exception code, module name, module base and RVA. A guest with its own crash reporter replaces the top-level filter installed at attach, so its assertions never reached `unhandled_exception`; the vectored handler runs before the guest's top-level filter and any vectored handler the guest registers last (one it registers first can resume the exception before BetterXen sees it). Module names are written as UTF-8, and `bx-cli trace` notes when the record cap was reached. The records are first-chance (the guest may still handle the exception), handling is unchanged, and at most 16 are written per process. `bx-telemetry` parses them and `bx-cli trace` lists them under "Breakpoint/assert exceptions, first chance".
- **Test:** `tests/conformance/test_veh_breakpoint/` replaces the top-level filter and resumes from its own vectored handler, as such a guest does. It raises 21 int3 breakpoints at a labelled site and one `STATUS_ASSERTION_FAILURE`, and requires exactly 16 records, the int3 records at the RVA it computes from the label and its own module base, and no `unhandled_exception`. It fails against the previous `bx_runtime_veh.dll`.
- [Target-build bring-up: development cycle and review](docs/testing/target-build-review.md): how contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently.
- `xgameruntime.dll` serves the XPackage installation monitor offline: the running package is reported fully installed, launchable and complete. Monitor handles share the mount handles' table, generation and lock: stale handles are rejected, closing twice is harmless, and uninitialize releases them. Progress registrations are accepted, logged and never fired. `XPackageEnumeratePackages` reports this game for `XPackageKind::Game` and no content packages. Both replace stubs that a project-authorized target build calls at startup. The save-container mount path ends with the drive-root separator, and `test_xgameruntime_saves` expects it.
- `AcpHal.dll`:
+2 -1
View File
@@ -4,7 +4,7 @@
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
- [Roadmap](roadmap.md) — Single authoritative plan: the foundation milestones (M0–M2) and the stages the target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), with exit gates and decision gates.
- [Working Method](process/working-method.md) — Proposed: what an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
- [Working Method](process/working-method.md) — What an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
@@ -28,6 +28,7 @@
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
## Governance, Security & Legal
+10
View File
@@ -268,3 +268,13 @@ retrieved = "2026-11-22"
architecture = "Xbox Series X, Hot Chips 32 architectural presentation"
test = "Read slides 12 and 13. No console execution."
uncertainty = "The slides do not specify opcode semantics, an ABI or a command packet layout."
[[claim]]
id = "CLAIM-XBOX-CS-ENTRY-ABI"
class = "U"
claim = "For project-authored compute shaders with explicit root signatures, the NewBE backend of Microsoft's Series X|S PIX shader compiler generated wave64 code that receives root data from s4 in root-parameter order (one SGPR per constant, two per root descriptor address, one per 32-bit table pointer), thread-group IDs after the root data, the root-data address in s0:s1 when the data overflows, and root buffer descriptors built inline with a record count of -1."
sources = ["docs/research/console-shader-abi.md"]
retrieved = "2026-11-28"
architecture = "Xbox Series X|S compute shaders, as compiled by the GDK 2026.10 (10.0.26100.9661) Scarlett PIX shader compiler (NewBE) under CrossOver 26.3 (26.3.0.39832) on Apple M5, macOS 27.2.1"
test = "Compiled eleven project-authored cs_6_5/cs_6_6 probes and read the compiler's assembly listings; the compiler and its outputs are used under Microsoft's authorization and are not in the repository."
uncertainty = "Class U: no public source establishes this; it rests on an authorized reading of a non-public compiler's listings, which only a contributor with the same authorization can reproduce, and which has not been independently reproduced. Register roles are inferred from the generated code and the reported COMPUTE_PGM_RSRC2 fields. NewBE only: the ACO backend (xdxc), which produces ACCC code, generates different code and agrees so far only on the root UAV address in s[4:5]. One compiler build, compute only, no console execution, and the ACCC container layout is not covered."
+2 -2
View File
@@ -1,6 +1,6 @@
# Working Method: the Blocker Queue
**Status: proposed**, together with the matching change to [AGENTS.md §0](../../AGENTS.md).
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
BetterXen is built by collaborators who each have the project-authorized target build and who work by pointing a coding agent at this repository and saying **"work"**. This document is written for that. It answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
@@ -175,7 +175,7 @@ Everything else is the queue.
## Starting the queue
The queue starts with what the first target-build runs already found. Each line becomes a blocker issue or a tooling issue when this proposal is accepted.
The queue starts with what the first target-build runs already found. Each line was filed as an issue on 2026-11-29 (#664–#680); the table is kept as a record of the starting point, and the issues are the live state.
| Stage | Signature or task | Track |
| --- | --- | --- |
+75
View File
@@ -0,0 +1,75 @@
# Console compute shader entry ABI (probe results)
Recorded 2026-11-28 (CLAIM-XBOX-CS-ENTRY-ABI). This page lists facts derived from the assembly listing of Microsoft's Series X|S PIX shader compiler (its NewBE code generator), used under an authorization Microsoft gave the project for its GDK material (see "Provenance"). The compiler, its output and the GDK files are not in this repository. No listing, binary or documentation text is reproduced. Only the observations below are. It complements [RDNA 2 notes](rdna2.md), which cover AMD's public ISA, and [Shader containers](shader-containers.md).
What this is:
- **Measured:** what the compiler emitted for eleven compute shaders the project wrote (p00–p10 below), compiled on one host: Apple M5, macOS 27.2.1, CrossOver 26.3 (26.3.0.39832), GDK 2026.10 (10.0.26100.9661).
- **Inferred:** what each register holds. The interpretations below are read from the generated code. They agree with the user-SGPR, thread-group-ID and thread-ID fields of AMD's publicly documented `COMPUTE_PGM_RSRC2` register, which the compiler reports for each shader.
What this is not: a console run, a description of the ACCC/FSPX container, a description of the ACO backend that produces the code in ACCC containers (see "Root buffer access"), or anything about graphics stages. The compiler used here writes plain DXIL objects. The console code appears only in its assembly listing, so how that code is stored in an ACCC container is still unknown (CLAIM-XBOX-ISA-ABI).
## Method
Each probe is a `cs_6_5` compute shader (`cs_6_6` for the 64-bit atomic) with an explicit `[RootSignature]`. The compiler needs a root signature to generate console code. It reported "GFX10" for the target. The probes change one thing at a time:
| Probe | Root signature | Shader |
| --- | --- | --- |
| p00 | `SRV(t0), SRV(t1), UAV(u0)` | `o[i] = a[i] + b[i]`, 64 threads |
| p01 | `RootConstants(num32BitConstants=4, b0), UAV(u0)` | uses all four constants |
| p02 | `CBV(b0), UAV(u0)` | reads two constants |
| p03 | `DescriptorTable(SRV(t0, numDescriptors=2)), DescriptorTable(UAV(u0))` | p00 through tables |
| p04 | `DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), UAV(u0)` | `Texture2D.SampleLevel` |
| p05 | `UAV(u0), SRV(t0), SRV(t1)` | p00 with the parameters reordered |
| p06 | `UAV(u0)` | `[numthreads(8,8,1)]`, writes group and thread IDs |
| p07 | `SRV(t0), UAV(u0)` | `WaveActiveSum` |
| p08 | `SRV(t0), UAV(u0)` | 256 bytes of `groupshared` and a barrier |
| p09 | `UAV(u0)` | 64-bit `InterlockedAdd` |
| p10 | `RootConstants(num32BitConstants=20, b0), UAV(u0)` | sums all 20 constants |
## Observations
**Wave size.** Every probe was compiled for 64-lane waves: the compiler reported wave32 as disabled. In p07 `WaveActiveSum` became a full 64-lane reduction that combines the two 32-lane halves and uses a 64-bit execution mask. D3DMetal 4.0b3, the version measured in [D3DMetal GPU limits](d3dmetal-gpu-limits.md), runs 32-lane waves only; D3DMetal 3.0 was not measured. None of the probes declares a wave size, so wave64 is what this compiler generates by default, and console-compiled compute code has to be treated as wave64 unless it declares otherwise, not only when a shader declares `WaveSize(64)`.
**Root arguments in registers.** Root-signature data starts at `s4`, in root-parameter order. p05 moves the registers with the parameters.
- A root constant takes one SGPR (p01: `s4`–`s7`).
- A root CBV, SRV or UAV takes two SGPRs, a 64-bit GPU address (p00: `s4:s5`, `s6:s7`, `s8:s9`).
- A descriptor table takes one SGPR, a 32-bit pointer. The shader clears the upper half itself (p03, p04).
- The thread-group IDs follow the root data, x before y (p00: `s10`; p06: `s6`, `s7`). Thread IDs arrive in `v0` (x) and `v1` (y), as the reported thread-ID count indicates.
**Overflow.** `s0`–`s3` come before the root data. When the root data does not fit in user SGPRs (p10: 20 constants and a UAV), only those four are passed, and `s0:s1` holds the address of the root data in memory. The shader loads the constants from offset 0 and the UAV address from offset `0x50`, which is root dword 20. Whether `s0:s1` points at the same data when the arguments also fit in registers was not tested.
**Root buffer access.** For a root SRV, UAV or CBV, the shader builds the buffer descriptor itself from the root address:
- **Stride:** in word 1, the `STRIDE` field (bits 29:16 in the public GFX10 layout), taken from the element type: 4 bytes for `uint`, 8 for `uint64_t`, 16 for the root CBV.
- **Record count:** `-1` (`NUM_RECORDS` = 0xFFFFFFFF). With the `OOB_SELECT` below, the only bounds check compares the index against `NUM_RECORDS`, so it never fires: accesses through root descriptors are effectively not bounds-checked.
- **Word 3:** the constant `0x11014fac` in every probe. Decoded with the public GFX10 buffer-descriptor layout (Mesa `src/amd/common/ac_descriptors.c` / `gfx10-rsrc.json`, LLVM `SIDefines.h`): destination swizzle X, Y, Z, W; `FORMAT` 20 (`32_UINT`); `RESOURCE_LEVEL` 1; `OOB_SELECT` 1 (the index is checked against `NUM_RECORDS`); `TYPE` 0 (buffer). These observations describe the NewBE path only. The ACO path (`xdxc`), which produces the code in the ACCC containers titles ship, generates different code for the same HLSL: its word 3 is `0x31016fac`, which decodes the same way except `FORMAT` 22 (`32_FLOAT`) and `OOB_SELECT` 3 (raw), two bits apart (`0x20002000`). Of these probes' facts, only the root UAV address in `s[4:5]` has been checked to agree on ACO. That comparison is recorded in the shader corpus PR [#650](https://github.com/MacosPorters/betterxen/pull/650) (open); until it lands, treat ACO agreement beyond that as unverified.
**Descriptor tables.** Descriptors are loaded from the table address:
- buffer descriptors 32 bytes apart (p03 loads at offsets `0` and `0x20`);
- a texture descriptor of 32 bytes and a sampler descriptor of 16 bytes (p04).
For each such load, the compiler also reported the instruction offset and the HLSL binding it came from: class, register, space and resource kind.
**Other.** p08 uses LDS (`ds_write_b32`, `ds_read_b32`), and its size shows in the reported LDS allocation. p09 is a native `buffer_atomic_add_x2`. The shader hash from the container's `HASH` part is embedded at the start of the generated code.
## Consequences
- **Branch D2** ([ADR 0008](../adr/0008-m2-shader-format-gate.md)) gains a candidate compute entry ABI: where root constants, root descriptors, table pointers and IDs are, and how buffer descriptors are formed, as the NewBE path generates them. It is not accepted for D2 until it is reproduced independently, and checked against the ACO code that ACCC containers carry.
- **Binding recovery** may not need data-flow analysis if ACCC containers carry the same per-load binding table. That depends on the container format, which is still unknown.
- **Wave64** is the default. The D1 path also needs to know whether a title's DXIL assumes 64 lanes.
- **Bounds:** out-of-range accesses through root descriptors are not discarded on the console the way bounds-checked descriptors would discard them.
## Open
- **Graphics stages** (vertex and pixel inputs, exports) were not probed.
- **ACCC-only output:** `xdxc` emits containers that keep DXIL and add ACCC. Which compiler or option emits ACCC-only (DXIL-stripped) containers, like those in the target workload's upscaler component (see the [roadmap](../roadmap.md) scan entry), is open.
- **ACO agreement:** which of these NewBE facts hold for the ACO code (see "Root buffer access").
- **SGPR alignment:** every probe placed its 64-bit root addresses after an even number of SGPRs. Whether an odd count of one-SGPR parameters before a root descriptor inserts a padding SGPR is untested.
- **Overflow threshold:** the probes jump from 6 root dwords to 22. The exact cutoff, and whether overflow is always all-or-nothing, are unmeasured.
- **`s0`–`s3`:** what they hold when root data fits in registers.
- **One compiler build, one host:** a different GDK version may differ.
## Provenance
- **Source:** facts were read from listings that Microsoft's licensed Series X|S shader compiler produced for shaders the project wrote. That compiler is not public, so none of this can be checked against a public source, except the descriptor decode above.
- **Authorization:** the maintainer (@atesahmet0) has stated that Microsoft's authorization for the project's use of its GDK material covers publishing derived observations like these in this repository. The material itself (the compiler, its listings and binaries, and the GDK documentation) is never committed. The authorization record is held privately (the process is proposed in [#661](https://github.com/MacosPorters/betterxen/pull/661)).
- **Reproduction:** only a contributor with the same authorization can reproduce these observations. That reproduction has not happened yet, so the claim is recorded as class U: unestablished by public sources, with an authorized observation behind it.
+126 -1
View File
@@ -41,6 +41,21 @@ const HOST_ENV_ALLOWLIST: &[&str] = &[
"XPC_SERVICE_NAME",
];
/// Opt-in `bx_runtime_veh.dll` diagnostic switches. They carry addresses and counts, never
/// credentials, so the isolated guest environment lets them through by name; every other
/// variable is still stripped.
const DIAGNOSTIC_ENV_ALLOWLIST: &[&str] = &[
"BX_VEH_AV_CONTEXT",
"BX_VEH_AV_ALL",
"BX_VEH_WATCH",
"BX_VEH_WATCH_RANGE",
"BX_VEH_WATCH_RANGE_MAX",
"BX_VEH_HIT",
"BX_VEH_HIT_ALL",
"BX_VEH_HIT_RDX",
"BX_VEH_SAMPLE",
];
fn usage_text() -> &'static str {
"BetterXen Hybrid CLI (bx-cli)\n\
\n\
@@ -375,6 +390,40 @@ fn render_trace(text: &str) -> String {
);
}
}
if !summary.breakpoint_exceptions.is_empty() {
let _ = writeln!(
out,
"\nBreakpoint/assert exceptions, first chance ({}):",
summary.breakpoint_exceptions.len()
);
for hit in &summary.breakpoint_exceptions {
let _ = writeln!(
out,
" code={} {} + RVA={} (module_base={} address={})",
hit.exception_code.as_deref().unwrap_or("unknown"),
hit.module.as_deref().unwrap_or("?"),
hit.rva.as_deref().unwrap_or("unknown"),
hit.module_base.as_deref().unwrap_or("unknown"),
hit.address.as_deref().unwrap_or("unknown"),
);
}
// Any record at the cap counts: concurrent threads, or several processes appending to one
// log, can write the capped record before a lower-numbered one.
if let Some(limit) =
summary
.breakpoint_exceptions
.iter()
.find_map(|hit| match (hit.record, hit.limit) {
(Some(record), Some(limit)) if limit > 0 && record >= limit => Some(limit),
_ => None,
})
{
let _ = writeln!(
out,
" cap of {limit} records reached; later breakpoints were not recorded"
);
}
}
if !summary.unimpl_apis.is_empty() {
let _ = writeln!(out, "\nUnimplemented APIs:");
for (api, count) in &summary.unimpl_apis {
@@ -402,7 +451,7 @@ where
{
let mut env_map = BTreeMap::new();
env_map.insert("PATH".to_string(), SAFE_CHILD_PATH.to_string());
for &key in HOST_ENV_ALLOWLIST {
for &key in HOST_ENV_ALLOWLIST.iter().chain(DIAGNOSTIC_ENV_ALLOWLIST) {
if let Some(val) = lookup(key) {
env_map.insert(key.to_string(), val);
}
@@ -1657,6 +1706,26 @@ sub setup_bottle_wineprefix {
assert!(!child.contains_key("CX_GRAPHICS_BACKEND"));
}
#[test]
fn isolated_env_passes_only_the_named_veh_diagnostics() {
let host = BTreeMap::from([
("BX_VEH_AV_CONTEXT", "1"),
("BX_VEH_SAMPLE", "5"),
("BX_VEH_UNKNOWN", "x"),
("BX_LOG_FILE", "/tmp/elsewhere.jsonl"),
("GH_TOKEN", "secret_token"),
]);
let child = collect_isolated_host_env(|k| host.get(k).map(|s| (*s).to_string()));
assert_eq!(
child.get("BX_VEH_AV_CONTEXT").map(String::as_str),
Some("1")
);
assert_eq!(child.get("BX_VEH_SAMPLE").map(String::as_str), Some("5"));
assert!(!child.contains_key("BX_VEH_UNKNOWN"));
assert!(!child.contains_key("BX_LOG_FILE"));
assert!(!child.contains_key("GH_TOKEN"));
}
#[test]
fn converts_unix_path_to_wine_z_drive() {
assert_eq!(
@@ -1723,6 +1792,62 @@ sub setup_bottle_wineprefix {
assert_eq!(format_shader_gate_section(&summarize_jsonl(log)), "");
}
#[test]
fn renders_breakpoint_exceptions_with_module_and_rva() {
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x0000000002236178","address":"0x0000000142236178","record":1,"limit":16}
"#;
let rendered = render_trace(log);
assert!(
rendered.contains(
"\nBreakpoint/assert exceptions, first chance (1):\n code=0x80000003 \
title.exe + RVA=0x0000000002236178 (module_base=0x0000000140000000 \
address=0x0000000142236178)\n"
),
"{rendered}"
);
assert!(!rendered.contains("Unhandled exceptions"), "{rendered}");
assert!(
!rendered.contains("cap of"),
"one of 16 records is not the cap: {rendered}"
);
}
#[test]
fn notes_when_the_breakpoint_record_cap_is_reached() {
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":15,"limit":16}
{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":16,"limit":16}
"#;
let rendered = render_trace(log);
assert!(
rendered.contains(" cap of 16 records reached; later breakpoints were not recorded\n"),
"{rendered}"
);
}
#[test]
fn notes_the_cap_when_a_capped_record_is_not_the_last_line() {
// Two threads (or processes) appending: the capped record lands before record 15.
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":16,"limit":16}
{"ts_ms":6,"tid":8,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":15,"limit":16}
"#;
let rendered = render_trace(log);
assert!(
rendered.contains(" cap of 16 records reached; later breakpoints were not recorded\n"),
"{rendered}"
);
}
#[test]
fn prints_the_address_of_a_breakpoint_outside_any_image() {
let log = r#"{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
"#;
let rendered = render_trace(log);
assert!(
rendered.contains("address=0x0000000000410000"),
"{rendered}"
);
}
#[test]
fn renders_decisions_kinds_stages_gaps_and_missing_bridge() {
// Realistic records, matching the emitter in shims/d3d12_xs/shader_gate.cpp.
+71
View File
@@ -18,6 +18,9 @@ pub struct TraceSummary {
pub amd_traps: BTreeMap<String, TrapCount>,
pub adx_errors: usize,
pub unhandled_exceptions: Vec<UnhandledException>,
/// First-chance `breakpoint_exception` records (int3 and assertion failures), which a
/// guest's own crash reporter would otherwise hide from `unhandled_exception`.
pub breakpoint_exceptions: Vec<BreakpointException>,
pub unimpl_apis: BTreeMap<String, usize>,
pub unimpl_vtables: BTreeMap<String, usize>,
/// Aggregated `shader_gate` records from `d3d12_xs.dll` (#496).
@@ -182,6 +185,30 @@ pub struct UnhandledException {
pub rip: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
pub struct BreakpointException {
pub exception_code: Option<String>,
pub module: Option<String>,
pub module_base: Option<String>,
pub rva: Option<String>,
/// The faulting address, which locates a breakpoint outside any image (module `?`).
pub address: Option<String>,
/// 1-based index of this record and the per-process cap, so a reader can tell a run
/// that hit the cap (later breakpoints not recorded) from one that stopped short of it.
pub record: Option<u32>,
pub limit: Option<u32>,
}
fn extract_json_u32(line: &str, key: &str) -> Option<u32> {
let needle = format!("\"{key}\":");
let start = line.find(&needle)? + needle.len();
let digits: &str = &line[start..];
let end = digits
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(digits.len());
digits[..end].parse().ok()
}
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let needle = format!("\"{key}\":\"");
let start = line.find(&needle)? + needle.len();
@@ -344,6 +371,17 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
});
}
"breakpoint_exception" => {
summary.breakpoint_exceptions.push(BreakpointException {
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
module: extract_json_str(trimmed, "module").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),
address: extract_json_str(trimmed, "address").map(str::to_owned),
record: extract_json_u32(trimmed, "record"),
limit: extract_json_u32(trimmed, "limit"),
});
}
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
"unimpl_vtable" => {
*summary
@@ -420,6 +458,39 @@ mod tests {
assert_eq!(summary.clwb_trap_lower_bound, None);
}
#[test]
fn collects_breakpoint_exceptions_in_log_order() {
let log = r#"
{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x0000000002236178","address":"0x0000000142236178","record":1,"limit":16}
{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
"#;
let summary = summarize_jsonl(log);
assert!(summary.unhandled_exceptions.is_empty());
assert_eq!(
summary.breakpoint_exceptions,
[
BreakpointException {
exception_code: Some("0x80000003".into()),
module: Some("title.exe".into()),
module_base: Some("0x0000000140000000".into()),
rva: Some("0x0000000002236178".into()),
address: Some("0x0000000142236178".into()),
record: Some(1),
limit: Some(16),
},
BreakpointException {
exception_code: Some("0xc0000420".into()),
module: Some("?".into()),
module_base: Some("0x0000000000000000".into()),
rva: Some("0x0000000000000000".into()),
address: Some("0x0000000000410000".into()),
record: Some(2),
limit: Some(16),
},
]
);
}
#[test]
fn collects_unhandled_exceptions_in_log_order() {
let log = r#"
+893 -3
View File
@@ -1,8 +1,12 @@
#include <windows.h>
#include <tlhelp32.h>
#include <atomic>
#include <cstdio>
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <initializer_list>
#include <intrin.h>
#include "bx_config.h"
@@ -18,6 +22,12 @@ 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};
std::atomic<uint32_t> g_breakpoint_records{0};
// Breakpoint and assertion-failure records per process, so a guest that uses int3 on purpose
// cannot flood the log.
constexpr uint32_t kMaxBreakpointRecords = 16;
constexpr DWORD kStatusAssertionFailure = 0xC0000420;
// Other AMD-only instructions Rosetta 2 (and Intel CPUs) raise #UD on. Their
// counts reach the JSONL trace only: the frozen .def has no export for them.
@@ -354,11 +364,874 @@ LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) {
return disposition;
}
// A guest with its own crash reporter replaces the top-level filter installed at attach, so
// log_unhandled_exception never sees its assertions. The vectored handler runs before the
// guest's top-level filter and before any vectored handler the guest registers last; a handler
// the guest registers first can resume the exception before this one sees it. It records
// breakpoints and assertion failures with their module offset. They are first-chance, so the
// guest may still handle them; handling is left unchanged.
void log_breakpoint(const EXCEPTION_RECORD& record) {
// Past the cap the counter is not advanced again, so it cannot wrap around to 1.
if (g_breakpoint_records.load(std::memory_order_relaxed) >= kMaxBreakpointRecords) {
return;
}
const uint32_t index = g_breakpoint_records.fetch_add(1, std::memory_order_relaxed) + 1;
if (index > kMaxBreakpointRecords) {
return;
}
// The calls below can change the thread's last-error value; a resumed first-chance exception
// must leave the guest's error state as it was.
const DWORD last_error = GetLastError();
const uintptr_t address = reinterpret_cast<uintptr_t>(record.ExceptionAddress);
MEMORY_BASIC_INFORMATION region{};
uintptr_t module_base = 0;
char module[MAX_PATH] = "?";
if (VirtualQuery(record.ExceptionAddress, &region, sizeof(region)) &&
region.Type == MEM_IMAGE) {
module_base = reinterpret_cast<uintptr_t>(region.AllocationBase);
// Wide API plus an explicit UTF-8 conversion: the ANSI form returns the name in the
// active code page, which would make a non-ASCII module name invalid UTF-8 in the JSON.
wchar_t path[MAX_PATH];
const DWORD length =
GetModuleFileNameW(reinterpret_cast<HMODULE>(module_base), path, MAX_PATH);
if (length > 0 && length < MAX_PATH) {
const wchar_t* slash = std::wcsrchr(path, L'\\');
const wchar_t* name = slash ? slash + 1 : path;
if (WideCharToMultiByte(CP_UTF8, 0, name, -1, module, sizeof(module), nullptr, nullptr) == 0) {
std::snprintf(module, sizeof(module), "?");
}
}
}
char line[1024];
const int length = std::snprintf(
line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\","
"\"event\":\"breakpoint_exception\",\"exception_code\":\"0x%08lx\","
"\"module\":\"%s\",\"module_base\":\"0x%016llx\",\"rva\":\"0x%016llx\","
"\"address\":\"0x%016llx\",\"record\":%u,\"limit\":%u}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
record.ExceptionCode, module, static_cast<unsigned long long>(module_base),
static_cast<unsigned long long>(module_base ? address - module_base : 0),
static_cast<unsigned long long>(address), index, kMaxBreakpointRecords);
if (length > 0 && length < static_cast<int>(sizeof(line))) {
write_log_line(line, static_cast<size_t>(length));
}
SetLastError(last_error);
}
// Diagnostics (off unless BX_VEH_AV_CONTEXT is set): the first access violations in an image
// are logged with the general registers and, for each address in the variable, 64 bytes of
// memory. An entry "*ADDR+OFF" first reads the pointer at ADDR, then dumps at pointer + OFF.
// Reads are guarded by VirtualQuery; handling is left unchanged (first chance, search continues).
bool readable_bytes(uintptr_t address, size_t size) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(address), &region, sizeof(region)) || region.State != MEM_COMMIT ||
(region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
return false;
}
return address + size <= reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
// A JSONL line built with bounded appends: an append that does not fit is dropped and marks the
// line truncated, so the length never passes the buffer. Four bytes stay reserved for the closing
// "\"}\n". Text from the environment or module names goes through add_escaped.
class LineBuf {
public:
LineBuf(char* p, size_t cap) : p_(p), cap_(cap - 4) { p_[0] = '\0'; }
void add(const char* fmt, ...) {
if (truncated_) return;
va_list ap;
va_start(ap, fmt);
const int n = std::vsnprintf(p_ + len_, cap_ - len_, fmt, ap);
va_end(ap);
if (n < 0 || static_cast<size_t>(n) >= cap_ - len_) {
p_[len_] = '\0'; // drop the partial append
truncated_ = true;
return;
}
len_ += static_cast<size_t>(n);
}
// JSON string escaping for " \ and control characters; other bytes (UTF-8) pass through.
void add_escaped(const char* text, size_t max) {
for (size_t i = 0; text[i] && i < max && !truncated_; ++i) {
const unsigned char ch = static_cast<unsigned char>(text[i]);
if (ch == '"' || ch == '\\') add("\\%c", ch);
else if (ch < 0x20) add("\\u%04x", ch);
else add("%c", ch);
}
}
bool room(size_t n) const { return !truncated_ && cap_ - len_ > n; }
// Closes the JSON string and object and writes the line.
void finish() {
std::memcpy(p_ + len_, "\"}\n", 4);
write_log_line(p_, len_ + 3);
}
private:
char* p_;
size_t cap_;
size_t len_ = 0;
bool truncated_ = false;
};
// A module's file name (without the directory) in UTF-8, or "?" when it cannot be read.
void module_name_utf8(uintptr_t base, char* out, size_t size) {
wchar_t path[MAX_PATH];
const DWORD n = base ? GetModuleFileNameW(reinterpret_cast<HMODULE>(base), path, MAX_PATH) : 0;
if (n == 0 || n >= MAX_PATH) {
std::snprintf(out, size, "?");
return;
}
const wchar_t* slash = std::wcsrchr(path, L'\\');
const wchar_t* name = slash ? slash + 1 : path;
if (WideCharToMultiByte(CP_UTF8, 0, name, -1, out, static_cast<int>(size), nullptr, nullptr) == 0) {
std::snprintf(out, size, "?");
}
}
// BX_VEH_AV_CONTEXT and BX_VEH_AV_ALL, read once when runtime_veh attaches. With the context
// switch unset the access-violation path does nothing at all.
char g_av_spec[512];
bool g_av_context_on = false;
bool g_av_all = false;
void read_av_switches() {
const DWORD n = GetEnvironmentVariableA("BX_VEH_AV_CONTEXT", g_av_spec, sizeof(g_av_spec));
g_av_context_on = n > 0 && n < sizeof(g_av_spec);
char v[4];
const DWORD k = GetEnvironmentVariableA("BX_VEH_AV_ALL", v, sizeof(v));
g_av_all = k > 0 && k < sizeof(v) && v[0] == '1';
}
void log_av_context(const EXCEPTION_POINTERS& ep) {
static std::atomic<uint32_t> logged{0};
if (!g_av_context_on || logged.fetch_add(1) >= 16) return;
const CONTEXT& c = *ep.ContextRecord;
char line[1600];
LineBuf out(line, sizeof(line));
out.add("{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"av_context\","
"\"detail\":\"rip=%llx fault=%llx rax=%llx rbx=%llx rcx=%llx rdx=%llx rsi=%llx rdi=%llx rbp=%llx "
"rsp=%llx r8=%llx r9=%llx r10=%llx r11=%llx r12=%llx r13=%llx r14=%llx r15=%llx",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)c.Rip,
(unsigned long long)(ep.ExceptionRecord->NumberParameters >= 2 ? ep.ExceptionRecord->ExceptionInformation[1] : 0),
(unsigned long long)c.Rax, (unsigned long long)c.Rbx, (unsigned long long)c.Rcx,
(unsigned long long)c.Rdx, (unsigned long long)c.Rsi, (unsigned long long)c.Rdi,
(unsigned long long)c.Rbp, (unsigned long long)c.Rsp, (unsigned long long)c.R8,
(unsigned long long)c.R9, (unsigned long long)c.R10, (unsigned long long)c.R11,
(unsigned long long)c.R12, (unsigned long long)c.R13, (unsigned long long)c.R14,
(unsigned long long)c.R15);
// The comma-separated spec, scanned without shared state (several threads can fault at once).
for (const char* cursor = g_av_spec; *cursor && out.room(220);) {
const char* comma = std::strchr(cursor, ',');
const size_t length = comma ? static_cast<size_t>(comma - cursor) : std::strlen(cursor);
char item[64];
const size_t take = length < sizeof(item) - 1 ? length : sizeof(item) - 1;
std::memcpy(item, cursor, take);
item[take] = '\0';
cursor += length + (comma ? 1 : 0);
// "*A+O": dump at [A]+O. "**A+O1+O2": dump at [[A]+O1]+O2.
const int derefs = item[0] == '*' ? (item[1] == '*' ? 2 : 1) : 0;
char* rest = nullptr;
uintptr_t address = static_cast<uintptr_t>(std::strtoull(item + derefs, &rest, 16));
uintptr_t offsets[2] = {0, 0};
for (int k = 0; k < 2 && rest && *rest == '+'; ++k) offsets[k] = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
bool ok = true;
for (int k = 0; k < derefs && ok; ++k) {
ok = readable_bytes(address, 8);
if (ok) address = *reinterpret_cast<const uintptr_t*>(address) + offsets[k];
}
out.add(" | ");
out.add_escaped(item, sizeof(item));
if (!ok) {
out.add(" unresolved");
continue;
}
if (derefs == 0) address += offsets[0];
out.add(" @%llx:", (unsigned long long)address);
MEMORY_BASIC_INFORMATION mbi{};
if (VirtualQuery(reinterpret_cast<void*>(address), &mbi, sizeof(mbi))) {
out.add(" [type=%lx prot=%lx alloc=%llx region=%llx+%llx]", static_cast<unsigned long>(mbi.Type),
static_cast<unsigned long>(mbi.Protect), (unsigned long long)reinterpret_cast<uintptr_t>(mbi.AllocationBase),
(unsigned long long)reinterpret_cast<uintptr_t>(mbi.BaseAddress), (unsigned long long)mbi.RegionSize);
}
if (!readable_bytes(address, 64)) {
out.add(" unreadable");
continue;
}
const auto* q = reinterpret_cast<const uint64_t*>(address);
for (int i = 0; i < 8; ++i) out.add(" %llx", (unsigned long long)q[i]);
}
// The faulting thread's stack: up to eight frames, unwound from its context, as module+offset.
out.add(" | stack:");
CONTEXT walk = c;
for (int i = 0; i < 8 && walk.Rip && out.room(64); ++i) {
MEMORY_BASIC_INFORMATION region{};
uintptr_t base = 0;
if (VirtualQuery(reinterpret_cast<void*>(walk.Rip), &region, sizeof(region)) && region.Type == MEM_IMAGE) {
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
char name[96] = "anon";
if (base) module_name_utf8(base, name, sizeof(name));
out.add(" ");
out.add_escaped(name, 24);
out.add("+%llx", (unsigned long long)(walk.Rip - base));
DWORD64 image = 0;
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
if (!fn) {
if (!readable_bytes(static_cast<uintptr_t>(walk.Rsp), 8)) break;
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
walk.Rsp += 8;
continue;
}
PVOID handler_data = nullptr;
DWORD64 frame = 0;
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
}
out.finish();
}
// A diagnostic that had to stop (a protection change failed): logged once per kind.
void log_disarmed(const char* what, uintptr_t address) {
char line[256];
const int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"diagnostic_disarmed\","
"\"detail\":\"%s address=%llx error=%lu\"}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), what,
(unsigned long long)address, GetLastError());
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
}
// Set when runtime_veh detaches: helper threads stop at their next step and log nothing more.
std::atomic<bool> g_diag_stop{false};
std::atomic<int> g_diag_threads{0};
// Diagnostics (off unless BX_VEH_WATCH=ADDR:LEN, hex): a software write watch. A helper thread
// makes the page holding [ADDR, ADDR+LEN) read-only as soon as that page is committed. Each
// write fault in the page is allowed by restoring write access and single-stepping the writing
// instruction; writes inside the range are logged with the instruction's module offset and the
// value after the write, then the page is protected again. Writes by other threads while the
// page is briefly writable are not seen, and system calls that write into the page fail while
// it is protected, so this is for diagnosis only.
uintptr_t g_watch_begin = 0, g_watch_end = 0, g_watch_page = 0;
std::atomic<bool> g_watch_armed{false};
std::atomic<uint32_t> g_watch_logged{0};
DWORD g_watch_tls = TLS_OUT_OF_INDEXES;
// The watched address: "A:LEN", or a pointer chain "*A+O:LEN" / "**A+O1+O2:LEN" that the helper
// thread resolves once every pointer in it is non-null and readable.
uintptr_t g_watch_root = 0, g_watch_offsets[2] = {0, 0}, g_watch_length = 8;
int g_watch_derefs = 0;
bool resolve_watch(uintptr_t* out) {
uintptr_t address = g_watch_root;
for (int k = 0; k < g_watch_derefs; ++k) {
if (!readable_bytes(address, 8)) return false;
const uintptr_t next = *reinterpret_cast<const uintptr_t*>(address);
if (!next) return false;
address = next + g_watch_offsets[k];
}
if (g_watch_derefs == 0) address += g_watch_offsets[0];
*out = address;
return true;
}
DWORD WINAPI watch_arm_thread(LPVOID) {
for (int i = 0; i < 600000 && !g_watch_armed.load() && !g_diag_stop.load(); ++i) {
uintptr_t begin = 0;
DWORD old = 0;
if (resolve_watch(&begin) && readable_bytes(begin, g_watch_length)) {
g_watch_begin = begin;
g_watch_end = begin + g_watch_length;
g_watch_page = begin & ~static_cast<uintptr_t>(4095);
char line[512];
int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"watch_armed\","
"\"detail\":\"address=%llx contents:",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)begin);
for (uintptr_t a = begin; a + 8 <= g_watch_end && len < static_cast<int>(sizeof(line)) - 24; a += 8) {
len += std::snprintf(line + len, sizeof(line) - len, " %llx",
(unsigned long long)*reinterpret_cast<const uint64_t*>(a));
}
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
if (VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) {
g_watch_armed = true;
} else {
log_disarmed("watch: could not protect the page", g_watch_page);
}
break;
}
Sleep(1);
}
return 0;
}
void start_write_watch() {
char spec[96];
const DWORD n = GetEnvironmentVariableA("BX_VEH_WATCH", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return;
g_watch_derefs = spec[0] == '*' ? (spec[1] == '*' ? 2 : 1) : 0;
char* rest = nullptr;
g_watch_root = static_cast<uintptr_t>(std::strtoull(spec + g_watch_derefs, &rest, 16));
for (int k = 0; k < 2 && rest && *rest == '+'; ++k) g_watch_offsets[k] = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
if (rest && *rest == ':') g_watch_length = static_cast<uintptr_t>(std::strtoull(rest + 1, nullptr, 16));
g_watch_tls = TlsAlloc();
if (g_watch_tls == TLS_OUT_OF_INDEXES) return;
if (HANDLE t = CreateThread(nullptr, 0, watch_arm_thread, nullptr, 0, nullptr)) {
++g_diag_threads;
CloseHandle(t);
}
}
void log_watched_write(uintptr_t rip, uintptr_t address, uint64_t value) {
if (g_watch_logged.fetch_add(1) >= 64) return;
MEMORY_BASIC_INFORMATION region{};
uintptr_t base = 0;
if (VirtualQuery(reinterpret_cast<void*>(rip), &region, sizeof(region)) && region.Type == MEM_IMAGE) {
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
char line[256];
const int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"watched_write\","
"\"detail\":\"rip=%llx module_base=%llx address=%llx value_after=%llx\"}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)rip, (unsigned long long)base, (unsigned long long)address,
(unsigned long long)value);
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
}
// Returns true when the exception belonged to the write watch and was handled.
bool handle_write_watch(PEXCEPTION_POINTERS ep) {
if (!g_watch_armed.load() || g_watch_tls == TLS_OUT_OF_INDEXES) return false;
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
if (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1) {
const uintptr_t address = static_cast<uintptr_t>(r.ExceptionInformation[1]);
if ((address & ~static_cast<uintptr_t>(4095)) != g_watch_page) return false;
DWORD old = 0;
if (!VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old)) {
// Fail open: the write cannot be allowed, so the guest gets its access violation.
g_watch_armed = false;
log_disarmed("watch: could not unprotect the page", g_watch_page);
return false;
}
// Remember the write for the single-step that follows it (+1 so 0 means "none").
TlsSetValue(g_watch_tls, reinterpret_cast<void*>(address + 1));
ep->ContextRecord->EFlags |= 0x100;
return true;
}
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_watch_tls));
if (!pending) return false;
TlsSetValue(g_watch_tls, nullptr);
const uintptr_t address = pending - 1;
if (address >= g_watch_begin && address < g_watch_end) {
const uintptr_t slot = address & ~static_cast<uintptr_t>(7);
log_watched_write(static_cast<uintptr_t>(reinterpret_cast<uintptr_t>(r.ExceptionAddress)), address,
*reinterpret_cast<const uint64_t*>(slot));
}
DWORD old = 0;
if (!g_watch_armed.load() || !VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) {
if (g_watch_armed.exchange(false)) log_disarmed("watch: could not re-protect the page", g_watch_page);
}
return true;
}
return false;
}
// Diagnostics (off unless BX_VEH_WATCH_RANGE=A:LEN, hex, at most 16 MiB): a write watch over a
// range of pages, for data whose exact address moves between runs. A helper thread makes each
// read-write page in the range read-only as soon as it is committed. A write fault is allowed by
// restoring the page and single-stepping the instruction; the write is logged with its address,
// the value after it and up to six frames of the writing thread, unwound from its context. After
// 64 logged writes the whole range is made writable again and the watch stops.
constexpr size_t kRangeWatchPages = 4096;
uintptr_t g_rw_begin = 0, g_rw_end = 0;
std::atomic<uint8_t> g_rw_armed[kRangeWatchPages];
std::atomic<bool> g_rw_on{false};
std::atomic<uint32_t> g_rw_logged{0};
DWORD g_rw_tls = TLS_OUT_OF_INDEXES;
void range_watch_stop() {
g_rw_on = false;
for (size_t i = 0; i < kRangeWatchPages; ++i) {
if (g_rw_armed[i].exchange(0)) {
DWORD old = 0;
VirtualProtect(reinterpret_cast<void*>(g_rw_begin + i * 4096), 4096, PAGE_READWRITE, &old);
}
}
}
// "*A+O:LEN": the range starts at [A] + O, resolved once the pointer at A is readable and non-zero.
uintptr_t g_rw_root = 0, g_rw_offset = 0, g_rw_length = 0;
DWORD WINAPI range_watch_thread(LPVOID) {
if (g_rw_root) {
for (int i = 0; i < 600000; ++i) {
if (g_diag_stop.load()) return 0;
if (readable_bytes(g_rw_root, 8) && *reinterpret_cast<const uintptr_t*>(g_rw_root)) break;
Sleep(1);
}
if (!readable_bytes(g_rw_root, 8) || !*reinterpret_cast<const uintptr_t*>(g_rw_root)) return 0;
const uintptr_t begin = (*reinterpret_cast<const uintptr_t*>(g_rw_root) + g_rw_offset) & ~static_cast<uintptr_t>(4095);
g_rw_end = (begin + g_rw_length + 4095) & ~static_cast<uintptr_t>(4095);
g_rw_begin = begin;
char line[200];
const int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"range_watch_resolved\","
"\"detail\":\"begin=%llx end=%llx\"}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)g_rw_begin, (unsigned long long)g_rw_end);
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
}
const size_t pages = (g_rw_end - g_rw_begin) / 4096;
for (int round = 0; round < 600000 && g_rw_on.load() && !g_diag_stop.load(); ++round) {
bool all = true;
for (size_t i = 0; i < pages && g_rw_on.load(); ++i) {
if (g_rw_armed[i].load()) continue;
all = false;
const uintptr_t page = g_rw_begin + i * 4096;
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(page), &region, sizeof(region)) || region.State != MEM_COMMIT ||
region.Protect != PAGE_READWRITE) {
continue;
}
DWORD old = 0;
if (VirtualProtect(reinterpret_cast<void*>(page), 4096, PAGE_READONLY, &old)) g_rw_armed[i] = 1;
}
if (all) break;
Sleep(1);
}
return 0;
}
void start_range_watch() {
char spec[64];
const DWORD n = GetEnvironmentVariableA("BX_VEH_WATCH_RANGE", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return;
char* rest = nullptr;
const bool chain = spec[0] == '*';
const uintptr_t first = static_cast<uintptr_t>(std::strtoull(spec + (chain ? 1 : 0), &rest, 16));
uintptr_t offset = 0;
if (chain && rest && *rest == '+') offset = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
const uintptr_t length = rest && *rest == ':' ? static_cast<uintptr_t>(std::strtoull(rest + 1, nullptr, 16)) : 0;
if (!first || !length || length > kRangeWatchPages * 4096) return;
g_rw_tls = TlsAlloc();
if (g_rw_tls == TLS_OUT_OF_INDEXES) return;
if (chain) {
g_rw_root = first;
g_rw_offset = offset;
g_rw_length = length;
} else {
g_rw_begin = first & ~static_cast<uintptr_t>(4095);
g_rw_end = (g_rw_begin + length + 4095) & ~static_cast<uintptr_t>(4095);
}
g_rw_on = true;
if (HANDLE t = CreateThread(nullptr, 0, range_watch_thread, nullptr, 0, nullptr)) {
++g_diag_threads;
CloseHandle(t);
}
}
void log_range_write(const CONTEXT& c, uintptr_t address) {
uintptr_t frames[6]{};
int count = 0;
CONTEXT walk = c;
for (; count < 6 && walk.Rip; ++count) {
frames[count] = static_cast<uintptr_t>(walk.Rip);
DWORD64 image = 0;
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
if (!fn) {
if (!readable_bytes(static_cast<uintptr_t>(walk.Rsp), 8)) { ++count; break; }
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
walk.Rsp += 8;
continue;
}
PVOID handler_data = nullptr;
DWORD64 frame = 0;
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
}
char line[640];
int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"range_write\","
"\"detail\":\"address=%llx value_after=%llx frames:",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)address,
(unsigned long long)*reinterpret_cast<const uint64_t*>(address & ~static_cast<uintptr_t>(7)));
for (int i = 0; i < count && len < static_cast<int>(sizeof(line)) - 48; ++i) {
MEMORY_BASIC_INFORMATION region{};
uintptr_t base = 0;
if (VirtualQuery(reinterpret_cast<void*>(frames[i]), &region, sizeof(region)) && region.Type == MEM_IMAGE) {
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
len += std::snprintf(line + len, sizeof(line) - len, " %llx+%llx", (unsigned long long)base,
(unsigned long long)(frames[i] - base));
}
if (len > 0 && len < static_cast<int>(sizeof(line)) - 4) {
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
write_log_line(line, static_cast<size_t>(len));
}
}
// Returns true when the exception belonged to the range watch and was handled.
bool handle_range_watch(PEXCEPTION_POINTERS ep) {
if (g_rw_tls == TLS_OUT_OF_INDEXES) return false;
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
if (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1) {
const uintptr_t address = static_cast<uintptr_t>(r.ExceptionInformation[1]);
if (address < g_rw_begin || address >= g_rw_end) return false;
const size_t index = (address - g_rw_begin) / 4096;
if (!g_rw_armed[index].load()) return false;
DWORD old = 0;
if (!VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READWRITE, &old)) {
g_rw_armed[index] = 0; // fail open: the guest gets its access violation
log_disarmed("range watch: could not unprotect a page", g_rw_begin + index * 4096);
return false;
}
TlsSetValue(g_rw_tls, reinterpret_cast<void*>(address + 1));
ep->ContextRecord->EFlags |= 0x100;
return true;
}
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_rw_tls));
if (!pending) return false;
TlsSetValue(g_rw_tls, nullptr);
const uintptr_t address = pending - 1;
static const uint32_t cap = [] {
char v[16];
const DWORD k = GetEnvironmentVariableA("BX_VEH_WATCH_RANGE_MAX", v, sizeof(v));
const unsigned long want = (k > 0 && k < sizeof(v)) ? std::strtoul(v, nullptr, 10) : 64;
return static_cast<uint32_t>(want == 0 ? 64 : (want > 200000 ? 200000 : want));
}();
const uint32_t n = g_rw_logged.fetch_add(1);
if (n < cap) log_range_write(*ep->ContextRecord, address);
if (n + 1 >= cap) {
range_watch_stop();
} else if (g_rw_on.load()) {
DWORD old = 0;
const size_t index = (address - g_rw_begin) / 4096;
if (g_rw_armed[index].load() &&
!VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READONLY, &old)) {
g_rw_armed[index] = 0;
log_disarmed("range watch: could not re-protect a page", g_rw_begin + index * 4096);
}
}
return true;
}
return false;
}
// Diagnostics (off unless BX_VEH_HIT=A1,A2,..., hex, at most 8): software code breakpoints in this
// process. Each address gets an int3 when runtime_veh attaches; a hit logs the registers, puts the
// original byte back, single-steps that instruction and re-inserts the int3. The first 16 hits per
// address are logged, then every 256th. Other threads can pass an address unseen while its byte is
// restored, so this is for diagnosis only.
struct CodeHit {
uintptr_t address;
uint8_t original;
std::atomic<uint32_t> hits;
};
CodeHit g_code_hits[8];
int g_code_hit_count = 0;
DWORD g_code_hit_tls = TLS_OUT_OF_INDEXES;
// False when the byte could not be written. A failure to restore the page's original protection
// is logged: the page then stays writable, which the log record makes visible.
bool write_code_byte(uintptr_t address, uint8_t value) {
DWORD old = 0;
if (!VirtualProtect(reinterpret_cast<void*>(address), 1, PAGE_EXECUTE_READWRITE, &old)) return false;
*reinterpret_cast<volatile uint8_t*>(address) = value;
DWORD unused = 0;
if (!VirtualProtect(reinterpret_cast<void*>(address), 1, old, &unused)) {
log_disarmed("code hit: could not restore the page protection", address);
}
FlushInstructionCache(GetCurrentProcess(), reinterpret_cast<void*>(address), 1);
return true;
}
// Diagnostics (off unless BX_VEH_SAMPLE=MS, decimal): a sampling profiler for every thread in the
// process. Every MS milliseconds a helper thread visits each other thread: while it is suspended
// only its context and up to 64 KiB of its stack are copied (no heap or loader calls, so a thread
// suspended inside either cannot deadlock the sampler). After it resumes, up to eight frames are
// unwound against the copy with the images' unwind data and logged as module base + offset, with
// the thread id. At most 20000 samples are logged. For diagnosis only.
DWORD g_sample_interval = 0;
DWORD g_sample_self = 0;
alignas(16) uint8_t g_sample_stack[64 * 1024];
void sample_thread(DWORD tid) {
HANDLE h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, tid);
if (!h) return;
CONTEXT c{};
c.ContextFlags = CONTEXT_FULL;
uintptr_t stack_lo = 0;
size_t copied = 0;
bool got = false;
if (SuspendThread(h) != static_cast<DWORD>(-1)) {
got = GetThreadContext(h, &c) != FALSE;
MEMORY_BASIC_INFORMATION region{};
if (got && VirtualQuery(reinterpret_cast<void*>(c.Rsp), &region, sizeof(region)) && region.State == MEM_COMMIT) {
stack_lo = static_cast<uintptr_t>(c.Rsp);
const uintptr_t end = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
copied = end - stack_lo < sizeof(g_sample_stack) ? end - stack_lo : sizeof(g_sample_stack);
std::memcpy(g_sample_stack, reinterpret_cast<const void*>(stack_lo), copied);
}
ResumeThread(h);
}
CloseHandle(h);
if (!got) return;
// Unwind against the copy: stack addresses (rsp, and rbp when it points into the stack) are
// rebased into g_sample_stack; return addresses read from it are the thread's real ones.
const uintptr_t copy = reinterpret_cast<uintptr_t>(g_sample_stack);
auto in_stack = [&](DWORD64 a) { return a >= stack_lo && a < stack_lo + copied; };
CONTEXT walk = c;
walk.Rsp = copy;
if (in_stack(c.Rbp)) walk.Rbp = copy + (c.Rbp - stack_lo);
uintptr_t frames[8]{};
int count = 0;
for (; count < 8 && walk.Rip; ++count) {
frames[count] = static_cast<uintptr_t>(walk.Rip);
if (walk.Rsp < copy || walk.Rsp + 8 > copy + copied) { ++count; break; }
DWORD64 image = 0;
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
if (!fn) { // leaf function: the return address is at rsp
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
walk.Rsp += 8;
continue;
}
PVOID handler_data = nullptr;
DWORD64 frame = 0;
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
}
char line[760];
LineBuf out(line, sizeof(line));
out.add("{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"sample\",\"detail\":\"thread=%lu",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), tid);
for (int i = 0; i < count && out.room(64); ++i) {
MEMORY_BASIC_INFORMATION region{};
uintptr_t base = 0;
if (VirtualQuery(reinterpret_cast<void*>(frames[i]), &region, sizeof(region)) && region.Type == MEM_IMAGE) {
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
// The thread runs again, so the loader lock taken by GetModuleFileNameW cannot be held by it.
char name[96] = "anon";
if (base) module_name_utf8(base, name, sizeof(name));
out.add(" ");
out.add_escaped(name, 24);
out.add("+%llx", (unsigned long long)(frames[i] - base));
}
if (!g_diag_stop.load()) out.finish();
}
DWORD WINAPI sampler_main(LPVOID) {
const DWORD pid = GetCurrentProcessId();
for (int logged = 0; logged < 20000 && !g_diag_stop.load();) {
Sleep(g_sample_interval);
if (g_diag_stop.load()) break;
DWORD tids[256];
int n = 0;
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (snap == INVALID_HANDLE_VALUE) continue;
THREADENTRY32 te{};
te.dwSize = sizeof(te);
for (BOOL ok = Thread32First(snap, &te); ok && n < 256; ok = Thread32Next(snap, &te)) {
if (te.th32OwnerProcessID == pid && te.th32ThreadID != g_sample_self) tids[n++] = te.th32ThreadID;
}
CloseHandle(snap);
for (int i = 0; i < n; ++i, ++logged) sample_thread(tids[i]);
}
return 0;
}
void start_sampler() {
char spec[16];
const DWORD n = GetEnvironmentVariableA("BX_VEH_SAMPLE", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return;
g_sample_interval = static_cast<DWORD>(std::strtoul(spec, nullptr, 10));
if (g_sample_interval == 0) return;
if (HANDLE t = CreateThread(nullptr, 0, sampler_main, nullptr, 0, &g_sample_self)) {
++g_diag_threads;
CloseHandle(t);
}
}
void start_code_hits() {
char spec[256];
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return;
g_code_hit_tls = TlsAlloc();
if (g_code_hit_tls == TLS_OUT_OF_INDEXES) return;
for (const char* item = spec; *item && g_code_hit_count < 8;) {
char* end = nullptr;
const uintptr_t address = static_cast<uintptr_t>(std::strtoull(item, &end, 16));
const char* comma = std::strchr(item, ',');
item = comma ? comma + 1 : item + std::strlen(item);
MEMORY_BASIC_INFORMATION region{};
if (!address || !VirtualQuery(reinterpret_cast<void*>(address), &region, sizeof(region)) ||
region.Type != MEM_IMAGE || region.State != MEM_COMMIT) {
continue;
}
CodeHit& hit = g_code_hits[g_code_hit_count];
hit.address = address;
hit.original = *reinterpret_cast<const uint8_t*>(address);
if (write_code_byte(address, 0xCC)) ++g_code_hit_count;
}
char line[160];
const int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"code_hits_armed\","
"\"detail\":\"count=%d\"}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), g_code_hit_count);
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
}
void log_code_hit(const CodeHit& hit, uint32_t count, const CONTEXT& c) {
char line[2048];
int len = std::snprintf(
line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"code_hit\","
"\"detail\":\"address=%llx hit=%u rax=%llx rbx=%llx rcx=%llx rdx=%llx rsi=%llx rdi=%llx rbp=%llx rsp=%llx "
"r8=%llx r9=%llx r10=%llx r11=%llx r12=%llx r13=%llx r14=%llx r15=%llx",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), (unsigned long long)hit.address, count,
(unsigned long long)c.Rax, (unsigned long long)c.Rbx, (unsigned long long)c.Rcx, (unsigned long long)c.Rdx,
(unsigned long long)c.Rsi, (unsigned long long)c.Rdi, (unsigned long long)c.Rbp, (unsigned long long)c.Rsp,
(unsigned long long)c.R8, (unsigned long long)c.R9, (unsigned long long)c.R10, (unsigned long long)c.R11,
(unsigned long long)c.R12, (unsigned long long)c.R13, (unsigned long long)c.R14, (unsigned long long)c.R15);
// The first 16 bytes behind the three argument registers, when they point at readable memory.
const struct {
const char* name;
DWORD64 value;
} args[] = {{"rcx", c.Rcx}, {"rdx", c.Rdx}, {"r8", c.R8}};
for (const auto& a : args) {
if (len <= 0 || len >= static_cast<int>(sizeof(line)) - 64 || !readable_bytes(static_cast<uintptr_t>(a.value), 16)) continue;
const auto* q = reinterpret_cast<const uint64_t*>(static_cast<uintptr_t>(a.value));
len += std::snprintf(line + len, sizeof(line) - len, " [%s]=%016llx %016llx", a.name, (unsigned long long)q[0],
(unsigned long long)q[1]);
// Printable text (a path or name argument): up to 96 characters of it.
const auto* s = reinterpret_cast<const unsigned char*>(static_cast<uintptr_t>(a.value));
if (s[0] >= 0x20 && s[0] < 0x7f && s[1] >= 0x20 && s[1] < 0x7f && readable_bytes(static_cast<uintptr_t>(a.value), 96)) {
char text[97];
int n = 0;
while (n < 96 && s[n] >= 0x20 && s[n] < 0x7f) {
text[n] = (s[n] == '"' || s[n] == '\\') ? '_' : static_cast<char>(s[n]);
++n;
}
text[n] = '\0';
if (len < static_cast<int>(sizeof(line)) - 120) {
len += std::snprintf(line + len, sizeof(line) - len, " [%s]s=%s", a.name, text);
}
}
}
// BX_VEH_HIT_RDX=LEN (hex, at most 0x200): also dump LEN bytes of the object rdx points to.
static const size_t rdx_len = [] {
char v[16];
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT_RDX", v, sizeof(v));
if (n == 0 || n >= sizeof(v)) return static_cast<size_t>(0);
const size_t want = static_cast<size_t>(std::strtoull(v, nullptr, 16)) & ~static_cast<size_t>(7);
return want > 0x200 ? static_cast<size_t>(0x200) : want;
}();
if (rdx_len && len > 0 && readable_bytes(static_cast<uintptr_t>(c.Rdx), rdx_len)) {
const auto* q = reinterpret_cast<const uint64_t*>(static_cast<uintptr_t>(c.Rdx));
len += std::snprintf(line + len, sizeof(line) - len, " rdx_obj:");
for (size_t i = 0; i < rdx_len / 8 && len < static_cast<int>(sizeof(line)) - 24; ++i) {
len += std::snprintf(line + len, sizeof(line) - len, " %llx", (unsigned long long)q[i]);
}
}
if (len > 0 && len < static_cast<int>(sizeof(line)) - 4) {
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
write_log_line(line, static_cast<size_t>(len));
}
}
// Returns true when the exception belonged to a code breakpoint and was handled.
bool handle_code_hit(PEXCEPTION_POINTERS ep) {
if (g_code_hit_count == 0) return false;
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
CONTEXT& c = *ep->ContextRecord;
if (r.ExceptionCode == EXCEPTION_BREAKPOINT) {
const uintptr_t at = reinterpret_cast<uintptr_t>(r.ExceptionAddress);
for (int i = 0; i < g_code_hit_count; ++i) {
CodeHit& hit = g_code_hits[i];
if (at != hit.address && c.Rip - 1 != hit.address) continue;
const uint32_t count = hit.hits.fetch_add(1) + 1;
static const bool every = [] {
char v[4];
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT_ALL", v, sizeof(v));
return n > 0 && n < sizeof(v) && v[0] == '1';
}();
if (count <= 16 || count % 256 == 0 || (every && count <= 20000)) log_code_hit(hit, count, c);
if (!write_code_byte(hit.address, hit.original)) {
// The original instruction cannot be put back: stop handling this address and let
// the breakpoint reach the guest instead of looping on it.
log_disarmed("code hit: could not restore the original byte", hit.address);
hit.address = 0;
return false;
}
c.Rip = hit.address;
c.EFlags |= 0x100;
TlsSetValue(g_code_hit_tls, reinterpret_cast<void*>(static_cast<uintptr_t>(i + 1)));
return true;
}
return false;
}
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_code_hit_tls));
if (!pending) return false;
TlsSetValue(g_code_hit_tls, nullptr);
CodeHit& hit = g_code_hits[pending - 1];
if (hit.address && !g_diag_stop.load() && !write_code_byte(hit.address, 0xCC)) {
log_disarmed("code hit: could not re-insert the breakpoint", hit.address);
hit.address = 0;
}
return true;
}
return false;
}
// Restores every page and code byte the diagnostics changed (used at detach).
void disarm_diagnostics() {
if (g_watch_armed.exchange(false)) {
DWORD old = 0;
VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old);
}
if (g_rw_on.load() || g_rw_begin) range_watch_stop();
for (int i = 0; i < g_code_hit_count; ++i) {
CodeHit& hit = g_code_hits[i];
if (hit.address && *reinterpret_cast<const volatile uint8_t*>(hit.address) == 0xCC) {
write_code_byte(hit.address, hit.original);
}
hit.address = 0;
}
for (DWORD* tls : {&g_watch_tls, &g_rw_tls, &g_code_hit_tls}) {
if (*tls != TLS_OUT_OF_INDEXES) {
TlsFree(*tls);
*tls = TLS_OUT_OF_INDEXES;
}
}
}
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
if (!ep || !ep->ExceptionRecord || !ep->ContextRecord) {
return EXCEPTION_CONTINUE_SEARCH;
}
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION) {
if (handle_code_hit(ep)) return EXCEPTION_CONTINUE_EXECUTION;
if (handle_range_watch(ep)) return EXCEPTION_CONTINUE_EXECUTION;
if (handle_write_watch(ep)) return EXCEPTION_CONTINUE_EXECUTION;
const DWORD code = ep->ExceptionRecord->ExceptionCode;
if (code == EXCEPTION_BREAKPOINT || code == kStatusAssertionFailure) {
log_breakpoint(*ep->ExceptionRecord);
return EXCEPTION_CONTINUE_SEARCH;
}
if (code == EXCEPTION_ACCESS_VIOLATION) {
if (!g_av_context_on) return EXCEPTION_CONTINUE_SEARCH; // diagnostics off: no work at all
MEMORY_BASIC_INFORMATION region{};
if (g_av_all || (VirtualQuery(ep->ExceptionRecord->ExceptionAddress, &region, sizeof(region)) && region.Type == MEM_IMAGE)) {
log_av_context(*ep);
}
return EXCEPTION_CONTINUE_SEARCH;
}
if (code != EXCEPTION_ILLEGAL_INSTRUCTION) {
return EXCEPTION_CONTINUE_SEARCH;
}
@@ -479,6 +1352,15 @@ const bx_runtime_config_t* bx_get_runtime_config(void) {
int bx_veh_install(void) {
if (!g_veh_handle) {
g_veh_handle = AddVectoredExceptionHandler(1, bx_veh_handler);
if (g_veh_handle) {
read_av_switches();
// The helper threads below start running only after the loader lock is released; nothing
// here waits for them. They check g_diag_stop and stop at detach.
start_write_watch();
start_code_hits();
start_sampler();
start_range_watch();
}
}
return g_veh_handle != nullptr ? 1 : 0;
}
@@ -503,15 +1385,23 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
if (current_filter != log_unhandled_exception) {
SetUnhandledExceptionFilter(current_filter);
}
// Stop the diagnostics and take them out of the guest's memory: restore watched pages and
// original code bytes. Nothing waits for the helper threads (that would deadlock on the
// loader lock); they stop at their next step.
g_diag_stop = true;
disarm_diagnostics();
if (g_veh_handle) {
RemoveVectoredExceptionHandler(g_veh_handle);
g_veh_handle = nullptr;
}
if (g_log_handle != INVALID_HANDLE_VALUE) {
// A helper thread may still be inside write_log_line when this runs. While any helper was
// started, the log handle and its lock are left alive (the process is ending, or the DLL is
// being unloaded with threads that only touch them); otherwise they are released.
if (g_diag_threads.load() == 0 && g_log_handle != INVALID_HANDLE_VALUE) {
CloseHandle(g_log_handle);
g_log_handle = INVALID_HANDLE_VALUE;
}
if (g_log_lock_ready) {
if (g_diag_threads.load() == 0 && g_log_lock_ready) {
DeleteCriticalSection(&g_log_lock);
g_log_lock_ready = false;
}
@@ -0,0 +1,2 @@
add_executable(test_veh_breakpoint main.cpp)
target_link_libraries(test_veh_breakpoint PRIVATE bx_runtime_veh kernel32)
@@ -0,0 +1,155 @@
/*
* runtime_veh records breakpoints and assertion failures even when the guest has replaced the
* top-level exception filter, as a title with its own crash reporter does.
*
* The test installs its own top-level filter and a last-registered vectored handler that
* resumes after each int3, then raises breakpoints at a labelled site and one
* STATUS_ASSERTION_FAILURE. The expected RVA is the label's address minus this module's base,
* computed here, not by the shim. Needs BX_LOG_FILE (bx-cli --log).
*/
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <string>
extern "C" uint64_t bx_veh_get_clwb_trap_count(void);
extern "C" void bx_breakpoint_site(void);
__asm__(".text\n"
".globl bx_breakpoint_site\n"
"bx_breakpoint_site:\n"
" int3\n"
" ret\n");
namespace {
constexpr DWORD kStatusAssertionFailure = 0xC0000420;
constexpr int kRecordLimit = 16;
int g_failures = 0;
volatile LONG g_resumed = 0;
volatile LONG g_filter_calls = 0;
void check(bool ok, const char* what) {
if (!ok) {
std::fprintf(stderr, "FAIL: test_veh_breakpoint: %s\n", what);
++g_failures;
}
}
LONG WINAPI guest_filter(PEXCEPTION_POINTERS) {
InterlockedIncrement(&g_filter_calls);
return EXCEPTION_CONTINUE_SEARCH;
}
LONG CALLBACK resume(PEXCEPTION_POINTERS ep) {
const DWORD code = ep->ExceptionRecord->ExceptionCode;
if (code == EXCEPTION_BREAKPOINT) {
ep->ContextRecord->Rip =
reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress) + 1;
InterlockedIncrement(&g_resumed);
return EXCEPTION_CONTINUE_EXECUTION;
}
if (code == kStatusAssertionFailure) {
InterlockedIncrement(&g_resumed);
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
std::string read_log_from(long offset) {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* file = std::fopen(path, "rb")) {
if (std::fseek(file, offset, SEEK_SET) == 0) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), file)) > 0) text.append(buffer, got);
}
std::fclose(file);
}
return text;
}
long log_size() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return -1;
long size = 0;
if (FILE* file = std::fopen(path, "rb")) {
if (std::fseek(file, 0, SEEK_END) == 0) size = std::ftell(file);
std::fclose(file);
}
return size < 0 ? 0 : size;
}
int count_lines_with(const std::string& log, const char* a, const char* b = nullptr) {
int count = 0;
size_t start = 0;
while (start < log.size()) {
size_t end = log.find('\n', start);
if (end == std::string::npos) end = log.size();
const std::string line = log.substr(start, end - start);
if (line.find(a) != std::string::npos && (!b || line.find(b) != std::string::npos)) {
++count;
}
start = end + 1;
}
return count;
}
} // namespace
int main() {
// Keep a static import on bx_runtime_veh.dll so its handler is installed at attach.
volatile uint64_t attached = bx_veh_get_clwb_trap_count();
(void)attached;
const long mark = log_size();
if (mark < 0) {
std::fprintf(stderr, "FAIL: test_veh_breakpoint: BX_LOG_FILE must be set\n");
return 1;
}
// A title's crash reporter takes over the top-level filter after runtime_veh attached.
SetUnhandledExceptionFilter(guest_filter);
PVOID handler = AddVectoredExceptionHandler(0, resume);
check(handler != nullptr, "AddVectoredExceptionHandler");
// A recorded breakpoint leaves the guest thread's last-error value as it was.
SetLastError(0x12345678);
bx_breakpoint_site();
check(GetLastError() == 0x12345678, "a recorded breakpoint preserves the thread's last-error value");
RaiseException(kStatusAssertionFailure, 0, 0, nullptr);
for (int i = 0; i < kRecordLimit + 4; ++i) bx_breakpoint_site();
RemoveVectoredExceptionHandler(handler);
check(g_resumed == kRecordLimit + 6, "every exception reached the guest's own handler");
check(g_filter_calls == 0, "no exception went unhandled");
const uintptr_t base = reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
const uintptr_t site = reinterpret_cast<uintptr_t>(&bx_breakpoint_site);
char rva[64];
std::snprintf(rva, sizeof(rva), "\"rva\":\"0x%016llx\"",
static_cast<unsigned long long>(site - base));
const std::string log = read_log_from(mark);
const int records = count_lines_with(log, "\"event\":\"breakpoint_exception\"");
check(records == kRecordLimit, "records stop at the per-process limit of 16");
check(count_lines_with(log, "\"exception_code\":\"0x80000003\"", rva) == kRecordLimit - 1,
"each recorded int3 names the labelled site's RVA");
check(count_lines_with(log, "\"exception_code\":\"0xc0000420\"") == 1,
"the assertion failure is recorded");
// RaiseException reports an address inside kernelbase, so only the int3 records name this
// module.
check(count_lines_with(log, "\"module\":\"test_veh_breakpoint.exe\"") == kRecordLimit - 1,
"int3 records name this module");
check(count_lines_with(log, "\"event\":\"unhandled_exception\"") == 0,
"nothing was reported as unhandled");
if (g_failures) return 1;
std::printf("PASS: test_veh_breakpoint (%d records, cap %d)\n", records, kRecordLimit);
return 0;
}
@@ -0,0 +1,6 @@
add_executable(test_veh_diagnostics main.cpp)
target_include_directories(test_veh_diagnostics PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_link_libraries(test_veh_diagnostics PRIVATE bx_runtime_veh kernel32)
# A fixed image base: the parent passes its own code address to the child's BX_VEH_HIT, which is
# armed before the child's main runs.
target_link_options(test_veh_diagnostics PRIVATE -Wl,--disable-dynamicbase)
@@ -0,0 +1,389 @@
// Conformance test for bx_runtime_veh.dll's opt-in diagnostics (BX_VEH_AV_CONTEXT, BX_VEH_AV_ALL,
// BX_VEH_WATCH, BX_VEH_HIT, BX_VEH_SAMPLE).
//
// The switches are read when runtime_veh attaches, before main, so the parent starts this same
// executable as a child once per mode with that mode's environment, then reads the shared JSONL
// log (BX_LOG_FILE) for the records the child produced. Expected values come from what each child
// does, not from runtime_veh. Every record must be valid JSON and valid UTF-8.
//
// Run under `bx-cli run --log`. Exit 0: all checks passed. Exit 1: a check failed. Exit 77: the
// host cannot run a mode (logged as SKIP).
#include <windows.h>
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <string>
#include <vector>
extern "C" __declspec(dllimport) uint64_t bx_veh_get_clwb_trap_count(void);
// A store whose length the child's handler knows (mov [rcx], rdx = 48 89 11), used to make a
// write fault the child can step over.
extern "C" void store_qword(volatile uint64_t* at, uint64_t value);
asm(".globl store_qword\n"
"store_qword:\n"
" movq %rdx, (%rcx)\n"
" ret\n");
// The code-breakpoint target. Not inlined, so the child calls the address the parent passes.
extern "C" __attribute__((noinline)) int hit_target(const char* text) {
volatile int sum = 0;
for (const char* c = text; *c; ++c) sum += *c;
return sum;
}
namespace {
int g_failures = 0;
int g_checks = 0;
void check(bool ok, const char* what) {
++g_checks;
if (!ok) {
++g_failures;
std::printf("FAIL: test_veh_diagnostics: %s\n", what);
}
}
constexpr uintptr_t kWatchBase = 0x7A0000000ull; // the child's watched allocation
// --- Child side --------------------------------------------------------------------------------
volatile LONG g_child_avs = 0;
LONG CALLBACK child_handler(PEXCEPTION_POINTERS ep) {
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) return EXCEPTION_CONTINUE_SEARCH;
InterlockedIncrement(&g_child_avs);
// A real fault in store_qword: step over its 3-byte store.
if (reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress) == reinterpret_cast<uintptr_t>(&store_qword)) {
ep->ContextRecord->Rip += 3;
}
return EXCEPTION_CONTINUE_EXECUTION; // a raised (continuable) one resumes after RaiseException
}
void raise_av() {
const ULONG_PTR info[2] = {1, 0x1234};
RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 2, info);
}
DWORD WINAPI raise_many(LPVOID) {
for (int i = 0; i < 8; ++i) raise_av();
return 0;
}
int child(const char* mode, const char* arg) {
(void)bx_veh_get_clwb_trap_count(); // keeps the runtime_veh import
AddVectoredExceptionHandler(0, child_handler); // after runtime_veh's own handler
if (!std::strcmp(mode, "off")) {
for (int i = 0; i < 4; ++i) raise_av();
return g_child_avs == 4 ? 0 : 2;
}
if (!std::strcmp(mode, "av")) {
HANDLE threads[4];
for (auto& t : threads) t = CreateThread(nullptr, 0, raise_many, nullptr, 0, nullptr);
WaitForMultipleObjects(4, threads, TRUE, 10000);
for (auto t : threads) CloseHandle(t);
return g_child_avs == 32 ? 0 : 2;
}
if (!std::strcmp(mode, "watch")) {
auto* base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(kWatchBase), 0x10000,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
if (base != reinterpret_cast<uint8_t*>(kWatchBase)) return 77;
// The helper thread protects the page once it is committed.
MEMORY_BASIC_INFORMATION mbi{};
for (int i = 0; i < 2000; ++i) {
if (VirtualQuery(base, &mbi, sizeof(mbi)) && mbi.Protect == PAGE_READONLY) break;
Sleep(1);
}
if (mbi.Protect != PAGE_READONLY) return 3;
*reinterpret_cast<volatile uint64_t*>(base + 0x10) = 0x1122334455667788ull; // watched: logged
*reinterpret_cast<volatile uint64_t*>(base + 0x200) = 7; // same page, not watched
if (*reinterpret_cast<volatile uint64_t*>(base + 0x10) != 0x1122334455667788ull) return 4;
// Decommit the watched page: the next write faults, and runtime_veh cannot unprotect the
// page, so it must disarm and pass the fault on (to child_handler) rather than loop.
if (!VirtualFree(base, 0x1000, MEM_DECOMMIT)) return 5;
const LONG before = g_child_avs;
store_qword(reinterpret_cast<volatile uint64_t*>(base + 0x10), 9);
return g_child_avs == before + 1 ? 0 : 6;
}
if (!std::strcmp(mode, "hit")) {
const uintptr_t expected = static_cast<uintptr_t>(std::strtoull(arg, nullptr, 16));
if (expected != reinterpret_cast<uintptr_t>(&hit_target)) return 77; // image relocated
hit_target("quote\" back\\ path");
hit_target("second call");
return 0;
}
if (!std::strcmp(mode, "sample")) {
const DWORD until = GetTickCount() + 300;
volatile uint64_t spin = 0;
while (GetTickCount() < until) spin = spin + 1;
return spin ? 0 : 2;
}
return 2;
}
// --- Parent side -------------------------------------------------------------------------------
std::wstring widen(const char* s) {
std::wstring out;
while (*s) out.push_back(static_cast<wchar_t>(static_cast<unsigned char>(*s++)));
return out;
}
std::string read_log_from(const char* path, uint64_t offset) {
std::string text;
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
if (f == INVALID_HANDLE_VALUE) return text;
LARGE_INTEGER at;
at.QuadPart = static_cast<LONGLONG>(offset);
SetFilePointerEx(f, at, nullptr, FILE_BEGIN);
char buf[65536];
DWORD got = 0;
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got) text.append(buf, got);
CloseHandle(f);
return text;
}
uint64_t file_size(const char* path) {
WIN32_FILE_ATTRIBUTE_DATA data{};
if (!GetFileAttributesExA(path, GetFileExInfoStandard, &data)) return 0;
return (static_cast<uint64_t>(data.nFileSizeHigh) << 32) | data.nFileSizeLow;
}
// A JSONL record: one object whose strings use only JSON escapes and no raw control characters,
// in valid UTF-8.
bool valid_record(const std::string& line) {
if (line.size() < 2 || line.front() != '{' || line.back() != '}') return false;
bool in_string = false;
for (size_t i = 0; i < line.size(); ++i) {
const unsigned char c = static_cast<unsigned char>(line[i]);
if (c >= 0x80) { // UTF-8 sequence
const int extra = (c & 0xE0) == 0xC0 ? 1 : (c & 0xF0) == 0xE0 ? 2 : (c & 0xF8) == 0xF0 ? 3 : -1;
if (extra < 0 || i + extra >= line.size()) return false;
for (int k = 1; k <= extra; ++k) {
if ((static_cast<unsigned char>(line[i + k]) & 0xC0) != 0x80) return false;
}
i += extra;
continue;
}
if (!in_string) {
if (c == '"') in_string = true;
continue;
}
if (c < 0x20) return false;
if (c == '"') {
in_string = false;
} else if (c == '\\') {
if (i + 1 >= line.size()) return false;
const char e = line[++i];
if (e == 'u') {
if (i + 4 >= line.size()) return false;
for (int k = 1; k <= 4; ++k) {
if (!std::isxdigit(static_cast<unsigned char>(line[i + k]))) return false;
}
i += 4;
} else if (!std::strchr("\"\\/bfnrt", e)) {
return false;
}
}
}
return !in_string;
}
std::vector<std::string> records(const std::string& text, const char* event) {
std::vector<std::string> out;
const std::string needle = std::string("\"event\":\"") + event + "\"";
size_t start = 0;
while (start < text.size()) {
size_t end = text.find('\n', start);
if (end == std::string::npos) end = text.size();
std::string line = text.substr(start, end - start);
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.find(needle) != std::string::npos) out.push_back(line);
start = end + 1;
}
return out;
}
struct ChildRun {
DWORD exit_code = 0xFFFFFFFF;
std::string log;
};
// Starts `exe` as a child in `mode` with the extra environment variables, waits for it, and
// returns its exit code and the log lines it appended.
ChildRun run_child(const std::wstring& exe, const char* mode, const char* arg,
const std::vector<std::wstring>& extra_env, const char* log_path) {
ChildRun run;
std::wstring block;
if (wchar_t* env = GetEnvironmentStringsW()) {
for (const wchar_t* p = env; *p; p += std::wcslen(p) + 1) {
std::wstring entry(p);
if (entry.rfind(L"BX_VEH_", 0) == 0) continue; // only this mode's switches
block += entry;
block.push_back(L'\0');
}
FreeEnvironmentStringsW(env);
}
for (const auto& e : extra_env) {
block += e;
block.push_back(L'\0');
}
block.push_back(L'\0');
std::wstring cmd = L"\"" + exe + L"\" child " + widen(mode) + L" " + widen(arg);
STARTUPINFOW si{};
si.cb = sizeof(si);
PROCESS_INFORMATION pi{};
const uint64_t before = file_size(log_path);
if (!CreateProcessW(exe.c_str(), cmd.data(), nullptr, nullptr, FALSE, CREATE_UNICODE_ENVIRONMENT, block.data(),
nullptr, &si, &pi)) {
return run;
}
if (WaitForSingleObject(pi.hProcess, 60000) == WAIT_OBJECT_0) GetExitCodeProcess(pi.hProcess, &run.exit_code);
else TerminateProcess(pi.hProcess, 9);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
run.log = read_log_from(log_path, before);
return run;
}
bool all_valid(const std::vector<std::string>& lines) {
for (const auto& l : lines) {
if (!valid_record(l)) {
std::printf(" invalid record: %.200s\n", l.c_str());
return false;
}
}
return true;
}
int parent(const char* log_path) {
wchar_t self[MAX_PATH];
GetModuleFileNameW(nullptr, self, MAX_PATH);
const std::wstring exe(self);
int skipped = 0;
// Off: synthetic access violations produce no av_context record.
{
ChildRun r = run_child(exe, "off", "-", {}, log_path);
check(r.exit_code == 0, "off: child handled its access violations (exit 0)");
check(records(r.log, "av_context").empty(), "off: no av_context record without BX_VEH_AV_CONTEXT");
}
// AV context from four threads at once, with a spec containing a quote, a backslash and a
// control character and far too long for one line: 16 records (the cap), each valid JSON.
std::wstring spec = L"BX_VEH_AV_CONTEXT=zz\"q\\b\x01,";
for (int i = 0; i < 80; ++i) spec += L"*10+8,";
{
ChildRun r = run_child(exe, "av", "-", {spec, L"BX_VEH_AV_ALL=1"}, log_path);
const auto lines = records(r.log, "av_context");
check(r.exit_code == 0, "av: every access violation reached the child (exit 0)");
check(lines.size() == 16, "av: 16 av_context records from 32 faults (the cap)");
check(all_valid(lines), "av: every av_context record is valid JSON");
bool escaped = false;
for (const auto& l : lines) escaped = escaped || l.find("zz\\\"q\\\\b\\u0001") != std::string::npos;
check(escaped, "av: the spec token is JSON-escaped");
bool stack = true;
for (const auto& l : lines) stack = stack && l.find("| stack:") != std::string::npos;
check(stack, "av: a truncated spec still leaves room for the stack");
}
// A non-ASCII module name in the stack must stay valid UTF-8.
{
std::wstring dir = exe.substr(0, exe.find_last_of(L'\\') + 1);
const std::wstring copy = dir + L"veh_ünïcode.exe";
if (CopyFileW(exe.c_str(), copy.c_str(), FALSE)) {
ChildRun r = run_child(copy, "av", "-", {L"BX_VEH_AV_CONTEXT=1", L"BX_VEH_AV_ALL=1"}, log_path);
const auto lines = records(r.log, "av_context");
check(r.exit_code == 0 && !lines.empty(), "unicode: the renamed child logged av_context");
check(all_valid(lines), "unicode: records with a non-ASCII module name are valid JSON and UTF-8");
bool named = false;
for (const auto& l : lines) named = named || l.find("veh_\xc3\xbc" "n\xc3\xaf" "code") != std::string::npos;
check(named, "unicode: the module name is written in UTF-8");
DeleteFileW(copy.c_str());
} else {
std::printf("SKIP: unicode mode: could not copy the executable\n");
++skipped;
}
}
// Write watch: one logged write, a write outside the range not logged, and a protection
// failure that disarms the watch and lets the fault reach the guest.
{
wchar_t watch[64];
std::swprintf(watch, 64, L"BX_VEH_WATCH=%llx:8", static_cast<unsigned long long>(kWatchBase + 0x10));
ChildRun r = run_child(exe, "watch", "-", {watch}, log_path);
if (r.exit_code == 77) {
std::printf("SKIP: watch mode: the fixed test address is not free in this process\n");
++skipped;
} else {
const auto writes = records(r.log, "watched_write");
const auto disarmed = records(r.log, "diagnostic_disarmed");
check(r.exit_code == 0, "watch: the write to the decommitted page reached the child (exit 0)");
check(writes.size() == 1 && writes[0].find("address=7a0000010") != std::string::npos &&
writes[0].find("value_after=1122334455667788") != std::string::npos,
"watch: exactly the watched write is logged, with its value");
check(disarmed.size() == 1 && disarmed[0].find("watch: could not unprotect") != std::string::npos,
"watch: a failed protection change disarms the watch and is logged");
check(all_valid(writes) && all_valid(disarmed), "watch: records are valid JSON");
}
}
// Code breakpoint: two calls, two hits (the breakpoint is re-armed), the string argument safe.
{
char address[32];
std::snprintf(address, sizeof(address), "%llx", static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(&hit_target)));
std::wstring hit = L"BX_VEH_HIT=" + widen(address);
ChildRun r = run_child(exe, "hit", address, {hit}, log_path);
if (r.exit_code == 77) {
std::printf("SKIP: hit mode: the child's image was relocated\n");
++skipped;
} else {
const auto hits = records(r.log, "code_hit");
check(r.exit_code == 0, "hit: the child ran through both breakpoint hits (exit 0)");
check(hits.size() == 2, "hit: both calls are logged (the breakpoint is re-armed)");
check(all_valid(hits), "hit: code_hit records are valid JSON");
bool text = false;
for (const auto& l : hits) text = text || l.find("[rcx]s=quote_ back_ path") != std::string::npos;
check(text, "hit: a string argument is logged with quote and backslash made safe");
}
}
// Sampler: records while the child runs, valid JSON, and a clean exit.
{
ChildRun r = run_child(exe, "sample", "-", {L"BX_VEH_SAMPLE=5"}, log_path);
const auto samples = records(r.log, "sample");
check(r.exit_code == 0, "sample: the child exits normally with the sampler running");
check(!samples.empty(), "sample: sample records are written");
check(all_valid(samples), "sample: sample records are valid JSON");
}
if (g_failures) {
std::printf("FAIL: test_veh_diagnostics (%d of %d checks failed)\n", g_failures, g_checks);
return 1;
}
if (skipped) {
std::printf("SKIP: test_veh_diagnostics: %d mode(s) could not run on this host (%d checks passed)\n", skipped, g_checks);
return 77;
}
std::printf("PASS: test_veh_diagnostics (%d checks: off, AV context, UTF-8 module names, write watch, code hit, sampler)\n",
g_checks);
return 0;
}
} // namespace
int main(int argc, char** argv) {
if (argc >= 4 && !std::strcmp(argv[1], "child")) return child(argv[2], argv[3]);
char log_path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
if (n == 0 || n >= sizeof(log_path)) {
std::printf("FAIL: test_veh_diagnostics: BX_LOG_FILE must be set (run under bx-cli run --log)\n");
return 1;
}
return parent(log_path);
}