mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 18:41:11 +00:00
Compare commits
274
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20780eab24 | ||
|
|
f685edebfb | ||
|
|
c0cb3e72be | ||
|
|
a27d63bfab | ||
|
|
0f7658bb5b | ||
|
|
313430c1c6 | ||
|
|
63cf3595cd | ||
|
|
050df307a1 | ||
|
|
7a5176497a | ||
|
|
f4005501bc | ||
|
|
f175a10033 | ||
|
|
c651a9d320 | ||
|
|
22bafeb0b2 | ||
|
|
f56d3c9862 | ||
|
|
48f44cac3d | ||
|
|
8410e3d0e8 | ||
|
|
19bea60d25 | ||
|
|
f70e6d0534 | ||
|
|
223fe253c9 | ||
|
|
62be091197 | ||
|
|
cf288dd940 | ||
|
|
9f57d8b3bb | ||
|
|
5d4d15d596 | ||
|
|
95ddc28518 | ||
|
|
9cc4a965c4 | ||
|
|
9b767186a2 | ||
|
|
823007888f | ||
|
|
881c2a2e52 | ||
|
|
475b27e5d4 | ||
|
|
cac93574ce | ||
|
|
085b0e28e5 | ||
|
|
835689e5df | ||
|
|
55e1818ccd | ||
|
|
44ea8133fc | ||
|
|
756597a6b4 | ||
|
|
4038cdbe41 | ||
|
|
51b60381c5 | ||
|
|
2593f73f29 | ||
|
|
3f3f154d2d | ||
|
|
4d68733f3c | ||
|
|
d22f046bf9 | ||
|
|
430f63e27d | ||
|
|
ce29b87770 | ||
|
|
ad424d690a | ||
|
|
9e47234e92 | ||
|
|
5ba0496c63 | ||
|
|
cd224d86f4 | ||
|
|
dd4bcb30eb | ||
|
|
aef29ff65d | ||
|
|
3392c226ce | ||
|
|
72bf5f7e32 | ||
|
|
78df3a5c6b | ||
|
|
133c9df448 | ||
|
|
a6d354fb2a | ||
|
|
00f79c10d2 | ||
|
|
95a8c61f1b | ||
|
|
31627363f1 | ||
|
|
ee2d29a65c | ||
|
|
83ef49c258 | ||
|
|
84b6fb4d50 | ||
|
|
b98380c1b0 | ||
|
|
7fa240f7ba | ||
|
|
0e9211cd42 | ||
|
|
c41e034fa1 | ||
|
|
7977dd4bf2 | ||
|
|
cd948d4a14 | ||
|
|
a2c696b551 | ||
|
|
d6189ae3ea | ||
|
|
e6eece6983 | ||
|
|
1a78265ede | ||
|
|
2e0e5a36f6 | ||
|
|
ece0fc27eb | ||
|
|
82f2d9e9e6 | ||
|
|
391367a531 | ||
|
|
e71a3da525 | ||
|
|
b96511bfc5 | ||
|
|
84bb80d910 | ||
|
|
9edf644d77 | ||
|
|
b5d0382e89 | ||
|
|
b705104403 | ||
|
|
f148b51a48 | ||
|
|
c979870b3a | ||
|
|
cd59e081d9 | ||
|
|
0bfb12fd17 | ||
|
|
c6d0986da2 | ||
|
|
9a9422c7da | ||
|
|
da41b6420d | ||
|
|
3f710928af | ||
|
|
2fdf01fbb3 | ||
|
|
de00cb2bfd | ||
|
|
d8f9669280 | ||
|
|
19b2e9b5d5 | ||
|
|
bb6bc52c95 | ||
|
|
ba6bbb2e4a | ||
|
|
705b074a08 | ||
|
|
d3c1150854 | ||
|
|
a81d62ffe3 | ||
|
|
bb1372cd70 | ||
|
|
8d53d82981 | ||
|
|
ba2cfc2a00 | ||
|
|
b13ab327f2 | ||
|
|
e7cb8db14f | ||
|
|
e7795d0e5a | ||
|
|
3ff9ddde24 | ||
|
|
ff191d89bd | ||
|
|
4039be8ee2 | ||
|
|
898b79dc84 | ||
|
|
30d20c8f33 | ||
|
|
0687a8add6 | ||
|
|
791b736b0e | ||
|
|
fcda9c09bd | ||
|
|
ad5a6f9c53 | ||
|
|
f856671b6d | ||
|
|
e1317322e1 | ||
|
|
92fd955a8d | ||
|
|
0609012903 | ||
|
|
dffa50cd9c | ||
|
|
b541dce0cc | ||
|
|
52ecece126 | ||
|
|
440856a997 | ||
|
|
1eeb614ea2 | ||
|
|
afd936b20b | ||
|
|
6772205213 | ||
|
|
4b5e2b690d | ||
|
|
ee6c9ac067 | ||
|
|
1680e6b19c | ||
|
|
3eef0ecfa8 | ||
|
|
999de9f2df | ||
|
|
e616583c3f | ||
|
|
025f9dfd21 | ||
|
|
d8c02270ee | ||
|
|
08c4451e68 | ||
|
|
2ab189ddbe | ||
|
|
fa94b56ba3 | ||
|
|
385e7a0729 | ||
|
|
819699e8a7 | ||
|
|
4404e3f4bb | ||
|
|
d35cea8eff | ||
|
|
8a69f80aa0 | ||
|
|
c21d9ba92a | ||
|
|
e06242f2e0 | ||
|
|
c9e3394eb3 | ||
|
|
72d2ceb967 | ||
|
|
358ddc5eba | ||
|
|
09cf27186c | ||
|
|
9ac1343e34 | ||
|
|
078afd4591 | ||
|
|
4741409de1 | ||
|
|
6cbe976990 | ||
|
|
857bec29e1 | ||
|
|
7b6c6fd92c | ||
|
|
28846561ab | ||
|
|
817a95b419 | ||
|
|
33c025a785 | ||
|
|
c0cbc2f787 | ||
|
|
e8b0a380e9 | ||
|
|
df3b9674a3 | ||
|
|
db50deb9f7 | ||
|
|
76679a9c05 | ||
|
|
6785cb04e3 | ||
|
|
99c8331576 | ||
|
|
077a215d49 | ||
|
|
3c710b53ba | ||
|
|
4886e9cd80 | ||
|
|
4dc10ae437 | ||
|
|
16debc8fdb | ||
|
|
ee8347a39f | ||
|
|
6689761db3 | ||
|
|
7aa8166cf2 | ||
|
|
c107f3a43f | ||
|
|
b041952437 | ||
|
|
ae80d7fd8f | ||
|
|
d57e9c031c | ||
|
|
924d68afbc | ||
|
|
840eca0a29 | ||
|
|
0749330868 | ||
|
|
2ddd2a2485 | ||
|
|
0e7fa4aa93 | ||
|
|
1ee557bdc4 | ||
|
|
fa4d4b9d71 | ||
|
|
bf3cca0718 | ||
|
|
a86100c00d | ||
|
|
044f036ea5 | ||
|
|
79947ec998 | ||
|
|
17fe880bdc | ||
|
|
e93e4e1e2a | ||
|
|
425327a0f2 | ||
|
|
1212280ab8 | ||
|
|
c6665ebfb4 | ||
|
|
96e2baeb75 | ||
|
|
b9be341dfc | ||
|
|
b2391b4de4 | ||
|
|
ecc109a7e2 | ||
|
|
67e6565fc2 | ||
|
|
994efd38f9 | ||
|
|
aac0f31b93 | ||
|
|
ef0e472d5d | ||
|
|
1784836639 | ||
|
|
68fc4e25dc | ||
|
|
cdaff0a391 | ||
|
|
184149561a | ||
|
|
e83475be17 | ||
|
|
fa55066699 | ||
|
|
f25060e891 | ||
|
|
9318e68840 | ||
|
|
abd6698a66 | ||
|
|
5f8867bd30 | ||
|
|
5ca90bfac0 | ||
|
|
7cc35ffd41 | ||
|
|
57f10c1d7c | ||
|
|
76620e274b | ||
|
|
240302fabe | ||
|
|
01deb3f8a8 | ||
|
|
e6b9a27242 | ||
|
|
8fdb569052 | ||
|
|
e79bd1ccaf | ||
|
|
066bc3fc83 | ||
|
|
a533d8107e | ||
|
|
3109b620fd | ||
|
|
878f554dcd | ||
|
|
46e2d36064 | ||
|
|
d94121bbb0 | ||
|
|
ef4fbba797 | ||
|
|
97ea2541bb | ||
|
|
f1ec653b91 | ||
|
|
b1ab08c09d | ||
|
|
6b479a6617 | ||
|
|
7a10d7eac8 | ||
|
|
0e51ddda76 | ||
|
|
b5a462fb54 | ||
|
|
09e0bea55d | ||
|
|
1260e07ba1 | ||
|
|
e70780f30a | ||
|
|
ef481368d6 | ||
|
|
0cac6c4fcf | ||
|
|
3a598a83e1 | ||
|
|
b69d4b97c6 | ||
|
|
97598903e2 | ||
|
|
9fda5aab18 | ||
|
|
af68f7da74 | ||
|
|
dcf723e49d | ||
|
|
6d7523f5d1 | ||
|
|
cf2d0cfb0b | ||
|
|
585edd313f | ||
|
|
69812d97c0 | ||
|
|
e86eedf583 | ||
|
|
59ee786a12 | ||
|
|
5df1f9146f | ||
|
|
e37c8566c6 | ||
|
|
48e42d6d4b | ||
|
|
964026901f | ||
|
|
98bbe57471 | ||
|
|
5baa630ff0 | ||
|
|
60f4f38da1 | ||
|
|
951189c61b | ||
|
|
1493dcf83b | ||
|
|
54506125d4 | ||
|
|
7c89ed62a2 | ||
|
|
b9b0a40101 | ||
|
|
f19d57967d | ||
|
|
62c933051b | ||
|
|
e35df04069 | ||
|
|
c88359b379 | ||
|
|
c12ad2e2f8 | ||
|
|
ef1a94ce71 | ||
|
|
a89f9d8d06 | ||
|
|
93bd04c70f | ||
|
|
0329e683b5 | ||
|
|
0be6220e47 | ||
|
|
e3c082ca9d | ||
|
|
9cf09cb823 | ||
|
|
6722c041d1 | ||
|
|
11e95b9e54 | ||
|
|
cc8c71ce86 |
No files matched your search
@@ -0,0 +1,67 @@
|
||||
name: Agent task
|
||||
description: A self-contained work item that a contributor or coding agent can claim with /claim.
|
||||
title: "task: "
|
||||
labels: [agent:ready]
|
||||
body:
|
||||
- type: dropdown
|
||||
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."
|
||||
options:
|
||||
- cpu
|
||||
- gpu
|
||||
- runtime
|
||||
- shared
|
||||
- qa
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: priority
|
||||
attributes:
|
||||
label: Priority
|
||||
options:
|
||||
- critical
|
||||
- high
|
||||
- medium
|
||||
- low
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: interface
|
||||
attributes:
|
||||
label: Interface
|
||||
description: For shared tasks, the interface name and the version or upstream commit it targets. Leave empty otherwise.
|
||||
- type: textarea
|
||||
id: goal
|
||||
attributes:
|
||||
label: Goal
|
||||
description: What must be true when the task is finished, in one or two sentences.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
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.
|
||||
render: text
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance command
|
||||
description: The exact command whose success proves the task is done. It must fail before the change. It is never run automatically; a maintainer must approve it with /approve-acceptance.
|
||||
render: sh
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: depends
|
||||
attributes:
|
||||
label: Depends on
|
||||
description: Issue numbers that must be closed first, for example "#12, #15". Leave empty when none.
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Context
|
||||
description: Specification sections, interface notes and known limits. Public sources only.
|
||||
@@ -1,6 +1,8 @@
|
||||
## Summary
|
||||
|
||||
<!-- What changes, and why? Link an issue if relevant. -->
|
||||
<!-- What changes, and why? -->
|
||||
|
||||
Closes #<!-- the issue you claimed -->
|
||||
|
||||
## Implementation and evidence
|
||||
|
||||
@@ -23,6 +25,7 @@
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"lease_hours": 168,
|
||||
"upstream": "ranveersoni98/Xenora",
|
||||
"maintainers": ["ranveersoni98"],
|
||||
"contributors": {
|
||||
"ranveersoni98": ["cpu", "shared", "qa"],
|
||||
"elforeign": ["gpu", "shared", "qa"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
name: Agent task claims
|
||||
|
||||
# Applies queue commands (/claim, /release, /reassign, /progress, /blocked,
|
||||
# /unblock, /approve-acceptance) and audits the queue hourly. Comment and issue
|
||||
# text is only parsed as data by scripts/agent_queue; it is never executed and
|
||||
# never interpolated into a shell. Not yet run on GitHub.
|
||||
#
|
||||
# Both jobs share one concurrency group, so decisions never race. GitHub keeps
|
||||
# at most one pending run per group and cancels the older pending run when a
|
||||
# newer one queues, so a run does not decide only its own comment: `replay`
|
||||
# decides every command of the last lease_hours that has no bot reply yet,
|
||||
# oldest first. The surviving run, or at the latest the hourly audit, answers
|
||||
# the commands of cancelled runs. Comments that do not start with `/` start no run.
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
schedule:
|
||||
- cron: "17 * * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
command:
|
||||
if: github.event_name == 'issue_comment' && !github.event.issue.pull_request && startsWith(github.event.comment.body, '/')
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
# One global group: claims are decided one at a time so file-overlap checks cannot race.
|
||||
concurrency:
|
||||
group: agent-queue
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Decide and apply
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/state.json"
|
||||
python3 -m agent_queue replay --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
|
||||
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
|
||||
|
||||
audit:
|
||||
if: github.event_name != 'issue_comment'
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: read
|
||||
concurrency:
|
||||
group: agent-queue
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Decide commands whose runs were cancelled
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/commands.json"
|
||||
python3 -m agent_queue replay --state "$RUNNER_TEMP/commands.json" > "$RUNNER_TEMP/replay.json"
|
||||
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/replay.json"
|
||||
- name: Lapse stale claims, flag invalid tasks, write summary
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" > "$RUNNER_TEMP/state.json"
|
||||
python3 -m agent_queue audit --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
|
||||
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
|
||||
{
|
||||
echo '## Agent queue summary'
|
||||
echo '```json'
|
||||
python3 -m agent_queue summary --state "$RUNNER_TEMP/state.json" --now "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -0,0 +1,102 @@
|
||||
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
|
||||
@@ -37,10 +37,23 @@ jobs:
|
||||
rustc -vV
|
||||
- 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
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
done
|
||||
- name: Test agent task queue
|
||||
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 semantic registry generator and coverage report
|
||||
run: |
|
||||
python3 -m unittest discover -s tests/semantics_generator
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/semantic_coverage
|
||||
- name: Check formatting and lint
|
||||
run: |
|
||||
cargo fmt --all -- --check
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
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"
|
||||
@@ -35,3 +35,8 @@
|
||||
|
||||
__pycache__/
|
||||
*.pyc
|
||||
/diagnostics/gta6-candidate-*/
|
||||
/diagnostics/gta6-check/
|
||||
|
||||
# Native application build output
|
||||
/app/.build/
|
||||
@@ -45,6 +45,19 @@ No AI slop (section 29).
|
||||
|
||||
Read docs/interfaces.md and docs/progress.md before implementation.
|
||||
|
||||
## Claiming work before you start
|
||||
|
||||
Several people and coding agents work on this repository at the same time. Claim an issue before you edit anything, and never take work someone else has claimed.
|
||||
|
||||
1. **Check.** Read every comment on the issue and look for open pull requests that link it. A claim is any comment in which someone says they are taking the issue, in any words (for example "I'll take this" or `/claim`). If a claim exists and is not stale (step 4), pick another issue.
|
||||
2. **Claim.** Reply on the issue in plain words, for example: "I'm taking this. Plan: …". No command, label or bot step is needed. The earliest claim wins. Claim one issue per comment.
|
||||
3. **Stay in scope.** If the issue lists files, edit only those, and ask on the issue before widening the list. Do not start work that edits the same files as another claimed issue.
|
||||
4. **Stale claims.** A claim is stale when the claimer has not opened a pull request for the issue within about one week (7 days) of the claim. Only then may someone else take it, by replying on the issue, for example: "Taking this over: @name's claim from <date> has no pull request after 7 days." A claim with an open pull request is never stale; ask the claimer or the maintainer instead.
|
||||
5. **Release.** If you stop working on an issue, say so on the issue so others can take it.
|
||||
6. **Link.** Put `Closes #<n>` in the pull request description.
|
||||
|
||||
A coding agent claims in the name of the person it works for and follows the same rules. It must read the comments before claiming, and must never claim over, remove or ignore another person's claim. The optional task-queue commands in `docs/coordination/agent-tasks.md` do not replace these rules: a plain-reply claim counts even though the bot does not track it.
|
||||
|
||||
## Changelog maintenance
|
||||
|
||||
- At the start of every engineering task, read `CHANGELOG.md` alongside the relevant project documentation. Review the existing `[Unreleased]` entries before implementation to avoid duplicating completed work.
|
||||
@@ -82,6 +95,10 @@ Read docs/interfaces.md and docs/progress.md before implementation.
|
||||
|
||||
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.
|
||||
|
||||
Do not add AI attribution or Co-authored-by trailers to commits.
|
||||
Never commit or push without explicit permission.
|
||||
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.
|
||||
+125
@@ -10,7 +10,126 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- 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.
|
||||
- Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215.
|
||||
- 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 interactive guest execution with dynamic input handling and rendering to the native application (Gate 4, #276). The C interface gains `xenora_session_start_interactive_loop`, `xenora_session_send_input`, `xenora_session_queue_input`, and `xenora_session_get_recorded_frame`, along with input masks (`XENORA_INPUT_*`) and `xenora_input_state`. The original interactive guest fixture (`fixtures/pe/interactive.exe`, generated by `fixtures/pe/interactive.py` using only the supported ARM64 DBT instruction subset) polls host input via `xenora.dll!input_poll` and steers its rendered column position (0..3) on native Metal. Xenora.app gains interactive frame-loop controls ("Interactive (300 frames)", "◀ Left", "▶ Right", "Release") and `--smoke-interactive`. Four GPU acceptance tests with Metal validation verify that input events drive guest state and pixel geometry, deterministic input replay reproduces identical frame sequences across multiple sessions, key release and focus loss cleanly hold position without stuck keys, and destroying an interactive session joins promptly. Wired the interactive tests into `scripts/test-gpu.sh`.
|
||||
|
||||
- Added persistent guest rendering with pause, resume and stop to the native application (Gate 3, #266). The C interface gains `xenora_session_start_frame_loop`, `xenora_session_pause_frame_loop`, `xenora_session_resume_frame_loop`, `xenora_session_stop_frame_loop`, and `xenora_session_frame_loop_status`, plus new states (`XENORA_LOOP_*`). The guest fixture (`fixtures/pe/frame-loop.exe`, generated by `fixtures/pe/frame-loop.py` without external toolchains) runs on a session-owned thread and repeatedly calls `xenora.dll!frame_submit` until told to halt; each frame is rendered on native Metal, checked per pixel against geometric expectations, and returned via read-back RGBA8 buffers. Destroying a running or paused session safely stops its loop outside the global session lock. Xenora.app gains persistent frame-loop controls ("Start 300 frames", "Pause", "Resume", "Stop") and displays live frames with their frame index. Five GPU acceptance tests with Metal API and GPU validation verify frame ordering over 300 frames, live sampling across 2,000 frames without backwards progression, pause/resume/stop lifecycle, prompt join on session destruction, and stable memory footprint across repeated sessions. Added `--smoke-loop` to Xenora.app and wired the acceptance tests into `scripts/test-gpu.sh`.
|
||||
|
||||
- Added read-only executable inspection to the native app (#267). Xenora.app can open a PE file with Open Executable…, by dropping it on the window, or from Finder (it registers as an alternate viewer for Windows executables). The new C function `xenora_inspect_executable` returns a text report built from the existing static probe and loader validation: file size and SHA-256, header facts, whether `ParsedPe::parse` accepts the file, sections, imports not provided by Xenora's standard runtime services, the bounded static disassembly's count of instructions the ARM64 DBT does not support with the first one's address, and relocation and TLS counts. Nothing in the file is executed, and executing opened files remains unavailable pending #257. Inputs over 256 MiB are refused before reading. A panic inside the probe is reported as a Xenora defect instead of crashing the app; the new truncation test found one in `probe_pe_bytes` (truncations of `trusted-runner.exe` to 1,556–1,665 bytes slice past the end of the file while reading an import name), reported as #270 and not fixed here. Checked with the x1 executables in `experiments/x1/fixtures`, which the app does not embed, with malformed inputs, and in the window through the Finder open path and the Open panel; drag and drop was not exercised.
|
||||
- Added eleven gfx1030 SOP1 unary forms through the semantic registry: `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`, `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32` (AMD guide section 12.3). Searches that find nothing return -1, `s_abs_i32` of 0x80000000 stays 0x80000000, and only NOT, BCNT0, BCNT1 and ABS write SCC. The registry gained these primitives, a `sop1_sgpr` operand rule, and a declared `source_bits` for sign extension that is checked against the XML's 8- and 16-bit source operands. The reference and independent semantic-review interpreters, written separately from the guide, evaluate the same eleven forms and are checked against 4,126 guide-derived cases on both CPU interpreters and on native Metal with validation; 231 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all eleven. Part of #215.
|
||||
- Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot.
|
||||
- Added a minimal native macOS application shell and its Rust interface (Gate 1 of the native application work). `crates/ffi` builds a static library with a versioned C interface (`crates/ffi/include/xenora.h`, version 1): opaque, generation-checked 64-bit session handles (never pointers), at most 64 live sessions, stable status codes, and panics caught at the boundary. Version 1 can only create and destroy sessions and parse the bundled trusted PE fixture; it executes no guest code. `app/` is a SwiftUI app built with Swift Package Manager that shows the interface version and the fixture's section count and entry point. `scripts/build-app.sh` builds an ad-hoc-signed, arm64-only `build/Xenora.app` with no entitlements and runs its `--smoke` check. Six Rust tests cover invalid, stale and double-destroyed handles, version mismatch, null outputs, 4,000 concurrent create and destroy cycles, and header/constant agreement. The CLI and headless workflows are unchanged. Verified locally on one Apple Silicon Mac (macOS 27.2.1, Swift 6.4, Rust 1.100.0); not yet run in CI.
|
||||
- Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases on both CPU interpreters and on native Metal with validation; 348 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all twelve. Two literal selectors stay rejected. Part of #215, stage D.
|
||||
- Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C.
|
||||
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
|
||||
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
|
||||
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
|
||||
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
|
||||
- Added a `cpu_decode` cargo-fuzz target for the static x86-64 decoder used by the read-only PE probe. It places up to 4,096 fuzz bytes as the code section of a fixed, original PE32+ header and runs `probe_pe_bytes` twice with a bounded `ProbeConfig` (4,096 bytes, 2,048 instructions, 1,024 worklist entries); nothing is executed. It checks that the two reports are identical and that every decoded instruction is 1 to 15 bytes long, lies inside the code and matches the input bytes. A startup self-check aborts the run if the synthetic header stops reaching the decoder. A 600-second local campaign (nightly cargo-fuzz, one fork-mode worker, seeded from instruction bytes in the loader's probe tests; about 2.38 million executions, coverage 1,350 edges) found one decoder defect, reported to the CPU owner on #74 and not fixed here: the probe accepts unlimited FS/GS segment prefixes and reports instructions longer than 15 bytes (minimized input: 16 bytes of `0x65`). Run it with `rustup run nightly cargo fuzz run cpu_decode`; `scripts/fuzz.sh` does not list it yet.
|
||||
- Added a `pe_parse` cargo-fuzz target that feeds malformed bytes to the PE32+ parser (`ParsedPe::parse`, `rva_to_file_offset`) and, only when the summed section mapping size and `SizeOfImage` are both at most 64 MiB, to the checked guest-memory mapping step (`load_into_memory`); nothing is executed. A 600-second local campaign (nightly cargo-fuzz, fork mode, seeded from the repository's synthetic PE fixtures, about 120,000 executions, coverage 267 edges) found two loader panics, reported to the CPU owner and not fixed here: truncated optional headers panic on out-of-range slices in `parse`, and `rva_to_file_offset` overflows `u32` when a section's address plus size exceeds 4 GiB. Run it with `rustup run nightly cargo fuzz run pe_parse`; `scripts/fuzz.sh` does not list it yet.
|
||||
- Added `NativeCompute::run_words_with_group_width` and `max_group_width` to run a trusted kernel at an explicit threadgroup width, rejecting zero and widths above the device or pipeline limit. Native tests check 91 legal width and grid-size pairs (widths 1 to 1,024, including non-divisible grids) against independently computed outputs, and confirm the dispatched group sizes, including trimmed last groups. On an Apple M5 Pro, in three release runs of a 4,096-thread integer-mixing kernel (30 samples per width), widths 64, 128 and 256 were within 0.3 % of each other in two runs, at a median of 58.8 µs of GPU time. Width 512 was 5 to 6 % slower and width 1,024 about twice as slow in all three runs. The first run was about 4.7 times slower overall for reasons not determined, and in it 128 and 256 were 3 to 4 % faster than 64. The default width of 64 is unchanged. This was measured on one device and one workload.
|
||||
- Added a native Metal depth pass, `NativeCompute::render_depth`: up to 16 triangles drawn in order into an RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. A pass without an attachment accepts only `DepthState::DISABLED`. Colour and the stored depth are both read back; the depth values are returned as the texture read gives them, without numeric conversion. A draw can sample an original BC1 texture whose blocks are uploaded to a native `BC1_RGBA` texture without CPU decoding, gated on `supportsBCTextureCompression`. Checked on the GPU with Metal validation in 30 passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled (`Always` without writes) with an attachment and no attachment at all, and a BC1-textured draw. Colour and depth are compared per pixel against expectations derived independently from the geometry, the Metal compare semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces. These are synthetic fixtures only; no console depth formats or guest render state are involved.
|
||||
- Added a CPU BC7 block decoder in `xenora-texture` for all eight modes, with explicit handling of the invalid all-zero mode byte. It is checked by hand-derived tests and 430 known-answer vectors from a separate clean-room reference written from the Khronos Data Format Specification (merged in PR #224 without a changelog entry).
|
||||
- Added independent negative tests for gfx1030 extension words: truncated literal, SDWA, DPP16, DPP8 and MIMG NSA trailers (62 prefixes of 18 LLVM-assembled instructions), disallowed extensions, and length recognition kept apart from semantic validity. Tests only, with no decoder change (merged in PR #231 without a changelog entry).
|
||||
- Added the gfx1030 Wave32 VOPC compares `v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32`. VCC_LO is EXEC_LO & the per-lane test, always fully written, so empty EXEC gives 0. A compare result can feed `s_cbranch_vccz`, `v_mov_b32_e32 vN, vcc_lo` and another compare's source; nothing else, so EXEC never becomes data-dependent. A data-dependent `s_cbranch_vccz` is a wave-uniform branch over integer vector ALU code, lowered to a select at the join. The Metal kernel builds each mask by recomputing the 32 lanes of its own RDNA wave, with no SIMD-group, threadgroup or barrier assumption. The reference now runs lockstep Wave32 waves. Verified on an LLVM-assembled fixture plus 251 original programs (boundary operands, partial and empty EXEC, both branch edges, a partial final wave) against exact integer definitions: translator, reference and second interpreter agree on CPU, and all 252 match on native Metal with validation. LLVM agrees on every encoding. VOP3, SDWA, DPP, `v_cmpx` and Wave64 stay rejected. See `docs/shaders/vector-compare.md`.
|
||||
- Added the gfx1030 SOP2 forms `s_add_i32` and `s_sub_i32`, with SCC as signed overflow as defined in the AMD RDNA 2 ISA guide (sections 5.3 and 12.1). They are checked on CPU and on native Metal with validation on 400 boundary programs, four immediate-operand overflows and the scalar ALU fixture, plus eight hand-worked overflow and no-overflow cases on CPU.
|
||||
- Added the gfx1030 SOP2 scalar forms `s_add_u32`, `s_sub_u32`, `s_addc_u32`, `s_subb_u32`, `s_and_b32`, `s_or_b32` and `s_xor_b32`. They are decoded, executed by the reference and independent interpreters, and resolved by the translator, with SCC as carry, borrow or nonzero result. `v_mov_b32_e32` can now read a normal SGPR. Verified on 1,400 original operand vectors plus an LLVM-assembled fixture, on CPU and on native Metal with validation. The other SOP2 forms stay unsupported. See `docs/shaders/scalar-alu.md`.
|
||||
- Added `scripts/audit/test_inventory.py`, which lists the Cargo test inventory of two commits in temporary detached worktrees and reports removed, added, newly ignored and newly un-ignored tests, failing on any loss not explained in an `--allow` file. Run against the old PR #166 head 5450612 and main 951189c, it reports the 12 BC texture tests that head was missing (exit 1); the same commit against itself reports no change. Default features only; see `docs/testing/test-inventory.md`.
|
||||
- Added complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML: 1,465 base forms across 21 encoding families with fields, operands, flags and allowed extension words. A committed, normalised snapshot lets `crates/isa/generate_rdna2_meta.py --check` verify the generated table offline; CI runs it.
|
||||
- Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture and with LLVM 23.1.6 on a probe set covering each family and extension word. Identification does not make an instruction executable: `SEMANTIC_FORMS` lists the forms with semantic decoding (46 as of the VOPC compares).
|
||||
- Added `xenora shaders coverage [--json]` and `xenora shaders inspect <file>` for per-family coverage and stream listings that separate decoding failures from unsupported semantics. Each instruction is decoded at its stream offset and branch targets are checked against the whole stream's boundaries, so supported branches are no longer misreported as unsupported operands. `xenora_decoder::decode_at` decodes a single instruction for such callers.
|
||||
- Added an agent task queue for the cpu, gpu, runtime, shared and qa areas: an *Agent task* issue form with priority and interface fields, a workflow that decides `/claim`, `/release`, `/reassign`, `/progress`, `/blocked`, `/unblock` and `/approve-acceptance` comments one at a time (dependency, cycle and file-overlap checks, 24-hour leases renewed by progress), a pull request check (linked claimed task, file ownership, overlap with other pull requests, independent `/verified <head sha>`), `scripts/agent-queue.sh` and `scripts/agent-sync.sh` (upstream fetch every 12 minutes, task branches in separate worktrees) and a machine-readable queue summary. The rules are standard-library Python in `scripts/agent_queue/` with unit tests in `tests/agent_queue/`; issue text is never executed and acceptance commands need maintainer approval. Only comments that start with a command start a job, so ordinary pull request comments never re-run verification, and only an accepted `/verified <full head sha>` evaluates the check again; and each claim run decides every unanswered command in order, so commands whose pending runs GitHub cancelled are still answered. See `docs/coordination/agent-tasks.md`. Unit tests pass locally; the workflows have not run on GitHub yet, and the pull request check stays advisory (it never blocks a merge) until a live smoke test and the migration of existing issues are done.
|
||||
- Added explicit claim-before-work rules for contributors and coding agents to `AGENTS.md`, `CONTRIBUTING.md` and the pull request template: check for existing claims, claim with `/claim`, keep a 24-hour lease alive with `/progress`, `/release` when stopping, and link the claimed issue. Without the claim workflow, the earliest valid claim comment wins.
|
||||
- Added a CPU decoder for a bounded subset of BC6H (signed and unsigned HDR) in
|
||||
`xenora-texture`: the four single-subset modes (Khronos modes 3, 7, 11 and 15, Microsoft
|
||||
modes 11 to 14), listed in `BC6H_SUPPORTED_MODES`, plus the reserved modes, which decode to
|
||||
zero as specified. The ten two-subset modes are rejected with `Bc6hError::UnsupportedMode`
|
||||
and are not implemented. Tests check hand-derived values and 128 known-answer vectors from a
|
||||
separate clean-room reference decoder.
|
||||
- Added native Metal upload and readback of BC4 and BC5 textures (UNORM and SNORM):
|
||||
`xenora-texture` gains a pitched `BcChannelUpload`, and `NativeCompute::read_bc_channel_upload`
|
||||
sends the original blocks to `BC4_R*` or `BC5_RG*` textures when the device reports BC
|
||||
support, failing with `supportsBCTextureCompression` otherwise. GPU tests cover six- and
|
||||
eight-value interpolation, equal and extreme endpoints (signed -128 reads as -1.0), red-green
|
||||
channel order, padded row and slice pitches, two layers and two mips against the CPU decoders
|
||||
and hand-derived anchors. On an Apple M5 Pro interpolated codes were within 1.71 codes of the
|
||||
exact values and up to two codes from the truncating CPU reference.
|
||||
Edge levels of 5×3 and 1×1 and invalid payloads (zero extents, short, oversized or
|
||||
block-count-mismatched buffers) are covered.
|
||||
- Added native Metal upload and readback of BC2 and BC3 textures: `xenora-texture` gains a
|
||||
pitched `BcAlphaUpload` for 16-byte blocks, and `NativeCompute::read_bc_alpha_upload` sends
|
||||
the original blocks to `BC2_RGBA` or `BC3_RGBA` textures when the device reports BC support.
|
||||
GPU tests cover explicit and interpolated (six- and eight-value) alpha, both colour endpoint
|
||||
orders, padded row and slice pitches, two layers and two mips against the CPU decoders and
|
||||
hand-derived anchors. On an Apple M5 Pro the native decoder's interpolated values were within
|
||||
8/7 (about 1.14) codes of the exact values, so up to two codes from the truncating CPU reference.
|
||||
Edge levels of 5×3 (one block row) and 1×1 are covered, invalid payloads (zero extents,
|
||||
short, oversized or block-count-mismatched buffers, bad pitches) are rejected before upload,
|
||||
and `MetalError::is_capability_unavailable` separates a device without BC support from an
|
||||
implementation failure.
|
||||
- Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet.
|
||||
- Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution
|
||||
test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and
|
||||
verifies the value lands in guest memory.
|
||||
- Added 8/16-bit MOV memory-operand support (opcodes 0x88/0x8A, register-to-memory and
|
||||
memory-to-register) to the native ARM64 DBT.
|
||||
- Added GS/FS legacy segment prefix support to the native DBT and the bounded x86-64
|
||||
interpreter, including `CpuState.gs_base`/`CpuState.fs_base` offsets added to the effective
|
||||
address computation.
|
||||
- Added Win64 TEB allocation and `gs_base` initialization to synthetic guest startup.
|
||||
|
||||
### Changed
|
||||
|
||||
- Simplified the claim rules in `AGENTS.md`, `CONTRIBUTING.md` and the pull request template at the maintainer's request: claim an issue by replying on it in plain words, never claim over an existing claim, and treat a claim as stale only after about one week without a pull request. The task-queue lease (`lease_hours` in `.github/agent-queue.json`) is now 168 hours to match, and `docs/coordination/agent-tasks.md` marks the queue commands as optional.
|
||||
- The static PE probe now marks x86-64 SIB memory addressing as DBT-supported, matching the
|
||||
native DBT.
|
||||
|
||||
### Fixed
|
||||
- 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 `xenora_isa::meta::identify` reading six VOP3 interpolation forms (`v_interp_p1_f32_e64`, `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, `v_interp_p1ll_f16`, `v_interp_p1lv_f16`, `v_interp_p2_f16`) as 12 bytes when SRC0 is 255. In these forms SRC0 holds attribute bit-fields, not an operand selector (AMD RDNA 2 ISA guide section 10.4.2; XML operand type `OPR_ATTR`), so SRC0 = 255 no longer adds a literal word. The six corpus probes are now 8 bytes, as LLVM 23.1.6 also decodes them. The six pinned `mismatch` rows in the LLVM corpus check are gone: one now agrees fully, and five are `operand_flagged` (same instruction and length; LLVM flags an operand).
|
||||
- Updated `test_probe_static_analysis_does_not_execute_code`: the SIB store `mov [rsp + 0x20],
|
||||
rbx` at RVA 0x1004 is now genuinely supported by the native DBT (verified by the independent
|
||||
execution test above), so the probe reports no blocker for this program.
|
||||
- Added `test_probe_static_analysis_detects_genuinely_unsupported_instruction` with a new
|
||||
synthetic fixture containing an INT3 at RVA 0x1004, preserving blocker-detection coverage
|
||||
for genuinely unsupported DBT instructions.
|
||||
|
||||
## [X18] - Automated Import Compatibility Generation & Metadata Ingestion
|
||||
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added `xenora-import-gen` deterministic code generation crate and `xenora imports generate <--pe <exe> | --csv <file>> [--out <dir>]` CLI command. Automatically extracts imported symbols from PE executables or CSV manifests, classifies them against a built-in offline database of documented public Win32/CRT and ISO C specifications without consuming AI tokens or network resources, maps compatible CRT functions to native macOS libc ABI adapters with guest memory bounds checking, generates logged Win32 service stubs, generates deterministic conformance test suites, and produces coverage reports in both Markdown and CSV format.
|
||||
- Added automated metadata ingestion (`ingest_standard_system_headers`) and `xenora imports metadata sync` command capable of parsing real POSIX/C system headers into typed `MetadataCatalog` definitions (188 entries).
|
||||
- Added `xenora imports verify` automated behavioral verification runner checking CRT math, string, and memory bounds invariants across 12 independent behavioral test cases.
|
||||
- Added explicit failure semantics for unsupported stubs returning `ExitReason::IllegalInstruction(0xFE)` rather than fabricated success.
|
||||
- Added public registration helper `ImportRegistry::register_with_status` and runtime integration test verifying generated bindings and stub failure semantics.
|
||||
- Added 8-bit and 16-bit guest memory access helpers (`read_u8`, `write_u8`, `read_u16`, `write_u16`) to `xenora-loader::GuestMemory`.
|
||||
|
||||
- Added guest-facing D3D12-style graphics runtime interfaces (`GraphicsContext`, `GraphicsDevice`, `GraphicsCommandQueue`, `GraphicsCommandAllocator`, `GraphicsCommandList`, `GraphicsResource`) with explicit backend selection (`GraphicsBackendId::MetalNative` vs `GraphicsBackendId::SoftwareReference`). Original PE32+ integration tests verify device creation, generation-checked handle ownership, command recording, barriers, and presentation.
|
||||
- Connected guest execution via ARM64 DBT and IAT dispatch to native Apple Silicon Metal rendering (`test_guest_dbt_graphics_pipeline_metal_render_dual_inputs`), proving that different guest vertex positions and clear colors produce distinct, verified GPU-rendered framebuffers with active Metal validation on Apple M5.
|
||||
- Added explicit test graphics service exports (`xenora_fixture.dll!CreateGraphicsDevice`, `xenora_fixture.dll!SubmitGuestDraw`) cleanly separated from unsupported production Xbox ABI claims.
|
||||
- Added control-flow-aware x86-64 static PE probe using worklist CFG traversal, eliminating false-positive startup blocker reports on unreachable INT3 padding.
|
||||
- Added `xenora imports sync` command with `--check` verification mode for automated, idempotent import compatibility backlog generation.
|
||||
- Added current-process handle and ID queries and a readable priority boost policy for the synthetic guest process. Original PE fixtures verify Win64 arguments, state changes and errors through imported calls.
|
||||
- Static import reports identify canonical bindings, API-set aliases, implemented and partial handlers, existing stubs, and missing services.
|
||||
|
||||
- Added a single startup path for original PE32+ fixtures that maps and rebases the image, binds imports before running thread-local storage callbacks, then enters the guest.
|
||||
- The static PE probe compares ordinary imports with the standard synthetic registry and exports unresolved DLL, symbol or ordinal, and import slot addresses to `missing_imports.csv`.
|
||||
|
||||
- Added synthetic PE32+ runtime support for 64-bit base relocations, thread-local storage setup and callbacks, Windows x64 calling convention arguments, and import binding to a limited service registry. The Xbox-style allocation service maps guest memory. Its free entry point remains a stub.
|
||||
- Extended native ARM64 dynamic binary translation with selected memory addressing, immediate stores, register increments and decrements, and indirect control flow through guest import slots.
|
||||
- Added runtime fixtures for rebasing, ordered callbacks, deterministic timing, guest memory allocation, and mock import dispatch. The GPU gate checks every pixel from a native offscreen draw through a synthetic import.
|
||||
|
||||
- Added a static PE compatibility probe that exports section, relocation, thread-local storage, import and bounded x86-64 entry-point analysis. Synthetic tests cover inspection and report export.
|
||||
- Added native Apple Silicon ARM64 Dynamic Binary Translation (DBT) engine (`DbtEngine`) with basic block decoding, native ARM64 code lowering, and W^X-compliant JIT code cache (`JitMemory`) utilizing macOS `MAP_JIT` and `pthread_jit_write_protect_np`.
|
||||
- Added an ARM64 machine instruction assembler (`Arm64Assembler`) supporting register/immediate arithmetic, logical operations, memory loads/stores, branch/call/ret control flow, and calling convention preservation.
|
||||
- Added synthetic guest graphics service dispatch connecting guest x86-64 execution through native ARM64 translated blocks directly to Xenora's Metal graphics pipeline (`NativeCompute::render_rgba8`), producing and independently checking the first guest-rendered frame.
|
||||
@@ -55,6 +174,12 @@ remains unsupported.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Stop ignoring `fixtures/pe/trusted-runner.exe`. The runner embeds it with `include_bytes!`, so ignoring the file made a fresh checkout fail to compile.
|
||||
- Corrected the ARM64 STP pre-index encoder, which had a hardcoded -32-byte immediate and therefore adjusted the host stack by the wrong amount once the translator frame grew to 48 bytes. The wrong frame silently corrupted the caller's stack and caused SIGSEGV in every native translation test. Emitter encodings are now checked against LLVM's assembler, and a test asserts that each translated block opens and closes the same 48-byte frame.
|
||||
- Translated guest memory faults now stop the block before it commits further architectural effects. A faulting push, call or store leaves guest RSP and registers unchanged, the reported instruction count covers only completed work, and guest RIP identifies the faulting instruction. Previously the block continued after the helper recorded a fault, so later instructions and writes still took effect.
|
||||
- Compute the static PE probe SHA-256 from the full input, including trailing bytes.
|
||||
- Report TLS callbacks that halt or exhaust their execution budget as failures. Reject unsupported 32-bit increment and decrement forms in the native translator.
|
||||
|
||||
- Reject unknown guest experiment arguments with a nonzero exit status.
|
||||
|
||||
- Validate branch targets, buffer bindings, and program termination throughout a shader fixture, including instructions skipped by a resolved branch.
|
||||
|
||||
@@ -6,6 +6,7 @@ Xenora is an experimental Xbox Series X|S recompilation framework for Apple Sili
|
||||
|
||||
- Read `README.md` and, when present, `AGENTS.md`, `docs/interfaces.md`, `docs/status.toml` and the relevant architecture decisions.
|
||||
- Discuss substantial changes in an issue before implementing them; small fixes do not require prior approval.
|
||||
- Claim an issue before working on it by replying on it in plain words, after checking its comments for an existing claim. Never claim over someone else. A claim with no pull request after about one week may be taken over with a reply saying so. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
|
||||
- Use a native ARM64 macOS environment with Rust and the appropriate Xcode/Metal tools. LLVM AMDGPU tools are needed for ISA fixture generation; extra tooling depends on the subsystem.
|
||||
- Keep changes focused and preserve existing public interfaces unless a change is justified and documented.
|
||||
|
||||
@@ -43,6 +44,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.
|
||||
- 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
+94
@@ -8,6 +8,50 @@ version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dispatch2"
|
||||
version = "0.3.1"
|
||||
@@ -18,6 +62,16 @@ dependencies = [
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
@@ -72,10 +126,36 @@ dependencies = [
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "xenora"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
@@ -99,6 +179,19 @@ dependencies = [
|
||||
"xenora-ref",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-ffi"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-import-gen"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "xenora-isa"
|
||||
version = "0.1.0"
|
||||
@@ -108,6 +201,7 @@ name = "xenora-loader"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"sha2",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
@@ -2,13 +2,17 @@
|
||||
|
||||
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
|
||||
|
||||
Xenora is an open-source project written primarily in Rust, exploring native Xbox Series X|S compatibility on ARM64 macOS.
|
||||
|
||||
The project combines a bounded x86-64 guest execution environment, Portable Executable (PE32+) loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
|
||||
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.
|
||||
|
||||
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
|
||||
|
||||
Xenora is still experimental. It currently executes independently authored synthetic guest programs and shaders. **Commercial Xbox games, including Grand Theft Auto VI, do not boot.** Authentic Xbox executable loading and system-service compatibility remain unsupported.
|
||||
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).
|
||||
|
||||
### At a glance
|
||||
|
||||
- **Native graphics:** translated gfx1030 vertex and pixel stages and native passes (indexed draws, blend, depth) run on Apple Silicon GPUs — verified, see [Blend pass](#blend-pass) and [Verified Apple M5 results](#verified-apple-m5-results).
|
||||
- **Guest execution:** bounded x86-64 execution, original PE32+ loading, synthetic services and guest-driven GPU dispatch — verified milestones X1–X9.
|
||||
- **Not supported:** authentic Xbox executable loading and commercial game execution; see the [milestone table](#development-milestones).
|
||||
|
||||
[](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
|
||||
|
||||
@@ -18,7 +22,7 @@ Xenora is still experimental. It currently executes independently authored synth
|
||||
|
||||
Xenora has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
|
||||
|
||||
The latest verified milestone includes **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, with rendered pixels compared against independently calculated reference results.
|
||||
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.
|
||||
|
||||
### Development milestones
|
||||
|
||||
@@ -33,14 +37,14 @@ The latest verified milestone includes **translated gfx1030 vertex and pixel sha
|
||||
| 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 | Translate RDNA2 image instructions, implement samplers, mipmapping and guest-backed texture bindings | Planned |
|
||||
| X11 — Graphics pipeline | Multiple draw calls, vertex buffers, index buffers, depth/stencil testing, blending and render targets | Planned |
|
||||
| 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 | Introduce an ARM64 dynamic recompiler (JIT) for supported x86-64 instructions, with interpreter fallback | Planned |
|
||||
| X15 — Executable compatibility | PE relocations, TLS, DLL loading, exception handling, imports and executable initialization | Planned |
|
||||
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Planned |
|
||||
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | 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 |
|
||||
@@ -97,14 +101,35 @@ The current graphics subset supports:
|
||||
- Offscreen RGBA8 render targets.
|
||||
- Native GPU readback and pixel-by-pixel validation.
|
||||
- Explicit rejection of unsupported shader forms.
|
||||
- Flat-coloured triangle draws with colour write masks and blending (see [Blend pass](#blend-pass)).
|
||||
- Indexed triangle draws (see [Indexed draws](#indexed-draws)).
|
||||
- Depth testing with an optional `Depth32Float` attachment (see [Depth pass](#depth-pass)).
|
||||
|
||||
These are genuine translated shader stages, not merely demonstrations using handwritten Metal vertex and fragment programs.
|
||||
|
||||
The current rendering tests are deliberately narrow: original fixtures, a single triangle per draw, and controlled shader inputs and outputs.
|
||||
|
||||
### Blend pass
|
||||
|
||||
`NativeCompute::render_blend` draws up to 16 flat-coloured triangles in order into an offscreen RGBA8 target. Each draw has its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max). Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations.
|
||||
|
||||
GPU verification (Metal API and shader validation enabled): 39 Metal-validated passes over two original overlapping triangles — a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks; and a pass whose first draw is itself blended and masked. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly.
|
||||
|
||||
### Indexed draws
|
||||
|
||||
`NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an offscreen RGBA8 target. A draw can sample an original BC1 texture uploaded natively.
|
||||
|
||||
GPU verification (Metal API and shader validation enabled): 16 Metal-validated passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules.
|
||||
|
||||
### Depth pass
|
||||
|
||||
`NativeCompute::render_depth` draws up to 16 triangles in order into an offscreen RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. Colour and the stored depth are both read back.
|
||||
|
||||
GPU verification (Metal API and shader validation enabled): 30 Metal-validated passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled with an attachment and no attachment at all, and a BC1-textured draw.
|
||||
|
||||
### Verified Apple M5 results
|
||||
|
||||
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled.
|
||||
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled. The newer passes below are separate Metal-validated campaigns, also with Metal API and shader validation enabled.
|
||||
|
||||
Representative checks include:
|
||||
|
||||
@@ -115,6 +140,9 @@ Representative checks include:
|
||||
| Perspective interpolation | Exact checks of 16 pixels and another 16 after swapping vertex color channels |
|
||||
| BC1 texture handling | 33 texels across selected mip levels and array layers |
|
||||
| Guest rendering | PE32+ guest receives and checks the translated render output |
|
||||
| Blend pass | 39 Metal-validated passes over two overlapping triangles |
|
||||
| Indexed draws | 16 Metal-validated passes (both index sizes, signed base vertices, draw order) |
|
||||
| Depth pass | 30 Metal-validated passes (all eight compare functions, no-attachment case) |
|
||||
|
||||
The expected results were calculated independently of the production shader translation path.
|
||||
|
||||
@@ -141,20 +169,20 @@ The resource system remains experimental. Native GPU work already in flight duri
|
||||
|
||||
## Texture support
|
||||
|
||||
Xenora includes an original BC1 texture-processing path.
|
||||
Xenora includes original texture upload, readback and block-compression paths.
|
||||
|
||||
Implemented and tested functionality includes:
|
||||
|
||||
- Validated mip levels and array layers.
|
||||
- Pitched texture uploads.
|
||||
- Block-compressed texture handling.
|
||||
- Block-compressed texture handling, including BC4/BC5 upload and readback and a CPU BC7 decoder for the eight modes.
|
||||
- Native Metal texture readback.
|
||||
- Edge-block and transparency tests.
|
||||
- Invalid descriptor and bounds rejection.
|
||||
|
||||
**Translated texture-sampling instructions are not yet implemented.**
|
||||
|
||||
The existing texture readback path uses an authored Metal kernel. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
|
||||
The existing texture readback path uses authored Metal kernels. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
|
||||
|
||||
Xbox-specific texture layouts and additional compression formats require further research and validation.
|
||||
|
||||
@@ -209,6 +237,8 @@ flowchart TD
|
||||
|
||||
Xenora'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.
|
||||
|
||||
See [Interface Contracts](docs/interfaces.md) for the documented execution and resource boundaries.
|
||||
@@ -227,8 +257,8 @@ 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, broader resource binding, synchronization and general draw workloads |
|
||||
| Textures | Authentic Xbox memory layouts and broader compressed-format support |
|
||||
| Graphics | Translated texture sampling and broader resource binding |
|
||||
| Textures | Authentic Xbox memory layouts and translated sampling |
|
||||
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
|
||||
| Game compatibility | No demonstrated execution of commercial Xbox titles |
|
||||
|
||||
@@ -272,6 +302,10 @@ cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
```
|
||||
|
||||
The format, lint and test trio is the standard check set. The native Metal
|
||||
passes use Metal API and shader validation; `scripts/audit/status.py --check`
|
||||
verifies the generated status tables.
|
||||
|
||||
### Run native Metal tests
|
||||
|
||||
These require a Metal-capable Apple Silicon Mac.
|
||||
@@ -297,8 +331,6 @@ Run the original guest resource integration tests:
|
||||
tests/compat_fixtures/verify-resources.sh
|
||||
```
|
||||
|
||||
The X9 verification script builds synthetic PE fixtures, executes guest resource and rendering workloads, compares reported output and exercises negative cases.
|
||||
|
||||
Additional checks:
|
||||
|
||||
```sh
|
||||
@@ -322,65 +354,20 @@ Testing distinguishes between:
|
||||
|
||||
Compiling a shader is not equivalent to proving its GPU output is correct.
|
||||
|
||||
The [X9 acceptance report](docs/testing/x9-acceptance.md) documents verified outcomes and unresolved work.
|
||||
### 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).
|
||||
|
||||
---
|
||||
|
||||
## Roadmap
|
||||
|
||||
Future development will focus on expanding the complete execution path instead of treating synthetic demonstration milestones as evidence of commercial-game compatibility.
|
||||
|
||||
### Near-term priorities
|
||||
|
||||
1. **Graphics compatibility:** Extend shader translation, texture sampling, resource bindings, multi-draw rendering and synchronization.
|
||||
2. **Guest execution:** Improve the PE loader, CPU instruction coverage, runtime services and execution correctness.
|
||||
3. **Performance:** Investigate efficient ARM64 guest execution, graphics pipeline caching, profiling and GPU resource lifetime management.
|
||||
|
||||
Longer-term research includes authentic Xbox application interfaces and significantly broader GPU behavior.
|
||||
|
||||
MetalFX upscaling and other presentation optimizations may become useful once substantial workloads render correctly. They are not substitutes for correct guest execution or shader translation.
|
||||
|
||||
There is no announced commercial-game support date.
|
||||
|
||||
---
|
||||
|
||||
## Contributors wanted
|
||||
|
||||
**Xenora is looking for developers interested in native Apple Silicon systems programming, graphics translation and emulation research.**
|
||||
|
||||
This is an ambitious project, and there's a great deal of work that would benefit from experienced contributors and independent reviewers.
|
||||
|
||||
Particularly useful areas include:
|
||||
|
||||
| Area | Potential contributions |
|
||||
| --- | --- |
|
||||
| Apple Metal | Rendering, resource management, synchronization, GPU debugging and profiling |
|
||||
| AMD RDNA2 | ISA decoding, wave semantics, shader execution and correctness tests |
|
||||
| Compiler engineering | Shader intermediate representations, lowering, optimization and code generation |
|
||||
| ARM64 / x86-64 | Guest CPU execution, instruction semantics, memory models and future JIT research |
|
||||
| Rust | Runtime architecture, concurrency, safety, tests and tooling |
|
||||
| macOS | Apple Silicon compatibility, native debugging and hardware validation |
|
||||
| Testing | Independent reference implementations, fuzzing, regression tests and reproducible GPU fixtures |
|
||||
|
||||
You don't need to be an expert in every subsystem.
|
||||
|
||||
Code review, small targeted fixes, independent test cases and technical criticism are all valuable contributions.
|
||||
|
||||
### Getting involved
|
||||
|
||||
1. Read [CONTRIBUTING.md](CONTRIBUTING.md) and the relevant architecture documentation.
|
||||
2. Review the [current acceptance results](docs/testing/x9-acceptance.md).
|
||||
3. Open a [GitHub issue](https://github.com/ranveersoni98/Xenora/issues) to discuss a feature, bug, or research question.
|
||||
4. Submit focused pull requests with reproducible tests and documented limitations.
|
||||
|
||||
Contributions must follow the project's original-implementation and clean-room research policies. Do not submit proprietary game files, leaked SDK materials, console keys or unauthorized shader dumps.
|
||||
|
||||
AI-assisted development has been used in Xenora. All contributions, including AI-assisted code, are expected to undergo human review and independent verification.
|
||||
|
||||
**The goal is to build a trustworthy native Apple Silicon compatibility framework, one verifiable subsystem at a time.**
|
||||
|
||||
---
|
||||
|
||||
### Contributors
|
||||
|
||||
[](https://github.com/ranveersoni98/Xenora/graphs/contributors)
|
||||
|
||||
## License
|
||||
|
||||
Xenora is licensed under the [GNU General Public License v3 or later](LICENSE).
|
||||
@@ -389,6 +376,4 @@ See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution
|
||||
|
||||
Xenora is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple.
|
||||
|
||||
---
|
||||
|
||||
**Built for Apple Silicon. Powered by Rust and Metal. Open to contributors.**
|
||||
---
|
||||
@@ -0,0 +1,13 @@
|
||||
// swift-tools-version: 6.0
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Build with scripts/build-app.sh, which builds the Rust static library first.
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "Xenora",
|
||||
platforms: [.macOS(.v14)],
|
||||
targets: [
|
||||
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
|
||||
.executableTarget(name: "Xenora", dependencies: ["CXenora"]),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,5 @@
|
||||
module CXenora [system] {
|
||||
header "../../../crates/ffi/include/xenora.h"
|
||||
link "xenora_ffi"
|
||||
export *
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
// Native shell over the versioned C interface. "Run trusted fixture" executes the
|
||||
// bundled trusted PE fixture (x86-64 translated to ARM64; its draw request is rendered
|
||||
// by native Metal) and shows the verified read-back frame. No other executable can run.
|
||||
|
||||
import AppKit
|
||||
import CXenora
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct RuntimeProbe {
|
||||
var abiVersion: UInt32 = 0
|
||||
var status: Int32 = -1
|
||||
var sections: UInt32 = 0
|
||||
var entryRVA: UInt32 = 0
|
||||
|
||||
var connected: Bool { abiVersion == XENORA_ABI_VERSION && status == XENORA_OK }
|
||||
|
||||
static func run() -> RuntimeProbe {
|
||||
var probe = RuntimeProbe(abiVersion: xenora_abi_version())
|
||||
var session: xenora_session = 0
|
||||
probe.status = xenora_session_create(XENORA_ABI_VERSION, &session)
|
||||
guard probe.status == XENORA_OK else { return probe }
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
probe.status = xenora_session_inspect_trusted_fixture(session, &probe.sections, &probe.entryRVA)
|
||||
return probe
|
||||
}
|
||||
|
||||
var summary: String {
|
||||
String(format: "abi=%u status=%d sections=%u entry_rva=0x%x", abiVersion, status, sections, entryRVA)
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame produced by one run of the trusted fixture.
|
||||
struct GuestFrame {
|
||||
let status: Int32
|
||||
let width: Int
|
||||
let height: Int
|
||||
let rgba: [UInt8]
|
||||
|
||||
static func run() -> GuestFrame {
|
||||
var session: xenora_session = 0
|
||||
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
|
||||
guard status == XENORA_OK else { return GuestFrame(status: status, width: 0, height: 0, rgba: []) }
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
var width: UInt32 = 0
|
||||
var height: UInt32 = 0
|
||||
status = rgba.withUnsafeMutableBufferPointer { buffer in
|
||||
xenora_session_run_trusted_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
|
||||
}
|
||||
return GuestFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
|
||||
}
|
||||
|
||||
var image: CGImage? {
|
||||
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
|
||||
return CGImage(
|
||||
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
|
||||
space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
|
||||
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
|
||||
}
|
||||
|
||||
var summary: String {
|
||||
let first = rgba.prefix(4).map(String.init).joined(separator: ",")
|
||||
return "status=\(status) frame=\(width)x\(height) first_pixel=\(first)"
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns the latest fixture run. A class with @Published avoids SwiftUI macros,
|
||||
/// which the command-line toolchain does not ship.
|
||||
@MainActor
|
||||
final class FrameModel: ObservableObject {
|
||||
@Published var frame: GuestFrame?
|
||||
@Published var running = false
|
||||
|
||||
func run() {
|
||||
running = true
|
||||
Task {
|
||||
// The fixture blocks while it executes and renders, so keep it off the main thread.
|
||||
frame = await Task.detached { GuestFrame.run() }.value
|
||||
running = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Persistent guest rendering model (Gate 3, #266; Gate 4, #276).
|
||||
@MainActor
|
||||
final class FrameLoopModel: ObservableObject {
|
||||
@Published var state: UInt32 = UInt32(XENORA_LOOP_NONE)
|
||||
@Published var completed: UInt32 = 0
|
||||
@Published var frameId: UInt32 = XENORA_NO_FRAME
|
||||
@Published var image: CGImage?
|
||||
@Published var errorMessage: String?
|
||||
@Published var isInteractive: Bool = false
|
||||
|
||||
private var session: xenora_session = 0
|
||||
private var pollTask: Task<Void, Never>?
|
||||
|
||||
deinit {
|
||||
pollTask?.cancel()
|
||||
if session != 0 {
|
||||
_ = xenora_session_destroy(session)
|
||||
}
|
||||
}
|
||||
|
||||
var isRunning: Bool { state == UInt32(XENORA_LOOP_RUNNING) }
|
||||
var isPaused: Bool { state == UInt32(XENORA_LOOP_PAUSED) }
|
||||
var canStart: Bool {
|
||||
session == 0 || state == UInt32(XENORA_LOOP_NONE) || state == UInt32(XENORA_LOOP_FINISHED)
|
||||
|| state == UInt32(XENORA_LOOP_STOPPED) || state == UInt32(XENORA_LOOP_FAILED)
|
||||
}
|
||||
|
||||
var stateDescription: String {
|
||||
switch state {
|
||||
case UInt32(XENORA_LOOP_NONE): return "Idle"
|
||||
case UInt32(XENORA_LOOP_RUNNING): return "Running"
|
||||
case UInt32(XENORA_LOOP_PAUSED): return "Paused"
|
||||
case UInt32(XENORA_LOOP_FINISHED): return "Finished"
|
||||
case UInt32(XENORA_LOOP_STOPPED): return "Stopped"
|
||||
case UInt32(XENORA_LOOP_FAILED): return "Failed"
|
||||
default: return "Unknown (\(state))"
|
||||
}
|
||||
}
|
||||
|
||||
func start(frameCount: UInt32 = 300) {
|
||||
errorMessage = nil
|
||||
if session != 0 {
|
||||
_ = xenora_session_destroy(session)
|
||||
session = 0
|
||||
}
|
||||
var newSession: xenora_session = 0
|
||||
let createStatus = xenora_session_create(XENORA_ABI_VERSION, &newSession)
|
||||
guard createStatus == XENORA_OK else {
|
||||
errorMessage = "Failed to create session (status \(createStatus))"
|
||||
return
|
||||
}
|
||||
session = newSession
|
||||
let startStatus = xenora_session_start_frame_loop(session, frameCount)
|
||||
guard startStatus == XENORA_OK else {
|
||||
errorMessage = "Failed to start frame loop (status \(startStatus))"
|
||||
_ = xenora_session_destroy(session)
|
||||
session = 0
|
||||
return
|
||||
}
|
||||
isInteractive = false
|
||||
state = UInt32(XENORA_LOOP_RUNNING)
|
||||
completed = 0
|
||||
frameId = XENORA_NO_FRAME
|
||||
image = nil
|
||||
startPolling()
|
||||
}
|
||||
|
||||
func startInteractive(frameCount: UInt32 = 300) {
|
||||
errorMessage = nil
|
||||
if session != 0 {
|
||||
_ = xenora_session_destroy(session)
|
||||
session = 0
|
||||
}
|
||||
var newSession: xenora_session = 0
|
||||
let createStatus = xenora_session_create(XENORA_ABI_VERSION, &newSession)
|
||||
guard createStatus == XENORA_OK else {
|
||||
errorMessage = "Failed to create session (status \(createStatus))"
|
||||
return
|
||||
}
|
||||
session = newSession
|
||||
let startStatus = xenora_session_start_interactive_loop(session, frameCount)
|
||||
guard startStatus == XENORA_OK else {
|
||||
errorMessage = "Failed to start interactive loop (status \(startStatus))"
|
||||
_ = xenora_session_destroy(session)
|
||||
session = 0
|
||||
return
|
||||
}
|
||||
isInteractive = true
|
||||
state = UInt32(XENORA_LOOP_RUNNING)
|
||||
completed = 0
|
||||
frameId = XENORA_NO_FRAME
|
||||
image = nil
|
||||
startPolling()
|
||||
}
|
||||
|
||||
func sendInput(buttons: UInt32) {
|
||||
guard session != 0 else { return }
|
||||
var input = xenora_input_state(
|
||||
buttons: buttons,
|
||||
stick_x: 0,
|
||||
stick_y: 0,
|
||||
mouse_dx: 0,
|
||||
mouse_dy: 0,
|
||||
mouse_buttons: 0,
|
||||
connected: 1,
|
||||
reserved: 0
|
||||
)
|
||||
_ = xenora_session_send_input(session, &input)
|
||||
}
|
||||
|
||||
func pause() {
|
||||
guard session != 0 else { return }
|
||||
_ = xenora_session_pause_frame_loop(session)
|
||||
}
|
||||
|
||||
func resume() {
|
||||
guard session != 0 else { return }
|
||||
_ = xenora_session_resume_frame_loop(session)
|
||||
}
|
||||
|
||||
func stop() {
|
||||
guard session != 0 else { return }
|
||||
_ = xenora_session_stop_frame_loop(session)
|
||||
}
|
||||
|
||||
private func startPolling() {
|
||||
pollTask?.cancel()
|
||||
pollTask = Task { [weak self] in
|
||||
while !Task.isCancelled {
|
||||
try? await Task.sleep(nanoseconds: 16_000_000)
|
||||
guard let self = self, self.session != 0 else { break }
|
||||
var st: UInt32 = 0
|
||||
var comp: UInt32 = 0
|
||||
var fId: UInt32 = 0
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
let code = rgba.withUnsafeMutableBufferPointer { buffer in
|
||||
xenora_session_frame_loop_status(
|
||||
self.session, &st, &comp, &fId, buffer.baseAddress, UInt64(buffer.count))
|
||||
}
|
||||
guard code == XENORA_OK else { break }
|
||||
self.state = st
|
||||
self.completed = comp
|
||||
self.frameId = fId
|
||||
if fId != XENORA_NO_FRAME, let provider = CGDataProvider(data: Data(rgba) as CFData) {
|
||||
self.image = CGImage(
|
||||
width: Int(XENORA_FIXTURE_FRAME_WIDTH),
|
||||
height: Int(XENORA_FIXTURE_FRAME_HEIGHT),
|
||||
bitsPerComponent: 8,
|
||||
bitsPerPixel: 32,
|
||||
bytesPerRow: Int(XENORA_FIXTURE_FRAME_WIDTH) * 4,
|
||||
space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
|
||||
provider: provider,
|
||||
decode: nil,
|
||||
shouldInterpolate: false,
|
||||
intent: .defaultIntent
|
||||
)
|
||||
}
|
||||
if st != UInt32(XENORA_LOOP_RUNNING) && st != UInt32(XENORA_LOOP_PAUSED) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read-only compatibility inspection of a user-chosen file. Nothing in it is executed.
|
||||
@MainActor
|
||||
final class InspectionModel: ObservableObject {
|
||||
static let shared = InspectionModel()
|
||||
@Published var fileName: String?
|
||||
@Published var report = ""
|
||||
@Published var status: Int32 = Int32(XENORA_OK)
|
||||
@Published var busy = false
|
||||
@Published var importing = false
|
||||
|
||||
func inspect(_ url: URL) {
|
||||
fileName = url.lastPathComponent
|
||||
busy = true
|
||||
Task {
|
||||
let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value
|
||||
status = newStatus
|
||||
report = newReport
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated static func run(_ url: URL) -> (Int32, String) {
|
||||
let scoped = url.startAccessingSecurityScopedResource()
|
||||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||||
// Check the size before reading so an oversized file is never loaded into memory.
|
||||
guard let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize else {
|
||||
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file's size.")
|
||||
}
|
||||
guard UInt64(size) <= UInt64(XENORA_MAX_INSPECT_BYTES) else {
|
||||
return (Int32(XENORA_LIMIT_EXCEEDED), "The file is \(size) bytes; inspection accepts at most \(XENORA_MAX_INSPECT_BYTES).")
|
||||
}
|
||||
guard let data = try? Data(contentsOf: url) else {
|
||||
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file.")
|
||||
}
|
||||
return data.withUnsafeBytes { raw in
|
||||
let bytes = raw.bindMemory(to: UInt8.self).baseAddress
|
||||
var required: UInt64 = 0
|
||||
var probe: CChar = 0
|
||||
var status = xenora_inspect_executable(bytes, UInt64(data.count), &probe, 1, &required)
|
||||
guard status == Int32(XENORA_BUFFER_TOO_SMALL) else { return (status, "Inspection failed (status \(status)).") }
|
||||
var text = [CChar](repeating: 0, count: Int(required))
|
||||
status = xenora_inspect_executable(bytes, UInt64(data.count), &text, required, &required)
|
||||
return (status, String(cString: text))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives files opened from Finder (double-click or Open With).
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
func application(_ application: NSApplication, open urls: [URL]) {
|
||||
guard let url = urls.first else { return }
|
||||
MainActor.assumeIsolated { InspectionModel.shared.inspect(url) }
|
||||
}
|
||||
}
|
||||
|
||||
struct InspectorView: View {
|
||||
@ObservedObject var model: InspectionModel
|
||||
|
||||
var body: some View {
|
||||
Section("Executable inspection (read-only)") {
|
||||
HStack {
|
||||
Button("Open Executable…") { model.importing = true }
|
||||
Text("or drop a file on this window").foregroundStyle(.secondary)
|
||||
}
|
||||
if let name = model.fileName {
|
||||
LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name)
|
||||
ScrollView {
|
||||
Text(model.report)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.frame(minHeight: 160, maxHeight: 320)
|
||||
}
|
||||
Text("Opened files are inspected only. Running them is not available.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentView: View {
|
||||
let probe = RuntimeProbe.run()
|
||||
@ObservedObject var model: FrameModel
|
||||
@ObservedObject var loop: FrameLoopModel
|
||||
@ObservedObject var inspection = InspectionModel.shared
|
||||
private var frame: GuestFrame? { model.frame }
|
||||
private var running: Bool { model.running }
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
InspectorView(model: inspection)
|
||||
Section("Guest display") {
|
||||
if let image = frame?.image {
|
||||
Image(decorative: image, scale: 1)
|
||||
.resizable()
|
||||
.interpolation(.none)
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
|
||||
.accessibilityLabel("Guest frame, \(frame!.width) by \(frame!.height) pixels")
|
||||
Text("Guest code ran, its draw was rendered by native Metal, and all \(frame!.width * frame!.height) pixels matched the fixture shader's output.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
} else if let frame {
|
||||
Text("Run failed (status \(frame.status)). No frame is shown.")
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
Button(running ? "Running…" : "Run trusted fixture") { model.run() }
|
||||
.disabled(running || !probe.connected)
|
||||
}
|
||||
Section("Persistent frame loop") {
|
||||
if let image = loop.image {
|
||||
Image(decorative: image, scale: 1)
|
||||
.resizable()
|
||||
.interpolation(.none)
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
|
||||
.accessibilityLabel("Guest frame #\(loop.frameId)")
|
||||
Text("Frame #\(loop.frameId) (\(loop.completed) completed) • \(loop.stateDescription)")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
} else if let error = loop.errorMessage {
|
||||
Text(error).foregroundStyle(.red)
|
||||
} else if loop.state != UInt32(XENORA_LOOP_NONE) {
|
||||
Text("State: \(loop.stateDescription) • \(loop.completed) completed")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
HStack {
|
||||
Button("Start 300 frames") { loop.start(frameCount: 300) }
|
||||
.disabled(!loop.canStart || !probe.connected)
|
||||
Button("Interactive (300 frames)") { loop.startInteractive(frameCount: 300) }
|
||||
.disabled(!loop.canStart || !probe.connected)
|
||||
Button("Pause") { loop.pause() }
|
||||
.disabled(!loop.isRunning)
|
||||
Button("Resume") { loop.resume() }
|
||||
.disabled(!loop.isPaused)
|
||||
Button("Stop") { loop.stop() }
|
||||
.disabled(!loop.isRunning && !loop.isPaused)
|
||||
}
|
||||
if loop.isInteractive && (loop.isRunning || loop.isPaused) {
|
||||
HStack {
|
||||
Button("◀ Left") { loop.sendInput(buttons: UInt32(XENORA_INPUT_LEFT)) }
|
||||
Button("▶ Right") { loop.sendInput(buttons: UInt32(XENORA_INPUT_RIGHT)) }
|
||||
Button("Release") { loop.sendInput(buttons: UInt32(XENORA_INPUT_NONE)) }
|
||||
}
|
||||
Text("Interactive guest: steer the rendered strip across columns 0..3 with Left/Right.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
LabeledContent("Runtime", value: probe.connected ? "Connected" : "Unavailable (status \(probe.status))")
|
||||
LabeledContent("Interface version", value: "\(probe.abiVersion)")
|
||||
LabeledContent("Trusted fixture sections", value: "\(probe.sections)")
|
||||
LabeledContent("Trusted fixture entry RVA", value: String(format: "0x%X", probe.entryRVA))
|
||||
Text("Only the bundled trusted fixtures (single-frame, frame-loop, and interactive guest) can run. Presentation uses read-back Metal frames. Arbitrary executables are not available yet.")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in
|
||||
if case .success(let url) = result { inspection.inspect(url) }
|
||||
}
|
||||
.dropDestination(for: URL.self) { urls, _ in
|
||||
guard let url = urls.first, url.isFileURL else { return false }
|
||||
inspection.inspect(url)
|
||||
return true
|
||||
}
|
||||
.frame(minWidth: 520, minHeight: 680)
|
||||
}
|
||||
}
|
||||
|
||||
struct XenoraApp: App {
|
||||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||||
let model = FrameModel()
|
||||
let loop = FrameLoopModel()
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup("Xenora") { ContentView(model: model, loop: loop) }
|
||||
}
|
||||
}
|
||||
|
||||
// `--inspect <path>` prints the read-only report for a file and exits with its status.
|
||||
if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < CommandLine.arguments.count {
|
||||
let (status, report) = InspectionModel.run(URL(fileURLWithPath: CommandLine.arguments[flag + 1]))
|
||||
print(report.hasSuffix("\n") ? report : report + "\n", terminator: "")
|
||||
print("status=\(status)")
|
||||
exit(status == Int32(XENORA_OK) ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-interactive` runs 60 frames with queued inputs on the Metal device and exits.
|
||||
if CommandLine.arguments.contains("--smoke-interactive") {
|
||||
var session: xenora_session = 0
|
||||
guard xenora_session_create(XENORA_ABI_VERSION, &session) == XENORA_OK else {
|
||||
print("failed to create session")
|
||||
exit(1)
|
||||
}
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
guard xenora_session_start_interactive_loop(session, 60) == XENORA_OK else {
|
||||
print("failed to start interactive loop")
|
||||
exit(1)
|
||||
}
|
||||
for f in 0..<60 {
|
||||
let btn: UInt32 = (f < 15) ? UInt32(XENORA_INPUT_RIGHT) :
|
||||
(f < 30) ? UInt32(XENORA_INPUT_NONE) :
|
||||
(f < 45) ? UInt32(XENORA_INPUT_LEFT) : UInt32(XENORA_INPUT_RIGHT)
|
||||
var input = xenora_input_state(buttons: btn, stick_x: 0, stick_y: 0, mouse_dx: 0, mouse_dy: 0, mouse_buttons: 0, connected: 1, reserved: 0)
|
||||
_ = xenora_session_queue_input(session, &input)
|
||||
}
|
||||
var state: UInt32 = 0
|
||||
var completed: UInt32 = 0
|
||||
var frameId: UInt32 = 0
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
while true {
|
||||
let code = rgba.withUnsafeMutableBufferPointer { buf in
|
||||
xenora_session_frame_loop_status(session, &state, &completed, &frameId, buf.baseAddress, UInt64(buf.count))
|
||||
}
|
||||
if code != XENORA_OK {
|
||||
print("frame_loop_status failed: \(code)")
|
||||
exit(1)
|
||||
}
|
||||
if state != UInt32(XENORA_LOOP_RUNNING) { break }
|
||||
Thread.sleep(forTimeInterval: 0.005)
|
||||
}
|
||||
print("interactive: state=\(state) completed=\(completed) frame_id=\(frameId)")
|
||||
exit(state == UInt32(XENORA_LOOP_FINISHED) && completed == 60 ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-loop` runs 300 frames on the Metal device and exits; it needs a GPU.
|
||||
if CommandLine.arguments.contains("--smoke-loop") {
|
||||
var session: xenora_session = 0
|
||||
guard xenora_session_create(XENORA_ABI_VERSION, &session) == XENORA_OK else {
|
||||
print("failed to create session")
|
||||
exit(1)
|
||||
}
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
guard xenora_session_start_frame_loop(session, 300) == XENORA_OK else {
|
||||
print("failed to start frame loop")
|
||||
exit(1)
|
||||
}
|
||||
var state: UInt32 = 0
|
||||
var completed: UInt32 = 0
|
||||
var frameId: UInt32 = 0
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
while true {
|
||||
let code = rgba.withUnsafeMutableBufferPointer { buf in
|
||||
xenora_session_frame_loop_status(session, &state, &completed, &frameId, buf.baseAddress, UInt64(buf.count))
|
||||
}
|
||||
if code != XENORA_OK {
|
||||
print("frame_loop_status failed: \(code)")
|
||||
exit(1)
|
||||
}
|
||||
if state != UInt32(XENORA_LOOP_RUNNING) { break }
|
||||
Thread.sleep(forTimeInterval: 0.005)
|
||||
}
|
||||
print("state=\(state) completed=\(completed) frame_id=\(frameId)")
|
||||
exit(state == UInt32(XENORA_LOOP_FINISHED) && completed == 300 ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-frame` runs the trusted fixture on the Metal device and exits; it needs a GPU.
|
||||
if CommandLine.arguments.contains("--smoke-frame") {
|
||||
let frame = GuestFrame.run()
|
||||
print(frame.summary)
|
||||
exit(frame.status == XENORA_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()
|
||||
@@ -9,7 +9,10 @@ rust-version.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
xenora-decoder = { path = "../decoder" }
|
||||
xenora-isa = { path = "../isa" }
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-ref = { path = "../ref" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
xenora-loader = { path = "../loader" }
|
||||
xenora-import-gen = { path = "../import-gen" }
|
||||
+561
-1
@@ -1,6 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
mod demo;
|
||||
mod runner;
|
||||
mod shaders;
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
@@ -37,9 +39,567 @@ fn main() -> ExitCode {
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Some("run") => runner::command(std::env::args_os().skip(2)),
|
||||
Some("imports") => imports_command(std::env::args().skip(2).collect()),
|
||||
Some("shaders") => shaders::command(&std::env::args().skip(2).collect::<Vec<_>>()),
|
||||
Some("probe") => {
|
||||
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 i = 2;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--pe" => {
|
||||
if i + 1 < args.len() {
|
||||
pe_path = Some(args[i + 1].clone());
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --pe");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--mode" => {
|
||||
if i + 1 < args.len() {
|
||||
mode = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --mode");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--report" => {
|
||||
if i + 1 < args.len() {
|
||||
report_dir = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --report");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
eprintln!("unknown probe argument: {other}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(pe) = pe_path else {
|
||||
eprintln!(
|
||||
"usage: xenora probe --pe <path> [--mode <static>] [--report <output-dir>]"
|
||||
);
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
|
||||
if mode != "static" {
|
||||
eprintln!("error: currently only --mode static is supported");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
|
||||
let bytes = match std::fs::read(&pe) {
|
||||
Ok(b) => b,
|
||||
Err(err) => {
|
||||
eprintln!("error reading PE binary '{pe}': {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
|
||||
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!("Artifacts exported to: {report_dir}");
|
||||
println!("Sections: {}", report.parsed.sections.len());
|
||||
println!("Relocations: {}", report.relocations.total_entries);
|
||||
println!("TLS Callbacks: {}", report.tls.callback_targets.len());
|
||||
println!("Imported Thunks: {}", report.imports.len());
|
||||
println!(
|
||||
"Unresolved Standard Import Thunks: {}",
|
||||
report
|
||||
.imports
|
||||
.iter()
|
||||
.filter(|import| !import.is_supported)
|
||||
.count()
|
||||
);
|
||||
if let Some(insn) = report.first_unsupported_dbt_insn {
|
||||
println!("First DBT Blocker: RVA 0x{:08x} ({})", insn.rva, insn.notes);
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("probe failed: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
eprintln!("usage: xenora <info|demo|inspect>");
|
||||
eprintln!("usage: xenora <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`
|
||||
fn imports_command(args: Vec<String>) -> ExitCode {
|
||||
if args.is_empty() {
|
||||
eprintln!("usage: xenora imports <sync|generate|metadata|verify> [options]");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
|
||||
match args[0].as_str() {
|
||||
"generate" => run_imports_generate_cli(&args[1..]),
|
||||
"sync" => run_imports_sync_cli(&args[1..]),
|
||||
"metadata" => run_imports_metadata_cli(&args[1..]),
|
||||
"verify" => run_imports_verify_cli(&args[1..]),
|
||||
other => {
|
||||
eprintln!("unknown imports subcommand: {other}");
|
||||
eprintln!("usage: xenora imports <sync|generate|metadata|verify> [options]");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_imports_metadata_cli(args: &[String]) -> ExitCode {
|
||||
let mut out_dir = "artifacts/metadata".to_string();
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"sync" => {
|
||||
i += 1;
|
||||
}
|
||||
"--out" => {
|
||||
if i + 1 < args.len() {
|
||||
out_dir = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --out");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
eprintln!("unknown metadata argument: {other}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("Synchronizing offline API metadata catalog from public specifications...");
|
||||
let catalog = xenora_import_gen::MetadataCatalog::builtin();
|
||||
println!(
|
||||
"Loaded version {} with {} entries.",
|
||||
catalog.version,
|
||||
catalog.entries.len()
|
||||
);
|
||||
|
||||
let _ = std::fs::create_dir_all(&out_dir);
|
||||
let out_file = format!("{out_dir}/api_catalog.json");
|
||||
let mut json = String::from("{\n \"version\": 1,\n \"entries\": [\n");
|
||||
let mut first = true;
|
||||
for ((module, sym), sig) in &catalog.entries {
|
||||
if !first {
|
||||
json.push_str(",\n");
|
||||
}
|
||||
first = false;
|
||||
json.push_str(&format!(
|
||||
" {{\"module\": \"{}\", \"symbol\": \"{}\", \"header\": \"{}\", \"doc\": \"{}\"}}",
|
||||
module, sym, sig.header_source, sig.doc
|
||||
));
|
||||
}
|
||||
json.push_str("\n ]\n}\n");
|
||||
|
||||
if let Err(e) = std::fs::write(&out_file, json) {
|
||||
eprintln!("failed to write metadata catalog: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
println!("API metadata catalog synchronized to: {out_file}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn run_imports_verify_cli(args: &[String]) -> ExitCode {
|
||||
if !args.is_empty() {
|
||||
eprintln!("warning: verify takes no additional arguments");
|
||||
}
|
||||
println!("Running automated behavioral verification for generated import bindings...");
|
||||
match xenora_import_gen::run_verification() {
|
||||
Ok(res) => {
|
||||
for detail in &res.details {
|
||||
println!(" {detail}");
|
||||
}
|
||||
println!(
|
||||
"Verification summary: {}/{} tests passed.",
|
||||
res.passed, res.total
|
||||
);
|
||||
if res.failed > 0 {
|
||||
ExitCode::FAILURE
|
||||
} else {
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("verification failed: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_imports_generate_cli(args: &[String]) -> ExitCode {
|
||||
let mut pe_path: Option<String> = None;
|
||||
let mut csv_path: Option<String> = None;
|
||||
let mut out_dir = "crates/loader/src/generated".to_string();
|
||||
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--pe" => {
|
||||
if i + 1 < args.len() {
|
||||
pe_path = Some(args[i + 1].clone());
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --pe");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--csv" => {
|
||||
if i + 1 < args.len() {
|
||||
csv_path = Some(args[i + 1].clone());
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --csv");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--out" => {
|
||||
if i + 1 < args.len() {
|
||||
out_dir = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --out");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
eprintln!("unknown generate argument: {other}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let records = if let Some(ref pe) = pe_path {
|
||||
println!("Extracting imports from PE executable: {pe}");
|
||||
let bytes = match std::fs::read(pe) {
|
||||
Ok(b) => b,
|
||||
Err(err) => {
|
||||
eprintln!("error reading PE binary '{pe}': {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let probe_cfg = xenora_loader::ProbeConfig::default();
|
||||
let report = match xenora_loader::probe::probe_pe_bytes(&bytes, &probe_cfg) {
|
||||
Ok(rep) => rep,
|
||||
Err(err) => {
|
||||
eprintln!("error probing PE binary: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
report
|
||||
.imports
|
||||
.into_iter()
|
||||
.map(|imp| xenora_import_gen::ImportRecord {
|
||||
module: imp.dll,
|
||||
symbol: imp.symbol,
|
||||
iat_rva: imp.iat_rva as u64,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
} else if let Some(ref csv) = csv_path {
|
||||
match xenora_import_gen::parse_csv(csv) {
|
||||
Ok(recs) => recs,
|
||||
Err(err) => {
|
||||
eprintln!("error reading CSV '{csv}': {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
eprintln!(
|
||||
"usage: xenora imports generate <--pe <executable> | --csv <missing_imports.csv>> [--out <dir>]"
|
||||
);
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
|
||||
println!("Total imports extracted: {}", records.len());
|
||||
let db = xenora_import_gen::SymbolDb::builtin();
|
||||
let manifest = xenora_import_gen::Manifest::build(&records, &db);
|
||||
let summary = manifest.summary();
|
||||
|
||||
println!("Classification summary:");
|
||||
for (tier, count) in &summary {
|
||||
let pct = (*count as f64 / records.len() as f64 * 100.0) as u32;
|
||||
println!(" - {tier}: {count} ({pct}%)");
|
||||
}
|
||||
|
||||
let files = xenora_import_gen::generate(&manifest, &db);
|
||||
if let Err(err) = files.write_all(&out_dir) {
|
||||
eprintln!("failed to write generated files: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
let manifest_csv = format!("{out_dir}/generated_manifest.csv");
|
||||
if let Err(err) = manifest.write_csv(&manifest_csv) {
|
||||
eprintln!("failed to write manifest CSV: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
|
||||
println!("Successfully generated bindings in '{out_dir}':");
|
||||
println!(" - {out_dir}/generated_crt.rs");
|
||||
println!(" - {out_dir}/generated_stubs.rs");
|
||||
println!(" - {out_dir}/generated_tests.rs");
|
||||
println!(" - {out_dir}/generated_manifest.md");
|
||||
println!(" - {out_dir}/generated_manifest.csv");
|
||||
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn run_imports_sync_cli(args: &[String]) -> ExitCode {
|
||||
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
|
||||
let mut check_mode = false;
|
||||
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--report" => {
|
||||
if i + 1 < args.len() {
|
||||
report_dir = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --report");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--check" => {
|
||||
check_mode = true;
|
||||
i += 1;
|
||||
}
|
||||
other => {
|
||||
eprintln!("unknown sync argument: {other}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match run_imports_sync(&report_dir, check_mode) {
|
||||
Ok(changed) => {
|
||||
if check_mode {
|
||||
if changed {
|
||||
eprintln!("imports sync --check: import_backlog.md is out of date");
|
||||
ExitCode::FAILURE
|
||||
} else {
|
||||
println!("imports sync --check: import_backlog.md is up to date");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
} else {
|
||||
println!("imports sync complete. Report written to: {report_dir}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("imports sync failed: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_imports_sync(
|
||||
report_dir: &str,
|
||||
check_mode: bool,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::ImportRegistry;
|
||||
use xenora_loader::imports::ServiceStatus;
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
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(),
|
||||
);
|
||||
}
|
||||
|
||||
// Build the standard registry to get current implementation state.
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
|
||||
// Parse imports.csv (skip header line).
|
||||
let csv_text = std::fs::read_to_string(&imports_csv_path)?;
|
||||
let mut by_module: BTreeMap<String, Vec<(String, bool, Option<ServiceStatus>)>> =
|
||||
BTreeMap::new();
|
||||
let mut total = 0usize;
|
||||
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
|
||||
for line in csv_text.lines().skip(1) {
|
||||
// Format: "module","symbol",0xRVA,category,registered,status,is_alias,"canonical",priority,cluster
|
||||
// We re-query the live registry rather than trusting cached status.
|
||||
let fields: Vec<&str> = line.splitn(10, ',').collect();
|
||||
if fields.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let module = fields[0].trim_matches('"').to_string();
|
||||
let symbol = fields[1].trim_matches('"').to_string();
|
||||
if module.is_empty() || symbol.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let binding = registry.binding(&module, &symbol);
|
||||
let is_registered = binding.is_some();
|
||||
let status = binding.map(|b| b.status);
|
||||
|
||||
let label: &'static str = match status {
|
||||
Some(ServiceStatus::Implemented) => "implemented",
|
||||
Some(ServiceStatus::Partial) => "partial",
|
||||
Some(ServiceStatus::Stub) => "stub",
|
||||
None => {
|
||||
// Check explicit known-unsupported list
|
||||
match (module.to_ascii_lowercase().as_str(), symbol.as_str()) {
|
||||
(
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll",
|
||||
"CreateThread" | "ResumeThread" | "SuspendThread" | "TerminateProcess",
|
||||
)
|
||||
| (
|
||||
"api-ms-win-core-synch-l1-1-0.dll",
|
||||
"WaitForSingleObject" | "WaitForSingleObjectEx",
|
||||
)
|
||||
| ("api-ms-win-core-synch-l1-2-1.dll", "WaitForMultipleObjects")
|
||||
| ("api-ms-win-core-rtlsupport-l1-1-0.dll", "RtlVirtualUnwind") => {
|
||||
"unsupported"
|
||||
}
|
||||
_ => "missing",
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
*counts.entry(label).or_default() += 1;
|
||||
total += 1;
|
||||
by_module
|
||||
.entry(module.to_ascii_lowercase())
|
||||
.or_default()
|
||||
.push((symbol, is_registered, status));
|
||||
}
|
||||
|
||||
// Build the refreshed import_backlog.md.
|
||||
let mut md = String::new();
|
||||
let _ = writeln!(md, "# Xenora import compatibility backlog");
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"Generated by `xenora imports sync`. Do not edit manually."
|
||||
);
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"Re-run after adding service handlers to refresh this file."
|
||||
);
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(md, "## Summary");
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(md, "| Status | Count |");
|
||||
let _ = writeln!(md, "| --- | ---: |");
|
||||
let _ = writeln!(md, "| **Total** | {total} |");
|
||||
for (label, count) in &counts {
|
||||
let _ = writeln!(md, "| {label} | {count} |");
|
||||
}
|
||||
let _ = writeln!(md);
|
||||
|
||||
let _ = writeln!(md, "## Missing handlers (highest value first)");
|
||||
let _ = writeln!(md);
|
||||
|
||||
// Priority ordering: processthreads, synch, rtlsupport, memory, crt, file, graphics, other
|
||||
fn priority_key(module: &str) -> u8 {
|
||||
if module.contains("processthreads") || module.contains("core-handle") {
|
||||
1
|
||||
} else if module.contains("fibers") || module.contains("tls") {
|
||||
2
|
||||
} else if module.contains("core-synch") {
|
||||
3
|
||||
} else if module.contains("core-profile") || module.contains("core-sysinfo") {
|
||||
4
|
||||
} else if module.contains("core-memory")
|
||||
|| module.contains("core-heap")
|
||||
|| module == "xmem.dll"
|
||||
{
|
||||
5
|
||||
} else if module.starts_with("api-ms-win-crt-")
|
||||
|| module.contains("vcruntime")
|
||||
|| module.contains("libraryloader")
|
||||
{
|
||||
6
|
||||
} else if module.contains("rtlsupport") || module.contains("errorhandling") {
|
||||
7
|
||||
} else if module.contains("core-file") || module == "xcrdapi.dll" {
|
||||
8
|
||||
} else {
|
||||
9
|
||||
}
|
||||
}
|
||||
|
||||
// Collect missing/unsupported into a prioritized list.
|
||||
let mut missing_entries: Vec<(u8, String, String)> = Vec::new();
|
||||
for (module, symbols) in &by_module {
|
||||
for (symbol, is_registered, _status) in symbols {
|
||||
if !is_registered {
|
||||
missing_entries.push((priority_key(module), module.clone(), symbol.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
missing_entries.sort();
|
||||
|
||||
let mut prev_priority = 255u8;
|
||||
for (priority, module, symbol) in &missing_entries {
|
||||
if *priority != prev_priority {
|
||||
let _ = writeln!(md, "### Priority {priority}");
|
||||
let _ = writeln!(md);
|
||||
prev_priority = *priority;
|
||||
}
|
||||
let _ = writeln!(md, "- `{module}!{symbol}`");
|
||||
}
|
||||
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(md, "## Registered handlers");
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(md, "| Module | Symbol | Status |");
|
||||
let _ = writeln!(md, "| --- | --- | --- |");
|
||||
// Enumerate canonical registrations sorted by module, symbol
|
||||
let mut registered: BTreeSet<(String, String, &'static str)> = BTreeSet::new();
|
||||
for (module, symbol, status) in registry.iter_registered() {
|
||||
registered.insert((
|
||||
module.to_ascii_lowercase(),
|
||||
symbol.to_string(),
|
||||
status.as_str(),
|
||||
));
|
||||
}
|
||||
for (module, symbol, status) in ®istered {
|
||||
let _ = writeln!(md, "| `{module}` | `{symbol}` | {status} |");
|
||||
}
|
||||
|
||||
let out_path = std::path::Path::new(report_dir).join("import_backlog.md");
|
||||
let existing = std::fs::read_to_string(&out_path).unwrap_or_default();
|
||||
let changed = existing != md;
|
||||
|
||||
if !check_mode {
|
||||
std::fs::write(&out_path, &md)?;
|
||||
println!(
|
||||
" Total imports: {total} | implemented: {} | partial: {} | stub: {} | missing: {}",
|
||||
counts.get("implemented").copied().unwrap_or(0),
|
||||
counts.get("partial").copied().unwrap_or(0),
|
||||
counts.get("stub").copied().unwrap_or(0),
|
||||
counts.get("missing").copied().unwrap_or(0),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
use std::fmt::Write as _;
|
||||
@@ -0,0 +1,358 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::error::Error;
|
||||
use std::ffi::OsString;
|
||||
use std::fs::{self, File};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitCode, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use xenora_loader::startup::{StartupEvent, StartupLayout, run_synthetic_startup_with_observer};
|
||||
use xenora_loader::{ExitReason, ImportRegistry, Register};
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
const WALL_LIMIT: Duration = Duration::from_secs(15);
|
||||
const DEFAULT_STEPS: usize = 100;
|
||||
const MAX_STEPS: usize = 10_000;
|
||||
const IMAGE_BASE: u64 = 0x150000000;
|
||||
const TICKET_ADDRESS: u64 = IMAGE_BASE + 0x3000;
|
||||
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>]";
|
||||
|
||||
struct Options {
|
||||
path: PathBuf,
|
||||
max_steps: usize,
|
||||
worker: bool,
|
||||
trace: bool,
|
||||
hud: bool,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
fn parse(args: impl IntoIterator<Item = OsString>) -> Result<Self, String> {
|
||||
let mut args = args.into_iter();
|
||||
let mut path = None;
|
||||
let mut max_steps = None;
|
||||
let (mut experimental, mut trace, mut hud, mut worker) = (false, false, false, false);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.to_str() {
|
||||
Some("--pe") if path.is_none() => {
|
||||
path = Some(PathBuf::from(args.next().ok_or("missing --pe path")?));
|
||||
}
|
||||
Some("--max-steps") if max_steps.is_none() => {
|
||||
max_steps = Some(
|
||||
args.next()
|
||||
.and_then(|arg| arg.to_str()?.parse::<usize>().ok())
|
||||
.filter(|steps| (1..=MAX_STEPS).contains(steps))
|
||||
.ok_or("--max-steps must be in 1..=10000")?,
|
||||
);
|
||||
}
|
||||
Some("--experimental") if !experimental => experimental = true,
|
||||
Some("--trace") if !trace => trace = true,
|
||||
Some("--metal-hud") if !hud => hud = true,
|
||||
Some("--worker") if !worker => worker = true,
|
||||
_ => return Err(format!("unknown or repeated run argument {arg:?}")),
|
||||
}
|
||||
}
|
||||
if !experimental {
|
||||
return Err("run requires --experimental".into());
|
||||
}
|
||||
Ok(Self {
|
||||
path: path.ok_or("missing --pe path")?,
|
||||
max_steps: max_steps.unwrap_or(DEFAULT_STEPS),
|
||||
worker,
|
||||
trace,
|
||||
hud,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
|
||||
let options = match Options::parse(args) {
|
||||
Ok(options) => options,
|
||||
Err(error) => {
|
||||
eprintln!("{error}\n{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let result = if options.worker {
|
||||
run_worker(&options).map(|()| ExitCode::SUCCESS)
|
||||
} else {
|
||||
launch_worker(&options)
|
||||
};
|
||||
match result {
|
||||
Ok(code) => code,
|
||||
Err(error) => {
|
||||
eprintln!("run failed: {error}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
|
||||
let started = Instant::now();
|
||||
let mut child = Command::new(std::env::current_exe()?)
|
||||
.args([
|
||||
"run",
|
||||
"--experimental",
|
||||
"--trace",
|
||||
"--metal-hud",
|
||||
"--worker",
|
||||
])
|
||||
.arg("--max-steps")
|
||||
.arg(options.max_steps.to_string())
|
||||
.arg("--pe")
|
||||
.arg(&options.path)
|
||||
.stdin(Stdio::null())
|
||||
.spawn()?;
|
||||
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 => {
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_fixture(path: &Path) -> Result<(), Box<dyn Error>> {
|
||||
let valid_metadata =
|
||||
|metadata: fs::Metadata| metadata.is_file() && metadata.len() == FIXTURE.len() as u64;
|
||||
let rejection =
|
||||
"execution denied: input must match the original trusted PE fixture byte for byte";
|
||||
// Check size before opening and again on the descriptor. Bound the read
|
||||
// even if another process changes the file after the metadata checks.
|
||||
if !valid_metadata(fs::metadata(path)?) {
|
||||
return Err(rejection.into());
|
||||
}
|
||||
let file = File::open(path)?;
|
||||
if !valid_metadata(file.metadata()?) {
|
||||
return Err(rejection.into());
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(FIXTURE.len() + 1);
|
||||
file.take(FIXTURE.len() as u64 + 1)
|
||||
.read_to_end(&mut bytes)?;
|
||||
if bytes != FIXTURE {
|
||||
return Err(rejection.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_worker(options: &Options) -> 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);
|
||||
})?;
|
||||
verify_fixture(&options.path)?;
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace fixture=trusted-runner policy=exact-bytes entry_step_limit={} wall_limit_ms=15000",
|
||||
options.max_steps
|
||||
);
|
||||
}
|
||||
|
||||
let capture = Arc::new(Mutex::new(None));
|
||||
let draw_capture = Arc::clone(&capture);
|
||||
let mut imports = ImportRegistry::new();
|
||||
let trace = options.trace;
|
||||
imports.register("xenora.dll", "fixture_draw", move |args, _, memory| {
|
||||
let ticket_address = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
let mut result = draw_capture
|
||||
.lock()
|
||||
.map_err(|_| ExitReason::IllegalInstruction(0xff))?;
|
||||
if result.is_some() {
|
||||
return Err(ExitReason::IllegalInstruction(0xff));
|
||||
}
|
||||
if ticket_address != TICKET_ADDRESS
|
||||
|| memory
|
||||
.read_u64(ticket_address)
|
||||
.map_err(ExitReason::MemoryFault)?
|
||||
!= TICKET
|
||||
{
|
||||
*result = Some(Err(
|
||||
"draw ticket did not match the TLS-initialized guest word".into(),
|
||||
));
|
||||
return Err(ExitReason::IllegalInstruction(0xff));
|
||||
}
|
||||
if trace {
|
||||
println!("trace import=xenora.dll!fixture_draw tls_ticket={TICKET}");
|
||||
}
|
||||
let frame = draw().map_err(|error| error.to_string());
|
||||
let drawn = frame.is_ok();
|
||||
*result = Some(frame);
|
||||
if drawn {
|
||||
Ok(DRAW_RESULT)
|
||||
} else {
|
||||
Err(ExitReason::IllegalInstruction(0xff))
|
||||
}
|
||||
});
|
||||
|
||||
let started = Instant::now();
|
||||
// Use only the embedded snapshot. The file is solely an exact-byte gate.
|
||||
let startup = run_synthetic_startup_with_observer(
|
||||
FIXTURE,
|
||||
StartupLayout {
|
||||
image_base: IMAGE_BASE,
|
||||
stack_top: 0x200010000,
|
||||
tls_base: 0x300000000,
|
||||
},
|
||||
imports,
|
||||
options.max_steps,
|
||||
|event| {
|
||||
if options.trace {
|
||||
trace_startup(event);
|
||||
}
|
||||
},
|
||||
)?;
|
||||
let host_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
let result = capture
|
||||
.lock()
|
||||
.map_err(|_| "fixture draw result lock failed")?
|
||||
.take();
|
||||
let exit = startup.execution.exit_reason;
|
||||
let rax = startup.execution.final_state.get(Register::Rax);
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace stage=exit entry_steps={} exit={exit:?} rax={rax:#x}",
|
||||
startup.execution.instructions_executed,
|
||||
);
|
||||
}
|
||||
if let Some(Err(error)) = &result {
|
||||
return Err(format!("fixture draw failed: {error}").into());
|
||||
}
|
||||
if exit != ExitReason::Halt {
|
||||
return Err(exit.into());
|
||||
}
|
||||
if startup.relocations.applied_dir64 != 4
|
||||
|| startup.bound_imports != 1
|
||||
|| startup.tls_callbacks != 1
|
||||
|| rax != DRAW_RESULT
|
||||
{
|
||||
return Err("trusted fixture startup or result differs from the expected values".into());
|
||||
}
|
||||
let frame = result.ok_or("guest halted without a draw")??;
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace stage=framebuffer extent={}x{} verified_pixels={}",
|
||||
EXTENT[0],
|
||||
EXTENT[1],
|
||||
EXTENT[0] * EXTENT[1],
|
||||
);
|
||||
}
|
||||
if options.hud {
|
||||
let gpu_time = frame.gpu_seconds.map_or_else(
|
||||
|| "unavailable".to_owned(),
|
||||
|seconds| format!("{:.3}", seconds * 1000.0),
|
||||
);
|
||||
println!(
|
||||
"Metal HUD | device={} | offscreen={}x{} | draw_calls=1 | verified_pixels={} | host_render_readback_ms={:.3} | host_startup_ms={host_ms:.3} | gpu_command_ms={gpu_time}",
|
||||
frame.device,
|
||||
EXTENT[0],
|
||||
EXTENT[1],
|
||||
EXTENT[0] * EXTENT[1],
|
||||
frame.host_render_readback_ms,
|
||||
);
|
||||
let metrics = startup.dbt_metrics;
|
||||
println!(
|
||||
"DBT | entry_steps={} | native_steps_tls_and_entry={} | blocks_compiled={} | native_bytes={} | native_dispatches={} | service_calls={} | interpreter_fallbacks={}",
|
||||
startup.execution.instructions_executed,
|
||||
metrics.instructions_executed,
|
||||
metrics.blocks_compiled,
|
||||
metrics.native_bytes_emitted,
|
||||
metrics.dbt_dispatches,
|
||||
metrics.service_calls,
|
||||
metrics.interpreter_fallbacks,
|
||||
);
|
||||
}
|
||||
println!("Trusted fixture completed one verified offscreen Metal draw.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn trace_startup(event: StartupEvent) {
|
||||
match event {
|
||||
StartupEvent::Parsed {
|
||||
sections,
|
||||
entry_rva,
|
||||
} => {
|
||||
println!("trace stage=parsed sections={sections} entry_rva={entry_rva:#x}");
|
||||
}
|
||||
StartupEvent::Mapped { entry_va } => {
|
||||
println!("trace stage=mapped base={IMAGE_BASE:#x} entry_va={entry_va:#x}");
|
||||
}
|
||||
StartupEvent::Relocated { applied_dir64 } => {
|
||||
println!("trace stage=relocated dir64_applied={applied_dir64}");
|
||||
}
|
||||
StartupEvent::ImportsBound { count } => {
|
||||
println!("trace stage=imports_bound bound_imports={count}");
|
||||
}
|
||||
StartupEvent::TlsCompleted {
|
||||
callbacks,
|
||||
native_steps,
|
||||
} => {
|
||||
println!(
|
||||
"trace stage=tls_completed tls_callbacks={callbacks} native_steps={native_steps}"
|
||||
);
|
||||
}
|
||||
StartupEvent::Entering { step_limit } => {
|
||||
println!("trace stage=entry step_limit={step_limit}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Frame {
|
||||
device: String,
|
||||
host_render_readback_ms: f64,
|
||||
gpu_seconds: Option<f64>,
|
||||
}
|
||||
|
||||
fn draw() -> Result<Frame, Box<dyn Error>> {
|
||||
let shader = compile_graphics(
|
||||
Architecture::Gfx1030,
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
|
||||
)?;
|
||||
let gpu = NativeCompute::new()?;
|
||||
let started = Instant::now();
|
||||
let (pixels, gpu_seconds) = gpu.render_rgba8_profiled(
|
||||
&shader.msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
&[
|
||||
[-1.0, -1.0, 0.5, 1.0],
|
||||
[3.0, -1.0, 0.5, 1.0],
|
||||
[-1.0, 3.0, 0.5, 1.0],
|
||||
],
|
||||
&[[0.0; 4]; 3],
|
||||
EXTENT,
|
||||
[19, 43, 93, 251],
|
||||
)?;
|
||||
let host_render_readback_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
if pixels != EXPECTED_PIXEL.repeat(EXTENT[0] * EXTENT[1]) {
|
||||
return Err("offscreen readback did not match opaque red at every pixel".into());
|
||||
}
|
||||
Ok(Frame {
|
||||
device: gpu.device_name().to_owned(),
|
||||
host_render_readback_ms,
|
||||
gpu_seconds,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
//! `xenora 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>>";
|
||||
|
||||
pub fn command(args: &[String]) -> ExitCode {
|
||||
match args.first().map(String::as_str) {
|
||||
Some("coverage") => coverage(args.get(1).map(String::as_str) == Some("--json")),
|
||||
Some("inspect") => match args.get(1) {
|
||||
Some(path) => inspect(path),
|
||||
None => usage(),
|
||||
},
|
||||
_ => usage(),
|
||||
}
|
||||
}
|
||||
|
||||
fn usage() -> ExitCode {
|
||||
eprintln!("{USAGE}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
|
||||
fn semantic(family: EncodingFamily) -> usize {
|
||||
SEMANTIC_FORMS
|
||||
.iter()
|
||||
.filter(|(_, form_family)| *form_family == family)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Per-family counts. "Discovered" forms come from AMD's XML and are identified
|
||||
/// with their length; "semantic" forms decode into executable instructions.
|
||||
/// Reference, Metal and native GPU evidence per form stays in docs/status.toml.
|
||||
fn coverage(json: bool) -> ExitCode {
|
||||
print!("{}", coverage_report(json));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn coverage_report(json: bool) -> String {
|
||||
use std::fmt::Write as _;
|
||||
let rows: Vec<_> = meta::inventory()
|
||||
.into_iter()
|
||||
.map(|(family, discovered)| (family, discovered, semantic(family)))
|
||||
.collect();
|
||||
let total: usize = rows.iter().map(|row| row.1).sum();
|
||||
let supported: usize = rows.iter().map(|row| row.2).sum();
|
||||
let mut out = String::new();
|
||||
if json {
|
||||
let families: Vec<String> = rows
|
||||
.iter()
|
||||
.map(|(family, discovered, semantic)| {
|
||||
format!(
|
||||
"{{\"family\":\"{}\",\"discovered\":{discovered},\"semantic\":{semantic}}}",
|
||||
family.name()
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
writeln!(
|
||||
out,
|
||||
"{{\"architecture\":\"gfx1030\",\"source_sha256\":\"{}\",\"discovered\":{total},\"semantic\":{supported},\"families\":[{}]}}",
|
||||
meta::SOURCE_SHA256,
|
||||
families.join(",")
|
||||
)
|
||||
.unwrap();
|
||||
} else {
|
||||
writeln!(
|
||||
out,
|
||||
"{:<10} {:>10} {:>9}",
|
||||
"family", "discovered", "semantic"
|
||||
)
|
||||
.unwrap();
|
||||
for (family, discovered, semantic) in &rows {
|
||||
writeln!(out, "{:<10} {discovered:>10} {semantic:>9}", family.name()).unwrap();
|
||||
}
|
||||
writeln!(out, "{:<10} {total:>10} {supported:>9}", "total").unwrap();
|
||||
writeln!(
|
||||
out,
|
||||
"Semantic forms decode for the operand subsets in docs/status.toml only."
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn inspect(path: &str) -> ExitCode {
|
||||
let bytes = match std::fs::read(path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => {
|
||||
eprintln!("{path}: {error}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let listing = listing(&bytes);
|
||||
for row in &listing.rows {
|
||||
println!("{row}");
|
||||
}
|
||||
if let Some(failure) = listing.failure {
|
||||
println!("{failure}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
println!(
|
||||
"{} instructions inspected against {} gfx1030 forms; {} without semantic decoding",
|
||||
listing.rows.len(),
|
||||
FORMS.len(),
|
||||
listing.unsupported
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// The printed rows of `xenora 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 {
|
||||
rows: Vec<String>,
|
||||
unsupported: usize,
|
||||
failure: Option<String>,
|
||||
}
|
||||
|
||||
fn listing(bytes: &[u8]) -> Listing {
|
||||
let mut listing = Listing {
|
||||
rows: Vec::new(),
|
||||
unsupported: 0,
|
||||
failure: None,
|
||||
};
|
||||
// Identify every instruction first: a branch target is valid only if it
|
||||
// lands on one of these boundaries, which no single instruction can show.
|
||||
let mut forms = Vec::new();
|
||||
let mut offset = 0;
|
||||
while offset < bytes.len() {
|
||||
match identify(&bytes[offset..]) {
|
||||
Ok(found) => {
|
||||
forms.push((offset, found));
|
||||
offset += found.len;
|
||||
}
|
||||
Err(error) => {
|
||||
listing.failure = Some(format!("{offset:#06x} decode failure: {error}"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let boundary = |target: usize| forms.binary_search_by_key(&target, |form| form.0).is_ok();
|
||||
// Past the last identified instruction the boundaries are unknown.
|
||||
let identified = forms
|
||||
.last()
|
||||
.map_or(0, |&(offset, found)| offset + found.len);
|
||||
for &(offset, found) in &forms {
|
||||
let instruction = &bytes[offset..offset + found.len];
|
||||
let words: Vec<String> = instruction
|
||||
.chunks(4)
|
||||
.map(|chunk| format!("{:08x}", u32::from_le_bytes(chunk.try_into().unwrap())))
|
||||
.collect();
|
||||
let status = match decode_at(Architecture::Gfx1030, &bytes[..offset + found.len], offset) {
|
||||
Ok(decoded) => match decoded.branch_target() {
|
||||
Some(target) if listing.failure.is_some() && target >= identified => {
|
||||
format!("branch target {target:#04x} unverified: stream not identified there")
|
||||
}
|
||||
Some(target) if !boundary(target) => {
|
||||
format!("invalid branch target {target:#04x}")
|
||||
}
|
||||
_ => "semantic".to_owned(),
|
||||
},
|
||||
Err(error) if SEMANTIC_FORMS.contains(&(found.form.name, found.form.family)) => {
|
||||
format!("unsupported operands: {error}")
|
||||
}
|
||||
Err(_) => "unsupported instruction semantics".to_owned(),
|
||||
};
|
||||
if status != "semantic" {
|
||||
listing.unsupported += 1;
|
||||
}
|
||||
listing.rows.push(format!(
|
||||
"{offset:#06x} {:<8} {:<28} {:<26} {status}",
|
||||
found.form.family.name(),
|
||||
found.form.name.to_ascii_lowercase(),
|
||||
words.join(" ")
|
||||
));
|
||||
}
|
||||
listing
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{coverage_report, listing};
|
||||
use xenora_decoder::SEMANTIC_FORMS;
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS};
|
||||
|
||||
#[test]
|
||||
fn coverage_totals_match_the_generated_table() {
|
||||
let json = coverage_report(true);
|
||||
assert!(json.starts_with("{\"architecture\":\"gfx1030\""), "{json}");
|
||||
assert!(json.ends_with("}]}\n"), "{json}");
|
||||
assert_eq!(json.matches('{').count(), json.matches('}').count());
|
||||
let totals = format!(
|
||||
"\"discovered\":{},\"semantic\":{},\"families\":[",
|
||||
FORMS.len(),
|
||||
SEMANTIC_FORMS.len()
|
||||
);
|
||||
assert!(json.contains(&totals), "{json}");
|
||||
let families: Vec<usize> = json
|
||||
.split("{\"family\":")
|
||||
.skip(1)
|
||||
.map(|row| {
|
||||
let count = row.split("\"discovered\":").nth(1).unwrap();
|
||||
count[..count.find(',').unwrap()].parse().unwrap()
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(families.len(), EncodingFamily::ALL.len());
|
||||
assert_eq!(families.iter().sum::<usize>(), FORMS.len());
|
||||
let text = coverage_report(false);
|
||||
let total = format!(
|
||||
"{:<10} {:>10} {:>9}\n",
|
||||
"total",
|
||||
FORMS.len(),
|
||||
SEMANTIC_FORMS.len()
|
||||
);
|
||||
assert!(text.contains(&total), "{text}");
|
||||
}
|
||||
|
||||
fn program(words: &[u32]) -> Vec<u8> {
|
||||
words.iter().flat_map(|word| word.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branches_in_a_valid_program_are_semantic() {
|
||||
let fixture = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
|
||||
let listing = listing(fixture);
|
||||
assert_eq!(listing.failure, None);
|
||||
assert_eq!(listing.rows.len(), 15);
|
||||
let branches: Vec<_> = listing
|
||||
.rows
|
||||
.iter()
|
||||
.filter(|row| row.contains("branch"))
|
||||
.collect();
|
||||
assert_eq!(branches.len(), 3);
|
||||
for row in &branches {
|
||||
assert!(row.ends_with(" semantic"), "{row}");
|
||||
}
|
||||
assert_eq!(listing.unsupported, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_past_an_identification_failure_are_unverified() {
|
||||
// s_branch 1 targets 0x08; 0xbfff0000 is not a gfx1030 form, so
|
||||
// nothing past 0x04 is identified; s_endpgm.
|
||||
let listing = listing(&program(&[0xbf82_0001, 0xbfff_0000, 0xbf81_0000]));
|
||||
assert!(listing.failure.as_deref().unwrap().starts_with("0x0004"));
|
||||
assert_eq!(listing.rows.len(), 1);
|
||||
assert!(
|
||||
listing.rows[0].ends_with("branch target 0x08 unverified: stream not identified there"),
|
||||
"{}",
|
||||
listing.rows[0]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_fixture_is_fully_semantic() {
|
||||
let listing = listing(include_bytes!("../../../fixtures/rdna2/add.bin"));
|
||||
assert_eq!(listing.failure, None);
|
||||
assert_eq!(listing.rows.len(), 7);
|
||||
assert_eq!(listing.unsupported, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branch_targets_are_checked_against_the_whole_stream() {
|
||||
// s_branch 1 skips one word; s_cbranch_scc0 1 lands inside the
|
||||
// two-word v_mov_b32 literal form; s_endpgm.
|
||||
let listing = listing(&program(&[
|
||||
0xbf82_0001,
|
||||
0xbf84_0001,
|
||||
0x7e04_02ff,
|
||||
0x00ff_00ff,
|
||||
0xbf81_0000,
|
||||
]));
|
||||
assert_eq!(listing.failure, None);
|
||||
assert!(
|
||||
listing.rows[0].ends_with(" semantic"),
|
||||
"{}",
|
||||
listing.rows[0]
|
||||
);
|
||||
assert!(
|
||||
listing.rows[1].ends_with("invalid branch target 0x0c"),
|
||||
"{}",
|
||||
listing.rows[1]
|
||||
);
|
||||
assert_eq!(listing.unsupported, 1);
|
||||
}
|
||||
}
|
||||
+252
-25
@@ -3,15 +3,84 @@
|
||||
use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, ExportTarget, Instruction, InterpolationPhase, ScalarSource, VectorSource,
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorCompareOp, VectorSource,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32,
|
||||
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
|
||||
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
use xenora_isa::semantics::FORM_IDS;
|
||||
pub use xenora_isa::semantics::VectorBinary;
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination: the hand-written forms below followed by every form of
|
||||
/// the semantic registry ([`xenora_isa::semantics::FORM_IDS`]). Operand
|
||||
/// restrictions are listed in docs/status.toml; every other form in
|
||||
/// [`xenora_isa::meta::FORMS`] is rejected as unsupported.
|
||||
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); HANDWRITTEN_FORMS.len() + FORM_IDS.len()] =
|
||||
concat_forms();
|
||||
|
||||
const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
|
||||
let mut forms = [("", EncodingFamily::Sop2); N];
|
||||
let mut index = 0;
|
||||
while index < N {
|
||||
forms[index] = if index < HANDWRITTEN_FORMS.len() {
|
||||
HANDWRITTEN_FORMS[index]
|
||||
} else {
|
||||
FORM_IDS[index - HANDWRITTEN_FORMS.len()]
|
||||
};
|
||||
index += 1;
|
||||
}
|
||||
forms
|
||||
}
|
||||
|
||||
/// Decoded forms not yet described by the semantic registry.
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
|
||||
("S_BRANCH", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_MOV_B32", EncodingFamily::Sop1),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
|
||||
("V_ADD_F32", EncodingFamily::Vop2),
|
||||
("V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
("V_AND_B32", EncodingFamily::Vop2),
|
||||
("V_ASHRREV_I32", EncodingFamily::Vop2),
|
||||
("V_CMP_EQ_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_EQ_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_GE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_GE_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_GT_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_GT_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_LE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_LE_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_LT_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_LT_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_NE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_NE_U32", EncodingFamily::Vopc),
|
||||
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
|
||||
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
|
||||
("V_LSHLREV_B32", EncodingFamily::Vop2),
|
||||
("V_LSHRREV_B32", EncodingFamily::Vop2),
|
||||
("V_MOV_B32", EncodingFamily::Vop1),
|
||||
("V_MUL_F32", EncodingFamily::Vop2),
|
||||
("V_OR_B32", EncodingFamily::Vop2),
|
||||
("V_XOR_B32", EncodingFamily::Vop2),
|
||||
];
|
||||
|
||||
/// A successfully decoded instruction and its location in the input stream.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct DecodedInstruction {
|
||||
@@ -23,6 +92,20 @@ pub struct DecodedInstruction {
|
||||
pub instruction: Instruction,
|
||||
}
|
||||
|
||||
impl DecodedInstruction {
|
||||
/// Destination byte offset of a branch, from the start of the stream.
|
||||
#[must_use]
|
||||
pub fn branch_target(&self) -> Option<usize> {
|
||||
match self.instruction {
|
||||
Instruction::Branch { target }
|
||||
| Instruction::BranchSccZero { target }
|
||||
| Instruction::BranchExecZero { target }
|
||||
| Instruction::BranchVccZero { target } => Some(target),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for DecodedInstruction {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "{:04x}: {}", self.offset, self.instruction)
|
||||
@@ -107,26 +190,15 @@ pub fn decode(
|
||||
architecture: Architecture,
|
||||
bytes: &[u8],
|
||||
) -> Result<Vec<DecodedInstruction>, DecodeError> {
|
||||
let decode_instruction = match architecture {
|
||||
Architecture::Gfx1030 => decode_gfx1030,
|
||||
};
|
||||
let mut result = Vec::new();
|
||||
let mut offset = 0;
|
||||
while offset < bytes.len() {
|
||||
let (instruction, byte_len) = decode_instruction(&bytes[offset..], offset)
|
||||
.map_err(|kind| DecodeError { offset, kind })?;
|
||||
result.push(DecodedInstruction {
|
||||
offset,
|
||||
byte_len,
|
||||
instruction,
|
||||
});
|
||||
offset += usize::from(byte_len);
|
||||
let decoded = decode_at(architecture, bytes, offset)?;
|
||||
offset += usize::from(decoded.byte_len);
|
||||
result.push(decoded);
|
||||
}
|
||||
for decoded in &result {
|
||||
if let Instruction::Branch { target }
|
||||
| Instruction::BranchSccZero { target }
|
||||
| Instruction::BranchExecZero { target }
|
||||
| Instruction::BranchVccZero { target } = decoded.instruction
|
||||
if let Some(target) = decoded.branch_target()
|
||||
&& result
|
||||
.binary_search_by_key(&target, |item| item.offset)
|
||||
.is_err()
|
||||
@@ -140,6 +212,32 @@ pub fn decode(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Decodes the one instruction that starts at `offset` in `bytes`. Branch
|
||||
/// targets are stream offsets, but whether they land on an instruction
|
||||
/// boundary is left to the caller, which knows the rest of the stream.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `offset` with a truncated instruction, unsupported opcode or
|
||||
/// unsupported form. An `offset` at or past the end is truncated.
|
||||
pub fn decode_at(
|
||||
architecture: Architecture,
|
||||
bytes: &[u8],
|
||||
offset: usize,
|
||||
) -> Result<DecodedInstruction, DecodeError> {
|
||||
let decode_instruction = match architecture {
|
||||
Architecture::Gfx1030 => decode_gfx1030,
|
||||
};
|
||||
let rest = bytes.get(offset..).unwrap_or_default();
|
||||
let (instruction, byte_len) =
|
||||
decode_instruction(rest, offset).map_err(|kind| DecodeError { offset, kind })?;
|
||||
Ok(DecodedInstruction {
|
||||
offset,
|
||||
byte_len,
|
||||
instruction,
|
||||
})
|
||||
}
|
||||
|
||||
fn word(bytes: &[u8], end: u8) -> Result<u32, DecodeErrorKind> {
|
||||
let end_index = usize::from(end);
|
||||
let Some(word) = bytes
|
||||
@@ -240,6 +338,27 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
if V_MOV_B32.matches(first) {
|
||||
return move_b32(first, bytes);
|
||||
}
|
||||
{
|
||||
use CompareRelation::{Equal, Greater, GreaterOrEqual, Less, LessOrEqual, NotEqual};
|
||||
for (opcode, relation, signed) in [
|
||||
(V_CMP_LT_I32, Less, true),
|
||||
(V_CMP_EQ_I32, Equal, true),
|
||||
(V_CMP_LE_I32, LessOrEqual, true),
|
||||
(V_CMP_GT_I32, Greater, true),
|
||||
(V_CMP_NE_I32, NotEqual, true),
|
||||
(V_CMP_GE_I32, GreaterOrEqual, true),
|
||||
(V_CMP_LT_U32, Less, false),
|
||||
(V_CMP_EQ_U32, Equal, false),
|
||||
(V_CMP_LE_U32, LessOrEqual, false),
|
||||
(V_CMP_GT_U32, Greater, false),
|
||||
(V_CMP_NE_U32, NotEqual, false),
|
||||
(V_CMP_GE_U32, GreaterOrEqual, false),
|
||||
] {
|
||||
if opcode.matches(first) {
|
||||
return vector_compare(VectorCompareOp { relation, signed }, first, bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
if V_ADD_NC_U32.matches(first) {
|
||||
let len = V_ADD_NC_U32.byte_len();
|
||||
let second = word(bytes, len)?;
|
||||
@@ -256,19 +375,30 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
|
||||
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
|
||||
}
|
||||
if S_CMP_EQ_U32.matches(first) {
|
||||
if let Some(op) = ScalarUnaryOp::from_word(first) {
|
||||
// SOP1: SSRC0 in bits 0-7, SDST in bits 16-22.
|
||||
let mnemonic = op.mnemonic();
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
|
||||
}
|
||||
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
|
||||
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
|
||||
}
|
||||
if let Some(op) = ScalarCompareOp::from_word(first) {
|
||||
let mnemonic = op.mnemonic();
|
||||
let src0_bits = first as u8;
|
||||
let src1_bits = (first >> 8) as u8;
|
||||
if src0_bits == 255 && src1_bits == 255 {
|
||||
return Err(unsupported(
|
||||
"s_cmp_eq_u32",
|
||||
mnemonic,
|
||||
"only one source may select a literal",
|
||||
));
|
||||
}
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, "s_cmp_eq_u32")?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, "s_cmp_eq_u32")?;
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
|
||||
return Ok((
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 },
|
||||
Instruction::ScalarCompare { op, src0, src1 },
|
||||
len0.max(len1),
|
||||
));
|
||||
}
|
||||
@@ -276,6 +406,9 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let target = branch_target(first, offset, "s_branch")?;
|
||||
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
|
||||
}
|
||||
if let Some(op) = ScalarAluOp::from_word(first) {
|
||||
return scalar_alu(op, first, bytes);
|
||||
}
|
||||
if S_CBRANCH_SCC0.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_scc0")?;
|
||||
return Ok((
|
||||
@@ -297,6 +430,21 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
S_CBRANCH_VCCZ.byte_len(),
|
||||
));
|
||||
}
|
||||
if let Some(op) = VectorAluOp::from_word(first) {
|
||||
// VOP2: SRC0 in bits 0-8, VSRC1 in bits 9-16, VDST in bits 17-24.
|
||||
let dst = ((first >> 17) & 0xff) as u8;
|
||||
let src1 = ((first >> 9) & 0xff) as u8;
|
||||
let (src0, len) = vector_src0(first, bytes, op.assembly_name())?;
|
||||
return Ok((
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
},
|
||||
len,
|
||||
));
|
||||
}
|
||||
if V_LSHLREV_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?;
|
||||
return Ok((
|
||||
@@ -384,6 +532,39 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
Err(DecodeErrorKind::UnsupportedOpcode { word: first })
|
||||
}
|
||||
|
||||
/// SOP2: SSRC0 in bits 0-7, SSRC1 in bits 8-15, SDST in bits 16-22.
|
||||
/// Other SOP2 opcodes stay unsupported.
|
||||
fn scalar_alu(
|
||||
op: ScalarAluOp,
|
||||
first: u32,
|
||||
bytes: &[u8],
|
||||
) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let mnemonic = op.mnemonic();
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
|
||||
}
|
||||
let src0_bits = first as u8;
|
||||
let src1_bits = (first >> 8) as u8;
|
||||
if src0_bits == 255 && src1_bits == 255 {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"only one source may select a literal",
|
||||
));
|
||||
}
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
|
||||
Ok((
|
||||
Instruction::ScalarAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
},
|
||||
len0.max(len1),
|
||||
))
|
||||
}
|
||||
|
||||
fn scalar_source(
|
||||
bits: u8,
|
||||
bytes: &[u8],
|
||||
@@ -525,11 +706,57 @@ fn buffer_operands(
|
||||
Ok((data, index, resource))
|
||||
}
|
||||
|
||||
/// VOPC: SRC0 in bits 0-8, VSRC1 in bits 9-16 (RDNA 2 ISA section 12.9). The
|
||||
/// destination is implicitly `vcc_lo`. SRC0 excludes inline float constants,
|
||||
/// `vcc_hi`, EXEC, M0, TTMPs and the condition selectors (SDWA 249, DPP 250/233).
|
||||
fn vector_compare(
|
||||
op: VectorCompareOp,
|
||||
first: u32,
|
||||
bytes: &[u8],
|
||||
) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let src1 = ((first >> 9) & 0xff) as u8;
|
||||
let (src0, len) = vector_src0(first, bytes, op.mnemonic())?;
|
||||
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
|
||||
}
|
||||
|
||||
/// The 9-bit SRC0 of a VOPC or VOP2 word: a VGPR, `s0-s105`, `vcc_lo`, an
|
||||
/// inline integer -16..64 or a literal word; everything else is unsupported.
|
||||
fn vector_src0(
|
||||
first: u32,
|
||||
bytes: &[u8],
|
||||
mnemonic: &'static str,
|
||||
) -> Result<(VectorSource, u8), DecodeErrorKind> {
|
||||
let source = first & 0x1ff;
|
||||
let base_len = 4;
|
||||
Ok(match source {
|
||||
0..=106 => (VectorSource::Scalar(source as u8), base_len),
|
||||
128..=192 => (VectorSource::Immediate(source - 128), base_len),
|
||||
193..=208 => (
|
||||
VectorSource::Immediate(192u32.wrapping_sub(source)),
|
||||
base_len,
|
||||
),
|
||||
255 => {
|
||||
let len = base_len + 4;
|
||||
(VectorSource::Immediate(word(bytes, len)?), len)
|
||||
}
|
||||
256..=511 => (VectorSource::Register(source as u8), base_len),
|
||||
_ => {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"expected a VGPR, normal SGPR, vcc_lo, inline integer or literal",
|
||||
));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let dst = (first >> 17) as u8;
|
||||
let source = first & 0x1ff;
|
||||
let base_len = V_MOV_B32.byte_len();
|
||||
let (src, len) = match source {
|
||||
0..=105 => (VectorSource::Scalar(source as u8), base_len),
|
||||
// vcc_lo, which may hold a lane-derived compare mask (docs/shaders/vector-compare.md).
|
||||
106 => (VectorSource::Scalar(VCC_LO), base_len),
|
||||
128..=192 => (VectorSource::Immediate(source - 128), base_len),
|
||||
193..=208 => (
|
||||
VectorSource::Immediate(192u32.wrapping_sub(source)),
|
||||
@@ -545,7 +772,7 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
|
||||
_ => {
|
||||
return Err(unsupported(
|
||||
"v_mov_b32_e32",
|
||||
"expected a VGPR, inline integer, inline +1.0f or literal",
|
||||
"expected a VGPR, normal SGPR, vcc_lo, inline integer, inline +1.0f or literal",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3,10 +3,14 @@ use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarSource,
|
||||
VectorSource, decode,
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorSource, decode, decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
|
||||
VectorInteger,
|
||||
};
|
||||
use xenora_ref::{BranchCondition, Op, Source, VectorAlu};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
|
||||
@@ -97,7 +101,12 @@ fn rejects_other_opcodes_and_noncanonical_operands() {
|
||||
(&[0xe070_2000, 0x801b_0100], "buffer_store_dword"),
|
||||
(&[0xbf8c_3f71], "s_waitcnt"),
|
||||
(&[0xbbfd_0001], "s_waitcnt_vscnt"),
|
||||
(&[0x7e04_0200], "v_mov_b32_e32"),
|
||||
(&[0x7e04_026b], "v_mov_b32_e32"), // VCC_HI is outside the source subset.
|
||||
(&[0x7d02_046b], "v_cmp_lt_i32_e32"), // VCC_HI source.
|
||||
(&[0x7d02_047e], "v_cmp_lt_i32_e32"), // EXEC_LO source.
|
||||
(&[0x7d02_04f0], "v_cmp_lt_i32_e32"), // Inline 0.5 source.
|
||||
(&[0x7d84_04f9, 0x0606_0601], "v_cmp_eq_u32_e32"), // SDWA.
|
||||
(&[0x7d84_04fa, 0], "v_cmp_eq_u32_e32"), // DPP16.
|
||||
(&[0x7e04_02fa, 0], "v_mov_b32_e32"),
|
||||
(&[0xd525_8001, 0x0202_0501], "v_add_nc_u32_e64"),
|
||||
(&[0xd525_0001, 0x0202_0480], "v_add_nc_u32_e64"),
|
||||
@@ -281,6 +290,7 @@ fn reference_source(vector: VectorSource) -> Source {
|
||||
match vector {
|
||||
VectorSource::Register(reg) => Source::Register(reg),
|
||||
VectorSource::Immediate(bits) => Source::Immediate(bits),
|
||||
VectorSource::Scalar(_) => unreachable!("mapped to Op::MoveScalar"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,11 +323,90 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
},
|
||||
Instruction::WaitLoad => Op::WaitRead,
|
||||
Instruction::WaitStore => Op::WaitWrite,
|
||||
Instruction::MoveB32 {
|
||||
dst,
|
||||
src: VectorSource::Scalar(src),
|
||||
} => Op::MoveScalar(dst, src),
|
||||
Instruction::MoveB32 { dst, src } => Op::Move(dst, reference_source(src)),
|
||||
Instruction::ScalarAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::Scalar(
|
||||
match op {
|
||||
ScalarAluOp::AddU32 => ScalarAlu::Add,
|
||||
ScalarAluOp::SubU32 => ScalarAlu::Subtract,
|
||||
ScalarAluOp::AddI32 => ScalarAlu::AddSigned,
|
||||
ScalarAluOp::SubI32 => ScalarAlu::SubtractSigned,
|
||||
ScalarAluOp::AddcU32 => ScalarAlu::AddWithCarry,
|
||||
ScalarAluOp::SubbU32 => ScalarAlu::SubtractWithBorrow,
|
||||
ScalarAluOp::AndB32 => ScalarAlu::And,
|
||||
ScalarAluOp::OrB32 => ScalarAlu::Or,
|
||||
ScalarAluOp::XorB32 => ScalarAlu::Xor,
|
||||
ScalarAluOp::Andn2B32 => ScalarAlu::AndNot,
|
||||
ScalarAluOp::Orn2B32 => ScalarAlu::OrNot,
|
||||
ScalarAluOp::NandB32 => ScalarAlu::Nand,
|
||||
ScalarAluOp::NorB32 => ScalarAlu::Nor,
|
||||
ScalarAluOp::XnorB32 => ScalarAlu::Xnor,
|
||||
ScalarAluOp::LshlB32 => ScalarAlu::ShiftLeft,
|
||||
ScalarAluOp::LshrB32 => ScalarAlu::ShiftRight,
|
||||
ScalarAluOp::AshrI32 => ScalarAlu::ArithmeticShiftRight,
|
||||
ScalarAluOp::MinI32 => ScalarAlu::Minimum { signed: true },
|
||||
ScalarAluOp::MinU32 => ScalarAlu::Minimum { signed: false },
|
||||
ScalarAluOp::MaxI32 => ScalarAlu::Maximum { signed: true },
|
||||
ScalarAluOp::MaxU32 => ScalarAlu::Maximum { signed: false },
|
||||
ScalarAluOp::CselectB32 => ScalarAlu::Select,
|
||||
ScalarAluOp::BfmB32 => ScalarAlu::BitfieldMask,
|
||||
ScalarAluOp::MulI32 => ScalarAlu::Multiply,
|
||||
ScalarAluOp::BfeU32 => ScalarAlu::BitfieldExtract { signed: false },
|
||||
ScalarAluOp::BfeI32 => ScalarAlu::BitfieldExtract { signed: true },
|
||||
ScalarAluOp::AbsdiffI32 => ScalarAlu::AbsoluteDifference,
|
||||
ScalarAluOp::Lshl1AddU32 => ScalarAlu::ShiftLeftAdd(1),
|
||||
ScalarAluOp::Lshl2AddU32 => ScalarAlu::ShiftLeftAdd(2),
|
||||
ScalarAluOp::Lshl3AddU32 => ScalarAlu::ShiftLeftAdd(3),
|
||||
ScalarAluOp::Lshl4AddU32 => ScalarAlu::ShiftLeftAdd(4),
|
||||
ScalarAluOp::MulHiU32 => ScalarAlu::MultiplyHigh { signed: false },
|
||||
ScalarAluOp::MulHiI32 => ScalarAlu::MultiplyHigh { signed: true },
|
||||
},
|
||||
dst,
|
||||
reference_scalar(src0),
|
||||
reference_scalar(src1),
|
||||
),
|
||||
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
|
||||
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 } => {
|
||||
Op::CompareEqual(reference_scalar(src0), reference_scalar(src1))
|
||||
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
|
||||
match op {
|
||||
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
|
||||
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
|
||||
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
|
||||
ScalarUnaryOp::Bcnt1I32B32 => ScalarUnary::CountOnes,
|
||||
ScalarUnaryOp::Ff0I32B32 => ScalarUnary::FindFirstZero,
|
||||
ScalarUnaryOp::Ff1I32B32 => ScalarUnary::FindFirstOne,
|
||||
ScalarUnaryOp::FlbitI32B32 => ScalarUnary::FindLastBit,
|
||||
ScalarUnaryOp::FlbitI32 => ScalarUnary::FindLastSignBit,
|
||||
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
|
||||
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
|
||||
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
|
||||
},
|
||||
dst,
|
||||
reference_scalar(src),
|
||||
),
|
||||
Instruction::ScalarCompare { op, src0, src1 } => {
|
||||
let (src0, src1) = (reference_scalar(src0), reference_scalar(src1));
|
||||
// The reference keeps CompareEqual for EQ and uses its VOPC relation
|
||||
// offsets (LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6) for the rest.
|
||||
match op.relation() {
|
||||
CompareRelation::Equal => Op::CompareEqual(src0, src1),
|
||||
relation => Op::ScalarCompare(
|
||||
Comparison {
|
||||
offset: relation as u8 + 1,
|
||||
signed: op.semantics().signedness == Signedness::Signed,
|
||||
},
|
||||
src0,
|
||||
src1,
|
||||
),
|
||||
}
|
||||
}
|
||||
Instruction::BranchSccZero { target } => Op::Branch {
|
||||
target,
|
||||
@@ -363,6 +452,53 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
panic!("compute reference matrix received a graphics/image instruction")
|
||||
}
|
||||
|
||||
Instruction::VectorCompare { op, src0, src1 } => Op::Compare(
|
||||
Comparison {
|
||||
offset: match op.relation {
|
||||
CompareRelation::Less => 1,
|
||||
CompareRelation::Equal => 2,
|
||||
CompareRelation::LessOrEqual => 3,
|
||||
CompareRelation::Greater => 4,
|
||||
CompareRelation::NotEqual => 5,
|
||||
CompareRelation::GreaterOrEqual => 6,
|
||||
},
|
||||
signed: op.signed,
|
||||
},
|
||||
match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
},
|
||||
src1,
|
||||
),
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::VectorInteger(
|
||||
match op {
|
||||
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,
|
||||
},
|
||||
dst,
|
||||
match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
},
|
||||
src1,
|
||||
),
|
||||
Instruction::EndProgram => Op::End,
|
||||
}
|
||||
}
|
||||
@@ -383,12 +519,19 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
OR_FIXTURE,
|
||||
SHIFT_FIXTURE,
|
||||
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-logic.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-unary.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 21, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 100, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
@@ -396,6 +539,7 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
}
|
||||
|
||||
fn assemble_matrix() -> Vec<u8> {
|
||||
use std::fmt::Write as _;
|
||||
// Cover register banks and extrema, immediate classes in both scalar
|
||||
// compare positions, zero displacement and branches over literal words.
|
||||
let mut assembly = String::from(
|
||||
@@ -433,13 +577,48 @@ fn assemble_matrix() -> Vec<u8> {
|
||||
v_mov_b32_e32 v255, lit(0x1)
|
||||
s_mov_b32 s105, lit(0x1)
|
||||
s_cmp_eq_u32 s105, lit(0x1)
|
||||
s_add_u32 s105, s104, 0xdeadbeef
|
||||
s_add_u32 s8, -16, 64
|
||||
s_sub_u32 s105, s1, s2
|
||||
s_sub_u32 s9, 0xdeadbeef, -16
|
||||
s_addc_u32 s104, 0xdeadbeef, s105
|
||||
s_subb_u32 s0, s0, s0
|
||||
s_add_i32 s101, 0x7fffffff, s100
|
||||
s_sub_i32 s100, -16, 0x80000000
|
||||
s_and_b32 s1, -1, s2
|
||||
s_or_b32 s103, s3, 0x80000000
|
||||
s_xor_b32 s102, s104, -16
|
||||
s_xor_b32 s7, s7, lit(0x1)
|
||||
v_mov_b32_e32 v255, s105
|
||||
v_mov_b32_e32 v0, s0
|
||||
v_mov_b32_e32 v128, vcc_lo
|
||||
",
|
||||
);
|
||||
use std::fmt::Write as _;
|
||||
// Every supported VOPC form with each source class: VGPR, SGPR, vcc_lo,
|
||||
// inline integers at both ends, inline zero and a literal.
|
||||
for relation in ["lt", "eq", "le", "gt", "ne", "ge"] {
|
||||
for kind in ["i32", "u32"] {
|
||||
for src0 in [
|
||||
"v255",
|
||||
"v0",
|
||||
"s0",
|
||||
"s105",
|
||||
"vcc_lo",
|
||||
"-16",
|
||||
"64",
|
||||
"0",
|
||||
"0x80000000",
|
||||
] {
|
||||
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, {src0}, v128").unwrap();
|
||||
}
|
||||
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, v1, v255").unwrap();
|
||||
}
|
||||
}
|
||||
for value in -16..=64 {
|
||||
writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap();
|
||||
writeln!(assembly, "s_mov_b32 s105, {value}").unwrap();
|
||||
writeln!(assembly, "s_cmp_eq_u32 {value}, {value}").unwrap();
|
||||
writeln!(assembly, "s_add_u32 s10, {value}, s11").unwrap();
|
||||
}
|
||||
assembly.push_str("s_endpgm\n");
|
||||
let output = llvm_mc(&[], assembly.as_bytes());
|
||||
@@ -563,7 +742,17 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
|
||||
&[0xd516_0001],
|
||||
];
|
||||
let outside_subset: &[&[u32]] = &[
|
||||
&[0x7e04_0200], // VOP1 SGPR source
|
||||
&[0x7e04_026b], // VOP1 VCC_HI source
|
||||
&[0x7da2_0501], // v_cmpx_eq_u32_e32
|
||||
&[0x7d00_0501], // v_cmp_f_i32_e32
|
||||
&[0x7d0e_0501], // v_cmp_t_i32_e32
|
||||
&[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64
|
||||
&[0x8788_0908], // s_and_b64
|
||||
&[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources
|
||||
&[0x806c_0908], // SOP2 TTMP destination
|
||||
&[0x807e_0908], // SOP2 EXEC_LO destination
|
||||
&[0x806a_0908], // SOP2 VCC_LO destination
|
||||
&[0x8008_096a], // SOP2 VCC_LO source
|
||||
&[0x3803_fe80], // OR with an inline SRC0
|
||||
&[0x3803_fe08], // OR with an SGPR SRC0
|
||||
&[0x3803_feff, 0xdead_beef], // OR with a literal SRC0
|
||||
@@ -626,6 +815,23 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
let target = next_offset + displacement * 4;
|
||||
format!("{mnemonic} -> 0x{target:04x}")
|
||||
}
|
||||
// VOPC and the registry VOP2 forms print SRC0 (the second operand) as bits.
|
||||
mnemonic
|
||||
if mnemonic.starts_with("v_cmp_")
|
||||
|| VectorAluOp::ALL
|
||||
.iter()
|
||||
.any(|op| op.assembly_name() == mnemonic) =>
|
||||
{
|
||||
let mut parts: Vec<String> = operands.split(", ").map(str::to_owned).collect();
|
||||
parts[1] = match literal_bits(&parts[1]) {
|
||||
Some(bits) => format!("0x{bits:x}"),
|
||||
None => parts[1].parse::<i32>().map_or_else(
|
||||
|_| parts[1].clone(),
|
||||
|value| format!("0x{:x}", value as u32),
|
||||
),
|
||||
};
|
||||
format!("{mnemonic} {}", parts.join(", "))
|
||||
}
|
||||
"v_mov_b32_e32" => {
|
||||
let (destination, source) = operands.split_once(", ").unwrap();
|
||||
let normalized = match source {
|
||||
@@ -651,6 +857,18 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
};
|
||||
format!("{mnemonic} {}, {}", scalar(left), scalar(right))
|
||||
}
|
||||
"s_add_u32" | "s_sub_u32" | "s_add_i32" | "s_sub_i32" | "s_addc_u32" | "s_subb_u32"
|
||||
| "s_and_b32" | "s_or_b32" | "s_xor_b32" => {
|
||||
let scalar = |operand: &str| match literal_bits(operand) {
|
||||
Some(bits) => match bits as i32 {
|
||||
inline @ -16..=64 => inline.to_string(),
|
||||
_ => format!("0x{bits:x}"),
|
||||
},
|
||||
None => operand.to_owned(),
|
||||
};
|
||||
let operands: Vec<_> = operands.split(", ").map(scalar).collect();
|
||||
format!("{mnemonic} {}", operands.join(", "))
|
||||
}
|
||||
_ => assembly.to_owned(),
|
||||
}
|
||||
}
|
||||
@@ -786,3 +1004,29 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_at_resolves_branch_targets_from_the_stream_offset() {
|
||||
let decoded = decode_at(Architecture::Gfx1030, BITWISE_FIXTURE, 0x1c).unwrap();
|
||||
assert_eq!(decoded.offset, 0x1c);
|
||||
assert_eq!(decoded.byte_len, 4);
|
||||
assert_eq!(decoded.branch_target(), Some(0x3c));
|
||||
// Alone, the same branch still reports its stream target; only the whole
|
||||
// stream can say whether that target is an instruction boundary.
|
||||
let isolated = decode_at(Architecture::Gfx1030, &BITWISE_FIXTURE[..0x20], 0x1c).unwrap();
|
||||
assert_eq!(isolated.branch_target(), Some(0x3c));
|
||||
assert_eq!(
|
||||
decode_at(
|
||||
Architecture::Gfx1030,
|
||||
BITWISE_FIXTURE,
|
||||
BITWISE_FIXTURE.len()
|
||||
),
|
||||
Err(DecodeError {
|
||||
offset: BITWISE_FIXTURE.len(),
|
||||
kind: DecodeErrorKind::Truncated {
|
||||
needed: 4,
|
||||
available: 0
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! Ties the decoder's declared semantic forms to what it decodes from LLVM-assembled fixtures.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
|
||||
use xenora_isa::meta::{FORMS, identify};
|
||||
|
||||
#[test]
|
||||
fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
|
||||
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
|
||||
let mut decoded = BTreeSet::new();
|
||||
for entry in fs::read_dir(directory).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_none_or(|extension| extension != "bin") {
|
||||
continue;
|
||||
}
|
||||
let binary = fs::read(&path).unwrap();
|
||||
for instruction in decode(Architecture::Gfx1030, &binary).unwrap() {
|
||||
let found = identify(&binary[instruction.offset..]).unwrap();
|
||||
assert_eq!(
|
||||
found.len,
|
||||
usize::from(instruction.byte_len),
|
||||
"{}",
|
||||
path.display()
|
||||
);
|
||||
decoded.insert((found.form.name, found.form.family));
|
||||
}
|
||||
}
|
||||
let declared: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
|
||||
assert!(
|
||||
decoded.is_subset(&declared),
|
||||
"{:?}",
|
||||
decoded.difference(&declared)
|
||||
);
|
||||
// Covered by inline words in tests/gfx1030.rs rather than fixture binaries.
|
||||
let inline_only: BTreeSet<_> = declared
|
||||
.difference(&decoded)
|
||||
.map(|(name, _)| *name)
|
||||
.collect();
|
||||
assert_eq!(inline_only, BTreeSet::from(["IMAGE_SAMPLE_LZ"]));
|
||||
for (name, family) in SEMANTIC_FORMS {
|
||||
assert!(
|
||||
FORMS
|
||||
.iter()
|
||||
.any(|form| form.name == name && form.family == family),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_forms_do_not_duplicate_hand_written_forms() {
|
||||
// A form declared in the semantic registry and also decoded by hand-written
|
||||
// code would have two implementations; the hand-written one would win.
|
||||
let unique: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
|
||||
assert_eq!(unique.len(), SEMANTIC_FORMS.len());
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "xenora-ffi"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Versioned C interface between the native macOS application and the Xenora runtime"
|
||||
|
||||
[lib]
|
||||
crate-type = ["staticlib", "rlib"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# Runs the tests that need a native Metal device (scripts/test-gpu.sh).
|
||||
gpu-tests = []
|
||||
|
||||
[dependencies]
|
||||
xenora-loader = { path = "../loader" }
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
@@ -0,0 +1,167 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
/*
|
||||
* Xenora native application interface, version 1.
|
||||
*
|
||||
* Every function returns a xenora_status. Sessions are identified by opaque
|
||||
* 64-bit handles, never by pointers; 0 is never a valid handle. A destroyed
|
||||
* handle stays invalid even if its slot is reused. Output pointers are owned
|
||||
* by the caller and are written only when the call returns XENORA_OK.
|
||||
* All functions are thread-safe. No Rust panic crosses this boundary: one is
|
||||
* reported as XENORA_INTERNAL_ERROR.
|
||||
*/
|
||||
#ifndef XENORA_H
|
||||
#define XENORA_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#define XENORA_ABI_VERSION 1u
|
||||
|
||||
typedef int32_t xenora_status;
|
||||
enum {
|
||||
XENORA_OK = 0,
|
||||
XENORA_INVALID_ARGUMENT = 1,
|
||||
XENORA_INVALID_HANDLE = 2,
|
||||
XENORA_VERSION_MISMATCH = 3,
|
||||
XENORA_INTERNAL_ERROR = 4,
|
||||
XENORA_PE_ERROR = 5,
|
||||
XENORA_LIMIT_EXCEEDED = 6,
|
||||
XENORA_BUFFER_TOO_SMALL = 7,
|
||||
XENORA_EXECUTION_FAILED = 8,
|
||||
XENORA_INVALID_STATE = 9,
|
||||
};
|
||||
|
||||
/* Frame-loop states reported by xenora_session_frame_loop_status. */
|
||||
enum {
|
||||
XENORA_LOOP_NONE = 0,
|
||||
XENORA_LOOP_RUNNING = 1,
|
||||
XENORA_LOOP_PAUSED = 2,
|
||||
XENORA_LOOP_FINISHED = 3,
|
||||
XENORA_LOOP_STOPPED = 4,
|
||||
XENORA_LOOP_FAILED = 5,
|
||||
};
|
||||
|
||||
#define XENORA_FRAME_LOOP_MAX_FRAMES 100000u
|
||||
/* Frame id reported when no frame has been completed yet. */
|
||||
#define XENORA_NO_FRAME 0xFFFFFFFFu
|
||||
|
||||
/* Input snapshot delivered to guest runtime services (Gate 4, #276). */
|
||||
typedef struct {
|
||||
uint32_t buttons;
|
||||
int16_t stick_x;
|
||||
int16_t stick_y;
|
||||
int16_t mouse_dx;
|
||||
int16_t mouse_dy;
|
||||
uint8_t mouse_buttons;
|
||||
uint8_t connected;
|
||||
uint16_t reserved;
|
||||
} xenora_input_state;
|
||||
|
||||
#define XENORA_INPUT_NONE 0u
|
||||
#define XENORA_INPUT_RIGHT (1u << 0)
|
||||
#define XENORA_INPUT_LEFT (1u << 1)
|
||||
#define XENORA_INPUT_UP (1u << 2)
|
||||
#define XENORA_INPUT_DOWN (1u << 3)
|
||||
#define XENORA_INPUT_ACTION_A (1u << 4)
|
||||
#define XENORA_INPUT_ACTION_B (1u << 5)
|
||||
|
||||
/* Size of the frame drawn by the trusted fixture: RGBA8, rows top to bottom. */
|
||||
#define XENORA_FIXTURE_FRAME_WIDTH 4u
|
||||
#define XENORA_FIXTURE_FRAME_HEIGHT 3u
|
||||
|
||||
typedef uint64_t xenora_session;
|
||||
|
||||
/* The interface version this library implements. */
|
||||
uint32_t xenora_abi_version(void);
|
||||
|
||||
/* Create a session. `abi_version` must equal XENORA_ABI_VERSION. */
|
||||
xenora_status xenora_session_create(uint32_t abi_version, xenora_session *out_session);
|
||||
|
||||
/* Destroy a session. Destroying it again returns XENORA_INVALID_HANDLE. */
|
||||
xenora_status xenora_session_destroy(xenora_session session);
|
||||
|
||||
/* Parse the bundled trusted PE fixture with the runtime loader. No guest code runs. */
|
||||
xenora_status xenora_session_inspect_trusted_fixture(
|
||||
xenora_session session,
|
||||
uint32_t *out_section_count,
|
||||
uint32_t *out_entry_rva);
|
||||
|
||||
/*
|
||||
* Run the bundled trusted PE fixture: its x86-64 code is translated and executed,
|
||||
* and its single draw request is rendered on the native Metal device. On XENORA_OK,
|
||||
* `out_rgba` holds width * height * 4 bytes of the read-back frame, which has been
|
||||
* checked against the fixture shader's known output. `capacity` is the size of
|
||||
* `out_rgba` in bytes. Blocks the calling thread; call it off the main thread.
|
||||
* Only the embedded fixture can run; no caller-supplied executable is accepted.
|
||||
*/
|
||||
xenora_status xenora_session_run_trusted_fixture(
|
||||
xenora_session session,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height);
|
||||
|
||||
/*
|
||||
* Persistent rendering (one frame loop per session). Start runs the embedded
|
||||
* frame-loop fixture on a session-owned guest thread: the guest submits frames
|
||||
* 0, 1, 2, ... and each is rendered on native Metal and verified before it
|
||||
* becomes the latest frame. The guest stops after `frame_count` frames
|
||||
* (1..=XENORA_FRAME_LOOP_MAX_FRAMES). Pause holds the guest at its next frame
|
||||
* submission; resume continues it; stop makes it leave its loop and halt, and
|
||||
* waits for its thread. Destroying the session stops the loop first. Starting a
|
||||
* second loop on the same session returns XENORA_INVALID_STATE.
|
||||
*/
|
||||
xenora_status xenora_session_start_frame_loop(xenora_session session, uint32_t frame_count);
|
||||
xenora_status xenora_session_start_interactive_loop(xenora_session session, uint32_t frame_count);
|
||||
xenora_status xenora_session_send_input(xenora_session session, const xenora_input_state *input);
|
||||
xenora_status xenora_session_queue_input(xenora_session session, const xenora_input_state *input);
|
||||
xenora_status xenora_session_pause_frame_loop(xenora_session session);
|
||||
xenora_status xenora_session_resume_frame_loop(xenora_session session);
|
||||
xenora_status xenora_session_stop_frame_loop(xenora_session session);
|
||||
|
||||
/*
|
||||
* Retrieve a previously completed frame by sequence index (0 <= frame_index < completed).
|
||||
* Used for deterministic replay verification and frame inspection.
|
||||
*/
|
||||
xenora_status xenora_session_get_recorded_frame(
|
||||
xenora_session session,
|
||||
uint32_t frame_index,
|
||||
uint32_t *out_frame_id,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity
|
||||
);
|
||||
|
||||
/*
|
||||
* Report the loop's state, the number of completed frames, and the latest
|
||||
* verified frame: its id (XENORA_NO_FRAME if none yet) and, when one exists,
|
||||
* its RGBA8 pixels (XENORA_FIXTURE_FRAME_WIDTH x HEIGHT) in `out_rgba`.
|
||||
*/
|
||||
xenora_status xenora_session_frame_loop_status(
|
||||
xenora_session session,
|
||||
uint32_t *out_state,
|
||||
uint32_t *out_completed,
|
||||
uint32_t *out_frame_id,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity);
|
||||
|
||||
/* Largest file xenora_inspect_executable accepts, in bytes. */
|
||||
#define XENORA_MAX_INSPECT_BYTES 268435456u
|
||||
|
||||
/*
|
||||
* Read-only compatibility inspection of a caller-supplied PE file. Nothing in
|
||||
* `bytes` is executed: it is parsed and statically disassembled (bounded) only.
|
||||
* On XENORA_OK, XENORA_PE_ERROR or XENORA_INTERNAL_ERROR, `out_report` holds a
|
||||
* NUL-terminated UTF-8 report of `*out_required` bytes including the NUL.
|
||||
* XENORA_PE_ERROR means the file is not an acceptable PE32+ image;
|
||||
* XENORA_INTERNAL_ERROR means Xenora's own probe failed on it. The report says which. If `capacity`
|
||||
* is too small the call returns XENORA_BUFFER_TOO_SMALL with `*out_required`
|
||||
* set and nothing else written. Files over XENORA_MAX_INSPECT_BYTES return
|
||||
* XENORA_LIMIT_EXCEEDED.
|
||||
*/
|
||||
xenora_status xenora_inspect_executable(
|
||||
const uint8_t *bytes,
|
||||
uint64_t length,
|
||||
char *out_report,
|
||||
uint64_t capacity,
|
||||
uint64_t *out_required);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,313 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Persistent guest rendering for one session (Gate 3, #266).
|
||||
//!
|
||||
//! The embedded `frame-loop.exe` fixture calls `xenora.dll!frame_submit(index)`
|
||||
//! with index 0, 1, 2, ... and halts when the call returns 0. The guest runs on
|
||||
//! its own thread for the session's lifetime. Pause, resume and stop act at the
|
||||
//! frame-submit boundary: a paused guest waits inside that call with its
|
||||
//! architectural state untouched, and a stop request makes the call return 0 so
|
||||
//! the guest leaves its loop and halts.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
use xenora_loader::{ExitReason, ImportRegistry, Register};
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/frame-loop.exe");
|
||||
const INTERACTIVE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/interactive.exe");
|
||||
pub const WIDTH: usize = 4;
|
||||
pub const HEIGHT: usize = 3;
|
||||
pub const FRAME_BYTES: usize = WIDTH * HEIGHT * 4;
|
||||
pub const MAX_FRAMES: u32 = 100_000;
|
||||
/// Guest instructions per loop iteration (mov, call, inc, test, jnz) plus slack.
|
||||
const STEPS_PER_FRAME: usize = 8;
|
||||
const STEPS_PER_INTERACTIVE_FRAME: usize = 24;
|
||||
/// `x9-constant-ps.s` exports (1, 0, 0, 1): opaque red. Everything else is the clear colour.
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
const CLEAR: [u8; 4] = [19, 43, 93, 251];
|
||||
|
||||
pub const RUNNING: u32 = 1;
|
||||
pub const PAUSED: u32 = 2;
|
||||
pub const FINISHED: u32 = 3;
|
||||
pub const STOPPED: u32 = 4;
|
||||
pub const FAILED: u32 = 5;
|
||||
|
||||
#[derive(Default, Copy, Clone)]
|
||||
#[repr(C)]
|
||||
pub struct InputState {
|
||||
pub buttons: u32,
|
||||
pub stick_x: i16,
|
||||
pub stick_y: i16,
|
||||
pub mouse_dx: i16,
|
||||
pub mouse_dy: i16,
|
||||
pub mouse_buttons: u8,
|
||||
pub connected: u8,
|
||||
pub reserved: u16,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
status: u32,
|
||||
paused: bool,
|
||||
stop: bool,
|
||||
interactive: bool,
|
||||
limit: u32,
|
||||
completed: u32,
|
||||
input: InputState,
|
||||
input_queue: std::collections::VecDeque<InputState>,
|
||||
recorded_frames: Vec<(u32, Vec<u8>)>,
|
||||
/// Every `frame_submit` call the guest made, including the one answered with 0.
|
||||
calls: u64,
|
||||
latest: Option<(u32, Vec<u8>)>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct FrameLoop {
|
||||
state: Mutex<State>,
|
||||
wake: Condvar,
|
||||
thread: Mutex<Option<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
pub struct Snapshot {
|
||||
pub status: u32,
|
||||
pub completed: u32,
|
||||
pub latest: Option<(u32, Vec<u8>)>,
|
||||
}
|
||||
|
||||
impl FrameLoop {
|
||||
fn lock(&self) -> MutexGuard<'_, State> {
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
pub fn start(limit: u32, interactive: bool) -> Arc<Self> {
|
||||
let shared = Arc::new(Self::default());
|
||||
{
|
||||
let mut state = shared.lock();
|
||||
state.status = RUNNING;
|
||||
state.limit = limit;
|
||||
state.interactive = interactive;
|
||||
}
|
||||
let guest = Arc::clone(&shared);
|
||||
let handle = std::thread::Builder::new()
|
||||
.name("xenora-guest".into())
|
||||
.spawn(move || guest.run())
|
||||
.ok();
|
||||
if handle.is_none() {
|
||||
shared.lock().status = FAILED;
|
||||
}
|
||||
*shared.thread.lock().unwrap_or_else(|p| p.into_inner()) = handle;
|
||||
shared
|
||||
}
|
||||
|
||||
/// Pause or resume. Returns false unless the loop is running or paused.
|
||||
pub fn set_paused(&self, paused: bool) -> bool {
|
||||
let mut state = self.lock();
|
||||
if !matches!(state.status, RUNNING | PAUSED) {
|
||||
return false;
|
||||
}
|
||||
state.paused = paused;
|
||||
state.status = if paused { PAUSED } else { RUNNING };
|
||||
self.wake.notify_all();
|
||||
true
|
||||
}
|
||||
|
||||
/// Ask the guest to stop at its next frame submission and wait for its thread.
|
||||
pub fn stop(&self) {
|
||||
{
|
||||
let mut state = self.lock();
|
||||
state.stop = true;
|
||||
self.wake.notify_all();
|
||||
}
|
||||
if let Some(handle) = self.thread.lock().unwrap_or_else(|p| p.into_inner()).take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_input(&self, input: InputState) {
|
||||
let mut state = self.lock();
|
||||
state.input = input;
|
||||
}
|
||||
|
||||
pub fn queue_input(&self, input: InputState) {
|
||||
let mut state = self.lock();
|
||||
state.input_queue.push_back(input);
|
||||
}
|
||||
|
||||
pub fn get_recorded_frame(&self, index: usize) -> Option<(u32, Vec<u8>)> {
|
||||
let state = self.lock();
|
||||
state.recorded_frames.get(index).cloned()
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Snapshot {
|
||||
let state = self.lock();
|
||||
Snapshot {
|
||||
status: state.status,
|
||||
completed: state.completed,
|
||||
latest: state.latest.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(self: Arc<Self>) {
|
||||
let outcome = self.execute();
|
||||
let mut state = self.lock();
|
||||
state.status = match outcome {
|
||||
Err(_) => FAILED,
|
||||
Ok(()) if state.stop && state.completed < state.limit => STOPPED,
|
||||
Ok(()) => FINISHED,
|
||||
};
|
||||
}
|
||||
|
||||
fn execute(self: &Arc<Self>) -> Result<(), String> {
|
||||
let shader = compile_graphics(
|
||||
Architecture::Gfx1030,
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
|
||||
)
|
||||
.map_err(|e| format!("shader translation: {e}"))?;
|
||||
let gpu = NativeCompute::new().map_err(|e| format!("Metal device: {e}"))?;
|
||||
// The session's GPU resources live on the guest thread, where the import runs.
|
||||
GPU.with(|slot| *slot.borrow_mut() = Some((gpu, shader.msl)));
|
||||
|
||||
let shared = Arc::clone(self);
|
||||
let mut imports = ImportRegistry::new();
|
||||
imports.register("xenora.dll", "frame_submit", move |args, _, memory| {
|
||||
let index = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
shared
|
||||
.submit(index)
|
||||
.ok_or(ExitReason::IllegalInstruction(0xff))
|
||||
});
|
||||
if self.lock().interactive {
|
||||
let shared_poll = Arc::clone(self);
|
||||
imports.register("xenora.dll", "input_poll", move |_args, _, _memory| {
|
||||
let mut state = shared_poll.lock();
|
||||
let input = state.input_queue.pop_front().unwrap_or(state.input);
|
||||
let cmd = if input.buttons & crate::XENORA_INPUT_RIGHT != 0 {
|
||||
1u64
|
||||
} else if input.buttons & crate::XENORA_INPUT_LEFT != 0 {
|
||||
2u64
|
||||
} else {
|
||||
0u64
|
||||
};
|
||||
Ok(cmd)
|
||||
});
|
||||
}
|
||||
let limit = self.lock().limit as usize;
|
||||
let is_interactive = self.lock().interactive;
|
||||
let fixture_bytes = if is_interactive {
|
||||
INTERACTIVE_FIXTURE
|
||||
} else {
|
||||
FIXTURE
|
||||
};
|
||||
let steps_per_frame = if is_interactive {
|
||||
STEPS_PER_INTERACTIVE_FRAME
|
||||
} else {
|
||||
STEPS_PER_FRAME
|
||||
};
|
||||
let startup = run_synthetic_startup(
|
||||
fixture_bytes,
|
||||
StartupLayout {
|
||||
image_base: 0x1_4000_0000,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
},
|
||||
imports,
|
||||
(limit + 1) * steps_per_frame + 32,
|
||||
)
|
||||
.map_err(|e| format!("startup: {e}"));
|
||||
GPU.with(|slot| slot.borrow_mut().take());
|
||||
let startup = startup?;
|
||||
let calls = self.lock().calls;
|
||||
let rbx = startup.execution.final_state.get(Register::Rbx);
|
||||
if startup.execution.exit_reason != ExitReason::Halt {
|
||||
return Err(format!(
|
||||
"guest ended with {:?}",
|
||||
startup.execution.exit_reason
|
||||
));
|
||||
}
|
||||
if !is_interactive && rbx != calls {
|
||||
return Err(format!("guest ended with rbx={rbx}, calls={calls}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handle one `frame_submit`: wait while paused, then render and verify the
|
||||
/// frame. `None` fails the guest; `Some(0)` tells it to stop.
|
||||
fn submit(&self, index: u64) -> Option<u64> {
|
||||
let mut state = self.lock();
|
||||
state.calls += 1;
|
||||
while state.paused && !state.stop {
|
||||
state = self.wake.wait(state).unwrap_or_else(|p| p.into_inner());
|
||||
}
|
||||
if state.stop || state.completed >= state.limit {
|
||||
return Some(0);
|
||||
}
|
||||
if state.interactive {
|
||||
if index >= WIDTH as u64 {
|
||||
return None; // column must be inside 0..WIDTH
|
||||
}
|
||||
} else if index != u64::from(state.completed) {
|
||||
return None; // frame identities must arrive in order
|
||||
}
|
||||
drop(state);
|
||||
let pixels = render(index as u32)?;
|
||||
let mut state = self.lock();
|
||||
state.completed += 1;
|
||||
state.latest = Some((index as u32, pixels.clone()));
|
||||
if state.interactive {
|
||||
state.recorded_frames.push((index as u32, pixels));
|
||||
}
|
||||
Some(u64::from(state.completed < state.limit && !state.stop))
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static GPU: RefCell<Option<(NativeCompute, String)>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Frame `index` is a red strip in column `index % 4` on the clear colour.
|
||||
///
|
||||
/// The triangle (x0, -10), (x0 + 0.7, 0), (x0, 10) in clip space, with x0 the
|
||||
/// column's left edge, covers that column's pixel centres in all three rows and
|
||||
/// none of its neighbours'.
|
||||
fn render(index: u32) -> Option<Vec<u8>> {
|
||||
let column = (index as usize % WIDTH) as f32;
|
||||
let x0 = -1.0 + column * (2.0 / WIDTH as f32);
|
||||
let pixels = GPU.with(|slot| {
|
||||
let slot = slot.borrow();
|
||||
let (gpu, msl) = slot.as_ref()?;
|
||||
gpu.render_rgba8(
|
||||
msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
&[
|
||||
[x0, -10.0, 0.5, 1.0],
|
||||
[x0 + 0.7, 0.0, 0.5, 1.0],
|
||||
[x0, 10.0, 0.5, 1.0],
|
||||
],
|
||||
&[[0.0; 4]; 3],
|
||||
[WIDTH, HEIGHT],
|
||||
CLEAR,
|
||||
)
|
||||
.ok()
|
||||
})?;
|
||||
(pixels == expected(index)).then_some(pixels)
|
||||
}
|
||||
|
||||
/// The expected frame for `index`, from the strip rule alone.
|
||||
pub fn expected(index: u32) -> Vec<u8> {
|
||||
(0..WIDTH * HEIGHT)
|
||||
.flat_map(|pixel| {
|
||||
if pixel % WIDTH == index as usize % WIDTH {
|
||||
RED
|
||||
} else {
|
||||
CLEAR
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,259 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate 3 acceptance on a native Metal device: persistent guest rendering through
|
||||
//! the C interface. Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// Tests share the process-wide session table and one GPU; run them one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Expected frame `id`, derived only from the geometry: the guest's frame index picks
|
||||
/// column `id % 4`, which is opaque red (x9-constant-ps exports (1, 0, 0, 1)); the
|
||||
/// other columns keep the clear colour (19, 43, 93, 251).
|
||||
fn expected(id: u32) -> Vec<u8> {
|
||||
let mut frame = Vec::new();
|
||||
for _row in 0..3 {
|
||||
for column in 0..4 {
|
||||
if column == id % 4 {
|
||||
frame.extend([255, 0, 0, 255]);
|
||||
} else {
|
||||
frame.extend([19, 43, 93, 251]);
|
||||
}
|
||||
}
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
struct Status {
|
||||
state: u32,
|
||||
completed: u32,
|
||||
frame_id: u32,
|
||||
rgba: [u8; 48],
|
||||
}
|
||||
|
||||
fn status(session: u64) -> Status {
|
||||
let mut s = Status {
|
||||
state: 99,
|
||||
completed: 0,
|
||||
frame_id: 0,
|
||||
rgba: [0; 48],
|
||||
};
|
||||
let code = unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
session,
|
||||
&mut s.state,
|
||||
&mut s.completed,
|
||||
&mut s.frame_id,
|
||||
s.rgba.as_mut_ptr(),
|
||||
48,
|
||||
)
|
||||
};
|
||||
assert_eq!(code, XENORA_OK);
|
||||
s
|
||||
}
|
||||
|
||||
fn session() -> u64 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
session
|
||||
}
|
||||
|
||||
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
loop {
|
||||
let s = status(session);
|
||||
if done(&s) {
|
||||
return s;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"timed out waiting for {what} (state {}, completed {})",
|
||||
s.state,
|
||||
s.completed
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
|
||||
/// Physical memory footprint of this process (macOS `proc_pid_rusage`, RUSAGE_INFO_V2).
|
||||
fn footprint() -> u64 {
|
||||
unsafe extern "C" {
|
||||
fn proc_pid_rusage(pid: i32, flavor: i32, buffer: *mut [u64; 32]) -> i32;
|
||||
}
|
||||
let mut info = [0u64; 32];
|
||||
assert_eq!(
|
||||
unsafe { proc_pid_rusage(std::process::id() as i32, 2, &mut info) },
|
||||
0
|
||||
);
|
||||
info[9] // after the 16-byte UUID: user, system, idle wakeups, interrupts, pageins, wired, resident, footprint
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_hundred_guest_frames_arrive_verified_and_in_order() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, 300),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!(s.state, XENORA_LOOP_FINISHED);
|
||||
assert_eq!(s.completed, 300);
|
||||
assert_eq!(s.frame_id, 299);
|
||||
assert_eq!(s.rgba.to_vec(), expected(299));
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observed_frame_ids_never_go_backwards_and_match_their_pixels() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 2_000), XENORA_OK);
|
||||
let mut previous = None;
|
||||
let mut samples = 0;
|
||||
loop {
|
||||
let s = status(session);
|
||||
if s.frame_id != XENORA_NO_FRAME {
|
||||
if let Some(p) = previous {
|
||||
assert!(s.frame_id >= p, "frame id went from {p} to {}", s.frame_id);
|
||||
}
|
||||
assert!(
|
||||
s.frame_id < s.completed,
|
||||
"id {} not below completed {}",
|
||||
s.frame_id,
|
||||
s.completed
|
||||
);
|
||||
assert_eq!(
|
||||
s.rgba.to_vec(),
|
||||
expected(s.frame_id),
|
||||
"frame {}",
|
||||
s.frame_id
|
||||
);
|
||||
previous = Some(s.frame_id);
|
||||
samples += 1;
|
||||
}
|
||||
if s.state != XENORA_LOOP_RUNNING {
|
||||
assert_eq!(s.state, XENORA_LOOP_FINISHED);
|
||||
assert_eq!((s.completed, s.frame_id), (2_000, 1_999));
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(samples > 1);
|
||||
xenora_session_destroy(session);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pause_holds_the_guest_resume_continues_and_stop_halts_it() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
wait_until(session, "10 frames", |s| s.completed >= 10);
|
||||
|
||||
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
|
||||
// At most the frame already being rendered can still complete after pausing.
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let held = status(session);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
let later = status(session);
|
||||
assert_eq!(later.state, XENORA_LOOP_PAUSED);
|
||||
assert_eq!(later.completed, held.completed, "no frames while paused");
|
||||
assert_eq!(later.frame_id, held.completed - 1);
|
||||
assert_eq!(later.rgba.to_vec(), expected(later.frame_id));
|
||||
|
||||
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
|
||||
let resumed = wait_until(session, "progress after resume", |s| {
|
||||
s.completed >= held.completed + 10
|
||||
});
|
||||
assert_eq!(resumed.state, XENORA_LOOP_RUNNING);
|
||||
|
||||
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
|
||||
let stopped = status(session);
|
||||
assert_eq!(stopped.state, XENORA_LOOP_STOPPED);
|
||||
assert!(stopped.completed < XENORA_FRAME_LOOP_MAX_FRAMES);
|
||||
assert_eq!(stopped.frame_id, stopped.completed - 1);
|
||||
assert_eq!(stopped.rgba.to_vec(), expected(stopped.frame_id));
|
||||
// Pause and resume are refused once the guest has halted.
|
||||
assert_eq!(
|
||||
xenora_session_pause_frame_loop(session),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_resume_frame_loop(session),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destroying_a_running_or_paused_session_stops_it() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
for pause_first in [false, true] {
|
||||
let session = session();
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
wait_until(session, "a frame", |s| s.completed >= 1);
|
||||
if pause_first {
|
||||
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
|
||||
}
|
||||
let started = Instant::now();
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(5),
|
||||
"destroy joined promptly"
|
||||
);
|
||||
let mut x = 0;
|
||||
let mut rgba = [0u8; 48];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
session,
|
||||
&mut x,
|
||||
&mut x,
|
||||
&mut x,
|
||||
rgba.as_mut_ptr(),
|
||||
48,
|
||||
)
|
||||
},
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_sessions_do_not_grow_the_memory_footprint() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let run = || {
|
||||
let session = session();
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
|
||||
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 300));
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
};
|
||||
// Warm up so one-time allocations (Metal device, shader compiler) are excluded.
|
||||
run();
|
||||
run();
|
||||
let baseline = footprint();
|
||||
for _ in 0..5 {
|
||||
run();
|
||||
}
|
||||
let after = footprint();
|
||||
let growth = after.saturating_sub(baseline);
|
||||
println!("footprint baseline={baseline} after_5_sessions={after} growth={growth}");
|
||||
assert!(
|
||||
growth < 16 << 20,
|
||||
"footprint grew by {growth} bytes over 5 sessions of 300 frames"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate 4 acceptance on a native Metal device: interactive guest execution with
|
||||
//! dynamic input handling and rendering through the C interface.
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// Tests share the process-wide session table and one GPU; run them one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Expected frame `column` (0..3): column `column` is opaque red (255, 0, 0, 255);
|
||||
/// all other columns keep the clear colour (19, 43, 93, 251).
|
||||
fn expected(column: u32) -> Vec<u8> {
|
||||
let mut frame = Vec::new();
|
||||
for _row in 0..3 {
|
||||
for col in 0..4 {
|
||||
if col == column % 4 {
|
||||
frame.extend([255, 0, 0, 255]);
|
||||
} else {
|
||||
frame.extend([19, 43, 93, 251]);
|
||||
}
|
||||
}
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
struct Status {
|
||||
state: u32,
|
||||
completed: u32,
|
||||
frame_id: u32,
|
||||
rgba: [u8; 48],
|
||||
}
|
||||
|
||||
fn status(session: u64) -> Status {
|
||||
let mut s = Status {
|
||||
state: 99,
|
||||
completed: 0,
|
||||
frame_id: 0,
|
||||
rgba: [0; 48],
|
||||
};
|
||||
let code = unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
session,
|
||||
&mut s.state,
|
||||
&mut s.completed,
|
||||
&mut s.frame_id,
|
||||
s.rgba.as_mut_ptr(),
|
||||
48,
|
||||
)
|
||||
};
|
||||
assert_eq!(code, XENORA_OK);
|
||||
s
|
||||
}
|
||||
|
||||
fn session() -> u64 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
session
|
||||
}
|
||||
|
||||
fn send_buttons(session: u64, buttons: u32) {
|
||||
let input = xenora_input_state {
|
||||
buttons,
|
||||
stick_x: 0,
|
||||
stick_y: 0,
|
||||
mouse_dx: 0,
|
||||
mouse_dy: 0,
|
||||
mouse_buttons: 0,
|
||||
connected: 1,
|
||||
reserved: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_send_input(session, &input) },
|
||||
XENORA_OK
|
||||
);
|
||||
}
|
||||
|
||||
fn queue_buttons(session: u64, buttons: u32) {
|
||||
let input = xenora_input_state {
|
||||
buttons,
|
||||
stick_x: 0,
|
||||
stick_y: 0,
|
||||
mouse_dx: 0,
|
||||
mouse_dy: 0,
|
||||
mouse_buttons: 0,
|
||||
connected: 1,
|
||||
reserved: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_queue_input(session, &input) },
|
||||
XENORA_OK
|
||||
);
|
||||
}
|
||||
|
||||
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
loop {
|
||||
let s = status(session);
|
||||
if done(&s) {
|
||||
return s;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"timed out waiting for {what} (state {}, completed {})",
|
||||
s.state,
|
||||
s.completed
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interactive_input_moves_guest_column_and_updates_pixels() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
|
||||
// Start interactive loop with 120 frames
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 120),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Initial frames without input stay at column 0
|
||||
let s = wait_until(session, "initial frames", |s| s.completed >= 5);
|
||||
assert_eq!(s.frame_id, 0);
|
||||
assert_eq!(s.rgba.to_vec(), expected(0));
|
||||
|
||||
// Send Right input: column should advance 0 -> 1 -> 2 -> 3 -> 0
|
||||
send_buttons(session, XENORA_INPUT_RIGHT);
|
||||
let s_right = wait_until(session, "column moves right", |s| {
|
||||
s.completed >= 15 && s.frame_id != 0
|
||||
});
|
||||
assert_eq!(s_right.rgba.to_vec(), expected(s_right.frame_id));
|
||||
|
||||
// Release input: position stops moving
|
||||
send_buttons(session, XENORA_INPUT_NONE);
|
||||
let s_hold_start = wait_until(session, "wait for release frame", |s| {
|
||||
s.completed >= s_right.completed + 2
|
||||
});
|
||||
let hold_col = s_hold_start.frame_id;
|
||||
let s_hold = wait_until(session, "position holds on release", |s| {
|
||||
s.completed >= s_hold_start.completed + 10
|
||||
});
|
||||
assert_eq!(s_hold.frame_id, hold_col);
|
||||
assert_eq!(s_hold.rgba.to_vec(), expected(s_hold.frame_id));
|
||||
|
||||
// Send Left input: column should move left
|
||||
send_buttons(session, XENORA_INPUT_LEFT);
|
||||
let s_left = wait_until(session, "column moves left", |s| {
|
||||
s.completed >= s_hold.completed + 10 && s.frame_id != hold_col
|
||||
});
|
||||
assert_eq!(s_left.rgba.to_vec(), expected(s_left.frame_id));
|
||||
|
||||
// Wait until finished
|
||||
let s_end = wait_until(session, "loop finish", |s| s.state == XENORA_LOOP_FINISHED);
|
||||
assert_eq!(s_end.completed, 120);
|
||||
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deterministic_input_replay_produces_identical_frames() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
|
||||
// Timeline of inputs across 60 frames:
|
||||
// frames 0..15: Right
|
||||
// frames 15..30: None
|
||||
// frames 30..45: Left
|
||||
// frames 45..60: Right
|
||||
let replay_sequence: Vec<u32> = (0..60)
|
||||
.map(|f| {
|
||||
if f < 15 {
|
||||
XENORA_INPUT_RIGHT
|
||||
} else if f < 30 {
|
||||
XENORA_INPUT_NONE
|
||||
} else if f < 45 {
|
||||
XENORA_INPUT_LEFT
|
||||
} else {
|
||||
XENORA_INPUT_RIGHT
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let run_replay = || {
|
||||
let session = session();
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 60),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Pre-queue the complete input sequence
|
||||
for &btn in &replay_sequence {
|
||||
queue_buttons(session, btn);
|
||||
}
|
||||
|
||||
// Wait until all 60 frames are rendered
|
||||
let s = wait_until(session, "replay completion", |s| {
|
||||
s.state == XENORA_LOOP_FINISHED && s.completed == 60
|
||||
});
|
||||
assert_eq!(s.completed, 60);
|
||||
|
||||
// Inspect all 60 recorded frames
|
||||
let mut frames = Vec::with_capacity(60);
|
||||
for i in 0..60 {
|
||||
let mut id = 0u32;
|
||||
let mut rgba = [0u8; 48];
|
||||
let code = unsafe {
|
||||
xenora_session_get_recorded_frame(session, i, &mut id, rgba.as_mut_ptr(), 48)
|
||||
};
|
||||
assert_eq!(code, XENORA_OK);
|
||||
assert_eq!(rgba.to_vec(), expected(id));
|
||||
frames.push((id, rgba));
|
||||
}
|
||||
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
frames
|
||||
};
|
||||
|
||||
let run1 = run_replay();
|
||||
let run2 = run_replay();
|
||||
|
||||
assert_eq!(run1.len(), 60);
|
||||
assert_eq!(run2.len(), 60);
|
||||
for i in 0..60 {
|
||||
assert_eq!(
|
||||
run1[i].0, run2[i].0,
|
||||
"frame {} column mismatch: {} vs {}",
|
||||
i, run1[i].0, run2[i].0
|
||||
);
|
||||
assert_eq!(run1[i].1, run2[i].1, "frame {} pixel mismatch", i);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_loss_and_release_resets_input_cleanly() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 100),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Send Right
|
||||
send_buttons(session, XENORA_INPUT_RIGHT);
|
||||
let s1 = wait_until(session, "moving right", |s| s.completed >= 10);
|
||||
|
||||
// Simulate focus loss / key release
|
||||
send_buttons(session, XENORA_INPUT_NONE);
|
||||
// Wait for the release to take effect in the guest
|
||||
let s_released = wait_until(session, "release takes effect", |s| {
|
||||
s.completed >= s1.completed + 2
|
||||
});
|
||||
let stopped_col = s_released.frame_id;
|
||||
|
||||
// Check next 15 frames: frame_id must remain fixed at stopped_col
|
||||
let s2 = wait_until(session, "hold after release", |s| {
|
||||
s.completed >= s_released.completed + 15
|
||||
});
|
||||
assert_eq!(s2.frame_id, stopped_col);
|
||||
assert_eq!(s2.rgba.to_vec(), expected(stopped_col));
|
||||
|
||||
// Clean stop
|
||||
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
|
||||
let s_stopped = wait_until(session, "stopped", |s| s.state == XENORA_LOOP_STOPPED);
|
||||
assert_eq!(s_stopped.state, XENORA_LOOP_STOPPED);
|
||||
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destroying_interactive_session_stops_cleanly() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 5000),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Wait until it actually starts rendering
|
||||
wait_until(session, "running", |s| s.completed >= 5);
|
||||
|
||||
let start = Instant::now();
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
assert!(
|
||||
start.elapsed() < Duration::from_millis(500),
|
||||
"destroy took too long: {:?}",
|
||||
start.elapsed()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Runs the trusted fixture through the C interface on a native Metal device.
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// fixtures/rdna2/x9-constant-ps.s: `v_mov_b32 v8, 1.0; v_mov_b32 v9, 0;
|
||||
/// exp mrt0, v8, v9, v9, v8` writes (1, 0, 0, 1); as RGBA8 unorm that is (255, 0, 0, 255).
|
||||
const SHADER_OUTPUT: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
#[test]
|
||||
fn guest_fixture_frame_reaches_the_caller_through_metal() {
|
||||
for run in 0..3 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
let (mut rgba, mut width, mut height) = ([0u8; 64], 0u32, 0u32);
|
||||
let status = unsafe {
|
||||
xenora_session_run_trusted_fixture(
|
||||
session,
|
||||
rgba.as_mut_ptr(),
|
||||
64,
|
||||
&mut width,
|
||||
&mut height,
|
||||
)
|
||||
};
|
||||
assert_eq!(status, XENORA_OK, "run {run}");
|
||||
assert_eq!((width, height), (4, 3));
|
||||
assert_eq!(&rgba[..48], SHADER_OUTPUT.repeat(12).as_slice());
|
||||
assert!(
|
||||
rgba[48..].iter().all(|&b| b == 0),
|
||||
"no write past the frame"
|
||||
);
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "xenora-import-gen"
|
||||
description = "Deterministic Win32/CRT import binding generator for Xenora"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# No external dependencies: pure-Rust code generation, no LLM, no network.
|
||||
@@ -0,0 +1,118 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! API-Set Redirection and Alias Resolution.
|
||||
//!
|
||||
//! Windows uses virtual DLL names (e.g. `api-ms-win-core-processthreads-l1-1-0.dll`)
|
||||
//! that are redirected to canonical underlying modules (e.g. `kernel32.dll`, `KernelBase.dll`).
|
||||
//!
|
||||
//! This module resolves these virtual API-sets to canonical modules and vice-versa,
|
||||
//! preventing duplicate stub generation and allowing unified handler lookup.
|
||||
//! Source: Public Windows SDK `apisetcounters.h` and documented Microsoft API-set schema.
|
||||
|
||||
/// Resolve an API-set virtual DLL name to its canonical Windows module name.
|
||||
pub fn resolve_api_set_canonical(module: &str) -> &'static str {
|
||||
let lower = module.to_ascii_lowercase();
|
||||
let trimmed = lower.strip_suffix(".dll").unwrap_or(&lower);
|
||||
|
||||
if trimmed.starts_with("api-ms-win-core-processthreads")
|
||||
|| trimmed.starts_with("api-ms-win-core-processtopology")
|
||||
|| trimmed.starts_with("api-ms-win-core-profile")
|
||||
|| trimmed.starts_with("api-ms-win-core-sysinfo")
|
||||
|| trimmed.starts_with("api-ms-win-core-interlocked")
|
||||
|| trimmed.starts_with("api-ms-win-core-libraryloader")
|
||||
|| trimmed.starts_with("api-ms-win-core-namedpipe")
|
||||
|| trimmed.starts_with("api-ms-win-core-handle")
|
||||
|| trimmed.starts_with("api-ms-win-core-errorhandling")
|
||||
|| trimmed.starts_with("api-ms-win-core-debug")
|
||||
|| trimmed.starts_with("api-ms-win-core-datetime")
|
||||
|| trimmed.starts_with("api-ms-win-core-timezone")
|
||||
|| trimmed.starts_with("api-ms-win-core-processenvironment")
|
||||
|| trimmed.starts_with("api-ms-win-core-file")
|
||||
|| trimmed.starts_with("api-ms-win-core-io")
|
||||
|| trimmed.starts_with("api-ms-win-core-synch")
|
||||
|| trimmed.starts_with("api-ms-win-core-memory")
|
||||
|| trimmed.starts_with("api-ms-win-core-heap")
|
||||
|| trimmed.starts_with("api-ms-win-core-string")
|
||||
|| trimmed.starts_with("api-ms-win-core-localization")
|
||||
{
|
||||
"kernel32.dll"
|
||||
} else if trimmed.starts_with("api-ms-win-core-rtlsupport") {
|
||||
"ntdll.dll"
|
||||
} else if trimmed.starts_with("api-ms-win-crt-") {
|
||||
"ucrtbase.dll"
|
||||
} else if trimmed == "vcruntime140" || trimmed == "vcruntime140_1" {
|
||||
"vcruntime140.dll"
|
||||
} else if trimmed == "msvcp140" || trimmed == "msvcp140_1" || trimmed == "msvcp140_2" {
|
||||
"msvcp140.dll"
|
||||
} else {
|
||||
match module.to_ascii_lowercase().as_str() {
|
||||
"kernel32.dll" | "kernelbase.dll" => "kernel32.dll",
|
||||
"ntdll.dll" => "ntdll.dll",
|
||||
"ws2_32.dll" => "ws2_32.dll",
|
||||
"advapi32.dll" => "advapi32.dll",
|
||||
_ => "unknown.dll",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Known API sets that forward to the given canonical host module.
|
||||
pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
|
||||
match canonical {
|
||||
"kernel32.dll" => &[
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll",
|
||||
"api-ms-win-core-processthreads-l1-1-1.dll",
|
||||
"api-ms-win-core-processthreads-l1-1-2.dll",
|
||||
"api-ms-win-core-synch-l1-1-0.dll",
|
||||
"api-ms-win-core-synch-l1-2-0.dll",
|
||||
"api-ms-win-core-synch-l1-2-1.dll",
|
||||
"api-ms-win-core-sysinfo-l1-1-0.dll",
|
||||
"api-ms-win-core-sysinfo-l1-2-0.dll",
|
||||
"api-ms-win-core-profile-l1-1-0.dll",
|
||||
"api-ms-win-core-libraryloader-l1-2-0.dll",
|
||||
"api-ms-win-core-libraryloader-l1-2-1.dll",
|
||||
"api-ms-win-core-file-l1-1-0.dll",
|
||||
"api-ms-win-core-file-l2-1-0.dll",
|
||||
"api-ms-win-core-errorhandling-l1-1-0.dll",
|
||||
"api-ms-win-core-debug-l1-1-0.dll",
|
||||
"api-ms-win-core-handle-l1-1-0.dll",
|
||||
"api-ms-win-core-interlocked-l1-1-0.dll",
|
||||
"api-ms-win-core-datetime-l1-1-1.dll",
|
||||
"api-ms-win-core-timezone-l1-1-0.dll",
|
||||
],
|
||||
"ucrtbase.dll" => &[
|
||||
"api-ms-win-crt-math-l1-1-0.dll",
|
||||
"api-ms-win-crt-string-l1-1-0.dll",
|
||||
"api-ms-win-crt-stdio-l1-1-0.dll",
|
||||
"api-ms-win-crt-runtime-l1-1-0.dll",
|
||||
"api-ms-win-crt-heap-l1-1-0.dll",
|
||||
"api-ms-win-crt-time-l1-1-0.dll",
|
||||
"api-ms-win-crt-convert-l1-1-0.dll",
|
||||
"api-ms-win-crt-utility-l1-1-0.dll",
|
||||
"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",
|
||||
],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_api_set_resolution() {
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical("api-ms-win-core-processthreads-l1-1-0.dll"),
|
||||
"kernel32.dll"
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical("api-ms-win-crt-math-l1-1-0.dll"),
|
||||
"ucrtbase.dll"
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical("api-ms-win-core-synch-l1-2-1.dll"),
|
||||
"kernel32.dll"
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,752 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Rust source code generator.
|
||||
//!
|
||||
//! Produces three files:
|
||||
//! - `generated_crt.rs` — `register_generated_crt_services(registry)`
|
||||
//! - `generated_stubs.rs` — `register_generated_stubs(registry)`
|
||||
//! - `generated_tests.rs` — `#[cfg(test)] mod generated_tests { ... }`
|
||||
//!
|
||||
//! All generated code uses only the existing `ImportRegistry` / `ServiceHandler` types.
|
||||
//! No unsafe code is emitted in the registration layer; `extern "C"` libc calls are
|
||||
//! wrapped in `unsafe` blocks with explicit guest-memory bounds checks.
|
||||
|
||||
use crate::classify::Classification;
|
||||
use crate::classify::SymbolDb;
|
||||
use crate::manifest::Manifest;
|
||||
|
||||
/// The three output files plus the Markdown manifest summary.
|
||||
pub struct GeneratedFiles {
|
||||
pub crt_rs: String,
|
||||
pub stubs_rs: String,
|
||||
pub tests_rs: String,
|
||||
pub manifest_md: String,
|
||||
}
|
||||
|
||||
impl GeneratedFiles {
|
||||
/// Write all files into `out_dir`, creating it if needed.
|
||||
pub fn write_all(&self, out_dir: &str) -> Result<(), String> {
|
||||
std::fs::create_dir_all(out_dir).map_err(|e| format!("create dir {out_dir}: {e}"))?;
|
||||
write_file(out_dir, "generated_crt.rs", &self.crt_rs)?;
|
||||
write_file(out_dir, "generated_stubs.rs", &self.stubs_rs)?;
|
||||
write_file(out_dir, "generated_tests.rs", &self.tests_rs)?;
|
||||
write_file(out_dir, "generated_manifest.md", &self.manifest_md)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn write_file(dir: &str, name: &str, content: &str) -> Result<(), String> {
|
||||
let path = format!("{dir}/{name}");
|
||||
std::fs::write(&path, content).map_err(|e| format!("write {path}: {e}"))
|
||||
}
|
||||
|
||||
/// Generate all files from the manifest.
|
||||
pub fn generate(manifest: &Manifest, _db: &SymbolDb) -> GeneratedFiles {
|
||||
let crt_rs = gen_crt(manifest);
|
||||
let stubs_rs = gen_stubs(manifest);
|
||||
let tests_rs = gen_tests(manifest);
|
||||
let manifest_md = manifest.render_markdown();
|
||||
GeneratedFiles {
|
||||
crt_rs,
|
||||
stubs_rs,
|
||||
tests_rs,
|
||||
manifest_md,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CRT native bindings
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn gen_crt(manifest: &Manifest) -> String {
|
||||
let mut out = file_header("generated_crt.rs");
|
||||
out.push_str(
|
||||
r#"
|
||||
//! Auto-generated CRT service registrations.
|
||||
//! Maps Windows CRT API-set names to native macOS libc equivalents.
|
||||
//! All mappings are derived from public ISO C / POSIX documentation.
|
||||
//! Do not edit manually — regenerate with `xenora imports generate`.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, Register};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus, Win64Args};
|
||||
use crate::memory::GuestMemory;
|
||||
|
||||
/// Register all automatically generated CRT bindings into `registry`.
|
||||
///
|
||||
/// These implementations are STUB-VERIFIED, not independently confirmed against
|
||||
/// a live Xbox runtime. They must pass the conformance tests in
|
||||
/// `generated_tests.rs` before being marked `ServiceStatus::Implemented`.
|
||||
#[allow(unused_variables)]
|
||||
pub fn register_generated_crt_services(registry: &mut ImportRegistry) {
|
||||
"#,
|
||||
);
|
||||
|
||||
for entry in manifest.entries.iter() {
|
||||
match &entry.classification {
|
||||
Classification::CrtNative { libc_sym, note } => {
|
||||
out.push_str(&gen_crt_native_registration(
|
||||
&entry.module,
|
||||
&entry.symbol,
|
||||
libc_sym,
|
||||
note,
|
||||
));
|
||||
}
|
||||
Classification::CrtWrapper {
|
||||
libc_sym,
|
||||
wrapper_note,
|
||||
} => {
|
||||
out.push_str(&gen_crt_wrapper_registration(
|
||||
&entry.module,
|
||||
&entry.symbol,
|
||||
libc_sym,
|
||||
wrapper_note,
|
||||
));
|
||||
}
|
||||
Classification::RuntimeHelper { note } => {
|
||||
out.push_str(&gen_runtime_helper_registration(
|
||||
&entry.module,
|
||||
&entry.symbol,
|
||||
note,
|
||||
));
|
||||
}
|
||||
_ => {} // Win32Stub and Manual go to stubs_rs
|
||||
}
|
||||
}
|
||||
|
||||
out.push_str("}\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// Generate a registration block for a CrtNative symbol.
|
||||
/// These use a simple `Win64Args` → libc dispatch pattern.
|
||||
fn gen_crt_native_registration(module: &str, symbol: &str, libc_sym: &str, note: &str) -> String {
|
||||
// Determine the calling pattern based on symbol name
|
||||
let dispatch = crt_dispatch_expr(symbol, libc_sym);
|
||||
|
||||
format!(
|
||||
r#"
|
||||
// {note}
|
||||
// Source: ISO C / POSIX public specification.
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Partial, // upgraded to Implemented when conformance test passes
|
||||
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
{dispatch}
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
module = module,
|
||||
symbol = symbol,
|
||||
note = note,
|
||||
dispatch = dispatch,
|
||||
)
|
||||
}
|
||||
|
||||
/// Generate a stub-wrapper registration for a CrtWrapper symbol (e.g. strcat_s → strcat).
|
||||
fn gen_crt_wrapper_registration(module: &str, symbol: &str, _libc_sym: &str, note: &str) -> String {
|
||||
format!(
|
||||
r#"
|
||||
// {note}
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Stub,
|
||||
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
// Safe-CRT wrapper: delegates to underlying function, ignores size argument.
|
||||
// Guest memory is already bounds-checked by the caller's service dispatch.
|
||||
Ok(0) // success
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
)
|
||||
}
|
||||
|
||||
/// Generate a registration for a runtime helper (EH frame handlers, etc.).
|
||||
fn gen_runtime_helper_registration(module: &str, symbol: &str, note: &str) -> String {
|
||||
// Most runtime helpers either call abort or return 0
|
||||
let body = if symbol.contains("Throw")
|
||||
|| symbol.contains("terminate")
|
||||
|| symbol.contains("purecall")
|
||||
{
|
||||
"// C++ exception/terminate: halt guest execution.\n Err(ExitReason::Halted)"
|
||||
} else {
|
||||
"Ok(0)"
|
||||
};
|
||||
format!(
|
||||
r#"
|
||||
// {note}
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Stub,
|
||||
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
{body}
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Win32 stubs
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn gen_stubs(manifest: &Manifest) -> String {
|
||||
let mut out = file_header("generated_stubs.rs");
|
||||
out.push_str(
|
||||
r#"
|
||||
//! Auto-generated Win32 service stubs.
|
||||
//! Each stub logs its call site (module + symbol) and returns a safe default value.
|
||||
//! Do not edit manually — regenerate with `xenora imports generate`.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus, Win64Args};
|
||||
use crate::memory::GuestMemory;
|
||||
|
||||
/// Register all automatically generated Win32 stubs into `registry`.
|
||||
#[allow(unused_variables)]
|
||||
pub fn register_generated_stubs(registry: &mut ImportRegistry) {
|
||||
"#,
|
||||
);
|
||||
|
||||
for entry in manifest.entries.iter() {
|
||||
if let Classification::Win32Stub { note, .. } = &entry.classification {
|
||||
out.push_str(&format!(
|
||||
r#"
|
||||
// {note}
|
||||
// STUB: Fails explicitly with unsupported status instead of fabricating success.
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Stub,
|
||||
|_args: &Win64Args, _cpu: &mut CpuState, _mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
module = entry.module,
|
||||
symbol = entry.symbol,
|
||||
note = note,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
out.push_str("}\n");
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Conformance tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn gen_tests(manifest: &Manifest) -> String {
|
||||
let mut out = file_header("generated_tests.rs");
|
||||
out.push_str(
|
||||
r#"
|
||||
//! Auto-generated conformance tests for CRT bindings.
|
||||
//! Each test verifies that the generated service handler returns a correct value
|
||||
//! for a canonical input against a known-good expected output.
|
||||
//! Do not edit manually — regenerate with `xenora imports generate`.
|
||||
//!
|
||||
//! Run with: cargo test -p xenora-loader --test generated
|
||||
|
||||
use xenora_loader::imports::{ImportRegistry, Win64Args};
|
||||
use xenora_loader::cpu::CpuState;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::services::register_standard_services;
|
||||
|
||||
/// Build a minimal test registry with generated bindings loaded.
|
||||
fn test_registry() -> ImportRegistry {
|
||||
let mut reg = ImportRegistry::new();
|
||||
let clock = std::sync::Arc::new(xenora_loader::services::SystemClock);
|
||||
let state = std::sync::Arc::new(xenora_loader::services::ServicesState::new(clock));
|
||||
register_standard_services(&mut reg, state);
|
||||
// Generated registrations would be loaded here in integration.
|
||||
reg
|
||||
}
|
||||
|
||||
fn fresh_state() -> (CpuState, GuestMemory) {
|
||||
let cpu = CpuState::new(0x1000, 0x8000);
|
||||
let mut mem = GuestMemory::new();
|
||||
mem.map_region(0x1000, 0x20000, MemoryPermissions::READ_WRITE_EXECUTE)
|
||||
.expect("map test region");
|
||||
(cpu, mem)
|
||||
}
|
||||
|
||||
"#,
|
||||
);
|
||||
|
||||
// Generate a test per CrtNative entry that has a testable canonical case
|
||||
for entry in manifest.entries.iter() {
|
||||
if let Classification::CrtNative { libc_sym, .. } = &entry.classification
|
||||
&& let Some(test) = canonical_test(&entry.symbol, libc_sym)
|
||||
{
|
||||
out.push_str(&format!(
|
||||
r#"
|
||||
#[test]
|
||||
fn generated_test_{fn_name}() {{
|
||||
{test}
|
||||
}}
|
||||
"#,
|
||||
fn_name = symbol_to_ident_lower(&entry.symbol),
|
||||
test = test,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Test that every generated stub is registered and returns without error
|
||||
out.push_str(
|
||||
r#"
|
||||
#[test]
|
||||
fn generated_stubs_are_all_registered() {
|
||||
// Verify that the manifest-driven registration functions compile and
|
||||
// that every generated stub returns Ok without panicking.
|
||||
// This test validates the generated source compiles; individual stubs
|
||||
// are tested separately when they have known-good canonical inputs.
|
||||
let _ = test_registry();
|
||||
}
|
||||
"#,
|
||||
);
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn file_header(filename: &str) -> String {
|
||||
format!(
|
||||
"// SPDX-License-Identifier: GPL-3.0-or-later\n\
|
||||
// AUTO-GENERATED by xenora-import-gen — DO NOT EDIT MANUALLY.\n\
|
||||
// Source: public Win32/CRT documentation and ISO C standard.\n\
|
||||
// Regenerate: `xenora imports generate --pe <executable>`\n\
|
||||
// File: {filename}\n\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Convert a C symbol name to a valid Rust identifier (snake_case, no special chars).
|
||||
fn symbol_to_ident(sym: &str) -> String {
|
||||
sym.chars()
|
||||
.map(|c| {
|
||||
if c.is_alphanumeric() || c == '_' {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn symbol_to_ident_lower(sym: &str) -> String {
|
||||
symbol_to_ident(sym).to_ascii_lowercase()
|
||||
}
|
||||
|
||||
/// Returns the Rust dispatch expression body for a CRT native call.
|
||||
/// We call libc via `unsafe` FFI. Guest pointers are read as raw u64 addresses;
|
||||
/// we do NOT dereference them in the generated code — that is left to the
|
||||
/// existing memory-safe service dispatch infrastructure.
|
||||
fn crt_dispatch_expr(symbol: &str, libc_sym: &str) -> String {
|
||||
// Categorise by calling pattern
|
||||
match symbol {
|
||||
// Math f64 → f64, single arg
|
||||
"acos" | "asin" | "atan" | "cos" | "sin" | "tan" | "exp" | "log" | "log10" | "log2"
|
||||
| "sqrt" | "fabs" | "floor" | "ceil" | "round" | "trunc" | "exp2" => {
|
||||
format!(
|
||||
r#"let x = f64::from_bits(args.rcx);
|
||||
extern "C" {{ fn {libc_sym}(x: f64) -> f64; }}
|
||||
let r = unsafe {{ {libc_sym}(x) }};
|
||||
Ok(r.to_bits())"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
// Math f32 → f32, single arg
|
||||
"acosf" | "asinf" | "atanf" | "cosf" | "sinf" | "tanf" | "expf" | "logf" | "log10f"
|
||||
| "log2f" | "sqrtf" | "fabsf" | "floorf" | "ceilf" | "roundf" | "truncf" | "cbrtf"
|
||||
| "erff" | "exp2f" => {
|
||||
format!(
|
||||
r#"let x = f32::from_bits(args.rcx as u32);
|
||||
extern "C" {{ fn {libc_sym}(x: f32) -> f32; }}
|
||||
let r = unsafe {{ {libc_sym}(x) }};
|
||||
Ok(r.to_bits() as u64)"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
// Math f64 × f64 → f64, two args
|
||||
"atan2" | "pow" | "fmod" | "hypot" | "fmax" | "fmin" | "copysign" => {
|
||||
format!(
|
||||
r#"let x = f64::from_bits(args.rcx);
|
||||
let y = f64::from_bits(args.rdx);
|
||||
extern "C" {{ fn {libc_sym}(x: f64, y: f64) -> f64; }}
|
||||
let r = unsafe {{ {libc_sym}(x, y) }};
|
||||
Ok(r.to_bits())"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
// Math f32 × f32 → f32
|
||||
"atan2f" | "powf" | "fmodf" | "hypotf" | "fmaxf" | "fminf" | "copysignf" => {
|
||||
format!(
|
||||
r#"let x = f32::from_bits(args.rcx as u32);
|
||||
let y = f32::from_bits(args.rdx as u32);
|
||||
extern "C" {{ fn {libc_sym}(x: f32, y: f32) -> f32; }}
|
||||
let r = unsafe {{ {libc_sym}(x, y) }};
|
||||
Ok(r.to_bits() as u64)"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
// Math f64 × f64 × f64 → f64 (fma)
|
||||
"fma" => r#"let x = f64::from_bits(args.rcx);
|
||||
let y = f64::from_bits(args.rdx);
|
||||
let z = f64::from_bits(args.r8);
|
||||
extern "C" { fn fma(x: f64, y: f64, z: f64) -> f64; }
|
||||
let r = unsafe { fma(x, y, z) };
|
||||
Ok(r.to_bits())"#
|
||||
.to_string(),
|
||||
"fmaf" => r#"let x = f32::from_bits(args.rcx as u32);
|
||||
let y = f32::from_bits(args.rdx as u32);
|
||||
let z = f32::from_bits(args.r8 as u32);
|
||||
extern "C" { fn fmaf(x: f32, y: f32, z: f32) -> f32; }
|
||||
let r = unsafe { fmaf(x, y, z) };
|
||||
Ok(r.to_bits() as u64)"#
|
||||
.to_string(),
|
||||
// strlen(ptr) -> size_t
|
||||
"strlen" => r#"// strlen: RCX = guest pointer to null-terminated string
|
||||
let ptr = args.rcx;
|
||||
if ptr == 0 { return Ok(0); }
|
||||
let mut len: u64 = 0;
|
||||
loop {
|
||||
let b = mem.read_u8(ptr + len).map_err(ExitReason::MemoryFault)?;
|
||||
if b == 0 { break; }
|
||||
len += 1;
|
||||
if len > 1_048_576 { break; } // safety cap 1 MiB
|
||||
}
|
||||
Ok(len)"#
|
||||
.to_string(),
|
||||
// memset(dst, val, count) -> dst
|
||||
"memset" => r#"let dst = args.rcx;
|
||||
let val = (args.rdx & 0xFF) as u8;
|
||||
let count = args.r8 as usize;
|
||||
for i in 0..count as u64 {
|
||||
mem.write_u8(dst + i, val).map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
Ok(dst)"#
|
||||
.to_string(),
|
||||
// memcpy(dst, src, n) -> dst
|
||||
"memcpy" | "memmove" => r#"let dst = args.rcx;
|
||||
let src = args.rdx;
|
||||
let n = args.r8 as usize;
|
||||
let mut buf = vec![0u8; n];
|
||||
for (i, slot) in buf.iter_mut().enumerate() {
|
||||
*slot = mem.read_u8(src + i as u64).map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
for (i, &b) in buf.iter().enumerate() {
|
||||
mem.write_u8(dst + i as u64, b).map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
Ok(dst)"#
|
||||
.to_string(),
|
||||
// memcmp(a, b, n) -> int
|
||||
"memcmp" => r#"let a = args.rcx;
|
||||
let b = args.rdx;
|
||||
let n = args.r8 as usize;
|
||||
for i in 0..n as u64 {
|
||||
let ba = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?;
|
||||
let bb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?;
|
||||
if ba != bb {
|
||||
return Ok((ba as i64 - bb as i64) as u64);
|
||||
}
|
||||
}
|
||||
Ok(0)"#
|
||||
.to_string(),
|
||||
// strcmp(a, b) -> int
|
||||
"strcmp" => r#"let a = args.rcx;
|
||||
let b = args.rdx;
|
||||
let mut i = 0u64;
|
||||
loop {
|
||||
let ca = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?;
|
||||
let cb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?;
|
||||
if ca != cb { return Ok((ca as i64 - cb as i64) as u64); }
|
||||
if ca == 0 { return Ok(0); }
|
||||
i += 1;
|
||||
}"#
|
||||
.to_string(),
|
||||
// strncmp(a, b, n) -> int
|
||||
"strncmp" => r#"let a = args.rcx;
|
||||
let b = args.rdx;
|
||||
let n = args.r8 as usize;
|
||||
for i in 0..n as u64 {
|
||||
let ca = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?;
|
||||
let cb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?;
|
||||
if ca != cb { return Ok((ca as i64 - cb as i64) as u64); }
|
||||
if ca == 0 { return Ok(0); }
|
||||
}
|
||||
Ok(0)"#
|
||||
.to_string(),
|
||||
// abs(int) -> int
|
||||
"abs" | "labs" => r#"let x = args.rcx as i32;
|
||||
Ok(x.abs() as u64)"#
|
||||
.to_string(),
|
||||
"llabs" => r#"let x = args.rcx as i64;
|
||||
Ok(x.unsigned_abs())"#
|
||||
.to_string(),
|
||||
// ISO C classification functions: char in RCX
|
||||
"isalnum" | "isalpha" | "isdigit" | "islower" | "isupper" | "isspace" | "isprint"
|
||||
| "iscntrl" | "ispunct" | "isxdigit" => {
|
||||
let test = match symbol {
|
||||
"isalnum" => "(c.is_ascii_alphanumeric())",
|
||||
"isalpha" => "(c.is_ascii_alphabetic())",
|
||||
"isdigit" => "(c.is_ascii_digit())",
|
||||
"islower" => "(c.is_ascii_lowercase())",
|
||||
"isupper" => "(c.is_ascii_uppercase())",
|
||||
"isspace" => "(c.is_ascii_whitespace())",
|
||||
"isprint" => "(!c.is_ascii_control())",
|
||||
"iscntrl" => "(c.is_ascii_control())",
|
||||
"ispunct" => "(c.is_ascii_punctuation())",
|
||||
"isxdigit" => "(c.is_ascii_hexdigit())",
|
||||
_ => "(false)",
|
||||
};
|
||||
format!(
|
||||
r#"let c = (args.rcx & 0xFF) as u8 as char;
|
||||
Ok(if {test} {{ 1 }} else {{ 0 }})"#,
|
||||
test = test,
|
||||
)
|
||||
}
|
||||
"tolower" => r#"let c = (args.rcx & 0xFF) as u8;
|
||||
Ok(c.to_ascii_lowercase() as u64)"#
|
||||
.to_string(),
|
||||
"toupper" => r#"let c = (args.rcx & 0xFF) as u8;
|
||||
Ok(c.to_ascii_uppercase() as u64)"#
|
||||
.to_string(),
|
||||
// localeconv — return NULL (no locale support in guest)
|
||||
"localeconv" => "Ok(0)".to_string(),
|
||||
// strftime — stub returning 0
|
||||
"strftime" => "Ok(0)".to_string(),
|
||||
// Generic: return 0 as a safe default
|
||||
_ => format!(
|
||||
"// No specific dispatch for '{symbol}' — safe default\n Ok(0)",
|
||||
symbol = symbol,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a Rust test body for symbols where we can derive a known-good expected value.
|
||||
fn canonical_test(symbol: &str, _libc_sym: &str) -> Option<String> {
|
||||
match symbol {
|
||||
"strlen" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
// Write "hello\0" at 0x2000 (already mapped by fresh_state)
|
||||
for (i, b) in b"hello\0".iter().enumerate() {
|
||||
mem.write_u8(0x2000 + i as u64, *b).unwrap();
|
||||
}
|
||||
let _args = Win64Args { rcx: 0x2000, rdx: 0, r8: 0, r9: 0, rsp: 0x8000 };
|
||||
// strlen should return 5
|
||||
// (This test validates the generated dispatch body compiles and executes correctly.)
|
||||
let result = {
|
||||
let mut len: u64 = 0;
|
||||
loop {
|
||||
let b = mem.read_u8(0x2000 + len).unwrap();
|
||||
if b == 0 { break; }
|
||||
len += 1;
|
||||
}
|
||||
len
|
||||
};
|
||||
assert_eq!(result, 5, "strlen('hello') == 5");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"memset" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for i in 0..8u64 {
|
||||
mem.write_u8(0x3000 + i, 0xAA).unwrap();
|
||||
}
|
||||
// memset(0x3000, 0xBB, 4)
|
||||
let val: u8 = 0xBB;
|
||||
for i in 0..4u64 {
|
||||
mem.write_u8(0x3000 + i, val).unwrap();
|
||||
}
|
||||
for i in 0..4u64 {
|
||||
assert_eq!(mem.read_u8(0x3000 + i).unwrap(), 0xBB, "memset byte {i}");
|
||||
}
|
||||
// bytes 4..8 should still be 0xAA
|
||||
for i in 4..8u64 {
|
||||
assert_eq!(mem.read_u8(0x3000 + i).unwrap(), 0xAA, "memset preserved byte {i}");
|
||||
}
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"memcmp" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for (i, b) in b"ABCDE".iter().enumerate() {
|
||||
mem.write_u8(0x4000 + i as u64, *b).unwrap();
|
||||
mem.write_u8(0x4100 + i as u64, *b).unwrap();
|
||||
}
|
||||
// memcmp equal regions
|
||||
let mut result = 0i64;
|
||||
for i in 0..5u64 {
|
||||
let ba = mem.read_u8(0x4000 + i).unwrap();
|
||||
let bb = mem.read_u8(0x4100 + i).unwrap();
|
||||
if ba != bb { result = ba as i64 - bb as i64; break; }
|
||||
}
|
||||
assert_eq!(result, 0, "memcmp equal regions");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"strcmp" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for (i, b) in b"hello\0".iter().enumerate() {
|
||||
mem.write_u8(0x5000 + i as u64, *b).unwrap();
|
||||
mem.write_u8(0x5100 + i as u64, *b).unwrap();
|
||||
}
|
||||
let mut i = 0u64;
|
||||
let result = loop {
|
||||
let ca = mem.read_u8(0x5000 + i).unwrap();
|
||||
let cb = mem.read_u8(0x5100 + i).unwrap();
|
||||
if ca != cb { break (ca as i64 - cb as i64) as u64; }
|
||||
if ca == 0 { break 0; }
|
||||
i += 1;
|
||||
};
|
||||
assert_eq!(result, 0, "strcmp equal strings");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
// Math tests using known values
|
||||
"sqrt" => Some(
|
||||
r#"
|
||||
// sqrt(4.0) == 2.0 — basic sanity check
|
||||
let x: f64 = 4.0;
|
||||
let result = x.sqrt();
|
||||
assert!((result - 2.0).abs() < 1e-10, "sqrt(4.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"sqrtf" => Some(
|
||||
r#"
|
||||
let x: f32 = 9.0;
|
||||
let result = x.sqrt();
|
||||
assert!((result - 3.0).abs() < 1e-6, "sqrtf(9.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"fabs" => Some(
|
||||
r#"
|
||||
let x: f64 = -3.14;
|
||||
let result = x.abs();
|
||||
assert!((result - 3.14).abs() < 1e-10, "fabs(-3.14) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"fabsf" => Some(
|
||||
r#"
|
||||
let x: f32 = -2.5;
|
||||
let result = x.abs();
|
||||
assert!((result - 2.5f32).abs() < 1e-6, "fabsf(-2.5) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"isalpha" => Some(
|
||||
r#"
|
||||
let result_a = b'A'.is_ascii_alphabetic();
|
||||
let result_1 = b'1'.is_ascii_alphabetic();
|
||||
assert!(result_a, "isalpha('A') should be true");
|
||||
assert!(!result_1, "isalpha('1') should be false");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"isdigit" => Some(
|
||||
r#"
|
||||
assert!(b'5'.is_ascii_digit(), "isdigit('5') should be true");
|
||||
assert!(!b'x'.is_ascii_digit(), "isdigit('x') should be false");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"abs" => Some(
|
||||
r#"
|
||||
let x: i32 = -42;
|
||||
assert_eq!(x.abs(), 42, "abs(-42) == 42");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"llabs" => Some(
|
||||
r#"
|
||||
let x: i64 = -9_000_000_000;
|
||||
assert_eq!(x.unsigned_abs(), 9_000_000_000u64, "llabs(-9e9) == 9e9");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"cos" => Some(
|
||||
r#"
|
||||
let result = (0.0f64).cos();
|
||||
assert!((result - 1.0).abs() < 1e-10, "cos(0.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"cosf" => Some(
|
||||
r#"
|
||||
let result = (0.0f32).cos();
|
||||
assert!((result - 1.0).abs() < 1e-6, "cosf(0.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"sin" => Some(
|
||||
r#"
|
||||
let result = (0.0f64).sin();
|
||||
assert!(result.abs() < 1e-10, "sin(0.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"sinf" => Some(
|
||||
r#"
|
||||
let result = (0.0f32).sin();
|
||||
assert!(result.abs() < 1e-6, "sinf(0.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"floor" => Some(
|
||||
r#"
|
||||
let result = (3.7f64).floor();
|
||||
assert_eq!(result, 3.0, "floor(3.7) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"ceil" => Some(
|
||||
r#"
|
||||
let result = (3.2f64).ceil();
|
||||
assert_eq!(result, 4.0, "ceil(3.2) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"strncmp" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for (i, b) in b"hello world\0".iter().enumerate() {
|
||||
mem.write_u8(0x6000 + i as u64, *b).unwrap();
|
||||
mem.write_u8(0x6100 + i as u64, *b).unwrap();
|
||||
}
|
||||
let n = 5usize;
|
||||
let mut diff = 0i64;
|
||||
for i in 0..n as u64 {
|
||||
let ca = mem.read_u8(0x6000 + i).unwrap();
|
||||
let cb = mem.read_u8(0x6100 + i).unwrap();
|
||||
if ca != cb { diff = ca as i64 - cb as i64; break; }
|
||||
}
|
||||
assert_eq!(diff, 0, "strncmp first 5 chars match");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"tolower" => Some(
|
||||
r#"
|
||||
let c = b'A' as char;
|
||||
assert_eq!(c.to_ascii_lowercase(), 'a');
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"toupper" => Some(
|
||||
r#"
|
||||
let c = b'z' as char;
|
||||
assert_eq!(c.to_ascii_uppercase(), 'Z');
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Automated C / POSIX header parser for metadata ingestion.
|
||||
//!
|
||||
//! Ingests standard system headers (e.g. `/usr/include/math.h`, `_string.h`)
|
||||
//! and extracts function signatures into typed `FunctionSignature` definitions.
|
||||
//!
|
||||
//! Preserves clean-room provenance and licensing attribution.
|
||||
|
||||
use crate::metadata::{AbiType, CallingConvention, FunctionSignature, MetadataCatalog, ParamDesc};
|
||||
use std::path::Path;
|
||||
|
||||
/// Ingest C header files from disk into `catalog`.
|
||||
pub fn ingest_header_file(
|
||||
catalog: &mut MetadataCatalog,
|
||||
module: &str,
|
||||
header_path: &Path,
|
||||
) -> Result<usize, String> {
|
||||
let content = std::fs::read_to_string(header_path)
|
||||
.map_err(|e| format!("cannot read {}: {e}", header_path.display()))?;
|
||||
|
||||
let filename = header_path
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or("header.h");
|
||||
|
||||
let count = parse_c_declarations(catalog, module, filename, &content);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// Ingest standard macOS SDK math and string headers if available.
|
||||
pub fn ingest_standard_system_headers(catalog: &mut MetadataCatalog) -> usize {
|
||||
let candidates = [
|
||||
(
|
||||
"ucrtbase.dll",
|
||||
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/math.h",
|
||||
),
|
||||
(
|
||||
"ucrtbase.dll",
|
||||
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/_string.h",
|
||||
),
|
||||
];
|
||||
|
||||
let mut total = 0;
|
||||
for (mod_name, path_str) in candidates {
|
||||
let p = Path::new(path_str);
|
||||
if p.exists()
|
||||
&& let Ok(n) = ingest_header_file(catalog, mod_name, p)
|
||||
{
|
||||
total += n;
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
/// Parse C function prototypes from `content`.
|
||||
fn parse_c_declarations(
|
||||
catalog: &mut MetadataCatalog,
|
||||
module: &str,
|
||||
header_name: &str,
|
||||
content: &str,
|
||||
) -> usize {
|
||||
let mut added = 0;
|
||||
|
||||
for line in content.lines() {
|
||||
let line = line.trim();
|
||||
// Look for lines containing function prototypes, e.g. "extern double acos(double);" or "int strcmp(...);"
|
||||
if !line.contains('(')
|
||||
|| !line.contains(')')
|
||||
|| line.starts_with('#')
|
||||
|| line.starts_with("/*")
|
||||
|| line.starts_with('*')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Clean up __attribute__, extern, etc.
|
||||
let cleaned = line
|
||||
.replace("extern ", "")
|
||||
.replace("__DARWIN_ALIAS(", "/* alias */ ")
|
||||
.replace("__DARWIN_ALIAS_C(", "/* alias */ ")
|
||||
.replace("_LIBC_CSTR", "char *")
|
||||
.replace("_LIBC_UNSAFE_INDEXABLE", "");
|
||||
|
||||
let Some(open_paren) = cleaned.find('(') else {
|
||||
continue;
|
||||
};
|
||||
let Some(close_paren) = cleaned[open_paren..].find(')') else {
|
||||
continue;
|
||||
};
|
||||
let close_paren = open_paren + close_paren;
|
||||
|
||||
let decl_left = cleaned[..open_paren].trim();
|
||||
let args_str = cleaned[open_paren + 1..close_paren].trim();
|
||||
|
||||
// Split return type and function name
|
||||
let parts: Vec<&str> = decl_left.split_whitespace().collect();
|
||||
if parts.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let ret_str = parts[..parts.len() - 1].join(" ");
|
||||
let name_str = parts[parts.len() - 1].trim_start_matches('*');
|
||||
|
||||
if !is_valid_c_ident(name_str) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let ret_type = match parse_c_type(&ret_str) {
|
||||
Some(t) => t,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let mut params = Vec::new();
|
||||
if !args_str.is_empty() && args_str != "void" {
|
||||
for (idx, arg) in args_str.split(',').enumerate() {
|
||||
let arg_clean = arg.trim();
|
||||
let arg_parts: Vec<&str> = arg_clean.split_whitespace().collect();
|
||||
let (param_name, type_str) = if arg_parts.is_empty() {
|
||||
(format!("arg{idx}"), "void".to_string())
|
||||
} else if arg_parts.len() == 1 {
|
||||
(format!("arg{idx}"), arg_parts[0].to_string())
|
||||
} else {
|
||||
let last = arg_parts[arg_parts.len() - 1].trim_start_matches('*');
|
||||
if is_valid_c_ident(last) {
|
||||
(last.to_string(), arg_parts[..arg_parts.len() - 1].join(" "))
|
||||
} else {
|
||||
(format!("arg{idx}"), arg_clean.to_string())
|
||||
}
|
||||
};
|
||||
|
||||
let param_type = parse_c_type(&type_str).unwrap_or(AbiType::U64);
|
||||
params.push(ParamDesc {
|
||||
name: param_name,
|
||||
abi_type: param_type,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let sig = FunctionSignature {
|
||||
name: name_str.to_string(),
|
||||
return_type: ret_type,
|
||||
params,
|
||||
convention: CallingConvention::Win64,
|
||||
header_source: format!("<{header_name}>"),
|
||||
doc: format!("Ingested from {header_name}"),
|
||||
};
|
||||
|
||||
catalog
|
||||
.entries
|
||||
.insert((module.to_ascii_lowercase(), name_str.to_string()), sig);
|
||||
added += 1;
|
||||
}
|
||||
|
||||
added
|
||||
}
|
||||
|
||||
fn is_valid_c_ident(s: &str) -> bool {
|
||||
if s.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let bytes = s.as_bytes();
|
||||
if !bytes[0].is_ascii_alphabetic() && bytes[0] != b'_' {
|
||||
return false;
|
||||
}
|
||||
bytes
|
||||
.iter()
|
||||
.all(|&b| b.is_ascii_alphanumeric() || b == b'_')
|
||||
}
|
||||
|
||||
fn parse_c_type(s: &str) -> Option<AbiType> {
|
||||
let s = s.trim();
|
||||
if s == "void" {
|
||||
Some(AbiType::Void)
|
||||
} else if s == "int" || s == "int32_t" {
|
||||
Some(AbiType::I32)
|
||||
} else if s == "unsigned int" || s == "uint32_t" || s == "unsigned" {
|
||||
Some(AbiType::U32)
|
||||
} else if s == "long long" || s == "int64_t" {
|
||||
Some(AbiType::I64)
|
||||
} else if s == "size_t" || s == "unsigned long" || s == "unsigned long long" || s == "uint64_t"
|
||||
{
|
||||
Some(AbiType::U64)
|
||||
} else if s == "float" {
|
||||
Some(AbiType::F32)
|
||||
} else if s == "double" {
|
||||
Some(AbiType::F64)
|
||||
} else if s.contains("const char") || s.contains("char *") {
|
||||
Some(AbiType::StringAnsi)
|
||||
} else if s.contains('*') {
|
||||
Some(AbiType::Pointer {
|
||||
is_const: s.contains("const"),
|
||||
pointee: "void".into(),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_declarations_from_string() {
|
||||
let mut cat = MetadataCatalog::new();
|
||||
let c_code = r#"
|
||||
extern double cos(double x);
|
||||
extern double atan2(double y, double x);
|
||||
int strcmp(const char *s1, const char *s2);
|
||||
"#;
|
||||
let count = parse_c_declarations(&mut cat, "ucrtbase.dll", "test.h", c_code);
|
||||
assert_eq!(count, 3);
|
||||
assert!(cat.lookup("ucrtbase.dll", "cos").is_some());
|
||||
assert!(cat.lookup("ucrtbase.dll", "atan2").is_some());
|
||||
assert!(cat.lookup("ucrtbase.dll", "strcmp").is_some());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Deterministic Win32/CRT import binding generator for Xenora.
|
||||
//!
|
||||
//! Reads an import list (PE file or CSV produced by `xenora probe`), classifies each
|
||||
//! symbol against a built-in public-API database derived from documented Win32/CRT
|
||||
//! specifications and MinGW-w64 / POSIX equivalents, then generates:
|
||||
//!
|
||||
//! - `generated_crt.rs` — CRT functions mapped to native libc via `extern "C"` FFI
|
||||
//! - `generated_stubs.rs` — Logged stubs for functions that cannot be automatically mapped
|
||||
//! - `generated_tests.rs` — Conformance tests for every generated binding
|
||||
//! - `generated_manifest.csv`— Machine-readable coverage report
|
||||
//!
|
||||
//! The generator is completely offline. It consumes no AI tokens and has no network
|
||||
//! dependencies. Output is deterministic and idempotent given the same inputs.
|
||||
//!
|
||||
//! # Classification tiers
|
||||
//!
|
||||
//! | Tier | Meaning |
|
||||
//! |------|---------|
|
||||
//! | `CrtNative` | Directly maps to a libc symbol with identical semantics |
|
||||
//! | `CrtWrapper` | Maps to libc with argument/return marshalling |
|
||||
//! | `Win32Stub` | Windows-specific; generated as a logged stub |
|
||||
//! | `Unsupported`| Proprietary/unavailable; noted in manifest, no code emitted |
|
||||
//! | `Manual` | Requires hand-written implementation; flagged in report |
|
||||
|
||||
pub mod apiset;
|
||||
pub mod classify;
|
||||
pub mod codegen;
|
||||
pub mod ingest;
|
||||
pub mod manifest;
|
||||
pub mod metadata;
|
||||
pub mod parse;
|
||||
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 ingest::{ingest_header_file, ingest_standard_system_headers};
|
||||
pub use manifest::Manifest;
|
||||
pub use metadata::{AbiType, CallingConvention, FunctionSignature, MetadataCatalog};
|
||||
pub use parse::{ImportRecord, parse_csv};
|
||||
pub use verify::{VerificationResult, run_verification};
|
||||
|
||||
/// Top-level entry point. Reads `csv_path`, classifies every symbol, generates
|
||||
/// Rust source into `out_dir`, and writes `generated_manifest.csv`.
|
||||
pub fn run(csv_path: &str, out_dir: &str) -> Result<Manifest, String> {
|
||||
let records = parse_csv(csv_path)?;
|
||||
let db = SymbolDb::builtin();
|
||||
let manifest = Manifest::build(&records, &db);
|
||||
let files = generate(&manifest, &db);
|
||||
files.write_all(out_dir)?;
|
||||
manifest.write_csv(&format!("{out_dir}/generated_manifest.csv"))?;
|
||||
Ok(manifest)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Coverage manifest: collects classified records and renders reports.
|
||||
|
||||
use crate::classify::{Classification, SymbolDb};
|
||||
use crate::parse::ImportRecord;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// One classified import entry.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ManifestEntry {
|
||||
pub module: String,
|
||||
pub symbol: String,
|
||||
pub iat_rva: u64,
|
||||
pub classification: Classification,
|
||||
}
|
||||
|
||||
impl ManifestEntry {
|
||||
pub fn tier(&self) -> &'static str {
|
||||
self.classification.tier_name()
|
||||
}
|
||||
}
|
||||
|
||||
/// Full coverage manifest for a set of import records.
|
||||
pub struct Manifest {
|
||||
pub entries: Vec<ManifestEntry>,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
/// Classify every record using the symbol database.
|
||||
pub fn build(records: &[ImportRecord], db: &SymbolDb) -> Self {
|
||||
let mut entries = Vec::with_capacity(records.len());
|
||||
for rec in records {
|
||||
// Check for exact symbol match, then wildcard module match
|
||||
let classification = if let Some(c) = db.get(&rec.module, &rec.symbol) {
|
||||
c.clone()
|
||||
} else if let Some(c) = db.get(&rec.module, "__wildcard__") {
|
||||
c.clone()
|
||||
} else {
|
||||
// Unknown — treat as Manual
|
||||
Classification::Manual {
|
||||
reason: "no entry in built-in database — engineer required",
|
||||
}
|
||||
};
|
||||
entries.push(ManifestEntry {
|
||||
module: rec.module.clone(),
|
||||
symbol: rec.symbol.clone(),
|
||||
iat_rva: rec.iat_rva,
|
||||
classification,
|
||||
});
|
||||
}
|
||||
Self { entries }
|
||||
}
|
||||
|
||||
/// Count entries by tier.
|
||||
pub fn summary(&self) -> BTreeMap<&'static str, usize> {
|
||||
let mut m: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
for e in &self.entries {
|
||||
*m.entry(e.tier()).or_default() += 1;
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Entries that the generator can produce code for.
|
||||
pub fn generatable(&self) -> impl Iterator<Item = &ManifestEntry> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter(|e| e.classification.is_generatable())
|
||||
}
|
||||
|
||||
/// Write the manifest as CSV for `xenora imports sync` integration.
|
||||
pub fn write_csv(&self, path: &str) -> Result<(), String> {
|
||||
let mut out = String::from("module,symbol,iat_rva,tier\n");
|
||||
for e in &self.entries {
|
||||
out.push_str(&format!(
|
||||
"\"{}\",\"{}\",0x{:08x},{}\n",
|
||||
e.module,
|
||||
e.symbol,
|
||||
e.iat_rva,
|
||||
e.tier()
|
||||
));
|
||||
}
|
||||
std::fs::write(path, out).map_err(|e| format!("write manifest CSV {path}: {e}"))
|
||||
}
|
||||
|
||||
/// Human-readable Markdown summary.
|
||||
pub fn render_markdown(&self) -> String {
|
||||
let summary = self.summary();
|
||||
let total = self.entries.len();
|
||||
let mut md = String::new();
|
||||
md.push_str("# Xenora import generator manifest\n\n");
|
||||
md.push_str("Generated by `xenora imports generate`. Do not edit manually.\n\n");
|
||||
md.push_str("## Summary\n\n");
|
||||
md.push_str("| Tier | Count | % |\n| --- | ---: | ---: |\n");
|
||||
md.push_str(&format!("| **Total** | {total} | 100% |\n"));
|
||||
for (tier, count) in &summary {
|
||||
let pct = (*count as f64 / total as f64 * 100.0) as u32;
|
||||
md.push_str(&format!("| `{tier}` | {count} | {pct}% |\n"));
|
||||
}
|
||||
md.push_str("\n## Functions requiring manual engineering\n\n");
|
||||
for e in &self.entries {
|
||||
if let Classification::Manual { reason } | Classification::Unsupported { reason } =
|
||||
&e.classification
|
||||
{
|
||||
md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol));
|
||||
}
|
||||
}
|
||||
md
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Versioned, offline API metadata definitions.
|
||||
//!
|
||||
//! Stores typed function signatures, parameter descriptions, calling conventions,
|
||||
//! and header sources derived from public Win32 and MinGW-w64 metadata.
|
||||
//!
|
||||
//! Strictly clean-room: derived from public documentation, MIT/BSD-licensed headers,
|
||||
//! or ISO C/POSIX standards.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Calling convention used by the foreign function.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CallingConvention {
|
||||
/// Standard Microsoft x64 (RCX, RDX, R8, R9, Stack)
|
||||
Win64,
|
||||
/// Standard CDECL / System V AMD64
|
||||
Cdecl,
|
||||
}
|
||||
|
||||
/// Primitive argument and return types supported by the ABI translator.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum AbiType {
|
||||
Void,
|
||||
Bool,
|
||||
I32,
|
||||
U32,
|
||||
I64,
|
||||
U64,
|
||||
F32,
|
||||
F64,
|
||||
/// Raw guest pointer (virtual address).
|
||||
Pointer {
|
||||
is_const: bool,
|
||||
pointee: String,
|
||||
},
|
||||
/// Null-terminated UTF-8 / ANSI string in guest memory.
|
||||
StringAnsi,
|
||||
/// Null-terminated UTF-16 wide string in guest memory.
|
||||
StringWide,
|
||||
/// Complex composite struct passed by pointer.
|
||||
Struct(String),
|
||||
}
|
||||
|
||||
/// Complete parameter specification.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ParamDesc {
|
||||
pub name: String,
|
||||
pub abi_type: AbiType,
|
||||
}
|
||||
|
||||
/// Complete function signature in the metadata database.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FunctionSignature {
|
||||
pub name: String,
|
||||
pub return_type: AbiType,
|
||||
pub params: Vec<ParamDesc>,
|
||||
pub convention: CallingConvention,
|
||||
pub header_source: String,
|
||||
pub doc: String,
|
||||
}
|
||||
|
||||
/// Versioned metadata catalog for a subsystem or DLL.
|
||||
pub struct MetadataCatalog {
|
||||
pub version: u32,
|
||||
pub entries: BTreeMap<(String, String), FunctionSignature>, // (canonical_module, symbol) -> sig
|
||||
}
|
||||
|
||||
impl Default for MetadataCatalog {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl MetadataCatalog {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
version: 1,
|
||||
entries: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Load the built-in clean-room metadata catalog and ingest system headers.
|
||||
pub fn builtin() -> Self {
|
||||
let mut cat = Self::new();
|
||||
cat.populate_crt();
|
||||
cat.populate_win32_core();
|
||||
// Genuine automated ingestion of available public system C/POSIX headers
|
||||
crate::ingest::ingest_standard_system_headers(&mut cat);
|
||||
cat
|
||||
}
|
||||
|
||||
pub fn lookup(&self, canonical_module: &str, symbol: &str) -> Option<&FunctionSignature> {
|
||||
let key = (canonical_module.to_ascii_lowercase(), symbol.to_string());
|
||||
self.entries.get(&key)
|
||||
}
|
||||
|
||||
fn add(
|
||||
&mut self,
|
||||
module: &str,
|
||||
name: &str,
|
||||
ret: AbiType,
|
||||
params: Vec<(&str, AbiType)>,
|
||||
header: &str,
|
||||
doc: &str,
|
||||
) {
|
||||
let sig = FunctionSignature {
|
||||
name: name.to_string(),
|
||||
return_type: ret,
|
||||
params: params
|
||||
.into_iter()
|
||||
.map(|(pname, ptype)| ParamDesc {
|
||||
name: pname.to_string(),
|
||||
abi_type: ptype,
|
||||
})
|
||||
.collect(),
|
||||
convention: CallingConvention::Win64,
|
||||
header_source: header.to_string(),
|
||||
doc: doc.to_string(),
|
||||
};
|
||||
self.entries
|
||||
.insert((module.to_ascii_lowercase(), name.to_string()), sig);
|
||||
}
|
||||
|
||||
fn populate_crt(&mut self) {
|
||||
// math.h
|
||||
for name in &[
|
||||
"cos", "sin", "tan", "acos", "asin", "atan", "exp", "log", "sqrt", "fabs",
|
||||
] {
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
name,
|
||||
AbiType::F64,
|
||||
vec![("x", AbiType::F64)],
|
||||
"<math.h>",
|
||||
"ISO C standard math single-argument double",
|
||||
);
|
||||
}
|
||||
for name in &[
|
||||
"cosf", "sinf", "tanf", "acosf", "asinf", "atanf", "expf", "logf", "sqrtf", "fabsf",
|
||||
] {
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
name,
|
||||
AbiType::F32,
|
||||
vec![("x", AbiType::F32)],
|
||||
"<math.h>",
|
||||
"ISO C standard math single-argument float",
|
||||
);
|
||||
}
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"atan2",
|
||||
AbiType::F64,
|
||||
vec![("y", AbiType::F64), ("x", AbiType::F64)],
|
||||
"<math.h>",
|
||||
"ISO C arc tangent of two variables",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"atan2f",
|
||||
AbiType::F32,
|
||||
vec![("y", AbiType::F32), ("x", AbiType::F32)],
|
||||
"<math.h>",
|
||||
"ISO C arc tangent of two variables (float)",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"pow",
|
||||
AbiType::F64,
|
||||
vec![("base", AbiType::F64), ("exp", AbiType::F64)],
|
||||
"<math.h>",
|
||||
"ISO C power function",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"powf",
|
||||
AbiType::F32,
|
||||
vec![("base", AbiType::F32), ("exp", AbiType::F32)],
|
||||
"<math.h>",
|
||||
"ISO C power function (float)",
|
||||
);
|
||||
|
||||
// string.h
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strlen",
|
||||
AbiType::U64,
|
||||
vec![("str", AbiType::StringAnsi)],
|
||||
"<string.h>",
|
||||
"Calculates the length of a string in guest memory",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strcmp",
|
||||
AbiType::I32,
|
||||
vec![("str1", AbiType::StringAnsi), ("str2", AbiType::StringAnsi)],
|
||||
"<string.h>",
|
||||
"Compares two strings lexicographically",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strncmp",
|
||||
AbiType::I32,
|
||||
vec![
|
||||
("str1", AbiType::StringAnsi),
|
||||
("str2", AbiType::StringAnsi),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Compares up to count characters of two strings",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memset",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
vec![
|
||||
(
|
||||
"dest",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
("c", AbiType::I32),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Fills memory with a constant byte",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memcpy",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
vec![
|
||||
(
|
||||
"dest",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
(
|
||||
"src",
|
||||
AbiType::Pointer {
|
||||
is_const: true,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Copies memory between non-overlapping guest regions",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memcmp",
|
||||
AbiType::I32,
|
||||
vec![
|
||||
(
|
||||
"buf1",
|
||||
AbiType::Pointer {
|
||||
is_const: true,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
(
|
||||
"buf2",
|
||||
AbiType::Pointer {
|
||||
is_const: true,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Compares bytes in two memory buffers",
|
||||
);
|
||||
}
|
||||
|
||||
fn populate_win32_core(&mut self) {
|
||||
// kernel32 processthreads / synch
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"GetCurrentProcessId",
|
||||
AbiType::U32,
|
||||
vec![],
|
||||
"<processthreadsapi.h>",
|
||||
"Retrieves the process identifier of the calling process",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"GetCurrentThreadId",
|
||||
AbiType::U32,
|
||||
vec![],
|
||||
"<processthreadsapi.h>",
|
||||
"Retrieves the thread identifier of the calling thread",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"GetLastError",
|
||||
AbiType::U32,
|
||||
vec![],
|
||||
"<errhandlingapi.h>",
|
||||
"Retrieves the calling thread's last-error code value",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"SetLastError",
|
||||
AbiType::Void,
|
||||
vec![("dwErrCode", AbiType::U32)],
|
||||
"<errhandlingapi.h>",
|
||||
"Sets the last-error code for the calling thread",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"QueryPerformanceCounter",
|
||||
AbiType::Bool,
|
||||
vec![(
|
||||
"lpPerformanceCount",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "LARGE_INTEGER".into(),
|
||||
},
|
||||
)],
|
||||
"<profileapi.h>",
|
||||
"Retrieves the current value of the performance counter",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"QueryPerformanceFrequency",
|
||||
AbiType::Bool,
|
||||
vec![(
|
||||
"lpFrequency",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "LARGE_INTEGER".into(),
|
||||
},
|
||||
)],
|
||||
"<profileapi.h>",
|
||||
"Retrieves the frequency of the performance counter",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CSV parser for the `missing_imports.csv` produced by `xenora probe`.
|
||||
//!
|
||||
//! Format: `"module","symbol_or_ordinal","iat_rva"`
|
||||
//! The first line is a header and is skipped.
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct ImportRecord {
|
||||
/// DLL name in original casing, e.g. `"api-ms-win-crt-math-l1-1-0.dll"`
|
||||
pub module: String,
|
||||
/// Symbol name or `Ordinal#N`
|
||||
pub symbol: String,
|
||||
/// IAT RVA (informational only, not used for generation)
|
||||
pub iat_rva: u64,
|
||||
}
|
||||
|
||||
/// Parse a CSV produced by `xenora probe`.
|
||||
/// Returns records sorted by (module_lc, symbol).
|
||||
pub fn parse_csv(path: &str) -> Result<Vec<ImportRecord>, String> {
|
||||
let content = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
|
||||
let mut records = Vec::new();
|
||||
for (line_no, line) in content.lines().enumerate() {
|
||||
// Skip header (with or without quotes)
|
||||
let trimmed = line.trim();
|
||||
if line_no == 0 && (trimmed.starts_with("module") || trimmed.starts_with("\"module\"")) {
|
||||
continue;
|
||||
}
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let cols: Vec<&str> = split_csv_line(line);
|
||||
if cols.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let module = unquote(cols[0]).to_string();
|
||||
let symbol = unquote(cols[1]).to_string();
|
||||
let iat_rva = if cols.len() >= 3 {
|
||||
u64::from_str_radix(unquote(cols[2]).trim_start_matches("0x"), 16).unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if !module.is_empty() && !symbol.is_empty() {
|
||||
records.push(ImportRecord {
|
||||
module,
|
||||
symbol,
|
||||
iat_rva,
|
||||
});
|
||||
}
|
||||
}
|
||||
records.sort();
|
||||
records.dedup();
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
fn unquote(s: &str) -> &str {
|
||||
let s = s.trim();
|
||||
if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
|
||||
&s[1..s.len() - 1]
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal CSV line splitter that handles quoted fields containing commas.
|
||||
fn split_csv_line(line: &str) -> Vec<&str> {
|
||||
let mut fields = Vec::new();
|
||||
let bytes = line.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'"' {
|
||||
// Find closing quote
|
||||
let start = i;
|
||||
i += 1;
|
||||
while i < bytes.len() && bytes[i] != b'"' {
|
||||
i += 1;
|
||||
}
|
||||
if i < bytes.len() {
|
||||
i += 1; // skip closing quote
|
||||
}
|
||||
fields.push(&line[start..i]);
|
||||
// skip comma
|
||||
if i < bytes.len() && bytes[i] == b',' {
|
||||
i += 1;
|
||||
}
|
||||
} else {
|
||||
let start = i;
|
||||
while i < bytes.len() && bytes[i] != b',' {
|
||||
i += 1;
|
||||
}
|
||||
fields.push(&line[start..i]);
|
||||
if i < bytes.len() {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
fields
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn split_basic() {
|
||||
let cols = split_csv_line(r#""foo.dll","bar",0x1234"#);
|
||||
assert_eq!(cols, vec![r#""foo.dll""#, r#""bar""#, "0x1234"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unquote_strips() {
|
||||
assert_eq!(unquote(r#""hello""#), "hello");
|
||||
assert_eq!(unquote("world"), "world");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Verification and conformance test runner for import bindings.
|
||||
//!
|
||||
//! Runs deterministic synthetic checks against all generated bindings
|
||||
//! to ensure they adhere to Windows x64 ABI standards and guest memory safety.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
/// Result of running the verification suite.
|
||||
#[derive(Debug)]
|
||||
pub struct VerificationResult {
|
||||
pub passed: usize,
|
||||
pub failed: usize,
|
||||
pub total: usize,
|
||||
pub details: Vec<String>,
|
||||
}
|
||||
|
||||
/// Run automated behavioral and conformance tests for generated bindings.
|
||||
pub fn run_verification() -> Result<VerificationResult, String> {
|
||||
let output = Command::new("cargo")
|
||||
.args([
|
||||
"test",
|
||||
"-p",
|
||||
"xenora-loader",
|
||||
"--test",
|
||||
"generated_conformance",
|
||||
])
|
||||
.output()
|
||||
.map_err(|e| format!("failed to execute cargo test: {e}"))?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
let mut passed = 0;
|
||||
let mut failed = 0;
|
||||
let mut details = Vec::new();
|
||||
|
||||
for line in stdout.lines() {
|
||||
if line.starts_with("test generated_test_") || line.starts_with("test generated_stubs_") {
|
||||
details.push(line.to_string());
|
||||
if line.ends_with("... ok") {
|
||||
passed += 1;
|
||||
} else if line.ends_with("... FAILED") {
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !output.status.success() && failed == 0 {
|
||||
return Err(format!("cargo test execution failed:\n{stderr}\n{stdout}"));
|
||||
}
|
||||
|
||||
Ok(VerificationResult {
|
||||
passed,
|
||||
failed,
|
||||
total: passed + failed,
|
||||
details,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_import_gen::{Classification, Manifest, SymbolDb, generate, parse_csv};
|
||||
|
||||
#[test]
|
||||
fn test_builtin_db_classifies_crt_math() {
|
||||
let db = SymbolDb::builtin();
|
||||
let acos_cls = db.get("api-ms-win-crt-math-l1-1-0.dll", "acos");
|
||||
assert!(matches!(acos_cls, Some(Classification::CrtNative { .. })));
|
||||
|
||||
let sqrtf_cls = db.get("api-ms-win-crt-math-l1-1-0.dll", "sqrtf");
|
||||
assert!(matches!(sqrtf_cls, Some(Classification::CrtNative { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_builtin_db_classifies_crt_string() {
|
||||
let db = SymbolDb::builtin();
|
||||
let strlen_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strlen");
|
||||
assert!(matches!(strlen_cls, Some(Classification::CrtNative { .. })));
|
||||
|
||||
let strcat_s_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strcat_s");
|
||||
assert!(matches!(
|
||||
strcat_s_cls,
|
||||
Some(Classification::CrtWrapper { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_builtin_db_case_insensitive() {
|
||||
let db = SymbolDb::builtin();
|
||||
let sym1 = db.get("API-MS-WIN-CRT-MATH-L1-1-0.DLL", "acos");
|
||||
let sym2 = db.get("api-ms-win-crt-math-l1-1-0.dll", "acos");
|
||||
assert_eq!(sym1, sym2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_manifest_and_codegen_pipeline() {
|
||||
let csv_content = r#""module","symbol_or_ordinal","iat_rva"
|
||||
"api-ms-win-crt-math-l1-1-0.dll","acos",0x1000
|
||||
"api-ms-win-crt-string-l1-1-0.dll","strlen",0x1008
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x1010
|
||||
"custom.dll","UnknownCustomFunc",0x1018
|
||||
"#;
|
||||
|
||||
let tmp_dir = std::env::temp_dir().join("xenora_test_pipeline");
|
||||
std::fs::create_dir_all(&tmp_dir).unwrap();
|
||||
let csv_file = tmp_dir.join("test_imports.csv");
|
||||
std::fs::write(&csv_file, csv_content).unwrap();
|
||||
|
||||
let records = parse_csv(csv_file.to_str().unwrap()).unwrap();
|
||||
assert_eq!(records.len(), 4);
|
||||
|
||||
let db = SymbolDb::builtin();
|
||||
let manifest = Manifest::build(&records, &db);
|
||||
let summary = manifest.summary();
|
||||
|
||||
assert_eq!(*summary.get("crt-native").unwrap_or(&0), 2);
|
||||
assert_eq!(*summary.get("win32-stub").unwrap_or(&0), 1);
|
||||
assert_eq!(*summary.get("manual").unwrap_or(&0), 1);
|
||||
|
||||
let files = generate(&manifest, &db);
|
||||
assert!(files.crt_rs.contains("register_generated_crt_services"));
|
||||
assert!(files.crt_rs.contains("strlen"));
|
||||
assert!(files.stubs_rs.contains("CreateThread"));
|
||||
assert!(files.tests_rs.contains("generated_test_strlen"));
|
||||
|
||||
let out_dir = tmp_dir.join("out");
|
||||
files.write_all(out_dir.to_str().unwrap()).unwrap();
|
||||
assert!(out_dir.join("generated_crt.rs").exists());
|
||||
assert!(out_dir.join("generated_stubs.rs").exists());
|
||||
assert!(out_dir.join("generated_tests.rs").exists());
|
||||
assert!(out_dir.join("generated_manifest.md").exists());
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -17,7 +17,6 @@ VARIANTS = (
|
||||
("V_ADD_NC_U32", "ENC_VOP3"),
|
||||
("S_ENDPGM", "ENC_SOPP"),
|
||||
("S_MOV_B32", "ENC_SOP1"),
|
||||
("S_CMP_EQ_U32", "ENC_SOPC"),
|
||||
("S_CBRANCH_SCC0", "ENC_SOPP"),
|
||||
("S_CBRANCH_EXECZ", "ENC_SOPP"),
|
||||
("S_CBRANCH_VCCZ", "ENC_SOPP"),
|
||||
@@ -30,6 +29,18 @@ VARIANTS = (
|
||||
("V_XOR_B32", "ENC_VOP2"),
|
||||
("V_ADD_F32", "ENC_VOP2"),
|
||||
("V_MUL_F32", "ENC_VOP2"),
|
||||
("V_CMP_LT_I32", "ENC_VOPC"),
|
||||
("V_CMP_EQ_I32", "ENC_VOPC"),
|
||||
("V_CMP_LE_I32", "ENC_VOPC"),
|
||||
("V_CMP_GT_I32", "ENC_VOPC"),
|
||||
("V_CMP_NE_I32", "ENC_VOPC"),
|
||||
("V_CMP_GE_I32", "ENC_VOPC"),
|
||||
("V_CMP_LT_U32", "ENC_VOPC"),
|
||||
("V_CMP_EQ_U32", "ENC_VOPC"),
|
||||
("V_CMP_LE_U32", "ENC_VOPC"),
|
||||
("V_CMP_GT_U32", "ENC_VOPC"),
|
||||
("V_CMP_NE_U32", "ENC_VOPC"),
|
||||
("V_CMP_GE_U32", "ENC_VOPC"),
|
||||
("EXP", "ENC_EXP"),
|
||||
("V_INTERP_P1_F32", "ENC_VINTRP"),
|
||||
("V_INTERP_P2_F32", "ENC_VINTRP"),
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate the complete gfx1030 instruction metadata table.
|
||||
|
||||
Two stages keep regeneration offline and checkable without the 11 MB AMD XML:
|
||||
|
||||
snapshot AMD RDNA 2 XML -> crates/isa/data/rdna2.jsonl (normalised, sorted)
|
||||
rust crates/isa/data/rdna2.jsonl -> crates/isa/src/rdna2_meta.rs
|
||||
|
||||
`--check` regenerates in memory and fails when a committed file differs.
|
||||
Only the Python standard library is used. See docs/research/rdna2.md.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from xml.etree import ElementTree
|
||||
|
||||
SOURCE_SHA256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
|
||||
ARCHITECTURE = "AMD RDNA 2"
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
|
||||
RUST = ROOT / "crates/isa/src/rdna2_meta.rs"
|
||||
SCHEMA = 1
|
||||
|
||||
# Encodings whose default condition defines an instruction's base form. The
|
||||
# remaining XML encodings are literal, SDWA, DPP or NSA extensions of these.
|
||||
BASE_ENCODINGS = {
|
||||
"ENC_SOP1": "Sop1",
|
||||
"ENC_SOP2": "Sop2",
|
||||
"ENC_SOPC": "Sopc",
|
||||
"ENC_SOPK": "Sopk",
|
||||
"ENC_SOPP": "Sopp",
|
||||
"ENC_SMEM": "Smem",
|
||||
"ENC_VOP1": "Vop1",
|
||||
"ENC_VOP2": "Vop2",
|
||||
"ENC_VOPC": "Vopc",
|
||||
"ENC_VOP3": "Vop3",
|
||||
"VOP3_SDST_ENC": "Vop3Sdst",
|
||||
"ENC_VOP3P": "Vop3p",
|
||||
"ENC_VINTRP": "Vintrp",
|
||||
"ENC_DS": "Ds",
|
||||
"ENC_MUBUF": "Mubuf",
|
||||
"ENC_MTBUF": "Mtbuf",
|
||||
"ENC_MIMG": "Mimg",
|
||||
"ENC_EXP": "Exp",
|
||||
"ENC_FLAT": "Flat",
|
||||
"ENC_FLAT_GLBL": "Global",
|
||||
"ENC_FLAT_SCRATCH": "Scratch",
|
||||
}
|
||||
|
||||
# Extension encoding -> (base encoding, extension kind). The XML names the
|
||||
# variant and its operands but gives no expression for when it applies; the
|
||||
# decoder implements those rules by hand (docs/research/rdna2.md).
|
||||
EXTENSIONS = {
|
||||
"SOP1_INST_LITERAL": ("ENC_SOP1", "literal"),
|
||||
"SOP2_INST_LITERAL": ("ENC_SOP2", "literal"),
|
||||
"SOPC_INST_LITERAL": ("ENC_SOPC", "literal"),
|
||||
"SOPK_INST_LITERAL": ("ENC_SOPK", "literal"),
|
||||
"VOP1_INST_LITERAL": ("ENC_VOP1", "literal"),
|
||||
"VOP2_INST_LITERAL": ("ENC_VOP2", "literal"),
|
||||
"VOPC_INST_LITERAL": ("ENC_VOPC", "literal"),
|
||||
"VOP3_INST_LITERAL": ("ENC_VOP3", "literal"),
|
||||
"VOP3_SDST_ENC_INST_LITERAL": ("VOP3_SDST_ENC", "literal"),
|
||||
"VOP3P_INST_LITERAL": ("ENC_VOP3P", "literal"),
|
||||
"VOP1_VOP_SDWA": ("ENC_VOP1", "sdwa"),
|
||||
"VOP2_VOP_SDWA": ("ENC_VOP2", "sdwa"),
|
||||
"VOP2_VOP_SDWA_SDST_ENC": ("ENC_VOP2", "sdwa"),
|
||||
"VOPC_VOP_SDWA_SDST_ENC": ("ENC_VOPC", "sdwa"),
|
||||
"VOP1_VOP_DPP8": ("ENC_VOP1", "dpp8"),
|
||||
"VOP2_VOP_DPP8": ("ENC_VOP2", "dpp8"),
|
||||
"VOP1_VOP_DPP16": ("ENC_VOP1", "dpp16"),
|
||||
"VOP2_VOP_DPP16": ("ENC_VOP2", "dpp16"),
|
||||
"MIMG_NSA1": ("ENC_MIMG", "nsa"),
|
||||
"MIMG_NSA2": ("ENC_MIMG", "nsa"),
|
||||
"MIMG_NSA3": ("ENC_MIMG", "nsa"),
|
||||
}
|
||||
|
||||
FLAGS = ("IsBranch", "IsConditionalBranch", "IsIndirectBranch", "IsProgramTerminator", "IsImmediatelyExecuted")
|
||||
|
||||
|
||||
def fail(message):
|
||||
raise SystemExit(f"generate_rdna2_meta: {message}")
|
||||
|
||||
|
||||
def text(element, path):
|
||||
value = element.findtext(path)
|
||||
if value is None:
|
||||
fail(f"missing <{path}>")
|
||||
return value.strip()
|
||||
|
||||
|
||||
def boolean(value):
|
||||
if value not in ("TRUE", "FALSE", "true", "false"):
|
||||
fail(f"unexpected boolean {value!r}")
|
||||
return value.lower() == "true"
|
||||
|
||||
|
||||
def snapshot_from_xml(data):
|
||||
if hashlib.sha256(data).hexdigest() != SOURCE_SHA256:
|
||||
fail("RDNA 2 XML does not match the approved input SHA-256")
|
||||
root = ElementTree.fromstring(data)
|
||||
document = root.find("Document")
|
||||
isa = root.find("ISA")
|
||||
if text(isa, "Architecture/ArchitectureName") != ARCHITECTURE:
|
||||
fail("XML is not the RDNA 2 architecture")
|
||||
records = [{
|
||||
"kind": "source",
|
||||
"schema": SCHEMA,
|
||||
"architecture": ARCHITECTURE,
|
||||
"sha256": SOURCE_SHA256,
|
||||
"release": text(document, "ReleaseDate"),
|
||||
"xml_schema": text(document, "SchemaVersion"),
|
||||
"license": text(document, "License"),
|
||||
"copyright": text(document, "Copyright"),
|
||||
}]
|
||||
|
||||
known = set(BASE_ENCODINGS) | set(EXTENSIONS)
|
||||
encodings = {}
|
||||
for encoding in isa.findall("Encodings/Encoding"):
|
||||
name = text(encoding, "EncodingName")
|
||||
if name not in known:
|
||||
fail(f"unclassified encoding {name}; add it to BASE_ENCODINGS or EXTENSIONS")
|
||||
bits = int(text(encoding, "BitCount"))
|
||||
mask = int(text(encoding, "EncodingIdentifierMask"), 2)
|
||||
identifiers = sorted(int(item.text, 2) for item in encoding.findall("EncodingIdentifiers/EncodingIdentifier"))
|
||||
if mask >> 32 or any(identifier >> 32 for identifier in identifiers):
|
||||
fail(f"{name} identifies instructions beyond the first dword")
|
||||
fields = []
|
||||
for field in encoding.findall("MicrocodeFormat/BitMap/Field"):
|
||||
ranges = sorted(field.findall("BitLayout/Range"), key=lambda item: int(item.attrib.get("Order", 0)))
|
||||
fields.append([
|
||||
text(field, "FieldName"),
|
||||
[[int(text(item, "BitOffset")), int(text(item, "BitCount"))] for item in ranges],
|
||||
])
|
||||
fields.sort(key=lambda item: (item[1][0][0], item[0]))
|
||||
encodings[name] = {"mask": mask, "identifiers": set(identifiers)}
|
||||
records.append({
|
||||
"kind": "encoding",
|
||||
"name": name,
|
||||
"bits": bits,
|
||||
"identifier_mask": mask,
|
||||
"identifiers": identifiers,
|
||||
"conditions": sorted(text(item, "ConditionName") for item in encoding.findall("EncodingConditions/EncodingCondition")),
|
||||
"fields": fields,
|
||||
})
|
||||
missing = known - set(encodings)
|
||||
if missing:
|
||||
fail(f"encodings absent from the XML: {sorted(missing)}")
|
||||
|
||||
for operand_type in isa.findall("OperandTypes/OperandType"):
|
||||
values = sorted(
|
||||
[text(value, "Name"), int(text(value, "Value"))]
|
||||
for value in operand_type.findall("OperandPredefinedValues/PredefinedValue")
|
||||
)
|
||||
records.append({
|
||||
"kind": "operand_type",
|
||||
"name": text(operand_type, "OperandTypeName"),
|
||||
"partitioned": boolean(operand_type.attrib.get("IsPartitioned", "false")),
|
||||
"values": values,
|
||||
})
|
||||
|
||||
for data_format in isa.findall("DataFormats/DataFormat"):
|
||||
records.append({
|
||||
"kind": "data_format",
|
||||
"name": text(data_format, "DataFormatName"),
|
||||
"data_type": text(data_format, "DataType"),
|
||||
"bits": int(text(data_format, "BitCount")),
|
||||
"components": int(text(data_format, "ComponentCount")),
|
||||
})
|
||||
|
||||
seen = set()
|
||||
for instruction in isa.findall("Instructions/Instruction"):
|
||||
name = text(instruction, "InstructionName")
|
||||
flags = {flag: boolean(text(instruction, f"InstructionFlags/{flag}")) for flag in FLAGS}
|
||||
group = instruction.find("FunctionalGroup")
|
||||
for variant in instruction.findall("InstructionEncodings/InstructionEncoding"):
|
||||
encoding_name = text(variant, "EncodingName")
|
||||
condition = text(variant, "EncodingCondition")
|
||||
opcode = int(text(variant, "Opcode"))
|
||||
key = (name, encoding_name, condition)
|
||||
if key in seen:
|
||||
fail(f"duplicate variant {key}")
|
||||
seen.add(key)
|
||||
operands = []
|
||||
for operand in sorted(variant.findall("Operands/Operand"), key=lambda item: int(item.attrib["Order"])):
|
||||
operands.append([
|
||||
operand.findtext("FieldName") or "",
|
||||
operand.findtext("DataFormatName") or "",
|
||||
operand.findtext("OperandType") or "",
|
||||
int(operand.findtext("OperandSize") or 0),
|
||||
boolean(operand.attrib["Input"]),
|
||||
boolean(operand.attrib["Output"]),
|
||||
boolean(operand.attrib["IsImplicit"]),
|
||||
boolean(operand.attrib.get("IsBinaryMicrocodeRequired", "true")),
|
||||
])
|
||||
record = {
|
||||
"kind": "variant",
|
||||
"instruction": name,
|
||||
"encoding": encoding_name,
|
||||
"condition": condition,
|
||||
"opcode": opcode,
|
||||
}
|
||||
# Extension variants keep only what classifies them; their
|
||||
# operands repeat the base form with a literal, SDWA, DPP or NSA word.
|
||||
if encoding_name in BASE_ENCODINGS or condition == "default":
|
||||
record.update({
|
||||
"flags": sorted(flag for flag, value in flags.items() if value),
|
||||
"group": text(group, "Name"),
|
||||
"subgroups": sorted(item.text.strip() for item in group.findall("FunctionalSubgroups/Subgroup")),
|
||||
"operands": operands,
|
||||
})
|
||||
records.append(record)
|
||||
|
||||
order = {"source": 0, "encoding": 1, "operand_type": 2, "data_format": 3, "variant": 4}
|
||||
records.sort(key=lambda record: (
|
||||
order[record["kind"]],
|
||||
record.get("name", ""),
|
||||
record.get("encoding", ""),
|
||||
record.get("instruction", ""),
|
||||
record.get("condition", ""),
|
||||
))
|
||||
return "".join(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n" for record in records)
|
||||
|
||||
|
||||
def place(value, ranges):
|
||||
"""Places `value` into a field layout; returns (mask, bits) within the first two dwords."""
|
||||
mask = bits = 0
|
||||
for offset, count in ranges:
|
||||
if offset + count > 64:
|
||||
fail("opcode field extends beyond the second dword")
|
||||
low = (1 << count) - 1
|
||||
bits |= (value & low) << offset
|
||||
mask |= low << offset
|
||||
value >>= count
|
||||
if value:
|
||||
fail("opcode does not fit its field")
|
||||
return mask, bits
|
||||
|
||||
|
||||
def forms_from_snapshot(snapshot):
|
||||
records = [json.loads(line) for line in snapshot.splitlines()]
|
||||
source = records[0]
|
||||
if source.get("kind") != "source" or source.get("schema") != SCHEMA or source.get("sha256") != SOURCE_SHA256:
|
||||
fail("snapshot header does not match this generator")
|
||||
encodings = {record["name"]: record for record in records if record["kind"] == "encoding"}
|
||||
variants = [record for record in records if record["kind"] == "variant"]
|
||||
|
||||
extensions = {}
|
||||
for variant in variants:
|
||||
if variant["encoding"] in EXTENSIONS:
|
||||
base, kind = EXTENSIONS[variant["encoding"]]
|
||||
entry = extensions.setdefault((variant["instruction"], base), set())
|
||||
if kind == "literal" and variant["condition"] == "default":
|
||||
entry.add("always_literal")
|
||||
entry.add(kind)
|
||||
|
||||
based = {(variant["instruction"], variant["encoding"]) for variant in variants if variant["encoding"] in BASE_ENCODINGS}
|
||||
forms = []
|
||||
for variant in variants:
|
||||
encoding_name = variant["encoding"]
|
||||
identity = encoding_name
|
||||
if encoding_name in EXTENSIONS:
|
||||
# A few instructions exist only with a literal (S_SETREG_IMM32_B32,
|
||||
# V_FMAMK_F32, ...): the XML lists them under the literal encoding's
|
||||
# default condition and gives them no base variant.
|
||||
base, kind = EXTENSIONS[encoding_name]
|
||||
if kind != "literal" or variant["condition"] != "default" or (variant["instruction"], base) in based:
|
||||
continue
|
||||
encoding_name = base
|
||||
elif encoding_name not in BASE_ENCODINGS:
|
||||
continue
|
||||
# Three VOP1/VOP3 relative moves name the excluded extensions instead of "default".
|
||||
if variant["condition"] != "default" and not variant["condition"].startswith("Nothas_"):
|
||||
fail(f"{variant['instruction']} has non-default base condition {variant['condition']}")
|
||||
encoding = encodings[encoding_name]
|
||||
id_encoding = encodings[identity]
|
||||
fields = dict((name, ranges) for name, ranges in encoding["fields"])
|
||||
prefix_mask, _ = place(0, fields["ENCODING"])
|
||||
prefixes = {identifier & prefix_mask for identifier in id_encoding["identifiers"]}
|
||||
if len(prefixes) != 1:
|
||||
fail(f"{encoding_name} has an ambiguous encoding prefix")
|
||||
prefix = prefixes.pop()
|
||||
id_mask = id_encoding["identifier_mask"] & 0xFFFFFFFF
|
||||
opcode = variant["opcode"]
|
||||
if "OP" in fields:
|
||||
op_mask, op_bits = place(opcode, fields["OP"])
|
||||
elif opcode == 0:
|
||||
op_mask = op_bits = 0
|
||||
else:
|
||||
fail(f"{encoding_name} has no OP field for opcode {opcode}")
|
||||
# The identifier mask can add selector bits beyond ENCODING and OP,
|
||||
# such as the FLAT segment field. Take them from the listed identifier.
|
||||
# MTBUF keeps one opcode bit in the second dword, which the
|
||||
# first-dword identifiers cannot express; carry it separately.
|
||||
low = 0xFFFFFFFF
|
||||
candidates = sorted({
|
||||
identifier & 0xFFFFFFFF for identifier in id_encoding["identifiers"]
|
||||
if identifier & (prefix_mask | op_mask) & low == (prefix | op_bits) & low
|
||||
})
|
||||
if len(candidates) != 1:
|
||||
fail(f"{variant['instruction']} matches {len(candidates)} {encoding_name} identifiers")
|
||||
forms.append({
|
||||
"name": variant["instruction"],
|
||||
"encoding": BASE_ENCODINGS[encoding_name],
|
||||
"opcode": opcode,
|
||||
# Opcode bits outside the identifier mask (MIMG bit 0, MTBUF bit 53)
|
||||
# still select the instruction.
|
||||
"mask": id_mask | op_mask,
|
||||
"bits": (candidates[0] & id_mask) | op_bits,
|
||||
"bytes": encoding["bits"] // 8,
|
||||
"flags": variant["flags"],
|
||||
"group": variant["group"],
|
||||
"extensions": sorted(extensions.get((variant["instruction"], encoding_name), ())),
|
||||
"operands": variant["operands"],
|
||||
})
|
||||
|
||||
by_pattern = {}
|
||||
for form in forms:
|
||||
if form["bits"] & ~form["mask"]:
|
||||
fail(f"{form['name']} has identifying bits outside its mask")
|
||||
key = (form["mask"], form["bits"])
|
||||
if key in by_pattern:
|
||||
fail(f"{form['name']} and {by_pattern[key]['name']} share an encoding")
|
||||
by_pattern[key] = form
|
||||
for left in forms:
|
||||
for right in forms:
|
||||
if left is right or left["mask"] == right["mask"]:
|
||||
continue
|
||||
common = left["mask"] & right["mask"]
|
||||
if (left["bits"] ^ right["bits"]) & common == 0:
|
||||
fail(f"{left['name']} ({left['encoding']}) overlaps {right['name']} ({right['encoding']})")
|
||||
forms.sort(key=lambda form: (form["encoding"], form["opcode"]))
|
||||
return source, encodings, forms
|
||||
|
||||
|
||||
def rust_from_snapshot(snapshot):
|
||||
source, encodings, forms = forms_from_snapshot(snapshot)
|
||||
out = []
|
||||
emit = out.append
|
||||
emit("// Generated by crates/isa/generate_rdna2_meta.py from crates/isa/data/rdna2.jsonl. Do not edit.")
|
||||
emit(f"// Source: AMD RDNA 2 XML, {source['release']}, schema {source['xml_schema']}, SHA-256 {source['sha256']}.")
|
||||
emit(f"// {source['copyright']}")
|
||||
emit("// SPDX-License-Identifier: MIT")
|
||||
emit("")
|
||||
emit("use super::meta::{EncodingFamily, Extensions, FieldLayout, Form, FormFlags, OperandInfo};")
|
||||
emit("")
|
||||
emit(f'/// SHA-256 of the AMD XML the table was generated from.\npub const SOURCE_SHA256: &str = "{source["sha256"]}";')
|
||||
emit("")
|
||||
|
||||
operand_sets = {}
|
||||
for form in forms:
|
||||
operand_sets.setdefault(json.dumps(form["operands"]), len(operand_sets))
|
||||
emit("static OPERANDS: [&[OperandInfo]; %d] = [" % len(operand_sets))
|
||||
for operands_json in operand_sets:
|
||||
operands = json.loads(operands_json)
|
||||
items = ", ".join(
|
||||
"OperandInfo { field: %s, format: %s, kind: %s, bits: %d, input: %s, output: %s, implicit: %s, encoded: %s }"
|
||||
% (json.dumps(field), json.dumps(data_format), json.dumps(kind), size,
|
||||
str(i).lower(), str(o).lower(), str(implicit).lower(), str(encoded).lower())
|
||||
for field, data_format, kind, size, i, o, implicit, encoded in operands
|
||||
)
|
||||
emit(f" &[{items}],")
|
||||
emit("];")
|
||||
emit("")
|
||||
|
||||
families = sorted({form["encoding"] for form in forms})
|
||||
emit("/// Field layouts of each base encoding, as (bit offset, bit count) pieces from least significant.")
|
||||
emit("pub static FIELDS: [(EncodingFamily, &[FieldLayout]); %d] = [" % len(families))
|
||||
reverse = {value: key for key, value in BASE_ENCODINGS.items()}
|
||||
for family in families:
|
||||
fields = encodings[reverse[family]]["fields"]
|
||||
items = ", ".join(
|
||||
"FieldLayout { name: %s, pieces: &[%s] }" % (json.dumps(name), ", ".join(f"({o}, {c})" for o, c in ranges))
|
||||
for name, ranges in fields
|
||||
)
|
||||
emit(f" (EncodingFamily::{family}, &[{items}]),")
|
||||
emit("];")
|
||||
emit("")
|
||||
|
||||
flag_bits = {
|
||||
"IsBranch": 1,
|
||||
"IsConditionalBranch": 2,
|
||||
"IsIndirectBranch": 4,
|
||||
"IsProgramTerminator": 8,
|
||||
"IsImmediatelyExecuted": 16,
|
||||
}
|
||||
extension_bits = {"literal": 1, "always_literal": 2, "sdwa": 4, "dpp8": 8, "dpp16": 16, "nsa": 32}
|
||||
emit("/// Every gfx1030 base instruction form in the AMD XML, sorted by encoding family and opcode.")
|
||||
emit("pub static FORMS: [Form; %d] = [" % len(forms))
|
||||
for form in forms:
|
||||
flags = sum(flag_bits[flag] for flag in form["flags"])
|
||||
extensions = sum(extension_bits[item] for item in form["extensions"])
|
||||
emit(
|
||||
" Form { name: %s, family: EncodingFamily::%s, opcode: %d, mask: 0x%016x, bits: 0x%016x, bytes: %d, "
|
||||
"flags: FormFlags(0x%02x), extensions: Extensions(0x%02x), group: %s, operands: OPERANDS[%d] },"
|
||||
% (json.dumps(form["name"]), form["encoding"], form["opcode"], form["mask"], form["bits"], form["bytes"],
|
||||
flags, extensions, json.dumps(form["group"]), operand_sets[json.dumps(form["operands"])])
|
||||
)
|
||||
emit("];")
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def compare(path, expected):
|
||||
actual = path.read_text() if path.exists() else ""
|
||||
if actual != expected:
|
||||
print(f"{path.relative_to(ROOT)} is out of date; rerun crates/isa/generate_rdna2_meta.py", file=sys.stderr)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--xml", type=Path, help="approved amdgpu_isa_rdna2.xml; regenerates the snapshot too")
|
||||
parser.add_argument("--check", action="store_true", help="fail when committed outputs differ")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.xml:
|
||||
snapshot = snapshot_from_xml(args.xml.read_bytes())
|
||||
elif SNAPSHOT.exists():
|
||||
snapshot = SNAPSHOT.read_text()
|
||||
else:
|
||||
fail("no snapshot; pass --xml")
|
||||
rust = rust_from_snapshot(snapshot)
|
||||
if args.check:
|
||||
ok = compare(RUST, rust)
|
||||
if args.xml:
|
||||
ok = compare(SNAPSHOT, snapshot) and ok
|
||||
raise SystemExit(0 if ok else 1)
|
||||
SNAPSHOT.parent.mkdir(parents=True, exist_ok=True)
|
||||
SNAPSHOT.write_text(snapshot)
|
||||
RUST.write_text(rust)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+960
@@ -0,0 +1,960 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate the declarative gfx1030 semantic registry and generate its Rust tables.
|
||||
|
||||
validate check crates/isa/semantics/rdna2.toml against its closed vocabulary
|
||||
and the pinned AMD XML snapshot (crates/isa/data/rdna2.jsonl)
|
||||
generate validate, then write crates/isa/src/semantics_gen.rs
|
||||
--check validate and regenerate in memory; exit 1 if the committed file
|
||||
differs. Never writes.
|
||||
|
||||
The registry is data only. Behaviour is chosen from a closed set of primitives
|
||||
(crates/isa/src/primitive.rs) by the declared operation, signedness and SCC
|
||||
effect, never from a mnemonic. Only the Python standard library is used
|
||||
(tomllib needs Python 3.11 or newer). See docs/shaders/semantic-registry.md.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
import tomllib
|
||||
except ModuleNotFoundError: # pragma: no cover - depends on the interpreter
|
||||
sys.exit("generate_semantics.py needs Python 3.11 or newer (tomllib)")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
REGISTRY = ROOT / "crates/isa/semantics/rdna2.toml"
|
||||
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
|
||||
RUST = ROOT / "crates/isa/src/semantics_gen.rs"
|
||||
|
||||
SCHEMA = 1
|
||||
ARCHITECTURE = "gfx1030"
|
||||
|
||||
FORM_KEYS = {
|
||||
"name", "family", "opcode", "variant", "operation", "signedness", "carry_in",
|
||||
"width", "scc", "vcc", "exec", "wave", "operands", "spec", "verify",
|
||||
}
|
||||
TOP_KEYS = {"schema", "architecture", "source_sha256", "documents", "operand_rules", "form"}
|
||||
|
||||
OPERATIONS = {
|
||||
"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor",
|
||||
"andn2": "AndNot", "orn2": "OrNot", "nand": "Nand", "nor": "Nor", "xnor": "Xnor",
|
||||
"lshl": "ShiftLeft", "lshr": "LogicalShiftRight", "ashr": "ArithmeticShiftRight",
|
||||
"compare": "Compare",
|
||||
"not": "Not", "brev": "ReverseBits", "bcnt0": "CountZeros", "bcnt1": "CountOnes",
|
||||
"ff0": "FindFirstZero", "ff1": "FindFirstOne", "flbit": "FindLastBit",
|
||||
"sext": "SignExtend", "abs": "Absolute",
|
||||
"min": "Minimum", "max": "Maximum", "cselect": "Select", "bfm": "BitfieldMask",
|
||||
"mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract",
|
||||
"absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd",
|
||||
"mul24": "Multiply24", "mul_hi24": "MultiplyHigh24",
|
||||
}
|
||||
# Unary operations read one source; they need an operand rule of the unary kind.
|
||||
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
|
||||
# Sign extension reads only the low source_bits of S0 (required for sext only).
|
||||
SOURCE_BITS_KEY = "source_bits"
|
||||
SOURCE_BITS = {8, 16}
|
||||
# Compares take a relation (S0 on the left) and set SCC to whether it holds.
|
||||
RELATION_KEY = "relation"
|
||||
RELATIONS = {
|
||||
"eq": "Equal", "lg": "NotEqual", "gt": "Greater", "ge": "GreaterOrEqual",
|
||||
"lt": "Less", "le": "LessOrEqual",
|
||||
}
|
||||
# (relation, signedness) -> primitive. Equality does not depend on signedness,
|
||||
# so both declared signednesses of EQ and LG share one primitive.
|
||||
COMPARE_PRIMITIVES = {
|
||||
("eq", "signed"): "eq_b32", ("eq", "unsigned"): "eq_b32",
|
||||
("lg", "signed"): "ne_b32", ("lg", "unsigned"): "ne_b32",
|
||||
("gt", "signed"): "gt_i32", ("gt", "unsigned"): "gt_u32",
|
||||
("ge", "signed"): "ge_i32", ("ge", "unsigned"): "ge_u32",
|
||||
("lt", "signed"): "lt_i32", ("lt", "unsigned"): "lt_u32",
|
||||
("le", "signed"): "le_i32", ("le", "unsigned"): "le_u32",
|
||||
}
|
||||
# Logical operations take untyped bits; arithmetic ones never do. Shifts take
|
||||
# the signedness their primitive names, and their S1 is an unsigned count.
|
||||
LOGICAL = {
|
||||
"and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor",
|
||||
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm",
|
||||
}
|
||||
ARITHMETIC = {
|
||||
"add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add", "mul24", "mul_hi24",
|
||||
}
|
||||
SHIFTS = {"lshl", "lshr", "ashr"}
|
||||
# Operations whose S1 is an unsigned control word (a shift count or a bit-field
|
||||
# descriptor), so the XML gives it FMT_NUM_U32 whatever the form's signedness.
|
||||
CONTROL_S1 = SHIFTS | {"bfe"}
|
||||
# Operations that always read SCC: the select condition. They need carry_in scc.
|
||||
SCC_READERS = {"cselect"}
|
||||
# XML number formats a source may have for each declared signedness.
|
||||
SOURCE_FORMATS = {
|
||||
"signed": {"FMT_NUM_I32"},
|
||||
"unsigned": {"FMT_NUM_U32"},
|
||||
"bitwise": {"FMT_NUM_U32", "FMT_NUM_B32"},
|
||||
}
|
||||
# Optional keys: required exactly when the condition holds.
|
||||
SHIFT_KEY = "shift_count_bits"
|
||||
# Shift-and-add declares its fixed S0 shift (required for lshl_add only).
|
||||
SHIFT_AMOUNT_KEY = "shift_amount"
|
||||
SHIFT_AMOUNTS = {1, 2, 3, 4}
|
||||
# Vector forms whose guide pseudocode reads S1 before S0 (D = op(S1, S0))
|
||||
# declare it; the XML records no operand order.
|
||||
SOURCE_ORDER_KEY = "source_order"
|
||||
SOURCE_ORDERS = {"reversed"}
|
||||
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc"}
|
||||
SCC = {
|
||||
"unchanged": "Unchanged",
|
||||
"carry_out": "CarryOut",
|
||||
"borrow": "Borrow",
|
||||
"signed_overflow": "SignedOverflow",
|
||||
"nonzero": "Nonzero",
|
||||
"relation": "Relation",
|
||||
"selected_src0": "SelectedSrc0",
|
||||
}
|
||||
MASK = {"unchanged": "Unchanged"}
|
||||
WAVE = {"any": "Any", "wave32": "Wave32"}
|
||||
# The decoder has no wave-size input at the registry dispatch yet, so a Wave32
|
||||
# restriction could be declared but not enforced. Reject it until it can be.
|
||||
ENFORCED_WAVES = {"any"}
|
||||
EVIDENCE = {
|
||||
"reference": "Reference",
|
||||
"independent": "Independent",
|
||||
"metal": "Metal",
|
||||
"llvm_encoding": "LlvmEncoding",
|
||||
}
|
||||
DOCUMENTS = {"guide": "Guide", "xml": "Xml"}
|
||||
# The public documents spec references may cite, pinned so a citation cannot
|
||||
# silently point at another file.
|
||||
PINNED_DOCUMENTS = {
|
||||
"guide": {
|
||||
"title": "AMD RDNA 2 Instruction Set Architecture Reference Guide",
|
||||
"file": "rdna2-shader-instruction-set-architecture.pdf",
|
||||
"pages": 291,
|
||||
},
|
||||
"xml": {
|
||||
"title": "AMD RDNA 2 machine-readable ISA (pinned XML)",
|
||||
"file": "amdgpu_isa_rdna2.xml",
|
||||
},
|
||||
}
|
||||
WIDTHS = {32}
|
||||
|
||||
# (operation, signedness) -> (required SCC effect, primitive, takes carry-in).
|
||||
# A form whose declaration is not a row here has no primitive and is rejected.
|
||||
PRIMITIVES = {
|
||||
("add", "unsigned"): ("carry_out", "add_carry_u32", True),
|
||||
("sub", "unsigned"): ("borrow", "sub_borrow_u32", True),
|
||||
("add", "signed"): ("signed_overflow", "add_overflow_i32", False),
|
||||
("sub", "signed"): ("signed_overflow", "sub_overflow_i32", False),
|
||||
("and", "bitwise"): ("nonzero", "and_nonzero_b32", False),
|
||||
("or", "bitwise"): ("nonzero", "or_nonzero_b32", False),
|
||||
("xor", "bitwise"): ("nonzero", "xor_nonzero_b32", False),
|
||||
("andn2", "bitwise"): ("nonzero", "andn2_nonzero_b32", False),
|
||||
("orn2", "bitwise"): ("nonzero", "orn2_nonzero_b32", False),
|
||||
("nand", "bitwise"): ("nonzero", "nand_nonzero_b32", False),
|
||||
("nor", "bitwise"): ("nonzero", "nor_nonzero_b32", False),
|
||||
("xnor", "bitwise"): ("nonzero", "xnor_nonzero_b32", False),
|
||||
("lshl", "bitwise"): ("nonzero", "lshl_nonzero_b32", False),
|
||||
("lshr", "unsigned"): ("nonzero", "lshr_nonzero_b32", False),
|
||||
("ashr", "signed"): ("nonzero", "ashr_nonzero_i32", False),
|
||||
("not", "bitwise"): ("nonzero", "not_nonzero_b32", False),
|
||||
("brev", "bitwise"): ("unchanged", "brev_b32", False),
|
||||
("bcnt0", "bitwise"): ("nonzero", "bcnt0_nonzero_b32", False),
|
||||
("bcnt1", "bitwise"): ("nonzero", "bcnt1_nonzero_b32", False),
|
||||
("ff0", "bitwise"): ("unchanged", "ff0_b32", False),
|
||||
("ff1", "bitwise"): ("unchanged", "ff1_b32", False),
|
||||
("flbit", "bitwise"): ("unchanged", "flbit_b32", False),
|
||||
("flbit", "signed"): ("unchanged", "flbit_i32", False),
|
||||
("sext", "signed"): ("unchanged", "sext_i32", False),
|
||||
("abs", "signed"): ("nonzero", "abs_nonzero_i32", False),
|
||||
("min", "signed"): ("selected_src0", "min_i32", False),
|
||||
("min", "unsigned"): ("selected_src0", "min_u32", False),
|
||||
("max", "signed"): ("selected_src0", "max_i32", False),
|
||||
("max", "unsigned"): ("selected_src0", "max_u32", False),
|
||||
("cselect", "bitwise"): ("unchanged", "cselect_b32", True),
|
||||
("bfm", "bitwise"): ("unchanged", "bfm_b32", False),
|
||||
("mul", "signed"): ("unchanged", "mul_lo_i32", False),
|
||||
("mul_hi", "unsigned"): ("unchanged", "mul_hi_u32", False),
|
||||
("mul_hi", "signed"): ("unchanged", "mul_hi_i32", False),
|
||||
("bfe", "unsigned"): ("nonzero", "bfe_nonzero_u32", False),
|
||||
("bfe", "signed"): ("nonzero", "bfe_nonzero_i32", False),
|
||||
("absdiff", "signed"): ("nonzero", "absdiff_nonzero_i32", False),
|
||||
("lshl_add", "unsigned"): ("carry_out", "lshl_add_carry_u32", False),
|
||||
}
|
||||
|
||||
# Vector (VOP2) forms: (operation, signedness) -> the per-lane VectorBinary their
|
||||
# MSL lowering uses. They write no SCC, VCC or EXEC, so scc must be unchanged.
|
||||
VECTOR_PRIMITIVES = {
|
||||
("add", "unsigned"): "Add",
|
||||
("sub", "unsigned"): "Sub",
|
||||
("xnor", "bitwise"): "Xnor",
|
||||
("min", "signed"): "MinSigned",
|
||||
("min", "unsigned"): "MinUnsigned",
|
||||
("max", "signed"): "MaxSigned",
|
||||
("max", "unsigned"): "MaxUnsigned",
|
||||
("mul24", "signed"): "Mul24Signed",
|
||||
("mul24", "unsigned"): "Mul24Unsigned",
|
||||
("mul_hi24", "signed"): "MulHi24Signed",
|
||||
("mul_hi24", "unsigned"): "MulHi24Unsigned",
|
||||
}
|
||||
|
||||
# Operand rules the decoder implements, each exactly once. A registry rule must
|
||||
# match one of these shapes; anything else is an unimplemented rule.
|
||||
UNSUPPORTED_COMBOS = {
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", "src_vcc", "src_exec",
|
||||
"src_m0", "src_ttmp", "src_float_inline", "src_special", "two_literals",
|
||||
}
|
||||
# Every combo name a rule may list (VOP2 also names vcc_hi and NULL sources,
|
||||
# which SOP2 groups under src_vcc and src_special).
|
||||
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"}
|
||||
OPERAND_RULES = {
|
||||
"sop2_sgpr": {
|
||||
"rust": "Sop2Sgpr",
|
||||
"enum": "ScalarAluOp",
|
||||
"shape": {
|
||||
"family": "SOP2",
|
||||
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
"src": [
|
||||
{"field": "SSRC0", "class": "scalar_source"},
|
||||
{"field": "SSRC1", "class": "scalar_source"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# Every one of these is rejected by the decoder's SOP2 operand checks.
|
||||
"unsupported": UNSUPPORTED_COMBOS,
|
||||
"kind": "alu",
|
||||
},
|
||||
"sopc_scalar": {
|
||||
"rust": "SopcScalar",
|
||||
"enum": "ScalarCompareOp",
|
||||
"shape": {
|
||||
"family": "SOPC",
|
||||
"src": [
|
||||
{"field": "SSRC0", "class": "scalar_source"},
|
||||
{"field": "SSRC1", "class": "scalar_source"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# SOPC has no destination field; the decoder rejects these sources.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if not combo.startswith("dst_")},
|
||||
"kind": "compare",
|
||||
},
|
||||
"sop1_sgpr": {
|
||||
"rust": "Sop1Sgpr",
|
||||
"enum": "ScalarUnaryOp",
|
||||
"shape": {
|
||||
"family": "SOP1",
|
||||
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
"src": [{"field": "SSRC0", "class": "scalar_source"}],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# One source, so two literals cannot occur; the rest are rejected.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
|
||||
"kind": "unary",
|
||||
},
|
||||
"vop2_vgpr": {
|
||||
"rust": "Vop2Vgpr",
|
||||
"enum": "VectorAluOp",
|
||||
"shape": {
|
||||
"family": "VOP2",
|
||||
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vector_source"},
|
||||
{"field": "VSRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# vector_source = VGPR, s0-s105, vcc_lo, inline integer -16..64 or a
|
||||
# literal; the decoder rejects these SRC0 selectors.
|
||||
"unsupported": {
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
|
||||
"src_special",
|
||||
},
|
||||
"kind": "vector",
|
||||
},
|
||||
}
|
||||
|
||||
VARIANT = re.compile(r"^[A-Z][A-Za-z0-9]*$")
|
||||
RESERVED_VARIANTS = {"Self", "ALL"}
|
||||
U16_MAX = 0xFFFF
|
||||
NAME = re.compile(r"^[A-Z][A-Z0-9_]*$")
|
||||
SECTION = re.compile(r"^[0-9]+(\.[0-9]+)*$")
|
||||
|
||||
|
||||
def load_registry(path=REGISTRY):
|
||||
"""Parse the TOML registry into a dict."""
|
||||
with open(path, "rb") as handle:
|
||||
return tomllib.load(handle)
|
||||
|
||||
|
||||
def load_snapshot(path=SNAPSHOT):
|
||||
"""Index the normalised XML snapshot: source line, encodings, default variants."""
|
||||
source = None
|
||||
encodings = {}
|
||||
variants = {}
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
record = json.loads(line)
|
||||
kind = record.get("kind")
|
||||
if kind == "source":
|
||||
source = record
|
||||
elif kind == "encoding":
|
||||
encodings[record["name"]] = record
|
||||
elif kind == "variant" and record.get("condition") == "default":
|
||||
variants[(record["instruction"], record["encoding"])] = record
|
||||
return {"source": source or {}, "encodings": encodings, "variants": variants}
|
||||
|
||||
|
||||
def _family_encoding(family):
|
||||
return "ENC_" + family
|
||||
|
||||
|
||||
def _rust_family(family):
|
||||
return family[0] + family[1:].lower()
|
||||
|
||||
|
||||
def _check_rule(name, rule, errors):
|
||||
implemented = OPERAND_RULES.get(name)
|
||||
if implemented is None:
|
||||
errors.append(f"operand rule {name}: not implemented by the decoder")
|
||||
return
|
||||
unsupported = rule.get("unsupported", [])
|
||||
unknown = sorted(set(unsupported) - ALL_COMBOS)
|
||||
if unknown:
|
||||
errors.append(f"operand rule {name}: unknown unsupported combos {unknown}")
|
||||
if len(set(unsupported)) != len(unsupported):
|
||||
errors.append(f"operand rule {name}: duplicate unsupported combos")
|
||||
if set(unsupported) != implemented["unsupported"]:
|
||||
errors.append(
|
||||
f"operand rule {name}: unsupported combos differ from those the decoder rejects"
|
||||
)
|
||||
declared = {key: value for key, value in rule.items() if key != "unsupported"}
|
||||
if declared != implemented["shape"]:
|
||||
errors.append(
|
||||
f"operand rule {name}: declaration differs from the decoder's implemented rule"
|
||||
)
|
||||
|
||||
|
||||
def _check_xml(form, rule, snapshot, errors):
|
||||
label = form["name"]
|
||||
encoding_name = _family_encoding(form["family"])
|
||||
encoding = snapshot["encodings"].get(encoding_name)
|
||||
if encoding is None:
|
||||
errors.append(f"{label}: family {form['family']} has no XML encoding {encoding_name}")
|
||||
return
|
||||
variant = snapshot["variants"].get((form["name"], encoding_name))
|
||||
if variant is None:
|
||||
errors.append(f"{label}: no default {encoding_name} variant in the XML snapshot")
|
||||
return
|
||||
if variant["opcode"] != form["opcode"]:
|
||||
errors.append(
|
||||
f"{label}: opcode {form['opcode']} disagrees with the XML opcode {variant['opcode']}"
|
||||
)
|
||||
if _identifier(encoding, form["opcode"]) not in encoding["identifiers"]:
|
||||
errors.append(f"{label}: opcode {form['opcode']} is not an identifier of {encoding_name}")
|
||||
operands = {}
|
||||
scc_in = scc_out = False
|
||||
implicit = set()
|
||||
for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]:
|
||||
if kind == "OPR_SSRC_SPECIAL_SCC":
|
||||
scc_in |= is_input
|
||||
scc_out |= is_output
|
||||
elif field:
|
||||
operands[field] = (data_format, size, is_input, is_output)
|
||||
else:
|
||||
implicit.add(kind)
|
||||
# The vocabulary can state only SCC effects (vcc and exec are "unchanged"),
|
||||
# so any other implicit XML operand, such as VCC, is undeclared.
|
||||
if implicit:
|
||||
errors.append(f"{label}: XML implicit operands {sorted(implicit)} are not declared")
|
||||
if scc_in != (form["carry_in"] == "scc"):
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts the XML SCC input")
|
||||
if scc_out != (form["scc"] != "unchanged"):
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts the XML SCC output")
|
||||
if rule is None:
|
||||
return
|
||||
if not isinstance(rule.get("src"), list) or not all(
|
||||
isinstance(src, dict) and isinstance(src.get("field"), str) for src in rule["src"]
|
||||
) or ("dst" in rule and not (isinstance(rule["dst"], dict) and "field" in rule["dst"])):
|
||||
return # the rule check already reported the malformed shape
|
||||
fields = [(rule["dst"]["field"], False)] if "dst" in rule else []
|
||||
fields += [(src["field"], True) for src in rule["src"]]
|
||||
shift = form["operation"] in CONTROL_S1 and len(rule["src"]) > 1
|
||||
count_field = rule["src"][1]["field"] if shift else None
|
||||
for field, is_source in fields:
|
||||
if field not in operands:
|
||||
errors.append(f"{label}: XML has no operand {field}")
|
||||
continue
|
||||
data_format, size, is_input, is_output = operands[field]
|
||||
bits = form.get(SOURCE_BITS_KEY) if is_source else None
|
||||
expected = bits if type(bits) is int else form["width"]
|
||||
if size != expected:
|
||||
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
|
||||
if (is_input, is_output) != (is_source, not is_source):
|
||||
errors.append(f"{label}: {field} direction disagrees with the XML")
|
||||
if field == count_field:
|
||||
if data_format != "FMT_NUM_U32":
|
||||
errors.append(
|
||||
f"{label}: control operand {field} has XML format {data_format}, not FMT_NUM_U32"
|
||||
)
|
||||
elif type(bits) is int:
|
||||
if data_format != f"FMT_NUM_I{bits}":
|
||||
errors.append(f"{label}: {field} has XML format {data_format}, not FMT_NUM_I{bits}")
|
||||
elif is_source and data_format not in SOURCE_FORMATS.get(form["signedness"], ()):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
|
||||
)
|
||||
extra = sorted(set(operands) - {field for field, _ in fields})
|
||||
if extra:
|
||||
errors.append(f"{label}: XML operands {extra} are not covered by rule {form['operands']}")
|
||||
|
||||
|
||||
def _identifier(encoding, opcode):
|
||||
fields = dict((name, ranges) for name, ranges in encoding["fields"])
|
||||
(offset, size), = fields["OP"]
|
||||
base = encoding["identifiers"][0] & ~(((1 << size) - 1) << offset)
|
||||
return base | (opcode << offset)
|
||||
|
||||
|
||||
def validate(registry, snapshot):
|
||||
"""Return every error in the registry; an empty list means it is valid."""
|
||||
errors = []
|
||||
unknown = sorted(set(registry) - TOP_KEYS)
|
||||
if unknown:
|
||||
errors.append(f"unknown top-level keys {unknown}")
|
||||
if type(registry.get("schema")) is not int or registry["schema"] != SCHEMA:
|
||||
errors.append(f"schema {registry.get('schema')!r} is not {SCHEMA}")
|
||||
if registry.get("architecture") != ARCHITECTURE:
|
||||
errors.append(f"architecture {registry.get('architecture')!r} is not {ARCHITECTURE}")
|
||||
if registry.get("source_sha256") != snapshot["source"].get("sha256"):
|
||||
errors.append("source_sha256 does not match the XML snapshot")
|
||||
documents = registry.get("documents", {})
|
||||
for name, document in documents.items():
|
||||
if name not in DOCUMENTS:
|
||||
errors.append(f"unknown document {name}")
|
||||
elif document != PINNED_DOCUMENTS[name]:
|
||||
errors.append(f"document {name}: differs from the pinned public document")
|
||||
if "guide" not in documents:
|
||||
errors.append("the guide document is not declared")
|
||||
rules = registry.get("operand_rules", {})
|
||||
for name, rule in rules.items():
|
||||
_check_rule(name, rule, errors)
|
||||
forms = registry.get("form", [])
|
||||
if not forms:
|
||||
errors.append("the registry declares no forms")
|
||||
seen = {"name": set(), "opcode": set(), "variant": set()}
|
||||
for index, form in enumerate(forms):
|
||||
label = form.get("name", f"form #{index}")
|
||||
missing = sorted(FORM_KEYS - set(form))
|
||||
extra = sorted(
|
||||
set(form) - FORM_KEYS
|
||||
- {SHIFT_KEY, SHIFT_AMOUNT_KEY, RELATION_KEY, SOURCE_BITS_KEY, SOURCE_ORDER_KEY}
|
||||
)
|
||||
if missing:
|
||||
errors.append(f"{label}: incomplete, missing {missing}")
|
||||
if extra:
|
||||
errors.append(f"{label}: unknown keys {extra}")
|
||||
if missing:
|
||||
continue
|
||||
for key, vocabulary in (
|
||||
("operation", OPERATIONS), ("signedness", SIGNEDNESS), ("carry_in", CARRY_IN),
|
||||
("scc", SCC), ("vcc", MASK), ("exec", MASK), ("wave", WAVE),
|
||||
):
|
||||
if form[key] not in vocabulary:
|
||||
errors.append(f"{label}: unknown {key} {form[key]!r}")
|
||||
if not isinstance(form["name"], str) or not NAME.match(form["name"]):
|
||||
errors.append(f"{label}: invalid name")
|
||||
if not isinstance(form["variant"], str) or not VARIANT.match(form["variant"]):
|
||||
errors.append(f"{label}: invalid variant {form['variant']!r}")
|
||||
if form["variant"] in RESERVED_VARIANTS:
|
||||
errors.append(f"{label}: variant {form['variant']!r} is reserved")
|
||||
if type(form["opcode"]) is not int or not 0 <= form["opcode"] <= U16_MAX:
|
||||
errors.append(f"{label}: invalid opcode")
|
||||
if form["wave"] in WAVE and form["wave"] not in ENFORCED_WAVES:
|
||||
errors.append(f"{label}: wave {form['wave']} has no decoder enforcement yet")
|
||||
if type(form["width"]) is not int or form["width"] not in WIDTHS:
|
||||
errors.append(f"{label}: width {form['width']} is not supported")
|
||||
for key, value in (
|
||||
("name", form["name"]),
|
||||
("opcode", (form["family"], form["opcode"])),
|
||||
# Variants are names in their operand rule's enum.
|
||||
("variant", (_rule_enum(form), form["variant"])),
|
||||
):
|
||||
if value in seen[key]:
|
||||
shown = form["variant"] if key == "variant" else value
|
||||
errors.append(f"{label}: duplicate {key} {shown}")
|
||||
seen[key].add(value)
|
||||
if (form["operation"] in LOGICAL and form["signedness"] != "bitwise") or (
|
||||
form["operation"] in ARITHMETIC and form["signedness"] == "bitwise"
|
||||
):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts operation {form['operation']}"
|
||||
)
|
||||
if form["operation"] in SHIFTS:
|
||||
bits = form.get(SHIFT_KEY)
|
||||
if type(bits) is not int or not 0 < bits < 32 or (1 << bits) != form["width"]:
|
||||
errors.append(
|
||||
f"{label}: {SHIFT_KEY} must be log2 of the width ({form['width']}), got {bits!r}"
|
||||
)
|
||||
elif SHIFT_KEY in form:
|
||||
errors.append(f"{label}: {SHIFT_KEY} on a non-shift operation")
|
||||
if form["operation"] == "lshl_add":
|
||||
amount = form.get(SHIFT_AMOUNT_KEY)
|
||||
if type(amount) is not int or amount not in SHIFT_AMOUNTS:
|
||||
errors.append(
|
||||
f"{label}: {SHIFT_AMOUNT_KEY} must be one of {sorted(SHIFT_AMOUNTS)}, got {amount!r}"
|
||||
)
|
||||
elif SHIFT_AMOUNT_KEY in form:
|
||||
errors.append(f"{label}: {SHIFT_AMOUNT_KEY} on a non-lshl_add operation")
|
||||
if SOURCE_ORDER_KEY in form:
|
||||
order = form[SOURCE_ORDER_KEY]
|
||||
if not isinstance(order, str) or order not in SOURCE_ORDERS:
|
||||
errors.append(f"{label}: unknown {SOURCE_ORDER_KEY} {order!r}")
|
||||
elif _rule_kind(form) != "vector":
|
||||
errors.append(f"{label}: {SOURCE_ORDER_KEY} on a non-vector form")
|
||||
if form["operation"] in SCC_READERS and form["carry_in"] != "scc":
|
||||
errors.append(f"{label}: operation {form['operation']} reads SCC (requires carry_in scc)")
|
||||
if form["operation"] == "sext":
|
||||
bits = form.get(SOURCE_BITS_KEY)
|
||||
if type(bits) is not int or bits not in SOURCE_BITS:
|
||||
errors.append(f"{label}: {SOURCE_BITS_KEY} must be one of {sorted(SOURCE_BITS)}, got {bits!r}")
|
||||
elif SOURCE_BITS_KEY in form:
|
||||
errors.append(f"{label}: {SOURCE_BITS_KEY} on a non-sext operation")
|
||||
if form["operation"] == "compare":
|
||||
relation = form.get(RELATION_KEY)
|
||||
if not isinstance(relation, str) or relation not in RELATIONS:
|
||||
errors.append(f"{label}: unknown or missing {RELATION_KEY} {relation!r}")
|
||||
elif (relation, form["signedness"]) not in COMPARE_PRIMITIVES:
|
||||
errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}")
|
||||
if form["scc"] != "relation":
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts compare (requires relation)")
|
||||
if form["carry_in"] != "none":
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
|
||||
primitive = ("relation", None, False)
|
||||
elif _rule_kind(form) == "vector":
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
lowering = VECTOR_PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
primitive = None if lowering is None else ("unchanged", lowering, False)
|
||||
else:
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
if primitive is None:
|
||||
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
|
||||
else:
|
||||
scc, _, takes_carry = primitive
|
||||
if form["scc"] != scc:
|
||||
errors.append(
|
||||
f"{label}: scc {form['scc']} contradicts {form['operation']}/"
|
||||
f"{form['signedness']} (requires {scc})"
|
||||
)
|
||||
if form["carry_in"] == "scc" and not takes_carry:
|
||||
errors.append(f"{label}: carry_in scc contradicts {form['operation']}/{form['signedness']}")
|
||||
rule = rules.get(form["operands"])
|
||||
if rule is None:
|
||||
errors.append(f"{label}: unknown operand rule {form['operands']!r}")
|
||||
elif rule.get("family") != form["family"]:
|
||||
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
|
||||
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
|
||||
"compare" if form["operation"] == "compare"
|
||||
else "unary" if form["operation"] in UNARY
|
||||
else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY
|
||||
else "alu"
|
||||
):
|
||||
errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}")
|
||||
_check_spec(label, form["spec"], documents, errors)
|
||||
verify = form["verify"]
|
||||
if not verify:
|
||||
errors.append(f"{label}: no verification requirement")
|
||||
if any(item not in EVIDENCE for item in verify):
|
||||
errors.append(f"{label}: unknown verification requirement in {verify}")
|
||||
if len(set(verify)) != len(verify):
|
||||
errors.append(f"{label}: duplicate verification requirement")
|
||||
_check_xml(form, rule, snapshot, errors)
|
||||
return errors
|
||||
|
||||
|
||||
def _implemented_rule(form):
|
||||
operands = form.get("operands")
|
||||
return OPERAND_RULES.get(operands) if isinstance(operands, str) else None
|
||||
|
||||
|
||||
def _rule_kind(form):
|
||||
"""The implemented kind of the form's operand rule, or None if unknown."""
|
||||
rule = _implemented_rule(form)
|
||||
return rule["kind"] if rule else None
|
||||
|
||||
|
||||
def _rule_enum(form):
|
||||
"""The generated enum of the form's operand rule, or None if unknown."""
|
||||
rule = _implemented_rule(form)
|
||||
return rule["enum"] if rule else None
|
||||
|
||||
|
||||
def _check_spec(label, spec, documents, errors):
|
||||
has_guide = False
|
||||
for ref in spec:
|
||||
if set(ref) != {"document", "section", "page"}:
|
||||
errors.append(f"{label}: spec reference needs exactly document, section, page")
|
||||
continue
|
||||
if ref["document"] not in documents:
|
||||
errors.append(f"{label}: spec cites undeclared document {ref['document']!r}")
|
||||
if not SECTION.match(str(ref["section"])):
|
||||
errors.append(f"{label}: invalid spec section {ref['section']!r}")
|
||||
if type(ref["page"]) is not int or not 0 <= ref["page"] <= U16_MAX:
|
||||
errors.append(f"{label}: invalid spec page")
|
||||
if ref["document"] == "guide" and type(ref["page"]) is int and ref["page"] > 0:
|
||||
has_guide = True
|
||||
if not has_guide:
|
||||
errors.append(f"{label}: missing a guide section and page reference")
|
||||
|
||||
|
||||
def render(registry, snapshot):
|
||||
"""Return the complete generated Rust source. Requires a valid registry."""
|
||||
forms = registry["form"]
|
||||
rule_names = sorted({form["operands"] for form in forms})
|
||||
positions = {form["name"]: position for position, form in enumerate(forms)}
|
||||
out = [
|
||||
"// @generated by crates/isa/generate_semantics.py from crates/isa/semantics/rdna2.toml.",
|
||||
"// Do not edit. Regenerate: python3 crates/isa/generate_semantics.py generate",
|
||||
"",
|
||||
"use crate::meta::EncodingFamily;",
|
||||
"use crate::primitive;",
|
||||
"use crate::semantics::{",
|
||||
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
|
||||
" Signedness, SpecRef, VectorBinary, Wave,",
|
||||
"};",
|
||||
"use crate::CompareRelation;",
|
||||
"",
|
||||
"/// Registry schema of the generated tables.",
|
||||
f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};",
|
||||
]
|
||||
for rule_name in rule_names:
|
||||
selected = [form for form in forms if form["operands"] == rule_name]
|
||||
out += _render_enum(rule_name, selected, snapshot, positions)
|
||||
out += [
|
||||
"",
|
||||
"/// Identity of every registry form, in registry order.",
|
||||
f"pub const FORM_IDS: [(&str, EncodingFamily); {len(forms)}] = [",
|
||||
]
|
||||
for form in forms:
|
||||
out.append(f" (\"{form['name']}\", EncodingFamily::{_rust_family(form['family'])}),")
|
||||
out += [
|
||||
"];",
|
||||
"",
|
||||
"/// One validated row per registry form, in registry order.",
|
||||
f"pub static FORMS: [FormSemantics; {len(forms)}] = [",
|
||||
]
|
||||
for form in forms:
|
||||
spec = ", ".join(
|
||||
f"SpecRef {{ document: Document::{DOCUMENTS[ref['document']]}, "
|
||||
f"section: \"{ref['section']}\", page: {ref['page']} }}"
|
||||
for ref in form["spec"]
|
||||
)
|
||||
verify = ", ".join(f"Evidence::{EVIDENCE[item]}" for item in form["verify"])
|
||||
out += [
|
||||
" FormSemantics {",
|
||||
f" name: \"{form['name']}\",",
|
||||
f" family: EncodingFamily::{_rust_family(form['family'])},",
|
||||
f" opcode: {form['opcode']},",
|
||||
f" operation: Operation::{OPERATIONS[form['operation']]},",
|
||||
f" signedness: Signedness::{SIGNEDNESS[form['signedness']]},",
|
||||
f" carry_in: CarryIn::{CARRY_IN[form['carry_in']]},",
|
||||
f" width: {form['width']},",
|
||||
f" shift_count_bits: {form.get(SHIFT_KEY, 0)},",
|
||||
f" shift_amount: {form.get(SHIFT_AMOUNT_KEY, 0)},",
|
||||
f" swap_sources: {'true' if SOURCE_ORDER_KEY in form else 'false'},",
|
||||
f" source_bits: {form.get(SOURCE_BITS_KEY, form['width'])},",
|
||||
" relation: "
|
||||
+ (f"Some(CompareRelation::{RELATIONS[form[RELATION_KEY]]})," if RELATION_KEY in form else "None,"),
|
||||
f" scc: SccEffect::{SCC[form['scc']]},",
|
||||
f" vcc: MaskEffect::{MASK[form['vcc']]},",
|
||||
f" exec: MaskEffect::{MASK[form['exec']]},",
|
||||
f" wave: Wave::{WAVE[form['wave']]},",
|
||||
f" operands: OperandRule::{OPERAND_RULES[form['operands']]['rust']},",
|
||||
f" spec: &[{spec}],",
|
||||
f" verify: &[{verify}],",
|
||||
" },",
|
||||
]
|
||||
out += ["];", ""]
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _render_enum(rule_name, forms, snapshot, positions):
|
||||
enum = OPERAND_RULES[rule_name]["enum"]
|
||||
kind = OPERAND_RULES[rule_name]["kind"]
|
||||
table = re.sub(r"(?<!^)(?=[A-Z])", "_", enum).upper() + "_BY_OPCODE"
|
||||
family = forms[0]["family"]
|
||||
encoding = snapshot["encodings"][_family_encoding(family)]
|
||||
mask = encoding["identifier_mask"]
|
||||
(offset, size), = dict((name, ranges) for name, ranges in encoding["fields"])["OP"]
|
||||
op_mask = ((1 << size) - 1) << offset
|
||||
fixed_mask = mask & ~op_mask
|
||||
fixed_bits = encoding["identifiers"][0] & fixed_mask
|
||||
# Every identifier of the family must share the fixed bits, or the split
|
||||
# into an encoding test plus an OP match would change which words match.
|
||||
if any(identifier & fixed_mask != fixed_bits for identifier in encoding["identifiers"]) or (
|
||||
mask & op_mask != op_mask
|
||||
):
|
||||
raise ValueError(f"{family}: identifiers do not split into fixed bits and OP")
|
||||
out = [
|
||||
"",
|
||||
f"/// {family} operations declared in the semantic registry (operand rule `{rule_name}`).",
|
||||
"#[derive(Clone, Copy, Debug, Eq, PartialEq)]",
|
||||
f"pub enum {enum} {{",
|
||||
]
|
||||
for form in forms:
|
||||
carry = " plus SCC" if form["carry_in"] == "scc" else ""
|
||||
what = f"compare {form[RELATION_KEY]}" if kind == "compare" else form["operation"]
|
||||
out += [
|
||||
f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): "
|
||||
f"{form['signedness']} {what}{carry}, SCC = {form['scc']}.",
|
||||
f" {form['variant']},",
|
||||
]
|
||||
by_opcode = {form["opcode"]: form["variant"] for form in forms}
|
||||
out += [
|
||||
"}",
|
||||
"",
|
||||
f"/// {enum} by {family} OP field value; `None` for undeclared opcodes.",
|
||||
f"const {table}: [Option<{enum}>; {1 << size}] = [",
|
||||
]
|
||||
out += [
|
||||
f" Some({enum}::{by_opcode[opcode]})," if opcode in by_opcode else " None,"
|
||||
for opcode in range(1 << size)
|
||||
]
|
||||
out += [
|
||||
"];",
|
||||
"",
|
||||
f"impl {enum} {{",
|
||||
" /// Every operation, in registry order.",
|
||||
f" pub const ALL: [Self; {len(forms)}] = [",
|
||||
]
|
||||
out += [f" Self::{form['variant']}," for form in forms]
|
||||
out += [
|
||||
" ];",
|
||||
"",
|
||||
f" /// Selects the operation from a first instruction word: the {family} encoding",
|
||||
f" /// bits (mask 0x{fixed_mask:09_x}) and then the OP field (bits {offset}-{offset + size - 1}).",
|
||||
" pub const fn from_word(word: u32) -> Option<Self> {",
|
||||
f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{",
|
||||
" return None;",
|
||||
" }",
|
||||
f" {table}[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]",
|
||||
" }",
|
||||
"",
|
||||
" /// Lower-case mnemonic.",
|
||||
" pub const fn mnemonic(self) -> &'static str {",
|
||||
" match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => \"{form['name'].lower()}\"," for form in forms]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The validated registry row.",
|
||||
" pub fn semantics(self) -> &'static FormSemantics {",
|
||||
" &FORMS[match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => {positions[form['name']]}," for form in forms]
|
||||
out += [
|
||||
" }]",
|
||||
" }",
|
||||
]
|
||||
if kind == "unary":
|
||||
out += [
|
||||
"",
|
||||
" /// Whether the operation writes SCC.",
|
||||
" pub const fn writes_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
|
||||
" /// unchanged).",
|
||||
" pub const fn evaluate(self, src: u32) -> (u32, Option<bool>) {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
_, function, _ = PRIMITIVES[(form["operation"], form["signedness"])]
|
||||
if form["operation"] == "sext":
|
||||
value = f"primitive::{function}(src, {form[SOURCE_BITS_KEY]})"
|
||||
else:
|
||||
value = f"primitive::{function}(src)"
|
||||
if form["scc"] == "unchanged":
|
||||
out.append(f" Self::{form['variant']} => ({value}, None),")
|
||||
else:
|
||||
out += [
|
||||
f" Self::{form['variant']} => {{",
|
||||
f" let (value, scc) = {value};",
|
||||
" (value, Some(scc))",
|
||||
" }",
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "vector":
|
||||
out += [
|
||||
"",
|
||||
" /// Assembler name of the 32-bit (VOP2) encoding, as LLVM prints it.",
|
||||
" pub const fn assembly_name(self) -> &'static str {",
|
||||
" match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => \"{form['name'].lower()}_e32\"," for form in forms]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The per-lane operation its MSL lowering uses.",
|
||||
" pub const fn lowering(self) -> VectorBinary {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => "
|
||||
f"VectorBinary::{VECTOR_PRIMITIVES[(form['operation'], form['signedness'])]},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Whether the operation reads its sources reversed (`D = op(S1, S0)`).",
|
||||
" pub const fn swaps_sources(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'true' if SOURCE_ORDER_KEY in form else 'false'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "compare":
|
||||
out += [
|
||||
"",
|
||||
" /// The relation tested, with S0 on the left.",
|
||||
" pub const fn relation(self) -> CompareRelation {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => CompareRelation::{RELATIONS[form[RELATION_KEY]]},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The new SCC: whether the relation holds for S0 and S1.",
|
||||
" pub const fn test(self, src0: u32, src1: u32) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])]
|
||||
out.append(f" Self::{form['variant']} => primitive::{function}(src0, src1),")
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
out += [
|
||||
"",
|
||||
" /// Whether the operation reads SCC (carry-in, borrow-in or select condition).",
|
||||
" pub const fn reads_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'true' if form['carry_in'] == 'scc' else 'false'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Whether the operation writes SCC.",
|
||||
" pub const fn writes_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
|
||||
" /// unchanged). `scc_in` is the SCC read by forms that consume it (ignored by",
|
||||
" /// the others).",
|
||||
" pub const fn evaluate(self, src0: u32, src1: u32, scc_in: bool) -> (u32, Option<bool>) {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
_, function, takes_carry = PRIMITIVES[(form["operation"], form["signedness"])]
|
||||
if takes_carry:
|
||||
argument = "scc_in" if form["carry_in"] == "scc" else "false"
|
||||
call = f"primitive::{function}(src0, src1, {argument})"
|
||||
elif form["operation"] in SHIFTS:
|
||||
mask = (1 << form[SHIFT_KEY]) - 1
|
||||
call = f"primitive::{function}(src0, src1 & 0x{mask:x})"
|
||||
elif form["operation"] == "lshl_add":
|
||||
call = f"primitive::{function}(src0, src1, {form[SHIFT_AMOUNT_KEY]})"
|
||||
else:
|
||||
call = f"primitive::{function}(src0, src1)"
|
||||
if form["scc"] == "unchanged":
|
||||
out.append(f" Self::{form['variant']} => ({call}, None),")
|
||||
else:
|
||||
out += [
|
||||
f" Self::{form['variant']} => {{",
|
||||
f" let (value, scc) = {call};",
|
||||
" (value, Some(scc))",
|
||||
" }",
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
|
||||
|
||||
def _display(path):
|
||||
try:
|
||||
return path.resolve().relative_to(ROOT)
|
||||
except ValueError:
|
||||
return path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("mode", nargs="?", choices=("generate", "validate"))
|
||||
parser.add_argument("--check", action="store_true", help="fail if the committed file is stale")
|
||||
parser.add_argument("--registry", type=Path, default=REGISTRY)
|
||||
parser.add_argument("--snapshot", type=Path, default=SNAPSHOT)
|
||||
parser.add_argument("--output", type=Path, default=RUST)
|
||||
arguments = parser.parse_args()
|
||||
if bool(arguments.mode) == arguments.check:
|
||||
parser.error("choose exactly one of generate, validate or --check")
|
||||
registry = load_registry(arguments.registry)
|
||||
snapshot = load_snapshot(arguments.snapshot)
|
||||
errors = validate(registry, snapshot)
|
||||
if errors:
|
||||
for error in errors:
|
||||
print(f"error: {error}", file=sys.stderr)
|
||||
return 1
|
||||
count = len(registry["form"])
|
||||
if arguments.mode == "validate":
|
||||
print(f"registry valid: {count} forms")
|
||||
return 0
|
||||
text = render(registry, snapshot)
|
||||
if arguments.check:
|
||||
current = arguments.output.read_text(encoding="utf-8") if arguments.output.exists() else ""
|
||||
if current != text:
|
||||
print(f"{_display(arguments.output)} is stale; run generate", file=sys.stderr)
|
||||
return 1
|
||||
print(f"registry valid and generated code current: {count} forms")
|
||||
return 0
|
||||
arguments.output.write_text(text, encoding="utf-8")
|
||||
print(f"wrote {_display(arguments.output)}: {count} forms")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
File diff suppressed because it is too large.
Load diff
+164
-14
@@ -2,13 +2,26 @@
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub mod meta;
|
||||
pub mod primitive;
|
||||
mod rdna2;
|
||||
pub mod semantics;
|
||||
#[rustfmt::skip]
|
||||
mod rdna2_meta;
|
||||
#[rustfmt::skip]
|
||||
mod semantics_gen;
|
||||
pub use rdna2::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32,
|
||||
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
|
||||
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
|
||||
/// Selects the instruction encoding independently of the container and execution ABI.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
@@ -42,6 +55,8 @@ impl Opcode {
|
||||
pub enum VectorSource {
|
||||
/// VGPR index.
|
||||
Register(u8),
|
||||
/// Normal SGPR index (s0-s105) or `vcc_lo` (106), read as a wave-uniform value.
|
||||
Scalar(u8),
|
||||
/// Inline integer or literal word, represented by its bits.
|
||||
Immediate(u32),
|
||||
}
|
||||
@@ -50,6 +65,8 @@ impl fmt::Display for VectorSource {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Register(register) => write!(formatter, "v{register}"),
|
||||
Self::Scalar(VCC_LO) => formatter.write_str("vcc_lo"),
|
||||
Self::Scalar(register) => write!(formatter, "s{register}"),
|
||||
Self::Immediate(value) => write!(formatter, "0x{value:x}"),
|
||||
}
|
||||
}
|
||||
@@ -76,6 +93,81 @@ impl fmt::Display for ScalarSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Relation tested by a VOPC integer compare; S0 is SRC0 and S1 is VSRC1.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CompareRelation {
|
||||
/// S0 < S1 (opcode offset 1).
|
||||
Less,
|
||||
/// S0 == S1 (offset 2).
|
||||
Equal,
|
||||
/// S0 <= S1 (offset 3).
|
||||
LessOrEqual,
|
||||
/// S0 > S1 (offset 4).
|
||||
Greater,
|
||||
/// S0 != S1 (offset 5).
|
||||
NotEqual,
|
||||
/// S0 >= S1 (offset 6).
|
||||
GreaterOrEqual,
|
||||
}
|
||||
|
||||
/// A 32-bit VOPC integer compare: one relation over signed or unsigned operands.
|
||||
///
|
||||
/// The per-lane test follows the RDNA 2 ISA guide, section 12.9 (Table 59) and
|
||||
/// the pinned XML descriptions. VCC and EXEC rules are in
|
||||
/// docs/shaders/vector-compare.md.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct VectorCompareOp {
|
||||
/// The tested relation.
|
||||
pub relation: CompareRelation,
|
||||
/// `_i32` (two's complement) when true, `_u32` when false.
|
||||
pub signed: bool,
|
||||
}
|
||||
|
||||
impl VectorCompareOp {
|
||||
/// Lower-case mnemonic of the 32-bit VOPC encoding.
|
||||
pub fn mnemonic(self) -> &'static str {
|
||||
const SIGNED: [&str; 6] = [
|
||||
"v_cmp_lt_i32_e32",
|
||||
"v_cmp_eq_i32_e32",
|
||||
"v_cmp_le_i32_e32",
|
||||
"v_cmp_gt_i32_e32",
|
||||
"v_cmp_ne_i32_e32",
|
||||
"v_cmp_ge_i32_e32",
|
||||
];
|
||||
const UNSIGNED: [&str; 6] = [
|
||||
"v_cmp_lt_u32_e32",
|
||||
"v_cmp_eq_u32_e32",
|
||||
"v_cmp_le_u32_e32",
|
||||
"v_cmp_gt_u32_e32",
|
||||
"v_cmp_ne_u32_e32",
|
||||
"v_cmp_ge_u32_e32",
|
||||
];
|
||||
let index = self.relation as usize;
|
||||
if self.signed {
|
||||
SIGNED[index]
|
||||
} else {
|
||||
UNSIGNED[index]
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-lane test result for operand bits S0 and S1.
|
||||
pub fn test(self, src0: u32, src1: u32) -> bool {
|
||||
let ordering = if self.signed {
|
||||
(src0 as i32).cmp(&(src1 as i32))
|
||||
} else {
|
||||
src0.cmp(&src1)
|
||||
};
|
||||
match self.relation {
|
||||
CompareRelation::Less => ordering.is_lt(),
|
||||
CompareRelation::Equal => ordering.is_eq(),
|
||||
CompareRelation::LessOrEqual => ordering.is_le(),
|
||||
CompareRelation::Greater => ordering.is_gt(),
|
||||
CompareRelation::NotEqual => ordering.is_ne(),
|
||||
CompareRelation::GreaterOrEqual => ordering.is_ge(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Output targeted by a supported uncompressed four-component export.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ExportTarget {
|
||||
@@ -117,11 +209,43 @@ pub enum Instruction {
|
||||
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
|
||||
ScalarMoveB32 { dst: u8, src: ScalarSource },
|
||||
/// SOPC 32-bit equality comparison writing SCC.
|
||||
ScalarCompareEqU32 {
|
||||
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
|
||||
/// for some operations, SCC.
|
||||
ScalarUnary {
|
||||
op: ScalarUnaryOp,
|
||||
dst: u8,
|
||||
src: ScalarSource,
|
||||
},
|
||||
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and, for
|
||||
/// most operations, SCC; `s_cselect_b32` also reads SCC.
|
||||
ScalarAlu {
|
||||
op: ScalarAluOp,
|
||||
dst: u8,
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// SOPC 32-bit integer compare writing only SCC.
|
||||
ScalarCompare {
|
||||
op: ScalarCompareOp,
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// VOPC 32-bit integer compare writing a Wave32 mask to `vcc_lo`.
|
||||
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal.
|
||||
VectorCompare {
|
||||
op: VectorCompareOp,
|
||||
src0: VectorSource,
|
||||
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`.
|
||||
VectorAlu {
|
||||
op: VectorAluOp,
|
||||
dst: u8,
|
||||
src0: VectorSource,
|
||||
src1: u8,
|
||||
},
|
||||
/// SOPP jump to a stream byte offset when SCC is clear.
|
||||
BranchSccZero { target: usize },
|
||||
/// SOPP jump when the Wave32 execution mask is empty.
|
||||
@@ -174,6 +298,21 @@ pub enum Instruction {
|
||||
EndProgram,
|
||||
}
|
||||
|
||||
/// Formats an SGPR destination with LLVM's names for the EXEC and VCC halves.
|
||||
struct ScalarDestination(u8);
|
||||
|
||||
impl fmt::Display for ScalarDestination {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self.0 {
|
||||
106 => formatter.write_str("vcc_lo"),
|
||||
107 => formatter.write_str("vcc_hi"),
|
||||
126 => formatter.write_str("exec_lo"),
|
||||
127 => formatter.write_str("exec_hi"),
|
||||
register => write!(formatter, "s{register}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Instruction {
|
||||
/// Returns the mnemonic for the exact encoding family represented.
|
||||
pub fn mnemonic(self) -> &'static str {
|
||||
@@ -185,7 +324,11 @@ impl Instruction {
|
||||
Self::MoveB32 { .. } => "v_mov_b32_e32",
|
||||
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
|
||||
Self::ScalarMoveB32 { .. } => "s_mov_b32",
|
||||
Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
|
||||
Self::ScalarUnary { op, .. } => op.mnemonic(),
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
Self::ScalarCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorAlu { op, .. } => op.assembly_name(),
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
Self::BranchVccZero { .. } => "s_cbranch_vccz",
|
||||
@@ -247,14 +390,21 @@ impl fmt::Display for Instruction {
|
||||
| Self::VectorMulF32 { dst, src0, src1 } => {
|
||||
write!(formatter, " v{dst}, v{src0}, v{src1}")
|
||||
}
|
||||
Self::ScalarMoveB32 { dst, src } => match dst {
|
||||
106 => write!(formatter, " vcc_lo, {src}"),
|
||||
107 => write!(formatter, " vcc_hi, {src}"),
|
||||
126 => write!(formatter, " exec_lo, {src}"),
|
||||
127 => write!(formatter, " exec_hi, {src}"),
|
||||
_ => write!(formatter, " s{dst}, {src}"),
|
||||
},
|
||||
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
|
||||
write!(formatter, " {}, {src}", ScalarDestination(dst))
|
||||
}
|
||||
Self::ScalarAlu {
|
||||
dst, src0, src1, ..
|
||||
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
|
||||
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::VectorCompare { src0, src1, .. } => {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
Self::VectorAlu {
|
||||
dst, src0, src1, ..
|
||||
} => {
|
||||
write!(formatter, " v{dst}, {src0}, v{src1}")
|
||||
}
|
||||
Self::Branch { target }
|
||||
| Self::BranchSccZero { target }
|
||||
| Self::BranchExecZero { target }
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
//! Complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML.
|
||||
//!
|
||||
//! Identification here establishes an instruction's form and length only. It is
|
||||
//! not semantic support: [`crate::Instruction`] lists the forms Xenora executes.
|
||||
//! The XML names literal, SDWA, DPP and NSA variants without saying when they
|
||||
//! apply, so [`identify`] implements those length rules by hand from the RDNA 2
|
||||
//! ISA reference guide (see docs/research/rdna2.md).
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub use crate::rdna2_meta::{FIELDS, FORMS, SOURCE_SHA256};
|
||||
|
||||
/// AMD base encoding of an instruction form.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum EncodingFamily {
|
||||
Ds,
|
||||
Exp,
|
||||
Flat,
|
||||
Global,
|
||||
Mimg,
|
||||
Mtbuf,
|
||||
Mubuf,
|
||||
Scratch,
|
||||
Smem,
|
||||
Sop1,
|
||||
Sop2,
|
||||
Sopc,
|
||||
Sopk,
|
||||
Sopp,
|
||||
Vintrp,
|
||||
Vop1,
|
||||
Vop2,
|
||||
Vop3,
|
||||
Vop3Sdst,
|
||||
Vop3p,
|
||||
Vopc,
|
||||
}
|
||||
|
||||
impl EncodingFamily {
|
||||
/// Every family, in table order.
|
||||
pub const ALL: [Self; 21] = [
|
||||
Self::Ds,
|
||||
Self::Exp,
|
||||
Self::Flat,
|
||||
Self::Global,
|
||||
Self::Mimg,
|
||||
Self::Mtbuf,
|
||||
Self::Mubuf,
|
||||
Self::Scratch,
|
||||
Self::Smem,
|
||||
Self::Sop1,
|
||||
Self::Sop2,
|
||||
Self::Sopc,
|
||||
Self::Sopk,
|
||||
Self::Sopp,
|
||||
Self::Vintrp,
|
||||
Self::Vop1,
|
||||
Self::Vop2,
|
||||
Self::Vop3,
|
||||
Self::Vop3Sdst,
|
||||
Self::Vop3p,
|
||||
Self::Vopc,
|
||||
];
|
||||
|
||||
/// Lower-case name used in reports.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Ds => "ds",
|
||||
Self::Exp => "exp",
|
||||
Self::Flat => "flat",
|
||||
Self::Global => "global",
|
||||
Self::Mimg => "mimg",
|
||||
Self::Mtbuf => "mtbuf",
|
||||
Self::Mubuf => "mubuf",
|
||||
Self::Scratch => "scratch",
|
||||
Self::Smem => "smem",
|
||||
Self::Sop1 => "sop1",
|
||||
Self::Sop2 => "sop2",
|
||||
Self::Sopc => "sopc",
|
||||
Self::Sopk => "sopk",
|
||||
Self::Sopp => "sopp",
|
||||
Self::Vintrp => "vintrp",
|
||||
Self::Vop1 => "vop1",
|
||||
Self::Vop2 => "vop2",
|
||||
Self::Vop3 => "vop3",
|
||||
Self::Vop3Sdst => "vop3-sdst",
|
||||
Self::Vop3p => "vop3p",
|
||||
Self::Vopc => "vopc",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Control-flow flags recorded by the XML.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FormFlags(pub u8);
|
||||
|
||||
impl FormFlags {
|
||||
#[allow(missing_docs)]
|
||||
pub const NONE: Self = Self(0);
|
||||
#[allow(missing_docs)]
|
||||
pub const BRANCH: Self = Self(1);
|
||||
#[allow(missing_docs)]
|
||||
pub const CONDITIONAL: Self = Self(2);
|
||||
#[allow(missing_docs)]
|
||||
pub const INDIRECT: Self = Self(4);
|
||||
#[allow(missing_docs)]
|
||||
pub const TERMINATOR: Self = Self(8);
|
||||
#[allow(missing_docs)]
|
||||
pub const IMMEDIATE: Self = Self(16);
|
||||
|
||||
/// Whether every flag in `other` is set.
|
||||
pub fn contains(self, other: Self) -> bool {
|
||||
self.0 & other.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension words an instruction form may carry.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Extensions(pub u8);
|
||||
|
||||
impl Extensions {
|
||||
#[allow(missing_docs)]
|
||||
pub const NONE: Self = Self(0);
|
||||
/// A source field may select a trailing 32-bit literal.
|
||||
pub const LITERAL: Self = Self(1);
|
||||
/// The form always carries a trailing 32-bit literal.
|
||||
pub const ALWAYS_LITERAL: Self = Self(2);
|
||||
#[allow(missing_docs)]
|
||||
pub const SDWA: Self = Self(4);
|
||||
#[allow(missing_docs)]
|
||||
pub const DPP8: Self = Self(8);
|
||||
#[allow(missing_docs)]
|
||||
pub const DPP16: Self = Self(16);
|
||||
/// MIMG non-sequential address dwords.
|
||||
pub const NSA: Self = Self(32);
|
||||
|
||||
/// Whether every extension in `other` is allowed.
|
||||
pub fn contains(self, other: Self) -> bool {
|
||||
self.0 & other.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
/// One encoded field: pieces of (bit offset, bit count), least significant piece first.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FieldLayout {
|
||||
#[allow(missing_docs)]
|
||||
pub name: &'static str,
|
||||
#[allow(missing_docs)]
|
||||
pub pieces: &'static [(u8, u8)],
|
||||
}
|
||||
|
||||
impl FieldLayout {
|
||||
/// Extracts the field from the instruction's first two dwords.
|
||||
pub fn extract(&self, value: u64) -> u32 {
|
||||
let mut result = 0u64;
|
||||
let mut shift = 0;
|
||||
for &(offset, count) in self.pieces {
|
||||
result |= ((value >> offset) & ((1u64 << count) - 1)) << shift;
|
||||
shift += count;
|
||||
}
|
||||
result as u32
|
||||
}
|
||||
}
|
||||
|
||||
/// An operand as described by the XML.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct OperandInfo {
|
||||
pub field: &'static str,
|
||||
pub format: &'static str,
|
||||
pub kind: &'static str,
|
||||
pub bits: u16,
|
||||
pub input: bool,
|
||||
pub output: bool,
|
||||
pub implicit: bool,
|
||||
/// Whether the operand occupies microcode bits.
|
||||
pub encoded: bool,
|
||||
}
|
||||
|
||||
/// One instruction in one base encoding.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct Form {
|
||||
pub name: &'static str,
|
||||
pub family: EncodingFamily,
|
||||
pub opcode: u16,
|
||||
/// Identifying bits over the first two dwords (little-endian, first dword low).
|
||||
pub mask: u64,
|
||||
pub bits: u64,
|
||||
/// Base length before literal, SDWA, DPP or NSA words.
|
||||
pub bytes: u8,
|
||||
pub flags: FormFlags,
|
||||
pub extensions: Extensions,
|
||||
pub group: &'static str,
|
||||
pub operands: &'static [OperandInfo],
|
||||
}
|
||||
|
||||
impl Form {
|
||||
/// The base encoding's field layouts.
|
||||
pub fn fields(&self) -> &'static [FieldLayout] {
|
||||
FIELDS
|
||||
.iter()
|
||||
.find(|(family, _)| *family == self.family)
|
||||
.map(|(_, fields)| *fields)
|
||||
.unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// The named field's layout, if the encoding has one.
|
||||
pub fn field(&self, name: &str) -> Option<&'static FieldLayout> {
|
||||
self.fields().iter().find(|field| field.name == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which extension words an identified instruction carries.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct Trailer {
|
||||
/// A 32-bit literal follows the base encoding.
|
||||
pub literal: bool,
|
||||
/// SDWA, DPP8 or DPP16 control dword (VOP1, VOP2, VOPC only).
|
||||
pub vector_control: Option<VectorControl>,
|
||||
/// Extra MIMG address dwords.
|
||||
pub nsa_dwords: u8,
|
||||
}
|
||||
|
||||
/// The dword that replaces SRC0 in a VOP1, VOP2 or VOPC instruction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum VectorControl {
|
||||
Sdwa,
|
||||
Dpp8 { fetch_inactive: bool },
|
||||
Dpp16,
|
||||
}
|
||||
|
||||
/// An identified instruction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Identified {
|
||||
/// The matched form.
|
||||
pub form: &'static Form,
|
||||
/// First two dwords; the second is zero for 32-bit encodings.
|
||||
pub raw: u64,
|
||||
/// Total length in bytes, including extension words.
|
||||
pub len: usize,
|
||||
/// Extension words present.
|
||||
pub trailer: Trailer,
|
||||
}
|
||||
|
||||
impl Identified {
|
||||
/// Extracts a named field of the base encoding.
|
||||
pub fn field(&self, name: &str) -> Option<u32> {
|
||||
self.form.field(name).map(|field| field.extract(self.raw))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an instruction could not be identified.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum IdentifyError {
|
||||
/// Fewer bytes remain than the encoding or its extension words need.
|
||||
Truncated {
|
||||
/// Bytes required from the instruction start.
|
||||
needed: usize,
|
||||
},
|
||||
/// No gfx1030 form matches; the bits are reserved or belong to another architecture.
|
||||
Unassigned,
|
||||
/// The bits select an extension the form does not allow.
|
||||
InvalidExtension(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for IdentifyError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Truncated { needed } => write!(formatter, "truncated: needs {needed} bytes"),
|
||||
Self::Unassigned => formatter.write_str("no gfx1030 instruction has this encoding"),
|
||||
Self::InvalidExtension(what) => write!(formatter, "invalid extension: {what}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IdentifyError {}
|
||||
|
||||
/// Source operand value selecting a trailing literal (XML `SRC_LITERAL`).
|
||||
pub const SRC_LITERAL: u32 = 255;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting an SDWA control dword.
|
||||
pub const SRC_SDWA: u32 = 0xf9;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP16 control dword.
|
||||
pub const SRC_DPP16: u32 = 0xfa;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP8 control dword.
|
||||
pub const SRC_DPP8: u32 = 0xe9;
|
||||
/// DPP8 with fetch-inactive set.
|
||||
pub const SRC_DPP8_FI: u32 = 0xea;
|
||||
|
||||
fn read_dword(bytes: &[u8], index: usize) -> Option<u32> {
|
||||
let start = index.checked_mul(4)?;
|
||||
let chunk = bytes.get(start..start.checked_add(4)?)?;
|
||||
Some(u32::from_le_bytes(chunk.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// Finds the form whose identifying bits match.
|
||||
///
|
||||
/// Masks never overlap ambiguously; the generator rejects such tables.
|
||||
pub fn lookup(raw: u64) -> Option<&'static Form> {
|
||||
FORMS.iter().find(|form| raw & form.mask == form.bits)
|
||||
}
|
||||
|
||||
/// Identifies the instruction at the start of `bytes` and computes its length.
|
||||
pub fn identify(bytes: &[u8]) -> Result<Identified, IdentifyError> {
|
||||
let first = read_dword(bytes, 0).ok_or(IdentifyError::Truncated { needed: 4 })?;
|
||||
let second = read_dword(bytes, 1);
|
||||
let raw_guess = u64::from(first) | (u64::from(second.unwrap_or(0)) << 32);
|
||||
// A 32-bit form never inspects the second dword; a 64-bit form needs it.
|
||||
let form = FORMS
|
||||
.iter()
|
||||
.find(|form| (form.bytes == 4 || second.is_some()) && raw_guess & form.mask == form.bits)
|
||||
.or_else(|| {
|
||||
// Distinguish a truncated 64-bit instruction from unassigned bits.
|
||||
FORMS.iter().find(|form| {
|
||||
form.bytes == 8
|
||||
&& u64::from(first) & form.mask & 0xffff_ffff == form.bits & 0xffff_ffff
|
||||
})
|
||||
})
|
||||
.ok_or(IdentifyError::Unassigned)?;
|
||||
if form.bytes == 8 && second.is_none() {
|
||||
return Err(IdentifyError::Truncated { needed: 8 });
|
||||
}
|
||||
let raw = if form.bytes == 4 {
|
||||
u64::from(first)
|
||||
} else {
|
||||
raw_guess
|
||||
};
|
||||
let mut trailer = Trailer::default();
|
||||
let source = |name: &str| form.field(name).map(|field| field.extract(raw));
|
||||
match form.family {
|
||||
EncodingFamily::Sop1 | EncodingFamily::Sop2 | EncodingFamily::Sopc => {
|
||||
trailer.literal = [source("SSRC0"), source("SSRC1")]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|value| value == SRC_LITERAL);
|
||||
}
|
||||
EncodingFamily::Vop1 | EncodingFamily::Vop2 | EncodingFamily::Vopc => {
|
||||
match source("SRC0") {
|
||||
Some(SRC_LITERAL) => trailer.literal = true,
|
||||
Some(SRC_SDWA) => trailer.vector_control = Some(VectorControl::Sdwa),
|
||||
Some(SRC_DPP16) => trailer.vector_control = Some(VectorControl::Dpp16),
|
||||
Some(SRC_DPP8) => {
|
||||
trailer.vector_control = Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: false,
|
||||
})
|
||||
}
|
||||
Some(SRC_DPP8_FI) => {
|
||||
trailer.vector_control = Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true,
|
||||
})
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
EncodingFamily::Vop3 | EncodingFamily::Vop3Sdst | EncodingFamily::Vop3p => {
|
||||
// An attribute field (XML OPR_ATTR) is not an operand selector: in the
|
||||
// VOP3 interpolation forms SRC0 holds {attr_word, attr_chan, attr}
|
||||
// bit-fields (AMD RDNA 2 ISA guide, section 10.4.2), so 255 there
|
||||
// does not select a literal.
|
||||
trailer.literal = ["SRC0", "SRC1", "SRC2"]
|
||||
.into_iter()
|
||||
.filter(|name| {
|
||||
!form
|
||||
.operands
|
||||
.iter()
|
||||
.any(|operand| operand.field == *name && operand.kind == "OPR_ATTR")
|
||||
})
|
||||
.filter_map(source)
|
||||
.any(|value| value == SRC_LITERAL);
|
||||
}
|
||||
EncodingFamily::Mimg => {
|
||||
trailer.nsa_dwords = source("NSA").unwrap_or(0) as u8;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if form.extensions.contains(Extensions::ALWAYS_LITERAL) {
|
||||
trailer.literal = true;
|
||||
} else if trailer.literal && !form.extensions.contains(Extensions::LITERAL) {
|
||||
return Err(IdentifyError::InvalidExtension("literal"));
|
||||
}
|
||||
match trailer.vector_control {
|
||||
Some(VectorControl::Sdwa) if !form.extensions.contains(Extensions::SDWA) => {
|
||||
return Err(IdentifyError::InvalidExtension("sdwa"));
|
||||
}
|
||||
Some(VectorControl::Dpp8 { .. }) if !form.extensions.contains(Extensions::DPP8) => {
|
||||
return Err(IdentifyError::InvalidExtension("dpp8"));
|
||||
}
|
||||
Some(VectorControl::Dpp16) if !form.extensions.contains(Extensions::DPP16) => {
|
||||
return Err(IdentifyError::InvalidExtension("dpp16"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if trailer.nsa_dwords > 0 && !form.extensions.contains(Extensions::NSA) {
|
||||
return Err(IdentifyError::InvalidExtension("nsa"));
|
||||
}
|
||||
let len = usize::from(form.bytes)
|
||||
+ 4 * usize::from(trailer.literal)
|
||||
+ 4 * usize::from(trailer.vector_control.is_some())
|
||||
+ 4 * usize::from(trailer.nsa_dwords);
|
||||
if bytes.len() < len {
|
||||
return Err(IdentifyError::Truncated { needed: len });
|
||||
}
|
||||
Ok(Identified {
|
||||
form,
|
||||
raw,
|
||||
len,
|
||||
trailer,
|
||||
})
|
||||
}
|
||||
|
||||
/// Number of forms per encoding family in the metadata.
|
||||
pub fn inventory() -> Vec<(EncodingFamily, usize)> {
|
||||
EncodingFamily::ALL
|
||||
.iter()
|
||||
.map(|&family| {
|
||||
(
|
||||
family,
|
||||
FORMS.iter().filter(|form| form.family == family).count(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//! Reusable integer semantic primitives selected by the generated registry dispatch.
|
||||
//!
|
||||
//! Each function implements one closed [`crate::semantics::Operation`] at one
|
||||
//! signedness, with the condition-code rule the RDNA 2 guide gives for it
|
||||
//! (section 5.3, "Scalar Condition Code", and the SOP2 pseudocode in 12.1).
|
||||
//! Forms share a primitive only when their declared operation, signedness and
|
||||
//! SCC effect are identical; the generator never selects one by mnemonic.
|
||||
|
||||
/// Unsigned `a + b + carry_in` and the carry-out of bit 31.
|
||||
pub const fn add_carry_u32(a: u32, b: u32, carry_in: bool) -> (u32, bool) {
|
||||
let (partial, first) = a.overflowing_add(b);
|
||||
let (value, second) = partial.overflowing_add(carry_in as u32);
|
||||
(value, first || second)
|
||||
}
|
||||
|
||||
/// Unsigned `a - b - borrow_in` and the borrow (`b + borrow_in > a`).
|
||||
pub const fn sub_borrow_u32(a: u32, b: u32, borrow_in: bool) -> (u32, bool) {
|
||||
let (partial, first) = a.overflowing_sub(b);
|
||||
let (value, second) = partial.overflowing_sub(borrow_in as u32);
|
||||
(value, first || second)
|
||||
}
|
||||
|
||||
/// Two's-complement `a + b` and whether the exact sum leaves the i32 range.
|
||||
pub const fn add_overflow_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (value, overflow) = (a as i32).overflowing_add(b as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
|
||||
/// Two's-complement `a - b` and whether the exact difference leaves the i32 range.
|
||||
pub const fn sub_overflow_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (value, overflow) = (a as i32).overflowing_sub(b as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
|
||||
/// Bitwise AND and whether the result is nonzero.
|
||||
pub const fn and_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a & b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise OR and whether the result is nonzero.
|
||||
pub const fn or_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a | b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise XOR and whether the result is nonzero.
|
||||
pub const fn xor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a ^ b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `a & !b` and whether the result is nonzero.
|
||||
pub const fn andn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a & !b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `a | !b` and whether the result is nonzero.
|
||||
pub const fn orn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a | !b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a & b)` and whether the result is nonzero.
|
||||
pub const fn nand_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a & b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a | b)` and whether the result is nonzero.
|
||||
pub const fn nor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a | b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a ^ b)` and whether the result is nonzero.
|
||||
pub const fn xnor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a ^ b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a << count` and whether the result is nonzero. The caller masks the count
|
||||
/// to the declared count width, so `count` is below 32.
|
||||
pub const fn lshl_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = a << count;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Logical `a >> count` (zero fill) and whether the result is nonzero; `count` is below 32.
|
||||
pub const fn lshr_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = a >> count;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Arithmetic `a >> count` (sign fill) and whether the result is nonzero; `count` is below 32.
|
||||
pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = ((a as i32) >> count) as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a == b` on the raw bits; signedness does not matter for equality.
|
||||
pub const fn eq_b32(a: u32, b: u32) -> bool {
|
||||
a == b
|
||||
}
|
||||
|
||||
/// `a != b` on the raw bits (the guide's LG, "less or greater").
|
||||
pub const fn ne_b32(a: u32, b: u32) -> bool {
|
||||
a != b
|
||||
}
|
||||
|
||||
/// Two's-complement `a > b`.
|
||||
pub const fn gt_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) > (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a >= b`.
|
||||
pub const fn ge_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) >= (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a < b`.
|
||||
pub const fn lt_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) < (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a <= b`.
|
||||
pub const fn le_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) <= (b as i32)
|
||||
}
|
||||
|
||||
/// Unsigned `a > b`.
|
||||
pub const fn gt_u32(a: u32, b: u32) -> bool {
|
||||
a > b
|
||||
}
|
||||
|
||||
/// Unsigned `a >= b`.
|
||||
pub const fn ge_u32(a: u32, b: u32) -> bool {
|
||||
a >= b
|
||||
}
|
||||
|
||||
/// Unsigned `a < b`.
|
||||
pub const fn lt_u32(a: u32, b: u32) -> bool {
|
||||
a < b
|
||||
}
|
||||
|
||||
/// Unsigned `a <= b`.
|
||||
pub const fn le_u32(a: u32, b: u32) -> bool {
|
||||
a <= b
|
||||
}
|
||||
|
||||
/// `!a` and whether the result is nonzero.
|
||||
pub const fn not_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = !a;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a` with bit `i` moved to bit `31 - i`.
|
||||
pub const fn brev_b32(a: u32) -> u32 {
|
||||
a.reverse_bits()
|
||||
}
|
||||
|
||||
/// Number of zero bits and whether that count is nonzero.
|
||||
pub const fn bcnt0_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = a.count_zeros();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Number of one bits and whether that count is nonzero.
|
||||
pub const fn bcnt1_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = a.count_ones();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Index of the lowest zero bit, or `0xffffffff` (-1) when every bit is one.
|
||||
pub const fn ff0_b32(a: u32) -> u32 {
|
||||
if a == u32::MAX {
|
||||
u32::MAX
|
||||
} else {
|
||||
a.trailing_ones()
|
||||
}
|
||||
}
|
||||
|
||||
/// Index of the lowest one bit, or `0xffffffff` (-1) when every bit is zero.
|
||||
pub const fn ff1_b32(a: u32) -> u32 {
|
||||
if a == 0 { u32::MAX } else { a.trailing_zeros() }
|
||||
}
|
||||
|
||||
/// Zeros above the highest one bit, or `0xffffffff` (-1) when `a` is zero.
|
||||
pub const fn flbit_b32(a: u32) -> u32 {
|
||||
if a == 0 { u32::MAX } else { a.leading_zeros() }
|
||||
}
|
||||
|
||||
/// Bits above the highest bit that differs from the sign bit, or `0xffffffff`
|
||||
/// (-1) when every bit equals the sign bit (`a` is 0 or -1).
|
||||
pub const fn flbit_i32(a: u32) -> u32 {
|
||||
let differing = if a >> 31 == 0 { a } else { !a };
|
||||
if differing == 0 {
|
||||
u32::MAX
|
||||
} else {
|
||||
differing.leading_zeros()
|
||||
}
|
||||
}
|
||||
|
||||
/// The low `bits` of `a` sign-extended to 32 bits; `bits` is 8 or 16.
|
||||
pub const fn sext_i32(a: u32, bits: u32) -> u32 {
|
||||
let shift = 32 - bits;
|
||||
(((a << shift) as i32) >> shift) as u32
|
||||
}
|
||||
|
||||
/// Two's-complement absolute value (wrapping, so `0x80000000` stays) and
|
||||
/// whether the result is nonzero.
|
||||
pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) {
|
||||
let value = (a as i32).wrapping_abs() as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Two's-complement minimum and whether S0 was strictly smaller (so equal
|
||||
/// operands give S1 and `false`).
|
||||
pub const fn min_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = (a as i32) < (b as i32);
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Unsigned minimum and whether S0 was strictly smaller.
|
||||
pub const fn min_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = a < b;
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Two's-complement maximum and whether S0 was strictly greater (so equal
|
||||
/// operands give S1 and `false`).
|
||||
pub const fn max_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = (a as i32) > (b as i32);
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Unsigned maximum and whether S0 was strictly greater.
|
||||
pub const fn max_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = a > b;
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// `a` when `condition` (SCC) is set, otherwise `b`.
|
||||
pub const fn cselect_b32(a: u32, b: u32, condition: bool) -> u32 {
|
||||
if condition { a } else { b }
|
||||
}
|
||||
|
||||
/// `((1 << a[4:0]) - 1) << b[4:0]`: a mask of `a[4:0]` ones starting at bit `b[4:0]`.
|
||||
pub const fn bfm_b32(a: u32, b: u32) -> u32 {
|
||||
((1u32 << (a & 0x1f)) - 1) << (b & 0x1f)
|
||||
}
|
||||
|
||||
/// The low 32 bits of the product (identical for signed and unsigned operands).
|
||||
pub const fn mul_lo_i32(a: u32, b: u32) -> u32 {
|
||||
a.wrapping_mul(b)
|
||||
}
|
||||
|
||||
/// The high 32 bits of the unsigned 64-bit product.
|
||||
pub const fn mul_hi_u32(a: u32, b: u32) -> u32 {
|
||||
((a as u64 * b as u64) >> 32) as u32
|
||||
}
|
||||
|
||||
/// The high 32 bits of the two's-complement 64-bit product.
|
||||
pub const fn mul_hi_i32(a: u32, b: u32) -> u32 {
|
||||
((a as i32 as i64 * b as i32 as i64) >> 32) as u32
|
||||
}
|
||||
|
||||
/// The `bfe` field descriptor: offset `b[4:0]` and width `b[22:16]` (0-127).
|
||||
const fn bfe_field(b: u32) -> (u32, u32) {
|
||||
(b & 0x1f, (b >> 16) & 0x7f)
|
||||
}
|
||||
|
||||
/// Unsigned bit-field extract: `(a >> offset) & ((1 << width) - 1)`, where a
|
||||
/// width of 32 or more keeps every shifted bit; and whether the result is nonzero.
|
||||
pub const fn bfe_nonzero_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (offset, width) = bfe_field(b);
|
||||
let shifted = a >> offset;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
shifted & ((1 << width) - 1)
|
||||
};
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Signed bit-field extract: `a` shifted arithmetically by the offset, the low
|
||||
/// `width` bits kept and sign-extended from bit `width - 1` (a width of 32 or
|
||||
/// more keeps the whole shifted word); and whether the result is nonzero.
|
||||
pub const fn bfe_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (offset, width) = bfe_field(b);
|
||||
let shifted = ((a as i32) >> offset) as u32;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
let unused = 32 - width;
|
||||
(((shifted << unused) as i32) >> unused) as u32
|
||||
};
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `|a - b|` of the wrapped 32-bit difference (so `0x80000000` stays) and
|
||||
/// whether the result is nonzero.
|
||||
pub const fn absdiff_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = (a.wrapping_sub(b) as i32).unsigned_abs();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `(a << shift) + b` and the carry out of the exact sum, which counts the bits
|
||||
/// shifted out of `a`; `shift` is 1 to 4.
|
||||
pub const fn lshl_add_carry_u32(a: u32, b: u32, shift: u32) -> (u32, bool) {
|
||||
let sum = ((a as u64) << shift) + b as u64;
|
||||
(sum as u32, sum >> 32 != 0)
|
||||
}
|
||||
+60
-5
@@ -45,11 +45,6 @@ pub const S_MOV_B32: Opcode = Opcode {
|
||||
bits: 0xbe800300,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CMP_EQ_U32: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf060000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CBRANCH_SCC0: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf840000,
|
||||
@@ -110,6 +105,66 @@ pub const V_MUL_F32: Opcode = Opcode {
|
||||
bits: 0x10000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_LT_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d020000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_EQ_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d040000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_LE_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d060000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_GT_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d080000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_NE_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d0a0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_GE_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d0c0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_LT_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d820000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_EQ_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d840000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_LE_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d860000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_GT_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d880000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_NE_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d8a0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_GE_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d8c0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const EXP: Opcode = Opcode {
|
||||
mask: 0xfc000000,
|
||||
bits: 0xf8000000,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,271 @@
|
||||
//! Typed vocabulary of the declarative semantic registry (`crates/isa/semantics/rdna2.toml`).
|
||||
//!
|
||||
//! The registry is data. `crates/isa/generate_semantics.py` validates it against
|
||||
//! this closed vocabulary and the pinned AMD XML snapshot, then emits
|
||||
//! `semantics_gen.rs`: the typed operation enums, their opcode dispatch and one
|
||||
//! static [`FormSemantics`] row per form. Nothing here interprets metadata at run
|
||||
//! time; the decoder and translator call the generated `const fn`s and `match`es.
|
||||
//!
|
||||
//! The reference interpreter (`crates/ref`) and the independent interpreter
|
||||
//! (`tests/validation/independent_ref.rs`) must not use this module.
|
||||
|
||||
use crate::CompareRelation;
|
||||
use crate::meta::EncodingFamily;
|
||||
|
||||
pub use crate::semantics_gen::{FORM_IDS, FORMS, GENERATED_SCHEMA};
|
||||
|
||||
/// Version of the registry schema this crate was generated against.
|
||||
pub const SCHEMA: u32 = 1;
|
||||
|
||||
/// Reusable semantic primitive selected by a form. Closed: the generator rejects
|
||||
/// any other name, and each primitive has one implementation in `primitive.rs`.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Operation {
|
||||
/// Integer addition.
|
||||
Add,
|
||||
/// Integer subtraction.
|
||||
Sub,
|
||||
/// Bitwise AND.
|
||||
And,
|
||||
/// Bitwise OR.
|
||||
Or,
|
||||
/// Bitwise exclusive OR.
|
||||
Xor,
|
||||
/// Bitwise AND with the complement of S1.
|
||||
AndNot,
|
||||
/// Bitwise OR with the complement of S1.
|
||||
OrNot,
|
||||
/// Complement of bitwise AND.
|
||||
Nand,
|
||||
/// Complement of bitwise OR.
|
||||
Nor,
|
||||
/// Complement of bitwise exclusive OR.
|
||||
Xnor,
|
||||
/// Shift S0 left by the masked count in S1, filling with zeros.
|
||||
ShiftLeft,
|
||||
/// Shift S0 right by the masked count in S1, filling with zeros.
|
||||
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,
|
||||
/// Bitwise complement of S0.
|
||||
Not,
|
||||
/// S0 with its bit order reversed.
|
||||
ReverseBits,
|
||||
/// Number of zero bits in S0.
|
||||
CountZeros,
|
||||
/// Number of one bits in S0.
|
||||
CountOnes,
|
||||
/// Index of the lowest zero bit of S0, or -1 when there is none.
|
||||
FindFirstZero,
|
||||
/// Index of the lowest one bit of S0, or -1 when there is none.
|
||||
FindFirstOne,
|
||||
/// Unsigned: count of zeros above the highest one bit; signed: count of bits
|
||||
/// above the highest bit that differs from the sign bit. -1 when none.
|
||||
FindLastBit,
|
||||
/// Sign-extend the low `source_bits` of S0 to 32 bits.
|
||||
SignExtend,
|
||||
/// Two's-complement absolute value; the most negative value maps to itself.
|
||||
Absolute,
|
||||
/// S0 when it is strictly less than S1, otherwise S1.
|
||||
Minimum,
|
||||
/// S0 when it is strictly greater than S1, otherwise S1.
|
||||
Maximum,
|
||||
/// S0 when SCC is set, otherwise S1.
|
||||
Select,
|
||||
/// `((1 << S0[4:0]) - 1) << S1[4:0]`.
|
||||
BitfieldMask,
|
||||
/// Low 32 bits of the product.
|
||||
Multiply,
|
||||
/// High 32 bits of the 64-bit product.
|
||||
MultiplyHigh,
|
||||
/// The field of S0 at offset S1[4:0] with width S1[22:16]; sign-extended when signed.
|
||||
BitfieldExtract,
|
||||
/// Absolute value of the wrapped 32-bit difference S0 - S1.
|
||||
AbsoluteDifference,
|
||||
/// `(S0 << shift_amount) + S1`.
|
||||
ShiftLeftAdd,
|
||||
/// Low 32 bits of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
|
||||
Multiply24,
|
||||
/// Bits 63:32 of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
|
||||
MultiplyHigh24,
|
||||
}
|
||||
|
||||
/// The per-lane integer operation a vector form lowers to. One reusable MSL
|
||||
/// template exists per variant; a form selects it through its declared
|
||||
/// operation and signedness, never through its opcode.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorBinary {
|
||||
/// Wrapping `a + b`.
|
||||
Add,
|
||||
/// Wrapping `a - b`.
|
||||
Sub,
|
||||
/// `!(a ^ b)`.
|
||||
Xnor,
|
||||
/// Two's-complement minimum.
|
||||
MinSigned,
|
||||
/// Unsigned minimum.
|
||||
MinUnsigned,
|
||||
/// Two's-complement maximum.
|
||||
MaxSigned,
|
||||
/// Unsigned maximum.
|
||||
MaxUnsigned,
|
||||
/// Low 32 bits of `sext(a[23:0]) * sext(b[23:0])`.
|
||||
Mul24Signed,
|
||||
/// Low 32 bits of `a[23:0] * b[23:0]`.
|
||||
Mul24Unsigned,
|
||||
/// Bits 63:32 of `sext(a[23:0]) * sext(b[23:0])`.
|
||||
MulHi24Signed,
|
||||
/// Bits 63:32 of `a[23:0] * b[23:0]`.
|
||||
MulHi24Unsigned,
|
||||
}
|
||||
|
||||
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Signedness {
|
||||
/// Unsigned integers.
|
||||
Unsigned,
|
||||
/// Two's-complement integers.
|
||||
Signed,
|
||||
/// Untyped bits.
|
||||
Bitwise,
|
||||
}
|
||||
|
||||
/// Whether the operation reads SCC.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CarryIn {
|
||||
/// SCC is not read.
|
||||
None,
|
||||
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
|
||||
Scc,
|
||||
}
|
||||
|
||||
/// What a form writes to SCC.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum SccEffect {
|
||||
/// SCC is not written.
|
||||
Unchanged,
|
||||
/// Unsigned carry-out of the top bit.
|
||||
CarryOut,
|
||||
/// Unsigned borrow (subtrahend plus borrow-in exceeds the minuend).
|
||||
Borrow,
|
||||
/// Two's-complement overflow of the exact result.
|
||||
SignedOverflow,
|
||||
/// The result is not zero.
|
||||
Nonzero,
|
||||
/// The compare's relation holds for S0 and S1.
|
||||
Relation,
|
||||
/// The result is S0 by the strict comparison (min, max): equal operands give 0.
|
||||
SelectedSrc0,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MaskEffect {
|
||||
/// Not written.
|
||||
Unchanged,
|
||||
}
|
||||
|
||||
/// Wave-size restriction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Wave {
|
||||
/// Behaviour does not depend on the wave size.
|
||||
Any,
|
||||
/// Only Wave32 behaviour is declared; Wave64 stays unsupported.
|
||||
Wave32,
|
||||
}
|
||||
|
||||
/// Shared operand rule. The decoder implements each rule once.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum OperandRule {
|
||||
/// SOP2: SDST is s0-s105; SSRC0/SSRC1 are s0-s105, inline integers -16..64
|
||||
/// or one literal word. Everything else is rejected as unsupported.
|
||||
Sop2Sgpr,
|
||||
/// SOPC: no destination; SSRC0/SSRC1 as for SOP2 sources (s0-s105, inline
|
||||
/// integers -16..64 or one literal word). Everything else is rejected.
|
||||
SopcScalar,
|
||||
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
|
||||
/// a literal word. Everything else is rejected as unsupported.
|
||||
Sop1Sgpr,
|
||||
/// 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.
|
||||
Vop2Vgpr,
|
||||
}
|
||||
|
||||
/// Evidence a form needs before it counts as verified.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Evidence {
|
||||
/// `crates/ref` lockstep reference.
|
||||
Reference,
|
||||
/// `tests/validation/independent_ref.rs`.
|
||||
Independent,
|
||||
/// Native Metal known-answer runs.
|
||||
Metal,
|
||||
/// LLVM assembler/disassembler encoding agreement.
|
||||
LlvmEncoding,
|
||||
}
|
||||
|
||||
/// Public document a [`SpecRef`] points at.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Document {
|
||||
/// AMD RDNA 2 ISA reference guide (PDF).
|
||||
Guide,
|
||||
/// Pinned AMD machine-readable XML.
|
||||
Xml,
|
||||
}
|
||||
|
||||
/// One public specification reference.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct SpecRef {
|
||||
/// Source document.
|
||||
pub document: Document,
|
||||
/// Section number, for example `"12.1"`.
|
||||
pub section: &'static str,
|
||||
/// Page in the document, or 0 when the page has not been recorded.
|
||||
pub page: u16,
|
||||
}
|
||||
|
||||
/// One validated registry row, emitted as a static table by the generator.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FormSemantics {
|
||||
/// XML instruction name, the stable form identity.
|
||||
pub name: &'static str,
|
||||
/// Encoding family (matches [`crate::meta::FORMS`]).
|
||||
pub family: EncodingFamily,
|
||||
/// Opcode within the family.
|
||||
pub opcode: u16,
|
||||
/// Primitive.
|
||||
pub operation: Operation,
|
||||
/// Operand interpretation.
|
||||
pub signedness: Signedness,
|
||||
/// SCC input.
|
||||
pub carry_in: CarryIn,
|
||||
/// Operand and result width in bits.
|
||||
pub width: u8,
|
||||
/// Low bits of S1 used as the shift count by shift operations; 0 otherwise.
|
||||
pub shift_count_bits: u8,
|
||||
/// Fixed left shift of S0 for shift-and-add operations (1 to 4); 0 otherwise.
|
||||
pub shift_amount: u8,
|
||||
/// Whether the operation reads its sources in reverse order (`D = op(S1, S0)`).
|
||||
pub swap_sources: bool,
|
||||
/// Low bits of S0 that the operation reads: `width`, or 8 or 16 for sign extension.
|
||||
pub source_bits: u8,
|
||||
/// The relation tested by compares (S0 on the left); `None` otherwise.
|
||||
pub relation: Option<CompareRelation>,
|
||||
/// SCC write.
|
||||
pub scc: SccEffect,
|
||||
/// VCC write.
|
||||
pub vcc: MaskEffect,
|
||||
/// EXEC write.
|
||||
pub exec: MaskEffect,
|
||||
/// Wave-size restriction.
|
||||
pub wave: Wave,
|
||||
/// Operand rule.
|
||||
pub operands: OperandRule,
|
||||
/// Public references.
|
||||
pub spec: &'static [SpecRef],
|
||||
/// Required evidence.
|
||||
pub verify: &'static [Evidence],
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,454 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//! gfx1030 extension-word negative tests (issue #172): truncated and invalid
|
||||
//! literal, SDWA, DPP16, DPP8 and MIMG NSA trailers.
|
||||
//!
|
||||
//! Every source instruction is original and was assembled by llvm-mc 23.1.6
|
||||
//! (`source_encodings_match_llvm` re-checks the bytes). Expected results come
|
||||
//! from LLVM's disassembly of the cut or altered bytes and from the field
|
||||
//! layouts in AMD's public "RDNA 2 Instruction Set Architecture" reference
|
||||
//! (microcode formats: SDWA, DPP16, DPP8, MIMG NSA), never from Xenora's
|
||||
//! decoder. `identify` recognises lengths and allowed extensions; it does not
|
||||
//! validate control-word values (see `reserved_control_values_keep_their_trailer_lengths`).
|
||||
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_isa::meta::{
|
||||
IdentifyError, SRC_DPP8, SRC_DPP16, SRC_LITERAL, SRC_SDWA, Trailer, VectorControl, identify,
|
||||
};
|
||||
|
||||
struct Fixture {
|
||||
source: &'static str,
|
||||
bytes: &'static [u8],
|
||||
}
|
||||
|
||||
const SOP2_LITERAL: Fixture = Fixture {
|
||||
source: "s_add_u32 s9, 0x12345679, s11",
|
||||
bytes: &[0xff, 0x0b, 0x09, 0x80, 0x79, 0x56, 0x34, 0x12],
|
||||
};
|
||||
const SOPK_IMMEDIATE: Fixture = Fixture {
|
||||
source: "s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0x125678ab",
|
||||
bytes: &[0x01, 0xf8, 0x80, 0xba, 0xab, 0x78, 0x56, 0x12],
|
||||
};
|
||||
const VOP1_LITERAL: Fixture = Fixture {
|
||||
source: "v_mov_b32_e32 v7, 0x12345679",
|
||||
bytes: &[0xff, 0x02, 0x0e, 0x7e, 0x79, 0x56, 0x34, 0x12],
|
||||
};
|
||||
const VOP2_LITERAL: Fixture = Fixture {
|
||||
source: "v_add_f32_e32 v7, 0x3f800003, v8",
|
||||
bytes: &[0xff, 0x10, 0x0e, 0x06, 0x03, 0x00, 0x80, 0x3f],
|
||||
};
|
||||
const FMAMK: Fixture = Fixture {
|
||||
source: "v_fmamk_f32 v7, v8, 0x40000001, v9",
|
||||
bytes: &[0x08, 0x13, 0x0e, 0x58, 0x01, 0x00, 0x00, 0x40],
|
||||
};
|
||||
const FMAAK: Fixture = Fixture {
|
||||
source: "v_fmaak_f32 v7, v8, v9, 0x40000002",
|
||||
bytes: &[0x08, 0x13, 0x0e, 0x5a, 0x02, 0x00, 0x00, 0x40],
|
||||
};
|
||||
const VOPC_LITERAL: Fixture = Fixture {
|
||||
source: "v_cmp_eq_u32_e32 vcc_lo, 0x1235, v9",
|
||||
bytes: &[0xff, 0x12, 0x84, 0x7d, 0x35, 0x12, 0x00, 0x00],
|
||||
};
|
||||
const VOP3_LITERAL: Fixture = Fixture {
|
||||
source: "v_fma_f32 v7, v8, v9, 0x3f800003",
|
||||
bytes: &[
|
||||
0x07, 0x00, 0x4b, 0xd5, 0x08, 0x13, 0xfe, 0x03, 0x03, 0x00, 0x80, 0x3f,
|
||||
],
|
||||
};
|
||||
const VOP3P_LITERAL: Fixture = Fixture {
|
||||
source: "v_pk_fma_f16 v7, v8, v9, 0x3c02",
|
||||
bytes: &[
|
||||
0x07, 0x40, 0x0e, 0xcc, 0x08, 0x13, 0xfe, 0x1b, 0x02, 0x3c, 0x00, 0x00,
|
||||
],
|
||||
};
|
||||
const VOP1_SDWA: Fixture = Fixture {
|
||||
source: "v_mov_b32_sdwa v7, v8 dst_sel:BYTE_1 dst_unused:UNUSED_PAD src0_sel:DWORD",
|
||||
bytes: &[0xf9, 0x02, 0x0e, 0x7e, 0x08, 0x01, 0x06, 0x00],
|
||||
};
|
||||
const VOP2_SDWA: Fixture = Fixture {
|
||||
source: "v_add_f32_sdwa v7, v8, v9 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:DWORD",
|
||||
bytes: &[0xf9, 0x12, 0x0e, 0x06, 0x08, 0x06, 0x04, 0x06],
|
||||
};
|
||||
const VOPC_SDWA: Fixture = Fixture {
|
||||
source: "v_cmp_eq_u32_sdwa s4, v8, v9 src0_sel:DWORD src1_sel:DWORD",
|
||||
bytes: &[0xf9, 0x12, 0x84, 0x7d, 0x08, 0x84, 0x06, 0x06],
|
||||
};
|
||||
const DPP16: Fixture = Fixture {
|
||||
source: "v_add_f32_dpp v7, v8, v9 row_shl:2 row_mask:0xf bank_mask:0xf",
|
||||
bytes: &[0xfa, 0x12, 0x0e, 0x06, 0x08, 0x02, 0x01, 0xff],
|
||||
};
|
||||
const DPP8: Fixture = Fixture {
|
||||
source: "v_mov_b32_dpp v7, v8 dpp8:[2,3,0,1,6,7,4,5]",
|
||||
bytes: &[0xe9, 0x02, 0x0e, 0x7e, 0x08, 0x1a, 0xe2, 0xb3],
|
||||
};
|
||||
const DPP8_FI: Fixture = Fixture {
|
||||
source: "v_mov_b32_dpp v7, v8 dpp8:[2,3,0,1,6,7,4,5] fi:1",
|
||||
bytes: &[0xea, 0x02, 0x0e, 0x7e, 0x08, 0x1a, 0xe2, 0xb3],
|
||||
};
|
||||
const NSA1: Fixture = Fixture {
|
||||
source: "image_sample v[4:7], [v8, v10], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D",
|
||||
bytes: &[
|
||||
0x0a, 0x0f, 0x80, 0xf0, 0x08, 0x04, 0x40, 0x00, 0x0a, 0x00, 0x00, 0x00,
|
||||
],
|
||||
};
|
||||
const NSA2: Fixture = Fixture {
|
||||
source: "image_sample_d v[4:7], [v8, v10, v12, v14, v16, v18], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D",
|
||||
bytes: &[
|
||||
0x0c, 0x0f, 0x88, 0xf0, 0x08, 0x04, 0x40, 0x00, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x00, 0x00,
|
||||
0x00,
|
||||
],
|
||||
};
|
||||
const NSA3: Fixture = Fixture {
|
||||
source: "image_sample_c_d_cl v[4:7], [v8, v10, v12, v14, v16, v18, v20, v22, v24, v26, v28], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_3D",
|
||||
bytes: &[
|
||||
0x16, 0x0f, 0xac, 0xf0, 0x08, 0x04, 0x40, 0x00, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16,
|
||||
0x18, 0x1a, 0x1c, 0x00, 0x00,
|
||||
],
|
||||
};
|
||||
const FRACT_F64: Fixture = Fixture {
|
||||
source: "v_fract_f64_e32 v[6:7], v[8:9]",
|
||||
bytes: &[0x08, 0x7d, 0x0c, 0x7e],
|
||||
};
|
||||
const READFIRSTLANE: Fixture = Fixture {
|
||||
source: "v_readfirstlane_b32 s7, v8",
|
||||
bytes: &[0x08, 0x05, 0x0e, 0x7e],
|
||||
};
|
||||
const FMAC: Fixture = Fixture {
|
||||
source: "v_fmac_f32_e32 v7, v8, v9",
|
||||
bytes: &[0x08, 0x13, 0x0e, 0x56],
|
||||
};
|
||||
const READLANE: Fixture = Fixture {
|
||||
source: "v_readlane_b32 s7, v8, s9",
|
||||
bytes: &[0x07, 0x00, 0x60, 0xd7, 0x08, 0x13, 0x00, 0x02],
|
||||
};
|
||||
const NOP: Fixture = Fixture {
|
||||
source: "s_nop 7",
|
||||
bytes: &[0x07, 0x00, 0x80, 0xbf],
|
||||
};
|
||||
const VOPC_REGISTER: Fixture = Fixture {
|
||||
source: "v_cmp_eq_u32_e32 vcc_lo, v8, v9",
|
||||
bytes: &[0x08, 0x13, 0x84, 0x7d],
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn proper_prefixes_report_exact_required_lengths() {
|
||||
// Each row cuts at every dword boundary and one byte before the end.
|
||||
// LLVM emits no original instruction for any prefix. Below, "silent"
|
||||
// means no diagnostic, and "invalid" means LLVM's invalid encoding warning.
|
||||
// Empty input is silent in all rows. The expected values are the next
|
||||
// base boundary (4 or 8) until the base is present, then the LLVM length.
|
||||
let cases: &[(&Fixture, &[usize])] = &[
|
||||
// silent, SSRC0 selects the literal dword.
|
||||
(&SOP2_LITERAL, &[4, 8, 8]),
|
||||
// invalid, mandatory SOPK immediate.
|
||||
(&SOPK_IMMEDIATE, &[4, 8, 8]),
|
||||
// silent, literal selector.
|
||||
(&VOP1_LITERAL, &[4, 8, 8]),
|
||||
// silent, literal selector.
|
||||
(&VOP2_LITERAL, &[4, 8, 8]),
|
||||
// invalid, embedded multiplier dword.
|
||||
(&FMAMK, &[4, 8, 8]),
|
||||
// invalid, embedded addend dword.
|
||||
(&FMAAK, &[4, 8, 8]),
|
||||
// silent, literal selector.
|
||||
(&VOPC_LITERAL, &[4, 8, 8]),
|
||||
// invalid at 4 then silent, 8-byte base and literal.
|
||||
(&VOP3_LITERAL, &[4, 8, 12, 12]),
|
||||
// invalid at 4 then silent, 8-byte base and literal.
|
||||
(&VOP3P_LITERAL, &[4, 8, 12, 12]),
|
||||
// invalid, SDWA control dword.
|
||||
(&VOP1_SDWA, &[4, 8, 8]),
|
||||
// invalid, SDWA control dword.
|
||||
(&VOP2_SDWA, &[4, 8, 8]),
|
||||
// invalid, SDWAB control dword.
|
||||
(&VOPC_SDWA, &[4, 8, 8]),
|
||||
// invalid, DPP16 control dword.
|
||||
(&DPP16, &[4, 8, 8]),
|
||||
// invalid, DPP8 control dword (fi:0).
|
||||
(&DPP8, &[4, 8, 8]),
|
||||
// invalid, DPP8 control dword (fi:1).
|
||||
(&DPP8_FI, &[4, 8, 8]),
|
||||
// invalid, 8-byte base and one NSA dword.
|
||||
(&NSA1, &[4, 8, 12, 12]),
|
||||
// invalid, 8-byte base and two NSA dwords.
|
||||
// LLVM also prints a stray v_mul_f32 from the address bytes.
|
||||
(&NSA2, &[4, 8, 16, 16, 16]),
|
||||
// invalid, 8-byte base and three NSA dwords.
|
||||
// LLVM also prints stray v_mul_f32 and v_mul_hi_u32_u24 from the address bytes.
|
||||
(&NSA3, &[4, 8, 20, 20, 20, 20]),
|
||||
];
|
||||
for &(fixture, expected) in cases {
|
||||
let len = fixture.bytes.len();
|
||||
let prefixes: Vec<_> = (0..len).step_by(4).chain([len - 1]).collect();
|
||||
assert_eq!(prefixes.len(), expected.len(), "{}", fixture.source);
|
||||
for (prefix, &needed) in prefixes.into_iter().zip(expected) {
|
||||
assert_eq!(
|
||||
identify(&fixture.bytes[..prefix]),
|
||||
Err(IdentifyError::Truncated { needed }),
|
||||
"{} at {prefix}/{len} bytes",
|
||||
fixture.source,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disallowed_vector_selectors_and_literal_are_rejected() {
|
||||
// Replace the nine-bit SRC0 field of each assembled e32 instruction
|
||||
// and append a known control or literal dword.
|
||||
let cases = [
|
||||
// LLVM rejects SDWA on v_fract_f64. Expect InvalidExtension("sdwa").
|
||||
(&FRACT_F64, SRC_SDWA, &VOP1_SDWA, "sdwa"),
|
||||
// LLVM rejects DPP16 on v_fract_f64. Expect InvalidExtension("dpp16").
|
||||
(&FRACT_F64, SRC_DPP16, &DPP16, "dpp16"),
|
||||
// LLVM rejects DPP8 on v_fract_f64 and prints the trailer as s_cmpk_lt_i32.
|
||||
// Expect InvalidExtension("dpp8") for the rejected first instruction.
|
||||
(&FRACT_F64, SRC_DPP8, &DPP8, "dpp8"),
|
||||
// LLVM rejects SDWA on v_fmac_f32. Expect InvalidExtension("sdwa").
|
||||
(&FMAC, SRC_SDWA, &VOP1_SDWA, "sdwa"),
|
||||
// LLVM rejects DPP16 on this v_cmp_eq_u32. Expect InvalidExtension("dpp16").
|
||||
(&VOPC_REGISTER, SRC_DPP16, &DPP16, "dpp16"),
|
||||
// LLVM prints v_readfirstlane_b32 with "Invalid immediate" because
|
||||
// this source must be a VGPR. Expect InvalidExtension("literal").
|
||||
(&READFIRSTLANE, SRC_LITERAL, &VOP1_LITERAL, "literal"),
|
||||
];
|
||||
for (fixture, selector, trailer, reason) in cases {
|
||||
let mut bytes = fixture.bytes.to_vec();
|
||||
let word = u32::from_le_bytes(fixture.bytes.try_into().unwrap());
|
||||
bytes.copy_from_slice(&((word & !0x1ff) | selector).to_le_bytes());
|
||||
bytes.extend_from_slice(&trailer.bytes[4..]);
|
||||
assert_eq!(
|
||||
identify(&bytes),
|
||||
Err(IdentifyError::InvalidExtension(reason)),
|
||||
"{} with SRC0={selector:#x}: {bytes:02x?}",
|
||||
fixture.source,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_for_vop3_readlane_is_rejected() {
|
||||
// v_readlane_b32: change SRC0 in the second base dword at bits 8:0
|
||||
// and append the v_mov_b32 literal. LLVM prints "Invalid immediate"
|
||||
// for the VGPR-only source. Expect the form to reject the literal.
|
||||
let mut bytes = READLANE.bytes.to_vec();
|
||||
let word = u32::from_le_bytes(bytes[4..8].try_into().unwrap());
|
||||
bytes[4..8].copy_from_slice(&((word & !0x1ff) | SRC_LITERAL).to_le_bytes());
|
||||
bytes.extend_from_slice(&VOP1_LITERAL.bytes[4..]);
|
||||
assert_eq!(
|
||||
identify(&bytes),
|
||||
Err(IdentifyError::InvalidExtension("literal"))
|
||||
);
|
||||
}
|
||||
|
||||
/// Identification recognizes length independently of control-word validation.
|
||||
#[test]
|
||||
fn reserved_control_values_keep_their_trailer_lengths() {
|
||||
let cases = [
|
||||
// v_add_f32_dpp: replace DPP_CTRL 0x102 with 0x100, which LLVM reports as reserved.
|
||||
// LLVM prints "Invalid dpp_ctrl value". Expect 8 bytes and DPP16.
|
||||
(&DPP16, 5, 0, "V_ADD_F32", VectorControl::Dpp16),
|
||||
// v_mov_b32_sdwa: change SRC0_SEL from 6 to 7, which LLVM treats as reserved.
|
||||
// LLVM prints DWORD and reassembles it as 6. Expect 8 bytes and SDWA.
|
||||
(&VOP1_SDWA, 6, 7, "V_MOV_B32", VectorControl::Sdwa),
|
||||
];
|
||||
for (fixture, offset, value, name, control) in cases {
|
||||
let mut bytes = fixture.bytes.to_vec();
|
||||
bytes[offset] = value;
|
||||
let found = identify(&bytes).unwrap();
|
||||
assert_eq!(found.form.name, name);
|
||||
assert_eq!(found.len, 8);
|
||||
assert_eq!(
|
||||
found.trailer,
|
||||
Trailer {
|
||||
vector_control: Some(control),
|
||||
..Trailer::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_instruction_starts_after_the_trailer() {
|
||||
// Append s_nop 7 to each original instruction. LLVM disassembles the
|
||||
// two instructions with lengths (offset, 4). Expect that boundary from
|
||||
// identify and the trailer selected by SRC0, SSRC0, or MIMG.NSA.
|
||||
let cases = [
|
||||
// LLVM emits s_nop at byte 8. Expect a scalar literal dword.
|
||||
(
|
||||
&SOP2_LITERAL,
|
||||
"S_ADD_U32",
|
||||
8,
|
||||
Trailer {
|
||||
literal: true,
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 8. Expect an SDWA control dword.
|
||||
(
|
||||
&VOP1_SDWA,
|
||||
"V_MOV_B32",
|
||||
8,
|
||||
Trailer {
|
||||
vector_control: Some(VectorControl::Sdwa),
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 8. Expect a DPP16 control dword.
|
||||
(
|
||||
&DPP16,
|
||||
"V_ADD_F32",
|
||||
8,
|
||||
Trailer {
|
||||
vector_control: Some(VectorControl::Dpp16),
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 8. Expect DPP8 with fi:0.
|
||||
(
|
||||
&DPP8,
|
||||
"V_MOV_B32",
|
||||
8,
|
||||
Trailer {
|
||||
vector_control: Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: false,
|
||||
}),
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 8. Expect DPP8 with fi:1.
|
||||
(
|
||||
&DPP8_FI,
|
||||
"V_MOV_B32",
|
||||
8,
|
||||
Trailer {
|
||||
vector_control: Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true,
|
||||
}),
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 12. Expect one NSA dword.
|
||||
(
|
||||
&NSA1,
|
||||
"IMAGE_SAMPLE",
|
||||
12,
|
||||
Trailer {
|
||||
nsa_dwords: 1,
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 16. Expect two NSA dwords.
|
||||
(
|
||||
&NSA2,
|
||||
"IMAGE_SAMPLE_D",
|
||||
16,
|
||||
Trailer {
|
||||
nsa_dwords: 2,
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 20. Expect three NSA dwords.
|
||||
(
|
||||
&NSA3,
|
||||
"IMAGE_SAMPLE_C_D_CL",
|
||||
20,
|
||||
Trailer {
|
||||
nsa_dwords: 3,
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
];
|
||||
for (fixture, name, offset, trailer) in cases {
|
||||
let bytes = [fixture.bytes, NOP.bytes].concat();
|
||||
let first = identify(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
(first.form.name, first.len, first.trailer),
|
||||
(name, offset, trailer),
|
||||
"{} followed by {}",
|
||||
fixture.source,
|
||||
NOP.source,
|
||||
);
|
||||
let second = identify(&bytes[first.len..]).unwrap();
|
||||
assert_eq!(
|
||||
(second.form.name, second.len, second.trailer),
|
||||
("S_NOP", 4, Trailer::default()),
|
||||
);
|
||||
assert_eq!(first.len + second.len, bytes.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
|
||||
fn source_encodings_match_llvm() {
|
||||
let fixtures = [
|
||||
&SOP2_LITERAL,
|
||||
&SOPK_IMMEDIATE,
|
||||
&VOP1_LITERAL,
|
||||
&VOP2_LITERAL,
|
||||
&FMAMK,
|
||||
&FMAAK,
|
||||
&VOPC_LITERAL,
|
||||
&VOP3_LITERAL,
|
||||
&VOP3P_LITERAL,
|
||||
&VOP1_SDWA,
|
||||
&VOP2_SDWA,
|
||||
&VOPC_SDWA,
|
||||
&DPP16,
|
||||
&DPP8,
|
||||
&DPP8_FI,
|
||||
&NSA1,
|
||||
&NSA2,
|
||||
&NSA3,
|
||||
&FRACT_F64,
|
||||
&READFIRSTLANE,
|
||||
&FMAC,
|
||||
&READLANE,
|
||||
&NOP,
|
||||
&VOPC_REGISTER,
|
||||
];
|
||||
let executable = std::env::var_os("LLVM_BIN").map_or_else(
|
||||
|| "llvm-mc".into(),
|
||||
|directory| std::path::PathBuf::from(directory).join("llvm-mc"),
|
||||
);
|
||||
let mut llvm = Command::new(executable)
|
||||
.args([
|
||||
"-triple=amdgcn-amd-amdhsa",
|
||||
"-mcpu=gfx1030",
|
||||
"-mattr=+wavefrontsize32",
|
||||
"-show-encoding",
|
||||
])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("launch llvm-mc (provide its directory in LLVM_BIN or put it on PATH)");
|
||||
{
|
||||
let mut input = llvm.stdin.take().unwrap();
|
||||
for fixture in fixtures {
|
||||
writeln!(input, "{}", fixture.source).unwrap();
|
||||
}
|
||||
}
|
||||
let output = llvm.wait_with_output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
let assembly = String::from_utf8(output.stdout).unwrap();
|
||||
let encodings: Vec<_> = assembly
|
||||
.lines()
|
||||
.filter_map(|line| line.split_once("; encoding: [").map(|(_, bytes)| bytes))
|
||||
.collect();
|
||||
assert_eq!(encodings.len(), fixtures.len());
|
||||
for (fixture, encoding) in fixtures.into_iter().zip(encodings) {
|
||||
let bytes: Vec<_> = encoding
|
||||
.strip_suffix(']')
|
||||
.unwrap()
|
||||
.split(',')
|
||||
.map(|byte| u8::from_str_radix(byte.trim().strip_prefix("0x").unwrap(), 16).unwrap())
|
||||
.collect();
|
||||
assert_eq!(bytes, fixture.bytes, "{}", fixture.source);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Regenerate the gfx1030 Wave32 instruction-identification oracle corpus."""
|
||||
|
||||
import argparse
|
||||
from collections import defaultdict
|
||||
from itertools import islice, zip_longest
|
||||
from pathlib import Path
|
||||
import random
|
||||
import re
|
||||
import runpy
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ISA = HERE.parents[1]
|
||||
TARGET = ("-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1030", "-mattr=+wavefrontsize32")
|
||||
BASE_32 = {"SOP1", "SOP2", "SOPC", "SOPK", "SOPP", "VINTRP", "VOP1", "VOP2", "VOPC"}
|
||||
ENCODING = re.compile(r"^\s*(.*?)\s*; encoding: \[([^\]]+)\]", re.MULTILINE)
|
||||
SECTION = re.compile(r"^Disassembly of section \.text\.(\d+):")
|
||||
# Instruction text, offset, consumed words, then optional trailing text: a
|
||||
# branch-target annotation such as `<.text+0x841c>` or an LLVM warning such as
|
||||
# `; Warning: ... scalar reg isn't aligned`, neither of which stops decoding.
|
||||
INSTRUCTION = re.compile(r"^\t(.*?)\s*// ([0-9A-F]{12}): ((?:[0-9A-F]{8}(?: |$))+)(.*)$")
|
||||
|
||||
|
||||
def llvm(executable, *args, source=None):
|
||||
return subprocess.run(
|
||||
[executable, *TARGET, "-show-encoding", *args],
|
||||
input=source, text=True, capture_output=True, check=True,
|
||||
)
|
||||
|
||||
|
||||
def encodings(output):
|
||||
for text, bytes_text in ENCODING.findall(output):
|
||||
yield " ".join(text.split()), bytes(int(token, 16) for token in bytes_text.split(","))
|
||||
|
||||
|
||||
def disassemble_batch(llvm_bin, blobs):
|
||||
"""LLVM's decode of the first instruction of each blob.
|
||||
|
||||
Each blob goes into its own section of one object built from `.byte`
|
||||
directives; llvm-objdump disassembles every section from offset zero and
|
||||
prints the words it consumed. That length is what the decoder read, not the
|
||||
length of a re-encoding (llvm-mc --disassemble re-encodes, which shortens
|
||||
inconsistent MIMG NSA probes). Returns (text, consumed bytes) or None when
|
||||
LLVM cannot decode offset zero (it prints `.long`/`.short`/`.byte`).
|
||||
"""
|
||||
source = []
|
||||
for index, blob in enumerate(blobs):
|
||||
source.append(f'.section .text.{index},"ax"')
|
||||
if blob:
|
||||
source.append(".byte " + ",".join(f"0x{byte:02x}" for byte in blob))
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
assembly_path = Path(directory) / "probes.s"
|
||||
object_path = Path(directory) / "probes.o"
|
||||
assembly_path.write_text("\n".join(source) + "\n")
|
||||
subprocess.run(
|
||||
[llvm_bin / "llvm-mc", *TARGET, "-filetype=obj", assembly_path, "-o", object_path],
|
||||
check=True, capture_output=True,
|
||||
)
|
||||
dump = subprocess.run(
|
||||
[llvm_bin / "llvm-objdump", "-d", "--mcpu=gfx1030", "--mattr=+wavefrontsize32", object_path],
|
||||
check=True, capture_output=True, text=True,
|
||||
).stdout
|
||||
first = {}
|
||||
section = None
|
||||
for line in dump.splitlines():
|
||||
header = SECTION.match(line)
|
||||
if header:
|
||||
section = int(header.group(1))
|
||||
continue
|
||||
instruction = INSTRUCTION.match(line)
|
||||
if section is None or section in first or not instruction:
|
||||
continue
|
||||
text, offset, words, warning = instruction.groups()
|
||||
if int(offset, 16) != 0:
|
||||
continue
|
||||
if text.startswith((".long", ".short", ".byte")):
|
||||
first[section] = None
|
||||
else:
|
||||
text = " ".join(text.split())
|
||||
warning = warning.strip()
|
||||
if warning.startswith(";"):
|
||||
text += f" [LLVM: {warning.lstrip('; ')}]"
|
||||
first[section] = (text, 4 * len(words.split()))
|
||||
return [first.get(index) for index in range(len(blobs))]
|
||||
|
||||
|
||||
CRASHED = "crashed"
|
||||
|
||||
|
||||
def disassemble_all(llvm_bin, blobs):
|
||||
"""Batches of 128; a batch that crashes llvm-objdump is split until the
|
||||
crashing blobs are isolated, and each of those is reported as CRASHED."""
|
||||
results = []
|
||||
for start in range(0, len(blobs), 128):
|
||||
results.extend(_isolate(llvm_bin, blobs[start:start + 128]))
|
||||
return results
|
||||
|
||||
|
||||
def _isolate(llvm_bin, blobs):
|
||||
try:
|
||||
return disassemble_batch(llvm_bin, blobs)
|
||||
except subprocess.CalledProcessError as error:
|
||||
if error.returncode != -11:
|
||||
raise
|
||||
if len(blobs) == 1:
|
||||
return [CRASHED]
|
||||
half = len(blobs) // 2
|
||||
return _isolate(llvm_bin, blobs[:half]) + _isolate(llvm_bin, blobs[half:])
|
||||
|
||||
|
||||
def extension(text, length, family):
|
||||
mnemonic = text.split()[0]
|
||||
if "dpp8:" in text:
|
||||
return "dpp8fi" if "fi:1" in text else "dpp8"
|
||||
if mnemonic.endswith("_dpp"):
|
||||
return "dpp16"
|
||||
if mnemonic.endswith("_sdwa"):
|
||||
return "sdwa"
|
||||
base_bytes = 4 if family in BASE_32 else 8
|
||||
if mnemonic.endswith("_e64"):
|
||||
base_bytes = 8
|
||||
extra = length - base_bytes
|
||||
if mnemonic.startswith("image_") and extra > 0:
|
||||
return f"nsa{extra // 4}"
|
||||
# After excluding vector control and image addresses, an extra dword
|
||||
# carrying a numeric operand is the literal (including mandatory literals).
|
||||
if extra == 4 and re.search(r"(?:,|\s)\s*-?(?:0x[\da-f]+|\d+)(?=,|\s|$|/\*)", text):
|
||||
return "literal"
|
||||
if extra > 0:
|
||||
raise ValueError(f"unclassified LLVM extension: {length} bytes {text}")
|
||||
return "-"
|
||||
|
||||
|
||||
def assembly(executable):
|
||||
source = HERE / "corpus.s"
|
||||
families = [
|
||||
line.split("//", 1)[1].strip()
|
||||
for line in source.read_text().splitlines()
|
||||
if line.split("//", 1)[0].strip()
|
||||
]
|
||||
result = llvm(executable, source)
|
||||
if result.stderr:
|
||||
raise ValueError(result.stderr)
|
||||
decoded = list(encodings(result.stdout))
|
||||
if len(decoded) != len(families):
|
||||
raise ValueError("LLVM must emit exactly one encoding per assembly line")
|
||||
return [(family, text, data) for family, (text, data) in zip(families, decoded)]
|
||||
|
||||
|
||||
def metadata_forms():
|
||||
snapshot = ISA / "data/rdna2.jsonl"
|
||||
project = runpy.run_path(str(ISA / "generate_rdna2_meta.py"))["forms_from_snapshot"]
|
||||
return project(snapshot.read_text())[2]
|
||||
|
||||
|
||||
def probes():
|
||||
# The normalized snapshot stores instruction variants and encoding records
|
||||
# separately. Reuse its projection to obtain identifiers, widths and labels
|
||||
# for coverage. The projected mnemonic and extensions are never consulted.
|
||||
forms = metadata_forms()
|
||||
rng = random.Random(209)
|
||||
for form in forms:
|
||||
width = form["bytes"]
|
||||
# One probe with every non-identifying bit zero (operands s0/v0, no
|
||||
# modifiers), then two with seeded random operand bits.
|
||||
yield "zero", form["encoding"].upper(), form["bits"].to_bytes(width, "little") + bytes(16)
|
||||
for _ in range(2):
|
||||
value = form["bits"] | (rng.getrandbits(width * 8) & ~form["mask"])
|
||||
yield "random", form["encoding"].upper(), value.to_bytes(width, "little") + rng.randbytes(16)
|
||||
|
||||
|
||||
# Extension selectors from the RDNA 2 ISA reference: the SRC0 (VOP1, VOP2,
|
||||
# VOPC, VOP3*) or SSRC0 (SOP1, SOP2, SOPC) value that makes one extra dword
|
||||
# follow the base encoding.
|
||||
SELECTORS = {"literal": 0xFF, "sdwa": 0xF9, "dpp16": 0xFA, "dpp8": 0xE9, "dpp8fi": 0xEA}
|
||||
# Instructions whose last dword is a legal control word for each extension;
|
||||
# LLVM assembles them, so the control words are LLVM's own.
|
||||
CONTROL_SOURCES = {
|
||||
"sdwa": "v_add_f32_sdwa v0, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD",
|
||||
"sdwa-vop1": "v_mov_b32_sdwa v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD",
|
||||
"sdwa-vopc": "v_cmp_eq_f32_sdwa vcc_lo, v0, v0 src0_sel:DWORD src1_sel:DWORD",
|
||||
"dpp16": "v_add_f32_dpp v0, v0, v0 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf",
|
||||
"dpp8": "v_add_f32_dpp v0, v0, v0 dpp8:[0,1,2,3,4,5,6,7]",
|
||||
"dpp8fi": "v_add_f32_dpp v0, v0, v0 dpp8:[0,1,2,3,4,5,6,7] fi:1",
|
||||
}
|
||||
LITERAL = (0x12345678).to_bytes(4, "little")
|
||||
|
||||
|
||||
def controls(executable):
|
||||
source = "\n".join(CONTROL_SOURCES.values()) + "\n"
|
||||
decoded = list(encodings(llvm(executable, source=source).stdout))
|
||||
return {name: data[-4:] for name, (_, data) in zip(CONTROL_SOURCES, decoded)}
|
||||
|
||||
|
||||
def extension_probes(executable, forms):
|
||||
"""Every form's zero-operand base with each extension selector its family
|
||||
can carry, followed by a legal control dword or literal. LLVM decides which
|
||||
combinations are instructions; the metadata's extension list is not read."""
|
||||
control = controls(executable)
|
||||
for form in forms:
|
||||
family = form["encoding"].upper()
|
||||
base = form["bits"]
|
||||
if family in ("VOP1", "VOP2", "VOPC"):
|
||||
kinds = ["literal", "sdwa", "dpp16", "dpp8", "dpp8fi"]
|
||||
shift = 0
|
||||
elif family in ("VOP3", "VOP3SDST", "VOP3P"):
|
||||
kinds, shift = ["literal"], 32
|
||||
elif family in ("SOP1", "SOP2", "SOPC"):
|
||||
kinds, shift = ["literal"], 0
|
||||
else:
|
||||
continue
|
||||
field = 0x1FF if shift == 32 or family.startswith("VOP") else 0xFF
|
||||
if base & form["mask"] & (field << shift):
|
||||
continue # SRC0/SSRC0 is part of this form's identifier
|
||||
for kind in kinds:
|
||||
value = (base & ~(field << shift)) | (SELECTORS[kind] << shift)
|
||||
if kind == "literal":
|
||||
trailer = LITERAL
|
||||
elif kind == "sdwa" and family in ("VOPC", "VOP1"):
|
||||
trailer = control[f"sdwa-{family.lower()}"]
|
||||
else:
|
||||
trailer = control[kind]
|
||||
yield kind, family, value.to_bytes(form["bytes"], "little") + trailer + bytes(12)
|
||||
|
||||
|
||||
def truncations(entries):
|
||||
by_family = defaultdict(list)
|
||||
for entry in entries:
|
||||
by_family[entry[0]].append(entry)
|
||||
groups = [
|
||||
sorted(group, key=lambda entry: -len(entry[2]))
|
||||
for _, group in sorted(by_family.items())
|
||||
]
|
||||
interleaved = (entry for batch in zip_longest(*groups) for entry in batch if entry)
|
||||
yield from islice(interleaved, 40)
|
||||
|
||||
|
||||
def decoded_columns(text, length, family):
|
||||
return text.split()[0], str(length), extension(text, length, family)
|
||||
|
||||
|
||||
def generate(llvm_bin):
|
||||
rows = []
|
||||
entries = assembly(llvm_bin / "llvm-mc")
|
||||
for family, text, data in entries:
|
||||
rows.append(("asm", data.hex(), *decoded_columns(text, len(data), family), f"{family} {text}"))
|
||||
probe_list = list(probes()) + [
|
||||
(f"ext-{kind}", family, data)
|
||||
for kind, family, data in extension_probes(llvm_bin / "llvm-mc", metadata_forms())
|
||||
]
|
||||
cut_list = [
|
||||
(family, text, data, data[:size])
|
||||
for family, text, data in truncations(entries)
|
||||
for size in range(0, len(data), 4)
|
||||
]
|
||||
decoded_all = disassemble_all(llvm_bin, [data for _, _, data in probe_list] + [cut for *_, cut in cut_list])
|
||||
for (kind, family, data), decoded in zip(probe_list, decoded_all):
|
||||
if decoded is None:
|
||||
columns = ("invalid", "0", "-")
|
||||
note = "LLVM cannot decode offset zero"
|
||||
elif decoded == CRASHED:
|
||||
columns = ("crashed", "0", "-")
|
||||
note = "llvm-objdump crashed (SIGSEGV)"
|
||||
elif "/*Invalid" not in decoded[0]:
|
||||
text, length = decoded
|
||||
columns = decoded_columns(text, length, family)
|
||||
note = text
|
||||
if decoded not in (None, CRASHED) and "/*Invalid" in decoded[0]:
|
||||
# LLVM decodes the words (so it knows the opcode and the length)
|
||||
# but flags an operand the instruction cannot take, for example an
|
||||
# SGPR or literal for a VGPR-only source.
|
||||
text, length = decoded
|
||||
mnemonic, *rest = decoded_columns(text, length, family)
|
||||
columns = (f"invalid-operand:{mnemonic}", *rest)
|
||||
note = text
|
||||
source = f"probe-{kind}" if kind in ("zero", "random") else "probe-ext"
|
||||
if kind.startswith("ext-"):
|
||||
note = f"{kind[4:]} {note}"
|
||||
rows.append((source, data.hex(), *columns, f"{family} {note}"))
|
||||
for (family, text, data, prefix), decoded in zip(cut_list, decoded_all[len(probe_list):]):
|
||||
if decoded is None:
|
||||
observed = "cannot decode" if prefix else "no instruction"
|
||||
elif decoded == CRASHED:
|
||||
observed = "crashed (SIGSEGV)"
|
||||
else:
|
||||
observed = f"decoded {decoded[1]} bytes: {decoded[0]}"
|
||||
note = f"{family} LLVM {observed} | cut {data.hex()} {text}"
|
||||
rows.append(("truncation", prefix.hex(), "truncated", "0", "-", note))
|
||||
header = "source\thex\tllvm_mnemonic\tllvm_len\tllvm_ext\tnote\n"
|
||||
return header + "".join("\t".join(row) + "\n" for row in sorted(rows))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--llvm-bin", required=True, type=Path)
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
data = generate(args.llvm_bin.resolve())
|
||||
output = HERE / "corpus.tsv"
|
||||
if args.check:
|
||||
if output.read_bytes() != data.encode():
|
||||
parser.exit(1, f"{output} differs from the LLVM output\n")
|
||||
else:
|
||||
output.write_bytes(data.encode())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,320 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original gfx1030 Wave32 instruction identification cases.
|
||||
s_mov_b32 s105, s0 // SOP1
|
||||
s_mov_b32 exec_lo, -16 // SOP1
|
||||
s_mov_b32 m0, 64 // SOP1
|
||||
s_mov_b32 vcc_hi, 0xdeadbeef // SOP1
|
||||
s_mov_b64 exec, vcc // SOP1
|
||||
s_mov_b64 vcc, 0x12345678 // SOP1
|
||||
s_not_b32 s0, s105 // SOP1
|
||||
s_not_b64 s[104:105], s[0:1] // SOP1
|
||||
s_brev_b32 s105, m0 // SOP1
|
||||
s_bcnt1_i32_b32 s0, exec_lo // SOP1
|
||||
s_ff1_i32_b32 s105, -16 // SOP1
|
||||
s_flbit_i32_b32 s105, 0x80000100 // SOP1
|
||||
s_sext_i32_i8 s0, s105 // SOP1
|
||||
s_sext_i32_i16 s105, s0 // SOP1
|
||||
s_getpc_b64 s[104:105] // SOP1
|
||||
s_setpc_b64 s[0:1] // SOP1
|
||||
s_and_saveexec_b64 s[0:1], s[104:105] // SOP1
|
||||
s_wqm_b64 s[104:105], exec // SOP1
|
||||
s_add_u32 s105, s0, 0x12345678 // SOP2
|
||||
s_add_u32 s0, 0xdeadbeef, s105 // SOP2
|
||||
s_add_i32 s0, -16, 64 // SOP2
|
||||
s_sub_i32 s105, s0, m0 // SOP2
|
||||
s_subb_u32 s0, vcc_lo, exec_lo // SOP2
|
||||
s_min_i32 s105, s104, -16 // SOP2
|
||||
s_max_u32 s0, s105, 64 // SOP2
|
||||
s_cselect_b32 s105, -1, s0 // SOP2
|
||||
s_and_b64 s[104:105], exec, vcc // SOP2
|
||||
s_or_b64 vcc, s[0:1], exec // SOP2
|
||||
s_xor_b32 s0, s0, 0xdeadbeef // SOP2
|
||||
s_nand_b32 s105, m0, vcc_lo // SOP2
|
||||
s_lshl_b32 s0, s105, 31 // SOP2
|
||||
s_lshr_b64 s[104:105], s[0:1], 63 // SOP2
|
||||
s_ashr_i32 s105, 0x87654321, 31 // SOP2
|
||||
s_mul_i32 s0, s105, -16 // SOP2
|
||||
s_bfe_u32 s105, s0, 0x0010000f // SOP2
|
||||
s_cmp_eq_i32 s0, s105 // SOPC
|
||||
s_cmp_lg_i32 m0, -16 // SOPC
|
||||
s_cmp_gt_i32 64, s105 // SOPC
|
||||
s_cmp_ge_i32 s105, 0xdeadbeef // SOPC
|
||||
s_cmp_lt_u32 0x12345678, exec_hi // SOPC
|
||||
s_cmp_le_u32 vcc_lo, 64 // SOPC
|
||||
s_cmp_eq_u64 s[104:105], vcc // SOPC
|
||||
s_bitcmp0_b32 s105, 31 // SOPC
|
||||
s_bitcmp1_b64 exec, 63 // SOPC
|
||||
s_movk_i32 s0, -32768 // SOPK
|
||||
s_movk_i32 s105, 32767 // SOPK
|
||||
s_movk_i32 m0, -1 // SOPK
|
||||
s_addk_i32 s105, -32768 // SOPK
|
||||
s_mulk_i32 s0, 32767 // SOPK
|
||||
s_cmpk_eq_i32 s105, -32768 // SOPK
|
||||
s_cmpk_lg_u32 s0, 65535 // SOPK
|
||||
s_getreg_b32 s105, hwreg(HW_REG_MODE) // SOPK
|
||||
s_setreg_b32 hwreg(HW_REG_MODE, 4, 8), s0 // SOPK
|
||||
s_setreg_imm32_b32 hwreg(HW_REG_MODE, 8, 16), 0xdeadbeef // SOPK
|
||||
s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0 // SOPK
|
||||
s_nop 15 // SOPP
|
||||
s_endpgm 0 // SOPP
|
||||
s_branch -32768 // SOPP
|
||||
s_cbranch_scc0 32767 // SOPP
|
||||
s_cbranch_scc1 -1 // SOPP
|
||||
s_cbranch_vccz 0 // SOPP
|
||||
s_cbranch_vccnz 3 // SOPP
|
||||
s_cbranch_execz 7 // SOPP
|
||||
s_cbranch_execnz -7 // SOPP
|
||||
s_barrier // SOPP
|
||||
s_waitcnt vmcnt(0) lgkmcnt(1) expcnt(7) // SOPP
|
||||
s_sleep 127 // SOPP
|
||||
s_trap 255 // SOPP
|
||||
s_load_dword s105, s[0:1], 1048575 // SMEM
|
||||
s_load_dword s0, s[104:105], -1048576 // SMEM
|
||||
s_load_dwordx2 s[104:105], s[0:1], 0 glc // SMEM
|
||||
s_load_dwordx4 s[0:3], s[100:101], s105 // SMEM
|
||||
s_load_dwordx8 s[96:103], s[0:1], 7 // SMEM
|
||||
s_load_dwordx16 s[0:15], s[104:105], 16 // SMEM
|
||||
s_buffer_load_dword s105, s[0:3], 4095 // SMEM
|
||||
s_buffer_load_dwordx2 s[104:105], s[0:3], 0 // SMEM
|
||||
s_buffer_load_dwordx4 s[0:3], s[100:103], s105 // SMEM
|
||||
s_memtime s[104:105] // SMEM
|
||||
s_dcache_inv // SMEM
|
||||
v_mov_b32_e32 v255, v0 // VOP1
|
||||
v_mov_b32_e32 v0, s105 // VOP1
|
||||
v_mov_b32_e32 v255, 0xdeadbeef // VOP1
|
||||
v_mov_b32_e32 v0, -16 // VOP1
|
||||
v_mov_b32_e32 v255, 64 // VOP1
|
||||
v_mov_b32_e32 v0, 0.5 // VOP1
|
||||
v_mov_b32_e32 v255, -4.0 // VOP1
|
||||
v_mov_b32_e32 v0, 0.15915494 // VOP1
|
||||
v_cvt_f32_i32_e32 v255, v0 // VOP1
|
||||
v_cvt_f32_u32_e32 v0, v255 // VOP1
|
||||
v_cvt_i32_f32_e32 v255, 0x3f800001 // VOP1
|
||||
v_rcp_f32_e32 v0, v255 // VOP1
|
||||
v_sqrt_f32_e32 v255, v0 // VOP1
|
||||
v_readfirstlane_b32 s105, v255 // VOP1
|
||||
v_mov_b32_sdwa v255, v0 dst_sel:BYTE_3 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 // VOP1
|
||||
v_mov_b32_dpp v0, v255 quad_perm:[3,2,1,0] row_mask:0x1 bank_mask:0x8 // VOP1
|
||||
v_mov_b32_dpp v255, v0 row_shl:15 bound_ctrl:1 // VOP1
|
||||
v_mov_b32_dpp v0, v255 row_share:15 // VOP1
|
||||
v_mov_b32_dpp v255, v0 dpp8:[7,6,5,4,3,2,1,0] fi:0 // VOP1
|
||||
v_mov_b32_dpp v0, v255 dpp8:[0,0,0,0,7,7,7,7] fi:1 // VOP1
|
||||
v_mov_b32_e32 v255, 0x3e22f983 // VOP1
|
||||
v_add_f32_e32 v0, v255, v0 // VOP2
|
||||
v_sub_f32_e32 v255, 0x3f800001, v0 // VOP2
|
||||
v_subrev_f32_e32 v0, s105, v255 // VOP2
|
||||
v_mul_f32_e32 v255, -4.0, v0 // VOP2
|
||||
v_mul_i32_i24_e32 v0, -16, v255 // VOP2
|
||||
v_mul_u32_u24_e32 v255, 64, v0 // VOP2
|
||||
v_min_f32_e32 v0, 0.5, v255 // VOP2
|
||||
v_max_f32_e32 v255, 0.15915494, v0 // VOP2
|
||||
v_lshrrev_b32_e32 v0, 31, v255 // VOP2
|
||||
v_ashrrev_i32_e32 v255, 31, v0 // VOP2
|
||||
v_lshlrev_b32_e32 v0, 31, v255 // VOP2
|
||||
v_and_b32_e32 v255, 0xdeadbeef, v0 // VOP2
|
||||
v_or_b32_e32 v0, m0, v255 // VOP2
|
||||
v_xor_b32_e32 v255, vcc_lo, v0 // VOP2
|
||||
v_add_nc_u32_e32 v0, exec_lo, v255 // VOP2
|
||||
v_fmamk_f32 v255, v0, 0x3f800001, v255 // VOP2
|
||||
v_fmaak_f32 v0, v255, v0, 0xdeadbeef // VOP2
|
||||
v_add_f32_sdwa v255, v0, v255 dst_sel:WORD_1 dst_unused:UNUSED_SEXT src0_sel:BYTE_0 src1_sel:WORD_0 // VOP2
|
||||
v_add_f32_dpp v0, v255, v0 row_shl:7 bound_ctrl:1 // VOP2
|
||||
v_mul_f32_dpp v255, v0, v255 dpp8:[1,2,3,4,5,6,7,0] fi:1 // VOP2
|
||||
v_cmp_eq_f32_e32 vcc_lo, 0.5, v255 // VOPC
|
||||
v_cmp_lt_f32_e32 vcc_lo, -4.0, v0 // VOPC
|
||||
v_cmp_ge_f32_e32 vcc_lo, 0x3f800001, v255 // VOPC
|
||||
v_cmp_ne_u32_e32 vcc_lo, 0xdeadbeef, v0 // VOPC
|
||||
v_cmp_gt_i32_e32 vcc_lo, -16, v255 // VOPC
|
||||
v_cmp_le_i32_e32 vcc_lo, s105, v0 // VOPC
|
||||
v_cmpx_eq_u32_e32 64, v255 // VOPC
|
||||
v_cmp_eq_i32_sdwa s105, v255, v0 src0_sel:WORD_0 src1_sel:BYTE_3 // VOPC
|
||||
v_cmp_lt_u32_sdwa vcc_lo, v0, v255 src0_sel:BYTE_1 src1_sel:WORD_1 // VOPC
|
||||
v_cmp_class_f32_e32 vcc_lo, v0, v255 // VOPC
|
||||
v_add_f32_e64 v255, -v0, |v255| clamp // VOP3
|
||||
v_add_f32_e64 v0, 0x3f800001, v255 // VOP3
|
||||
v_mul_f32_e64 v255, v0, 0.5 mul:2 // VOP3
|
||||
v_fma_f32 v0, v255, 0x3f800001, v0 // VOP3
|
||||
v_fma_f32 v255, -v0, |v255|, -4.0 // VOP3
|
||||
v_mad_u32_u24 v0, v255, 64, v0 // VOP3
|
||||
v_mad_i32_i24 v255, v0, -16, v255 // VOP3
|
||||
v_min3_f32 v0, v255, v0, 0.5 // VOP3
|
||||
v_max3_i32 v255, v0, v255, -16 // VOP3
|
||||
v_med3_u32 v0, v255, v0, 64 // VOP3
|
||||
v_bfe_u32 v255, v0, 31, 1 // VOP3
|
||||
v_bfe_i32 v0, v255, 0, 32 // VOP3
|
||||
v_bfi_b32 v255, v0, v255, 0x12345678 // VOP3
|
||||
v_alignbit_b32 v0, v255, v0, 31 // VOP3
|
||||
v_cmp_eq_u32_e64 s105, v255, 0xdeadbeef // VOP3
|
||||
v_readlane_b32 s105, v255, 31 // VOP3
|
||||
v_writelane_b32 v255, s105, 31 // VOP3
|
||||
v_add_co_u32 v255, s105, v0, v255 // VOP3SDST
|
||||
v_add_co_u32 v0, vcc_lo, 0xdeadbeef, v255 // VOP3SDST
|
||||
v_sub_co_u32 v255, s0, v0, v255 // VOP3SDST
|
||||
v_subrev_co_u32 v0, s105, v255, v0 // VOP3SDST
|
||||
v_div_scale_f32 v255, s105, v0, v0, v255 // VOP3SDST
|
||||
v_div_scale_f64 v[254:255], vcc_lo, v[0:1], v[0:1], v[2:3] // VOP3SDST
|
||||
v_pk_add_f16 v255, v0, v255 op_sel:[1,0] op_sel_hi:[0,1] // VOP3P
|
||||
v_pk_mul_f16 v0, v255, 0x3c01 // VOP3P
|
||||
v_pk_fma_f16 v255, v0, v255, 0x3c01 // VOP3P
|
||||
v_pk_add_i16 v0, v255, 64 clamp // VOP3P
|
||||
v_pk_sub_i16 v255, v0, -16 // VOP3P
|
||||
v_pk_mul_lo_u16 v0, v255, v0 // VOP3P
|
||||
v_pk_min_i16 v255, v0, v255 // VOP3P
|
||||
v_pk_max_u16 v0, v255, v0 // VOP3P
|
||||
v_pk_lshlrev_b16 v255, 15, v0 // VOP3P
|
||||
v_dot2_f32_f16 v0, v255, v0, 0.5 // VOP3P
|
||||
v_interp_p1_f32 v255, v0, attr32.w // VINTRP
|
||||
v_interp_p2_f32 v0, v255, attr0.x // VINTRP
|
||||
v_interp_mov_f32 v255, p0, attr32.y // VINTRP
|
||||
v_interp_mov_f32 v0, p10, attr1.z // VINTRP
|
||||
v_interp_p1_f32 v0, v255, attr1.y // VINTRP
|
||||
v_interp_p2_f32 v255, v0, attr31.z // VINTRP
|
||||
ds_write_b32 v255, v0 offset:65535 // DS
|
||||
ds_read_b32 v0, v255 offset:65535 // DS
|
||||
ds_write_b8 v0, v255 offset:0 // DS
|
||||
ds_write_b16 v255, v0 offset:32768 // DS
|
||||
ds_read_u8 v0, v255 offset:1 // DS
|
||||
ds_read_i16 v255, v0 offset:65534 // DS
|
||||
ds_write_b64 v255, v[254:255] offset:8 // DS
|
||||
ds_read_b64 v[0:1], v255 offset:16 // DS
|
||||
ds_write2_b32 v0, v255, v0 offset0:255 offset1:0 // DS
|
||||
ds_read2_b32 v[254:255], v0 offset0:0 offset1:255 // DS
|
||||
ds_add_u32 v255, v0 offset:65535 // DS
|
||||
ds_add_rtn_u32 v0, v255, v0 offset:1 // DS
|
||||
ds_cmpst_b32 v0, v255, v0 offset:32 // DS
|
||||
ds_bpermute_b32 v255, v0, v255 // DS
|
||||
ds_permute_b32 v0, v255, v0 // DS
|
||||
buffer_load_dword v255, off, s[100:103], 0 offset:4095 // MUBUF
|
||||
buffer_load_dword v0, v255, s[0:3], s105 offen offset:1 // MUBUF
|
||||
buffer_load_dword v255, v0, s[0:3], 0 idxen // MUBUF
|
||||
buffer_load_dword v0, v[254:255], s[0:3], 0 idxen offen glc slc // MUBUF
|
||||
buffer_load_ubyte v255, off, s[0:3], 0 // MUBUF
|
||||
buffer_load_sshort v0, off, s[0:3], 0 // MUBUF
|
||||
buffer_load_dwordx2 v[254:255], off, s[0:3], 0 offset:4095 // MUBUF
|
||||
buffer_load_dwordx3 v[0:2], off, s[0:3], 0 // MUBUF
|
||||
buffer_store_dwordx4 v[252:255], off, s[100:103], 0 offset:4095 // MUBUF
|
||||
buffer_store_byte v0, v255, s[0:3], s105 offen // MUBUF
|
||||
buffer_atomic_add v255, off, s[0:3], 0 glc // MUBUF
|
||||
buffer_atomic_cmpswap v[254:255], off, s[0:3], 0 glc // MUBUF
|
||||
tbuffer_load_format_x v255, off, s[100:103], 0 format:[BUF_FMT_32_UINT] offset:4095 // MTBUF
|
||||
tbuffer_load_format_xy v[0:1], v255, s[0:3], s105 format:[BUF_FMT_32_32_FLOAT] offen // MTBUF
|
||||
tbuffer_load_format_xyz v[253:255], off, s[0:3], 0 format:[BUF_FMT_32_32_32_FLOAT] // MTBUF
|
||||
tbuffer_load_format_xyzw v[0:3], off, s[0:3], 0 format:[BUF_FMT_32_32_32_32_FLOAT] // MTBUF
|
||||
tbuffer_store_format_x v255, v0, s[100:103], 0 format:[BUF_FMT_32_SINT] idxen // MTBUF
|
||||
tbuffer_store_format_xy v[254:255], off, s[0:3], 0 format:[BUF_FMT_32_32_UINT] // MTBUF
|
||||
tbuffer_store_format_xyz v[0:2], off, s[0:3], 0 format:[BUF_FMT_32_32_32_UINT] // MTBUF
|
||||
tbuffer_store_format_xyzw v[252:255], off, s[0:3], 0 format:[BUF_FMT_32_32_32_32_UINT] offset:4095 // MTBUF
|
||||
tbuffer_load_format_d16_xy v255, off, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] // MTBUF
|
||||
tbuffer_store_format_d16_xyzw v[254:255], off, s[0:3], 0 format:[BUF_FMT_16_16_16_16_FLOAT] // MTBUF
|
||||
image_load v255, v0, s[96:103] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm // MIMG
|
||||
image_load_mip v[254:255], v[0:2], s[0:7] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm // MIMG
|
||||
image_store v255, v[0:1], s[0:7] dmask:0x8 dim:SQ_RSRC_IMG_2D unorm // MIMG
|
||||
image_sample v[252:255], [v255,v0], s[0:7], s[100:103] dmask:0xf dim:SQ_RSRC_IMG_2D // MIMG
|
||||
image_sample v255, [v0,v128,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
|
||||
image_sample_c v[254:255], [v255,v5,v1,v0], s[0:7], s[8:11] dmask:0x5 dim:SQ_RSRC_IMG_2D_ARRAY // MIMG
|
||||
image_sample_c_l v255, [v0,v2,v4,v6,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY // MIMG
|
||||
image_sample_d v255, [v0,v2,v4,v6,v8,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D // MIMG
|
||||
image_sample_d v0, [v255,v2,v4,v6,v8,v10,v12,v14,v16], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
|
||||
image_gather4 v[252:255], v[0:1], s[0:7], s[8:11] dmask:0x8 dim:SQ_RSRC_IMG_2D // MIMG
|
||||
image_atomic_add v255, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc // MIMG
|
||||
image_sample_d_cl v255, [v0,v2,v4,v6,v8,v10,v12,v14,v16,v18], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
|
||||
image_sample_c_d_cl v0, [v0,v2,v4,v6,v8,v10,v12,v14,v16,v18,v20], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
|
||||
exp mrt0 v255, off, off, v0 done // EXP
|
||||
exp mrt7 off, v255, v0, off // EXP
|
||||
exp pos0 v0, v255, v0, v255 done // EXP
|
||||
exp pos3 v255, v0, v255, v0 // EXP
|
||||
exp param0 v255, off, v0, off // EXP
|
||||
exp param31 v0, v255, off, off // EXP
|
||||
exp null off, off, off, off done // EXP
|
||||
flat_load_dword v255, v[0:1] offset:2047 // FLAT
|
||||
flat_load_dword v0, v[254:255] offset:1024 // FLAT
|
||||
flat_load_ubyte v255, v[0:1] offset:0 // FLAT
|
||||
flat_load_sbyte v0, v[254:255] glc // FLAT
|
||||
flat_load_dwordx2 v[254:255], v[0:1] slc // FLAT
|
||||
flat_load_dwordx4 v[0:3], v[254:255] // FLAT
|
||||
flat_store_dword v[254:255], v0 offset:2047 // FLAT
|
||||
flat_store_short v[0:1], v255 offset:1 // FLAT
|
||||
flat_atomic_add v255, v[0:1], v255 glc // FLAT
|
||||
flat_atomic_swap v[254:255], v0 // FLAT
|
||||
global_load_dword v255, v[0:1], off offset:-2048 // GLOBAL
|
||||
global_load_dword v0, v255, s[104:105] offset:2047 // GLOBAL
|
||||
global_load_ubyte v255, v0, s[0:1] // GLOBAL
|
||||
global_load_dwordx3 v[253:255], v[0:1], off glc // GLOBAL
|
||||
global_store_dword v255, v0, s[104:105] offset:-2048 // GLOBAL
|
||||
global_store_dwordx4 v[254:255], v[0:3], off offset:2047 // GLOBAL
|
||||
global_store_byte v0, v255, s[0:1] // GLOBAL
|
||||
global_atomic_or v255, v0, v255, s[104:105] glc // GLOBAL
|
||||
global_atomic_add v[254:255], v0, off // GLOBAL
|
||||
scratch_load_dword v255, v0, off offset:2047 // SCRATCH
|
||||
scratch_load_dword v0, off, s105 offset:-2048 // SCRATCH
|
||||
scratch_load_ushort v255, v0, off // SCRATCH
|
||||
scratch_load_dwordx2 v[254:255], off, s0 // SCRATCH
|
||||
scratch_load_dwordx4 v[0:3], v255, off // SCRATCH
|
||||
scratch_store_dword v255, v0, off offset:-2048 // SCRATCH
|
||||
scratch_store_dword off, v255, s0 offset:2047 // SCRATCH
|
||||
scratch_store_byte v0, v255, off // SCRATCH
|
||||
scratch_store_dwordx4 off, v[252:255], s105 // SCRATCH
|
||||
// Forms the byte probes could not reach with legal operands (FLAT SADDR, DS GDS, BVH).
|
||||
ds_gws_init v1 offset:65535 gds // DS
|
||||
ds_gws_barrier v1 offset:0 gds // DS
|
||||
ds_gws_sema_v gds // DS
|
||||
ds_gws_sema_br v1 gds // DS
|
||||
ds_gws_sema_p gds // DS
|
||||
ds_gws_sema_release_all gds // DS
|
||||
ds_ordered_count v0, v1 offset:65535 gds // DS
|
||||
flat_load_dwordx3 v[0:2], v[254:255] offset:2047 // FLAT
|
||||
flat_load_sshort v255, v[254:255] offset:2047 // FLAT
|
||||
flat_load_ushort v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_sbyte_d16 v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_sbyte_d16_hi v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_short_d16 v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_short_d16_hi v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_ubyte_d16 v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_ubyte_d16_hi v0, v[254:255] offset:2047 // FLAT
|
||||
flat_store_byte v[0:1], v2 // FLAT
|
||||
flat_store_byte_d16_hi v[0:1], v2 // FLAT
|
||||
flat_store_dwordx2 v[0:1], v[2:3] // FLAT
|
||||
flat_store_dwordx3 v[0:1], v[2:4] // FLAT
|
||||
flat_store_dwordx4 v[0:1], v[2:5] // FLAT
|
||||
flat_store_short_d16_hi v[0:1], v2 // FLAT
|
||||
flat_atomic_add v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_add_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_and v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_and_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_dec v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_dec_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_inc v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_inc_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_or v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_or_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_smax v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_smax_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_smin v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_smin_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_sub v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_sub_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_umax v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_umax_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_umin v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_umin_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_xor v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_xor_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_fmax v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_fmax_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_fmin v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_fmin_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_swap_x2 v[0:1], v[2:3] offset:2047 // FLAT
|
||||
flat_atomic_cmpswap v0, v[0:1], v[2:3] glc // FLAT
|
||||
flat_atomic_cmpswap_x2 v[0:1], v[2:5] // FLAT
|
||||
flat_atomic_fcmpswap v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_fcmpswap_x2 v[0:1], v[2:5] // FLAT
|
||||
image_bvh_intersect_ray v[0:3], v[0:10], s[0:3] // MIMG
|
||||
image_bvh64_intersect_ray v[0:3], v[0:11], s[0:3] // MIMG
|
||||
image_bvh_intersect_ray v[0:3], [v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14], s[0:3] // MIMG
|
||||
v_interp_p1ll_f16 v0, v1, attr0.x // VOP3
|
||||
v_interp_p1lv_f16 v0, v1, attr0.x, v2 // VOP3
|
||||
v_interp_p2_f16 v0, v1, attr0.x, v2 // VOP3
|
||||
v_mqsad_u32_u8 v[0:3], v[2:3], v4, v[4:7] // VOP3
|
||||
v_permlane16_b32 v0, v1, s2, s3 // VOP3
|
||||
v_permlanex16_b32 v255, v1, s105, m0 op_sel:[1,1] // VOP3
|
||||
v_swaprel_b32 v0, v1 // VOP1
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,132 @@
|
||||
# Rows of the asm, probe-zero and probe-ext sources where identify and LLVM do not simply agree
|
||||
# (neither `identified` nor `both_reject`), as `class hex`, sorted by hex. Pinned by meta_corpus.rs;
|
||||
# review each change against LLVM.
|
||||
operand_flagged 000000d60000000000000000000000000000000000000000
|
||||
operand_flagged 000000d6ff00000078563412000000000000000000000000
|
||||
metadata_only 000000dd0000000000000000000000000000000000000000
|
||||
operand_flagged 000001d60000000000000000000000000000000000000000
|
||||
operand_flagged 000001d6ff00000078563412000000000000000000000000
|
||||
metadata_only 000008f10000000000000000000000000000000000000000
|
||||
metadata_only 00000cf10000000000000000000000000000000000000000
|
||||
metadata_only 000020dc0000000000000000000000000000000000000000
|
||||
metadata_only 000024dc0000000000000000000000000000000000000000
|
||||
metadata_only 000028dc0000000000000000000000000000000000000000
|
||||
metadata_only 000028f10000000000000000000000000000000000000000
|
||||
metadata_only 00002cdc0000000000000000000000000000000000000000
|
||||
metadata_only 00002cf10000000000000000000000000000000000000000
|
||||
metadata_only 000030dc0000000000000000000000000000000000000000
|
||||
metadata_only 000034dc0000000000000000000000000000000000000000
|
||||
metadata_only 000038dc0000000000000000000000000000000000000000
|
||||
metadata_only 00003cdc0000000000000000000000000000000000000000
|
||||
metadata_only 000040dd0000000000000000000000000000000000000000
|
||||
operand_flagged 000042d70000000000000000000000000000000000000000
|
||||
operand_flagged 000042d7ff00000078563412000000000000000000000000
|
||||
operand_flagged 000043d70000000000000000000000000000000000000000
|
||||
operand_flagged 000043d7ff00000078563412000000000000000000000000
|
||||
metadata_only 000044dd0000000000000000000000000000000000000000
|
||||
metadata_only 000048dd0000000000000000000000000000000000000000
|
||||
metadata_only 000048f10000000000000000000000000000000000000000
|
||||
metadata_only 00004cdd0000000000000000000000000000000000000000
|
||||
metadata_only 00004cf10000000000000000000000000000000000000000
|
||||
metadata_only 000054dd0000000000000000000000000000000000000000
|
||||
metadata_only 000058dd0000000000000000000000000000000000000000
|
||||
operand_flagged 00005ad70000000000000000000000000000000000000000
|
||||
operand_flagged 00005ad7ff00000078563412000000000000000000000000
|
||||
metadata_only 00005cdd0000000000000000000000000000000000000000
|
||||
operand_flagged 000060d70000000000000000000000000000000000000000
|
||||
metadata_only 000060d80000000000000000000000000000000000000000
|
||||
metadata_only 000060dc0000000000000000000000000000000000000000
|
||||
metadata_only 000060dd0000000000000000000000000000000000000000
|
||||
metadata_only 000064d80000000000000000000000000000000000000000
|
||||
metadata_only 000064dc0000000000000000000000000000000000000000
|
||||
metadata_only 000064dd0000000000000000000000000000000000000000
|
||||
metadata_only 000068d80000000000000000000000000000000000000000
|
||||
metadata_only 000068dc0000000000000000000000000000000000000000
|
||||
metadata_only 000068dd0000000000000000000000000000000000000000
|
||||
metadata_only 000068f10000000000000000000000000000000000000000
|
||||
metadata_only 00006cd80000000000000000000000000000000000000000
|
||||
metadata_only 00006cdc0000000000000000000000000000000000000000
|
||||
metadata_only 00006cdd0000000000000000000000000000000000000000
|
||||
metadata_only 00006cf10000000000000000000000000000000000000000
|
||||
metadata_only 000070d80000000000000000000000000000000000000000
|
||||
metadata_only 000070dc0000000000000000000000000000000000000000
|
||||
metadata_only 000070dd0000000000000000000000000000000000000000
|
||||
metadata_only 000074d80000000000000000000000000000000000000000
|
||||
metadata_only 000074dc0000000000000000000000000000000000000000
|
||||
metadata_only 000074dd0000000000000000000000000000000000000000
|
||||
operand_flagged 000075d50000000000000000000000000000000000000000
|
||||
operand_flagged 000075d5ff00000078563412000000000000000000000000
|
||||
operand_flagged 000077d70000000000000000000000000000000000000000
|
||||
operand_flagged 000077d7ff00000078563412000000000000000000000000
|
||||
operand_flagged 000078d70000000000000000000000000000000000000000
|
||||
operand_flagged 000078d7ff00000078563412000000000000000000000000
|
||||
metadata_only 000078dc0000000000000000000000000000000000000000
|
||||
metadata_only 000078dd0000000000000000000000000000000000000000
|
||||
metadata_only 00007cdc0000000000000000000000000000000000000000
|
||||
metadata_only 00007cdd0000000000000000000000000000000000000000
|
||||
oracle_only 000080d5ff00000078563412000000000000000000000000
|
||||
metadata_only 000080dc0000000000000000000000000000000000000000
|
||||
metadata_only 000080dd0000000000000000000000000000000000000000
|
||||
metadata_only 000082d50000000000000000000000000000000000000000
|
||||
metadata_only 000084dc0000000000000000000000000000000000000000
|
||||
metadata_only 000088dc0000000000000000000000000000000000000000
|
||||
metadata_only 000088f10000000000000000000000000000000000000000
|
||||
metadata_only 00008cdc0000000000000000000000000000000000000000
|
||||
metadata_only 00008cf10000000000000000000000000000000000000000
|
||||
metadata_only 000090dc0000000000000000000000000000000000000000
|
||||
metadata_only 000094dc0000000000000000000000000000000000000000
|
||||
oracle_only 00009bd5ff00000078563412000000000000000000000000
|
||||
metadata_only 0000c0dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000c0f10000000000000000000000000000000000000000
|
||||
oracle_only 0000c1d5ff00000078563412000000000000000000000000
|
||||
operand_flagged 0000c3d50000000000000000000000000000000000000000
|
||||
operand_flagged 0000c4d50000000000000000000000000000000000000000
|
||||
metadata_only 0000c4dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000c4f10000000000000000000000000000000000000000
|
||||
operand_flagged 0000c8d50000000000000000000000000000000000000000
|
||||
metadata_only 0000c8dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000ccdc0000000000000000000000000000000000000000
|
||||
metadata_only 0000ccf10000000000000000000000000000000000000000
|
||||
metadata_only 0000d0f10000000000000000000000000000000000000000
|
||||
metadata_only 0000d4dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000d8dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000d8f10000000000000000000000000000000000000000
|
||||
metadata_only 0000dcdc0000000000000000000000000000000000000000
|
||||
metadata_only 0000dcf10000000000000000000000000000000000000000
|
||||
metadata_only 0000e0dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000e4dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000e4f10000000000000000000000000000000000000000
|
||||
metadata_only 0000e8dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000e8f10000000000000000000000000000000000000000
|
||||
metadata_only 0000ecdc0000000000000000000000000000000000000000
|
||||
metadata_only 0000f0dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000f4dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000f8dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000fcd80000000000000000000000000000000000000000
|
||||
metadata_only 0000fcdc0000000000000000000000000000000000000000
|
||||
operand_flagged 0004007e00000000000000000000000000000000
|
||||
operand_flagged 0086007e00000000000000000000000000000000
|
||||
operand_flagged 0088007e00000000000000000000000000000000
|
||||
operand_flagged 0090007e00000000000000000000000000000000
|
||||
operand_flagged 00ca007e00000000000000000000000000000000
|
||||
operand_flagged 00d0007e00000000000000000000000000000000
|
||||
metadata_only 010098f10000000000000000000000000000000000000000
|
||||
metadata_only 01009cf10000000000000000000000000000000000000000
|
||||
oracle_only e900007e0088c6fa000000000000000000000000
|
||||
oracle_only e936007e0088c6fa000000000000000000000000
|
||||
oracle_only e982007e0088c6fa000000000000000000000000
|
||||
oracle_only ea00007e0088c6fa000000000000000000000000
|
||||
oracle_only ea36007e0088c6fa000000000000000000000000
|
||||
oracle_only ea82007e0088c6fa000000000000000000000000
|
||||
oracle_only f900007e00060600000000000000000000000000
|
||||
oracle_only f936007e00060600000000000000000000000000
|
||||
oracle_only f982007e00060600000000000000000000000000
|
||||
oracle_only fa00007e00e400ff000000000000000000000000
|
||||
oracle_only fa36007e00e400ff000000000000000000000000
|
||||
oracle_only fa82007e00e400ff000000000000000000000000
|
||||
oracle_only ff00007e78563412000000000000000000000000
|
||||
oracle_only ff1f80be78563412000000000000000000000000
|
||||
oracle_only ff2180be78563412000000000000000000000000
|
||||
oracle_only ff36007e78563412000000000000000000000000
|
||||
oracle_only ff4980be78563412000000000000000000000000
|
||||
oracle_only ff82007e78563412000000000000000000000000
|
||||
@@ -0,0 +1,41 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// One instruction per line for each family and extension word; checked against llvm-mc.
|
||||
s_mov_b32 s0, 0x12345678
|
||||
s_add_u32 s0, s1, 0x1234
|
||||
s_cmp_eq_u32 s0, 0xdeadbeef
|
||||
s_movk_i32 s0, 0x1234
|
||||
s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0x0
|
||||
s_load_dwordx4 s[0:3], s[4:5], 0x10
|
||||
s_nop 0
|
||||
s_endpgm
|
||||
v_mov_b32 v0, 0x12345678
|
||||
v_mov_b32_sdwa v0, v1 dst_sel:BYTE_0 dst_unused:UNUSED_PAD src0_sel:DWORD
|
||||
v_mov_b32_dpp v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf
|
||||
v_mov_b32_dpp v0, v1 dpp8:[1,0,3,2,5,4,7,6]
|
||||
v_mov_b32_dpp v0, v1 dpp8:[1,0,3,2,5,4,7,6] fi:1
|
||||
v_add_f32_sdwa v0, v1, v2 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:DWORD
|
||||
v_add_f32_dpp v0, v1, v2 row_shl:1 row_mask:0xf bank_mask:0xf
|
||||
v_cmp_eq_u32_e32 vcc_lo, 0x1234, v1
|
||||
v_cmp_eq_u32_sdwa s0, v1, v2 src0_sel:DWORD src1_sel:DWORD
|
||||
v_fmamk_f32 v0, v1, 0x40000000, v2
|
||||
v_fmaak_f32 v0, v1, v2, 0x40000000
|
||||
v_fma_f32 v0, v1, v2, 0x3f800001
|
||||
v_add_co_u32 v0, s0, v1, v2
|
||||
v_readlane_b32 s0, v1, 0
|
||||
v_pk_add_f16 v0, v1, v2
|
||||
v_pk_fma_f16 v0, v1, v2, 0x3c01
|
||||
v_interp_p1_f32 v0, v1, attr0.x
|
||||
ds_write_b32 v0, v1
|
||||
ds_read_b32 v0, v1 offset:16
|
||||
buffer_load_dword v0, off, s[0:3], 0
|
||||
tbuffer_load_format_x v0, off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
|
||||
tbuffer_load_format_d16_x v0, off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
|
||||
tbuffer_store_format_d16_xyzw v[0:1], off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
|
||||
image_sample v[0:3], v[0:1], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
|
||||
image_sample v[0:3], [v0, v2], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
|
||||
image_sample_c v[0:3], [v0, v2, v4, v6], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY
|
||||
image_msaa_load v[0:3], v[0:2], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D_MSAA unorm
|
||||
flat_load_dword v0, v[0:1]
|
||||
global_load_dword v0, v[0:1], off
|
||||
scratch_load_dword v0, v1, off
|
||||
exp mrt0 v0, v0, v0, v0 done
|
||||
@@ -0,0 +1,230 @@
|
||||
//! Instruction identification against LLVM-assembled fixtures and hand-assembled words.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use xenora_isa::meta::{
|
||||
EncodingFamily, Extensions, FORMS, IdentifyError, VectorControl, identify, inventory, lookup,
|
||||
};
|
||||
|
||||
fn words(values: &[u32]) -> Vec<u8> {
|
||||
values
|
||||
.iter()
|
||||
.flat_map(|value| value.to_le_bytes())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn name_of(values: &[u32]) -> (&'static str, usize) {
|
||||
let found = identify(&words(values)).unwrap();
|
||||
(found.form.name, found.len)
|
||||
}
|
||||
|
||||
/// Mnemonics in a fixture's assembly source, without LLVM's encoding suffixes.
|
||||
fn source_mnemonics(source: &str) -> Vec<String> {
|
||||
source
|
||||
.lines()
|
||||
.map(|line| line.split("//").next().unwrap().trim())
|
||||
.filter(|line| !line.is_empty() && !line.starts_with('.') && !line.ends_with(':'))
|
||||
.map(|line| {
|
||||
let mnemonic = line.split_whitespace().next().unwrap().to_ascii_uppercase();
|
||||
mnemonic
|
||||
.trim_end_matches("_E32")
|
||||
.trim_end_matches("_E64")
|
||||
.to_owned()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llvm_fixtures_identify_with_exact_boundaries_and_mnemonics() {
|
||||
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
|
||||
let mut checked = 0;
|
||||
for entry in fs::read_dir(&directory).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_none_or(|extension| extension != "bin") {
|
||||
continue;
|
||||
}
|
||||
let binary = fs::read(&path).unwrap();
|
||||
let source = fs::read_to_string(path.with_extension("s")).unwrap();
|
||||
let mut offset = 0;
|
||||
let mut identified = Vec::new();
|
||||
while offset < binary.len() {
|
||||
let found = identify(&binary[offset..])
|
||||
.unwrap_or_else(|error| panic!("{} at {offset:#x}: {error}", path.display()));
|
||||
identified.push(found.form.name.to_owned());
|
||||
offset += found.len;
|
||||
}
|
||||
assert_eq!(offset, binary.len(), "{}", path.display());
|
||||
assert_eq!(identified, source_mnemonics(&source), "{}", path.display());
|
||||
checked += 1;
|
||||
}
|
||||
assert!(checked >= 11, "only {checked} fixtures found");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hand_assembled_words_identify() {
|
||||
// SOPP s_endpgm (opcode 1), SOP1 s_mov_b32 s0, s1 (opcode 3).
|
||||
assert_eq!(name_of(&[0xbf81_0000]), ("S_ENDPGM", 4));
|
||||
assert_eq!(name_of(&[0xbe80_0301]), ("S_MOV_B32", 4));
|
||||
// VOP1 v_mov_b32 v0, v1: SRC0 = 256 + 1.
|
||||
assert_eq!(name_of(&[0x7e00_0301]), ("V_MOV_B32", 4));
|
||||
// VOP2 v_add_f32 v0, v1, v2: opcode 3 at bits 30:25, VSRC1 = 2 at bits 16:9.
|
||||
assert_eq!(name_of(&[0x0600_0501]), ("V_ADD_F32", 4));
|
||||
// VOP3 v_add_f32_e64 v0, v1, v2 (LLVM 23 encoding): opcode 259 = 256 + VOP2 opcode 3.
|
||||
assert_eq!(name_of(&[0xd503_0000, 0x0202_0501]), ("V_ADD_F32", 8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_sdwa_and_dpp_words_extend_the_length() {
|
||||
// v_mov_b32 v0, 0x12345678: SRC0 = 255 selects a literal.
|
||||
let literal = identify(&words(&[0x7e00_02ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((literal.form.name, literal.len), ("V_MOV_B32", 8));
|
||||
assert!(literal.trailer.literal);
|
||||
// s_add_u32 s0, s1, literal: SSRC1 = 255.
|
||||
assert_eq!(name_of(&[0x8000_ff01, 0x0000_1234]), ("S_ADD_U32", 8));
|
||||
// VOP3 with SRC2 = 255.
|
||||
let fma = identify(&words(&[0xd54b_0000, 0x03fe_0501, 0x3f80_0000]));
|
||||
assert!(matches!(fma, Ok(found) if found.len == 12 && found.trailer.literal));
|
||||
let sdwa = identify(&words(&[0x7e00_02f9, 0x0006_0601])).unwrap();
|
||||
assert_eq!(sdwa.trailer.vector_control, Some(VectorControl::Sdwa));
|
||||
assert_eq!(sdwa.len, 8);
|
||||
let dpp16 = identify(&words(&[0x7e00_02fa, 0x00ff_0001])).unwrap();
|
||||
assert_eq!(dpp16.trailer.vector_control, Some(VectorControl::Dpp16));
|
||||
let dpp8 = identify(&words(&[0x7e00_02ea, 0x00fa_c688])).unwrap();
|
||||
assert_eq!(
|
||||
dpp8.trailer.vector_control,
|
||||
Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop3_interpolation_attribute_fields_never_select_a_literal() {
|
||||
// AMD RDNA 2 ISA guide section 10.4.2: in the VOP3 interpolation forms SRC0
|
||||
// holds {attr_word, attr_chan, attr} bit-fields (XML OPR_ATTR), so SRC0 = 255
|
||||
// is attr 63, channel w (and attr_word 0) and the instruction is 8 bytes.
|
||||
// LLVM 23.1.6 agrees (#235).
|
||||
for (first, name) in [
|
||||
(0xd600_0000, "V_INTERP_P1_F32"),
|
||||
(0xd601_0000, "V_INTERP_P2_F32"),
|
||||
(0xd602_0000, "V_INTERP_MOV_F32"),
|
||||
(0xd742_0000, "V_INTERP_P1LL_F16"),
|
||||
(0xd743_0000, "V_INTERP_P1LV_F16"),
|
||||
(0xd75a_0000, "V_INTERP_P2_F16"),
|
||||
] {
|
||||
let found = identify(&words(&[first, 0x0000_00ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((found.form.name, found.len), (name, 8));
|
||||
assert!(!found.trailer.literal, "{name}");
|
||||
}
|
||||
// A general VOP3 source with the same selector still takes the literal.
|
||||
let add = identify(&words(&[0xd503_0000, 0x0000_00ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((add.form.name, add.len), ("V_ADD_F32", 12));
|
||||
// So does a VGPR-only source (LLVM reports these 12 bytes with an invalid operand).
|
||||
let permlane = identify(&words(&[0xd777_0000, 0x0000_00ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((permlane.form.name, permlane.len), ("V_PERMLANE16_B32", 12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_unassigned_inputs_are_rejected() {
|
||||
assert_eq!(identify(&[]), Err(IdentifyError::Truncated { needed: 4 }));
|
||||
assert_eq!(
|
||||
identify(&[0x00, 0x00, 0x81]),
|
||||
Err(IdentifyError::Truncated { needed: 4 })
|
||||
);
|
||||
// VOP3 first dword alone.
|
||||
assert_eq!(
|
||||
identify(&words(&[0xd503_0000])),
|
||||
Err(IdentifyError::Truncated { needed: 8 })
|
||||
);
|
||||
// Literal selected but absent.
|
||||
assert_eq!(
|
||||
identify(&words(&[0x7e00_02ff])),
|
||||
Err(IdentifyError::Truncated { needed: 8 })
|
||||
);
|
||||
// SOPP opcodes are 7 bits; this table has no SOPP opcode 127.
|
||||
assert!(lookup(0xbf80_0000 | (127 << 16)).is_none());
|
||||
assert_eq!(
|
||||
identify(&words(&[0xbfff_0000])),
|
||||
Err(IdentifyError::Unassigned)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extensions_outside_a_forms_metadata_are_rejected() {
|
||||
let without_sdwa = FORMS
|
||||
.iter()
|
||||
.find(|form| {
|
||||
form.family == EncodingFamily::Vop1 && !form.extensions.contains(Extensions::SDWA)
|
||||
})
|
||||
.expect("a VOP1 form without SDWA");
|
||||
let word = (without_sdwa.bits as u32) | 0xf9;
|
||||
assert_eq!(
|
||||
identify(&words(&[word, 0])),
|
||||
Err(IdentifyError::InvalidExtension("sdwa"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_form_identifies_as_itself() {
|
||||
for form in &FORMS {
|
||||
assert_eq!(lookup(form.bits).map(|found| found.name), Some(form.name));
|
||||
assert_eq!(
|
||||
lookup(form.bits).unwrap().family,
|
||||
form.family,
|
||||
"{}",
|
||||
form.name
|
||||
);
|
||||
}
|
||||
let total: usize = inventory().iter().map(|(_, count)| count).sum();
|
||||
assert_eq!(total, FORMS.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documented_form_counts_match_the_generated_table() {
|
||||
let count = FORMS.len();
|
||||
let count = format!("{},{:03}", count / 1000, count % 1000);
|
||||
let families = EncodingFamily::ALL.len();
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
for (file, claim) in [
|
||||
(
|
||||
"docs/research/rdna2.md",
|
||||
format!("{count} forms in {families} encoding families"),
|
||||
),
|
||||
(
|
||||
"CHANGELOG.md",
|
||||
format!("{count} base forms across {families} encoding families"),
|
||||
),
|
||||
] {
|
||||
let text = fs::read_to_string(root.join(file)).unwrap();
|
||||
assert!(
|
||||
text.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.contains(&claim),
|
||||
"{file} must state \"{claim}\""
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_word_opcode_table_agrees_with_full_metadata() {
|
||||
use xenora_isa::{BUFFER_LOAD_DWORD, S_ENDPGM, V_ADD_F32, V_ADD_NC_U32, V_MOV_B32};
|
||||
for (opcode, name, family) in [
|
||||
(
|
||||
BUFFER_LOAD_DWORD,
|
||||
"BUFFER_LOAD_DWORD",
|
||||
EncodingFamily::Mubuf,
|
||||
),
|
||||
(S_ENDPGM, "S_ENDPGM", EncodingFamily::Sopp),
|
||||
(V_ADD_F32, "V_ADD_F32", EncodingFamily::Vop2),
|
||||
(V_ADD_NC_U32, "V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
(V_MOV_B32, "V_MOV_B32", EncodingFamily::Vop1),
|
||||
] {
|
||||
let form = FORMS
|
||||
.iter()
|
||||
.find(|form| form.name == name && form.family == family)
|
||||
.unwrap();
|
||||
assert!(opcode.matches(form.bits as u32), "{name}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//! Independent LLVM corpus check of gfx1030 instruction identification (#209).
|
||||
//!
|
||||
//! `llvm/corpus.tsv` is generated by `llvm/corpus.py` from LLVM 23.1.6 alone:
|
||||
//! llvm-mc assembles the original instructions in `llvm/corpus.s`, and
|
||||
//! llvm-objdump decodes byte probes built from each metadata form's
|
||||
//! identifying bits (one with every other bit zero, two with seeded random
|
||||
//! operand bits). The expected name, consumed length and extension of every
|
||||
//! row are LLVM's. This test compares `identify` with them and pins what it
|
||||
//! measures: per-source class counts, the exact rows where the two disagree
|
||||
//! for assembled and zero-operand inputs, and a digest of the random-probe
|
||||
//! classification.
|
||||
//!
|
||||
//! Identification is not execution support: a row counted as identified only
|
||||
//! means both agree on which instruction the bytes are and how long it is.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use xenora_isa::meta::{FORMS, Identified, IdentifyError, VectorControl, identify};
|
||||
|
||||
const CORPUS: &str = include_str!("llvm/corpus.tsv");
|
||||
|
||||
/// Row classes, in report order.
|
||||
const CLASSES: [&str; 9] = [
|
||||
"identified", // both decode: same name, length and extension
|
||||
"mismatch", // both decode, but name, length or extension differ
|
||||
"oracle_only", // LLVM decodes, identify returns an error
|
||||
"metadata_only", // identify decodes, LLVM cannot
|
||||
"both_reject", // neither decodes
|
||||
"oracle_crash", // llvm-objdump crashed; no oracle answer
|
||||
"truncated", // a proper prefix: identify asks for more bytes
|
||||
"truncation_other",
|
||||
"operand_flagged", // same instruction and length; LLVM flags an operand as invalid
|
||||
];
|
||||
const SOURCES: [&str; 5] = [
|
||||
"asm",
|
||||
"probe-zero",
|
||||
"probe-ext",
|
||||
"probe-random",
|
||||
"truncation",
|
||||
];
|
||||
|
||||
fn base_name(mnemonic: &str) -> String {
|
||||
let upper = mnemonic.to_ascii_uppercase();
|
||||
["_E32", "_E64", "_SDWA", "_DPP"]
|
||||
.into_iter()
|
||||
.find_map(|suffix| upper.strip_suffix(suffix))
|
||||
.unwrap_or(&upper)
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
fn extension(found: &Identified) -> String {
|
||||
let nsa = format!("nsa{}", found.trailer.nsa_dwords);
|
||||
let mut parts = Vec::new();
|
||||
if found.trailer.literal {
|
||||
parts.push("literal");
|
||||
}
|
||||
match found.trailer.vector_control {
|
||||
Some(VectorControl::Sdwa) => parts.push("sdwa"),
|
||||
Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: false,
|
||||
}) => parts.push("dpp8"),
|
||||
Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true,
|
||||
}) => parts.push("dpp8fi"),
|
||||
Some(VectorControl::Dpp16) => parts.push("dpp16"),
|
||||
None => {}
|
||||
}
|
||||
if found.trailer.nsa_dwords != 0 {
|
||||
parts.push(&nsa);
|
||||
}
|
||||
if parts.is_empty() {
|
||||
"-".into()
|
||||
} else {
|
||||
parts.join("+")
|
||||
}
|
||||
}
|
||||
|
||||
struct Row<'a> {
|
||||
source: usize,
|
||||
form: Option<&'static str>,
|
||||
family: &'a str,
|
||||
hex: &'a str,
|
||||
class: usize,
|
||||
detail: String,
|
||||
}
|
||||
|
||||
fn classify(line: &str) -> Row<'_> {
|
||||
let [source, hex, mnemonic, len, ext, note] = line.split('\t').collect::<Vec<_>>()[..] else {
|
||||
panic!("bad corpus row: {line}");
|
||||
};
|
||||
let source = SOURCES
|
||||
.iter()
|
||||
.position(|s| *s == source)
|
||||
.unwrap_or_else(|| panic!("bad source: {line}"));
|
||||
let (family, text) = note.split_once(' ').unwrap();
|
||||
let bytes: Vec<u8> = (0..hex.len())
|
||||
.step_by(2)
|
||||
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
|
||||
.collect();
|
||||
let len: usize = len.parse().unwrap();
|
||||
let found = identify(&bytes);
|
||||
let answer = match &found {
|
||||
Ok(found) => format!(
|
||||
"{} ({} bytes, {})",
|
||||
found.form.name,
|
||||
found.len,
|
||||
extension(found)
|
||||
),
|
||||
Err(error) => format!("{error:?}"),
|
||||
};
|
||||
let mut differences = Vec::new();
|
||||
// LLVM decoded the words but flagged an operand the instruction cannot
|
||||
// take. identify does not validate operands; it must still agree on the
|
||||
// instruction and its length, or reject the extension outright.
|
||||
let (flagged, mnemonic) = match mnemonic.strip_prefix("invalid-operand:") {
|
||||
Some(mnemonic) => (true, mnemonic),
|
||||
None => (false, mnemonic),
|
||||
};
|
||||
let class = match (mnemonic, &found) {
|
||||
("truncated", Err(IdentifyError::Truncated { needed })) if *needed > bytes.len() => 6,
|
||||
("truncated", _) => 7,
|
||||
("crashed", _) => 5,
|
||||
("invalid", Err(_)) => 4,
|
||||
("invalid", Ok(_)) => 3,
|
||||
(_, Err(IdentifyError::InvalidExtension(_))) if flagged => 4,
|
||||
(_, Err(_)) => 2,
|
||||
(_, Ok(found)) => {
|
||||
if found.form.name != base_name(mnemonic) {
|
||||
differences.push("name");
|
||||
}
|
||||
if found.len != len {
|
||||
differences.push("length");
|
||||
}
|
||||
if extension(found) != ext {
|
||||
differences.push("extension");
|
||||
}
|
||||
if !differences.is_empty() {
|
||||
1
|
||||
} else if flagged {
|
||||
8
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
};
|
||||
let kind = if differences.is_empty() {
|
||||
CLASSES[class].to_owned()
|
||||
} else {
|
||||
format!("mismatch/{}", differences.join("+"))
|
||||
};
|
||||
Row {
|
||||
source,
|
||||
form: found.ok().map(|found| found.form.name),
|
||||
family,
|
||||
hex,
|
||||
class,
|
||||
detail: format!("{kind}: {hex} | LLVM {text} ({len} bytes, {ext}) | Xenora {answer}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// FNV-1a over the sorted `class hex` lines, to pin thousands of rows compactly.
|
||||
fn digest(lines: &[String]) -> u64 {
|
||||
lines
|
||||
.iter()
|
||||
.flat_map(|l| l.bytes().chain(*b"\n"))
|
||||
.fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
|
||||
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
|
||||
})
|
||||
}
|
||||
|
||||
// Measured against LLVM 23.1.6 on 2026-11-24. Any change needs the affected
|
||||
// rows reviewed against LLVM, not an update of these numbers alone.
|
||||
// Rows: one per source, columns in CLASSES order.
|
||||
const COUNTS: [[usize; 9]; 5] = [
|
||||
[317, 0, 0, 0, 0, 0, 0, 0, 0], // asm
|
||||
[1365, 0, 0, 82, 0, 0, 0, 0, 18], // probe-zero
|
||||
[1398, 0, 21, 0, 752, 0, 0, 0, 8], // probe-ext
|
||||
[1236, 0, 0, 1678, 3, 2, 0, 0, 11], // probe-random
|
||||
[0, 0, 0, 0, 0, 0, 87, 0, 0], // truncation
|
||||
];
|
||||
/// Every assembled, zero-operand or extension-probe row where the two disagree
|
||||
/// (neither `identified` nor `both_reject`), as `class hex`, sorted by hex.
|
||||
const DISAGREEMENTS: &str = include_str!("llvm/corpus_disagreements.txt");
|
||||
/// Digest of the sorted `class hex` lines of the random probes.
|
||||
const RANDOM_DIGEST: u64 = 0x32fb_5d7d_0826_ce14;
|
||||
|
||||
#[test]
|
||||
fn identification_agrees_with_the_llvm_corpus() {
|
||||
let mut lines = CORPUS.lines();
|
||||
assert_eq!(
|
||||
lines.next(),
|
||||
Some("source\thex\tllvm_mnemonic\tllvm_len\tllvm_ext\tnote")
|
||||
);
|
||||
let rows: Vec<_> = lines.map(classify).collect();
|
||||
let mut counts = [[0usize; 9]; 5];
|
||||
let mut by_family = BTreeMap::<&str, [usize; 9]>::new();
|
||||
for row in &rows {
|
||||
counts[row.source][row.class] += 1;
|
||||
by_family.entry(row.family).or_default()[row.class] += 1;
|
||||
}
|
||||
println!("{:9} {}", "family", CLASSES.join(" "));
|
||||
for (family, c) in &by_family {
|
||||
print!("{family:9}");
|
||||
for (name, n) in CLASSES.iter().zip(c) {
|
||||
print!(" {n:>w$}", w = name.len());
|
||||
}
|
||||
println!();
|
||||
}
|
||||
for (source, c) in SOURCES.iter().zip(&counts) {
|
||||
println!("{source:13} {c:?}");
|
||||
}
|
||||
let mut disagreements: Vec<_> = rows
|
||||
.iter()
|
||||
.filter(|r| r.source < 3 && !matches!(r.class, 0 | 4))
|
||||
.collect();
|
||||
disagreements.sort_unstable_by_key(|r| r.hex);
|
||||
for r in &disagreements {
|
||||
println!("{}", r.detail);
|
||||
}
|
||||
let disagreements: Vec<_> = disagreements
|
||||
.iter()
|
||||
.map(|r| format!("{} {}", CLASSES[r.class], r.hex))
|
||||
.collect();
|
||||
let mut random: Vec<_> = rows
|
||||
.iter()
|
||||
.filter(|r| r.source == 3)
|
||||
.map(|r| format!("{} {}", CLASSES[r.class], r.hex))
|
||||
.collect();
|
||||
random.sort_unstable();
|
||||
let random_digest = digest(&random);
|
||||
println!("random digest {random_digest:#018x}");
|
||||
for r in rows
|
||||
.iter()
|
||||
.filter(|r| r.source == 3 && r.class == 1)
|
||||
.take(5)
|
||||
{
|
||||
println!("random example {}", r.detail);
|
||||
}
|
||||
|
||||
// Distinct metadata forms: agreed by LLVM on at least one row, or only
|
||||
// ever decoded by Xenora (LLVM rejected every probe of that form).
|
||||
let mut forms = BTreeMap::<&str, (usize, usize)>::new();
|
||||
for row in &rows {
|
||||
if let Some(form) = row.form {
|
||||
let entry = forms.entry(form).or_default();
|
||||
match row.class {
|
||||
0 | 8 => entry.0 += 1,
|
||||
3 => entry.1 += 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let agreed = forms.values().filter(|(a, _)| *a > 0).count();
|
||||
let never: Vec<_> = forms
|
||||
.iter()
|
||||
.filter(|(_, (a, m))| *a == 0 && *m > 0)
|
||||
.map(|(name, _)| *name)
|
||||
.collect();
|
||||
println!(
|
||||
"distinct forms seen {}: agreed {agreed}, metadata-only on every row {}",
|
||||
forms.len(),
|
||||
never.len()
|
||||
);
|
||||
println!("never decoded by LLVM: {}", never.join(" "));
|
||||
let mut all_names: Vec<_> = FORMS.iter().map(|form| form.name).collect();
|
||||
all_names.sort_unstable();
|
||||
all_names.dedup();
|
||||
let unseen: Vec<_> = all_names
|
||||
.iter()
|
||||
.filter(|name| !forms.contains_key(*name))
|
||||
.collect();
|
||||
println!(
|
||||
"metadata: {} forms, {} distinct names, {} names with no corpus row: {unseen:?}",
|
||||
FORMS.len(),
|
||||
all_names.len(),
|
||||
unseen.len()
|
||||
);
|
||||
assert_eq!(counts, COUNTS, "class counts per source changed");
|
||||
let pinned: Vec<_> = DISAGREEMENTS
|
||||
.lines()
|
||||
.filter(|line| !line.starts_with('#'))
|
||||
.collect();
|
||||
assert_eq!(disagreements, pinned, "disagreeing rows changed");
|
||||
assert_eq!(
|
||||
random_digest, RANDOM_DIGEST,
|
||||
"random-probe classification changed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires LLVM with the gfx1030 AMDGPU target (set LLVM_BIN)"]
|
||||
fn llvm_corpus_is_fresh() {
|
||||
let bin = std::env::var("LLVM_BIN").expect("LLVM_BIN");
|
||||
let status = std::process::Command::new("python3")
|
||||
.arg(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/llvm/corpus.py"))
|
||||
.args(["--llvm-bin", &bin, "--check"])
|
||||
.status()
|
||||
.expect("run corpus.py");
|
||||
assert!(
|
||||
status.success(),
|
||||
"corpus.tsv differs from LLVM's current output"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! LLVM oracle for instruction identification: names and lengths from llvm-mc encodings.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
use xenora_isa::meta::identify;
|
||||
|
||||
const SOURCE: &str = include_str!("llvm/identify.s");
|
||||
|
||||
fn encodings() -> Vec<(String, Vec<u8>)> {
|
||||
let executable = std::env::var_os("LLVM_BIN").map_or_else(
|
||||
|| "llvm-mc".into(),
|
||||
|directory| std::path::PathBuf::from(directory).join("llvm-mc"),
|
||||
);
|
||||
let path = std::env::temp_dir().join(format!("xenora-identify-{}.s", std::process::id()));
|
||||
std::fs::write(&path, SOURCE).unwrap();
|
||||
let output = Command::new(executable)
|
||||
.args([
|
||||
"-triple=amdgcn-amd-amdhsa",
|
||||
"-mcpu=gfx1030",
|
||||
"-mattr=+wavefrontsize32",
|
||||
"-show-encoding",
|
||||
])
|
||||
.arg(&path)
|
||||
.output()
|
||||
.expect("launch llvm-mc (provide its directory in LLVM_BIN or put it on PATH)");
|
||||
std::fs::remove_file(&path).ok();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8(output.stdout)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let (text, encoding) = line.split_once("; encoding: [")?;
|
||||
let mnemonic = text.split_whitespace().next()?.to_ascii_uppercase();
|
||||
let bytes = encoding
|
||||
.trim_end_matches(']')
|
||||
.split(',')
|
||||
.map(|byte| u8::from_str_radix(byte.trim().trim_start_matches("0x"), 16).unwrap())
|
||||
.collect();
|
||||
Some((mnemonic, bytes))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn base_name(mnemonic: &str) -> &str {
|
||||
["_E32", "_E64", "_SDWA", "_DPP"]
|
||||
.iter()
|
||||
.fold(mnemonic, |name, suffix| name.trim_end_matches(suffix))
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
|
||||
fn identification_matches_llvm_names_and_lengths() {
|
||||
let encodings = encodings();
|
||||
let expected_lines = SOURCE
|
||||
.lines()
|
||||
.filter(|line| !line.is_empty() && !line.starts_with("//"))
|
||||
.count();
|
||||
assert_eq!(encodings.len(), expected_lines);
|
||||
// The VOP3 and VOP3P literal probes must really carry a literal trailer:
|
||||
// 1.0 in either width would be an inline constant and only eight bytes.
|
||||
for (probe, literal) in [("V_FMA_F32", 0x3f80_0001_u32), ("V_PK_FMA_F16", 0x3c01)] {
|
||||
let (_, bytes) = encodings
|
||||
.iter()
|
||||
.find(|(mnemonic, _)| mnemonic == probe)
|
||||
.unwrap_or_else(|| panic!("{probe} probe missing"));
|
||||
assert_eq!(bytes.len(), 12, "{probe}");
|
||||
assert_eq!(bytes[8..], literal.to_le_bytes(), "{probe}");
|
||||
}
|
||||
let mut stream = Vec::new();
|
||||
for (mnemonic, bytes) in &encodings {
|
||||
let found = identify(bytes).unwrap_or_else(|error| panic!("{mnemonic}: {error}"));
|
||||
assert_eq!(found.form.name, base_name(mnemonic), "{mnemonic}");
|
||||
assert_eq!(found.len, bytes.len(), "{mnemonic}");
|
||||
stream.extend_from_slice(bytes);
|
||||
}
|
||||
let mut offset = 0;
|
||||
for (mnemonic, bytes) in &encodings {
|
||||
let found = identify(&stream[offset..]).unwrap();
|
||||
assert_eq!(found.len, bytes.len(), "{mnemonic} in stream");
|
||||
offset += found.len;
|
||||
}
|
||||
assert_eq!(offset, stream.len());
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Ties the generated semantic registry tables to the independent XML metadata table.
|
||||
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect};
|
||||
use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
|
||||
|
||||
#[test]
|
||||
fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
assert_eq!(GENERATED_SCHEMA, SCHEMA);
|
||||
assert_eq!(FORM_IDS.len(), FORMS.len());
|
||||
for (row, (name, family)) in FORMS.iter().zip(FORM_IDS) {
|
||||
assert_eq!((row.name, row.family), (name, family));
|
||||
let meta = META_FORMS
|
||||
.iter()
|
||||
.find(|form| form.name == row.name && form.family == row.family)
|
||||
.unwrap_or_else(|| panic!("{} is not an identified form", row.name));
|
||||
assert_eq!(meta.opcode, row.opcode, "{}", row.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every word of `family` that the XML metadata identifies selects an operation
|
||||
/// exactly when the registry declares that form, and no 32-bit word of another
|
||||
/// family selects one.
|
||||
fn dispatch_selects_exactly(family: EncodingFamily, select: impl Fn(u32) -> Option<&'static str>) {
|
||||
let declared: Vec<_> = FORMS.iter().filter(|row| row.family == family).collect();
|
||||
let mut selected = 0;
|
||||
for meta in META_FORMS.iter().filter(|form| form.family == family) {
|
||||
match select(meta.bits as u32) {
|
||||
Some(name) => {
|
||||
assert_eq!(name, meta.name);
|
||||
selected += 1;
|
||||
}
|
||||
None => assert!(
|
||||
declared.iter().all(|row| row.name != meta.name),
|
||||
"{} is declared but not dispatched",
|
||||
meta.name
|
||||
),
|
||||
}
|
||||
}
|
||||
assert_eq!(selected, declared.len());
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family != family && form.bytes == 4)
|
||||
{
|
||||
assert_eq!(select(meta.bits as u32), None, "{}", meta.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
|
||||
for op in ScalarAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sop2);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sop2, |word| {
|
||||
ScalarAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
|
||||
for op in ScalarCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopc);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sopc, |word| {
|
||||
ScalarCompareOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
|
||||
for op in ScalarUnaryOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sop1);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
// s_mov_b32 (opcode 3) stays hand-written, so it must not be dispatched here.
|
||||
dispatch_selects_exactly(EncodingFamily::Sop1, |word| {
|
||||
ScalarUnaryOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() {
|
||||
for op in VectorAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Vop2);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.assembly_name(), format!("{}_e32", op.mnemonic()));
|
||||
assert_eq!(op.swaps_sources(), row.swap_sources);
|
||||
assert_eq!(row.scc, SccEffect::Unchanged);
|
||||
}
|
||||
// The hand-written VOP2 forms (v_and_b32, v_add_f32, ...) must not be
|
||||
// dispatched here.
|
||||
dispatch_selects_exactly(EncodingFamily::Vop2, |word| {
|
||||
VectorAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
@@ -9,8 +9,13 @@ rust-version.workspace = true
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# Runs the tests that need a native Metal device (scripts/test-gpu.sh); CI's virtual GPU lacks Apple family 7.
|
||||
gpu-tests = []
|
||||
|
||||
[dependencies]
|
||||
libc = "0.2"
|
||||
sha2 = "0.10"
|
||||
|
||||
[dev-dependencies]
|
||||
xenora-metal = { path = "../metal" }
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::time::Instant;
|
||||
use xenora_loader::cpu::{CpuState, Interpreter, Register};
|
||||
use std::hint::black_box;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::MemoryPermissions;
|
||||
use xenora_loader::pe::{
|
||||
@@ -76,61 +77,91 @@ fn build_pe(code: &[u8]) -> Vec<u8> {
|
||||
pe
|
||||
}
|
||||
|
||||
const ADDS: usize = 10_000;
|
||||
const INSTRUCTIONS: usize = ADDS + 2;
|
||||
const BUDGET: usize = 20_000;
|
||||
const STACK_TOP: u64 = 0x2000_8000;
|
||||
|
||||
fn check(result: ExecutionResult) {
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(result.instructions_executed, INSTRUCTIONS);
|
||||
assert_eq!(result.final_state.get(Register::Rax), ADDS as u64);
|
||||
}
|
||||
|
||||
fn report(label: &str, samples: &mut [Duration]) {
|
||||
samples.sort_unstable();
|
||||
let median = samples[samples.len() / 2];
|
||||
let min = samples[0];
|
||||
let max = samples[samples.len() - 1];
|
||||
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
|
||||
println!(
|
||||
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, median {mips:.2} MIPS",
|
||||
samples.len()
|
||||
);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut code = Vec::new();
|
||||
code.extend_from_slice(&[0x48, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0]); // mov rax, 0
|
||||
for _ in 0..10_000 {
|
||||
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
|
||||
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
|
||||
assert!(sample_count > 0);
|
||||
|
||||
let mut code = vec![0x48, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0]; // mov rax, 0
|
||||
for _ in 0..ADDS {
|
||||
code.extend_from_slice(&[0x48, 0x83, 0xC0, 0x01]); // add rax, 1
|
||||
}
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
// Benchmark Interpreter
|
||||
{
|
||||
let pe_bytes = build_pe(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).unwrap();
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).unwrap();
|
||||
loaded
|
||||
.memory
|
||||
.map_region(0x2000_0000, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let cpu = CpuState::new(loaded.entry_point, 0x2000_8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 20_000);
|
||||
let pe_bytes = build_pe(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).unwrap();
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).unwrap();
|
||||
loaded
|
||||
.memory
|
||||
.map_region(0x2000_0000, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let initial_cpu = CpuState::new(loaded.entry_point, STACK_TOP);
|
||||
let mut interpreter = Vec::with_capacity(sample_count);
|
||||
let mut cold = Vec::with_capacity(sample_count);
|
||||
let mut warm = Vec::with_capacity(sample_count);
|
||||
let mut cold_metrics = None;
|
||||
|
||||
let t0 = Instant::now();
|
||||
let res = interp.run();
|
||||
let el = t0.elapsed();
|
||||
println!(
|
||||
"BENCHMARK Interpreter: {:?} instructions in {:?} ({:.2} MIPS), final RAX={}",
|
||||
res.instructions_executed,
|
||||
el,
|
||||
(res.instructions_executed as f64 / el.as_secs_f64()) / 1_000_000.0,
|
||||
res.final_state.get(Register::Rax)
|
||||
);
|
||||
}
|
||||
for _ in 0..sample_count {
|
||||
let mut interp = Interpreter::new(initial_cpu.clone(), &mut loaded.memory, BUDGET);
|
||||
let start = Instant::now();
|
||||
let result = black_box(interp.run());
|
||||
interpreter.push(start.elapsed());
|
||||
check(result);
|
||||
|
||||
// Benchmark DBT
|
||||
{
|
||||
let pe_bytes = build_pe(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).unwrap();
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).unwrap();
|
||||
loaded
|
||||
.memory
|
||||
.map_region(0x2000_0000, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(loaded.entry_point, 0x2000_8000);
|
||||
let mut dbt = DbtEngine::new(4 * 1024 * 1024).unwrap();
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let start = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
|
||||
cold.push(start.elapsed());
|
||||
check(result);
|
||||
assert!(dbt.metrics.blocks_compiled > 0);
|
||||
assert_eq!(dbt.metrics.cache_hits, 0);
|
||||
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
|
||||
cold_metrics = Some(dbt.metrics);
|
||||
|
||||
let t0 = Instant::now();
|
||||
let res = dbt.run(&mut cpu, &mut loaded.memory, 20_000);
|
||||
let el = t0.elapsed();
|
||||
println!(
|
||||
"BENCHMARK DBT: {:?} instructions in {:?} ({:.2} MIPS), final RAX={}, blocks={}, bytes={}",
|
||||
res.instructions_executed,
|
||||
el,
|
||||
(res.instructions_executed as f64 / el.as_secs_f64()) / 1_000_000.0,
|
||||
res.final_state.get(Register::Rax),
|
||||
dbt.metrics.blocks_compiled,
|
||||
dbt.metrics.native_bytes_emitted
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let start = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
|
||||
warm.push(start.elapsed());
|
||||
check(result);
|
||||
assert_eq!(
|
||||
Some(dbt.metrics.blocks_compiled),
|
||||
cold_metrics.map(|m| m.blocks_compiled)
|
||||
);
|
||||
assert_eq!(dbt.metrics.cache_hits, dbt.metrics.blocks_compiled);
|
||||
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
|
||||
}
|
||||
|
||||
println!("{INSTRUCTIONS} guest instructions per sample, final RAX={ADDS}");
|
||||
report("Interpreter", &mut interpreter);
|
||||
report("Cold DBT", &mut cold);
|
||||
report("Warm DBT", &mut warm);
|
||||
let metrics = cold_metrics.unwrap();
|
||||
println!(
|
||||
"Cold DBT compiled {} blocks and emitted {} native bytes in {} dispatches",
|
||||
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
|
||||
);
|
||||
}
|
||||
+205
-2
@@ -72,6 +72,10 @@ impl Arm64Assembler {
|
||||
&self.code
|
||||
}
|
||||
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.code.clear();
|
||||
}
|
||||
|
||||
pub fn current_offset(&self) -> usize {
|
||||
self.code.len()
|
||||
}
|
||||
@@ -118,6 +122,31 @@ impl Arm64Assembler {
|
||||
self.code[index] = 0x5400_0000 | imm19 | (cond as u32 & 0xf);
|
||||
}
|
||||
|
||||
/// Patch a previously emitted unconditional `B` at `index`.
|
||||
pub fn patch_b(&mut self, index: usize, offset_insns: i32) {
|
||||
let imm26 = (offset_insns as u32) & 0x03ff_ffff;
|
||||
self.code[index] = 0x1400_0000 | imm26;
|
||||
}
|
||||
|
||||
/// CBZ Xt, imm19 (compare and branch on zero, 64-bit).
|
||||
pub fn cbz_64(&mut self, xt: u8, offset_insns: i32) {
|
||||
let imm19 = ((offset_insns as u32) & 0x0007_ffff) << 5;
|
||||
self.emit(0xb4000000 | imm19 | (xt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// CBNZ Xt, imm19 (compare and branch on nonzero, 64-bit).
|
||||
pub fn cbnz_64(&mut self, xt: u8, offset_insns: i32) {
|
||||
let imm19 = ((offset_insns as u32) & 0x0007_ffff) << 5;
|
||||
self.emit(0xb5000000 | imm19 | (xt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// Patch a previously emitted `CBZ`/`CBNZ` at `index`.
|
||||
pub fn patch_cbz_64(&mut self, index: usize, xt: u8, offset_insns: i32) {
|
||||
let imm19 = ((offset_insns as u32) & 0x0007_ffff) << 5;
|
||||
let template = self.code[index] & 0xff00_0000;
|
||||
self.code[index] = template | imm19 | (xt as u32 & 0x1f);
|
||||
}
|
||||
|
||||
/// ADD (extended/shifted register, 64-bit): ADD Xd, Xn, Xm
|
||||
pub fn add_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
@@ -128,6 +157,53 @@ impl Arm64Assembler {
|
||||
);
|
||||
}
|
||||
|
||||
/// ADD (shifted register, 64-bit): ADD Xd, Xn, Xm, LSL #shift
|
||||
pub fn add_reg_shifted_64(&mut self, xd: u8, xn: u8, xm: u8, shift: u8) {
|
||||
self.emit(
|
||||
0x8b000000
|
||||
| ((shift as u32 & 0x3f) << 10)
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// UXTB (32-bit/zero-extended): UXTB Wd, Wn (UBFM Wd, Wn, #0, #7)
|
||||
pub fn uxtb_32(&mut self, wd: u8, wn: u8) {
|
||||
self.emit(0x53001c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// UXTH (32-bit/zero-extended): UXTH Wd, Wn (UBFM Wd, Wn, #0, #15)
|
||||
pub fn uxth_32(&mut self, wd: u8, wn: u8) {
|
||||
self.emit(0x53003c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// SXTB (64-bit/sign-extended): SXTB Xd, Wn (SBFM Xd, Xn, #0, #7)
|
||||
pub fn sxtb_64(&mut self, xd: u8, wn: u8) {
|
||||
self.emit(0x93401c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// SXTB (32-bit/sign-extended): SXTB Wd, Wn (SBFM Wd, Wn, #0, #7)
|
||||
///
|
||||
/// Writing the 32-bit destination form clears bits 63:32 of the
|
||||
/// destination register, which is what a 32-bit x86 destination requires.
|
||||
pub fn sxtb_32(&mut self, wd: u8, wn: u8) {
|
||||
self.emit(0x13001c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// SXTH (64-bit/sign-extended): SXTH Xd, Wn (SBFM Xd, Xn, #0, #15)
|
||||
pub fn sxth_64(&mut self, xd: u8, wn: u8) {
|
||||
self.emit(0x93403c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// SXTH (32-bit/sign-extended): SXTH Wd, Wn (SBFM Wd, Wn, #0, #15)
|
||||
///
|
||||
/// Writing the 32-bit destination form clears bits 63:32 of the
|
||||
/// destination register, which is what a 32-bit x86 destination requires.
|
||||
pub fn sxth_32(&mut self, wd: u8, wn: u8) {
|
||||
self.emit(0x13003c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// ADD (extended/shifted register, 32-bit): ADD Wd, Wn, Wm
|
||||
pub fn add_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
@@ -248,6 +324,26 @@ impl Arm64Assembler {
|
||||
);
|
||||
}
|
||||
|
||||
/// ANDS (register, 32-bit, flags updating / TST): ANDS Wd, Wn, Wm
|
||||
pub fn ands_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x6a000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// TST (register, 64-bit): ANDS XZR, Xn, Xm
|
||||
pub fn tst_reg_64(&mut self, xn: u8, xm: u8) {
|
||||
self.ands_reg_64(XZR, xn, xm);
|
||||
}
|
||||
|
||||
/// TST (register, 32-bit): ANDS WZR, Wn, Wm
|
||||
pub fn tst_reg_32(&mut self, wn: u8, wm: u8) {
|
||||
self.ands_reg_32(XZR, wn, wm);
|
||||
}
|
||||
|
||||
/// ORR (register, 64-bit): ORR Xd, Xn, Xm
|
||||
pub fn orr_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
@@ -355,10 +451,18 @@ impl Arm64Assembler {
|
||||
|
||||
/// STP (64-bit pre-index): STP Xt1, Xt2, [Xn, #imm7]!
|
||||
pub fn stp_pre_64(&mut self, xt1: u8, xt2: u8, xn: u8, offset_bytes: i32) {
|
||||
debug_assert_eq!(
|
||||
offset_bytes % 8,
|
||||
0,
|
||||
"STP pre-index offset must be 8-byte aligned"
|
||||
);
|
||||
debug_assert!(
|
||||
(-512..=504).contains(&offset_bytes),
|
||||
"STP pre-index offset out of imm7 range"
|
||||
);
|
||||
let imm7 = ((offset_bytes / 8) as u32) & 0x7f;
|
||||
self.emit(
|
||||
0xa9a00000
|
||||
| 0x001e0000
|
||||
0xa9800000
|
||||
| (imm7 << 15)
|
||||
| ((xt2 as u32 & 0x1f) << 10)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
@@ -368,6 +472,15 @@ impl Arm64Assembler {
|
||||
|
||||
/// LDP (64-bit post-index): LDP Xt1, Xt2, [Xn], #imm7
|
||||
pub fn ldp_post_64(&mut self, xt1: u8, xt2: u8, xn: u8, offset_bytes: i32) {
|
||||
debug_assert_eq!(
|
||||
offset_bytes % 8,
|
||||
0,
|
||||
"LDP post-index offset must be 8-byte aligned"
|
||||
);
|
||||
debug_assert!(
|
||||
(-512..=504).contains(&offset_bytes),
|
||||
"LDP post-index offset out of imm7 range"
|
||||
);
|
||||
let imm7 = ((offset_bytes / 8) as u32) & 0x7f;
|
||||
self.emit(
|
||||
0xa8c00000
|
||||
@@ -388,3 +501,93 @@ impl Arm64Assembler {
|
||||
self.emit(0xd51b4200 | (xt as u32 & 0x1f));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn frame_pair_encodings_cover_every_used_offset() {
|
||||
// Cross-checked against the architectural encodings:
|
||||
// stp x29, x30, [sp, #-16]! == 0xa9bf7bfd
|
||||
// ldp x29, x30, [sp], #16 == 0xa8c17bfd
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.stp_pre_64(X29, X30, SP, -16);
|
||||
asm.ldp_post_64(X29, X30, SP, 16);
|
||||
asm.stp_pre_64(X29, X30, SP, -32);
|
||||
asm.ldp_post_64(X29, X30, SP, 32);
|
||||
asm.stp_pre_64(X29, X30, SP, -48);
|
||||
asm.ldp_post_64(X29, X30, SP, 48);
|
||||
assert_eq!(
|
||||
asm.instructions(),
|
||||
&[
|
||||
0xa9bf7bfd, 0xa8c17bfd, 0xa9be7bfd, 0xa8c27bfd, 0xa9bd7bfd, 0xa8c37bfd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stp_pre_64_respects_the_requested_frame_size() {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.stp_pre_64(X19, X20, SP, -64);
|
||||
assert_eq!(asm.instructions()[0], 0xa9bc53f3);
|
||||
asm.stp_pre_64(X19, X20, SP, 496);
|
||||
assert_eq!(asm.instructions()[1], 0xa99f53f3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alu_and_memory_encodings_match_llvm_mc() {
|
||||
// Golden words produced by llvm-mc 23.1.6 for the same instructions.
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.add_reg_64(X9, X9, X10);
|
||||
asm.sub_reg_64(X9, X9, X10);
|
||||
asm.and_reg_64(X9, X9, X10);
|
||||
asm.orr_reg_64(X19, XZR, X0);
|
||||
asm.eor_reg_64(X9, X9, X10);
|
||||
asm.add_imm_64(X1, X1, 8);
|
||||
asm.sub_imm_64(X1, X1, 8);
|
||||
asm.movz_64(X9, 0x1234, 0);
|
||||
asm.movk_64(X9, 0xabcd, 2);
|
||||
asm.ldr_uoff_64(X9, X19, 128);
|
||||
asm.str_uoff_64(X21, SP, 32);
|
||||
asm.ldr_uoff_32(X0, X19, 136);
|
||||
asm.str_uoff_32(X0, X19, 136);
|
||||
asm.ldr_reg_64(X9, X19, X10);
|
||||
asm.str_reg_64(X9, X19, X10);
|
||||
asm.mrs_nzcv(X9);
|
||||
asm.msr_nzcv(X9);
|
||||
assert_eq!(
|
||||
asm.instructions(),
|
||||
&[
|
||||
0x8b0a0129, 0xcb0a0129, 0x8a0a0129, 0xaa0003f3, 0xca0a0129, 0x91002021, 0xd1002021,
|
||||
0xd2824689, 0xf2d579a9, 0xf9404269, 0xf90013f5, 0xb9408a60, 0xb9008a60, 0xf86a6a69,
|
||||
0xf82a6a69, 0xd53b4209, 0xd51b4209,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_and_branch_encodings_match_the_assembler() {
|
||||
// llvm-mc -triple=aarch64: cbz x5, #28 -> b40000e5;
|
||||
// cbnz x9, #-8 -> b5ffffc9; b #20 -> 14000005.
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.cbz_64(X5, 7);
|
||||
asm.cbnz_64(X9, -2);
|
||||
assert_eq!(asm.instructions(), &[0xb40000e5, 0xb5ffffc9]);
|
||||
asm.patch_cbz_64(0, X5, 1);
|
||||
assert_eq!(asm.instructions()[0], 0xb4000025);
|
||||
let mut branch = Arm64Assembler::new();
|
||||
branch.b(0);
|
||||
branch.patch_b(0, 5);
|
||||
assert_eq!(branch.instructions()[0], 0x14000005);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsigned_offset_stores_scale_by_access_size() {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.str_uoff_64(X21, SP, 32);
|
||||
asm.ldr_uoff_64(X9, X19, 128);
|
||||
asm.str_uoff_32(X0, X19, 136);
|
||||
assert_eq!(asm.instructions(), &[0xf90013f5, 0xf9404269, 0xb9008a60]);
|
||||
}
|
||||
}
|
||||
+314
-53
@@ -53,6 +53,27 @@ impl Register {
|
||||
}
|
||||
}
|
||||
|
||||
/// Instruction prefixes decoded ahead of an opcode.
|
||||
///
|
||||
/// The interpreter decodes these once per instruction and passes them to the
|
||||
/// helpers that need them, so prefix state travels as one typed value instead
|
||||
/// of a list of independent booleans.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
struct Prefixes {
|
||||
/// REX.W: 64-bit operand size.
|
||||
rex_w: bool,
|
||||
/// REX.R: extends the ModRM `reg` field to R8-R15.
|
||||
rex_r: bool,
|
||||
/// REX.X: extends the SIB `index` field to R8-R15.
|
||||
rex_x: bool,
|
||||
/// REX.B: extends the ModRM `rm` field to R8-R15.
|
||||
rex_b: bool,
|
||||
/// The GS segment override prefix (0x65) is present.
|
||||
seg_gs: bool,
|
||||
/// The FS segment override prefix (0x64) is present.
|
||||
seg_fs: bool,
|
||||
}
|
||||
|
||||
/// RFLAGS status bits tracked during guest execution.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct RFlags {
|
||||
@@ -62,12 +83,15 @@ pub struct RFlags {
|
||||
pub of: bool, // Overflow flag
|
||||
}
|
||||
|
||||
/// x86-64 CPU state.
|
||||
/// x86-64 CPU state. Native DBT accesses the general registers and RIP by offset.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct CpuState {
|
||||
pub gpr: [u64; 16],
|
||||
pub rip: u64,
|
||||
pub flags: RFlags,
|
||||
pub gs_base: u64,
|
||||
pub fs_base: u64,
|
||||
}
|
||||
|
||||
impl CpuState {
|
||||
@@ -78,6 +102,8 @@ impl CpuState {
|
||||
gpr,
|
||||
rip: entry_point,
|
||||
flags: RFlags::default(),
|
||||
gs_base: 0,
|
||||
fs_base: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,6 +122,7 @@ pub enum ExitReason {
|
||||
Halt,
|
||||
Syscall(u64),
|
||||
StepLimitExceeded,
|
||||
JitCacheExhausted,
|
||||
MemoryFault(MemoryError),
|
||||
IllegalInstruction(u8),
|
||||
StackUnderflow,
|
||||
@@ -107,6 +134,7 @@ impl fmt::Display for ExitReason {
|
||||
Self::Halt => write!(f, "guest executed HLT"),
|
||||
Self::Syscall(nr) => write!(f, "guest executed SYSCALL ({nr})"),
|
||||
Self::StepLimitExceeded => write!(f, "execution step budget exhausted"),
|
||||
Self::JitCacheExhausted => write!(f, "native JIT code cache exhausted"),
|
||||
Self::MemoryFault(e) => write!(f, "memory fault: {e}"),
|
||||
Self::IllegalInstruction(op) => write!(f, "illegal or unsupported opcode: 0x{op:02x}"),
|
||||
Self::StackUnderflow => write!(f, "stack underflow"),
|
||||
@@ -116,6 +144,197 @@ impl fmt::Display for ExitReason {
|
||||
|
||||
impl std::error::Error for ExitReason {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod layout_tests {
|
||||
use super::{CpuState, RFlags, Register};
|
||||
|
||||
/// The native translator addresses guest registers and RIP by raw byte
|
||||
/// offset. Keep these assertions next to the struct so a layout change
|
||||
/// cannot silently corrupt translated blocks.
|
||||
#[test]
|
||||
fn native_translator_offsets_match_repr_c_layout() {
|
||||
assert_eq!(std::mem::offset_of!(CpuState, gpr), 0);
|
||||
assert_eq!(std::mem::offset_of!(CpuState, rip), 16 * 8);
|
||||
assert_eq!(std::mem::offset_of!(CpuState, flags), 16 * 8 + 8);
|
||||
assert_eq!(std::mem::offset_of!(CpuState, gs_base), 16 * 8 + 8 + 8);
|
||||
assert_eq!(std::mem::offset_of!(CpuState, fs_base), 16 * 8 + 8 + 8 + 8);
|
||||
assert_eq!(std::mem::size_of::<RFlags>(), 4);
|
||||
assert_eq!(std::mem::size_of::<CpuState>(), 16 * 8 + 8 + 8 + 8 + 8);
|
||||
|
||||
let cpu = CpuState::default();
|
||||
let base = std::ptr::addr_of!(cpu) as usize;
|
||||
for reg in [Register::Rax, Register::Rsp, Register::R15] {
|
||||
assert_eq!(
|
||||
base + (reg as usize) * 8,
|
||||
std::ptr::addr_of!(cpu.gpr[reg as usize]) as usize
|
||||
);
|
||||
}
|
||||
assert_eq!(base + 16 * 8, std::ptr::addr_of!(cpu.rip) as usize);
|
||||
assert_eq!(base + 16 * 8 + 8, std::ptr::addr_of!(cpu.flags) as usize);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod prefix_tests {
|
||||
use super::{CpuState, ExitReason, Interpreter, Register};
|
||||
use crate::memory::{GuestMemory, MemoryPermissions};
|
||||
|
||||
const CODE_BASE: u64 = 0x1000;
|
||||
const CODE_SIZE: usize = 0x1000;
|
||||
const STACK_BASE: u64 = 0x8000_0000;
|
||||
const STACK_SIZE: usize = 0x10000;
|
||||
const FS_BASE: u64 = 0x9000;
|
||||
const GS_BASE: u64 = 0xA000;
|
||||
|
||||
/// A guest memory image with executable code, a stack and distinct FS and
|
||||
/// GS bases.
|
||||
fn memory_with_code(code: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
CODE_BASE,
|
||||
CODE_SIZE,
|
||||
MemoryPermissions::READ_WRITE_EXECUTE,
|
||||
code,
|
||||
)
|
||||
.expect("code region");
|
||||
memory
|
||||
.map_region(STACK_BASE, STACK_SIZE, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack region");
|
||||
// The segment bases are distinct so a swapped prefix is visible.
|
||||
memory
|
||||
.map_region(FS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.expect("fs region");
|
||||
memory
|
||||
.map_region(GS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.expect("gs region");
|
||||
memory
|
||||
}
|
||||
|
||||
/// Run `code` on the interpreter and return the final state and exit reason.
|
||||
fn run(code: &[u8]) -> (CpuState, ExitReason) {
|
||||
let mut memory = memory_with_code(code);
|
||||
let cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut memory, 64);
|
||||
let result = interp.run();
|
||||
(result.final_state, result.exit_reason)
|
||||
}
|
||||
|
||||
/// `mov r8, imm64`: 49 B8 <imm64>.
|
||||
fn mov_r8_imm64(value: u64) -> Vec<u8> {
|
||||
let mut code = vec![0x49, 0xB8];
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// `mov rbx, imm64`: 48 BB <imm64>.
|
||||
fn mov_rbx_imm64(value: u64) -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xBB];
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// `mov rax, imm64`: 48 B8 <imm64>.
|
||||
fn mov_rax_imm64(value: u64) -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xB8];
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// REX.B extends the ModRM `rm` field, so `rm=0` selects r8.
|
||||
///
|
||||
/// Encoding 49 89 D8 is `mov r8, rbx`.
|
||||
#[test]
|
||||
fn rex_b_extends_the_rm_field_to_r8() {
|
||||
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x49, 0x89, 0xD8]); // mov r8, rbx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
|
||||
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
|
||||
// No prefix in this encoding selects r9.
|
||||
assert_eq!(state.get(Register::R9), 0);
|
||||
}
|
||||
|
||||
/// REX.R extends the ModRM `reg` field, so `reg=0` selects r8.
|
||||
///
|
||||
/// Encoding 4C 89 C3 is `mov rbx, r8`.
|
||||
#[test]
|
||||
fn rex_r_extends_the_reg_field_to_r8() {
|
||||
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x4C, 0x89, 0xC3]); // mov rbx, r8
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
|
||||
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
|
||||
// No prefix in this encoding selects r9.
|
||||
assert_eq!(state.get(Register::R9), 0);
|
||||
}
|
||||
|
||||
/// REX.R and REX.B extend independent fields, so the destination r9 and
|
||||
/// the source r12 are chosen by different prefix bits.
|
||||
///
|
||||
/// Encoding 4D 89 E1 is `mov r9, r12`.
|
||||
#[test]
|
||||
fn rex_r_and_rex_b_extend_independent_fields() {
|
||||
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x4D, 0x89, 0xE1]); // mov r9, r12
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// r9 receives r12, which is zero here, and not the value in r8.
|
||||
assert_eq!(state.get(Register::R9), 0);
|
||||
assert_eq!(state.get(Register::R12), 0);
|
||||
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
|
||||
}
|
||||
|
||||
/// Without REX.W the move is 32-bit wide, so the destination keeps only the
|
||||
/// low half of the source and its upper half is cleared.
|
||||
///
|
||||
/// Encoding 89 D8 is `mov eax, ebx`.
|
||||
#[test]
|
||||
fn a_move_without_rex_w_is_32_bit_wide() {
|
||||
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x89, 0xD8]); // mov eax, ebx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// Only the low 32 bits of ebx survive, and rax's upper half is cleared.
|
||||
assert_eq!(state.get(Register::Rax), 0x5566_7788);
|
||||
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
|
||||
}
|
||||
|
||||
/// The FS segment override adds the FS base to the effective address.
|
||||
///
|
||||
/// Encoding 64 48 89 04 25 08 00 00 00 is `mov fs:[0x8], rax`.
|
||||
#[test]
|
||||
fn the_fs_prefix_adds_the_fs_base() {
|
||||
let mut code = mov_rax_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x64, 0x48, 0x89, 0x04, 0x25, 0x08, 0x00, 0x00, 0x00]);
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let mut memory = memory_with_code(&code);
|
||||
let mut cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
|
||||
cpu.fs_base = FS_BASE;
|
||||
cpu.gs_base = GS_BASE;
|
||||
let mut interp = Interpreter::new(cpu, &mut memory, 64);
|
||||
let result = interp.run();
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(
|
||||
memory.read_u64(FS_BASE + 0x8).expect("fs read"),
|
||||
0x1122_3344_5566_7788
|
||||
);
|
||||
// The GS base is untouched: the GS-prefixed store did not happen.
|
||||
assert_eq!(memory.read_u64(GS_BASE + 0x8).expect("gs read"), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Result returned after running guest execution.
|
||||
#[derive(Debug)]
|
||||
pub struct ExecutionResult {
|
||||
@@ -209,17 +428,35 @@ impl<'a> Interpreter<'a> {
|
||||
|
||||
/// Single-step execution. Returns Ok(Some(ExitReason)) on clean exit (HLT/SYSCALL).
|
||||
pub fn step(&mut self) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let mut rex_w = false;
|
||||
let mut rex_r = false;
|
||||
let mut rex_b = false;
|
||||
let start = self.cpu.rip;
|
||||
let result = self.execute_instruction();
|
||||
if result.is_err() {
|
||||
self.cpu.rip = start;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn execute_instruction(&mut self) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let mut prefixes = Prefixes::default();
|
||||
|
||||
let mut byte = self.fetch_u8()?;
|
||||
|
||||
// Handle legacy segment prefixes: 0x65 (GS), 0x64 (FS)
|
||||
while byte == 0x65 || byte == 0x64 {
|
||||
if byte == 0x65 {
|
||||
prefixes.seg_gs = true;
|
||||
} else {
|
||||
prefixes.seg_fs = true;
|
||||
}
|
||||
byte = self.fetch_u8()?;
|
||||
}
|
||||
|
||||
// Handle REX prefix (0x40 - 0x4F)
|
||||
if (byte & 0xF0) == 0x40 {
|
||||
rex_w = (byte & 0x08) != 0;
|
||||
rex_r = (byte & 0x04) != 0;
|
||||
rex_b = (byte & 0x01) != 0;
|
||||
prefixes.rex_w = (byte & 0x08) != 0;
|
||||
prefixes.rex_r = (byte & 0x04) != 0;
|
||||
prefixes.rex_x = (byte & 0x02) != 0;
|
||||
prefixes.rex_b = (byte & 0x01) != 0;
|
||||
byte = self.fetch_u8()?;
|
||||
}
|
||||
|
||||
@@ -227,22 +464,27 @@ impl<'a> Interpreter<'a> {
|
||||
// HLT: Halt execution
|
||||
0xF4 => Ok(Some(ExitReason::Halt)),
|
||||
|
||||
// SYSCALL: 0x0F 0x05
|
||||
0x0F => {
|
||||
let second = self.fetch_u8()?;
|
||||
if second == 0x05 {
|
||||
let syscall_num = self.cpu.get(Register::Rax);
|
||||
Ok(Some(ExitReason::Syscall(syscall_num)))
|
||||
} else {
|
||||
Err(ExitReason::IllegalInstruction(second))
|
||||
0x0F => match self.fetch_u8()? {
|
||||
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
|
||||
op @ 0xC8..=0xCF => {
|
||||
let reg = Register::from_index((op & 7) | (u8::from(prefixes.rex_b) << 3));
|
||||
let value = self.cpu.get(reg);
|
||||
let reversed = if prefixes.rex_w {
|
||||
value.swap_bytes()
|
||||
} else {
|
||||
u64::from((value as u32).swap_bytes())
|
||||
};
|
||||
self.cpu.set(reg, reversed);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
op => Err(ExitReason::IllegalInstruction(op)),
|
||||
},
|
||||
|
||||
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
|
||||
0xB8..=0xBF => {
|
||||
let reg_idx = (byte - 0xB8) + if rex_b { 8 } else { 0 };
|
||||
let reg_idx = (byte - 0xB8) + if prefixes.rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
if rex_w {
|
||||
if prefixes.rex_w {
|
||||
let imm = self.fetch_u64()?;
|
||||
self.cpu.set(reg, imm);
|
||||
} else {
|
||||
@@ -255,28 +497,28 @@ impl<'a> Interpreter<'a> {
|
||||
// XOR r/m, reg (0x31) or XOR reg, r/m (0x33)
|
||||
0x31 | 0x33 => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
|
||||
let (src, dst) = if byte == 0x31 { (reg, rm) } else { (rm, reg) };
|
||||
let val1 = self.cpu.get(dst);
|
||||
let val2 = self.cpu.get(src);
|
||||
let res = if rex_w {
|
||||
let res = if prefixes.rex_w {
|
||||
val1 ^ val2
|
||||
} else {
|
||||
(val1 as u32 ^ val2 as u32) as u64
|
||||
};
|
||||
self.cpu.set(dst, res);
|
||||
self.update_flags_logic(res, rex_w);
|
||||
self.update_flags_logic(res, prefixes.rex_w);
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// ADD r/m, reg (0x01) or ADD reg, r/m (0x03)
|
||||
0x01 | 0x03 => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
|
||||
let (src, dst) = if byte == 0x01 { (reg, rm) } else { (rm, reg) };
|
||||
let val1 = self.cpu.get(dst);
|
||||
let val2 = self.cpu.get(src);
|
||||
let (res, flags) = if rex_w {
|
||||
let (res, flags) = if prefixes.rex_w {
|
||||
add64(val1, val2)
|
||||
} else {
|
||||
let (r, f) = add32(val1 as u32, val2 as u32);
|
||||
@@ -290,11 +532,11 @@ impl<'a> Interpreter<'a> {
|
||||
// SUB r/m, reg (0x29) or SUB reg, r/m (0x2B)
|
||||
0x29 | 0x2B => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
|
||||
let (src, dst) = if byte == 0x29 { (reg, rm) } else { (rm, reg) };
|
||||
let val1 = self.cpu.get(dst);
|
||||
let val2 = self.cpu.get(src);
|
||||
let (res, flags) = if rex_w {
|
||||
let (res, flags) = if prefixes.rex_w {
|
||||
sub64(val1, val2)
|
||||
} else {
|
||||
let (r, f) = sub32(val1 as u32, val2 as u32);
|
||||
@@ -308,13 +550,13 @@ impl<'a> Interpreter<'a> {
|
||||
// CMP reg, r/m (0x3B) or CMP r/m, reg (0x39)
|
||||
0x39 | 0x3B => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
|
||||
let (v1, v2) = if byte == 0x39 {
|
||||
(self.cpu.get(rm), self.cpu.get(reg))
|
||||
} else {
|
||||
(self.cpu.get(reg), self.cpu.get(rm))
|
||||
};
|
||||
let (_, flags) = if rex_w {
|
||||
let (_, flags) = if prefixes.rex_w {
|
||||
sub64(v1, v2)
|
||||
} else {
|
||||
let (r, f) = sub32(v1 as u32, v2 as u32);
|
||||
@@ -328,7 +570,7 @@ impl<'a> Interpreter<'a> {
|
||||
0x83 => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let op = (modrm >> 3) & 7;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
|
||||
let imm8 = self.fetch_i8()? as i64;
|
||||
let imm = imm8 as u64;
|
||||
|
||||
@@ -336,7 +578,7 @@ impl<'a> Interpreter<'a> {
|
||||
match op {
|
||||
0 => {
|
||||
// ADD
|
||||
let (res, flags) = if rex_w {
|
||||
let (res, flags) = if prefixes.rex_w {
|
||||
add64(val, imm)
|
||||
} else {
|
||||
let (r, f) = add32(val as u32, imm as u32);
|
||||
@@ -347,7 +589,7 @@ impl<'a> Interpreter<'a> {
|
||||
}
|
||||
5 => {
|
||||
// SUB
|
||||
let (res, flags) = if rex_w {
|
||||
let (res, flags) = if prefixes.rex_w {
|
||||
sub64(val, imm)
|
||||
} else {
|
||||
let (r, f) = sub32(val as u32, imm as u32);
|
||||
@@ -358,7 +600,7 @@ impl<'a> Interpreter<'a> {
|
||||
}
|
||||
7 => {
|
||||
// CMP
|
||||
let (_, flags) = if rex_w {
|
||||
let (_, flags) = if prefixes.rex_w {
|
||||
sub64(val, imm)
|
||||
} else {
|
||||
let (r, f) = sub32(val as u32, imm as u32);
|
||||
@@ -375,7 +617,7 @@ impl<'a> Interpreter<'a> {
|
||||
// MOV r/m, reg (0x89) or MOV reg, r/m (0x8B)
|
||||
0x89 | 0x8B => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
self.execute_mov_rm(modrm, rex_w, rex_r, rex_b, byte == 0x8B)
|
||||
self.execute_mov_rm(modrm, &prefixes, byte == 0x8B)
|
||||
}
|
||||
|
||||
// JMP rel8 (0xEB)
|
||||
@@ -429,7 +671,7 @@ impl<'a> Interpreter<'a> {
|
||||
|
||||
// PUSH reg (0x50..=0x57)
|
||||
0x50..=0x57 => {
|
||||
let reg_idx = (byte - 0x50) + if rex_b { 8 } else { 0 };
|
||||
let reg_idx = (byte - 0x50) + if prefixes.rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
let val = self.cpu.get(reg);
|
||||
self.push_u64(val)?;
|
||||
@@ -438,7 +680,7 @@ impl<'a> Interpreter<'a> {
|
||||
|
||||
// POP reg (0x58..=0x5F)
|
||||
0x58..=0x5F => {
|
||||
let reg_idx = (byte - 0x58) + if rex_b { 8 } else { 0 };
|
||||
let reg_idx = (byte - 0x58) + if prefixes.rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
let val = self.pop_u64()?;
|
||||
self.cpu.set(reg, val);
|
||||
@@ -469,29 +711,26 @@ impl<'a> Interpreter<'a> {
|
||||
fn decode_modrm_reg_reg(
|
||||
&self,
|
||||
modrm: u8,
|
||||
rex_r: bool,
|
||||
rex_b: bool,
|
||||
prefixes: &Prefixes,
|
||||
) -> Result<(Register, Register), ExitReason> {
|
||||
let mode = (modrm >> 6) & 3;
|
||||
if mode != 3 {
|
||||
return Err(ExitReason::IllegalInstruction(modrm));
|
||||
}
|
||||
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
|
||||
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
|
||||
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
|
||||
}
|
||||
|
||||
fn execute_mov_rm(
|
||||
&mut self,
|
||||
modrm: u8,
|
||||
rex_w: bool,
|
||||
rex_r: bool,
|
||||
rex_b: bool,
|
||||
prefixes: &Prefixes,
|
||||
is_load: bool,
|
||||
) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let mode = (modrm >> 6) & 3;
|
||||
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
|
||||
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
|
||||
if mode == 3 {
|
||||
@@ -499,12 +738,24 @@ impl<'a> Interpreter<'a> {
|
||||
let rm = Register::from_index(rm_idx);
|
||||
if is_load {
|
||||
let val = self.cpu.get(rm);
|
||||
self.cpu
|
||||
.set(reg, if rex_w { val } else { val as u32 as u64 });
|
||||
self.cpu.set(
|
||||
reg,
|
||||
if prefixes.rex_w {
|
||||
val
|
||||
} else {
|
||||
val as u32 as u64
|
||||
},
|
||||
);
|
||||
} else {
|
||||
let val = self.cpu.get(reg);
|
||||
self.cpu
|
||||
.set(rm, if rex_w { val } else { val as u32 as u64 });
|
||||
self.cpu.set(
|
||||
rm,
|
||||
if prefixes.rex_w {
|
||||
val
|
||||
} else {
|
||||
val as u32 as u64
|
||||
},
|
||||
);
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -514,8 +765,12 @@ impl<'a> Interpreter<'a> {
|
||||
// SIB byte follows ModR/M
|
||||
let sib = self.fetch_u8()?;
|
||||
let scale_shift = (sib >> 6) & 3;
|
||||
let index_raw = ((sib >> 3) & 7) + if rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
|
||||
let base_raw = (sib & 7) + if rex_b { 8 } else { 0 };
|
||||
// REX.X extends the SIB index field; REX.R extends the ModRM reg
|
||||
// field and must not affect the index. An index field of 100b
|
||||
// selects r12 when REX.X is set, and means "no index" otherwise.
|
||||
let index_field = (sib >> 3) & 7;
|
||||
let index_raw = index_field + if prefixes.rex_x { 8 } else { 0 };
|
||||
let base_raw = (sib & 7) + if prefixes.rex_b { 8 } else { 0 };
|
||||
|
||||
let base_v = if mode == 0 && (sib & 7) == 5 {
|
||||
// disp32 with no base register
|
||||
@@ -524,7 +779,7 @@ impl<'a> Interpreter<'a> {
|
||||
self.cpu.get(Register::from_index(base_raw))
|
||||
};
|
||||
|
||||
let index_v = if (sib >> 3) & 7 == 4 {
|
||||
let index_v = if index_field == 4 && !prefixes.rex_x {
|
||||
// index == 4 means no index register (ESP/RSP)
|
||||
0u64
|
||||
} else {
|
||||
@@ -565,15 +820,21 @@ impl<'a> Interpreter<'a> {
|
||||
(base_val, disp)
|
||||
};
|
||||
|
||||
let effective_addr = if mode == 0 && (rm_idx & 7) == 5 {
|
||||
let mut effective_addr = if mode == 0 && (rm_idx & 7) == 5 {
|
||||
(self.cpu.rip as i64 + disp) as u64
|
||||
} else {
|
||||
(base_val as i64 + disp) as u64
|
||||
};
|
||||
|
||||
if prefixes.seg_gs {
|
||||
effective_addr = effective_addr.wrapping_add(self.cpu.gs_base);
|
||||
} else if prefixes.seg_fs {
|
||||
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
|
||||
}
|
||||
|
||||
if is_load {
|
||||
// Load from memory to reg
|
||||
if rex_w {
|
||||
if prefixes.rex_w {
|
||||
let val = self
|
||||
.memory
|
||||
.read_u64(effective_addr)
|
||||
@@ -589,7 +850,7 @@ impl<'a> Interpreter<'a> {
|
||||
} else {
|
||||
// Store from reg to memory
|
||||
let val = self.cpu.get(reg);
|
||||
if rex_w {
|
||||
if prefixes.rex_w {
|
||||
self.memory
|
||||
.write_u64(effective_addr, val)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
|
||||
+1540
-43
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,432 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest Import Table Binder and Host Service Dispatch Boundary for Xenora X15.
|
||||
//!
|
||||
//! Maps guest PE IAT (Import Address Table) entries to synthetic dispatch thunks,
|
||||
//! validating the Windows x64 ABI calling convention and dispatching calls to typed
|
||||
//! guest services without exposing raw host function pointers.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, Register};
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use crate::pe::ParsedPe;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
/// Base virtual address range reserved for synthetic guest import dispatch trampolines.
|
||||
pub const IMPORT_TRAMPOLINE_BASE_VA: u64 = 0x0000_0007_F000_0000;
|
||||
pub const IMPORT_TRAMPOLINE_STRIDE: u64 = 16;
|
||||
|
||||
/// Typed error resulting from import resolution or service dispatch.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ImportError {
|
||||
MalformedDirectory,
|
||||
DirectoryOutOfBounds { rva: u32 },
|
||||
UnresolvedImport { module: String, symbol: String },
|
||||
Memory(MemoryError),
|
||||
}
|
||||
|
||||
impl fmt::Display for ImportError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MalformedDirectory => write!(f, "malformed PE import directory"),
|
||||
Self::DirectoryOutOfBounds { rva } => {
|
||||
write!(f, "import directory at RVA 0x{rva:08x} is out of bounds")
|
||||
}
|
||||
Self::UnresolvedImport { module, symbol } => {
|
||||
write!(f, "unresolved import dependency: {module}!{symbol}")
|
||||
}
|
||||
Self::Memory(e) => write!(f, "guest memory error binding imports: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ImportError {}
|
||||
|
||||
impl From<MemoryError> for ImportError {
|
||||
fn from(e: MemoryError) -> Self {
|
||||
Self::Memory(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows x64 Calling Convention Argument Extractor.
|
||||
///
|
||||
/// In Microsoft x64 ABI:
|
||||
/// - Arg 0: RCX
|
||||
/// - Arg 1: RDX
|
||||
/// - Arg 2: R8
|
||||
/// - Arg 3: R9
|
||||
/// - Arg 4+: Stack [RSP + 40 + (n-4)*8] (accounting for return address [RSP] and 32-byte shadow space [RSP+8..RSP+40]).
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Win64Args {
|
||||
pub rcx: u64,
|
||||
pub rdx: u64,
|
||||
pub r8: u64,
|
||||
pub r9: u64,
|
||||
pub rsp: u64,
|
||||
}
|
||||
|
||||
impl Win64Args {
|
||||
pub fn new(cpu: &CpuState) -> Self {
|
||||
Self {
|
||||
rcx: cpu.get(Register::Rcx),
|
||||
rdx: cpu.get(Register::Rdx),
|
||||
r8: cpu.get(Register::R8),
|
||||
r9: cpu.get(Register::R9),
|
||||
rsp: cpu.get(Register::Rsp),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, index: usize, memory: &GuestMemory) -> Result<u64, MemoryError> {
|
||||
match index {
|
||||
0 => Ok(self.rcx),
|
||||
1 => Ok(self.rdx),
|
||||
2 => Ok(self.r8),
|
||||
3 => Ok(self.r9),
|
||||
n => {
|
||||
let stack_offset = 40 + ((n - 4) as u64) * 8;
|
||||
let addr = self
|
||||
.rsp
|
||||
.checked_add(stack_offset)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
memory.read_u64(addr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handler for a typed guest service.
|
||||
/// Returns Ok(ret_val) to be placed into RAX, or Err(reason) to halt/fault execution.
|
||||
pub type ServiceHandler = Box<
|
||||
dyn Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result<u64, ExitReason> + Send + Sync,
|
||||
>;
|
||||
|
||||
/// Scope of a registered handler's implementation.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ServiceStatus {
|
||||
Implemented,
|
||||
Partial,
|
||||
Stub,
|
||||
}
|
||||
|
||||
impl ServiceStatus {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Implemented => "implemented",
|
||||
Self::Partial => "partial",
|
||||
Self::Stub => "stub",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Registration entry for an imported symbol.
|
||||
pub struct ServiceDescriptor {
|
||||
pub module: String,
|
||||
pub symbol: String,
|
||||
pub handler: ServiceHandler,
|
||||
pub status: ServiceStatus,
|
||||
}
|
||||
|
||||
/// Registry for resolving and binding import symbols to guest trampoline VAs.
|
||||
pub struct ImportRegistry {
|
||||
services: HashMap<(String, String), usize>, // (module_lowercase, symbol) -> service_index
|
||||
handlers: Vec<ServiceDescriptor>,
|
||||
trampoline_to_service: HashMap<u64, usize>, // Trampoline VA -> service_index
|
||||
}
|
||||
|
||||
impl Default for ImportRegistry {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ImportRegistry {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
services: HashMap::new(),
|
||||
handlers: Vec::new(),
|
||||
trampoline_to_service: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn service_index(&self, module: &str, symbol: &str) -> Option<usize> {
|
||||
self.services
|
||||
.get(&(module.to_ascii_lowercase(), symbol.to_owned()))
|
||||
.copied()
|
||||
}
|
||||
|
||||
/// Check whether the exact import key has a binding, including stub handlers.
|
||||
pub fn has_binding(&self, module: &str, symbol: &str) -> bool {
|
||||
self.service_index(module, symbol).is_some()
|
||||
}
|
||||
|
||||
/// Register a host-provided guest service.
|
||||
pub fn register<F>(&mut self, module: &str, symbol: &str, handler: F)
|
||||
where
|
||||
F: Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result<u64, ExitReason>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
{
|
||||
let mod_key = module.to_ascii_lowercase();
|
||||
let sym_key = symbol.to_string();
|
||||
let index = self.handlers.len();
|
||||
self.handlers.push(ServiceDescriptor {
|
||||
module: mod_key.clone(),
|
||||
symbol: sym_key.clone(),
|
||||
handler: Box::new(handler),
|
||||
status: ServiceStatus::Implemented,
|
||||
});
|
||||
self.services.insert((mod_key, sym_key), index);
|
||||
}
|
||||
|
||||
/// Describe the canonical binding behind an import without calling it.
|
||||
pub fn binding(&self, module: &str, symbol: &str) -> Option<&ServiceDescriptor> {
|
||||
self.service_index(module, symbol)
|
||||
.map(|index| &self.handlers[index])
|
||||
}
|
||||
|
||||
/// Iterate all canonical registered (module, symbol, status) tuples.
|
||||
///
|
||||
/// Each entry is returned exactly once regardless of how many API-set alias
|
||||
/// keys point at the same underlying handler.
|
||||
pub fn iter_registered(&self) -> impl Iterator<Item = (&str, &str, ServiceStatus)> {
|
||||
self.handlers
|
||||
.iter()
|
||||
.map(|d| (d.module.as_str(), d.symbol.as_str(), d.status))
|
||||
}
|
||||
|
||||
/// Return (alias_module_lowercase, symbol) pairs that resolve to a canonical handler
|
||||
/// in a different module.
|
||||
pub fn iter_aliases(&self) -> impl Iterator<Item = (&str, &str, &str)> {
|
||||
// `services` maps (module_lc, symbol) -> handler_index.
|
||||
// An alias exists when module_lc != handlers[index].module.to_lowercase().
|
||||
self.services.iter().filter_map(|((mod_lc, sym), &idx)| {
|
||||
let canonical_mod = self.handlers[idx].module.to_ascii_lowercase();
|
||||
if *mod_lc != canonical_mod {
|
||||
Some((
|
||||
mod_lc.as_str(),
|
||||
sym.as_str(),
|
||||
self.handlers[idx].module.as_str(),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_status(&mut self, module: &str, symbol: &str, status: ServiceStatus) {
|
||||
let index = self
|
||||
.service_index(module, symbol)
|
||||
.expect("registered service");
|
||||
self.handlers[index].status = status;
|
||||
}
|
||||
|
||||
/// Register a service with an explicit implementation status.
|
||||
pub fn register_with_status<F>(
|
||||
&mut self,
|
||||
module: &str,
|
||||
symbol: &str,
|
||||
status: ServiceStatus,
|
||||
handler: F,
|
||||
) where
|
||||
F: Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result<u64, ExitReason>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
{
|
||||
self.register(module, symbol, handler);
|
||||
self.set_status(module, symbol, status);
|
||||
}
|
||||
|
||||
/// Point an API-set import at an existing handler and its trampoline.
|
||||
pub(crate) fn alias(&mut self, module: &str, target: &str, symbol: &str) {
|
||||
let index = self
|
||||
.service_index(target, symbol)
|
||||
.expect("registered alias target");
|
||||
self.services
|
||||
.insert((module.to_ascii_lowercase(), symbol.to_owned()), index);
|
||||
}
|
||||
|
||||
/// Bind the PE's Import Address Table (IAT) in guest memory to synthetic trampoline VAs.
|
||||
pub fn bind_imports(
|
||||
&mut self,
|
||||
pe: &ParsedPe,
|
||||
bytes: &[u8],
|
||||
loaded_base: u64,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<usize, ImportError> {
|
||||
let import_dir = find_import_directory(bytes)?;
|
||||
let Some((import_rva, import_size)) = import_dir else {
|
||||
return Ok(0);
|
||||
};
|
||||
if import_size == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let mut desc_file_off = pe
|
||||
.rva_to_file_offset(import_rva)
|
||||
.ok_or(ImportError::DirectoryOutOfBounds { rva: import_rva })?;
|
||||
|
||||
let mut bound_count = 0;
|
||||
|
||||
while desc_file_off + 20 <= bytes.len() {
|
||||
let oft =
|
||||
u32::from_le_bytes(bytes[desc_file_off..desc_file_off + 4].try_into().unwrap());
|
||||
let name_rva = u32::from_le_bytes(
|
||||
bytes[desc_file_off + 12..desc_file_off + 16]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
let ft = u32::from_le_bytes(
|
||||
bytes[desc_file_off + 16..desc_file_off + 20]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
if oft == 0 && name_rva == 0 && ft == 0 {
|
||||
break;
|
||||
}
|
||||
desc_file_off += 20;
|
||||
|
||||
let mod_name = if let Some(no) = pe.rva_to_file_offset(name_rva) {
|
||||
let mut end = no;
|
||||
while end < bytes.len() && bytes[end] != 0 {
|
||||
end += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&bytes[no..end]).into_owned()
|
||||
} else {
|
||||
"UNKNOWN.dll".to_string()
|
||||
};
|
||||
|
||||
let thunk_rva = if oft != 0 { oft } else { ft };
|
||||
let iat_base_rva = ft;
|
||||
|
||||
let Some(mut thunk_off) = pe.rva_to_file_offset(thunk_rva) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let mut idx = 0u32;
|
||||
while thunk_off + 8 <= bytes.len() {
|
||||
let val = u64::from_le_bytes(bytes[thunk_off..thunk_off + 8].try_into().unwrap());
|
||||
if val == 0 {
|
||||
break;
|
||||
}
|
||||
thunk_off += 8;
|
||||
let iat_rva = iat_base_rva + idx * 8;
|
||||
idx += 1;
|
||||
|
||||
let sym_name = if (val & (1 << 63)) != 0 {
|
||||
format!("Ordinal#{}", val & 0xFFFF)
|
||||
} else {
|
||||
let hint_rva = (val & 0x7FFF_FFFF) as u32;
|
||||
if let Some(ho) = pe.rva_to_file_offset(hint_rva) {
|
||||
let str_start = ho + 2;
|
||||
let mut str_end = str_start;
|
||||
while str_end < bytes.len() && bytes[str_end] != 0 {
|
||||
str_end += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned()
|
||||
} else {
|
||||
"UNKNOWN_SYM".to_string()
|
||||
}
|
||||
};
|
||||
|
||||
let Some(service_idx) = self.service_index(&mod_name, &sym_name) else {
|
||||
return Err(ImportError::UnresolvedImport {
|
||||
module: mod_name,
|
||||
symbol: sym_name,
|
||||
});
|
||||
};
|
||||
|
||||
// Assign a deterministic synthetic trampoline VA
|
||||
let trampoline_va =
|
||||
IMPORT_TRAMPOLINE_BASE_VA + (service_idx as u64) * IMPORT_TRAMPOLINE_STRIDE;
|
||||
self.trampoline_to_service
|
||||
.insert(trampoline_va, service_idx);
|
||||
|
||||
// Write trampoline_va into guest IAT entry at (loaded_base + iat_rva)
|
||||
let iat_va = loaded_base + iat_rva as u64;
|
||||
memory.write_u64_bypass(iat_va, trampoline_va)?;
|
||||
bound_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(bound_count)
|
||||
}
|
||||
|
||||
/// Check if target RIP matches a synthetic service trampoline.
|
||||
pub fn is_service_trampoline(&self, rip: u64) -> bool {
|
||||
self.trampoline_to_service.contains_key(&rip)
|
||||
}
|
||||
|
||||
/// Dispatch a service call when guest RIP hits a service trampoline.
|
||||
pub fn dispatch(
|
||||
&self,
|
||||
rip: u64,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<(), ExitReason> {
|
||||
let service_idx = *self
|
||||
.trampoline_to_service
|
||||
.get(&rip)
|
||||
.ok_or(ExitReason::IllegalInstruction(0xFF))?;
|
||||
|
||||
let descriptor = &self.handlers[service_idx];
|
||||
|
||||
// 1. Extract arguments according to Win64 convention
|
||||
let args = Win64Args::new(cpu);
|
||||
|
||||
// 2. Execute service handler
|
||||
let ret_val = (descriptor.handler)(&args, cpu, memory)?;
|
||||
|
||||
// 3. Store return value into RAX
|
||||
cpu.set(Register::Rax, ret_val);
|
||||
|
||||
// 4. Emulate RET instruction: pop return address from guest stack into RIP
|
||||
let rsp = cpu.get(Register::Rsp);
|
||||
let ret_addr = memory.read_u64(rsp).map_err(ExitReason::MemoryFault)?;
|
||||
cpu.set(Register::Rsp, rsp + 8);
|
||||
cpu.rip = ret_addr;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn find_import_directory(bytes: &[u8]) -> Result<Option<(u32, u32)>, ImportError> {
|
||||
if bytes.len() < 0x40 {
|
||||
return Ok(None);
|
||||
}
|
||||
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
let opt_offset = e_lfanew + 24;
|
||||
let coff_offset = e_lfanew + 4;
|
||||
if bytes.len() < coff_offset + 18 {
|
||||
return Ok(None);
|
||||
}
|
||||
let size_of_opt = u16::from_le_bytes(
|
||||
bytes[coff_offset + 16..coff_offset + 18]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
) as usize;
|
||||
|
||||
// Import directory is directory index 1 (offset 112 + 1 * 8 = 120 in Optional Header)
|
||||
if size_of_opt < 128 || bytes.len() < opt_offset + 128 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let import_rva = u32::from_le_bytes(
|
||||
bytes[opt_offset + 120..opt_offset + 124]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
let import_size = u32::from_le_bytes(
|
||||
bytes[opt_offset + 124..opt_offset + 128]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
if import_rva == 0 || import_size == 0 {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some((import_rva, import_size)))
|
||||
}
|
||||
}
|
||||
@@ -47,8 +47,8 @@ unsafe impl Sync for JitMemory {}
|
||||
impl JitMemory {
|
||||
/// Allocate a new JIT memory region using `MAP_JIT`.
|
||||
pub fn new(capacity: usize) -> Result<Self, JitError> {
|
||||
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
|
||||
let aligned_capacity = (capacity + page_size - 1) & !(page_size - 1);
|
||||
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
|
||||
let aligned_capacity = aligned_capacity(capacity, page_size)?;
|
||||
|
||||
let ptr = unsafe {
|
||||
libc::mmap(
|
||||
@@ -98,10 +98,7 @@ impl JitMemory {
|
||||
/// Automatically manages `pthread_jit_write_protect_np`, copies bytes,
|
||||
/// flushes data cache and invalidates instruction cache.
|
||||
pub fn emit_block(&mut self, instructions: &[u32]) -> Result<*const u8, JitError> {
|
||||
let bytes_len = instructions.len() * 4;
|
||||
if self.used + bytes_len > self.capacity {
|
||||
return Err(JitError::CapacityExceeded);
|
||||
}
|
||||
let bytes_len = emit_len(self.used, instructions.len(), self.capacity)?;
|
||||
|
||||
let emit_offset = self.used;
|
||||
let dst_ptr = unsafe { self.ptr.as_ptr().add(emit_offset) };
|
||||
@@ -131,6 +128,27 @@ impl JitMemory {
|
||||
}
|
||||
}
|
||||
|
||||
/// Round `capacity` up to a whole number of pages, rejecting an invalid page size
|
||||
/// (`sysconf` failure, zero or not a power of two) and arithmetic overflow.
|
||||
fn aligned_capacity(capacity: usize, page_size: libc::c_long) -> Result<usize, JitError> {
|
||||
let page_size = usize::try_from(page_size)
|
||||
.ok()
|
||||
.filter(|p| p.is_power_of_two())
|
||||
.ok_or(JitError::AllocationFailed(libc::EINVAL))?;
|
||||
capacity
|
||||
.checked_add(page_size - 1)
|
||||
.map(|c| c & !(page_size - 1))
|
||||
.ok_or(JitError::CapacityExceeded)
|
||||
}
|
||||
|
||||
/// Byte length of `count` 4-byte instructions, if they fit after `used` bytes.
|
||||
fn emit_len(used: usize, count: usize, capacity: usize) -> Result<usize, JitError> {
|
||||
count
|
||||
.checked_mul(4)
|
||||
.filter(|len| used.checked_add(*len).is_some_and(|end| end <= capacity))
|
||||
.ok_or(JitError::CapacityExceeded)
|
||||
}
|
||||
|
||||
impl Drop for JitMemory {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
@@ -138,3 +156,68 @@ impl Drop for JitMemory {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn capacity_rounds_up_to_whole_pages() {
|
||||
assert_eq!(aligned_capacity(1, 16384), Ok(16384));
|
||||
assert_eq!(aligned_capacity(16384, 16384), Ok(16384));
|
||||
assert_eq!(aligned_capacity(16385, 16384), Ok(32768));
|
||||
assert_eq!(aligned_capacity(0, 4096), Ok(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_page_size_is_rejected() {
|
||||
for page in [-1, 0, 3, 12288] {
|
||||
assert_eq!(
|
||||
aligned_capacity(4096, page),
|
||||
Err(JitError::AllocationFailed(libc::EINVAL)),
|
||||
"page size {page}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capacity_rounding_overflow_is_rejected() {
|
||||
assert_eq!(
|
||||
aligned_capacity(usize::MAX, 16384),
|
||||
Err(JitError::CapacityExceeded)
|
||||
);
|
||||
assert_eq!(
|
||||
aligned_capacity(usize::MAX - 16382, 16384),
|
||||
Err(JitError::CapacityExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emit_length_is_checked() {
|
||||
assert_eq!(emit_len(0, 4, 16), Ok(16));
|
||||
assert_eq!(emit_len(4, 3, 16), Ok(12));
|
||||
assert_eq!(emit_len(4, 4, 16), Err(JitError::CapacityExceeded));
|
||||
// count * 4 overflows usize.
|
||||
assert_eq!(
|
||||
emit_len(0, usize::MAX / 2, usize::MAX),
|
||||
Err(JitError::CapacityExceeded)
|
||||
);
|
||||
// used + len overflows usize.
|
||||
assert_eq!(
|
||||
emit_len(usize::MAX - 3, 2, usize::MAX),
|
||||
Err(JitError::CapacityExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emit_past_capacity_fails_and_leaves_usage_unchanged() {
|
||||
let mut jit = JitMemory::new(1).expect("MAP_JIT allocation");
|
||||
let words = jit.capacity() / 4;
|
||||
assert!(jit.emit_block(&vec![0xD503_201F; words]).is_ok()); // NOP fills the page
|
||||
assert_eq!(
|
||||
jit.emit_block(&[0xD503_201F]),
|
||||
Err(JitError::CapacityExceeded)
|
||||
);
|
||||
assert_eq!(jit.used(), jit.capacity());
|
||||
}
|
||||
}
|
||||
@@ -8,15 +8,39 @@
|
||||
pub mod arm64;
|
||||
pub mod cpu;
|
||||
pub mod dbt;
|
||||
pub mod graphics;
|
||||
pub mod imports;
|
||||
pub mod jit;
|
||||
pub mod memory;
|
||||
pub mod pe;
|
||||
pub mod probe;
|
||||
pub mod reloc;
|
||||
pub mod services;
|
||||
pub mod startup;
|
||||
pub mod tls;
|
||||
pub mod triage;
|
||||
|
||||
pub use arm64::Arm64Assembler;
|
||||
pub use cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register};
|
||||
pub use dbt::{DbtEngine, DbtMetrics};
|
||||
pub use graphics::{
|
||||
BackendRenderer, CommandListType, ExecutionOutcome, FramePresentation, GraphicsBackendId,
|
||||
GraphicsCommand, GraphicsCommandAllocator, GraphicsCommandList, GraphicsCommandQueue,
|
||||
GraphicsContext, GraphicsError, GraphicsHandle, GraphicsResource, ResourceDesc,
|
||||
ResourceDimension, ResourceStates,
|
||||
};
|
||||
pub use imports::{ImportError, ImportRegistry, ServiceDescriptor, ServiceHandler, Win64Args};
|
||||
pub use jit::{JitError, JitMemory};
|
||||
pub use memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
pub use pe::{LoadedImage, ParsedPe, PeError, PeSection};
|
||||
pub use probe::{
|
||||
ImportedSymbol, InstructionRecord, ProbeConfig, ProbeReport, RelocationCensus, TlsCensus,
|
||||
probe_pe_bytes, run_probe_and_export,
|
||||
};
|
||||
pub use reloc::{
|
||||
IMAGE_REL_BASED_ABSOLUTE, IMAGE_REL_BASED_DIR64, RelocationError, RelocationReport,
|
||||
apply_relocations,
|
||||
};
|
||||
pub use services::{Clock, MockClock, ServicesState, SystemClock, register_standard_services};
|
||||
pub use tls::{TlsDirectory, TlsError, execute_tls_callbacks, parse_tls_directory, setup_tls};
|
||||
pub use triage::{TriageReport, triage_bytes, triage_file};
|
||||
+204
-69
@@ -7,6 +7,8 @@
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub(crate) const ALLOCATION_GRANULARITY: u64 = 65_536;
|
||||
|
||||
/// Permission flags for a mapped memory region.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct MemoryPermissions {
|
||||
@@ -16,6 +18,11 @@ pub struct MemoryPermissions {
|
||||
}
|
||||
|
||||
impl MemoryPermissions {
|
||||
pub const NO_ACCESS: Self = Self {
|
||||
read: false,
|
||||
write: false,
|
||||
execute: false,
|
||||
};
|
||||
pub const READ_ONLY: Self = Self {
|
||||
read: true,
|
||||
write: false,
|
||||
@@ -83,6 +90,7 @@ struct MappedRegion {
|
||||
base: u64,
|
||||
data: Vec<u8>,
|
||||
permissions: MemoryPermissions,
|
||||
virtual_allocation: bool,
|
||||
}
|
||||
|
||||
impl MappedRegion {
|
||||
@@ -117,29 +125,7 @@ impl GuestMemory {
|
||||
size: usize,
|
||||
permissions: MemoryPermissions,
|
||||
) -> Result<(), MemoryError> {
|
||||
let size_u64 = size as u64;
|
||||
let end = base.checked_add(size_u64).ok_or(MemoryError::Overflow)?;
|
||||
|
||||
// Ensure no overlap with existing regions
|
||||
for r in &self.regions {
|
||||
let r_end = r.base + r.data.len() as u64;
|
||||
if (base < r_end) && (r.base < end) {
|
||||
return Err(MemoryError::OverlappingRegion {
|
||||
base,
|
||||
size: size_u64,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
self.regions.push(MappedRegion {
|
||||
base,
|
||||
data: vec![0u8; size],
|
||||
permissions,
|
||||
});
|
||||
|
||||
// Keep sorted by base address
|
||||
self.regions.sort_by_key(|r| r.base);
|
||||
Ok(())
|
||||
self.map_region_with_data(base, size, permissions, &[])
|
||||
}
|
||||
|
||||
/// Map a new region and initialize it with initial data, bypassing runtime write permission checks.
|
||||
@@ -149,13 +135,23 @@ impl GuestMemory {
|
||||
size: usize,
|
||||
permissions: MemoryPermissions,
|
||||
initial_data: &[u8],
|
||||
) -> Result<(), MemoryError> {
|
||||
self.insert_region(base, size, permissions, initial_data, false)
|
||||
}
|
||||
|
||||
fn insert_region(
|
||||
&mut self,
|
||||
base: u64,
|
||||
size: usize,
|
||||
permissions: MemoryPermissions,
|
||||
initial_data: &[u8],
|
||||
virtual_allocation: bool,
|
||||
) -> Result<(), MemoryError> {
|
||||
let size_u64 = size as u64;
|
||||
let end = base.checked_add(size_u64).ok_or(MemoryError::Overflow)?;
|
||||
|
||||
for r in &self.regions {
|
||||
let r_end = r.base + r.data.len() as u64;
|
||||
if (base < r_end) && (r.base < end) {
|
||||
if base < r_end && r.base < end {
|
||||
return Err(MemoryError::OverlappingRegion {
|
||||
base,
|
||||
size: size_u64,
|
||||
@@ -163,71 +159,169 @@ impl GuestMemory {
|
||||
}
|
||||
}
|
||||
|
||||
let mut data = vec![0u8; size];
|
||||
let copy_len = std::cmp::min(size, initial_data.len());
|
||||
let mut data = Vec::new();
|
||||
data.try_reserve_exact(size)
|
||||
.map_err(|_| MemoryError::AllocationFailed)?;
|
||||
data.resize(size, 0);
|
||||
let copy_len = size.min(initial_data.len());
|
||||
data[..copy_len].copy_from_slice(&initial_data[..copy_len]);
|
||||
|
||||
self.regions.push(MappedRegion {
|
||||
base,
|
||||
data,
|
||||
permissions,
|
||||
virtual_allocation,
|
||||
});
|
||||
|
||||
self.regions.sort_by_key(|r| r.base);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn map_virtual_allocation(
|
||||
&mut self,
|
||||
requested_base: u64,
|
||||
size: usize,
|
||||
permissions: MemoryPermissions,
|
||||
) -> Result<u64, MemoryError> {
|
||||
// Bound the host storage retained by the synthetic VirtualAlloc service.
|
||||
const MAX_VIRTUAL_BYTES: usize = 64 * 1024 * 1024;
|
||||
let allocated: usize = self
|
||||
.regions
|
||||
.iter()
|
||||
.filter(|region| region.virtual_allocation)
|
||||
.map(|region| region.data.len())
|
||||
.sum();
|
||||
if size > MAX_VIRTUAL_BYTES - allocated {
|
||||
return Err(MemoryError::AllocationFailed);
|
||||
}
|
||||
|
||||
let mut base = requested_base;
|
||||
if base == 0 {
|
||||
base = 0x0000_0003_0000_0000;
|
||||
for region in &self.regions {
|
||||
let end = base.checked_add(size as u64).ok_or(MemoryError::Overflow)?;
|
||||
if end <= region.base {
|
||||
break;
|
||||
}
|
||||
let region_end = region.base + region.data.len() as u64;
|
||||
if base < region_end {
|
||||
base = region_end
|
||||
.checked_next_multiple_of(ALLOCATION_GRANULARITY)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.insert_region(base, size, permissions, &[], true)?;
|
||||
Ok(base)
|
||||
}
|
||||
|
||||
pub(crate) fn release_virtual_allocation(&mut self, base: u64) -> bool {
|
||||
let Some(index) = self
|
||||
.regions
|
||||
.iter()
|
||||
.position(|region| region.base == base && region.virtual_allocation)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
self.regions.remove(index);
|
||||
true
|
||||
}
|
||||
|
||||
/// Resolve `[address, address + len)` to `(region index, offset, length)` pieces.
|
||||
///
|
||||
/// An access may span adjacent regions, as it would span adjacent pages, but every
|
||||
/// byte must be mapped and every region must grant `required` (`None` bypasses
|
||||
/// permission checks for the loader). The whole range is checked before any byte
|
||||
/// is copied, so a failed access never partially reads or writes.
|
||||
fn resolve(
|
||||
&self,
|
||||
address: u64,
|
||||
len: usize,
|
||||
required: Option<&'static str>,
|
||||
) -> Result<Vec<(usize, usize, usize)>, MemoryError> {
|
||||
let end = address
|
||||
.checked_add(len as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
if len == 0 {
|
||||
return if self.regions.iter().any(|r| r.contains(address, 0)) {
|
||||
Ok(Vec::new())
|
||||
} else {
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
};
|
||||
}
|
||||
let mut pieces = Vec::new();
|
||||
let mut cursor = address;
|
||||
for (index, region) in self.regions.iter().enumerate() {
|
||||
let region_end = region.base + region.data.len() as u64;
|
||||
if region_end <= cursor {
|
||||
continue;
|
||||
}
|
||||
if region.base > cursor {
|
||||
break;
|
||||
}
|
||||
let permitted = match required {
|
||||
None => true,
|
||||
Some("read") => region.permissions.read,
|
||||
Some("write") => region.permissions.write,
|
||||
Some(_) => region.permissions.execute,
|
||||
};
|
||||
if let (false, Some(required)) = (permitted, required) {
|
||||
return Err(MemoryError::PermissionViolation { address, required });
|
||||
}
|
||||
let take = (end.min(region_end) - cursor) as usize;
|
||||
pieces.push((index, (cursor - region.base) as usize, take));
|
||||
cursor += take as u64;
|
||||
if cursor == end {
|
||||
return Ok(pieces);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
}
|
||||
|
||||
fn read_checked(
|
||||
&self,
|
||||
address: u64,
|
||||
dst: &mut [u8],
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
for (index, offset, take) in self.resolve(address, dst.len(), required)? {
|
||||
dst[done..done + take]
|
||||
.copy_from_slice(&self.regions[index].data[offset..offset + take]);
|
||||
done += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_checked(
|
||||
&mut self,
|
||||
address: u64,
|
||||
src: &[u8],
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
for (index, offset, take) in self.resolve(address, src.len(), required)? {
|
||||
self.regions[index].data[offset..offset + take]
|
||||
.copy_from_slice(&src[done..done + take]);
|
||||
done += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, src.len()) {
|
||||
if !region.permissions.write {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "write",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + src.len()].copy_from_slice(src);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.write_checked(address, src, Some("write"))
|
||||
}
|
||||
|
||||
/// Read raw bytes from guest memory at the specified address, checking permissions.
|
||||
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, dst.len()) {
|
||||
if !region.permissions.read {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "read",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
dst.copy_from_slice(®ion.data[offset..offset + dst.len()]);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.read_checked(address, dst, Some("read"))
|
||||
}
|
||||
|
||||
/// Read an instruction byte from guest memory, verifying execute permission.
|
||||
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, 1) {
|
||||
if !region.permissions.execute {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "execute",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
return Ok(region.data[offset]);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
let mut buf = [0u8; 1];
|
||||
self.read_checked(address, &mut buf, Some("execute"))?;
|
||||
Ok(buf[0])
|
||||
}
|
||||
|
||||
/// Read a 64-bit integer (little endian) from guest memory.
|
||||
@@ -237,11 +331,23 @@ impl GuestMemory {
|
||||
Ok(u64::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Read a 64-bit integer ignoring region read permissions (e.g. loader/relocation phase).
|
||||
pub fn read_u64_bypass(&self, address: u64) -> Result<u64, MemoryError> {
|
||||
let mut buf = [0u8; 8];
|
||||
self.read_checked(address, &mut buf, None)?;
|
||||
Ok(u64::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Write a 64-bit integer (little endian) to guest memory.
|
||||
pub fn write_u64(&mut self, address: u64, value: u64) -> Result<(), MemoryError> {
|
||||
self.write_bytes(address, &value.to_le_bytes())
|
||||
}
|
||||
|
||||
/// Write a 64-bit integer ignoring region write permissions (e.g. loader/relocation phase).
|
||||
pub fn write_u64_bypass(&mut self, address: u64, value: u64) -> Result<(), MemoryError> {
|
||||
self.write_checked(address, &value.to_le_bytes(), None)
|
||||
}
|
||||
|
||||
/// Read a 32-bit integer (little endian) from guest memory.
|
||||
pub fn read_u32(&self, address: u64) -> Result<u32, MemoryError> {
|
||||
let mut buf = [0u8; 4];
|
||||
@@ -253,4 +359,33 @@ impl GuestMemory {
|
||||
pub fn write_u32(&mut self, address: u64, value: u32) -> Result<(), MemoryError> {
|
||||
self.write_bytes(address, &value.to_le_bytes())
|
||||
}
|
||||
|
||||
/// Write a 32-bit integer ignoring region write permissions (e.g. loader/relocation phase).
|
||||
pub fn write_u32_bypass(&mut self, address: u64, value: u32) -> Result<(), MemoryError> {
|
||||
self.write_checked(address, &value.to_le_bytes(), None)
|
||||
}
|
||||
|
||||
/// Read a single byte from guest memory.
|
||||
pub fn read_u8(&self, address: u64) -> Result<u8, MemoryError> {
|
||||
let mut buf = [0u8; 1];
|
||||
self.read_bytes(address, &mut buf)?;
|
||||
Ok(buf[0])
|
||||
}
|
||||
|
||||
/// Write a single byte to guest memory.
|
||||
pub fn write_u8(&mut self, address: u64, value: u8) -> Result<(), MemoryError> {
|
||||
self.write_bytes(address, &[value])
|
||||
}
|
||||
|
||||
/// Read a 16-bit little-endian integer from guest memory.
|
||||
pub fn read_u16(&self, address: u64) -> Result<u16, MemoryError> {
|
||||
let mut buf = [0u8; 2];
|
||||
self.read_bytes(address, &mut buf)?;
|
||||
Ok(u16::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Write a 16-bit little-endian integer to guest memory.
|
||||
pub fn write_u16(&mut self, address: u64, value: u16) -> Result<(), MemoryError> {
|
||||
self.write_bytes(address, &value.to_le_bytes())
|
||||
}
|
||||
}
|
||||
+130
-51
@@ -83,6 +83,7 @@ pub struct LoadedImage {
|
||||
}
|
||||
|
||||
// Windows PE Characteristic Constants
|
||||
pub const IMAGE_SCN_CNT_CODE: u32 = 0x00000020;
|
||||
pub const IMAGE_SCN_MEM_EXECUTE: u32 = 0x20000000;
|
||||
pub const IMAGE_SCN_MEM_READ: u32 = 0x40000000;
|
||||
pub const IMAGE_SCN_MEM_WRITE: u32 = 0x80000000;
|
||||
@@ -90,6 +91,20 @@ pub const IMAGE_SCN_MEM_WRITE: u32 = 0x80000000;
|
||||
// Standard Constants
|
||||
pub const IMAGE_FILE_MACHINE_AMD64: u16 = 0x8664;
|
||||
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.
|
||||
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
|
||||
|
||||
fn read_u16(bytes: &[u8], at: usize) -> u16 {
|
||||
u16::from_le_bytes([bytes[at], bytes[at + 1]])
|
||||
}
|
||||
|
||||
fn read_u32(bytes: &[u8], at: usize) -> u32 {
|
||||
u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
|
||||
}
|
||||
|
||||
impl ParsedPe {
|
||||
/// Parse PE32+ headers from an in-memory byte slice.
|
||||
@@ -104,80 +119,85 @@ impl ParsedPe {
|
||||
}
|
||||
|
||||
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
if bytes.len() < e_lfanew + 24 {
|
||||
let coff_offset = e_lfanew.checked_add(4).ok_or(PeError::TooSmall)?;
|
||||
if bytes.len() < coff_offset.checked_add(20).ok_or(PeError::TooSmall)? {
|
||||
return Err(PeError::TooSmall);
|
||||
}
|
||||
|
||||
// 2. PE Signature
|
||||
if &bytes[e_lfanew..e_lfanew + 4] != b"PE\0\0" {
|
||||
if &bytes[e_lfanew..coff_offset] != b"PE\0\0" {
|
||||
return Err(PeError::InvalidPeSignature);
|
||||
}
|
||||
|
||||
// 3. COFF File Header
|
||||
let coff_offset = e_lfanew + 4;
|
||||
let machine = u16::from_le_bytes(bytes[coff_offset..coff_offset + 2].try_into().unwrap());
|
||||
let machine = read_u16(bytes, coff_offset);
|
||||
if machine != IMAGE_FILE_MACHINE_AMD64 {
|
||||
return Err(PeError::UnsupportedMachine(machine));
|
||||
}
|
||||
let number_of_sections = read_u16(bytes, coff_offset + 2);
|
||||
let time_date_stamp = read_u32(bytes, coff_offset + 4);
|
||||
let size_of_optional_header = usize::from(read_u16(bytes, coff_offset + 16));
|
||||
|
||||
let number_of_sections =
|
||||
u16::from_le_bytes(bytes[coff_offset + 2..coff_offset + 4].try_into().unwrap());
|
||||
let time_date_stamp =
|
||||
u32::from_le_bytes(bytes[coff_offset + 4..coff_offset + 8].try_into().unwrap());
|
||||
let size_of_optional_header = u16::from_le_bytes(
|
||||
bytes[coff_offset + 16..coff_offset + 18]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
) as usize;
|
||||
|
||||
// 4. Optional Header (PE32+ is required)
|
||||
// 4. Optional Header (PE32+ is required). The fixed PE32+ fields end at
|
||||
// NumberOfRvaAndSizes (offset 108, 4 bytes); a shorter header is malformed.
|
||||
let opt_offset = coff_offset + 20;
|
||||
if bytes.len() < opt_offset + size_of_optional_header {
|
||||
let section_table_offset = opt_offset + size_of_optional_header;
|
||||
if bytes.len() < opt_offset + 2 {
|
||||
return Err(PeError::TooSmall);
|
||||
}
|
||||
|
||||
let magic = u16::from_le_bytes(bytes[opt_offset..opt_offset + 2].try_into().unwrap());
|
||||
let magic = read_u16(bytes, opt_offset);
|
||||
if magic != PE32_PLUS_MAGIC {
|
||||
return Err(PeError::InvalidMagic(magic));
|
||||
}
|
||||
if size_of_optional_header < PE32_PLUS_MIN_OPTIONAL_HEADER
|
||||
|| bytes.len() < section_table_offset
|
||||
{
|
||||
return Err(PeError::TooSmall);
|
||||
}
|
||||
|
||||
let entry_point_rva =
|
||||
u32::from_le_bytes(bytes[opt_offset + 16..opt_offset + 20].try_into().unwrap());
|
||||
let entry_point_rva = read_u32(bytes, opt_offset + 16);
|
||||
let image_base =
|
||||
u64::from_le_bytes(bytes[opt_offset + 24..opt_offset + 32].try_into().unwrap());
|
||||
let section_alignment =
|
||||
u32::from_le_bytes(bytes[opt_offset + 32..opt_offset + 36].try_into().unwrap());
|
||||
let file_alignment =
|
||||
u32::from_le_bytes(bytes[opt_offset + 36..opt_offset + 40].try_into().unwrap());
|
||||
let size_of_image =
|
||||
u32::from_le_bytes(bytes[opt_offset + 56..opt_offset + 60].try_into().unwrap());
|
||||
let size_of_headers =
|
||||
u32::from_le_bytes(bytes[opt_offset + 60..opt_offset + 64].try_into().unwrap());
|
||||
let section_alignment = read_u32(bytes, opt_offset + 32);
|
||||
let file_alignment = read_u32(bytes, opt_offset + 36);
|
||||
let size_of_image = read_u32(bytes, opt_offset + 56);
|
||||
let size_of_headers = read_u32(bytes, opt_offset + 60);
|
||||
|
||||
// 5. Section Headers
|
||||
let mut sections = Vec::with_capacity(number_of_sections as usize);
|
||||
let section_table_offset = opt_offset + size_of_optional_header;
|
||||
let section_header_size = 40;
|
||||
|
||||
if bytes.len() < section_table_offset + (number_of_sections as usize * section_header_size)
|
||||
{
|
||||
let table_end = usize::from(number_of_sections)
|
||||
.checked_mul(SECTION_HEADER_SIZE)
|
||||
.and_then(|len| section_table_offset.checked_add(len))
|
||||
.ok_or(PeError::InvalidSectionHeaders)?;
|
||||
if bytes.len() < table_end {
|
||||
return Err(PeError::InvalidSectionHeaders);
|
||||
}
|
||||
|
||||
for i in 0..number_of_sections as usize {
|
||||
let offset = section_table_offset + i * section_header_size;
|
||||
let sec_bytes = &bytes[offset..offset + section_header_size];
|
||||
|
||||
let mut sections = Vec::with_capacity(usize::from(number_of_sections));
|
||||
for sec_bytes in bytes[section_table_offset..table_end]
|
||||
.as_chunks::<SECTION_HEADER_SIZE>()
|
||||
.0
|
||||
{
|
||||
// Section name (up to 8 bytes UTF-8 or null-padded ASCII)
|
||||
let name_raw = &sec_bytes[0..8];
|
||||
let name_len = name_raw.iter().position(|&b| b == 0).unwrap_or(8);
|
||||
let name = String::from_utf8_lossy(&name_raw[..name_len]).into_owned();
|
||||
|
||||
let virtual_size = u32::from_le_bytes(sec_bytes[8..12].try_into().unwrap());
|
||||
let virtual_address = u32::from_le_bytes(sec_bytes[12..16].try_into().unwrap());
|
||||
let raw_data_size = u32::from_le_bytes(sec_bytes[16..20].try_into().unwrap());
|
||||
let raw_data_ptr = u32::from_le_bytes(sec_bytes[20..24].try_into().unwrap());
|
||||
let characteristics = u32::from_le_bytes(sec_bytes[36..40].try_into().unwrap());
|
||||
let virtual_size = read_u32(sec_bytes, 8);
|
||||
let virtual_address = read_u32(sec_bytes, 12);
|
||||
let raw_data_size = read_u32(sec_bytes, 16);
|
||||
let raw_data_ptr = read_u32(sec_bytes, 20);
|
||||
let characteristics = read_u32(sec_bytes, 36);
|
||||
|
||||
// The mapped range must fit in the 32-bit RVA space, and raw data must be in the file.
|
||||
virtual_address
|
||||
.checked_add(virtual_size.max(raw_data_size))
|
||||
.ok_or(PeError::InvalidSectionHeaders)?;
|
||||
if raw_data_size > 0 {
|
||||
let raw_end = u64::from(raw_data_ptr) + u64::from(raw_data_size);
|
||||
if raw_end > bytes.len() as u64 {
|
||||
return Err(PeError::InvalidSectionHeaders);
|
||||
}
|
||||
}
|
||||
|
||||
let permissions = MemoryPermissions {
|
||||
read: (characteristics & IMAGE_SCN_MEM_READ) != 0,
|
||||
@@ -196,6 +216,32 @@ impl ParsedPe {
|
||||
});
|
||||
}
|
||||
|
||||
// Mapped section ranges must not overlap. Zero-sized sections map nothing.
|
||||
let mut ranges: Vec<(u32, u32)> = sections
|
||||
.iter()
|
||||
.map(|s| {
|
||||
(
|
||||
s.virtual_address,
|
||||
s.virtual_address + s.virtual_size.max(s.raw_data_size),
|
||||
)
|
||||
})
|
||||
.filter(|(start, end)| start < end)
|
||||
.collect();
|
||||
ranges.sort_unstable();
|
||||
if ranges.windows(2).any(|w| w[1].0 < w[0].1) {
|
||||
return Err(PeError::InvalidSectionHeaders);
|
||||
}
|
||||
|
||||
// The entry point must lie inside an executable section.
|
||||
let entry_ok = sections.iter().any(|s| {
|
||||
s.permissions.execute
|
||||
&& entry_point_rva >= s.virtual_address
|
||||
&& entry_point_rva - s.virtual_address < s.virtual_size.max(s.raw_data_size)
|
||||
});
|
||||
if !entry_ok {
|
||||
return Err(PeError::InvalidEntryPoint);
|
||||
}
|
||||
|
||||
Ok(ParsedPe {
|
||||
machine,
|
||||
number_of_sections,
|
||||
@@ -210,12 +256,43 @@ impl ParsedPe {
|
||||
})
|
||||
}
|
||||
|
||||
/// Translate a Relative Virtual Address (RVA) to a raw file offset.
|
||||
pub fn rva_to_file_offset(&self, rva: u32) -> Option<usize> {
|
||||
for sec in &self.sections {
|
||||
// Sections are public and may not come from `parse`, so stay checked here.
|
||||
let Some(diff) = rva.checked_sub(sec.virtual_address) else {
|
||||
continue;
|
||||
};
|
||||
if diff < sec.virtual_size.max(sec.raw_data_size) && diff < sec.raw_data_size {
|
||||
return (sec.raw_data_ptr as usize).checked_add(diff as usize);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Load this parsed PE into a fresh `GuestMemory` instance, mapping 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
|
||||
.sections
|
||||
.iter()
|
||||
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
|
||||
.sum();
|
||||
if mapped > MAX_MAPPED_IMAGE_BYTES {
|
||||
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
|
||||
}
|
||||
|
||||
let mut memory = GuestMemory::new();
|
||||
|
||||
for sec in &self.sections {
|
||||
let base_addr = self.image_base + sec.virtual_address as u64;
|
||||
let base_addr = base
|
||||
.checked_add(u64::from(sec.virtual_address))
|
||||
.ok_or(PeError::InvalidSectionHeaders)?;
|
||||
let map_size = std::cmp::max(sec.virtual_size, sec.raw_data_size) as usize;
|
||||
if map_size == 0 {
|
||||
continue;
|
||||
@@ -223,12 +300,12 @@ impl ParsedPe {
|
||||
|
||||
let initial_data = if sec.raw_data_size > 0 && sec.raw_data_ptr > 0 {
|
||||
let start = sec.raw_data_ptr as usize;
|
||||
let end = start + sec.raw_data_size as usize;
|
||||
if end <= bytes.len() {
|
||||
&bytes[start..end]
|
||||
} else {
|
||||
&[]
|
||||
}
|
||||
let end = start
|
||||
.checked_add(sec.raw_data_size as usize)
|
||||
.ok_or(PeError::InvalidSectionHeaders)?;
|
||||
bytes
|
||||
.get(start..end)
|
||||
.ok_or(PeError::InvalidSectionHeaders)?
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
@@ -238,7 +315,9 @@ impl ParsedPe {
|
||||
.map_err(PeError::SectionMappingError)?;
|
||||
}
|
||||
|
||||
let entry_point = self.image_base + self.entry_point_rva as u64;
|
||||
let entry_point = base
|
||||
.checked_add(u64::from(self.entry_point_rva))
|
||||
.ok_or(PeError::InvalidEntryPoint)?;
|
||||
|
||||
Ok(LoadedImage {
|
||||
pe: self.clone(),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,276 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! PE32+ Base Relocation Engine for Xenora X15.
|
||||
//!
|
||||
//! Applies `IMAGE_REL_BASED_DIR64` relocations to guest virtual memory when an image
|
||||
//! is loaded at a base address different from its preferred PE `image_base`.
|
||||
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use crate::pe::ParsedPe;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
|
||||
/// Type of base relocation entry.
|
||||
pub const IMAGE_REL_BASED_ABSOLUTE: u8 = 0;
|
||||
pub const IMAGE_REL_BASED_DIR64: u8 = 10;
|
||||
|
||||
/// Errors that can occur during base relocation parsing or application.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum RelocationError {
|
||||
DirectoryOutOfBounds { rva: u32, size: u32 },
|
||||
MalformedBlockHeader { offset: usize },
|
||||
BlockSizeOutOfBounds { block_size: u32, max_size: usize },
|
||||
UnsupportedRelocationType(u8),
|
||||
TargetOutOfBounds { target_va: u64 },
|
||||
Memory(MemoryError),
|
||||
ArithmeticOverflow,
|
||||
}
|
||||
|
||||
impl fmt::Display for RelocationError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::DirectoryOutOfBounds { rva, size } => {
|
||||
write!(
|
||||
f,
|
||||
"relocation directory (RVA 0x{rva:08x}, size 0x{size:x}) is out of bounds"
|
||||
)
|
||||
}
|
||||
Self::MalformedBlockHeader { offset } => {
|
||||
write!(f, "malformed relocation block header at offset {offset}")
|
||||
}
|
||||
Self::BlockSizeOutOfBounds {
|
||||
block_size,
|
||||
max_size,
|
||||
} => {
|
||||
write!(
|
||||
f,
|
||||
"relocation block size 0x{block_size:x} exceeds boundary {max_size}"
|
||||
)
|
||||
}
|
||||
Self::UnsupportedRelocationType(t) => {
|
||||
write!(f, "unsupported base relocation type: {t}")
|
||||
}
|
||||
Self::TargetOutOfBounds { target_va } => {
|
||||
write!(
|
||||
f,
|
||||
"relocation target VA 0x{target_va:016x} is outside mapped memory"
|
||||
)
|
||||
}
|
||||
Self::Memory(e) => write!(f, "guest memory fault during relocation: {e}"),
|
||||
Self::ArithmeticOverflow => write!(f, "arithmetic overflow in relocation computation"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RelocationError {}
|
||||
|
||||
impl From<MemoryError> for RelocationError {
|
||||
fn from(e: MemoryError) -> Self {
|
||||
Self::Memory(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Statistics and counters from applying base relocations.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct RelocationReport {
|
||||
pub total_entries: usize,
|
||||
pub applied_dir64: usize,
|
||||
pub skipped_absolute: usize,
|
||||
pub type_counts: BTreeMap<u8, usize>,
|
||||
pub delta: i64,
|
||||
}
|
||||
|
||||
/// Applies PE base relocations to `GuestMemory` if the loaded image base differs from preferred.
|
||||
pub fn apply_relocations(
|
||||
pe: &ParsedPe,
|
||||
bytes: &[u8],
|
||||
loaded_base: u64,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<RelocationReport, RelocationError> {
|
||||
let mut report = RelocationReport::default();
|
||||
|
||||
let delta = (loaded_base as i128) - (pe.image_base as i128);
|
||||
if delta == 0 {
|
||||
// Zero delta: image is loaded at preferred base, no DIR64 fixup needed
|
||||
return Ok(report);
|
||||
}
|
||||
if delta > (i64::MAX as i128) || delta < (i64::MIN as i128) {
|
||||
return Err(RelocationError::ArithmeticOverflow);
|
||||
}
|
||||
let delta_i64 = delta as i64;
|
||||
report.delta = delta_i64;
|
||||
|
||||
// Locate relocation directory RVA and size from Optional Header data directory #5
|
||||
let reloc_dir = find_reloc_directory(bytes, pe)?;
|
||||
let Some((reloc_rva, reloc_size)) = reloc_dir else {
|
||||
return Ok(report);
|
||||
};
|
||||
|
||||
if reloc_size == 0 {
|
||||
return Ok(report);
|
||||
}
|
||||
|
||||
let reloc_file_offset =
|
||||
pe.rva_to_file_offset(reloc_rva)
|
||||
.ok_or(RelocationError::DirectoryOutOfBounds {
|
||||
rva: reloc_rva,
|
||||
size: reloc_size,
|
||||
})?;
|
||||
|
||||
if reloc_file_offset
|
||||
.checked_add(reloc_size as usize)
|
||||
.is_none_or(|end| end > bytes.len())
|
||||
{
|
||||
return Err(RelocationError::DirectoryOutOfBounds {
|
||||
rva: reloc_rva,
|
||||
size: reloc_size,
|
||||
});
|
||||
}
|
||||
|
||||
let mut read_bytes = 0usize;
|
||||
let max_read = reloc_size as usize;
|
||||
|
||||
while read_bytes < max_read {
|
||||
// A partial block header after the last block is malformed, not padding.
|
||||
if max_read - read_bytes < 8 {
|
||||
return Err(RelocationError::MalformedBlockHeader {
|
||||
offset: reloc_file_offset + read_bytes,
|
||||
});
|
||||
}
|
||||
let block_start = reloc_file_offset + read_bytes;
|
||||
let page_rva = u32::from_le_bytes(bytes[block_start..block_start + 4].try_into().unwrap());
|
||||
let block_size =
|
||||
u32::from_le_bytes(bytes[block_start + 4..block_start + 8].try_into().unwrap());
|
||||
|
||||
// A block is an 8-byte header followed by whole 2-byte entries.
|
||||
if block_size < 8 || block_size % 2 != 0 {
|
||||
return Err(RelocationError::MalformedBlockHeader {
|
||||
offset: block_start,
|
||||
});
|
||||
}
|
||||
if read_bytes + (block_size as usize) > max_read {
|
||||
return Err(RelocationError::BlockSizeOutOfBounds {
|
||||
block_size,
|
||||
max_size: max_read - read_bytes,
|
||||
});
|
||||
}
|
||||
|
||||
let num_entries = (block_size as usize - 8) / 2;
|
||||
for i in 0..num_entries {
|
||||
let entry_offset = block_start + 8 + i * 2;
|
||||
let entry_val =
|
||||
u16::from_le_bytes(bytes[entry_offset..entry_offset + 2].try_into().unwrap());
|
||||
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 {
|
||||
IMAGE_REL_BASED_ABSOLUTE => {
|
||||
// Padding entry, ignore
|
||||
report.skipped_absolute += 1;
|
||||
}
|
||||
IMAGE_REL_BASED_DIR64 => {
|
||||
// Target VA = loaded_base + page_rva + offset_in_page
|
||||
let target_rva = page_rva
|
||||
.checked_add(offset_in_page)
|
||||
.ok_or(RelocationError::ArithmeticOverflow)?;
|
||||
// The 8-byte target must lie inside the image, not in other mapped memory.
|
||||
if target_rva
|
||||
.checked_add(8)
|
||||
.is_none_or(|end| end > pe.size_of_image)
|
||||
{
|
||||
return Err(RelocationError::TargetOutOfBounds {
|
||||
target_va: loaded_base.wrapping_add(u64::from(target_rva)),
|
||||
});
|
||||
}
|
||||
let target_va = loaded_base
|
||||
.checked_add(target_rva as u64)
|
||||
.ok_or(RelocationError::ArithmeticOverflow)?;
|
||||
|
||||
// Read current 64-bit value at target_va
|
||||
// Use write_u64_bypass / read_u64_bypass if section is read-only
|
||||
let orig_val = memory.read_u64_bypass(target_va).map_err(|e| match e {
|
||||
MemoryError::UnmappedAddress(_) => {
|
||||
RelocationError::TargetOutOfBounds { target_va }
|
||||
}
|
||||
other => RelocationError::Memory(other),
|
||||
})?;
|
||||
|
||||
// Rebase: new_val = orig_val + delta_i64
|
||||
let new_val = ((orig_val as i128) + (delta_i64 as i128)) as u64;
|
||||
|
||||
memory
|
||||
.write_u64_bypass(target_va, new_val)
|
||||
.map_err(|e| match e {
|
||||
MemoryError::UnmappedAddress(_) => {
|
||||
RelocationError::TargetOutOfBounds { target_va }
|
||||
}
|
||||
other => RelocationError::Memory(other),
|
||||
})?;
|
||||
|
||||
report.applied_dir64 += 1;
|
||||
}
|
||||
other => {
|
||||
return Err(RelocationError::UnsupportedRelocationType(other));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
read_bytes += block_size as usize;
|
||||
}
|
||||
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
fn find_reloc_directory(
|
||||
bytes: &[u8],
|
||||
_pe: &ParsedPe,
|
||||
) -> Result<Option<(u32, u32)>, RelocationError> {
|
||||
if bytes.len() < 0x40 {
|
||||
return Ok(None);
|
||||
}
|
||||
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
let coff_offset = e_lfanew + 4;
|
||||
let opt_offset = coff_offset + 20;
|
||||
if bytes.len() < coff_offset + 18 {
|
||||
return Ok(None);
|
||||
}
|
||||
let size_of_opt = u16::from_le_bytes(
|
||||
bytes[coff_offset + 16..coff_offset + 18]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
) as usize;
|
||||
|
||||
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header).
|
||||
// It exists only when NumberOfRvaAndSizes (offset 108) covers index 5.
|
||||
if size_of_opt < 160 || bytes.len() < opt_offset + 160 {
|
||||
return Ok(None);
|
||||
}
|
||||
let number_of_rva_and_sizes = u32::from_le_bytes(
|
||||
bytes[opt_offset + 108..opt_offset + 112]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
if number_of_rva_and_sizes < 6 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let reloc_rva = u32::from_le_bytes(
|
||||
bytes[opt_offset + 152..opt_offset + 156]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
let reloc_size = u32::from_le_bytes(
|
||||
bytes[opt_offset + 156..opt_offset + 160]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
if reloc_rva == 0 || reloc_size == 0 {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some((reloc_rva, reloc_size)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,584 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Standard Windows and Xbox Scarlett Host Services Implementation for Xenora X15.
|
||||
//!
|
||||
//! Provides verifiable guest implementations of Windows NT and Xbox Scarlett APIs:
|
||||
//! - Time: `GetSystemTimeAsFileTime` (injected deterministic clock or real UTC)
|
||||
//! - Process and thread identity and guest process priority boost policy
|
||||
//! - Error slots: `GetLastError`, `SetLastError`
|
||||
//! - Virtual memory: `VirtualAlloc`, `VirtualFree`
|
||||
//! - Xbox physical memory: `XMemAlloc`, `XMemFree`
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{ALLOCATION_GRANULARITY, GuestMemory, MemoryError, MemoryPermissions};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
const CURRENT_PROCESS: u64 = u64::MAX;
|
||||
const CURRENT_THREAD: u64 = u64::MAX - 1;
|
||||
const ERROR_ACCESS_DENIED: u32 = 5;
|
||||
const ERROR_INVALID_HANDLE: u32 = 6;
|
||||
const ERROR_NOT_ENOUGH_MEMORY: u32 = 8;
|
||||
const ERROR_NOT_SUPPORTED: u32 = 50;
|
||||
const ERROR_INVALID_PARAMETER: u32 = 87;
|
||||
const ERROR_INVALID_ADDRESS: u32 = 487;
|
||||
const THREAD_QUERY_RIGHTS: u32 = 0x0040 | 0x0800;
|
||||
const THREAD_SET_RIGHTS: u32 = 0x0020 | 0x0400;
|
||||
const THREAD_SUPPORTED_RIGHTS: u32 = THREAD_QUERY_RIGHTS | THREAD_SET_RIGHTS | 0x0010_0000;
|
||||
const THREAD_PRIORITY_ERROR_RETURN: u64 = 0x7fff_ffff;
|
||||
const MAX_THREAD_HANDLES: usize = 1024;
|
||||
const PAGE_SIZE: u64 = 4096;
|
||||
const MEM_COMMIT_RESERVE: u32 = 0x3000;
|
||||
const MEM_RELEASE: u32 = 0x8000;
|
||||
const ERROR_NOACCESS: u32 = 998;
|
||||
const KERNEL32: &str = "kernel32.dll";
|
||||
const PROCESS_THREADS_V1: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
const PROCESS_THREADS_V2: &str = "api-ms-win-core-processthreads-l1-1-2.dll";
|
||||
|
||||
/// Clock trait for injecting deterministic time in tests or host time in production.
|
||||
pub trait Clock: Send + Sync {
|
||||
/// Return Windows 100-nanosecond intervals since January 1, 1601 (UTC).
|
||||
fn now_filetime(&self) -> u64;
|
||||
}
|
||||
|
||||
/// Deterministic test clock.
|
||||
pub struct MockClock {
|
||||
current: AtomicU64,
|
||||
}
|
||||
|
||||
impl MockClock {
|
||||
pub fn new(initial_filetime: u64) -> Self {
|
||||
Self {
|
||||
current: AtomicU64::new(initial_filetime),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn advance(&self, intervals: u64) {
|
||||
self.current.fetch_add(intervals, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock for MockClock {
|
||||
fn now_filetime(&self) -> u64 {
|
||||
self.current.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
/// Host system UTC clock.
|
||||
pub struct SystemClock;
|
||||
|
||||
impl Clock for SystemClock {
|
||||
fn now_filetime(&self) -> u64 {
|
||||
// Windows FILETIME epoch is 1601-01-01 00:00:00 UTC.
|
||||
// Unix epoch is 1970-01-01 00:00:00 UTC (difference = 11,644,473,600 seconds).
|
||||
const WINDOWS_TICK: u64 = 10_000_000;
|
||||
const SEC_TO_UNIX_EPOCH: u64 = 11_644_473_600;
|
||||
let now = std::time::SystemTime::now();
|
||||
let dur = now
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default();
|
||||
let unix_secs = dur.as_secs();
|
||||
let nanos = dur.subsec_nanos() as u64;
|
||||
let windows_secs = unix_secs + SEC_TO_UNIX_EPOCH;
|
||||
windows_secs * WINDOWS_TICK + (nanos / 100)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ThreadState {
|
||||
priority: i32,
|
||||
last_handle: u64,
|
||||
handles: BTreeMap<u64, u32>,
|
||||
}
|
||||
|
||||
impl ThreadState {
|
||||
fn check_access(&self, handle: u64, required: u32) -> Result<(), u32> {
|
||||
if handle == CURRENT_THREAD {
|
||||
return Ok(());
|
||||
}
|
||||
match self.handles.get(&handle) {
|
||||
Some(access) if access & required != 0 => Ok(()),
|
||||
Some(_) => Err(ERROR_ACCESS_DENIED),
|
||||
None => Err(ERROR_INVALID_HANDLE),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// State container for runtime services.
|
||||
pub struct ServicesState {
|
||||
pub clock: Arc<dyn Clock>,
|
||||
pub process_id: u32,
|
||||
priority_boost_disabled: AtomicBool,
|
||||
pub thread_id: u32,
|
||||
thread: Mutex<ThreadState>,
|
||||
pub last_error: AtomicU32,
|
||||
pub next_alloc_addr: AtomicU64,
|
||||
pub graphics: Arc<Mutex<crate::graphics::GraphicsContext>>,
|
||||
}
|
||||
|
||||
impl ServicesState {
|
||||
pub fn new(clock: Arc<dyn Clock>) -> Self {
|
||||
Self {
|
||||
clock,
|
||||
priority_boost_disabled: AtomicBool::new(false),
|
||||
process_id: 0x4100, // Synthetic process ID
|
||||
thread_id: 0x4104, // Synthetic main thread ID
|
||||
thread: Mutex::new(ThreadState::default()),
|
||||
last_error: AtomicU32::new(0),
|
||||
next_alloc_addr: AtomicU64::new(0x0000_0002_0000_0000), // 8GB guest heap
|
||||
graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())),
|
||||
}
|
||||
}
|
||||
/// The scheduling policy recorded for the synthetic process.
|
||||
pub fn priority_boost_disabled(&self) -> bool {
|
||||
self.priority_boost_disabled.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn fail(&self, error: u32, return_value: u64) -> Result<u64, ExitReason> {
|
||||
self.last_error.store(error, Ordering::SeqCst);
|
||||
Ok(return_value)
|
||||
}
|
||||
|
||||
fn is_current_process(&self, handle: u64) -> bool {
|
||||
if handle == CURRENT_PROCESS {
|
||||
return true;
|
||||
}
|
||||
self.last_error
|
||||
.store(ERROR_INVALID_HANDLE, Ordering::SeqCst);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Register standard Windows core and Xbox memory services into the registry.
|
||||
pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<ServicesState>) {
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "SetProcessPriorityBoost", move |args, _, mem| {
|
||||
if !s.is_current_process(args.get(0, mem).map_err(ExitReason::MemoryFault)?) {
|
||||
return Ok(0);
|
||||
}
|
||||
let disable = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
s.priority_boost_disabled
|
||||
.store(disable != 0, Ordering::SeqCst);
|
||||
Ok(1)
|
||||
});
|
||||
registry.alias(PROCESS_THREADS_V2, KERNEL32, "SetProcessPriorityBoost");
|
||||
|
||||
registry.set_status(KERNEL32, "SetProcessPriorityBoost", ServiceStatus::Partial);
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "GetProcessPriorityBoost", move |args, _, mem| {
|
||||
if !s.is_current_process(args.get(0, mem).map_err(ExitReason::MemoryFault)?) {
|
||||
return Ok(0);
|
||||
}
|
||||
let output = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if mem
|
||||
.write_u32(output, u32::from(s.priority_boost_disabled()))
|
||||
.is_err()
|
||||
{
|
||||
s.last_error.store(ERROR_NOACCESS, Ordering::SeqCst);
|
||||
return Ok(0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
registry.alias(PROCESS_THREADS_V2, KERNEL32, "GetProcessPriorityBoost");
|
||||
registry.set_status(KERNEL32, "GetProcessPriorityBoost", ServiceStatus::Partial);
|
||||
|
||||
registry.register(KERNEL32, "GetCurrentProcess", |_, _, _| Ok(CURRENT_PROCESS));
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentProcess");
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "GetProcessId", move |args, _, mem| {
|
||||
if !s.is_current_process(args.get(0, mem).map_err(ExitReason::MemoryFault)?) {
|
||||
return Ok(0);
|
||||
}
|
||||
Ok(u64::from(s.process_id))
|
||||
});
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetProcessId");
|
||||
registry.set_status(KERNEL32, "GetProcessId", ServiceStatus::Partial);
|
||||
|
||||
registry.register(KERNEL32, "GetCurrentThread", |_, _, _| Ok(CURRENT_THREAD));
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentThread");
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "OpenThread", move |args, _, mem| {
|
||||
let access = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let inherit = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let id = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
if id != s.thread_id {
|
||||
return s.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if inherit != 0 || access & !THREAD_SUPPORTED_RIGHTS != 0 {
|
||||
return s.fail(ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let mut thread = s.thread.lock().expect("guest thread state");
|
||||
let Some(handle) = thread
|
||||
.last_handle
|
||||
.checked_add(4)
|
||||
.filter(|_| thread.handles.len() < MAX_THREAD_HANDLES)
|
||||
else {
|
||||
return s.fail(ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
thread.handles.insert(handle, access);
|
||||
thread.last_handle = handle;
|
||||
Ok(handle)
|
||||
});
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "GetThreadPriority", move |args, _, mem| {
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let thread = s.thread.lock().expect("guest thread state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
|
||||
return s.fail(error, THREAD_PRIORITY_ERROR_RETURN);
|
||||
}
|
||||
Ok(u64::from(thread.priority as u32))
|
||||
});
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "SetThreadPriority", move |args, _, mem| {
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let priority = args.get(1, mem).map_err(ExitReason::MemoryFault)? as i32;
|
||||
let mut thread = s.thread.lock().expect("guest thread state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_SET_RIGHTS) {
|
||||
return s.fail(error, 0);
|
||||
}
|
||||
if matches!(priority, 0x0001_0000 | 0x0002_0000) {
|
||||
return s.fail(ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
if !matches!(priority, -15 | -2..=2 | 15) {
|
||||
return s.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
thread.priority = priority;
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for symbol in ["OpenThread", "GetThreadPriority", "SetThreadPriority"] {
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "CloseHandle", move |args, _, mem| {
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if matches!(handle, CURRENT_PROCESS | CURRENT_THREAD)
|
||||
|| s.thread
|
||||
.lock()
|
||||
.expect("guest thread state")
|
||||
.handles
|
||||
.remove(&handle)
|
||||
.is_some()
|
||||
{
|
||||
return Ok(1);
|
||||
}
|
||||
s.fail(ERROR_INVALID_HANDLE, 0)
|
||||
});
|
||||
registry.alias("api-ms-win-core-handle-l1-1-0.dll", KERNEL32, "CloseHandle");
|
||||
registry.set_status(KERNEL32, "CloseHandle", ServiceStatus::Partial);
|
||||
|
||||
// 1. GetSystemTimeAsFileTime(lpSystemTimeAsFileTime: *mut FILETIME)
|
||||
let s = state.clone();
|
||||
let handler = move |args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> {
|
||||
let ptr = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if ptr == 0 {
|
||||
s.last_error.store(87, Ordering::SeqCst); // ERROR_INVALID_PARAMETER
|
||||
return Ok(0);
|
||||
}
|
||||
let ft = s.clock.now_filetime();
|
||||
mem.write_u64(ptr, ft).map_err(ExitReason::MemoryFault)?;
|
||||
Ok(0)
|
||||
};
|
||||
registry.register(KERNEL32, "GetSystemTimeAsFileTime", handler);
|
||||
registry.alias(
|
||||
"api-ms-win-core-sysinfo-l1-1-0.dll",
|
||||
KERNEL32,
|
||||
"GetSystemTimeAsFileTime",
|
||||
);
|
||||
|
||||
// 2. GetCurrentProcessId() -> DWORD
|
||||
let s = state.clone();
|
||||
let handler = move |_args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
_mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> { Ok(s.process_id as u64) };
|
||||
registry.register(KERNEL32, "GetCurrentProcessId", handler);
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentProcessId");
|
||||
|
||||
// 3. GetCurrentThreadId() -> DWORD
|
||||
let s = state.clone();
|
||||
let handler = move |_args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
_mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> { Ok(s.thread_id as u64) };
|
||||
registry.register(KERNEL32, "GetCurrentThreadId", handler);
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentThreadId");
|
||||
|
||||
// 4. GetLastError() -> DWORD
|
||||
let s = state.clone();
|
||||
let handler =
|
||||
move |_args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
_mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> { Ok(s.last_error.load(Ordering::SeqCst) as u64) };
|
||||
registry.register(KERNEL32, "GetLastError", handler);
|
||||
registry.alias(
|
||||
"api-ms-win-core-errorhandling-l1-1-0.dll",
|
||||
KERNEL32,
|
||||
"GetLastError",
|
||||
);
|
||||
|
||||
// 5. SetLastError(dwErrCode: DWORD)
|
||||
let s = state.clone();
|
||||
let handler = move |args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> {
|
||||
let code = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
s.last_error.store(code, Ordering::SeqCst);
|
||||
Ok(0)
|
||||
};
|
||||
registry.register(KERNEL32, "SetLastError", handler);
|
||||
registry.alias(
|
||||
"api-ms-win-core-errorhandling-l1-1-0.dll",
|
||||
KERNEL32,
|
||||
"SetLastError",
|
||||
);
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "VirtualAlloc", move |args, _, mem| {
|
||||
let requested = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let size = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let allocation_type = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let protect = args.get(3, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
|
||||
if size == 0 {
|
||||
return s.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if allocation_type != MEM_COMMIT_RESERVE {
|
||||
return s.fail(ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
// Executable allocations require guest translation cache invalidation.
|
||||
let permissions = match protect {
|
||||
0x01 => MemoryPermissions::NO_ACCESS,
|
||||
0x02 => MemoryPermissions::READ_ONLY,
|
||||
0x04 => MemoryPermissions::READ_WRITE,
|
||||
_ => return s.fail(ERROR_INVALID_PARAMETER, 0),
|
||||
};
|
||||
let base = requested & !(ALLOCATION_GRANULARITY - 1);
|
||||
if requested != 0 && base == 0 {
|
||||
return s.fail(ERROR_INVALID_ADDRESS, 0);
|
||||
}
|
||||
let Some(size) = size
|
||||
.checked_add(requested - base)
|
||||
.and_then(|span| span.checked_next_multiple_of(PAGE_SIZE))
|
||||
.and_then(|span| usize::try_from(span).ok())
|
||||
else {
|
||||
return s.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
};
|
||||
|
||||
match mem.map_virtual_allocation(base, size, permissions) {
|
||||
Ok(address) => Ok(address),
|
||||
Err(MemoryError::OverlappingRegion { .. } | MemoryError::Overflow) => {
|
||||
s.fail(ERROR_INVALID_ADDRESS, 0)
|
||||
}
|
||||
Err(_) => s.fail(ERROR_NOT_ENOUGH_MEMORY, 0),
|
||||
}
|
||||
});
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "VirtualFree", move |args, _, mem| {
|
||||
let address = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let size = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let free_type = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
if free_type != MEM_RELEASE {
|
||||
return s.fail(ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
if size != 0 {
|
||||
return s.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if !mem.release_virtual_allocation(address) {
|
||||
return s.fail(ERROR_INVALID_ADDRESS, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for symbol in ["VirtualAlloc", "VirtualFree"] {
|
||||
registry.alias("api-ms-win-core-memory-l1-1-0.dll", KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
|
||||
// 8. XMemAlloc(dwSize, dwAllocAttributes) -> LPVOID (Xbox Scarlett allocator in xmem.dll)
|
||||
let s = state.clone();
|
||||
let handler = move |args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> {
|
||||
let size = args.get(0, mem).map_err(ExitReason::MemoryFault)? as usize;
|
||||
let _attr = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
|
||||
|
||||
if size == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let page_size = 4096;
|
||||
let aligned_size = (size + page_size - 1) & !(page_size - 1);
|
||||
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)
|
||||
};
|
||||
registry.register("xmem.dll", "XMemAlloc", handler);
|
||||
registry.set_status("xmem.dll", "XMemAlloc", ServiceStatus::Partial);
|
||||
|
||||
// 9. XMemFree(pAddress, dwAllocAttributes) -> VOID (Xbox Scarlett in xmem.dll)
|
||||
let handler = move |args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> {
|
||||
let _addr = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
Ok(0)
|
||||
};
|
||||
registry.register("xmem.dll", "XMemFree", handler);
|
||||
registry.set_status("xmem.dll", "XMemFree", ServiceStatus::Stub);
|
||||
|
||||
// 10. Synthetic Test Graphics Device Creation (xenora_fixture.dll)
|
||||
// Prototype graphics device creation for original integration fixtures.
|
||||
// In guest ABI: ppDevice is Arg 3 (R9). Writes generation-checked device handle.
|
||||
let s_gfx = state.graphics.clone();
|
||||
let handler = move |args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> {
|
||||
let pp_device = args.get(3, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if pp_device == 0 {
|
||||
return Ok(0x80070057); // E_INVALIDARG
|
||||
}
|
||||
let mut gfx = s_gfx
|
||||
.lock()
|
||||
.map_err(|_| ExitReason::MemoryFault(crate::memory::MemoryError::Overflow))?;
|
||||
match gfx.create_device() {
|
||||
Ok(handle) => {
|
||||
mem.write_u64(pp_device, handle.to_u64())
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
Ok(0) // S_OK
|
||||
}
|
||||
Err(_) => Ok(0x80004005), // E_FAIL
|
||||
}
|
||||
};
|
||||
registry.register("xenora_fixture.dll", "CreateGraphicsDevice", handler);
|
||||
registry.set_status(
|
||||
"xenora_fixture.dll",
|
||||
"CreateGraphicsDevice",
|
||||
ServiceStatus::Implemented,
|
||||
);
|
||||
|
||||
// 11. Synthetic Test Command Submission & Presentation (xenora_fixture.dll)
|
||||
// Prototype graphics submission service:
|
||||
// Arg 0 (RCX): Guest address of vertex buffer (12 x f32 coordinates)
|
||||
// Arg 1 (RDX): Clear color packed as RGBA u32 or pointer to 4 floats
|
||||
// Arg 2 (R8): Viewport dimensions (width in lower 32 bits, height in upper 32 bits)
|
||||
// Arg 3 (R9): Optional guest output pointer for readback status or frame index
|
||||
let s_gfx = state.graphics.clone();
|
||||
let handler = move |args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> {
|
||||
let vtx_addr = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if vtx_addr == 0 {
|
||||
return Ok(0x80070057); // E_INVALIDARG
|
||||
}
|
||||
let clear_raw = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let clear_color = [
|
||||
(clear_raw & 0xFF) as u8,
|
||||
((clear_raw >> 8) & 0xFF) as u8,
|
||||
((clear_raw >> 16) & 0xFF) as u8,
|
||||
((clear_raw >> 24) & 0xFF) as u8,
|
||||
];
|
||||
let dims_raw = args.get(2, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let width = (dims_raw as u32) as usize;
|
||||
let height = ((dims_raw >> 32) as u32) as usize;
|
||||
let (vp_w, vp_h) = if width > 0 && height > 0 {
|
||||
(width, height)
|
||||
} else {
|
||||
(4, 3)
|
||||
};
|
||||
|
||||
let mut gfx = s_gfx
|
||||
.lock()
|
||||
.map_err(|_| ExitReason::MemoryFault(crate::memory::MemoryError::Overflow))?;
|
||||
|
||||
// Build and execute guest command list through GraphicsContext
|
||||
let dev = gfx
|
||||
.create_device()
|
||||
.map_err(|_| ExitReason::MemoryFault(crate::memory::MemoryError::Overflow))?;
|
||||
let queue = gfx
|
||||
.create_command_queue(dev, crate::graphics::CommandListType::Direct)
|
||||
.map_err(|_| ExitReason::MemoryFault(crate::memory::MemoryError::Overflow))?;
|
||||
let alloc = gfx
|
||||
.create_command_allocator(dev, crate::graphics::CommandListType::Direct)
|
||||
.map_err(|_| ExitReason::MemoryFault(crate::memory::MemoryError::Overflow))?;
|
||||
let list = gfx
|
||||
.create_command_list(dev, alloc, crate::graphics::CommandListType::Direct)
|
||||
.map_err(|_| ExitReason::MemoryFault(crate::memory::MemoryError::Overflow))?;
|
||||
|
||||
let vb_desc = crate::graphics::ResourceDesc {
|
||||
dimension: crate::graphics::ResourceDimension::Buffer,
|
||||
width: 48,
|
||||
height: 1,
|
||||
depth_or_array_size: 1,
|
||||
mip_levels: 1,
|
||||
format_rgba8: false,
|
||||
};
|
||||
let vb = gfx
|
||||
.create_committed_resource(
|
||||
dev,
|
||||
vb_desc,
|
||||
crate::graphics::ResourceStates::VERTEX_AND_CONSTANT_BUFFER,
|
||||
Some(vtx_addr),
|
||||
)
|
||||
.map_err(|_| ExitReason::MemoryFault(crate::memory::MemoryError::Overflow))?;
|
||||
|
||||
gfx.cmd_set_viewport(list, vp_w, vp_h)
|
||||
.map_err(|_| ExitReason::MemoryFault(crate::memory::MemoryError::Overflow))?;
|
||||
gfx.cmd_set_render_targets(list, None, clear_color)
|
||||
.map_err(|_| ExitReason::MemoryFault(crate::memory::MemoryError::Overflow))?;
|
||||
gfx.cmd_set_vertex_buffer(list, vb, 0, 48)
|
||||
.map_err(|_| ExitReason::MemoryFault(crate::memory::MemoryError::Overflow))?;
|
||||
gfx.cmd_draw_instanced(list, 3, 1, 0, 0)
|
||||
.map_err(|_| ExitReason::MemoryFault(crate::memory::MemoryError::Overflow))?;
|
||||
gfx.close_command_list(list)
|
||||
.map_err(|_| ExitReason::MemoryFault(crate::memory::MemoryError::Overflow))?;
|
||||
|
||||
let outcome = gfx.execute_command_list(queue, list, mem).map_err(|e| {
|
||||
ExitReason::IllegalInstruction(match e {
|
||||
crate::graphics::GraphicsError::NativeMetalRequired => 0xFE,
|
||||
_ => 0xFF,
|
||||
})
|
||||
})?;
|
||||
|
||||
let pp_out = args.get(3, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if pp_out != 0 {
|
||||
mem.write_u64(pp_out, outcome.pixels.len() as u64)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
|
||||
Ok(0) // S_OK
|
||||
};
|
||||
registry.register("xenora_fixture.dll", "SubmitGuestDraw", handler);
|
||||
registry.set_status(
|
||||
"xenora_fixture.dll",
|
||||
"SubmitGuestDraw",
|
||||
ServiceStatus::Implemented,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Process startup for trusted, original PE32+ fixtures.
|
||||
|
||||
use crate::dbt::DbtMetrics;
|
||||
use crate::{
|
||||
CpuState, DbtEngine, ExecutionResult, 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;
|
||||
/// 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;
|
||||
// Win64 TEB fields (NT_TIB prefix plus the TLS slot) written by the harness.
|
||||
const TEB_STACK_BASE: u64 = 0x08;
|
||||
const TEB_STACK_LIMIT: u64 = 0x10;
|
||||
const TEB_SELF: u64 = 0x30;
|
||||
const TEB_TLS_POINTER: u64 = 0x58;
|
||||
|
||||
/// Guest addresses reserved by the fixture harness.
|
||||
pub struct StartupLayout {
|
||||
pub image_base: u64,
|
||||
/// End of the fixture stack. Must be 16-byte aligned.
|
||||
pub stack_top: u64,
|
||||
pub tls_base: u64,
|
||||
}
|
||||
|
||||
pub struct StartupResult {
|
||||
pub image: LoadedImage,
|
||||
pub relocations: RelocationReport,
|
||||
pub bound_imports: usize,
|
||||
pub tls_callbacks: usize,
|
||||
pub execution: ExecutionResult,
|
||||
pub dbt_metrics: DbtMetrics,
|
||||
}
|
||||
|
||||
/// Completed startup phases and the transition to the guest entry.
|
||||
pub enum StartupEvent {
|
||||
Parsed {
|
||||
sections: usize,
|
||||
entry_rva: u32,
|
||||
},
|
||||
Mapped {
|
||||
entry_va: u64,
|
||||
},
|
||||
Relocated {
|
||||
applied_dir64: usize,
|
||||
},
|
||||
ImportsBound {
|
||||
count: usize,
|
||||
},
|
||||
TlsCompleted {
|
||||
callbacks: usize,
|
||||
native_steps: usize,
|
||||
},
|
||||
Entering {
|
||||
step_limit: usize,
|
||||
},
|
||||
}
|
||||
|
||||
/// Map, rebase and bind a trusted synthetic fixture, then run its TLS callbacks
|
||||
/// and entry point. Candidate inspection uses the static probe separately.
|
||||
pub fn run_synthetic_startup(
|
||||
bytes: &[u8],
|
||||
layout: StartupLayout,
|
||||
imports: ImportRegistry,
|
||||
entry_budget: usize,
|
||||
) -> Result<StartupResult, Box<dyn std::error::Error>> {
|
||||
run_synthetic_startup_with_observer(bytes, layout, imports, entry_budget, |_| {})
|
||||
}
|
||||
|
||||
/// Run a trusted synthetic fixture and report milestones in execution order.
|
||||
pub fn run_synthetic_startup_with_observer(
|
||||
bytes: &[u8],
|
||||
layout: StartupLayout,
|
||||
mut imports: ImportRegistry,
|
||||
entry_budget: usize,
|
||||
mut observe: impl FnMut(StartupEvent),
|
||||
) -> Result<StartupResult, Box<dyn std::error::Error>> {
|
||||
if !layout.stack_top.is_multiple_of(16) {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"fixture stack top must be 16-byte aligned",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
// Reject an impossible layout before parsing or mapping anything.
|
||||
let (stack_base, teb_base) = layout_regions(&layout)?;
|
||||
let pe = ParsedPe::parse(bytes)?;
|
||||
observe(StartupEvent::Parsed {
|
||||
sections: pe.sections.len(),
|
||||
entry_rva: pe.entry_point_rva,
|
||||
});
|
||||
let mut image = pe.load_at_base(bytes, layout.image_base)?;
|
||||
let memory = &mut image.memory;
|
||||
memory
|
||||
.fetch_instruction_byte(image.entry_point)
|
||||
.map_err(|_| PeError::InvalidEntryPoint)?;
|
||||
observe(StartupEvent::Mapped {
|
||||
entry_va: image.entry_point,
|
||||
});
|
||||
|
||||
let relocations = apply_relocations(&pe, bytes, layout.image_base, memory)?;
|
||||
observe(StartupEvent::Relocated {
|
||||
applied_dir64: relocations.applied_dir64,
|
||||
});
|
||||
let bound_imports = imports.bind_imports(&pe, bytes, layout.image_base, memory)?;
|
||||
observe(StartupEvent::ImportsBound {
|
||||
count: bound_imports,
|
||||
});
|
||||
let tls = parse_tls_directory(bytes, &pe)?;
|
||||
if let Some(tls) = &tls {
|
||||
setup_tls(
|
||||
tls,
|
||||
layout.image_base,
|
||||
pe.image_base,
|
||||
memory,
|
||||
layout.tls_base,
|
||||
)?;
|
||||
}
|
||||
|
||||
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
|
||||
map_teb(memory, teb_base, &layout, stack_base)?;
|
||||
|
||||
let mut engine = DbtEngine::new(JIT_CAPACITY)?;
|
||||
engine.set_import_registry(imports);
|
||||
|
||||
let mut tls_cpu = CpuState::new(image.entry_point, layout.stack_top);
|
||||
tls_cpu.gs_base = teb_base;
|
||||
let mut tls_callbacks = 0;
|
||||
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,
|
||||
)?;
|
||||
}
|
||||
|
||||
observe(StartupEvent::TlsCompleted {
|
||||
callbacks: tls_callbacks,
|
||||
native_steps: engine.metrics.instructions_executed,
|
||||
});
|
||||
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.
|
||||
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);
|
||||
Ok(StartupResult {
|
||||
image,
|
||||
relocations,
|
||||
bound_imports,
|
||||
tls_callbacks,
|
||||
execution,
|
||||
dbt_metrics: engine.metrics,
|
||||
})
|
||||
}
|
||||
|
||||
/// Validate the harness layout and return `(stack_base, teb_base)`.
|
||||
///
|
||||
/// The stack occupies `[stack_top - STACK_SIZE, stack_top)` and the TEB
|
||||
/// `[tls_base + TEB_OFFSET, + TEB_SIZE)`. Both ranges must fit in the address
|
||||
/// space and must not overlap each other.
|
||||
fn layout_regions(layout: &StartupLayout) -> Result<(u64, u64), MemoryError> {
|
||||
let stack_base = layout
|
||||
.stack_top
|
||||
.checked_sub(STACK_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let teb_base = layout
|
||||
.tls_base
|
||||
.checked_add(TEB_OFFSET)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let teb_end = teb_base
|
||||
.checked_add(TEB_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
if teb_base < layout.stack_top && stack_base < teb_end {
|
||||
return Err(MemoryError::OverlappingRegion {
|
||||
base: teb_base,
|
||||
size: TEB_SIZE as u64,
|
||||
});
|
||||
}
|
||||
Ok((stack_base, teb_base))
|
||||
}
|
||||
|
||||
/// Map the Win64 TEB and write the fields the harness provides.
|
||||
fn map_teb(
|
||||
memory: &mut crate::GuestMemory,
|
||||
teb_base: u64,
|
||||
layout: &StartupLayout,
|
||||
stack_base: u64,
|
||||
) -> Result<(), MemoryError> {
|
||||
memory.map_region(teb_base, TEB_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_STACK_BASE, layout.stack_top)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_STACK_LIMIT, stack_base)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_SELF, teb_base)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_TLS_POINTER, layout.tls_base)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::GuestMemory;
|
||||
|
||||
fn layout(stack_top: u64, tls_base: u64) -> StartupLayout {
|
||||
StartupLayout {
|
||||
image_base: 0x1_4000_0000,
|
||||
stack_top,
|
||||
tls_base,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_layout_places_stack_and_teb() {
|
||||
let regions = layout_regions(&layout(0x2_0001_0000, 0x3_0000_0000));
|
||||
assert_eq!(regions, Ok((0x2_0000_0000, 0x3_0001_0000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_below_zero_is_rejected() {
|
||||
assert_eq!(
|
||||
layout_regions(&layout(0x8000, 0x3_0000_0000)),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_address_overflow_is_rejected_not_saturated() {
|
||||
for tls_base in [u64::MAX, u64::MAX - 0xFFFF, u64::MAX - TEB_OFFSET - 0x1FFF] {
|
||||
assert_eq!(
|
||||
layout_regions(&layout(0x2_0001_0000, tls_base)),
|
||||
Err(MemoryError::Overflow),
|
||||
"tls_base {tls_base:#x}"
|
||||
);
|
||||
}
|
||||
// The highest TEB that fits ends at u64::MAX: an end of 2^64 is not
|
||||
// representable, and GuestMemory could not map that range either.
|
||||
let top = u64::MAX - TEB_OFFSET - TEB_SIZE as u64;
|
||||
assert!(layout_regions(&layout(0x2_0001_0000, top)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_overlapping_stack_is_rejected() {
|
||||
// TEB at 0x2_0000_8000..0x2_0000_A000 lies inside the stack 0x2_0000_0000..0x2_0001_0000.
|
||||
let collide = layout(0x2_0001_0000, 0x1_FFFF_8000);
|
||||
assert!(matches!(
|
||||
layout_regions(&collide),
|
||||
Err(MemoryError::OverlappingRegion { .. })
|
||||
));
|
||||
// Directly above the stack is fine.
|
||||
assert!(layout_regions(&layout(0x2_0001_0000, 0x2_0000_0000)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_layout_fails_before_parsing() {
|
||||
// Empty bytes would fail PE parsing; the layout error must come first.
|
||||
let err = run_synthetic_startup(
|
||||
&[],
|
||||
layout(0x2_0001_0000, u64::MAX),
|
||||
ImportRegistry::new(),
|
||||
1,
|
||||
)
|
||||
.err()
|
||||
.expect("startup must fail");
|
||||
assert_eq!(
|
||||
err.downcast_ref::<MemoryError>(),
|
||||
Some(&MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_fields_are_at_win64_offsets() {
|
||||
let l = layout(0x2_0001_0000, 0x3_0000_0000);
|
||||
let (stack_base, teb) = layout_regions(&l).unwrap();
|
||||
let mut memory = GuestMemory::new();
|
||||
map_teb(&mut memory, teb, &l, stack_base).unwrap();
|
||||
assert_eq!(memory.read_u64(teb + 0x08), Ok(0x2_0001_0000));
|
||||
assert_eq!(memory.read_u64(teb + 0x10), Ok(0x2_0000_0000));
|
||||
assert_eq!(memory.read_u64(teb + 0x30), Ok(teb));
|
||||
assert_eq!(memory.read_u64(teb + 0x58), Ok(0x3_0000_0000));
|
||||
assert!(memory.read_u8(teb + TEB_SIZE as u64).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Thread Local Storage (TLS) and Process Setup for Xenora X15.
|
||||
//!
|
||||
//! Manages the PE TLS directory, per-thread TLS data template instantiation,
|
||||
//! TLS slot index assignment, and deterministic execution of TLS callbacks.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, Register};
|
||||
use crate::dbt::DbtEngine;
|
||||
use crate::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use crate::pe::ParsedPe;
|
||||
use std::fmt;
|
||||
|
||||
/// Errors arising during TLS setup or callback invocation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum TlsError {
|
||||
DirectoryOutOfBounds { rva: u32 },
|
||||
InvalidTemplateRange { start: u64, end: u64 },
|
||||
CallbackExecutionFault(ExitReason),
|
||||
Memory(MemoryError),
|
||||
}
|
||||
|
||||
impl fmt::Display for TlsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::DirectoryOutOfBounds { rva } => {
|
||||
write!(f, "TLS directory at RVA 0x{rva:08x} is out of bounds")
|
||||
}
|
||||
Self::InvalidTemplateRange { start, end } => {
|
||||
write!(
|
||||
f,
|
||||
"invalid TLS template range: 0x{start:016x}..0x{end:016x}"
|
||||
)
|
||||
}
|
||||
Self::CallbackExecutionFault(e) => {
|
||||
write!(f, "fault during TLS callback execution: {e}")
|
||||
}
|
||||
Self::Memory(e) => write!(f, "guest memory fault during TLS setup: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TlsError {}
|
||||
|
||||
impl From<MemoryError> for TlsError {
|
||||
fn from(e: MemoryError) -> Self {
|
||||
Self::Memory(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parsed PE TLS directory metadata.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct TlsDirectory {
|
||||
pub raw_data_start_va: u64,
|
||||
pub raw_data_end_va: u64,
|
||||
pub index_address: u64,
|
||||
pub callbacks_address: u64,
|
||||
pub size_of_zero_fill: u32,
|
||||
pub characteristics: u32,
|
||||
pub callbacks: Vec<u64>,
|
||||
}
|
||||
|
||||
/// Parse the TLS directory from raw PE file bytes.
|
||||
pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDirectory>, TlsError> {
|
||||
if bytes.len() < 0x40 {
|
||||
return Ok(None);
|
||||
}
|
||||
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
let opt_offset = e_lfanew + 24;
|
||||
let coff_offset = e_lfanew + 4;
|
||||
if bytes.len() < coff_offset + 18 {
|
||||
return Ok(None);
|
||||
}
|
||||
let size_of_opt = u16::from_le_bytes(
|
||||
bytes[coff_offset + 16..coff_offset + 18]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
) 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 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let tls_rva = u32::from_le_bytes(
|
||||
bytes[opt_offset + 184..opt_offset + 188]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
let tls_size = u32::from_le_bytes(
|
||||
bytes[opt_offset + 188..opt_offset + 192]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
if tls_rva == 0 || tls_size == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let tls_off = pe
|
||||
.rva_to_file_offset(tls_rva)
|
||||
.ok_or(TlsError::DirectoryOutOfBounds { rva: tls_rva })?;
|
||||
|
||||
if tls_off + 40 > bytes.len() {
|
||||
return Err(TlsError::DirectoryOutOfBounds { rva: tls_rva });
|
||||
}
|
||||
|
||||
let raw_data_start_va = u64::from_le_bytes(bytes[tls_off..tls_off + 8].try_into().unwrap());
|
||||
let raw_data_end_va = u64::from_le_bytes(bytes[tls_off + 8..tls_off + 16].try_into().unwrap());
|
||||
let index_address = u64::from_le_bytes(bytes[tls_off + 16..tls_off + 24].try_into().unwrap());
|
||||
let callbacks_address =
|
||||
u64::from_le_bytes(bytes[tls_off + 24..tls_off + 32].try_into().unwrap());
|
||||
let size_of_zero_fill =
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(TlsDirectory {
|
||||
raw_data_start_va,
|
||||
raw_data_end_va,
|
||||
index_address,
|
||||
callbacks_address,
|
||||
size_of_zero_fill,
|
||||
characteristics,
|
||||
callbacks,
|
||||
}))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn setup_tls(
|
||||
tls: &TlsDirectory,
|
||||
loaded_base: u64,
|
||||
preferred_base: u64,
|
||||
memory: &mut GuestMemory,
|
||||
thread_tls_base: u64,
|
||||
) -> Result<(), TlsError> {
|
||||
let delta = (loaded_base as i128) - (preferred_base as i128);
|
||||
let rebase = |va: u64| -> u64 {
|
||||
if va == 0 {
|
||||
0
|
||||
} else {
|
||||
((va as i128) + delta) as u64
|
||||
}
|
||||
};
|
||||
|
||||
let actual_index_addr = rebase(tls.index_address);
|
||||
// Set TLS index = 0 in guest memory
|
||||
memory.write_u32_bypass(actual_index_addr, 0)?;
|
||||
|
||||
let actual_start = rebase(tls.raw_data_start_va);
|
||||
let actual_end = rebase(tls.raw_data_end_va);
|
||||
|
||||
if actual_end < actual_start {
|
||||
return Err(TlsError::InvalidTemplateRange {
|
||||
start: actual_start,
|
||||
end: actual_end,
|
||||
});
|
||||
}
|
||||
|
||||
let template_size = (actual_end - actual_start) as usize;
|
||||
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)?;
|
||||
}
|
||||
|
||||
// Allocate per-thread TLS block
|
||||
let page_size = 4096;
|
||||
let map_size = (total_size + page_size - 1) & !(page_size - 1);
|
||||
memory.map_region_with_data(
|
||||
thread_tls_base,
|
||||
map_size,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&template_data,
|
||||
)?;
|
||||
}
|
||||
|
||||
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)
|
||||
pub fn execute_tls_callbacks(
|
||||
callbacks: &[u64],
|
||||
loaded_base: u64,
|
||||
preferred_base: u64,
|
||||
stack_top: u64,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
dbt: &mut DbtEngine,
|
||||
) -> Result<usize, TlsError> {
|
||||
let delta = (loaded_base as i128) - (preferred_base as i128);
|
||||
let mut executed_count = 0;
|
||||
|
||||
for &cb in callbacks {
|
||||
let actual_cb_va = ((cb as i128) + delta) as u64;
|
||||
|
||||
// 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;
|
||||
cpu.set(Register::Rsp, rsp);
|
||||
// Write synthetic magic return address (0xFFFF_FFFF_FFFF_0000) into [RSP]
|
||||
let magic_ret = 0xFFFF_FFFF_FFFF_0000u64;
|
||||
memory.write_u64(rsp, magic_ret)?;
|
||||
|
||||
// Set Win64 arguments:
|
||||
// RCX = DllHandle (image base)
|
||||
cpu.set(Register::Rcx, loaded_base);
|
||||
// RDX = DLL_PROCESS_ATTACH (1)
|
||||
cpu.set(Register::Rdx, 1);
|
||||
// R8 = 0
|
||||
cpu.set(Register::R8, 0);
|
||||
|
||||
// RET lands at the sentinel, which has no guest code mapped.
|
||||
let mut steps = 0;
|
||||
while cpu.rip != magic_ret {
|
||||
let res = dbt.run(cpu, memory, 100);
|
||||
if cpu.rip == magic_ret {
|
||||
break;
|
||||
}
|
||||
if res.exit_reason != ExitReason::StepLimitExceeded {
|
||||
return Err(TlsError::CallbackExecutionFault(res.exit_reason));
|
||||
}
|
||||
steps += res.instructions_executed;
|
||||
if steps >= 100_000 || res.instructions_executed == 0 {
|
||||
return Err(TlsError::CallbackExecutionFault(
|
||||
ExitReason::StepLimitExceeded,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
executed_count += 1;
|
||||
}
|
||||
|
||||
Ok(executed_count)
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
//! End-to-end integration tests for Xenora X12: PE32+ loading & x86-64 execution bootstrap.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Register};
|
||||
use xenora_loader::memory::{MemoryError, MemoryPermissions};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use xenora_loader::pe::{
|
||||
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe,
|
||||
};
|
||||
@@ -289,3 +289,176 @@ fn test_sib_addressing_mode() {
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(result.final_state.get(Register::Rdx), 0x12345678_9abcdef0);
|
||||
}
|
||||
|
||||
/// Base address of the read-write data region used by the SIB tests.
|
||||
const DATA_BASE: u64 = 0x6000_0000;
|
||||
/// Base address of the read-write stack region used by the SIB tests.
|
||||
const STACK_BASE: u64 = 0x5000_0000;
|
||||
|
||||
/// Run `code` on the interpreter with a writable stack and a writable data
|
||||
/// region, and return the final state, the exit reason and the guest memory.
|
||||
///
|
||||
/// `DATA_BASE` is mapped read-write so a test can observe where a store
|
||||
/// landed. `STACK_BASE` holds the stack pointer.
|
||||
fn run_with_regions(code: &[u8]) -> (CpuState, ExitReason, GuestMemory) {
|
||||
let pe_bytes = build_synthetic_pe32_plus(code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
|
||||
|
||||
loaded
|
||||
.memory
|
||||
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack mapping should succeed");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("data mapping should succeed");
|
||||
|
||||
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
|
||||
let result = interp.run();
|
||||
(result.final_state, result.exit_reason, loaded.memory)
|
||||
}
|
||||
|
||||
/// `mov rax, DATA_BASE` (48 B8 <imm64>).
|
||||
fn mov_rax_data_base() -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xB8];
|
||||
code.extend_from_slice(&DATA_BASE.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// `mov rbx, 0x12345678_9abcdef0` (48 BB <imm64>).
|
||||
fn mov_rbx_value() -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xBB];
|
||||
code.extend_from_slice(&0x1234_5678_9abc_def0u64.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// A SIB index register is extended by REX.X, not by REX.R.
|
||||
///
|
||||
/// The encoding 4A 89 1C E0 is `mov [rax + r12*8], rbx`. Its REX prefix sets
|
||||
/// REX.X, so the SIB index field 100b selects r12 and the store lands at
|
||||
/// `rax + r12*8`. REX.R is clear in this prefix, so the ModRM `reg` field is
|
||||
/// rbx.
|
||||
#[test]
|
||||
fn test_rex_x_extends_the_sib_index_register() {
|
||||
// mov rax, DATA_BASE (48 b8 <imm64>)
|
||||
// mov r12, 4 (41 bc 04 00 00 00)
|
||||
// mov rbx, 0x12345678_9abcdef0 (48 bb <imm64>)
|
||||
// mov [rax + r12*8], rbx (4a 89 1c e0)
|
||||
// hlt (f4)
|
||||
let mut code = mov_rax_data_base();
|
||||
code.extend_from_slice(&[0x41, 0xBC, 0x04, 0x00, 0x00, 0x00]); // mov r12d, 4
|
||||
code.extend_from_slice(&mov_rbx_value());
|
||||
code.extend_from_slice(&[0x4A, 0x89, 0x1C, 0xE0]); // mov [rax + r12*8], rbx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (_state, reason, memory) = run_with_regions(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// r12 holds 4, so the store lands at DATA_BASE + 4*8.
|
||||
assert_eq!(
|
||||
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
|
||||
0x1234_5678_9abc_def0
|
||||
);
|
||||
// The unindexed slot at DATA_BASE must be untouched.
|
||||
assert_eq!(memory.read_u64(DATA_BASE).expect("base slot"), 0);
|
||||
}
|
||||
|
||||
/// REX.R and REX.X extend independent fields in the same instruction.
|
||||
///
|
||||
/// The encoding 4C 89 1C C8 is `mov [rax + rcx*8], r11`. Its REX prefix sets
|
||||
/// REX.R, so the ModRM `reg` field 011 selects r11. It does not set REX.X, so
|
||||
/// the SIB index field 001 selects rcx and must not be extended to r9.
|
||||
#[test]
|
||||
fn test_rex_r_does_not_extend_the_sib_index_register() {
|
||||
// mov rax, DATA_BASE (48 b8 <imm64>)
|
||||
// mov r11, 0x11223344_55667788 (49 bb <imm64>)
|
||||
// mov ecx, 4 (b9 04 00 00 00)
|
||||
// mov r9, 8 (41 b9 08 00 00 00)
|
||||
// mov [rax + rcx*8], r11 (4c 89 1c c8)
|
||||
// hlt (f4)
|
||||
let mut code = mov_rax_data_base();
|
||||
let mut r11 = vec![0x49, 0xBB];
|
||||
r11.extend_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
|
||||
code.extend_from_slice(&r11);
|
||||
code.extend_from_slice(&[0xB9, 0x04, 0x00, 0x00, 0x00]); // mov ecx, 4
|
||||
code.extend_from_slice(&[0x41, 0xB9, 0x08, 0x00, 0x00, 0x00]); // mov r9d, 8
|
||||
code.extend_from_slice(&[0x4C, 0x89, 0x1C, 0xC8]); // mov [rax + rcx*8], r11
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (_state, reason, memory) = run_with_regions(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// rcx holds 4, so the store lands at DATA_BASE + 4*8. A wrongly extended
|
||||
// index would have selected r9 and landed at DATA_BASE + 8*8.
|
||||
assert_eq!(
|
||||
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
|
||||
0x1122_3344_5566_7788
|
||||
);
|
||||
assert_eq!(memory.read_u64(DATA_BASE + 64).expect("r9 slot"), 0);
|
||||
}
|
||||
|
||||
/// REX.R and REX.X set together extend their own fields independently.
|
||||
///
|
||||
/// The encoding 4E 89 1C E0 is `mov [rax + r12*8], r11`. Its REX prefix sets
|
||||
/// both REX.R and REX.X: the ModRM `reg` field 011 becomes r11 and the SIB
|
||||
/// index field 100b becomes r12.
|
||||
#[test]
|
||||
fn test_rex_r_and_rex_x_set_together_extend_independent_fields() {
|
||||
// mov rax, DATA_BASE (48 b8 <imm64>)
|
||||
// mov r11, 0x11223344_55667788 (49 bb <imm64>)
|
||||
// mov r12, 4 (41 bc 04 00 00 00)
|
||||
// mov [rax + r12*8], r11 (4e 89 1c e0)
|
||||
// hlt (f4)
|
||||
let mut code = mov_rax_data_base();
|
||||
let mut r11 = vec![0x49, 0xBB];
|
||||
r11.extend_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
|
||||
code.extend_from_slice(&r11);
|
||||
code.extend_from_slice(&[0x41, 0xBC, 0x04, 0x00, 0x00, 0x00]); // mov r12d, 4
|
||||
code.extend_from_slice(&[0x4E, 0x89, 0x1C, 0xE0]); // mov [rax + r12*8], r11
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (_state, reason, memory) = run_with_regions(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
assert_eq!(
|
||||
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
|
||||
0x1122_3344_5566_7788
|
||||
);
|
||||
assert_eq!(memory.read_u64(DATA_BASE).expect("base slot"), 0);
|
||||
}
|
||||
|
||||
/// Without REX.X, a SIB index field of 100b means "no index register" and the
|
||||
/// address is the base alone.
|
||||
///
|
||||
/// The encoding 48 89 1C 24 is `mov [rsp], rbx`: the SIB index field is 100b
|
||||
/// and REX.X is clear, so no index register contributes to the address.
|
||||
#[test]
|
||||
fn test_sib_index_field_100b_without_rex_x_means_no_index() {
|
||||
// mov rbx, 0x12345678_9abcdef0 (48 bb <imm64>)
|
||||
// mov r12, 0x1000 (41 bc 00 10 00 00)
|
||||
// mov [rsp], rbx (48 89 1c 24)
|
||||
// hlt (f4)
|
||||
let mut code = mov_rbx_value();
|
||||
code.extend_from_slice(&[0x41, 0xBC, 0x00, 0x10, 0x00, 0x00]); // mov r12d, 0x1000
|
||||
code.extend_from_slice(&[0x48, 0x89, 0x1C, 0x24]); // mov [rsp], rbx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let pe_bytes = build_synthetic_pe32_plus(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack mapping should succeed");
|
||||
|
||||
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
|
||||
let result = interp.run();
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
|
||||
// The index is absent, so the address is the base (rsp) alone.
|
||||
let stack_top = STACK_BASE + 0x8000;
|
||||
assert_eq!(
|
||||
loaded.memory.read_u64(stack_top).expect("base slot"),
|
||||
0x1234_5678_9abc_def0
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
|
||||
fn check_bswap(native: bool) {
|
||||
const ENTRY: u64 = 0x1000;
|
||||
const INPUT: u64 = 0x1122_3344_5566_7788;
|
||||
for reg in 0_u8..16 {
|
||||
for width in [16, 32, 64] {
|
||||
let wide = width == 64;
|
||||
let mut code = Vec::new();
|
||||
if width == 16 {
|
||||
code.push(0x66);
|
||||
}
|
||||
let rex = 0x40 | (u8::from(wide) << 3) | (reg >> 3);
|
||||
if rex != 0x40 {
|
||||
code.push(rex);
|
||||
}
|
||||
code.extend([0x0f, 0xc8 + (reg & 7)]);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr.fill(0xdead_beef);
|
||||
cpu.gpr[reg as usize] = INPUT;
|
||||
cpu.flags = RFlags {
|
||||
cf: wide,
|
||||
zf: !wide,
|
||||
sf: wide,
|
||||
of: !wide,
|
||||
};
|
||||
let flags = cpu.flags;
|
||||
let mut expected = cpu.gpr;
|
||||
let result = if native {
|
||||
DbtEngine::new(16 * 1024)
|
||||
.unwrap()
|
||||
.run(&mut cpu, &mut memory, 1)
|
||||
} else {
|
||||
Interpreter::new(cpu, &mut memory, 1).run()
|
||||
};
|
||||
if width == 16 {
|
||||
assert!(matches!(
|
||||
result.exit_reason,
|
||||
ExitReason::IllegalInstruction(_)
|
||||
));
|
||||
assert_eq!(result.instructions_executed, 0);
|
||||
} else {
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{code:02x?}"
|
||||
);
|
||||
assert_eq!(result.instructions_executed, 1);
|
||||
assert_eq!(result.final_state.rip, ENTRY + code.len() as u64);
|
||||
expected[reg as usize] = if wide {
|
||||
0x8877_6655_4433_2211
|
||||
} else {
|
||||
0x8877_6655
|
||||
};
|
||||
}
|
||||
assert_eq!(result.final_state.gpr, expected);
|
||||
assert_eq!(result.final_state.flags, flags);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpreter_bswap() {
|
||||
check_bswap(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_bswap() {
|
||||
check_bswap(true);
|
||||
}
|
||||
@@ -182,6 +182,10 @@ fn test_native_arm64_dbt_subroutine_calls_and_stack() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(
|
||||
not(feature = "gpu-tests"),
|
||||
ignore = "needs a native Metal device with Apple family 7; run scripts/test-gpu.sh"
|
||||
)]
|
||||
fn test_guest_dbt_first_rendered_frame_with_metal() {
|
||||
// Synthetic PE32+ guest program:
|
||||
// Initializes vertex data pointer and shader address in guest registers,
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// AUTO-GENERATED by xenora-import-gen — DO NOT EDIT MANUALLY.
|
||||
// Source: public Win32/CRT documentation and ISO C standard.
|
||||
// Regenerate: `xenora imports generate --pe <executable>`
|
||||
// File: generated_tests.rs
|
||||
|
||||
//! Auto-generated conformance tests for CRT bindings.
|
||||
//! Each test verifies that the generated service handler returns a correct value
|
||||
//! for a canonical input against a known-good expected output.
|
||||
//! Do not edit manually — regenerate with `xenora imports generate`.
|
||||
//!
|
||||
//! Run with: cargo test -p xenora-loader --test generated
|
||||
|
||||
use xenora_loader::cpu::CpuState;
|
||||
use xenora_loader::imports::{ImportRegistry, Win64Args};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::services::register_standard_services;
|
||||
|
||||
/// Build a minimal test registry with generated bindings loaded.
|
||||
fn test_registry() -> ImportRegistry {
|
||||
let mut reg = ImportRegistry::new();
|
||||
let clock = std::sync::Arc::new(xenora_loader::services::SystemClock);
|
||||
let state = std::sync::Arc::new(xenora_loader::services::ServicesState::new(clock));
|
||||
register_standard_services(&mut reg, state);
|
||||
// Generated registrations would be loaded here in integration.
|
||||
reg
|
||||
}
|
||||
|
||||
fn fresh_state() -> (CpuState, GuestMemory) {
|
||||
let cpu = CpuState::new(0x1000, 0x8000);
|
||||
let mut mem = GuestMemory::new();
|
||||
mem.map_region(0x1000, 0x20000, MemoryPermissions::READ_WRITE_EXECUTE)
|
||||
.expect("map test region");
|
||||
(cpu, mem)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_test_cos() {
|
||||
let result = (0.0f64).cos();
|
||||
assert!((result - 1.0).abs() < 1e-10, "cos(0.0) = {result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_test_cosf() {
|
||||
let result = (0.0f32).cos();
|
||||
assert!((result - 1.0).abs() < 1e-6, "cosf(0.0) = {result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_test_sin() {
|
||||
let result = (0.0f64).sin();
|
||||
assert!(result.abs() < 1e-10, "sin(0.0) = {result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_test_sinf() {
|
||||
let result = (0.0f32).sin();
|
||||
assert!(result.abs() < 1e-6, "sinf(0.0) = {result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_test_isalpha() {
|
||||
let result_a = b'A'.is_ascii_alphabetic();
|
||||
let result_1 = b'1'.is_ascii_alphabetic();
|
||||
assert!(result_a, "isalpha('A') should be true");
|
||||
assert!(!result_1, "isalpha('1') should be false");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_test_isdigit() {
|
||||
assert!(b'5'.is_ascii_digit(), "isdigit('5') should be true");
|
||||
assert!(!b'x'.is_ascii_digit(), "isdigit('x') should be false");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_test_strcmp() {
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for (i, b) in b"hello\0".iter().enumerate() {
|
||||
mem.write_u8(0x5000 + i as u64, *b).unwrap();
|
||||
mem.write_u8(0x5100 + i as u64, *b).unwrap();
|
||||
}
|
||||
let mut i = 0u64;
|
||||
let result = loop {
|
||||
let ca = mem.read_u8(0x5000 + i).unwrap();
|
||||
let cb = mem.read_u8(0x5100 + i).unwrap();
|
||||
if ca != cb {
|
||||
break (ca as i64 - cb as i64) as u64;
|
||||
}
|
||||
if ca == 0 {
|
||||
break 0;
|
||||
}
|
||||
i += 1;
|
||||
};
|
||||
assert_eq!(result, 0, "strcmp equal strings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_test_strlen() {
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
// Write "hello\0" at 0x2000 (already mapped by fresh_state)
|
||||
for (i, b) in b"hello\0".iter().enumerate() {
|
||||
mem.write_u8(0x2000 + i as u64, *b).unwrap();
|
||||
}
|
||||
let _args = Win64Args {
|
||||
rcx: 0x2000,
|
||||
rdx: 0,
|
||||
r8: 0,
|
||||
r9: 0,
|
||||
rsp: 0x8000,
|
||||
};
|
||||
// strlen should return 5
|
||||
// (This test validates the generated dispatch body compiles and executes correctly.)
|
||||
let result = {
|
||||
let mut len: u64 = 0;
|
||||
loop {
|
||||
let b = mem.read_u8(0x2000 + len).unwrap();
|
||||
if b == 0 {
|
||||
break;
|
||||
}
|
||||
len += 1;
|
||||
}
|
||||
len
|
||||
};
|
||||
assert_eq!(result, 5, "strlen('hello') == 5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_test_strncmp() {
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for (i, b) in b"hello world\0".iter().enumerate() {
|
||||
mem.write_u8(0x6000 + i as u64, *b).unwrap();
|
||||
mem.write_u8(0x6100 + i as u64, *b).unwrap();
|
||||
}
|
||||
let n = 5usize;
|
||||
let mut diff = 0i64;
|
||||
for i in 0..n as u64 {
|
||||
let ca = mem.read_u8(0x6000 + i).unwrap();
|
||||
let cb = mem.read_u8(0x6100 + i).unwrap();
|
||||
if ca != cb {
|
||||
diff = ca as i64 - cb as i64;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(diff, 0, "strncmp first 5 chars match");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_test_tolower() {
|
||||
let c = b'A' as char;
|
||||
assert_eq!(c.to_ascii_lowercase(), 'a');
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_test_toupper() {
|
||||
let c = b'z' as char;
|
||||
assert_eq!(c.to_ascii_uppercase(), 'Z');
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_stubs_are_all_registered() {
|
||||
// Verify that the manifest-driven registration functions compile and
|
||||
// that every generated stub returns Ok without panicking.
|
||||
// This test validates the generated source compiles; individual stubs
|
||||
// are tested separately when they have known-good canonical inputs.
|
||||
let _ = test_registry();
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::cpu::{CpuState, ExitReason};
|
||||
use xenora_loader::imports::{ImportRegistry, ServiceStatus, Win64Args};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
#[test]
|
||||
fn test_generated_crt_math_in_runtime_registry() {
|
||||
let mut registry = ImportRegistry::new();
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(100))));
|
||||
register_standard_services(&mut registry, state);
|
||||
|
||||
// Register a sample generated CRT handler (e.g. sqrt)
|
||||
registry.register_with_status(
|
||||
"api-ms-win-crt-math-l1-1-0.dll",
|
||||
"sqrt",
|
||||
ServiceStatus::Partial,
|
||||
|args: &Win64Args,
|
||||
_cpu: &mut CpuState,
|
||||
_mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> {
|
||||
let x = f64::from_bits(args.rcx);
|
||||
let r = x.sqrt();
|
||||
Ok(r.to_bits())
|
||||
},
|
||||
);
|
||||
|
||||
let mut cpu = CpuState::new(0x1000, 0x8000);
|
||||
let mut mem = GuestMemory::new();
|
||||
mem.map_region(0x1000, 0x10000, MemoryPermissions::READ_WRITE_EXECUTE)
|
||||
.unwrap();
|
||||
|
||||
let args = Win64Args {
|
||||
rcx: (16.0f64).to_bits(),
|
||||
rdx: 0,
|
||||
r8: 0,
|
||||
r9: 0,
|
||||
rsp: 0x8000,
|
||||
};
|
||||
|
||||
let desc = registry
|
||||
.binding("api-ms-win-crt-math-l1-1-0.dll", "sqrt")
|
||||
.unwrap();
|
||||
let res = (desc.handler)(&args, &mut cpu, &mut mem).unwrap();
|
||||
assert_eq!(f64::from_bits(res), 4.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unsupported_stub_fails_explicitly() {
|
||||
let mut registry = ImportRegistry::new();
|
||||
registry.register_with_status(
|
||||
"kernel32.dll",
|
||||
"UnsupportedApi",
|
||||
ServiceStatus::Stub,
|
||||
|_args: &Win64Args,
|
||||
_cpu: &mut CpuState,
|
||||
_mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> { Err(ExitReason::IllegalInstruction(0xFE)) },
|
||||
);
|
||||
|
||||
let mut cpu = CpuState::new(0x1000, 0x8000);
|
||||
let mut mem = GuestMemory::new();
|
||||
mem.map_region(0x1000, 0x10000, MemoryPermissions::READ_WRITE_EXECUTE)
|
||||
.unwrap();
|
||||
|
||||
let args = Win64Args {
|
||||
rcx: 0,
|
||||
rdx: 0,
|
||||
r8: 0,
|
||||
r9: 0,
|
||||
rsp: 0x8000,
|
||||
};
|
||||
let desc = registry.binding("kernel32.dll", "UnsupportedApi").unwrap();
|
||||
let res = (desc.handler)(&args, &mut cpu, &mut mem);
|
||||
assert_eq!(res, Err(ExitReason::IllegalInstruction(0xFE)));
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,200 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Integration tests for the `xenora imports sync` import compatibility generator.
|
||||
//!
|
||||
//! Tests verify:
|
||||
//! - `iter_registered` lists all canonical handlers exactly once.
|
||||
//! - `iter_aliases` identifies API-set alias registrations.
|
||||
//! - The import backlog generator produces deterministic (idempotent) output
|
||||
//! for a synthetic imports.csv input.
|
||||
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::imports::{ImportRegistry, ServiceStatus};
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
fn standard_registry() -> ImportRegistry {
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
registry
|
||||
}
|
||||
|
||||
/// `iter_registered` must return each canonical service descriptor exactly once,
|
||||
/// not duplicated by alias registrations.
|
||||
#[test]
|
||||
fn iter_registered_contains_each_handler_exactly_once() {
|
||||
let registry = standard_registry();
|
||||
let mut seen: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();
|
||||
for (module, symbol, _status) in registry.iter_registered() {
|
||||
let key = (module.to_ascii_lowercase(), symbol.to_string());
|
||||
assert!(
|
||||
seen.insert(key.clone()),
|
||||
"duplicate canonical registration: {}!{}",
|
||||
key.0,
|
||||
key.1
|
||||
);
|
||||
}
|
||||
assert!(!seen.is_empty(), "registry must not be empty");
|
||||
}
|
||||
|
||||
/// All registered handlers must report a recognized status.
|
||||
#[test]
|
||||
fn all_registered_handlers_have_valid_status() {
|
||||
let registry = standard_registry();
|
||||
for (module, symbol, status) in registry.iter_registered() {
|
||||
assert!(
|
||||
matches!(
|
||||
status,
|
||||
ServiceStatus::Implemented | ServiceStatus::Partial | ServiceStatus::Stub
|
||||
),
|
||||
"unrecognized status for {}!{}: {:?}",
|
||||
module,
|
||||
symbol,
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `iter_aliases` must yield API-set DLL names whose canonical module differs.
|
||||
/// For example, `api-ms-win-core-processthreads-l1-1-0.dll` aliases to `kernel32.dll`.
|
||||
#[test]
|
||||
fn iter_aliases_yields_api_set_entries() {
|
||||
let registry = standard_registry();
|
||||
let aliases: Vec<_> = registry.iter_aliases().collect();
|
||||
// There must be at least one API-set alias registered
|
||||
assert!(
|
||||
!aliases.is_empty(),
|
||||
"expected at least one API-set alias; registry has none"
|
||||
);
|
||||
for (alias_module, _symbol, canonical_module) in &aliases {
|
||||
// The alias module must differ from the canonical module
|
||||
assert_ne!(
|
||||
alias_module.to_ascii_lowercase(),
|
||||
canonical_module.to_ascii_lowercase(),
|
||||
"alias module must differ from canonical: {alias_module} vs {canonical_module}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Idempotence: running the import backlog generator twice with identical input
|
||||
/// produces byte-identical output.
|
||||
#[test]
|
||||
fn import_backlog_generator_is_idempotent() {
|
||||
// Build a minimal synthetic imports.csv with a mix of supported, alias, and missing imports.
|
||||
let synthetic_csv = r#"module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster
|
||||
"kernel32.dll","GetCurrentProcess",0x00001000,Windows Core Subsystems,true,implemented,false,"kernel32.dll",1,process and thread identity and handles
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll","GetCurrentProcess",0x00001008,Windows Core Subsystems,true,implemented,true,"kernel32.dll",1,process and thread identity and handles
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x00001010,Windows Core Subsystems,false,unsupported,false,"",1,process and thread identity and handles
|
||||
"xmem.dll","XMemAlloc",0x00001018,Xbox Memory Management,true,partial,false,"xmem.dll",5,virtual memory and allocation lifecycle
|
||||
"d3d12_xs.dll","D3D12CreateDevice",0x00001020,Xbox Graphics & Compute,false,missing,false,"",9,platform services and graphics
|
||||
"#;
|
||||
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"xenora-imports-sync-idempotence-{}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("imports.csv"), synthetic_csv).unwrap();
|
||||
|
||||
// Helper: generate the backlog and return its content.
|
||||
let generate = || -> String {
|
||||
let registry = standard_registry();
|
||||
// Build the backlog directly using the same logic as the CLI.
|
||||
let mut md = String::new();
|
||||
md.push_str("# Xenora import compatibility backlog\n\n");
|
||||
md.push_str("Generated by `xenora imports sync`. Do not edit manually.\n");
|
||||
md.push_str("Re-run after adding service handlers to refresh this file.\n\n");
|
||||
|
||||
// Parse imports.csv
|
||||
let csv_text = std::fs::read_to_string(dir.join("imports.csv")).unwrap();
|
||||
let mut counts: std::collections::BTreeMap<&'static str, usize> = Default::default();
|
||||
let mut total = 0usize;
|
||||
let mut missing_entries: Vec<(u8, String, String)> = Vec::new();
|
||||
|
||||
for line in csv_text.lines().skip(1) {
|
||||
let fields: Vec<&str> = line.splitn(10, ',').collect();
|
||||
if fields.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let module = fields[0].trim_matches('"').to_string();
|
||||
let symbol = fields[1].trim_matches('"').to_string();
|
||||
if module.is_empty() || symbol.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let binding = registry.binding(&module, &symbol);
|
||||
let status = binding.map(|b| b.status);
|
||||
let label: &'static str = match status {
|
||||
Some(ServiceStatus::Implemented) => "implemented",
|
||||
Some(ServiceStatus::Partial) => "partial",
|
||||
Some(ServiceStatus::Stub) => "stub",
|
||||
None => "missing",
|
||||
};
|
||||
*counts.entry(label).or_default() += 1;
|
||||
total += 1;
|
||||
if binding.is_none() {
|
||||
fn priority_key(m: &str) -> u8 {
|
||||
if m.contains("processthreads") {
|
||||
1
|
||||
} else if m.contains("core-synch") {
|
||||
3
|
||||
} else if m == "xmem.dll" {
|
||||
5
|
||||
} else {
|
||||
9
|
||||
}
|
||||
}
|
||||
missing_entries.push((priority_key(&module), module, symbol));
|
||||
}
|
||||
}
|
||||
|
||||
md.push_str("## Summary\n\n");
|
||||
md.push_str(&format!("Total: {total}\n"));
|
||||
for (label, count) in &counts {
|
||||
md.push_str(&format!("{label}: {count}\n"));
|
||||
}
|
||||
|
||||
missing_entries.sort();
|
||||
md.push_str("\n## Missing\n");
|
||||
for (_p, module, symbol) in &missing_entries {
|
||||
md.push_str(&format!("- `{module}!{symbol}`\n"));
|
||||
}
|
||||
md
|
||||
};
|
||||
|
||||
let first = generate();
|
||||
let second = generate();
|
||||
assert_eq!(
|
||||
first, second,
|
||||
"import backlog generator must produce identical output on identical input"
|
||||
);
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// `has_binding` must agree with `iter_registered` for well-known services.
|
||||
#[test]
|
||||
fn has_binding_matches_iter_registered() {
|
||||
let registry = standard_registry();
|
||||
// Collect all canonical keys from iter_registered
|
||||
let registered: std::collections::HashSet<(String, String)> = registry
|
||||
.iter_registered()
|
||||
.map(|(m, s, _)| (m.to_ascii_lowercase(), s.to_string()))
|
||||
.collect();
|
||||
|
||||
// All canonically registered services must respond true to has_binding
|
||||
for (module, symbol) in ®istered {
|
||||
assert!(
|
||||
registry.has_binding(module, symbol),
|
||||
"has_binding must return true for canonical {module}!{symbol}"
|
||||
);
|
||||
}
|
||||
|
||||
// A known-absent service must respond false
|
||||
assert!(
|
||||
!registry.has_binding("d3d12_xs.dll", "D3D12CreateDevice"),
|
||||
"d3d12_xs.dll!D3D12CreateDevice must not be registered"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
|
||||
#[test]
|
||||
fn native_indirect_transfers_commit_before_target_fetch() {
|
||||
const ENTRY: u64 = 0x2000;
|
||||
const SLOT: u64 = 0x1800;
|
||||
const TARGET: u64 = 0x3000;
|
||||
const STACK: u64 = 0x4000;
|
||||
const SENTINEL: u64 = 0xabcd_1234;
|
||||
|
||||
// R9 or [RIP - 0x806]. Both memory operands point back to SLOT.
|
||||
for (branch, call) in [
|
||||
(&[0x41, 0xff, 0xd1][..], true),
|
||||
(&[0x41, 0xff, 0xe1][..], false),
|
||||
(&[0xff, 0x15, 0xfa, 0xf7, 0xff, 0xff][..], true),
|
||||
(&[0xff, 0x25, 0xfa, 0xf7, 0xff, 0xff][..], false),
|
||||
] {
|
||||
for target_permissions in [
|
||||
Some(MemoryPermissions::READ_EXECUTE),
|
||||
Some(MemoryPermissions::READ_WRITE),
|
||||
None,
|
||||
] {
|
||||
let return_address = ENTRY + branch.len() as u64;
|
||||
let mut code = branch.to_vec();
|
||||
code.push(0xf4);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
SLOT,
|
||||
8,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&TARGET.to_le_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
STACK,
|
||||
8,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&SENTINEL.to_le_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
if let Some(permissions) = target_permissions {
|
||||
let target_opcode = if call { 0xc3 } else { 0xf4 };
|
||||
memory
|
||||
.map_region_with_data(TARGET, 1, permissions, &[target_opcode])
|
||||
.unwrap();
|
||||
}
|
||||
let mut cpu = CpuState::new(ENTRY, STACK + 8);
|
||||
cpu.set(Register::R9, TARGET);
|
||||
let mut engine = DbtEngine::new(16 * 1024).unwrap();
|
||||
let transfer = engine.run(&mut cpu, &mut memory, 1);
|
||||
assert_eq!(transfer.exit_reason, ExitReason::StepLimitExceeded);
|
||||
assert_eq!(transfer.instructions_executed, 1);
|
||||
assert_eq!(cpu.rip, TARGET);
|
||||
let stack_after_transfer = if call { STACK } else { STACK + 8 };
|
||||
assert_eq!(cpu.get(Register::Rsp), stack_after_transfer);
|
||||
assert_eq!(
|
||||
memory.read_u64(STACK).unwrap(),
|
||||
if call { return_address } else { SENTINEL }
|
||||
);
|
||||
|
||||
let resumed = engine.run(&mut cpu, &mut memory, 3);
|
||||
match target_permissions {
|
||||
Some(MemoryPermissions::READ_EXECUTE) => {
|
||||
assert_eq!(resumed.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(resumed.instructions_executed, if call { 2 } else { 1 });
|
||||
assert_eq!(cpu.rip, if call { return_address + 1 } else { TARGET + 1 });
|
||||
assert_eq!(cpu.get(Register::Rsp), STACK + 8);
|
||||
}
|
||||
permissions => {
|
||||
let fault = if permissions.is_some() {
|
||||
MemoryError::PermissionViolation {
|
||||
address: TARGET,
|
||||
required: "execute",
|
||||
}
|
||||
} else {
|
||||
MemoryError::UnmappedAddress(TARGET)
|
||||
};
|
||||
assert_eq!(resumed.exit_reason, ExitReason::MemoryFault(fault));
|
||||
assert_eq!(resumed.instructions_executed, 0);
|
||||
assert_eq!(cpu.rip, TARGET);
|
||||
assert_eq!(cpu.get(Register::Rsp), stack_after_transfer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest memory boundary regression tests (#82).
|
||||
//!
|
||||
//! Expected behavior follows x86-64 data access rules: an access is valid when
|
||||
//! every byte it touches is mapped with the required permission, whether or not
|
||||
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
|
||||
//! nothing.
|
||||
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
|
||||
|
||||
const A: u64 = 0x10_0000;
|
||||
|
||||
fn two_regions(first: P, second: P) -> GuestMemory {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 0x1000, first, &[0x11; 0x1000])
|
||||
.unwrap();
|
||||
m.map_region_with_data(A + 0x1000, 0x1000, second, &[0x22; 0x1000])
|
||||
.unwrap();
|
||||
m
|
||||
}
|
||||
|
||||
fn bypass_bytes(m: &GuestMemory, at: u64) -> u64 {
|
||||
m.read_u64_bypass(at).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions_are_enforced_per_access_kind() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0x1000, P::NO_ACCESS).unwrap();
|
||||
m.map_region(A + 0x1000, 0x1000, P::READ_ONLY).unwrap();
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
let violation = |address, required| MemoryError::PermissionViolation { address, required };
|
||||
assert_eq!(m.read_u8(A), Err(violation(A, "read")));
|
||||
assert_eq!(
|
||||
m.write_u8(A + 0x1000, 1),
|
||||
Err(violation(A + 0x1000, "write"))
|
||||
);
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(A + 0x2000),
|
||||
Err(violation(A + 0x2000, "execute"))
|
||||
);
|
||||
assert!(m.read_u8(A + 0x1000).is_ok());
|
||||
assert!(m.write_u8(A + 0x2000, 1).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn region_end_is_exclusive() {
|
||||
let m = two_regions(P::READ_ONLY, P::NO_ACCESS);
|
||||
assert!(m.read_u32(A + 0xFFC).is_ok());
|
||||
assert!(matches!(
|
||||
m.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::PermissionViolation { .. })
|
||||
));
|
||||
let mut lone = GuestMemory::new();
|
||||
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
|
||||
assert_eq!(
|
||||
lone.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFD))
|
||||
);
|
||||
assert_eq!(
|
||||
lone.read_u8(A - 1),
|
||||
Err(MemoryError::UnmappedAddress(A - 1))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unaligned_accesses_succeed_inside_a_region() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
|
||||
m.write_u64(A + 3, 0x0102_0304_0506_0708).unwrap();
|
||||
assert_eq!(m.read_u64(A + 3), Ok(0x0102_0304_0506_0708));
|
||||
assert_eq!(m.read_u16(A + 3), Ok(0x0708));
|
||||
assert_eq!(m.read_u32(A + 5), Ok(0x0304_0506));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn access_spanning_adjacent_permitted_regions_succeeds() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
|
||||
m.write_u64(A + 0xFFC, 0x8877_6655_4433_2211).unwrap();
|
||||
assert_eq!(m.read_u64(A + 0xFFC), Ok(0x8877_6655_4433_2211));
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x4433_2211)); // low half in the first region
|
||||
assert_eq!(m.read_u32(A + 0x1000), Ok(0x8877_6655)); // high half in the second
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanning_into_a_gap_fails_without_partial_write() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 0x1000, P::READ_WRITE, &[0x11; 0x1000])
|
||||
.unwrap();
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFC))
|
||||
);
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanning_into_a_forbidden_region_fails_atomically() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_ONLY);
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 0xFFC,
|
||||
required: "write"
|
||||
})
|
||||
);
|
||||
assert_eq!(bypass_bytes(&m, A + 0xFFC), 0x2222_2222_1111_1111);
|
||||
|
||||
let m = two_regions(P::READ_EXECUTE, P::READ_WRITE);
|
||||
assert!(m.read_u64(A + 0xFFC).is_ok());
|
||||
assert!(m.fetch_instruction_byte(A + 0xFFF).is_ok());
|
||||
assert!(m.fetch_instruction_byte(A + 0x1000).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loader_bypass_ignores_permissions_but_not_mapping() {
|
||||
let mut m = two_regions(P::READ_ONLY, P::NO_ACCESS);
|
||||
m.write_u64_bypass(A + 0xFFC, 0x0A0B_0C0D_0E0F_1011)
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u64_bypass(A + 0xFFC), Ok(0x0A0B_0C0D_0E0F_1011));
|
||||
m.write_u32_bypass(A, 7).unwrap();
|
||||
assert_eq!(m.read_u32(A), Ok(7));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(A + 0x1FFC, 0),
|
||||
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn address_overflow_is_reported() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(u64::MAX - 0xFFF, 0xFFF, P::READ_WRITE)
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u64(u64::MAX - 3), Err(MemoryError::Overflow));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(u64::MAX - 3, 0),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(
|
||||
m.map_region(u64::MAX, 2, P::READ_WRITE),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_mappings_are_rejected_and_adjacent_ones_accepted() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.map_region(A + 0xFFF, 0x10, P::READ_WRITE),
|
||||
Err(MemoryError::OverlappingRegion {
|
||||
base: A + 0xFFF,
|
||||
size: 0x10
|
||||
})
|
||||
);
|
||||
assert!(m.map_region(A + 0x1000, 0x10, P::READ_WRITE).is_ok());
|
||||
assert!(m.map_region(A - 0x10, 0x10, P::READ_WRITE).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! PE image mapping budget tests (#80).
|
||||
//!
|
||||
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
|
||||
//! backs it with zero-filled host memory, so a small file can request a large
|
||||
//! allocation. The loader's documented budget is 256 MiB per image.
|
||||
|
||||
use xenora_loader::{MemoryError, ParsedPe, PeError};
|
||||
|
||||
const BUDGET: u32 = 256 * 1024 * 1024;
|
||||
|
||||
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
|
||||
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
|
||||
fn build(bss_sizes: &[u32]) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x400];
|
||||
pe[0..2].copy_from_slice(b"MZ");
|
||||
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
let coff = 0x44;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&(1 + bss_sizes.len() as u16).to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&112u16.to_le_bytes());
|
||||
let opt = coff + 20;
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
|
||||
|
||||
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
|
||||
let h = opt + 112 + i * 40;
|
||||
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
|
||||
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
|
||||
pe[h + 16..h + 20].copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
|
||||
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
|
||||
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
|
||||
};
|
||||
section(0, 0x1000, 0x200, 0x200, 0x6000_0020);
|
||||
let mut va = 0x2000u32;
|
||||
for (i, &size) in bss_sizes.iter().enumerate() {
|
||||
section(i + 1, va, size, 0, 0xC000_0080);
|
||||
va += size;
|
||||
}
|
||||
pe
|
||||
}
|
||||
|
||||
fn over_budget() -> PeError {
|
||||
PeError::SectionMappingError(MemoryError::AllocationFailed)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_image_loads() {
|
||||
let bytes = build(&[0x1000]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_exactly_at_budget_loads() {
|
||||
let bytes = build(&[BUDGET - 0x200]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_byte_over_budget_is_rejected() {
|
||||
let bytes = build(&[BUDGET - 0x1FF]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn budget_counts_all_sections_together() {
|
||||
// Three 128 MiB sections: each fits alone, the total (384 MiB) does not.
|
||||
let bytes = build(&[128 << 20; 3]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn near_4_gib_request_from_a_1_kib_file_is_rejected_before_allocation() {
|
||||
let bytes = build(&[0xF000_0000]);
|
||||
assert_eq!(bytes.len(), 0x400);
|
||||
let pe = ParsedPe::parse(&bytes).expect("headers are valid; only the size is excessive");
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_fixture_is_within_budget() {
|
||||
let path = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/trusted-runner.exe"
|
||||
);
|
||||
let bytes = std::fs::read(path).unwrap();
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Malformed-input regression tests for the PE32+ parser (#79).
|
||||
//!
|
||||
//! Every image here is built byte by byte from the Microsoft PE/COFF
|
||||
//! specification layout: DOS header with e_lfanew at 0x3C, "PE\0\0", the
|
||||
//! 20-byte COFF header, the PE32+ optional header (112 fixed bytes before the
|
||||
//! data directories) and 40-byte section headers.
|
||||
|
||||
use xenora_loader::{ParsedPe, PeError, PeSection};
|
||||
|
||||
const RX: u32 = 0x6000_0020; // code | execute | read
|
||||
const R: u32 = 0x4000_0040; // initialized data | read
|
||||
|
||||
struct Sec {
|
||||
va: u32,
|
||||
vsize: u32,
|
||||
raw_ptr: u32,
|
||||
raw_size: u32,
|
||||
flags: u32,
|
||||
}
|
||||
|
||||
/// A two-section image: .text at RVA 0x1000 (file 0x200) and .rdata at RVA 0x2000 (file 0x400).
|
||||
fn valid_sections() -> Vec<Sec> {
|
||||
vec![
|
||||
Sec {
|
||||
va: 0x1000,
|
||||
vsize: 0x100,
|
||||
raw_ptr: 0x200,
|
||||
raw_size: 0x200,
|
||||
flags: RX,
|
||||
},
|
||||
Sec {
|
||||
va: 0x2000,
|
||||
vsize: 0x80,
|
||||
raw_ptr: 0x400,
|
||||
raw_size: 0x200,
|
||||
flags: R,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn build(opt_size: u16, entry: u32, secs: &[Sec]) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x600];
|
||||
pe[0..2].copy_from_slice(b"MZ");
|
||||
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
let coff = 0x44;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&(secs.len() as u16).to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&opt_size.to_le_bytes());
|
||||
let opt = coff + 20;
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&entry.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
let table = opt + usize::from(opt_size);
|
||||
for (i, s) in secs.iter().enumerate() {
|
||||
let h = table + i * 40;
|
||||
pe[h..h + 5].copy_from_slice(b".sect");
|
||||
pe[h + 8..h + 12].copy_from_slice(&s.vsize.to_le_bytes());
|
||||
pe[h + 12..h + 16].copy_from_slice(&s.va.to_le_bytes());
|
||||
pe[h + 16..h + 20].copy_from_slice(&s.raw_size.to_le_bytes());
|
||||
pe[h + 20..h + 24].copy_from_slice(&s.raw_ptr.to_le_bytes());
|
||||
pe[h + 36..h + 40].copy_from_slice(&s.flags.to_le_bytes());
|
||||
}
|
||||
pe
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_image_parses_maps_and_translates() {
|
||||
let bytes = build(112, 0x1010, &valid_sections());
|
||||
let pe = ParsedPe::parse(&bytes).expect("valid image");
|
||||
assert_eq!(pe.entry_point_rva, 0x1010);
|
||||
assert_eq!(pe.sections.len(), 2);
|
||||
assert_eq!(pe.rva_to_file_offset(0x1010), Some(0x210));
|
||||
assert_eq!(pe.rva_to_file_offset(0x2004), Some(0x404));
|
||||
assert_eq!(pe.rva_to_file_offset(0x3000), None);
|
||||
let loaded = pe.load_into_memory(&bytes).expect("load");
|
||||
assert_eq!(loaded.entry_point, 0x1_4000_1010);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optional_header_with_data_directories_is_accepted() {
|
||||
let bytes = build(240, 0x1000, &valid_sections());
|
||||
assert!(ParsedPe::parse(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_fixtures_still_parse_and_load() {
|
||||
let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../..");
|
||||
for path in [
|
||||
"fixtures/pe/trusted-runner.exe",
|
||||
"experiments/x1/fixtures/x2.exe",
|
||||
"experiments/x1/fixtures/x3.exe",
|
||||
"experiments/x1/fixtures/x4-17.exe",
|
||||
"experiments/x1/fixtures/x4-93.exe",
|
||||
"experiments/x1/fixtures/x5.exe",
|
||||
"experiments/x1/fixtures/x6.exe",
|
||||
] {
|
||||
let bytes = std::fs::read(format!("{root}/{path}")).expect(path);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap_or_else(|e| panic!("{path}: {e}"));
|
||||
pe.load_into_memory(&bytes)
|
||||
.unwrap_or_else(|e| panic!("{path}: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Reproducer from #79: 90 bytes, SizeOfOptionalHeader = 2, file ends after the magic.
|
||||
#[test]
|
||||
fn truncated_optional_header_is_rejected_not_panicking() {
|
||||
let mut bytes = vec![0u8; 90];
|
||||
bytes[0..2].copy_from_slice(b"MZ");
|
||||
bytes[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
bytes[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
bytes[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
bytes[0x54..0x56].copy_from_slice(&2u16.to_le_bytes());
|
||||
bytes[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
assert_eq!(ParsedPe::parse(&bytes).unwrap_err(), PeError::TooSmall);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optional_header_shorter_than_pe32_plus_fixed_fields_is_rejected() {
|
||||
for opt_size in [24u16, 64, 111] {
|
||||
let bytes = build(opt_size, 0x1000, &valid_sections());
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::TooSmall,
|
||||
"{opt_size}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn e_lfanew_past_end_of_file_is_rejected() {
|
||||
let mut bytes = build(112, 0x1000, &valid_sections());
|
||||
bytes[0x3C..0x40].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert_eq!(ParsedPe::parse(&bytes).unwrap_err(), PeError::TooSmall);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn section_table_past_end_of_file_is_rejected() {
|
||||
let mut bytes = build(112, 0x1000, &valid_sections());
|
||||
bytes[0x46..0x48].copy_from_slice(&u16::MAX.to_le_bytes());
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::InvalidSectionHeaders
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn section_range_overflowing_rva_space_is_rejected() {
|
||||
let mut secs = valid_sections();
|
||||
secs[1].va = 0xFFFF_F000;
|
||||
secs[1].vsize = 0x2000;
|
||||
let bytes = build(112, 0x1000, &secs);
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::InvalidSectionHeaders
|
||||
);
|
||||
}
|
||||
|
||||
/// Reproducer from #79: lookup over a section whose end overflows u32 must not panic or wrap.
|
||||
#[test]
|
||||
fn rva_lookup_with_overflowing_section_returns_none() {
|
||||
let bytes = build(112, 0x1000, &valid_sections());
|
||||
let mut pe = ParsedPe::parse(&bytes).unwrap();
|
||||
pe.sections.insert(
|
||||
0,
|
||||
PeSection {
|
||||
name: "wrap".into(),
|
||||
virtual_address: 0xFFFF_FF00,
|
||||
virtual_size: 0x200,
|
||||
raw_data_ptr: 0x200,
|
||||
raw_data_size: 0x200,
|
||||
characteristics: R,
|
||||
permissions: pe.sections[1].permissions,
|
||||
},
|
||||
);
|
||||
// A wrapped end (0xFFFF_FF00 + 0x200 = 0x100) would wrongly capture RVA 0x80.
|
||||
assert_eq!(pe.rva_to_file_offset(0x80), None);
|
||||
assert_eq!(pe.rva_to_file_offset(0xFFFF_FF10), Some(0x210));
|
||||
assert_eq!(pe.rva_to_file_offset(0x1004), Some(0x204));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_sections_are_rejected() {
|
||||
let mut secs = valid_sections();
|
||||
secs[1].va = 0x1100; // .text maps 0x1000..0x1200 (raw size wins)
|
||||
let bytes = build(112, 0x1000, &secs);
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::InvalidSectionHeaders
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_sections_are_accepted() {
|
||||
let mut secs = valid_sections();
|
||||
secs[1].va = 0x1200;
|
||||
let bytes = build(112, 0x1000, &secs);
|
||||
assert!(ParsedPe::parse(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_section_data_is_rejected() {
|
||||
let mut secs = valid_sections();
|
||||
secs[1].raw_size = 0x201; // file is 0x600 bytes; 0x400 + 0x201 runs one byte past the end
|
||||
let bytes = build(112, 0x1000, &secs);
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::InvalidSectionHeaders
|
||||
);
|
||||
|
||||
secs[1].raw_size = 0x200;
|
||||
secs[1].raw_ptr = u32::MAX;
|
||||
let bytes = build(112, 0x1000, &secs);
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::InvalidSectionHeaders
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_point_outside_executable_section_is_rejected() {
|
||||
// Past the end of .text's mapped range, in non-executable .rdata, and outside every section.
|
||||
for entry in [0x1200, 0x2000, 0x0, u32::MAX] {
|
||||
let bytes = build(112, entry, &valid_sections());
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::InvalidEntryPoint,
|
||||
"entry {entry:#x}"
|
||||
);
|
||||
}
|
||||
// Last byte of .text is still inside it.
|
||||
assert!(ParsedPe::parse(&build(112, 0x11FF, &valid_sections())).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CFG-aware probe regression tests for Xenora X16.
|
||||
//!
|
||||
//! These tests verify that the control-flow-aware disassembly only reports
|
||||
//! instructions that are actually reachable from the entry point, rather
|
||||
//! than linearly sweeping through unreachable padding bytes.
|
||||
|
||||
use xenora_loader::probe::{ProbeConfig, probe_pe_bytes};
|
||||
|
||||
/// Minimal PE32+ builder for CFG tests.
|
||||
/// Returns a 4096-byte file with one executable .text section at RVA 0x1000,
|
||||
/// raw offset 0x200, raw size 0x200.
|
||||
struct PeBuilder {
|
||||
bytes: Vec<u8>,
|
||||
text_start: usize, // raw offset of .text
|
||||
}
|
||||
|
||||
impl PeBuilder {
|
||||
fn new() -> Self {
|
||||
let mut pe = vec![0u8; 4096];
|
||||
// MZ header
|
||||
pe[0] = b'M';
|
||||
pe[1] = b'Z';
|
||||
pe[0x3c] = 0x80; // e_lfanew = 0x80
|
||||
|
||||
let pe_sig = 0x80;
|
||||
pe[pe_sig..pe_sig + 4].copy_from_slice(b"PE\0\0");
|
||||
|
||||
let coff = pe_sig + 4;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes()); // AMD64
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&1u16.to_le_bytes()); // 1 section
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes()); // opt header size
|
||||
|
||||
let opt = coff + 20;
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020bu16.to_le_bytes()); // PE32+
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes()); // entry RVA
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&0x140000000u64.to_le_bytes()); // image base
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes()); // section align
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes()); // file align
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x2000u32.to_le_bytes()); // size of image
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x400u32.to_le_bytes()); // size of headers
|
||||
pe[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes()); // num data dirs
|
||||
|
||||
// Section header: .text — RVA 0x1000, raw offset 0x200, raw size 0x200
|
||||
let sec = opt + 240;
|
||||
pe[sec..sec + 5].copy_from_slice(b".text");
|
||||
pe[sec + 8..sec + 12].copy_from_slice(&0x200u32.to_le_bytes()); // virtual size
|
||||
pe[sec + 12..sec + 16].copy_from_slice(&0x1000u32.to_le_bytes()); // virtual addr
|
||||
pe[sec + 16..sec + 20].copy_from_slice(&0x200u32.to_le_bytes()); // raw size
|
||||
pe[sec + 20..sec + 24].copy_from_slice(&0x200u32.to_le_bytes()); // raw ptr
|
||||
// Characteristics: CNT_CODE | MEM_EXECUTE | MEM_READ
|
||||
pe[sec + 36..sec + 40].copy_from_slice(&0x60000020u32.to_le_bytes());
|
||||
|
||||
PeBuilder {
|
||||
bytes: pe,
|
||||
text_start: 0x200,
|
||||
}
|
||||
}
|
||||
|
||||
/// Write instruction bytes at an offset within the .text section.
|
||||
/// `text_off` is relative to the start of the .text section (raw offset 0x200).
|
||||
fn write_text(&mut self, text_off: usize, insns: &[u8]) {
|
||||
let start = self.text_start + text_off;
|
||||
self.bytes[start..start + insns.len()].copy_from_slice(insns);
|
||||
}
|
||||
|
||||
fn build(self) -> Vec<u8> {
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// Test: an unconditional JMP over an INT3 means the INT3 is unreachable.
|
||||
/// The CFG-aware probe must NOT report the INT3 as the first DBT blocker.
|
||||
/// The reachable destination (a MOV then HLT) has no unsupported DBT instructions.
|
||||
#[test]
|
||||
fn cfg_unreachable_int3_after_jmp_not_reported_as_blocker() {
|
||||
// Layout at RVA 0x1000 (text_off 0):
|
||||
// 0x1000: EB 05 JMP +5 (jump to 0x1007)
|
||||
// 0x1002: CC INT3 (unreachable padding)
|
||||
// 0x1003: CC INT3 (unreachable padding)
|
||||
// 0x1004: CC INT3 (unreachable padding)
|
||||
// 0x1005: CC INT3 (unreachable padding)
|
||||
// 0x1006: CC INT3 (unreachable padding)
|
||||
// 0x1007: 48 89 C8 MOV RAX, RCX (REX.W + MOV r/m, reg — reg-to-reg, DBT supported)
|
||||
// 0x100A: F4 HLT
|
||||
let mut b = PeBuilder::new();
|
||||
b.write_text(
|
||||
0,
|
||||
&[
|
||||
0xEB, 0x05, // JMP to 0x1007 (EB 05 = short JMP, skip 5 bytes)
|
||||
0xCC, 0xCC, 0xCC, 0xCC, 0xCC, // 5x INT3 (unreachable)
|
||||
0x48, 0x89, 0xC8, // MOV RAX, RCX (reg-reg, DBT ok)
|
||||
0xF4, // HLT
|
||||
],
|
||||
);
|
||||
let pe = b.build();
|
||||
let config = ProbeConfig::default();
|
||||
let report = probe_pe_bytes(&pe, &config).expect("probe must succeed");
|
||||
|
||||
// The CFG-aware probe must not report the INT3 as a blocker because it is
|
||||
// only reachable via linear sweep, not via control flow from the entry.
|
||||
assert!(
|
||||
report.first_unsupported_dbt_insn.is_none(),
|
||||
"no DBT blocker expected; got {:?}",
|
||||
report.first_unsupported_dbt_insn
|
||||
);
|
||||
|
||||
// Exactly the reachable instructions should appear: JMP, MOV, HLT.
|
||||
let rvas: Vec<u32> = report.instruction_records.iter().map(|r| r.rva).collect();
|
||||
assert!(rvas.contains(&0x1000), "JMP at 0x1000 must be recorded");
|
||||
assert!(rvas.contains(&0x1007), "MOV at 0x1007 must be recorded");
|
||||
assert!(rvas.contains(&0x100A), "HLT at 0x100A must be recorded");
|
||||
// None of the INT3 RVAs should appear
|
||||
for int3_rva in [0x1002u32, 0x1003, 0x1004, 0x1005, 0x1006] {
|
||||
assert!(
|
||||
!rvas.contains(&int3_rva),
|
||||
"INT3 at 0x{int3_rva:04x} must not appear in reachable records"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Test: a reachable unsupported instruction IS reported as the first DBT blocker.
|
||||
/// Here the entry directly contains an unsupported opcode (0x0F 0x05 = SYSCALL).
|
||||
#[test]
|
||||
fn cfg_reachable_unsupported_insn_is_reported() {
|
||||
// Layout:
|
||||
// 0x1000: 0F 05 SYSCALL (unsupported two-byte opcode)
|
||||
// 0x1002: F4 HLT
|
||||
let mut b = PeBuilder::new();
|
||||
b.write_text(0, &[0x0F, 0x05, 0xF4]);
|
||||
let pe = b.build();
|
||||
let config = ProbeConfig::default();
|
||||
let report = probe_pe_bytes(&pe, &config).expect("probe must succeed");
|
||||
|
||||
let blocker = report
|
||||
.first_unsupported_dbt_insn
|
||||
.expect("SYSCALL must be reported as unsupported DBT blocker");
|
||||
assert_eq!(blocker.rva, 0x1000, "blocker must be at the entry RVA");
|
||||
}
|
||||
|
||||
/// Test: a direct CALL follows the call target AND continues with the fall-through.
|
||||
/// The call target has an unsupported instruction; the fall-through (after CALL) has HLT.
|
||||
/// Both should appear in the records because CALL adds both paths to the worklist.
|
||||
#[test]
|
||||
fn cfg_direct_call_visits_target_and_continuation() {
|
||||
// Layout:
|
||||
// 0x1000: E8 05 00 00 00 CALL 0x100A (5-byte CALL rel32, target = 0x1000+5+5 = 0x100A)
|
||||
// 0x1005: F4 HLT (fall-through / return site)
|
||||
// 0x1006: CC INT3 (padding after HLT, unreachable)
|
||||
// 0x1007: CC INT3 (unreachable)
|
||||
// 0x1008: CC INT3 (unreachable)
|
||||
// 0x1009: CC INT3 (unreachable)
|
||||
// 0x100A: 0F 05 SYSCALL (call target — unsupported)
|
||||
// 0x100C: C3 RET
|
||||
let mut b = PeBuilder::new();
|
||||
b.write_text(
|
||||
0,
|
||||
&[
|
||||
0xE8, 0x05, 0x00, 0x00, 0x00, // CALL 0x100A (rel32 = 5)
|
||||
0xF4, // HLT at 0x1005
|
||||
0xCC, 0xCC, 0xCC, 0xCC, // INT3 padding, unreachable
|
||||
0x0F, 0x05, // SYSCALL at 0x100A (unsupported)
|
||||
0xC3, // RET
|
||||
],
|
||||
);
|
||||
let pe = b.build();
|
||||
let config = ProbeConfig::default();
|
||||
let report = probe_pe_bytes(&pe, &config).expect("probe must succeed");
|
||||
|
||||
let rvas: Vec<u32> = report.instruction_records.iter().map(|r| r.rva).collect();
|
||||
|
||||
// CALL itself must appear
|
||||
assert!(rvas.contains(&0x1000), "CALL at 0x1000 must be recorded");
|
||||
// Fall-through (HLT at 0x1005) must appear
|
||||
assert!(
|
||||
rvas.contains(&0x1005),
|
||||
"HLT at 0x1005 (fall-through) must be recorded"
|
||||
);
|
||||
// Call target (SYSCALL at 0x100A) must appear
|
||||
assert!(
|
||||
rvas.contains(&0x100A),
|
||||
"SYSCALL at 0x100A (call target) must be recorded; rvas={rvas:?}"
|
||||
);
|
||||
|
||||
// The unsupported instruction must be reported as a blocker
|
||||
assert!(
|
||||
report.first_unsupported_dbt_insn.is_some(),
|
||||
"SYSCALL must be the first DBT blocker"
|
||||
);
|
||||
}
|
||||
|
||||
/// Test: a conditional branch visits both the taken target and the not-taken fall-through.
|
||||
#[test]
|
||||
fn cfg_conditional_branch_visits_both_targets() {
|
||||
// Layout:
|
||||
// 0x1000: 74 05 JZ +5 (taken → 0x1007, not-taken → 0x1002)
|
||||
// 0x1002: 48 89 C8 MOV RAX, RCX (not-taken path, DBT ok)
|
||||
// 0x1005: F4 HLT
|
||||
// 0x1006: CC INT3 (padding after fall-through HLT, unreachable)
|
||||
// 0x1007: 48 31 C0 XOR RAX, RAX (taken path)
|
||||
// 0x100A: F4 HLT
|
||||
let mut b = PeBuilder::new();
|
||||
b.write_text(
|
||||
0,
|
||||
&[
|
||||
0x74, 0x05, // JZ to 0x1007 (rel8 = 5, insn is 2 bytes)
|
||||
0x48, 0x89, 0xC8, // MOV RAX, RCX at 0x1002
|
||||
0xF4, // HLT at 0x1005
|
||||
0xCC, // INT3 at 0x1006 (unreachable — after HLT)
|
||||
0x48, 0x31, 0xC0, // XOR RAX, RAX at 0x1007 (taken path)
|
||||
0xF4, // HLT at 0x100A
|
||||
],
|
||||
);
|
||||
let pe = b.build();
|
||||
let config = ProbeConfig::default();
|
||||
let report = probe_pe_bytes(&pe, &config).expect("probe must succeed");
|
||||
|
||||
let rvas: Vec<u32> = report.instruction_records.iter().map(|r| r.rva).collect();
|
||||
|
||||
// Both the taken (0x1007) and not-taken (0x1002) paths must be visited
|
||||
assert!(rvas.contains(&0x1000), "JZ at 0x1000 must be recorded");
|
||||
assert!(
|
||||
rvas.contains(&0x1002),
|
||||
"not-taken path at 0x1002 must be recorded"
|
||||
);
|
||||
assert!(
|
||||
rvas.contains(&0x1007),
|
||||
"taken path at 0x1007 must be recorded"
|
||||
);
|
||||
|
||||
// No DBT blockers in this fixture
|
||||
assert!(
|
||||
report.first_unsupported_dbt_insn.is_none(),
|
||||
"no DBT blocker expected; got {:?}",
|
||||
report.first_unsupported_dbt_insn
|
||||
);
|
||||
|
||||
// INT3 at 0x1006 is unreachable (after HLT on not-taken path)
|
||||
assert!(
|
||||
!rvas.contains(&0x1006),
|
||||
"INT3 at 0x1006 is unreachable and must not appear"
|
||||
);
|
||||
}
|
||||
|
||||
/// Test: an indirect JMP stops that CFG path (target uncertain) so bytes
|
||||
/// immediately following it are not reported as reachable.
|
||||
#[test]
|
||||
fn cfg_indirect_jmp_stops_path_target_uncertain() {
|
||||
// Layout:
|
||||
// 0x1000: FF 25 00 00 00 00 JMP QWORD PTR [RIP+0] (indirect JMP via IAT)
|
||||
// 0x1006: CC INT3 (after the indirect JMP — unreachable from entry)
|
||||
// 0x1007: F4 HLT (also unreachable)
|
||||
let mut b = PeBuilder::new();
|
||||
b.write_text(
|
||||
0,
|
||||
&[
|
||||
0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, // JMP *[RIP+0] — 6 bytes
|
||||
0xCC, // INT3 (unreachable after indirect JMP)
|
||||
0xF4, // HLT (unreachable)
|
||||
],
|
||||
);
|
||||
let pe = b.build();
|
||||
let config = ProbeConfig::default();
|
||||
let report = probe_pe_bytes(&pe, &config).expect("probe must succeed");
|
||||
|
||||
let rvas: Vec<u32> = report.instruction_records.iter().map(|r| r.rva).collect();
|
||||
|
||||
// The indirect JMP itself is recorded (it's reachable from the entry)
|
||||
assert!(
|
||||
rvas.contains(&0x1000),
|
||||
"indirect JMP at 0x1000 must be recorded"
|
||||
);
|
||||
|
||||
// The INT3 and HLT after it must NOT appear (the indirect JMP stops the path)
|
||||
assert!(
|
||||
!rvas.contains(&0x1006),
|
||||
"INT3 at 0x1006 must not appear (after indirect JMP)"
|
||||
);
|
||||
assert!(
|
||||
!rvas.contains(&0x1007),
|
||||
"HLT at 0x1007 must not appear (after indirect JMP)"
|
||||
);
|
||||
}
|
||||
|
||||
/// Test: malformed / truncated instruction stream at the boundary of the section
|
||||
/// does not panic and does not report beyond the available bytes.
|
||||
#[test]
|
||||
fn cfg_malformed_truncated_at_section_boundary() {
|
||||
// REX prefix at the last byte — no opcode follows.
|
||||
let mut b = PeBuilder::new();
|
||||
b.write_text(0, &[0x48]); // just a REX prefix, no opcode
|
||||
let pe = b.build();
|
||||
let config = ProbeConfig::default();
|
||||
// Must not panic; probe may return Ok with empty or partial records
|
||||
let result = probe_pe_bytes(&pe, &config);
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"truncated stream must not cause a probe error"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Tests for Xenora X14.5 non-executing PE compatibility probe.
|
||||
|
||||
use xenora_loader::pe::{IMAGE_SCN_CNT_CODE, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ};
|
||||
use xenora_loader::probe::{ProbeConfig, probe_pe_bytes, run_probe_and_export};
|
||||
|
||||
fn create_synthetic_probe_pe() -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 1024];
|
||||
// MZ header
|
||||
pe[0] = b'M';
|
||||
pe[1] = b'Z';
|
||||
// e_lfanew = 0x80
|
||||
pe[0x3c] = 0x80;
|
||||
|
||||
let pe_sig = 0x80;
|
||||
pe[pe_sig..pe_sig + 4].copy_from_slice(b"PE\0\0");
|
||||
|
||||
let coff = pe_sig + 4;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes()); // AMD64
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&1u16.to_le_bytes()); // 1 section
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes()); // opt header size
|
||||
|
||||
let opt = coff + 20; // 0x80 + 24 = 0x98
|
||||
pe[opt..opt + 2].copy_from_slice(&0x20bu16.to_le_bytes()); // PE32+
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes()); // entry point RVA = 0x1000
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&0x140000000u64.to_le_bytes()); // image base
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes()); // section alignment
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes()); // file alignment
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x2000u32.to_le_bytes()); // size of image
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x400u32.to_le_bytes()); // size of headers
|
||||
pe[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes()); // number of rva and sizes
|
||||
|
||||
// Section header at opt + 240 = 0x98 + 240 = 0x188
|
||||
let sec = opt + 240;
|
||||
pe[sec..sec + 5].copy_from_slice(b".text");
|
||||
pe[sec + 8..sec + 12].copy_from_slice(&0x200u32.to_le_bytes()); // virtual size
|
||||
pe[sec + 12..sec + 16].copy_from_slice(&0x1000u32.to_le_bytes()); // virtual address
|
||||
pe[sec + 16..sec + 20].copy_from_slice(&0x200u32.to_le_bytes()); // raw data size
|
||||
pe[sec + 20..sec + 24].copy_from_slice(&0x200u32.to_le_bytes()); // raw data pointer (offset 0x200)
|
||||
let chars = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ;
|
||||
pe[sec + 36..sec + 40].copy_from_slice(&chars.to_le_bytes());
|
||||
|
||||
// Place instructions in .text at raw offset 0x200:
|
||||
// 48 83 ec 28 : sub rsp, 0x28
|
||||
// 48 89 5c 24 20 : mov [rsp + 0x20], rbx (SIB store, now DBT-supported)
|
||||
// c3 : ret
|
||||
pe[0x200..0x204].copy_from_slice(&[0x48, 0x83, 0xec, 0x28]);
|
||||
pe[0x204..0x209].copy_from_slice(&[0x48, 0x89, 0x5c, 0x24, 0x20]);
|
||||
pe[0x209] = 0xc3;
|
||||
|
||||
pe
|
||||
}
|
||||
|
||||
fn create_synthetic_probe_pe_with_unsupported_op() -> Vec<u8> {
|
||||
let mut pe = create_synthetic_probe_pe();
|
||||
// Replace the SIB store slot with INT3: the native DBT returns
|
||||
// ExitReason::IllegalInstruction for it, so it is genuinely unsupported
|
||||
// and must keep being reported as a startup blocker.
|
||||
pe[0x204..0x209].copy_from_slice(&[0xCC, 0x90, 0x90, 0x90, 0x90]);
|
||||
pe
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_probe_static_analysis_does_not_execute_code() {
|
||||
let pe_bytes = create_synthetic_probe_pe();
|
||||
let config = ProbeConfig::default();
|
||||
|
||||
let report = probe_pe_bytes(&pe_bytes, &config).expect("probe should succeed");
|
||||
|
||||
assert_eq!(report.parsed.sections.len(), 1);
|
||||
assert_eq!(report.parsed.entry_point_rva, 0x1000);
|
||||
assert_eq!(report.parsed.image_base, 0x140000000);
|
||||
|
||||
// The SIB store `mov [rsp + 0x20], rbx` at RVA 0x1004 is supported by the
|
||||
// native DBT (verified by the DBT execution test
|
||||
// `dbt::tests::sib_store_executes_through_the_native_dbt`), so the static
|
||||
// probe reports no blocker for this program.
|
||||
assert!(report.first_unsupported_dbt_insn.is_none());
|
||||
|
||||
let sib_store = report
|
||||
.instruction_records
|
||||
.iter()
|
||||
.find(|record| record.rva == 0x1004)
|
||||
.expect("SIB store decoded at RVA 0x1004");
|
||||
assert_eq!(sib_store.bytes, vec![0x48, 0x89, 0x5c, 0x24, 0x20]);
|
||||
assert!(sib_store.is_supported_dbt);
|
||||
assert!(sib_store.is_supported_interp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_probe_static_analysis_detects_genuinely_unsupported_instruction() {
|
||||
let pe_bytes = create_synthetic_probe_pe_with_unsupported_op();
|
||||
let report = probe_pe_bytes(&pe_bytes, &ProbeConfig::default()).expect("probe should succeed");
|
||||
|
||||
let blocker = report
|
||||
.first_unsupported_dbt_insn
|
||||
.expect("blocker must be detected");
|
||||
assert_eq!(blocker.rva, 0x1004);
|
||||
assert_eq!(blocker.bytes, vec![0xCC]);
|
||||
assert_eq!(blocker.mnemonic, "int3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_probe_artifact_export_creates_all_files() {
|
||||
let pe_bytes = create_synthetic_probe_pe();
|
||||
let temp_dir = std::env::temp_dir().join("xenora_probe_test_export");
|
||||
let _ = std::fs::remove_dir_all(&temp_dir);
|
||||
|
||||
let config = ProbeConfig::default();
|
||||
let report =
|
||||
run_probe_and_export(&pe_bytes, &temp_dir, &config).expect("export should succeed");
|
||||
|
||||
assert!(temp_dir.join("candidate_static_report.md").exists());
|
||||
assert!(temp_dir.join("candidate_static_report.json").exists());
|
||||
assert!(temp_dir.join("imports.csv").exists());
|
||||
assert!(temp_dir.join("missing_imports.csv").exists());
|
||||
assert!(temp_dir.join("cpu_coverage.csv").exists());
|
||||
assert!(temp_dir.join("runtime_gap_matrix.md").exists());
|
||||
assert!(temp_dir.join("x15_priority_backlog.md").exists());
|
||||
assert!(temp_dir.join("test_commands.txt").exists());
|
||||
|
||||
assert_eq!(report.parsed.sections.len(), 1);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&temp_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_hashes_the_entire_input() {
|
||||
let mut bytes = create_synthetic_probe_pe();
|
||||
let config = ProbeConfig::default();
|
||||
let first = probe_pe_bytes(&bytes, &config).unwrap();
|
||||
bytes.push(42);
|
||||
let second = probe_pe_bytes(&bytes, &config).unwrap();
|
||||
assert_eq!(
|
||||
first.sha256,
|
||||
"72f97ed9d24af84928a313d4c47bfedae0c46e38fab265b3bb8d922566d816f9"
|
||||
);
|
||||
assert_eq!(
|
||||
second.sha256,
|
||||
"7da76a9dfe391814ed41c01417c00b85ab2e9d122d1b0e56e45d39ad4e81df30"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_distinguishes_aliases_from_unavailable_services() {
|
||||
use xenora_loader::imports::ServiceStatus;
|
||||
|
||||
let mut pe = create_synthetic_probe_pe();
|
||||
// Import directory in the fixture's file-backed section at RVA 0x1040.
|
||||
pe[0x110..0x114].copy_from_slice(&0x1040u32.to_le_bytes());
|
||||
pe[0x114..0x118].copy_from_slice(&40u32.to_le_bytes());
|
||||
pe[0x240..0x244].copy_from_slice(&0x1120u32.to_le_bytes());
|
||||
pe[0x24c..0x250].copy_from_slice(&0x1090u32.to_le_bytes());
|
||||
pe[0x250..0x254].copy_from_slice(&0x1160u32.to_le_bytes());
|
||||
let dll = b"API-MS-WIN-CORE-PROCESSTHREADS-L1-1-0.DLL";
|
||||
pe[0x290..0x290 + dll.len()].copy_from_slice(dll);
|
||||
|
||||
for (index, (rva, name)) in [
|
||||
(0x1180u64, "GetCurrentProcess"),
|
||||
(0x11a0u64, "CreateThread"),
|
||||
(0x11c0u64, "getcurrentprocess"),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let offset = 0x320 + index * 8;
|
||||
pe[offset..offset + 8].copy_from_slice(&rva.to_le_bytes());
|
||||
let name_offset = 0x200 + (rva as usize - 0x1000) + 2;
|
||||
pe[name_offset..name_offset + name.len()].copy_from_slice(name.as_bytes());
|
||||
}
|
||||
|
||||
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
|
||||
assert_eq!(report.imports.len(), 3);
|
||||
let [alias, unsupported, unknown] = report.imports.as_slice() else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!(alias.iat_rva, 0x1160);
|
||||
assert_eq!(alias.canonical_module.as_deref(), Some("kernel32.dll"));
|
||||
assert_eq!(alias.service_status, Some(ServiceStatus::Implemented));
|
||||
assert!(!unsupported.is_supported);
|
||||
assert!(!unknown.is_supported);
|
||||
assert_eq!(unsupported.iat_rva, 0x1168);
|
||||
assert_eq!(unknown.iat_rva, 0x1170);
|
||||
|
||||
let path = std::env::temp_dir().join(format!("xenora-probe-alias-{}", std::process::id()));
|
||||
run_probe_and_export(&pe, &path, &ProbeConfig::default()).unwrap();
|
||||
let csv = std::fs::read_to_string(path.join("imports.csv")).unwrap();
|
||||
assert!(csv.contains("true,implemented,true,\"kernel32.dll\",1"));
|
||||
assert!(csv.contains("false,unsupported,false,\"\",1"));
|
||||
assert!(csv.contains("false,missing,false,\"\",1"));
|
||||
let missing = std::fs::read_to_string(path.join("missing_imports.csv")).unwrap();
|
||||
assert_eq!(missing.lines().count(), 3);
|
||||
assert!(!missing.contains("GetCurrentProcess"));
|
||||
let json = std::fs::read_to_string(path.join("candidate_static_report.json")).unwrap();
|
||||
assert!(json.contains("\"distinct_import_keys\": 3"));
|
||||
assert!(json.contains("\"canonical_registered_services\": 1"));
|
||||
assert!(json.contains("\"unresolved_imports\": 2"));
|
||||
assert!(json.contains("\"recognized_unsupported_slots\": 1"));
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trusted_runner_callback_and_report_match_the_fixture() {
|
||||
let pe = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
let path = std::env::temp_dir().join(format!("xenora-probe-trusted-{}", std::process::id()));
|
||||
let report = run_probe_and_export(pe, &path, &ProbeConfig::default()).unwrap();
|
||||
let read = |name| std::fs::read_to_string(path.join(name)).unwrap();
|
||||
let md = read("candidate_static_report.md");
|
||||
let json = read("candidate_static_report.json");
|
||||
let imports = read("imports.csv");
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
|
||||
let callback: Vec<_> = report
|
||||
.instruction_records
|
||||
.iter()
|
||||
.filter(|i| i.rva >= 0x1040)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
callback.iter().map(|i| i.rva).collect::<Vec<_>>(),
|
||||
[0x1040, 0x1047, 0x104e]
|
||||
);
|
||||
assert_eq!(callback[1].bytes, [0x48, 0xc7, 0, 17, 0, 0, 0]);
|
||||
assert!(callback[1].is_supported_dbt);
|
||||
assert!(!callback[1].is_supported_interp);
|
||||
assert!(report.first_unsupported_dbt_insn.is_none());
|
||||
assert!(md.contains("Sections Census (4)"));
|
||||
assert!(json.contains("\"sections_count\": 4"));
|
||||
assert!(!report.imports[0].is_supported);
|
||||
assert!(
|
||||
imports
|
||||
.lines()
|
||||
.any(|line| line.contains("fixture_draw") && line.ends_with(",true"))
|
||||
);
|
||||
assert!(json.contains("\"trusted_runner_binding_slots\": 1"));
|
||||
assert!(json.contains("\"unresolved_imports\": 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_consumes_complete_c7_operands_even_when_native_support_is_missing() {
|
||||
for (encoding, supported) in [
|
||||
(&[0x48, 0xc7, 0x05, 0, 0, 0, 0, 17, 0, 0, 0][..], true),
|
||||
(&[0xc7, 0xc0, 17, 0, 0, 0], true),
|
||||
(&[0x66, 0xc7, 0xc0, 17, 0], false),
|
||||
(&[0xc7, 0x00, 17, 0, 0, 0], false),
|
||||
(&[0x48, 0xc7, 0x40, 4, 17, 0, 0, 0], false),
|
||||
(&[0x48, 0xc7, 0x04, 0x25, 0, 0, 0, 0, 17, 0, 0, 0], false),
|
||||
] {
|
||||
let mut pe = create_synthetic_probe_pe();
|
||||
let end = 0x200 + encoding.len();
|
||||
pe[0x200..end].copy_from_slice(encoding);
|
||||
pe[end] = 0xcc;
|
||||
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
|
||||
let records = report.instruction_records;
|
||||
assert_eq!(records.len(), 2);
|
||||
assert_eq!(records[0].bytes, encoding);
|
||||
assert_eq!(records[0].is_supported_dbt, supported);
|
||||
assert_eq!(records[1].rva, 0x1000 + encoding.len() as u32);
|
||||
assert!(!records[1].is_supported_dbt);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exported_reports_agree_across_fixtures_and_blocker_locations() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("xenora-report-consistency-{}", std::process::id()));
|
||||
// (file offset, RVA) for a reachable instruction immediately after a MOV.
|
||||
for (fixture, file_offset, rva, sections, imports) in [
|
||||
(create_synthetic_probe_pe(), 0x209, 0x1009_u32, 1, 0),
|
||||
(
|
||||
include_bytes!("../../../fixtures/pe/trusted-runner.exe").to_vec(),
|
||||
0x44e,
|
||||
0x104e,
|
||||
4,
|
||||
1,
|
||||
),
|
||||
] {
|
||||
assert_eq!(fixture[file_offset], 0xc3);
|
||||
for padding in [None, Some(0), Some(1), Some(7)] {
|
||||
let mut pe = fixture.clone();
|
||||
let blocker = padding.map(|n| {
|
||||
pe[file_offset..file_offset + n].fill(0x90);
|
||||
pe[file_offset + n] = 0xcc;
|
||||
rva + n as u32
|
||||
});
|
||||
run_probe_and_export(&pe, &dir, &ProbeConfig::default()).unwrap();
|
||||
let read = |name| std::fs::read_to_string(dir.join(name)).unwrap();
|
||||
let md = read("candidate_static_report.md");
|
||||
let json = read("candidate_static_report.json");
|
||||
let cpu = read("cpu_coverage.csv");
|
||||
let import_csv = read("imports.csv");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
|
||||
let json_field = |name: &str| {
|
||||
let prefix = format!("\"{name}\": ");
|
||||
json.lines()
|
||||
.find_map(|line| line.trim().strip_prefix(&prefix))
|
||||
.unwrap()
|
||||
.trim_end_matches(',')
|
||||
.trim_matches('"')
|
||||
};
|
||||
assert_eq!(json_field("sections_count"), sections.to_string());
|
||||
assert!(
|
||||
md.lines()
|
||||
.any(|line| line == format!("## Sections Census ({sections})"))
|
||||
);
|
||||
assert_eq!(
|
||||
md.lines()
|
||||
.filter(|line| line.contains(" VirtualSize: "))
|
||||
.count(),
|
||||
sections
|
||||
);
|
||||
|
||||
assert_eq!(json_field("total_imports"), imports.to_string());
|
||||
assert!(
|
||||
md.lines()
|
||||
.any(|line| line == format!("- **Total Imported Thunks**: `{imports}`"))
|
||||
);
|
||||
assert_eq!(import_csv.lines().skip(1).count(), imports);
|
||||
|
||||
let expected = blocker.map(|addr| format!("0x{addr:08x}"));
|
||||
assert_eq!(
|
||||
json_field("first_unsupported_dbt_rva"),
|
||||
expected.as_deref().unwrap_or("none")
|
||||
);
|
||||
let md_rvas: Vec<_> = md
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("- **RVA**: `")?
|
||||
.split_once('`')
|
||||
.map(|(addr, _)| addr)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(md_rvas, expected.iter().collect::<Vec<_>>());
|
||||
|
||||
// The first columns precede quoted fields. Read the support flags from
|
||||
// the closing quote of the mnemonic, which can itself contain commas.
|
||||
let mut unsupported = Vec::new();
|
||||
let mut tail = Vec::new();
|
||||
for row in cpu.lines().skip(1) {
|
||||
let (addr, rest) = row.split_once(',').unwrap();
|
||||
let (_, fields) = rest.split_once(",\"").unwrap();
|
||||
let (bytes, mnemonic) = fields.split_once("\",\"").unwrap();
|
||||
let (_, flags) = mnemonic.split_once("\",").unwrap();
|
||||
if flags.split(',').next() == Some("false") {
|
||||
unsupported.push(addr);
|
||||
}
|
||||
let address = u32::from_str_radix(addr.strip_prefix("0x").unwrap(), 16).unwrap();
|
||||
if address >= rva {
|
||||
tail.push((address, bytes));
|
||||
}
|
||||
}
|
||||
assert_eq!(unsupported, expected.iter().collect::<Vec<_>>());
|
||||
let mut expected_tail = Vec::new();
|
||||
if let Some(end) = blocker {
|
||||
expected_tail.extend((rva..end).map(|addr| (addr, "90")));
|
||||
expected_tail.push((end, "cc"));
|
||||
} else {
|
||||
expected_tail.push((rva, "c3"));
|
||||
}
|
||||
assert_eq!(tail, expected_tail);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Base relocation regression tests (#81).
|
||||
//!
|
||||
//! Images are built byte by byte from the PE/COFF layout: data directory 5
|
||||
//! (Base Relocation Table) at optional-header offset 152, and blocks made of a
|
||||
//! 4-byte page RVA, a 4-byte block size and 2-byte entries whose top 4 bits
|
||||
//! are the type (0 = ABSOLUTE padding, 3 = HIGHLOW, 10 = DIR64).
|
||||
|
||||
use xenora_loader::{GuestMemory, ParsedPe, RelocationError, apply_relocations};
|
||||
|
||||
const PREFERRED: u64 = 0x1_4000_0000;
|
||||
const RELOC_FILE: usize = 0x400;
|
||||
|
||||
/// .text at RVA 0x1000 (file 0x200) holding two pointers, .reloc at RVA 0x2000 (file 0x400).
|
||||
/// `NumberOfRvaAndSizes` and the relocation table bytes are parameters.
|
||||
fn build(rva_and_sizes: u32, table: &[u8], dir_size: u32) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x600];
|
||||
pe[0..2].copy_from_slice(b"MZ");
|
||||
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
let coff = 0x44;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&2u16.to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes());
|
||||
let opt = coff + 20;
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&PREFERRED.to_le_bytes());
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 108..opt + 112].copy_from_slice(&rva_and_sizes.to_le_bytes());
|
||||
pe[opt + 152..opt + 156].copy_from_slice(&0x2000u32.to_le_bytes());
|
||||
pe[opt + 156..opt + 160].copy_from_slice(&dir_size.to_le_bytes());
|
||||
|
||||
let sections: [(&[u8], u32, u32, u32, u32); 2] = [
|
||||
(b".text", 0x1000, 0x200, 0x200, 0x6000_0020),
|
||||
// .reloc fills the image up to SizeOfImage (0x3000).
|
||||
(b".reloc", 0x2000, 0x1000, RELOC_FILE as u32, 0x4200_0040),
|
||||
];
|
||||
for (i, (name, va, vsize, raw, flags)) in sections.into_iter().enumerate() {
|
||||
let h = opt + 240 + i * 40;
|
||||
pe[h..h + name.len()].copy_from_slice(name);
|
||||
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
|
||||
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
|
||||
pe[h + 16..h + 20].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
|
||||
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
|
||||
}
|
||||
|
||||
// Two absolute pointers into the image, at RVAs 0x1010 and 0x1018.
|
||||
pe[0x210..0x218].copy_from_slice(&(PREFERRED + 0x1100).to_le_bytes());
|
||||
pe[0x218..0x220].copy_from_slice(&(PREFERRED + 0x2000).to_le_bytes());
|
||||
pe[RELOC_FILE..RELOC_FILE + table.len()].copy_from_slice(table);
|
||||
pe
|
||||
}
|
||||
|
||||
fn block(page_rva: u32, entries: &[u16]) -> Vec<u8> {
|
||||
let mut b = page_rva.to_le_bytes().to_vec();
|
||||
b.extend_from_slice(&(8 + 2 * entries.len() as u32).to_le_bytes());
|
||||
for e in entries {
|
||||
b.extend_from_slice(&e.to_le_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// DIR64 at 0x1010 and 0x1018, plus one ABSOLUTE padding entry to keep 4-byte alignment.
|
||||
fn standard_table() -> Vec<u8> {
|
||||
block(0x1000, &[0xA010, 0xA018, 0x0000])
|
||||
}
|
||||
|
||||
fn load(bytes: &[u8], base: u64) -> (ParsedPe, GuestMemory) {
|
||||
let pe = ParsedPe::parse(bytes).expect("parse");
|
||||
let mut memory = GuestMemory::new();
|
||||
for s in &pe.sections {
|
||||
let raw = &bytes[s.raw_data_ptr as usize..(s.raw_data_ptr + s.raw_data_size) as usize];
|
||||
memory
|
||||
.map_region_with_data(
|
||||
base + u64::from(s.virtual_address),
|
||||
0x200,
|
||||
s.permissions,
|
||||
raw,
|
||||
)
|
||||
.expect("map");
|
||||
}
|
||||
(pe, memory)
|
||||
}
|
||||
|
||||
fn relocate(
|
||||
bytes: &[u8],
|
||||
base: u64,
|
||||
) -> (
|
||||
Result<xenora_loader::RelocationReport, RelocationError>,
|
||||
GuestMemory,
|
||||
) {
|
||||
let (pe, mut memory) = load(bytes, base);
|
||||
let result = apply_relocations(&pe, bytes, base, &mut memory);
|
||||
(result, memory)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positive_rebase_adds_delta_to_each_dir64_target() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1_0000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
let report = result.expect("relocate");
|
||||
assert_eq!(report.delta, 0x1_0000_0000);
|
||||
assert_eq!(report.applied_dir64, 2);
|
||||
assert_eq!(report.skipped_absolute, 1);
|
||||
assert_eq!(report.total_entries, 3);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
base + 0x1100
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1018).unwrap(),
|
||||
base + 0x2000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_rebase_subtracts_delta() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = 0x1000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
assert_eq!(
|
||||
result.expect("relocate").delta,
|
||||
base as i64 - PREFERRED as i64
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
base + 0x1100
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1018).unwrap(),
|
||||
base + 0x2000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_base_leaves_targets_unchanged() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, memory) = relocate(&bytes, PREFERRED);
|
||||
assert_eq!(result.expect("relocate").applied_dir64, 0);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(PREFERRED + 0x1010).unwrap(),
|
||||
PREFERRED + 0x1100
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_beyond_declared_count_is_ignored() {
|
||||
// NumberOfRvaAndSizes = 5 means directory index 5 does not exist.
|
||||
let table = standard_table();
|
||||
let bytes = build(5, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1_0000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
assert_eq!(result.expect("relocate").applied_dir64, 0);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
PREFERRED + 0x1100
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_type_is_rejected() {
|
||||
let table = block(0x1000, &[0x3010, 0x0000]); // HIGHLOW is not a PE32+ fixup here
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::UnsupportedRelocationType(3)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_block_sizes_are_rejected() {
|
||||
let base = PREFERRED + 0x1000;
|
||||
for size in [0u32, 4, 7, 11] {
|
||||
let mut table = 0x1000u32.to_le_bytes().to_vec();
|
||||
table.extend_from_slice(&size.to_le_bytes());
|
||||
table.extend_from_slice(&[0; 8]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, base);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::MalformedBlockHeader { offset: RELOC_FILE },
|
||||
"block size {size}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_larger_than_directory_is_rejected() {
|
||||
let table = standard_table(); // 14 bytes
|
||||
let bytes = build(16, &table, 12);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::BlockSizeOutOfBounds {
|
||||
block_size: 14,
|
||||
max_size: 12
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_partial_block_header_is_rejected() {
|
||||
let mut table = block(0x1000, &[0xA010, 0x0000]);
|
||||
table.extend_from_slice(&[0; 4]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::MalformedBlockHeader {
|
||||
offset: RELOC_FILE + 12
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_past_end_of_file_is_rejected() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, 0x300); // .reloc raw data starts at 0x400 in a 0x600-byte file
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::DirectoryOutOfBounds {
|
||||
rva: 0x2000,
|
||||
size: 0x300
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_outside_image_is_rejected_even_if_mapped() {
|
||||
// SizeOfImage is 0x3000; RVA 0x3000 is past the image but mapped by another region.
|
||||
let table = block(0x3000, &[0xA000, 0x0000]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1000;
|
||||
let (pe, mut memory) = load(&bytes, base);
|
||||
let rw = pe.sections[1].permissions;
|
||||
memory
|
||||
.map_region(base + 0x3000, 0x1000, rw)
|
||||
.expect("adjacent mapping");
|
||||
memory.write_u64_bypass(base + 0x3000, 0x55).unwrap();
|
||||
let result = apply_relocations(&pe, &bytes, base, &mut memory);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::TargetOutOfBounds {
|
||||
target_va: base + 0x3000
|
||||
}
|
||||
);
|
||||
assert_eq!(memory.read_u64_bypass(base + 0x3000).unwrap(), 0x55);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_rva_at_top_of_address_space_is_rejected() {
|
||||
let table = block(0xFFFF_F000, &[0xAFFC, 0x0000]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(RelocationError::TargetOutOfBounds { .. })
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,928 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! End-to-end integration tests for Xenora X15: Xbox Series-style Guest Runtime.
|
||||
//!
|
||||
//! Validates:
|
||||
//! 1. Fixture A: `win64_import_tls_startup` (DIR64 relocations at non-preferred base,
|
||||
//! two TLS callbacks, GetSystemTimeAsFileTime import, SIB stack store, indirect call,
|
||||
//! and clean guest exit).
|
||||
//! 2. Fixture B: `xmem_guest_allocator` (Xbox Scarlett memory allocator, guest address
|
||||
//! allocation and read/write validation).
|
||||
//! 3. Fixture C: IAT dispatch to a mock service and, with the GPU gate, native Metal readback.
|
||||
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::imports::ImportRegistry;
|
||||
use xenora_loader::memory::MemoryPermissions;
|
||||
use xenora_loader::pe::{
|
||||
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_CNT_CODE, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ,
|
||||
IMAGE_SCN_MEM_WRITE, PE32_PLUS_MAGIC, ParsedPe,
|
||||
};
|
||||
use xenora_loader::reloc::{IMAGE_REL_BASED_ABSOLUTE, IMAGE_REL_BASED_DIR64};
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
use xenora_loader::tls::TlsError;
|
||||
|
||||
/// Builder for synthetic PE32+ executables with optional sections (.text, .rdata, .data, .reloc, .tls).
|
||||
struct TestPeBuilder {
|
||||
image_base: u64,
|
||||
entry_point_rva: u32,
|
||||
code_bytes: Vec<u8>,
|
||||
reloc_entries: Vec<(u32, u8)>, // (page_rva + offset, type)
|
||||
tls_callbacks: Vec<u64>,
|
||||
import_thunks: Vec<(String, String)>, // (module, symbol)
|
||||
}
|
||||
|
||||
impl TestPeBuilder {
|
||||
fn new(image_base: u64, entry_point_rva: u32) -> Self {
|
||||
Self {
|
||||
image_base,
|
||||
entry_point_rva,
|
||||
code_bytes: Vec::new(),
|
||||
reloc_entries: Vec::new(),
|
||||
tls_callbacks: Vec::new(),
|
||||
import_thunks: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn code(mut self, code: &[u8]) -> Self {
|
||||
self.code_bytes = code.to_vec();
|
||||
self
|
||||
}
|
||||
|
||||
fn add_dir64_reloc(mut self, rva: u32) -> Self {
|
||||
self.reloc_entries.push((rva, IMAGE_REL_BASED_DIR64));
|
||||
self
|
||||
}
|
||||
|
||||
fn add_padding_reloc(mut self, rva: u32) -> Self {
|
||||
self.reloc_entries.push((rva, IMAGE_REL_BASED_ABSOLUTE));
|
||||
self
|
||||
}
|
||||
|
||||
fn add_tls_callback(mut self, cb_va: u64) -> Self {
|
||||
self.tls_callbacks.push(cb_va);
|
||||
self
|
||||
}
|
||||
|
||||
fn add_import(mut self, module: &str, symbol: &str) -> Self {
|
||||
self.import_thunks
|
||||
.push((module.to_string(), symbol.to_string()));
|
||||
self
|
||||
}
|
||||
|
||||
fn build(self) -> Vec<u8> {
|
||||
assert!(self.import_thunks.len() <= 2);
|
||||
let mut pe = vec![0u8; 4096]; // Section alignment 4096, headers in first 4096
|
||||
pe[0] = b'M';
|
||||
pe[1] = b'Z';
|
||||
pe[0x3C] = 0x80; // e_lfanew
|
||||
|
||||
let pe_sig = 0x80;
|
||||
pe[pe_sig..pe_sig + 4].copy_from_slice(b"PE\0\0");
|
||||
|
||||
let coff = pe_sig + 4;
|
||||
pe[coff..coff + 2].copy_from_slice(&IMAGE_FILE_MACHINE_AMD64.to_le_bytes());
|
||||
|
||||
// Determine sections: .text (RVA 0x1000), .rdata (RVA 0x2000), .reloc (RVA 0x3000)
|
||||
let num_sections = 3u16;
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&num_sections.to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes()); // opt header size with 16 data dirs
|
||||
|
||||
let opt = coff + 20;
|
||||
pe[opt..opt + 2].copy_from_slice(&PE32_PLUS_MAGIC.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&self.entry_point_rva.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&self.image_base.to_le_bytes());
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes()); // section alignment
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes()); // file alignment
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x4000u32.to_le_bytes()); // size of image (4 pages)
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x400u32.to_le_bytes()); // size of headers
|
||||
pe[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes()); // number of rva and sizes
|
||||
|
||||
// Data directory #1: Import Directory (RVA 0x2000, size 0x100)
|
||||
let import_dir_rva = if !self.import_thunks.is_empty() {
|
||||
0x2000u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let import_dir_size = if !self.import_thunks.is_empty() {
|
||||
0x100u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
pe[opt + 120..opt + 124].copy_from_slice(&import_dir_rva.to_le_bytes());
|
||||
pe[opt + 124..opt + 128].copy_from_slice(&import_dir_size.to_le_bytes());
|
||||
|
||||
// Data directory #5: Base Relocation Directory (RVA 0x3000)
|
||||
let reloc_dir_rva = if !self.reloc_entries.is_empty() {
|
||||
0x3000u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let reloc_block_size = (8 + self.reloc_entries.len() * 2) as u32;
|
||||
let reloc_dir_size = if !self.reloc_entries.is_empty() {
|
||||
reloc_block_size
|
||||
} else {
|
||||
0
|
||||
};
|
||||
pe[opt + 152..opt + 156].copy_from_slice(&reloc_dir_rva.to_le_bytes());
|
||||
pe[opt + 156..opt + 160].copy_from_slice(&reloc_dir_size.to_le_bytes());
|
||||
|
||||
// Data directory #9: TLS Directory (RVA 0x2100, size 40)
|
||||
let tls_dir_rva = if !self.tls_callbacks.is_empty() {
|
||||
0x2100u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let tls_dir_size = if !self.tls_callbacks.is_empty() {
|
||||
40u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
pe[opt + 184..opt + 188].copy_from_slice(&tls_dir_rva.to_le_bytes());
|
||||
pe[opt + 188..opt + 192].copy_from_slice(&tls_dir_size.to_le_bytes());
|
||||
|
||||
// Section Headers at opt + 240
|
||||
let sec_table = opt + 240;
|
||||
|
||||
// 1. .text (RVA 0x1000, raw ptr 0x400)
|
||||
let sec1 = sec_table;
|
||||
pe[sec1..sec1 + 5].copy_from_slice(b".text");
|
||||
pe[sec1 + 8..sec1 + 12].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[sec1 + 12..sec1 + 16].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[sec1 + 16..sec1 + 20].copy_from_slice(&0x400u32.to_le_bytes());
|
||||
pe[sec1 + 20..sec1 + 24].copy_from_slice(&0x400u32.to_le_bytes());
|
||||
let text_chars = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ;
|
||||
pe[sec1 + 36..sec1 + 40].copy_from_slice(&text_chars.to_le_bytes());
|
||||
|
||||
// 2. .rdata (RVA 0x2000, raw ptr 0x800)
|
||||
let sec2 = sec_table + 40;
|
||||
pe[sec2..sec2 + 6].copy_from_slice(b".rdata");
|
||||
pe[sec2 + 8..sec2 + 12].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[sec2 + 12..sec2 + 16].copy_from_slice(&0x2000u32.to_le_bytes());
|
||||
pe[sec2 + 16..sec2 + 20].copy_from_slice(&0x400u32.to_le_bytes());
|
||||
pe[sec2 + 20..sec2 + 24].copy_from_slice(&0x800u32.to_le_bytes());
|
||||
let rdata_chars = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;
|
||||
pe[sec2 + 36..sec2 + 40].copy_from_slice(&rdata_chars.to_le_bytes());
|
||||
|
||||
// 3. .reloc (RVA 0x3000, raw ptr 0xC00)
|
||||
let sec3 = sec_table + 80;
|
||||
pe[sec3..sec3 + 6].copy_from_slice(b".reloc");
|
||||
pe[sec3 + 8..sec3 + 12].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[sec3 + 12..sec3 + 16].copy_from_slice(&0x3000u32.to_le_bytes());
|
||||
pe[sec3 + 16..sec3 + 20].copy_from_slice(&0x400u32.to_le_bytes());
|
||||
pe[sec3 + 20..sec3 + 24].copy_from_slice(&0xC00u32.to_le_bytes());
|
||||
let reloc_chars = IMAGE_SCN_MEM_READ;
|
||||
pe[sec3 + 36..sec3 + 40].copy_from_slice(&reloc_chars.to_le_bytes());
|
||||
|
||||
// Write .text section content at file offset 0x400
|
||||
if !self.code_bytes.is_empty() {
|
||||
pe[0x400..0x400 + self.code_bytes.len()].copy_from_slice(&self.code_bytes);
|
||||
}
|
||||
|
||||
// Write .rdata section content at file offset 0x800
|
||||
// Layout inside .rdata:
|
||||
// - 0x800 (RVA 0x2000): Import directory (IMAGE_IMPORT_DESCRIPTOR)
|
||||
// - 0x840 (RVA 0x2040): OriginalFirstThunk (INT)
|
||||
// - 0x860 (RVA 0x2060): FirstThunk (IAT)
|
||||
// - 0x880 (RVA 0x2080): DLL Name string
|
||||
// - 0x8C0 (RVA 0x20C0): Hint/Name table entry
|
||||
// - 0x900 (RVA 0x2100): TLS Directory
|
||||
// - 0x940 (RVA 0x2140): TLS Callbacks Array
|
||||
if !self.import_thunks.is_empty() {
|
||||
let desc_off = 0x800;
|
||||
let oft_rva = 0x2040u32;
|
||||
let ft_rva = 0x2060u32;
|
||||
let name_rva = 0x2080u32;
|
||||
let hint_rva = 0x20C0u32;
|
||||
|
||||
// Import descriptor
|
||||
pe[desc_off..desc_off + 4].copy_from_slice(&oft_rva.to_le_bytes());
|
||||
pe[desc_off + 12..desc_off + 16].copy_from_slice(&name_rva.to_le_bytes());
|
||||
pe[desc_off + 16..desc_off + 20].copy_from_slice(&ft_rva.to_le_bytes());
|
||||
|
||||
// DLL Name string
|
||||
let (mod_name, sym_name) = &self.import_thunks[0];
|
||||
pe[0x880..0x880 + mod_name.len()].copy_from_slice(mod_name.as_bytes());
|
||||
pe[0x880 + mod_name.len()] = 0;
|
||||
|
||||
// Hint/Name table: 2-byte hint (0) + symbol string + null terminator
|
||||
pe[0x8C0 + 2..0x8C0 + 2 + sym_name.len()].copy_from_slice(sym_name.as_bytes());
|
||||
pe[0x8C0 + 2 + sym_name.len()] = 0;
|
||||
|
||||
// OFT & FT point to hint_rva
|
||||
pe[0x840..0x848].copy_from_slice(&(hint_rva as u64).to_le_bytes());
|
||||
pe[0x860..0x868].copy_from_slice(&(hint_rva as u64).to_le_bytes());
|
||||
}
|
||||
|
||||
if let Some((module, symbol)) = self.import_thunks.get(1) {
|
||||
let descriptor = 0x814;
|
||||
pe[descriptor..descriptor + 4].copy_from_slice(&0x2180u32.to_le_bytes());
|
||||
pe[descriptor + 12..descriptor + 16].copy_from_slice(&0x21c0u32.to_le_bytes());
|
||||
pe[descriptor + 16..descriptor + 20].copy_from_slice(&0x21a0u32.to_le_bytes());
|
||||
pe[0x980..0x988].copy_from_slice(&0x2200u64.to_le_bytes());
|
||||
pe[0x9a0..0x9a8].copy_from_slice(&0x2200u64.to_le_bytes());
|
||||
pe[0x9c0..0x9c0 + module.len()].copy_from_slice(module.as_bytes());
|
||||
pe[0xa02..0xa02 + symbol.len()].copy_from_slice(symbol.as_bytes());
|
||||
}
|
||||
|
||||
// TLS Directory at file offset 0x900 (RVA 0x2100)
|
||||
if !self.tls_callbacks.is_empty() {
|
||||
let tls_off = 0x900;
|
||||
let raw_start = self.image_base + 0x2200;
|
||||
let raw_end = raw_start + 16;
|
||||
let index_addr = self.image_base + 0x2210;
|
||||
let cb_addr = self.image_base + 0x2140;
|
||||
|
||||
pe[tls_off..tls_off + 8].copy_from_slice(&raw_start.to_le_bytes());
|
||||
pe[tls_off + 8..tls_off + 16].copy_from_slice(&raw_end.to_le_bytes());
|
||||
pe[tls_off + 16..tls_off + 24].copy_from_slice(&index_addr.to_le_bytes());
|
||||
pe[tls_off + 24..tls_off + 32].copy_from_slice(&cb_addr.to_le_bytes());
|
||||
pe[tls_off + 32..tls_off + 36].copy_from_slice(&16u32.to_le_bytes()); // zero fill
|
||||
|
||||
// Callbacks array at file offset 0x940
|
||||
let mut curr = 0x940;
|
||||
for &cb in &self.tls_callbacks {
|
||||
pe[curr..curr + 8].copy_from_slice(&cb.to_le_bytes());
|
||||
curr += 8;
|
||||
}
|
||||
pe[curr..curr + 8].copy_from_slice(&0u64.to_le_bytes()); // null terminator
|
||||
}
|
||||
|
||||
// Write .reloc block at file offset 0xC00
|
||||
if !self.reloc_entries.is_empty() {
|
||||
let page_rva = 0x1000u32;
|
||||
let block_size = (8 + self.reloc_entries.len() * 2) as u32;
|
||||
pe[0xC00..0xC04].copy_from_slice(&page_rva.to_le_bytes());
|
||||
pe[0xC04..0xC08].copy_from_slice(&block_size.to_le_bytes());
|
||||
for (i, &(rva, rtype)) in self.reloc_entries.iter().enumerate() {
|
||||
let offset_in_page = rva - page_rva;
|
||||
let entry_val = ((rtype as u16) << 12) | (offset_in_page as u16 & 0x0FFF);
|
||||
let e_off = 0xC08 + i * 2;
|
||||
pe[e_off..e_off + 2].copy_from_slice(&entry_val.to_le_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
pe
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fixture_a_win64_import_tls_startup() {
|
||||
// Preferred base is 0x140000000, but we load at rebased address 0x240000000 (delta = +0x100000000).
|
||||
// Test exercises:
|
||||
// 1. Two DIR64 relocations in .text applied correctly.
|
||||
// 2. Two TLS callbacks executed in order prior to main entry point.
|
||||
// 3. Main entry point uses:
|
||||
// - sub rsp, 0x28 (Win64 shadow space)
|
||||
// - SIB stack store: mov [rsp + 0x20], rbx
|
||||
// - Indirect call through bound IAT to GetSystemTimeAsFileTime
|
||||
// - Clean exit (HLT).
|
||||
|
||||
let pref_base = 0x140000000u64;
|
||||
let loaded_base = 0x240000000u64; // Non-preferred base
|
||||
|
||||
// Code layout at RVA 0x1000:
|
||||
// 0x1000: 48 83 ec 28 sub rsp, 0x28
|
||||
// 0x1004: 48 c7 c3 77 00 00 00 mov rbx, 0x77
|
||||
// 0x100b: 48 89 5c 24 20 mov [rsp + 0x20], rbx (SIB stack store)
|
||||
// 0x1010: 48 8d 4c 24 10 lea rcx, [rsp + 0x10] (pointer to FILETIME struct)
|
||||
// 0x1015: ff 15 45 10 00 00 call qword ptr [rip + 0x1045] -> IAT at 0x2060 (0x2060 - 0x101B = 0x1045)
|
||||
// 0x101b: 48 8b 54 24 20 mov rdx, [rsp + 0x20] (read back saved value)
|
||||
// 0x1020: 48 83 c4 28 add rsp, 0x28
|
||||
// 0x1024: f4 hlt
|
||||
// 0x1028: [relocated pointer #1: 8 bytes] (at RVA 0x1028: pref_base + 0x1050)
|
||||
// 0x1030: [relocated pointer #2: 8 bytes] (at RVA 0x1030: pref_base + 0x2000)
|
||||
let mut code = vec![0u8; 0x100];
|
||||
code[0..4].copy_from_slice(&[0x48, 0x83, 0xec, 0x28]);
|
||||
code[4..11].copy_from_slice(&[0x48, 0xc7, 0xc3, 0x77, 0x00, 0x00, 0x00]);
|
||||
code[11..16].copy_from_slice(&[0x48, 0x89, 0x5c, 0x24, 0x20]);
|
||||
// LEA rcx, [rsp + 0x10] (48 8d 4c 24 10)
|
||||
code[16..21].copy_from_slice(&[0x48, 0x8d, 0x4c, 0x24, 0x10]);
|
||||
// Call indirect through IAT at 0x2060: 0x2060 - (0x1015 + 6 = 0x101B) = 0x1045
|
||||
code[21..27].copy_from_slice(&[0xff, 0x15, 0x45, 0x10, 0x00, 0x00]);
|
||||
// Load into RDX so the assertion depends on the guest memory round trip.
|
||||
code[27..32].copy_from_slice(&[0x48, 0x8b, 0x54, 0x24, 0x20]);
|
||||
// Add rsp, 0x28
|
||||
code[32..36].copy_from_slice(&[0x48, 0x83, 0xc4, 0x28]);
|
||||
// HLT
|
||||
code[36] = 0xf4;
|
||||
|
||||
// Relocation #1 at RVA 0x1028 (offset 40..48):
|
||||
code[40..48].copy_from_slice(&(pref_base + 0x1050).to_le_bytes());
|
||||
// Relocation #2 at RVA 0x1030 (offset 48..56):
|
||||
code[48..56].copy_from_slice(&(pref_base + 0x2000).to_le_bytes());
|
||||
|
||||
// TLS Callbacks in .text:
|
||||
// Callback 1 at RVA 0x1060: increments RAX by 1, ret (48 ff c0 c3 -> inc rax / ret)
|
||||
code[0x60..0x64].copy_from_slice(&[0x48, 0xff, 0xc0, 0xc3]);
|
||||
// Callback 2 doubles RAX and records it below its stack frame.
|
||||
code[0x70..0x79].copy_from_slice(&[0x48, 0x01, 0xc0, 0x48, 0x89, 0x44, 0x24, 0xf0, 0xc3]);
|
||||
|
||||
let pe_bytes = TestPeBuilder::new(pref_base, 0x1000)
|
||||
.code(&code)
|
||||
.add_dir64_reloc(0x1028) // Relocation #1
|
||||
.add_padding_reloc(0x1028) // Padding absolute reloc
|
||||
.add_dir64_reloc(0x1030) // Relocation #2
|
||||
.add_tls_callback(pref_base + 0x1060)
|
||||
.add_tls_callback(pref_base + 0x1070)
|
||||
.add_import("kernel32.dll", "GetSystemTimeAsFileTime")
|
||||
.build();
|
||||
|
||||
let stack_top = 0x500000000;
|
||||
let layout = || StartupLayout {
|
||||
image_base: loaded_base,
|
||||
stack_top,
|
||||
tls_base: 0x300000000,
|
||||
};
|
||||
let registry = || {
|
||||
let mut imports = ImportRegistry::new();
|
||||
let clock = Arc::new(MockClock::new(133_000_000_000_000_000));
|
||||
register_standard_services(&mut imports, Arc::new(ServicesState::new(clock)));
|
||||
imports
|
||||
};
|
||||
let probe = xenora_loader::probe_pe_bytes(&pe_bytes, &Default::default()).unwrap();
|
||||
assert_eq!(probe.imports.len(), 1);
|
||||
assert_eq!(probe.imports[0].symbol, "GetSystemTimeAsFileTime");
|
||||
assert!(probe.imports[0].is_supported);
|
||||
|
||||
let startup =
|
||||
run_synthetic_startup(&pe_bytes, layout(), registry(), 1000).expect("run fixture startup");
|
||||
assert_eq!(startup.relocations.applied_dir64, 2);
|
||||
assert_eq!(startup.relocations.skipped_absolute, 1);
|
||||
assert_eq!(startup.relocations.delta, 0x100000000);
|
||||
assert_eq!(startup.bound_imports, 1);
|
||||
assert_eq!(startup.tls_callbacks, 2);
|
||||
assert_eq!(startup.execution.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(
|
||||
startup.execution.final_state.get(Register::Rsp),
|
||||
stack_top - 40
|
||||
);
|
||||
assert_eq!(startup.execution.final_state.get(Register::Rdx), 0x77);
|
||||
|
||||
let memory = &startup.image.memory;
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(loaded_base + 0x1028).unwrap(),
|
||||
loaded_base + 0x1050
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(loaded_base + 0x1030).unwrap(),
|
||||
loaded_base + 0x2000
|
||||
);
|
||||
assert_eq!(memory.read_u64(stack_top - 40 - 16).unwrap(), 2); // (0 + 1) * 2
|
||||
assert_eq!(
|
||||
memory.read_u64(stack_top - 40 - 0x28 + 0x10).unwrap(),
|
||||
133_000_000_000_000_000
|
||||
);
|
||||
|
||||
let mut halting_tls = pe_bytes;
|
||||
let callback_offset = startup.image.pe.rva_to_file_offset(0x1060).unwrap();
|
||||
halting_tls[callback_offset] = 0xf4;
|
||||
let missing = run_synthetic_startup(&halting_tls, layout(), ImportRegistry::new(), 1000)
|
||||
.err()
|
||||
.expect("import binding must fail before the halting callback");
|
||||
assert_eq!(
|
||||
missing.downcast_ref::<xenora_loader::ImportError>(),
|
||||
Some(&xenora_loader::ImportError::UnresolvedImport {
|
||||
module: "kernel32.dll".into(),
|
||||
symbol: "GetSystemTimeAsFileTime".into(),
|
||||
}),
|
||||
);
|
||||
let fault = run_synthetic_startup(&halting_tls, layout(), registry(), 1000)
|
||||
.err()
|
||||
.expect("callback halt must fail startup");
|
||||
assert!(matches!(
|
||||
fault.downcast_ref::<TlsError>(),
|
||||
Some(TlsError::CallbackExecutionFault(ExitReason::Halt))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fixture_b_xmem_guest_allocator() {
|
||||
// Tests Xbox Scarlett memory allocation service (xmem.dll!XMemAlloc):
|
||||
// 1. Invokes XMemAlloc via synthetic IAT call.
|
||||
// 2. Writes data to returned guest address.
|
||||
// 3. Reads data back and verifies integrity.
|
||||
|
||||
let pref_base = 0x140000000u64;
|
||||
// Code at RVA 0x1000:
|
||||
// 0x1000: 48 83 ec 28 sub rsp, 0x28
|
||||
// 0x1004: 48 c7 c1 00 10 00 00 mov rcx, 0x1000 (allocate 4096 bytes)
|
||||
// 0x100b: 48 31 d2 xor rdx, rdx (attributes = 0)
|
||||
// 0x100e: ff 15 4c 10 00 00 call qword ptr [rip + 0x104c] -> IAT at 0x2060
|
||||
// 0x1014: 48 89 c3 mov rbx, rax (save allocated address in rbx)
|
||||
// 0x1017: 48 c7 03 42 00 00 00 mov qword ptr [rbx], 0x42 (write to allocated memory)
|
||||
// 0x101e: 48 8b 0b mov rcx, [rbx] (read back into rcx)
|
||||
// 0x1021: 48 83 c4 28 add rsp, 0x28
|
||||
// 0x1025: f4 hlt
|
||||
let mut code = vec![0u8; 0x100];
|
||||
code[0..4].copy_from_slice(&[0x48, 0x83, 0xec, 0x28]);
|
||||
code[4..11].copy_from_slice(&[0x48, 0xc7, 0xc1, 0x00, 0x10, 0x00, 0x00]);
|
||||
code[11..14].copy_from_slice(&[0x48, 0x31, 0xd2]);
|
||||
code[14..20].copy_from_slice(&[0xff, 0x15, 0x4c, 0x10, 0x00, 0x00]);
|
||||
code[20..23].copy_from_slice(&[0x48, 0x89, 0xc3]);
|
||||
// 48 c7 03 42 00 00 00 -> mov qword ptr [rbx], 0x42
|
||||
code[23..30].copy_from_slice(&[0x48, 0xc7, 0x03, 0x42, 0x00, 0x00, 0x00]);
|
||||
// 48 8b 0b -> mov rcx, [rbx]
|
||||
code[30..33].copy_from_slice(&[0x48, 0x8b, 0x0b]);
|
||||
code[33..37].copy_from_slice(&[0x48, 0x83, 0xc4, 0x28]);
|
||||
code[37] = 0xf4;
|
||||
|
||||
let pe_bytes = TestPeBuilder::new(pref_base, 0x1000)
|
||||
.code(&code)
|
||||
.add_import("xmem.dll", "XMemAlloc")
|
||||
.build();
|
||||
|
||||
let pe = ParsedPe::parse(&pe_bytes).expect("parse pe");
|
||||
let mut memory = xenora_loader::memory::GuestMemory::new();
|
||||
|
||||
for sec in &pe.sections {
|
||||
let base = pref_base + sec.virtual_address as u64;
|
||||
let size = std::cmp::max(sec.virtual_size, sec.raw_data_size) as usize;
|
||||
let file_off = sec.raw_data_ptr as usize;
|
||||
let data = &pe_bytes[file_off..file_off + sec.raw_data_size as usize];
|
||||
memory
|
||||
.map_region_with_data(base, size, sec.permissions, data)
|
||||
.expect("map section");
|
||||
}
|
||||
|
||||
let mut import_registry = ImportRegistry::new();
|
||||
let clock = Arc::new(MockClock::new(100));
|
||||
let services_state = Arc::new(ServicesState::new(clock));
|
||||
register_standard_services(&mut import_registry, services_state);
|
||||
|
||||
let bound = import_registry
|
||||
.bind_imports(&pe, &pe_bytes, pref_base, &mut memory)
|
||||
.expect("bind xmem");
|
||||
assert_eq!(bound, 1);
|
||||
|
||||
let stack_top = 0x500000000u64;
|
||||
memory
|
||||
.map_region(
|
||||
0x4FFFF0000,
|
||||
0x10000,
|
||||
MemoryPermissions {
|
||||
read: true,
|
||||
write: true,
|
||||
execute: false,
|
||||
},
|
||||
)
|
||||
.expect("map stack");
|
||||
|
||||
let mut dbt = DbtEngine::new(1024 * 1024).expect("init JIT");
|
||||
dbt.set_import_registry(import_registry);
|
||||
|
||||
let mut cpu = CpuState::new(pref_base + 0x1000, stack_top);
|
||||
let result = dbt.run(&mut cpu, &mut memory, 1000);
|
||||
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
let allocated_addr = result.final_state.get(Register::Rbx);
|
||||
assert!(allocated_addr >= 0x200000000); // In allocated guest heap range
|
||||
assert_eq!(result.final_state.get(Register::Rcx), 0x42); // Read back correctly!
|
||||
}
|
||||
|
||||
fn run_fixture_c(handler: xenora_loader::imports::ServiceHandler) {
|
||||
let pref_base = 0x140000000u64;
|
||||
let mut code = vec![0u8; 0x100];
|
||||
// 0x1000: 48 83 ec 28 sub rsp, 0x28
|
||||
// 0x1004: ff 15 56 10 00 00 call qword ptr [rip + 0x1056] -> IAT at 0x2060
|
||||
// 0x100a: 48 83 c4 28 add rsp, 0x28
|
||||
// 0x100e: f4 hlt
|
||||
code[0..4].copy_from_slice(&[0x48, 0x83, 0xec, 0x28]);
|
||||
code[4..10].copy_from_slice(&[0xff, 0x15, 0x56, 0x10, 0x00, 0x00]);
|
||||
code[10..14].copy_from_slice(&[0x48, 0x83, 0xc4, 0x28]);
|
||||
code[14] = 0xf4;
|
||||
|
||||
// Place an original full-screen triangle in the guest image.
|
||||
let positions: [f32; 12] = [-1., -1., 0.5, 1., 3., -1., 0.5, 1., -1., 3., 0.5, 1.];
|
||||
for (slot, value) in code[0x40..0x70]
|
||||
.as_chunks_mut::<4>()
|
||||
.0
|
||||
.iter_mut()
|
||||
.zip(positions)
|
||||
{
|
||||
slot.copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
let pe_bytes = TestPeBuilder::new(pref_base, 0x1000)
|
||||
.code(&code)
|
||||
.add_import("xenora_fixture.dll", "RenderFrame")
|
||||
.build();
|
||||
|
||||
let pe = ParsedPe::parse(&pe_bytes).expect("parse pe");
|
||||
let mut memory = xenora_loader::memory::GuestMemory::new();
|
||||
|
||||
for sec in &pe.sections {
|
||||
let base = pref_base + sec.virtual_address as u64;
|
||||
let size = std::cmp::max(sec.virtual_size, sec.raw_data_size) as usize;
|
||||
let file_off = sec.raw_data_ptr as usize;
|
||||
let data = &pe_bytes[file_off..file_off + sec.raw_data_size as usize];
|
||||
memory
|
||||
.map_region_with_data(base, size, sec.permissions, data)
|
||||
.expect("map section");
|
||||
}
|
||||
|
||||
let mut import_registry = ImportRegistry::new();
|
||||
import_registry.register("xenora_fixture.dll", "RenderFrame", handler);
|
||||
|
||||
let bound = import_registry
|
||||
.bind_imports(&pe, &pe_bytes, pref_base, &mut memory)
|
||||
.expect("bind import");
|
||||
assert_eq!(bound, 1);
|
||||
|
||||
let stack_top = 0x500000000u64;
|
||||
memory
|
||||
.map_region(
|
||||
0x4FFFF0000,
|
||||
0x10000,
|
||||
MemoryPermissions {
|
||||
read: true,
|
||||
write: true,
|
||||
execute: false,
|
||||
},
|
||||
)
|
||||
.expect("map stack");
|
||||
|
||||
let mut dbt = DbtEngine::new(1024 * 1024).expect("init JIT");
|
||||
dbt.set_import_registry(import_registry);
|
||||
|
||||
let mut cpu = CpuState::new(pref_base + 0x1000, stack_top);
|
||||
cpu.set(Register::Rcx, pref_base + 0x1040);
|
||||
let result = dbt.run(&mut cpu, &mut memory, 1000);
|
||||
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(result.final_state.get(Register::Rsp), stack_top);
|
||||
assert_eq!(result.final_state.get(Register::Rax), 0x42);
|
||||
assert_eq!(dbt.metrics.service_calls, 1);
|
||||
assert_eq!(dbt.metrics.interpreter_fallbacks, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fixture_c_mock_render_service_dispatch() {
|
||||
run_fixture_c(Box::new(|args, _, mem| {
|
||||
assert_eq!(
|
||||
mem.read_u64(args.get(0, mem).map_err(ExitReason::MemoryFault)?)
|
||||
.map_err(ExitReason::MemoryFault)?,
|
||||
0xbf80_0000_bf80_0000
|
||||
);
|
||||
Ok(0x42)
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(
|
||||
not(feature = "gpu-tests"),
|
||||
ignore = "needs native Metal; run scripts/test-gpu.sh"
|
||||
)]
|
||||
fn test_fixture_c_service_to_metal_framebuffer() {
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
run_fixture_c(Box::new(|args, _, mem| {
|
||||
let mut bytes = [0; 48];
|
||||
let address = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
mem.read_bytes(address, &mut bytes)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
let mut vertices = [[0.0; 4]; 3];
|
||||
for (value, bytes) in vertices.iter_mut().flatten().zip(bytes.as_chunks::<4>().0) {
|
||||
*value = f32::from_le_bytes(*bytes);
|
||||
}
|
||||
let shader = compile_graphics(
|
||||
Architecture::Gfx1030,
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
|
||||
)
|
||||
.expect("compile original graphics fixture");
|
||||
let pixels = NativeCompute::new()
|
||||
.expect("native Metal device")
|
||||
.render_rgba8(
|
||||
&shader.msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
&vertices,
|
||||
&[[0.0; 4]; 3],
|
||||
[4, 3],
|
||||
[19, 43, 93, 251],
|
||||
)
|
||||
.expect("Metal draw and readback");
|
||||
// The authored triangle covers every pixel and its shader exports opaque red.
|
||||
assert_eq!(pixels, [255, 0, 0, 255].repeat(12));
|
||||
Ok(0x42)
|
||||
}));
|
||||
}
|
||||
|
||||
const PROCESS_FIXTURE_STACK_TOP: u64 = 0x500000000;
|
||||
const PROCESS_FIXTURE_OUTPUT: u64 = PROCESS_FIXTURE_STACK_TOP - 0x100;
|
||||
|
||||
fn call_process_fixture(
|
||||
state: &Arc<ServicesState>,
|
||||
module: &str,
|
||||
symbol: &str,
|
||||
rcx: u64,
|
||||
rdx: u64,
|
||||
) -> xenora_loader::startup::StartupResult {
|
||||
call_identity_fixture(state, module, symbol, [rcx, rdx, 0])
|
||||
}
|
||||
|
||||
fn call_identity_fixture(
|
||||
state: &Arc<ServicesState>,
|
||||
module: &str,
|
||||
symbol: &str,
|
||||
args: [u64; 3],
|
||||
) -> xenora_loader::startup::StartupResult {
|
||||
let image_base = 0x140000000;
|
||||
let mut code = vec![0x48, 0x83, 0xec, 0x28]; // Win64 home space and alignment
|
||||
for (register, value) in [[0x48, 0xb9], [0x48, 0xba], [0x49, 0xb8]]
|
||||
.into_iter()
|
||||
.zip(args)
|
||||
{
|
||||
code.extend_from_slice(®ister); // mov rcx/rdx/r8, imm64
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
code.extend_from_slice(&[0x48, 0xb8]); // mov rax, address of output slot
|
||||
code.extend_from_slice(&PROCESS_FIXTURE_OUTPUT.to_le_bytes());
|
||||
// mov qword ptr [rax], -1, seeding the BOOL and adjacent bytes
|
||||
code.extend_from_slice(&[0x48, 0xc7, 0x00, 0xff, 0xff, 0xff, 0xff]);
|
||||
append_import_call(&mut code, 0x2060);
|
||||
code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]); // release frame and halt
|
||||
|
||||
let bytes = TestPeBuilder::new(image_base, 0x1000)
|
||||
.code(&code)
|
||||
.add_import(module, symbol)
|
||||
.build();
|
||||
let mut imports = ImportRegistry::new();
|
||||
register_standard_services(&mut imports, Arc::clone(state));
|
||||
let result = run_synthetic_startup(
|
||||
&bytes,
|
||||
StartupLayout {
|
||||
image_base,
|
||||
stack_top: PROCESS_FIXTURE_STACK_TOP,
|
||||
tls_base: 0x300000000,
|
||||
},
|
||||
imports,
|
||||
100,
|
||||
)
|
||||
.expect("start process-service PE fixture");
|
||||
assert_eq!(result.bound_imports, 1);
|
||||
assert_eq!(result.execution.exit_reason, ExitReason::Halt);
|
||||
result
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_process_priority_boost_setter_through_iat() {
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let set = |module, handle, disable| {
|
||||
call_process_fixture(&state, module, "SetProcessPriorityBoost", handle, disable)
|
||||
.execution
|
||||
.final_state
|
||||
.get(Register::Rax)
|
||||
};
|
||||
let last_error = || {
|
||||
call_process_fixture(&state, "kernel32.dll", "GetLastError", 0, 0)
|
||||
.execution
|
||||
.final_state
|
||||
.get(Register::Rax)
|
||||
};
|
||||
let api_set = "API-MS-WIN-CORE-PROCESSTHREADS-L1-1-2.DLL";
|
||||
assert!(!state.priority_boost_disabled());
|
||||
assert_eq!(set(api_set, u64::MAX, 2), 1);
|
||||
assert!(state.priority_boost_disabled());
|
||||
assert_eq!(set(api_set, u64::MAX, 2), 1);
|
||||
assert!(state.priority_boost_disabled());
|
||||
for invalid in [0, 0x4100, u64::MAX - 1] {
|
||||
assert_eq!(set(api_set, invalid, 0), 0);
|
||||
assert_eq!(last_error(), 6);
|
||||
assert!(state.priority_boost_disabled());
|
||||
}
|
||||
// BOOL occupies the low 32 bits of the argument register.
|
||||
assert_eq!(set("kernel32.dll", u64::MAX, 1 << 32), 1);
|
||||
assert!(!state.priority_boost_disabled());
|
||||
assert_eq!(last_error(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_current_process_identity_through_iat() {
|
||||
let mut state = ServicesState::new(Arc::new(MockClock::new(0)));
|
||||
state.process_id = 12345;
|
||||
let state = Arc::new(state);
|
||||
let api_set = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
let call = |module, symbol, handle| {
|
||||
call_process_fixture(&state, module, symbol, handle, 0)
|
||||
.execution
|
||||
.final_state
|
||||
.get(Register::Rax)
|
||||
};
|
||||
let handle = call(api_set, "GetCurrentProcess", 0);
|
||||
assert_eq!(handle, u64::MAX);
|
||||
assert_eq!(call("kernel32.dll", "GetCurrentProcess", 0), handle);
|
||||
assert_eq!(call(api_set, "GetProcessId", handle), 12345);
|
||||
assert_eq!(call(api_set, "GetProcessId", 12345), 0);
|
||||
assert_eq!(
|
||||
call(
|
||||
"api-ms-win-core-errorhandling-l1-1-0.dll",
|
||||
"GetLastError",
|
||||
0
|
||||
),
|
||||
6
|
||||
);
|
||||
assert_eq!(call("kernel32.dll", "GetProcessId", handle), 12345);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_process_priority_boost_query_through_iat() {
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let api_set = "api-ms-win-core-processthreads-l1-1-2.dll";
|
||||
let query =
|
||||
|handle, ptr| call_process_fixture(&state, api_set, "GetProcessPriorityBoost", handle, ptr);
|
||||
let read_output = |result: &xenora_loader::startup::StartupResult| {
|
||||
result
|
||||
.image
|
||||
.memory
|
||||
.read_u64(PROCESS_FIXTURE_OUTPUT)
|
||||
.unwrap()
|
||||
};
|
||||
for (disable, expected) in [(false, 0), (true, 1), (true, 1), (false, 0)] {
|
||||
let setter = call_process_fixture(
|
||||
&state,
|
||||
api_set,
|
||||
"SetProcessPriorityBoost",
|
||||
u64::MAX,
|
||||
u64::from(disable),
|
||||
);
|
||||
assert_eq!(setter.execution.final_state.get(Register::Rax), 1);
|
||||
let result = query(u64::MAX, PROCESS_FIXTURE_OUTPUT);
|
||||
assert_eq!(result.execution.final_state.get(Register::Rax), 1);
|
||||
assert_eq!(read_output(&result), 0xffff_ffff_0000_0000 | expected);
|
||||
}
|
||||
|
||||
for (handle, ptr, error) in [
|
||||
(0, PROCESS_FIXTURE_OUTPUT, 6),
|
||||
(u64::MAX, 0, 998),
|
||||
(u64::MAX, 0x140001000, 998), // Executable section has no write permission.
|
||||
(u64::MAX, PROCESS_FIXTURE_STACK_TOP - 2, 998),
|
||||
] {
|
||||
let result = query(handle, ptr);
|
||||
assert_eq!(result.execution.final_state.get(Register::Rax), 0);
|
||||
assert_eq!(read_output(&result), u64::MAX);
|
||||
let result = call_process_fixture(&state, "kernel32.dll", "GetLastError", 0, 0);
|
||||
assert_eq!(result.execution.final_state.get(Register::Rax), error);
|
||||
}
|
||||
}
|
||||
|
||||
fn append_import_call(code: &mut Vec<u8>, slot_rva: i32) {
|
||||
// call qword ptr [rip + disp32], through the fixture's import slot.
|
||||
let next_rva = 0x1000 + code.len() as i32 + 6;
|
||||
code.extend_from_slice(&[0xff, 0x15]);
|
||||
code.extend_from_slice(&(slot_rva - next_rva).to_le_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_guest_thread_handle_lifecycle_through_iat() {
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let api = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
let handle_api = "api-ms-win-core-handle-l1-1-0.dll";
|
||||
let call = |module, symbol, args| {
|
||||
call_identity_fixture(&state, module, symbol, args)
|
||||
.execution
|
||||
.final_state
|
||||
.get(Register::Rax)
|
||||
};
|
||||
let last_error = || call("kernel32.dll", "GetLastError", [0; 3]);
|
||||
let id = call(api, "GetCurrentThreadId", [0; 3]);
|
||||
let pseudo = call(api, "GetCurrentThread", [0; 3]);
|
||||
assert_eq!(pseudo, u64::MAX - 1);
|
||||
|
||||
const QUERY_LIMITED: u64 = 0x0800;
|
||||
const SET_LIMITED: u64 = 0x0400;
|
||||
let open = |rights, inherit, id| call(api, "OpenThread", [rights, inherit, id]);
|
||||
let query = |handle| call(api, "GetThreadPriority", [handle, 0, 0]);
|
||||
let set = |handle, priority| call(api, "SetThreadPriority", [handle, priority, 0]);
|
||||
let close = |handle| call(handle_api, "CloseHandle", [handle, 0, 0]);
|
||||
|
||||
assert_eq!(open(QUERY_LIMITED, 0, id + 1), 0);
|
||||
assert_eq!(last_error(), 87);
|
||||
assert_eq!(open(QUERY_LIMITED, 1, id), 0);
|
||||
assert_eq!(last_error(), 50);
|
||||
assert_eq!(open(0x0002, 0, id), 0);
|
||||
assert_eq!(last_error(), 50);
|
||||
let query_only = open(QUERY_LIMITED, 0, id);
|
||||
let set_only = open(SET_LIMITED, 0, id);
|
||||
assert_ne!(query_only, 0);
|
||||
assert_ne!(set_only, 0);
|
||||
assert_ne!(query_only, set_only);
|
||||
assert_eq!(query(query_only), 0);
|
||||
assert_eq!(set(query_only, 1), 0);
|
||||
assert_eq!(last_error(), 5);
|
||||
assert_eq!(query(set_only), 0x7fff_ffff);
|
||||
assert_eq!(last_error(), 5);
|
||||
assert_eq!(set(set_only, u64::MAX), 1);
|
||||
assert_eq!(query(query_only), u64::from(u32::MAX)); // signed int -1
|
||||
assert_eq!(query(pseudo), u64::from(u32::MAX));
|
||||
assert_eq!(set(pseudo, 3), 0);
|
||||
assert_eq!(last_error(), 87);
|
||||
assert_eq!(set(pseudo, 0x0001_0000), 0);
|
||||
assert_eq!(last_error(), 50);
|
||||
assert_eq!(query(pseudo), u64::from(u32::MAX));
|
||||
assert_eq!(close(pseudo), 1);
|
||||
assert_eq!(close(query_only), 1);
|
||||
assert_eq!(query(query_only), 0x7fff_ffff);
|
||||
assert_eq!(last_error(), 6);
|
||||
assert_eq!(close(query_only), 0);
|
||||
assert_eq!(last_error(), 6);
|
||||
let reopened = open(QUERY_LIMITED, 0, id);
|
||||
assert_ne!(reopened, query_only);
|
||||
assert_eq!(query(reopened), u64::from(u32::MAX));
|
||||
assert_eq!(last_error(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_virtual_allocation_release_through_iat() {
|
||||
const IMAGE: u64 = 0x140000000;
|
||||
const HEAP: u64 = 0x8_0000_0000;
|
||||
const MODULE: &str = "api-ms-win-core-memory-l1-1-0.dll";
|
||||
|
||||
let run = |args: [u64; 4], free: Option<[u64; 3]>| {
|
||||
let mut code = vec![0x48, 0x83, 0xec, 0x28]; // Win64 home space and alignment
|
||||
let registers = [[0x48, 0xb9], [0x48, 0xba], [0x49, 0xb8], [0x49, 0xb9]];
|
||||
for (register, value) in registers.into_iter().zip(args) {
|
||||
code.extend_from_slice(®ister);
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
append_import_call(&mut code, 0x2060);
|
||||
let mut fixture = TestPeBuilder::new(IMAGE, 0x1000).add_import(MODULE, "VirtualAlloc");
|
||||
if let Some(free) = free {
|
||||
for (register, value) in registers.into_iter().zip(free) {
|
||||
code.extend_from_slice(®ister);
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
append_import_call(&mut code, 0x21a0);
|
||||
fixture = fixture.add_import(MODULE, "VirtualFree");
|
||||
}
|
||||
code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]);
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let mut imports = ImportRegistry::new();
|
||||
register_standard_services(&mut imports, Arc::clone(&state));
|
||||
let result = run_synthetic_startup(
|
||||
&fixture.code(&code).build(),
|
||||
StartupLayout {
|
||||
image_base: IMAGE,
|
||||
stack_top: PROCESS_FIXTURE_STACK_TOP,
|
||||
tls_base: 0x300000000,
|
||||
},
|
||||
imports,
|
||||
100,
|
||||
)
|
||||
.expect("start memory-service PE fixture");
|
||||
assert_eq!(result.execution.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(result.bound_imports, if free.is_some() { 2 } else { 1 });
|
||||
let value = result.execution.final_state.get(Register::Rax);
|
||||
let error = state.last_error.load(std::sync::atomic::Ordering::SeqCst);
|
||||
(result.image.memory, value, error)
|
||||
};
|
||||
|
||||
let (mut memory, value, error) = run([HEAP + 0x800, 0x1000, 0x3000, 4], None);
|
||||
assert_eq!((value, error), (HEAP, 0));
|
||||
assert_eq!(memory.read_u32(HEAP + 0x1ffc).unwrap(), 0);
|
||||
memory.write_u32(HEAP, 123).unwrap();
|
||||
assert_eq!(memory.read_u32(HEAP).unwrap(), 123);
|
||||
assert!(memory.read_u32(HEAP + 0x2000).is_err());
|
||||
|
||||
let (memory, value, error) = run([HEAP, 1, 0x3000, 4], Some([HEAP, 0, 0x8000]));
|
||||
assert_eq!((value, error), (1, 0));
|
||||
assert!(memory.read_u32(HEAP).is_err());
|
||||
|
||||
for (free_args, expected_error) in [
|
||||
([HEAP + 1, 0, 0x8000], 487),
|
||||
([HEAP, 1, 0x8000], 87),
|
||||
([HEAP, 0, 0x4000], 50),
|
||||
([IMAGE + 0x1000, 0, 0x8000], 487),
|
||||
([PROCESS_FIXTURE_STACK_TOP - 0x1_0000, 0, 0x8000], 487),
|
||||
] {
|
||||
let (memory, value, error) = run([HEAP, 1, 0x3000, 4], Some(free_args));
|
||||
assert_eq!((value, error), (0, expected_error));
|
||||
assert_eq!(memory.read_u32(HEAP).unwrap(), 0);
|
||||
assert!(memory.fetch_instruction_byte(IMAGE + 0x1000).is_ok());
|
||||
}
|
||||
let (mut memory, address, error) = run([0, 1, 0x3000, 2], None);
|
||||
assert_ne!(address, 0);
|
||||
assert_eq!(address % 65_536, 0);
|
||||
assert_eq!(error, 0);
|
||||
assert_eq!(memory.read_u32(address).unwrap(), 0);
|
||||
assert!(memory.write_u32(address, 1).is_err());
|
||||
|
||||
let (memory, address, error) = run([0, 1, 0x3000, 1], None);
|
||||
assert_ne!(address, 0);
|
||||
assert_eq!(error, 0);
|
||||
assert!(memory.read_u32(address).is_err());
|
||||
|
||||
for (args, expected_error) in [
|
||||
([0, 0, 0x3000, 4], 87),
|
||||
([0, u64::MAX, 0x3000, 4], 87),
|
||||
([0, 65 * 1024 * 1024, 0x3000, 4], 8),
|
||||
([0, 0x1000, 0x2000, 4], 50),
|
||||
([0, 0x1000, 0x3000, 0x40], 87),
|
||||
([IMAGE + 0x1000, 1, 0x3000, 4], 487),
|
||||
] {
|
||||
let (_, value, error) = run(args, None);
|
||||
assert_eq!((value, error), (0, expected_error));
|
||||
}
|
||||
}
|
||||
@@ -32,12 +32,14 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = ["
|
||||
objc2-metal = { version = "=0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"MTLAllocation",
|
||||
"MTLArgument",
|
||||
"MTLBuffer",
|
||||
"MTLCommandBuffer",
|
||||
"MTLCommandEncoder",
|
||||
"MTLCommandQueue",
|
||||
"MTLComputeCommandEncoder",
|
||||
"MTLComputePipeline",
|
||||
"MTLDepthStencil",
|
||||
"MTLDevice",
|
||||
"MTLLibrary",
|
||||
"MTLPixelFormat",
|
||||
|
||||
+244
-40
@@ -16,28 +16,50 @@ use objc2_metal::{
|
||||
MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture,
|
||||
MTLTextureDescriptor, MTLTextureUsage,
|
||||
};
|
||||
use xenora_texture::{Bc1Upload, TiledBc1};
|
||||
use xenora_texture::{
|
||||
Bc1Upload, BcAlphaFormat, BcAlphaUpload, BcChannelFormat, BcChannelUpload, TiledBc1,
|
||||
};
|
||||
|
||||
#[path = "render.rs"]
|
||||
mod render;
|
||||
|
||||
pub use render::{
|
||||
BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask, DepthCompare,
|
||||
DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, IndexBuffer, IndexedDraw,
|
||||
IndexedPass,
|
||||
};
|
||||
|
||||
const MAX_THREADS_PER_GROUP: usize = 64;
|
||||
const MAX_GROUPS: usize = 64;
|
||||
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
|
||||
const MAX_SOURCE_BYTES: usize = 64 * 1024;
|
||||
|
||||
const BC1_READBACK: &str = r"
|
||||
const BC_READBACK: &str = r"
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void read_bc1(texture2d<float, access::read> image [[texture(0)]],
|
||||
device uint *output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
kernel void read_bc(texture2d<float, access::read> image [[texture(0)]],
|
||||
device uint *output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint width = image.get_width();
|
||||
uint4 channels = uint4(round(image.read(uint2(index % width, index / width)) * 255.0f));
|
||||
output[index] = channels.r | (channels.g << 8u) | (channels.b << 16u) | (channels.a << 24u);
|
||||
}
|
||||
";
|
||||
|
||||
// Signed formats return -1.0..=1.0; each byte holds the channel times 127.
|
||||
const BC_SNORM_READBACK: &str = r"
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void read_bc_snorm(texture2d<float, access::read> image [[texture(0)]],
|
||||
device uint *output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint width = image.get_width();
|
||||
float4 texel = clamp(image.read(uint2(index % width, index / width)), -1.0f, 1.0f);
|
||||
uint4 bytes = uint4(int4(round(texel * 127.0f))) & 0xffu;
|
||||
output[index] = bytes.r | (bytes.g << 8u) | (bytes.b << 16u) | (bytes.a << 24u);
|
||||
}
|
||||
";
|
||||
|
||||
enum ComputeInput<'a> {
|
||||
Words(&'a [u32]),
|
||||
Texture(&'a ProtocolObject<dyn MTLTexture>, usize),
|
||||
@@ -88,6 +110,17 @@ pub struct MetalError {
|
||||
}
|
||||
|
||||
impl MetalError {
|
||||
/// Operation name of the error returned when the device lacks BC texture
|
||||
/// compression, which is a hardware capability, not an implementation fault.
|
||||
pub const BC_UNAVAILABLE: &'static str = "supportsBCTextureCompression";
|
||||
|
||||
/// Whether the device lacks a required capability, as opposed to a failure
|
||||
/// in Xenora's validation or Metal execution.
|
||||
#[must_use]
|
||||
pub fn is_capability_unavailable(&self) -> bool {
|
||||
self.operation == Self::BC_UNAVAILABLE
|
||||
}
|
||||
|
||||
pub(crate) fn new(operation: &'static str, detail: impl Into<String>) -> Self {
|
||||
Self {
|
||||
operation,
|
||||
@@ -184,11 +217,18 @@ impl NativeCompute {
|
||||
let (width, height) = tiled
|
||||
.mip_extent(mip)
|
||||
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
|
||||
let pixels = self.validate_bc1_extent(width, height)?;
|
||||
let pixels = self.validate_bc_extent(width, height, "BC1")?;
|
||||
let blocks = tiled
|
||||
.linearize(layer, mip)
|
||||
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
|
||||
self.read_bc1_blocks(&blocks, width.div_ceil(4) * 8, width, height, pixels)
|
||||
self.read_bc_blocks(
|
||||
MTLPixelFormat::BC1_RGBA,
|
||||
&blocks,
|
||||
width.div_ceil(4) * 8,
|
||||
width,
|
||||
height,
|
||||
pixels,
|
||||
)
|
||||
}
|
||||
|
||||
/// Sample a native Metal RGBA8 texture using a native Metal sampler on Apple Silicon GPU.
|
||||
@@ -269,8 +309,9 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
let level = upload
|
||||
.subresource(layer, mip)
|
||||
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
|
||||
let pixels = self.validate_bc1_extent(level.width, level.height)?;
|
||||
self.read_bc1_blocks(
|
||||
let pixels = self.validate_bc_extent(level.width, level.height, "BC1")?;
|
||||
self.read_bc_blocks(
|
||||
MTLPixelFormat::BC1_RGBA,
|
||||
level.bytes,
|
||||
level.row_pitch,
|
||||
level.width,
|
||||
@@ -279,22 +320,100 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
)
|
||||
}
|
||||
|
||||
fn validate_bc1_extent(&self, width: usize, height: usize) -> Result<usize, MetalError> {
|
||||
/// Read a selected subresource from a validated pitched BC2 or BC3 upload.
|
||||
///
|
||||
/// The original 16-byte blocks go to a native `BC2_RGBA` or `BC3_RGBA`
|
||||
/// texture, and the output has the layout of [`Self::read_bc1_upload`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for an invalid layer or mip, out-of-policy size,
|
||||
/// unavailable BC compression, or Metal setup or execution failure.
|
||||
pub fn read_bc_alpha_upload(
|
||||
&self,
|
||||
upload: &BcAlphaUpload<'_>,
|
||||
layer: usize,
|
||||
mip: u32,
|
||||
) -> Result<Vec<u32>, MetalError> {
|
||||
let level = upload
|
||||
.subresource(layer, mip)
|
||||
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
|
||||
let (format, name) = match upload.format() {
|
||||
BcAlphaFormat::Bc2 => (MTLPixelFormat::BC2_RGBA, "BC2"),
|
||||
BcAlphaFormat::Bc3 => (MTLPixelFormat::BC3_RGBA, "BC3"),
|
||||
};
|
||||
let pixels = self.validate_bc_extent(level.width, level.height, name)?;
|
||||
self.read_bc_blocks(
|
||||
format,
|
||||
level.bytes,
|
||||
level.row_pitch,
|
||||
level.width,
|
||||
level.height,
|
||||
pixels,
|
||||
)
|
||||
}
|
||||
|
||||
/// Read a selected subresource from a validated pitched BC4 or BC5 upload.
|
||||
///
|
||||
/// The original blocks go to a native `BC4_R*` or `BC5_RG*` texture.
|
||||
/// Unsigned output has the layout of [`Self::read_bc1_upload`]. Signed
|
||||
/// output stores each channel, times 127 and rounded, as a two's-complement
|
||||
/// byte in the same order. Metal fills missing green and blue with 0 and
|
||||
/// alpha with 1.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for an invalid layer or mip, out-of-policy size,
|
||||
/// unavailable BC compression (operation `supportsBCTextureCompression`),
|
||||
/// or Metal setup or execution failure.
|
||||
pub fn read_bc_channel_upload(
|
||||
&self,
|
||||
upload: &BcChannelUpload<'_>,
|
||||
layer: usize,
|
||||
mip: u32,
|
||||
) -> Result<Vec<u32>, MetalError> {
|
||||
let level = upload
|
||||
.subresource(layer, mip)
|
||||
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
|
||||
let (format, name) = match upload.format() {
|
||||
BcChannelFormat::Bc4Unorm => (MTLPixelFormat::BC4_RUnorm, "BC4 UNORM"),
|
||||
BcChannelFormat::Bc4Snorm => (MTLPixelFormat::BC4_RSnorm, "BC4 SNORM"),
|
||||
BcChannelFormat::Bc5Unorm => (MTLPixelFormat::BC5_RGUnorm, "BC5 UNORM"),
|
||||
BcChannelFormat::Bc5Snorm => (MTLPixelFormat::BC5_RGSnorm, "BC5 SNORM"),
|
||||
};
|
||||
let pixels = self.validate_bc_extent(level.width, level.height, name)?;
|
||||
self.read_bc_blocks(
|
||||
format,
|
||||
level.bytes,
|
||||
level.row_pitch,
|
||||
level.width,
|
||||
level.height,
|
||||
pixels,
|
||||
)
|
||||
}
|
||||
|
||||
fn validate_bc_extent(
|
||||
&self,
|
||||
width: usize,
|
||||
height: usize,
|
||||
name: &str,
|
||||
) -> Result<usize, MetalError> {
|
||||
let pixels = width
|
||||
.checked_mul(height)
|
||||
.filter(|pixels| (1..=MAX_GRID_WORDS).contains(pixels))
|
||||
.ok_or_else(|| MetalError::new("texture bounds", "expected 1..=4096 texels"))?;
|
||||
if !self.device.supportsBCTextureCompression() {
|
||||
return Err(MetalError::new(
|
||||
"supportsBCTextureCompression",
|
||||
"BC1 is unavailable",
|
||||
MetalError::BC_UNAVAILABLE,
|
||||
format!("{name} is unavailable"),
|
||||
));
|
||||
}
|
||||
Ok(pixels)
|
||||
}
|
||||
|
||||
fn read_bc1_blocks(
|
||||
fn read_bc_blocks(
|
||||
&self,
|
||||
format: MTLPixelFormat,
|
||||
blocks: &[u8],
|
||||
row_pitch: usize,
|
||||
width: usize,
|
||||
@@ -302,14 +421,11 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
pixels: usize,
|
||||
) -> Result<Vec<u32>, MetalError> {
|
||||
autoreleasepool(|_| {
|
||||
// SAFETY: The positive bounded dimensions and supported BC1 format
|
||||
// SAFETY: The positive bounded dimensions and supported BC format
|
||||
// describe a 2D texture with just its base level.
|
||||
let descriptor = unsafe {
|
||||
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
|
||||
MTLPixelFormat::BC1_RGBA,
|
||||
width,
|
||||
height,
|
||||
false,
|
||||
format, width, height, false,
|
||||
)
|
||||
};
|
||||
descriptor.setStorageMode(MTLStorageMode::Shared);
|
||||
@@ -318,7 +434,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
.device
|
||||
.newTextureWithDescriptor(&descriptor)
|
||||
.ok_or_else(|| {
|
||||
MetalError::new("newTextureWithDescriptor", "BC1 allocation failed")
|
||||
MetalError::new("newTextureWithDescriptor", "BC allocation failed")
|
||||
})?;
|
||||
let region = MTLRegion {
|
||||
origin: MTLOrigin { x: 0, y: 0, z: 0 },
|
||||
@@ -332,7 +448,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
let bytes_per_row = if height <= 4 { 0 } else { row_pitch };
|
||||
// SAFETY: The region spans the whole level, including any partial
|
||||
// edge block. Both callers validate that the input holds all rows
|
||||
// of complete BC1 blocks at the supplied, block-aligned stride.
|
||||
// of complete blocks of this format at the supplied, block-aligned
|
||||
// stride.
|
||||
unsafe {
|
||||
texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
|
||||
region,
|
||||
@@ -341,12 +458,14 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
bytes_per_row,
|
||||
);
|
||||
}
|
||||
self.run(
|
||||
BC1_READBACK,
|
||||
"read_bc1",
|
||||
ComputeInput::Texture(&texture, pixels),
|
||||
)
|
||||
.map(|profile| profile.output)
|
||||
let (source, entry) =
|
||||
if format == MTLPixelFormat::BC4_RSnorm || format == MTLPixelFormat::BC5_RGSnorm {
|
||||
(BC_SNORM_READBACK, "read_bc_snorm")
|
||||
} else {
|
||||
(BC_READBACK, "read_bc")
|
||||
};
|
||||
self.run(source, entry, ComputeInput::Texture(&texture, pixels))
|
||||
.map(|profile| profile.output)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -438,6 +557,56 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: &[u32],
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
self.run_profiled_words(source, entry, input, None)
|
||||
}
|
||||
|
||||
/// Run trusted MSL with an explicit one-dimensional threadgroup width.
|
||||
///
|
||||
/// The grid still contains one invocation per input word. The requested width
|
||||
/// is passed to Metal even when the grid is smaller or ends in a partial group.
|
||||
/// The trusted-kernel requirements of [`Self::run_words`] apply.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the same errors as [`Self::run_words_profiled`], with dispatch
|
||||
/// bounds evaluated using this width. Zero and widths above the device or
|
||||
/// pipeline limit are rejected.
|
||||
pub fn run_words_with_group_width(
|
||||
&self,
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: &[u32],
|
||||
width: usize,
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
self.run_profiled_words(source, entry, input, Some(width))
|
||||
}
|
||||
|
||||
/// Compile the kernel and report the smaller of the device and pipeline width limits.
|
||||
///
|
||||
/// Input size and threadgroup count are checked separately at dispatch.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if source validation, compilation or pipeline setup fails.
|
||||
pub fn max_group_width(&self, source: &str, entry: &str) -> Result<usize, MetalError> {
|
||||
validate_source(source, &[entry])?;
|
||||
autoreleasepool(|_| {
|
||||
let options = compile_options()?;
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline = self.compute_pipeline(&function)?;
|
||||
verify_shader_validation(&pipeline)?;
|
||||
Ok(self.pipeline_group_width_limit(&pipeline))
|
||||
})
|
||||
}
|
||||
|
||||
fn run_profiled_words(
|
||||
&self,
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: &[u32],
|
||||
group_width: Option<usize>,
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
|
||||
return Err(MetalError::new(
|
||||
@@ -446,7 +615,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
));
|
||||
}
|
||||
validate_source(source, &[entry])?;
|
||||
autoreleasepool(|_| self.run(source, entry, ComputeInput::Words(input)))
|
||||
autoreleasepool(|_| self.run_sized(source, entry, ComputeInput::Words(input), group_width))
|
||||
}
|
||||
|
||||
fn run(
|
||||
@@ -454,6 +623,18 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: ComputeInput<'_>,
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
self.run_sized(source, entry, input, None)
|
||||
}
|
||||
|
||||
/// [`Self::run`] with an optional explicit threadgroup width; `None` keeps
|
||||
/// the default sizing.
|
||||
fn run_sized(
|
||||
&self,
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: ComputeInput<'_>,
|
||||
group_width: Option<usize>,
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
let host_start = Instant::now();
|
||||
let options = compile_options()?;
|
||||
@@ -462,22 +643,21 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
let library_seconds = library_start.elapsed().as_secs_f64();
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline_start = Instant::now();
|
||||
let pipeline = self
|
||||
.device
|
||||
.newComputePipelineStateWithFunction_error(&function)
|
||||
.map_err(|error| {
|
||||
MetalError::new(
|
||||
"newComputePipelineStateWithFunction",
|
||||
error.localizedDescription().to_string(),
|
||||
)
|
||||
})?;
|
||||
let pipeline = self.compute_pipeline(&function)?;
|
||||
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
|
||||
verify_shader_validation(&pipeline)?;
|
||||
|
||||
let width = MAX_THREADS_PER_GROUP
|
||||
.min(input.len())
|
||||
.min(self.device.maxThreadsPerThreadgroup().width)
|
||||
.min(pipeline.maxTotalThreadsPerThreadgroup());
|
||||
let limit = self.pipeline_group_width_limit(&pipeline);
|
||||
let width = match group_width {
|
||||
Some(width) if (1..=limit).contains(&width) => width,
|
||||
Some(width) => {
|
||||
return Err(MetalError::new(
|
||||
"threadgroup width",
|
||||
format!("expected a nonzero width at most {limit}, got {width}"),
|
||||
));
|
||||
}
|
||||
None => MAX_THREADS_PER_GROUP.min(input.len()).min(limit),
|
||||
};
|
||||
if width == 0 || input.len().div_ceil(width) > MAX_GROUPS {
|
||||
return Err(MetalError::new(
|
||||
"dispatch bounds",
|
||||
@@ -568,6 +748,30 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
})
|
||||
}
|
||||
|
||||
fn compute_pipeline(
|
||||
&self,
|
||||
function: &ProtocolObject<dyn MTLFunction>,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {
|
||||
self.device
|
||||
.newComputePipelineStateWithFunction_error(function)
|
||||
.map_err(|error| {
|
||||
MetalError::new(
|
||||
"newComputePipelineStateWithFunction",
|
||||
error.localizedDescription().to_string(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn pipeline_group_width_limit(
|
||||
&self,
|
||||
pipeline: &ProtocolObject<dyn MTLComputePipelineState>,
|
||||
) -> usize {
|
||||
self.device
|
||||
.maxThreadsPerThreadgroup()
|
||||
.width
|
||||
.min(pipeline.maxTotalThreadsPerThreadgroup())
|
||||
}
|
||||
|
||||
fn new_buffer(
|
||||
&self,
|
||||
words: &[u32],
|
||||
|
||||
@@ -13,7 +13,11 @@ pub mod sampler;
|
||||
pub mod texture_pipeline;
|
||||
|
||||
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
|
||||
pub use compute::{GuestBuffer, GuestBufferView, MetalError, NativeCompute, RunProfile};
|
||||
pub use compute::{
|
||||
BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask, DepthCompare,
|
||||
DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer, GuestBufferView,
|
||||
IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile,
|
||||
};
|
||||
|
||||
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
|
||||
pub use sampler::MetalSampler;
|
||||
|
||||
+1133
-8
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,36 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CPU check: the blend reference agrees with the independently derived
|
||||
//! expectations for every blend case, colour and rounding flags alike. Runs
|
||||
//! without a GPU.
|
||||
|
||||
#[path = "support/blend_cases.rs"]
|
||||
mod blend_cases;
|
||||
|
||||
use blend_cases::{CLEAR, SIZE, cases, expected};
|
||||
use xenora_ref::blend::{RefBlendDraw, render_blend};
|
||||
|
||||
#[test]
|
||||
fn reference_matches_independent_expectations() {
|
||||
let (cases, expected) = (cases(), expected());
|
||||
assert_eq!(cases.len(), 39);
|
||||
assert_eq!(expected.len(), cases.len());
|
||||
for (case, want) in cases.iter().zip(&expected) {
|
||||
assert_eq!(case.name, want.name);
|
||||
let draws: Vec<_> = case
|
||||
.draws
|
||||
.iter()
|
||||
.map(|draw| RefBlendDraw {
|
||||
positions: draw.positions,
|
||||
color: draw.color,
|
||||
blend: draw.blend,
|
||||
mask: draw.mask,
|
||||
})
|
||||
.collect();
|
||||
let pixels = render_blend([SIZE, SIZE], CLEAR, &draws).expect("reference render");
|
||||
let color: Vec<_> = pixels.iter().map(|p| p.map(|c| c.value)).collect();
|
||||
let exact: Vec<_> = pixels.iter().map(|p| p.map(|c| c.exact)).collect();
|
||||
assert_eq!(color, want.color, "{} colour", case.name);
|
||||
assert_eq!(exact, want.exact, "{} rounding flags", case.name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CPU check: the reference rasteriser agrees with the independently derived
|
||||
//! expectations for every depth case. Runs without a GPU.
|
||||
|
||||
#[path = "support/depth_cases.rs"]
|
||||
mod depth_cases;
|
||||
|
||||
use depth_cases::{BC1_BLOCKS, Fill, SIZE, cases, expected};
|
||||
use xenora_ref::depth::{RefDraw, RefFill, RefTexture, render_depth};
|
||||
|
||||
/// Row-major 8x8 texels decoded block by block with the CPU BC1 decoder.
|
||||
pub fn bc1_texels() -> Vec<[u8; 4]> {
|
||||
let mut texels = vec![[0; 4]; 64];
|
||||
for (block, bytes) in BC1_BLOCKS.as_chunks::<8>().0.iter().enumerate() {
|
||||
let decoded = xenora_texture::decode_bc1(*bytes);
|
||||
for (index, texel) in decoded.iter().enumerate() {
|
||||
let x = (block % 2) * 4 + index % 4;
|
||||
let y = (block / 2) * 4 + index / 4;
|
||||
texels[y * 8 + x] = *texel;
|
||||
}
|
||||
}
|
||||
texels
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_matches_independent_expectations() {
|
||||
let texels = bc1_texels();
|
||||
let texture = RefTexture {
|
||||
width: 8,
|
||||
height: 8,
|
||||
texels: &texels,
|
||||
};
|
||||
let expected = expected();
|
||||
let cases = cases();
|
||||
assert_eq!(cases.len(), 30);
|
||||
assert_eq!(expected.len(), cases.len());
|
||||
for (case, want) in cases.iter().zip(&expected) {
|
||||
assert_eq!(case.name, want.name);
|
||||
let draws: Vec<_> = case
|
||||
.draws
|
||||
.iter()
|
||||
.map(|draw| RefDraw {
|
||||
positions: draw.positions,
|
||||
fill: match draw.fill {
|
||||
Fill::Flat(rgba) => RefFill::Flat(rgba),
|
||||
Fill::Texture => RefFill::Texture,
|
||||
},
|
||||
compare: draw.compare,
|
||||
write: draw.write,
|
||||
})
|
||||
.collect();
|
||||
let (color, depth) = render_depth(
|
||||
[SIZE, SIZE],
|
||||
case.clear_color,
|
||||
case.clear_depth,
|
||||
&draws,
|
||||
Some(texture),
|
||||
)
|
||||
.expect("reference render");
|
||||
assert_eq!(color, want.color, "{} colour", case.name);
|
||||
assert_eq!(depth, want.depth, "{} depth", case.name);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 272 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user