wasm.c

C source for Emulating a round-screen ESP32 board, 71 lines. Raw file

// wasm.c - the self-test front-end. The same emulator core (xtensa.c, mem.c,
// mmio.c, co5300.c) that boots the real firmware is here driven on a tiny
// bare-metal payload (selftest/wtest.elf) loaded straight into SRAM: no mask
// ROM and no 32 MB flash image, so it starts instantly and is small enough to
// ship. Compiled to WebAssembly for the emulator article's live hero, and to a
// native binary (-DEMU_SELFTEST_MAIN) for testing.
//
// The guest prints to UART0, which mmio.c sends to stdout; under emscripten
// that surfaces through Module.print, so the page shows the real console. The
// CO5300 frame memory is read out with co5300_rgba() for the panel canvas.

#include <stdint.h>
#include <stdlib.h>
#include "mem.h"
#include "xtensa.h"

void     elf_load(const char *path);
void     co5300_rgba(uint8_t *out);
void     co5300_dump_ppm(const char *path);
void     systimer_step(void);
extern uint64_t g_ticks;

// _start is linked first in wtest.ld, so the entry point is the SRAM origin.
#define SELF_ENTRY 0x40380000u
#define SELF_SP    0x3FCEB000u
#define SCREEN_W   466
#define SCREEN_H   466

int g_mspi_dbg = 0;   // MSPI trace flag (normally owned by the CLI main.c, unused here)

static xtensa_t cpu;
static uint8_t  s_rgba[SCREEN_W * SCREEN_H * 4];

// Load the self-test and seed core 0 exactly as the real boot seeds it.
void emu_boot(const char *elf_path)
{
    mem_init();
    elf_load(elf_path ? elf_path : "wtest.elf");
    xt_reset(&cpu, SELF_ENTRY);
    cpu.core_id = 0;
    xt_set_a(&cpu, 1, SELF_SP);
    xt_set_a(&cpu, 0, 0x80000000);
}

// Run up to n instructions; returns 1 once the core has halted.
int emu_step(int n)
{
    for (int i = 0; i < n && !cpu.halted; i++) {
        g_ticks++;
        systimer_step();
        xt_step(&cpu);
    }
    return cpu.halted;
}

uint8_t *emu_screen(void) { co5300_rgba(s_rgba); return s_rgba; }
int      emu_width(void)  { return SCREEN_W; }
int      emu_height(void) { return SCREEN_H; }
uint32_t emu_pc(void)     { return cpu.pc; }

#ifdef EMU_SELFTEST_MAIN
#include <stdio.h>
int main(int argc, char **argv)
{
    emu_boot(argc > 1 ? argv[1] : "wtest.elf");
    emu_step(argc > 2 ? atoi(argv[2]) : 8000000);
    co5300_dump_ppm(argc > 3 ? argv[3] : "/tmp/selftest.ppm");
    printf("\n[selftest] final pc=%08x %s\n", cpu.pc, cpu.halted ? cpu.stopmsg : "(idle)");
    return 0;
}
#endif