줄바꿈을 LF로 통일

서버에서 바로 빌드하고 고칠 수 있게 저장소 줄바꿈을 LF로 맞췄습니다.
CRLF로 들어가 있던 sh 빌드 스크립트도 이제 리눅스에서 그대로 돌아갑니다.
내용은 바뀌지 않았습니다.
This commit is contained in:
syskiller committed 2026-11-24 07:13:54 +09:00
1 parent 40615838ac
commit 2d48091205
623 files changed
+501372 -501365

No files matched your search

+52 -52
View File
@@ -1,52 +1,52 @@
# ArduboyEmu
The Arduboy on the Tamagotchi Paradise, as a further program of the Paramix menu.
No game here: bring your own games (.hex).
- `src/core/avr.c`: own emulation of the ATmega32U4 (16 MHz AVR) and of what the Arduboy uses of it:
- CPU: every instruction of the AVRe+ core with its cycles. The program is decoded once into one word per
instruction (handler and operands). The flags are kept apart and only put together when SREG is read.
Straight code runs without the event check; jumps check it.
- Timers 0, 1, 3 and 4: brought up to date when read or written and at their next event (all modes the
Arduino and Arduboy libraries use). Each timer's next event is kept until a write, a flag or an interrupt
changes it (AB_EVC), so a fast sound interrupt costs little.
- SPI to the SSD1306 display (commands, both addressing modes, inverting, contrast, start line, flipping), the
display's reset pin, the state the boot loader leaves it in.
- Buttons on the pins (kept current in the data space, so reading them is a plain load), EEPROM (1 KB), ADC (random values for seeds), PLL, watchdog (reset), sleep.
- Busy waiting (AB_SPIN): a loop that only asks the clock (millis(), micros()) and changes nothing is skipped up to
the next event.
- Sound: the tone of the speaker pins, from the timer that drives them or from the pin changes (AB_SND2: the pitch
from the times of the changes, both pins at once count once), and the PWM samples of OC4A (ATMlib music) from
their rising edges. The program leaves out changes below 3 % so the buzzer is not started anew every 20 ms.
- `src/core/jit.inc` (AB_JIT, on the Paradise): the fast core. The program is translated block by block into Thumb-2
code in the SRAM (a 56 KB cache, emptied when full). AVR registers stay in the data space, the flags in ARM
registers; a flag is only worked out when something later reads it (H only inside a block). Blocks jump straight
to each other while cycles are left (AB_CHAIN), else through a small dispatcher. Rare instructions (I/O, SREG,
sleep, the signed multiplications) run in C (`jit_op`) with the flags handed over. The display byte (OUT SPDR) has its
own short helper; reading SPSR and the button pins, and SBIC/SBIS on them, are translated inline. On the PC the interpreter of
avr.c runs (it is the reference).
- `src/app/main.c`: the Paradise program (PRAM). Settings block "ABXP" at 0x140: game, length, save, flags (bit 0
English, bit 1 wheel the other way round), name, keys (12 bytes: Arduboy buttons for the Paradise inputs 0 A, 1 B,
2 C, 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B; bits 1 up, 2 down, 4 left, 8 right, 16 A, 32 B).
The game lies at the start of its own 64 KB block (the cached window), the save behind it at +0x8000 (4 KB settings,
4 KB EEPROM, 8 KB state).
- Screen: 128 x 64 at 1:1, 3:2 or 2:1 height (setting PICTURE, default 1:1 = SMALL, switch AB_SIZE0). Pictures that games switch for greys come out grey.
- Fixed keys: A+B+C settings (colour, picture, sound, light, dim, screen off, restart game, language); wheel held 2 s
= save and back to the Paradise.
- Save: the EEPROM goes to the flash 3 s after the game wrote it (1 s without a key), when the screen goes off and on
leaving. On leaving the whole state too (`emu/src/emu/pstate.h`), read once at the next start.
- The core is built with GCC (arm-none-eabi-gcc): each handler gets its own dispatch.
Build: `sh src/app/build.sh` gives `ab.bin`.
Tests:
- `test/hostab.c` (gcc on the PC): runs a game, pictures as PGM (KEYS, SHOTS, OUT, PCS for a pc histogram).
- `test/fuzz.c`, `test/lock.c`: the CPU against simavr (libsimavr-dev), see the files.
- `test/jitfuzz/`: random programs run by the interpreter on the PC and by the fast core in Unicorn, compared
(`run.sh seed`).
- `python3 test/mkimg.py ab.bin game.hex img.bin` then `python3 test/devab.py src/app/ab.elf img.bin <ms>` (Unicorn,
KEYS="t:mask,...", SHOTS="t,...", OUT=dir); `test/prof.py` instructions per function, `test/profl.py` per line.
Author: mameise
No session (1.7.3 test7, switch SESS_FLAG): flags bit 12 set by the Studio ("Remember where you left off" off): leaving writes
no state, a start drops an old one; only the game's own save (cartridge RAM or EEPROM) is kept.
# ArduboyEmu
The Arduboy on the Tamagotchi Paradise, as a further program of the Paramix menu.
No game here: bring your own games (.hex).
- `src/core/avr.c`: own emulation of the ATmega32U4 (16 MHz AVR) and of what the Arduboy uses of it:
- CPU: every instruction of the AVRe+ core with its cycles. The program is decoded once into one word per
instruction (handler and operands). The flags are kept apart and only put together when SREG is read.
Straight code runs without the event check; jumps check it.
- Timers 0, 1, 3 and 4: brought up to date when read or written and at their next event (all modes the
Arduino and Arduboy libraries use). Each timer's next event is kept until a write, a flag or an interrupt
changes it (AB_EVC), so a fast sound interrupt costs little.
- SPI to the SSD1306 display (commands, both addressing modes, inverting, contrast, start line, flipping), the
display's reset pin, the state the boot loader leaves it in.
- Buttons on the pins (kept current in the data space, so reading them is a plain load), EEPROM (1 KB), ADC (random values for seeds), PLL, watchdog (reset), sleep.
- Busy waiting (AB_SPIN): a loop that only asks the clock (millis(), micros()) and changes nothing is skipped up to
the next event.
- Sound: the tone of the speaker pins, from the timer that drives them or from the pin changes (AB_SND2: the pitch
from the times of the changes, both pins at once count once), and the PWM samples of OC4A (ATMlib music) from
their rising edges. The program leaves out changes below 3 % so the buzzer is not started anew every 20 ms.
- `src/core/jit.inc` (AB_JIT, on the Paradise): the fast core. The program is translated block by block into Thumb-2
code in the SRAM (a 56 KB cache, emptied when full). AVR registers stay in the data space, the flags in ARM
registers; a flag is only worked out when something later reads it (H only inside a block). Blocks jump straight
to each other while cycles are left (AB_CHAIN), else through a small dispatcher. Rare instructions (I/O, SREG,
sleep, the signed multiplications) run in C (`jit_op`) with the flags handed over. The display byte (OUT SPDR) has its
own short helper; reading SPSR and the button pins, and SBIC/SBIS on them, are translated inline. On the PC the interpreter of
avr.c runs (it is the reference).
- `src/app/main.c`: the Paradise program (PRAM). Settings block "ABXP" at 0x140: game, length, save, flags (bit 0
English, bit 1 wheel the other way round), name, keys (12 bytes: Arduboy buttons for the Paradise inputs 0 A, 1 B,
2 C, 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B; bits 1 up, 2 down, 4 left, 8 right, 16 A, 32 B).
The game lies at the start of its own 64 KB block (the cached window), the save behind it at +0x8000 (4 KB settings,
4 KB EEPROM, 8 KB state).
- Screen: 128 x 64 at 1:1, 3:2 or 2:1 height (setting PICTURE, default 1:1 = SMALL, switch AB_SIZE0). Pictures that games switch for greys come out grey.
- Fixed keys: A+B+C settings (colour, picture, sound, light, dim, screen off, restart game, language); wheel held 2 s
= save and back to the Paradise.
- Save: the EEPROM goes to the flash 3 s after the game wrote it (1 s without a key), when the screen goes off and on
leaving. On leaving the whole state too (`emu/src/emu/pstate.h`), read once at the next start.
- The core is built with GCC (arm-none-eabi-gcc): each handler gets its own dispatch.
Build: `sh src/app/build.sh` gives `ab.bin`.
Tests:
- `test/hostab.c` (gcc on the PC): runs a game, pictures as PGM (KEYS, SHOTS, OUT, PCS for a pc histogram).
- `test/fuzz.c`, `test/lock.c`: the CPU against simavr (libsimavr-dev), see the files.
- `test/jitfuzz/`: random programs run by the interpreter on the PC and by the fast core in Unicorn, compared
(`run.sh seed`).
- `python3 test/mkimg.py ab.bin game.hex img.bin` then `python3 test/devab.py src/app/ab.elf img.bin <ms>` (Unicorn,
KEYS="t:mask,...", SHOTS="t,...", OUT=dir); `test/prof.py` instructions per function, `test/profl.py` per line.
Author: mameise
No session (1.7.3 test7, switch SESS_FLAG): flags bit 12 set by the Studio ("Remember where you left off" off): leaving writes
no state, a start drops an old one; only the game's own save (cartridge RAM or EEPROM) is kept.
+19 -19
View File
@@ -1,19 +1,19 @@
#!/bin/sh
# Build ArduboyEmu for the Paradise (clang/lld, Cortex-M3). Output: ../../ab.bin
set -e
cd "$(dirname "$0")"
E=../../../emu/src/emu
C=../core
CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -fno-common -Wall -Wno-unused-function -Wno-unused-variable -Wno-parentheses -Wno-dangling-else -Wno-unknown-attributes -fno-builtin-memset -ffunction-sections -DAVR_FAST= -DPERFORMANCE -DFAST_LCD -DEXIT_KEY -DLCD_FASTCLK -DTONE_FIX -DBL_SLEEP -DPARA_BACK -DPARA_MB_KEEP -DBL_PWM -DBL_MR3RST -DTONE_SAFE -DGPLAY -DSESS_FLAG $XCF"
O=""
for f in main.c $C/avr.c $E/hw.c $E/flash.c $E/libc.c; do
n=$(basename $f .c); OPT=-Os
case $n in avr) OPT=-O2;; esac
if [ $n = avr ] && [ -z "$CLANG_CORE" ]; then
# the core with GCC: each handler gets its own dispatch (clang shares one indirect jump for all)
arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -fno-common -ffunction-sections -fno-tree-loop-distribute-patterns -Wall -Wno-unused-function -Wno-unused-variable -Wno-misleading-indentation -DAVR_FAST= $XCF -O2 -c $f -o $n.o
else clang $CF $OPT -c $f -o $n.o; fi
O="$O $n.o"; done
ld.lld -T link.ld --gc-sections --no-rosegment $O -o ab.elf
llvm-objcopy -O binary -j .text -j .data -j .init ab.elf ab.bin
cp ab.bin ../../ab.bin; rm -f *.o ab.bin; [ -n "$KEEPELF" ] || rm -f ab.elf; ls -l ../../ab.bin
#!/bin/sh
# Build ArduboyEmu for the Paradise (clang/lld, Cortex-M3). Output: ../../ab.bin
set -e
cd "$(dirname "$0")"
E=../../../emu/src/emu
C=../core
CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -fno-common -Wall -Wno-unused-function -Wno-unused-variable -Wno-parentheses -Wno-dangling-else -Wno-unknown-attributes -fno-builtin-memset -ffunction-sections -DAVR_FAST= -DPERFORMANCE -DFAST_LCD -DEXIT_KEY -DLCD_FASTCLK -DTONE_FIX -DBL_SLEEP -DPARA_BACK -DPARA_MB_KEEP -DBL_PWM -DBL_MR3RST -DTONE_SAFE -DGPLAY -DSESS_FLAG $XCF"
O=""
for f in main.c $C/avr.c $E/hw.c $E/flash.c $E/libc.c; do
n=$(basename $f .c); OPT=-Os
case $n in avr) OPT=-O2;; esac
if [ $n = avr ] && [ -z "$CLANG_CORE" ]; then
# the core with GCC: each handler gets its own dispatch (clang shares one indirect jump for all)
arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -fno-common -ffunction-sections -fno-tree-loop-distribute-patterns -Wall -Wno-unused-function -Wno-unused-variable -Wno-misleading-indentation -DAVR_FAST= $XCF -O2 -c $f -o $n.o
else clang $CF $OPT -c $f -o $n.o; fi
O="$O $n.o"; done
ld.lld -T link.ld --gc-sections --no-rosegment $O -o ab.elf
llvm-objcopy -O binary -j .text -j .data -j .init ab.elf ab.bin
cp ab.bin ../../ab.bin; rm -f *.o ab.bin; [ -n "$KEEPELF" ] || rm -f ab.elf; ls -l ../../ab.bin
+99 -99
View File
@@ -1,99 +1,99 @@
/* generated by gen/font.py: custom 5x7 font */
static const unsigned char g_font[96][7]={
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x04,0x04,0x04,0x04,0x04,0x00,0x04},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x19,0x19,0x02,0x04,0x08,0x13,0x13},
{0x0c,0x12,0x14,0x08,0x15,0x12,0x0d},
{0x04,0x04,0x08,0x00,0x00,0x00,0x00},
{0x02,0x04,0x08,0x08,0x08,0x04,0x02},
{0x08,0x04,0x02,0x02,0x02,0x04,0x08},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x04,0x04,0x1f,0x04,0x04,0x00},
{0x00,0x00,0x00,0x00,0x0c,0x04,0x08},
{0x00,0x00,0x00,0x1f,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x0c,0x0c},
{0x01,0x01,0x02,0x04,0x08,0x10,0x10},
{0x0e,0x11,0x13,0x15,0x19,0x11,0x0e},
{0x04,0x0c,0x04,0x04,0x04,0x04,0x0e},
{0x0e,0x11,0x01,0x02,0x04,0x08,0x1f},
{0x1e,0x01,0x01,0x0e,0x01,0x01,0x1e},
{0x02,0x06,0x0a,0x12,0x1f,0x02,0x02},
{0x1f,0x10,0x1e,0x01,0x01,0x11,0x0e},
{0x0e,0x10,0x10,0x1e,0x11,0x11,0x0e},
{0x1f,0x01,0x02,0x04,0x08,0x08,0x08},
{0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e},
{0x0e,0x11,0x11,0x0f,0x01,0x01,0x0e},
{0x00,0x04,0x04,0x00,0x04,0x04,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x02,0x04,0x08,0x10,0x08,0x04,0x02},
{0x00,0x00,0x1f,0x00,0x1f,0x00,0x00},
{0x08,0x04,0x02,0x01,0x02,0x04,0x08},
{0x0e,0x11,0x01,0x02,0x04,0x00,0x04},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x0e,0x11,0x11,0x1f,0x11,0x11,0x11},
{0x1e,0x11,0x11,0x1e,0x11,0x11,0x1e},
{0x0e,0x11,0x10,0x10,0x10,0x11,0x0e},
{0x1e,0x11,0x11,0x11,0x11,0x11,0x1e},
{0x1f,0x10,0x10,0x1e,0x10,0x10,0x1f},
{0x1f,0x10,0x10,0x1e,0x10,0x10,0x10},
{0x0e,0x11,0x10,0x17,0x11,0x11,0x0f},
{0x11,0x11,0x11,0x1f,0x11,0x11,0x11},
{0x0e,0x04,0x04,0x04,0x04,0x04,0x0e},
{0x07,0x02,0x02,0x02,0x02,0x12,0x0c},
{0x11,0x12,0x14,0x18,0x14,0x12,0x11},
{0x10,0x10,0x10,0x10,0x10,0x10,0x1f},
{0x11,0x1b,0x15,0x15,0x11,0x11,0x11},
{0x11,0x19,0x15,0x13,0x11,0x11,0x11},
{0x0e,0x11,0x11,0x11,0x11,0x11,0x0e},
{0x1e,0x11,0x11,0x1e,0x10,0x10,0x10},
{0x0e,0x11,0x11,0x11,0x15,0x12,0x0d},
{0x1e,0x11,0x11,0x1e,0x14,0x12,0x11},
{0x0f,0x10,0x10,0x0e,0x01,0x01,0x1e},
{0x1f,0x04,0x04,0x04,0x04,0x04,0x04},
{0x11,0x11,0x11,0x11,0x11,0x11,0x0e},
{0x11,0x11,0x11,0x11,0x11,0x0a,0x04},
{0x11,0x11,0x11,0x15,0x15,0x15,0x0a},
{0x11,0x11,0x0a,0x04,0x0a,0x11,0x11},
{0x11,0x11,0x0a,0x04,0x04,0x04,0x04},
{0x1f,0x01,0x02,0x04,0x08,0x10,0x1f},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x11,0x0a,0x04,0x0a,0x11},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x11,0x0e,0x11,0x1f,0x11,0x11,0x11},
{0x11,0x0e,0x11,0x11,0x11,0x11,0x0e},
{0x11,0x00,0x11,0x11,0x11,0x11,0x0e},
};
/* generated by gen/font.py: custom 5x7 font */
static const unsigned char g_font[96][7]={
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x04,0x04,0x04,0x04,0x04,0x00,0x04},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x19,0x19,0x02,0x04,0x08,0x13,0x13},
{0x0c,0x12,0x14,0x08,0x15,0x12,0x0d},
{0x04,0x04,0x08,0x00,0x00,0x00,0x00},
{0x02,0x04,0x08,0x08,0x08,0x04,0x02},
{0x08,0x04,0x02,0x02,0x02,0x04,0x08},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x04,0x04,0x1f,0x04,0x04,0x00},
{0x00,0x00,0x00,0x00,0x0c,0x04,0x08},
{0x00,0x00,0x00,0x1f,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x0c,0x0c},
{0x01,0x01,0x02,0x04,0x08,0x10,0x10},
{0x0e,0x11,0x13,0x15,0x19,0x11,0x0e},
{0x04,0x0c,0x04,0x04,0x04,0x04,0x0e},
{0x0e,0x11,0x01,0x02,0x04,0x08,0x1f},
{0x1e,0x01,0x01,0x0e,0x01,0x01,0x1e},
{0x02,0x06,0x0a,0x12,0x1f,0x02,0x02},
{0x1f,0x10,0x1e,0x01,0x01,0x11,0x0e},
{0x0e,0x10,0x10,0x1e,0x11,0x11,0x0e},
{0x1f,0x01,0x02,0x04,0x08,0x08,0x08},
{0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e},
{0x0e,0x11,0x11,0x0f,0x01,0x01,0x0e},
{0x00,0x04,0x04,0x00,0x04,0x04,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x02,0x04,0x08,0x10,0x08,0x04,0x02},
{0x00,0x00,0x1f,0x00,0x1f,0x00,0x00},
{0x08,0x04,0x02,0x01,0x02,0x04,0x08},
{0x0e,0x11,0x01,0x02,0x04,0x00,0x04},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x0e,0x11,0x11,0x1f,0x11,0x11,0x11},
{0x1e,0x11,0x11,0x1e,0x11,0x11,0x1e},
{0x0e,0x11,0x10,0x10,0x10,0x11,0x0e},
{0x1e,0x11,0x11,0x11,0x11,0x11,0x1e},
{0x1f,0x10,0x10,0x1e,0x10,0x10,0x1f},
{0x1f,0x10,0x10,0x1e,0x10,0x10,0x10},
{0x0e,0x11,0x10,0x17,0x11,0x11,0x0f},
{0x11,0x11,0x11,0x1f,0x11,0x11,0x11},
{0x0e,0x04,0x04,0x04,0x04,0x04,0x0e},
{0x07,0x02,0x02,0x02,0x02,0x12,0x0c},
{0x11,0x12,0x14,0x18,0x14,0x12,0x11},
{0x10,0x10,0x10,0x10,0x10,0x10,0x1f},
{0x11,0x1b,0x15,0x15,0x11,0x11,0x11},
{0x11,0x19,0x15,0x13,0x11,0x11,0x11},
{0x0e,0x11,0x11,0x11,0x11,0x11,0x0e},
{0x1e,0x11,0x11,0x1e,0x10,0x10,0x10},
{0x0e,0x11,0x11,0x11,0x15,0x12,0x0d},
{0x1e,0x11,0x11,0x1e,0x14,0x12,0x11},
{0x0f,0x10,0x10,0x0e,0x01,0x01,0x1e},
{0x1f,0x04,0x04,0x04,0x04,0x04,0x04},
{0x11,0x11,0x11,0x11,0x11,0x11,0x0e},
{0x11,0x11,0x11,0x11,0x11,0x0a,0x04},
{0x11,0x11,0x11,0x15,0x15,0x15,0x0a},
{0x11,0x11,0x0a,0x04,0x0a,0x11,0x11},
{0x11,0x11,0x0a,0x04,0x04,0x04,0x04},
{0x1f,0x01,0x02,0x04,0x08,0x10,0x1f},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x11,0x0a,0x04,0x0a,0x11},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x11,0x0e,0x11,0x1f,0x11,0x11,0x11},
{0x11,0x0e,0x11,0x11,0x11,0x11,0x0e},
{0x11,0x00,0x11,0x11,0x11,0x11,0x0e},
};
+23 -23
View File
@@ -1,23 +1,23 @@
ENTRY(Reset_Handler)
MEMORY {
PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000
SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F000
}
SECTIONS {
.text : {
KEEP(*(.vectors))
KEEP(*(.pmxcfg))
*(.text*)
*(.rodata*)
. = ALIGN(4);
__pdata_start = .;
} > PRAM
.bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM
/* mutable data in SRAM (initial values in PRAM, copied at startup), as in TamaEmu */
.data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM
__data_load = LOADADDR(.data);
.init : { . = ALIGN(4); KEEP(*(.initcode)) KEEP(*(.initdata*)) KEEP(*(.initcode_z)) . = ALIGN(4); __prog_end = .; } > PRAM
ASSERT(__prog_end <= 0x10000, "program too big for PRAM")
ASSERT(__bss_end <= 0x1801F000, "RAM full")
/DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) }
}
ENTRY(Reset_Handler)
MEMORY {
PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000
SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F000
}
SECTIONS {
.text : {
KEEP(*(.vectors))
KEEP(*(.pmxcfg))
*(.text*)
*(.rodata*)
. = ALIGN(4);
__pdata_start = .;
} > PRAM
.bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM
/* mutable data in SRAM (initial values in PRAM, copied at startup), as in TamaEmu */
.data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM
__data_load = LOADADDR(.data);
.init : { . = ALIGN(4); KEEP(*(.initcode)) KEEP(*(.initdata*)) KEEP(*(.initcode_z)) . = ALIGN(4); __prog_end = .; } > PRAM
ASSERT(__prog_end <= 0x10000, "program too big for PRAM")
ASSERT(__bss_end <= 0x1801F000, "RAM full")
/DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) }
}
+470 -470
View File
@@ -1,470 +1,470 @@
/* ArduboyEmu: the Arduboy on the Tamagotchi Paradise, a further program of the Paramix menu. Bring your own games
* (.hex). Core: own ATmega32U4 emulation (../core/avr.c).
* Screen: the Arduboy's 128 x 64 at 1:1, 3:2 or 2:1 height (setting PICTURE); greys that games make by switching two
* pictures come out as grey. Keys: set in the Studio (tab Arduboy). A+B+C together: settings; wheel held 2 s: save and
* back to the Paradise. Sound: the speaker's tone on the Paradise's buzzer. Save: the EEPROM (1 KB) goes to the flash a
* few seconds after the game wrote it, and on leaving; on leaving the whole state too, the next start continues there.
* Author: mameise */
#include "../../../emu/src/emu/hw.h"
#include "../../../emu/src/emu/exitkey.h"
#include "../../../emu/src/emu/flash.h"
#define PARA_ATTR
#include "../../../emu/src/emu/paraclock.h"
#ifdef PARA_BACK
#include "../../../emu/src/emu/paraback.h"
#ifdef GPLAY
#define GP_POINTS
#include "../../../emu/src/emu/gplay.h"
#endif
#endif
#include "../core/avr.h"
#include "font.h"
/* ---- settings block at 0x140, filled in by the Studio ----
* keys[i]: Arduboy buttons (bit 0 UP, 1 DOWN, 2 LEFT, 3 RIGHT, 4 A, 5 B) for the Paradise input i: 0 A, 1 B, 2 C,
* 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B. flags: bit 0 English, bit 1 wheel the other way round.
* save_off: 4 KB settings of the device, 4 KB EEPROM (1 KB used), then the state (up to 8 KB). */
#define NIN 9
typedef struct { u32 magic, version, rom_off, rom_len, save_off, flags; char name[16]; u8 keys[12]; } AbCfg;
#define AB_MAGIC 0x50584241u /* "ABXP" */
__attribute__((section(".pmxcfg"), used))
volatile const AbCfg g_cfg = { AB_MAGIC, 1, 0, 0, 0, 0, {0}, { AB_LEFT, AB_B, AB_RIGHT, AB_A, AB_UP, AB_DOWN, 0, 0, 0 } };
#define SETTINGS (g_cfg.save_off)
#define EEP_AT (g_cfg.save_off + 0x1000u)
#define STATE_AT (g_cfg.save_off + 0x2000u)
#define STATE_MAX 0x2000u
#define XIP_BASE_REG REG(0x4002F004u)
#define XIP_CTRL_REG REG(0x4002F000u)
#define ROMWIN ((const u16 *)0x10000000u)
/* ---- time: SysTick 1 ms; the wheel's encoder is read here too ---- */
static volatile u32 g_ms;
static volatile s32 g_enc_acc; static u32 g_enc_last;
static const signed char QD[16] = { 0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0 };
#define GPIO2 0x4001A000u
#define SYST_CSR REG(0xE000E010u)
#define SYST_RVR REG(0xE000E014u)
#define SYST_CVR REG(0xE000E018u)
#define CORE_HZ 96000000u
__attribute__((used)) void systick_c(void)
{
g_ms++;
u32 n = REG(GPIO2) & 3u;
if (n != g_enc_last) { g_enc_acc += QD[(g_enc_last << 2) | n]; g_enc_last = n; }
}
__attribute__((naked)) void SysTick_Handler(void) { __asm__ volatile("b systick_c\n"); }
void abort(void) { for (;;) hw_wdt_feed(); }
/* ---- settings on the device ---- */
typedef struct { u8 magic[4]; u8 pal, dim, lang, dimto, off, r0, size, mute; } AbSet; /* mute: 0 = sound on */
#ifndef AB_SIZE0
#define AB_SIZE0 0 /* 1.7.3 test10: picture size SMALL by default (1:1, not stretched); 1 = MEDIUM as before */
#endif
static AbSet g_set = { {'A','B','S','1'}, 0, 7, 0, 6, 3, 0x80, AB_SIZE0, 0 };
/* background, dot: white, amber, cyan (as the OLED), paper (black on white) */
static const u16 PAL[4][2] = { { 0x0000u, 0xFFFFu }, { 0x0000u, 0xFDA0u }, { 0x0000u, 0x5FFFu }, { 0xEF5Du, 0x10A2u } };
static const char *const PAL_NM[2][4] = { { "WEISS", "GELB", "BLAU", "PAPIER" }, { "WHITE", "AMBER", "CYAN", "PAPER" } };
static const char *const SIZE_NM[2][3] = { { "KLEIN", "MITTEL", "GROSS" }, { "SMALL", "MEDIUM", "LARGE" } };
#define T_N 7
static const u32 T_MS[T_N] = { 10000u, 20000u, 30000u, 60000u, 120000u, 300000u, 600000u };
static const char *const T_NM[2][T_N + 1] = { { "10 S", "20 S", "30 S", "1 MIN", "2 MIN", "5 MIN", "10 MIN", "NIE" }, { "10 S", "20 S", "30 S", "1 MIN", "2 MIN", "5 MIN", "10 MIN", "NEVER" } };
#define LV_N 11
#define DIM2_N 10
static const u8 LV_PCT[LV_N] = { 100u, 5u, 10u, 20u, 30u, 40u, 50u, 60u, 70u, 80u, 90u };
static const u8 DIM2_PCT[DIM2_N] = { 1u, 2u, 3u, 5u, 10u, 15u, 20u, 30u, 40u, 50u };
static int en(void) { return g_set.lang ? g_set.lang == 2u : (int)(g_cfg.flags & 1u); }
static u16 BG, INK, OFF;
static u16 g_lut[3]; /* dot off, grey, on (with the game's contrast) */
static u32 g_contrast = 0x100u;
static int g_dimmed, g_redraw;
static u16 mix(u16 a, u16 b, int p, int q) /* a + (b - a) * p / q */
{
int r = (a >> 11) + (((b >> 11) - (a >> 11)) * p) / q, g = ((a >> 5) & 63) + ((((b >> 5) & 63) - ((a >> 5) & 63)) * p) / q;
int bl = (a & 31) + (((b & 31) - (a & 31)) * p) / q;
return (u16)((r << 11) | (g << 5) | bl);
}
static void lut(void)
{
const u16 *p = PAL[g_set.pal & 3u];
u32 c = 128u + (A_LCD.contrast >> 1); /* the game's contrast: 128..255 of the full dot */
g_lut[0] = p[0]; g_lut[2] = mix(p[0], p[1], (int)c, 255); g_lut[1] = mix(p[0], p[1], (int)c, 510);
g_contrast = A_LCD.contrast;
}
static void colours(void)
{
const u16 *p = PAL[g_set.pal & 3u];
BG = p[0]; INK = p[1]; OFF = mix(p[0], p[1], 1, 2);
lut();
#ifdef BL_PWM
{ u32 l = LV_PCT[(g_set.r0 & 15u) % LV_N], d = DIM2_PCT[g_set.dimto % DIM2_N];
hw_bl_set(g_dimmed ? (d < l ? d : l) : l); }
#endif
g_redraw = 1;
}
/* sector buffer (4 KB) and state buffer: the end of the fast core's cache (ab_scratch empties it), so the cache is
* bigger; only used between runs */
static void set_load(void)
{
const volatile u8 *p = XIP_PTR(SETTINGS); AbSet t; u8 *d = (u8 *)&t;
for (u32 i = 0; i < sizeof t; i++) d[i] = p[i];
if (t.magic[0] == 'A' && t.magic[1] == 'B' && t.magic[2] == 'S' && t.magic[3] == '1' && t.pal < 4u && t.dim <= T_N && t.off <= T_N && t.lang < 3u && t.size < 3u) g_set = t;
colours();
}
static void set_store(void)
{
u8 *sec = ab_scratch();
for (u32 i = 0; i < 0x1000u; i++) sec[i] = 0xFF;
const u8 *s = (const u8 *)&g_set; for (u32 i = 0; i < sizeof g_set; i++) sec[i] = s[i];
flash_update4k(SETTINGS, sec);
}
/* ---- EEPROM (the games' saves, 1 KB) ---- */
static u32 g_tone_now;
static void tone(u32 hz)
{
#ifndef AB_TONE_ALL
/* as GB_TONE_RESTART: every new pitch starts the buzzer anew (a new pitch in the running timer stayed silent on the
* device); changes below about 3 % (measuring) are left out, so it does not start anew every 20 ms */
if (hz && g_tone_now) { u32 d = hz > g_tone_now ? hz - g_tone_now : g_tone_now - hz; if (d * 32u < g_tone_now) return; }
#endif
if (hz != g_tone_now) { if (hz && g_tone_now) hw_tone(0); g_tone_now = hz; hw_tone(hz); }
}
static void eep_load(void) { const volatile u8 *p = XIP_PTR(EEP_AT); for (u32 i = 0; i < AVR_EEP; i++) A_EEP[i] = p[i]; }
static void eep_store(void)
{
u8 *sec = ab_scratch();
for (u32 i = 0; i < 0x1000u; i++) sec[i] = i < AVR_EEP ? A_EEP[i] : 0xFFu;
tone(0); flash_update4k(EEP_AT, sec);
A_EEP_DIRTY = 0;
}
/* ---- screen ---- */
static u8 g_snap[2][1024] __attribute__((aligned(4))); /* the last two full pictures */
static u32 g_si, g_nsnap, g_nsnap_shown;
void ab_frame(void)
{
u32 *d = (u32 *)g_snap[g_si ^= 1u]; const u32 *s = (const u32 *)A_GD;
for (int i = 0; i < 256; i++) d[i] = s[i];
g_nsnap++;
}
static u8 g_src[64][128] __attribute__((aligned(4))); /* the Arduboy's rows as shown: 0 off, 1 grey, 2 on */
static u16 g_row[128] __attribute__((aligned(4)));
static int g_dirty_lo = 64, g_dirty_hi = -1; /* changed source rows */
static int oh(void) { return g_set.size == 0 ? 64 : g_set.size == 1 ? 96 : 128; }
static void src_dirty_all(void) { for (int y = 0; y < 64; y++) for (int x = 0; x < 128; x++) g_src[y][x] = 0xFF; }
/* one row of the Arduboy's picture: 0, 1 (grey) or 2 per dot */
static void src_row(int y, const u8 *a, const u8 *b, u8 *o)
{
if (!A_LCD.on) { for (int x = 0; x < 128; x++) o[x] = 0; return; }
if (A_LCD.allon) { for (int x = 0; x < 128; x++) o[x] = 2; return; }
int ry = (A_LCD.flip_y ? y : 63 - y) + A_LCD.start; ry &= 63;
const u8 *pa = a + (ry >> 3) * 128, *pb = b + (ry >> 3) * 128; u32 sh = (u32)ry & 7u, inv = A_LCD.invert ? 1u : 0u;
if (A_LCD.flip_x) for (int x = 0; x < 128; x++) o[x] = (u8)((((pa[x] >> sh) & 1u) ^ inv) + (((pb[x] >> sh) & 1u) ^ inv));
else for (int x = 0; x < 128; x++) o[x] = (u8)((((pa[127 - x] >> sh) & 1u) ^ inv) + (((pb[127 - x] >> sh) & 1u) ^ inv));
}
static void frame_build(void)
{
const u8 *a, *b;
if (g_nsnap != g_nsnap_shown && g_nsnap >= 2u) { a = g_snap[g_si]; b = g_snap[g_si ^ 1u]; g_nsnap_shown = g_nsnap; }
else { a = A_GD; b = A_GD; }
if (A_LCD.contrast != g_contrast) { lut(); g_redraw = 1; }
static u8 t[128] __attribute__((aligned(4)));
for (int y = 0; y < 64; y++) {
src_row(y, a, b, t);
u32 *f = (u32 *)g_src[y], d = 0; const u32 *w = (const u32 *)t;
for (int x = 0; x < 32; x++) { d |= f[x] ^ w[x]; f[x] = w[x]; }
if (d) { if (y < g_dirty_lo) g_dirty_lo = y; if (y > g_dirty_hi) g_dirty_hi = y; }
}
}
/* output row r of the shown height h from the source rows */
static void out_px(int r, int h)
{
if (h == 64) { const u8 *f = g_src[r]; for (int x = 0; x < 128; x++) g_row[x] = g_lut[f[x]]; return; }
if (h == 128) { const u8 *f = g_src[r >> 1]; for (int x = 0; x < 128; x++) g_row[x] = g_lut[f[x]]; return; }
int k = r / 3, m = r % 3; const u8 *p = g_src[2 * k], *q = g_src[2 * k + 1]; /* 2 rows to 3: a, (a + b) / 2, b */
if (m == 0) for (int x = 0; x < 128; x++) g_row[x] = g_lut[p[x]];
else if (m == 2) for (int x = 0; x < 128; x++) g_row[x] = g_lut[q[x]];
else for (int x = 0; x < 128; x++) g_row[x] = g_lut[(p[x] + q[x] + 1u) >> 1];
}
static void push(int all)
{
int h = oh(), oy = (128 - h) / 2;
if (g_redraw) { g_redraw = 0; all = 1; }
if (all && oy) { /* the bars */
for (int x = 0; x < 128; x++) g_row[x] = BG;
hw_px_begin(0, 0, 128, (u32)oy); for (int y = 0; y < oy; y++) hw_px_row(g_row, 128); hw_px_end();
hw_px_begin(0, (u32)(oy + h), 128, 128); for (int y = oy + h; y < 128; y++) hw_px_row(g_row, 128); hw_px_end();
}
int lo = all ? 0 : g_dirty_lo, hi = all ? 63 : g_dirty_hi;
g_dirty_lo = 64; g_dirty_hi = -1;
if (lo > hi) return;
int r0 = h == 64 ? lo : h == 128 ? 2 * lo : (lo >> 1) * 3, r1 = h == 64 ? hi : h == 128 ? 2 * hi + 1 : (hi >> 1) * 3 + 2;
hw_px_begin(0, (u32)(oy + r0), 128, (u32)(oy + r1 + 1));
for (int r = r0; r <= r1; r++) { out_px(r, h); hw_px_row(g_row, 128); }
hw_px_end();
}
/* ---- the settings menu (A+B+C): A next line, B change, C close ---- */
static int g_menu, g_msel, g_mtop;
static void text(int x, int y, const char *s, u16 col, u16 *row, int ry)
{
for (; *s; s++, x += 6) {
int c = (unsigned char)*s; if (c >= 97 && c <= 122) c -= 32; c = (c < 32 || c > 127) ? 0 : c - 32;
if (ry < y || ry >= y + 7) continue;
u8 bits = g_font[c][ry - y];
for (int k = 0; k < 5; k++) if ((bits & (0x10 >> k)) && x + k >= 0 && x + k < 128) row[x + k] = col;
}
}
enum { M_PAL, M_SIZE, M_SND, M_LIGHT, M_DIM, M_DIMTO, M_OFF, M_RESET, M_LANG, M_N };
static int g_items[M_N], g_nitems;
static void menu_items(void)
{
g_nitems = 0;
for (int k = 0; k < M_N; k++) { if (k == M_DIMTO && g_set.dim >= T_N) continue; g_items[g_nitems++] = k; }
if (g_msel >= g_nitems) g_msel = g_nitems - 1;
}
static void pct(char *o, int v) { int n = 0; if (v >= 100) o[n++] = '1'; if (v >= 10) o[n++] = (char)('0' + (v / 10) % 10); o[n++] = (char)('0' + v % 10); o[n++] = '%'; o[n] = 0; }
static int g_reset_ask;
static void menu_line(int it, const char **a, char *b)
{
int e = en(); const char *v = 0; b[0] = 0;
switch (it) {
case M_PAL: *a = e ? "COLOUR" : "FARBE"; v = PAL_NM[e][g_set.pal & 3u]; break;
case M_SIZE: *a = e ? "PICTURE" : "BILD"; v = SIZE_NM[e][g_set.size % 3u]; break;
case M_SND: *a = e ? "SOUND" : "TON"; v = g_set.mute ? (e ? "OFF" : "AUS") : (e ? "ON" : "AN"); break;
case M_LIGHT: *a = e ? "LIGHT" : "LICHT"; pct(b, LV_PCT[(g_set.r0 & 15u) % LV_N]); break;
case M_DIM: *a = e ? "DIM AFTER" : "DIMMEN NACH"; v = T_NM[e][g_set.dim <= T_N ? g_set.dim : T_N]; break;
case M_DIMTO: *a = e ? "DIM TO" : "DIMMEN AUF"; pct(b, DIM2_PCT[g_set.dimto % DIM2_N]); break;
case M_OFF: *a = e ? "SCREEN OFF" : "BILD AUS NACH"; v = T_NM[e][g_set.off <= T_N ? g_set.off : T_N]; break;
case M_RESET: *a = e ? "RESTART GAME" : "SPIEL NEU"; v = g_reset_ask ? (e ? "SURE? B" : "SICHER? B") : ""; break;
default: *a = e ? "LANGUAGE" : "SPRACHE"; v = e ? "ENGLISH" : "DEUTSCH"; break;
}
if (v) { int n = 0; while (v[n] && n < 11) { b[n] = v[n]; n++; } b[n] = 0; }
}
#define ROWS 9
static void menu_draw(void)
{
if (g_msel < g_mtop) g_mtop = g_msel;
if (g_msel >= g_mtop + ROWS) g_mtop = g_msel - ROWS + 1;
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) {
for (int x = 0; x < 128; x++) g_row[x] = BG;
text(4, 3, en() ? "SETTINGS" : "EINSTELLUNGEN", INK, g_row, y);
if (y == 12) for (int x = 0; x < 128; x++) g_row[x] = OFF;
for (int k = 0; k < ROWS && g_mtop + k < g_nitems; k++) {
int i = g_mtop + k, ly = 16 + k * 11; const char *a; char b[12]; menu_line(g_items[i], &a, b);
if (i == g_msel && y >= ly - 2 && y < ly + 9) for (int x = 0; x < 128; x++) g_row[x] = INK;
u16 c = i == g_msel ? BG : INK;
text(4, ly, a, c, g_row, y); int w = 0; while (b[w]) w++; text(124 - w * 6, ly, b, c, g_row, y);
}
text(4, 118, en() ? "A NEXT B SET C OK" : "A ZEILE B SETZEN C OK", OFF, g_row, y);
hw_px_row(g_row, 128);
}
hw_px_end();
}
static int g_set_dirty;
static void ab_fresh(void);
static void menu_close(void)
{
g_menu = 0; g_reset_ask = 0; if (g_set_dirty) { set_store(); g_set_dirty = 0; }
src_dirty_all(); frame_build(); push(1);
}
static void menu_key(u32 k)
{
if (k & BTN_A) { g_msel = (g_msel + 1) % g_nitems; g_reset_ask = 0; }
if (k & BTN_B) {
switch (g_items[g_msel]) {
case M_PAL: g_set.pal = (u8)((g_set.pal + 1u) & 3u); break;
case M_SIZE: g_set.size = (u8)((g_set.size + 1u) % 3u); break;
case M_SND: g_set.mute ^= 1u; break;
case M_LIGHT: g_set.r0 = (u8)(0x80u | (((g_set.r0 & 15u) + 1u) % LV_N)); break;
case M_DIM: g_set.dim = (u8)((g_set.dim + 1u) % (T_N + 1u)); if (g_set.dim < T_N && g_set.off < T_N && g_set.off <= g_set.dim) g_set.off = (u8)(g_set.dim + 1u); break;
case M_DIMTO: g_set.dimto = (u8)((g_set.dimto + 1u) % DIM2_N); break;
case M_OFF: do g_set.off = (u8)((g_set.off + 1u) % (T_N + 1u)); while (g_set.off < T_N && g_set.dim < T_N && g_set.off <= g_set.dim); break;
case M_RESET: if (g_reset_ask) { g_reset_ask = 0; ab_fresh(); menu_close(); return; } g_reset_ask = 1; break;
default: g_set.lang = (u8)(en() ? 1u : 2u); break;
}
if (g_items[g_msel] != M_RESET) g_set_dirty = 1;
colours(); menu_items();
}
if (k & BTN_C) { menu_close(); return; }
menu_draw();
}
static void message(const char *a, const char *b)
{
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) { for (int x = 0; x < 128; x++) g_row[x] = BG; text(4, 50, a, INK, g_row, y); text(4, 62, b, INK, g_row, y); hw_px_row(g_row, 128); }
hw_px_end();
}
/* ---- keys: the Paradise inputs to the Arduboy's buttons (map from the Studio) ---- */
static u32 g_wheel_until[2]; /* wheel up / down held until (ms) */
static u32 ab_keys(u32 b, u32 now)
{
u32 in = 0;
int ac = (b & (BTN_A | BTN_C)) == (BTN_A | BTN_C), bc = (b & (BTN_B | BTN_C)) == (BTN_B | BTN_C), ab = (b & (BTN_A | BTN_B)) == (BTN_A | BTN_B);
u32 used = 0; /* a pair held: its two keys count as the pair only (if the pair has a meaning) */
if (ac && g_cfg.keys[6]) { in |= 1u << 6; used |= BTN_A | BTN_C; }
if (bc && g_cfg.keys[7]) { in |= 1u << 7; used |= BTN_B | BTN_C; }
if (ab && g_cfg.keys[8]) { in |= 1u << 8; used |= BTN_A | BTN_B; }
u32 r = b & ~used;
if (r & BTN_A) in |= 1u; if (r & BTN_B) in |= 2u; if (r & BTN_C) in |= 4u; if (b & BTN_WHEEL) in |= 8u;
if ((s32)(g_wheel_until[0] - now) > 0) in |= 16u;
if ((s32)(g_wheel_until[1] - now) > 0) in |= 32u;
u32 k = 0;
for (int i = 0; i < NIN; i++) if (in & (1u << i)) k |= g_cfg.keys[i];
return k;
}
/* ---- the game ---- */
static void ab_fresh(void) { A_KEYS = 0; ab_reset(); }
/* ---- the whole state on leaving (wheel held), read once at the next start ---- */
#include "../../../emu/src/emu/pstate.h"
#ifdef SESS_FLAG
#define NOSESS ((g_cfg.flags & 0x1000u) != 0u) /* 1.7.3 test7: the Studio's "remember on leaving" off: only the game's own save */
#else
#define NOSESS 0
#endif
#define STATE_N 0x1400u
static int g_running;
static u32 st_tag(void) { return 0x41420001u ^ (u32)STATE_N ^ g_cfg.rom_len ^ (u32)&A_D ^ (u32)ab_run; }
static void state_store(void)
{
if (!g_running) return;
u8 *sec = ab_scratch(), *st = sec + 0x1000u;
for (u32 i = 0; i < STATE_N; i++) st[i] = 0;
if (!ab_state_save(st, STATE_N)) return;
StPart pt[1] = { { st, STATE_N } };
st_store(STATE_AT, STATE_MAX, st_tag(), pt, 1, sec);
}
static int state_load(void)
{
if (NOSESS) { st_drop(STATE_AT); return 0; }
u8 *st = ab_scratch() + 0x1000u;
StPart pt[1] = { { st, STATE_N } };
int ok = st_load(STATE_AT, STATE_MAX, st_tag(), pt, 1) && ab_state_load(st, STATE_N);
st_drop(STATE_AT);
return ok;
}
/* ---- leaving ---- */
static void leave(void)
{
tone(0); hw_tone(0);
if (g_set_dirty) set_store();
REG(0x20000FF8u) = 0;
REG(0x20000FFCu) = 0x4C584D50u; /* "PMXL": back on purpose, the autostart stays off */
if (g_running && !NOSESS) { message(en() ? "SAVING" : "SPEICHERN", ""); state_store(); }
if (A_EEP_DIRTY) eep_store();
#ifdef PARA_BACK
#ifdef GPLAY
para_points((uint8_t *)ab_scratch()); /* play time to Tamapoints */
#endif
para_back_fix(ab_scratch());
#endif
hw_bl_pwm_off();
for (u32 t = 0; hw_buttons() && t < 20000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed();
XIP_BASE_REG = 0x60011000u; XIP_CTRL_REG = 3u;
hw_back_to_paradise();
}
__attribute__((used)) volatile u32 g_abst[4]; /* ms run, pictures pushed, ms dropped, last slice in ms (for the tests) */
extern u32 __bss_start, __bss_end;
void Reset_Handler(void)
{
__asm__ volatile("cpsid i");
u32 cnt = REG(0x45000304u), para = para_clock(cnt, 0, 0x1F000u, 0, 0);
if (!para) para = para_mailbox(cnt);
#ifdef PARA_BACK
para_leave_mark(cnt, para);
#endif
__asm__ volatile("" ::: "memory");
for (u32 *p = &__bss_start; p < &__bss_end; p++) *p = 0;
{ extern u32 __data_start, __data_end, __data_load;
const u32 *src = &__data_load; for (u32 *p = &__data_start; p < &__data_end; p++) *p = *src++; }
(void)para;
hw_init();
hw_tone(0);
XIP_BASE_REG = 0x60000000u | g_cfg.rom_off; /* the game in the cached window from 0x10000000 */
XIP_CTRL_REG = 3u;
REG(GPIO2 + 0x04) &= ~3u; g_enc_last = REG(GPIO2) & 3u;
set_load();
ab_load(ROMWIN, (g_cfg.rom_len + 1u) / 2u);
eep_load();
ab_reset();
state_load();
A_EEP_DIRTY = 0;
g_running = 1;
src_dirty_all();
frame_build(); push(1);
SYST_RVR = CORE_HZ / 1000u - 1u; SYST_CVR = 0; SYST_CSR = 7;
__asm__ volatile("cpsie i");
u32 last_in = g_ms, wheel_ms = 0, eep_ms = 0, done_ms = g_ms, last_push = g_ms, mk0 = 0, tone_ms = g_ms, tone_cyc = A_CYC;
int bl = 1, lock = 1, menu_lock = 0;
for (;;) {
hw_wdt_feed();
u32 now = g_ms;
u32 b = hw_buttons();
if (lock) { if (b) b = 0; else lock = 0; }
/* wheel steps: one step = 4 phases; each step holds up or down for 150 ms */
{ s32 a = g_enc_acc;
if (a >= 4 || a <= -4) {
__asm__ volatile("cpsid i"); g_enc_acc -= a >= 4 ? 4 : -4; __asm__ volatile("cpsie i");
int up = (a > 0) ^ ((g_cfg.flags & 2u) != 0);
u32 *u = &g_wheel_until[up ? 0 : 1]; *u = ((s32)(*u - now) > 0 ? *u : now) + 150u;
last_in = now;
if (g_menu) { g_msel = up ? (g_msel + g_nitems - 1) % g_nitems : (g_msel + 1) % g_nitems; menu_draw(); }
} }
if (b) {
last_in = now;
if (!bl || g_dimmed) { /* the key only wakes */
bl = 1; hw_backlight(1); if (g_dimmed) { g_dimmed = 0; colours(); }
if (g_menu) menu_draw(); else push(1);
while (hw_buttons()) hw_wdt_feed();
done_ms = g_ms;
continue;
}
}
/* wheel held 2 s: save and back */
if (b & BTN_WHEEL) { if (!wheel_ms) wheel_ms = now ? now : 1; else if (EXIT_NOW(now - wheel_ms, 2000u)) leave(); } else wheel_ms = 0;
/* A+B+C: settings */
if ((b & (BTN_A | BTN_B | BTN_C)) == (BTN_A | BTN_B | BTN_C) && !g_menu && !menu_lock) {
tone(0); A_KEYS = 0; g_menu = 1; menu_lock = 1; g_msel = 0; g_mtop = 0; menu_items(); menu_draw(); mk0 = BTN_A | BTN_B | BTN_C;
}
if (!(b & (BTN_A | BTN_B | BTN_C))) menu_lock = 0;
if (g_menu) {
u32 k = b & (BTN_A | BTN_B | BTN_C), nk = k & ~mk0; mk0 = k; if (nk) menu_key(nk);
done_ms = g_ms;
__asm__ volatile("wfi");
continue;
}
if (!bl) { tone(0); done_ms = g_ms; __asm__ volatile("wfi"); continue; } /* screen off: the game waits (battery) */
A_KEYS = ab_keys(b, now);
/* the Arduboy runs 16000 cycles per millisecond */
if ((s32)(now - done_ms) > 0) {
if ((s32)(now - done_ms) > 50) { g_abst[2] += now - done_ms - 50u; done_ms = now - 50u; } /* too far behind: drop the time */
u32 t0 = g_ms;
ab_run(16000u);
done_ms++; g_abst[0]++; g_abst[3] = g_ms - t0;
if (now - tone_ms >= 20u) {
u32 hz = ab_tone(A_CYC - tone_cyc); tone_ms = now; tone_cyc = A_CYC;
tone(!g_set.mute && hz >= 40u && hz <= 12000u ? hz : 0u);
}
if (now - last_push >= 33u) { last_push = now; frame_build(); push(0); g_abst[1]++; }
}
if (A_EEP_DIRTY && !eep_ms) eep_ms = now ? now : 1;
if (eep_ms && now - eep_ms > 3000u && now - last_in > 1000u) { eep_ms = 0; eep_store(); }
if (bl && !g_dimmed && g_set.dim < T_N && now - last_in > T_MS[g_set.dim]) { g_dimmed = 1; colours(); push(1); }
if (bl && g_set.off < T_N && now - last_in > T_MS[g_set.off]) { bl = 0; tone(0); hw_backlight(0); if (A_EEP_DIRTY) { eep_ms = 0; eep_store(); } }
if ((s32)(g_ms - done_ms) <= 0) __asm__ volatile("wfi");
}
}
__attribute__((naked)) static void Default_Handler(void) { __asm__ volatile("1: b 1b\n"); }
__attribute__((naked)) static void Irq_Off(void) { __asm__ volatile("cpsid i\n bx lr\n"); }
__attribute__((section(".vectors"), used))
const void *const g_vectors[16 + 64] = { (void *)0x18020000u, (void *)Reset_Handler,
[2 ... 10] = (void *)Default_Handler, [11] = (void *)Irq_Off, [12 ... 13] = (void *)Default_Handler, [14] = (void *)Irq_Off,
[15] = (void *)SysTick_Handler, [16 ... 79] = (void *)Irq_Off };
/* ArduboyEmu: the Arduboy on the Tamagotchi Paradise, a further program of the Paramix menu. Bring your own games
* (.hex). Core: own ATmega32U4 emulation (../core/avr.c).
* Screen: the Arduboy's 128 x 64 at 1:1, 3:2 or 2:1 height (setting PICTURE); greys that games make by switching two
* pictures come out as grey. Keys: set in the Studio (tab Arduboy). A+B+C together: settings; wheel held 2 s: save and
* back to the Paradise. Sound: the speaker's tone on the Paradise's buzzer. Save: the EEPROM (1 KB) goes to the flash a
* few seconds after the game wrote it, and on leaving; on leaving the whole state too, the next start continues there.
* Author: mameise */
#include "../../../emu/src/emu/hw.h"
#include "../../../emu/src/emu/exitkey.h"
#include "../../../emu/src/emu/flash.h"
#define PARA_ATTR
#include "../../../emu/src/emu/paraclock.h"
#ifdef PARA_BACK
#include "../../../emu/src/emu/paraback.h"
#ifdef GPLAY
#define GP_POINTS
#include "../../../emu/src/emu/gplay.h"
#endif
#endif
#include "../core/avr.h"
#include "font.h"
/* ---- settings block at 0x140, filled in by the Studio ----
* keys[i]: Arduboy buttons (bit 0 UP, 1 DOWN, 2 LEFT, 3 RIGHT, 4 A, 5 B) for the Paradise input i: 0 A, 1 B, 2 C,
* 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B. flags: bit 0 English, bit 1 wheel the other way round.
* save_off: 4 KB settings of the device, 4 KB EEPROM (1 KB used), then the state (up to 8 KB). */
#define NIN 9
typedef struct { u32 magic, version, rom_off, rom_len, save_off, flags; char name[16]; u8 keys[12]; } AbCfg;
#define AB_MAGIC 0x50584241u /* "ABXP" */
__attribute__((section(".pmxcfg"), used))
volatile const AbCfg g_cfg = { AB_MAGIC, 1, 0, 0, 0, 0, {0}, { AB_LEFT, AB_B, AB_RIGHT, AB_A, AB_UP, AB_DOWN, 0, 0, 0 } };
#define SETTINGS (g_cfg.save_off)
#define EEP_AT (g_cfg.save_off + 0x1000u)
#define STATE_AT (g_cfg.save_off + 0x2000u)
#define STATE_MAX 0x2000u
#define XIP_BASE_REG REG(0x4002F004u)
#define XIP_CTRL_REG REG(0x4002F000u)
#define ROMWIN ((const u16 *)0x10000000u)
/* ---- time: SysTick 1 ms; the wheel's encoder is read here too ---- */
static volatile u32 g_ms;
static volatile s32 g_enc_acc; static u32 g_enc_last;
static const signed char QD[16] = { 0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0 };
#define GPIO2 0x4001A000u
#define SYST_CSR REG(0xE000E010u)
#define SYST_RVR REG(0xE000E014u)
#define SYST_CVR REG(0xE000E018u)
#define CORE_HZ 96000000u
__attribute__((used)) void systick_c(void)
{
g_ms++;
u32 n = REG(GPIO2) & 3u;
if (n != g_enc_last) { g_enc_acc += QD[(g_enc_last << 2) | n]; g_enc_last = n; }
}
__attribute__((naked)) void SysTick_Handler(void) { __asm__ volatile("b systick_c\n"); }
void abort(void) { for (;;) hw_wdt_feed(); }
/* ---- settings on the device ---- */
typedef struct { u8 magic[4]; u8 pal, dim, lang, dimto, off, r0, size, mute; } AbSet; /* mute: 0 = sound on */
#ifndef AB_SIZE0
#define AB_SIZE0 0 /* 1.7.3 test10: picture size SMALL by default (1:1, not stretched); 1 = MEDIUM as before */
#endif
static AbSet g_set = { {'A','B','S','1'}, 0, 7, 0, 6, 3, 0x80, AB_SIZE0, 0 };
/* background, dot: white, amber, cyan (as the OLED), paper (black on white) */
static const u16 PAL[4][2] = { { 0x0000u, 0xFFFFu }, { 0x0000u, 0xFDA0u }, { 0x0000u, 0x5FFFu }, { 0xEF5Du, 0x10A2u } };
static const char *const PAL_NM[2][4] = { { "WEISS", "GELB", "BLAU", "PAPIER" }, { "WHITE", "AMBER", "CYAN", "PAPER" } };
static const char *const SIZE_NM[2][3] = { { "KLEIN", "MITTEL", "GROSS" }, { "SMALL", "MEDIUM", "LARGE" } };
#define T_N 7
static const u32 T_MS[T_N] = { 10000u, 20000u, 30000u, 60000u, 120000u, 300000u, 600000u };
static const char *const T_NM[2][T_N + 1] = { { "10 S", "20 S", "30 S", "1 MIN", "2 MIN", "5 MIN", "10 MIN", "NIE" }, { "10 S", "20 S", "30 S", "1 MIN", "2 MIN", "5 MIN", "10 MIN", "NEVER" } };
#define LV_N 11
#define DIM2_N 10
static const u8 LV_PCT[LV_N] = { 100u, 5u, 10u, 20u, 30u, 40u, 50u, 60u, 70u, 80u, 90u };
static const u8 DIM2_PCT[DIM2_N] = { 1u, 2u, 3u, 5u, 10u, 15u, 20u, 30u, 40u, 50u };
static int en(void) { return g_set.lang ? g_set.lang == 2u : (int)(g_cfg.flags & 1u); }
static u16 BG, INK, OFF;
static u16 g_lut[3]; /* dot off, grey, on (with the game's contrast) */
static u32 g_contrast = 0x100u;
static int g_dimmed, g_redraw;
static u16 mix(u16 a, u16 b, int p, int q) /* a + (b - a) * p / q */
{
int r = (a >> 11) + (((b >> 11) - (a >> 11)) * p) / q, g = ((a >> 5) & 63) + ((((b >> 5) & 63) - ((a >> 5) & 63)) * p) / q;
int bl = (a & 31) + (((b & 31) - (a & 31)) * p) / q;
return (u16)((r << 11) | (g << 5) | bl);
}
static void lut(void)
{
const u16 *p = PAL[g_set.pal & 3u];
u32 c = 128u + (A_LCD.contrast >> 1); /* the game's contrast: 128..255 of the full dot */
g_lut[0] = p[0]; g_lut[2] = mix(p[0], p[1], (int)c, 255); g_lut[1] = mix(p[0], p[1], (int)c, 510);
g_contrast = A_LCD.contrast;
}
static void colours(void)
{
const u16 *p = PAL[g_set.pal & 3u];
BG = p[0]; INK = p[1]; OFF = mix(p[0], p[1], 1, 2);
lut();
#ifdef BL_PWM
{ u32 l = LV_PCT[(g_set.r0 & 15u) % LV_N], d = DIM2_PCT[g_set.dimto % DIM2_N];
hw_bl_set(g_dimmed ? (d < l ? d : l) : l); }
#endif
g_redraw = 1;
}
/* sector buffer (4 KB) and state buffer: the end of the fast core's cache (ab_scratch empties it), so the cache is
* bigger; only used between runs */
static void set_load(void)
{
const volatile u8 *p = XIP_PTR(SETTINGS); AbSet t; u8 *d = (u8 *)&t;
for (u32 i = 0; i < sizeof t; i++) d[i] = p[i];
if (t.magic[0] == 'A' && t.magic[1] == 'B' && t.magic[2] == 'S' && t.magic[3] == '1' && t.pal < 4u && t.dim <= T_N && t.off <= T_N && t.lang < 3u && t.size < 3u) g_set = t;
colours();
}
static void set_store(void)
{
u8 *sec = ab_scratch();
for (u32 i = 0; i < 0x1000u; i++) sec[i] = 0xFF;
const u8 *s = (const u8 *)&g_set; for (u32 i = 0; i < sizeof g_set; i++) sec[i] = s[i];
flash_update4k(SETTINGS, sec);
}
/* ---- EEPROM (the games' saves, 1 KB) ---- */
static u32 g_tone_now;
static void tone(u32 hz)
{
#ifndef AB_TONE_ALL
/* as GB_TONE_RESTART: every new pitch starts the buzzer anew (a new pitch in the running timer stayed silent on the
* device); changes below about 3 % (measuring) are left out, so it does not start anew every 20 ms */
if (hz && g_tone_now) { u32 d = hz > g_tone_now ? hz - g_tone_now : g_tone_now - hz; if (d * 32u < g_tone_now) return; }
#endif
if (hz != g_tone_now) { if (hz && g_tone_now) hw_tone(0); g_tone_now = hz; hw_tone(hz); }
}
static void eep_load(void) { const volatile u8 *p = XIP_PTR(EEP_AT); for (u32 i = 0; i < AVR_EEP; i++) A_EEP[i] = p[i]; }
static void eep_store(void)
{
u8 *sec = ab_scratch();
for (u32 i = 0; i < 0x1000u; i++) sec[i] = i < AVR_EEP ? A_EEP[i] : 0xFFu;
tone(0); flash_update4k(EEP_AT, sec);
A_EEP_DIRTY = 0;
}
/* ---- screen ---- */
static u8 g_snap[2][1024] __attribute__((aligned(4))); /* the last two full pictures */
static u32 g_si, g_nsnap, g_nsnap_shown;
void ab_frame(void)
{
u32 *d = (u32 *)g_snap[g_si ^= 1u]; const u32 *s = (const u32 *)A_GD;
for (int i = 0; i < 256; i++) d[i] = s[i];
g_nsnap++;
}
static u8 g_src[64][128] __attribute__((aligned(4))); /* the Arduboy's rows as shown: 0 off, 1 grey, 2 on */
static u16 g_row[128] __attribute__((aligned(4)));
static int g_dirty_lo = 64, g_dirty_hi = -1; /* changed source rows */
static int oh(void) { return g_set.size == 0 ? 64 : g_set.size == 1 ? 96 : 128; }
static void src_dirty_all(void) { for (int y = 0; y < 64; y++) for (int x = 0; x < 128; x++) g_src[y][x] = 0xFF; }
/* one row of the Arduboy's picture: 0, 1 (grey) or 2 per dot */
static void src_row(int y, const u8 *a, const u8 *b, u8 *o)
{
if (!A_LCD.on) { for (int x = 0; x < 128; x++) o[x] = 0; return; }
if (A_LCD.allon) { for (int x = 0; x < 128; x++) o[x] = 2; return; }
int ry = (A_LCD.flip_y ? y : 63 - y) + A_LCD.start; ry &= 63;
const u8 *pa = a + (ry >> 3) * 128, *pb = b + (ry >> 3) * 128; u32 sh = (u32)ry & 7u, inv = A_LCD.invert ? 1u : 0u;
if (A_LCD.flip_x) for (int x = 0; x < 128; x++) o[x] = (u8)((((pa[x] >> sh) & 1u) ^ inv) + (((pb[x] >> sh) & 1u) ^ inv));
else for (int x = 0; x < 128; x++) o[x] = (u8)((((pa[127 - x] >> sh) & 1u) ^ inv) + (((pb[127 - x] >> sh) & 1u) ^ inv));
}
static void frame_build(void)
{
const u8 *a, *b;
if (g_nsnap != g_nsnap_shown && g_nsnap >= 2u) { a = g_snap[g_si]; b = g_snap[g_si ^ 1u]; g_nsnap_shown = g_nsnap; }
else { a = A_GD; b = A_GD; }
if (A_LCD.contrast != g_contrast) { lut(); g_redraw = 1; }
static u8 t[128] __attribute__((aligned(4)));
for (int y = 0; y < 64; y++) {
src_row(y, a, b, t);
u32 *f = (u32 *)g_src[y], d = 0; const u32 *w = (const u32 *)t;
for (int x = 0; x < 32; x++) { d |= f[x] ^ w[x]; f[x] = w[x]; }
if (d) { if (y < g_dirty_lo) g_dirty_lo = y; if (y > g_dirty_hi) g_dirty_hi = y; }
}
}
/* output row r of the shown height h from the source rows */
static void out_px(int r, int h)
{
if (h == 64) { const u8 *f = g_src[r]; for (int x = 0; x < 128; x++) g_row[x] = g_lut[f[x]]; return; }
if (h == 128) { const u8 *f = g_src[r >> 1]; for (int x = 0; x < 128; x++) g_row[x] = g_lut[f[x]]; return; }
int k = r / 3, m = r % 3; const u8 *p = g_src[2 * k], *q = g_src[2 * k + 1]; /* 2 rows to 3: a, (a + b) / 2, b */
if (m == 0) for (int x = 0; x < 128; x++) g_row[x] = g_lut[p[x]];
else if (m == 2) for (int x = 0; x < 128; x++) g_row[x] = g_lut[q[x]];
else for (int x = 0; x < 128; x++) g_row[x] = g_lut[(p[x] + q[x] + 1u) >> 1];
}
static void push(int all)
{
int h = oh(), oy = (128 - h) / 2;
if (g_redraw) { g_redraw = 0; all = 1; }
if (all && oy) { /* the bars */
for (int x = 0; x < 128; x++) g_row[x] = BG;
hw_px_begin(0, 0, 128, (u32)oy); for (int y = 0; y < oy; y++) hw_px_row(g_row, 128); hw_px_end();
hw_px_begin(0, (u32)(oy + h), 128, 128); for (int y = oy + h; y < 128; y++) hw_px_row(g_row, 128); hw_px_end();
}
int lo = all ? 0 : g_dirty_lo, hi = all ? 63 : g_dirty_hi;
g_dirty_lo = 64; g_dirty_hi = -1;
if (lo > hi) return;
int r0 = h == 64 ? lo : h == 128 ? 2 * lo : (lo >> 1) * 3, r1 = h == 64 ? hi : h == 128 ? 2 * hi + 1 : (hi >> 1) * 3 + 2;
hw_px_begin(0, (u32)(oy + r0), 128, (u32)(oy + r1 + 1));
for (int r = r0; r <= r1; r++) { out_px(r, h); hw_px_row(g_row, 128); }
hw_px_end();
}
/* ---- the settings menu (A+B+C): A next line, B change, C close ---- */
static int g_menu, g_msel, g_mtop;
static void text(int x, int y, const char *s, u16 col, u16 *row, int ry)
{
for (; *s; s++, x += 6) {
int c = (unsigned char)*s; if (c >= 97 && c <= 122) c -= 32; c = (c < 32 || c > 127) ? 0 : c - 32;
if (ry < y || ry >= y + 7) continue;
u8 bits = g_font[c][ry - y];
for (int k = 0; k < 5; k++) if ((bits & (0x10 >> k)) && x + k >= 0 && x + k < 128) row[x + k] = col;
}
}
enum { M_PAL, M_SIZE, M_SND, M_LIGHT, M_DIM, M_DIMTO, M_OFF, M_RESET, M_LANG, M_N };
static int g_items[M_N], g_nitems;
static void menu_items(void)
{
g_nitems = 0;
for (int k = 0; k < M_N; k++) { if (k == M_DIMTO && g_set.dim >= T_N) continue; g_items[g_nitems++] = k; }
if (g_msel >= g_nitems) g_msel = g_nitems - 1;
}
static void pct(char *o, int v) { int n = 0; if (v >= 100) o[n++] = '1'; if (v >= 10) o[n++] = (char)('0' + (v / 10) % 10); o[n++] = (char)('0' + v % 10); o[n++] = '%'; o[n] = 0; }
static int g_reset_ask;
static void menu_line(int it, const char **a, char *b)
{
int e = en(); const char *v = 0; b[0] = 0;
switch (it) {
case M_PAL: *a = e ? "COLOUR" : "FARBE"; v = PAL_NM[e][g_set.pal & 3u]; break;
case M_SIZE: *a = e ? "PICTURE" : "BILD"; v = SIZE_NM[e][g_set.size % 3u]; break;
case M_SND: *a = e ? "SOUND" : "TON"; v = g_set.mute ? (e ? "OFF" : "AUS") : (e ? "ON" : "AN"); break;
case M_LIGHT: *a = e ? "LIGHT" : "LICHT"; pct(b, LV_PCT[(g_set.r0 & 15u) % LV_N]); break;
case M_DIM: *a = e ? "DIM AFTER" : "DIMMEN NACH"; v = T_NM[e][g_set.dim <= T_N ? g_set.dim : T_N]; break;
case M_DIMTO: *a = e ? "DIM TO" : "DIMMEN AUF"; pct(b, DIM2_PCT[g_set.dimto % DIM2_N]); break;
case M_OFF: *a = e ? "SCREEN OFF" : "BILD AUS NACH"; v = T_NM[e][g_set.off <= T_N ? g_set.off : T_N]; break;
case M_RESET: *a = e ? "RESTART GAME" : "SPIEL NEU"; v = g_reset_ask ? (e ? "SURE? B" : "SICHER? B") : ""; break;
default: *a = e ? "LANGUAGE" : "SPRACHE"; v = e ? "ENGLISH" : "DEUTSCH"; break;
}
if (v) { int n = 0; while (v[n] && n < 11) { b[n] = v[n]; n++; } b[n] = 0; }
}
#define ROWS 9
static void menu_draw(void)
{
if (g_msel < g_mtop) g_mtop = g_msel;
if (g_msel >= g_mtop + ROWS) g_mtop = g_msel - ROWS + 1;
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) {
for (int x = 0; x < 128; x++) g_row[x] = BG;
text(4, 3, en() ? "SETTINGS" : "EINSTELLUNGEN", INK, g_row, y);
if (y == 12) for (int x = 0; x < 128; x++) g_row[x] = OFF;
for (int k = 0; k < ROWS && g_mtop + k < g_nitems; k++) {
int i = g_mtop + k, ly = 16 + k * 11; const char *a; char b[12]; menu_line(g_items[i], &a, b);
if (i == g_msel && y >= ly - 2 && y < ly + 9) for (int x = 0; x < 128; x++) g_row[x] = INK;
u16 c = i == g_msel ? BG : INK;
text(4, ly, a, c, g_row, y); int w = 0; while (b[w]) w++; text(124 - w * 6, ly, b, c, g_row, y);
}
text(4, 118, en() ? "A NEXT B SET C OK" : "A ZEILE B SETZEN C OK", OFF, g_row, y);
hw_px_row(g_row, 128);
}
hw_px_end();
}
static int g_set_dirty;
static void ab_fresh(void);
static void menu_close(void)
{
g_menu = 0; g_reset_ask = 0; if (g_set_dirty) { set_store(); g_set_dirty = 0; }
src_dirty_all(); frame_build(); push(1);
}
static void menu_key(u32 k)
{
if (k & BTN_A) { g_msel = (g_msel + 1) % g_nitems; g_reset_ask = 0; }
if (k & BTN_B) {
switch (g_items[g_msel]) {
case M_PAL: g_set.pal = (u8)((g_set.pal + 1u) & 3u); break;
case M_SIZE: g_set.size = (u8)((g_set.size + 1u) % 3u); break;
case M_SND: g_set.mute ^= 1u; break;
case M_LIGHT: g_set.r0 = (u8)(0x80u | (((g_set.r0 & 15u) + 1u) % LV_N)); break;
case M_DIM: g_set.dim = (u8)((g_set.dim + 1u) % (T_N + 1u)); if (g_set.dim < T_N && g_set.off < T_N && g_set.off <= g_set.dim) g_set.off = (u8)(g_set.dim + 1u); break;
case M_DIMTO: g_set.dimto = (u8)((g_set.dimto + 1u) % DIM2_N); break;
case M_OFF: do g_set.off = (u8)((g_set.off + 1u) % (T_N + 1u)); while (g_set.off < T_N && g_set.dim < T_N && g_set.off <= g_set.dim); break;
case M_RESET: if (g_reset_ask) { g_reset_ask = 0; ab_fresh(); menu_close(); return; } g_reset_ask = 1; break;
default: g_set.lang = (u8)(en() ? 1u : 2u); break;
}
if (g_items[g_msel] != M_RESET) g_set_dirty = 1;
colours(); menu_items();
}
if (k & BTN_C) { menu_close(); return; }
menu_draw();
}
static void message(const char *a, const char *b)
{
hw_px_begin(0, 0, 128, 128);
for (int y = 0; y < 128; y++) { for (int x = 0; x < 128; x++) g_row[x] = BG; text(4, 50, a, INK, g_row, y); text(4, 62, b, INK, g_row, y); hw_px_row(g_row, 128); }
hw_px_end();
}
/* ---- keys: the Paradise inputs to the Arduboy's buttons (map from the Studio) ---- */
static u32 g_wheel_until[2]; /* wheel up / down held until (ms) */
static u32 ab_keys(u32 b, u32 now)
{
u32 in = 0;
int ac = (b & (BTN_A | BTN_C)) == (BTN_A | BTN_C), bc = (b & (BTN_B | BTN_C)) == (BTN_B | BTN_C), ab = (b & (BTN_A | BTN_B)) == (BTN_A | BTN_B);
u32 used = 0; /* a pair held: its two keys count as the pair only (if the pair has a meaning) */
if (ac && g_cfg.keys[6]) { in |= 1u << 6; used |= BTN_A | BTN_C; }
if (bc && g_cfg.keys[7]) { in |= 1u << 7; used |= BTN_B | BTN_C; }
if (ab && g_cfg.keys[8]) { in |= 1u << 8; used |= BTN_A | BTN_B; }
u32 r = b & ~used;
if (r & BTN_A) in |= 1u; if (r & BTN_B) in |= 2u; if (r & BTN_C) in |= 4u; if (b & BTN_WHEEL) in |= 8u;
if ((s32)(g_wheel_until[0] - now) > 0) in |= 16u;
if ((s32)(g_wheel_until[1] - now) > 0) in |= 32u;
u32 k = 0;
for (int i = 0; i < NIN; i++) if (in & (1u << i)) k |= g_cfg.keys[i];
return k;
}
/* ---- the game ---- */
static void ab_fresh(void) { A_KEYS = 0; ab_reset(); }
/* ---- the whole state on leaving (wheel held), read once at the next start ---- */
#include "../../../emu/src/emu/pstate.h"
#ifdef SESS_FLAG
#define NOSESS ((g_cfg.flags & 0x1000u) != 0u) /* 1.7.3 test7: the Studio's "remember on leaving" off: only the game's own save */
#else
#define NOSESS 0
#endif
#define STATE_N 0x1400u
static int g_running;
static u32 st_tag(void) { return 0x41420001u ^ (u32)STATE_N ^ g_cfg.rom_len ^ (u32)&A_D ^ (u32)ab_run; }
static void state_store(void)
{
if (!g_running) return;
u8 *sec = ab_scratch(), *st = sec + 0x1000u;
for (u32 i = 0; i < STATE_N; i++) st[i] = 0;
if (!ab_state_save(st, STATE_N)) return;
StPart pt[1] = { { st, STATE_N } };
st_store(STATE_AT, STATE_MAX, st_tag(), pt, 1, sec);
}
static int state_load(void)
{
if (NOSESS) { st_drop(STATE_AT); return 0; }
u8 *st = ab_scratch() + 0x1000u;
StPart pt[1] = { { st, STATE_N } };
int ok = st_load(STATE_AT, STATE_MAX, st_tag(), pt, 1) && ab_state_load(st, STATE_N);
st_drop(STATE_AT);
return ok;
}
/* ---- leaving ---- */
static void leave(void)
{
tone(0); hw_tone(0);
if (g_set_dirty) set_store();
REG(0x20000FF8u) = 0;
REG(0x20000FFCu) = 0x4C584D50u; /* "PMXL": back on purpose, the autostart stays off */
if (g_running && !NOSESS) { message(en() ? "SAVING" : "SPEICHERN", ""); state_store(); }
if (A_EEP_DIRTY) eep_store();
#ifdef PARA_BACK
#ifdef GPLAY
para_points((uint8_t *)ab_scratch()); /* play time to Tamapoints */
#endif
para_back_fix(ab_scratch());
#endif
hw_bl_pwm_off();
for (u32 t = 0; hw_buttons() && t < 20000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed();
XIP_BASE_REG = 0x60011000u; XIP_CTRL_REG = 3u;
hw_back_to_paradise();
}
__attribute__((used)) volatile u32 g_abst[4]; /* ms run, pictures pushed, ms dropped, last slice in ms (for the tests) */
extern u32 __bss_start, __bss_end;
void Reset_Handler(void)
{
__asm__ volatile("cpsid i");
u32 cnt = REG(0x45000304u), para = para_clock(cnt, 0, 0x1F000u, 0, 0);
if (!para) para = para_mailbox(cnt);
#ifdef PARA_BACK
para_leave_mark(cnt, para);
#endif
__asm__ volatile("" ::: "memory");
for (u32 *p = &__bss_start; p < &__bss_end; p++) *p = 0;
{ extern u32 __data_start, __data_end, __data_load;
const u32 *src = &__data_load; for (u32 *p = &__data_start; p < &__data_end; p++) *p = *src++; }
(void)para;
hw_init();
hw_tone(0);
XIP_BASE_REG = 0x60000000u | g_cfg.rom_off; /* the game in the cached window from 0x10000000 */
XIP_CTRL_REG = 3u;
REG(GPIO2 + 0x04) &= ~3u; g_enc_last = REG(GPIO2) & 3u;
set_load();
ab_load(ROMWIN, (g_cfg.rom_len + 1u) / 2u);
eep_load();
ab_reset();
state_load();
A_EEP_DIRTY = 0;
g_running = 1;
src_dirty_all();
frame_build(); push(1);
SYST_RVR = CORE_HZ / 1000u - 1u; SYST_CVR = 0; SYST_CSR = 7;
__asm__ volatile("cpsie i");
u32 last_in = g_ms, wheel_ms = 0, eep_ms = 0, done_ms = g_ms, last_push = g_ms, mk0 = 0, tone_ms = g_ms, tone_cyc = A_CYC;
int bl = 1, lock = 1, menu_lock = 0;
for (;;) {
hw_wdt_feed();
u32 now = g_ms;
u32 b = hw_buttons();
if (lock) { if (b) b = 0; else lock = 0; }
/* wheel steps: one step = 4 phases; each step holds up or down for 150 ms */
{ s32 a = g_enc_acc;
if (a >= 4 || a <= -4) {
__asm__ volatile("cpsid i"); g_enc_acc -= a >= 4 ? 4 : -4; __asm__ volatile("cpsie i");
int up = (a > 0) ^ ((g_cfg.flags & 2u) != 0);
u32 *u = &g_wheel_until[up ? 0 : 1]; *u = ((s32)(*u - now) > 0 ? *u : now) + 150u;
last_in = now;
if (g_menu) { g_msel = up ? (g_msel + g_nitems - 1) % g_nitems : (g_msel + 1) % g_nitems; menu_draw(); }
} }
if (b) {
last_in = now;
if (!bl || g_dimmed) { /* the key only wakes */
bl = 1; hw_backlight(1); if (g_dimmed) { g_dimmed = 0; colours(); }
if (g_menu) menu_draw(); else push(1);
while (hw_buttons()) hw_wdt_feed();
done_ms = g_ms;
continue;
}
}
/* wheel held 2 s: save and back */
if (b & BTN_WHEEL) { if (!wheel_ms) wheel_ms = now ? now : 1; else if (EXIT_NOW(now - wheel_ms, 2000u)) leave(); } else wheel_ms = 0;
/* A+B+C: settings */
if ((b & (BTN_A | BTN_B | BTN_C)) == (BTN_A | BTN_B | BTN_C) && !g_menu && !menu_lock) {
tone(0); A_KEYS = 0; g_menu = 1; menu_lock = 1; g_msel = 0; g_mtop = 0; menu_items(); menu_draw(); mk0 = BTN_A | BTN_B | BTN_C;
}
if (!(b & (BTN_A | BTN_B | BTN_C))) menu_lock = 0;
if (g_menu) {
u32 k = b & (BTN_A | BTN_B | BTN_C), nk = k & ~mk0; mk0 = k; if (nk) menu_key(nk);
done_ms = g_ms;
__asm__ volatile("wfi");
continue;
}
if (!bl) { tone(0); done_ms = g_ms; __asm__ volatile("wfi"); continue; } /* screen off: the game waits (battery) */
A_KEYS = ab_keys(b, now);
/* the Arduboy runs 16000 cycles per millisecond */
if ((s32)(now - done_ms) > 0) {
if ((s32)(now - done_ms) > 50) { g_abst[2] += now - done_ms - 50u; done_ms = now - 50u; } /* too far behind: drop the time */
u32 t0 = g_ms;
ab_run(16000u);
done_ms++; g_abst[0]++; g_abst[3] = g_ms - t0;
if (now - tone_ms >= 20u) {
u32 hz = ab_tone(A_CYC - tone_cyc); tone_ms = now; tone_cyc = A_CYC;
tone(!g_set.mute && hz >= 40u && hz <= 12000u ? hz : 0u);
}
if (now - last_push >= 33u) { last_push = now; frame_build(); push(0); g_abst[1]++; }
}
if (A_EEP_DIRTY && !eep_ms) eep_ms = now ? now : 1;
if (eep_ms && now - eep_ms > 3000u && now - last_in > 1000u) { eep_ms = 0; eep_store(); }
if (bl && !g_dimmed && g_set.dim < T_N && now - last_in > T_MS[g_set.dim]) { g_dimmed = 1; colours(); push(1); }
if (bl && g_set.off < T_N && now - last_in > T_MS[g_set.off]) { bl = 0; tone(0); hw_backlight(0); if (A_EEP_DIRTY) { eep_ms = 0; eep_store(); } }
if ((s32)(g_ms - done_ms) <= 0) __asm__ volatile("wfi");
}
}
__attribute__((naked)) static void Default_Handler(void) { __asm__ volatile("1: b 1b\n"); }
__attribute__((naked)) static void Irq_Off(void) { __asm__ volatile("cpsid i\n bx lr\n"); }
__attribute__((section(".vectors"), used))
const void *const g_vectors[16 + 64] = { (void *)0x18020000u, (void *)Reset_Handler,
[2 ... 10] = (void *)Default_Handler, [11] = (void *)Irq_Off, [12 ... 13] = (void *)Default_Handler, [14] = (void *)Irq_Off,
[15] = (void *)SysTick_Handler, [16 ... 79] = (void *)Irq_Off };
+926 -926
View File
File diff suppressed because it is too large. Load diff
+57 -57
View File
@@ -1,57 +1,57 @@
/* ArduboyEmu: the ATmega32U4 of the Arduboy (16 MHz AVR) with what the Arduboy uses of it: timers 0, 1, 3, 4, SPI to
* the SSD1306 display, the buttons, EEPROM, ADC (random seeds), the PLL and an idle USB, the speaker pins.
* Own code, no other emulator in it. Author: mameise. License: GPL-3.0-or-later (as Paramix Studio). */
#ifndef AVR_H
#define AVR_H
#include <stdint.h>
typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef int32_t s32;
#define AVR_FLASH_WORDS 16384u
#define AVR_DATA 0xB00u /* 32 registers, 64 + 160 I/O, 2.5 KB SRAM */
#define AVR_EEP 1024u
/* buttons (pressed = 1) */
#define AB_UP 1u
#define AB_DOWN 2u
#define AB_LEFT 4u
#define AB_RIGHT 8u
#define AB_A 16u
#define AB_B 32u
#if (defined(__arm__) && !defined(AB_NOJIT)) || defined(AB_JIT_HOST)
#define AB_JIT 1 /* the fast core (jit.inc) */
#else
#define AB_JIT 0
#endif
/* the data space (4 KB: addresses are masked), the fast core's context just before it */
typedef struct { u32 jit[64]; u8 d[0x1000]; } AbMem;
extern AbMem g_mem;
#define A_D (g_mem.d)
extern u8 A_EEP[AVR_EEP];
extern u8 A_GD[1024]; /* the display's memory: 8 pages of 128 columns */
#if !AB_JIT
extern u32 A_OP[AVR_FLASH_WORDS + 4]; /* the program, decoded */
#endif
extern const u16 *A_FLASH; /* the program as it is (words, little endian) */
extern u32 A_CYC; /* cycles run (wraps) */
extern int A_EEP_DIRTY; /* the game wrote the EEPROM */
extern u32 A_KEYS; /* buttons held */
extern u32 A_FRAMES; /* display frames sent (1024 data bytes) */
/* display state the program needs to draw */
typedef struct { u8 on, invert, contrast, flip_x, flip_y, allon, start; } AvrLcd;
extern AvrLcd A_LCD;
void ab_frame(void); /* called after each full picture (weak, the program may give its own) */
void ab_load(const u16 *flash, u32 words); /* decode the program (words beyond: 0xFFFF) */
void ab_reset(void);
void ab_run(u32 cycles); /* run about this many cycles */
/* the speaker: tone in Hz (0 silent), from the timers driving the pins or the pin changes counted since the last call
* over `cycles` */
u32 ab_tone(u32 cycles);
/* state save / load (registers, data, timers, display): bytes used, 0 when it did not fit */
u32 ab_state_save(u8 *buf, u32 size);
/* 9 KB of scratch memory for the program between runs (with the fast core: the end of its cache, emptied) */
#define AB_SCRATCH 0x2400u
u8 *ab_scratch(void);
int ab_state_load(const u8 *buf, u32 size);
#endif
/* ArduboyEmu: the ATmega32U4 of the Arduboy (16 MHz AVR) with what the Arduboy uses of it: timers 0, 1, 3, 4, SPI to
* the SSD1306 display, the buttons, EEPROM, ADC (random seeds), the PLL and an idle USB, the speaker pins.
* Own code, no other emulator in it. Author: mameise. License: GPL-3.0-or-later (as Paramix Studio). */
#ifndef AVR_H
#define AVR_H
#include <stdint.h>
typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef int32_t s32;
#define AVR_FLASH_WORDS 16384u
#define AVR_DATA 0xB00u /* 32 registers, 64 + 160 I/O, 2.5 KB SRAM */
#define AVR_EEP 1024u
/* buttons (pressed = 1) */
#define AB_UP 1u
#define AB_DOWN 2u
#define AB_LEFT 4u
#define AB_RIGHT 8u
#define AB_A 16u
#define AB_B 32u
#if (defined(__arm__) && !defined(AB_NOJIT)) || defined(AB_JIT_HOST)
#define AB_JIT 1 /* the fast core (jit.inc) */
#else
#define AB_JIT 0
#endif
/* the data space (4 KB: addresses are masked), the fast core's context just before it */
typedef struct { u32 jit[64]; u8 d[0x1000]; } AbMem;
extern AbMem g_mem;
#define A_D (g_mem.d)
extern u8 A_EEP[AVR_EEP];
extern u8 A_GD[1024]; /* the display's memory: 8 pages of 128 columns */
#if !AB_JIT
extern u32 A_OP[AVR_FLASH_WORDS + 4]; /* the program, decoded */
#endif
extern const u16 *A_FLASH; /* the program as it is (words, little endian) */
extern u32 A_CYC; /* cycles run (wraps) */
extern int A_EEP_DIRTY; /* the game wrote the EEPROM */
extern u32 A_KEYS; /* buttons held */
extern u32 A_FRAMES; /* display frames sent (1024 data bytes) */
/* display state the program needs to draw */
typedef struct { u8 on, invert, contrast, flip_x, flip_y, allon, start; } AvrLcd;
extern AvrLcd A_LCD;
void ab_frame(void); /* called after each full picture (weak, the program may give its own) */
void ab_load(const u16 *flash, u32 words); /* decode the program (words beyond: 0xFFFF) */
void ab_reset(void);
void ab_run(u32 cycles); /* run about this many cycles */
/* the speaker: tone in Hz (0 silent), from the timers driving the pins or the pin changes counted since the last call
* over `cycles` */
u32 ab_tone(u32 cycles);
/* state save / load (registers, data, timers, display): bytes used, 0 when it did not fit */
u32 ab_state_save(u8 *buf, u32 size);
/* 9 KB of scratch memory for the program between runs (with the fast core: the end of its cache, emptied) */
#define AB_SCRATCH 0x2400u
u8 *ab_scratch(void);
int ab_state_load(const u8 *buf, u32 size);
#endif
+763 -763
View File
File diff suppressed because it is too large. Load diff
+181 -181
View File
@@ -1,181 +1,181 @@
# ArduboyEmu (ab.bin) in Unicorn, as devt7.py: hardware calls caught, the screen into a picture.
# into a picture, the SysTick is advanced every RT instructions (96 MHz Cortex-M3 ~ RT per ms).
# python3 devv3.py <v3.elf> <image with v3.bin at APPOFF> <ms> [KEYS="t:mask,..."] [SHOTS="t,t,..."] [OUT=dir]
import sys, struct, subprocess, os
from unicorn import *
from unicorn.arm_const import *
elf, img, total_ms = sys.argv[1], sys.argv[2], int(sys.argv[3])
RT = int(os.environ.get('RT', '64000')) # instructions per millisecond (96 MHz, ~1.5 cycles each)
out = os.environ.get('OUT', '.')
syms = {}
for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 3: syms[p[2]] = int(p[0], 16)
fl = bytearray(open(img, 'rb').read())
u = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS)
u.ctl_set_cpu_model(UC_CPU_ARM_CORTEX_M4)
APPOFF = int(os.environ.get('APPOFF', '0xA0000'), 16) # program image (1.6.0: more programs elsewhere)
u.mem_map(0, 0x10000); u.mem_write(0, bytes(fl[APPOFF:APPOFF + 0x10000]))
u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, 0x1000)
u.mem_map(0x10000000, 0x100000)
u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, bytes(fl))
u.mem_map(0x40000000, 0x100000); u.mem_map(0x45000000, 0x1000); u.mem_map(0xE000E000, 0x1000); u.mem_map(0xE0001000, 0x1000) # DWT (CYCCNT reads 0 here)
u.mem_write(0x4000B014, struct.pack('<I', 0x60)) # 1.6.9 T7_LINK: UART1 LSR, sender empty (nothing received)
cfg = APPOFF + 0x140
rom_off = struct.unpack_from('<I', fl, cfg + 8)[0]
u.mem_write(0x10000000, bytes(fl[rom_off:rom_off + 0x100000]))
XIPN = [0]
def _xipw(uc, acc, a, sz, v, ud): # 1.7.2 GB_PAGES: the window follows its base register
o = v - 0x60000000
if 0 <= o < 0x1000000: uc.mem_write(0x10000000, bytes(fl[o:o + 0x100000]).ljust(0x100000, b'\xff')); XIPN[0] += 1
u.hook_add(UC_HOOK_MEM_WRITE, _xipw, begin=0x4002F004, end=0x4002F007)
import atexit; atexit.register(lambda: print('window moves', XIPN[0]))
WH = [] # WHEEL='t:steps,...' (+ one way, - the other): the encoder phases at GPIO2
for p in os.environ.get('WHEEL', '').split(','):
if ':' in p: t, n = p.split(':'); WH.append([float(t), int(n)])
state_enc = {'ph': 0, 'q': []}
GRAY = [0, 1, 3, 2]
fb = [[0] * 128 for _ in range(128)]
rect = {'x0': 0, 'x1': 0, 'y': 0, 'x': 0}
KS = []
for p in os.environ.get('KEYS', '').split(','):
if ':' in p: t, m = p.split(':'); KS.append((float(t), int(m)))
SH = [float(x) for x in os.environ.get('SHOTS', '').split(',') if x]
state = {'ms': 0, 'tone': [], 'left': 0, 'flashw': 0}
def keys():
m = 0
for t, v in KS:
if state['ms'] / 1000.0 >= t: m = v
return m
def ret(uc, v=None):
if v is not None: uc.reg_write(UC_ARM_REG_R0, v)
uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR) | 1)
def h_begin(uc, *a):
x0, y0, x1, y1 = (uc.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3))
rect.update(x0=x0, x1=x1, y=y0, x=x0); ret(uc)
def h_row(uc, *a):
p, n = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1)
d = struct.unpack('<%dH' % n, uc.mem_read(p, 2 * n))
for v in d:
if rect['y'] < 128 and rect['x'] < 128: fb[rect['y']][rect['x']] = v
rect['x'] += 1
if rect['x'] >= rect['x1']: rect['x'] = rect['x0']; rect['y'] += 1
ret(uc)
def h_tone(uc, *a): state['tone'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc)
def h_btn(uc, *a): ret(uc, keys())
def h_prog(uc, *a):
ad, src = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1)
d = bytes(uc.mem_read(src, 0x1000)); a = ad & 0xFFFFFF
uc.mem_write(0x60000000 + a, d); fl[a:a + 0x1000] = d; state['flashw'] += 1; ret(uc)
def h_erase(uc, *a):
a = uc.reg_read(UC_ARM_REG_R0) & 0xFFFFFF
uc.mem_write(0x60000000 + a, b'\xff' * 0x1000); fl[a:a + 0x1000] = b'\xff' * 0x1000; ret(uc)
def h_back(uc, *a): state['back'] = 1; uc.emu_stop()
def h_nop(uc, *a): ret(uc)
H = {'hw_px_begin': h_begin, 'hw_px_row': h_row, 'hw_px_end': h_nop, 'hw_tone': h_tone, 'hw_buttons': h_btn,
'flash_prog4k': h_prog, 'flash_erase4k': h_erase, 'hw_back_to_paradise': h_back, 'hw_init': h_nop,
'hw_backlight': h_nop, 'hw_bl_pwm_off': h_nop, 'hw_wdt_feed': h_nop}
for n, f in H.items():
a = syms[n] & ~1
u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: f(uc))(f), begin=a, end=a)
import builtins
if hasattr(builtins, '__gbprof'): u.hook_add(UC_HOOK_BLOCK, builtins.__gbprof[0])
if os.environ.get('CACHESIM'): # test38: the I-cache of the flash window (16 KB, 32-byte lines, WAYS ways, LRU): misses per frame
_ways = int(os.environ.get('WAYS', '4')); _sets = 16384 // 32 // _ways
_cs = [[] for _ in range(_sets)]; state['miss'] = 0; state['acc'] = 0
def _cr(uc, acc, a, sz, v, ud):
state['acc'] += 1
ln = (a - 0x10000000) >> 5; s = _cs[ln % _sets]
if ln in s: s.remove(ln); s.append(ln); return
state['miss'] += 1; s.append(ln)
if len(s) > _ways: s.pop(0)
u.hook_add(UC_HOOK_MEM_READ, _cr, begin=0x10000000, end=0x100FFFFF)
def bad(uc, access, addr, size, value, ud):
print('unmapped', access, hex(addr), 'pc', hex(uc.reg_read(UC_ARM_REG_PC))); return False
u.hook_add(UC_HOOK_MEM_UNMAPPED, bad)
# 1.6.9 test22 CLK_ECO: the AHB prescaler at 0x45000010 slows the core: RT >> sh instructions per ms
state['sh'] = 0; state['shms'] = [0, 0, 0, 0]
def _ahb(uc, acc, a, sz, v, ud):
state['sh'] = v & 7
if os.environ.get('ECOLOG'): print('AHB', v & 7, 'at ms', state['ms'])
u.hook_add(UC_HOOK_MEM_WRITE, _ahb, begin=0x45000010, end=0x45000013)
if os.environ.get('MEMW'):
_mw = int(os.environ['MEMW'], 16)
u.hook_add(UC_HOOK_MEM_WRITE, lambda uc, acc, a, sz, v, ud: print('W %08x = %08x at ms %d' % (a, v, state['ms'])), begin=_mw, end=_mw + 0x3F)
def shot(name):
from PIL import Image
im = Image.new('RGB', (128, 128))
for y in range(128):
for x in range(128):
v = fb[y][x]; im.putpixel((x, y), (((v >> 11) & 31) << 3, ((v >> 5) & 63) << 2, (v & 31) << 3))
im.save(os.path.join(out, name))
if os.environ.get('PMB'): # test: the Paradise's time in the mailbox (seconds since 1970, local)
_t = int(os.environ['PMB']); _c = int(os.environ.get('RTC0', '5000'))
u.mem_write(0x20000FC0, struct.pack('<IIII', 0x4B4C4350, _t, _c, (~_t) & 0xFFFFFFFF))
# 1.6.11 test2 GB_LINK: two of these joined by pipes, one exchange per ms (LINKW: pipe to write, LINKR: pipe to read)
LK = {'tx': bytearray(), 'n0': 0}
if os.environ.get('LINKW'):
def _uw(uc, acc, a, sz, v, ud):
LK['n0'] += 1
if LK['n0'] > 1: LK['tx'].append(v & 0xFF) # the first is the baud divisor
u.hook_add(UC_HOOK_MEM_WRITE, _uw, begin=0x4000B000, end=0x4000B000)
LK['w'] = os.fdopen(os.open(os.environ['LINKW'], os.O_RDWR), 'wb', buffering=0); LK['r'] = os.fdopen(os.open(os.environ['LINKR'], os.O_RDWR), 'rb', buffering=0) # (O_RDWR: no wait for the other end)
def link_ms():
d = bytes(LK['tx']); LK['tx'] = bytearray()
LK['w'].write(struct.pack('<H', len(d)) + d)
h = LK['r'].read(2)
while len(h) < 2: h += LK['r'].read(2 - len(h))
n = struct.unpack('<H', h)[0]; got = b''
while len(got) < n: got += LK['r'].read(n - len(got))
if got:
a = syms['g_pl']; rt = u.mem_read(a + 257, 1)[0]
for b in got: u.mem_write(a + rt, bytes([b])); rt = (rt + 1) & 0xFF
u.mem_write(a + 257, bytes([rt]))
sp, rst = struct.unpack('<II', bytes(u.mem_read(0, 8)))
u.reg_write(UC_ARM_REG_SP, sp)
pc = rst; gms = syms['g_ms']; rtc0 = int(os.environ.get('RTC0', '5000'))
emu_ms_sym = None
si = 0
while state['ms'] < total_ms and 'back' not in state:
u.mem_write(0x45000304, struct.pack('<I', rtc0 + state['ms'] // 1000))
try:
u.emu_start(pc | 1, 0xFFFFFFF0, count=max(1, RT >> state['sh'])); state['shms'][min(state['sh'], 3)] += 1
except UcError as ex:
print('error', ex, hex(u.reg_read(UC_ARM_REG_PC))); break
pc = u.reg_read(UC_ARM_REG_PC)
state['ms'] += 1
if 'w' in LK: link_ms()
v = struct.unpack('<I', u.mem_read(gms, 4))[0]; u.mem_write(gms, struct.pack('<I', v + 1))
# 1.6.9 test13 T7_KEYQ: the GPIO as the keys say (pressed = 0) and the tick's press counter
km = keys(); u.mem_write(0x40018000, struct.pack('<I', 0xFFFFFFFF & ~(((km & 1) << 9) | ((km & 2) << 10) | ((km & 4) << 8) | ((km & 8) << 5))))
if 'g_kin' in syms:
e = km & ~state.get('kprev', 0) & 7; state['kprev'] = km
u.mem_write(syms['g_kprev'], bytes([km & 7]))
for i in range(3):
if e & (1 << i): a = syms['g_kin'] + i; u.mem_write(a, bytes([(u.mem_read(a, 1)[0] + 1) & 0xFF]))
for w in WH:
if w[1] and state['ms'] / 1000.0 >= w[0]:
d = 1 if w[1] > 0 else -1; state_enc['ph'] = (state_enc['ph'] + d) % 4; w[0] += 0.004 if (state_enc['ph'] % 4) else 0.02
if state_enc['ph'] == 0: w[1] -= d
u.mem_write(0x4001A000, struct.pack('<I', GRAY[state_enc['ph']]))
for pk in os.environ.get('POKE', '').split(','): # test: 'ms:symbol+off:byte' written once
if pk.count(':') == 2 and int(pk.split(':')[0]) == state['ms']:
_t, _a, _v = pk.split(':'); _n, _o = (_a.split('+') + ['0'])[:2]; u.mem_write(syms[_n] + int(_o, 0), bytes([int(_v, 0)]))
if os.environ.get('DROPLOG') and 'g_v3st' in syms:
_d = struct.unpack('<I', u.mem_read(syms['g_v3st'] + 4, 4))[0]
if _d != state.get('drop', 0): print('drop', _d - state.get('drop', 0), 'at ms', state['ms'], 'sh', state['sh']); state['drop'] = _d
if si < len(SH) and state['ms'] >= SH[si] * 1000: shot('shot_%02d.png' % si); si += 1
if 'miss' in state and state['ms'] % 1000 == 0:
_f = struct.unpack('<I', u.mem_read(syms['g_abst'], 4))[0]; _df = max(1, _f - state.get('f0', 0))
print('s %2d frames %3d misses/frame %6.0f reads/frame %7.0f' % (state['ms'] // 1000, _df, state['miss'] / _df, state['acc'] / _df))
state['f0'] = _f; state['miss'] = 0; state['acc'] = 0
st = struct.unpack('<4I', bytes(u.mem_read(syms['g_abst'], 16)))
print('ms run', st[0], 'pictures', st[1], 'ms dropped', st[2], 'last slice ms', st[3])
(os.environ.get('TONES') and print('tones:', state['tone']));print('ms', state['ms'], 'tones', len(state['tone']), 'flash writes', state['flashw'], 'back' if 'back' in state else '', 'pc', hex(pc))
print('ms per clock step (96, 48, 24, 12 MHz):', state['shms'])
open(os.path.join(out, 'flash_after.bin'), 'wb').write(fl)
shot('shot_end.png')
for _d in os.environ.get('DUMP', '').split(','): # test: 'symbol+off:len' printed at the end
if ':' in _d:
_a, _l = _d.split(':'); _n, _o = (_a.split('+') + ['0'])[:2]
print('DUMP', _d, bytes(u.mem_read(syms[_n] + int(_o, 0), int(_l, 0))).hex())
# ArduboyEmu (ab.bin) in Unicorn, as devt7.py: hardware calls caught, the screen into a picture.
# into a picture, the SysTick is advanced every RT instructions (96 MHz Cortex-M3 ~ RT per ms).
# python3 devv3.py <v3.elf> <image with v3.bin at APPOFF> <ms> [KEYS="t:mask,..."] [SHOTS="t,t,..."] [OUT=dir]
import sys, struct, subprocess, os
from unicorn import *
from unicorn.arm_const import *
elf, img, total_ms = sys.argv[1], sys.argv[2], int(sys.argv[3])
RT = int(os.environ.get('RT', '64000')) # instructions per millisecond (96 MHz, ~1.5 cycles each)
out = os.environ.get('OUT', '.')
syms = {}
for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 3: syms[p[2]] = int(p[0], 16)
fl = bytearray(open(img, 'rb').read())
u = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS)
u.ctl_set_cpu_model(UC_CPU_ARM_CORTEX_M4)
APPOFF = int(os.environ.get('APPOFF', '0xA0000'), 16) # program image (1.6.0: more programs elsewhere)
u.mem_map(0, 0x10000); u.mem_write(0, bytes(fl[APPOFF:APPOFF + 0x10000]))
u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, 0x1000)
u.mem_map(0x10000000, 0x100000)
u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, bytes(fl))
u.mem_map(0x40000000, 0x100000); u.mem_map(0x45000000, 0x1000); u.mem_map(0xE000E000, 0x1000); u.mem_map(0xE0001000, 0x1000) # DWT (CYCCNT reads 0 here)
u.mem_write(0x4000B014, struct.pack('<I', 0x60)) # 1.6.9 T7_LINK: UART1 LSR, sender empty (nothing received)
cfg = APPOFF + 0x140
rom_off = struct.unpack_from('<I', fl, cfg + 8)[0]
u.mem_write(0x10000000, bytes(fl[rom_off:rom_off + 0x100000]))
XIPN = [0]
def _xipw(uc, acc, a, sz, v, ud): # 1.7.2 GB_PAGES: the window follows its base register
o = v - 0x60000000
if 0 <= o < 0x1000000: uc.mem_write(0x10000000, bytes(fl[o:o + 0x100000]).ljust(0x100000, b'\xff')); XIPN[0] += 1
u.hook_add(UC_HOOK_MEM_WRITE, _xipw, begin=0x4002F004, end=0x4002F007)
import atexit; atexit.register(lambda: print('window moves', XIPN[0]))
WH = [] # WHEEL='t:steps,...' (+ one way, - the other): the encoder phases at GPIO2
for p in os.environ.get('WHEEL', '').split(','):
if ':' in p: t, n = p.split(':'); WH.append([float(t), int(n)])
state_enc = {'ph': 0, 'q': []}
GRAY = [0, 1, 3, 2]
fb = [[0] * 128 for _ in range(128)]
rect = {'x0': 0, 'x1': 0, 'y': 0, 'x': 0}
KS = []
for p in os.environ.get('KEYS', '').split(','):
if ':' in p: t, m = p.split(':'); KS.append((float(t), int(m)))
SH = [float(x) for x in os.environ.get('SHOTS', '').split(',') if x]
state = {'ms': 0, 'tone': [], 'left': 0, 'flashw': 0}
def keys():
m = 0
for t, v in KS:
if state['ms'] / 1000.0 >= t: m = v
return m
def ret(uc, v=None):
if v is not None: uc.reg_write(UC_ARM_REG_R0, v)
uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR) | 1)
def h_begin(uc, *a):
x0, y0, x1, y1 = (uc.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3))
rect.update(x0=x0, x1=x1, y=y0, x=x0); ret(uc)
def h_row(uc, *a):
p, n = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1)
d = struct.unpack('<%dH' % n, uc.mem_read(p, 2 * n))
for v in d:
if rect['y'] < 128 and rect['x'] < 128: fb[rect['y']][rect['x']] = v
rect['x'] += 1
if rect['x'] >= rect['x1']: rect['x'] = rect['x0']; rect['y'] += 1
ret(uc)
def h_tone(uc, *a): state['tone'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc)
def h_btn(uc, *a): ret(uc, keys())
def h_prog(uc, *a):
ad, src = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1)
d = bytes(uc.mem_read(src, 0x1000)); a = ad & 0xFFFFFF
uc.mem_write(0x60000000 + a, d); fl[a:a + 0x1000] = d; state['flashw'] += 1; ret(uc)
def h_erase(uc, *a):
a = uc.reg_read(UC_ARM_REG_R0) & 0xFFFFFF
uc.mem_write(0x60000000 + a, b'\xff' * 0x1000); fl[a:a + 0x1000] = b'\xff' * 0x1000; ret(uc)
def h_back(uc, *a): state['back'] = 1; uc.emu_stop()
def h_nop(uc, *a): ret(uc)
H = {'hw_px_begin': h_begin, 'hw_px_row': h_row, 'hw_px_end': h_nop, 'hw_tone': h_tone, 'hw_buttons': h_btn,
'flash_prog4k': h_prog, 'flash_erase4k': h_erase, 'hw_back_to_paradise': h_back, 'hw_init': h_nop,
'hw_backlight': h_nop, 'hw_bl_pwm_off': h_nop, 'hw_wdt_feed': h_nop}
for n, f in H.items():
a = syms[n] & ~1
u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: f(uc))(f), begin=a, end=a)
import builtins
if hasattr(builtins, '__gbprof'): u.hook_add(UC_HOOK_BLOCK, builtins.__gbprof[0])
if os.environ.get('CACHESIM'): # test38: the I-cache of the flash window (16 KB, 32-byte lines, WAYS ways, LRU): misses per frame
_ways = int(os.environ.get('WAYS', '4')); _sets = 16384 // 32 // _ways
_cs = [[] for _ in range(_sets)]; state['miss'] = 0; state['acc'] = 0
def _cr(uc, acc, a, sz, v, ud):
state['acc'] += 1
ln = (a - 0x10000000) >> 5; s = _cs[ln % _sets]
if ln in s: s.remove(ln); s.append(ln); return
state['miss'] += 1; s.append(ln)
if len(s) > _ways: s.pop(0)
u.hook_add(UC_HOOK_MEM_READ, _cr, begin=0x10000000, end=0x100FFFFF)
def bad(uc, access, addr, size, value, ud):
print('unmapped', access, hex(addr), 'pc', hex(uc.reg_read(UC_ARM_REG_PC))); return False
u.hook_add(UC_HOOK_MEM_UNMAPPED, bad)
# 1.6.9 test22 CLK_ECO: the AHB prescaler at 0x45000010 slows the core: RT >> sh instructions per ms
state['sh'] = 0; state['shms'] = [0, 0, 0, 0]
def _ahb(uc, acc, a, sz, v, ud):
state['sh'] = v & 7
if os.environ.get('ECOLOG'): print('AHB', v & 7, 'at ms', state['ms'])
u.hook_add(UC_HOOK_MEM_WRITE, _ahb, begin=0x45000010, end=0x45000013)
if os.environ.get('MEMW'):
_mw = int(os.environ['MEMW'], 16)
u.hook_add(UC_HOOK_MEM_WRITE, lambda uc, acc, a, sz, v, ud: print('W %08x = %08x at ms %d' % (a, v, state['ms'])), begin=_mw, end=_mw + 0x3F)
def shot(name):
from PIL import Image
im = Image.new('RGB', (128, 128))
for y in range(128):
for x in range(128):
v = fb[y][x]; im.putpixel((x, y), (((v >> 11) & 31) << 3, ((v >> 5) & 63) << 2, (v & 31) << 3))
im.save(os.path.join(out, name))
if os.environ.get('PMB'): # test: the Paradise's time in the mailbox (seconds since 1970, local)
_t = int(os.environ['PMB']); _c = int(os.environ.get('RTC0', '5000'))
u.mem_write(0x20000FC0, struct.pack('<IIII', 0x4B4C4350, _t, _c, (~_t) & 0xFFFFFFFF))
# 1.6.11 test2 GB_LINK: two of these joined by pipes, one exchange per ms (LINKW: pipe to write, LINKR: pipe to read)
LK = {'tx': bytearray(), 'n0': 0}
if os.environ.get('LINKW'):
def _uw(uc, acc, a, sz, v, ud):
LK['n0'] += 1
if LK['n0'] > 1: LK['tx'].append(v & 0xFF) # the first is the baud divisor
u.hook_add(UC_HOOK_MEM_WRITE, _uw, begin=0x4000B000, end=0x4000B000)
LK['w'] = os.fdopen(os.open(os.environ['LINKW'], os.O_RDWR), 'wb', buffering=0); LK['r'] = os.fdopen(os.open(os.environ['LINKR'], os.O_RDWR), 'rb', buffering=0) # (O_RDWR: no wait for the other end)
def link_ms():
d = bytes(LK['tx']); LK['tx'] = bytearray()
LK['w'].write(struct.pack('<H', len(d)) + d)
h = LK['r'].read(2)
while len(h) < 2: h += LK['r'].read(2 - len(h))
n = struct.unpack('<H', h)[0]; got = b''
while len(got) < n: got += LK['r'].read(n - len(got))
if got:
a = syms['g_pl']; rt = u.mem_read(a + 257, 1)[0]
for b in got: u.mem_write(a + rt, bytes([b])); rt = (rt + 1) & 0xFF
u.mem_write(a + 257, bytes([rt]))
sp, rst = struct.unpack('<II', bytes(u.mem_read(0, 8)))
u.reg_write(UC_ARM_REG_SP, sp)
pc = rst; gms = syms['g_ms']; rtc0 = int(os.environ.get('RTC0', '5000'))
emu_ms_sym = None
si = 0
while state['ms'] < total_ms and 'back' not in state:
u.mem_write(0x45000304, struct.pack('<I', rtc0 + state['ms'] // 1000))
try:
u.emu_start(pc | 1, 0xFFFFFFF0, count=max(1, RT >> state['sh'])); state['shms'][min(state['sh'], 3)] += 1
except UcError as ex:
print('error', ex, hex(u.reg_read(UC_ARM_REG_PC))); break
pc = u.reg_read(UC_ARM_REG_PC)
state['ms'] += 1
if 'w' in LK: link_ms()
v = struct.unpack('<I', u.mem_read(gms, 4))[0]; u.mem_write(gms, struct.pack('<I', v + 1))
# 1.6.9 test13 T7_KEYQ: the GPIO as the keys say (pressed = 0) and the tick's press counter
km = keys(); u.mem_write(0x40018000, struct.pack('<I', 0xFFFFFFFF & ~(((km & 1) << 9) | ((km & 2) << 10) | ((km & 4) << 8) | ((km & 8) << 5))))
if 'g_kin' in syms:
e = km & ~state.get('kprev', 0) & 7; state['kprev'] = km
u.mem_write(syms['g_kprev'], bytes([km & 7]))
for i in range(3):
if e & (1 << i): a = syms['g_kin'] + i; u.mem_write(a, bytes([(u.mem_read(a, 1)[0] + 1) & 0xFF]))
for w in WH:
if w[1] and state['ms'] / 1000.0 >= w[0]:
d = 1 if w[1] > 0 else -1; state_enc['ph'] = (state_enc['ph'] + d) % 4; w[0] += 0.004 if (state_enc['ph'] % 4) else 0.02
if state_enc['ph'] == 0: w[1] -= d
u.mem_write(0x4001A000, struct.pack('<I', GRAY[state_enc['ph']]))
for pk in os.environ.get('POKE', '').split(','): # test: 'ms:symbol+off:byte' written once
if pk.count(':') == 2 and int(pk.split(':')[0]) == state['ms']:
_t, _a, _v = pk.split(':'); _n, _o = (_a.split('+') + ['0'])[:2]; u.mem_write(syms[_n] + int(_o, 0), bytes([int(_v, 0)]))
if os.environ.get('DROPLOG') and 'g_v3st' in syms:
_d = struct.unpack('<I', u.mem_read(syms['g_v3st'] + 4, 4))[0]
if _d != state.get('drop', 0): print('drop', _d - state.get('drop', 0), 'at ms', state['ms'], 'sh', state['sh']); state['drop'] = _d
if si < len(SH) and state['ms'] >= SH[si] * 1000: shot('shot_%02d.png' % si); si += 1
if 'miss' in state and state['ms'] % 1000 == 0:
_f = struct.unpack('<I', u.mem_read(syms['g_abst'], 4))[0]; _df = max(1, _f - state.get('f0', 0))
print('s %2d frames %3d misses/frame %6.0f reads/frame %7.0f' % (state['ms'] // 1000, _df, state['miss'] / _df, state['acc'] / _df))
state['f0'] = _f; state['miss'] = 0; state['acc'] = 0
st = struct.unpack('<4I', bytes(u.mem_read(syms['g_abst'], 16)))
print('ms run', st[0], 'pictures', st[1], 'ms dropped', st[2], 'last slice ms', st[3])
(os.environ.get('TONES') and print('tones:', state['tone']));print('ms', state['ms'], 'tones', len(state['tone']), 'flash writes', state['flashw'], 'back' if 'back' in state else '', 'pc', hex(pc))
print('ms per clock step (96, 48, 24, 12 MHz):', state['shms'])
open(os.path.join(out, 'flash_after.bin'), 'wb').write(fl)
shot('shot_end.png')
for _d in os.environ.get('DUMP', '').split(','): # test: 'symbol+off:len' printed at the end
if ':' in _d:
_a, _l = _d.split(':'); _n, _o = (_a.split('+') + ['0'])[:2]
print('DUMP', _d, bytes(u.mem_read(syms[_n] + int(_o, 0), int(_l, 0))).hex())
+92 -92
View File
@@ -1,92 +1,92 @@
/* CPU check against simavr: random instruction runs (ALU, branches, skips), registers and SREG after each step.
* gcc -O1 -DAB_SINGLE -o fuzz fuzz.c ../src/core/avr.c -lsimavr -lelf && ./fuzz 3000 */
/* random ALU sequences: our core against simavr */
#include <simavr/sim_avr.h>
#include <simavr/sim_core.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/core/avr.h"
extern u32 ab_pc(void);
static u16 fl[AVR_FLASH_WORDS];
static unsigned rr(void) { return (unsigned)rand(); }
static u16 gen(void)
{
unsigned d = rr() & 31, r = rr() & 31, K = rr() & 255, d4 = rr() & 15, b = rr() & 7;
switch (rr() % 40) {
case 0: return 0x0C00 | (r & 16) << 5 | d << 4 | (r & 15); /* ADD */
case 1: return 0x1C00 | (r & 16) << 5 | d << 4 | (r & 15); /* ADC */
case 2: return 0x1800 | (r & 16) << 5 | d << 4 | (r & 15); /* SUB */
case 3: return 0x0800 | (r & 16) << 5 | d << 4 | (r & 15); /* SBC */
case 4: return 0x2000 | (r & 16) << 5 | d << 4 | (r & 15); /* AND */
case 5: return 0x2800 | (r & 16) << 5 | d << 4 | (r & 15); /* OR */
case 6: return 0x2400 | (r & 16) << 5 | d << 4 | (r & 15); /* EOR */
case 7: return 0x1400 | (r & 16) << 5 | d << 4 | (r & 15); /* CP */
case 8: return 0x0400 | (r & 16) << 5 | d << 4 | (r & 15); /* CPC */
case 9: return 0x2C00 | (r & 16) << 5 | d << 4 | (r & 15); /* MOV */
case 10: return 0x5000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* SUBI */
case 11: return 0x4000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* SBCI */
case 12: return 0x7000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* ANDI */
case 13: return 0x6000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* ORI */
case 14: return 0x3000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* CPI */
case 15: return 0x9400 | d << 4 | 0; /* COM */
case 16: return 0x9400 | d << 4 | 1; /* NEG */
case 17: return 0x9400 | d << 4 | 2; /* SWAP */
case 18: return 0x9400 | d << 4 | 3; /* INC */
case 19: return 0x9400 | d << 4 | 5; /* ASR */
case 20: return 0x9400 | d << 4 | 6; /* LSR */
case 21: return 0x9400 | d << 4 | 7; /* ROR */
case 22: return 0x9400 | d << 4 | 10; /* DEC */
case 23: return 0x9C00 | (r & 16) << 5 | d << 4 | (r & 15); /* MUL */
case 24: return 0x0200 | d4 << 4 | (rr() & 15); /* MULS */
case 25: return 0x0300 | (rr() & 0x88) | (rr() & 0x77); /* MULSU FMUL* */
case 26: return 0x9600 | (rr() & 0xFF); /* ADIW */
case 27: return 0x9700 | (rr() & 0xFF); /* SBIW */
case 28: return 0x0100 | (rr() & 0xFF); /* MOVW */
case 29: return 0xFA00 | d << 4 | b; /* BST */
case 30: return 0xF800 | d << 4 | b; /* BLD */
case 31: { static const int B[4] = { 0, 1, 5, 6 }; return 0x9408 | B[rr() & 3] << 4 | ((rr() & 1) << 7); } /* BSET/BCLR of C Z H T */
case 32: return 0xE000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* LDI */
case 34: case 35: return 0xF000 | (rr() & 0x400) | (1 << 3) | (rr() & 7); /* BRBS/BRBC .+1 */
case 36: return 0xFC00 | (rr() & 0x200) | d << 4 | b; /* SBRC/SBRS */
case 37: return 0x1000 | (r & 16) << 5 | d << 4 | (r & 15); /* CPSE */
default: return 0x0000;
}
}
int main(int argc, char **argv)
{
int seeds = argc > 1 ? atoi(argv[1]) : 200, fails = 0;
for (int sd = 1; sd <= seeds; sd++) {
srand(sd);
int n = 200;
for (int i = 0; i < n; i++) { fl[i] = gen(); if (fl[i] == 0x9478 || fl[i] == 0x94F8) fl[i] = 0; { unsigned o = fl[i] & 0xfc0f; if ((o == 0x940c || o == 0x940d || o == 0x940e || o == 0x940f || o == 0x9000 || o == 0x9200) && (fl[i] & 0xFE0F) != 0x9000) fl[i] = 0; } if ((fl[i] & 0xFE0F) == 0x9000 && i + 1 < n) { fl[++i] = 0x0100 + (rr() & 0x7FF); } }
fl[n] = 0xCFFF; /* rjmp . */
avr_t *a = avr_make_mcu_by_name("atmega32u4"); avr_init(a);
avr_loadcode(a, (uint8_t *)fl, (n + 1) * 2, 0);
ab_load(fl, n + 1); ab_reset();
unsigned sreg0 = rr() & 0x6F; sreg0 |= (((sreg0 >> 2) ^ (sreg0 >> 3)) & 1) << 4;
for (int i = 0; i < 32; i++) { u8 v = rr(); a->data[i] = v; A_D[i] = v; }
a->data[R_SREG] = sreg0; for (int i = 0; i < 8; i++) a->sreg[i] = (sreg0 >> i) & 1; A_D[0x5F] = sreg0;
for (int i = 0x100; i < 0xB00; i++) { u8 v = rr(); a->data[i] = v; A_D[i] = v; }
a->pc = 0;
for (int st = 0; st < n; st++) {
u16 w = fl[a->pc / 2];
if (a->pc / 2 >= n) break;
avr_run(a);
ab_run(1);
if (getenv("TR") && sd == atoi(getenv("TR"))) { unsigned s2 = 0; for (int i = 0; i < 8; i++) if (a->sreg[i]) s2 |= 1 << i; printf(" st %d op %04x sreg sim %02x ours %02x pc %x/%x cyc %llu/%u\n", st, w, s2, A_D[0x5F], a->pc/2, ab_pc(), (unsigned long long)a->cycle, A_CYC); }
unsigned s1 = 0; for (int i = 0; i < 8; i++) if (a->sreg[i]) s1 |= 1 << i;
int bad = s1 != A_D[0x5F] || a->pc / 2 != ab_pc(); for (int i = 0; i < 32; i++) if (a->data[i] != A_D[i]) bad = 1;
if (bad) {
printf("seed %d step %d at %x op %04x: sreg sim %02x ours %02x pc sim %x ours %x\n", sd, st, (unsigned)0, w, s1, A_D[0x5F], a->pc/2, ab_pc());
for (int i = 0; i < 32; i++) if (a->data[i] != A_D[i]) printf(" r%d sim %02x ours %02x\n", i, a->data[i], A_D[i]);
fails++; break;
}
}
avr_terminate(a);
if (fails > 10) break;
}
printf("fails %d\n", fails);
return 0;
}
/* CPU check against simavr: random instruction runs (ALU, branches, skips), registers and SREG after each step.
* gcc -O1 -DAB_SINGLE -o fuzz fuzz.c ../src/core/avr.c -lsimavr -lelf && ./fuzz 3000 */
/* random ALU sequences: our core against simavr */
#include <simavr/sim_avr.h>
#include <simavr/sim_core.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/core/avr.h"
extern u32 ab_pc(void);
static u16 fl[AVR_FLASH_WORDS];
static unsigned rr(void) { return (unsigned)rand(); }
static u16 gen(void)
{
unsigned d = rr() & 31, r = rr() & 31, K = rr() & 255, d4 = rr() & 15, b = rr() & 7;
switch (rr() % 40) {
case 0: return 0x0C00 | (r & 16) << 5 | d << 4 | (r & 15); /* ADD */
case 1: return 0x1C00 | (r & 16) << 5 | d << 4 | (r & 15); /* ADC */
case 2: return 0x1800 | (r & 16) << 5 | d << 4 | (r & 15); /* SUB */
case 3: return 0x0800 | (r & 16) << 5 | d << 4 | (r & 15); /* SBC */
case 4: return 0x2000 | (r & 16) << 5 | d << 4 | (r & 15); /* AND */
case 5: return 0x2800 | (r & 16) << 5 | d << 4 | (r & 15); /* OR */
case 6: return 0x2400 | (r & 16) << 5 | d << 4 | (r & 15); /* EOR */
case 7: return 0x1400 | (r & 16) << 5 | d << 4 | (r & 15); /* CP */
case 8: return 0x0400 | (r & 16) << 5 | d << 4 | (r & 15); /* CPC */
case 9: return 0x2C00 | (r & 16) << 5 | d << 4 | (r & 15); /* MOV */
case 10: return 0x5000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* SUBI */
case 11: return 0x4000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* SBCI */
case 12: return 0x7000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* ANDI */
case 13: return 0x6000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* ORI */
case 14: return 0x3000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* CPI */
case 15: return 0x9400 | d << 4 | 0; /* COM */
case 16: return 0x9400 | d << 4 | 1; /* NEG */
case 17: return 0x9400 | d << 4 | 2; /* SWAP */
case 18: return 0x9400 | d << 4 | 3; /* INC */
case 19: return 0x9400 | d << 4 | 5; /* ASR */
case 20: return 0x9400 | d << 4 | 6; /* LSR */
case 21: return 0x9400 | d << 4 | 7; /* ROR */
case 22: return 0x9400 | d << 4 | 10; /* DEC */
case 23: return 0x9C00 | (r & 16) << 5 | d << 4 | (r & 15); /* MUL */
case 24: return 0x0200 | d4 << 4 | (rr() & 15); /* MULS */
case 25: return 0x0300 | (rr() & 0x88) | (rr() & 0x77); /* MULSU FMUL* */
case 26: return 0x9600 | (rr() & 0xFF); /* ADIW */
case 27: return 0x9700 | (rr() & 0xFF); /* SBIW */
case 28: return 0x0100 | (rr() & 0xFF); /* MOVW */
case 29: return 0xFA00 | d << 4 | b; /* BST */
case 30: return 0xF800 | d << 4 | b; /* BLD */
case 31: { static const int B[4] = { 0, 1, 5, 6 }; return 0x9408 | B[rr() & 3] << 4 | ((rr() & 1) << 7); } /* BSET/BCLR of C Z H T */
case 32: return 0xE000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* LDI */
case 34: case 35: return 0xF000 | (rr() & 0x400) | (1 << 3) | (rr() & 7); /* BRBS/BRBC .+1 */
case 36: return 0xFC00 | (rr() & 0x200) | d << 4 | b; /* SBRC/SBRS */
case 37: return 0x1000 | (r & 16) << 5 | d << 4 | (r & 15); /* CPSE */
default: return 0x0000;
}
}
int main(int argc, char **argv)
{
int seeds = argc > 1 ? atoi(argv[1]) : 200, fails = 0;
for (int sd = 1; sd <= seeds; sd++) {
srand(sd);
int n = 200;
for (int i = 0; i < n; i++) { fl[i] = gen(); if (fl[i] == 0x9478 || fl[i] == 0x94F8) fl[i] = 0; { unsigned o = fl[i] & 0xfc0f; if ((o == 0x940c || o == 0x940d || o == 0x940e || o == 0x940f || o == 0x9000 || o == 0x9200) && (fl[i] & 0xFE0F) != 0x9000) fl[i] = 0; } if ((fl[i] & 0xFE0F) == 0x9000 && i + 1 < n) { fl[++i] = 0x0100 + (rr() & 0x7FF); } }
fl[n] = 0xCFFF; /* rjmp . */
avr_t *a = avr_make_mcu_by_name("atmega32u4"); avr_init(a);
avr_loadcode(a, (uint8_t *)fl, (n + 1) * 2, 0);
ab_load(fl, n + 1); ab_reset();
unsigned sreg0 = rr() & 0x6F; sreg0 |= (((sreg0 >> 2) ^ (sreg0 >> 3)) & 1) << 4;
for (int i = 0; i < 32; i++) { u8 v = rr(); a->data[i] = v; A_D[i] = v; }
a->data[R_SREG] = sreg0; for (int i = 0; i < 8; i++) a->sreg[i] = (sreg0 >> i) & 1; A_D[0x5F] = sreg0;
for (int i = 0x100; i < 0xB00; i++) { u8 v = rr(); a->data[i] = v; A_D[i] = v; }
a->pc = 0;
for (int st = 0; st < n; st++) {
u16 w = fl[a->pc / 2];
if (a->pc / 2 >= n) break;
avr_run(a);
ab_run(1);
if (getenv("TR") && sd == atoi(getenv("TR"))) { unsigned s2 = 0; for (int i = 0; i < 8; i++) if (a->sreg[i]) s2 |= 1 << i; printf(" st %d op %04x sreg sim %02x ours %02x pc %x/%x cyc %llu/%u\n", st, w, s2, A_D[0x5F], a->pc/2, ab_pc(), (unsigned long long)a->cycle, A_CYC); }
unsigned s1 = 0; for (int i = 0; i < 8; i++) if (a->sreg[i]) s1 |= 1 << i;
int bad = s1 != A_D[0x5F] || a->pc / 2 != ab_pc(); for (int i = 0; i < 32; i++) if (a->data[i] != A_D[i]) bad = 1;
if (bad) {
printf("seed %d step %d at %x op %04x: sreg sim %02x ours %02x pc sim %x ours %x\n", sd, st, (unsigned)0, w, s1, A_D[0x5F], a->pc/2, ab_pc());
for (int i = 0; i < 32; i++) if (a->data[i] != A_D[i]) printf(" r%d sim %02x ours %02x\n", i, a->data[i], A_D[i]);
fails++; break;
}
}
avr_terminate(a);
if (fails > 10) break;
}
printf("fails %d\n", fails);
return 0;
}
+63 -63
View File
@@ -1,63 +1,63 @@
/* PC test of the ArduboyEmu core: hostab game.hex seconds [KEYS="t:mask,..."] [SHOTS="t,..."] [OUT=dir]
* Writes the display as PGM pictures (128 x 64) at the shot times, prints frames, sound and timing. */
#include "../src/core/avr.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
static u16 g_fl[AVR_FLASH_WORDS];
extern u32 ab_pc(void);
static u32 g_hist[AVR_FLASH_WORDS];
static int hexval(const char *s, int n) { int v = 0; for (int i = 0; i < n; i++) { int c = s[i]; v = v * 16 + (c <= '9' ? c - '0' : (c | 32) - 'a' + 10); } return v; }
static u32 load_hex(const char *fn)
{
FILE *f = fopen(fn, "r"); if (!f) { perror(fn); exit(1); }
u8 *b = (u8 *)g_fl; memset(b, 0xFF, sizeof g_fl);
char l[600]; u32 hi = 0, top = 0;
while (fgets(l, sizeof l, f)) {
if (l[0] != ':') continue;
int n = hexval(l + 1, 2), ad = hexval(l + 3, 4), ty = hexval(l + 7, 2);
if (ty == 0) for (int i = 0; i < n; i++) { u32 a = hi + ad + i; if (a < sizeof g_fl) { b[a] = (u8)hexval(l + 9 + 2 * i, 2); if (a + 1 > top) top = a + 1; } }
else if (ty == 2) hi = hexval(l + 9, 4) << 4;
else if (ty == 4) hi = hexval(l + 9, 4) << 16;
}
fclose(f);
return (top + 1) / 2;
}
static void shot(const char *out, int k)
{
char fn[512]; snprintf(fn, sizeof fn, "%s/shot%02d.pgm", out, k);
FILE *f = fopen(fn, "wb"); fprintf(f, "P5 128 64 255\n");
for (int y = 0; y < 64; y++) for (int x = 0; x < 128; x++) {
int on = (A_GD[(y >> 3) * 128 + x] >> (y & 7)) & 1;
if (A_LCD.invert) on ^= 1;
if (!A_LCD.on) on = 0;
fputc(on ? 255 : 0, f);
}
fclose(f);
}
int main(int argc, char **argv)
{
u32 words = load_hex(argv[1]); double secs = atof(argv[2]);
const char *ks = getenv("KEYS"), *ss = getenv("SHOTS"), *out = getenv("OUT"); if (!out) out = ".";
double kt[64]; u32 km[64]; int nk = 0; double st[64]; int ns = 0;
if (ks) { const char *p = ks; while (*p && nk < 64) { kt[nk] = atof(p); const char *c = strchr(p, ':'); km[nk++] = (u32)atoi(c + 1); p = strchr(c, ','); if (!p) break; p++; } }
if (ss) { const char *p = ss; while (*p && ns < 64) { st[ns++] = atof(p); p = strchr(p, ','); if (!p) break; p++; } }
ab_load(g_fl, words); ab_reset();
for (u32 i = 0; i < AVR_EEP; i++) A_EEP[i] = 0xFF;
clock_t c0 = clock(); int si = 0; u32 tones = 0, lastf = 0;
u32 ms_n = (u32)(secs * 1000);
for (u32 ms = 0; ms < ms_n; ms++) {
double t = ms / 1000.0; A_KEYS = 0; for (int i = 0; i < nk; i++) if (t >= kt[i]) A_KEYS = km[i];
if (getenv("CALLER")) { u32 c = strtoul(getenv("CALLER"), 0, 16); for (u32 e = A_CYC + 16000; (s32)(A_CYC - e) < 0; ) { if (ab_pc() == c) { u32 sp = A_D[0x5D] | A_D[0x5E] << 8; g_hist[((A_D[sp + 1] << 8) | A_D[sp + 2]) & 0x3FFF]++; } ab_run(1); } } else
if (getenv("PCS")) for (int q = 0; q < 16; q++) { ab_run(1000); g_hist[ab_pc() & 0x3FFF]++; } else ab_run(16000);
if (ms % 50 == 49) { u32 hz = ab_tone(800000); if (hz) tones++; }
while (si < ns && t >= st[si]) shot(out, si++);
if (ms % 1000 == 999) { printf("t=%u s frames %u (+%u)\n", (ms + 1) / 1000, A_FRAMES, A_FRAMES - lastf); lastf = A_FRAMES; }
}
while (si < ns) shot(out, si++);
if (getenv("PCS") || getenv("CALLER")) { for (int k = 0; k < 8; k++) { u32 b = 0, bi = 0; for (u32 i = 0; i < AVR_FLASH_WORDS; i++) if (g_hist[i] > b) { b = g_hist[i]; bi = i; } printf("pc %04x (byte %05x) %u\n", bi, bi * 2, b); g_hist[bi] = 0; } }
double el = (double)(clock() - c0) / CLOCKS_PER_SEC;
printf("frames %u, tone windows %u, host %.2f s for %.1f s\n", A_FRAMES, tones, el, secs);
return 0;
}
/* PC test of the ArduboyEmu core: hostab game.hex seconds [KEYS="t:mask,..."] [SHOTS="t,..."] [OUT=dir]
* Writes the display as PGM pictures (128 x 64) at the shot times, prints frames, sound and timing. */
#include "../src/core/avr.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
static u16 g_fl[AVR_FLASH_WORDS];
extern u32 ab_pc(void);
static u32 g_hist[AVR_FLASH_WORDS];
static int hexval(const char *s, int n) { int v = 0; for (int i = 0; i < n; i++) { int c = s[i]; v = v * 16 + (c <= '9' ? c - '0' : (c | 32) - 'a' + 10); } return v; }
static u32 load_hex(const char *fn)
{
FILE *f = fopen(fn, "r"); if (!f) { perror(fn); exit(1); }
u8 *b = (u8 *)g_fl; memset(b, 0xFF, sizeof g_fl);
char l[600]; u32 hi = 0, top = 0;
while (fgets(l, sizeof l, f)) {
if (l[0] != ':') continue;
int n = hexval(l + 1, 2), ad = hexval(l + 3, 4), ty = hexval(l + 7, 2);
if (ty == 0) for (int i = 0; i < n; i++) { u32 a = hi + ad + i; if (a < sizeof g_fl) { b[a] = (u8)hexval(l + 9 + 2 * i, 2); if (a + 1 > top) top = a + 1; } }
else if (ty == 2) hi = hexval(l + 9, 4) << 4;
else if (ty == 4) hi = hexval(l + 9, 4) << 16;
}
fclose(f);
return (top + 1) / 2;
}
static void shot(const char *out, int k)
{
char fn[512]; snprintf(fn, sizeof fn, "%s/shot%02d.pgm", out, k);
FILE *f = fopen(fn, "wb"); fprintf(f, "P5 128 64 255\n");
for (int y = 0; y < 64; y++) for (int x = 0; x < 128; x++) {
int on = (A_GD[(y >> 3) * 128 + x] >> (y & 7)) & 1;
if (A_LCD.invert) on ^= 1;
if (!A_LCD.on) on = 0;
fputc(on ? 255 : 0, f);
}
fclose(f);
}
int main(int argc, char **argv)
{
u32 words = load_hex(argv[1]); double secs = atof(argv[2]);
const char *ks = getenv("KEYS"), *ss = getenv("SHOTS"), *out = getenv("OUT"); if (!out) out = ".";
double kt[64]; u32 km[64]; int nk = 0; double st[64]; int ns = 0;
if (ks) { const char *p = ks; while (*p && nk < 64) { kt[nk] = atof(p); const char *c = strchr(p, ':'); km[nk++] = (u32)atoi(c + 1); p = strchr(c, ','); if (!p) break; p++; } }
if (ss) { const char *p = ss; while (*p && ns < 64) { st[ns++] = atof(p); p = strchr(p, ','); if (!p) break; p++; } }
ab_load(g_fl, words); ab_reset();
for (u32 i = 0; i < AVR_EEP; i++) A_EEP[i] = 0xFF;
clock_t c0 = clock(); int si = 0; u32 tones = 0, lastf = 0;
u32 ms_n = (u32)(secs * 1000);
for (u32 ms = 0; ms < ms_n; ms++) {
double t = ms / 1000.0; A_KEYS = 0; for (int i = 0; i < nk; i++) if (t >= kt[i]) A_KEYS = km[i];
if (getenv("CALLER")) { u32 c = strtoul(getenv("CALLER"), 0, 16); for (u32 e = A_CYC + 16000; (s32)(A_CYC - e) < 0; ) { if (ab_pc() == c) { u32 sp = A_D[0x5D] | A_D[0x5E] << 8; g_hist[((A_D[sp + 1] << 8) | A_D[sp + 2]) & 0x3FFF]++; } ab_run(1); } } else
if (getenv("PCS")) for (int q = 0; q < 16; q++) { ab_run(1000); g_hist[ab_pc() & 0x3FFF]++; } else ab_run(16000);
if (ms % 50 == 49) { u32 hz = ab_tone(800000); if (hz) tones++; }
while (si < ns && t >= st[si]) shot(out, si++);
if (ms % 1000 == 999) { printf("t=%u s frames %u (+%u)\n", (ms + 1) / 1000, A_FRAMES, A_FRAMES - lastf); lastf = A_FRAMES; }
}
while (si < ns) shot(out, si++);
if (getenv("PCS") || getenv("CALLER")) { for (int k = 0; k < 8; k++) { u32 b = 0, bi = 0; for (u32 i = 0; i < AVR_FLASH_WORDS; i++) if (g_hist[i] > b) { b = g_hist[i]; bi = i; } printf("pc %04x (byte %05x) %u\n", bi, bi * 2, b); g_hist[bi] = 0; } }
double el = (double)(clock() - c0) / CLOCKS_PER_SEC;
printf("frames %u, tone windows %u, host %.2f s for %.1f s\n", A_FRAMES, tones, el, secs);
return 0;
}
+10 -10
View File
@@ -1,10 +1,10 @@
#!/bin/bash
# smallest prefix of seed $1 that differs
lo=0; hi=200
while [ $((hi-lo)) -gt 1 ]; do m=$(((lo+hi)/2)); if ./run.sh $1 $m | grep -q ok; then lo=$m; else hi=$m; fi; done
echo "seed $1 first diff at body $hi"
python3 -c "
import sys; sys.path.insert(0,'/tmp/jf'); import gen
p=gen.gen($1,$hi); n=len(gen.gen($1,0))-3
for k,x in enumerate(p[n:n+$hi]): print(k, '%04x'%x)
" | tail -4
#!/bin/bash
# smallest prefix of seed $1 that differs
lo=0; hi=200
while [ $((hi-lo)) -gt 1 ]; do m=$(((lo+hi)/2)); if ./run.sh $1 $m | grep -q ok; then lo=$m; else hi=$m; fi; done
echo "seed $1 first diff at body $hi"
python3 -c "
import sys; sys.path.insert(0,'/tmp/jf'); import gen
p=gen.gen($1,$hi); n=len(gen.gen($1,0))-3
for k,x in enumerate(p[n:n+$hi]): print(k, '%04x'%x)
" | tail -4
+9 -9
View File
@@ -1,9 +1,9 @@
import sys
for d in sys.argv[1:]:
r=open(d+'/ref.txt').read().split(); j=open(d+'/jit.txt').read().split()
out=[]
for k,(a,b) in enumerate(zip(r,j)):
base = 0 if k==0 else 0x100
for i in range(0,len(a),2):
if a[i:i+2]!=b[i:i+2]: out.append('%x:%s/%s'%(base+i//2, a[i:i+2], b[i:i+2]))
print(d, ' '.join(out[:8]))
import sys
for d in sys.argv[1:]:
r=open(d+'/ref.txt').read().split(); j=open(d+'/jit.txt').read().split()
out=[]
for k,(a,b) in enumerate(zip(r,j)):
base = 0 if k==0 else 0x100
for i in range(0,len(a),2):
if a[i:i+2]!=b[i:i+2]: out.append('%x:%s/%s'%(base+i//2, a[i:i+2], b[i:i+2]))
print(d, ' '.join(out[:8]))
+83 -83
View File
@@ -1,83 +1,83 @@
import random, sys, struct
def gen(seed, lim=10**9):
R = random.Random(seed); w = []
# init registers r0..r31 via r16
for r in list(range(0, 16)) + list(range(17, 32)):
v = R.randrange(256); w.append(0xE000 | (v & 0xF0) << 4 | (0 << 4) | (v & 15)) # ldi r16, v
w.append(0x2C00 | (r & 16) << 5 | (r & 15) << 4 | 0 | (16 & 16) << 5 | (16 & 15)) # mov r, r16 (placeholder fixed below)
# fix movs: mov rd, r16: 0010 11rd dddd rrrr with r=16 -> r bit4 at bit9
out = []
for i in range(0, len(w), 2):
out.append(w[i]); r = (list(range(0, 16)) + list(range(17, 32)))[i // 2]
out.append(0x2C00 | 0x200 | ((r & 16) << 4) | ((r & 15) << 4) | 0)
v = R.randrange(256); out.append(0xE000 | (v & 0xF0) << 4 | (v & 15))
# SREG: random consistent (S = N^V), no I
s = R.randrange(128) & 0x6F; s |= (((s >> 2) ^ (s >> 3)) & 1) << 4
out.append(0xE010 | (s & 0xF0) << 4 | (s & 15)) # ldi r17, s
out.append(0xBF1F) # out SREG, r17
out.append(0xE0A0); out.append(0xE0B1) # X = 0x100
out.append(0xE0C8); out.append(0xE0D1) # Y = 0x108
out.append(0xE0E0 | 0); out.append(0xE0F1) # Z = 0x100 (r30=0? ldi r30,0)
body = []
n = 120
i = 0
depth = 0
while i < n:
d = R.randrange(32); r = R.randrange(32); K = R.randrange(256); d4 = R.randrange(16); b = R.randrange(8)
c = R.randrange(46)
def dr(op): return op | (r & 16) << 5 | d << 4 | (r & 15)
if c < 10: x = dr([0x0C00,0x1C00,0x1800,0x0800,0x2000,0x2800,0x2400,0x1400,0x0400,0x2C00][c])
elif c < 15: x = [0x5000,0x4000,0x7000,0x6000,0x3000][c-10] | (K & 0xF0) << 4 | d4 << 4 | (K & 15)
elif c < 23: x = 0x9400 | d << 4 | [0,1,2,3,5,6,7,10][c-15]
elif c == 23: x = 0x9C00 | (r & 16) << 5 | d << 4 | (r & 15)
elif c == 24: x = 0x0200 | d4 << 4 | R.randrange(16)
elif c == 25: x = 0x0300 | R.randrange(256) & 0xFF
elif c == 26: x = 0x9600 | R.randrange(256) & 0x3F | 0x00 # adiw r24
elif c == 27: x = 0x9700 | R.randrange(256) & 0x3F
elif c == 28: x = 0x0100 | R.randrange(256)
elif c == 29: x = 0xFA00 | d << 4 | b
elif c == 30: x = 0xF800 | d << 4 | b
elif c == 31: x = 0x9408 | [0,1,5,6][R.randrange(4)] << 4 | R.randrange(2) << 7
elif c in (32, 33): x = 0xF000 | R.randrange(2) << 10 | 1 << 3 | R.choice([0,1,2,3,4,6,7]) # branch .+1 (not on H)
elif c == 34: x = 0xFC00 | R.randrange(2) << 9 | d << 4 | b
elif c == 35: x = 0x1000 | (r & 16) << 5 | d << 4 | (r & 15)
elif c == 36: # ld/st through X, Y, Z (pointers kept in 0x100..0x13F)
if d >= 26: d = 16
x = [0x900C,0x900D,0x9009,0x9001,0x920C,0x920D,0x9209,0x9201,0x8000,0x8200][R.randrange(10)] | d << 4
elif c == 37: # ldd/std Y+q
if d >= 26: d = 17
q = R.randrange(8); x = (0x8008 | (R.randrange(2) << 9) | d << 4 | q)
elif c == 38:
if not depth: continue
if d >= 26: d = 18
x = 0x900F | d << 4; depth -= 1 # pop
elif c == 39: x = 0x920F | d << 4; depth += 1 # push
elif c == 40: x = 0x95C8 # lpm
elif c == 41: x = 0x9004 | d << 4 # lpm rd, Z
elif c == 42: # reset pointers into range
body += [0xE0A0 | R.randrange(16), 0xE0B1, 0xE0C0 | R.randrange(8), 0xE0D1, 0xE0E0 | R.randrange(16), 0xE0F1]; i += 6; continue
elif c == 43: x = 0x0000 # (in rd, SREG: H differs on purpose)
elif c == 44: x = 0x9000 | (d % 26) << 4; body += [0, x, 0x0100 + R.randrange(0x40)]; i += 3; continue # lds
else: x = 0x9200 | d << 4; body += [0, x, 0x0100 + R.randrange(0x40)]; i += 3; continue # sts
# keep the pointers sane: never write r26..r31 with ALU ops
if c < 36 and c not in (28,) and ((x >> 4) & 31) >= 26 and c not in (32, 33, 34, 35, 29, 31): x = 0
if c == 28 and ((x >> 4) & 15) * 2 >= 26: x = 0
if c in (26, 27): x = x & ~0x30 # adiw/sbiw r24 only
body.append(x); i += 1
# avoid skips landing in the middle of a 2-word instruction: put a nop after each 2-word one
fixed = []
for k, x in enumerate(body):
fixed.append(x)
if (x & 0xFE0F) in (0x9000, 0x9200) and k + 1 < len(body): pass
prog = out + fixed[:lim] + [0x0000, 0x0000, 0xCFFF]
return prog
def to_hex(prog, fn):
b = b''.join(struct.pack('<H', x & 0xFFFF) for x in prog)
with open(fn, 'w') as f:
for a in range(0, len(b), 16):
c = b[a:a+16]; s = len(c) + (a >> 8) + (a & 255) + sum(c)
f.write(':%02X%04X00%s%02X\n' % (len(c), a, c.hex().upper(), (-s) & 255))
f.write(':00000001FF\n')
open(fn + '.bin', 'wb').write(b)
if __name__ == '__main__':
to_hex(gen(int(sys.argv[1]), int(sys.argv[3]) if len(sys.argv) > 3 else 10**9), sys.argv[2])
import random, sys, struct
def gen(seed, lim=10**9):
R = random.Random(seed); w = []
# init registers r0..r31 via r16
for r in list(range(0, 16)) + list(range(17, 32)):
v = R.randrange(256); w.append(0xE000 | (v & 0xF0) << 4 | (0 << 4) | (v & 15)) # ldi r16, v
w.append(0x2C00 | (r & 16) << 5 | (r & 15) << 4 | 0 | (16 & 16) << 5 | (16 & 15)) # mov r, r16 (placeholder fixed below)
# fix movs: mov rd, r16: 0010 11rd dddd rrrr with r=16 -> r bit4 at bit9
out = []
for i in range(0, len(w), 2):
out.append(w[i]); r = (list(range(0, 16)) + list(range(17, 32)))[i // 2]
out.append(0x2C00 | 0x200 | ((r & 16) << 4) | ((r & 15) << 4) | 0)
v = R.randrange(256); out.append(0xE000 | (v & 0xF0) << 4 | (v & 15))
# SREG: random consistent (S = N^V), no I
s = R.randrange(128) & 0x6F; s |= (((s >> 2) ^ (s >> 3)) & 1) << 4
out.append(0xE010 | (s & 0xF0) << 4 | (s & 15)) # ldi r17, s
out.append(0xBF1F) # out SREG, r17
out.append(0xE0A0); out.append(0xE0B1) # X = 0x100
out.append(0xE0C8); out.append(0xE0D1) # Y = 0x108
out.append(0xE0E0 | 0); out.append(0xE0F1) # Z = 0x100 (r30=0? ldi r30,0)
body = []
n = 120
i = 0
depth = 0
while i < n:
d = R.randrange(32); r = R.randrange(32); K = R.randrange(256); d4 = R.randrange(16); b = R.randrange(8)
c = R.randrange(46)
def dr(op): return op | (r & 16) << 5 | d << 4 | (r & 15)
if c < 10: x = dr([0x0C00,0x1C00,0x1800,0x0800,0x2000,0x2800,0x2400,0x1400,0x0400,0x2C00][c])
elif c < 15: x = [0x5000,0x4000,0x7000,0x6000,0x3000][c-10] | (K & 0xF0) << 4 | d4 << 4 | (K & 15)
elif c < 23: x = 0x9400 | d << 4 | [0,1,2,3,5,6,7,10][c-15]
elif c == 23: x = 0x9C00 | (r & 16) << 5 | d << 4 | (r & 15)
elif c == 24: x = 0x0200 | d4 << 4 | R.randrange(16)
elif c == 25: x = 0x0300 | R.randrange(256) & 0xFF
elif c == 26: x = 0x9600 | R.randrange(256) & 0x3F | 0x00 # adiw r24
elif c == 27: x = 0x9700 | R.randrange(256) & 0x3F
elif c == 28: x = 0x0100 | R.randrange(256)
elif c == 29: x = 0xFA00 | d << 4 | b
elif c == 30: x = 0xF800 | d << 4 | b
elif c == 31: x = 0x9408 | [0,1,5,6][R.randrange(4)] << 4 | R.randrange(2) << 7
elif c in (32, 33): x = 0xF000 | R.randrange(2) << 10 | 1 << 3 | R.choice([0,1,2,3,4,6,7]) # branch .+1 (not on H)
elif c == 34: x = 0xFC00 | R.randrange(2) << 9 | d << 4 | b
elif c == 35: x = 0x1000 | (r & 16) << 5 | d << 4 | (r & 15)
elif c == 36: # ld/st through X, Y, Z (pointers kept in 0x100..0x13F)
if d >= 26: d = 16
x = [0x900C,0x900D,0x9009,0x9001,0x920C,0x920D,0x9209,0x9201,0x8000,0x8200][R.randrange(10)] | d << 4
elif c == 37: # ldd/std Y+q
if d >= 26: d = 17
q = R.randrange(8); x = (0x8008 | (R.randrange(2) << 9) | d << 4 | q)
elif c == 38:
if not depth: continue
if d >= 26: d = 18
x = 0x900F | d << 4; depth -= 1 # pop
elif c == 39: x = 0x920F | d << 4; depth += 1 # push
elif c == 40: x = 0x95C8 # lpm
elif c == 41: x = 0x9004 | d << 4 # lpm rd, Z
elif c == 42: # reset pointers into range
body += [0xE0A0 | R.randrange(16), 0xE0B1, 0xE0C0 | R.randrange(8), 0xE0D1, 0xE0E0 | R.randrange(16), 0xE0F1]; i += 6; continue
elif c == 43: x = 0x0000 # (in rd, SREG: H differs on purpose)
elif c == 44: x = 0x9000 | (d % 26) << 4; body += [0, x, 0x0100 + R.randrange(0x40)]; i += 3; continue # lds
else: x = 0x9200 | d << 4; body += [0, x, 0x0100 + R.randrange(0x40)]; i += 3; continue # sts
# keep the pointers sane: never write r26..r31 with ALU ops
if c < 36 and c not in (28,) and ((x >> 4) & 31) >= 26 and c not in (32, 33, 34, 35, 29, 31): x = 0
if c == 28 and ((x >> 4) & 15) * 2 >= 26: x = 0
if c in (26, 27): x = x & ~0x30 # adiw/sbiw r24 only
body.append(x); i += 1
# avoid skips landing in the middle of a 2-word instruction: put a nop after each 2-word one
fixed = []
for k, x in enumerate(body):
fixed.append(x)
if (x & 0xFE0F) in (0x9000, 0x9200) and k + 1 < len(body): pass
prog = out + fixed[:lim] + [0x0000, 0x0000, 0xCFFF]
return prog
def to_hex(prog, fn):
b = b''.join(struct.pack('<H', x & 0xFFFF) for x in prog)
with open(fn, 'w') as f:
for a in range(0, len(b), 16):
c = b[a:a+16]; s = len(c) + (a >> 8) + (a & 255) + sum(c)
f.write(':%02X%04X00%s%02X\n' % (len(c), a, c.hex().upper(), (-s) & 255))
f.write(':00000001FF\n')
open(fn + '.bin', 'wb').write(b)
if __name__ == '__main__':
to_hex(gen(int(sys.argv[1]), int(sys.argv[3]) if len(sys.argv) > 3 else 10**9), sys.argv[2])
+13 -13
View File
@@ -1,13 +1,13 @@
#include "../../src/core/avr.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static u16 fl[AVR_FLASH_WORDS];
int main(int argc, char **argv)
{
FILE *f = fopen(argv[1], "rb"); memset(fl, 0xFF, sizeof fl); size_t n = fread(fl, 1, sizeof fl, f); fclose(f);
ab_load(fl, (n + 1) / 2); ab_reset();
for (int ms = 0; ms < 30; ms++) ab_run(16000);
for (int i = 0; i < 96; i++) printf("%02x", A_D[i]); printf("\n");
for (int i = 0x100; i < 0x140; i++) printf("%02x", A_D[i]); printf("\n");
}
#include "../../src/core/avr.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static u16 fl[AVR_FLASH_WORDS];
int main(int argc, char **argv)
{
FILE *f = fopen(argv[1], "rb"); memset(fl, 0xFF, sizeof fl); size_t n = fread(fl, 1, sizeof fl, f); fclose(f);
ab_load(fl, (n + 1) / 2); ab_reset();
for (int ms = 0; ms < 30; ms++) ab_run(16000);
for (int i = 0; i < 96; i++) printf("%02x", A_D[i]); printf("\n");
for (int i = 0x100; i < 0x140; i++) printf("%02x", A_D[i]); printf("\n");
}
+10 -10
View File
@@ -1,10 +1,10 @@
#!/bin/bash
# setup: cp * /tmp/jf; cd /tmp/jf; gcc -O1 -o ref ref.c <studio>/ab/src/core/avr.c; cp <studio>/ab/ab.bin <studio>/ab/src/app/ab.elf /tmp/jf (KEEPELF=1 build)
# run.sh seed: compare host interpreter and the device JIT (Unicorn)
s=$1; d=/tmp/jf/w$s${2:+_$2}; mkdir -p $d; cd /tmp/jf
python3 gen.py $s $d/p.hex $2
./ref $d/p.hex.bin > $d/ref.txt
cd /home/claude/studio/ab/test
python3 mkimg.py /tmp/jf/ab.bin $d/p.hex $d/img.bin
OUT=$d DUMP="g_mem+256:96,g_mem+512:64" python3 devab.py /tmp/jf/ab.elf $d/img.bin 40 2>&1 | grep DUMP | awk '{print $3}' > $d/jit.txt
if python3 /tmp/jf/same.py $d; then echo "seed $s ok"; rm -rf $d; else echo "seed $s DIFF"; fi
#!/bin/bash
# setup: cp * /tmp/jf; cd /tmp/jf; gcc -O1 -o ref ref.c <studio>/ab/src/core/avr.c; cp <studio>/ab/ab.bin <studio>/ab/src/app/ab.elf /tmp/jf (KEEPELF=1 build)
# run.sh seed: compare host interpreter and the device JIT (Unicorn)
s=$1; d=/tmp/jf/w$s${2:+_$2}; mkdir -p $d; cd /tmp/jf
python3 gen.py $s $d/p.hex $2
./ref $d/p.hex.bin > $d/ref.txt
cd /home/claude/studio/ab/test
python3 mkimg.py /tmp/jf/ab.bin $d/p.hex $d/img.bin
OUT=$d DUMP="g_mem+256:96,g_mem+512:64" python3 devab.py /tmp/jf/ab.elf $d/img.bin 40 2>&1 | grep DUMP | awk '{print $3}' > $d/jit.txt
if python3 /tmp/jf/same.py $d; then echo "seed $s ok"; rm -rf $d; else echo "seed $s DIFF"; fi
+5 -5
View File
@@ -1,5 +1,5 @@
import sys
d=sys.argv[1]; r=open(d+'/ref.txt').read().split(); j=open(d+'/jit.txt').read().split()
if len(r)!=2 or len(j)!=2: sys.exit(1)
a=bytearray.fromhex(r[0]); b=bytearray.fromhex(j[0]); a[0x5f]&=0xDF; b[0x5f]&=0xDF
sys.exit(0 if a==b and r[1]==j[1] else 1)
import sys
d=sys.argv[1]; r=open(d+'/ref.txt').read().split(); j=open(d+'/jit.txt').read().split()
if len(r)!=2 or len(j)!=2: sys.exit(1)
a=bytearray.fromhex(r[0]); b=bytearray.fromhex(j[0]); a[0x5f]&=0xDF; b[0x5f]&=0xDF
sys.exit(0 if a==b and r[1]==j[1] else 1)
+52 -52
View File
@@ -1,52 +1,52 @@
/* lockstep against simavr on a game: gcc -O1 -DAB_SINGLE -o lock lock.c ../src/core/avr.c -lsimavr -lelf && ./lock game.hex steps
* (interrupts and I/O reads differ between the two: the simulator is followed there) */
/* lockstep: game hex in our core and simavr, instruction by instruction */
#include <simavr/sim_avr.h>
#include <simavr/sim_core.h>
#include <simavr/sim_hex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/core/avr.h"
extern u32 ab_pc(void); extern void ab_set_pc(u32); extern void ab_wake(void);
static u16 fl[AVR_FLASH_WORDS];
int main(int argc, char **argv)
{
uint32_t sz, base; uint8_t *code = read_ihex_file(argv[1], &sz, &base);
long steps = atol(argv[2]);
memset(fl, 0xFF, sizeof fl); memcpy(fl, code, sz);
avr_t *a = avr_make_mcu_by_name("atmega32u4"); a->frequency = 16000000; avr_init(a);
avr_loadcode(a, code, sz, base);
ab_load(fl, (sz + 1) / 2); ab_reset();
long syncs = 0, irqs = 0; unsigned lastpc = 0;
static char hist[64][160]; int hn = 0;
for (long st = 0; st < steps; st++) {
unsigned pc0 = a->pc / 2;
u16 w = fl[pc0];
unsigned spa = a->data[0x5D] | a->data[0x5E] << 8, spb = A_D[0x5D] | A_D[0x5E] << 8, ourpc = ab_pc();
avr_run(a);
ab_run(1);
snprintf(hist[hn++ & 63], 160, "st %ld pc %04x/%04x op %04x sp %04x/%04x r24 %02x/%02x -> %04x/%04x sreg %02x", st, pc0, ourpc, w, spa, spb, a->data[24], A_D[24], a->pc/2, ab_pc(), A_D[0x5F]);
unsigned p1 = a->pc / 2, p2 = ab_pc();
int isld = (w & 0xF800) == 0xB000 || (w & 0xFE0F) == 0x9000 || (w & 0xFC00) == 0x9000 || (w & 0xD200) == 0x8000;
if (p1 != p2) {
int skio = (w & 0xFD00) == 0x9900; if (p1 < 0x56 || p2 < 0x56 || skio || p1 == pc0 || p2 == pc0) { /* one took an interrupt: follow the simulator */
for (int i = 0; i < 32; i++) A_D[i] = a->data[i];
for (int i = 0x100; i < 0xB00; i++) A_D[i] = a->data[i];
A_D[0x5D] = a->data[0x5D]; A_D[0x5E] = a->data[0x5E];
{ unsigned s1 = 0; for (int i = 0; i < 8; i++) if (a->sreg[i]) s1 |= 1 << i; A_D[0x5F] = s1; }
ab_wake(); ab_set_pc(p1); A_CYC = (u32)a->cycle; irqs++; continue;
}
for (int k = 0; k < 40; k++) puts(hist[(hn + 24 + k) & 63]);
printf("step %ld: pc sim %04x ours %04x (from %04x op %04x) cyc sim %llu ours %u\n", st, p1, p2, pc0, w, (unsigned long long)a->cycle, A_CYC); break; }
for (int i = 0; i < 32; i++) if (a->data[i] != A_D[i]) {
if (isld) { A_D[i] = a->data[i]; syncs++; }
else { for (int k = 0; k < 40; k++) puts(hist[(hn + 24 + k) & 63]); printf("step %ld pc %04x op %04x: r%d sim %02x ours %02x\n", st, pc0, w, i, a->data[i], A_D[i]); st = steps; break; }
}
if (0 && a->cycle != A_CYC) { printf("cycles step %ld pc %04x op %04x sim %llu ours %u\n", st, pc0, w, (unsigned long long)a->cycle, A_CYC); break; }
if (0) { for (int k = 0; k < 40; k++) puts(hist[(hn + 24 + k) & 63]); printf("SP differs at step %ld\n", st); break; }
lastpc = pc0;
}
printf("irqs %ld syncs %ld cyc sim %llu ours %u\n", irqs, syncs, (unsigned long long)a->cycle, A_CYC);
return 0;
}
/* lockstep against simavr on a game: gcc -O1 -DAB_SINGLE -o lock lock.c ../src/core/avr.c -lsimavr -lelf && ./lock game.hex steps
* (interrupts and I/O reads differ between the two: the simulator is followed there) */
/* lockstep: game hex in our core and simavr, instruction by instruction */
#include <simavr/sim_avr.h>
#include <simavr/sim_core.h>
#include <simavr/sim_hex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/core/avr.h"
extern u32 ab_pc(void); extern void ab_set_pc(u32); extern void ab_wake(void);
static u16 fl[AVR_FLASH_WORDS];
int main(int argc, char **argv)
{
uint32_t sz, base; uint8_t *code = read_ihex_file(argv[1], &sz, &base);
long steps = atol(argv[2]);
memset(fl, 0xFF, sizeof fl); memcpy(fl, code, sz);
avr_t *a = avr_make_mcu_by_name("atmega32u4"); a->frequency = 16000000; avr_init(a);
avr_loadcode(a, code, sz, base);
ab_load(fl, (sz + 1) / 2); ab_reset();
long syncs = 0, irqs = 0; unsigned lastpc = 0;
static char hist[64][160]; int hn = 0;
for (long st = 0; st < steps; st++) {
unsigned pc0 = a->pc / 2;
u16 w = fl[pc0];
unsigned spa = a->data[0x5D] | a->data[0x5E] << 8, spb = A_D[0x5D] | A_D[0x5E] << 8, ourpc = ab_pc();
avr_run(a);
ab_run(1);
snprintf(hist[hn++ & 63], 160, "st %ld pc %04x/%04x op %04x sp %04x/%04x r24 %02x/%02x -> %04x/%04x sreg %02x", st, pc0, ourpc, w, spa, spb, a->data[24], A_D[24], a->pc/2, ab_pc(), A_D[0x5F]);
unsigned p1 = a->pc / 2, p2 = ab_pc();
int isld = (w & 0xF800) == 0xB000 || (w & 0xFE0F) == 0x9000 || (w & 0xFC00) == 0x9000 || (w & 0xD200) == 0x8000;
if (p1 != p2) {
int skio = (w & 0xFD00) == 0x9900; if (p1 < 0x56 || p2 < 0x56 || skio || p1 == pc0 || p2 == pc0) { /* one took an interrupt: follow the simulator */
for (int i = 0; i < 32; i++) A_D[i] = a->data[i];
for (int i = 0x100; i < 0xB00; i++) A_D[i] = a->data[i];
A_D[0x5D] = a->data[0x5D]; A_D[0x5E] = a->data[0x5E];
{ unsigned s1 = 0; for (int i = 0; i < 8; i++) if (a->sreg[i]) s1 |= 1 << i; A_D[0x5F] = s1; }
ab_wake(); ab_set_pc(p1); A_CYC = (u32)a->cycle; irqs++; continue;
}
for (int k = 0; k < 40; k++) puts(hist[(hn + 24 + k) & 63]);
printf("step %ld: pc sim %04x ours %04x (from %04x op %04x) cyc sim %llu ours %u\n", st, p1, p2, pc0, w, (unsigned long long)a->cycle, A_CYC); break; }
for (int i = 0; i < 32; i++) if (a->data[i] != A_D[i]) {
if (isld) { A_D[i] = a->data[i]; syncs++; }
else { for (int k = 0; k < 40; k++) puts(hist[(hn + 24 + k) & 63]); printf("step %ld pc %04x op %04x: r%d sim %02x ours %02x\n", st, pc0, w, i, a->data[i], A_D[i]); st = steps; break; }
}
if (0 && a->cycle != A_CYC) { printf("cycles step %ld pc %04x op %04x sim %llu ours %u\n", st, pc0, w, (unsigned long long)a->cycle, A_CYC); break; }
if (0) { for (int k = 0; k < 40; k++) puts(hist[(hn + 24 + k) & 63]); printf("SP differs at step %ld\n", st); break; }
lastpc = pc0;
}
printf("irqs %ld syncs %ld cyc sim %llu ours %u\n", irqs, syncs, (unsigned long long)a->cycle, A_CYC);
return 0;
}
+25 -25
View File
@@ -1,25 +1,25 @@
# test image: ab.bin at 0xA0000 with its settings block, the game at 0x200000, the saves at 0x300000 (16 KB)
# python3 mkimg.py ab.bin game.hex out.bin [flags]
import sys, struct
app, hexf, out = sys.argv[1], sys.argv[2], sys.argv[3]
def hex2bin(fn):
b = bytearray(b'\xff' * 0x8000); top = 0; hi = 0
for l in open(fn):
l = l.strip()
if not l.startswith(':'): continue
n, ad, ty = int(l[1:3], 16), int(l[3:7], 16), int(l[7:9], 16)
if ty == 0:
for i in range(n):
a = hi + ad + i
if a < len(b): b[a] = int(l[9 + 2 * i:11 + 2 * i], 16); top = max(top, a + 1)
elif ty == 2: hi = int(l[9:13], 16) << 4
elif ty == 4: hi = int(l[9:13], 16) << 16
return bytes(b[:top + (top & 1)])
fl = bytearray(b'\xff' * 0x400000)
a = open(app, 'rb').read(); r = hex2bin(hexf)
fl[0xA0000:0xA0000 + len(a)] = a; fl[0x200000:0x200000 + len(r)] = r
flags = int(sys.argv[4]) if len(sys.argv) > 4 else 0
c = 0xA0000 + 0x140
struct.pack_into('<6I16s', fl, c, 0x50584241, 1, 0x200000, len(r), 0x300000, flags, b'ARDUBOY')
struct.pack_into('<12B', fl, c + 40, 4, 32, 8, 16, 1, 2, 0, 0, 0, 0, 0, 0)
open(out, 'wb').write(fl)
# test image: ab.bin at 0xA0000 with its settings block, the game at 0x200000, the saves at 0x300000 (16 KB)
# python3 mkimg.py ab.bin game.hex out.bin [flags]
import sys, struct
app, hexf, out = sys.argv[1], sys.argv[2], sys.argv[3]
def hex2bin(fn):
b = bytearray(b'\xff' * 0x8000); top = 0; hi = 0
for l in open(fn):
l = l.strip()
if not l.startswith(':'): continue
n, ad, ty = int(l[1:3], 16), int(l[3:7], 16), int(l[7:9], 16)
if ty == 0:
for i in range(n):
a = hi + ad + i
if a < len(b): b[a] = int(l[9 + 2 * i:11 + 2 * i], 16); top = max(top, a + 1)
elif ty == 2: hi = int(l[9:13], 16) << 4
elif ty == 4: hi = int(l[9:13], 16) << 16
return bytes(b[:top + (top & 1)])
fl = bytearray(b'\xff' * 0x400000)
a = open(app, 'rb').read(); r = hex2bin(hexf)
fl[0xA0000:0xA0000 + len(a)] = a; fl[0x200000:0x200000 + len(r)] = r
flags = int(sys.argv[4]) if len(sys.argv) > 4 else 0
c = 0xA0000 + 0x140
struct.pack_into('<6I16s', fl, c, 0x50584241, 1, 0x200000, len(r), 0x300000, flags, b'ARDUBOY')
struct.pack_into('<12B', fl, c + 40, 4, 32, 8, 16, 1, 2, 0, 0, 0, 0, 0, 0)
open(out, 'wb').write(fl)
+19 -19
View File
@@ -1,19 +1,19 @@
# count instructions per function (PROF=1 in devgb): exec devgb with a block hook
import os, sys, subprocess, bisect, collections
elf = sys.argv[1]
fs = []
for l in subprocess.run(['llvm-nm', '-S', '--size-sort', elf], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 4 and p[2] in 'tT': fs.append((int(p[0], 16) & ~1, int(p[1], 16), p[3]))
fs.sort(); starts = [f[0] for f in fs]
cnt = collections.Counter()
def blk(uc, addr, size, ud):
i = bisect.bisect_right(starts, addr) - 1
if i >= 0 and addr < fs[i][0] + fs[i][1]: cnt[fs[i][2]] += size // 2
else: cnt['?'] += size // 2
import builtins
builtins.__gbprof = (blk, cnt)
exec(open(os.path.join(os.path.dirname(__file__), 'devab.py')).read())
tot = sum(cnt.values())
for n, c in cnt.most_common(25): print('%6.2f%% %s' % (100 * c / tot, n))
# count instructions per function (PROF=1 in devgb): exec devgb with a block hook
import os, sys, subprocess, bisect, collections
elf = sys.argv[1]
fs = []
for l in subprocess.run(['llvm-nm', '-S', '--size-sort', elf], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 4 and p[2] in 'tT': fs.append((int(p[0], 16) & ~1, int(p[1], 16), p[3]))
fs.sort(); starts = [f[0] for f in fs]
cnt = collections.Counter()
def blk(uc, addr, size, ud):
i = bisect.bisect_right(starts, addr) - 1
if i >= 0 and addr < fs[i][0] + fs[i][1]: cnt[fs[i][2]] += size // 2
else: cnt['?'] += size // 2
import builtins
builtins.__gbprof = (blk, cnt)
exec(open(os.path.join(os.path.dirname(__file__), 'devab.py')).read())
tot = sum(cnt.values())
for n, c in cnt.most_common(25): print('%6.2f%% %s' % (100 * c / tot, n))
+15 -15
View File
@@ -1,15 +1,15 @@
# where the time goes in the translated code: dispatcher stub vs blocks (python3 profj.py elf img ms)
import os, sys, subprocess, collections, builtins
elf = sys.argv[1]
syms0 = {}
for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 3: syms0[p[2]] = int(p[0], 16)
cb = syms0['g_code']; cnt = collections.Counter(); tot = [0]
def blk(uc, addr, size, ud):
n = size // 2; tot[0] += n
if cb <= addr < cb + 0x10000: cnt['stub' if addr - cb < 0x50 else 'block'] += n
else: cnt['C'] += n
builtins.__gbprof = (blk, cnt)
exec(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'devab.py')).read())
for k, v in cnt.most_common(): print('%6.2f%% %s' % (100 * v / tot[0], k))
# where the time goes in the translated code: dispatcher stub vs blocks (python3 profj.py elf img ms)
import os, sys, subprocess, collections, builtins
elf = sys.argv[1]
syms0 = {}
for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 3: syms0[p[2]] = int(p[0], 16)
cb = syms0['g_code']; cnt = collections.Counter(); tot = [0]
def blk(uc, addr, size, ud):
n = size // 2; tot[0] += n
if cb <= addr < cb + 0x10000: cnt['stub' if addr - cb < 0x50 else 'block'] += n
else: cnt['C'] += n
builtins.__gbprof = (blk, cnt)
exec(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'devab.py')).read())
for k, v in cnt.most_common(): print('%6.2f%% %s' % (100 * v / tot[0], k))
+23 -23
View File
@@ -1,23 +1,23 @@
# instructions per source line (needs an ELF with -g): python3 profl.py elf img ms
import os, sys, subprocess, collections
elf = sys.argv[1]
cnt = collections.Counter()
def blk(uc, addr, size, ud): cnt[addr] += size // 2
import builtins
builtins.__gbprof = (blk, cnt)
exec(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'devab.py')).read())
# expand blocks to instruction addresses roughly: attribute the block to its first address
addrs = sorted(cnt)
out = subprocess.run(['llvm-addr2line', '-e', elf, '-f'] + [hex(a) for a in addrs], capture_output=True, text=True).stdout.splitlines()
# llvm-addr2line with -i prints inline chains; take the first file:line per address
res = collections.Counter(); i = 0; k = 0
lines = out
mp = {}
cur = 0
j = 0
for a in addrs:
fn = lines[j]; loc = lines[j + 1]; j += 2
while j < len(lines) and not lines[j].startswith('0x') and j + 1 < len(lines) and ':' in lines[j + 1] and not lines[j].startswith('/') and lines[j] != '??' and False: j += 2
res[(fn, loc.split('/')[-1])] += cnt[a]
tot = sum(res.values())
for (fn, loc), c in res.most_common(40): print('%6.2f%% %s %s' % (100 * c / tot, fn, loc))
# instructions per source line (needs an ELF with -g): python3 profl.py elf img ms
import os, sys, subprocess, collections
elf = sys.argv[1]
cnt = collections.Counter()
def blk(uc, addr, size, ud): cnt[addr] += size // 2
import builtins
builtins.__gbprof = (blk, cnt)
exec(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'devab.py')).read())
# expand blocks to instruction addresses roughly: attribute the block to its first address
addrs = sorted(cnt)
out = subprocess.run(['llvm-addr2line', '-e', elf, '-f'] + [hex(a) for a in addrs], capture_output=True, text=True).stdout.splitlines()
# llvm-addr2line with -i prints inline chains; take the first file:line per address
res = collections.Counter(); i = 0; k = 0
lines = out
mp = {}
cur = 0
j = 0
for a in addrs:
fn = lines[j]; loc = lines[j + 1]; j += 2
while j < len(lines) and not lines[j].startswith('0x') and j + 1 < len(lines) and ':' in lines[j + 1] and not lines[j].startswith('/') and lines[j] != '??' and False: j += 2
res[(fn, loc.split('/')[-1])] += cnt[a]
tot = sum(res.values())
for (fn, loc), c in res.most_common(40): print('%6.2f%% %s %s' % (100 * c / tot, fn, loc))