Compare commits
724
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22769aa438
|
||
|
|
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
|
||
|
|
509b669db5 | ||
|
|
73cf96ed6c
|
||
|
|
76254928e6
|
||
|
|
1c74631a5e
|
||
|
|
aaed1e95dd
|
||
|
|
2865cb3803
|
||
|
|
4f52a65169
|
||
|
|
b0b8bb9028
|
||
|
|
4a5210f347
|
||
|
|
3fef407efc
|
||
|
|
cc700c6cf8
|
||
|
|
dd90ff812c
|
||
|
|
240fe65da7
|
||
|
|
f4260d0cf4
|
||
|
|
a1bd60671b
|
||
|
|
5ef43045bc
|
||
|
|
3931e86b41
|
||
|
|
5a0476e8b0
|
||
|
|
ed05f337ce
|
||
|
|
94c80e61ba
|
||
|
|
98d2d81882
|
||
|
|
d5d63d79c0
|
||
|
|
1ad7554762
|
||
|
|
738976352c | ||
|
|
d5ec6e77b9
|
||
|
|
4a5763523b
|
||
|
|
f7c31592bb
|
||
|
|
2d2c320638
|
||
|
|
d9e680082d
|
||
|
|
0723057038
|
||
|
|
5c1e6dac83
|
||
|
|
e1afc164ae
|
||
|
|
70cde0d975
|
||
|
|
8f98aee64e | ||
|
|
9b0a83f96c
|
||
|
|
7a696623b5
|
||
|
|
5436c54e6d
|
||
|
|
4cdfaefda7
|
||
|
|
58a5f9a3a6
|
||
|
|
b8d33c9e02
|
||
|
|
47ab664280
|
||
|
|
c65362c186 | ||
|
|
f5580ae0ce
|
||
|
|
e672e4d6b6
|
||
|
|
698a076632
|
||
|
|
63892dcfb9
|
||
|
|
5e80ea46b8
|
||
|
|
035e9d5676 | ||
|
|
c4aca95635 | ||
|
|
3453494341 | ||
|
|
214a189a5f
|
||
|
|
201226b892
|
||
|
|
e6978397ab
|
||
|
|
6b08633798
|
||
|
|
7e3e8c81f5
|
||
|
|
21030f5c08
|
||
|
|
a27ad45f91
|
||
|
|
c7e4d7398f
|
||
|
|
6fc0bf129c
|
||
|
|
0ff4909079
|
||
|
|
67e7acf73b
|
||
|
|
fab5ed2c46
|
||
|
|
99f320fdea
|
||
|
|
d4b8229981
|
||
|
|
7b7a633ef4
|
||
|
|
ecc1a864bb
|
||
|
|
a024e199fb
|
||
|
|
f652e8d5d3
|
||
|
|
2b9efa8417
|
||
|
|
619ac2c975
|
||
|
|
b532a05612
|
||
|
|
aa9987b46b
|
||
|
|
147f97c5c4
|
||
|
|
03494c8cd7
|
||
|
|
d5eb5cf033
|
||
|
|
17878e481c
|
||
|
|
d576f7ddbd
|
||
|
|
d7c970a3e2
|
||
|
|
f3f689fbef
|
||
|
|
0553b3927e
|
||
|
|
f4540fc803
|
||
|
|
4b31248dff
|
||
|
|
077378a3b5
|
||
|
|
d3321c4400
|
||
|
|
9b65005ffb
|
||
|
|
4737e65f5a
|
||
|
|
683d291afd
|
||
|
|
9c5c1df394
|
||
|
|
76fd0943d3
|
||
|
|
52aed9d0ea
|
||
|
|
8152269d5b
|
||
|
|
9ac48379ed
|
||
|
|
d5f38d778d
|
||
|
|
0c32457a10
|
||
|
|
9cb0e77b01
|
||
|
|
fd5a5cd22c
|
||
|
|
5df15d0c6d
|
||
|
|
015c30dd99
|
||
|
|
462583fac2
|
||
|
|
27d26b328b
|
||
|
|
f714db77fc
|
||
|
|
6a894b987d
|
||
|
|
7a81712005
|
||
|
|
db55207fb9
|
||
|
|
91f67e3aaf
|
||
|
|
70ffadab6c
|
||
|
|
c8b3b6afcc
|
||
|
|
998252aa25
|
||
|
|
fe6931d420
|
||
|
|
b241db7011
|
||
|
|
14acd47421
|
||
|
|
f8cb42daf2
|
||
|
|
8883b8a21f
|
||
|
|
bcf30f8c4a
|
||
|
|
d8422d26af
|
||
|
|
38d551fe01
|
||
|
|
9f402de894
|
||
|
|
1394f8e241
|
||
|
|
833798e143
|
||
|
|
6ffaf8fd08
|
||
|
|
75edde476b
|
||
|
|
a99f11027c
|
||
|
|
3041fdf46b
|
||
|
|
f12ac453a3
|
||
|
|
10dfc7bf15
|
||
|
|
1bd921979f
|
||
|
|
04b1f5a7aa
|
||
|
|
68b87254a7
|
||
|
|
d588502b57
|
||
|
|
60e0875147
|
||
|
|
af8f4304b9
|
||
|
|
9a60754e5a
|
||
|
|
ea12bd3fd5
|
||
|
|
a6ad14fcb2
|
||
|
|
f6751a03a4
|
||
|
|
1b0e290e1d
|
||
|
|
f77b9f762f
|
||
|
|
01c50f0b20
|
||
|
|
24c81d27a9
|
||
|
|
a75df486ce
|
||
|
|
c0ed9ba8e0
|
||
|
|
af2e8ba51e
|
||
|
|
4fb872dde5
|
||
|
|
5ec270dd43
|
||
|
|
384587bb04
|
||
|
|
ed5d6abec9
|
||
|
|
818e27eb31
|
||
|
|
8545c67939
|
||
|
|
eb835bafee
|
||
|
|
f126a64099
|
||
|
|
39d1214f03
|
||
|
|
c6e3199821
|
||
|
|
5c53b92627
|
||
|
|
8ce12d9a71
|
||
|
|
24e7a3b083
|
||
|
|
df9b248c98
|
||
|
|
96062bf1d0
|
||
|
|
2a79f641dd
|
||
|
|
d5ef8a2003
|
||
|
|
cfdca93160
|
||
|
|
a04f462939
|
||
|
|
98b899c380
|
||
|
|
ca40a7b939
|
||
|
|
52502830a3
|
||
|
|
9d9d2404a1
|
||
|
|
af755a1241
|
||
|
|
a199857280
|
||
|
|
1a782cbb5c
|
||
|
|
6950f2bef0
|
||
|
|
78ed7a8253
|
||
|
|
196d54b366
|
||
|
|
8d1e0a57d6
|
||
|
|
bd507aeaa5
|
||
|
|
25d4f3eacb
|
||
|
|
c07a1cc230
|
||
|
|
f6d33cd8e5
|
||
|
|
49c9b018bc
|
||
|
|
b48386b154
|
||
|
|
d123919b73
|
||
|
|
24d6962c0f
|
||
|
|
3f50bdaa70
|
||
|
|
b7e149a1ab
|
||
|
|
123d39331e
|
||
|
|
70c5e08d66
|
||
|
|
49025b1055
|
||
|
|
3fba722b50
|
||
|
|
e894ea1a8c
|
||
|
|
5095fc1a76
|
||
|
|
29736e9577
|
||
|
|
35f5b8fa86
|
||
|
|
860f0db31c
|
||
|
|
c7382763cd
|
||
|
|
fa651af3c3
|
||
|
|
b57e186490
|
||
|
|
155be962b7
|
||
|
|
b9ac2a98ee
|
||
|
|
a10055f61b
|
||
|
|
a7ddbcabb2
|
||
|
|
b9723cfc40
|
||
|
|
a7a40bd9c1
|
||
|
|
cb7f6c8bb4
|
||
|
|
a5b332a362
|
||
|
|
de3ccabd62
|
||
|
|
7ba1d71b69
|
||
|
|
546a4f219b
|
||
|
|
929dcde0c6
|
||
|
|
d24533cc62
|
||
|
|
7feeabc1b6
|
||
|
|
3297980055
|
||
|
|
966f0f9a8f
|
||
|
|
13f025e448
|
||
|
|
46146993aa
|
||
|
|
650f1e0716
|
||
|
|
3d4d1dc45d
|
||
|
|
dc7da102c8
|
||
|
|
39a9001f54
|
||
|
|
79e55303bd
|
||
|
|
8d80685654
|
||
|
|
790629fee7
|
||
|
|
8b744a120e
|
||
|
|
a5daebd849
|
||
|
|
6d875784ea
|
||
|
|
d929f68dd7
|
||
|
|
7a65fbe02c
|
||
|
|
6423c6b4bc
|
||
|
|
29056ce0ad
|
||
|
|
73dc0c4cb2
|
||
|
|
c7786fa8b0
|
||
|
|
e2a970e69c
|
||
|
|
63631578e5
|
||
|
|
f75c61004c
|
||
|
|
90ecd77031
|
||
|
|
4f73f46ba9
|
||
|
|
f28d7515b8
|
||
|
|
d2bf437f53
|
||
|
|
2638b0fc88
|
||
|
|
463f72a123
|
||
|
|
bddd588464
|
||
|
|
1135514508
|
||
|
|
a115281d88
|
||
|
|
ab2ebba286
|
||
|
|
f994a566d8
|
||
|
|
a4cc1487c4
|
||
|
|
2ba8507284
|
||
|
|
df8c0db6eb
|
||
|
|
6a4f7ea773
|
||
|
|
f5d259ba2a
|
||
|
|
c80260e780
|
||
|
|
7eb2e5d75b
|
||
|
|
07e9871b13
|
||
|
|
d511ae4fe9
|
||
|
|
61cd7611bb
|
||
|
|
bfcdc5538d
|
||
|
|
99f024eaa9
|
||
|
|
1a8ec25c07
|
||
|
|
c9b9f18b32
|
||
|
|
6eda2d21ac
|
||
|
|
cf94ecda84
|
||
|
|
5b4b1ea58d
|
||
|
|
5941cd7248
|
||
|
|
c56256f63e
|
||
|
|
c6411fd53c
|
||
|
|
e486c1980e
|
||
|
|
2592b1a1d1
|
||
|
|
0a087d51fb
|
||
|
|
937e0d70b6
|
||
|
|
c68b300d5e
|
||
|
|
2fb6fb2cda
|
||
|
|
55e97f4407
|
||
|
|
d994005f8b
|
||
|
|
5cf77359fb
|
||
|
|
06b49cf433
|
||
|
|
912b9b0075
|
||
|
|
66f34eeb58
|
||
|
|
c9f844ab61
|
||
|
|
c12c1f7939
|
||
|
|
0e76368cba
|
||
|
|
07f986df5b
|
||
|
|
adb4dad14b
|
||
|
|
aea8f3bc08
|
||
|
|
836b280998
|
||
|
|
8c02f505d0
|
||
|
|
acd74d57ff
|
||
|
|
e6cfef9a77
|
||
|
|
4cee158206
|
||
|
|
00ad4730c8
|
||
|
|
9a62b7b643
|
||
|
|
a7669c9a8f
|
||
|
|
89163807b4
|
||
|
|
6cbcddfd99
|
||
|
|
bb1372aa65
|
||
|
|
737780d7d5
|
||
|
|
5fff614708
|
||
|
|
783a675abc
|
||
|
|
010dbc96ff
|
||
|
|
a1053eefd5
|
||
|
|
18c9ebceae
|
||
|
|
728f057067
|
||
|
|
5629f76f74
|
||
|
|
4c97430ea4
|
||
|
|
4e66387f4e
|
||
|
|
6b372b2613
|
||
|
|
97c6ccb6f2
|
||
|
|
92df0ae074
|
||
|
|
eb3156dd8c
|
||
|
|
d6bbef06a5
|
||
|
|
e52a426f02
|
||
|
|
0b97de6d2e
|
||
|
|
ba2344e324
|
||
|
|
0cacf4fed8
|
||
|
|
60384bf720
|
||
|
|
567ab21709
|
||
|
|
90095bb21e
|
||
|
|
aab53d30be
|
||
|
|
c5c1f68f7c
|
||
|
|
bbe7ea4dbe
|
||
|
|
747ac81da2
|
||
|
|
f9120e740b
|
||
|
|
05838d10b0
|
||
|
|
c795eeb3dc
|
||
|
|
62e68bf7ff
|
||
|
|
5b9524f401
|
||
|
|
06c8e95cc9
|
||
|
|
51ecdeeb5c
|
||
|
|
39eb8b2827
|
||
|
|
5caa3e112e
|
||
|
|
31080ea40d
|
||
|
|
28df72417b
|
||
|
|
0b2a97aa88
|
||
|
|
524b47fd61
|
||
|
|
47c082adb1
|
||
|
|
b134de99e7
|
||
|
|
c8a0444d8e
|
||
|
|
78485b194c
|
||
|
|
24ac158419
|
||
|
|
4a6f5940db
|
||
|
|
0852b4332b
|
||
|
|
c7e9acbdc2
|
||
|
|
075fe8526c
|
||
|
|
9ba2aab1a5
|
||
|
|
4e633163ce
|
||
|
|
887564bb3a
|
||
|
|
178e11d786
|
||
|
|
1544c511b7
|
||
|
|
dd8ded9671
|
||
|
|
8c76f952db
|
||
|
|
6695b3bc5f
|
||
|
|
93c13f93aa
|
||
|
|
55f820a76b
|
||
|
|
afcf38eb2a
|
||
|
|
91800cf95a
|
||
|
|
cd68bb0d0a
|
||
|
|
71bb007499
|
||
|
|
c0f821a8d6
|
||
|
|
57b08703e1
|
||
|
|
9b4a9add7e
|
||
|
|
e0309038b9
|
||
|
|
aa942c582b
|
||
|
|
c66c4d9213
|
||
|
|
d3d12ac68d
|
||
|
|
21863fa357
|
||
|
|
9b25757b63
|
||
|
|
69eaf199b3
|
||
|
|
1533e2d600
|
||
|
|
314f193804
|
||
|
|
28ec041381
|
||
|
|
d64a6b8bb5
|
||
|
|
6af011db67
|
||
|
|
e198971379
|
||
|
|
8f45b04848
|
||
|
|
b3a3c95f86
|
||
|
|
266c47c9ac
|
||
|
|
38f07c0b26
|
||
|
|
8fb0cb91e6
|
||
|
|
fc48c86bbe
|
||
|
|
0740268257
|
||
|
|
e3c623aea5
|
||
|
|
3fd2574be7
|
||
|
|
bcc5930f65
|
||
|
|
43e366bcd5
|
||
|
|
85a5f2d63f
|
||
|
|
d1c87ef6e7
|
||
|
|
b51bd71352
|
||
|
|
4a1f51fe84
|
||
|
|
aef5b89cdb
|
||
|
|
f319d0dbaf
|
||
|
|
a9d06aaf86
|
||
|
|
98c9094eca
|
||
|
|
13da077d92
|
||
|
|
79a0768d8e
|
||
|
|
e0fccbae6b
|
||
|
|
5fce506365
|
||
|
|
84ab6bd40c
|
||
|
|
f7077ffec0
|
||
|
|
fea5e09f82
|
||
|
|
858552f55f
|
||
|
|
48c6c6d7b0
|
||
|
|
a9345244e3
|
||
|
|
490b1243d8
|
||
|
|
6c1366ace9
|
||
|
|
da63ac1886
|
||
|
|
8e65ff65c5
|
||
|
|
c718d36fe2
|
||
|
|
13169698cf
|
||
|
|
072b6133d5
|
||
|
|
6e25cf5fac
|
||
|
|
78e12a065e
|
||
|
|
641e7af6fb
|
||
|
|
e6133baedf
|
||
|
|
cdfb1188ee
|
||
|
|
4ccd38580f
|
||
|
|
ba673b4547
|
||
|
|
6782c54354
|
@@ -0,0 +1,39 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ main, master ]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
components: rustfmt, clippy, llvm-tools-preview
|
||||||
|
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
|
||||||
|
- name: Discard reports from previous runs
|
||||||
|
run: rm -rf target/quality-gate target/llvm-cov
|
||||||
|
|
||||||
|
- name: Provision quality-gate tools and native dependencies
|
||||||
|
run: bash scripts/provision-quality-gate.sh
|
||||||
|
|
||||||
|
- 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/quality-gate/**
|
||||||
|
target/llvm-cov/**
|
||||||
|
if-no-files-found: warn
|
||||||
+15
-1
@@ -1,4 +1,5 @@
|
|||||||
# ===== Rust / Cargo =====
|
# ===== Rust / Cargo =====
|
||||||
|
.cargo/config.toml
|
||||||
/target/
|
/target/
|
||||||
**/target/
|
**/target/
|
||||||
|
|
||||||
@@ -10,6 +11,7 @@
|
|||||||
# RustRover / IntelliJ
|
# RustRover / IntelliJ
|
||||||
.idea/
|
.idea/
|
||||||
*.iml
|
*.iml
|
||||||
|
.junie
|
||||||
|
|
||||||
# VS Code
|
# VS Code
|
||||||
.vscode/
|
.vscode/
|
||||||
@@ -55,4 +57,16 @@ dist-staging
|
|||||||
dist-staging/**
|
dist-staging/**
|
||||||
|
|
||||||
temp
|
temp
|
||||||
temp/**
|
temp/**
|
||||||
|
|
||||||
|
**/build/**
|
||||||
|
**/node_modules/**
|
||||||
|
|
||||||
|
AGENTS.md
|
||||||
|
|
||||||
|
.python-version
|
||||||
|
.venv
|
||||||
|
|
||||||
|
discussion/*
|
||||||
|
!discussion/lessons/
|
||||||
|
!discussion/lessons/**
|
||||||
|
|||||||
Generated
+1270
-726
File diff suppressed because it is too large
Load Diff
+14
-5
@@ -1,10 +1,19 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"crates/prometeu-core",
|
"crates/console/prometeu-bytecode",
|
||||||
"crates/prometeu-runtime-desktop",
|
"crates/console/prometeu-drivers",
|
||||||
"crates/prometeu",
|
"crates/console/prometeu-firmware",
|
||||||
"crates/prometeu-bytecode",
|
"crates/console/prometeu-hal",
|
||||||
"crates/prometeu-compiler",
|
"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",
|
||||||
|
"crates/dev/prometeu-quality-checks",
|
||||||
]
|
]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
.PHONY: fmt fmt-check clippy test-local 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 test-quality-gate cobertura
|
||||||
|
|
||||||
|
fmt:
|
||||||
|
cargo fmt --all
|
||||||
|
|
||||||
|
fmt-check:
|
||||||
|
cargo fmt --all -- --check
|
||||||
|
|
||||||
|
clippy:
|
||||||
|
cargo clippy --workspace --all-targets --all-features -- -D warnings
|
||||||
|
|
||||||
|
test-local:
|
||||||
|
cargo test --workspace --all-targets --all-features --no-fail-fast
|
||||||
|
|
||||||
|
test-debugger-socket:
|
||||||
|
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
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
coverage-json:
|
||||||
|
cargo llvm-cov report --json --summary-only --output-path target/llvm-cov/summary.json
|
||||||
|
|
||||||
|
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-local test-debugger-socket
|
||||||
|
# Keep the step list here: CI providers consume the repository contract.
|
||||||
|
# The runner executes each step serially even if the caller supplies make -j.
|
||||||
|
CI_DOMAIN_STEPS = clean fmt-check clippy test-quality-gate test-local test-debugger-socket coverage coverage-report-json coverage-xml coverage-json coverage-domain-audit coverage-domain-gate
|
||||||
|
|
||||||
|
ci: ci-domains
|
||||||
|
ci-domains:
|
||||||
|
python3 scripts/run-quality-gate.py $(CI_DOMAIN_STEPS)
|
||||||
|
|
||||||
|
test-quality-gate:
|
||||||
|
python3 -B -m unittest discover -s scripts/tests -p 'test_quality_gate.py'
|
||||||
|
cobertura: coverage-xml coverage-json
|
||||||
@@ -1,84 +1,185 @@
|
|||||||
# PROMETEU
|
# PROMETEU Runtime
|
||||||
|
|
||||||
PROMETEU is an **educational and experimental 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 discussion artifacts.
|
||||||
|
|
||||||
> PROMETEU is a simple, explicit, and educational virtual machine.
|
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;
|
||||||
|
- discussion workflow and lessons learned.
|
||||||
|
|
||||||
## 🎯 Project Goals
|
## What This Repository Contains
|
||||||
|
|
||||||
- **Simulate simple "logical hardware"**: Create a low entry barrier for understanding how computers work.
|
- `crates/console/`: core machine/runtime crates such as `prometeu-vm`, `prometeu-system`, `prometeu-hal`, `prometeu-drivers`, and `prometeu-firmware`
|
||||||
- **Deterministic Loop**: Ensure the same code produces the same result on any platform.
|
- `crates/host/`: host-side execution surfaces, currently including `prometeu-host-desktop-winit`
|
||||||
- **Total Portability**: The core does not depend on an operating system, allowing it to run from modern computers to dedicated hardware.
|
- `crates/tools/`: user-facing and support binaries such as `prometeu` and `pbxgen-stress`
|
||||||
- **First-Class Tools**: Offer deep debugging and inspection as a central part of the experience.
|
- `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/`: agendas, decisions, plans, and lessons for architectural work
|
||||||
|
- `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.
|
- [Machine specs](docs/specs/runtime/README.md): authoritative contract for the PROMETEU machine, peripherals, firmware, cartridge format, timing, and host ABI
|
||||||
- **No implicit heuristics**: the system doesn't "guess intentions".
|
- [VM architecture](docs/vm-arch/ARCHITECTURE.md): authoritative internal architecture for VM/runtime invariants
|
||||||
- **Deterministic**: same input → same result.
|
- [ISA reference](docs/vm-arch/ISA_CORE.md): bytecode-level instruction set authority
|
||||||
- **Hardware-first**: APIs model peripherals, not modern frameworks.
|
- [Discussion workflow](discussion/index.ndjson): architectural agenda, decision, and execution traceability
|
||||||
- **Portable by definition**: if it doesn't work on all platforms, it doesn't exist.
|
|
||||||
|
|
||||||
---
|
## Workspace Layout
|
||||||
|
|
||||||
## 📦 Monorepo Structure
|
This repository is a Rust workspace rooted at [Cargo.toml](Cargo.toml) with members in:
|
||||||
|
|
||||||
This repository is organized as a Rust workspace and contains several components:
|
- `crates/console`
|
||||||
|
- `crates/host`
|
||||||
|
- `crates/tools`
|
||||||
|
- `crates/dev`
|
||||||
|
|
||||||
- **[crates/](./crates)**: Software implementation in Rust.
|
The main user-facing dispatcher binary is `prometeu`, built from `crates/tools/prometeu-cli`.
|
||||||
- **[prometeu](./crates/prometeu)**: Unified command-line interface (CLI).
|
The same package also builds `prometeu-runtime`, which embeds the current desktop host runtime.
|
||||||
- **[prometeu-core](./crates/prometeu-core)**: The logical core, VM, and internal OS.
|
|
||||||
- **[prometeu-runtime-desktop](crates/prometeu-runtime-desktop)**: 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.
|
|
||||||
|
|
||||||
---
|
Current CLI surface:
|
||||||
|
|
||||||
## 🛠️ Requirements
|
- `prometeu run <cart>`
|
||||||
|
- `prometeu debug <cart> --port <port>`
|
||||||
|
|
||||||
- **Rust**: Version defined in `rust-toolchain.toml`.
|
The dispatcher forwards runtime execution to `prometeu-runtime`.
|
||||||
- **Installation**: Use [rustup](https://rustup.rs/) to install the required toolchain.
|
For lower-level local runs, `prometeu-runtime` also accepts:
|
||||||
|
|
||||||
---
|
- `--run <cart>`
|
||||||
|
- `--debug <cart> --port <port>`
|
||||||
|
- `--fs-root <path>`
|
||||||
|
- `--cap <path>`
|
||||||
|
|
||||||
## ▶️ Quick Start
|
Other ecosystem commands, such as build, pack, and verification tooling, are not part of the current dispatcher surface in this workspace.
|
||||||
|
|
||||||
To compile the full project:
|
## Requirements
|
||||||
|
|
||||||
|
- Rust toolchain from [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
|
||||||
|
|
||||||
|
Build the workspace:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo build
|
cargo build
|
||||||
```
|
```
|
||||||
|
|
||||||
To run an example cartridge:
|
Inspect the CLI:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./target/debug/prometeu run test-cartridges/color-square
|
cargo run -q -p prometeu-cli --bin prometeu -- --help
|
||||||
```
|
```
|
||||||
|
|
||||||
For more details on how to use the CLI, see the **[prometeu](./crates/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
|
||||||
|
```
|
||||||
|
|
||||||
|
The five debugger socket tests bind localhost sockets and are marked ignored in Rust test metadata; both `make test` and `make ci-domains` select only `runner::tests` through `test-debugger-socket`. Physical audio and other 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`
|
||||||
|
- `target/quality-gate/metadata.json` and per-step logs
|
||||||
|
|
||||||
|
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,
|
||||||
|
all-target tests, the five debugger socket tests, fresh 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 discussion workflow;
|
||||||
|
- 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,17 +0,0 @@
|
|||||||
00000000 Call U32(18) U32(0)
|
|
||||||
0000000A FrameSync
|
|
||||||
0000000C Jmp U32(0)
|
|
||||||
00000012 PushI32 U32(1) ; test_supported.ts:2
|
|
||||||
00000018 SetLocal U32(0) ; test_supported.ts:2
|
|
||||||
0000001E GetLocal U32(0) ; test_supported.ts:3
|
|
||||||
00000024 PushI32 U32(10) ; test_supported.ts:3
|
|
||||||
0000002A Lt ; test_supported.ts:3
|
|
||||||
0000002C JmpIfFalse U32(80) ; test_supported.ts:3
|
|
||||||
00000032 GetLocal U32(0) ; test_supported.ts:4
|
|
||||||
00000038 PushI32 U32(1) ; test_supported.ts:4
|
|
||||||
0000003E Add ; test_supported.ts:4
|
|
||||||
00000040 Dup ; test_supported.ts:4
|
|
||||||
00000042 SetLocal U32(0) ; test_supported.ts:4
|
|
||||||
00000048 Pop ; test_supported.ts:4
|
|
||||||
0000004A Jmp U32(80)
|
|
||||||
00000050 Ret
|
|
||||||
Binary file not shown.
@@ -1,74 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"pc": 18,
|
|
||||||
"file": "test_supported.ts",
|
|
||||||
"line": 2,
|
|
||||||
"col": 13
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"pc": 24,
|
|
||||||
"file": "test_supported.ts",
|
|
||||||
"line": 2,
|
|
||||||
"col": 9
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"pc": 30,
|
|
||||||
"file": "test_supported.ts",
|
|
||||||
"line": 3,
|
|
||||||
"col": 9
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"pc": 36,
|
|
||||||
"file": "test_supported.ts",
|
|
||||||
"line": 3,
|
|
||||||
"col": 13
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"pc": 42,
|
|
||||||
"file": "test_supported.ts",
|
|
||||||
"line": 3,
|
|
||||||
"col": 9
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"pc": 44,
|
|
||||||
"file": "test_supported.ts",
|
|
||||||
"line": 3,
|
|
||||||
"col": 5
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"pc": 50,
|
|
||||||
"file": "test_supported.ts",
|
|
||||||
"line": 4,
|
|
||||||
"col": 13
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"pc": 56,
|
|
||||||
"file": "test_supported.ts",
|
|
||||||
"line": 4,
|
|
||||||
"col": 17
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"pc": 62,
|
|
||||||
"file": "test_supported.ts",
|
|
||||||
"line": 4,
|
|
||||||
"col": 13
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"pc": 64,
|
|
||||||
"file": "test_supported.ts",
|
|
||||||
"line": 4,
|
|
||||||
"col": 9
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"pc": 66,
|
|
||||||
"file": "test_supported.ts",
|
|
||||||
"line": 4,
|
|
||||||
"col": 9
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"pc": 72,
|
|
||||||
"file": "test_supported.ts",
|
|
||||||
"line": 4,
|
|
||||||
"col": 9
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@@ -6,4 +6,4 @@ license.workspace = true
|
|||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# No dependencies for now
|
serde = { version = "1.0", features = ["derive", "rc"] }
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
//! This module defines the Application Binary Interface (ABI) of the Prometeu Virtual Machine.
|
||||||
|
//! It specifies how instructions are encoded in bytes and how they interact with memory.
|
||||||
|
|
||||||
|
/// Attempted to execute an unknown or invalid opcode.
|
||||||
|
pub const TRAP_ILLEGAL_INSTRUCTION: u32 = 0x0000_0001;
|
||||||
|
/// Program explicitly requested termination via the TRAP opcode.
|
||||||
|
pub const TRAP_EXPLICIT: u32 = 0x0000_0002;
|
||||||
|
/// Out-of-bounds access (e.g., stack/heap/local index out of range).
|
||||||
|
pub const TRAP_OOB: u32 = 0x0000_0003;
|
||||||
|
/// Type mismatch for the attempted operation (e.g., wrong operand type or syscall argument type).
|
||||||
|
pub const TRAP_TYPE: u32 = 0x0000_0004;
|
||||||
|
/// The syscall ID provided is not recognized by the system.
|
||||||
|
pub const TRAP_INVALID_SYSCALL: u32 = 0x0000_0007;
|
||||||
|
/// Not enough values on the operand stack for the requested operation/syscall.
|
||||||
|
pub const TRAP_STACK_UNDERFLOW: u32 = 0x0000_0008;
|
||||||
|
/// Attempted to access a local slot that is out of bounds for the current frame.
|
||||||
|
pub const TRAP_INVALID_LOCAL: u32 = 0x0000_0009;
|
||||||
|
/// Division or modulo by zero.
|
||||||
|
pub const TRAP_DIV_ZERO: u32 = 0x0000_000A;
|
||||||
|
/// Attempted to call a function that does not exist in the function table.
|
||||||
|
pub const TRAP_INVALID_FUNC: u32 = 0x0000_000B;
|
||||||
|
/// Executed RET with an incorrect stack height (mismatch with function metadata).
|
||||||
|
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.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||||
|
pub struct SourceSpan {
|
||||||
|
pub file_id: u32,
|
||||||
|
pub start: u32,
|
||||||
|
pub end: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Detailed information about a runtime trap.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct TrapInfo {
|
||||||
|
/// The specific trap code (e.g., TRAP_OOB).
|
||||||
|
pub code: u32,
|
||||||
|
/// The numeric value of the opcode that triggered the trap.
|
||||||
|
pub opcode: u16,
|
||||||
|
/// A human-readable message explaining the trap.
|
||||||
|
pub message: String,
|
||||||
|
/// The absolute Program Counter (PC) address where the trap occurred.
|
||||||
|
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;
|
||||||
@@ -0,0 +1,394 @@
|
|||||||
|
//! Minimal deterministic assembler for the canonical disassembly format.
|
||||||
|
//!
|
||||||
|
//! This is intended primarily for roundtrip tests: `bytes -> disassemble -> assemble -> bytes`.
|
||||||
|
//! It supports all mnemonics emitted by `disassembler.rs` and their operand formats.
|
||||||
|
|
||||||
|
use crate::isa::core::CoreOpCode;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum AsmError {
|
||||||
|
EmptyLine,
|
||||||
|
UnknownMnemonic(String),
|
||||||
|
UnexpectedOperand(String),
|
||||||
|
MissingOperand(String),
|
||||||
|
InvalidOperand(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_u16(v: u16, out: &mut Vec<u8>) {
|
||||||
|
out.extend_from_slice(&v.to_le_bytes());
|
||||||
|
}
|
||||||
|
fn emit_u32(v: u32, out: &mut Vec<u8>) {
|
||||||
|
out.extend_from_slice(&v.to_le_bytes());
|
||||||
|
}
|
||||||
|
fn emit_i32(v: i32, out: &mut Vec<u8>) {
|
||||||
|
out.extend_from_slice(&v.to_le_bytes());
|
||||||
|
}
|
||||||
|
fn emit_i64(v: i64, out: &mut Vec<u8>) {
|
||||||
|
out.extend_from_slice(&v.to_le_bytes());
|
||||||
|
}
|
||||||
|
fn emit_f64_bits(bits: u64, out: &mut Vec<u8>) {
|
||||||
|
out.extend_from_slice(&bits.to_le_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_u32_any(s: &str) -> Result<u32, AsmError> {
|
||||||
|
let s = s.trim();
|
||||||
|
if let Some(rest) = s.strip_prefix("0x") {
|
||||||
|
u32::from_str_radix(rest, 16).map_err(|_| AsmError::InvalidOperand(s.into()))
|
||||||
|
} else {
|
||||||
|
s.parse::<u32>().map_err(|_| AsmError::InvalidOperand(s.into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_i32_any(s: &str) -> Result<i32, AsmError> {
|
||||||
|
s.trim().parse::<i32>().map_err(|_| AsmError::InvalidOperand(s.into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_i64_any(s: &str) -> Result<i64, AsmError> {
|
||||||
|
s.trim().parse::<i64>().map_err(|_| AsmError::InvalidOperand(s.into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_f64_bits(s: &str) -> Result<u64, AsmError> {
|
||||||
|
let s = s.trim();
|
||||||
|
let s = s.strip_prefix("f64:").ok_or_else(|| AsmError::InvalidOperand(s.into()))?;
|
||||||
|
let hex = s.strip_prefix("0x").ok_or_else(|| AsmError::InvalidOperand(s.into()))?;
|
||||||
|
if hex.len() != 16 {
|
||||||
|
return Err(AsmError::InvalidOperand(s.into()));
|
||||||
|
}
|
||||||
|
u64::from_str_radix(hex, 16).map_err(|_| AsmError::InvalidOperand(s.into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_keyvals(s: &str) -> Result<(&str, &str), AsmError> {
|
||||||
|
// 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();
|
||||||
|
if parts.next().is_some() {
|
||||||
|
return Err(AsmError::InvalidOperand(s.into()));
|
||||||
|
}
|
||||||
|
Ok((a, b))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_pair<'a>(a: &'a str, ka: &str, b: &'a str, kb: &str) -> Result<(u32, u32), AsmError> {
|
||||||
|
let (ka_l, va_s) = a.split_once('=').ok_or_else(|| AsmError::InvalidOperand(a.into()))?;
|
||||||
|
let (kb_l, vb_s) = b.split_once('=').ok_or_else(|| AsmError::InvalidOperand(b.into()))?;
|
||||||
|
if ka_l.trim() != ka || kb_l.trim() != kb {
|
||||||
|
return Err(AsmError::InvalidOperand(format!("expected keys {} and {}", ka, kb)));
|
||||||
|
}
|
||||||
|
let va = parse_u32_any(va_s)?;
|
||||||
|
let vb = parse_u32_any(vb_s)?;
|
||||||
|
Ok((va, vb))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_mnemonic(line: &str) -> (&str, &str) {
|
||||||
|
let line = line.trim();
|
||||||
|
if let Some(sp) = line.find(char::is_whitespace) {
|
||||||
|
let (mn, rest) = line.split_at(sp);
|
||||||
|
(mn, rest.trim())
|
||||||
|
} else {
|
||||||
|
(line, "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn assemble(src: &str) -> Result<Vec<u8>, AsmError> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for raw_line in src.lines() {
|
||||||
|
let line = raw_line.trim();
|
||||||
|
if line.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (mn, ops) = parse_mnemonic(line);
|
||||||
|
match mn {
|
||||||
|
// Zero-operand
|
||||||
|
"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);
|
||||||
|
}
|
||||||
|
"TRAP" => {
|
||||||
|
emit_u16(CoreOpCode::Trap as u16, &mut out);
|
||||||
|
}
|
||||||
|
"DUP" => {
|
||||||
|
emit_u16(CoreOpCode::Dup as u16, &mut out);
|
||||||
|
}
|
||||||
|
"SWAP" => {
|
||||||
|
emit_u16(CoreOpCode::Swap as u16, &mut out);
|
||||||
|
}
|
||||||
|
"ADD" => {
|
||||||
|
emit_u16(CoreOpCode::Add as u16, &mut out);
|
||||||
|
}
|
||||||
|
"SUB" => {
|
||||||
|
emit_u16(CoreOpCode::Sub as u16, &mut out);
|
||||||
|
}
|
||||||
|
"MUL" => {
|
||||||
|
emit_u16(CoreOpCode::Mul as u16, &mut out);
|
||||||
|
}
|
||||||
|
"DIV" => {
|
||||||
|
emit_u16(CoreOpCode::Div as u16, &mut out);
|
||||||
|
}
|
||||||
|
"MOD" => {
|
||||||
|
emit_u16(CoreOpCode::Mod as u16, &mut out);
|
||||||
|
}
|
||||||
|
"NEG" => {
|
||||||
|
emit_u16(CoreOpCode::Neg as u16, &mut out);
|
||||||
|
}
|
||||||
|
"EQ" => {
|
||||||
|
emit_u16(CoreOpCode::Eq as u16, &mut out);
|
||||||
|
}
|
||||||
|
"NEQ" => {
|
||||||
|
emit_u16(CoreOpCode::Neq as u16, &mut out);
|
||||||
|
}
|
||||||
|
"LT" => {
|
||||||
|
emit_u16(CoreOpCode::Lt as u16, &mut out);
|
||||||
|
}
|
||||||
|
"LTE" => {
|
||||||
|
emit_u16(CoreOpCode::Lte as u16, &mut out);
|
||||||
|
}
|
||||||
|
"GT" => {
|
||||||
|
emit_u16(CoreOpCode::Gt as u16, &mut out);
|
||||||
|
}
|
||||||
|
"GTE" => {
|
||||||
|
emit_u16(CoreOpCode::Gte as u16, &mut out);
|
||||||
|
}
|
||||||
|
"AND" => {
|
||||||
|
emit_u16(CoreOpCode::And as u16, &mut out);
|
||||||
|
}
|
||||||
|
"OR" => {
|
||||||
|
emit_u16(CoreOpCode::Or as u16, &mut out);
|
||||||
|
}
|
||||||
|
"NOT" => {
|
||||||
|
emit_u16(CoreOpCode::Not as u16, &mut out);
|
||||||
|
}
|
||||||
|
"BIT_AND" => {
|
||||||
|
emit_u16(CoreOpCode::BitAnd as u16, &mut out);
|
||||||
|
}
|
||||||
|
"BIT_OR" => {
|
||||||
|
emit_u16(CoreOpCode::BitOr as u16, &mut out);
|
||||||
|
}
|
||||||
|
"BIT_XOR" => {
|
||||||
|
emit_u16(CoreOpCode::BitXor as u16, &mut out);
|
||||||
|
}
|
||||||
|
"SHL" => {
|
||||||
|
emit_u16(CoreOpCode::Shl as u16, &mut out);
|
||||||
|
}
|
||||||
|
"SHR" => {
|
||||||
|
emit_u16(CoreOpCode::Shr as u16, &mut out);
|
||||||
|
}
|
||||||
|
"RET" => {
|
||||||
|
emit_u16(CoreOpCode::Ret 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// One u32 immediate (decimal or hex accepted; SYSCALL/HOSTCALL commonly use hex/idx)
|
||||||
|
"JMP" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::Jmp as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"JMP_IF_FALSE" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::JmpIfFalse as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"JMP_IF_TRUE" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::JmpIfTrue as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"PUSH_CONST" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::PushConst as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"PUSH_I64" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::PushI64 as u16, &mut out);
|
||||||
|
emit_i64(parse_i64_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"PUSH_F64" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::PushF64 as u16, &mut out);
|
||||||
|
emit_f64_bits(parse_f64_bits(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"PUSH_BOOL" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
let v = parse_u32_any(ops)? as u8;
|
||||||
|
emit_u16(CoreOpCode::PushBool as u16, &mut out);
|
||||||
|
out.push(v);
|
||||||
|
}
|
||||||
|
"PUSH_I32" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::PushI32 as u16, &mut out);
|
||||||
|
emit_i32(parse_i32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"POP_N" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::PopN as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"GET_GLOBAL" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::GetGlobal as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"SET_GLOBAL" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::SetGlobal as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"GET_LOCAL" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::GetLocal as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"SET_LOCAL" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::SetLocal as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"CALL" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::Call as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"CALL_CLOSURE" | "GET_CAPTURE" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
let opcode = if mn == "CALL_CLOSURE" {
|
||||||
|
CoreOpCode::CallClosure
|
||||||
|
} else {
|
||||||
|
CoreOpCode::GetCapture
|
||||||
|
};
|
||||||
|
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()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::Hostcall as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"SYSCALL" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::Syscall as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"INTRINSIC" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
emit_u16(CoreOpCode::Intrinsic as u16, &mut out);
|
||||||
|
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" => {
|
||||||
|
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,
|
||||||
|
_ => CoreOpCode::ArraySet,
|
||||||
|
};
|
||||||
|
emit_u16(op as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &mut out);
|
||||||
|
}
|
||||||
|
"DYN_PACK" | "DYN_UNPACK" | "DYN_CAN_UNPACK" => {
|
||||||
|
if ops.is_empty() {
|
||||||
|
return Err(AsmError::MissingOperand(line.into()));
|
||||||
|
}
|
||||||
|
let opcode = match mn {
|
||||||
|
"DYN_PACK" => CoreOpCode::DynPack,
|
||||||
|
"DYN_UNPACK" => CoreOpCode::DynUnpack,
|
||||||
|
_ => CoreOpCode::DynCanUnpack,
|
||||||
|
};
|
||||||
|
emit_u16(opcode as u16, &mut out);
|
||||||
|
emit_u32(parse_u32_any(ops)?, &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())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
//! Canonical bytecode decoder for Prometeu Bytecode (PBX payload).
|
||||||
|
//!
|
||||||
|
//! Single source of truth for instruction decoding used by compiler/linker/verifier/VM.
|
||||||
|
//!
|
||||||
|
//! Contract:
|
||||||
|
//! - Instructions are encoded as: [opcode: u16 LE][immediate: spec.imm_bytes]
|
||||||
|
//! - `decode_next(pc, bytes)` returns a typed `DecodedInstr` with canonical `next_pc`.
|
||||||
|
//! - Immediate helpers validate sizes deterministically and return explicit errors.
|
||||||
|
|
||||||
|
use crate::isa::core::{CoreOpCode, CoreOpCodeSpecExt, CoreOpcodeSpec};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum DecodeError {
|
||||||
|
TruncatedOpcode { pc: usize },
|
||||||
|
UnknownOpcode { pc: usize, opcode: u16 },
|
||||||
|
TruncatedImmediate { pc: usize, opcode: CoreOpCode, need: usize, have: usize },
|
||||||
|
ImmediateSizeMismatch { pc: usize, opcode: CoreOpCode, expected: usize, actual: usize },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct DecodedInstr<'a> {
|
||||||
|
pub opcode: CoreOpCode,
|
||||||
|
pub pc: usize,
|
||||||
|
pub next_pc: usize,
|
||||||
|
/// Raw immediate bytes slice, guaranteed to have length `opcode.spec().imm_bytes`.
|
||||||
|
pub imm: &'a [u8],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> DecodedInstr<'a> {
|
||||||
|
#[inline]
|
||||||
|
fn ensure_len(&self, expected: usize) -> Result<(), DecodeError> {
|
||||||
|
if self.imm.len() != expected {
|
||||||
|
return Err(DecodeError::ImmediateSizeMismatch {
|
||||||
|
pc: self.pc,
|
||||||
|
opcode: self.opcode,
|
||||||
|
expected,
|
||||||
|
actual: self.imm.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn imm_u8(&self) -> Result<u8, DecodeError> {
|
||||||
|
self.ensure_len(1)?;
|
||||||
|
Ok(self.imm[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn imm_u16(&self) -> Result<u16, DecodeError> {
|
||||||
|
self.ensure_len(2)?;
|
||||||
|
Ok(u16::from_le_bytes(self.imm.try_into().unwrap()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn imm_u32(&self) -> Result<u32, DecodeError> {
|
||||||
|
self.ensure_len(4)?;
|
||||||
|
Ok(u32::from_le_bytes(self.imm.try_into().unwrap()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn imm_i32(&self) -> Result<i32, DecodeError> {
|
||||||
|
self.ensure_len(4)?;
|
||||||
|
Ok(i32::from_le_bytes(self.imm.try_into().unwrap()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn imm_i64(&self) -> Result<i64, DecodeError> {
|
||||||
|
self.ensure_len(8)?;
|
||||||
|
Ok(i64::from_le_bytes(self.imm.try_into().unwrap()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn imm_f64(&self) -> Result<f64, DecodeError> {
|
||||||
|
self.ensure_len(8)?;
|
||||||
|
Ok(f64::from_le_bytes(self.imm.try_into().unwrap()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper for opcodes carrying two u32 values packed in 8 bytes (e.g., ALLOC meta).
|
||||||
|
#[inline]
|
||||||
|
pub fn imm_u32x2(&self) -> Result<(u32, u32), DecodeError> {
|
||||||
|
self.ensure_len(8)?;
|
||||||
|
let a = u32::from_le_bytes(self.imm[0..4].try_into().unwrap());
|
||||||
|
let b = u32::from_le_bytes(self.imm[4..8].try_into().unwrap());
|
||||||
|
Ok((a, b))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes the instruction at program counter `pc` from `bytes`.
|
||||||
|
/// Returns the decoded instruction with canonical `next_pc`.
|
||||||
|
#[inline]
|
||||||
|
pub fn decode_next(pc: usize, bytes: &'_ [u8]) -> Result<DecodedInstr<'_>, DecodeError> {
|
||||||
|
if pc.checked_add(2).is_none_or(|end| end > bytes.len()) {
|
||||||
|
return Err(DecodeError::TruncatedOpcode { pc });
|
||||||
|
}
|
||||||
|
|
||||||
|
let opcode_val = u16::from_le_bytes([bytes[pc], bytes[pc + 1]]);
|
||||||
|
let opcode = CoreOpCode::try_from(opcode_val)
|
||||||
|
.map_err(|_| DecodeError::UnknownOpcode { pc, opcode: opcode_val })?;
|
||||||
|
|
||||||
|
let spec: CoreOpcodeSpec = opcode.spec();
|
||||||
|
let imm_start = pc + 2;
|
||||||
|
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 {
|
||||||
|
pc,
|
||||||
|
opcode,
|
||||||
|
need: spec.imm_bytes as usize,
|
||||||
|
have: bytes.len().saturating_sub(imm_start),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(DecodedInstr { opcode, pc, next_pc: imm_end, imm: &bytes[imm_start..imm_end] })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_opcode_is_reported_deterministically() {
|
||||||
|
// 0x0060 was previously a legacy opcode; now it must be unknown.
|
||||||
|
let bytes = vec![0x60, 0x00]; // little-endian u16 = 0x0060
|
||||||
|
match decode_next(0, &bytes) {
|
||||||
|
Err(DecodeError::UnknownOpcode { pc, opcode }) => {
|
||||||
|
assert_eq!(pc, 0);
|
||||||
|
assert_eq!(opcode, 0x0060);
|
||||||
|
}
|
||||||
|
other => panic!("expected UnknownOpcode, got {:?}", other),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
//! Deterministic disassembler for Prometeu Bytecode (PBX payload).
|
||||||
|
//!
|
||||||
|
//! Goals:
|
||||||
|
//! - Stable formatting across platforms (snapshot-friendly).
|
||||||
|
//! - Complete coverage of the Core ISA, including closures/coroutines.
|
||||||
|
//! - Roundtrip-safe with the paired `assembler` module.
|
||||||
|
//!
|
||||||
|
//! Format (one instruction per line):
|
||||||
|
//! - `MNEMONIC` for zero-operand instructions.
|
||||||
|
//! - `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>, 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.
|
||||||
|
//!
|
||||||
|
//! Notes:
|
||||||
|
//! - All integers are printed in base-10 except where explicitly noted.
|
||||||
|
//! - Floats use exact bit-pattern format to prevent locale/rounding differences.
|
||||||
|
//! - Ordering is the canonical decode order; no address prefixes are emitted.
|
||||||
|
|
||||||
|
use crate::decode_next;
|
||||||
|
use crate::isa::core::{CoreOpCode, CoreOpCodeSpecExt};
|
||||||
|
use crate::DecodeError;
|
||||||
|
|
||||||
|
fn fmt_f64_bits(bits: u64) -> String {
|
||||||
|
// Fixed-width 16 hex digits, lowercase.
|
||||||
|
format!("f64:0x{bits:016x}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_operand(op: CoreOpCode, imm: &[u8]) -> String {
|
||||||
|
match op {
|
||||||
|
CoreOpCode::Jmp | CoreOpCode::JmpIfFalse | CoreOpCode::JmpIfTrue => {
|
||||||
|
let v = u32::from_le_bytes(imm.try_into().unwrap());
|
||||||
|
format!("{}", v)
|
||||||
|
}
|
||||||
|
CoreOpCode::PushI64 => {
|
||||||
|
let v = i64::from_le_bytes(imm.try_into().unwrap());
|
||||||
|
format!("{}", v)
|
||||||
|
}
|
||||||
|
CoreOpCode::PushF64 => {
|
||||||
|
let v = u64::from_le_bytes(imm.try_into().unwrap());
|
||||||
|
fmt_f64_bits(v)
|
||||||
|
}
|
||||||
|
CoreOpCode::PushBool => {
|
||||||
|
let v = imm[0];
|
||||||
|
format!("{}", v)
|
||||||
|
}
|
||||||
|
CoreOpCode::PushI32 => {
|
||||||
|
let v = i32::from_le_bytes(imm.try_into().unwrap());
|
||||||
|
format!("{}", v)
|
||||||
|
}
|
||||||
|
CoreOpCode::PopN
|
||||||
|
| CoreOpCode::PushConst
|
||||||
|
| CoreOpCode::GetGlobal
|
||||||
|
| CoreOpCode::SetGlobal
|
||||||
|
| CoreOpCode::GetLocal
|
||||||
|
| CoreOpCode::SetLocal
|
||||||
|
| CoreOpCode::Call
|
||||||
|
| CoreOpCode::Sleep
|
||||||
|
| CoreOpCode::GetCapture
|
||||||
|
| CoreOpCode::CallClosure
|
||||||
|
| CoreOpCode::Hostcall
|
||||||
|
| CoreOpCode::DynPack
|
||||||
|
| CoreOpCode::DynUnpack
|
||||||
|
| CoreOpCode::DynCanUnpack
|
||||||
|
| CoreOpCode::StructNew
|
||||||
|
| CoreOpCode::ArrayNew
|
||||||
|
| CoreOpCode::ArrayLen
|
||||||
|
| CoreOpCode::ArrayGet
|
||||||
|
| CoreOpCode::ArraySet => {
|
||||||
|
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::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={}, type={}", fn_id, cap)
|
||||||
|
}
|
||||||
|
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());
|
||||||
|
let argc = u32::from_le_bytes(imm[4..8].try_into().unwrap());
|
||||||
|
format!("fn={}, argc={}", fn_id, argc)
|
||||||
|
}
|
||||||
|
CoreOpCode::Syscall => {
|
||||||
|
let id = u32::from_le_bytes(imm.try_into().unwrap());
|
||||||
|
// Hex id stable, avoids dependency on HAL metadata.
|
||||||
|
format!("0x{:04x}", id)
|
||||||
|
}
|
||||||
|
CoreOpCode::Intrinsic => {
|
||||||
|
let id = u32::from_le_bytes(imm.try_into().unwrap());
|
||||||
|
format!("0x{:04x}", id)
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
// Fallback: raw immediate hex (little-endian, as encoded)
|
||||||
|
let mut s = String::with_capacity(2 + imm.len() * 2);
|
||||||
|
s.push_str("0x");
|
||||||
|
for b in imm {
|
||||||
|
use core::fmt::Write as _;
|
||||||
|
let _ = write!(&mut s, "{:02x}", b);
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Disassembles a contiguous byte slice (single function body) into deterministic text.
|
||||||
|
pub fn disassemble(bytes: &[u8]) -> Result<String, DecodeError> {
|
||||||
|
let mut pc = 0usize;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while pc < bytes.len() {
|
||||||
|
let instr = decode_next(pc, bytes)?;
|
||||||
|
let name = instr.opcode.spec().name;
|
||||||
|
let imm_len = instr.opcode.spec().imm_bytes as usize;
|
||||||
|
if imm_len == 0 {
|
||||||
|
out.push(name.to_string());
|
||||||
|
} else {
|
||||||
|
let ops = format_operand(instr.opcode, instr.imm);
|
||||||
|
out.push(format!("{} {}", name, ops));
|
||||||
|
}
|
||||||
|
pc = instr.next_pc;
|
||||||
|
}
|
||||||
|
Ok(out.join("\n"))
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
//! Core ISA profile (bytecode-level, stable, canonical).
|
||||||
|
//!
|
||||||
|
//! This profile is the canonical opcode surface used by decoder/disasm and
|
||||||
|
//! 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:
|
||||||
|
// `prometeu_bytecode::isa::core::*`.
|
||||||
|
|
||||||
|
pub use crate::opcode::OpCode as CoreOpCode;
|
||||||
|
pub use crate::opcode_spec::{OpCodeSpecExt as CoreOpCodeSpecExt, OpcodeSpec as CoreOpcodeSpec};
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
//! ISA module tree
|
||||||
|
//!
|
||||||
|
//! This module defines stable ISA profiles. For PR-1.4 we expose the
|
||||||
|
//! minimal core ISA surface used by the encoder/decoder and (later) verifier.
|
||||||
|
|
||||||
|
pub mod core;
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
mod abi;
|
||||||
|
pub mod assembler;
|
||||||
|
mod decoder;
|
||||||
|
mod disassembler;
|
||||||
|
pub mod isa; // canonical ISA boundary (core and future profiles)
|
||||||
|
pub mod model;
|
||||||
|
mod opcode;
|
||||||
|
mod opcode_spec;
|
||||||
|
mod program_image;
|
||||||
|
mod resource_failure;
|
||||||
|
mod value;
|
||||||
|
|
||||||
|
pub use abi::{
|
||||||
|
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, DecodedInstr};
|
||||||
|
pub use disassembler::disassemble;
|
||||||
|
pub use model::{LoadError, SyscallDecl, PBX_MAGIC};
|
||||||
|
pub use program_image::ExecutionFunction;
|
||||||
|
pub use program_image::ProgramImage;
|
||||||
|
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 v1 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
use crate::abi::SourceSpan;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// An entry in the Constant Pool.
|
||||||
|
///
|
||||||
|
/// The Constant Pool is a table of unique values used by the program.
|
||||||
|
/// Instead of embedding large data (like strings) directly in the instruction stream,
|
||||||
|
/// the bytecode uses `PushConst <index>` to load these values onto the stack.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub enum ConstantPoolEntry {
|
||||||
|
/// Reserved index (0). Represents a null/undefined value.
|
||||||
|
Null,
|
||||||
|
/// A 64-bit integer constant.
|
||||||
|
Int64(i64),
|
||||||
|
/// A 64-bit floating point constant.
|
||||||
|
Float64(f64),
|
||||||
|
/// A boolean constant.
|
||||||
|
Boolean(bool),
|
||||||
|
/// A UTF-8 string constant.
|
||||||
|
String(String),
|
||||||
|
/// A 32-bit integer constant.
|
||||||
|
Int32(i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum LoadError {
|
||||||
|
InvalidMagic,
|
||||||
|
InvalidVersion,
|
||||||
|
InvalidEndianness,
|
||||||
|
OverlappingSections,
|
||||||
|
SectionOutOfBounds,
|
||||||
|
InvalidOpcode,
|
||||||
|
InvalidConstIndex,
|
||||||
|
InvalidFunctionIndex,
|
||||||
|
MalformedHeader,
|
||||||
|
MalformedSection,
|
||||||
|
MissingSyscallSection,
|
||||||
|
DuplicateSyscallIdentity,
|
||||||
|
InvalidUtf8,
|
||||||
|
UnexpectedEof,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct DebugInfo {
|
||||||
|
pub pc_to_span: Vec<(u32, SourceSpan)>, // Sorted by PC
|
||||||
|
pub function_names: Vec<(u32, String)>, // (func_idx, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Export {
|
||||||
|
pub symbol: String,
|
||||||
|
pub func_idx: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct SyscallDecl {
|
||||||
|
pub module: String,
|
||||||
|
pub name: String,
|
||||||
|
pub version: u16,
|
||||||
|
pub arg_slots: u16,
|
||||||
|
pub ret_slots: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const PBX_MAGIC: [u8; 4] = *b"PBX\0";
|
||||||
@@ -0,0 +1,356 @@
|
|||||||
|
/// Represents a single instruction in the Prometeu Virtual Machine.
|
||||||
|
///
|
||||||
|
/// Each OpCode is encoded as a 16-bit unsigned integer (u16) in the bytecode.
|
||||||
|
/// The PVM is a stack-based machine, meaning most instructions take their
|
||||||
|
/// operands from the top of the stack and push their results back onto it.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[repr(u16)]
|
||||||
|
pub enum OpCode {
|
||||||
|
// --- 6.1 Execution Control ---
|
||||||
|
/// No operation. Does nothing for 1 cycle.
|
||||||
|
Nop = 0x00,
|
||||||
|
/// Stops the Virtual Machine execution immediately.
|
||||||
|
Halt = 0x01,
|
||||||
|
/// Unconditional jump to a specific PC (Program Counter) address.
|
||||||
|
/// Operand: addr (u32)
|
||||||
|
Jmp = 0x02,
|
||||||
|
/// Jumps to `addr` if the value at the top of the stack is `false`.
|
||||||
|
/// Operand: addr (u32)
|
||||||
|
/// Stack: [bool] -> []
|
||||||
|
JmpIfFalse = 0x03,
|
||||||
|
/// Jumps to `addr` if the value at the top of the stack is `true`.
|
||||||
|
/// Operand: addr (u32)
|
||||||
|
/// Stack: [bool] -> []
|
||||||
|
JmpIfTrue = 0x04,
|
||||||
|
/// Triggers a software breakpoint. Used for debugging.
|
||||||
|
Trap = 0x05,
|
||||||
|
|
||||||
|
// --- 6.2 Stack Manipulation ---
|
||||||
|
/// Loads a constant from the Constant Pool into the stack.
|
||||||
|
/// Operand: index (u32)
|
||||||
|
/// Stack: [] -> [value]
|
||||||
|
PushConst = 0x10,
|
||||||
|
/// Removes the top value from the stack.
|
||||||
|
/// Stack: [val] -> []
|
||||||
|
Pop = 0x11,
|
||||||
|
/// Duplicates the top value of the stack.
|
||||||
|
/// Stack: [val] -> [val, val]
|
||||||
|
Dup = 0x12,
|
||||||
|
/// Swaps the two top values of the stack.
|
||||||
|
/// Stack: [a, b] -> [b, a]
|
||||||
|
Swap = 0x13,
|
||||||
|
/// Pushes a 64-bit integer literal onto the stack.
|
||||||
|
/// Operand: value (i64)
|
||||||
|
PushI64 = 0x14,
|
||||||
|
/// Pushes a 64-bit float literal onto the stack.
|
||||||
|
/// Operand: value (f64)
|
||||||
|
PushF64 = 0x15,
|
||||||
|
/// Pushes a boolean literal onto the stack (0=false, 1=true).
|
||||||
|
/// Operand: value (u8)
|
||||||
|
PushBool = 0x16,
|
||||||
|
/// Pushes a 32-bit integer literal onto the stack.
|
||||||
|
/// Operand: value (i32)
|
||||||
|
PushI32 = 0x17,
|
||||||
|
/// Removes `n` values from the stack.
|
||||||
|
/// Operand: n (u32)
|
||||||
|
PopN = 0x18,
|
||||||
|
// --- 6.3 Arithmetic ---
|
||||||
|
/// Adds the two top values (a + b).
|
||||||
|
/// Stack: [a, b] -> [result]
|
||||||
|
Add = 0x20,
|
||||||
|
/// Subtracts the top value from the second one (a - b).
|
||||||
|
/// Stack: [a, b] -> [result]
|
||||||
|
Sub = 0x21,
|
||||||
|
/// Multiplies the two top values (a * b).
|
||||||
|
/// Stack: [a, b] -> [result]
|
||||||
|
Mul = 0x22,
|
||||||
|
/// Divides the second top value by the top one (a / b).
|
||||||
|
/// Stack: [a, b] -> [result]
|
||||||
|
Div = 0x23,
|
||||||
|
/// Remainder of the division of the second top value by the top one (a % b).
|
||||||
|
/// Stack: [a, b] -> [result]
|
||||||
|
Mod = 0x24,
|
||||||
|
// --- 6.4 Comparison and Logic ---
|
||||||
|
/// Checks if a equals b.
|
||||||
|
/// Stack: [a, b] -> [bool]
|
||||||
|
Eq = 0x30,
|
||||||
|
/// Checks if a is not equal to b.
|
||||||
|
/// Stack: [a, b] -> [bool]
|
||||||
|
Neq = 0x31,
|
||||||
|
/// Checks if a is less than b.
|
||||||
|
/// Stack: [a, b] -> [bool]
|
||||||
|
Lt = 0x32,
|
||||||
|
/// Checks if a is greater than b.
|
||||||
|
/// Stack: [a, b] -> [bool]
|
||||||
|
Gt = 0x33,
|
||||||
|
/// Logical AND.
|
||||||
|
/// Stack: [bool, bool] -> [bool]
|
||||||
|
And = 0x34,
|
||||||
|
/// Logical OR.
|
||||||
|
/// Stack: [bool, bool] -> [bool]
|
||||||
|
Or = 0x35,
|
||||||
|
/// Logical NOT.
|
||||||
|
/// Stack: [bool] -> [bool]
|
||||||
|
Not = 0x36,
|
||||||
|
/// Bitwise AND.
|
||||||
|
/// Stack: [int, int] -> [int]
|
||||||
|
BitAnd = 0x37,
|
||||||
|
/// Bitwise OR.
|
||||||
|
/// Stack: [int, int] -> [int]
|
||||||
|
BitOr = 0x38,
|
||||||
|
/// Bitwise XOR.
|
||||||
|
/// Stack: [int, int] -> [int]
|
||||||
|
BitXor = 0x39,
|
||||||
|
/// Bitwise Shift Left.
|
||||||
|
/// Stack: [int, count] -> [int]
|
||||||
|
Shl = 0x3A,
|
||||||
|
/// Bitwise Shift Right.
|
||||||
|
/// Stack: [int, count] -> [int]
|
||||||
|
Shr = 0x3B,
|
||||||
|
/// Checks if a is less than or equal to b.
|
||||||
|
/// Stack: [a, b] -> [bool]
|
||||||
|
Lte = 0x3C,
|
||||||
|
/// Checks if a is greater than or equal to b.
|
||||||
|
/// Stack: [a, b] -> [bool]
|
||||||
|
Gte = 0x3D,
|
||||||
|
/// Negates a number (-a).
|
||||||
|
/// Stack: [num] -> [num]
|
||||||
|
Neg = 0x3E,
|
||||||
|
|
||||||
|
// --- 6.5 Variables ---
|
||||||
|
/// Loads a value from a global variable slot.
|
||||||
|
/// Operand: slot_index (u32)
|
||||||
|
/// Stack: [] -> [value]
|
||||||
|
GetGlobal = 0x40,
|
||||||
|
/// Stores the top value into a global variable slot.
|
||||||
|
/// Operand: slot_index (u32)
|
||||||
|
/// Stack: [value] -> []
|
||||||
|
SetGlobal = 0x41,
|
||||||
|
/// Loads a value from a local variable slot in the current frame.
|
||||||
|
/// Operand: slot_index (u32)
|
||||||
|
/// Stack: [] -> [value]
|
||||||
|
GetLocal = 0x42,
|
||||||
|
/// Stores the top value into a local variable slot in the current frame.
|
||||||
|
/// Operand: slot_index (u32)
|
||||||
|
/// Stack: [value] -> []
|
||||||
|
SetLocal = 0x43,
|
||||||
|
|
||||||
|
// --- 6.6 Functions ---
|
||||||
|
/// Calls a function by its index in the function table.
|
||||||
|
/// Operand: func_id (u32)
|
||||||
|
/// Stack: [arg0, arg1, ...] -> [return_slots...]
|
||||||
|
Call = 0x50,
|
||||||
|
/// Returns from the current function.
|
||||||
|
/// Stack: [return_val] -> [return_val]
|
||||||
|
Ret = 0x51,
|
||||||
|
/// Create a typed instance: FunctionId, FnTypeId. Captures come from metadata.
|
||||||
|
MakeClosure = 0x52,
|
||||||
|
/// Invoke with expected FnTypeId; environment belongs to CallFrame, not arg0.
|
||||||
|
CallClosure = 0x53,
|
||||||
|
/// Retired opcode, recognized only for load rejection and diagnostics.
|
||||||
|
Spawn = 0x54,
|
||||||
|
/// Retired opcode, recognized only for load rejection and diagnostics.
|
||||||
|
Yield = 0x55,
|
||||||
|
/// 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.
|
||||||
|
/// Operand: sysc_index (u32)
|
||||||
|
/// This opcode is valid only in PBX artifact form and must be patched by the loader
|
||||||
|
/// into a final numeric `SYSCALL <id>` before verification or execution.
|
||||||
|
Hostcall = 0x71,
|
||||||
|
/// Invokes a final numeric system function (Firmware/OS).
|
||||||
|
/// Raw `SYSCALL` is valid only after loader patching and is rejected in PBX pre-load artifacts.
|
||||||
|
/// Operand: syscall_id (u32)
|
||||||
|
/// Stack: [args...] -> [results...] (depends on syscall)
|
||||||
|
Syscall = 0x70,
|
||||||
|
/// Invokes a VM-owned intrinsic by final numeric id.
|
||||||
|
/// Operand: intrinsic_id (u32)
|
||||||
|
/// Stack: [args...] -> [results...] (depends on intrinsic metadata)
|
||||||
|
Intrinsic = 0x72,
|
||||||
|
/// 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,
|
||||||
|
|
||||||
|
// Registry-backed collection operations. cycles() is their base component.
|
||||||
|
StructNew = 0xA0,
|
||||||
|
StructGet = 0xA1,
|
||||||
|
StructSet = 0xA2,
|
||||||
|
ArrayNew = 0xA3,
|
||||||
|
ArrayLen = 0xA4,
|
||||||
|
ArrayGet = 0xA5,
|
||||||
|
ArraySet = 0xA6,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<u16> for OpCode {
|
||||||
|
type Error = String;
|
||||||
|
|
||||||
|
fn try_from(value: u16) -> Result<Self, Self::Error> {
|
||||||
|
match value {
|
||||||
|
0x00 => Ok(OpCode::Nop),
|
||||||
|
0x01 => Ok(OpCode::Halt),
|
||||||
|
0x02 => Ok(OpCode::Jmp),
|
||||||
|
0x03 => Ok(OpCode::JmpIfFalse),
|
||||||
|
0x04 => Ok(OpCode::JmpIfTrue),
|
||||||
|
0x05 => Ok(OpCode::Trap),
|
||||||
|
0x10 => Ok(OpCode::PushConst),
|
||||||
|
0x11 => Ok(OpCode::Pop),
|
||||||
|
0x12 => Ok(OpCode::Dup),
|
||||||
|
0x13 => Ok(OpCode::Swap),
|
||||||
|
0x14 => Ok(OpCode::PushI64),
|
||||||
|
0x15 => Ok(OpCode::PushF64),
|
||||||
|
0x16 => Ok(OpCode::PushBool),
|
||||||
|
0x17 => Ok(OpCode::PushI32),
|
||||||
|
0x18 => Ok(OpCode::PopN),
|
||||||
|
0x20 => Ok(OpCode::Add),
|
||||||
|
0x21 => Ok(OpCode::Sub),
|
||||||
|
0x22 => Ok(OpCode::Mul),
|
||||||
|
0x23 => Ok(OpCode::Div),
|
||||||
|
0x24 => Ok(OpCode::Mod),
|
||||||
|
0x30 => Ok(OpCode::Eq),
|
||||||
|
0x31 => Ok(OpCode::Neq),
|
||||||
|
0x32 => Ok(OpCode::Lt),
|
||||||
|
0x33 => Ok(OpCode::Gt),
|
||||||
|
0x34 => Ok(OpCode::And),
|
||||||
|
0x35 => Ok(OpCode::Or),
|
||||||
|
0x36 => Ok(OpCode::Not),
|
||||||
|
0x37 => Ok(OpCode::BitAnd),
|
||||||
|
0x38 => Ok(OpCode::BitOr),
|
||||||
|
0x39 => Ok(OpCode::BitXor),
|
||||||
|
0x3A => Ok(OpCode::Shl),
|
||||||
|
0x3B => Ok(OpCode::Shr),
|
||||||
|
0x3C => Ok(OpCode::Lte),
|
||||||
|
0x3D => Ok(OpCode::Gte),
|
||||||
|
0x3E => Ok(OpCode::Neg),
|
||||||
|
0x40 => Ok(OpCode::GetGlobal),
|
||||||
|
0x41 => Ok(OpCode::SetGlobal),
|
||||||
|
0x42 => Ok(OpCode::GetLocal),
|
||||||
|
0x43 => Ok(OpCode::SetLocal),
|
||||||
|
0x50 => Ok(OpCode::Call),
|
||||||
|
0x51 => Ok(OpCode::Ret),
|
||||||
|
0x52 => Ok(OpCode::MakeClosure),
|
||||||
|
0x53 => Ok(OpCode::CallClosure),
|
||||||
|
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),
|
||||||
|
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),
|
||||||
|
|
||||||
|
_ => Err(format!("Invalid OpCode: 0x{:04X}", value)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OpCode {
|
||||||
|
/// 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,
|
||||||
|
OpCode::Halt => 1,
|
||||||
|
OpCode::Jmp => 2,
|
||||||
|
OpCode::JmpIfFalse => 3,
|
||||||
|
OpCode::JmpIfTrue => 3,
|
||||||
|
OpCode::Trap => 1,
|
||||||
|
OpCode::PushConst => 2,
|
||||||
|
OpCode::Pop => 1,
|
||||||
|
OpCode::PopN => 2,
|
||||||
|
OpCode::Dup => 1,
|
||||||
|
OpCode::Swap => 1,
|
||||||
|
OpCode::PushI64 => 2,
|
||||||
|
OpCode::PushF64 => 2,
|
||||||
|
OpCode::PushBool => 2,
|
||||||
|
OpCode::PushI32 => 2,
|
||||||
|
OpCode::Add => 2,
|
||||||
|
OpCode::Sub => 2,
|
||||||
|
OpCode::Mul => 4,
|
||||||
|
OpCode::Div => 6,
|
||||||
|
OpCode::Mod => 6,
|
||||||
|
OpCode::Eq => 2,
|
||||||
|
OpCode::Neq => 2,
|
||||||
|
OpCode::Lt => 2,
|
||||||
|
OpCode::Gt => 2,
|
||||||
|
OpCode::And => 2,
|
||||||
|
OpCode::Or => 2,
|
||||||
|
OpCode::Not => 1,
|
||||||
|
OpCode::BitAnd => 2,
|
||||||
|
OpCode::BitOr => 2,
|
||||||
|
OpCode::BitXor => 2,
|
||||||
|
OpCode::Shl => 2,
|
||||||
|
OpCode::Shr => 2,
|
||||||
|
OpCode::Lte => 2,
|
||||||
|
OpCode::Gte => 2,
|
||||||
|
OpCode::Neg => 1,
|
||||||
|
OpCode::GetGlobal => 3,
|
||||||
|
OpCode::SetGlobal => 3,
|
||||||
|
OpCode::GetLocal => 2,
|
||||||
|
OpCode::SetLocal => 2,
|
||||||
|
OpCode::Call => 5,
|
||||||
|
OpCode::Ret => 4,
|
||||||
|
OpCode::MakeClosure => 8,
|
||||||
|
OpCode::CallClosure | OpCode::CallTrait => 6,
|
||||||
|
OpCode::GetCapture => 2,
|
||||||
|
OpCode::Spawn => 6,
|
||||||
|
OpCode::Yield => 1,
|
||||||
|
OpCode::Sleep => 1,
|
||||||
|
OpCode::Syscall => 1,
|
||||||
|
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::StructNew => 8,
|
||||||
|
OpCode::StructGet => 3,
|
||||||
|
OpCode::StructSet => 4,
|
||||||
|
OpCode::ArrayNew => 8,
|
||||||
|
OpCode::ArrayLen => 3,
|
||||||
|
OpCode::ArrayGet => 3,
|
||||||
|
OpCode::ArraySet => 4,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,710 @@
|
|||||||
|
use crate::opcode::OpCode;
|
||||||
|
|
||||||
|
/// Specification for a single OpCode.
|
||||||
|
/// All JMP/JMP_IF_* immediate are u32 absolute offsets from function start.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct OpcodeSpec {
|
||||||
|
pub name: &'static str,
|
||||||
|
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 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 {
|
||||||
|
fn spec(&self) -> OpcodeSpec {
|
||||||
|
match self {
|
||||||
|
OpCode::Nop => OpcodeSpec {
|
||||||
|
name: "NOP",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Halt => OpcodeSpec {
|
||||||
|
name: "HALT",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: true,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Jmp => OpcodeSpec {
|
||||||
|
name: "JMP",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: true,
|
||||||
|
is_terminator: true,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::JmpIfFalse => OpcodeSpec {
|
||||||
|
name: "JMP_IF_FALSE",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(1),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: true,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: true,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::JmpIfTrue => OpcodeSpec {
|
||||||
|
name: "JMP_IF_TRUE",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(1),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: true,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: true,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Trap => OpcodeSpec {
|
||||||
|
name: "TRAP",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: true,
|
||||||
|
may_trap: true,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::PushConst => OpcodeSpec {
|
||||||
|
name: "PUSH_CONST",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Pop => OpcodeSpec {
|
||||||
|
name: "POP",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(1),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::PopN => OpcodeSpec {
|
||||||
|
name: "POP_N",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Dup => OpcodeSpec {
|
||||||
|
name: "DUP",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(1),
|
||||||
|
pushes: Some(2),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Swap => OpcodeSpec {
|
||||||
|
name: "SWAP",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(2),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::PushI64 => OpcodeSpec {
|
||||||
|
name: "PUSH_I64",
|
||||||
|
imm_bytes: 8,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::PushF64 => OpcodeSpec {
|
||||||
|
name: "PUSH_F64",
|
||||||
|
imm_bytes: 8,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::PushBool => OpcodeSpec {
|
||||||
|
name: "PUSH_BOOL",
|
||||||
|
imm_bytes: 1,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::PushI32 => OpcodeSpec {
|
||||||
|
name: "PUSH_I32",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Add => OpcodeSpec {
|
||||||
|
name: "ADD",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: true,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Sub => OpcodeSpec {
|
||||||
|
name: "SUB",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: true,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Mul => OpcodeSpec {
|
||||||
|
name: "MUL",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: true,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Div => OpcodeSpec {
|
||||||
|
name: "DIV",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: true,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Mod => OpcodeSpec {
|
||||||
|
name: "MOD",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: true,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Eq => OpcodeSpec {
|
||||||
|
name: "EQ",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Neq => OpcodeSpec {
|
||||||
|
name: "NEQ",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Lt => OpcodeSpec {
|
||||||
|
name: "LT",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Gt => OpcodeSpec {
|
||||||
|
name: "GT",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::And => OpcodeSpec {
|
||||||
|
name: "AND",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Or => OpcodeSpec {
|
||||||
|
name: "OR",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Not => OpcodeSpec {
|
||||||
|
name: "NOT",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(1),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::BitAnd => OpcodeSpec {
|
||||||
|
name: "BIT_AND",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::BitOr => OpcodeSpec {
|
||||||
|
name: "BIT_OR",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::BitXor => OpcodeSpec {
|
||||||
|
name: "BIT_XOR",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Shl => OpcodeSpec {
|
||||||
|
name: "SHL",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Shr => OpcodeSpec {
|
||||||
|
name: "SHR",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Lte => OpcodeSpec {
|
||||||
|
name: "LTE",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Gte => OpcodeSpec {
|
||||||
|
name: "GTE",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(2),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Neg => OpcodeSpec {
|
||||||
|
name: "NEG",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(1),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::GetGlobal => OpcodeSpec {
|
||||||
|
name: "GET_GLOBAL",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::SetGlobal => OpcodeSpec {
|
||||||
|
name: "SET_GLOBAL",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(1),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::GetLocal => OpcodeSpec {
|
||||||
|
name: "GET_LOCAL",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(1),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::SetLocal => OpcodeSpec {
|
||||||
|
name: "SET_LOCAL",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(1),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Call => OpcodeSpec {
|
||||||
|
name: "CALL",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: true,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Ret => OpcodeSpec {
|
||||||
|
name: "RET",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: true,
|
||||||
|
may_trap: false,
|
||||||
|
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: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Yield => OpcodeSpec {
|
||||||
|
name: "YIELD",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
// Retired encoding: retained for diagnostic decoding only.
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
// Loading rejects this opcode, including unreachable occurrences.
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Sleep => OpcodeSpec {
|
||||||
|
name: "SLEEP",
|
||||||
|
// One u32 immediate: duration_ticks
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
// Retired encoding: retained for diagnostic decoding only.
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
// Loading rejects this opcode, including unreachable occurrences.
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Hostcall => OpcodeSpec {
|
||||||
|
name: "HOSTCALL",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Syscall => OpcodeSpec {
|
||||||
|
name: "SYSCALL",
|
||||||
|
imm_bytes: 4,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: true,
|
||||||
|
is_safepoint: false,
|
||||||
|
},
|
||||||
|
OpCode::Intrinsic => OpcodeSpec {
|
||||||
|
name: "INTRINSIC",
|
||||||
|
imm_bytes: 4,
|
||||||
|
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::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::FrameSync => OpcodeSpec {
|
||||||
|
name: "FRAME_SYNC",
|
||||||
|
imm_bytes: 0,
|
||||||
|
pops: Some(0),
|
||||||
|
pushes: Some(0),
|
||||||
|
is_branch: false,
|
||||||
|
is_terminator: false,
|
||||||
|
may_trap: false,
|
||||||
|
is_safepoint: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
// Infer the numeric range from the TryFrom<u16> mapping used in opcode.rs tests
|
||||||
|
// by scanning a plausible range (0..1024) and keeping all successful decodes.
|
||||||
|
#[test]
|
||||||
|
fn every_opcode_has_spec_and_imm_defined() {
|
||||||
|
let mut count = 0usize;
|
||||||
|
for val in 0u16..=1023u16 {
|
||||||
|
if let Ok(op) = OpCode::try_from(val) {
|
||||||
|
let spec = op.spec();
|
||||||
|
// Access all fields to ensure they are present and not optimized away
|
||||||
|
let _ = (
|
||||||
|
spec.name,
|
||||||
|
spec.imm_bytes,
|
||||||
|
spec.pops,
|
||||||
|
spec.pushes,
|
||||||
|
spec.is_branch,
|
||||||
|
spec.is_terminator,
|
||||||
|
spec.may_trap,
|
||||||
|
);
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(count > 0, "No opcodes were found via OpCode::try_from");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
/// 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::DebugInfo;
|
||||||
|
use crate::value::Value;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
/// 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<[ExecutionFunction]>,
|
||||||
|
pub debug_info: Option<Arc<DebugInfo>>,
|
||||||
|
pub exports: Arc<HashMap<String, u32>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProgramImage {
|
||||||
|
pub fn create_trap(&self, code: u32, opcode: u16, mut message: String, pc: u32) -> TrapInfo {
|
||||||
|
let span = self
|
||||||
|
.debug_info
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|di| di.pc_to_span.iter().find(|(p, _)| *p == pc).map(|(_, s)| s.clone()));
|
||||||
|
|
||||||
|
if let Some(func_idx) = self.find_function_index(pc) {
|
||||||
|
if let Some(func_name) = self.get_function_name(func_idx) {
|
||||||
|
message = format!("{} (in function {})", message, func_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TrapInfo { code, opcode, message, pc, span, resource: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find_function_index(&self, pc: u32) -> Option<usize> {
|
||||||
|
self.functions.iter().position(|f| pc >= f.code_offset && pc < (f.code_offset + f.code_len))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_function_name(&self, func_idx: usize) -> Option<&str> {
|
||||||
|
self.debug_info
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|di| di.function_names.iter().find(|(idx, _)| *idx as usize == func_idx))
|
||||||
|
.map(|(_, name)| name.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,833 @@
|
|||||||
|
//! 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),
|
||||||
|
}
|
||||||
|
#[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 v1 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] != [1, 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 v1 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 v1 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(&[1, 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 v1 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 v1; 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,180 @@
|
|||||||
|
//! 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::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 {}
|
||||||
+91
-4
@@ -1,15 +1,52 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::cell::Cell;
|
||||||
use std::cmp::Ordering;
|
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.
|
||||||
|
///
|
||||||
|
/// 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 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.
|
||||||
|
///
|
||||||
|
/// 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)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
#[serde(untagged)]
|
#[serde(untagged)]
|
||||||
pub enum Value {
|
pub enum Value {
|
||||||
|
/// 32-bit signed integer. Used for most loop counters and indices.
|
||||||
Int32(i32),
|
Int32(i32),
|
||||||
|
/// 64-bit signed integer. Used for large numbers and timestamps.
|
||||||
Int64(i64),
|
Int64(i64),
|
||||||
|
/// 64-bit double precision float. Used for physics and complex math.
|
||||||
Float(f64),
|
Float(f64),
|
||||||
|
/// Boolean value (true/false).
|
||||||
Boolean(bool),
|
Boolean(bool),
|
||||||
String(String),
|
/// UTF-8 string. Strings are immutable and usually come from the Constant Pool.
|
||||||
Ref(usize), // Heap reference
|
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`).
|
||||||
Null,
|
Null,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,7 +64,7 @@ impl PartialEq for Value {
|
|||||||
(Value::Float(a), Value::Int64(b)) => *a == *b as f64,
|
(Value::Float(a), Value::Int64(b)) => *a == *b as f64,
|
||||||
(Value::Boolean(a), Value::Boolean(b)) => a == b,
|
(Value::Boolean(a), Value::Boolean(b)) => a == b,
|
||||||
(Value::String(a), Value::String(b)) => a == b,
|
(Value::String(a), Value::String(b)) => a == b,
|
||||||
(Value::Ref(a), Value::Ref(b)) => a == b,
|
(Value::HeapRef(a), Value::HeapRef(b)) => a == b,
|
||||||
(Value::Null, Value::Null) => true,
|
(Value::Null, Value::Null) => true,
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
@@ -54,6 +91,14 @@ impl PartialOrd for Value {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl 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> {
|
pub fn as_float(&self) -> Option<f64> {
|
||||||
match self {
|
match self {
|
||||||
Value::Int32(i) => Some(*i as f64),
|
Value::Int32(i) => Some(*i as f64),
|
||||||
@@ -71,6 +116,48 @@ impl Value {
|
|||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) => 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)]
|
#[cfg(test)]
|
||||||
@@ -116,4 +203,4 @@ mod tests {
|
|||||||
assert_eq!(v_bool.as_float(), None);
|
assert_eq!(v_bool.as_float(), None);
|
||||||
assert_eq!(v_bool.as_integer(), None);
|
assert_eq!(v_bool.as_integer(), None);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
use prometeu_bytecode::isa::core::CoreOpCode;
|
||||||
|
use prometeu_bytecode::{assemble, disassemble};
|
||||||
|
|
||||||
|
fn emit(op: CoreOpCode, imm: Option<&[u8]>, out: &mut Vec<u8>) {
|
||||||
|
out.extend_from_slice(&(op as u16).to_le_bytes());
|
||||||
|
if let Some(bytes) = imm {
|
||||||
|
out.extend_from_slice(bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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();
|
||||||
|
|
||||||
|
emit(CoreOpCode::PushI32, Some(&7i32.to_le_bytes()), &mut prog);
|
||||||
|
// MAKE_CLOSURE (fn=1, captures=0)
|
||||||
|
let mut mc = [0u8; 8];
|
||||||
|
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
|
||||||
|
emit(CoreOpCode::CallClosure, Some(&1u32.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 gfx2d.draw_line (0x1003)
|
||||||
|
emit(CoreOpCode::Syscall, Some(&0x1003u32.to_le_bytes()), &mut prog);
|
||||||
|
// FRAME_SYNC
|
||||||
|
emit(CoreOpCode::FrameSync, None, &mut prog);
|
||||||
|
// HALT
|
||||||
|
emit(CoreOpCode::Halt, None, &mut prog);
|
||||||
|
|
||||||
|
let text = disassemble(&prog).expect("disasm ok");
|
||||||
|
let rebuilt = assemble(&text).expect("assemble ok");
|
||||||
|
assert_eq!(rebuilt, prog, "re-assembled bytes must match original");
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
use prometeu_bytecode::disassemble;
|
||||||
|
use prometeu_bytecode::isa::core::CoreOpCode;
|
||||||
|
|
||||||
|
fn emit(op: CoreOpCode, imm: Option<&[u8]>, out: &mut Vec<u8>) {
|
||||||
|
out.extend_from_slice(&(op as u16).to_le_bytes());
|
||||||
|
if let Some(bytes) = imm {
|
||||||
|
out.extend_from_slice(bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn snapshot_representative_program_is_stable() {
|
||||||
|
let mut prog = Vec::new();
|
||||||
|
emit(CoreOpCode::PushI32, Some(&7i32.to_le_bytes()), &mut prog);
|
||||||
|
// MAKE_CLOSURE (fn=1, captures=0)
|
||||||
|
let mut mc = [0u8; 8];
|
||||||
|
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 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);
|
||||||
|
// HOSTCALL 2
|
||||||
|
emit(CoreOpCode::Hostcall, Some(&2u32.to_le_bytes()), &mut prog);
|
||||||
|
// SYSCALL 0x1003
|
||||||
|
emit(CoreOpCode::Syscall, Some(&0x1003u32.to_le_bytes()), &mut prog);
|
||||||
|
// FRAME_SYNC
|
||||||
|
emit(CoreOpCode::FrameSync, None, &mut prog);
|
||||||
|
// HALT
|
||||||
|
emit(CoreOpCode::Halt, None, &mut prog);
|
||||||
|
|
||||||
|
let text = disassemble(&prog).expect("disasm ok");
|
||||||
|
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,206 @@
|
|||||||
|
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),
|
||||||
|
];
|
||||||
|
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, &[0x97, 0]),
|
||||||
|
Err(DecodeError::UnknownOpcode { opcode: 0x97, .. })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
#[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),
|
||||||
|
] {
|
||||||
|
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",
|
||||||
|
] {
|
||||||
|
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",
|
||||||
|
] {
|
||||||
|
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
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,160 @@
|
|||||||
|
use prometeu_bytecode::decode_next;
|
||||||
|
use prometeu_bytecode::isa::core::{CoreOpCode, CoreOpCodeSpecExt};
|
||||||
|
|
||||||
|
fn encode_instr(op: CoreOpCode, imm: Option<&[u8]>) -> Vec<u8> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let code = op as u16;
|
||||||
|
out.extend_from_slice(&code.to_le_bytes());
|
||||||
|
let spec = op.spec();
|
||||||
|
let need = spec.imm_bytes as usize;
|
||||||
|
match (need, imm) {
|
||||||
|
(0, None) => {}
|
||||||
|
(n, Some(bytes)) if bytes.len() == n => out.extend_from_slice(bytes),
|
||||||
|
(n, Some(bytes)) => {
|
||||||
|
panic!("immediate size mismatch for {:?}: expected {}, got {}", op, n, bytes.len())
|
||||||
|
}
|
||||||
|
(n, None) => panic!("missing immediate for {:?}: need {} bytes", op, n),
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn disasm(bytes: &[u8]) -> String {
|
||||||
|
// Minimal test-only disasm: NAME [operands]
|
||||||
|
let mut pc = 0usize;
|
||||||
|
let mut lines = Vec::new();
|
||||||
|
while pc < bytes.len() {
|
||||||
|
match decode_next(pc, bytes) {
|
||||||
|
Ok(instr) => {
|
||||||
|
let name = instr.opcode.spec().name;
|
||||||
|
let mut line = String::from(name);
|
||||||
|
let imm_len = instr.opcode.spec().imm_bytes as usize;
|
||||||
|
if imm_len > 0 {
|
||||||
|
// Heuristic formatting based on known op immediates
|
||||||
|
line.push(' ');
|
||||||
|
let s = match instr.opcode {
|
||||||
|
CoreOpCode::Jmp | CoreOpCode::JmpIfFalse | CoreOpCode::JmpIfTrue => {
|
||||||
|
format!("{}", instr.imm_u32().unwrap())
|
||||||
|
}
|
||||||
|
CoreOpCode::PushI64 => format!("{}", instr.imm_i64().unwrap()),
|
||||||
|
CoreOpCode::PushF64 => format!("{}", instr.imm_f64().unwrap()),
|
||||||
|
CoreOpCode::PushBool => format!("{}", instr.imm_u8().unwrap()),
|
||||||
|
CoreOpCode::PushI32 => format!("{}", instr.imm_i32().unwrap()),
|
||||||
|
CoreOpCode::PopN | CoreOpCode::PushConst | CoreOpCode::Hostcall => {
|
||||||
|
format!("{}", instr.imm_u32().unwrap())
|
||||||
|
}
|
||||||
|
CoreOpCode::Syscall | CoreOpCode::Intrinsic => {
|
||||||
|
format!("0x{}", hex::encode(instr.imm))
|
||||||
|
}
|
||||||
|
_ => format!("0x{}", hex::encode(instr.imm)),
|
||||||
|
};
|
||||||
|
line.push_str(&s);
|
||||||
|
}
|
||||||
|
lines.push(line);
|
||||||
|
pc = instr.next_pc;
|
||||||
|
}
|
||||||
|
Err(_) => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encode_decode_roundtrip_preserves_structure() {
|
||||||
|
// Program: PUSH_I32 42; PUSH_I32 100; ADD; PUSH_BOOL 1; JMP 12; NOP; HALT
|
||||||
|
let mut prog = Vec::new();
|
||||||
|
prog.extend(encode_instr(CoreOpCode::PushI32, Some(&42i32.to_le_bytes())));
|
||||||
|
prog.extend(encode_instr(CoreOpCode::PushI32, Some(&100i32.to_le_bytes())));
|
||||||
|
prog.extend(encode_instr(CoreOpCode::Add, None));
|
||||||
|
prog.extend(encode_instr(CoreOpCode::PushBool, Some(&[1u8])));
|
||||||
|
// Jump to the HALT (compute absolute PC within this byte slice)
|
||||||
|
// Current pc after previous: 2+4 + 2+4 + 2 + 2+1 = 17 bytes
|
||||||
|
// Next we place: JMP (2+4), NOP (2), HALT (2)
|
||||||
|
// We want JMP target to land at the HALT's pc
|
||||||
|
let jmp_target: u32 = 17 + 2 + 4 + 2; // pc where HALT starts
|
||||||
|
prog.extend(encode_instr(CoreOpCode::Jmp, Some(&jmp_target.to_le_bytes())));
|
||||||
|
prog.extend(encode_instr(CoreOpCode::Nop, None));
|
||||||
|
prog.extend(encode_instr(CoreOpCode::Halt, None));
|
||||||
|
|
||||||
|
// Decode sequentially and check opcodes and immediates
|
||||||
|
let mut pc = 0usize;
|
||||||
|
let mut seen = Vec::new();
|
||||||
|
while pc < prog.len() {
|
||||||
|
let instr = decode_next(pc, &prog).expect("decode ok");
|
||||||
|
seen.push(instr);
|
||||||
|
pc = instr.next_pc;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert_eq!(seen.len(), 7);
|
||||||
|
assert_eq!(seen[0].opcode, CoreOpCode::PushI32);
|
||||||
|
assert_eq!(seen[0].imm_i32().unwrap(), 42);
|
||||||
|
assert_eq!(seen[1].opcode, CoreOpCode::PushI32);
|
||||||
|
assert_eq!(seen[1].imm_i32().unwrap(), 100);
|
||||||
|
assert_eq!(seen[2].opcode, CoreOpCode::Add);
|
||||||
|
assert_eq!(seen[3].opcode, CoreOpCode::PushBool);
|
||||||
|
assert_eq!(seen[3].imm_u8().unwrap(), 1);
|
||||||
|
assert_eq!(seen[4].opcode, CoreOpCode::Jmp);
|
||||||
|
assert_eq!(seen[4].imm_u32().unwrap(), jmp_target);
|
||||||
|
assert_eq!(seen[5].opcode, CoreOpCode::Nop);
|
||||||
|
assert_eq!(seen[6].opcode, CoreOpCode::Halt);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn disasm_contains_expected_mnemonics_and_operands() {
|
||||||
|
// Tiny deterministic sample: NOP; PUSH_I32 -7; PUSH_BOOL 0; ADD; HALT
|
||||||
|
let mut prog = Vec::new();
|
||||||
|
prog.extend(encode_instr(CoreOpCode::Nop, None));
|
||||||
|
prog.extend(encode_instr(CoreOpCode::PushI32, Some(&(-7i32).to_le_bytes())));
|
||||||
|
prog.extend(encode_instr(CoreOpCode::PushBool, Some(&[0u8])));
|
||||||
|
prog.extend(encode_instr(CoreOpCode::Add, None));
|
||||||
|
prog.extend(encode_instr(CoreOpCode::Halt, None));
|
||||||
|
|
||||||
|
let text = disasm(&prog);
|
||||||
|
|
||||||
|
// Must contain stable opcode names and operand text
|
||||||
|
assert!(text.contains("NOP"));
|
||||||
|
assert!(text.contains("PUSH_I32 -7"));
|
||||||
|
assert!(text.contains("PUSH_BOOL 0"));
|
||||||
|
assert!(text.contains("ADD"));
|
||||||
|
assert!(text.contains("HALT"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostcall_roundtrips_with_decimal_index() {
|
||||||
|
let mut prog = Vec::new();
|
||||||
|
prog.extend(encode_instr(CoreOpCode::Hostcall, Some(&7u32.to_le_bytes())));
|
||||||
|
prog.extend(encode_instr(CoreOpCode::Halt, None));
|
||||||
|
|
||||||
|
let text = disasm(&prog);
|
||||||
|
|
||||||
|
assert!(text.contains("HOSTCALL 7"));
|
||||||
|
|
||||||
|
let rebuilt = prometeu_bytecode::assemble(&text).expect("assemble hostcall");
|
||||||
|
assert_eq!(rebuilt, prog);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn intrinsic_roundtrips_with_hex_id() {
|
||||||
|
let mut prog = Vec::new();
|
||||||
|
prog.extend(encode_instr(CoreOpCode::Intrinsic, Some(&0x1000u32.to_le_bytes())));
|
||||||
|
prog.extend(encode_instr(CoreOpCode::Halt, None));
|
||||||
|
|
||||||
|
let text = prometeu_bytecode::disassemble(&prog).expect("disasm intrinsic");
|
||||||
|
|
||||||
|
assert!(text.contains("INTRINSIC 0x1000"));
|
||||||
|
|
||||||
|
let rebuilt = prometeu_bytecode::assemble(&text).expect("assemble intrinsic");
|
||||||
|
assert_eq!(rebuilt, prog);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Minimal hex helper to avoid extra deps in tests
|
||||||
|
mod hex {
|
||||||
|
pub fn encode(bytes: &[u8]) -> String {
|
||||||
|
let mut s = String::with_capacity(bytes.len() * 2);
|
||||||
|
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||||
|
for &b in bytes {
|
||||||
|
s.push(HEX[(b >> 4) as usize] as char);
|
||||||
|
s.push(HEX[(b & 0x0f) as usize] as char);
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[package]
|
||||||
|
name = "prometeu-drivers"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
license.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
serde_json = "1.0.149"
|
||||||
|
prometeu-hal = { path = "../prometeu-hal" }
|
||||||
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]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,445 @@
|
|||||||
|
use prometeu_hal::{AudioBridge, AudioOpStatus};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
/// Maximum number of simultaneous audio voices supported by the hardware.
|
||||||
|
pub const MAX_CHANNELS: usize = 16;
|
||||||
|
/// Standard sample rate for the final audio output.
|
||||||
|
pub const OUTPUT_SAMPLE_RATE: u32 = 48000;
|
||||||
|
|
||||||
|
use crate::memory_banks::SoundBankPoolAccess;
|
||||||
|
/// Looping mode for samples (re-exported from the hardware contract).
|
||||||
|
pub use prometeu_hal::LoopMode;
|
||||||
|
use prometeu_hal::sample::Sample;
|
||||||
|
|
||||||
|
/// State of a single playback voice (channel).
|
||||||
|
///
|
||||||
|
/// 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>>,
|
||||||
|
/// Whether this channel is currently active.
|
||||||
|
pub active: bool,
|
||||||
|
/// Current playback position within the sample (fractional for pitch shifting).
|
||||||
|
pub pos: f64,
|
||||||
|
/// Playback speed multiplier (1.0 = original speed).
|
||||||
|
pub pitch: f64,
|
||||||
|
/// Voice volume (0-255).
|
||||||
|
pub volume: u8,
|
||||||
|
/// Stereo panning (0=Full Left, 127=Center, 255=Full Right).
|
||||||
|
pub pan: u8,
|
||||||
|
/// Loop configuration for this voice.
|
||||||
|
pub loop_mode: LoopMode,
|
||||||
|
/// Internal priority metadata; the guest explicitly selects its voice.
|
||||||
|
pub priority: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Channel {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
sample: None,
|
||||||
|
active: false,
|
||||||
|
pos: 0.0,
|
||||||
|
pitch: 1.0,
|
||||||
|
volume: 255,
|
||||||
|
pan: 127,
|
||||||
|
loop_mode: LoopMode::Off,
|
||||||
|
priority: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commands sent from the Core to the Host audio backend.
|
||||||
|
///
|
||||||
|
/// Because the Core logic runs at 60Hz and Audio is generated at 48kHz,
|
||||||
|
/// we use an asynchronous command queue to synchronize them.
|
||||||
|
pub enum AudioCommand {
|
||||||
|
/// Start playing a sample on a specific voice.
|
||||||
|
Play {
|
||||||
|
sample: Arc<Sample>,
|
||||||
|
voice_id: usize,
|
||||||
|
volume: u8,
|
||||||
|
pan: u8,
|
||||||
|
pitch: f64,
|
||||||
|
priority: u8,
|
||||||
|
loop_mode: LoopMode,
|
||||||
|
},
|
||||||
|
/// 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 },
|
||||||
|
/// Update panning of an ongoing playback.
|
||||||
|
SetPan { voice_id: usize, pan: u8 },
|
||||||
|
/// Update pitch of an ongoing playback.
|
||||||
|
SetPitch { voice_id: usize, pitch: f64 },
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
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,
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
};
|
||||||
|
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>,
|
||||||
|
voice_id: usize,
|
||||||
|
volume: u8,
|
||||||
|
pan: u8,
|
||||||
|
pitch: f64,
|
||||||
|
priority: u8,
|
||||||
|
loop_mode: LoopMode,
|
||||||
|
) -> AudioOpStatus {
|
||||||
|
if voice_id >= MAX_CHANNELS {
|
||||||
|
return AudioOpStatus::VoiceInvalid;
|
||||||
|
}
|
||||||
|
if !pitch.is_finite() || pitch <= 0.0 {
|
||||||
|
return AudioOpStatus::ArgRangeInvalid;
|
||||||
|
}
|
||||||
|
self.enqueue(
|
||||||
|
voice_id,
|
||||||
|
AudioCommand::Play { sample, voice_id, volume, pan, pitch, priority, loop_mode },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
if !pitch.is_finite() || pitch <= 0.0 {
|
||||||
|
return AudioOpStatus::ArgRangeInvalid;
|
||||||
|
}
|
||||||
|
self.enqueue(voice_id, AudioCommand::SetPitch { voice_id, pitch })
|
||||||
|
}
|
||||||
|
fn ready(&self) -> bool {
|
||||||
|
self.transport.ready()
|
||||||
|
}
|
||||||
|
fn begin_frame(&mut self) { /* Staging may already contain debugger steps. */
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::memory_banks::{MemoryBanks, SoundBankPoolAccess, SoundBankPoolInstaller};
|
||||||
|
use prometeu_hal::sound_bank::SoundBank;
|
||||||
|
|
||||||
|
fn sample() -> Arc<Sample> {
|
||||||
|
Arc::new(Sample::new(44_100, vec![0, 1, 0, -1]))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn play_returns_voice_invalid_for_out_of_range_voice() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
let sound_banks = Arc::clone(&banks) as Arc<dyn SoundBankPoolAccess>;
|
||||||
|
let mut audio = Audio::new(sound_banks);
|
||||||
|
|
||||||
|
let status = audio.play(0, 0, MAX_CHANNELS, 255, 128, 1.0, 0, LoopMode::Off);
|
||||||
|
|
||||||
|
assert_eq!(status, AudioOpStatus::VoiceInvalid);
|
||||||
|
assert!(audio.commands.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn play_returns_sample_not_found_when_sample_is_missing() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
let installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
|
||||||
|
installer.install_sound_bank(0, Arc::new(SoundBank::new(vec![sample()])));
|
||||||
|
let sound_banks = Arc::clone(&banks) as Arc<dyn SoundBankPoolAccess>;
|
||||||
|
let mut audio = Audio::new(sound_banks);
|
||||||
|
|
||||||
|
let status = audio.play(0, 1, 0, 255, 128, 1.0, 0, LoopMode::Off);
|
||||||
|
|
||||||
|
assert_eq!(status, AudioOpStatus::SampleNotFound);
|
||||||
|
assert!(audio.commands.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn play_sample_returns_voice_invalid_without_side_effects() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
let sound_banks = Arc::clone(&banks) as Arc<dyn SoundBankPoolAccess>;
|
||||||
|
let mut audio = Audio::new(sound_banks);
|
||||||
|
|
||||||
|
let status = audio.play_sample(sample(), MAX_CHANNELS, 255, 128, 1.0, 0, LoopMode::Off);
|
||||||
|
|
||||||
|
assert_eq!(status, AudioOpStatus::VoiceInvalid);
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,472 @@
|
|||||||
|
use crate::asset::AssetManager;
|
||||||
|
use crate::audio::Audio;
|
||||||
|
use crate::frame_composer::FrameComposer;
|
||||||
|
use crate::gfx::Gfx;
|
||||||
|
use crate::memory_banks::{
|
||||||
|
GlyphBankPoolAccess, GlyphBankPoolInstaller, MemoryBanks, SceneBankPoolAccess,
|
||||||
|
SceneBankPoolInstaller, SoundBankPoolAccess, SoundBankPoolInstaller,
|
||||||
|
};
|
||||||
|
use crate::pad::Pad;
|
||||||
|
use crate::touch::Touch;
|
||||||
|
use prometeu_hal::cartridge::AssetsPayloadSource;
|
||||||
|
use prometeu_hal::sprite::Sprite;
|
||||||
|
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.
|
||||||
|
///
|
||||||
|
/// This struct represents the "Mainboard" of the PROMETEU console.
|
||||||
|
/// It acts as a container for all hardware subsystems. In the Prometeu
|
||||||
|
/// architecture, hardware is decoupled from the OS and VM, allowing
|
||||||
|
/// for easier testing and different host implementations (Desktop, Web, etc.).
|
||||||
|
///
|
||||||
|
/// ### Console Specifications:
|
||||||
|
/// - **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.
|
||||||
|
pub frame_composer: FrameComposer,
|
||||||
|
/// The Sound Processing Unit (SPU). Manages sample playback and volume control.
|
||||||
|
pub audio: Audio,
|
||||||
|
/// The standard digital gamepad. Provides state for D-Pad, face buttons, and triggers.
|
||||||
|
pub pad: Pad,
|
||||||
|
/// The absolute pointer input device (Mouse/Touchscreen).
|
||||||
|
pub touch: Touch,
|
||||||
|
/// The Asset Management system (DMA). Handles loading data into VRAM (GlyphBanks) and ARAM (SoundBanks).
|
||||||
|
pub assets: AssetManager,
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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.frame_composer.begin_frame();
|
||||||
|
}
|
||||||
|
|
||||||
|
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) -> prometeu_hal::ComposerOpStatus {
|
||||||
|
self.frame_composer.set_camera(x, y);
|
||||||
|
prometeu_hal::ComposerOpStatus::Ok
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = 480;
|
||||||
|
/// Internal hardware height in pixels.
|
||||||
|
pub const H: usize = 270;
|
||||||
|
|
||||||
|
/// Creates a fresh hardware instance with default settings.
|
||||||
|
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>,
|
||||||
|
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,
|
||||||
|
Arc::clone(&memory_banks) as Arc<dyn GlyphBankPoolAccess>,
|
||||||
|
),
|
||||||
|
frame_composer: FrameComposer::new(
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::memory_banks::{
|
||||||
|
GlyphBankPoolInstaller, SceneBankPoolAccess, SceneBankPoolInstaller,
|
||||||
|
};
|
||||||
|
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.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_asset_id,
|
||||||
|
tile_size: TileSize::Size8,
|
||||||
|
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||||
|
tilemap: TileMap {
|
||||||
|
width: 4,
|
||||||
|
height: 4,
|
||||||
|
tiles: vec![
|
||||||
|
Tile {
|
||||||
|
active: true,
|
||||||
|
glyph: Glyph { glyph_id: 0, palette_id: 0 },
|
||||||
|
flip_x: false,
|
||||||
|
flip_y: false,
|
||||||
|
};
|
||||||
|
16
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
SceneBank { layers: std::array::from_fn(|_| layer.clone()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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_with_glyph_asset_id(0)));
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
let mut resolver = SceneViewportResolver::new(16, 16, 4, 4, 12, 20);
|
||||||
|
let update = resolver.update(&scene, 0, 0);
|
||||||
|
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hardware_constructs_frame_composer_with_shared_scene_bank_access() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
banks.install_scene_bank(2, Arc::new(make_scene()));
|
||||||
|
|
||||||
|
let hardware =
|
||||||
|
Hardware::new_with_memory_banks(banks, Arc::new(crate::ControlledWallClock::default()));
|
||||||
|
let scene = hardware
|
||||||
|
.frame_composer
|
||||||
|
.scene_bank_slot(2)
|
||||||
|
.expect("scene bank slot 2 should be resident");
|
||||||
|
|
||||||
|
assert_eq!(hardware.frame_composer.viewport_size(), (Hardware::W, Hardware::H));
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
mod asset;
|
||||||
|
mod audio;
|
||||||
|
mod frame_composer;
|
||||||
|
mod gfx;
|
||||||
|
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, 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::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,119 @@
|
|||||||
|
//! 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::ReadOnly,
|
||||||
|
K::StorageFull => Error::NoSpace,
|
||||||
|
K::InvalidInput | K::UnexpectedEof => Error::InvalidRange,
|
||||||
|
K::Unsupported => Error::Unsupported,
|
||||||
|
_ => Error::IoError,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl FileMemcard {
|
||||||
|
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)?;
|
||||||
|
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 result = (|| {
|
||||||
|
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)?;
|
||||||
|
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(io_error)?;
|
||||||
|
Ok(card)
|
||||||
|
}
|
||||||
|
Err(e) => Err(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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
//! 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};
|
||||||
|
|
||||||
|
/// Non-generic interface for peripherals to access graphical glyph banks.
|
||||||
|
pub trait GlyphBankPoolAccess: Send + Sync {
|
||||||
|
/// Returns a reference to the resident GlyphBank in the specified slot, if any.
|
||||||
|
fn glyph_bank_slot(&self, slot: usize) -> Option<Arc<GlyphBank>>;
|
||||||
|
/// Returns the total number of slots available in this bank.
|
||||||
|
fn glyph_bank_slot_count(&self) -> usize;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Non-generic interface for the AssetManager to install graphical glyph banks.
|
||||||
|
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.
|
||||||
|
pub trait SoundBankPoolAccess: Send + Sync {
|
||||||
|
/// Returns a reference to the resident SoundBank in the specified slot, if any.
|
||||||
|
fn sound_bank_slot(&self, slot: usize) -> Option<Arc<SoundBank>>;
|
||||||
|
/// Returns the total number of slots available in this bank.
|
||||||
|
fn sound_bank_slot_count(&self) -> usize;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Non-generic interface for the AssetManager to install sound banks.
|
||||||
|
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.
|
||||||
|
pub trait SceneBankPoolAccess: Send + Sync {
|
||||||
|
/// Returns a reference to the resident SceneBank in the specified slot, if any.
|
||||||
|
fn scene_bank_slot(&self, slot: usize) -> Option<Arc<SceneBank>>;
|
||||||
|
/// Returns the total number of slots available in this bank.
|
||||||
|
fn scene_bank_slot_count(&self) -> usize;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Non-generic interface for the AssetManager to install scene banks.
|
||||||
|
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.
|
||||||
|
///
|
||||||
|
/// MemoryBanks represent the actual hardware slot state.
|
||||||
|
/// Peripherals consume this state via narrow, non-generic traits.
|
||||||
|
/// AssetManager coordinates residency and installs assets into these slots.
|
||||||
|
pub struct MemoryBanks {
|
||||||
|
glyph_bank_pool: Arc<RwLock<[Option<Arc<GlyphBank>>; 16]>>,
|
||||||
|
sound_bank_pool: Arc<RwLock<[Option<Arc<SoundBank>>; 16]>>,
|
||||||
|
scene_bank_pool: Arc<RwLock<[Option<Arc<SceneBank>>; 16]>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for MemoryBanks {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MemoryBanks {
|
||||||
|
/// Creates a new set of memory banks with empty slots.
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
glyph_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
|
||||||
|
sound_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
|
||||||
|
scene_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GlyphBankPoolAccess for MemoryBanks {
|
||||||
|
fn glyph_bank_slot(&self, slot: usize) -> Option<Arc<GlyphBank>> {
|
||||||
|
let pool = self.glyph_bank_pool.read().unwrap();
|
||||||
|
pool.get(slot).and_then(|s| s.as_ref().map(Arc::clone))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn glyph_bank_slot_count(&self) -> usize {
|
||||||
|
16
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GlyphBankPoolInstaller for MemoryBanks {
|
||||||
|
fn install_glyph_bank(&self, slot: usize, bank: Arc<GlyphBank>) {
|
||||||
|
let mut pool = self.glyph_bank_pool.write().unwrap();
|
||||||
|
if slot < 16 {
|
||||||
|
pool[slot] = Some(bank);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear_glyph_banks(&self) {
|
||||||
|
self.glyph_bank_pool.write().unwrap().fill(None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SoundBankPoolAccess for MemoryBanks {
|
||||||
|
fn sound_bank_slot(&self, slot: usize) -> Option<Arc<SoundBank>> {
|
||||||
|
let pool = self.sound_bank_pool.read().unwrap();
|
||||||
|
pool.get(slot).and_then(|s| s.as_ref().map(Arc::clone))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sound_bank_slot_count(&self) -> usize {
|
||||||
|
16
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SoundBankPoolInstaller for MemoryBanks {
|
||||||
|
fn install_sound_bank(&self, slot: usize, bank: Arc<SoundBank>) {
|
||||||
|
let mut pool = self.sound_bank_pool.write().unwrap();
|
||||||
|
if slot < 16 {
|
||||||
|
pool[slot] = Some(bank);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear_sound_banks(&self) {
|
||||||
|
self.sound_bank_pool.write().unwrap().fill(None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SceneBankPoolAccess for MemoryBanks {
|
||||||
|
fn scene_bank_slot(&self, slot: usize) -> Option<Arc<SceneBank>> {
|
||||||
|
let pool = self.scene_bank_pool.read().unwrap();
|
||||||
|
pool.get(slot).and_then(|s| s.as_ref().map(Arc::clone))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scene_bank_slot_count(&self) -> usize {
|
||||||
|
16
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SceneBankPoolInstaller for MemoryBanks {
|
||||||
|
fn install_scene_bank(&self, slot: usize, bank: Arc<SceneBank>) {
|
||||||
|
let mut pool = self.scene_bank_pool.write().unwrap();
|
||||||
|
if slot < 16 {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+54
-10
@@ -1,5 +1,5 @@
|
|||||||
use crate::model::Button;
|
use prometeu_hal::button::Button;
|
||||||
use crate::hardware::input_signal::InputSignals;
|
use prometeu_hal::{InputSignals, PadBridge};
|
||||||
|
|
||||||
#[derive(Default, Clone, Copy, Debug)]
|
#[derive(Default, Clone, Copy, Debug)]
|
||||||
pub struct Pad {
|
pub struct Pad {
|
||||||
@@ -10,13 +10,59 @@ pub struct Pad {
|
|||||||
|
|
||||||
pub a: Button, // ps: square
|
pub a: Button, // ps: square
|
||||||
pub b: Button, // ps: circle
|
pub b: Button, // ps: circle
|
||||||
pub x: Button, // ps: triangle
|
pub x: Button, // ps: triangle
|
||||||
pub y: Button, // ps: cross
|
pub y: Button, // ps: cross
|
||||||
pub l: Button, // ps: R
|
pub l: Button, // ps: R
|
||||||
pub r: Button, // ps: L
|
pub r: Button, // ps: L
|
||||||
|
|
||||||
pub start: Button,
|
pub start: Button,
|
||||||
pub select: Button,
|
pub select: Button,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PadBridge for Pad {
|
||||||
|
fn begin_frame(&mut self, signals: &InputSignals) {
|
||||||
|
self.begin_frame(signals)
|
||||||
|
}
|
||||||
|
fn any(&self) -> bool {
|
||||||
|
self.any()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn up(&self) -> &Button {
|
||||||
|
&self.up
|
||||||
|
}
|
||||||
|
fn down(&self) -> &Button {
|
||||||
|
&self.down
|
||||||
|
}
|
||||||
|
fn left(&self) -> &Button {
|
||||||
|
&self.left
|
||||||
|
}
|
||||||
|
fn right(&self) -> &Button {
|
||||||
|
&self.right
|
||||||
|
}
|
||||||
|
fn a(&self) -> &Button {
|
||||||
|
&self.a
|
||||||
|
}
|
||||||
|
fn b(&self) -> &Button {
|
||||||
|
&self.b
|
||||||
|
}
|
||||||
|
fn x(&self) -> &Button {
|
||||||
|
&self.x
|
||||||
|
}
|
||||||
|
fn y(&self) -> &Button {
|
||||||
|
&self.y
|
||||||
|
}
|
||||||
|
fn l(&self) -> &Button {
|
||||||
|
&self.l
|
||||||
|
}
|
||||||
|
fn r(&self) -> &Button {
|
||||||
|
&self.r
|
||||||
|
}
|
||||||
|
fn start(&self) -> &Button {
|
||||||
|
&self.start
|
||||||
|
}
|
||||||
|
fn select(&self) -> &Button {
|
||||||
|
&self.select
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Pad {
|
impl Pad {
|
||||||
@@ -25,18 +71,18 @@ impl Pad {
|
|||||||
self.down.begin_frame(signals.down_signal);
|
self.down.begin_frame(signals.down_signal);
|
||||||
self.left.begin_frame(signals.left_signal);
|
self.left.begin_frame(signals.left_signal);
|
||||||
self.right.begin_frame(signals.right_signal);
|
self.right.begin_frame(signals.right_signal);
|
||||||
|
|
||||||
self.a.begin_frame(signals.a_signal);
|
self.a.begin_frame(signals.a_signal);
|
||||||
self.b.begin_frame(signals.b_signal);
|
self.b.begin_frame(signals.b_signal);
|
||||||
self.x.begin_frame(signals.x_signal);
|
self.x.begin_frame(signals.x_signal);
|
||||||
self.y.begin_frame(signals.y_signal);
|
self.y.begin_frame(signals.y_signal);
|
||||||
self.l.begin_frame(signals.l_signal);
|
self.l.begin_frame(signals.l_signal);
|
||||||
self.r.begin_frame(signals.r_signal);
|
self.r.begin_frame(signals.r_signal);
|
||||||
|
|
||||||
self.start.begin_frame(signals.start_signal);
|
self.start.begin_frame(signals.start_signal);
|
||||||
self.select.begin_frame(signals.select_signal);
|
self.select.begin_frame(signals.select_signal);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn any(&self) -> bool {
|
pub fn any(&self) -> bool {
|
||||||
self.a.down
|
self.a.down
|
||||||
|| self.b.down
|
|| self.b.down
|
||||||
@@ -48,5 +94,3 @@ impl Pad {
|
|||||||
|| self.select.down
|
|| self.select.down
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -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,33 @@
|
|||||||
|
use prometeu_hal::button::Button;
|
||||||
|
use prometeu_hal::{InputSignals, TouchBridge};
|
||||||
|
|
||||||
|
#[derive(Default, Clone, Copy, Debug)]
|
||||||
|
pub struct Touch {
|
||||||
|
pub f: Button,
|
||||||
|
pub x: i32,
|
||||||
|
pub y: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Touch {
|
||||||
|
/// Transient flags should last only 1 frame.
|
||||||
|
pub fn begin_frame(&mut self, signals: &InputSignals) {
|
||||||
|
self.f.begin_frame(signals.f_signal);
|
||||||
|
self.x = signals.x_pos;
|
||||||
|
self.y = signals.y_pos;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TouchBridge for Touch {
|
||||||
|
fn begin_frame(&mut self, signals: &InputSignals) {
|
||||||
|
self.begin_frame(signals)
|
||||||
|
}
|
||||||
|
fn f(&self) -> &Button {
|
||||||
|
&self.f
|
||||||
|
}
|
||||||
|
fn x(&self) -> i32 {
|
||||||
|
self.x
|
||||||
|
}
|
||||||
|
fn y(&self) -> i32 {
|
||||||
|
self.y
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
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.
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
[package]
|
||||||
|
name = "prometeu-firmware"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
license.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
prometeu-vm = { path = "../prometeu-vm" }
|
||||||
|
prometeu-system = { path = "../prometeu-system" }
|
||||||
|
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" }
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
|
pub enum BootTarget {
|
||||||
|
#[default]
|
||||||
|
Hub,
|
||||||
|
Cartridge {
|
||||||
|
path: String,
|
||||||
|
debug: bool,
|
||||||
|
debug_port: u16,
|
||||||
|
},
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
+14
-7
@@ -1,10 +1,12 @@
|
|||||||
pub use crate::firmware::firmware_step_reset::ResetStep;
|
pub use crate::firmware::firmware_step_confirm_discard::ConfirmDiscardStep;
|
||||||
pub use crate::firmware::firmware_step_splash_screen::SplashScreenStep;
|
|
||||||
pub use crate::firmware::firmware_step_launch_hub::LaunchHubStep;
|
|
||||||
pub use crate::firmware::firmware_step_hub_home::HubHomeStep;
|
|
||||||
pub use crate::firmware::firmware_step_load_cartridge::LoadCartridgeStep;
|
|
||||||
pub use crate::firmware::firmware_step_game_running::GameRunningStep;
|
|
||||||
pub use crate::firmware::firmware_step_crash_screen::AppCrashesStep;
|
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)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum FirmwareState {
|
pub enum FirmwareState {
|
||||||
@@ -12,7 +14,12 @@ pub enum FirmwareState {
|
|||||||
SplashScreen(SplashScreenStep),
|
SplashScreen(SplashScreenStep),
|
||||||
LaunchHub(LaunchHubStep),
|
LaunchHub(LaunchHubStep),
|
||||||
HubHome(HubHomeStep),
|
HubHome(HubHomeStep),
|
||||||
|
ConfirmDiscard(ConfirmDiscardStep),
|
||||||
LoadCartridge(LoadCartridgeStep),
|
LoadCartridge(LoadCartridgeStep),
|
||||||
|
ResumeResidentGame,
|
||||||
|
MemoryIoFault,
|
||||||
|
MemoryCardRemoved(super::firmware_step_confirm_discard::MemoryCardRemovedStep),
|
||||||
GameRunning(GameRunningStep),
|
GameRunning(GameRunningStep),
|
||||||
|
ShellRunning(ShellRunningStep),
|
||||||
AppCrashes(AppCrashesStep),
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
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)]
|
||||||
|
pub struct AppCrashesStep {
|
||||||
|
pub report: CrashReport,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppCrashesStep {
|
||||||
|
pub fn log_message(&self) -> String {
|
||||||
|
format!("App Crashed: {}", self.report)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
|
ctx.os.log(LogLevel::Error, LogSource::Pos, self.report.log_tag(), self.log_message());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
|
// Update peripherals for input on the crash screen
|
||||||
|
ctx.platform.input_mut().pad_mut().begin_frame(ctx.signals);
|
||||||
|
|
||||||
|
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.platform.input().pad().start().down {
|
||||||
|
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use prometeu_bytecode::TrapInfo;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn crash_step_formats_trap_from_structured_report() {
|
||||||
|
let step = AppCrashesStep {
|
||||||
|
report: CrashReport::VmTrap {
|
||||||
|
trap: TrapInfo {
|
||||||
|
code: 0xAB,
|
||||||
|
opcode: 0x22,
|
||||||
|
message: "type mismatch".into(),
|
||||||
|
pc: 0x44,
|
||||||
|
span: None,
|
||||||
|
resource: None,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let msg = step.log_message();
|
||||||
|
assert!(msg.contains("PVM Trap 0x000000AB"));
|
||||||
|
assert!(msg.contains("PC 0x44"));
|
||||||
|
assert!(msg.contains("opcode 0x0022"));
|
||||||
|
assert!(msg.contains("type mismatch"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
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 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 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 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 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
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 outcome = ctx.hub.update_shell_profile(ctx.os, ctx.platform);
|
||||||
|
if let Some(report) = outcome.crash {
|
||||||
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
if resident_app_id == cartridge.app_id {
|
||||||
|
return Some(FirmwareState::ResumeResidentGame);
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||||
|
}
|
||||||
+10
-5
@@ -1,8 +1,8 @@
|
|||||||
use crate::firmware::boot_target::BootTarget;
|
use crate::firmware::boot_target::BootTarget;
|
||||||
use crate::firmware::firmware_state::{FirmwareState, HubHomeStep, LoadCartridgeStep};
|
use crate::firmware::firmware_state::{FirmwareState, HubHomeStep, LoadCartridgeStep};
|
||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
use crate::model::CartridgeLoader;
|
use prometeu_hal::cartridge_loader::CartridgeLoader;
|
||||||
use crate::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct LaunchHubStep;
|
pub struct LaunchHubStep;
|
||||||
@@ -19,10 +19,15 @@ impl LaunchHubStep {
|
|||||||
Ok(cartridge) => {
|
Ok(cartridge) => {
|
||||||
// In the case of debug, we could pause here, but the requirement says
|
// In the case of debug, we could pause here, but the requirement says
|
||||||
// for the Runtime to open the socket and wait.
|
// for the Runtime to open the socket and wait.
|
||||||
return Some(FirmwareState::LoadCartridge(LoadCartridgeStep { cartridge }));
|
return Some(FirmwareState::LoadCartridge(LoadCartridgeStep::new(cartridge)));
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
ctx.os.log(LogLevel::Error, LogSource::Pos, 0, format!("Failed to auto-load cartridge: {:?}", e));
|
ctx.os.log(
|
||||||
|
LogLevel::Error,
|
||||||
|
LogSource::Pos,
|
||||||
|
0,
|
||||||
|
format!("Failed to auto-load cartridge: {:?}", e),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -30,4 +35,4 @@ impl LaunchHubStep {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
use crate::firmware::firmware_state::{
|
||||||
|
AppCrashesStep, FirmwareState, GameRunningStep, HubHomeStep, ShellRunningStep,
|
||||||
|
};
|
||||||
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
|
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::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,
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
ctx.os.log(
|
||||||
|
LogLevel::Info,
|
||||||
|
LogSource::Pos,
|
||||||
|
0,
|
||||||
|
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.platform.assets_mut().initialize_for_cartridge(
|
||||||
|
self.cartridge.asset_table.clone(),
|
||||||
|
self.cartridge.preload.clone(),
|
||||||
|
self.cartridge.assets.clone(),
|
||||||
|
);
|
||||||
|
|
||||||
|
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 ctx.os.memcard().choose_for_game(
|
||||||
|
self.cartridge.app_id,
|
||||||
|
self.cartridge.memcard_slots.unwrap() as usize,
|
||||||
|
choice,
|
||||||
|
created_at,
|
||||||
|
) {
|
||||||
|
Ok(()) => self.preparing_memcard = true,
|
||||||
|
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 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
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.os.windows().set_focus(id);
|
||||||
|
return Some(FirmwareState::ShellRunning(ShellRunningStep::new(task_id)));
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {}
|
||||||
|
}
|
||||||
+10
-3
@@ -1,7 +1,7 @@
|
|||||||
use crate::firmware::boot_target::BootTarget;
|
use crate::firmware::boot_target::BootTarget;
|
||||||
use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep, SplashScreenStep};
|
use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep, SplashScreenStep};
|
||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
use crate::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct ResetStep;
|
pub struct ResetStep;
|
||||||
@@ -9,7 +9,14 @@ pub struct ResetStep;
|
|||||||
impl ResetStep {
|
impl ResetStep {
|
||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Firmware Reset".to_string());
|
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> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
@@ -20,4 +27,4 @@ impl ResetStep {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||||
}
|
}
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
-15
@@ -1,7 +1,9 @@
|
|||||||
use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep};
|
use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep};
|
||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
use crate::log::{LogLevel, LogSource};
|
use prometeu_hal::color::Color;
|
||||||
use crate::model::Color;
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
|
use prometeu_hal::primitives::Rect;
|
||||||
|
use prometeu_hal::{FrameId, GfxUiCommand, RenderSubmission, ShellUiFramePacket};
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct SplashScreenStep {
|
pub struct SplashScreenStep {
|
||||||
@@ -12,23 +14,20 @@ impl SplashScreenStep {
|
|||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Showing SplashScreen".to_string());
|
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Showing SplashScreen".to_string());
|
||||||
// Play sound on enter
|
// 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> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
const ANIMATION_DURATION: u32 = 60; // 1 second at 60fps
|
const ANIMATION_DURATION: u32 = 60; // 1 second at 60fps
|
||||||
const TOTAL_DURATION: u32 = 240; // 4 seconds total (updated from 2s based on total_duration logic)
|
const TOTAL_DURATION: u32 = 240; // 4 seconds total (updated from 2s based on total_duration logic)
|
||||||
|
|
||||||
// Update peripherals for input
|
// Update peripherals for input
|
||||||
ctx.hw.pad_mut().begin_frame(ctx.signals);
|
ctx.platform.input_mut().pad_mut().begin_frame(ctx.signals);
|
||||||
|
|
||||||
// Clear screen
|
|
||||||
ctx.hw.gfx_mut().clear(Color::BLACK);
|
|
||||||
|
|
||||||
// Draw expanding square
|
// 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 max_size = (sw.min(sh) as i32 / 2).max(1);
|
||||||
|
|
||||||
let current_size = if self.frame < ANIMATION_DURATION {
|
let current_size = if self.frame < ANIMATION_DURATION {
|
||||||
(max_size * (self.frame as i32 + 1)) / ANIMATION_DURATION as i32
|
(max_size * (self.frame as i32 + 1)) / ANIMATION_DURATION as i32
|
||||||
} else {
|
} else {
|
||||||
@@ -37,13 +36,22 @@ impl SplashScreenStep {
|
|||||||
|
|
||||||
let x = (sw as i32 - current_size) / 2;
|
let x = (sw as i32 - current_size) / 2;
|
||||||
let y = (sh 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);
|
let packet = ShellUiFramePacket::new(vec![
|
||||||
ctx.hw.gfx_mut().present();
|
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
|
// Transition logic
|
||||||
// If any button is pressed at any time after the animation ends
|
// 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));
|
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,4 +65,4 @@ impl SplashScreenStep {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||||
}
|
}
|
||||||
+13
-8
@@ -1,17 +1,22 @@
|
|||||||
|
mod boot_target;
|
||||||
|
#[allow(clippy::module_inception)]
|
||||||
mod firmware;
|
mod firmware;
|
||||||
pub mod firmware_state;
|
pub mod firmware_state;
|
||||||
mod boot_target;
|
|
||||||
|
|
||||||
pub(crate) mod firmware_step_reset;
|
|
||||||
pub(crate) mod firmware_step_splash_screen;
|
|
||||||
pub(crate) mod firmware_step_launch_hub;
|
|
||||||
pub(crate) mod firmware_step_hub_home;
|
|
||||||
pub(crate) mod firmware_step_load_cartridge;
|
|
||||||
pub(crate) mod firmware_step_game_running;
|
|
||||||
pub(crate) mod firmware_step_crash_screen;
|
pub(crate) mod firmware_step_crash_screen;
|
||||||
|
pub(crate) mod firmware_step_game_running;
|
||||||
|
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;
|
mod prometeu_context;
|
||||||
|
pub(crate) mod resident_game_termination;
|
||||||
|
|
||||||
|
pub use boot_target::BootTarget;
|
||||||
pub use firmware::Firmware;
|
pub use firmware::Firmware;
|
||||||
pub use firmware_state::FirmwareState;
|
pub use firmware_state::FirmwareState;
|
||||||
pub use prometeu_context::PrometeuContext;
|
pub use prometeu_context::PrometeuContext;
|
||||||
pub use boot_target::BootTarget;
|
|
||||||
|
pub(crate) mod firmware_step_confirm_discard;
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
use crate::firmware::boot_target::BootTarget;
|
||||||
|
use prometeu_hal::{InputSignals, RuntimePlatform};
|
||||||
|
use prometeu_system::{PrometeuHub, SystemOS};
|
||||||
|
|
||||||
|
pub struct PrometeuContext<'a> {
|
||||||
|
pub os: &'a mut SystemOS,
|
||||||
|
pub hub: &'a mut PrometeuHub,
|
||||||
|
pub boot_target: &'a BootTarget,
|
||||||
|
pub signals: &'a InputSignals,
|
||||||
|
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,3 @@
|
|||||||
|
pub mod firmware;
|
||||||
|
|
||||||
|
pub use firmware::*;
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "prometeu-core"
|
name = "prometeu-hal"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license.workspace = true
|
license.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
prometeu-bytecode = { path = "../prometeu-bytecode" }
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
serde_json = "1.0.149"
|
serde_json = "1.0.149"
|
||||||
prometeu-bytecode = { path = "../prometeu-bytecode" }
|
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub enum AppMode {
|
||||||
|
Game,
|
||||||
|
Shell,
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
pub type HandleId = u32;
|
||||||
|
pub type AssetId = i32;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
|
||||||
|
#[allow(non_camel_case_types)]
|
||||||
|
pub enum BankType {
|
||||||
|
GLYPH,
|
||||||
|
SOUNDS,
|
||||||
|
SCENE,
|
||||||
|
// TILEMAPS,
|
||||||
|
// BLOBS,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
|
||||||
|
pub enum AssetCodec {
|
||||||
|
#[serde(rename = "NONE")]
|
||||||
|
None,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
pub struct AssetEntry {
|
||||||
|
pub asset_id: AssetId,
|
||||||
|
pub asset_name: String,
|
||||||
|
pub bank_type: BankType,
|
||||||
|
pub offset: u64,
|
||||||
|
pub size: u64,
|
||||||
|
pub decoded_size: u64,
|
||||||
|
pub codec: AssetCodec,
|
||||||
|
pub metadata: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
pub struct GlyphBankMetadata {
|
||||||
|
pub tile_size: u32,
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
pub palette_count: u32,
|
||||||
|
pub palette_authored: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
pub struct SoundBankMetadata {
|
||||||
|
pub sample_rate: u32,
|
||||||
|
pub channels: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
|
pub struct SceneBankMetadata {}
|
||||||
|
|
||||||
|
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;
|
||||||
|
// 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;
|
||||||
|
|
||||||
|
impl AssetEntry {
|
||||||
|
pub fn metadata_as_glyph_bank(&self) -> Result<GlyphBankMetadata, String> {
|
||||||
|
if self.bank_type != BankType::GLYPH {
|
||||||
|
return Err(format!(
|
||||||
|
"Asset {} is not a GLYPH bank (type: {:?})",
|
||||||
|
self.asset_id, self.bank_type
|
||||||
|
));
|
||||||
|
}
|
||||||
|
serde_json::from_value(self.metadata.clone())
|
||||||
|
.map_err(|e| format!("Invalid GLYPH metadata for asset {}: {}", self.asset_id, e))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn metadata_as_sound_bank(&self) -> Result<SoundBankMetadata, String> {
|
||||||
|
if self.bank_type != BankType::SOUNDS {
|
||||||
|
return Err(format!(
|
||||||
|
"Asset {} is not a SOUNDS bank (type: {:?})",
|
||||||
|
self.asset_id, self.bank_type
|
||||||
|
));
|
||||||
|
}
|
||||||
|
serde_json::from_value(self.metadata.clone())
|
||||||
|
.map_err(|e| format!("Invalid SOUNDS metadata for asset {}: {}", self.asset_id, e))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn metadata_as_scene_bank(&self) -> Result<SceneBankMetadata, String> {
|
||||||
|
if self.bank_type != BankType::SCENE {
|
||||||
|
return Err(format!(
|
||||||
|
"Asset {} is not a SCENE bank (type: {:?})",
|
||||||
|
self.asset_id, self.bank_type
|
||||||
|
));
|
||||||
|
}
|
||||||
|
serde_json::from_value(self.metadata.clone())
|
||||||
|
.map_err(|e| format!("Invalid SCENE metadata for asset {}: {}", self.asset_id, e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
pub struct PreloadEntry {
|
||||||
|
pub asset_id: AssetId,
|
||||||
|
pub slot: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[repr(i32)]
|
||||||
|
pub enum LoadStatus {
|
||||||
|
PENDING = 0,
|
||||||
|
LOADING = 1,
|
||||||
|
READY = 2,
|
||||||
|
COMMITTED = 3,
|
||||||
|
CANCELED = 4,
|
||||||
|
ERROR = 5,
|
||||||
|
UnknownHandle = 6,
|
||||||
|
QUEUED = 7,
|
||||||
|
ACTIVE = 8,
|
||||||
|
SUPERSEDED = 9,
|
||||||
|
EMPTY = 10,
|
||||||
|
INVALID = 11,
|
||||||
|
BackendUnavailable = 12,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[repr(i32)]
|
||||||
|
pub enum AssetLoadError {
|
||||||
|
AssetNotFound = 3,
|
||||||
|
SlotKindMismatch = 4,
|
||||||
|
SlotIndexInvalid = 5,
|
||||||
|
BackendError = 6,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[repr(i32)]
|
||||||
|
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)]
|
||||||
|
pub struct BankTelemetry {
|
||||||
|
pub bank_type: BankType,
|
||||||
|
pub used_slots: usize,
|
||||||
|
pub total_slots: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct SlotStats {
|
||||||
|
pub asset_id: Option<AssetId>,
|
||||||
|
pub asset_name: Option<String>,
|
||||||
|
pub generation: u32,
|
||||||
|
pub resident_bytes: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub struct SlotRef {
|
||||||
|
pub asset_type: BankType,
|
||||||
|
pub index: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SlotRef {
|
||||||
|
pub fn gfx(index: usize) -> Self {
|
||||||
|
Self { asset_type: BankType::GLYPH, index }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn audio(index: usize) -> Self {
|
||||||
|
Self { asset_type: BankType::SOUNDS, index }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn scene(index: usize) -> Self {
|
||||||
|
Self { asset_type: BankType::SCENE, index }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
use crate::asset::{
|
||||||
|
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;
|
||||||
|
fn shutdown(&self);
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
use crate::sample::Sample;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum LoopMode {
|
||||||
|
Off,
|
||||||
|
On,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[repr(i32)]
|
||||||
|
pub enum AudioOpStatus {
|
||||||
|
Ok = 0,
|
||||||
|
VoiceInvalid = 1,
|
||||||
|
SampleNotFound = 2,
|
||||||
|
ArgRangeInvalid = 3,
|
||||||
|
AssetNotFound = 4,
|
||||||
|
NoEffect = 5,
|
||||||
|
BankInvalid = 6,
|
||||||
|
CommandLimit = 7,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait AudioBridge {
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
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;
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn play_sample(
|
||||||
|
&mut self,
|
||||||
|
sample: Arc<Sample>,
|
||||||
|
voice_id: usize,
|
||||||
|
volume: u8,
|
||||||
|
pan: u8,
|
||||||
|
pitch: f64,
|
||||||
|
priority: u8,
|
||||||
|
loop_mode: LoopMode,
|
||||||
|
) -> AudioOpStatus;
|
||||||
|
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>;
|
||||||
|
}
|
||||||
+4
-3
@@ -15,18 +15,19 @@ pub enum ButtonId {
|
|||||||
Select = 11,
|
Select = 11,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
#[derive(Default, Clone, Copy, Debug)]
|
#[derive(Default, Clone, Copy, Debug)]
|
||||||
pub struct Button {
|
pub struct Button {
|
||||||
pub pressed: bool,
|
pub pressed: bool,
|
||||||
pub released: bool,
|
pub released: bool,
|
||||||
pub down: bool,
|
pub down: bool,
|
||||||
pub hold_frames: u32,
|
pub hold_frames: u16,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Button {
|
impl Button {
|
||||||
pub fn begin_frame(&mut self, is_down_now: bool) {
|
pub fn begin_frame(&mut self, is_down_now: bool) {
|
||||||
let was_down = self.down;
|
let was_down = self.down;
|
||||||
self.down = is_down_now.clone();
|
self.down = is_down_now;
|
||||||
|
|
||||||
self.pressed = !was_down && self.down;
|
self.pressed = !was_down && self.down;
|
||||||
self.released = was_down && !self.down;
|
self.released = was_down && !self.down;
|
||||||
@@ -37,4 +38,4 @@ impl Button {
|
|||||||
self.hold_frames = 0;
|
self.hold_frames = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
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, Read, Seek, SeekFrom};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
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)]
|
||||||
|
pub struct Cartridge {
|
||||||
|
pub app_id: u32,
|
||||||
|
pub title: String,
|
||||||
|
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>,
|
||||||
|
pub preload: Vec<PreloadEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct CartridgeDTO {
|
||||||
|
pub app_id: u32,
|
||||||
|
pub title: String,
|
||||||
|
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>,
|
||||||
|
pub preload: Vec<PreloadEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<CartridgeDTO> for Cartridge {
|
||||||
|
fn from(dto: CartridgeDTO) -> Self {
|
||||||
|
Self {
|
||||||
|
app_id: dto.app_id,
|
||||||
|
title: dto.title,
|
||||||
|
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,
|
||||||
|
preload: dto.preload,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum AssetsPayloadSource {
|
||||||
|
Memory(Arc<[u8]>),
|
||||||
|
File(Arc<FileAssetsPayloadSource>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AssetsPayloadSource {
|
||||||
|
pub fn empty() -> Self {
|
||||||
|
Self::Memory(Arc::<[u8]>::from(Vec::<u8>::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_bytes(bytes: Vec<u8>) -> Self {
|
||||||
|
Self::Memory(Arc::<[u8]>::from(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_file(path: PathBuf, payload_offset: u64, payload_len: u64) -> Self {
|
||||||
|
Self::File(Arc::new(FileAssetsPayloadSource { path, payload_offset, payload_len }))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Self::Memory(bytes) => bytes.is_empty(),
|
||||||
|
Self::File(source) => source.payload_len == 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn open_slice(&self, offset: u64, size: u64) -> io::Result<AssetsPayloadSlice> {
|
||||||
|
match self {
|
||||||
|
Self::Memory(bytes) => {
|
||||||
|
let start =
|
||||||
|
usize::try_from(offset).map_err(|_| invalid_input("asset offset overflow"))?;
|
||||||
|
let len =
|
||||||
|
usize::try_from(size).map_err(|_| invalid_input("asset size overflow"))?;
|
||||||
|
let end =
|
||||||
|
start.checked_add(len).ok_or_else(|| invalid_input("asset range overflow"))?;
|
||||||
|
if end > bytes.len() {
|
||||||
|
return Err(invalid_input("asset range out of bounds"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(AssetsPayloadSlice::Memory { bytes: Arc::clone(bytes), start, len })
|
||||||
|
}
|
||||||
|
Self::File(source) => {
|
||||||
|
let end = offset
|
||||||
|
.checked_add(size)
|
||||||
|
.ok_or_else(|| invalid_input("asset range overflow"))?;
|
||||||
|
if end > source.payload_len {
|
||||||
|
return Err(invalid_input("asset range out of bounds"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(AssetsPayloadSlice::File { source: Arc::clone(source), offset, size })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct FileAssetsPayloadSource {
|
||||||
|
pub path: PathBuf,
|
||||||
|
pub payload_offset: u64,
|
||||||
|
pub payload_len: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum AssetsPayloadSlice {
|
||||||
|
Memory { bytes: Arc<[u8]>, start: usize, len: usize },
|
||||||
|
File { source: Arc<FileAssetsPayloadSource>, offset: u64, size: u64 },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AssetsPayloadSlice {
|
||||||
|
pub fn open_reader(&self) -> io::Result<AssetsPayloadReader> {
|
||||||
|
match self {
|
||||||
|
Self::Memory { bytes, start, len } => {
|
||||||
|
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)?;
|
||||||
|
let absolute_start = source.payload_offset + offset;
|
||||||
|
file.seek(SeekFrom::Start(absolute_start))?;
|
||||||
|
Ok(AssetsPayloadReader::File(FileSliceReader {
|
||||||
|
file,
|
||||||
|
start: absolute_start,
|
||||||
|
len: *size,
|
||||||
|
position: 0,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_all(&self) -> io::Result<Vec<u8>> {
|
||||||
|
let mut reader = self.open_reader()?;
|
||||||
|
let mut buffer = Vec::new();
|
||||||
|
reader.read_to_end(&mut buffer)?;
|
||||||
|
Ok(buffer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum AssetsPayloadReader {
|
||||||
|
Memory(MemorySliceReader),
|
||||||
|
File(FileSliceReader),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Read for AssetsPayloadReader {
|
||||||
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
|
match self {
|
||||||
|
Self::Memory(reader) => reader.read(buf),
|
||||||
|
Self::File(reader) => reader.read(buf),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Seek for AssetsPayloadReader {
|
||||||
|
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
|
||||||
|
match self {
|
||||||
|
Self::Memory(reader) => reader.seek(pos),
|
||||||
|
Self::File(reader) => reader.seek(pos),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
len: u64,
|
||||||
|
position: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Read for FileSliceReader {
|
||||||
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
|
if self.position >= self.len {
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let remaining = (self.len - self.position) as usize;
|
||||||
|
let to_read = remaining.min(buf.len());
|
||||||
|
let read = self.file.read(&mut buf[..to_read])?;
|
||||||
|
self.position += read as u64;
|
||||||
|
Ok(read)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Seek for FileSliceReader {
|
||||||
|
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
|
||||||
|
let next = match pos {
|
||||||
|
SeekFrom::Start(offset) => offset as i128,
|
||||||
|
SeekFrom::Current(delta) => self.position as i128 + delta as i128,
|
||||||
|
SeekFrom::End(delta) => self.len as i128 + delta as i128,
|
||||||
|
};
|
||||||
|
|
||||||
|
if next < 0 || next as u64 > self.len {
|
||||||
|
return Err(invalid_input("slice seek out of bounds"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let next = next as u64;
|
||||||
|
self.file.seek(SeekFrom::Start(self.start + next))?;
|
||||||
|
self.position = next;
|
||||||
|
Ok(self.position)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invalid_input(message: &'static str) -> io::Error {
|
||||||
|
io::Error::new(io::ErrorKind::InvalidInput, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct AssetsPackPrelude {
|
||||||
|
pub magic: [u8; 4],
|
||||||
|
pub schema_version: u32,
|
||||||
|
pub header_len: u32,
|
||||||
|
pub payload_offset: u64,
|
||||||
|
pub flags: u32,
|
||||||
|
pub reserved: u32,
|
||||||
|
pub header_checksum: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AssetsPackPrelude {
|
||||||
|
pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
|
||||||
|
if bytes.len() < ASSETS_PA_PRELUDE_SIZE {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut magic = [0_u8; 4];
|
||||||
|
magic.copy_from_slice(&bytes[0..4]);
|
||||||
|
|
||||||
|
Some(Self {
|
||||||
|
magic,
|
||||||
|
schema_version: u32::from_le_bytes(bytes[4..8].try_into().ok()?),
|
||||||
|
header_len: u32::from_le_bytes(bytes[8..12].try_into().ok()?),
|
||||||
|
payload_offset: u64::from_le_bytes(bytes[12..20].try_into().ok()?),
|
||||||
|
flags: u32::from_le_bytes(bytes[20..24].try_into().ok()?),
|
||||||
|
reserved: u32::from_le_bytes(bytes[24..28].try_into().ok()?),
|
||||||
|
header_checksum: u32::from_le_bytes(bytes[28..32].try_into().ok()?),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_bytes(self) -> [u8; ASSETS_PA_PRELUDE_SIZE] {
|
||||||
|
let mut bytes = [0_u8; ASSETS_PA_PRELUDE_SIZE];
|
||||||
|
bytes[0..4].copy_from_slice(&self.magic);
|
||||||
|
bytes[4..8].copy_from_slice(&self.schema_version.to_le_bytes());
|
||||||
|
bytes[8..12].copy_from_slice(&self.header_len.to_le_bytes());
|
||||||
|
bytes[12..20].copy_from_slice(&self.payload_offset.to_le_bytes());
|
||||||
|
bytes[20..24].copy_from_slice(&self.flags.to_le_bytes());
|
||||||
|
bytes[24..28].copy_from_slice(&self.reserved.to_le_bytes());
|
||||||
|
bytes[28..32].copy_from_slice(&self.header_checksum.to_le_bytes());
|
||||||
|
bytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
pub struct AssetsPackHeader {
|
||||||
|
#[serde(default)]
|
||||||
|
pub asset_table: Vec<AssetEntry>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub preload: Vec<PreloadEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum CartridgeError {
|
||||||
|
NotFound,
|
||||||
|
InvalidFormat,
|
||||||
|
InvalidManifest,
|
||||||
|
UnsupportedVersion,
|
||||||
|
MissingProgram,
|
||||||
|
MissingAssets,
|
||||||
|
IoError,
|
||||||
|
ProgramLoadFailed(prometeu_bytecode::load_limits::LoadFailure),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum Capability {
|
||||||
|
None,
|
||||||
|
System,
|
||||||
|
Gfx,
|
||||||
|
Composer,
|
||||||
|
Gfx2d,
|
||||||
|
Gfxui,
|
||||||
|
Audio,
|
||||||
|
Fs,
|
||||||
|
Memcard,
|
||||||
|
Log,
|
||||||
|
Asset,
|
||||||
|
Bank,
|
||||||
|
All,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct CartridgeManifest {
|
||||||
|
pub magic: String,
|
||||||
|
pub cartridge_version: u32,
|
||||||
|
pub app_id: u32,
|
||||||
|
pub title: String,
|
||||||
|
pub app_version: String,
|
||||||
|
pub app_mode: AppMode,
|
||||||
|
#[serde(default)]
|
||||||
|
pub capabilities: Vec<Capability>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub memcard_slots: Option<u8>,
|
||||||
|
}
|
||||||
@@ -0,0 +1,727 @@
|
|||||||
|
use crate::asset::{AssetEntry, BankType};
|
||||||
|
use crate::cartridge::{
|
||||||
|
ASSETS_PA_MAGIC, ASSETS_PA_PRELUDE_SIZE, ASSETS_PA_SCHEMA_VERSION, AssetsPackHeader,
|
||||||
|
AssetsPackPrelude, AssetsPayloadSource, Capability, Cartridge, CartridgeDTO, CartridgeError,
|
||||||
|
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};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
pub struct CartridgeLoader;
|
||||||
|
|
||||||
|
impl CartridgeLoader {
|
||||||
|
pub fn load(path: impl AsRef<Path>) -> Result<Cartridge, CartridgeError> {
|
||||||
|
let path = path.as_ref();
|
||||||
|
if !path.exists() {
|
||||||
|
return Err(CartridgeError::NotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
if path.is_dir() {
|
||||||
|
DirectoryCartridgeLoader::load(path)
|
||||||
|
} else if path.extension().is_some_and(|ext| ext == "pmc") {
|
||||||
|
PackedCartridgeLoader::load(path)
|
||||||
|
} else {
|
||||||
|
Err(CartridgeError::InvalidFormat)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct DirectoryCartridgeLoader;
|
||||||
|
|
||||||
|
impl DirectoryCartridgeLoader {
|
||||||
|
pub fn load(path: &Path) -> Result<Cartridge, CartridgeError> {
|
||||||
|
let manifest_path = path.join("manifest.json");
|
||||||
|
if !manifest_path.exists() {
|
||||||
|
return Err(CartridgeError::InvalidManifest);
|
||||||
|
}
|
||||||
|
|
||||||
|
let manifest_content =
|
||||||
|
fs::read_to_string(manifest_path).map_err(|_| CartridgeError::IoError)?;
|
||||||
|
let manifest: CartridgeManifest =
|
||||||
|
serde_json::from_str(&manifest_content).map_err(|_| CartridgeError::InvalidManifest)?;
|
||||||
|
|
||||||
|
// Additional validation as per requirements
|
||||||
|
if manifest.magic != "PMTU" {
|
||||||
|
return Err(CartridgeError::InvalidManifest);
|
||||||
|
}
|
||||||
|
if manifest.cartridge_version != 1 {
|
||||||
|
return Err(CartridgeError::UnsupportedVersion);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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() {
|
||||||
|
let parsed = parse_assets_pack(&assets_pa_path)?;
|
||||||
|
(
|
||||||
|
AssetsPayloadSource::from_file(
|
||||||
|
assets_pa_path.clone(),
|
||||||
|
parsed.payload_offset,
|
||||||
|
parsed.payload_len,
|
||||||
|
),
|
||||||
|
parsed.header.asset_table,
|
||||||
|
parsed.header.preload,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
if capabilities & caps::ASSET != 0 {
|
||||||
|
return Err(CartridgeError::MissingAssets);
|
||||||
|
}
|
||||||
|
|
||||||
|
(AssetsPayloadSource::empty(), Vec::new(), Vec::new())
|
||||||
|
};
|
||||||
|
|
||||||
|
let dto = CartridgeDTO {
|
||||||
|
app_id: manifest.app_id,
|
||||||
|
title: manifest.title,
|
||||||
|
app_version: manifest.app_version,
|
||||||
|
app_mode: manifest.app_mode,
|
||||||
|
capabilities,
|
||||||
|
memcard_slots: manifest.memcard_slots,
|
||||||
|
program,
|
||||||
|
assets,
|
||||||
|
asset_table,
|
||||||
|
preload,
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Cartridge::from(dto))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_capabilities(capabilities: &[Capability]) -> Result<CapFlags, CartridgeError> {
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
let mut normalized = caps::NONE;
|
||||||
|
|
||||||
|
for capability in capabilities {
|
||||||
|
if !seen.insert(*capability) {
|
||||||
|
return Err(CartridgeError::InvalidManifest);
|
||||||
|
}
|
||||||
|
|
||||||
|
normalized |= match capability {
|
||||||
|
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,
|
||||||
|
Capability::All => caps::ALL,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(normalized)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ParsedAssetsPack {
|
||||||
|
header: AssetsPackHeader,
|
||||||
|
payload_offset: u64,
|
||||||
|
payload_len: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_assets_pack(path: &Path) -> Result<ParsedAssetsPack, CartridgeError> {
|
||||||
|
let mut file = fs::File::open(path).map_err(|_| CartridgeError::IoError)?;
|
||||||
|
let mut prelude_bytes = [0_u8; ASSETS_PA_PRELUDE_SIZE];
|
||||||
|
file.read_exact(&mut prelude_bytes).map_err(|_| CartridgeError::InvalidFormat)?;
|
||||||
|
|
||||||
|
let prelude =
|
||||||
|
AssetsPackPrelude::from_bytes(&prelude_bytes).ok_or(CartridgeError::InvalidFormat)?;
|
||||||
|
|
||||||
|
if prelude.magic != ASSETS_PA_MAGIC || prelude.schema_version != ASSETS_PA_SCHEMA_VERSION {
|
||||||
|
return Err(CartridgeError::InvalidFormat);
|
||||||
|
}
|
||||||
|
|
||||||
|
let header_start = ASSETS_PA_PRELUDE_SIZE;
|
||||||
|
let header_len =
|
||||||
|
usize::try_from(prelude.header_len).map_err(|_| CartridgeError::InvalidFormat)?;
|
||||||
|
let header_end = header_start.checked_add(header_len).ok_or(CartridgeError::InvalidFormat)?;
|
||||||
|
let payload_offset =
|
||||||
|
usize::try_from(prelude.payload_offset).map_err(|_| CartridgeError::InvalidFormat)?;
|
||||||
|
let file_len = usize::try_from(file.metadata().map_err(|_| CartridgeError::IoError)?.len())
|
||||||
|
.map_err(|_| CartridgeError::InvalidFormat)?;
|
||||||
|
|
||||||
|
if payload_offset < header_start || header_end > file_len || payload_offset > file_len {
|
||||||
|
return Err(CartridgeError::InvalidFormat);
|
||||||
|
}
|
||||||
|
if header_end != payload_offset {
|
||||||
|
return Err(CartridgeError::InvalidFormat);
|
||||||
|
}
|
||||||
|
|
||||||
|
file.seek(SeekFrom::Start(header_start as u64)).map_err(|_| CartridgeError::IoError)?;
|
||||||
|
let mut header_bytes = vec![0_u8; header_len];
|
||||||
|
file.read_exact(&mut header_bytes).map_err(|_| CartridgeError::InvalidFormat)?;
|
||||||
|
let header: AssetsPackHeader =
|
||||||
|
serde_json::from_slice(&header_bytes).map_err(|_| CartridgeError::InvalidFormat)?;
|
||||||
|
validate_preload(&header.asset_table, &header.preload)?;
|
||||||
|
let payload_len =
|
||||||
|
u64::try_from(file_len - payload_offset).map_err(|_| CartridgeError::InvalidFormat)?;
|
||||||
|
|
||||||
|
Ok(ParsedAssetsPack { header, payload_offset: prelude.payload_offset, payload_len })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_preload(
|
||||||
|
asset_table: &[AssetEntry],
|
||||||
|
preload: &[crate::asset::PreloadEntry],
|
||||||
|
) -> Result<(), CartridgeError> {
|
||||||
|
let mut claimed_slots = HashSet::<(BankType, usize)>::new();
|
||||||
|
|
||||||
|
for item in preload {
|
||||||
|
let entry = asset_table
|
||||||
|
.iter()
|
||||||
|
.find(|entry| entry.asset_id == item.asset_id)
|
||||||
|
.ok_or(CartridgeError::InvalidFormat)?;
|
||||||
|
|
||||||
|
if !claimed_slots.insert((entry.bank_type, item.slot)) {
|
||||||
|
return Err(CartridgeError::InvalidFormat);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
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_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};
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
static TEST_DIR_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
||||||
|
struct TestCartridgeDir {
|
||||||
|
path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TestCartridgeDir {
|
||||||
|
fn new(manifest: serde_json::Value) -> Self {
|
||||||
|
let unique = TEST_DIR_COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let timestamp = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.expect("system time must be after unix epoch")
|
||||||
|
.as_nanos();
|
||||||
|
let path = std::env::temp_dir()
|
||||||
|
.join(format!("prometeu-hal-cartridge-loader-{}-{}", timestamp, unique));
|
||||||
|
|
||||||
|
fs::create_dir_all(&path).expect("must create temporary cartridge directory");
|
||||||
|
fs::write(
|
||||||
|
path.join("manifest.json"),
|
||||||
|
serde_json::to_vec_pretty(&manifest).expect("manifest must serialize"),
|
||||||
|
)
|
||||||
|
.expect("must write manifest.json");
|
||||||
|
fs::write(path.join("program.pbx"), [0x01_u8, 0x02, 0x03]).expect("must write program");
|
||||||
|
|
||||||
|
Self { path }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn path(&self) -> &Path {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_assets_pa(
|
||||||
|
&self,
|
||||||
|
asset_table: Vec<AssetEntry>,
|
||||||
|
preload: Vec<PreloadEntry>,
|
||||||
|
payload: &[u8],
|
||||||
|
) {
|
||||||
|
let header = serde_json::to_vec(&AssetsPackHeader { asset_table, preload })
|
||||||
|
.expect("assets header must serialize");
|
||||||
|
let payload_offset = (ASSETS_PA_PRELUDE_SIZE + header.len()) as u64;
|
||||||
|
let prelude = AssetsPackPrelude {
|
||||||
|
magic: ASSETS_PA_MAGIC,
|
||||||
|
schema_version: ASSETS_PA_SCHEMA_VERSION,
|
||||||
|
header_len: header.len() as u32,
|
||||||
|
payload_offset,
|
||||||
|
flags: 0,
|
||||||
|
reserved: 0,
|
||||||
|
header_checksum: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut bytes = prelude.to_bytes().to_vec();
|
||||||
|
bytes.extend_from_slice(&header);
|
||||||
|
bytes.extend_from_slice(payload);
|
||||||
|
fs::write(self.path.join("assets.pa"), bytes).expect("must write assets.pa");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TestCartridgeDir {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = fs::remove_dir_all(&self.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn manifest_with_capabilities(capabilities: Option<Vec<&str>>) -> serde_json::Value {
|
||||||
|
let mut manifest = json!({
|
||||||
|
"magic": "PMTU",
|
||||||
|
"cartridge_version": 1,
|
||||||
|
"app_id": 1001,
|
||||||
|
"title": "Example",
|
||||||
|
"app_version": "1.0.0",
|
||||||
|
"app_mode": "Game"
|
||||||
|
});
|
||||||
|
|
||||||
|
if let Some(capabilities) = capabilities {
|
||||||
|
manifest["capabilities"] = json!(capabilities);
|
||||||
|
}
|
||||||
|
|
||||||
|
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));
|
||||||
|
|
||||||
|
let cartridge = DirectoryCartridgeLoader::load(dir.path()).expect("cartridge must load");
|
||||||
|
|
||||||
|
assert_eq!(cartridge.capabilities, caps::NONE);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_with_single_capability_normalizes_to_flag() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["gfx"])));
|
||||||
|
|
||||||
|
let cartridge = DirectoryCartridgeLoader::load(dir.path()).expect("cartridge must load");
|
||||||
|
|
||||||
|
assert_eq!(cartridge.capabilities, caps::GFX);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_with_multiple_capabilities_combines_flags() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["gfx", "audio"])));
|
||||||
|
|
||||||
|
let cartridge = DirectoryCartridgeLoader::load(dir.path()).expect("cartridge must load");
|
||||||
|
|
||||||
|
assert_eq!(cartridge.capabilities, caps::GFX | caps::AUDIO);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_with_all_capability_normalizes_to_all_flags() {
|
||||||
|
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");
|
||||||
|
|
||||||
|
assert_eq!(cartridge.capabilities, caps::ALL);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_with_none_capability_keeps_zero_flags() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["none"])));
|
||||||
|
|
||||||
|
let cartridge = DirectoryCartridgeLoader::load(dir.path()).expect("cartridge must load");
|
||||||
|
|
||||||
|
assert_eq!(cartridge.capabilities, caps::NONE);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_with_duplicate_capabilities_fails() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["gfx", "gfx"])));
|
||||||
|
|
||||||
|
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(error, CartridgeError::InvalidManifest));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_with_unknown_capability_fails() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["network"])));
|
||||||
|
|
||||||
|
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(error, CartridgeError::InvalidManifest));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_with_legacy_input_capability_fails() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["input"])));
|
||||||
|
|
||||||
|
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(error, CartridgeError::InvalidManifest));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_asset_entry(offset: u64, size: u64) -> AssetEntry {
|
||||||
|
AssetEntry {
|
||||||
|
asset_id: 7,
|
||||||
|
asset_name: "tiles".to_string(),
|
||||||
|
bank_type: BankType::GLYPH,
|
||||||
|
offset,
|
||||||
|
size,
|
||||||
|
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_MAX_PALETTE_COUNT_V1,
|
||||||
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_with_asset_capability_requires_assets_pa() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["asset"])));
|
||||||
|
|
||||||
|
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(error, CartridgeError::MissingAssets));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_without_asset_capability_accepts_missing_assets_pa() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["gfx"])));
|
||||||
|
|
||||||
|
let cartridge = DirectoryCartridgeLoader::load(dir.path()).expect("cartridge must load");
|
||||||
|
|
||||||
|
assert!(cartridge.assets.is_empty());
|
||||||
|
assert!(cartridge.asset_table.is_empty());
|
||||||
|
assert!(cartridge.preload.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_reads_asset_table_and_preload_from_assets_pa_header() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["asset"])));
|
||||||
|
let payload = vec![1_u8, 2, 3, 4];
|
||||||
|
dir.write_assets_pa(
|
||||||
|
vec![test_asset_entry(0, payload.len() as u64)],
|
||||||
|
vec![PreloadEntry { asset_id: 7, slot: 2 }],
|
||||||
|
&payload,
|
||||||
|
);
|
||||||
|
|
||||||
|
let cartridge = DirectoryCartridgeLoader::load(dir.path()).expect("cartridge must load");
|
||||||
|
|
||||||
|
let slice = cartridge
|
||||||
|
.assets
|
||||||
|
.open_slice(0, payload.len() as u64)
|
||||||
|
.expect("payload slice must open")
|
||||||
|
.read_all()
|
||||||
|
.expect("payload slice must read");
|
||||||
|
assert_eq!(slice, payload);
|
||||||
|
assert_eq!(cartridge.asset_table.len(), 1);
|
||||||
|
assert_eq!(cartridge.asset_table[0].asset_name, "tiles");
|
||||||
|
assert_eq!(cartridge.preload.len(), 1);
|
||||||
|
assert_eq!(cartridge.preload[0].asset_id, 7);
|
||||||
|
assert_eq!(cartridge.preload[0].slot, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_rejects_preload_with_missing_asset_id() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["asset"])));
|
||||||
|
dir.write_assets_pa(
|
||||||
|
vec![test_asset_entry(0, 4)],
|
||||||
|
vec![PreloadEntry { asset_id: 999, slot: 2 }],
|
||||||
|
&[1_u8, 2, 3, 4],
|
||||||
|
);
|
||||||
|
|
||||||
|
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(error, CartridgeError::InvalidFormat));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_rejects_preload_slot_clash_per_bank_type() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["asset"])));
|
||||||
|
let asset_table = vec![
|
||||||
|
test_asset_entry(0, 4),
|
||||||
|
AssetEntry {
|
||||||
|
asset_id: 8,
|
||||||
|
asset_name: "other_tiles".to_string(),
|
||||||
|
bank_type: BankType::GLYPH,
|
||||||
|
offset: 4,
|
||||||
|
size: 4,
|
||||||
|
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_MAX_PALETTE_COUNT_V1,
|
||||||
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
let preload =
|
||||||
|
vec![PreloadEntry { asset_id: 7, slot: 2 }, PreloadEntry { asset_id: 8, slot: 2 }];
|
||||||
|
dir.write_assets_pa(asset_table, preload, &[1_u8, 2, 3, 4, 5, 6, 7, 8]);
|
||||||
|
|
||||||
|
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(error, CartridgeError::InvalidFormat));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_rejects_invalid_assets_pa_prelude() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["asset"])));
|
||||||
|
fs::write(dir.path().join("assets.pa"), b"not-a-valid-pack").expect("must write assets.pa");
|
||||||
|
|
||||||
|
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(error, CartridgeError::InvalidFormat));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_rejects_invalid_assets_pa_header_json() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["asset"])));
|
||||||
|
let prelude = AssetsPackPrelude {
|
||||||
|
magic: ASSETS_PA_MAGIC,
|
||||||
|
schema_version: ASSETS_PA_SCHEMA_VERSION,
|
||||||
|
header_len: 4,
|
||||||
|
payload_offset: (ASSETS_PA_PRELUDE_SIZE + 4) as u64,
|
||||||
|
flags: 0,
|
||||||
|
reserved: 0,
|
||||||
|
header_checksum: 0,
|
||||||
|
};
|
||||||
|
let mut bytes = prelude.to_bytes().to_vec();
|
||||||
|
bytes.extend_from_slice(b"{no}");
|
||||||
|
fs::write(dir.path().join("assets.pa"), bytes).expect("must write assets.pa");
|
||||||
|
|
||||||
|
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(error, CartridgeError::InvalidFormat));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_rejects_unknown_codec_string_in_assets_pa_header() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["asset"])));
|
||||||
|
let header = serde_json::json!({
|
||||||
|
"asset_table": [{
|
||||||
|
"asset_id": 7,
|
||||||
|
"asset_name": "tiles",
|
||||||
|
"bank_type": "GLYPH",
|
||||||
|
"offset": 0,
|
||||||
|
"size": 4,
|
||||||
|
"decoded_size": 768,
|
||||||
|
"codec": "LZ4",
|
||||||
|
"metadata": {
|
||||||
|
"tile_size": 16,
|
||||||
|
"width": 16,
|
||||||
|
"height": 16,
|
||||||
|
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
|
}
|
||||||
|
}],
|
||||||
|
"preload": []
|
||||||
|
});
|
||||||
|
let header_bytes = serde_json::to_vec(&header).expect("header must serialize");
|
||||||
|
let prelude = AssetsPackPrelude {
|
||||||
|
magic: ASSETS_PA_MAGIC,
|
||||||
|
schema_version: ASSETS_PA_SCHEMA_VERSION,
|
||||||
|
header_len: header_bytes.len() as u32,
|
||||||
|
payload_offset: (ASSETS_PA_PRELUDE_SIZE + header_bytes.len()) as u64,
|
||||||
|
flags: 0,
|
||||||
|
reserved: 0,
|
||||||
|
header_checksum: 0,
|
||||||
|
};
|
||||||
|
let mut bytes = prelude.to_bytes().to_vec();
|
||||||
|
bytes.extend_from_slice(&header_bytes);
|
||||||
|
bytes.extend_from_slice(&[1_u8, 2, 3, 4]);
|
||||||
|
fs::write(dir.path().join("assets.pa"), bytes).expect("must write assets.pa");
|
||||||
|
|
||||||
|
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(error, CartridgeError::InvalidFormat));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_rejects_legacy_raw_codec_string_in_assets_pa_header() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["asset"])));
|
||||||
|
let header = serde_json::json!({
|
||||||
|
"asset_table": [{
|
||||||
|
"asset_id": 7,
|
||||||
|
"asset_name": "tiles",
|
||||||
|
"bank_type": "GLYPH",
|
||||||
|
"offset": 0,
|
||||||
|
"size": 4,
|
||||||
|
"decoded_size": 768,
|
||||||
|
"codec": "RAW",
|
||||||
|
"metadata": {
|
||||||
|
"tile_size": 16,
|
||||||
|
"width": 16,
|
||||||
|
"height": 16,
|
||||||
|
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
|
}
|
||||||
|
}],
|
||||||
|
"preload": []
|
||||||
|
});
|
||||||
|
let header_bytes = serde_json::to_vec(&header).expect("header must serialize");
|
||||||
|
let prelude = AssetsPackPrelude {
|
||||||
|
magic: ASSETS_PA_MAGIC,
|
||||||
|
schema_version: ASSETS_PA_SCHEMA_VERSION,
|
||||||
|
header_len: header_bytes.len() as u32,
|
||||||
|
payload_offset: (ASSETS_PA_PRELUDE_SIZE + header_bytes.len()) as u64,
|
||||||
|
flags: 0,
|
||||||
|
reserved: 0,
|
||||||
|
header_checksum: 0,
|
||||||
|
};
|
||||||
|
let mut bytes = prelude.to_bytes().to_vec();
|
||||||
|
bytes.extend_from_slice(&header_bytes);
|
||||||
|
bytes.extend_from_slice(&[1_u8, 2, 3, 4]);
|
||||||
|
fs::write(dir.path().join("assets.pa"), bytes).expect("must write assets.pa");
|
||||||
|
|
||||||
|
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(error, CartridgeError::InvalidFormat));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
/// Represents a canonical RGBA8888 color in RGBA channel order.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub struct Color(pub u32);
|
||||||
|
|
||||||
|
impl Color {
|
||||||
|
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);
|
||||||
|
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 RGBA8888 channels from canonical RGBA raw order.
|
||||||
|
#[inline(always)]
|
||||||
|
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 RGBA8888 channels into canonical RGBA raw order.
|
||||||
|
#[inline(always)]
|
||||||
|
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 opaque RGBA8888 color from 8-bit RGB components.
|
||||||
|
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
|
||||||
|
Self::rgba(r, g, b, 255)
|
||||||
|
}
|
||||||
|
|
||||||
|
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: u32) -> Self {
|
||||||
|
Self(raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn raw(self) -> u32 {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn hex(self) -> i32 {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[repr(i32)]
|
||||||
|
pub enum ComposerOpStatus {
|
||||||
|
Ok = 0,
|
||||||
|
SceneUnavailable = 1,
|
||||||
|
ArgRangeInvalid = 2,
|
||||||
|
BankInvalid = 3,
|
||||||
|
LayerInvalid = 4,
|
||||||
|
SpriteOverflow = 5,
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
use crate::app_mode::AppMode;
|
||||||
|
#[cfg(test)]
|
||||||
|
use prometeu_bytecode::Value;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
pub const DEVTOOLS_PROTOCOL_VERSION: u32 = 1;
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "type")]
|
||||||
|
pub enum DebugCommand {
|
||||||
|
#[serde(rename = "ok")]
|
||||||
|
Ok,
|
||||||
|
#[serde(rename = "start")]
|
||||||
|
Start,
|
||||||
|
#[serde(rename = "pause")]
|
||||||
|
Pause,
|
||||||
|
#[serde(rename = "resume")]
|
||||||
|
Resume,
|
||||||
|
#[serde(rename = "step")]
|
||||||
|
Step,
|
||||||
|
#[serde(rename = "stepFrame")]
|
||||||
|
StepFrame,
|
||||||
|
#[serde(rename = "getState")]
|
||||||
|
GetState,
|
||||||
|
#[serde(rename = "setBreakpoint")]
|
||||||
|
SetBreakpoint { pc: usize },
|
||||||
|
#[serde(rename = "listBreakpoints")]
|
||||||
|
ListBreakpoints,
|
||||||
|
#[serde(rename = "clearBreakpoint")]
|
||||||
|
ClearBreakpoint { pc: usize },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "type")]
|
||||||
|
pub enum DebugResponse {
|
||||||
|
#[serde(rename = "handshake")]
|
||||||
|
Handshake { protocol_version: u32, runtime_version: String, cartridge: HandshakeCartridge },
|
||||||
|
#[serde(rename = "getState")]
|
||||||
|
GetState { pc: usize, stack_top: crate::ValueSnapshot, frame_index: u64, app_id: u32 },
|
||||||
|
#[serde(rename = "breakpoints")]
|
||||||
|
Breakpoints { pcs: Vec<usize> },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct HandshakeCartridge {
|
||||||
|
pub app_id: u32,
|
||||||
|
pub title: String,
|
||||||
|
pub app_version: String,
|
||||||
|
pub app_mode: AppMode,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "event")]
|
||||||
|
pub enum DebugEvent {
|
||||||
|
#[serde(rename = "breakpointHit")]
|
||||||
|
BreakpointHit { pc: usize, frame_index: u64 },
|
||||||
|
#[serde(rename = "log")]
|
||||||
|
Log { level: String, source: String, msg: String },
|
||||||
|
#[serde(rename = "telemetry")]
|
||||||
|
Telemetry {
|
||||||
|
frame_index: u64,
|
||||||
|
vm_steps: u32,
|
||||||
|
syscalls: u32,
|
||||||
|
cycles: u64,
|
||||||
|
cycles_budget: u64,
|
||||||
|
host_cpu_time_us: u64,
|
||||||
|
violations: u32,
|
||||||
|
glyph_slots_used: u32,
|
||||||
|
glyph_slots_total: u32,
|
||||||
|
sound_slots_used: u32,
|
||||||
|
sound_slots_total: u32,
|
||||||
|
scene_slots_used: u32,
|
||||||
|
scene_slots_total: u32,
|
||||||
|
},
|
||||||
|
#[serde(rename = "fault")]
|
||||||
|
Fault {
|
||||||
|
kind: String,
|
||||||
|
summary: String,
|
||||||
|
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 },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_telemetry_event_serialization() {
|
||||||
|
let event = DebugEvent::Telemetry {
|
||||||
|
frame_index: 10,
|
||||||
|
vm_steps: 100,
|
||||||
|
syscalls: 5,
|
||||||
|
cycles: 5000,
|
||||||
|
cycles_budget: 10000,
|
||||||
|
host_cpu_time_us: 1200,
|
||||||
|
violations: 0,
|
||||||
|
glyph_slots_used: 1,
|
||||||
|
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();
|
||||||
|
assert!(json.contains("\"event\":\"telemetry\""));
|
||||||
|
assert!(json.contains("\"cycles\":5000"));
|
||||||
|
assert!(json.contains("\"cycles_budget\":10000"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_get_state_serialization() {
|
||||||
|
let resp = DebugResponse::GetState {
|
||||||
|
pc: 42,
|
||||||
|
stack_top: vec![Value::Int64(10), Value::String("test".into()), Value::Boolean(true)]
|
||||||
|
.into(),
|
||||||
|
frame_index: 5,
|
||||||
|
app_id: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
let json = serde_json::to_string(&resp).unwrap();
|
||||||
|
assert!(json.contains("\"type\":\"getState\""));
|
||||||
|
assert!(json.contains("\"pc\":42"));
|
||||||
|
assert!(json.contains("\"stack_top\":[10,\"test\",true]"));
|
||||||
|
assert!(json.contains("\"frame_index\":5"));
|
||||||
|
assert!(json.contains("\"app_id\":1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_fault_event_serialization() {
|
||||||
|
let event = DebugEvent::Fault {
|
||||||
|
kind: "vm_trap".into(),
|
||||||
|
summary: "PVM Trap 0x00000004".into(),
|
||||||
|
pc: Some(12),
|
||||||
|
trap_code: Some(4),
|
||||||
|
opcode: Some(0x70),
|
||||||
|
span: None,
|
||||||
|
resource: None,
|
||||||
|
init: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let json = serde_json::to_string(&event).unwrap();
|
||||||
|
assert!(json.contains("\"event\":\"fault\""));
|
||||||
|
assert!(json.contains("\"kind\":\"vm_trap\""));
|
||||||
|
assert!(json.contains("\"trap_code\":4"));
|
||||||
|
assert!(json.contains("\"opcode\":112"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
use crate::color::Color;
|
||||||
|
use crate::scene_viewport_cache::SceneViewportCache;
|
||||||
|
use crate::scene_viewport_resolver::ResolverUpdate;
|
||||||
|
use crate::sprite::Sprite;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum BlendMode {
|
||||||
|
None,
|
||||||
|
Half,
|
||||||
|
HalfPlus,
|
||||||
|
HalfMinus,
|
||||||
|
Full,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[repr(i32)]
|
||||||
|
pub enum GfxOpStatus {
|
||||||
|
Ok = 0,
|
||||||
|
AssetNotFound = 1,
|
||||||
|
InvalidSpriteIndex = 2,
|
||||||
|
ArgRangeInvalid = 3,
|
||||||
|
BankInvalid = 4,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait GfxBridge {
|
||||||
|
fn size(&self) -> (usize, usize);
|
||||||
|
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);
|
||||||
|
fn draw_pixel(&mut self, x: i32, y: i32, color: Color);
|
||||||
|
fn draw_line(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, color: Color);
|
||||||
|
fn draw_circle(&mut self, xc: i32, yc: i32, r: i32, color: Color);
|
||||||
|
fn draw_circle_points(&mut self, xc: i32, yc: i32, x: i32, y: i32, color: Color);
|
||||||
|
fn fill_circle(&mut self, xc: i32, yc: i32, r: i32, color: Color);
|
||||||
|
fn draw_circle_lines(&mut self, xc: i32, yc: i32, x: i32, y: i32, color: Color);
|
||||||
|
fn draw_disc(&mut self, x: i32, y: i32, r: i32, border_color: Color, fill_color: Color);
|
||||||
|
fn draw_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color);
|
||||||
|
fn draw_square(
|
||||||
|
&mut self,
|
||||||
|
x: i32,
|
||||||
|
y: i32,
|
||||||
|
w: i32,
|
||||||
|
h: i32,
|
||||||
|
border_color: Color,
|
||||||
|
fill_color: Color,
|
||||||
|
);
|
||||||
|
fn draw_horizontal_line(&mut self, x0: i32, x1: i32, y: i32, color: Color);
|
||||||
|
fn draw_vertical_line(&mut self, x: i32, y0: i32, y1: i32, color: Color);
|
||||||
|
fn present(&mut self);
|
||||||
|
/// Render the canonical game frame with no bound scene.
|
||||||
|
///
|
||||||
|
/// Deferred `gfx.*` overlay/debug primitives are intentionally outside this
|
||||||
|
/// contract and are drained by a separate final overlay stage.
|
||||||
|
fn render_no_scene_frame(&mut self);
|
||||||
|
/// Render the canonical scene-backed game frame from cache/resolver state.
|
||||||
|
///
|
||||||
|
/// 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,
|
||||||
|
resolved_glyph_slots: &[usize; 4],
|
||||||
|
);
|
||||||
|
fn load_frame_sprites(&mut self, sprites: &[Sprite]);
|
||||||
|
/// Submit text into the `gfx.*` primitive path.
|
||||||
|
///
|
||||||
|
/// Under the accepted runtime contract this is not the canonical game
|
||||||
|
/// composition path; it belongs to the deferred final overlay/debug family.
|
||||||
|
fn draw_text(&mut self, x: i32, y: i32, text: &str, color: Color);
|
||||||
|
fn draw_char(&mut self, x: i32, y: i32, c: char, color: Color);
|
||||||
|
|
||||||
|
fn sprite(&self, index: usize) -> &Sprite;
|
||||||
|
fn sprite_mut(&mut self, index: usize) -> &mut Sprite;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
|
||||||
|
pub struct Glyph {
|
||||||
|
pub glyph_id: u16,
|
||||||
|
pub palette_id: u8,
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
use crate::color::Color;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
pub const GLYPH_BANK_MAX_PALETTE_COUNT_V1: usize = 64;
|
||||||
|
pub const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
|
||||||
|
|
||||||
|
/// Standard sizes for square tiles.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub enum TileSize {
|
||||||
|
/// 8x8 pixels.
|
||||||
|
Size8 = 8,
|
||||||
|
/// 16x16 pixels.
|
||||||
|
Size16 = 16,
|
||||||
|
/// 32x32 pixels.
|
||||||
|
Size32 = 32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A container for graphical assets.
|
||||||
|
///
|
||||||
|
/// A GlyphBank stores the decoded runtime representation of a glyph-bank asset.
|
||||||
|
///
|
||||||
|
/// Serialized `assets.pa` payloads keep pixel indices packed as `4bpp` nibbles.
|
||||||
|
/// After decode, the runtime expands them to one `u8` palette index per pixel
|
||||||
|
/// while preserving the same `0..15` logical range.
|
||||||
|
pub struct GlyphBank {
|
||||||
|
/// Dimension of each individual tile in the bank.
|
||||||
|
pub tile_size: TileSize,
|
||||||
|
/// Width of the full bank sheet in pixels.
|
||||||
|
pub width: usize,
|
||||||
|
/// Height of the full bank sheet in pixels.
|
||||||
|
pub height: usize,
|
||||||
|
|
||||||
|
/// Decoded pixel data stored as one palette index per pixel.
|
||||||
|
/// Serialized payloads are packed; runtime memory is expanded.
|
||||||
|
/// 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.
|
||||||
|
///
|
||||||
|
/// 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 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],
|
||||||
|
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)
|
||||||
|
pub fn get_pixel_index(&self, tile_id: u16, local_x: usize, local_y: usize) -> u8 {
|
||||||
|
let size = self.tile_size as usize;
|
||||||
|
let tiles_per_row = self.width / size;
|
||||||
|
let tile_x = (tile_id as usize % tiles_per_row) * size;
|
||||||
|
let tile_y = (tile_id as usize / tiles_per_row) * size;
|
||||||
|
|
||||||
|
let pixel_x = tile_x + local_x;
|
||||||
|
let pixel_y = tile_y + local_y;
|
||||||
|
|
||||||
|
if pixel_x < self.width && pixel_y < self.height {
|
||||||
|
self.pixel_indices[pixel_y * self.width + pixel_x]
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
use crate::platform::RuntimePlatform;
|
||||||
|
use crate::vm_fault::VmFault;
|
||||||
|
|
||||||
|
pub struct HostContext<'a> {
|
||||||
|
pub platform: Option<&'a mut dyn RuntimePlatform>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> HostContext<'a> {
|
||||||
|
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_platform(&mut self) -> Result<&mut dyn RuntimePlatform, VmFault> {
|
||||||
|
match &mut self.platform {
|
||||||
|
Some(platform) => Ok(*platform),
|
||||||
|
None => Err(VmFault::Unavailable),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait HostContextProvider {
|
||||||
|
fn make_ctx(&'_ mut self) -> HostContext<'_>;
|
||||||
|
}
|
||||||
@@ -0,0 +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> {
|
||||||
|
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) {
|
||||||
|
if self.admit() {
|
||||||
|
self.stack.push(Value::Boolean(v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn push_int(&mut self, v: i64) {
|
||||||
|
if self.admit() {
|
||||||
|
self.stack.push(Value::Int64(v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn push_null(&mut self) {
|
||||||
|
if self.admit() {
|
||||||
|
self.stack.push(Value::Null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// 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, 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
-4
@@ -15,12 +15,9 @@ pub struct InputSignals {
|
|||||||
|
|
||||||
pub start_signal: bool,
|
pub start_signal: bool,
|
||||||
pub select_signal: bool,
|
pub select_signal: bool,
|
||||||
|
|
||||||
// TOUCH
|
// TOUCH
|
||||||
pub f_signal: bool,
|
pub f_signal: bool,
|
||||||
pub x_pos: i32,
|
pub x_pos: i32,
|
||||||
pub y_pos: i32,
|
pub y_pos: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl InputSignals {
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
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;
|
||||||
|
pub mod color;
|
||||||
|
pub mod composer_status;
|
||||||
|
pub mod debugger_protocol;
|
||||||
|
pub mod gfx_bridge;
|
||||||
|
pub mod glyph;
|
||||||
|
pub mod glyph_bank;
|
||||||
|
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;
|
||||||
|
pub mod scene_viewport_cache;
|
||||||
|
pub mod scene_viewport_resolver;
|
||||||
|
pub mod sound_bank;
|
||||||
|
pub mod sprite;
|
||||||
|
pub mod syscalls;
|
||||||
|
pub mod telemetry;
|
||||||
|
pub mod tile;
|
||||||
|
pub mod tilemap;
|
||||||
|
pub mod touch_bridge;
|
||||||
|
pub mod value_snapshot;
|
||||||
|
pub mod vm_fault;
|
||||||
|
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 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;
|
||||||
+1
-2
@@ -1,5 +1,4 @@
|
|||||||
use crate::log::LogLevel;
|
use crate::log::{LogLevel, LogSource};
|
||||||
use crate::log::LogSource;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct LogEvent {
|
pub struct LogEvent {
|
||||||
+20
-3
@@ -1,10 +1,13 @@
|
|||||||
use std::collections::VecDeque;
|
|
||||||
use crate::log::{LogEvent, LogLevel, LogSource};
|
use crate::log::{LogEvent, LogLevel, LogSource};
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
|
||||||
pub struct LogService {
|
pub struct LogService {
|
||||||
events: VecDeque<LogEvent>,
|
events: VecDeque<LogEvent>,
|
||||||
capacity: usize,
|
capacity: usize,
|
||||||
next_seq: u64,
|
next_seq: u64,
|
||||||
|
pub logs_count: Arc<AtomicU32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LogService {
|
impl LogService {
|
||||||
@@ -13,10 +16,19 @@ impl LogService {
|
|||||||
events: VecDeque::with_capacity(capacity),
|
events: VecDeque::with_capacity(capacity),
|
||||||
capacity,
|
capacity,
|
||||||
next_seq: 0,
|
next_seq: 0,
|
||||||
|
logs_count: Arc::new(AtomicU32::new(0)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn log(&mut self, ts_ms: u64, frame: u64, level: LogLevel, source: LogSource, tag: u16, msg: String) {
|
pub fn log(
|
||||||
|
&mut self,
|
||||||
|
ts_ms: u64,
|
||||||
|
frame: u64,
|
||||||
|
level: LogLevel,
|
||||||
|
source: LogSource,
|
||||||
|
tag: u16,
|
||||||
|
msg: String,
|
||||||
|
) {
|
||||||
if self.events.len() >= self.capacity {
|
if self.events.len() >= self.capacity {
|
||||||
self.events.pop_front();
|
self.events.pop_front();
|
||||||
}
|
}
|
||||||
@@ -30,6 +42,11 @@ impl LogService {
|
|||||||
msg,
|
msg,
|
||||||
});
|
});
|
||||||
self.next_seq += 1;
|
self.next_seq += 1;
|
||||||
|
self.logs_count.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reset_count(&mut self) {
|
||||||
|
self.logs_count.store(0, Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_recent(&self, n: usize) -> Vec<LogEvent> {
|
pub fn get_recent(&self, n: usize) -> Vec<LogEvent> {
|
||||||
@@ -55,7 +72,7 @@ mod tests {
|
|||||||
service.log(100, 1, LogLevel::Info, LogSource::Pos, 0, "Log 1".to_string());
|
service.log(100, 1, LogLevel::Info, LogSource::Pos, 0, "Log 1".to_string());
|
||||||
service.log(110, 1, LogLevel::Info, LogSource::Pos, 0, "Log 2".to_string());
|
service.log(110, 1, LogLevel::Info, LogSource::Pos, 0, "Log 2".to_string());
|
||||||
service.log(120, 1, LogLevel::Info, LogSource::Pos, 0, "Log 3".to_string());
|
service.log(120, 1, LogLevel::Info, LogSource::Pos, 0, "Log 3".to_string());
|
||||||
|
|
||||||
assert_eq!(service.events.len(), 3);
|
assert_eq!(service.events.len(), 3);
|
||||||
assert_eq!(service.events[0].msg, "Log 1");
|
assert_eq!(service.events[0].msg, "Log 1");
|
||||||
|
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
mod log_level;
|
|
||||||
mod log_source;
|
|
||||||
mod log_event;
|
mod log_event;
|
||||||
|
mod log_level;
|
||||||
mod log_service;
|
mod log_service;
|
||||||
|
mod log_source;
|
||||||
|
|
||||||
pub use log_level::LogLevel;
|
|
||||||
pub use log_source::LogSource;
|
|
||||||
pub use log_event::LogEvent;
|
pub use log_event::LogEvent;
|
||||||
|
pub use log_level::LogLevel;
|
||||||
pub use log_service::LogService;
|
pub use log_service::LogService;
|
||||||
|
pub use log_source::LogSource;
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
//! 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,
|
||||||
|
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,17 @@
|
|||||||
|
use crate::vm_fault::VmFault;
|
||||||
|
use prometeu_bytecode::{TRAP_TYPE, Value};
|
||||||
|
|
||||||
|
pub fn expect_int(args: &[Value], idx: usize) -> Result<i64, VmFault> {
|
||||||
|
args.get(idx)
|
||||||
|
.and_then(|v| v.as_integer())
|
||||||
|
.ok_or_else(|| VmFault::Trap(TRAP_TYPE, format!("Expected integer at index {}", idx)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn expect_bool(args: &[Value], idx: usize) -> Result<bool, VmFault> {
|
||||||
|
args.get(idx)
|
||||||
|
.and_then(|v| match v {
|
||||||
|
Value::Boolean(b) => Some(*b),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.ok_or_else(|| VmFault::Trap(TRAP_TYPE, format!("Expected boolean at index {}", idx)))
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
use crate::host_context::HostContext;
|
||||||
|
use crate::host_return::HostReturn;
|
||||||
|
use crate::vm_fault::VmFault;
|
||||||
|
use prometeu_bytecode::Value;
|
||||||
|
|
||||||
|
pub type SyscallId = u32;
|
||||||
|
|
||||||
|
pub trait NativeInterface {
|
||||||
|
/// Dispatches a syscall from the Virtual Machine to the native implementation.
|
||||||
|
///
|
||||||
|
/// ABI Rule: Arguments for the syscall are passed in `args`.
|
||||||
|
///
|
||||||
|
/// Returns are written via `ret`.
|
||||||
|
fn syscall(
|
||||||
|
&mut self,
|
||||||
|
id: SyscallId,
|
||||||
|
args: &[Value],
|
||||||
|
ret: &mut HostReturn,
|
||||||
|
ctx: &mut HostContext,
|
||||||
|
) -> Result<(), VmFault>;
|
||||||
|
}
|
||||||
@@ -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,20 @@
|
|||||||
|
use crate::button::Button;
|
||||||
|
use crate::input_signals::InputSignals;
|
||||||
|
|
||||||
|
pub trait PadBridge {
|
||||||
|
fn begin_frame(&mut self, signals: &InputSignals);
|
||||||
|
fn any(&self) -> bool;
|
||||||
|
|
||||||
|
fn up(&self) -> &Button;
|
||||||
|
fn down(&self) -> &Button;
|
||||||
|
fn left(&self) -> &Button;
|
||||||
|
fn right(&self) -> &Button;
|
||||||
|
fn a(&self) -> &Button;
|
||||||
|
fn b(&self) -> &Button;
|
||||||
|
fn x(&self) -> &Button;
|
||||||
|
fn y(&self) -> &Button;
|
||||||
|
fn l(&self) -> &Button;
|
||||||
|
fn r(&self) -> &Button;
|
||||||
|
fn start(&self) -> &Button;
|
||||||
|
fn select(&self) -> &Button;
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user