Basys 3 RISC-V computer

The Basys 3 Z-80 computer with the Z-80 replaced by an RV32IM processor
written from scratch (rtl/rv32_cpu.v): multi-cycle, 90 MHz, CSRs and
traps, interrupts, two hardware triggers and a resumable NMI for the
monitor. Passes riscv-tests rv32ui/um/mi.

rv32_system.v keeps all the Z-80 machine's peripherals, with I/O port N
at FFFFFF00h + N, 80 KB of RAM with BASIC preloaded, and a 32 KB monitor
ROM. BASIC, the five games and the monitor (with an RV32 disassembler,
assembler, breakpoints and single step) are ported to RISC-V GCC. Python
emulator and tests in tools/; full-system simulation in sim/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
brad ArantandClaude Opus 5.5 committed 2026-11-30 18:09:18 -08:00
commit 5930b958b4
103 files changed
+55677

No files matched your search

+541
View File
@@ -0,0 +1,541 @@
/* RISC-V assembler for the monitor (included by monitor.c).
*
* The syntax the disassembler prints. A line is
* [line number] [label:] [instruction or directive] [; comment]
* (the line number is there when the source was typed into BASIC). Numbers:
* 123, 0FFH, $FF, 0x1F, 1010B, 'A'; $ alone is the current address.
* Expressions use + - * / & | and parentheses. Registers are X0-X31 or their
* ABI names (ZERO RA SP GP TP T0-T6 S0-S11 FP A0-A7); memory operands are
* offset(register). CSRs by name (MSTATUS, MEPC, CYCLE...) or number.
*
* Instructions: RV32I and M, CSRRW..CSRRCI, ECALL EBREAK MRET MNRET WFI FENCE
* FENCE.I, and the usual short forms: NOP LI LA MV NOT NEG SEQZ SNEZ SLTZ SGTZ
* J JR JAL target RET CALL BEQZ BNEZ BLEZ BGEZ BLTZ BGTZ BGT BLE BGTU BLEU CSRR
* CSRW CSRS CSRC CSRWI CSRSI CSRCI. LI is one instruction for a constant of
* -2048..2047 known by then, else LUI and ADDI; LA is AUIPC and ADDI.
* Directives: ORG, EQU (NAME EQU value), DB/DEFB/DEFM (numbers and "strings"),
* DH (16 bits), DW/DEFW (32 bits), DS/DEFS n, ALIGN n, END. Instructions must
* be on a 4-byte boundary. Labels are up to 8 characters.
*/
#define MAXSYM 200
struct sym { char name[8]; u32 val; u16 line; };
static struct sym syms[MAXSYM];
static u16 nsym;
static u32 a_pc; /* address of the line being assembled */
static u32 a_lo, a_hi; /* lowest and highest byte written */
static u8 a_pass; /* 1: sizes and labels, 2: bytes */
static u8 a_undef; /* the expression used an undefined symbol */
static u8 a_fwd; /* ... or one defined further on */
static u8 a_end; /* END seen */
static u16 a_lnum; /* source line, for forward references */
static const char *a_err; /* this line's error */
static const char *ap; /* parse pointer */
static void a_fail(const char *m) { if (!a_err) a_err = m; }
static void a_sp(void) { while (*ap == ' ' || *ap == '\t') ap++; }
static u8 a_alpha(char c) { return (c >= 'A' && c <= 'Z') || c == '_' || c == '.'; }
static u8 a_alnum(char c) { return a_alpha(c) || (c >= '0' && c <= '9'); }
static void a_emit(u8 b)
{
if (a_pass == 2) {
if (!wr(a_pc, b)) a_fail("CAN'T WRITE THERE");
if (a_pc < a_lo) a_lo = a_pc;
if (a_pc > a_hi) a_hi = a_pc;
}
a_pc++;
}
static void a_emit32(u32 w) { a_emit(w); a_emit(w >> 8); a_emit(w >> 16); a_emit(w >> 24); }
static i16 sym_find(const char *n)
{
u16 i;
for (i = 0; i < nsym; i++)
if (!memcmp(syms[i].name, n, 8)) return i;
return -1;
}
static void sym_def(const char *n, u32 v)
{
i16 i = sym_find(n);
if (a_pass == 2) {
if (i >= 0 && syms[i].val != v) a_fail("PHASE ERROR");
return;
}
if (i >= 0) { a_fail("DUPLICATE LABEL"); return; }
if (nsym == MAXSYM) { a_fail("TOO MANY LABELS"); return; }
memcpy(syms[nsym].name, n, 8);
syms[nsym].val = v;
syms[nsym++].line = a_lnum;
}
/* a name at ap (up to 8 characters kept) */
static void a_name(char *n)
{
u8 k = 0;
memset(n, 0, 8);
while (a_alnum(*ap)) { if (k < 8) n[k++] = *ap; ap++; }
}
/* ---------------------------------------------------------- expressions */
static u32 a_expr(void);
static u32 a_number(void)
{
const char *s = ap;
u32 v = 0;
u8 base = 10, n = 0;
if (s[0] == '0' && s[1] == 'X') { base = 16; s += 2; }
else {
while (a_alnum(s[n])) n++;
if (s[n - 1] == 'H') base = 16;
else if (s[n - 1] == 'B') {
u8 k;
for (k = 0; k < n - 1 && (s[k] == '0' || s[k] == '1'); k++);
if (k == n - 1) base = 2;
}
}
for (; a_alnum(*s); s++) {
char c = *s;
u8 d = c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : 99;
if ((c == 'H' && base == 16) || (c == 'B' && base == 2 && !a_alnum(s[1]))) { s++; break; }
if (d >= base) { a_fail("BAD NUMBER"); break; }
v = v * base + d;
}
ap = s;
return v;
}
static u32 a_factor(void)
{
u32 v;
a_sp();
if (*ap == '-') { ap++; return -a_factor(); }
if (*ap == '+') { ap++; return a_factor(); }
if (*ap == '(') {
ap++;
v = a_expr();
a_sp();
if (*ap == ')') ap++; else a_fail("MISSING )");
return v;
}
if (*ap == '\'' && ap[1] && ap[2] == '\'') { v = (u8)ap[1]; ap += 3; return v; }
if (*ap == '$') {
ap++;
if ((*ap >= '0' && *ap <= '9') || (*ap >= 'A' && *ap <= 'F')) {
v = 0;
while ((*ap >= '0' && *ap <= '9') || (*ap >= 'A' && *ap <= 'F'))
v = v * 16 + (*ap <= '9' ? *ap - '0' : *ap - 'A' + 10), ap++;
return v;
}
return a_pc;
}
if (*ap >= '0' && *ap <= '9') return a_number();
if (a_alpha(*ap)) {
char n[8];
i16 i;
a_name(n);
i = sym_find(n);
if (i >= 0) {
if (a_lnum && syms[i].line > a_lnum) a_fwd = 1;
return syms[i].val;
}
a_undef = 1;
if (a_pass == 2) a_fail("UNDEFINED LABEL");
return 0;
}
a_fail("BAD EXPRESSION");
return 0;
}
static u32 a_term(void)
{
u32 v = a_factor(), w;
for (;;) {
a_sp();
if (*ap == '*') { ap++; v *= a_factor(); }
else if (*ap == '/') { ap++; w = a_factor(); if (w) v /= w; else a_fail("DIVIDE BY 0"); }
else return v;
}
}
static u32 a_expr(void)
{
u32 v = a_term();
for (;;) {
a_sp();
if (*ap == '+') { ap++; v += a_term(); }
else if (*ap == '-') { ap++; v -= a_term(); }
else if (*ap == '&') { ap++; v &= a_term(); }
else if (*ap == '|') { ap++; v |= a_term(); }
else return v;
}
}
/* ------------------------------------------------------------- operands */
#define MAXOP 3
static char a_ops[MAXOP][40];
static u8 a_nops;
/* the operands at ap, split at commas outside brackets and quotes */
static void a_split(void)
{
a_nops = 0;
a_sp();
while (*ap) {
const char *s = ap;
u8 d = 0, q = 0, len;
while (*ap && (d || q || *ap != ',')) {
if (*ap == '\'' && !q && ap[1] && ap[2] == '\'') ap += 2;
else if (*ap == '"') q = !q;
else if (*ap == '(') d++;
else if (*ap == ')' && d) d--;
ap++;
}
len = ap - s;
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--;
if (a_nops == MAXOP || len >= sizeof a_ops[0]) { a_fail("TOO MANY OPERANDS"); return; }
memcpy(a_ops[a_nops], s, len);
a_ops[a_nops++][len] = 0;
if (*ap == ',') { ap++; a_sp(); }
}
}
/* a register name, the whole of s; 0xFF if it isn't one */
static u8 a_regname(const char *s)
{
u8 i;
if (s[0] == 'X' && s[1] >= '0' && s[1] <= '9') {
u8 k = s[1] - '0';
if (s[2] >= '0' && s[2] <= '9') { k = k * 10 + s[2] - '0'; if (s[3]) return 0xFF; }
else if (s[2]) return 0xFF;
return k < 32 ? k : 0xFF;
}
if (!strcmp(s, "FP")) return 8;
for (i = 0; i < 32; i++) if (!strcmp(s, regn[i])) return i;
return 0xFF;
}
static u8 a_reg(u8 i)
{
u8 r = i < a_nops ? a_regname(a_ops[i]) : 0xFF;
if (r == 0xFF) a_fail("BAD REGISTER");
return r & 31;
}
static u32 a_val(const char *s)
{
u32 v;
ap = s;
v = a_expr();
a_sp();
if (*ap) a_fail("BAD OPERAND");
return v;
}
static u32 a_imm(u8 i)
{
if (i >= a_nops) { a_fail("MISSING OPERAND"); return 0; }
return a_val(a_ops[i]);
}
/* offset(reg) or (reg); the register number, the offset in *off */
static u8 a_mem(u8 i, i32 *off)
{
char *s, *o;
u8 n, r;
*off = 0;
if (i >= a_nops) { a_fail("MISSING OPERAND"); return 0; }
s = a_ops[i];
n = strlen(s);
if (!n || s[n - 1] != ')' || !(o = strrchr(s, '('))) { a_fail("OFFSET(REGISTER)"); return 0; }
s[n - 1] = 0;
r = a_regname(o + 1);
if (r == 0xFF) { a_fail("BAD REGISTER"); return 0; }
*o = 0;
if (o > s) *off = (i32)a_val(s);
return r;
}
static u16 a_csr(u8 i)
{
const struct csrn *c;
u32 v;
if (i >= a_nops) { a_fail("MISSING OPERAND"); return 0; }
for (c = csrs; c->s; c++) if (!strcmp(a_ops[i], c->s)) return c->n;
v = a_val(a_ops[i]);
if (v > 0xFFF) a_fail("BAD CSR");
return v;
}
/* ------------------------------------------------------------ encoding */
static i32 a_range(i32 v, i32 lo, i32 hi)
{
if (a_pass == 2 && (v < lo || v > hi)) a_fail("VALUE OUT OF RANGE");
return v;
}
static u32 enc_i(u32 base, u8 rd, u8 rs1, i32 imm)
{
imm = a_range(imm, -2048, 2047);
return base | rd << 7 | rs1 << 15 | ((u32)imm & 0xFFF) << 20;
}
static u32 enc_r(u32 base, u8 rd, u8 rs1, u8 rs2) { return base | rd << 7 | rs1 << 15 | rs2 << 20; }
static u32 enc_s(u32 base, u8 rs1, u8 rs2, i32 imm)
{
u32 v = (u32)a_range(imm, -2048, 2047);
return base | (v & 31) << 7 | rs1 << 15 | rs2 << 20 | (v >> 5 & 0x7F) << 25;
}
static u32 enc_b(u32 base, u8 rs1, u8 rs2, u32 target)
{
i32 d = (i32)(target - a_pc);
u32 v;
if (a_pass == 2 && (d & 1)) a_fail("ODD TARGET");
if (a_pass == 2 && (d < -4096 || d > 4094)) a_fail("BRANCH TOO FAR");
v = (u32)d;
return base | rs1 << 15 | rs2 << 20 | (v >> 11 & 1) << 7 | (v >> 1 & 15) << 8 |
(v >> 5 & 0x3F) << 25 | (v >> 12 & 1) << 31;
}
static u32 enc_j(u8 rd, u32 target)
{
i32 d = (i32)(target - a_pc);
u32 v;
if (a_pass == 2 && (d & 1)) a_fail("ODD TARGET");
if (a_pass == 2 && (d < -(1 << 20) || d >= (1 << 20))) a_fail("JUMP TOO FAR");
v = (u32)d;
return 0x6F | rd << 7 | (v >> 12 & 0xFF) << 12 | (v >> 11 & 1) << 20 |
(v >> 1 & 0x3FF) << 21 | (v >> 20 & 1) << 31;
}
static u32 enc_u(u32 base, u8 rd, u32 imm)
{
if (a_pass == 2 && imm > 0xFFFFF) a_fail("VALUE OUT OF RANGE");
return base | rd << 7 | (imm & 0xFFFFF) << 12;
}
/* the LUI/AUIPC part and the ADDI part of a 32-bit value */
static u32 hi20(u32 v) { return (v + 0x800) >> 12 & 0xFFFFF; }
static i32 lo12(u32 v) { return sx(v, 12); }
/* --------------------------------------------------------- instructions */
enum {
F_R, F_I, F_SH, F_LD, F_ST, F_B, F_U, F_JAL, F_JALR, F_CSR, F_CSRI, F_FIX,
P_LI, P_LA, P_MV, P_NOT, P_NEG, P_SEQZ, P_SNEZ, P_SLTZ, P_SGTZ, P_J, P_JR, P_RET,
P_CALL, P_BZ, P_BZS, P_BSW, P_CSRR, P_CSRW, P_CSRWI
};
struct ins { char name[8]; u8 f; u32 base; };
static const struct ins itab[] = {
{ "ADD", F_R, 0x00000033 }, { "SUB", F_R, 0x40000033 }, { "SLL", F_R, 0x00001033 },
{ "SLT", F_R, 0x00002033 }, { "SLTU", F_R, 0x00003033 }, { "XOR", F_R, 0x00004033 },
{ "SRL", F_R, 0x00005033 }, { "SRA", F_R, 0x40005033 }, { "OR", F_R, 0x00006033 },
{ "AND", F_R, 0x00007033 },
{ "MUL", F_R, 0x02000033 }, { "MULH", F_R, 0x02001033 }, { "MULHSU", F_R, 0x02002033 },
{ "MULHU", F_R, 0x02003033 }, { "DIV", F_R, 0x02004033 }, { "DIVU", F_R, 0x02005033 },
{ "REM", F_R, 0x02006033 }, { "REMU", F_R, 0x02007033 },
{ "ADDI", F_I, 0x00000013 }, { "SLTI", F_I, 0x00002013 }, { "SLTIU", F_I, 0x00003013 },
{ "XORI", F_I, 0x00004013 }, { "ORI", F_I, 0x00006013 }, { "ANDI", F_I, 0x00007013 },
{ "SLLI", F_SH, 0x00001013 }, { "SRLI", F_SH, 0x00005013 }, { "SRAI", F_SH, 0x40005013 },
{ "LB", F_LD, 0x00000003 }, { "LH", F_LD, 0x00001003 }, { "LW", F_LD, 0x00002003 },
{ "LBU", F_LD, 0x00004003 }, { "LHU", F_LD, 0x00005003 },
{ "SB", F_ST, 0x00000023 }, { "SH", F_ST, 0x00001023 }, { "SW", F_ST, 0x00002023 },
{ "BEQ", F_B, 0x00000063 }, { "BNE", F_B, 0x00001063 }, { "BLT", F_B, 0x00004063 },
{ "BGE", F_B, 0x00005063 }, { "BLTU", F_B, 0x00006063 }, { "BGEU", F_B, 0x00007063 },
{ "LUI", F_U, 0x00000037 }, { "AUIPC", F_U, 0x00000017 },
{ "JAL", F_JAL, 0 }, { "JALR", F_JALR, 0x00000067 },
{ "CSRRW", F_CSR, 0x00001073 }, { "CSRRS", F_CSR, 0x00002073 }, { "CSRRC", F_CSR, 0x00003073 },
{ "CSRRWI", F_CSRI, 0x00005073 }, { "CSRRSI", F_CSRI, 0x00006073 }, { "CSRRCI", F_CSRI, 0x00007073 },
{ "ECALL", F_FIX, 0x00000073 }, { "EBREAK", F_FIX, 0x00100073 }, { "MRET", F_FIX, 0x30200073 },
{ "MNRET", F_FIX, 0x70200073 }, { "WFI", F_FIX, 0x10500073 }, { "FENCE", F_FIX, 0x0FF0000F },
{ "FENCE.I", F_FIX, 0x0000100F }, { "NOP", F_FIX, 0x00000013 },
{ "LI", P_LI, 0 }, { "LA", P_LA, 0 }, { "MV", P_MV, 0 }, { "NOT", P_NOT, 0 },
{ "NEG", P_NEG, 0 }, { "SEQZ", P_SEQZ, 0 }, { "SNEZ", P_SNEZ, 0 }, { "SLTZ", P_SLTZ, 0 },
{ "SGTZ", P_SGTZ, 0 }, { "J", P_J, 0 }, { "JR", P_JR, 0 }, { "RET", P_RET, 0 },
{ "CALL", P_CALL, 0 },
{ "BEQZ", P_BZ, 0x00000063 }, { "BNEZ", P_BZ, 0x00001063 }, { "BLTZ", P_BZ, 0x00004063 },
{ "BGEZ", P_BZ, 0x00005063 }, { "BGTZ", P_BZS, 0x00004063 }, { "BLEZ", P_BZS, 0x00005063 },
{ "BGT", P_BSW, 0x00004063 }, { "BLE", P_BSW, 0x00005063 }, { "BGTU", P_BSW, 0x00006063 },
{ "BLEU", P_BSW, 0x00007063 },
{ "CSRR", P_CSRR, 0 }, { "CSRW", P_CSRW, 0x00001073 }, { "CSRS", P_CSRW, 0x00002073 },
{ "CSRC", P_CSRW, 0x00003073 }, { "CSRWI", P_CSRWI, 0x00005073 },
{ "CSRSI", P_CSRWI, 0x00006073 }, { "CSRCI", P_CSRWI, 0x00007073 },
};
#define NINS (sizeof itab / sizeof itab[0])
static void a_need(u8 n) { if (a_nops != n) a_fail(a_nops < n ? "MISSING OPERAND" : "TOO MANY OPERANDS"); }
static void a_instr(const struct ins *t)
{
u32 b = t->base, v;
i32 off;
u8 rd, rs;
if (a_pc & 3) { a_fail("NOT ON A WORD: USE ALIGN 4"); return; }
switch (t->f) {
case F_R: a_need(3); a_emit32(enc_r(b, a_reg(0), a_reg(1), a_reg(2))); return;
case F_I: a_need(3); a_emit32(enc_i(b, a_reg(0), a_reg(1), (i32)a_imm(2))); return;
case F_SH:
a_need(3);
v = a_imm(2);
if (a_pass == 2 && v > 31) a_fail("SHIFT OVER 31");
a_emit32(enc_r(b, a_reg(0), a_reg(1), v & 31));
return;
case F_LD: a_need(2); rd = a_reg(0); rs = a_mem(1, &off); a_emit32(enc_i(b, rd, rs, off)); return;
case F_ST: a_need(2); rd = a_reg(0); rs = a_mem(1, &off); a_emit32(enc_s(b, rs, rd, off)); return;
case F_B: a_need(3); a_emit32(enc_b(b, a_reg(0), a_reg(1), a_imm(2))); return;
case F_U: a_need(2); a_emit32(enc_u(b, a_reg(0), a_imm(1))); return;
case F_JAL: /* JAL target (RA) or JAL rd,target */
if (a_nops == 1) { a_emit32(enc_j(1, a_imm(0))); return; }
a_need(2); a_emit32(enc_j(a_reg(0), a_imm(1))); return;
case F_JALR: /* JALR rs / JALR rd,off(rs) / JALR rd,rs,off */
if (a_nops == 1) { a_emit32(enc_i(b, 1, a_reg(0), 0)); return; }
if (a_nops == 2) { rd = a_reg(0); rs = a_mem(1, &off); a_emit32(enc_i(b, rd, rs, off)); return; }
a_need(3); a_emit32(enc_i(b, a_reg(0), a_reg(1), (i32)a_imm(2))); return;
case F_CSR: a_need(3); a_emit32(b | a_reg(0) << 7 | a_reg(2) << 15 | (u32)a_csr(1) << 20); return;
case F_CSRI:
a_need(3);
v = a_imm(2);
if (a_pass == 2 && v > 31) a_fail("VALUE OVER 31");
a_emit32(b | a_reg(0) << 7 | (v & 31) << 15 | (u32)a_csr(1) << 20);
return;
case F_FIX: a_need(0); a_emit32(b); return;
case P_LI:
a_need(2);
rd = a_reg(0);
a_undef = a_fwd = 0;
v = a_imm(1);
if (!a_undef && !a_fwd && (i32)v >= -2048 && (i32)v <= 2047) {
a_emit32(enc_i(0x13, rd, 0, (i32)v));
} else {
a_emit32(enc_u(0x37, rd, hi20(v)));
a_emit32(enc_i(0x13, rd, rd, lo12(v)));
}
return;
case P_LA:
a_need(2);
rd = a_reg(0);
v = a_imm(1) - a_pc;
a_emit32(enc_u(0x17, rd, hi20(v)));
a_emit32(enc_i(0x13, rd, rd, lo12(v)));
return;
case P_MV: a_need(2); a_emit32(enc_i(0x13, a_reg(0), a_reg(1), 0)); return;
case P_NOT: a_need(2); a_emit32(enc_i(0x4013, a_reg(0), a_reg(1), -1)); return;
case P_NEG: a_need(2); a_emit32(enc_r(0x40000033, a_reg(0), 0, a_reg(1))); return;
case P_SEQZ: a_need(2); a_emit32(enc_i(0x3013, a_reg(0), a_reg(1), 1)); return;
case P_SNEZ: a_need(2); a_emit32(enc_r(0x3033, a_reg(0), 0, a_reg(1))); return;
case P_SLTZ: a_need(2); a_emit32(enc_r(0x2033, a_reg(0), a_reg(1), 0)); return;
case P_SGTZ: a_need(2); a_emit32(enc_r(0x2033, a_reg(0), 0, a_reg(1))); return;
case P_J: a_need(1); a_emit32(enc_j(0, a_imm(0))); return;
case P_CALL: a_need(1); a_emit32(enc_j(1, a_imm(0))); return;
case P_JR: a_need(1); a_emit32(enc_i(0x67, 0, a_reg(0), 0)); return;
case P_RET: a_need(0); a_emit32(0x00008067); return;
case P_BZ: a_need(2); a_emit32(enc_b(b, a_reg(0), 0, a_imm(1))); return;
case P_BZS: a_need(2); a_emit32(enc_b(b, 0, a_reg(0), a_imm(1))); return;
case P_BSW: a_need(3); rs = a_reg(0); a_emit32(enc_b(b, a_reg(1), rs, a_imm(2))); return;
case P_CSRR: a_need(2); a_emit32(0x2073 | a_reg(0) << 7 | (u32)a_csr(1) << 20); return;
case P_CSRW: a_need(2); a_emit32(b | a_reg(1) << 15 | (u32)a_csr(0) << 20); return;
case P_CSRWI:
a_need(2);
v = a_imm(1);
if (a_pass == 2 && v > 31) a_fail("VALUE OVER 31");
a_emit32(b | (v & 31) << 15 | (u32)a_csr(0) << 20);
return;
}
}
/* DB/DH/DW items: numbers and (for DB) strings */
static void a_data(u8 size)
{
for (;;) {
a_sp();
if (*ap == '"' && size == 1) {
ap++;
while (*ap && *ap != '"') a_emit(*ap++);
if (*ap) ap++;
} else {
u32 v = a_expr();
u8 k;
for (k = 0; k < size; k++) a_emit(v >> (8 * k));
}
a_sp();
if (*ap != ',') break;
ap++;
}
if (*ap) a_fail("BAD DATA");
}
static u8 is_w(const char *w, const char *s) { return !strncmp(w, s, 8); }
/* Assemble one source line (uppercase except in quotes). */
static void a_line(char *s)
{
char w[8], lab[8];
u8 has_lab = 0, q = 0;
u16 m;
char *c;
a_err = 0;
/* cut the comment */
for (c = s; *c; c++) {
if (*c == '"') q = !q;
else if (*c == '\'' && !q && c[1] && c[2] == '\'') c += 2;
else if (*c == ';' && !q) { *c = 0; break; }
}
ap = s;
a_sp();
if (*ap >= '0' && *ap <= '9') { /* a BASIC line number */
const char *t = ap;
while (*t >= '0' && *t <= '9') t++;
if (*t == ' ' || !*t) ap = t;
}
a_sp();
if (!*ap) return;
if (!a_alpha(*ap)) { a_fail("SYNTAX ERROR"); return; }
a_name(w);
a_sp();
if (*ap == ':') { /* LABEL: */
ap++;
memcpy(lab, w, 8); has_lab = 1;
a_sp();
if (!*ap) { sym_def(lab, a_pc); return; }
if (!a_alpha(*ap)) { a_fail("SYNTAX ERROR"); return; }
a_name(w);
a_sp();
} else if (!strncmp(ap, "EQU", 3) && !a_alnum(ap[3])) {
memcpy(lab, w, 8); has_lab = 1;
memcpy(w, "EQU\0\0\0\0\0", 8);
ap += 3;
}
if (is_w(w, "EQU")) {
u32 v = a_expr();
if (!has_lab) a_fail("EQU NEEDS A NAME");
else if (a_undef && a_pass == 1) a_fail("EQU BEFORE ITS VALUE");
else sym_def(lab, v);
return;
}
if (has_lab) sym_def(lab, a_pc);
if (is_w(w, "ORG")) { a_pc = a_expr(); return; }
if (is_w(w, "END")) { a_end = 1; return; }
if (is_w(w, "DB") || is_w(w, "DEFB") || is_w(w, "DEFM")) { a_data(1); return; }
if (is_w(w, "DH")) { a_data(2); return; }
if (is_w(w, "DW") || is_w(w, "DEFW")) { a_data(4); return; }
if (is_w(w, "DS") || is_w(w, "DEFS")) { a_pc += a_expr(); return; }
if (is_w(w, "ALIGN")) {
u32 n = a_expr();
if (!n || (n & (n - 1))) a_fail("ALIGN TO A POWER OF 2");
else while (a_pc & (n - 1)) a_emit(0);
return;
}
for (m = 0; m < NINS; m++)
if (!strncmp(w, itab[m].name, 8)) break;
if (m == NINS) { a_fail("UNKNOWN INSTRUCTION"); return; }
a_split();
if (a_err) return;
a_instr(&itab[m]);
}
/* Upper-case a source line outside quotes, in place. */
static void a_upper(char *s)
{
u8 q = 0;
for (; *s; s++) {
if (*s == '"') q = !q;
else if (*s == '\'' && !q && s[1] && s[2] == '\'') s += 2;
else if (!q && *s >= 'a' && *s <= 'z') *s -= 32;
if (*s == '\t') *s = ' ';
}
}
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
# Compile the monitor and write monitor.mem (its 32 KB bank) and monitor.bin;
# also out/monitor-host, the disassembler and assembler for the PC (tests).
set -e
cd "$(dirname "$0")"
source ../scripts/rv_env.sh
mkdir -p out
CFLAGS="$RV_ARCH -Os -mno-relax -ffunction-sections -fdata-sections -fno-common -Wall -I../include"
${RV_PREFIX}gcc $CFLAGS -c -o out/crt0.o crt0.S
${RV_PREFIX}gcc $CFLAGS -c -o out/monitor.o monitor.c
${RV_PREFIX}gcc $CFLAGS -c -o out/string.o ../lib/string.c
${RV_PREFIX}gcc $CFLAGS -c -o out/setjmp.o ../lib/setjmp.S
${RV_PREFIX}gcc $RV_ARCH -nostdlib -nostartfiles -T monitor.ld -Wl,--no-relax -Wl,--gc-sections \
-Wl,--build-id=none -Wl,-Map,out/monitor.map -o out/monitor.elf \
out/crt0.o out/monitor.o out/string.o out/setjmp.o -lgcc
${RV_PREFIX}objcopy -O binary -j .text -j .data out/monitor.elf monitor.bin
${RV_PREFIX}nm -n out/monitor.elf > out/monitor.sym
python3 ../tools/bin2mem.py monitor.bin monitor.mem 8192
${RV_PREFIX}size out/monitor.elf
cc -O1 -Wall -o out/monitor-host monitor.c
+95
View File
@@ -0,0 +1,95 @@
# Monitor start-up. The monitor has ROM at 20000-27FFF and RAM (data only) at
# 28000-29FFF. It is entered by the NMI (20000h: the Pause key, MONITOR, a
# breakpoint or a single step) or by a trap (20004h, BASIC's mtvec: an illegal
# instruction, a misaligned access, ebreak, ecall, an unhandled interrupt).
# The program's registers go to u (struct regs in monitor.c), the monitor runs,
# and mnret takes the program back to u.pc with its registers as u has them.
.equ U, 0x29F00 # struct regs, below RAM's last 256 bytes
.equ INITED, 0x29FFC # C data is set up once, then kept
.equ U_PC, 128
.equ U_HOW, 132 # 0 NMI, 1 trap
.equ U_CAUSE, 136
.equ U_TVAL, 140
.equ U_STATUS, 144
.section .text.start, "ax"
.globl _start, u
.set u, U
_start:
j nmi_entry # 20000h
j trap_entry # 20004h
.macro SAVE_REGS
sw x1, 4(sp)
.irp n, 3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
sw x\n, 4*\n(sp)
.endr
csrr t0, 0x740 # mnscratch: the program's sp
sw t0, 8(sp)
sw zero, 0(sp)
.endm
nmi_entry:
csrw 0x740, sp # mnscratch
li sp, U
SAVE_REGS
csrr t0, 0x741 # mnepc
sw t0, U_PC(sp)
sw zero, U_HOW(sp)
j common
trap_entry:
csrci 0x744, 8 # NMIE off first: no NMI may reuse mnscratch
csrw 0x740, sp
li sp, U
SAVE_REGS
csrr t0, mepc
sw t0, U_PC(sp)
li t0, 1
sw t0, U_HOW(sp)
csrr t0, mcause
sw t0, U_CAUSE(sp)
csrr t0, mtval
sw t0, U_TVAL(sp)
csrr t0, mstatus
sw t0, U_STATUS(sp)
common:
li sp, U # the monitor's stack, below u
li t0, INITED
lw t1, 0(t0)
li t2, 0xA5A5
beq t1, t2, 3f
la a0, __data_start # copy initialised data
la a1, __data_load
la a2, __data_end
1: bgeu a0, a2, 2f
lw t1, 0(a1)
sw t1, 0(a0)
addi a0, a0, 4
addi a1, a1, 4
j 1b
2: la a0, __bss_start # clear the rest
la a2, __bss_end
21: bgeu a0, a2, 22f
sw zero, 0(a0)
addi a0, a0, 4
j 21b
22: sw t2, 0(t0)
3: call mon_main
li sp, U
lw t0, U_PC(sp)
csrw 0x741, t0 # mnepc
lw t0, U_HOW(sp)
beqz t0, 4f
csrr t0, mstatus # from a trap: interrupts back as they were
andi t0, t0, 0x80
beqz t0, 4f
csrsi mstatus, 8
4: lw x1, 4(sp)
.irp n, 3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
lw x\n, 4*\n(sp)
.endr
lw sp, 8(sp)
.word 0x70200073 # mnret
BIN
View File
Binary file not shown.
+1118
View File
File diff suppressed because it is too large. Load diff
+32
View File
@@ -0,0 +1,32 @@
/* The monitor: ROM 20000-27FFF (writes ignored), RAM 28000-29FFF (data only)
with the saved registers at 29F00h (crt0.S) and the stack below them. */
OUTPUT_ARCH("riscv")
ENTRY(_start)
MEMORY
{
ROM (rx) : ORIGIN = 0x20000, LENGTH = 0x8000
RAM (rw) : ORIGIN = 0x28000, LENGTH = 0x1B00
}
SECTIONS
{
.text : {
KEEP(*(.text.start))
*(.text .text.*)
*(.rodata .rodata.* .srodata .srodata.*)
. = ALIGN(4);
} > ROM
.data : ALIGN(4) {
__data_start = .;
*(.data .data.* .sdata .sdata.*)
. = ALIGN(4);
__data_end = .;
} > RAM AT > ROM
__data_load = LOADADDR(.data);
.bss (NOLOAD) : ALIGN(4) {
__bss_start = .;
*(.sbss .sbss.* .bss .bss.* COMMON)
. = ALIGN(4);
__bss_end = .;
} > RAM
/DISCARD/ : { *(.comment) *(.riscv.attributes) }
}
+8192
View File
File diff suppressed because it is too large. Load diff
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/env python3
"""Assemble a test program with the monitor's assembler (out/monitor-host)
and with GNU as, and check the bytes are the same.
python3 test-asm.py
"""
import os
import re
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
# the monitor's syntax; to_gnu() below turns it into GNU as's
SRC = r"""
ORG 12000H
COUNT EQU 10
START: LA A1,MSG ; the message
LI A2,COUNT
LI A3,BIG ; defined further on: LUI and ADDI
LI T0,-2048
LI T1,2047
LOOP: LBU A0,0(A1)
BEQZ A0,DONE
WAIT: LBU T0,-256(ZERO)
ANDI T0,T0,2
BEQZ T0,WAIT
SB A0,-255(ZERO)
ADDI A1,A1,1
J LOOP
DONE: ADDI A2,A2,-1
BNEZ A2,START
MUL A4,A2,A3
DIVU A5,A4,A3
REMU A6,A4,A3
SLLI A7,A6,3
SRAI S2,A7,1
SUB S3,S2,A7
NEG S4,S3
NOT S5,S4
SEQZ S6,S5
SNEZ S7,S5
BGT S6,S7,DONE
BLEU S6,S7,LOOP
BGTZ S6,LOOP
BLEZ S6,LOOP
JAL RA,DONE
JAL DONE
JALR T0
JALR RA,4(T0)
JR T0
CSRR A0,MSTATUS
CSRW MSCRATCH,A0
CSRSI MSTATUS,8
CSRRW A1,0x305,A2
LUI S8,0x12345
AUIPC S9,1
SW S9,-4(SP)
SH S9,2(SP)
LH S10,2(SP)
LHU S11,2(SP)
LW S11,0(SP)
ECALL
EBREAK
MRET
WFI
FENCE
FENCE.I
NOP
RET
MSG: DB "HI",13,10,0
ALIGN 4
TAB: DW START,DONE,0x12345678
DH 1234,0xFFFF
DS 6
DB 'A'
BIG EQU 0x12345
"""
def to_gnu(src):
out = [".text", ".option norelax", ".option norvc", "_start:"]
for line in src.strip().splitlines():
line = line.split(";")[0]
line = line.replace("$", ".")
m = re.match(r"(\w+)\s+EQU\s+(.*)", line.strip())
if m:
out.append(".equ %s, %s" % (m.group(1).lower(), m.group(2).lower()))
continue
if line.strip().startswith("ORG"):
continue
line = re.sub(r'\bDB "(\w+)",', r'.ascii "\1"\n .byte ', line)
line = re.sub(r"\bDB\b", ".byte", line)
line = re.sub(r"\bDH\b", ".half", line)
line = re.sub(r"\bDW\b", ".word", line)
line = re.sub(r"\bDS\s+(\d+)", r".skip \1", line)
line = re.sub(r"\bALIGN (\d+)", r".balign \1, 0", line)
line = re.sub(r"\bJAL DONE\b", "jal ra,DONE", line)
line = re.sub(r"\bJALR T0\b", "jalr ra,0(t0)", line)
line = re.sub(r"\bLI A3,BIG\b", "lui a3,%hi(BIG)\n addi a3,a3,%lo(BIG)", line)
out.append(line.lower().replace("'a'", "'A'").replace('"hi"', '"HI"'))
return "\n".join(out) + "\n"
def main():
pre = subprocess.run(["bash", "-c", "source %s/../scripts/rv_env.sh; echo $RV_PREFIX" % HERE],
capture_output=True, text=True).stdout.strip()
ours = subprocess.run([os.path.join(HERE, "out", "monitor-host"), "asmbin"], input=SRC,
capture_output=True, text=True).stdout.strip()
if not re.fullmatch(r"[0-9A-F]{5} [0-9A-F]+", ours):
print("FAIL the monitor's assembler: " + ours)
sys.exit(1)
start, ours = ours.split()
tmp = tempfile.mkdtemp()
open(os.path.join(tmp, "t.s"), "w").write(to_gnu(SRC))
subprocess.run([pre + "as", "-march=rv32im_zicsr_zifencei", "-mno-relax", "-o", os.path.join(tmp, "t.o"),
os.path.join(tmp, "t.s")], check=True)
subprocess.run([pre + "ld", "-m", "elf32lriscv", "--no-relax", "-e", "0x12000", "-Ttext=0x12000", "-o", os.path.join(tmp, "t.elf"),
os.path.join(tmp, "t.o")], check=True)
subprocess.run([pre + "objcopy", "-O", "binary", os.path.join(tmp, "t.elf"), os.path.join(tmp, "t.bin")],
check=True)
gnu = open(os.path.join(tmp, "t.bin"), "rb").read().hex().upper()
# GNU pads the section's end to a word
if len(gnu) > len(ours) and set(gnu[len(ours):]) <= {"0"}:
gnu = gnu[:len(ours)]
ok = start == "12000" and ours == gnu
if not ok:
for i in range(0, max(len(ours), len(gnu)), 8):
if ours[i:i + 8] != gnu[i:i + 8]:
print("first difference at %05X: monitor %s, GNU %s" % (0x12000 + i // 2, ours[i:i + 8], gnu[i:i + 8]))
break
print("lengths: monitor %d bytes, GNU %d" % (len(ours) // 2, len(gnu) // 2))
print(("PASS" if ok else "FAIL") + " %d bytes from 12000h the same as GNU as" % (len(ours) // 2))
sys.exit(0 if ok else 1)
if __name__ == "__main__":
main()
+191
View File
@@ -0,0 +1,191 @@
#!/usr/bin/env python3
"""Check the monitor's disassembler and assembler (out/monitor-host, built by
build.sh) on random instructions of every kind:
- each word disassembles to the same instruction GNU objdump shows (same
mnemonic, registers and values), and
- the monitor's assembler turns that text back into the same word.
python3 test-disasm.py [count per kind]
"""
import os
import random
import re
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "tools"))
HOST = os.path.join(HERE, "out", "monitor-host")
N = int(sys.argv[1]) if len(sys.argv) > 1 else 300
random.seed(1)
def prefix():
out = subprocess.run(["bash", "-c", "source %s/../scripts/rv_env.sh; echo $RV_PREFIX" % HERE],
capture_output=True, text=True).stdout.strip()
return out
def r():
return random.randrange(32)
def words():
"""Random valid RV32IM / Zicsr / system instructions."""
ws = []
csrs = [0x300, 0x301, 0x304, 0x305, 0x340, 0x341, 0x342, 0x343, 0x344, 0x744, 0xB00,
0xC00, 0xC01, 0xC82, 0xF14, 0x7A0, 0x123]
for _ in range(N):
imm = random.randrange(4096)
ws.append(0x37 | r() << 7 | random.randrange(1 << 20) << 12) # lui
ws.append(0x17 | r() << 7 | random.randrange(1 << 20) << 12) # auipc
j = random.randrange(1 << 20) << 1 # jal
v = j
ws.append(0x6F | r() << 7 | (v >> 12 & 0xFF) << 12 | (v >> 11 & 1) << 20 |
(v >> 1 & 0x3FF) << 21 | (v >> 20 & 1) << 31)
ws.append(0x67 | r() << 7 | r() << 15 | imm << 20) # jalr
b = random.randrange(1 << 12) << 1
f3 = random.choice([0, 1, 4, 5, 6, 7])
ws.append(0x63 | f3 << 12 | r() << 15 | r() << 20 | (b >> 11 & 1) << 7 |
(b >> 1 & 15) << 8 | (b >> 5 & 0x3F) << 25 | (b >> 12 & 1) << 31)
ws.append(0x03 | random.choice([0, 1, 2, 4, 5]) << 12 | r() << 7 | r() << 15 | imm << 20)
s = random.randrange(4096)
ws.append(0x23 | random.choice([0, 1, 2]) << 12 | (s & 31) << 7 | r() << 15 | r() << 20 |
(s >> 5) << 25)
ws.append(0x13 | random.choice([0, 2, 3, 4, 6, 7]) << 12 | r() << 7 | r() << 15 | imm << 20)
ws.append(0x13 | random.choice([(1, 0), (5, 0), (5, 0x20)])[0] << 12 | r() << 7 | r() << 15 |
random.randrange(32) << 20)
f = random.choice([(0, 0), (0, 0x20), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (5, 0x20),
(6, 0), (7, 0)] + [(k, 1) for k in range(8)])
ws.append(0x33 | f[0] << 12 | f[1] << 25 | r() << 7 | r() << 15 | r() << 20)
ws.append(0x73 | random.choice([1, 2, 3, 5, 6, 7]) << 12 | r() << 7 | r() << 15 |
random.choice(csrs) << 20)
# the special cases the disassembler shortens
ws.append(0x13 | r() << 7 | 0 << 15 | imm << 20) # li
ws.append(0x13 | r() << 7 | r() << 15) # mv
ws.append(0x00008067) # ret
ws += [0x13, 0x73, 0x00100073, 0x30200073, 0x70200073, 0x10500073, 0x0FF0000F, 0x100F]
return ws
def norm_gnu(text, addr):
"""objdump's operand text -> list of tokens to compare."""
text = re.sub(r"<[^>]*>|#.*", "", text).strip()
m = text.split(None, 1)
mn = m[0].upper()
ops = m[1].split(",") if len(m) > 1 else []
return mn, [o.strip().upper() for o in ops]
def val(tok, base10_ok=True):
tok = tok.strip()
if re.fullmatch(r"-?0X[0-9A-F]+", tok):
return int(tok, 16)
if re.fullmatch(r"-?[0-9A-F]+H", tok):
return int(tok[:-1], 16)
if re.fullmatch(r"-?\d+", tok):
return int(tok)
return None
CSRN = {"MSTATUS": 0x300, "MISA": 0x301, "MIE": 0x304, "MTVEC": 0x305, "MSCRATCH": 0x340,
"MEPC": 0x341, "MCAUSE": 0x342, "MTVAL": 0x343, "MIP": 0x344, "MNSCRATCH": 0x740,
"MNEPC": 0x741, "MNCAUSE": 0x742, "MNSTATUS": 0x744, "TSELECT": 0x7A0, "TDATA1": 0x7A1,
"TDATA2": 0x7A2, "TCONTROL": 0x7A5, "MCYCLE": 0xB00, "MINSTRET": 0xB02, "MCYCLEH": 0xB80,
"MINSTRETH": 0xB82, "CYCLE": 0xC00, "TIME": 0xC01, "INSTRET": 0xC02, "CYCLEH": 0xC80,
"TIMEH": 0xC81, "INSTRETH": 0xC82, "MHARTID": 0xF14}
def same(gnu_mn, gnu_ops, our):
m = our.split(None, 1)
mn = m[0]
ops = [o.strip() for o in m[1].split(",")] if len(m) > 1 else []
# objdump's other spellings of the same instructions
if gnu_mn == "JR" and gnu_ops and "(" in gnu_ops[0]:
gnu_mn, gnu_ops = "JALR", ["ZERO"] + gnu_ops
elif gnu_mn == "JALR" and len(gnu_ops) == 1 and "(" in gnu_ops[0]:
gnu_ops = ["RA"] + gnu_ops
elif gnu_mn.startswith("RD") and gnu_mn[2:] in CSRN:
gnu_mn, gnu_ops = "CSRR", gnu_ops + [gnu_mn[2:]]
gnu_ops = [str(CSRN[o]) if o in CSRN else o for o in gnu_ops]
ops = [str(CSRN[o]) if o in CSRN else o for o in ops]
alias = {"FENCE.I": "FENCE.I", "UNIMP": "DW"}
if alias.get(gnu_mn, gnu_mn) != mn:
return False
# objdump writes "fence iorw,iorw"
if mn == "FENCE":
return True
if len(ops) != len(gnu_ops):
return False
for a, b in zip(gnu_ops, ops):
if a == b:
continue
ma, mb = re.fullmatch(r"(.*)\((\w+)\)", a), re.fullmatch(r"(.*)\((\w+)\)", b)
if ma and mb:
if ma.group(2) != mb.group(2) or val(ma.group(1) or "0") != val(mb.group(1) or "0"):
return False
continue
va, vb = val(a), val(b)
if va is None or vb is None:
return False
if va & 0xFFFFFFFF != vb & 0xFFFFFFFF:
return False
return True
def main():
pre = prefix()
ws = words()
tmp = tempfile.mkdtemp()
with open(os.path.join(tmp, "w.bin"), "wb") as f:
for w in ws:
f.write(w.to_bytes(4, "little"))
dump = subprocess.run([pre + "objdump", "-D", "-b", "binary", "-m", "riscv:rv32",
"-M", "numeric", "--adjust-vma=0x1000", os.path.join(tmp, "w.bin")],
capture_output=True, text=True).stdout
gnu = {}
for line in dump.splitlines():
mm = re.match(r"\s*([0-9a-f]+):\s+([0-9a-f]{8})\s+(.*)", line)
if mm and int(mm.group(1), 16) >= 0x1000:
gnu[int(mm.group(1), 16) - 0x1000] = mm.group(3)
ours = subprocess.run([HOST, "dis"], input="".join("%08X\n" % w for w in ws),
capture_output=True, text=True).stdout.splitlines()
regn = ["ZERO", "RA", "SP", "GP", "TP", "T0", "T1", "T2", "S0", "S1"] + \
["A%d" % i for i in range(8)] + ["S%d" % i for i in range(2, 12)] + ["T3", "T4", "T5", "T6"]
bad_dis = 0
for i, (w, o) in enumerate(zip(ws, ours)):
g = gnu.get(4 * i)
if g is None or w == 0x70200073: # (binutils doesn't know MNRET)
continue
gm, gops = norm_gnu(g, 0x1000)
# objdump -M numeric prints x registers: map to ABI names; and its
# branch/jump targets are relative to this word (we disassemble at 1000h)
gops = [re.sub(r"\bX(\d+)\b", lambda q: regn[int(q.group(1))], t) for t in gops]
if gm in ("J", "JAL", "BEQ", "BNE", "BLT", "BGE", "BLTU", "BGEU", "BEQZ", "BNEZ", "BLTZ",
"BGEZ", "BLEZ", "BGTZ"):
v = val(gops[-1])
if v is not None:
gops[-1] = str((v - 4 * i) & 0xFFFFFFFF)
if not same(gm, gops, o):
bad_dis += 1
if bad_dis <= 15:
print("DIS %08X: objdump '%s', monitor '%s'" % (w, g, o))
# round trip through the monitor's assembler, one instruction at 1000h each
bad_asm = 0
back = subprocess.run([HOST, "asm"], input="".join("ORG 1000H\n%s\n" % o for o in ours),
capture_output=True, text=True).stdout.splitlines()
for w, o, b in zip(ws, ours, back):
want = 0x0FF0000F if (w & 0x707F) == 0x0F else w
if b.startswith("ERROR") or int(b, 16) != want:
bad_asm += 1
if bad_asm <= 15:
print("ASM %08X -> '%s' -> %s" % (w, o, b))
print("%d instructions: %d disassembled differently from objdump, %d assembled back wrong"
% (len(ws), bad_dis, bad_asm))
sys.exit(1 if bad_dis or bad_asm else 0)
if __name__ == "__main__":
main()