sdcc -v
SDCC : z80/sm83/mos6502/mos65c02 TD- 4.3.0 #14110 (Linux)
Generated code for a function has a loop which seems to result in an imbalanced stack (more pushes than pops) that causes a crash on return.
Attached repro example is from a GBDK user. They reduced it down some and I've reduced it down further, but the function is still a bit large. It's at the point where removing code now sometimes causes the bug to vanish.
Adding the --nolospre to the SDCC arguments removes the bug.
Adding -Wf--max-allocs-per-node10000 instead also removes the bug, but lower values (such as 5000) does not remove the bug.
The relevant section seems to be this:
ld a, #0x05
00216$:
push af
ldhl sp, #14
sla (hl)
inc hl
rl (hl)
dec a
jr NZ, 00216$
pop af
For reference, below are the build commands used, but it's been stripped of GBDK specific code and should build without it.
```
sdcc -msm83 --no-std-crt0 --fsigned-char --use-stdout -D__PORT_sm83 -D__TARGET_gb -Wa-pogn -I"/gbdk/gbdk_4.2.0/gbdk/"lib/gb -DINT_16_BITS --debug -I"/gbdk/gbdk_4.2.0/gbdk/"include -c main.c -o o/main.o
sdldgb -n -i -y -j -g _shadow_OAM=0xC000 -g .STACK=0xE000 -g .refresh_OAM=0xFF80 -b _DATA=0xC0A0 -b _CODE=0x0200 -k "gbdk/gbdk_4.2.0/gbdk/"lib/sm83/ -l sm83.lib -k "gbdk/gbdk_4.2.0/gbdk/"lib/gb/ -l gb.lib MinimumCrash.ihx "gbdev/gbdk/gbdk_4.2.0/gbdk/"lib/gb/crt0.o o/main.o
makebin -yN -Z MinimumCrash.ihx MinimumCrash.gb
``
That main.c includes a
rand.hthat is not part of the standard libary. It also uses a number of unknown types (e.g. UINT8, INT8, WORD, UINT16, INT16, UBYTE).Sorry about that, here is an updated version that is more generic
Thanks. I can compile that one (though the generated asm looks fine on my system - I tried sdcc builds both with and without the treedec library). However, I think I found the problematic part in z80 code generation.
However, I think I have been able to track down the issue in code generation anyway. In principle, it affects all z80-related ports, but it is on a code path rarely used by ports other than sm83.
The attached patch should fix it.
And here is a regression test for the bug.
Thanks! Yes, your patch appears to resolve the issue. It removes the leading POP as well as the looped PUSH. The stack pointer is at the correct value when returning from the function, so the program no longer crashes.
A diff on the output
Fixed in the next branch in [r14194].
Related
Commit: [r14194]
Fixed in [r14211] by merging next to trunk.
Related
Commit: [r14211]