Files
Basys3Terminal/monitor/monitor.c
T
brad ArantandClaude Opus 5.5 fe1daf180d Monitor: Z-80 assembler (ASM "file", A addr)
Two-pass table-driven assembler in the monitor: assembles BASIC-saved
source files from the file system, or one line at a time with A addr.
Labels, EQU/ORG/DB/DW/DS/END, expressions. Table generated from the
disassembler (tools/gen-asmtab.py); round-trip and sdasz80 tests, plus a
Z-80 build run in z80emu. Monitor RAM grows to 6000-7FFF for the symbol
table. Works around an SDCC 4.5 inline strcpy bug with s_copy().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:42:42 -08:00

1146 lines
35 KiB
C

/* Machine-code monitor for the Basys 3 Z-80.
*
* Entered by an NMI (the Pause key, BASIC's MONITOR, a breakpoint or a single
* step), with the monitor's bank in place of 0000-7FFF. It shows the
* registers, a disassembly from the PC, the stack and a memory dump on the
* terminal's alternate screen, and takes commands on the bottom line.
*
* The program's memory below 8000h is hidden by the bank, so it is read
* through the debug port (62h-64h); from 8000h up it is read directly. The
* program's AF and PC sit on its stack (pushed by the NMI and the trampoline).
*/
#include <stdint.h>
#include <string.h>
#include <setjmp.h>
typedef uint8_t u8;
typedef uint16_t u16;
typedef int16_t i16;
typedef uint32_t u32;
typedef int32_t i32;
#ifdef __SDCC
__sfr __at 0x00 con_stat;
__sfr __at 0x01 con_data;
__sfr __at 0x60 mon_ctl;
__sfr __at 0x62 dbg_lo;
__sfr __at 0x63 dbg_hi;
__sfr __at 0x64 dbg_dat;
__sfr __at 0x65 bp0_lo;
__sfr __at 0x66 bp0_hi;
__sfr __at 0x67 bp_ctl;
__sfr __at 0x68 bp1_lo;
__sfr __at 0x69 bp1_hi;
__sfr __at 0x10 tim0;
__sfr __at 0x11 tim1;
__sfr __at 0x12 tim2;
__sfr __at 0x13 tim3;
__sfr __at 0x40 fl_ctl;
__sfr __at 0x41 fl_dat;
/* BASIC's clock (set by DATE), kept at a fixed address in its RAM */
#define CLK_SEC (*(volatile u32 *)0xF3F8)
#define CLK_MS (*(volatile i32 *)0xF3FC)
/* saved by crt0.s at 7F00h */
struct regs {
u16 sp, bc, de, hl, ix, iy, af2, bc2, de2, hl2;
u8 i, r, exit;
};
extern struct regs u;
static void putc_(char c) { while (!(con_stat & 2)); con_data = c; }
static u8 getk(void) { while (!(con_stat & 1)); return con_data; }
static u8 rd(u16 a)
{
if (a & 0x8000) return *(volatile u8 *)a;
dbg_lo = a; dbg_hi = a >> 8;
return dbg_dat;
}
static u8 wr(u16 a, u8 v)
{
if (!(a & 0x8000)) return 0;
*(volatile u8 *)a = v;
return 1;
}
#else
/* host build: only for testing the disassembler (see disasm_test) */
#include <stdio.h>
static u8 hostmem[65536];
static void putc_(char c) { putchar(c); }
static u8 rd(u16 a) { return hostmem[a]; }
#endif
/* SDCC 4.5 expands strcpy inline with A as scratch, and can lose a value it
had parked in A (seen as a wrong pointer to the next call), so copy with a
real function. */
static void s_copy(char *d, const char *s) { while ((*d++ = *s++)); }
/* ------------------------------------------------------------ text out */
static char line[96];
static char *lp;
static void s_ch(char c) { *lp++ = c; }
static void s_str(const char *s) { while (*s) *lp++ = *s++; }
static const char hexd[] = "0123456789ABCDEF";
static void s_h2(u8 v) { s_ch(hexd[v >> 4]); s_ch(hexd[v & 15]); }
static void s_h4(u16 v) { s_h2(v >> 8); s_h2(v); }
/* assembler style: 3EH, 0FFH, 1234H, 0C000H */
static void s_lit8(u8 v) { if (v >= 0xA0) s_ch('0'); s_h2(v); s_ch('H'); }
#ifdef __SDCC
#define s_n8 s_lit8
static void s_n16(u16 v) { if (v >= 0xA000) s_ch('0'); s_h4(v); s_ch('H'); }
#else
/* host build: symbolic mode prints operand kinds (n, nn, e, d) instead of
numbers, for tools/gen-asmtab.py */
static u8 symb;
static void s_n8(u8 v) { if (symb) s_ch('n'); else s_lit8(v); }
static void s_n16(u16 v) { if (symb) s_str("nn"); else { if (v >= 0xA000) s_ch('0'); s_h4(v); s_ch('H'); } }
#endif
/* ---------------------------------------------------------- disassembler */
static u16 da; /* next byte to decode */
static u8 ixm; /* 0 HL, 1 IX, 2 IY */
static u8 ixd; /* displacement for DDCB */
static u8 nb(void) { return rd(da++); }
static const char *const r8n[] = { "B", "C", "D", "E", "H", "L", "(HL)", "A" };
static const char *const ccn[] = { "NZ", "Z", "NC", "C", "PO", "PE", "P", "M" };
static const char *const alun[] = { "ADD A,", "ADC A,", "SUB ", "SBC A,", "AND ", "XOR ", "OR ", "CP " };
static const char *const rotn[] = { "RLC ", "RRC ", "RL ", "RR ", "SLA ", "SRA ", "SLL ", "SRL " };
static const char *const blkn[] = {
"LDI", "CPI", "INI", "OUTI", "LDD", "CPD", "IND", "OUTD",
"LDIR", "CPIR", "INIR", "OTIR", "LDDR", "CPDR", "INDR", "OTDR" };
static const char *const op7n[] = { "RLCA", "RRCA", "RLA", "RRA", "DAA", "CPL", "SCF", "CCF" };
static void s_hl(void) { s_str(ixm == 0 ? "HL" : ixm == 1 ? "IX" : "IY"); }
static void s_disp(u8 d)
{
#ifndef __SDCC
if (symb) { s_str("+d"); return; }
#endif
if (d & 0x80) { s_ch('-'); d = -d; } else s_ch('+');
s_lit8(d);
}
static void s_ind(void) /* (HL) or (IX+d), reading d */
{
if (!ixm) { s_str("(HL)"); return; }
s_ch('('); s_hl(); s_disp(nb()); s_ch(')');
}
/* register r; mem = the instruction also uses (HL), so H and L stay H and L */
static void s_r8(u8 r, u8 mem)
{
if (r == 6) s_ind();
else if (ixm && !mem && (r == 4 || r == 5)) { s_str(ixm == 1 ? "IX" : "IY"); s_ch(r == 4 ? 'H' : 'L'); }
else s_str(r8n[r]);
}
static void s_rp(u8 p) { if (p == 2) s_hl(); else s_str(p == 0 ? "BC" : p == 1 ? "DE" : "SP"); }
static void s_rp2(u8 p) { if (p == 3) s_str("AF"); else s_rp(p); }
static void s_nn(void) { u16 v = nb(); v |= (u16)nb() << 8; s_n16(v); }
static void s_rel(void)
{
i16 d = (int8_t)nb();
#ifndef __SDCC
if (symb) { s_ch('e'); return; }
#endif
s_n16(da + d);
}
static void dis_cb(u8 op)
{
u8 x = op >> 6, y = (op >> 3) & 7, z = op & 7;
if (x == 0) s_str(rotn[y]);
else { s_str(x == 1 ? "BIT " : x == 2 ? "RES " : "SET "); s_ch('0' + y); s_ch(','); }
if (ixm) {
s_ch('('); s_hl(); s_disp(ixd); s_ch(')');
if (z != 6 && x != 1) { s_ch(','); s_str(r8n[z]); } /* undocumented copy */
} else s_str(r8n[z]);
}
static void dis_ed(u8 op)
{
u8 x = op >> 6, y = (op >> 3) & 7, z = op & 7, p = y >> 1, q = y & 1;
if (x == 1) switch (z) {
case 0: s_str("IN "); if (y != 6) { s_str(r8n[y]); s_ch(','); } s_str("(C)"); return;
case 1: s_str("OUT (C),"); s_str(y == 6 ? "0" : r8n[y]); return;
case 2: s_str(q ? "ADC HL," : "SBC HL,"); s_rp(p); return;
case 3:
s_str("LD ");
if (q) { s_rp(p); s_ch(','); s_ch('('); s_nn(); s_ch(')'); }
else { s_ch('('); s_nn(); s_str("),"); s_rp(p); }
return;
case 4: s_str("NEG"); return;
case 5: s_str(y == 1 ? "RETI" : "RETN"); return;
case 6: s_str("IM "); s_ch("0012"[y & 3]); return;
case 7: {
static const char *const n7[] = { "LD I,A", "LD R,A", "LD A,I", "LD A,R", "RRD", "RLD", "NOP*", "NOP*" };
s_str(n7[y]); return;
}
}
if (x == 2 && z <= 3 && y >= 4) { s_str(blkn[(y - 4) * 4 + z]); return; }
s_str("NOP*");
}
static void dis_main(u8 op)
{
u8 x = op >> 6, y = (op >> 3) & 7, z = op & 7, p = y >> 1, q = y & 1;
switch (x) {
case 0:
switch (z) {
case 0:
if (y == 0) s_str("NOP");
else if (y == 1) s_str("EX AF,AF'");
else if (y == 2) { s_str("DJNZ "); s_rel(); }
else if (y == 3) { s_str("JR "); s_rel(); }
else { s_str("JR "); s_str(ccn[y - 4]); s_ch(','); s_rel(); }
return;
case 1:
if (!q) { s_str("LD "); s_rp(p); s_ch(','); s_nn(); }
else { s_str("ADD "); s_hl(); s_ch(','); s_rp(p); }
return;
case 2: {
static const char *const m[] = { "(BC)", "(DE)" };
s_str("LD ");
if (!q) {
if (p < 2) { s_str(m[p]); s_str(",A"); }
else { s_ch('('); s_nn(); s_str("),"); if (p == 2) s_hl(); else s_ch('A'); }
} else {
if (p < 2) { s_str("A,"); s_str(m[p]); }
else { if (p == 2) s_hl(); else s_ch('A'); s_str(",("); s_nn(); s_ch(')'); }
}
return;
}
case 3: s_str(q ? "DEC " : "INC "); s_rp(p); return;
case 4: s_str("INC "); s_r8(y, 0); return;
case 5: s_str("DEC "); s_r8(y, 0); return;
case 6: s_str("LD "); s_r8(y, 0); s_ch(','); s_n8(nb()); return;
default: s_str(op7n[y]); return;
}
case 1:
if (op == 0x76) { s_str("HALT"); return; }
s_str("LD "); s_r8(y, z == 6); s_ch(','); s_r8(z, y == 6);
return;
case 2:
s_str(alun[y]); s_r8(z, 0);
return;
default:
switch (z) {
case 0: s_str("RET "); s_str(ccn[y]); return;
case 1:
if (!q) { s_str("POP "); s_rp2(p); }
else if (p == 0) s_str("RET");
else if (p == 1) s_str("EXX");
else if (p == 2) { s_str("JP ("); s_hl(); s_ch(')'); }
else { s_str("LD SP,"); s_hl(); }
return;
case 2: s_str("JP "); s_str(ccn[y]); s_ch(','); s_nn(); return;
case 3:
switch (y) {
case 0: s_str("JP "); s_nn(); return;
case 2: s_str("OUT ("); s_n8(nb()); s_str("),A"); return;
case 3: s_str("IN A,("); s_n8(nb()); s_ch(')'); return;
case 4: s_str("EX (SP),"); s_hl(); return;
case 5: s_str("EX DE,HL"); return;
case 6: s_str("DI"); return;
default: s_str("EI"); return;
}
case 4: s_str("CALL "); s_str(ccn[y]); s_ch(','); s_nn(); return;
case 5:
if (!q) { s_str("PUSH "); s_rp2(p); }
else { s_str("CALL "); s_nn(); }
return;
case 6: s_str(alun[y]); s_n8(nb()); return;
default: s_str("RST "); s_lit8(y * 8); return;
}
}
}
/* Disassemble the instruction at a into line (from lp); returns its length. */
static u8 disasm(u16 a)
{
u8 op;
da = a;
ixm = 0;
op = nb();
if (op == 0xDD || op == 0xFD) {
u8 n = rd(da);
if (n == 0xDD || n == 0xFD || n == 0xED) { /* a prefix doing nothing */
s_str("DB "); s_n8(op);
return 1;
}
ixm = op == 0xDD ? 1 : 2;
op = nb();
}
if (op == 0xCB) {
if (ixm) { ixd = nb(); dis_cb(nb()); }
else dis_cb(nb());
} else if (op == 0xED) dis_ed(nb());
else dis_main(op);
return da - a;
}
#include "asm.c"
#ifndef __SDCC
static void a_out(u16 addr, u8 b) { hostmem[addr] = b; }
/* Host test of the assembler: "line" assembles each stdin line alone at
address 0 and prints its bytes; "file" assembles stdin as one program in
two passes and prints address and bytes per line, or the error. */
static int asm_test(int file)
{
static char src[2000][128];
u16 n = 0, i;
u8 p;
while (n < 2000 && fgets(src[n], sizeof src[n], stdin)) {
src[n][strcspn(src[n], "\r\n")] = 0;
a_upper(src[n]);
n++;
}
if (!file) {
a_pass = 2;
for (i = 0; i < n; i++) {
char t[128];
u16 j;
strcpy(t, src[i]);
a_pc = 0; a_lo = 0xFFFF; a_hi = 0; a_undef = 0;
a_line(t);
if (a_err) printf("ERROR %s\n", a_err);
else { for (j = 0; j < a_pc; j++) printf("%02X", hostmem[j]); printf("\n"); }
}
return 0;
}
nsym = 0;
for (p = 1; p <= 2; p++) {
a_pass = p; a_pc = 0xF000; a_end = 0; a_lo = 0xFFFF; a_hi = 0;
for (i = 0; i < n && !a_end; i++) {
char t[128];
u16 at = a_pc, j;
strcpy(t, src[i]);
a_undef = 0;
a_line(t);
if (a_err && (p == 2 || !a_undef)) { printf("LINE %u: %s\n", i + 1, a_err); if (p == 1) return 1; }
if (p == 2) {
printf("%04X ", at);
for (j = at; j < a_pc; j++) printf("%02X", hostmem[j]);
printf("\t%s\n", src[i]);
}
}
}
printf("%u symbols, %04X-%04X\n", nsym, a_lo, a_hi);
return 0;
}
/* Host test: disassemble every opcode form, one per line, for the round trip
through sdasz80 in monitor/test-disasm.sh. Format: hex bytes TAB text. */
int main(int argc, char **argv)
{
static const u8 pre[][2] = { {0, 0}, {0xCB, 0}, {0xED, 0}, {0xDD, 0}, {0xFD, 0}, {0xDD, 0xCB}, {0xFD, 0xCB} };
u16 k, i;
if (argc > 1 && !strcmp(argv[1], "line")) return asm_test(0);
if (argc > 1 && !strcmp(argv[1], "file")) return asm_test(1);
symb = argc > 1;
for (k = 0; k < 7; k++)
for (i = 0; i < 256; i++) {
u8 n = 0, len, j;
memset(hostmem, 0, 16);
if (pre[k][0]) hostmem[n++] = pre[k][0];
if (pre[k][1] == 0xCB) { hostmem[n++] = 0xCB; hostmem[n++] = 0x85; } /* d = -7BH */
hostmem[n++] = i;
if (k == 3 || k == 4) {
if (i == 0xCB || i == 0xDD || i == 0xED || i == 0xFD) continue;
}
hostmem[n] = 0x12; hostmem[n + 1] = 0x34; hostmem[n + 2] = 0x56;
lp = line;
len = disasm(0x100 - 0x100);
*lp = 0;
for (j = 0; j < len; j++) printf("%02X", hostmem[j]);
printf("\t%s\n", line);
}
return 0;
}
#else
/* ------------------------------------------------------------- screen */
static void puts_(const char *s) { while (*s) putc_(*s++); }
static void at(u8 r, u8 c) /* r, c from 0 */
{
putc_(27); putc_('[');
r++; c++;
if (r >= 10) putc_('0' + r / 10);
putc_('0' + r % 10); putc_(';');
if (c >= 10) putc_('0' + c / 10);
putc_('0' + c % 10); putc_('H');
}
static void sgr(const char *s) { putc_(27); putc_('['); puts_(s); putc_('m'); }
static void flush_line(void) { *lp = 0; puts_(line); }
static void clr_eol(void) { puts_("\033[K"); }
/* --------------------------------------------------------------- state */
#define DIS_ROWS 16
#define MEM_ROWS 6
#define DIS_TOP 5
#define MEM_TOP 22
static u16 dis_a; /* first line of the disassembly window */
static u16 mem_a; /* first line of the memory window */
static u16 bp; /* the user's breakpoint */
static u8 bp_set;
static u8 go_after; /* stepping off a breakpoint, then G */
static u16 steps; /* more single steps to do */
static char cmd[40];
static u8 msg_err;
static const char *msg;
static u8 why_in; /* why the monitor was entered */
static char load_msg[24];
static u16 pc_get(void) { return rd(u.sp + 2) | (u16)rd(u.sp + 3) << 8; }
static u16 af_get(void) { return rd(u.sp) | (u16)rd(u.sp + 1) << 8; }
static u8 pc_set(u16 v) { return wr(u.sp + 2, v) & wr(u.sp + 3, v >> 8); }
static u8 af_set(u16 v) { return wr(u.sp, v) & wr(u.sp + 1, v >> 8); }
static u16 sp_get(void) { return u.sp + 4; }
/* ------------------------------------------------------------- drawing */
static void s_reg(const char *n, u16 v) { s_str(n); s_h4(v); s_str(" "); }
static void draw_regs(void)
{
u16 af = af_get();
u8 f = af, i;
static const char fl[] = "SZ5H3PNC";
lp = line;
s_reg(" PC ", pc_get()); s_reg("SP ", sp_get()); s_reg("AF ", af);
s_reg("BC ", u.bc); s_reg("DE ", u.de); s_reg("HL ", u.hl);
s_reg("IX ", u.ix); s_reg("IY ", u.iy);
at(2, 0); flush_line(); clr_eol();
lp = line;
s_reg(" AF'", u.af2); s_reg("BC'", u.bc2); s_reg("DE'", u.de2); s_reg("HL'", u.hl2);
s_str("I "); s_h2(u.i); s_str(" FLAGS ");
for (i = 0; i < 8; i++) s_ch(f & (0x80 >> i) ? fl[i] : '-');
at(3, 0); flush_line(); clr_eol();
}
static void draw_dis(void)
{
u16 a = dis_a, pc = pc_get();
u8 r, n, j;
for (r = 0; r < DIS_ROWS; r++) {
lp = line;
s_ch(a == pc ? '>' : ' ');
s_ch(bp_set && a == bp ? '*' : ' ');
s_h4(a); s_str(" ");
{
char *t = lp;
n = disasm(a);
/* the text went in at t; move it right of the bytes */
{
char txt[40];
u8 k = lp - t;
memcpy(txt, t, k); txt[k] = 0;
lp = t;
for (j = 0; j < 4; j++) {
if (j < n) s_h2(rd(a + j)); else s_str(" ");
s_ch(' ');
}
s_ch(' ');
s_str(txt);
}
}
while (lp < line + 50) s_ch(' ');
at(DIS_TOP + r, 0);
if (a == pc) sgr("1;33;44");
flush_line();
if (a == pc) sgr("0");
a += n;
}
}
static void draw_stack(void)
{
u16 s = sp_get();
u8 r;
at(DIS_TOP, 54); sgr("36"); puts_("STACK"); sgr("0");
for (r = 0; r < DIS_ROWS - 2; r++) {
lp = line;
s_h4(s); s_str(" ");
s_h4(rd(s) | (u16)rd(s + 1) << 8);
at(DIS_TOP + 1 + r, 54); flush_line();
s += 2;
}
}
static void draw_mem(void)
{
u16 a = mem_a;
u8 r, j, c;
for (r = 0; r < MEM_ROWS; r++) {
lp = line;
s_ch(' '); s_h4(a); s_str(" ");
for (j = 0; j < 16; j++) { s_h2(rd(a + j)); s_ch(j == 7 ? '-' : ' '); }
s_ch(' ');
for (j = 0; j < 16; j++) { c = rd(a + j); s_ch(c >= 32 && c < 127 ? c : '.'); }
at(MEM_TOP + r, 0); flush_line(); clr_eol();
a += 16;
}
}
static const char *why_text(u8 w)
{
switch (w) {
case 1: return "PAUSE KEY";
case 2: return "MONITOR COMMAND";
case 3: return "STEP";
case 4: return "BREAKPOINT";
case 5: return "STEP OVER";
default: return "";
}
}
static void draw_all(void)
{
puts_("\033[2J");
at(0, 0); sgr("1;37;44");
lp = line;
s_str(" Z-80 MONITOR");
while (lp < line + 50) s_ch(' ');
s_str("STOPPED BY ");
s_str(why_text(why_in));
while (lp < line + 80) s_ch(' ');
flush_line(); sgr("0");
draw_regs();
at(DIS_TOP - 1, 0); sgr("36"); puts_(" ADDR BYTES INSTRUCTION"); sgr("0");
draw_dis();
draw_stack();
at(MEM_TOP - 1, 0); sgr("36"); puts_(" MEMORY"); sgr("0");
draw_mem();
at(28, 0); sgr("36");
puts_(" ENTER step O over G go X exit B bp D/M addr E edit R reg ? help");
sgr("0");
}
/* --------------------------------------------------------------- input */
static u8 is_hex(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'); }
static char *cp;
static void skip_sp(void) { while (*cp == ' ' || *cp == ',') cp++; }
/* hex number at cp; 0 if none */
static u8 get_hex(u16 *v)
{
u8 n = 0;
skip_sp();
*v = 0;
while (is_hex(*cp)) {
*v = *v << 4 | (*cp <= '9' ? *cp - '0' : *cp - 'A' + 10);
cp++; n++;
}
return n;
}
static void show_msg(void)
{
at(29, 40); clr_eol();
if (msg) { sgr(msg_err ? "1;31" : "32"); puts_(msg); sgr("0"); }
}
/* Read a command into cmd. Returns 1 for a line, or a key code for a key
that acts at once on an empty line: 'U', 'N' (up, down), 'P', 'Q' (page). */
static const char *prompt = "> ";
static u8 read_cmd(void)
{
u8 n = 0, c;
at(29, 0); puts_(prompt); clr_eol();
show_msg();
at(29, strlen(prompt));
puts_("\033[?25h");
for (;;) {
c = getk();
if (c == 27) {
c = getk();
if (c == '[' || c == 'O') {
u8 k = getk(), t = k;
while (t >= '0' && t <= '9') t = getk(); /* ESC [ 5 ~ */
puts_("\033[?25l");
if (k == 'A') return 'U';
if (k == 'B') return 'N';
if (k == '5') return 'P';
if (k == '6') return 'Q';
puts_("\033[?25h");
}
continue;
}
if (c == '\r' || c == '\n') { cmd[n] = 0; puts_("\033[?25l"); return 1; }
if (c == 8 || c == 127) { if (n) { n--; puts_("\b \b"); } continue; }
if (c == 21) { while (n) { n--; puts_("\b \b"); } continue; }
if (c >= 'a' && c <= 'z') c -= 32;
if (c >= ' ' && c < 127 && n < sizeof cmd - 1) { cmd[n++] = c; putc_(c); }
}
}
/* ------------------------------------------------------- flash files */
/* The same file system as BASIC's (basic.c): 448 blocks of 4 KB from
240000h, a directory in block 0 or 1 (the newer valid one). A memory file
holds its load address (2 bytes, low first) and then the bytes. */
#define FS_BASE 0x240000UL
#define FS_BLOCKS 448
#define MAXFILES 64
#define FBLK 8
struct dirent { char name[8]; u16 len; u16 blk[FBLK]; u16 date[2]; };
#define OLD_DIRENT 26
static struct {
char magic[4];
u16 seq, next;
struct dirent e[MAXFILES];
u16 sum;
} dir;
static u8 dir_cur;
static u8 bmap[FS_BLOCKS / 8];
static u8 page[256];
static u16 w_pos;
static u16 w_blk[FBLK];
static jmp_buf fs_jmp;
static const char *fs_msg;
static void fs_fail(const char *m) { fs_msg = m; longjmp(fs_jmp, 1); }
static i32 millis(void)
{
u8 a = tim0;
return (i32)a | (i32)tim1 << 8 | (i32)tim2 << 16 | (i32)tim3 << 24;
}
static u32 now(void)
{
u32 s = CLK_SEC;
return s ? s + (u32)(millis() - CLK_MS) / 1000 : 0;
}
static u8 spi(u8 b) { fl_dat = b; while (fl_ctl & 1); return fl_dat; }
static void fl_open(u8 cmd) { fl_ctl = 1; spi(cmd); }
static void fl_close(void) { fl_ctl = 0; }
static void fl_addr(u32 a) { spi(a >> 16); spi(a >> 8); spi(a); }
static void fl_read(u32 a, u8 *p, u16 n)
{
fl_open(0x03); fl_addr(a);
while (n--) *p++ = spi(0);
fl_close();
}
static void fl_wait(void)
{
i32 t = millis();
u8 st;
do {
fl_open(0x05); st = spi(0); fl_close();
if (millis() - t > 3000) fs_fail("FLASH ERROR");
} while (st & 1);
}
static void fl_write_op(u8 cmd, u32 a, const u8 *p, u16 n)
{
u8 ok;
fl_open(0x06); fl_close();
fl_open(cmd); fl_addr(a);
while (n--) spi(*p++);
ok = !(fl_ctl & 2);
fl_close();
if (!ok) fs_fail("FLASH ERROR");
fl_wait();
}
static u32 blk_addr(u16 b) { return FS_BASE + ((u32)b << 12); }
static u8 nblk(u16 len) { return (len + 4095) >> 12; }
static void fl_prog(u32 a, const u8 *p, u16 n)
{
u8 chk[32];
u16 i, k;
fl_write_op(0x02, a, p, n);
for (i = 0; i < n; i += k) {
k = n - i < 32 ? n - i : 32;
fl_read(a + i, chk, k);
if (memcmp(chk, p + i, k)) fs_fail("FLASH ERROR");
}
}
static u16 sum_of(u16 n)
{
u8 *p = (u8 *)&dir;
u16 s = 0x5AA5;
while (n--) s = (s << 1 | s >> 15) + *p++;
return s;
}
static u8 load_dir(u8 b)
{
u8 *p = (u8 *)&dir, i;
u16 old = 8 + MAXFILES * OLD_DIRENT;
fl_read(blk_addr(b), p, sizeof dir);
if (!memcmp(dir.magic, "BFS2", 4)) return dir.sum == sum_of(sizeof dir - 2);
if (memcmp(dir.magic, "BFS1", 4) || (p[old] | p[old + 1] << 8) != sum_of(old)) return 0;
for (i = MAXFILES; i--; ) {
memmove(&dir.e[i], p + 8 + i * OLD_DIRENT, OLD_DIRENT);
dir.e[i].date[0] = dir.e[i].date[1] = 0;
}
memcpy(dir.magic, "BFS2", 4);
return 1;
}
static void fs_mount(void)
{
u8 va, vb;
u16 sa;
fl_open(0x9F); va = spi(0); vb = spi(0); sa = spi(0); fl_close();
if (va != 0xC2 || vb != 0x20 || sa != 0x16) fs_fail("NO FLASH");
va = load_dir(0);
sa = dir.seq;
vb = load_dir(1);
if (va && (!vb || (i16)(sa - dir.seq) > 0)) { load_dir(0); dir_cur = 0; }
else if (vb) dir_cur = 1;
else {
memset(&dir, 0, sizeof dir);
memcpy(dir.magic, "BFS2", 4);
dir.next = 2;
dir_cur = 1;
}
}
static void fs_commit(void)
{
u8 b = dir_cur ^ 1, *p = (u8 *)&dir;
u16 i, n;
dir.seq++;
dir.sum = sum_of(sizeof dir - 2);
fl_write_op(0x20, blk_addr(b), 0, 0);
for (i = 0; i < sizeof dir; i += 256) {
n = sizeof dir - i < 256 ? sizeof dir - i : 256;
fl_prog(blk_addr(b) + i, p + i, n);
}
dir_cur = b;
}
static i16 find_file(const char *nm)
{
u8 i;
for (i = 0; i < MAXFILES; i++)
if (!memcmp(dir.e[i].name, nm, 8)) return i;
return -1;
}
static u16 alloc_blk(void)
{
u16 b = dir.next, k;
for (k = 0; k < FS_BLOCKS; k++, b++) {
if (b >= FS_BLOCKS) b = 2;
if (!(bmap[b >> 3] & (1 << (b & 7)))) {
bmap[b >> 3] |= 1 << (b & 7);
dir.next = b + 1;
return b;
}
}
fs_fail("DISK FULL");
return 0;
}
static void build_bmap(void)
{
u8 i, j, n;
memset(bmap, 0, sizeof bmap);
bmap[0] = 3;
for (i = 0; i < MAXFILES; i++)
if (dir.e[i].name[0])
for (j = 0, n = nblk(dir.e[i].len); j < n; j++)
bmap[dir.e[i].blk[j] >> 3] |= 1 << (dir.e[i].blk[j] & 7);
}
static void put_b(u8 c)
{
if (!(w_pos & 4095)) {
w_blk[w_pos >> 12] = alloc_blk();
fl_write_op(0x20, blk_addr(w_blk[w_pos >> 12]), 0, 0);
}
page[w_pos & 255] = c;
w_pos++;
if (!(w_pos & 255))
fl_prog(blk_addr(w_blk[(w_pos - 1) >> 12]) + ((w_pos - 256) & 4095), page, 256);
}
/* "NAME" at cp: 1-8 letters and digits */
static void get_fname(char *nm)
{
u8 n = 0;
skip_sp();
if (*cp++ != '"') fs_fail("NAME IN QUOTES");
memset(nm, 0, 8);
while (*cp && *cp != '"') {
if (n == 8 || !((*cp >= 'A' && *cp <= 'Z') || (*cp >= '0' && *cp <= '9'))) fs_fail("BAD FILE NAME");
nm[n++] = *cp++;
}
if (*cp) cp++;
if (!n) fs_fail("BAD FILE NAME");
}
/* SAVE "NAME" start end: memory start..end (inclusive) to a file */
static void mem_save(void)
{
char nm[8];
u16 a, e, n;
i16 i;
get_fname(nm);
if (!get_hex(&a) || !get_hex(&e) || e < a) fs_fail("SAVE \"NAME\" START END");
n = e - a + 1;
if (n > 32768U - 2) fs_fail("FILE TOO BIG");
fs_mount();
build_bmap();
i = find_file(nm);
if (i < 0) {
for (i = 0; i < MAXFILES && dir.e[i].name[0]; i++);
if (i == MAXFILES) fs_fail("TOO MANY FILES");
}
w_pos = 0;
put_b(a); put_b(a >> 8);
while (n--) put_b(rd(a++));
if (w_pos & 255)
fl_prog(blk_addr(w_blk[(w_pos - 1) >> 12]) + ((w_pos - (w_pos & 255)) & 4095), page, w_pos & 255);
if (!dir.e[i].name[0] || !(dir.e[i].date[0] | dir.e[i].date[1])) {
u32 t = now();
dir.e[i].date[0] = t; dir.e[i].date[1] = t >> 16;
}
memcpy(dir.e[i].name, nm, 8);
dir.e[i].len = w_pos;
memcpy(dir.e[i].blk, w_blk, sizeof w_blk);
fs_commit();
}
/* LOAD "NAME" [addr]: a memory file back, to its own address or addr */
static u16 ld_first, ld_last;
static void mem_load(void)
{
char nm[8];
u16 a, pos, len;
i16 i;
u8 has;
get_fname(nm);
has = get_hex(&a);
fs_mount();
i = find_file(nm);
if (i < 0) fs_fail("FILE NOT FOUND");
len = dir.e[i].len;
if (len < 2) fs_fail("NOT A MEMORY FILE");
for (pos = 0; pos < len; pos++) {
u8 c;
if (!(pos & 255))
fl_read(blk_addr(dir.e[i].blk[pos >> 12]) + (pos & 4095), page, 256);
c = page[pos & 255];
if (pos == 0) { if (!has) a = c; }
else if (pos == 1) { if (!has) a |= (u16)c << 8; ld_first = a; }
else {
if (!wr(a, c)) fs_fail("CAN'T LOAD BELOW 8000H");
ld_last = a++;
}
}
}
/* DIR: the files, four to a line, in the memory window */
static void mem_dir(void)
{
u8 i, n = 0, r;
fs_mount();
for (r = 0; r < MEM_ROWS; r++) { at(MEM_TOP + r, 0); clr_eol(); }
for (i = 0; i < MAXFILES && n < MEM_ROWS * 4; i++) {
u8 j;
if (!dir.e[i].name[0]) continue;
lp = line;
for (j = 0; j < 8; j++) s_ch(dir.e[i].name[j] ? dir.e[i].name[j] : ' ');
s_ch(' '); s_h4(dir.e[i].len); s_ch('H');
at(MEM_TOP + n / 4, 1 + (n & 3) * 20); flush_line();
n++;
}
if (!n) { at(MEM_TOP, 1); puts_("NO FILES"); }
}
/* ------------------------------------------------------------ assembler */
static void a_out(u16 addr, u8 b) { if (!wr(addr, b)) a_fail("CAN'T WRITE BELOW 8000H"); }
static u8 dis_shows(u16 pc);
static char a_src[128];
static u8 a_nerr;
static void s_dec(u16 v)
{
char b[6], *q = b + 5;
*q = 0;
do *--q = '0' + v % 10; while (v /= 10);
s_str(q);
}
/* one error, in the memory window (six fit) */
static void a_report(u16 ln)
{
if (a_nerr < MEM_ROWS) {
lp = line;
s_str(" LINE "); s_dec(ln);
s_str(": "); s_str(a_err);
*lp = 0;
at(MEM_TOP + a_nerr, 0); flush_line(); clr_eol();
}
a_nerr++;
}
/* ASM "NAME": assemble a source file from flash into memory */
static void mem_asm(void)
{
char nm[8];
i16 f;
u16 len, pos, ln;
u8 n, p, r;
get_fname(nm);
fs_mount();
f = find_file(nm);
if (f < 0) fs_fail("FILE NOT FOUND");
len = dir.e[f].len;
nsym = 0;
a_nerr = 0;
for (r = 0; r < MEM_ROWS; r++) { at(MEM_TOP + r, 0); clr_eol(); }
for (p = 1; p <= 2 && !a_nerr; p++) {
a_pass = p; a_pc = 0xF000; a_end = 0; a_lo = 0xFFFF; a_hi = 0;
n = 0; ln = 0;
for (pos = 0; pos <= len && !a_end; pos++) {
u8 c = '\n';
if (pos < len) {
if (!(pos & 255))
fl_read(blk_addr(dir.e[f].blk[pos >> 12]) + (pos & 4095), page, 256);
c = page[pos & 255];
}
if (c != '\n') { if (n < sizeof a_src - 1) a_src[n++] = c; continue; }
a_src[n] = 0;
n = 0;
ln++;
{
u16 num = 0; /* report BASIC's line number if there is one */
char *t = a_src;
while (*t == ' ') t++;
while (*t >= '0' && *t <= '9') num = num * 10 + (*t++ - '0');
a_upper(a_src);
a_undef = 0;
a_line(a_src);
if (a_err) a_report(num ? num : ln);
}
}
}
if (a_nerr) {
lp = line; s_dec(a_nerr); s_str(a_nerr == 1 ? " ERROR" : " ERRORS"); *lp = 0;
s_copy(load_msg, line);
fs_fail(load_msg);
}
if (a_lo > a_hi) fs_fail("NOTHING ASSEMBLED");
lp = line; s_str("ASSEMBLED "); s_h4(a_lo); s_ch('-'); s_h4(a_hi); *lp = 0;
s_copy(load_msg, line);
dis_a = mem_a = a_lo;
draw_mem(); draw_dis();
}
/* A addr: assemble lines typed at the bottom, one after another */
static void line_asm(u16 a)
{
static char pr[10];
for (;;) {
lp = pr; s_ch('A'); s_ch(' '); s_h4(a); s_str(": "); *lp = 0;
prompt = pr;
if (read_cmd() != 1) continue;
prompt = "> ";
if (!cmd[0]) { msg = 0; return; }
s_copy(a_src, cmd);
a_pass = 2; a_pc = a; a_undef = 0; a_lo = 0xFFFF; a_hi = 0;
a_line(a_src);
if (a_err) { msg = a_err; msg_err = 1; continue; }
msg = 0;
if (a < dis_a || !dis_shows(a)) dis_a = a;
a = a_pc;
draw_dis(); draw_mem();
}
}
/* ---------------------------------------------------------- commands */
static u8 op_is_call(u16 a)
{
u8 op = rd(a);
return op == 0xCD || (op & 0xC7) == 0xC4 || (op & 0xC7) == 0xC7;
}
/* Leave the monitor. mode: 0 run, 2 one instruction */
static void leave(u8 mode)
{
u.exit = mode;
bp0_lo = bp; bp0_hi = bp >> 8;
}
static u8 set_reg(void)
{
static const char *const names[] = { "PC", "SP", "AF", "BC", "DE", "HL", "IX", "IY" };
u8 i;
u16 v;
skip_sp();
for (i = 0; i < 8; i++)
if (cp[0] == names[i][0] && cp[1] == names[i][1]) break;
if (i == 8) return 0;
cp += 2;
skip_sp();
if (*cp == '=') cp++;
if (!get_hex(&v)) return 0;
switch (i) {
case 0: return pc_set(v);
case 1: { /* move AF and PC down to the new SP */
u16 pc = pc_get(), af = af_get();
u.sp = v - 4;
return pc_set(pc) & af_set(af);
}
case 2: return af_set(v);
case 3: u.bc = v; break;
case 4: u.de = v; break;
case 5: u.hl = v; break;
case 6: u.ix = v; break;
default: u.iy = v; break;
}
return 1;
}
/* Returns 1 when the monitor should be left (u.exit set). */
static u8 command(void)
{
u16 v, a;
u8 c;
cp = cmd;
skip_sp();
msg = 0; msg_err = 0;
if (!memcmp(cp, "ASM", 3)) {
cp += 3;
if (setjmp(fs_jmp)) { msg = fs_msg; msg_err = 1; return 0; }
mem_asm();
msg = load_msg;
return 0;
}
if (cp[0] == 'A' && (cp[1] == ' ' || !cp[1])) {
u16 a;
cp++;
if (!get_hex(&a)) { msg = "A ADDR, THEN INSTRUCTIONS; EMPTY LINE ENDS"; msg_err = 1; return 0; }
line_asm(a);
return 0;
}
if (!memcmp(cp, "SAVE", 4) || !memcmp(cp, "LOAD", 4) || !memcmp(cp, "DIR", 3)) {
c = *cp;
cp += c == 'D' ? 3 : 4;
if (setjmp(fs_jmp)) { msg = fs_msg; msg_err = 1; return 0; }
if (c == 'S') { mem_save(); msg = "SAVED"; }
else if (c == 'L') {
mem_load();
lp = line; s_str("LOADED "); s_h4(ld_first); s_ch('-'); s_h4(ld_last); *lp = 0;
s_copy(load_msg, line);
msg = load_msg;
mem_a = ld_first;
draw_mem(); draw_dis();
} else { mem_dir(); msg = "M TO SHOW MEMORY AGAIN"; }
return 0;
}
c = *cp;
if (c) cp++;
switch (c) {
case 0: /* Enter: one step */
case 'S':
steps = get_hex(&v) && v ? v - 1 : 0;
leave(2);
return 1;
case 'O': /* step over a CALL or RST */
a = pc_get();
if (!op_is_call(a)) { leave(2); return 1; }
lp = line;
v = a + disasm(a);
bp1_lo = v; bp1_hi = v >> 8;
bp_ctl = (bp_set && bp != a ? 1 : 0) | 2;
leave(0);
return 1;
case 'G':
case 'X':
if (get_hex(&v) && !pc_set(v)) { msg = "STACK IS IN ROM"; msg_err = 1; return 0; }
if (bp_set && pc_get() == bp) { go_after = 1; leave(2); return 1; }
bp_ctl = bp_set;
leave(0);
return 1;
case 'B':
if (get_hex(&v)) { bp = v; bp_set = 1; msg = "BREAKPOINT SET"; }
else { bp_set = 0; msg = "BREAKPOINT CLEARED"; }
draw_dis();
return 0;
case 'D':
if (get_hex(&v)) dis_a = v; else dis_a = pc_get();
draw_dis();
return 0;
case 'M':
if (get_hex(&v)) mem_a = v;
draw_mem();
return 0;
case 'E': /* E addr bytes... */
if (!get_hex(&a)) { msg = "E ADDR BYTE BYTE ..."; msg_err = 1; return 0; }
while (get_hex(&v))
if (!wr(a++, v)) { msg = "ROM: NOT CHANGED"; msg_err = 1; break; }
draw_all();
return 0;
case 'R':
if (!set_reg()) { msg = "R PC|SP|AF|BC|DE|HL|IX|IY = VALUE"; msg_err = 1; return 0; }
draw_regs(); draw_dis(); draw_stack();
return 0;
case '?':
case 'H':
msg = "ASM \"N\" A ADDR SAVE \"N\" A B LOAD \"N\" [A] DIR";
return 0;
default:
msg = "? TYPE ? FOR HELP"; msg_err = 1;
return 0;
}
}
/* Is pc shown in the disassembly window? */
static u8 dis_shows(u16 pc)
{
u16 a = dis_a;
u8 r;
for (r = 0; r < DIS_ROWS - 2; r++) {
if (a == pc) return 1;
lp = line;
a += disasm(a);
}
return 0;
}
void mon_main(void)
{
u8 why = mon_ctl, k;
u16 pc = pc_get();
bp_ctl = 0; /* no breakpoints inside the monitor */
if (go_after && why == 3) { /* stepped off the breakpoint: now go */
go_after = 0;
bp_ctl = bp_set;
leave(0);
return;
}
if (steps && why == 3) {
steps--;
leave(2);
return;
}
steps = 0;
go_after = 0;
if (!dis_shows(pc)) dis_a = pc;
puts_("\0337\033[?47h\033[?25l"); /* save the cursor, alternate screen */
why_in = why;
draw_all();
for (;;) {
k = read_cmd();
if (k == 1) {
if (command()) break;
continue;
}
if (k == 'U') dis_a--;
else if (k == 'N') { lp = line; dis_a += disasm(dis_a); }
else if (k == 'P') mem_a -= 16 * MEM_ROWS;
else if (k == 'Q') mem_a += 16 * MEM_ROWS;
if (k == 'U' || k == 'N') draw_dis(); else draw_mem();
}
puts_("\033[?25h\033[?47l\0338");
}
#endif