Compare commits
328
Commits
509b669db5
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1adf86dd5
|
||
|
|
2d5735cb13
|
||
|
|
dccf4d0775
|
||
|
|
c3589be1ad
|
||
|
|
49d7fca0b7
|
||
|
|
c649e02816
|
||
|
|
09d8778f04
|
||
|
|
1aa939eca8 | ||
|
|
a4bec5bc45
|
||
|
|
dcf6561ea7
|
||
|
|
69ad1931de
|
||
|
|
57992cf214
|
||
|
|
d9b9eeb171
|
||
|
|
f7d7c16753
|
||
|
|
07b69314b1 | ||
|
|
4669ced98e
|
||
|
|
a2275932a5
|
||
|
|
39468740c3
|
||
|
|
3f9d235546
|
||
|
|
bb6f212779
|
||
|
|
418e574ac8
|
||
|
|
461b554c1a
|
||
|
|
46bbad19c2
|
||
|
|
e09f1197bc
|
||
|
|
ff73f8ad39
|
||
|
|
bad942fb25
|
||
|
|
e0e01ed1de
|
||
|
|
3899b7f12c
|
||
|
|
6c2a07e579
|
||
|
|
0af8b2b1fe
|
||
|
|
23dc6fc66d
|
||
|
|
3e39a90083
|
||
|
|
9318cf7cd3
|
||
|
|
2e041266f1
|
||
|
|
ec84a6bba5
|
||
|
|
86bade3e1f
|
||
|
|
8732f4b0f4
|
||
|
|
61cf41f088
|
||
|
|
8381800fce
|
||
|
|
d48978988e
|
||
|
|
dd3594240e
|
||
|
|
c6fff08e7c
|
||
|
|
7e3d61c52d
|
||
|
|
78b6312d6b
|
||
|
|
dac72c5e73
|
||
|
|
63e371955a
|
||
|
|
74c7522dd1
|
||
|
|
1124ac10e7
|
||
|
|
c7236f1269
|
||
|
|
ba603ce64a
|
||
|
|
a9d91be39e
|
||
|
|
a563f3b456
|
||
|
|
43b466c813
|
||
|
|
01112da951
|
||
|
|
8d32fef65c
|
||
|
|
60d66d22a5
|
||
|
|
43314573d7
|
||
|
|
dff4041de7
|
||
|
|
126a9e50e7
|
||
|
|
01fab56cc6 | ||
|
|
4f10f6e584
|
||
|
|
e8e4d64e42
|
||
|
|
31ad7f9446
|
||
|
|
6d185ab97e | ||
|
|
89101d1b20
|
||
|
|
2516fae4fc | ||
|
|
e0c08c8b00
|
||
|
|
5b106af0f3 | ||
|
|
6ef376763c
|
||
|
|
f50a3f127f
|
||
|
|
f0f3f972ce
|
||
|
|
b2d2533acb
|
||
|
|
4b499288e2
|
||
|
|
aa3b31deb5 | ||
|
|
f784ccd774
|
||
|
|
7cced0709b
|
||
|
|
e2a5a67621
|
||
|
|
fbe4d0cac0
|
||
|
|
4c0f1cb9ad
|
||
|
|
94ffd241bd
|
||
|
|
a415c172c7
|
||
|
|
c89116b6f8
|
||
|
|
dc279fe72b
|
||
|
|
01221769cd
|
||
|
|
3cce8a2b25 | ||
|
|
de53eb5ad7
|
||
|
|
49cb16b6cb
|
||
|
|
3aec829c70
|
||
|
|
73c8246c8d
|
||
|
|
fa0a768b84
|
||
|
|
62573e9574
|
||
|
|
c814e057dc
|
||
|
|
8d719843c7
|
||
|
|
d6afa6ae6b
|
||
|
|
3df8227ebf
|
||
|
|
b30ff73e3d
|
||
|
|
dcd3479b1d
|
||
|
|
0ffb3467b1
|
||
|
|
313b896e7b | ||
|
|
6dc8cb5372
|
||
|
|
c34bbaf936
|
||
|
|
e613ab43c9
|
||
|
|
4e05daf280
|
||
|
|
8098dbd7f4
|
||
|
|
e01b463e1f
|
||
|
|
b8fc5a0534
|
||
|
|
f26731413f
|
||
|
|
fa2e329d4b
|
||
|
|
c3d6b70b0c
|
||
|
|
49a676ff86
|
||
|
|
23a181de46
|
||
|
|
bd27f5eb63
|
||
|
|
6646ccfbb5
|
||
|
|
0ecab2910b
|
||
|
|
3eeda25e97
|
||
|
|
a22215392d
|
||
|
|
e19409a2ef
|
||
|
|
a517a24978
|
||
|
|
a771f6320e
|
||
|
|
d645bbb7bd
|
||
|
|
5ff273f167
|
||
|
|
33f70d1c6e
|
||
|
|
999136fef3
|
||
|
|
1b29b2f985
|
||
|
|
29e002c5f3
|
||
|
|
57c9af939b
|
||
|
|
d54dadf2a5
|
||
|
|
126bffa37d
|
||
|
|
4bc9ce2b73 | ||
|
|
95465869b1
|
||
|
|
377cb41a3f
|
||
|
|
6593581954
|
||
|
|
badc9b8874
|
||
|
|
f49accc796
|
||
|
|
46b2fae514
|
||
|
|
7307870414
|
||
|
|
5137592cdd
|
||
|
|
68fd3bcd65
|
||
|
|
d39e03c7d9
|
||
|
|
2ab5c43334
|
||
|
|
23d3ed641e | ||
|
|
5d3db4c22a
|
||
|
|
b84946a3a0
|
||
|
|
0adec90f23
|
||
|
|
8747c4f4cf
|
||
|
|
961557583b
|
||
|
|
30c24a4ea7
|
||
|
|
7598a15782
|
||
|
|
54dad3b398
|
||
|
|
8f37d971cd
|
||
|
|
bd147938a0
|
||
|
|
443b1d7cfb | ||
|
|
21b5d59a7d
|
||
|
|
aa917cf44e
|
||
|
|
850ca8691b
|
||
|
|
67a629dbe4
|
||
|
|
6b5b27d068
|
||
|
|
cfb5b1ac89
|
||
|
|
0c6a669e6e
|
||
|
|
4b890850aa
|
||
|
|
28105c2bf2
|
||
|
|
76d4e9c8ce
|
||
|
|
57bf2b84d3
|
||
|
|
4c48b92f3b
|
||
|
|
12d314a62d
|
||
|
|
3916a652b2
|
||
|
|
cafbc42018
|
||
|
|
1022750c12
|
||
|
|
373f842bef
|
||
|
|
a761e73587
|
||
|
|
b4f7b4f3c0
|
||
|
|
9cf9fa6163
|
||
|
|
117a18ee72
|
||
|
|
f45b3a38cb
|
||
|
|
5381ae02b1
|
||
|
|
1d6b799960
|
||
|
|
d0a2682366
|
||
|
|
c62aef51ba
|
||
|
|
d2bace2612
|
||
|
|
6f3df74e79
|
||
|
|
18cfeedbff
|
||
|
|
a268bd0b75
|
||
|
|
9b03d13a0a
|
||
|
|
80a36a3e7a
|
||
|
|
26e038e195
|
||
|
|
df0d7949c8
|
||
|
|
8cd218dc04
|
||
|
|
e4c1390614
|
||
|
|
8c43d85ce8
|
||
|
|
f01822bd53
|
||
|
|
c88c927fee
|
||
|
|
3521eec319
|
||
|
|
dcfc258aeb
|
||
|
|
84daa5fd70
|
||
|
|
d2a53d0efa
|
||
|
|
b06462111a
|
||
|
|
51f6a36b1d
|
||
|
|
6cb0918715
|
||
|
|
38a3edc0fd
|
||
|
|
261d9561a4 | ||
|
|
5ba47eb20a
|
||
|
|
91fab7de96
|
||
|
|
232fb7106d
|
||
|
|
d79c11faa8
|
||
|
|
295666b310
|
||
|
|
41266d3fd5
|
||
|
|
74df4b89ac
|
||
|
|
ae85ed4eff
|
||
|
|
5e00f6bb0d
|
||
|
|
57439846c5
|
||
|
|
5e3cb87b57
|
||
|
|
7c35edcb84
|
||
|
|
c3396f5a61
|
||
|
|
105a6de11e
|
||
|
|
96a23e5419
|
||
|
|
2b69be0f11
|
||
|
|
38544ed3f1
|
||
|
|
ab0e577c6f
|
||
|
|
d2fbe62f7a | ||
|
|
a07104aad1
|
||
|
|
d9c208ad4f
|
||
|
|
f9a86fafb0
|
||
|
|
537096057a
|
||
|
|
f273745589
|
||
|
|
c4c2dfb017
|
||
|
|
668a061964
|
||
|
|
1256d33a72
|
||
|
|
4d5818c244
|
||
|
|
88ac752d9e
|
||
|
|
70c6bd17c8
|
||
|
|
eb398846a0
|
||
|
|
74ef393294
|
||
|
|
13fc1bdbe4
|
||
|
|
2e214b544b
|
||
|
|
8f74bd2b22
|
||
|
|
c16c5a426c
|
||
|
|
1393eeb54f
|
||
|
|
414bdd0333
|
||
|
|
edfac5a99b
|
||
|
|
f62be06dc5
|
||
|
|
fa485ff0a2 | ||
|
|
82a3380426
|
||
|
|
c2698e6a22
|
||
|
|
d929f8e2f1
|
||
|
|
32b838f9c4
|
||
|
|
2154dba080
|
||
|
|
a8e3040d1e
|
||
|
|
1663ab5413
|
||
|
|
15615f3b54
|
||
|
|
a0601fe816
|
||
|
|
4207a193e8 | ||
|
|
4d2ea6400d
|
||
|
|
bfe900797f
|
||
|
|
f36fd1ed7c | ||
|
|
aebebcae04
|
||
|
|
df9f82fcd2
|
||
|
|
569707d002
|
||
|
|
fbebd8887a
|
||
|
|
5282089c7d | ||
|
|
deaababb1e
|
||
|
|
446044c4e6
|
||
|
|
d1f4547e44
|
||
|
|
ab825d3274
|
||
|
|
28cb21118b
|
||
|
|
cccbd48e57
|
||
|
|
c1f5691cd8 | ||
|
|
be684ab0f9
|
||
|
|
6694bd2dd1 | ||
|
|
2bfbe3b2be
|
||
|
|
6de583c9d4
|
||
|
|
20e8439416
|
||
|
|
bea3f76aa7
|
||
|
|
da908ffcb4
|
||
|
|
e3ac3dfd06
|
||
|
|
4d34e08c6c
|
||
|
|
673df0ae6f
|
||
|
|
d4106253e8 | ||
|
|
29d531f622
|
||
|
|
983e4cfc29 | ||
|
|
1bd64e6bc5
|
||
|
|
eda9c6e613
|
||
|
|
b82363d065
|
||
|
|
38fc71f739
|
||
|
|
1ab2898f5e
|
||
|
|
6a681ba4bc
|
||
|
|
4ca53046bf
|
||
|
|
d10d5aa7db
|
||
|
|
b0762c776a | ||
|
|
1c91d1c2df
|
||
|
|
0c8de434cf
|
||
|
|
92be3b90fb
|
||
|
|
41801a8e7a
|
||
|
|
4227d26101
|
||
|
|
0d6ff430a0
|
||
|
|
26686c288c
|
||
|
|
c52f196b7a
|
||
|
|
5984eaaf24
|
||
|
|
15e1e2321e
|
||
|
|
401a56a4c6
|
||
|
|
6ed3f24b1c
|
||
|
|
7b1c3f256a | ||
|
|
27e034f89f
|
||
|
|
eddd99b754
|
||
|
|
77351a8813
|
||
|
|
6bd4c13d24
|
||
|
|
cbc94768a5
|
||
|
|
cdb8dfb2ac
|
||
|
|
b04bbed617
|
||
|
|
3c32f26f79 | ||
|
|
c78f091efe
|
||
|
|
193fe78b5e
|
||
|
|
f0663856c3
|
||
|
|
f622387f4a
|
||
|
|
dc58794656 | ||
|
|
cd6bf6b313
|
||
|
|
8937963819
|
||
|
|
762f60e00f
|
||
|
|
811af09ea7
|
||
|
|
09821cf9cc
|
||
|
|
8c5957a0a9
|
||
|
|
affd0eb118
|
||
|
|
88eaf16045 | ||
|
|
4ee7eff2fb
|
||
|
|
c87a1b7f62
|
||
|
|
33dd6d008b
|
||
|
|
52785b5a8c
|
||
|
|
aaf4dff69d
|
||
|
|
e895b01b8f
|
@@ -13,17 +13,27 @@ jobs:
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt, clippy
|
||||
- name: Install repository Rust toolchain
|
||||
run: |
|
||||
toolchain=$(python3 -c 'import tomllib; print(tomllib.load(open("rust-toolchain.toml", "rb"))["toolchain"]["channel"])')
|
||||
rustup toolchain install "$toolchain" --profile minimal
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
|
||||
- name: Format check
|
||||
run: cargo fmt -- --check
|
||||
- name: Discard reports from previous runs
|
||||
run: rm -rf target/llvm-cov
|
||||
|
||||
- name: Clippy
|
||||
run: cargo clippy --workspace --all-features
|
||||
- name: Provision quality-gate tools and native dependencies
|
||||
run: bash scripts/provision-quality-gate.sh
|
||||
|
||||
- name: Test
|
||||
run: cargo test --workspace --all-targets --all-features --no-fail-fast
|
||||
- name: Repository quality gate
|
||||
run: make ci-domains
|
||||
|
||||
- name: Publish gate evidence (including failures)
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: quality-gate-${{ runner.os }}-${{ github.sha }}
|
||||
path: |
|
||||
target/llvm-cov/**
|
||||
if-no-files-found: warn
|
||||
|
||||
+6
-1
@@ -1,4 +1,5 @@
|
||||
# ===== Rust / Cargo =====
|
||||
.cargo/config.toml
|
||||
/target/
|
||||
**/target/
|
||||
|
||||
@@ -10,6 +11,7 @@
|
||||
# RustRover / IntelliJ
|
||||
.idea/
|
||||
*.iml
|
||||
.junie
|
||||
|
||||
# VS Code
|
||||
.vscode/
|
||||
@@ -60,4 +62,7 @@ temp/**
|
||||
**/build/**
|
||||
**/node_modules/**
|
||||
|
||||
AGENTS.md
|
||||
AGENTS.md
|
||||
|
||||
.python-version
|
||||
.venv
|
||||
|
||||
Generated
+1167
-346
File diff suppressed because it is too large
Load Diff
+3
-4
@@ -1,16 +1,15 @@
|
||||
[workspace]
|
||||
members = [
|
||||
"crates/console/prometeu-bytecode",
|
||||
|
||||
"crates/console/prometeu-bytecode",
|
||||
"crates/console/prometeu-drivers",
|
||||
"crates/console/prometeu-firmware",
|
||||
"crates/console/prometeu-hal",
|
||||
"crates/console/prometeu-system",
|
||||
"crates/console/prometeu-vm",
|
||||
|
||||
"crates/host/prometeu-host-desktop-winit",
|
||||
|
||||
"crates/host/prometeu-host-headless",
|
||||
"crates/tools/prometeu-cli",
|
||||
"crates/tools/pbxgen-dummy-boy",
|
||||
"crates/tools/pbxgen-stress",
|
||||
"crates/dev/prometeu-test-support",
|
||||
"crates/dev/prometeu-layer-tests",
|
||||
|
||||
@@ -1,25 +1,35 @@
|
||||
.PHONY: fmt fmt-check clippy tes-local test-debugger-socket test ci cobertura
|
||||
.PHONY: fmt fmt-check clippy test-unit test-local test-integration test-debugger-socket clean coverage coverage-xml coverage-json coverage-report-json coverage-domain-list coverage-domain-evidence coverage-domain-audit coverage-domain-gate test ci ci-domains cobertura
|
||||
|
||||
fmt:
|
||||
cargo fmt
|
||||
cargo fmt --all
|
||||
|
||||
fmt-check:
|
||||
cargo fmt -- --check
|
||||
cargo fmt --all -- --check
|
||||
|
||||
clippy:
|
||||
cargo clippy --workspace --all-features
|
||||
cargo clippy --workspace --all-targets --all-features -- -D warnings
|
||||
|
||||
test-local:
|
||||
cargo test --workspace --all-targets --all-features --no-fail-fast
|
||||
test-unit:
|
||||
cargo test --workspace --lib --bins --all-features --no-fail-fast
|
||||
|
||||
# Compatibility entry point: repository-local verification is unit-only.
|
||||
test-local: test-unit
|
||||
|
||||
# Explicit opt-in, orchestrated by ../tooling; test sources stay in this repository.
|
||||
test-integration:
|
||||
cargo test --workspace --tests --all-features --no-fail-fast
|
||||
|
||||
test-debugger-socket:
|
||||
cargo test -p prometeu-host-desktop-winit --lib -- --ignored
|
||||
cargo test -p prometeu-host-desktop-winit --lib runner::tests -- --ignored
|
||||
|
||||
clean:
|
||||
cargo llvm-cov clean --workspace
|
||||
|
||||
coverage:
|
||||
cargo llvm-cov --workspace --all-features --html --output-dir target/llvm-cov
|
||||
cargo llvm-cov --workspace --lib --bins --all-features --html --output-dir target/llvm-cov
|
||||
|
||||
coverage-report-json:
|
||||
cargo llvm-cov report --json --output-path target/llvm-cov/report.json
|
||||
|
||||
coverage-xml:
|
||||
cargo llvm-cov report --cobertura --output-path target/llvm-cov/cobertura.xml
|
||||
@@ -27,6 +37,29 @@ coverage-xml:
|
||||
coverage-json:
|
||||
cargo llvm-cov report --json --summary-only --output-path target/llvm-cov/summary.json
|
||||
|
||||
test: fmt-check clippy test-local test-debugger-socket
|
||||
ci: clean fmt-check clippy coverage
|
||||
coverage-domain-list:
|
||||
./scripts/coverage-domain-evidence.sh --list
|
||||
|
||||
coverage-domain-audit:
|
||||
python3 scripts/audit-coverage-domains.py --report target/llvm-cov/report.json
|
||||
|
||||
coverage-domain-evidence:
|
||||
@if [ -z "$(DOMAIN)" ]; then \
|
||||
echo "usage: make coverage-domain-evidence DOMAIN=<domain>"; \
|
||||
exit 1; \
|
||||
fi
|
||||
./scripts/coverage-domain-evidence.sh "$(DOMAIN)"
|
||||
|
||||
coverage-domain-gate:
|
||||
./scripts/coverage-domain-evidence.sh --check-all
|
||||
|
||||
test: fmt-check clippy test-unit
|
||||
# Local and GitHub entry point; Jenkins exposes the same targets as stages.
|
||||
CI_DOMAIN_STEPS = clean fmt-check clippy test-unit coverage coverage-report-json coverage-xml coverage-json coverage-domain-audit coverage-domain-gate
|
||||
|
||||
ci: ci-domains
|
||||
ci-domains:
|
||||
rm -rf target/llvm-cov
|
||||
+@set -e; for step in $(CI_DOMAIN_STEPS); do $(MAKE) --no-print-directory -j1 $$step; done
|
||||
|
||||
cobertura: coverage-xml coverage-json
|
||||
|
||||
@@ -1,95 +1,205 @@
|
||||
# PROMETEU
|
||||
# PROMETEU Runtime
|
||||
|
||||
PROMETEU is an **educational and experimental fantasy handheld / fantasy console ecosystem** inspired by classic consoles, focusing on **teaching programming, system architecture, and hardware concepts through software**.
|
||||
PROMETEU is an educational and experimental fantasy handheld / fantasy console.
|
||||
This repository contains the Rust runtime workspace for the machine: VM-facing components, virtual peripherals, firmware/system services, host integration, CLI entrypoints, development utilities, specs, and engineering lessons.
|
||||
|
||||
> PROMETEU is a fantasy console with a simple, explicit, and educational VM/runtime inside it.
|
||||
The VM is only one subsystem of the machine. The canonical docs in this repository intentionally distinguish:
|
||||
|
||||
---
|
||||
- machine-level specs;
|
||||
- VM/runtime internal architecture;
|
||||
- implementation crates;
|
||||
- engineering lessons learned.
|
||||
|
||||
## 🎯 Project Goals
|
||||
## What This Repository Contains
|
||||
|
||||
- **Simulate simple "logical hardware"**: Create a low entry barrier for understanding how computers work.
|
||||
- **Deterministic Loop**: Ensure the same code produces the same result on any platform.
|
||||
- **Total Portability**: The core does not depend on an operating system, allowing it to run from modern computers to dedicated hardware.
|
||||
- **First-Class Tools**: Offer deep debugging and inspection as a central part of the experience.
|
||||
- **DIY hardware affinity**: Keep the machine model close enough to handheld/console-era hardware that it can inform real embedded and homebrew-style implementations.
|
||||
- `crates/console/`: core machine/runtime crates such as `prometeu-vm`, `prometeu-system`, `prometeu-hal`, `prometeu-drivers`, and `prometeu-firmware`
|
||||
- `crates/host/`: host-side execution surfaces, currently including `prometeu-host-desktop-winit`
|
||||
- `crates/tools/`: user-facing and support binaries such as `prometeu` and `pbxgen-stress`
|
||||
- `crates/dev/`: test support, layer tests, and quality-check utilities
|
||||
- `docs/specs/runtime/`: canonical PROMETEU machine specs
|
||||
- `docs/vm-arch/`: canonical VM/runtime architecture and ISA references
|
||||
- `devtools/`: debugger protocol material
|
||||
- `discussion/lessons/`: published engineering lessons and supporting assets
|
||||
- `test-cartridges/`: cartridge fixtures used for validation and manual runs
|
||||
|
||||
---
|
||||
## Canonical Documentation
|
||||
|
||||
## 🧠 Design Philosophy
|
||||
Use these entrypoints instead of inferring the model from isolated source files:
|
||||
|
||||
- **No magic**: everything is explicit.
|
||||
- **No implicit heuristics**: the system doesn't "guess intentions".
|
||||
- **Deterministic**: same input → same result.
|
||||
- **Hardware-first**: APIs model peripherals, not modern frameworks.
|
||||
- **Portable by definition**: if it doesn't work on all platforms, it doesn't exist.
|
||||
- **Console-era sensibility**: PROMETEU carries intentional influence from NES, SNES, Mega Drive, Game Boy, GBA, CPS-2, and adjacent DIY-friendly hardware thinking.
|
||||
- [Machine specs](docs/specs/runtime/README.md): authoritative contract for the PROMETEU machine, peripherals, firmware, cartridge format, timing, and host ABI
|
||||
- [VM architecture](docs/vm-arch/ARCHITECTURE.md): authoritative internal architecture for VM/runtime invariants
|
||||
- [ISA reference](docs/vm-arch/ISA_CORE.md): bytecode-level instruction set authority
|
||||
- [Engineering lessons](discussion/lessons/): published results and rationale
|
||||
|
||||
## 🧭 Canonical Architecture
|
||||
Engineering discussions, decisions, plans and execution evidence are maintained in
|
||||
the enclosing [Prometeu Engineering workspace](../README.md) using
|
||||
[AI Engineering](../.ai-engineering/README.md).
|
||||
|
||||
PROMETEU is the machine. The VM/runtime is one subsystem inside that machine.
|
||||
## Workspace Layout
|
||||
|
||||
Authoritative documents:
|
||||
This repository is a Rust workspace rooted at [Cargo.toml](Cargo.toml) with members in:
|
||||
|
||||
- [`docs/runtime/virtual-machine/ARCHITECTURE.md`](docs/vm-arch/ARCHITECTURE.md) is normative for VM/runtime invariants.
|
||||
- [`docs/runtime/specs/README.md`](docs/specs/runtime/README.md) describes the broader PROMETEU machine, hardware model, and fantasy console context.
|
||||
- Supporting material under `docs/` may expand, explain, or propose changes, but it must not silently collapse the whole machine into the VM layer.
|
||||
- `crates/console`
|
||||
- `crates/host`
|
||||
- `crates/tools`
|
||||
- `crates/dev`
|
||||
|
||||
---
|
||||
The main user-facing dispatcher binary is `prometeu`, built from `crates/tools/prometeu-cli`.
|
||||
The same package also builds `prometeu-runtime`, which embeds the current desktop host runtime.
|
||||
|
||||
## 📦 Monorepo Structure
|
||||
Current CLI surface:
|
||||
|
||||
This repository is organized as a Rust workspace and contains several components:
|
||||
- `prometeu run <cart>`
|
||||
- `prometeu debug <cart> --port <port>`
|
||||
|
||||
- **[crates/](./crates)**: Software implementation in Rust.
|
||||
- **[prometeu](crates/tools/prometeu)**: Unified command-line interface (CLI).
|
||||
- **[prometeu-drivers](crates/console/prometeu-drivers)**: The virtual hardware (GPU, SPU, Input).
|
||||
- **[prometeu-host-desktop-winit](crates/host/prometeu-host-desktop-winit)**: Host for execution on Desktop systems.
|
||||
- **[docs/](./docs)**: Technical documentation and system specifications.
|
||||
- **[devtools-protocol/](devtools)**: Definition of the communication protocol for development tools.
|
||||
- **[test-cartridges/](./test-cartridges)**: Cartridge examples and test suites.
|
||||
The dispatcher forwards runtime execution to `prometeu-runtime`.
|
||||
For lower-level local runs, `prometeu-runtime` also accepts:
|
||||
|
||||
---
|
||||
- `--run <cart>`
|
||||
- `--debug <cart> --port <port>`
|
||||
- `--fs-root <path>`
|
||||
- `--cap <path>`
|
||||
|
||||
## 🛠️ Requirements
|
||||
Other ecosystem commands, such as build, pack, and verification tooling, are not part of the current dispatcher surface in this workspace.
|
||||
|
||||
- **Rust**: Version defined in `rust-toolchain.toml`.
|
||||
- **Installation**: Use [rustup](https://rustup.rs/) to install the required toolchain.
|
||||
## Requirements
|
||||
|
||||
---
|
||||
- Rust **1.98.1**, pinned in [rust-toolchain.toml](rust-toolchain.toml)
|
||||
- `rustup` for toolchain installation and management
|
||||
- `cargo-llvm-cov` for coverage targets such as `make coverage` and `make ci-domains`
|
||||
- a local graphical environment for desktop runtime commands
|
||||
|
||||
## ▶️ Quick Start
|
||||
From the repository root, install and verify the pinned toolchain:
|
||||
|
||||
To compile the full project:
|
||||
```bash
|
||||
rustup toolchain install 1.98.1 --profile minimal --component rustfmt,clippy
|
||||
rustc --version
|
||||
```
|
||||
|
||||
Rustup selects the pinned version automatically for commands run in this repository.
|
||||
CI installs the toolchain from the same file.
|
||||
|
||||
## Quick Start
|
||||
|
||||
Build the workspace:
|
||||
|
||||
```bash
|
||||
cargo build
|
||||
```
|
||||
|
||||
To run an example cartridge:
|
||||
Inspect the CLI:
|
||||
|
||||
```bash
|
||||
./target/debug/prometeu run test-cartridges/color-square-ts
|
||||
cargo run -q -p prometeu-cli --bin prometeu -- --help
|
||||
```
|
||||
|
||||
For more details on how to use the CLI, see the **[prometeu](crates/tools/prometeu)** README.
|
||||
Run the current stress cartridge fixture:
|
||||
|
||||
---
|
||||
```bash
|
||||
cargo run -q -p prometeu-cli --bin prometeu -- run test-cartridges/stress-console
|
||||
```
|
||||
|
||||
## 🚧 Project Status
|
||||
Run the embedded runtime binary directly:
|
||||
|
||||
⚠️ **Early stage (bootstrap)**
|
||||
```bash
|
||||
cargo run -q -p prometeu-cli --bin prometeu-runtime -- --run test-cartridges/stress-console
|
||||
```
|
||||
|
||||
Currently, the focus is on stabilizing the core architecture and debugging protocol. Nothing here should be considered a stable API yet.
|
||||
Regenerate and run the stress cartridge fixture:
|
||||
|
||||
---
|
||||
```bash
|
||||
./scripts/run-stress.sh
|
||||
```
|
||||
|
||||
## 📜 License
|
||||
The desktop runtime opens a native window through the host layer, so runtime commands are intended for a local graphical environment.
|
||||
|
||||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
||||
## Validation
|
||||
|
||||
---
|
||||
Format, lint, and test the workspace:
|
||||
|
||||
## ✨ Final Note
|
||||
```bash
|
||||
make test
|
||||
```
|
||||
|
||||
PROMETEU is both a technical and pedagogical project. The idea is not to hide complexity, but to **expose the right complexity**, at the right level, so it can be understood, studied, and explored.
|
||||
Run the shared strict CI gate (`make ci` is an alias):
|
||||
|
||||
```bash
|
||||
make ci
|
||||
```
|
||||
|
||||
The authoritative target used by both GitHub and Jenkins is:
|
||||
|
||||
```bash
|
||||
make ci-domains
|
||||
```
|
||||
|
||||
`make test-unit` selects library and binary unit-test harnesses with
|
||||
`--lib --bins --all-features`; `test-local` remains an alias. Both `make test`
|
||||
and `make ci-domains` run only this suite. Integration targets under `tests/`,
|
||||
installed-process qualification and the five ignored debugger socket tests are
|
||||
excluded from the pipeline. They remain available explicitly through
|
||||
`make test-integration` and `make test-debugger-socket`, orchestrated by
|
||||
`../tooling`. Tests and fixtures stay in this repository. Physical audio and manual probes remain opt-in. See
|
||||
[quality-gate prerequisites and commands](docs/vm-arch/COVERAGE_DOMAINS.md#commands-and-ci).
|
||||
|
||||
## Coverage Governance
|
||||
|
||||
The repository uses a two-layer runtime-edge coverage model:
|
||||
|
||||
- a mandatory CI gate based on canonical runtime-edge domains;
|
||||
- domain-oriented review evidence for the canonical runtime-edge domains.
|
||||
|
||||
The fifteen canonical domains and fixed floors are defined in
|
||||
[the repository configuration](files/config/runtime-edge-coverage-domains.json).
|
||||
Use `make coverage-domain-list` or the [ownership documentation](docs/vm-arch/COVERAGE_DOMAINS.md)
|
||||
to inspect the current map.
|
||||
|
||||
Global coverage artifacts:
|
||||
|
||||
```bash
|
||||
make ci-domains
|
||||
```
|
||||
|
||||
This produces:
|
||||
|
||||
- `target/llvm-cov/html`
|
||||
- `target/llvm-cov/report.json`
|
||||
- `target/llvm-cov/summary.json`
|
||||
- `target/llvm-cov/cobertura.xml`
|
||||
|
||||
Domain-oriented evidence helpers:
|
||||
|
||||
```bash
|
||||
make coverage-domain-list
|
||||
make coverage-domain-evidence DOMAIN=firmware
|
||||
make coverage-domain-evidence DOMAIN=host-dependent
|
||||
make coverage-domain-evidence DOMAIN=host/headless
|
||||
```
|
||||
|
||||
`make ci-domains` runs formatting, strict workspace/all-target/all-feature Clippy,
|
||||
library/binary unit tests, fresh unit-only coverage and every domain
|
||||
ownership/evidence gate. Both CI providers archive available evidence on failure.
|
||||
A failing run never lowers a configured floor; local and CI checks use the same
|
||||
repository-owned commands. Reports identify their revision, source/configuration
|
||||
and actual execution platform.
|
||||
|
||||
When a PR changes the observable contract of a canonical domain, it is expected to:
|
||||
|
||||
- add or adjust tests for that domain; or
|
||||
- justify explicitly why the observable contract did not change.
|
||||
|
||||
Improving the global percentage alone is not sufficient review evidence when the changed behavior belongs to a canonical domain.
|
||||
|
||||
## Current State
|
||||
|
||||
The project is still in active architectural and implementation convergence.
|
||||
|
||||
- the machine contract is being clarified through the specs and AI Engineering;
|
||||
- the workspace already contains concrete runtime and host code;
|
||||
- the CLI dispatcher currently exposes the runtime paths that are backed by binaries in this workspace.
|
||||
|
||||
Treat APIs, file formats, and execution flows as evolving unless the relevant spec explicitly defines them as stable.
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the [MIT License](LICENSE).
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
|
||||
0.1.0
|
||||
|
||||
@@ -6,4 +6,4 @@ license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde = { version = "1.0", features = ["derive", "rc"] }
|
||||
|
||||
@@ -24,6 +24,21 @@ pub const TRAP_BAD_RET_SLOTS: u32 = 0x0000_000C;
|
||||
/// The intrinsic ID provided is not recognized by the runtime, or its metadata is invalid.
|
||||
pub const TRAP_INVALID_INTRINSIC: u32 = 0x0000_000D;
|
||||
|
||||
/// Valid absence used where an instance is required.
|
||||
pub const TRAP_NULL_REFERENCE: u32 = 0x0000_000E;
|
||||
/// Invalid, dead or stale generational heap reference.
|
||||
pub const TRAP_INVALID_HANDLE: u32 = 0x0000_000F;
|
||||
/// Quota, checked size overflow or recoverable allocation failure.
|
||||
pub const TRAP_RESOURCE_LIMIT: u32 = 0x0000_0010;
|
||||
/// Known input query unavailable on this platform.
|
||||
pub const TRAP_UNAVAILABLE: u32 = 0x0000_0011;
|
||||
/// Mathematical domain is invalid for the supplied finite arguments.
|
||||
pub const TRAP_NUMERIC_DOMAIN: u32 = 0x0000_0012;
|
||||
/// Finite input produces an unrepresentable result or integer destination.
|
||||
pub const TRAP_NUMERIC_RANGE: u32 = 0x0000_0013;
|
||||
/// A NaN or infinite input cannot enter guest numeric computation.
|
||||
pub const TRAP_NON_FINITE: u32 = 0x0000_0014;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Detailed information about a source code span.
|
||||
@@ -47,4 +62,9 @@ pub struct TrapInfo {
|
||||
pub pc: u32,
|
||||
/// Optional source span information if debug symbols are available.
|
||||
pub span: Option<SourceSpan>,
|
||||
/// Machine-readable quota context; messages are not its serialization.
|
||||
pub resource: Option<crate::ResourceFailure>,
|
||||
}
|
||||
|
||||
/// All 64 unbiased bounded-random candidates were rejected.
|
||||
pub const TRAP_RANDOM_REJECTION_LIMIT: u32 = 0x0000_0015;
|
||||
|
||||
@@ -58,7 +58,7 @@ fn parse_f64_bits(s: &str) -> Result<u64, AsmError> {
|
||||
}
|
||||
|
||||
fn parse_keyvals(s: &str) -> Result<(&str, &str), AsmError> {
|
||||
// Parses formats like: "fn=123, captures=2" or "fn=3, argc=1"
|
||||
// Parses keyed u32 immediates such as "fn=123, type=2" or "type=3, method=1"
|
||||
let mut parts = s.split(',');
|
||||
let a = parts.next().ok_or_else(|| AsmError::MissingOperand(s.into()))?.trim();
|
||||
let b = parts.next().ok_or_else(|| AsmError::MissingOperand(s.into()))?.trim();
|
||||
@@ -102,6 +102,7 @@ pub fn assemble(src: &str) -> Result<Vec<u8>, AsmError> {
|
||||
"NOP" => {
|
||||
emit_u16(CoreOpCode::Nop as u16, &mut out);
|
||||
}
|
||||
"POP" => emit_u16(CoreOpCode::Pop as u16, &mut out),
|
||||
"HALT" => {
|
||||
emit_u16(CoreOpCode::Halt as u16, &mut out);
|
||||
}
|
||||
@@ -177,8 +178,8 @@ pub fn assemble(src: &str) -> Result<Vec<u8>, AsmError> {
|
||||
"RET" => {
|
||||
emit_u16(CoreOpCode::Ret as u16, &mut out);
|
||||
}
|
||||
"YIELD" => {
|
||||
emit_u16(CoreOpCode::Yield as u16, &mut out);
|
||||
"YIELD" | "SLEEP" | "SPAWN" => {
|
||||
return Err(AsmError::InvalidOperand("retired coroutine instruction".into()));
|
||||
}
|
||||
"FRAME_SYNC" => {
|
||||
emit_u16(CoreOpCode::FrameSync as u16, &mut out);
|
||||
@@ -284,60 +285,35 @@ pub fn assemble(src: &str) -> Result<Vec<u8>, AsmError> {
|
||||
emit_u16(CoreOpCode::Call as u16, &mut out);
|
||||
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||
}
|
||||
"CALL_CLOSURE" => {
|
||||
"CALL_CLOSURE" | "GET_CAPTURE" => {
|
||||
if ops.is_empty() {
|
||||
return Err(AsmError::MissingOperand(line.into()));
|
||||
}
|
||||
let (k, v) =
|
||||
ops.split_once('=').ok_or_else(|| AsmError::InvalidOperand(ops.into()))?;
|
||||
if k.trim() != "argc" {
|
||||
return Err(AsmError::InvalidOperand(ops.into()));
|
||||
}
|
||||
emit_u16(CoreOpCode::CallClosure as u16, &mut out);
|
||||
emit_u32(parse_u32_any(v)?, &mut out);
|
||||
}
|
||||
"MAKE_CLOSURE" => {
|
||||
if ops.is_empty() {
|
||||
return Err(AsmError::MissingOperand(line.into()));
|
||||
}
|
||||
let (a, b) = parse_keyvals(ops)?;
|
||||
// Accept either order but require exact key names
|
||||
let (fn_id, captures) = if a.starts_with("fn=") && b.starts_with("captures=") {
|
||||
parse_pair(a, "fn", b, "captures")?
|
||||
} else if a.starts_with("captures=") && b.starts_with("fn=") {
|
||||
let (cap, fid) = parse_pair(a, "captures", b, "fn")?;
|
||||
(fid, cap)
|
||||
let opcode = if mn == "CALL_CLOSURE" {
|
||||
CoreOpCode::CallClosure
|
||||
} else {
|
||||
return Err(AsmError::InvalidOperand(ops.into()));
|
||||
CoreOpCode::GetCapture
|
||||
};
|
||||
emit_u16(CoreOpCode::MakeClosure as u16, &mut out);
|
||||
emit_u32(fn_id, &mut out);
|
||||
emit_u32(captures, &mut out);
|
||||
}
|
||||
"SPAWN" => {
|
||||
if ops.is_empty() {
|
||||
return Err(AsmError::MissingOperand(line.into()));
|
||||
}
|
||||
let (a, b) = parse_keyvals(ops)?;
|
||||
let (fn_id, argc) = if a.starts_with("fn=") && b.starts_with("argc=") {
|
||||
parse_pair(a, "fn", b, "argc")?
|
||||
} else if a.starts_with("argc=") && b.starts_with("fn=") {
|
||||
let (ac, fid) = parse_pair(a, "argc", b, "fn")?;
|
||||
(fid, ac)
|
||||
} else {
|
||||
return Err(AsmError::InvalidOperand(ops.into()));
|
||||
};
|
||||
emit_u16(CoreOpCode::Spawn as u16, &mut out);
|
||||
emit_u32(fn_id, &mut out);
|
||||
emit_u32(argc, &mut out);
|
||||
}
|
||||
"SLEEP" => {
|
||||
if ops.is_empty() {
|
||||
return Err(AsmError::MissingOperand(line.into()));
|
||||
}
|
||||
emit_u16(CoreOpCode::Sleep as u16, &mut out);
|
||||
emit_u16(opcode as u16, &mut out);
|
||||
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||
}
|
||||
"MAKE_CLOSURE" | "CALL_TRAIT" => {
|
||||
let (a, b) = parse_keyvals(ops)?;
|
||||
let (key_a, key_b, opcode) = if mn == "MAKE_CLOSURE" {
|
||||
("fn", "type", CoreOpCode::MakeClosure)
|
||||
} else {
|
||||
("type", "method", CoreOpCode::CallTrait)
|
||||
};
|
||||
let (first, second) = if a.starts_with(&format!("{}=", key_a)) {
|
||||
parse_pair(a, key_a, b, key_b)?
|
||||
} else {
|
||||
let (second, first) = parse_pair(a, key_b, b, key_a)?;
|
||||
(first, second)
|
||||
};
|
||||
emit_u16(opcode as u16, &mut out);
|
||||
emit_u32(first, &mut out);
|
||||
emit_u32(second, &mut out);
|
||||
}
|
||||
"HOSTCALL" => {
|
||||
if ops.is_empty() {
|
||||
return Err(AsmError::MissingOperand(line.into()));
|
||||
@@ -360,6 +336,66 @@ pub fn assemble(src: &str) -> Result<Vec<u8>, AsmError> {
|
||||
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||
}
|
||||
|
||||
"STRUCT_GET" | "STRUCT_SET" => {
|
||||
let (a, b) = parse_keyvals(ops)?;
|
||||
let (ty, field) = parse_pair(a, "type", b, "field")?;
|
||||
let op =
|
||||
if mn == "STRUCT_GET" { CoreOpCode::StructGet } else { CoreOpCode::StructSet };
|
||||
emit_u16(op as u16, &mut out);
|
||||
emit_u32(ty, &mut out);
|
||||
emit_u32(field, &mut out);
|
||||
}
|
||||
"STRUCT_NEW" | "ARRAY_NEW" | "ARRAY_LEN" | "ARRAY_GET" | "ARRAY_SET" | "ARRAY_COPY" => {
|
||||
if ops.is_empty() {
|
||||
return Err(AsmError::MissingOperand(line.into()));
|
||||
}
|
||||
let op = match mn {
|
||||
"STRUCT_NEW" => CoreOpCode::StructNew,
|
||||
"ARRAY_NEW" => CoreOpCode::ArrayNew,
|
||||
"ARRAY_LEN" => CoreOpCode::ArrayLen,
|
||||
"ARRAY_GET" => CoreOpCode::ArrayGet,
|
||||
"ARRAY_COPY" => CoreOpCode::ArrayCopy,
|
||||
_ => CoreOpCode::ArraySet,
|
||||
};
|
||||
emit_u16(op as u16, &mut out);
|
||||
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||
}
|
||||
"DYN_PACK" | "DYN_UNPACK" | "DYN_CAN_UNPACK" | "REF_IDENTITY_HASH" => {
|
||||
if ops.is_empty() {
|
||||
return Err(AsmError::MissingOperand(line.into()));
|
||||
}
|
||||
let opcode = match mn {
|
||||
"DYN_PACK" => CoreOpCode::DynPack,
|
||||
"DYN_UNPACK" => CoreOpCode::DynUnpack,
|
||||
"REF_IDENTITY_HASH" => CoreOpCode::RefIdentityHash,
|
||||
_ => CoreOpCode::DynCanUnpack,
|
||||
};
|
||||
emit_u16(opcode as u16, &mut out);
|
||||
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||
}
|
||||
"REF_IDENTITY_EQ" => {
|
||||
let (a, b) = parse_keyvals(ops)?;
|
||||
let (left, right) = parse_pair(a, "left", b, "right")?;
|
||||
emit_u16(CoreOpCode::RefIdentityEq as u16, &mut out);
|
||||
emit_u32(left, &mut out);
|
||||
emit_u32(right, &mut out);
|
||||
}
|
||||
"REF_IS_EXACT" | "REF_IMPLEMENTS" | "REF_TO_TRAIT" | "REF_CAST" => {
|
||||
if ops.is_empty() {
|
||||
return Err(AsmError::MissingOperand(line.into()));
|
||||
}
|
||||
let (a, b) = parse_keyvals(ops)?;
|
||||
let (source, target) = parse_pair(a, "source", b, "target")?;
|
||||
let opcode = match mn {
|
||||
"REF_IS_EXACT" => CoreOpCode::RefIsExact,
|
||||
"REF_IMPLEMENTS" => CoreOpCode::RefImplements,
|
||||
"REF_TO_TRAIT" => CoreOpCode::RefToTrait,
|
||||
_ => CoreOpCode::RefCast,
|
||||
};
|
||||
emit_u16(opcode as u16, &mut out);
|
||||
emit_u32(source, &mut out);
|
||||
emit_u32(target, &mut out);
|
||||
}
|
||||
other => return Err(AsmError::UnknownMnemonic(other.into())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ impl<'a> DecodedInstr<'a> {
|
||||
/// Returns the decoded instruction with canonical `next_pc`.
|
||||
#[inline]
|
||||
pub fn decode_next(pc: usize, bytes: &'_ [u8]) -> Result<DecodedInstr<'_>, DecodeError> {
|
||||
if pc + 2 > bytes.len() {
|
||||
if pc.checked_add(2).is_none_or(|end| end > bytes.len()) {
|
||||
return Err(DecodeError::TruncatedOpcode { pc });
|
||||
}
|
||||
|
||||
@@ -100,7 +100,13 @@ pub fn decode_next(pc: usize, bytes: &'_ [u8]) -> Result<DecodedInstr<'_>, Decod
|
||||
|
||||
let spec: CoreOpcodeSpec = opcode.spec();
|
||||
let imm_start = pc + 2;
|
||||
let imm_end = imm_start + (spec.imm_bytes as usize);
|
||||
let imm_end =
|
||||
imm_start.checked_add(spec.imm_bytes as usize).ok_or(DecodeError::TruncatedImmediate {
|
||||
pc,
|
||||
opcode,
|
||||
need: spec.imm_bytes as usize,
|
||||
have: bytes.len().saturating_sub(imm_start),
|
||||
})?;
|
||||
|
||||
if imm_end > bytes.len() {
|
||||
return Err(DecodeError::TruncatedImmediate {
|
||||
|
||||
@@ -10,9 +10,9 @@
|
||||
//! - `MNEMONIC <imm>` for 1-operand instructions (decimal unless stated).
|
||||
//! - Special operand formats:
|
||||
//! - `PUSH_F64 f64:0xhhhhhhhhhhhhhhhh` — exact IEEE-754 bits in hex (little-endian to_bits()).
|
||||
//! - `MAKE_CLOSURE fn=<u32>, captures=<u32>`
|
||||
//! - `SPAWN fn=<u32>, argc=<u32>`
|
||||
//! - `CALL_CLOSURE argc=<u32>`
|
||||
//! - `MAKE_CLOSURE fn=<u32>, type=<u32>`
|
||||
//! - Retired SPAWN/YIELD/SLEEP are identified for diagnostics only.
|
||||
//! - `CALL_CLOSURE <FnTypeId>`
|
||||
//! - `HOSTCALL <index>` is printed in decimal because it is a `SYSC` table index.
|
||||
//! - `SYSCALL` is printed as `SYSCALL 0xhhhh` (numeric id in hex) to avoid cross-crate deps.
|
||||
//!
|
||||
@@ -60,18 +60,51 @@ fn format_operand(op: CoreOpCode, imm: &[u8]) -> String {
|
||||
| CoreOpCode::SetLocal
|
||||
| CoreOpCode::Call
|
||||
| CoreOpCode::Sleep
|
||||
| CoreOpCode::Hostcall => {
|
||||
| CoreOpCode::GetCapture
|
||||
| CoreOpCode::CallClosure
|
||||
| CoreOpCode::Hostcall
|
||||
| CoreOpCode::DynPack
|
||||
| CoreOpCode::DynUnpack
|
||||
| CoreOpCode::RefIdentityHash
|
||||
| CoreOpCode::DynCanUnpack
|
||||
| CoreOpCode::StructNew
|
||||
| CoreOpCode::ArrayNew
|
||||
| CoreOpCode::ArrayLen
|
||||
| CoreOpCode::ArrayGet
|
||||
| CoreOpCode::ArraySet
|
||||
| CoreOpCode::ArrayCopy => {
|
||||
let v = u32::from_le_bytes(imm.try_into().unwrap());
|
||||
format!("{}", v)
|
||||
}
|
||||
CoreOpCode::StructGet | CoreOpCode::StructSet => {
|
||||
let ty = u32::from_le_bytes(imm[..4].try_into().unwrap());
|
||||
let field = u32::from_le_bytes(imm[4..].try_into().unwrap());
|
||||
format!("type={}, field={}", ty, field)
|
||||
}
|
||||
CoreOpCode::RefIdentityEq => {
|
||||
let left = u32::from_le_bytes(imm[..4].try_into().unwrap());
|
||||
let right = u32::from_le_bytes(imm[4..].try_into().unwrap());
|
||||
format!("left={}, right={}", left, right)
|
||||
}
|
||||
CoreOpCode::RefIsExact
|
||||
| CoreOpCode::RefImplements
|
||||
| CoreOpCode::RefToTrait
|
||||
| CoreOpCode::RefCast => {
|
||||
let source = u32::from_le_bytes(imm[..4].try_into().unwrap());
|
||||
let target = u32::from_le_bytes(imm[4..].try_into().unwrap());
|
||||
format!("source={}, target={}", source, target)
|
||||
}
|
||||
CoreOpCode::MakeClosure => {
|
||||
let fn_id = u32::from_le_bytes(imm[0..4].try_into().unwrap());
|
||||
let cap = u32::from_le_bytes(imm[4..8].try_into().unwrap());
|
||||
format!("fn={}, captures={}", fn_id, cap)
|
||||
format!("fn={}, type={}", fn_id, cap)
|
||||
}
|
||||
CoreOpCode::CallClosure => {
|
||||
let argc = u32::from_le_bytes(imm.try_into().unwrap());
|
||||
format!("argc={}", argc)
|
||||
CoreOpCode::CallTrait => {
|
||||
let (ty, method) = (
|
||||
u32::from_le_bytes(imm[..4].try_into().unwrap()),
|
||||
u32::from_le_bytes(imm[4..].try_into().unwrap()),
|
||||
);
|
||||
format!("type={}, method={}", ty, method)
|
||||
}
|
||||
CoreOpCode::Spawn => {
|
||||
let fn_id = u32::from_le_bytes(imm[0..4].try_into().unwrap());
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Core ISA profile (bytecode-level, stable, canonical).
|
||||
//!
|
||||
//! This profile is the canonical opcode surface used by decoder/disasm and
|
||||
//! mirrors the runtime-visible instruction set implemented today, including
|
||||
//! closures, coroutines, intrinsics, and hostcall patching semantics.
|
||||
//! exposes the canonical encoding for closures, coroutines, intrinsics,
|
||||
//! hostcall patching and Registry instructions. Recognition by tooling alone
|
||||
//! does not authorize execution without validated program metadata.
|
||||
|
||||
// For PR-1.4 we define the core profile as the current `OpCode` set. We re-export
|
||||
// the opcode type and spec so downstream tools can import from a stable path:
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
//! Shared bytecode layout utilities, used by both compiler (emitter/linker)
|
||||
//! and the VM (verifier/loader). This ensures a single source of truth for
|
||||
//! how function ranges, instruction boundaries, and pc→function lookups are
|
||||
//! interpreted post-link.
|
||||
|
||||
use crate::model::FunctionMeta;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FunctionLayout {
|
||||
pub start: usize,
|
||||
pub end: usize, // exclusive
|
||||
}
|
||||
|
||||
/// Precompute canonical [start, end) ranges for all functions.
|
||||
///
|
||||
/// Contract:
|
||||
/// - Ranges are computed by sorting functions by `code_offset` (stable),
|
||||
/// then using the next function's start as the current end; the last
|
||||
/// function ends at `code_len_total`.
|
||||
/// - The returned vector is indexed by the original function indices.
|
||||
pub fn compute_function_layouts(
|
||||
functions: &[FunctionMeta],
|
||||
code_len_total: usize,
|
||||
) -> Vec<FunctionLayout> {
|
||||
// Build index array and sort by start offset (stable to preserve relative order).
|
||||
let mut idxs: Vec<usize> = (0..functions.len()).collect();
|
||||
idxs.sort_by_key(|&i| functions[i].code_offset as usize);
|
||||
|
||||
// Optional guard: offsets should be strictly increasing (duplicates are suspicious).
|
||||
for w in idxs.windows(2) {
|
||||
if let [a, b] = *w {
|
||||
let sa = functions[a].code_offset as usize;
|
||||
let sb = functions[b].code_offset as usize;
|
||||
debug_assert!(
|
||||
sa < sb,
|
||||
"Function code_offset must be strictly increasing: {} vs {} (indices {} and {})",
|
||||
sa,
|
||||
sb,
|
||||
a,
|
||||
b
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let mut out = vec![FunctionLayout { start: 0, end: 0 }; functions.len()];
|
||||
for (pos, &i) in idxs.iter().enumerate() {
|
||||
let start = functions[i].code_offset as usize;
|
||||
let end = if pos + 1 < idxs.len() {
|
||||
functions[idxs[pos + 1]].code_offset as usize
|
||||
} else {
|
||||
code_len_total
|
||||
};
|
||||
out[i] = FunctionLayout { start, end };
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn build_funcs(offsets: &[usize], lens: Option<&[usize]>) -> Vec<FunctionMeta> {
|
||||
let mut v = Vec::new();
|
||||
for (i, off) in offsets.iter().copied().enumerate() {
|
||||
let len_u32 = lens.and_then(|ls| ls.get(i).copied()).unwrap_or(0) as u32;
|
||||
v.push(FunctionMeta {
|
||||
code_offset: off as u32,
|
||||
code_len: len_u32,
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
max_stack_slots: 0,
|
||||
});
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_function_layouts_end_is_next_start() {
|
||||
// Synthetic functions with known offsets: 0, 10, 25; total_len = 40
|
||||
let funcs = build_funcs(&[0, 10, 25], None);
|
||||
let layouts = compute_function_layouts(&funcs, 40);
|
||||
|
||||
assert_eq!(layouts.len(), 3);
|
||||
assert_eq!(layouts[0], FunctionLayout { start: 0, end: 10 });
|
||||
assert_eq!(layouts[1], FunctionLayout { start: 10, end: 25 });
|
||||
assert_eq!(layouts[2], FunctionLayout { start: 25, end: 40 });
|
||||
|
||||
for i in 0..3 {
|
||||
let l = &layouts[i];
|
||||
assert_eq!(
|
||||
l.end - l.start,
|
||||
(funcs.get(i + 1).map(|n| n.code_offset as usize).unwrap_or(40))
|
||||
- (funcs[i].code_offset as usize)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,22 +3,32 @@ pub mod assembler;
|
||||
mod decoder;
|
||||
mod disassembler;
|
||||
pub mod isa; // canonical ISA boundary (core and future profiles)
|
||||
mod layout;
|
||||
pub mod model;
|
||||
mod opcode;
|
||||
mod opcode_spec;
|
||||
mod program_image;
|
||||
mod resource_failure;
|
||||
mod value;
|
||||
|
||||
pub use abi::{
|
||||
TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT, TRAP_ILLEGAL_INSTRUCTION,
|
||||
TRAP_INVALID_FUNC, TRAP_INVALID_INTRINSIC, TRAP_INVALID_LOCAL, TRAP_INVALID_SYSCALL, TRAP_OOB,
|
||||
TRAP_STACK_UNDERFLOW, TRAP_TYPE,
|
||||
SourceSpan, TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT,
|
||||
TRAP_ILLEGAL_INSTRUCTION, TRAP_INVALID_FUNC, TRAP_INVALID_HANDLE, TRAP_INVALID_INTRINSIC,
|
||||
TRAP_INVALID_LOCAL, TRAP_INVALID_SYSCALL, TRAP_NON_FINITE, TRAP_NULL_REFERENCE,
|
||||
TRAP_NUMERIC_DOMAIN, TRAP_NUMERIC_RANGE, TRAP_OOB, TRAP_RANDOM_REJECTION_LIMIT,
|
||||
TRAP_RESOURCE_LIMIT, TRAP_STACK_UNDERFLOW, TRAP_TYPE, TRAP_UNAVAILABLE,
|
||||
};
|
||||
pub use assembler::{assemble, AsmError};
|
||||
pub use decoder::{decode_next, DecodeError};
|
||||
pub use decoder::{decode_next, DecodeError, DecodedInstr};
|
||||
pub use disassembler::disassemble;
|
||||
pub use layout::{compute_function_layouts, FunctionLayout};
|
||||
pub use model::{BytecodeLoader, FunctionMeta, LoadError, SyscallDecl};
|
||||
pub use model::{LoadError, SyscallDecl, PBX_MAGIC};
|
||||
pub use program_image::ExecutionFunction;
|
||||
pub use program_image::ProgramImage;
|
||||
pub use value::{HeapRef, Value};
|
||||
pub use resource_failure::{ResourceFailure, ResourceReason, RuntimeResource};
|
||||
pub use value::{string_materialization_count, HeapRef, Value};
|
||||
|
||||
pub mod load_limits;
|
||||
pub mod registry;
|
||||
pub mod registry_codec;
|
||||
|
||||
mod registry_instruction;
|
||||
pub use registry_instruction::RegistryStackEffect;
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
//! Shared PBX v0 resource limits and structured validation failures.
|
||||
//! Counters are deterministic; a failed reservation never changes usage.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
|
||||
const MIB: u64 = 1_048_576;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum LoadCode {
|
||||
#[serde(rename = "LOAD_INVALID_FORMAT")]
|
||||
InvalidFormat,
|
||||
#[serde(rename = "LOAD_UNSUPPORTED_FORMAT")]
|
||||
UnsupportedFormat,
|
||||
#[serde(rename = "LOAD_INVALID_REFERENCE")]
|
||||
InvalidReference,
|
||||
#[serde(rename = "LOAD_INVALID_REGISTRY")]
|
||||
InvalidRegistry,
|
||||
#[serde(rename = "LOAD_INVALID_CODE")]
|
||||
InvalidCode,
|
||||
#[serde(rename = "LOAD_RESOURCE_LIMIT")]
|
||||
ResourceLimit,
|
||||
#[serde(rename = "LOAD_INVALID_ENTRYPOINT")]
|
||||
InvalidEntrypoint,
|
||||
}
|
||||
impl LoadCode {
|
||||
pub const fn tag(self) -> &'static str {
|
||||
match self {
|
||||
Self::InvalidFormat => "LOAD_INVALID_FORMAT",
|
||||
Self::UnsupportedFormat => "LOAD_UNSUPPORTED_FORMAT",
|
||||
Self::InvalidReference => "LOAD_INVALID_REFERENCE",
|
||||
Self::InvalidRegistry => "LOAD_INVALID_REGISTRY",
|
||||
Self::InvalidCode => "LOAD_INVALID_CODE",
|
||||
Self::ResourceLimit => "LOAD_RESOURCE_LIMIT",
|
||||
Self::InvalidEntrypoint => "LOAD_INVALID_ENTRYPOINT",
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum LoadReason {
|
||||
LifecycleRole,
|
||||
LifecycleSignature,
|
||||
DuplicateLifecycleRole,
|
||||
Magic,
|
||||
Version,
|
||||
Endianness,
|
||||
Reserved,
|
||||
SectionKind,
|
||||
MissingSection,
|
||||
DuplicateSection,
|
||||
Overlap,
|
||||
Truncated,
|
||||
TrailingBytes,
|
||||
InvalidFlag,
|
||||
Utf8,
|
||||
Category,
|
||||
Builtin,
|
||||
TypeId,
|
||||
FunctionId,
|
||||
OwnerCategory,
|
||||
TraitCategory,
|
||||
DuplicateBuiltin,
|
||||
DuplicateArray,
|
||||
DuplicateFn,
|
||||
StructuralTypeCycle,
|
||||
CaptureIndex,
|
||||
CaptureCount,
|
||||
CapturedDirectCall,
|
||||
RemovedOpcode,
|
||||
ArrayCycle,
|
||||
DuplicateImplementation,
|
||||
MethodCount,
|
||||
Signature,
|
||||
CodeRange,
|
||||
FrameSlots,
|
||||
ReturnSlots,
|
||||
Overflow,
|
||||
Limit,
|
||||
Allocation,
|
||||
ConstantTag,
|
||||
NonFiniteValue,
|
||||
DebugRange,
|
||||
DuplicateSyscall,
|
||||
UnknownOpcode,
|
||||
LocalSlot,
|
||||
JumpTarget,
|
||||
InstructionBoundary,
|
||||
BooleanImmediate,
|
||||
ConstantIndex,
|
||||
NativeId,
|
||||
UnpatchedHostcall,
|
||||
StackUnderflow,
|
||||
StackOverflow,
|
||||
StackJoin,
|
||||
ReturnHeight,
|
||||
UnterminatedPath,
|
||||
UnknownClosureCallee,
|
||||
NotClosure,
|
||||
InvalidYield,
|
||||
TypeMismatch,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[repr(usize)]
|
||||
pub enum LoadResource {
|
||||
PbxBytes,
|
||||
CodeBytes,
|
||||
Types,
|
||||
Functions,
|
||||
Implementations,
|
||||
NestedRecords,
|
||||
NameBytes,
|
||||
RegistryBytes,
|
||||
TemporaryBytes,
|
||||
Work,
|
||||
ConstantEntries,
|
||||
ConstantStringBytes,
|
||||
}
|
||||
const RESOURCE_COUNT: usize = 12;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum IdDomain {
|
||||
Type,
|
||||
Function,
|
||||
Implementation,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LoadFailure {
|
||||
pub code: LoadCode,
|
||||
pub reason: LoadReason,
|
||||
pub section: Option<u32>,
|
||||
pub offset: Option<usize>,
|
||||
pub record: Option<u32>,
|
||||
pub member: Option<u32>,
|
||||
pub id_domain: Option<IdDomain>,
|
||||
pub referenced_id: Option<u32>,
|
||||
pub function: Option<u32>,
|
||||
pub pc: Option<u32>,
|
||||
pub resource: Option<LoadResource>,
|
||||
pub requested: Option<u64>,
|
||||
pub limit: Option<u64>,
|
||||
}
|
||||
impl LoadFailure {
|
||||
pub fn new(code: LoadCode, reason: LoadReason) -> Self {
|
||||
Self {
|
||||
code,
|
||||
reason,
|
||||
section: None,
|
||||
offset: None,
|
||||
record: None,
|
||||
member: None,
|
||||
id_domain: None,
|
||||
referenced_id: None,
|
||||
function: None,
|
||||
pc: None,
|
||||
resource: None,
|
||||
requested: None,
|
||||
limit: None,
|
||||
}
|
||||
}
|
||||
pub fn at(mut self, section: u32, offset: usize) -> Self {
|
||||
self.section = Some(section);
|
||||
self.offset = Some(offset);
|
||||
self
|
||||
}
|
||||
pub fn record(mut self, record: u32) -> Self {
|
||||
self.record = Some(record);
|
||||
self
|
||||
}
|
||||
pub fn member(mut self, member: u32) -> Self {
|
||||
self.member = Some(member);
|
||||
self
|
||||
}
|
||||
pub fn in_section(mut self, section: u32) -> Self {
|
||||
self.section = Some(section);
|
||||
self
|
||||
}
|
||||
pub fn reference(mut self, domain: IdDomain, id: u32) -> Self {
|
||||
self.id_domain = Some(domain);
|
||||
self.referenced_id = Some(id);
|
||||
self
|
||||
}
|
||||
pub fn in_function(mut self, function: u32, pc: Option<u32>) -> Self {
|
||||
self.function = Some(function);
|
||||
self.pc = pc;
|
||||
self
|
||||
}
|
||||
pub fn resource(resource: LoadResource, requested: u64, limit: u64) -> Self {
|
||||
Self {
|
||||
resource: Some(resource),
|
||||
requested: Some(requested),
|
||||
limit: Some(limit),
|
||||
..Self::new(LoadCode::ResourceLimit, LoadReason::Limit)
|
||||
}
|
||||
}
|
||||
}
|
||||
impl fmt::Display for LoadFailure {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}: {:?}", self.code.tag(), self.reason)?;
|
||||
if let Some(section) = self.section {
|
||||
write!(f, " in section {section}")?;
|
||||
}
|
||||
if let Some(offset) = self.offset {
|
||||
write!(f, " at byte {offset}")?;
|
||||
}
|
||||
if let Some(record) = self.record {
|
||||
write!(f, " (record {record})")?;
|
||||
}
|
||||
if let Some(resource) = self.resource {
|
||||
write!(f, " ({resource:?}: {:?} / {:?})", self.requested, self.limit)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl std::error::Error for LoadFailure {}
|
||||
|
||||
/// Product maxima; callers may lower limits but cannot raise the accepted ceilings.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct LoadLimits {
|
||||
pub pbx_bytes: u64,
|
||||
pub code_bytes: u64,
|
||||
pub types: u64,
|
||||
pub functions: u64,
|
||||
pub implementations: u64,
|
||||
pub nested_records: u64,
|
||||
pub name_bytes: u64,
|
||||
pub individual_name_bytes: u64,
|
||||
pub registry_bytes: u64,
|
||||
pub temporary_bytes: u64,
|
||||
pub work: u64,
|
||||
pub frame_slots: u64,
|
||||
pub result_slots: u64,
|
||||
pub constant_entries: u64,
|
||||
pub constant_string_bytes: u64,
|
||||
pub individual_string_bytes: u64,
|
||||
}
|
||||
impl Default for LoadLimits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pbx_bytes: 64 * MIB,
|
||||
code_bytes: 32 * MIB,
|
||||
types: 65_536,
|
||||
functions: 65_536,
|
||||
implementations: 262_144,
|
||||
nested_records: 1_048_576,
|
||||
name_bytes: 4 * MIB,
|
||||
individual_name_bytes: 4096,
|
||||
registry_bytes: 64 * MIB,
|
||||
temporary_bytes: 128 * MIB,
|
||||
work: 268_435_456,
|
||||
frame_slots: 16_384,
|
||||
result_slots: 1024,
|
||||
constant_entries: 1_048_576,
|
||||
constant_string_bytes: 64 * MIB,
|
||||
individual_string_bytes: 4 * MIB,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl LoadLimits {
|
||||
fn ceiling(self, r: LoadResource) -> u64 {
|
||||
match r {
|
||||
LoadResource::PbxBytes => self.pbx_bytes,
|
||||
LoadResource::CodeBytes => self.code_bytes,
|
||||
LoadResource::Types => self.types,
|
||||
LoadResource::Functions => self.functions,
|
||||
LoadResource::Implementations => self.implementations,
|
||||
LoadResource::NestedRecords => self.nested_records,
|
||||
LoadResource::NameBytes => self.name_bytes,
|
||||
LoadResource::RegistryBytes => self.registry_bytes,
|
||||
LoadResource::TemporaryBytes => self.temporary_bytes,
|
||||
LoadResource::Work => self.work,
|
||||
LoadResource::ConstantEntries => self.constant_entries,
|
||||
LoadResource::ConstantStringBytes => self.constant_string_bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// One load attempt's counters. Successful retained allocations stay charged
|
||||
/// for the remainder of this attempt; executable-image lifetime accounting is
|
||||
/// a separate owner. Reuse a budget only when its earlier allocations still live.
|
||||
#[derive(Debug)]
|
||||
pub struct LoadBudget {
|
||||
limits: LoadLimits,
|
||||
used: [u64; RESOURCE_COUNT],
|
||||
peak: [u64; RESOURCE_COUNT],
|
||||
}
|
||||
impl LoadBudget {
|
||||
pub fn new(limits: LoadLimits) -> Self {
|
||||
Self { limits, used: [0; RESOURCE_COUNT], peak: [0; RESOURCE_COUNT] }
|
||||
}
|
||||
pub fn limit(&self, r: LoadResource) -> u64 {
|
||||
self.limits.ceiling(r).min(LoadLimits::default().ceiling(r))
|
||||
}
|
||||
pub fn individual_string_limit(&self) -> u64 {
|
||||
self.limits.individual_string_bytes.min(4 * MIB)
|
||||
}
|
||||
pub fn individual_name_limit(&self) -> u64 {
|
||||
self.limits.individual_name_bytes.min(4096)
|
||||
}
|
||||
pub fn frame_limit(&self) -> u64 {
|
||||
self.limits.frame_slots.min(16_384)
|
||||
}
|
||||
pub fn result_limit(&self) -> u64 {
|
||||
self.limits.result_slots.min(1024)
|
||||
}
|
||||
pub fn used(&self, r: LoadResource) -> u64 {
|
||||
self.used[r as usize]
|
||||
}
|
||||
/// Highest admitted reservation total during this budget's lifetime.
|
||||
/// Refunds and failed load transactions retain this measurement; refused
|
||||
/// charges do not increase it. This is accounted capacity, not process RSS.
|
||||
pub fn peak_usage(&self, r: LoadResource) -> u64 {
|
||||
self.peak[r as usize]
|
||||
}
|
||||
pub fn charge(&mut self, r: LoadResource, amount: u64) -> Result<(), LoadFailure> {
|
||||
let next = self
|
||||
.used(r)
|
||||
.checked_add(amount)
|
||||
.ok_or_else(|| LoadFailure::new(LoadCode::ResourceLimit, LoadReason::Overflow))?;
|
||||
self.check(r, next)?;
|
||||
self.used[r as usize] = next;
|
||||
self.peak[r as usize] = self.peak[r as usize].max(next);
|
||||
Ok(())
|
||||
}
|
||||
pub fn check(&self, r: LoadResource, amount: u64) -> Result<(), LoadFailure> {
|
||||
if amount > self.limit(r) {
|
||||
Err(LoadFailure::resource(r, amount, self.limit(r)))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
pub fn refund(&mut self, r: LoadResource, amount: u64) {
|
||||
self.used[r as usize] = self.used[r as usize]
|
||||
.checked_sub(amount)
|
||||
.expect("internal load budget accounting imbalance");
|
||||
}
|
||||
pub fn work(&mut self, amount: usize) -> Result<(), LoadFailure> {
|
||||
self.charge(LoadResource::Work, amount as u64)
|
||||
}
|
||||
pub(crate) fn vector<T>(
|
||||
&mut self,
|
||||
count: usize,
|
||||
r: LoadResource,
|
||||
) -> Result<Vec<T>, LoadFailure> {
|
||||
let bytes = count
|
||||
.checked_mul(std::mem::size_of::<T>())
|
||||
.ok_or_else(|| LoadFailure::new(LoadCode::ResourceLimit, LoadReason::Overflow))?
|
||||
as u64;
|
||||
self.charge(r, bytes)?;
|
||||
let mut result = Vec::new();
|
||||
if result.try_reserve_exact(count).is_err() {
|
||||
self.refund(r, bytes);
|
||||
return Err(LoadFailure::new(LoadCode::ResourceLimit, LoadReason::Allocation));
|
||||
}
|
||||
let actual = (result.capacity() as u64)
|
||||
.checked_mul(std::mem::size_of::<T>() as u64)
|
||||
.ok_or_else(|| LoadFailure::new(LoadCode::ResourceLimit, LoadReason::Overflow))?;
|
||||
if let Err(err) = self.charge(r, actual - bytes) {
|
||||
self.refund(r, bytes);
|
||||
return Err(err);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
/// Roll back retained counters on failure; attempted work remains charged.
|
||||
pub(crate) fn transaction<T>(
|
||||
&mut self,
|
||||
f: impl FnOnce(&mut Self) -> Result<T, LoadFailure>,
|
||||
) -> Result<T, LoadFailure> {
|
||||
let before = self.used;
|
||||
let result = f(self);
|
||||
if result.is_err() {
|
||||
let work = self.used(LoadResource::Work);
|
||||
self.used = before;
|
||||
self.used[LoadResource::Work as usize] = work;
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn peak_tracks_admitted_capacity_through_refunds_and_failed_transactions() {
|
||||
let mut budget = LoadBudget::new(LoadLimits { temporary_bytes: 10, ..Default::default() });
|
||||
budget.charge(LoadResource::TemporaryBytes, 3).unwrap();
|
||||
let result: Result<(), LoadFailure> = budget.transaction(|budget| {
|
||||
budget.charge(LoadResource::TemporaryBytes, 7)?;
|
||||
budget.work(2)?;
|
||||
budget.charge(LoadResource::TemporaryBytes, 1)
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(budget.used(LoadResource::TemporaryBytes), 3);
|
||||
assert_eq!(budget.peak_usage(LoadResource::TemporaryBytes), 10);
|
||||
assert_eq!(budget.used(LoadResource::Work), 2);
|
||||
assert_eq!(budget.peak_usage(LoadResource::Work), 2);
|
||||
budget.refund(LoadResource::TemporaryBytes, 3);
|
||||
assert_eq!(budget.used(LoadResource::TemporaryBytes), 0);
|
||||
assert_eq!(budget.peak_usage(LoadResource::TemporaryBytes), 10);
|
||||
assert!(budget.charge(LoadResource::TemporaryBytes, u64::MAX).is_err());
|
||||
assert_eq!(budget.peak_usage(LoadResource::TemporaryBytes), 10);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
use crate::abi::SourceSpan;
|
||||
use crate::opcode::OpCode;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// An entry in the Constant Pool.
|
||||
///
|
||||
@@ -42,16 +40,6 @@ pub enum LoadError {
|
||||
UnexpectedEof,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FunctionMeta {
|
||||
pub code_offset: u32,
|
||||
pub code_len: u32,
|
||||
pub param_slots: u16,
|
||||
pub local_slots: u16,
|
||||
pub return_slots: u16,
|
||||
pub max_stack_slots: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct DebugInfo {
|
||||
pub pc_to_span: Vec<(u32, SourceSpan)>, // Sorted by PC
|
||||
@@ -73,874 +61,4 @@ pub struct SyscallDecl {
|
||||
pub ret_slots: u16,
|
||||
}
|
||||
|
||||
const SECTION_KIND_CONST_POOL: u32 = 0;
|
||||
const SECTION_KIND_FUNCTIONS: u32 = 1;
|
||||
const SECTION_KIND_CODE: u32 = 2;
|
||||
const SECTION_KIND_DEBUG: u32 = 3;
|
||||
const SECTION_KIND_EXPORTS: u32 = 4;
|
||||
const SECTION_KIND_SYSCALLS: u32 = 5;
|
||||
|
||||
/// Represents the final serialized format of a PBS v0 module.
|
||||
///
|
||||
/// This structure is a pure data container for the PBS format. It does NOT
|
||||
/// contain any linker-like logic (symbol resolution, patching, etc.).
|
||||
/// All multi-module programs must be flattened and linked by the compiler
|
||||
/// before being serialized into this format.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct BytecodeModule {
|
||||
pub version: u16,
|
||||
pub const_pool: Vec<ConstantPoolEntry>,
|
||||
pub functions: Vec<FunctionMeta>,
|
||||
pub code: Vec<u8>,
|
||||
pub debug_info: Option<DebugInfo>,
|
||||
pub exports: Vec<Export>,
|
||||
pub syscalls: Vec<SyscallDecl>,
|
||||
}
|
||||
|
||||
impl BytecodeModule {
|
||||
pub fn serialize(&self) -> Vec<u8> {
|
||||
let cp_data = self.serialize_const_pool();
|
||||
let func_data = self.serialize_functions();
|
||||
let code_data = self.code.clone();
|
||||
let debug_data =
|
||||
self.debug_info.as_ref().map(|di| self.serialize_debug(di)).unwrap_or_default();
|
||||
let export_data = self.serialize_exports();
|
||||
let syscall_data = self.serialize_syscalls();
|
||||
|
||||
let mut final_sections = Vec::new();
|
||||
if !cp_data.is_empty() {
|
||||
final_sections.push((SECTION_KIND_CONST_POOL, cp_data));
|
||||
}
|
||||
if !func_data.is_empty() {
|
||||
final_sections.push((SECTION_KIND_FUNCTIONS, func_data));
|
||||
}
|
||||
if !code_data.is_empty() {
|
||||
final_sections.push((SECTION_KIND_CODE, code_data));
|
||||
}
|
||||
if !debug_data.is_empty() {
|
||||
final_sections.push((SECTION_KIND_DEBUG, debug_data));
|
||||
}
|
||||
if !export_data.is_empty() {
|
||||
final_sections.push((SECTION_KIND_EXPORTS, export_data));
|
||||
}
|
||||
final_sections.push((SECTION_KIND_SYSCALLS, syscall_data));
|
||||
|
||||
let mut out = Vec::new();
|
||||
// Magic "PBS\0"
|
||||
out.extend_from_slice(b"PBS\0");
|
||||
// Version 0
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
// Endianness 0 (Little Endian), Reserved
|
||||
out.extend_from_slice(&[0u8, 0u8]);
|
||||
// section_count
|
||||
out.extend_from_slice(&(final_sections.len() as u32).to_le_bytes());
|
||||
// padding to 32 bytes
|
||||
out.extend_from_slice(&[0u8; 20]);
|
||||
|
||||
let mut current_offset = 32 + (final_sections.len() as u32 * 12);
|
||||
|
||||
// Write section table
|
||||
for (kind, data) in &final_sections {
|
||||
let k: u32 = *kind;
|
||||
out.extend_from_slice(&k.to_le_bytes());
|
||||
out.extend_from_slice(¤t_offset.to_le_bytes());
|
||||
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
current_offset += data.len() as u32;
|
||||
}
|
||||
|
||||
// Write section data
|
||||
for (_, data) in final_sections {
|
||||
out.extend_from_slice(&data);
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
fn serialize_const_pool(&self) -> Vec<u8> {
|
||||
if self.const_pool.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut data = Vec::new();
|
||||
data.extend_from_slice(&(self.const_pool.len() as u32).to_le_bytes());
|
||||
for entry in &self.const_pool {
|
||||
match entry {
|
||||
ConstantPoolEntry::Null => data.push(0),
|
||||
ConstantPoolEntry::Int64(v) => {
|
||||
data.push(1);
|
||||
data.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
ConstantPoolEntry::Float64(v) => {
|
||||
data.push(2);
|
||||
data.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
ConstantPoolEntry::Boolean(v) => {
|
||||
data.push(3);
|
||||
data.push(if *v { 1 } else { 0 });
|
||||
}
|
||||
ConstantPoolEntry::String(v) => {
|
||||
data.push(4);
|
||||
let s_bytes = v.as_bytes();
|
||||
data.extend_from_slice(&(s_bytes.len() as u32).to_le_bytes());
|
||||
data.extend_from_slice(s_bytes);
|
||||
}
|
||||
ConstantPoolEntry::Int32(v) => {
|
||||
data.push(5);
|
||||
data.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn serialize_functions(&self) -> Vec<u8> {
|
||||
if self.functions.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut data = Vec::new();
|
||||
data.extend_from_slice(&(self.functions.len() as u32).to_le_bytes());
|
||||
for f in &self.functions {
|
||||
data.extend_from_slice(&f.code_offset.to_le_bytes());
|
||||
data.extend_from_slice(&f.code_len.to_le_bytes());
|
||||
data.extend_from_slice(&f.param_slots.to_le_bytes());
|
||||
data.extend_from_slice(&f.local_slots.to_le_bytes());
|
||||
data.extend_from_slice(&f.return_slots.to_le_bytes());
|
||||
data.extend_from_slice(&f.max_stack_slots.to_le_bytes());
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn serialize_debug(&self, di: &DebugInfo) -> Vec<u8> {
|
||||
let mut data = Vec::new();
|
||||
data.extend_from_slice(&(di.pc_to_span.len() as u32).to_le_bytes());
|
||||
for (pc, span) in &di.pc_to_span {
|
||||
data.extend_from_slice(&pc.to_le_bytes());
|
||||
data.extend_from_slice(&span.file_id.to_le_bytes());
|
||||
data.extend_from_slice(&span.start.to_le_bytes());
|
||||
data.extend_from_slice(&span.end.to_le_bytes());
|
||||
}
|
||||
data.extend_from_slice(&(di.function_names.len() as u32).to_le_bytes());
|
||||
for (idx, name) in &di.function_names {
|
||||
data.extend_from_slice(&idx.to_le_bytes());
|
||||
let n_bytes = name.as_bytes();
|
||||
data.extend_from_slice(&(n_bytes.len() as u32).to_le_bytes());
|
||||
data.extend_from_slice(n_bytes);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn serialize_exports(&self) -> Vec<u8> {
|
||||
if self.exports.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut data = Vec::new();
|
||||
data.extend_from_slice(&(self.exports.len() as u32).to_le_bytes());
|
||||
for exp in &self.exports {
|
||||
data.extend_from_slice(&exp.func_idx.to_le_bytes());
|
||||
let s_bytes = exp.symbol.as_bytes();
|
||||
data.extend_from_slice(&(s_bytes.len() as u32).to_le_bytes());
|
||||
data.extend_from_slice(s_bytes);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn serialize_syscalls(&self) -> Vec<u8> {
|
||||
let mut data = Vec::new();
|
||||
data.extend_from_slice(&(self.syscalls.len() as u32).to_le_bytes());
|
||||
for syscall in &self.syscalls {
|
||||
let module = syscall.module.as_bytes();
|
||||
let name = syscall.name.as_bytes();
|
||||
assert!(u16::try_from(module.len()).is_ok(), "SYSC module name exceeds u16 length");
|
||||
assert!(u16::try_from(name.len()).is_ok(), "SYSC syscall name exceeds u16 length");
|
||||
|
||||
data.extend_from_slice(&(module.len() as u16).to_le_bytes());
|
||||
data.extend_from_slice(module);
|
||||
data.extend_from_slice(&(name.len() as u16).to_le_bytes());
|
||||
data.extend_from_slice(name);
|
||||
data.extend_from_slice(&syscall.version.to_le_bytes());
|
||||
data.extend_from_slice(&syscall.arg_slots.to_le_bytes());
|
||||
data.extend_from_slice(&syscall.ret_slots.to_le_bytes());
|
||||
}
|
||||
data
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BytecodeLoader;
|
||||
|
||||
impl BytecodeLoader {
|
||||
pub fn load(bytes: &[u8]) -> Result<BytecodeModule, LoadError> {
|
||||
if bytes.len() < 32 {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
|
||||
// Magic "PBS\0"
|
||||
if &bytes[0..4] != b"PBS\0" {
|
||||
return Err(LoadError::InvalidMagic);
|
||||
}
|
||||
|
||||
let version = u16::from_le_bytes([bytes[4], bytes[5]]);
|
||||
if version != 0 {
|
||||
return Err(LoadError::InvalidVersion);
|
||||
}
|
||||
|
||||
let endianness = bytes[6];
|
||||
if endianness != 0 {
|
||||
// 0 = Little Endian
|
||||
return Err(LoadError::InvalidEndianness);
|
||||
}
|
||||
|
||||
let section_count = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
|
||||
|
||||
let mut sections = Vec::new();
|
||||
let mut pos = 32;
|
||||
for _ in 0..section_count {
|
||||
if pos + 12 > bytes.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let kind =
|
||||
u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]);
|
||||
let offset = u32::from_le_bytes([
|
||||
bytes[pos + 4],
|
||||
bytes[pos + 5],
|
||||
bytes[pos + 6],
|
||||
bytes[pos + 7],
|
||||
]);
|
||||
let length = u32::from_le_bytes([
|
||||
bytes[pos + 8],
|
||||
bytes[pos + 9],
|
||||
bytes[pos + 10],
|
||||
bytes[pos + 11],
|
||||
]);
|
||||
|
||||
// Basic bounds check
|
||||
if (offset as usize) + (length as usize) > bytes.len() {
|
||||
return Err(LoadError::SectionOutOfBounds);
|
||||
}
|
||||
|
||||
sections.push((kind, offset, length));
|
||||
pos += 12;
|
||||
}
|
||||
|
||||
// Check for overlapping sections
|
||||
for i in 0..sections.len() {
|
||||
for j in i + 1..sections.len() {
|
||||
let (_, o1, l1) = sections[i];
|
||||
let (_, o2, l2) = sections[j];
|
||||
|
||||
if (o1 < o2 + l2) && (o2 < o1 + l1) {
|
||||
return Err(LoadError::OverlappingSections);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut module = BytecodeModule {
|
||||
version,
|
||||
const_pool: Vec::new(),
|
||||
functions: Vec::new(),
|
||||
code: Vec::new(),
|
||||
debug_info: None,
|
||||
exports: Vec::new(),
|
||||
syscalls: Vec::new(),
|
||||
};
|
||||
let mut has_syscalls = false;
|
||||
|
||||
for (kind, offset, length) in sections {
|
||||
let section_data = &bytes[offset as usize..(offset + length) as usize];
|
||||
match kind {
|
||||
SECTION_KIND_CONST_POOL => {
|
||||
// Const Pool
|
||||
module.const_pool = parse_const_pool(section_data)?;
|
||||
}
|
||||
SECTION_KIND_FUNCTIONS => {
|
||||
// Functions
|
||||
module.functions = parse_functions(section_data)?;
|
||||
}
|
||||
SECTION_KIND_CODE => {
|
||||
// Code
|
||||
module.code = section_data.to_vec();
|
||||
}
|
||||
SECTION_KIND_DEBUG => {
|
||||
// Debug Info
|
||||
module.debug_info = Some(parse_debug_section(section_data)?);
|
||||
}
|
||||
SECTION_KIND_EXPORTS => {
|
||||
// Exports
|
||||
module.exports = parse_exports(section_data)?;
|
||||
}
|
||||
SECTION_KIND_SYSCALLS => {
|
||||
module.syscalls = parse_syscalls(section_data)?;
|
||||
has_syscalls = true;
|
||||
}
|
||||
_ => {} // Skip unknown or optional sections
|
||||
}
|
||||
}
|
||||
|
||||
if !has_syscalls {
|
||||
return Err(LoadError::MissingSyscallSection);
|
||||
}
|
||||
|
||||
// Additional validations
|
||||
validate_module(&module)?;
|
||||
|
||||
Ok(module)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_const_pool(data: &[u8]) -> Result<Vec<ConstantPoolEntry>, LoadError> {
|
||||
if data.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if data.len() < 4 {
|
||||
return Err(LoadError::MalformedSection);
|
||||
}
|
||||
let count = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
|
||||
let mut cp = Vec::with_capacity(count);
|
||||
let mut pos = 4;
|
||||
|
||||
for _ in 0..count {
|
||||
if pos >= data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let tag = data[pos];
|
||||
pos += 1;
|
||||
match tag {
|
||||
0 => cp.push(ConstantPoolEntry::Null),
|
||||
1 => {
|
||||
// Int64
|
||||
if pos + 8 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let val = i64::from_le_bytes(data[pos..pos + 8].try_into().unwrap());
|
||||
cp.push(ConstantPoolEntry::Int64(val));
|
||||
pos += 8;
|
||||
}
|
||||
2 => {
|
||||
// Float64
|
||||
if pos + 8 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let val = f64::from_le_bytes(data[pos..pos + 8].try_into().unwrap());
|
||||
cp.push(ConstantPoolEntry::Float64(val));
|
||||
pos += 8;
|
||||
}
|
||||
3 => {
|
||||
// Boolean
|
||||
if pos >= data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
cp.push(ConstantPoolEntry::Boolean(data[pos] != 0));
|
||||
pos += 1;
|
||||
}
|
||||
4 => {
|
||||
// String
|
||||
if pos + 4 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let len = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
|
||||
pos += 4;
|
||||
if pos + len > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let s = String::from_utf8_lossy(&data[pos..pos + len]).into_owned();
|
||||
cp.push(ConstantPoolEntry::String(s));
|
||||
pos += len;
|
||||
}
|
||||
5 => {
|
||||
// Int32
|
||||
if pos + 4 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let val = i32::from_le_bytes(data[pos..pos + 4].try_into().unwrap());
|
||||
cp.push(ConstantPoolEntry::Int32(val));
|
||||
pos += 4;
|
||||
}
|
||||
_ => return Err(LoadError::MalformedSection),
|
||||
}
|
||||
}
|
||||
Ok(cp)
|
||||
}
|
||||
|
||||
fn parse_functions(data: &[u8]) -> Result<Vec<FunctionMeta>, LoadError> {
|
||||
if data.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if data.len() < 4 {
|
||||
return Err(LoadError::MalformedSection);
|
||||
}
|
||||
let count = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
|
||||
let mut functions = Vec::with_capacity(count);
|
||||
let mut pos = 4;
|
||||
|
||||
for _ in 0..count {
|
||||
if pos + 16 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let code_offset = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap());
|
||||
let code_len = u32::from_le_bytes(data[pos + 4..pos + 8].try_into().unwrap());
|
||||
let param_slots = u16::from_le_bytes(data[pos + 8..pos + 10].try_into().unwrap());
|
||||
let local_slots = u16::from_le_bytes(data[pos + 10..pos + 12].try_into().unwrap());
|
||||
let return_slots = u16::from_le_bytes(data[pos + 12..pos + 14].try_into().unwrap());
|
||||
let max_stack_slots = u16::from_le_bytes(data[pos + 14..pos + 16].try_into().unwrap());
|
||||
|
||||
functions.push(FunctionMeta {
|
||||
code_offset,
|
||||
code_len,
|
||||
param_slots,
|
||||
local_slots,
|
||||
return_slots,
|
||||
max_stack_slots,
|
||||
});
|
||||
pos += 16;
|
||||
}
|
||||
Ok(functions)
|
||||
}
|
||||
|
||||
fn parse_debug_section(data: &[u8]) -> Result<DebugInfo, LoadError> {
|
||||
if data.is_empty() {
|
||||
return Ok(DebugInfo::default());
|
||||
}
|
||||
if data.len() < 8 {
|
||||
return Err(LoadError::MalformedSection);
|
||||
}
|
||||
|
||||
let mut pos = 0;
|
||||
|
||||
// PC to Span table
|
||||
let span_count = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
|
||||
pos += 4;
|
||||
let mut pc_to_span = Vec::with_capacity(span_count);
|
||||
for _ in 0..span_count {
|
||||
if pos + 16 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let pc = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap());
|
||||
let file_id = u32::from_le_bytes(data[pos + 4..pos + 8].try_into().unwrap());
|
||||
let start = u32::from_le_bytes(data[pos + 8..pos + 12].try_into().unwrap());
|
||||
let end = u32::from_le_bytes(data[pos + 12..pos + 16].try_into().unwrap());
|
||||
pc_to_span.push((pc, SourceSpan { file_id, start, end }));
|
||||
pos += 16;
|
||||
}
|
||||
|
||||
// Function names table
|
||||
if pos + 4 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let func_name_count = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
|
||||
pos += 4;
|
||||
let mut function_names = Vec::with_capacity(func_name_count);
|
||||
for _ in 0..func_name_count {
|
||||
if pos + 8 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let func_idx = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap());
|
||||
let name_len = u32::from_le_bytes(data[pos + 4..pos + 8].try_into().unwrap()) as usize;
|
||||
pos += 8;
|
||||
if pos + name_len > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let name = String::from_utf8_lossy(&data[pos..pos + name_len]).into_owned();
|
||||
function_names.push((func_idx, name));
|
||||
pos += name_len;
|
||||
}
|
||||
|
||||
Ok(DebugInfo { pc_to_span, function_names })
|
||||
}
|
||||
|
||||
fn parse_exports(data: &[u8]) -> Result<Vec<Export>, LoadError> {
|
||||
if data.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if data.len() < 4 {
|
||||
return Err(LoadError::MalformedSection);
|
||||
}
|
||||
let count = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
|
||||
let mut exports = Vec::with_capacity(count);
|
||||
let mut pos = 4;
|
||||
|
||||
for _ in 0..count {
|
||||
if pos + 8 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let func_idx = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap());
|
||||
let name_len = u32::from_le_bytes(data[pos + 4..pos + 8].try_into().unwrap()) as usize;
|
||||
pos += 8;
|
||||
if pos + name_len > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let symbol = String::from_utf8_lossy(&data[pos..pos + name_len]).into_owned();
|
||||
exports.push(Export { symbol, func_idx });
|
||||
pos += name_len;
|
||||
}
|
||||
Ok(exports)
|
||||
}
|
||||
|
||||
fn parse_syscalls(data: &[u8]) -> Result<Vec<SyscallDecl>, LoadError> {
|
||||
if data.len() < 4 {
|
||||
return Err(LoadError::MalformedSection);
|
||||
}
|
||||
|
||||
let count = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
|
||||
let mut syscalls = Vec::with_capacity(count);
|
||||
let mut pos = 4;
|
||||
|
||||
for _ in 0..count {
|
||||
if pos + 2 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let module_len = u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
|
||||
pos += 2;
|
||||
if pos + module_len > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let module = std::str::from_utf8(&data[pos..pos + module_len])
|
||||
.map_err(|_| LoadError::InvalidUtf8)?;
|
||||
pos += module_len;
|
||||
|
||||
if pos + 2 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let name_len = u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap()) as usize;
|
||||
pos += 2;
|
||||
if pos + name_len > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let name =
|
||||
std::str::from_utf8(&data[pos..pos + name_len]).map_err(|_| LoadError::InvalidUtf8)?;
|
||||
pos += name_len;
|
||||
|
||||
if pos + 6 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let version = u16::from_le_bytes(data[pos..pos + 2].try_into().unwrap());
|
||||
let arg_slots = u16::from_le_bytes(data[pos + 2..pos + 4].try_into().unwrap());
|
||||
let ret_slots = u16::from_le_bytes(data[pos + 4..pos + 6].try_into().unwrap());
|
||||
pos += 6;
|
||||
|
||||
syscalls.push(SyscallDecl {
|
||||
module: module.to_owned(),
|
||||
name: name.to_owned(),
|
||||
version,
|
||||
arg_slots,
|
||||
ret_slots,
|
||||
});
|
||||
}
|
||||
|
||||
if pos != data.len() {
|
||||
return Err(LoadError::MalformedSection);
|
||||
}
|
||||
|
||||
Ok(syscalls)
|
||||
}
|
||||
|
||||
fn validate_module(module: &BytecodeModule) -> Result<(), LoadError> {
|
||||
let mut syscall_identities = HashSet::with_capacity(module.syscalls.len());
|
||||
for syscall in &module.syscalls {
|
||||
if !syscall_identities.insert((
|
||||
syscall.module.clone(),
|
||||
syscall.name.clone(),
|
||||
syscall.version,
|
||||
)) {
|
||||
return Err(LoadError::DuplicateSyscallIdentity);
|
||||
}
|
||||
}
|
||||
|
||||
for func in &module.functions {
|
||||
// Opcode stream bounds
|
||||
if (func.code_offset as usize) + (func.code_len as usize) > module.code.len() {
|
||||
return Err(LoadError::InvalidFunctionIndex);
|
||||
}
|
||||
}
|
||||
|
||||
// Basic opcode scan for const pool indices
|
||||
let mut pos = 0;
|
||||
while pos < module.code.len() {
|
||||
if pos + 2 > module.code.len() {
|
||||
break; // Unexpected EOF in middle of opcode, maybe should be error
|
||||
}
|
||||
let op_val = u16::from_le_bytes([module.code[pos], module.code[pos + 1]]);
|
||||
let opcode = OpCode::try_from(op_val).map_err(|_| LoadError::InvalidOpcode)?;
|
||||
pos += 2;
|
||||
|
||||
match opcode {
|
||||
OpCode::PushConst => {
|
||||
if pos + 4 > module.code.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let idx =
|
||||
u32::from_le_bytes(module.code[pos..pos + 4].try_into().unwrap()) as usize;
|
||||
if idx >= module.const_pool.len() {
|
||||
return Err(LoadError::InvalidConstIndex);
|
||||
}
|
||||
pos += 4;
|
||||
}
|
||||
OpCode::PushI32
|
||||
| OpCode::Jmp
|
||||
| OpCode::JmpIfFalse
|
||||
| OpCode::JmpIfTrue
|
||||
| OpCode::GetGlobal
|
||||
| OpCode::SetGlobal
|
||||
| OpCode::GetLocal
|
||||
| OpCode::SetLocal
|
||||
| OpCode::PopN
|
||||
| OpCode::Hostcall
|
||||
| OpCode::Syscall
|
||||
| OpCode::Intrinsic => {
|
||||
pos += 4;
|
||||
}
|
||||
OpCode::PushI64 | OpCode::PushF64 => {
|
||||
pos += 8;
|
||||
}
|
||||
OpCode::PushBool => {
|
||||
pos += 1;
|
||||
}
|
||||
OpCode::Call => {
|
||||
pos += 4;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn create_header(section_count: u32) -> Vec<u8> {
|
||||
let mut h = vec![0u8; 32];
|
||||
h[0..4].copy_from_slice(b"PBS\0");
|
||||
h[4..6].copy_from_slice(&0u16.to_le_bytes()); // version
|
||||
h[6] = 0; // endianness
|
||||
h[8..12].copy_from_slice(§ion_count.to_le_bytes());
|
||||
h
|
||||
}
|
||||
|
||||
fn minimal_module() -> BytecodeModule {
|
||||
BytecodeModule {
|
||||
version: 0,
|
||||
const_pool: vec![],
|
||||
functions: vec![],
|
||||
code: vec![],
|
||||
debug_info: None,
|
||||
exports: vec![],
|
||||
syscalls: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn build_pbs_with_sections(sections: Vec<(u32, Vec<u8>)>) -> Vec<u8> {
|
||||
let mut data = create_header(sections.len() as u32);
|
||||
let mut offset = 32 + (sections.len() as u32 * 12);
|
||||
|
||||
for (kind, section_data) in §ions {
|
||||
data.extend_from_slice(&kind.to_le_bytes());
|
||||
data.extend_from_slice(&offset.to_le_bytes());
|
||||
data.extend_from_slice(&(section_data.len() as u32).to_le_bytes());
|
||||
offset += section_data.len() as u32;
|
||||
}
|
||||
|
||||
for (_, section_data) in sections {
|
||||
data.extend_from_slice(§ion_data);
|
||||
}
|
||||
|
||||
data
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_magic() {
|
||||
let mut data = create_header(0);
|
||||
data[0] = b'X';
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidMagic));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_version() {
|
||||
let mut data = create_header(0);
|
||||
data[4] = 1;
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidVersion));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_endianness() {
|
||||
let mut data = create_header(0);
|
||||
data[6] = 1;
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidEndianness));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_overlapping_sections() {
|
||||
let mut data = create_header(2);
|
||||
// Section 1: Kind 0, Offset 64, Length 32
|
||||
data.extend_from_slice(&0u32.to_le_bytes());
|
||||
data.extend_from_slice(&64u32.to_le_bytes());
|
||||
data.extend_from_slice(&32u32.to_le_bytes());
|
||||
// Section 2: Kind 1, Offset 80, Length 32 (Overlaps with Section 1)
|
||||
data.extend_from_slice(&1u32.to_le_bytes());
|
||||
data.extend_from_slice(&80u32.to_le_bytes());
|
||||
data.extend_from_slice(&32u32.to_le_bytes());
|
||||
|
||||
// Ensure data is long enough for the offsets
|
||||
data.resize(256, 0);
|
||||
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::OverlappingSections));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_section_out_of_bounds() {
|
||||
let mut data = create_header(1);
|
||||
// Section 1: Kind 0, Offset 64, Length 1000
|
||||
data.extend_from_slice(&0u32.to_le_bytes());
|
||||
data.extend_from_slice(&64u32.to_le_bytes());
|
||||
data.extend_from_slice(&1000u32.to_le_bytes());
|
||||
|
||||
data.resize(256, 0);
|
||||
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::SectionOutOfBounds));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_function_code_offset() {
|
||||
let mut data = create_header(3);
|
||||
// Section 1: Functions, Kind 1, Offset 80, Length 20 (Header 4 + 1 entry 16)
|
||||
data.extend_from_slice(&1u32.to_le_bytes());
|
||||
data.extend_from_slice(&80u32.to_le_bytes());
|
||||
data.extend_from_slice(&20u32.to_le_bytes());
|
||||
|
||||
// Section 2: Code, Kind 2, Offset 128, Length 10
|
||||
data.extend_from_slice(&2u32.to_le_bytes());
|
||||
data.extend_from_slice(&128u32.to_le_bytes());
|
||||
data.extend_from_slice(&10u32.to_le_bytes());
|
||||
|
||||
// Section 3: SYSC, Kind 5, Offset 160, Length 4 (empty)
|
||||
data.extend_from_slice(&5u32.to_le_bytes());
|
||||
data.extend_from_slice(&160u32.to_le_bytes());
|
||||
data.extend_from_slice(&4u32.to_le_bytes());
|
||||
|
||||
data.resize(256, 0);
|
||||
|
||||
// Setup functions section
|
||||
let func_data_start = 80;
|
||||
data[func_data_start..func_data_start + 4].copy_from_slice(&1u32.to_le_bytes()); // 1 function
|
||||
let entry_start = func_data_start + 4;
|
||||
data[entry_start..entry_start + 4].copy_from_slice(&5u32.to_le_bytes()); // code_offset = 5
|
||||
data[entry_start + 4..entry_start + 8].copy_from_slice(&10u32.to_le_bytes()); // code_len = 10
|
||||
// 5 + 10 = 15 > 10 (code section length)
|
||||
data[160..164].copy_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidFunctionIndex));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_const_index() {
|
||||
let mut data = create_header(3);
|
||||
// Section 1: Const Pool, Kind 0, Offset 80, Length 4 (Empty CP)
|
||||
data.extend_from_slice(&0u32.to_le_bytes());
|
||||
data.extend_from_slice(&80u32.to_le_bytes());
|
||||
data.extend_from_slice(&4u32.to_le_bytes());
|
||||
|
||||
// Section 2: Code, Kind 2, Offset 128, Length 6 (PushConst 0)
|
||||
data.extend_from_slice(&2u32.to_le_bytes());
|
||||
data.extend_from_slice(&128u32.to_le_bytes());
|
||||
data.extend_from_slice(&6u32.to_le_bytes());
|
||||
|
||||
// Section 3: SYSC, Kind 5, Offset 160, Length 4 (empty)
|
||||
data.extend_from_slice(&5u32.to_le_bytes());
|
||||
data.extend_from_slice(&160u32.to_le_bytes());
|
||||
data.extend_from_slice(&4u32.to_le_bytes());
|
||||
|
||||
data.resize(256, 0);
|
||||
|
||||
// Setup empty CP
|
||||
data[80..84].copy_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
// Setup code with PushConst 0
|
||||
data[128..130].copy_from_slice(&(OpCode::PushConst as u16).to_le_bytes());
|
||||
data[130..134].copy_from_slice(&0u32.to_le_bytes());
|
||||
data[160..164].copy_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidConstIndex));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_missing_sysc_section_is_rejected() {
|
||||
let data = create_header(0);
|
||||
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::MissingSyscallSection));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_valid_minimal_load_with_empty_sysc() {
|
||||
let data = minimal_module().serialize();
|
||||
let module = BytecodeLoader::load(&data).unwrap();
|
||||
assert_eq!(module.version, 0);
|
||||
assert!(module.const_pool.is_empty());
|
||||
assert!(module.functions.is_empty());
|
||||
assert!(module.code.is_empty());
|
||||
assert!(module.syscalls.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_valid_sysc_roundtrip() {
|
||||
let mut module = minimal_module();
|
||||
module.syscalls = vec![SyscallDecl {
|
||||
module: "gfx".into(),
|
||||
name: "draw_line".into(),
|
||||
version: 1,
|
||||
arg_slots: 4,
|
||||
ret_slots: 0,
|
||||
}];
|
||||
|
||||
let data = module.serialize();
|
||||
let loaded = BytecodeLoader::load(&data).unwrap();
|
||||
|
||||
assert_eq!(loaded.syscalls, module.syscalls);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_malformed_sysc_section_is_rejected() {
|
||||
let data = build_pbs_with_sections(vec![(SECTION_KIND_SYSCALLS, vec![1, 0, 0])]);
|
||||
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::MalformedSection));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_utf8_in_sysc_section_is_rejected() {
|
||||
let mut sysc = Vec::new();
|
||||
sysc.extend_from_slice(&1u32.to_le_bytes());
|
||||
sysc.extend_from_slice(&1u16.to_le_bytes());
|
||||
sysc.push(0xFF);
|
||||
sysc.extend_from_slice(&1u16.to_le_bytes());
|
||||
sysc.push(b'x');
|
||||
sysc.extend_from_slice(&1u16.to_le_bytes());
|
||||
sysc.extend_from_slice(&0u16.to_le_bytes());
|
||||
sysc.extend_from_slice(&0u16.to_le_bytes());
|
||||
|
||||
let data = build_pbs_with_sections(vec![(SECTION_KIND_SYSCALLS, sysc)]);
|
||||
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidUtf8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_duplicate_sysc_identity_is_rejected() {
|
||||
let mut module = minimal_module();
|
||||
module.syscalls = vec![
|
||||
SyscallDecl {
|
||||
module: "system".into(),
|
||||
name: "has_cart".into(),
|
||||
version: 1,
|
||||
arg_slots: 0,
|
||||
ret_slots: 1,
|
||||
},
|
||||
SyscallDecl {
|
||||
module: "system".into(),
|
||||
name: "has_cart".into(),
|
||||
version: 1,
|
||||
arg_slots: 0,
|
||||
ret_slots: 1,
|
||||
},
|
||||
];
|
||||
|
||||
let data = module.serialize();
|
||||
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::DuplicateSyscallIdentity));
|
||||
}
|
||||
}
|
||||
pub const PBX_MAGIC: [u8; 4] = *b"PBX\0";
|
||||
|
||||
@@ -143,46 +143,20 @@ pub enum OpCode {
|
||||
/// Returns from the current function.
|
||||
/// Stack: [return_val] -> [return_val]
|
||||
Ret = 0x51,
|
||||
/// Creates a closure capturing values from the operand stack (Model B).
|
||||
/// Operands: fn_id (u32), capture_count (u32)
|
||||
/// Stack before: [..., captured_N, ..., captured_1]
|
||||
/// Pops capture_count values (top-first), preserves order as [captured_1..captured_N]
|
||||
/// and stores them inside the closure environment. Pushes a HeapRef to the closure.
|
||||
/// Create a typed instance: FunctionId, FnTypeId. Captures come from metadata.
|
||||
MakeClosure = 0x52,
|
||||
/// Calls a closure value with hidden arg0 semantics (Model B).
|
||||
/// Operand: arg_count (u32) — number of user-supplied args (excludes hidden arg0)
|
||||
/// Stack before: [..., argN, ..., arg1, closure_ref]
|
||||
/// Behavior:
|
||||
/// - Pops `closure_ref` and validates it is a Closure.
|
||||
/// - Pops `arg_count` user args.
|
||||
/// - Fetches `fn_id` from the closure and creates a new call frame.
|
||||
/// - Injects hidden arg0 = closure_ref, followed by user args as arg1..argN.
|
||||
/// Invoke with expected FnTypeId; environment belongs to CallFrame, not arg0.
|
||||
CallClosure = 0x53,
|
||||
|
||||
// --- 7.x Concurrency / Coroutines ---
|
||||
/// Spawns a new coroutine to run a function with arguments.
|
||||
/// Operands: fn_id (u32), arg_count (u32)
|
||||
/// Semantics:
|
||||
/// - Pops `arg_count` arguments from the current operand stack (top-first),
|
||||
/// preserving user order as arg1..argN for the callee.
|
||||
/// - Allocates a new Coroutine object with its own stack and a single entry frame
|
||||
/// pointing at `fn_id`.
|
||||
/// - Enqueues the coroutine into the scheduler ready queue.
|
||||
/// - Does NOT switch execution immediately; current coroutine continues.
|
||||
/// Retired opcode, recognized only for load rejection and diagnostics.
|
||||
Spawn = 0x54,
|
||||
|
||||
/// Cooperatively yields the current coroutine. Execution continues
|
||||
/// until the next VM safepoint (FRAME_SYNC), where the scheduler
|
||||
/// may switch to another ready coroutine.
|
||||
/// Retired opcode, recognized only for load rejection and diagnostics.
|
||||
Yield = 0x55,
|
||||
|
||||
/// Suspends the current coroutine for a number of logical ticks.
|
||||
/// Operand: duration_ticks (u32)
|
||||
/// Semantics:
|
||||
/// - Set the coroutine wake tick to `current_tick + duration_ticks`.
|
||||
/// - End the current logical frame (as if reaching FRAME_SYNC).
|
||||
/// - The coroutine will resume execution on or after the wake tick.
|
||||
/// Retired opcode, recognized only for load rejection and diagnostics.
|
||||
Sleep = 0x56,
|
||||
/// Copy complete current-frame capture group by declaration index.
|
||||
GetCapture = 0x57,
|
||||
/// Dispatch through an immutable implementation: TraitTypeId, method index.
|
||||
CallTrait = 0x58,
|
||||
|
||||
// --- 6.8 Peripherals and System ---
|
||||
/// Pre-load host binding call by `SYSC` table index.
|
||||
@@ -202,6 +176,37 @@ pub enum OpCode {
|
||||
/// Synchronizes the VM with the hardware frame (usually 60Hz).
|
||||
/// Execution pauses until the next VSync.
|
||||
FrameSync = 0x80,
|
||||
|
||||
// Registry-dependent typed operations (DEC-0045).
|
||||
/// DYN_PACK: TypeId:u32; requires validated Registry metadata.
|
||||
DynPack = 0x90,
|
||||
/// DYN_UNPACK: TypeId:u32; requires validated Registry metadata.
|
||||
DynUnpack = 0x91,
|
||||
/// DYN_CAN_UNPACK: TypeId:u32; requires validated Registry metadata.
|
||||
DynCanUnpack = 0x92,
|
||||
/// REF_IS_EXACT: source:TypeId, target:TypeId; requires validated Registry metadata.
|
||||
RefIsExact = 0x93,
|
||||
/// REF_IMPLEMENTS: source:TypeId, target:TypeId; requires validated Registry metadata.
|
||||
RefImplements = 0x94,
|
||||
/// REF_TO_TRAIT: source:TypeId, target:TypeId; requires validated Registry metadata.
|
||||
RefToTrait = 0x95,
|
||||
/// REF_CAST: source:TypeId, target:TypeId; requires validated Registry metadata.
|
||||
RefCast = 0x96,
|
||||
/// Query a complete typed reference identity; source TypeId.
|
||||
RefIdentityHash = 0x97,
|
||||
/// Compare two complete typed references; left/right TypeIds.
|
||||
RefIdentityEq = 0x98,
|
||||
|
||||
// Registry-backed collection operations. cycles() is their base component.
|
||||
StructNew = 0xA0,
|
||||
StructGet = 0xA1,
|
||||
StructSet = 0xA2,
|
||||
ArrayNew = 0xA3,
|
||||
ArrayLen = 0xA4,
|
||||
ArrayGet = 0xA5,
|
||||
ArraySet = 0xA6,
|
||||
/// Complete stored groups, overlap-safe; Array TypeId:u32.
|
||||
ArrayCopy = 0xA9,
|
||||
}
|
||||
|
||||
impl TryFrom<u16> for OpCode {
|
||||
@@ -255,18 +260,39 @@ impl TryFrom<u16> for OpCode {
|
||||
0x54 => Ok(OpCode::Spawn),
|
||||
0x55 => Ok(OpCode::Yield),
|
||||
0x56 => Ok(OpCode::Sleep),
|
||||
0x57 => Ok(OpCode::GetCapture),
|
||||
0x58 => Ok(OpCode::CallTrait),
|
||||
0x70 => Ok(OpCode::Syscall),
|
||||
0x71 => Ok(OpCode::Hostcall),
|
||||
0x72 => Ok(OpCode::Intrinsic),
|
||||
0x80 => Ok(OpCode::FrameSync),
|
||||
0x90 => Ok(OpCode::DynPack),
|
||||
0x91 => Ok(OpCode::DynUnpack),
|
||||
0x92 => Ok(OpCode::DynCanUnpack),
|
||||
0x93 => Ok(OpCode::RefIsExact),
|
||||
0x94 => Ok(OpCode::RefImplements),
|
||||
0x95 => Ok(OpCode::RefToTrait),
|
||||
0x96 => Ok(OpCode::RefCast),
|
||||
0x97 => Ok(OpCode::RefIdentityHash),
|
||||
0x98 => Ok(OpCode::RefIdentityEq),
|
||||
0xA0 => Ok(OpCode::StructNew),
|
||||
0xA1 => Ok(OpCode::StructGet),
|
||||
0xA2 => Ok(OpCode::StructSet),
|
||||
0xA3 => Ok(OpCode::ArrayNew),
|
||||
0xA4 => Ok(OpCode::ArrayLen),
|
||||
0xA5 => Ok(OpCode::ArrayGet),
|
||||
0xA6 => Ok(OpCode::ArraySet),
|
||||
0xA9 => Ok(OpCode::ArrayCopy),
|
||||
|
||||
_ => Err(format!("Invalid OpCode: 0x{:04X}", value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OpCode {
|
||||
/// Returns the cost of the instruction in VM cycles.
|
||||
/// This is used for performance monitoring and resource limiting (Certification).
|
||||
/// Returns fixed VM cycles, or the base component for collection operations.
|
||||
/// Collection execution adds Registry widths and valid construction length;
|
||||
/// callers must not use this base alone as the complete attempt cost.
|
||||
pub fn cycles(&self) -> u64 {
|
||||
match self {
|
||||
OpCode::Nop => 1,
|
||||
@@ -311,7 +337,8 @@ impl OpCode {
|
||||
OpCode::Call => 5,
|
||||
OpCode::Ret => 4,
|
||||
OpCode::MakeClosure => 8,
|
||||
OpCode::CallClosure => 6,
|
||||
OpCode::CallClosure | OpCode::CallTrait => 6,
|
||||
OpCode::GetCapture => 2,
|
||||
OpCode::Spawn => 6,
|
||||
OpCode::Yield => 1,
|
||||
OpCode::Sleep => 1,
|
||||
@@ -319,6 +346,23 @@ impl OpCode {
|
||||
OpCode::Hostcall => 1,
|
||||
OpCode::Intrinsic => 1,
|
||||
OpCode::FrameSync => 1,
|
||||
OpCode::DynPack => 8,
|
||||
OpCode::DynUnpack => 4,
|
||||
OpCode::DynCanUnpack => 3,
|
||||
OpCode::RefIsExact => 4,
|
||||
OpCode::RefImplements => 4,
|
||||
OpCode::RefToTrait => 5,
|
||||
OpCode::RefCast => 4,
|
||||
OpCode::RefIdentityHash => 8,
|
||||
OpCode::RefIdentityEq => 4,
|
||||
OpCode::StructNew => 8,
|
||||
OpCode::StructGet => 3,
|
||||
OpCode::StructSet => 4,
|
||||
OpCode::ArrayNew => 8,
|
||||
OpCode::ArrayLen => 3,
|
||||
OpCode::ArrayGet => 3,
|
||||
OpCode::ArraySet => 4,
|
||||
OpCode::ArrayCopy => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,18 +5,24 @@ use crate::opcode::OpCode;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct OpcodeSpec {
|
||||
pub name: &'static str,
|
||||
pub imm_bytes: u8, // immediate payload size (decode)
|
||||
pub pops: u16, // slots popped
|
||||
pub pushes: u16, // slots pushed
|
||||
pub is_branch: bool, // has a control-flow target
|
||||
pub imm_bytes: u8, // immediate payload size (decode)
|
||||
/// None requires Registry resolution; it never means zero slots.
|
||||
pub pops: Option<u16>, // slots popped
|
||||
/// None requires Registry resolution; it never means zero slots.
|
||||
pub pushes: Option<u16>, // slots pushed
|
||||
pub is_branch: bool, // has a control-flow target
|
||||
pub is_terminator: bool, // ends basic block: JMP/RET/TRAP/HALT
|
||||
pub may_trap: bool, // runtime trap possible
|
||||
/// Marks this opcode as a VM safepoint. Used by GC/scheduler policies.
|
||||
pub may_trap: bool, // runtime trap possible
|
||||
/// Marks this opcode as a VM safepoint. Used by GC policies. Last-root RET is also a contextual GC opportunity.
|
||||
pub is_safepoint: bool,
|
||||
}
|
||||
|
||||
pub trait OpCodeSpecExt {
|
||||
fn spec(&self) -> OpcodeSpec;
|
||||
/// These instructions cannot be verified from slot-only ExecutionFunction.
|
||||
fn requires_registry(&self) -> bool {
|
||||
self.spec().pops.is_none() || self.spec().pushes.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
impl OpCodeSpecExt for OpCode {
|
||||
@@ -25,8 +31,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Nop => OpcodeSpec {
|
||||
name: "NOP",
|
||||
imm_bytes: 0,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -35,8 +41,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Halt => OpcodeSpec {
|
||||
name: "HALT",
|
||||
imm_bytes: 0,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: true,
|
||||
may_trap: false,
|
||||
@@ -45,8 +51,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Jmp => OpcodeSpec {
|
||||
name: "JMP",
|
||||
imm_bytes: 4,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: true,
|
||||
is_terminator: true,
|
||||
may_trap: false,
|
||||
@@ -55,8 +61,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::JmpIfFalse => OpcodeSpec {
|
||||
name: "JMP_IF_FALSE",
|
||||
imm_bytes: 4,
|
||||
pops: 1,
|
||||
pushes: 0,
|
||||
pops: Some(1),
|
||||
pushes: Some(0),
|
||||
is_branch: true,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
@@ -65,8 +71,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::JmpIfTrue => OpcodeSpec {
|
||||
name: "JMP_IF_TRUE",
|
||||
imm_bytes: 4,
|
||||
pops: 1,
|
||||
pushes: 0,
|
||||
pops: Some(1),
|
||||
pushes: Some(0),
|
||||
is_branch: true,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
@@ -75,8 +81,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Trap => OpcodeSpec {
|
||||
name: "TRAP",
|
||||
imm_bytes: 0,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: true,
|
||||
may_trap: true,
|
||||
@@ -85,8 +91,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::PushConst => OpcodeSpec {
|
||||
name: "PUSH_CONST",
|
||||
imm_bytes: 4,
|
||||
pops: 0,
|
||||
pushes: 1,
|
||||
pops: Some(0),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -95,8 +101,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Pop => OpcodeSpec {
|
||||
name: "POP",
|
||||
imm_bytes: 0,
|
||||
pops: 1,
|
||||
pushes: 0,
|
||||
pops: Some(1),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -105,8 +111,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::PopN => OpcodeSpec {
|
||||
name: "POP_N",
|
||||
imm_bytes: 4,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -115,8 +121,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Dup => OpcodeSpec {
|
||||
name: "DUP",
|
||||
imm_bytes: 0,
|
||||
pops: 1,
|
||||
pushes: 2,
|
||||
pops: Some(1),
|
||||
pushes: Some(2),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -125,8 +131,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Swap => OpcodeSpec {
|
||||
name: "SWAP",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 2,
|
||||
pops: Some(2),
|
||||
pushes: Some(2),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -135,8 +141,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::PushI64 => OpcodeSpec {
|
||||
name: "PUSH_I64",
|
||||
imm_bytes: 8,
|
||||
pops: 0,
|
||||
pushes: 1,
|
||||
pops: Some(0),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -145,8 +151,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::PushF64 => OpcodeSpec {
|
||||
name: "PUSH_F64",
|
||||
imm_bytes: 8,
|
||||
pops: 0,
|
||||
pushes: 1,
|
||||
pops: Some(0),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -155,8 +161,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::PushBool => OpcodeSpec {
|
||||
name: "PUSH_BOOL",
|
||||
imm_bytes: 1,
|
||||
pops: 0,
|
||||
pushes: 1,
|
||||
pops: Some(0),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -165,8 +171,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::PushI32 => OpcodeSpec {
|
||||
name: "PUSH_I32",
|
||||
imm_bytes: 4,
|
||||
pops: 0,
|
||||
pushes: 1,
|
||||
pops: Some(0),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -175,8 +181,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Add => OpcodeSpec {
|
||||
name: "ADD",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
@@ -185,8 +191,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Sub => OpcodeSpec {
|
||||
name: "SUB",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
@@ -195,8 +201,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Mul => OpcodeSpec {
|
||||
name: "MUL",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
@@ -205,8 +211,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Div => OpcodeSpec {
|
||||
name: "DIV",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
@@ -215,8 +221,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Mod => OpcodeSpec {
|
||||
name: "MOD",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
@@ -225,8 +231,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Eq => OpcodeSpec {
|
||||
name: "EQ",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -235,8 +241,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Neq => OpcodeSpec {
|
||||
name: "NEQ",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -245,8 +251,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Lt => OpcodeSpec {
|
||||
name: "LT",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -255,8 +261,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Gt => OpcodeSpec {
|
||||
name: "GT",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -265,8 +271,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::And => OpcodeSpec {
|
||||
name: "AND",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -275,8 +281,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Or => OpcodeSpec {
|
||||
name: "OR",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -285,8 +291,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Not => OpcodeSpec {
|
||||
name: "NOT",
|
||||
imm_bytes: 0,
|
||||
pops: 1,
|
||||
pushes: 1,
|
||||
pops: Some(1),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -295,8 +301,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::BitAnd => OpcodeSpec {
|
||||
name: "BIT_AND",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -305,8 +311,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::BitOr => OpcodeSpec {
|
||||
name: "BIT_OR",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -315,8 +321,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::BitXor => OpcodeSpec {
|
||||
name: "BIT_XOR",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -325,8 +331,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Shl => OpcodeSpec {
|
||||
name: "SHL",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -335,8 +341,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Shr => OpcodeSpec {
|
||||
name: "SHR",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -345,8 +351,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Lte => OpcodeSpec {
|
||||
name: "LTE",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -355,8 +361,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Gte => OpcodeSpec {
|
||||
name: "GTE",
|
||||
imm_bytes: 0,
|
||||
pops: 2,
|
||||
pushes: 1,
|
||||
pops: Some(2),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -365,8 +371,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Neg => OpcodeSpec {
|
||||
name: "NEG",
|
||||
imm_bytes: 0,
|
||||
pops: 1,
|
||||
pushes: 1,
|
||||
pops: Some(1),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -375,8 +381,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::GetGlobal => OpcodeSpec {
|
||||
name: "GET_GLOBAL",
|
||||
imm_bytes: 4,
|
||||
pops: 0,
|
||||
pushes: 1,
|
||||
pops: Some(0),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -385,8 +391,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::SetGlobal => OpcodeSpec {
|
||||
name: "SET_GLOBAL",
|
||||
imm_bytes: 4,
|
||||
pops: 1,
|
||||
pushes: 0,
|
||||
pops: Some(1),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -395,8 +401,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::GetLocal => OpcodeSpec {
|
||||
name: "GET_LOCAL",
|
||||
imm_bytes: 4,
|
||||
pops: 0,
|
||||
pushes: 1,
|
||||
pops: Some(0),
|
||||
pushes: Some(1),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -405,8 +411,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::SetLocal => OpcodeSpec {
|
||||
name: "SET_LOCAL",
|
||||
imm_bytes: 4,
|
||||
pops: 1,
|
||||
pushes: 0,
|
||||
pops: Some(1),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -415,8 +421,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Call => OpcodeSpec {
|
||||
name: "CALL",
|
||||
imm_bytes: 4,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
@@ -425,44 +431,41 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Ret => OpcodeSpec {
|
||||
name: "RET",
|
||||
imm_bytes: 0,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: true,
|
||||
may_trap: false,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::MakeClosure => OpcodeSpec {
|
||||
name: "MAKE_CLOSURE",
|
||||
// Two u32 immediates: fn_id and capture_count
|
||||
imm_bytes: 8,
|
||||
// Dynamic, depends on capture_count; keep 0 here for verifier-free spec
|
||||
pops: 0,
|
||||
pushes: 1,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::CallClosure => OpcodeSpec {
|
||||
name: "CALL_CLOSURE",
|
||||
// One u32 immediate: arg_count (user args, excludes hidden arg0)
|
||||
imm_bytes: 4,
|
||||
// Dynamic: pops closure_ref + arg_count; keep 0 in spec layer
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::MakeClosure | OpCode::CallClosure | OpCode::GetCapture | OpCode::CallTrait => {
|
||||
OpcodeSpec {
|
||||
name: match self {
|
||||
OpCode::MakeClosure => "MAKE_CLOSURE",
|
||||
OpCode::CallClosure => "CALL_CLOSURE",
|
||||
OpCode::GetCapture => "GET_CAPTURE",
|
||||
_ => "CALL_TRAIT",
|
||||
},
|
||||
imm_bytes: if matches!(self, OpCode::MakeClosure | OpCode::CallTrait) {
|
||||
8
|
||||
} else {
|
||||
4
|
||||
},
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
}
|
||||
}
|
||||
OpCode::Spawn => OpcodeSpec {
|
||||
name: "SPAWN",
|
||||
// Two u32 immediates: fn_id and arg_count
|
||||
imm_bytes: 8,
|
||||
// Dynamic pops depends on arg_count; keep 0 here in spec layer
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -471,33 +474,33 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Yield => OpcodeSpec {
|
||||
name: "YIELD",
|
||||
imm_bytes: 0,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
// Not a block terminator; effect realized at safepoint
|
||||
// Retired encoding: retained for diagnostic decoding only.
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
// Treated as a safepoint marker for cooperative scheduling
|
||||
is_safepoint: true,
|
||||
// Loading rejects this opcode, including unreachable occurrences.
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::Sleep => OpcodeSpec {
|
||||
name: "SLEEP",
|
||||
// One u32 immediate: duration_ticks
|
||||
imm_bytes: 4,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
// Ends execution at safepoint after instruction completes
|
||||
// Retired encoding: retained for diagnostic decoding only.
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
// Considered a safepoint since it forces a frame boundary
|
||||
is_safepoint: true,
|
||||
// Loading rejects this opcode, including unreachable occurrences.
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::Hostcall => OpcodeSpec {
|
||||
name: "HOSTCALL",
|
||||
imm_bytes: 4,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
@@ -506,8 +509,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Syscall => OpcodeSpec {
|
||||
name: "SYSCALL",
|
||||
imm_bytes: 4,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
@@ -516,8 +519,178 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::Intrinsic => OpcodeSpec {
|
||||
name: "INTRINSIC",
|
||||
imm_bytes: 4,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::DynPack => OpcodeSpec {
|
||||
name: "DYN_PACK",
|
||||
imm_bytes: 4,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::DynUnpack => OpcodeSpec {
|
||||
name: "DYN_UNPACK",
|
||||
imm_bytes: 4,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::DynCanUnpack => OpcodeSpec {
|
||||
name: "DYN_CAN_UNPACK",
|
||||
imm_bytes: 4,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::RefIsExact => OpcodeSpec {
|
||||
name: "REF_IS_EXACT",
|
||||
imm_bytes: 8,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::RefImplements => OpcodeSpec {
|
||||
name: "REF_IMPLEMENTS",
|
||||
imm_bytes: 8,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::RefToTrait => OpcodeSpec {
|
||||
name: "REF_TO_TRAIT",
|
||||
imm_bytes: 8,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::RefCast => OpcodeSpec {
|
||||
name: "REF_CAST",
|
||||
imm_bytes: 8,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::RefIdentityHash => OpcodeSpec {
|
||||
name: "REF_IDENTITY_HASH",
|
||||
imm_bytes: 4,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::RefIdentityEq => OpcodeSpec {
|
||||
name: "REF_IDENTITY_EQ",
|
||||
imm_bytes: 8,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::StructNew => OpcodeSpec {
|
||||
name: "STRUCT_NEW",
|
||||
imm_bytes: 4,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::StructGet => OpcodeSpec {
|
||||
name: "STRUCT_GET",
|
||||
imm_bytes: 8,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::StructSet => OpcodeSpec {
|
||||
name: "STRUCT_SET",
|
||||
imm_bytes: 8,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::ArrayNew => OpcodeSpec {
|
||||
name: "ARRAY_NEW",
|
||||
imm_bytes: 4,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::ArrayLen => OpcodeSpec {
|
||||
name: "ARRAY_LEN",
|
||||
imm_bytes: 4,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::ArrayGet => OpcodeSpec {
|
||||
name: "ARRAY_GET",
|
||||
imm_bytes: 4,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::ArraySet => OpcodeSpec {
|
||||
name: "ARRAY_SET",
|
||||
imm_bytes: 4,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
is_safepoint: false,
|
||||
},
|
||||
OpCode::ArrayCopy => OpcodeSpec {
|
||||
name: "ARRAY_COPY",
|
||||
imm_bytes: 4,
|
||||
pops: None,
|
||||
pushes: None,
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: true,
|
||||
@@ -526,8 +699,8 @@ impl OpCodeSpecExt for OpCode {
|
||||
OpCode::FrameSync => OpcodeSpec {
|
||||
name: "FRAME_SYNC",
|
||||
imm_bytes: 0,
|
||||
pops: 0,
|
||||
pushes: 0,
|
||||
pops: Some(0),
|
||||
pushes: Some(0),
|
||||
is_branch: false,
|
||||
is_terminator: false,
|
||||
may_trap: false,
|
||||
|
||||
@@ -1,43 +1,35 @@
|
||||
/// Resolved execution widths derived from sealed Registry metadata.
|
||||
/// This cache is never serialized as a PBX function signature.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ExecutionFunction {
|
||||
pub code_offset: u32,
|
||||
pub code_len: u32,
|
||||
pub param_slots: u16,
|
||||
pub local_slots: u16,
|
||||
pub return_slots: u16,
|
||||
pub max_stack_slots: u16,
|
||||
}
|
||||
|
||||
use crate::abi::TrapInfo;
|
||||
use crate::model::{BytecodeModule, ConstantPoolEntry, DebugInfo, Export, FunctionMeta};
|
||||
use crate::model::DebugInfo;
|
||||
use crate::value::Value;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Represents a fully linked, executable PBS program image.
|
||||
///
|
||||
/// Under the Prometeu architecture, the ProgramImage is a "closed-world" artifact
|
||||
/// produced by the compiler. All linking, relocation, and symbol resolution
|
||||
/// MUST be performed by the compiler before this image is created.
|
||||
///
|
||||
/// The runtime (VM) assumes this image is authoritative and performs no
|
||||
/// additional linking or fixups.
|
||||
/// Immutable execution payload/cache, produced during sealed image publication.
|
||||
/// This container does not authorize execution. VM sessions require the private
|
||||
/// ValidatedProgramImage factory, including bounded Registry/ISA/native checks.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ProgramImage {
|
||||
pub rom: Arc<[u8]>,
|
||||
pub constant_pool: Arc<[Value]>,
|
||||
pub functions: Arc<[FunctionMeta]>,
|
||||
pub debug_info: Option<DebugInfo>,
|
||||
pub functions: Arc<[ExecutionFunction]>,
|
||||
pub debug_info: Option<Arc<DebugInfo>>,
|
||||
pub exports: Arc<HashMap<String, u32>>,
|
||||
}
|
||||
|
||||
impl ProgramImage {
|
||||
pub fn new(
|
||||
rom: Vec<u8>,
|
||||
constant_pool: Vec<Value>,
|
||||
functions: Vec<FunctionMeta>,
|
||||
debug_info: Option<DebugInfo>,
|
||||
exports: HashMap<String, u32>,
|
||||
) -> Self {
|
||||
Self {
|
||||
rom: Arc::from(rom),
|
||||
constant_pool: Arc::from(constant_pool),
|
||||
functions: Arc::from(functions),
|
||||
debug_info,
|
||||
exports: Arc::new(exports),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_trap(&self, code: u32, opcode: u16, mut message: String, pc: u32) -> TrapInfo {
|
||||
let span = self
|
||||
.debug_info
|
||||
@@ -50,7 +42,7 @@ impl ProgramImage {
|
||||
}
|
||||
}
|
||||
|
||||
TrapInfo { code, opcode, message, pc, span }
|
||||
TrapInfo { code, opcode, message, pc, span, resource: None }
|
||||
}
|
||||
|
||||
pub fn find_function_index(&self, pc: u32) -> Option<usize> {
|
||||
@@ -64,61 +56,3 @@ impl ProgramImage {
|
||||
.map(|(_, name)| name.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<BytecodeModule> for ProgramImage {
|
||||
fn from(module: BytecodeModule) -> Self {
|
||||
let constant_pool: Vec<Value> = module
|
||||
.const_pool
|
||||
.iter()
|
||||
.map(|entry| match entry {
|
||||
ConstantPoolEntry::Null => Value::Null,
|
||||
ConstantPoolEntry::Int64(v) => Value::Int64(*v),
|
||||
ConstantPoolEntry::Float64(v) => Value::Float(*v),
|
||||
ConstantPoolEntry::Boolean(v) => Value::Boolean(*v),
|
||||
ConstantPoolEntry::String(v) => Value::String(v.clone()),
|
||||
ConstantPoolEntry::Int32(v) => Value::Int32(*v),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut exports = HashMap::new();
|
||||
for export in module.exports {
|
||||
exports.insert(export.symbol, export.func_idx);
|
||||
}
|
||||
|
||||
ProgramImage::new(module.code, constant_pool, module.functions, module.debug_info, exports)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ProgramImage> for BytecodeModule {
|
||||
fn from(program: ProgramImage) -> Self {
|
||||
let const_pool = program
|
||||
.constant_pool
|
||||
.iter()
|
||||
.map(|v| match v {
|
||||
Value::Null => ConstantPoolEntry::Null,
|
||||
Value::Int64(v) => ConstantPoolEntry::Int64(*v),
|
||||
Value::Float(v) => ConstantPoolEntry::Float64(*v),
|
||||
Value::Boolean(v) => ConstantPoolEntry::Boolean(*v),
|
||||
Value::String(v) => ConstantPoolEntry::String(v.clone()),
|
||||
Value::Int32(v) => ConstantPoolEntry::Int32(*v),
|
||||
Value::HeapRef(_) => ConstantPoolEntry::Null,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let exports = program
|
||||
.exports
|
||||
.iter()
|
||||
.map(|(symbol, &func_idx)| Export { symbol: symbol.clone(), func_idx })
|
||||
.collect();
|
||||
|
||||
BytecodeModule {
|
||||
version: 0,
|
||||
const_pool,
|
||||
functions: program.functions.as_ref().to_vec(),
|
||||
code: program.rom.as_ref().to_vec(),
|
||||
debug_info: program.debug_info.clone(),
|
||||
exports,
|
||||
syscalls: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,846 @@
|
||||
//! Typed PBX declarations and bounded immutable Registry resolution.
|
||||
//! These declarations do not authorize execution: code and bindings still require verification.
|
||||
use crate::load_limits::IdDomain;
|
||||
use crate::load_limits::{
|
||||
LoadBudget, LoadCode as C, LoadFailure as E, LoadReason as R, LoadResource as Q,
|
||||
};
|
||||
use crate::Value;
|
||||
use std::sync::Arc;
|
||||
|
||||
macro_rules! id {
|
||||
($name:ident) => {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct $name(pub u32);
|
||||
};
|
||||
}
|
||||
id!(TypeId);
|
||||
id!(FunctionId);
|
||||
id!(ImplementationId);
|
||||
id!(BuiltinId);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct NamedType {
|
||||
pub type_id: TypeId,
|
||||
pub name: Option<String>,
|
||||
}
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Signature {
|
||||
pub parameters: Vec<NamedType>,
|
||||
pub results: Vec<TypeId>,
|
||||
}
|
||||
impl Signature {
|
||||
pub fn same_types(&self, other: &Self) -> bool {
|
||||
self.parameters.len() == other.parameters.len()
|
||||
&& self
|
||||
.parameters
|
||||
.iter()
|
||||
.map(|p| p.type_id)
|
||||
.eq(other.parameters.iter().map(|p| p.type_id))
|
||||
&& self.results == other.results
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MethodDecl {
|
||||
pub name: Option<String>,
|
||||
pub signature: Signature,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum TypeKind {
|
||||
Builtin(BuiltinId),
|
||||
Struct(Vec<NamedType>),
|
||||
Array(TypeId),
|
||||
Trait(Vec<MethodDecl>),
|
||||
Fn(Signature),
|
||||
}
|
||||
impl TypeKind {
|
||||
/// Categories supported by identity queries, not by legacy REF_* conversions.
|
||||
pub fn is_identity_reference(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Struct(_)
|
||||
| Self::Array(_)
|
||||
| Self::Fn(_)
|
||||
| Self::Trait(_)
|
||||
| Self::Builtin(BuiltinId::RANDOM)
|
||||
)
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TypeDecl {
|
||||
pub name: Option<String>,
|
||||
pub kind: TypeKind,
|
||||
}
|
||||
/// Runtime-owned roles; frontend names and FunctionIds are independent.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum LifecycleRole {
|
||||
#[default]
|
||||
None = 0,
|
||||
BeforePause = 1,
|
||||
BeforeResume = 2,
|
||||
MemcardBoot = 3,
|
||||
}
|
||||
impl TryFrom<u8> for LifecycleRole {
|
||||
type Error = E;
|
||||
fn try_from(value: u8) -> Result<Self, E> {
|
||||
match value {
|
||||
0 => Ok(Self::None),
|
||||
1 => Ok(Self::BeforePause),
|
||||
2 => Ok(Self::BeforeResume),
|
||||
3 => Ok(Self::MemcardBoot),
|
||||
_ => Err(E::new(C::InvalidRegistry, R::LifecycleRole)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct FunctionDecl {
|
||||
pub lifecycle_role: LifecycleRole,
|
||||
pub name: Option<String>,
|
||||
pub signature: Signature,
|
||||
pub code_offset: u32,
|
||||
pub code_len: u32,
|
||||
pub local_slots: u32,
|
||||
pub max_stack_slots: u32,
|
||||
/// Ordered logical capture groups, encoded in the separate PBX section 8.
|
||||
pub captures: Vec<TypeId>,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ImplementationDecl {
|
||||
pub owner: TypeId,
|
||||
pub trait_id: TypeId,
|
||||
pub methods: Vec<FunctionId>,
|
||||
}
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RegistryDeclarations {
|
||||
pub types: Vec<TypeDecl>,
|
||||
pub functions: Vec<FunctionDecl>,
|
||||
pub implementations: Vec<ImplementationDecl>,
|
||||
}
|
||||
|
||||
pub type StringSlot = Option<Arc<str>>;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DynamicSlot {
|
||||
pub type_id: Option<TypeId>,
|
||||
pub payload: Value,
|
||||
}
|
||||
impl Default for DynamicSlot {
|
||||
fn default() -> Self {
|
||||
Self { type_id: None, payload: Value::Null }
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DefaultKind {
|
||||
Int32,
|
||||
Int64,
|
||||
Float,
|
||||
Bool,
|
||||
Null,
|
||||
Vec2,
|
||||
Pixel,
|
||||
Trait,
|
||||
Dynamic,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Ownership {
|
||||
Plain,
|
||||
GuestReference,
|
||||
NativeString,
|
||||
TraitReceiver,
|
||||
Dynamic,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StorageLayout {
|
||||
pub size: usize,
|
||||
pub alignment: usize,
|
||||
pub slots: u32,
|
||||
pub ownership: Ownership,
|
||||
pub default: DefaultKind,
|
||||
}
|
||||
impl StorageLayout {
|
||||
fn new(
|
||||
size: usize,
|
||||
alignment: usize,
|
||||
slots: u32,
|
||||
ownership: Ownership,
|
||||
default: DefaultKind,
|
||||
) -> Self {
|
||||
Self { size, alignment, slots, ownership, default }
|
||||
}
|
||||
pub fn nullable(self) -> bool {
|
||||
!matches!(self.ownership, Ownership::Plain)
|
||||
}
|
||||
/// Canonical stack-side defaults, with no allocation or source constructor.
|
||||
/// Native typed storage still requires its own initialized-slot construction.
|
||||
pub fn default_values(self) -> &'static [Value] {
|
||||
match self.default {
|
||||
DefaultKind::Int32 => &[Value::Int32(0)],
|
||||
DefaultKind::Int64 => &[Value::Int64(0)],
|
||||
DefaultKind::Float => &[Value::Float(0.0)],
|
||||
DefaultKind::Bool => &[Value::Boolean(false)],
|
||||
DefaultKind::Null => &[Value::Null],
|
||||
DefaultKind::Vec2 => &[Value::Float(0.0), Value::Float(0.0)],
|
||||
DefaultKind::Pixel => &[Value::Int64(0), Value::Int64(0), Value::Int64(0)],
|
||||
DefaultKind::Trait | DefaultKind::Dynamic => &[Value::Null, Value::Null],
|
||||
}
|
||||
}
|
||||
}
|
||||
impl BuiltinId {
|
||||
pub const COLOR: Self = Self(1);
|
||||
pub const VEC2: Self = Self(2);
|
||||
pub const PIXEL: Self = Self(3);
|
||||
pub const INT32: Self = Self(0x10);
|
||||
pub const INT64: Self = Self(0x11);
|
||||
pub const FLOAT: Self = Self(0x12);
|
||||
pub const BOOL: Self = Self(0x13);
|
||||
pub const STRING: Self = Self(0x14);
|
||||
pub const DYNAMIC: Self = Self(0x15);
|
||||
pub const RANDOM: Self = Self(0x16);
|
||||
pub fn layout(self) -> Result<StorageLayout, E> {
|
||||
use DefaultKind as D;
|
||||
use Ownership as O;
|
||||
let (size, alignment, slots, ownership, default) = match self {
|
||||
Self::COLOR => (4, 4, 1, O::Plain, D::Int64),
|
||||
Self::VEC2 => (16, 8, 2, O::Plain, D::Vec2),
|
||||
Self::PIXEL => (24, 8, 3, O::Plain, D::Pixel),
|
||||
Self::INT32 => (4, 4, 1, O::Plain, D::Int32),
|
||||
Self::INT64 => (8, 8, 1, O::Plain, D::Int64),
|
||||
Self::FLOAT => (8, 8, 1, O::Plain, D::Float),
|
||||
Self::BOOL => (1, 1, 1, O::Plain, D::Bool),
|
||||
Self::RANDOM => (8, 8, 1, O::GuestReference, D::Null),
|
||||
Self::STRING => {
|
||||
(size_of::<StringSlot>(), align_of::<StringSlot>(), 1, O::NativeString, D::Null)
|
||||
}
|
||||
Self::DYNAMIC => {
|
||||
(size_of::<DynamicSlot>(), align_of::<DynamicSlot>(), 2, O::Dynamic, D::Dynamic)
|
||||
}
|
||||
_ => return Err(E::new(C::UnsupportedFormat, R::Builtin)),
|
||||
};
|
||||
Ok(StorageLayout::new(size, alignment, slots, ownership, default))
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct FieldLayout {
|
||||
pub type_id: TypeId,
|
||||
pub offset: usize,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct OwnedField {
|
||||
pub offset: usize,
|
||||
pub ownership: Ownership,
|
||||
}
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct StructLayout {
|
||||
/// Sum of execution-slot widths, resolved once for deterministic NEW charging.
|
||||
pub initialization_slots: u64,
|
||||
pub size: usize,
|
||||
pub alignment: usize,
|
||||
pub fields: Vec<FieldLayout>,
|
||||
/// Sorted offsets for fields requiring guest tracing or native ownership handling.
|
||||
pub owned_fields: Vec<OwnedField>,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ArrayLayout {
|
||||
pub element_type_id: TypeId,
|
||||
pub stride: usize,
|
||||
pub element_alignment: usize,
|
||||
}
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct TypeLayout {
|
||||
pub storage: StorageLayout,
|
||||
pub instance: Option<StructLayout>,
|
||||
pub array: Option<ArrayLayout>,
|
||||
pub callable: Option<FunctionLayout>,
|
||||
pub methods: Vec<FunctionLayout>,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct CaptureLayout {
|
||||
pub type_id: TypeId,
|
||||
pub slot_offset: u32,
|
||||
pub slots: u32,
|
||||
}
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct FunctionLayout {
|
||||
pub parameter_slots: u32,
|
||||
pub result_slots: u32,
|
||||
pub capture_slots: u32,
|
||||
pub captures: Vec<CaptureLayout>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Registry {
|
||||
lifecycle_hooks: [Option<FunctionId>; 3],
|
||||
declarations: RegistryDeclarations,
|
||||
layouts: Vec<TypeLayout>,
|
||||
functions: Vec<FunctionLayout>,
|
||||
// Sorted by owner/trait; original implementation IDs are never remapped.
|
||||
implementations: Vec<(TypeId, TypeId, ImplementationId)>,
|
||||
}
|
||||
impl Registry {
|
||||
pub fn lifecycle_hook(&self, role: LifecycleRole) -> Option<FunctionId> {
|
||||
match role {
|
||||
LifecycleRole::None => None,
|
||||
LifecycleRole::BeforePause => self.lifecycle_hooks[0],
|
||||
LifecycleRole::BeforeResume => self.lifecycle_hooks[1],
|
||||
LifecycleRole::MemcardBoot => self.lifecycle_hooks[2],
|
||||
}
|
||||
}
|
||||
pub fn declarations(&self) -> &RegistryDeclarations {
|
||||
&self.declarations
|
||||
}
|
||||
pub fn type_layout(&self, id: TypeId) -> Option<&TypeLayout> {
|
||||
self.layouts.get(id.0 as usize)
|
||||
}
|
||||
pub fn function_layout(&self, id: FunctionId) -> Option<&FunctionLayout> {
|
||||
self.functions.get(id.0 as usize)
|
||||
}
|
||||
pub fn implementation(&self, owner: TypeId, trait_id: TypeId) -> Option<ImplementationId> {
|
||||
self.implementations
|
||||
.binary_search_by_key(&(owner, trait_id), |&(a, b, _)| (a, b))
|
||||
.ok()
|
||||
.map(|i| self.implementations[i].2)
|
||||
}
|
||||
/// Resolves declarations, not code/bindings. The caller must still verify before publication.
|
||||
/// Declaration allocations are retained and charged here, even for non-PBX producers.
|
||||
pub fn resolve(
|
||||
declarations: RegistryDeclarations,
|
||||
code_len: usize,
|
||||
budget: &mut LoadBudget,
|
||||
) -> Result<Self, E> {
|
||||
budget.transaction(|budget| Self::resolve_inner(declarations, code_len, budget))
|
||||
}
|
||||
fn resolve_inner(
|
||||
d: RegistryDeclarations,
|
||||
code_len: usize,
|
||||
b: &mut LoadBudget,
|
||||
) -> Result<Self, E> {
|
||||
b.check(Q::Types, d.types.len() as u64)?;
|
||||
b.check(Q::Functions, d.functions.len() as u64)?;
|
||||
b.check(Q::Implementations, d.implementations.len() as u64)?;
|
||||
b.check(Q::CodeBytes, code_len as u64)?;
|
||||
charge_declarations(&d, b)?;
|
||||
validate_declarations(&d, b)?;
|
||||
let mut layouts = b.vector(d.types.len(), Q::RegistryBytes)?;
|
||||
for (i, t) in d.types.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
let storage = match t.kind {
|
||||
TypeKind::Builtin(id) => id.layout().map_err(|e| e.record(i as u32))?,
|
||||
TypeKind::Trait(_) => {
|
||||
StorageLayout::new(16, 8, 2, Ownership::TraitReceiver, DefaultKind::Trait)
|
||||
}
|
||||
_ => StorageLayout::new(8, 8, 1, Ownership::GuestReference, DefaultKind::Null),
|
||||
};
|
||||
layouts.push(TypeLayout {
|
||||
storage,
|
||||
instance: None,
|
||||
array: None,
|
||||
callable: None,
|
||||
methods: Vec::new(),
|
||||
});
|
||||
}
|
||||
for (i, t) in d.types.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
if let TypeKind::Fn(s) = &t.kind {
|
||||
layouts[i].callable = Some(resolve_signature(s, &layouts, b)?);
|
||||
}
|
||||
if let TypeKind::Trait(methods) = &t.kind {
|
||||
let mut resolved = b.vector(methods.len(), Q::RegistryBytes)?;
|
||||
for method in methods {
|
||||
b.work(1)?;
|
||||
resolved.push(resolve_signature(&method.signature, &layouts, b)?);
|
||||
}
|
||||
layouts[i].methods = resolved;
|
||||
}
|
||||
if let TypeKind::Array(element_type_id) = t.kind {
|
||||
let element = layouts[element_type_id.0 as usize].storage;
|
||||
layouts[i].array = Some(ArrayLayout {
|
||||
element_type_id,
|
||||
stride: align(element.size, element.alignment)?,
|
||||
element_alignment: element.alignment,
|
||||
});
|
||||
}
|
||||
if let TypeKind::Struct(fields) = &t.kind {
|
||||
let mut offsets = b.vector(fields.len(), Q::RegistryBytes)?;
|
||||
b.work(fields.len())?;
|
||||
let owned_count = fields
|
||||
.iter()
|
||||
.filter(|f| layouts[f.type_id.0 as usize].storage.ownership != Ownership::Plain)
|
||||
.count();
|
||||
let mut owned = b.vector(owned_count, Q::RegistryBytes)?;
|
||||
let (mut size, mut alignment) = (0, 1);
|
||||
let mut initialization_slots = 0u64;
|
||||
for field in fields {
|
||||
b.work(1)?;
|
||||
let layout = layouts[field.type_id.0 as usize].storage;
|
||||
initialization_slots = initialization_slots
|
||||
.checked_add(u64::from(layout.slots))
|
||||
.ok_or_else(overflow)?;
|
||||
size = align(size, layout.alignment)?;
|
||||
offsets.push(FieldLayout { type_id: field.type_id, offset: size });
|
||||
if layout.ownership != Ownership::Plain {
|
||||
owned.push(OwnedField { offset: size, ownership: layout.ownership });
|
||||
}
|
||||
size = size.checked_add(layout.size).ok_or_else(overflow)?;
|
||||
alignment = alignment.max(layout.alignment);
|
||||
}
|
||||
layouts[i].instance = Some(StructLayout {
|
||||
initialization_slots,
|
||||
size: align(size, alignment)?,
|
||||
alignment,
|
||||
fields: offsets,
|
||||
owned_fields: owned,
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut lifecycle_hooks = [None; 3];
|
||||
let mut functions = b.vector(d.functions.len(), Q::RegistryBytes)?;
|
||||
let mut ranges = b.vector(d.functions.len(), Q::TemporaryBytes)?;
|
||||
for (i, f) in d.functions.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
if f.lifecycle_role != LifecycleRole::None {
|
||||
let signature_valid = if f.lifecycle_role == LifecycleRole::MemcardBoot {
|
||||
f.signature.parameters.len() == 1
|
||||
&& f.signature.results.len() == 1
|
||||
&& d.types
|
||||
.get(f.signature.parameters[0].type_id.0 as usize)
|
||||
.is_some_and(|t| t.kind == TypeKind::Builtin(BuiltinId::INT64))
|
||||
&& d.types
|
||||
.get(f.signature.results[0].0 as usize)
|
||||
.is_some_and(|t| t.kind == TypeKind::Builtin(BuiltinId::INT32))
|
||||
} else {
|
||||
f.signature.parameters.is_empty() && f.signature.results.is_empty()
|
||||
};
|
||||
let invalid = i == 0 || !signature_valid || !f.captures.is_empty();
|
||||
if invalid {
|
||||
return Err(E::new(C::InvalidEntrypoint, R::LifecycleSignature)
|
||||
.in_section(1)
|
||||
.record(i as u32)
|
||||
.in_function(i as u32, None));
|
||||
}
|
||||
let slot = &mut lifecycle_hooks[f.lifecycle_role as usize - 1];
|
||||
if slot.replace(FunctionId(i as u32)).is_some() {
|
||||
return Err(E::new(C::InvalidRegistry, R::DuplicateLifecycleRole)
|
||||
.in_section(1)
|
||||
.record(i as u32)
|
||||
.in_function(i as u32, None));
|
||||
}
|
||||
}
|
||||
|
||||
let params = width(f.signature.parameters.iter().map(|p| p.type_id), &layouts, b)?;
|
||||
let results = width(f.signature.results.iter().copied(), &layouts, b)?;
|
||||
let frame = u64::from(params) + u64::from(f.local_slots) + u64::from(f.max_stack_slots);
|
||||
if frame > b.frame_limit() {
|
||||
return Err(E::new(C::InvalidCode, R::FrameSlots)
|
||||
.in_section(1)
|
||||
.record(i as u32)
|
||||
.in_function(i as u32, None));
|
||||
}
|
||||
if u64::from(results) > b.result_limit() {
|
||||
return Err(E::new(C::InvalidCode, R::ReturnSlots)
|
||||
.in_section(1)
|
||||
.record(i as u32)
|
||||
.in_function(i as u32, None));
|
||||
}
|
||||
let end = f.code_offset.checked_add(f.code_len).ok_or_else(|| {
|
||||
E::new(C::InvalidCode, R::CodeRange)
|
||||
.in_section(1)
|
||||
.record(i as u32)
|
||||
.in_function(i as u32, Some(f.code_offset))
|
||||
})?;
|
||||
if end as usize > code_len || f.code_len == 0 {
|
||||
return Err(E::new(C::InvalidCode, R::CodeRange)
|
||||
.in_section(1)
|
||||
.record(i as u32)
|
||||
.in_function(i as u32, Some(f.code_offset)));
|
||||
}
|
||||
ranges.push((f.code_offset, end, i as u32));
|
||||
let mut captures = b.vector(f.captures.len(), Q::RegistryBytes)?;
|
||||
let mut capture_slots = 0u32;
|
||||
for &type_id in &f.captures {
|
||||
b.work(1)?;
|
||||
let slots = layouts[type_id.0 as usize].storage.slots;
|
||||
captures.push(CaptureLayout { type_id, slot_offset: capture_slots, slots });
|
||||
capture_slots = capture_slots.checked_add(slots).ok_or_else(overflow)?;
|
||||
}
|
||||
functions.push(FunctionLayout {
|
||||
parameter_slots: params,
|
||||
result_slots: results,
|
||||
capture_slots,
|
||||
captures,
|
||||
});
|
||||
}
|
||||
sort_work(ranges.len(), b)?;
|
||||
ranges.sort_unstable();
|
||||
for pair in ranges.windows(2) {
|
||||
b.work(1)?;
|
||||
if pair[0].1 > pair[1].0 {
|
||||
return Err(E::new(C::InvalidCode, R::CodeRange).record(pair[1].2));
|
||||
}
|
||||
}
|
||||
b.refund(Q::TemporaryBytes, (ranges.capacity() * size_of::<(u32, u32, u32)>()) as u64);
|
||||
drop(ranges);
|
||||
let mut implementations = b.vector(d.implementations.len(), Q::RegistryBytes)?;
|
||||
for (i, imp) in d.implementations.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
if !matches!(d.types[imp.owner.0 as usize].kind, TypeKind::Struct(_)) {
|
||||
return Err(E::new(C::InvalidReference, R::OwnerCategory)
|
||||
.in_section(7)
|
||||
.record(i as u32)
|
||||
.reference(IdDomain::Type, imp.owner.0));
|
||||
}
|
||||
let TypeKind::Trait(methods) = &d.types[imp.trait_id.0 as usize].kind else {
|
||||
return Err(E::new(C::InvalidReference, R::TraitCategory)
|
||||
.in_section(7)
|
||||
.record(i as u32)
|
||||
.reference(IdDomain::Type, imp.trait_id.0));
|
||||
};
|
||||
if methods.len() != imp.methods.len() {
|
||||
return Err(E::new(C::InvalidRegistry, R::MethodCount)
|
||||
.in_section(7)
|
||||
.record(i as u32));
|
||||
}
|
||||
for (j, (method, id)) in methods.iter().zip(&imp.methods).enumerate() {
|
||||
let signature = &d.functions[id.0 as usize].signature;
|
||||
if !d.functions[id.0 as usize].captures.is_empty() {
|
||||
return Err(E::new(C::InvalidRegistry, R::CapturedDirectCall)
|
||||
.in_section(7)
|
||||
.record(i as u32)
|
||||
.member(j as u32));
|
||||
}
|
||||
b.work(signature.parameters.len() + signature.results.len() + 1)?;
|
||||
if signature.parameters.first().map(|p| p.type_id) != Some(imp.owner)
|
||||
|| signature.parameters.len() != method.signature.parameters.len() + 1
|
||||
|| !signature.parameters.iter().skip(1).map(|p| p.type_id).eq(method
|
||||
.signature
|
||||
.parameters
|
||||
.iter()
|
||||
.map(|p| p.type_id))
|
||||
|| signature.results != method.signature.results
|
||||
{
|
||||
return Err(E::new(C::InvalidRegistry, R::Signature)
|
||||
.in_section(7)
|
||||
.record(i as u32)
|
||||
.member(j as u32));
|
||||
}
|
||||
}
|
||||
implementations.push((imp.owner, imp.trait_id, ImplementationId(i as u32)));
|
||||
}
|
||||
sort_work(implementations.len(), b)?;
|
||||
implementations.sort_unstable();
|
||||
for pair in implementations.windows(2) {
|
||||
b.work(1)?;
|
||||
if (pair[0].0, pair[0].1) == (pair[1].0, pair[1].1) {
|
||||
return Err(E::new(C::InvalidRegistry, R::DuplicateImplementation)
|
||||
.in_section(7)
|
||||
.record(pair[1].2 .0));
|
||||
}
|
||||
}
|
||||
Ok(Self { lifecycle_hooks, declarations: d, layouts, functions, implementations })
|
||||
}
|
||||
}
|
||||
fn overflow() -> E {
|
||||
E::new(C::ResourceLimit, R::Overflow)
|
||||
}
|
||||
fn resolve_signature(
|
||||
s: &Signature,
|
||||
layouts: &[TypeLayout],
|
||||
b: &mut LoadBudget,
|
||||
) -> Result<FunctionLayout, E> {
|
||||
let parameter_slots = width(s.parameters.iter().map(|p| p.type_id), layouts, b)?;
|
||||
let result_slots = width(s.results.iter().copied(), layouts, b)?;
|
||||
if u64::from(parameter_slots) > b.frame_limit() {
|
||||
return Err(E::new(C::InvalidRegistry, R::FrameSlots));
|
||||
}
|
||||
if u64::from(result_slots) > b.result_limit() {
|
||||
return Err(E::new(C::InvalidRegistry, R::ReturnSlots));
|
||||
}
|
||||
Ok(FunctionLayout { parameter_slots, result_slots, capture_slots: 0, captures: Vec::new() })
|
||||
}
|
||||
fn align(n: usize, a: usize) -> Result<usize, E> {
|
||||
n.checked_add(a - 1).map(|v| v & !(a - 1)).ok_or_else(overflow)
|
||||
}
|
||||
fn width(
|
||||
ids: impl Iterator<Item = TypeId>,
|
||||
layouts: &[TypeLayout],
|
||||
b: &mut LoadBudget,
|
||||
) -> Result<u32, E> {
|
||||
let mut sum = 0u32;
|
||||
for id in ids {
|
||||
b.work(1)?;
|
||||
sum = sum.checked_add(layouts[id.0 as usize].storage.slots).ok_or_else(overflow)?;
|
||||
}
|
||||
Ok(sum)
|
||||
}
|
||||
fn sort_work(n: usize, b: &mut LoadBudget) -> Result<(), E> {
|
||||
let bits = usize::BITS - n.leading_zeros();
|
||||
b.work(n.checked_mul(bits as usize + 1).ok_or_else(overflow)?)
|
||||
}
|
||||
fn type_ref(id: TypeId, d: &RegistryDeclarations) -> Result<(), E> {
|
||||
if (id.0 as usize) < d.types.len() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(E::new(C::InvalidReference, R::TypeId).reference(IdDomain::Type, id.0))
|
||||
}
|
||||
}
|
||||
fn name(name: &Option<String>, b: &mut LoadBudget) -> Result<(), E> {
|
||||
if let Some(name) = name {
|
||||
if name.len() as u64 > b.individual_name_limit() {
|
||||
return Err(E::resource(Q::NameBytes, name.len() as u64, b.individual_name_limit()));
|
||||
}
|
||||
b.charge(Q::NameBytes, name.len() as u64)?;
|
||||
b.work(name.len())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn named(items: &[NamedType], d: &RegistryDeclarations, b: &mut LoadBudget) -> Result<(), E> {
|
||||
b.charge(Q::NestedRecords, items.len() as u64)?;
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
type_ref(item.type_id, d).map_err(|e| e.member(i as u32))?;
|
||||
name(&item.name, b)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn signature(s: &Signature, d: &RegistryDeclarations, b: &mut LoadBudget) -> Result<(), E> {
|
||||
named(&s.parameters, d, b)?;
|
||||
b.charge(Q::NestedRecords, s.results.len() as u64)?;
|
||||
for (i, id) in s.results.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
type_ref(*id, d).map_err(|e| e.member(i as u32))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn signature_order(
|
||||
a: &Signature,
|
||||
b: &Signature,
|
||||
budget: &mut LoadBudget,
|
||||
) -> Result<std::cmp::Ordering, E> {
|
||||
use std::cmp::Ordering;
|
||||
for (a, b) in a.parameters.iter().zip(&b.parameters) {
|
||||
budget.work(1)?;
|
||||
let order = a.type_id.cmp(&b.type_id);
|
||||
if order != Ordering::Equal {
|
||||
return Ok(order);
|
||||
}
|
||||
}
|
||||
budget.work(1)?;
|
||||
let order = a.parameters.len().cmp(&b.parameters.len());
|
||||
if order != Ordering::Equal {
|
||||
return Ok(order);
|
||||
}
|
||||
for (a, b) in a.results.iter().zip(&b.results) {
|
||||
budget.work(1)?;
|
||||
let order = a.cmp(b);
|
||||
if order != Ordering::Equal {
|
||||
return Ok(order);
|
||||
}
|
||||
}
|
||||
budget.work(1)?;
|
||||
Ok(a.results.len().cmp(&b.results.len()))
|
||||
}
|
||||
/// Validate all edges before indexed layout resolution; IDs remain table positions.
|
||||
pub(crate) fn validate_declarations(d: &RegistryDeclarations, b: &mut LoadBudget) -> Result<(), E> {
|
||||
b.charge(Q::Types, d.types.len() as u64)?;
|
||||
b.charge(Q::Functions, d.functions.len() as u64)?;
|
||||
b.charge(Q::Implementations, d.implementations.len() as u64)?;
|
||||
let mut constructors = b.vector(d.types.len(), Q::TemporaryBytes)?;
|
||||
for (i, t) in d.types.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
name(&t.name, b).map_err(|e| e.in_section(6).record(i as u32))?;
|
||||
let result = (|| match &t.kind {
|
||||
TypeKind::Builtin(id) => {
|
||||
id.layout()?;
|
||||
constructors.push((0, id.0, i as u32));
|
||||
Ok(())
|
||||
}
|
||||
TypeKind::Array(id) => {
|
||||
type_ref(*id, d)?;
|
||||
constructors.push((1, id.0, i as u32));
|
||||
Ok(())
|
||||
}
|
||||
TypeKind::Struct(fields) => named(fields, d, b),
|
||||
TypeKind::Fn(s) => signature(s, d, b),
|
||||
TypeKind::Trait(methods) => {
|
||||
b.charge(Q::NestedRecords, methods.len() as u64)?;
|
||||
for m in methods {
|
||||
b.work(1)?;
|
||||
name(&m.name, b)?;
|
||||
signature(&m.signature, d, b)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
})();
|
||||
result.map_err(|e| e.in_section(6).record(i as u32))?;
|
||||
}
|
||||
sort_work(constructors.len(), b)?;
|
||||
constructors.sort_unstable();
|
||||
for pair in constructors.windows(2) {
|
||||
b.work(1)?;
|
||||
if (pair[0].0, pair[0].1) == (pair[1].0, pair[1].1) {
|
||||
return Err(E::new(
|
||||
C::InvalidRegistry,
|
||||
if pair[1].0 == 0 { R::DuplicateBuiltin } else { R::DuplicateArray },
|
||||
)
|
||||
.record(pair[1].2));
|
||||
}
|
||||
}
|
||||
b.refund(Q::TemporaryBytes, (constructors.capacity() * size_of::<(i32, u32, u32)>()) as u64);
|
||||
drop(constructors);
|
||||
// Sorted Fn indices use fallible, metered comparisons; names are never keys.
|
||||
let mut fns = b.vector::<usize>(d.types.len(), Q::TemporaryBytes)?;
|
||||
for (id, t) in d.types.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
let TypeKind::Fn(key) = &t.kind else { continue };
|
||||
let (mut lo, mut hi) = (0, fns.len());
|
||||
while lo < hi {
|
||||
let mid = lo + (hi - lo) / 2;
|
||||
let TypeKind::Fn(other) = &d.types[fns[mid]].kind else { unreachable!() };
|
||||
match signature_order(key, other, b)? {
|
||||
std::cmp::Ordering::Equal => {
|
||||
return Err(E::new(C::InvalidRegistry, R::DuplicateFn)
|
||||
.in_section(6)
|
||||
.record(id as u32))
|
||||
}
|
||||
std::cmp::Ordering::Less => hi = mid,
|
||||
std::cmp::Ordering::Greater => lo = mid + 1,
|
||||
}
|
||||
}
|
||||
b.work(fns.len() - lo + 1)?;
|
||||
fns.insert(lo, id);
|
||||
}
|
||||
b.refund(Q::TemporaryBytes, (fns.capacity() * size_of::<usize>()) as u64);
|
||||
drop(fns);
|
||||
// Iterative DFS processes each structural edge once; nominal nodes are leaves.
|
||||
let mut colors = b.vector::<u8>(d.types.len(), Q::TemporaryBytes)?;
|
||||
b.work(d.types.len())?;
|
||||
colors.resize(d.types.len(), 0);
|
||||
let mut walk = b.vector::<(usize, usize)>(d.types.len(), Q::TemporaryBytes)?;
|
||||
for start in 0..d.types.len() {
|
||||
b.work(1)?;
|
||||
if colors[start] != 0 {
|
||||
continue;
|
||||
}
|
||||
colors[start] = 1;
|
||||
walk.push((start, 0));
|
||||
while let Some((node, edge)) = walk.last_mut() {
|
||||
b.work(1)?;
|
||||
let next = match &d.types[*node].kind {
|
||||
TypeKind::Array(id) if *edge == 0 => Some(*id),
|
||||
TypeKind::Fn(s) => s.parameters.get(*edge).map(|p| p.type_id).or_else(|| {
|
||||
edge.checked_sub(s.parameters.len()).and_then(|e| s.results.get(e)).copied()
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
*edge += 1;
|
||||
if let Some(id) = next {
|
||||
let id = id.0 as usize;
|
||||
if colors[id] == 1 {
|
||||
b.work(walk.len())?;
|
||||
let reason =
|
||||
if walk.iter().any(|(n, _)| matches!(d.types[*n].kind, TypeKind::Fn(_))) {
|
||||
R::StructuralTypeCycle
|
||||
} else {
|
||||
R::ArrayCycle
|
||||
};
|
||||
return Err(E::new(C::InvalidRegistry, reason).in_section(6).record(id as u32));
|
||||
}
|
||||
if colors[id] == 0 {
|
||||
colors[id] = 1;
|
||||
walk.push((id, 0));
|
||||
}
|
||||
} else {
|
||||
colors[*node] = 2;
|
||||
walk.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
b.refund(Q::TemporaryBytes, colors.capacity() as u64);
|
||||
b.refund(Q::TemporaryBytes, (walk.capacity() * size_of::<(usize, usize)>()) as u64);
|
||||
drop(colors);
|
||||
drop(walk);
|
||||
for (i, f) in d.functions.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
name(&f.name, b).map_err(|e| e.in_section(1).record(i as u32))?;
|
||||
signature(&f.signature, d, b).map_err(|e| e.in_section(1).record(i as u32))?;
|
||||
b.charge(Q::NestedRecords, f.captures.len() as u64)?;
|
||||
for (j, &id) in f.captures.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
type_ref(id, d).map_err(|e| e.in_section(8).record(i as u32).member(j as u32))?;
|
||||
}
|
||||
}
|
||||
for (i, imp) in d.implementations.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
type_ref(imp.owner, d).map_err(|e| e.in_section(7).record(i as u32))?;
|
||||
type_ref(imp.trait_id, d).map_err(|e| e.in_section(7).record(i as u32))?;
|
||||
b.charge(Q::NestedRecords, imp.methods.len() as u64)?;
|
||||
for (j, id) in imp.methods.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
if id.0 as usize >= d.functions.len() {
|
||||
return Err(E::new(C::InvalidReference, R::FunctionId)
|
||||
.in_section(7)
|
||||
.reference(IdDomain::Function, id.0)
|
||||
.record(i as u32)
|
||||
.member(j as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn charge_vec<T>(v: &Vec<T>, b: &mut LoadBudget) -> Result<(), E> {
|
||||
b.charge(
|
||||
Q::RegistryBytes,
|
||||
(v.capacity() as u64).checked_mul(size_of::<T>() as u64).ok_or_else(overflow)?,
|
||||
)
|
||||
}
|
||||
fn charge_name(n: &Option<String>, b: &mut LoadBudget) -> Result<(), E> {
|
||||
if let Some(n) = n {
|
||||
b.charge(Q::RegistryBytes, n.capacity() as u64)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn charge_named(v: &Vec<NamedType>, b: &mut LoadBudget) -> Result<(), E> {
|
||||
charge_vec(v, b)?;
|
||||
for p in v {
|
||||
b.work(1)?;
|
||||
charge_name(&p.name, b)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn charge_signature(s: &Signature, b: &mut LoadBudget) -> Result<(), E> {
|
||||
charge_named(&s.parameters, b)?;
|
||||
charge_vec(&s.results, b)
|
||||
}
|
||||
fn charge_declarations(d: &RegistryDeclarations, b: &mut LoadBudget) -> Result<(), E> {
|
||||
b.charge(Q::RegistryBytes, size_of::<Registry>() as u64)?;
|
||||
charge_vec(&d.types, b)?;
|
||||
charge_vec(&d.functions, b)?;
|
||||
charge_vec(&d.implementations, b)?;
|
||||
for t in &d.types {
|
||||
b.work(1)?;
|
||||
charge_name(&t.name, b)?;
|
||||
match &t.kind {
|
||||
TypeKind::Struct(fields) => charge_named(fields, b)?,
|
||||
TypeKind::Fn(s) => charge_signature(s, b)?,
|
||||
TypeKind::Trait(methods) => {
|
||||
charge_vec(methods, b)?;
|
||||
for m in methods {
|
||||
b.work(1)?;
|
||||
charge_name(&m.name, b)?;
|
||||
charge_signature(&m.signature, b)?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for f in &d.functions {
|
||||
b.work(1)?;
|
||||
charge_name(&f.name, b)?;
|
||||
charge_signature(&f.signature, b)?;
|
||||
charge_vec(&f.captures, b)?;
|
||||
}
|
||||
for imp in &d.implementations {
|
||||
b.work(1)?;
|
||||
charge_vec(&imp.methods, b)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,515 @@
|
||||
//! Strict PBX v0 envelope and Registry sections. No legacy fallback.
|
||||
//! Envelope parsing is structural only: non-Registry sections and instructions
|
||||
//! must be validated by their consumers before an executable image is published.
|
||||
use crate::load_limits::{
|
||||
LoadBudget, LoadCode as C, LoadFailure as E, LoadReason as R, LoadResource as Q,
|
||||
};
|
||||
use crate::registry::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Section<'a> {
|
||||
pub kind: u32,
|
||||
pub offset: usize,
|
||||
pub bytes: &'a [u8],
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct PbxEnvelope<'a> {
|
||||
sections: [Option<Section<'a>>; 9],
|
||||
}
|
||||
impl<'a> PbxEnvelope<'a> {
|
||||
pub fn section(&self, kind: u32) -> Option<Section<'a>> {
|
||||
self.sections.get(kind as usize).copied().flatten()
|
||||
}
|
||||
pub fn parse(bytes: &'a [u8], b: &mut LoadBudget) -> Result<Self, E> {
|
||||
b.transaction(|b| Self::parse_inner(bytes, b))
|
||||
}
|
||||
fn parse_inner(bytes: &'a [u8], b: &mut LoadBudget) -> Result<Self, E> {
|
||||
b.check(Q::PbxBytes, bytes.len() as u64)?;
|
||||
if bytes.len() < 32 {
|
||||
return Err(E::new(C::InvalidFormat, R::Truncated));
|
||||
}
|
||||
b.work(32)?;
|
||||
if &bytes[..4] != b"PBX\0" {
|
||||
return Err(E::new(C::InvalidFormat, R::Magic));
|
||||
}
|
||||
if bytes[4..6] != [0, 0] {
|
||||
return Err(E::new(C::UnsupportedFormat, R::Version));
|
||||
}
|
||||
if bytes[6] != 0 {
|
||||
return Err(E::new(C::InvalidFormat, R::Endianness));
|
||||
}
|
||||
if bytes[7] != 0 || bytes[12..32].iter().any(|&x| x != 0) {
|
||||
return Err(E::new(C::InvalidFormat, R::Reserved));
|
||||
}
|
||||
let count = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize;
|
||||
let directory_end =
|
||||
count.checked_mul(12).and_then(|n| n.checked_add(32)).ok_or_else(overflow)?;
|
||||
if directory_end > bytes.len() {
|
||||
return Err(E::new(C::InvalidFormat, R::Truncated));
|
||||
}
|
||||
let mut result = Self { sections: [None; 9] };
|
||||
for i in 0..count {
|
||||
b.work(13)?;
|
||||
let pos = 32 + i * 12;
|
||||
let kind = u32::from_le_bytes(bytes[pos..pos + 4].try_into().unwrap());
|
||||
if kind > 8 {
|
||||
return Err(E::new(C::UnsupportedFormat, R::SectionKind).at(kind, pos));
|
||||
}
|
||||
if result.sections[kind as usize].is_some() {
|
||||
return Err(E::new(C::InvalidFormat, R::DuplicateSection).at(kind, pos));
|
||||
}
|
||||
let start = u32::from_le_bytes(bytes[pos + 4..pos + 8].try_into().unwrap()) as usize;
|
||||
let len = u32::from_le_bytes(bytes[pos + 8..pos + 12].try_into().unwrap()) as usize;
|
||||
let end = start.checked_add(len).ok_or_else(overflow)?;
|
||||
if end > bytes.len() {
|
||||
return Err(E::new(C::InvalidFormat, R::Truncated).at(kind, start));
|
||||
}
|
||||
if start < directory_end {
|
||||
return Err(E::new(C::InvalidFormat, R::Overlap).at(kind, start));
|
||||
}
|
||||
if kind == 2 {
|
||||
b.check(Q::CodeBytes, len as u64)?;
|
||||
}
|
||||
for other in result.sections.iter().flatten() {
|
||||
b.work(1)?;
|
||||
if len > 0
|
||||
&& !other.bytes.is_empty()
|
||||
&& start < other.offset + other.bytes.len()
|
||||
&& other.offset < end
|
||||
{
|
||||
return Err(E::new(C::InvalidFormat, R::Overlap).at(kind, start));
|
||||
}
|
||||
}
|
||||
result.sections[kind as usize] =
|
||||
Some(Section { kind, offset: start, bytes: &bytes[start..end] });
|
||||
}
|
||||
for kind in [0, 1, 2, 4, 5, 6, 7, 8] {
|
||||
if result.sections[kind].is_none() {
|
||||
return Err(E::new(C::InvalidFormat, R::MissingSection).at(kind as u32, 8));
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
/// Decode and resolve Registry metadata only. This is not an executable loader.
|
||||
pub fn resolve_registry(&self, b: &mut LoadBudget) -> Result<Registry, E> {
|
||||
b.transaction(|b| {
|
||||
let resources = [
|
||||
Q::TemporaryBytes,
|
||||
Q::Types,
|
||||
Q::Functions,
|
||||
Q::Implementations,
|
||||
Q::NestedRecords,
|
||||
Q::NameBytes,
|
||||
];
|
||||
let before = resources.map(|r| b.used(r));
|
||||
let types = Reader::new(self.section(6).unwrap(), b).types()?;
|
||||
let mut functions = Reader::new(self.section(1).unwrap(), b).functions()?;
|
||||
Reader::new(self.section(8).unwrap(), b).captures(&mut functions)?;
|
||||
let implementations = Reader::new(self.section(7).unwrap(), b).implementations()?;
|
||||
// Ownership moves from parse scratch to retained Registry. No clone or
|
||||
// simultaneous second declaration allocation occurs at this boundary.
|
||||
for (r, used) in resources.into_iter().zip(before) {
|
||||
b.refund(r, b.used(r) - used);
|
||||
}
|
||||
Registry::resolve(
|
||||
RegistryDeclarations { types, functions, implementations },
|
||||
self.section(2).unwrap().bytes.len(),
|
||||
b,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
fn overflow() -> E {
|
||||
E::new(C::ResourceLimit, R::Overflow)
|
||||
}
|
||||
struct Reader<'a, 'b> {
|
||||
section: Section<'a>,
|
||||
pos: usize,
|
||||
budget: &'b mut LoadBudget,
|
||||
}
|
||||
impl<'a, 'b> Reader<'a, 'b> {
|
||||
fn new(section: Section<'a>, budget: &'b mut LoadBudget) -> Self {
|
||||
Self { section, pos: 0, budget }
|
||||
}
|
||||
fn error(&self, code: C, reason: R) -> E {
|
||||
E::new(code, reason).at(self.section.kind, self.section.offset + self.pos)
|
||||
}
|
||||
fn take(&mut self, n: usize) -> Result<&'a [u8], E> {
|
||||
let end = self.pos.checked_add(n).ok_or_else(overflow)?;
|
||||
let value = self
|
||||
.section
|
||||
.bytes
|
||||
.get(self.pos..end)
|
||||
.ok_or_else(|| self.error(C::InvalidFormat, R::Truncated))?;
|
||||
self.budget.work(n)?;
|
||||
self.pos = end;
|
||||
Ok(value)
|
||||
}
|
||||
fn byte(&mut self) -> Result<u8, E> {
|
||||
Ok(self.take(1)?[0])
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32, E> {
|
||||
Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
|
||||
}
|
||||
fn finish(&self) -> Result<(), E> {
|
||||
if self.pos == self.section.bytes.len() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(self.error(C::InvalidFormat, R::TrailingBytes))
|
||||
}
|
||||
}
|
||||
fn list<T>(&mut self, resource: Q, min_bytes: usize) -> Result<(Vec<T>, usize), E> {
|
||||
let count = self.u32()? as usize;
|
||||
self.budget.charge(resource, count as u64)?;
|
||||
let min = count.checked_mul(min_bytes).ok_or_else(overflow)?;
|
||||
if min > self.section.bytes.len() - self.pos {
|
||||
return Err(self.error(C::InvalidFormat, R::Truncated));
|
||||
}
|
||||
Ok((self.budget.vector(count, Q::TemporaryBytes)?, count))
|
||||
}
|
||||
fn name(&mut self) -> Result<Option<String>, E> {
|
||||
match self.byte()? {
|
||||
0 => Ok(None),
|
||||
1 => {
|
||||
let len = self.u32()? as usize;
|
||||
if len as u64 > self.budget.individual_name_limit() {
|
||||
return Err(E::resource(
|
||||
Q::NameBytes,
|
||||
len as u64,
|
||||
self.budget.individual_name_limit(),
|
||||
)
|
||||
.at(self.section.kind, self.section.offset + self.pos));
|
||||
}
|
||||
self.budget.charge(Q::NameBytes, len as u64)?;
|
||||
let bytes = self.take(len)?;
|
||||
self.budget.work(len)?;
|
||||
let value = std::str::from_utf8(bytes)
|
||||
.map_err(|_| self.error(C::InvalidFormat, R::Utf8))?;
|
||||
self.budget.work(len)?;
|
||||
let mut storage = self.budget.vector::<u8>(len, Q::TemporaryBytes)?;
|
||||
storage.extend_from_slice(value.as_bytes());
|
||||
// UTF-8 was checked above; moving Vec into String performs no allocation.
|
||||
Ok(Some(
|
||||
String::from_utf8(storage)
|
||||
.map_err(|_| self.error(C::InvalidFormat, R::Utf8))?,
|
||||
))
|
||||
}
|
||||
_ => Err(self.error(C::InvalidFormat, R::InvalidFlag)),
|
||||
}
|
||||
}
|
||||
fn named(&mut self) -> Result<Vec<NamedType>, E> {
|
||||
let (mut out, n) = self.list(Q::NestedRecords, 5)?;
|
||||
for i in 0..n {
|
||||
self.budget.work(1)?;
|
||||
let type_id = TypeId(self.u32()?);
|
||||
let name = self.name().map_err(|e| e.member(i as u32))?;
|
||||
out.push(NamedType { type_id, name });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
fn signature(&mut self) -> Result<Signature, E> {
|
||||
let parameters = self.named()?;
|
||||
let (mut results, n) = self.list(Q::NestedRecords, 4)?;
|
||||
for _ in 0..n {
|
||||
self.budget.work(1)?;
|
||||
results.push(TypeId(self.u32()?));
|
||||
}
|
||||
Ok(Signature { parameters, results })
|
||||
}
|
||||
fn types(mut self) -> Result<Vec<TypeDecl>, E> {
|
||||
let (mut out, n) = self.list(Q::Types, 6)?;
|
||||
for i in 0..n {
|
||||
self.budget.work(1)?;
|
||||
let record = (|| {
|
||||
let kind = self.byte()?;
|
||||
let name = self.name()?;
|
||||
let kind = match kind {
|
||||
0 => TypeKind::Builtin(BuiltinId(self.u32()?)),
|
||||
1 => TypeKind::Struct(self.named()?),
|
||||
2 => TypeKind::Array(TypeId(self.u32()?)),
|
||||
4 => TypeKind::Fn(self.signature()?),
|
||||
3 => {
|
||||
let (mut methods, n) = self.list(Q::NestedRecords, 9)?;
|
||||
for j in 0..n {
|
||||
self.budget.work(1)?;
|
||||
let name = self.name()?;
|
||||
let signature = self.signature().map_err(|e| e.member(j as u32))?;
|
||||
methods.push(MethodDecl { name, signature });
|
||||
}
|
||||
TypeKind::Trait(methods)
|
||||
}
|
||||
_ => return Err(self.error(C::UnsupportedFormat, R::Category)),
|
||||
};
|
||||
Ok(TypeDecl { name, kind })
|
||||
})()
|
||||
.map_err(|e: E| e.record(i as u32))?;
|
||||
out.push(record);
|
||||
}
|
||||
self.finish()?;
|
||||
Ok(out)
|
||||
}
|
||||
fn functions(mut self) -> Result<Vec<FunctionDecl>, E> {
|
||||
let (mut out, n) = self.list(Q::Functions, 26)?;
|
||||
for i in 0..n {
|
||||
self.budget.work(1)?;
|
||||
let f = (|| {
|
||||
Ok(FunctionDecl {
|
||||
lifecycle_role: LifecycleRole::try_from(self.byte()?).map_err(|e| {
|
||||
e.at(1, self.section.offset + self.pos - 1).in_function(i as u32, None)
|
||||
})?,
|
||||
name: self.name()?,
|
||||
signature: self.signature()?,
|
||||
code_offset: self.u32()?,
|
||||
code_len: self.u32()?,
|
||||
local_slots: self.u32()?,
|
||||
max_stack_slots: self.u32()?,
|
||||
captures: Vec::new(),
|
||||
})
|
||||
})()
|
||||
.map_err(|e: E| e.record(i as u32))?;
|
||||
out.push(f);
|
||||
}
|
||||
self.finish()?;
|
||||
Ok(out)
|
||||
}
|
||||
fn captures(mut self, functions: &mut [FunctionDecl]) -> Result<(), E> {
|
||||
let n = self.u32()? as usize;
|
||||
if n != functions.len() {
|
||||
let mut error = self.error(C::InvalidFormat, R::CaptureCount);
|
||||
error.requested = Some(n as u64);
|
||||
error.limit = Some(functions.len() as u64);
|
||||
return Err(error);
|
||||
}
|
||||
for (i, function) in functions.iter_mut().enumerate() {
|
||||
self.budget.work(1)?;
|
||||
let (mut captures, n) =
|
||||
self.list(Q::NestedRecords, 4).map_err(|e| e.record(i as u32))?;
|
||||
for _ in 0..n {
|
||||
self.budget.work(1)?;
|
||||
captures.push(TypeId(self.u32()?));
|
||||
}
|
||||
function.captures = captures;
|
||||
}
|
||||
self.finish()
|
||||
}
|
||||
fn implementations(mut self) -> Result<Vec<ImplementationDecl>, E> {
|
||||
let (mut out, n) = self.list(Q::Implementations, 12)?;
|
||||
for i in 0..n {
|
||||
self.budget.work(1)?;
|
||||
let imp = (|| {
|
||||
let owner = TypeId(self.u32()?);
|
||||
let trait_id = TypeId(self.u32()?);
|
||||
let (mut methods, n) = self.list(Q::NestedRecords, 4)?;
|
||||
for _ in 0..n {
|
||||
self.budget.work(1)?;
|
||||
methods.push(FunctionId(self.u32()?));
|
||||
}
|
||||
Ok(ImplementationDecl { owner, trait_id, methods })
|
||||
})()
|
||||
.map_err(|e: E| e.record(i as u32))?;
|
||||
out.push(imp);
|
||||
}
|
||||
self.finish()?;
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw section input for a v0 envelope writer. Non-Registry section bytes must
|
||||
/// come from their own validated writers; this API never invents defaults.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct SectionData<'a> {
|
||||
pub kind: u32,
|
||||
pub bytes: &'a [u8],
|
||||
}
|
||||
/// Assemble strict v0 sections. The output buffer is charged to temporary load storage.
|
||||
pub fn encode_envelope(sections: &[SectionData<'_>], b: &mut LoadBudget) -> Result<Vec<u8>, E> {
|
||||
b.transaction(|b| {
|
||||
let mut by_kind = [None; 9];
|
||||
for section in sections {
|
||||
b.work(1)?;
|
||||
if section.kind > 8 {
|
||||
return Err(E::new(C::UnsupportedFormat, R::SectionKind));
|
||||
}
|
||||
if by_kind[section.kind as usize].replace(section.bytes).is_some() {
|
||||
return Err(E::new(C::InvalidFormat, R::DuplicateSection));
|
||||
}
|
||||
}
|
||||
for k in [0, 1, 2, 4, 5, 6, 7, 8] {
|
||||
if by_kind[k].is_none() {
|
||||
return Err(E::new(C::InvalidFormat, R::MissingSection).at(k as u32, 8));
|
||||
}
|
||||
}
|
||||
b.check(Q::CodeBytes, by_kind[2].unwrap().len() as u64)?;
|
||||
let count = sections.len();
|
||||
let directory_end = 32 + 12 * count;
|
||||
let total = sections
|
||||
.iter()
|
||||
.try_fold(directory_end, |n, s| n.checked_add(s.bytes.len()).ok_or_else(overflow))?;
|
||||
b.check(Q::PbxBytes, total as u64)?;
|
||||
b.work(total)?;
|
||||
let mut out = b.vector(total, Q::TemporaryBytes)?;
|
||||
out.extend_from_slice(b"PBX\0");
|
||||
out.extend_from_slice(&[0, 0, 0, 0]);
|
||||
out.extend_from_slice(&(count as u32).to_le_bytes());
|
||||
out.extend_from_slice(&[0; 20]);
|
||||
let mut offset = directory_end;
|
||||
for (kind, data) in by_kind.iter().enumerate() {
|
||||
if let Some(data) = data {
|
||||
out.extend_from_slice(&(kind as u32).to_le_bytes());
|
||||
out.extend_from_slice(&(offset as u32).to_le_bytes());
|
||||
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
offset += data.len();
|
||||
}
|
||||
}
|
||||
for data in by_kind.into_iter().flatten() {
|
||||
out.extend_from_slice(data);
|
||||
}
|
||||
Ok(out)
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RegistrySections {
|
||||
pub types: Vec<u8>,
|
||||
pub functions: Vec<u8>,
|
||||
pub implementations: Vec<u8>,
|
||||
pub captures: Vec<u8>,
|
||||
}
|
||||
/// Field-by-field serialization of already resolved Registry declarations.
|
||||
/// There is no source-language inference or unsupported-value-to-null fallback.
|
||||
pub fn encode_registry(registry: &Registry, b: &mut LoadBudget) -> Result<RegistrySections, E> {
|
||||
b.transaction(|b| {
|
||||
let d = registry.declarations();
|
||||
let types = write_section(b, |w| {
|
||||
w.count(d.types.len())?;
|
||||
for t in &d.types {
|
||||
w.byte(match t.kind {
|
||||
TypeKind::Builtin(_) => 0,
|
||||
TypeKind::Struct(_) => 1,
|
||||
TypeKind::Array(_) => 2,
|
||||
TypeKind::Trait(_) => 3,
|
||||
TypeKind::Fn(_) => 4,
|
||||
})?;
|
||||
w.name(&t.name)?;
|
||||
match &t.kind {
|
||||
TypeKind::Builtin(id) => w.u32(id.0)?,
|
||||
TypeKind::Struct(fields) => w.named(fields)?,
|
||||
TypeKind::Array(id) => w.u32(id.0)?,
|
||||
TypeKind::Fn(s) => w.signature(s)?,
|
||||
TypeKind::Trait(methods) => {
|
||||
w.count(methods.len())?;
|
||||
for m in methods {
|
||||
w.name(&m.name)?;
|
||||
w.signature(&m.signature)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let functions = write_section(b, |w| {
|
||||
w.count(d.functions.len())?;
|
||||
for f in &d.functions {
|
||||
w.byte(f.lifecycle_role as u8)?;
|
||||
w.name(&f.name)?;
|
||||
w.signature(&f.signature)?;
|
||||
w.u32(f.code_offset)?;
|
||||
w.u32(f.code_len)?;
|
||||
w.u32(f.local_slots)?;
|
||||
w.u32(f.max_stack_slots)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let implementations = write_section(b, |w| {
|
||||
w.count(d.implementations.len())?;
|
||||
for imp in &d.implementations {
|
||||
w.u32(imp.owner.0)?;
|
||||
w.u32(imp.trait_id.0)?;
|
||||
w.count(imp.methods.len())?;
|
||||
for id in &imp.methods {
|
||||
w.u32(id.0)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let captures = write_section(b, |w| {
|
||||
w.count(d.functions.len())?;
|
||||
for f in &d.functions {
|
||||
w.count(f.captures.len())?;
|
||||
for id in &f.captures {
|
||||
w.u32(id.0)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(RegistrySections { types, functions, implementations, captures })
|
||||
})
|
||||
}
|
||||
// Count first so a malicious producer cannot trigger unbounded geometric growth.
|
||||
struct Writer<'a> {
|
||||
out: Option<&'a mut Vec<u8>>,
|
||||
len: usize,
|
||||
budget: &'a mut LoadBudget,
|
||||
}
|
||||
impl Writer<'_> {
|
||||
fn bytes(&mut self, bytes: &[u8]) -> Result<(), E> {
|
||||
self.budget.work(bytes.len())?;
|
||||
self.len = self.len.checked_add(bytes.len()).ok_or_else(overflow)?;
|
||||
self.budget.check(Q::PbxBytes, self.len as u64)?;
|
||||
if let Some(out) = self.out.as_mut() {
|
||||
out.extend_from_slice(bytes);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn byte(&mut self, n: u8) -> Result<(), E> {
|
||||
self.bytes(&[n])
|
||||
}
|
||||
fn u32(&mut self, n: u32) -> Result<(), E> {
|
||||
self.bytes(&n.to_le_bytes())
|
||||
}
|
||||
fn count(&mut self, n: usize) -> Result<(), E> {
|
||||
self.u32(u32::try_from(n).map_err(|_| overflow())?)
|
||||
}
|
||||
fn name(&mut self, n: &Option<String>) -> Result<(), E> {
|
||||
match n {
|
||||
None => self.byte(0),
|
||||
Some(n) => {
|
||||
self.byte(1)?;
|
||||
self.count(n.len())?;
|
||||
self.bytes(n.as_bytes())
|
||||
}
|
||||
}
|
||||
}
|
||||
fn named(&mut self, items: &[NamedType]) -> Result<(), E> {
|
||||
self.count(items.len())?;
|
||||
for p in items {
|
||||
self.u32(p.type_id.0)?;
|
||||
self.name(&p.name)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn signature(&mut self, s: &Signature) -> Result<(), E> {
|
||||
self.named(&s.parameters)?;
|
||||
self.count(s.results.len())?;
|
||||
for id in &s.results {
|
||||
self.u32(id.0)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn write_section(
|
||||
b: &mut LoadBudget,
|
||||
write: impl Fn(&mut Writer<'_>) -> Result<(), E>,
|
||||
) -> Result<Vec<u8>, E> {
|
||||
let mut counter = Writer { out: None, len: 0, budget: b };
|
||||
write(&mut counter)?;
|
||||
let len = counter.len;
|
||||
let mut out = b.vector(len, Q::TemporaryBytes)?;
|
||||
write(&mut Writer { out: Some(&mut out), len: 0, budget: b })?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
mod payloads;
|
||||
pub use payloads::{OwnedPbx, ParsedPbx};
|
||||
mod writer;
|
||||
pub use writer::PbxModule;
|
||||
@@ -0,0 +1,393 @@
|
||||
//! Validation of unchanged non-Registry section encodings, without allocating
|
||||
//! guest constants or publishing an executable image.
|
||||
use super::*;
|
||||
use crate::abi::SourceSpan;
|
||||
use crate::load_limits::IdDomain;
|
||||
use crate::model::{ConstantPoolEntry, DebugInfo, Export, SyscallDecl};
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// Owned, bounded PBX v0 tables for the executable loader. This is not an
|
||||
/// executable image: bindings and instruction/type verification are still due.
|
||||
#[derive(Debug)]
|
||||
pub struct OwnedPbx {
|
||||
pub registry: Registry,
|
||||
pub constants: Vec<ConstantPoolEntry>,
|
||||
pub code: Vec<u8>,
|
||||
pub debug: Option<DebugInfo>,
|
||||
pub exports: Vec<Export>,
|
||||
pub syscalls: Vec<SyscallDecl>,
|
||||
}
|
||||
impl OwnedPbx {
|
||||
pub fn parse(bytes: &[u8], budget: &mut LoadBudget) -> Result<Self, E> {
|
||||
budget.transaction(|budget| {
|
||||
let parsed = ParsedPbx::parse(bytes, budget)?;
|
||||
let constants = Reader::new(parsed.section(0).unwrap(), budget).owned_constants()?;
|
||||
let exports = Reader::new(parsed.section(4).unwrap(), budget).owned_exports()?;
|
||||
let syscalls = Reader::new(parsed.section(5).unwrap(), budget).owned_syscalls()?;
|
||||
let debug = parsed
|
||||
.section(3)
|
||||
.map(|section| Reader::new(section, budget).owned_debug())
|
||||
.transpose()?;
|
||||
let section = parsed.section(2).unwrap();
|
||||
let mut code = budget
|
||||
.vector(section.bytes.len(), Q::TemporaryBytes)
|
||||
.map_err(|e| e.at(2, section.offset))?;
|
||||
budget.work(section.bytes.len()).map_err(|e| e.at(2, section.offset))?;
|
||||
code.extend_from_slice(section.bytes);
|
||||
Ok(Self { registry: parsed.registry, constants, code, debug, exports, syscalls })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// All PBX tables have passed binary and reference validation. Code has NOT
|
||||
/// passed instruction/type-flow verification and host calls are NOT bound.
|
||||
#[derive(Debug)]
|
||||
pub struct ParsedPbx<'a> {
|
||||
envelope: PbxEnvelope<'a>,
|
||||
registry: Registry,
|
||||
}
|
||||
impl<'a> ParsedPbx<'a> {
|
||||
pub fn parse(bytes: &'a [u8], budget: &mut LoadBudget) -> Result<Self, E> {
|
||||
budget.transaction(|budget| {
|
||||
let envelope = PbxEnvelope::parse(bytes, budget)?;
|
||||
let registry = envelope.resolve_registry(budget)?;
|
||||
let functions = registry.declarations().functions.len();
|
||||
let code_len = envelope.section(2).unwrap().bytes.len();
|
||||
Reader::new(envelope.section(0).unwrap(), budget).constants()?;
|
||||
Reader::new(envelope.section(4).unwrap(), budget).exports(functions)?;
|
||||
Reader::new(envelope.section(5).unwrap(), budget).syscalls()?;
|
||||
if let Some(debug) = envelope.section(3) {
|
||||
Reader::new(debug, budget).debug(functions, code_len)?;
|
||||
}
|
||||
Ok(Self { envelope, registry })
|
||||
})
|
||||
}
|
||||
pub fn registry(&self) -> &Registry {
|
||||
&self.registry
|
||||
}
|
||||
pub fn section(&self, kind: u32) -> Option<Section<'a>> {
|
||||
self.envelope.section(kind)
|
||||
}
|
||||
/// Re-encode validated tables in canonical directory order; debug absence is preserved.
|
||||
pub fn encode(&self, budget: &mut LoadBudget) -> Result<Vec<u8>, E> {
|
||||
let mut sections = [SectionData { kind: 0, bytes: &[] }; 9];
|
||||
let mut count = 0;
|
||||
for kind in 0..9 {
|
||||
if let Some(section) = self.section(kind) {
|
||||
sections[count] = SectionData { kind, bytes: section.bytes };
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
encode_envelope(§ions[..count], budget)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a, '_> {
|
||||
fn owned_vector<T>(&mut self, count: usize) -> Result<Vec<T>, E> {
|
||||
self.budget
|
||||
.vector(count, Q::TemporaryBytes)
|
||||
.map_err(|e| e.at(self.section.kind, self.section.offset + self.pos))
|
||||
}
|
||||
fn owned_text(&mut self, len: usize) -> Result<String, E> {
|
||||
let value = self.utf8(len)?;
|
||||
let mut bytes = self.owned_vector(len)?;
|
||||
self.budget.work(len)?;
|
||||
bytes.extend_from_slice(value.as_bytes());
|
||||
Ok(String::from_utf8(bytes).expect("UTF-8 checked before allocation"))
|
||||
}
|
||||
fn owned_constants(mut self) -> Result<Vec<ConstantPoolEntry>, E> {
|
||||
let count = self.raw_count(1)?;
|
||||
let mut out = self.owned_vector(count)?;
|
||||
for i in 0..count {
|
||||
self.budget.work(1)?;
|
||||
let value = (|| {
|
||||
Ok(match self.byte()? {
|
||||
0 => ConstantPoolEntry::Null,
|
||||
1 => ConstantPoolEntry::Int64(i64::from_le_bytes(
|
||||
self.take(8)?.try_into().unwrap(),
|
||||
)),
|
||||
2 => ConstantPoolEntry::Float64(f64::from_bits(u64::from_le_bytes(
|
||||
self.take(8)?.try_into().unwrap(),
|
||||
))),
|
||||
3 => ConstantPoolEntry::Boolean(self.byte()? == 1),
|
||||
4 => {
|
||||
let len = self.u32()? as usize;
|
||||
ConstantPoolEntry::String(self.owned_text(len)?)
|
||||
}
|
||||
5 => ConstantPoolEntry::Int32(i32::from_le_bytes(
|
||||
self.take(4)?.try_into().unwrap(),
|
||||
)),
|
||||
_ => return Err(self.error(C::UnsupportedFormat, R::ConstantTag)),
|
||||
})
|
||||
})()
|
||||
.map_err(|e: E| e.record(i as u32))?;
|
||||
out.push(value);
|
||||
}
|
||||
self.finish()?;
|
||||
Ok(out)
|
||||
}
|
||||
fn owned_exports(mut self) -> Result<Vec<Export>, E> {
|
||||
let count = self.raw_count(8)?;
|
||||
let mut out = self.owned_vector(count)?;
|
||||
for i in 0..count {
|
||||
self.budget.work(1)?;
|
||||
let func_idx = self.u32()?;
|
||||
let len = self.u32()? as usize;
|
||||
let symbol = self.owned_text(len).map_err(|e| e.record(i as u32))?;
|
||||
out.push(Export { func_idx, symbol });
|
||||
}
|
||||
self.finish()?;
|
||||
Ok(out)
|
||||
}
|
||||
fn owned_syscalls(mut self) -> Result<Vec<SyscallDecl>, E> {
|
||||
let count = self.raw_count(10)?;
|
||||
let mut out = self.owned_vector(count)?;
|
||||
for i in 0..count {
|
||||
self.budget.work(1)?;
|
||||
let record = (|| {
|
||||
let len = self.u16()? as usize;
|
||||
let module = self.owned_text(len)?;
|
||||
let len = self.u16()? as usize;
|
||||
let name = self.owned_text(len)?;
|
||||
Ok(SyscallDecl {
|
||||
module,
|
||||
name,
|
||||
version: self.u16()?,
|
||||
arg_slots: self.u16()?,
|
||||
ret_slots: self.u16()?,
|
||||
})
|
||||
})()
|
||||
.map_err(|e: E| e.record(i as u32))?;
|
||||
out.push(record);
|
||||
}
|
||||
self.finish()?;
|
||||
Ok(out)
|
||||
}
|
||||
fn owned_debug(mut self) -> Result<DebugInfo, E> {
|
||||
let count = self.raw_count(16)?;
|
||||
let mut pc_to_span = self.owned_vector(count)?;
|
||||
for i in 0..count {
|
||||
self.budget.work(1)?;
|
||||
let value = (|| {
|
||||
Ok((
|
||||
self.u32()?,
|
||||
SourceSpan { file_id: self.u32()?, start: self.u32()?, end: self.u32()? },
|
||||
))
|
||||
})()
|
||||
.map_err(|e: E| e.record(i as u32))?;
|
||||
pc_to_span.push(value);
|
||||
}
|
||||
let count = self.raw_count(8)?;
|
||||
let mut function_names = self.owned_vector(count)?;
|
||||
for i in 0..count {
|
||||
self.budget.work(1)?;
|
||||
let id = self.u32()?;
|
||||
let len = self.u32()? as usize;
|
||||
let name = self.owned_text(len).map_err(|e| e.record(i as u32))?;
|
||||
function_names.push((id, name));
|
||||
}
|
||||
self.finish()?;
|
||||
Ok(DebugInfo { pc_to_span, function_names })
|
||||
}
|
||||
fn u16(&mut self) -> Result<u16, E> {
|
||||
Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap()))
|
||||
}
|
||||
fn raw_count(&mut self, minimum: usize) -> Result<usize, E> {
|
||||
let count = self.u32()? as usize;
|
||||
if count.checked_mul(minimum).ok_or_else(overflow)? > self.section.bytes.len() - self.pos {
|
||||
return Err(self.error(C::InvalidFormat, R::Truncated));
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
fn utf8(&mut self, len: usize) -> Result<&'a str, E> {
|
||||
let bytes = self.take(len)?;
|
||||
self.budget.work(len)?;
|
||||
std::str::from_utf8(bytes).map_err(|_| self.error(C::InvalidFormat, R::Utf8))
|
||||
}
|
||||
fn text(&mut self, len: usize) -> Result<&'a str, E> {
|
||||
if len as u64 > self.budget.individual_name_limit() {
|
||||
return Err(E::resource(Q::NameBytes, len as u64, self.budget.individual_name_limit())
|
||||
.at(self.section.kind, self.section.offset + self.pos));
|
||||
}
|
||||
self.utf8(len)
|
||||
}
|
||||
fn function(&self, id: u32, count: usize) -> Result<(), E> {
|
||||
if id as usize >= count {
|
||||
Err(self.error(C::InvalidReference, R::FunctionId).reference(IdDomain::Function, id))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn constants(mut self) -> Result<(), E> {
|
||||
let count = self.u32()? as usize;
|
||||
self.budget.charge(Q::ConstantEntries, count as u64)?;
|
||||
if count > self.section.bytes.len() - self.pos {
|
||||
return Err(self.error(C::InvalidFormat, R::Truncated));
|
||||
}
|
||||
for i in 0..count {
|
||||
self.budget.work(1)?;
|
||||
(|| {
|
||||
match self.byte()? {
|
||||
0 => {}
|
||||
1 => {
|
||||
self.take(8)?;
|
||||
}
|
||||
2 => {
|
||||
let at = self.pos;
|
||||
let bits = u64::from_le_bytes(self.take(8)?.try_into().unwrap());
|
||||
if bits & 0x7ff0_0000_0000_0000 == 0x7ff0_0000_0000_0000 {
|
||||
return Err(E::new(C::InvalidFormat, R::NonFiniteValue)
|
||||
.at(self.section.kind, self.section.offset + at));
|
||||
}
|
||||
}
|
||||
3 => {
|
||||
if self.byte()? > 1 {
|
||||
return Err(self.error(C::InvalidFormat, R::InvalidFlag));
|
||||
}
|
||||
}
|
||||
4 => {
|
||||
let len = self.u32()? as usize;
|
||||
if len as u64 > self.budget.individual_string_limit() {
|
||||
return Err(E::resource(
|
||||
Q::ConstantStringBytes,
|
||||
len as u64,
|
||||
self.budget.individual_string_limit(),
|
||||
)
|
||||
.at(0, self.section.offset + self.pos));
|
||||
}
|
||||
self.budget.charge(Q::ConstantStringBytes, len as u64)?;
|
||||
self.utf8(len)?;
|
||||
}
|
||||
5 => {
|
||||
self.take(4)?;
|
||||
}
|
||||
_ => return Err(self.error(C::UnsupportedFormat, R::ConstantTag)),
|
||||
}
|
||||
Ok(())
|
||||
})()
|
||||
.map_err(|e: E| e.record(i as u32))?;
|
||||
}
|
||||
self.finish()
|
||||
}
|
||||
fn exports(mut self, functions: usize) -> Result<(), E> {
|
||||
let count = self.raw_count(8)?;
|
||||
for i in 0..count {
|
||||
self.budget.work(1)?;
|
||||
let id = self.u32()?;
|
||||
self.function(id, functions).map_err(|e| e.record(i as u32))?;
|
||||
let len = self.u32()? as usize;
|
||||
self.text(len).map_err(|e| e.record(i as u32))?;
|
||||
}
|
||||
self.finish()
|
||||
}
|
||||
fn debug(mut self, functions: usize, code_len: usize) -> Result<(), E> {
|
||||
let count = self.raw_count(16)?;
|
||||
for i in 0..count {
|
||||
self.budget.work(1)?;
|
||||
let pc = self.u32()?;
|
||||
self.u32()?; // source file ID, local to debug information
|
||||
let start = self.u32()?;
|
||||
let end = self.u32()?;
|
||||
if pc as usize >= code_len || end < start {
|
||||
return Err(self.error(C::InvalidFormat, R::DebugRange).record(i as u32));
|
||||
}
|
||||
}
|
||||
let names = self.raw_count(8)?;
|
||||
for i in 0..names {
|
||||
self.budget.work(1)?;
|
||||
let id = self.u32()?;
|
||||
self.function(id, functions).map_err(|e| e.record(i as u32))?;
|
||||
let len = self.u32()? as usize;
|
||||
self.text(len).map_err(|e| e.record(i as u32))?;
|
||||
}
|
||||
self.finish()
|
||||
}
|
||||
pub(super) fn syscalls(mut self) -> Result<(), E> {
|
||||
let count = self.raw_count(10)?;
|
||||
let mut identities = self.budget.vector(count, Q::TemporaryBytes)?;
|
||||
for i in 0..count {
|
||||
self.budget.work(1)?;
|
||||
let len = self.u16()? as usize;
|
||||
let module = self.text(len).map_err(|e| e.record(i as u32))?;
|
||||
let len = self.u16()? as usize;
|
||||
let name = self.text(len).map_err(|e| e.record(i as u32))?;
|
||||
let version = self.u16()?;
|
||||
self.u16()?; // argument slots, unchanged SYSC encoding
|
||||
self.u16()?; // result slots
|
||||
identities.push((module, name, version, i as u32));
|
||||
}
|
||||
self.finish()?;
|
||||
// Fallible heapsort bounds both auxiliary storage and comparison work;
|
||||
// unlike sorting with an error flag it stops immediately at quota refusal.
|
||||
fallible_sort(&mut identities, |a, b| {
|
||||
let module = text_cmp(a.0, b.0, self.budget)?;
|
||||
if module != Ordering::Equal {
|
||||
return Ok(module);
|
||||
}
|
||||
let name = text_cmp(a.1, b.1, self.budget)?;
|
||||
if name != Ordering::Equal {
|
||||
return Ok(name);
|
||||
}
|
||||
self.budget.work(1)?;
|
||||
Ok((a.2, a.3).cmp(&(b.2, b.3)))
|
||||
})?;
|
||||
for pair in identities.windows(2) {
|
||||
self.budget.work(1)?;
|
||||
if text_cmp(pair[0].0, pair[1].0, self.budget)? == Ordering::Equal
|
||||
&& text_cmp(pair[0].1, pair[1].1, self.budget)? == Ordering::Equal
|
||||
&& pair[0].2 == pair[1].2
|
||||
{
|
||||
return Err(self.error(C::InvalidFormat, R::DuplicateSyscall).record(pair[1].3));
|
||||
}
|
||||
}
|
||||
self.budget.refund(
|
||||
Q::TemporaryBytes,
|
||||
(identities.capacity() * size_of::<(&str, &str, u16, u32)>()) as u64,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn text_cmp(a: &str, b: &str, budget: &mut LoadBudget) -> Result<Ordering, E> {
|
||||
for (a, b) in a.bytes().zip(b.bytes()) {
|
||||
budget.work(2)?;
|
||||
match a.cmp(&b) {
|
||||
Ordering::Equal => {}
|
||||
other => return Ok(other),
|
||||
}
|
||||
}
|
||||
budget.work(1)?;
|
||||
Ok(a.len().cmp(&b.len()))
|
||||
}
|
||||
fn fallible_sort<T>(
|
||||
items: &mut [T],
|
||||
mut cmp: impl FnMut(&T, &T) -> Result<Ordering, E>,
|
||||
) -> Result<(), E> {
|
||||
fn sift<T>(
|
||||
items: &mut [T],
|
||||
mut root: usize,
|
||||
cmp: &mut impl FnMut(&T, &T) -> Result<Ordering, E>,
|
||||
) -> Result<(), E> {
|
||||
while let Some(child) =
|
||||
root.checked_mul(2).and_then(|n| n.checked_add(1)).filter(|&i| i < items.len())
|
||||
{
|
||||
let mut child = child;
|
||||
if child + 1 < items.len() && cmp(&items[child], &items[child + 1])? == Ordering::Less {
|
||||
child += 1;
|
||||
}
|
||||
if cmp(&items[root], &items[child])? != Ordering::Less {
|
||||
break;
|
||||
}
|
||||
items.swap(root, child);
|
||||
root = child;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
for root in (0..items.len() / 2).rev() {
|
||||
sift(items, root, &mut cmp)?;
|
||||
}
|
||||
for end in (1..items.len()).rev() {
|
||||
items.swap(0, end);
|
||||
sift(&mut items[..end], 0, &mut cmp)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Producer-side serialization of a complete typed module. This writer emits
|
||||
//! only v0; executable consumers still need bindings and code verification.
|
||||
use super::*;
|
||||
use crate::load_limits::IdDomain;
|
||||
use crate::model::{ConstantPoolEntry, DebugInfo, Export, SyscallDecl};
|
||||
|
||||
/// Borrowed producer data with already resolved Registry declarations. There
|
||||
/// is no version selector, inferred signature or generic Value-to-null path.
|
||||
pub struct PbxModule<'a> {
|
||||
pub registry: &'a Registry,
|
||||
pub constants: &'a [ConstantPoolEntry],
|
||||
pub code: &'a [u8],
|
||||
pub debug: Option<&'a DebugInfo>,
|
||||
pub exports: &'a [Export],
|
||||
pub syscalls: &'a [SyscallDecl],
|
||||
}
|
||||
|
||||
impl PbxModule<'_> {
|
||||
/// All intermediate sections coexist with the final output and are charged
|
||||
/// until dropped. On success only the returned Vec capacity remains charged.
|
||||
pub fn serialize(&self, budget: &mut LoadBudget) -> Result<Vec<u8>, E> {
|
||||
budget.transaction(|budget| {
|
||||
let temporary_before = budget.used(Q::TemporaryBytes);
|
||||
budget.check(Q::CodeBytes, self.code.len() as u64)?;
|
||||
for (id, function) in self.registry.declarations().functions.iter().enumerate() {
|
||||
budget.work(1)?;
|
||||
if u64::from(function.code_offset) + u64::from(function.code_len)
|
||||
> self.code.len() as u64
|
||||
{
|
||||
return Err(E::new(C::InvalidCode, R::CodeRange)
|
||||
.in_section(2)
|
||||
.in_function(id as u32, Some(function.code_offset)));
|
||||
}
|
||||
}
|
||||
let registry = encode_registry(self.registry, budget)?;
|
||||
let constants = write_section(budget, |w| self.write_constants(w))?;
|
||||
let exports = write_section(budget, |w| self.write_exports(w))?;
|
||||
let syscalls = write_section(budget, |w| self.write_syscalls(w))?;
|
||||
// Reuse the bounded identity validator; do not introduce a second
|
||||
// native-binding catalog or an unbounded duplicate search.
|
||||
Reader::new(Section { kind: 5, offset: 0, bytes: &syscalls }, budget).syscalls()?;
|
||||
let debug = self
|
||||
.debug
|
||||
.map(|di| write_section(budget, |w| self.write_debug(di, w)))
|
||||
.transpose()?;
|
||||
let mut sections = [SectionData { kind: 0, bytes: &[] }; 9];
|
||||
let mut count = 0;
|
||||
for (kind, bytes) in [
|
||||
(0, Some(constants.as_slice())),
|
||||
(1, Some(registry.functions.as_slice())),
|
||||
(2, Some(self.code)),
|
||||
(3, debug.as_deref()),
|
||||
(4, Some(exports.as_slice())),
|
||||
(5, Some(syscalls.as_slice())),
|
||||
(6, Some(registry.types.as_slice())),
|
||||
(7, Some(registry.implementations.as_slice())),
|
||||
(8, Some(registry.captures.as_slice())),
|
||||
] {
|
||||
if let Some(bytes) = bytes {
|
||||
sections[count] = SectionData { kind, bytes };
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
let out = encode_envelope(§ions[..count], budget)?;
|
||||
// The borrowed section array and all owned intermediate Vecs die
|
||||
// before return. Preserve prior scratch plus returned output only.
|
||||
let retained = out.capacity() as u64;
|
||||
drop(debug);
|
||||
drop(syscalls);
|
||||
drop(exports);
|
||||
drop(constants);
|
||||
drop(registry);
|
||||
budget.refund(
|
||||
Q::TemporaryBytes,
|
||||
budget.used(Q::TemporaryBytes) - temporary_before - retained,
|
||||
);
|
||||
Ok(out)
|
||||
})
|
||||
}
|
||||
|
||||
fn write_constants(&self, w: &mut Writer<'_>) -> Result<(), E> {
|
||||
w.budget.check(Q::ConstantEntries, self.constants.len() as u64)?;
|
||||
w.count(self.constants.len())?;
|
||||
let mut string_bytes = 0u64;
|
||||
for (id, entry) in self.constants.iter().enumerate() {
|
||||
w.budget.work(1)?;
|
||||
match entry {
|
||||
ConstantPoolEntry::Null => w.byte(0)?,
|
||||
ConstantPoolEntry::Int64(value) => {
|
||||
w.byte(1)?;
|
||||
w.bytes(&value.to_le_bytes())?;
|
||||
}
|
||||
ConstantPoolEntry::Float64(value) => {
|
||||
w.byte(2)?;
|
||||
w.bytes(&value.to_bits().to_le_bytes())?;
|
||||
}
|
||||
ConstantPoolEntry::Boolean(value) => {
|
||||
w.byte(3)?;
|
||||
w.byte(u8::from(*value))?;
|
||||
}
|
||||
ConstantPoolEntry::String(value) => {
|
||||
if value.len() as u64 > w.budget.individual_string_limit() {
|
||||
return Err(E::resource(
|
||||
Q::ConstantStringBytes,
|
||||
value.len() as u64,
|
||||
w.budget.individual_string_limit(),
|
||||
)
|
||||
.in_section(0)
|
||||
.record(id as u32));
|
||||
}
|
||||
string_bytes =
|
||||
string_bytes.checked_add(value.len() as u64).ok_or_else(overflow)?;
|
||||
w.budget.check(Q::ConstantStringBytes, string_bytes)?;
|
||||
w.byte(4)?;
|
||||
w.count(value.len())?;
|
||||
w.bytes(value.as_bytes())?;
|
||||
}
|
||||
ConstantPoolEntry::Int32(value) => {
|
||||
w.byte(5)?;
|
||||
w.bytes(&value.to_le_bytes())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn check_function(&self, id: u32) -> Result<(), E> {
|
||||
if id as usize >= self.registry.declarations().functions.len() {
|
||||
Err(E::new(C::InvalidReference, R::FunctionId).reference(IdDomain::Function, id))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn write_exports(&self, w: &mut Writer<'_>) -> Result<(), E> {
|
||||
w.count(self.exports.len())?;
|
||||
for (record, export) in self.exports.iter().enumerate() {
|
||||
w.budget.work(1)?;
|
||||
self.check_function(export.func_idx)
|
||||
.map_err(|e| e.in_section(4).record(record as u32))?;
|
||||
w.u32(export.func_idx)?;
|
||||
w.text(&export.symbol, 4)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn write_syscalls(&self, w: &mut Writer<'_>) -> Result<(), E> {
|
||||
w.count(self.syscalls.len())?;
|
||||
for syscall in self.syscalls {
|
||||
w.budget.work(1)?;
|
||||
w.text(&syscall.module, 2)?;
|
||||
w.text(&syscall.name, 2)?;
|
||||
w.bytes(&syscall.version.to_le_bytes())?;
|
||||
w.bytes(&syscall.arg_slots.to_le_bytes())?;
|
||||
w.bytes(&syscall.ret_slots.to_le_bytes())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn write_debug(&self, debug: &DebugInfo, w: &mut Writer<'_>) -> Result<(), E> {
|
||||
w.count(debug.pc_to_span.len())?;
|
||||
for (record, (pc, span)) in debug.pc_to_span.iter().enumerate() {
|
||||
w.budget.work(1)?;
|
||||
if *pc as usize >= self.code.len() || span.end < span.start {
|
||||
return Err(E::new(C::InvalidFormat, R::DebugRange)
|
||||
.in_section(3)
|
||||
.record(record as u32));
|
||||
}
|
||||
w.u32(*pc)?;
|
||||
w.u32(span.file_id)?;
|
||||
w.u32(span.start)?;
|
||||
w.u32(span.end)?;
|
||||
}
|
||||
w.count(debug.function_names.len())?;
|
||||
for (record, (id, name)) in debug.function_names.iter().enumerate() {
|
||||
w.budget.work(1)?;
|
||||
self.check_function(*id).map_err(|e| e.in_section(3).record(record as u32))?;
|
||||
w.u32(*id)?;
|
||||
w.text(name, 4)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Writer<'_> {
|
||||
fn text(&mut self, value: &str, length_bytes: usize) -> Result<(), E> {
|
||||
if value.len() as u64 > self.budget.individual_name_limit() {
|
||||
return Err(E::resource(
|
||||
Q::NameBytes,
|
||||
value.len() as u64,
|
||||
self.budget.individual_name_limit(),
|
||||
));
|
||||
}
|
||||
if length_bytes == 2 {
|
||||
self.bytes(&u16::try_from(value.len()).map_err(|_| overflow())?.to_le_bytes())?;
|
||||
} else {
|
||||
self.count(value.len())?;
|
||||
}
|
||||
self.bytes(value.as_bytes())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Registry-aware immediate validation and slot effects for typed instructions.
|
||||
use crate::decoder::DecodedInstr;
|
||||
use crate::isa::core::{CoreOpCode as Op, CoreOpCodeSpecExt};
|
||||
use crate::load_limits::{IdDomain, LoadCode, LoadFailure, LoadReason};
|
||||
use crate::registry::{FunctionId, Registry, TypeId, TypeKind};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RegistryStackEffect {
|
||||
pub pops: u32,
|
||||
pub pushes: u32,
|
||||
}
|
||||
|
||||
impl DecodedInstr<'_> {
|
||||
/// Capture effects require the enclosing function's resolved environment.
|
||||
pub fn registry_stack_effect_in(
|
||||
&self,
|
||||
registry: &Registry,
|
||||
function: FunctionId,
|
||||
) -> Result<Option<RegistryStackEffect>, LoadFailure> {
|
||||
if self.opcode == Op::GetCapture {
|
||||
let index = self
|
||||
.imm_u32()
|
||||
.map_err(|_| LoadFailure::new(LoadCode::InvalidCode, LoadReason::Truncated))?;
|
||||
let capture = registry
|
||||
.function_layout(function)
|
||||
.and_then(|f| f.captures.get(index as usize))
|
||||
.ok_or_else(|| {
|
||||
LoadFailure::new(LoadCode::InvalidReference, LoadReason::CaptureIndex)
|
||||
.member(index)
|
||||
})?;
|
||||
return Ok(Some(RegistryStackEffect { pops: 0, pushes: capture.slots }));
|
||||
}
|
||||
self.registry_stack_effect(registry)
|
||||
}
|
||||
/// Resolve an instruction's exact group widths and check immediate domains.
|
||||
/// None means this is not a Registry instruction, not a zero stack effect.
|
||||
/// This does not prove that the values on the stack satisfy the signature.
|
||||
pub fn registry_stack_effect(
|
||||
&self,
|
||||
registry: &Registry,
|
||||
) -> Result<Option<RegistryStackEffect>, LoadFailure> {
|
||||
if !self.opcode.requires_registry() {
|
||||
return Ok(None);
|
||||
}
|
||||
let malformed = || {
|
||||
let mut e = LoadFailure::new(LoadCode::InvalidCode, LoadReason::Truncated);
|
||||
e.pc = u32::try_from(self.pc).ok();
|
||||
e
|
||||
};
|
||||
let type_info = |id: u32| {
|
||||
let decl = registry.declarations().types.get(id as usize);
|
||||
let layout = registry.type_layout(TypeId(id));
|
||||
decl.zip(layout).ok_or_else(|| {
|
||||
let mut e = LoadFailure::new(LoadCode::InvalidReference, LoadReason::TypeId)
|
||||
.reference(IdDomain::Type, id);
|
||||
e.pc = u32::try_from(self.pc).ok();
|
||||
e
|
||||
})
|
||||
};
|
||||
let bad_category = |id: u32| {
|
||||
let mut e = LoadFailure::new(LoadCode::InvalidReference, LoadReason::Category)
|
||||
.reference(IdDomain::Type, id);
|
||||
e.pc = u32::try_from(self.pc).ok();
|
||||
e
|
||||
};
|
||||
let (pops, pushes) = match self.opcode {
|
||||
Op::MakeClosure => {
|
||||
let (function, ty) = self.imm_u32x2().map_err(|_| malformed())?;
|
||||
let (_, layout) = type_info(ty)?;
|
||||
if layout.callable.is_none() {
|
||||
return Err(bad_category(ty));
|
||||
}
|
||||
let target = registry.function_layout(FunctionId(function)).ok_or_else(|| {
|
||||
LoadFailure::new(LoadCode::InvalidReference, LoadReason::FunctionId)
|
||||
.reference(IdDomain::Function, function)
|
||||
})?;
|
||||
(target.capture_slots, 1)
|
||||
}
|
||||
Op::CallClosure => {
|
||||
let ty = self.imm_u32().map_err(|_| malformed())?;
|
||||
let (_, layout) = type_info(ty)?;
|
||||
let signature = layout.callable.as_ref().ok_or_else(|| bad_category(ty))?;
|
||||
(
|
||||
signature.parameter_slots.checked_add(1).ok_or_else(malformed)?,
|
||||
signature.result_slots,
|
||||
)
|
||||
}
|
||||
Op::GetCapture => {
|
||||
return Err(LoadFailure::new(LoadCode::InvalidReference, LoadReason::CaptureIndex));
|
||||
}
|
||||
Op::CallTrait => {
|
||||
let (ty, method) = self.imm_u32x2().map_err(|_| malformed())?;
|
||||
let (_, layout) = type_info(ty)?;
|
||||
let signature = layout
|
||||
.methods
|
||||
.get(method as usize)
|
||||
.ok_or_else(|| bad_category(ty).member(method))?;
|
||||
(
|
||||
signature.parameter_slots.checked_add(2).ok_or_else(malformed)?,
|
||||
signature.result_slots,
|
||||
)
|
||||
}
|
||||
Op::DynPack | Op::DynUnpack | Op::DynCanUnpack => {
|
||||
let id = self.imm_u32().map_err(|_| malformed())?;
|
||||
let (_, layout) = type_info(id)?;
|
||||
match self.opcode {
|
||||
Op::DynPack => (layout.storage.slots, 2),
|
||||
Op::DynUnpack => (2, layout.storage.slots),
|
||||
_ => (2, 1),
|
||||
}
|
||||
}
|
||||
Op::RefIsExact | Op::RefImplements | Op::RefToTrait | Op::RefCast => {
|
||||
let (source, target) = self.imm_u32x2().map_err(|_| malformed())?;
|
||||
let (source_decl, source_layout) = type_info(source)?;
|
||||
let (target_decl, target_layout) = type_info(target)?;
|
||||
if !matches!(
|
||||
source_decl.kind,
|
||||
TypeKind::Struct(_) | TypeKind::Array(_) | TypeKind::Trait(_)
|
||||
) {
|
||||
return Err(bad_category(source));
|
||||
}
|
||||
let trait_target = matches!(self.opcode, Op::RefImplements | Op::RefToTrait);
|
||||
if (trait_target && !matches!(target_decl.kind, TypeKind::Trait(_)))
|
||||
|| (!trait_target
|
||||
&& !matches!(target_decl.kind, TypeKind::Struct(_) | TypeKind::Array(_)))
|
||||
{
|
||||
return Err(bad_category(target));
|
||||
}
|
||||
let pushes = if matches!(self.opcode, Op::RefIsExact | Op::RefImplements) {
|
||||
1
|
||||
} else {
|
||||
target_layout.storage.slots
|
||||
};
|
||||
(source_layout.storage.slots, pushes)
|
||||
}
|
||||
Op::RefIdentityHash | Op::RefIdentityEq => {
|
||||
let (left, right) = if self.opcode == Op::RefIdentityHash {
|
||||
(self.imm_u32().map_err(|_| malformed())?, None)
|
||||
} else {
|
||||
let (a, b) = self.imm_u32x2().map_err(|_| malformed())?;
|
||||
(a, Some(b))
|
||||
};
|
||||
let mut pops = 0;
|
||||
for id in std::iter::once(left).chain(right) {
|
||||
let (decl, layout) = type_info(id)?;
|
||||
if !decl.kind.is_identity_reference() {
|
||||
return Err(bad_category(id));
|
||||
}
|
||||
pops += layout.storage.slots;
|
||||
}
|
||||
(pops, 1)
|
||||
}
|
||||
Op::ArrayCopy => {
|
||||
let array = self.imm_u32().map_err(|_| malformed())?;
|
||||
let (_, layout) = type_info(array)?;
|
||||
layout.array.ok_or_else(|| bad_category(array))?;
|
||||
(5, 0)
|
||||
}
|
||||
Op::StructNew
|
||||
| Op::StructGet
|
||||
| Op::StructSet
|
||||
| Op::ArrayNew
|
||||
| Op::ArrayLen
|
||||
| Op::ArrayGet
|
||||
| Op::ArraySet => {
|
||||
let (id, field) = if matches!(self.opcode, Op::StructGet | Op::StructSet) {
|
||||
self.imm_u32x2().map_err(|_| malformed())?
|
||||
} else {
|
||||
(self.imm_u32().map_err(|_| malformed())?, 0)
|
||||
};
|
||||
let (_, layout) = type_info(id)?;
|
||||
if matches!(self.opcode, Op::StructNew | Op::StructGet | Op::StructSet) {
|
||||
let instance = layout.instance.as_ref().ok_or_else(|| bad_category(id))?;
|
||||
match self.opcode {
|
||||
Op::StructNew => (0, 1),
|
||||
op => {
|
||||
let f = instance
|
||||
.fields
|
||||
.get(field as usize)
|
||||
.ok_or_else(|| bad_category(id).member(field))?;
|
||||
let w = registry.type_layout(f.type_id).unwrap().storage.slots;
|
||||
if op == Op::StructGet {
|
||||
(1, w)
|
||||
} else {
|
||||
(1 + w, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let array = layout.array.as_ref().ok_or_else(|| bad_category(id))?;
|
||||
let w = registry.type_layout(array.element_type_id).unwrap().storage.slots;
|
||||
match self.opcode {
|
||||
Op::ArrayNew | Op::ArrayLen => (1, 1),
|
||||
Op::ArrayGet => (2, w),
|
||||
_ => (2 + w, 0),
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => unreachable!("requires_registry is defined by the typed opcode catalogue"),
|
||||
};
|
||||
Ok(Some(RegistryStackEffect { pops, pushes }))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//! Resource fault context shared by the VM, native boundary and host tooling.
|
||||
//! Accounting and product ceilings remain owned by the runtime budget.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[repr(usize)]
|
||||
pub enum RuntimeResource {
|
||||
GuestBytes,
|
||||
HandleSlots,
|
||||
AuxiliaryBytes,
|
||||
TemporaryBytes,
|
||||
StringBytes,
|
||||
StringAllocations,
|
||||
IndividualStringBytes,
|
||||
CallDepth,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ResourceReason {
|
||||
Limit,
|
||||
SizeOverflow,
|
||||
AllocationFailed,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceFailure {
|
||||
pub resource: RuntimeResource,
|
||||
pub reason: ResourceReason,
|
||||
pub requested: u64,
|
||||
pub limit: u64,
|
||||
}
|
||||
impl fmt::Display for ResourceFailure {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{:?}: {:?}, requested {}, limit {}",
|
||||
self.resource, self.reason, self.requested, self.limit
|
||||
)
|
||||
}
|
||||
}
|
||||
impl std::error::Error for ResourceFailure {}
|
||||
@@ -1,19 +1,36 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::cell::Cell;
|
||||
use std::cmp::Ordering;
|
||||
use std::sync::Arc;
|
||||
|
||||
thread_local! {
|
||||
static STRING_MATERIALIZATION_COUNT: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Opaque handle that references an object stored in the VM heap.
|
||||
///
|
||||
/// This is an index-based handle. It does not imply ownership and carries
|
||||
/// no lifetime information. GC/allocator integration will come in later PRs.
|
||||
/// Handles belong to the heap/session that issued them. Native boundaries must
|
||||
/// preserve that provenance. Generation zero is reserved; compact null is (0, 0).
|
||||
#[repr(C, align(8))]
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
|
||||
pub struct HeapRef(pub u32);
|
||||
pub struct HeapRef {
|
||||
pub index: u32,
|
||||
pub generation: u32,
|
||||
}
|
||||
|
||||
impl HeapRef {
|
||||
pub const NULL: Self = Self { index: 0, generation: 0 };
|
||||
pub const fn is_null(self) -> bool {
|
||||
self.index == 0 && self.generation == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents any piece of data that can be stored on the VM stack or in globals.
|
||||
///
|
||||
/// The PVM is "dynamically typed" at the bytecode level, meaning a single
|
||||
/// `Value` enum can hold different primitive types. The VM performs
|
||||
/// automatic type promotion (e.g., adding an Int32 to a Float64 results
|
||||
/// in a Float64) to ensure mathematical correctness.
|
||||
/// This enum is a physical carrier, not a semantic type declaration. Registry
|
||||
/// boundaries validate exact types and complete multi-slot groups. Arithmetic
|
||||
/// instructions may have their own numeric promotion rules; those rules do not
|
||||
/// authorize implicit conversions at typed storage or call boundaries.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum Value {
|
||||
@@ -26,7 +43,7 @@ pub enum Value {
|
||||
/// Boolean value (true/false).
|
||||
Boolean(bool),
|
||||
/// UTF-8 string. Strings are immutable and usually come from the Constant Pool.
|
||||
String(String),
|
||||
String(Arc<str>),
|
||||
/// A handle to an object on the heap (opaque reference).
|
||||
HeapRef(HeapRef),
|
||||
/// Represents the absence of a value (equivalent to `null` or `undefined`).
|
||||
@@ -74,6 +91,14 @@ impl PartialOrd for Value {
|
||||
}
|
||||
|
||||
impl Value {
|
||||
pub fn string<S>(value: S) -> Self
|
||||
where
|
||||
S: Into<Arc<str>>,
|
||||
{
|
||||
STRING_MATERIALIZATION_COUNT.with(|count| count.set(count.get() + 1));
|
||||
Value::String(value.into())
|
||||
}
|
||||
|
||||
pub fn as_float(&self) -> Option<f64> {
|
||||
match self {
|
||||
Value::Int32(i) => Some(*i as f64),
|
||||
@@ -92,18 +117,47 @@ impl Value {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::inherent_to_string)]
|
||||
pub fn to_string(&self) -> String {
|
||||
pub fn append_to_string(&self, out: &mut String) {
|
||||
self.write_text(out).expect("writing into String is infallible");
|
||||
}
|
||||
|
||||
/// Writes existing Value text without allocating a String, so bounded
|
||||
/// callers can measure and reserve with their own fmt::Write sink.
|
||||
pub fn write_text(&self, out: &mut impl std::fmt::Write) -> std::fmt::Result {
|
||||
match self {
|
||||
Value::Int32(i) => i.to_string(),
|
||||
Value::Int64(i) => i.to_string(),
|
||||
Value::Float(f) => f.to_string(),
|
||||
Value::Boolean(b) => b.to_string(),
|
||||
Value::String(s) => s.clone(),
|
||||
Value::HeapRef(r) => format!("[HeapRef {}]", r.0),
|
||||
Value::Null => "null".to_string(),
|
||||
Value::Int32(i) => write!(out, "{}", i),
|
||||
Value::Int64(i) => write!(out, "{}", i),
|
||||
Value::Float(f) => write!(out, "{}", f),
|
||||
Value::Boolean(b) => write!(out, "{}", b),
|
||||
Value::String(s) => out.write_str(s),
|
||||
Value::HeapRef(r) => write!(out, "[HeapRef {}:{}]", r.index, r.generation),
|
||||
Value::Null => out.write_str("null"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn string_len_hint(&self) -> usize {
|
||||
match self {
|
||||
Value::String(s) => s.len(),
|
||||
Value::Null => 4,
|
||||
Value::Boolean(true) => 4,
|
||||
Value::Boolean(false) => 5,
|
||||
Value::Int32(i) => i.to_string().len(),
|
||||
Value::Int64(i) => i.to_string().len(),
|
||||
Value::Float(f) => f.to_string().len(),
|
||||
Value::HeapRef(r) => 11 + r.index.to_string().len() + r.generation.to_string().len(),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::inherent_to_string)]
|
||||
pub fn to_string(&self) -> String {
|
||||
let mut out = String::with_capacity(self.string_len_hint());
|
||||
self.append_to_string(&mut out);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
pub fn string_materialization_count() -> u64 {
|
||||
STRING_MATERIALIZATION_COUNT.with(Cell::get)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -9,7 +9,7 @@ fn emit(op: CoreOpCode, imm: Option<&[u8]>, out: &mut Vec<u8>) {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_disasm_assemble_byte_equal_with_closures_and_coroutines() {
|
||||
fn roundtrip_disasm_assemble_byte_equal_with_typed_callables() {
|
||||
// Program: PUSH_I32 7; MAKE_CLOSURE fn=1,captures=0; CALL_CLOSURE argc=1;
|
||||
// SPAWN fn=2,argc=1; YIELD; SLEEP 3; HOSTCALL 2; SYSCALL 0x1003; FRAME_SYNC; HALT
|
||||
let mut prog = Vec::new();
|
||||
@@ -22,18 +22,12 @@ fn roundtrip_disasm_assemble_byte_equal_with_closures_and_coroutines() {
|
||||
emit(CoreOpCode::MakeClosure, Some(&mc), &mut prog);
|
||||
// CALL_CLOSURE argc=1
|
||||
emit(CoreOpCode::CallClosure, Some(&1u32.to_le_bytes()), &mut prog);
|
||||
// SPAWN (fn=2, argc=1)
|
||||
let mut sp = [0u8; 8];
|
||||
sp[0..4].copy_from_slice(&2u32.to_le_bytes());
|
||||
sp[4..8].copy_from_slice(&1u32.to_le_bytes());
|
||||
emit(CoreOpCode::Spawn, Some(&sp), &mut prog);
|
||||
// YIELD
|
||||
emit(CoreOpCode::Yield, None, &mut prog);
|
||||
// SLEEP 3
|
||||
emit(CoreOpCode::Sleep, Some(&3u32.to_le_bytes()), &mut prog);
|
||||
emit(CoreOpCode::GetCapture, Some(&0u32.to_le_bytes()), &mut prog);
|
||||
let trait_call = [7u32.to_le_bytes(), 0u32.to_le_bytes()].concat();
|
||||
emit(CoreOpCode::CallTrait, Some(&trait_call), &mut prog);
|
||||
// HOSTCALL sysc[2]
|
||||
emit(CoreOpCode::Hostcall, Some(&2u32.to_le_bytes()), &mut prog);
|
||||
// SYSCALL gfx.draw_line (0x1003)
|
||||
// SYSCALL gfx2d.draw_line (0x1003)
|
||||
emit(CoreOpCode::Syscall, Some(&0x1003u32.to_le_bytes()), &mut prog);
|
||||
// FRAME_SYNC
|
||||
emit(CoreOpCode::FrameSync, None, &mut prog);
|
||||
|
||||
@@ -17,7 +17,7 @@ fn snapshot_representative_program_is_stable() {
|
||||
mc[0..4].copy_from_slice(&1u32.to_le_bytes());
|
||||
mc[4..8].copy_from_slice(&0u32.to_le_bytes());
|
||||
emit(CoreOpCode::MakeClosure, Some(&mc), &mut prog);
|
||||
// CALL_CLOSURE argc=1
|
||||
// CALL_CLOSURE 1
|
||||
emit(CoreOpCode::CallClosure, Some(&1u32.to_le_bytes()), &mut prog);
|
||||
// SPAWN (fn=2, argc=1)
|
||||
let mut sp = [0u8; 8];
|
||||
@@ -38,6 +38,6 @@ fn snapshot_representative_program_is_stable() {
|
||||
emit(CoreOpCode::Halt, None, &mut prog);
|
||||
|
||||
let text = disassemble(&prog).expect("disasm ok");
|
||||
let expected = "PUSH_I32 7\nMAKE_CLOSURE fn=1, captures=0\nCALL_CLOSURE argc=1\nSPAWN fn=2, argc=1\nYIELD\nSLEEP 3\nHOSTCALL 2\nSYSCALL 0x1003\nFRAME_SYNC\nHALT";
|
||||
let expected = "PUSH_I32 7\nMAKE_CLOSURE fn=1, type=0\nCALL_CLOSURE 1\nSPAWN fn=2, argc=1\nYIELD\nSLEEP 3\nHOSTCALL 2\nSYSCALL 0x1003\nFRAME_SYNC\nHALT";
|
||||
assert_eq!(text, expected);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
use prometeu_bytecode::isa::core::{CoreOpCode as Op, CoreOpCodeSpecExt};
|
||||
use prometeu_bytecode::load_limits::{LoadBudget, LoadCode, LoadLimits, LoadReason};
|
||||
use prometeu_bytecode::registry::*;
|
||||
use prometeu_bytecode::{assemble, decode_next, disassemble, DecodeError, RegistryStackEffect};
|
||||
|
||||
fn registry() -> Registry {
|
||||
let types = vec![
|
||||
TypeKind::Builtin(BuiltinId::INT32),
|
||||
TypeKind::Builtin(BuiltinId::VEC2),
|
||||
TypeKind::Builtin(BuiltinId::PIXEL),
|
||||
TypeKind::Builtin(BuiltinId::DYNAMIC),
|
||||
TypeKind::Struct(vec![]),
|
||||
TypeKind::Array(TypeId(0)),
|
||||
TypeKind::Trait(vec![]),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|kind| TypeDecl { name: None, kind })
|
||||
.collect();
|
||||
Registry::resolve(
|
||||
RegistryDeclarations { types, ..Default::default() },
|
||||
0,
|
||||
&mut LoadBudget::new(LoadLimits::default()),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_typed_instructions_match_independent_bytes_and_costs() {
|
||||
let cases: &[(&str, &[u8], u64)] = &[
|
||||
("DYN_PACK 16909060", &[0x90, 0, 4, 3, 2, 1], 8),
|
||||
("DYN_UNPACK 16909060", &[0x91, 0, 4, 3, 2, 1], 4),
|
||||
("DYN_CAN_UNPACK 16909060", &[0x92, 0, 4, 3, 2, 1], 3),
|
||||
("REF_IS_EXACT source=16909060, target=84281096", &[0x93, 0, 4, 3, 2, 1, 8, 7, 6, 5], 4),
|
||||
("REF_IMPLEMENTS source=16909060, target=84281096", &[0x94, 0, 4, 3, 2, 1, 8, 7, 6, 5], 4),
|
||||
("REF_TO_TRAIT source=16909060, target=84281096", &[0x95, 0, 4, 3, 2, 1, 8, 7, 6, 5], 5),
|
||||
("REF_CAST source=16909060, target=84281096", &[0x96, 0, 4, 3, 2, 1, 8, 7, 6, 5], 4),
|
||||
("REF_IDENTITY_HASH 16909060", &[0x97, 0, 4, 3, 2, 1], 8),
|
||||
("REF_IDENTITY_EQ left=16909060, right=84281096", &[0x98, 0, 4, 3, 2, 1, 8, 7, 6, 5], 4),
|
||||
];
|
||||
for &(text, bytes, cycles) in cases {
|
||||
assert_eq!(assemble(text).unwrap(), bytes);
|
||||
assert_eq!(disassemble(bytes).unwrap(), text);
|
||||
let decoded = decode_next(0, bytes).unwrap();
|
||||
assert_eq!(decoded.next_pc, bytes.len());
|
||||
assert_eq!(decoded.opcode.cycles(), cycles);
|
||||
assert_eq!(decoded.opcode.spec().pops, None);
|
||||
assert_eq!(decoded.opcode.spec().pushes, None);
|
||||
assert!(decoded.opcode.requires_registry());
|
||||
for n in 0..bytes.len() {
|
||||
assert!(decode_next(0, &bytes[..n]).is_err(), "{text}, prefix {n}");
|
||||
}
|
||||
}
|
||||
assert!(matches!(
|
||||
decode_next(0, &[0x99, 0]),
|
||||
Err(DecodeError::UnknownOpcode { opcode: 0x99, .. })
|
||||
));
|
||||
}
|
||||
#[test]
|
||||
fn slot_effects_resolve_semantic_widths_and_reference_categories() {
|
||||
let registry = registry();
|
||||
for (text, pops, pushes) in [
|
||||
("DYN_PACK 0", 1, 2),
|
||||
("DYN_PACK 1", 2, 2),
|
||||
("DYN_PACK 2", 3, 2),
|
||||
("DYN_PACK 3", 2, 2),
|
||||
("DYN_UNPACK 2", 2, 3),
|
||||
("DYN_CAN_UNPACK 2", 2, 1),
|
||||
("REF_IS_EXACT source=6, target=4", 2, 1),
|
||||
("REF_IMPLEMENTS source=5, target=6", 1, 1),
|
||||
("REF_TO_TRAIT source=4, target=6", 1, 2),
|
||||
("REF_TO_TRAIT source=6, target=6", 2, 2),
|
||||
("REF_CAST source=6, target=4", 2, 1),
|
||||
("REF_IDENTITY_HASH 6", 2, 1),
|
||||
("REF_IDENTITY_EQ left=6, right=4", 3, 1),
|
||||
] {
|
||||
let bytes = assemble(text).unwrap();
|
||||
assert_eq!(
|
||||
decode_next(0, &bytes).unwrap().registry_stack_effect(®istry).unwrap(),
|
||||
Some(RegistryStackEffect { pops, pushes }),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
assert_eq!(decode_next(0, &[0, 0]).unwrap().registry_stack_effect(®istry).unwrap(), None);
|
||||
}
|
||||
#[test]
|
||||
fn invalid_type_immediates_are_contextual_load_errors() {
|
||||
let registry = registry();
|
||||
for text in ["DYN_PACK 7", "DYN_UNPACK 4294967295", "REF_CAST source=7, target=4"] {
|
||||
let bytes = assemble(text).unwrap();
|
||||
let e = decode_next(0, &bytes).unwrap().registry_stack_effect(®istry).unwrap_err();
|
||||
assert_eq!(
|
||||
(e.code, e.reason, e.pc),
|
||||
(LoadCode::InvalidReference, LoadReason::TypeId, Some(0))
|
||||
);
|
||||
}
|
||||
for text in [
|
||||
"REF_CAST source=3, target=4",
|
||||
"REF_IS_EXACT source=4, target=6",
|
||||
"REF_TO_TRAIT source=4, target=0",
|
||||
"REF_IMPLEMENTS source=0, target=6",
|
||||
"REF_IDENTITY_HASH 0",
|
||||
"REF_IDENTITY_HASH 3",
|
||||
"REF_IDENTITY_EQ left=4, right=1",
|
||||
] {
|
||||
let bytes = assemble(text).unwrap();
|
||||
let e = decode_next(0, &bytes).unwrap().registry_stack_effect(®istry).unwrap_err();
|
||||
assert_eq!(
|
||||
(e.code, e.reason),
|
||||
(LoadCode::InvalidReference, LoadReason::Category),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn assembler_rejects_missing_overflowing_or_ambiguous_type_ids() {
|
||||
for text in [
|
||||
"DYN_PACK",
|
||||
"DYN_PACK -1",
|
||||
"DYN_PACK 4294967296",
|
||||
"DYN_PACK 1 2",
|
||||
"REF_CAST source=4",
|
||||
"REF_CAST source=4, target=5, target=6",
|
||||
"REF_CAST source=4, trait=6",
|
||||
"REF_IDENTITY_HASH",
|
||||
"REF_IDENTITY_HASH -1",
|
||||
"REF_IDENTITY_EQ left=4",
|
||||
"REF_IDENTITY_EQ left=4, target=5",
|
||||
] {
|
||||
assert!(assemble(text).is_err(), "{text}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn decoder_extreme_pc_does_not_overflow() {
|
||||
assert!(matches!(
|
||||
decode_next(usize::MAX, &[]),
|
||||
Err(DecodeError::TruncatedOpcode { pc: usize::MAX })
|
||||
));
|
||||
assert_eq!(Op::DynPack as u16, 0x0090);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_literal_encodings_roundtrip_and_reject_every_truncation() {
|
||||
for (text, bytes, base) in [
|
||||
("STRUCT_NEW 16909060", vec![0xa0, 0, 4, 3, 2, 1], 8),
|
||||
("STRUCT_GET type=16909060, field=84281096", vec![0xa1, 0, 4, 3, 2, 1, 8, 7, 6, 5], 3),
|
||||
("STRUCT_SET type=16909060, field=84281096", vec![0xa2, 0, 4, 3, 2, 1, 8, 7, 6, 5], 4),
|
||||
("ARRAY_NEW 16909060", vec![0xa3, 0, 4, 3, 2, 1], 8),
|
||||
("ARRAY_LEN 16909060", vec![0xa4, 0, 4, 3, 2, 1], 3),
|
||||
("ARRAY_GET 16909060", vec![0xa5, 0, 4, 3, 2, 1], 3),
|
||||
("ARRAY_SET 16909060", vec![0xa6, 0, 4, 3, 2, 1], 4),
|
||||
] {
|
||||
assert_eq!(assemble(text).unwrap(), bytes);
|
||||
assert_eq!(disassemble(&bytes).unwrap(), text);
|
||||
let op = decode_next(0, &bytes).unwrap().opcode;
|
||||
assert_eq!(op.cycles(), base);
|
||||
assert!(op.requires_registry() && op.spec().may_trap);
|
||||
assert!(!op.spec().is_safepoint && !op.spec().is_branch && !op.spec().is_terminator);
|
||||
for n in 0..bytes.len() {
|
||||
assert!(decode_next(0, &bytes[..n]).is_err());
|
||||
}
|
||||
}
|
||||
for bad in [
|
||||
"STRUCT_NEW",
|
||||
"ARRAY_NEW -1",
|
||||
"ARRAY_GET 4294967296",
|
||||
"ARRAY_LEN 1 2",
|
||||
"STRUCT_GET type=1",
|
||||
"STRUCT_SET type=1, field=2, field=3",
|
||||
"STRUCT_GET type=1, field=-1",
|
||||
] {
|
||||
assert!(assemble(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn collection_effects_and_cached_initialization_width_are_exact() {
|
||||
let d = RegistryDeclarations {
|
||||
types: vec![
|
||||
TypeDecl { name: None, kind: TypeKind::Builtin(BuiltinId::PIXEL) },
|
||||
TypeDecl {
|
||||
name: None,
|
||||
kind: TypeKind::Struct(vec![
|
||||
NamedType { type_id: TypeId(0), name: None },
|
||||
NamedType { type_id: TypeId(1), name: None },
|
||||
]),
|
||||
},
|
||||
TypeDecl { name: None, kind: TypeKind::Array(TypeId(0)) },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let r = Registry::resolve(d, 0, &mut LoadBudget::new(Default::default())).unwrap();
|
||||
assert_eq!(
|
||||
r.type_layout(TypeId(1)).unwrap().instance.as_ref().unwrap().initialization_slots,
|
||||
4
|
||||
);
|
||||
for (s, pops, pushes) in [
|
||||
("STRUCT_NEW 1", 0, 1),
|
||||
("STRUCT_GET type=1, field=0", 1, 3),
|
||||
("STRUCT_SET type=1, field=0", 4, 0),
|
||||
("ARRAY_NEW 2", 1, 1),
|
||||
("ARRAY_LEN 2", 1, 1),
|
||||
("ARRAY_GET 2", 2, 3),
|
||||
("ARRAY_SET 2", 5, 0),
|
||||
] {
|
||||
let code = assemble(s).unwrap();
|
||||
assert_eq!(
|
||||
decode_next(0, &code).unwrap().registry_stack_effect(&r).unwrap(),
|
||||
Some(RegistryStackEffect { pops, pushes })
|
||||
);
|
||||
}
|
||||
for s in ["STRUCT_NEW 0", "ARRAY_NEW 1", "STRUCT_GET type=1, field=2", "ARRAY_GET 99"] {
|
||||
let code = assemble(s).unwrap();
|
||||
assert_eq!(
|
||||
decode_next(0, &code).unwrap().registry_stack_effect(&r).unwrap_err().code,
|
||||
LoadCode::InvalidReference
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_storage_encodings_and_mnemonics_are_unsupported() {
|
||||
for opcode in [0xa7u16, 0xa8, 0xaa, 0xab] {
|
||||
assert!(Op::try_from(opcode).is_err());
|
||||
let bytes = opcode.to_le_bytes();
|
||||
assert!(
|
||||
matches!(decode_next(0,&bytes),Err(DecodeError::UnknownOpcode{pc:0,opcode: actual}) if actual == opcode)
|
||||
);
|
||||
assert!(disassemble(&bytes).is_err());
|
||||
}
|
||||
for text in
|
||||
["INDEX_GUARD", "ARRAY_CHECK_LENGTH 1", "STORAGE_PUBLISH 1,2,0,1", "FIELDS_PUBLISH 1"]
|
||||
{
|
||||
assert!(assemble(text).is_err(), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_copy_encoding_effects_and_registry_categories_are_independent_oracles() {
|
||||
let bytes = [0xa9, 0, 4, 3, 2, 1];
|
||||
assert_eq!(assemble("ARRAY_COPY 16909060").unwrap(), bytes);
|
||||
assert_eq!(disassemble(&bytes).unwrap(), "ARRAY_COPY 16909060");
|
||||
let instruction = decode_next(0, &bytes).unwrap();
|
||||
assert_eq!(instruction.opcode, Op::ArrayCopy);
|
||||
assert_eq!(instruction.opcode.cycles(), 4);
|
||||
let spec = instruction.opcode.spec();
|
||||
assert_eq!((spec.imm_bytes, spec.pops, spec.pushes), (4, None, None));
|
||||
assert!(instruction.opcode.requires_registry() && spec.may_trap);
|
||||
assert!(!spec.is_safepoint && !spec.is_branch && !spec.is_terminator);
|
||||
for end in 0..6 {
|
||||
assert!(decode_next(0, &bytes[..end]).is_err());
|
||||
}
|
||||
let registry = registry();
|
||||
let bytes = assemble("ARRAY_COPY 5").unwrap();
|
||||
assert_eq!(
|
||||
decode_next(0, &bytes).unwrap().registry_stack_effect(®istry).unwrap(),
|
||||
Some(RegistryStackEffect { pops: 5, pushes: 0 })
|
||||
);
|
||||
for (id, reason) in [
|
||||
(0, LoadReason::Category),
|
||||
(4, LoadReason::Category),
|
||||
(6, LoadReason::Category),
|
||||
(99, LoadReason::TypeId),
|
||||
] {
|
||||
let bytes = assemble(&format!("ARRAY_COPY {id}")).unwrap();
|
||||
let error = decode_next(0, &bytes).unwrap().registry_stack_effect(®istry).unwrap_err();
|
||||
assert_eq!(
|
||||
(error.code, error.reason, error.pc),
|
||||
(LoadCode::InvalidReference, reason, Some(0))
|
||||
);
|
||||
}
|
||||
for text in ["ARRAY_COPY", "ARRAY_COPY -1", "ARRAY_COPY 4294967296", "ARRAY_COPY 1 2"] {
|
||||
assert!(assemble(text).is_err());
|
||||
}
|
||||
// These are legal immediate bytes, not instruction boundaries.
|
||||
let bytes = assemble("PUSH_I64 18735214094965159\nHALT").unwrap();
|
||||
assert!(disassemble(&bytes).is_ok());
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,187 @@
|
||||
//! Format authority shared by complete-buffer and bounded resumable decoding.
|
||||
use super::*;
|
||||
|
||||
pub(super) fn glyph_layout(
|
||||
entry: &AssetEntry,
|
||||
) -> Result<(TileSize, usize, usize, usize, usize, usize), String> {
|
||||
let meta = entry.metadata_as_glyph_bank()?;
|
||||
|
||||
let tile_size = match meta.tile_size {
|
||||
8 => TileSize::Size8,
|
||||
16 => TileSize::Size16,
|
||||
32 => TileSize::Size32,
|
||||
_ => return Err(format!("Invalid tile_size: {}", meta.tile_size)),
|
||||
};
|
||||
|
||||
let palette_count = meta.palette_count as usize;
|
||||
if !(1..=GLYPH_BANK_MAX_PALETTE_COUNT_V1).contains(&palette_count) {
|
||||
return Err(format!("Invalid palette_count: {}", meta.palette_count));
|
||||
}
|
||||
|
||||
let width = meta.width as usize;
|
||||
let height = meta.height as usize;
|
||||
|
||||
let logical_pixels = width.checked_mul(height).ok_or("GlyphBank dimensions overflow")?;
|
||||
let serialized_pixel_bytes = logical_pixels.div_ceil(2);
|
||||
let palette_bytes = palette_count
|
||||
.checked_mul(GLYPH_BANK_PALETTE_BYTES_PER_PALETTE)
|
||||
.ok_or("GlyphBank palette size overflow")?;
|
||||
let serialized_size = serialized_pixel_bytes
|
||||
.checked_add(palette_bytes)
|
||||
.ok_or("GlyphBank serialized size overflow")?;
|
||||
let decoded_size =
|
||||
logical_pixels.checked_add(palette_bytes).ok_or("GlyphBank decoded size overflow")?;
|
||||
|
||||
if entry.size != serialized_size as u64 {
|
||||
return Err(format!(
|
||||
"Invalid GLYPHBANK serialized size: expected {}, got {}",
|
||||
serialized_size, entry.size
|
||||
));
|
||||
}
|
||||
|
||||
if entry.decoded_size != decoded_size as u64 {
|
||||
return Err(format!(
|
||||
"Invalid GLYPHBANK decoded_size: expected {}, got {}",
|
||||
decoded_size, entry.decoded_size
|
||||
));
|
||||
}
|
||||
|
||||
Ok((tile_size, width, height, serialized_pixel_bytes, palette_count, palette_bytes))
|
||||
}
|
||||
|
||||
pub(super) fn append_pixels(pixels: &mut Vec<u8>, bytes: &[u8], logical: usize) {
|
||||
for &packed in bytes {
|
||||
if pixels.len() < logical {
|
||||
pixels.push(packed >> 4);
|
||||
}
|
||||
if pixels.len() < logical {
|
||||
pixels.push(packed & 15);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn write_palettes(
|
||||
palettes: &mut [[Color; GLYPH_BANK_COLORS_PER_PALETTE]],
|
||||
position: usize,
|
||||
bytes: &[u8],
|
||||
) {
|
||||
for (i, rgba) in bytes.as_chunks::<4>().0.iter().enumerate() {
|
||||
let at = position / 4 + i;
|
||||
palettes[at / 16][at % 16] = Color::rgba(rgba[0], rgba[1], rgba[2], rgba[3]);
|
||||
}
|
||||
}
|
||||
pub(super) fn sound_rate(entry: &AssetEntry) -> Result<u32, String> {
|
||||
Ok(entry.metadata_as_sound_bank()?.sample_rate)
|
||||
}
|
||||
// Callers split on even chunk boundaries. Only the final odd byte is ignored.
|
||||
pub(super) fn append_pcm(data: &mut Vec<i16>, bytes: &[u8]) {
|
||||
data.extend(bytes.as_chunks::<2>().0.iter().map(|p| i16::from_le_bytes(*p)));
|
||||
}
|
||||
pub(super) fn payload_size(entry: &AssetEntry, actual: usize) -> Result<(), String> {
|
||||
if actual as u64 != entry.size {
|
||||
return Err("Invalid asset payload size".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn scene_metadata(entry: &AssetEntry) -> Result<(), String> {
|
||||
entry.metadata_as_scene_bank().map(|_| ())
|
||||
}
|
||||
pub(super) fn empty_layers() -> [SceneLayer; SCENE_LAYER_COUNT_V1] {
|
||||
std::array::from_fn(|_| SceneLayer {
|
||||
active: false,
|
||||
glyph_asset_id: 0,
|
||||
tile_size: TileSize::Size8,
|
||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||
tilemap: TileMap { width: 0, height: 0, tiles: Vec::new() },
|
||||
})
|
||||
}
|
||||
pub(super) fn scene_header(bytes: &[u8]) -> Result<(), String> {
|
||||
if bytes.len() < SCENE_HEADER_BYTES_V1 {
|
||||
return Err("Buffer too small for SCENE".into());
|
||||
}
|
||||
if bytes[..4] != SCENE_PAYLOAD_MAGIC_V1 {
|
||||
return Err("Invalid SCENE magic".into());
|
||||
}
|
||||
let version = u16::from_le_bytes([bytes[4], bytes[5]]);
|
||||
if version != SCENE_PAYLOAD_VERSION_V1 {
|
||||
return Err(format!("Unsupported SCENE version: {version}"));
|
||||
}
|
||||
let count = u16::from_le_bytes([bytes[6], bytes[7]]) as usize;
|
||||
if count != SCENE_LAYER_COUNT_V1 {
|
||||
return Err(format!("Invalid SCENE layer count: {count}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn scene_layer(
|
||||
bytes: &[u8],
|
||||
position: usize,
|
||||
payload_len: u64,
|
||||
decoded: &mut usize,
|
||||
) -> Result<SceneLayer, String> {
|
||||
if bytes.len() < SCENE_LAYER_HEADER_BYTES_V1 {
|
||||
return Err("Buffer too small for SCENE layer header".into());
|
||||
}
|
||||
let u32at = |at| u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap());
|
||||
let tile_size = match bytes[5] {
|
||||
8 => TileSize::Size8,
|
||||
16 => TileSize::Size16,
|
||||
32 => TileSize::Size32,
|
||||
other => return Err(format!("Invalid SCENE tile size: {other}")),
|
||||
};
|
||||
let x = f32::from_le_bytes(bytes[8..12].try_into().unwrap());
|
||||
let y = f32::from_le_bytes(bytes[12..16].try_into().unwrap());
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
return Err("Invalid SCENE parallax_factor".into());
|
||||
}
|
||||
let width = u32at(16) as usize;
|
||||
let height = u32at(20) as usize;
|
||||
let count = u32at(24) as usize;
|
||||
let expected = width.checked_mul(height).ok_or("SCENE tile count overflow")?;
|
||||
if count != expected {
|
||||
return Err(format!(
|
||||
"Invalid SCENE tile count for layer: expected {expected}, got {count}"
|
||||
));
|
||||
}
|
||||
let end = count
|
||||
.checked_mul(SCENE_TILE_RECORD_BYTES_V1)
|
||||
.and_then(|n| position.checked_add(n))
|
||||
.ok_or("SCENE payload overflow")?;
|
||||
if end as u64 > payload_len {
|
||||
return Err("Buffer too small for SCENE tile data".into());
|
||||
}
|
||||
*decoded = decoded
|
||||
.checked_add(SCENE_DECODED_LAYER_OVERHEAD_BYTES_V1)
|
||||
.and_then(|n| count.checked_mul(size_of::<Tile>()).and_then(|b| n.checked_add(b)))
|
||||
.ok_or("SCENE decoded_size overflow")?;
|
||||
Ok(SceneLayer {
|
||||
active: bytes[0] & 1 != 0,
|
||||
glyph_asset_id: i32::from_le_bytes(bytes[1..5].try_into().unwrap()),
|
||||
tile_size,
|
||||
parallax_factor: ParallaxFactor { x, y },
|
||||
tilemap: TileMap { width, height, tiles: Vec::with_capacity(count) },
|
||||
})
|
||||
}
|
||||
pub(super) fn append_tiles(tiles: &mut Vec<Tile>, bytes: &[u8]) {
|
||||
tiles.extend(bytes.as_chunks::<SCENE_TILE_RECORD_BYTES_V1>().0.iter().map(|b| Tile {
|
||||
active: b[0] & 1 != 0,
|
||||
glyph: Glyph { glyph_id: u16::from_le_bytes([b[2], b[3]]), palette_id: b[1] },
|
||||
flip_x: b[0] & 2 != 0,
|
||||
flip_y: b[0] & 4 != 0,
|
||||
}));
|
||||
}
|
||||
pub(super) fn scene_finish(
|
||||
entry: &AssetEntry,
|
||||
position: usize,
|
||||
decoded: usize,
|
||||
) -> Result<(), String> {
|
||||
payload_size(entry, position)?;
|
||||
if decoded as u64 != entry.decoded_size {
|
||||
return Err(format!(
|
||||
"Invalid SCENE decoded_size: expected {decoded}, got {}",
|
||||
entry.decoded_size
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) mod tests;
|
||||
@@ -0,0 +1,432 @@
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
struct FileFixture(std::path::PathBuf);
|
||||
impl FileFixture {
|
||||
fn new(name: &str, bytes: &[u8]) -> Self {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("prometeu-conformance-{}-{name}", std::process::id()));
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
fn source(&self, declared_len: u64) -> Arc<RwLock<AssetsPayloadSource>> {
|
||||
Arc::new(RwLock::new(AssetsPayloadSource::from_file(self.0.clone(), 0, declared_len)))
|
||||
}
|
||||
}
|
||||
impl Drop for FileFixture {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_file(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
fn pcm_entry(size: u64) -> AssetEntry {
|
||||
AssetEntry {
|
||||
asset_id: 1,
|
||||
asset_name: "pcm".into(),
|
||||
bank_type: BankType::SOUNDS,
|
||||
offset: 0,
|
||||
size,
|
||||
decoded_size: size,
|
||||
codec: AssetCodec::None,
|
||||
metadata: json!({"sample_rate": 44100, "channels": 1}),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pcm_chunk_edges_and_odd_tails_have_explicit_baseline_outputs() {
|
||||
for len in [0, 1, 2, 3, 4095, 4096, 4097, 8191, 8192, 8193] {
|
||||
let bytes: Vec<u8> = (0..len).map(|i| if i % 2 == 0 { 0x34 } else { 0x12 }).collect();
|
||||
let entry = pcm_entry(len as u64);
|
||||
let expected = json!([[vec![0x1234_i16; len / 2], 44100, null, null]]);
|
||||
let buffer = AssetManager::decode_sound_bank_from_buffer(&entry, &bytes).unwrap();
|
||||
let reader = AssetManager::decode_sound_bank_from_reader(&entry, &mut &bytes[..]).unwrap();
|
||||
let source = Arc::new(RwLock::new(AssetsPayloadSource::from_bytes(bytes)));
|
||||
let production = AssetManager::perform_load_sound_bank(&entry, source.clone()).unwrap();
|
||||
assert_eq!(sound_snapshot(&buffer), expected, "buffer len={len}");
|
||||
assert_eq!(sound_snapshot(&reader), expected, "reader len={len}");
|
||||
assert_eq!(sound_snapshot(&production), expected, "legacy load len={len}");
|
||||
assert_eq!(
|
||||
resumable::conformance_result(&entry, &source).unwrap(),
|
||||
expected,
|
||||
"resumable len={len}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn physically_truncated_pcm_file_is_rejected_by_both_modes() {
|
||||
// Two actual bytes, three declared bytes: the missing byte is an odd tail.
|
||||
// The approved rule rejects missing declared bytes, including an odd tail.
|
||||
let fixture = FileFixture::new("truncated-pcm", &[0x34, 0x12]);
|
||||
let entry = pcm_entry(3);
|
||||
let source = fixture.source(3);
|
||||
assert!(AssetManager::perform_load_sound_bank(&entry, source.clone()).is_err());
|
||||
assert!(resumable::conformance_result(&entry, &source).is_err());
|
||||
// With the declared byte physically present, both accept and ignore it.
|
||||
std::fs::write(&fixture.0, [0x34, 0x12, 0xff]).unwrap();
|
||||
let expected = json!([[[0x1234], 44100, null, null]]);
|
||||
assert_eq!(resumable::conformance_result(&entry, &source).unwrap(), expected);
|
||||
assert_eq!(
|
||||
sound_snapshot(&AssetManager::perform_load_sound_bank(&entry, source.clone()).unwrap()),
|
||||
expected
|
||||
);
|
||||
// Memory carriers reject the range before either decoder can accept it.
|
||||
let memory = Arc::new(RwLock::new(AssetsPayloadSource::from_bytes(vec![0x34, 0x12])));
|
||||
assert!(AssetManager::perform_load_sound_bank(&entry, memory.clone()).is_err());
|
||||
assert!(resumable::conformance_result(&entry, &memory).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn physically_short_scene_file_is_rejected_by_both_modes() {
|
||||
// Minimal scene: four empty layers, 12-byte header + 4 * 32-byte headers.
|
||||
let mut bytes = vec![0_u8; 140];
|
||||
bytes[..8].copy_from_slice(&[b'S', b'C', b'N', b'E', 1, 0, 4, 0]);
|
||||
for start in [12, 44, 76, 108] {
|
||||
bytes[start + 5] = 8;
|
||||
}
|
||||
let fixture = FileFixture::new("short-scene", &bytes);
|
||||
let mut entry = AssetEntry {
|
||||
asset_id: 2,
|
||||
asset_name: "scene".into(),
|
||||
bank_type: BankType::SCENE,
|
||||
offset: 0,
|
||||
size: 141,
|
||||
decoded_size: 64,
|
||||
codec: AssetCodec::None,
|
||||
metadata: json!({}),
|
||||
};
|
||||
let expected = json!(vec![json!([false, 0, 8, 0.0, 0.0, 0, 0, []]); 4]);
|
||||
let source = fixture.source(141);
|
||||
assert!(AssetManager::perform_load_scene_bank(&entry, source.clone()).is_err());
|
||||
assert!(resumable::conformance_result(&entry, &source).is_err());
|
||||
// Exact physical/declared size is accepted by both.
|
||||
entry.size = 140;
|
||||
assert_eq!(resumable::conformance_result(&entry, &source).unwrap(), expected);
|
||||
assert_eq!(
|
||||
scene_snapshot(&AssetManager::perform_load_scene_bank(&entry, source.clone()).unwrap()),
|
||||
expected
|
||||
);
|
||||
// An actual trailing byte is rejected by both.
|
||||
entry.size = 141;
|
||||
bytes.push(0);
|
||||
std::fs::write(&fixture.0, bytes).unwrap();
|
||||
assert!(AssetManager::perform_load_scene_bank(&entry, source.clone()).is_err());
|
||||
assert!(resumable::conformance_result(&entry, &source).is_err());
|
||||
}
|
||||
|
||||
// Every mode sees the same declared slice, just as it does in production.
|
||||
fn check_case(name: &str, entry: &AssetEntry, bytes: Vec<u8>, expected: Option<Value>) {
|
||||
let source = Arc::new(RwLock::new(AssetsPayloadSource::from_bytes(bytes)));
|
||||
for mode in 0..4 {
|
||||
let result = (|| -> Result<Value, String> {
|
||||
if mode == 3 {
|
||||
return resumable::conformance_result(entry, &source);
|
||||
}
|
||||
if mode == 2 {
|
||||
return match entry.bank_type {
|
||||
BankType::GLYPH => AssetManager::perform_load_glyph_bank(entry, source.clone())
|
||||
.map(|b| glyph_snapshot(&b)),
|
||||
BankType::SOUNDS => {
|
||||
AssetManager::perform_load_sound_bank(entry, source.clone())
|
||||
.map(|b| sound_snapshot(&b))
|
||||
}
|
||||
BankType::SCENE => AssetManager::perform_load_scene_bank(entry, source.clone())
|
||||
.map(|b| scene_snapshot(&b)),
|
||||
};
|
||||
}
|
||||
let slice = source
|
||||
.read()
|
||||
.unwrap()
|
||||
.open_slice(entry.offset, entry.size)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let bytes = slice.read_all().map_err(|e| e.to_string())?;
|
||||
let mut reader = &bytes[..];
|
||||
match (entry.bank_type, mode) {
|
||||
(BankType::GLYPH, 0) => AssetManager::decode_glyph_bank_from_buffer(entry, &bytes)
|
||||
.map(|b| glyph_snapshot(&b)),
|
||||
(BankType::GLYPH, _) => {
|
||||
AssetManager::decode_glyph_bank_from_reader(entry, &mut reader)
|
||||
.map(|b| glyph_snapshot(&b))
|
||||
}
|
||||
(BankType::SOUNDS, 0) => AssetManager::decode_sound_bank_from_buffer(entry, &bytes)
|
||||
.map(|b| sound_snapshot(&b)),
|
||||
(BankType::SOUNDS, _) => {
|
||||
AssetManager::decode_sound_bank_from_reader(entry, &mut reader)
|
||||
.map(|b| sound_snapshot(&b))
|
||||
}
|
||||
(BankType::SCENE, 0) => AssetManager::decode_scene_bank_from_buffer(entry, &bytes)
|
||||
.map(|b| scene_snapshot(&b)),
|
||||
(BankType::SCENE, _) => {
|
||||
AssetManager::decode_scene_bank_from_reader(entry, &mut reader)
|
||||
.map(|b| scene_snapshot(&b))
|
||||
}
|
||||
}
|
||||
})();
|
||||
assert_eq!(result.ok(), expected, "{name}, mode={mode}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyph_layout_palette_nibbles_and_chunk_boundaries() {
|
||||
for pixels in [0_usize, 1, 2, 8191, 8192, 8193, 16385] {
|
||||
for palettes in [1, 3, 64] {
|
||||
let mut bytes = vec![0x12; pixels.div_ceil(2)];
|
||||
bytes.extend(std::iter::repeat_n([0x12, 0x34, 0x56, 0x78], palettes * 16).flatten());
|
||||
let entry = AssetEntry {
|
||||
asset_id: 1,
|
||||
asset_name: "glyph".into(),
|
||||
bank_type: BankType::GLYPH,
|
||||
offset: 0,
|
||||
size: bytes.len() as u64,
|
||||
decoded_size: (pixels + palettes * 64) as u64,
|
||||
codec: AssetCodec::None,
|
||||
metadata: json!({"tile_size":16,"width":pixels,"height":1,"palette_count":palettes,"palette_authored":palettes}),
|
||||
};
|
||||
let expected = json!([
|
||||
16,
|
||||
pixels,
|
||||
1,
|
||||
(0..pixels).map(|i| 1 + i % 2).collect::<Vec<_>>(),
|
||||
vec![vec![0x12345678_u32; 16]; palettes]
|
||||
]);
|
||||
check_case("glyph-valid", &entry, bytes.clone(), Some(expected));
|
||||
for (key, value) in [
|
||||
("tile_size", json!(7)),
|
||||
("palette_count", json!(0)),
|
||||
("palette_count", json!(65)),
|
||||
("width", json!(-1)),
|
||||
("height", json!("bad")),
|
||||
] {
|
||||
let mut invalid = entry.clone();
|
||||
invalid.metadata[key] = value;
|
||||
check_case(key, &invalid, bytes.clone(), None);
|
||||
}
|
||||
let mut invalid = entry.clone();
|
||||
invalid.decoded_size += 1;
|
||||
check_case("glyph-decoded-size", &invalid, bytes.clone(), None);
|
||||
let mut invalid = entry.clone();
|
||||
invalid.size += 1;
|
||||
let mut extra = bytes.clone();
|
||||
extra.push(0);
|
||||
check_case("glyph-trailing", &invalid, extra, None);
|
||||
bytes.pop();
|
||||
check_case("glyph-truncated", &entry, bytes, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn empty_scene() -> (AssetEntry, Vec<u8>, Value) {
|
||||
let mut bytes = vec![0_u8; 140];
|
||||
bytes[..8].copy_from_slice(&[b'S', b'C', b'N', b'E', 1, 0, 4, 0]);
|
||||
for start in [12, 44, 76, 108] {
|
||||
bytes[start + 5] = 8;
|
||||
}
|
||||
let entry = AssetEntry {
|
||||
asset_id: 2,
|
||||
asset_name: "scene".into(),
|
||||
bank_type: BankType::SCENE,
|
||||
offset: 0,
|
||||
size: 140,
|
||||
decoded_size: 64,
|
||||
codec: AssetCodec::None,
|
||||
metadata: json!({}),
|
||||
};
|
||||
(entry, bytes, json!(vec![json!([false, 0, 8, 0.0, 0.0, 0, 0, []]); 4]))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scene_header_ranges_nonfinite_and_truncation_corpus() {
|
||||
let (entry, bytes, expected) = empty_scene();
|
||||
check_case("empty-scene", &entry, bytes.clone(), Some(expected));
|
||||
for end in 0..bytes.len() {
|
||||
let mut e = entry.clone();
|
||||
e.size = end as u64;
|
||||
check_case("scene-every-truncation", &e, bytes[..end].to_vec(), None);
|
||||
}
|
||||
for (offset, value) in [(0, 0xff), (4, 2), (6, 3), (17, 7), (36, 1)] {
|
||||
let mut invalid = bytes.clone();
|
||||
invalid[offset] = value;
|
||||
check_case("scene-invalid-header-field", &entry, invalid, None);
|
||||
}
|
||||
for offset in [20, 24] {
|
||||
for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let mut invalid = bytes.clone();
|
||||
invalid[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
|
||||
check_case("scene-nonfinite", &entry, invalid, None);
|
||||
}
|
||||
}
|
||||
let mut invalid = bytes.clone();
|
||||
for offset in [28, 32, 36] {
|
||||
invalid[offset..offset + 4].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
}
|
||||
check_case("scene-dimensions-overflow-or-count-mismatch", &entry, invalid, None);
|
||||
let mut invalid = bytes.clone();
|
||||
for offset in [28, 32, 36] {
|
||||
invalid[offset..offset + 4].copy_from_slice(&1_u32.to_le_bytes());
|
||||
}
|
||||
// Four layer headers no longer fit after the declared tile consumes bytes.
|
||||
check_case("scene-tile-range", &entry, invalid, None);
|
||||
let mut sequence_metadata = entry.clone();
|
||||
sequence_metadata.metadata = json!([]);
|
||||
check_case(
|
||||
"scene-empty-sequence-metadata",
|
||||
&sequence_metadata,
|
||||
bytes.clone(),
|
||||
Some(empty_scene().2),
|
||||
);
|
||||
let mut e = entry.clone();
|
||||
e.decoded_size += 1;
|
||||
check_case("scene-decoded-size", &e, bytes.clone(), None);
|
||||
e = entry.clone();
|
||||
e.size += 1;
|
||||
let mut trailing = bytes.clone();
|
||||
trailing.push(0);
|
||||
check_case("scene-trailing", &e, trailing, None);
|
||||
for metadata in [json!(null), json!("bad")] {
|
||||
e = entry.clone();
|
||||
e.metadata = metadata;
|
||||
check_case("scene-metadata", &e, bytes.clone(), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scene_tile_chunk_edges_flags_and_reserved_bytes() {
|
||||
for count in [1_usize, 1023, 1024, 1025, 2049] {
|
||||
let (mut entry, mut bytes, mut expected) = empty_scene();
|
||||
bytes[12] = 0xff; // Only the active flag is meaningful.
|
||||
bytes[13..17].copy_from_slice(&(-7_i32).to_le_bytes());
|
||||
bytes[17] = 32;
|
||||
bytes[18..20].copy_from_slice(&[0xff; 2]); // Reserved fields are ignored.
|
||||
bytes[20..24].copy_from_slice(&(-0.5_f32).to_le_bytes());
|
||||
bytes[24..28].copy_from_slice(&2.0_f32.to_le_bytes());
|
||||
bytes[28..32].copy_from_slice(&(count as u32).to_le_bytes());
|
||||
bytes[32..36].copy_from_slice(&1_u32.to_le_bytes());
|
||||
bytes[36..40].copy_from_slice(&(count as u32).to_le_bytes());
|
||||
bytes.splice(44..44, std::iter::repeat_n([0xff, 255, 0x34, 0x12], count).flatten());
|
||||
entry.size = bytes.len() as u64;
|
||||
entry.decoded_size += (count * size_of::<Tile>()) as u64;
|
||||
expected[0] = json!([
|
||||
true,
|
||||
-7,
|
||||
32,
|
||||
-0.5,
|
||||
2.0,
|
||||
count,
|
||||
1,
|
||||
vec![(true, 0x1234, 255, true, true); count]
|
||||
]);
|
||||
check_case("scene-chunks", &entry, bytes, Some(expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pcm_metadata_and_source_range_corpus() {
|
||||
for metadata in [
|
||||
json!(null),
|
||||
json!({}),
|
||||
json!({"sample_rate":-1,"channels":1}),
|
||||
json!({"sample_rate":44100,"channels":"bad"}),
|
||||
] {
|
||||
let mut e = pcm_entry(2);
|
||||
e.metadata = metadata;
|
||||
check_case("pcm-metadata", &e, vec![0x34, 0x12], None);
|
||||
}
|
||||
// These fields are currently descriptive, not extra PCM layout constraints.
|
||||
let mut e = pcm_entry(2);
|
||||
e.metadata = json!({"sample_rate":0,"channels":0});
|
||||
e.decoded_size = 999;
|
||||
check_case(
|
||||
"pcm-permissive-metadata",
|
||||
&e,
|
||||
vec![0x34, 0x12],
|
||||
Some(json!([[[0x1234], 0, null, null]])),
|
||||
);
|
||||
for offset in [1, u64::MAX] {
|
||||
let mut e = pcm_entry(2);
|
||||
e.offset = offset;
|
||||
check_case("source-range", &e, vec![0x34, 0x12], None);
|
||||
}
|
||||
let mut e = pcm_entry(2);
|
||||
e.size = u64::MAX;
|
||||
check_case("source-size-overflow", &e, vec![0x34, 0x12], None);
|
||||
}
|
||||
|
||||
pub(in crate::asset) fn glyph_snapshot(bank: &GlyphBank) -> Value {
|
||||
json!([
|
||||
bank.tile_size as u8,
|
||||
bank.width,
|
||||
bank.height,
|
||||
bank.pixel_indices,
|
||||
bank.palettes
|
||||
.iter()
|
||||
.map(|p| p.iter().map(|c| c.raw()).collect::<Vec<_>>())
|
||||
.collect::<Vec<_>>()
|
||||
])
|
||||
}
|
||||
pub(in crate::asset) fn sound_snapshot(bank: &SoundBank) -> Value {
|
||||
json!(
|
||||
bank.samples
|
||||
.iter()
|
||||
.map(|s| (&s.data, s.sample_rate, s.loop_start, s.loop_end))
|
||||
.collect::<Vec<_>>()
|
||||
)
|
||||
}
|
||||
pub(in crate::asset) fn scene_snapshot(bank: &SceneBank) -> Value {
|
||||
json!(
|
||||
bank.layers
|
||||
.iter()
|
||||
.map(|l| json!([
|
||||
l.active,
|
||||
l.glyph_asset_id,
|
||||
l.tile_size as u8,
|
||||
l.parallax_factor.x,
|
||||
l.parallax_factor.y,
|
||||
l.tilemap.width,
|
||||
l.tilemap.height,
|
||||
l.tilemap
|
||||
.tiles
|
||||
.iter()
|
||||
.map(|t| (t.active, t.glyph.glyph_id, t.glyph.palette_id, t.flip_x, t.flip_y))
|
||||
.collect::<Vec<_>>()
|
||||
]))
|
||||
.collect::<Vec<_>>()
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_scene_arithmetic_rejects_overflow_before_allocating() {
|
||||
let (_, bytes, _) = empty_scene();
|
||||
let mut header = bytes[12..44].to_vec();
|
||||
header[16..20].copy_from_slice(&1_u32.to_le_bytes());
|
||||
header[20..24].copy_from_slice(&1_u32.to_le_bytes());
|
||||
header[24..28].copy_from_slice(&1_u32.to_le_bytes());
|
||||
assert!(scene_layer(&header, usize::MAX, u64::MAX, &mut 0).is_err());
|
||||
let mut decoded = usize::MAX;
|
||||
assert!(scene_layer(&header, 44, 48, &mut decoded).is_err());
|
||||
assert!(scene_layer(&header, 44, 47, &mut 0).is_err());
|
||||
assert!(scene_layer(&header[..31], 44, 48, &mut 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn physically_truncated_glyph_palette_is_rejected_by_both_modes() {
|
||||
let fixture = FileFixture::new("truncated-glyph", &[0; 63]);
|
||||
let entry = AssetEntry {
|
||||
asset_id: 3,
|
||||
asset_name: "empty-glyph".into(),
|
||||
bank_type: BankType::GLYPH,
|
||||
offset: 0,
|
||||
size: 64,
|
||||
decoded_size: 64,
|
||||
codec: AssetCodec::None,
|
||||
metadata: json!({"tile_size":8,"width":0,"height":0,"palette_count":1,"palette_authored":1}),
|
||||
};
|
||||
let source = fixture.source(64);
|
||||
assert!(AssetManager::perform_load_glyph_bank(&entry, source.clone()).is_err());
|
||||
assert!(resumable::conformance_result(&entry, &source).is_err());
|
||||
std::fs::write(&fixture.0, [0; 64]).unwrap();
|
||||
let expected = json!([8, 0, 0, [], vec![vec![0; 16]]]);
|
||||
assert_eq!(
|
||||
glyph_snapshot(&AssetManager::perform_load_glyph_bank(&entry, source.clone()).unwrap()),
|
||||
expected
|
||||
);
|
||||
assert_eq!(resumable::conformance_result(&entry, &source).unwrap(), expected);
|
||||
}
|
||||
@@ -0,0 +1,572 @@
|
||||
//! Bounded decoding steps retain progress while the shared lane services saves.
|
||||
use super::*;
|
||||
use prometeu_hal::background_work::{BackgroundWork, WorkStep};
|
||||
use prometeu_hal::cartridge::AssetsPayloadReader;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Resources {
|
||||
handles: Arc<RwLock<HandleTable>>,
|
||||
generations: Arc<RwLock<TargetGenerationTable>>,
|
||||
source: Arc<RwLock<AssetsPayloadSource>>,
|
||||
telemetry: Arc<Mutex<AssetPipelineTelemetryState>>,
|
||||
gfx: BankPolicy<GlyphBank>,
|
||||
sound: BankPolicy<SoundBank>,
|
||||
scene: BankPolicy<SceneBank>,
|
||||
}
|
||||
impl Resources {
|
||||
pub(super) fn new(m: &AssetManager) -> Self {
|
||||
Self {
|
||||
handles: m.handles.clone(),
|
||||
generations: m.target_generations.clone(),
|
||||
source: m.assets_data.clone(),
|
||||
telemetry: m.pipeline_telemetry.clone(),
|
||||
gfx: m.gfx_policy.clone(),
|
||||
sound: m.sound_policy.clone(),
|
||||
scene: m.scene_policy.clone(),
|
||||
}
|
||||
}
|
||||
fn current(&self, job: &AssetLoadJob) -> bool {
|
||||
AssetManager::is_current_target_generation(
|
||||
&self.generations,
|
||||
job.slot,
|
||||
job.request_generation,
|
||||
)
|
||||
}
|
||||
}
|
||||
pub(super) fn schedule(
|
||||
queue: Arc<AssetLoadQueue>,
|
||||
lane: Arc<dyn BackgroundWork>,
|
||||
resources: Resources,
|
||||
) {
|
||||
{
|
||||
let mut state = queue.state.lock().unwrap();
|
||||
if state.scheduled || state.shutdown {
|
||||
return;
|
||||
}
|
||||
state.scheduled = true;
|
||||
}
|
||||
let owner = queue.clone();
|
||||
let failure_queue = queue.clone();
|
||||
let failures = resources.clone();
|
||||
let mut active: Option<(AssetLoadJob, Decoder, Instant)> = None;
|
||||
if lane
|
||||
.submit_asset(Box::new(move |canceled| {
|
||||
if canceled || owner.state.lock().unwrap().shutdown {
|
||||
let mut state = owner.state.lock().unwrap();
|
||||
state.scheduled = false;
|
||||
state.active = None;
|
||||
return WorkStep::Failed;
|
||||
}
|
||||
if active.is_none() {
|
||||
let job = {
|
||||
let mut state = owner.state.lock().unwrap();
|
||||
match state.pending.pop_front() {
|
||||
Some(job) => {
|
||||
state.active = Some(job.clone());
|
||||
job
|
||||
}
|
||||
None => {
|
||||
state.scheduled = false;
|
||||
return WorkStep::Complete;
|
||||
}
|
||||
}
|
||||
};
|
||||
if !resources.current(&job) {
|
||||
resources.telemetry.lock().unwrap().record_stale_discard();
|
||||
owner.complete_active(job.handle_id, job.request_generation);
|
||||
return WorkStep::Yield;
|
||||
}
|
||||
if let Some(handle) = resources.handles.write().unwrap().get_mut(&job.handle_id) {
|
||||
handle.status = LoadStatus::LOADING;
|
||||
handle.progress = ASSET_PROGRESS_LOADING;
|
||||
}
|
||||
let start = Instant::now();
|
||||
resources.telemetry.lock().unwrap().record_started(0);
|
||||
match Decoder::new(&job.entry, &resources.source) {
|
||||
Ok(decoder) => active = Some((job, decoder, start)),
|
||||
Err(_) => {
|
||||
AssetManager::complete_load_job(
|
||||
&resources.handles,
|
||||
&job,
|
||||
LoadStatus::ERROR,
|
||||
);
|
||||
AssetManager::record_load_job_finished(
|
||||
&resources.telemetry,
|
||||
&job,
|
||||
start,
|
||||
LoadStatus::ERROR,
|
||||
);
|
||||
owner.complete_active(job.handle_id, job.request_generation);
|
||||
return WorkStep::Yield;
|
||||
}
|
||||
}
|
||||
return WorkStep::Yield;
|
||||
}
|
||||
let (job, decoder, start) = active.as_mut().unwrap();
|
||||
if !resources.current(job) {
|
||||
resources.telemetry.lock().unwrap().record_stale_discard();
|
||||
owner.complete_active(job.handle_id, job.request_generation);
|
||||
active = None;
|
||||
return WorkStep::Yield;
|
||||
}
|
||||
match decoder.step() {
|
||||
Ok(None) => WorkStep::Yield,
|
||||
outcome => {
|
||||
let generations = resources.generations.read().unwrap();
|
||||
let status = if let Ok(Some(bank)) = outcome {
|
||||
if generations.get(&job.slot).copied().unwrap_or(0)
|
||||
== job.request_generation
|
||||
{
|
||||
match bank {
|
||||
Decoded::Glyph(bank) => {
|
||||
let resident = resources.gfx.put_resident(
|
||||
job.asset_id,
|
||||
Arc::new(bank),
|
||||
job.entry.decoded_size as usize,
|
||||
);
|
||||
resources.gfx.stage(
|
||||
job.handle_id,
|
||||
resident,
|
||||
job.entry.decoded_size as usize,
|
||||
);
|
||||
}
|
||||
Decoded::Sound(bank) => {
|
||||
let resident = resources.sound.put_resident(
|
||||
job.asset_id,
|
||||
Arc::new(bank),
|
||||
job.entry.decoded_size as usize,
|
||||
);
|
||||
resources.sound.stage(
|
||||
job.handle_id,
|
||||
resident,
|
||||
job.entry.decoded_size as usize,
|
||||
);
|
||||
}
|
||||
Decoded::Scene(bank) => {
|
||||
let resident = resources.scene.put_resident(
|
||||
job.asset_id,
|
||||
Arc::new(bank),
|
||||
job.entry.decoded_size as usize,
|
||||
);
|
||||
resources.scene.stage(
|
||||
job.handle_id,
|
||||
resident,
|
||||
job.entry.decoded_size as usize,
|
||||
);
|
||||
}
|
||||
}
|
||||
LoadStatus::READY
|
||||
} else {
|
||||
LoadStatus::ERROR
|
||||
}
|
||||
} else {
|
||||
LoadStatus::ERROR
|
||||
};
|
||||
drop(generations);
|
||||
AssetManager::complete_load_job(&resources.handles, job, status);
|
||||
AssetManager::record_load_job_finished(
|
||||
&resources.telemetry,
|
||||
job,
|
||||
*start,
|
||||
status,
|
||||
);
|
||||
owner.complete_active(job.handle_id, job.request_generation);
|
||||
active = None;
|
||||
WorkStep::Yield
|
||||
}
|
||||
}
|
||||
}))
|
||||
.is_err()
|
||||
{
|
||||
let mut state = failure_queue.state.lock().unwrap();
|
||||
state.scheduled = false;
|
||||
for job in state.pending.drain(..) {
|
||||
AssetManager::complete_load_job(&failures.handles, &job, LoadStatus::ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
enum Decoded {
|
||||
Glyph(GlyphBank),
|
||||
Sound(SoundBank),
|
||||
Scene(SceneBank),
|
||||
}
|
||||
enum State {
|
||||
Glyph {
|
||||
bank: GlyphBank,
|
||||
packed: usize,
|
||||
position: usize,
|
||||
palette_bytes: usize,
|
||||
palette_position: usize,
|
||||
},
|
||||
Sound {
|
||||
sample_rate: u32,
|
||||
data: Vec<i16>,
|
||||
remaining: usize,
|
||||
},
|
||||
Scene {
|
||||
layers: [SceneLayer; SCENE_LAYER_COUNT_V1],
|
||||
layer: usize,
|
||||
tiles_left: usize,
|
||||
header: bool,
|
||||
decoded: usize,
|
||||
},
|
||||
Done,
|
||||
}
|
||||
struct Decoder {
|
||||
reader: AssetsPayloadReader,
|
||||
entry: AssetEntry,
|
||||
state: State,
|
||||
position: usize,
|
||||
}
|
||||
impl Decoder {
|
||||
fn new(entry: &AssetEntry, source: &Arc<RwLock<AssetsPayloadSource>>) -> Result<Self, String> {
|
||||
let reader = source
|
||||
.read()
|
||||
.unwrap()
|
||||
.open_slice(entry.offset, entry.size)
|
||||
.map_err(|e| e.to_string())?
|
||||
.open_reader()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let state = match entry.bank_type {
|
||||
BankType::GLYPH => {
|
||||
let (tile_size, width, height, packed, palette_count, palette_bytes) =
|
||||
AssetManager::decode_glyph_bank_layout(entry)?;
|
||||
State::Glyph {
|
||||
bank: GlyphBank {
|
||||
tile_size,
|
||||
width,
|
||||
height,
|
||||
pixel_indices: Vec::with_capacity(width * height),
|
||||
palettes: vec![[Color::BLACK; 16]; palette_count],
|
||||
},
|
||||
packed,
|
||||
position: 0,
|
||||
palette_bytes,
|
||||
palette_position: 0,
|
||||
}
|
||||
}
|
||||
BankType::SOUNDS => {
|
||||
let sample_rate = decode::sound_rate(entry)?;
|
||||
State::Sound {
|
||||
sample_rate,
|
||||
data: Vec::with_capacity(entry.size as usize / 2),
|
||||
remaining: entry.size as usize,
|
||||
}
|
||||
}
|
||||
BankType::SCENE => {
|
||||
decode::scene_metadata(entry)?;
|
||||
State::Scene {
|
||||
layers: decode::empty_layers(),
|
||||
layer: 0,
|
||||
tiles_left: 0,
|
||||
header: false,
|
||||
decoded: 0,
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(Self { reader, entry: entry.clone(), state, position: 0 })
|
||||
}
|
||||
fn step(&mut self) -> Result<Option<Decoded>, String> {
|
||||
let mut bytes = [0; 4096];
|
||||
match &mut self.state {
|
||||
State::Glyph { bank, packed, position, palette_bytes, palette_position } => {
|
||||
if *position < *packed {
|
||||
let n = (*packed - *position).min(bytes.len());
|
||||
self.reader.read_exact(&mut bytes[..n]).map_err(|e| e.to_string())?;
|
||||
decode::append_pixels(
|
||||
&mut bank.pixel_indices,
|
||||
&bytes[..n],
|
||||
bank.width * bank.height,
|
||||
);
|
||||
*position += n;
|
||||
return Ok(None);
|
||||
}
|
||||
if *palette_position < *palette_bytes {
|
||||
let n = (*palette_bytes - *palette_position).min(bytes.len());
|
||||
self.reader.read_exact(&mut bytes[..n]).map_err(|e| e.to_string())?;
|
||||
decode::write_palettes(&mut bank.palettes, *palette_position, &bytes[..n]);
|
||||
*palette_position += n;
|
||||
return Ok(None);
|
||||
}
|
||||
let State::Glyph { bank, .. } = std::mem::replace(&mut self.state, State::Done)
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
Ok(Some(Decoded::Glyph(bank)))
|
||||
}
|
||||
State::Sound { sample_rate, data, remaining } => {
|
||||
if *remaining > 0 {
|
||||
let n = (*remaining).min(bytes.len());
|
||||
self.reader.read_exact(&mut bytes[..n]).map_err(|e| e.to_string())?;
|
||||
decode::append_pcm(data, &bytes[..n]);
|
||||
*remaining -= n;
|
||||
return Ok(None);
|
||||
}
|
||||
let rate = *sample_rate;
|
||||
let data = std::mem::take(data);
|
||||
self.state = State::Done;
|
||||
Ok(Some(Decoded::Sound(SoundBank::new(vec![Arc::new(Sample::new(rate, data))]))))
|
||||
}
|
||||
State::Scene { layers, layer, tiles_left, header, decoded } => {
|
||||
if !*header {
|
||||
self.reader
|
||||
.read_exact(&mut bytes[..SCENE_HEADER_BYTES_V1])
|
||||
.map_err(|e| e.to_string())?;
|
||||
decode::scene_header(&bytes[..SCENE_HEADER_BYTES_V1])?;
|
||||
self.position += SCENE_HEADER_BYTES_V1;
|
||||
*header = true;
|
||||
return Ok(None);
|
||||
}
|
||||
if *tiles_left > 0 {
|
||||
let n = (*tiles_left).min(bytes.len() / SCENE_TILE_RECORD_BYTES_V1);
|
||||
let count = n * SCENE_TILE_RECORD_BYTES_V1;
|
||||
self.reader.read_exact(&mut bytes[..count]).map_err(|e| e.to_string())?;
|
||||
decode::append_tiles(&mut layers[*layer - 1].tilemap.tiles, &bytes[..count]);
|
||||
*tiles_left -= n;
|
||||
self.position += count;
|
||||
return Ok(None);
|
||||
}
|
||||
if *layer < layers.len() {
|
||||
self.reader
|
||||
.read_exact(&mut bytes[..SCENE_LAYER_HEADER_BYTES_V1])
|
||||
.map_err(|e| e.to_string())?;
|
||||
self.position += SCENE_LAYER_HEADER_BYTES_V1;
|
||||
layers[*layer] = decode::scene_layer(
|
||||
&bytes[..SCENE_LAYER_HEADER_BYTES_V1],
|
||||
self.position,
|
||||
self.entry.size,
|
||||
decoded,
|
||||
)?;
|
||||
let count = layers[*layer].tilemap.width * layers[*layer].tilemap.height;
|
||||
*layer += 1;
|
||||
*tiles_left = count;
|
||||
return Ok(None);
|
||||
}
|
||||
decode::scene_finish(&self.entry, self.position, *decoded)?;
|
||||
let State::Scene { layers, .. } = std::mem::replace(&mut self.state, State::Done)
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
Ok(Some(Decoded::Scene(SceneBank { layers })))
|
||||
}
|
||||
State::Done => Err("Decoder already complete".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Test-only access to the production state machine; no alternate decode rules.
|
||||
#[cfg(test)]
|
||||
pub(super) fn conformance_result(
|
||||
entry: &AssetEntry,
|
||||
source: &Arc<RwLock<AssetsPayloadSource>>,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
use std::io::Seek;
|
||||
let mut decoder = Decoder::new(entry, source)?;
|
||||
for _ in 0..100 {
|
||||
let before = decoder.reader.stream_position().unwrap();
|
||||
let result = decoder.step();
|
||||
let after = decoder.reader.stream_position().unwrap();
|
||||
assert!(after >= before && after - before <= 4096, "unbounded or rewound decode step");
|
||||
if let Some(bank) = result? {
|
||||
return Ok(match bank {
|
||||
Decoded::Glyph(bank) => super::decode::tests::glyph_snapshot(&bank),
|
||||
Decoded::Sound(bank) => super::decode::tests::sound_snapshot(&bank),
|
||||
Decoded::Scene(bank) => super::decode::tests::scene_snapshot(&bank),
|
||||
});
|
||||
}
|
||||
}
|
||||
panic!("conformance fixture exceeded its step budget")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use prometeu_hal::background_work::{AssetWork, WorkUnavailable};
|
||||
#[derive(Default)]
|
||||
struct ManualLane(Mutex<VecDeque<AssetWork>>);
|
||||
impl BackgroundWork for ManualLane {
|
||||
fn submit_asset(&self, work: AssetWork) -> Result<(), WorkUnavailable> {
|
||||
self.0.lock().unwrap().push_back(work);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl ManualLane {
|
||||
fn step(&self) -> bool {
|
||||
let Some(mut work) = self.0.lock().unwrap().pop_front() else { return false };
|
||||
if work(false) == WorkStep::Yield {
|
||||
self.0.lock().unwrap().push_back(work);
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn shared_decoder_yields_and_matches_existing_glyph_format() {
|
||||
let mut data = vec![0x12; 32];
|
||||
data.extend([255; 64]);
|
||||
let entry = AssetEntry {
|
||||
asset_id: 7,
|
||||
asset_name: "glyph".into(),
|
||||
bank_type: BankType::GLYPH,
|
||||
codec: AssetCodec::None,
|
||||
offset: 0,
|
||||
size: data.len() as u64,
|
||||
decoded_size: 128,
|
||||
metadata: serde_json::json!({"tile_size":8,"width":8,"height":8,"palette_count":1,"palette_authored":1}),
|
||||
};
|
||||
let expected = AssetManager::decode_glyph_bank_from_buffer(&entry, &data).unwrap();
|
||||
let banks = Arc::new(crate::memory_banks::MemoryBanks::new());
|
||||
let mut manager = AssetManager::new(
|
||||
vec![entry],
|
||||
AssetsPayloadSource::from_bytes(data),
|
||||
banks.clone(),
|
||||
banks.clone(),
|
||||
banks,
|
||||
);
|
||||
let lane = Arc::new(ManualLane::default());
|
||||
assert!(manager.bind_background_work(lane.clone()));
|
||||
let handle = manager.load(7, 0).unwrap();
|
||||
let mut steps = 0;
|
||||
while lane.step() {
|
||||
steps += 1;
|
||||
assert!(steps < 20);
|
||||
}
|
||||
assert!(steps >= 4);
|
||||
assert_eq!(manager.status(handle), LoadStatus::READY);
|
||||
let staging = manager.gfx_policy.staging.read().unwrap();
|
||||
let (actual, _) = staging.get(&handle).unwrap();
|
||||
assert_eq!(actual.pixel_indices, expected.pixel_indices);
|
||||
assert_eq!(actual.palettes, expected.palettes);
|
||||
}
|
||||
fn decode_in_steps(entry: &AssetEntry, bytes: Vec<u8>) -> Decoded {
|
||||
let source = Arc::new(RwLock::new(AssetsPayloadSource::from_bytes(bytes)));
|
||||
let mut decoder = Decoder::new(entry, &source).unwrap();
|
||||
for _ in 0..100 {
|
||||
if let Some(result) = decoder.step().unwrap() {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
panic!("decoder did not finish")
|
||||
}
|
||||
#[test]
|
||||
fn resumable_sound_and_scene_preserve_existing_formats() {
|
||||
let pcm: Vec<i16> = (0..5000).map(|n| n as i16 - 2500).collect();
|
||||
let bytes: Vec<u8> = pcm.iter().flat_map(|n| n.to_le_bytes()).collect();
|
||||
let entry = AssetEntry {
|
||||
asset_id: 1,
|
||||
asset_name: "pcm".into(),
|
||||
bank_type: BankType::SOUNDS,
|
||||
offset: 0,
|
||||
size: bytes.len() as u64,
|
||||
decoded_size: bytes.len() as u64,
|
||||
codec: AssetCodec::None,
|
||||
metadata: serde_json::json!({"sample_rate":44100,"channels":1}),
|
||||
};
|
||||
let Decoded::Sound(bank) = decode_in_steps(&entry, bytes) else { panic!() };
|
||||
assert_eq!(bank.samples[0].data, pcm);
|
||||
let scene = crate::asset::tests::test_scene();
|
||||
let bytes = crate::asset::tests::encode_scene_payload(&scene);
|
||||
let entry = crate::asset::tests::test_scene_asset_entry("scene", &bytes, &scene);
|
||||
let Decoded::Scene(actual) = decode_in_steps(&entry, bytes) else { panic!() };
|
||||
for (a, b) in actual.layers.iter().zip(scene.layers.iter()) {
|
||||
assert_eq!(a.active, b.active);
|
||||
assert_eq!(a.glyph_asset_id, b.glyph_asset_id);
|
||||
assert_eq!(a.tile_size, b.tile_size);
|
||||
assert_eq!(a.parallax_factor.x, b.parallax_factor.x);
|
||||
assert_eq!(a.tilemap.width, b.tilemap.width);
|
||||
assert_eq!(a.tilemap.height, b.tilemap.height);
|
||||
assert_eq!(a.tilemap.tiles.len(), b.tilemap.tiles.len());
|
||||
for (x, y) in a.tilemap.tiles.iter().zip(&b.tilemap.tiles) {
|
||||
assert_eq!(
|
||||
(x.active, x.glyph.glyph_id, x.glyph.palette_id, x.flip_x, x.flip_y),
|
||||
(y.active, y.glyph.glyph_id, y.glyph.palette_id, y.flip_x, y.flip_y)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn shared_preload_waits_for_worker_and_frame_publication() {
|
||||
let bytes = vec![0; 8192];
|
||||
let entry = AssetEntry {
|
||||
asset_id: 1,
|
||||
asset_name: "pcm".into(),
|
||||
bank_type: BankType::SOUNDS,
|
||||
offset: 0,
|
||||
size: bytes.len() as u64,
|
||||
decoded_size: bytes.len() as u64,
|
||||
codec: AssetCodec::None,
|
||||
metadata: serde_json::json!({"sample_rate":44100,"channels":1}),
|
||||
};
|
||||
let banks = Arc::new(crate::memory_banks::MemoryBanks::new());
|
||||
let mut manager = AssetManager::new(
|
||||
vec![],
|
||||
AssetsPayloadSource::empty(),
|
||||
banks.clone(),
|
||||
banks.clone(),
|
||||
banks,
|
||||
);
|
||||
let lane = Arc::new(ManualLane::default());
|
||||
assert!(manager.bind_background_work(lane.clone()));
|
||||
manager.initialize_for_cartridge(
|
||||
vec![entry],
|
||||
vec![PreloadEntry { asset_id: 1, slot: 0 }],
|
||||
AssetsPayloadSource::from_bytes(bytes),
|
||||
);
|
||||
assert_eq!(manager.preloads_ready(), Ok(false));
|
||||
while lane.step() {}
|
||||
assert_eq!(manager.preloads_ready(), Ok(false));
|
||||
manager.apply_commits();
|
||||
assert_eq!(manager.preloads_ready(), Ok(true));
|
||||
assert_eq!(manager.slot_info(SlotRef::audio(0)).asset_id, Some(1));
|
||||
}
|
||||
#[test]
|
||||
fn canceled_and_superseded_partial_decoders_never_publish() {
|
||||
use crate::memory_banks::SoundBankPoolAccess;
|
||||
let bytes = vec![0x12; 16384];
|
||||
let entry = AssetEntry {
|
||||
asset_id: 1,
|
||||
asset_name: "pcm".into(),
|
||||
bank_type: BankType::SOUNDS,
|
||||
offset: 0,
|
||||
size: bytes.len() as u64,
|
||||
decoded_size: bytes.len() as u64,
|
||||
codec: AssetCodec::None,
|
||||
metadata: serde_json::json!({"sample_rate":44100,"channels":1}),
|
||||
};
|
||||
let mut newer = entry.clone();
|
||||
newer.asset_id = 2;
|
||||
let banks = Arc::new(crate::memory_banks::MemoryBanks::new());
|
||||
let mut manager = AssetManager::new(
|
||||
vec![entry, newer],
|
||||
AssetsPayloadSource::from_bytes(bytes),
|
||||
banks.clone(),
|
||||
banks.clone(),
|
||||
banks.clone(),
|
||||
);
|
||||
let lane = Arc::new(ManualLane::default());
|
||||
assert!(manager.bind_background_work(lane.clone()));
|
||||
let handle = manager.load(1, 0).unwrap();
|
||||
assert!(lane.step());
|
||||
assert!(lane.step());
|
||||
assert_eq!(manager.status(handle), LoadStatus::LOADING);
|
||||
assert_eq!(manager.cancel(handle), AssetOpStatus::Ok);
|
||||
while lane.step() {}
|
||||
assert_eq!(manager.status(handle), LoadStatus::CANCELED);
|
||||
assert!(manager.sound_policy.staging.read().unwrap().is_empty());
|
||||
manager.apply_commits();
|
||||
assert!(banks.sound_bank_slot(0).is_none());
|
||||
let old = manager.load(1, 0).unwrap();
|
||||
assert!(lane.step());
|
||||
assert!(lane.step());
|
||||
let new = manager.load(2, 0).unwrap();
|
||||
assert_eq!(old, new); // Stable slot handle, different request generation.
|
||||
assert!(lane.step()); // Discard the in-flight old decoder.
|
||||
assert!(manager.sound_policy.staging.read().unwrap().is_empty());
|
||||
while lane.step() {}
|
||||
assert_eq!(manager.status(new), LoadStatus::READY);
|
||||
assert!(banks.sound_bank_slot(0).is_none());
|
||||
assert_eq!(manager.commit(new), AssetOpStatus::Ok);
|
||||
manager.apply_commits();
|
||||
assert_eq!(manager.slot_info(SlotRef::audio(0)).asset_id, Some(2));
|
||||
assert_eq!(banks.sound_bank_slot(0).unwrap().samples[0].data, vec![0x1212; 8192]);
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,7 @@ use prometeu_hal::sample::Sample;
|
||||
|
||||
/// State of a single playback voice (channel).
|
||||
///
|
||||
/// The Core maintains this state to provide information to the App (e.g., is_playing),
|
||||
/// but the actual real-time mixing is performed by the Host using commands.
|
||||
/// This state belongs exclusively to the mixer, which observes natural completion.
|
||||
pub struct Channel {
|
||||
/// The actual sample data being played.
|
||||
pub sample: Option<Arc<Sample>>,
|
||||
@@ -30,7 +29,7 @@ pub struct Channel {
|
||||
pub pan: u8,
|
||||
/// Loop configuration for this voice.
|
||||
pub loop_mode: LoopMode,
|
||||
/// Playback priority (used for voice stealing policies).
|
||||
/// Internal priority metadata; the guest explicitly selects its voice.
|
||||
pub priority: u8,
|
||||
}
|
||||
|
||||
@@ -64,7 +63,7 @@ pub enum AudioCommand {
|
||||
priority: u8,
|
||||
loop_mode: LoopMode,
|
||||
},
|
||||
/// Immediately stop playback on a voice.
|
||||
/// Stop playback on a voice when this command is applied.
|
||||
Stop { voice_id: usize },
|
||||
/// Update volume of an ongoing playback.
|
||||
SetVolume { voice_id: usize, volume: u8 },
|
||||
@@ -72,36 +71,65 @@ pub enum AudioCommand {
|
||||
SetPan { voice_id: usize, pan: u8 },
|
||||
/// Update pitch of an ongoing playback.
|
||||
SetPitch { voice_id: usize, pitch: f64 },
|
||||
/// Pause all audio processing.
|
||||
MasterPause,
|
||||
/// Resume audio processing.
|
||||
MasterResume,
|
||||
}
|
||||
|
||||
/// PROMETEU Audio Subsystem.
|
||||
///
|
||||
/// Models a multi-channel PCM sampler (SPU).
|
||||
/// The audio system in Prometeu is **command-based**. This means the Core
|
||||
/// doesn't generate raw audio samples; instead, it sends high-level commands
|
||||
/// (like `Play`, `Stop`, `SetVolume`) to a queue. The physical host backend
|
||||
/// (e.g., CPAL on desktop) then consumes these commands and performs the
|
||||
/// actual mixing at the native hardware sample rate.
|
||||
///
|
||||
/// ### Key Features:
|
||||
/// - **16 Simultaneous Voices**: Independent volume, pan, and pitch.
|
||||
/// - **Sample-based Synthesis**: Plays PCM data stored in SoundBanks.
|
||||
/// - **Stereo Output**: 48kHz output target.
|
||||
mod transport;
|
||||
pub use transport::{AudioDelivery, AudioTransport};
|
||||
|
||||
pub const MAX_COMMANDS_PER_FRAME: usize = 1024;
|
||||
|
||||
/// Bounded producer staging. Samples belong to staged/published commands and the
|
||||
/// mixer, never to a second playback mirror that cannot observe completion.
|
||||
pub struct Audio {
|
||||
/// Local state of the hardware voices. This state is used for logic
|
||||
/// (e.g., checking if a sound is still playing) and is synchronized with the Host.
|
||||
pub voices: [Channel; MAX_CHANNELS],
|
||||
/// Queue of pending commands to be processed by the Host mixer.
|
||||
/// This queue is typically flushed and sent to the Host once per frame.
|
||||
pub commands: Vec<AudioCommand>,
|
||||
/// Interface to access sound memory banks (ARAM).
|
||||
commands: Vec<AudioCommand>,
|
||||
/// Admission survives an early lifecycle flush of the interrupted frame.
|
||||
frame_commands_admitted: usize,
|
||||
lifecycle_commands: Vec<AudioCommand>,
|
||||
in_lifecycle: bool,
|
||||
session: Option<u32>,
|
||||
transport: AudioTransport,
|
||||
pub sound_banks: Arc<dyn SoundBankPoolAccess>,
|
||||
}
|
||||
|
||||
impl Audio {
|
||||
pub fn new(sound_banks: Arc<dyn SoundBankPoolAccess>) -> Self {
|
||||
Self {
|
||||
commands: Vec::new(),
|
||||
frame_commands_admitted: 0,
|
||||
lifecycle_commands: Vec::new(),
|
||||
in_lifecycle: false,
|
||||
session: None,
|
||||
transport: AudioTransport::default(),
|
||||
sound_banks,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn transport(&self) -> AudioTransport {
|
||||
self.transport.clone()
|
||||
}
|
||||
|
||||
fn enqueue(&mut self, voice: usize, command: AudioCommand) -> AudioOpStatus {
|
||||
if voice >= MAX_CHANNELS {
|
||||
return AudioOpStatus::VoiceInvalid;
|
||||
}
|
||||
let admitted = if self.in_lifecycle {
|
||||
self.lifecycle_commands.len()
|
||||
} else {
|
||||
self.frame_commands_admitted
|
||||
};
|
||||
if admitted >= MAX_COMMANDS_PER_FRAME {
|
||||
return AudioOpStatus::CommandLimit;
|
||||
}
|
||||
if self.in_lifecycle {
|
||||
self.lifecycle_commands.push(command);
|
||||
} else {
|
||||
self.commands.push(command);
|
||||
self.frame_commands_admitted += 1;
|
||||
}
|
||||
AudioOpStatus::Ok
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioBridge for Audio {
|
||||
fn play(
|
||||
&mut self,
|
||||
@@ -112,14 +140,23 @@ impl AudioBridge for Audio {
|
||||
pan: u8,
|
||||
pitch: f64,
|
||||
priority: u8,
|
||||
loop_mode: prometeu_hal::LoopMode,
|
||||
loop_mode: LoopMode,
|
||||
) -> AudioOpStatus {
|
||||
let lm = match loop_mode {
|
||||
prometeu_hal::LoopMode::Off => LoopMode::Off,
|
||||
prometeu_hal::LoopMode::On => LoopMode::On,
|
||||
if voice_id >= MAX_CHANNELS {
|
||||
return AudioOpStatus::VoiceInvalid;
|
||||
}
|
||||
if !pitch.is_finite() || pitch <= 0.0 {
|
||||
return AudioOpStatus::ArgRangeInvalid;
|
||||
}
|
||||
let Some(bank) = self.sound_banks.sound_bank_slot(bank_id as usize) else {
|
||||
return AudioOpStatus::BankInvalid;
|
||||
};
|
||||
self.play(bank_id, sample_id, voice_id, volume, pan, pitch, priority, lm)
|
||||
let Some(sample) = bank.samples.get(sample_id as usize).cloned() else {
|
||||
return AudioOpStatus::SampleNotFound;
|
||||
};
|
||||
self.play_sample(sample, voice_id, volume, pan, pitch, priority, loop_mode)
|
||||
}
|
||||
|
||||
fn play_sample(
|
||||
&mut self,
|
||||
sample: Arc<Sample>,
|
||||
@@ -128,156 +165,85 @@ impl AudioBridge for Audio {
|
||||
pan: u8,
|
||||
pitch: f64,
|
||||
priority: u8,
|
||||
loop_mode: prometeu_hal::LoopMode,
|
||||
) -> AudioOpStatus {
|
||||
let lm = match loop_mode {
|
||||
prometeu_hal::LoopMode::Off => LoopMode::Off,
|
||||
prometeu_hal::LoopMode::On => LoopMode::On,
|
||||
};
|
||||
self.play_sample(sample, voice_id, volume, pan, pitch, priority, lm)
|
||||
}
|
||||
fn stop(&mut self, voice_id: usize) {
|
||||
self.stop(voice_id)
|
||||
}
|
||||
fn set_volume(&mut self, voice_id: usize, volume: u8) {
|
||||
self.set_volume(voice_id, volume)
|
||||
}
|
||||
fn set_pan(&mut self, voice_id: usize, pan: u8) {
|
||||
self.set_pan(voice_id, pan)
|
||||
}
|
||||
fn set_pitch(&mut self, voice_id: usize, pitch: f64) {
|
||||
self.set_pitch(voice_id, pitch)
|
||||
}
|
||||
fn is_playing(&self, voice_id: usize) -> bool {
|
||||
self.is_playing(voice_id)
|
||||
}
|
||||
fn clear_commands(&mut self) {
|
||||
self.clear_commands()
|
||||
}
|
||||
}
|
||||
|
||||
impl Audio {
|
||||
/// Initializes the audio system with empty voices and sound bank access.
|
||||
pub fn new(sound_banks: Arc<dyn SoundBankPoolAccess>) -> Self {
|
||||
Self {
|
||||
voices: std::array::from_fn(|_| Channel::default()),
|
||||
commands: Vec::new(),
|
||||
sound_banks,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn play(
|
||||
&mut self,
|
||||
bank_id: u8,
|
||||
sample_id: u16,
|
||||
voice_id: usize,
|
||||
volume: u8,
|
||||
pan: u8,
|
||||
pitch: f64,
|
||||
priority: u8,
|
||||
loop_mode: LoopMode,
|
||||
) -> AudioOpStatus {
|
||||
if voice_id >= MAX_CHANNELS {
|
||||
return AudioOpStatus::VoiceInvalid;
|
||||
}
|
||||
|
||||
// Resolve the sample from the hardware pools
|
||||
let bank_slot = self.sound_banks.sound_bank_slot(bank_id as usize);
|
||||
if bank_slot.is_none() {
|
||||
return AudioOpStatus::BankInvalid;
|
||||
if !pitch.is_finite() || pitch <= 0.0 {
|
||||
return AudioOpStatus::ArgRangeInvalid;
|
||||
}
|
||||
|
||||
let sample =
|
||||
bank_slot.and_then(|bank| bank.samples.get(sample_id as usize).map(Arc::clone));
|
||||
|
||||
if let Some(s) = sample {
|
||||
// println!(
|
||||
// "[Audio] Resolved sample from bank {} sample {}. Playing on voice {}.",
|
||||
// bank_id, sample_id, voice_id
|
||||
// );
|
||||
self.play_sample(s, voice_id, volume, pan, pitch, priority, loop_mode)
|
||||
} else {
|
||||
AudioOpStatus::SampleNotFound
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn play_sample(
|
||||
&mut self,
|
||||
sample: Arc<Sample>,
|
||||
voice_id: usize,
|
||||
volume: u8,
|
||||
pan: u8,
|
||||
pitch: f64,
|
||||
priority: u8,
|
||||
loop_mode: LoopMode,
|
||||
) -> AudioOpStatus {
|
||||
if voice_id >= MAX_CHANNELS {
|
||||
return AudioOpStatus::VoiceInvalid;
|
||||
}
|
||||
|
||||
// Update local state
|
||||
self.voices[voice_id] = Channel {
|
||||
sample: Some(Arc::clone(&sample)),
|
||||
active: true,
|
||||
pos: 0.0,
|
||||
pitch,
|
||||
volume,
|
||||
pan,
|
||||
loop_mode,
|
||||
priority,
|
||||
};
|
||||
|
||||
// Push command to the host
|
||||
self.commands.push(AudioCommand::Play {
|
||||
sample,
|
||||
self.enqueue(
|
||||
voice_id,
|
||||
volume,
|
||||
pan,
|
||||
pitch,
|
||||
priority,
|
||||
loop_mode,
|
||||
});
|
||||
AudioOpStatus::Ok
|
||||
AudioCommand::Play { sample, voice_id, volume, pan, pitch, priority, loop_mode },
|
||||
)
|
||||
}
|
||||
|
||||
pub fn stop(&mut self, voice_id: usize) {
|
||||
if voice_id < MAX_CHANNELS {
|
||||
self.voices[voice_id].active = false;
|
||||
self.voices[voice_id].sample = None;
|
||||
self.commands.push(AudioCommand::Stop { voice_id });
|
||||
fn stop(&mut self, voice_id: usize) -> AudioOpStatus {
|
||||
self.enqueue(voice_id, AudioCommand::Stop { voice_id })
|
||||
}
|
||||
fn set_volume(&mut self, voice_id: usize, volume: u8) -> AudioOpStatus {
|
||||
self.enqueue(voice_id, AudioCommand::SetVolume { voice_id, volume })
|
||||
}
|
||||
fn set_pan(&mut self, voice_id: usize, pan: u8) -> AudioOpStatus {
|
||||
self.enqueue(voice_id, AudioCommand::SetPan { voice_id, pan })
|
||||
}
|
||||
fn set_pitch(&mut self, voice_id: usize, pitch: f64) -> AudioOpStatus {
|
||||
if voice_id >= MAX_CHANNELS {
|
||||
return AudioOpStatus::VoiceInvalid;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_volume(&mut self, voice_id: usize, volume: u8) {
|
||||
if voice_id < MAX_CHANNELS {
|
||||
self.voices[voice_id].volume = volume;
|
||||
self.commands.push(AudioCommand::SetVolume { voice_id, volume });
|
||||
if !pitch.is_finite() || pitch <= 0.0 {
|
||||
return AudioOpStatus::ArgRangeInvalid;
|
||||
}
|
||||
self.enqueue(voice_id, AudioCommand::SetPitch { voice_id, pitch })
|
||||
}
|
||||
|
||||
pub fn set_pan(&mut self, voice_id: usize, pan: u8) {
|
||||
if voice_id < MAX_CHANNELS {
|
||||
self.voices[voice_id].pan = pan;
|
||||
self.commands.push(AudioCommand::SetPan { voice_id, pan });
|
||||
}
|
||||
fn ready(&self) -> bool {
|
||||
self.transport.ready()
|
||||
}
|
||||
|
||||
pub fn set_pitch(&mut self, voice_id: usize, pitch: f64) {
|
||||
if voice_id < MAX_CHANNELS {
|
||||
self.voices[voice_id].pitch = pitch;
|
||||
self.commands.push(AudioCommand::SetPitch { voice_id, pitch });
|
||||
}
|
||||
fn begin_frame(&mut self) { /* Staging may already contain debugger steps. */
|
||||
}
|
||||
|
||||
pub fn is_playing(&self, voice_id: usize) -> bool {
|
||||
if voice_id < MAX_CHANNELS { self.voices[voice_id].active } else { false }
|
||||
fn finish_frame(&mut self) {
|
||||
let commands = std::mem::replace(&mut self.commands, self.transport.take_buffer());
|
||||
self.transport.publish(commands, false);
|
||||
self.frame_commands_admitted = 0;
|
||||
}
|
||||
|
||||
/// Clears the command queue. The Host should consume this every frame.
|
||||
pub fn clear_commands(&mut self) {
|
||||
fn abort_frame(&mut self) {
|
||||
self.commands.clear();
|
||||
self.frame_commands_admitted = 0;
|
||||
}
|
||||
fn lifecycle_ready(&self) -> bool {
|
||||
self.transport.lifecycle_ready()
|
||||
}
|
||||
fn begin_lifecycle(&mut self) {
|
||||
self.in_lifecycle = true;
|
||||
}
|
||||
fn finish_lifecycle(&mut self, success: bool) {
|
||||
self.in_lifecycle = false;
|
||||
if success {
|
||||
// Publish the earlier frame prefix first so a callback stop cannot
|
||||
// be undone by an old play on resume. Do not replenish frame quota.
|
||||
let mut commands = std::mem::replace(&mut self.commands, self.transport.take_buffer());
|
||||
commands.append(&mut self.lifecycle_commands);
|
||||
self.transport.publish(commands, true);
|
||||
} else {
|
||||
self.lifecycle_commands.clear();
|
||||
self.abort_frame();
|
||||
}
|
||||
}
|
||||
fn set_session(&mut self, session: Option<u32>) {
|
||||
if self.session != session {
|
||||
self.reset();
|
||||
self.session = session;
|
||||
}
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.abort_frame();
|
||||
self.lifecycle_commands.clear();
|
||||
self.in_lifecycle = false;
|
||||
self.transport.reset();
|
||||
}
|
||||
fn set_paused(&mut self, paused: bool) {
|
||||
self.transport.set_paused(paused);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,7 +292,154 @@ mod tests {
|
||||
let status = audio.play_sample(sample(), MAX_CHANNELS, 255, 128, 1.0, 0, LoopMode::Off);
|
||||
|
||||
assert_eq!(status, AudioOpStatus::VoiceInvalid);
|
||||
assert!(!audio.voices.iter().any(|voice| voice.active));
|
||||
assert!(audio.commands.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod control_tests {
|
||||
use super::*;
|
||||
use crate::MemoryBanks;
|
||||
|
||||
fn audio() -> Audio {
|
||||
Audio::new(Arc::new(MemoryBanks::new()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quota_is_shared_and_rejections_never_publish_partial_effects() {
|
||||
let mut audio = audio();
|
||||
for _ in 0..MAX_COMMANDS_PER_FRAME - 1 {
|
||||
assert_eq!(audio.stop(0), AudioOpStatus::Ok);
|
||||
}
|
||||
assert_eq!(audio.set_volume(15, 0), AudioOpStatus::Ok);
|
||||
assert_eq!(audio.set_pan(0, 255), AudioOpStatus::CommandLimit);
|
||||
assert_eq!(audio.set_pitch(16, f64::NAN), AudioOpStatus::VoiceInvalid);
|
||||
assert_eq!(audio.set_pitch(0, f64::NAN), AudioOpStatus::ArgRangeInvalid);
|
||||
let sample = Arc::new(Sample::new(48_000, vec![1]));
|
||||
assert_eq!(
|
||||
audio.play_sample(sample.clone(), 0, 255, 0, 1.0, 0, LoopMode::Off),
|
||||
AudioOpStatus::CommandLimit
|
||||
);
|
||||
assert_eq!(Arc::strong_count(&sample), 1);
|
||||
assert!(audio.transport.try_take().unwrap().frame.is_none());
|
||||
audio.finish_frame();
|
||||
assert!(!audio.ready());
|
||||
assert_eq!(
|
||||
audio.transport.try_take().unwrap().frame.unwrap().len(),
|
||||
MAX_COMMANDS_PER_FRAME
|
||||
);
|
||||
assert!(audio.ready());
|
||||
audio.begin_frame();
|
||||
assert_eq!(audio.stop(0), AudioOpStatus::Ok);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_and_reset_bypass_full_guest_batch_and_release_samples() {
|
||||
let mut audio = audio();
|
||||
audio.set_session(Some(1));
|
||||
let sample = Arc::new(Sample::new(48_000, vec![1]));
|
||||
let weak = Arc::downgrade(&sample);
|
||||
assert_eq!(audio.play_sample(sample, 0, 255, 0, 1.0, 0, LoopMode::On), AudioOpStatus::Ok);
|
||||
for _ in 1..MAX_COMMANDS_PER_FRAME {
|
||||
audio.stop(1);
|
||||
}
|
||||
audio.finish_frame();
|
||||
assert!(!audio.ready());
|
||||
assert!(audio.lifecycle_ready());
|
||||
audio.begin_lifecycle();
|
||||
assert_eq!(audio.stop(0), AudioOpStatus::Ok);
|
||||
audio.finish_lifecycle(true);
|
||||
audio.set_paused(true);
|
||||
let delivery = audio.transport.try_take().unwrap();
|
||||
assert!(delivery.paused);
|
||||
assert_eq!(delivery.frame.as_ref().unwrap().len(), MAX_COMMANDS_PER_FRAME);
|
||||
assert!(matches!(
|
||||
delivery.lifecycle.as_ref().unwrap()[0],
|
||||
AudioCommand::Stop { voice_id: 0 }
|
||||
));
|
||||
let old_epoch = delivery.epoch;
|
||||
drop(delivery);
|
||||
assert!(weak.upgrade().is_none(), "driver must not retain a playback mirror");
|
||||
audio.stop(0);
|
||||
audio.finish_frame();
|
||||
audio.begin_lifecycle();
|
||||
audio.stop(1);
|
||||
audio.finish_lifecycle(true);
|
||||
audio.set_session(Some(2));
|
||||
let delivery = audio.transport.try_take().unwrap();
|
||||
assert!(delivery.epoch > old_epoch);
|
||||
assert!(delivery.frame.is_none() && delivery.lifecycle.is_none());
|
||||
assert!(audio.ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_publishes_prefix_first_and_aborted_batches_are_cancelled() {
|
||||
let mut audio = audio();
|
||||
audio.set_pan(0, 17);
|
||||
audio.begin_lifecycle();
|
||||
audio.stop(1);
|
||||
audio.finish_lifecycle(true);
|
||||
let delivery = audio.transport.try_take().unwrap();
|
||||
assert!(delivery.frame.is_none());
|
||||
let lifecycle = delivery.lifecycle.unwrap();
|
||||
assert!(matches!(lifecycle[0], AudioCommand::SetPan { pan: 17, .. }));
|
||||
assert!(matches!(lifecycle[1], AudioCommand::Stop { voice_id: 1 }));
|
||||
audio.set_volume(0, 23);
|
||||
audio.finish_frame();
|
||||
let commands = audio.transport.try_take().unwrap().frame.unwrap();
|
||||
assert_eq!(commands.len(), 1);
|
||||
assert!(matches!(commands[0], AudioCommand::SetVolume { volume: 23, .. }));
|
||||
audio.stop(0);
|
||||
audio.abort_frame();
|
||||
audio.finish_frame();
|
||||
audio.begin_lifecycle();
|
||||
audio.stop(1);
|
||||
audio.finish_lifecycle(false);
|
||||
let delivery = audio.transport.try_take().unwrap();
|
||||
assert!(delivery.frame.is_none() && delivery.lifecycle.is_none());
|
||||
}
|
||||
#[test]
|
||||
fn prefix_flush_preserves_quota_and_combined_delivery_is_bounded() {
|
||||
let mut audio = audio();
|
||||
for _ in 0..MAX_COMMANDS_PER_FRAME {
|
||||
assert_eq!(audio.stop(0), AudioOpStatus::Ok);
|
||||
}
|
||||
audio.begin_lifecycle();
|
||||
for _ in 0..MAX_COMMANDS_PER_FRAME {
|
||||
assert_eq!(audio.stop(1), AudioOpStatus::Ok);
|
||||
}
|
||||
assert_eq!(audio.stop(1), AudioOpStatus::CommandLimit);
|
||||
audio.finish_lifecycle(true);
|
||||
let delivery = audio.transport.try_take().unwrap().lifecycle.unwrap();
|
||||
assert_eq!(delivery.len(), 2 * MAX_COMMANDS_PER_FRAME);
|
||||
assert!(matches!(delivery[0], AudioCommand::Stop { voice_id: 0 }));
|
||||
assert!(matches!(delivery[MAX_COMMANDS_PER_FRAME], AudioCommand::Stop { voice_id: 1 }));
|
||||
assert_eq!(audio.stop(0), AudioOpStatus::CommandLimit);
|
||||
// Resume and another pause must not replenish the interrupted frame quota.
|
||||
for _ in 0..2 {
|
||||
audio.begin_lifecycle();
|
||||
audio.stop(1);
|
||||
audio.finish_lifecycle(true);
|
||||
audio.transport.consume_silently();
|
||||
assert_eq!(audio.stop(0), AudioOpStatus::CommandLimit);
|
||||
}
|
||||
audio.finish_frame();
|
||||
assert!(audio.transport.try_take().unwrap().frame.is_none());
|
||||
assert_eq!(audio.stop(0), AudioOpStatus::Ok);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_callback_cancels_unpublished_prefix_and_its_sample_reference() {
|
||||
let mut audio = audio();
|
||||
let sample = Arc::new(Sample::new(48_000, vec![1]));
|
||||
let weak = Arc::downgrade(&sample);
|
||||
audio.play_sample(sample, 0, 255, 0, 1.0, 0, LoopMode::On);
|
||||
audio.begin_lifecycle();
|
||||
audio.stop(0);
|
||||
audio.finish_lifecycle(false);
|
||||
audio.finish_frame();
|
||||
let delivery = audio.transport.try_take().unwrap();
|
||||
assert!(delivery.frame.is_none() && delivery.lifecycle.is_none());
|
||||
assert!(weak.upgrade().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
use super::AudioCommand;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// One pending frame plus an independent lifecycle lane. Control state never
|
||||
/// competes with guest commands for capacity. The lifecycle batch can include
|
||||
/// an interrupted frame prefix (at most 1024 + 1024 commands). Only one consumer
|
||||
/// may drain it.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct AudioTransport(Arc<Mutex<Mailbox>>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct Mailbox {
|
||||
epoch: u64,
|
||||
paused: bool,
|
||||
frame: Option<Vec<AudioCommand>>,
|
||||
lifecycle: Option<Vec<AudioCommand>>,
|
||||
recycled: [Option<Vec<AudioCommand>>; 4],
|
||||
}
|
||||
|
||||
pub struct AudioDelivery {
|
||||
pub epoch: u64,
|
||||
pub paused: bool,
|
||||
pub frame: Option<Vec<AudioCommand>>,
|
||||
pub lifecycle: Option<Vec<AudioCommand>>,
|
||||
}
|
||||
|
||||
impl AudioTransport {
|
||||
/// The real-time consumer never waits for the producer's short critical section.
|
||||
pub fn try_take(&self) -> Option<AudioDelivery> {
|
||||
let mut state = self.0.try_lock().ok()?;
|
||||
Some(AudioDelivery {
|
||||
epoch: state.epoch,
|
||||
paused: state.paused,
|
||||
frame: state.frame.take(),
|
||||
lifecycle: state.lifecycle.take(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn consume_silently(&self) {
|
||||
if let Some(delivery) = self.try_take() {
|
||||
for batch in [delivery.frame, delivery.lifecycle].into_iter().flatten() {
|
||||
self.recycle_commands(batch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Main/service lane only: drop command owners and retain bounded empty storage.
|
||||
pub fn recycle_commands(&self, mut commands: Vec<AudioCommand>) {
|
||||
commands.clear();
|
||||
let mut state = self.0.lock().expect("audio mailbox");
|
||||
if let Some(slot) = state.recycled.iter_mut().find(|slot| slot.is_none()) {
|
||||
*slot = Some(commands);
|
||||
}
|
||||
// Excess empty buffers are destroyed here, never in the data callback.
|
||||
}
|
||||
|
||||
pub(super) fn take_buffer(&self) -> Vec<AudioCommand> {
|
||||
self.0
|
||||
.lock()
|
||||
.expect("audio mailbox")
|
||||
.recycled
|
||||
.iter_mut()
|
||||
.find_map(Option::take)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn ready(&self) -> bool {
|
||||
let state = self.0.lock().expect("audio mailbox");
|
||||
state.frame.is_none() && state.lifecycle.is_none()
|
||||
}
|
||||
|
||||
pub fn lifecycle_ready(&self) -> bool {
|
||||
self.0.lock().expect("audio mailbox").lifecycle.is_none()
|
||||
}
|
||||
|
||||
pub(super) fn publish(&self, commands: Vec<AudioCommand>, lifecycle: bool) {
|
||||
if commands.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut state = self.0.lock().expect("audio mailbox");
|
||||
let target = if lifecycle { &mut state.lifecycle } else { &mut state.frame };
|
||||
assert!(target.is_none(), "audio producer must respect backpressure");
|
||||
*target = Some(commands);
|
||||
}
|
||||
|
||||
pub(super) fn reset(&self) {
|
||||
let mut state = self.0.lock().expect("audio mailbox");
|
||||
state.epoch = state.epoch.checked_add(1).expect("audio epoch exhausted");
|
||||
state.frame = None;
|
||||
state.lifecycle = None;
|
||||
state.paused = false;
|
||||
}
|
||||
|
||||
pub(super) fn set_paused(&self, paused: bool) {
|
||||
self.0.lock().expect("audio mailbox").paused = paused;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn realtime_consumer_does_not_wait_for_publication_lock() {
|
||||
let transport = AudioTransport::default();
|
||||
let guard = transport.0.lock().unwrap();
|
||||
assert!(transport.try_take().is_none());
|
||||
drop(guard);
|
||||
assert!(transport.try_take().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod reuse_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn service_recycles_storage_and_releases_sample_owners() {
|
||||
use prometeu_hal::{LoopMode, sample::Sample};
|
||||
let transport = AudioTransport::default();
|
||||
let sample = Arc::new(Sample::new(48000, vec![1]));
|
||||
let weak = Arc::downgrade(&sample);
|
||||
let mut batch = Vec::with_capacity(1024);
|
||||
let allocation = batch.as_ptr();
|
||||
batch.push(AudioCommand::Play {
|
||||
sample,
|
||||
voice_id: 0,
|
||||
volume: 255,
|
||||
pan: 0,
|
||||
pitch: 1.0,
|
||||
priority: 0,
|
||||
loop_mode: LoopMode::Off,
|
||||
});
|
||||
transport.recycle_commands(batch);
|
||||
assert!(weak.upgrade().is_none());
|
||||
let reused = transport.take_buffer();
|
||||
assert_eq!(reused.as_ptr(), allocation);
|
||||
assert_eq!(reused.capacity(), 1024);
|
||||
assert!(reused.is_empty());
|
||||
for _ in 0..8 {
|
||||
transport.recycle_commands(Vec::with_capacity(16));
|
||||
}
|
||||
assert_eq!(transport.0.lock().unwrap().recycled.iter().flatten().count(), 4);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
use crate::asset::GlyphAssetSlotIndex;
|
||||
use crate::memory_banks::SceneBankPoolAccess;
|
||||
use prometeu_hal::GfxBridge;
|
||||
use prometeu_hal::glyph::Glyph;
|
||||
use prometeu_hal::scene_bank::SceneBank;
|
||||
use prometeu_hal::scene_viewport_cache::SceneViewportCache;
|
||||
use prometeu_hal::scene_viewport_resolver::{CacheRefreshRequest, SceneViewportResolver};
|
||||
use prometeu_hal::scene_viewport_resolver::{
|
||||
CacheRefreshRequest, ResolverUpdate, SceneViewportResolver,
|
||||
};
|
||||
use prometeu_hal::sprite::Sprite;
|
||||
use prometeu_hal::{
|
||||
BoundScenePacket, Camera2D, ComposerFramePacket, ComposerOpStatus, Game2DFrameComposer,
|
||||
Game2DFramePacket, GameSpritePacket, GfxBridge, HudPacket,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
const EMPTY_SPRITE: Sprite = Sprite {
|
||||
@@ -116,6 +122,7 @@ impl SpriteController {
|
||||
|
||||
pub struct FrameComposer {
|
||||
scene_bank_pool: Arc<dyn SceneBankPoolAccess>,
|
||||
glyph_slot_index: GlyphAssetSlotIndex,
|
||||
viewport_width_px: usize,
|
||||
viewport_height_px: usize,
|
||||
active_scene_id: Option<usize>,
|
||||
@@ -128,14 +135,38 @@ pub struct FrameComposer {
|
||||
sprite_controller: SpriteController,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ComposerBuffer {
|
||||
pub bound_scene: Option<BoundScenePacket>,
|
||||
pub camera: Camera2D,
|
||||
pub sprites: Vec<GameSpritePacket>,
|
||||
pub hud: HudPacket,
|
||||
}
|
||||
|
||||
impl ComposerBuffer {
|
||||
pub fn close(self) -> Game2DFramePacket {
|
||||
Game2DFramePacket::new(
|
||||
ComposerFramePacket {
|
||||
bound_scene: self.bound_scene,
|
||||
camera: self.camera,
|
||||
sprites: self.sprites,
|
||||
hud: self.hud,
|
||||
},
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl FrameComposer {
|
||||
pub fn new(
|
||||
viewport_width_px: usize,
|
||||
viewport_height_px: usize,
|
||||
scene_bank_pool: Arc<dyn SceneBankPoolAccess>,
|
||||
glyph_slot_index: GlyphAssetSlotIndex,
|
||||
) -> Self {
|
||||
Self {
|
||||
scene_bank_pool,
|
||||
glyph_slot_index,
|
||||
viewport_width_px,
|
||||
viewport_height_px,
|
||||
active_scene_id: None,
|
||||
@@ -187,6 +218,8 @@ impl FrameComposer {
|
||||
return false;
|
||||
};
|
||||
|
||||
let _ = self.resolve_glyph_slots(&scene, scene_bank_id, "bind_scene");
|
||||
|
||||
let (cache, resolver) =
|
||||
Self::build_scene_runtime(self.viewport_width_px, self.viewport_height_px, &scene);
|
||||
self.active_scene_id = Some(scene_bank_id);
|
||||
@@ -238,19 +271,54 @@ impl FrameComposer {
|
||||
self.sprite_controller.ordered_sprites()
|
||||
}
|
||||
|
||||
pub fn composer_buffer_snapshot(&self) -> ComposerBuffer {
|
||||
ComposerBuffer {
|
||||
bound_scene: self
|
||||
.active_scene_id
|
||||
.map(|scene_bank_id| BoundScenePacket { bank_id: scene_bank_id as i32 }),
|
||||
camera: Camera2D { x: self.camera_x_px, y: self.camera_y_px },
|
||||
sprites: self
|
||||
.ordered_sprites()
|
||||
.into_iter()
|
||||
.map(|sprite| GameSpritePacket {
|
||||
glyph_id: sprite.glyph.glyph_id as i32,
|
||||
palette_id: sprite.glyph.palette_id as i32,
|
||||
x: sprite.x,
|
||||
y: sprite.y,
|
||||
layer: sprite.layer as i32,
|
||||
bank_id: sprite.bank_id as i32,
|
||||
flip_x: sprite.flip_x,
|
||||
flip_y: sprite.flip_y,
|
||||
priority: sprite.priority as i32,
|
||||
})
|
||||
.collect(),
|
||||
hud: HudPacket::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn close_game2d_packet(&self) -> Game2DFramePacket {
|
||||
self.composer_buffer_snapshot().close()
|
||||
}
|
||||
|
||||
pub fn render_frame(&mut self, gfx: &mut dyn GfxBridge) {
|
||||
let ordered_sprites = self.ordered_sprites();
|
||||
gfx.load_frame_sprites(&ordered_sprites);
|
||||
|
||||
if let (Some(scene), Some(cache), Some(resolver)) =
|
||||
(self.active_scene.as_deref(), self.cache.as_mut(), self.resolver.as_mut())
|
||||
{
|
||||
if let Some(scene) = self.active_scene.as_deref() {
|
||||
let scene_bank_id = self.active_scene_id.expect("active scene id must exist");
|
||||
let resolved_glyph_slots =
|
||||
self.resolve_glyph_slots(scene, scene_bank_id, "render_frame");
|
||||
let (Some(cache), Some(resolver)) = (self.cache.as_mut(), self.resolver.as_mut())
|
||||
else {
|
||||
panic!("SCENE runtime invariant broken: active scene without cache/resolver");
|
||||
};
|
||||
let update = resolver.update(scene, self.camera_x_px, self.camera_y_px);
|
||||
Self::sync_cache_windows(cache, &update);
|
||||
Self::apply_refresh_requests(cache, scene, &update.refresh_requests);
|
||||
// `FrameComposer` owns only canonical game-frame composition.
|
||||
// Deferred `gfx.*` primitives are drained later by a separate
|
||||
// overlay/debug stage outside this service boundary.
|
||||
gfx.render_scene_from_cache(cache, &update);
|
||||
gfx.render_scene_from_cache(cache, &update, &resolved_glyph_slots);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -259,6 +327,55 @@ impl FrameComposer {
|
||||
gfx.render_no_scene_frame();
|
||||
}
|
||||
|
||||
pub fn render_game2d_frame_packet(
|
||||
&mut self,
|
||||
packet: &Game2DFramePacket,
|
||||
gfx: &mut dyn GfxBridge,
|
||||
) {
|
||||
let sprites: Vec<Sprite> =
|
||||
packet.composer.sprites.iter().map(Self::sprite_from_packet).collect();
|
||||
gfx.load_frame_sprites(&sprites);
|
||||
|
||||
let Some(bound_scene) = packet.composer.bound_scene else {
|
||||
gfx.render_no_scene_frame();
|
||||
return;
|
||||
};
|
||||
|
||||
let scene_bank_id = bound_scene.bank_id as usize;
|
||||
if self.active_scene_id != Some(scene_bank_id) && !self.bind_scene(scene_bank_id) {
|
||||
gfx.render_no_scene_frame();
|
||||
return;
|
||||
}
|
||||
|
||||
self.camera_x_px = packet.composer.camera.x;
|
||||
self.camera_y_px = packet.composer.camera.y;
|
||||
|
||||
let scene =
|
||||
self.active_scene.as_deref().expect("active scene should exist after packet bind");
|
||||
let resolved_glyph_slots = self.resolve_glyph_slots(scene, scene_bank_id, "render_packet");
|
||||
let (Some(cache), Some(resolver)) = (self.cache.as_mut(), self.resolver.as_mut()) else {
|
||||
panic!("SCENE runtime invariant broken: packet scene without cache/resolver");
|
||||
};
|
||||
let update = resolver.update(scene, self.camera_x_px, self.camera_y_px);
|
||||
Self::sync_cache_windows(cache, &update);
|
||||
Self::apply_refresh_requests(cache, scene, &update.refresh_requests);
|
||||
gfx.render_scene_from_cache(cache, &update, &resolved_glyph_slots);
|
||||
}
|
||||
|
||||
fn sprite_from_packet(sprite: &GameSpritePacket) -> Sprite {
|
||||
Sprite {
|
||||
glyph: Glyph { glyph_id: sprite.glyph_id as u16, palette_id: sprite.palette_id as u8 },
|
||||
x: sprite.x,
|
||||
y: sprite.y,
|
||||
layer: sprite.layer as u8,
|
||||
bank_id: sprite.bank_id as u8,
|
||||
active: true,
|
||||
flip_x: sprite.flip_x,
|
||||
flip_y: sprite.flip_y,
|
||||
priority: sprite.priority as u8,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_scene_runtime(
|
||||
viewport_width_px: usize,
|
||||
viewport_height_px: usize,
|
||||
@@ -284,6 +401,23 @@ impl FrameComposer {
|
||||
)
|
||||
}
|
||||
|
||||
fn resolve_glyph_slots(
|
||||
&self,
|
||||
scene: &SceneBank,
|
||||
scene_bank_id: usize,
|
||||
phase: &str,
|
||||
) -> [usize; 4] {
|
||||
std::array::from_fn(|layer_index| {
|
||||
let layer = &scene.layers[layer_index];
|
||||
self.glyph_slot_index.glyph_slot_for_asset(layer.glyph_asset_id).unwrap_or_else(|| {
|
||||
panic!(
|
||||
"SCENE dependency fatal during {}: scene_bank_id={}, layer={}, glyph_asset_id={}",
|
||||
phase, scene_bank_id, layer_index, layer.glyph_asset_id
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn apply_refresh_requests(
|
||||
cache: &mut SceneViewportCache,
|
||||
scene: &SceneBank,
|
||||
@@ -306,38 +440,96 @@ impl FrameComposer {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_cache_windows(cache: &mut SceneViewportCache, update: &ResolverUpdate) {
|
||||
for request in &update.copy_requests {
|
||||
cache.move_layer_window_to(
|
||||
request.layer_index,
|
||||
request.cache_origin_tile_x,
|
||||
request.cache_origin_tile_y,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Game2DFrameComposer for FrameComposer {
|
||||
fn begin_frame(&mut self) {
|
||||
FrameComposer::begin_frame(self);
|
||||
}
|
||||
|
||||
fn bind_scene(&mut self, scene_bank_id: usize) -> ComposerOpStatus {
|
||||
if FrameComposer::bind_scene(self, scene_bank_id) {
|
||||
ComposerOpStatus::Ok
|
||||
} else {
|
||||
ComposerOpStatus::SceneUnavailable
|
||||
}
|
||||
}
|
||||
|
||||
fn unbind_scene(&mut self) {
|
||||
FrameComposer::unbind_scene(self);
|
||||
}
|
||||
|
||||
fn set_camera(&mut self, x: i32, y: i32) -> ComposerOpStatus {
|
||||
FrameComposer::set_camera(self, x, y);
|
||||
ComposerOpStatus::Ok
|
||||
}
|
||||
|
||||
fn emit_sprite(&mut self, sprite: Sprite) -> ComposerOpStatus {
|
||||
if FrameComposer::emit_sprite(self, sprite) {
|
||||
ComposerOpStatus::Ok
|
||||
} else {
|
||||
ComposerOpStatus::SpriteOverflow
|
||||
}
|
||||
}
|
||||
|
||||
fn close_game2d_packet(&self) -> Game2DFramePacket {
|
||||
FrameComposer::close_game2d_packet(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::gfx::Gfx;
|
||||
use crate::hardware::Hardware;
|
||||
use crate::memory_banks::{
|
||||
GlyphBankPoolAccess, GlyphBankPoolInstaller, MemoryBanks, SceneBankPoolInstaller,
|
||||
};
|
||||
use prometeu_hal::asset::AssetId;
|
||||
use prometeu_hal::color::Color;
|
||||
use prometeu_hal::glyph_bank::{GlyphBank, TileSize};
|
||||
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
||||
use prometeu_hal::tile::Tile;
|
||||
use prometeu_hal::tilemap::TileMap;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
|
||||
fn make_scene() -> SceneBank {
|
||||
make_scene_with_palette(1, 1, TileSize::Size8)
|
||||
}
|
||||
|
||||
fn make_scene_with_palette(
|
||||
glyph_bank_id: u8,
|
||||
glyph_asset_id: AssetId,
|
||||
palette_id: u8,
|
||||
tile_size: TileSize,
|
||||
) -> SceneBank {
|
||||
make_scene_grid(glyph_asset_id, palette_id, tile_size, 2, 2)
|
||||
}
|
||||
|
||||
fn make_scene_grid(
|
||||
glyph_asset_id: AssetId,
|
||||
palette_id: u8,
|
||||
tile_size: TileSize,
|
||||
width: usize,
|
||||
height: usize,
|
||||
) -> SceneBank {
|
||||
let layer = SceneLayer {
|
||||
active: true,
|
||||
glyph_bank_id,
|
||||
glyph_asset_id,
|
||||
tile_size,
|
||||
parallax_factor: ParallaxFactor { x: 1.0, y: 0.5 },
|
||||
tilemap: TileMap {
|
||||
width: 2,
|
||||
height: 2,
|
||||
width,
|
||||
height,
|
||||
tiles: vec![
|
||||
Tile {
|
||||
active: true,
|
||||
@@ -345,7 +537,7 @@ mod tests {
|
||||
flip_x: false,
|
||||
flip_y: false,
|
||||
};
|
||||
4
|
||||
width * height
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -353,21 +545,35 @@ mod tests {
|
||||
SceneBank { layers: std::array::from_fn(|_| layer.clone()) }
|
||||
}
|
||||
|
||||
fn make_glyph_slot_index(bindings: &[(AssetId, usize)]) -> GlyphAssetSlotIndex {
|
||||
let index = GlyphAssetSlotIndex::new();
|
||||
let mut slots = [None; 16];
|
||||
for (asset_id, slot) in bindings {
|
||||
slots[*slot] = Some(*asset_id);
|
||||
}
|
||||
index.rebuild_from_slots(&slots);
|
||||
index
|
||||
}
|
||||
|
||||
fn make_glyph_bank(tile_size: TileSize, palette_id: u8, color: Color) -> GlyphBank {
|
||||
let size = tile_size as usize;
|
||||
let mut bank = GlyphBank::new(tile_size, size, size);
|
||||
bank.palettes[palette_id as usize][1] = color;
|
||||
for pixel in &mut bank.pixel_indices {
|
||||
*pixel = 1;
|
||||
}
|
||||
let mut bank =
|
||||
GlyphBank::with_palette_count(tile_size, size, size, palette_id as usize + 1);
|
||||
bank.palette_mut(palette_id).unwrap()[1] = color;
|
||||
bank.pixel_indices.fill(1);
|
||||
bank
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_composer_starts_unbound_with_empty_owned_state() {
|
||||
let frame_composer = FrameComposer::new(320, 180, Arc::new(MemoryBanks::new()));
|
||||
let frame_composer = FrameComposer::new(
|
||||
Hardware::W,
|
||||
Hardware::H,
|
||||
Arc::new(MemoryBanks::new()),
|
||||
make_glyph_slot_index(&[]),
|
||||
);
|
||||
|
||||
assert_eq!(frame_composer.viewport_size(), (320, 180));
|
||||
assert_eq!(frame_composer.viewport_size(), (Hardware::W, Hardware::H));
|
||||
assert_eq!(frame_composer.active_scene_id(), None);
|
||||
assert!(frame_composer.active_scene().is_none());
|
||||
assert_eq!(frame_composer.scene_status(), SceneStatus::Unbound);
|
||||
@@ -384,7 +590,8 @@ mod tests {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_scene_bank(3, Arc::new(make_scene()));
|
||||
|
||||
let frame_composer = FrameComposer::new(320, 180, banks);
|
||||
let frame_composer =
|
||||
FrameComposer::new(Hardware::W, Hardware::H, banks, make_glyph_slot_index(&[(1, 0)]));
|
||||
let scene =
|
||||
frame_composer.scene_bank_slot(3).expect("scene bank slot 3 should be resident");
|
||||
|
||||
@@ -400,7 +607,8 @@ mod tests {
|
||||
|
||||
let expected_scene =
|
||||
banks.scene_bank_slot(3).expect("scene bank slot 3 should be resident");
|
||||
let mut frame_composer = FrameComposer::new(320, 180, banks);
|
||||
let mut frame_composer =
|
||||
FrameComposer::new(Hardware::W, Hardware::H, banks, make_glyph_slot_index(&[(1, 0)]));
|
||||
|
||||
assert!(frame_composer.bind_scene(3));
|
||||
|
||||
@@ -419,7 +627,8 @@ mod tests {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_scene_bank(1, Arc::new(make_scene()));
|
||||
|
||||
let mut frame_composer = FrameComposer::new(320, 180, banks);
|
||||
let mut frame_composer =
|
||||
FrameComposer::new(Hardware::W, Hardware::H, banks, make_glyph_slot_index(&[(1, 0)]));
|
||||
assert!(frame_composer.bind_scene(1));
|
||||
|
||||
frame_composer.unbind_scene();
|
||||
@@ -433,7 +642,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn set_camera_stores_top_left_pixel_coordinates() {
|
||||
let mut frame_composer = FrameComposer::new(320, 180, Arc::new(MemoryBanks::new()));
|
||||
let mut frame_composer = FrameComposer::new(
|
||||
Hardware::W,
|
||||
Hardware::H,
|
||||
Arc::new(MemoryBanks::new()),
|
||||
make_glyph_slot_index(&[]),
|
||||
);
|
||||
|
||||
frame_composer.set_camera(-12, 48);
|
||||
|
||||
@@ -445,16 +659,22 @@ mod tests {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_scene_bank(0, Arc::new(make_scene()));
|
||||
|
||||
let mut frame_composer = FrameComposer::new(320, 180, banks);
|
||||
let mut frame_composer =
|
||||
FrameComposer::new(Hardware::W, Hardware::H, banks, make_glyph_slot_index(&[(1, 0)]));
|
||||
assert!(frame_composer.bind_scene(0));
|
||||
|
||||
let cache = frame_composer.cache().expect("cache should exist for bound scene");
|
||||
assert_eq!((cache.width(), cache.height()), (45, 27));
|
||||
assert_eq!((cache.width(), cache.height()), (65, 38));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_scene_binding_falls_back_to_no_scene_state() {
|
||||
let mut frame_composer = FrameComposer::new(320, 180, Arc::new(MemoryBanks::new()));
|
||||
let mut frame_composer = FrameComposer::new(
|
||||
Hardware::W,
|
||||
Hardware::H,
|
||||
Arc::new(MemoryBanks::new()),
|
||||
make_glyph_slot_index(&[]),
|
||||
);
|
||||
|
||||
assert!(!frame_composer.bind_scene(7));
|
||||
|
||||
@@ -463,6 +683,28 @@ mod tests {
|
||||
assert!(frame_composer.resolver().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bind_scene_panics_when_scene_dependency_is_not_resident() {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_scene_bank(0, Arc::new(make_scene()));
|
||||
|
||||
let mut frame_composer =
|
||||
FrameComposer::new(Hardware::W, Hardware::H, banks, make_glyph_slot_index(&[]));
|
||||
|
||||
let panic = catch_unwind(AssertUnwindSafe(|| frame_composer.bind_scene(0)))
|
||||
.expect_err("bind_scene should panic when dependency is missing");
|
||||
let message = if let Some(message) = panic.downcast_ref::<String>() {
|
||||
message.clone()
|
||||
} else if let Some(message) = panic.downcast_ref::<&str>() {
|
||||
(*message).to_string()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
assert!(message.contains("SCENE dependency fatal during bind_scene"));
|
||||
assert!(message.contains("glyph_asset_id=1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sprite_controller_begin_frame_resets_sprite_count_and_buckets() {
|
||||
let mut controller = SpriteController::new();
|
||||
@@ -582,7 +824,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn frame_composer_emits_ordered_sprites_for_rendering() {
|
||||
let mut frame_composer = FrameComposer::new(320, 180, Arc::new(MemoryBanks::new()));
|
||||
let mut frame_composer = FrameComposer::new(
|
||||
Hardware::W,
|
||||
Hardware::H,
|
||||
Arc::new(MemoryBanks::new()),
|
||||
make_glyph_slot_index(&[]),
|
||||
);
|
||||
frame_composer.begin_frame();
|
||||
|
||||
assert!(frame_composer.emit_sprite(Sprite {
|
||||
@@ -620,8 +867,12 @@ mod tests {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_glyph_bank(1, Arc::new(make_glyph_bank(TileSize::Size8, 3, Color::WHITE)));
|
||||
|
||||
let mut frame_composer =
|
||||
FrameComposer::new(16, 16, Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>);
|
||||
let mut frame_composer = FrameComposer::new(
|
||||
16,
|
||||
16,
|
||||
Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>,
|
||||
make_glyph_slot_index(&[]),
|
||||
);
|
||||
frame_composer.begin_frame();
|
||||
assert!(frame_composer.emit_sprite(Sprite {
|
||||
glyph: Glyph { glyph_id: 0, palette_id: 3 },
|
||||
@@ -636,8 +887,6 @@ mod tests {
|
||||
}));
|
||||
|
||||
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
||||
gfx.scene_fade_level = 31;
|
||||
gfx.hud_fade_level = 31;
|
||||
|
||||
frame_composer.render_frame(&mut gfx);
|
||||
gfx.present();
|
||||
@@ -645,19 +894,127 @@ mod tests {
|
||||
assert_eq!(gfx.front_buffer()[0], Color::WHITE.raw());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_buffer_snapshot_closes_into_game2d_packet_without_fade_state() {
|
||||
let mut frame_composer = FrameComposer::new(
|
||||
Hardware::W,
|
||||
Hardware::H,
|
||||
Arc::new(MemoryBanks::default()),
|
||||
make_glyph_slot_index(&[]),
|
||||
);
|
||||
|
||||
frame_composer.set_camera(10, 20);
|
||||
frame_composer.begin_frame();
|
||||
assert!(frame_composer.emit_sprite(Sprite {
|
||||
glyph: Glyph { glyph_id: 7, palette_id: 3 },
|
||||
x: 4,
|
||||
y: 5,
|
||||
layer: 2,
|
||||
bank_id: 1,
|
||||
active: false,
|
||||
flip_x: true,
|
||||
flip_y: false,
|
||||
priority: 9,
|
||||
}));
|
||||
|
||||
let packet = frame_composer.close_game2d_packet();
|
||||
|
||||
assert_eq!(packet.composer.bound_scene, None);
|
||||
assert_eq!(packet.composer.camera, Camera2D { x: 10, y: 20 });
|
||||
assert_eq!(packet.composer.sprites.len(), 1);
|
||||
assert_eq!(packet.composer.sprites[0].glyph_id, 7);
|
||||
assert_eq!(packet.composer.sprites[0].palette_id, 3);
|
||||
assert_eq!(packet.composer.sprites[0].layer, 2);
|
||||
assert!(packet.composer.sprites[0].flip_x);
|
||||
assert!(packet.composer.hud.commands.is_empty());
|
||||
assert!(packet.gfx2d.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn game2d_frame_composer_facade_closes_equivalent_packet() {
|
||||
let mut frame_composer = FrameComposer::new(
|
||||
Hardware::W,
|
||||
Hardware::H,
|
||||
Arc::new(MemoryBanks::default()),
|
||||
make_glyph_slot_index(&[]),
|
||||
);
|
||||
|
||||
let composer: &mut dyn Game2DFrameComposer = &mut frame_composer;
|
||||
assert_eq!(composer.set_camera(10, 20), ComposerOpStatus::Ok);
|
||||
composer.begin_frame();
|
||||
assert_eq!(
|
||||
composer.emit_sprite(Sprite {
|
||||
glyph: Glyph { glyph_id: 7, palette_id: 3 },
|
||||
x: 4,
|
||||
y: 5,
|
||||
layer: 2,
|
||||
bank_id: 1,
|
||||
active: false,
|
||||
flip_x: true,
|
||||
flip_y: false,
|
||||
priority: 9,
|
||||
}),
|
||||
ComposerOpStatus::Ok
|
||||
);
|
||||
|
||||
let packet = composer.close_game2d_packet();
|
||||
|
||||
assert_eq!(packet.composer.bound_scene, None);
|
||||
assert_eq!(packet.composer.camera, Camera2D { x: 10, y: 20 });
|
||||
assert_eq!(packet.composer.sprites.len(), 1);
|
||||
assert_eq!(packet.composer.sprites[0].glyph_id, 7);
|
||||
assert_eq!(packet.composer.sprites[0].palette_id, 3);
|
||||
assert_eq!(packet.composer.sprites[0].layer, 2);
|
||||
assert!(packet.composer.sprites[0].flip_x);
|
||||
assert!(packet.gfx2d.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_buffer_preserves_integer_layer_ordering() {
|
||||
let mut frame_composer = FrameComposer::new(
|
||||
Hardware::W,
|
||||
Hardware::H,
|
||||
Arc::new(MemoryBanks::default()),
|
||||
make_glyph_slot_index(&[]),
|
||||
);
|
||||
frame_composer.begin_frame();
|
||||
|
||||
for (glyph_id, layer, priority) in [(1, 3, 1), (2, 1, 2), (3, 1, 1), (4, 0, 9)] {
|
||||
assert!(frame_composer.emit_sprite(Sprite {
|
||||
glyph: Glyph { glyph_id, palette_id: 0 },
|
||||
x: 0,
|
||||
y: 0,
|
||||
layer,
|
||||
bank_id: 0,
|
||||
active: false,
|
||||
flip_x: false,
|
||||
flip_y: false,
|
||||
priority,
|
||||
}));
|
||||
}
|
||||
|
||||
let packet = frame_composer.close_game2d_packet();
|
||||
let glyph_order: Vec<i32> =
|
||||
packet.composer.sprites.iter().map(|sprite| sprite.glyph_id).collect();
|
||||
|
||||
assert_eq!(glyph_order, vec![4, 3, 2, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_frame_with_scene_applies_refreshes_before_composition() {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank(TileSize::Size8, 2, Color::BLUE)));
|
||||
banks.install_scene_bank(0, Arc::new(make_scene_with_palette(0, 2, TileSize::Size8)));
|
||||
|
||||
let mut frame_composer =
|
||||
FrameComposer::new(16, 16, Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>);
|
||||
let mut frame_composer = FrameComposer::new(
|
||||
16,
|
||||
16,
|
||||
Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>,
|
||||
make_glyph_slot_index(&[(0, 0)]),
|
||||
);
|
||||
assert!(frame_composer.bind_scene(0));
|
||||
|
||||
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
||||
gfx.scene_fade_level = 31;
|
||||
gfx.hud_fade_level = 31;
|
||||
|
||||
frame_composer.render_frame(&mut gfx);
|
||||
gfx.present();
|
||||
@@ -673,6 +1030,41 @@ mod tests {
|
||||
assert_eq!(gfx.front_buffer()[0], Color::BLUE.raw());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_frame_realigns_cache_window_before_refresh_when_camera_moves() {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
let scene = Arc::new(make_scene_grid(0, 2, TileSize::Size8, 16, 16));
|
||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank(TileSize::Size8, 2, Color::BLUE)));
|
||||
banks.install_scene_bank(0, Arc::clone(&scene));
|
||||
|
||||
let mut frame_composer = FrameComposer::new(
|
||||
16,
|
||||
16,
|
||||
Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>,
|
||||
make_glyph_slot_index(&[(0, 0)]),
|
||||
);
|
||||
assert!(frame_composer.bind_scene(0));
|
||||
|
||||
let mut expected_resolver = FrameComposer::build_scene_runtime(16, 16, &scene).1;
|
||||
expected_resolver.update(&scene, 0, 0);
|
||||
let expected_update = expected_resolver.update(&scene, 40, 0);
|
||||
|
||||
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
||||
|
||||
frame_composer.render_frame(&mut gfx);
|
||||
frame_composer.set_camera(40, 0);
|
||||
frame_composer.render_frame(&mut gfx);
|
||||
|
||||
let cache = frame_composer.cache().expect("cache should exist");
|
||||
assert_eq!(
|
||||
cache.layers[0].logical_origin(),
|
||||
(
|
||||
expected_update.copy_requests[0].cache_origin_tile_x,
|
||||
expected_update.copy_requests[0].cache_origin_tile_y,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_frame_survives_scene_transition_through_unbind_and_rebind() {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
@@ -682,11 +1074,13 @@ mod tests {
|
||||
banks.install_scene_bank(0, Arc::new(make_scene_with_palette(0, 1, TileSize::Size8)));
|
||||
banks.install_scene_bank(1, Arc::new(make_scene_with_palette(1, 2, TileSize::Size8)));
|
||||
|
||||
let mut frame_composer =
|
||||
FrameComposer::new(16, 16, Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>);
|
||||
let mut frame_composer = FrameComposer::new(
|
||||
16,
|
||||
16,
|
||||
Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>,
|
||||
make_glyph_slot_index(&[(0, 0), (1, 1)]),
|
||||
);
|
||||
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
||||
gfx.scene_fade_level = 31;
|
||||
gfx.hud_fade_level = 31;
|
||||
|
||||
assert!(frame_composer.bind_scene(0));
|
||||
frame_composer.render_frame(&mut gfx);
|
||||
@@ -716,4 +1110,57 @@ mod tests {
|
||||
gfx.present();
|
||||
assert_eq!(gfx.front_buffer()[0], Color::BLUE.raw());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_frame_panics_when_dependency_disappears_after_bind() {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank(TileSize::Size8, 1, Color::RED)));
|
||||
banks.install_scene_bank(0, Arc::new(make_scene_with_palette(1, 1, TileSize::Size8)));
|
||||
|
||||
let glyph_slot_index = make_glyph_slot_index(&[(1, 0)]);
|
||||
let mut frame_composer = FrameComposer::new(
|
||||
16,
|
||||
16,
|
||||
Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>,
|
||||
glyph_slot_index.clone(),
|
||||
);
|
||||
assert!(frame_composer.bind_scene(0));
|
||||
|
||||
glyph_slot_index.rebuild_from_slots(&[None; 16]);
|
||||
|
||||
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
||||
let panic = catch_unwind(AssertUnwindSafe(|| frame_composer.render_frame(&mut gfx)))
|
||||
.expect_err("render_frame should panic when dependency disappears");
|
||||
let message = if let Some(message) = panic.downcast_ref::<String>() {
|
||||
message.clone()
|
||||
} else if let Some(message) = panic.downcast_ref::<&str>() {
|
||||
(*message).to_string()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
assert!(message.contains("SCENE dependency fatal during render_frame"));
|
||||
assert!(message.contains("glyph_asset_id=1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_frame_resolves_glyph_dependency_by_asset_id_not_by_slot_number() {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_glyph_bank(7, Arc::new(make_glyph_bank(TileSize::Size8, 2, Color::BLUE)));
|
||||
banks.install_scene_bank(0, Arc::new(make_scene_with_palette(42, 2, TileSize::Size8)));
|
||||
|
||||
let mut frame_composer = FrameComposer::new(
|
||||
16,
|
||||
16,
|
||||
Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>,
|
||||
make_glyph_slot_index(&[(42, 7)]),
|
||||
);
|
||||
assert!(frame_composer.bind_scene(0));
|
||||
|
||||
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
||||
frame_composer.render_frame(&mut gfx);
|
||||
gfx.present();
|
||||
|
||||
assert_eq!(gfx.front_buffer()[0], Color::BLUE.raw());
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,39 +0,0 @@
|
||||
use crate::gfx::BlendMode;
|
||||
use prometeu_hal::color::Color;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum OverlayCommand {
|
||||
FillRectBlend { x: i32, y: i32, w: i32, h: i32, color: Color, mode: BlendMode },
|
||||
DrawLine { x0: i32, y0: i32, x1: i32, y1: i32, color: Color },
|
||||
DrawCircle { x: i32, y: i32, r: i32, color: Color },
|
||||
DrawDisc { x: i32, y: i32, r: i32, border_color: Color, fill_color: Color },
|
||||
DrawSquare { x: i32, y: i32, w: i32, h: i32, border_color: Color, fill_color: Color },
|
||||
DrawText { x: i32, y: i32, text: String, color: Color },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct DeferredGfxOverlay {
|
||||
commands: Vec<OverlayCommand>,
|
||||
}
|
||||
|
||||
impl DeferredGfxOverlay {
|
||||
pub fn begin_frame(&mut self) {
|
||||
self.commands.clear();
|
||||
}
|
||||
|
||||
pub fn push(&mut self, command: OverlayCommand) {
|
||||
self.commands.push(command);
|
||||
}
|
||||
|
||||
pub fn commands(&self) -> &[OverlayCommand] {
|
||||
&self.commands
|
||||
}
|
||||
|
||||
pub fn command_count(&self) -> usize {
|
||||
self.commands.len()
|
||||
}
|
||||
|
||||
pub fn take_commands(&mut self) -> Vec<OverlayCommand> {
|
||||
std::mem::take(&mut self.commands)
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,14 @@ use crate::pad::Pad;
|
||||
use crate::touch::Touch;
|
||||
use prometeu_hal::cartridge::AssetsPayloadSource;
|
||||
use prometeu_hal::sprite::Sprite;
|
||||
use prometeu_hal::{AssetBridge, AudioBridge, GfxBridge, HardwareBridge, PadBridge, TouchBridge};
|
||||
use prometeu_hal::{
|
||||
AssetBridge, AudioBridge, InputPlatform, NoopTelemetryPlatform, PadBridge, RenderBackend,
|
||||
RuntimePlatform, TelemetryPlatform, TouchBridge, WallClock,
|
||||
};
|
||||
use prometeu_hal::{
|
||||
Game2DFrameComposer, Game2DFramePacket, RenderSubmission, RenderSubmissionPacket,
|
||||
};
|
||||
use prometeu_hal::{RenderSubmissionSink, RenderSubmitError};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Aggregate structure for all virtual hardware peripherals.
|
||||
@@ -21,11 +28,14 @@ use std::sync::Arc;
|
||||
/// for easier testing and different host implementations (Desktop, Web, etc.).
|
||||
///
|
||||
/// ### Console Specifications:
|
||||
/// - **Resolution**: 320x180 (16:9 Aspect Ratio).
|
||||
/// - **Color Depth**: RGB565 (16-bit).
|
||||
/// - **Resolution**: 480x270 (16:9 Aspect Ratio).
|
||||
/// - **Color Format**: RGBA8888.
|
||||
/// - **Audio**: Stereo, Command-based mixing.
|
||||
/// - **Input**: 12-button Digital Gamepad + Absolute Touch/Mouse.
|
||||
pub struct Hardware {
|
||||
wall_clock: Arc<dyn WallClock>,
|
||||
/// Shared physical memory bank ownership used by peripherals and worker backends.
|
||||
pub memory_banks: Arc<MemoryBanks>,
|
||||
/// The Graphics Processing Unit (GPU). Handles drawing primitives, sprites, and tilemaps.
|
||||
pub gfx: Gfx,
|
||||
/// Canonical frame orchestration owner for scene/camera/cache/resolver/sprites.
|
||||
@@ -40,60 +50,94 @@ pub struct Hardware {
|
||||
pub assets: AssetManager,
|
||||
}
|
||||
|
||||
impl Default for Hardware {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
impl Hardware {
|
||||
fn consume_render_submission(&mut self, submission: &RenderSubmission) {
|
||||
match &submission.packet {
|
||||
RenderSubmissionPacket::Game2D(packet) => {
|
||||
if packet.composer.bound_scene.is_none() {
|
||||
self.gfx.render_game2d_frame_packet(packet);
|
||||
} else {
|
||||
self.frame_composer.render_game2d_frame_packet(packet, &mut self.gfx);
|
||||
self.gfx.apply_gfx2d_commands(&packet.gfx2d);
|
||||
}
|
||||
}
|
||||
RenderSubmissionPacket::ShellUi(packet) => {
|
||||
self.gfx.render_shell_ui_frame_packet(packet);
|
||||
}
|
||||
}
|
||||
self.gfx.present();
|
||||
}
|
||||
}
|
||||
|
||||
impl HardwareBridge for Hardware {
|
||||
impl RenderSubmissionSink for Hardware {
|
||||
fn submit_render_submission(
|
||||
&mut self,
|
||||
submission: RenderSubmission,
|
||||
) -> Result<(), RenderSubmitError> {
|
||||
self.consume_render_submission(&submission);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderBackend for Hardware {
|
||||
fn render_frame(&mut self) {
|
||||
if self.frame_composer.active_scene_id().is_none() {
|
||||
let packet = self.frame_composer.close_game2d_packet();
|
||||
self.gfx.render_game2d_frame_packet(&packet);
|
||||
} else {
|
||||
self.frame_composer.render_frame(&mut self.gfx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Game2DFrameComposer for Hardware {
|
||||
fn begin_frame(&mut self) {
|
||||
self.gfx.begin_overlay_frame();
|
||||
self.frame_composer.begin_frame();
|
||||
}
|
||||
|
||||
fn bind_scene(&mut self, scene_bank_id: usize) -> bool {
|
||||
self.frame_composer.bind_scene(scene_bank_id)
|
||||
fn bind_scene(&mut self, scene_bank_id: usize) -> prometeu_hal::ComposerOpStatus {
|
||||
if self.frame_composer.bind_scene(scene_bank_id) {
|
||||
prometeu_hal::ComposerOpStatus::Ok
|
||||
} else {
|
||||
prometeu_hal::ComposerOpStatus::SceneUnavailable
|
||||
}
|
||||
}
|
||||
|
||||
fn unbind_scene(&mut self) {
|
||||
self.frame_composer.unbind_scene();
|
||||
}
|
||||
|
||||
fn set_camera(&mut self, x: i32, y: i32) {
|
||||
fn set_camera(&mut self, x: i32, y: i32) -> prometeu_hal::ComposerOpStatus {
|
||||
self.frame_composer.set_camera(x, y);
|
||||
prometeu_hal::ComposerOpStatus::Ok
|
||||
}
|
||||
|
||||
fn emit_sprite(&mut self, sprite: Sprite) -> bool {
|
||||
self.frame_composer.emit_sprite(sprite)
|
||||
fn emit_sprite(&mut self, sprite: Sprite) -> prometeu_hal::ComposerOpStatus {
|
||||
let Some(bank) = self.gfx.glyph_banks.glyph_bank_slot(sprite.bank_id as usize) else {
|
||||
return prometeu_hal::ComposerOpStatus::BankInvalid;
|
||||
};
|
||||
|
||||
if !bank.contains_palette(sprite.glyph.palette_id) {
|
||||
return prometeu_hal::ComposerOpStatus::BankInvalid;
|
||||
}
|
||||
|
||||
if self.frame_composer.emit_sprite(sprite) {
|
||||
prometeu_hal::ComposerOpStatus::Ok
|
||||
} else {
|
||||
prometeu_hal::ComposerOpStatus::SpriteOverflow
|
||||
}
|
||||
}
|
||||
|
||||
fn render_frame(&mut self) {
|
||||
self.frame_composer.render_frame(&mut self.gfx);
|
||||
self.gfx.drain_overlay_debug();
|
||||
}
|
||||
|
||||
fn has_glyph_bank(&self, bank_id: usize) -> bool {
|
||||
self.gfx.glyph_banks.glyph_bank_slot(bank_id).is_some()
|
||||
}
|
||||
|
||||
fn gfx(&self) -> &dyn GfxBridge {
|
||||
&self.gfx
|
||||
}
|
||||
fn gfx_mut(&mut self) -> &mut dyn GfxBridge {
|
||||
&mut self.gfx
|
||||
}
|
||||
|
||||
fn audio(&self) -> &dyn AudioBridge {
|
||||
&self.audio
|
||||
}
|
||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
|
||||
&mut self.audio
|
||||
fn close_game2d_packet(&self) -> Game2DFramePacket {
|
||||
self.frame_composer.close_game2d_packet()
|
||||
}
|
||||
}
|
||||
|
||||
impl InputPlatform for Hardware {
|
||||
fn pad(&self) -> &dyn PadBridge {
|
||||
&self.pad
|
||||
}
|
||||
|
||||
fn pad_mut(&mut self) -> &mut dyn PadBridge {
|
||||
&mut self.pad
|
||||
}
|
||||
@@ -101,32 +145,87 @@ impl HardwareBridge for Hardware {
|
||||
fn touch(&self) -> &dyn TouchBridge {
|
||||
&self.touch
|
||||
}
|
||||
|
||||
fn touch_mut(&mut self) -> &mut dyn TouchBridge {
|
||||
&mut self.touch
|
||||
}
|
||||
}
|
||||
|
||||
static NOOP_TELEMETRY: NoopTelemetryPlatform = NoopTelemetryPlatform;
|
||||
|
||||
impl RuntimePlatform for Hardware {
|
||||
fn wall_clock(&self) -> &dyn WallClock {
|
||||
self.wall_clock.as_ref()
|
||||
}
|
||||
|
||||
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink {
|
||||
self
|
||||
}
|
||||
|
||||
fn render_backend(&mut self) -> &mut dyn RenderBackend {
|
||||
self
|
||||
}
|
||||
|
||||
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer {
|
||||
self
|
||||
}
|
||||
|
||||
fn audio(&self) -> &dyn AudioBridge {
|
||||
&self.audio
|
||||
}
|
||||
|
||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
|
||||
&mut self.audio
|
||||
}
|
||||
|
||||
fn input(&self) -> &dyn InputPlatform {
|
||||
self
|
||||
}
|
||||
|
||||
fn input_mut(&mut self) -> &mut dyn InputPlatform {
|
||||
self
|
||||
}
|
||||
|
||||
fn assets(&self) -> &dyn AssetBridge {
|
||||
&self.assets
|
||||
}
|
||||
|
||||
fn assets_mut(&mut self) -> &mut dyn AssetBridge {
|
||||
&mut self.assets
|
||||
}
|
||||
|
||||
fn telemetry(&self) -> &dyn TelemetryPlatform {
|
||||
&NOOP_TELEMETRY
|
||||
}
|
||||
}
|
||||
|
||||
impl Hardware {
|
||||
/// Internal hardware width in pixels.
|
||||
pub const W: usize = 320;
|
||||
pub const W: usize = 480;
|
||||
/// Internal hardware height in pixels.
|
||||
pub const H: usize = 180;
|
||||
pub const H: usize = 270;
|
||||
|
||||
/// Creates a fresh hardware instance with default settings.
|
||||
pub fn new() -> Self {
|
||||
Self::new_with_memory_banks(Arc::new(MemoryBanks::new()))
|
||||
pub fn new(wall_clock: Arc<dyn WallClock>) -> Self {
|
||||
Self::new_with_memory_banks(Arc::new(MemoryBanks::new()), wall_clock)
|
||||
}
|
||||
|
||||
/// Creates hardware with explicit shared bank ownership.
|
||||
pub fn new_with_memory_banks(memory_banks: Arc<MemoryBanks>) -> Self {
|
||||
pub fn new_with_memory_banks(
|
||||
memory_banks: Arc<MemoryBanks>,
|
||||
wall_clock: Arc<dyn WallClock>,
|
||||
) -> Self {
|
||||
let assets = AssetManager::new(
|
||||
vec![],
|
||||
AssetsPayloadSource::empty(),
|
||||
Arc::clone(&memory_banks) as Arc<dyn GlyphBankPoolInstaller>,
|
||||
Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolInstaller>,
|
||||
Arc::clone(&memory_banks) as Arc<dyn SceneBankPoolInstaller>,
|
||||
);
|
||||
let glyph_slot_index = assets.glyph_asset_slot_index();
|
||||
Self {
|
||||
wall_clock,
|
||||
memory_banks: Arc::clone(&memory_banks),
|
||||
gfx: Gfx::new(
|
||||
Self::W,
|
||||
Self::H,
|
||||
@@ -136,17 +235,12 @@ impl Hardware {
|
||||
Self::W,
|
||||
Self::H,
|
||||
Arc::clone(&memory_banks) as Arc<dyn SceneBankPoolAccess>,
|
||||
glyph_slot_index,
|
||||
),
|
||||
audio: Audio::new(Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolAccess>),
|
||||
pad: Pad::default(),
|
||||
touch: Touch::default(),
|
||||
assets: AssetManager::new(
|
||||
vec![],
|
||||
AssetsPayloadSource::empty(),
|
||||
Arc::clone(&memory_banks) as Arc<dyn GlyphBankPoolInstaller>,
|
||||
Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolInstaller>,
|
||||
Arc::clone(&memory_banks) as Arc<dyn SceneBankPoolInstaller>,
|
||||
),
|
||||
assets,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -160,26 +254,33 @@ mod tests {
|
||||
use prometeu_hal::color::Color;
|
||||
use prometeu_hal::glyph::Glyph;
|
||||
use prometeu_hal::glyph_bank::{GlyphBank, TileSize};
|
||||
use prometeu_hal::primitives::Rect;
|
||||
use prometeu_hal::scene_bank::SceneBank;
|
||||
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
||||
use prometeu_hal::scene_viewport_cache::SceneViewportCache;
|
||||
use prometeu_hal::scene_viewport_resolver::SceneViewportResolver;
|
||||
use prometeu_hal::tile::Tile;
|
||||
use prometeu_hal::tilemap::TileMap;
|
||||
use prometeu_hal::{
|
||||
BoundScenePacket, Camera2D, ComposerFramePacket, FrameId, GameSpritePacket, Gfx2dCommand,
|
||||
GfxUiCommand, ShellUiFramePacket,
|
||||
};
|
||||
|
||||
fn make_glyph_bank() -> GlyphBank {
|
||||
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||
bank.palettes[0][1] = Color::RED;
|
||||
for pixel in &mut bank.pixel_indices {
|
||||
*pixel = 1;
|
||||
}
|
||||
bank.palette_mut(0).unwrap()[1] = Color::RED;
|
||||
bank.pixel_indices.fill(1);
|
||||
bank
|
||||
}
|
||||
|
||||
fn make_scene() -> SceneBank {
|
||||
make_scene_with_glyph_asset_id(1)
|
||||
}
|
||||
|
||||
fn make_scene_with_glyph_asset_id(glyph_asset_id: i32) -> SceneBank {
|
||||
let layer = SceneLayer {
|
||||
active: true,
|
||||
glyph_bank_id: 0,
|
||||
glyph_asset_id,
|
||||
tile_size: TileSize::Size8,
|
||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||
tilemap: TileMap {
|
||||
@@ -204,9 +305,12 @@ mod tests {
|
||||
fn hardware_can_render_scene_from_shared_scene_bank_pipeline() {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
||||
banks.install_scene_bank(0, Arc::new(make_scene()));
|
||||
banks.install_scene_bank(0, Arc::new(make_scene_with_glyph_asset_id(0)));
|
||||
|
||||
let mut hardware = Hardware::new_with_memory_banks(Arc::clone(&banks));
|
||||
let mut hardware = Hardware::new_with_memory_banks(
|
||||
Arc::clone(&banks),
|
||||
Arc::new(crate::ControlledWallClock::default()),
|
||||
);
|
||||
let scene = banks.scene_bank_slot(0).expect("scene bank slot 0 should be resident");
|
||||
let mut cache = SceneViewportCache::new(&scene, 4, 4);
|
||||
cache.materialize_all_layers(&scene);
|
||||
@@ -214,9 +318,7 @@ mod tests {
|
||||
let mut resolver = SceneViewportResolver::new(16, 16, 4, 4, 12, 20);
|
||||
let update = resolver.update(&scene, 0, 0);
|
||||
|
||||
hardware.gfx.scene_fade_level = 31;
|
||||
hardware.gfx.hud_fade_level = 31;
|
||||
hardware.gfx.render_scene_from_cache(&cache, &update);
|
||||
hardware.gfx.render_scene_from_cache(&cache, &update, &[0, 0, 0, 0]);
|
||||
hardware.gfx.present();
|
||||
|
||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
||||
@@ -227,7 +329,8 @@ mod tests {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_scene_bank(2, Arc::new(make_scene()));
|
||||
|
||||
let hardware = Hardware::new_with_memory_banks(banks);
|
||||
let hardware =
|
||||
Hardware::new_with_memory_banks(banks, Arc::new(crate::ControlledWallClock::default()));
|
||||
let scene = hardware
|
||||
.frame_composer
|
||||
.scene_bank_slot(2)
|
||||
@@ -237,4 +340,133 @@ mod tests {
|
||||
assert_eq!(hardware.frame_composer.scene_bank_slot_count(), 16);
|
||||
assert_eq!(scene.layers[0].tile_size, TileSize::Size8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publish_game2d_submission_applies_gfx2d_overlay_after_active_scene() {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
||||
banks.install_scene_bank(0, Arc::new(make_scene_with_glyph_asset_id(0)));
|
||||
|
||||
let mut hardware =
|
||||
Hardware::new_with_memory_banks(banks, Arc::new(crate::ControlledWallClock::default()));
|
||||
let mut glyph_slots = [None; 16];
|
||||
glyph_slots[0] = Some(0);
|
||||
hardware.assets.glyph_asset_slot_index().rebuild_from_slots(&glyph_slots);
|
||||
assert_eq!(
|
||||
Game2DFrameComposer::bind_scene(&mut hardware, 0),
|
||||
prometeu_hal::ComposerOpStatus::Ok
|
||||
);
|
||||
|
||||
let mut packet = Game2DFrameComposer::close_game2d_packet(&hardware);
|
||||
packet.gfx2d = vec![Gfx2dCommand::FillRect {
|
||||
rect: Rect { x: 0, y: 0, w: 1, h: 1 },
|
||||
color: Color::BLUE,
|
||||
}];
|
||||
|
||||
RenderSubmissionSink::submit_render_submission(
|
||||
&mut hardware,
|
||||
RenderSubmission::game2d(FrameId::ZERO, packet),
|
||||
)
|
||||
.expect("local sink should publish Game2D packet");
|
||||
|
||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::BLUE.raw());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publish_game2d_submission_uses_packet_scene_and_sprites_not_live_frame_state() {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
||||
banks.install_scene_bank(0, Arc::new(make_scene_with_glyph_asset_id(0)));
|
||||
|
||||
let mut hardware =
|
||||
Hardware::new_with_memory_banks(banks, Arc::new(crate::ControlledWallClock::default()));
|
||||
let mut glyph_slots = [None; 16];
|
||||
glyph_slots[0] = Some(0);
|
||||
hardware.assets.glyph_asset_slot_index().rebuild_from_slots(&glyph_slots);
|
||||
assert_eq!(
|
||||
Game2DFrameComposer::bind_scene(&mut hardware, 0),
|
||||
prometeu_hal::ComposerOpStatus::Ok
|
||||
);
|
||||
|
||||
let packet = Game2DFramePacket::new(
|
||||
ComposerFramePacket {
|
||||
bound_scene: Some(BoundScenePacket { bank_id: 0 }),
|
||||
camera: Camera2D::default(),
|
||||
sprites: vec![GameSpritePacket {
|
||||
glyph_id: 0,
|
||||
palette_id: 0,
|
||||
x: 0,
|
||||
y: 0,
|
||||
layer: 0,
|
||||
bank_id: 0,
|
||||
flip_x: false,
|
||||
flip_y: false,
|
||||
priority: 0,
|
||||
}],
|
||||
hud: Default::default(),
|
||||
},
|
||||
Vec::new(),
|
||||
);
|
||||
|
||||
Game2DFrameComposer::begin_frame(&mut hardware);
|
||||
RenderSubmissionSink::submit_render_submission(
|
||||
&mut hardware,
|
||||
RenderSubmission::game2d(FrameId::ZERO, packet),
|
||||
)
|
||||
.expect("local sink should publish Game2D packet");
|
||||
|
||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_submission_sink_accepts_owned_game2d_submission() {
|
||||
let mut hardware = Hardware::new(Arc::new(crate::ControlledWallClock::default()));
|
||||
let packet = Game2DFramePacket::new(
|
||||
ComposerFramePacket::default(),
|
||||
vec![Gfx2dCommand::Clear { color: Color::BLUE }],
|
||||
);
|
||||
let submission = RenderSubmission::game2d(FrameId::ZERO, packet);
|
||||
|
||||
RenderSubmissionSink::submit_render_submission(&mut hardware, submission)
|
||||
.expect("local sink should accept owned Game2D submissions");
|
||||
|
||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::BLUE.raw());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_submission_sink_accepts_owned_shell_ui_submission() {
|
||||
let mut hardware = Hardware::new(Arc::new(crate::ControlledWallClock::default()));
|
||||
let packet = ShellUiFramePacket::new(vec![GfxUiCommand::Clear { color: Color::RED }]);
|
||||
let submission = RenderSubmission::shell_ui(FrameId::ZERO, packet);
|
||||
|
||||
RenderSubmissionSink::submit_render_submission(&mut hardware, submission)
|
||||
.expect("local sink should accept owned ShellUi submissions");
|
||||
|
||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emit_sprite_rejects_palette_id_outside_loaded_glyph_bank() {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
||||
let mut hardware =
|
||||
Hardware::new_with_memory_banks(banks, Arc::new(crate::ControlledWallClock::default()));
|
||||
|
||||
let status = Game2DFrameComposer::emit_sprite(
|
||||
&mut hardware,
|
||||
Sprite {
|
||||
glyph: Glyph { glyph_id: 0, palette_id: 1 },
|
||||
x: 0,
|
||||
y: 0,
|
||||
layer: 0,
|
||||
bank_id: 0,
|
||||
active: false,
|
||||
flip_x: false,
|
||||
flip_y: false,
|
||||
priority: 0,
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(status, prometeu_hal::ComposerOpStatus::BankInvalid);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,19 +2,28 @@ mod asset;
|
||||
mod audio;
|
||||
mod frame_composer;
|
||||
mod gfx;
|
||||
mod gfx_overlay;
|
||||
pub mod hardware;
|
||||
mod local_render_backend;
|
||||
mod memory_banks;
|
||||
mod pad;
|
||||
mod test_platform;
|
||||
mod touch;
|
||||
mod wall_clock;
|
||||
|
||||
pub use crate::asset::AssetManager;
|
||||
pub use crate::audio::{Audio, AudioCommand, Channel, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};
|
||||
pub use crate::frame_composer::{FrameComposer, SceneStatus, SpriteController};
|
||||
pub use crate::audio::{
|
||||
Audio, AudioCommand, AudioDelivery, AudioTransport, Channel, MAX_CHANNELS,
|
||||
MAX_COMMANDS_PER_FRAME, OUTPUT_SAMPLE_RATE,
|
||||
};
|
||||
pub use crate::frame_composer::{ComposerBuffer, FrameComposer, SceneStatus, SpriteController};
|
||||
pub use crate::gfx::Gfx;
|
||||
pub use crate::gfx_overlay::{DeferredGfxOverlay, OverlayCommand};
|
||||
pub use crate::local_render_backend::LocalFramebufferRenderBackend;
|
||||
pub use crate::memory_banks::{
|
||||
GlyphBankPoolAccess, GlyphBankPoolInstaller, MemoryBanks, SceneBankPoolAccess,
|
||||
SceneBankPoolInstaller, SoundBankPoolAccess, SoundBankPoolInstaller,
|
||||
};
|
||||
pub use crate::pad::Pad;
|
||||
pub use crate::test_platform::TestPlatform;
|
||||
pub use crate::wall_clock::ControlledWallClock;
|
||||
|
||||
pub mod memcard;
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
use crate::asset::GlyphAssetSlotIndex;
|
||||
use crate::frame_composer::FrameComposer;
|
||||
use crate::gfx::Gfx;
|
||||
use crate::memory_banks::{GlyphBankPoolAccess, MemoryBanks, SceneBankPoolAccess};
|
||||
use prometeu_hal::app_mode::AppMode;
|
||||
use prometeu_hal::{
|
||||
OwnedRgba8888Frame, RenderSubmission, RenderSubmissionPacket, RenderWorkerBackend,
|
||||
RenderWorkerError,
|
||||
};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub struct LocalFramebufferRenderBackend {
|
||||
gfx: Mutex<Gfx>,
|
||||
frame_composer: Mutex<FrameComposer>,
|
||||
}
|
||||
|
||||
impl LocalFramebufferRenderBackend {
|
||||
pub fn new(width: usize, height: usize, glyph_banks: Arc<dyn GlyphBankPoolAccess>) -> Self {
|
||||
Self::new_with_parts(
|
||||
width,
|
||||
height,
|
||||
glyph_banks,
|
||||
Arc::new(MemoryBanks::new()),
|
||||
GlyphAssetSlotIndex::new(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn new_with_memory_banks(
|
||||
width: usize,
|
||||
height: usize,
|
||||
memory_banks: Arc<MemoryBanks>,
|
||||
glyph_slot_index: GlyphAssetSlotIndex,
|
||||
) -> Self {
|
||||
Self::new_with_parts(
|
||||
width,
|
||||
height,
|
||||
Arc::clone(&memory_banks) as Arc<dyn GlyphBankPoolAccess>,
|
||||
memory_banks,
|
||||
glyph_slot_index,
|
||||
)
|
||||
}
|
||||
|
||||
fn new_with_parts(
|
||||
width: usize,
|
||||
height: usize,
|
||||
glyph_banks: Arc<dyn GlyphBankPoolAccess>,
|
||||
scene_banks: Arc<dyn SceneBankPoolAccess>,
|
||||
glyph_slot_index: GlyphAssetSlotIndex,
|
||||
) -> Self {
|
||||
Self {
|
||||
gfx: Mutex::new(Gfx::new(width, height, glyph_banks)),
|
||||
frame_composer: Mutex::new(FrameComposer::new(
|
||||
width,
|
||||
height,
|
||||
scene_banks,
|
||||
glyph_slot_index,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render_submission(
|
||||
&self,
|
||||
submission: &RenderSubmission,
|
||||
) -> Result<OwnedRgba8888Frame, RenderWorkerError> {
|
||||
let mut gfx = self.gfx.lock().map_err(|_| RenderWorkerError::InternalFailure)?;
|
||||
match &submission.packet {
|
||||
RenderSubmissionPacket::Game2D(packet) if submission.app_mode == AppMode::Game => {
|
||||
if packet.composer.bound_scene.is_none() {
|
||||
gfx.render_game2d_frame_packet(packet);
|
||||
} else {
|
||||
let mut frame_composer = self
|
||||
.frame_composer
|
||||
.lock()
|
||||
.map_err(|_| RenderWorkerError::InternalFailure)?;
|
||||
frame_composer.render_game2d_frame_packet(packet, &mut *gfx);
|
||||
gfx.apply_gfx2d_commands(&packet.gfx2d);
|
||||
}
|
||||
}
|
||||
RenderSubmissionPacket::ShellUi(packet) if submission.app_mode == AppMode::Shell => {
|
||||
gfx.render_shell_ui_frame_packet(packet);
|
||||
}
|
||||
_ => return Err(RenderWorkerError::RenderFailed),
|
||||
}
|
||||
|
||||
gfx.present();
|
||||
let (width, height) = gfx.size();
|
||||
OwnedRgba8888Frame::packed(
|
||||
submission.frame_id,
|
||||
submission.ownership,
|
||||
width,
|
||||
height,
|
||||
gfx.front_buffer().to_vec(),
|
||||
)
|
||||
.map_err(|_| RenderWorkerError::InternalFailure)
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderWorkerBackend for LocalFramebufferRenderBackend {
|
||||
fn render(
|
||||
&self,
|
||||
submission: &RenderSubmission,
|
||||
) -> Result<OwnedRgba8888Frame, RenderWorkerError> {
|
||||
self.render_submission(submission)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::memory_banks::MemoryBanks;
|
||||
use prometeu_hal::app_mode::AppMode;
|
||||
use prometeu_hal::color::Color;
|
||||
use prometeu_hal::primitives::Rect;
|
||||
use prometeu_hal::{
|
||||
FrameId, Game2DFramePacket, Gfx2dCommand, GfxUiCommand, RenderOwnership, ShellUiFramePacket,
|
||||
};
|
||||
|
||||
fn backend() -> LocalFramebufferRenderBackend {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
LocalFramebufferRenderBackend::new(4, 4, banks)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_backend_renders_game2d_submission_to_owned_frame() {
|
||||
let backend = backend();
|
||||
let packet = Game2DFramePacket {
|
||||
gfx2d: vec![Gfx2dCommand::FillRect {
|
||||
rect: Rect { x: 1, y: 1, w: 2, h: 2 },
|
||||
color: Color::RED,
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let ownership = RenderOwnership::new(3, AppMode::Game, 9);
|
||||
let submission =
|
||||
RenderSubmission::game2d(FrameId::new(5), packet).with_ownership(ownership);
|
||||
|
||||
let frame = backend.render(&submission).expect("game frame should render");
|
||||
|
||||
assert_eq!(frame.frame_id, FrameId::new(5));
|
||||
assert_eq!(frame.ownership, ownership);
|
||||
assert_eq!(frame.width, 4);
|
||||
assert_eq!(frame.height, 4);
|
||||
assert_eq!(frame.pixels[1 + 4], Color::RED.raw());
|
||||
assert_eq!(frame.pixels[2 + 2 * 4], Color::RED.raw());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_backend_renders_shell_ui_submission_to_owned_frame() {
|
||||
let backend = backend();
|
||||
let packet = ShellUiFramePacket::new(vec![GfxUiCommand::FillRect {
|
||||
rect: Rect { x: 0, y: 0, w: 1, h: 1 },
|
||||
color: Color::GREEN,
|
||||
}]);
|
||||
let ownership = RenderOwnership::new(4, AppMode::Shell, 10);
|
||||
let submission =
|
||||
RenderSubmission::shell_ui(FrameId::new(6), packet).with_ownership(ownership);
|
||||
|
||||
let frame = backend.render(&submission).expect("shell frame should render");
|
||||
|
||||
assert_eq!(frame.frame_id, FrameId::new(6));
|
||||
assert_eq!(frame.ownership, ownership);
|
||||
assert_eq!(frame.pixels[0], Color::GREEN.raw());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! File-host implementation. IO runs only on the shared worker, never the guest lane.
|
||||
use prometeu_hal::memcard::{MemcardIoError as Error, MemcardStorage};
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::path::Path;
|
||||
|
||||
pub struct FileMemcard {
|
||||
file: File,
|
||||
length: u64,
|
||||
read_only: bool,
|
||||
}
|
||||
fn io_error(e: std::io::Error) -> Error {
|
||||
use std::io::ErrorKind as K;
|
||||
match e.kind() {
|
||||
K::NotFound => Error::Unavailable,
|
||||
K::PermissionDenied => Error::AccessDenied,
|
||||
K::AlreadyExists => Error::AlreadyExists,
|
||||
K::StorageFull => Error::NoSpace,
|
||||
K::InvalidInput | K::UnexpectedEof => Error::InvalidRange,
|
||||
K::Unsupported => Error::Unsupported,
|
||||
_ => Error::IoError,
|
||||
}
|
||||
}
|
||||
impl FileMemcard {
|
||||
fn lock(file: &File) -> Result<(), Error> {
|
||||
file.try_lock().map_err(|error| match error {
|
||||
std::fs::TryLockError::WouldBlock => Error::Busy,
|
||||
std::fs::TryLockError::Error(error) => io_error(error),
|
||||
})
|
||||
}
|
||||
pub fn open(path: &Path, read_only: bool) -> Result<Self, Error> {
|
||||
let file = OpenOptions::new().read(true).write(!read_only).open(path).map_err(io_error)?;
|
||||
Self::lock(&file)?;
|
||||
let length = file.metadata().map_err(io_error)?.len();
|
||||
Ok(Self { file, length, read_only })
|
||||
}
|
||||
/// Write every byte and verify allocated blocks before formatting/publication.
|
||||
/// The initializer supplies the runtime-owned format. Existing files are never replaced.
|
||||
#[cfg(unix)]
|
||||
pub fn create(
|
||||
path: &Path,
|
||||
length: u64,
|
||||
initialize: impl FnOnce(&mut dyn MemcardStorage, [u8; 16]) -> Result<(), Error>,
|
||||
) -> Result<Self, Error> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let mut id = [0; 16];
|
||||
File::open("/dev/urandom").and_then(|mut f| f.read_exact(&mut id)).map_err(io_error)?;
|
||||
let parent =
|
||||
path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
|
||||
let suffix: String = id.iter().map(|b| format!("{b:02x}")).collect();
|
||||
let temporary = parent.join(format!(".memcard-{suffix}.tmp"));
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temporary)
|
||||
.map_err(io_error)?;
|
||||
let mut published = false;
|
||||
let result = (|| {
|
||||
Self::lock(&file)?;
|
||||
let mut card = Self { file, length, read_only: false };
|
||||
let zeros = [0u8; 65_536];
|
||||
let mut offset = 0;
|
||||
while offset < length {
|
||||
let n = (length - offset).min(zeros.len() as u64) as usize;
|
||||
card.file.write_all(&zeros[..n]).map_err(io_error)?;
|
||||
offset += n as u64;
|
||||
}
|
||||
card.sync()?;
|
||||
if card.file.metadata().map_err(io_error)?.blocks().saturating_mul(512) < length {
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
initialize(&mut card, id)?;
|
||||
card.sync()?;
|
||||
// hard_link publishes without replacing a user file; parent sync makes the name durable.
|
||||
std::fs::hard_link(&temporary, path).map_err(io_error)?;
|
||||
published = true;
|
||||
File::open(parent).and_then(|f| f.sync_all()).map_err(io_error)?;
|
||||
Ok(card)
|
||||
})();
|
||||
let cleanup =
|
||||
std::fs::remove_file(&temporary).and_then(|()| File::open(parent)?.sync_all());
|
||||
match result {
|
||||
Ok(card) => {
|
||||
cleanup.map_err(|_| Error::Indeterminate)?;
|
||||
Ok(card)
|
||||
}
|
||||
Err(e) => Err(if published { Error::Indeterminate } else { e }),
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
pub fn create(
|
||||
_path: &Path,
|
||||
_length: u64,
|
||||
_initialize: impl FnOnce(&mut dyn MemcardStorage, [u8; 16]) -> Result<(), Error>,
|
||||
) -> Result<Self, Error> {
|
||||
Err(Error::Unsupported)
|
||||
}
|
||||
fn check(&self, offset: u64, length: usize) -> Result<(), Error> {
|
||||
if length > 65_536 || offset.checked_add(length as u64).is_none_or(|end| end > self.length)
|
||||
{
|
||||
return Err(Error::InvalidRange);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl MemcardStorage for FileMemcard {
|
||||
fn len(&self) -> Result<u64, Error> {
|
||||
Ok(self.length)
|
||||
}
|
||||
fn read_only(&self) -> bool {
|
||||
self.read_only
|
||||
}
|
||||
fn read_at(&mut self, offset: u64, target: &mut [u8]) -> Result<(), Error> {
|
||||
self.check(offset, target.len())?;
|
||||
self.file.seek(SeekFrom::Start(offset)).map_err(io_error)?;
|
||||
self.file.read_exact(target).map_err(io_error)
|
||||
}
|
||||
fn write_at(&mut self, offset: u64, source: &[u8]) -> Result<(), Error> {
|
||||
if self.read_only {
|
||||
return Err(Error::ReadOnly);
|
||||
}
|
||||
self.check(offset, source.len())?;
|
||||
self.file.seek(SeekFrom::Start(offset)).map_err(io_error)?;
|
||||
self.file.write_all(source).map_err(io_error)
|
||||
}
|
||||
fn sync(&mut self) -> Result<(), Error> {
|
||||
self.file.sync_all().map_err(io_error)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,13 @@
|
||||
//! Memory bank access boundary.
|
||||
//!
|
||||
//! Render consumers must cross this boundary through small, read-only traits.
|
||||
//! Frame packets carry resource IDs; large resident resources stay in banks and
|
||||
//! are read in place through a narrow HAL callback contract. Installation and
|
||||
//! slot replacement remain separate owner-side operations and are not part of
|
||||
//! the render read surface.
|
||||
|
||||
use prometeu_hal::glyph_bank::GlyphBank;
|
||||
use prometeu_hal::render_resources::RenderResourceAccess as HalRenderResourceAccess;
|
||||
use prometeu_hal::scene_bank::SceneBank;
|
||||
use prometeu_hal::sound_bank::SoundBank;
|
||||
use std::sync::{Arc, RwLock};
|
||||
@@ -15,6 +24,8 @@ pub trait GlyphBankPoolAccess: Send + Sync {
|
||||
pub trait GlyphBankPoolInstaller: Send + Sync {
|
||||
/// Atomically swaps the resident GlyphBank in the specified slot.
|
||||
fn install_glyph_bank(&self, slot: usize, bank: Arc<GlyphBank>);
|
||||
/// Clears all resident GlyphBank slots.
|
||||
fn clear_glyph_banks(&self);
|
||||
}
|
||||
|
||||
/// Non-generic interface for peripherals to access sound banks.
|
||||
@@ -29,6 +40,8 @@ pub trait SoundBankPoolAccess: Send + Sync {
|
||||
pub trait SoundBankPoolInstaller: Send + Sync {
|
||||
/// Atomically swaps the resident SoundBank in the specified slot.
|
||||
fn install_sound_bank(&self, slot: usize, bank: Arc<SoundBank>);
|
||||
/// Clears all resident SoundBank slots.
|
||||
fn clear_sound_banks(&self);
|
||||
}
|
||||
|
||||
/// Non-generic interface for peripherals to access scene banks.
|
||||
@@ -43,6 +56,8 @@ pub trait SceneBankPoolAccess: Send + Sync {
|
||||
pub trait SceneBankPoolInstaller: Send + Sync {
|
||||
/// Atomically swaps the resident SceneBank in the specified slot.
|
||||
fn install_scene_bank(&self, slot: usize, bank: Arc<SceneBank>);
|
||||
/// Clears all resident SceneBank slots.
|
||||
fn clear_scene_banks(&self);
|
||||
}
|
||||
|
||||
/// Centralized container for all hardware memory banks.
|
||||
@@ -91,6 +106,10 @@ impl GlyphBankPoolInstaller for MemoryBanks {
|
||||
pool[slot] = Some(bank);
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_glyph_banks(&self) {
|
||||
self.glyph_bank_pool.write().unwrap().fill(None);
|
||||
}
|
||||
}
|
||||
|
||||
impl SoundBankPoolAccess for MemoryBanks {
|
||||
@@ -111,6 +130,10 @@ impl SoundBankPoolInstaller for MemoryBanks {
|
||||
pool[slot] = Some(bank);
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_sound_banks(&self) {
|
||||
self.sound_bank_pool.write().unwrap().fill(None);
|
||||
}
|
||||
}
|
||||
|
||||
impl SceneBankPoolAccess for MemoryBanks {
|
||||
@@ -131,4 +154,95 @@ impl SceneBankPoolInstaller for MemoryBanks {
|
||||
pool[slot] = Some(bank);
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_scene_banks(&self) {
|
||||
self.scene_bank_pool.write().unwrap().fill(None);
|
||||
}
|
||||
}
|
||||
|
||||
impl HalRenderResourceAccess for MemoryBanks {
|
||||
fn with_glyph_bank<R>(&self, bank_id: usize, read: impl FnOnce(&GlyphBank) -> R) -> Option<R> {
|
||||
let pool = self.glyph_bank_pool.read().unwrap();
|
||||
let bank = pool.get(bank_id)?.as_deref()?;
|
||||
Some(read(bank))
|
||||
}
|
||||
|
||||
fn glyph_bank_count(&self) -> usize {
|
||||
16
|
||||
}
|
||||
|
||||
fn with_scene_bank<R>(&self, bank_id: usize, read: impl FnOnce(&SceneBank) -> R) -> Option<R> {
|
||||
let pool = self.scene_bank_pool.read().unwrap();
|
||||
let bank = pool.get(bank_id)?.as_deref()?;
|
||||
Some(read(bank))
|
||||
}
|
||||
|
||||
fn scene_bank_count(&self) -> usize {
|
||||
16
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use prometeu_hal::color::Color;
|
||||
use prometeu_hal::glyph::Glyph;
|
||||
use prometeu_hal::glyph_bank::TileSize;
|
||||
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
||||
use prometeu_hal::tile::Tile;
|
||||
use prometeu_hal::tilemap::TileMap;
|
||||
|
||||
fn assert_send_sync<T: Send + Sync>() {}
|
||||
|
||||
fn make_glyph_bank() -> GlyphBank {
|
||||
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||
bank.palette_mut(0).unwrap()[1] = Color::WHITE;
|
||||
bank
|
||||
}
|
||||
|
||||
fn make_scene_bank() -> SceneBank {
|
||||
let layer = SceneLayer {
|
||||
active: true,
|
||||
glyph_asset_id: 0,
|
||||
tile_size: TileSize::Size8,
|
||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||
tilemap: TileMap {
|
||||
width: 1,
|
||||
height: 1,
|
||||
tiles: vec![Tile {
|
||||
active: true,
|
||||
glyph: Glyph { glyph_id: 0, palette_id: 0 },
|
||||
flip_x: false,
|
||||
flip_y: false,
|
||||
}],
|
||||
},
|
||||
};
|
||||
SceneBank { layers: std::array::from_fn(|_| layer.clone()) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_resource_access_traits_are_thread_safe() {
|
||||
assert_send_sync::<MemoryBanks>();
|
||||
assert_send_sync::<Arc<dyn GlyphBankPoolAccess>>();
|
||||
assert_send_sync::<Arc<dyn SceneBankPoolAccess>>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_resource_access_exposes_read_only_glyph_and_scene_banks_without_arc_contract() {
|
||||
let banks = MemoryBanks::new();
|
||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
||||
banks.install_scene_bank(1, Arc::new(make_scene_bank()));
|
||||
|
||||
let glyph_tile_size =
|
||||
HalRenderResourceAccess::with_glyph_bank(&banks, 0, |bank| bank.tile_size);
|
||||
let scene_tile_size =
|
||||
HalRenderResourceAccess::with_scene_bank(&banks, 1, |bank| bank.layers[0].tile_size);
|
||||
|
||||
assert_eq!(glyph_tile_size, Some(TileSize::Size8));
|
||||
assert_eq!(scene_tile_size, Some(TileSize::Size8));
|
||||
assert_eq!(HalRenderResourceAccess::with_glyph_bank(&banks, 15, |_| ()), None);
|
||||
assert_eq!(HalRenderResourceAccess::with_scene_bank(&banks, 15, |_| ()), None);
|
||||
assert_eq!(HalRenderResourceAccess::glyph_bank_count(&banks), 16);
|
||||
assert_eq!(HalRenderResourceAccess::scene_bank_count(&banks), 16);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
use crate::ControlledWallClock;
|
||||
use crate::hardware::Hardware;
|
||||
use crate::memory_banks::MemoryBanks;
|
||||
use prometeu_hal::{
|
||||
AssetBridge, AudioBridge, Game2DFrameComposer, InputPlatform, RenderBackend,
|
||||
RenderSubmissionSink, RuntimePlatform, TelemetryPlatform, WallClock,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct TestPlatform {
|
||||
hardware: Hardware,
|
||||
controlled_wall_clock: Option<Arc<ControlledWallClock>>,
|
||||
}
|
||||
|
||||
impl Default for TestPlatform {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl TestPlatform {
|
||||
pub fn new() -> Self {
|
||||
Self::new_with_memory_banks(Arc::new(MemoryBanks::new()))
|
||||
}
|
||||
|
||||
pub fn new_with_memory_banks(memory_banks: Arc<MemoryBanks>) -> Self {
|
||||
let clock = Arc::new(ControlledWallClock::default());
|
||||
Self {
|
||||
hardware: Hardware::new_with_memory_banks(memory_banks, clock.clone()),
|
||||
controlled_wall_clock: Some(clock),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_with_wall_clock(clock: Arc<dyn WallClock>) -> Self {
|
||||
Self { hardware: Hardware::new(clock), controlled_wall_clock: None }
|
||||
}
|
||||
|
||||
/// Native controls for the default clock. Injected providers are controlled by their owner.
|
||||
pub fn controlled_wall_clock(&self) -> Option<&ControlledWallClock> {
|
||||
self.controlled_wall_clock.as_deref()
|
||||
}
|
||||
|
||||
pub fn local_hardware(&self) -> &Hardware {
|
||||
&self.hardware
|
||||
}
|
||||
|
||||
pub fn local_hardware_mut(&mut self) -> &mut Hardware {
|
||||
&mut self.hardware
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimePlatform for TestPlatform {
|
||||
fn wall_clock(&self) -> &dyn WallClock {
|
||||
self.hardware.wall_clock()
|
||||
}
|
||||
|
||||
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink {
|
||||
self.hardware.render_submission_sink()
|
||||
}
|
||||
|
||||
fn render_backend(&mut self) -> &mut dyn RenderBackend {
|
||||
self.hardware.render_backend()
|
||||
}
|
||||
|
||||
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer {
|
||||
self.hardware.game2d_frame_composer()
|
||||
}
|
||||
|
||||
fn audio(&self) -> &dyn AudioBridge {
|
||||
self.hardware.audio()
|
||||
}
|
||||
|
||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
|
||||
self.hardware.audio_mut()
|
||||
}
|
||||
|
||||
fn input(&self) -> &dyn InputPlatform {
|
||||
self.hardware.input()
|
||||
}
|
||||
|
||||
fn input_mut(&mut self) -> &mut dyn InputPlatform {
|
||||
self.hardware.input_mut()
|
||||
}
|
||||
|
||||
fn assets(&self) -> &dyn AssetBridge {
|
||||
self.hardware.assets()
|
||||
}
|
||||
|
||||
fn assets_mut(&mut self) -> &mut dyn AssetBridge {
|
||||
self.hardware.assets_mut()
|
||||
}
|
||||
|
||||
fn telemetry(&self) -> &dyn TelemetryPlatform {
|
||||
self.hardware.telemetry()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use prometeu_hal::{FrameId, Game2DFramePacket, RenderSubmission};
|
||||
|
||||
#[test]
|
||||
fn test_platform_initializes_required_facades() {
|
||||
let mut platform = TestPlatform::new();
|
||||
|
||||
platform.game2d_frame_composer().begin_frame();
|
||||
platform
|
||||
.render_submission_sink()
|
||||
.submit_render_submission(RenderSubmission::game2d(
|
||||
FrameId::ZERO,
|
||||
Game2DFramePacket::default(),
|
||||
))
|
||||
.expect("test platform render sink should accept local submission");
|
||||
assert!(platform.audio().ready());
|
||||
assert!(!platform.input().pad().any());
|
||||
assert!(platform.telemetry().telemetry_snapshot().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_clock_is_shared_with_hardware_and_can_be_injected() {
|
||||
let platform = TestPlatform::new();
|
||||
assert_eq!(platform.wall_clock().utc_unix_seconds(), 0);
|
||||
let clock = platform.controlled_wall_clock().expect("default controls");
|
||||
clock.set(42);
|
||||
assert_eq!(platform.local_hardware().wall_clock().utc_unix_seconds(), 42);
|
||||
clock.advance(3);
|
||||
assert_eq!(platform.wall_clock().utc_unix_seconds(), 45);
|
||||
|
||||
let custom = Arc::new(ControlledWallClock::new(900));
|
||||
let platform = TestPlatform::new_with_wall_clock(custom.clone());
|
||||
assert!(platform.controlled_wall_clock().is_none());
|
||||
assert_eq!(platform.wall_clock().utc_unix_seconds(), 900);
|
||||
custom.set(7);
|
||||
assert_eq!(platform.local_hardware().wall_clock().utc_unix_seconds(), 7);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use prometeu_hal::WallClock;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// A native harness-controlled civil clock. Reads and runtime ticks never advance it.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ControlledWallClock {
|
||||
seconds: AtomicU64,
|
||||
}
|
||||
|
||||
impl ControlledWallClock {
|
||||
pub fn new(seconds: u64) -> Self {
|
||||
Self { seconds: AtomicU64::new(seconds) }
|
||||
}
|
||||
|
||||
/// Set civil time explicitly, including backwards adjustments.
|
||||
pub fn set(&self, seconds: u64) {
|
||||
self.seconds.store(seconds, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Advance civil time explicitly, saturating at the largest timestamp.
|
||||
// `try_update` requires Rust 1.95; keep older stable CI toolchains compatible.
|
||||
#[allow(deprecated)]
|
||||
pub fn advance(&self, seconds: u64) {
|
||||
// Harness control may retry on a concurrent update; reads remain a single load.
|
||||
let _ = self.seconds.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
|
||||
Some(current.saturating_add(seconds))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl WallClock for ControlledWallClock {
|
||||
fn utc_unix_seconds(&self) -> u64 {
|
||||
self.seconds.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn explicit_changes_allow_regression_and_saturate_without_advancing_on_read() {
|
||||
let clock = ControlledWallClock::default();
|
||||
assert_eq!(clock.utc_unix_seconds(), 0);
|
||||
clock.set(100);
|
||||
for _ in 0..10 {
|
||||
assert_eq!(clock.utc_unix_seconds(), 100);
|
||||
}
|
||||
clock.advance(9);
|
||||
assert_eq!(clock.utc_unix_seconds(), 109);
|
||||
clock.set(3);
|
||||
assert_eq!(clock.utc_unix_seconds(), 3);
|
||||
clock.advance(u64::MAX);
|
||||
clock.advance(1);
|
||||
assert_eq!(clock.utc_unix_seconds(), u64::MAX);
|
||||
clock.set(0);
|
||||
assert_eq!(clock.utc_unix_seconds(), 0);
|
||||
}
|
||||
}
|
||||
@@ -12,3 +12,4 @@ prometeu-hal = { path = "../prometeu-hal" }
|
||||
[dev-dependencies]
|
||||
prometeu-drivers = { path = "../prometeu-drivers" }
|
||||
prometeu-bytecode = { path = "../prometeu-bytecode" }
|
||||
prometeu-test-support = { path = "../../dev/prometeu-test-support" }
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,9 +1,11 @@
|
||||
pub use crate::firmware::firmware_step_confirm_discard::ConfirmDiscardStep;
|
||||
pub use crate::firmware::firmware_step_crash_screen::AppCrashesStep;
|
||||
pub use crate::firmware::firmware_step_game_running::GameRunningStep;
|
||||
pub use crate::firmware::firmware_step_hub_home::HubHomeStep;
|
||||
pub use crate::firmware::firmware_step_launch_hub::LaunchHubStep;
|
||||
pub use crate::firmware::firmware_step_load_cartridge::LoadCartridgeStep;
|
||||
pub use crate::firmware::firmware_step_reset::ResetStep;
|
||||
pub use crate::firmware::firmware_step_shell_running::ShellRunningStep;
|
||||
pub use crate::firmware::firmware_step_splash_screen::SplashScreenStep;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -12,7 +14,12 @@ pub enum FirmwareState {
|
||||
SplashScreen(SplashScreenStep),
|
||||
LaunchHub(LaunchHubStep),
|
||||
HubHome(HubHomeStep),
|
||||
ConfirmDiscard(ConfirmDiscardStep),
|
||||
LoadCartridge(LoadCartridgeStep),
|
||||
ResumeResidentGame,
|
||||
MemoryIoFault,
|
||||
MemoryCardRemoved(super::firmware_step_confirm_discard::MemoryCardRemovedStep),
|
||||
GameRunning(GameRunningStep),
|
||||
ShellRunning(ShellRunningStep),
|
||||
AppCrashes(AppCrashesStep),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
use super::{
|
||||
firmware_state::{FirmwareState, HubHomeStep, LoadCartridgeStep},
|
||||
prometeu_context::PrometeuContext,
|
||||
resident_game_termination,
|
||||
};
|
||||
use prometeu_hal::{
|
||||
FrameId, GfxUiCommand, RenderSubmission, ShellUiFramePacket, cartridge::Cartridge, color::Color,
|
||||
};
|
||||
|
||||
/// Player-owned exit decision. It never starts a save implicitly.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ConfirmDiscardStep {
|
||||
next: Option<Cartridge>,
|
||||
released: bool,
|
||||
}
|
||||
impl ConfirmDiscardStep {
|
||||
pub fn new(next: Option<Cartridge>) -> Self {
|
||||
Self { next, released: false }
|
||||
}
|
||||
pub fn on_enter(&mut self, _ctx: &mut PrometeuContext) {}
|
||||
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||
let lines = [
|
||||
"Unsaved progress",
|
||||
"Leaving this game will discard RAM saves.",
|
||||
"A: Discard and leave",
|
||||
"B: Return to Home without leaving the game",
|
||||
];
|
||||
let mut commands = vec![GfxUiCommand::Clear { color: Color::BLACK }];
|
||||
commands.extend(lines.into_iter().enumerate().map(|(i, text)| GfxUiCommand::DrawText {
|
||||
x: 8,
|
||||
y: 8 + i as i32 * 20,
|
||||
text: text.into(),
|
||||
color: Color::WHITE,
|
||||
}));
|
||||
let _ = ctx.platform.render_submission_sink().submit_render_submission(
|
||||
RenderSubmission::shell_ui(FrameId::ZERO, ShellUiFramePacket::new(commands)),
|
||||
);
|
||||
if !ctx.signals.a_signal && !ctx.signals.b_signal {
|
||||
self.released = true;
|
||||
}
|
||||
if self.released && ctx.signals.b_signal {
|
||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||
}
|
||||
if self.released && ctx.signals.a_signal {
|
||||
if resident_game_termination::terminate_resident_game(ctx.os, ctx.platform, true)
|
||||
.is_err()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
return Some(match self.next.take() {
|
||||
Some(card) => {
|
||||
FirmwareState::LoadCartridge(LoadCartridgeStep::new_game_switch(card))
|
||||
}
|
||||
None => FirmwareState::HubHome(HubHomeStep),
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MemoryCardRemovedStep {
|
||||
released: bool,
|
||||
}
|
||||
impl MemoryCardRemovedStep {
|
||||
pub fn on_enter(&mut self, _ctx: &mut PrometeuContext) {}
|
||||
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||
if !ctx.os.memcard().session.removal_pending() {
|
||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||
}
|
||||
let lines = [
|
||||
"Memory card is unavailable.",
|
||||
"Progress remains in memory.",
|
||||
"Reinsert a card through the host, or choose:",
|
||||
"A: Continue without saving to disk",
|
||||
"B: Leave the game",
|
||||
];
|
||||
let mut commands = vec![GfxUiCommand::Clear { color: Color::BLACK }];
|
||||
commands.extend(lines.into_iter().enumerate().map(|(i, text)| GfxUiCommand::DrawText {
|
||||
x: 8,
|
||||
y: 8 + i as i32 * 20,
|
||||
text: text.into(),
|
||||
color: Color::WHITE,
|
||||
}));
|
||||
let _ = ctx.platform.render_submission_sink().submit_render_submission(
|
||||
RenderSubmission::shell_ui(FrameId::ZERO, ShellUiFramePacket::new(commands)),
|
||||
);
|
||||
if !ctx.signals.a_signal && !ctx.signals.b_signal {
|
||||
self.released = true;
|
||||
}
|
||||
if self.released && ctx.signals.a_signal && ctx.os.detach_memcard().is_ok() {
|
||||
return Some(FirmwareState::ResumeResidentGame);
|
||||
}
|
||||
if self.released && ctx.signals.b_signal {
|
||||
return Some(FirmwareState::ConfirmDiscard(ConfirmDiscardStep::new(None)));
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep};
|
||||
use crate::firmware::prometeu_context::PrometeuContext;
|
||||
use prometeu_hal::color::Color;
|
||||
use prometeu_hal::log::{LogLevel, LogSource};
|
||||
use prometeu_hal::{FrameId, GfxUiCommand, RenderSubmission, ShellUiFramePacket};
|
||||
use prometeu_system::CrashReport;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -20,16 +21,30 @@ impl AppCrashesStep {
|
||||
|
||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||
// Update peripherals for input on the crash screen
|
||||
ctx.hw.pad_mut().begin_frame(ctx.signals);
|
||||
ctx.platform.input_mut().pad_mut().begin_frame(ctx.signals);
|
||||
|
||||
// Error screen: red background, white text
|
||||
ctx.hw.gfx_mut().clear(Color::RED);
|
||||
// For now we just log or show something simple
|
||||
// In the future, use draw_text
|
||||
ctx.hw.gfx_mut().present();
|
||||
let mut commands = vec![GfxUiCommand::Clear { color: Color::RED }];
|
||||
if let CrashReport::VmPanic { message, .. } = &self.report
|
||||
&& message.starts_with("Memcard")
|
||||
{
|
||||
let text: Vec<char> = message.chars().take(240).collect();
|
||||
commands.extend(text.chunks(48).enumerate().map(|(line, chars)| {
|
||||
GfxUiCommand::DrawText {
|
||||
x: 8,
|
||||
y: 8 + line as i32 * 20,
|
||||
text: chars.iter().collect(),
|
||||
color: Color::WHITE,
|
||||
}
|
||||
}));
|
||||
}
|
||||
let packet = ShellUiFramePacket::new(commands);
|
||||
ctx.platform
|
||||
.render_submission_sink()
|
||||
.submit_render_submission(RenderSubmission::shell_ui(FrameId::ZERO, packet))
|
||||
.expect("firmware crash render submission should publish");
|
||||
|
||||
// If START is pressed, return to the Hub
|
||||
if ctx.hw.pad().start().down {
|
||||
if ctx.platform.input().pad().start().down {
|
||||
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
||||
}
|
||||
|
||||
@@ -54,6 +69,7 @@ mod tests {
|
||||
message: "type mismatch".into(),
|
||||
pc: 0x44,
|
||||
span: None,
|
||||
resource: None,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,23 +1,81 @@
|
||||
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState};
|
||||
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState, HubHomeStep};
|
||||
use crate::firmware::prometeu_context::PrometeuContext;
|
||||
use prometeu_hal::app_mode::AppMode;
|
||||
use prometeu_hal::log::{LogLevel, LogSource};
|
||||
use prometeu_system::task::{TaskId, TaskState};
|
||||
use prometeu_system::{CrashReport, ResidentGameState};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct GameRunningStep;
|
||||
pub struct GameRunningStep {
|
||||
pub task_id: TaskId,
|
||||
}
|
||||
|
||||
impl GameRunningStep {
|
||||
pub fn new(task_id: TaskId) -> Self {
|
||||
Self { task_id }
|
||||
}
|
||||
|
||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Entering GameRunning".to_string());
|
||||
}
|
||||
|
||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||
let result = ctx.os.tick(ctx.vm, ctx.signals, ctx.hw);
|
||||
let Some(task_state) = ctx.os.lifecycle().task_state(self.task_id) else {
|
||||
// TODO: is it panic?
|
||||
let report =
|
||||
CrashReport::VmPanic { message: "task is gone, panic!".to_string(), pc: None };
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
};
|
||||
|
||||
if !ctx.os.logical_frame_active {
|
||||
ctx.hw.gfx_mut().present();
|
||||
if matches!(task_state, TaskState::Suspended | TaskState::Closed) {
|
||||
ctx.os.vm().transition_render_owner(AppMode::Shell, 0);
|
||||
return Some(match ctx.os.lifecycle().foreground_owner() {
|
||||
prometeu_system::ForegroundOwner::Shell(task_id) => FirmwareState::ShellRunning(
|
||||
crate::firmware::firmware_state::ShellRunningStep::new(task_id),
|
||||
),
|
||||
_ => FirmwareState::HubHome(HubHomeStep),
|
||||
});
|
||||
}
|
||||
if task_state != TaskState::Foreground {
|
||||
// TODO: is it panic?
|
||||
let report = CrashReport::VmPanic {
|
||||
message: "should be running as foreground, panic!".to_string(),
|
||||
pc: None,
|
||||
};
|
||||
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
}
|
||||
|
||||
result.map(|report| FirmwareState::AppCrashes(AppCrashesStep { report }))
|
||||
let pause_requested = matches!(
|
||||
ctx.os.lifecycle().resident_game().map(|game| game.state),
|
||||
Some(ResidentGameState::PauseRequested { .. })
|
||||
);
|
||||
let result = ctx.os.vm().tick_session(self.task_id, ctx.signals, ctx.platform);
|
||||
|
||||
if let Some(report) = result {
|
||||
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
}
|
||||
|
||||
if pause_requested {
|
||||
match ctx.os.lifecycle().advance_game_pause_budget(self.task_id) {
|
||||
Ok(true) => {
|
||||
ctx.os.vm().transition_render_owner(AppMode::Shell, 0);
|
||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(_) => {
|
||||
let report = CrashReport::VmPanic {
|
||||
message: "failed to advance game pause budget".to_string(),
|
||||
pc: None,
|
||||
};
|
||||
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState};
|
||||
use crate::firmware::firmware_state::{
|
||||
AppCrashesStep, FirmwareState, LoadCartridgeStep, ShellRunningStep,
|
||||
};
|
||||
use crate::firmware::prometeu_context::PrometeuContext;
|
||||
use crate::firmware::resident_game_termination;
|
||||
use prometeu_hal::app_mode::AppMode;
|
||||
use prometeu_hal::cartridge_loader::CartridgeLoader;
|
||||
use prometeu_hal::log::{LogLevel, LogSource};
|
||||
use prometeu_hal::primitives::Rect;
|
||||
use prometeu_system::SystemProfileAction;
|
||||
use prometeu_system::windows::WindowOwner;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HubHomeStep;
|
||||
@@ -8,30 +16,130 @@ pub struct HubHomeStep;
|
||||
impl HubHomeStep {
|
||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||
ctx.os.log(LogLevel::Info, LogSource::Hub, 0, "Entering HubHome".to_string());
|
||||
ctx.os.windows().remove_all_windows();
|
||||
ctx.hub.init();
|
||||
}
|
||||
|
||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||
let mut error = None;
|
||||
|
||||
// Always updates the Hub GUI (clears screen and processes input if no focus)
|
||||
ctx.hub.gui_update(ctx.os, ctx.hw);
|
||||
|
||||
if let Some(focused_id) = ctx.hub.window_manager.focused {
|
||||
if ctx.hw.pad().start().down {
|
||||
ctx.hub.window_manager.remove_window(focused_id);
|
||||
} else {
|
||||
// System App runs here, drawing over the Hub background
|
||||
error = ctx.os.tick(ctx.vm, ctx.signals, ctx.hw);
|
||||
}
|
||||
let outcome = ctx.hub.update_shell_profile(ctx.os, ctx.platform);
|
||||
if let Some(report) = outcome.crash {
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
}
|
||||
|
||||
// Renders the System App window borders
|
||||
ctx.hub.render(ctx.os, ctx.hw);
|
||||
match outcome.action {
|
||||
Some(SystemProfileAction::LaunchNativeShell(app)) => {
|
||||
let task_id = match ctx
|
||||
.os
|
||||
.sessions()
|
||||
.try_create_native_shell_task(app.app_id(), app.title())
|
||||
{
|
||||
Ok(task_id) => task_id,
|
||||
Err(error) => {
|
||||
ctx.os.log(
|
||||
LogLevel::Warn,
|
||||
LogSource::Hub,
|
||||
0,
|
||||
format!("Failed to launch native shell {}: {:?}", app.title(), error),
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let id = ctx.os.windows().add_window(
|
||||
app.title().to_string(),
|
||||
WindowOwner::Task(task_id),
|
||||
Rect { x: 40, y: 20, w: 400, h: 220 },
|
||||
app.color(),
|
||||
);
|
||||
ctx.os.windows().set_focus(id);
|
||||
return Some(FirmwareState::ShellRunning(ShellRunningStep::new(task_id)));
|
||||
}
|
||||
Some(SystemProfileAction::LaunchGame { target }) => {
|
||||
match CartridgeLoader::load(&target.path) {
|
||||
Ok(cartridge) => {
|
||||
if ctx.os.lifecycle().resident_game_task().is_none()
|
||||
&& ctx.os.memcard().session.mode().is_some()
|
||||
{
|
||||
if ctx.os.memcard().session.unsaved() {
|
||||
return Some(FirmwareState::ConfirmDiscard(
|
||||
super::firmware_state::ConfirmDiscardStep::new(Some(cartridge)),
|
||||
));
|
||||
}
|
||||
ctx.os.memcard().session.end_session();
|
||||
}
|
||||
if cartridge.app_mode == AppMode::Game
|
||||
&& let Some(resident_task_id) = ctx.os.lifecycle().resident_game_task()
|
||||
{
|
||||
let resident_app_id = ctx
|
||||
.os
|
||||
.sessions()
|
||||
.vm_session_for_task(resident_task_id)
|
||||
.map(|session| session.app_id)
|
||||
.unwrap_or(0);
|
||||
|
||||
ctx.hw.gfx_mut().present();
|
||||
if resident_app_id == cartridge.app_id {
|
||||
return Some(FirmwareState::ResumeResidentGame);
|
||||
}
|
||||
|
||||
if let Some(report) = error {
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
if ctx.os.memcard().session.unsaved() {
|
||||
return Some(FirmwareState::ConfirmDiscard(
|
||||
super::firmware_state::ConfirmDiscardStep::new(Some(cartridge)),
|
||||
));
|
||||
}
|
||||
if let Err(error) = resident_game_termination::terminate_resident_game(
|
||||
ctx.os,
|
||||
ctx.platform,
|
||||
false,
|
||||
) {
|
||||
ctx.os.log(
|
||||
LogLevel::Error,
|
||||
LogSource::Hub,
|
||||
0,
|
||||
format!(
|
||||
"Failed to terminate resident game app_id {} before launching {}: {:?}",
|
||||
resident_app_id, cartridge.title, error
|
||||
),
|
||||
);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
return Some(FirmwareState::LoadCartridge(
|
||||
LoadCartridgeStep::new_game_switch(cartridge),
|
||||
));
|
||||
}
|
||||
Err(error) => {
|
||||
ctx.os.log(
|
||||
LogLevel::Error,
|
||||
LogSource::Hub,
|
||||
0,
|
||||
format!(
|
||||
"Failed to launch Home game {}: {:?}",
|
||||
target.path.display(),
|
||||
error
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(SystemProfileAction::KillResidentGame) => {
|
||||
if ctx.os.memcard().session.unsaved() {
|
||||
return Some(FirmwareState::ConfirmDiscard(
|
||||
super::firmware_state::ConfirmDiscardStep::new(None),
|
||||
));
|
||||
}
|
||||
|
||||
if let Err(error) =
|
||||
resident_game_termination::terminate_resident_game(ctx.os, ctx.platform, true)
|
||||
{
|
||||
ctx.os.log(
|
||||
LogLevel::Error,
|
||||
LogSource::Hub,
|
||||
0,
|
||||
format!("Failed to kill resident game from Hub: {error:?}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
Some(SystemProfileAction::CloseShell) | None => {}
|
||||
}
|
||||
|
||||
None
|
||||
|
||||
@@ -1,22 +1,75 @@
|
||||
use crate::firmware::firmware_state::{
|
||||
AppCrashesStep, FirmwareState, GameRunningStep, HubHomeStep,
|
||||
AppCrashesStep, FirmwareState, GameRunningStep, HubHomeStep, ShellRunningStep,
|
||||
};
|
||||
use crate::firmware::prometeu_context::PrometeuContext;
|
||||
use prometeu_hal::cartridge::{AppMode, Cartridge};
|
||||
use crate::firmware::resident_game_termination;
|
||||
use prometeu_hal::app_mode::AppMode;
|
||||
use prometeu_hal::cartridge::Cartridge;
|
||||
use prometeu_hal::color::Color;
|
||||
use prometeu_hal::log::{LogLevel, LogSource};
|
||||
use prometeu_hal::window::Rect;
|
||||
use prometeu_hal::primitives::Rect;
|
||||
use prometeu_system::CrashReport;
|
||||
use prometeu_system::windows::WindowOwner;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LoadCartridgeStep {
|
||||
pub cartridge: Cartridge,
|
||||
init_error: Option<CrashReport>,
|
||||
awaiting_memcard: bool,
|
||||
preparing_memcard: bool,
|
||||
input_released: bool,
|
||||
memcard_message: String,
|
||||
loaded_task_id: Option<prometeu_system::task::TaskId>,
|
||||
loaded_app_mode: Option<AppMode>,
|
||||
failure_recovery: LoadCartridgeFailureRecovery,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum LoadCartridgeFailureRecovery {
|
||||
AppCrash,
|
||||
ReturnToHub,
|
||||
}
|
||||
|
||||
impl LoadCartridgeStep {
|
||||
pub fn new(cartridge: Cartridge) -> Self {
|
||||
Self { cartridge, init_error: None }
|
||||
Self {
|
||||
cartridge,
|
||||
init_error: None,
|
||||
awaiting_memcard: false,
|
||||
preparing_memcard: false,
|
||||
input_released: false,
|
||||
memcard_message: String::new(),
|
||||
loaded_task_id: None,
|
||||
loaded_app_mode: None,
|
||||
failure_recovery: LoadCartridgeFailureRecovery::AppCrash,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_memcard_choice(&self) -> bool {
|
||||
self.awaiting_memcard && !self.preparing_memcard
|
||||
}
|
||||
/// Typed host and UI admission share this single policy boundary.
|
||||
pub fn choose_memcard(
|
||||
&mut self,
|
||||
os: &mut prometeu_system::SystemOS,
|
||||
choice: prometeu_system::memcard::admission::Choice,
|
||||
created_at: u64,
|
||||
) -> prometeu_system::memcard::image::Result<()> {
|
||||
if !self.needs_memcard_choice() {
|
||||
return Err(prometeu_system::memcard::image::Error::InvalidState);
|
||||
}
|
||||
os.memcard().choose_for_game(
|
||||
self.cartridge.app_id,
|
||||
self.cartridge.memcard_slots.unwrap() as usize,
|
||||
choice,
|
||||
created_at,
|
||||
)?;
|
||||
self.preparing_memcard = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn new_game_switch(cartridge: Cartridge) -> Self {
|
||||
Self { failure_recovery: LoadCartridgeFailureRecovery::ReturnToHub, ..Self::new(cartridge) }
|
||||
}
|
||||
|
||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||
@@ -27,35 +80,216 @@ impl LoadCartridgeStep {
|
||||
format!("Loading cartridge: {}", self.cartridge.title),
|
||||
);
|
||||
|
||||
ctx.platform.game2d_frame_composer().unbind_scene();
|
||||
|
||||
if self.cartridge.app_mode == AppMode::Game && self.cartridge.memcard_slots.is_some() {
|
||||
self.awaiting_memcard = true;
|
||||
ctx.os.vm().transition_render_owner(AppMode::Shell, 0);
|
||||
return;
|
||||
}
|
||||
self.load(ctx);
|
||||
}
|
||||
|
||||
fn load(&mut self, ctx: &mut PrometeuContext) {
|
||||
// Initialize Asset Manager
|
||||
ctx.hw.assets_mut().initialize_for_cartridge(
|
||||
ctx.platform.assets_mut().initialize_for_cartridge(
|
||||
self.cartridge.asset_table.clone(),
|
||||
self.cartridge.preload.clone(),
|
||||
self.cartridge.assets.clone(),
|
||||
);
|
||||
|
||||
self.init_error = ctx.os.initialize_vm(ctx.vm, &self.cartridge).err();
|
||||
match ctx.os.sessions().load_vm_cartridge(&self.cartridge) {
|
||||
Ok(loaded) => {
|
||||
self.loaded_task_id = Some(loaded.task_id);
|
||||
self.loaded_app_mode = Some(loaded.app_mode);
|
||||
}
|
||||
Err(report) => {
|
||||
self.init_error = Some(report.into_crash_report("load VM cartridge into session"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||
if self.awaiting_memcard {
|
||||
use prometeu_system::memcard::admission::{Choice, PreparationState};
|
||||
if self.preparing_memcard {
|
||||
match ctx.os.memcard().admission.state {
|
||||
PreparationState::Ready => {
|
||||
self.awaiting_memcard = false;
|
||||
self.preparing_memcard = false;
|
||||
self.load(ctx);
|
||||
}
|
||||
PreparationState::Failed(error) => {
|
||||
self.memcard_message = Self::preparation_message(error);
|
||||
self.preparing_memcard = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if self.awaiting_memcard {
|
||||
let pressed = ctx.signals.a_signal
|
||||
|| ctx.signals.b_signal
|
||||
|| ctx.signals.x_signal
|
||||
|| ctx.signals.y_signal;
|
||||
if !pressed {
|
||||
self.input_released = true;
|
||||
}
|
||||
if self.input_released && pressed && !self.preparing_memcard {
|
||||
self.input_released = false;
|
||||
if ctx.signals.b_signal {
|
||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||
}
|
||||
let choice = if ctx.signals.a_signal {
|
||||
Choice::Persistent
|
||||
} else if ctx.signals.x_signal {
|
||||
Choice::MemoryFresh
|
||||
} else {
|
||||
Choice::MemoryExisting
|
||||
};
|
||||
let created_at = ctx.platform.wall_clock().utc_unix_seconds();
|
||||
match self.choose_memcard(ctx.os, choice, created_at) {
|
||||
Ok(()) => {}
|
||||
Err(error) => self.memcard_message = Self::preparation_message(error),
|
||||
}
|
||||
}
|
||||
self.draw_memcard(ctx);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(report) = self.init_error.take() {
|
||||
if self.failure_recovery == LoadCartridgeFailureRecovery::ReturnToHub {
|
||||
if self.cartridge.app_mode == AppMode::Game
|
||||
&& let Some(task_id) = ctx.os.lifecycle().resident_game_task()
|
||||
{
|
||||
let is_partial_target = ctx
|
||||
.os
|
||||
.sessions()
|
||||
.vm_session_for_task(task_id)
|
||||
.map(|session| session.app_id == self.cartridge.app_id)
|
||||
.unwrap_or(false);
|
||||
|
||||
if is_partial_target {
|
||||
let _ = resident_game_termination::terminate_resident_game(
|
||||
ctx.os,
|
||||
ctx.platform,
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
ctx.os.log(
|
||||
LogLevel::Error,
|
||||
LogSource::Hub,
|
||||
0,
|
||||
format!(
|
||||
"Failed to switch to game {} app_id {}; returning to Home: {:?}",
|
||||
self.cartridge.title, self.cartridge.app_id, report
|
||||
),
|
||||
);
|
||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||
}
|
||||
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
}
|
||||
|
||||
if self.cartridge.app_mode == AppMode::System {
|
||||
let id = ctx.hub.window_manager.add_window(
|
||||
match ctx.platform.assets().preloads_ready() {
|
||||
Ok(false) => return None,
|
||||
Err(error) => {
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep {
|
||||
report: CrashReport::VmPanic {
|
||||
message: format!("Cartridge preload failed: {error:?}"),
|
||||
pc: None,
|
||||
},
|
||||
}));
|
||||
}
|
||||
Ok(true) => {}
|
||||
}
|
||||
let Some(task_id) = self.loaded_task_id.take() else {
|
||||
let report = CrashReport::VmPanic {
|
||||
message: format!(
|
||||
"cartridge {} was not loaded into a VM session",
|
||||
self.cartridge.title
|
||||
),
|
||||
pc: None,
|
||||
};
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
};
|
||||
|
||||
if self.loaded_app_mode == Some(AppMode::Shell) {
|
||||
let id = ctx.os.windows().add_window(
|
||||
self.cartridge.title.clone(),
|
||||
WindowOwner::Task(task_id),
|
||||
Rect { x: 40, y: 20, w: 240, h: 140 },
|
||||
Color::WHITE,
|
||||
);
|
||||
ctx.hub.window_manager.set_focus(id);
|
||||
|
||||
// System apps do not change the firmware state to GameRunning.
|
||||
// They run in the background or via windows in the Hub.
|
||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||
ctx.os.windows().set_focus(id);
|
||||
return Some(FirmwareState::ShellRunning(ShellRunningStep::new(task_id)));
|
||||
}
|
||||
|
||||
Some(FirmwareState::GameRunning(GameRunningStep))
|
||||
Some(FirmwareState::GameRunning(GameRunningStep::new(task_id)))
|
||||
}
|
||||
|
||||
fn preparation_message(error: prometeu_system::memcard::image::Error) -> String {
|
||||
use prometeu_system::memcard::image::Error;
|
||||
match error {
|
||||
Error::NoSpace => "This memory card has no room for this game.".into(),
|
||||
Error::Corrupt => "The memory card failed its integrity checks.".into(),
|
||||
Error::ReadOnly => "This memory card cannot accept saves.".into(),
|
||||
Error::OutOfMemory => "There is not enough memory to start this game.".into(),
|
||||
Error::Busy => "The memory card is still busy. Please wait.".into(),
|
||||
Error::InvalidState => "No usable memory card or existing save is available.".into(),
|
||||
_ => format!("Memory card unavailable: {error:?}"),
|
||||
}
|
||||
}
|
||||
fn draw_memcard(&self, ctx: &mut PrometeuContext) {
|
||||
use prometeu_hal::{FrameId, GfxUiCommand, RenderSubmission, ShellUiFramePacket};
|
||||
let installed = ctx.os.memcard().card_installed();
|
||||
let existing = ctx.os.memcard().card_has_game(self.cartridge.app_id);
|
||||
let mut lines = vec!["Save memory".to_string(), self.cartridge.title.clone()];
|
||||
if let Some((recovered, degraded, blocked)) = ctx.os.memcard().installed_health() {
|
||||
if recovered {
|
||||
lines.push("Recovered an older save after an integrity failure.".into());
|
||||
}
|
||||
if degraded {
|
||||
lines.push("Memory card degraded: some blocks are excluded.".into());
|
||||
}
|
||||
if blocked {
|
||||
lines.push("Disk saving is unavailable on this card.".into());
|
||||
}
|
||||
}
|
||||
if let prometeu_system::memcard::admission::PreparationState::Failed(error) =
|
||||
ctx.os.memcard().admission.state
|
||||
{
|
||||
lines.push(Self::preparation_message(error));
|
||||
}
|
||||
|
||||
if self.preparing_memcard {
|
||||
lines.push("Preparing save memory...".into());
|
||||
} else {
|
||||
lines.push(
|
||||
if installed { "A: Use installed memory card" } else { "No memory card installed" }
|
||||
.into(),
|
||||
);
|
||||
lines.push("X: Start fresh without saving to disk".into());
|
||||
if existing {
|
||||
lines.push("Y: Load saves, then play without disk saving".into());
|
||||
}
|
||||
lines.push("B: Return to Home".into());
|
||||
}
|
||||
if !self.memcard_message.is_empty() {
|
||||
lines.push(self.memcard_message.clone());
|
||||
}
|
||||
let mut commands = vec![GfxUiCommand::Clear { color: Color::BLACK }];
|
||||
commands.extend(lines.into_iter().enumerate().map(|(i, text)| GfxUiCommand::DrawText {
|
||||
x: 8,
|
||||
y: 8 + i as i32 * 20,
|
||||
text,
|
||||
color: Color::WHITE,
|
||||
}));
|
||||
let _ = ctx.platform.render_submission_sink().submit_render_submission(
|
||||
RenderSubmission::shell_ui(FrameId::ZERO, ShellUiFramePacket::new(commands)),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||
|
||||
@@ -9,7 +9,14 @@ pub struct ResetStep;
|
||||
impl ResetStep {
|
||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Firmware Reset".to_string());
|
||||
ctx.os.reset(ctx.vm);
|
||||
// Reset is a cold-boot boundary. Clearing only the VM session leaves
|
||||
// the lifecycle registry pointing at the old resident game, which
|
||||
// rejects the next cartridge as a second resident game.
|
||||
let _ = ctx.os.lifecycle().terminate_resident_game();
|
||||
ctx.os.sessions().clear_vm_sessions();
|
||||
ctx.os.vm().reset_global_runtime_state();
|
||||
ctx.platform.audio_mut().reset();
|
||||
ctx.platform.audio_mut().set_session(None);
|
||||
}
|
||||
|
||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState, HubHomeStep};
|
||||
use crate::firmware::prometeu_context::PrometeuContext;
|
||||
use prometeu_hal::log::LogSource;
|
||||
use prometeu_system::process::ProcessKind;
|
||||
use prometeu_system::task::{TaskId, TaskState};
|
||||
use prometeu_system::{CrashReport, SystemProfileAction};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ShellRunningStep {
|
||||
pub task_id: TaskId,
|
||||
}
|
||||
|
||||
impl ShellRunningStep {
|
||||
pub fn new(task_id: TaskId) -> Self {
|
||||
Self { task_id }
|
||||
}
|
||||
|
||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||
ctx.os.info(LogSource::Hub, "Entering ShellRunning".to_string());
|
||||
}
|
||||
|
||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||
let Some(task_state) = ctx.os.lifecycle().task_state(self.task_id) else {
|
||||
let report = CrashReport::VmPanic {
|
||||
message: format!("ShellRunningStep has no task for {:?}", self.task_id),
|
||||
pc: None,
|
||||
};
|
||||
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
};
|
||||
|
||||
match task_state {
|
||||
TaskState::Foreground => {
|
||||
// Continue below.
|
||||
}
|
||||
|
||||
TaskState::Closed => {
|
||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||
}
|
||||
|
||||
TaskState::Crashed => {
|
||||
let report = CrashReport::VmPanic {
|
||||
message: format!("Shell task {:?} is already crashed", self.task_id),
|
||||
pc: None,
|
||||
};
|
||||
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
}
|
||||
|
||||
TaskState::Suspended | TaskState::Background => {
|
||||
let report = CrashReport::VmPanic {
|
||||
message: format!(
|
||||
"ShellRunningStep expected foreground task {:?}, got {:?}",
|
||||
self.task_id, task_state,
|
||||
),
|
||||
pc: None,
|
||||
};
|
||||
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
}
|
||||
}
|
||||
|
||||
let process_kind = match ctx.os.lifecycle().process_kind_for_task(self.task_id) {
|
||||
Ok(process_kind) => process_kind,
|
||||
Err(error) => {
|
||||
let report = CrashReport::VmPanic {
|
||||
message: format!(
|
||||
"ShellRunningStep cannot resolve process for {:?}: {:?}",
|
||||
self.task_id, error,
|
||||
),
|
||||
pc: None,
|
||||
};
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
}
|
||||
};
|
||||
|
||||
let outcome = match process_kind {
|
||||
ProcessKind::VmShell => {
|
||||
ctx.hub.update_vm_shell_profile(ctx.os, self.task_id, ctx.signals, ctx.platform)
|
||||
}
|
||||
ProcessKind::NativeShell => ctx.hub.update_native_shell_profile(ctx.os, ctx.platform),
|
||||
ProcessKind::VmGame => {
|
||||
let report = CrashReport::VmPanic {
|
||||
message: format!(
|
||||
"ShellRunningStep expected shell process for {:?}, got VmGame",
|
||||
self.task_id,
|
||||
),
|
||||
pc: None,
|
||||
};
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(report) = outcome.crash {
|
||||
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
}
|
||||
|
||||
if outcome.action == Some(SystemProfileAction::CloseShell) {
|
||||
self.close_current_shell(ctx);
|
||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||
}
|
||||
|
||||
if !ctx.os.windows().focused_window_belongs_to_task(self.task_id) {
|
||||
ctx.os.info(
|
||||
LogSource::Hub,
|
||||
format!(
|
||||
"Closing shell task {:?}: focused window does not belong to task",
|
||||
self.task_id,
|
||||
),
|
||||
);
|
||||
self.close_current_shell(ctx);
|
||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn close_current_shell(&mut self, ctx: &mut PrometeuContext) {
|
||||
if let Err(error) = ctx.os.lifecycle().close_task(self.task_id) {
|
||||
ctx.os.error(
|
||||
LogSource::Hub,
|
||||
format!("Failed to close shell task {:?}: {:?}", self.task_id, error),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_exit(&mut self, ctx: &mut PrometeuContext) {
|
||||
ctx.os.info(LogSource::Hub, "Exiting ShellRunning".to_string());
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep};
|
||||
use crate::firmware::prometeu_context::PrometeuContext;
|
||||
use prometeu_hal::color::Color;
|
||||
use prometeu_hal::log::{LogLevel, LogSource};
|
||||
use prometeu_hal::primitives::Rect;
|
||||
use prometeu_hal::{FrameId, GfxUiCommand, RenderSubmission, ShellUiFramePacket};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SplashScreenStep {
|
||||
@@ -12,7 +14,7 @@ impl SplashScreenStep {
|
||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Showing SplashScreen".to_string());
|
||||
// Play sound on enter
|
||||
// ctx.hw.audio_mut().play(0, 0, 0, 255, 127, 1.0, 0, LoopMode::Off);
|
||||
// ctx.platform.audio_mut().play(0, 0, 0, 255, 127, 1.0, 0, LoopMode::Off);
|
||||
}
|
||||
|
||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||
@@ -20,13 +22,10 @@ impl SplashScreenStep {
|
||||
const TOTAL_DURATION: u32 = 240; // 4 seconds total (updated from 2s based on total_duration logic)
|
||||
|
||||
// Update peripherals for input
|
||||
ctx.hw.pad_mut().begin_frame(ctx.signals);
|
||||
|
||||
// Clear screen
|
||||
ctx.hw.gfx_mut().clear(Color::BLACK);
|
||||
ctx.platform.input_mut().pad_mut().begin_frame(ctx.signals);
|
||||
|
||||
// Draw expanding square
|
||||
let (sw, sh) = ctx.hw.gfx().size();
|
||||
let (sw, sh) = ctx.platform.display_size();
|
||||
let max_size = (sw.min(sh) as i32 / 2).max(1);
|
||||
|
||||
let current_size = if self.frame < ANIMATION_DURATION {
|
||||
@@ -38,12 +37,21 @@ impl SplashScreenStep {
|
||||
let x = (sw as i32 - current_size) / 2;
|
||||
let y = (sh as i32 - current_size) / 2;
|
||||
|
||||
ctx.hw.gfx_mut().fill_rect(x, y, current_size, current_size, Color::WHITE);
|
||||
ctx.hw.gfx_mut().present();
|
||||
let packet = ShellUiFramePacket::new(vec![
|
||||
GfxUiCommand::Clear { color: Color::ORANGE },
|
||||
GfxUiCommand::FillRect {
|
||||
rect: Rect { x, y, w: current_size, h: current_size },
|
||||
color: Color::WHITE,
|
||||
},
|
||||
]);
|
||||
ctx.platform
|
||||
.render_submission_sink()
|
||||
.submit_render_submission(RenderSubmission::shell_ui(FrameId::ZERO, packet))
|
||||
.expect("firmware splash render submission should publish");
|
||||
|
||||
// Transition logic
|
||||
// If any button is pressed at any time after the animation ends
|
||||
if self.frame >= ANIMATION_DURATION && ctx.hw.pad().any() {
|
||||
if self.frame >= ANIMATION_DURATION && ctx.platform.input().pad().any() {
|
||||
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
||||
}
|
||||
|
||||
|
||||
@@ -9,10 +9,14 @@ pub(crate) mod firmware_step_hub_home;
|
||||
pub(crate) mod firmware_step_launch_hub;
|
||||
pub(crate) mod firmware_step_load_cartridge;
|
||||
pub(crate) mod firmware_step_reset;
|
||||
pub(crate) mod firmware_step_shell_running;
|
||||
pub(crate) mod firmware_step_splash_screen;
|
||||
mod prometeu_context;
|
||||
pub(crate) mod resident_game_termination;
|
||||
|
||||
pub use boot_target::BootTarget;
|
||||
pub use firmware::Firmware;
|
||||
pub use firmware_state::FirmwareState;
|
||||
pub use prometeu_context::PrometeuContext;
|
||||
|
||||
pub(crate) mod firmware_step_confirm_discard;
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
use crate::firmware::boot_target::BootTarget;
|
||||
use prometeu_hal::{HardwareBridge, InputSignals};
|
||||
use prometeu_system::{PrometeuHub, VirtualMachineRuntime};
|
||||
use prometeu_vm::VirtualMachine;
|
||||
use prometeu_hal::{InputSignals, RuntimePlatform};
|
||||
use prometeu_system::{PrometeuHub, SystemOS};
|
||||
|
||||
pub struct PrometeuContext<'a> {
|
||||
pub vm: &'a mut VirtualMachine,
|
||||
pub os: &'a mut VirtualMachineRuntime,
|
||||
pub os: &'a mut SystemOS,
|
||||
pub hub: &'a mut PrometeuHub,
|
||||
pub boot_target: &'a BootTarget,
|
||||
pub signals: &'a InputSignals,
|
||||
pub hw: &'a mut dyn HardwareBridge,
|
||||
pub platform: &'a mut dyn RuntimePlatform,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use prometeu_hal::RuntimePlatform;
|
||||
use prometeu_hal::app_mode::AppMode;
|
||||
use prometeu_hal::log::LogSource;
|
||||
use prometeu_system::task::TaskId;
|
||||
use prometeu_system::{LifecycleError, SystemOS};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum ResidentGameTerminationOutcome {
|
||||
NoResidentGame,
|
||||
Terminated { task_id: TaskId, title: String },
|
||||
}
|
||||
|
||||
pub(crate) fn terminate_resident_game(
|
||||
os: &mut SystemOS,
|
||||
platform: &mut dyn RuntimePlatform,
|
||||
log_manual_hub_kill: bool,
|
||||
) -> Result<ResidentGameTerminationOutcome, LifecycleError> {
|
||||
let Some(task_id) = os.lifecycle().resident_game_task() else {
|
||||
os.memcard().session.end_session();
|
||||
return Ok(ResidentGameTerminationOutcome::NoResidentGame);
|
||||
};
|
||||
|
||||
let title = os
|
||||
.sessions()
|
||||
.vm_session_for_task(task_id)
|
||||
.map(|session| session.title.clone())
|
||||
.unwrap_or_else(|| "<unknown>".to_string());
|
||||
|
||||
let terminated = os.lifecycle().terminate_resident_game()?;
|
||||
let Some(task_id) = terminated else {
|
||||
return Ok(ResidentGameTerminationOutcome::NoResidentGame);
|
||||
};
|
||||
|
||||
os.memcard().session.end_session();
|
||||
platform.audio_mut().set_session(None);
|
||||
os.vm().transition_render_owner(AppMode::Shell, 0);
|
||||
platform.game2d_frame_composer().unbind_scene();
|
||||
platform.assets_mut().shutdown();
|
||||
|
||||
if log_manual_hub_kill {
|
||||
os.info(LogSource::Hub, format!("Resident game killed from Hub: {title}"));
|
||||
}
|
||||
|
||||
Ok(ResidentGameTerminationOutcome::Terminated { task_id, title })
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub enum AppMode {
|
||||
Game,
|
||||
Shell,
|
||||
}
|
||||
@@ -53,7 +53,11 @@ pub const SCENE_PAYLOAD_MAGIC_V1: [u8; 4] = *b"SCNE";
|
||||
pub const SCENE_PAYLOAD_VERSION_V1: u16 = 1;
|
||||
pub const SCENE_LAYER_COUNT_V1: usize = 4;
|
||||
pub const SCENE_HEADER_BYTES_V1: usize = 12;
|
||||
pub const SCENE_LAYER_HEADER_BYTES_V1: usize = 28;
|
||||
// Per-layer header:
|
||||
// flags:u8 + glyph_asset_id:i32 + tile_size:u8 + reserved:u16
|
||||
// + parallax_x:f32 + parallax_y:f32 + width:u32 + height:u32
|
||||
// + tile_count:u32 + reserved:u32
|
||||
pub const SCENE_LAYER_HEADER_BYTES_V1: usize = 32;
|
||||
pub const SCENE_TILE_RECORD_BYTES_V1: usize = 4;
|
||||
pub const SCENE_DECODED_LAYER_OVERHEAD_BYTES_V1: usize = 16;
|
||||
|
||||
@@ -108,6 +112,12 @@ pub enum LoadStatus {
|
||||
CANCELED = 4,
|
||||
ERROR = 5,
|
||||
UnknownHandle = 6,
|
||||
QUEUED = 7,
|
||||
ACTIVE = 8,
|
||||
SUPERSEDED = 9,
|
||||
EMPTY = 10,
|
||||
INVALID = 11,
|
||||
BackendUnavailable = 12,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -125,6 +135,36 @@ pub enum AssetOpStatus {
|
||||
Ok = 0,
|
||||
UnknownHandle = 1,
|
||||
InvalidState = 2,
|
||||
Superseded = 3,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AssetBacklogInfo {
|
||||
pub status: AssetOpStatus,
|
||||
pub pending_count: u32,
|
||||
pub active_handle: HandleId,
|
||||
pub active_asset_id: Option<AssetId>,
|
||||
pub active_bank_type: Option<BankType>,
|
||||
pub active_slot: Option<usize>,
|
||||
pub active_progress: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AssetBacklogPosition {
|
||||
pub status: AssetOpStatus,
|
||||
pub state: LoadStatus,
|
||||
pub position: u32,
|
||||
pub progress: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AssetTargetStatus {
|
||||
pub status: AssetOpStatus,
|
||||
pub asset_id: Option<AssetId>,
|
||||
pub handle: HandleId,
|
||||
pub state: LoadStatus,
|
||||
pub position: u32,
|
||||
pub progress: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
|
||||
@@ -1,20 +1,40 @@
|
||||
use crate::asset::{
|
||||
AssetEntry, AssetId, AssetLoadError, AssetOpStatus, BankTelemetry, HandleId, LoadStatus,
|
||||
PreloadEntry, SlotRef, SlotStats,
|
||||
AssetBacklogInfo, AssetBacklogPosition, AssetEntry, AssetId, AssetLoadError, AssetOpStatus,
|
||||
AssetTargetStatus, BankTelemetry, BankType, HandleId, LoadStatus, PreloadEntry, SlotRef,
|
||||
SlotStats,
|
||||
};
|
||||
use crate::cartridge::AssetsPayloadSource;
|
||||
|
||||
pub trait AssetBridge {
|
||||
/// Bind before cartridge preload/loading. Hosts supporting memcard must use
|
||||
/// this same lane for assets; an unsupported bridge refuses the fast profile.
|
||||
fn bind_background_work(
|
||||
&mut self,
|
||||
_lane: std::sync::Arc<dyn crate::background_work::BackgroundWork>,
|
||||
) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn initialize_for_cartridge(
|
||||
&self,
|
||||
assets: Vec<AssetEntry>,
|
||||
preload: Vec<PreloadEntry>,
|
||||
assets_data: AssetsPayloadSource,
|
||||
);
|
||||
/// Admission waits until all preloads are installed. Failure blocks guest boot.
|
||||
fn preloads_ready(&self) -> Result<bool, AssetLoadError> {
|
||||
Ok(true)
|
||||
}
|
||||
fn load(&self, asset_id: AssetId, slot_index: usize) -> Result<HandleId, AssetLoadError>;
|
||||
fn status(&self, handle: HandleId) -> LoadStatus;
|
||||
fn commit(&self, handle: HandleId) -> AssetOpStatus;
|
||||
fn cancel(&self, handle: HandleId) -> AssetOpStatus;
|
||||
fn backlog_info(&self) -> AssetBacklogInfo;
|
||||
fn backlog_position(&self, handle: HandleId) -> AssetBacklogPosition;
|
||||
fn backlog_move(&self, handle: HandleId, new_position: usize) -> AssetOpStatus;
|
||||
fn backlog_promote(&self, handle: HandleId) -> AssetOpStatus;
|
||||
fn backlog_demote(&self, handle: HandleId) -> AssetOpStatus;
|
||||
fn target_status(&self, bank_type: BankType, slot: usize) -> AssetTargetStatus;
|
||||
fn apply_commits(&self);
|
||||
fn bank_telemetry(&self) -> Vec<BankTelemetry>;
|
||||
fn slot_info(&self, slot: SlotRef) -> SlotStats;
|
||||
|
||||
@@ -17,6 +17,7 @@ pub enum AudioOpStatus {
|
||||
AssetNotFound = 4,
|
||||
NoEffect = 5,
|
||||
BankInvalid = 6,
|
||||
CommandLimit = 7,
|
||||
}
|
||||
|
||||
pub trait AudioBridge {
|
||||
@@ -43,10 +44,22 @@ pub trait AudioBridge {
|
||||
priority: u8,
|
||||
loop_mode: LoopMode,
|
||||
) -> AudioOpStatus;
|
||||
fn stop(&mut self, voice_id: usize);
|
||||
fn set_volume(&mut self, voice_id: usize, volume: u8);
|
||||
fn set_pan(&mut self, voice_id: usize, pan: u8);
|
||||
fn set_pitch(&mut self, voice_id: usize, pitch: f64);
|
||||
fn is_playing(&self, voice_id: usize) -> bool;
|
||||
fn clear_commands(&mut self);
|
||||
fn stop(&mut self, voice_id: usize) -> AudioOpStatus;
|
||||
fn set_volume(&mut self, voice_id: usize, volume: u8) -> AudioOpStatus;
|
||||
fn set_pan(&mut self, voice_id: usize, pan: u8) -> AudioOpStatus;
|
||||
fn set_pitch(&mut self, voice_id: usize, pitch: f64) -> AudioOpStatus;
|
||||
/// Pending publication must be consumed before starting another guest frame.
|
||||
fn ready(&self) -> bool;
|
||||
fn begin_frame(&mut self);
|
||||
fn finish_frame(&mut self);
|
||||
fn abort_frame(&mut self);
|
||||
/// Lifecycle has independent bounded staging/publication, even with a pending frame.
|
||||
fn lifecycle_ready(&self) -> bool;
|
||||
fn begin_lifecycle(&mut self);
|
||||
/// Success publishes the interrupted frame prefix before callback commands,
|
||||
/// without replenishing frame quota. Failure cancels both unpublished parts.
|
||||
fn finish_lifecycle(&mut self, success: bool);
|
||||
fn set_session(&mut self, session: Option<u32>);
|
||||
fn reset(&mut self);
|
||||
fn set_paused(&mut self, paused: bool);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
//! Portable submission seam for host-owned cooperative IO execution.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum WorkStep {
|
||||
Yield,
|
||||
Complete,
|
||||
Failed,
|
||||
}
|
||||
pub type AssetWork = Box<dyn FnMut(bool) -> WorkStep + Send + 'static>;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct WorkUnavailable;
|
||||
pub trait BackgroundWork: Send + Sync {
|
||||
fn submit_asset(&self, work: AssetWork) -> Result<(), WorkUnavailable>;
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
use crate::app_mode::AppMode;
|
||||
use crate::asset::{AssetEntry, PreloadEntry};
|
||||
use crate::syscalls::CapFlags;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs::File;
|
||||
use std::io::{self, Cursor, Read, Seek, SeekFrom};
|
||||
use std::io::{self, Read, Seek, SeekFrom};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -10,12 +11,6 @@ pub const ASSETS_PA_MAGIC: [u8; 4] = *b"ASPA";
|
||||
pub const ASSETS_PA_SCHEMA_VERSION: u32 = 1;
|
||||
pub const ASSETS_PA_PRELUDE_SIZE: usize = 32;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub enum AppMode {
|
||||
Game,
|
||||
System,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Cartridge {
|
||||
pub app_id: u32,
|
||||
@@ -23,6 +18,7 @@ pub struct Cartridge {
|
||||
pub app_version: String,
|
||||
pub app_mode: AppMode,
|
||||
pub capabilities: CapFlags,
|
||||
pub memcard_slots: Option<u8>,
|
||||
pub program: Vec<u8>,
|
||||
pub assets: AssetsPayloadSource,
|
||||
pub asset_table: Vec<AssetEntry>,
|
||||
@@ -36,6 +32,7 @@ pub struct CartridgeDTO {
|
||||
pub app_version: String,
|
||||
pub app_mode: AppMode,
|
||||
pub capabilities: CapFlags,
|
||||
pub memcard_slots: Option<u8>,
|
||||
pub program: Vec<u8>,
|
||||
pub assets: AssetsPayloadSource,
|
||||
pub asset_table: Vec<AssetEntry>,
|
||||
@@ -50,6 +47,7 @@ impl From<CartridgeDTO> for Cartridge {
|
||||
app_version: dto.app_version,
|
||||
app_mode: dto.app_mode,
|
||||
capabilities: dto.capabilities,
|
||||
memcard_slots: dto.memcard_slots,
|
||||
program: dto.program,
|
||||
assets: dto.assets,
|
||||
asset_table: dto.asset_table,
|
||||
@@ -130,8 +128,12 @@ impl AssetsPayloadSlice {
|
||||
pub fn open_reader(&self) -> io::Result<AssetsPayloadReader> {
|
||||
match self {
|
||||
Self::Memory { bytes, start, len } => {
|
||||
let data = Arc::<[u8]>::from(bytes[*start..*start + *len].to_vec());
|
||||
Ok(AssetsPayloadReader::Memory(Cursor::new(data)))
|
||||
Ok(AssetsPayloadReader::Memory(MemorySliceReader {
|
||||
bytes: Arc::clone(bytes),
|
||||
start: *start,
|
||||
len: *len,
|
||||
position: 0,
|
||||
}))
|
||||
}
|
||||
Self::File { source, offset, size } => {
|
||||
let mut file = File::open(&source.path)?;
|
||||
@@ -156,7 +158,7 @@ impl AssetsPayloadSlice {
|
||||
}
|
||||
|
||||
pub enum AssetsPayloadReader {
|
||||
Memory(Cursor<Arc<[u8]>>),
|
||||
Memory(MemorySliceReader),
|
||||
File(FileSliceReader),
|
||||
}
|
||||
|
||||
@@ -178,6 +180,37 @@ impl Seek for AssetsPayloadReader {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MemorySliceReader {
|
||||
bytes: Arc<[u8]>,
|
||||
start: usize,
|
||||
len: usize,
|
||||
position: usize,
|
||||
}
|
||||
impl Read for MemorySliceReader {
|
||||
fn read(&mut self, target: &mut [u8]) -> io::Result<usize> {
|
||||
let n = target.len().min(self.len.saturating_sub(self.position));
|
||||
target[..n].copy_from_slice(
|
||||
&self.bytes[self.start + self.position..self.start + self.position + n],
|
||||
);
|
||||
self.position += n;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
impl Seek for MemorySliceReader {
|
||||
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
|
||||
let next = match pos {
|
||||
SeekFrom::Start(n) => n as i128,
|
||||
SeekFrom::Current(n) => self.position as i128 + n as i128,
|
||||
SeekFrom::End(n) => self.len as i128 + n as i128,
|
||||
};
|
||||
if next < 0 || next > self.len as i128 {
|
||||
return Err(invalid_input("slice seek out of bounds"));
|
||||
}
|
||||
self.position = next as usize;
|
||||
Ok(self.position as u64)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FileSliceReader {
|
||||
file: File,
|
||||
start: u64,
|
||||
@@ -283,6 +316,7 @@ pub enum CartridgeError {
|
||||
MissingProgram,
|
||||
MissingAssets,
|
||||
IoError,
|
||||
ProgramLoadFailed(prometeu_bytecode::load_limits::LoadFailure),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
|
||||
@@ -291,15 +325,19 @@ pub enum Capability {
|
||||
None,
|
||||
System,
|
||||
Gfx,
|
||||
Composer,
|
||||
Gfx2d,
|
||||
Gfxui,
|
||||
Audio,
|
||||
Fs,
|
||||
Memcard,
|
||||
Log,
|
||||
Asset,
|
||||
Bank,
|
||||
All,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct CartridgeManifest {
|
||||
pub magic: String,
|
||||
pub cartridge_version: u32,
|
||||
@@ -309,4 +347,6 @@ pub struct CartridgeManifest {
|
||||
pub app_mode: AppMode,
|
||||
#[serde(default)]
|
||||
pub capabilities: Vec<Capability>,
|
||||
#[serde(default)]
|
||||
pub memcard_slots: Option<u8>,
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ use crate::cartridge::{
|
||||
CartridgeManifest,
|
||||
};
|
||||
use crate::syscalls::{CapFlags, caps};
|
||||
use prometeu_bytecode::load_limits::{
|
||||
LoadBudget, LoadFailure, LoadLimits, LoadReason, LoadResource,
|
||||
};
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
@@ -52,13 +55,20 @@ impl DirectoryCartridgeLoader {
|
||||
}
|
||||
|
||||
let capabilities = normalize_capabilities(&manifest.capabilities)?;
|
||||
if ((capabilities & caps::MEMCARD) != 0) != manifest.memcard_slots.is_some()
|
||||
|| manifest.memcard_slots.is_some_and(|n| !(1..=64).contains(&n))
|
||||
{
|
||||
return Err(CartridgeError::InvalidManifest);
|
||||
}
|
||||
|
||||
let program_path = path.join("program.pbx");
|
||||
if !program_path.exists() {
|
||||
return Err(CartridgeError::MissingProgram);
|
||||
}
|
||||
|
||||
let program = fs::read(program_path).map_err(|_| CartridgeError::IoError)?;
|
||||
let mut program_file = fs::File::open(program_path).map_err(|_| CartridgeError::IoError)?;
|
||||
let program_len = program_file.metadata().map_err(|_| CartridgeError::IoError)?.len();
|
||||
let program = read_program(&mut program_file, program_len, LoadLimits::default())?;
|
||||
|
||||
let assets_pa_path = path.join("assets.pa");
|
||||
let (assets, asset_table, preload) = if assets_pa_path.exists() {
|
||||
@@ -86,6 +96,7 @@ impl DirectoryCartridgeLoader {
|
||||
app_version: manifest.app_version,
|
||||
app_mode: manifest.app_mode,
|
||||
capabilities,
|
||||
memcard_slots: manifest.memcard_slots,
|
||||
program,
|
||||
assets,
|
||||
asset_table,
|
||||
@@ -98,6 +109,59 @@ impl DirectoryCartridgeLoader {
|
||||
|
||||
pub struct PackedCartridgeLoader;
|
||||
|
||||
/// Admit the PBX input separately from parsing scratch. Metadata rejects an
|
||||
/// oversized file before reservation; bounded reads also cover file growth.
|
||||
fn read_program(
|
||||
reader: &mut impl Read,
|
||||
size_hint: u64,
|
||||
limits: LoadLimits,
|
||||
) -> Result<Vec<u8>, CartridgeError> {
|
||||
let budget = LoadBudget::new(limits);
|
||||
let limit = budget.limit(LoadResource::PbxBytes);
|
||||
budget.check(LoadResource::PbxBytes, size_hint).map_err(CartridgeError::ProgramLoadFailed)?;
|
||||
let resource_error = |reason, requested| {
|
||||
let mut error = LoadFailure::resource(LoadResource::PbxBytes, requested, limit);
|
||||
error.reason = reason;
|
||||
CartridgeError::ProgramLoadFailed(error)
|
||||
};
|
||||
let mut out = Vec::<u8>::new();
|
||||
let initial =
|
||||
usize::try_from(size_hint).map_err(|_| resource_error(LoadReason::Overflow, size_hint))?;
|
||||
out.try_reserve_exact(initial)
|
||||
.map_err(|_| resource_error(LoadReason::Allocation, size_hint))?;
|
||||
budget
|
||||
.check(LoadResource::PbxBytes, out.capacity() as u64)
|
||||
.map_err(CartridgeError::ProgramLoadFailed)?;
|
||||
let mut chunk = [0u8; 8192];
|
||||
loop {
|
||||
// At the ceiling inspect one extra byte without growing the input.
|
||||
let remaining = limit - out.len() as u64;
|
||||
let read_len = remaining.min(chunk.len() as u64).max(1) as usize;
|
||||
let count = match reader.read(&mut chunk[..read_len]) {
|
||||
Ok(count) => count,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(_) => return Err(CartridgeError::IoError),
|
||||
};
|
||||
if count == 0 {
|
||||
return Ok(out);
|
||||
}
|
||||
let requested = (out.len() as u64)
|
||||
.checked_add(count as u64)
|
||||
.ok_or_else(|| resource_error(LoadReason::Overflow, u64::MAX))?;
|
||||
budget
|
||||
.check(LoadResource::PbxBytes, requested)
|
||||
.map_err(CartridgeError::ProgramLoadFailed)?;
|
||||
// Reserve exact growth rather than allowing Vec's geometric growth to
|
||||
// exceed admission. Existing spare capacity is reused without billing twice.
|
||||
out.try_reserve_exact(count)
|
||||
.map_err(|_| resource_error(LoadReason::Allocation, requested))?;
|
||||
budget
|
||||
.check(LoadResource::PbxBytes, out.capacity() as u64)
|
||||
.map_err(CartridgeError::ProgramLoadFailed)?;
|
||||
out.extend_from_slice(&chunk[..count]);
|
||||
}
|
||||
}
|
||||
|
||||
impl PackedCartridgeLoader {
|
||||
pub fn load(_path: &Path) -> Result<Cartridge, CartridgeError> {
|
||||
Err(CartridgeError::InvalidFormat)
|
||||
@@ -117,8 +181,12 @@ fn normalize_capabilities(capabilities: &[Capability]) -> Result<CapFlags, Cartr
|
||||
Capability::None => caps::NONE,
|
||||
Capability::System => caps::SYSTEM,
|
||||
Capability::Gfx => caps::GFX,
|
||||
Capability::Composer => caps::COMPOSER,
|
||||
Capability::Gfx2d => caps::GFX2D,
|
||||
Capability::Gfxui => caps::GFXUI,
|
||||
Capability::Audio => caps::AUDIO,
|
||||
Capability::Fs => caps::FS,
|
||||
Capability::Memcard => caps::MEMCARD,
|
||||
Capability::Log => caps::LOG,
|
||||
Capability::Asset => caps::ASSET,
|
||||
Capability::Bank => caps::BANK,
|
||||
@@ -200,7 +268,8 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::asset::{AssetCodec, AssetEntry, BankType, PreloadEntry};
|
||||
use crate::cartridge::{ASSETS_PA_MAGIC, ASSETS_PA_SCHEMA_VERSION, AssetsPackPrelude};
|
||||
use crate::glyph_bank::GLYPH_BANK_PALETTE_COUNT_V1;
|
||||
use crate::glyph_bank::GLYPH_BANK_MAX_PALETTE_COUNT_V1;
|
||||
use prometeu_bytecode::load_limits::LoadCode;
|
||||
use serde_json::json;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
@@ -286,6 +355,76 @@ mod tests {
|
||||
manifest
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn program_admission_accepts_exact_limit_and_rejects_growth_after_metadata() {
|
||||
let limits = LoadLimits { pbx_bytes: 3, ..Default::default() };
|
||||
for hint in [0, 1, 3] {
|
||||
assert_eq!(read_program(&mut &b"abc"[..], hint, limits).unwrap(), b"abc");
|
||||
let error = read_program(&mut &b"abcd"[..], hint, limits).unwrap_err();
|
||||
let CartridgeError::ProgramLoadFailed(error) = error else {
|
||||
panic!("typed PBX admission failure expected")
|
||||
};
|
||||
assert_eq!((error.code, error.reason), (LoadCode::ResourceLimit, LoadReason::Limit));
|
||||
assert_eq!(
|
||||
(error.resource, error.requested, error.limit),
|
||||
(Some(LoadResource::PbxBytes), Some(4), Some(3))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn program_admission_rejects_oversized_metadata_before_reading() {
|
||||
struct MustNotRead;
|
||||
impl Read for MustNotRead {
|
||||
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
|
||||
panic!("must reject before reading")
|
||||
}
|
||||
}
|
||||
let limits = LoadLimits { pbx_bytes: 3, ..Default::default() };
|
||||
assert!(matches!(
|
||||
read_program(&mut MustNotRead, 4, limits),
|
||||
Err(CartridgeError::ProgramLoadFailed(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn program_admission_handles_empty_short_and_interrupted_reads() {
|
||||
assert!(read_program(&mut &[][..], 0, LoadLimits::default()).unwrap().is_empty());
|
||||
struct ShortReads {
|
||||
interrupted: bool,
|
||||
remaining: &'static [u8],
|
||||
}
|
||||
impl Read for ShortReads {
|
||||
fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
|
||||
if !self.interrupted {
|
||||
self.interrupted = true;
|
||||
return Err(std::io::ErrorKind::Interrupted.into());
|
||||
}
|
||||
if self.remaining.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
bytes[0] = self.remaining[0];
|
||||
self.remaining = &self.remaining[1..];
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
let mut reader = ShortReads { interrupted: false, remaining: b"abc" };
|
||||
assert_eq!(read_program(&mut reader, 2, LoadLimits::default()).unwrap(), b"abc");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_loader_rejects_oversized_pbx_with_default_limit() {
|
||||
let dir = TestCartridgeDir::new(manifest_with_capabilities(None));
|
||||
let file = fs::OpenOptions::new().write(true).open(dir.path().join("program.pbx")).unwrap();
|
||||
let limit = LoadLimits::default().pbx_bytes;
|
||||
file.set_len(limit + 1).unwrap(); // Sparse file; no giant content allocation.
|
||||
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
||||
let CartridgeError::ProgramLoadFailed(error) = error else {
|
||||
panic!("typed PBX admission failure expected")
|
||||
};
|
||||
assert_eq!((error.requested, error.limit), (Some(limit + 1), Some(64 * 1_048_576)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_without_capabilities_defaults_to_none() {
|
||||
let dir = TestCartridgeDir::new(manifest_with_capabilities(None));
|
||||
@@ -315,7 +454,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn load_with_all_capability_normalizes_to_all_flags() {
|
||||
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["all"])));
|
||||
let mut manifest = manifest_with_capabilities(Some(vec!["all"]));
|
||||
manifest["memcard_slots"] = serde_json::json!(1);
|
||||
let dir = TestCartridgeDir::new(manifest);
|
||||
dir.write_assets_pa(vec![], vec![], &[]);
|
||||
|
||||
let cartridge = DirectoryCartridgeLoader::load(dir.path()).expect("cartridge must load");
|
||||
@@ -366,14 +507,14 @@ mod tests {
|
||||
bank_type: BankType::GLYPH,
|
||||
offset,
|
||||
size,
|
||||
decoded_size: 16 * 16 + (GLYPH_BANK_PALETTE_COUNT_V1 as u64 * 16 * 2),
|
||||
decoded_size: 16 * 16 + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 as u64 * 16 * 4),
|
||||
codec: AssetCodec::None,
|
||||
metadata: json!({
|
||||
"tile_size": 16,
|
||||
"width": 16,
|
||||
"height": 16,
|
||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
||||
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -449,14 +590,14 @@ mod tests {
|
||||
bank_type: BankType::GLYPH,
|
||||
offset: 4,
|
||||
size: 4,
|
||||
decoded_size: 16 * 16 + (GLYPH_BANK_PALETTE_COUNT_V1 as u64 * 16 * 2),
|
||||
decoded_size: 16 * 16 + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 as u64 * 16 * 4),
|
||||
codec: AssetCodec::None,
|
||||
metadata: json!({
|
||||
"tile_size": 16,
|
||||
"width": 16,
|
||||
"height": 16,
|
||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
||||
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||
}),
|
||||
},
|
||||
];
|
||||
@@ -516,8 +657,8 @@ mod tests {
|
||||
"tile_size": 16,
|
||||
"width": 16,
|
||||
"height": 16,
|
||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
||||
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||
}
|
||||
}],
|
||||
"preload": []
|
||||
@@ -558,8 +699,8 @@ mod tests {
|
||||
"tile_size": 16,
|
||||
"width": 16,
|
||||
"height": 16,
|
||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
||||
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||
}
|
||||
}],
|
||||
"preload": []
|
||||
|
||||
@@ -1,75 +1,67 @@
|
||||
/// Represents a 16-bit color in the RGB565 format.
|
||||
///
|
||||
/// The RGB565 format is a common high-color representation for embedded systems:
|
||||
/// - **Red**: 5 bits (0..31)
|
||||
/// - **Green**: 6 bits (0..63)
|
||||
/// - **Blue**: 5 bits (0..31)
|
||||
///
|
||||
/// Prometeu does not have a hardware alpha channel. Transparency is achieved
|
||||
/// by using a specific color key (Magenta / 0xF81F) which the GFX engine
|
||||
/// skips during rendering.
|
||||
/// Represents a canonical RGBA8888 color in RGBA channel order.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Color(pub u16);
|
||||
pub struct Color(pub u32);
|
||||
|
||||
impl Color {
|
||||
pub const BLACK: Self = Self::rgb(0, 0, 0); // 0x0000
|
||||
pub const WHITE: Self = Self::rgb(255, 255, 255); // 0xFFFF
|
||||
pub const RED: Self = Self::rgb(255, 0, 0); // 0xF800
|
||||
pub const GREEN: Self = Self::rgb(0, 255, 0); // 0x07E0
|
||||
pub const BLUE: Self = Self::rgb(0, 0, 255); // 0x001F
|
||||
pub const YELLOW: Self = Self::rgb(255, 255, 0); // 0xFFE0
|
||||
pub const BLACK: Self = Self::rgb(0, 0, 0);
|
||||
pub const WHITE: Self = Self::rgb(255, 255, 255);
|
||||
pub const RED: Self = Self::rgb(255, 0, 0);
|
||||
pub const GREEN: Self = Self::rgb(0, 255, 0);
|
||||
pub const BLUE: Self = Self::rgb(0, 0, 255);
|
||||
pub const YELLOW: Self = Self::rgb(255, 255, 0);
|
||||
pub const ORANGE: Self = Self::rgb(255, 128, 0);
|
||||
pub const INDIGO: Self = Self::rgb(75, 0, 130);
|
||||
pub const GRAY: Self = Self::rgb(128, 128, 128);
|
||||
pub const CYAN: Self = Self::rgb(0, 255, 255); // 0x07FF
|
||||
pub const MAGENTA: Self = Self::rgb(255, 0, 255); // 0xF81F
|
||||
pub const COLOR_KEY: Self = Self::MAGENTA;
|
||||
pub const TRANSPARENT: Self = Self::MAGENTA;
|
||||
pub const CYAN: Self = Self::rgb(0, 255, 255);
|
||||
pub const MAGENTA: Self = Self::rgb(255, 0, 255);
|
||||
pub const TRANSPARENT: Self = Self::rgba(0, 0, 0, 0);
|
||||
#[deprecated(note = "Use RGBA alpha transparency; COLOR_KEY is temporary migration residue.")]
|
||||
pub const COLOR_KEY: Self = Self::TRANSPARENT;
|
||||
|
||||
/// Extracts channels in the native RGB565 range:
|
||||
/// R: 0..31, G: 0..63, B: 0..31
|
||||
/// Extracts RGBA8888 channels from canonical RGBA raw order.
|
||||
#[inline(always)]
|
||||
pub const fn unpack_to_native(px: u16) -> (u8, u8, u8) {
|
||||
let r = ((px >> 11) & 0x1F) as u8;
|
||||
let g = ((px >> 5) & 0x3F) as u8;
|
||||
let b = (px & 0x1F) as u8;
|
||||
(r, g, b)
|
||||
pub const fn unpack_to_native(px: u32) -> (u8, u8, u8, u8) {
|
||||
let r = ((px >> 24) & 0xFF) as u8;
|
||||
let g = ((px >> 16) & 0xFF) as u8;
|
||||
let b = ((px >> 8) & 0xFF) as u8;
|
||||
let a = (px & 0xFF) as u8;
|
||||
(r, g, b, a)
|
||||
}
|
||||
|
||||
/// Packs channels from the native RGB565 range into a pixel:
|
||||
/// R: 0..31, G: 0..63, B: 0..31
|
||||
/// Packs RGBA8888 channels into canonical RGBA raw order.
|
||||
#[inline(always)]
|
||||
pub const fn pack_from_native(r: u8, g: u8, b: u8) -> u16 {
|
||||
((r as u16 & 0x1F) << 11) | ((g as u16 & 0x3F) << 5) | (b as u16 & 0x1F)
|
||||
pub const fn pack_from_native(r: u8, g: u8, b: u8, a: u8) -> u32 {
|
||||
((r as u32) << 24) | ((g as u32) << 16) | ((b as u32) << 8) | a as u32
|
||||
}
|
||||
|
||||
/// Creates an RGB565 color from 8-bit components (0..255).
|
||||
/// Creates an opaque RGBA8888 color from 8-bit RGB components.
|
||||
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
|
||||
let r5 = (r as u16 >> 3) & 0x1F;
|
||||
let g6 = (g as u16 >> 2) & 0x3F;
|
||||
let b5 = (b as u16 >> 3) & 0x1F;
|
||||
Self::rgba(r, g, b, 255)
|
||||
}
|
||||
|
||||
Self((r5 << 11) | (g6 << 5) | b5)
|
||||
pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
|
||||
Self(Self::pack_from_native(r, g, b, a))
|
||||
}
|
||||
|
||||
pub const fn gray_scale(c: u8) -> Self {
|
||||
Self::rgb(c, c, c)
|
||||
}
|
||||
|
||||
pub const fn from_raw(raw: u16) -> Self {
|
||||
pub const fn from_raw(raw: u32) -> Self {
|
||||
Self(raw)
|
||||
}
|
||||
|
||||
pub const fn raw(self) -> u16 {
|
||||
pub const fn raw(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub const fn hex(self) -> i32 {
|
||||
let (r5, g6, b5) = Self::unpack_to_native(self.0);
|
||||
let r8 = ((r5 as u32) << 3) | ((r5 as u32) >> 2);
|
||||
let g8 = ((g6 as u32) << 2) | ((g6 as u32) >> 4);
|
||||
let b8 = ((b5 as u32) << 3) | ((b5 as u32) >> 2);
|
||||
let hex = r8 << 16 | g8 << 8 | b8;
|
||||
let (r, g, b, _) = Self::unpack_to_native(self.0);
|
||||
let hex = (r as u32) << 16 | (g as u32) << 8 | b as u32;
|
||||
hex as i32
|
||||
}
|
||||
|
||||
pub const fn alpha(self) -> u8 {
|
||||
(self.0 & 0xFF) as u8
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::cartridge::AppMode;
|
||||
use crate::app_mode::AppMode;
|
||||
#[cfg(test)]
|
||||
use prometeu_bytecode::Value;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -35,12 +36,12 @@ pub enum DebugResponse {
|
||||
#[serde(rename = "handshake")]
|
||||
Handshake { protocol_version: u32, runtime_version: String, cartridge: HandshakeCartridge },
|
||||
#[serde(rename = "getState")]
|
||||
GetState { pc: usize, stack_top: Vec<Value>, frame_index: u64, app_id: u32 },
|
||||
GetState { pc: usize, stack_top: crate::ValueSnapshot, frame_index: u64, app_id: u32 },
|
||||
#[serde(rename = "breakpoints")]
|
||||
Breakpoints { pcs: Vec<usize> },
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HandshakeCartridge {
|
||||
pub app_id: u32,
|
||||
pub title: String,
|
||||
@@ -68,6 +69,8 @@ pub enum DebugEvent {
|
||||
glyph_slots_total: u32,
|
||||
sound_slots_used: u32,
|
||||
sound_slots_total: u32,
|
||||
scene_slots_used: u32,
|
||||
scene_slots_total: u32,
|
||||
},
|
||||
#[serde(rename = "fault")]
|
||||
Fault {
|
||||
@@ -76,6 +79,9 @@ pub enum DebugEvent {
|
||||
pc: Option<u32>,
|
||||
trap_code: Option<u32>,
|
||||
opcode: Option<u16>,
|
||||
span: Option<prometeu_bytecode::SourceSpan>,
|
||||
resource: Option<prometeu_bytecode::ResourceFailure>,
|
||||
init: Option<serde_json::Value>,
|
||||
},
|
||||
#[serde(rename = "cert")]
|
||||
Cert { rule: String, used: u64, limit: u64, frame_index: u64 },
|
||||
@@ -99,6 +105,8 @@ mod tests {
|
||||
glyph_slots_total: 16,
|
||||
sound_slots_used: 2,
|
||||
sound_slots_total: 16,
|
||||
scene_slots_used: 3,
|
||||
scene_slots_total: 16,
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&event).unwrap();
|
||||
@@ -111,7 +119,8 @@ mod tests {
|
||||
fn test_get_state_serialization() {
|
||||
let resp = DebugResponse::GetState {
|
||||
pc: 42,
|
||||
stack_top: vec![Value::Int64(10), Value::String("test".into()), Value::Boolean(true)],
|
||||
stack_top: vec![Value::Int64(10), Value::String("test".into()), Value::Boolean(true)]
|
||||
.into(),
|
||||
frame_index: 5,
|
||||
app_id: 1,
|
||||
};
|
||||
@@ -132,6 +141,9 @@ mod tests {
|
||||
pc: Some(12),
|
||||
trap_code: Some(4),
|
||||
opcode: Some(0x70),
|
||||
span: None,
|
||||
resource: None,
|
||||
init: None,
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&event).unwrap();
|
||||
|
||||
@@ -24,7 +24,7 @@ pub enum GfxOpStatus {
|
||||
|
||||
pub trait GfxBridge {
|
||||
fn size(&self) -> (usize, usize);
|
||||
fn front_buffer(&self) -> &[u16];
|
||||
fn front_buffer(&self) -> &[u32];
|
||||
fn clear(&mut self, color: Color);
|
||||
fn fill_rect_blend(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color, mode: BlendMode);
|
||||
fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color);
|
||||
@@ -57,7 +57,12 @@ pub trait GfxBridge {
|
||||
///
|
||||
/// Deferred `gfx.*` overlay/debug primitives are intentionally outside this
|
||||
/// contract and are drained by a separate final overlay stage.
|
||||
fn render_scene_from_cache(&mut self, cache: &SceneViewportCache, update: &ResolverUpdate);
|
||||
fn render_scene_from_cache(
|
||||
&mut self,
|
||||
cache: &SceneViewportCache,
|
||||
update: &ResolverUpdate,
|
||||
resolved_glyph_slots: &[usize; 4],
|
||||
);
|
||||
fn load_frame_sprites(&mut self, sprites: &[Sprite]);
|
||||
/// Submit text into the `gfx.*` primitive path.
|
||||
///
|
||||
@@ -68,13 +73,4 @@ pub trait GfxBridge {
|
||||
|
||||
fn sprite(&self, index: usize) -> &Sprite;
|
||||
fn sprite_mut(&mut self, index: usize) -> &mut Sprite;
|
||||
|
||||
fn scene_fade_level(&self) -> u8;
|
||||
fn set_scene_fade_level(&mut self, level: u8);
|
||||
fn scene_fade_color(&self) -> Color;
|
||||
fn set_scene_fade_color(&mut self, color: Color);
|
||||
fn hud_fade_level(&self) -> u8;
|
||||
fn set_hud_fade_level(&mut self, level: u8);
|
||||
fn hud_fade_color(&self) -> Color;
|
||||
fn set_hud_fade_color(&mut self, color: Color);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::color::Color;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const GLYPH_BANK_PALETTE_COUNT_V1: usize = 64;
|
||||
pub const GLYPH_BANK_MAX_PALETTE_COUNT_V1: usize = 64;
|
||||
pub const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
|
||||
|
||||
/// Standard sizes for square tiles.
|
||||
@@ -32,24 +32,62 @@ pub struct GlyphBank {
|
||||
|
||||
/// Decoded pixel data stored as one palette index per pixel.
|
||||
/// Serialized payloads are packed; runtime memory is expanded.
|
||||
/// Index 0 is always reserved for transparency.
|
||||
/// Palette indices are ordinary indices; transparency is resolved through
|
||||
/// the RGBA alpha channel of the palette entry.
|
||||
pub pixel_indices: Vec<u8>,
|
||||
/// Runtime-facing v1 palette table: 64 palettes of 16 RGB565 colors each.
|
||||
pub palettes: [[Color; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1],
|
||||
/// Runtime-facing v1 palette table.
|
||||
///
|
||||
/// Palette identity is the direct index in this vector. A resident glyph
|
||||
/// bank carries exactly the palettes materialized from its payload.
|
||||
pub palettes: Vec<[Color; GLYPH_BANK_COLORS_PER_PALETTE]>,
|
||||
}
|
||||
|
||||
impl GlyphBank {
|
||||
/// Creates an empty glyph bank with the specified dimensions.
|
||||
/// Creates an empty glyph bank with one palette.
|
||||
pub fn new(tile_size: TileSize, width: usize, height: usize) -> Self {
|
||||
Self::with_palette_count(tile_size, width, height, 1)
|
||||
}
|
||||
|
||||
/// Creates an empty glyph bank with the specified resident palette count.
|
||||
pub fn with_palette_count(
|
||||
tile_size: TileSize,
|
||||
width: usize,
|
||||
height: usize,
|
||||
palette_count: usize,
|
||||
) -> Self {
|
||||
assert!(
|
||||
(1..=GLYPH_BANK_MAX_PALETTE_COUNT_V1).contains(&palette_count),
|
||||
"glyph bank palette_count must be in 1..={}",
|
||||
GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||
);
|
||||
|
||||
Self {
|
||||
tile_size,
|
||||
width,
|
||||
height,
|
||||
pixel_indices: vec![0; width * height], // Index 0 = Transparent
|
||||
palettes: [[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1],
|
||||
pixel_indices: vec![0; width * height],
|
||||
palettes: vec![[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; palette_count],
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of resident palettes.
|
||||
pub fn palette_count(&self) -> usize {
|
||||
self.palettes.len()
|
||||
}
|
||||
|
||||
/// Returns true when the palette id is valid for this resident bank.
|
||||
pub fn contains_palette(&self, palette_id: u8) -> bool {
|
||||
(palette_id as usize) < self.palette_count()
|
||||
}
|
||||
|
||||
/// Returns a mutable palette slot when the palette exists.
|
||||
pub fn palette_mut(
|
||||
&mut self,
|
||||
palette_id: u8,
|
||||
) -> Option<&mut [Color; GLYPH_BANK_COLORS_PER_PALETTE]> {
|
||||
self.palettes.get_mut(palette_id as usize)
|
||||
}
|
||||
|
||||
/// Resolves a global tile ID and local pixel coordinates to a palette index.
|
||||
/// tile_id: the tile index in the bank
|
||||
/// local_x, local_y: the pixel position inside the tile (0 to tile_size-1)
|
||||
@@ -65,22 +103,53 @@ impl GlyphBank {
|
||||
if pixel_x < self.width && pixel_y < self.height {
|
||||
self.pixel_indices[pixel_y * self.width + pixel_x]
|
||||
} else {
|
||||
0 // Default to transparent if out of bounds
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps a 4-bit index to a real RGB565 Color using the specified palette.
|
||||
pub fn resolve_color(&self, palette_id: u8, pixel_index: u8) -> Color {
|
||||
// Hardware Rule: Index 0 is always transparent.
|
||||
// We use Magenta as the 'transparent' signal color during composition.
|
||||
if pixel_index == 0 {
|
||||
return Color::COLOR_KEY;
|
||||
}
|
||||
|
||||
/// Maps a 4-bit index to a real RGBA8888 Color using the specified palette.
|
||||
pub fn resolve_color(&self, palette_id: u8, pixel_index: u8) -> Option<Color> {
|
||||
self.palettes
|
||||
.get(palette_id as usize)
|
||||
.and_then(|palette| palette.get(pixel_index as usize))
|
||||
.copied()
|
||||
.unwrap_or(Color::COLOR_KEY)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn new_glyph_bank_uses_single_resident_palette() {
|
||||
let bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||
|
||||
assert_eq!(bank.palette_count(), 1);
|
||||
assert!(bank.contains_palette(0));
|
||||
assert!(!bank.contains_palette(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyph_bank_can_materialize_v1_max_palette_count() {
|
||||
let bank =
|
||||
GlyphBank::with_palette_count(TileSize::Size8, 8, 8, GLYPH_BANK_MAX_PALETTE_COUNT_V1);
|
||||
|
||||
assert_eq!(bank.palette_count(), GLYPH_BANK_MAX_PALETTE_COUNT_V1);
|
||||
assert!(bank.contains_palette((GLYPH_BANK_MAX_PALETTE_COUNT_V1 - 1) as u8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_palette_lookup_is_distinct_from_transparent_color() {
|
||||
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||
bank.palette_mut(0).unwrap()[1] = Color::TRANSPARENT;
|
||||
|
||||
assert_eq!(bank.resolve_color(0, 1), Some(Color::TRANSPARENT));
|
||||
assert_eq!(bank.resolve_color(1, 1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "glyph bank palette_count must be in 1..=64")]
|
||||
fn glyph_bank_rejects_zero_resident_palettes() {
|
||||
let _ = GlyphBank::with_palette_count(TileSize::Size8, 8, 8, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
use crate::asset_bridge::AssetBridge;
|
||||
use crate::audio_bridge::AudioBridge;
|
||||
use crate::gfx_bridge::GfxBridge;
|
||||
use crate::pad_bridge::PadBridge;
|
||||
use crate::sprite::Sprite;
|
||||
use crate::touch_bridge::TouchBridge;
|
||||
|
||||
pub trait HardwareBridge {
|
||||
fn begin_frame(&mut self);
|
||||
fn bind_scene(&mut self, scene_bank_id: usize) -> bool;
|
||||
fn unbind_scene(&mut self);
|
||||
fn set_camera(&mut self, x: i32, y: i32);
|
||||
fn emit_sprite(&mut self, sprite: Sprite) -> bool;
|
||||
fn render_frame(&mut self);
|
||||
fn has_glyph_bank(&self, bank_id: usize) -> bool;
|
||||
|
||||
fn gfx(&self) -> &dyn GfxBridge;
|
||||
fn gfx_mut(&mut self) -> &mut dyn GfxBridge;
|
||||
|
||||
fn audio(&self) -> &dyn AudioBridge;
|
||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge;
|
||||
|
||||
fn pad(&self) -> &dyn PadBridge;
|
||||
fn pad_mut(&mut self) -> &mut dyn PadBridge;
|
||||
|
||||
fn touch(&self) -> &dyn TouchBridge;
|
||||
fn touch_mut(&mut self) -> &mut dyn TouchBridge;
|
||||
|
||||
fn assets(&self) -> &dyn AssetBridge;
|
||||
fn assets_mut(&mut self) -> &mut dyn AssetBridge;
|
||||
}
|
||||
@@ -1,19 +1,23 @@
|
||||
use crate::hardware_bridge::HardwareBridge;
|
||||
use crate::platform::RuntimePlatform;
|
||||
use crate::vm_fault::VmFault;
|
||||
|
||||
pub struct HostContext<'a> {
|
||||
pub hw: Option<&'a mut dyn HardwareBridge>,
|
||||
pub platform: Option<&'a mut dyn RuntimePlatform>,
|
||||
}
|
||||
|
||||
impl<'a> HostContext<'a> {
|
||||
pub fn new(hw: Option<&'a mut dyn HardwareBridge>) -> Self {
|
||||
Self { hw }
|
||||
pub fn new(platform: Option<&'a mut dyn RuntimePlatform>) -> Self {
|
||||
Self { platform }
|
||||
}
|
||||
|
||||
pub fn new_platform(platform: Option<&'a mut dyn RuntimePlatform>) -> Self {
|
||||
Self::new(platform)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn require_hw(&mut self) -> Result<&mut dyn HardwareBridge, VmFault> {
|
||||
match &mut self.hw {
|
||||
Some(hw) => Ok(*hw),
|
||||
pub fn require_platform(&mut self) -> Result<&mut dyn RuntimePlatform, VmFault> {
|
||||
match &mut self.platform {
|
||||
Some(platform) => Ok(*platform),
|
||||
None => Err(VmFault::Unavailable),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,288 @@
|
||||
use crate::vm_fault::VmFault;
|
||||
use prometeu_bytecode::{HeapRef, Value};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Native producers describe their output before materializing guest content.
|
||||
/// The VM provides the session allocator; HAL does not own guest quotas.
|
||||
pub trait GuestStringAllocator {
|
||||
fn byte_limit(&self) -> u64;
|
||||
fn build(
|
||||
&mut self,
|
||||
length: usize,
|
||||
writer: &mut dyn FnMut(&mut dyn std::fmt::Write) -> std::fmt::Result,
|
||||
) -> Result<Arc<str>, VmFault>;
|
||||
}
|
||||
|
||||
/// A bounded, call-scoped Array<Int32> byte carrier. Implementations validate
|
||||
/// concrete array type, every value and all bounds before exposing mutations.
|
||||
pub trait GuestByteArrays {
|
||||
fn validate(&mut self, handle: HeapRef, offset: usize, count: usize) -> Result<(), VmFault>;
|
||||
fn read(&mut self, handle: HeapRef, offset: usize, target: &mut [u8]) -> Result<(), VmFault>;
|
||||
fn write(&mut self, handle: HeapRef, offset: usize, bytes: &[u8]) -> Result<(), VmFault>;
|
||||
}
|
||||
|
||||
/// Writes only into result slots reserved by the VM. A native handler cannot
|
||||
/// grow the operand buffer or exceed its declared result count.
|
||||
pub struct HostReturn<'a> {
|
||||
stack: &'a mut Vec<Value>,
|
||||
remaining: usize,
|
||||
overflowed: bool,
|
||||
strings: &'a mut dyn GuestStringAllocator,
|
||||
failure: Option<VmFault>,
|
||||
arrays: Option<&'a mut dyn GuestByteArrays>,
|
||||
}
|
||||
|
||||
impl<'a> HostReturn<'a> {
|
||||
pub fn new(stack: &'a mut Vec<Value>) -> Self {
|
||||
Self { stack }
|
||||
fn size_overflow(&mut self) -> VmFault {
|
||||
let error = VmFault::ResourceLimit(prometeu_bytecode::ResourceFailure {
|
||||
resource: prometeu_bytecode::RuntimeResource::StringBytes,
|
||||
reason: prometeu_bytecode::ResourceReason::SizeOverflow,
|
||||
requested: u64::MAX,
|
||||
limit: self.strings.byte_limit(),
|
||||
});
|
||||
self.failure = Some(error.clone());
|
||||
error
|
||||
}
|
||||
pub fn new(
|
||||
stack: &'a mut Vec<Value>,
|
||||
result_slots: usize,
|
||||
strings: &'a mut dyn GuestStringAllocator,
|
||||
) -> Self {
|
||||
Self {
|
||||
stack,
|
||||
remaining: result_slots,
|
||||
overflowed: false,
|
||||
strings,
|
||||
failure: None,
|
||||
arrays: None,
|
||||
}
|
||||
}
|
||||
pub fn with_arrays(mut self, arrays: &'a mut dyn GuestByteArrays) -> Self {
|
||||
self.arrays = Some(arrays);
|
||||
self
|
||||
}
|
||||
pub fn byte_arrays(&mut self) -> Result<&mut (dyn GuestByteArrays + 'a), VmFault> {
|
||||
self.arrays.as_deref_mut().ok_or(VmFault::Unavailable)
|
||||
}
|
||||
pub fn failure(&self) -> Option<&VmFault> {
|
||||
self.failure.as_ref()
|
||||
}
|
||||
pub fn overflowed(&self) -> bool {
|
||||
self.overflowed
|
||||
}
|
||||
fn admit(&mut self) -> bool {
|
||||
if self.failure.is_some() {
|
||||
return false;
|
||||
}
|
||||
if self.remaining == 0 || self.stack.len() == self.stack.capacity() {
|
||||
self.overflowed = true;
|
||||
false
|
||||
} else {
|
||||
self.remaining -= 1;
|
||||
true
|
||||
}
|
||||
}
|
||||
pub fn push_bool(&mut self, v: bool) {
|
||||
self.stack.push(Value::Boolean(v));
|
||||
if self.admit() {
|
||||
self.stack.push(Value::Boolean(v));
|
||||
}
|
||||
}
|
||||
pub fn push_int(&mut self, v: i64) {
|
||||
self.stack.push(Value::Int64(v));
|
||||
if self.admit() {
|
||||
self.stack.push(Value::Int64(v));
|
||||
}
|
||||
}
|
||||
pub fn push_null(&mut self) {
|
||||
self.stack.push(Value::Null);
|
||||
if self.admit() {
|
||||
self.stack.push(Value::Null);
|
||||
}
|
||||
}
|
||||
pub fn push_gate(&mut self, g: usize) {
|
||||
// Temporary: cast incoming handle/HeapRef index. Real allocator will provide proper handles.
|
||||
self.stack.push(Value::HeapRef(HeapRef(g as u32)));
|
||||
/// Return a handle issued by the current session's heap.
|
||||
pub fn push_gate(&mut self, handle: HeapRef) {
|
||||
if self.admit() {
|
||||
self.stack.push(if handle.is_null() { Value::Null } else { Value::HeapRef(handle) });
|
||||
}
|
||||
}
|
||||
pub fn push_string(&mut self, s: String) {
|
||||
self.stack.push(Value::String(s));
|
||||
pub fn push_string(&mut self, text: &str) -> Result<(), VmFault> {
|
||||
self.push_string_with_len(text.len(), &mut |writer| writer.write_str(text))
|
||||
}
|
||||
pub fn push_string_with_len(
|
||||
&mut self,
|
||||
length: usize,
|
||||
writer: &mut dyn FnMut(&mut dyn std::fmt::Write) -> std::fmt::Result,
|
||||
) -> Result<(), VmFault> {
|
||||
if !self.admit() {
|
||||
return self.failure.clone().map_or(Ok(()), Err);
|
||||
}
|
||||
match self.strings.build(length, writer) {
|
||||
Ok(content) => {
|
||||
self.stack.push(Value::String(content));
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
self.failure = Some(error.clone());
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn push_utf8_lossy(&mut self, bytes: &[u8]) -> Result<(), VmFault> {
|
||||
let mut length = 0usize;
|
||||
lossy_chunks(bytes, &mut |part| {
|
||||
length = length.checked_add(part.len()).ok_or(std::fmt::Error)?;
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|_| self.size_overflow())?;
|
||||
self.push_string_with_len(length, &mut |writer| {
|
||||
lossy_chunks(bytes, &mut |part| writer.write_str(part))
|
||||
})
|
||||
}
|
||||
pub fn push_hex(&mut self, bytes: &[u8]) -> Result<(), VmFault> {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let length = bytes.len().checked_mul(2).ok_or_else(|| self.size_overflow())?;
|
||||
self.push_string_with_len(length, &mut |writer| {
|
||||
for &byte in bytes {
|
||||
let pair = [HEX[(byte >> 4) as usize], HEX[(byte & 15) as usize]];
|
||||
writer.write_str(std::str::from_utf8(&pair).expect("ASCII hex"))?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
pub fn push_joined<'s, I: Iterator<Item = &'s str> + Clone>(
|
||||
&mut self,
|
||||
parts: I,
|
||||
separator: &str,
|
||||
) -> Result<(), VmFault> {
|
||||
let mut length = 0usize;
|
||||
for (index, part) in parts.clone().enumerate() {
|
||||
if index > 0 {
|
||||
length = length.checked_add(separator.len()).ok_or_else(|| self.size_overflow())?;
|
||||
}
|
||||
length = length.checked_add(part.len()).ok_or_else(|| self.size_overflow())?;
|
||||
}
|
||||
self.push_string_with_len(length, &mut |writer| {
|
||||
for (index, part) in parts.clone().enumerate() {
|
||||
if index > 0 {
|
||||
writer.write_str(separator)?;
|
||||
}
|
||||
writer.write_str(part)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn lossy_chunks(
|
||||
mut bytes: &[u8],
|
||||
emit: &mut dyn FnMut(&str) -> std::fmt::Result,
|
||||
) -> std::fmt::Result {
|
||||
while !bytes.is_empty() {
|
||||
match std::str::from_utf8(bytes) {
|
||||
Ok(valid) => {
|
||||
emit(valid)?;
|
||||
break;
|
||||
}
|
||||
Err(error) => {
|
||||
let valid = error.valid_up_to();
|
||||
emit(std::str::from_utf8(&bytes[..valid]).expect("validated prefix"))?;
|
||||
emit("\u{fffd}")?;
|
||||
match error.error_len() {
|
||||
Some(invalid) => bytes = &bytes[valid + invalid..],
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
struct RejectStrings;
|
||||
impl GuestStringAllocator for RejectStrings {
|
||||
fn byte_limit(&self) -> u64 {
|
||||
0
|
||||
}
|
||||
fn build(
|
||||
&mut self,
|
||||
_length: usize,
|
||||
_writer: &mut dyn FnMut(&mut dyn std::fmt::Write) -> std::fmt::Result,
|
||||
) -> Result<Arc<str>, VmFault> {
|
||||
panic!("unexpected string allocation")
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn native_results_cannot_grow_the_reserved_buffer_or_exceed_the_signature() {
|
||||
let mut stack = Vec::with_capacity(8);
|
||||
let capacity = stack.capacity();
|
||||
let mut strings = RejectStrings;
|
||||
let mut ret = HostReturn::new(&mut stack, 1, &mut strings);
|
||||
ret.push_int(7);
|
||||
ret.push_int(8);
|
||||
assert!(ret.overflowed());
|
||||
assert_eq!(stack, vec![Value::Int64(7)]);
|
||||
assert_eq!(stack.capacity(), capacity);
|
||||
let mut empty = Vec::new();
|
||||
let mut ret = HostReturn::new(&mut empty, 1, &mut strings);
|
||||
ret.push_null();
|
||||
assert!(ret.overflowed());
|
||||
assert!(empty.is_empty());
|
||||
assert_eq!(empty.capacity(), 0);
|
||||
}
|
||||
|
||||
struct Collect;
|
||||
impl GuestStringAllocator for Collect {
|
||||
fn byte_limit(&self) -> u64 {
|
||||
u64::MAX
|
||||
}
|
||||
fn build(
|
||||
&mut self,
|
||||
length: usize,
|
||||
writer: &mut dyn FnMut(&mut dyn std::fmt::Write) -> std::fmt::Result,
|
||||
) -> Result<Arc<str>, VmFault> {
|
||||
let mut text = String::new();
|
||||
writer(&mut text).unwrap();
|
||||
assert_eq!(text.len(), length);
|
||||
Ok(Arc::from(text))
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn measured_native_encoding_matches_utf8_lossy_hex_and_join_semantics() {
|
||||
for bytes in [
|
||||
b"plain".as_slice(),
|
||||
"é猫".as_bytes(),
|
||||
&[0xff, 0xe2, 0x82],
|
||||
&[0xf0, 0x80, 0x80, 0x80, 0x61, 0xc2, 0xa9],
|
||||
&[],
|
||||
] {
|
||||
let mut stack = Vec::with_capacity(1);
|
||||
let mut allocator = Collect;
|
||||
let mut ret = HostReturn::new(&mut stack, 1, &mut allocator);
|
||||
ret.push_utf8_lossy(bytes).unwrap();
|
||||
assert_eq!(stack, vec![Value::string(String::from_utf8_lossy(bytes).as_ref())]);
|
||||
}
|
||||
for byte in 0..=255u8 {
|
||||
let bytes = [b'a', byte, b'b', byte];
|
||||
let mut stack = Vec::with_capacity(1);
|
||||
let mut allocator = Collect;
|
||||
HostReturn::new(&mut stack, 1, &mut allocator).push_utf8_lossy(&bytes).unwrap();
|
||||
assert_eq!(stack, vec![Value::string(String::from_utf8_lossy(&bytes).as_ref())]);
|
||||
}
|
||||
let mut stack = Vec::with_capacity(2);
|
||||
let mut allocator = Collect;
|
||||
let mut ret = HostReturn::new(&mut stack, 2, &mut allocator);
|
||||
ret.push_hex(&[0, 0x12, 0xab, 0xff]).unwrap();
|
||||
ret.push_joined(["", "é", "猫"].into_iter(), ";").unwrap();
|
||||
assert_eq!(stack, vec![Value::string("0012abff"), Value::string(";é;猫")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_native_result_buffer_does_not_invoke_string_allocator() {
|
||||
let mut stack = Vec::with_capacity(1);
|
||||
let mut allocator = RejectStrings;
|
||||
let mut ret = HostReturn::new(&mut stack, 0, &mut allocator);
|
||||
ret.push_string("ignored").unwrap();
|
||||
assert!(ret.overflowed());
|
||||
assert!(stack.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
pub mod app_mode;
|
||||
pub mod asset;
|
||||
pub mod asset_bridge;
|
||||
pub mod audio_bridge;
|
||||
pub mod background_work;
|
||||
pub mod button;
|
||||
pub mod cartridge;
|
||||
pub mod cartridge_loader;
|
||||
@@ -10,14 +12,20 @@ pub mod debugger_protocol;
|
||||
pub mod gfx_bridge;
|
||||
pub mod glyph;
|
||||
pub mod glyph_bank;
|
||||
pub mod hardware_bridge;
|
||||
pub mod host_context;
|
||||
pub mod host_return;
|
||||
pub mod input_signals;
|
||||
pub mod log;
|
||||
pub mod memcard;
|
||||
pub mod native_helpers;
|
||||
pub mod native_interface;
|
||||
pub mod owned_frame;
|
||||
pub mod pad_bridge;
|
||||
pub mod platform;
|
||||
pub mod primitives;
|
||||
pub mod render_resources;
|
||||
pub mod render_submission;
|
||||
pub mod render_worker;
|
||||
pub mod sample;
|
||||
pub mod scene_bank;
|
||||
pub mod scene_layer;
|
||||
@@ -30,18 +38,35 @@ pub mod telemetry;
|
||||
pub mod tile;
|
||||
pub mod tilemap;
|
||||
pub mod touch_bridge;
|
||||
pub mod value_snapshot;
|
||||
pub mod vm_fault;
|
||||
pub mod window;
|
||||
pub mod wall_clock;
|
||||
|
||||
pub use asset_bridge::AssetBridge;
|
||||
pub use audio_bridge::{AudioBridge, AudioOpStatus, LoopMode};
|
||||
pub use composer_status::ComposerOpStatus;
|
||||
pub use gfx_bridge::{BlendMode, GfxBridge, GfxOpStatus};
|
||||
pub use hardware_bridge::HardwareBridge;
|
||||
pub use host_context::{HostContext, HostContextProvider};
|
||||
pub use host_return::HostReturn;
|
||||
pub use input_signals::InputSignals;
|
||||
pub use native_helpers::{expect_bool, expect_int};
|
||||
pub use native_interface::{NativeInterface, SyscallId};
|
||||
pub use owned_frame::{OwnedRgba8888Frame, OwnedRgba8888FrameError};
|
||||
pub use pad_bridge::PadBridge;
|
||||
pub use platform::{
|
||||
AssetStoragePlatform, AudioPlatform, ClockPacingPlatform, Game2DFrameComposer, InputPlatform,
|
||||
NoopTelemetryPlatform, RenderBackend, RenderSubmissionSink, RenderSubmitError, RuntimePlatform,
|
||||
TelemetryPlatform, TestPlatform,
|
||||
};
|
||||
pub use render_resources::RenderResourceAccess;
|
||||
pub use render_submission::{
|
||||
BoundScenePacket, Camera2D, ComposerFramePacket, FrameId, Game2DFramePacket, GameSpritePacket,
|
||||
Gfx2dCommand, GfxUiCommand, HudCommand, HudPacket, RenderOwnership, RenderSubmission,
|
||||
RenderSubmissionPacket, ShellUiFramePacket,
|
||||
};
|
||||
pub use render_worker::{
|
||||
RenderWorkerBackend, RenderWorkerError, RenderWorkerFrameSink, RenderWorkerTelemetry,
|
||||
};
|
||||
pub use touch_bridge::TouchBridge;
|
||||
pub use value_snapshot::ValueSnapshot;
|
||||
pub use wall_clock::WallClock;
|
||||
|
||||
@@ -57,6 +57,21 @@ impl LogService {
|
||||
self.events.iter().filter(|e| e.seq > seq).cloned().collect()
|
||||
}
|
||||
|
||||
/// Non-destructive page in native sequence order. A null cursor includes zero.
|
||||
pub fn get_page(&self, after: Option<u64>, limit: usize) -> Vec<LogEvent> {
|
||||
self.events
|
||||
.iter()
|
||||
.filter(|event| after.is_none_or(|seq| event.seq > seq))
|
||||
.take(limit)
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Retained bounds, independent of any reader's progress.
|
||||
pub fn sequence_bounds(&self) -> (Option<u64>, Option<u64>) {
|
||||
(self.events.front().map(|event| event.seq), self.last_seq())
|
||||
}
|
||||
|
||||
pub fn last_seq(&self) -> Option<u64> {
|
||||
self.events.back().map(|e| e.seq)
|
||||
}
|
||||
@@ -107,4 +122,35 @@ mod tests {
|
||||
assert_eq!(after[0].msg, "Log 3");
|
||||
assert_eq!(after[1].msg, "Log 4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_preserve_zero_requery_and_retained_bounds() {
|
||||
let mut service = LogService::new(3);
|
||||
assert_eq!(service.sequence_bounds(), (None, None));
|
||||
assert!(service.get_page(None, 2).is_empty());
|
||||
for i in 0..3 {
|
||||
service.log(i, i, LogLevel::Info, LogSource::Pos, 7, format!("{i}"));
|
||||
}
|
||||
assert_eq!(service.sequence_bounds(), (Some(0), Some(2)));
|
||||
for _ in 0..2 {
|
||||
let page = service.get_page(None, 2);
|
||||
assert_eq!(page.iter().map(|event| event.seq).collect::<Vec<_>>(), vec![0, 1]);
|
||||
}
|
||||
assert_eq!(service.get_page(Some(1), 2)[0].seq, 2);
|
||||
assert!(service.get_page(Some(2), 2).is_empty());
|
||||
service.log(3, 3, LogLevel::Info, LogSource::Pos, 7, "next".into());
|
||||
assert_eq!(service.sequence_bounds(), (Some(1), Some(3)));
|
||||
assert_eq!(service.get_page(Some(2), 2)[0].seq, 3);
|
||||
assert_eq!(service.get_page(None, 10).len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_cursors_preserve_large_unsigned_sequences() {
|
||||
let mut service = LogService::new(3);
|
||||
service.next_seq = u64::MAX - 2;
|
||||
service.log(0, 0, LogLevel::Info, LogSource::Pos, 0, "first".into());
|
||||
service.log(0, 0, LogLevel::Info, LogSource::Pos, 0, "second".into());
|
||||
assert_eq!(service.get_page(Some(u64::MAX - 2), 1)[0].seq, u64::MAX - 1);
|
||||
assert!(service.get_page(Some(u64::MAX), 1).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
//! Host region IO. Logical mapping, checksums and publication belong to the runtime.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MemcardIoError {
|
||||
Unavailable,
|
||||
ReadOnly,
|
||||
InvalidRange,
|
||||
NoSpace,
|
||||
Unsupported,
|
||||
Busy,
|
||||
AccessDenied,
|
||||
AlreadyExists,
|
||||
Indeterminate,
|
||||
IoError,
|
||||
}
|
||||
|
||||
/// Implementations return success only for a complete transfer. Errors may have
|
||||
/// partial effects. Instances stay owned by their worker until all IO has ceased.
|
||||
pub trait MemcardStorage: Send {
|
||||
fn len(&self) -> Result<u64, MemcardIoError>;
|
||||
fn is_empty(&self) -> Result<bool, MemcardIoError> {
|
||||
self.len().map(|length| length == 0)
|
||||
}
|
||||
fn read_at(&mut self, offset: u64, target: &mut [u8]) -> Result<(), MemcardIoError>;
|
||||
fn write_at(&mut self, offset: u64, source: &[u8]) -> Result<(), MemcardIoError>;
|
||||
fn sync(&mut self) -> Result<(), MemcardIoError>;
|
||||
fn read_only(&self) -> bool;
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
use crate::render_submission::{FrameId, RenderOwnership};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OwnedRgba8888Frame {
|
||||
pub frame_id: FrameId,
|
||||
pub ownership: RenderOwnership,
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub stride_pixels: usize,
|
||||
pub pixels: Vec<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum OwnedRgba8888FrameError {
|
||||
EmptyDimensions,
|
||||
StrideTooSmall,
|
||||
PixelBufferTooSmall,
|
||||
}
|
||||
|
||||
impl OwnedRgba8888Frame {
|
||||
pub fn new(
|
||||
frame_id: FrameId,
|
||||
ownership: RenderOwnership,
|
||||
width: usize,
|
||||
height: usize,
|
||||
stride_pixels: usize,
|
||||
pixels: Vec<u32>,
|
||||
) -> Result<Self, OwnedRgba8888FrameError> {
|
||||
if width == 0 || height == 0 {
|
||||
return Err(OwnedRgba8888FrameError::EmptyDimensions);
|
||||
}
|
||||
if stride_pixels < width {
|
||||
return Err(OwnedRgba8888FrameError::StrideTooSmall);
|
||||
}
|
||||
let required_len = stride_pixels
|
||||
.checked_mul(height)
|
||||
.ok_or(OwnedRgba8888FrameError::PixelBufferTooSmall)?;
|
||||
if pixels.len() < required_len {
|
||||
return Err(OwnedRgba8888FrameError::PixelBufferTooSmall);
|
||||
}
|
||||
|
||||
Ok(Self { frame_id, ownership, width, height, stride_pixels, pixels })
|
||||
}
|
||||
|
||||
pub fn packed(
|
||||
frame_id: FrameId,
|
||||
ownership: RenderOwnership,
|
||||
width: usize,
|
||||
height: usize,
|
||||
pixels: Vec<u32>,
|
||||
) -> Result<Self, OwnedRgba8888FrameError> {
|
||||
Self::new(frame_id, ownership, width, height, width, pixels)
|
||||
}
|
||||
|
||||
pub fn required_pixel_len(&self) -> usize {
|
||||
self.stride_pixels * self.height
|
||||
}
|
||||
|
||||
pub fn row(&self, y: usize) -> Option<&[u32]> {
|
||||
if y >= self.height {
|
||||
return None;
|
||||
}
|
||||
|
||||
let start = y * self.stride_pixels;
|
||||
Some(&self.pixels[start..start + self.width])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app_mode::AppMode;
|
||||
|
||||
fn ownership() -> RenderOwnership {
|
||||
RenderOwnership::new(11, AppMode::Game, 42)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_rgba8888_frame_preserves_metadata_and_pixels() {
|
||||
let pixels = vec![0x11223344, 0x55667788, 0x99AABBCC, 0xDDEEFF00];
|
||||
let frame = OwnedRgba8888Frame::packed(FrameId::new(7), ownership(), 2, 2, pixels.clone())
|
||||
.expect("valid packed RGBA8888 frame");
|
||||
|
||||
assert_eq!(frame.frame_id, FrameId::new(7));
|
||||
assert_eq!(frame.ownership, ownership());
|
||||
assert_eq!(frame.width, 2);
|
||||
assert_eq!(frame.height, 2);
|
||||
assert_eq!(frame.stride_pixels, 2);
|
||||
assert_eq!(frame.pixels, pixels);
|
||||
assert_eq!(frame.required_pixel_len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checked_constructor_rejects_empty_dimensions() {
|
||||
let err = OwnedRgba8888Frame::new(FrameId::ZERO, ownership(), 0, 1, 1, vec![0])
|
||||
.expect_err("zero width should be rejected");
|
||||
|
||||
assert_eq!(err, OwnedRgba8888FrameError::EmptyDimensions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checked_constructor_rejects_stride_smaller_than_width() {
|
||||
let err = OwnedRgba8888Frame::new(FrameId::ZERO, ownership(), 3, 1, 2, vec![0, 0, 0])
|
||||
.expect_err("stride smaller than width should be rejected");
|
||||
|
||||
assert_eq!(err, OwnedRgba8888FrameError::StrideTooSmall);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checked_constructor_rejects_short_pixel_buffer() {
|
||||
let err = OwnedRgba8888Frame::new(FrameId::ZERO, ownership(), 2, 2, 3, vec![0; 5])
|
||||
.expect_err("buffer shorter than stride * height should be rejected");
|
||||
|
||||
assert_eq!(err, OwnedRgba8888FrameError::PixelBufferTooSmall);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_returns_visible_width_without_stride_padding() {
|
||||
let frame =
|
||||
OwnedRgba8888Frame::new(FrameId::ZERO, ownership(), 2, 2, 3, vec![1, 2, 99, 3, 4, 88])
|
||||
.expect("valid padded frame");
|
||||
|
||||
assert_eq!(frame.row(0), Some(&[1, 2][..]));
|
||||
assert_eq!(frame.row(1), Some(&[3, 4][..]));
|
||||
assert_eq!(frame.row(2), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use crate::asset_bridge::AssetBridge;
|
||||
use crate::audio_bridge::AudioBridge;
|
||||
use crate::composer_status::ComposerOpStatus;
|
||||
use crate::pad_bridge::PadBridge;
|
||||
use crate::render_submission::{Game2DFramePacket, RenderSubmission};
|
||||
use crate::sprite::Sprite;
|
||||
use crate::telemetry::TelemetryFrame;
|
||||
use crate::touch_bridge::TouchBridge;
|
||||
use crate::wall_clock::WallClock;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RenderSubmitError {
|
||||
BackendUnavailable,
|
||||
SubmissionRejected,
|
||||
}
|
||||
|
||||
pub trait RenderSubmissionSink {
|
||||
fn submit_render_submission(
|
||||
&mut self,
|
||||
submission: RenderSubmission,
|
||||
) -> Result<(), RenderSubmitError>;
|
||||
}
|
||||
|
||||
pub trait RenderBackend {
|
||||
fn render_frame(&mut self);
|
||||
}
|
||||
|
||||
pub trait Game2DFrameComposer {
|
||||
fn begin_frame(&mut self);
|
||||
fn bind_scene(&mut self, scene_bank_id: usize) -> ComposerOpStatus;
|
||||
fn unbind_scene(&mut self);
|
||||
fn set_camera(&mut self, x: i32, y: i32) -> ComposerOpStatus;
|
||||
fn emit_sprite(&mut self, sprite: Sprite) -> ComposerOpStatus;
|
||||
fn close_game2d_packet(&self) -> Game2DFramePacket;
|
||||
}
|
||||
|
||||
pub trait AudioPlatform: AudioBridge {}
|
||||
impl<T: AudioBridge + ?Sized> AudioPlatform for T {}
|
||||
|
||||
pub trait InputPlatform {
|
||||
fn pad(&self) -> &dyn PadBridge;
|
||||
fn pad_mut(&mut self) -> &mut dyn PadBridge;
|
||||
fn touch(&self) -> &dyn TouchBridge;
|
||||
fn touch_mut(&mut self) -> &mut dyn TouchBridge;
|
||||
}
|
||||
|
||||
pub trait AssetStoragePlatform: AssetBridge {}
|
||||
impl<T: AssetBridge + ?Sized> AssetStoragePlatform for T {}
|
||||
|
||||
pub trait ClockPacingPlatform {}
|
||||
|
||||
pub trait TelemetryPlatform {
|
||||
fn telemetry_snapshot(&self) -> Option<TelemetryFrame> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct NoopTelemetryPlatform;
|
||||
|
||||
impl TelemetryPlatform for NoopTelemetryPlatform {}
|
||||
|
||||
pub trait RuntimePlatform {
|
||||
fn wall_clock(&self) -> &dyn WallClock;
|
||||
|
||||
fn display_size(&self) -> (usize, usize) {
|
||||
(480, 270)
|
||||
}
|
||||
|
||||
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink;
|
||||
fn render_backend(&mut self) -> &mut dyn RenderBackend;
|
||||
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer;
|
||||
fn audio(&self) -> &dyn AudioBridge;
|
||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge;
|
||||
fn input(&self) -> &dyn InputPlatform;
|
||||
fn input_mut(&mut self) -> &mut dyn InputPlatform;
|
||||
fn assets(&self) -> &dyn AssetBridge;
|
||||
fn assets_mut(&mut self) -> &mut dyn AssetBridge;
|
||||
fn telemetry(&self) -> &dyn TelemetryPlatform;
|
||||
}
|
||||
|
||||
pub trait TestPlatform: RuntimePlatform {}
|
||||
impl<T: RuntimePlatform + ?Sized> TestPlatform for T {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn assert_render_sink_object(_: &mut dyn RenderSubmissionSink) {}
|
||||
fn assert_backend_object(_: &mut dyn RenderBackend) {}
|
||||
fn assert_composer_object(_: &mut dyn Game2DFrameComposer) {}
|
||||
|
||||
struct CompileOnly;
|
||||
|
||||
impl RenderSubmissionSink for CompileOnly {
|
||||
fn submit_render_submission(
|
||||
&mut self,
|
||||
_submission: RenderSubmission,
|
||||
) -> Result<(), RenderSubmitError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderBackend for CompileOnly {
|
||||
fn render_frame(&mut self) {}
|
||||
}
|
||||
|
||||
impl Game2DFrameComposer for CompileOnly {
|
||||
fn begin_frame(&mut self) {}
|
||||
|
||||
fn bind_scene(&mut self, _scene_bank_id: usize) -> ComposerOpStatus {
|
||||
ComposerOpStatus::Ok
|
||||
}
|
||||
|
||||
fn unbind_scene(&mut self) {}
|
||||
|
||||
fn set_camera(&mut self, _x: i32, _y: i32) -> ComposerOpStatus {
|
||||
ComposerOpStatus::Ok
|
||||
}
|
||||
|
||||
fn emit_sprite(&mut self, _sprite: Sprite) -> ComposerOpStatus {
|
||||
ComposerOpStatus::Ok
|
||||
}
|
||||
|
||||
fn close_game2d_packet(&self) -> Game2DFramePacket {
|
||||
Game2DFramePacket::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_platform_facades_are_object_safe() {
|
||||
let mut compile_only = CompileOnly;
|
||||
|
||||
assert_render_sink_object(&mut compile_only);
|
||||
assert_backend_object(&mut compile_only);
|
||||
assert_composer_object(&mut compile_only);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_submit_error_is_typed_and_debuggable() {
|
||||
assert_eq!(format!("{:?}", RenderSubmitError::BackendUnavailable), "BackendUnavailable");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Rect {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub w: i32,
|
||||
pub h: i32,
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
use crate::glyph_bank::GlyphBank;
|
||||
use crate::scene_bank::SceneBank;
|
||||
|
||||
/// Read-only render resource lookup used by render backends.
|
||||
///
|
||||
/// Resource ids are stable bank slots carried by render submissions. The
|
||||
/// callback shape keeps bank ownership inside the provider while exposing only
|
||||
/// borrowed read access to the caller.
|
||||
pub trait RenderResourceAccess {
|
||||
/// Reads a resident glyph bank by id.
|
||||
fn with_glyph_bank<R>(&self, bank_id: usize, read: impl FnOnce(&GlyphBank) -> R) -> Option<R>;
|
||||
|
||||
/// Returns the number of glyph bank ids accepted by this provider.
|
||||
fn glyph_bank_count(&self) -> usize;
|
||||
|
||||
/// Reads a resident scene bank by id.
|
||||
fn with_scene_bank<R>(&self, bank_id: usize, read: impl FnOnce(&SceneBank) -> R) -> Option<R>;
|
||||
|
||||
/// Returns the number of scene bank ids accepted by this provider.
|
||||
fn scene_bank_count(&self) -> usize;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::glyph::Glyph;
|
||||
use crate::glyph_bank::TileSize;
|
||||
use crate::scene_layer::{ParallaxFactor, SceneLayer};
|
||||
use crate::tile::Tile;
|
||||
use crate::tilemap::TileMap;
|
||||
|
||||
struct TestRenderResources {
|
||||
glyph_banks: Vec<Option<GlyphBank>>,
|
||||
scene_banks: Vec<Option<SceneBank>>,
|
||||
}
|
||||
|
||||
impl RenderResourceAccess for TestRenderResources {
|
||||
fn with_glyph_bank<R>(
|
||||
&self,
|
||||
bank_id: usize,
|
||||
read: impl FnOnce(&GlyphBank) -> R,
|
||||
) -> Option<R> {
|
||||
self.glyph_banks.get(bank_id)?.as_ref().map(read)
|
||||
}
|
||||
|
||||
fn glyph_bank_count(&self) -> usize {
|
||||
self.glyph_banks.len()
|
||||
}
|
||||
|
||||
fn with_scene_bank<R>(
|
||||
&self,
|
||||
bank_id: usize,
|
||||
read: impl FnOnce(&SceneBank) -> R,
|
||||
) -> Option<R> {
|
||||
self.scene_banks.get(bank_id)?.as_ref().map(read)
|
||||
}
|
||||
|
||||
fn scene_bank_count(&self) -> usize {
|
||||
self.scene_banks.len()
|
||||
}
|
||||
}
|
||||
|
||||
fn scene_bank(tile_size: TileSize) -> SceneBank {
|
||||
let layer = SceneLayer {
|
||||
active: true,
|
||||
glyph_asset_id: 7,
|
||||
tile_size,
|
||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||
tilemap: TileMap {
|
||||
width: 1,
|
||||
height: 1,
|
||||
tiles: vec![Tile {
|
||||
active: true,
|
||||
glyph: Glyph { glyph_id: 3, palette_id: 0 },
|
||||
flip_x: false,
|
||||
flip_y: false,
|
||||
}],
|
||||
},
|
||||
};
|
||||
|
||||
SceneBank { layers: std::array::from_fn(|_| layer.clone()) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_resident_resources_by_id() {
|
||||
let resources = TestRenderResources {
|
||||
glyph_banks: vec![None, Some(GlyphBank::new(TileSize::Size16, 16, 16)), None],
|
||||
scene_banks: vec![Some(scene_bank(TileSize::Size8)), None],
|
||||
};
|
||||
|
||||
assert_eq!(resources.glyph_bank_count(), 3);
|
||||
assert_eq!(resources.scene_bank_count(), 2);
|
||||
assert_eq!(resources.with_glyph_bank(1, |bank| bank.tile_size), Some(TileSize::Size16));
|
||||
assert_eq!(
|
||||
resources.with_scene_bank(0, |bank| bank.layers[0].tile_size),
|
||||
Some(TileSize::Size8)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_resources_return_none() {
|
||||
let resources = TestRenderResources { glyph_banks: vec![None], scene_banks: vec![None] };
|
||||
|
||||
assert_eq!(resources.with_glyph_bank(0, |bank| bank.width), None);
|
||||
assert_eq!(resources.with_glyph_bank(9, |bank| bank.width), None);
|
||||
assert_eq!(resources.with_scene_bank(0, |bank| bank.layers[0].active), None);
|
||||
assert_eq!(resources.with_scene_bank(9, |bank| bank.layers[0].active), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
use crate::app_mode::AppMode;
|
||||
use crate::color::Color;
|
||||
use crate::primitives::Rect;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
||||
pub struct FrameId(pub u64);
|
||||
|
||||
impl FrameId {
|
||||
pub const ZERO: Self = Self(0);
|
||||
|
||||
pub const fn new(value: u64) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
pub const fn get(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub const fn next(self) -> Self {
|
||||
Self(self.0.wrapping_add(1))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RenderSubmission {
|
||||
pub frame_id: FrameId,
|
||||
pub app_mode: AppMode,
|
||||
pub ownership: RenderOwnership,
|
||||
pub packet: RenderSubmissionPacket,
|
||||
}
|
||||
|
||||
impl RenderSubmission {
|
||||
pub const fn game2d(frame_id: FrameId, packet: Game2DFramePacket) -> Self {
|
||||
Self {
|
||||
frame_id,
|
||||
app_mode: AppMode::Game,
|
||||
ownership: RenderOwnership::new(0, AppMode::Game, 0),
|
||||
packet: RenderSubmissionPacket::Game2D(packet),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn shell_ui(frame_id: FrameId, packet: ShellUiFramePacket) -> Self {
|
||||
Self {
|
||||
frame_id,
|
||||
app_mode: AppMode::Shell,
|
||||
ownership: RenderOwnership::new(0, AppMode::Shell, 0),
|
||||
packet: RenderSubmissionPacket::ShellUi(packet),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn with_ownership(mut self, ownership: RenderOwnership) -> Self {
|
||||
self.ownership = ownership;
|
||||
self
|
||||
}
|
||||
|
||||
pub const fn is_coherent(&self) -> bool {
|
||||
matches!(
|
||||
(self.app_mode, &self.packet),
|
||||
(AppMode::Game, RenderSubmissionPacket::Game2D(_))
|
||||
| (AppMode::Shell, RenderSubmissionPacket::ShellUi(_))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RenderOwnership {
|
||||
pub epoch: u64,
|
||||
pub app_mode: AppMode,
|
||||
pub app_id: u32,
|
||||
}
|
||||
|
||||
impl RenderOwnership {
|
||||
pub const fn new(epoch: u64, app_mode: AppMode, app_id: u32) -> Self {
|
||||
Self { epoch, app_mode, app_id }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RenderSubmissionPacket {
|
||||
Game2D(Game2DFramePacket),
|
||||
ShellUi(ShellUiFramePacket),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct Game2DFramePacket {
|
||||
pub composer: ComposerFramePacket,
|
||||
pub gfx2d: Vec<Gfx2dCommand>,
|
||||
}
|
||||
|
||||
impl Game2DFramePacket {
|
||||
pub fn new(composer: ComposerFramePacket, gfx2d: Vec<Gfx2dCommand>) -> Self {
|
||||
Self { composer, gfx2d }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ShellUiFramePacket {
|
||||
pub commands: Vec<GfxUiCommand>,
|
||||
}
|
||||
|
||||
impl ShellUiFramePacket {
|
||||
pub fn new(commands: Vec<GfxUiCommand>) -> Self {
|
||||
Self { commands }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct ComposerFramePacket {
|
||||
pub bound_scene: Option<BoundScenePacket>,
|
||||
pub camera: Camera2D,
|
||||
pub sprites: Vec<GameSpritePacket>,
|
||||
pub hud: HudPacket,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BoundScenePacket {
|
||||
pub bank_id: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct Camera2D {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct GameSpritePacket {
|
||||
pub glyph_id: i32,
|
||||
pub palette_id: i32,
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub layer: i32,
|
||||
pub bank_id: i32,
|
||||
pub flip_x: bool,
|
||||
pub flip_y: bool,
|
||||
pub priority: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct HudPacket {
|
||||
pub commands: Vec<HudCommand>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum HudCommand {
|
||||
Clear { color: Color },
|
||||
FillRect { rect: Rect, color: Color },
|
||||
DrawText { x: i32, y: i32, text: String, color: Color },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Gfx2dCommand {
|
||||
Clear { color: Color },
|
||||
FillRect { rect: Rect, color: Color },
|
||||
DrawLine { x0: i32, y0: i32, x1: i32, y1: i32, color: Color },
|
||||
DrawCircle { x: i32, y: i32, radius: i32, color: Color },
|
||||
DrawDisc { x: i32, y: i32, radius: i32, border_color: Color, fill_color: Color },
|
||||
DrawSquare { rect: Rect, border_color: Color, fill_color: Color },
|
||||
DrawText { x: i32, y: i32, text: String, color: Color },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum GfxUiCommand {
|
||||
Clear { color: Color },
|
||||
FillRect { rect: Rect, color: Color },
|
||||
DrawLine { x0: i32, y0: i32, x1: i32, y1: i32, color: Color },
|
||||
DrawCircle { x: i32, y: i32, radius: i32, color: Color },
|
||||
DrawDisc { x: i32, y: i32, radius: i32, border_color: Color, fill_color: Color },
|
||||
DrawSquare { rect: Rect, border_color: Color, fill_color: Color },
|
||||
DrawText { x: i32, y: i32, text: String, color: Color },
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn constructors_pin_app_mode_to_packet_kind() {
|
||||
let game = RenderSubmission::game2d(FrameId::new(7), Game2DFramePacket::default());
|
||||
assert_eq!(game.app_mode, AppMode::Game);
|
||||
assert!(matches!(game.packet, RenderSubmissionPacket::Game2D(_)));
|
||||
assert!(game.is_coherent());
|
||||
|
||||
let shell =
|
||||
RenderSubmission::shell_ui(FrameId::new(8), ShellUiFramePacket::new(Vec::new()));
|
||||
assert_eq!(shell.app_mode, AppMode::Shell);
|
||||
assert!(matches!(shell.packet, RenderSubmissionPacket::ShellUi(_)));
|
||||
assert!(shell.is_coherent());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coherence_check_rejects_mismatched_envelope() {
|
||||
let submission = RenderSubmission {
|
||||
frame_id: FrameId::new(1),
|
||||
app_mode: AppMode::Game,
|
||||
ownership: RenderOwnership::new(0, AppMode::Game, 0),
|
||||
packet: RenderSubmissionPacket::ShellUi(ShellUiFramePacket::new(Vec::new())),
|
||||
};
|
||||
|
||||
assert!(!submission.is_coherent());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ownership_can_be_stamped_by_runtime() {
|
||||
let submission = RenderSubmission::game2d(FrameId::new(3), Game2DFramePacket::default())
|
||||
.with_ownership(RenderOwnership::new(9, AppMode::Game, 42));
|
||||
|
||||
assert_eq!(submission.ownership, RenderOwnership::new(9, AppMode::Game, 42));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_submission_owns_command_payload() {
|
||||
let mut commands = vec![Gfx2dCommand::DrawText {
|
||||
x: 1,
|
||||
y: 2,
|
||||
text: "before".to_string(),
|
||||
color: Color::WHITE,
|
||||
}];
|
||||
let submission = RenderSubmission::game2d(
|
||||
FrameId::new(2),
|
||||
Game2DFramePacket::new(Default::default(), commands.clone()),
|
||||
);
|
||||
|
||||
commands.push(Gfx2dCommand::Clear { color: Color::BLACK });
|
||||
|
||||
let RenderSubmissionPacket::Game2D(packet) = submission.packet else {
|
||||
panic!("expected game packet");
|
||||
};
|
||||
assert_eq!(packet.gfx2d.len(), 1);
|
||||
assert_eq!(
|
||||
packet.gfx2d[0],
|
||||
Gfx2dCommand::DrawText { x: 1, y: 2, text: "before".to_string(), color: Color::WHITE }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_id_advances_monotonically_with_wrapping_arithmetic() {
|
||||
assert_eq!(FrameId::new(41).next(), FrameId::new(42));
|
||||
assert_eq!(FrameId::new(u64::MAX).next(), FrameId::ZERO);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
use std::fmt;
|
||||
|
||||
use crate::{OwnedRgba8888Frame, RenderSubmission};
|
||||
|
||||
/// Typed failure surface for the real render worker and its backend.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RenderWorkerError {
|
||||
BackendUnavailable,
|
||||
RenderFailed,
|
||||
PublishFailed,
|
||||
PresentFailed,
|
||||
ShutdownTimeout,
|
||||
StaleSubmissionDiscarded,
|
||||
WorkerPanic,
|
||||
InternalFailure,
|
||||
}
|
||||
|
||||
impl fmt::Display for RenderWorkerError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::BackendUnavailable => f.write_str("render backend unavailable"),
|
||||
Self::RenderFailed => f.write_str("render failed"),
|
||||
Self::PublishFailed => f.write_str("render publish failed"),
|
||||
Self::PresentFailed => f.write_str("render present failed"),
|
||||
Self::ShutdownTimeout => f.write_str("render worker shutdown timed out"),
|
||||
Self::StaleSubmissionDiscarded => f.write_str("stale render submission discarded"),
|
||||
Self::WorkerPanic => f.write_str("render worker panicked"),
|
||||
Self::InternalFailure => f.write_str("internal render worker failure"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RenderWorkerError {}
|
||||
|
||||
pub trait RenderWorkerBackend: Send + 'static {
|
||||
fn render(
|
||||
&self,
|
||||
submission: &RenderSubmission,
|
||||
) -> Result<OwnedRgba8888Frame, RenderWorkerError>;
|
||||
}
|
||||
|
||||
pub trait RenderWorkerFrameSink: Send + 'static {
|
||||
fn publish(&self, frame: OwnedRgba8888Frame) -> Result<(), RenderWorkerError>;
|
||||
}
|
||||
|
||||
/// Snapshot of render worker handoff, render, publish, and shutdown counters.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct RenderWorkerTelemetry {
|
||||
pub produced_submissions: u64,
|
||||
pub replaced_before_consume: u64,
|
||||
pub consumed_submissions: u64,
|
||||
pub published_frames: u64,
|
||||
pub presented_frames: u64,
|
||||
pub repeated_frames: u64,
|
||||
pub stale_submission_discards: u64,
|
||||
pub render_failures: u64,
|
||||
pub publish_failures: u64,
|
||||
pub present_failures: u64,
|
||||
pub shutdown_timeouts: u64,
|
||||
pub worker_panics: u64,
|
||||
pub last_produced_frame_id: u64,
|
||||
pub last_consumed_frame_id: u64,
|
||||
pub last_published_frame_id: u64,
|
||||
pub last_presented_frame_id: u64,
|
||||
pub last_dropped_frame_id: u64,
|
||||
pub last_error_frame_id: u64,
|
||||
pub active_render_epoch: u64,
|
||||
}
|
||||
|
||||
impl RenderWorkerTelemetry {
|
||||
pub fn record_produced(&mut self, frame_id: u64) {
|
||||
self.produced_submissions += 1;
|
||||
self.last_produced_frame_id = frame_id;
|
||||
}
|
||||
|
||||
pub fn record_replaced_before_consume(&mut self, frame_id: u64) {
|
||||
self.replaced_before_consume += 1;
|
||||
self.last_dropped_frame_id = frame_id;
|
||||
}
|
||||
|
||||
pub fn record_consumed(&mut self, frame_id: u64) {
|
||||
self.consumed_submissions += 1;
|
||||
self.last_consumed_frame_id = frame_id;
|
||||
}
|
||||
|
||||
pub fn record_published(&mut self, frame_id: u64) {
|
||||
self.published_frames += 1;
|
||||
self.last_published_frame_id = frame_id;
|
||||
}
|
||||
|
||||
pub fn record_presented(&mut self, frame_id: u64) {
|
||||
self.presented_frames += 1;
|
||||
self.last_presented_frame_id = frame_id;
|
||||
}
|
||||
|
||||
pub fn record_repeated_frame(&mut self, frame_id: u64) {
|
||||
self.repeated_frames += 1;
|
||||
self.last_presented_frame_id = frame_id;
|
||||
}
|
||||
|
||||
pub fn record_stale_submission_discarded(&mut self, frame_id: u64) {
|
||||
self.stale_submission_discards += 1;
|
||||
self.last_dropped_frame_id = frame_id;
|
||||
}
|
||||
|
||||
pub fn record_error(&mut self, error: RenderWorkerError, frame_id: u64) {
|
||||
match error {
|
||||
RenderWorkerError::BackendUnavailable | RenderWorkerError::RenderFailed => {
|
||||
self.render_failures += 1;
|
||||
}
|
||||
RenderWorkerError::PublishFailed => {
|
||||
self.publish_failures += 1;
|
||||
}
|
||||
RenderWorkerError::PresentFailed => {
|
||||
self.present_failures += 1;
|
||||
}
|
||||
RenderWorkerError::ShutdownTimeout => {
|
||||
self.shutdown_timeouts += 1;
|
||||
}
|
||||
RenderWorkerError::WorkerPanic => {
|
||||
self.worker_panics += 1;
|
||||
}
|
||||
RenderWorkerError::StaleSubmissionDiscarded => {
|
||||
self.stale_submission_discards += 1;
|
||||
self.last_dropped_frame_id = frame_id;
|
||||
}
|
||||
RenderWorkerError::InternalFailure => {
|
||||
self.render_failures += 1;
|
||||
}
|
||||
}
|
||||
self.last_error_frame_id = frame_id;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn render_worker_error_is_copy_equatable_and_debuggable() {
|
||||
let error = RenderWorkerError::ShutdownTimeout;
|
||||
let copied = error;
|
||||
|
||||
assert_eq!(copied, RenderWorkerError::ShutdownTimeout);
|
||||
assert_eq!(format!("{:?}", error), "ShutdownTimeout");
|
||||
assert_eq!(error.to_string(), "render worker shutdown timed out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_worker_telemetry_defaults_to_zero() {
|
||||
assert_eq!(
|
||||
RenderWorkerTelemetry::default(),
|
||||
RenderWorkerTelemetry {
|
||||
produced_submissions: 0,
|
||||
replaced_before_consume: 0,
|
||||
consumed_submissions: 0,
|
||||
published_frames: 0,
|
||||
presented_frames: 0,
|
||||
repeated_frames: 0,
|
||||
stale_submission_discards: 0,
|
||||
render_failures: 0,
|
||||
publish_failures: 0,
|
||||
present_failures: 0,
|
||||
shutdown_timeouts: 0,
|
||||
worker_panics: 0,
|
||||
last_produced_frame_id: 0,
|
||||
last_consumed_frame_id: 0,
|
||||
last_published_frame_id: 0,
|
||||
last_presented_frame_id: 0,
|
||||
last_dropped_frame_id: 0,
|
||||
last_error_frame_id: 0,
|
||||
active_render_epoch: 0,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_worker_telemetry_records_counters_and_frame_ids() {
|
||||
let mut telemetry = RenderWorkerTelemetry::default();
|
||||
|
||||
telemetry.record_produced(10);
|
||||
telemetry.record_replaced_before_consume(10);
|
||||
telemetry.record_consumed(11);
|
||||
telemetry.record_published(11);
|
||||
telemetry.record_presented(11);
|
||||
telemetry.record_repeated_frame(11);
|
||||
telemetry.record_error(RenderWorkerError::PublishFailed, 12);
|
||||
telemetry.record_error(RenderWorkerError::WorkerPanic, 13);
|
||||
telemetry.record_stale_submission_discarded(14);
|
||||
|
||||
assert_eq!(telemetry.produced_submissions, 1);
|
||||
assert_eq!(telemetry.replaced_before_consume, 1);
|
||||
assert_eq!(telemetry.consumed_submissions, 1);
|
||||
assert_eq!(telemetry.published_frames, 1);
|
||||
assert_eq!(telemetry.presented_frames, 1);
|
||||
assert_eq!(telemetry.repeated_frames, 1);
|
||||
assert_eq!(telemetry.publish_failures, 1);
|
||||
assert_eq!(telemetry.worker_panics, 1);
|
||||
assert_eq!(telemetry.stale_submission_discards, 1);
|
||||
assert_eq!(telemetry.last_error_frame_id, 13);
|
||||
assert_eq!(telemetry.last_dropped_frame_id, 14);
|
||||
}
|
||||
}
|
||||
@@ -8,16 +8,22 @@ pub struct SceneBank {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::asset::AssetId;
|
||||
use crate::glyph::Glyph;
|
||||
use crate::glyph_bank::TileSize;
|
||||
use crate::scene_layer::ParallaxFactor;
|
||||
use crate::tile::Tile;
|
||||
use crate::tilemap::TileMap;
|
||||
|
||||
fn layer(glyph_bank_id: u8, parallax_x: f32, parallax_y: f32, glyph_id: u16) -> SceneLayer {
|
||||
fn layer(
|
||||
glyph_asset_id: AssetId,
|
||||
parallax_x: f32,
|
||||
parallax_y: f32,
|
||||
glyph_id: u16,
|
||||
) -> SceneLayer {
|
||||
SceneLayer {
|
||||
active: true,
|
||||
glyph_bank_id,
|
||||
glyph_asset_id,
|
||||
tile_size: TileSize::Size16,
|
||||
parallax_factor: ParallaxFactor { x: parallax_x, y: parallax_y },
|
||||
tilemap: TileMap {
|
||||
@@ -25,7 +31,7 @@ mod tests {
|
||||
height: 1,
|
||||
tiles: vec![Tile {
|
||||
active: true,
|
||||
glyph: Glyph { glyph_id, palette_id: glyph_bank_id },
|
||||
glyph: Glyph { glyph_id, palette_id: 1 },
|
||||
flip_x: false,
|
||||
flip_y: false,
|
||||
}],
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::asset::AssetId;
|
||||
use crate::glyph_bank::TileSize;
|
||||
use crate::tilemap::TileMap;
|
||||
|
||||
@@ -10,7 +11,7 @@ pub struct ParallaxFactor {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SceneLayer {
|
||||
pub active: bool,
|
||||
pub glyph_bank_id: u8,
|
||||
pub glyph_asset_id: AssetId,
|
||||
pub tile_size: TileSize,
|
||||
pub parallax_factor: ParallaxFactor,
|
||||
pub tilemap: TileMap,
|
||||
@@ -26,7 +27,7 @@ mod tests {
|
||||
fn scene_layer_preserves_parallax_factor_and_tilemap_ownership() {
|
||||
let layer = SceneLayer {
|
||||
active: true,
|
||||
glyph_bank_id: 7,
|
||||
glyph_asset_id: 7,
|
||||
tile_size: TileSize::Size16,
|
||||
parallax_factor: ParallaxFactor { x: 0.5, y: 0.75 },
|
||||
tilemap: TileMap {
|
||||
@@ -49,7 +50,7 @@ mod tests {
|
||||
},
|
||||
};
|
||||
|
||||
assert_eq!(layer.glyph_bank_id, 7);
|
||||
assert_eq!(layer.glyph_asset_id, 7);
|
||||
assert_eq!(layer.parallax_factor.x, 0.5);
|
||||
assert_eq!(layer.parallax_factor.y, 0.75);
|
||||
assert_eq!(layer.tilemap.width, 2);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::asset::AssetId;
|
||||
use crate::glyph_bank::TileSize;
|
||||
use crate::scene_bank::SceneBank;
|
||||
use crate::scene_layer::SceneLayer;
|
||||
@@ -12,7 +13,7 @@ pub struct CachedTileEntry {
|
||||
pub glyph_id: u16,
|
||||
pub palette_id: u8,
|
||||
pub flags: u8,
|
||||
pub glyph_bank_id: u8,
|
||||
pub glyph_asset_id: AssetId,
|
||||
}
|
||||
|
||||
impl CachedTileEntry {
|
||||
@@ -38,7 +39,7 @@ impl CachedTileEntry {
|
||||
glyph_id: tile.glyph.glyph_id,
|
||||
palette_id: tile.glyph.palette_id,
|
||||
flags,
|
||||
glyph_bank_id: layer.glyph_bank_id,
|
||||
glyph_asset_id: layer.glyph_asset_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,7 +66,7 @@ pub struct SceneViewportLayerCache {
|
||||
logical_origin_y: i32,
|
||||
ring_origin_x: usize,
|
||||
ring_origin_y: usize,
|
||||
pub glyph_bank_id: u8,
|
||||
pub glyph_asset_id: AssetId,
|
||||
pub tile_size: TileSize,
|
||||
entries: Vec<CachedTileEntry>,
|
||||
pub valid: bool,
|
||||
@@ -80,7 +81,7 @@ impl SceneViewportLayerCache {
|
||||
logical_origin_y: 0,
|
||||
ring_origin_x: 0,
|
||||
ring_origin_y: 0,
|
||||
glyph_bank_id: layer.glyph_bank_id,
|
||||
glyph_asset_id: layer.glyph_asset_id,
|
||||
tile_size: layer.tile_size,
|
||||
entries: vec![CachedTileEntry::default(); width * height],
|
||||
valid: false,
|
||||
@@ -136,7 +137,7 @@ impl SceneViewportLayerCache {
|
||||
}
|
||||
|
||||
pub fn refresh_region(&mut self, layer: &SceneLayer, region: ViewportRegion) {
|
||||
self.glyph_bank_id = layer.glyph_bank_id;
|
||||
self.glyph_asset_id = layer.glyph_asset_id;
|
||||
self.tile_size = layer.tile_size;
|
||||
|
||||
let max_x = region.x.saturating_add(region.width).min(self.width);
|
||||
@@ -268,6 +269,7 @@ impl SceneViewportCache {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::asset::AssetId;
|
||||
use crate::glyph::Glyph;
|
||||
use crate::glyph_bank::TileSize;
|
||||
use crate::scene_layer::ParallaxFactor;
|
||||
@@ -278,22 +280,17 @@ mod tests {
|
||||
Tile { active: true, glyph: Glyph { glyph_id, palette_id }, flip_x, flip_y }
|
||||
}
|
||||
|
||||
fn make_layer(glyph_bank_id: u8, base_glyph: u16) -> SceneLayer {
|
||||
fn make_layer(glyph_asset_id: AssetId, base_glyph: u16) -> SceneLayer {
|
||||
let mut tiles = Vec::new();
|
||||
for y in 0..4 {
|
||||
for x in 0..4 {
|
||||
tiles.push(make_tile(
|
||||
base_glyph + (y * 4 + x) as u16,
|
||||
glyph_bank_id,
|
||||
x % 2 == 0,
|
||||
y % 2 == 1,
|
||||
));
|
||||
tiles.push(make_tile(base_glyph + (y * 4 + x) as u16, 1, x % 2 == 0, y % 2 == 1));
|
||||
}
|
||||
}
|
||||
|
||||
SceneLayer {
|
||||
active: true,
|
||||
glyph_bank_id,
|
||||
glyph_asset_id,
|
||||
tile_size: TileSize::Size16,
|
||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||
tilemap: TileMap { width: 4, height: 4, tiles },
|
||||
@@ -364,7 +361,7 @@ mod tests {
|
||||
assert!(entry.active);
|
||||
assert_eq!(entry.glyph_id, 105);
|
||||
assert_eq!(entry.palette_id, 1);
|
||||
assert_eq!(entry.glyph_bank_id, 1);
|
||||
assert_eq!(entry.glyph_asset_id, 1);
|
||||
assert!(!entry.flip_x());
|
||||
assert!(entry.flip_y());
|
||||
}
|
||||
|
||||
@@ -386,6 +386,7 @@ impl SceneViewportResolver {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::asset::AssetId;
|
||||
use crate::glyph::Glyph;
|
||||
use crate::glyph_bank::TileSize;
|
||||
use crate::scene_layer::{ParallaxFactor, SceneLayer};
|
||||
@@ -411,7 +412,7 @@ mod tests {
|
||||
|
||||
SceneLayer {
|
||||
active: true,
|
||||
glyph_bank_id: 1,
|
||||
glyph_asset_id: 1 as AssetId,
|
||||
tile_size,
|
||||
parallax_factor: ParallaxFactor { x: parallax_x, y: parallax_y },
|
||||
tilemap: TileMap { width, height, tiles },
|
||||
@@ -432,20 +433,20 @@ mod tests {
|
||||
#[test]
|
||||
fn first_update_initializes_master_and_layer_anchors() {
|
||||
let scene = make_scene();
|
||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
|
||||
let update = resolver.update(&scene, 0, 0);
|
||||
|
||||
assert_eq!(update.master_anchor, TileAnchor { x: 12, y: 8 });
|
||||
assert_eq!(update.layer_anchors[0], TileAnchor { x: 12, y: 8 });
|
||||
assert_eq!(update.layer_anchors[1], TileAnchor { x: 12, y: 8 });
|
||||
assert_eq!(update.master_anchor, TileAnchor { x: 17, y: 10 });
|
||||
assert_eq!(update.layer_anchors[0], TileAnchor { x: 17, y: 10 });
|
||||
assert_eq!(update.layer_anchors[1], TileAnchor { x: 17, y: 10 });
|
||||
assert_eq!(update.refresh_requests.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_layer_copy_requests_follow_parallax_factor() {
|
||||
let scene = make_scene();
|
||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
|
||||
let update = resolver.update(&scene, 32, 48);
|
||||
|
||||
@@ -460,24 +461,24 @@ mod tests {
|
||||
#[test]
|
||||
fn hysteresis_prevents_small_back_and_forth_refresh_churn() {
|
||||
let scene = make_scene();
|
||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
|
||||
let _ = resolver.update(&scene, 0, 0);
|
||||
let update = resolver.update(&scene, 8, 0);
|
||||
|
||||
assert!(update.refresh_requests.is_empty());
|
||||
assert_eq!(update.master_anchor, TileAnchor { x: 12, y: 8 });
|
||||
assert_eq!(update.master_anchor, TileAnchor { x: 17, y: 10 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_high_speed_movement_advances_in_tile_steps() {
|
||||
let scene = make_scene();
|
||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
|
||||
let _ = resolver.update(&scene, 0, 0);
|
||||
let update = resolver.update(&scene, 64, 0);
|
||||
|
||||
assert!(update.master_anchor.x > 12);
|
||||
assert!(update.master_anchor.x > 17);
|
||||
assert!(update.refresh_requests.iter().any(|request| matches!(
|
||||
request,
|
||||
CacheRefreshRequest::RefreshColumn { layer_index: 0, .. }
|
||||
@@ -488,18 +489,18 @@ mod tests {
|
||||
#[test]
|
||||
fn anchors_clamp_near_scene_edges() {
|
||||
let scene = make_scene();
|
||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
|
||||
let update = resolver.update(&scene, 10_000, 10_000);
|
||||
|
||||
assert_eq!(update.master_anchor, TileAnchor { x: 51, y: 56 });
|
||||
assert_eq!(update.layer_anchors[0], TileAnchor { x: 51, y: 56 });
|
||||
assert_eq!(update.master_anchor, TileAnchor { x: 46, y: 53 });
|
||||
assert_eq!(update.layer_anchors[0], TileAnchor { x: 46, y: 53 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_trigger_converts_to_non_overlapping_region_requests() {
|
||||
let scene = make_scene();
|
||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
|
||||
let _ = resolver.update(&scene, 0, 0);
|
||||
let update = resolver.update(&scene, 64, 80);
|
||||
@@ -514,15 +515,15 @@ mod tests {
|
||||
.collect();
|
||||
|
||||
assert_eq!(regions.len(), 2);
|
||||
assert_eq!(regions[0].x + regions[0].width, 25);
|
||||
assert_eq!(regions[0].height, 16);
|
||||
assert_eq!(regions[1].width, 24);
|
||||
assert_eq!(regions[1].height, 1);
|
||||
assert_eq!(regions[0].x + regions[0].width, 35);
|
||||
assert_eq!(regions[0].height, 21);
|
||||
assert_eq!(regions[1].width, 34);
|
||||
assert_eq!(regions[1].height, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_scene_requests_full_invalidation_for_all_layers() {
|
||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
|
||||
let requests = resolver.reset_scene();
|
||||
|
||||
|
||||
@@ -11,6 +11,12 @@ pub use resolver::{
|
||||
resolve_declared_program_syscalls, resolve_program_syscalls, resolve_syscall,
|
||||
};
|
||||
|
||||
/// Native metadata iteration for bounded image binding. This is not guest
|
||||
/// reflection; callers account comparisons before examining catalogue entries.
|
||||
pub fn catalogue() -> impl Iterator<Item = &'static SyscallRegistryEntry> {
|
||||
domains::all_entries()
|
||||
}
|
||||
|
||||
/// Enumeration of all System Calls (Syscalls) available in the Prometeu environment.
|
||||
///
|
||||
/// Syscalls are the primary mechanism for a program running in the Virtual Machine
|
||||
@@ -18,7 +24,7 @@ pub use resolver::{
|
||||
///
|
||||
/// Each Syscall has a unique 32-bit ID. The IDs are grouped by category:
|
||||
/// - **0x0xxx**: System & OS Control
|
||||
/// - **0x1xxx**: Graphics (GFX)
|
||||
/// - **0x1xxx**: Game 2D primitives (`gfx2d`) and Shell UI primitives (`gfxui`)
|
||||
/// - **0x11xx**: Frame Composer orchestration
|
||||
/// - **0x2xxx**: Reserved for legacy input syscalls (disabled for v1 VM-owned input)
|
||||
/// - **0x3xxx**: Audio (PCM & Mixing)
|
||||
@@ -29,7 +35,6 @@ pub use resolver::{
|
||||
#[repr(u32)]
|
||||
pub enum Syscall {
|
||||
SystemHasCart = 0x0001,
|
||||
SystemRunCart = 0x0002,
|
||||
GfxClear = 0x1001,
|
||||
GfxFillRect = 0x1002,
|
||||
GfxDrawLine = 0x1003,
|
||||
@@ -37,13 +42,23 @@ pub enum Syscall {
|
||||
GfxDrawDisc = 0x1005,
|
||||
GfxDrawSquare = 0x1006,
|
||||
GfxDrawText = 0x1008,
|
||||
GfxClear565 = 0x1010,
|
||||
GfxUiClear = 0x1201,
|
||||
GfxUiFillRect = 0x1202,
|
||||
GfxUiDrawLine = 0x1203,
|
||||
GfxUiDrawCircle = 0x1204,
|
||||
GfxUiDrawDisc = 0x1205,
|
||||
GfxUiDrawSquare = 0x1206,
|
||||
GfxUiDrawText = 0x1208,
|
||||
ComposerBindScene = 0x1101,
|
||||
ComposerUnbindScene = 0x1102,
|
||||
ComposerSetCamera = 0x1103,
|
||||
ComposerEmitSprite = 0x1104,
|
||||
AudioPlaySample = 0x3001,
|
||||
AudioPlay = 0x3002,
|
||||
AudioStop = 0x3003,
|
||||
AudioSetVolume = 0x3004,
|
||||
AudioSetPan = 0x3005,
|
||||
AudioSetPitch = 0x3006,
|
||||
FsOpen = 0x4001,
|
||||
FsRead = 0x4002,
|
||||
FsWrite = 0x4003,
|
||||
@@ -51,20 +66,33 @@ pub enum Syscall {
|
||||
FsListDir = 0x4005,
|
||||
FsExists = 0x4006,
|
||||
FsDelete = 0x4007,
|
||||
MemBootstrap = 0x4200,
|
||||
MemSlotCount = 0x4201,
|
||||
MemSlotStat = 0x4202,
|
||||
MemSlotRead = 0x4203,
|
||||
MemSlotWrite = 0x4204,
|
||||
MemSlotCommit = 0x4205,
|
||||
MemSlotClear = 0x4206,
|
||||
MemQuery = 0x4207,
|
||||
MemRelease = 0x4208,
|
||||
MemInfo = 0x4209,
|
||||
MemMetadata = 0x420A,
|
||||
MemPresentation = 0x420B,
|
||||
MemDiagnostic = 0x420C,
|
||||
MemPublishPresentation = 0x420D,
|
||||
LogWrite = 0x5001,
|
||||
LogWriteTag = 0x5002,
|
||||
AssetLoad = 0x6001,
|
||||
AssetStatus = 0x6002,
|
||||
AssetCommit = 0x6003,
|
||||
AssetCancel = 0x6004,
|
||||
AssetBacklogInfo = 0x6005,
|
||||
AssetBacklogPosition = 0x6006,
|
||||
AssetBacklogMove = 0x6007,
|
||||
AssetBacklogPromote = 0x6008,
|
||||
AssetBacklogDemote = 0x6009,
|
||||
AssetTargetStatus = 0x600A,
|
||||
BankInfo = 0x6101,
|
||||
BankSlotInfo = 0x6102,
|
||||
}
|
||||
|
||||
/// Canonical metadata describing a syscall using the unified slot-based ABI.
|
||||
|
||||
@@ -2,10 +2,15 @@ use super::CapFlags;
|
||||
|
||||
pub const NONE: CapFlags = 0;
|
||||
pub const SYSTEM: CapFlags = 1 << 0;
|
||||
pub const GFX: CapFlags = 1 << 1;
|
||||
pub const COMPOSER: CapFlags = 1 << 1;
|
||||
pub const AUDIO: CapFlags = 1 << 2;
|
||||
pub const FS: CapFlags = 1 << 3;
|
||||
pub const LOG: CapFlags = 1 << 4;
|
||||
pub const ASSET: CapFlags = 1 << 5;
|
||||
pub const BANK: CapFlags = 1 << 6;
|
||||
pub const ALL: CapFlags = SYSTEM | GFX | AUDIO | FS | LOG | ASSET | BANK;
|
||||
pub const GFX2D: CapFlags = 1 << 7;
|
||||
pub const GFXUI: CapFlags = 1 << 8;
|
||||
pub const MEMCARD: CapFlags = 1 << 9;
|
||||
pub const GFX: CapFlags = COMPOSER | GFX2D;
|
||||
pub const ALL: CapFlags =
|
||||
SYSTEM | COMPOSER | AUDIO | FS | LOG | ASSET | BANK | GFX2D | GFXUI | MEMCARD;
|
||||
|
||||
@@ -24,4 +24,40 @@ pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||
.caps(caps::ASSET)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::AssetBacklogInfo, "asset", "backlog_info")
|
||||
.args(0)
|
||||
.rets(7)
|
||||
.caps(caps::ASSET)
|
||||
.non_deterministic()
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::AssetBacklogPosition, "asset", "backlog_position")
|
||||
.args(1)
|
||||
.rets(4)
|
||||
.caps(caps::ASSET)
|
||||
.non_deterministic()
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::AssetBacklogMove, "asset", "backlog_move")
|
||||
.args(2)
|
||||
.rets(1)
|
||||
.caps(caps::ASSET)
|
||||
.non_deterministic()
|
||||
.cost(10),
|
||||
SyscallRegistryEntry::builder(Syscall::AssetBacklogPromote, "asset", "backlog_promote")
|
||||
.args(1)
|
||||
.rets(1)
|
||||
.caps(caps::ASSET)
|
||||
.non_deterministic()
|
||||
.cost(10),
|
||||
SyscallRegistryEntry::builder(Syscall::AssetBacklogDemote, "asset", "backlog_demote")
|
||||
.args(1)
|
||||
.rets(1)
|
||||
.caps(caps::ASSET)
|
||||
.non_deterministic()
|
||||
.cost(10),
|
||||
SyscallRegistryEntry::builder(Syscall::AssetTargetStatus, "asset", "target_status")
|
||||
.args(2)
|
||||
.rets(6)
|
||||
.caps(caps::ASSET)
|
||||
.non_deterministic()
|
||||
.cost(5),
|
||||
];
|
||||
|
||||
@@ -11,4 +11,24 @@ pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||
.rets(1)
|
||||
.caps(caps::AUDIO)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::AudioStop, "audio", "stop")
|
||||
.args(1)
|
||||
.rets(1)
|
||||
.caps(caps::AUDIO)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::AudioSetVolume, "audio", "set_volume")
|
||||
.args(2)
|
||||
.rets(1)
|
||||
.caps(caps::AUDIO)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::AudioSetPan, "audio", "set_pan")
|
||||
.args(2)
|
||||
.rets(1)
|
||||
.caps(caps::AUDIO)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::AudioSetPitch, "audio", "set_pitch")
|
||||
.args(2)
|
||||
.rets(1)
|
||||
.caps(caps::AUDIO)
|
||||
.cost(5),
|
||||
];
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
||||
|
||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||
SyscallRegistryEntry::builder(Syscall::BankInfo, "bank", "info")
|
||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] =
|
||||
&[SyscallRegistryEntry::builder(Syscall::BankInfo, "bank", "info")
|
||||
.args(1)
|
||||
.rets(1)
|
||||
.caps(caps::BANK),
|
||||
SyscallRegistryEntry::builder(Syscall::BankSlotInfo, "bank", "slot_info")
|
||||
.args(2)
|
||||
.rets(1)
|
||||
.caps(caps::BANK),
|
||||
];
|
||||
.rets(2)
|
||||
.caps(caps::BANK)];
|
||||
|
||||
@@ -4,19 +4,19 @@ pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||
SyscallRegistryEntry::builder(Syscall::ComposerBindScene, "composer", "bind_scene")
|
||||
.args(1)
|
||||
.rets(1)
|
||||
.caps(caps::GFX)
|
||||
.caps(caps::COMPOSER)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::ComposerUnbindScene, "composer", "unbind_scene")
|
||||
.rets(1)
|
||||
.caps(caps::GFX)
|
||||
.caps(caps::COMPOSER)
|
||||
.cost(2),
|
||||
SyscallRegistryEntry::builder(Syscall::ComposerSetCamera, "composer", "set_camera")
|
||||
.args(2)
|
||||
.caps(caps::GFX)
|
||||
.caps(caps::COMPOSER)
|
||||
.cost(2),
|
||||
SyscallRegistryEntry::builder(Syscall::ComposerEmitSprite, "composer", "emit_sprite")
|
||||
.args(9)
|
||||
.rets(1)
|
||||
.caps(caps::GFX)
|
||||
.caps(caps::COMPOSER)
|
||||
.cost(5),
|
||||
];
|
||||
|
||||
@@ -32,37 +32,4 @@ pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||
.caps(caps::FS)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemSlotCount, "mem", "slot_count")
|
||||
.rets(2)
|
||||
.caps(caps::FS),
|
||||
SyscallRegistryEntry::builder(Syscall::MemSlotStat, "mem", "slot_stat")
|
||||
.args(1)
|
||||
.rets(5)
|
||||
.caps(caps::FS)
|
||||
.non_deterministic()
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::MemSlotRead, "mem", "slot_read")
|
||||
.args(3)
|
||||
.rets(3)
|
||||
.caps(caps::FS)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemSlotWrite, "mem", "slot_write")
|
||||
.args(3)
|
||||
.rets(2)
|
||||
.caps(caps::FS)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemSlotCommit, "mem", "slot_commit")
|
||||
.args(1)
|
||||
.rets(1)
|
||||
.caps(caps::FS)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemSlotClear, "mem", "slot_clear")
|
||||
.args(1)
|
||||
.rets(1)
|
||||
.caps(caps::FS)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
];
|
||||
|
||||
@@ -1,36 +1,32 @@
|
||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
||||
|
||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||
SyscallRegistryEntry::builder(Syscall::GfxClear, "gfx", "clear")
|
||||
SyscallRegistryEntry::builder(Syscall::GfxClear, "gfx2d", "clear")
|
||||
.args(1)
|
||||
.caps(caps::GFX)
|
||||
.caps(caps::GFX2D)
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxFillRect, "gfx", "fill_rect")
|
||||
SyscallRegistryEntry::builder(Syscall::GfxFillRect, "gfx2d", "fill_rect")
|
||||
.args(5)
|
||||
.caps(caps::GFX)
|
||||
.caps(caps::GFX2D)
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxDrawLine, "gfx", "draw_line")
|
||||
SyscallRegistryEntry::builder(Syscall::GfxDrawLine, "gfx2d", "draw_line")
|
||||
.args(5)
|
||||
.caps(caps::GFX)
|
||||
.caps(caps::GFX2D)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxDrawCircle, "gfx", "draw_circle")
|
||||
SyscallRegistryEntry::builder(Syscall::GfxDrawCircle, "gfx2d", "draw_circle")
|
||||
.args(4)
|
||||
.caps(caps::GFX)
|
||||
.caps(caps::GFX2D)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxDrawDisc, "gfx", "draw_disc")
|
||||
SyscallRegistryEntry::builder(Syscall::GfxDrawDisc, "gfx2d", "draw_disc")
|
||||
.args(5)
|
||||
.caps(caps::GFX)
|
||||
.caps(caps::GFX2D)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxDrawSquare, "gfx", "draw_square")
|
||||
SyscallRegistryEntry::builder(Syscall::GfxDrawSquare, "gfx2d", "draw_square")
|
||||
.args(6)
|
||||
.caps(caps::GFX)
|
||||
.caps(caps::GFX2D)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxDrawText, "gfx", "draw_text")
|
||||
SyscallRegistryEntry::builder(Syscall::GfxDrawText, "gfx2d", "draw_text")
|
||||
.args(4)
|
||||
.caps(caps::GFX)
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxClear565, "gfx", "clear_565")
|
||||
.args(1)
|
||||
.caps(caps::GFX)
|
||||
.caps(caps::GFX2D)
|
||||
.cost(20),
|
||||
];
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
||||
|
||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||
SyscallRegistryEntry::builder(Syscall::GfxUiClear, "gfxui", "clear")
|
||||
.args(1)
|
||||
.caps(caps::GFXUI)
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxUiFillRect, "gfxui", "fill_rect")
|
||||
.args(5)
|
||||
.caps(caps::GFXUI)
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxUiDrawLine, "gfxui", "draw_line")
|
||||
.args(5)
|
||||
.caps(caps::GFXUI)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxUiDrawCircle, "gfxui", "draw_circle")
|
||||
.args(4)
|
||||
.caps(caps::GFXUI)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxUiDrawDisc, "gfxui", "draw_disc")
|
||||
.args(5)
|
||||
.caps(caps::GFXUI)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxUiDrawSquare, "gfxui", "draw_square")
|
||||
.args(6)
|
||||
.caps(caps::GFXUI)
|
||||
.cost(5),
|
||||
SyscallRegistryEntry::builder(Syscall::GfxUiDrawText, "gfxui", "draw_text")
|
||||
.args(4)
|
||||
.caps(caps::GFXUI)
|
||||
.cost(20),
|
||||
];
|
||||
@@ -0,0 +1,87 @@
|
||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||
SyscallRegistryEntry::builder(Syscall::MemBootstrap, "mem", "bootstrap")
|
||||
.args(0)
|
||||
.rets(1)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemSlotCount, "mem", "slot_count")
|
||||
.args(1)
|
||||
.rets(2)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemSlotStat, "mem", "slot_stat")
|
||||
.args(2)
|
||||
.rets(7)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemSlotRead, "mem", "slot_read")
|
||||
.args(6)
|
||||
.rets(2)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemSlotWrite, "mem", "slot_write")
|
||||
.args(6)
|
||||
.rets(2)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemSlotCommit, "mem", "slot_commit")
|
||||
.args(2)
|
||||
.rets(2)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemSlotClear, "mem", "slot_clear")
|
||||
.args(2)
|
||||
.rets(1)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemQuery, "mem", "query")
|
||||
.args(2)
|
||||
.rets(3)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemRelease, "mem", "release")
|
||||
.args(2)
|
||||
.rets(1)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemInfo, "mem", "info")
|
||||
.args(1)
|
||||
.rets(6)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemMetadata, "mem", "metadata")
|
||||
.args(1)
|
||||
.rets(4)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemPresentation, "mem", "presentation")
|
||||
.args(8)
|
||||
.rets(1)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemDiagnostic, "mem", "diagnostic")
|
||||
.args(2)
|
||||
.rets(1)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
SyscallRegistryEntry::builder(Syscall::MemPublishPresentation, "mem", "publish_presentation")
|
||||
.args(1)
|
||||
.rets(2)
|
||||
.caps(caps::MEMCARD)
|
||||
.non_deterministic()
|
||||
.cost(20),
|
||||
];
|
||||
@@ -4,6 +4,7 @@ mod bank;
|
||||
mod composer;
|
||||
mod fs;
|
||||
mod gfx;
|
||||
mod gfxui;
|
||||
mod log;
|
||||
mod system;
|
||||
|
||||
@@ -13,10 +14,14 @@ pub(crate) fn all_entries() -> impl Iterator<Item = &'static SyscallRegistryEntr
|
||||
system::ENTRIES
|
||||
.iter()
|
||||
.chain(gfx::ENTRIES.iter())
|
||||
.chain(gfxui::ENTRIES.iter())
|
||||
.chain(composer::ENTRIES.iter())
|
||||
.chain(audio::ENTRIES.iter())
|
||||
.chain(fs::ENTRIES.iter())
|
||||
.chain(memcard::ENTRIES.iter())
|
||||
.chain(log::ENTRIES.iter())
|
||||
.chain(asset::ENTRIES.iter())
|
||||
.chain(bank::ENTRIES.iter())
|
||||
}
|
||||
|
||||
mod memcard;
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
||||
|
||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||
SyscallRegistryEntry::builder(Syscall::SystemHasCart, "system", "has_cart")
|
||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] =
|
||||
&[SyscallRegistryEntry::builder(Syscall::SystemHasCart, "system", "has_cart")
|
||||
.rets(1)
|
||||
.caps(caps::SYSTEM),
|
||||
SyscallRegistryEntry::builder(Syscall::SystemRunCart, "system", "run_cart")
|
||||
.caps(caps::SYSTEM)
|
||||
.non_deterministic()
|
||||
.cost(50),
|
||||
];
|
||||
.caps(caps::SYSTEM)];
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user