jarikomppa / specnext

Collection of my projects for zx spectrum next
The Unlicense
47 stars 7 forks source link

Sync address corrupted with CLEAR $9FFF prior to .sync #8

Open NealeTools opened 1 month ago

NealeTools commented 1 month ago

Sync address corrupted ("INVERSE w") if CLEAR $9FFF is issued in NextBASIC prior to a manual .sync from the the NextBASIC editor. Link to discussion: https://discord.com/channels/556228195767156758/753259643051966554/1284854875741618219

jarikomppa commented 1 month ago

note for future me: problem is with delaying command line reading before mucking about with the memory map

janko-jj commented 1 month ago

In this scenario (misbehavior after "CLEAR $9FFF : .sync") that CLEAR moved the stack to the only part of the memory where it can be corrupted by the active crt0 code:

shutdown:
        ld      a,      #0x54 ; nextreg
        ld      bc,     #0x243B   ; nextreg select
        out     (c),    a
        inc     b                 ; nextreg i/o
        ld      a, (_mmu4)
        out     (c),     a
        ; * <=============== ld sp,(#store_sp)   is needed here to avoid the corruption of the paged in page

        ld      de, (_pagehandle)       ; page
        ld      hl, #0x0003             ; free zx memory
        exx                             ; place parameters in alternates
        ld      de, #0x01bd             ; IDE_BANK
        ld      c, #7                   ; "usually 7, but 0 for some calls"
        rst     #0x8
        .db     #0x94                   ; +3dos call
allocfail:  
        ld sp,(#store_sp)       ; restore original SP 

Without restoring the SP, the following locations (-0x80+0x8000 in RAM) are instead of remaining unchanged:

-00002060: 0000 0000 0000 0000 0000 0000 0000 0000  ................
-00002070: 0000 0000 0000 0000 0000 0000 0000 0000  ................

overwritten with:

+00002060: 0000 0000 0000 0000 0000 00e8 3b1b e0bb  ............;...
+00002070: 3385 201b e029 3f4c 0567 2044 0067 2000  3. ..)?L.g D.g .

There, 0x2067 corresponds to the address after the rst $08 and the "code" byte from the crt0:

2063 0e07      ld      c,$07
2065 cf        rst     $08
2066 94        sub     h
2067 ed7b7c20  ld      sp,($207c)
206b e1        pop     hl
206c d1        pop     de