다마고치 연구소 한국어판 소스 공개
Paramix Studio / build (push) Canceled after 0s
Paramix Studio / pages (push) Canceled after 0s

This commit is contained in:
syskiller committed 2026-11-10 21:17:44 +09:00
commit db23855630
661 files changed
+503597

No files matched your search

+52
View File
@@ -0,0 +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.
BIN
View File
Binary file not shown.
+19
View File
@@ -0,0 +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
+99
View File
@@ -0,0 +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},
};
+23
View File
@@ -0,0 +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*) }
}
+470
View File
@@ -0,0 +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 };
+926
View File
@@ -0,0 +1,926 @@
/* ArduboyEmu: ATmega32U4 core and the Arduboy's hardware (see avr.h). Author: mameise. License: GPL-3.0-or-later. */
#include "avr.h"
#include <stdint.h>
#ifndef AVR_FAST
#define AVR_FAST __attribute__((optimize("O2")))
#endif
AbMem g_mem __attribute__((aligned(8)));
u8 A_EEP[AVR_EEP] __attribute__((aligned(4)));
u8 A_GD[1024] __attribute__((aligned(4)));
#if !AB_JIT
u32 A_OP[AVR_FLASH_WORDS + 4]; /* behind the end: O_BAD, which wraps the pc */
#endif
const u16 *A_FLASH;
static u32 g_words;
u32 A_CYC, A_KEYS, A_FRAMES;
int A_EEP_DIRTY;
AvrLcd A_LCD;
#ifdef AB_COUNT
u32 A_INS, A_OPC[96], A_PCH[16384];
#endif
/* ------------------------------------------------------------------ decoding
* One u32 per program word: the handler (low 16 bits: its index, or on the Paradise its address in PRAM) and the
* operands in the high 16 bits (f = o >> 16):
* two registers: d | r << 5 (CPSE: | skip of a two-word instruction << 10); register and byte: d | K << 8;
* jumps and branches: the target word; SBRC/SBRS/BLD/BST: d | skip2 << 5 | bit mask << 8;
* SBI/CBI/SBIC/SBIS: bit mask | (I/O address - 0x20) << 8 | skip2 << 13; LDS/STS: d, the address in the next slot. */
enum {
O_NOP, O_MOVW, O_MULS, O_MULSU, O_FMUL, O_FMULS, O_FMULSU, O_CPC, O_SBC, O_ADD, O_CPSE, O_CP, O_SUB, O_ADC, O_AND,
O_EOR, O_OR, O_MOV, O_CPI, O_SBCI, O_SUBI, O_ORI, O_ANDI, O_LDDY, O_LDDZ, O_STDY, O_STDZ, O_LDS, O_LDZP, O_LDMZ,
O_LPMZ, O_LPMZP, O_LDYP, O_LDMY, O_LDX, O_LDXP, O_LDMX, O_POP, O_STS, O_STZP, O_STMZ, O_STYP, O_STMY, O_STX, O_STXP,
O_STMX, O_PUSH, O_COM, O_NEG, O_SWAP, O_INC, O_ASR, O_LSR, O_ROR, O_DEC, O_BSET, O_BCLR, O_RET, O_RETI, O_SLEEP,
O_WDR, O_LPM0, O_IJMP, O_ICALL, O_JMP, O_CALL, O_ADIW, O_SBIW, O_CBI, O_SBIC, O_SBI, O_SBIS, O_MUL, O_IN, O_OUT,
O_RJMP, O_RCALL, O_LDI, O_BLD, O_BST, O_SBRC, O_SBRS, O_INSREG, O_OUTSREG,
O_BREQ, O_BRNE, O_BRCS, O_BRCC, O_BRMI, O_BRPL, O_BRVS, O_BRVC, O_BRLT, O_BRGE, O_BRHS, O_BRHC, O_BRTS, O_BRTC,
O_BRIE, O_BRID, O_BAD, O_N
};
static int two_words(u32 w) { return (w & 0xFE0Fu) == 0x9000u || (w & 0xFE0Fu) == 0x9200u || (w & 0xFE0Cu) == 0x940Cu; }
#define F(op, f) ((u32)(op) | ((u32)(f) << 16))
static u32 decode(u32 pc)
{
u32 w = A_FLASH[pc], w2 = pc + 1 < AVR_FLASH_WORDS ? A_FLASH[pc + 1] : 0, sk2 = pc + 1 < AVR_FLASH_WORDS && two_words(w2);
u32 d5 = (w >> 4) & 31u, r5 = (w & 15u) | ((w >> 5) & 16u), d4 = 16u + ((w >> 4) & 15u), K8 = ((w >> 4) & 0xF0u) | (w & 15u);
#define DR(op, d, r) F(op, (d) | (r) << 5)
#define DK(op, d, k) F(op, (d) | (k) << 8)
switch (w >> 12) {
case 0x0:
if (w == 0) return O_NOP;
switch ((w >> 10) & 3u) {
case 0:
if ((w & 0xFF00u) == 0x0100u) return DR(O_MOVW, ((w >> 4) & 15u) * 2u, (w & 15u) * 2u);
if ((w & 0xFF00u) == 0x0200u) return DR(O_MULS, d4, 16u + (w & 15u));
if ((w & 0xFF00u) == 0x0300u) {
u32 d = 16u + ((w >> 4) & 7u), r = 16u + (w & 7u);
switch (w & 0x88u) { case 0x00: return DR(O_MULSU, d, r); case 0x08: return DR(O_FMUL, d, r); case 0x80: return DR(O_FMULS, d, r); default: return DR(O_FMULSU, d, r); }
}
return O_BAD;
case 1: return DR(O_CPC, d5, r5);
case 2: return DR(O_SBC, d5, r5);
default: return DR(O_ADD, d5, r5);
}
case 0x1:
switch ((w >> 10) & 3u) { case 0: return DR(O_CPSE, d5, r5) | sk2 << 26; case 1: return DR(O_CP, d5, r5); case 2: return DR(O_SUB, d5, r5); default: return DR(O_ADC, d5, r5); }
case 0x2:
switch ((w >> 10) & 3u) { case 0: return DR(O_AND, d5, r5); case 1: return DR(O_EOR, d5, r5); case 2: return DR(O_OR, d5, r5); default: return DR(O_MOV, d5, r5); }
case 0x3: return DK(O_CPI, d4, K8);
case 0x4: return DK(O_SBCI, d4, K8);
case 0x5: return DK(O_SUBI, d4, K8);
case 0x6: return DK(O_ORI, d4, K8);
case 0x7: return DK(O_ANDI, d4, K8);
case 0x8: case 0xA: {
u32 q = (w & 7u) | ((w >> 7) & 0x18u) | ((w >> 8) & 0x20u), st = (w >> 9) & 1u, y = (w >> 3) & 1u;
return DK(st ? (y ? O_STDY : O_STDZ) : (y ? O_LDDY : O_LDDZ), d5, q);
}
case 0x9:
switch ((w >> 9) & 7u) {
case 0: /* 1001 000d */
switch (w & 15u) {
case 0: return F(O_LDS, d5);
case 1: return F(O_LDZP, d5); case 2: return F(O_LDMZ, d5);
case 4: case 6: return F(O_LPMZ, d5); case 5: case 7: return F(O_LPMZP, d5);
case 9: return F(O_LDYP, d5); case 10: return F(O_LDMY, d5);
case 12: return F(O_LDX, d5); case 13: return F(O_LDXP, d5); case 14: return F(O_LDMX, d5);
case 15: return F(O_POP, d5);
default: return O_BAD;
}
case 1:
switch (w & 15u) {
case 0: return F(O_STS, d5);
case 1: return F(O_STZP, d5); case 2: return F(O_STMZ, d5);
case 9: return F(O_STYP, d5); case 10: return F(O_STMY, d5);
case 12: return F(O_STX, d5); case 13: return F(O_STXP, d5); case 14: return F(O_STMX, d5);
case 15: return F(O_PUSH, d5);
default: return O_BAD;
}
case 2: /* 1001 010x */
switch (w & 15u) {
case 0: return F(O_COM, d5); case 1: return F(O_NEG, d5); case 2: return F(O_SWAP, d5);
case 3: return F(O_INC, d5); case 5: return F(O_ASR, d5); case 6: return F(O_LSR, d5);
case 7: return F(O_ROR, d5); case 10: return F(O_DEC, d5);
case 12: case 13: case 14: case 15: {
u32 k = ((((w >> 4) & 31u) << 1 | (w & 1u)) << 16 | w2) & 0x3FFFu;
return F((w & 2u) ? O_CALL : O_JMP, k);
}
case 8:
if ((w & 0xFF0Fu) == 0x9408u) return F((w & 0x80u) ? O_BCLR : O_BSET, 1u << ((w >> 4) & 7u));
switch (w) {
case 0x9508: return O_RET; case 0x9518: return O_RETI; case 0x9588: return O_SLEEP; case 0x9598: return O_NOP;
case 0x95A8: return O_WDR; case 0x95C8: case 0x95D8: return O_LPM0; case 0x95E8: case 0x95F8: return O_NOP;
}
return O_BAD;
case 9:
if (w == 0x9409u || w == 0x9419u) return O_IJMP;
if (w == 0x9509u || w == 0x9519u) return O_ICALL;
return O_BAD;
default: return O_BAD;
}
case 3:
return DK((w & 0x0100u) ? O_SBIW : O_ADIW, 24u + ((w >> 3) & 6u), ((w >> 2) & 0x30u) | (w & 15u));
case 4: case 5: {
u32 a = (w >> 3) & 31u, m = 1u << (w & 7u), set = (w >> 9) & 1u, sk = (w >> 8) & 1u;
return F(set ? (sk ? O_SBIS : O_SBI) : (sk ? O_SBIC : O_CBI), m | a << 8 | sk2 << 13);
}
default: return DR(O_MUL, d5, r5);
}
case 0xB: {
u32 a = 0x20u + ((w & 15u) | ((w >> 5) & 0x30u));
if (a == 0x5Fu) return F((w & 0x0800u) ? O_OUTSREG : O_INSREG, d5);
return DK((w & 0x0800u) ? O_OUT : O_IN, d5, a);
}
case 0xC: { s32 k = (s32)(w << 20) >> 20; return F(O_RJMP, (pc + 1 + (u32)k) & 0x3FFFu); }
case 0xD: { s32 k = (s32)(w << 20) >> 20; return F(O_RCALL, (pc + 1 + (u32)k) & 0x3FFFu); }
case 0xE: return DK(O_LDI, d4, K8);
default: {
if ((w & 0x0800u) == 0) { /* BRBS / BRBC: one handler per flag and sense */
s32 k = (s32)(w << 22) >> 25; u32 t = (pc + 1 + (u32)k) & 0x3FFFu, b = w & 7u, clr = (w >> 10) & 1u;
static const u8 BR[8] = { O_BRCS, O_BREQ, O_BRMI, O_BRVS, O_BRLT, O_BRHS, O_BRTS, O_BRIE };
return F(BR[b] + clr, t);
}
u32 m = 1u << (w & 7u);
switch ((w >> 9) & 3u) {
case 0: return DK(O_BLD, d5, m);
case 1: return DK(O_BST, d5, m);
case 2: return DK(O_SBRC, d5 | sk2 << 5, m);
default: return DK(O_SBRS, d5 | sk2 << 5, m);
}
}
}
}
/* ------------------------------------------------------------------ I/O registers (data addresses) */
#define PINB 0x23
#define DDRB 0x24
#define PORTB 0x25
#define PINC 0x26
#define DDRC 0x27
#define PORTC 0x28
#define PIND 0x29
#define DDRD 0x2A
#define PORTD 0x2B
#define PINE 0x2C
#define DDRE 0x2D
#define PORTE 0x2E
#define PINF 0x2F
#define DDRF 0x30
#define PORTF 0x31
#define TIFR0 0x35
#define TIFR1 0x36
#define TIFR3 0x38
#define TIFR4 0x39
#define EECR 0x3F
#define EEDR 0x40
#define EEARL 0x41
#define EEARH 0x42
#define TCCR0A 0x44
#define TCCR0B 0x45
#define TCNT0 0x46
#define OCR0A 0x47
#define OCR0B 0x48
#define PLLCSR 0x49
#define SPCR 0x4C
#define SPSR 0x4D
#define SPDR 0x4E
#define SMCR 0x53
#define MCUSR 0x54
#define SPL 0x5D
#define SPH 0x5E
#define SREG 0x5F
#define WDTCSR 0x60
#define TIMSK0 0x6E
#define TIMSK1 0x6F
#define TIMSK3 0x71
#define TIMSK4 0x72
#define ADCL 0x78
#define ADCH 0x79
#define ADCSRA 0x7A
#define TCCR1A 0x80
#define TCCR3A 0x90
#define TCNT4 0xBE
#define TC4H 0xBF
#define TCCR4A 0xC0
#define TCCR4B 0xC1
#define TCCR4C 0xC2
#define TCCR4D 0xC3
#define OCR4A 0xCF
#define OCR4B 0xD0
#define OCR4C 0xD1
#define OCR4D 0xD2
#define PLLFRQ 0x52
#define I_FLAG 0x80u
/* ------------------------------------------------------------------ timers
* The counter is a position ph in one period P (up: P = top + 1, count = ph; both ways: P = 2 top, count goes up then
* down). Kept at cycle `base`; brought up to date (flags set) when read or changed and at each event. */
typedef struct {
u32 base, ph, P, top, sh, mul, dual, tov_ok, temp, ocr[4];
u8 tifr, timsk, t16;
} Tm;
static Tm g_t[4]; /* timer 0, 1, 3, 4 */
/* AB_EVC: each timer's next event (cycle) is kept until something changes it (I/O write, flag change, interrupt);
* only a timer whose event came is brought up to date (at the latest every 4M cycles) */
#ifndef AB_EVC
#define AB_EVC 1
#endif
static u32 g_tat[4], g_tv; /* g_tv bit i: g_tat[i] holds */
static const u8 T_TIFR[4] = { TIFR0, TIFR1, TIFR3, TIFR4 }, T_TIMSK[4] = { TIMSK0, TIMSK1, TIMSK3, TIMSK4 };
/* flag bits of the compare channels and overflow */
static const u8 T_FB[4][4] = { { 2, 4, 0, 0 }, { 2, 4, 8, 0 }, { 2, 4, 8, 0 }, { 0x40, 0x20, 0x80, 0 } };
static const u8 T_TOV[4] = { 1, 1, 1, 4 };
#define STOP 255u
static u32 tm_count(const Tm *t) { return t->dual && t->ph > t->top ? t->P - t->ph : t->ph; }
static u32 tm_dist(const Tm *t, u32 e) { return (e + t->P - t->ph - 1u) % t->P + 1u; } /* ticks until position e */
static void tm_flags(Tm *t, u32 n, u8 *fl)
{
if (!n) return;
u32 f = 0;
for (int c = 0; c < 3; c++) {
u32 v = t->ocr[c], b = T_FB[t - g_t][c];
if (!b || v > t->top) continue;
if (tm_dist(t, v) <= n) f |= b;
else if (t->dual && v && v < t->top && tm_dist(t, t->P - v) <= n) f |= b;
}
if (t->tov_ok && tm_dist(t, 0) <= n) f |= T_TOV[t - g_t];
*fl |= (u8)f;
}
static void tm_sync(int i)
{
Tm *t = &g_t[i];
if (t->sh == STOP) { t->base = A_CYC; return; }
u32 el = A_CYC - t->base, n = (el * t->mul) >> t->sh;
if (!n) return;
t->base += t->mul == 1u ? n << t->sh : ((n << t->sh) + t->mul - 1u) / t->mul;
{ u8 *fl = &A_D[T_TIFR[i]]; u32 o = *fl; tm_flags(t, n, fl); if (*fl != o) g_tv &= ~(1u << i); }
t->ph = (t->ph + n % t->P) % t->P;
}
/* cycles until the next flag that would start an interrupt (0xFFFFFFFF: none) */
static u32 tm_next(int i)
{
Tm *t = &g_t[i];
u32 m = A_D[T_TIMSK[i]] & ~A_D[T_TIFR[i]];
if (t->sh == STOP || !m) return 0xFFFFFFFFu;
u32 best = 0xFFFFFFFFu;
for (int c = 0; c < 3; c++) {
u32 v = t->ocr[c], b = T_FB[i][c];
if (!(m & b) || v > t->top) continue;
u32 dd = tm_dist(t, v); if (dd < best) best = dd;
if (t->dual && v && v < t->top) { dd = tm_dist(t, t->P - v); if (dd < best) best = dd; }
}
if ((m & T_TOV[i]) && t->tov_ok) { u32 dd = tm_dist(t, 0); if (dd < best) best = dd; }
if (best == 0xFFFFFFFFu) return best;
/* cycles: the tick `best` comes at base + best * 2^sh / mul */
u32 at = t->base + (t->mul == 1u ? best << t->sh : ((best << t->sh) + t->mul - 1u) / t->mul);
u32 d = at - A_CYC;
return (s32)d < 0 ? 0u : d; /* already due (the clock moved on since the last sync) */
}
static const u8 PS0[8] = { STOP, 0, 3, 6, 8, 10, STOP, STOP };
static void tm_cfg(int i)
{
Tm *t = &g_t[i]; u32 cnt = tm_count(t), wgm, top = 0xFF, dual = 0, tov = 1;
t->mul = 1;
if (i == 0) {
wgm = (A_D[TCCR0A] & 3u) | ((A_D[TCCR0B] >> 1) & 4u); t->sh = PS0[A_D[TCCR0B] & 7u];
switch (wgm) { case 1: dual = 1; break; case 2: top = t->ocr[0]; tov = top == 0xFF; break; case 5: dual = 1; top = t->ocr[0]; break; case 7: top = t->ocr[0]; break; }
} else if (i < 3) {
u32 a = i == 1 ? TCCR1A : TCCR3A;
wgm = (A_D[a] & 3u) | ((A_D[a + 1] >> 1) & 12u); t->sh = PS0[A_D[a + 1] & 7u];
static const u16 TOPS[16] = { 0xFFFF, 0xFF, 0x1FF, 0x3FF, 0, 0xFF, 0x1FF, 0x3FF, 1, 0, 1, 0, 1, 0xFFFF, 1, 0 };
top = TOPS[wgm]; if (!top) top = t->ocr[0]; else if (top == 1) top = t->ocr[3]; /* 0: OCRnA, 1: ICRn */
dual = (wgm >= 1 && wgm <= 3) || (wgm >= 8 && wgm <= 11);
tov = wgm == 0 || (wgm >= 5 && wgm <= 7) || wgm >= 14 || dual || top == 0xFFFF;
} else {
u32 cs = A_D[TCCR4B] & 15u; t->sh = cs ? cs - 1u : STOP;
u32 tm = (A_D[PLLFRQ] >> 4) & 3u; static const u8 MUL[4] = { 1, 6, 4, 3 }; /* PLL 96 MHz /1, /1.5, /2 */
if (tm && (A_D[PLLCSR] & 2u)) { t->mul = MUL[tm]; if (tm == 2) t->mul = 4; }
top = t->ocr[3] ? t->ocr[3] : 0x3FF; dual = (A_D[TCCR4D] & 3u) == 1u;
}
if (top == 0) top = 1;
t->top = top; t->dual = dual; t->tov_ok = tov; t->P = dual ? 2u * top : top + 1u;
t->ph = cnt % t->P;
}
/* ------------------------------------------------------------------ display (SSD1306) */
static u32 g_col, g_page, g_c0 = 0, g_c1 = 127, g_p0 = 0, g_p1 = 7, g_amode = 2, g_cmd_n, g_cmd[8];
static u32 lcd_args(u32 c)
{
switch (c) {
case 0x81: case 0x20: case 0xA8: case 0xD3: case 0xD5: case 0xD9: case 0xDA: case 0xDB: case 0x8D: return 1;
case 0x21: case 0x22: case 0xA3: return 2;
case 0x26: case 0x27: return 6;
case 0x29: case 0x2A: return 5;
default: return 0;
}
}
#ifdef AB_TRACE
#include <stdio.h>
#endif
/* boot: as the Arduboy's boot loader leaves the display (on, rows across); rst: the display's own reset (pin PD7) */
static void lcd_reset(int boot)
{
A_LCD.on = (u8)boot; A_LCD.invert = 0; A_LCD.contrast = boot ? 0xCF : 0x7F; A_LCD.flip_x = (u8)boot; A_LCD.flip_y = (u8)boot; A_LCD.allon = 0; A_LCD.start = 0;
g_col = g_page = 0; g_c0 = 0; g_c1 = 127; g_p0 = 0; g_p1 = 7; g_amode = boot ? 0 : 2; g_cmd_n = 0;
}
static void lcd_cmd(u32 c)
{
#ifdef AB_TRACE
printf("cmd %02x\n", c);
#endif
if (g_cmd_n) {
g_cmd[g_cmd_n++] = c;
if (g_cmd_n <= lcd_args(g_cmd[0])) return;
switch (g_cmd[0]) {
case 0x81: A_LCD.contrast = (u8)g_cmd[1]; break;
case 0x20: g_amode = g_cmd[1] & 3u; break;
case 0x21: g_c0 = g_cmd[1] & 127u; g_c1 = g_cmd[2] & 127u; g_col = g_c0; break;
case 0x22: g_p0 = g_cmd[1] & 7u; g_p1 = g_cmd[2] & 7u; g_page = g_p0; break;
}
g_cmd_n = 0; return;
}
if (lcd_args(c)) { g_cmd[0] = c; g_cmd_n = 1; return; }
if (c <= 0x0F) { g_col = (g_col & 0xF0u) | c; return; }
if (c <= 0x1F) { g_col = (g_col & 0x0Fu) | ((c & 7u) << 4); return; }
if (c >= 0x40 && c <= 0x7F) { A_LCD.start = (u8)(c & 63u); return; }
if (c >= 0xB0 && c <= 0xB7) { g_page = c & 7u; return; }
switch (c) {
case 0xAE: A_LCD.on = 0; break; case 0xAF: A_LCD.on = 1; break;
case 0xA6: A_LCD.invert = 0; break; case 0xA7: A_LCD.invert = 1; break;
case 0xA4: A_LCD.allon = 0; break; case 0xA5: A_LCD.allon = 1; break;
case 0xA0: A_LCD.flip_x = 0; break; case 0xA1: A_LCD.flip_x = 1; break;
case 0xC0: A_LCD.flip_y = 0; break; case 0xC8: A_LCD.flip_y = 1; break;
}
}
/* the program may want each full picture (greys made by switching pictures) */
__attribute__((weak)) void ab_frame(void) {}
static inline __attribute__((always_inline)) void lcd_data(u32 v)
{
#ifdef AB_TRACE
{ static u32 n, nz; n++; if (v) nz++; if ((n & 0xFFF) == 0) printf("data %u nonzero %u cyc %u\n", n, nz, A_CYC); }
#endif
u32 col = g_col;
A_GD[(g_page & 7u) * 128u + (col & 127u)] = (u8)v;
if (__builtin_expect(g_amode == 0 && col < g_c1, 1)) { g_col = col + 1u; return; }
if (g_amode == 2) { g_col = (col + 1u) & 127u; return; }
if (g_amode == 0) {
if (g_col >= g_c1) { g_col = g_c0; if (g_page >= g_p1) { g_page = g_p0; A_FRAMES++; ab_frame(); } else g_page++; }
else g_col++;
} else {
if (g_page >= g_p1) { g_page = g_p0; if (g_col >= g_c1) { g_col = g_c0; A_FRAMES++; ab_frame(); } else g_col++; }
else g_page++;
}
}
/* ------------------------------------------------------------------ the rest of the hardware */
/* AB_SND2: the pitch from the times of the pin changes (not their number in the window), a change of both speaker pins
* at once counts once, and sound made by PWM samples on OC4A (ATMlib) from the rising edges of the samples */
#ifndef AB_SND2
#define AB_SND2 1
#endif
static u32 g_tt0, g_tt1, g_pe, g_pt0, g_pt1, g_pl, g_pd;
static u32 g_lfsr = 0xACE1u, g_tog, g_wdt_at, g_sleep, g_spm, g_pc, g_rst;
/* AB_SPIN: busy waiting (a loop that only asks the clock, as millis() and micros() do, and changes nothing) is skipped
* up to the next event. Anchor: "in rd, SREG" (the start of millis() and micros()). An iteration from the anchor back to
* it, at the same stack depth, that wrote nothing but its own stack (and the call into the anchor's function: 32
* bytes above it) and no I/O, changes nothing but the time. */
#ifndef AB_SPIN
#define AB_SPIN 1
#endif
#if AB_JIT
#define g_dirty (g_mem.jit[9]) /* J_DIRTY of jit.inc */
static u32 g_anc_pc = 0xFFFFFFFFu, g_anc_sp, g_tread;
#else
static u32 g_anc_pc = 0xFFFFFFFFu, g_anc_sp, g_dirty = 1, g_tread;
#endif
static u32 rnd(void) { g_lfsr ^= g_lfsr << 13; g_lfsr ^= g_lfsr >> 17; g_lfsr ^= g_lfsr << 5; return g_lfsr; }
#define WDT_ON (A_D[WDTCSR] & 0x48u)
static void wdt_restart(void)
{
u32 p = (A_D[WDTCSR] & 7u) | ((A_D[WDTCSR] >> 2) & 8u); if (p > 9u) p = 9u;
g_wdt_at = A_CYC + (16000u * 16u << p); /* 16 ms << WDP */
}
static int tm_of(u32 a, u32 *reg)
{
if (a >= TCCR0A && a <= OCR0B) { *reg = a; return 0; }
if (a >= 0x80 && a <= 0x8D) { *reg = a; return 1; }
if (a >= 0x90 && a <= 0x9D) { *reg = a; return 2; }
if (a == TCNT4 || a == TC4H || (a >= TCCR4A && a <= 0xC4) || (a >= OCR4A && a <= OCR4D)) { *reg = a; return 3; }
return -1;
}
static u32 pins(u32 port, u32 ext)
{
u32 ddr = A_D[port - 1];
return (A_D[port] & ddr) | (ext & ~ddr);
}
static u8 io_rd(u32 a)
{
u32 r;
#ifdef AB_IOSTAT
{ extern u32 A_IOR[256]; A_IOR[a & 255u]++; }
#endif
switch (a) {
case PINB: case PINC: case PIND: case PINE: case PINF: return A_D[a]; /* pins_upd */
case PLLCSR: return (u8)((A_D[PLLCSR] & ~1u) | ((A_D[PLLCSR] >> 1) & 1u));
case SPSR: return A_D[SPSR];
case SPDR: A_D[SPSR] &= 0x3Fu; return 0;
case ADCL: return A_D[ADCL];
case EECR: return A_D[EECR] & ~2u;
}
int i = tm_of(a, &r);
if (i >= 0) {
tm_sync(i); Tm *t = &g_t[i];
if (i == 0) { if (a == TCNT0) { g_tread = 1; return (u8)tm_count(t); } return A_D[a]; }
if (i < 3) {
u32 o = a - (i == 1 ? 0x80u : 0x90u);
if (o == 4) { u32 c = tm_count(t); t->temp = c >> 8; g_tread = 1; return (u8)c; }
if (o == 5) return (u8)t->temp;
if (o == 6) { t->temp = t->ocr[3] >> 8; return (u8)t->ocr[3]; }
if (o == 7) return (u8)t->temp;
if (o >= 8 && o <= 13) { u32 v = t->ocr[(o - 8) >> 1]; return (u8)(o & 1u ? v >> 8 : v); }
return A_D[a];
}
if (a == TCNT4) { u32 c = tm_count(t); A_D[TC4H] = (u8)(c >> 8); g_tread = 1; return (u8)c; }
if (a >= OCR4A && a <= OCR4D) { static const u8 SL[4] = { 0, 1, 3, 2 }; u32 x = t->ocr[SL[a - OCR4A]]; A_D[TC4H] = (u8)(x >> 8); return (u8)x; }
return A_D[a];
}
return A_D[a];
}
/* returns 1 when an interrupt may now be due (the run loop looks again) */
#ifdef AB_IOSTAT
u32 A_IOW[256], A_IOR[256];
#endif
/* the pins as the program reads them, kept in the data space (the fast core reads them there) */
static void pins_upd(void)
{
u32 m = 0xFFu; if (A_KEYS & AB_UP) m &= ~0x80u; if (A_KEYS & AB_RIGHT) m &= ~0x40u; if (A_KEYS & AB_LEFT) m &= ~0x20u; if (A_KEYS & AB_DOWN) m &= ~0x10u;
A_D[PINB] = (u8)pins(PORTB, (A_KEYS & AB_B) ? 0xEFu : 0xFFu); A_D[PINC] = (u8)pins(PORTC, 0xFFu);
A_D[PIND] = (u8)pins(PORTD, 0xFFu); A_D[PINE] = (u8)pins(PORTE, (A_KEYS & AB_A) ? 0xBFu : 0xFFu); A_D[PINF] = (u8)pins(PORTF, m);
}
static int io_wr0(u32 a, u32 v);
static int io_wr(u32 a, u32 v)
{
int r = io_wr0(a, v);
if (a >= PINB && a <= PORTF) pins_upd();
else if (!(a >= SPCR && a <= SPDR) && !(a >= SPL && a <= SREG)) g_tv = 0;
return r;
}
static int io_wr0(u32 a, u32 v)
{
u32 r, old;
#ifdef AB_IOSTAT
A_IOW[a & 255u]++;
#endif
if (a != SPL && a != SPH && a != SREG) g_dirty = 1;
switch (a) {
case PINB: case PINC: case PIND: case PINE: case PINF: a += 2; v = A_D[a] ^ v; /* fall through: toggle */
case PORTB: case PORTD: case PORTE: case PORTF: case PORTC:
old = A_D[a]; A_D[a] = (u8)v;
if (a == PORTD && (old & ~v & A_D[DDRD] & 0x80u)) lcd_reset(0); /* display reset pin low */
if (a == PORTC) { u32 x = (old ^ v) & A_D[DDRC] & 0xC0u;
#if AB_SND2
if (x) { if (!g_tog) g_tt0 = A_CYC; g_tog++; g_tt1 = A_CYC; }
#else
g_tog += (x >> 7) + ((x >> 6) & 1u);
#endif
}
return 0;
case TIFR0: case TIFR1: case TIFR3: case TIFR4:
{ int i = a == TIFR0 ? 0 : a == TIFR1 ? 1 : a == TIFR3 ? 2 : 3; tm_sync(i); A_D[a] &= (u8)~v; return 1; }
case TIMSK0: case TIMSK1: case TIMSK3: case TIMSK4:
{ int i = a == TIMSK0 ? 0 : a == TIMSK1 ? 1 : a == TIMSK3 ? 2 : 3; tm_sync(i); A_D[a] = (u8)v; return 1; }
case SREG: old = A_D[SREG]; A_D[SREG] = (u8)v; return (v & ~old & I_FLAG) != 0;
case SPDR:
A_D[SPDR] = (u8)v;
if (A_D[SPCR] & 0x40u) {
if (A_D[PORTD] & 0x10u) lcd_data(v); else lcd_cmd(v); /* the display is always selected (CS not used) */
A_D[SPSR] |= 0x80u;
return (A_D[SPCR] & 0x80u) != 0;
}
return 0;
case SPSR: A_D[SPSR] = (u8)((A_D[SPSR] & 0xFEu) | (v & 1u)); return 0;
case EECR:
A_D[EECR] = (u8)(v & 0x3Fu);
if (v & 1u) A_D[EEDR] = A_EEP[(A_D[EEARL] | A_D[EEARH] << 8) & (AVR_EEP - 1u)];
if ((v & 2u) && (v & 4u || g_spm)) {
u32 ad = (A_D[EEARL] | A_D[EEARH] << 8) & (AVR_EEP - 1u), md = (v >> 4) & 3u, nv = md == 0 ? A_D[EEDR] : md == 1 ? 0xFFu : (A_EEP[ad] & A_D[EEDR]);
if (A_EEP[ad] != nv) { A_EEP[ad] = (u8)nv; A_EEP_DIRTY = 1; }
A_D[EECR] &= ~6u;
}
g_spm = (v & 4u) != 0;
return (v & 8u) != 0;
case ADCSRA:
A_D[ADCSRA] = (u8)(v & ~0x10u) | (A_D[ADCSRA] & 0x10u & ~v);
if (v & 0x40u) { u32 x = rnd() & 0x3FFu; A_D[ADCL] = (u8)x; A_D[ADCH] = (u8)(x >> 8); A_D[ADCSRA] = (u8)((A_D[ADCSRA] & ~0x40u) | 0x10u); return (v & 8u) != 0; }
return 0;
case WDTCSR:
A_D[WDTCSR] = (u8)((v & 0x7Fu) | (A_D[WDTCSR] & 0x80u & ~v));
if (WDT_ON) wdt_restart();
return 1;
case SMCR: A_D[SMCR] = (u8)v; return 0;
case MCUSR: A_D[MCUSR] = (u8)(A_D[MCUSR] & v); return 0;
case PLLCSR: A_D[PLLCSR] = (u8)(v & 0xFEu); tm_sync(3); tm_cfg(3); return 0;
case PLLFRQ: A_D[PLLFRQ] = (u8)v; tm_sync(3); tm_cfg(3); return 0;
}
int i = tm_of(a, &r);
if (i >= 0) {
tm_sync(i); Tm *t = &g_t[i];
if (i == 0) {
if (a == TCNT0) { t->ph = v % t->P; return 1; }
A_D[a] = (u8)v;
if (a == OCR0A) t->ocr[0] = v; else if (a == OCR0B) t->ocr[1] = v;
tm_cfg(0); return 1;
}
if (i < 3) {
u32 o = a - (i == 1 ? 0x80u : 0x90u);
if (o == 5 || o == 7 || o == 9 || o == 11 || o == 13) { t->temp = v; return 0; }
u32 w = (t->temp << 8) | v;
if (o == 4) { t->ph = w % t->P; return 1; }
if (o == 6) t->ocr[3] = w; else if (o >= 8) t->ocr[(o - 8) >> 1] = w; else A_D[a] = (u8)v;
tm_cfg(i); return 1;
}
u32 w = ((A_D[TC4H] & 3u) << 8) | v;
if (a == TC4H) { A_D[TC4H] = (u8)(v & 3u); return 0; }
if (a == TCNT4) { t->ph = w % t->P; return 1; }
if (a == OCR4A) {
t->ocr[0] = w;
#if AB_SND2
if (w > g_pl + 8u) { if (g_pd != 1u) { if (!g_pe) g_pt0 = A_CYC; g_pe++; g_pt1 = A_CYC; } g_pd = 1; }
else if (w + 8u < g_pl) g_pd = 2;
g_pl = w;
#endif
} else if (a == OCR4B) t->ocr[1] = w;
else if (a == OCR4C) t->ocr[3] = w; else if (a == OCR4D) t->ocr[2] = w; /* D has the third flag, C is the top */
else A_D[a] = (u8)v;
tm_cfg(3); return 1;
}
A_D[a] = (u8)v;
return 0;
}
/* the interrupt to run now (vector number), 0: none */
static u32 irq_now(void)
{
u32 f;
if ((A_D[WDTCSR] & 0xC0u) == 0xC0u) return 12;
if ((f = A_D[TIFR1] & A_D[TIMSK1] & 0x2Fu)) return f & 0x20u ? 16 : f & 2u ? 17 : f & 4u ? 18 : f & 8u ? 19 : 20;
if ((f = A_D[TIFR0] & A_D[TIMSK0] & 7u)) return f & 2u ? 21 : f & 4u ? 22 : 23;
if ((A_D[SPSR] & 0x80u) && (A_D[SPCR] & 0x80u)) return 24;
if ((A_D[ADCSRA] & 0x18u) == 0x18u) return 29;
if (A_D[EECR] & 8u) return 30;
if ((f = A_D[TIFR3] & A_D[TIMSK3] & 0x2Fu)) return f & 0x20u ? 31 : f & 2u ? 32 : f & 4u ? 33 : f & 8u ? 34 : 35;
if ((f = A_D[TIFR4] & A_D[TIMSK4] & 0xE4u)) return f & 0x40u ? 38 : f & 0x20u ? 39 : f & 0x80u ? 40 : 41;
return 0;
}
#ifdef AB_IOSTAT
u32 A_IRQ[64];
#endif
static void irq_ack(u32 v)
{
#ifdef AB_IOSTAT
A_IRQ[v & 63u]++;
#endif
g_tv &= v >= 38 ? ~8u : v >= 31 ? ~4u : v >= 21 ? ~1u : v >= 16 ? ~2u : ~0u;
switch (v) {
case 12: A_D[WDTCSR] &= ~0x80u; break;
case 16: A_D[TIFR1] &= ~0x20u; break; case 17: A_D[TIFR1] &= ~2u; break; case 18: A_D[TIFR1] &= ~4u; break; case 19: A_D[TIFR1] &= ~8u; break; case 20: A_D[TIFR1] &= ~1u; break;
case 21: A_D[TIFR0] &= ~2u; break; case 22: A_D[TIFR0] &= ~4u; break; case 23: A_D[TIFR0] &= ~1u; break;
case 24: A_D[SPSR] &= ~0x80u; break; case 29: A_D[ADCSRA] &= ~0x10u; break;
case 31: A_D[TIFR3] &= ~0x20u; break; case 32: A_D[TIFR3] &= ~2u; break; case 33: A_D[TIFR3] &= ~4u; break; case 34: A_D[TIFR3] &= ~8u; break; case 35: A_D[TIFR3] &= ~1u; break;
case 38: A_D[TIFR4] &= ~0x40u; break; case 39: A_D[TIFR4] &= ~0x20u; break; case 40: A_D[TIFR4] &= ~0x80u; break; case 41: A_D[TIFR4] &= ~4u; break;
}
}
static void ev_sync(void)
{
#if AB_EVC
for (int i = 0; i < 4; i++) if (!(g_tv & (1u << i)) || (s32)(A_CYC - g_tat[i]) >= 0) { tm_sync(i); g_tv &= ~(1u << i); }
#else
for (int i = 0; i < 4; i++) tm_sync(i);
#endif
if (WDT_ON && (s32)(A_CYC - g_wdt_at) >= 0) {
if (A_D[WDTCSR] & 0x40u) { A_D[WDTCSR] |= 0x80u; wdt_restart(); }
else { ab_reset(); A_D[MCUSR] |= 8u; }
}
}
static u32 ev_next(void)
{
u32 b = 0xFFFFFFFFu;
#if AB_EVC
for (int i = 0; i < 4; i++) {
if (!(g_tv & (1u << i))) { u32 n = tm_next(i); g_tat[i] = A_CYC + (n < 0x400000u ? n : 0x400000u); g_tv |= 1u << i; }
u32 n = g_tat[i] - A_CYC; if ((s32)n < 0) n = 0; if (n < b) b = n;
}
#else
for (int i = 0; i < 4; i++) { u32 n = tm_next(i); if (n < b) b = n; }
#endif
if (WDT_ON) { u32 n = g_wdt_at - A_CYC; if ((s32)n < 0) n = 0; if (n < b) b = n; }
return b;
}
/* ------------------------------------------------------------------ program */
#if !AB_JIT
static void *const *g_T; /* the handlers (filled in by the first ab_run(0)) */
#if defined(__arm__) && !defined(AB_INDEX)
#define AB_ADDR 1 /* the handler's address in the op (PRAM is below 64 KB) */
#else
#define AB_ADDR 0
#endif
static u32 op_of(u32 o) { u32 i = o & 0xFFFFu; return AB_ADDR ? (o & 0xFFFF0000u) | ((u32)(uintptr_t)g_T[i] & 0xFFFFu) : o; }
void ab_load(const u16 *flash, u32 words)
{
if (!g_T) ab_run(0);
A_FLASH = flash; g_words = words;
for (u32 pc = 0; pc < AVR_FLASH_WORDS; pc++) A_OP[pc] = op_of(pc < words ? decode(pc) : O_BAD);
for (u32 pc = 0; pc + 1 < words; pc++) { /* LDS, STS: the address in the next slot */
u32 w = flash[pc];
if ((w & 0xFE0Fu) == 0x9000u || (w & 0xFE0Fu) == 0x9200u) A_OP[pc + 1] = op_of(F(O_BAD, flash[pc + 1]));
}
for (u32 pc = AVR_FLASH_WORDS; pc < AVR_FLASH_WORDS + 4; pc++) A_OP[pc] = op_of(O_BAD);
}
#endif
void ab_reset(void)
{
for (u32 i = 0; i < AVR_DATA; i++) A_D[i] = 0;
A_D[SPL] = (u8)(AVR_DATA - 1u); A_D[SPH] = (u8)((AVR_DATA - 1u) >> 8);
A_D[PLLFRQ] = 0x04; A_D[0x61] = 0; A_D[MCUSR] = 1;
for (int i = 0; i < 4; i++) { Tm *t = &g_t[i]; for (u32 k = 0; k < sizeof *t; k++) ((u8 *)t)[k] = 0; t->base = A_CYC; }
g_t[3].ocr[3] = 0xFF;
for (int i = 0; i < 4; i++) tm_cfg(i);
lcd_reset(1);
g_sleep = 0; g_spm = 0; g_pc = 0; g_rst = 1; g_dirty = 1; g_anc_pc = 0xFFFFFFFFu; g_tv = 0; pins_upd();
}
#if !AB_JIT
/* ------------------------------------------------------------------ the CPU
* Flags are kept apart and put together only when SREG is read: fc = C (0/1), fz = 0 exactly when Z, fn bit 7 = N,
* fv bit 7 = V, fh bit 4 = H, S = N ^ V; sr keeps I and T. left: cycles until the next event (lim). */
#define T_F 64u
#define R(i) D[i]
#define RW(i) (D[i] | (u32)D[(i) + 1] << 8)
#define SP_GET() (D[SPL] | (u32)D[SPH] << 8)
#define SP_SET(v) do { u32 _v = (v); D[SPL] = (u8)_v; D[SPH] = (u8)(_v >> 8); } while (0)
#define PUSHB(v) do { u32 _s = SP_GET(); D[_s < 0x1000u ? _s : 0xFFFu] = (u8)(v); if (_s > g_anc_sp + 32u) g_dirty = 1; SP_SET(_s - 1u); } while (0)
#define POPB() ({ u32 _s = SP_GET() + 1u; SP_SET(_s); D[_s < 0x1000u ? _s : 0xFFFu]; })
#define PUSHPC(p) do { PUSHB(p); PUSHB((p) >> 8); } while (0)
#define POPPC() ({ u32 _h = POPB(); u32 _l = POPB(); ((_h << 8) | _l) & 0x3FFFu; })
AVR_FAST void ab_run(u32 cycles)
{
static void *const T[O_N] = {
&&nop, &&movw, &&muls, &&mulsu, &&fmul, &&fmuls, &&fmulsu, &&cpc, &&sbc, &&add, &&cpse, &&cp, &&sub, &&adc, &&and_,
&&eor, &&or_, &&mov, &&cpi, &&sbci, &&subi, &&ori, &&andi, &&lddy, &&lddz, &&stdy, &&stdz, &&lds, &&ldzp, &&ldmz,
&&lpmz, &&lpmzp, &&ldyp, &&ldmy, &&ldx, &&ldxp, &&ldmx, &&pop, &&sts, &&stzp, &&stmz, &&styp, &&stmy, &&stx, &&stxp,
&&stmx, &&push, &&com, &&neg, &&swap, &&inc, &&asr, &&lsr, &&ror, &&dec, &&bset, &&bclr, &&ret, &&reti, &&sleep,
&&wdr, &&lpm0, &&ijmp, &&icall, &&jmp, &&call, &&adiw, &&sbiw, &&cbi, &&sbic, &&sbi, &&sbis, &&mul, &&in, &&out,
&&rjmp, &&rcall, &&ldi, &&bld, &&bst, &&sbrc, &&sbrs, &&insreg, &&outsreg,
&&breq, &&brne, &&brcs, &&brcc, &&brmi, &&brpl, &&brvs, &&brvc, &&brlt, &&brge, &&brhs, &&brhc, &&brts, &&brtc,
&&brie, &&brid, &&bad };
if (!cycles) { g_T = T; return; }
u8 *D = A_D; __asm__("" : "+r"(D)); /* one base register for the data space */
u32 end = A_CYC + cycles, pc = g_pc, lim, sr, fc, fz, fn, fv, fh, o, d, a, b, v, res;
s32 left;
const u32 *ip;
pins_upd(); /* the buttons */
for (;;) {
g_rst = 0; ev_sync(); if (g_rst) pc = 0;
if ((D[SREG] & I_FLAG) && (v = irq_now())) {
irq_ack(v);
if (g_sleep) { g_sleep = 0; A_CYC += 4; }
PUSHPC(pc); D[SREG] &= ~I_FLAG; pc = v * 2u; A_CYC += 5;
}
if ((s32)(A_CYC - end) >= 0) break;
lim = ev_next(); lim = lim < end - A_CYC ? A_CYC + lim : end;
if (g_sleep) { A_CYC = lim; continue; }
left = (s32)(lim - A_CYC);
v = D[SREG]; sr = v & 0xC0u; fc = v & 1u; fz = (v & 2u) ? 0u : 1u; fn = (v & 4u) << 5; fv = (v & 8u) << 4; fh = (v & 32u) >> 1;
ip = A_OP + pc;
#define SRG() ((sr & 0xC0u) | fc | (fz ? 0u : 2u) | ((fn >> 5) & 4u) | ((fv >> 4) & 8u) | (((fn ^ fv) >> 3) & 16u) | ((fh << 1) & 32u))
#define SRSET(x) do { u32 _x = (x); sr = _x & 0xC0u; fc = _x & 1u; fz = (_x & 2u) ? 0u : 1u; fn = (_x & 4u) << 5; fv = (_x & 8u) << 4; fh = (_x & 32u) >> 1; } while (0)
#define CYC() (lim - (u32)left)
#define SAVE() do { A_CYC = CYC(); } while (0)
#define BREAK_AFTER() do { lim -= (u32)left; left = 0; } while (0) /* leave after this instruction */
#define ONE_MORE(n) do { lim = lim - (u32)left + (n) + 1u; left = (s32)(n) + 1; } while (0)
#if AB_ADDR
#define GO() goto *(void *)(uintptr_t)(o & 0xFFFFu)
#else
#define GO() goto *T[o & 255u]
#endif
#ifdef AB_COUNT
#define CNT A_INS++; A_OPC[(AB_ADDR ? 0 : o & 255u)]++; A_PCH[PCNOW & 0x3FFFu]++;
#else
#define CNT
#endif
#define NEXT(n) do { CNT left -= (s32)(n); if (left <= 0) goto leave; o = *ip; GO(); } while (0)
/* straight on: the event check waits for the next jump (a block of straight code is short) */
#ifdef AB_SINGLE
#define STEP(n) do { ip++; NEXT(n); } while (0) /* tests: one instruction per ab_run(1) */
#else
#define STEP(n) do { CNT left -= (s32)(n); o = *++ip; GO(); } while (0)
#endif
#define D5 ((o >> 16) & 31u)
#define R5 ((o >> 21) & 31u)
#define KH (o >> 24)
#define T14 (o >> 16)
#define RD_DATA(ad, dst) do { u32 _a = (ad); if (_a >= 0x100u) dst = D[_a < 0x1000u ? _a : 0xFFFu]; /* as the fast core: beyond the 4 KB on its last byte */ else if (_a < 0x20u) dst = D[_a]; else if (_a == SREG) dst = SRG(); else { SAVE(); dst = io_rd(_a); } } while (0)
#define WR_DATA(ad, val) do { u32 _a = (ad); if (_a >= 0x100u) { D[_a < 0x1000u ? _a : 0xFFFu] = (u8)(val); if (_a < SP_GET() || _a > g_anc_sp + 32u) g_dirty = 1; } \
else if (_a < 0x20u) D[_a] = (u8)(val); else if (_a == SREG) { u32 _v = (val); if ((_v & ~sr & I_FLAG) && irq_now()) ONE_MORE(2u); SRSET(_v); } \
else { SAVE(); if (io_wr(_a, (val))) BREAK_AFTER(); } } while (0)
#define JUMP(t) (ip = A_OP + (t))
#define PCNOW ((u32)(ip - A_OP))
o = *ip; GO();
nop: STEP(1);
movw: d = D5; a = R5; D[d] = D[a]; D[d + 1] = D[a + 1]; STEP(1);
muls: res = (u32)((s32)(int8_t)R(D5) * (s32)(int8_t)R(R5)) & 0xFFFFu; goto mulf;
mulsu: res = (u32)((s32)(int8_t)R(D5) * (s32)R(R5)) & 0xFFFFu; goto mulf;
mul: res = (u32)R(D5) * R(R5);
mulf: D[0] = (u8)res; D[1] = (u8)(res >> 8); fc = res >> 15; fz = res; STEP(2);
fmul: res = (u32)R(D5) * R(R5); goto fmulf;
fmuls: res = (u32)((s32)(int8_t)R(D5) * (s32)(int8_t)R(R5)) & 0xFFFFu; goto fmulf;
fmulsu: res = (u32)((s32)(int8_t)R(D5) * (s32)R(R5)) & 0xFFFFu;
fmulf: fc = res >> 15; res = (res << 1) & 0xFFFFu; fz = res; D[0] = (u8)res; D[1] = (u8)(res >> 8); STEP(2);
#define ADDF(a_, b_, r_) do { fc = (r_) >> 8; fz = (r_) & 0xFFu; fn = (r_); fv = ((a_) ^ (r_)) & ((b_) ^ (r_)); fh = (a_) ^ (b_) ^ (r_); } while (0)
#define SUBF(a_, b_, r_) do { fc = ((r_) >> 8) & 1u; fz = (r_) & 0xFFu; fn = (r_); fv = ((a_) ^ (b_)) & ((a_) ^ (r_)); fh = (a_) ^ (b_) ^ (r_); } while (0)
#define SBCF(a_, b_, r_) do { fc = ((r_) >> 8) & 1u; fz |= (r_) & 0xFFu; fn = (r_); fv = ((a_) ^ (b_)) & ((a_) ^ (r_)); fh = (a_) ^ (b_) ^ (r_); } while (0)
add: d = D5; a = R(d); b = R(R5); res = a + b; D[d] = (u8)res; ADDF(a, b, res); STEP(1);
adc: d = D5; a = R(d); b = R(R5); res = a + b + fc; D[d] = (u8)res; ADDF(a, b, res); STEP(1);
sub: d = D5; a = R(d); b = R(R5); res = a - b; D[d] = (u8)res; SUBF(a, b, res); STEP(1);
sbc: d = D5; a = R(d); b = R(R5); res = a - b - fc; D[d] = (u8)res; SBCF(a, b, res); STEP(1);
cp: a = R(D5); b = R(R5); res = a - b; SUBF(a, b, res); STEP(1);
cpc: a = R(D5); b = R(R5); res = a - b - fc; SBCF(a, b, res); STEP(1);
cpi: a = R(D5); b = KH; res = a - b; SUBF(a, b, res); STEP(1);
subi: d = D5; a = R(d); b = KH; res = a - b; D[d] = (u8)res; SUBF(a, b, res); STEP(1);
sbci: d = D5; a = R(d); b = KH; res = a - b - fc; D[d] = (u8)res; SBCF(a, b, res); STEP(1);
cpse: if (R(D5) == R(R5)) { a = (o >> 26) & 1u; ip += 2u + a; NEXT(2u + a); } STEP(1);
and_: d = D5; res = R(d) & R(R5); goto logic;
eor: d = D5; res = R(d) ^ R(R5); goto logic;
or_: d = D5; res = R(d) | R(R5); goto logic;
andi: d = D5; res = R(d) & KH; goto logic;
ori: d = D5; res = R(d) | KH;
logic: D[d] = (u8)res; fz = res; fn = res; fv = 0; STEP(1);
mov: D[D5] = D[R5]; STEP(1);
ldi: D[D5] = (u8)KH; STEP(1);
lddy: a = RW(28) + KH; goto ldd;
lddz: a = RW(30) + KH;
ldd: RD_DATA(a & 0xFFFFu, v); D[D5] = (u8)v; STEP(2);
stdy: a = RW(28) + KH; goto std_;
stdz: a = RW(30) + KH;
std_: v = D[D5]; WR_DATA(a & 0xFFFFu, v); STEP(2);
lds: a = ip[1] >> 16; RD_DATA(a, v); D[D5] = (u8)v; ip += 2; NEXT(2);
sts: a = ip[1] >> 16; v = D[D5]; WR_DATA(a, v); ip += 2; NEXT(2);
#define PTR_LD(rp, pre, post) do { a = RW(rp); if (pre) a = (a - 1u) & 0xFFFFu; RD_DATA(a, v); if (post) a = (a + 1u) & 0xFFFFu; if ((pre) || (post)) { D[rp] = (u8)a; D[rp + 1] = (u8)(a >> 8); } D[D5] = (u8)v; } while (0)
#define PTR_ST(rp, pre, post) do { a = RW(rp); if (pre) a = (a - 1u) & 0xFFFFu; v = D[D5]; WR_DATA(a, v); if (post) a = (a + 1u) & 0xFFFFu; if ((pre) || (post)) { D[rp] = (u8)a; D[rp + 1] = (u8)(a >> 8); } } while (0)
ldzp: PTR_LD(30, 0, 1); STEP(2);
ldmz: PTR_LD(30, 1, 0); STEP(2);
ldyp: PTR_LD(28, 0, 1); STEP(2);
ldmy: PTR_LD(28, 1, 0); STEP(2);
ldx: PTR_LD(26, 0, 0); STEP(2);
ldxp: PTR_LD(26, 0, 1); STEP(2);
ldmx: PTR_LD(26, 1, 0); STEP(2);
stzp: PTR_ST(30, 0, 1); STEP(2);
stmz: PTR_ST(30, 1, 0); STEP(2);
styp: PTR_ST(28, 0, 1); STEP(2);
stmy: PTR_ST(28, 1, 0); STEP(2);
stx: PTR_ST(26, 0, 0); STEP(2);
stxp: PTR_ST(26, 0, 1); STEP(2);
stmx: PTR_ST(26, 1, 0); STEP(2);
lpmz: a = RW(30); D[D5] = (u8)(A_FLASH[(a >> 1) & 0x3FFFu] >> ((a & 1u) * 8u)); STEP(3);
lpmzp: a = RW(30); D[D5] = (u8)(A_FLASH[(a >> 1) & 0x3FFFu] >> ((a & 1u) * 8u)); a = (a + 1u) & 0xFFFFu; D[30] = (u8)a; D[31] = (u8)(a >> 8); STEP(3);
lpm0: a = RW(30); D[0] = (u8)(A_FLASH[(a >> 1) & 0x3FFFu] >> ((a & 1u) * 8u)); STEP(3);
push: PUSHB(D[D5]); STEP(2);
pop: D[D5] = (u8)POPB(); STEP(2);
com: d = D5; res = ~R(d) & 0xFFu; D[d] = (u8)res; fc = 1; fv = 0; fn = fz = res; STEP(1);
neg: d = D5; a = R(d); res = 0u - a; D[d] = (u8)res; SUBF(0u, a, res); STEP(1);
swap: d = D5; a = R(d); D[d] = (u8)((a >> 4) | (a << 4)); STEP(1);
inc: d = D5; a = R(d); res = (a + 1u) & 0xFFu; D[d] = (u8)res; fv = res & ~a; fn = fz = res; STEP(1);
dec: d = D5; a = R(d); res = (a - 1u) & 0xFFu; D[d] = (u8)res; fv = a & ~res; fn = fz = res; STEP(1);
asr: d = D5; a = R(d); res = (a >> 1) | (a & 0x80u); goto shf;
lsr: d = D5; a = R(d); res = a >> 1; goto shf;
ror: d = D5; a = R(d); res = (a >> 1) | (fc << 7);
shf: D[d] = (u8)res; fc = a & 1u; fn = fz = res; fv = res ^ (fc << 7); STEP(1);
bset: v = SRG(); a = (o >> 16) & 255u; if ((a & ~v & I_FLAG) && irq_now()) ONE_MORE(1u); SRSET(v | a); STEP(1);
bclr: v = SRG(); SRSET(v & ~(o >> 16)); STEP(1);
bst: sr = (sr & ~T_F) | ((D[D5] & KH) ? T_F : 0u); STEP(1);
bld: d = D5; if (sr & T_F) D[d] |= (u8)KH; else D[d] &= (u8)~KH; STEP(1);
ret: JUMP(POPPC()); NEXT(4);
reti: JUMP(POPPC()); sr |= I_FLAG; if (irq_now()) ONE_MORE(4u); NEXT(4);
sleep: ip++; if (D[SMCR] & 1u) { g_sleep = 1; BREAK_AFTER(); } NEXT(1);
wdr: if (WDT_ON) { SAVE(); wdt_restart(); } STEP(1);
ijmp: JUMP(RW(30) & 0x3FFFu); NEXT(2);
icall: a = PCNOW + 1u; PUSHPC(a); JUMP(RW(30) & 0x3FFFu); NEXT(3);
jmp: JUMP(T14); NEXT(3);
call: a = PCNOW + 2u; PUSHPC(a); JUMP(T14); NEXT(4);
rjmp: JUMP(T14); NEXT(2);
rcall: a = PCNOW + 1u; PUSHPC(a); JUMP(T14); NEXT(3);
adiw: d = D5; a = RW(d); res = (a + KH) & 0xFFFFu; D[d] = (u8)res; D[d + 1] = (u8)(res >> 8);
fz = res; fn = res >> 8; fc = ((a & ~res) >> 15) & 1u; fv = (res & ~a) >> 8; STEP(2);
sbiw: d = D5; a = RW(d); res = (a - KH) & 0xFFFFu; D[d] = (u8)res; D[d + 1] = (u8)(res >> 8);
fz = res; fn = res >> 8; fc = ((res & ~a) >> 15) & 1u; fv = (a & ~res) >> 8; STEP(2);
#define IOA (((o >> 24) & 31u) + 0x20u)
#define IOM ((o >> 16) & 255u)
#define IS_PIN(a_) ((a_) >= PINB && (a_) <= PORTF && ((a_) - PINB) % 3u == 0u)
#define IS_FLAG(a_) ((a_) >= TIFR0 && (a_) <= TIFR4)
cbi: a = IOA; SAVE();
if (!IS_PIN(a) && !IS_FLAG(a)) { v = io_rd(a) & ~IOM; if (io_wr(a, v)) BREAK_AFTER(); }
STEP(2);
sbi: a = IOA; SAVE();
v = (IS_PIN(a) || IS_FLAG(a)) ? IOM : io_rd(a) | IOM;
if (io_wr(a, v)) BREAK_AFTER();
STEP(2);
sbic: a = IOA; SAVE(); v = io_rd(a); if (!(v & IOM)) { a = (o >> 29) & 1u; ip += 2u + a; NEXT(2u + a); } STEP(1);
sbis: a = IOA; SAVE(); v = io_rd(a); if (v & IOM) { a = (o >> 29) & 1u; ip += 2u + a; NEXT(2u + a); } STEP(1);
sbrc: if (!(D[D5] & KH)) { a = (o >> 21) & 1u; ip += 2u + a; NEXT(2u + a); } STEP(1);
sbrs: if (D[D5] & KH) { a = (o >> 21) & 1u; ip += 2u + a; NEXT(2u + a); } STEP(1);
in: SAVE(); D[D5] = io_rd(KH); STEP(1);
out: SAVE(); if (io_wr(KH, D[D5])) BREAK_AFTER(); STEP(1);
outsreg: v = D[D5]; if ((v & ~sr & I_FLAG) && irq_now()) ONE_MORE(1u); SRSET(v); STEP(1);
insreg: D[D5] = (u8)SRG();
if (AB_SPIN) { /* busy waiting: see g_anc_pc */
u32 sp = SP_GET(), pcn = PCNOW;
if (pcn == g_anc_pc && sp == g_anc_sp) {
if (!g_dirty) {
u32 cyc = CYC(), to = lim; if (g_tread && to - cyc > 512u) to = cyc + 512u;
if ((s32)(to - cyc) > 1) left = (s32)(lim - to) + 1; /* after this instruction the time is `to` */
}
g_dirty = 0; g_tread = 0;
} else if (g_dirty) { g_anc_pc = pcn; g_anc_sp = sp; g_dirty = 0; g_tread = 0; }
}
STEP(1);
breq: if (!fz) { JUMP(T14); NEXT(2); } STEP(1);
brne: if (fz) { JUMP(T14); NEXT(2); } STEP(1);
brcs: if (fc) { JUMP(T14); NEXT(2); } STEP(1);
brcc: if (!fc) { JUMP(T14); NEXT(2); } STEP(1);
brmi: if (fn & 0x80u) { JUMP(T14); NEXT(2); } STEP(1);
brpl: if (!(fn & 0x80u)) { JUMP(T14); NEXT(2); } STEP(1);
brvs: if (fv & 0x80u) { JUMP(T14); NEXT(2); } STEP(1);
brvc: if (!(fv & 0x80u)) { JUMP(T14); NEXT(2); } STEP(1);
brlt: if ((fn ^ fv) & 0x80u) { JUMP(T14); NEXT(2); } STEP(1);
brge: if (!((fn ^ fv) & 0x80u)) { JUMP(T14); NEXT(2); } STEP(1);
brhs: if (fh & 0x10u) { JUMP(T14); NEXT(2); } STEP(1);
brhc: if (!(fh & 0x10u)) { JUMP(T14); NEXT(2); } STEP(1);
brts: if (sr & T_F) { JUMP(T14); NEXT(2); } STEP(1);
brtc: if (!(sr & T_F)) { JUMP(T14); NEXT(2); } STEP(1);
brie: if (sr & I_FLAG) { JUMP(T14); NEXT(2); } STEP(1);
brid: if (!(sr & I_FLAG)) { JUMP(T14); NEXT(2); } STEP(1);
bad: JUMP((PCNOW + 1u) & 0x3FFFu); NEXT(1);
leave:
A_CYC = CYC(); D[SREG] = (u8)SRG(); pc = PCNOW;
}
g_pc = pc;
}
#undef SAVE
#endif
/* ------------------------------------------------------------------ sound */
u32 ab_tone(u32 cycles)
{
u32 t = g_tog; g_tog = 0;
/* timer 3 toggling OC3A (PC6) in CTC mode */
if ((A_D[TCCR3A] & 0xC0u) == 0x40u && (A_D[DDRC] & 0x40u) && g_t[2].sh != STOP)
return (16000000u / (2u << g_t[2].sh)) / (g_t[2].top + 1u);
/* timer 4 toggling OC4A (PC7) */
if ((A_D[TCCR4A] & 0xC2u) == 0x40u && (A_D[DDRC] & 0x80u) && g_t[3].sh != STOP) /* not PWM4A: there 01 is PWM on both pins */
return (16000000u / (2u << g_t[3].sh)) * g_t[3].mul / (g_t[3].top + 1u);
#if AB_SND2
u32 e = g_pe; g_pe = 0;
if (t >= 3u && g_tt1 != g_tt0) return (t - 1u) * 8000000u / (g_tt1 - g_tt0); /* two changes per period */
if (e >= 2u && e < 250u && g_pt1 != g_pt0 && (A_D[TCCR4A] & 0xC2u) > 0x02u) return (e - 1u) * 16000000u / (g_pt1 - g_pt0);
return 0;
#else
if (t < 4u || !cycles) return 0;
cycles /= 1000u; if (!cycles) return 0;
return t * 8000u / cycles;
#endif
}
/* ------------------------------------------------------------------ state */
#define ST_ID 0x31534241u /* "ABS1" */
u32 ab_state_save(u8 *buf, u32 size)
{
struct { void *p; u32 n; } P[] = { { A_D, AVR_DATA }, { A_GD, 1024 }, { &A_LCD, sizeof A_LCD }, { g_t, sizeof g_t },
{ &g_pc, 4 }, { &A_CYC, 4 }, { &g_col, 4 }, { &g_page, 4 }, { &g_c0, 4 }, { &g_c1, 4 }, { &g_p0, 4 }, { &g_p1, 4 },
{ &g_amode, 4 }, { &g_cmd_n, 4 }, { g_cmd, sizeof g_cmd }, { &g_lfsr, 4 }, { &g_wdt_at, 4 }, { &g_sleep, 4 } };
u32 n = 4; if (size < 4) return 0;
buf[0] = 'A'; buf[1] = 'B'; buf[2] = 'S'; buf[3] = '1';
for (u32 i = 0; i < sizeof P / sizeof P[0]; i++) { if (n + P[i].n > size) return 0; for (u32 k = 0; k < P[i].n; k++) buf[n + k] = ((u8 *)P[i].p)[k]; n += P[i].n; }
return n;
}
int ab_state_load(const u8 *buf, u32 size)
{
struct { void *p; u32 n; } P[] = { { A_D, AVR_DATA }, { A_GD, 1024 }, { &A_LCD, sizeof A_LCD }, { g_t, sizeof g_t },
{ &g_pc, 4 }, { &A_CYC, 4 }, { &g_col, 4 }, { &g_page, 4 }, { &g_c0, 4 }, { &g_c1, 4 }, { &g_p0, 4 }, { &g_p1, 4 },
{ &g_amode, 4 }, { &g_cmd_n, 4 }, { g_cmd, sizeof g_cmd }, { &g_lfsr, 4 }, { &g_wdt_at, 4 }, { &g_sleep, 4 } };
u32 n = 4, tot = 4;
for (u32 i = 0; i < sizeof P / sizeof P[0]; i++) tot += P[i].n;
if (size < tot || buf[0] != 'A' || buf[1] != 'B' || buf[2] != 'S' || buf[3] != '1') return 0;
for (u32 i = 0; i < sizeof P / sizeof P[0]; i++) { for (u32 k = 0; k < P[i].n; k++) ((u8 *)P[i].p)[k] = buf[n + k]; n += P[i].n; }
g_tv = 0; pins_upd();
return 1;
}
#if !AB_JIT
u8 *ab_scratch(void) { static u8 b[AB_SCRATCH] __attribute__((aligned(4))); return b; }
#endif
u32 ab_pc(void) { return g_pc; }
void ab_set_pc(u32 p) { g_pc = p; }
void ab_wake(void) { g_sleep = 0; }
u32 ab_tm(int i, int c) { return c < 4 ? g_t[i].ocr[c] : c == 4 ? g_t[i].top : g_t[i].sh; }
#if AB_JIT
#include "jit.inc"
#endif
+57
View File
@@ -0,0 +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
+763
View File
@@ -0,0 +1,763 @@
/* ArduboyEmu AB_JIT: the AVR program translated block by block into Thumb-2 for the Paradise's Cortex-M3 (code in
* the SRAM: a cache, emptied when full). Included at the end of avr.c (uses its I/O, timers and interrupts).
*
* Registers of the translated code: r4 = the data space D (the context lies just before it), r5 = cycles left until
* the next event, r6 = fz (0 exactly when Z), r7 = fc (C, 0/1), r8 = fn (bit 7 N), r9 = fv (bit 7 V), r10 = fh
* (bit 4 H), r11 = I and T (bits 7, 6). r0..r3, r12, lr are free. A block ends at a jump, a branch, a skip, a call,
* a return or after JB_MAX instructions; it subtracts its cycles and goes to the dispatcher with the next pc in r0.
* The dispatcher leaves for C when no cycles are left. Flags are worked out only where something later reads them
* (in the block, or at its end: C, Z, N, V; H only for an instruction that reads it in the same block).
* Rare instructions (I/O, SREG, sleep ...) run in C (jit_op) with the flags handed over in the context.
* Author: mameise. License: GPL-3.0-or-later. */
#ifndef T_F
#define T_F 64u
#endif
/* ---- the context before D: g_mem.jit[i] lies at D - 4 * (64 - i) ---- */
enum { J_XLATE = 1, J_OP, J_LD, J_ST, J_MAP, J_CODE1, J_FLASH, J_PC, J_DIRTY, J_IN, J_OUT, J_BIT, J_SPDR,
J_LEFT = 56, J_FZ, J_FC, J_FN, J_FV, J_FH, J_SR, J_SPARE };
#define JOFF(i) (4u * (64u - (i))) /* offset below D */
#define JC (g_mem.jit)
#ifndef JIT_CACHE
#define JIT_CACHE 0x11C00u /* bytes of translated code (71 KB; its last 9 KB are also ab_scratch) */
#endif
#define JB_MAX 40u
static u16 g_map[AVR_FLASH_WORDS]; /* pc -> code (in halfwords from g_code, 0: not translated) */
static u16 g_code[JIT_CACHE / 2] __attribute__((aligned(4)));
static u16 *g_ep, *g_cend; /* emit pointer, end of the cache */
static u32 g_stub_enter, g_stub_disp, g_stub_exit; /* halfword offsets in g_code */
static u32 g_hold, g_flushes;
#define PEND_N 512u
static u16 g_pend_at[PEND_N], g_pend_pc[PEND_N]; static u32 g_npend, g_blk_pc, g_blk_at; /* AB_CHAIN */
/* ---------------- Thumb-2 encoder ---------------- */
static void H1(u32 x) { if (g_ep < g_cend) *g_ep = (u16)x; g_ep++; }
static void H2(u32 a, u32 b) { H1(a); H1(b); }
#define LDRB_I 0xF890u
#define STRB_I 0xF880u
#define LDRH_I 0xF8B0u
#define STRH_I 0xF8A0u
#define LDR_I 0xF8D0u
#define STR_I 0xF8C0u
static void mem_i(u32 op, u32 rt, u32 rn, u32 imm)
{
if (rt < 8u && rn < 8u) { /* the 16-bit forms (half the code) */
if ((op == LDRB_I || op == STRB_I) && imm < 32u) { H1((op == LDRB_I ? 0x7800u : 0x7000u) | (imm << 6) | (rn << 3) | rt); return; }
if ((op == LDRH_I || op == STRH_I) && imm < 64u && !(imm & 1u)) { H1((op == LDRH_I ? 0x8800u : 0x8000u) | ((imm >> 1) << 6) | (rn << 3) | rt); return; }
}
H2(op | rn, (rt << 12) | (imm & 0xFFFu));
}
static void ldr_ctx(u32 rt, u32 i) { H2(0xF850u | 4u, (rt << 12) | 0xC00u | JOFF(i)); } /* ldr rt, [r4, #-off] */
static void str_ctx(u32 rt, u32 i) { H2(0xF840u | 4u, (rt << 12) | 0xC00u | JOFF(i)); }
#define LDRB_R 0xF810u
#define STRB_R 0xF800u
#define LDRH_R 0xF830u
static void mem_r(u32 op, u32 rt, u32 rn, u32 rm, u32 sh) { H2(op | rn, (rt << 12) | (sh << 4) | rm); }
static void dp_r_w(u32 op, u32 s, u32 rd, u32 rn, u32 rm, u32 ty, u32 sh);
#define DP_AND 0xEA00u
#define DP_BIC 0xEA20u
#define DP_ORR 0xEA40u
#define DP_EOR 0xEA80u
#define DP_ADD 0xEB00u
#define DP_ADC 0xEB40u
#define DP_SUB 0xEBA0u
#define SH_LSL 0u
#define SH_LSR 1u
#define SH_ASR 2u
static void dp_r(u32 op, u32 s, u32 rd, u32 rn, u32 rm, u32 ty, u32 sh)
{
/* 16-bit forms where the flags they set do not matter (no flag test follows them) */
if (!s && !sh && rd < 8u && rn < 8u && rm < 8u) {
if (op == DP_ADD) { H1(0x1800u | (rm << 6) | (rn << 3) | rd); return; }
if (op == DP_SUB) { H1(0x1A00u | (rm << 6) | (rn << 3) | rd); return; }
if (rd == rn && (op == DP_AND || op == DP_EOR || op == DP_ORR || op == DP_BIC)) { H1(0x4000u | ((op == DP_AND ? 0u : op == DP_EOR ? 1u : op == DP_ORR ? 12u : 14u) << 6) | (rm << 3) | rd); return; }
}
dp_r_w(op, s, rd, rn, rm, ty, sh);
}
static void dp_r_w(u32 op, u32 s, u32 rd, u32 rn, u32 rm, u32 ty, u32 sh) { H2(op | (s << 4) | rn, ((sh >> 2) << 12) | (rd << 8) | ((sh & 3u) << 6) | (ty << 4) | rm); }
static void mov_r(u32 rd, u32 rm) { H1(0x4600u | ((rd & 8u) << 4) | (rm << 3) | (rd & 7u)); }
static void movs_sh(u32 rd, u32 rm, u32 ty, u32 sh) { dp_r(DP_ORR, 1, rd, 15, rm, ty, sh); }
static void mov_sh(u32 rd, u32 rm, u32 ty, u32 sh) { dp_r(DP_ORR, 0, rd, 15, rm, ty, sh); }
#define DI_AND 0xF000u
#define DI_ORR 0xF040u
#define DI_EOR 0xF080u
#define DI_ADD 0xF100u
#define DI_SUB 0xF1A0u
static void dp_i(u32 op, u32 s, u32 rd, u32 rn, u32 imm8) { H2(op | (s << 4) | rn, (rd << 8) | (imm8 & 255u)); }
static void tst_i(u32 rn, u32 imm8) { dp_i(DI_AND, 1, 15, rn, imm8); }
static void cmp_i(u32 rn, u32 imm8) { dp_i(DI_SUB, 1, 15, rn, imm8); }
static void movw(u32 rd, u32 v) { if (rd < 8u && v < 256u) { H1(0x2000u | (rd << 8) | v); return; } H2(0xF240u | (((v >> 11) & 1u) << 10) | ((v >> 12) & 15u), (((v >> 8) & 7u) << 12) | (rd << 8) | (v & 255u)); }
static void movt(u32 rd, u32 v) { H2(0xF2C0u | (((v >> 11) & 1u) << 10) | ((v >> 12) & 15u), (((v >> 8) & 7u) << 12) | (rd << 8) | (v & 255u)); }
static void ubfx(u32 rd, u32 rn, u32 lsb, u32 w) { H2(0xF3C0u | rn, ((lsb >> 2) << 12) | (rd << 8) | ((lsb & 3u) << 6) | (w - 1u)); }
/* usat rd, #12, rn: addresses beyond the 4 KB land on its last byte (not on the registers) */
static void sat12(u32 rd, u32 rn) { H2(0xF380u | rn, (rd << 8) | 12u); }
static void uxtb(u32 rd, u32 rm) { if (rd < 8u && rm < 8u) { H1(0xB2C0u | (rm << 3) | rd); return; } H2(0xFA5Fu, 0xF080u | (rd << 8) | rm); }
static void sxtb(u32 rd, u32 rm) { H2(0xFA4Fu, 0xF080u | (rd << 8) | rm); }
static void mul(u32 rd, u32 rn, u32 rm) { H2(0xFB00u | rn, 0xF000u | (rd << 8) | rm); }
static void subw(u32 rd, u32 rn, u32 imm) { H2(0xF2A0u | rn | (((imm >> 11) & 1u) << 10), (((imm >> 8) & 7u) << 12) | (rd << 8) | (imm & 255u)); }
static void addw(u32 rd, u32 rn, u32 imm) { H2(0xF200u | rn | (((imm >> 11) & 1u) << 10), (((imm >> 8) & 7u) << 12) | (rd << 8) | (imm & 255u)); }
static void subs5(u32 n) { while (n > 255u) { H1(0x3D00u | 255u); n -= 255u; } if (n) H1(0x3D00u | n); } /* subs r5, #n */
static void blx(u32 rm) { H1(0x4780u | (rm << 3)); }
static void bx(u32 rm) { H1(0x4700u | (rm << 3)); }
/* branches: to a halfword index in g_code */
static void bcc_w(u32 cc, u32 to) /* b<cc>.w, +-1 MB */
{
s32 off = (s32)(to - (u32)(g_ep - g_code) - 2u) * 2;
u32 s = (off >> 20) & 1u, j2 = (off >> 19) & 1u, j1 = (off >> 18) & 1u;
H2(0xF000u | (s << 10) | (cc << 6) | ((off >> 12) & 0x3Fu), 0x8000u | (j1 << 13) | (j2 << 11) | ((off >> 1) & 0x7FFu));
}
static void b_w(u32 to)
{
s32 off = (s32)(to - (u32)(g_ep - g_code) - 2u) * 2;
u32 s = (off >> 24) & 1u, i1 = (off >> 23) & 1u, i2 = (off >> 22) & 1u, j1 = (~(i1 ^ s)) & 1u, j2 = (~(i2 ^ s)) & 1u;
H2(0xF000u | (s << 10) | ((off >> 12) & 0x3FFu), 0x9000u | (j1 << 13) | (j2 << 11) | ((off >> 1) & 0x7FFu));
}
#define CC_EQ 0u
#define CC_NE 1u
#define CC_CS 2u
#define CC_CC 3u
#define CC_LE 13u
/* a forward conditional branch (16 bit) filled in later */
static u16 *bcc_fwd(u32 cc) { u16 *p = g_ep; H1(0xD000u | (cc << 8)); return p; }
static void fix_fwd(u16 *p) { if (p >= g_cend) return; s32 off = (s32)((g_ep - p) - 2); *p |= (u16)(off & 255); }
static u16 *b_fwd(void) { u16 *p = g_ep; H1(0xE000u); return p; }
static void fix_b(u16 *p) { if (p >= g_cend) return; s32 off = (s32)((g_ep - p) - 2); *p |= (u16)(off & 0x7FFu); }
#define R_D 4u
#define R_LEFT 5u
#define R_FZ 6u
#define R_FC 7u
#define R_FN 8u
#define R_FV 9u
#define R_FH 10u
#define R_SR 11u
/* ---------------- the stubs at the start of the cache ---------------- */
static void stubs(void)
{
g_ep = g_code + 2; /* offset 0 means "not translated" */
/* enter: push {r3-r11, lr}; r4 = D; load r5..r11; r0 = pc */
g_stub_enter = (u32)(g_ep - g_code);
H2(0xE92Du, 0x4FF8u);
movw(R_D, (u32)(uintptr_t)A_D & 0xFFFFu); movt(R_D, (u32)(uintptr_t)A_D >> 16);
subw(12, R_D, JOFF(J_LEFT)); H2(0xE890u | 12u, 0x0FE0u); /* ldm r12, {r5-r11} */
ldr_ctx(0, J_PC);
/* dispatch: r0 = pc */
g_stub_disp = (u32)(g_ep - g_code);
H1(0x2D00u); /* cmp r5, #0 */
u16 *pe = bcc_fwd(CC_LE);
ldr_ctx(1, J_MAP); mem_r(LDRH_R, 2, 1, 0, 1); /* ldrh r2, [r1, r0, lsl #1] */
H1(0x2A00u); u16 *px = bcc_fwd(CC_EQ); /* cmp r2, #0; beq translate */
ldr_ctx(1, J_CODE1); dp_r(DP_ADD, 0, 1, 1, 2, SH_LSL, 1); bx(1);
fix_fwd(px);
ldr_ctx(12, J_XLATE); blx(12); /* r0 = pc again */
b_w(g_stub_disp);
fix_fwd(pe);
/* exit: pc in r0 */
g_stub_exit = (u32)(g_ep - g_code);
str_ctx(0, J_PC);
subw(12, R_D, JOFF(J_LEFT)); H2(0xE880u | 12u, 0x0FE0u); /* stm r12, {r5-r11} */
H2(0xE8BDu, 0x8FF8u); /* pop {r3-r11, pc} */
}
static void jit_flush(void)
{
for (u32 i = 0; i < AVR_FLASH_WORDS; i++) g_map[i] = 0;
g_cend = g_code + JIT_CACHE / 2;
g_npend = 0; g_blk_pc = 0xFFFFFFFFu;
stubs();
g_flushes++;
}
/* ---------------- what each instruction reads and sets of the flags ---------------- */
#define FC 1u
#define FZ 2u
#define FN 4u
#define FV 8u
#define FH 16u
#define FALL 31u
enum { K_HELP, K_ADD, K_ADC, K_SUB, K_SBC, K_CP, K_CPC, K_AND, K_OR, K_EOR, K_MOV, K_MOVW, K_LDI, K_SUBI, K_SBCI, K_CPI,
K_ANDI, K_ORI, K_COM, K_NEG, K_SWAP, K_INC, K_DEC, K_ASR, K_LSR, K_ROR, K_ADIW, K_SBIW, K_MUL, K_LDS, K_STS, K_LDD,
K_STD, K_LD, K_ST, K_LPM, K_PUSH, K_POP, K_BST, K_BLD, K_INSP, K_OUTSP, K_NOP, K_IN, K_OUT, K_BITIO, K_CLI,
/* block ends */
K_RJMP, K_JMP, K_RCALL, K_CALL, K_RET, K_IJMP, K_ICALL, K_BR, K_SBRC, K_SBRS, K_CPSE, K_SKIPIO, K_RETI, K_END };
typedef struct { u16 pc, w, w2, len; u8 k, a, b, c, use, def, live, cyc; } JIns;
static u32 two_w(u32 w) { return (w & 0xFE0Fu) == 0x9000u || (w & 0xFE0Fu) == 0x9200u || (w & 0xFE0Cu) == 0x940Cu; }
/* classify; a, b, c operands (see each kind) */
static void jdec(u32 pc, JIns *x)
{
u32 w = A_FLASH[pc], w2 = pc + 1 < AVR_FLASH_WORDS ? A_FLASH[pc + 1] : 0;
u32 d5 = (w >> 4) & 31u, r5 = (w & 15u) | ((w >> 5) & 16u), d4 = 16u + ((w >> 4) & 15u), K8 = ((w >> 4) & 0xF0u) | (w & 15u);
x->pc = (u16)pc; x->w = (u16)w; x->w2 = (u16)w2; x->len = two_w(w) ? 2 : 1; x->k = K_HELP; x->a = x->b = x->c = 0;
x->use = FALL; x->def = FALL; x->cyc = 1;
#define S(k_, a_, b_, u_, d_, cy_) do { x->k = (k_); x->a = (u8)(a_); x->b = (u8)(b_); x->use = (u_); x->def = (d_); x->cyc = (cy_); } while (0)
switch (w >> 12) {
case 0x0:
if (w == 0) { S(K_NOP, 0, 0, 0, 0, 1); return; }
switch ((w >> 10) & 3u) {
case 0:
if ((w & 0xFF00u) == 0x0100u) { S(K_MOVW, ((w >> 4) & 15u) * 2u, (w & 15u) * 2u, 0, 0, 1); return; }
return; /* MULS, MULSU, FMUL...: in C */
case 1: S(K_CPC, d5, r5, FC | FZ, FALL, 1); return;
case 2: S(K_SBC, d5, r5, FC | FZ, FALL, 1); return;
default: S(K_ADD, d5, r5, 0, FALL, 1); return;
}
case 0x1:
switch ((w >> 10) & 3u) {
case 0: S(K_CPSE, d5, r5, 0, 0, 1); return;
case 1: S(K_CP, d5, r5, 0, FALL, 1); return;
case 2: S(K_SUB, d5, r5, 0, FALL, 1); return;
default: S(K_ADC, d5, r5, FC, FALL, 1); return;
}
case 0x2:
switch ((w >> 10) & 3u) {
case 0: S(K_AND, d5, r5, 0, FZ | FN | FV, 1); return;
case 1: S(K_EOR, d5, r5, 0, FZ | FN | FV, 1); return;
case 2: S(K_OR, d5, r5, 0, FZ | FN | FV, 1); return;
default: S(K_MOV, d5, r5, 0, 0, 1); return;
}
case 0x3: S(K_CPI, d4, K8, 0, FALL, 1); return;
case 0x4: S(K_SBCI, d4, K8, FC | FZ, FALL, 1); return;
case 0x5: S(K_SUBI, d4, K8, 0, FALL, 1); return;
case 0x6: S(K_ORI, d4, K8, 0, FZ | FN | FV, 1); return;
case 0x7: S(K_ANDI, d4, K8, 0, FZ | FN | FV, 1); return;
case 0x8: case 0xA: {
u32 q = (w & 7u) | ((w >> 7) & 0x18u) | ((w >> 8) & 0x20u), st = (w >> 9) & 1u, y = (w >> 3) & 1u;
S(st ? K_STD : K_LDD, d5, q, st ? FC | FZ | FN | FV : 0, 0, 2); x->c = (u8)(y ? 28 : 30); /* a store may leave for C */
return;
}
case 0x9:
switch ((w >> 9) & 7u) {
case 0: case 1: {
u32 st = (w >> 9) & 1u, m = w & 15u;
if (m == 0) { if (!st && w2 >= 0x100u) S(K_LDS, d5, 0, 0, 0, 2); else if (st && w2 >= 0x100u) S(K_STS, d5, 0, 0, 0, 2); else if (w2 < 0x20u) S(st ? K_STS : K_LDS, d5, 0, 0, 0, 2); return; }
if (!st && (m == 4 || m == 5 || m == 6 || m == 7)) { S(K_LPM, d5, (m & 1u), 0, 0, 3); return; }
if (m == 15) { S(st ? K_PUSH : K_POP, d5, 0, 0, 0, 2); return; }
/* LD / ST: c = pointer register, b: 0 plain, 1 post increment, 2 pre decrement */
{ u32 p = 0, mode = 0;
switch (m) { case 1: p = 30; mode = 1; break; case 2: p = 30; mode = 2; break; case 9: p = 28; mode = 1; break; case 10: p = 28; mode = 2; break;
case 12: p = 26; break; case 13: p = 26; mode = 1; break; case 14: p = 26; mode = 2; break; default: return; }
S(st ? K_ST : K_LD, d5, mode, st ? FC | FZ | FN | FV : 0, 0, 2); x->c = (u8)p; return; }
}
case 2:
switch (w & 15u) {
case 0: S(K_COM, d5, 0, 0, FC | FZ | FN | FV, 1); return;
case 1: S(K_NEG, d5, 0, 0, FALL, 1); return;
case 2: S(K_SWAP, d5, 0, 0, 0, 1); return;
case 3: S(K_INC, d5, 0, 0, FZ | FN | FV, 1); return;
case 5: S(K_ASR, d5, 0, 0, FC | FZ | FN | FV, 1); return;
case 6: S(K_LSR, d5, 0, 0, FC | FZ | FN | FV, 1); return;
case 7: S(K_ROR, d5, 0, FC, FC | FZ | FN | FV, 1); return;
case 10: S(K_DEC, d5, 0, 0, FZ | FN | FV, 1); return;
case 12: case 13: case 14: case 15: {
u32 k = ((((w >> 4) & 31u) << 1 | (w & 1u)) << 16 | w2) & 0x3FFFu;
x->k = (w & 2u) ? K_CALL : K_JMP; x->use = 0; x->def = 0; x->cyc = (w & 2u) ? 4 : 3; x->c = 0; x->w2 = (u16)k; return;
}
case 8:
if (w == 0x9508u) { x->k = K_RET; x->use = 0; x->def = 0; x->cyc = 4; return; }
if (w == 0x9518u) { x->k = K_RETI; x->use = 0; x->def = 0; x->cyc = 4; return; }
if (w == 0x95C8u || w == 0x95D8u) { S(K_LPM, 0, 0, 0, 0, 3); return; } /* LPM r0, Z */
if (w == 0x94F8u) { S(K_CLI, 0, 0, 0, 0, 1); return; }
if ((w & 0xFF0Fu) == 0x9408u && !(w & 0x80u) && ((w >> 4) & 7u) < 6u) return; /* SEC ... : in C */
return;
case 9:
if (w == 0x9409u || w == 0x9419u) { x->k = K_IJMP; x->use = 0; x->def = 0; x->cyc = 2; return; }
if (w == 0x9509u || w == 0x9519u) { x->k = K_ICALL; x->use = 0; x->def = 0; x->cyc = 3; return; }
return;
default: return;
}
case 3: S((w & 0x0100u) ? K_SBIW : K_ADIW, 24u + ((w >> 3) & 6u), ((w >> 2) & 0x30u) | (w & 15u), 0, FC | FZ | FN | FV, 2); return;
case 4: case 5:
if (w & 0x0100u) { x->k = K_SKIPIO; x->cyc = 1; x->use = 0; x->def = 0; } /* SBIC, SBIS: in C, then a skip */
else { x->k = K_BITIO; x->cyc = 2; x->use = 0; x->def = 0; } /* SBI, CBI */
return;
default: S(K_MUL, d5, r5, 0, FC | FZ, 2); return;
}
case 0xB: {
u32 a = 0x20u + ((w & 15u) | ((w >> 5) & 0x30u));
if (a == SPL || a == SPH) { S((w & 0x0800u) ? K_OUTSP : K_INSP, d5, a, 0, 0, 1); return; }
if (a != SREG) { S((w & 0x0800u) ? K_OUT : K_IN, d5, a, 0, 0, 1); return; } /* I/O without the flags */
return; /* SREG: in C */
}
case 0xC: { s32 k = (s32)(w << 20) >> 20; x->k = K_RJMP; x->use = 0; x->def = 0; x->cyc = 2; x->w2 = (u16)((pc + 1 + (u32)k) & 0x3FFFu); return; }
case 0xD: { s32 k = (s32)(w << 20) >> 20; x->k = K_RCALL; x->use = 0; x->def = 0; x->cyc = 3; x->w2 = (u16)((pc + 1 + (u32)k) & 0x3FFFu); return; }
case 0xE: S(K_LDI, d4, K8, 0, 0, 1); return;
default:
if ((w & 0x0800u) == 0) { /* BRBS / BRBC: a = flag bit, b = 1 when "clear" */
s32 k = (s32)(w << 22) >> 25; u32 b = w & 7u;
static const u8 U[8] = { FC, FZ, FN, FV, FN | FV, FH, 0, 0 };
x->k = K_BR; x->a = (u8)b; x->b = (u8)((w >> 10) & 1u); x->use = U[b]; x->def = 0; x->cyc = 1; x->w2 = (u16)((pc + 1 + (u32)k) & 0x3FFFu);
return;
}
{ u32 m = 1u << (w & 7u);
switch ((w >> 9) & 3u) {
case 0: S(K_BLD, d5, m, 0, 0, 1); return;
case 1: S(K_BST, d5, m, 0, 0, 1); return;
case 2: S(K_SBRC, d5, m, 0, 0, 1); return;
default: S(K_SBRS, d5, m, 0, 0, 1); return;
}
}
}
#undef S
}
static int ends_block(u32 k) { return k >= K_RJMP; }
/* ---------------- C helpers called from translated code ---------------- */
#define CTX_SR() ((JC[J_SR] & 0xC0u) | (JC[J_FC] & 1u) | (JC[J_FZ] ? 0u : 2u) | ((JC[J_FN] >> 5) & 4u) | ((JC[J_FV] >> 4) & 8u) | (((JC[J_FN] ^ JC[J_FV]) >> 3) & 16u) | ((JC[J_FH] << 1) & 32u))
static void ctx_srset(u32 x) { JC[J_SR] = x & 0xC0u; JC[J_FC] = x & 1u; JC[J_FZ] = (x & 2u) ? 0u : 1u; JC[J_FN] = (x & 4u) << 5; JC[J_FV] = (x & 8u) << 4; JC[J_FH] = (x & 32u) >> 1; }
static u32 g_jlim; /* the event cycle of this run (A_CYC = g_jlim - left) */
#define JCYC() (g_jlim - JC[J_LEFT])
/* SREG written (I may come on): returns 1 when an interrupt is due now (leave for C, one instruction first) */
static u32 sr_write(u32 v)
{
u32 on = v & ~JC[J_SR] & I_FLAG; ctx_srset(v);
if (on && irq_now()) { g_hold = 1; return 1; }
return 0;
}
static u32 j_rd(u32 a)
{
if (a >= 0x100u) return a < AVR_DATA ? A_D[a] : 0u;
if (a < 0x20u) return A_D[a];
if (a == SREG) return CTX_SR();
A_CYC = JCYC(); return io_rd(a);
}
static u32 j_wr(u32 a, u32 v)
{
if (a >= 0x100u) { if (a < AVR_DATA) A_D[a] = (u8)v; JC[J_DIRTY] = 1; return 0; }
if (a < 0x20u) { A_D[a] = (u8)v; return 0; }
if (a == SREG) return sr_write(v);
A_CYC = JCYC(); return io_wr(a, v) ? 1u : 0u;
}
/* loads and stores of the pointer instructions that hit I/O (the fast path is in the code) */
__attribute__((used)) static u32 jit_ld(u32 a) { return j_rd(a & 0xFFFFu); }
__attribute__((used)) static u32 jit_st(u32 a, u32 v) { return j_wr(a & 0xFFFFu, v & 255u); }
/* I/O without the flags (left is in the context for the time) */
__attribute__((used)) static u32 jit_in(u32 a) { A_CYC = JCYC(); return io_rd(a); }
__attribute__((used)) static u32 jit_out(u32 a, u32 v) { A_CYC = JCYC(); return io_wr(a, v) ? 1u : 0u; }
/* the display's byte (the most frequent I/O by far): as io_wr(SPDR) */
__attribute__((used)) static u32 jit_spdr(u32 v)
{
JC[J_DIRTY] = 1; A_D[SPDR] = (u8)v;
if (!(A_D[SPCR] & 0x40u)) return 0;
if (A_D[PORTD] & 0x10u) lcd_data(v); else lcd_cmd(v);
A_D[SPSR] |= 0x80u;
return (A_D[SPCR] & 0x80u) != 0;
}
/* SBI, CBI, SBIC, SBIS (the word): bit 0 leave for C, bit 1 skip */
__attribute__((used)) static u32 jit_bit(u32 w)
{
u32 a = 0x20u + ((w >> 3) & 31u), m = 1u << (w & 7u), pin = a >= PINB && a <= PORTF && (a - PINB) % 3u == 0u, fl = a >= TIFR0 && a <= TIFR4;
A_CYC = JCYC();
switch ((w >> 8) & 3u) {
case 0: return (!pin && !fl && io_wr(a, io_rd(a) & ~m)) ? 1u : 0u;
case 2: return io_wr(a, (pin || fl) ? m : io_rd(a) | m) ? 1u : 0u;
case 1: return (io_rd(a) & m) ? 0u : 2u;
default: return (io_rd(a) & m) ? 2u : 0u;
}
}
/* one rare instruction at pc, flags in the context. Returns bit 0: leave for C after it, bit 1: the condition (skip) */
__attribute__((used)) static u32 jit_op(u32 pc)
{
u32 w = A_FLASH[pc], w2 = A_FLASH[(pc + 1) & 0x3FFFu], r = 0;
u32 d5 = (w >> 4) & 31u, r5 = (w & 15u) | ((w >> 5) & 16u);
switch (w >> 12) {
case 0x0: { /* MULS, MULSU, FMUL, FMULS, FMULSU */
u32 d = 16u + ((w >> 4) & 15u), rr = 16u + (w & 15u), res, f = 0;
if ((w & 0xFF00u) == 0x0200u) res = (u32)((s32)(int8_t)A_D[d] * (s32)(int8_t)A_D[rr]);
else {
d = 16u + ((w >> 4) & 7u); rr = 16u + (w & 7u);
switch (w & 0x88u) {
case 0x00: res = (u32)((s32)(int8_t)A_D[d] * (s32)A_D[rr]); break;
case 0x08: res = (u32)A_D[d] * A_D[rr]; f = 1; break;
case 0x80: res = (u32)((s32)(int8_t)A_D[d] * (s32)(int8_t)A_D[rr]); f = 1; break;
default: res = (u32)((s32)(int8_t)A_D[d] * (s32)A_D[rr]); f = 1; break;
}
}
res &= 0xFFFFu; JC[J_FC] = res >> 15; if (f) res = (res << 1) & 0xFFFFu;
JC[J_FZ] = res; A_D[0] = (u8)res; A_D[1] = (u8)(res >> 8);
return 0;
}
case 0x9:
if ((w & 0xFE0Fu) == 0x9000u) { A_D[d5] = (u8)j_rd(w2); return 0; }
if ((w & 0xFE0Fu) == 0x9200u) return j_wr(w2, A_D[d5]);
if ((w & 0xFF0Fu) == 0x9408u) { /* BSET / BCLR */
u32 m = 1u << ((w >> 4) & 7u), v = CTX_SR();
return sr_write((w & 0x80u) ? v & ~m : v | m);
}
if (w == 0x9588u) { if (A_D[SMCR] & 1u) { g_sleep = 1; return 1; } return 0; }
if (w == 0x95A8u) { if (WDT_ON) { A_CYC = JCYC(); wdt_restart(); } return 0; }
if ((w & 0xFC00u) == 0x9800u) { /* CBI, SBI, SBIC, SBIS */
u32 a = 0x20u + ((w >> 3) & 31u), m = 1u << (w & 7u), pin = a >= PINB && a <= PORTF && (a - PINB) % 3u == 0u, fl = a >= TIFR0 && a <= TIFR4;
A_CYC = JCYC();
switch ((w >> 8) & 3u) {
case 0: if (!pin && !fl) r = io_wr(a, io_rd(a) & ~m) ? 1u : 0u; return r;
case 2: r = io_wr(a, (pin || fl) ? m : io_rd(a) | m) ? 1u : 0u; return r;
case 1: return (io_rd(a) & m) ? 0u : 2u;
default: return (io_rd(a) & m) ? 2u : 0u;
}
}
if ((w & 0xFC00u) == 0x9400u && (w & 15u) == 1u) { /* NEG (rarely needs all flags) */
u32 a = A_D[d5], res = (0u - a); A_D[d5] = (u8)res;
JC[J_FC] = (res >> 8) & 1u; JC[J_FZ] = res & 255u; JC[J_FN] = res; JC[J_FV] = a & res; JC[J_FH] = a ^ res; return 0;
}
return 0;
case 0xB: {
u32 a = 0x20u + ((w & 15u) | ((w >> 5) & 0x30u));
if (w & 0x0800u) {
u32 v = A_D[d5];
if (a == SREG) return sr_write(v);
A_CYC = JCYC(); return io_wr(a, v) ? 1u : 0u;
}
if (a == SREG) { /* IN rd, SREG: also the anchor of the busy waiting (see avr.c) */
A_D[d5] = (u8)CTX_SR();
if (AB_SPIN) {
u32 sp = A_D[SPL] | (u32)A_D[SPH] << 8;
if (pc == g_anc_pc && sp == g_anc_sp) {
if (!JC[J_DIRTY]) {
u32 cyc = JCYC(), to = g_jlim; if (g_tread && to - cyc > 512u) to = cyc + 512u;
if ((s32)(to - cyc) > 1) JC[J_LEFT] = g_jlim - to;
}
JC[J_DIRTY] = 0; g_tread = 0;
} else if (JC[J_DIRTY]) { g_anc_pc = pc; g_anc_sp = sp; JC[J_DIRTY] = 0; g_tread = 0; }
}
return 0;
}
A_CYC = JCYC(); A_D[d5] = io_rd(a); return 0;
}
case 0xF:
if ((w & 0xFE08u) == 0xFA00u) { JC[J_SR] = (JC[J_SR] & ~T_F) | ((A_D[d5] & (1u << (w & 7u))) ? T_F : 0u); return 0; }
return 0;
}
(void)r5;
return 0;
}
/* ---------------- the translator ---------------- */
static JIns g_jb[JB_MAX + 1];
/* emit: load AVR register d into host register rt */
static void ldr_avr(u32 rt, u32 d) { mem_i(LDRB_I, rt, R_D, d); }
static void str_avr(u32 rt, u32 d) { mem_i(STRB_I, rt, R_D, d); }
static u32 g_acc; /* cycles of the block not yet taken from r5 */
static void flush_cyc(void) { subs5(g_acc); g_acc = 0; }
/* call a C helper with the flags handed over (r0 = arg) */
static void sync_out(void) { subw(12, R_D, JOFF(J_LEFT)); H2(0xE880u | 12u, 0x0FE0u); }
static void sync_in(void) { subw(12, R_D, JOFF(J_LEFT)); H2(0xE890u | 12u, 0x0FE0u); }
static void call_ctx(u32 h) { ldr_ctx(12, h); blx(12); }
/* leave the block towards pc: straight to its code when it is there and cycles are left (AB_CHAIN), else through
* the dispatcher. A jump to a block not yet there is noted and set straight when that block is made. */
#define CC_GT 12u
static void exit_to(u32 pc, u32 cyc)
{
if (cyc) subs5(cyc); else H1(0x2D00u); /* the flags for the test */
u32 at = pc == g_blk_pc ? g_blk_at : g_map[pc];
if (at) { bcc_w(CC_GT, at); movw(0, pc); b_w(g_stub_disp); return; }
if (g_npend < PEND_N) { g_pend_at[g_npend] = (u16)(g_ep - g_code); g_pend_pc[g_npend++] = (u16)pc; }
movw(0, pc); b_w(g_stub_disp); H2(0xF3AFu, 0x8000u); /* nop.w: room for the patch */
}
static void chain_fix(u32 pc, u32 at)
{
u16 *keep = g_ep;
for (u32 i = 0; i < g_npend; ) {
if (g_pend_pc[i] != pc) { i++; continue; }
g_ep = g_code + g_pend_at[i]; bcc_w(CC_GT, at); movw(0, pc); b_w(g_stub_disp);
g_pend_at[i] = g_pend_at[g_npend - 1]; g_pend_pc[i] = g_pend_pc[--g_npend];
}
g_ep = keep;
}
static void exit_c(u32 pc) { movw(0, pc); b_w(g_stub_exit); }
/* flags from a result in r2 (operands in r0, r1), only those wanted */
static void fl_add(u32 want, int sticky)
{
if (want & FC) ubfx(R_FC, 2, 8, 1);
if (want & FZ) { if (sticky) { uxtb(3, 2); dp_r(DP_ORR, 0, R_FZ, R_FZ, 3, 0, 0); } else uxtb(R_FZ, 2); }
if (want & FN) mov_r(R_FN, 2);
if (want & FH) { dp_r(DP_EOR, 0, R_FH, 0, 1, 0, 0); dp_r(DP_EOR, 0, R_FH, R_FH, 2, 0, 0); }
}
static void fl_v_add(void) { dp_r(DP_EOR, 0, 3, 0, 2, 0, 0); dp_r(DP_EOR, 0, 12, 1, 2, 0, 0); dp_r(DP_AND, 0, R_FV, 3, 12, 0, 0); }
static void fl_v_sub(void) { dp_r(DP_EOR, 0, 3, 0, 1, 0, 0); dp_r(DP_EOR, 0, 12, 0, 2, 0, 0); dp_r(DP_AND, 0, R_FV, 3, 12, 0, 0); }
/* address of a data access in r0 (16 bit): r2 = the byte (load), or store r2; slow path for 0x20..0xFF */
static void data_ld(void)
{
subw(1, 0, 0x20); cmp_i(1, 0xE0); u16 *slow = bcc_fwd(CC_CC);
sat12(1, 0); mem_r(LDRB_R, 2, R_D, 1, 0); u16 *done = b_fwd();
fix_fwd(slow);
H1(0x9000u | (0u << 8) | 0); /* str r0, [sp] (keep the address) */
sync_out(); call_ctx(J_LD); mov_r(2, 0); sync_in(); H1(0x9800u); /* ldr r0, [sp] */
fix_b(done);
}
/* store r2 at the address in r0; status in r0 bit 0 (only on the slow path; fast path r0 = address >= 0x20) */
static u16 *data_st(void)
{
subw(1, 0, 0x20); cmp_i(1, 0xE0); u16 *slow = bcc_fwd(CC_CC);
sat12(1, 0); mem_r(STRB_R, 2, R_D, 1, 0);
/* dirty when below the stack pointer (data, not stack) */
mem_i(LDRH_I, 3, R_D, SPL); dp_r(DP_SUB, 1, 15, 0, 3, 0, 0); u16 *nd = bcc_fwd(CC_CS); str_ctx(R_D, J_DIRTY); fix_fwd(nd);
u16 *done = b_fwd();
fix_fwd(slow);
H1(0x9000u); sync_out(); mov_r(1, 2); call_ctx(J_ST); sync_in();
tst_i(0, 1); u16 *brk = bcc_fwd(CC_NE); H1(0x9800u);
fix_b(done);
return brk; /* the caller lets it leave for C (after the instruction) */
}
/* pointer register p (26, 28, 30) into r0, with pre decrement / post increment written back after */
static void ptr_get(u32 p, u32 mode) { mem_i(LDRH_I, 0, R_D, p); if (mode == 2) { subw(0, 0, 1); H2(0xFA1Fu, 0xF080u | (0u << 8) | 0u); mem_i(STRH_I, 0, R_D, p); } }
static void ptr_post(u32 p, u32 mode) { if (mode == 1) { mem_i(LDRH_I, 3, R_D, p); addw(3, 3, 1); mem_i(STRH_I, 3, R_D, p); } }
/* push the return address (2 bytes) */
static void push_pc(u32 ret)
{
mem_i(LDRH_I, 0, R_D, SPL); movw(2, ret);
sat12(1, 0); mem_r(STRB_R, 2, R_D, 1, 0);
subw(1, 0, 1); sat12(1, 1); mov_sh(2, 2, SH_LSR, 8); mem_r(STRB_R, 2, R_D, 1, 0);
subw(0, 0, 2); mem_i(STRH_I, 0, R_D, SPL);
}
/* pop a return address into r0 */
static void pop_pc(void)
{
mem_i(LDRH_I, 0, R_D, SPL);
addw(1, 0, 1); sat12(1, 1); mem_r(LDRB_R, 2, R_D, 1, 0);
addw(1, 0, 2); sat12(1, 1); mem_r(LDRB_R, 3, R_D, 1, 0);
addw(0, 0, 2); mem_i(STRH_I, 0, R_D, SPL);
dp_r(DP_ORR, 0, 0, 3, 2, SH_LSL, 8); ubfx(0, 0, 0, 14);
}
/* one block from pc; returns the code's halfword offset (0: no room) */
static u32 xlate(u32 pc)
{
u32 n = 0;
while (n < JB_MAX) {
JIns *x = &g_jb[n]; jdec(pc, x); n++;
if (ends_block(x->k)) break;
pc = (pc + x->len) & 0x3FFFu;
if (pc == 0) break;
}
/* which flags are read later: at the end C, Z, N, V (H only inside a block) */
u32 live = FC | FZ | FN | FV;
for (u32 i = n; i-- > 0; ) { g_jb[i].live = (u8)live; live = (live & ~g_jb[i].def) | g_jb[i].use; }
u16 *start = g_ep; g_acc = 0; g_blk_pc = g_jb[0].pc; g_blk_at = (u32)(start - g_code);
for (u32 i = 0; i < n; i++) {
JIns *x = &g_jb[i]; u32 want = x->def & x->live, next = (x->pc + x->len) & 0x3FFFu;
g_acc += x->cyc;
switch (x->k) {
case K_NOP: break;
case K_LDI: movw(0, x->b); str_avr(0, x->a); break;
case K_MOV: ldr_avr(0, x->b); str_avr(0, x->a); break;
case K_MOVW: mem_i(LDRH_I, 0, R_D, x->b); mem_i(STRH_I, 0, R_D, x->a); break;
case K_ADD: case K_ADC:
ldr_avr(0, x->a); ldr_avr(1, x->b); dp_r(DP_ADD, 0, 2, 0, 1, 0, 0);
if (x->k == K_ADC) dp_r(DP_ADD, 0, 2, 2, R_FC, 0, 0);
str_avr(2, x->a); if (want & FV) fl_v_add(); fl_add(want, 0); break;
case K_SUB: case K_SBC: case K_CP: case K_CPC: case K_SUBI: case K_SBCI: case K_CPI: {
int imm = x->k == K_SUBI || x->k == K_SBCI || x->k == K_CPI, carry = x->k == K_SBC || x->k == K_CPC || x->k == K_SBCI;
int store = x->k == K_SUB || x->k == K_SBC || x->k == K_SUBI || x->k == K_SBCI;
ldr_avr(0, x->a); if (imm) movw(1, x->b); else ldr_avr(1, x->b);
dp_r(DP_SUB, 0, 2, 0, 1, 0, 0); if (carry) dp_r(DP_SUB, 0, 2, 2, R_FC, 0, 0);
if (store) str_avr(2, x->a);
if (want & FV) fl_v_sub(); fl_add(want, carry); break;
}
case K_AND: case K_OR: case K_EOR: case K_ANDI: case K_ORI:
ldr_avr(0, x->a);
if (x->k == K_ANDI || x->k == K_ORI) dp_i(x->k == K_ANDI ? DI_AND : DI_ORR, 0, 2, 0, x->b);
else { ldr_avr(1, x->b); dp_r(x->k == K_AND ? DP_AND : x->k == K_OR ? DP_ORR : DP_EOR, 0, 2, 0, 1, 0, 0); }
str_avr(2, x->a);
if (want & FZ) mov_r(R_FZ, 2); if (want & FN) mov_r(R_FN, 2); if (want & FV) movw(R_FV, 0); break;
case K_COM:
ldr_avr(0, x->a); dp_i(DI_EOR, 0, 2, 0, 0xFF); str_avr(2, x->a);
if (want & FC) movw(R_FC, 1); if (want & FZ) mov_r(R_FZ, 2); if (want & FN) mov_r(R_FN, 2); if (want & FV) movw(R_FV, 0); break;
case K_NEG:
ldr_avr(1, x->a); movw(0, 0); dp_r(DP_SUB, 0, 2, 0, 1, 0, 0); str_avr(2, x->a);
if (want & FV) fl_v_sub(); fl_add(want, 0); break;
case K_SWAP:
ldr_avr(0, x->a); mov_sh(1, 0, SH_LSR, 4); dp_r(DP_ORR, 0, 2, 1, 0, SH_LSL, 4); str_avr(2, x->a); break;
case K_INC: case K_DEC:
ldr_avr(0, x->a); if (x->k == K_INC) addw(2, 0, 1); else subw(2, 0, 1); uxtb(2, 2); str_avr(2, x->a);
if (want & FV) { if (x->k == K_INC) dp_r(DP_BIC, 0, R_FV, 2, 0, 0, 0); else dp_r(DP_BIC, 0, R_FV, 0, 2, 0, 0); }
if (want & FZ) mov_r(R_FZ, 2); if (want & FN) mov_r(R_FN, 2); break;
case K_ASR: case K_LSR: case K_ROR:
ldr_avr(0, x->a);
if (x->k == K_LSR) mov_sh(2, 0, SH_LSR, 1);
else if (x->k == K_ASR) { dp_i(DI_AND, 0, 2, 0, 0x80); dp_r(DP_ORR, 0, 2, 2, 0, SH_LSR, 1); }
else { mov_sh(2, 0, SH_LSR, 1); dp_r(DP_ORR, 0, 2, 2, R_FC, SH_LSL, 7); }
str_avr(2, x->a);
dp_i(DI_AND, 0, R_FC, 0, 1); /* C always (ROR reads it next) */
if (want & FZ) mov_r(R_FZ, 2); if (want & FN) mov_r(R_FN, 2);
if (want & FV) dp_r(DP_EOR, 0, R_FV, 2, R_FC, SH_LSL, 7);
break;
case K_ADIW: case K_SBIW:
mem_i(LDRH_I, 0, R_D, x->a);
if (x->k == K_ADIW) addw(2, 0, x->b); else subw(2, 0, x->b);
H2(0xFA1Fu, 0xF080u | (2u << 8) | 2u); /* uxth r2, r2 */
mem_i(STRH_I, 2, R_D, x->a);
if (want & FZ) mov_r(R_FZ, 2); if (want & FN) mov_sh(R_FN, 2, SH_LSR, 8);
if (want & FC) { if (x->k == K_ADIW) dp_r(DP_BIC, 0, 3, 0, 2, 0, 0); else dp_r(DP_BIC, 0, 3, 2, 0, 0, 0); ubfx(R_FC, 3, 15, 1); }
if (want & FV) { if (x->k == K_ADIW) dp_r(DP_BIC, 0, 3, 2, 0, 0, 0); else dp_r(DP_BIC, 0, 3, 0, 2, 0, 0); mov_sh(R_FV, 3, SH_LSR, 8); }
break;
case K_MUL:
ldr_avr(0, x->a); ldr_avr(1, x->b); mul(2, 0, 1); mem_i(STRH_I, 2, R_D, 0);
if (want & FC) ubfx(R_FC, 2, 15, 1); if (want & FZ) mov_r(R_FZ, 2); break;
case K_LDS: case K_STS:
if (x->w2 >= 0x100u || x->w2 < 0x20u) {
u32 ad = x->w2 & 0xFFFu;
if (x->k == K_LDS) { mem_i(LDRB_I, 0, R_D, ad); str_avr(0, x->a); }
else { ldr_avr(0, x->a); mem_i(STRB_I, 0, R_D, ad); if (x->w2 >= 0x100u) str_ctx(R_D, J_DIRTY); }
break;
}
goto help;
case K_LDD: case K_STD:
flush_cyc();
mem_i(LDRH_I, 0, R_D, x->c); if (x->b) addw(0, 0, x->b);
if (x->k == K_LDD) { data_ld(); str_avr(2, x->a); }
else { ldr_avr(2, x->a); u16 *brk = data_st(); u16 *ok = b_fwd(); fix_fwd(brk); exit_c(next); fix_b(ok); }
break;
case K_LD: case K_ST:
flush_cyc();
ptr_get(x->c, x->b);
if (x->k == K_LD) { data_ld(); str_avr(2, x->a); ptr_post(x->c, x->b); }
else { ldr_avr(2, x->a); u16 *brk = data_st(); ptr_post(x->c, x->b); u16 *ok = b_fwd(); fix_fwd(brk); ptr_post(x->c, x->b); exit_c(next); fix_b(ok); }
break;
case K_LPM:
mem_i(LDRH_I, 0, R_D, 30); ubfx(1, 0, 0, 15); ldr_ctx(3, J_FLASH); mem_r(LDRB_R, 2, 3, 1, 0);
str_avr(2, x->a);
if (x->b) { addw(0, 0, 1); mem_i(STRH_I, 0, R_D, 30); }
break;
case K_PUSH:
mem_i(LDRH_I, 0, R_D, SPL); sat12(1, 0); ldr_avr(2, x->a); mem_r(STRB_R, 2, R_D, 1, 0);
subw(0, 0, 1); mem_i(STRH_I, 0, R_D, SPL); break;
case K_POP:
mem_i(LDRH_I, 0, R_D, SPL); addw(0, 0, 1); mem_i(STRH_I, 0, R_D, SPL); sat12(1, 0); mem_r(LDRB_R, 2, R_D, 1, 0); str_avr(2, x->a); break;
case K_INSP: mem_i(LDRB_I, 0, R_D, x->b); str_avr(0, x->a); break;
case K_IN:
if (x->b == SPSR || (x->b >= PINB && x->b <= PINF && (x->b - PINB) % 3u == 0u)) { mem_i(LDRB_I, 0, R_D, x->b); str_avr(0, x->a); break; } /* kept current in D */
flush_cyc(); str_ctx(R_LEFT, J_LEFT); movw(0, x->b); call_ctx(J_IN); str_avr(0, x->a); break;
case K_OUT:
if (x->b == SPDR) { ldr_avr(0, x->a); call_ctx(J_SPDR); tst_i(0, 1); { u16 *ok = bcc_fwd(CC_EQ); flush_cyc(); exit_c(next); fix_fwd(ok); } break; }
flush_cyc(); str_ctx(R_LEFT, J_LEFT); movw(0, x->b); ldr_avr(1, x->a); call_ctx(J_OUT);
tst_i(0, 1); { u16 *ok = bcc_fwd(CC_EQ); exit_c(next); fix_fwd(ok); } break;
case K_BITIO: flush_cyc(); str_ctx(R_LEFT, J_LEFT); movw(0, x->w); call_ctx(J_BIT);
tst_i(0, 1); { u16 *ok = bcc_fwd(CC_EQ); exit_c(next); fix_fwd(ok); } break;
case K_CLI: dp_i(DI_AND, 0, R_SR, R_SR, 0x7F); break;
case K_OUTSP: ldr_avr(0, x->a); mem_i(STRB_I, 0, R_D, x->b); break;
case K_BST:
ldr_avr(0, x->a); tst_i(0, x->b); dp_i(DI_AND, 0, R_SR, R_SR, 0xBF);
{ u16 *z = bcc_fwd(CC_EQ); dp_i(DI_ORR, 0, R_SR, R_SR, 0x40); fix_fwd(z); }
break;
case K_BLD:
ldr_avr(0, x->a); dp_i(DI_AND, 0, 0, 0, (~x->b) & 0xFFu); tst_i(R_SR, 0x40);
{ u16 *z = bcc_fwd(CC_EQ); dp_i(DI_ORR, 0, 0, 0, x->b); fix_fwd(z); }
str_avr(0, x->a); break;
/* ---- block ends ---- */
case K_RJMP: case K_JMP: exit_to(x->w2, g_acc); g_acc = 0; break;
case K_RCALL: case K_CALL: push_pc(next); exit_to(x->w2, g_acc); g_acc = 0; break;
case K_RET: pop_pc(); subs5(g_acc); g_acc = 0; b_w(g_stub_disp); break;
case K_RETI: pop_pc(); subs5(g_acc); g_acc = 0; dp_i(DI_ORR, 0, R_SR, R_SR, 0x80); str_ctx(R_D, J_SPARE); b_w(g_stub_exit); break; /* C: one instruction, then the interrupts */
case K_IJMP: case K_ICALL:
if (x->k == K_ICALL) push_pc(next);
mem_i(LDRH_I, 0, R_D, 30); ubfx(0, 0, 0, 14); subs5(g_acc); g_acc = 0; b_w(g_stub_disp); break;
case K_BR: {
u32 c = g_acc - x->cyc; /* not taken: 1 cycle, taken: 2 */
u16 *tk;
switch (x->a) {
case 0: H1(0x2F00u); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break; /* C: cmp r7, #0 */
case 1: H1(0x2E00u); tk = bcc_fwd(x->b ? CC_NE : CC_EQ); break; /* Z: cmp r6, #0 */
case 2: tst_i(R_FN, 0x80); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break;
case 3: tst_i(R_FV, 0x80); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break;
case 4: dp_r(DP_EOR, 0, 0, R_FN, R_FV, 0, 0); tst_i(0, 0x80); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break;
case 5: tst_i(R_FH, 0x10); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break;
case 6: tst_i(R_SR, 0x40); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break;
default: tst_i(R_SR, 0x80); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break;
}
exit_to(next, c + 1);
fix_fwd(tk); exit_to(x->w2, c + 2); g_acc = 0; break;
}
case K_SBRC: case K_SBRS: case K_CPSE: {
u32 c = g_acc - x->cyc, l2 = two_w(A_FLASH[next]) ? 2u : 1u;
u16 *sk;
if (x->k == K_CPSE) { ldr_avr(0, x->a); ldr_avr(1, x->b); dp_r(DP_SUB, 1, 15, 0, 1, 0, 0); sk = bcc_fwd(CC_EQ); }
else { ldr_avr(0, x->a); tst_i(0, x->b); sk = bcc_fwd(x->k == K_SBRC ? CC_EQ : CC_NE); }
exit_to(next, c + 1);
fix_fwd(sk); exit_to((next + l2) & 0x3FFFu, c + 1 + l2); g_acc = 0; break;
}
case K_SKIPIO: {
u32 c = g_acc - x->cyc, l2 = two_w(A_FLASH[next]) ? 2u : 1u;
subs5(c); g_acc = 0;
u32 ia = 0x20u + ((x->w >> 3) & 31u), sk_set = (x->w & 0x0200u) != 0; /* SBIS: skip when set */
u16 *sk;
if (ia == SPSR || (ia >= PINB && ia <= PINF && (ia - PINB) % 3u == 0u)) {
mem_i(LDRB_I, 0, R_D, ia); tst_i(0, 1u << (x->w & 7u)); sk = bcc_fwd(sk_set ? CC_NE : CC_EQ);
} else { str_ctx(R_LEFT, J_LEFT); movw(0, x->w); call_ctx(J_BIT); tst_i(0, 2); sk = bcc_fwd(CC_NE); }
exit_to(next, 1);
fix_fwd(sk); exit_to((next + l2) & 0x3FFFu, 1 + l2); break;
}
default:
help:
flush_cyc();
sync_out(); movw(0, x->pc); call_ctx(J_OP); sync_in();
tst_i(0, 1); { u16 *ok = bcc_fwd(CC_EQ); exit_c(next); fix_fwd(ok); }
break;
}
if (g_ep >= g_cend - 64) return 0;
}
if (!ends_block(g_jb[n - 1].k)) { u32 nx = (g_jb[n - 1].pc + g_jb[n - 1].len) & 0x3FFFu; exit_to(nx, g_acc); g_acc = 0; }
if (g_ep >= g_cend - 8) return 0;
return (u32)(start - g_code);
}
/* called by the dispatcher: translate the block at pc (empty the cache when full), returns pc */
__attribute__((used)) static u32 jit_xlate(u32 pc)
{
pc &= 0x3FFFu;
u32 at = xlate(pc);
if (!at) { jit_flush(); at = xlate(pc); }
g_map[pc] = (u16)at; g_blk_pc = 0xFFFFFFFFu;
chain_fix(pc, at);
#ifdef __arm__
__asm__ volatile("dsb\n isb" ::: "memory");
#endif
return pc;
}
static void jit_init(void)
{
JC[J_XLATE] = (u32)(uintptr_t)jit_xlate; JC[J_OP] = (u32)(uintptr_t)jit_op; JC[J_LD] = (u32)(uintptr_t)jit_ld; JC[J_ST] = (u32)(uintptr_t)jit_st;
JC[J_IN] = (u32)(uintptr_t)jit_in; JC[J_OUT] = (u32)(uintptr_t)jit_out; JC[J_BIT] = (u32)(uintptr_t)jit_bit; JC[J_SPDR] = (u32)(uintptr_t)jit_spdr;
JC[J_MAP] = (u32)(uintptr_t)g_map; JC[J_CODE1] = (u32)(uintptr_t)g_code | 1u; JC[J_FLASH] = (u32)(uintptr_t)A_FLASH;
jit_flush();
}
u8 *ab_scratch(void) { jit_flush(); return (u8 *)g_code + JIT_CACHE - AB_SCRATCH; }
void ab_load(const u16 *flash, u32 words)
{
A_FLASH = flash; g_words = words;
jit_init();
}
#ifdef AB_JIT_HOST
u16 *jit_code(u32 *n) { *n = (u32)(g_ep - g_code); return g_code; }
u32 jit_x(u32 pc) { return jit_xlate(pc); }
u32 jit_at(u32 pc) { return g_map[pc]; }
#endif
AVR_FAST void ab_run(u32 cycles)
{
u32 end = A_CYC + cycles, pc = g_pc, lim, v;
pins_upd(); /* the buttons */
#ifdef AB_JIT_HOST
void (*enter)(void) = 0; (void)enter; return;
#else
void (*enter)(void) = (void (*)(void))((uintptr_t)(g_code + g_stub_enter) | 1u);
#endif
for (;;) {
g_rst = 0; ev_sync(); if (g_rst) pc = 0;
if (g_hold) g_hold = 0; /* after SEI, RETI: one more instruction first */
else if ((A_D[SREG] & I_FLAG) && (v = irq_now())) {
irq_ack(v);
if (g_sleep) { g_sleep = 0; A_CYC += 4; }
{ u32 s = A_D[SPL] | (u32)A_D[SPH] << 8;
A_D[s & 0xFFFu] = (u8)pc; s--; A_D[s & 0xFFFu] = (u8)(pc >> 8); s--; A_D[SPL] = (u8)s; A_D[SPH] = (u8)(s >> 8); }
A_D[SREG] &= ~I_FLAG; pc = v * 2u; A_CYC += 5;
}
if ((s32)(A_CYC - end) >= 0) break;
lim = ev_next(); lim = lim < end - A_CYC ? A_CYC + lim : end;
if (g_sleep) { A_CYC = lim; continue; }
g_jlim = lim; JC[J_LEFT] = lim - A_CYC; JC[J_PC] = pc; ctx_srset(A_D[SREG]);
enter();
A_CYC = g_jlim - JC[J_LEFT]; A_D[SREG] = (u8)CTX_SR(); pc = JC[J_PC] & 0x3FFFu;
if (JC[J_SPARE]) { JC[J_SPARE] = 0; g_hold = 1; }
}
g_pc = pc;
}
+181
View File
@@ -0,0 +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())
+92
View File
@@ -0,0 +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;
}
+63
View File
@@ -0,0 +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;
}
+10
View File
@@ -0,0 +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
+9
View File
@@ -0,0 +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]))
+83
View File
@@ -0,0 +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])
+13
View File
@@ -0,0 +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");
}
+10
View File
@@ -0,0 +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
+5
View File
@@ -0,0 +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)
+52
View File
@@ -0,0 +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;
}
+25
View File
@@ -0,0 +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)
+19
View File
@@ -0,0 +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))
+15
View File
@@ -0,0 +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))
+23
View File
@@ -0,0 +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))