mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 04:59:52 +00:00
Compare commits
337
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2713c9e049 | ||
|
|
bd13b17f30 | ||
|
|
5b99b6bd63 | ||
|
|
b23e6fd6e5 | ||
|
|
d2ca4c3995 | ||
|
|
59b6c4db5e | ||
|
|
ca2fe15d3e | ||
|
|
8fbef1e31f | ||
|
|
6fd254825d | ||
|
|
db3bdb5a5c | ||
|
|
9b20f78a06 | ||
|
|
77cec214c0 | ||
|
|
953254a435 | ||
|
|
39b628d60d | ||
|
|
1d70633958 | ||
|
|
a9f55b51f7 | ||
|
|
722388a46d | ||
|
|
e7ff293eba | ||
|
|
dfaaa07df4 | ||
|
|
962b83c731 | ||
|
|
7fff77c801 | ||
|
|
c3684a1ae8 | ||
|
|
d561595599 | ||
|
|
8cab0b1de8 | ||
|
|
d2367dca30 | ||
|
|
60ad6c779e | ||
|
|
ffc7056d26 | ||
|
|
9923e59114 | ||
|
|
feba95fe39 | ||
|
|
a275de6e2e | ||
|
|
25986845da | ||
|
|
df9652740b | ||
|
|
1ca491d8d0 | ||
|
|
964a8296f2 | ||
|
|
d8a8c96408 | ||
|
|
50321b3f14 | ||
|
|
1fe07f45ee | ||
|
|
d486d21813 | ||
|
|
4c92c88b29 | ||
|
|
478e9218ac | ||
|
|
8d2662dcd7 | ||
|
|
fe1bf568c8 | ||
|
|
873652d685 | ||
|
|
84f561b12b | ||
|
|
2b113a2e5e | ||
|
|
9a26e1ee36 | ||
|
|
c84b80b24f | ||
|
|
ae804f0530 | ||
|
|
64e7b16983 | ||
|
|
1ea898b4bf | ||
|
|
7946968cc4 | ||
|
|
67b8cff9df | ||
|
|
51c23a2f38 | ||
|
|
7d97e67448 | ||
|
|
d9261db887 | ||
|
|
5c0c82b3f9 | ||
|
|
b71db3c25a | ||
|
|
566f803111 | ||
|
|
857c16fcf7 | ||
|
|
4f5c6913f5 | ||
|
|
e4ddb05a1a | ||
|
|
d33a7c6941 | ||
|
|
4e838207fe | ||
|
|
b40bbae1da | ||
|
|
b04b41f26a | ||
|
|
3dd3ef06e2 | ||
|
|
b2654e93a4 | ||
|
|
fee956293d | ||
|
|
146d2dd467 | ||
|
|
a0d9b85dbf | ||
|
|
5366b93986 | ||
|
|
50c392111d | ||
|
|
f43a07ce31 | ||
|
|
10fd1cd4be | ||
|
|
95aa10c60f | ||
|
|
873b4fd4a9 | ||
|
|
120878de2d | ||
|
|
d26af53cef | ||
|
|
b6ebaaad5e | ||
|
|
aba82cdb77 | ||
|
|
44ac976291 | ||
|
|
d71efe0495 | ||
|
|
0bd8e19aac | ||
|
|
a1744a2754 | ||
|
|
e93509ef5b | ||
|
|
8344e299c9 | ||
|
|
433dc43695 | ||
|
|
c18f9ffa7f | ||
|
|
a0f2d833aa | ||
|
|
61afca42c9 | ||
|
|
be19e4e28f | ||
|
|
33ccf7fd55 | ||
|
|
bb62353cfe | ||
|
|
1f2e7d3bb6 | ||
|
|
b5b646a58d | ||
|
|
acb3839351 | ||
|
|
f9d5838091 | ||
|
|
4314071ac7 | ||
|
|
4173a781af | ||
|
|
4e15e5f43b | ||
|
|
cf4010ba94 | ||
|
|
b9e6a9d365 | ||
|
|
a1a1020ebd | ||
|
|
e755ee94ed | ||
|
|
2f68ee9d4a | ||
|
|
e7a2159c82 | ||
|
|
98e9420b7f | ||
|
|
238b5a001b | ||
|
|
e289318132 | ||
|
|
99ed89787e | ||
|
|
522560d0a2 | ||
|
|
f685b54e32 | ||
|
|
0690a3ecb4 | ||
|
|
7286989296 | ||
|
|
d28d539a90 | ||
|
|
8c4b2344df | ||
|
|
a75d018435 | ||
|
|
4652eb08cb | ||
|
|
d1bcd0249d | ||
|
|
097bb0b5b8 | ||
|
|
2d77b35e56 | ||
|
|
19f63a0985 | ||
|
|
45322af82e | ||
|
|
aa9a961ef4 | ||
|
|
10347dc21b | ||
|
|
4d530392d1 | ||
|
|
f02eb2678e | ||
|
|
19a905c30e | ||
|
|
bfe0bbfaf7 | ||
|
|
5442503d57 | ||
|
|
f0c61c7a91 | ||
|
|
0caca18634 | ||
|
|
81a32e3ec6 | ||
|
|
8edf3abf53 | ||
|
|
0c397c5957 | ||
|
|
417b19c859 | ||
|
|
4cc703d566 | ||
|
|
5ae43a3cb8 | ||
|
|
ab73969135 | ||
|
|
8ee0304237 | ||
|
|
42cdb7d122 | ||
|
|
2ea75603be | ||
|
|
6fc06dccff | ||
|
|
a1295d5a48 | ||
|
|
0a17f0cb73 | ||
|
|
20d7b9ece4 | ||
|
|
db80c0b3e3 | ||
|
|
db46390fa9 | ||
|
|
a9abc36eef | ||
|
|
972bc0a35c | ||
|
|
c0e90338d1 | ||
|
|
e32c85ff12 | ||
|
|
d409c26458 | ||
|
|
e57386950b | ||
|
|
1fafc2e43f | ||
|
|
0aeb2b69a9 | ||
|
|
1342878c49 | ||
|
|
d6c9f846f0 | ||
|
|
34e99b3745 | ||
|
|
d5fa319f56 | ||
|
|
e5d83e87ac | ||
|
|
985d3b9e78 | ||
|
|
0929d0214b | ||
|
|
43f8287c92 | ||
|
|
a91c7fa39d | ||
|
|
22425287e2 | ||
|
|
874c7c7a63 | ||
|
|
f30e4af4eb | ||
|
|
501117c4d8 | ||
|
|
3d796f51cf | ||
|
|
66f7127553 | ||
|
|
714eaf49e2 | ||
|
|
c93b505223 | ||
|
|
d8f7f2cb13 | ||
|
|
042c08c855 | ||
|
|
7e4ccd1e97 | ||
|
|
96c772edc5 | ||
|
|
0236ec6ba9 | ||
|
|
48d22f533b | ||
|
|
52e7e3808d | ||
|
|
464393e02a | ||
|
|
aae04a2956 | ||
|
|
721073169c | ||
|
|
26148f49f6 | ||
|
|
e81382de37 | ||
|
|
496938aef4 | ||
|
|
9d94c0f40a | ||
|
|
4e18000798 | ||
|
|
8c188b04c9 | ||
|
|
9eb75522f0 | ||
|
|
3f41f7406b | ||
|
|
1c8d7a40de | ||
|
|
afe8d16d9e | ||
|
|
67023d292b | ||
|
|
d326e929a9 | ||
|
|
324eab08c3 | ||
|
|
149869a053 | ||
|
|
a6b0e89cac | ||
|
|
32251af4c8 | ||
|
|
1c6bd25723 | ||
|
|
007ad360e9 | ||
|
|
0d6cef6c4e | ||
|
|
64a0cb1596 | ||
|
|
53e5e38a4e | ||
|
|
47a819e05b | ||
|
|
7d28fc89de | ||
|
|
9a29bd9c37 | ||
|
|
38359969cd | ||
|
|
652c6ae02f | ||
|
|
0529c62226 | ||
|
|
e6fa931264 | ||
|
|
3b47c21bb0 | ||
|
|
9a62d86a89 | ||
|
|
4b32c532fe | ||
|
|
af1b84ad75 | ||
|
|
cf438e25aa | ||
|
|
bd46504a97 | ||
|
|
cc4dd092cf | ||
|
|
04ee981103 | ||
|
|
bbc84c0da0 | ||
|
|
d2f77cdea3 | ||
|
|
3a36379db4 | ||
|
|
147e2a9f1a | ||
|
|
a7fa8b0d65 | ||
|
|
fd0e73bc28 | ||
|
|
35de41bd5f | ||
|
|
e6b657a2e9 | ||
|
|
c05e631c6d | ||
|
|
6bac25f099 | ||
|
|
d35c278284 | ||
|
|
34a583b101 | ||
|
|
061c28b405 | ||
|
|
3b52215a30 | ||
|
|
0214a7bab5 | ||
|
|
fbec436b89 | ||
|
|
47b526fba9 | ||
|
|
c68e3ccb4c | ||
|
|
e856f080d1 | ||
|
|
fb6282ceb2 | ||
|
|
bb6a9f6912 | ||
|
|
a7e3e1e42c | ||
|
|
9c76bf16f0 | ||
|
|
2f28a5adbb | ||
|
|
788de1e83b | ||
|
|
7dd1329866 | ||
|
|
4b579af70d | ||
|
|
b4f45573cf | ||
|
|
0766307acc | ||
|
|
9dfdfd1134 | ||
|
|
ce8d16e367 | ||
|
|
8df13ae976 | ||
|
|
36c4fbd520 | ||
|
|
3c8b6bad97 | ||
|
|
d4c29cd7dd | ||
|
|
7246ab5ea6 | ||
|
|
938cbd3028 | ||
|
|
c9505e53e2 | ||
|
|
02eb8046a1 | ||
|
|
4a0b5d4ded | ||
|
|
00eb6971e9 | ||
|
|
c3b0025977 | ||
|
|
1013746e17 | ||
|
|
7c88e5d655 | ||
|
|
bb318ed2ba | ||
|
|
b1b57cf16a | ||
|
|
cdcc55c33e | ||
|
|
0730f4dbbf | ||
|
|
6f27da3ccc | ||
|
|
6236996f41 | ||
|
|
05f2526d27 | ||
|
|
e5aca73c55 | ||
|
|
281d92bfb5 | ||
|
|
5131de9cd6 | ||
|
|
fec13fa27a | ||
|
|
68503a674c | ||
|
|
82cb66e80f | ||
|
|
06dbe2946d | ||
|
|
685217e61b | ||
|
|
a0d4b7bf5d | ||
|
|
14d5083f0f | ||
|
|
0115af5c04 | ||
|
|
9ddb708cdf | ||
|
|
5b7ffec90a | ||
|
|
48c5d20aa9 | ||
|
|
8049c36f51 | ||
|
|
94783fa603 | ||
|
|
c91036f879 | ||
|
|
c1cea65e17 | ||
|
|
974d1fc62c | ||
|
|
6f1ac2a906 | ||
|
|
223a754eb7 | ||
|
|
3d19c756e2 | ||
|
|
729e1b4cb1 | ||
|
|
d195978903 | ||
|
|
830f93ff14 | ||
|
|
4962f054c8 | ||
|
|
67dfb18166 | ||
|
|
782c49167c | ||
|
|
6106c37912 | ||
|
|
d2491dee07 | ||
|
|
823a5812a0 | ||
|
|
c1ca4ea140 | ||
|
|
710a2e1e73 | ||
|
|
de92766b29 | ||
|
|
b09d96fd62 | ||
|
|
4d44765363 | ||
|
|
6de750b152 | ||
|
|
c95e175210 | ||
|
|
adf10db015 | ||
|
|
6814d78230 | ||
|
|
4e4a6b36be | ||
|
|
403a67747f | ||
|
|
509811aad0 | ||
|
|
dc3b02b62f | ||
|
|
d847d7ea6e | ||
|
|
b9372408c8 | ||
|
|
8b67479526 | ||
|
|
0fdb995892 | ||
|
|
b55a4c24ef | ||
|
|
1dcf722323 | ||
|
|
48e1e5c8c1 | ||
|
|
6947fe7ff6 | ||
|
|
94732d90ca | ||
|
|
1e8893a6bf | ||
|
|
d7f7d586d3 | ||
|
|
b8fbdf35b9 | ||
|
|
d01627b3de | ||
|
|
291c9807ee | ||
|
|
84866956b9 | ||
|
|
47cb26ebdd | ||
|
|
eaeab25590 | ||
|
|
8d19006c32 | ||
|
|
84221ac715 | ||
|
|
673e2a4556 | ||
|
|
b49d50e34e | ||
|
|
e0a6dae554 | ||
|
|
b3a6a57a8e |
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# Every change needs a review from the maintainers team.
|
||||
* @MacosPorters/maintainers
|
||||
@@ -7,8 +7,9 @@ body:
|
||||
id: area
|
||||
attributes:
|
||||
label: Area
|
||||
description: "cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review."
|
||||
description: "hybrid: CrossOver integration, configuration, diagnostics, benchmarks (active). The areas below are preserved native research unless hybrid work requires them. cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review."
|
||||
options:
|
||||
- hybrid
|
||||
- cpu
|
||||
- gpu
|
||||
- runtime
|
||||
@@ -43,7 +44,7 @@ body:
|
||||
id: files
|
||||
attributes:
|
||||
label: Files
|
||||
description: Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap.
|
||||
description: 'Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap.'
|
||||
render: text
|
||||
validations:
|
||||
required: true
|
||||
|
||||
@@ -1,42 +1,57 @@
|
||||
name: Bug report
|
||||
description: Report a reproducible defect in Xenora or XenoMetal.
|
||||
description: A reproducible defect.
|
||||
title: "bug: "
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Use synthetic or authorized inputs only. For vulnerabilities, follow SECURITY.md. Remove personal paths, credentials and private data from logs.
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. For vulnerabilities follow SECURITY.md.'
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Description
|
||||
description: What went wrong? Identify the affected subsystem and expected behavior.
|
||||
description: 'What went wrong and what you expected.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: Reproduction steps
|
||||
description: Include exact commands and a minimal, legally distributable input if applicable.
|
||||
description: 'Exact commands and a minimal, legally distributable input.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: Environment
|
||||
description: Commit, macOS, Apple GPU, RAM, Rust, Xcode and relevant tool versions. Include sanitized doctor output if available.
|
||||
description: 'Commit, macOS, chip, memory, CrossOver and Rosetta 2 versions, graphics backend. Remove personal paths and credentials.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: output
|
||||
id: scope
|
||||
attributes:
|
||||
label: Actual output and diagnostics
|
||||
description: Include expected versus actual results, validation-layer messages and relevant logs.
|
||||
- type: checkboxes
|
||||
id: confirmation
|
||||
label: Scope and dependencies
|
||||
description: 'Affected area; related issues.'
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Confirmation
|
||||
options:
|
||||
- label: I searched for existing reports and have not included sensitive or unauthorized material.
|
||||
required: true
|
||||
label: Acceptance criteria
|
||||
description: 'When is this fixed?'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'How to confirm the fix independently.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: 'Only if third-party code or a dependency is involved.'
|
||||
validations:
|
||||
required: false
|
||||
@@ -0,0 +1,50 @@
|
||||
name: Documentation
|
||||
description: Fix, add or restructure documentation.
|
||||
title: "docs: "
|
||||
labels: [documentation]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem
|
||||
description: 'What is unclear, wrong or missing.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Technical context
|
||||
description: 'Pages and sources involved.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Scope
|
||||
description: 'Files to change; update docs/README.md if pages are added or moved.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: 'None if none.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Claims are scoped to their evidence; links work.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'scripts/audit/docs_hygiene.py and claims audit pass.'
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,31 +0,0 @@
|
||||
name: Feature proposal
|
||||
description: Propose a compiler, graphics, tooling or other project enhancement.
|
||||
title: "feat: "
|
||||
labels: [enhancement]
|
||||
body:
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem or gap
|
||||
description: Which limitation does this feature address?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: Proposed approach
|
||||
description: Explain the intended behavior and affected components. Link relevant public specifications when available.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: criteria
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: What observable results and tests would demonstrate completion?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives and trade-offs
|
||||
description: Include limitations, dependency costs or impacts on native ARM64 and Metal if relevant.
|
||||
@@ -1,31 +0,0 @@
|
||||
name: Hardware verification report
|
||||
description: Submit real hardware test results for Xenora.
|
||||
title: "hardware: "
|
||||
labels: [needs-verification]
|
||||
body:
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: Test environment
|
||||
description: Commit, Apple chip/GPU, RAM, macOS, Xcode/Metal version, Rust version, validation settings. Do not include serial numbers or registry IDs.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: commands
|
||||
attributes:
|
||||
label: Commands and inputs
|
||||
description: Include exact commands and synthetic or authorized fixture identifiers.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: results
|
||||
attributes:
|
||||
label: Results
|
||||
description: Report actual output, pass/fail/skip counts, and limitations. Compilation alone does not prove execution.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: performance
|
||||
attributes:
|
||||
label: Performance data (optional)
|
||||
description: Include repetitions, warm-up, timing method, validation state and variability if reporting measurements.
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Hybrid engineering task
|
||||
description: Integration, configuration, diagnostics or tooling around CrossOver.
|
||||
title: "task: "
|
||||
labels: [track: hybrid]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem
|
||||
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Technical context
|
||||
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Scope
|
||||
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: "Blocking issues or decisions; write 'none' if none."
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Observable, checkable results.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Performance investigation
|
||||
description: Measure or improve performance with evidence.
|
||||
title: "perf: "
|
||||
labels: [performance,track: hybrid]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. Do not promise gains before measuring.'
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem and metric
|
||||
description: 'Which metric (average FPS, 1% low, frame-time percentiles, CPU or GPU use, memory, startup, shader compile latency) and why.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Technical context
|
||||
description: 'Workload, hardware (reference: M4, 24 GB), software versions, settings.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Scope
|
||||
description: 'Measurement only, or change as well.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: 'Measurement protocol (#353) and baseline (#355).'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Measured before-and-after under equivalent conditions, with variance.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'Correctness and rendering equivalence verified before the result counts.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,42 +1,57 @@
|
||||
name: Technical research
|
||||
description: Record an ISA, Metal or publicly documented graphics research finding.
|
||||
name: Upstream research or dependency evaluation
|
||||
description: Assess a project, component or license from public sources.
|
||||
title: "research: "
|
||||
labels: [research]
|
||||
labels: [research,track: hybrid]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Use only public, authorized sources. Do not link to leaked SDKs, private documentation or unauthorized game content.
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
|
||||
- type: textarea
|
||||
id: question
|
||||
id: problem
|
||||
attributes:
|
||||
label: Research question or finding
|
||||
label: Question
|
||||
description: 'The decision this research informs.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: sources
|
||||
id: context
|
||||
attributes:
|
||||
label: Sources and applicability
|
||||
description: URLs, specification sections or revision, exact architecture and license/provenance if relevant.
|
||||
label: Technical context
|
||||
description: 'What is already known; link docs/research/upstream-registry.md entries.'
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: evidence
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Evidence class (highest applicable)
|
||||
options:
|
||||
- A - Measured on named hardware
|
||||
- B - Normative source for exact target
|
||||
- C - Normative source for related target
|
||||
- D - Non-normative official material
|
||||
- E - Independent software behavior
|
||||
- F - Uncorroborated community claim
|
||||
- U - Unknown or assumption
|
||||
label: Scope
|
||||
description: 'Which versions or components; desk research or execution.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: 'Other issues or decisions; execution may need a maintainer-approved environment.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Each claim cites vendor or upstream documentation, or a recorded observation of a stated version; unknowns stay marked unknown.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation, limitations and proposed next steps
|
||||
description: Distinguish Apple or desktop RDNA observations from Xbox behavior.
|
||||
label: Validation requirements
|
||||
description: 'Independent re-derivation and evidence class (A to U).'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Testing and validation
|
||||
description: Add or run a validation for a workload or behaviour.
|
||||
title: "validate: "
|
||||
labels: [needs-verification,track: hybrid]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem
|
||||
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Technical context
|
||||
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Scope
|
||||
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: "Blocking issues or decisions; write 'none' if none."
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Observable, checkable results.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,40 +0,0 @@
|
||||
## Summary
|
||||
|
||||
<!-- What changes, and why? -->
|
||||
|
||||
Closes #<!-- the issue you claimed -->
|
||||
|
||||
## Implementation and evidence
|
||||
|
||||
<!-- Describe affected subsystems, architecture assumptions, specification sections and upstream provenance where applicable. -->
|
||||
|
||||
## Verification
|
||||
|
||||
<!-- List actual commands and outcomes. Include hardware, validation-layer state and pass/fail/skip counts for GPU tests. Mark unrun checks explicitly. -->
|
||||
|
||||
| Check | Result / evidence |
|
||||
| --- | --- |
|
||||
| Formatting and lint | |
|
||||
| Unit / integration tests | |
|
||||
| GPU / differential tests | |
|
||||
| Fuzzing / mutation / benchmarks, if relevant | |
|
||||
|
||||
## Compatibility and limitations
|
||||
|
||||
<!-- Note unsupported behavior, regressions, interface changes, performance effects and remaining uncertainty. -->
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] I claimed the linked issue with a reply before starting, and nobody else held a live claim on it.
|
||||
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
|
||||
- [ ] The change preserves native ARM64 and Metal-first requirements.
|
||||
- [ ] I added relevant tests or explained why they are not applicable.
|
||||
- [ ] I did not report skipped or unrun tests as passing.
|
||||
- [ ] I updated applicable documentation, claims and status records.
|
||||
- [ ] Third-party code and fixtures have verified licenses and provenance, or none were added.
|
||||
- [ ] No restricted materials, credentials or private data are included.
|
||||
- [ ] My commits are signed off under the DCO.
|
||||
|
||||
## AI assistance
|
||||
|
||||
<!-- Describe material assistance and the checks you personally performed, or state none. -->
|
||||
@@ -1,9 +1,8 @@
|
||||
{
|
||||
"lease_hours": 168,
|
||||
"upstream": "ranveersoni98/Xenora",
|
||||
"maintainers": ["ranveersoni98"],
|
||||
"contributors": {
|
||||
"ranveersoni98": ["cpu", "shared", "qa"],
|
||||
"elforeign": ["gpu", "shared", "qa"]
|
||||
}
|
||||
"upstream": "MacosPorters/betterxen",
|
||||
"maintainers": [
|
||||
"Arths17"
|
||||
],
|
||||
"contributors": {}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
## Related issue
|
||||
|
||||
Closes #
|
||||
|
||||
## Summary
|
||||
|
||||
## Technical changes
|
||||
|
||||
## Tests performed
|
||||
|
||||
Commands, versions, pass/fail/skip counts and hardware. A skipped test is not a pass.
|
||||
|
||||
## Performance impact
|
||||
|
||||
Measured before and after under equivalent conditions, or "none expected" with reason.
|
||||
|
||||
## Compatibility impact
|
||||
|
||||
Workloads, macOS or CrossOver versions and hardware affected. Do not claim support that was not tested.
|
||||
|
||||
## Known limitations
|
||||
|
||||
## Third-party code attribution
|
||||
|
||||
Source repository, exact commit, license, modifications. "None" if none.
|
||||
|
||||
## Dependency and licensing considerations
|
||||
|
||||
New or changed dependencies, license compatibility with GPL-3.0-or-later, redistribution limits (proprietary components are never bundled). DCO: commits are signed off.
|
||||
@@ -1,102 +0,0 @@
|
||||
name: Agent PR checks
|
||||
|
||||
# Checks pull requests against the task queue: linked claimed task, file
|
||||
# ownership, overlap with other open pull requests, and independent
|
||||
# verification. Runs on the base branch only: pull request code is never checked
|
||||
# out or executed; changed files come from the API. Not yet run on GitHub.
|
||||
#
|
||||
# Advisory: problems are reported as a warning and in the run summary, but the
|
||||
# check does not fail until a live smoke test and the migration of existing
|
||||
# issues are done (docs/coordination/agent-tasks.md). Only a comment starting
|
||||
# with /verified starts the verify job; ordinary comments start nothing.
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
check:
|
||||
if: github.event_name == 'pull_request_target'
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
issues: read
|
||||
pull-requests: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check pull request
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
|
||||
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
|
||||
status=0
|
||||
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
|
||||
{
|
||||
echo '## Agent PR check'
|
||||
echo '```json'
|
||||
cat "$RUNNER_TEMP/result.json"
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
# 1 means problems were found: advisory for now. Anything else is a failure of the check itself.
|
||||
if [ "$status" -eq 1 ]; then
|
||||
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
|
||||
elif [ "$status" -ne 0 ]; then
|
||||
exit "$status"
|
||||
fi
|
||||
|
||||
verify:
|
||||
if: github.event_name == 'issue_comment' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/verified')
|
||||
runs-on: ubuntu-24.04-arm
|
||||
# issues: write posts the reply.
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: read
|
||||
concurrency:
|
||||
group: agent-verify-${{ github.event.issue.number }}
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Record verification and check again
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
|
||||
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
|
||||
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
|
||||
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
|
||||
# Check again only after an accepted verification of the current head: refused, stale,
|
||||
# malformed or unauthorized /verified comments get a reply and nothing else.
|
||||
if ! python3 -m agent_queue should-rerun --actions "$RUNNER_TEMP/actions.json"; then exit 0; fi
|
||||
# pull_request_target runs are recorded against the base branch, not the pull request
|
||||
# head, so the earlier check run cannot be found by head SHA. Evaluate the same check here.
|
||||
status=0
|
||||
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
|
||||
{
|
||||
echo '## Agent PR check after verification'
|
||||
echo '```json'
|
||||
cat "$RUNNER_TEMP/result.json"
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
if [ "$status" -eq 1 ]; then
|
||||
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
|
||||
elif [ "$status" -ne 0 ]; then
|
||||
exit "$status"
|
||||
fi
|
||||
@@ -35,12 +35,27 @@ jobs:
|
||||
run: |
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
|
||||
rustc -vV
|
||||
- name: Install the Gate A2 C toolchain
|
||||
# crates/loader/tests/gate_a2.rs builds a hosted C program from source
|
||||
# with mingw-w64 and fails, never skips, when the compiler is missing.
|
||||
env:
|
||||
HOMEBREW_NO_AUTO_UPDATE: 1
|
||||
HOMEBREW_NO_INSTALL_CLEANUP: 1
|
||||
run: |
|
||||
brew install mingw-w64
|
||||
compiler="$(brew --prefix mingw-w64)/bin/x86_64-w64-mingw32-gcc"
|
||||
file -bL "$compiler" | grep arm64
|
||||
lipo -archs "$compiler" | grep arm64
|
||||
otool -L "$compiler"
|
||||
"$compiler" --version | head -1
|
||||
- name: Check generated status and PE fixtures
|
||||
run: |
|
||||
python3 crates/isa/generate_rdna2_meta.py --check
|
||||
python3 crates/isa/generate_semantics.py --check
|
||||
python3 scripts/audit/semantic_coverage.py --check
|
||||
python3 scripts/audit/status.py --check
|
||||
# The generated status check must not depend on the host locale encoding.
|
||||
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 python3 scripts/audit/status.py --check
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
done
|
||||
@@ -48,8 +63,8 @@ jobs:
|
||||
run: |
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
|
||||
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
|
||||
- name: Test pull request template check
|
||||
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
|
||||
- name: Test native audit JSON decoding
|
||||
run: python3 -m unittest discover -s tests/audit
|
||||
- name: Test semantic registry generator and coverage report
|
||||
run: |
|
||||
python3 -m unittest discover -s tests/semantics_generator
|
||||
@@ -65,11 +80,41 @@ jobs:
|
||||
cargo test --locked --workspace
|
||||
cargo test --locked --manifest-path experiments/x1/Cargo.toml
|
||||
scripts/audit/dependencies.sh
|
||||
scripts/audit/claims.sh
|
||||
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 scripts/audit/claims.sh
|
||||
- name: Inspect native CLI
|
||||
run: |
|
||||
cargo build --locked -p xenora
|
||||
binary=target/aarch64-apple-darwin/debug/xenora
|
||||
cargo build --locked -p betterxen
|
||||
binary=target/aarch64-apple-darwin/debug/betterxen
|
||||
file "$binary"
|
||||
test "$(lipo -archs "$binary")" = arm64
|
||||
otool -L "$binary"
|
||||
|
||||
native-app:
|
||||
name: Native app build and smoke
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 20
|
||||
env:
|
||||
CARGO_BUILD_JOBS: 3
|
||||
RUSTUP_TOOLCHAIN: 1.100.0-aarch64-apple-darwin
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Verify runner architecture
|
||||
run: |
|
||||
uname -m
|
||||
test "$(uname -m)" = arm64
|
||||
test "$(sysctl -n sysctl.proc_translated)" = 0
|
||||
- name: Install native Rust
|
||||
run: |
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal
|
||||
rustc -vV
|
||||
- name: Show Swift and Xcode
|
||||
run: |
|
||||
xcodebuild -version
|
||||
swift --version
|
||||
# Builds the locked C ABI library and the Swift app together, checks the
|
||||
# executable is arm64-only and links only system libraries, and runs
|
||||
# `--smoke`. This is an app build and smoke result, not GPU verification.
|
||||
- name: Build BetterXen.app and run its smoke check
|
||||
run: scripts/build-app.sh
|
||||
@@ -0,0 +1,43 @@
|
||||
name: Repository hygiene
|
||||
|
||||
# Fast checks on tracked files that need no Rust toolchain and no network:
|
||||
# merge-conflict markers, broken relative Markdown links and invalid workflow
|
||||
# YAML (scripts/audit/docs_hygiene.py). A second, advisory step warns when
|
||||
# source or script changes arrive without a CHANGELOG.md update; it never fails.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: hygiene-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
hygiene:
|
||||
name: Repository hygiene
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
- name: Install PyYAML
|
||||
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
|
||||
- name: Check documentation and workflow files
|
||||
run: python3 scripts/audit/docs_hygiene.py --require-yaml
|
||||
- name: Remind about the changelog (advisory)
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: |
|
||||
changed="$(git diff --name-only "$BASE_SHA"...HEAD || true)"
|
||||
if printf '%s\n' "$changed" | grep -Eq '^(crates|scripts|shaders|fixtures)/' \
|
||||
&& ! printf '%s\n' "$changed" | grep -qx 'CHANGELOG.md'; then
|
||||
echo "::warning title=Changelog::Source or script files changed without a CHANGELOG.md update."
|
||||
fi
|
||||
@@ -1,38 +0,0 @@
|
||||
name: PR template
|
||||
|
||||
# Fails when a pull request description does not follow
|
||||
# .github/PULL_REQUEST_TEMPLATE.md: every section present and filled in, a
|
||||
# linked issue ("Closes #N" or "No linked issue: <reason>"), and the
|
||||
# claimed-first and DCO checkboxes ticked. Runs again whenever the description
|
||||
# is edited; comments never start it. Runs on the base branch: pull request
|
||||
# code is never checked out or executed, and the description is read as data.
|
||||
#
|
||||
# To make it blocking, mark the "PR template / description" check as required
|
||||
# in the branch protection rule for main.
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, edited, reopened, synchronize]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
description:
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check the description against the template
|
||||
run: |
|
||||
set -u
|
||||
status=0
|
||||
python3 scripts/pr_template_check.py --event "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/result.txt" || status=$?
|
||||
cat "$RUNNER_TEMP/result.txt"
|
||||
{ echo '## PR template'; cat "$RUNNER_TEMP/result.txt"; } >> "$GITHUB_STEP_SUMMARY"
|
||||
if [ "$status" -ne 0 ]; then
|
||||
echo "::error title=PR description does not follow the template::$(tail -n +2 "$RUNNER_TEMP/result.txt" | head -n -1 | tr '\n' ' ')"
|
||||
fi
|
||||
exit "$status"
|
||||
+3
-2
@@ -35,8 +35,9 @@
|
||||
|
||||
__pycache__/
|
||||
*.pyc
|
||||
/diagnostics/gta6-candidate-*/
|
||||
/diagnostics/gta6-check/
|
||||
/diagnostics/probe/
|
||||
/diagnostics/title-candidate-*/
|
||||
/diagnostics/title-check/
|
||||
|
||||
# Native application build output
|
||||
/app/.build/
|
||||
@@ -1,40 +1,60 @@
|
||||
# Xenora engineering rules
|
||||
# BetterXen engineering rules
|
||||
|
||||
### Native Apple Silicon
|
||||
These rules apply to every contributor and coding agent. They were rewritten on the `planning/hybrid-first-transition` branch when BetterXen moved from native-first to CrossOver-based hybrid development. `CLAUDE.md` is a symlink to this file. The decision is recorded in `docs/adr/0005-crossover-hybrid-direction.md`; the plan is `docs/roadmap.md`.
|
||||
|
||||
Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dependencies, Wine, CrossOver, Windows compatibility layers, OpenGL fallback rendering, or unnecessary graphics abstraction layers.
|
||||
### Direction
|
||||
|
||||
- SPIR-V is permitted as a compiler intermediate representation. It does not justify a Vulkan runtime.
|
||||
- All host executables and native dependencies must support ARM64. Verify with file, lipo -archs and otool -L.
|
||||
- Never run Intel binaries through Rosetta, even temporarily. Never add a dependency that requires Rosetta to build or run. If a dependency cannot run natively, find an alternative or document the limitation.
|
||||
- The guest architecture being decoded may be x86-64, but Xenora itself runs natively on ARM64.
|
||||
- BetterXen is hybrid-first Apple Silicon compatibility research. **CrossOver is the primary compatibility foundation and hybrid is the only active development direction.** CrossOver is an externally installed dependency unless its license explicitly permits another distribution model.
|
||||
- BetterXen's own work is the layer around it: integration, configuration, environment management, diagnostics, reproducible testing, benchmarking and measured optimization. Reuse established infrastructure before writing an independent replacement; write one only for a demonstrated limitation.
|
||||
- The independent native implementation (x86-64 decoder, ARM64 translator, runtime, gfx1030 shader compiler, Metal backend) is **preserved and paused**. Do not delete it, expand its roadmap, create speculative native issues or assign contributors to it by default. Native work is allowed only when hybrid development directly requires it, or after an explicit maintainer decision to resume (`docs/research/native-roadmap.md`). Keep its tests passing.
|
||||
- This is the intended architecture, not a verified Xbox compatibility stack. Do not assume CrossOver, Rosetta 2 or D3DMetal provide Xbox runtime compatibility; verify the actual capabilities and integration boundaries of the installed versions.
|
||||
|
||||
### Planning
|
||||
|
||||
- Planning is progressive. Only the current phase has a milestone and open issues; the roadmap outlines later phases provisionally and `Parked ideas` holds future items. Do not create speculative issues, trackers or milestones for distant phases; promote an idea when its prerequisites are met.
|
||||
- Every new issue states a specific problem, the evidence it is needed, a deliverable, upstream references, a reuse assessment, dependencies, acceptance criteria and a validation method. Do not create administrative issues to manage planning.
|
||||
- Do not open native-only issues. If hybrid work needs a native component, file a focused hybrid issue.
|
||||
|
||||
### Dependencies and reuse
|
||||
|
||||
- Wine-based compatibility infrastructure, CrossOver, Rosetta 2 where supported and technically appropriate, and D3DMetal (subject to its license terms) are permitted. DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX and similar projects may be evaluated and used where appropriate. Legitimate external dependencies and open-source implementations are encouraged.
|
||||
- Before integrating or copying anything: verify the exact license of the component (the file for copied source, not just the repository), check compatibility with GPL-3.0-or-later and with every other selected component, preserve copyright notices, record the source repository and exact commit or version, document modifications, and add the entry to `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved. Never remove upstream notices.
|
||||
- Do not bundle, modify or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Do not assume a proprietary component can be incorporated into GPL-licensed source. Distinguish open-source parts from proprietary parts in every assessment.
|
||||
- Do not bypass licensing or activation requirements of any dependency.
|
||||
- Provenance first: exclude anything derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds, including VIctory, its forks and similar efforts, are discovery references at documentation level; adopt nothing from them without a per-file provenance and license review recorded in the registry. Game-specific, asset-specific and decryption-related code is never adopted.
|
||||
|
||||
### Native Apple Silicon host
|
||||
|
||||
- BetterXen's own host executables, libraries and tools must support ARM64 natively; verify with file, lipo -archs and otool -L. Do not add x86-64 host executables that BetterXen itself builds or ships.
|
||||
- Rosetta 2 may be used where Apple supports it and CrossOver or another selected component relies on it for x86-64 guest code. Record versions and its support status; do not depend on it for BetterXen's own code.
|
||||
- Support M1 through M5 and future generations through runtime capability detection. Do not assume all Apple GPUs share capabilities.
|
||||
- Use aarch64-apple-darwin as the Rust target.
|
||||
- Use aarch64-apple-darwin as the Rust target. Metal is the host graphics API. Do not add graphics abstraction layers beyond what a selected component or a measured need justifies.
|
||||
- SPIR-V remains permitted as a compiler intermediate representation.
|
||||
|
||||
### Honesty and evidence
|
||||
|
||||
- Never report a test as passed unless it ran and passed. Never count a skipped test as GPU verification.
|
||||
- Never invent benchmark results, hardware compatibility, API names, instruction encodings, hardware capabilities or implementation status.
|
||||
- Never invent benchmark results, hardware compatibility, API names, instruction encodings, hardware capabilities, interface details, product capabilities or implementation status. Never promise a performance improvement before measuring it.
|
||||
- Never claim a clean build unless the commands actually succeeded.
|
||||
- Never present planned features as working. State clearly that game execution is not supported unless demonstrated.
|
||||
- Never replace GPU tests with mocks and then claim GPU support.
|
||||
- Unknown information is classified as unknown and becomes a documented research task.
|
||||
- Every hardware claim carries an evidence class (section 9). Never present a lower-class claim as if it were a higher-class one.
|
||||
- Never claim "verified on Xbox hardware". Xenora has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so.
|
||||
- Unknown information is classified as unknown and becomes a documented research task. Facts about CrossOver, Rosetta 2, D3DMetal and other upstreams must cite vendor or upstream documentation, or a recorded observation of a stated version.
|
||||
- Every hardware claim carries an evidence class (see docs/claims.toml). Never present a lower-class claim as if it were a higher-class one.
|
||||
- Never claim "verified on Xbox hardware". BetterXen has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so.
|
||||
- Do not hide errors behind fallbacks. Do not translate unsupported instructions into silent no-ops. Do not weaken or delete tests to make them pass. Do not change mutation counting, tolerances or gate definitions to improve a score.
|
||||
- A phase is complete only with the evidence its exit conditions name. Do not derive progress from commits, lines of code, closed issues or isolated passing fixtures.
|
||||
|
||||
### Independence of verification
|
||||
|
||||
- The agent that writes a component does not certify it. The two independent reviewers (section 5) re-derive expectations from primary sources and are not told the implementers' conclusions as ground truth.
|
||||
- The agent that writes a component does not certify it. Independent reviewers re-derive expectations from primary sources and are not told the implementers' conclusions as ground truth.
|
||||
- The same faulty code must never produce both the expected and the actual values in a test.
|
||||
|
||||
### Legal and clean-room
|
||||
|
||||
- Use only publicly accessible documentation and authorized materials. Never obtain or use leaked SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, or proprietary game binaries and shader collections. Do not attempt to bypass documentation access restrictions.
|
||||
- Use only publicly accessible documentation, publicly licensed software and authorized materials. All validation uses independently authored or authorized workloads. Never obtain or use leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds and shader collections. Do not attempt to bypass documentation access restrictions.
|
||||
- Contributors who have seen leaked or confidential Xbox materials must not contribute. State this in CONTRIBUTING.md and require a DCO sign-off (Signed-off-by) on contributions.
|
||||
- Include a plain statement in docs/legal.md: Xenora does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. Add a note that this is not legal advice and that contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
|
||||
- Before copying or adapting any upstream code: verify the exact license of that file (not just the repo), check GPL-3.0-or-later compatibility, preserve copyright notices, record source repository and exact commit, document modifications, include required attribution. Never remove upstream copyright notices. If licensing is uncertain, stop using that code until resolved.
|
||||
- Keep Xenora's emulator implementation original. Never copy, port, translate or adapt emulator source from Leonida, KyTx, AnyPS5 or similar projects.
|
||||
- docs/legal.md states: BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. This is not legal advice; contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
|
||||
- Keep BetterXen's own implementation original where it is original. Never copy, port, translate or adapt source from emulator projects built for leaked or unauthorized material (for example PE-Vulkan, KyTx, AnyPS5 and similar).
|
||||
- Validate the technical compatibility and safety of user-provided files. Do not ask for ownership receipts, accounts or acquisition provenance as part of file loading. Contributor provenance and licensing obligations still apply.
|
||||
- Never place restricted material in the repository or its Git history.
|
||||
- Do not push, publish, or change remote visibility without explicit user authorization. Prepare locally and report readiness.
|
||||
@@ -43,7 +63,7 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep
|
||||
|
||||
No AI slop (section 29).
|
||||
|
||||
Read docs/interfaces.md and docs/progress.md before implementation.
|
||||
Read docs/roadmap.md, docs/interfaces.md and docs/progress.md before implementation.
|
||||
|
||||
## Claiming work before you start
|
||||
|
||||
@@ -84,14 +104,14 @@ A coding agent claims in the name of the person it works for and follows the sam
|
||||
- Lint: `cargo clippy --workspace --all-targets -- -D warnings`
|
||||
- Test: `cargo test --workspace`
|
||||
- Verify the synthetic fixtures: `scripts/assemble-fixture.sh --check`
|
||||
- Run native GPU correctness: `scripts/test-gpu.sh`
|
||||
- Run native GPU correctness (preserved native research): `scripts/test-gpu.sh`
|
||||
- Run the three RDNA-to-Metal fixtures: `scripts/demo.sh`
|
||||
- Run independent CPU validation: `cargo test --locked -p xenora-semantic-review`
|
||||
- Run the correctness-gated benchmark suite: `scripts/benchmark.sh` (idle machine, release, validation off)
|
||||
- Run source mutation on decoder/shader/ref: `scripts/mutation.sh` (R2 owns triage)
|
||||
- Check generated status tables: `python3 scripts/audit/status.py --check`.
|
||||
- Check claims and dependency direction: `scripts/audit/claims.sh` and `scripts/audit/dependencies.sh`
|
||||
- Fuzz one CPU-only parser at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference>` (600 seconds by default).
|
||||
- Fuzz one target at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference|runtime_services>` (600 seconds by default). `runtime_services` drives the standard guest service registry.
|
||||
|
||||
Keep generated and gate logs under ignored `artifacts/`. Use at most four Cargo build jobs across two simultaneous CPU-heavy jobs, with one GPU job and one fuzz or mutation campaign at a time.
|
||||
|
||||
@@ -101,4 +121,4 @@ Preserve the configured Git author and committer identity.
|
||||
|
||||
## Ownership
|
||||
|
||||
Xbox and claims owns public console research. ISA owns the decoder and oracle fixtures. Compiler owns the parser, IR and MSL. Metal owns the native GPU backend. Testing owns the independent reference and fixture validation. Infrastructure owns shared Cargo configuration, policies and the CPU boundary. R1 independently audits claims and release evidence. R2 independently validates semantic expectations and mutation results.
|
||||
These are responsibility areas, not personal assignments; do not assign people without their agreement. Hybrid integration owns the CrossOver assessment, integration boundary, configuration, diagnostics and benchmarks. Xbox and claims owns public console research. ISA owns the decoder and oracle fixtures. Compiler owns the parser, IR and MSL. Metal owns the native GPU backend. Testing owns the independent reference and fixture validation. Infrastructure owns shared Cargo configuration, policies and the CPU boundary. R1 independently audits claims and release evidence. R2 independently validates semantic expectations and mutation results.
|
||||
+136
@@ -9,17 +9,119 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- Review follow-up on the proposed `victory-shader` import (#394): `translate_native` now reports immediate samplers as static samplers (a sampled texel read 0 on the GPU before), BetterXen's GPU tests use a host that `VICTORY_WARP` cannot redirect, the double-precision probes take run-time operands and were rerun (same result), and a per-file provenance review records that the crate was developed against one commercial title's shaders. **The import is not approved; a maintainer decision is required** (`docs/research/victory-shader-provenance.md`). Earlier statements that the crate had nothing game-specific are withdrawn.
|
||||
- Fixed the two wave-operation failures the vendored victory-shader tests showed under D3DMetal (`docs/research/shader-wave-semantics.md`). Device capabilities were measured with a new original D3D12 host (`workloads/d3d12-wave-probe`): shader model 6.6, wave operations, waves exactly 32 lanes, no double-precision shader operations. One failure was a wrong test precondition (a 64-lane lowering run on the 32-lane device); the test now checks the device width and asserts the recompiler's refusal. The other was unsupported double-precision operations: shaders compiled from original HLSL by Microsoft's DXC that use a `double` ran without writing anything, while float wave operations worked. The recompiler's one native-double site (`active_f64_sum`) now builds the console's balanced sum tree with its existing integer fp64 add and no longer declares doubles. Local results on one Apple M4 under CrossOver 26.3, not independently reproduced: the whole suite passes (229 passed, 3 ignored; the vendored original had 2 failures); 24 new GPU cases compare full 64-bit sums with a CPU model of the tree; both regression tests fail against the original lowering. Cost not measured; tree-order fidelity relies on the recompiler's own recognizer.
|
||||
- Added `scripts/hybrid/run-shader-gpu-tests.sh`, which cross-builds the vendored `victory-shader` test executable for Windows and runs it under CrossOver through `betterxen-hybrid run` (supervision, memory guard, stall detection, JSON record), either BetterXen's ten tests or the whole upstream suite. It takes both the runner and the test executable from the messages of the cargo invocations that built them, and stops if a build fails (review fix: an earlier version piped cargo into the parser, so a failed build exited 0 and ran a stale executable, and it assumed the runner was under `target/`). `scripts/hybrid/test-run-shader-gpu-tests.sh` is a stubbed regression test for both. It needs the runner from #384 and #388. Verified on the Apple M4 with CrossOver 26.3: fixtures pass; the whole suite shows the known failures; there is no fallback to a guessed path. Not independently reviewed.
|
||||
- Integrated skakwy's `victory-shader` (GFX10/RDNA 2 machine code to DXIL SM 6.6 recompiler, about 43,500 lines of Rust) as `crates/victory-shader`, with provenance in its `UPSTREAM.md`, the Mesa notice preserved and 19 lines of lint-only edits to upstream files. Added `translate_native` and tests that translate BetterXen's own gfx1030 fixtures to DXIL and, on Windows targets, run them on the GPU through D3D12. Local results on one Apple M4 with CrossOver 26.3 (D3DMetal), not independently reproduced: 177 upstream CPU-side tests pass on macOS; all 6 fixtures with expected words matched the manifest on the GPU, with a negative control; the GPU tests fail without D3D12 instead of skipping; the full upstream suite under CrossOver has 224 passed, 2 failed, 3 ignored. DXIL validation by `dxil.dll` was not run. The native RDNA-to-Metal compiler is unchanged. See `docs/research/victory-shader-integration.md`.
|
||||
- Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. VIctory-family projects are excluded from reuse on provenance grounds. The GitHub project board is not yet configured because the token lacks the `project` scope (#346).
|
||||
- Added hybrid research records: `docs/research/hybrid-backlog-research-2026-11-25.md` (findings and registry candidates, from search summaries) and `docs/research/primary-source-verification-2026-11-25.md` (re-check against CodeWeavers, Apple, DXMT and Wine primary pages). It confirms CrossOver's backend list, finds no public documentation of `CX_GRAPHICS_BACKEND`, and records that two Apple notices on Rosetta's end disagree; D3DMetal's license text and CrossOver's Rosetta and ARM64 plans remain unverified. Eleven issues created from the research were reviewed the same day: #364 and #365 stay in Phase 1, the others are parked and recorded under "Parked ideas" in the roadmap. Rust 1.100.0 (already installed) is the required toolchain; the default `stable` was 1.94.1. Planning only; nothing was installed or run.
|
||||
- Added File > Open Executable… with Command-O to the app (#252). It opens the focused window's read-only file importer, the same one as that window's button, and is disabled when no window can present it; each window keeps its own importer, so with several windows only the focused one shows the picker. The chosen file goes through the same inspection path as the button, drag and drop and Finder Open With; nothing is executed. A file-importer failure is now shown in red with the system's description instead of being ignored, a cancelled picker shows nothing, and the message clears on the next selection. `BetterXen --smoke-import-result`, run by `scripts/build-app.sh`, checks cancellation, a shown failure and its clearing; it fails on the previous importer handling. Checked locally on Apple Silicon in the running app (Command-O and the menu item open the picker, cancel shows no error, a second Command-O opens it again, with two windows only the focused one presents it, and with every window closed the menu item is disabled); not yet independently reviewed.
|
||||
- Added `docs/research/texture-formats.md`, an inventory of the texture formats and layouts BetterXen handles (#260). For BC1–BC7, RGBA8 and Depth32Float it separates container recognition, CPU decoding, layout conversion, native Metal upload and readback, translated sampling, the host-side D3D12-shaped API (called from Rust, not wired to guest imports) and guest reachability through imported services, and links each cell's implementing files and tests and each format's exact public specification sections, including the packed BC footprints from #241. It cross-references #208 and #209 instead of opening duplicate tasks, lists console layouts, console descriptors and asset or audio containers as unknowns, and ranks three proposed follow-ups with fixture recipes and owners. Research only; no implementation changed.
|
||||
- Rewrote the README around the six development phases and the first-launchable-application target (#311), with colour-coded Mermaid diagrams (system flow, milestone roadmap, CPU, runtime-service and shader-form charts built from the generated registries), badges, a repository overview, a contributing section and corrected texture-sampling wording. The older X1–X25 capability map is kept in a collapsible section. The diagrams were not render-tested locally.
|
||||
- Added a fast "Repository hygiene" check (`.github/workflows/hygiene.yml`, `scripts/audit/docs_hygiene.py`). It runs on Ubuntu without a Rust toolchain or network access and fails only on merge-conflict markers, broken relative Markdown links and invalid workflow YAML in tracked files. A separate advisory step warns, without failing, when source or script changes have no changelog entry. A local run over the 626 tracked files found no problems, and planted failures of each kind were caught; it has not yet run on GitHub.
|
||||
- Documented the proposed guest AVX/AVX2 state and decoding contract and specified an original integer fixture with known results and fault controls (#299).
|
||||
|
||||
### Removed
|
||||
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
|
||||
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
|
||||
|
||||
### Changed
|
||||
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
|
||||
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
|
||||
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
|
||||
- Replaced the issue templates with hybrid task, bug, research, performance, validation and documentation forms and added a pull request template. Fixed invalid YAML in the agent-task template. README, CONTRIBUTING and the docs index now describe the hybrid direction.
|
||||
- Replaced our own references to a specific commercial game title (README non-affiliation line, research and integration notes, ignored diagnostics folder names) with generic "commercial title" wording. The ignored folder names are now `diagnostics/title-candidate-*` and `diagnostics/title-check`. Third-party repository names, URLs and code-span paths in research notes are unchanged so their provenance stays accurate. Our own prose references to the upstream project formerly named in the research notes now read "PE-Vulkan project". Added the PortWatch native-macOS research notes. No behavior change.
|
||||
- TLS setup now copies templates from 64 KiB up to 1 MiB straight into the zeroed thread data block, after checking that every template byte is readable, instead of staging them in a second buffer (#111). The pointer array and data block layout, the TLS index write and the error for an unreadable template are unchanged, and nothing is mapped when the template cannot be read. On an Apple M2 Pro, median setup time for original synthetic templates over 31 interleaved samples fell by 21.7 % at 64 KiB, 19.0 % at 256 KiB and 14.2 % at 768 KiB. Smaller and larger templates keep the single staged read and showed no change beyond run-to-run variation.
|
||||
- Removed the contributor avatar section from the README.
|
||||
- Added `.github/CODEOWNERS` so pull requests request review from the `MacosPorters/maintainers` team. With the `main` branch rule that requires code-owner review, a maintainer must approve each change before it merges.
|
||||
- Repaired destination issue links in 20 migrated PR descriptions while retaining the imported text, attribution and contributor certifications. Template and review requirements remain in place.
|
||||
- Moved 163 unused migration PR refs from branches to verified archive tags, retaining the 22 open-PR branches. Historical refs no longer clutter the branch list or produce recent-push PR prompts.
|
||||
- Renamed the project branding and native app and primary CLI package/binary to BetterXen (`betterxen`), and updated active repository links to `MacosPorters/betterxen`. Legacy `xenora-*` library packages and synthetic guest ABI names remain for compatibility. Upstream licenses, notices and historical evidence are retained.
|
||||
- Guest `strlen`, `strnlen`, `wcslen` and `wcsnlen` scan memory in 256-unit blocks, falling back to single units at mapping boundaries so faults still report the first inaccessible unit. On Apple M2 Pro the 63-byte `strlen` workload went from 1,990 ns to 223 ns per call (median of 10 batches, on a machine that was not idle).
|
||||
- The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only.
|
||||
- Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104).
|
||||
- Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged.
|
||||
- The ARM64 assembler uses one 32-bit `MOVN` for zero-extended constants such as `0xFFFF1234` that previously took two wide moves (#89). On an Apple M1 Pro, a synthetic workload with 4,096 affected loads emitted 163,920 native bytes, down from 180,304 (9.1%). The native tests verify the encoding and the full 64-bit register result.
|
||||
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
|
||||
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
|
||||
- Changed the default report folder of `xenora probe` and `xenora imports sync` to `diagnostics/probe`, which Git ignores (#364). Anyone relying on the earlier default has to pass `--report`.
|
||||
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
|
||||
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
|
||||
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
|
||||
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
|
||||
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
|
||||
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
|
||||
- Avoided resolver allocations for permitted guest data reads and writes contained in one mapping, preserving checked fallback for split spans and faults (#105).
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
|
||||
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
|
||||
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
|
||||
- DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported.
|
||||
- Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version.
|
||||
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
|
||||
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
|
||||
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
|
||||
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
|
||||
|
||||
### Added
|
||||
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
|
||||
- Added a `Native app build and smoke` CI job (#248). On the same native `macos-26` runner image and pinned Rust toolchain as the Rust checks, it runs `scripts/build-app.sh`, which builds the locked C ABI library and the Swift app together, bundles and ad-hoc signs `BetterXen.app`, and runs its `--smoke` check, so a Swift compile, link or smoke failure is designed to fail CI (implemented and verified locally; not yet shown on a CI run). `scripts/build-app.sh` also prints `file` and a single `otool -L` listing for the executable, fails if that listing fails or is empty, and fails if the executable links any library outside `/System/Library/` and `/usr/lib/`, naming bundle-relative (`@rpath`, `@executable_path`, `@loader_path`) entries separately (checked locally against stubbed failing, empty, bundle-relative and non-system listings). The job is an app build and smoke result; it runs no Metal fixture and is not GPU verification.
|
||||
- Added a CPU and loader coverage map (#154) with decoder inventory, native and shared execution paths, and test counts from a pinned Apple M5 run.
|
||||
- Recorded the migrated PR integration decisions, native verification and scope exclusions in the testing documentation.
|
||||
- Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated
|
||||
submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline,
|
||||
submission, GPU, readback), with median, p90, p99 and maximum. Every sample must produce the fixture's
|
||||
expected output, or the run stops without writing results. `docs/testing/benchmarks.md` records one
|
||||
release run on an Apple M4: a fresh process took about 43 ms (median), 36 ms of it creating the Metal
|
||||
device and queue, while repeated runs in one process needed about 0.2 ms of host submission. Measurement
|
||||
only; nothing was optimized.
|
||||
- Added an opt-in, budgeted staged upload for RGBA8 textures (#144). `MetalRgba8Texture::upload_staged` fills a
|
||||
Private-storage texture through one reused Shared staging buffer that never exceeds a `StagingBudget`. It
|
||||
copies whole-row bands with a blit encoder and reuses the buffer only after the previous command buffer has
|
||||
completed with status Completed. `plan_staged_upload` rejects missing, duplicate or out-of-range mip levels,
|
||||
wrong mip sizes, short row pitches or byte buffers, and budgets smaller than one row, all before any Metal
|
||||
object is created. A blit `read_back` returns any mip as tight RGBA8 bytes. On one Apple M4 under Metal API
|
||||
validation, readback matched independently built patterns for every level of a padded 37×19, six-level
|
||||
texture under four budgets, and matched the existing direct `upload`. Staging is slower than the direct path
|
||||
(2048² with 12 mips, release build: 2.1 ms direct, 2.7 ms with a 4 MiB budget, 17.8 ms with 256 KiB), so
|
||||
`upload` and its callers are unchanged. Not yet independently accepted.
|
||||
- The gfx1030 identification benchmark fixture now runs as an ordinary integration test, so workspace tests check LLVM-derived names, families, lengths and byte boundaries without invoking a timing run.
|
||||
- Added a CPU benchmark for gfx1030 metadata identification (#173). It verifies instruction boundaries on a mixed-family stream assembled with LLVM and reports first-pass and repeated-pass throughput.
|
||||
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
|
||||
- Added a BetterXen development phase plan based on current source, pending PRs and existing acceptance records, linked from both contributor entry points. It separates baseline reconciliation, hosted C execution, guest threading, translated rendering, application integration and measured optimization; no new runtime or compatibility acceptance is claimed.
|
||||
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
|
||||
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
|
||||
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
|
||||
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
|
||||
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify stack alignment before CALL and at callee entry (`RSP % 16 == 8`), accessibility of the caller-allocated 32-byte shadow space, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
|
||||
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
|
||||
- LAHF and SAHF run in both engines, and guest CPUID reports them in leaf `8000_0001h`, ECX bit 0 (#387; Intel SDM Vol. 2A LAHF, Vol. 2B SAHF). The DBT runs them through the shared semantics. The four known answers from #155 that both engines refused are now verified, with twelve more cases, and the independent reference in `tests/x86_integer.rs` covers both instructions.
|
||||
- LOOP, LOOPE, LOOPNE and JRCXZ run in both engines (#396; Intel SDM Vol. 2A, LOOP/LOOPcc and Jcc). The count is RCX; the address-size prefix stays rejected, so JECXZ and the ECX-counted forms are still refused. The DBT runs them through the shared semantics and ends its block at each. The three known answers from #155 that both engines refused are now verified, with eleven more cases, and `tests/cpu_loop.rs` checks a loop that spans translated blocks against a step-by-step model for every count, ZF match point and step budget.
|
||||
- Added checked, per-mip copy footprints for synthetic block-compressed texture arrays. Contributors can pack tight block rows or repack entire chains with independent row and placement alignment, and pass selected BC1–BC5 levels to the existing Metal readers (#391).
|
||||
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
|
||||
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
|
||||
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
|
||||
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
|
||||
- Added `scripts/cpu-tests.sh`, which lists the default-feature workspace test targets and runs
|
||||
deterministic shards of them (`--shard K/N`), with `--check N` showing every target lands in
|
||||
exactly one shard. It does not replace `cargo test --locked --workspace` or
|
||||
`scripts/test-gpu.sh`. `docs/testing/cpu-coverage.md` records local CPU gate timings on one
|
||||
Apple M4 host (about 40 s wall time; one loader target takes about 19 s) and shows that the 2- and
|
||||
3-shard unions match the full gate's 681 passed and 34 ignored tests (#159).
|
||||
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
|
||||
- Added MOVNTI, the SSE2 non-temporal store of a 32- or 64-bit general register to memory (part of #125). Both engines used to stop on it with an illegal-instruction exit. It is an ordinary store, as the other non-temporal stores already are; the register form and the 66 prefix stay rejected, and a destination that cannot be written faults without changing state. The SDM-derived case `movdqa_movaps_aligned_store_and_load` in `cpu_known_answers.rs`, which ends in a MOVNTI, moved from refused to verified, and `tests/x86/integer.txt` gains four assembled instructions checked by the text-only reference in `x86_integer.rs`. MASKMOVDQU stays rejected and SSE2 stays unreported by CPUID. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added MFENCE, LFENCE and SFENCE and documented the ordering of guest memory accesses (part of #199). Both engines used to stop on a fence with an illegal-instruction exit. Each engine runs one guest instruction at a time on one host thread and completes its loads and stores before the next, so accesses are already totally ordered and the fences change nothing; `docs/cpu/instruction-registry.md` states this and that it holds only while guest threads do not run on several host threads. Five single-thread cases in `cpu_known_answers.rs` and three assembled fixtures cover them, and the memory forms that share the opcode stay rejected. SSE2 is still not reported by CPUID because other SSE2 instructions are rejected; the refused SSE2 instruction that `cpu_features.rs` holds is now MASKMOVDQU. No multi-thread behaviour is established, and nothing was compared with x86 hardware; awaiting independent review.
|
||||
- Added the accumulator short form of XCHG, opcodes 91 to 97 and 90 with REX.B, at 16, 32 and 64 bits (part of #118). Assemblers choose this form whenever one operand is the accumulator, and both engines used to stop on it with an illegal-instruction exit. A 16-bit exchange keeps the upper 48 bits of both registers, a 32-bit one clears both upper halves, and `49 90` exchanges RAX with R8 while plain `90` stays NOP. Both engines run the shared semantics; nothing is lowered to ARM64. Three SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 20 assembled instructions checked by the text-only reference in `x86_integer.rs`. F3 before this form, 16-bit PUSH and POP and LODSW stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added SHLD and SHRD, the double-precision shifts (`0F A4`/`0F A5` and `0F AC`/`0F AD`), for 16-, 32- and 64-bit register and memory destinations with the count in an 8-bit immediate or in CL (part of #121). The count is masked to five bits (six for 64-bit operands); a masked count of zero changes nothing, the vacated bits are filled from the source register, CF receives the last bit shifted out of the destination, ZF, SF and PF follow the result, OF is set only for a count of one (a sign change) and AF is undefined. A 16-bit count above 16 leaves the result and flags undefined in the Intel SDM; Xenora keeps every flag and writes the bits of the 32-bit concatenation, and no test relies on that. The registry gained the operand encodings `rm_reg_imm` and `rm_reg_cl`. Both engines run the shared semantics; nothing is lowered to ARM64. Eight SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 72 assembled SHLD and SHRD instructions, checked by a bit-at-a-time reference in `x86_integer.rs` and by the faulting read-modify-write test. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added RCL and RCR, the rotates through the carry flag, for 8-, 16-, 32- and 64-bit register and memory operands with a count of one, CL or an immediate (part of #121). The count is masked to five bits (six for 64-bit operands) and then reduced modulo 9 or 17 for 8- and 16-bit operands; a masked count of zero changes nothing, CF receives the last bit rotated out, and OF is set only for a count of one. Both engines run the shared semantics; nothing is lowered to ARM64. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and its shift sweep now runs both instructions at every width, count and carry against its bit-loop model. `tests/x86/integer.txt` gains 80 assembled RCL and RCR instructions, checked by the single-step reference in `x86_integer.rs`. SHLD and SHRD stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
|
||||
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
|
||||
- Added a deterministic guest thread scheduler (first part of #323): independent CPU contexts, guarded stacks and TEBs on one host thread, with bounded turns, `CreateThread`, `ExitThread`, `TerminateThread`, `GetExitCodeThread`, `SuspendThread`, `ResumeThread` and `SwitchToThread`. With a scheduler attached, `WaitForSingleObject` and `WaitForMultipleObjects` block only the calling guest thread, with timeouts, on threads, events, semaphores and mutexes; abandoned mutexes, deadlocks and per-thread faults are reported. Guest threads never run concurrently. Critical sections, SRW locks, condition variables and `Sleep` do not block per thread yet. See `docs/runtime/threads.md`.
|
||||
- Added decoding and Metal shader translation for the sixteen Wave32 VOPC 64-bit integer compares (#215). They read VGPR pairs, known even-aligned SGPR pairs or sign-extended inline integers and write the Wave32 VCC mask. The guide-derived oracle passes on native Metal (4,640 cases in 3,818 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added XADD and CMPXCHG for 8- to 64-bit register and memory destinations, and the LOCK prefix on their memory forms (#198). LOCK anywhere else, CMPXCHG8B and CMPXCHG16B stay rejected. Both engines run the new forms on the shared semantics, one instruction at a time, so a locked instruction is indivisible today and LOCK changes no result; `docs/cpu/instruction-registry.md` states the ordering, alignment, compare-failure and fault rules a guest scheduler must preserve. A failed compare still writes the destination, so it faults on memory that cannot be written. Nothing is lowered to ARM64 atomic instructions, and no multi-thread behaviour is established. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, with 62 LLVM-assembled fixtures and five new tests in `x86_atomic.rs`; not compared with x86 hardware and awaiting independent review.
|
||||
- Added CPUID with a fixed, host-independent guest contract (#130). It reports a synthetic processor with the vendor string `Xenora guest` and sets a feature bit only when every instruction of that feature is implemented: CMOV, POPCNT, LZCNT and long mode today. SSE and SSE2 are not reported while parts of them, such as RSQRTPS and MFENCE, are still rejected, so the table is truthful about Xenora and not a plausible hardware model. Unlisted leaves return zeros. `tests/cpu_features.rs` pins every leaf in both engines, requires each reported feature's instructions among the executed fixtures, and holds a refused witness instruction for 31 unreported features. `docs/cpu/instruction-registry.md` gives the table and the rule for reporting a new feature. Not compared with a processor; awaiting independent review.
|
||||
@@ -42,6 +144,7 @@ remains unsupported.
|
||||
- Added 985 LLVM-assembled integer instructions with a bit-level reference that reads only their assembly text, compared with the interpreter and the DBT over 47,280 states, plus 4,000 random instruction sequences compared between the engines.
|
||||
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
|
||||
- Added MOVZX, MOVSX (0F B6/B7/BE/BF) and MOVSXD (63) for register and checked memory operands in the interpreter and the native DBT, with exact lengths in the static probe (parts of #65, #66, #67, #68 and #117; awaiting independent review). Covered: 16-, 32- and 64-bit destinations, AH/CH/DH/BH without REX, FS/GS bases and RIP-relative operands. Other 0x66 forms are rejected instead of running at the wrong width. Known-answer encodings come from the LLVM assembler; MOV immediates (B8-BF) have regressions proving they are never read as sign extensions.
|
||||
- Added FNINIT (`DB E3`), the one instruction a C program built with the mingw-w64 runtime needs that the decoder refused (#378, part of Gate A2). Guest state gains the x87 control, status and tag words in `CpuState::x87`, and FNINIT sets them to the Intel SDM values `037F`, `0` and `FFFF`. Both engines run the shared semantics; nothing is lowered to ARM64 and the host's floating-point state is never touched. The registry gains a form key, `rm`, that pins a register-only form to one ModRM byte, because the other bytes of `DB /4` are different instructions. No other x87 instruction exists: FNSTCW, FLDCW, FNCLEX, FWAIT and all x87 arithmetic stay rejected, there are no x87 data registers, nothing can read the three words back, and CPUID still reports no FPU. Nine SDM-derived cases in `cpu_known_answers.rs`, whose harness now starts every case with the three words away from their reset values and requires every other instruction to keep them, one assembled fixture checked by the text-only reference in `x86_integer.rs`, and a sweep of every ModRM byte under opcodes `D8` to `DF` in both engines cover it. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
|
||||
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
|
||||
- Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues.
|
||||
@@ -52,6 +155,12 @@ remains unsupported.
|
||||
|
||||
- Added guest mutexes, critical sections, SRW locks, condition variables, synchronous one-time initialization, interlocked SLists, and TLS and FLS slots. Ownership is per guest thread (TEB). Calls that would have to block stop the guest with an explicit runtime-limit fault, because there is no guest scheduler yet. An original PE32+ fixture calls every service through its import table, using two guest TEBs. See `docs/interfaces.md`.
|
||||
|
||||
- Added an MSVC decorated-name decoder (`xenora_import_gen::demangle`), and import manifests now show undecorated names for C++ imports that need manual engineering. Unsupported constructs return no result rather than a guess. Tests decode names mangled independently by clang for `x86_64-pc-windows-msvc`.
|
||||
|
||||
- Added a guest service dispatch benchmark (`cargo bench -p xenora-loader --bench service_dispatch`). It runs correctness-gated guest loops that call services through the import table under the DBT; see `docs/testing/benchmarks.md`.
|
||||
|
||||
- Added a `runtime_services` fuzz target (`scripts/fuzz.sh runtime_services`) and a stable-toolchain replay test sharing the same driver. Both call random sequences of the standard guest services with zero, all-ones, writable, read-only, executable, unmapped, raw and earlier-result arguments, and check after every call that read-only and code memory are unchanged and nonvolatile registers are preserved. Writable guest memory is filled from a deterministic pattern so corpus bytes are reserved for dispatch. An earlier 300-second campaign's input and edge counts are withdrawn: that run exhausted each input while filling the 65,536-byte writable region and never reached the dispatch loop. After the harness fix, a local 300-second campaign on Apple Silicon (`scripts/fuzz.sh runtime_services 300`) ran 96,589 inputs (4,008 coverage edges, 9,940 features) without a crash; the first minutes also found a ~3.7 GiB `XMemAlloc` host OOM, which is now fixed by failing closed on overflowing sizes and routing mappings through the virtual allocation budget. Services that wait on real time or reach native Metal are excluded.
|
||||
|
||||
- Added guest system information, memory status, calendar time conversion, interrupt time and sleeping. The guest sees a configurable simulated machine (`GuestSystemProfile`, one processor by default), kept separate from the detected host hardware (`HostCapabilities`). Sleeping goes through the injectable clock, so tests advance time deterministically. An original PE32+ fixture verifies `SYSTEM_INFO`, `MEMORYSTATUSEX` and `SYSTEMTIME` layouts and leap-year handling against dates computed independently.
|
||||
|
||||
- Added services that call guest code and continue when it returns. The import dispatcher can run a sequence of guest callbacks on a checked stack frame, verifying the Win64 nonvolatile registers after each one. The CRT uses this for `qsort`, `qsort_s`, `bsearch`, `bsearch_s`, `_initterm`, `_initterm_e`, onexit tables, `atexit` and `_cexit`. Kernel32 uses it for `InitOnceExecuteOnce` and `FlsFree` cleanup callbacks. Original guest comparators and initializers in a PE32+ fixture verify ordering, stop-on-failure and register preservation.
|
||||
@@ -60,6 +169,8 @@ remains unsupported.
|
||||
|
||||
- Added guest module lookup and named symbol resolution for built-in Kernel32 and UCRT services.
|
||||
|
||||
- Added process exit and the first Gate A milestone, A1 (#329). `kernel32.dll!ExitProcess` stops the guest with the new `ExitReason::ProcessExit(status)`, carrying all 32 bits of the status, and never ends the host; a returning entry point does the same with EAX. The exit closes every guest handle, including Winsock sockets and task-queue handles, and the engine that ran the guest executes nothing further. A TLS callback that exits ends startup with that exit as its outcome, and the remaining callbacks and the entry point do not run. Startup reserves the page holding the return addresses the engine intercepts, so an image mapped over them is refused. `atexit` functions are not run. A1 is an original C program with no C library linked (`tests/compat_fixtures/gate_a1.c`): `crates/loader/tests/gate_a1.rs` builds it from source with clang and an LLD on every run, executes it through the loader, the standard services and the DBT at `-O0`, `-O1`, `-O2` and `-Os`, and checks its exit status, its report, its files and its memory against values recomputed in Rust. `docs/testing/gate-a.md` records what A1 shows and that Gate A stays open until the hosted milestone, A2, passes. Verified locally with two compilers; awaiting independent review.
|
||||
|
||||
- Added same-process guest file handle duplication with a shared file position.
|
||||
|
||||
- Added guest file and directory enumeration with typed search handles.
|
||||
@@ -68,22 +179,34 @@ remains unsupported.
|
||||
|
||||
- Added nested guest directories and checked file deletion on the synthetic drive.
|
||||
|
||||
- Added the second Gate A milestone, A2 (#419): an original hosted C program, `tests/compat_fixtures/gate_a2.c`, built from source by the new test `crates/loader/tests/gate_a2.rs` with the mingw-w64 C runtime (UCRT) and run through the loader, the standard services and the ARM64 DBT. The runtime's own startup code runs before `main`. The program takes `argc` and `argv`, sorts heap data with `qsort`, prints with `printf`, writes a report with `fprintf` and reads it back with `fgets`, registers a function with `atexit` and returns from `main`. At `-O0`, `-O1`, `-O2` and `-Os` it ends with exit status 0, and its captured output and its report match, byte for byte, text recomputed in Rust. Seven more tests cover other arguments, four wrong command lines, a step budget that is too small, and control variants that end in a failed check, in `exit(42)` and in `abort()`. The test needs mingw-w64 on the host and fails, not skips, without it, so the CI workflow now installs it. Nothing from mingw-w64 is stored in the repository. Local runs used mingw-w64 14.0.0 with GCC 16.2.0. This is one program and one C runtime, compared by hand with a native build of the same source and not with Windows or x86 hardware; `docs/testing/gate-a.md` lists what it does not show. Awaiting independent review.
|
||||
|
||||
- Added file seeking and end-of-file resizing on the synthetic guest drive.
|
||||
|
||||
- Added a bounded synthetic guest drive with synchronous file open, read, write, and size queries.
|
||||
|
||||
- Added files for a hosted C program (#402, part of Gate A2): `fopen`, `fclose`, `fgets` and `perror`, and file streams for the output services from #400, so `fprintf`, `fwrite` and `fputs` write to a file `fopen` returned. The files are the ones on the in-memory `C:` drive behind `CreateFileW`, so a file written through a C stream is the file `ReadFile` reads, and the reverse. `fopen` takes `r`, `w` or `a` with `+`, `b` and `t` as Microsoft's page describes them; text mode, the default, stores a line feed as carriage return and line feed, reads the pair back as a line feed and ends input at `CTRL+Z`. Failures return their documented results; the `errno` values beyond `EINVAL` for a null or empty argument are Xenora's choice. Nothing is buffered, there is no seeking, a C stream takes no part in Win32 sharing, and the other mode characters are refused. All four services are `partial`. Eight tests in `runtime_services.rs`, four in the new `crt_files.rs` that cross-check with `ReadFile` and `WriteFile`, and a unit test of the mode strings cover it. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added unnamed guest semaphores with checked release and immediate mixed-object waits.
|
||||
|
||||
- Added non-alertable extended event waits through both Win64 wait APIs.
|
||||
|
||||
- Added the C runtime's `exit`, `_exit` and `abort` (#395, part of Gate A2), on top of the process exit from #329. A C program ends through `exit`, not `ExitProcess`, and a program built with the mingw-w64 runtime imports all three; the loader refused it before its entry point because they did not resolve. `exit` calls the functions registered with `atexit` and `_crt_atexit`, most recently registered first, and then ends the guest with `ExitReason::ProcessExit(status)`; `_exit` ends it with its status and `abort` with exit code 3, and neither calls a registered function. All three go through the same cleanup as `ExitProcess` and never end the host. A function registered while `exit` runs is called next, as ISO C requires; `exit` called again from a registered function, which ISO C leaves undefined, runs the remaining functions once and ends with the later status. All three are partial: no stream is flushed because there are none, `abort` prints no message and calls no `SIGABRT` handler, and thread-local destructors are not run. Nine tests in `crt_exit.rs` call them from guest code. `docs/testing/gate-a.md` now describes A2 as in progress and not passing. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added immediate wait-any and wait-all for guest event handles.
|
||||
|
||||
- Added guest CRT signed and unsigned 64-bit conversions for narrow and wide strings.
|
||||
|
||||
- Added command-line arguments for a hosted C program (#392, part of Gate A2): the C runtime services `__p___argc`, `__p___argv`, `__p__environ`, `_configure_narrow_argv` and `_initialize_narrow_environment`, and a host method, `ServicesState::set_program_arguments`, that supplies the program's `argv`. A program built with the mingw-w64 runtime gets `argc`, `argv` and `envp` for `main` through these five, and the loader refused it before its entry point because they did not resolve. After configuration the guest finds the host's arguments in `__argc` and `__argv`, each NUL-terminated, with a null pointer after the last; with no host input it gets one empty argument, as ISO C specifies. The host method refuses a NUL byte, more than 32,767 bytes in all, and a call after the guest has built its table. The three variables are documented and the two initialization functions are not, so their behaviour is Xenora's: no code page, no wildcard expansion, and an empty environment table. All five are `partial`. Four tests in `runtime_services.rs` call the services from guest code and compare what the guest sees with what the test supplied. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added bounded guest CRT long-integer parsing for byte and wide strings.
|
||||
|
||||
- Added standard output for a hosted C program (#400, part of Gate A2): a `printf` formatting engine, the standard streams, and capture of what the guest writes to `stdout` and `stderr`. The services are `__acrt_iob_func`, `__stdio_common_vfprintf` (what `printf` and `fprintf` call in a program built with the mingw-w64 runtime), `fwrite`, `fputs`, `fflush` and `setvbuf`; a host reads the output through `ServicesState::standard_output` and `standard_error`. The engine handles the flags, width, precision and size prefixes of `d`, `i`, `u`, `o`, `x`, `X`, `c`, `s`, `p` and `%%` as Microsoft's format specification page and ISO C describe, reading arguments from the guest's `va_list`. The standard streams are text-mode streams, so a line feed is captured as carriage return and line feed. Floating-point and wide conversions, a locale object, other streams and files are not modelled and stop the guest with the runtime-limit fault instead of printing something wrong; `%n` and unknown conversions return -1 with `EINVAL`. All six services are `partial`. The engine's output matches the host C library's `snprintf` on 2,600 generated cases whose result ISO C defines (`crates/loader/tests/printf/reference.py`), with hand-written cases for the Windows-specific rules, and seven tests in `runtime_services.rs` call the services from guest code. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread.
|
||||
|
||||
- Added nine C runtime services that a C program's startup code calls or imports before `main`, and one alias (#382, part of Gate A2): `_set_app_type`, `_set_new_mode`, `_configthreadlocale`, `__setusermatherr`, `_set_invalid_parameter_handler`, `__p__fmode`, `__p__commode`, `signal` and `SetUnhandledExceptionFilter`, plus `memcpy` through `api-ms-win-crt-private-l1-1-0.dll`. A program built with the mingw-w64 runtime imports all of them, and the loader refused it before its entry point because they did not resolve. Each records what it is given and returns what its public documentation says: the previous mode, setting or handler, the documented failure value, or the address of the guest variables `_fmode` and `_commode`. All nine are declared `partial` in the typed registry because nothing acts on a recorded value: no handler or filter is ever called, no signal is raised, there is no locale, and nothing reads `_fmode` yet. `ServicesState` gains two read-only accessors, `crt_app_type` and `crt_user_math_error`. Five tests in `runtime_services.rs` call the services from guest code through a bound import table. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added guest CRT allocation, zeroed array allocation, resizing, and release.
|
||||
|
||||
- Added private guest heap creation and destruction with per-heap allocation ownership.
|
||||
@@ -92,6 +215,8 @@ remains unsupported.
|
||||
|
||||
- Added the synthetic default process heap with allocation, size queries, and release.
|
||||
|
||||
- Added `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` as `stub` services so that a C program built with the mingw-w64 runtime can bind its imports (#388, part of Gate A2). Such a program imports all three and does not call them on a normal run; without them the loader refused it before its entry point. A call to any of them stops the guest with the runtime-limit fault (`IllegalInstruction(0xFE)`) and writes nothing, so a program that needs one stops there and cannot run on with a made-up result. No page protection is changed, no region is described and no exception is dispatched. The service generator's API-set table gains `api-ms-win-crt-private-l1-1-0.dll` for `ucrtbase.dll`, which is inferred and not taken from a document that names it. Two tests in `runtime_services.rs` call the stubs from guest code and check how they resolve. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added Win64 signatures for wide-string length and comparison and overlapping byte moves to the import catalog.
|
||||
|
||||
- Added guest CRT wide-string length and comparison using Windows 16-bit code units.
|
||||
@@ -185,7 +310,17 @@ remains unsupported.
|
||||
native DBT.
|
||||
|
||||
### Fixed
|
||||
- `MockClock::advance` no longer wraps the FILETIME. A large advance made the synthetic wall clock run backwards while the performance count beside it stopped at its maximum; both now stop at their maximum (#204).
|
||||
- Fixed `DuplicateHandle` and `GetThreadId` naming the main thread from other guest threads, `OwningThread` in critical sections always holding the main thread's ID, the callback-depth limit being shared by all guest threads, and pending one-time initializations being unbounded.
|
||||
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
|
||||
- Fixed a latent ARM64 `LSLV` encoding bug that forced bit 1 of the shift-count register field (part of #131). The dynamic binary translator uses `X10` in its only call, which already has that bit set. `RBIT`, `CLZ` and `LSLV` now panic on out-of-range register numbers before emitting an instruction. Encoding tests use words checked against LLVM's assembler.
|
||||
- Fixed flat (untextured) guest `DrawInstanced` draws in the synthetic D3D12-style graphics context (#148). A draw with zero instances or fewer than three vertices now draws nothing. A non-zero start vertex or start instance, more than one instance or more than three vertices now fails with `GraphicsError::Unsupported` instead of drawing the view's first triangle. Vertex reads stay inside the vertex buffer, so a view past its end, or one whose guest address would overflow, fails with `IndexOutOfRange` instead of reading neighbouring guest memory or panicking. `crates/loader/tests/repeated_frames.rs` runs these through repeated reset, record, close and execute frames on the software reference backend, with hand-derived pixels; no native Metal result is claimed.
|
||||
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
|
||||
- Fixed TLS callback metadata that was accepted or misread without an error (#78). A non-zero `AddressOfCallbacks` outside the image's sections, or 4 GiB or more above the image base, is now refused; it used to mean "no callbacks" or read the list from an unrelated place. The callback list must reach its null entry inside its section, where the section's zero-filled tail counts, and a list of more than 64 callbacks is refused where it used to be cut short. `execute_tls_callbacks` refuses a stack top that is not 16-byte aligned or cannot hold the entry frame, which used to overflow a subtraction, and a file cut inside the TLS data-directory entry no longer panics the parser. `TlsError` gains four variants for these cases. Twelve unit tests in `crates/loader/src/tls.rs` use original headers and code, and also check the argument registers, the stack pointer at entry and after return, callback order and the instruction budget. Expectations come from Microsoft's public PE Format and x64 calling convention pages; nothing ran on Windows, and independent review is pending.
|
||||
- Fixed the thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
|
||||
- Fixed the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
|
||||
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
|
||||
- Fixed guest flags in the native DBT (#64, #70). They lived only in host NZCV, so they were lost across helper calls and block boundaries and register ADD, SUB and XOR set none. JB, JAE, JBE and JA used ARM carry polarity, which is inverted for subtraction. Flags are now stored in the guest state.
|
||||
@@ -194,6 +329,7 @@ remains unsupported.
|
||||
- Fixed 32-bit guest stores and loads in the native DBT (MOV 89/8B and C7 /0), which accessed eight bytes: stores overwrote the next four guest bytes and accesses at the end of a mapping faulted. RIP-relative operands of byte moves and extensions, which were read as RBP-relative, and LEA with a segment prefix, which added the segment base, are fixed too.
|
||||
- Fixed an x86 prefix-length test that read an untracked fuzz artifact and so failed on every fresh checkout; its input is now inline.
|
||||
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
|
||||
- Fixed `scripts/audit/status.py` and the Python embedded in `scripts/audit/claims.sh` reading and writing tracked files in the process locale encoding instead of UTF-8: under an ASCII or cp1252 locale the status check crashed on `docs/claims.toml` or reported a spurious `xenora-progress.svg` difference. Both scripts now pass `encoding="utf-8"`, as the rest of `scripts/` does, the two write sites also pin `newline="\n"` so a Windows host cannot turn tracked LF files into CRLF when it regenerates them, and CI runs the two checks again under a non-UTF-8 locale so the requirement stays enforced.
|
||||
|
||||
- Generated CRT adapters now report unsupported calls when the required guest ABI or runtime behavior is missing.
|
||||
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# Code of Conduct
|
||||
|
||||
Xenora welcomes contributors with different backgrounds and experience levels. Discussions should be about the technical work and conducted with respect.
|
||||
BetterXen welcomes contributors with different backgrounds and experience levels. Discussions should be about the technical work and conducted with respect.
|
||||
|
||||
## Expected behavior
|
||||
|
||||
@@ -19,4 +19,4 @@ If possible, use an available private contact channel for a repository maintaine
|
||||
|
||||
Maintainers may remove content, limit participation or block accounts when necessary to protect the community. Responses should be proportionate to the behavior and protect the privacy of affected people. Do not retaliate against anyone reporting a concern in good faith.
|
||||
|
||||
This policy applies to repository issues, pull requests, discussions and other spaces officially managed by Xenora.
|
||||
This policy applies to repository issues, pull requests, discussions and other spaces officially managed by BetterXen.
|
||||
+9
-5
@@ -1,6 +1,10 @@
|
||||
# Contributing to Xenora
|
||||
# Contributing to BetterXen
|
||||
|
||||
Xenora is an experimental Xbox Series X|S recompilation framework for Apple Silicon. Its graphics subsystem, XenoMetal, targets native Metal execution. Contributions should improve verified behavior rather than expand untested claims.
|
||||
BetterXen is hybrid-first Apple Silicon compatibility research built around an externally installed CrossOver, with a preserved but paused independent native implementation. Contributions should improve verified behavior rather than expand untested claims.
|
||||
|
||||
## Which work is active
|
||||
|
||||
The only active development track is the CrossOver-based hybrid architecture in [docs/roadmap.md](docs/roadmap.md). Planning is progressive: only the current milestone (Phase 1) has open issues; ideas for later phases are parked in the roadmap. Native research is paused, its backlog is closed and indexed in [docs/research/native-issue-archive.md](docs/research/native-issue-archive.md), and the few native issues still open only have assigned contributors with open pull requests. Do not start native work; if hybrid development needs a native component, file a focused hybrid issue. Pick an open issue in the current milestone and check its dependencies first. The engineering rules in `AGENTS.md` permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal (subject to licensing) and allow evaluating DXMT, DXVK, VKD3D-Proton and MoltenVK. CrossOver is proprietary: do not bundle or redistribute any of it, and record the exact versions you test. Before adopting or copying any upstream code, verify its license and provenance and add it to the [upstream registry](docs/research/upstream-registry.md); projects built around leaked or unauthorized game builds are not a source of code. Use the issue templates (hybrid task, bug, research, performance, validation, documentation) and fill in the licensing and provenance section.
|
||||
|
||||
## Getting started
|
||||
|
||||
@@ -28,11 +32,11 @@ For a performance change, provide reproducible before-and-after results using eq
|
||||
|
||||
## Research and clean-room policy
|
||||
|
||||
Use publicly accessible specifications and authorized materials only. Do not submit leaked SDKs, confidential documentation, firmware, keys, proprietary game binaries or unauthorized shader dumps. Under Xenora's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
|
||||
Use publicly accessible specifications and authorized materials only. Do not submit leaked SDKs, confidential documentation, firmware, keys, proprietary game binaries or unauthorized shader dumps. Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
|
||||
|
||||
Distinguish desktop RDNA behavior from Xbox-specific behavior. Cite primary sources with exact applicable architectures and record uncertainties using the project's evidence classification when available. Tests on Apple GPUs do not establish verification on Xbox hardware.
|
||||
|
||||
Xenora implements its own Rust guest runtime, decoder, typed IR, shader
|
||||
BetterXen implements its own Rust guest runtime, decoder, typed IR, shader
|
||||
compiler and native Metal backend from public technical specifications
|
||||
and independently derived tests. Contributions must not copy, port or
|
||||
adapt code, decoder tables, internal metadata or implementation
|
||||
@@ -44,7 +48,7 @@ Before incorporating third-party code, verify per-file license compatibility wit
|
||||
## Pull requests
|
||||
|
||||
- Branch from the current main branch, keep commits focused, and link relevant issues.
|
||||
- Fill in every section of the pull request template, keep `Closes #<number>` (or write `No linked issue: <reason>`), and tick the claimed-first and DCO checkboxes. The *PR template* check fails until the description does, and runs again each time you edit it.
|
||||
- Describe what changes and why, link the issue you claimed with `Closes #<number>`, state which checks you actually ran, and disclose material AI assistance. Separate unverified work from supported behavior.
|
||||
- Include a clear explanation, tests and any documentation/status updates. Separate unverified work from supported behavior.
|
||||
- Disclose material AI assistance and personally review generated changes. AI output is not an authoritative source, test oracle or substitute for independent review.
|
||||
- Never include secrets, personal paths, credentials or private data in patches or logs.
|
||||
|
||||
Generated
+211
-8
@@ -2,6 +2,19 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "betterxen"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
@@ -126,6 +139,24 @@ dependencies = [
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
@@ -137,12 +168,60 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
@@ -150,22 +229,139 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "xenora"
|
||||
name = "victory-shader"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
"thiserror",
|
||||
"windows",
|
||||
"windows-sys",
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
|
||||
dependencies = [
|
||||
"windows-collections",
|
||||
"windows-core",
|
||||
"windows-future",
|
||||
"windows-numerics",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-collections"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-future"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
"windows-link",
|
||||
"windows-threading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-numerics"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-threading"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-benchmarks"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-isa",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
@@ -204,6 +400,7 @@ dependencies = [
|
||||
"sha2",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
"xenora-texture",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -241,3 +438,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "xenora-texture"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "zlib-rs"
|
||||
version = "0.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"
|
||||
@@ -10,3 +10,10 @@ rust-version = "1.100"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
|
||||
# Whole-program optimization for release and bench builds (#116). On an Apple M5 the
|
||||
# interpreter ran about 6 % and cold DBT about 9 % faster in `dbt_bench`, at the cost of
|
||||
# slower release builds. Debug and test builds are unaffected.
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
@@ -1,63 +1,122 @@
|
||||
# Xenora
|
||||
<div align="center">
|
||||
|
||||
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
|
||||
# BetterXen
|
||||
|
||||
Xenora is an open-source project written primarily in Rust that builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
|
||||
**Hybrid-first Apple Silicon compatibility research built around CrossOver, with preserved independent native ARM64 and Metal research (paused).**
|
||||
|
||||
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
|
||||
[](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml)
|
||||
-1f6feb?logo=apple&logoColor=white)
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
Xenora is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
|
||||
**The paused native implementation described below uses no Wine, CrossOver, Rosetta or Vulkan runtime. The active hybrid direction intends to use CrossOver and Rosetta 2, subject to research and licensing review.**
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Current direction.** BetterXen's only active development track is a CrossOver-based hybrid architecture: CrossOver (installed externally) as the compatibility foundation, with BetterXen providing whatever integration, configuration, diagnostics, benchmarking and optimization research shows is missing. This is the *intended* architecture, **not a verified Xbox compatibility stack**: no Xbox title has been shown to run through it, and CrossOver is not assumed to provide Xbox runtime compatibility. Work is at the research stage (Phase 1). Planning is progressive: only the current phase has open issues. The independent native implementation described below is **preserved but paused indefinitely**. See the [roadmap](docs/roadmap.md), [ADR 0005](docs/adr/0005-crossover-hybrid-direction.md), the [upstream research registry](docs/research/upstream-registry.md) and the [deferred native roadmap](docs/research/native-roadmap.md). The rewritten engineering rules are in [AGENTS.md](AGENTS.md).
|
||||
|
||||
</div>
|
||||
|
||||
BetterXen is a community-maintained, open-source project written primarily in Rust. Its native research implementation (paused) builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend. The host runs as ARM64 code; the x86-64 code being emulated is guest data.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **BetterXen is experimental.** Verified work is restricted to independently authored synthetic programs and shaders. Authentic Xbox executable loading, system-service compatibility and commercial game execution are **not supported**. Progress is measured by reproducible tests, not by estimated game compatibility percentages. See the [current limitations](#current-limitations).
|
||||
|
||||
> [!CAUTION]
|
||||
> **Xenora strictly opposes piracy.** Xenora is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. Xenora is not affiliated with Microsoft or any other publisher or platform holder.
|
||||
|
||||
[](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
|
||||
> **BetterXen strictly opposes piracy.** BetterXen is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. BetterXen is not affiliated with Microsoft or any other publisher or platform holder.
|
||||
|
||||
---
|
||||
|
||||
## What works today?
|
||||
## How it fits together
|
||||
|
||||
Xenora has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
|
||||
One guest program travels through three native subsystems. Every stage is checked against an independently derived expectation.
|
||||
|
||||
The latest verified milestones include **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, the native Metal **blend pass** (`NativeCompute::render_blend`) and **indexed triangle draws** (`NativeCompute::render_indexed`) into offscreen targets, with rendered pixels compared against independently calculated reference results.
|
||||
```mermaid
|
||||
%%{init: {'theme':'base','themeVariables':{'fontFamily':'system-ui, sans-serif','lineColor':'#6e7781'}}}%%
|
||||
flowchart LR
|
||||
A["Original PE32+<br/>test program"]:::guest --> B["Loader<br/>relocations, TLS, imports"]:::guest
|
||||
B --> C["x86-64 interpreter<br/>+ ARM64 translator"]:::cpu
|
||||
C --> D["Typed runtime<br/>services"]:::cpu
|
||||
D --> E["Guest graphics<br/>commands"]:::gpu
|
||||
S["Original gfx1030<br/>shader bytes"]:::shader --> T["RDNA 2 decoder<br/>+ validated IR"]:::shader --> U["Metal Shading<br/>Language"]:::shader
|
||||
E --> M["Native Metal<br/>pipelines"]:::gpu
|
||||
U --> M
|
||||
M --> G["Apple Silicon GPU<br/>+ readback"]:::gpu
|
||||
G --> V{"Matches the<br/>independent<br/>CPU reference?"}:::check
|
||||
S -.-> R["Independent<br/>CPU reference"]:::check -.-> V
|
||||
|
||||
### Development milestones
|
||||
classDef guest fill:#ddf4ff,stroke:#0969da,color:#0a3069
|
||||
classDef cpu fill:#dafbe1,stroke:#1a7f37,color:#0f5323
|
||||
classDef shader fill:#fbefff,stroke:#8250df,color:#512a97
|
||||
classDef gpu fill:#fff8c5,stroke:#9a6700,color:#4d2d00
|
||||
classDef check fill:#ffebe9,stroke:#cf222e,color:#82071e
|
||||
```
|
||||
|
||||
| Milestone | Implementation | Status |
|
||||
| --- | --- | --- |
|
||||
| X1 — Guest CPU | Bounded x86-64 instruction execution on ARM64 macOS | Verified |
|
||||
| X2 — Executable loading | Loading original fixed-base PE32+ test executables | Verified |
|
||||
| X3 — GPU compute | Guest-submitted Metal compute workloads and readback | Verified |
|
||||
| X4 — Metal rendering | Guest-driven offscreen rendering using authored Metal shaders | Verified |
|
||||
| X5 — Guest execution expansion | Additional bounded CPU execution and fixture coverage | Implemented |
|
||||
| X6 — Guest control flow | Nested calls, returns, checked memory and synthetic PE execution | Verified |
|
||||
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
|
||||
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
|
||||
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
|
||||
| X10 — Texture sampling | Translated image instructions are still planned; upload, readback and decode of BC compressed formats is implemented (see [Texture support](#texture-support)) | Planned |
|
||||
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
|
||||
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
|
||||
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
|
||||
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
|
||||
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
|
||||
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
|
||||
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
|
||||
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
|
||||
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
|
||||
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
|
||||
| X21 — Application compatibility | Execute increasingly complex independently authored applications through the complete guest CPU and GPU pipeline | Planned |
|
||||
| X22 — First application boot | Establish a reproducible startup and error-reporting path for supported game-like applications | Planned |
|
||||
| X23 — Initial game compatibility | Investigate startup and execution of legally supported game software, identifying missing runtime and graphics behavior | Long-term goal |
|
||||
| X24 — Gameplay and performance | Expand rendering correctness, input, audio, memory management, shader caching and execution performance | Long-term goal |
|
||||
| X25 — Running games | Achieve reproducible, stable execution of compatible games on native Apple Silicon macOS using Metal | Long-term goal |
|
||||
Legend: 🟦 guest loading · 🟩 guest CPU and services · 🟪 shader translation · 🟨 native Metal · 🟥 independent verification.
|
||||
|
||||
---
|
||||
|
||||
## Roadmap
|
||||
|
||||
The active plan is the [roadmap](docs/roadmap.md): **Phase 1 — CrossOver Research, Feasibility and Baseline** is the only active phase, and later phases are provisional and will be defined from its findings. The current issues are in the [Phase 1 milestone](https://github.com/MacosPorters/betterxen/milestone/9). The native implementation's six phases and the X1 to X25 capability map are archived in [docs/archive/readme-native-milestones.md](docs/archive/readme-native-milestones.md) and the [native-first plan](docs/archive/development-phases-native-first.md). Native work is paused indefinitely and resumes only after an explicit maintainer decision.
|
||||
|
||||
**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. Actual priorities will change as compatibility testing reveals new blockers. Successfully completing one milestone does not guarantee that a particular game will run.
|
||||
|
||||
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
|
||||
|
||||
---
|
||||
|
||||
## Repository at a glance
|
||||
|
||||
Counts below come from the generated registries and were read from the repository, not measured on new runs. They describe synthetic fixtures only.
|
||||
|
||||
| Area | Where | What exists today |
|
||||
| --- | --- | --- |
|
||||
| Guest CPU | `crates/loader` | A generated x86-64 decoder and interpreter, plus a native ARM64 dynamic binary translator (DBT) for a bounded subset. The instruction registry declares 213 operations, 403 forms and 498 opcode slots; 93 operations have at least one form lowered to ARM64 and the rest run through shared interpreter semantics. See the [instruction registry](docs/cpu/instruction-registry.md). |
|
||||
| Executable loading | `crates/loader` | PE32+ loading, relocations, thread-local storage, import binding and a static inspection report. |
|
||||
| Runtime services | `crates/loader`, `crates/import-gen` | A typed service registry: 47 declared services (7 implemented, 37 partial, 3 stubs), all exercised through guest dispatch, none independently accepted. See the [registry](docs/runtime/registry.md) and [generated coverage](docs/runtime/services.md). Guest threads run on a deterministic scheduler on one host thread. |
|
||||
| Shader ISA | `crates/isa`, `crates/decoder`, `crates/shader`, `crates/ref` | The RDNA 2 (gfx1030) instruction snapshot lists 1,465 forms; 189 are decoder-supported, 185 are lowered to Metal Shading Language, and 18 are Metal-verified on fixtures. See the [semantic coverage](docs/shaders/semantic-coverage.md). An independent CPU reference checks GPU output. |
|
||||
| Metal backend | `crates/metal` | Native compute, blend, indexed-draw, depth and sampled-texture passes, with Metal API and shader validation. |
|
||||
| Textures | `crates/texture` | Upload, readback, BC1 to BC7 decoding and sampler code. |
|
||||
| Application | `app`, `crates/ffi` | A Swift macOS app over a versioned C interface: frame loop, interactive input, persistent resources, audio and a sandboxed virtual filesystem, all against synthetic guests. |
|
||||
| Test and tooling | `tests`, `fuzz`, `benchmarks`, `scripts` | Original guest programs, independent validation, fuzz targets (CPU decode, PE parse, instruction streams, fixtures, reference, runtime services), mutation testing, correctness-gated benchmarks, and audit scripts for claims, status tables and dependency direction. |
|
||||
|
||||
The `betterxen` command-line tool provides `info`, `demo`, `inspect <pe>`, `probe --pe <path> --mode static`, `run`, `imports` and `shaders`. Run `cargo run -p betterxen` with no arguments to see its usage.
|
||||
|
||||
|
||||
### Where the numbers stand
|
||||
|
||||
Counts come from the repository's generated registries at this revision. They describe synthetic fixtures only and are not compatibility percentages.
|
||||
|
||||
```mermaid
|
||||
%%{init: {'theme':'base','themeVariables':{'pie1':'#1a7f37','pie2':'#d0d7de','pieTitleTextSize':'16px','pieStrokeColor':'#ffffff','pieOuterStrokeColor':'#ffffff','fontFamily':'system-ui, sans-serif'}}}%%
|
||||
pie showData title Guest CPU — 213 declared x86-64 operations
|
||||
"Lowered to ARM64 (at least one native form)" : 93
|
||||
"Shared interpreter semantics only" : 120
|
||||
```
|
||||
|
||||
```mermaid
|
||||
%%{init: {'theme':'base','themeVariables':{'pie1':'#1a7f37','pie2':'#d4a72c','pie3':'#cf222e','pieStrokeColor':'#ffffff','pieOuterStrokeColor':'#ffffff','fontFamily':'system-ui, sans-serif'}}}%%
|
||||
pie showData title Runtime services — 47 declared, none independently accepted
|
||||
"Implemented" : 7
|
||||
"Partial" : 37
|
||||
"Stub" : 3
|
||||
```
|
||||
|
||||
```mermaid
|
||||
%%{init: {'theme':'base','themeVariables':{'xyChart':{'plotColorPalette':'#8250df'}}}}%%
|
||||
xychart-beta
|
||||
title "gfx1030 instruction forms by stage (1,465 identified)"
|
||||
x-axis ["Decoder-supported", "Lowered to MSL", "Metal-verified"]
|
||||
y-axis "Forms" 0 --> 200
|
||||
bar [189, 185, 18]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Native graphics translation
|
||||
|
||||
Xenora's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
|
||||
BetterXen's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
|
||||
|
||||
The translation process is:
|
||||
|
||||
@@ -164,7 +223,7 @@ The resource system remains experimental. Native GPU work already in flight duri
|
||||
|
||||
## Texture support
|
||||
|
||||
Xenora includes original texture upload, readback and block-compression paths.
|
||||
BetterXen includes original texture upload, readback and block-compression paths.
|
||||
|
||||
Implemented and tested functionality includes:
|
||||
|
||||
@@ -175,15 +234,15 @@ Implemented and tested functionality includes:
|
||||
- Edge-block and transparency tests.
|
||||
- Invalid descriptor and bounds rejection.
|
||||
|
||||
**Translated texture-sampling instructions are not yet implemented.**
|
||||
**Translated texture sampling covers one instruction and one sampler mode.** A guest draw with the translated `image_sample_lz` pixel stage and a point/clamp sampler matched the software reference and hand-derived images on a local Apple M5 Pro run (one-level RGBA8 and an 8×8 BC1 texture). Other image instructions, filtering modes and formats are not implemented, and this is local verification, not independent acceptance.
|
||||
|
||||
The existing texture readback path uses authored Metal kernels. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
|
||||
The texture upload and readback paths use authored Metal kernels. They should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
|
||||
|
||||
Xbox-specific texture layouts and additional compression formats require further research and validation.
|
||||
|
||||
## Architecture
|
||||
|
||||
Xenora is organized around three connected subsystems: guest execution, shader translation and native GPU execution.
|
||||
BetterXen is organized around three connected subsystems: guest execution, shader translation and native GPU execution.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
@@ -228,13 +287,22 @@ flowchart TD
|
||||
L --> M
|
||||
K --> M
|
||||
end
|
||||
|
||||
classDef guestNode fill:#dafbe1,stroke:#1a7f37,color:#0f5323
|
||||
classDef shaderNode fill:#fbefff,stroke:#8250df,color:#512a97
|
||||
classDef metalNode fill:#fff8c5,stroke:#9a6700,color:#4d2d00
|
||||
classDef checkNode fill:#ffebe9,stroke:#cf222e,color:#82071e
|
||||
class A,B,C,D guestNode
|
||||
class E,F,G,H shaderNode
|
||||
class I,J,K metalNode
|
||||
class L,M checkNode
|
||||
```
|
||||
|
||||
Xenora's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
|
||||
BetterXen's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
|
||||
|
||||
The native graphics pipeline runs translated vertex and pixel stages, the indexed-draw and blend passes and the depth pass into offscreen Metal targets, with GPU readback compared against independent CPU references.
|
||||
|
||||
The project does not currently provide a general-purpose x86-64 dynamic recompiler or a complete Xbox operating-system implementation.
|
||||
The native ARM64 dynamic recompiler covers a bounded subset of x86-64 instructions; the rest run through the shared interpreter semantics (see the [CPU coverage map](docs/testing/cpu-coverage.md) once it lands). The project does not provide a complete Xbox operating-system implementation.
|
||||
|
||||
See [Interface Contracts](docs/interfaces.md) for the documented execution and resource boundaries.
|
||||
|
||||
@@ -242,7 +310,7 @@ See [Interface Contracts](docs/interfaces.md) for the documented execution and r
|
||||
|
||||
## Current limitations
|
||||
|
||||
Xenora is an engineering research project, not a working commercial-game emulator.
|
||||
BetterXen is an engineering research project, not a working commercial-game emulator.
|
||||
|
||||
The following remain unsupported or incomplete:
|
||||
|
||||
@@ -252,18 +320,18 @@ The following remain unsupported or incomplete:
|
||||
| Executable loader | General relocations, TLS, DLL initialization and authentic Xbox startup |
|
||||
| Xbox runtime | Console-specific services, system APIs, filesystem and application lifecycle |
|
||||
| RDNA2 shaders | General control flow, broader instructions, Wave64, cross-lane operations and mesh stages |
|
||||
| Graphics | Translated texture sampling and broader resource binding |
|
||||
| Textures | Authentic Xbox memory layouts and translated sampling |
|
||||
| Graphics | Broader translated texture sampling (one instruction and sampler mode exist) and broader resource binding |
|
||||
| Textures | Authentic Xbox memory layouts and broader translated sampling |
|
||||
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
|
||||
| Game compatibility | No demonstrated execution of commercial Xbox titles |
|
||||
|
||||
Xenora's current shader fixtures target a bounded subset of desktop gfx1030 behavior. This is not equivalent to complete Xbox Series GPU compatibility.
|
||||
BetterXen's current shader fixtures target a bounded subset of desktop gfx1030 behavior. This is not equivalent to complete Xbox Series GPU compatibility.
|
||||
|
||||
Progress is measured by reproducible tests rather than estimated game compatibility percentages.
|
||||
|
||||
---
|
||||
|
||||
## Building Xenora
|
||||
## Building BetterXen
|
||||
|
||||
### Requirements
|
||||
|
||||
@@ -278,15 +346,15 @@ The recorded Apple M5 environment uses Rust 1.100.0 and Xcode 27.2.
|
||||
### Clone
|
||||
|
||||
```sh
|
||||
git clone https://github.com/ranveersoni98/Xenora.git
|
||||
cd Xenora
|
||||
git clone https://github.com/MacosPorters/betterxen.git
|
||||
cd betterxen
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```sh
|
||||
scripts/bootstrap.sh
|
||||
cargo build --locked -p xenora
|
||||
cargo build --locked -p betterxen
|
||||
```
|
||||
|
||||
### Run core tests
|
||||
@@ -309,7 +377,7 @@ These require a Metal-capable Apple Silicon Mac.
|
||||
scripts/test-gpu.sh
|
||||
```
|
||||
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths.
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host. On macOS, the script uses a Python 3 fallback when GNU `timeout` is unavailable.
|
||||
|
||||
### Verify guest execution
|
||||
|
||||
@@ -349,9 +417,21 @@ Testing distinguishes between:
|
||||
|
||||
Compiling a shader is not equivalent to proving its GPU output is correct.
|
||||
|
||||
### Contributing
|
||||
|
||||
Contributions are welcome, and several people and coding agents work in this repository at once. To avoid duplicated work:
|
||||
|
||||
1. Read every comment on an issue and check for open pull requests that link it.
|
||||
2. Claim the issue with a plain reply (for example "I'm taking this. Plan: ...") before you edit anything. The earliest live claim wins, and a claim is stale only after about seven days without a pull request.
|
||||
3. Stay inside the files the issue lists, and put `Closes #<n>` in the pull request description.
|
||||
4. Sign off every commit (DCO) and use only public documentation and original code. Anyone who has seen leaked or confidential Xbox material must not contribute.
|
||||
5. Update `CHANGELOG.md` for meaningful changes. Changes to `main` need maintainer review through [CODEOWNERS](.github/CODEOWNERS).
|
||||
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md), [docs/legal.md](docs/legal.md) and the [documentation index](docs/README.md) for the full rules.
|
||||
|
||||
### Where the work is heading
|
||||
|
||||
See the [roadmap table](#development-milestones) for proposed milestones, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
|
||||
See the [roadmap](docs/roadmap.md) for the current phase and the [changelog](CHANGELOG.md) for unreleased additions. The paused native implementation's open research items are listed under [current limitations](#current-limitations).
|
||||
|
||||
---
|
||||
|
||||
@@ -359,16 +439,12 @@ See the [roadmap table](#development-milestones) for proposed milestones, and th
|
||||
|
||||
---
|
||||
|
||||
### Contributors
|
||||
|
||||
[](https://github.com/ranveersoni98/Xenora/graphs/contributors)
|
||||
|
||||
## License
|
||||
|
||||
Xenora is licensed under the [GNU General Public License v3 or later](LICENSE).
|
||||
BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE).
|
||||
|
||||
See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution and [docs/legal.md](docs/legal.md) for the project's research and legal boundaries.
|
||||
|
||||
Xenora is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple.
|
||||
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, any game publisher or Apple.
|
||||
|
||||
---
|
||||
+2
-2
@@ -2,13 +2,13 @@
|
||||
|
||||
## Scope
|
||||
|
||||
Xenora is experimental and is not currently represented as a security-hardened runtime. Treat shaders, binary containers, caches and native library inputs as untrusted. Do not use it to process untrusted content in a sensitive environment.
|
||||
BetterXen is experimental and is not currently represented as a security-hardened runtime. Treat shaders, binary containers, caches and native library inputs as untrusted. Do not use it to process untrusted content in a sensitive environment.
|
||||
|
||||
The project does not promise a fixed security support window at this stage. Report issues against a specific revision, preferably reproduced on current `main` where safe.
|
||||
|
||||
## Reporting vulnerabilities
|
||||
|
||||
Use [GitHub private vulnerability reporting](https://github.com/ranveersoni98/Xenora/security/advisories/new), if enabled. If it is unavailable, request a private reporting channel without disclosing exploit details publicly. Do not open a public issue containing sensitive vulnerability details, credentials, or private data.
|
||||
Use [GitHub private vulnerability reporting](https://github.com/MacosPorters/betterxen/security/advisories/new), if enabled. If it is unavailable, request a private reporting channel without disclosing exploit details publicly. Do not open a public issue containing sensitive vulnerability details, credentials, or private data.
|
||||
|
||||
Include the affected commit, environment, affected component, expected and actual behavior, impact and a minimal, authorized reproduction. Use synthetic inputs wherever possible. Do not attach protected content, leaked SDK material or proprietary shaders.
|
||||
|
||||
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
# Getting help
|
||||
|
||||
Start with the [README](README.md) and the relevant documentation in the repository, if available. Xenora is an experimental research project, not a commercial game compatibility service.
|
||||
Start with the [README](README.md) and the relevant documentation in the repository, if available. BetterXen is an experimental research project, not a commercial game compatibility service.
|
||||
|
||||
- Use [GitHub Issues](https://github.com/ranveersoni98/Xenora/issues) for reproducible bugs, feature proposals, research findings and hardware verification reports.
|
||||
- Use [GitHub Discussions](https://github.com/ranveersoni98/Xenora/discussions) for general questions if Discussions is enabled. Otherwise, search existing issues before filing a relevant question.
|
||||
- Use [GitHub Issues](https://github.com/MacosPorters/betterxen/issues) for reproducible bugs, feature proposals, research findings and hardware verification reports.
|
||||
- Use [GitHub Discussions](https://github.com/MacosPorters/betterxen/discussions) for general questions if Discussions is enabled. Otherwise, search existing issues before filing a relevant question.
|
||||
- Follow [SECURITY.md](SECURITY.md) for security-sensitive reports.
|
||||
|
||||
Include the exact revision, host architecture, macOS version, relevant tool versions, steps to reproduce and sanitized output. Do not share personal paths, private account information, protected game assets, credentials or confidential material. If the reported feature is not yet implemented, identify it as a request rather than a regression.
|
||||
@@ -15,3 +15,7 @@ Cargo resolves the Rust packages from crates.io at the source checksums in [Carg
|
||||
[LLVM 23.1.6](https://github.com/llvm/llvm-project/tree/5b10d2d74929eae78912771222c9855af97496f4) is used as an external fixture tool under Apache-2.0 WITH LLVM-exception. Xcode and Metal are separate Apple tools under Apple's license terms.
|
||||
|
||||
The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses.
|
||||
|
||||
`crates/victory-shader` is vendored from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (GPL-3.0; authors and provenance in [its UPSTREAM.md](crates/victory-shader/UPSTREAM.md)); it contains opcode names generated from Mesa (MIT, Copyright (c) 2018 Valve Corporation) with the notice kept in `src/gfx10/opcodes.rs`. Its Rust dependencies are `thiserror` (MIT OR Apache-2.0), `zlib-rs` (Zlib), and on Windows targets `windows`/`windows-sys` (MIT OR Apache-2.0); versions are in `Cargo.lock`.
|
||||
|
||||
Microsoft's DirectX Shader Compiler (release v1.9.2609, `dxc_2026_09_29.zip`; University of Illinois/NCSA licence with MIT components per its `LICENSE-LLVM.txt`, `LICENCE-MIT.txt` and `LICENSE-MS.txt`) is used as an external tool to compile the HLSL probes in `workloads/d3d12-wave-probe/hlsl/`; it is not vendored or distributed.
|
||||
+2
-2
@@ -4,10 +4,10 @@
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "Xenora",
|
||||
name: "BetterXen",
|
||||
platforms: [.macOS(.v14)],
|
||||
targets: [
|
||||
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
|
||||
.executableTarget(name: "Xenora", dependencies: ["CXenora"]),
|
||||
.executableTarget(name: "BetterXen", dependencies: ["CXenora"], path: "Sources/Xenora"),
|
||||
]
|
||||
)
|
||||
@@ -638,13 +638,65 @@ final class InspectionModel: ObservableObject {
|
||||
@Published var report = ""
|
||||
@Published var status: Int32 = Int32(XENORA_OK)
|
||||
@Published var busy = false
|
||||
@Published var importing = false
|
||||
/// Why the last file selection could not be used, shown until the next selection.
|
||||
@Published var selectionError: String?
|
||||
|
||||
/// Called when a window is about to show the read-only file importer, from its
|
||||
/// button or File > Open Executable…. Each window presents its own importer.
|
||||
func requestImport() {
|
||||
selectionError = nil
|
||||
}
|
||||
|
||||
/// Handles the importer's completion. A cancelled picker is not a failure.
|
||||
func importFinished(_ result: Result<URL, Error>) {
|
||||
switch result {
|
||||
case .success(let url):
|
||||
inspect(url)
|
||||
case .failure(let error):
|
||||
if let cocoa = error as? CocoaError, cocoa.code == .userCancelled {
|
||||
return
|
||||
}
|
||||
selectionError = "The selected file could not be opened: \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads and reports one file off the main thread. Replaceable only for the
|
||||
/// `--smoke-inspection-order` check.
|
||||
private let reader: @Sendable (URL) -> (Int32, String)
|
||||
/// Number of the latest `inspect` call. Only that call may publish a result.
|
||||
private var latestRequest: UInt64 = 0
|
||||
/// Reads that have finished, whether their result was published or discarded.
|
||||
/// `--smoke-inspection-order` waits on it instead of on a fixed delay.
|
||||
private(set) var finishedReads: UInt64 = 0
|
||||
|
||||
init(reader: @escaping @Sendable (URL) -> (Int32, String) = InspectionModel.run) {
|
||||
self.reader = reader
|
||||
}
|
||||
|
||||
var failed: Bool { !busy && fileName != nil && status != Int32(XENORA_OK) }
|
||||
|
||||
func inspect(_ url: URL) {
|
||||
latestRequest &+= 1
|
||||
let request = latestRequest
|
||||
selectionError = nil
|
||||
fileName = url.lastPathComponent
|
||||
report = ""
|
||||
status = Int32(XENORA_OK)
|
||||
busy = true
|
||||
let reader = reader
|
||||
Task {
|
||||
let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value
|
||||
// The read blocks on file I/O (and, in `--smoke-inspection-order`, on
|
||||
// its gate), so it runs on a Dispatch queue instead of occupying a
|
||||
// Swift concurrency worker that other tasks may need.
|
||||
let (newStatus, newReport) = await withCheckedContinuation { continuation in
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
continuation.resume(returning: reader(url))
|
||||
}
|
||||
}
|
||||
finishedReads &+= 1
|
||||
// A newer selection owns the published state, including `busy`;
|
||||
// an older read that finishes late is discarded.
|
||||
guard request == latestRequest else { return }
|
||||
status = newStatus
|
||||
report = newReport
|
||||
busy = false
|
||||
@@ -685,17 +737,51 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the file importer of the focused window. Absent when no window can
|
||||
/// present it, which disables File > Open Executable….
|
||||
struct OpenExecutableKey: FocusedValueKey {
|
||||
typealias Value = () -> Void
|
||||
}
|
||||
|
||||
extension FocusedValues {
|
||||
var openExecutable: OpenExecutableKey.Value? {
|
||||
get { self[OpenExecutableKey.self] }
|
||||
set { self[OpenExecutableKey.self] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
/// File > Open Executable… (Command-O), routed to the focused window's importer.
|
||||
struct OpenExecutableCommand: Commands {
|
||||
@FocusedValue(\.openExecutable) private var openExecutable
|
||||
|
||||
var body: some Commands {
|
||||
CommandGroup(after: .newItem) {
|
||||
Button("Open Executable…") { openExecutable?() }
|
||||
.keyboardShortcut("o")
|
||||
.disabled(openExecutable == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct InspectorView: View {
|
||||
@ObservedObject var model: InspectionModel
|
||||
let openImporter: () -> Void
|
||||
|
||||
var body: some View {
|
||||
Section("Executable inspection (read-only)") {
|
||||
HStack {
|
||||
Button("Open Executable…") { model.importing = true }
|
||||
Button("Open Executable…") { openImporter() }
|
||||
Text("or drop a file on this window").foregroundStyle(.secondary)
|
||||
}
|
||||
if let error = model.selectionError {
|
||||
Text(error).foregroundStyle(.red)
|
||||
}
|
||||
if let name = model.fileName {
|
||||
LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name)
|
||||
if model.failed {
|
||||
Text("Inspection of \(name) failed (status \(model.status)).")
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
ScrollView {
|
||||
Text(model.report)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
@@ -716,12 +802,19 @@ struct ContentView: View {
|
||||
@ObservedObject var model: FrameModel
|
||||
@ObservedObject var loop: FrameLoopModel
|
||||
@ObservedObject var inspection = InspectionModel.shared
|
||||
/// This window's importer. Kept per window so only the window that asked shows it.
|
||||
@State private var importing = false
|
||||
private var frame: GuestFrame? { model.frame }
|
||||
private var running: Bool { model.running }
|
||||
|
||||
private func openImporter() {
|
||||
inspection.requestImport()
|
||||
importing = true
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
InspectorView(model: inspection)
|
||||
InspectorView(model: inspection, openImporter: openImporter)
|
||||
Section("Guest display") {
|
||||
if let image = frame?.image {
|
||||
Image(decorative: image, scale: 1)
|
||||
@@ -822,8 +915,8 @@ struct ContentView: View {
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in
|
||||
if case .success(let url) = result { inspection.inspect(url) }
|
||||
.fileImporter(isPresented: $importing, allowedContentTypes: [.item]) { result in
|
||||
inspection.importFinished(result)
|
||||
}
|
||||
.dropDestination(for: URL.self) { urls, _ in
|
||||
guard let url = urls.first, url.isFileURL else { return false }
|
||||
@@ -831,16 +924,18 @@ struct ContentView: View {
|
||||
return true
|
||||
}
|
||||
.frame(minWidth: 520, minHeight: 680)
|
||||
.focusedSceneValue(\.openExecutable, openImporter)
|
||||
}
|
||||
}
|
||||
|
||||
struct XenoraApp: App {
|
||||
struct BetterXenApp: App {
|
||||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||||
let model = FrameModel()
|
||||
let loop = FrameLoopModel()
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup("Xenora") { ContentView(model: model, loop: loop) }
|
||||
WindowGroup("BetterXen") { ContentView(model: model, loop: loop) }
|
||||
.commands { OpenExecutableCommand() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1009,10 +1104,122 @@ if CommandLine.arguments.contains("--smoke-frame") {
|
||||
exit(frame.status == XENORA_OK ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-inspection-order` checks that only the latest selection publishes an
|
||||
// inspection result. Files are never read: an injected reader blocks until the check
|
||||
// releases that file, so the check, not timing, decides which read finishes first.
|
||||
// It needs no GPU.
|
||||
if CommandLine.arguments.contains("--smoke-inspection-order") {
|
||||
final class ReadGates: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var gates: [String: DispatchSemaphore] = [:]
|
||||
func gate(_ name: String) -> DispatchSemaphore {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
if let gate = gates[name] { return gate }
|
||||
let gate = DispatchSemaphore(value: 0)
|
||||
gates[name] = gate
|
||||
return gate
|
||||
}
|
||||
func release(_ name: String) { gate(name).signal() }
|
||||
}
|
||||
let gates = ReadGates()
|
||||
// "<scenario>-<a|b>-<ok|fail>"; a gate that is never released times out
|
||||
// instead of hanging, and the check then fails on its own deadline.
|
||||
let reader: @Sendable (URL) -> (Int32, String) = { url in
|
||||
let name = url.lastPathComponent
|
||||
_ = gates.gate(name).wait(timeout: .now() + 10)
|
||||
let status = name.hasSuffix("-ok") ? Int32(XENORA_OK) : Int32(XENORA_INVALID_ARGUMENT)
|
||||
return (status, "report \(name)")
|
||||
}
|
||||
func file(_ name: String) -> URL { URL(fileURLWithPath: "/nonexistent/\(name)") }
|
||||
|
||||
Task { @MainActor in
|
||||
var failures: [String] = []
|
||||
// Waits for the model to finish `count` reads. The deadline only bounds the
|
||||
// check; the order of completions is set by releasing gates.
|
||||
@MainActor func settle(_ model: InspectionModel, _ count: UInt64, _ label: String) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(5)
|
||||
while model.finishedReads < count {
|
||||
if Date() > deadline {
|
||||
failures.append("\(label): read \(count) did not finish")
|
||||
return false
|
||||
}
|
||||
try? await Task.sleep(nanoseconds: 2_000_000)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@MainActor func expect(_ model: InspectionModel, _ name: String, busy: Bool, report: String, ok: Bool, _ label: String) {
|
||||
let actual = "file=\(model.fileName ?? "-") busy=\(model.busy) status=\(model.status) report=\(model.report)"
|
||||
if model.fileName != name || model.busy != busy || model.report != report
|
||||
|| (model.status == Int32(XENORA_OK)) != ok {
|
||||
failures.append("\(label): \(actual)")
|
||||
}
|
||||
}
|
||||
// The newer read finishes first; the older one finishes afterwards and must
|
||||
// change nothing, whatever its outcome.
|
||||
for (scenario, first, second, ok) in [("s1", "a-ok", "b-ok", true), ("s2", "a-fail", "b-ok", true),
|
||||
("s3", "a-ok", "b-fail", false)] {
|
||||
let (older, newer) = ("\(scenario)-\(first)", "\(scenario)-\(second)")
|
||||
let model = InspectionModel(reader: reader)
|
||||
model.inspect(file(older))
|
||||
model.inspect(file(newer))
|
||||
gates.release(newer)
|
||||
if await settle(model, 1, "\(older) then \(newer)") {
|
||||
expect(model, newer, busy: false, report: "report \(newer)", ok: ok, "\(newer) finished")
|
||||
}
|
||||
gates.release(older)
|
||||
if await settle(model, 2, "\(older) then \(newer)") {
|
||||
expect(model, newer, busy: false, report: "report \(newer)", ok: ok, "stale \(older) finished")
|
||||
}
|
||||
}
|
||||
// The older read finishes first and must not clear the newer request's busy state.
|
||||
let model = InspectionModel(reader: reader)
|
||||
model.inspect(file("s4-a-ok"))
|
||||
model.inspect(file("s4-b-fail"))
|
||||
gates.release("s4-a-ok")
|
||||
if await settle(model, 1, "s4") {
|
||||
expect(model, "s4-b-fail", busy: true, report: "", ok: true, "stale s4-a-ok finished first")
|
||||
}
|
||||
gates.release("s4-b-fail")
|
||||
if await settle(model, 2, "s4") {
|
||||
expect(model, "s4-b-fail", busy: false, report: "report s4-b-fail", ok: false, "s4-b-fail finished")
|
||||
}
|
||||
for failure in failures { print("smoke-inspection-order: FAILED \(failure)") }
|
||||
print("smoke-inspection-order: \(failures.isEmpty ? "ok" : "\(failures.count) failed")")
|
||||
exit(failures.isEmpty ? 0 : 1)
|
||||
}
|
||||
dispatchMain()
|
||||
}
|
||||
|
||||
// `--smoke-import-result` checks how a file-importer result reaches the inspector:
|
||||
// a cancelled picker shows nothing, a failure is shown, and a new selection clears it.
|
||||
// No file is opened or read.
|
||||
if CommandLine.arguments.contains("--smoke-import-result") {
|
||||
let ok = MainActor.assumeIsolated { () -> Bool in
|
||||
var failures: [String] = []
|
||||
let model = InspectionModel()
|
||||
model.importFinished(.failure(CocoaError(.userCancelled)))
|
||||
if model.selectionError != nil || model.fileName != nil { failures.append("cancel shows a message") }
|
||||
model.importFinished(.failure(CocoaError(.fileReadNoPermission)))
|
||||
if model.selectionError == nil || model.fileName != nil { failures.append("failure is not shown") }
|
||||
model.requestImport()
|
||||
if model.selectionError != nil { failures.append("reopening keeps the old message") }
|
||||
model.importFinished(.failure(CocoaError(.fileReadNoPermission)))
|
||||
model.inspect(URL(fileURLWithPath: "/nonexistent/import-result-check"))
|
||||
if model.selectionError != nil || model.fileName != "import-result-check" {
|
||||
failures.append("a new selection keeps the old message")
|
||||
}
|
||||
for failure in failures { print("smoke-import-result: FAILED \(failure)") }
|
||||
return failures.isEmpty
|
||||
}
|
||||
print("smoke-import-result: \(ok ? "ok" : "failed")")
|
||||
exit(ok ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
|
||||
if CommandLine.arguments.contains("--smoke") {
|
||||
let probe = RuntimeProbe.run()
|
||||
print(probe.summary)
|
||||
exit(probe.connected ? 0 : 1)
|
||||
}
|
||||
XenoraApp.main()
|
||||
BetterXenApp.main()
|
||||
@@ -17,3 +17,10 @@ path = "src/main.rs"
|
||||
xenora-shader = { path = "../crates/shader" }
|
||||
xenora-ref = { path = "../crates/ref" }
|
||||
xenora-metal = { path = "../crates/metal" }
|
||||
|
||||
[dev-dependencies]
|
||||
xenora-isa = { path = "../crates/isa" }
|
||||
|
||||
[[bench]]
|
||||
name = "gfx1030_identify"
|
||||
harness = false
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original gfx1030 Wave32 instruction stream for metadata identification.
|
||||
s_mov_b32 s12, 0x89abcdef
|
||||
v_add_f32_e32 v4, v5, v9
|
||||
s_cmp_lt_u32 s12, s13
|
||||
ds_read_b32 v8, v2 offset:12
|
||||
v_mov_b32_dpp v9, v6 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf
|
||||
s_add_u32 s16, s17, s18
|
||||
buffer_store_dword v7, off, s[4:7], 0
|
||||
v_fma_f32 v5, v8, v10, 0x3f800003
|
||||
s_movk_i32 s19, 0x2345
|
||||
global_load_dword v3, v[10:11], off
|
||||
v_cmp_lt_u32_e32 vcc_lo, v3, v7
|
||||
s_load_dword s20, s[22:23], 0x20
|
||||
v_pk_add_f16 v3, v4, v6
|
||||
s_waitcnt vmcnt(0)
|
||||
@@ -0,0 +1,143 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CPU-only gfx1030 metadata benchmark.
|
||||
//!
|
||||
//! Run `cargo bench --locked -p xenora-benchmarks --bench gfx1030_identify`
|
||||
//! from the repository root. Repeat the command to collect independent
|
||||
//! first-pass samples. The first pass is the first identification in a fresh
|
||||
//! process with the input already in memory. It does not measure process
|
||||
//! startup or guarantee cold hardware caches. Repeated passes use the same
|
||||
//! stream after the untimed correctness check.
|
||||
//!
|
||||
//! To verify the fixture bytes and instruction lengths independently, run:
|
||||
//! ```sh
|
||||
//! llvm-mc -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
|
||||
//! -show-encoding benchmarks/benches/fixtures/gfx1030_mixed.s
|
||||
//! ```
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use xenora_isa::meta::{EncodingFamily, Identified, identify};
|
||||
|
||||
const COPIES: usize = 4096;
|
||||
const WARM_PASSES: usize = 9;
|
||||
|
||||
// Encodings and lengths come from llvm-mc, one row per instruction in
|
||||
// fixtures/gfx1030_mixed.s. Each word is stored in little-endian order.
|
||||
const FIXTURE: &[(&str, EncodingFamily, &[u32])] = {
|
||||
use EncodingFamily::*;
|
||||
&[
|
||||
("S_MOV_B32", Sop1, &[0xbe8c03ff, 0x89abcdef]),
|
||||
("V_ADD_F32", Vop2, &[0x06081305]),
|
||||
("S_CMP_LT_U32", Sopc, &[0xbf0a0d0c]),
|
||||
("DS_READ_B32", Ds, &[0xd8d8000c, 0x08000002]),
|
||||
("V_MOV_B32", Vop1, &[0x7e1202fa, 0xff004e06]),
|
||||
("S_ADD_U32", Sop2, &[0x80101211]),
|
||||
("BUFFER_STORE_DWORD", Mubuf, &[0xe0700000, 0x80010700]),
|
||||
("V_FMA_F32", Vop3, &[0xd54b0005, 0x03fe1508, 0x3f800003]),
|
||||
("S_MOVK_I32", Sopk, &[0xb0132345]),
|
||||
("GLOBAL_LOAD_DWORD", Global, &[0xdc308000, 0x037d000a]),
|
||||
("V_CMP_LT_U32", Vopc, &[0x7d820f03]),
|
||||
("S_LOAD_DWORD", Smem, &[0xf400050b, 0xfa000020]),
|
||||
("V_PK_ADD_F16", Vop3p, &[0xcc0f4003, 0x1a020d04]),
|
||||
("S_WAITCNT", Sopp, &[0xbf8c3f70]),
|
||||
]
|
||||
};
|
||||
|
||||
fn walk(stream: &[u8], mut observe: impl FnMut(usize, Identified)) -> usize {
|
||||
let mut offset = 0;
|
||||
let mut count = 0;
|
||||
while offset < stream.len() {
|
||||
let identified = identify(&stream[offset..])
|
||||
.unwrap_or_else(|error| panic!("identification failed at byte {offset}: {error}"));
|
||||
observe(offset, identified);
|
||||
offset += identified.len;
|
||||
count += 1;
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
fn verify(stream: &[u8]) {
|
||||
let mut expected_offset = 0;
|
||||
let mut expected = FIXTURE.iter().cycle();
|
||||
let count = walk(stream, |offset, identified| {
|
||||
let &(name, family, words) = expected.next().expect("fixture is nonempty");
|
||||
let len = std::mem::size_of_val(words);
|
||||
assert_eq!(offset, expected_offset, "byte boundary for {name}");
|
||||
assert_eq!(identified.len, len, "length of {name} at byte {offset}");
|
||||
assert_eq!(identified.form.name, name, "mnemonic at byte {offset}");
|
||||
assert_eq!(identified.form.family, family, "family at byte {offset}");
|
||||
expected_offset += len;
|
||||
});
|
||||
assert_eq!(expected_offset, stream.len());
|
||||
assert_eq!(count, COPIES * FIXTURE.len());
|
||||
}
|
||||
|
||||
fn measure(stream: &[u8]) -> Duration {
|
||||
let start = Instant::now();
|
||||
let count = walk(black_box(stream), |_, identified| {
|
||||
black_box(identified);
|
||||
});
|
||||
let elapsed = start.elapsed();
|
||||
assert_eq!(count, COPIES * FIXTURE.len());
|
||||
elapsed
|
||||
}
|
||||
|
||||
fn report(label: &str, elapsed: Duration, byte_count: usize) {
|
||||
let seconds = elapsed.as_secs_f64();
|
||||
let count = (COPIES * FIXTURE.len()) as f64;
|
||||
println!(
|
||||
"{label}: {:.3} ms, {:.2} ns/instruction, {:.2} MiB/s",
|
||||
seconds * 1e3,
|
||||
seconds * 1e9 / count,
|
||||
byte_count as f64 / (1024.0 * 1024.0) / seconds
|
||||
);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let block: Vec<u8> = FIXTURE
|
||||
.iter()
|
||||
.flat_map(|(_, _, words)| words.iter().flat_map(|word| word.to_le_bytes()))
|
||||
.collect();
|
||||
let stream = block.repeat(COPIES);
|
||||
|
||||
// 'cargo test --all-targets' checks the fixture without timing it.
|
||||
if !std::env::args().any(|arg| arg == "--bench") {
|
||||
verify(&stream);
|
||||
return;
|
||||
}
|
||||
|
||||
// Keep the first pass ahead of any metadata lookups. Validate the entire
|
||||
// stream before reporting any timings. That validation also warms the path.
|
||||
let first = measure(&stream);
|
||||
verify(&stream);
|
||||
let mut warm = [Duration::ZERO; WARM_PASSES];
|
||||
for sample in &mut warm {
|
||||
*sample = measure(&stream);
|
||||
}
|
||||
warm.sort_unstable();
|
||||
|
||||
println!(
|
||||
"gfx1030 metadata identification: {} instructions, {} bytes, {} repeated passes",
|
||||
COPIES * FIXTURE.len(),
|
||||
stream.len(),
|
||||
WARM_PASSES
|
||||
);
|
||||
report("First pass in a fresh process", first, stream.len());
|
||||
report("Repeated minimum", warm[0], stream.len());
|
||||
report("Repeated median", warm[WARM_PASSES / 2], stream.len());
|
||||
report("Repeated maximum", warm[WARM_PASSES - 1], stream.len());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn mixed_llvm_fixture_preserves_names_families_lengths_and_boundaries() {
|
||||
let block: Vec<u8> = super::FIXTURE
|
||||
.iter()
|
||||
.flat_map(|(_, _, words)| words.iter().flat_map(|word| word.to_le_bytes()))
|
||||
.collect();
|
||||
super::verify(&block.repeat(super::COPIES));
|
||||
}
|
||||
}
|
||||
+17
-2
@@ -162,10 +162,21 @@ struct BatchResult {
|
||||
pipelined: Stats,
|
||||
}
|
||||
|
||||
mod startup;
|
||||
mod startup_report;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Taken before anything else so a fresh startup child can report the time
|
||||
// from its parent's spawn to `main`.
|
||||
let entered = SystemTime::now();
|
||||
let mut args = std::env::args().skip(1).peekable();
|
||||
match args.peek().map(String::as_str) {
|
||||
Some("startup") => return startup::run(args.skip(1)),
|
||||
Some("startup-child") => return startup::child(entered, args.skip(1)),
|
||||
_ => {}
|
||||
}
|
||||
let mut output = PathBuf::from("benchmarks/results");
|
||||
let mut reps = DEFAULT_REPS;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--output" => {
|
||||
@@ -179,7 +190,11 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
.map_err(|_| "--reps must be a positive integer")?;
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!("usage: xenora-bench [--output DIR] [--reps N]");
|
||||
println!(
|
||||
"usage: xenora-bench [--output DIR] [--reps N]\n \
|
||||
xenora-bench startup [--fixture NAME] [--words N] [--processes N] \
|
||||
[--reps N] [--output DIR]"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
other => return Err(format!("unknown argument {other}").into()),
|
||||
|
||||
@@ -0,0 +1,405 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Metal startup distributions: fresh processes versus repeated submissions (#178).
|
||||
//!
|
||||
//! `xenora-bench startup` checks one manifest fixture against the independent
|
||||
//! reference, then measures it two ways:
|
||||
//!
|
||||
//! - **Fresh process.** It launches its own executable `--processes` times. Each
|
||||
//! child creates the Metal device and queue, translates the fixture, runs it
|
||||
//! once with `run_words_profiled`, checks the output and prints one sample line.
|
||||
//! - **Repeated.** In this process it creates one device, then translates and runs
|
||||
//! the same fixture `--reps` times. The first run is reported on its own.
|
||||
//!
|
||||
//! Every sample must produce the expected words. One wrong output, failed child or
|
||||
//! unparsable sample line stops the run before anything is written. The
|
||||
//! numbers describe this host only; two distributions do not explain each other.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, ENTRY_POINT, compile};
|
||||
|
||||
use crate::startup_report::Report;
|
||||
use crate::{Fixture, Metadata, expand, parse_manifest, percentile, slug};
|
||||
|
||||
const DEFAULT_PROCESSES: usize = 30;
|
||||
const DEFAULT_REPS: usize = 100;
|
||||
/// A fresh process that has not exited by then is killed and fails the run.
|
||||
const CHILD_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Phases of one run, in seconds. `spawn_to_main` exists only for fresh processes.
|
||||
pub(crate) const PHASES: [&str; 8] = [
|
||||
"spawn_to_main",
|
||||
"device",
|
||||
"translate",
|
||||
"library",
|
||||
"pipeline",
|
||||
"submit",
|
||||
"gpu",
|
||||
"readback",
|
||||
];
|
||||
|
||||
/// One run's phase timings, indexed like [`PHASES`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub(crate) struct Sample(pub(crate) [f64; PHASES.len()]);
|
||||
|
||||
impl Sample {
|
||||
fn line(&self) -> String {
|
||||
let fields: Vec<String> = PHASES
|
||||
.iter()
|
||||
.zip(self.0)
|
||||
.map(|(name, value)| format!("{name}={value:e}"))
|
||||
.collect();
|
||||
format!("startup-sample {}", fields.join(" "))
|
||||
}
|
||||
|
||||
/// Parses exactly the line [`Sample::line`] prints: every phase once, in order.
|
||||
pub(crate) fn parse(line: &str) -> Result<Self, String> {
|
||||
let rest = line
|
||||
.strip_prefix("startup-sample ")
|
||||
.ok_or("missing startup-sample prefix")?;
|
||||
let fields: Vec<&str> = rest.split(' ').collect();
|
||||
if fields.len() != PHASES.len() {
|
||||
return Err(format!(
|
||||
"expected {} fields, got {}",
|
||||
PHASES.len(),
|
||||
fields.len()
|
||||
));
|
||||
}
|
||||
let mut sample = Self::default();
|
||||
for (i, (field, name)) in fields.iter().zip(PHASES).enumerate() {
|
||||
let value = field
|
||||
.strip_prefix(name)
|
||||
.and_then(|v| v.strip_prefix('='))
|
||||
.ok_or_else(|| format!("field {i} is not {name}=<seconds>"))?;
|
||||
let value: f64 = value.parse().map_err(|_| format!("bad {name} value"))?;
|
||||
if !value.is_finite() || value < 0.0 {
|
||||
return Err(format!("{name} must be finite and non-negative"));
|
||||
}
|
||||
sample.0[i] = value;
|
||||
}
|
||||
Ok(sample)
|
||||
}
|
||||
}
|
||||
|
||||
/// Median, tail and extremes of one phase.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub(crate) struct Summary {
|
||||
pub(crate) n: usize,
|
||||
pub(crate) min: f64,
|
||||
pub(crate) median: f64,
|
||||
pub(crate) p90: f64,
|
||||
pub(crate) p99: f64,
|
||||
pub(crate) max: f64,
|
||||
}
|
||||
|
||||
pub(crate) fn summarize(values: &[f64]) -> Option<Summary> {
|
||||
if values.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut sorted = values.to_vec();
|
||||
sorted.sort_by(f64::total_cmp);
|
||||
Some(Summary {
|
||||
n: sorted.len(),
|
||||
min: sorted[0],
|
||||
median: percentile(&sorted, 0.5),
|
||||
p90: percentile(&sorted, 0.9),
|
||||
p99: percentile(&sorted, 0.99),
|
||||
max: sorted[sorted.len() - 1],
|
||||
})
|
||||
}
|
||||
|
||||
struct Options {
|
||||
fixture: Option<String>,
|
||||
words: Option<usize>,
|
||||
processes: usize,
|
||||
reps: usize,
|
||||
output: PathBuf,
|
||||
}
|
||||
|
||||
fn count(value: Option<String>, flag: &str) -> Result<usize, String> {
|
||||
let n: usize = value
|
||||
.ok_or_else(|| format!("{flag} needs a count"))?
|
||||
.parse()
|
||||
.map_err(|_| format!("{flag} must be a positive integer"))?;
|
||||
if n == 0 {
|
||||
return Err(format!("{flag} must be at least 1"));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn parse_options(mut args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let mut options = Options {
|
||||
fixture: None,
|
||||
words: None,
|
||||
processes: DEFAULT_PROCESSES,
|
||||
reps: DEFAULT_REPS,
|
||||
output: PathBuf::from("artifacts/startup"),
|
||||
};
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--fixture" => options.fixture = Some(args.next().ok_or("--fixture needs a name")?),
|
||||
"--words" => options.words = Some(count(args.next(), "--words")?),
|
||||
"--processes" => options.processes = count(args.next(), "--processes")?,
|
||||
"--reps" => options.reps = count(args.next(), "--reps")?,
|
||||
"--output" => {
|
||||
options.output = PathBuf::from(args.next().ok_or("--output needs a path")?);
|
||||
}
|
||||
other => return Err(format!("unknown startup argument {other}")),
|
||||
}
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
/// The fixture to time and its word count, after the reference agrees with it.
|
||||
fn select(options: &Options) -> Result<(Fixture, usize), Box<dyn Error>> {
|
||||
let fixtures = parse_manifest(&fs::read_to_string("benchmarks/manifest.toml")?)?;
|
||||
let fixture = match &options.fixture {
|
||||
Some(name) => fixtures.into_iter().find(|f| &f.name == name),
|
||||
None => fixtures.into_iter().next(),
|
||||
}
|
||||
.ok_or("fixture not found in benchmarks/manifest.toml")?;
|
||||
let code = fs::read(&fixture.path)?;
|
||||
let reference = xenora_ref::execute(&code, &fixture.input).map_err(|e| e.to_string())?;
|
||||
if reference != fixture.expected {
|
||||
return Err("reference disagrees with hand-derived expected values".into());
|
||||
}
|
||||
let words = options
|
||||
.words
|
||||
.unwrap_or_else(|| *fixture.sizes.first().unwrap_or(&fixture.input.len()));
|
||||
Ok((fixture, words))
|
||||
}
|
||||
|
||||
/// Translates and runs the fixture once on `metal`, checking the output.
|
||||
fn run_once(
|
||||
metal: &NativeCompute,
|
||||
fixture: &Fixture,
|
||||
words: usize,
|
||||
sample: &mut Sample,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let input = expand(&fixture.input, words);
|
||||
let expected = expand(&fixture.expected, words);
|
||||
let start = Instant::now();
|
||||
let code = fs::read(&fixture.path)?;
|
||||
let compiled = compile(Architecture::Gfx1030, &code).map_err(|e| e.to_string())?;
|
||||
sample.0[2] = start.elapsed().as_secs_f64();
|
||||
let profile = metal
|
||||
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if profile.output != expected {
|
||||
return Err(format!("{} output disagrees with known answers", fixture.name).into());
|
||||
}
|
||||
sample.0[3] = profile.library_seconds;
|
||||
sample.0[4] = profile.pipeline_seconds;
|
||||
sample.0[5] = profile.host_seconds - profile.library_seconds - profile.pipeline_seconds;
|
||||
sample.0[6] = profile.gpu_seconds;
|
||||
sample.0[7] = profile.readback_seconds;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unix_nanos(time: SystemTime) -> u128 {
|
||||
time.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos())
|
||||
}
|
||||
|
||||
/// Entry point of one fresh child process, called first thing in `main`.
|
||||
///
|
||||
/// `entered` is the wall-clock time at `main`; the parent passes the wall-clock
|
||||
/// time just before it spawned this process.
|
||||
pub(crate) fn child(
|
||||
entered: SystemTime,
|
||||
mut args: impl Iterator<Item = String>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let spawned: u128 = args.next().ok_or("missing spawn time")?.parse()?;
|
||||
let options = parse_options(args)?;
|
||||
let (fixture, words) = select(&options)?;
|
||||
let mut sample = Sample::default();
|
||||
sample.0[0] = unix_nanos(entered).saturating_sub(spawned) as f64 / 1e9;
|
||||
let start = Instant::now();
|
||||
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
|
||||
sample.0[1] = start.elapsed().as_secs_f64();
|
||||
run_once(&metal, &fixture, words, &mut sample)?;
|
||||
println!("{}", sample.line());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn forwarded(fixture: &Fixture, words: usize) -> Vec<String> {
|
||||
vec![
|
||||
"--fixture".into(),
|
||||
fixture.name.clone(),
|
||||
"--words".into(),
|
||||
words.to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Runs one fresh child and returns its spawn-to-exit wall time and stdout.
|
||||
///
|
||||
/// The child inherits this process's environment on purpose, so its `MTL_*`
|
||||
/// validation settings are the ones the run's metadata records.
|
||||
fn spawn_child(
|
||||
exe: &std::path::Path,
|
||||
fixture: &Fixture,
|
||||
words: usize,
|
||||
) -> Result<(f64, String), Box<dyn Error>> {
|
||||
let started = Instant::now();
|
||||
let spawned = unix_nanos(SystemTime::now());
|
||||
let mut child = Command::new(exe)
|
||||
.arg("startup-child")
|
||||
.arg(spawned.to_string())
|
||||
.args(forwarded(fixture, words))
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
// Drain both pipes while waiting, so a child that writes more than a pipe
|
||||
// buffer (validation logs, for example) cannot block and look like a hang.
|
||||
let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
|
||||
std::thread::spawn(move || {
|
||||
let mut text = String::new();
|
||||
if let Some(mut pipe) = pipe {
|
||||
let _ = pipe.read_to_string(&mut text);
|
||||
}
|
||||
text
|
||||
})
|
||||
};
|
||||
let out = drain(child.stdout.take().map(|p| Box::new(p) as _));
|
||||
let err = drain(child.stderr.take().map(|p| Box::new(p) as _));
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if started.elapsed() > CHILD_TIMEOUT {
|
||||
child.kill()?;
|
||||
child.wait()?;
|
||||
return Err(format!("no exit within {} s", CHILD_TIMEOUT.as_secs()).into());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
};
|
||||
let seconds = started.elapsed().as_secs_f64();
|
||||
let stdout = out.join().map_err(|_| "stdout reader panicked")?;
|
||||
let stderr = err.join().map_err(|_| "stderr reader panicked")?;
|
||||
if !status.success() {
|
||||
return Err(format!("{status}: {}", stderr.trim()).into());
|
||||
}
|
||||
Ok((seconds, stdout))
|
||||
}
|
||||
|
||||
/// Runs both regimes and writes `startup.json` and `report.md`.
|
||||
pub(crate) fn run(args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
|
||||
let options = parse_options(args)?;
|
||||
let (fixture, words) = select(&options)?;
|
||||
let exe = std::env::current_exe()?;
|
||||
|
||||
let mut fresh = Vec::with_capacity(options.processes);
|
||||
let mut wall = Vec::with_capacity(options.processes);
|
||||
for i in 0..options.processes {
|
||||
let (seconds, stdout) = spawn_child(&exe, &fixture, words)
|
||||
.map_err(|e| format!("fresh process {i} failed: {e}"))?;
|
||||
wall.push(seconds);
|
||||
let line = stdout
|
||||
.lines()
|
||||
.find(|l| l.starts_with("startup-sample "))
|
||||
.ok_or_else(|| format!("fresh process {i} printed no sample"))?;
|
||||
fresh.push(Sample::parse(line).map_err(|e| format!("fresh process {i}: {e}"))?);
|
||||
}
|
||||
|
||||
let mut first = Sample::default();
|
||||
let start = Instant::now();
|
||||
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
|
||||
first.0[1] = start.elapsed().as_secs_f64();
|
||||
run_once(&metal, &fixture, words, &mut first)?;
|
||||
let mut repeated = Vec::with_capacity(options.reps);
|
||||
for _ in 0..options.reps {
|
||||
let mut sample = Sample::default();
|
||||
run_once(&metal, &fixture, words, &mut sample)?;
|
||||
repeated.push(sample);
|
||||
}
|
||||
|
||||
let metadata = Metadata::collect(&metal.device_name(), options.reps);
|
||||
let dir = options
|
||||
.output
|
||||
.join(slug(&metadata.device))
|
||||
.join(&metadata.run_id);
|
||||
fs::create_dir_all(&dir)?;
|
||||
fs::write(dir.join("metadata.json"), metadata.to_json())?;
|
||||
let report = Report {
|
||||
fixture: &fixture.name,
|
||||
words,
|
||||
fresh: &fresh,
|
||||
wall: &wall,
|
||||
first: &first,
|
||||
repeated: &repeated,
|
||||
};
|
||||
fs::write(dir.join("startup.json"), report.json())?;
|
||||
let markdown = report.markdown(&metadata);
|
||||
fs::write(dir.join("report.md"), &markdown)?;
|
||||
println!("{markdown}");
|
||||
println!("Startup results written to {}", dir.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sample_lines_round_trip() {
|
||||
let sample = Sample([0.5, 1e-3, 2.5e-4, 0.0, 7.0, 1e-9, 3.25, 42.0]);
|
||||
assert_eq!(Sample::parse(&sample.line()), Ok(sample));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sample_lines_reject_damaged_input() {
|
||||
let line = Sample([1.0; PHASES.len()]).line();
|
||||
assert!(Sample::parse(&line.replacen("startup-sample", "sample", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("device=", "devise=", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=-1e0", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=NaN", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=x", 1)).is_err());
|
||||
assert!(Sample::parse(line.rsplit_once(' ').unwrap().0).is_err());
|
||||
assert!(Sample::parse(&format!("{line} extra=1")).is_err());
|
||||
// Phases out of order are refused even when every name is present.
|
||||
let swapped = line
|
||||
.replacen("device=", "TMP=", 1)
|
||||
.replacen("translate=", "device=", 1)
|
||||
.replacen("TMP=", "translate=", 1);
|
||||
assert!(Sample::parse(&swapped).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_uses_interpolated_percentiles() {
|
||||
// 1..=100: position 0.9 * 99 = 89.1 lies between 90 and 91, and
|
||||
// 0.99 * 99 = 98.01 between 99 and 100.
|
||||
let values: Vec<f64> = (1..=100).rev().map(f64::from).collect();
|
||||
let s = summarize(&values).unwrap();
|
||||
assert_eq!((s.n, s.min, s.max), (100, 1.0, 100.0));
|
||||
assert!((s.median - 50.5).abs() < 1e-9);
|
||||
assert!((s.p90 - 90.1).abs() < 1e-9);
|
||||
assert!((s.p99 - 99.01).abs() < 1e-9);
|
||||
assert_eq!(summarize(&[]), None);
|
||||
let one = summarize(&[3.0]).unwrap();
|
||||
assert_eq!(
|
||||
(one.median, one.p90, one.p99, one.max),
|
||||
(3.0, 3.0, 3.0, 3.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_reject_bad_counts_and_flags() {
|
||||
let parse = |args: &[&str]| parse_options(args.iter().map(|s| s.to_string()));
|
||||
let defaults = parse(&[]).unwrap();
|
||||
assert_eq!(
|
||||
(defaults.processes, defaults.reps),
|
||||
(DEFAULT_PROCESSES, DEFAULT_REPS)
|
||||
);
|
||||
let set = parse(&["--processes", "3", "--reps", "5", "--words", "64"]).unwrap();
|
||||
assert_eq!((set.processes, set.reps, set.words), (3, 5, Some(64)));
|
||||
assert!(parse(&["--processes", "0"]).is_err());
|
||||
assert!(parse(&["--reps", "-1"]).is_err());
|
||||
assert!(parse(&["--words"]).is_err());
|
||||
assert!(parse(&["--fast"]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! JSON and markdown output of `xenora-bench startup` (#178).
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use crate::startup::{PHASES, Sample, Summary, summarize};
|
||||
use crate::{Metadata, json_str};
|
||||
|
||||
pub(crate) struct Report<'a> {
|
||||
pub(crate) fixture: &'a str,
|
||||
pub(crate) words: usize,
|
||||
pub(crate) fresh: &'a [Sample],
|
||||
pub(crate) wall: &'a [f64],
|
||||
pub(crate) first: &'a Sample,
|
||||
pub(crate) repeated: &'a [Sample],
|
||||
}
|
||||
|
||||
fn column(samples: &[Sample], phase: usize) -> Vec<f64> {
|
||||
samples.iter().map(|s| s.0[phase]).collect()
|
||||
}
|
||||
|
||||
fn summary_json(summary: Option<Summary>) -> String {
|
||||
summary.map_or_else(
|
||||
|| "null".to_string(),
|
||||
|s| {
|
||||
format!(
|
||||
"{{\"n\": {}, \"min\": {:e}, \"median\": {:e}, \"p90\": {:e}, \"p99\": {:e}, \"max\": {:e}}}",
|
||||
s.n, s.min, s.median, s.p90, s.p99, s.max
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
impl Report<'_> {
|
||||
pub(crate) fn json(&self) -> String {
|
||||
let mut out = format!(
|
||||
"{{\n \"fixture\": {},\n \"words\": {},\n \"process_wall\": {},\n",
|
||||
json_str(self.fixture),
|
||||
self.words,
|
||||
summary_json(summarize(self.wall))
|
||||
);
|
||||
for (regime, samples) in [("fresh", self.fresh), ("repeated", self.repeated)] {
|
||||
let _ = writeln!(out, " \"{regime}\": {{");
|
||||
for (i, phase) in PHASES.iter().enumerate() {
|
||||
let comma = if i + 1 < PHASES.len() { "," } else { "" };
|
||||
let summary = if regime == "repeated" && i < 2 {
|
||||
None
|
||||
} else {
|
||||
summarize(&column(samples, i))
|
||||
};
|
||||
let _ = writeln!(out, " \"{phase}\": {}{comma}", summary_json(summary));
|
||||
}
|
||||
out.push_str(" },\n");
|
||||
}
|
||||
let first: Vec<String> = PHASES
|
||||
.iter()
|
||||
.zip(self.first.0)
|
||||
.skip(1)
|
||||
.map(|(p, v)| format!("\"{p}\": {v:e}"))
|
||||
.collect();
|
||||
let _ = writeln!(out, " \"first_in_process\": {{{}}},", first.join(", "));
|
||||
// Raw fresh-process samples in launch order, so a cold first process
|
||||
// (for example an empty Metal shader cache) stays visible.
|
||||
let rows: Vec<String> = self
|
||||
.fresh
|
||||
.iter()
|
||||
.zip(self.wall)
|
||||
.map(|(sample, wall)| {
|
||||
let phases: Vec<String> = sample.0.iter().map(|v| format!("{v:e}")).collect();
|
||||
format!("[{}, {wall:e}]", phases.join(", "))
|
||||
})
|
||||
.collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" \"fresh_samples_columns\": [{}, \"process_wall\"],\n \"fresh_samples\": [\n {}\n ]\n}}",
|
||||
PHASES
|
||||
.iter()
|
||||
.map(|p| json_str(p))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
rows.join(",\n ")
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn markdown(&self, metadata: &Metadata) -> String {
|
||||
let ms = |v: f64| format!("{:.3}", v * 1e3);
|
||||
let mut out = format!(
|
||||
"# Metal startup: `{}`, {} words\n\nDevice {}, {} build, commit `{}`, API validation `{}`, shader validation `{}`, power `{}`, thermal `{}`.\n\nAll values in milliseconds. Fresh: {} processes. Repeated: {} runs after the first in one process. Every sample produced the expected output.\n\n| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
|
||||
self.fixture,
|
||||
self.words,
|
||||
metadata.device,
|
||||
metadata.profile,
|
||||
metadata.commit,
|
||||
metadata.api_validation,
|
||||
metadata.shader_validation,
|
||||
metadata.power,
|
||||
metadata.thermal,
|
||||
self.fresh.len(),
|
||||
self.repeated.len(),
|
||||
);
|
||||
for (i, phase) in PHASES.iter().enumerate() {
|
||||
let fresh = summarize(&column(self.fresh, i));
|
||||
let repeated = (i >= 2)
|
||||
.then(|| summarize(&column(self.repeated, i)))
|
||||
.flatten();
|
||||
let cells = |s: Option<Summary>| {
|
||||
s.map_or_else(
|
||||
|| "– | – | – | –".to_string(),
|
||||
|s| {
|
||||
format!(
|
||||
"{} | {} | {} | {}",
|
||||
ms(s.median),
|
||||
ms(s.p90),
|
||||
ms(s.p99),
|
||||
ms(s.max)
|
||||
)
|
||||
},
|
||||
)
|
||||
};
|
||||
let first = if i == 0 {
|
||||
"–".to_string()
|
||||
} else {
|
||||
ms(self.first.0[i])
|
||||
};
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| `{phase}` | {} | {first} | {} |",
|
||||
cells(fresh),
|
||||
cells(repeated)
|
||||
);
|
||||
}
|
||||
if let Some(s) = summarize(self.wall) {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| process wall (spawn to exit) | {} | {} | {} | {} | – | – | – | – | – |",
|
||||
ms(s.median),
|
||||
ms(s.p90),
|
||||
ms(s.p99),
|
||||
ms(s.max)
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Exercise the benchmark's LLVM-derived fixture during ordinary workspace tests.
|
||||
#[allow(dead_code)]
|
||||
#[path = "../benches/gfx1030_identify.rs"]
|
||||
mod benchmark;
|
||||
@@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "xenora"
|
||||
name = "betterxen"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
+23
-19
@@ -6,11 +6,14 @@ mod shaders;
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
/// Where `probe` writes and `imports sync` reads without `--report`.
|
||||
const DEFAULT_REPORT_DIR: &str = "diagnostics/probe";
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match std::env::args().nth(1).as_deref() {
|
||||
Some("info") => {
|
||||
println!(
|
||||
"Xenora {} ({})",
|
||||
"BetterXen {} ({})",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
std::env::consts::ARCH
|
||||
);
|
||||
@@ -18,7 +21,7 @@ fn main() -> ExitCode {
|
||||
}
|
||||
Some("inspect") => {
|
||||
let Some(file_path) = std::env::args().nth(2) else {
|
||||
eprintln!("usage: xenora inspect <path-to-pe-binary>");
|
||||
eprintln!("usage: betterxen inspect <path-to-pe-binary>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
match xenora_loader::triage_file(&file_path) {
|
||||
@@ -46,7 +49,7 @@ fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let mut pe_path: Option<String> = None;
|
||||
let mut mode = "static".to_string();
|
||||
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
|
||||
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
|
||||
|
||||
let mut i = 2;
|
||||
while i < args.len() {
|
||||
@@ -87,7 +90,7 @@ fn main() -> ExitCode {
|
||||
|
||||
let Some(pe) = pe_path else {
|
||||
eprintln!(
|
||||
"usage: xenora probe --pe <path> [--mode <static>] [--report <output-dir>]"
|
||||
"usage: betterxen probe --pe <path> [--mode <static>] [--report <output-dir>]"
|
||||
);
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
@@ -108,7 +111,7 @@ fn main() -> ExitCode {
|
||||
let config = xenora_loader::ProbeConfig::default();
|
||||
match xenora_loader::run_probe_and_export(&bytes, &report_dir, &config) {
|
||||
Ok(report) => {
|
||||
println!("Xenora static PE probe complete.");
|
||||
println!("BetterXen static PE probe complete.");
|
||||
println!("Artifacts exported to: {report_dir}");
|
||||
println!("Sections: {}", report.parsed.sections.len());
|
||||
println!("Relocations: {}", report.relocations.total_entries);
|
||||
@@ -134,19 +137,19 @@ fn main() -> ExitCode {
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports|shaders>");
|
||||
eprintln!("usage: betterxen <info|demo|inspect|probe|run|imports|shaders>");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `xenora imports sync [--report <dir>] [--check]`
|
||||
/// `xenora imports generate --pe <path> [--out <dir>]`
|
||||
/// `xenora imports metadata sync [--out <dir>]`
|
||||
/// `xenora imports verify`
|
||||
/// `betterxen imports sync [--report <dir>] [--check]`
|
||||
/// `betterxen imports generate --pe <path> [--out <dir>]`
|
||||
/// `betterxen imports metadata sync [--out <dir>]`
|
||||
/// `betterxen imports verify`
|
||||
fn imports_command(args: Vec<String>) -> ExitCode {
|
||||
if args.is_empty() {
|
||||
eprintln!("usage: xenora imports <sync|generate|metadata|verify> [options]");
|
||||
eprintln!("usage: betterxen imports <sync|generate|metadata|verify> [options]");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
|
||||
@@ -157,7 +160,7 @@ fn imports_command(args: Vec<String>) -> ExitCode {
|
||||
"verify" => run_imports_verify_cli(&args[1..]),
|
||||
other => {
|
||||
eprintln!("unknown imports subcommand: {other}");
|
||||
eprintln!("usage: xenora imports <sync|generate|metadata|verify> [options]");
|
||||
eprintln!("usage: betterxen imports <sync|generate|metadata|verify> [options]");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
@@ -328,7 +331,7 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode {
|
||||
}
|
||||
} else {
|
||||
eprintln!(
|
||||
"usage: xenora imports generate <--pe <executable> | --csv <missing_imports.csv>> [--out <dir>]"
|
||||
"usage: betterxen imports generate <--pe <executable> | --csv <missing_imports.csv>> [--out <dir>]"
|
||||
);
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
@@ -373,7 +376,7 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode {
|
||||
}
|
||||
|
||||
fn run_imports_sync_cli(args: &[String]) -> ExitCode {
|
||||
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
|
||||
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
|
||||
let mut check_mode = false;
|
||||
|
||||
let mut i = 0;
|
||||
@@ -434,9 +437,10 @@ fn run_imports_sync(
|
||||
|
||||
let imports_csv_path = std::path::Path::new(report_dir).join("imports.csv");
|
||||
if !imports_csv_path.exists() {
|
||||
return Err(
|
||||
format!("imports.csv not found in '{report_dir}'. Run `xenora probe` first.").into(),
|
||||
);
|
||||
return Err(format!(
|
||||
"imports.csv not found in '{report_dir}'. Run `betterxen probe` first."
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
// Build the standard registry to get current implementation state.
|
||||
@@ -522,11 +526,11 @@ fn run_imports_sync(
|
||||
|
||||
// Build the refreshed import_backlog.md.
|
||||
let mut md = String::new();
|
||||
let _ = writeln!(md, "# Xenora import compatibility backlog");
|
||||
let _ = writeln!(md, "# BetterXen import compatibility backlog");
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"Generated by `xenora imports sync`. Do not edit manually."
|
||||
"Generated by `betterxen imports sync`. Do not edit manually."
|
||||
);
|
||||
let _ = writeln!(
|
||||
md,
|
||||
|
||||
+120
-17
@@ -2,10 +2,10 @@
|
||||
|
||||
use std::error::Error;
|
||||
use std::ffi::OsString;
|
||||
use std::fs::{self, File};
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitCode, Stdio};
|
||||
use std::process::{Child, Command, ExitCode, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -16,6 +16,10 @@ use xenora_loader::{
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
#[path = "startup_report.rs"]
|
||||
mod startup_report;
|
||||
use startup_report::{Events, JOURNAL_ERROR_EXIT, Journal, Termination, WATCHDOG_EXIT};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
const SERVICES_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/runtime-services.exe");
|
||||
const WALL_LIMIT: Duration = Duration::from_secs(15);
|
||||
@@ -27,7 +31,7 @@ const TICKET: u64 = 17;
|
||||
const DRAW_RESULT: u64 = 0x42;
|
||||
const EXTENT: [usize; 2] = [4, 3];
|
||||
const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255];
|
||||
const USAGE: &str = "usage: xenora run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>]";
|
||||
const USAGE: &str = "usage: betterxen run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>] [--startup-report <path>]";
|
||||
|
||||
struct Options {
|
||||
path: PathBuf,
|
||||
@@ -35,6 +39,8 @@ struct Options {
|
||||
worker: bool,
|
||||
trace: bool,
|
||||
hud: bool,
|
||||
report: Option<PathBuf>,
|
||||
journal: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
@@ -42,6 +48,8 @@ impl Options {
|
||||
let mut args = args.into_iter();
|
||||
let mut path = None;
|
||||
let mut max_steps = None;
|
||||
let mut report = None;
|
||||
let mut journal = None;
|
||||
let (mut experimental, mut trace, mut hud, mut worker) = (false, false, false, false);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.to_str() {
|
||||
@@ -56,6 +64,16 @@ impl Options {
|
||||
.ok_or("--max-steps must be in 1..=10000")?,
|
||||
);
|
||||
}
|
||||
Some("--startup-report") if report.is_none() => {
|
||||
report = Some(PathBuf::from(
|
||||
args.next().ok_or("missing --startup-report path")?,
|
||||
));
|
||||
}
|
||||
Some("--startup-journal") if journal.is_none() => {
|
||||
journal = Some(PathBuf::from(
|
||||
args.next().ok_or("missing worker journal path")?,
|
||||
));
|
||||
}
|
||||
Some("--experimental") if !experimental => experimental = true,
|
||||
Some("--trace") if !trace => trace = true,
|
||||
Some("--metal-hud") if !hud => hud = true,
|
||||
@@ -66,12 +84,17 @@ impl Options {
|
||||
if !experimental {
|
||||
return Err("run requires --experimental".into());
|
||||
}
|
||||
if (worker && report.is_some()) || (!worker && journal.is_some()) {
|
||||
return Err("invalid startup report option for this process".into());
|
||||
}
|
||||
Ok(Self {
|
||||
path: path.ok_or("missing --pe path")?,
|
||||
max_steps: max_steps.unwrap_or(DEFAULT_STEPS),
|
||||
worker,
|
||||
trace,
|
||||
hud,
|
||||
report,
|
||||
journal,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -85,7 +108,7 @@ pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
|
||||
}
|
||||
};
|
||||
let result = if options.worker {
|
||||
run_worker(&options).map(|()| ExitCode::SUCCESS)
|
||||
worker_command(&options)
|
||||
} else {
|
||||
launch_worker(&options)
|
||||
};
|
||||
@@ -99,8 +122,26 @@ pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
|
||||
}
|
||||
|
||||
fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
|
||||
let journal = options
|
||||
.report
|
||||
.as_ref()
|
||||
.map(|_| Journal::create())
|
||||
.transpose()?;
|
||||
let executable = std::env::current_exe()?;
|
||||
let destination = options
|
||||
.report
|
||||
.as_ref()
|
||||
.map(|path| {
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)
|
||||
.map_err(|error| format!("could not create startup report: {error}"))
|
||||
})
|
||||
.transpose()?;
|
||||
let started = Instant::now();
|
||||
let mut child = Command::new(std::env::current_exe()?)
|
||||
let mut command = Command::new(executable);
|
||||
command
|
||||
.args([
|
||||
"run",
|
||||
"--experimental",
|
||||
@@ -112,29 +153,73 @@ fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
|
||||
.arg(options.max_steps.to_string())
|
||||
.arg("--pe")
|
||||
.arg(&options.path)
|
||||
.stdin(Stdio::null())
|
||||
.spawn()?;
|
||||
.stdin(Stdio::null());
|
||||
if let Some(journal) = &journal {
|
||||
command.arg("--startup-journal").arg(journal.path());
|
||||
}
|
||||
let termination = command
|
||||
.spawn()
|
||||
.and_then(|child| supervise(child, started, WALL_LIMIT));
|
||||
if let (Some(journal), Some(destination)) = (&journal, destination)
|
||||
&& let Err(error) = journal.finish(destination, &termination)
|
||||
{
|
||||
eprintln!("could not write startup report: {error}");
|
||||
if matches!(&termination, Ok(Termination::Exited(status)) if status.success()) {
|
||||
return Ok(ExitCode::FAILURE);
|
||||
}
|
||||
}
|
||||
match termination? {
|
||||
Termination::Exited(status) => match status.code() {
|
||||
Some(code) => Ok(ExitCode::from(u8::try_from(code)?)),
|
||||
None => Err(format!("worker terminated: {status}").into()),
|
||||
},
|
||||
Termination::Deadline => {
|
||||
Err("experimental worker exceeded its 15 second wall deadline".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn supervise(mut child: Child, started: Instant, limit: Duration) -> std::io::Result<Termination> {
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
return match status.code() {
|
||||
Some(code) => Ok(ExitCode::from(u8::try_from(code)?)),
|
||||
None => Err(format!("worker terminated: {status}").into()),
|
||||
};
|
||||
}
|
||||
Ok(None) if started.elapsed() < WALL_LIMIT => {
|
||||
Ok(Some(status)) => return Ok(Termination::Exited(status)),
|
||||
Ok(None) if started.elapsed() < limit => {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
status => {
|
||||
let _ = child.kill();
|
||||
child.wait()?;
|
||||
status?;
|
||||
return Err("experimental worker exceeded its 15 second wall deadline".into());
|
||||
return Ok(Termination::Deadline);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn worker_command(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
|
||||
let mut events = match options.journal.as_deref().map(Events::open).transpose() {
|
||||
Ok(events) => events,
|
||||
Err(error) => {
|
||||
eprintln!("could not open startup journal: {error}");
|
||||
return Ok(ExitCode::from(JOURNAL_ERROR_EXIT));
|
||||
}
|
||||
};
|
||||
let result = run_worker(options, events.as_mut());
|
||||
if let Some(events) = events.as_mut() {
|
||||
if let Err(error) = &result {
|
||||
events.failure(error.as_ref());
|
||||
}
|
||||
if let Some(error) = events.write_error() {
|
||||
if let Err(error) = result {
|
||||
eprintln!("run failed: {error}");
|
||||
}
|
||||
eprintln!("could not write startup journal: {error}");
|
||||
return Ok(ExitCode::from(JOURNAL_ERROR_EXIT));
|
||||
}
|
||||
}
|
||||
result.map(|()| ExitCode::SUCCESS)
|
||||
}
|
||||
|
||||
fn verify_fixture(path: &Path) -> Result<&'static [u8], Box<dyn Error>> {
|
||||
let valid_metadata =
|
||||
|metadata: fs::Metadata| metadata.is_file() && metadata.len() == FIXTURE.len() as u64;
|
||||
@@ -158,14 +243,14 @@ fn verify_fixture(path: &Path) -> Result<&'static [u8], Box<dyn Error>> {
|
||||
.ok_or_else(|| rejection.into())
|
||||
}
|
||||
|
||||
fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
fn run_worker(options: &Options, mut events: Option<&mut Events>) -> Result<(), Box<dyn Error>> {
|
||||
std::thread::Builder::new()
|
||||
.name("xenora-deadline".into())
|
||||
.spawn(|| {
|
||||
std::thread::sleep(WALL_LIMIT);
|
||||
// The supervisor also enforces this deadline. The worker retains
|
||||
// its own deadline if it is invoked directly.
|
||||
std::process::exit(124);
|
||||
std::process::exit(i32::from(WATCHDOG_EXIT));
|
||||
})?;
|
||||
let fixture = verify_fixture(&options.path)?;
|
||||
let (name, ticket, bound_imports) = if fixture == SERVICES_FIXTURE {
|
||||
@@ -232,6 +317,16 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
imports,
|
||||
options.max_steps,
|
||||
|event| {
|
||||
if let Some(events) = events.as_deref_mut() {
|
||||
events.stage(match &event {
|
||||
StartupEvent::Parsed { .. } => "parsed",
|
||||
StartupEvent::Mapped { .. } => "mapped",
|
||||
StartupEvent::Relocated { .. } => "relocated",
|
||||
StartupEvent::ImportsBound { .. } => "imports_bound",
|
||||
StartupEvent::TlsCompleted { .. } => "tls_completed",
|
||||
StartupEvent::Entering { .. } => "entry",
|
||||
});
|
||||
}
|
||||
if options.trace {
|
||||
trace_startup(event);
|
||||
}
|
||||
@@ -244,6 +339,11 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
.take();
|
||||
let exit = startup.execution.exit_reason;
|
||||
let rax = startup.execution.final_state.get(Register::Rax);
|
||||
if exit == ExitReason::Halt
|
||||
&& let Some(events) = events.as_deref_mut()
|
||||
{
|
||||
events.stage("exit");
|
||||
}
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace stage=exit entry_steps={} exit={exit:?} rax={rax:#x}",
|
||||
@@ -264,6 +364,9 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
return Err("trusted fixture startup or result differs from the expected values".into());
|
||||
}
|
||||
let frame = result.ok_or("guest halted without a draw")??;
|
||||
if let Some(events) = events {
|
||||
events.stage("framebuffer");
|
||||
}
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace stage=framebuffer extent={}x{} verified_pixels={}",
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! `xenora shaders`: instruction inventory and stream inspection.
|
||||
//! `betterxen shaders`: instruction inventory and stream inspection.
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode_at};
|
||||
use xenora_isa::meta::{self, EncodingFamily, FORMS, identify};
|
||||
|
||||
const USAGE: &str = "usage: xenora shaders <coverage [--json] | inspect <gfx1030.bin>>";
|
||||
const USAGE: &str = "usage: betterxen shaders <coverage [--json] | inspect <gfx1030.bin>>";
|
||||
|
||||
pub fn command(args: &[String]) -> ExitCode {
|
||||
match args.first().map(String::as_str) {
|
||||
@@ -109,7 +109,7 @@ fn inspect(path: &str) -> ExitCode {
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// The printed rows of `xenora shaders inspect`, the number of rows that do
|
||||
/// The printed rows of `betterxen shaders inspect`, the number of rows that do
|
||||
/// not decode into executable instructions and the identification failure
|
||||
/// that ended the stream early, if any.
|
||||
struct Listing {
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitStatus;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
pub(super) const WATCHDOG_EXIT: u8 = 124;
|
||||
pub(super) const JOURNAL_ERROR_EXIT: u8 = 125;
|
||||
const VERSION: &str = "1";
|
||||
const RECORD_SEPARATOR: char = '\t';
|
||||
const MAX_BYTES: usize = 8192;
|
||||
const MAX_ERROR_BYTES: usize = 2048;
|
||||
const STAGES: [&str; 8] = [
|
||||
"parsed",
|
||||
"mapped",
|
||||
"relocated",
|
||||
"imports_bound",
|
||||
"tls_completed",
|
||||
"entry",
|
||||
"exit",
|
||||
"framebuffer",
|
||||
];
|
||||
|
||||
pub(super) struct Journal(PathBuf);
|
||||
|
||||
impl Journal {
|
||||
pub(super) fn create() -> io::Result<Self> {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
loop {
|
||||
let id = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("betterxen-startup-{}-{id}", std::process::id()));
|
||||
match fs::DirBuilder::new().mode(0o700).create(&directory) {
|
||||
Ok(()) => return Ok(Self(directory)),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn path(&self) -> PathBuf {
|
||||
self.0.join("events")
|
||||
}
|
||||
|
||||
fn read(&self) -> Report {
|
||||
let mut bytes = Vec::new();
|
||||
match File::open(self.path())
|
||||
.and_then(|file| file.take((MAX_BYTES + 1) as u64).read_to_end(&mut bytes))
|
||||
{
|
||||
Ok(_) => Report::parse(&bytes),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Report::default(),
|
||||
Err(_) => Report {
|
||||
integrity: "unreadable",
|
||||
..Report::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn finish(
|
||||
&self,
|
||||
mut destination: File,
|
||||
termination: &io::Result<Termination>,
|
||||
) -> io::Result<()> {
|
||||
destination.write_all(self.read().json(termination).as_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Journal {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_file(self.path());
|
||||
let _ = fs::remove_dir(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Events(File, Option<io::Error>);
|
||||
|
||||
impl Events {
|
||||
pub(super) fn open(path: &Path) -> io::Result<Self> {
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)
|
||||
.map(|file| Self(file, None))
|
||||
}
|
||||
|
||||
pub(super) fn stage(&mut self, stage: &str) {
|
||||
self.record(format_args!("{VERSION}\t{stage}"));
|
||||
}
|
||||
|
||||
pub(super) fn failure(&mut self, error: &dyn std::error::Error) {
|
||||
let message = error.to_string();
|
||||
let end = message.floor_char_boundary(MAX_ERROR_BYTES);
|
||||
let mut encoded = String::with_capacity(end * 2);
|
||||
for byte in message[..end].bytes() {
|
||||
write!(encoded, "{byte:02x}").unwrap();
|
||||
}
|
||||
self.record(format_args!(
|
||||
"{VERSION}\tfailure\t{}\t{encoded}",
|
||||
u8::from(end < message.len())
|
||||
));
|
||||
}
|
||||
fn record(&mut self, arguments: std::fmt::Arguments<'_>) {
|
||||
if self.1.is_none() {
|
||||
self.1 = writeln!(self.0, "{arguments}").err();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn write_error(&self) -> Option<&io::Error> {
|
||||
self.1.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) enum Termination {
|
||||
Exited(ExitStatus),
|
||||
Deadline,
|
||||
}
|
||||
|
||||
struct Report {
|
||||
completed: usize,
|
||||
error: Option<String>,
|
||||
error_truncated: bool,
|
||||
integrity: &'static str,
|
||||
}
|
||||
|
||||
impl Default for Report {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
completed: 0,
|
||||
error: None,
|
||||
error_truncated: false,
|
||||
integrity: "complete",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Report {
|
||||
fn parse(bytes: &[u8]) -> Self {
|
||||
let mut report = Self::default();
|
||||
let bounded = &bytes[..bytes.len().min(MAX_BYTES)];
|
||||
for line in bounded.split_inclusive(|&byte| byte == b'\n') {
|
||||
let Some(line) = line.strip_suffix(b"\n") else {
|
||||
report.integrity = "truncated";
|
||||
break;
|
||||
};
|
||||
if !std::str::from_utf8(line).is_ok_and(|line| report.record(line)) {
|
||||
report.integrity = "malformed";
|
||||
break;
|
||||
}
|
||||
}
|
||||
if bytes.len() > MAX_BYTES {
|
||||
report.integrity = "oversized";
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
fn record(&mut self, line: &str) -> bool {
|
||||
let Some((VERSION, record)) = line.split_once(RECORD_SEPARATOR) else {
|
||||
return false;
|
||||
};
|
||||
if self.error.is_some() {
|
||||
return false;
|
||||
}
|
||||
if STAGES.get(self.completed) == Some(&record) {
|
||||
self.completed += 1;
|
||||
return true;
|
||||
}
|
||||
let Some((truncated, encoded)) = record
|
||||
.strip_prefix("failure\t")
|
||||
.and_then(|s| s.split_once('\t'))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(truncated, "0" | "1")
|
||||
|| encoded.len() > MAX_ERROR_BYTES * 2
|
||||
|| !encoded.len().is_multiple_of(2)
|
||||
|| !encoded.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let (pairs, _) = encoded.as_bytes().as_chunks::<2>();
|
||||
let Some(message) = pairs
|
||||
.iter()
|
||||
.map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok())
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.and_then(|bytes| String::from_utf8(bytes).ok())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
self.error = Some(message);
|
||||
self.error_truncated = truncated == "1";
|
||||
true
|
||||
}
|
||||
|
||||
fn json(&self, termination: &io::Result<Termination>) -> String {
|
||||
let unwritable = matches!(termination, Ok(Termination::Exited(status))
|
||||
if status.code() == Some(i32::from(JOURNAL_ERROR_EXIT)));
|
||||
let integrity = if unwritable {
|
||||
"unwritable"
|
||||
} else {
|
||||
self.integrity
|
||||
};
|
||||
let (outcome, status, detail) = match termination {
|
||||
Ok(Termination::Deadline) => (
|
||||
"timeout",
|
||||
None,
|
||||
Some("worker exceeded the wall deadline".into()),
|
||||
),
|
||||
Err(error) => ("unknown", None, Some(error.to_string())),
|
||||
Ok(Termination::Exited(status)) if status.code() == Some(i32::from(WATCHDOG_EXIT)) => (
|
||||
"timeout",
|
||||
Some(status),
|
||||
Some("worker watchdog expired".into()),
|
||||
),
|
||||
Ok(Termination::Exited(status)) if unwritable => (
|
||||
"unknown",
|
||||
Some(status),
|
||||
Some("worker could not write its startup journal".into()),
|
||||
),
|
||||
Ok(Termination::Exited(status))
|
||||
if status.success()
|
||||
&& self.error.is_none()
|
||||
&& self.completed == STAGES.len()
|
||||
&& self.integrity == "complete" =>
|
||||
{
|
||||
("verified", Some(status), None)
|
||||
}
|
||||
Ok(Termination::Exited(status))
|
||||
if status.code().is_some() && !status.success() && self.error.is_some() =>
|
||||
{
|
||||
("stage_failure", Some(status), None)
|
||||
}
|
||||
Ok(Termination::Exited(status)) if status.code().is_some() && !status.success() => {
|
||||
("early_exit", Some(status), Some(status.to_string()))
|
||||
}
|
||||
Ok(Termination::Exited(status)) => ("unknown", Some(status), Some(status.to_string())),
|
||||
};
|
||||
let stages = &STAGES[..self.completed];
|
||||
let records = stages
|
||||
.iter()
|
||||
.map(|stage| format!(r#"{{"schema_version":{VERSION},"stage":"{stage}"}}"#))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let last = json_string(stages.last().copied());
|
||||
let error = json_string(self.error.as_deref());
|
||||
let detail = json_string(detail.as_deref());
|
||||
let code = status
|
||||
.and_then(|status| status.code())
|
||||
.map_or("null".into(), |code| code.to_string());
|
||||
format!(
|
||||
"{{\"schema_version\":{VERSION},\"outcome\":\"{outcome}\",\"last_completed_stage\":{last},\"record_integrity\":\"{}\",\"worker_exit_code\":{code},\"termination_detail\":{detail},\"error\":{error},\"error_truncated\":{},\"stages\":[{records}]}}\n",
|
||||
integrity, self.error_truncated
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn json_string(value: Option<&str>) -> String {
|
||||
let Some(value) = value else {
|
||||
return String::from("null");
|
||||
};
|
||||
let mut escaped = String::from("\"");
|
||||
for ch in value.chars() {
|
||||
match ch {
|
||||
'"' => escaped.push_str("\\\""),
|
||||
'\\' => escaped.push_str("\\\\"),
|
||||
'\0'..='\u{1f}' => write!(escaped, "\\u{:04x}", u32::from(ch)).unwrap(),
|
||||
_ => escaped.push(ch),
|
||||
}
|
||||
}
|
||||
escaped.push('"');
|
||||
escaped
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[test]
|
||||
fn journal_write_error_surfaces_in_report() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let journal = Journal::create().unwrap();
|
||||
fs::write(journal.path(), b"1\tparsed\n").unwrap();
|
||||
let mut events = Events(File::open(journal.path()).unwrap(), None);
|
||||
events.stage("mapped");
|
||||
assert!(events.write_error().is_some());
|
||||
let status = ExitStatus::from_raw(i32::from(JOURNAL_ERROR_EXIT) << 8);
|
||||
let result = journal.read().json(&Ok(Termination::Exited(status)));
|
||||
assert!(
|
||||
result.contains(r#""record_integrity":"unwritable""#),
|
||||
"{result}"
|
||||
);
|
||||
assert!(
|
||||
result.contains(r#""last_completed_stage":"parsed""#),
|
||||
"{result}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_failure_keeps_signal_detail_after_all_stages() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let journal = Journal::create().unwrap();
|
||||
let mut events = Events::open(&journal.path()).unwrap();
|
||||
for stage in STAGES {
|
||||
events.stage(stage);
|
||||
}
|
||||
events.failure(&io::Error::other("late error"));
|
||||
let report = journal.read();
|
||||
assert_eq!(report.integrity, "complete");
|
||||
let result = report.json(&Ok(Termination::Exited(ExitStatus::from_raw(15))));
|
||||
assert!(result.contains(r#""outcome":"unknown""#), "{result}");
|
||||
assert!(result.contains(r#""error":"late error""#), "{result}");
|
||||
assert!(result.contains("signal: 15"), "{result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supervisor_distinguishes_early_exit_watchdog_signal_and_deadline() {
|
||||
for (script, limit, outcome, code) in [
|
||||
("exit 9", Duration::from_secs(2), "early_exit", "9"),
|
||||
("exit 124", Duration::from_secs(2), "timeout", "124"),
|
||||
("kill -TERM $$", Duration::from_secs(2), "unknown", "null"),
|
||||
(
|
||||
"exec sleep 5",
|
||||
Duration::from_millis(250),
|
||||
"timeout",
|
||||
"null",
|
||||
),
|
||||
] {
|
||||
let journal = Journal::create().unwrap();
|
||||
let started = Instant::now();
|
||||
let child = Command::new("/bin/sh")
|
||||
.args([
|
||||
"-c",
|
||||
&format!("printf '1\\tparsed\\n' > \"$1\"; {script}"),
|
||||
"worker",
|
||||
])
|
||||
.arg(journal.path())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let termination = super::super::supervise(child, started, limit);
|
||||
let report = journal.read().json(&termination);
|
||||
assert!(
|
||||
report.contains(&format!(r#""outcome":"{outcome}""#)),
|
||||
"{report}"
|
||||
);
|
||||
assert!(
|
||||
report.contains(&format!(r#""worker_exit_code":{code}"#)),
|
||||
"{report}"
|
||||
);
|
||||
assert!(
|
||||
report.contains(r#""last_completed_stage":"parsed""#),
|
||||
"{report}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_records_keep_only_the_valid_prefix() {
|
||||
let mut oversized = b"1\tparsed\n1\tmapped".to_vec();
|
||||
oversized.resize(MAX_BYTES + 1, b'x');
|
||||
for (bytes, integrity) in [
|
||||
(&b"1\tparsed\n1\tmapped"[..], "truncated"),
|
||||
(&b"1\tparsed\n1\tentry\n1\tmapped\n"[..], "malformed"),
|
||||
(&b"1\tparsed\n1\tfailure\t0\tqq\n"[..], "malformed"),
|
||||
(oversized.as_slice(), "oversized"),
|
||||
] {
|
||||
let journal = Journal::create().unwrap();
|
||||
fs::write(journal.path(), bytes).unwrap();
|
||||
let report = journal.read();
|
||||
assert_eq!(report.completed, 1);
|
||||
assert_eq!(report.integrity, integrity);
|
||||
assert!(report.error.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_preserves_original_context_with_bounded_utf8() {
|
||||
let journal = Journal::create().unwrap();
|
||||
let mut events = Events::open(&journal.path()).unwrap();
|
||||
events.stage("parsed");
|
||||
let message = format!("line\nwith \"quote\" and \\{}", "é".repeat(MAX_ERROR_BYTES));
|
||||
events.failure(&io::Error::other(&message[..]));
|
||||
let report = journal.read();
|
||||
assert_eq!(
|
||||
report.error.as_deref(),
|
||||
Some(&message[..message.floor_char_boundary(MAX_ERROR_BYTES)])
|
||||
);
|
||||
assert!(report.error_truncated);
|
||||
let json = report.json(&Ok(Termination::Deadline));
|
||||
assert!(
|
||||
json.contains(r#"line\u000awith \"quote\" and \\"#),
|
||||
"{json}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Default report folder of `betterxen probe` and `betterxen imports sync`.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn probe_and_sync_use_the_same_default_folder() {
|
||||
let fixture = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/delay-imports.exe"
|
||||
);
|
||||
let folder = std::env::temp_dir().join(format!("xenora-default-{}", std::process::id()));
|
||||
std::fs::create_dir(&folder).unwrap();
|
||||
for arguments in [&["probe", "--pe", fixture][..], &["imports", "sync"]] {
|
||||
let status = Command::new(env!("CARGO_BIN_EXE_betterxen"))
|
||||
.args(arguments)
|
||||
.current_dir(&folder)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "{arguments:?}");
|
||||
}
|
||||
let written = ["imports.csv", "import_backlog.md"]
|
||||
.map(|name| folder.join("diagnostics/probe").join(name).is_file());
|
||||
std::fs::remove_dir_all(folder).unwrap();
|
||||
assert_eq!(written, [true, true]);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! `xenora imports sync` over a probe report that lists delay-loaded imports.
|
||||
//! `betterxen imports sync` over a probe report that lists delay-loaded imports.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
@@ -13,8 +13,8 @@ fn backlog_leaves_out_delay_loaded_imports() {
|
||||
"/../../fixtures/pe/delay-imports.exe"
|
||||
);
|
||||
let report = std::env::temp_dir().join(format!("xenora-sync-delayed-{}", std::process::id()));
|
||||
let xenora = |arguments: &[&str]| {
|
||||
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
|
||||
let betterxen = |arguments: &[&str]| {
|
||||
let status = Command::new(env!("CARGO_BIN_EXE_betterxen"))
|
||||
.args(arguments)
|
||||
.arg("--report")
|
||||
.arg(&report)
|
||||
@@ -22,8 +22,8 @@ fn backlog_leaves_out_delay_loaded_imports() {
|
||||
.unwrap();
|
||||
assert!(status.success(), "{arguments:?}");
|
||||
};
|
||||
xenora(&["probe", "--pe", fixture]);
|
||||
xenora(&["imports", "sync"]);
|
||||
betterxen(&["probe", "--pe", fixture]);
|
||||
betterxen(&["imports", "sync"]);
|
||||
let listed = std::fs::read_to_string(report.join("imports.csv")).unwrap();
|
||||
let backlog = std::fs::read_to_string(report.join("import_backlog.md")).unwrap();
|
||||
std::fs::remove_dir_all(report).unwrap();
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
const STARTUP_STAGES: &[&str] = &[
|
||||
"parsed",
|
||||
"mapped",
|
||||
"relocated",
|
||||
"imports_bound",
|
||||
"tls_completed",
|
||||
"entry",
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn trusted_fixture_preserves_step_failure() {
|
||||
let report = run_fixture("1", false);
|
||||
assert!(report.contains(r#""outcome":"stage_failure""#), "{report}");
|
||||
assert!(
|
||||
report.contains(r#""last_completed_stage":"entry""#),
|
||||
"{report}"
|
||||
);
|
||||
assert!(report.contains("step budget exhausted"), "{report}");
|
||||
assert_stages(&report, STARTUP_STAGES);
|
||||
assert!(!report.contains(r#""stage":"exit""#), "{report}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with Apple family 7 capabilities"]
|
||||
fn trusted_fixture_reports_verified_progress() {
|
||||
let report = run_fixture("100", true);
|
||||
assert!(report.contains(r#""outcome":"verified""#), "{report}");
|
||||
assert!(
|
||||
report.contains(r#""last_completed_stage":"framebuffer""#),
|
||||
"{report}"
|
||||
);
|
||||
let stages = [STARTUP_STAGES, &["exit", "framebuffer"]].concat();
|
||||
assert_stages(&report, &stages);
|
||||
}
|
||||
|
||||
fn run_fixture(steps: &str, success: bool) -> String {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"betterxen-report-test-{}-{steps}.json",
|
||||
std::process::id()
|
||||
));
|
||||
let fixture = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/trusted-runner.exe"
|
||||
);
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_betterxen"))
|
||||
.args([
|
||||
"run",
|
||||
"--experimental",
|
||||
"--pe",
|
||||
fixture,
|
||||
"--max-steps",
|
||||
steps,
|
||||
"--startup-report",
|
||||
])
|
||||
.arg(&path)
|
||||
.output()
|
||||
.unwrap();
|
||||
let report = std::fs::read_to_string(&path);
|
||||
if report.is_ok() {
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
}
|
||||
assert_eq!(output.status.success(), success, "{output:?}, {report:?}");
|
||||
report.unwrap()
|
||||
}
|
||||
|
||||
fn assert_stages(report: &str, stages: &[&str]) {
|
||||
assert!(report.contains(r#""schema_version":1"#), "{report}");
|
||||
let mut remaining = report;
|
||||
for stage in stages {
|
||||
remaining = remaining
|
||||
.split_once(&format!(r#""stage":"{stage}""#))
|
||||
.unwrap()
|
||||
.1;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_report_path_prevents_worker_launch() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"betterxen-report-existing-{}.json",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::write(&path, "previous report").unwrap();
|
||||
let result = Command::new(env!("CARGO_BIN_EXE_betterxen"))
|
||||
.args([
|
||||
"run",
|
||||
"--experimental",
|
||||
"--pe",
|
||||
"missing-fixture",
|
||||
"--startup-report",
|
||||
])
|
||||
.arg(&path)
|
||||
.output()
|
||||
.unwrap();
|
||||
let contents = std::fs::read_to_string(&path).unwrap();
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(contents, "previous report");
|
||||
assert!(!result.status.success());
|
||||
let stderr = String::from_utf8(result.stderr).unwrap();
|
||||
assert!(
|
||||
stderr.contains("could not create startup report"),
|
||||
"{stderr}"
|
||||
);
|
||||
assert!(!stderr.contains("No such file or directory"), "{stderr}");
|
||||
}
|
||||
+41
-13
@@ -5,8 +5,8 @@ use std::fmt;
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp,
|
||||
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource, VectorSwapOp,
|
||||
VectorUnaryOp,
|
||||
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
VectorSource, VectorSwapOp, VectorUnaryOp,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
@@ -330,6 +330,26 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
if let Some(op) = VectorCompareOp::from_word(first) {
|
||||
return vector_compare(op, first, bytes);
|
||||
}
|
||||
if let Some(op) = VectorCompareVop3Op::from_word(first) {
|
||||
let second = word(bytes, 8)?;
|
||||
let sdst = first as u8;
|
||||
if sdst > VCC_LO {
|
||||
return Err(unsupported(
|
||||
op.assembly_name(),
|
||||
"expected a destination of s0-s105 or vcc_lo",
|
||||
));
|
||||
}
|
||||
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
|
||||
return Ok((
|
||||
Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0,
|
||||
src1,
|
||||
},
|
||||
8,
|
||||
));
|
||||
}
|
||||
if let Some(op) = VectorAluVop3Op::from_word(first) {
|
||||
let second = word(bytes, 8)?;
|
||||
return Ok((vop3_vgpr2(op, first, second)?, 8));
|
||||
@@ -723,29 +743,37 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
|
||||
Ok((Instruction::MoveB32 { dst, src }, len))
|
||||
}
|
||||
|
||||
/// Operand rule `vop3_vgpr2`: VDST in bits 0-7 of the first word, SRC0 and SRC1
|
||||
/// in bits 0-8 and 9-17 of the second (RDNA 2 ISA section 13.3.4, VOP3A). Both sources
|
||||
/// are VGPRs, ABS, OP_SEL, CLAMP, OMOD and NEG are clear, and the unused SRC2 is
|
||||
/// the gfx1030 assembler's inline-zero operand encoding.
|
||||
fn vop3_vgpr2(
|
||||
op: VectorAluVop3Op,
|
||||
first: u32,
|
||||
second: u32,
|
||||
) -> Result<Instruction, DecodeErrorKind> {
|
||||
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
|
||||
Ok(Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst: first as u8,
|
||||
src0,
|
||||
src1,
|
||||
})
|
||||
}
|
||||
|
||||
/// Common VOP3A source and modifier checks (RDNA 2 ISA section 13.3.4).
|
||||
/// SRC0 and SRC1 are VGPRs, the unused SRC2 is inline zero, and ABS, OP_SEL,
|
||||
/// CLAMP, OMOD and NEG are clear.
|
||||
fn vop3_vgpr2_sources(
|
||||
mnemonic: &'static str,
|
||||
first: u32,
|
||||
second: u32,
|
||||
) -> Result<(u8, u8), DecodeErrorKind> {
|
||||
let src0 = second & 0x1ff;
|
||||
let src1 = (second >> 9) & 0x1ff;
|
||||
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
|
||||
return Err(unsupported(
|
||||
op.assembly_name(),
|
||||
mnemonic,
|
||||
"expected two VGPR sources and no modifiers",
|
||||
));
|
||||
}
|
||||
Ok(Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst: first as u8,
|
||||
src0: src0 as u8,
|
||||
src1: src1 as u8,
|
||||
})
|
||||
Ok((src0 as u8, src1 as u8))
|
||||
}
|
||||
|
||||
fn scalar_form(
|
||||
|
||||
+304
-36
@@ -5,7 +5,7 @@ use std::process::{Command, Stdio};
|
||||
use xenora_decoder::{
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
|
||||
VectorSource, VectorUnaryOp, decode, decode_at,
|
||||
VectorCompareOp, VectorCompareVop3Op, VectorSource, VectorUnaryOp, decode, decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
@@ -71,6 +71,127 @@ fn decodes_each_fixture_instruction_with_offset_and_length() {
|
||||
assert_eq!(instructions, wanted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_wave32_vop3_compares_from_llvm_words() {
|
||||
use VectorCompareVop3Op::*;
|
||||
|
||||
// llvm-mc -triple=amdgcn -mcpu=gfx1030 -mattr=+wavefrontsize32 -show-encoding
|
||||
let cases: [(u32, VectorCompareVop3Op, u8); 19] = [
|
||||
// v_cmp_lt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x81,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd481_0004, CmpLtI32, 4),
|
||||
// v_cmp_eq_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x82,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd482_0004, CmpEqI32, 4),
|
||||
// v_cmp_le_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x83,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd483_0004, CmpLeI32, 4),
|
||||
// v_cmp_gt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x84,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd484_0004, CmpGtI32, 4),
|
||||
// v_cmp_ne_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x85,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd485_0004, CmpNeI32, 4),
|
||||
// v_cmp_ge_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x86,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd486_0004, CmpGeI32, 4),
|
||||
// v_cmp_lt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc1,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c1_0004, CmpLtU32, 4),
|
||||
// v_cmp_eq_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_0004, CmpEqU32, 4),
|
||||
// v_cmp_le_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc3,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c3_0004, CmpLeU32, 4),
|
||||
// v_cmp_gt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc4,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c4_0004, CmpGtU32, 4),
|
||||
// v_cmp_ne_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc5,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c5_0004, CmpNeU32, 4),
|
||||
// v_cmp_ge_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc6,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c6_0004, CmpGeU32, 4),
|
||||
// v_cmp_f_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x80,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd480_0004, CmpFI32, 4),
|
||||
// v_cmp_t_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x87,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd487_0004, CmpTI32, 4),
|
||||
// v_cmp_f_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc0,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c0_0004, CmpFU32, 4),
|
||||
// v_cmp_t_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc7,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c7_0004, CmpTU32, 4),
|
||||
// v_cmp_eq_u32_e64 s0, v1, v2 ; encoding: [0x00,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_0000, CmpEqU32, 0),
|
||||
// v_cmp_eq_u32_e64 s105, v1, v2 ; encoding: [0x69,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_0069, CmpEqU32, 105),
|
||||
// v_cmp_eq_u32_e64 vcc_lo, v1, v2 ; encoding: [0x6a,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_006a, CmpEqU32, 106),
|
||||
];
|
||||
for (first, op, sdst) in cases {
|
||||
let code: Vec<_> = [first, 0x0202_0501]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let decoded = decode(Architecture::Gfx1030, &code).unwrap();
|
||||
let dst = if sdst == 106 {
|
||||
"vcc_lo".to_owned()
|
||||
} else {
|
||||
format!("s{sdst}")
|
||||
};
|
||||
assert_eq!(
|
||||
decoded,
|
||||
[DecodedInstruction {
|
||||
offset: 0,
|
||||
byte_len: 8,
|
||||
instruction: Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0: 1,
|
||||
src1: 2
|
||||
},
|
||||
}],
|
||||
);
|
||||
assert_eq!(
|
||||
decoded[0].instruction.to_string(),
|
||||
format!("{} {dst}, v1, v2", op.assembly_name())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_noncanonical_wave32_vop3_compare_operands() {
|
||||
// v_cmp_eq_u32_e64 s4, v1, v2
|
||||
let first = 0xd4c2_0004;
|
||||
let second = 0x0202_0501;
|
||||
let rejects = |first, second| {
|
||||
let code: Vec<_> = [first, second]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let error = decode(Architecture::Gfx1030, &code).unwrap_err();
|
||||
assert_eq!(error.offset, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
error.kind,
|
||||
DecodeErrorKind::UnsupportedForm {
|
||||
mnemonic: "v_cmp_eq_u32_e64",
|
||||
..
|
||||
}
|
||||
),
|
||||
"{first:#010x} {second:#010x}: {error}"
|
||||
);
|
||||
};
|
||||
|
||||
// Includes vcc_hi (107), TTMPs (108-123), null (124), m0 (125) and EXEC (126-127).
|
||||
for sdst in 107..=255 {
|
||||
rejects((first & !0xff) | sdst, second);
|
||||
}
|
||||
for bit in 8..=15 {
|
||||
// ABS, OP_SEL and CLAMP.
|
||||
rejects(first | (1 << bit), second);
|
||||
}
|
||||
for bit in 27..=31 {
|
||||
// OMOD and NEG.
|
||||
rejects(first, second | (1 << bit));
|
||||
}
|
||||
rejects(first, second ^ (1 << 18)); // SRC2 = 129 instead of 128.
|
||||
for shift in [0, 9] {
|
||||
for selector in [4, 106, 128, 240, 255] {
|
||||
// SGPR, VCC_LO, inline integer/float, literal.
|
||||
rejects(first, (second & !(0x1ff << shift)) | (selector << shift));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_non_boundary_prefix_reports_the_incomplete_instruction() {
|
||||
let lengths = [8, 4, 8, 8, 8, 4, 4];
|
||||
@@ -303,6 +424,44 @@ fn reference_scalar(scalar: ScalarSource) -> Source {
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_comparison(op: VectorCompareOp) -> Comparison {
|
||||
Comparison {
|
||||
offset: match op.relation() {
|
||||
CompareRelation::Less => 1,
|
||||
CompareRelation::Equal => 2,
|
||||
CompareRelation::LessOrEqual => 3,
|
||||
CompareRelation::Greater => 4,
|
||||
CompareRelation::NotEqual => 5,
|
||||
CompareRelation::GreaterOrEqual => 6,
|
||||
CompareRelation::False => 0,
|
||||
CompareRelation::True => 7,
|
||||
},
|
||||
signed: op.signed(),
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_vector_integer(op: VectorAluOp) -> VectorInteger {
|
||||
match op {
|
||||
VectorAluOp::CndmaskB32 => VectorInteger::Select,
|
||||
VectorAluOp::AddCoCiU32 => VectorInteger::AddCarry,
|
||||
VectorAluOp::SubCoCiU32 => VectorInteger::SubtractBorrow { reversed: false },
|
||||
VectorAluOp::SubrevCoCiU32 => VectorInteger::SubtractBorrow { reversed: true },
|
||||
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
|
||||
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
|
||||
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
|
||||
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
|
||||
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
|
||||
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
|
||||
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
|
||||
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
|
||||
VectorAluOp::XnorB32 => VectorInteger::Xnor,
|
||||
VectorAluOp::AddNcU32 => VectorInteger::Add,
|
||||
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
|
||||
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
|
||||
_ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"),
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_op(instruction: Instruction) -> Op {
|
||||
match instruction {
|
||||
Instruction::BufferLoadDword {
|
||||
@@ -391,13 +550,23 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
reference_scalar(src0),
|
||||
reference_scalar(src1),
|
||||
),
|
||||
// The reference's VOP3 add; it is the only VOP3 variant so far.
|
||||
Instruction::VectorAluVop3 {
|
||||
op: VectorAluVop3Op::AddNcU32,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::Add(dst, src0, src1),
|
||||
Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::VectorInteger(
|
||||
reference_vector_integer(op.base()),
|
||||
dst,
|
||||
CompareSource::Vector(src0),
|
||||
src1,
|
||||
),
|
||||
Instruction::ScalarUnary { op, dst, src } => {
|
||||
let src = reference_scalar(src);
|
||||
let unary = match op {
|
||||
@@ -506,19 +675,7 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
}
|
||||
|
||||
Instruction::VectorCompare { op, src0, src1 } => {
|
||||
let comparison = Comparison {
|
||||
offset: match op.relation() {
|
||||
CompareRelation::Less => 1,
|
||||
CompareRelation::Equal => 2,
|
||||
CompareRelation::LessOrEqual => 3,
|
||||
CompareRelation::Greater => 4,
|
||||
CompareRelation::NotEqual => 5,
|
||||
CompareRelation::GreaterOrEqual => 6,
|
||||
CompareRelation::False => 0,
|
||||
CompareRelation::True => 7,
|
||||
},
|
||||
signed: op.signed(),
|
||||
};
|
||||
let comparison = reference_comparison(op);
|
||||
let src0 = match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
@@ -531,31 +688,24 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
width => panic!("unexpected VOPC operand width {width}"),
|
||||
}
|
||||
}
|
||||
Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::CompareVop3(
|
||||
sdst,
|
||||
reference_comparison(op.base()),
|
||||
CompareSource::Vector(src0),
|
||||
src1,
|
||||
),
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::VectorInteger(
|
||||
match op {
|
||||
VectorAluOp::CndmaskB32 => VectorInteger::Select,
|
||||
VectorAluOp::AddCoCiU32 => VectorInteger::AddCarry,
|
||||
VectorAluOp::SubCoCiU32 => VectorInteger::SubtractBorrow { reversed: false },
|
||||
VectorAluOp::SubrevCoCiU32 => VectorInteger::SubtractBorrow { reversed: true },
|
||||
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
|
||||
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
|
||||
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
|
||||
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
|
||||
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
|
||||
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
|
||||
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
|
||||
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
|
||||
VectorAluOp::XnorB32 => VectorInteger::Xnor,
|
||||
VectorAluOp::AddNcU32 => VectorInteger::Add,
|
||||
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
|
||||
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
|
||||
_ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"),
|
||||
},
|
||||
reference_vector_integer(op),
|
||||
dst,
|
||||
match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
@@ -596,12 +746,14 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-unary.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare-16.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vop3-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vop3-compare.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 142, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 169, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
@@ -829,7 +981,7 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
|
||||
let outside_subset: &[&[u32]] = &[
|
||||
&[0x7e04_026b], // VOP1 VCC_HI source
|
||||
&[0x7da2_0501], // v_cmpx_eq_u32_e32
|
||||
&[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64
|
||||
&[0xd482_006a, 0x0002_0501], // v_cmp_eq_i32_e64 with SRC2 = 0
|
||||
&[0x8788_0908], // s_and_b64
|
||||
&[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources
|
||||
&[0x806c_0908], // SOP2 TTMP destination
|
||||
@@ -1119,6 +1271,122 @@ fn decode_at_resolves_branch_targets_from_the_stream_offset() {
|
||||
);
|
||||
}
|
||||
|
||||
// llvm-mc -triple=amdgcn -mcpu=gfx1030 -show-encoding
|
||||
const VOP3_INTEGER_ENCODINGS: [(VectorAluVop3Op, u32); 11] = [
|
||||
// v_mul_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x09,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulI32I24, 0xd50900ff),
|
||||
// v_mul_hi_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0a,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulHiI32I24, 0xd50a00ff),
|
||||
// v_mul_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0b,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulU32U24, 0xd50b00ff),
|
||||
// v_mul_hi_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0c,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulHiU32U24, 0xd50c00ff),
|
||||
// v_min_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x11,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MinI32, 0xd51100ff),
|
||||
// v_max_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x12,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MaxI32, 0xd51200ff),
|
||||
// v_min_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x13,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MinU32, 0xd51300ff),
|
||||
// v_max_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x14,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MaxU32, 0xd51400ff),
|
||||
// v_xnor_b32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x1e,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::XnorB32, 0xd51e00ff),
|
||||
// v_sub_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x26,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::SubNcU32, 0xd52600ff),
|
||||
// v_subrev_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x27,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::SubrevNcU32, 0xd52700ff),
|
||||
];
|
||||
const VOP3_INTEGER_SOURCE_WORD: u32 = 0x0202_ff00;
|
||||
|
||||
#[test]
|
||||
fn decodes_registry_vop3_integer_encodings() {
|
||||
for (op, first) in VOP3_INTEGER_ENCODINGS {
|
||||
let bytes = [first.to_le_bytes(), VOP3_INTEGER_SOURCE_WORD.to_le_bytes()].concat();
|
||||
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
|
||||
assert_eq!(decoded.len(), 1);
|
||||
assert_eq!(decoded[0].byte_len, 8);
|
||||
assert_eq!(
|
||||
decoded[0].instruction,
|
||||
Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst: 255,
|
||||
src0: 0,
|
||||
src1: 127,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_vop3_integer_fixture() {
|
||||
use VectorAluVop3Op::*;
|
||||
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vop3-integer.bin");
|
||||
let decoded = decode(Architecture::Gfx1030, code).unwrap();
|
||||
let expected = [
|
||||
(MulI32I24, 2, 1, 1),
|
||||
(MulHiI32I24, 3, 2, 1),
|
||||
(MulU32U24, 4, 2, 1),
|
||||
(MulHiU32U24, 255, 4, 1),
|
||||
(MinI32, 6, 1, 2),
|
||||
(MaxI32, 7, 1, 4),
|
||||
(MinU32, 8, 3, 1),
|
||||
(MaxU32, 9, 255, 2),
|
||||
(XnorB32, 10, 1, 255),
|
||||
(SubNcU32, 11, 6, 10),
|
||||
(SubrevNcU32, 1, 1, 9),
|
||||
];
|
||||
let actual: Vec<_> = decoded
|
||||
.iter()
|
||||
.filter_map(|decoded| match decoded.instruction {
|
||||
Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Some((decoded.offset, decoded.byte_len, op, dst, src0, src1)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let expected: Vec<_> = expected
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, (op, dst, src0, src1))| (12 + 8 * index, 8, op, dst, src0, src1))
|
||||
.collect();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_registry_vop3_integer_modifiers_and_other_sources() {
|
||||
for (op, first) in VOP3_INTEGER_ENCODINGS {
|
||||
let second = VOP3_INTEGER_SOURCE_WORD;
|
||||
let reject = |first: u32, second: u32| {
|
||||
let bytes = [first.to_le_bytes(), second.to_le_bytes()].concat();
|
||||
let error = decode(Architecture::Gfx1030, &bytes)
|
||||
.expect_err(&format!("{op:?} accepted {first:#010x} {second:#010x}"));
|
||||
assert_eq!(error.offset, 0);
|
||||
assert!(matches!(
|
||||
error.kind,
|
||||
DecodeErrorKind::UnsupportedForm { mnemonic, .. }
|
||||
if mnemonic == op.assembly_name()
|
||||
));
|
||||
};
|
||||
|
||||
// First word: ABS[10:8], OP_SEL[14:11], CLAMP[15].
|
||||
for bit in 8..=15 {
|
||||
reject(first | (1 << bit), second);
|
||||
}
|
||||
// Second word: OMOD[28:27], NEG[31:29].
|
||||
for bit in 27..=31 {
|
||||
reject(first, second | (1 << bit));
|
||||
}
|
||||
|
||||
reject(first, second & !0x1ff); // SRC0 = s0
|
||||
reject(first, (second & !(0x1ff << 9)) | (128 << 9)); // SRC1 = inline zero
|
||||
reject(first, second | (1 << 18)); // SRC2 = inline one
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_sopk_immediates_and_rejects_non_sgpr_operands() {
|
||||
use xenora_decoder::ScalarImmediateCompareOp;
|
||||
|
||||
@@ -71,6 +71,13 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
|
||||
"api-ms-win-crt-filesystem-l1-1-0.dll",
|
||||
"api-ms-win-crt-locale-l1-1-0.dll",
|
||||
"api-ms-win-crt-environment-l1-1-0.dll",
|
||||
// The API set a program built with the mingw-w64 UCRT runtime
|
||||
// imports `memcpy` and `__C_specific_handler` from. That it
|
||||
// forwards to ucrtbase.dll is inferred from its name and from
|
||||
// Microsoft's "Universal CRT deployment" page, which says the
|
||||
// Universal CRT ships as ucrtbase.dll plus `api-ms-win-*.dll`
|
||||
// forwarders. No document naming this set was found.
|
||||
"api-ms-win-crt-private-l1-1-0.dll",
|
||||
],
|
||||
_ => &[],
|
||||
}
|
||||
|
||||
@@ -0,0 +1,529 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Decoding of Microsoft Visual C++ decorated names, for diagnostics.
|
||||
//!
|
||||
//! Written from the publicly described decoration scheme: a leading `?`,
|
||||
//! `@`-terminated name fragments listed innermost first, single-digit name and
|
||||
//! type back-references, an access and storage code, a calling convention,
|
||||
//! the return type and the parameter list. Output follows the style of
|
||||
//! Microsoft's `undname` tool. Anything outside the supported subset returns
|
||||
//! `None` instead of a guess, so callers fall back to the decorated name.
|
||||
|
||||
const MAX_DEPTH: usize = 16;
|
||||
|
||||
/// The undecorated form of `symbol`, or `None` when it is not a decorated
|
||||
/// C++ name or uses an unsupported construct.
|
||||
pub fn demangle(symbol: &str) -> Option<String> {
|
||||
let mut parser = Parser {
|
||||
input: symbol.as_bytes(),
|
||||
position: 0,
|
||||
names: Vec::new(),
|
||||
types: Vec::new(),
|
||||
depth: 0,
|
||||
};
|
||||
let result = parser.symbol()?;
|
||||
(parser.position == parser.input.len()).then_some(result)
|
||||
}
|
||||
|
||||
/// A special name introduced by `?` and a code inside the qualified name.
|
||||
enum Special {
|
||||
Constructor,
|
||||
Destructor,
|
||||
Operator(&'static str),
|
||||
Vftable,
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
input: &'a [u8],
|
||||
position: usize,
|
||||
names: Vec<String>,
|
||||
types: Vec<String>,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.input.get(self.position).copied()
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Option<u8> {
|
||||
let byte = self.peek()?;
|
||||
self.position += 1;
|
||||
Some(byte)
|
||||
}
|
||||
|
||||
fn eat(&mut self, byte: u8) -> bool {
|
||||
let found = self.peek() == Some(byte);
|
||||
if found {
|
||||
self.position += 1;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn eat_str(&mut self, text: &str) -> bool {
|
||||
let found = self.input[self.position..].starts_with(text.as_bytes());
|
||||
if found {
|
||||
self.position += text.len();
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn symbol(&mut self) -> Option<String> {
|
||||
if !self.eat(b'?') {
|
||||
return None;
|
||||
}
|
||||
let (name, special) = self.qualified_name(true)?;
|
||||
match self.peek()? {
|
||||
b'0'..=b'4' => self.variable(&name),
|
||||
b'6' => {
|
||||
self.next();
|
||||
let qualifier = cv(self.next()?)?;
|
||||
self.eat(b'@');
|
||||
if !matches!(special, Some(Special::Vftable)) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("{} {name}", qualifier.trim()))
|
||||
}
|
||||
_ => self.function(&name, special.as_ref()),
|
||||
}
|
||||
}
|
||||
|
||||
fn variable(&mut self, name: &str) -> Option<String> {
|
||||
let access = match self.next()? {
|
||||
b'0' => "private: static ",
|
||||
b'1' => "protected: static ",
|
||||
b'2' => "public: static ",
|
||||
_ => "",
|
||||
};
|
||||
let kind = self.data_type()?;
|
||||
self.eat(b'E');
|
||||
let qualifier = cv(self.next()?)?;
|
||||
Some(format!("{access}{kind}{qualifier} {name}"))
|
||||
}
|
||||
|
||||
fn function(&mut self, name: &str, special: Option<&Special>) -> Option<String> {
|
||||
let (access, member) = match self.next()? {
|
||||
b'A' | b'B' => ("private: ", true),
|
||||
b'C' | b'D' => ("private: static ", false),
|
||||
b'E' | b'F' => ("private: virtual ", true),
|
||||
b'I' | b'J' => ("protected: ", true),
|
||||
b'K' | b'L' => ("protected: static ", false),
|
||||
b'M' | b'N' => ("protected: virtual ", true),
|
||||
b'Q' | b'R' => ("public: ", true),
|
||||
b'S' | b'T' => ("public: static ", false),
|
||||
b'U' | b'V' => ("public: virtual ", true),
|
||||
b'Y' | b'Z' => ("", false),
|
||||
_ => return None,
|
||||
};
|
||||
let mut this = String::new();
|
||||
if member {
|
||||
let pointer64 = self.eat(b'E');
|
||||
this.push_str(cv(self.next()?)?.trim_start());
|
||||
if pointer64 {
|
||||
this.push_str(" __ptr64");
|
||||
}
|
||||
}
|
||||
let convention = match self.next()? {
|
||||
b'A' | b'B' => "__cdecl",
|
||||
b'C' | b'D' => "__pascal",
|
||||
b'E' | b'F' => "__thiscall",
|
||||
b'G' | b'H' => "__stdcall",
|
||||
b'I' | b'J' => "__fastcall",
|
||||
b'Q' => "__vectorcall",
|
||||
_ => return None,
|
||||
};
|
||||
let returns = if self.eat(b'@') {
|
||||
if !matches!(special, Some(Special::Constructor | Special::Destructor)) {
|
||||
return None;
|
||||
}
|
||||
String::new()
|
||||
} else {
|
||||
if self.eat(b'?') {
|
||||
cv(self.next()?)?;
|
||||
}
|
||||
format!("{} ", self.data_type()?)
|
||||
};
|
||||
let parameters = self.parameters()?;
|
||||
if !self.eat(b'Z') {
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"{access}{returns}{convention} {name}({parameters}){this}"
|
||||
))
|
||||
}
|
||||
|
||||
fn parameters(&mut self) -> Option<String> {
|
||||
if self.eat(b'X') {
|
||||
return Some("void".to_owned());
|
||||
}
|
||||
let mut parameters = Vec::new();
|
||||
loop {
|
||||
match self.peek()? {
|
||||
b'@' => {
|
||||
self.next();
|
||||
break;
|
||||
}
|
||||
b'Z' => {
|
||||
self.next();
|
||||
parameters.push("...".to_owned());
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
let start = self.position;
|
||||
let kind = self.data_type()?;
|
||||
if self.position - start > 1 && self.types.len() < 10 {
|
||||
self.types.push(kind.clone());
|
||||
}
|
||||
parameters.push(kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(parameters.join(","))
|
||||
}
|
||||
|
||||
/// Fragments up to `@`, joined outermost first.
|
||||
fn qualified_name(&mut self, allow_special: bool) -> Option<(String, Option<Special>)> {
|
||||
let mut special = None;
|
||||
let mut fragments = Vec::new();
|
||||
if allow_special
|
||||
&& self.peek() == Some(b'?')
|
||||
&& self.input.get(self.position + 1) != Some(&b'$')
|
||||
{
|
||||
self.next();
|
||||
special = Some(self.special()?);
|
||||
} else {
|
||||
fragments.push(self.fragment()?);
|
||||
}
|
||||
while !self.eat(b'@') {
|
||||
fragments.push(self.fragment()?);
|
||||
}
|
||||
fragments.reverse();
|
||||
let scope = fragments.join("::");
|
||||
let name = match &special {
|
||||
None => scope,
|
||||
Some(special) => {
|
||||
let class = || Some(fragments.last()?.split('<').next()?.to_owned());
|
||||
let leaf = match special {
|
||||
Special::Constructor => class()?,
|
||||
Special::Destructor => format!("~{}", class()?),
|
||||
Special::Operator(name) => name.to_string(),
|
||||
Special::Vftable => "`vftable'".to_owned(),
|
||||
};
|
||||
if scope.is_empty() {
|
||||
leaf
|
||||
} else {
|
||||
format!("{scope}::{leaf}")
|
||||
}
|
||||
}
|
||||
};
|
||||
Some((name, special))
|
||||
}
|
||||
|
||||
fn special(&mut self) -> Option<Special> {
|
||||
Some(match self.next()? {
|
||||
b'0' => Special::Constructor,
|
||||
b'1' => Special::Destructor,
|
||||
b'2' => Special::Operator("operator new"),
|
||||
b'3' => Special::Operator("operator delete"),
|
||||
b'4' => Special::Operator("operator="),
|
||||
b'8' => Special::Operator("operator=="),
|
||||
b'9' => Special::Operator("operator!="),
|
||||
b'A' => Special::Operator("operator[]"),
|
||||
b'R' => Special::Operator("operator()"),
|
||||
b'_' => match self.next()? {
|
||||
b'7' => Special::Vftable,
|
||||
b'U' => Special::Operator("operator new[]"),
|
||||
b'V' => Special::Operator("operator delete[]"),
|
||||
_ => return None,
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn fragment(&mut self) -> Option<String> {
|
||||
if let Some(digit @ b'0'..=b'9') = self.peek() {
|
||||
self.next();
|
||||
return self.names.get(usize::from(digit - b'0')).cloned();
|
||||
}
|
||||
let fragment = if self.eat_str("?$") {
|
||||
self.template()?
|
||||
} else {
|
||||
self.identifier()?
|
||||
};
|
||||
if self.names.len() < 10 && !self.names.contains(&fragment) {
|
||||
self.names.push(fragment.clone());
|
||||
}
|
||||
Some(fragment)
|
||||
}
|
||||
|
||||
fn identifier(&mut self) -> Option<String> {
|
||||
let start = self.position;
|
||||
while self.peek()? != b'@' {
|
||||
let byte = self.next()?;
|
||||
if !(byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$') {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let text = std::str::from_utf8(&self.input[start..self.position]).ok()?;
|
||||
self.next();
|
||||
(!text.is_empty()).then(|| text.to_owned())
|
||||
}
|
||||
|
||||
/// `name@arguments@`, with back-references local to the argument list.
|
||||
fn template(&mut self) -> Option<String> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let outer_names = std::mem::take(&mut self.names);
|
||||
let outer_types = std::mem::take(&mut self.types);
|
||||
let name = self.identifier();
|
||||
if let Some(name) = &name {
|
||||
self.names.push(name.clone());
|
||||
}
|
||||
let mut arguments = Vec::new();
|
||||
let result = (|| {
|
||||
let name = name?;
|
||||
while !self.eat(b'@') {
|
||||
let start = self.position;
|
||||
let argument = if self.eat(b'$') {
|
||||
if !self.eat(b'0') {
|
||||
return None;
|
||||
}
|
||||
self.number()?.to_string()
|
||||
} else {
|
||||
self.data_type()?
|
||||
};
|
||||
if self.position - start > 1 && self.types.len() < 10 {
|
||||
self.types.push(argument.clone());
|
||||
}
|
||||
arguments.push(argument);
|
||||
}
|
||||
let joined = arguments.join(",");
|
||||
let close = if joined.ends_with('>') { " >" } else { ">" };
|
||||
Some(format!("{name}<{joined}{close}"))
|
||||
})();
|
||||
self.names = outer_names;
|
||||
self.types = outer_types;
|
||||
self.depth -= 1;
|
||||
result
|
||||
}
|
||||
|
||||
/// `0`–`9` encode 1–10; otherwise hexadecimal digits `A`–`P` end with `@`.
|
||||
fn number(&mut self) -> Option<i64> {
|
||||
let negative = self.eat(b'?');
|
||||
let value = match self.next()? {
|
||||
digit @ b'0'..=b'9' => i64::from(digit - b'0') + 1,
|
||||
b'@' => 0,
|
||||
mut digit => {
|
||||
let mut value: i64 = 0;
|
||||
loop {
|
||||
if !(b'A'..=b'P').contains(&digit) {
|
||||
return None;
|
||||
}
|
||||
value = value
|
||||
.checked_mul(16)?
|
||||
.checked_add(i64::from(digit - b'A'))?;
|
||||
digit = self.next()?;
|
||||
if digit == b'@' {
|
||||
break value;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
Some(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
fn data_type(&mut self) -> Option<String> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let result = self.data_type_inner();
|
||||
self.depth -= 1;
|
||||
result
|
||||
}
|
||||
|
||||
fn data_type_inner(&mut self) -> Option<String> {
|
||||
let code = self.next()?;
|
||||
let primitive = match code {
|
||||
b'X' => "void",
|
||||
b'C' => "signed char",
|
||||
b'D' => "char",
|
||||
b'E' => "unsigned char",
|
||||
b'F' => "short",
|
||||
b'G' => "unsigned short",
|
||||
b'H' => "int",
|
||||
b'I' => "unsigned int",
|
||||
b'J' => "long",
|
||||
b'K' => "unsigned long",
|
||||
b'M' => "float",
|
||||
b'N' => "double",
|
||||
b'O' => "long double",
|
||||
b'0'..=b'9' => return self.types.get(usize::from(code - b'0')).cloned(),
|
||||
b'_' => match self.next()? {
|
||||
b'J' => "__int64",
|
||||
b'K' => "unsigned __int64",
|
||||
b'N' => "bool",
|
||||
b'W' => "wchar_t",
|
||||
b'S' => "char16_t",
|
||||
b'U' => "char32_t",
|
||||
b'Q' => "char8_t",
|
||||
_ => return None,
|
||||
},
|
||||
b'V' => return Some(format!("class {}", self.qualified_name(false)?.0)),
|
||||
b'U' => return Some(format!("struct {}", self.qualified_name(false)?.0)),
|
||||
b'T' => return Some(format!("union {}", self.qualified_name(false)?.0)),
|
||||
b'W' => {
|
||||
if !self.eat(b'4') {
|
||||
return None;
|
||||
}
|
||||
return Some(format!("enum {}", self.qualified_name(false)?.0));
|
||||
}
|
||||
b'P' | b'Q' | b'R' | b'S' => return self.indirection("*", pointer_cv(code)),
|
||||
b'A' => return self.indirection("&", ""),
|
||||
b'B' => return self.indirection("&", " volatile"),
|
||||
b'$' => {
|
||||
if self.eat_str("$Q") {
|
||||
return self.indirection("&&", "");
|
||||
}
|
||||
if self.eat_str("$T") {
|
||||
return Some("std::nullptr_t".to_owned());
|
||||
}
|
||||
return None;
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(primitive.to_owned())
|
||||
}
|
||||
|
||||
/// A pointer or reference: an optional `E` for `__ptr64`, the pointee's
|
||||
/// qualifiers, then the pointee.
|
||||
fn indirection(&mut self, symbol: &str, own: &str) -> Option<String> {
|
||||
let pointer64 = self.eat(b'E');
|
||||
let pointee_cv = cv(self.next()?)?;
|
||||
let pointee = self.data_type()?;
|
||||
let width = if pointer64 { " __ptr64" } else { "" };
|
||||
Some(format!("{pointee}{pointee_cv} {symbol}{own}{width}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn cv(code: u8) -> Option<&'static str> {
|
||||
Some(match code {
|
||||
b'A' => "",
|
||||
b'B' => " const",
|
||||
b'C' => " volatile",
|
||||
b'D' => " const volatile",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn pointer_cv(code: u8) -> &'static str {
|
||||
match code {
|
||||
b'Q' => " const",
|
||||
b'R' => " volatile",
|
||||
b'S' => " const volatile",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::demangle;
|
||||
|
||||
#[test]
|
||||
fn decodes_global_functions_and_operators() {
|
||||
for (decorated, expected) in [
|
||||
("?foo@@YAXXZ", "void __cdecl foo(void)"),
|
||||
("?foo@@YAHH@Z", "int __cdecl foo(int)"),
|
||||
("?f@@YAXPEBD@Z", "void __cdecl f(char const * __ptr64)"),
|
||||
("?f@@YAXHZZ", "void __cdecl f(int,...)"),
|
||||
(
|
||||
"??2@YAPEAX_K@Z",
|
||||
"void * __ptr64 __cdecl operator new(unsigned __int64)",
|
||||
),
|
||||
(
|
||||
"??3@YAXPEAX@Z",
|
||||
"void __cdecl operator delete(void * __ptr64)",
|
||||
),
|
||||
(
|
||||
"??_U@YAPEAX_K@Z",
|
||||
"void * __ptr64 __cdecl operator new[](unsigned __int64)",
|
||||
),
|
||||
(
|
||||
"?_Xlength_error@std@@YAXPEBD@Z",
|
||||
"void __cdecl std::_Xlength_error(char const * __ptr64)",
|
||||
),
|
||||
("?g@@YA_N_J0@Z", "bool __cdecl g(__int64,__int64)"),
|
||||
] {
|
||||
assert_eq!(
|
||||
demangle(decorated).as_deref(),
|
||||
Some(expected),
|
||||
"{decorated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_members_constructors_and_data() {
|
||||
for (decorated, expected) in [
|
||||
(
|
||||
"?bar@Foo@@QEAAXH@Z",
|
||||
"public: void __cdecl Foo::bar(int) __ptr64",
|
||||
),
|
||||
(
|
||||
"?get@Foo@@QEBAHXZ",
|
||||
"public: int __cdecl Foo::get(void)const __ptr64",
|
||||
),
|
||||
("??0Foo@@QEAA@XZ", "public: __cdecl Foo::Foo(void) __ptr64"),
|
||||
(
|
||||
"??1Foo@@UEAA@XZ",
|
||||
"public: virtual __cdecl Foo::~Foo(void) __ptr64",
|
||||
),
|
||||
(
|
||||
"?make@Foo@@SAPEAV1@XZ",
|
||||
"public: static class Foo * __ptr64 __cdecl Foo::make(void)",
|
||||
),
|
||||
("?x@ns@@3HA", "int ns::x"),
|
||||
("?count@Foo@@2HB", "public: static int const Foo::count"),
|
||||
("??_7type_info@@6B@", "const type_info::`vftable'"),
|
||||
] {
|
||||
assert_eq!(
|
||||
demangle(decorated).as_deref(),
|
||||
Some(expected),
|
||||
"{decorated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_templates_and_back_references() {
|
||||
assert_eq!(
|
||||
demangle("?g@@YAXAEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z")
|
||||
.as_deref(),
|
||||
Some(
|
||||
"void __cdecl g(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > & __ptr64)"
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
demangle("?h@@YAXV?$array@H$0BA@@std@@@Z").as_deref(),
|
||||
Some("void __cdecl h(class std::array<int,16>)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_undecorated_and_unsupported_names() {
|
||||
for symbol in [
|
||||
"malloc",
|
||||
"",
|
||||
"?",
|
||||
"?foo@@",
|
||||
"?foo@@YAXXZtrailing",
|
||||
"??_R0?AVtype_info@@@8",
|
||||
"?f@@YAXP6AXXZ@Z",
|
||||
&format!("?f@@YAX{}@Z", "PEA".repeat(40) + "H"),
|
||||
] {
|
||||
assert_eq!(demangle(symbol), None, "{symbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@
|
||||
pub mod apiset;
|
||||
pub mod classify;
|
||||
pub mod codegen;
|
||||
pub mod demangle;
|
||||
pub mod ingest;
|
||||
pub mod manifest;
|
||||
pub mod metadata;
|
||||
@@ -37,6 +38,7 @@ pub mod verify;
|
||||
pub use apiset::{get_api_sets_for_canonical, resolve_api_set_canonical};
|
||||
pub use classify::{Classification, SymbolDb};
|
||||
pub use codegen::{GeneratedFiles, generate};
|
||||
pub use demangle::demangle;
|
||||
pub use ingest::{ingest_header_file, ingest_standard_system_headers};
|
||||
pub use manifest::Manifest;
|
||||
pub use metadata::{AbiType, CallingConvention, FunctionSignature, MetadataCatalog};
|
||||
|
||||
@@ -166,7 +166,13 @@ impl Manifest {
|
||||
if let Classification::Manual { reason } | Classification::Unsupported { reason } =
|
||||
&e.classification
|
||||
{
|
||||
md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol));
|
||||
match crate::demangle(&e.symbol) {
|
||||
Some(name) => md.push_str(&format!(
|
||||
"- `{}!{}` (`{name}`) — {reason}\n",
|
||||
e.module, e.symbol
|
||||
)),
|
||||
None => md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol)),
|
||||
}
|
||||
}
|
||||
}
|
||||
md
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Decorated names produced by an independent mangler: Apple clang 21 with
|
||||
//! `-target x86_64-pc-windows-msvc -S` on the declarations quoted beside each
|
||||
//! case. Expected strings restate those declarations in `undname` style; they
|
||||
//! are not taken from the decoder.
|
||||
|
||||
use xenora_import_gen::demangle;
|
||||
|
||||
#[test]
|
||||
fn clang_msvc_manglings_decode_to_their_declarations() {
|
||||
for (decorated, expected) in [
|
||||
// void foo();
|
||||
("?foo@@YAXXZ", "void __cdecl foo(void)"),
|
||||
// int foo2(int);
|
||||
("?foo2@@YAHH@Z", "int __cdecl foo2(int)"),
|
||||
// void f(const char*);
|
||||
("?f@@YAXPEBD@Z", "void __cdecl f(char const * __ptr64)"),
|
||||
// void fv(int, ...);
|
||||
("?fv@@YAXHZZ", "void __cdecl fv(int,...)"),
|
||||
// bool g(long long, long long);
|
||||
("?g@@YA_N_J0@Z", "bool __cdecl g(__int64,__int64)"),
|
||||
// namespace std { void _Xlength_error(const char*); }
|
||||
(
|
||||
"?_Xlength_error@std@@YAXPEBD@Z",
|
||||
"void __cdecl std::_Xlength_error(char const * __ptr64)",
|
||||
),
|
||||
// struct Foo { void bar(int); };
|
||||
(
|
||||
"?bar@Foo@@QEAAXH@Z",
|
||||
"public: void __cdecl Foo::bar(int) __ptr64",
|
||||
),
|
||||
// struct Foo { int get() const; };
|
||||
(
|
||||
"?get@Foo@@QEBAHXZ",
|
||||
"public: int __cdecl Foo::get(void)const __ptr64",
|
||||
),
|
||||
// struct Foo { Foo(); };
|
||||
("??0Foo@@QEAA@XZ", "public: __cdecl Foo::Foo(void) __ptr64"),
|
||||
// struct Foo { static Foo* make(); };
|
||||
(
|
||||
"?make@Foo@@SAPEAU1@XZ",
|
||||
"public: static struct Foo * __ptr64 __cdecl Foo::make(void)",
|
||||
),
|
||||
// void use(Foo&);
|
||||
(
|
||||
"?use@@YAXAEAUFoo@@@Z",
|
||||
"void __cdecl use(struct Foo & __ptr64)",
|
||||
),
|
||||
// namespace ns { int x; }
|
||||
("?x@ns@@3HA", "int ns::x"),
|
||||
// Global operator new(size_t) and sized operator delete(void*, size_t).
|
||||
(
|
||||
"??2@YAPEAX_K@Z",
|
||||
"void * __ptr64 __cdecl operator new(unsigned __int64)",
|
||||
),
|
||||
(
|
||||
"??3@YAXPEAX_K@Z",
|
||||
"void __cdecl operator delete(void * __ptr64,unsigned __int64)",
|
||||
),
|
||||
// void gs(std::basic_string<char, std::char_traits<char>, std::allocator<char>>&);
|
||||
(
|
||||
"?gs@@YAXAEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z",
|
||||
"void __cdecl gs(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > & __ptr64)",
|
||||
),
|
||||
// void h(std::array<int, 16>);
|
||||
(
|
||||
"?h@@YAXV?$array@H$0BA@@std@@@Z",
|
||||
"void __cdecl h(class std::array<int,16>)",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
demangle(decorated).as_deref(),
|
||||
Some(expected),
|
||||
"{decorated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_clang_manglings_are_reported_rather_than_guessed() {
|
||||
// void (*keep[])(): function pointer types are outside the supported subset.
|
||||
assert_eq!(demangle("?keep@@3PAP6AXXZA"), None);
|
||||
// A compiler-generated cleanup funclet nested in another function's scope.
|
||||
assert_eq!(demangle("?dtor$2@?0??use@@YAXAEAUFoo@@@Z@4HA"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifests_show_undecorated_names_for_unclassified_cxx_imports() {
|
||||
use xenora_import_gen::{ImportRecord, Manifest, SymbolDb};
|
||||
let record = |symbol: &str| ImportRecord {
|
||||
module: "msvcp140.dll".to_owned(),
|
||||
symbol: symbol.to_owned(),
|
||||
ordinal: None,
|
||||
iat_rva: 0x2000,
|
||||
};
|
||||
let manifest = Manifest::build(
|
||||
&[
|
||||
record("?_Xlength_error@std@@YAXPEBD@Z"),
|
||||
record("?keep@@3PAP6AXXZA"),
|
||||
],
|
||||
&SymbolDb::builtin(),
|
||||
);
|
||||
let markdown = manifest.render_markdown();
|
||||
assert!(markdown.contains(
|
||||
"- `msvcp140.dll!?_Xlength_error@std@@YAXPEBD@Z` (`void __cdecl std::_Xlength_error(char const * __ptr64)`) —"
|
||||
));
|
||||
assert!(markdown.contains("- `msvcp140.dll!?keep@@3PAP6AXXZA` —"));
|
||||
}
|
||||
@@ -44,7 +44,7 @@ TOP_KEYS = {
|
||||
# An encoding variant is another encoding of a form already in the registry (for
|
||||
# example the VOP3 `_e64` encoding of a VOP2 form): pure data that names the base
|
||||
# form, the encoding family, its opcode there and the operand rule of that
|
||||
# encoding. It inherits the base form's operation, signedness and effects.
|
||||
# encoding. The rule may redirect the base form's mask to an explicit destination.
|
||||
VARIANT_KEYS = {"of", "family", "opcode", "operands", "spec", "verify"}
|
||||
# The assembler suffix LLVM prints for a variant's encoding family.
|
||||
ASSEMBLY_SUFFIX = {"VOP3": "_e64"}
|
||||
@@ -151,8 +151,9 @@ SCC = {
|
||||
"selected_src0": "SelectedSrc0",
|
||||
}
|
||||
# lane_mask: the Wave32 compare or carry result written to VCC_LO.
|
||||
# sdst_lane_mask: the Wave32 compare result written to explicit VOP3A SDST.
|
||||
# EXEC writes such as v_cmpx have no contract, so exec must stay unchanged.
|
||||
MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask"}
|
||||
MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask", "sdst_lane_mask": "SdstLaneMask"}
|
||||
WAVE = {"any": "Any", "wave32": "Wave32"}
|
||||
# The synthetic compute fixture ABI fixes the wave size for these operand-rule
|
||||
# kinds and for the VCC-reading VOP2 rule. Other forms declare "any".
|
||||
@@ -275,7 +276,12 @@ UNSUPPORTED_COMBOS = {
|
||||
# which SOP2 groups under src_vcc and src_special).
|
||||
# VOP3 rules also name source classes and encoding fields they refuse.
|
||||
VOP3_COMBOS = {"src_sgpr", "src_inline", "src_literal", "modifiers", "src2"}
|
||||
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} | VOP3_COMBOS
|
||||
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null", "dst_vcc_hi"} | VOP3_COMBOS
|
||||
VOP3_VGPR2_UNSUPPORTED = {
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
|
||||
}
|
||||
|
||||
VECTOR_UNARY_PRIMITIVES = {
|
||||
("not", "bitwise"): "Not",
|
||||
("brev", "bitwise"): "ReverseBits",
|
||||
@@ -495,16 +501,34 @@ OPERAND_RULES = {
|
||||
},
|
||||
# Two VGPR sources only, with ABS, OP_SEL, CLAMP, OMOD and NEG clear and
|
||||
# SRC2 the assembler's unused inline zero; the decoder rejects the rest.
|
||||
"unsupported": {
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
|
||||
},
|
||||
"unsupported": VOP3_VGPR2_UNSUPPORTED,
|
||||
"kind": "vector_vop3",
|
||||
# Only encoding variants of forms whose rule has this kind may use it.
|
||||
"variant_of": "vector",
|
||||
# The generated enum of this rule's variants; base() maps to "enum".
|
||||
"variant_enum": "VectorAluVop3Op",
|
||||
},
|
||||
"vop3_cmp_vgpr2": {
|
||||
"rust": "Vop3CmpVgpr2",
|
||||
"enum": "VectorCompareOp",
|
||||
"shape": {
|
||||
"family": "VOP3",
|
||||
"dst": {"field": "VDST", "class": "sgpr", "min": 0, "max": 106},
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vgpr"},
|
||||
{"field": "SRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 0,
|
||||
"variant_only": True,
|
||||
},
|
||||
"unsupported": VOP3_VGPR2_UNSUPPORTED | {
|
||||
"dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
},
|
||||
"kind": "vector_compare_vop3",
|
||||
"variant_of": "vector_compare",
|
||||
"variant_enum": "VectorCompareVop3Op",
|
||||
"vcc_transition": ("lane_mask", "sdst_lane_mask"),
|
||||
},
|
||||
"vop2_vgpr": {
|
||||
"rust": "Vop2Vgpr",
|
||||
"enum": "VectorAluOp",
|
||||
@@ -744,18 +768,18 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
):
|
||||
mask_inputs += 1
|
||||
elif field:
|
||||
operands[field] = (data_format, size, is_input, is_output)
|
||||
operands[field] = (data_format, kind, size, is_input, is_output)
|
||||
elif kind == "OPR_VCC":
|
||||
vcc_operands.append((is_input, is_output))
|
||||
vcc_operands.append((data_format, size, is_input, is_output))
|
||||
else:
|
||||
implicit.add(kind)
|
||||
if form["carry_in"] == "vcc":
|
||||
if vcc_operands.count((True, False)) != 1:
|
||||
if vcc_operands.count(("FMT_NUM_M64", 64, True, False)) != 1:
|
||||
errors.append(f"{label}: carry_in vcc requires one implicit XML VCC input")
|
||||
if (True, False) in vcc_operands:
|
||||
vcc_operands.remove((True, False))
|
||||
if ("FMT_NUM_M64", 64, True, False) in vcc_operands:
|
||||
vcc_operands.remove(("FMT_NUM_M64", 64, True, False))
|
||||
if form["vcc"] == "lane_mask":
|
||||
if vcc_operands != [(False, True)]:
|
||||
if vcc_operands != [("FMT_NUM_M64", 64, False, True)]:
|
||||
errors.append(f"{label}: vcc lane_mask but the XML has no implicit VCC output")
|
||||
elif vcc_operands:
|
||||
implicit.add("OPR_VCC")
|
||||
@@ -780,7 +804,7 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
if field not in operands:
|
||||
errors.append(f"{label}: XML has no operand {field}")
|
||||
continue
|
||||
data_format, size, is_input, is_output = operands[field]
|
||||
data_format, kind, size, is_input, is_output = operands[field]
|
||||
if field == "SIMM16" and _rule_kind(form) == "control":
|
||||
expected_kind, expected_format = (
|
||||
("OPR_LABEL", "FMT_NUM_I16") if form["operands"] == "sopp_branch"
|
||||
@@ -800,6 +824,11 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
continue
|
||||
bits = form.get(SOURCE_BITS_KEY) if is_source else None
|
||||
expected = bits if type(bits) is int else form["width"]
|
||||
if not is_source and form["vcc"] == "sdst_lane_mask":
|
||||
# The XML describes the Wave64 pair. The Wave32 ABI writes one SGPR.
|
||||
expected = 64
|
||||
if (kind, data_format) != ("OPR_SREG", "FMT_NUM_M64"):
|
||||
errors.append(f"{label}: {field} is not a scalar mask destination in the XML")
|
||||
if size != expected:
|
||||
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
|
||||
# The XML marks both swap operands as outputs. Guide 12.8 also
|
||||
@@ -896,10 +925,11 @@ def validate(registry, snapshot):
|
||||
if form["wave"] in WAVE and form["wave"] != wave:
|
||||
errors.append(f"{label}: wave {form['wave']} is not enforced for this rule (requires {wave})")
|
||||
lane_mask = _rule_kind(form) == "vector_compare" or (reads_vcc and form["operation"] != "cselect")
|
||||
if form["vcc"] in MASK and (form["vcc"] == "lane_mask") != lane_mask:
|
||||
vcc = "lane_mask" if lane_mask else "unchanged"
|
||||
if form["vcc"] in MASK and form["vcc"] != vcc:
|
||||
errors.append(
|
||||
f"{label}: vcc {form['vcc']} contradicts rule {form['operands']} "
|
||||
f"(requires {'lane_mask' if lane_mask else 'unchanged'})"
|
||||
f"(requires {vcc})"
|
||||
)
|
||||
if form["exec"] != "unchanged":
|
||||
errors.append(f"{label}: exec {form['exec']} has no contract (requires unchanged)")
|
||||
@@ -1070,9 +1100,10 @@ def variant_row(registry, variant, base=None):
|
||||
"""The base form re-encoded: its declaration with the variant's identity."""
|
||||
if base is None:
|
||||
base = next(form for form in registry["form"] if form.get("name") == variant["of"])
|
||||
_, vcc = OPERAND_RULES[variant["operands"]].get("vcc_transition", ("unchanged", "unchanged"))
|
||||
return dict(
|
||||
base, family=variant["family"], opcode=variant["opcode"], operands=variant["operands"],
|
||||
spec=variant["spec"], verify=variant["verify"],
|
||||
vcc=vcc, spec=variant["spec"], verify=variant["verify"],
|
||||
)
|
||||
|
||||
|
||||
@@ -1142,24 +1173,32 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors):
|
||||
if FORM_KEYS - set(base):
|
||||
errors.append(f"{label}: not checked, its form {variant['of']} is incomplete")
|
||||
continue
|
||||
base_vcc, _ = implemented.get("vcc_transition", ("unchanged", "unchanged"))
|
||||
if base["vcc"] != base_vcc:
|
||||
errors.append(
|
||||
f"{label}: operand rule {variant['operands']} requires a base "
|
||||
f"destination contract of {base_vcc}, got {base['vcc']}"
|
||||
)
|
||||
# The same base row as the completeness check above (with duplicate
|
||||
# declarations, the dict keeps the last one).
|
||||
_check_xml(variant_row(registry, variant, base), rule, snapshot, errors)
|
||||
# Every explicit operand, destination included, has the base encoding's
|
||||
# data format, in the same order (VSRC1 of VOP2 is SRC1 of VOP3).
|
||||
# Explicit destinations and sources keep the base encoding's data format
|
||||
# in the same role. The implicit-to-explicit mask transition is checked
|
||||
# above and in _check_xml for each encoding.
|
||||
base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"])))
|
||||
own_xml = snapshot["variants"].get((variant["of"], _family_encoding(variant["family"])))
|
||||
base_rule = rules.get(base.get("operands"))
|
||||
if base_xml and own_xml and _well_formed(base_rule) and _well_formed(rule):
|
||||
# Operands correspond by role, in rule order: the destination, then
|
||||
# each source (VSRC1 of VOP2 is SRC1 of VOP3).
|
||||
def roles(rule, record):
|
||||
def roles(rule, record, explicit_dst):
|
||||
by_field = {row[0]: row[1] for row in record["operands"] if row[0]}
|
||||
fields = ([rule["dst"]["field"]] if "dst" in rule else [])
|
||||
fields = [rule["dst"]["field"]] if explicit_dst else []
|
||||
fields += [src["field"] for src in rule.get("src", [])]
|
||||
return [(field, by_field.get(field)) for field in fields]
|
||||
|
||||
pairs = list(zip(roles(base_rule, base_xml), roles(rule, own_xml)))
|
||||
explicit_dst = "dst" in base_rule and "dst" in rule
|
||||
pairs = zip(roles(base_rule, base_xml, explicit_dst), roles(rule, own_xml, explicit_dst))
|
||||
for (base_field, base_format), (field, data_format) in pairs:
|
||||
if base_format != data_format:
|
||||
errors.append(
|
||||
|
||||
@@ -49,6 +49,7 @@ file = "amdgpu_isa_rdna2.xml"
|
||||
# width operand and result width in bits
|
||||
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
|
||||
# vcc, exec unchanged (stated, not implied) | lane_mask (Wave32 VOPC compare or VOP2 carry output)
|
||||
# VOP3A compare variant rows derive sdst_lane_mask from their operand rule.
|
||||
# wave any | wave32 (wave32 for VOPC compares, VOP1 integer forms and VCC-reading VOP2 forms)
|
||||
# operands a key of [operand_rules]
|
||||
# spec references; at least one guide section with a page
|
||||
|
||||
@@ -1,6 +1,202 @@
|
||||
# VOP3 encodings of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- Wave32 VOPC compares in VOP3A (#215) ----
|
||||
|
||||
# VDST encodes the scalar lane-mask destination, including vcc_lo (selector 106).
|
||||
# The two sources are VGPRs. Modifiers are clear and SRC2 is inline zero.
|
||||
[operand_rules.vop3_cmp_vgpr2]
|
||||
family = "VOP3"
|
||||
dst = { field = "VDST", class = "sgpr", min = 0, max = 106 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vgpr" },
|
||||
{ field = "SRC1", class = "vgpr" },
|
||||
]
|
||||
max_literals = 0
|
||||
variant_only = true
|
||||
unsupported = [
|
||||
"dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
|
||||
]
|
||||
|
||||
# Opcodes come from the pinned XML's default ENC_VOP3 records.
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LT_I32"
|
||||
family = "VOP3"
|
||||
opcode = 129
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_EQ_I32"
|
||||
family = "VOP3"
|
||||
opcode = 130
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LE_I32"
|
||||
family = "VOP3"
|
||||
opcode = 131
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GT_I32"
|
||||
family = "VOP3"
|
||||
opcode = 132
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_NE_I32"
|
||||
family = "VOP3"
|
||||
opcode = 133
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GE_I32"
|
||||
family = "VOP3"
|
||||
opcode = 134
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LT_U32"
|
||||
family = "VOP3"
|
||||
opcode = 193
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_EQ_U32"
|
||||
family = "VOP3"
|
||||
opcode = 194
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LE_U32"
|
||||
family = "VOP3"
|
||||
opcode = 195
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GT_U32"
|
||||
family = "VOP3"
|
||||
opcode = 196
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_NE_U32"
|
||||
family = "VOP3"
|
||||
opcode = 197
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GE_U32"
|
||||
family = "VOP3"
|
||||
opcode = 198
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_F_I32"
|
||||
family = "VOP3"
|
||||
opcode = 128
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_T_I32"
|
||||
family = "VOP3"
|
||||
opcode = 135
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_F_U32"
|
||||
family = "VOP3"
|
||||
opcode = 192
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_T_U32"
|
||||
family = "VOP3"
|
||||
opcode = 199
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- VOP3 encoding variants of registry forms (#215) ----
|
||||
# An [[encoding_variant]] re-encodes a form declared in another family file: it
|
||||
# names the form (`of`), this family, the XML opcode here and the operand rule
|
||||
@@ -37,3 +233,130 @@ spec = [
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ABS and NEG apply to floating-point inputs (guide 6.2.1) and OMOD
|
||||
# applies to floating-point results (6.2.2). These integer forms use neither.
|
||||
# OP_SEL selects 16-bit halves (13.3.4). CLAMP saturates integer results
|
||||
# (6.5), which these registry forms do not declare. SGPR, inline and literal
|
||||
# sources remain outside this operand rule.
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_I32_I24"
|
||||
family = "VOP3"
|
||||
opcode = 265
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 131 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_HI_I32_I24"
|
||||
family = "VOP3"
|
||||
opcode = 266
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 132 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_U32_U24"
|
||||
family = "VOP3"
|
||||
opcode = 267
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 132 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_HI_U32_U24"
|
||||
family = "VOP3"
|
||||
opcode = 268
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 132 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MIN_I32"
|
||||
family = "VOP3"
|
||||
opcode = 273
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MAX_I32"
|
||||
family = "VOP3"
|
||||
opcode = 274
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MIN_U32"
|
||||
family = "VOP3"
|
||||
opcode = 275
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MAX_U32"
|
||||
family = "VOP3"
|
||||
opcode = 276
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_XNOR_B32"
|
||||
family = "VOP3"
|
||||
opcode = 286
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_SUB_NC_U32"
|
||||
family = "VOP3"
|
||||
opcode = 294
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_SUBREV_NC_U32"
|
||||
family = "VOP3"
|
||||
opcode = 295
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
+14
-1
@@ -20,7 +20,8 @@ pub use rdna2::{
|
||||
};
|
||||
pub use semantics_gen::{
|
||||
ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp,
|
||||
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSwapOp, VectorUnaryOp,
|
||||
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
VectorSwapOp, VectorUnaryOp,
|
||||
};
|
||||
|
||||
impl VectorAluOp {
|
||||
@@ -227,6 +228,14 @@ pub enum Instruction {
|
||||
src0: VectorSource,
|
||||
src1: u8,
|
||||
},
|
||||
/// VOP3A 32-bit integer compare writing a Wave32 mask to s0-s105 or `vcc_lo`.
|
||||
/// Both sources are VGPR indices.
|
||||
VectorCompareVop3 {
|
||||
op: VectorCompareVop3Op,
|
||||
sdst: u8,
|
||||
src0: u8,
|
||||
src1: u8,
|
||||
},
|
||||
/// VOP2 32-bit per-lane integer operation from the semantic registry.
|
||||
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal;
|
||||
/// `src1` is a VGPR. Inactive lanes keep `dst`.
|
||||
@@ -309,6 +318,7 @@ impl Instruction {
|
||||
Self::ScalarImmediate { op, .. } => op.mnemonic(),
|
||||
Self::ScalarImmediateCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.assembly_name(),
|
||||
Self::VectorCompareVop3 { op, .. } => op.assembly_name(),
|
||||
Self::VectorAlu { op, .. } => op.assembly_name(),
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
@@ -393,6 +403,9 @@ impl fmt::Display for Instruction {
|
||||
Self::VectorCompare { src0, src1, .. } => {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
Self::VectorCompareVop3 {
|
||||
sdst, src0, src1, ..
|
||||
} => write!(formatter, " {}, v{src0}, v{src1}", ScalarDestination(sdst)),
|
||||
Self::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
|
||||
@@ -47,7 +47,7 @@ pub enum Operation {
|
||||
LogicalShiftRight,
|
||||
/// Shift S0 right by the masked count in S1, filling with its sign bit.
|
||||
ArithmeticShiftRight,
|
||||
/// Compare S0 with S1 under the form's relation; writes only SCC.
|
||||
/// Compare S0 with S1 under the form's relation, producing SCC or a lane mask.
|
||||
Compare,
|
||||
/// Bitwise complement of S0.
|
||||
Not,
|
||||
@@ -227,7 +227,7 @@ pub enum SccEffect {
|
||||
SelectedSrc0,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC.
|
||||
/// Where a form writes its lane mask, if any.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MaskEffect {
|
||||
/// Not written.
|
||||
@@ -236,6 +236,8 @@ pub enum MaskEffect {
|
||||
/// exists) & test(lane n), fully written; `VCC_HI` has no known value after
|
||||
/// it (docs/shaders/vector-compare.md section 3).
|
||||
LaneMask,
|
||||
/// Wave32 VOP3A compare mask written to SDST, which may be `vcc_lo`.
|
||||
SdstLaneMask,
|
||||
}
|
||||
|
||||
/// Wave-size restriction.
|
||||
@@ -288,6 +290,9 @@ pub enum OperandRule {
|
||||
/// VGPRs, no input or output modifiers, SRC2 unused. Everything else is
|
||||
/// rejected as unsupported.
|
||||
Vop3Vgpr2,
|
||||
/// VOP3A compare: VDST encodes s0-s105 or `vcc_lo`; SRC0 and SRC1 are
|
||||
/// VGPRs, SRC2 is unused and all modifiers are clear.
|
||||
Vop3CmpVgpr2,
|
||||
/// VOP2 vector: VDST is v0-v255; SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline
|
||||
/// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is
|
||||
/// rejected as unsupported.
|
||||
@@ -365,7 +370,7 @@ pub struct FormSemantics {
|
||||
pub relation: Option<CompareRelation>,
|
||||
/// SCC write.
|
||||
pub scc: SccEffect,
|
||||
/// VCC write.
|
||||
/// Implicit VCC write or explicit scalar destination for a compare mask.
|
||||
pub vcc: MaskEffect,
|
||||
/// EXEC write.
|
||||
pub exec: MaskEffect,
|
||||
|
||||
+834
-10
@@ -3421,17 +3421,62 @@ impl VectorCompareOp {
|
||||
}
|
||||
}
|
||||
|
||||
/// VOP3 encodings of registry forms (operand rule `vop3_vgpr2`).
|
||||
/// VOP3 encodings of registry forms (operand rule `vop3_cmp_vgpr2`).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorAluVop3Op {
|
||||
/// `v_add_nc_u32_e64` (VOP3 opcode 293).
|
||||
AddNcU32,
|
||||
pub enum VectorCompareVop3Op {
|
||||
/// `v_cmp_lt_i32_e64` (VOP3 opcode 129).
|
||||
CmpLtI32,
|
||||
/// `v_cmp_eq_i32_e64` (VOP3 opcode 130).
|
||||
CmpEqI32,
|
||||
/// `v_cmp_le_i32_e64` (VOP3 opcode 131).
|
||||
CmpLeI32,
|
||||
/// `v_cmp_gt_i32_e64` (VOP3 opcode 132).
|
||||
CmpGtI32,
|
||||
/// `v_cmp_ne_i32_e64` (VOP3 opcode 133).
|
||||
CmpNeI32,
|
||||
/// `v_cmp_ge_i32_e64` (VOP3 opcode 134).
|
||||
CmpGeI32,
|
||||
/// `v_cmp_lt_u32_e64` (VOP3 opcode 193).
|
||||
CmpLtU32,
|
||||
/// `v_cmp_eq_u32_e64` (VOP3 opcode 194).
|
||||
CmpEqU32,
|
||||
/// `v_cmp_le_u32_e64` (VOP3 opcode 195).
|
||||
CmpLeU32,
|
||||
/// `v_cmp_gt_u32_e64` (VOP3 opcode 196).
|
||||
CmpGtU32,
|
||||
/// `v_cmp_ne_u32_e64` (VOP3 opcode 197).
|
||||
CmpNeU32,
|
||||
/// `v_cmp_ge_u32_e64` (VOP3 opcode 198).
|
||||
CmpGeU32,
|
||||
/// `v_cmp_f_i32_e64` (VOP3 opcode 128).
|
||||
CmpFI32,
|
||||
/// `v_cmp_t_i32_e64` (VOP3 opcode 135).
|
||||
CmpTI32,
|
||||
/// `v_cmp_f_u32_e64` (VOP3 opcode 192).
|
||||
CmpFU32,
|
||||
/// `v_cmp_t_u32_e64` (VOP3 opcode 199).
|
||||
CmpTU32,
|
||||
}
|
||||
|
||||
impl VectorAluVop3Op {
|
||||
impl VectorCompareVop3Op {
|
||||
/// Every variant, in registry order.
|
||||
pub const ALL: [Self; 1] = [
|
||||
Self::AddNcU32,
|
||||
pub const ALL: [Self; 16] = [
|
||||
Self::CmpLtI32,
|
||||
Self::CmpEqI32,
|
||||
Self::CmpLeI32,
|
||||
Self::CmpGtI32,
|
||||
Self::CmpNeI32,
|
||||
Self::CmpGeI32,
|
||||
Self::CmpLtU32,
|
||||
Self::CmpEqU32,
|
||||
Self::CmpLeU32,
|
||||
Self::CmpGtU32,
|
||||
Self::CmpNeU32,
|
||||
Self::CmpGeU32,
|
||||
Self::CmpFI32,
|
||||
Self::CmpTI32,
|
||||
Self::CmpFU32,
|
||||
Self::CmpTU32,
|
||||
];
|
||||
|
||||
/// Selects the variant from the first word of its VOP3 encoding: the
|
||||
@@ -3442,7 +3487,159 @@ impl VectorAluVop3Op {
|
||||
return None;
|
||||
}
|
||||
match (word >> 16) & 0x3ff {
|
||||
128 => Some(Self::CmpFI32),
|
||||
129 => Some(Self::CmpLtI32),
|
||||
130 => Some(Self::CmpEqI32),
|
||||
131 => Some(Self::CmpLeI32),
|
||||
132 => Some(Self::CmpGtI32),
|
||||
133 => Some(Self::CmpNeI32),
|
||||
134 => Some(Self::CmpGeI32),
|
||||
135 => Some(Self::CmpTI32),
|
||||
192 => Some(Self::CmpFU32),
|
||||
193 => Some(Self::CmpLtU32),
|
||||
194 => Some(Self::CmpEqU32),
|
||||
195 => Some(Self::CmpLeU32),
|
||||
196 => Some(Self::CmpGtU32),
|
||||
197 => Some(Self::CmpNeU32),
|
||||
198 => Some(Self::CmpGeU32),
|
||||
199 => Some(Self::CmpTU32),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The form this encodes, whose declaration it inherits.
|
||||
pub const fn base(self) -> VectorCompareOp {
|
||||
match self {
|
||||
Self::CmpLtI32 => VectorCompareOp::CmpLtI32,
|
||||
Self::CmpEqI32 => VectorCompareOp::CmpEqI32,
|
||||
Self::CmpLeI32 => VectorCompareOp::CmpLeI32,
|
||||
Self::CmpGtI32 => VectorCompareOp::CmpGtI32,
|
||||
Self::CmpNeI32 => VectorCompareOp::CmpNeI32,
|
||||
Self::CmpGeI32 => VectorCompareOp::CmpGeI32,
|
||||
Self::CmpLtU32 => VectorCompareOp::CmpLtU32,
|
||||
Self::CmpEqU32 => VectorCompareOp::CmpEqU32,
|
||||
Self::CmpLeU32 => VectorCompareOp::CmpLeU32,
|
||||
Self::CmpGtU32 => VectorCompareOp::CmpGtU32,
|
||||
Self::CmpNeU32 => VectorCompareOp::CmpNeU32,
|
||||
Self::CmpGeU32 => VectorCompareOp::CmpGeU32,
|
||||
Self::CmpFI32 => VectorCompareOp::CmpFI32,
|
||||
Self::CmpTI32 => VectorCompareOp::CmpTI32,
|
||||
Self::CmpFU32 => VectorCompareOp::CmpFU32,
|
||||
Self::CmpTU32 => VectorCompareOp::CmpTU32,
|
||||
}
|
||||
}
|
||||
|
||||
/// Assembler name of the VOP3 encoding, as LLVM prints it.
|
||||
pub const fn assembly_name(self) -> &'static str {
|
||||
match self {
|
||||
Self::CmpLtI32 => "v_cmp_lt_i32_e64",
|
||||
Self::CmpEqI32 => "v_cmp_eq_i32_e64",
|
||||
Self::CmpLeI32 => "v_cmp_le_i32_e64",
|
||||
Self::CmpGtI32 => "v_cmp_gt_i32_e64",
|
||||
Self::CmpNeI32 => "v_cmp_ne_i32_e64",
|
||||
Self::CmpGeI32 => "v_cmp_ge_i32_e64",
|
||||
Self::CmpLtU32 => "v_cmp_lt_u32_e64",
|
||||
Self::CmpEqU32 => "v_cmp_eq_u32_e64",
|
||||
Self::CmpLeU32 => "v_cmp_le_u32_e64",
|
||||
Self::CmpGtU32 => "v_cmp_gt_u32_e64",
|
||||
Self::CmpNeU32 => "v_cmp_ne_u32_e64",
|
||||
Self::CmpGeU32 => "v_cmp_ge_u32_e64",
|
||||
Self::CmpFI32 => "v_cmp_f_i32_e64",
|
||||
Self::CmpTI32 => "v_cmp_t_i32_e64",
|
||||
Self::CmpFU32 => "v_cmp_f_u32_e64",
|
||||
Self::CmpTU32 => "v_cmp_t_u32_e64",
|
||||
}
|
||||
}
|
||||
|
||||
/// The validated registry row of this encoding.
|
||||
pub fn semantics(self) -> &'static FormSemantics {
|
||||
&FORMS[match self {
|
||||
Self::CmpLtI32 => 151,
|
||||
Self::CmpEqI32 => 152,
|
||||
Self::CmpLeI32 => 153,
|
||||
Self::CmpGtI32 => 154,
|
||||
Self::CmpNeI32 => 155,
|
||||
Self::CmpGeI32 => 156,
|
||||
Self::CmpLtU32 => 157,
|
||||
Self::CmpEqU32 => 158,
|
||||
Self::CmpLeU32 => 159,
|
||||
Self::CmpGtU32 => 160,
|
||||
Self::CmpNeU32 => 161,
|
||||
Self::CmpGeU32 => 162,
|
||||
Self::CmpFI32 => 163,
|
||||
Self::CmpTI32 => 164,
|
||||
Self::CmpFU32 => 165,
|
||||
Self::CmpTU32 => 166,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
/// VOP3 encodings of registry forms (operand rule `vop3_vgpr2`).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorAluVop3Op {
|
||||
/// `v_add_nc_u32_e64` (VOP3 opcode 293).
|
||||
AddNcU32,
|
||||
/// `v_mul_i32_i24_e64` (VOP3 opcode 265).
|
||||
MulI32I24,
|
||||
/// `v_mul_hi_i32_i24_e64` (VOP3 opcode 266).
|
||||
MulHiI32I24,
|
||||
/// `v_mul_u32_u24_e64` (VOP3 opcode 267).
|
||||
MulU32U24,
|
||||
/// `v_mul_hi_u32_u24_e64` (VOP3 opcode 268).
|
||||
MulHiU32U24,
|
||||
/// `v_min_i32_e64` (VOP3 opcode 273).
|
||||
MinI32,
|
||||
/// `v_max_i32_e64` (VOP3 opcode 274).
|
||||
MaxI32,
|
||||
/// `v_min_u32_e64` (VOP3 opcode 275).
|
||||
MinU32,
|
||||
/// `v_max_u32_e64` (VOP3 opcode 276).
|
||||
MaxU32,
|
||||
/// `v_xnor_b32_e64` (VOP3 opcode 286).
|
||||
XnorB32,
|
||||
/// `v_sub_nc_u32_e64` (VOP3 opcode 294).
|
||||
SubNcU32,
|
||||
/// `v_subrev_nc_u32_e64` (VOP3 opcode 295).
|
||||
SubrevNcU32,
|
||||
}
|
||||
|
||||
impl VectorAluVop3Op {
|
||||
/// Every variant, in registry order.
|
||||
pub const ALL: [Self; 12] = [
|
||||
Self::AddNcU32,
|
||||
Self::MulI32I24,
|
||||
Self::MulHiI32I24,
|
||||
Self::MulU32U24,
|
||||
Self::MulHiU32U24,
|
||||
Self::MinI32,
|
||||
Self::MaxI32,
|
||||
Self::MinU32,
|
||||
Self::MaxU32,
|
||||
Self::XnorB32,
|
||||
Self::SubNcU32,
|
||||
Self::SubrevNcU32,
|
||||
];
|
||||
|
||||
/// Selects the variant from the first word of its VOP3 encoding: the
|
||||
/// encoding bits (mask 0xfc00_0000) and then the OP field (bits
|
||||
/// 16-25). `None` for undeclared opcodes.
|
||||
pub const fn from_word(word: u32) -> Option<Self> {
|
||||
if word & 0xfc00_0000 != 0xd400_0000 {
|
||||
return None;
|
||||
}
|
||||
match (word >> 16) & 0x3ff {
|
||||
265 => Some(Self::MulI32I24),
|
||||
266 => Some(Self::MulHiI32I24),
|
||||
267 => Some(Self::MulU32U24),
|
||||
268 => Some(Self::MulHiU32U24),
|
||||
273 => Some(Self::MinI32),
|
||||
274 => Some(Self::MaxI32),
|
||||
275 => Some(Self::MinU32),
|
||||
276 => Some(Self::MaxU32),
|
||||
286 => Some(Self::XnorB32),
|
||||
293 => Some(Self::AddNcU32),
|
||||
294 => Some(Self::SubNcU32),
|
||||
295 => Some(Self::SubrevNcU32),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -3451,6 +3648,17 @@ impl VectorAluVop3Op {
|
||||
pub const fn base(self) -> VectorAluOp {
|
||||
match self {
|
||||
Self::AddNcU32 => VectorAluOp::AddNcU32,
|
||||
Self::MulI32I24 => VectorAluOp::MulI32I24,
|
||||
Self::MulHiI32I24 => VectorAluOp::MulHiI32I24,
|
||||
Self::MulU32U24 => VectorAluOp::MulU32U24,
|
||||
Self::MulHiU32U24 => VectorAluOp::MulHiU32U24,
|
||||
Self::MinI32 => VectorAluOp::MinI32,
|
||||
Self::MaxI32 => VectorAluOp::MaxI32,
|
||||
Self::MinU32 => VectorAluOp::MinU32,
|
||||
Self::MaxU32 => VectorAluOp::MaxU32,
|
||||
Self::XnorB32 => VectorAluOp::XnorB32,
|
||||
Self::SubNcU32 => VectorAluOp::SubNcU32,
|
||||
Self::SubrevNcU32 => VectorAluOp::SubrevNcU32,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3458,19 +3666,41 @@ impl VectorAluVop3Op {
|
||||
pub const fn assembly_name(self) -> &'static str {
|
||||
match self {
|
||||
Self::AddNcU32 => "v_add_nc_u32_e64",
|
||||
Self::MulI32I24 => "v_mul_i32_i24_e64",
|
||||
Self::MulHiI32I24 => "v_mul_hi_i32_i24_e64",
|
||||
Self::MulU32U24 => "v_mul_u32_u24_e64",
|
||||
Self::MulHiU32U24 => "v_mul_hi_u32_u24_e64",
|
||||
Self::MinI32 => "v_min_i32_e64",
|
||||
Self::MaxI32 => "v_max_i32_e64",
|
||||
Self::MinU32 => "v_min_u32_e64",
|
||||
Self::MaxU32 => "v_max_u32_e64",
|
||||
Self::XnorB32 => "v_xnor_b32_e64",
|
||||
Self::SubNcU32 => "v_sub_nc_u32_e64",
|
||||
Self::SubrevNcU32 => "v_subrev_nc_u32_e64",
|
||||
}
|
||||
}
|
||||
|
||||
/// The validated registry row of this encoding.
|
||||
pub fn semantics(self) -> &'static FormSemantics {
|
||||
&FORMS[match self {
|
||||
Self::AddNcU32 => 151,
|
||||
Self::AddNcU32 => 167,
|
||||
Self::MulI32I24 => 168,
|
||||
Self::MulHiI32I24 => 169,
|
||||
Self::MulU32U24 => 170,
|
||||
Self::MulHiU32U24 => 171,
|
||||
Self::MinI32 => 172,
|
||||
Self::MaxI32 => 173,
|
||||
Self::MinU32 => 174,
|
||||
Self::MaxU32 => 175,
|
||||
Self::XnorB32 => 176,
|
||||
Self::SubNcU32 => 177,
|
||||
Self::SubrevNcU32 => 178,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity of every registry form and encoding variant, in registry order.
|
||||
pub const FORM_IDS: [(&str, EncodingFamily); 152] = [
|
||||
pub const FORM_IDS: [(&str, EncodingFamily); 179] = [
|
||||
("S_ADD_U32", EncodingFamily::Sop2),
|
||||
("S_SUB_U32", EncodingFamily::Sop2),
|
||||
("S_ADD_I32", EncodingFamily::Sop2),
|
||||
@@ -3622,11 +3852,38 @@ pub const FORM_IDS: [(&str, EncodingFamily); 152] = [
|
||||
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
("V_CMP_LT_I32", EncodingFamily::Vop3),
|
||||
("V_CMP_EQ_I32", EncodingFamily::Vop3),
|
||||
("V_CMP_LE_I32", EncodingFamily::Vop3),
|
||||
("V_CMP_GT_I32", EncodingFamily::Vop3),
|
||||
("V_CMP_NE_I32", EncodingFamily::Vop3),
|
||||
("V_CMP_GE_I32", EncodingFamily::Vop3),
|
||||
("V_CMP_LT_U32", EncodingFamily::Vop3),
|
||||
("V_CMP_EQ_U32", EncodingFamily::Vop3),
|
||||
("V_CMP_LE_U32", EncodingFamily::Vop3),
|
||||
("V_CMP_GT_U32", EncodingFamily::Vop3),
|
||||
("V_CMP_NE_U32", EncodingFamily::Vop3),
|
||||
("V_CMP_GE_U32", EncodingFamily::Vop3),
|
||||
("V_CMP_F_I32", EncodingFamily::Vop3),
|
||||
("V_CMP_T_I32", EncodingFamily::Vop3),
|
||||
("V_CMP_F_U32", EncodingFamily::Vop3),
|
||||
("V_CMP_T_U32", EncodingFamily::Vop3),
|
||||
("V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
("V_MUL_I32_I24", EncodingFamily::Vop3),
|
||||
("V_MUL_HI_I32_I24", EncodingFamily::Vop3),
|
||||
("V_MUL_U32_U24", EncodingFamily::Vop3),
|
||||
("V_MUL_HI_U32_U24", EncodingFamily::Vop3),
|
||||
("V_MIN_I32", EncodingFamily::Vop3),
|
||||
("V_MAX_I32", EncodingFamily::Vop3),
|
||||
("V_MIN_U32", EncodingFamily::Vop3),
|
||||
("V_MAX_U32", EncodingFamily::Vop3),
|
||||
("V_XNOR_B32", EncodingFamily::Vop3),
|
||||
("V_SUB_NC_U32", EncodingFamily::Vop3),
|
||||
("V_SUBREV_NC_U32", EncodingFamily::Vop3),
|
||||
];
|
||||
|
||||
/// One validated row per registry form, in registry order.
|
||||
pub static FORMS: [FormSemantics; 152] = [
|
||||
pub static FORMS: [FormSemantics; 179] = [
|
||||
FormSemantics {
|
||||
name: "S_ADD_U32",
|
||||
family: EncodingFamily::Sop2,
|
||||
@@ -6798,6 +7055,342 @@ pub static FORMS: [FormSemantics; 152] = [
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.5", page: 125 }, SpecRef { document: Document::Guide, section: "13.1.5", page: 245 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_LT_I32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 129,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Less),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_EQ_I32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 130,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Equal),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_LE_I32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 131,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::LessOrEqual),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_GT_I32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 132,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Greater),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_NE_I32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 133,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::NotEqual),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_GE_I32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 134,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::GreaterOrEqual),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_LT_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 193,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Less),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_EQ_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 194,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Equal),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_LE_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 195,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::LessOrEqual),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_GT_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 196,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Greater),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_NE_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 197,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::NotEqual),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_GE_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 198,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::GreaterOrEqual),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_F_I32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 128,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::False),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_T_I32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 135,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::True),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_F_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 192,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::False),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_T_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 199,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::True),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::SdstLaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::Vop3CmpVgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_ADD_NC_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
@@ -6819,4 +7412,235 @@ pub static FORMS: [FormSemantics; 152] = [
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_MUL_I32_I24",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 265,
|
||||
operation: Operation::Multiply24,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Vop3Vgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 131 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_MUL_HI_I32_I24",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 266,
|
||||
operation: Operation::MultiplyHigh24,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Vop3Vgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 132 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_MUL_U32_U24",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 267,
|
||||
operation: Operation::Multiply24,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Vop3Vgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 132 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_MUL_HI_U32_U24",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 268,
|
||||
operation: Operation::MultiplyHigh24,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Vop3Vgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 132 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_MIN_I32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 273,
|
||||
operation: Operation::Minimum,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Vop3Vgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 133 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_MAX_I32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 274,
|
||||
operation: Operation::Maximum,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Vop3Vgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 133 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_MIN_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 275,
|
||||
operation: Operation::Minimum,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Vop3Vgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 133 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_MAX_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 276,
|
||||
operation: Operation::Maximum,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Vop3Vgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 133 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_XNOR_B32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 286,
|
||||
operation: Operation::Xnor,
|
||||
signedness: Signedness::Bitwise,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Vop3Vgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_SUB_NC_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 294,
|
||||
operation: Operation::Sub,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Vop3Vgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_SUBREV_NC_U32",
|
||||
family: EncodingFamily::Vop3,
|
||||
opcode: 295,
|
||||
operation: Operation::Sub,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: true,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Vop3Vgpr2,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
];
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{
|
||||
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave,
|
||||
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, OperandRule, SCHEMA, SccEffect,
|
||||
Signedness, Wave,
|
||||
};
|
||||
use xenora_isa::{
|
||||
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp,
|
||||
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
|
||||
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
};
|
||||
|
||||
#[test]
|
||||
@@ -261,8 +262,38 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
|
||||
assert_eq!(row.swap_sources, base.swap_sources);
|
||||
assert_eq!(op.assembly_name(), format!("{}_e64", op.base().mnemonic()));
|
||||
}
|
||||
for base_op in VectorCompareOp::ALL {
|
||||
let base = base_op.semantics();
|
||||
let mut variants = VectorCompareVop3Op::ALL
|
||||
.into_iter()
|
||||
.filter(|op| op.base() == base_op);
|
||||
if base.width != 32 {
|
||||
assert_eq!(variants.next(), None, "{}", base.name);
|
||||
continue;
|
||||
}
|
||||
let op = variants
|
||||
.next()
|
||||
.expect("32-bit VOPC form must have a VOP3A encoding");
|
||||
assert_eq!(variants.next(), None);
|
||||
let row = op.semantics();
|
||||
assert_eq!((row.name, row.family), (base.name, EncodingFamily::Vop3));
|
||||
assert_eq!(row.operation, base.operation);
|
||||
assert_eq!(row.signedness, base.signedness);
|
||||
assert_eq!(row.relation, base.relation);
|
||||
assert_eq!(row.scc, SccEffect::Unchanged);
|
||||
assert_eq!(row.exec, MaskEffect::Unchanged);
|
||||
assert_eq!(row.wave, Wave::Wave32);
|
||||
assert_eq!(row.width, 32);
|
||||
assert_eq!(row.vcc, MaskEffect::SdstLaneMask);
|
||||
assert_eq!(row.operands, OperandRule::Vop3CmpVgpr2);
|
||||
assert_eq!(op.assembly_name(), format!("{}_e64", base_op.mnemonic()));
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Vop3, |word| {
|
||||
VectorAluVop3Op::from_word(word).map(|op| op.semantics().name)
|
||||
let alu = VectorAluVop3Op::from_word(word);
|
||||
let compare = VectorCompareVop3Op::from_word(word);
|
||||
assert!(alu.is_none() || compare.is_none(), "{word:#x}");
|
||||
alu.map(|op| op.semantics().name)
|
||||
.or_else(|| compare.map(|op| op.semantics().name))
|
||||
});
|
||||
// No first word of the other 64-bit families (VOP3B shares VOP3's
|
||||
// encoding bits) selects a variant.
|
||||
@@ -276,5 +307,11 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
assert_eq!(
|
||||
VectorCompareVop3Op::from_word(meta.bits as u32),
|
||||
None,
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ gpu-tests = []
|
||||
[dependencies]
|
||||
libc = "0.2"
|
||||
sha2 = "0.10"
|
||||
xenora-texture = { path = "../texture" }
|
||||
|
||||
[dev-dependencies]
|
||||
xenora-metal = { path = "../metal" }
|
||||
@@ -24,3 +25,7 @@ xenora-shader = { path = "../shader" }
|
||||
[[bench]]
|
||||
name = "dbt_bench"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "service_dispatch"
|
||||
harness = false
|
||||
+1215
-22
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,225 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest-to-host service dispatch cost, measured with original guest loops
|
||||
//! that call standard services through a bound import table under the DBT.
|
||||
//!
|
||||
//! Every workload checks its result before timing. Each reported figure is
|
||||
//! the per-iteration time of a loop of `ITERATIONS` calls: one warm-up batch,
|
||||
//! then `BATCHES` measured batches. The empty loop is reported separately so
|
||||
//! readers can subtract the loop and translation overhead themselves.
|
||||
//!
|
||||
//! Run with `cargo bench --locked -p xenora-loader --bench service_dispatch`.
|
||||
|
||||
#[path = "../tests/support/mod.rs"]
|
||||
mod support;
|
||||
|
||||
use std::time::Instant;
|
||||
use support::*;
|
||||
use xenora_loader::cpu::{ExitReason, Register};
|
||||
use xenora_loader::services::sysinfo::HostCapabilities;
|
||||
|
||||
const IMPORTS: &[(&str, &str)] = &[
|
||||
("kernel32.dll", "GetLastError"),
|
||||
("kernel32.dll", "CreateEventW"),
|
||||
("kernel32.dll", "WaitForSingleObject"),
|
||||
("ucrtbase.dll", "strlen"),
|
||||
("kernel32.dll", "GetProcessHeap"),
|
||||
("kernel32.dll", "HeapAlloc"),
|
||||
("kernel32.dll", "HeapFree"),
|
||||
("ucrtbase.dll", "qsort"),
|
||||
];
|
||||
|
||||
const ITERATIONS: u32 = 10_000;
|
||||
const BATCHES: usize = 10;
|
||||
const CELL_EVENT: u64 = SCRATCH + 0x10;
|
||||
const CELL_HEAP: u64 = SCRATCH + 0x18;
|
||||
const STRING: u64 = SCRATCH + 0x100;
|
||||
const ARRAY: u64 = SCRATCH + 0x200;
|
||||
const ARRAY_LEN: u32 = 16;
|
||||
|
||||
const EMPTY: usize = 0;
|
||||
const LAST_ERROR: usize = 1;
|
||||
const WAIT: usize = 2;
|
||||
const STRLEN: usize = 3;
|
||||
const HEAP: usize = 4;
|
||||
const QSORT: usize = 5;
|
||||
const COMPARE: usize = 6;
|
||||
|
||||
/// A tiny x86-64 assembler for the routines below.
|
||||
struct Asm {
|
||||
base: u64,
|
||||
code: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Asm {
|
||||
fn new(routine_index: usize) -> Self {
|
||||
Self {
|
||||
base: routine(routine_index),
|
||||
code: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn bytes(&mut self, bytes: &[u8]) -> &mut Self {
|
||||
self.code.extend_from_slice(bytes);
|
||||
self
|
||||
}
|
||||
|
||||
fn imm64(&mut self, opcode: &[u8], value: u64) -> &mut Self {
|
||||
self.bytes(opcode).bytes(&value.to_le_bytes())
|
||||
}
|
||||
|
||||
fn imm32(&mut self, opcode: &[u8], value: u32) -> &mut Self {
|
||||
self.bytes(opcode).bytes(&value.to_le_bytes())
|
||||
}
|
||||
|
||||
/// `call qword ptr [rip + displacement]` through an import slot.
|
||||
fn call_import(&mut self, symbol: &str) -> &mut Self {
|
||||
let index = IMPORTS
|
||||
.iter()
|
||||
.position(|(_, name)| *name == symbol)
|
||||
.unwrap();
|
||||
let next = self.base + self.code.len() as u64 + 6;
|
||||
let displacement = import_slot(IMPORTS, index).wrapping_sub(next) as u32;
|
||||
self.imm32(&[0xFF, 0x15], displacement)
|
||||
}
|
||||
|
||||
/// `mov ebx, ITERATIONS`, the loop body, `dec ebx; jnz body; hlt`.
|
||||
fn counted(routine_index: usize, body: impl FnOnce(&mut Self)) -> Vec<u8> {
|
||||
let mut asm = Self::new(routine_index);
|
||||
asm.imm32(&[0xBB], ITERATIONS);
|
||||
let start = asm.code.len();
|
||||
body(&mut asm);
|
||||
asm.bytes(&[0xFF, 0xCB]); // dec ebx
|
||||
let back = start as i64 - (asm.code.len() as i64 + 2);
|
||||
asm.bytes(&[0x75, i8::try_from(back).unwrap() as u8, 0xF4]);
|
||||
asm.code
|
||||
}
|
||||
}
|
||||
|
||||
fn routines() -> Vec<Vec<u8>> {
|
||||
let mut routines = vec![Vec::new(); 7];
|
||||
routines[EMPTY] = Asm::counted(EMPTY, |_| {});
|
||||
routines[LAST_ERROR] = Asm::counted(LAST_ERROR, |asm| {
|
||||
asm.call_import("GetLastError");
|
||||
});
|
||||
routines[WAIT] = Asm::counted(WAIT, |asm| {
|
||||
asm.imm64(&[0x48, 0xB8], CELL_EVENT) // mov rax, cell
|
||||
.bytes(&[0x48, 0x8B, 0x08]) // mov rcx, [rax]
|
||||
.bytes(&[0x31, 0xD2]) // xor edx, edx
|
||||
.call_import("WaitForSingleObject");
|
||||
});
|
||||
routines[STRLEN] = Asm::counted(STRLEN, |asm| {
|
||||
asm.imm64(&[0x48, 0xB9], STRING).call_import("strlen");
|
||||
});
|
||||
routines[HEAP] = Asm::counted(HEAP, |asm| {
|
||||
asm.imm64(&[0x48, 0xB8], CELL_HEAP)
|
||||
.bytes(&[0x48, 0x8B, 0x08]) // mov rcx, [rax]
|
||||
.bytes(&[0x31, 0xD2])
|
||||
.imm32(&[0x41, 0xB8], 64) // mov r8d, 64
|
||||
.call_import("HeapAlloc")
|
||||
.bytes(&[0x49, 0x89, 0xC0]) // mov r8, rax
|
||||
.imm64(&[0x48, 0xB8], CELL_HEAP)
|
||||
.bytes(&[0x48, 0x8B, 0x08])
|
||||
.bytes(&[0x31, 0xD2])
|
||||
.call_import("HeapFree");
|
||||
});
|
||||
routines[QSORT] = Asm::counted(QSORT, |asm| {
|
||||
asm.imm64(&[0x48, 0xB9], ARRAY)
|
||||
.imm32(&[0xBA], ARRAY_LEN) // mov edx, count
|
||||
.imm32(&[0x41, 0xB8], 4) // mov r8d, width
|
||||
.imm64(&[0x49, 0xB9], routine(COMPARE))
|
||||
.call_import("qsort");
|
||||
});
|
||||
// int compare(const int *a, const int *b) { return *a - *b; }
|
||||
routines[COMPARE] = vec![0x8B, 0x01, 0x2B, 0x02, 0xC3];
|
||||
routines
|
||||
}
|
||||
|
||||
fn median(samples: &mut [f64]) -> f64 {
|
||||
samples.sort_by(f64::total_cmp);
|
||||
samples[samples.len() / 2]
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut guest = Guest::new(IMPORTS, &routines());
|
||||
let event = guest.call("CreateEventW", &[0, 1, 1, 0]);
|
||||
assert_ne!(event, 0);
|
||||
guest.memory.write_u64(CELL_EVENT, event).unwrap();
|
||||
let heap = guest.call("GetProcessHeap", &[]);
|
||||
guest.memory.write_u64(CELL_HEAP, heap).unwrap();
|
||||
guest.memory.write_bytes(STRING, &[b'a'; 63]).unwrap();
|
||||
guest.memory.write_u8(STRING + 63, 0).unwrap();
|
||||
let unsorted: Vec<i32> = (0..ARRAY_LEN as i32)
|
||||
.map(|i| (i * 7919) % 31 - 15)
|
||||
.collect();
|
||||
|
||||
let reset_array = |guest: &mut Guest| {
|
||||
for (index, value) in unsorted.iter().enumerate() {
|
||||
guest
|
||||
.memory
|
||||
.write_u32(ARRAY + 4 * index as u64, *value as u32)
|
||||
.unwrap();
|
||||
}
|
||||
};
|
||||
|
||||
let host = HostCapabilities::detect();
|
||||
let brand = std::process::Command::new("sysctl")
|
||||
.args(["-n", "machdep.cpu.brand_string"])
|
||||
.output()
|
||||
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
|
||||
.unwrap_or_default();
|
||||
println!(
|
||||
"host: {brand}, {} logical processors; profile: {}",
|
||||
host.logical_processors.unwrap_or(0),
|
||||
if cfg!(debug_assertions) {
|
||||
"debug"
|
||||
} else {
|
||||
"release"
|
||||
},
|
||||
);
|
||||
println!("{ITERATIONS} iterations per batch, 1 warm-up and {BATCHES} measured batches");
|
||||
println!("workload,median_ns_per_iteration,min_ns,max_ns");
|
||||
|
||||
for (name, index, check) in [
|
||||
("empty loop", EMPTY, None),
|
||||
("GetLastError", LAST_ERROR, Some(0)),
|
||||
(
|
||||
"WaitForSingleObject (signaled manual-reset event)",
|
||||
WAIT,
|
||||
Some(0),
|
||||
),
|
||||
("strlen (63 bytes)", STRLEN, Some(63)),
|
||||
("HeapAlloc + HeapFree (64 bytes)", HEAP, Some(1)),
|
||||
("qsort (16 ints, guest comparator)", QSORT, Some(0)),
|
||||
] {
|
||||
let mut samples = Vec::with_capacity(BATCHES);
|
||||
for batch in 0..=BATCHES {
|
||||
if index == QSORT {
|
||||
reset_array(&mut guest);
|
||||
}
|
||||
let start = Instant::now();
|
||||
let (cpu, exit) = guest.execute(routine(index), usize::MAX);
|
||||
let elapsed = start.elapsed();
|
||||
assert_eq!(exit, ExitReason::Halt, "{name}");
|
||||
assert_eq!(cpu.get(Register::Rbx), 0, "{name} loop count");
|
||||
if let Some(expected) = check {
|
||||
assert_eq!(cpu.get(Register::Rax), expected, "{name} result");
|
||||
}
|
||||
if index == QSORT {
|
||||
let mut expected = unsorted.clone();
|
||||
expected.sort();
|
||||
let sorted: Vec<i32> = (0..ARRAY_LEN as u64)
|
||||
.map(|i| guest.u32_at(ARRAY + 4 * i) as i32)
|
||||
.collect();
|
||||
assert_eq!(sorted, expected, "{name} ordering");
|
||||
}
|
||||
if batch > 0 {
|
||||
samples.push(elapsed.as_nanos() as f64 / f64::from(ITERATIONS));
|
||||
}
|
||||
}
|
||||
let (min, max) = samples.iter().fold((f64::MAX, 0f64), |(low, high), &s| {
|
||||
(low.min(s), high.max(s))
|
||||
});
|
||||
println!("{name},{:.1},{min:.1},{max:.1}", median(&mut samples));
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,9 @@
|
||||
differs. Never writes.
|
||||
|
||||
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
|
||||
forms sharing an opcode, operand constraints that contradict each other, LOCK
|
||||
on a form that cannot write memory, and flags declared both written and
|
||||
undefined. Standard library only (Python 3.11+).
|
||||
forms sharing an opcode, operand constraints that contradict each other, a
|
||||
fixed r/m field on a form that could take memory, LOCK on a form that cannot
|
||||
write memory, and flags declared both written and undefined. Standard library only (Python 3.11+).
|
||||
"""
|
||||
|
||||
import sys
|
||||
@@ -27,7 +27,7 @@ RUST = HERE / "src/x86_table.rs"
|
||||
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
|
||||
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
|
||||
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
|
||||
"memory_only", "register_only", "no_rex_b", "unaligned", "lock"}
|
||||
"memory_only", "register_only", "rm", "no_rex_b", "unaligned", "lock"}
|
||||
GROUP_KEYS = {"map", "opcodes", "digits"}
|
||||
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
|
||||
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
|
||||
@@ -50,6 +50,8 @@ ENCS = {
|
||||
"rm_imm": ("RmImm", True, {"ib", "iz"}),
|
||||
"rm_one": ("RmOne", True, {""}),
|
||||
"rm_cl": ("RmCl", True, {""}),
|
||||
"rm_reg_imm": ("RmRegImm", True, {"ub"}),
|
||||
"rm_reg_cl": ("RmRegCl", True, {""}),
|
||||
"acc_imm": ("AccImm", False, {"ib", "iz"}),
|
||||
"op_reg": ("OpReg", False, {""}),
|
||||
"op_reg_imm": ("OpRegImm", False, {"ib", "iv"}),
|
||||
@@ -66,7 +68,7 @@ ENCS = {
|
||||
"reg_xmm_imm": ("RegXmmImm", True, {"ub"}),
|
||||
}
|
||||
# Encodings whose ModRM operand is the destination, so LOCK can apply to it.
|
||||
RM_DESTINATIONS = {"rm_reg", "rm", "rm_imm", "rm_one", "rm_cl"}
|
||||
RM_DESTINATIONS = {"rm_reg", "rm", "rm_imm", "rm_one", "rm_cl", "rm_reg_imm", "rm_reg_cl"}
|
||||
# Encodings whose ModRM operand is an XMM register or memory of the source width.
|
||||
XMM_RM = {"xmm_rm", "rm_xmm", "xmm_rm_imm", "rm_imm_xmm", "reg_xmm", "reg_xmm_imm"}
|
||||
# One-byte opcodes that are prefixes or the two-byte escape, never instructions.
|
||||
@@ -167,6 +169,13 @@ def load(text):
|
||||
fail(f"{where}: memory_only and register_only contradict")
|
||||
if (form.get("memory_only") or form.get("register_only")) and not modrm:
|
||||
fail(f"{where}: operand restriction without ModRM")
|
||||
form.setdefault("rm", None)
|
||||
if form["rm"] is not None:
|
||||
# bool is an int in Python; `rm = true` is not a field value.
|
||||
if type(form["rm"]) is not int or not 0 <= form["rm"] <= 7:
|
||||
fail(f"{where}: rm must be a ModRM r/m field value 0-7")
|
||||
if not form.get("register_only") or form["digit"] is None:
|
||||
fail(f"{where}: a fixed r/m field needs register_only and a digit")
|
||||
sourced = form["enc"] in XMM_RM or form["enc"] == "xmm_gpr_imm"
|
||||
if sourced != bool(form["src"]) and form["enc"] not in ("reg_rm", "rm"):
|
||||
fail(f"{where}: source size does not match the encoding")
|
||||
@@ -271,6 +280,7 @@ def generate(operations, forms):
|
||||
f"source: {SRCS[form['src']]}, has_modrm: {str(ENCS[form['enc']][1]).lower()}, "
|
||||
f"memory_only: {str(bool(form.get('memory_only'))).lower()}, "
|
||||
f"register_only: {str(bool(form.get('register_only'))).lower()}, "
|
||||
f"fixed_rm: {'None' if form['rm'] is None else 'Some(%d)' % form['rm']}, "
|
||||
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
|
||||
f"unaligned: {str(bool(form.get('unaligned'))).lower()}, "
|
||||
f"lockable: {str(bool(form.get('lock'))).lower()} }},")
|
||||
|
||||
@@ -116,6 +116,93 @@ service kernel32.dll GetSystemTimeAsFileTime(time: out<8>) -> void
|
||||
ref sysinfoapi.h GetSystemTimeAsFileTime
|
||||
test system_time_comes_from_the_injected_clock
|
||||
|
||||
# Standard streams and formatted output for a hosted C program. Output to
|
||||
# stdout and stderr is captured, and a stream from fopen is a file. A pointer
|
||||
# that is no stream, reading stdin, and floating-point and wide conversions
|
||||
# stop the guest with the runtime-limit fault.
|
||||
|
||||
service ucrtbase.dll __acrt_iob_func(index: u32) -> ptr
|
||||
handler standard_stream
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest for an index above 2 or when the streams cannot be allocated
|
||||
ref corecrt_wstdio.h __acrt_iob_func
|
||||
test standard_streams_are_three_stable_file_objects
|
||||
|
||||
service ucrtbase.dll __stdio_common_vfprintf(options: u64, stream: ptr, format: ptr, locale: ptr, arguments: ptr) -> i32
|
||||
handler vfprintf
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled
|
||||
ref corecrt_stdio_config.h __stdio_common_vfprintf; Microsoft Learn, vfprintf and format specification syntax
|
||||
test formatted_output_reaches_the_captured_standard_streams
|
||||
|
||||
service ucrtbase.dll fwrite(buffer: ptr, size: u64, count: u64, stream: ptr) -> u64
|
||||
handler fwrite
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails 0 with errno EINVAL for a null buffer or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream
|
||||
ref stdio.h fwrite
|
||||
test fwrite_and_fputs_write_to_the_captured_standard_streams
|
||||
|
||||
service ucrtbase.dll fputs(text: ptr, stream: ptr) -> i32
|
||||
handler fputs
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails EOF with errno EINVAL for a null string or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream
|
||||
ref stdio.h fputs
|
||||
test fwrite_and_fputs_write_to_the_captured_standard_streams
|
||||
|
||||
service ucrtbase.dll fflush(stream: ptr) -> i32
|
||||
handler fflush
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest for a pointer that is no stream
|
||||
ref stdio.h fflush
|
||||
test fflush_and_setvbuf_return_their_documented_results
|
||||
|
||||
service ucrtbase.dll setvbuf(stream: ptr, buffer: ptr, mode: i32, size: u64) -> i32
|
||||
handler setvbuf
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a pointer that is no stream
|
||||
ref stdio.h setvbuf
|
||||
test fflush_and_setvbuf_return_their_documented_results
|
||||
|
||||
# Files for a hosted C program, on the in-memory drive the handle services use.
|
||||
|
||||
service ucrtbase.dll fopen(name: ptr, mode: ptr) -> ptr
|
||||
handler fopen
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails null with errno EINVAL, ENOENT, EACCES, EMFILE, ENOSPC or ENOMEM
|
||||
ref stdio.h fopen
|
||||
test a_file_written_through_a_stream_reads_back_line_by_line
|
||||
|
||||
service ucrtbase.dll fclose(stream: ptr) -> i32
|
||||
handler fclose
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails EOF with errno EINVAL for a null stream; stops the guest for a standard stream or a pointer that is no stream
|
||||
ref stdio.h fclose
|
||||
test a_file_written_through_a_stream_reads_back_line_by_line
|
||||
|
||||
service ucrtbase.dll fgets(buffer: ptr, count: i32, stream: ptr) -> ptr
|
||||
handler fgets
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails null at end of file; null with errno EINVAL or EBADF; stops the guest for stdin or a pointer that is no stream
|
||||
ref stdio.h fgets
|
||||
test fgets_reads_lines_within_its_count
|
||||
|
||||
service ucrtbase.dll perror(message: ptr) -> void
|
||||
handler perror
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails never
|
||||
ref stdio.h perror
|
||||
test perror_writes_the_message_and_the_error_text_to_stderr
|
||||
|
||||
service kernel32.dll GetLastError() -> u32
|
||||
handler get_last_error
|
||||
status partial
|
||||
@@ -132,6 +219,51 @@ service kernel32.dll SetLastError(code: u32) -> void
|
||||
ref errhandlingapi.h SetLastError
|
||||
test last_error_is_set_by_failures_and_by_the_guest
|
||||
|
||||
# What a hosted C program's startup code hands to `main`. The three pointer
|
||||
# functions and the two initialization functions are listed by Microsoft only
|
||||
# by name; crates/loader/src/services/crt_arguments.rs says what is documented,
|
||||
# inferred and Xenora's choice.
|
||||
|
||||
service ucrtbase.dll __p___argc() -> ptr
|
||||
handler argc_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, __argc, __argv, __wargv
|
||||
test program_arguments_reach_the_guest_as_argc_and_argv
|
||||
|
||||
service ucrtbase.dll __p___argv() -> ptr
|
||||
handler argv_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, __argc, __argv, __wargv
|
||||
test program_arguments_reach_the_guest_as_argc_and_argv
|
||||
|
||||
service ucrtbase.dll __p__environ() -> ptr
|
||||
handler environ_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-environment-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, _environ, _wenviron
|
||||
test the_environment_table_is_empty_and_ends_with_a_null_pointer
|
||||
|
||||
service ucrtbase.dll _configure_narrow_argv(mode: i32) -> i32
|
||||
handler configure_narrow_argv
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails EINVAL for a mode other than 0, 1 or 2; stops the guest when the table cannot be allocated
|
||||
ref corecrt_startup.h _configure_narrow_argv
|
||||
test program_arguments_reach_the_guest_as_argc_and_argv
|
||||
|
||||
service ucrtbase.dll _initialize_narrow_environment() -> i32
|
||||
handler initialize_narrow_environment
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails stops the guest when the table cannot be allocated
|
||||
ref corecrt_startup.h _initialize_narrow_environment
|
||||
test the_environment_table_is_empty_and_ends_with_a_null_pointer
|
||||
|
||||
service kernel32.dll VirtualAlloc(address: ptr, size: u64, kind: u32, protect: u32) -> ptr
|
||||
handler virtual_alloc
|
||||
status partial
|
||||
@@ -148,6 +280,34 @@ service kernel32.dll VirtualFree(address: ptr, size: u64, kind: u32) -> bool32
|
||||
ref memoryapi.h VirtualFree
|
||||
test virtual_memory_is_mapped_released_and_bounded
|
||||
|
||||
# Stubs. A program built with the mingw-w64 runtime imports these three and
|
||||
# does not call them on a normal run. They exist so that its imports bind. A
|
||||
# call stops the guest with the runtime-limit fault and changes nothing.
|
||||
|
||||
service kernel32.dll VirtualProtect(address: ptr, size: u64, protect: u32, old: out<4>) -> bool32
|
||||
handler virtual_protect
|
||||
status stub
|
||||
alias api-ms-win-core-memory-l1-1-0.dll
|
||||
fails always: stops the guest with the runtime-limit fault; no protection changes
|
||||
ref memoryapi.h VirtualProtect
|
||||
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
|
||||
|
||||
service kernel32.dll VirtualQuery(address: ptr, information: out<48>, length: u64) -> u64
|
||||
handler virtual_query
|
||||
status stub
|
||||
alias api-ms-win-core-memory-l1-1-0.dll
|
||||
fails always: stops the guest with the runtime-limit fault; nothing is written
|
||||
ref memoryapi.h VirtualQuery
|
||||
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
|
||||
|
||||
service ucrtbase.dll __C_specific_handler(record: ptr, frame: ptr, context: ptr, dispatcher: ptr) -> i32
|
||||
handler c_specific_handler
|
||||
status stub
|
||||
alias api-ms-win-crt-private-l1-1-0.dll
|
||||
fails always: stops the guest with the runtime-limit fault; no exception is dispatched
|
||||
ref Microsoft Learn, x64 exception handling, language-specific handler
|
||||
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
|
||||
|
||||
service ucrtbase.dll sqrt(x: f64) -> f64
|
||||
handler sqrt
|
||||
status partial
|
||||
@@ -179,3 +339,78 @@ service ucrtbase.dll fabsf(x: f32) -> f32
|
||||
fails never
|
||||
ref math.h fabsf (ISO C, IEC 60559 abs)
|
||||
test floating_arguments_and_results_use_xmm_registers
|
||||
|
||||
# What a C program's startup code configures before `main`. Each value is
|
||||
# recorded and returned as documented; nothing in the runtime acts on it.
|
||||
|
||||
service ucrtbase.dll _set_app_type(kind: i32) -> void
|
||||
handler set_app_type
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails never
|
||||
ref corecrt_startup.h _set_app_type
|
||||
test crt_app_type_and_math_error_handler_are_recorded
|
||||
|
||||
service ucrtbase.dll _set_new_mode(mode: i32) -> i32
|
||||
handler set_new_mode
|
||||
status partial
|
||||
alias api-ms-win-crt-heap-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a mode other than 0 or 1
|
||||
ref new.h _set_new_mode
|
||||
test crt_startup_modes_return_the_previous_setting
|
||||
|
||||
service ucrtbase.dll _configthreadlocale(request: i32) -> i32
|
||||
handler configure_thread_locale
|
||||
status partial
|
||||
alias api-ms-win-crt-locale-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a request other than 0, 1 or 2
|
||||
ref locale.h _configthreadlocale
|
||||
test crt_startup_modes_return_the_previous_setting
|
||||
|
||||
service ucrtbase.dll __setusermatherr(handler: ptr) -> void
|
||||
handler set_user_math_error
|
||||
status partial
|
||||
alias api-ms-win-crt-math-l1-1-0.dll
|
||||
fails never
|
||||
ref corecrt_startup.h __setusermatherr
|
||||
test crt_app_type_and_math_error_handler_are_recorded
|
||||
|
||||
service ucrtbase.dll _set_invalid_parameter_handler(handler: ptr) -> ptr
|
||||
handler set_invalid_parameter_handler
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails never
|
||||
ref stdlib.h _set_invalid_parameter_handler
|
||||
test crt_startup_handlers_return_the_previous_handler
|
||||
|
||||
service ucrtbase.dll __p__fmode() -> ptr
|
||||
handler file_mode_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, __p__fmode
|
||||
test crt_file_mode_variables_are_guest_memory
|
||||
|
||||
service ucrtbase.dll __p__commode() -> ptr
|
||||
handler commit_mode_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, __p__commode
|
||||
test crt_file_mode_variables_are_guest_memory
|
||||
|
||||
service ucrtbase.dll signal(signal: i32, handler: ptr) -> ptr
|
||||
handler signal
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails SIG_ERR with errno EINVAL for a signal the documentation does not list
|
||||
ref signal.h signal
|
||||
test crt_startup_handlers_return_the_previous_handler
|
||||
|
||||
service kernel32.dll SetUnhandledExceptionFilter(filter: ptr) -> ptr
|
||||
handler set_unhandled_exception_filter
|
||||
status partial
|
||||
alias api-ms-win-core-errorhandling-l1-1-0.dll
|
||||
fails never
|
||||
ref errhandlingapi.h SetUnhandledExceptionFilter
|
||||
test crt_startup_handlers_return_the_previous_handler
|
||||
+239
-20
@@ -307,23 +307,27 @@ impl Arm64Assembler {
|
||||
}
|
||||
|
||||
/// RBIT Xd, Xn: reverse the bit order of the source.
|
||||
/// Panics if a register number exceeds 31.
|
||||
pub fn rbit_64(&mut self, xd: u8, xn: u8) {
|
||||
self.emit(0xdac0_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
|
||||
assert!(xd <= XZR && xn <= XZR, "RBIT register must be in 0..=31");
|
||||
self.emit(0xdac0_0000 | (u32::from(xn) << 5) | u32::from(xd));
|
||||
}
|
||||
|
||||
/// CLZ Xd, Xn: count the leading zero bits of the source.
|
||||
/// Panics if a register number exceeds 31.
|
||||
pub fn clz_64(&mut self, xd: u8, xn: u8) {
|
||||
self.emit(0xdac0_1000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
|
||||
assert!(xd <= XZR && xn <= XZR, "CLZ register must be in 0..=31");
|
||||
self.emit(0xdac0_1000 | (u32::from(xn) << 5) | u32::from(xd));
|
||||
}
|
||||
|
||||
/// LSLV Xd, Xn, Xm: shift the source left by the amount in Xm.
|
||||
/// Panics if a register number exceeds 31.
|
||||
pub fn lslv_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0x9ac2_2000
|
||||
| ((u32::from(xm) & 0x1f) << 16)
|
||||
| ((u32::from(xn) & 0x1f) << 5)
|
||||
| (u32::from(xd) & 0x1f),
|
||||
assert!(
|
||||
xd <= XZR && xn <= XZR && xm <= XZR,
|
||||
"LSLV register must be in 0..=31"
|
||||
);
|
||||
self.emit(0x9ac0_2000 | (u32::from(xm) << 16) | (u32::from(xn) << 5) | u32::from(xd));
|
||||
}
|
||||
|
||||
/// LDR Qt, [Xn, #offset] (offset a multiple of 16)
|
||||
@@ -430,6 +434,46 @@ impl Arm64Assembler {
|
||||
);
|
||||
}
|
||||
|
||||
/// ADCS (64-bit, flags updating): ADCS Xd, Xn, Xm computes Xn + Xm + C.
|
||||
pub fn adcs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xba000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADCS (32-bit, flags updating): ADCS Wd, Wn, Wm computes Wn + Wm + C.
|
||||
pub fn adcs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x3a000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SBCS (64-bit, flags updating): SBCS Xd, Xn, Xm computes Xn - Xm - !C.
|
||||
pub fn sbcs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xfa000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SBCS (32-bit, flags updating): SBCS Wd, Wn, Wm computes Wn - Wm - !C.
|
||||
pub fn sbcs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x7a000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADD (immediate, 64-bit): ADD Xd, Xn, #imm12
|
||||
pub fn add_imm_64(&mut self, xd: u8, xn: u8, imm12: u16) {
|
||||
self.emit(
|
||||
@@ -582,22 +626,42 @@ impl Arm64Assembler {
|
||||
self.emit(0xf2800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// Load a full 64-bit constant into register Xd.
|
||||
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
|
||||
let w0 = (val & 0xffff) as u16;
|
||||
let w1 = ((val >> 16) & 0xffff) as u16;
|
||||
let w2 = ((val >> 32) & 0xffff) as u16;
|
||||
let w3 = ((val >> 48) & 0xffff) as u16;
|
||||
/// MOVN (64-bit with shift): MOVN Xd, #imm16, LSL #shift writes
|
||||
/// NOT (imm16 << shift), so every other halfword becomes 0xFFFF.
|
||||
pub fn movn_64(&mut self, xd: u8, imm16: u16, shift_idx: u8) {
|
||||
let hw = (shift_idx & 3) as u32;
|
||||
self.emit(0x92800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
self.movz_64(xd, w0, 0);
|
||||
if w1 != 0 || (w2 == 0 && w3 == 0) {
|
||||
self.movk_64(xd, w1, 1);
|
||||
/// Load a full 64-bit constant into Xd with the fewest wide moves.
|
||||
/// A 32-bit MOVN leaves one low halfword set to 0xFFFF and zero-extends
|
||||
/// the result into Xd. For other values, select a 64-bit MOVZ or MOVN
|
||||
/// background and use MOVK for the remaining halfwords.
|
||||
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
|
||||
let halves: [u16; 4] = std::array::from_fn(|i| (val >> (16 * i)) as u16);
|
||||
let zeros = halves.iter().filter(|&&h| h == 0).count();
|
||||
let ones = halves.iter().filter(|&&h| h == 0xffff).count();
|
||||
// With only the top two halfwords zero, a 32-bit MOVN saves one
|
||||
// instruction when either of the lower halfwords is all ones.
|
||||
if zeros == 2 && ones != 0 && val >> 32 == 0 {
|
||||
let index = usize::from(halves[1] != u16::MAX);
|
||||
let imm16 = u32::from(!halves[index]);
|
||||
self.emit(0x1280_0000 | ((index as u32) << 21) | (imm16 << 5) | u32::from(xd & 0x1f));
|
||||
return;
|
||||
}
|
||||
if w2 != 0 || w3 != 0 {
|
||||
self.movk_64(xd, w2, 2);
|
||||
let background = if ones > zeros { 0xffff } else { 0 };
|
||||
// The first halfword that differs from the background, or halfword 0
|
||||
// when none does (val is 0 or all ones).
|
||||
let first = halves.iter().position(|&h| h != background).unwrap_or(0);
|
||||
if background == 0 {
|
||||
self.movz_64(xd, halves[first], first as u8);
|
||||
} else {
|
||||
self.movn_64(xd, !halves[first], first as u8);
|
||||
}
|
||||
if w3 != 0 {
|
||||
self.movk_64(xd, w3, 3);
|
||||
for (index, &half) in halves.iter().enumerate().skip(first + 1) {
|
||||
if half != background {
|
||||
self.movk_64(xd, half, index as u8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -778,6 +842,44 @@ mod tests {
|
||||
assert_eq!(branch.instructions()[0], 0x14000005);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rbit_clz_lslv_encodings_match_llvm() {
|
||||
// A64 words from Apple Clang's integrated assembler and llvm-objdump.
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.rbit_64(X10, X9); // rbit x10, x9
|
||||
asm.rbit_64(X0, XZR); // rbit x0, xzr
|
||||
asm.clz_64(X10, X10); // clz x10, x10
|
||||
asm.clz_64(XZR, X30); // clz xzr, x30
|
||||
asm.lslv_64(X11, X11, X10); // lslv x11, x11, x10
|
||||
asm.lslv_64(X0, X1, X0); // lslv x0, x1, x0
|
||||
asm.lslv_64(XZR, X30, XZR); // lslv xzr, x30, xzr
|
||||
assert_eq!(
|
||||
asm.instructions(),
|
||||
[
|
||||
0xdac0012a, 0xdac003e0, 0xdac0114a, 0xdac013df, 0x9aca216b, 0x9ac02020, 0x9adf23df,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rbit_clz_lslv_reject_out_of_range_registers() {
|
||||
let invalid_operands: [fn(&mut Arm64Assembler); 7] = [
|
||||
|asm| asm.rbit_64(32, X0),
|
||||
|asm| asm.rbit_64(X0, 32),
|
||||
|asm| asm.clz_64(32, X0),
|
||||
|asm| asm.clz_64(X0, 32),
|
||||
|asm| asm.lslv_64(32, X0, X0),
|
||||
|asm| asm.lslv_64(X0, 32, X0),
|
||||
|asm| asm.lslv_64(X0, X0, 32),
|
||||
];
|
||||
for (index, emit) in invalid_operands.into_iter().enumerate() {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| emit(&mut asm)));
|
||||
assert!(result.is_err(), "invalid operand case {index} was accepted");
|
||||
assert!(asm.instructions().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsigned_offset_stores_scale_by_access_size() {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
@@ -786,4 +888,121 @@ mod tests {
|
||||
asm.str_uoff_32(X0, X19, 136);
|
||||
assert_eq!(asm.instructions(), &[0xf90013f5, 0xf9404269, 0xb9008a60]);
|
||||
}
|
||||
|
||||
/// Constants at the halfword boundaries the MOVZ/MOVN choice depends on.
|
||||
const IMMEDIATE_EDGES: [u64; 18] = [
|
||||
0,
|
||||
1,
|
||||
0xffff,
|
||||
0x1_0000,
|
||||
0x8000_0000,
|
||||
0xffff_1234,
|
||||
0x1234_ffff,
|
||||
0xffff_ffff,
|
||||
0x1_0000_0000,
|
||||
0x1234_0000_0000_0000,
|
||||
0x0000_0001_0000_0005,
|
||||
0x1234_5678_9abc_def0,
|
||||
0x7fff_ffff_ffff_ffff,
|
||||
0x8000_0000_0000_0000,
|
||||
0xffff_0000_ffff_ffff,
|
||||
0xffff_ffff_edcc_5678,
|
||||
0xffff_ffff_ffff_1234,
|
||||
u64::MAX,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn immediate_sequences_match_llvm_encodings() {
|
||||
// A64 words from llvm-mc and Apple Clang's integrated assembler.
|
||||
let cases: &[(u64, &[u32])] = &[
|
||||
(0, &[0xd2800000]), // movz x0, #0
|
||||
(u64::MAX, &[0x92800000]), // movn x0, #0
|
||||
(0xffff_1234, &[0x129db960]), // movn w0, #0xedcb
|
||||
(0x1234_ffff, &[0x12bdb960]), // movn w0, #0xedcb, lsl #16
|
||||
(0xffff_ffff, &[0x12800000]), // movn w0, #0
|
||||
(0xffff_ffff_ffff_1234, &[0x929db960]), // movn x0, #0xedcb
|
||||
(0x1234_0000_0000_0000, &[0xd2e24680]), // movz x0, #0x1234, lsl #48
|
||||
(0xffff_0000_ffff_ffff, &[0x92dfffe0]), // movn x0, #0xffff, lsl #32
|
||||
(0x0000_0001_0000_0005, &[0xd28000a0, 0xf2c00020]), // movz #5; movk #1, lsl #32
|
||||
// movn x0, #0xa987; movk x0, #0xedcc, lsl #16
|
||||
(0xffff_ffff_edcc_5678, &[0x929530e0, 0xf2bdb980]),
|
||||
];
|
||||
for &(value, expected) in cases {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.load_imm_64(X0, value);
|
||||
assert_eq!(asm.instructions(), expected, "{value:#x}");
|
||||
}
|
||||
// movz x9, #0xdef0; movk x9, #0x9abc, lsl #16; #0x5678, lsl #32;
|
||||
// #0x1234, lsl #48
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.load_imm_64(X9, 0x1234_5678_9abc_def0);
|
||||
assert_eq!(
|
||||
asm.instructions(),
|
||||
&[0xd29bde09, 0xf2b35789, 0xf2cacf09, 0xf2e24689]
|
||||
);
|
||||
}
|
||||
|
||||
/// A 32-bit MOVN can write a zero-extended value if its low word's
|
||||
/// complement fits in a single halfword. Otherwise count the halfwords
|
||||
/// that differ from either 64-bit initializer's background.
|
||||
fn shortest_wide_move(value: u64) -> usize {
|
||||
if let Ok(low) = u32::try_from(value) {
|
||||
let complement = !low;
|
||||
if complement <= u32::from(u16::MAX) || complement.trailing_zeros() >= 16 {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
let halves = (0..4).map(|i| (value >> (16 * i)) & 0xffff);
|
||||
let not_zero = halves.clone().filter(|&h| h != 0).count();
|
||||
let not_ones = halves.filter(|&h| h != 0xffff).count();
|
||||
not_zero.min(not_ones).max(1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediates_run_on_the_host_and_use_the_fewest_wide_moves() {
|
||||
let mut values = IMMEDIATE_EDGES.to_vec();
|
||||
let mut state = 0x9e37_79b9_7f4a_7c15u64;
|
||||
for _ in 0..512 {
|
||||
state ^= state >> 12;
|
||||
state ^= state << 25;
|
||||
state ^= state >> 27;
|
||||
let raw = state.wrapping_mul(0x2545_f491_4f6c_dd1d);
|
||||
// Force some halfwords to zero or all ones so both MOVZ and MOVN
|
||||
// sequences of every length occur.
|
||||
let mut value = raw;
|
||||
for half in 0..4 {
|
||||
match (raw >> (60 - 2 * half)) & 3 {
|
||||
0 => value &= !(0xffff << (16 * half)),
|
||||
1 => value |= 0xffff << (16 * half),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
values.push(value);
|
||||
}
|
||||
let mut jit = crate::jit::JitMemory::new(64 * 1024).unwrap();
|
||||
for value in values {
|
||||
for register in [X0, X9] {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
// Seed the destination so a W-register load must clear the high bits.
|
||||
asm.movn_64(register, 0, 0);
|
||||
// Assembler offsets count 32-bit instruction words.
|
||||
let start = asm.current_offset();
|
||||
asm.load_imm_64(register, value);
|
||||
assert_eq!(
|
||||
asm.current_offset() - start,
|
||||
shortest_wide_move(value),
|
||||
"{value:#x}"
|
||||
);
|
||||
if register != X0 {
|
||||
asm.mov_reg_64(X0, register);
|
||||
}
|
||||
asm.ret();
|
||||
let entry = jit.emit_block(asm.instructions()).unwrap();
|
||||
// SAFETY: the block is a complete AAPCS64 leaf function that
|
||||
// writes only X0 (and X9, a caller-saved register) and returns.
|
||||
let function: extern "C" fn() -> u64 = unsafe { std::mem::transmute(entry) };
|
||||
assert_eq!(function(), value, "{value:#x} in x{register}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,36 @@ impl Default for Mxcsr {
|
||||
}
|
||||
}
|
||||
|
||||
/// x87 FPU control, status and tag words.
|
||||
///
|
||||
/// FNINIT is the only instruction that writes them and nothing reads them yet.
|
||||
/// The x87 data registers and every other x87 instruction are not modelled.
|
||||
/// The host's floating-point state is never involved.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct X87State {
|
||||
pub control: u16,
|
||||
pub status: u16,
|
||||
pub tag: u16,
|
||||
}
|
||||
|
||||
impl X87State {
|
||||
/// What FINIT and FNINIT set (Intel SDM Vol. 2A, "FINIT/FNINIT"; Vol. 1,
|
||||
/// 8.1.3 to 8.1.7): every exception masked, 64-bit precision, round to
|
||||
/// nearest; no flag, top of stack 0; every register tagged empty.
|
||||
pub const INIT: Self = Self {
|
||||
control: 0x037F,
|
||||
status: 0,
|
||||
tag: 0xFFFF,
|
||||
};
|
||||
}
|
||||
|
||||
impl Default for X87State {
|
||||
fn default() -> Self {
|
||||
Self::INIT
|
||||
}
|
||||
}
|
||||
|
||||
/// x86-64 CPU state. Native DBT accesses the general registers and RIP by offset.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
@@ -99,6 +129,9 @@ pub struct CpuState {
|
||||
pub mxcsr: Mxcsr,
|
||||
/// Direction flag: string instructions step RSI and RDI down when set.
|
||||
pub df: bool,
|
||||
/// Starts as FNINIT leaves it. The value an operating system gives a new
|
||||
/// thread is not modelled.
|
||||
pub x87: X87State,
|
||||
}
|
||||
|
||||
impl CpuState {
|
||||
@@ -114,6 +147,7 @@ impl CpuState {
|
||||
xmm: [0; 16],
|
||||
mxcsr: Mxcsr::default(),
|
||||
df: false,
|
||||
x87: X87State::INIT,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,6 +164,8 @@ impl CpuState {
|
||||
pub const CPUID_CMOV: u32 = 1 << 15;
|
||||
/// CPUID leaf 1, ECX: POPCNT.
|
||||
pub const CPUID_POPCNT: u32 = 1 << 23;
|
||||
/// CPUID leaf 0x8000_0001, ECX: LAHF and SAHF in 64-bit mode.
|
||||
pub const CPUID_LAHF_SAHF: u32 = 1;
|
||||
/// CPUID leaf 0x8000_0001, ECX: LZCNT.
|
||||
pub const CPUID_LZCNT: u32 = 1 << 5;
|
||||
/// CPUID leaf 0x8000_0001, EDX: 64-bit mode.
|
||||
@@ -150,7 +186,7 @@ pub fn cpuid(leaf: u32, _subleaf: u32) -> [u32; 4] {
|
||||
1 => [0, 0, CPUID_POPCNT, CPUID_CMOV],
|
||||
// Highest extended leaf.
|
||||
0x8000_0000 => [0x8000_0001, 0, 0, 0],
|
||||
0x8000_0001 => [0, 0, CPUID_LZCNT, CPUID_LONG_MODE],
|
||||
0x8000_0001 => [0, 0, CPUID_LAHF_SAHF | CPUID_LZCNT, CPUID_LONG_MODE],
|
||||
_ => [0; 4],
|
||||
}
|
||||
}
|
||||
@@ -167,12 +203,21 @@ pub enum ExitReason {
|
||||
StackUnderflow,
|
||||
/// Division by zero or a quotient too large for its destination (#DE).
|
||||
DivideError,
|
||||
/// A misaligned 16-byte operand or a reserved MXCSR bit (#GP).
|
||||
/// A non-canonical data address, misaligned 16-byte operand or reserved MXCSR bit (#GP).
|
||||
GeneralProtection,
|
||||
/// An unmasked SSE floating-point exception (#XM); MXCSR holds its flags.
|
||||
SimdException,
|
||||
/// A host service changed a register the Win64 ABI requires it to preserve.
|
||||
ServiceAbiViolation,
|
||||
/// The guest ended its own process with this exit status. Only the guest
|
||||
/// stops; the host keeps running.
|
||||
ProcessExit(u32),
|
||||
/// A service has to wait; it had no effect and runs again later.
|
||||
GuestBlocked,
|
||||
/// A service completed and asked the scheduler for a turn.
|
||||
GuestYield,
|
||||
/// The running guest thread ended itself.
|
||||
GuestThreadExited,
|
||||
}
|
||||
|
||||
impl fmt::Display for ExitReason {
|
||||
@@ -188,9 +233,13 @@ impl fmt::Display for ExitReason {
|
||||
Self::DivideError => write!(f, "guest divide error"),
|
||||
Self::GeneralProtection => write!(f, "guest general-protection fault"),
|
||||
Self::SimdException => write!(f, "guest SIMD floating-point exception"),
|
||||
Self::ProcessExit(status) => write!(f, "guest process exited with status {status}"),
|
||||
Self::ServiceAbiViolation => {
|
||||
write!(f, "host service changed a nonvolatile guest register")
|
||||
}
|
||||
Self::GuestBlocked => write!(f, "guest thread is waiting"),
|
||||
Self::GuestYield => write!(f, "guest thread gave up its turn"),
|
||||
Self::GuestThreadExited => write!(f, "guest thread exited"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -199,7 +248,21 @@ impl std::error::Error for ExitReason {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod layout_tests {
|
||||
use super::{CpuState, RFlags, Register};
|
||||
use super::{CpuState, RFlags, Register, X87State};
|
||||
|
||||
/// Intel SDM Vol. 2A, "FINIT/FNINIT", Operation.
|
||||
#[test]
|
||||
fn a_new_guest_starts_with_the_x87_words_fninit_sets() {
|
||||
let init = X87State {
|
||||
control: 0x037F,
|
||||
status: 0,
|
||||
tag: 0xFFFF,
|
||||
};
|
||||
assert_eq!(X87State::INIT, init);
|
||||
assert_eq!(X87State::default(), init);
|
||||
assert_eq!(CpuState::default().x87, init);
|
||||
assert_eq!(CpuState::new(0x1000, 0x2000).x87, init);
|
||||
}
|
||||
|
||||
/// The native translator addresses guest registers and RIP by raw byte
|
||||
/// offset. Keep these assertions next to the struct so a layout change
|
||||
@@ -470,6 +533,8 @@ impl From<DecodeError<MemoryError>> for ExitReason {
|
||||
match error {
|
||||
DecodeError::Fetch(fault) => Self::MemoryFault(fault),
|
||||
DecodeError::Unsupported(byte) => Self::IllegalInstruction(byte),
|
||||
// Intel SDM Vol. 3A, 7.15: exceeding the 15-byte limit is #GP(0).
|
||||
DecodeError::TooLong => Self::GeneralProtection,
|
||||
}
|
||||
}
|
||||
}
|
||||
+601
-20
@@ -15,7 +15,7 @@ use crate::memory::GuestMemory;
|
||||
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment, decode};
|
||||
use crate::x86_exec;
|
||||
use crate::x86_table::{FORMS, Op};
|
||||
use std::collections::HashMap;
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
const MAX_BLOCK_INSTRUCTIONS: usize = 16;
|
||||
|
||||
@@ -29,6 +29,9 @@ pub struct DbtMetrics {
|
||||
pub blocks_compiled: usize,
|
||||
pub cache_hits: usize,
|
||||
pub cache_misses: usize,
|
||||
/// Cached blocks discarded because their guest bytes or executable mappings
|
||||
/// changed. Each also counts as a cache miss.
|
||||
pub blocks_invalidated: usize,
|
||||
pub native_bytes_emitted: usize,
|
||||
pub dbt_dispatches: usize,
|
||||
pub instructions_executed: usize,
|
||||
@@ -37,17 +40,50 @@ pub struct DbtMetrics {
|
||||
pub service_calls: usize,
|
||||
}
|
||||
|
||||
/// A translated block and its executable-memory generation.
|
||||
///
|
||||
/// Guest stores into executable memory (Intel SDM Vol. 3A 11.6), executable
|
||||
/// mapping changes and another address space invalidate the retained token.
|
||||
/// An unchanged token takes a constant-time check. After a generation or address
|
||||
/// space change, bytes and execute permissions are revalidated once before an
|
||||
/// identical translation may be reused in that generation.
|
||||
/// Validation occurs at dispatch boundaries: a store into the currently running
|
||||
/// block's later instructions still needs a separate dispatch-boundary design.
|
||||
struct CachedBlock {
|
||||
code: *const u8,
|
||||
generation: Arc<()>,
|
||||
start: u64,
|
||||
source: Box<[u8]>,
|
||||
}
|
||||
|
||||
impl CachedBlock {
|
||||
fn is_current(&mut self, memory: &GuestMemory) -> bool {
|
||||
if memory.code_is_current(&self.generation) {
|
||||
return true;
|
||||
}
|
||||
if !self.source.iter().enumerate().all(|(offset, &byte)| {
|
||||
matches!(memory.fetch_instruction_byte(self.start.wrapping_add(offset as u64)), Ok(current) if current == byte)
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
self.generation = memory.code_generation();
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Dynamic Binary Translator and native execution runtime.
|
||||
pub struct DbtEngine {
|
||||
jit: JitMemory,
|
||||
block_cache: HashMap<u64, *const u8>,
|
||||
limited_block_cache: HashMap<(u64, usize), *const u8>,
|
||||
block_cache: HashMap<u64, CachedBlock>,
|
||||
limited_block_cache: HashMap<(u64, usize), CachedBlock>,
|
||||
assembler: Arm64Assembler,
|
||||
/// Decoded instructions that emitted helper calls point into.
|
||||
decoded_blocks: Vec<Box<[Insn]>>,
|
||||
services: HashMap<u64, HostServiceFn>,
|
||||
pub import_registry: Option<crate::imports::ImportRegistry>,
|
||||
pub metrics: DbtMetrics,
|
||||
/// Exit status of a guest that ended its process on this engine.
|
||||
exited: Option<u32>,
|
||||
}
|
||||
|
||||
impl DbtEngine {
|
||||
@@ -62,6 +98,7 @@ impl DbtEngine {
|
||||
services: HashMap::new(),
|
||||
import_registry: None,
|
||||
metrics: DbtMetrics::default(),
|
||||
exited: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -79,11 +116,61 @@ impl DbtEngine {
|
||||
}
|
||||
|
||||
/// Execute guest code starting at CPU RIP until HLT, budget exhaustion, or fault.
|
||||
///
|
||||
/// Once the guest has ended its process, this engine executes nothing
|
||||
/// further: every later call reports the same exit.
|
||||
pub fn run(
|
||||
&mut self,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
max_instructions: usize,
|
||||
) -> ExecutionResult {
|
||||
self.run_bounded(cpu, memory, max_instructions, true)
|
||||
}
|
||||
|
||||
/// As [`Self::run`], but stop at the first block boundary that reaches the
|
||||
/// budget. Repeated slices reuse whole blocks instead of compiling a
|
||||
/// shortened one at every cutoff. The budget may be exceeded by less than
|
||||
/// one block.
|
||||
pub(crate) fn run_slice(
|
||||
&mut self,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
max_instructions: usize,
|
||||
) -> ExecutionResult {
|
||||
self.run_bounded(cpu, memory, max_instructions, false)
|
||||
}
|
||||
|
||||
/// Both entry points go through the process-exit latch: once the guest
|
||||
/// process has exited, no guest instruction runs again, whichever guest
|
||||
/// thread the caller tries to run.
|
||||
fn run_bounded(
|
||||
&mut self,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
max_instructions: usize,
|
||||
exact: bool,
|
||||
) -> ExecutionResult {
|
||||
if let Some(status) = self.exited {
|
||||
return ExecutionResult {
|
||||
instructions_executed: 0,
|
||||
final_state: cpu.clone(),
|
||||
exit_reason: ExitReason::ProcessExit(status),
|
||||
};
|
||||
}
|
||||
let result = self.execute(cpu, memory, max_instructions, exact);
|
||||
if let ExitReason::ProcessExit(status) = result.exit_reason {
|
||||
self.exited = Some(status);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn execute(
|
||||
&mut self,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
max_instructions: usize,
|
||||
exact: bool,
|
||||
) -> ExecutionResult {
|
||||
let mut instructions_count = 0;
|
||||
|
||||
@@ -119,7 +206,11 @@ impl DbtEngine {
|
||||
}
|
||||
|
||||
// Look up or translate block at cpu.rip
|
||||
let block_limit = (max_instructions - instructions_count).min(MAX_BLOCK_INSTRUCTIONS);
|
||||
let block_limit = if exact {
|
||||
(max_instructions - instructions_count).min(MAX_BLOCK_INSTRUCTIONS)
|
||||
} else {
|
||||
MAX_BLOCK_INSTRUCTIONS
|
||||
};
|
||||
let mut block = self.get_or_compile_block(cpu.rip, memory, block_limit);
|
||||
// A decode failure can belong to a later instruction in the block.
|
||||
// Execute the current instruction alone so earlier effects retire
|
||||
@@ -127,7 +218,9 @@ impl DbtEngine {
|
||||
if block_limit > 1
|
||||
&& matches!(
|
||||
block,
|
||||
Err(ExitReason::IllegalInstruction(_) | ExitReason::MemoryFault(_))
|
||||
Err(ExitReason::IllegalInstruction(_)
|
||||
| ExitReason::MemoryFault(_)
|
||||
| ExitReason::GeneralProtection)
|
||||
)
|
||||
{
|
||||
block = self.get_or_compile_block(cpu.rip, memory, 1);
|
||||
@@ -186,26 +279,34 @@ impl DbtEngine {
|
||||
block_limit: usize,
|
||||
) -> Result<*const u8, ExitReason> {
|
||||
if block_limit == MAX_BLOCK_INSTRUCTIONS {
|
||||
if let Some(&fn_ptr) = self.block_cache.get(&rip) {
|
||||
self.metrics.cache_hits += 1;
|
||||
return Ok(fn_ptr);
|
||||
if let Some(cached) = self.block_cache.get_mut(&rip) {
|
||||
if cached.is_current(memory) {
|
||||
self.metrics.cache_hits += 1;
|
||||
return Ok(cached.code);
|
||||
}
|
||||
self.metrics.blocks_invalidated += 1;
|
||||
}
|
||||
self.metrics.cache_misses += 1;
|
||||
let compiled_ptr = self.compile_block(rip, memory, block_limit)?;
|
||||
self.block_cache.insert(rip, compiled_ptr);
|
||||
return Ok(compiled_ptr);
|
||||
let compiled = self.compile_block(rip, memory, block_limit)?;
|
||||
let code = compiled.code;
|
||||
self.block_cache.insert(rip, compiled);
|
||||
return Ok(code);
|
||||
}
|
||||
|
||||
// Keep budget-limited blocks separate so they cannot shorten a later run.
|
||||
let key = (rip, block_limit);
|
||||
if let Some(&fn_ptr) = self.limited_block_cache.get(&key) {
|
||||
self.metrics.cache_hits += 1;
|
||||
return Ok(fn_ptr);
|
||||
if let Some(cached) = self.limited_block_cache.get_mut(&key) {
|
||||
if cached.is_current(memory) {
|
||||
self.metrics.cache_hits += 1;
|
||||
return Ok(cached.code);
|
||||
}
|
||||
self.metrics.blocks_invalidated += 1;
|
||||
}
|
||||
self.metrics.cache_misses += 1;
|
||||
let compiled_ptr = self.compile_block(rip, memory, block_limit)?;
|
||||
self.limited_block_cache.insert(key, compiled_ptr);
|
||||
Ok(compiled_ptr)
|
||||
let compiled = self.compile_block(rip, memory, block_limit)?;
|
||||
let code = compiled.code;
|
||||
self.limited_block_cache.insert(key, compiled);
|
||||
Ok(code)
|
||||
}
|
||||
|
||||
fn compile_block(
|
||||
@@ -213,7 +314,7 @@ impl DbtEngine {
|
||||
start_rip: u64,
|
||||
memory: &GuestMemory,
|
||||
block_limit: usize,
|
||||
) -> Result<*const u8, ExitReason> {
|
||||
) -> Result<CachedBlock, ExitReason> {
|
||||
// Decode the whole block first: lowering needs to know whether a later
|
||||
// instruction observes the flags an earlier one produces.
|
||||
let mut decoded = Vec::with_capacity(block_limit);
|
||||
@@ -292,8 +393,17 @@ impl DbtEngine {
|
||||
.map_err(|_| ExitReason::JitCacheExhausted)?;
|
||||
self.metrics.blocks_compiled += 1;
|
||||
self.metrics.native_bytes_emitted += asm.instructions().len() * 4;
|
||||
let source = (0..rip.wrapping_sub(start_rip))
|
||||
.map(|offset| memory.fetch_instruction_byte(start_rip.wrapping_add(offset)))
|
||||
.collect::<Result<Box<[u8]>, _>>()
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
self.decoded_blocks.push(insns);
|
||||
Ok(emitted)
|
||||
Ok(CachedBlock {
|
||||
code: emitted,
|
||||
generation: memory.code_generation(),
|
||||
start: start_rip,
|
||||
source,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,6 +445,9 @@ pub fn is_native(insn: &Insn) -> bool {
|
||||
let scanned = matches!(insn.size, 2 | 4 | 8);
|
||||
match insn.op {
|
||||
Op::Add | Op::Sub | Op::Cmp | Op::And | Op::Or | Op::Xor | Op::Test => wide,
|
||||
// Register and immediate forms only; a memory destination would have
|
||||
// to restore the guest carry again after the store helper call.
|
||||
Op::Adc | Op::Sbb => wide && insn.memory().is_none(),
|
||||
Op::Inc | Op::Dec | Op::Neg | Op::Not => wide,
|
||||
Op::Cmov => wide,
|
||||
Op::Bsf | Op::Bsr => scanned,
|
||||
@@ -587,9 +700,26 @@ impl Emitter<'_> {
|
||||
}
|
||||
|
||||
/// X11 = X9 op X10, setting host NZCV only for the arithmetic operations.
|
||||
/// ADC and SBB also read the guest CF and clobber X12 and X13.
|
||||
fn compute(&mut self, op: Op, wide: bool) {
|
||||
let asm = &mut *self.asm;
|
||||
if matches!(op, Op::Adc | Op::Sbb) {
|
||||
// ADCS adds the host C, so C must equal the guest CF. SBCS
|
||||
// subtracts NOT C, while x86 SBB subtracts the borrow CF, so there
|
||||
// C must be its inverse. A compare sets C when it does not borrow.
|
||||
asm.ldrb_uoff(X12, X19, CF);
|
||||
if op == Op::Adc {
|
||||
asm.load_imm_64(X13, 1);
|
||||
asm.cmp_reg_32(X12, X13); // C = CF >= 1
|
||||
} else {
|
||||
asm.cmp_reg_32(XZR, X12); // C = 0 >= CF
|
||||
}
|
||||
}
|
||||
match (op, wide) {
|
||||
(Op::Adc, true) => asm.adcs_reg_64(X11, X9, X10),
|
||||
(Op::Adc, false) => asm.adcs_reg_32(X11, X9, X10),
|
||||
(Op::Sbb, true) => asm.sbcs_reg_64(X11, X9, X10),
|
||||
(Op::Sbb, false) => asm.sbcs_reg_32(X11, X9, X10),
|
||||
(Op::Add | Op::Inc, true) => asm.adds_reg_64(X11, X9, X10),
|
||||
(Op::Add | Op::Inc, false) => asm.adds_reg_32(X11, X9, X10),
|
||||
(Op::And | Op::Test, true) => asm.ands_reg_64(X11, X9, X10),
|
||||
@@ -623,7 +753,7 @@ impl Emitter<'_> {
|
||||
match op {
|
||||
// INC and DEC leave CF unchanged.
|
||||
Op::Inc | Op::Dec => {}
|
||||
Op::Add => {
|
||||
Op::Add | Op::Adc => {
|
||||
asm.cset_32(X12, Condition::Cs);
|
||||
asm.strb_uoff(X12, X19, CF);
|
||||
}
|
||||
@@ -1214,11 +1344,22 @@ struct BlockContext {
|
||||
const BLOCK_CTX_FAULTED_OFFSET: u32 = 8;
|
||||
const _: () = assert!(std::mem::offset_of!(BlockContext, faulted) == 8);
|
||||
|
||||
fn check_guest_address(ctx: *mut BlockContext, address: u64, size: u8) -> bool {
|
||||
if x86_exec::canonical_access(address, size) {
|
||||
return true;
|
||||
}
|
||||
fault(ctx, ExitReason::GeneralProtection);
|
||||
false
|
||||
}
|
||||
|
||||
extern "C" fn write_u64_helper(ctx: *mut BlockContext, addr: u64, val: u64) {
|
||||
unsafe {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 8) {
|
||||
return;
|
||||
}
|
||||
let mem = &mut *(*ctx).memory_ptr;
|
||||
if let Err(e) = mem.write_u64(addr, val) {
|
||||
(*ctx).faulted = 1;
|
||||
@@ -1232,6 +1373,9 @@ extern "C" fn read_u64_helper(ctx: *mut BlockContext, addr: u64) -> u64 {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return 0;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 8) {
|
||||
return 0;
|
||||
}
|
||||
let mem = &*(*ctx).memory_ptr;
|
||||
match mem.read_u64(addr) {
|
||||
Ok(v) => v,
|
||||
@@ -1275,6 +1419,9 @@ fn fault(ctx: *mut BlockContext, reason: ExitReason) {
|
||||
|
||||
/// Read 16 bytes at any alignment; returned in X0 (low) and X1 (high).
|
||||
extern "C" fn read_u128_helper(ctx: *mut BlockContext, addr: u64) -> u128 {
|
||||
if !check_guest_address(ctx, addr, 16) {
|
||||
return 0;
|
||||
}
|
||||
let memory = unsafe { &*(*ctx).memory_ptr };
|
||||
let mut bytes = [0; 16];
|
||||
if let Err(error) = memory.read_bytes(addr, &mut bytes) {
|
||||
@@ -1293,6 +1440,9 @@ extern "C" fn read_aligned_u128_helper(ctx: *mut BlockContext, addr: u64) -> u12
|
||||
|
||||
/// Write 16 bytes at any alignment; `value` arrives in X2 (low) and X3 (high).
|
||||
extern "C" fn write_u128_helper(ctx: *mut BlockContext, addr: u64, value: u128) {
|
||||
if !check_guest_address(ctx, addr, 16) {
|
||||
return;
|
||||
}
|
||||
let memory = unsafe { &mut *(*ctx).memory_ptr };
|
||||
if let Err(error) = memory.write_bytes(addr, &value.to_le_bytes()) {
|
||||
fault(ctx, ExitReason::MemoryFault(error));
|
||||
@@ -1340,6 +1490,9 @@ extern "C" fn write_u16_helper(ctx: *mut BlockContext, addr: u64, val: u64) {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 2) {
|
||||
return;
|
||||
}
|
||||
let mem = &mut *(*ctx).memory_ptr;
|
||||
if let Err(e) = mem.write_u16(addr, val as u16) {
|
||||
(*ctx).faulted = 1;
|
||||
@@ -1353,6 +1506,9 @@ extern "C" fn write_u32_helper(ctx: *mut BlockContext, addr: u64, val: u64) {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 4) {
|
||||
return;
|
||||
}
|
||||
let mem = &mut *(*ctx).memory_ptr;
|
||||
if let Err(e) = mem.write_u32(addr, val as u32) {
|
||||
(*ctx).faulted = 1;
|
||||
@@ -1366,6 +1522,9 @@ extern "C" fn read_u32_helper(ctx: *mut BlockContext, addr: u64) -> u64 {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return 0;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 4) {
|
||||
return 0;
|
||||
}
|
||||
let mem = &*(*ctx).memory_ptr;
|
||||
match mem.read_u32(addr) {
|
||||
Ok(v) => u64::from(v),
|
||||
@@ -1383,6 +1542,9 @@ extern "C" fn write_u8_helper(ctx: *mut BlockContext, addr: u64, val: u64) {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 1) {
|
||||
return;
|
||||
}
|
||||
let mem = &mut *(*ctx).memory_ptr;
|
||||
if let Err(e) = mem.write_u8(addr, val as u8) {
|
||||
(*ctx).faulted = 1;
|
||||
@@ -1396,6 +1558,9 @@ extern "C" fn read_u8_helper(ctx: *mut BlockContext, addr: u64) -> u64 {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return 0;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 1) {
|
||||
return 0;
|
||||
}
|
||||
let mem = &*(*ctx).memory_ptr;
|
||||
match mem.read_u8(addr) {
|
||||
Ok(v) => v as u64,
|
||||
@@ -1413,6 +1578,9 @@ extern "C" fn read_u16_helper(ctx: *mut BlockContext, addr: u64) -> u64 {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return 0;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 2) {
|
||||
return 0;
|
||||
}
|
||||
let mem = &*(*ctx).memory_ptr;
|
||||
match mem.read_u16(addr) {
|
||||
Ok(v) => v as u64,
|
||||
@@ -1452,6 +1620,216 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
/// `mov eax, imm32; hlt`, with the immediate at `ENTRY + 1`.
|
||||
fn mov_eax(imm: u8) -> [u8; 6] {
|
||||
[0xB8, imm, 0x00, 0x00, 0x00, 0xF4]
|
||||
}
|
||||
|
||||
fn writable_fixture(code: &[u8]) -> (DbtEngine, GuestMemory) {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
ENTRY,
|
||||
code.len(),
|
||||
MemoryPermissions::READ_WRITE_EXECUTE,
|
||||
code,
|
||||
)
|
||||
.unwrap();
|
||||
(DbtEngine::new(64 * 1024).unwrap(), memory)
|
||||
}
|
||||
|
||||
fn rax_after_run(engine: &mut DbtEngine, memory: &mut GuestMemory, limit: usize) -> u64 {
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
let result = engine.run(&mut cpu, memory, limit);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
cpu.get(Register::Rax)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_code_stays_cached() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
assert_eq!(engine.metrics.blocks_compiled, 1);
|
||||
assert_eq!(engine.metrics.cache_hits, 1);
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_writes_and_allocations_do_not_invalidate_executable_code() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
memory
|
||||
.map_region(ENTRY + 0x1000, 8, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
for value in 0..64 {
|
||||
memory.write_u64(ENTRY + 0x1000, value).unwrap();
|
||||
let allocation = memory
|
||||
.map_virtual_allocation(0, 4096, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
assert!(memory.release_virtual_allocation(allocation));
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
}
|
||||
assert_eq!(engine.metrics.blocks_compiled, 1);
|
||||
assert_eq!(engine.metrics.cache_hits, 64);
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloned_address_spaces_diverge_when_executable_code_changes() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
let mut cloned = memory.clone();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
|
||||
memory.write_u8(ENTRY + 1, 7).unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 7);
|
||||
// A deep clone shares the proven identical executable snapshot. The
|
||||
// write in the original space must still force retranslation there.
|
||||
assert_eq!(engine.metrics.blocks_compiled, 2);
|
||||
assert_eq!(engine.metrics.cache_hits, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_bypass_writes_invalidate_cached_translations() {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
ENTRY,
|
||||
8,
|
||||
MemoryPermissions::READ_EXECUTE,
|
||||
&[0xB8, 1, 0, 0, 0, 0xF4, 0, 0],
|
||||
)
|
||||
.unwrap();
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
assert!(memory.write_u32(ENTRY + 1, 9).is_err());
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 0);
|
||||
memory
|
||||
.write_u64_bypass(ENTRY, u64::from_le_bytes([0xB8, 2, 0, 0, 0, 0xF4, 0, 0]))
|
||||
.unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
|
||||
memory.write_u32_bypass(ENTRY + 1, 3).unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 3);
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_writes_crossing_regions_invalidate_cached_translations() {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, 2, MemoryPermissions::READ_WRITE_EXECUTE, &[0xB8, 1])
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
ENTRY + 2,
|
||||
4,
|
||||
MemoryPermissions::READ_WRITE_EXECUTE,
|
||||
&[0, 0, 0, 0xF4],
|
||||
)
|
||||
.unwrap();
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
memory.write_u32(ENTRY + 1, 9).unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 9);
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remapped_non_executable_memory_cannot_reuse_a_translation() {
|
||||
let mut memory = GuestMemory::new();
|
||||
let base = memory
|
||||
.map_virtual_allocation(0, 4096, MemoryPermissions::READ_WRITE_EXECUTE)
|
||||
.unwrap();
|
||||
memory.write_bytes(base, &mov_eax(1)).unwrap();
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
let mut cpu = CpuState::new(base, 0);
|
||||
assert_eq!(
|
||||
engine.run(&mut cpu, &mut memory, 16).exit_reason,
|
||||
ExitReason::Halt
|
||||
);
|
||||
assert!(memory.release_virtual_allocation(base));
|
||||
assert_eq!(
|
||||
memory.map_virtual_allocation(base, 4096, MemoryPermissions::READ_WRITE),
|
||||
Ok(base)
|
||||
);
|
||||
memory.write_bytes(base, &mov_eax(1)).unwrap();
|
||||
let mut cpu = CpuState::new(base, 0);
|
||||
assert!(matches!(
|
||||
engine.run(&mut cpu, &mut memory, 16).exit_reason,
|
||||
ExitReason::MemoryFault(_)
|
||||
));
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_code_rewrites_report_bounded_jit_cache_exhaustion() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
for value in 0..16_384u32 {
|
||||
memory.write_u32(ENTRY + 1, value).unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
let result = engine.run(&mut cpu, &mut memory, 16);
|
||||
if result.exit_reason == ExitReason::JitCacheExhausted {
|
||||
return;
|
||||
}
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(cpu.get(Register::Rax), u64::from(value));
|
||||
}
|
||||
panic!("rewritten blocks unexpectedly avoided the bounded JIT capacity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewritten_code_is_translated_again() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
memory.write_bytes(ENTRY + 1, &[2]).unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
|
||||
assert_eq!(engine.metrics.blocks_compiled, 2);
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 1);
|
||||
// The new translation is cached in turn.
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
|
||||
assert_eq!(engine.metrics.blocks_compiled, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewriting_the_last_byte_of_a_block_is_detected() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
// HLT becomes NOP, so the block now runs off the end of the mapping.
|
||||
memory.write_bytes(ENTRY + 5, &[0x90]).unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
let result = engine.run(&mut cpu, &mut memory, 16);
|
||||
assert!(matches!(result.exit_reason, ExitReason::MemoryFault(_)));
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn budget_limited_block_is_checked_against_current_bytes() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
for expected in [1, 3] {
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
let result = engine.run(&mut cpu, &mut memory, 1);
|
||||
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
|
||||
assert_eq!(cpu.get(Register::Rax), expected);
|
||||
memory.write_bytes(ENTRY + 1, &[3]).unwrap();
|
||||
}
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_address_space_does_not_reuse_a_block() {
|
||||
let (mut engine, mut first) = writable_fixture(&mov_eax(1));
|
||||
let (_, mut second) = writable_fixture(&mov_eax(7));
|
||||
assert_eq!(rax_after_run(&mut engine, &mut first, 16), 1);
|
||||
assert_eq!(rax_after_run(&mut engine, &mut second, 16), 7);
|
||||
|
||||
let mut unmapped = GuestMemory::new();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
let result = engine.run(&mut cpu, &mut unmapped, 16);
|
||||
assert!(matches!(result.exit_reason, ExitReason::MemoryFault(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_block_obeys_remaining_budget() {
|
||||
let code = [
|
||||
@@ -2267,4 +2645,207 @@ mod tests {
|
||||
ExitReason::MemoryFault(MemoryError::UnmappedAddress(FS_BASE + 8))
|
||||
);
|
||||
}
|
||||
|
||||
/// Intel SDM Volume 1, section 3.4.3.1: for `SUB` and `CMP`, `CF` is the
|
||||
/// borrow out of the most significant bit. `JB` is `CF = 1`, `JAE` is
|
||||
/// `CF = 0`, `JBE` is `CF = 1 or ZF = 1` and `JA` is `CF = 0 and ZF = 0`.
|
||||
///
|
||||
/// ARM64 reports the inverse: `SUBS` sets `C` when the subtraction does
|
||||
/// *not* borrow, and its `HI`/`LS` conditions are defined on that same
|
||||
/// inverted carry. These four x86 conditions therefore cannot be taken
|
||||
/// from an ARM64 condition code without translating the borrow first,
|
||||
/// which makes them the ones to pin at the boundaries.
|
||||
/// One unsigned condition: the low nibble pair as encoded in the `0x70`
|
||||
/// block, and the rule that decides it from CF and ZF.
|
||||
type UnsignedCondition = (u8, fn(bool, bool) -> bool);
|
||||
|
||||
const UNSIGNED_CONDITIONS: [UnsignedCondition; 4] = [
|
||||
(0x72, |cf, _zf| cf), // JB, JC, JNAE
|
||||
(0x73, |cf, _zf| !cf), // JAE, JNB, JNC
|
||||
(0x76, |cf, zf| cf || zf), // JBE, JNA
|
||||
(0x77, |cf, zf| !cf && !zf), // JA, JNBE
|
||||
];
|
||||
|
||||
/// Build `<op> eax, ebx` (or `rax, rbx`) followed by the short or near form
|
||||
/// of `condition`. The not-taken path writes 1 to `ECX` and halts, the
|
||||
/// taken path writes 2. A near branch targets offset 140, which a `disp8`
|
||||
/// cannot reach, so the two encodings are exercised separately.
|
||||
fn unsigned_branch_program(op: [u8; 2], condition: u8, wide: bool, near: bool) -> Vec<u8> {
|
||||
let mut code = Vec::new();
|
||||
if wide {
|
||||
code.push(0x48); // REX.W
|
||||
}
|
||||
code.extend_from_slice(&op); // cmp/sub eax, ebx
|
||||
let jcc = code.len();
|
||||
if near {
|
||||
// The near form is `0F 8x`, where x is the low nibble of the
|
||||
// short form's opcode.
|
||||
code.extend_from_slice(&[0x0F, 0x80 | (condition & 0x0F), 0, 0, 0, 0]);
|
||||
} else {
|
||||
code.extend_from_slice(&[condition, 0]);
|
||||
}
|
||||
code.extend_from_slice(&[0xB9, 1, 0, 0, 0]); // mov ecx, 1
|
||||
code.push(0xF4); // hlt
|
||||
let target = if near { 140 } else { code.len() };
|
||||
while code.len() < target {
|
||||
code.push(0x90); // nop
|
||||
}
|
||||
code.extend_from_slice(&[0xB9, 2, 0, 0, 0]); // mov ecx, 2
|
||||
code.push(0xF4); // hlt
|
||||
let next = jcc + if near { 6 } else { 2 };
|
||||
let displacement = target as i64 - next as i64;
|
||||
if near {
|
||||
code[jcc + 2..jcc + 6].copy_from_slice(&(displacement as i32).to_le_bytes());
|
||||
} else {
|
||||
code[jcc + 1] = displacement as i8 as u8;
|
||||
}
|
||||
code
|
||||
}
|
||||
|
||||
/// Run one branch program and return `(ecx, cf, zf)`.
|
||||
fn run_unsigned_branch(code: &[u8], left: u64, right: u64) -> (u64, bool, bool) {
|
||||
let (mut engine, mut cpu, mut memory) = fixture(code);
|
||||
cpu.set(Register::Rax, left);
|
||||
cpu.set(Register::Rbx, right);
|
||||
let result = engine.run(&mut cpu, &mut memory, 32);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
// Either the two-instruction taken path or the two-instruction
|
||||
// not-taken path runs after the compare and the branch.
|
||||
assert_eq!(result.instructions_executed, 4);
|
||||
// The compare, the branch and the halting move all run as translated
|
||||
// ARM64, not through the shared interpreter.
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
|
||||
(cpu.get(Register::Rcx), cpu.flags.cf, cpu.flags.zf)
|
||||
}
|
||||
|
||||
/// The four unsigned conditions, at both ends of the 32-bit and 64-bit
|
||||
/// ranges, in the short and the near encoding. Expected flags and
|
||||
/// outcomes come from the SDM rules above, not from the lowering.
|
||||
#[test]
|
||||
fn unsigned_branch_conditions_follow_the_borrow_at_every_boundary() {
|
||||
const CMP: [u8; 2] = [0x39, 0xD8];
|
||||
let cases: &[(bool, u64, u64)] = &[
|
||||
// 32-bit: zero, one, equal operands, both ends of the range, and
|
||||
// the pair where the sign bit flips but the unsigned order holds.
|
||||
(false, 0, 0),
|
||||
(false, 0, 1),
|
||||
(false, 1, 0),
|
||||
(false, 0xFFFF_FFFF, 0xFFFF_FFFF),
|
||||
(false, 0xFFFF_FFFF, 0),
|
||||
(false, 0, 0xFFFF_FFFF),
|
||||
(false, 0x7FFF_FFFF, 0x8000_0000),
|
||||
(false, 0x8000_0000, 0x7FFF_FFFF),
|
||||
// The same boundaries at 64 bits, plus a subtraction that clears
|
||||
// the sign bit without borrowing.
|
||||
(true, 0, 0),
|
||||
(true, 0, 1),
|
||||
(true, 1, 0),
|
||||
(true, u64::MAX, u64::MAX),
|
||||
(true, u64::MAX, 0),
|
||||
(true, 0, u64::MAX),
|
||||
(true, 0x7FFF_FFFF_FFFF_FFFF, 0x8000_0000_0000_0000),
|
||||
(true, 0x8000_0000_0000_0000, 0x7FFF_FFFF_FFFF_FFFF),
|
||||
(true, 0x8000_0000_0000_0000, 1),
|
||||
];
|
||||
|
||||
for &(wide, left, right) in cases {
|
||||
let mask = if wide { u64::MAX } else { u64::from(u32::MAX) };
|
||||
let (left, right) = (left & mask, right & mask);
|
||||
// SDM: CF is the borrow out of the most significant bit, ZF is a
|
||||
// zero result. Both follow from the operands alone.
|
||||
let (cf, zf) = (left < right, left == right);
|
||||
for &(condition, holds) in &UNSIGNED_CONDITIONS {
|
||||
let taken = holds(cf, zf);
|
||||
for &near in &[false, true] {
|
||||
let code = unsigned_branch_program(CMP, condition, wide, near);
|
||||
let (ecx, got_cf, got_zf) = run_unsigned_branch(&code, left, right);
|
||||
let case = format!(
|
||||
"{condition:#04x} {:#x} {:#x} {}",
|
||||
left,
|
||||
right,
|
||||
if near { "near" } else { "short" }
|
||||
);
|
||||
assert_eq!(got_cf, cf, "{case}: CF");
|
||||
assert_eq!(got_zf, zf, "{case}: ZF");
|
||||
assert_eq!(ecx, if taken { 2 } else { 1 }, "{case}: branch outcome");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `SUB` is the other producer of the carry these conditions read, and the
|
||||
/// one where the ARM64 carry is inverted: `0 - 1` borrows, while
|
||||
/// `0x8000_0000_0000_0000 - 1` does not borrow even though it clears the
|
||||
/// sign bit.
|
||||
#[test]
|
||||
fn subtract_borrow_into_and_out_of_the_high_bit_feeds_the_unsigned_branches() {
|
||||
const SUB: [u8; 2] = [0x29, 0xD8];
|
||||
let cases: &[(bool, u64, u64)] = &[
|
||||
(false, 0, 1),
|
||||
(false, 0x8000_0000, 1),
|
||||
(true, 0, 1),
|
||||
(true, 0x8000_0000_0000_0000, 1),
|
||||
];
|
||||
|
||||
for &(wide, left, right) in cases {
|
||||
let mask = if wide { u64::MAX } else { u64::from(u32::MAX) };
|
||||
let (left, right) = (left & mask, right & mask);
|
||||
let (cf, zf) = (left < right, left == right);
|
||||
for &(condition, holds) in &UNSIGNED_CONDITIONS {
|
||||
let taken = holds(cf, zf);
|
||||
for &near in &[false, true] {
|
||||
let code = unsigned_branch_program(SUB, condition, wide, near);
|
||||
let (ecx, got_cf, got_zf) = run_unsigned_branch(&code, left, right);
|
||||
let case = format!(
|
||||
"{condition:#04x} {:#x} {:#x} {}",
|
||||
left,
|
||||
right,
|
||||
if near { "near" } else { "short" }
|
||||
);
|
||||
assert_eq!(got_cf, cf, "{case}: CF");
|
||||
assert_eq!(got_zf, zf, "{case}: ZF");
|
||||
assert_eq!(ecx, if taken { 2 } else { 1 }, "{case}: branch outcome");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The carry these conditions read is produced in one translated block and
|
||||
/// consumed in the next. A lowering that left it in the host's condition
|
||||
/// flags would pass the single-block cases above and fail here.
|
||||
#[test]
|
||||
fn unsigned_branch_reads_flags_stored_by_a_previous_block() {
|
||||
const CMP: [u8; 2] = [0x39, 0xD8];
|
||||
let cases: &[(bool, u64, u64)] = &[
|
||||
(false, 0, 0), // CF = 0, ZF = 1
|
||||
(false, 0, 1), // CF = 1, ZF = 0
|
||||
(false, 0xFFFF_FFFF, 0), // CF = 0, ZF = 0
|
||||
(true, 0x8000_0000_0000_0000, 1), // CF = 0 although the sign bit clears
|
||||
];
|
||||
|
||||
for &(wide, left, right) in cases {
|
||||
let (cf, zf) = (left < right, left == right);
|
||||
for &(condition, holds) in &UNSIGNED_CONDITIONS {
|
||||
let taken = holds(cf, zf);
|
||||
let code = unsigned_branch_program(CMP, condition, wide, false);
|
||||
let (mut engine, mut cpu, mut memory) = fixture(&code);
|
||||
cpu.set(Register::Rax, left);
|
||||
cpu.set(Register::Rbx, right);
|
||||
|
||||
// One instruction per run: the compare is translated as a
|
||||
// one-instruction block, so the branch is compiled separately
|
||||
// and can only read the flags the first block stored.
|
||||
let first = engine.run(&mut cpu, &mut memory, 1);
|
||||
assert_eq!(first.exit_reason, ExitReason::StepLimitExceeded);
|
||||
assert_eq!(cpu.rip, ENTRY + if wide { 3 } else { 2 });
|
||||
assert_eq!((cpu.flags.cf, cpu.flags.zf), (cf, zf));
|
||||
|
||||
let second = engine.run(&mut cpu, &mut memory, 8);
|
||||
assert_eq!(second.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(second.instructions_executed, 3);
|
||||
assert_eq!(cpu.get(Register::Rcx), if taken { 2 } else { 1 });
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1051
-14
File diff suppressed because it is too large.
Load diff
@@ -196,8 +196,25 @@ fn trampoline_address(index: usize) -> u64 {
|
||||
}
|
||||
|
||||
const CALLBACK_RETURN: u64 = IMPORT_TRAMPOLINE_BASE_VA - IMPORT_TRAMPOLINE_STRIDE;
|
||||
/// Return address placed under a process entry point. Reaching it ends the
|
||||
/// process with EAX as its exit status.
|
||||
pub const ENTRY_RETURN: u64 = CALLBACK_RETURN - IMPORT_TRAMPOLINE_STRIDE;
|
||||
/// The 4 KiB page that holds [`ENTRY_RETURN`] and the callback return
|
||||
/// address. The engine intercepts those two addresses before it executes
|
||||
/// anything there, so startup reserves the page: guest code mapped over it
|
||||
/// would never run.
|
||||
pub const RETURN_SENTINEL_PAGE: u64 = ENTRY_RETURN & !0xFFF;
|
||||
const _: () = assert!(CALLBACK_RETURN & !0xFFF == RETURN_SENTINEL_PAGE);
|
||||
/// Nested guest callbacks allowed in one guest thread.
|
||||
const MAX_CALLBACK_DEPTH: usize = 32;
|
||||
|
||||
fn callback_depth(memory: &GuestMemory, teb: u64) -> usize {
|
||||
memory
|
||||
.callback_frames
|
||||
.range((teb, 0)..=(teb, u64::MAX))
|
||||
.count()
|
||||
}
|
||||
|
||||
pub(crate) struct GuestCallback {
|
||||
pub(crate) entry: u64,
|
||||
pub(crate) context: u64,
|
||||
@@ -264,6 +281,8 @@ pub(crate) struct CallbackFrame {
|
||||
|
||||
/// Registry for resolving and binding import symbols to guest trampoline VAs.
|
||||
pub struct ImportRegistry {
|
||||
/// Set by the standard services so a call can end the caller's turn.
|
||||
pub(crate) hooks: Option<Arc<crate::services::threads::SchedulerHooks>>,
|
||||
// (lower-case module, name) -> service index. Symbol names keep their case.
|
||||
services: HashMap<(String, ImportName), usize>,
|
||||
handlers: Vec<ServiceDescriptor>,
|
||||
@@ -282,6 +301,7 @@ impl Default for ImportRegistry {
|
||||
impl ImportRegistry {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
hooks: None,
|
||||
services: HashMap::new(),
|
||||
handlers: Vec::new(),
|
||||
callback_dispatchers: HashMap::new(),
|
||||
@@ -609,7 +629,7 @@ impl ImportRegistry {
|
||||
args: [u64; 4],
|
||||
) -> Result<(), ExitReason> {
|
||||
let key = (cpu.gs_base, slot + 8);
|
||||
if memory.callback_frames.len() >= MAX_CALLBACK_DEPTH
|
||||
if callback_depth(memory, cpu.gs_base) >= MAX_CALLBACK_DEPTH
|
||||
|| memory.callback_frames.contains_key(&key)
|
||||
{
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
@@ -635,6 +655,7 @@ impl ImportRegistry {
|
||||
/// Check if target RIP matches a synthetic service trampoline.
|
||||
pub fn is_service_trampoline(&self, rip: u64) -> bool {
|
||||
rip == CALLBACK_RETURN
|
||||
|| rip == ENTRY_RETURN
|
||||
|| self.trampoline_to_service.contains_key(&rip)
|
||||
|| self.dynamic_trampolines.get(rip).is_some()
|
||||
}
|
||||
@@ -646,6 +667,22 @@ impl ImportRegistry {
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<(), ExitReason> {
|
||||
if rip == ENTRY_RETURN {
|
||||
// The entry point returned. Its result is the exit status, and it
|
||||
// goes through ExitProcess when that is registered so both ways of
|
||||
// ending do the same cleanup.
|
||||
let status = cpu.get(Register::Rax) as u32;
|
||||
let exit = ExitReason::ProcessExit(status);
|
||||
let Some(index) = self.index("kernel32.dll", &ImportName::Name("ExitProcess".into()))
|
||||
else {
|
||||
return Err(exit);
|
||||
};
|
||||
let mut args = Win64Args::new(cpu);
|
||||
args.rcx = u64::from(status);
|
||||
return Err((self.handlers[index].handler)(&args, cpu, memory)
|
||||
.err()
|
||||
.unwrap_or(exit));
|
||||
}
|
||||
if rip == CALLBACK_RETURN {
|
||||
let key = (cpu.gs_base, cpu.get(Register::Rsp));
|
||||
let frame = memory
|
||||
@@ -725,7 +762,7 @@ impl ImportRegistry {
|
||||
}
|
||||
if let Some(dispatcher) = self.callback_dispatchers.get(&service_idx) {
|
||||
let key = (cpu.gs_base, after);
|
||||
if memory.callback_frames.len() >= MAX_CALLBACK_DEPTH
|
||||
if callback_depth(memory, cpu.gs_base) >= MAX_CALLBACK_DEPTH
|
||||
|| memory.callback_frames.contains_key(&key)
|
||||
{
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
@@ -766,6 +803,9 @@ impl ImportRegistry {
|
||||
cpu.set(Register::Rax, value);
|
||||
cpu.set(Register::Rsp, after);
|
||||
cpu.rip = ret_addr;
|
||||
if self.hooks.as_ref().is_some_and(|h| h.switch_requested()) {
|
||||
return Err(ExitReason::GuestYield);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod reloc;
|
||||
pub mod runtime;
|
||||
#[rustfmt::skip]
|
||||
pub mod runtime_table;
|
||||
pub mod scheduler;
|
||||
pub mod services;
|
||||
pub mod softfloat;
|
||||
pub mod startup;
|
||||
|
||||
+916
-8
File diff suppressed because it is too large.
Load diff
+95
-8
@@ -3,7 +3,8 @@
|
||||
//! PE32+ (64-bit Portable Executable) format parser and section loader for Xenora.
|
||||
//!
|
||||
//! Parses standard PE32+ headers (DOS header, COFF header, Optional Header 64)
|
||||
//! and loads valid section headers into `GuestMemory` with appropriate permissions.
|
||||
//! and loads the headers and each section into `GuestMemory` with appropriate
|
||||
//! permissions.
|
||||
|
||||
use crate::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use std::fmt;
|
||||
@@ -19,6 +20,11 @@ pub enum PeError {
|
||||
InvalidSectionHeaders,
|
||||
SectionMappingError(MemoryError),
|
||||
InvalidEntryPoint,
|
||||
/// The headers cannot be mapped at the image base: `SizeOfHeaders` is
|
||||
/// zero, ends before the section table does, runs past the end of the
|
||||
/// file, or its pages reach into a section; or the bytes given to the
|
||||
/// loader do not hold the PE32+ headers that were parsed.
|
||||
InvalidHeaderSize,
|
||||
}
|
||||
|
||||
impl fmt::Display for PeError {
|
||||
@@ -42,6 +48,12 @@ impl fmt::Display for PeError {
|
||||
Self::InvalidSectionHeaders => write!(f, "invalid or corrupt section headers"),
|
||||
Self::SectionMappingError(e) => write!(f, "failed to map section: {e}"),
|
||||
Self::InvalidEntryPoint => write!(f, "entry point address is outside executable code"),
|
||||
Self::InvalidHeaderSize => write!(
|
||||
f,
|
||||
"the PE headers cannot be mapped: SizeOfHeaders is zero, shorter than the section \
|
||||
table, longer than the file or reaches into a section, or the bytes do not match \
|
||||
the parsed headers"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,6 +92,9 @@ pub struct LoadedImage {
|
||||
pub pe: ParsedPe,
|
||||
pub memory: GuestMemory,
|
||||
pub entry_point: u64,
|
||||
/// Guest address of the `ImageBase` field in the mapped optional header.
|
||||
/// Startup writes the load base there once relocations have been applied.
|
||||
pub(crate) image_base_field: u64,
|
||||
}
|
||||
|
||||
// Windows PE Characteristic Constants
|
||||
@@ -94,9 +109,14 @@ pub const PE32_PLUS_MAGIC: u16 = 0x020B;
|
||||
/// PE32+ optional header length up to and including NumberOfRvaAndSizes.
|
||||
const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112;
|
||||
const SECTION_HEADER_SIZE: usize = 40;
|
||||
/// Host memory budget for all mapped sections of one image. This is a loader policy
|
||||
/// limit, not a property of the PE format.
|
||||
/// Host memory budget for the mapped headers and sections of one image. This is a
|
||||
/// loader policy limit, not a property of the PE format.
|
||||
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
|
||||
/// The mapped headers end on a guest page boundary.
|
||||
const HEADER_PAGE: u64 = 0x1000;
|
||||
/// `ImageBase` and `SizeOfHeaders` within the PE32+ optional header.
|
||||
const OPTIONAL_IMAGE_BASE: usize = 24;
|
||||
const OPTIONAL_SIZE_OF_HEADERS: usize = 60;
|
||||
|
||||
fn read_u16(bytes: &[u8], at: usize) -> u16 {
|
||||
u16::from_le_bytes([bytes[at], bytes[at + 1]])
|
||||
@@ -270,25 +290,91 @@ impl ParsedPe {
|
||||
None
|
||||
}
|
||||
|
||||
/// Load this parsed PE into a fresh `GuestMemory` instance, mapping all sections.
|
||||
/// Where the headers are and how much to map for them: the file length of
|
||||
/// the headers, the page-rounded length of the mapping, and the file offset
|
||||
/// of the optional header's `ImageBase` field. Nothing is copied or
|
||||
/// allocated here.
|
||||
///
|
||||
/// A caller may pass bytes other than the ones parsed, so the header
|
||||
/// layout is read again from `bytes` with every access checked, and must
|
||||
/// be a PE32+ optional header that agrees with the parsed metadata.
|
||||
fn headers_for(&self, bytes: &[u8]) -> Result<(usize, u64, usize), PeError> {
|
||||
let field = |at: usize, len: usize| at.checked_add(len).and_then(|end| bytes.get(at..end));
|
||||
let u16_at = |at: usize| Some(u16::from_le_bytes(field(at, 2)?.try_into().ok()?));
|
||||
let u32_at = |at: usize| Some(u32::from_le_bytes(field(at, 4)?.try_into().ok()?));
|
||||
let layout = || {
|
||||
let coff = (u32_at(0x3C)? as usize).checked_add(4)?;
|
||||
let sections = u16_at(coff.checked_add(2)?)?;
|
||||
let optional_size = usize::from(u16_at(coff.checked_add(16)?)?);
|
||||
let optional = coff.checked_add(20)?;
|
||||
let image_base = optional.checked_add(OPTIONAL_IMAGE_BASE)?;
|
||||
let agrees = u16_at(optional)? == PE32_PLUS_MAGIC
|
||||
&& optional_size >= PE32_PLUS_MIN_OPTIONAL_HEADER
|
||||
&& sections == self.number_of_sections
|
||||
&& u64::from_le_bytes(field(image_base, 8)?.try_into().ok()?) == self.image_base
|
||||
&& u32_at(optional.checked_add(OPTIONAL_SIZE_OF_HEADERS)?)? == self.size_of_headers;
|
||||
let table_end = optional
|
||||
.checked_add(optional_size)?
|
||||
.checked_add(usize::from(sections).checked_mul(SECTION_HEADER_SIZE)?)?;
|
||||
agrees.then_some((image_base, table_end))
|
||||
};
|
||||
let (image_base, table_end) = layout().ok_or(PeError::InvalidHeaderSize)?;
|
||||
|
||||
// A size of zero is shorter than any section table.
|
||||
let len = self.size_of_headers as usize;
|
||||
if len < table_end || len > bytes.len() {
|
||||
return Err(PeError::InvalidHeaderSize);
|
||||
}
|
||||
let mapped = u64::from(self.size_of_headers).next_multiple_of(HEADER_PAGE);
|
||||
let reaches_a_section = self.sections.iter().any(|sec| {
|
||||
sec.virtual_size.max(sec.raw_data_size) > 0 && u64::from(sec.virtual_address) < mapped
|
||||
});
|
||||
if reaches_a_section {
|
||||
return Err(PeError::InvalidHeaderSize);
|
||||
}
|
||||
Ok((len, mapped, image_base))
|
||||
}
|
||||
|
||||
/// Load this parsed PE into a fresh `GuestMemory` instance, mapping the
|
||||
/// headers and all sections.
|
||||
pub fn load_into_memory(&self, bytes: &[u8]) -> Result<LoadedImage, PeError> {
|
||||
self.load_at_base(bytes, self.image_base)
|
||||
}
|
||||
|
||||
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
|
||||
// Each section becomes a zero-filled host allocation, so bound the total before
|
||||
// allocating anything. Sections may not overlap, so the sum is the mapped size.
|
||||
let mapped: u64 = self
|
||||
let (headers_len, headers_mapped, image_base_field) = self.headers_for(bytes)?;
|
||||
|
||||
// The headers and each section become zero-filled host allocations, so bound
|
||||
// the total before allocating anything. Sections may not overlap, so the sum
|
||||
// is the mapped size.
|
||||
let mapped = self
|
||||
.sections
|
||||
.iter()
|
||||
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
|
||||
.sum();
|
||||
.sum::<u64>()
|
||||
+ headers_mapped;
|
||||
if mapped > MAX_MAPPED_IMAGE_BYTES {
|
||||
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
|
||||
}
|
||||
|
||||
let mut memory = GuestMemory::new();
|
||||
|
||||
// Windows maps the headers read-only at the image base, and programs read
|
||||
// them: a C runtime finds its own sections this way before `main`. The
|
||||
// budget above is checked first, and the file bytes are the initial data
|
||||
// of the mapping, so nothing else is copied.
|
||||
memory
|
||||
.map_region_with_data(
|
||||
base,
|
||||
headers_mapped as usize,
|
||||
MemoryPermissions::READ_ONLY,
|
||||
&bytes[..headers_len],
|
||||
)
|
||||
.map_err(PeError::SectionMappingError)?;
|
||||
let image_base_field = base
|
||||
.checked_add(image_base_field as u64)
|
||||
.ok_or(PeError::InvalidHeaderSize)?;
|
||||
|
||||
for sec in &self.sections {
|
||||
let base_addr = base
|
||||
.checked_add(u64::from(sec.virtual_address))
|
||||
@@ -323,6 +409,7 @@ impl ParsedPe {
|
||||
pe: self.clone(),
|
||||
memory,
|
||||
entry_point,
|
||||
image_base_field,
|
||||
})
|
||||
}
|
||||
}
|
||||
+234
-1
@@ -163,7 +163,6 @@ pub fn apply_relocations(
|
||||
let reloc_type = (entry_val >> 12) as u8;
|
||||
let offset_in_page = (entry_val & 0x0FFF) as u32;
|
||||
|
||||
*report.type_counts.entry(reloc_type).or_insert(0) += 1;
|
||||
report.total_entries += 1;
|
||||
|
||||
match reloc_type {
|
||||
@@ -221,6 +220,17 @@ pub fn apply_relocations(
|
||||
read_bytes += block_size as usize;
|
||||
}
|
||||
|
||||
// Only these two types can reach a successful return. Build the public
|
||||
// histogram once instead of searching its tree for every relocation.
|
||||
for (kind, count) in [
|
||||
(IMAGE_REL_BASED_ABSOLUTE, report.skipped_absolute),
|
||||
(IMAGE_REL_BASED_DIR64, report.applied_dir64),
|
||||
] {
|
||||
if count != 0 {
|
||||
report.type_counts.insert(kind, count);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
@@ -274,3 +284,226 @@ fn find_reloc_directory(
|
||||
Ok(Some((reloc_rva, reloc_size)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::memory::MemoryPermissions;
|
||||
use crate::pe::PeSection;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
const PREFERRED: u64 = 0x140000000;
|
||||
const LOADED: u64 = PREFERRED + 0x200000;
|
||||
const DATA_RVA: u32 = 0x1000;
|
||||
const DIRECTORY_RVA: u32 = 0x10000000;
|
||||
const DIRECTORY_OFFSET: usize = 0x200;
|
||||
|
||||
// Original synthetic directory, laid out from Microsoft's PE Format,
|
||||
// .reloc section: eight-byte block headers and two-byte type/offset words.
|
||||
// https://learn.microsoft.com/windows/win32/debug/pe-format#the-reloc-section-image-only
|
||||
// Header fields and metadata are supplied directly: PE parsing is not timed.
|
||||
fn fixture(blocks: &[(u32, Vec<u16>)], data: &[u8]) -> (ParsedPe, Vec<u8>, GuestMemory) {
|
||||
let mut bytes = vec![0u8; DIRECTORY_OFFSET];
|
||||
bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
|
||||
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
|
||||
bytes[0x104..0x108].copy_from_slice(&16u32.to_le_bytes());
|
||||
bytes[0x130..0x134].copy_from_slice(&DIRECTORY_RVA.to_le_bytes());
|
||||
for (page, entries) in blocks {
|
||||
bytes.extend_from_slice(&page.to_le_bytes());
|
||||
bytes.extend_from_slice(&(8u32 + entries.len() as u32 * 2).to_le_bytes());
|
||||
for entry in entries {
|
||||
bytes.extend_from_slice(&entry.to_le_bytes());
|
||||
}
|
||||
}
|
||||
let size = (bytes.len() - DIRECTORY_OFFSET) as u32;
|
||||
bytes[0x134..0x138].copy_from_slice(&size.to_le_bytes());
|
||||
let pe = ParsedPe {
|
||||
machine: 0x8664,
|
||||
number_of_sections: 1,
|
||||
time_date_stamp: 0,
|
||||
image_base: PREFERRED,
|
||||
section_alignment: 4096,
|
||||
file_alignment: 512,
|
||||
size_of_image: DIRECTORY_RVA + size.max(4096),
|
||||
size_of_headers: 512,
|
||||
entry_point_rva: 0,
|
||||
sections: vec![PeSection {
|
||||
name: ".reloc".into(),
|
||||
virtual_address: DIRECTORY_RVA,
|
||||
virtual_size: size,
|
||||
raw_data_ptr: DIRECTORY_OFFSET as u32,
|
||||
raw_data_size: size,
|
||||
characteristics: 0x40000040,
|
||||
permissions: MemoryPermissions::READ_ONLY,
|
||||
}],
|
||||
};
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
LOADED + u64::from(DATA_RVA),
|
||||
data.len(),
|
||||
MemoryPermissions::READ_ONLY,
|
||||
data,
|
||||
)
|
||||
.unwrap();
|
||||
(pe, bytes, memory)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_padding_and_rebases_read_only_targets() {
|
||||
for (preferred, initial, expected) in [
|
||||
(PREFERRED, 0x140001234, 0x140201234),
|
||||
(LOADED + 0x200000, 0x140001234, 0x13fe01234),
|
||||
(LOADED - 8, u64::MAX - 3, 4),
|
||||
(LOADED + 8, 3, u64::MAX - 4),
|
||||
] {
|
||||
let (mut pe, bytes, mut memory) =
|
||||
fixture(&[(DATA_RVA, vec![0x0fff, 0xa000])], &initial.to_le_bytes());
|
||||
pe.image_base = preferred;
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), expected);
|
||||
assert_eq!(report.total_entries, 2);
|
||||
assert_eq!(report.applied_dir64, 1);
|
||||
assert_eq!(report.skipped_absolute, 1);
|
||||
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 1)]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_omits_types_that_did_not_occur() {
|
||||
for (entries, counts) in [
|
||||
(vec![], BTreeMap::new()),
|
||||
(vec![0x0fff, 0x0000], BTreeMap::from([(0, 2)])),
|
||||
(vec![0xa000, 0xa008], BTreeMap::from([(10, 2)])),
|
||||
] {
|
||||
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &[0; 16]);
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
assert_eq!(report.type_counts, counts);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_duplicate_and_overlapping_entry_order() {
|
||||
let (pe, bytes, mut memory) = fixture(
|
||||
&[(DATA_RVA, vec![0xa000, 0xa000, 0xa004, 0x0000])],
|
||||
&[0; 16],
|
||||
);
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
// Two additions of 0x200000 at offset zero, then one at offset four.
|
||||
let mut actual = [0; 16];
|
||||
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
|
||||
assert_eq!(
|
||||
actual,
|
||||
[0, 0, 0x40, 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
);
|
||||
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 3)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_fields_observe_prior_carries_in_directory_order() {
|
||||
let initial = [255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0];
|
||||
for (entries, expected) in [
|
||||
(vec![0xa000, 0xa004], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]),
|
||||
(vec![0xa004, 0xa000], [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]),
|
||||
] {
|
||||
let (mut pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &initial);
|
||||
pe.image_base = LOADED - 1;
|
||||
apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
let mut actual = [0; 12];
|
||||
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_prior_writes_and_rejects_unsupported_types() {
|
||||
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, vec![0xa000, 0xf008])], &[0; 16]);
|
||||
assert_eq!(
|
||||
apply_relocations(&pe, &bytes, LOADED, &mut memory),
|
||||
Err(RelocationError::UnsupportedRelocationType(15))
|
||||
);
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), 0x200000);
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1008).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_delta_keeps_the_empty_report_without_parsing() {
|
||||
let (mut pe, _, mut memory) = fixture(&[], &[0; 8]);
|
||||
pe.image_base = LOADED;
|
||||
assert_eq!(
|
||||
apply_relocations(&pe, &[], LOADED, &mut memory).unwrap(),
|
||||
RelocationReport::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual relocation timing run; release build on an otherwise idle host"]
|
||||
fn relocation_profile() {
|
||||
for pages in [1u32, 128] {
|
||||
for padding_every in [0usize, 2, 1] {
|
||||
let blocks: Vec<_> = (0..pages)
|
||||
.map(|page| {
|
||||
let entries = (0..512)
|
||||
.map(|slot| {
|
||||
let padding = padding_every != 0 && slot % padding_every == 0;
|
||||
(if padding { 0 } else { 0xa000 }) | (slot as u16 * 8)
|
||||
})
|
||||
.collect();
|
||||
(DATA_RVA + page * 4096, entries)
|
||||
})
|
||||
.collect();
|
||||
let (pe, bytes, initial) = fixture(&blocks, &vec![0; pages as usize * 4096]);
|
||||
let mut samples = Vec::new();
|
||||
for run in 0..36 {
|
||||
let mut memory = initial.clone();
|
||||
let start = Instant::now();
|
||||
let report = black_box(
|
||||
apply_relocations(
|
||||
black_box(&pe),
|
||||
black_box(&bytes),
|
||||
LOADED,
|
||||
black_box(&mut memory),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let elapsed = start.elapsed().as_secs_f64() * 1e6;
|
||||
assert_eq!(report.total_entries, pages as usize * 512);
|
||||
let padding = match padding_every {
|
||||
0 => 0,
|
||||
2 => report.total_entries / 2,
|
||||
_ => report.total_entries,
|
||||
};
|
||||
assert_eq!(report.skipped_absolute, padding);
|
||||
assert_eq!(report.applied_dir64, report.total_entries - padding);
|
||||
// Check every output against the fixture's independently specified pattern.
|
||||
for slot in 0..pages as usize * 512 {
|
||||
let expected = if padding_every != 0 && slot % padding_every == 0 {
|
||||
0
|
||||
} else {
|
||||
0x200000
|
||||
};
|
||||
assert_eq!(
|
||||
memory.read_u64(LOADED + 0x1000 + slot as u64 * 8).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
if run >= 5 {
|
||||
samples.push(elapsed);
|
||||
}
|
||||
}
|
||||
samples.sort_by(f64::total_cmp);
|
||||
let mean = samples.iter().sum::<f64>() / samples.len() as f64;
|
||||
let variance =
|
||||
samples.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / samples.len() as f64;
|
||||
println!(
|
||||
"pages={pages} padding_every={padding_every} n={} median_us={:.3} variance_us2={variance:.3} min_us={:.3} max_us={:.3}",
|
||||
samples.len(),
|
||||
samples[samples.len() / 2],
|
||||
samples[0],
|
||||
samples[samples.len() - 1]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata};
|
||||
use crate::services::{ServicesState, handlers};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub static SERVICES: [ServiceMetadata; 20] = [
|
||||
pub static SERVICES: [ServiceMetadata; 47] = [
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "SetProcessPriorityBoost",
|
||||
@@ -141,6 +141,116 @@ pub static SERVICES: [ServiceMetadata; 20] = [
|
||||
reference: "sysinfoapi.h GetSystemTimeAsFileTime",
|
||||
tests: &["system_time_comes_from_the_injected_clock"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__acrt_iob_func",
|
||||
parameters: &[Parameter { name: "index", kind: "u32" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "stops the guest for an index above 2 or when the streams cannot be allocated",
|
||||
reference: "corecrt_wstdio.h __acrt_iob_func",
|
||||
tests: &["standard_streams_are_three_stable_file_objects"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__stdio_common_vfprintf",
|
||||
parameters: &[Parameter { name: "options", kind: "u64" }, Parameter { name: "stream", kind: "ptr" }, Parameter { name: "format", kind: "ptr" }, Parameter { name: "locale", kind: "ptr" }, Parameter { name: "arguments", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "-1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled",
|
||||
reference: "corecrt_stdio_config.h __stdio_common_vfprintf; Microsoft Learn, vfprintf and format specification syntax",
|
||||
tests: &["formatted_output_reaches_the_captured_standard_streams"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fwrite",
|
||||
parameters: &[Parameter { name: "buffer", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "count", kind: "u64" }, Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "u64",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "0 with errno EINVAL for a null buffer or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream",
|
||||
reference: "stdio.h fwrite",
|
||||
tests: &["fwrite_and_fputs_write_to_the_captured_standard_streams"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fputs",
|
||||
parameters: &[Parameter { name: "text", kind: "ptr" }, Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "EOF with errno EINVAL for a null string or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream",
|
||||
reference: "stdio.h fputs",
|
||||
tests: &["fwrite_and_fputs_write_to_the_captured_standard_streams"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fflush",
|
||||
parameters: &[Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "stops the guest for a pointer that is no stream",
|
||||
reference: "stdio.h fflush",
|
||||
tests: &["fflush_and_setvbuf_return_their_documented_results"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "setvbuf",
|
||||
parameters: &[Parameter { name: "stream", kind: "ptr" }, Parameter { name: "buffer", kind: "ptr" }, Parameter { name: "mode", kind: "i32" }, Parameter { name: "size", kind: "u64" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "-1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a pointer that is no stream",
|
||||
reference: "stdio.h setvbuf",
|
||||
tests: &["fflush_and_setvbuf_return_their_documented_results"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fopen",
|
||||
parameters: &[Parameter { name: "name", kind: "ptr" }, Parameter { name: "mode", kind: "ptr" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "null with errno EINVAL, ENOENT, EACCES, EMFILE, ENOSPC or ENOMEM",
|
||||
reference: "stdio.h fopen",
|
||||
tests: &["a_file_written_through_a_stream_reads_back_line_by_line"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fclose",
|
||||
parameters: &[Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "EOF with errno EINVAL for a null stream; stops the guest for a standard stream or a pointer that is no stream",
|
||||
reference: "stdio.h fclose",
|
||||
tests: &["a_file_written_through_a_stream_reads_back_line_by_line"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fgets",
|
||||
parameters: &[Parameter { name: "buffer", kind: "ptr" }, Parameter { name: "count", kind: "i32" }, Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "null at end of file; null with errno EINVAL or EBADF; stops the guest for stdin or a pointer that is no stream",
|
||||
reference: "stdio.h fgets",
|
||||
tests: &["fgets_reads_lines_within_its_count"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "perror",
|
||||
parameters: &[Parameter { name: "message", kind: "ptr" }],
|
||||
result: "void",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "stdio.h perror",
|
||||
tests: &["perror_writes_the_message_and_the_error_text_to_stderr"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetLastError",
|
||||
@@ -163,6 +273,61 @@ pub static SERVICES: [ServiceMetadata; 20] = [
|
||||
reference: "errhandlingapi.h SetLastError",
|
||||
tests: &["last_error_is_set_by_failures_and_by_the_guest"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__p___argc",
|
||||
parameters: &[],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "stops the guest when the variable cannot be allocated",
|
||||
reference: "Microsoft Learn, C runtime library reference, __argc, __argv, __wargv",
|
||||
tests: &["program_arguments_reach_the_guest_as_argc_and_argv"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__p___argv",
|
||||
parameters: &[],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "stops the guest when the variable cannot be allocated",
|
||||
reference: "Microsoft Learn, C runtime library reference, __argc, __argv, __wargv",
|
||||
tests: &["program_arguments_reach_the_guest_as_argc_and_argv"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__p__environ",
|
||||
parameters: &[],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-environment-l1-1-0.dll"],
|
||||
failure: "stops the guest when the variable cannot be allocated",
|
||||
reference: "Microsoft Learn, C runtime library reference, _environ, _wenviron",
|
||||
tests: &["the_environment_table_is_empty_and_ends_with_a_null_pointer"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "_configure_narrow_argv",
|
||||
parameters: &[Parameter { name: "mode", kind: "i32" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "EINVAL for a mode other than 0, 1 or 2; stops the guest when the table cannot be allocated",
|
||||
reference: "corecrt_startup.h _configure_narrow_argv",
|
||||
tests: &["program_arguments_reach_the_guest_as_argc_and_argv"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "_initialize_narrow_environment",
|
||||
parameters: &[],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "stops the guest when the table cannot be allocated",
|
||||
reference: "corecrt_startup.h _initialize_narrow_environment",
|
||||
tests: &["the_environment_table_is_empty_and_ends_with_a_null_pointer"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "VirtualAlloc",
|
||||
@@ -185,6 +350,39 @@ pub static SERVICES: [ServiceMetadata; 20] = [
|
||||
reference: "memoryapi.h VirtualFree",
|
||||
tests: &["virtual_memory_is_mapped_released_and_bounded"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "VirtualProtect",
|
||||
parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "protect", kind: "u32" }, Parameter { name: "old", kind: "out<4>" }],
|
||||
result: "bool32",
|
||||
status: ServiceStatus::Stub,
|
||||
aliases: &["api-ms-win-core-memory-l1-1-0.dll"],
|
||||
failure: "always: stops the guest with the runtime-limit fault; no protection changes",
|
||||
reference: "memoryapi.h VirtualProtect",
|
||||
tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "VirtualQuery",
|
||||
parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "information", kind: "out<48>" }, Parameter { name: "length", kind: "u64" }],
|
||||
result: "u64",
|
||||
status: ServiceStatus::Stub,
|
||||
aliases: &["api-ms-win-core-memory-l1-1-0.dll"],
|
||||
failure: "always: stops the guest with the runtime-limit fault; nothing is written",
|
||||
reference: "memoryapi.h VirtualQuery",
|
||||
tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__C_specific_handler",
|
||||
parameters: &[Parameter { name: "record", kind: "ptr" }, Parameter { name: "frame", kind: "ptr" }, Parameter { name: "context", kind: "ptr" }, Parameter { name: "dispatcher", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Stub,
|
||||
aliases: &["api-ms-win-crt-private-l1-1-0.dll"],
|
||||
failure: "always: stops the guest with the runtime-limit fault; no exception is dispatched",
|
||||
reference: "Microsoft Learn, x64 exception handling, language-specific handler",
|
||||
tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "sqrt",
|
||||
@@ -229,6 +427,105 @@ pub static SERVICES: [ServiceMetadata; 20] = [
|
||||
reference: "math.h fabsf (ISO C, IEC 60559 abs)",
|
||||
tests: &["floating_arguments_and_results_use_xmm_registers"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "_set_app_type",
|
||||
parameters: &[Parameter { name: "kind", kind: "i32" }],
|
||||
result: "void",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "corecrt_startup.h _set_app_type",
|
||||
tests: &["crt_app_type_and_math_error_handler_are_recorded"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "_set_new_mode",
|
||||
parameters: &[Parameter { name: "mode", kind: "i32" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-heap-l1-1-0.dll"],
|
||||
failure: "-1 with errno EINVAL for a mode other than 0 or 1",
|
||||
reference: "new.h _set_new_mode",
|
||||
tests: &["crt_startup_modes_return_the_previous_setting"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "_configthreadlocale",
|
||||
parameters: &[Parameter { name: "request", kind: "i32" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-locale-l1-1-0.dll"],
|
||||
failure: "-1 with errno EINVAL for a request other than 0, 1 or 2",
|
||||
reference: "locale.h _configthreadlocale",
|
||||
tests: &["crt_startup_modes_return_the_previous_setting"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__setusermatherr",
|
||||
parameters: &[Parameter { name: "handler", kind: "ptr" }],
|
||||
result: "void",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-math-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "corecrt_startup.h __setusermatherr",
|
||||
tests: &["crt_app_type_and_math_error_handler_are_recorded"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "_set_invalid_parameter_handler",
|
||||
parameters: &[Parameter { name: "handler", kind: "ptr" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "stdlib.h _set_invalid_parameter_handler",
|
||||
tests: &["crt_startup_handlers_return_the_previous_handler"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__p__fmode",
|
||||
parameters: &[],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "stops the guest when the variable cannot be allocated",
|
||||
reference: "Microsoft Learn, C runtime library reference, __p__fmode",
|
||||
tests: &["crt_file_mode_variables_are_guest_memory"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__p__commode",
|
||||
parameters: &[],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "stops the guest when the variable cannot be allocated",
|
||||
reference: "Microsoft Learn, C runtime library reference, __p__commode",
|
||||
tests: &["crt_file_mode_variables_are_guest_memory"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "signal",
|
||||
parameters: &[Parameter { name: "signal", kind: "i32" }, Parameter { name: "handler", kind: "ptr" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "SIG_ERR with errno EINVAL for a signal the documentation does not list",
|
||||
reference: "signal.h signal",
|
||||
tests: &["crt_startup_handlers_return_the_previous_handler"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "SetUnhandledExceptionFilter",
|
||||
parameters: &[Parameter { name: "filter", kind: "ptr" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-errorhandling-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "errhandlingapi.h SetUnhandledExceptionFilter",
|
||||
tests: &["crt_startup_handlers_return_the_previous_handler"],
|
||||
},
|
||||
];
|
||||
|
||||
/// Register every generated service and its API-set aliases.
|
||||
@@ -331,6 +628,100 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__acrt_iob_func", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::standard_stream(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__stdio_common_vfprintf", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u64(2)?;
|
||||
let a3 = call.u64(3)?;
|
||||
let a4 = call.u64(4)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::vfprintf(&mut context, a0, a1, a2, a3, a4)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fwrite", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u64(2)?;
|
||||
let a3 = call.u64(3)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::fwrite(&mut context, a0, a1, a2, a3)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fputs", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::fputs(&mut context, a0, a1)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fflush", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::fflush(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "setvbuf", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.i32(2)?;
|
||||
let a3 = call.u64(3)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::setvbuf(&mut context, a0, a1, a2, a3)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fopen", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::fopen(&mut context, a0, a1)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fclose", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::fclose(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fgets", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.i32(1)?;
|
||||
let a2 = call.u64(2)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::fgets(&mut context, a0, a1, a2)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "perror", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let () = handlers::perror(&mut context, a0)?;
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "GetLastError", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
@@ -346,6 +737,42 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__p___argc", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::argc_pointer(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__p___argv", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::argv_pointer(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__p__environ", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::environ_pointer(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "_configure_narrow_argv", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.i32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::configure_narrow_argv(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "_initialize_narrow_environment", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::initialize_narrow_environment(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "VirtualAlloc", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
@@ -367,6 +794,38 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "VirtualProtect", ServiceStatus::Stub, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u32(2)?;
|
||||
let a3 = call.out::<4>(3)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: bool = handlers::virtual_protect(&mut context, a0, a1, a2, a3)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "VirtualQuery", ServiceStatus::Stub, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.out::<48>(1)?;
|
||||
let a2 = call.u64(2)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::virtual_query(&mut context, a0, a1, a2)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__C_specific_handler", ServiceStatus::Stub, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u64(2)?;
|
||||
let a3 = call.u64(3)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::c_specific_handler(&mut context, a0, a1, a2, a3)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "sqrt", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.f64(0)?;
|
||||
@@ -398,6 +857,77 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let result: crate::runtime::Float32 = handlers::fabsf(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "_set_app_type", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.i32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let () = handlers::set_app_type(&mut context, a0)?;
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "_set_new_mode", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.i32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::set_new_mode(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "_configthreadlocale", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.i32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::configure_thread_locale(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__setusermatherr", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let () = handlers::set_user_math_error(&mut context, a0)?;
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "_set_invalid_parameter_handler", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::set_invalid_parameter_handler(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__p__fmode", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::file_mode_pointer(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__p__commode", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::commit_mode_pointer(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "signal", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.i32(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::signal(&mut context, a0, a1)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "SetUnhandledExceptionFilter", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::set_unhandled_exception_filter(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
for service in &SERVICES {
|
||||
for alias in service.aliases {
|
||||
if let Err(error) = registry.try_alias(alias, service.library, service.symbol) {
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Deterministic cooperative scheduler for guest threads.
|
||||
//!
|
||||
//! One host thread runs one guest thread at a time, in first-in, first-out
|
||||
//! order, for a bounded number of instructions. The same program, quantum and
|
||||
//! clock always interleave the same way. Guest threads never run concurrently,
|
||||
//! so nothing here relies on a guest memory-ordering model.
|
||||
//!
|
||||
//! A service that has to wait returns [`ExitReason::GuestBlocked`] without any
|
||||
//! effect and with RIP still on its trampoline. The scheduler runs that call
|
||||
//! again when something it may wait for has changed, oldest waiter first.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason};
|
||||
use crate::dbt::DbtEngine;
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::services::ServicesState;
|
||||
use crate::services::threads::{RunState, THREAD_RETURN};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Default instructions a thread runs before the next one gets a turn.
|
||||
pub const DEFAULT_QUANTUM: usize = 1024;
|
||||
|
||||
/// Why scheduling stopped.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
/// The main thread executed HLT, the synthetic process exit.
|
||||
Halted,
|
||||
/// Every thread ended.
|
||||
AllThreadsExited,
|
||||
/// No thread can run and no wait has a deadline.
|
||||
Deadlock {
|
||||
blocked: Vec<u32>,
|
||||
suspended: Vec<u32>,
|
||||
},
|
||||
BudgetExhausted,
|
||||
/// A thread stopped for a reason the guest cannot handle.
|
||||
Fault {
|
||||
thread: u32,
|
||||
reason: ExitReason,
|
||||
rip: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// Result of one scheduled run.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ScheduleReport {
|
||||
pub outcome: Outcome,
|
||||
/// Guest instructions and service calls, including repeated waits.
|
||||
pub instructions: usize,
|
||||
/// Turns given to threads.
|
||||
pub turns: usize,
|
||||
/// Largest number of guest threads alive at once.
|
||||
pub peak_threads: usize,
|
||||
/// Main thread state when it last stopped.
|
||||
pub main: CpuState,
|
||||
}
|
||||
|
||||
pub struct Scheduler {
|
||||
state: Arc<ServicesState>,
|
||||
quantum: usize,
|
||||
}
|
||||
|
||||
enum Turn {
|
||||
Continue,
|
||||
Stop(Outcome),
|
||||
}
|
||||
|
||||
impl Scheduler {
|
||||
/// `quantum` is at least one instruction; a turn ends at the first block
|
||||
/// boundary that reaches it.
|
||||
pub fn new(state: Arc<ServicesState>, quantum: usize) -> Self {
|
||||
Self {
|
||||
state,
|
||||
quantum: quantum.max(1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `main` and every thread it creates. Only one scheduler may be
|
||||
/// attached to a service state at a time. Created threads still alive at
|
||||
/// the end are terminated with code 0 and reclaimed, so a run that had any
|
||||
/// cannot be continued.
|
||||
pub fn run(
|
||||
&self,
|
||||
engine: &mut DbtEngine,
|
||||
memory: &mut GuestMemory,
|
||||
main: &CpuState,
|
||||
budget: usize,
|
||||
) -> Result<ScheduleReport, ExitReason> {
|
||||
let main_id = self.state.attach_scheduler(main)?;
|
||||
let mut report = ScheduleReport {
|
||||
outcome: Outcome::BudgetExhausted,
|
||||
instructions: 0,
|
||||
turns: 0,
|
||||
peak_threads: 1,
|
||||
main: main.clone(),
|
||||
};
|
||||
while report.instructions < budget {
|
||||
match self.turn(engine, memory, main_id, budget, &mut report) {
|
||||
Turn::Continue => {}
|
||||
Turn::Stop(outcome) => {
|
||||
report.outcome = outcome;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if report.outcome == Outcome::BudgetExhausted && self.all_ended() {
|
||||
report.outcome = Outcome::AllThreadsExited;
|
||||
}
|
||||
let continues = report.outcome == Outcome::BudgetExhausted;
|
||||
self.state
|
||||
.detach_scheduler(memory, continues.then_some(&report.main));
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
fn turn(
|
||||
&self,
|
||||
engine: &mut DbtEngine,
|
||||
memory: &mut GuestMemory,
|
||||
main_id: u32,
|
||||
budget: usize,
|
||||
report: &mut ScheduleReport,
|
||||
) -> Turn {
|
||||
if let Some(outcome) = self.wake(engine, memory, main_id, budget, report) {
|
||||
return Turn::Stop(outcome);
|
||||
}
|
||||
let Some(id) = self.next_ready() else {
|
||||
// A spent budget may have left waiters untried, and must not sleep.
|
||||
if report.instructions >= budget {
|
||||
return Turn::Continue;
|
||||
}
|
||||
return self.idle();
|
||||
};
|
||||
report.turns += 1;
|
||||
let turn = self.take_credit(id).unwrap_or(self.quantum);
|
||||
let limit = turn.min(budget.saturating_sub(report.instructions));
|
||||
if limit == 0 {
|
||||
self.requeue(id);
|
||||
return Turn::Continue;
|
||||
}
|
||||
let before = report.instructions;
|
||||
let stop = self.run_thread(engine, memory, id, main_id, limit, report);
|
||||
match stop {
|
||||
Stop::Outcome(outcome) => Turn::Stop(outcome),
|
||||
Stop::Ended => Turn::Continue,
|
||||
Stop::Blocked => {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
table.sequence += 1;
|
||||
let sequence = table.sequence;
|
||||
if let Some(thread) = table.threads.get_mut(&id) {
|
||||
thread.run = RunState::Blocked(sequence);
|
||||
}
|
||||
Turn::Continue
|
||||
}
|
||||
Stop::Preempted { front } => {
|
||||
// Signaling keeps the caller's turn, but never renews it.
|
||||
let left = turn.saturating_sub(report.instructions - before);
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
if let Some(thread) = table.threads.get_mut(&id) {
|
||||
if front && left > 0 {
|
||||
thread.credit = Some(left);
|
||||
table.queue.push_front(id);
|
||||
} else {
|
||||
table.queue.push_back(id);
|
||||
}
|
||||
}
|
||||
Turn::Continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn all_ended(&self) -> bool {
|
||||
let table = self.state.threads.lock().expect("guest thread table");
|
||||
table.threads.is_empty()
|
||||
}
|
||||
|
||||
/// Put back a thread that got no turn.
|
||||
fn requeue(&self, id: u32) {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
table.queue.push_front(id);
|
||||
}
|
||||
|
||||
fn take_credit(&self, id: u32) -> Option<usize> {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
table.threads.get_mut(&id)?.credit.take()
|
||||
}
|
||||
|
||||
/// Remove and return the first thread that can run.
|
||||
fn next_ready(&self) -> Option<u32> {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
let position = table
|
||||
.queue
|
||||
.iter()
|
||||
.position(|id| table.threads.get(id).is_some_and(|t| t.suspend == 0))?;
|
||||
table.queue.remove(position)
|
||||
}
|
||||
|
||||
/// Run the pending call of every blocked thread, oldest first. A thread that
|
||||
/// ends with its call may be what an older one waits for, so that repeats
|
||||
/// the pass.
|
||||
fn wake(
|
||||
&self,
|
||||
engine: &mut DbtEngine,
|
||||
memory: &mut GuestMemory,
|
||||
main_id: u32,
|
||||
budget: usize,
|
||||
report: &mut ScheduleReport,
|
||||
) -> Option<Outcome> {
|
||||
loop {
|
||||
let mut ended = false;
|
||||
for id in self.blocked(report) {
|
||||
if report.instructions >= budget {
|
||||
return None;
|
||||
}
|
||||
match self.run_thread(engine, memory, id, main_id, 1, report) {
|
||||
Stop::Outcome(outcome) => return Some(outcome),
|
||||
Stop::Blocked => {}
|
||||
Stop::Ended => ended = true,
|
||||
Stop::Preempted { .. } => {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
if let Some(thread) = table.threads.get_mut(&id) {
|
||||
thread.run = RunState::Ready;
|
||||
table.queue.push_back(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !ended {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocked threads that are not suspended, oldest first.
|
||||
fn blocked(&self, report: &mut ScheduleReport) -> Vec<u32> {
|
||||
let table = self.state.threads.lock().expect("guest thread table");
|
||||
report.peak_threads = report.peak_threads.max(table.threads.len());
|
||||
let mut blocked: Vec<(u64, u32)> = table
|
||||
.threads
|
||||
.iter()
|
||||
.filter(|(_, thread)| thread.suspend == 0)
|
||||
.filter_map(|(&id, thread)| match thread.run {
|
||||
RunState::Blocked(sequence) => Some((sequence, id)),
|
||||
RunState::Ready => None,
|
||||
})
|
||||
.collect();
|
||||
blocked.sort_unstable();
|
||||
blocked.into_iter().map(|(_, id)| id).collect()
|
||||
}
|
||||
|
||||
/// Nothing can run: advance to the next deadline or stop.
|
||||
fn idle(&self) -> Turn {
|
||||
let table = self.state.threads.lock().expect("guest thread table");
|
||||
if table.threads.is_empty() {
|
||||
return Turn::Stop(Outcome::AllThreadsExited);
|
||||
}
|
||||
if let Some(deadline) = table.next_deadline() {
|
||||
drop(table);
|
||||
let now = self.state.clock.performance_count();
|
||||
self.state.clock.sleep(deadline.saturating_sub(now));
|
||||
return Turn::Continue;
|
||||
}
|
||||
let mut blocked = Vec::new();
|
||||
let mut suspended = Vec::new();
|
||||
for (&id, thread) in &table.threads {
|
||||
if thread.suspend > 0 {
|
||||
suspended.push(id);
|
||||
} else {
|
||||
blocked.push(id);
|
||||
}
|
||||
}
|
||||
Turn::Stop(Outcome::Deadlock { blocked, suspended })
|
||||
}
|
||||
|
||||
fn run_thread(
|
||||
&self,
|
||||
engine: &mut DbtEngine,
|
||||
memory: &mut GuestMemory,
|
||||
id: u32,
|
||||
main_id: u32,
|
||||
limit: usize,
|
||||
report: &mut ScheduleReport,
|
||||
) -> Stop {
|
||||
let cpu = {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
table.threads.get_mut(&id).and_then(|t| t.cpu.take())
|
||||
};
|
||||
let Some(mut cpu) = cpu else {
|
||||
return Stop::Ended;
|
||||
};
|
||||
self.state.hooks.take_switch();
|
||||
let result = engine.run_slice(&mut cpu, memory, limit);
|
||||
// The engine does not count a call that stops it.
|
||||
let stopped = matches!(
|
||||
result.exit_reason,
|
||||
ExitReason::GuestYield | ExitReason::GuestBlocked | ExitReason::GuestThreadExited
|
||||
);
|
||||
report.instructions += result.instructions_executed + usize::from(stopped);
|
||||
let rip = cpu.rip;
|
||||
let returned = (rip == THREAD_RETURN && id != main_id)
|
||||
.then(|| cpu.get(crate::cpu::Register::Rax) as u32);
|
||||
if id == main_id {
|
||||
report.main = cpu.clone();
|
||||
}
|
||||
let exit = {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
let Some(thread) = table.threads.get_mut(&id) else {
|
||||
return Stop::Ended;
|
||||
};
|
||||
thread.cpu = Some(cpu);
|
||||
thread.exit
|
||||
};
|
||||
if let Some(code) = exit.or(returned) {
|
||||
self.state.end_thread(id, code, memory);
|
||||
return Stop::Ended;
|
||||
}
|
||||
match result.exit_reason {
|
||||
ExitReason::StepLimitExceeded => Stop::Preempted { front: false },
|
||||
ExitReason::GuestYield => Stop::Preempted {
|
||||
front: !self.state.hooks.take_switch(),
|
||||
},
|
||||
ExitReason::GuestBlocked => Stop::Blocked,
|
||||
ExitReason::Halt if id == main_id => Stop::Outcome(Outcome::Halted),
|
||||
reason => Stop::Outcome(Outcome::Fault {
|
||||
thread: id,
|
||||
reason,
|
||||
rip,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Stop {
|
||||
Blocked,
|
||||
Ended,
|
||||
Preempted { front: bool },
|
||||
Outcome(Outcome),
|
||||
}
|
||||
+488
-16
@@ -10,19 +10,28 @@
|
||||
//! - Xbox physical memory: `XMemAlloc`, `XMemFree`
|
||||
|
||||
mod crt;
|
||||
mod crt_arguments;
|
||||
mod crt_callbacks;
|
||||
mod crt_files;
|
||||
mod crt_format;
|
||||
mod crt_startup;
|
||||
mod crt_streams;
|
||||
mod events;
|
||||
mod files;
|
||||
mod gdk_queue;
|
||||
mod heap;
|
||||
mod modules;
|
||||
mod platform_fixture;
|
||||
mod process;
|
||||
mod synch;
|
||||
pub mod sysinfo;
|
||||
mod task_fixture;
|
||||
pub(crate) mod threads;
|
||||
mod winsock;
|
||||
|
||||
use crate::runtime::HResult;
|
||||
pub use crt_arguments::{MAX_PROGRAM_ARGUMENT_BYTES, ProgramArgumentsError};
|
||||
pub use crt_streams::MAX_CAPTURED_OUTPUT;
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
@@ -92,8 +101,14 @@ impl MockClock {
|
||||
}
|
||||
}
|
||||
|
||||
/// Move both readings forward by `intervals` 100-nanosecond ticks. Each
|
||||
/// stops at its maximum, so neither ever runs backwards.
|
||||
pub fn advance(&self, intervals: u64) {
|
||||
self.current.fetch_add(intervals, Ordering::SeqCst);
|
||||
self.current
|
||||
.try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
|
||||
Some(current.saturating_add(intervals))
|
||||
})
|
||||
.expect("clock update always returns a value");
|
||||
self.performance_count
|
||||
.try_update(Ordering::SeqCst, Ordering::SeqCst, |count| {
|
||||
Some(count.saturating_add(intervals).min(MAX_PERFORMANCE_COUNT))
|
||||
@@ -192,9 +207,16 @@ pub struct ServicesState {
|
||||
pub guest_profile: sysinfo::GuestSystemProfile,
|
||||
objects: Mutex<ObjectState>,
|
||||
last_errors: Mutex<BTreeMap<u64, u32>>,
|
||||
crt_arguments: Mutex<crt_arguments::CrtArguments>,
|
||||
synch: Mutex<synch::Synch>,
|
||||
crt_streams: Mutex<crt_streams::StandardStreams>,
|
||||
pub(crate) threads: Mutex<threads::ThreadTable>,
|
||||
pub(crate) hooks: Arc<threads::SchedulerHooks>,
|
||||
/// Functions registered with `atexit`, run in reverse order by `_cexit`.
|
||||
atexit: Mutex<Vec<u64>>,
|
||||
/// The status the guest process exited with. Set once.
|
||||
exit_status: Mutex<Option<u32>>,
|
||||
crt_startup: Mutex<crt_startup::CrtStartup>,
|
||||
winsock: Mutex<winsock::Winsock>,
|
||||
task_fixture: Mutex<task_fixture::TaskFixture>,
|
||||
platform_fixture: Mutex<platform_fixture::PlatformFixture>,
|
||||
@@ -216,8 +238,14 @@ impl ServicesState {
|
||||
guest_profile: sysinfo::GuestSystemProfile::default(),
|
||||
objects: Mutex::new(ObjectState::default()),
|
||||
last_errors: Mutex::default(),
|
||||
crt_arguments: Mutex::default(),
|
||||
synch: Mutex::default(),
|
||||
crt_streams: Mutex::default(),
|
||||
threads: Mutex::default(),
|
||||
hooks: Arc::default(),
|
||||
atexit: Mutex::default(),
|
||||
exit_status: Mutex::default(),
|
||||
crt_startup: Mutex::default(),
|
||||
winsock: Mutex::default(),
|
||||
task_fixture: Mutex::default(),
|
||||
platform_fixture: Mutex::default(),
|
||||
@@ -228,6 +256,21 @@ impl ServicesState {
|
||||
graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())),
|
||||
}
|
||||
}
|
||||
/// Give a hosted C program the arguments its `main` receives in `argv`,
|
||||
/// program name first. Call it before running the guest: the C runtime's
|
||||
/// startup code builds `argv` once, and a call after that is refused.
|
||||
///
|
||||
/// The strings reach the guest as their bytes; no code page is applied.
|
||||
/// A host that never calls this gives the program one argument, the empty
|
||||
/// string. An empty slice gives it none.
|
||||
pub fn set_program_arguments(&self, arguments: &[&str]) -> Result<(), ProgramArgumentsError> {
|
||||
self.crt_arguments().supply(arguments)
|
||||
}
|
||||
|
||||
fn crt_arguments(&self) -> std::sync::MutexGuard<'_, crt_arguments::CrtArguments> {
|
||||
self.crt_arguments.lock().expect("program arguments")
|
||||
}
|
||||
|
||||
fn uptime_millis(&self) -> u64 {
|
||||
let ticks = self
|
||||
.clock
|
||||
@@ -241,6 +284,93 @@ impl ServicesState {
|
||||
self.priority_boost_disabled.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// The status the guest process exited with, once it has exited.
|
||||
pub fn exit_status(&self) -> Option<u32> {
|
||||
*self.exit_status.lock().expect("guest exit status")
|
||||
}
|
||||
|
||||
/// How many guest handles are open: kernel objects, sockets and task
|
||||
/// queues, which are kept in three separate tables.
|
||||
pub fn open_handle_count(&self) -> usize {
|
||||
let objects = self
|
||||
.objects
|
||||
.lock()
|
||||
.expect("guest object state")
|
||||
.handles
|
||||
.len();
|
||||
let sockets = self
|
||||
.winsock
|
||||
.lock()
|
||||
.expect("guest Winsock state")
|
||||
.open_count();
|
||||
let queues = self
|
||||
.gdk_queues
|
||||
.lock()
|
||||
.expect("GDK queue handle table")
|
||||
.open_count();
|
||||
objects + sockets + queues
|
||||
}
|
||||
|
||||
/// A file on the synthetic `C:` drive, named as the guest names it.
|
||||
pub fn file_contents(&self, path: &str) -> Option<Vec<u8>> {
|
||||
let path = path.replace('/', "\\").to_ascii_lowercase();
|
||||
let name = path.strip_prefix("c:\\").unwrap_or(&path);
|
||||
self.objects
|
||||
.lock()
|
||||
.expect("guest object state")
|
||||
.files
|
||||
.get(name)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// End the guest process. The first exit decides the status; a later one
|
||||
/// reports it again and changes nothing.
|
||||
///
|
||||
/// Every guest handle is closed: kernel objects, sockets and task queues.
|
||||
/// Files stay on the synthetic drive, guest memory stays mapped for the
|
||||
/// host to inspect, and `atexit` functions are not run.
|
||||
fn exit_process(&self, status: u32) -> u32 {
|
||||
let mut exited = self.exit_status.lock().expect("guest exit status");
|
||||
if let Some(first) = *exited {
|
||||
return first;
|
||||
}
|
||||
*exited = Some(status);
|
||||
// The three table locks are taken one at a time, never nested.
|
||||
self.objects
|
||||
.lock()
|
||||
.expect("guest object state")
|
||||
.handles
|
||||
.clear();
|
||||
self.winsock
|
||||
.lock()
|
||||
.expect("guest Winsock state")
|
||||
.close_all();
|
||||
self.winsock_changed.notify_all();
|
||||
self.gdk_queues
|
||||
.lock()
|
||||
.expect("GDK queue handle table")
|
||||
.close_all();
|
||||
self.gdk_queue_changed.notify_all();
|
||||
status
|
||||
}
|
||||
|
||||
/// Everything the guest has written to `stdout`, as the bytes a text-mode
|
||||
/// stream hands the operating system: each line feed the program wrote is
|
||||
/// a carriage return and a line feed here.
|
||||
pub fn standard_output(&self) -> Vec<u8> {
|
||||
self.crt_streams().output().to_vec()
|
||||
}
|
||||
|
||||
/// Everything the guest has written to `stderr`, in the same form as
|
||||
/// [`Self::standard_output`].
|
||||
pub fn standard_error(&self) -> Vec<u8> {
|
||||
self.crt_streams().error().to_vec()
|
||||
}
|
||||
|
||||
fn crt_streams(&self) -> std::sync::MutexGuard<'_, crt_streams::StandardStreams> {
|
||||
self.crt_streams.lock().expect("standard streams")
|
||||
}
|
||||
|
||||
/// Read the last-error value for a guest thread's TEB.
|
||||
pub fn last_error(&self, teb: u64) -> u32 {
|
||||
self.last_errors
|
||||
@@ -275,6 +405,22 @@ impl ServicesState {
|
||||
}
|
||||
}
|
||||
|
||||
fn crt_startup(&self) -> std::sync::MutexGuard<'_, crt_startup::CrtStartup> {
|
||||
self.crt_startup.lock().expect("C runtime startup state")
|
||||
}
|
||||
|
||||
/// The application type the guest passed to `_set_app_type`, zero until it
|
||||
/// does. Nothing in the runtime depends on it.
|
||||
pub fn crt_app_type(&self) -> i32 {
|
||||
self.crt_startup().app_type()
|
||||
}
|
||||
|
||||
/// The guest function passed to `__setusermatherr`, zero until one is. It
|
||||
/// is never called.
|
||||
pub fn crt_user_math_error(&self) -> u64 {
|
||||
self.crt_startup().user_math_error()
|
||||
}
|
||||
|
||||
/// Record a guest error and return the documented failure value.
|
||||
fn fail<T>(&self, teb: u64, error: u32, value: T) -> Result<T, ExitReason> {
|
||||
self.set_last_error(teb, error);
|
||||
@@ -294,11 +440,26 @@ impl ServicesState {
|
||||
/// hand-written fixture services.
|
||||
pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<ServicesState>) {
|
||||
crate::runtime_table::register(registry, &state);
|
||||
registry.hooks = Some(Arc::clone(&state.hooks));
|
||||
threads::register(registry, &state);
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "GetThreadId", move |args, cpu, mem| {
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if handle == CURRENT_THREAD {
|
||||
return Ok(u64::from(s.thread_id_of(cpu.gs_base)));
|
||||
}
|
||||
let thread = s.objects.lock().expect("guest object state");
|
||||
if let Some(GuestObject::Waitable { state, access }) = thread.handles.get(&handle)
|
||||
&& let events::Waitable::Thread { id, .. } =
|
||||
&*state.lock().expect("guest waitable state")
|
||||
{
|
||||
return if access & THREAD_QUERY_RIGHTS == 0 {
|
||||
s.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0)
|
||||
} else {
|
||||
Ok(u64::from(*id))
|
||||
};
|
||||
}
|
||||
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
|
||||
return s.fail(cpu.gs_base, error, 0);
|
||||
}
|
||||
@@ -324,8 +485,12 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
if inherit != 0 || options & !DUPLICATE_SAME_ACCESS != 0 || source == CURRENT_PROCESS {
|
||||
return s.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let worker = s.current_worker(cpu.gs_base);
|
||||
let mut thread = s.objects.lock().expect("guest object state");
|
||||
let (granted, mut object) = if source == CURRENT_THREAD {
|
||||
let (granted, mut object) = if let (CURRENT_THREAD, Some(state)) = (source, worker) {
|
||||
let access = threads::THREAD_ALL_ACCESS;
|
||||
(access, GuestObject::Waitable { state, access })
|
||||
} else if source == CURRENT_THREAD {
|
||||
(
|
||||
THREAD_SUPPORTED_RIGHTS,
|
||||
GuestObject::Thread(THREAD_SUPPORTED_RIGHTS),
|
||||
@@ -439,20 +604,24 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let page_size = 4096;
|
||||
let aligned_size = (size + page_size - 1) & !(page_size - 1);
|
||||
let page_size = 4096usize;
|
||||
// Huge or overflowing sizes fail closed. Unbounded map_region would
|
||||
// try to malloc multi-gigabyte host buffers (libFuzzer OOM on
|
||||
// ~3.7 GiB); route through the virtual budget instead.
|
||||
let Some(aligned_size) = size
|
||||
.checked_add(page_size - 1)
|
||||
.map(|rounded| rounded & !(page_size - 1))
|
||||
.filter(|&aligned| aligned != 0)
|
||||
else {
|
||||
return Ok(0);
|
||||
};
|
||||
let alloc_addr = s
|
||||
.next_alloc_addr
|
||||
.fetch_add(aligned_size as u64, Ordering::SeqCst);
|
||||
|
||||
if mem
|
||||
.map_region(alloc_addr, aligned_size, MemoryPermissions::READ_WRITE)
|
||||
.is_err()
|
||||
{
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
Ok(alloc_addr)
|
||||
Ok(mem
|
||||
.map_virtual_allocation(alloc_addr, aligned_size, MemoryPermissions::READ_WRITE)
|
||||
.unwrap_or(0))
|
||||
};
|
||||
registry.register("xmem.dll", "XMemAlloc", handler);
|
||||
registry.set_status("xmem.dll", "XMemAlloc", ServiceStatus::Partial);
|
||||
@@ -602,6 +771,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
platform_fixture::register(registry, &state);
|
||||
gdk_queue::register(registry, &state);
|
||||
modules::register(registry, &state);
|
||||
process::register(registry, &state);
|
||||
}
|
||||
|
||||
/// Implementations behind the generated adapters. A failure the guest can
|
||||
@@ -613,6 +783,9 @@ pub(crate) mod handlers {
|
||||
|
||||
type Outcome<T> = Result<T, ExitReason>;
|
||||
|
||||
/// The exit for a request the runtime does not model.
|
||||
const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
|
||||
|
||||
pub fn set_process_priority_boost(
|
||||
context: &mut ServiceContext<'_>,
|
||||
process: u64,
|
||||
@@ -664,7 +837,7 @@ pub(crate) mod handlers {
|
||||
}
|
||||
|
||||
pub fn get_current_thread_id(context: &mut ServiceContext<'_>) -> Outcome<u32> {
|
||||
Ok(context.state.thread_id)
|
||||
Ok(context.state.thread_id_of(context.teb))
|
||||
}
|
||||
|
||||
pub fn open_thread(
|
||||
@@ -674,21 +847,41 @@ pub(crate) mod handlers {
|
||||
id: u32,
|
||||
) -> Outcome<u64> {
|
||||
let state = context.state;
|
||||
if id != state.thread_id {
|
||||
let worker = state.worker_object(id);
|
||||
let main = id == state.thread_id && state.main_thread_alive();
|
||||
if !main && worker.is_none() {
|
||||
return state.fail(context.teb, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if inherit || access & !THREAD_SUPPORTED_RIGHTS != 0 {
|
||||
let supported = THREAD_SUPPORTED_RIGHTS
|
||||
| if worker.is_some() {
|
||||
threads::WORKER_RIGHTS
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if inherit || access & !supported != 0 {
|
||||
return state.fail(context.teb, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let mut thread = state.objects.lock().expect("guest object state");
|
||||
let Some(handle) = thread.next_handle() else {
|
||||
return state.fail(context.teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
thread.insert_handle(handle, GuestObject::Thread(access));
|
||||
let object = match worker {
|
||||
Some(state) => GuestObject::Waitable { state, access },
|
||||
None => GuestObject::Thread(access),
|
||||
};
|
||||
thread.insert_handle(handle, object);
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
pub fn get_thread_priority(context: &mut ServiceContext<'_>, handle: u64) -> Outcome<i32> {
|
||||
// Only the main thread has a priority; a worker must not change it.
|
||||
if handle == CURRENT_THREAD && context.state.current_worker(context.teb).is_some() {
|
||||
return context.state.fail(
|
||||
context.teb,
|
||||
ERROR_NOT_SUPPORTED,
|
||||
THREAD_PRIORITY_ERROR_RETURN as i32,
|
||||
);
|
||||
}
|
||||
let thread = context.state.objects.lock().expect("guest object state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
|
||||
return context
|
||||
@@ -703,6 +896,10 @@ pub(crate) mod handlers {
|
||||
handle: u64,
|
||||
priority: i32,
|
||||
) -> Outcome<bool> {
|
||||
// Only the main thread has a priority; a worker must not change it.
|
||||
if handle == CURRENT_THREAD && context.state.current_worker(context.teb).is_some() {
|
||||
return context.state.fail(context.teb, ERROR_NOT_SUPPORTED, false);
|
||||
}
|
||||
let state = context.state;
|
||||
let mut thread = state.objects.lock().expect("guest object state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_SET_RIGHTS) {
|
||||
@@ -741,6 +938,132 @@ pub(crate) mod handlers {
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
}
|
||||
|
||||
// Streams, files and formatted output (#400, #402). `crt_streams.rs` and
|
||||
// `crt_files.rs` hold the rules; a failure that has an errno value sets it
|
||||
// here. The stream state is always locked before the object state.
|
||||
|
||||
fn or_errno<T>(
|
||||
context: &mut ServiceContext<'_>,
|
||||
outcome: crt_streams::Outcome<T>,
|
||||
) -> Outcome<T> {
|
||||
match outcome? {
|
||||
Ok(value) => Ok(value),
|
||||
Err(crt_streams::Failed(value, errno)) => {
|
||||
crt::set_errno(context.memory, context.teb, errno)?;
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn standard_stream(context: &mut ServiceContext<'_>, index: u32) -> Outcome<u64> {
|
||||
context.state.crt_streams().file(context.memory, index)
|
||||
}
|
||||
|
||||
pub fn vfprintf(
|
||||
context: &mut ServiceContext<'_>,
|
||||
options: u64,
|
||||
stream: u64,
|
||||
format: u64,
|
||||
locale: u64,
|
||||
arguments: u64,
|
||||
) -> Outcome<i32> {
|
||||
let outcome = {
|
||||
let mut streams = context.state.crt_streams();
|
||||
let mut drive = context.state.objects.lock().expect("guest object state");
|
||||
streams.print(
|
||||
context.memory,
|
||||
&mut drive,
|
||||
options,
|
||||
stream,
|
||||
format,
|
||||
locale,
|
||||
arguments,
|
||||
)
|
||||
};
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fwrite(
|
||||
context: &mut ServiceContext<'_>,
|
||||
buffer: u64,
|
||||
size: u64,
|
||||
count: u64,
|
||||
stream: u64,
|
||||
) -> Outcome<u64> {
|
||||
let outcome = {
|
||||
let mut streams = context.state.crt_streams();
|
||||
let mut drive = context.state.objects.lock().expect("guest object state");
|
||||
streams.write_items(context.memory, &mut drive, buffer, size, count, stream)
|
||||
};
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fputs(context: &mut ServiceContext<'_>, text: u64, stream: u64) -> Outcome<i32> {
|
||||
let outcome = {
|
||||
let mut streams = context.state.crt_streams();
|
||||
let mut drive = context.state.objects.lock().expect("guest object state");
|
||||
streams.put_string(context.memory, &mut drive, text, stream)
|
||||
};
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fflush(context: &mut ServiceContext<'_>, stream: u64) -> Outcome<i32> {
|
||||
context.state.crt_streams().flush(stream)
|
||||
}
|
||||
|
||||
pub fn setvbuf(
|
||||
context: &mut ServiceContext<'_>,
|
||||
stream: u64,
|
||||
_buffer: u64,
|
||||
mode: i32,
|
||||
size: u64,
|
||||
) -> Outcome<i32> {
|
||||
let outcome = context.state.crt_streams().set_buffer(stream, mode, size);
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fopen(context: &mut ServiceContext<'_>, name: u64, mode: u64) -> Outcome<u64> {
|
||||
let outcome = {
|
||||
let mut streams = context.state.crt_streams();
|
||||
let mut drive = context.state.objects.lock().expect("guest object state");
|
||||
streams.open(context.memory, &mut drive, name, mode)
|
||||
};
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fclose(context: &mut ServiceContext<'_>, stream: u64) -> Outcome<i32> {
|
||||
let outcome = context.state.crt_streams().close(context.memory, stream);
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fgets(
|
||||
context: &mut ServiceContext<'_>,
|
||||
buffer: u64,
|
||||
count: i32,
|
||||
stream: u64,
|
||||
) -> Outcome<u64> {
|
||||
let outcome = {
|
||||
let mut streams = context.state.crt_streams();
|
||||
let drive = context.state.objects.lock().expect("guest object state");
|
||||
streams.get_line(context.memory, &drive, buffer, count, stream)
|
||||
};
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn perror(context: &mut ServiceContext<'_>, message: u64) -> Outcome<()> {
|
||||
let address = context
|
||||
.memory
|
||||
.crt_errno_address(context.teb)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
let errno = context
|
||||
.memory
|
||||
.read_u32(address)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
let mut streams = context.state.crt_streams();
|
||||
let mut drive = context.state.objects.lock().expect("guest object state");
|
||||
streams.report(context.memory, &mut drive, message, errno)
|
||||
}
|
||||
|
||||
pub fn get_last_error(context: &mut ServiceContext<'_>) -> Outcome<u32> {
|
||||
Ok(context.state.last_error(context.teb))
|
||||
}
|
||||
@@ -750,6 +1073,38 @@ pub(crate) mod handlers {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// What a hosted C program's startup code hands to `main` (#392).
|
||||
// `crt_arguments.rs` says what is documented, inferred and Xenora's choice.
|
||||
|
||||
pub fn argc_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
|
||||
let mut arguments = context.state.crt_arguments();
|
||||
arguments.address(context.memory, crt_arguments::Variable::Argc)
|
||||
}
|
||||
|
||||
pub fn argv_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
|
||||
let mut arguments = context.state.crt_arguments();
|
||||
arguments.address(context.memory, crt_arguments::Variable::Argv)
|
||||
}
|
||||
|
||||
pub fn environ_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
|
||||
let mut arguments = context.state.crt_arguments();
|
||||
arguments.address(context.memory, crt_arguments::Variable::Environ)
|
||||
}
|
||||
|
||||
pub fn configure_narrow_argv(context: &mut ServiceContext<'_>, mode: i32) -> Outcome<i32> {
|
||||
context
|
||||
.state
|
||||
.crt_arguments()
|
||||
.configure(context.memory, mode)
|
||||
}
|
||||
|
||||
pub fn initialize_narrow_environment(context: &mut ServiceContext<'_>) -> Outcome<i32> {
|
||||
context
|
||||
.state
|
||||
.crt_arguments()
|
||||
.initialize_environment(context.memory)
|
||||
}
|
||||
|
||||
pub fn virtual_alloc(
|
||||
context: &mut ServiceContext<'_>,
|
||||
requested: u64,
|
||||
@@ -813,6 +1168,42 @@ pub(crate) mod handlers {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// Stubs (#388). A program built with the mingw-w64 runtime imports these
|
||||
// three and does not call them on a normal run: the first two serve its
|
||||
// runtime pseudo-relocations and the third is the language handler Windows
|
||||
// calls while dispatching a structured exception. None is modelled, so a
|
||||
// call stops the guest with the runtime-limit fault. Returning a made-up
|
||||
// result would let the program run on with wrong state.
|
||||
|
||||
pub fn virtual_protect(
|
||||
_: &mut ServiceContext<'_>,
|
||||
_address: u64,
|
||||
_size: u64,
|
||||
_protect: u32,
|
||||
_old: OutPtr<4>,
|
||||
) -> Outcome<bool> {
|
||||
Err(RUNTIME_LIMIT)
|
||||
}
|
||||
|
||||
pub fn virtual_query(
|
||||
_: &mut ServiceContext<'_>,
|
||||
_address: u64,
|
||||
_information: OutPtr<48>,
|
||||
_length: u64,
|
||||
) -> Outcome<u64> {
|
||||
Err(RUNTIME_LIMIT)
|
||||
}
|
||||
|
||||
pub fn c_specific_handler(
|
||||
_: &mut ServiceContext<'_>,
|
||||
_record: u64,
|
||||
_frame: u64,
|
||||
_context: u64,
|
||||
_dispatcher: u64,
|
||||
) -> Outcome<i32> {
|
||||
Err(RUNTIME_LIMIT)
|
||||
}
|
||||
|
||||
/// The guest MXCSR is not visible to a service, so results use the default
|
||||
/// rounding and raise no guest flags; the registry marks them partial.
|
||||
const DEFAULT_MXCSR: u32 = crate::cpu::Mxcsr::RESET;
|
||||
@@ -835,4 +1226,85 @@ pub(crate) mod handlers {
|
||||
pub fn fabsf(_: &mut ServiceContext<'_>, x: Float32) -> Outcome<Float32> {
|
||||
Ok(Float32(x.0 & !(1 << 31)))
|
||||
}
|
||||
|
||||
// What a C program's startup code configures (#382). Each value is
|
||||
// recorded and returned; `crt_startup.rs` says what does not act on it.
|
||||
|
||||
pub fn set_app_type(context: &mut ServiceContext<'_>, kind: i32) -> Outcome<()> {
|
||||
context.state.crt_startup().set_app_type(kind);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_new_mode(context: &mut ServiceContext<'_>, mode: i32) -> Outcome<i32> {
|
||||
let previous = context.state.crt_startup().set_new_mode(mode);
|
||||
match previous {
|
||||
Some(previous) => Ok(previous),
|
||||
None => {
|
||||
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
|
||||
Ok(-1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn configure_thread_locale(context: &mut ServiceContext<'_>, request: i32) -> Outcome<i32> {
|
||||
let previous = context.state.crt_startup().configure_thread_locale(request);
|
||||
match previous {
|
||||
Some(previous) => Ok(previous),
|
||||
None => {
|
||||
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
|
||||
Ok(-1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_user_math_error(context: &mut ServiceContext<'_>, handler: u64) -> Outcome<()> {
|
||||
context.state.crt_startup().set_user_math_error(handler);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_invalid_parameter_handler(
|
||||
context: &mut ServiceContext<'_>,
|
||||
handler: u64,
|
||||
) -> Outcome<u64> {
|
||||
Ok(context
|
||||
.state
|
||||
.crt_startup()
|
||||
.set_invalid_parameter_handler(handler))
|
||||
}
|
||||
|
||||
pub fn file_mode_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
|
||||
context
|
||||
.state
|
||||
.crt_startup()
|
||||
.file_mode_address(context.memory, 0)
|
||||
}
|
||||
|
||||
pub fn commit_mode_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
|
||||
context
|
||||
.state
|
||||
.crt_startup()
|
||||
.file_mode_address(context.memory, 1)
|
||||
}
|
||||
|
||||
pub fn signal(context: &mut ServiceContext<'_>, signal: i32, handler: u64) -> Outcome<u64> {
|
||||
let previous = context.state.crt_startup().signal(signal, handler);
|
||||
match previous {
|
||||
Some(previous) => Ok(previous),
|
||||
None => {
|
||||
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
|
||||
// SIG_ERR is (void (*)(int))-1.
|
||||
Ok(u64::MAX)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_unhandled_exception_filter(
|
||||
context: &mut ServiceContext<'_>,
|
||||
filter: u64,
|
||||
) -> Outcome<u64> {
|
||||
Ok(context
|
||||
.state
|
||||
.crt_startup()
|
||||
.set_unhandled_exception_filter(filter))
|
||||
}
|
||||
}
|
||||
@@ -45,11 +45,38 @@ fn string_length(
|
||||
limit: u64,
|
||||
unit: StringUnit,
|
||||
) -> Result<u64, ExitReason> {
|
||||
const BLOCK: u64 = 256;
|
||||
let budget = SCAN_BUDGET / unit.width();
|
||||
for offset in 0..limit.min(budget) {
|
||||
if unit.read(memory, address, offset)? == 0 {
|
||||
return Ok(offset);
|
||||
let scan = limit.min(budget);
|
||||
let mut buffer = [0u8; 2 * BLOCK as usize];
|
||||
let mut offset = 0;
|
||||
while offset < scan {
|
||||
let count = BLOCK.min(scan - offset);
|
||||
let bytes = &mut buffer[..(count * unit.width()) as usize];
|
||||
// A block that crosses into unmapped or unreadable memory is scanned
|
||||
// one unit at a time, so a terminator before the boundary still ends
|
||||
// the scan and the fault reports the first inaccessible unit.
|
||||
let block = address
|
||||
.checked_add(offset * unit.width())
|
||||
.filter(|_| address != 0)
|
||||
.is_some_and(|start| memory.read_bytes(start, bytes).is_ok());
|
||||
for index in 0..count {
|
||||
let value = if block {
|
||||
match unit {
|
||||
StringUnit::Byte => u16::from(bytes[index as usize]),
|
||||
StringUnit::Wide => {
|
||||
let at = 2 * index as usize;
|
||||
u16::from_le_bytes([bytes[at], bytes[at + 1]])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
unit.read(memory, address, offset + index)?
|
||||
};
|
||||
if value == 0 {
|
||||
return Ok(offset + index);
|
||||
}
|
||||
}
|
||||
offset += count;
|
||||
}
|
||||
if limit <= budget {
|
||||
return Ok(limit);
|
||||
@@ -163,12 +190,14 @@ pub(super) fn register(registry: &mut ImportRegistry) {
|
||||
registry.alias(CRT_STRING_API, UCRT, symbol);
|
||||
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
// The mingw-w64 C runtime imports `memcpy` through this API set.
|
||||
registry.alias("api-ms-win-crt-private-l1-1-0.dll", UCRT, "memcpy");
|
||||
}
|
||||
|
||||
const ENOMEM: u32 = 12;
|
||||
const EINVAL: u32 = 22;
|
||||
pub(super) const EINVAL: u32 = 22;
|
||||
|
||||
fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> {
|
||||
pub(super) fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> {
|
||||
let address = memory
|
||||
.crt_errno_address(teb)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The arguments and environment a hosted C program's startup code hands to
|
||||
//! `main`.
|
||||
//!
|
||||
//! Documented: the global variables `__argc` (the argument count), `__argv` (a
|
||||
//! pointer to the array of argument strings) and `_environ` (a pointer to the
|
||||
//! array of environment strings), and ISO C's rule that a null pointer follows
|
||||
//! the last argument.
|
||||
//!
|
||||
//! Inferred: that `__p___argc`, `__p___argv` and `__p__environ` return the
|
||||
//! address of those variables, as the documented `__p__fmode` does for
|
||||
//! `_fmode`. Microsoft lists all five functions here only by name.
|
||||
//!
|
||||
//! Xenora's choice, because nothing public describes it: what
|
||||
//! `_configure_narrow_argv` and `_initialize_narrow_environment` do. The
|
||||
//! arguments come from the host, as bytes with no code page; wildcards are not
|
||||
//! expanded; and the environment table is empty.
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
|
||||
use std::fmt;
|
||||
|
||||
const EINVAL: i32 = 22;
|
||||
/// `_crt_argv_no_arguments`, `_crt_argv_unexpanded_arguments` and
|
||||
/// `_crt_argv_expanded_arguments` (corecrt_startup.h).
|
||||
const NO_ARGUMENTS: i32 = 0;
|
||||
const UNEXPANDED_ARGUMENTS: i32 = 1;
|
||||
const EXPANDED_ARGUMENTS: i32 = 2;
|
||||
/// Windows limits a command line to 32,767 characters including its
|
||||
/// terminator (`CreateProcess`). The same bound is applied here to the
|
||||
/// arguments with their terminators.
|
||||
pub const MAX_PROGRAM_ARGUMENT_BYTES: usize = 32_767;
|
||||
|
||||
/// Why [`super::ServicesState::set_program_arguments`] refused its input.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ProgramArgumentsError {
|
||||
/// An argument holds a NUL byte, which would end it early in the guest.
|
||||
ContainsNul,
|
||||
/// The arguments and their terminators exceed
|
||||
/// [`MAX_PROGRAM_ARGUMENT_BYTES`].
|
||||
TooLong,
|
||||
/// The guest has already built `__argv`; it would not see a change.
|
||||
AlreadyConfigured,
|
||||
}
|
||||
|
||||
impl fmt::Display for ProgramArgumentsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::ContainsNul => "a program argument contains a NUL byte",
|
||||
Self::TooLong => "the program arguments exceed 32,767 bytes",
|
||||
Self::AlreadyConfigured => "the guest has already configured its arguments",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ProgramArgumentsError {}
|
||||
|
||||
/// Which of the three guest variables a `__p_` function points at. The value
|
||||
/// is the variable's offset in their shared block.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Variable {
|
||||
Argc = 0,
|
||||
Argv = 8,
|
||||
Environ = 16,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct CrtArguments {
|
||||
/// What the host supplied, program name first.
|
||||
supplied: Option<Vec<Vec<u8>>>,
|
||||
/// Guest address of the block holding `__argc`, `__argv` and `_environ`.
|
||||
variables: Option<u64>,
|
||||
configured: bool,
|
||||
environment_initialized: bool,
|
||||
}
|
||||
|
||||
fn fault(error: MemoryError) -> ExitReason {
|
||||
ExitReason::MemoryFault(error)
|
||||
}
|
||||
|
||||
impl CrtArguments {
|
||||
pub(super) fn supply(&mut self, arguments: &[&str]) -> Result<(), ProgramArgumentsError> {
|
||||
if self.configured {
|
||||
return Err(ProgramArgumentsError::AlreadyConfigured);
|
||||
}
|
||||
if arguments.iter().any(|argument| argument.contains('\0')) {
|
||||
return Err(ProgramArgumentsError::ContainsNul);
|
||||
}
|
||||
let bytes: usize = arguments.iter().map(|argument| argument.len() + 1).sum();
|
||||
if bytes > MAX_PROGRAM_ARGUMENT_BYTES {
|
||||
return Err(ProgramArgumentsError::TooLong);
|
||||
}
|
||||
self.supplied = Some(
|
||||
arguments
|
||||
.iter()
|
||||
.map(|argument| argument.as_bytes().to_vec())
|
||||
.collect(),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Guest address of one of the three variables. They are allocated
|
||||
/// together from the process heap on first use, as zeros: no arguments,
|
||||
/// and null `__argv` and `_environ`.
|
||||
pub(super) fn address(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
variable: Variable,
|
||||
) -> Result<u64, ExitReason> {
|
||||
let base = match self.variables {
|
||||
Some(base) => base,
|
||||
None => {
|
||||
let base = memory
|
||||
.map_heap_allocation(PROCESS_HEAP, 24)
|
||||
.map_err(fault)?;
|
||||
self.variables = Some(base);
|
||||
base
|
||||
}
|
||||
};
|
||||
Ok(base + variable as u64)
|
||||
}
|
||||
|
||||
/// `_configure_narrow_argv`. Modes 1 and 2 build `__argc` and `__argv`
|
||||
/// once; a later call changes nothing. Mode 0 builds nothing. Any other
|
||||
/// mode is refused with `EINVAL`.
|
||||
pub(super) fn configure(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
mode: i32,
|
||||
) -> Result<i32, ExitReason> {
|
||||
match mode {
|
||||
NO_ARGUMENTS => return Ok(0),
|
||||
UNEXPANDED_ARGUMENTS | EXPANDED_ARGUMENTS => {}
|
||||
_ => return Ok(EINVAL),
|
||||
}
|
||||
if self.configured {
|
||||
return Ok(0);
|
||||
}
|
||||
// With no host input the program name is not available, and ISO C
|
||||
// then makes argv[0] the empty string.
|
||||
let default = [Vec::new()];
|
||||
let arguments = self.supplied.as_deref().unwrap_or(&default);
|
||||
let table_bytes = 8 * (arguments.len() + 1);
|
||||
let string_bytes: usize = arguments.iter().map(|argument| argument.len() + 1).sum();
|
||||
let table = memory
|
||||
.map_heap_allocation(PROCESS_HEAP, table_bytes + string_bytes)
|
||||
.map_err(fault)?;
|
||||
// The pointers first, then the strings. The block starts as zeros, so
|
||||
// the pointer after the last argument and every terminator are in place.
|
||||
let mut string = table + table_bytes as u64;
|
||||
for (index, argument) in arguments.iter().enumerate() {
|
||||
memory
|
||||
.write_u64(table + 8 * index as u64, string)
|
||||
.map_err(fault)?;
|
||||
memory.write_bytes(string, argument).map_err(fault)?;
|
||||
string += argument.len() as u64 + 1;
|
||||
}
|
||||
let count = arguments.len() as u32;
|
||||
let argc = self.address(memory, Variable::Argc)?;
|
||||
let argv = self.address(memory, Variable::Argv)?;
|
||||
memory.write_u32(argc, count).map_err(fault)?;
|
||||
memory.write_u64(argv, table).map_err(fault)?;
|
||||
self.configured = true;
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// `_initialize_narrow_environment`. Points `_environ` at an empty table,
|
||||
/// one null pointer, once.
|
||||
pub(super) fn initialize_environment(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<i32, ExitReason> {
|
||||
if !self.environment_initialized {
|
||||
let table = memory.map_heap_allocation(PROCESS_HEAP, 8).map_err(fault)?;
|
||||
let environ = self.address(memory, Variable::Environ)?;
|
||||
memory.write_u64(environ, table).map_err(fault)?;
|
||||
self.environment_initialized = true;
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
@@ -400,6 +400,57 @@ impl CallbackTask for ExitFunctions {
|
||||
}
|
||||
}
|
||||
|
||||
/// `exit`: calls the functions registered with `atexit` and `_crt_atexit`,
|
||||
/// most recently registered first, and then ends the guest process.
|
||||
///
|
||||
/// It takes one function at a time from the shared list. A function that is
|
||||
/// registered while `exit` runs is therefore called next, before the older
|
||||
/// ones that have not run yet, as ISO C requires (7.22.4.2, 7.22.4.4). A
|
||||
/// registered function that calls `exit` again, which ISO C leaves undefined,
|
||||
/// starts a second task on the same list: the remaining functions run once
|
||||
/// each and the process ends with the later status.
|
||||
struct Exit {
|
||||
state: Arc<ServicesState>,
|
||||
status: u32,
|
||||
}
|
||||
|
||||
impl Exit {
|
||||
fn next(&mut self) -> Result<CallbackStep, ExitReason> {
|
||||
let function = self
|
||||
.state
|
||||
.atexit
|
||||
.lock()
|
||||
.expect("guest atexit functions")
|
||||
.pop();
|
||||
match function {
|
||||
Some(entry) => Ok(CallbackStep::Call {
|
||||
entry,
|
||||
args: [0; 4],
|
||||
}),
|
||||
None => Err(ExitReason::ProcessExit(
|
||||
self.state.exit_process(self.status),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn start(mut self) -> Result<CallbackStart, ExitReason> {
|
||||
match self.next()? {
|
||||
CallbackStep::Call { entry, args } => Ok(CallbackStart::Call {
|
||||
task: Box::new(self),
|
||||
entry,
|
||||
args,
|
||||
}),
|
||||
CallbackStep::Return(value) => Ok(CallbackStart::Return(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CallbackTask for Exit {
|
||||
fn resume(&mut self, _: u64, _: u64, _: &mut GuestMemory) -> Result<CallbackStep, ExitReason> {
|
||||
self.next()
|
||||
}
|
||||
}
|
||||
|
||||
fn register_exit_tables(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register(UCRT, "_initialize_onexit_table", |args, _, mem| {
|
||||
let table = args.rcx;
|
||||
@@ -473,6 +524,24 @@ fn register_exit_tables(registry: &mut ImportRegistry, state: &Arc<ServicesState
|
||||
Ok(ExitFunctions { pending }.start())
|
||||
});
|
||||
|
||||
// exit does not return. It is partial: no stream is flushed, because
|
||||
// there are none, and thread-local destructors are not run.
|
||||
let s = Arc::clone(state);
|
||||
registry.register_callback_task(
|
||||
UCRT,
|
||||
"exit",
|
||||
ServiceStatus::Partial,
|
||||
move |args, _, _, _| {
|
||||
// The status is an int, the low half of the first argument.
|
||||
Exit {
|
||||
state: Arc::clone(&s),
|
||||
status: args.rcx as u32,
|
||||
}
|
||||
.start()
|
||||
},
|
||||
);
|
||||
registry.alias(CRT_RUNTIME_API, UCRT, "exit");
|
||||
|
||||
for symbol in [
|
||||
"_initialize_onexit_table",
|
||||
"_register_onexit_function",
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The C runtime's file streams: what `fopen` opens.
|
||||
//!
|
||||
//! A stream reads and writes a file on the in-memory `C:` drive that the
|
||||
//! handle services in `files.rs` also use, as the C runtime sits on Win32
|
||||
//! files on Windows. The rules are from the Microsoft Learn pages "fopen,
|
||||
//! _wfopen", "fclose, _fcloseall", "fgets, fgetws" and "perror, _wperror".
|
||||
//!
|
||||
//! Modes: `r`, `w` or `a`, then any of `+`, `b` and `t`. In text mode, which
|
||||
//! is the default as `_fmode` starts as `_O_TEXT`, "LF characters are
|
||||
//! translated to CR-LF combinations on output", "CR-LF combinations are
|
||||
//! translated into single line feeds on input", and "CTRL+Z is interpreted as
|
||||
//! an end-of-file character on input".
|
||||
//!
|
||||
//! Nothing is buffered: a write reaches the drive at once. There is no
|
||||
//! seeking, so the only positions are the start, the end, and wherever the
|
||||
//! last read or write left off.
|
||||
|
||||
use super::ObjectState;
|
||||
use super::files::DriveEntry;
|
||||
use crate::memory::{GuestMemory, PROCESS_HEAP};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// errno.h values.
|
||||
pub(super) const ENOENT: u32 = 2;
|
||||
pub(super) const EBADF: u32 = 9;
|
||||
pub(super) const ENOMEM: u32 = 12;
|
||||
pub(super) const EACCES: u32 = 13;
|
||||
pub(super) const EINVAL: u32 = 22;
|
||||
pub(super) const EMFILE: u32 = 24;
|
||||
pub(super) const ENOSPC: u32 = 28;
|
||||
|
||||
/// The most streams `fopen` keeps open at once.
|
||||
pub(super) const MAX_OPEN_STREAMS: usize = 64;
|
||||
/// `CTRL+Z`, which ends the input of a text-mode stream.
|
||||
const CTRL_Z: u8 = 0x1A;
|
||||
|
||||
/// The text `perror` prints for an `errno` value. The page gives the text for
|
||||
/// a missing file in its example; the others are the usual C library wording
|
||||
/// and are Xenora's choice.
|
||||
pub(super) fn error_text(errno: u32) -> &'static str {
|
||||
match errno {
|
||||
0 => "No error",
|
||||
ENOENT => "No such file or directory",
|
||||
EBADF => "Bad file descriptor",
|
||||
ENOMEM => "Not enough space",
|
||||
EACCES => "Permission denied",
|
||||
EINVAL => "Invalid argument",
|
||||
EMFILE => "Too many open files",
|
||||
ENOSPC => "No space left on device",
|
||||
_ => "Unknown error",
|
||||
}
|
||||
}
|
||||
|
||||
struct Mode {
|
||||
readable: bool,
|
||||
writable: bool,
|
||||
/// Every write goes to the end of the file.
|
||||
append: bool,
|
||||
/// The file must already exist.
|
||||
existing: bool,
|
||||
/// The file's contents are destroyed on opening.
|
||||
truncate: bool,
|
||||
text: bool,
|
||||
}
|
||||
|
||||
/// `r`, `w` or `a` first, then `+`, `b` and `t` in any order, each at most
|
||||
/// once and not both `b` and `t`. Anything else is not a mode this runtime
|
||||
/// opens, including the other characters the page lists.
|
||||
fn parse_mode(mode: &[u8]) -> Option<Mode> {
|
||||
let (&kind, rest) = mode.split_first()?;
|
||||
let (mut update, mut binary, mut text) = (false, false, false);
|
||||
for &byte in rest {
|
||||
let seen = match byte {
|
||||
b'+' => &mut update,
|
||||
b'b' => &mut binary,
|
||||
b't' => &mut text,
|
||||
_ => return None,
|
||||
};
|
||||
if std::mem::replace(seen, true) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if binary && text {
|
||||
return None;
|
||||
}
|
||||
let (readable, writable, append, existing, truncate) = match kind {
|
||||
b'r' => (true, update, false, true, false),
|
||||
b'w' => (update, true, false, false, true),
|
||||
b'a' => (update, true, true, false, false),
|
||||
_ => return None,
|
||||
};
|
||||
Some(Mode {
|
||||
readable,
|
||||
writable,
|
||||
append,
|
||||
existing,
|
||||
truncate,
|
||||
text: !binary,
|
||||
})
|
||||
}
|
||||
|
||||
struct FileStream {
|
||||
path: String,
|
||||
/// Where the next read, or the next write of a stream that does not
|
||||
/// append, takes place.
|
||||
position: u64,
|
||||
readable: bool,
|
||||
writable: bool,
|
||||
append: bool,
|
||||
text: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct FileStreams {
|
||||
/// Open streams by the guest address of their `FILE` object.
|
||||
open: BTreeMap<u64, FileStream>,
|
||||
}
|
||||
|
||||
impl FileStreams {
|
||||
pub(super) fn contains(&self, file: u64) -> bool {
|
||||
self.open.contains_key(&file)
|
||||
}
|
||||
|
||||
/// `fopen`. Returns the guest address of a new `FILE` object, or the
|
||||
/// `errno` value of the failure.
|
||||
pub(super) fn open(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
drive: &mut ObjectState,
|
||||
name: &[u8],
|
||||
mode: &[u8],
|
||||
) -> Result<u64, u32> {
|
||||
// An empty name or mode is an invalid parameter: neither is a mode
|
||||
// nor a name the drive accepts. Xenora's choice: so is any other mode
|
||||
// it does not open and any other name the drive rejects.
|
||||
let mode = parse_mode(mode).ok_or(EINVAL)?;
|
||||
let path = ObjectState::drive_path(name).ok_or(EINVAL)?;
|
||||
if self.open.len() >= MAX_OPEN_STREAMS {
|
||||
return Err(EMFILE);
|
||||
}
|
||||
let create = match drive.drive_entry(&path) {
|
||||
DriveEntry::Directory => return Err(EACCES),
|
||||
DriveEntry::File => false,
|
||||
DriveEntry::Missing { .. } if mode.existing => return Err(ENOENT),
|
||||
DriveEntry::Missing { parent: false } => return Err(ENOENT),
|
||||
DriveEntry::Missing { parent: true } => true,
|
||||
};
|
||||
// The FILE object is allocated before the drive is touched, so a
|
||||
// failed fopen neither creates a file nor destroys the contents of
|
||||
// one.
|
||||
let file = memory
|
||||
.map_heap_allocation(PROCESS_HEAP, 8)
|
||||
.map_err(|_| ENOMEM)?;
|
||||
if create && !drive.drive_create(&path) {
|
||||
memory.release_heap_allocation(PROCESS_HEAP, file);
|
||||
return Err(ENOSPC);
|
||||
}
|
||||
if mode.truncate {
|
||||
drive.drive_truncate(&path);
|
||||
}
|
||||
self.open.insert(
|
||||
file,
|
||||
FileStream {
|
||||
path,
|
||||
position: 0,
|
||||
readable: mode.readable,
|
||||
writable: mode.writable,
|
||||
append: mode.append,
|
||||
text: mode.text,
|
||||
},
|
||||
);
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// `fclose`. False when `file` is not an open stream.
|
||||
pub(super) fn close(&mut self, memory: &mut GuestMemory, file: u64) -> bool {
|
||||
if self.open.remove(&file).is_none() {
|
||||
return false;
|
||||
}
|
||||
memory.release_heap_allocation(PROCESS_HEAP, file);
|
||||
true
|
||||
}
|
||||
|
||||
/// Write to an open stream, in its mode. Returns the `errno` value of a
|
||||
/// failure, with nothing written.
|
||||
pub(super) fn write(
|
||||
&mut self,
|
||||
drive: &mut ObjectState,
|
||||
file: u64,
|
||||
bytes: &[u8],
|
||||
) -> Result<(), u32> {
|
||||
let stream = self.open.get_mut(&file).ok_or(EBADF)?;
|
||||
if !stream.writable {
|
||||
return Err(EBADF);
|
||||
}
|
||||
let stored: Vec<u8> = if stream.text {
|
||||
let mut stored = Vec::with_capacity(bytes.len());
|
||||
for &byte in bytes {
|
||||
if byte == b'\n' {
|
||||
stored.push(b'\r');
|
||||
}
|
||||
stored.push(byte);
|
||||
}
|
||||
stored
|
||||
} else {
|
||||
bytes.to_vec()
|
||||
};
|
||||
// "All write operations occur at the end of the file."
|
||||
if stream.append {
|
||||
stream.position = drive.drive_file(&stream.path).ok_or(EBADF)?.len() as u64;
|
||||
}
|
||||
match drive.drive_write(&stream.path, stream.position, &stored) {
|
||||
Some(true) => {
|
||||
stream.position += stored.len() as u64;
|
||||
Ok(())
|
||||
}
|
||||
Some(false) => Err(ENOSPC),
|
||||
// The file was deleted or moved while the stream was open.
|
||||
None => Err(EBADF),
|
||||
}
|
||||
}
|
||||
|
||||
/// `fgets`: up to `limit` characters, ending after a newline. `None` is
|
||||
/// end of file with nothing read.
|
||||
pub(super) fn read_line(
|
||||
&mut self,
|
||||
drive: &ObjectState,
|
||||
file: u64,
|
||||
limit: usize,
|
||||
) -> Result<Option<Vec<u8>>, u32> {
|
||||
let stream = self.open.get_mut(&file).ok_or(EBADF)?;
|
||||
if !stream.readable {
|
||||
return Err(EBADF);
|
||||
}
|
||||
let data = drive.drive_file(&stream.path).ok_or(EBADF)?;
|
||||
let mut at = usize::try_from(stream.position).map_or(data.len(), |at| at.min(data.len()));
|
||||
let ended = at == data.len() || (stream.text && data[at] == CTRL_Z);
|
||||
if limit == 0 {
|
||||
// No room to read a character: an empty line unless the stream
|
||||
// has ended.
|
||||
return Ok((!ended).then(Vec::new));
|
||||
}
|
||||
let mut line = Vec::new();
|
||||
while line.len() < limit && at < data.len() {
|
||||
let mut byte = data[at];
|
||||
if stream.text {
|
||||
if byte == CTRL_Z {
|
||||
break;
|
||||
}
|
||||
if byte == b'\r' && data.get(at + 1) == Some(&b'\n') {
|
||||
at += 1;
|
||||
byte = b'\n';
|
||||
}
|
||||
}
|
||||
at += 1;
|
||||
line.push(byte);
|
||||
if byte == b'\n' {
|
||||
break;
|
||||
}
|
||||
}
|
||||
stream.position = at as u64;
|
||||
Ok((!line.is_empty()).then_some(line))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parse_mode;
|
||||
|
||||
/// The six access types of the `fopen` page, each alone and with `t` or
|
||||
/// `b`, and what the page says of each.
|
||||
#[test]
|
||||
fn modes_follow_the_fopen_page() {
|
||||
// (mode, readable, writable, append, must exist, truncates)
|
||||
for (mode, readable, writable, append, existing, truncate) in [
|
||||
("r", true, false, false, true, false),
|
||||
("w", false, true, false, false, true),
|
||||
("a", false, true, true, false, false),
|
||||
("r+", true, true, false, true, false),
|
||||
("w+", true, true, false, false, true),
|
||||
("a+", true, true, true, false, false),
|
||||
] {
|
||||
for (suffix, text) in [("", true), ("t", true), ("b", false)] {
|
||||
let mut spellings = vec![format!("{mode}{suffix}")];
|
||||
if mode.len() == 2 && !suffix.is_empty() {
|
||||
// "rb+" is the same mode as "r+b".
|
||||
spellings.push(format!("{}{suffix}+", &mode[..1]));
|
||||
}
|
||||
for spelling in spellings {
|
||||
let parsed = parse_mode(spelling.as_bytes())
|
||||
.unwrap_or_else(|| panic!("{spelling} is a mode"));
|
||||
assert_eq!(
|
||||
(
|
||||
parsed.readable,
|
||||
parsed.writable,
|
||||
parsed.append,
|
||||
parsed.existing,
|
||||
parsed.truncate,
|
||||
parsed.text
|
||||
),
|
||||
(readable, writable, append, existing, truncate, text),
|
||||
"{spelling}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// "If t or b is prefixed to the argument, the function fails." The
|
||||
// other mode characters the page lists are not opened here, and
|
||||
// neither is anything that is not a mode.
|
||||
for mode in [
|
||||
"",
|
||||
"t",
|
||||
"b",
|
||||
"tr",
|
||||
"br",
|
||||
"+r",
|
||||
"x",
|
||||
"rw",
|
||||
"wr",
|
||||
"ra",
|
||||
"rbt",
|
||||
"rtb",
|
||||
"r++",
|
||||
"rbb",
|
||||
"wtt",
|
||||
"wx",
|
||||
"w+x",
|
||||
"rc",
|
||||
"rn",
|
||||
"rN",
|
||||
"rS",
|
||||
"rR",
|
||||
"wT",
|
||||
"wD",
|
||||
"r,ccs=UTF-8",
|
||||
"R",
|
||||
"W",
|
||||
"r ",
|
||||
" r",
|
||||
"rb+t",
|
||||
] {
|
||||
assert!(parse_mode(mode.as_bytes()).is_none(), "{mode:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,743 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Formatting for the narrow `printf` family.
|
||||
//!
|
||||
//! The rules are from Microsoft's "Format specification syntax: printf and
|
||||
//! wprintf functions" and, where that page is silent, from ISO C 7.21.6.1. A
|
||||
//! conversion specification is `%[flags][width][.precision][size]type`.
|
||||
//!
|
||||
//! Supported: the flags `-`, `+`, space, `#` and `0`; a width and a precision
|
||||
//! given as digits or as `*`; the size prefixes `hh`, `h`, `l`, `ll`, `j`,
|
||||
//! `z`, `t`, `I`, `I32` and `I64`; and the types `d`, `i`, `u`, `o`, `x`, `X`,
|
||||
//! `c`, `s`, `p` and `%%`.
|
||||
//!
|
||||
//! Refused as invalid, as Windows does by default: `%n`, and a character that
|
||||
//! has no meaning as a type. Refused as not modelled, so that nothing is
|
||||
//! printed wrongly: the floating-point types, and wide characters and strings.
|
||||
//!
|
||||
//! Where the documentation leaves a choice, the choice made here is marked
|
||||
//! "Xenora's choice" at the code that makes it.
|
||||
|
||||
use crate::memory::MemoryError;
|
||||
|
||||
/// The most one call may produce, and the largest width or precision.
|
||||
pub(super) const MAX_OUTPUT: usize = 1 << 20;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum FormatError {
|
||||
/// The format is not valid: `%n`, an unknown type, a size prefix that
|
||||
/// does not apply to its type, or a string that ends inside a
|
||||
/// specification.
|
||||
Invalid,
|
||||
/// The format is valid and asks for something that is not modelled.
|
||||
Unsupported,
|
||||
/// The output, a width or a precision exceeds [`MAX_OUTPUT`].
|
||||
TooLong,
|
||||
/// Reading an argument or a string failed.
|
||||
Fault(MemoryError),
|
||||
}
|
||||
|
||||
/// Where the arguments and strings of one call come from.
|
||||
pub(super) trait Source {
|
||||
/// The next 8-byte argument slot.
|
||||
fn argument(&mut self) -> Result<u64, MemoryError>;
|
||||
/// The bytes of the string at `address` up to its terminator, or the first
|
||||
/// `limit` of them. Never called with a null address.
|
||||
fn string(&mut self, address: u64, limit: usize) -> Result<Vec<u8>, MemoryError>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Size {
|
||||
None,
|
||||
Char,
|
||||
Short,
|
||||
/// `l`: a `long`, which is 32 bits on Windows, or a wide character or
|
||||
/// string.
|
||||
Long,
|
||||
/// `ll`, `j`, `z`, `t`, `I` and `I64`: 64 bits on a 64-bit system.
|
||||
Quad,
|
||||
/// `I32`.
|
||||
Int32,
|
||||
/// `w`: a wide character or string.
|
||||
Wide,
|
||||
/// `L`: a `long double`.
|
||||
LongDouble,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Flags {
|
||||
left: bool,
|
||||
plus: bool,
|
||||
space: bool,
|
||||
alternate: bool,
|
||||
zero: bool,
|
||||
}
|
||||
|
||||
struct Spec {
|
||||
flags: Flags,
|
||||
width: usize,
|
||||
precision: Option<usize>,
|
||||
size: Size,
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
format: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.format.get(self.at).copied()
|
||||
}
|
||||
|
||||
fn take(&mut self, byte: u8) -> bool {
|
||||
let found = self.peek() == Some(byte);
|
||||
self.at += usize::from(found);
|
||||
found
|
||||
}
|
||||
|
||||
/// Decimal digits, possibly none.
|
||||
fn number(&mut self) -> Result<usize, FormatError> {
|
||||
let mut value = 0usize;
|
||||
while let Some(digit @ b'0'..=b'9') = self.peek() {
|
||||
value = value * 10 + usize::from(digit - b'0');
|
||||
if value > MAX_OUTPUT {
|
||||
return Err(FormatError::TooLong);
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn size(&mut self) -> Size {
|
||||
if self.take(b'h') {
|
||||
return if self.take(b'h') {
|
||||
Size::Char
|
||||
} else {
|
||||
Size::Short
|
||||
};
|
||||
}
|
||||
if self.take(b'l') {
|
||||
return if self.take(b'l') {
|
||||
Size::Quad
|
||||
} else {
|
||||
Size::Long
|
||||
};
|
||||
}
|
||||
if self.take(b'I') {
|
||||
let rest = &self.format[self.at..];
|
||||
if rest.starts_with(b"64") {
|
||||
self.at += 2;
|
||||
return Size::Quad;
|
||||
}
|
||||
if rest.starts_with(b"32") {
|
||||
self.at += 2;
|
||||
return Size::Int32;
|
||||
}
|
||||
// `I` alone is ptrdiff_t or size_t.
|
||||
return Size::Quad;
|
||||
}
|
||||
match self.peek() {
|
||||
Some(b'j' | b'z' | b't') => {
|
||||
self.at += 1;
|
||||
Size::Quad
|
||||
}
|
||||
Some(b'w') => {
|
||||
self.at += 1;
|
||||
Size::Wide
|
||||
}
|
||||
Some(b'L') => {
|
||||
self.at += 1;
|
||||
Size::LongDouble
|
||||
}
|
||||
_ => Size::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An `int` argument is the low half of its slot.
|
||||
fn int(slot: u64) -> i32 {
|
||||
slot as u32 as i32
|
||||
}
|
||||
|
||||
fn bounded(value: usize) -> Result<usize, FormatError> {
|
||||
if value > MAX_OUTPUT {
|
||||
Err(FormatError::TooLong)
|
||||
} else {
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pad `body` to the field width. `zeros` puts the padding after the first
|
||||
/// `lead` bytes (a sign or prefix) as zeros instead of before them as blanks.
|
||||
fn pad(out: &mut Vec<u8>, spec: &Spec, lead: usize, body: &[u8], zeros: bool) {
|
||||
let fill = spec.width.saturating_sub(body.len());
|
||||
if spec.flags.left {
|
||||
out.extend_from_slice(body);
|
||||
out.resize(out.len() + fill, b' ');
|
||||
} else if zeros {
|
||||
out.extend_from_slice(&body[..lead]);
|
||||
out.resize(out.len() + fill, b'0');
|
||||
out.extend_from_slice(&body[lead..]);
|
||||
} else {
|
||||
out.resize(out.len() + fill, b' ');
|
||||
out.extend_from_slice(body);
|
||||
}
|
||||
}
|
||||
|
||||
fn digits(mut value: u64, base: u64, upper: bool) -> Vec<u8> {
|
||||
let table: &[u8; 16] = if upper {
|
||||
b"0123456789ABCDEF"
|
||||
} else {
|
||||
b"0123456789abcdef"
|
||||
};
|
||||
let mut reversed = Vec::new();
|
||||
loop {
|
||||
reversed.push(table[(value % base) as usize]);
|
||||
value /= base;
|
||||
if value == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
reversed.reverse();
|
||||
reversed
|
||||
}
|
||||
|
||||
fn integer(out: &mut Vec<u8>, spec: &Spec, kind: u8, slot: u64) -> Result<(), FormatError> {
|
||||
let signed = matches!(kind, b'd' | b'i');
|
||||
// Without a size prefix an integer argument is a 32-bit int, and so is a
|
||||
// long. `hh` and `h` arguments arrive as an int and are converted back.
|
||||
let (negative, magnitude) = if signed {
|
||||
let value = match spec.size {
|
||||
Size::None | Size::Long | Size::Int32 => i64::from(int(slot)),
|
||||
Size::Char => i64::from(slot as u8 as i8),
|
||||
Size::Short => i64::from(slot as u16 as i16),
|
||||
Size::Quad => slot as i64,
|
||||
Size::Wide | Size::LongDouble => return Err(FormatError::Invalid),
|
||||
};
|
||||
(value < 0, value.unsigned_abs())
|
||||
} else {
|
||||
let value = match spec.size {
|
||||
Size::None | Size::Long | Size::Int32 => u64::from(slot as u32),
|
||||
Size::Char => u64::from(slot as u8),
|
||||
Size::Short => u64::from(slot as u16),
|
||||
Size::Quad => slot,
|
||||
Size::Wide | Size::LongDouble => return Err(FormatError::Invalid),
|
||||
};
|
||||
(false, value)
|
||||
};
|
||||
|
||||
let (base, upper) = match kind {
|
||||
b'o' => (8, false),
|
||||
b'x' => (16, false),
|
||||
b'X' => (16, true),
|
||||
_ => (10, false),
|
||||
};
|
||||
// The precision is the minimum number of digits, 1 by default. A zero
|
||||
// value with a precision of zero has no digits.
|
||||
let precision = spec.precision.unwrap_or(1);
|
||||
let mut number = if magnitude == 0 && precision == 0 {
|
||||
Vec::new()
|
||||
} else {
|
||||
digits(magnitude, base, upper)
|
||||
};
|
||||
if number.len() < precision {
|
||||
let mut padded = vec![b'0'; precision - number.len()];
|
||||
padded.append(&mut number);
|
||||
number = padded;
|
||||
}
|
||||
|
||||
let mut body = Vec::new();
|
||||
if signed {
|
||||
// The blank is ignored when both it and + appear.
|
||||
if negative {
|
||||
body.push(b'-');
|
||||
} else if spec.flags.plus {
|
||||
body.push(b'+');
|
||||
} else if spec.flags.space {
|
||||
body.push(b' ');
|
||||
}
|
||||
}
|
||||
if spec.flags.alternate {
|
||||
match kind {
|
||||
// ISO C: the precision grows, only if it must, so that the first
|
||||
// digit is a zero. A zero value with a precision of zero is "0".
|
||||
b'o' if number.first() != Some(&b'0') => body.push(b'0'),
|
||||
b'x' if magnitude != 0 => body.extend_from_slice(b"0x"),
|
||||
b'X' if magnitude != 0 => body.extend_from_slice(b"0X"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let lead = body.len();
|
||||
body.append(&mut number);
|
||||
bounded(body.len().max(spec.width))?;
|
||||
// 0 is ignored with - and when an integer has a precision.
|
||||
let zeros = spec.flags.zero && spec.precision.is_none();
|
||||
pad(out, spec, lead, &body, zeros);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Format `format` with the arguments and strings `source` supplies. Returns
|
||||
/// the bytes to write; their number is the function result of the `printf`
|
||||
/// family.
|
||||
pub(super) fn format(format: &[u8], source: &mut dyn Source) -> Result<Vec<u8>, FormatError> {
|
||||
let mut out = Vec::new();
|
||||
let mut parser = Parser { format, at: 0 };
|
||||
while let Some(byte) = parser.peek() {
|
||||
parser.at += 1;
|
||||
if byte != b'%' {
|
||||
out.push(byte);
|
||||
bounded(out.len())?;
|
||||
continue;
|
||||
}
|
||||
if parser.take(b'%') {
|
||||
out.push(b'%');
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut flags = Flags::default();
|
||||
loop {
|
||||
match parser.peek() {
|
||||
Some(b'-') => flags.left = true,
|
||||
Some(b'+') => flags.plus = true,
|
||||
Some(b' ') => flags.space = true,
|
||||
Some(b'#') => flags.alternate = true,
|
||||
Some(b'0') => flags.zero = true,
|
||||
_ => break,
|
||||
}
|
||||
parser.at += 1;
|
||||
}
|
||||
let width = if parser.take(b'*') {
|
||||
// ISO C: a negative width is the - flag and a positive width.
|
||||
let value = int(source.argument().map_err(FormatError::Fault)?);
|
||||
flags.left |= value < 0;
|
||||
bounded(value.unsigned_abs() as usize)?
|
||||
} else {
|
||||
parser.number()?
|
||||
};
|
||||
let precision = if !parser.take(b'.') {
|
||||
None
|
||||
} else if parser.take(b'*') {
|
||||
// ISO C: a negative precision is taken as if it were omitted.
|
||||
let value = int(source.argument().map_err(FormatError::Fault)?);
|
||||
match usize::try_from(value) {
|
||||
Ok(value) => Some(bounded(value)?),
|
||||
Err(_) => None,
|
||||
}
|
||||
} else {
|
||||
Some(parser.number()?)
|
||||
};
|
||||
let size = parser.size();
|
||||
let spec = Spec {
|
||||
flags,
|
||||
width,
|
||||
precision,
|
||||
size,
|
||||
};
|
||||
let kind = parser.peek().ok_or(FormatError::Invalid)?;
|
||||
parser.at += 1;
|
||||
|
||||
match kind {
|
||||
b'd' | b'i' | b'u' | b'o' | b'x' | b'X' => {
|
||||
let slot = source.argument().map_err(FormatError::Fault)?;
|
||||
integer(&mut out, &spec, kind, slot)?;
|
||||
}
|
||||
b'c' => {
|
||||
match spec.size {
|
||||
Size::None | Size::Short => {}
|
||||
Size::Long | Size::Wide => return Err(FormatError::Unsupported),
|
||||
_ => return Err(FormatError::Invalid),
|
||||
}
|
||||
// The precision has no effect on a character.
|
||||
let slot = source.argument().map_err(FormatError::Fault)?;
|
||||
// Xenora's choice: 0 pads any type, as the page's description
|
||||
// of the flag is not limited to numbers.
|
||||
pad(&mut out, &spec, 0, &[slot as u8], spec.flags.zero);
|
||||
}
|
||||
b's' => {
|
||||
match spec.size {
|
||||
Size::None | Size::Short => {}
|
||||
Size::Long | Size::Wide => return Err(FormatError::Unsupported),
|
||||
_ => return Err(FormatError::Invalid),
|
||||
}
|
||||
let address = source.argument().map_err(FormatError::Fault)?;
|
||||
let limit = spec.precision.unwrap_or(MAX_OUTPUT + 1);
|
||||
let text = if address == 0 {
|
||||
// Xenora's choice: the precision also limits "(null)".
|
||||
let null = b"(null)";
|
||||
null[..null.len().min(limit)].to_vec()
|
||||
} else {
|
||||
source.string(address, limit).map_err(FormatError::Fault)?
|
||||
};
|
||||
bounded(text.len().max(spec.width))?;
|
||||
pad(&mut out, &spec, 0, &text, spec.flags.zero);
|
||||
}
|
||||
b'p' => {
|
||||
if spec.size != Size::None {
|
||||
return Err(FormatError::Invalid);
|
||||
}
|
||||
let slot = source.argument().map_err(FormatError::Fault)?;
|
||||
// "An address in hexadecimal digits" is all the page says.
|
||||
// Xenora's choice: sixteen upper-case digits, and no other
|
||||
// flag or precision has an effect.
|
||||
let text = format!("{slot:016X}");
|
||||
pad(&mut out, &spec, 0, text.as_bytes(), false);
|
||||
}
|
||||
// Wide characters and strings, floating point and the counted
|
||||
// string structures are valid and not modelled.
|
||||
b'C' | b'S' | b'Z' | b'e' | b'E' | b'f' | b'F' | b'g' | b'G' | b'a' | b'A' => {
|
||||
return Err(FormatError::Unsupported);
|
||||
}
|
||||
// %n is disabled by default, and any other character has no
|
||||
// meaning as a type.
|
||||
_ => return Err(FormatError::Invalid),
|
||||
}
|
||||
bounded(out.len())?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{FormatError, MAX_OUTPUT, Source, format};
|
||||
use crate::memory::MemoryError;
|
||||
|
||||
/// A string argument is the address `STRINGS + 0x100 * index`.
|
||||
const STRINGS: u64 = 0x1000_0000;
|
||||
|
||||
struct Call {
|
||||
slots: Vec<u64>,
|
||||
strings: Vec<Vec<u8>>,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
impl Source for Call {
|
||||
fn argument(&mut self) -> Result<u64, MemoryError> {
|
||||
let slot = self.slots.get(self.next).copied();
|
||||
self.next += 1;
|
||||
slot.ok_or(MemoryError::UnmappedAddress(self.next as u64))
|
||||
}
|
||||
|
||||
fn string(&mut self, address: u64, limit: usize) -> Result<Vec<u8>, MemoryError> {
|
||||
let index = ((address - STRINGS) / 0x100) as usize;
|
||||
let text = self
|
||||
.strings
|
||||
.get(index)
|
||||
.ok_or(MemoryError::UnmappedAddress(address))?;
|
||||
Ok(text[..text.len().min(limit)].to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
fn run(text: &str, slots: &[u64], strings: &[&str]) -> Result<String, FormatError> {
|
||||
let mut call = Call {
|
||||
slots: slots.to_vec(),
|
||||
strings: strings
|
||||
.iter()
|
||||
.map(|text| text.as_bytes().to_vec())
|
||||
.collect(),
|
||||
next: 0,
|
||||
};
|
||||
let bytes = format(text.as_bytes(), &mut call)?;
|
||||
assert_eq!(call.next, slots.len(), "{text}: arguments consumed");
|
||||
Ok(String::from_utf8(bytes).unwrap())
|
||||
}
|
||||
|
||||
fn ok(text: &str, slots: &[u64], strings: &[&str]) -> String {
|
||||
run(text, slots, strings).unwrap_or_else(|error| panic!("{text}: {error:?}"))
|
||||
}
|
||||
|
||||
/// The host C library's `snprintf`, on cases whose behaviour ISO C
|
||||
/// defines and Windows shares. `tests/printf/reference.py` wrote the file
|
||||
/// and says how each line is laid out.
|
||||
#[test]
|
||||
fn output_matches_the_host_c_library_on_defined_cases() {
|
||||
let vectors = include_str!("../../tests/printf/vectors.txt");
|
||||
let unhex = |text: &str| -> Vec<u8> {
|
||||
(0..text.len() / 2)
|
||||
.map(|at| u8::from_str_radix(&text[2 * at..2 * at + 2], 16).unwrap())
|
||||
.collect()
|
||||
};
|
||||
let mut cases = 0;
|
||||
for line in vectors.lines().filter(|line| !line.starts_with('#')) {
|
||||
let fields: Vec<&str> = line.split('\t').collect();
|
||||
let [template, arguments, expected] = fields[..] else {
|
||||
panic!("three fields: {line}");
|
||||
};
|
||||
let template = unhex(template);
|
||||
let (mut slots, mut strings) = (Vec::new(), Vec::new());
|
||||
for argument in arguments.split(',').filter(|text| !text.is_empty()) {
|
||||
let (kind, value) = argument.split_once(':').unwrap();
|
||||
match kind {
|
||||
"i" => slots.push(u64::from_str_radix(value, 16).unwrap()),
|
||||
"s" => {
|
||||
slots.push(STRINGS + 0x100 * strings.len() as u64);
|
||||
strings.push(unhex(value));
|
||||
}
|
||||
"n" => slots.push(0),
|
||||
_ => panic!("argument kind {kind}"),
|
||||
}
|
||||
}
|
||||
let mut call = Call {
|
||||
slots,
|
||||
strings,
|
||||
next: 0,
|
||||
};
|
||||
let shown = String::from_utf8_lossy(&template).into_owned();
|
||||
let got = format(&template, &mut call)
|
||||
.unwrap_or_else(|error| panic!("{shown} {arguments}: {error:?}"));
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&got),
|
||||
String::from_utf8_lossy(&unhex(expected)),
|
||||
"{shown} with {arguments}"
|
||||
);
|
||||
assert_eq!(call.next, call.slots.len(), "{shown}: arguments consumed");
|
||||
cases += 1;
|
||||
}
|
||||
assert!(cases > 2000, "{cases} cases");
|
||||
}
|
||||
|
||||
/// Rules the host C library does not share or that the reference leaves
|
||||
/// out, each from the format specification page.
|
||||
#[test]
|
||||
fn windows_sizes_follow_the_format_specification_page() {
|
||||
// "The formatter consumes integer arguments ... as 32-bit int types";
|
||||
// a long is a 32-bit type on Windows. The upper half of the slot is
|
||||
// not part of either.
|
||||
let slot = 0xFFFF_FFFF_8000_0001;
|
||||
assert_eq!(ok("%d", &[slot], &[]), "-2147483647");
|
||||
assert_eq!(ok("%ld", &[slot], &[]), "-2147483647");
|
||||
assert_eq!(ok("%lu", &[slot], &[]), "2147483649");
|
||||
assert_eq!(ok("%lx", &[0x1_2345_6789], &[]), "23456789");
|
||||
assert_eq!(ok("%I32d", &[slot], &[]), "-2147483647");
|
||||
assert_eq!(ok("%I32u", &[slot], &[]), "2147483649");
|
||||
// ll, I64, j, t, z and I alone are 64-bit.
|
||||
for size in ["ll", "I64", "j", "t", "z", "I"] {
|
||||
assert_eq!(
|
||||
ok(&format!("%{size}d"), &[slot], &[]),
|
||||
"-2147483647",
|
||||
"{size}"
|
||||
);
|
||||
assert_eq!(
|
||||
ok(&format!("%{size}u"), &[u64::MAX], &[]),
|
||||
"18446744073709551615",
|
||||
"{size}"
|
||||
);
|
||||
assert_eq!(
|
||||
ok(&format!("%{size}x"), &[0x1_2345_6789], &[]),
|
||||
"123456789",
|
||||
"{size}"
|
||||
);
|
||||
}
|
||||
assert_eq!(ok("%I64d", &[1 << 63], &[]), "-9223372036854775808");
|
||||
// I followed by other digits is the size I and then literal text?
|
||||
// No: digits after the size are not a type, so the format is invalid.
|
||||
assert_eq!(run("%I16d", &[1], &[]), Err(FormatError::Invalid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_characters_and_pointers() {
|
||||
// "If the argument that corresponds to %s ... is a null pointer,
|
||||
// "(null)" is displayed."
|
||||
assert_eq!(ok("[%s]", &[0], &[]), "[(null)]");
|
||||
assert_eq!(ok("[%10s]", &[0], &[]), "[ (null)]");
|
||||
assert_eq!(ok("[%-8s]", &[0], &[]), "[(null) ]");
|
||||
// Xenora's choice: the precision limits it too.
|
||||
assert_eq!(ok("[%.3s]", &[0], &[]), "[(nu]");
|
||||
// h is a single-byte character or string, as no prefix is.
|
||||
assert_eq!(
|
||||
ok("%hc%hs", &[u64::from(b'x'), super::tests::STRINGS], &["yz"]),
|
||||
"xyz"
|
||||
);
|
||||
// The precision has no effect on a character.
|
||||
assert_eq!(ok("[%.0c]", &[0x141], &[]), "[A]");
|
||||
// Xenora's choice for %p: sixteen upper-case hexadecimal digits.
|
||||
assert_eq!(ok("%p", &[0x1_4000_1abc], &[]), "0000000140001ABC");
|
||||
assert_eq!(ok("%p", &[0], &[]), "0000000000000000");
|
||||
assert_eq!(ok("[%20p]", &[0xABC], &[]), "[ 0000000000000ABC]");
|
||||
assert_eq!(ok("[%-20p]", &[0xABC], &[]), "[0000000000000ABC ]");
|
||||
// Xenora's choice: 0 pads a character and a string as it pads a number.
|
||||
assert_eq!(ok("[%03c]", &[u64::from(b'a')], &[]), "[00a]");
|
||||
assert_eq!(ok("[%05s]", &[STRINGS], &["ab"]), "[000ab]");
|
||||
assert_eq!(ok("[%-05s]", &[STRINGS], &["ab"]), "[ab ]");
|
||||
// "+: Use a sign (+ or -) to prefix the output value if it's of a
|
||||
// signed type", and the blank likewise: neither affects an unsigned
|
||||
// conversion.
|
||||
for (text, wanted) in [
|
||||
("%+u", "7"),
|
||||
("% u", "7"),
|
||||
("%+x", "7"),
|
||||
("% X", "7"),
|
||||
("%+o", "7"),
|
||||
("%+ 5u", " 7"),
|
||||
("%+d", "+7"),
|
||||
("% d", " 7"),
|
||||
] {
|
||||
assert_eq!(ok(text, &[7], &[]), wanted, "{text}");
|
||||
}
|
||||
// ISO C for %#.0o with a zero value, which the page does not cover.
|
||||
assert_eq!(ok("[%#.0o]", &[0], &[]), "[0]");
|
||||
assert_eq!(ok("[%.0o]", &[0], &[]), "[]");
|
||||
// Text between and around specifications is copied, and %% is a
|
||||
// percent sign.
|
||||
assert_eq!(
|
||||
ok("100%% of %s%c", &[STRINGS, u64::from(b'!')], &["it"]),
|
||||
"100% of it!"
|
||||
);
|
||||
assert_eq!(ok("", &[], &[]), "");
|
||||
assert_eq!(ok("plain", &[], &[]), "plain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_formats_are_refused() {
|
||||
// "The n specifier is disabled by default", and "if a percent sign is
|
||||
// followed by a character that has no meaning as a format field, the
|
||||
// invalid parameter handler is invoked."
|
||||
for text in [
|
||||
"%n",
|
||||
"%hn",
|
||||
"count %d%n",
|
||||
"%y",
|
||||
"%",
|
||||
"%5",
|
||||
"%-",
|
||||
"%.",
|
||||
"%.3",
|
||||
"%l",
|
||||
"%ll",
|
||||
"%h",
|
||||
"%I64",
|
||||
"%5%",
|
||||
"% %",
|
||||
"%!",
|
||||
"%\u{1}",
|
||||
] {
|
||||
let slots = [1, 2, 3];
|
||||
let mut call = Call {
|
||||
slots: slots.to_vec(),
|
||||
strings: Vec::new(),
|
||||
next: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
format(text.as_bytes(), &mut call),
|
||||
Err(FormatError::Invalid),
|
||||
"{text:?}"
|
||||
);
|
||||
}
|
||||
// A size prefix that does not apply to its type.
|
||||
for text in [
|
||||
"%wd", "%Ld", "%wu", "%Lx", "%llc", "%hhc", "%jc", "%lls", "%zs", "%I64s", "%lp",
|
||||
"%hp", "%llp", "%I32c",
|
||||
] {
|
||||
assert_eq!(run(text, &[1], &["s"]), Err(FormatError::Invalid), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_conversions_that_are_not_modelled_are_refused() {
|
||||
for kind in ["e", "E", "f", "F", "g", "G", "a", "A"] {
|
||||
for prefix in ["", ".3", "l", "L", "10.2", "#"] {
|
||||
let text = format!("%{prefix}{kind}");
|
||||
let mut call = Call {
|
||||
slots: vec![0x3FF0_0000_0000_0000],
|
||||
strings: Vec::new(),
|
||||
next: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
format(text.as_bytes(), &mut call),
|
||||
Err(FormatError::Unsupported),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
// Wide characters and strings: C and S, and c and s with l or w.
|
||||
for text in ["%C", "%S", "%lc", "%ls", "%wc", "%ws", "%Z", "%hC", "%hS"] {
|
||||
let mut call = Call {
|
||||
slots: vec![STRINGS],
|
||||
strings: vec![b"w".to_vec()],
|
||||
next: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
format(text.as_bytes(), &mut call),
|
||||
Err(FormatError::Unsupported),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
// Nothing is produced before a later refusal either: the caller gets
|
||||
// an error, not a prefix.
|
||||
assert_eq!(
|
||||
run("ok %d then %f", &[1, 2], &[]),
|
||||
Err(FormatError::Unsupported)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_and_faults() {
|
||||
let most = MAX_OUTPUT;
|
||||
// A width or precision up to the bound is honoured; one more is not.
|
||||
assert_eq!(ok(&format!("%{most}d"), &[7], &[]).len(), most);
|
||||
assert_eq!(
|
||||
run(&format!("%{}d", most + 1), &[7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
assert_eq!(ok(&format!("%.{most}d"), &[7], &[]).len(), most);
|
||||
assert_eq!(
|
||||
run(&format!("%.{}d", most + 1), &[7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
assert_eq!(
|
||||
run("%99999999999999999999d", &[7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
// The same through *, and the total over several conversions.
|
||||
assert_eq!(ok("%*d", &[most as u64, 7], &[]).len(), most);
|
||||
assert_eq!(
|
||||
run("%*d", &[most as u64 + 1, 7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
assert_eq!(
|
||||
run("%.*d", &[most as u64 + 1, 7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
let half = most / 2 + 1;
|
||||
assert_eq!(
|
||||
run(&format!("%{half}d%{half}d"), &[1, 2], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
// The most negative width is a left-justified width past the bound.
|
||||
assert_eq!(
|
||||
run("%*d", &[0x8000_0000, 7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
// A string is read only up to its precision.
|
||||
assert_eq!(ok("%.2s", &[STRINGS], &["abcdef"]), "ab");
|
||||
|
||||
// A missing argument or an unreadable string is a fault, wherever in
|
||||
// the specification it is needed.
|
||||
for text in [
|
||||
"%d",
|
||||
"%*d",
|
||||
"%.*d",
|
||||
"%5.*d",
|
||||
"%s",
|
||||
"%c",
|
||||
"%p",
|
||||
"%d %d %d %d",
|
||||
] {
|
||||
assert!(
|
||||
matches!(run(text, &[], &[]), Err(FormatError::Fault(_))),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
let mut call = Call {
|
||||
slots: vec![STRINGS + 0x900],
|
||||
strings: Vec::new(),
|
||||
next: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
format(b"%s", &mut call),
|
||||
Err(FormatError::Fault(MemoryError::UnmappedAddress(
|
||||
STRINGS + 0x900
|
||||
)))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! What a C program's startup code configures in the C runtime before `main`.
|
||||
//!
|
||||
//! Each value is recorded and returned as its public documentation says, and
|
||||
//! nothing acts on any of them yet. No invalid-parameter handler, signal
|
||||
//! handler, exception filter, math-error handler or new handler is ever called,
|
||||
//! there is no locale, and nothing reads `_fmode` or `_commode` until stdio
|
||||
//! exists. The registry therefore declares every service here `partial`.
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::memory::{GuestMemory, PROCESS_HEAP};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// `_O_TEXT` (fcntl.h), the documented initial value of `_fmode`.
|
||||
const O_TEXT: u32 = 0x4000;
|
||||
/// `_ENABLE_PER_THREAD_LOCALE` and `_DISABLE_PER_THREAD_LOCALE` (locale.h).
|
||||
const ENABLE_PER_THREAD_LOCALE: i32 = 1;
|
||||
const DISABLE_PER_THREAD_LOCALE: i32 = 2;
|
||||
/// The signals the documentation of `signal` lists, by their signal.h values:
|
||||
/// SIGINT, SIGILL, SIGFPE, SIGSEGV, SIGTERM and SIGABRT.
|
||||
const SIGNALS: [i32; 6] = [2, 4, 8, 11, 15, 22];
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct CrtStartup {
|
||||
app_type: i32,
|
||||
/// Whether `malloc` would call the new handler on failure. It never does.
|
||||
new_mode: i32,
|
||||
per_thread_locale: bool,
|
||||
user_math_error: u64,
|
||||
invalid_parameter_handler: u64,
|
||||
unhandled_exception_filter: u64,
|
||||
/// Handlers other than the default, `SIG_DFL`, which is zero.
|
||||
signals: BTreeMap<i32, u64>,
|
||||
/// Guest address of `_fmode`. `_commode` is the `int` after it.
|
||||
file_modes: Option<u64>,
|
||||
}
|
||||
|
||||
impl CrtStartup {
|
||||
pub(super) fn app_type(&self) -> i32 {
|
||||
self.app_type
|
||||
}
|
||||
|
||||
pub(super) fn set_app_type(&mut self, kind: i32) {
|
||||
self.app_type = kind;
|
||||
}
|
||||
|
||||
/// The previous mode, or `None` for a mode that is neither 0 nor 1.
|
||||
pub(super) fn set_new_mode(&mut self, mode: i32) -> Option<i32> {
|
||||
matches!(mode, 0 | 1).then(|| std::mem::replace(&mut self.new_mode, mode))
|
||||
}
|
||||
|
||||
/// The setting before the call, or `None` for a request that is not 0
|
||||
/// (query), enable or disable. A new process uses the global locale.
|
||||
pub(super) fn configure_thread_locale(&mut self, request: i32) -> Option<i32> {
|
||||
let before = if self.per_thread_locale {
|
||||
ENABLE_PER_THREAD_LOCALE
|
||||
} else {
|
||||
DISABLE_PER_THREAD_LOCALE
|
||||
};
|
||||
match request {
|
||||
0 => {}
|
||||
ENABLE_PER_THREAD_LOCALE => self.per_thread_locale = true,
|
||||
DISABLE_PER_THREAD_LOCALE => self.per_thread_locale = false,
|
||||
_ => return None,
|
||||
}
|
||||
Some(before)
|
||||
}
|
||||
|
||||
pub(super) fn user_math_error(&self) -> u64 {
|
||||
self.user_math_error
|
||||
}
|
||||
|
||||
pub(super) fn set_user_math_error(&mut self, handler: u64) {
|
||||
self.user_math_error = handler;
|
||||
}
|
||||
|
||||
pub(super) fn set_invalid_parameter_handler(&mut self, handler: u64) -> u64 {
|
||||
std::mem::replace(&mut self.invalid_parameter_handler, handler)
|
||||
}
|
||||
|
||||
pub(super) fn set_unhandled_exception_filter(&mut self, filter: u64) -> u64 {
|
||||
std::mem::replace(&mut self.unhandled_exception_filter, filter)
|
||||
}
|
||||
|
||||
/// The previous handler, or `None` for a signal the documentation does not
|
||||
/// list. One table serves the whole process.
|
||||
pub(super) fn signal(&mut self, signal: i32, handler: u64) -> Option<u64> {
|
||||
SIGNALS
|
||||
.contains(&signal)
|
||||
.then(|| self.signals.insert(signal, handler).unwrap_or(0))
|
||||
}
|
||||
|
||||
/// Guest address of `_fmode` (`index` 0) or `_commode` (`index` 1). Both
|
||||
/// are allocated together from the process heap on first use. `_fmode`
|
||||
/// starts as `_O_TEXT`, as documented. `_commode` starts as zero: its
|
||||
/// documentation gives no initial value, and zero is "no commit".
|
||||
pub(super) fn file_mode_address(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
index: u64,
|
||||
) -> Result<u64, ExitReason> {
|
||||
let base = match self.file_modes {
|
||||
Some(base) => base,
|
||||
None => {
|
||||
let base = memory
|
||||
.map_heap_allocation(PROCESS_HEAP, 8)
|
||||
.and_then(|base| memory.write_u32(base, O_TEXT).map(|()| base))
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
self.file_modes = Some(base);
|
||||
base
|
||||
}
|
||||
};
|
||||
Ok(base + 4 * index)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The streams of a hosted C program, and where their output goes.
|
||||
//!
|
||||
//! `__acrt_iob_func` hands out the `FILE` objects for `stdin`, `stdout` and
|
||||
//! `stderr`. What the guest writes to `stdout` and to `stderr` is kept in two
|
||||
//! host-side buffers that a host or a test reads through `ServicesState`.
|
||||
//!
|
||||
//! The standard streams "always open in text mode by default", and in text
|
||||
//! mode "each line feed is replaced with a carriage return-line feed pair"
|
||||
//! that "has no effect on the return value" (Microsoft Learn, "Text and
|
||||
//! binary mode file I/O" and "fwrite"). The buffers hold the bytes after that
|
||||
//! replacement, which is what the operating system would be handed.
|
||||
//!
|
||||
//! A stream that `fopen` returned is a file on the in-memory drive; its rules
|
||||
//! are in `crt_files.rs`.
|
||||
//!
|
||||
//! Output is never held back: there is no buffering to flush or to configure.
|
||||
//! A pointer that is no stream, reading `stdin` and closing a standard stream
|
||||
//! are not modelled and stop the guest with the runtime-limit fault.
|
||||
|
||||
use super::ObjectState;
|
||||
use super::crt_files::{self, EBADF, EINVAL, FileStreams};
|
||||
use super::crt_format::{self, FormatError, Source};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
|
||||
|
||||
/// The exit for a request the runtime does not model.
|
||||
const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
|
||||
/// `typedef struct _iobuf { void* _Placeholder; } FILE;` (corecrt_wstdio.h).
|
||||
const FILE_BYTES: u64 = 8;
|
||||
/// The most a format string or one `fwrite` or `fputs` may hold.
|
||||
const MAX_TRANSFER: u64 = 1 << 20;
|
||||
/// The longest file name or mode string `fopen` reads, in bytes.
|
||||
const MAX_NAME: u64 = 260;
|
||||
/// The most each captured stream keeps. Writing past it stops the guest.
|
||||
pub const MAX_CAPTURED_OUTPUT: usize = 16 << 20;
|
||||
|
||||
/// Option bits of `__stdio_common_vfprintf` (corecrt_stdio_config.h) that do
|
||||
/// not change anything this engine formats: the wide-specifier bit concerns
|
||||
/// the wide functions, and the exponent and rounding bits concern floating
|
||||
/// point. Any other bit stops the guest.
|
||||
const IGNORED_OPTIONS: u64 = 0x04 | 0x10 | 0x20;
|
||||
|
||||
/// `_IOFBF`, `_IOLBF` and `_IONBF` (stdio.h).
|
||||
const IOFBF: i32 = 0x0000;
|
||||
const IOLBF: i32 = 0x0040;
|
||||
const IONBF: i32 = 0x0004;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Stream {
|
||||
Input,
|
||||
Output,
|
||||
Error,
|
||||
/// A stream `fopen` returned, by the address of its `FILE` object.
|
||||
File(u64),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct StandardStreams {
|
||||
/// Guest address of the three `FILE` objects, `stdin` first.
|
||||
files: Option<u64>,
|
||||
output: Vec<u8>,
|
||||
error: Vec<u8>,
|
||||
/// The streams `fopen` has open.
|
||||
opened: FileStreams,
|
||||
}
|
||||
|
||||
/// What a service returns when it fails with a result and an `errno` value:
|
||||
/// the handler sets `errno` to the second field and returns the first.
|
||||
pub(super) struct Failed<T>(pub T, pub u32);
|
||||
|
||||
pub(super) type Outcome<T> = Result<Result<T, Failed<T>>, ExitReason>;
|
||||
|
||||
fn fault(error: MemoryError) -> ExitReason {
|
||||
ExitReason::MemoryFault(error)
|
||||
}
|
||||
|
||||
/// The bytes of the C string at `address`, without its terminator.
|
||||
fn c_string(memory: &GuestMemory, address: u64, limit: u64) -> Result<Vec<u8>, MemoryError> {
|
||||
let mut bytes = Vec::new();
|
||||
for offset in 0..limit {
|
||||
let at = address.checked_add(offset).ok_or(MemoryError::Overflow)?;
|
||||
match memory.read_u8(at)? {
|
||||
0 => break,
|
||||
byte => bytes.push(byte),
|
||||
}
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Arguments from the guest's `va_list`: one 8-byte slot each, in order.
|
||||
struct VaList<'a> {
|
||||
memory: &'a GuestMemory,
|
||||
next: u64,
|
||||
}
|
||||
|
||||
impl Source for VaList<'_> {
|
||||
fn argument(&mut self) -> Result<u64, MemoryError> {
|
||||
let slot = self.memory.read_u64(self.next)?;
|
||||
self.next = self.next.checked_add(8).ok_or(MemoryError::Overflow)?;
|
||||
Ok(slot)
|
||||
}
|
||||
|
||||
fn string(&mut self, address: u64, limit: usize) -> Result<Vec<u8>, MemoryError> {
|
||||
c_string(self.memory, address, limit as u64)
|
||||
}
|
||||
}
|
||||
|
||||
impl StandardStreams {
|
||||
pub(super) fn output(&self) -> &[u8] {
|
||||
&self.output
|
||||
}
|
||||
|
||||
pub(super) fn error(&self) -> &[u8] {
|
||||
&self.error
|
||||
}
|
||||
|
||||
/// `__acrt_iob_func`: the `FILE` object of `stdin` (0), `stdout` (1) or
|
||||
/// `stderr` (2). The three are allocated together from the process heap
|
||||
/// on first use.
|
||||
pub(super) fn file(&mut self, memory: &mut GuestMemory, index: u32) -> Result<u64, ExitReason> {
|
||||
if index > 2 {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
let base = match self.files {
|
||||
Some(base) => base,
|
||||
None => {
|
||||
let base = memory
|
||||
.map_heap_allocation(PROCESS_HEAP, (3 * FILE_BYTES) as usize)
|
||||
.map_err(fault)?;
|
||||
self.files = Some(base);
|
||||
base
|
||||
}
|
||||
};
|
||||
Ok(base + FILE_BYTES * u64::from(index))
|
||||
}
|
||||
|
||||
/// Which stream a non-null `FILE*` is: a standard stream, or one `fopen`
|
||||
/// returned. Any other pointer is no stream.
|
||||
fn stream(&self, file: u64) -> Result<Stream, ExitReason> {
|
||||
match self.files.map(|base| file.wrapping_sub(base)) {
|
||||
Some(0) => Ok(Stream::Input),
|
||||
Some(8) => Ok(Stream::Output),
|
||||
Some(16) => Ok(Stream::Error),
|
||||
_ if self.opened.contains(file) => Ok(Stream::File(file)),
|
||||
_ => Err(RUNTIME_LIMIT),
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream that may be written. Writing `stdin` is not modelled.
|
||||
fn writable(&self, file: u64) -> Result<Stream, ExitReason> {
|
||||
match self.stream(file)? {
|
||||
Stream::Input => Err(RUNTIME_LIMIT),
|
||||
stream => Ok(stream),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write to a stream. A standard stream is captured in text mode: each
|
||||
/// line feed becomes a carriage return and a line feed. A file stream can
|
||||
/// fail, with the `errno` value in the inner result and nothing written.
|
||||
fn write(
|
||||
&mut self,
|
||||
drive: &mut ObjectState,
|
||||
stream: Stream,
|
||||
bytes: &[u8],
|
||||
) -> Result<Result<(), u32>, ExitReason> {
|
||||
let captured = match stream {
|
||||
Stream::Output => &mut self.output,
|
||||
Stream::Error => &mut self.error,
|
||||
Stream::Input => return Err(RUNTIME_LIMIT),
|
||||
Stream::File(file) => return Ok(self.opened.write(drive, file, bytes)),
|
||||
};
|
||||
let feeds = bytes.iter().filter(|byte| **byte == b'\n').count();
|
||||
if bytes.len() + feeds > MAX_CAPTURED_OUTPUT - captured.len() {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
for &byte in bytes {
|
||||
if byte == b'\n' {
|
||||
captured.push(b'\r');
|
||||
}
|
||||
captured.push(byte);
|
||||
}
|
||||
Ok(Ok(()))
|
||||
}
|
||||
|
||||
/// `__stdio_common_vfprintf`. Returns the number of characters written,
|
||||
/// before the text-mode replacement.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn print(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
drive: &mut ObjectState,
|
||||
options: u64,
|
||||
file: u64,
|
||||
format: u64,
|
||||
locale: u64,
|
||||
arguments: u64,
|
||||
) -> Outcome<i32> {
|
||||
// A null stream or format: the function returns -1 and sets errno.
|
||||
if file == 0 || format == 0 {
|
||||
return Ok(Err(Failed(-1, EINVAL)));
|
||||
}
|
||||
if options & !IGNORED_OPTIONS != 0 || locale != 0 {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
let stream = self.writable(file)?;
|
||||
let template = c_string(memory, format, MAX_TRANSFER + 1).map_err(fault)?;
|
||||
if template.len() as u64 > MAX_TRANSFER {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
let mut source = VaList {
|
||||
memory,
|
||||
next: arguments,
|
||||
};
|
||||
let text = match crt_format::format(&template, &mut source) {
|
||||
Ok(text) => text,
|
||||
// Windows calls the invalid parameter handler for an invalid
|
||||
// format. Xenora's choice for when execution continues: nothing
|
||||
// is written and the result is that of a null format.
|
||||
Err(FormatError::Invalid) => return Ok(Err(Failed(-1, EINVAL))),
|
||||
Err(FormatError::Unsupported | FormatError::TooLong) => return Err(RUNTIME_LIMIT),
|
||||
Err(FormatError::Fault(error)) => return Err(fault(error)),
|
||||
};
|
||||
// "A negative value if an output error occurs."
|
||||
Ok(match self.write(drive, stream, &text)? {
|
||||
Ok(()) => Ok(text.len() as i32),
|
||||
Err(errno) => Err(Failed(-1, errno)),
|
||||
})
|
||||
}
|
||||
|
||||
/// `fwrite`. Returns the number of whole items written.
|
||||
pub(super) fn write_items(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
drive: &mut ObjectState,
|
||||
buffer: u64,
|
||||
size: u64,
|
||||
count: u64,
|
||||
file: u64,
|
||||
) -> Outcome<u64> {
|
||||
if buffer == 0 || file == 0 {
|
||||
return Ok(Err(Failed(0, EINVAL)));
|
||||
}
|
||||
let stream = self.writable(file)?;
|
||||
let Some(length) = size
|
||||
.checked_mul(count)
|
||||
.filter(|bytes| *bytes <= MAX_TRANSFER)
|
||||
else {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
};
|
||||
if length == 0 {
|
||||
return Ok(Ok(0));
|
||||
}
|
||||
let mut bytes = vec![0; length as usize];
|
||||
memory.read_bytes(buffer, &mut bytes).map_err(fault)?;
|
||||
// Fewer items than `count` means an error. A failed write here
|
||||
// writes none of them.
|
||||
Ok(match self.write(drive, stream, &bytes)? {
|
||||
Ok(()) => Ok(count),
|
||||
Err(errno) => Err(Failed(0, errno)),
|
||||
})
|
||||
}
|
||||
|
||||
/// `fputs`. Writes the string without its terminator and returns a
|
||||
/// nonnegative value, here 0; `EOF` is -1.
|
||||
pub(super) fn put_string(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
drive: &mut ObjectState,
|
||||
text: u64,
|
||||
file: u64,
|
||||
) -> Outcome<i32> {
|
||||
if text == 0 || file == 0 {
|
||||
return Ok(Err(Failed(-1, EINVAL)));
|
||||
}
|
||||
let stream = self.writable(file)?;
|
||||
let bytes = c_string(memory, text, MAX_TRANSFER + 1).map_err(fault)?;
|
||||
if bytes.len() as u64 > MAX_TRANSFER {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
Ok(match self.write(drive, stream, &bytes)? {
|
||||
Ok(()) => Ok(0),
|
||||
Err(errno) => Err(Failed(-1, errno)),
|
||||
})
|
||||
}
|
||||
|
||||
/// `fflush`. A null stream means every open stream. Nothing is ever held
|
||||
/// back, so there is nothing to do.
|
||||
pub(super) fn flush(&self, file: u64) -> Result<i32, ExitReason> {
|
||||
if file != 0 {
|
||||
self.stream(file)?;
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// `setvbuf`. The mode and size are checked as documented and then have
|
||||
/// no effect.
|
||||
pub(super) fn set_buffer(&self, file: u64, mode: i32, size: u64) -> Outcome<i32> {
|
||||
if file == 0 {
|
||||
return Ok(Err(Failed(-1, EINVAL)));
|
||||
}
|
||||
self.stream(file)?;
|
||||
let valid = match mode {
|
||||
// "No buffer is used, regardless of buffer or size."
|
||||
IONBF => true,
|
||||
// "Allowable range: 2 <= size <= INT_MAX".
|
||||
IOFBF | IOLBF => (2..=i32::MAX as u64).contains(&size),
|
||||
_ => false,
|
||||
};
|
||||
Ok(if valid {
|
||||
Ok(0)
|
||||
} else {
|
||||
Err(Failed(-1, EINVAL))
|
||||
})
|
||||
}
|
||||
|
||||
/// `fopen`. Returns the new `FILE*`, or null with the `errno` value.
|
||||
pub(super) fn open(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
drive: &mut ObjectState,
|
||||
name: u64,
|
||||
mode: u64,
|
||||
) -> Outcome<u64> {
|
||||
// A null name or mode is an invalid parameter, as an empty one is.
|
||||
if name == 0 || mode == 0 {
|
||||
return Ok(Err(Failed(0, EINVAL)));
|
||||
}
|
||||
let name = c_string(memory, name, MAX_NAME + 1).map_err(fault)?;
|
||||
let mode = c_string(memory, mode, MAX_NAME + 1).map_err(fault)?;
|
||||
if name.len() as u64 > MAX_NAME || mode.len() as u64 > MAX_NAME {
|
||||
return Ok(Err(Failed(0, EINVAL)));
|
||||
}
|
||||
Ok(self
|
||||
.opened
|
||||
.open(memory, drive, &name, &mode)
|
||||
.map_err(|errno| Failed(0, errno)))
|
||||
}
|
||||
|
||||
/// `fclose`. Returns 0, or `EOF` with `EINVAL` for a null stream. Closing
|
||||
/// a standard stream is not modelled.
|
||||
pub(super) fn close(&mut self, memory: &mut GuestMemory, file: u64) -> Outcome<i32> {
|
||||
if file == 0 {
|
||||
return Ok(Err(Failed(-1, EINVAL)));
|
||||
}
|
||||
match self.stream(file)? {
|
||||
Stream::File(file) => {
|
||||
self.opened.close(memory, file);
|
||||
Ok(Ok(0))
|
||||
}
|
||||
_ => Err(RUNTIME_LIMIT),
|
||||
}
|
||||
}
|
||||
|
||||
/// `fgets`. Returns `buffer`, or null at end of file or on an error.
|
||||
pub(super) fn get_line(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
drive: &ObjectState,
|
||||
buffer: u64,
|
||||
count: i32,
|
||||
file: u64,
|
||||
) -> Outcome<u64> {
|
||||
if buffer == 0 || file == 0 || count <= 0 {
|
||||
return Ok(Err(Failed(0, EINVAL)));
|
||||
}
|
||||
let file = match self.stream(file)? {
|
||||
Stream::File(file) => file,
|
||||
// Reading the standard input is not modelled.
|
||||
Stream::Input => return Err(RUNTIME_LIMIT),
|
||||
// The output streams cannot be read.
|
||||
Stream::Output | Stream::Error => return Ok(Err(Failed(0, EBADF))),
|
||||
};
|
||||
// Up to count - 1 characters, and then the terminator.
|
||||
let limit = ((count - 1) as u64).min(MAX_TRANSFER) as usize;
|
||||
let mut line = match self.opened.read_line(drive, file, limit) {
|
||||
Ok(Some(line)) => line,
|
||||
// End of file with nothing read: null, and the buffer is left
|
||||
// alone.
|
||||
Ok(None) => return Ok(Ok(0)),
|
||||
Err(errno) => return Ok(Err(Failed(0, errno))),
|
||||
};
|
||||
line.push(0);
|
||||
memory.write_bytes(buffer, &line).map_err(fault)?;
|
||||
Ok(Ok(buffer))
|
||||
}
|
||||
|
||||
/// `perror`: the message, a colon and a space when there is a message,
|
||||
/// then the text for `errno` and a newline, to `stderr`.
|
||||
pub(super) fn report(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
drive: &mut ObjectState,
|
||||
message: u64,
|
||||
errno: u32,
|
||||
) -> Result<(), ExitReason> {
|
||||
let mut text = Vec::new();
|
||||
if message != 0 {
|
||||
text = c_string(memory, message, MAX_TRANSFER + 1).map_err(fault)?;
|
||||
if text.len() as u64 > MAX_TRANSFER {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
}
|
||||
if !text.is_empty() {
|
||||
text.extend_from_slice(b": ");
|
||||
}
|
||||
text.extend_from_slice(crt_files::error_text(errno).as_bytes());
|
||||
text.push(b'\n');
|
||||
self.write(drive, Stream::Error, &text).map(|_| ())
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Unnamed event, semaphore and mutex objects and waits that can resolve without a guest scheduler.
|
||||
//! Unnamed event, semaphore and mutex objects and waits. A wait that cannot
|
||||
//! resolve at once blocks the guest thread if a scheduler is attached, and is
|
||||
//! unsupported otherwise.
|
||||
|
||||
use super::threads::PendingWait;
|
||||
use super::{
|
||||
ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOACCESS,
|
||||
ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, GuestObject, KERNEL32, ServicesState,
|
||||
@@ -13,11 +16,14 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
const SYNCH_API: &str = "api-ms-win-core-synch-l1-1-0.dll";
|
||||
const EVENT_MODIFY_STATE: u32 = 0x0002;
|
||||
const SYNCHRONIZE: u32 = 0x0010_0000;
|
||||
pub(super) const SYNCHRONIZE: u32 = 0x0010_0000;
|
||||
const EVENT_ALL_ACCESS: u32 = 0x001f_0003;
|
||||
const WAIT_OBJECT_0: u64 = 0;
|
||||
const INFINITE: u32 = u32::MAX;
|
||||
const TICKS_PER_MILLI: u64 = 10_000;
|
||||
const WAIT_TIMEOUT: u64 = 258;
|
||||
const WAIT_FAILED: u64 = u32::MAX as u64;
|
||||
const WAIT_ABANDONED_0: u64 = 0x80;
|
||||
|
||||
const SEMAPHORE_ALL_ACCESS: u32 = 0x001f_0003;
|
||||
const SEMAPHORE_MODIFY_STATE: u32 = 2;
|
||||
@@ -40,6 +46,13 @@ pub(super) enum Waitable {
|
||||
Mutex {
|
||||
owner: Option<u64>,
|
||||
recursion: u32,
|
||||
/// The owner ended without releasing it.
|
||||
abandoned: bool,
|
||||
},
|
||||
/// Signaled for good once the guest thread has ended.
|
||||
Thread {
|
||||
id: u32,
|
||||
exit_code: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -49,21 +62,30 @@ impl Waitable {
|
||||
Self::Event { signaled, .. } => *signaled,
|
||||
Self::Semaphore { count, .. } => *count > 0,
|
||||
Self::Mutex { owner, .. } => owner.is_none_or(|owner| owner == teb),
|
||||
Self::Thread { exit_code, .. } => exit_code.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
fn consume(&mut self, teb: u64) {
|
||||
/// Take the signal; true if it was an abandoned mutex.
|
||||
fn consume(&mut self, teb: u64) -> bool {
|
||||
match self {
|
||||
Self::Event {
|
||||
manual_reset,
|
||||
signaled,
|
||||
} => *signaled = *manual_reset,
|
||||
Self::Semaphore { count, .. } => *count -= 1,
|
||||
Self::Mutex { owner, recursion } => {
|
||||
Self::Mutex {
|
||||
owner,
|
||||
recursion,
|
||||
abandoned,
|
||||
} => {
|
||||
*owner = Some(teb);
|
||||
*recursion += 1;
|
||||
return std::mem::take(abandoned);
|
||||
}
|
||||
Self::Thread { .. } => {}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn at_recursion_limit(&self) -> bool {
|
||||
@@ -100,6 +122,7 @@ fn insert_mutex(
|
||||
let object = Waitable::Mutex {
|
||||
owner: initial_owner.then_some(teb),
|
||||
recursion: u32::from(initial_owner),
|
||||
abandoned: false,
|
||||
};
|
||||
insert_waitable(state, teb, object, access)
|
||||
}
|
||||
@@ -150,6 +173,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
return state.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
*current = signaled;
|
||||
if signaled {
|
||||
state.hooks.signal();
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
}
|
||||
@@ -202,6 +228,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
return release.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
*count += amount;
|
||||
release.hooks.signal();
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
@@ -244,7 +271,10 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
let mut state = state.lock().expect("guest waitable state");
|
||||
let Waitable::Mutex { owner, recursion } = &mut *state else {
|
||||
let Waitable::Mutex {
|
||||
owner, recursion, ..
|
||||
} = &mut *state
|
||||
else {
|
||||
return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
if *owner != Some(cpu.gs_base) {
|
||||
@@ -253,6 +283,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
*recursion -= 1;
|
||||
if *recursion == 0 {
|
||||
*owner = None;
|
||||
release.hooks.signal();
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
@@ -263,6 +294,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
] {
|
||||
let single = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
if let Some(result) = resume_wait(&single, cpu.gs_base) {
|
||||
return result;
|
||||
}
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let timeout = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
if extended && args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0 {
|
||||
@@ -277,6 +311,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
] {
|
||||
let multiple = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
if let Some(result) = resume_wait(&multiple, cpu.gs_base) {
|
||||
return result;
|
||||
}
|
||||
let count = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let address = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let all = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0;
|
||||
@@ -363,21 +400,75 @@ fn wait_for_objects(
|
||||
None => return state.fail(teb, ERROR_INVALID_HANDLE, WAIT_FAILED),
|
||||
}
|
||||
}
|
||||
let mut ready = Vec::with_capacity(handles.len());
|
||||
for (index, event) in waitables.into_iter().enumerate() {
|
||||
if event.lock().expect("guest waitable state").is_ready(teb) {
|
||||
ready.push((index, event));
|
||||
if let Some(result) = try_satisfy(&waitables, all, teb) {
|
||||
return result;
|
||||
}
|
||||
if timeout == 0 {
|
||||
return Ok(WAIT_TIMEOUT);
|
||||
}
|
||||
if !state.hooks.is_attached() {
|
||||
return state.fail(teb, ERROR_NOT_SUPPORTED, WAIT_FAILED);
|
||||
}
|
||||
// Keep the objects themselves: closing a handle or changing the guest's
|
||||
// handle array does not change a wait already in progress.
|
||||
let deadline = (timeout != INFINITE).then(|| {
|
||||
state
|
||||
.clock
|
||||
.performance_count()
|
||||
.saturating_add(u64::from(timeout) * TICKS_PER_MILLI)
|
||||
});
|
||||
let pending = PendingWait {
|
||||
objects: waitables.into_iter().map(Arc::clone).collect(),
|
||||
all,
|
||||
deadline,
|
||||
};
|
||||
state
|
||||
.threads
|
||||
.lock()
|
||||
.expect("guest thread table")
|
||||
.waits
|
||||
.insert(teb, pending);
|
||||
Err(ExitReason::GuestBlocked)
|
||||
}
|
||||
|
||||
/// Continue the wait this thread is blocked in, if any. Waiters are retried
|
||||
/// directly after a signal, so an object found signaled once the deadline has
|
||||
/// passed was signaled too late and is left alone.
|
||||
fn resume_wait(state: &ServicesState, teb: u64) -> Option<Result<u64, ExitReason>> {
|
||||
let mut table = state.threads.lock().expect("guest thread table");
|
||||
let pending = table.waits.get(&teb)?;
|
||||
let expired = pending
|
||||
.deadline
|
||||
.is_some_and(|deadline| state.clock.performance_count() >= deadline);
|
||||
let result = if expired {
|
||||
Some(Ok(WAIT_TIMEOUT))
|
||||
} else {
|
||||
let objects: Vec<&Arc<Mutex<Waitable>>> = pending.objects.iter().collect();
|
||||
try_satisfy(&objects, pending.all, teb)
|
||||
};
|
||||
if result.is_some() {
|
||||
table.waits.remove(&teb);
|
||||
}
|
||||
Some(result.unwrap_or(Err(ExitReason::GuestBlocked)))
|
||||
}
|
||||
|
||||
/// Consume the objects if the wait is satisfied now.
|
||||
fn try_satisfy(
|
||||
waitables: &[&Arc<Mutex<Waitable>>],
|
||||
all: bool,
|
||||
teb: u64,
|
||||
) -> Option<Result<u64, ExitReason>> {
|
||||
let mut ready = Vec::with_capacity(waitables.len());
|
||||
for (index, object) in waitables.iter().enumerate() {
|
||||
if object.lock().expect("guest waitable state").is_ready(teb) {
|
||||
ready.push((index, object));
|
||||
if !all {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ready.is_empty() || (all && ready.len() != handles.len()) {
|
||||
return if timeout == 0 {
|
||||
Ok(WAIT_TIMEOUT)
|
||||
} else {
|
||||
state.fail(teb, ERROR_NOT_SUPPORTED, WAIT_FAILED)
|
||||
};
|
||||
if ready.is_empty() || (all && ready.len() != waitables.len()) {
|
||||
return None;
|
||||
}
|
||||
if ready.iter().any(|(_, object)| {
|
||||
object
|
||||
@@ -386,11 +477,42 @@ fn wait_for_objects(
|
||||
.at_recursion_limit()
|
||||
}) {
|
||||
// Windows raises STATUS_MUTANT_LIMIT_EXCEEDED; exceptions are unsupported.
|
||||
return Err(ExitReason::IllegalInstruction(0xFE));
|
||||
return Some(Err(ExitReason::IllegalInstruction(0xFE)));
|
||||
}
|
||||
let first = ready[0].0;
|
||||
for (_, event) in ready {
|
||||
event.lock().expect("guest waitable state").consume(teb);
|
||||
let first = ready[0].0 as u64;
|
||||
let mut abandoned = None;
|
||||
for (index, object) in ready {
|
||||
if object.lock().expect("guest waitable state").consume(teb) {
|
||||
abandoned.get_or_insert(index as u64);
|
||||
}
|
||||
}
|
||||
Some(Ok(match abandoned {
|
||||
Some(index) => WAIT_ABANDONED_0 + index,
|
||||
None => WAIT_OBJECT_0 + first,
|
||||
}))
|
||||
}
|
||||
|
||||
impl ServicesState {
|
||||
/// Release every mutex owned by a guest thread that has ended.
|
||||
pub(super) fn abandon_mutexes(&self, teb: u64) {
|
||||
let objects = self.objects.lock().expect("guest object state");
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
let handles = objects.handles.values().filter_map(|object| match object {
|
||||
GuestObject::Waitable { state, .. } => Some(state),
|
||||
_ => None,
|
||||
});
|
||||
// A waiter keeps an object alive after its last handle is closed.
|
||||
let waiting = table.waits.values().flat_map(|wait| &wait.objects);
|
||||
for object in handles.chain(waiting) {
|
||||
if let Waitable::Mutex {
|
||||
owner,
|
||||
recursion,
|
||||
abandoned,
|
||||
} = &mut *object.lock().expect("guest waitable state")
|
||||
&& *owner == Some(teb)
|
||||
{
|
||||
(*owner, *recursion, *abandoned) = (None, 0, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(WAIT_OBJECT_0 + first as u64)
|
||||
}
|
||||
@@ -625,3 +625,89 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a path names on the drive, for the C runtime's file streams.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum DriveEntry {
|
||||
File,
|
||||
Directory,
|
||||
/// Nothing has this name. `parent` says whether its directory exists.
|
||||
Missing {
|
||||
parent: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// The drive as the C runtime's file streams (`crt_files.rs`) use it. They read
|
||||
/// and write the same files as the handle services above. A stream is not a
|
||||
/// handle: it takes no part in sharing, and a file it has open can be deleted
|
||||
/// or moved, after which its operations fail.
|
||||
impl super::ObjectState {
|
||||
/// A narrow file name as the drive stores it: ASCII, either slash, any
|
||||
/// case, with or without `C:\`. `None` for a name the drive rejects.
|
||||
pub(super) fn drive_path(name: &[u8]) -> Option<String> {
|
||||
if !name.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
let path = String::from_utf8_lossy(name)
|
||||
.replace('/', "\\")
|
||||
.to_ascii_lowercase();
|
||||
let path = path.strip_prefix("c:\\").unwrap_or(&path).to_owned();
|
||||
path.split('\\').all(valid_component).then_some(path)
|
||||
}
|
||||
|
||||
pub(super) fn drive_entry(&self, path: &str) -> DriveEntry {
|
||||
if self.files.contains_key(path) {
|
||||
DriveEntry::File
|
||||
} else if self.directories.contains(path) {
|
||||
DriveEntry::Directory
|
||||
} else {
|
||||
let parent = parent(path);
|
||||
DriveEntry::Missing {
|
||||
parent: parent.is_empty() || self.directories.contains(parent),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an empty file. False when the drive already holds as many files
|
||||
/// as it can.
|
||||
pub(super) fn drive_create(&mut self, path: &str) -> bool {
|
||||
if self.files.len() >= MAX_FILES {
|
||||
return false;
|
||||
}
|
||||
self.files.insert(path.to_owned(), Vec::new());
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn drive_file(&self, path: &str) -> Option<&[u8]> {
|
||||
self.files.get(path).map(Vec::as_slice)
|
||||
}
|
||||
|
||||
/// Empty a file. False when it does not exist.
|
||||
pub(super) fn drive_truncate(&mut self, path: &str) -> bool {
|
||||
self.files.get_mut(path).map(Vec::clear).is_some()
|
||||
}
|
||||
|
||||
/// Write `bytes` at `position`, growing the file as needed. `None` when
|
||||
/// the file does not exist; `Some(false)`, with nothing written, when the
|
||||
/// write would pass the drive's size bound.
|
||||
pub(super) fn drive_write(&mut self, path: &str, position: u64, bytes: &[u8]) -> Option<bool> {
|
||||
let used: usize = self.files.values().map(Vec::len).sum();
|
||||
let data = self.files.get_mut(path)?;
|
||||
let Some(end) = position
|
||||
.checked_add(bytes.len() as u64)
|
||||
.filter(|end| *end <= MAX_BYTES as u64)
|
||||
else {
|
||||
return Some(false);
|
||||
};
|
||||
let (start, end) = (position as usize, end as usize);
|
||||
let growth = end.saturating_sub(data.len());
|
||||
if growth > MAX_BYTES - used {
|
||||
return Some(false);
|
||||
}
|
||||
if growth != 0 {
|
||||
data.resize(end, 0);
|
||||
}
|
||||
data[start..end].copy_from_slice(bytes);
|
||||
Some(true)
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,18 @@ struct ScheduledCallback {
|
||||
}
|
||||
|
||||
impl QueueHandles {
|
||||
/// Task-queue handles the guest has open.
|
||||
pub(super) fn open_count(&self) -> usize {
|
||||
self.queues.len()
|
||||
}
|
||||
|
||||
/// Process exit: every handle is closed and nothing stays scheduled.
|
||||
pub(super) fn close_all(&mut self) {
|
||||
self.queues.clear();
|
||||
self.terminated.clear();
|
||||
self.pending.clear();
|
||||
}
|
||||
|
||||
fn open(
|
||||
&mut self,
|
||||
duplicate: Option<Queue>,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Process termination.
|
||||
|
||||
use super::{KERNEL32, ServicesState};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use std::sync::Arc;
|
||||
|
||||
const PROCESS_THREADS_API: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
const UCRT: &str = "ucrtbase.dll";
|
||||
const CRT_RUNTIME_API: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
|
||||
/// The exit code `abort` ends the process with (Microsoft Learn, "abort").
|
||||
const ABORT_STATUS: u32 = 3;
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
// ExitProcess does not return (processthreadsapi.h). It stops the guest
|
||||
// with its status and never ends the host. It is partial: there are no
|
||||
// other threads or loaded DLLs to notify.
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "ExitProcess", move |args, _, _| {
|
||||
// The status is a UINT, the low half of the first argument.
|
||||
Err(ExitReason::ProcessExit(s.exit_process(args.rcx as u32)))
|
||||
});
|
||||
registry.alias(PROCESS_THREADS_API, KERNEL32, "ExitProcess");
|
||||
registry.set_status(KERNEL32, "ExitProcess", ServiceStatus::Partial);
|
||||
|
||||
// _exit ends the process without calling the functions registered with
|
||||
// atexit (Microsoft Learn, "exit, _Exit, _exit"). `exit`, which does call
|
||||
// them, is beside `_cexit` in crt_callbacks.rs.
|
||||
let s = Arc::clone(state);
|
||||
registry.register(UCRT, "_exit", move |args, _, _| {
|
||||
// The status is an int, the low half of the first argument.
|
||||
Err(ExitReason::ProcessExit(s.exit_process(args.rcx as u32)))
|
||||
});
|
||||
|
||||
// abort ends the process with exit code 3 and calls no registered
|
||||
// function. It is partial: it prints no message, and it does not call a
|
||||
// SIGABRT handler, which the documentation says it does when one is set.
|
||||
let s = Arc::clone(state);
|
||||
registry.register(UCRT, "abort", move |_, _, _| {
|
||||
Err(ExitReason::ProcessExit(s.exit_process(ABORT_STATUS)))
|
||||
});
|
||||
|
||||
for symbol in ["_exit", "abort"] {
|
||||
registry.alias(CRT_RUNTIME_API, UCRT, symbol);
|
||||
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,10 @@
|
||||
//! Critical sections, slim reader/writer locks, condition variables, one-time
|
||||
//! initialization, interlocked singly linked lists and thread-local storage.
|
||||
//!
|
||||
//! Ownership is keyed by the calling guest TEB. No guest scheduler exists yet,
|
||||
//! so an operation that would have to block another guest thread stops the
|
||||
//! guest with the runtime-limit fault instead of pretending to synchronize.
|
||||
//! Ownership is keyed by the calling guest TEB. These objects do not block
|
||||
//! through the guest scheduler yet, so an operation that would have to wait for
|
||||
//! another guest thread stops the guest with the runtime-limit fault instead of
|
||||
//! pretending to synchronize.
|
||||
|
||||
use super::{
|
||||
ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, KERNEL32, ServicesState,
|
||||
@@ -37,6 +38,9 @@ const CRITICAL_SECTION_NO_DEBUG_INFO: u32 = 0x0100_0000;
|
||||
const MAX_CRITICAL_SECTIONS: usize = 4096;
|
||||
|
||||
const MAX_SRW_LOCKS: usize = 4096;
|
||||
const MAX_PENDING_INIT_ONCE: usize = 4096;
|
||||
/// Owner of a lock whose thread ended while holding it. Never a TEB address.
|
||||
const ENDED_THREAD: u64 = u64::MAX;
|
||||
const CONDITION_VARIABLE_LOCKMODE_SHARED: u32 = 1;
|
||||
|
||||
const INIT_ONCE_CHECK_ONLY: u32 = 1;
|
||||
@@ -161,6 +165,33 @@ pub(super) struct Synch {
|
||||
}
|
||||
|
||||
impl Synch {
|
||||
/// Drop the thread-local values of a guest thread that has ended, without
|
||||
/// running FLS callbacks. Locks it held stay held: its TEB address may be
|
||||
/// reused, and the next thread there must not own them.
|
||||
pub(super) fn retire_thread(&mut self, teb: u64) {
|
||||
self.tls_values.retain(|&(owner, _), _| owner != teb);
|
||||
self.fls_values.retain(|&(owner, _), _| owner != teb);
|
||||
for section in self.sections.values_mut() {
|
||||
if section.owner == Some(teb) {
|
||||
section.owner = Some(ENDED_THREAD);
|
||||
}
|
||||
}
|
||||
for lock in self.srw.values_mut() {
|
||||
if lock.exclusive == Some(teb) {
|
||||
lock.exclusive = Some(ENDED_THREAD);
|
||||
}
|
||||
if let Some(count) = lock.shared.remove(&teb) {
|
||||
let held = lock.shared.entry(ENDED_THREAD).or_default();
|
||||
*held = held.saturating_add(count);
|
||||
}
|
||||
}
|
||||
for owner in self.init_once_pending.values_mut() {
|
||||
if *owner == teb {
|
||||
*owner = ENDED_THREAD;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn section(&mut self, address: u64) -> Result<&mut CriticalSection, ExitReason> {
|
||||
// Using an uninitialized critical section is undefined; report it.
|
||||
self.sections.get_mut(&address).map_or_else(unsupported, Ok)
|
||||
@@ -228,6 +259,7 @@ fn enter_section(
|
||||
address: u64,
|
||||
teb: u64,
|
||||
) -> Result<bool, ExitReason> {
|
||||
let thread_id = state.thread_id_of(teb);
|
||||
let mut synch = state.synch.lock().expect("guest synchronization state");
|
||||
let section = synch.section(address)?;
|
||||
match section.owner {
|
||||
@@ -237,7 +269,7 @@ fn enter_section(
|
||||
}
|
||||
section.owner = Some(teb);
|
||||
section.recursion += 1;
|
||||
mirror_section(memory, address, section, state.thread_id)?;
|
||||
mirror_section(memory, address, section, thread_id)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -247,6 +279,7 @@ fn leave_section(
|
||||
address: u64,
|
||||
teb: u64,
|
||||
) -> Result<(), ExitReason> {
|
||||
let thread_id = state.thread_id_of(teb);
|
||||
let mut synch = state.synch.lock().expect("guest synchronization state");
|
||||
let section = synch.section(address)?;
|
||||
if section.owner != Some(teb) {
|
||||
@@ -256,7 +289,7 @@ fn leave_section(
|
||||
if section.recursion == 0 {
|
||||
section.owner = None;
|
||||
}
|
||||
mirror_section(memory, address, section, state.thread_id)
|
||||
mirror_section(memory, address, section, thread_id)
|
||||
}
|
||||
|
||||
/// Check that a pointer-sized synchronization object is readable and writable.
|
||||
@@ -611,8 +644,9 @@ fn register_srw_and_conditions(registry: &mut ImportRegistry, state: &Arc<Servic
|
||||
}
|
||||
}
|
||||
|
||||
/// A zero timeout releases and reacquires the lock, which no other guest
|
||||
/// thread can observe, then reports the timeout. Longer sleeps would block.
|
||||
/// A zero timeout releases and reacquires the lock within one service call, so
|
||||
/// no other guest thread can observe it, then reports the timeout. Longer sleeps
|
||||
/// would block.
|
||||
fn sleep_result(state: &ServicesState, teb: u64, timeout: u32) -> Result<u64, ExitReason> {
|
||||
if timeout == 0 {
|
||||
state.fail(teb, ERROR_TIMEOUT, 0)
|
||||
@@ -666,6 +700,9 @@ fn register_init_once(registry: &mut ImportRegistry, state: &Arc<ServicesState>)
|
||||
s.fail(teb, ERROR_GEN_FAILURE, 0)
|
||||
}
|
||||
0 if value == 0 => {
|
||||
if synch.init_once_pending.len() >= MAX_PENDING_INIT_ONCE {
|
||||
return unsupported();
|
||||
}
|
||||
mem.write_u32(pending, 1).map_err(fault)?;
|
||||
mem.write_u64(once, INIT_ONCE_PENDING).map_err(fault)?;
|
||||
synch.init_once_pending.insert(once, teb);
|
||||
@@ -727,6 +764,9 @@ fn register_init_once(registry: &mut ImportRegistry, state: &Arc<ServicesState>)
|
||||
return unsupported();
|
||||
}
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
if synch.init_once_pending.len() >= MAX_PENDING_INIT_ONCE {
|
||||
return unsupported();
|
||||
}
|
||||
mem.write_u64(scratch, 0).map_err(fault)?;
|
||||
mem.write_u64(once, INIT_ONCE_PENDING).map_err(fault)?;
|
||||
synch.init_once_pending.insert(once, teb);
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest thread table and the thread services.
|
||||
//!
|
||||
//! A guest thread is a CPU context, a guarded stack and a TEB. It is not a host
|
||||
//! thread: [`crate::scheduler`] runs one guest thread at a time on one host
|
||||
//! thread. Without an attached scheduler `CreateThread` reports
|
||||
//! `ERROR_NOT_SUPPORTED`, no thread object exists, and waits behave as they do
|
||||
//! for a single thread.
|
||||
|
||||
use super::events::{SYNCHRONIZE, Waitable};
|
||||
use super::{
|
||||
CURRENT_THREAD, ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER,
|
||||
ERROR_NOACCESS, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, GuestObject, KERNEL32, PAGE_SIZE,
|
||||
PROCESS_THREADS_V1, ServicesState, THREAD_QUERY_RIGHTS,
|
||||
};
|
||||
use crate::cpu::{CpuState, ExitReason, Register};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{ALLOCATION_GRANULARITY, GuestMemory, MemoryError, MemoryPermissions};
|
||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// Most guest threads alive at once, the main thread included.
|
||||
pub const MAX_THREADS: usize = 64;
|
||||
/// Stack of a thread created with a zero size.
|
||||
pub const DEFAULT_STACK: u64 = 256 * 1024;
|
||||
const MAX_STACK: u64 = 8 * 1024 * 1024;
|
||||
/// Highest suspend count (MAXIMUM_SUSPEND_COUNT).
|
||||
const MAX_SUSPEND: u32 = 127;
|
||||
/// GetExitCodeThread result while the thread runs.
|
||||
const STILL_ACTIVE: u32 = 259;
|
||||
const CREATE_SUSPENDED: u32 = 4;
|
||||
const STACK_SIZE_PARAM_IS_A_RESERVATION: u32 = 0x0001_0000;
|
||||
pub(super) const THREAD_ALL_ACCESS: u32 = 0x001F_FFFF;
|
||||
const THREAD_TERMINATE: u32 = 1;
|
||||
const THREAD_SUSPEND_RESUME: u32 = 2;
|
||||
/// Rights that exist only on worker thread objects.
|
||||
pub(super) const WORKER_RIGHTS: u32 = THREAD_TERMINATE | THREAD_SUSPEND_RESUME;
|
||||
const ERROR_SIGNAL_REFUSED: u32 = 156;
|
||||
|
||||
/// Each thread slot holds a guard page, the stack, a guard page and the TEB.
|
||||
const THREAD_AREA: u64 = 0x0000_0006_0000_0000;
|
||||
const THREAD_STRIDE: u64 = 0x0100_0000;
|
||||
const TEB_OFFSET: u64 = 0x00F0_0000;
|
||||
const TEB_SIZE: u64 = 0x2000;
|
||||
const TEB_STACK_BASE: u64 = 0x08;
|
||||
const TEB_STACK_LIMIT: u64 = 0x10;
|
||||
const TEB_SELF: u64 = 0x30;
|
||||
|
||||
/// Return address of a thread's start routine. Nothing is mapped there.
|
||||
pub(crate) const THREAD_RETURN: u64 = 0xFFFF_FFFF_FFFE_0000;
|
||||
|
||||
/// How a service asked the scheduler to act after it completed.
|
||||
const SWITCH_NONE: u8 = 0;
|
||||
const SWITCH_SIGNAL: u8 = 1;
|
||||
const SWITCH_YIELD: u8 = 2;
|
||||
|
||||
/// Shared between the services, the import dispatcher and the scheduler.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SchedulerHooks {
|
||||
attached: AtomicBool,
|
||||
switch: AtomicU8,
|
||||
}
|
||||
|
||||
impl SchedulerHooks {
|
||||
pub(crate) fn is_attached(&self) -> bool {
|
||||
self.attached.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// An object other threads may wait for changed.
|
||||
pub(super) fn signal(&self) {
|
||||
if self.is_attached() {
|
||||
self.switch.fetch_max(SWITCH_SIGNAL, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
fn yield_turn(&self) {
|
||||
self.switch.store(SWITCH_YIELD, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Whether the dispatcher should stop the current thread after the call.
|
||||
pub(crate) fn switch_requested(&self) -> bool {
|
||||
self.switch.load(Ordering::SeqCst) != SWITCH_NONE
|
||||
}
|
||||
|
||||
/// Take the request; true if the thread gives up its turn.
|
||||
pub(crate) fn take_switch(&self) -> bool {
|
||||
self.switch.swap(SWITCH_NONE, Ordering::SeqCst) == SWITCH_YIELD
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum RunState {
|
||||
Ready,
|
||||
/// Waiting in a service; the sequence number orders waiters.
|
||||
Blocked(u64),
|
||||
}
|
||||
|
||||
pub(crate) struct GuestThread {
|
||||
teb: u64,
|
||||
/// Taken by the scheduler while the thread runs.
|
||||
pub(crate) cpu: Option<CpuState>,
|
||||
pub(crate) run: RunState,
|
||||
pub(crate) suspend: u32,
|
||||
/// What is left of a turn the thread interrupted by signaling.
|
||||
pub(crate) credit: Option<usize>,
|
||||
object: Arc<Mutex<Waitable>>,
|
||||
slot: Option<u64>,
|
||||
allocations: Vec<u64>,
|
||||
/// Set by ExitThread and TerminateThread.
|
||||
pub(crate) exit: Option<u32>,
|
||||
}
|
||||
|
||||
/// Objects a blocked thread waits for, captured when it first blocked.
|
||||
pub(super) struct PendingWait {
|
||||
pub(super) objects: Vec<Arc<Mutex<Waitable>>>,
|
||||
pub(super) all: bool,
|
||||
pub(super) deadline: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ThreadTable {
|
||||
pub(crate) threads: BTreeMap<u32, GuestThread>,
|
||||
/// Ready threads in the order they run.
|
||||
pub(crate) queue: VecDeque<u32>,
|
||||
pub(super) waits: BTreeMap<u64, PendingWait>,
|
||||
/// Main thread wait of a run that stopped on its budget, and the context
|
||||
/// that continues it.
|
||||
continued: Option<(CpuState, PendingWait)>,
|
||||
slots: BTreeSet<u64>,
|
||||
last_id: u32,
|
||||
pub(crate) sequence: u64,
|
||||
}
|
||||
|
||||
impl ThreadTable {
|
||||
fn id_of(&self, teb: u64) -> Option<u32> {
|
||||
self.threads
|
||||
.iter()
|
||||
.find(|(_, thread)| thread.teb == teb)
|
||||
.map(|(&id, _)| id)
|
||||
}
|
||||
|
||||
fn by_object(&mut self, object: &Arc<Mutex<Waitable>>) -> Option<&mut GuestThread> {
|
||||
self.threads
|
||||
.values_mut()
|
||||
.find(|thread| Arc::ptr_eq(&thread.object, object))
|
||||
}
|
||||
|
||||
/// Earliest deadline of any wait that is not suspended away.
|
||||
pub(crate) fn next_deadline(&self) -> Option<u64> {
|
||||
self.threads
|
||||
.values()
|
||||
.filter(|thread| thread.suspend == 0 && thread.run != RunState::Ready)
|
||||
.filter_map(|thread| self.waits.get(&thread.teb)?.deadline)
|
||||
.min()
|
||||
}
|
||||
}
|
||||
|
||||
/// Arguments of CreateThread.
|
||||
struct ThreadRequest {
|
||||
stack: u64,
|
||||
start: u64,
|
||||
parameter: u64,
|
||||
suspended: bool,
|
||||
/// `stack` is the reservation rather than the initial commitment.
|
||||
reservation: bool,
|
||||
id_output: u64,
|
||||
}
|
||||
|
||||
fn map_thread(
|
||||
memory: &mut GuestMemory,
|
||||
base: u64,
|
||||
stack: u64,
|
||||
allocations: &mut Vec<u64>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let low = base + PAGE_SIZE;
|
||||
let top = low + stack;
|
||||
let teb = base + TEB_OFFSET;
|
||||
for (address, size, permissions) in [
|
||||
(base, PAGE_SIZE, MemoryPermissions::NO_ACCESS),
|
||||
(low, stack, MemoryPermissions::READ_WRITE),
|
||||
(top, PAGE_SIZE, MemoryPermissions::NO_ACCESS),
|
||||
(teb, TEB_SIZE, MemoryPermissions::READ_WRITE),
|
||||
] {
|
||||
allocations.push(memory.map_thread_region(address, size as usize, permissions)?);
|
||||
}
|
||||
// A recycled TEB address must not inherit the previous thread's errno.
|
||||
let errno = memory.crt_errno_address(teb)?;
|
||||
memory.write_u32_bypass(errno, 0)?;
|
||||
memory.write_u64_bypass(teb + TEB_STACK_BASE, top)?;
|
||||
memory.write_u64_bypass(teb + TEB_STACK_LIMIT, low)?;
|
||||
memory.write_u64_bypass(teb + TEB_SELF, teb)
|
||||
}
|
||||
|
||||
impl ServicesState {
|
||||
/// Adopt the calling context as the main guest thread.
|
||||
pub(crate) fn attach_scheduler(&self, main: &CpuState) -> Result<u32, ExitReason> {
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
if self.hooks.attached.swap(true, Ordering::SeqCst) {
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
}
|
||||
// IDs are never reused, even by a later run.
|
||||
table.last_id = table.last_id.max(self.thread_id);
|
||||
table.threads.insert(
|
||||
self.thread_id,
|
||||
GuestThread {
|
||||
teb: main.gs_base,
|
||||
cpu: Some(main.clone()),
|
||||
run: RunState::Ready,
|
||||
suspend: 0,
|
||||
credit: None,
|
||||
object: Arc::new(Mutex::new(Waitable::Thread {
|
||||
id: self.thread_id,
|
||||
exit_code: None,
|
||||
})),
|
||||
slot: None,
|
||||
allocations: Vec::new(),
|
||||
exit: None,
|
||||
},
|
||||
);
|
||||
table.queue.push_back(self.thread_id);
|
||||
if let Some((context, wait)) = table.continued.take()
|
||||
&& context == *main
|
||||
{
|
||||
table.waits.insert(main.gs_base, wait);
|
||||
}
|
||||
Ok(self.thread_id)
|
||||
}
|
||||
|
||||
/// Reclaim every created thread. The main thread keeps its per-thread state.
|
||||
/// `continues` is its context if the run stopped on its budget; its pending
|
||||
/// wait is then kept for that context.
|
||||
pub(crate) fn detach_scheduler(&self, memory: &mut GuestMemory, continues: Option<&CpuState>) {
|
||||
let workers: Vec<u32> = {
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
let worker = |(&id, thread): (&u32, &GuestThread)| thread.slot.map(|_| id);
|
||||
table.threads.iter().filter_map(worker).collect()
|
||||
};
|
||||
for id in workers {
|
||||
self.end_thread(id, 0, memory);
|
||||
}
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
if let Some(context) = continues {
|
||||
let wait = table.waits.remove(&context.gs_base);
|
||||
table.continued = wait.map(|wait| (context.clone(), wait));
|
||||
}
|
||||
table.threads.clear();
|
||||
table.queue.clear();
|
||||
table.waits.clear();
|
||||
drop(table);
|
||||
self.hooks.switch.store(SWITCH_NONE, Ordering::SeqCst);
|
||||
self.hooks.attached.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Record a thread's exit code, signal its object and reclaim its state.
|
||||
pub(crate) fn end_thread(&self, id: u32, code: u32, memory: &mut GuestMemory) {
|
||||
let thread = {
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let Some(thread) = table.threads.remove(&id) else {
|
||||
return;
|
||||
};
|
||||
table.queue.retain(|&queued| queued != id);
|
||||
table.waits.remove(&thread.teb);
|
||||
if let Some(slot) = thread.slot {
|
||||
table.slots.remove(&slot);
|
||||
}
|
||||
thread
|
||||
};
|
||||
if let Waitable::Thread { exit_code, .. } =
|
||||
&mut *thread.object.lock().expect("guest waitable state")
|
||||
{
|
||||
*exit_code = Some(code);
|
||||
}
|
||||
self.abandon_mutexes(thread.teb);
|
||||
self.retire_thread_last_error(thread.teb);
|
||||
self.synch
|
||||
.lock()
|
||||
.expect("guest synchronization state")
|
||||
.retire_thread(thread.teb);
|
||||
memory
|
||||
.callback_frames
|
||||
.retain(|&(teb, _), _| teb != thread.teb);
|
||||
for base in thread.allocations {
|
||||
memory.release_thread_region(base);
|
||||
}
|
||||
self.hooks.signal();
|
||||
}
|
||||
|
||||
/// ID of the guest thread whose TEB is `teb`.
|
||||
pub(super) fn thread_id_of(&self, teb: u64) -> u32 {
|
||||
self.threads
|
||||
.lock()
|
||||
.expect("guest thread table")
|
||||
.id_of(teb)
|
||||
.unwrap_or(self.thread_id)
|
||||
}
|
||||
|
||||
/// Whether the main thread can still be named by its ID.
|
||||
pub(super) fn main_thread_alive(&self) -> bool {
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
!self.hooks.is_attached() || table.threads.contains_key(&self.thread_id)
|
||||
}
|
||||
|
||||
/// Thread object for an ID, if that thread is alive and not the main thread.
|
||||
pub(super) fn worker_object(&self, id: u32) -> Option<Arc<Mutex<Waitable>>> {
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
table
|
||||
.threads
|
||||
.get(&id)
|
||||
.filter(|thread| thread.slot.is_some())
|
||||
.map(|thread| Arc::clone(&thread.object))
|
||||
}
|
||||
|
||||
/// Thread object of the calling worker, or `None` in the main thread.
|
||||
pub(super) fn current_worker(&self, teb: u64) -> Option<Arc<Mutex<Waitable>>> {
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
let thread = table.threads.get(&table.id_of(teb)?)?;
|
||||
thread.slot.map(|_| Arc::clone(&thread.object))
|
||||
}
|
||||
|
||||
fn create_thread(
|
||||
&self,
|
||||
teb: u64,
|
||||
memory: &mut GuestMemory,
|
||||
request: &ThreadRequest,
|
||||
) -> Result<u64, ExitReason> {
|
||||
if request.id_output != 0 && memory.check_write(request.id_output, 4).is_err() {
|
||||
return self.fail(teb, ERROR_NOACCESS, 0);
|
||||
}
|
||||
// Without the reservation flag the size is an initial commitment, and
|
||||
// the reservation is at least the default.
|
||||
let stack = if request.stack == 0 || !request.reservation {
|
||||
request.stack.max(DEFAULT_STACK)
|
||||
} else {
|
||||
request.stack
|
||||
};
|
||||
let Some(stack) = stack
|
||||
.checked_next_multiple_of(ALLOCATION_GRANULARITY)
|
||||
.filter(|&size| size <= MAX_STACK)
|
||||
else {
|
||||
return self.fail(teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
let mut objects = self.objects.lock().expect("guest object state");
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let handle = objects.next_handle();
|
||||
let id = table.last_id.checked_add(4);
|
||||
let (Some(handle), Some(id), true) = (handle, id, table.threads.len() < MAX_THREADS) else {
|
||||
return self.fail(teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
// A slot the guest has mapped something into is skipped.
|
||||
let mut prepared = None;
|
||||
for slot in (0..2 * MAX_THREADS as u64).filter(|slot| !table.slots.contains(slot)) {
|
||||
let base = THREAD_AREA + slot * THREAD_STRIDE;
|
||||
let mut allocations = Vec::new();
|
||||
// The start routine is entered as if called: RSP is 8 modulo 16,
|
||||
// and above it are the return address and a 32-byte home area.
|
||||
let rsp = base + PAGE_SIZE + stack - 40;
|
||||
let mapped = map_thread(memory, base, stack, &mut allocations)
|
||||
.and_then(|()| memory.write_u64(rsp, THREAD_RETURN));
|
||||
if mapped.is_ok() {
|
||||
prepared = Some((slot, base, rsp, allocations));
|
||||
break;
|
||||
}
|
||||
for base in allocations {
|
||||
memory.release_thread_region(base);
|
||||
}
|
||||
if !matches!(mapped, Err(MemoryError::OverlappingRegion { .. })) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some((slot, base, rsp, allocations)) = prepared else {
|
||||
return self.fail(teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
if request.id_output != 0 {
|
||||
memory
|
||||
.write_u32(request.id_output, id)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
let mut cpu = CpuState::new(request.start, rsp);
|
||||
cpu.gs_base = base + TEB_OFFSET;
|
||||
cpu.set(Register::Rcx, request.parameter);
|
||||
let object = Arc::new(Mutex::new(Waitable::Thread {
|
||||
id,
|
||||
exit_code: None,
|
||||
}));
|
||||
objects.insert_handle(
|
||||
handle,
|
||||
GuestObject::Waitable {
|
||||
state: Arc::clone(&object),
|
||||
access: THREAD_ALL_ACCESS,
|
||||
},
|
||||
);
|
||||
table.slots.insert(slot);
|
||||
table.last_id = id;
|
||||
table.threads.insert(
|
||||
id,
|
||||
GuestThread {
|
||||
teb: base + TEB_OFFSET,
|
||||
cpu: Some(cpu),
|
||||
run: RunState::Ready,
|
||||
suspend: u32::from(request.suspended),
|
||||
credit: None,
|
||||
object,
|
||||
slot: Some(slot),
|
||||
allocations,
|
||||
exit: None,
|
||||
},
|
||||
);
|
||||
table.queue.push_back(id);
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
/// Thread object and granted rights behind a handle.
|
||||
fn thread_handle(&self, teb: u64, handle: u64) -> Result<(Arc<Mutex<Waitable>>, u32), u32> {
|
||||
if handle == CURRENT_THREAD {
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let id = table.id_of(teb).ok_or(ERROR_INVALID_HANDLE)?;
|
||||
let thread = table.threads.get_mut(&id).ok_or(ERROR_INVALID_HANDLE)?;
|
||||
return Ok((Arc::clone(&thread.object), THREAD_ALL_ACCESS));
|
||||
}
|
||||
let objects = self.objects.lock().expect("guest object state");
|
||||
match objects.handles.get(&handle) {
|
||||
Some(GuestObject::Waitable { state, access })
|
||||
if matches!(
|
||||
*state.lock().expect("guest waitable state"),
|
||||
Waitable::Thread { .. }
|
||||
) =>
|
||||
{
|
||||
Ok((Arc::clone(state), *access))
|
||||
}
|
||||
// Handles to the main thread from OpenThread name no object.
|
||||
Some(GuestObject::Thread(_)) => Err(ERROR_NOT_SUPPORTED),
|
||||
_ => Err(ERROR_INVALID_HANDLE),
|
||||
}
|
||||
}
|
||||
|
||||
/// Change another thread's suspend count and return the previous one.
|
||||
fn change_suspend(&self, teb: u64, handle: u64, resume: bool) -> Result<u64, ExitReason> {
|
||||
const FAILED: u64 = u32::MAX as u64;
|
||||
let (object, access) = match self.thread_handle(teb, handle) {
|
||||
Ok(found) => found,
|
||||
Err(error) => return self.fail(teb, error, FAILED),
|
||||
};
|
||||
if access & THREAD_SUSPEND_RESUME == 0 {
|
||||
return self.fail(teb, ERROR_ACCESS_DENIED, FAILED);
|
||||
}
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let Some(thread) = table.by_object(&object) else {
|
||||
return self.fail(teb, ERROR_ACCESS_DENIED, FAILED); // terminated
|
||||
};
|
||||
let previous = thread.suspend;
|
||||
if resume {
|
||||
thread.suspend = previous.saturating_sub(1);
|
||||
} else if previous >= MAX_SUSPEND {
|
||||
return self.fail(teb, ERROR_SIGNAL_REFUSED, FAILED);
|
||||
} else {
|
||||
thread.suspend = previous + 1;
|
||||
}
|
||||
drop(table);
|
||||
self.hooks.signal();
|
||||
Ok(u64::from(previous))
|
||||
}
|
||||
|
||||
fn terminate(
|
||||
&self,
|
||||
teb: u64,
|
||||
handle: u64,
|
||||
code: u32,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<u64, ExitReason> {
|
||||
let (object, access) = match self.thread_handle(teb, handle) {
|
||||
Ok(found) => found,
|
||||
Err(error) => return self.fail(teb, error, 0),
|
||||
};
|
||||
if access & THREAD_TERMINATE == 0 {
|
||||
return self.fail(teb, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let Some(id) = table
|
||||
.threads
|
||||
.iter()
|
||||
.find(|(_, thread)| Arc::ptr_eq(&thread.object, &object))
|
||||
.map(|(&id, _)| id)
|
||||
else {
|
||||
return self.fail(teb, ERROR_ACCESS_DENIED, 0); // already terminated
|
||||
};
|
||||
let thread = table.threads.get_mut(&id).expect("thread found above");
|
||||
if thread.teb == teb {
|
||||
thread.exit = Some(code);
|
||||
return Err(ExitReason::GuestThreadExited);
|
||||
}
|
||||
drop(table);
|
||||
self.end_thread(id, code, memory);
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "CreateThread", move |args, cpu, memory| {
|
||||
let arg = |index| args.get(index, memory).map_err(ExitReason::MemoryFault);
|
||||
let attributes = arg(0)?;
|
||||
let flags = arg(4)? as u32;
|
||||
let request = ThreadRequest {
|
||||
stack: arg(1)?,
|
||||
start: arg(2)?,
|
||||
parameter: arg(3)?,
|
||||
suspended: flags & CREATE_SUSPENDED != 0,
|
||||
reservation: flags & STACK_SIZE_PARAM_IS_A_RESERVATION != 0,
|
||||
id_output: arg(5)?,
|
||||
};
|
||||
if !s.hooks.is_attached() || attributes != 0 {
|
||||
return s.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
if flags & !(CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION) != 0 {
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
s.create_thread(cpu.gs_base, memory, &request)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "ExitThread", move |args, cpu, _| {
|
||||
let mut table = s.threads.lock().expect("guest thread table");
|
||||
let Some(id) = table.id_of(cpu.gs_base) else {
|
||||
return Err(ExitReason::IllegalInstruction(0xFE));
|
||||
};
|
||||
table.threads.get_mut(&id).expect("thread found above").exit = Some(args.rcx as u32);
|
||||
Err(ExitReason::GuestThreadExited)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "TerminateThread", move |args, cpu, memory| {
|
||||
s.terminate(cpu.gs_base, args.rcx, args.rdx as u32, memory)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "GetExitCodeThread", move |args, cpu, memory| {
|
||||
let (object, access) = match s.thread_handle(cpu.gs_base, args.rcx) {
|
||||
Ok(found) => found,
|
||||
Err(error) => return s.fail(cpu.gs_base, error, 0),
|
||||
};
|
||||
if access & THREAD_QUERY_RIGHTS == 0 {
|
||||
return s.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
let code = match &*object.lock().expect("guest waitable state") {
|
||||
Waitable::Thread { exit_code, .. } => exit_code.unwrap_or(STILL_ACTIVE),
|
||||
_ => return s.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0),
|
||||
};
|
||||
if memory.write_u32(args.rdx, code).is_err() {
|
||||
return s.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for (symbol, resume) in [("SuspendThread", false), ("ResumeThread", true)] {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, _| {
|
||||
s.change_suspend(cpu.gs_base, args.rcx, resume)
|
||||
});
|
||||
}
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "SwitchToThread", move |_, cpu, _| {
|
||||
let table = s.threads.lock().expect("guest thread table");
|
||||
let current = table.id_of(cpu.gs_base);
|
||||
let other = table.threads.iter().any(|(&id, thread)| {
|
||||
Some(id) != current && thread.run == RunState::Ready && thread.suspend == 0
|
||||
});
|
||||
drop(table);
|
||||
if other {
|
||||
s.hooks.yield_turn();
|
||||
}
|
||||
Ok(u64::from(other))
|
||||
});
|
||||
|
||||
for symbol in [
|
||||
"CreateThread",
|
||||
"ExitThread",
|
||||
"TerminateThread",
|
||||
"GetExitCodeThread",
|
||||
"SuspendThread",
|
||||
"ResumeThread",
|
||||
"SwitchToThread",
|
||||
] {
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
const _: () = assert!(THREAD_ALL_ACCESS & SYNCHRONIZE != 0);
|
||||
}
|
||||
@@ -54,6 +54,16 @@ struct Socket {
|
||||
}
|
||||
|
||||
impl Winsock {
|
||||
/// Sockets the guest has open.
|
||||
pub(super) fn open_count(&self) -> usize {
|
||||
self.sockets.len()
|
||||
}
|
||||
|
||||
/// Process exit: every socket is closed.
|
||||
pub(super) fn close_all(&mut self) {
|
||||
self.sockets.clear();
|
||||
}
|
||||
|
||||
fn socket(&self, handle: u64) -> Result<&Socket, u32> {
|
||||
if self.refs == 0 {
|
||||
return Err(WSANOTINITIALISED);
|
||||
|
||||
@@ -35,6 +35,7 @@ pub struct Control {
|
||||
pub rounding: Rounding,
|
||||
pub denormals_are_zero: bool,
|
||||
pub flush_to_zero: bool,
|
||||
pub overflow_masked: bool,
|
||||
pub underflow_masked: bool,
|
||||
}
|
||||
|
||||
@@ -49,6 +50,7 @@ impl Control {
|
||||
},
|
||||
denormals_are_zero: mxcsr & 1 << 6 != 0,
|
||||
flush_to_zero: mxcsr & 1 << 15 != 0,
|
||||
overflow_masked: mxcsr & 1 << 10 != 0,
|
||||
underflow_masked: mxcsr & 1 << 11 != 0,
|
||||
}
|
||||
}
|
||||
@@ -263,6 +265,14 @@ fn round(
|
||||
flags |= PRECISION;
|
||||
}
|
||||
if leading > format.bias() {
|
||||
if !control.overflow_masked {
|
||||
// No result is delivered. Precision is reported only if rounding
|
||||
// with an unbounded exponent was inexact.
|
||||
return Outcome {
|
||||
bits: 0,
|
||||
flags: OVERFLOW | if inexact { PRECISION } else { 0 },
|
||||
};
|
||||
}
|
||||
let to_infinity = match control.rounding {
|
||||
Rounding::Nearest => true,
|
||||
Rounding::Down => sign,
|
||||
|
||||
@@ -3,14 +3,16 @@
|
||||
//! Process startup for trusted, original PE32+ fixtures.
|
||||
|
||||
use crate::dbt::DbtMetrics;
|
||||
use crate::tls::TlsError;
|
||||
use crate::{
|
||||
CpuState, DbtEngine, ExecutionResult, ImportRegistry, LoadedImage, MemoryError,
|
||||
CpuState, DbtEngine, ExecutionResult, ExitReason, ImportRegistry, LoadedImage, MemoryError,
|
||||
MemoryPermissions, ParsedPe, PeError, RelocationReport, apply_relocations,
|
||||
execute_tls_callbacks, parse_tls_directory, setup_tls,
|
||||
};
|
||||
|
||||
const STACK_SIZE: usize = 64 * 1024;
|
||||
const JIT_CAPACITY: usize = 1024 * 1024;
|
||||
const RETURN_SENTINEL_PAGE_SIZE: usize = 0x1000;
|
||||
/// The TEB is placed this far above the TLS base and spans two 4 KiB pages.
|
||||
const TEB_OFFSET: u64 = 0x10000;
|
||||
const TEB_SIZE: usize = 0x2000;
|
||||
@@ -95,6 +97,7 @@ pub fn run_synthetic_startup_with_observer(
|
||||
entry_rva: pe.entry_point_rva,
|
||||
});
|
||||
let mut image = pe.load_at_base(bytes, layout.image_base)?;
|
||||
let image_base_field = image.image_base_field;
|
||||
let memory = &mut image.memory;
|
||||
memory
|
||||
.fetch_instruction_byte(image.entry_point)
|
||||
@@ -104,6 +107,12 @@ pub fn run_synthetic_startup_with_observer(
|
||||
});
|
||||
|
||||
let relocations = apply_relocations(&pe, bytes, layout.image_base, memory)?;
|
||||
// The mapped optional header names the base the image is loaded at. This
|
||||
// is written after the relocations so that an entry aimed at the field
|
||||
// itself cannot leave it holding anything else.
|
||||
memory
|
||||
.write_u64_bypass(image_base_field, layout.image_base)
|
||||
.map_err(PeError::SectionMappingError)?;
|
||||
observe(StartupEvent::Relocated {
|
||||
applied_dir64: relocations.applied_dir64,
|
||||
});
|
||||
@@ -123,6 +132,14 @@ pub fn run_synthetic_startup_with_observer(
|
||||
}
|
||||
|
||||
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
// Keep guest code and data out of the page that holds the return
|
||||
// addresses the engine intercepts. An image or layout that already covers
|
||||
// it is refused here, and a later guest allocation there fails.
|
||||
memory.map_region(
|
||||
crate::imports::RETURN_SENTINEL_PAGE,
|
||||
RETURN_SENTINEL_PAGE_SIZE,
|
||||
MemoryPermissions::NO_ACCESS,
|
||||
)?;
|
||||
|
||||
map_teb(memory, teb_base, &layout, stack_base)?;
|
||||
|
||||
@@ -132,28 +149,59 @@ pub fn run_synthetic_startup_with_observer(
|
||||
let mut tls_cpu = CpuState::new(image.entry_point, layout.stack_top);
|
||||
tls_cpu.gs_base = teb_base;
|
||||
let mut tls_callbacks = 0;
|
||||
let mut exited_in_tls = None;
|
||||
if let Some(tls) = &tls {
|
||||
tls_callbacks = execute_tls_callbacks(
|
||||
&tls.callbacks,
|
||||
layout.image_base,
|
||||
pe.image_base,
|
||||
layout.stack_top,
|
||||
&mut tls_cpu,
|
||||
memory,
|
||||
&mut engine,
|
||||
)?;
|
||||
// One callback at a time, so that a callback which ends the process
|
||||
// is seen as an exit and not as a fault, and the callbacks that
|
||||
// finished before it are counted.
|
||||
for callback in &tls.callbacks {
|
||||
match execute_tls_callbacks(
|
||||
std::slice::from_ref(callback),
|
||||
layout.image_base,
|
||||
pe.image_base,
|
||||
layout.stack_top,
|
||||
&mut tls_cpu,
|
||||
memory,
|
||||
&mut engine,
|
||||
) {
|
||||
Ok(_) => tls_callbacks += 1,
|
||||
Err(TlsError::CallbackExecutionFault(ExitReason::ProcessExit(status))) => {
|
||||
exited_in_tls = Some(status);
|
||||
break;
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
observe(StartupEvent::TlsCompleted {
|
||||
callbacks: tls_callbacks,
|
||||
native_steps: engine.metrics.instructions_executed,
|
||||
});
|
||||
if let Some(status) = exited_in_tls {
|
||||
// The process ended before its entry point: the remaining callbacks
|
||||
// and the entry point do not run, and this is an ordinary outcome.
|
||||
return Ok(StartupResult {
|
||||
image,
|
||||
relocations,
|
||||
bound_imports,
|
||||
tls_callbacks,
|
||||
execution: ExecutionResult {
|
||||
instructions_executed: 0,
|
||||
final_state: tls_cpu,
|
||||
exit_reason: ExitReason::ProcessExit(status),
|
||||
},
|
||||
dbt_metrics: engine.metrics,
|
||||
});
|
||||
}
|
||||
observe(StartupEvent::Entering {
|
||||
step_limit: entry_budget,
|
||||
});
|
||||
|
||||
// Model function entry with the Win64 32-byte home area and return slot.
|
||||
// The synthetic entry point terminates with HLT.
|
||||
// An entry point may end with HLT, call ExitProcess, or return: the
|
||||
// return slot holds the address that ends the process with EAX.
|
||||
memory.write_u64_bypass(layout.stack_top - 40, crate::imports::ENTRY_RETURN)?;
|
||||
let mut entry_cpu = CpuState::new(image.entry_point, layout.stack_top - 40);
|
||||
entry_cpu.gs_base = teb_base;
|
||||
let execution = engine.run(&mut entry_cpu, memory, entry_budget);
|
||||
|
||||
+882
-33
@@ -11,11 +11,39 @@ use crate::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use crate::pe::ParsedPe;
|
||||
use std::fmt;
|
||||
|
||||
/// Most callbacks one TLS directory may list.
|
||||
pub const MAX_TLS_CALLBACKS: usize = 64;
|
||||
|
||||
/// Bytes below the stack top that a callback is entered with: the return
|
||||
/// address and the 32-byte home space the Win64 convention gives every callee.
|
||||
const CALLBACK_FRAME: u64 = 40;
|
||||
|
||||
/// Errors arising during TLS setup or callback invocation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum TlsError {
|
||||
DirectoryOutOfBounds { rva: u32 },
|
||||
InvalidTemplateRange { start: u64, end: u64 },
|
||||
DirectoryOutOfBounds {
|
||||
rva: u32,
|
||||
},
|
||||
InvalidTemplateRange {
|
||||
start: u64,
|
||||
end: u64,
|
||||
},
|
||||
/// `AddressOfCallbacks` is not zero and not inside a section of the image.
|
||||
CallbackArrayOutOfBounds {
|
||||
address: u64,
|
||||
},
|
||||
/// The callback array leaves its section before a null entry.
|
||||
CallbackArrayUnterminated {
|
||||
address: u64,
|
||||
},
|
||||
/// The callback array lists more than [`MAX_TLS_CALLBACKS`] entries.
|
||||
TooManyCallbacks {
|
||||
limit: usize,
|
||||
},
|
||||
/// The stack cannot hold a callback's entry frame or is not 16-byte aligned.
|
||||
InvalidCallbackStack {
|
||||
stack_top: u64,
|
||||
},
|
||||
CallbackExecutionFault(ExitReason),
|
||||
Memory(MemoryError),
|
||||
}
|
||||
@@ -32,6 +60,27 @@ impl fmt::Display for TlsError {
|
||||
"invalid TLS template range: 0x{start:016x}..0x{end:016x}"
|
||||
)
|
||||
}
|
||||
Self::CallbackArrayOutOfBounds { address } => {
|
||||
write!(
|
||||
f,
|
||||
"TLS callback array at 0x{address:016x} is outside the image"
|
||||
)
|
||||
}
|
||||
Self::CallbackArrayUnterminated { address } => {
|
||||
write!(
|
||||
f,
|
||||
"TLS callback array at 0x{address:016x} has no null entry in its section"
|
||||
)
|
||||
}
|
||||
Self::TooManyCallbacks { limit } => {
|
||||
write!(f, "TLS callback array lists more than {limit} callbacks")
|
||||
}
|
||||
Self::InvalidCallbackStack { stack_top } => {
|
||||
write!(
|
||||
f,
|
||||
"stack top 0x{stack_top:016x} cannot hold an aligned TLS callback frame"
|
||||
)
|
||||
}
|
||||
Self::CallbackExecutionFault(e) => {
|
||||
write!(f, "fault during TLS callback execution: {e}")
|
||||
}
|
||||
@@ -78,7 +127,7 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
) as usize;
|
||||
|
||||
// TLS directory is directory index 9 (offset 112 + 9 * 8 = 184 in Optional Header)
|
||||
if size_of_opt < 192 || bytes.len() < opt_offset + 188 {
|
||||
if size_of_opt < 192 || bytes.len() < opt_offset + 192 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
@@ -114,24 +163,7 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
u32::from_le_bytes(bytes[tls_off + 32..tls_off + 36].try_into().unwrap());
|
||||
let characteristics = u32::from_le_bytes(bytes[tls_off + 36..tls_off + 40].try_into().unwrap());
|
||||
|
||||
let mut callbacks = Vec::new();
|
||||
if callbacks_address >= pe.image_base {
|
||||
let cb_rva = (callbacks_address - pe.image_base) as u32;
|
||||
if let Some(cb_off) = pe.rva_to_file_offset(cb_rva) {
|
||||
let mut curr = cb_off;
|
||||
while curr + 8 <= bytes.len() {
|
||||
let target = u64::from_le_bytes(bytes[curr..curr + 8].try_into().unwrap());
|
||||
if target == 0 {
|
||||
break;
|
||||
}
|
||||
callbacks.push(target);
|
||||
curr += 8;
|
||||
if callbacks.len() >= 64 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let callbacks = read_callbacks(bytes, pe, callbacks_address)?;
|
||||
|
||||
Ok(Some(TlsDirectory {
|
||||
raw_data_start_va,
|
||||
@@ -144,9 +176,96 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
}))
|
||||
}
|
||||
|
||||
/// Read the null-terminated callback array that `address` names.
|
||||
///
|
||||
/// A null `address` means the image has no callbacks. Any other value must be a
|
||||
/// virtual address inside one section, and the array must reach its null entry
|
||||
/// inside that section. Bytes past the section's file data, up to its virtual
|
||||
/// size, are zero in the loaded image and are read as zero here.
|
||||
fn read_callbacks(bytes: &[u8], pe: &ParsedPe, address: u64) -> Result<Vec<u64>, TlsError> {
|
||||
if address == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let (section, start) = address
|
||||
.checked_sub(pe.image_base)
|
||||
.and_then(|rva| u32::try_from(rva).ok())
|
||||
.and_then(|rva| {
|
||||
pe.sections.iter().find_map(|section| {
|
||||
let offset = rva.checked_sub(section.virtual_address)?;
|
||||
let extent = section.virtual_size.max(section.raw_data_size);
|
||||
(offset < extent).then_some((section, u64::from(offset)))
|
||||
})
|
||||
})
|
||||
.ok_or(TlsError::CallbackArrayOutOfBounds { address })?;
|
||||
let extent = u64::from(section.virtual_size.max(section.raw_data_size));
|
||||
let byte_at = |offset: u64| -> Option<u8> {
|
||||
if offset >= extent {
|
||||
None
|
||||
} else if offset >= u64::from(section.raw_data_size) {
|
||||
Some(0)
|
||||
} else {
|
||||
let file = u64::from(section.raw_data_ptr) + offset;
|
||||
bytes.get(usize::try_from(file).ok()?).copied()
|
||||
}
|
||||
};
|
||||
|
||||
let mut callbacks = Vec::new();
|
||||
let mut offset = start;
|
||||
loop {
|
||||
let mut entry = [0u8; 8];
|
||||
for byte in &mut entry {
|
||||
*byte = byte_at(offset).ok_or(TlsError::CallbackArrayUnterminated { address })?;
|
||||
offset += 1;
|
||||
}
|
||||
let target = u64::from_le_bytes(entry);
|
||||
if target == 0 {
|
||||
return Ok(callbacks);
|
||||
}
|
||||
if callbacks.len() == MAX_TLS_CALLBACKS {
|
||||
return Err(TlsError::TooManyCallbacks {
|
||||
limit: MAX_TLS_CALLBACKS,
|
||||
});
|
||||
}
|
||||
callbacks.push(target);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes reserved at `thread_tls_base` for the thread's TLS pointer array.
|
||||
const TLS_ARRAY_SIZE: usize = 0x1000;
|
||||
|
||||
/// Bytes read per step when a template is checked and then copied into its
|
||||
/// block.
|
||||
const TEMPLATE_COPY_CHUNK: usize = 4096;
|
||||
|
||||
/// Smallest template copied into the zeroed block instead of a staging buffer.
|
||||
///
|
||||
/// Release timings of original synthetic templates on an Apple M2 Pro put the
|
||||
/// point where a second buffer dominates at 64 KiB. Below that, one read into
|
||||
/// a staging buffer is as fast or faster.
|
||||
const DIRECT_TEMPLATE_MIN: usize = 64 * 1024;
|
||||
|
||||
/// Templates at least this big keep the single staged read. On the same
|
||||
/// machine, proving the bytes readable and then copying them was no faster
|
||||
/// than the staging buffer once the template reached 1 MiB.
|
||||
const DIRECT_TEMPLATE_LIMIT: usize = 1024 * 1024;
|
||||
|
||||
/// Set up TLS runtime state in guest memory:
|
||||
/// 1. Assign TLS index (e.g. 0) at `index_address`.
|
||||
/// 2. Allocate and initialize per-thread TLS storage from the template.
|
||||
/// 1. Assign TLS index 0 at `index_address`.
|
||||
/// 2. Map the thread's TLS pointer array at `thread_tls_base`.
|
||||
/// 3. Map the thread's data block one page above it, initialized from the
|
||||
/// template and zero fill, and store its address in the array slot of the
|
||||
/// index.
|
||||
///
|
||||
/// `thread_tls_base` is the value the thread environment block holds as its
|
||||
/// TLS pointer. Compiled code loads that pointer, indexes it by the module's
|
||||
/// TLS index to find the data block, and then adds a variable's offset, so the
|
||||
/// array and the data are separate regions.
|
||||
///
|
||||
/// The block is the template followed by `SizeOfZeroFill` zero bytes. A
|
||||
/// template of at least 64 KiB and below 1 MiB is proved readable and then
|
||||
/// copied into a zeroed block. Every other size is read once into a staging
|
||||
/// buffer that initializes the block. Either way, a template that cannot be
|
||||
/// read leaves the pointer array unmapped.
|
||||
pub fn setup_tls(
|
||||
tls: &TlsDirectory,
|
||||
loaded_base: u64,
|
||||
@@ -181,31 +300,97 @@ pub fn setup_tls(
|
||||
let total_size = template_size + (tls.size_of_zero_fill as usize);
|
||||
|
||||
if total_size > 0 {
|
||||
// Read template bytes from image
|
||||
let mut template_data = vec![0u8; template_size];
|
||||
if template_size > 0 {
|
||||
memory.read_bytes(actual_start, &mut template_data)?;
|
||||
}
|
||||
let direct = (DIRECT_TEMPLATE_MIN..DIRECT_TEMPLATE_LIMIT).contains(&template_size);
|
||||
// The read happens before anything is mapped, so a missing or
|
||||
// unreadable template does not leave a pointer array behind.
|
||||
let staged = if direct {
|
||||
prove_template_readable(memory, actual_start, template_size)?;
|
||||
None
|
||||
} else {
|
||||
let mut staged = vec![0u8; template_size];
|
||||
if template_size > 0 {
|
||||
memory.read_bytes(actual_start, &mut staged)?;
|
||||
}
|
||||
Some(staged)
|
||||
};
|
||||
|
||||
// Allocate per-thread TLS block
|
||||
// Allocate the pointer array and the per-thread TLS block.
|
||||
let block_base = thread_tls_base
|
||||
.checked_add(TLS_ARRAY_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let page_size = 4096;
|
||||
let map_size = (total_size + page_size - 1) & !(page_size - 1);
|
||||
memory.map_region_with_data(
|
||||
memory.map_region(
|
||||
thread_tls_base,
|
||||
map_size,
|
||||
TLS_ARRAY_SIZE,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&template_data,
|
||||
)?;
|
||||
if let Some(staged) = staged.as_deref() {
|
||||
memory.map_region_with_data(
|
||||
block_base,
|
||||
map_size,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
staged,
|
||||
)?;
|
||||
} else {
|
||||
memory.map_region(block_base, map_size, MemoryPermissions::READ_WRITE)?;
|
||||
copy_template(memory, actual_start, block_base, template_size)?;
|
||||
}
|
||||
// Slot 0 belongs to the index assigned above.
|
||||
memory.write_u64(thread_tls_base, block_base)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read every template byte, discarding the contents.
|
||||
///
|
||||
/// Failure here means the template is not available. Callers map the block
|
||||
/// only after this returns.
|
||||
fn prove_template_readable(memory: &GuestMemory, addr: u64, len: usize) -> Result<(), TlsError> {
|
||||
let mut chunk = [0u8; TEMPLATE_COPY_CHUNK];
|
||||
let mut offset = 0usize;
|
||||
while offset < len {
|
||||
let n = (len - offset).min(TEMPLATE_COPY_CHUNK);
|
||||
let at = addr
|
||||
.checked_add(offset as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
memory.read_bytes(at, &mut chunk[..n])?;
|
||||
offset += n;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copy `len` bytes from `src` to `dst`. `dst` is already zeroed, which is the
|
||||
/// template's `SizeOfZeroFill` and the rounded tail of the block.
|
||||
fn copy_template(memory: &mut GuestMemory, src: u64, dst: u64, len: usize) -> Result<(), TlsError> {
|
||||
let mut chunk = [0u8; TEMPLATE_COPY_CHUNK];
|
||||
let mut offset = 0usize;
|
||||
while offset < len {
|
||||
let n = (len - offset).min(TEMPLATE_COPY_CHUNK);
|
||||
let from = src
|
||||
.checked_add(offset as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let to = dst
|
||||
.checked_add(offset as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
memory.read_bytes(from, &mut chunk[..n])?;
|
||||
memory.write_bytes(to, &chunk[..n])?;
|
||||
offset += n;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute all registered TLS callbacks in sequence.
|
||||
/// Signature: void (NTAPI *PIMAGE_TLS_CALLBACK)(PVOID DllHandle, DWORD Reason, PVOID Reserved);
|
||||
/// - RCX = DllHandle (loaded_base)
|
||||
/// - RDX = Reason (DLL_PROCESS_ATTACH = 1)
|
||||
/// - R8 = Reserved (0)
|
||||
///
|
||||
/// Each callback is entered as after a CALL from a 16-byte aligned stack: RSP
|
||||
/// is `stack_top - 40`, holding the return address below 32 bytes of home
|
||||
/// space. A `stack_top` that is not 16-byte aligned or cannot hold that frame
|
||||
/// is rejected before any callback runs.
|
||||
pub fn execute_tls_callbacks(
|
||||
callbacks: &[u64],
|
||||
loaded_base: u64,
|
||||
@@ -215,6 +400,12 @@ pub fn execute_tls_callbacks(
|
||||
memory: &mut GuestMemory,
|
||||
dbt: &mut DbtEngine,
|
||||
) -> Result<usize, TlsError> {
|
||||
if callbacks.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
if stack_top < CALLBACK_FRAME || !stack_top.is_multiple_of(16) {
|
||||
return Err(TlsError::InvalidCallbackStack { stack_top });
|
||||
}
|
||||
let delta = (loaded_base as i128) - (preferred_base as i128);
|
||||
let mut executed_count = 0;
|
||||
|
||||
@@ -224,7 +415,7 @@ pub fn execute_tls_callbacks(
|
||||
// Reset CPU state for callback execution adhering to Win64 ABI
|
||||
cpu.rip = actual_cb_va;
|
||||
// Stack pointer aligned with 32-byte shadow space + return address
|
||||
let rsp = stack_top - 40;
|
||||
let rsp = stack_top - CALLBACK_FRAME;
|
||||
cpu.set(Register::Rsp, rsp);
|
||||
// Write synthetic magic return address (0xFFFF_FFFF_FFFF_0000) into [RSP]
|
||||
let magic_ret = 0xFFFF_FFFF_FFFF_0000u64;
|
||||
@@ -261,3 +452,661 @@ pub fn execute_tls_callbacks(
|
||||
|
||||
Ok(executed_count)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
//! Expectations come from Microsoft's public PE Format page (the TLS
|
||||
//! directory: `AddressOfCallbacks` is a virtual address of a null-terminated
|
||||
//! array, and a callback is `void cb(PVOID DllHandle, DWORD Reason, PVOID
|
||||
//! Reserved)`) and its x64 calling convention page (the stack is 16-byte
|
||||
//! aligned before a call, the caller provides 32 bytes of home space, and
|
||||
//! the first three integer arguments are in RCX, RDX and R8). The headers
|
||||
//! and code bytes below are original. Nothing here ran on Windows.
|
||||
|
||||
use super::*;
|
||||
use crate::pe::PeSection;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
const IMAGE_BASE: u64 = 0x1_4000_0000;
|
||||
const SECTION_RVA: u32 = 0x1000;
|
||||
const SECTION_FILE: usize = 0x400;
|
||||
const SECTION_SIZE: u32 = 0x400;
|
||||
/// Offset of the optional header: `e_lfanew` (0x80), signature, COFF header.
|
||||
const OPTIONAL_HEADER: usize = 0x80 + 24;
|
||||
|
||||
fn parsed(virtual_size: u32) -> ParsedPe {
|
||||
ParsedPe {
|
||||
machine: 0x8664,
|
||||
number_of_sections: 1,
|
||||
time_date_stamp: 0,
|
||||
image_base: IMAGE_BASE,
|
||||
section_alignment: 0x1000,
|
||||
file_alignment: 0x200,
|
||||
size_of_image: 0x3000,
|
||||
size_of_headers: 0x400,
|
||||
entry_point_rva: 0,
|
||||
sections: vec![PeSection {
|
||||
name: ".rdata".into(),
|
||||
virtual_address: SECTION_RVA,
|
||||
virtual_size,
|
||||
raw_data_ptr: SECTION_FILE as u32,
|
||||
raw_data_size: SECTION_SIZE,
|
||||
characteristics: crate::pe::IMAGE_SCN_MEM_READ,
|
||||
permissions: MemoryPermissions::READ_ONLY,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
/// A file with one section holding a TLS directory at its start and the
|
||||
/// callback `entries` at `array_rva`. The directory names `callbacks_address`.
|
||||
/// Every byte after the section's file data is 0xCC.
|
||||
fn file(callbacks_address: u64, array_rva: u32, entries: &[u64]) -> Vec<u8> {
|
||||
let section_end = SECTION_FILE + SECTION_SIZE as usize;
|
||||
let mut bytes = vec![0u8; section_end];
|
||||
bytes.resize(section_end + 0x200, 0xCC);
|
||||
bytes[0x3C..0x40].copy_from_slice(&0x80u32.to_le_bytes());
|
||||
// SizeOfOptionalHeader: a PE32+ optional header with 16 data directories.
|
||||
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
|
||||
// Data directory 9 (TLS): RVA and size.
|
||||
let entry = OPTIONAL_HEADER + 112 + 9 * 8;
|
||||
bytes[entry..entry + 4].copy_from_slice(&SECTION_RVA.to_le_bytes());
|
||||
bytes[entry + 4..entry + 8].copy_from_slice(&40u32.to_le_bytes());
|
||||
// IMAGE_TLS_DIRECTORY64.AddressOfCallBacks is its fourth 8-byte field.
|
||||
bytes[SECTION_FILE + 24..SECTION_FILE + 32]
|
||||
.copy_from_slice(&callbacks_address.to_le_bytes());
|
||||
let mut at = SECTION_FILE + (array_rva - SECTION_RVA) as usize;
|
||||
for entry in entries {
|
||||
bytes[at..at + 8].copy_from_slice(&entry.to_le_bytes());
|
||||
at += 8;
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
fn callbacks_of(bytes: &[u8], pe: &ParsedPe) -> Result<Vec<u64>, TlsError> {
|
||||
parse_tls_directory(bytes, pe).map(|tls| tls.expect("a TLS directory").callbacks)
|
||||
}
|
||||
|
||||
const ARRAY_RVA: u32 = 0x1100;
|
||||
const ARRAY: u64 = IMAGE_BASE + ARRAY_RVA as u64;
|
||||
const FIRST: u64 = IMAGE_BASE + 0x2000;
|
||||
const SECOND: u64 = IMAGE_BASE + 0x2010;
|
||||
|
||||
#[test]
|
||||
fn callbacks_are_read_in_order_up_to_the_null_entry() {
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &[FIRST, SECOND, 0, IMAGE_BASE + 0x2020]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Ok(vec![FIRST, SECOND])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_callbacks_address_means_no_callbacks() {
|
||||
let bytes = file(0, ARRAY_RVA, &[FIRST, 0]);
|
||||
assert_eq!(callbacks_of(&bytes, &parsed(SECTION_SIZE)), Ok(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_outside_the_image_is_rejected() {
|
||||
for address in [8, IMAGE_BASE - 8, IMAGE_BASE + 0x800, IMAGE_BASE + 0x5000] {
|
||||
let bytes = file(address, ARRAY_RVA, &[FIRST, 0]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::CallbackArrayOutOfBounds { address }),
|
||||
"{address:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_address_is_not_truncated_to_32_bits() {
|
||||
// The low 32 bits of the offset name the real array.
|
||||
let address = ARRAY + (1 << 32);
|
||||
let bytes = file(address, ARRAY_RVA, &[FIRST, 0]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::CallbackArrayOutOfBounds { address })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_must_end_inside_its_section() {
|
||||
// Two entries fill the last 16 bytes of the section; the file goes on.
|
||||
let rva = SECTION_RVA + SECTION_SIZE - 16;
|
||||
let address = IMAGE_BASE + u64::from(rva);
|
||||
let bytes = file(address, rva, &[FIRST, SECOND]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::CallbackArrayUnterminated { address })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_fill_after_the_section_file_data_ends_the_array() {
|
||||
// The section is larger in memory than in the file, so the bytes after
|
||||
// its file data are zero when loaded, whatever follows in the file.
|
||||
let rva = SECTION_RVA + SECTION_SIZE - 16;
|
||||
let address = IMAGE_BASE + u64::from(rva);
|
||||
let bytes = file(address, rva, &[FIRST, SECOND]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE + 0x100)),
|
||||
Ok(vec![FIRST, SECOND])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_over_the_limit_is_rejected() {
|
||||
let entries: Vec<u64> = (0..65).map(|index| FIRST + index * 16).collect();
|
||||
let mut at_limit = entries[..MAX_TLS_CALLBACKS].to_vec();
|
||||
at_limit.push(0);
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &at_limit);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Ok(entries[..64].to_vec())
|
||||
);
|
||||
|
||||
let mut over = entries.clone();
|
||||
over.push(0);
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &over);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::TooManyCallbacks { limit: 64 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_cut_inside_the_tls_data_directory_has_no_tls_directory() {
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &[FIRST, 0]);
|
||||
let entry = OPTIONAL_HEADER + 112 + 9 * 8;
|
||||
for length in entry..entry + 8 {
|
||||
let directory = parse_tls_directory(&bytes[..length], &parsed(SECTION_SIZE));
|
||||
assert!(matches!(directory, Ok(None)), "length {length:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
const CODE: u64 = 0x40_0000;
|
||||
const STACK_TOP: u64 = 0x80_0000;
|
||||
const SENTINEL: u64 = 0xFFFF_FFFF_FFFF_0000;
|
||||
|
||||
/// Code at `CODE`, a 4 KiB stack below `STACK_TOP` and a fresh translator.
|
||||
fn guest(code: &[u8]) -> (CpuState, GuestMemory, DbtEngine) {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(CODE, 0x1000, MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(STACK_TOP - 0x1000, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
(
|
||||
CpuState::new(0, 0),
|
||||
memory,
|
||||
DbtEngine::new(64 * 1024).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Two callbacks 16 bytes apart. Each shifts RAX left by four bits and sets
|
||||
/// its own number in the low bits, so RAX records the order they ran in.
|
||||
const TAGGING: [u8; 25] = [
|
||||
0x48, 0xC1, 0xE0, 0x04, // shl rax, 4
|
||||
0x48, 0x83, 0xC8, 0x01, // or rax, 1
|
||||
0xC3, // ret
|
||||
0, 0, 0, 0, 0, 0, 0, // padding
|
||||
0x48, 0xC1, 0xE0, 0x04, // shl rax, 4
|
||||
0x48, 0x83, 0xC8, 0x02, // or rax, 2
|
||||
0xC3, // ret
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn a_callback_is_entered_with_the_win64_arguments_and_frame() {
|
||||
let code = [0x48, 0x89, 0xE0, 0xC3]; // mov rax, rsp; ret
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&code);
|
||||
// Loaded 64 KiB above the preferred base: the listed address is rebased.
|
||||
let loaded = IMAGE_BASE + 0x1_0000;
|
||||
let listed = [CODE - 0x1_0000];
|
||||
let ran = execute_tls_callbacks(
|
||||
&listed,
|
||||
loaded,
|
||||
IMAGE_BASE,
|
||||
STACK_TOP,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(ran, Ok(1));
|
||||
let entry_rsp = cpu.get(Register::Rax);
|
||||
assert_eq!(entry_rsp, STACK_TOP - 40);
|
||||
// A callee is entered 8 bytes off 16-byte alignment, as after a CALL.
|
||||
assert_eq!(entry_rsp % 16, 8);
|
||||
assert_eq!(memory.read_u64(entry_rsp), Ok(SENTINEL));
|
||||
assert_eq!(cpu.get(Register::Rcx), loaded);
|
||||
assert_eq!(cpu.get(Register::Rdx), 1); // DLL_PROCESS_ATTACH
|
||||
assert_eq!(cpu.get(Register::R8), 0);
|
||||
// RET popped the return address and nothing else.
|
||||
assert_eq!(cpu.get(Register::Rsp), entry_rsp + 8);
|
||||
assert_eq!(cpu.rip, SENTINEL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callbacks_run_in_array_order() {
|
||||
for (order, recorded) in [([CODE, CODE + 16], 0x12), ([CODE + 16, CODE], 0x21)] {
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&TAGGING);
|
||||
let ran = execute_tls_callbacks(
|
||||
&order,
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
STACK_TOP,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(ran, Ok(2));
|
||||
assert_eq!(cpu.get(Register::Rax), recorded);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_over_the_instruction_budget_stops_the_sequence() {
|
||||
let mut code = TAGGING.to_vec();
|
||||
code.resize(32, 0);
|
||||
code.extend([0xEB, 0xFE]); // jmp to itself
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&code);
|
||||
let ran = execute_tls_callbacks(
|
||||
&[CODE, CODE + 32, CODE + 16],
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
STACK_TOP,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(
|
||||
ran,
|
||||
Err(TlsError::CallbackExecutionFault(
|
||||
ExitReason::StepLimitExceeded
|
||||
))
|
||||
);
|
||||
// The first callback ran; the one after the endless one did not.
|
||||
assert_eq!(cpu.get(Register::Rax), 0x1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unusable_callback_stack_is_rejected_before_anything_runs() {
|
||||
for stack_top in [0, 32, STACK_TOP - 8, STACK_TOP - 1] {
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&TAGGING);
|
||||
let ran = execute_tls_callbacks(
|
||||
&[CODE],
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
stack_top,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(
|
||||
ran,
|
||||
Err(TlsError::InvalidCallbackStack { stack_top }),
|
||||
"{stack_top:#x}"
|
||||
);
|
||||
assert_eq!(cpu, CpuState::new(0, 0));
|
||||
assert_eq!(memory.read_u64(STACK_TOP - 48), Ok(0));
|
||||
// No callback, no frame: the stack is not looked at.
|
||||
let none = execute_tls_callbacks(&[], 0, 0, stack_top, &mut cpu, &mut memory, &mut dbt);
|
||||
assert_eq!(none, Ok(0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes that do not repeat every 256 or every 4096 bytes, so a chunk
|
||||
/// copied from the wrong offset cannot match.
|
||||
fn synthetic_template(len: usize) -> Vec<u8> {
|
||||
(0..len)
|
||||
.map(|index| {
|
||||
let mixed = index ^ (index >> 8) ^ (index >> 16);
|
||||
mixed.wrapping_mul(131).wrapping_add(17) as u8
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Image template at `template_at`, with `sentinel` 0xA5 bytes after it, and
|
||||
/// a writable index that does not start at zero.
|
||||
fn template_memory(
|
||||
template_at: u64,
|
||||
template: &[u8],
|
||||
sentinel: usize,
|
||||
index_at: u64,
|
||||
) -> GuestMemory {
|
||||
let mut image = template.to_vec();
|
||||
image.extend(std::iter::repeat_n(0xA5, sentinel));
|
||||
let map = (image.len() + 0xFFF) & !0xFFF;
|
||||
image.resize(map, 0);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(template_at, map, MemoryPermissions::READ_ONLY, &image)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(index_at, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
fn directory_at(
|
||||
template_at: u64,
|
||||
template_len: u64,
|
||||
index_at: u64,
|
||||
zero_fill: u32,
|
||||
) -> TlsDirectory {
|
||||
TlsDirectory {
|
||||
raw_data_start_va: template_at,
|
||||
raw_data_end_va: template_at + template_len,
|
||||
index_address: index_at,
|
||||
size_of_zero_fill: zero_fill,
|
||||
..TlsDirectory::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_block(
|
||||
memory: &GuestMemory,
|
||||
thread: u64,
|
||||
index: u64,
|
||||
template: &[u8],
|
||||
zero_fill: usize,
|
||||
) {
|
||||
assert_eq!(memory.read_u32(index).unwrap(), 0);
|
||||
let block = memory.read_u64(thread).unwrap();
|
||||
assert_eq!(block, thread + 0x1000, "the data block is the next page");
|
||||
// The block is mapped up to the next page boundary and no further.
|
||||
let mapped = (template.len() + zero_fill + 0xFFF) & !0xFFF;
|
||||
let mut got = vec![0xEEu8; mapped];
|
||||
memory.read_bytes(block, &mut got).unwrap();
|
||||
assert_eq!(&got[..template.len()], template);
|
||||
assert!(got[template.len()..].iter().all(|byte| *byte == 0));
|
||||
let end = block + mapped as u64;
|
||||
assert_eq!(memory.read_u8(end), Err(MemoryError::UnmappedAddress(end)));
|
||||
}
|
||||
|
||||
const TEMPLATE_AT: u64 = 0x2_0020_0000;
|
||||
const INDEX_AT: u64 = 0x2_0000_1000;
|
||||
const THREAD_AT: u64 = 0x5_0000_0000;
|
||||
|
||||
#[test]
|
||||
fn a_small_template_is_copied_and_zero_fill_does_not_take_the_following_bytes() {
|
||||
let template = synthetic_template(48);
|
||||
let mut memory = template_memory(TEMPLATE_AT, &template, 16, INDEX_AT);
|
||||
setup_tls(
|
||||
&directory_at(TEMPLATE_AT, template.len() as u64, INDEX_AT, 16),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut memory,
|
||||
THREAD_AT,
|
||||
)
|
||||
.unwrap();
|
||||
assert_block(&memory, THREAD_AT, INDEX_AT, &template, 16);
|
||||
let mut tail = [0u8; 16];
|
||||
memory
|
||||
.read_bytes(TEMPLATE_AT + template.len() as u64, &mut tail)
|
||||
.unwrap();
|
||||
assert_eq!(tail, [0xA5; 16]);
|
||||
let block = memory.read_u64(THREAD_AT).unwrap();
|
||||
memory.write_u64(block + 8, 0x0102_0304_0506_0708).unwrap();
|
||||
let mut image = [0u8; 8];
|
||||
memory.read_bytes(TEMPLATE_AT + 8, &mut image).unwrap();
|
||||
assert_eq!(image, template[8..16]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_staged_and_direct_copy_boundaries_keep_every_template_byte() {
|
||||
for len in [
|
||||
DIRECT_TEMPLATE_MIN - 1,
|
||||
DIRECT_TEMPLATE_MIN,
|
||||
DIRECT_TEMPLATE_MIN + TEMPLATE_COPY_CHUNK + 100,
|
||||
DIRECT_TEMPLATE_LIMIT - 1,
|
||||
DIRECT_TEMPLATE_LIMIT,
|
||||
] {
|
||||
let template = synthetic_template(len);
|
||||
let mut memory = template_memory(TEMPLATE_AT, &template, 24, INDEX_AT);
|
||||
setup_tls(
|
||||
&directory_at(TEMPLATE_AT, template.len() as u64, INDEX_AT, 24),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut memory,
|
||||
THREAD_AT,
|
||||
)
|
||||
.unwrap();
|
||||
assert_block(&memory, THREAD_AT, INDEX_AT, &template, 24);
|
||||
let mut tail = [0u8; 24];
|
||||
memory
|
||||
.read_bytes(TEMPLATE_AT + template.len() as u64, &mut tail)
|
||||
.unwrap();
|
||||
assert_eq!(tail, [0xA5; 24], "len {len}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rebased_direct_copy_reads_the_loaded_image() {
|
||||
let template = synthetic_template(DIRECT_TEMPLATE_MIN);
|
||||
let preferred = 0x1_4000_0000u64;
|
||||
let loaded = preferred + 0x80_0000;
|
||||
let template_at = preferred + 0x20_0000;
|
||||
let index_at = preferred + 0x1000;
|
||||
let mut memory =
|
||||
template_memory(template_at + 0x80_0000, &template, 0, index_at + 0x80_0000);
|
||||
setup_tls(
|
||||
&directory_at(template_at, template.len() as u64, index_at, 8),
|
||||
loaded,
|
||||
preferred,
|
||||
&mut memory,
|
||||
THREAD_AT,
|
||||
)
|
||||
.unwrap();
|
||||
assert_block(&memory, THREAD_AT, index_at + 0x80_0000, &template, 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_template_maps_no_pointer_array() {
|
||||
for len in [32usize, DIRECT_TEMPLATE_MIN, DIRECT_TEMPLATE_MIN + 50] {
|
||||
let mut missing = GuestMemory::new();
|
||||
missing
|
||||
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
let missing_result = setup_tls(
|
||||
&directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut missing,
|
||||
THREAD_AT,
|
||||
);
|
||||
assert_eq!(
|
||||
missing_result,
|
||||
Err(TlsError::Memory(MemoryError::UnmappedAddress(TEMPLATE_AT))),
|
||||
"{len}"
|
||||
);
|
||||
assert_eq!(missing.read_u32(INDEX_AT).unwrap(), 0);
|
||||
assert!(matches!(
|
||||
missing.read_u64(THREAD_AT),
|
||||
Err(MemoryError::UnmappedAddress(_))
|
||||
));
|
||||
|
||||
let mut denied = GuestMemory::new();
|
||||
denied
|
||||
.map_region(TEMPLATE_AT, len.max(0x1000), MemoryPermissions::NO_ACCESS)
|
||||
.unwrap();
|
||||
denied
|
||||
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
let denied_result = setup_tls(
|
||||
&directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut denied,
|
||||
THREAD_AT,
|
||||
);
|
||||
assert_eq!(
|
||||
denied_result,
|
||||
Err(TlsError::Memory(MemoryError::PermissionViolation {
|
||||
address: TEMPLATE_AT,
|
||||
required: "read",
|
||||
})),
|
||||
"{len}"
|
||||
);
|
||||
assert_eq!(denied.read_u32(INDEX_AT).unwrap(), 0);
|
||||
assert!(matches!(
|
||||
denied.read_u64(THREAD_AT),
|
||||
Err(MemoryError::UnmappedAddress(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_direct_copy_template_that_runs_out_of_its_mapping_maps_nothing() {
|
||||
let len = DIRECT_TEMPLATE_MIN + 100;
|
||||
let mut memory = GuestMemory::new();
|
||||
// Only the first chunk is mapped. The rest of the template is not.
|
||||
memory
|
||||
.map_region_with_data(
|
||||
TEMPLATE_AT,
|
||||
TEMPLATE_COPY_CHUNK,
|
||||
MemoryPermissions::READ_ONLY,
|
||||
&synthetic_template(TEMPLATE_COPY_CHUNK),
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
let result = setup_tls(
|
||||
&directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut memory,
|
||||
THREAD_AT,
|
||||
);
|
||||
// The same first unreadable byte the single staged read reports.
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(TlsError::Memory(MemoryError::UnmappedAddress(
|
||||
TEMPLATE_AT + TEMPLATE_COPY_CHUNK as u64
|
||||
)))
|
||||
);
|
||||
assert_eq!(memory.read_u32(INDEX_AT).unwrap(), 0);
|
||||
assert!(matches!(
|
||||
memory.read_u64(THREAD_AT),
|
||||
Err(MemoryError::UnmappedAddress(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_template_and_zero_fill_only_assigns_the_index() {
|
||||
let mut memory = template_memory(TEMPLATE_AT, &[], 0, INDEX_AT);
|
||||
setup_tls(
|
||||
&directory_at(TEMPLATE_AT, 0, INDEX_AT, 0),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut memory,
|
||||
THREAD_AT,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(memory.read_u32(INDEX_AT).unwrap(), 0);
|
||||
assert!(matches!(
|
||||
memory.read_u64(THREAD_AT),
|
||||
Err(MemoryError::UnmappedAddress(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_fill_only_block_is_zero_and_separate_from_the_array() {
|
||||
let mut memory = template_memory(TEMPLATE_AT, &[], 0, INDEX_AT);
|
||||
setup_tls(
|
||||
&directory_at(TEMPLATE_AT, 0, INDEX_AT, 24),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut memory,
|
||||
THREAD_AT,
|
||||
)
|
||||
.unwrap();
|
||||
assert_block(&memory, THREAD_AT, INDEX_AT, &[], 24);
|
||||
}
|
||||
|
||||
/// Byte pattern from the before/after timing runs. It is not the pattern
|
||||
/// the correctness tests use to catch a chunk copied from the wrong offset.
|
||||
fn timed_template(len: usize) -> Vec<u8> {
|
||||
(0..len)
|
||||
.map(|index| (index.wrapping_mul(131).wrapping_add(17)) as u8)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn timed_guest(template_len: usize, zero_fill: u32) -> (GuestMemory, TlsDirectory) {
|
||||
let template = timed_template(template_len);
|
||||
let mut memory = GuestMemory::new();
|
||||
if template_len > 0 {
|
||||
let map = (template_len + 0xFFF) & !0xFFF;
|
||||
memory
|
||||
.map_region_with_data(TEMPLATE_AT, map, MemoryPermissions::READ_ONLY, &template)
|
||||
.unwrap();
|
||||
}
|
||||
memory
|
||||
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
(
|
||||
memory,
|
||||
directory_at(TEMPLATE_AT, template_len as u64, INDEX_AT, zero_fill),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual TLS template timing run; release build on an otherwise idle host"]
|
||||
fn tls_template_initialization_profile() {
|
||||
// Sizes, zero fill and batch counts from the interleaved before/after runs.
|
||||
let cases = [
|
||||
(64usize, 0u32, 80usize),
|
||||
(4096, 0, 40),
|
||||
(65535, 0, 20),
|
||||
(65536, 128, 16),
|
||||
(262144, 0, 6),
|
||||
(786432, 0, 4),
|
||||
(1048576, 0, 4),
|
||||
(0, 1048576, 4),
|
||||
];
|
||||
for (template_len, zero_fill, batch) in cases {
|
||||
let (mut memory, directory) = timed_guest(template_len, zero_fill);
|
||||
setup_tls(&directory, IMAGE_BASE, IMAGE_BASE, &mut memory, THREAD_AT).unwrap();
|
||||
if template_len > 0 {
|
||||
let template = timed_template(template_len);
|
||||
let block = memory.read_u64(THREAD_AT).unwrap();
|
||||
let mut byte = [0u8; 1];
|
||||
memory.read_bytes(block, &mut byte).unwrap();
|
||||
assert_eq!(byte[0], template[0]);
|
||||
memory
|
||||
.read_bytes(block + template_len as u64 - 1, &mut byte)
|
||||
.unwrap();
|
||||
assert_eq!(byte[0], template[template_len - 1]);
|
||||
}
|
||||
|
||||
let mut samples = Vec::new();
|
||||
for run in 0..33 {
|
||||
let mut guests: Vec<_> = (0..batch)
|
||||
.map(|_| timed_guest(template_len, zero_fill))
|
||||
.collect();
|
||||
let start = Instant::now();
|
||||
for (memory, directory) in &mut guests {
|
||||
setup_tls(directory, IMAGE_BASE, IMAGE_BASE, memory, THREAD_AT).unwrap();
|
||||
black_box(memory);
|
||||
}
|
||||
if run >= 2 {
|
||||
let per_ns = start.elapsed().as_secs_f64() * 1e9 / batch as f64;
|
||||
samples.push(per_ns);
|
||||
}
|
||||
}
|
||||
samples.sort_by(f64::total_cmp);
|
||||
let n = samples.len();
|
||||
let mean = samples.iter().sum::<f64>() / n as f64;
|
||||
let sample_variance = samples
|
||||
.iter()
|
||||
.map(|sample| (sample - mean).powi(2))
|
||||
.sum::<f64>()
|
||||
/ (n - 1) as f64;
|
||||
println!(
|
||||
"template={template_len} zero_fill={zero_fill} batch={batch} n={n} median_ns={:.1} sample_variance_ns2={sample_variance:.1}",
|
||||
samples[n / 2]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,9 @@ use crate::x86_table::{
|
||||
/// Architectural x86-64 instruction length limit, in bytes.
|
||||
///
|
||||
/// An instruction may not exceed 15 bytes (Intel SDM Vol. 2A, "Instruction
|
||||
/// Length"). Sequences longer than this are not decodable and are rejected as
|
||||
/// illegal instructions.
|
||||
/// Length"). Decoding stops before a 16th byte would be fetched and reports
|
||||
/// [`DecodeError::TooLong`], a general-protection fault (Intel SDM Vol. 3A,
|
||||
/// 7.15).
|
||||
pub const MAX_INSTRUCTION_LEN: usize = 15;
|
||||
|
||||
/// Number of leading legacy segment prefix bytes (0x64 FS, 0x65 GS) at the
|
||||
@@ -47,6 +48,9 @@ pub struct Form {
|
||||
pub has_modrm: bool,
|
||||
pub memory_only: bool,
|
||||
pub register_only: bool,
|
||||
/// The only ModRM r/m field value the form accepts. Set only on
|
||||
/// register-only forms, so such a form matches exactly one ModRM byte.
|
||||
pub fixed_rm: Option<u8>,
|
||||
pub no_rex_b: bool,
|
||||
/// A 16-byte memory operand may have any alignment.
|
||||
pub unaligned: bool,
|
||||
@@ -76,6 +80,10 @@ pub enum Encoding {
|
||||
RmImm,
|
||||
RmOne,
|
||||
RmCl,
|
||||
/// `rm` from `rm` and `reg`, with an 8-bit count (SHLD, SHRD).
|
||||
RmRegImm,
|
||||
/// `rm` from `rm` and `reg`, with the count in CL (SHLD, SHRD).
|
||||
RmRegCl,
|
||||
AccImm,
|
||||
OpReg,
|
||||
OpRegImm,
|
||||
@@ -200,24 +208,24 @@ pub enum DecodeError<E> {
|
||||
Fetch(E),
|
||||
/// No declared form matches; carries the byte that decided it.
|
||||
Unsupported(u8),
|
||||
/// The instruction would be longer than [`MAX_INSTRUCTION_LEN`] bytes.
|
||||
TooLong,
|
||||
}
|
||||
|
||||
struct Cursor<F> {
|
||||
fetch: F,
|
||||
rip: u64,
|
||||
len: usize,
|
||||
last: u8,
|
||||
}
|
||||
|
||||
impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
|
||||
fn u8(&mut self) -> Result<u8, DecodeError<E>> {
|
||||
if self.len == MAX_INSTRUCTION_LEN {
|
||||
return Err(DecodeError::Unsupported(self.last));
|
||||
return Err(DecodeError::TooLong);
|
||||
}
|
||||
let byte =
|
||||
(self.fetch)(self.rip.wrapping_add(self.len as u64)).map_err(DecodeError::Fetch)?;
|
||||
self.len += 1;
|
||||
self.last = byte;
|
||||
Ok(byte)
|
||||
}
|
||||
|
||||
@@ -237,6 +245,15 @@ impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `byte` is a legacy prefix: an operand-size, address-size, segment,
|
||||
/// LOCK or repeat prefix (Intel SDM Vol. 2A, 2.1.1).
|
||||
fn is_legacy_prefix(byte: u8) -> bool {
|
||||
matches!(
|
||||
byte,
|
||||
0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 | 0x66 | 0x67 | 0xF0 | 0xF2 | 0xF3
|
||||
)
|
||||
}
|
||||
|
||||
/// Decode one instruction at `rip`. `fetch` supplies the byte at an address and
|
||||
/// is called only for bytes that belong to the instruction, in order.
|
||||
///
|
||||
@@ -247,20 +264,28 @@ pub fn decode<E>(
|
||||
rip: u64,
|
||||
fetch: impl FnMut(u64) -> Result<u8, E>,
|
||||
) -> Result<Insn, DecodeError<E>> {
|
||||
let mut cursor = Cursor {
|
||||
fetch,
|
||||
rip,
|
||||
len: 0,
|
||||
last: 0,
|
||||
};
|
||||
let mut cursor = Cursor { fetch, rip, len: 0 };
|
||||
let mut operand_size = false;
|
||||
let mut rep = false;
|
||||
let mut repne = false;
|
||||
let mut lock = false;
|
||||
let mut segment = None;
|
||||
let mut rex = 0;
|
||||
let mut byte = cursor.u8()?;
|
||||
loop {
|
||||
let selected = match byte {
|
||||
// REX applies only immediately before the opcode. One that is
|
||||
// followed by a legacy prefix is ignored (Intel SDM Vol. 2A, 2.2.1).
|
||||
0x40..=0x4F => {
|
||||
let next = cursor.u8()?;
|
||||
if !is_legacy_prefix(next) {
|
||||
rex = byte;
|
||||
byte = next;
|
||||
break;
|
||||
}
|
||||
byte = next;
|
||||
continue;
|
||||
}
|
||||
0x64 => Segment::Fs,
|
||||
0x65 => Segment::Gs,
|
||||
0x66 => {
|
||||
@@ -299,10 +324,6 @@ pub fn decode<E>(
|
||||
byte = cursor.u8()?;
|
||||
}
|
||||
|
||||
let rex = if byte & 0xF0 == 0x40 { byte } else { 0 };
|
||||
if rex != 0 {
|
||||
byte = cursor.u8()?;
|
||||
}
|
||||
let (rex_w, rex_r, rex_x, rex_b) =
|
||||
(rex & 8 != 0, (rex & 4) << 1, (rex & 2) << 2, (rex & 1) << 3);
|
||||
|
||||
@@ -345,9 +366,24 @@ pub fn decode<E>(
|
||||
GROUPS[usize::from(index)][usize::from((modrm >> 3) & 7)]
|
||||
}
|
||||
};
|
||||
let form = FORMS
|
||||
let mut form = FORMS
|
||||
.get(usize::from(form_index))
|
||||
.ok_or(DecodeError::Unsupported(opcode))?;
|
||||
let mut form_index = form_index;
|
||||
if form.no_rex_b && rex_b != 0 {
|
||||
// 90 is NOP only without REX.B. With it the byte exchanges r8 with the
|
||||
// accumulator, as the first register of the 91..97 row would (Intel
|
||||
// SDM Vol. 2B, "NOP" and "XCHG").
|
||||
match ONE_BYTE[slot + 1] {
|
||||
Entry::Form(index)
|
||||
if !two_byte && !rep && FORMS[usize::from(index)].encoding == Encoding::OpReg =>
|
||||
{
|
||||
form_index = index;
|
||||
form = &FORMS[usize::from(index)];
|
||||
}
|
||||
_ => return Err(DecodeError::Unsupported(opcode)),
|
||||
}
|
||||
}
|
||||
if form.has_modrm && matches!(entry, Entry::Form(_)) {
|
||||
modrm = cursor.u8()?;
|
||||
}
|
||||
@@ -368,10 +404,6 @@ pub fn decode<E>(
|
||||
if operand_size && !takes_operand_size && !overridden {
|
||||
return Err(DecodeError::Unsupported(0x66));
|
||||
}
|
||||
if form.no_rex_b && rex_b != 0 {
|
||||
return Err(DecodeError::Unsupported(opcode));
|
||||
}
|
||||
|
||||
let rm_size = if form.source != 0 { form.source } else { size };
|
||||
let register = |field: u8, extension: u8, width: u8| {
|
||||
if width == 1 && rex == 0 && field >= 4 {
|
||||
@@ -397,7 +429,7 @@ pub fn decode<E>(
|
||||
reg = register((modrm >> 3) & 7, rex_r, size);
|
||||
let mode = modrm >> 6;
|
||||
if mode == 3 {
|
||||
if form.memory_only {
|
||||
if form.memory_only || form.fixed_rm.is_some_and(|field| field != modrm & 7) {
|
||||
return Err(DecodeError::Unsupported(opcode));
|
||||
}
|
||||
rm = Some(RmOperand::Reg(register(modrm & 7, rex_b, rm_size)));
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! the state unchanged. Flags that the architecture leaves undefined keep their
|
||||
//! previous value, which is permitted but not something guests may rely on.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, RFlags, Register, cpuid};
|
||||
use crate::cpu::{CpuState, ExitReason, RFlags, Register, X87State, cpuid};
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
|
||||
use crate::x86_simd;
|
||||
@@ -49,6 +49,26 @@ pub fn address(cpu: &CpuState, operand: &MemOperand) -> u64 {
|
||||
base.wrapping_add(offset(cpu, operand))
|
||||
}
|
||||
|
||||
/// Whether a 64-bit guest address is canonical under the x86-64 48-bit
|
||||
/// virtual-address rule (Intel SDM Vol. 1, section 3.3.7.1).
|
||||
pub(crate) fn is_canonical(address: u64) -> bool {
|
||||
matches!(address >> 47, 0 | 0x1_ffff)
|
||||
}
|
||||
|
||||
/// Whether every byte of a data access has a canonical address. An overflowing
|
||||
/// range is left to [`GuestMemory`] so it keeps its existing overflow fault.
|
||||
pub(crate) fn canonical_access(address: u64, size: u8) -> bool {
|
||||
if !is_canonical(address) {
|
||||
return false;
|
||||
}
|
||||
if size <= 1 {
|
||||
return true;
|
||||
}
|
||||
address
|
||||
.checked_add(u64::from(size) - 1)
|
||||
.is_none_or(is_canonical)
|
||||
}
|
||||
|
||||
/// Effective address without a segment base, as LEA computes it.
|
||||
fn offset(cpu: &CpuState, operand: &MemOperand) -> u64 {
|
||||
let base = operand.base.map_or(0, |index| cpu.gpr[usize::from(index)]);
|
||||
@@ -78,6 +98,9 @@ pub(crate) fn write_reg(cpu: &mut CpuState, reg: RegOperand, size: u8, value: u6
|
||||
}
|
||||
|
||||
pub(crate) fn read_mem(memory: &GuestMemory, address: u64, size: u8) -> Result<u64, ExitReason> {
|
||||
if !canonical_access(address, size) {
|
||||
return Err(ExitReason::GeneralProtection);
|
||||
}
|
||||
match size {
|
||||
1 => memory.read_u8(address).map(u64::from),
|
||||
2 => memory.read_u16(address).map(u64::from),
|
||||
@@ -93,6 +116,9 @@ pub(crate) fn write_mem(
|
||||
size: u8,
|
||||
value: u64,
|
||||
) -> Result<(), ExitReason> {
|
||||
if !canonical_access(address, size) {
|
||||
return Err(ExitReason::GeneralProtection);
|
||||
}
|
||||
match size {
|
||||
1 => memory.write_u8(address, value as u8),
|
||||
2 => memory.write_u16(address, value as u16),
|
||||
@@ -241,6 +267,25 @@ fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64,
|
||||
flags.cf = signed >> (count - 1) & 1 != 0;
|
||||
(signed >> count) as u64
|
||||
}
|
||||
Op::Rcl | Op::Rcr => {
|
||||
// The carry flag is one more bit above the operand, so the rotation
|
||||
// is over `bits + 1` positions and the count is reduced modulo that.
|
||||
let width = bits + 1;
|
||||
let ring = wide | u128::from(old.cf) << bits;
|
||||
let by = count % width;
|
||||
let left = if op == Op::Rcl {
|
||||
by
|
||||
} else {
|
||||
(width - by) % width
|
||||
};
|
||||
let rotated = if left == 0 {
|
||||
ring
|
||||
} else {
|
||||
ring << left | ring >> (width - left)
|
||||
};
|
||||
flags.cf = rotated >> bits & 1 != 0;
|
||||
rotated as u64
|
||||
}
|
||||
_ => {
|
||||
let by = count % bits;
|
||||
let left = if op == Op::Rol {
|
||||
@@ -268,7 +313,7 @@ fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64,
|
||||
// OF is defined only for a count of one.
|
||||
if count == 1 {
|
||||
flags.of = match op {
|
||||
Op::Shl | Op::Rol => (result & top != 0) != flags.cf,
|
||||
Op::Shl | Op::Rol | Op::Rcl => (result & top != 0) != flags.cf,
|
||||
Op::Shr => value & top != 0,
|
||||
Op::Sar => false,
|
||||
_ => (result & top != 0) != (result & (top >> 1) != 0),
|
||||
@@ -277,6 +322,54 @@ fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64,
|
||||
Some((result, flags))
|
||||
}
|
||||
|
||||
/// SHLD and SHRD (Intel SDM Vol. 2B, "SHLD" and "SHRD"): `dst` is shifted by
|
||||
/// `count` and the vacated bits are filled from `src`, which is unchanged.
|
||||
/// `None` means a masked count of zero, which changes neither the destination
|
||||
/// nor the flags.
|
||||
///
|
||||
/// A count above the operand size is possible only for 16-bit operands and
|
||||
/// leaves the result and flags undefined. Xenora then returns the bits the
|
||||
/// 32-bit concatenation gives and keeps every flag; no test relies on that.
|
||||
fn double_shift(
|
||||
op: Op,
|
||||
dst: u64,
|
||||
src: u64,
|
||||
count: u64,
|
||||
size: u8,
|
||||
old: RFlags,
|
||||
) -> Option<(u64, RFlags)> {
|
||||
let count = (count & if size == 8 { 0x3F } else { 0x1F }) as u32;
|
||||
if count == 0 {
|
||||
return None;
|
||||
}
|
||||
let bits = 8 * u32::from(size);
|
||||
let (dst, src) = (u128::from(dst), u128::from(src));
|
||||
// SHLD shifts `dst:src` left and keeps the high half; SHRD shifts
|
||||
// `src:dst` right and keeps the low half. CF is the last bit shifted out
|
||||
// of the destination.
|
||||
let (result, cf) = if op == Op::Shld {
|
||||
let pair = dst << bits | src;
|
||||
let shifted = pair << count;
|
||||
(shifted >> bits, pair >> (2 * bits - count) & 1 != 0)
|
||||
} else {
|
||||
let pair = src << bits | dst;
|
||||
(pair >> count, pair >> (count - 1) & 1 != 0)
|
||||
};
|
||||
let result = result as u64 & mask(size);
|
||||
let mut flags = old;
|
||||
if count > bits {
|
||||
return Some((result, flags));
|
||||
}
|
||||
flags.cf = cf;
|
||||
result_flags(&mut flags, result, size);
|
||||
// OF is defined only for a count of one: set when the sign changed.
|
||||
if count == 1 {
|
||||
let top = u128::from(sign_bit(size));
|
||||
flags.of = (u128::from(result) & top != 0) != (dst & top != 0);
|
||||
}
|
||||
Some((result, flags))
|
||||
}
|
||||
|
||||
fn push(cpu: &mut CpuState, memory: &mut GuestMemory, value: u64) -> Result<(), ExitReason> {
|
||||
let sp = cpu.gpr[RSP]
|
||||
.checked_sub(8)
|
||||
@@ -354,6 +447,8 @@ pub fn execute(
|
||||
Encoding::OpRegImm => write_reg(cpu, insn.reg, size, insn.imm),
|
||||
_ => write_rm(cpu, memory, insn, insn.imm & mask(size))?,
|
||||
},
|
||||
// A non-temporal store is an ordinary store: there is no cache to bypass.
|
||||
Op::Movnti => write_rm(cpu, memory, insn, read_reg(cpu, insn.reg, size))?,
|
||||
Op::Movzx => {
|
||||
let value = read_rm(cpu, memory, insn)?;
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
@@ -367,6 +462,14 @@ pub fn execute(
|
||||
write_reg(cpu, insn.reg, size, offset(cpu, &operand));
|
||||
}
|
||||
}
|
||||
Op::Xchg if insn.encoding == Encoding::OpReg => {
|
||||
// The accumulator with the register in the opcode, never itself:
|
||||
// 90 without REX.B is NOP.
|
||||
let rax = accumulator(RAX);
|
||||
let (a, b) = (read_reg(cpu, rax, size), read_reg(cpu, insn.reg, size));
|
||||
write_reg(cpu, rax, size, b);
|
||||
write_reg(cpu, insn.reg, size, a);
|
||||
}
|
||||
Op::Xchg => {
|
||||
let (a, b) = operands(cpu, memory, insn)?;
|
||||
write_rm(cpu, memory, insn, b)?;
|
||||
@@ -419,7 +522,24 @@ pub fn execute(
|
||||
if negative { mask(size) } else { 0 },
|
||||
);
|
||||
}
|
||||
Op::Rol | Op::Ror | Op::Shl | Op::Shr | Op::Sar => {
|
||||
Op::Shld | Op::Shrd => {
|
||||
let dst = read_rm(cpu, memory, insn)?;
|
||||
let src = read_reg(cpu, insn.reg, size);
|
||||
let count = match insn.encoding {
|
||||
Encoding::RmRegCl => cpu.gpr[RCX] & 0xFF,
|
||||
_ => insn.imm & 0xFF,
|
||||
};
|
||||
match double_shift(insn.op, dst, src, count, size, cpu.flags) {
|
||||
Some((value, flags)) => {
|
||||
write_rm(cpu, memory, insn, value)?;
|
||||
cpu.flags = flags;
|
||||
}
|
||||
// As for the other shifts, a zero count still performs the
|
||||
// write's permission check and the 32-bit zero-extension.
|
||||
None => write_rm(cpu, memory, insn, dst)?,
|
||||
}
|
||||
}
|
||||
Op::Rol | Op::Ror | Op::Rcl | Op::Rcr | Op::Shl | Op::Shr | Op::Sar => {
|
||||
let (a, count) = operands(cpu, memory, insn)?;
|
||||
match shift(insn.op, a, count, size, cpu.flags) {
|
||||
Some((value, flags)) => {
|
||||
@@ -570,12 +690,42 @@ pub fn execute(
|
||||
next = insn.imm;
|
||||
}
|
||||
}
|
||||
// The count is RCX, decremented without changing any flag; LOOPE and
|
||||
// LOOPNE also test ZF (Intel SDM Vol. 2A, LOOP/LOOPcc).
|
||||
Op::Loop | Op::Loope | Op::Loopne => {
|
||||
let count = cpu.gpr[RCX].wrapping_sub(1);
|
||||
cpu.gpr[RCX] = count;
|
||||
let zf_holds = match insn.op {
|
||||
Op::Loope => cpu.flags.zf,
|
||||
Op::Loopne => !cpu.flags.zf,
|
||||
_ => true,
|
||||
};
|
||||
if count != 0 && zf_holds {
|
||||
next = insn.imm;
|
||||
}
|
||||
}
|
||||
// JRCXZ reads RCX and changes nothing (Intel SDM Vol. 2A, Jcc).
|
||||
Op::Jrcxz => {
|
||||
if cpu.gpr[RCX] == 0 {
|
||||
next = insn.imm;
|
||||
}
|
||||
}
|
||||
Op::Ret => {
|
||||
let sp = cpu.gpr[RSP];
|
||||
next = read_mem(memory, sp, 8)?;
|
||||
cpu.gpr[RSP] = sp.wrapping_add(8).wrapping_add(insn.imm);
|
||||
}
|
||||
Op::Nop => {}
|
||||
// Every load and store of an instruction completes before the next
|
||||
// instruction starts, on one host thread, so guest accesses are already
|
||||
// totally ordered and a fence has nothing further to enforce.
|
||||
Op::Lfence | Op::Mfence | Op::Sfence => {}
|
||||
// The control, status and tag words take their initial values. The
|
||||
// no-wait form checks no pending exception, and the data registers,
|
||||
// which Xenora does not model, are left alone and only tagged empty
|
||||
// (Intel SDM Vol. 2A, "FINIT/FNINIT"). FNINIT also clears the x87
|
||||
// instruction and data pointers and last opcode, which are not modelled.
|
||||
Op::Fninit => cpu.x87 = X87State::INIT,
|
||||
Op::Cpuid => {
|
||||
// The leaf is EAX and the subleaf ECX. Each result is a 32-bit
|
||||
// register write, so the upper halves are cleared.
|
||||
@@ -618,6 +768,28 @@ pub fn execute(
|
||||
Op::Clc => cpu.flags.cf = false,
|
||||
Op::Stc => cpu.flags.cf = true,
|
||||
Op::Cmc => cpu.flags.cf = !cpu.flags.cf,
|
||||
// AH = SF:ZF:0:AF:0:PF:1:CF (Intel SDM Vol. 2A, LAHF).
|
||||
Op::Lahf => {
|
||||
let f = cpu.flags;
|
||||
let ah = u64::from(f.sf) << 7
|
||||
| u64::from(f.zf) << 6
|
||||
| u64::from(f.af) << 4
|
||||
| u64::from(f.pf) << 2
|
||||
| 1 << 1
|
||||
| u64::from(f.cf);
|
||||
cpu.gpr[RAX] = cpu.gpr[RAX] & !0xFF00 | ah << 8;
|
||||
}
|
||||
// SF, ZF, AF, PF and CF from AH bits 7, 6, 4, 2 and 0; OF is
|
||||
// unchanged (Intel SDM Vol. 2B, SAHF).
|
||||
Op::Sahf => {
|
||||
let ah = (cpu.gpr[RAX] >> 8) as u8;
|
||||
let flags = &mut cpu.flags;
|
||||
flags.sf = ah & 0x80 != 0;
|
||||
flags.zf = ah & 0x40 != 0;
|
||||
flags.af = ah & 0x10 != 0;
|
||||
flags.pf = ah & 0x04 != 0;
|
||||
flags.cf = ah & 0x01 != 0;
|
||||
}
|
||||
Op::Hlt => {
|
||||
cpu.rip = next;
|
||||
return Ok(Some(ExitReason::Halt));
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
use crate::cpu::{CpuState, ExitReason, Mxcsr};
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::x86_decode::{Encoding, Insn, RegOperand, RmOperand};
|
||||
use crate::x86_exec::{address, read_mem, read_reg, rm_operand, write_mem, write_reg};
|
||||
use crate::x86_exec::{
|
||||
address, canonical_access, read_mem, read_reg, rm_operand, write_mem, write_reg,
|
||||
};
|
||||
use crate::x86_float;
|
||||
use crate::x86_table::{FORMS, Op};
|
||||
|
||||
@@ -216,6 +218,9 @@ fn read_vector(memory: &GuestMemory, address: u64, size: u8) -> Result<u128, Exi
|
||||
if size < 16 {
|
||||
return read_mem(memory, address, size).map(u128::from);
|
||||
}
|
||||
if !canonical_access(address, size) {
|
||||
return Err(ExitReason::GeneralProtection);
|
||||
}
|
||||
let mut bytes = [0; 16];
|
||||
memory
|
||||
.read_bytes(address, &mut bytes)
|
||||
@@ -232,6 +237,9 @@ fn write_vector(
|
||||
if size < 16 {
|
||||
return write_mem(memory, address, size, value as u64);
|
||||
}
|
||||
if !canonical_access(address, size) {
|
||||
return Err(ExitReason::GeneralProtection);
|
||||
}
|
||||
memory
|
||||
.write_bytes(address, &value.to_le_bytes())
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
|
||||
+674
-504
File diff suppressed because it is too large.
Load diff
@@ -164,3 +164,45 @@ fn vector_operations_match_llvm() {
|
||||
assert_eq!(assembler.instructions(), [*word], "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn carry_arithmetic_matches_llvm() {
|
||||
// `llvm-mc -triple=aarch64-apple-macos -show-encoding`.
|
||||
let cases: &[(&str, Emit, u32)] = &[
|
||||
(
|
||||
"adcs x11, x9, x10",
|
||||
|a| a.adcs_reg_64(11, 9, 10),
|
||||
0xba0a012b,
|
||||
),
|
||||
(
|
||||
"adcs w11, w9, w10",
|
||||
|a| a.adcs_reg_32(11, 9, 10),
|
||||
0x3a0a012b,
|
||||
),
|
||||
(
|
||||
"adcs x0, x30, x17",
|
||||
|a| a.adcs_reg_64(0, 30, 17),
|
||||
0xba1103c0,
|
||||
),
|
||||
(
|
||||
"sbcs x11, x9, x10",
|
||||
|a| a.sbcs_reg_64(11, 9, 10),
|
||||
0xfa0a012b,
|
||||
),
|
||||
(
|
||||
"sbcs w11, w9, w10",
|
||||
|a| a.sbcs_reg_32(11, 9, 10),
|
||||
0x7a0a012b,
|
||||
),
|
||||
(
|
||||
"sbcs w0, w30, w17",
|
||||
|a| a.sbcs_reg_32(0, 30, 17),
|
||||
0x7a1103c0,
|
||||
),
|
||||
];
|
||||
for (text, emit, word) in cases {
|
||||
let mut assembler = Arm64Assembler::new();
|
||||
emit(&mut assembler);
|
||||
assert_eq!(assembler.instructions(), [*word], "{text}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,644 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Seeded sequences of original x86-64 instructions for issue #74.
|
||||
//!
|
||||
//! Expected states follow the Intel SDM (Vol. 1, §§3.4.1 and 3.4.3,
|
||||
//! Vol. 2, ADD, SUB, CMP, XOR, MOV, Jcc, CALL, RET, DEC, MOVDQU, PADDB,
|
||||
//! PSUBW and PXOR, and Vol. 3A, §7.15, Page-Fault Exception). The oracles work from arithmetic operands, branch
|
||||
//! predicates, array indices and vector lanes. They never decode the emitted
|
||||
//! bytes or use Xenora's instruction or flag helpers.
|
||||
//!
|
||||
//! <https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html>
|
||||
//!
|
||||
//! The x86 bytes run as guest code through a synthetic memory map and end at
|
||||
//! Xenora's HLT sentinel. To replay a failure, use the printed test name and
|
||||
//! XENORA_CPU_DIFFERENTIAL_CASE index. For example:
|
||||
//!
|
||||
//! ```sh
|
||||
//! XENORA_CPU_DIFFERENTIAL_CASE=0 cargo test --locked -p xenora-loader \
|
||||
//! --test cpu_differential seeded_register_sequences -- --exact
|
||||
//! ```
|
||||
//!
|
||||
//! The seed and bytes are printed for reproducing the program outside this
|
||||
//! harness as well.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
|
||||
const CODE: u64 = 0x40_0000;
|
||||
const DATA: u64 = 0x50_0000;
|
||||
const DATA_LEN: usize = 192;
|
||||
const STACK_TOP: u64 = DATA + DATA_LEN as u64;
|
||||
const BUDGET: usize = 128;
|
||||
const TEST_SEED: u64 = 0x74_da7a_c0de_ba5e;
|
||||
|
||||
// SplitMix64 with a fresh stream per case. Changing the corpus order does not
|
||||
// affect replay of an existing index.
|
||||
struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
let mut word = self.0;
|
||||
word = (word ^ (word >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
word = (word ^ (word >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
word ^ (word >> 31)
|
||||
}
|
||||
|
||||
fn below(&mut self, end: usize) -> usize {
|
||||
(self.next() % end as u64) as usize
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct State {
|
||||
cpu: CpuState,
|
||||
data: [u8; DATA_LEN],
|
||||
af_defined: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn seeded(random: &mut Random) -> Self {
|
||||
let mut cpu = CpuState::new(CODE, STACK_TOP);
|
||||
cpu.gpr = std::array::from_fn(|_| random.next());
|
||||
cpu.set(Register::Rsp, STACK_TOP);
|
||||
cpu.xmm =
|
||||
std::array::from_fn(|_| (u128::from(random.next()) << 64) | u128::from(random.next()));
|
||||
let flags = random.next();
|
||||
cpu.flags = RFlags {
|
||||
cf: flags & 1 != 0,
|
||||
pf: flags & 2 != 0,
|
||||
af: flags & 4 != 0,
|
||||
zf: flags & 8 != 0,
|
||||
sf: flags & 16 != 0,
|
||||
of: flags & 32 != 0,
|
||||
};
|
||||
cpu.df = flags & 64 != 0;
|
||||
cpu.fs_base = DATA;
|
||||
cpu.gs_base = DATA + 64;
|
||||
Self {
|
||||
cpu,
|
||||
data: std::array::from_fn(|_| random.next() as u8),
|
||||
af_defined: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn checkpoint(&mut self, trace: &mut Vec<Self>, offset: usize) {
|
||||
self.cpu.rip = CODE + offset as u64;
|
||||
trace.push(self.clone());
|
||||
}
|
||||
|
||||
fn word(&self, offset: usize) -> u64 {
|
||||
u64::from_le_bytes(self.data[offset..offset + 8].try_into().unwrap())
|
||||
}
|
||||
|
||||
fn put_word(&mut self, offset: usize, value: u64) {
|
||||
self.data[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
struct Case {
|
||||
code: Vec<u8>,
|
||||
initial: State,
|
||||
// State after each attempted instruction, including the terminal instruction.
|
||||
trace: Vec<State>,
|
||||
native_only: bool,
|
||||
exit: ExitReason,
|
||||
}
|
||||
|
||||
impl Case {
|
||||
fn memory(&self) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
CODE,
|
||||
self.code.len(),
|
||||
MemoryPermissions::READ_EXECUTE,
|
||||
&self.code,
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
DATA,
|
||||
DATA_LEN,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&self.initial.data,
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
fn verify(&self, id: &str) {
|
||||
let steps = self.trace.len();
|
||||
assert!(steps < BUDGET);
|
||||
let compare = |engine: &str,
|
||||
result: ExecutionResult,
|
||||
memory: &GuestMemory,
|
||||
budget: usize,
|
||||
offset: usize| {
|
||||
let steps = (steps - offset).min(budget);
|
||||
let expected = &self.trace[offset + steps - 1];
|
||||
let label = || {
|
||||
let start_rip = if offset == 0 {
|
||||
self.initial.cpu.rip
|
||||
} else {
|
||||
self.trace[offset - 1].cpu.rip
|
||||
};
|
||||
format!(
|
||||
"{id} {engine} from {start_rip:#x}, after {} guest steps, bytes {:02x?}",
|
||||
offset + steps,
|
||||
self.code
|
||||
)
|
||||
};
|
||||
let finished = offset + steps == self.trace.len();
|
||||
let exit = if finished {
|
||||
self.exit
|
||||
} else {
|
||||
ExitReason::StepLimitExceeded
|
||||
};
|
||||
let retired = steps - usize::from(finished && self.exit != ExitReason::Halt);
|
||||
assert_eq!(result.exit_reason, exit, "{}", label());
|
||||
assert_eq!(result.instructions_executed, retired, "{}", label());
|
||||
let mut actual = result.final_state;
|
||||
if !expected.af_defined {
|
||||
actual.flags.af = expected.cpu.flags.af;
|
||||
}
|
||||
assert_eq!(actual, expected.cpu, "{}", label());
|
||||
let mut data = [0; DATA_LEN];
|
||||
memory.read_bytes(DATA, &mut data).unwrap();
|
||||
if let Some(index) = data.iter().zip(expected.data).position(|(&a, b)| a != b) {
|
||||
panic!(
|
||||
"{}: guest byte at {:#x}: got {:#04x}, expected {:#04x}",
|
||||
label(),
|
||||
DATA + index as u64,
|
||||
data[index],
|
||||
expected.data[index]
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let mut stepped = DbtEngine::new(128 * 1024).unwrap();
|
||||
let mut interpreted_memory = self.memory();
|
||||
let mut translated_memory = self.memory();
|
||||
let mut interpreted_cpu = self.initial.cpu.clone();
|
||||
let mut translated_cpu = self.initial.cpu.clone();
|
||||
// Check the first divergent retired instruction before testing full
|
||||
// blocks. Each engine continues from its own state at every step.
|
||||
for offset in 0..steps {
|
||||
let result = Interpreter::new(interpreted_cpu, &mut interpreted_memory, 1).run();
|
||||
interpreted_cpu = result.final_state.clone();
|
||||
compare(
|
||||
"interpreter (1 step)",
|
||||
result,
|
||||
&interpreted_memory,
|
||||
1,
|
||||
offset,
|
||||
);
|
||||
|
||||
let result = stepped.run(&mut translated_cpu, &mut translated_memory, 1);
|
||||
compare("DBT (1 step)", result, &translated_memory, 1, offset);
|
||||
}
|
||||
|
||||
// Exercise native block lowering and then reuse those blocks with a
|
||||
// fresh copy of the guest input and memory at the same addresses.
|
||||
let mut dbt = DbtEngine::new(128 * 1024).unwrap();
|
||||
let mut memory = self.memory();
|
||||
let result = Interpreter::new(self.initial.cpu.clone(), &mut memory, BUDGET).run();
|
||||
compare("interpreter", result, &memory, BUDGET, 0);
|
||||
let mut run_full = |engine| {
|
||||
let mut memory = self.memory();
|
||||
let result = dbt.run(&mut self.initial.cpu.clone(), &mut memory, BUDGET);
|
||||
compare(engine, result, &memory, BUDGET, 0);
|
||||
dbt.metrics
|
||||
};
|
||||
let cold = run_full("DBT (cold)");
|
||||
let cached = run_full("DBT (cached)");
|
||||
assert!(cold.blocks_compiled > 0, "{id}");
|
||||
assert_eq!(cold.blocks_compiled, cached.blocks_compiled, "{id}");
|
||||
assert!(cached.cache_hits > cold.cache_hits, "{id}");
|
||||
assert!(cached.dbt_dispatches > cold.dbt_dispatches, "{id}");
|
||||
|
||||
// These budgets cut the longer programs around a 16-instruction
|
||||
// native block boundary, including a resume from the truncated block.
|
||||
for budget in [15, 16, 17].into_iter().filter(|&budget| budget < steps) {
|
||||
let mut memory = self.memory();
|
||||
let mut cpu = self.initial.cpu.clone();
|
||||
let result = dbt.run(&mut cpu, &mut memory, budget);
|
||||
compare("DBT (limited)", result, &memory, budget, 0);
|
||||
let result = dbt.run(&mut cpu, &mut memory, BUDGET);
|
||||
compare("DBT (resumed)", result, &memory, BUDGET, budget);
|
||||
}
|
||||
|
||||
if self.native_only {
|
||||
assert_eq!(dbt.metrics.interpreter_fallbacks, 0, "{id}");
|
||||
assert_eq!(stepped.metrics.interpreter_fallbacks, 0, "{id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Alu {
|
||||
Add,
|
||||
Sub,
|
||||
Compare,
|
||||
Xor,
|
||||
Move,
|
||||
}
|
||||
|
||||
impl Alu {
|
||||
const OPS: [Self; 5] = [Self::Add, Self::Sub, Self::Compare, Self::Xor, Self::Move];
|
||||
|
||||
// SDM Vol. 2, §2.1 and the r/m,reg forms for each instruction. A bare
|
||||
// REX prefix selects SPL/BPL/SIL/DIL instead of the high byte registers.
|
||||
fn encode(self, code: &mut Vec<u8>, bits: u32, dst: usize, src: usize) {
|
||||
if bits == 16 {
|
||||
code.push(0x66);
|
||||
}
|
||||
let rex = 0x40 | (u8::from(bits == 64) << 3) | ((src as u8 >> 3) << 2) | (dst as u8 >> 3);
|
||||
if rex != 0x40 || (bits == 8 && (src >= 4 || dst >= 4)) {
|
||||
code.push(rex);
|
||||
}
|
||||
let byte_opcode = match self {
|
||||
Self::Add => 0x00,
|
||||
Self::Sub => 0x28,
|
||||
Self::Compare => 0x38,
|
||||
Self::Xor => 0x30,
|
||||
Self::Move => 0x88,
|
||||
};
|
||||
code.extend([
|
||||
byte_opcode | u8::from(bits != 8),
|
||||
0xc0 | ((src as u8 & 7) << 3) | (dst as u8 & 7),
|
||||
]);
|
||||
}
|
||||
|
||||
fn expect(self, state: &mut State, bits: u32, dst: usize, src: usize) {
|
||||
let mask = u64::MAX >> (64 - bits);
|
||||
let left = state.cpu.gpr[dst] & mask;
|
||||
let right = state.cpu.gpr[src] & mask;
|
||||
let result = match self {
|
||||
Self::Move => right,
|
||||
Self::Xor => {
|
||||
let result = left ^ right;
|
||||
state.cpu.flags = result_flags(result, bits);
|
||||
state.af_defined = false;
|
||||
result
|
||||
}
|
||||
Self::Add | Self::Compare | Self::Sub => {
|
||||
let (result, flags) = arithmetic(left, right, bits, matches!(self, Self::Add));
|
||||
state.cpu.flags = flags;
|
||||
state.af_defined = true;
|
||||
result
|
||||
}
|
||||
};
|
||||
if !matches!(self, Self::Compare) {
|
||||
state.cpu.gpr[dst] = if bits >= 32 {
|
||||
result
|
||||
} else {
|
||||
(state.cpu.gpr[dst] & !mask) | result
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn result_flags(result: u64, bits: u32) -> RFlags {
|
||||
RFlags {
|
||||
zf: result == 0,
|
||||
sf: result >> (bits - 1) == 1,
|
||||
pf: (result as u8).count_ones().is_multiple_of(2),
|
||||
..RFlags::default()
|
||||
}
|
||||
}
|
||||
|
||||
// Carry, auxiliary carry and signed overflow are derived by separate
|
||||
// widened calculations. The exact signed result determines overflow.
|
||||
fn arithmetic(left: u64, right: u64, bits: u32, add: bool) -> (u64, RFlags) {
|
||||
let modulus = 1i128 << bits;
|
||||
let signed = |word: u64| {
|
||||
let word = i128::from(word);
|
||||
if word >= modulus / 2 {
|
||||
word - modulus
|
||||
} else {
|
||||
word
|
||||
}
|
||||
};
|
||||
let operation = |a: i128, b: i128| if add { a + b } else { a - b };
|
||||
let wide = operation(i128::from(left), i128::from(right));
|
||||
let result = wide.rem_euclid(modulus) as u64;
|
||||
let mut flags = result_flags(result, bits);
|
||||
flags.cf = !(0..modulus).contains(&wide);
|
||||
let nibble = operation(i128::from(left & 15), i128::from(right & 15));
|
||||
flags.af = !(0..16).contains(&nibble);
|
||||
let signed_result = operation(signed(left), signed(right));
|
||||
flags.of = !(-modulus / 2..modulus / 2).contains(&signed_result);
|
||||
(result, flags)
|
||||
}
|
||||
|
||||
fn seeded_cases(
|
||||
test: &str,
|
||||
family: u64,
|
||||
count: usize,
|
||||
make_case: impl Fn(usize, &mut Random) -> Case,
|
||||
) {
|
||||
let selected = std::env::var("XENORA_CPU_DIFFERENTIAL_CASE")
|
||||
.ok()
|
||||
.map(|text| {
|
||||
let index = text
|
||||
.parse::<usize>()
|
||||
.expect("XENORA_CPU_DIFFERENTIAL_CASE must be a decimal case index");
|
||||
assert!(index < count, "{test} has case indices 0..{count}");
|
||||
index
|
||||
});
|
||||
for index in selected.map_or(0..count, |index| index..index + 1) {
|
||||
let seed = TEST_SEED ^ (family << 48) ^ index as u64;
|
||||
let case = make_case(index, &mut Random(seed));
|
||||
case.verify(&format!(
|
||||
"{test}: XENORA_CPU_DIFFERENTIAL_CASE={index} (seed {seed:#018x})"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_register_sequences() {
|
||||
const WIDTHS: [u32; 4] = [8, 16, 32, 64];
|
||||
seeded_cases("seeded_register_sequences", 1, 240, |index, random| {
|
||||
let mixed_widths = index >= 160;
|
||||
let bits = WIDTHS[index % 4];
|
||||
let edges = [
|
||||
0,
|
||||
1,
|
||||
15,
|
||||
16,
|
||||
(1u64 << (bits - 1)) - 1,
|
||||
1 << (bits - 1),
|
||||
u64::MAX,
|
||||
];
|
||||
let mut initial = State::seeded(random);
|
||||
// Keep random high bits when the operand is narrower than the GPR.
|
||||
let mask = u64::MAX >> (64 - bits);
|
||||
for reg in [0, 1, 2, 3, 8, 9, 10, 11] {
|
||||
let edge = edges[random.below(edges.len())];
|
||||
initial.cpu.gpr[reg] = (initial.cpu.gpr[reg] & !mask) | (edge & mask);
|
||||
}
|
||||
let mut state = initial.clone();
|
||||
let mut code = Vec::new();
|
||||
let mut trace = Vec::new();
|
||||
for step in 0..24 {
|
||||
let bits = if mixed_widths {
|
||||
WIDTHS[(index + step) % WIDTHS.len()]
|
||||
} else {
|
||||
bits
|
||||
};
|
||||
let op = Alu::OPS[random.below(Alu::OPS.len())];
|
||||
let dst = random.below(16);
|
||||
let src = random.below(16);
|
||||
op.encode(&mut code, bits, dst, src);
|
||||
op.expect(&mut state, bits, dst, src);
|
||||
state.checkpoint(&mut trace, code.len());
|
||||
}
|
||||
code.push(0xf4);
|
||||
state.checkpoint(&mut trace, code.len());
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: !mixed_widths && bits >= 32,
|
||||
exit: ExitReason::Halt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn branch_predicate(condition: usize, flags: RFlags) -> bool {
|
||||
let base = [
|
||||
flags.of,
|
||||
flags.cf,
|
||||
flags.zf,
|
||||
flags.cf || flags.zf,
|
||||
flags.sf,
|
||||
flags.pf,
|
||||
flags.sf != flags.of,
|
||||
flags.zf || flags.sf != flags.of,
|
||||
][condition / 2];
|
||||
base ^ !condition.is_multiple_of(2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_compare_branch_pairs() {
|
||||
seeded_cases("seeded_compare_branch_pairs", 2, 128, |index, random| {
|
||||
let condition = index % 16;
|
||||
let taken = index / 16 % 2 != 0;
|
||||
let bits = [32, 64][index / 32 % 2];
|
||||
let near = index >= 64;
|
||||
let sign = 1u64 << (bits - 1);
|
||||
let boundary = [0, 1, 2, sign - 1, sign, sign | 1, (sign - 1) | sign];
|
||||
let pairs = boundary
|
||||
.into_iter()
|
||||
.flat_map(|left| boundary.map(|right| (left, right)));
|
||||
let eligible: Vec<_> = pairs
|
||||
.filter(|&(left, right)| {
|
||||
branch_predicate(condition, arithmetic(left, right, bits, false).1) == taken
|
||||
})
|
||||
.collect();
|
||||
let (left, right) = eligible[random.below(eligible.len())];
|
||||
let mut initial = State::seeded(random);
|
||||
let mask = u64::MAX >> (64 - bits);
|
||||
initial.cpu.gpr[0] = (initial.cpu.gpr[0] & !mask) | left;
|
||||
initial.cpu.gpr[8] = (initial.cpu.gpr[8] & !mask) | right;
|
||||
let mut state = initial.clone();
|
||||
let mut code = Vec::new();
|
||||
let mut trace = Vec::new();
|
||||
Alu::Compare.encode(&mut code, bits, 0, 8);
|
||||
Alu::Compare.expect(&mut state, bits, 0, 8);
|
||||
let branch = code.len();
|
||||
state.checkpoint(&mut trace, branch);
|
||||
if near {
|
||||
code.extend([0x0f, 0x80 + condition as u8, 3, 0, 0, 0]);
|
||||
} else {
|
||||
code.extend([0x70 + condition as u8, 3]);
|
||||
}
|
||||
// The two arms set distinct low bytes of RDX, then stop.
|
||||
let fallthrough = code.len();
|
||||
code.extend([0xb2, 0x31, 0xf4, 0xb2, 0x73, 0xf4]);
|
||||
let arm = fallthrough + if taken { 3 } else { 0 };
|
||||
state.checkpoint(&mut trace, arm);
|
||||
state.cpu.gpr[2] = (state.cpu.gpr[2] & !255) | if taken { 0x73 } else { 0x31 };
|
||||
state.checkpoint(&mut trace, arm + 2);
|
||||
state.checkpoint(&mut trace, arm + 3);
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: true,
|
||||
exit: ExitReason::Halt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_memory_loop_with_calls() {
|
||||
seeded_cases("seeded_memory_loop_with_calls", 3, 64, |_, random| {
|
||||
let count = random.below(8) + 1;
|
||||
let input = random.below(8);
|
||||
let output = 80 + random.below(8);
|
||||
let mut initial = State::seeded(random);
|
||||
initial.cpu.set(Register::Rcx, count as u64);
|
||||
initial.cpu.set(Register::Rsi, DATA + input as u64);
|
||||
initial.cpu.set(Register::Rdi, DATA + output as u64);
|
||||
let code = vec![
|
||||
0xe8, 10, 0, 0, 0, // 0: call sum
|
||||
0x48, 0x89, 0x44, 0xcf, 0xf8, // 5: mov [rdi + rcx*8 - 8], rax
|
||||
0xff, 0xc9, // 10: dec ecx
|
||||
0x75, 0xf2, // 12: jnz start
|
||||
0xf4, // 14: hlt
|
||||
0x48, 0x03, 0x44, 0xce, 0xf8, // 15: sum: add rax, [rsi + rcx*8 - 8]
|
||||
0xc3, // 20: ret
|
||||
];
|
||||
let mut state = initial.clone();
|
||||
let mut trace = Vec::new();
|
||||
let mut sum = state.cpu.get(Register::Rax);
|
||||
for remaining in (1..=count).rev() {
|
||||
state.put_word(DATA_LEN - 8, CODE + 5);
|
||||
state.cpu.set(Register::Rsp, STACK_TOP - 8);
|
||||
state.checkpoint(&mut trace, 15);
|
||||
|
||||
let index = (remaining - 1) * 8;
|
||||
let (next, flags) = arithmetic(sum, initial.word(input + index), 64, true);
|
||||
sum = next;
|
||||
state.cpu.set(Register::Rax, sum);
|
||||
state.cpu.flags = flags;
|
||||
state.checkpoint(&mut trace, 20);
|
||||
|
||||
state.cpu.set(Register::Rsp, STACK_TOP);
|
||||
state.checkpoint(&mut trace, 5);
|
||||
state.put_word(output + index, sum);
|
||||
state.checkpoint(&mut trace, 10);
|
||||
|
||||
let (counter, mut flags) = arithmetic(remaining as u64, 1, 32, false);
|
||||
flags.cf = state.cpu.flags.cf; // DEC leaves carry intact.
|
||||
state.cpu.set(Register::Rcx, counter);
|
||||
state.cpu.flags = flags;
|
||||
state.checkpoint(&mut trace, 12);
|
||||
state.checkpoint(&mut trace, if counter == 0 { 14 } else { 0 });
|
||||
}
|
||||
state.checkpoint(&mut trace, 15);
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: true,
|
||||
exit: ExitReason::Halt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_vector_load_arithmetic_store() {
|
||||
seeded_cases("seeded_vector_load_arithmetic_store", 4, 64, |_, random| {
|
||||
let mut initial = State::seeded(random);
|
||||
let input = random.below(16);
|
||||
let output = 64 + random.below(16);
|
||||
initial.cpu.set(Register::Rsi, DATA + input as u64);
|
||||
initial.cpu.set(Register::Rdi, DATA + output as u64);
|
||||
let code = vec![
|
||||
0xf3, 0x44, 0x0f, 0x6f, 0x0e, // 0: movdqu xmm9, [rsi]
|
||||
0x66, 0x44, 0x0f, 0xfc, 0xca, // 5: paddb xmm9, xmm2
|
||||
0x66, 0x45, 0x0f, 0xf9, 0xcf, // 10: psubw xmm9, xmm15
|
||||
0x66, 0x44, 0x0f, 0xef, 0xc8, // 15: pxor xmm9, xmm0
|
||||
0xf3, 0x44, 0x0f, 0x7f, 0x0f, // 20: movdqu [rdi], xmm9
|
||||
0xf4,
|
||||
];
|
||||
let mut state = initial.clone();
|
||||
let mut trace = Vec::new();
|
||||
let mut lanes: [u8; 16] = initial.data[input..input + 16].try_into().unwrap();
|
||||
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
|
||||
state.checkpoint(&mut trace, 5);
|
||||
|
||||
for (lane, addend) in lanes.iter_mut().zip(initial.cpu.xmm[2].to_le_bytes()) {
|
||||
*lane = lane.wrapping_add(addend);
|
||||
}
|
||||
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
|
||||
state.checkpoint(&mut trace, 10);
|
||||
|
||||
let subtrahend = initial.cpu.xmm[15].to_le_bytes();
|
||||
let (words, _) = lanes.as_chunks_mut::<2>();
|
||||
let (subtrahends, _) = subtrahend.as_chunks::<2>();
|
||||
for (word, &rhs) in words.iter_mut().zip(subtrahends) {
|
||||
let left = u16::from_le_bytes(*word);
|
||||
let right = u16::from_le_bytes(rhs);
|
||||
*word = left.wrapping_sub(right).to_le_bytes();
|
||||
}
|
||||
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
|
||||
state.checkpoint(&mut trace, 15);
|
||||
|
||||
state.cpu.xmm[9] ^= initial.cpu.xmm[0];
|
||||
state.checkpoint(&mut trace, 20);
|
||||
state.data[output..output + 16].copy_from_slice(&state.cpu.xmm[9].to_le_bytes());
|
||||
state.checkpoint(&mut trace, 25);
|
||||
state.checkpoint(&mut trace, 26);
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: true,
|
||||
exit: ExitReason::Halt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_precise_memory_faults() {
|
||||
seeded_cases("seeded_precise_memory_faults", 5, 28, |index, random| {
|
||||
// Both branch outcomes and both operand directions at each of the
|
||||
// seven possible byte splits of an eight-byte operand.
|
||||
let store = index.is_multiple_of(2);
|
||||
let taken = (index / 2).is_multiple_of(2);
|
||||
let split = index / 4 + 1;
|
||||
let mut initial = State::seeded(random);
|
||||
let output = random.below(32);
|
||||
let value = initial.cpu.get(Register::Rax);
|
||||
let rhs = if taken { value } else { value ^ (1 << 63) };
|
||||
initial.cpu.set(Register::R8, rhs);
|
||||
initial.cpu.set(Register::Rdi, DATA + output as u64);
|
||||
initial.cpu.set(Register::Rsi, STACK_TOP - split as u64);
|
||||
let code = vec![
|
||||
0x48,
|
||||
0x89,
|
||||
0x07, // 0: mov [rdi], rax
|
||||
0x4c,
|
||||
0x39,
|
||||
0xc0, // 3: cmp rax, r8
|
||||
0x74,
|
||||
0x03, // 6: je faulting_move
|
||||
0x4d,
|
||||
0x89,
|
||||
0xd1, // 8: mov r9, r10
|
||||
0x48,
|
||||
if store { 0x89 } else { 0x8b },
|
||||
0x06, // 11: mov [rsi], rax or mov rax, [rsi]
|
||||
0xf4,
|
||||
];
|
||||
let mut state = initial.clone();
|
||||
let mut trace = Vec::new();
|
||||
state.put_word(output, value);
|
||||
state.checkpoint(&mut trace, 3);
|
||||
state.cpu.flags = arithmetic(value, rhs, 64, false).1;
|
||||
state.checkpoint(&mut trace, 6);
|
||||
if taken {
|
||||
state.checkpoint(&mut trace, 11);
|
||||
} else {
|
||||
state.checkpoint(&mut trace, 8);
|
||||
state.cpu.set(Register::R9, initial.cpu.get(Register::R10));
|
||||
state.checkpoint(&mut trace, 11);
|
||||
}
|
||||
// The faulting instruction leaves RIP, registers and all mapped bytes
|
||||
// intact. The preceding store and optional register move stay retired.
|
||||
state.checkpoint(&mut trace, 11);
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: true,
|
||||
exit: ExitReason::MemoryFault(MemoryError::UnmappedAddress(STACK_TOP)),
|
||||
}
|
||||
});
|
||||
}
|
||||
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user