Skip to content

Commit 1af6a11

Browse files
wilco2009claude
andcommitted
zx81sd: bank large data tables into block 7, --asm build option
Programs whose compiled size exceeds the ~32KB code/sysvar/heap budget (sprite bitmaps, screen dumps, sample tables...) can now relocate big constant data out of the way via a manual ORG into block 7 ($E000- $FFFF, previously unused). Adds block 7 to the boot page-map, and teaches split_sd81.py to skip packaging/loading pages that come out as 100% assembler gap-filler (the unused span this creates between code and the relocated data), instead of wastefully shipping/loading them. build_sd81.py gains --asm to also emit the generated assembly listing (a second zxbc.py pass), useful for tracing bugs live against the .map. Documents a related gotcha found while doing this on Mario GW: relocating a sub's asm body with ORG doesn't move where @name resolves to, since the compiler's own entry label is emitted before the ORG takes effect (PRECAUTIONS.md section 9, cross-linked from PORTING_GUIDE.md step 6). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 853b2ff commit 1af6a11

5 files changed

Lines changed: 130 additions & 10 deletions

File tree

‎src/arch/zx81sd/backend/main.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
(3, 11), # block 3 -> page 11
4949
(4, 12), # block 4 -> page 12
5050
(5, 13), # block 5 -> page 13
51+
(7, 15), # block 7 -> page 15 (data banking: large static tables via explicit ORG)
5152
]
5253

5354
_SD81_PAGE_PORT = 0xE7 # memory mapper port (full mode: OUT (C), A)

‎src/arch/zx81sd/doc/PORTING_GUIDE.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,13 @@ address-of reference at **global** scope keeps it alive:
140140
dim __keep_sprites as uinteger: __keep_sprites = @sprites
141141
```
142142

143+
If you're banking a large data table (sprites, a level map...) into
144+
block 7 to fit under the `$8000` budget (step 8) by wrapping a `sub`'s
145+
`asm` body in a manual `ORG $E000`/restore, `@name` stops pointing at
146+
the relocated data entirely (a different, related gap — see
147+
[PRECAUTIONS.md](PRECAUTIONS.md) section 9) — you'll need both this
148+
dead-code workaround *and* to stop using `@name` as an address.
149+
143150
## 7. Sysvar scratch bugs already fixed in the runtime — no action needed
144151

145152
Several shared `zx48k/runtime/` files historically hardcoded a raw

‎src/arch/zx81sd/doc/PRECAUTIONS.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,52 @@ Any real program using your library will almost certainly also use
234234
`sysvars.asm` — so leaving out the `#include` in your file is safe in
235235
practice, not a hack.
236236

237+
## 9. Relocating a `sub`'s content with a manual `ORG` leaves `@name` behind
238+
239+
If a program is too big to fit under the `$8000` sysvar/heap boundary
240+
(step 8 of [PORTING_GUIDE.md](PORTING_GUIDE.md)), a large constant data
241+
block (a sprite bitmap table, a level map...) can be banked out of the
242+
way by wrapping it in `ORG $E000` / restore-the-previous-`ORG` inside
243+
its `sub`'s `asm ... end asm` body, moving it into block 7 instead of
244+
the code/sysvar/heap area. This works for the **data bytes** — but
245+
`@name` (used from BASIC to get the sub's address, e.g. `poke @name,x`)
246+
keeps pointing at the sub's **original**, un-relocated position, not
247+
the `ORG`'d one.
248+
249+
The reason: `@name` resolves to wherever zxbasic's own auto-generated
250+
`_name:` entry label ends up, and that label is emitted as literal ASM
251+
text **immediately before** your `asm` block's own content — i.e.
252+
before your `ORG` line has had any effect. Labels bind to the
253+
assembler's address counter at the point they're textually defined
254+
(ordinary, correct assembler behavior — `zxbasm` isn't doing anything
255+
wrong here), so redirecting the content elsewhere doesn't drag the
256+
label along with it. If nothing else ever gets emitted at the sub's
257+
"natural" position (because everything real was redirected away by the
258+
`ORG`), the auto-generated `_name` and `_name__leave` (end-of-function)
259+
labels end up at the very same address — a telltale sign in the
260+
debugger/disassembly that `@name` is stale: it'll resolve to
261+
`._name_leave`, not to your relocated data.
262+
263+
Found while banking Mario GW's sprite bitmap table (`sub sprite()`,
264+
~5.4KB) into block 7: `init_sprites()`/`tilexy()`/`tilexyaddr()` all
265+
used `@sprite+N` to read/poke into it, silently computing addresses
266+
against the *old* position once the data itself moved to `$E000`.
267+
Symptom: no error at compile or load time — the game ran, the intro
268+
screen and music played fine, and it hung in an apparently unrelated
269+
infinite loop deep inside the sprite-blit routine (`tylexyasm`, stuck
270+
forever on `jr nz, sigline`), because the wrong addresses eventually
271+
corrupted the `(IX+n)` scratch fields the blit routine's own loop
272+
termination depends on — several steps removed from the actual bug.
273+
274+
**Workaround**: don't use `@name` for a sub whose content you've
275+
manually `ORG`'d elsewhere — use the literal target address directly
276+
(e.g. `$E000`) everywhere `@name` was used, under `#ifdef __ZX81SD__`.
277+
The `sub` declaration itself must stay (it's still what emits the
278+
relocated bytes), but since nothing references it via `@name` any more,
279+
guard it against the dead-code eliminator (section 6 above) with a
280+
throwaway global reference, e.g.
281+
`dim __keep as uinteger: __keep = @name`.
282+
237283
## See also
238284

239285
- [PORTING_GUIDE.md](PORTING_GUIDE.md) — step-by-step checklist for

‎src/arch/zx81sd/tools/build_sd81.py‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
generates <BASE>.P, the tokenized BASIC loader)
1414
1515
Usage:
16-
python build_sd81.py <source.bas> [output_base] [--copy-to DIR]
16+
python build_sd81.py <source.bas> [output_base] [--copy-to DIR] [--asm]
1717
[-O LEVEL] [-D MACRO ...] [zxbc.py extra args...]
1818
1919
output_base defaults to the source file's name (without extension),
@@ -24,6 +24,14 @@
2424
loader, and boot1.bin (from this tools/ folder) to DIR (e.g. an
2525
emulator's virtual-SD test folder).
2626
27+
--asm: also emit <base>.asm, the generated assembly listing (a second
28+
zxbc.py pass with -f asm, same source/optimize/defines). Off by
29+
default (it's a much bigger file than the .map and rarely needed) —
30+
turn it on when tracing a bug live against the .map/disassembly, to
31+
see the actual instructions around a given address instead of just
32+
its label. The .map (symbol addresses) is still always generated,
33+
unconditionally, as before.
34+
2735
__ZX81SD__ is always defined; pass more -D flags to add extras.
2836
Any unrecognized argument is forwarded to zxbc.py as-is (e.g. to
2937
tweak heap size, warnings, etc.).
@@ -56,6 +64,9 @@ def main():
5664
ap.add_argument(
5765
"--copy-to", metavar="DIR", help="Also copy the page files + .P loader here"
5866
)
67+
ap.add_argument(
68+
"--asm", action="store_true", help="Also emit <base>.asm (the generated assembly listing)"
69+
)
5970
ap.add_argument("-O", "--optimize", default="2", help="zxbc.py optimization level (default 2)")
6071
ap.add_argument(
6172
"-D",
@@ -101,6 +112,29 @@ def main():
101112
print(" ".join(zxbc_cmd))
102113
subprocess.run(zxbc_cmd, check=True)
103114

115+
if args.asm:
116+
asm_path = workdir / f"{base}.asm"
117+
asm_cmd = [
118+
sys.executable,
119+
str(ZXBC),
120+
str(source),
121+
"--arch=zx81sd",
122+
"-O",
123+
args.optimize,
124+
"-f",
125+
"asm",
126+
"-o",
127+
str(asm_path),
128+
]
129+
for d in ["__ZX81SD__"] + args.define:
130+
asm_cmd += ["-D", d]
131+
asm_cmd += extra
132+
133+
print()
134+
print("== zxbc.py (asm) ==")
135+
print(" ".join(asm_cmd))
136+
subprocess.run(asm_cmd, check=True)
137+
104138
print()
105139
print("== split_sd81.py ==")
106140
split_cmd = [sys.executable, str(SPLIT_SCRIPT), str(bin_path), base]

‎src/arch/zx81sd/tools/split_sd81.py‎

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,15 @@
1313
Page 11 -> block 3 ($6000-$7FFF): same (external stage 1 resides here before the jump)
1414
Page 12 -> block 4 ($8000-$9FFF): sysvars + heap (data, not executable without MC45)
1515
Page 13 -> block 5 ($A000-$BFFF): heap continuation
16+
Page 15 -> block 7 ($E000-$FFFF): data banking (large static tables placed
17+
here via explicit ORG, out of the code/sysvar/heap budget)
18+
19+
Any page that comes out 100% zero bytes is the assembler's own gap filler
20+
(zxbasm zero-fills address ranges nothing was ever written to — see
21+
src/zxbasm/memory.py), not real content: typically the unused span between
22+
the end of code and a data table deliberately ORG'd into block 7. Sysvars
23+
and heap are always freshly initialized at runtime, so this is safe to
24+
skip entirely — the page is neither packaged nor loaded (see split()).
1625
1726
The binary starts at $0000 and includes no .tap/.tzx header. Each
1827
output file is named <BASE>P<N>.BIN (uppercase), where N is the page.
@@ -76,20 +85,43 @@
7685
LOAD_WINDOW_ADDR = 57344 # $E000, block 7's window
7786

7887

79-
def split(input_path: str, output_base: str) -> list[str]:
88+
def split(input_path: str, output_base: str) -> list[tuple[int, str]]:
8089
with open(input_path, "rb") as f:
8190
data = f.read()
8291

8392
if not data:
8493
sys.exit(f"Error: {input_path} is empty")
8594

86-
pages_written = []
95+
pages_written: list[tuple[int, str]] = []
8796
page_num = FIRST_PAGE
8897
offset = 0
8998

9099
while offset < len(data):
91-
chunk = data[offset : offset + PAGE_SIZE]
100+
raw_chunk = data[offset : offset + PAGE_SIZE]
101+
102+
# A full (unpadded) page that's 100% zero bytes is the assembler's own
103+
# gap filler (zxbasm's MEMORY.dump() zero-fills any address range
104+
# nothing was ever written to — see src/zxbasm/memory.py), not real
105+
# program content. This shows up when a data table is deliberately
106+
# ORG'd far away from the code (e.g. into block 7, $E000+, to keep
107+
# it out of the code/sysvar/heap budget below $8000): everything in
108+
# between is a zero-filled gap that never needs to reach the SD card,
109+
# since sysvars/heap are freshly initialized at runtime anyway and
110+
# nothing reads that memory before writing it first. Skip packaging
111+
# and loading it — the runtime page-mapping (OUT to port $E7) for
112+
# that block is unaffected, it just won't have been pre-loaded with
113+
# this particular (irrelevant) content.
114+
if len(raw_chunk) == PAGE_SIZE and raw_chunk.count(0) == PAGE_SIZE:
115+
print(
116+
f" Page {page_num} (block {page_num - FIRST_PAGE}): "
117+
f"[{offset:#06x} - {offset + PAGE_SIZE - 1:#06x}] "
118+
"all zero filler, skipped (not packaged/loaded)"
119+
)
120+
offset += PAGE_SIZE
121+
page_num += 1
122+
continue
92123

124+
chunk = raw_chunk
93125
# Pad up to PAGE_SIZE with 0xFF (undefined value for unwritten FLASH/RAM)
94126
if len(chunk) < PAGE_SIZE:
95127
chunk = chunk + b"\xff" * (PAGE_SIZE - len(chunk))
@@ -98,7 +130,7 @@ def split(input_path: str, output_base: str) -> list[str]:
98130
with open(out_path, "wb") as f:
99131
f.write(chunk)
100132

101-
pages_written.append(out_path)
133+
pages_written.append((page_num, out_path))
102134
print(
103135
f" Page {page_num} (block {page_num - FIRST_PAGE}): "
104136
f"{out_path} "
@@ -111,15 +143,14 @@ def split(input_path: str, output_base: str) -> list[str]:
111143
return pages_written
112144

113145

114-
def generate_loader_lines(page_files: list[str]) -> list[tuple[int, str]]:
146+
def generate_loader_lines(pages: list[tuple[int, str]]) -> list[tuple[int, str]]:
115147
lines = []
116148
lines.append((2, "FAST"))
117149
lines.append((5, f"LOAD THEN CLEAR {CLEAR_ADDR}"))
118150
lines.append((10, f'LOAD FAST "{BOOT1_FILE}"CODE {BOOT1_ADDR}'))
119151

120152
line_no = 20
121-
for i, page_file in enumerate(page_files):
122-
page_num = FIRST_PAGE + i
153+
for page_num, page_file in pages:
123154
lines.append((line_no, f"LOAD *MAP 7,{page_num}"))
124155
lines.append((line_no + 5, f'LOAD FAST "{page_file}"CODE {LOAD_WINDOW_ADDR}'))
125156
line_no += 10
@@ -173,8 +204,9 @@ def main():
173204
print(f"Generated {len(pages)} file(s).")
174205
if len(pages) == 1:
175206
print("The program fits in a single page (8 KB).")
176-
else:
177-
print(f"Pages {FIRST_PAGE} to {FIRST_PAGE + len(pages) - 1}.")
207+
elif pages:
208+
page_numbers = [p for p, _ in pages]
209+
print(f"Pages {min(page_numbers)} to {max(page_numbers)} (some may have been skipped as filler).")
178210

179211
loader_lines = generate_loader_lines(pages)
180212
loader_text = generate_loader_text(loader_lines)

0 commit comments

Comments
 (0)