Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
Tools: ce_emu, TI-84 Plus CE programs run without a calculator
Mason363418920070cad
diff --git a/tools/ce_emu.py b/tools/ce_emu.pynew file mode 100644index 00000000..6ee60fa4--- /dev/null+++ b/tools/ce_emu.py@@ -0,0 +1,261 @@+#!/usr/bin/env python3+"""Run a TI-84 Plus CE program without a calculator or a ROM: CEmu's core with a small OS of its own (tools/ce_emu).++ python3 tools/ce_emu.py PROG.8xp [VARS.8xv ...] [--keys ...] [--shots ...] [--ms N] [--out DIR]+ python3 tools/ce_emu.py game ID [same options] a NumPlay game's CE build (games/ID/build/ti84ce)+ python3 tools/ce_emu.py sheet [ID ...] [--ms N] [-j N] [--out DIR]+ every CE build (games.json "ports"), a sheet of screens++Options:+ --keys "1500-1600:2nd,3000:clear" keys held from one time to another (ms; one time alone: 100 ms). CE names:+ 2nd mode del alpha math enter clear up down left right 0-9 add sub mul div+ power square ln log sin cos tan comma lparen rparen dot chs vars stat prgm+ apps xton sto recip yequ window zoom trace graph on; or NumWorks names on+ NumPlay's layout: ok (2nd) exe (enter) back (clear) home (mode)...+ --shots "2000,4000:play.png" the screen at these times (PNG)+ --ms N how long, in the calculator's time (5000)+ --ram NAME,... these variables in RAM, the others where their files say (the archive)+ --libs FILE|none the CE C libraries (default: clibs.8xg v15.0, downloaded once into+ ~/Documents/Assets/toolchains/ce-libs)+ --frame SYMBOL|ADDR a frame each time the CPU gets there (default: eadk_display_wait_for_vblank+ or eadk_keyboard_scan when the program has them, from its .obj next to it)+ --profile N the N functions the CPU was found in most+ --vars-out DIR the appvars and programs at the end, as files+ --rev m|i|pre-a the hardware revision (m, every CE since 2019)+ --trace every OS call+ --json the full report++It stops at a crash (a write to flash or to the stack limit, the reset vector, unmapped memory, an OS call it+lacks), a hang, an OS error, or the program's end, and says which. Frame rates are the calculator's: 48 MHz,+the LCD's memory traffic and the flash's wait states included."""+import concurrent.futures as cf+import hashlib+import json+import os+import re+import subprocess+import sys+import tempfile+import urllib.request++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+HERE = os.path.join(ROOT, "tools", "ce_emu")+EXE = os.path.join(HERE, "build", "ce_emu")+LIBS_DIR = os.path.expanduser("~/Documents/Assets/toolchains/ce-libs/v15.0")+LIBS_URL = "https://github.com/CE-Programming/libraries/releases/download/v15.0/clibs.8xg"+LIBS_SHA = "450bdefb41fe263f8d2d161b7cf431bbf99711f2ef78f02f796d530ed12dfbf0"+FRAME_SYMBOLS = ("_eadk_display_wait_for_vblank", "_eadk_keyboard_scan")+++def build():+ r = subprocess.run(["make", "-s", "-C", HERE], capture_output=True, text=True)+ if r.returncode:+ raise SystemExit("ce_emu: the build failed\n" + r.stdout + r.stderr)+++def libs():+ path = os.path.join(LIBS_DIR, "clibs.8xg")+ if not os.path.exists(path):+ os.makedirs(LIBS_DIR, exist_ok=True)+ data = urllib.request.urlopen(LIBS_URL).read()+ if hashlib.sha256(data).hexdigest() != LIBS_SHA:+ raise SystemExit("ce_emu: clibs.8xg isn't the one released")+ open(path, "wb").write(data)+ return path+++def symbols(prog):+ """The program's symbols, from the .obj (ELF) the CE toolchain leaves next to the .8xp."""+ obj = os.path.splitext(prog)[0] + ".obj"+ if not os.path.exists(obj):+ return {}+ try:+ from elftools.elf.elffile import ELFFile+ except ImportError:+ return {}+ out = {}+ with open(obj, "rb") as f:+ tab = ELFFile(f).get_section_by_name(".symtab")+ for s in tab.iter_symbols() if tab else []:+ if s.name and s["st_value"] >= 0xD00000 and not s.name.startswith(".L"):+ out[s.name] = s["st_value"]+ return out+++def profile_lines(samples, syms, n):+ import bisect+ import collections+ rom = {}+ for line in open(os.path.join(HERE, "build", "rom.map")):+ m = re.match(r"\s+0x([0-9a-f]{8})\s+(_\S+)\s*$", line)+ if m:+ rom["rom " + m.group(2)] = int(m.group(1), 16)+ table = sorted([(a, k) for k, a in syms.items()] + [(a, k) for k, a in rom.items()])+ addrs = [a for a, _ in table]+ hits = collections.Counter()+ total = 0+ for line in open(samples):+ a, k = line.split()+ a, k = int(a, 16), int(k)+ total += k+ i = bisect.bisect_right(addrs, a) - 1+ hits[table[i][1] if i >= 0 and a - addrs[i] < 0x2000 else f"?{a:06X}"] += k+ return [f"{100 * k / max(total, 1):5.1f}% {name}" for name, k in hits.most_common(n)]+++def run(files, keys="", shots="", ms=5000, out=".", ram="", lib=None, frame=None, rev="m", trace=False,+ vars_out=None, profile=0):+ """One run; its report (a dict)."""+ build()+ prog = next(f for f in files if f.lower().endswith(".8xp"))+ syms = symbols(prog)+ addr = None+ if frame:+ addr = int(frame, 0) if re.match(r"0x|\d", frame) else syms.get("_" + frame.lstrip("_"))+ if addr is None:+ raise SystemExit(f"ce_emu: no symbol {frame} in {os.path.splitext(prog)[0]}.obj")+ else:+ frame = next((s for s in FRAME_SYMBOLS if s in syms), None)+ addr = syms.get(frame) if frame else None+ with tempfile.TemporaryDirectory() as tmp:+ rep = os.path.join(tmp, "report.json")+ cmd = [EXE, "--rom", os.path.join(HERE, "build", "rom.bin"), "--names", os.path.join(HERE, "build", "ti84pceg.inc"),+ "--ms", str(ms), "--out", out, "--report", rep, "--rev", rev]+ cmd += ["--keys", keys] if keys else []+ cmd += ["--shots", shots] if shots else []+ cmd += ["--ram", ram] if ram else []+ cmd += ["--frame", hex(addr)] if addr else []+ cmd += ["--trace"] if trace else []+ cmd += ["--vars-out", vars_out] if vars_out else []+ cmd += ["--profile", os.path.join(tmp, "profile")] if profile else []+ cmd += files + ([lib] if lib else [])+ os.makedirs(out, exist_ok=True)+ r = subprocess.run(cmd, capture_output=True, text=True)+ if not os.path.exists(rep):+ raise SystemExit(f"ce_emu: {r.stderr.strip() or 'no report'}")+ report = json.load(open(rep))+ report["frame_symbol"] = frame.lstrip("_") if frame and addr else None+ report["stderr"] = r.stderr+ if profile:+ report["profile"] = profile_lines(os.path.join(tmp, "profile"), syms, profile)+ return report+++def summary(rep):+ s = f"{rep['program']}: {rep['status']}" + (f" ({rep['detail']})" if rep["detail"] else "")+ s += f"\n {rep['ms'] / 1000:.2f} s in {rep['wall_s']:.2f} s ({rep['speed']:.1f}x)"+ if rep["frames"] > 1:+ s += (f", {rep['fps']:.1f} fps ({rep['frame_symbol']}): {rep['frame_ms']:.1f} ms a frame, 95% under "+ f"{rep['frame_ms_p95']:.1f}, slowest {rep['frame_ms_max']:.1f}, {rep['cycles_per_frame'] / 1e6:.2f} M cycles")+ elif rep["lcd_base_writes"] > 2:+ s += f", {rep['lcd_base_writes']} buffer swaps"+ s += f"\n stack {rep['stack_bytes']} of 4096 bytes, {rep['free_ram']} bytes of RAM free, {rep['screen_changes']} screen changes"+ if rep["text"]:+ s += "\n home screen: " + rep["text"].replace("\n", " / ")+ if rep["warnings"]:+ s += "\n warnings: " + rep["warnings"].replace("\n", " / ")+ for line in rep.get("profile", []):+ s += "\n " + line+ return s+++def game_files(g):+ sys.path.insert(0, os.path.join(ROOT, "tools"))+ import ports+ fs = [p for p, _ in ports.outputs("ti84ce", g)]+ if not all(os.path.exists(p) for p in fs):+ raise SystemExit(f"ce_emu: {g} isn't built for the CE (python3 tools/ports.py build ti84ce {g})")+ return fs+++def sheet(todo, ms, out, jobs):+ """Every game for ms: its title (before OK), OK twice, the arrows; three screens each, side by side."""+ from PIL import Image, ImageDraw+ t1, t2 = ms * 2 // 5, ms * 3 // 5+ keys = f"{t1}-{t1 + 100}:2nd,{t2}-{t2 + 100}:2nd,{t2 + 400}-{t2 + 700}:right,{t2 + 900}-{t2 + 1200}:up," \+ f"{t2 + 1400}-{t2 + 1700}:left,{t2 + 1900}-{t2 + 2200}:down"+ times = [t1 - 50, t2 + 300, ms - 50]++ def one(g):+ d = os.path.join(out, g)+ try:+ return g, run(game_files(g), keys=keys, shots=",".join(f"{t}:{i}.png" for i, t in enumerate(times)), ms=ms,+ out=d, lib=libs())+ except SystemExit as e:+ return g, {"program": g, "status": "error", "detail": str(e)}++ build()+ with cf.ThreadPoolExecutor(jobs) as ex:+ results = list(ex.map(one, todo))+ w, h, cols = 160, 120, 4+ rows = (len(results) + cols - 1) // cols+ im = Image.new("RGB", (cols * (3 * w + 10), rows * (h + 26)), "white")+ dr = ImageDraw.Draw(im)+ lines = []+ for i, (g, rep) in enumerate(results):+ x, y = (i % cols) * (3 * w + 10), (i // cols) * (h + 26)+ for k in range(3):+ p = os.path.join(out, g, f"{k}.png")+ if os.path.exists(p):+ im.paste(Image.open(p).resize((w, h)), (x + k * w, y + 26))+ fps = f", {rep['fps']:.0f} fps" if rep.get("frames", 0) > 1 else ""+ bad = rep["status"] not in ("ok", "exited")+ dr.text((x + 2, y + 1), f"{g}: {rep['status']}{fps}", fill="red" if bad else "black")+ if bad:+ dr.text((x + 2, y + 12), rep["detail"][:80], fill="red")+ lines.append(summary(rep) if "ms" in rep else f"{g}: {rep['status']} ({rep['detail']})")+ path = os.path.join(out, "sheet.png")+ im.save(path)+ open(os.path.join(out, "summary.txt"), "w").write("\n".join(lines) + "\n")+ json.dump({g: r for g, r in results}, open(os.path.join(out, "reports.json"), "w"), indent=1)+ print("\n".join(lines))+ good = sum(r["status"] in ("ok", "exited") for _, r in results)+ print(f"{good}/{len(results)} run without a crash or hang; {path}")+ return 0 if good == len(results) else 1+++def main():+ a = sys.argv[1:]+ if not a or a[0] in ("-h", "--help"):+ print(__doc__)+ return 1+ opts = {"keys": "", "shots": "", "ms": "5000", "out": ".", "ram": "", "libs": None, "frame": None, "rev": "m",+ "vars-out": None, "profile": "0", "j": "6"}+ flags = {"trace": False, "json": False}+ pos = []+ i = 0+ while i < len(a):+ k = a[i].lstrip("-")+ if a[i].startswith("-") and k in opts and i + 1 < len(a):+ opts[k] = a[i + 1]+ i += 2+ elif a[i].startswith("-") and k in flags:+ flags[k] = True+ i += 1+ else:+ pos.append(a[i])+ i += 1+ if pos and pos[0] == "sheet":+ sys.path.insert(0, os.path.join(ROOT, "tools"))+ import ports+ todo = pos[1:] or ports.games([], "ti84ce")+ out = opts["out"] if opts["out"] != "." else os.path.join(ROOT, "build", "ce_emu")+ return sheet(todo, int(opts["ms"]) if opts["ms"] != "5000" else 10000, out, int(opts["j"]))+ if pos and pos[0] == "game":+ files = game_files(pos[1]) + pos[2:]+ else:+ files = pos+ if not any(f.lower().endswith(".8xp") for f in files):+ raise SystemExit("ce_emu: no .8xp to run")+ lib = None if opts["libs"] == "none" else opts["libs"] or libs()+ rep = run(files, keys=opts["keys"], shots=opts["shots"], ms=int(opts["ms"]), out=opts["out"], ram=opts["ram"],+ lib=lib, frame=opts["frame"], rev=opts["rev"], trace=flags["trace"], vars_out=opts["vars-out"],+ profile=int(opts["profile"]))+ if rep["stderr"]:+ sys.stderr.write(rep["stderr"])+ print(json.dumps({k: v for k, v in rep.items() if k != "stderr"}, indent=1) if flags["json"] else summary(rep))+ return 0 if rep["status"] in ("ok", "exited") else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/ce_emu/Makefile b/tools/ce_emu/Makefilenew file mode 100644index 00000000..ae96af3b--- /dev/null+++ b/tools/ce_emu/Makefile@@ -0,0 +1,55 @@+# ce_emu: TI-84 Plus CE programs run on CEmu's core (github.com/CE-Programming/CEmu, GPL-3.0) with a small OS of+# its own instead of TI's ROM. `make` fetches CEmu at the commit below into CEMU_SRC (outside the repo), builds its+# core with debug support, the flash image (rom.S, with CEDEV's binutils and runtime) and build/ce_emu.+CEMU_URL = https://github.com/CE-Programming/CEmu.git+CEMU_COMMIT = d7679d04c44741359b1f3a0444ff4eea99c34369+CEMU_SRC ?= $(HOME)/Documents/Assets/toolchains/ce-src/cemu+CEDEV ?= $(HOME)/Documents/Assets/toolchains/CEdev+BINUTILS = $(CEDEV)/binutils/bin+OUT = build+CC ?= cc+CFLAGS ?= -O2+CORE_FLAGS = -std=gnu11 -DDEBUG_SUPPORT -w $(CFLAGS)++CORE_SRC = $(filter-out $(CEMU_SRC)/core/os/os-emscripten.c $(CEMU_SRC)/core/os/os-win32.c, \+ $(wildcard $(CEMU_SRC)/core/*.c $(CEMU_SRC)/core/debug/*.c $(CEMU_SRC)/core/os/*.c $(CEMU_SRC)/core/usb/*.c))+CORE_OBJ = $(patsubst $(CEMU_SRC)/core/%.c,$(OUT)/core/%.o,$(CORE_SRC))++all: $(OUT)/ce_emu $(OUT)/rom.bin $(OUT)/ti84pceg.inc++$(CEMU_SRC)/.ce_emu_$(CEMU_COMMIT):+ @if [ ! -d $(CEMU_SRC)/.git ]; then git clone -q $(CEMU_URL) $(CEMU_SRC); fi+ @git -C $(CEMU_SRC) cat-file -e $(CEMU_COMMIT) 2>/dev/null || git -C $(CEMU_SRC) fetch -q origin+ @git -C $(CEMU_SRC) -c advice.detachedHead=false checkout -q $(CEMU_COMMIT)+ @touch $@++$(OUT)/core/%.o: $(CEMU_SRC)/core/%.c $(CEMU_SRC)/.ce_emu_$(CEMU_COMMIT)+ @mkdir -p $(@D)+ $(CC) $(CORE_FLAGS) -c $< -o $@++$(OUT)/libcemucore.a: $(CORE_OBJ)+ rm -f $@+ ar rcs $@ $(CORE_OBJ)++# the home screen's text is drawn with NumPlay's font+FONT = ../../launcher/src/font_data.c+$(OUT)/ce_emu: ce_emu.c os.c ce_emu.h $(FONT) $(OUT)/libcemucore.a+ $(CC) -std=gnu11 -Wall -Wno-unused-function -DDEBUG_SUPPORT $(CFLAGS) -I$(CEMU_SRC)/core ce_emu.c os.c $(FONT) \+ $(OUT)/libcemucore.a -lz -lm -o $@++# the OS routines' names, for messages (the toolchain's equates)+$(OUT)/ti84pceg.inc:+ @mkdir -p $(OUT)+ curl -fsSL -o $@ https://raw.githubusercontent.com/CE-Programming/toolchain/v15.0/src/include/ti84pceg.inc++$(OUT)/rom.bin: rom.S rom.ld+ @mkdir -p $(OUT)+ $(BINUTILS)/z80-none-elf-as -march=ez80+full rom.S -o $(OUT)/rom.o+ $(BINUTILS)/z80-none-elf-ld -T rom.ld --gc-sections -e 0 -Map $(OUT)/rom.map $(OUT)/rom.o \+ $(CEDEV)/lib/crt/libcrt.a $(CEDEV)/lib/libc/libc.a -o $(OUT)/rom.elf+ $(BINUTILS)/z80-none-elf-objcopy -O binary $(OUT)/rom.elf $@++clean:+ rm -rf $(OUT)++.PHONY: all cleandiff --git a/tools/ce_emu/ce_emu.c b/tools/ce_emu/ce_emu.cnew file mode 100644index 00000000..76e9c960--- /dev/null+++ b/tools/ce_emu/ce_emu.c@@ -0,0 +1,543 @@+/* ce_emu: a TI-84 Plus CE program run headless on CEmu's core (eZ80, LCD controller and panel, keypad, timers,+ * flash, memory protection), with os.c in place of TI-OS. Python's tools/ce_emu.py is the usual way in.+ *+ * ce_emu [options] PROGRAM.8xp [VARS.8xv|GROUP.8xg ...]+ *+ * --rom FILE the flash image (build/rom.bin)+ * --ms N how long to run, in the calculator's milliseconds (5000)+ * --keys SPEC keys held: "1500-1600:2nd,3000:clear" (CE names, or ok exe back home for the NumWorks's)+ * --shots SPEC "1000,2500" or "1000:title.png,..." (PNG, 320 x 240, into --out)+ * --out DIR where pictures go (.)+ * --ram NAME,... these variables in RAM; the others where their file puts them (the archive, mostly)+ * --frame ADDR a frame each time the CPU reaches ADDR (eadk_display_wait_for_vblank's, say)+ * --vars-out DIR the programs and appvars at the end, as files+ * --report FILE a JSON report (else a summary on stdout)+ * --rev pre-a|i|m the ASIC revision (m: every CE since 2019, the Python ones)+ * --names INC ti84pceg.inc, for the routines' names+ * --trace every OS call on stderr+ *+ * It stops at a crash (a protection fault: a write to flash, to the stack limit, out in unprivileged code; the+ * reset vector reached: an invalid instruction or a jump to 0; a write to unmapped memory), a hang (halt with+ * interrupts off, or the CPU stuck in a few bytes with no frames, screen changes, key reads or OS calls for+ * 3 seconds), an OS error with no handler, an OS routine os.c doesn't have, or the program's end. */+#include "ce_emu.h"+#include "asic.h"+#include "bus.h"+#include "control.h"+#include "cpu.h"+#include "debug/debug.h"+#include "emu.h"+#include "interrupt.h"+#include "keypad.h"+#include "lcd.h"+#include "mem.h"+#include "panel.h"+#include "schedule.h"+#include <stdarg.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <time.h>+#include <zlib.h>++#define CPU_HZ 48000000.0++static const struct {+ const char *name;+ int group, bit;+} KEYS[] = {+ {"graph", 1, 0}, {"trace", 1, 1}, {"zoom", 1, 2}, {"window", 1, 3}, {"yequ", 1, 4}, {"2nd", 1, 5}, {"mode", 1, 6},+ {"del", 1, 7}, {"sto", 2, 1}, {"ln", 2, 2}, {"log", 2, 3}, {"square", 2, 4}, {"recip", 2, 5}, {"math", 2, 6},+ {"alpha", 2, 7}, {"0", 3, 0}, {"1", 3, 1}, {"4", 3, 2}, {"7", 3, 3}, {"comma", 3, 4}, {"sin", 3, 5}, {"apps", 3, 6},+ {"xton", 3, 7}, {"dot", 4, 0}, {"2", 4, 1}, {"5", 4, 2}, {"8", 4, 3}, {"lparen", 4, 4}, {"cos", 4, 5},+ {"prgm", 4, 6}, {"stat", 4, 7}, {"chs", 5, 0}, {"3", 5, 1}, {"6", 5, 2}, {"9", 5, 3}, {"rparen", 5, 4},+ {"tan", 5, 5}, {"vars", 5, 6}, {"enter", 6, 0}, {"add", 6, 1}, {"sub", 6, 2}, {"mul", 6, 3}, {"div", 6, 4},+ {"power", 6, 5}, {"clear", 6, 6}, {"down", 7, 0}, {"left", 7, 1}, {"right", 7, 2}, {"up", 7, 3}, {"on", 2, 0},+ /* the NumWorks's names, on NumPlay's layout (platform/ti84ce/README.md) */+ {"ok", 1, 5}, {"exe", 6, 0}, {"back", 6, 6}, {"home", 1, 6}, {"backspace", 1, 7}, {"shift", 1, 4},+ {"toolbox", 2, 6}, {"var", 5, 6}, {"xnt", 3, 7}, {"plus", 6, 1}, {"minus", 6, 2}, {"ans", 5, 0},+};++typedef struct {+ uint64_t from, to;+ int group, bit;+} key_t_;++static struct {+ const char *rom, *out, *vars_out, *report, *names, *rev, *profile;+ uint64_t ms;+ key_t_ keys[256];+ int nkeys;+ struct {+ uint64_t at;+ char path[512];+ } shots[256];+ int nshots;+ char ram[64][9];+ int nram;+ uint32_t frame_addr;+} opt = {.ms = 5000, .out = ".", .rev = "m"};++/* ---- the run's state ---- */+static uint64_t now_ms, started_cycles, start_ms;+static bool stopping, started, exited;+static char status[32] = "ok", detail[1024];+static uint32_t exit_code;+static char warnings[8192];+static size_t warn_len;+static int nwarn;+static char console_err[512];+static char text_log[8192];+static size_t text_len;+static bool held[8][8], on_held;+static uint64_t key_reads, os_calls, frames, screen_changes, upbase_writes;+static uint64_t frame_cycles[100000];+static uint64_t last_frame_cycle;+static uint32_t last_hash;+static uint32_t *samples;++static uint64_t cycles_now(void) { return sched_total_cycles(); }+uint64_t emu_ms(void) { return now_ms; }+bool emu_key_held(int group, int bit) { return group >= 0 && group < 8 && bit >= 0 && bit < 8 && held[group][bit]; }+void emu_charge(uint32_t cycles) { debug.cpuCycles += cycles; }+void emu_jump(uint32_t pc) { debug_set_pc(pc); }++void emu_stop(const char *st, const char *fmt, ...) {+ if (stopping) return;+ va_list ap;+ va_start(ap, fmt);+ vsnprintf(detail, sizeof detail, fmt, ap);+ va_end(ap);+ snprintf(status, sizeof status, "%s", st);+ stopping = true;+ cpu_set_signal(CPU_SIGNAL_EXIT);+}+void emu_warn(const char *fmt, ...) {+ char buf[512];+ va_list ap;+ va_start(ap, fmt);+ vsnprintf(buf, sizeof buf, fmt, ap);+ va_end(ap);+ if (++nwarn > 40) return;+ warn_len += snprintf(warnings + warn_len, sizeof warnings - warn_len, "%s%s", warn_len ? "\n" : "", buf);+ if (warn_len >= sizeof warnings) warn_len = sizeof warnings - 1;+}+void emu_text(const char *s) {+ text_len += snprintf(text_log + text_len, sizeof text_log - text_len, "%s%s", text_len ? "\n" : "", s);+ if (text_len >= sizeof text_log) text_len = sizeof text_log - 1;+}+void emu_program_started(void) {+ started = true;+ started_cycles = cycles_now();+ start_ms = now_ms;+ last_frame_cycle = 0;+ debug_watch(0x000000, DBG_MASK_EXEC, true);+}+void emu_program_exited(uint32_t code) {+ exited = true;+ exit_code = code;+ emu_stop("exited", "the program returned %d at %llu ms", (int)(code & 0x800000 ? code - 0x1000000 : code),+ (unsigned long long)now_ms);+}++/* ---- CEmu's callbacks ---- */+void gui_console_clear(void) {}+void gui_console_printf(const char *fmt, ...) {+ if (strncmp(fmt, "[CEmu]", 6) == 0) return;+ va_list ap;+ va_start(ap, fmt);+ vfprintf(stderr, fmt, ap); /* (a program's dbg_printf) */+ va_end(ap);+}+void gui_console_err_printf(const char *fmt, ...) {+ va_list ap;+ va_start(ap, fmt);+ vsnprintf(console_err, sizeof console_err, fmt, ap);+ va_end(ap);+ if (!strncmp(console_err, "[CEmu] ", 7)) memmove(console_err, console_err + 7, strlen(console_err + 7) + 1);+ size_t n = strlen(console_err);+ while (n && console_err[n - 1] == '\n') console_err[--n] = 0;+}+asic_rev_t gui_handle_reset(const boot_ver_t *boot_ver, asic_rev_t loaded_rev, asic_rev_t default_rev,+ emu_device_t device, bool *python) {+ (void)boot_ver, (void)loaded_rev, (void)default_rev, (void)device;+ *python = false;+ return !strcmp(opt.rev, "pre-a") ? ASIC_REV_PRE_A : !strcmp(opt.rev, "i") ? ASIC_REV_I : ASIC_REV_M;+}+void gui_debug_close(void) {}+void gui_debug_open(int reason, uint32_t data) {+ uint32_t pc = cpu.registers.PC, sp = cpu.registers.SPL;+ switch (reason) {+ case DBG_BREAKPOINT:+ if (data == opt.frame_addr && opt.frame_addr) {+ uint64_t c = cycles_now();+ if (frames < sizeof frame_cycles / sizeof frame_cycles[0]) frame_cycles[frames] = c;+ frames++;+ last_frame_cycle = c;+ return;+ }+ if (data == 0x000000) {+ emu_stop("crash", "the reset vector: an invalid instruction or a jump to 0, returning to %06X",+ rd24(sp));+ return;+ }+ if (data == 0x000066) {+ emu_stop("crash", "NMI from the memory protection (status %d): %s", control.protectionStatus,+ console_err[0] ? console_err : "?");+ return;+ }+ os_calls++;+ if (!os_trap(data)) emu_stop("crash", "a breakpoint at %06X ce_emu doesn't know", data);+ return;+ case DBG_WATCHPOINT_READ:+ if (data >= 0xF50010 && data < 0xF50020) key_reads++;+ return;+ case DBG_WATCHPOINT_WRITE:+ if (data >= 0xE30010 && data < 0xE30013) {+ upbase_writes++;+ return;+ }+ if (started) emu_stop("crash", "a write to unmapped memory at %06X (pc %06X)", data, pc);+ return;+ case DBG_NMI_TRIGGERED:+ return; /* (the NMI handler's breakpoint tells) */+ case DBG_WATCHDOG_TIMEOUT: emu_stop("crash", "the watchdog timer ran out"); return;+ case DBG_MISC_RESET: emu_stop("crash", "the calculator reset: %s", console_err); return;+ case DBG_READY: emu_stop("crash", "the calculator reset: %s", console_err[0] ? console_err : "?"); return;+ case DBG_FROZEN: emu_stop("hang", "halt with interrupts off at %06X", pc); return;+ default:+ if (reason >= DBG_PORT_RANGE) { /* the toolchain's debug.h: a command written to 0xFFFFFF */+ if (data == CMD_ABORT) emu_stop("crash", "the program aborted (debug command), returning to %06X", rd24(sp));+ else if (data == CMD_DEBUG) emu_warn("dbg_Debugger() at %06X", rd24(sp));+ return;+ }+ return;+ }+}++/* ---- pictures ---- */+static uint32_t frame_px[LCD_WIDTH * LCD_HEIGHT];+static bool from_memory;+static void grab(void) {+ if (!from_memory) {+ emu_lcd_drawframe(frame_px);+ return;+ }+ uint32_t *dat, *end;+ emu_set_lcd_ptrs(&dat, &end, LCD_WIDTH, LCD_HEIGHT, lcd.upbase, lcd.control, false);+ emu_lcd_drawmem(frame_px, dat, end, lcd.control, LCD_SIZE);+}+static void png_chunk(FILE *f, const char *type, const uint8_t *d, uint32_t n) {+ uint8_t b[4] = {n >> 24, n >> 16, n >> 8, n};+ fwrite(b, 1, 4, f);+ fwrite(type, 1, 4, f);+ if (n) fwrite(d, 1, n, f);+ uint32_t c = crc32(crc32(0, (const uint8_t *)type, 4), d, n);+ uint8_t cb[4] = {c >> 24, c >> 16, c >> 8, c};+ fwrite(cb, 1, 4, f);+}+static bool save_png(const char *path) {+ static uint8_t raw[LCD_HEIGHT * (1 + LCD_WIDTH * 3)];+ grab();+ for (int y = 0; y < LCD_HEIGHT; y++) {+ uint8_t *r = raw + y * (1 + LCD_WIDTH * 3);+ r[0] = 0;+ for (int x = 0; x < LCD_WIDTH; x++) {+ uint32_t p = frame_px[y * LCD_WIDTH + x];+ r[1 + x * 3] = p >> 16, r[2 + x * 3] = p >> 8, r[3 + x * 3] = p;+ }+ }+ uLongf zn = compressBound(sizeof raw);+ uint8_t *z = malloc(zn);+ compress2(z, &zn, raw, sizeof raw, 6);+ FILE *f = fopen(path, "wb");+ if (!f) {+ free(z);+ return false;+ }+ fwrite("\x89PNG\r\n\x1a\n", 1, 8, f);+ uint8_t ihdr[13] = {0, 0, LCD_WIDTH >> 8, LCD_WIDTH & 0xFF, 0, 0, 0, LCD_HEIGHT, 8, 2, 0, 0, 0};+ png_chunk(f, "IHDR", ihdr, 13);+ png_chunk(f, "IDAT", z, (uint32_t)zn);+ png_chunk(f, "IEND", NULL, 0);+ fclose(f);+ free(z);+ return true;+}+static uint32_t screen_hash(void) {+ grab();+ return crc32(0, (const uint8_t *)frame_px, sizeof frame_px);+}++/* ---- options ---- */+static int key_index(const char *name, size_t n) {+ for (size_t i = 0; i < sizeof KEYS / sizeof KEYS[0]; i++)+ if (strlen(KEYS[i].name) == n && !strncmp(KEYS[i].name, name, n)) return (int)i;+ return -1;+}+static void parse_keys(const char *s) {+ while (s && *s && opt.nkeys < (int)(sizeof opt.keys / sizeof opt.keys[0])) {+ char *e;+ unsigned long long a = strtoull(s, &e, 10), b = a + 100;+ s = e;+ if (*s == '-') b = strtoull(s + 1, &e, 10), s = e;+ if (*s++ != ':') break;+ size_t n = strcspn(s, ",");+ int k = key_index(s, n);+ if (k < 0) {+ fprintf(stderr, "ce_emu: no key %.*s\n", (int)n, s);+ exit(2);+ }+ opt.keys[opt.nkeys++] = (key_t_){a, b, KEYS[k].group, KEYS[k].bit};+ s += n;+ if (*s == ',') s++;+ }+}+static void parse_shots(const char *s) {+ while (s && *s && opt.nshots < (int)(sizeof opt.shots / sizeof opt.shots[0])) {+ char *e;+ unsigned long long t = strtoull(s, &e, 10);+ s = e;+ size_t n = 0;+ if (*s == ':') n = strcspn(++s, ",");+ if (n) snprintf(opt.shots[opt.nshots].path, sizeof opt.shots[0].path, "%s/%.*s", opt.out, (int)n, s);+ else snprintf(opt.shots[opt.nshots].path, sizeof opt.shots[0].path, "%s/shot_%06llu.png", opt.out, t);+ opt.shots[opt.nshots++].at = t;+ s += n;+ if (*s == ',') s++;+ }+}++/* the keys held this millisecond, into CEmu's keypad */+static void apply_keys(void) {+ bool want[8][8] = {{0}}, want_on = false;+ for (int i = 0; i < opt.nkeys; i++)+ if (now_ms >= opt.keys[i].from && now_ms <= opt.keys[i].to) {+ if (opt.keys[i].group == 2 && opt.keys[i].bit == 0) want_on = true;+ else want[opt.keys[i].group][opt.keys[i].bit] = true;+ }+ for (int g = 1; g < 8; g++)+ for (int b = 0; b < 8; b++)+ if (want[g][b] != held[g][b]) held[g][b] = want[g][b], emu_keypad_event(g, b, want[g][b]);+ if (want_on != on_held) on_held = want_on, emu_keypad_event(2, 0, want_on);+}++static void json_str(FILE *f, const char *s) {+ fputc('"', f);+ for (; *s; s++) {+ if (*s == '"' || *s == '\\') fprintf(f, "\\%c", *s);+ else if (*s == '\n') fputs("\\n", f);+ else if ((unsigned char)*s < 32) fprintf(f, "\\u%04x", *s);+ else fputc(*s, f);+ }+ fputc('"', f);+}++int main(int argc, char **argv) {+ const char *files[64], *keys = NULL, *shots = NULL;+ int nfiles = 0;+ for (int i = 1; i < argc; i++) {+ const char *a = argv[i], *v = i + 1 < argc ? argv[i + 1] : NULL;+ if (!strcmp(a, "--rom") && v) opt.rom = v, i++;+ else if (!strcmp(a, "--ms") && v) opt.ms = strtoull(v, NULL, 10), i++;+ else if (!strcmp(a, "--keys") && v) keys = v, i++;+ else if (!strcmp(a, "--shots") && v) shots = v, i++;+ else if (!strcmp(a, "--out") && v) opt.out = v, i++;+ else if (!strcmp(a, "--vars-out") && v) opt.vars_out = v, i++;+ else if (!strcmp(a, "--report") && v) opt.report = v, i++;+ else if (!strcmp(a, "--names") && v) opt.names = v, i++;+ else if (!strcmp(a, "--rev") && v) opt.rev = v, i++;+ else if (!strcmp(a, "--frame") && v) opt.frame_addr = (uint32_t)strtoul(v, NULL, 0), i++;+ else if (!strcmp(a, "--trace")) os_trace = true;+ else if (!strcmp(a, "--screen-memory")) from_memory = true;+ else if (!strcmp(a, "--profile") && v) opt.profile = v, i++;+ else if (!strcmp(a, "--ram") && v) {+ for (const char *s = v; *s && opt.nram < 64;) {+ size_t n = strcspn(s, ",");+ snprintf(opt.ram[opt.nram++], 9, "%.*s", (int)(n > 8 ? 8 : n), s);+ s += n + (s[n] == ',');+ }+ i++;+ } else if (a[0] == '-') {+ fprintf(stderr, "ce_emu: unknown option %s (see the top of ce_emu.c)\n", a);+ return 2;+ } else if (nfiles < 64) {+ files[nfiles++] = a;+ }+ }+ if (!nfiles || !opt.rom) {+ fprintf(stderr, "usage: ce_emu --rom rom.bin [options] PROGRAM.8xp [VARS.8xv ...]\n");+ return 2;+ }+ mkdir(opt.out, 0755);+ parse_keys(keys);+ parse_shots(shots);+ if (opt.names) os_names_load(opt.names);++ debug_init();+ emu_state_t st = emu_load(EMU_DATA_ROM, opt.rom);+ if (st == EMU_STATE_INVALID) {+ fprintf(stderr, "ce_emu: can't load %s\n", opt.rom);+ return 2;+ }+ bus_init_rand(1, 2, 3); /* (the same unmapped reads every run) */+ emu_set_lcd_dma(1);+ emu_set_run_rate(1000);+ os_setup();++ /* the variables: the program first, in the archive unless --ram names it */+ char prog[9] = {0};+ static tivar_t vars[64];+ for (int i = 0; i < nfiles; i++) {+ int n = ti_read_file(files[i], vars, 64);+ if (n <= 0) {+ fprintf(stderr, "ce_emu: %s isn't a TI file\n", files[i]);+ return 2;+ }+ for (int k = 0; k < n; k++) {+ char nm[9] = {0};+ memcpy(nm, vars[k].name, vars[k].namelen);+ bool ram = !(vars[k].flag & 0x80);+ for (int r = 0; r < opt.nram; r++)+ if (!strcmp(opt.ram[r], nm)) ram = true;+ if (!prog[0] && ((vars[k].type & 0x3F) == 5 || (vars[k].type & 0x3F) == 6)) strcpy(prog, nm);+ if (!os_add_var(&vars[k], !ram)) fprintf(stderr, "ce_emu: %s twice, or no room for it\n", nm);+ }+ }+ if (!prog[0] || !os_set_program(prog)) {+ fprintf(stderr, "ce_emu: no program among the files\n");+ return 2;+ }++ /* the host's routines: every slot of the jump tables still holding a ret */+ for (uint32_t a = 0x80; a < 0x800; a += 4)+ if (rd8(a) == 0xC9) debug_watch(a, DBG_MASK_EXEC, true);+ for (uint32_t a = 0x20100; a < HLE_BASE + 4 * HLE_SLOTS; a += 4)+ if (rd8(a) == 0xC9) debug_watch(a, DBG_MASK_EXEC, true);+ debug_watch(0x66, DBG_MASK_EXEC, true);+ if (opt.frame_addr) debug_watch(opt.frame_addr, DBG_MASK_EXEC, true);+ for (uint32_t a = 0xF50010; a < 0xF50020; a++) debug_watch(a, DBG_MASK_READ, true);+ for (uint32_t a = 0xE30010; a < 0xE30013; a++) debug_watch(a, DBG_MASK_WRITE, true);+ for (uint32_t a = 0xD00000; a < 0xE00000; a++)+ if ((a & 0x7FFFF) >= SIZE_RAM) debug_watch(a, DBG_MASK_WRITE, true);+ for (uint32_t a = 0xC00000; a < 0xD00000; a++) debug_watch(a, DBG_MASK_WRITE, true);+ debug_flag(DBG_SOFT_COMMANDS | DBG_OPEN_ON_RESET, true);++ if (opt.profile) emu_set_run_rate(10000), samples = calloc(1 << 24, sizeof *samples);+ clock_t wall0 = clock();+ int shot = 0;+ uint32_t stuck_pc = 0;+ uint64_t stuck_since = 0, activity = 0, last_activity = 0;+ while (opt.nshots > 1) { /* (in time order) */+ bool sorted = true;+ for (int i = 1; i < opt.nshots; i++)+ if (opt.shots[i].at < opt.shots[i - 1].at) {+ __typeof__(opt.shots[0]) t = opt.shots[i];+ opt.shots[i] = opt.shots[i - 1], opt.shots[i - 1] = t, sorted = false;+ }+ if (sorted) break;+ }+ for (now_ms = 0; now_ms < opt.ms && !stopping; now_ms++) {+ apply_keys();+ if (opt.profile) { /* the PC every 0.1 ms */+ for (int k = 0; k < 10 && !stopping; k++) {+ emu_run(1);+ if (started) samples[cpu.registers.PC & 0xFFFFFF]++;+ }+ } else {+ emu_run(1);+ }+ while (shot < opt.nshots && opt.shots[shot].at <= now_ms) save_png(opt.shots[shot++].path);+ if (!started || stopping) continue;+ if (now_ms % 16 == 0) {+ uint32_t h = screen_hash();+ if (h != last_hash) screen_changes++, last_hash = h;+ }+ /* hangs */+ if (cpu.halted && !cpu.IEF1) emu_stop("hang", "halt with interrupts off at %06X", cpu.registers.PC);+ uint32_t pc = cpu.registers.PC;+ uint64_t act = frames + screen_changes + key_reads + os_calls + upbase_writes;+ if (act != activity) activity = act, last_activity = now_ms;+ if (pc - stuck_pc > 64 && stuck_pc - pc > 64) stuck_pc = pc, stuck_since = now_ms;+ uint64_t quiet = now_ms - (stuck_since > last_activity ? stuck_since : last_activity);+ if (quiet >= 3000)+ emu_stop("hang", "the CPU stayed around %06X for %llu ms: no frame, screen change, key read or OS call", pc,+ (unsigned long long)quiet);+ uint32_t sp = cpu.registers.SPL;+ if (cpu.ADL && (sp < STACK_BOT - 0x100 || sp > STACK_TOP)) {+ static bool told;+ if (!told) emu_warn("the stack pointer left the stack: %06X at %llu ms", sp, (unsigned long long)now_ms);+ told = true;+ }+ }+ double wall = (double)(clock() - wall0) / CLOCKS_PER_SEC;+ for (; shot < opt.nshots; shot++) save_png(opt.shots[shot].path);+ char last[600];+ snprintf(last, sizeof last, "%s/last.png", opt.out);+ save_png(last);+ int saved = opt.vars_out ? (mkdir(opt.vars_out, 0755), os_save_vars(opt.vars_out)) : 0;+ if (opt.profile) {+ FILE *pf = fopen(opt.profile, "w");+ for (uint32_t a = 0; pf && a < 1 << 24; a++)+ if (samples[a]) fprintf(pf, "%06X %u\n", a, samples[a]);+ if (pf) fclose(pf);+ }++ /* frames: the time from each to the next, past the first */+ uint64_t nf = frames < sizeof frame_cycles / sizeof frame_cycles[0] ? frames : sizeof frame_cycles / sizeof frame_cycles[0];+ double fps = 0, mean_ms = 0, max_ms = 0, p95 = 0;+ uint64_t over33 = 0;+ if (nf >= 2) {+ double *d = malloc((nf - 1) * sizeof *d);+ for (uint64_t i = 1; i < nf; i++) {+ d[i - 1] = (frame_cycles[i] - frame_cycles[i - 1]) / CPU_HZ * 1000;+ mean_ms += d[i - 1];+ if (d[i - 1] > max_ms) max_ms = d[i - 1];+ if (d[i - 1] > 33.4) over33++;+ }+ mean_ms /= nf - 1;+ fps = 1000 / mean_ms;+ for (uint64_t i = 1; i < nf - 1; i++) /* (insertion sort: a few thousand at most) */+ for (uint64_t j = i; j > 0 && d[j] < d[j - 1]; j--) {+ double t = d[j];+ d[j] = d[j - 1], d[j - 1] = t;+ }+ p95 = d[(uint64_t)((nf - 2) * 0.95)];+ free(d);+ }+ double emu_s = (double)now_ms / 1000;+ FILE *f = opt.report ? fopen(opt.report, "w") : NULL;+ if (f) {+ fprintf(f, "{\n \"program\": ");+ json_str(f, prog);+ fprintf(f, ",\n \"status\": ");+ json_str(f, status);+ fprintf(f, ",\n \"detail\": ");+ json_str(f, stopping ? detail : "");+ fprintf(f, ",\n \"ms\": %llu,\n \"exit_code\": %d,\n \"wall_s\": %.3f,\n \"speed\": %.2f,\n",+ (unsigned long long)now_ms, exited ? (int)exit_code : -1, wall, wall > 0 ? emu_s / wall : 0);+ fprintf(f, " \"cycles\": %llu,\n \"frames\": %llu,\n \"fps\": %.2f,\n \"frame_ms\": %.2f,\n \"frame_ms_p95\": %.2f,\n"+ " \"frame_ms_max\": %.2f,\n \"frames_over_33ms\": %llu,\n \"cycles_per_frame\": %.0f,\n",+ (unsigned long long)cycles_now(), (unsigned long long)frames, fps, mean_ms, p95, max_ms,+ (unsigned long long)over33, mean_ms * CPU_HZ / 1000);+ fprintf(f, " \"lcd_base_writes\": %llu,\n \"screen_changes\": %llu,\n \"key_reads\": %llu,\n",+ (unsigned long long)upbase_writes, (unsigned long long)screen_changes, (unsigned long long)key_reads);+ os_report(f);+ fprintf(f, " \"vars_saved\": %d,\n \"text\": ", saved);+ json_str(f, text_log);+ fprintf(f, ",\n \"warnings\": ");+ json_str(f, warnings);+ fprintf(f, "\n}\n");+ fclose(f);+ } else {+ printf("ce_emu: %s %s%s%s\n", prog, status, stopping ? ": " : "", stopping ? detail : "");+ printf("ce_emu: %.2f s emulated in %.2f s (%.1fx) at %.0f MHz", emu_s, wall, wall > 0 ? emu_s / wall : 0,+ sched_get_clock_rate(CLOCK_CPU) / 1e6);+ if (frames) printf(", %llu frames, %.1f fps, %.1f ms a frame (95%%: %.1f, slowest %.1f)", (unsigned long long)frames, fps,+ mean_ms, p95, max_ms);+ printf("\n");+ if (text_len) printf("ce_emu: home screen: %s\n", text_log);+ if (warn_len) printf("ce_emu: warnings: %s\n", warnings);+ }+ return !strcmp(status, "ok") || !strcmp(status, "exited") ? 0 : 1;+}diff --git a/tools/ce_emu/ce_emu.h b/tools/ce_emu/ce_emu.hnew file mode 100644index 00000000..085f2bab--- /dev/null+++ b/tools/ce_emu/ce_emu.h@@ -0,0 +1,81 @@+/* ce_emu: what the harness (ce_emu.c) and its OS (os.c) share. */+#ifndef CE_EMU_H+#define CE_EMU_H+#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>+#include <stdio.h>++/* TI-OS's RAM, as the CE toolchain's ti84pceg.inc names it */+#define FLAGS 0xD00080+#define KBD_SCAN_CODE 0xD00587+#define CUR_ROW 0xD00595+#define CUR_COL 0xD00596+#define OP1 0xD005F8+#define OP4 0xD00619+#define TEXT_SHADOW 0xD006C0+#define ERR_NO 0xD008DF+#define ERR_SP 0xD008E0+#define ASM_PRGM_SIZE 0xD0118C+#define TEMP_MEM 0xD02587+#define FPS_BASE 0xD0258A+#define FPS 0xD0258D+#define OP_BASE 0xD02590+#define OPS 0xD02593+#define P_TEMP_CNT 0xD02596+#define P_TEMP 0xD0259A+#define PROG_PTR 0xD0259D+#define NEW_DATA_PTR 0xD025A0+#define STACK_BOT 0xD1987E+#define STACK_TOP 0xD1A87E+#define USER_MEM 0xD1A881+#define SYM_TABLE 0xD3FFFF+#define VRAM 0xD40000+#define ARC_START 0x0C0000+#define ARC_END 0x3B0000++/* the flash image's own entry points (rom.S) */+#define HLE_BASE 0x023000+#define HLE_SLOTS 64+enum { HLE_START, HLE_EXIT, HLE_GETKEY_CODE };++/* a variable of a .8xp/.8xv/.8xg file */+typedef struct {+ uint8_t type, version, flag; /* flag 0x80: archived */+ uint8_t name[8], namelen;+ uint8_t *data; /* with its 2-byte size first, as in memory */+ uint32_t size;+} tivar_t;++/* memory */+uint8_t *mem_at(uint32_t addr, uint32_t len);+uint8_t rd8(uint32_t a);+uint32_t rd16(uint32_t a);+uint32_t rd24(uint32_t a);+void wr8(uint32_t a, uint8_t v);+void wr16(uint32_t a, uint32_t v);+void wr24(uint32_t a, uint32_t v);++/* os.c */+int ti_read_file(const char *path, tivar_t *out, int max);+void os_setup(void);+bool os_add_var(const tivar_t *v, bool archived);+bool os_set_program(const char *name);+bool os_trap(uint32_t pc);+void os_names_load(const char *inc_path);+const char *os_name(uint32_t addr);+void os_report(FILE *f);+int os_save_vars(const char *dir);+extern bool os_trace;++/* ce_emu.c, for os.c */+void emu_stop(const char *status, const char *fmt, ...);+void emu_warn(const char *fmt, ...);+void emu_text(const char *s);+bool emu_key_held(int group, int bit);+uint64_t emu_ms(void);+void emu_charge(uint32_t cycles);+void emu_jump(uint32_t pc);+void emu_program_started(void);+void emu_program_exited(uint32_t code);+#endifdiff --git a/tools/ce_emu/os.c b/tools/ce_emu/os.cnew file mode 100644index 00000000..b4e8fde3--- /dev/null+++ b/tools/ce_emu/os.c@@ -0,0 +1,950 @@+/* ce_emu's TI-OS: the routines of TI's boot code and OS that rom.S leaves to the host, done on CEmu's state.+ *+ * Variables are kept as TI-OS keeps them, so programs and the CE libraries that read memory directly see the+ * real layout: the VAT grows down from symTable (named variables, then programs and appvars from progPtr to+ * pTemp), RAM data lives from userMem up to the FP stack, and archived variables sit in flash from 0x0C0000+ * in TI's format (0xFC, size, type, version, address, name, data), their VAT pointer at the 0xFC. A running+ * program is a copy at userMem, asm_prgm_size long, outside the VAT.+ *+ * Each routine charges the cycles a real one would take, roughly: the float ones from the toolchain's notes+ * and the eZ80's speed (TI's boot code isn't public), the memory ones by the bytes they move. */+#include "ce_emu.h"+#include "cpu.h"+#include "debug/debug.h"+#include "mem.h"+#include <ctype.h>+#include <math.h>+#include <stdarg.h>+#include <stdlib.h>+#include <string.h>++#define R (cpu.registers)+#define F_C 0x01+#define F_N 0x02+#define F_PV 0x04+#define F_H 0x10+#define F_Z 0x40+#define F_S 0x80++#define E_UNDEFINED 141+#define E_MEMORY 142+#define E_ARCHIVED 175+#define E_ARCH_FULL 49++bool os_trace;++/* ---- memory ---- */+uint8_t *mem_at(uint32_t a, uint32_t n) {+ a &= 0xFFFFFF;+ if (a < mem.flash.size && a + n <= mem.flash.size) return mem.flash.block + a;+ if (a >= 0xD00000 && a + n <= 0xD00000 + SIZE_RAM) return mem.ram.block + (a - 0xD00000);+ return NULL;+}+uint8_t rd8(uint32_t a) {+ uint8_t *p = mem_at(a, 1);+ return p ? *p : 0;+}+uint32_t rd16(uint32_t a) { return rd8(a) | rd8(a + 1) << 8; }+uint32_t rd24(uint32_t a) { return rd8(a) | rd8(a + 1) << 8 | (uint32_t)rd8(a + 2) << 16; }+void wr8(uint32_t a, uint8_t v) {+ uint8_t *p = mem_at(a, 1);+ if (p) *p = v;+}+void wr16(uint32_t a, uint32_t v) { wr8(a, v), wr8(a + 1, v >> 8); }+void wr24(uint32_t a, uint32_t v) { wr8(a, v), wr8(a + 1, v >> 8), wr8(a + 2, v >> 16); }+static bool in_ram(uint32_t a) { return a >= 0xD00000 && a < 0xD40000; }+static void flag(uint8_t m, bool on) { R.F = on ? R.F | m : R.F & ~m; }+static uint32_t arg(int i) { return rd24(R.SPL + 3 + 3 * i); }+static uint32_t arg32(int i) { return arg(i) | (uint32_t)(arg(i + 1) & 0xFF) << 24; }++/* ---- names of the routines (ti84pceg.inc, when there is one) ---- */+static struct name { uint32_t addr; char *name; } *names;+static int nnames;+void os_names_load(const char *path) {+ FILE *f = fopen(path, "r");+ if (!f) return;+ char line[256];+ while (fgets(line, sizeof line, f)) {+ char n[128];+ unsigned a;+ if (line[0] != '?' || sscanf(line + 1, "%127s := %xh", n, &a) != 2) continue;+ if (a < 0x80 || (a >= 0x800 && a < 0x20100) || a >= 0x30000) continue;+ if (!(isupper((unsigned char)n[0]) || n[0] == '_' || !strncmp(n, "boot.", 5) || !strcmp(n, "sqrtf"))) continue;+ names = realloc(names, (nnames + 1) * sizeof *names);+ names[nnames++] = (struct name){a, strdup(n)};+ }+ fclose(f);+}+static const struct { uint32_t addr; const char *name; } BUILTIN[] = {+ {0x2014C, "GetCSC"}, {0x2050C, "ChkFindSym"}, {0x21D2C, "os_PutStrFull"}, {0x21D30, "os_PutStrLine"},+ {0x21D34, "os_SetCursorPos"}, {0x21D28, "os_GetCursorPos"}, {0x21ED4, "os_GetSystemInfo"},+ {0x21FF0, "os_MemChk"}, {0x22040, "os_ArcChk"}, {0x21FB8, "os_ChkFindSym"}, {0x22180, "os_GetAppVarData"},+ {0x22184, "os_CreateAppVar"}, {0x2217C, "os_DelAppVar"}, {0x21E00, "os_FontDrawText"}, {0x21E28, "os_FontSelect"},+};+const char *os_name(uint32_t addr) {+ for (int i = 0; i < nnames; i++)+ if (names[i].addr == addr) return names[i].name;+ for (size_t i = 0; i < sizeof BUILTIN / sizeof BUILTIN[0]; i++)+ if (BUILTIN[i].addr == addr) return BUILTIN[i].name;+ return "?";+}++/* ---- files ---- */+int ti_read_file(const char *path, tivar_t *out, int max) {+ FILE *f = fopen(path, "rb");+ if (!f) return -1;+ fseek(f, 0, SEEK_END);+ long n = ftell(f);+ rewind(f);+ uint8_t *d = malloc(n > 0 ? n : 1);+ if (fread(d, 1, n, f) != (size_t)n || n < 57 || memcmp(d, "**TI83F*", 8)) {+ fclose(f), free(d);+ return -1;+ }+ fclose(f);+ uint32_t end = 55 + (d[53] | d[54] << 8), p = 55;+ int k = 0;+ while (p + 17 <= end && end <= (uint32_t)n && k < max) {+ uint32_t hl = d[p] | d[p + 1] << 8, q = p + 2 + hl, vl = d[q] | d[q + 1] << 8;+ tivar_t *v = &out[k++];+ memset(v, 0, sizeof *v);+ v->type = d[p + 4];+ memcpy(v->name, d + p + 5, 8);+ for (v->namelen = 0; v->namelen < 8 && v->name[v->namelen]; v->namelen++) {}+ if (hl >= 13) v->version = d[p + 13], v->flag = d[p + 14];+ v->size = vl;+ v->data = malloc(vl);+ memcpy(v->data, d + q + 2, vl);+ p = q + 2 + vl;+ }+ free(d);+ return k;+}++/* ---- the VAT ---- */+typedef struct {+ uint32_t vat, len, data;+ uint8_t type, t2, ver, namelen, name[8];+ bool prog; /* in the programs' part (length-prefixed name) */+} ent_t;++static bool prog_type(uint8_t t) {+ t &= 0x3F;+ return t == 1 || t == 5 || t == 6 || t == 0x0D || t == 0x15 || t == 0x16 || t == 0x17;+}+static int type_class(uint8_t t) {+ t &= 0x3F;+ return t == 6 || t == 0x16 ? 5 : t == 0x0D ? 1 : t;+}+static void ent_read(uint32_t vat, bool prog, ent_t *e) {+ e->vat = vat, e->prog = prog;+ e->type = rd8(vat), e->t2 = rd8(vat - 1), e->ver = rd8(vat - 2);+ e->data = rd8(vat - 3) | rd8(vat - 4) << 8 | (uint32_t)rd8(vat - 5) << 16;+ uint32_t at = vat - 6;+ e->namelen = prog ? rd8(at--) : 3;+ if (e->namelen > 8) e->namelen = 8;+ for (int i = 0; i < e->namelen; i++) e->name[i] = rd8(at--);+ e->len = prog ? 7 + e->namelen : 9;+}+/* each entry in turn: from symTable down, then from progPtr down */+static bool ent_next(ent_t *e, bool first) {+ uint32_t prog_ptr = rd24(PROG_PTR), p_temp = rd24(P_TEMP);+ uint32_t vat = first ? SYM_TABLE : e->vat - e->len;+ bool prog = first ? false : e->prog;+ if (!prog && vat <= prog_ptr) prog = true, vat = prog_ptr;+ if (prog && (vat <= p_temp || vat < USER_MEM)) return false;+ ent_read(vat, prog, e);+ return !prog || (e->namelen > 0 && e->len <= vat - p_temp);+}+static int ent_count;+static bool find(uint8_t type, const uint8_t *name, int namelen, ent_t *e) {+ ent_count = 0;+ for (bool ok = ent_next(e, true); ok; ok = ent_next(e, false)) {+ ent_count++;+ if (e->prog != prog_type(type)) continue;+ if (e->prog) {+ if (e->namelen != namelen || memcmp(e->name, name, namelen) || type_class(e->type) != type_class(type)) continue;+ } else if (memcmp(e->name, name, 3)) {+ continue;+ }+ return true;+ }+ return false;+}+static int op1_name(uint8_t *name) {+ int n = 0;+ memset(name, 0, 8);+ while (n < 8 && (name[n] = rd8(OP1 + 1 + n))) n++;+ return n;+}+static bool find_op1(ent_t *e) {+ uint8_t name[8];+ int n = op1_name(name);+ return find(rd8(OP1), name, n, e);+}+static bool archived(const ent_t *e) { return !in_ram(e->data) && !(e->data >= VRAM && e->data < 0xE00000); }+/* where an archived entry's data (its size first) starts */+static uint32_t arc_data(const ent_t *e) { return e->data + 9 + e->prog + e->namelen; }+static uint32_t data_of(const ent_t *e) { return archived(e) ? arc_data(e) : e->data; }+/* the bytes of a variable's data, as TI-OS counts them */+static uint32_t data_size(uint8_t type, uint32_t p) {+ switch (type & 0x3F) {+ case 0x00: case 0x18: case 0x19: case 0x1C: case 0x20: case 0x21: return 9;+ case 0x0C: case 0x1B: case 0x1D: case 0x1E: case 0x1F: return 18;+ case 0x01: return 2 + rd16(p) * 9;+ case 0x0D: return 2 + rd16(p) * 18;+ case 0x02: return 2 + rd8(p) * rd8(p + 1) * 9;+ default: return 2 + rd16(p);+ }+}+static uint32_t fixed_size(uint8_t type) {+ switch (type & 0x3F) {+ case 0x00: case 0x18: case 0x19: case 0x1C: case 0x20: case 0x21: return 9;+ case 0x0C: case 0x1B: case 0x1D: case 0x1E: case 0x1F: return 18;+ default: return 0;+ }+}+static void ent_set_data(const ent_t *e, uint32_t data) { wr8(e->vat - 3, data), wr8(e->vat - 4, data >> 8), wr8(e->vat - 5, data >> 16); }++/* ---- RAM: the variables' data from userMem, the FP stack after it, then free RAM, the OP stack, the VAT ---- */+static uint32_t ram_free(void) { return rd24(OPS) - rd24(FPS); }+static void move_ptr(uint32_t addr, uint32_t at, int32_t n) {+ uint32_t p = rd24(addr);+ if (p < at) return;+ if (n < 0 && p < at - n) p = at;+ else p += n;+ wr24(addr, p);+}+static void move_vars(uint32_t at, int32_t n) {+ static const uint32_t PTRS[] = {TEMP_MEM, FPS_BASE, FPS, NEW_DATA_PTR};+ for (size_t i = 0; i < sizeof PTRS / sizeof PTRS[0]; i++) move_ptr(PTRS[i], at, n);+ ent_t e;+ for (bool ok = ent_next(&e, true); ok; ok = ent_next(&e, false)) {+ if (!in_ram(e.data) || e.data < at) continue;+ ent_set_data(&e, n < 0 && e.data < at - n ? at : e.data + n);+ }+}+static bool ram_insert(uint32_t at, uint32_t n) {+ uint32_t fps = rd24(FPS);+ if (!n) return true;+ if (at < USER_MEM || at > fps) {+ emu_stop("crash", "InsertMem at %06X, outside the variables' memory (%06X-%06X)", at, USER_MEM, fps);+ return false;+ }+ if (n > ram_free()) {+ emu_stop("crash", "InsertMem of %u bytes with %u free (not checked with EnoughMem)", n, ram_free());+ return false;+ }+ memmove(mem_at(at + n, fps - at), mem_at(at, fps - at), fps - at);+ move_vars(at, (int32_t)n);+ emu_charge(200 + 4 * (fps - at));+ return true;+}+static bool ram_delete(uint32_t at, uint32_t n) {+ uint32_t fps = rd24(FPS);+ if (!n) return true;+ if (at < USER_MEM || at + n > fps) {+ emu_stop("crash", "DelMem of %u bytes at %06X, outside the variables' memory (%06X-%06X)", n, at, USER_MEM, fps);+ return false;+ }+ memmove(mem_at(at, fps - at - n), mem_at(at + n, fps - at - n), fps - at - n);+ move_vars(at, -(int32_t)n);+ emu_charge(200 + 4 * (fps - at - n));+ return true;+}+/* room for a VAT entry of len bytes whose top is at `top` (pTemp or progPtr): what is below moves down */+static bool vat_open(uint32_t top, uint32_t len, bool symbol) {+ uint32_t ops = rd24(OPS);+ if (len > ram_free()) return false;+ memmove(mem_at(ops - len, top - ops + 1), mem_at(ops, top - ops + 1), top - ops + 1);+ if (symbol) wr24(PROG_PTR, rd24(PROG_PTR) - len);+ wr24(P_TEMP, rd24(P_TEMP) - len);+ wr24(OP_BASE, rd24(OP_BASE) - len);+ wr24(OPS, ops - len);+ return true;+}+static void vat_close(const ent_t *e) {+ uint32_t ops = rd24(OPS), below = e->vat - e->len;+ memmove(mem_at(ops + e->len, below - ops + 1), mem_at(ops, below - ops + 1), below - ops + 1);+ if (!e->prog) wr24(PROG_PTR, rd24(PROG_PTR) + e->len);+ wr24(P_TEMP, rd24(P_TEMP) + e->len);+ wr24(OP_BASE, rd24(OP_BASE) + e->len);+ wr24(OPS, ops + e->len);+}+static uint32_t vat_write(uint8_t type, uint8_t ver, const uint8_t *name, int namelen, uint32_t data) {+ bool prog = prog_type(type);+ uint32_t len = prog ? 7 + namelen : 9, top = prog ? rd24(P_TEMP) : rd24(PROG_PTR);+ if (!vat_open(top, len, !prog)) return 0;+ wr8(top, type), wr8(top - 1, 0), wr8(top - 2, ver);+ wr8(top - 3, data), wr8(top - 4, data >> 8), wr8(top - 5, data >> 16);+ uint32_t at = top - 6;+ if (prog) wr8(at--, namelen);+ for (int i = 0; i < (prog ? namelen : 3); i++) wr8(at--, i < namelen ? name[i] : 0);+ return top;+}++/* ---- the archive ---- */+static uint32_t arc_free = ARC_START;+static int arc_gcs;+static uint32_t arc_entry_len(const ent_t *e, uint32_t size) { return 9 + e->prog + e->namelen + size; }+static bool flash_write(uint32_t at, const uint8_t *src, uint32_t n) {+ uint8_t *p = mem_at(at, n);+ if (!p || at < ARC_START || at + n > ARC_END) return false;+ for (uint32_t i = 0; i < n; i++) p[i] &= src[i]; /* NOR: programming clears bits */+ return true;+}+/* a spot for n bytes, the next sector when this one hasn't the room */+static uint32_t arc_spot(uint32_t n) {+ uint32_t at = arc_free;+ if ((at & 0xFFFF) == 0) at++;+ if ((at & 0xFFFF) + n > 0x10000 && n <= 0xFFFF) at = (at | 0xFFFF) + 2;+ return at + n <= ARC_END ? at : 0;+}+static uint32_t arc_put(const ent_t *e, const uint8_t *data, uint32_t size) {+ uint32_t n = arc_entry_len(e, size), at = arc_spot(n);+ if (!at) return 0;+ uint8_t hdr[32], *h = hdr;+ *h++ = 0xFC, *h++ = (n - 3), *h++ = (n - 3) >> 8;+ *h++ = e->type, *h++ = e->t2, *h++ = e->ver, *h++ = 0, *h++ = 0, *h++ = 0;+ if (e->prog) *h++ = e->namelen;+ memcpy(h, e->name, e->namelen), h += e->namelen;+ uint8_t sector = 0xF0;+ flash_write(at & ~0xFFFF, §or, 1);+ flash_write(at, hdr, h - hdr);+ flash_write(at + (h - hdr), data, size);+ arc_free = at + n;+ emu_charge(5000 + 2400 * n); /* (flash writes: some 20 KB a second) */+ return at;+}+/* garbage collection: the entries still in use, packed again from the start; their VAT pointers follow */+static void arc_collect(void) {+ struct { uint32_t vat, data, size; bool prog; } *list = NULL;+ int n = 0;+ ent_t e;+ for (bool ok = ent_next(&e, true); ok; ok = ent_next(&e, false)) {+ if (!archived(&e) || e.data < ARC_START || e.data >= ARC_END) continue;+ list = realloc(list, (n + 1) * sizeof *list);+ list[n].vat = e.vat, list[n].prog = e.prog, list[n].data = arc_data(&e) - ARC_START;+ list[n++].size = data_size(e.type, arc_data(&e));+ }+ size_t cap = ARC_END - ARC_START;+ uint8_t *copy = malloc(cap);+ memcpy(copy, mem_at(ARC_START, cap), cap);+ memset(mem_at(ARC_START, cap), 0xFF, cap);+ arc_free = ARC_START;+ for (int i = 0; i < n; i++) {+ ent_read(list[i].vat, list[i].prog, &e);+ ent_set_data(&e, arc_put(&e, copy + list[i].data, list[i].size));+ }+ free(copy), free(list);+ arc_gcs++;+ emu_charge(48000000); /* about a second */+ emu_warn("archive garbage collected");+}+static bool arc_has_room(uint32_t n) { return arc_spot(n) != 0; }++/* ---- errors: TI-OS's error handlers (PushErrorHandler) or the program's end ---- */+static const char *err_name(int code) {+ switch (code & 0x7F) {+ case 13: return "UNDEFINED";+ case 14: return "MEMORY";+ case 47: return "ARCHIVED";+ case 49: return "ARCHIVE FULL";+ default: return "?";+ }+}+static void os_throw(int code) {+ uint32_t sp = rd24(ERR_SP);+ wr8(ERR_NO, code);+ if (!sp) {+ emu_stop("os-error", "ERR:%s (%d) with no error handler: TI-OS would end the program", err_name(code), code);+ return;+ }+ /* the frame PushErrorHandler made: old errSP, OPBase-OPS, FPS-FPSbase, the handler */+ wr24(ERR_SP, rd24(sp));+ wr24(OPS, rd24(OP_BASE) - rd24(sp + 3));+ wr24(FPS, rd24(FPS_BASE) + rd24(sp + 6));+ uint32_t handler = rd24(sp + 9);+ R.SPL = sp + 12;+ R.A = code;+ if (os_trace) fprintf(stderr, "[os] error %d to the handler at %06X\n", code, handler);+ emu_jump(handler);+}++/* ---- the home screen: TI-OS's 26 x 10 cells under the status bar, drawn with NumPlay's font ---- */+#include "../../launcher/src/font.h"+#define HOME_COLS 26+#define HOME_ROWS 10+static char line_buf[512];+static int line_len;+static void text_flush(void) {+ if (!line_len) return;+ line_buf[line_len] = 0;+ emu_text(line_buf);+ line_len = 0;+}+static void vram_fill(uint32_t y0, uint32_t y1, uint16_t c) {+ for (uint32_t i = y0 * 320; i < y1 * 320; i++) wr16(VRAM + 2 * i, c);+}+static void draw_cell(int row, int col, char ch) {+ const np_font_t *f = &np_font_body;+ int cw = 12, chh = 20, x0 = 4 + col * cw, y0 = 32 + row * chh;+ for (int y = 0; y < chh; y++)+ for (int x = 0; x < cw; x++) wr16(VRAM + 2 * ((y0 + y) * 320 + x0 + x), 0xFFFF);+ unsigned k = (uint8_t)ch;+ if (k < f->first || k >= (unsigned)f->first + f->count) return;+ const np_glyph_t *g = &f->glyphs[k - f->first];+ int pen = (cw - g->advance) / 2, base = (chh + f->ascent - f->descent) / 2;+ const uint8_t *d = f->data + g->offset;+ for (int j = 0; j < g->h; j++)+ for (int i = 0; i < g->w; i++) {+ int n = j * g->w + i, a = (d[n >> 1] >> ((n & 1) * 4)) & 15, cx = pen + g->x + i, cy = base + g->y + j;+ if (a < 6 || cx < 0 || cx >= cw || cy < 0 || cy >= chh) continue;+ uint16_t v = (uint16_t)(31 - a * 2), c = (uint16_t)(v << 11 | (v * 2) << 5 | v);+ wr16(VRAM + 2 * ((y0 + cy) * 320 + x0 + cx), c);+ }+}+static void home_scroll(void) {+ memmove(mem_at(TEXT_SHADOW, HOME_COLS * HOME_ROWS), mem_at(TEXT_SHADOW + HOME_COLS, HOME_COLS * (HOME_ROWS - 1)),+ HOME_COLS * (HOME_ROWS - 1));+ memset(mem_at(TEXT_SHADOW + HOME_COLS * (HOME_ROWS - 1), HOME_COLS), ' ', HOME_COLS);+ for (int r = 0; r < HOME_ROWS; r++)+ for (int c = 0; c < HOME_COLS; c++) draw_cell(r, c, rd8(TEXT_SHADOW + r * HOME_COLS + c));+}+static void new_line(void) {+ text_flush();+ wr8(CUR_COL, 0);+ if (rd8(CUR_ROW) + 1 >= HOME_ROWS) home_scroll();+ else wr8(CUR_ROW, rd8(CUR_ROW) + 1);+}+static void put_char(uint8_t c) {+ if (line_len < (int)sizeof line_buf - 1) line_buf[line_len++] = c >= 32 && c < 127 ? c : '?';+ int row = rd8(CUR_ROW), col = rd8(CUR_COL);+ if (row >= HOME_ROWS) row = HOME_ROWS - 1;+ if (col >= HOME_COLS) {+ new_line();+ row = rd8(CUR_ROW), col = 0;+ }+ wr8(TEXT_SHADOW + row * HOME_COLS + col, c);+ draw_cell(row, col, c);+ wr8(CUR_COL, col + 1);+ emu_charge(2500);+}+static uint32_t put_string(uint32_t s, bool wrap) {+ for (int n = 0; n < 4096; n++, s++) {+ uint8_t c = rd8(s);+ if (!c) break;+ if (!wrap && rd8(CUR_COL) >= HOME_COLS) continue;+ put_char(c);+ }+ return s;+}+static void clear_home(void) {+ memset(mem_at(TEXT_SHADOW, HOME_COLS * HOME_ROWS), ' ', HOME_COLS * HOME_ROWS);+}++/* ---- printf for boot_sprintf: the CE's 3-byte int arguments ---- */+static int ce_format(char *out, size_t cap, uint32_t fmt, int argi) {+ size_t o = 0;+ for (int n = 0; n < 1024; n++, fmt++) {+ char c = rd8(fmt), tmp[64], spec[16];+ if (!c) break;+ if (c != '%') {+ if (o + 1 < cap) out[o++] = c;+ continue;+ }+ int s = 0;+ spec[s++] = '%';+ for (c = rd8(++fmt); c && strchr("-+ #0123456789.", c) && s < 10; c = rd8(++fmt)) spec[s++] = c;+ bool l = c == 'l';+ if (l) c = rd8(++fmt);+ if (c == 'h') c = rd8(++fmt);+ tmp[0] = 0;+ if (c == '%') {+ strcpy(tmp, "%");+ } else if (c == 's') {+ char str[256];+ uint32_t p = arg(argi++);+ int k = 0;+ while (k < 255 && (str[k] = rd8(p + k))) k++;+ str[k] = 0;+ spec[s++] = 's', spec[s] = 0;+ snprintf(tmp, sizeof tmp, spec, str);+ } else if (c == 'c') {+ tmp[0] = arg(argi++), tmp[1] = 0;+ } else if (strchr("diuxXop", c)) {+ int64_t v = l ? arg32(argi) : arg(argi);+ argi += l ? 2 : 1;+ if (c == 'd' || c == 'i') v = l ? (int32_t)v : (v & 0x800000 ? (int64_t)v - 0x1000000 : v);+ spec[s++] = 'l', spec[s++] = 'l', spec[s++] = c == 'p' ? 'x' : c, spec[s] = 0;+ snprintf(tmp, sizeof tmp, spec, (long long)v);+ }+ for (char *t = tmp; *t; t++)+ if (o + 1 < cap) out[o++] = *t;+ }+ out[o] = 0;+ return (int)o;+}++/* ---- floats: TI's boot code works on A:UBC and E:UHL ---- */+static float as_float(uint32_t b) {+ float f;+ memcpy(&f, &b, 4);+ return f;+}+static uint32_t bits_of(float f) {+ uint32_t b;+ memcpy(&b, &f, 4);+ return b;+}+static float f_abc(void) { return as_float((uint32_t)R.A << 24 | (R.BC & 0xFFFFFF)); }+static float f_ehl(void) { return as_float((uint32_t)R.E << 24 | (R.HL & 0xFFFFFF)); }+static void set_abc(uint32_t b) { R.A = b >> 24, R.BC = b & 0xFFFFFF; }+static void ret_float(float f) { /* a C function's float: E:UHL */+ uint32_t b = bits_of(f);+ R.E = b >> 24, R.HL = b & 0xFFFFFF;+}+/* long to float, ties away from zero (as the toolchain says TI's __ltof rounds) */+static float ltof(int32_t x) {+ uint32_t v = x < 0 ? 0u - (uint32_t)x : (uint32_t)x;+ int top = 31;+ while (top > 0 && !(v >> top)) top--;+ if (top > 23) {+ int sh = top - 23;+ uint32_t m = v >> sh, rem = v & ((1u << sh) - 1);+ if (rem >= 1u << (sh - 1)) m++;+ return (x < 0 ? -1.0f : 1.0f) * ldexpf((float)m, sh);+ }+ return (float)x;+}+static int32_t ftol(float f) {+ if (isnan(f)) return 0;+ if (f >= 2147483648.0f) return INT32_MAX;+ if (f < -2147483648.0f) return INT32_MIN;+ return (int32_t)f;+}+/* x in A:UBC, y in E:UHL: flags as for y - x (as the toolchain's __dcmp): z when equal, s (and c) when y < x;+ * a NaN by its bits */+static int64_t fkey(float f) {+ uint32_t b = bits_of(f);+ return b >> 31 ? -(int64_t)(b & 0x7FFFFFFF) : (int64_t)(b & 0x7FFFFFFF);+}+static void fcmp(float x, float y) {+ uint8_t f = R.F & ~(F_C | F_Z | F_S | F_PV | F_N | F_H);+ bool less = isnan(x) || isnan(y) ? fkey(y) < fkey(x) : y < x;+ if (x == y) f |= F_Z;+ else if (less) f |= F_S | F_C;+ R.F = f;+}++/* ---- the program ---- */+static uint8_t prog_name[8], prog_namelen;+static uint32_t calls[0x30000 / 4];+static uint32_t unknown_calls;+static int csc_last = -1;+static uint64_t csc_repeat_at;+/* the CE's keys, TI's scan codes ((7 - group) * 8 + bit + 1) */+static int scan_code(void) {+ for (int g = 1; g <= 7; g++)+ for (int b = 0; b < 8; b++)+ if (emu_key_held(g, b)) return (7 - g) * 8 + b + 1;+ return 0;+}+static uint8_t get_csc(void) {+ int k = scan_code();+ uint64_t now = emu_ms();+ if (!k) {+ csc_last = -1;+ return 0;+ }+ if (k != csc_last) {+ csc_last = k, csc_repeat_at = now + 500;+ return k;+ }+ if (k <= 4 && now >= csc_repeat_at) { /* arrows repeat */+ csc_repeat_at = now + 100;+ return k;+ }+ return 0;+}+/* GetKey's codes for the scan codes */+static uint8_t key_code(uint8_t sk) {+ static const uint8_t K[57] = {+ [1] = 4, [2] = 2, [3] = 1, [4] = 3, [9] = 5, [10] = 0x80, [11] = 0x81, [12] = 0x82, [13] = 0x83, [14] = 0x84,+ [15] = 9, [17] = 0x8C, [18] = 0x90, [19] = 0x93, [20] = 0x96, [21] = 0x85, [25] = 0x8D, [26] = 0x8F, [27] = 0x92,+ [28] = 0x95, [33] = 0x8E, [34] = 0x91, [35] = 0x94, [36] = 0x97, [51] = 0x45, [55] = 0x45, [56] = 0x0A,+ };+ return sk < sizeof K && K[sk] ? K[sk] : sk;+}++/* ---- setting up: the variables, then the program to run ---- */+void os_setup(void) {+ wr24(TEMP_MEM, USER_MEM), wr24(FPS_BASE, USER_MEM), wr24(FPS, USER_MEM), wr24(NEW_DATA_PTR, USER_MEM);+ wr24(PROG_PTR, SYM_TABLE), wr24(P_TEMP, SYM_TABLE), wr24(OP_BASE, SYM_TABLE), wr24(OPS, SYM_TABLE);+ wr24(ERR_SP, 0), wr24(ASM_PRGM_SIZE, 0);+ clear_home();+ arc_free = ARC_START;+}+bool os_add_var(const tivar_t *v, bool to_archive) {+ ent_t e = {0};+ if (find(v->type, v->name, v->namelen, &e)) return false;+ memset(&e, 0, sizeof e);+ e.type = v->type & 0x3F, e.ver = v->version, e.namelen = prog_type(v->type) ? v->namelen : 3, e.prog = prog_type(v->type);+ memcpy(e.name, v->name, 8);+ if (to_archive) {+ uint32_t at = arc_put(&e, v->data, v->size);+ return at && vat_write(e.type, e.ver, v->name, v->namelen, at);+ }+ uint32_t at = rd24(FPS_BASE);+ if (!ram_insert(at, v->size)) return false;+ memcpy(mem_at(at, v->size), v->data, v->size);+ return vat_write(e.type, e.ver, v->name, v->namelen, at) != 0;+}+bool os_set_program(const char *name) {+ memset(prog_name, 0, 8);+ prog_namelen = (uint8_t)strnlen(name, 8);+ memcpy(prog_name, name, prog_namelen);+ ent_t e;+ return find(6, prog_name, prog_namelen, &e);+}+/* the program copied to userMem, as Asm( or a shell does */+static void run_program(void) {+ ent_t e;+ if (!find(6, prog_name, prog_namelen, &e)) {+ emu_stop("error", "no program %.8s", prog_name);+ return;+ }+ uint32_t d = data_of(&e), size = rd16(d);+ if (size < 3 || rd8(d + 2) != 0xEF || rd8(d + 3) != 0x7B) {+ emu_stop("error", "%.8s isn't an assembly program (no EF 7B)", prog_name);+ return;+ }+ uint32_t n = size - 2;+ if (!ram_insert(USER_MEM, n)) return;+ find(6, prog_name, prog_namelen, &e); /* (a program in RAM moved up) */+ memcpy(mem_at(USER_MEM, n), mem_at(data_of(&e) + 4, n), n);+ wr24(ASM_PRGM_SIZE, n);+ wr8(OP1, e.type & 0x3F);+ for (int i = 0; i < 8; i++) wr8(OP1 + 1 + i, i < prog_namelen ? prog_name[i] : 0);+ /* the stack, marked to measure how deep it goes */+ for (uint32_t a = STACK_BOT; a < R.SPL - 16; a++) wr8(a, 0xA5);+ emu_program_started();+}+int os_stack_used(void) {+ uint32_t a = STACK_BOT;+ while (a < STACK_TOP && rd8(a) == 0xA5) a++;+ return STACK_TOP - a;+}++/* ---- the routines ---- */+static void ret_found(const ent_t *e) {+ R.HL = e->vat, R.DE = e->data, R.A = e->type & 0x3F, R.B = archived(e) ? (e->data >> 16) & 0xFF : 0;+ flag(F_C, false);+}+static uint32_t chk_mem(uint32_t n) { return n <= ram_free(); }++bool os_trap(uint32_t pc) {+ bool boot = pc >= 0x80 && pc < 0x800, osj = pc >= 0x20100 && pc < HLE_BASE, own = pc >= HLE_BASE && pc < HLE_BASE + 4 * HLE_SLOTS;+ if (!(boot || osj || own) || (pc & 3)) return false;+ if (pc / 4 < sizeof calls / sizeof calls[0]) calls[pc / 4]++;+ if (os_trace && !own) fprintf(stderr, "[os] %6llu ms %06X %s\n", (unsigned long long)emu_ms(), pc, os_name(pc));+ ent_t e;+ uint8_t name[8];+ switch (pc) {+ /* the host's own */+ case HLE_BASE + 4 * HLE_START: run_program(); return true;+ case HLE_BASE + 4 * HLE_EXIT:+ text_flush();+ ram_delete(USER_MEM, rd24(ASM_PRGM_SIZE));+ wr24(ASM_PRGM_SIZE, 0);+ emu_program_exited(R.HL & 0xFFFFFF);+ return true;+ case HLE_BASE + 4 * HLE_GETKEY_CODE: R.A = key_code(R.A); return true;++ /* boot code */+ case 0x080: R.A = 5; return true; /* boot.GetBootVerMajor */+ case 0x084: R.A = 0; return true; /* GetHardwareVers */+ case 0x08C: R.A = 3; return true; /* GetBootVerMinor */+ case 0x090: R.A = 6; return true; /* GetBootVerBuild */+ case 0x0B4: { /* boot_DebugPrintf */+ char buf[512];+ ce_format(buf, sizeof buf, arg(0), 1);+ fprintf(stderr, "[dbg] %s", buf);+ return true;+ }+ case 0x0BC: { /* boot_sprintf */+ char buf[1024];+ int n = ce_format(buf, sizeof buf, arg(1), 2);+ uint8_t *p = mem_at(arg(0), n + 1);+ if (p) memcpy(p, buf, n + 1);+ R.HL = n;+ emu_charge(3000 + 400 * n);+ return true;+ }+ case 0x270: set_abc(bits_of(f_abc() + f_ehl())), emu_charge(350); return true; /* __fadd */+ case 0x274: fcmp(f_abc(), f_ehl()), emu_charge(110); return true; /* __fcmp */+ case 0x278: set_abc(bits_of(f_abc() / f_ehl())), emu_charge(1100); return true; /* __fdiv */+ case 0x27C: set_abc((uint32_t)ftol(f_abc())), emu_charge(170); return true; /* __ftol */+ case 0x284: set_abc(bits_of(ltof((int32_t)((uint32_t)R.A << 24 | (R.BC & 0xFFFFFF))))), emu_charge(150); return true;+ case 0x288: set_abc(bits_of(f_abc() * f_ehl())), emu_charge(450); return true; /* __fmul */+ case 0x290: set_abc(bits_of(f_abc() - f_ehl())), emu_charge(370); return true; /* __fsub */+ case 0x298: ret_float(sqrtf(as_float(arg32(0)))), emu_charge(2500); return true;+ case 0x374: vram_fill(0, 240, 0xFFFF), emu_charge(200000); return true; /* boot.ClearVRAM */+ case 0x378: R.HL = put_string(R.HL, true); return true; /* boot.PutS */+ case 0x384: case 0x388: return true; /* Initialize/TurnOffHardware */+ case 0x390: new_line(); return true; /* boot.NewLine */+ case 0x3B4: emu_charge(480000); return true; /* Delay10ms */++ /* the OS: keys, the home screen */+ case 0x2014C: R.A = get_csc(), wr8(KBD_SCAN_CODE, 0), emu_charge(300); return true; /* GetCSC */+ case 0x207B8: put_char(R.A); return true; /* PutC */+ case 0x207C0: R.HL = put_string(R.HL, true); return true; /* PutS */+ case 0x207C8: { /* PutPS */+ uint32_t p = R.HL & 0xFFFFFF, n = rd8(p);+ for (uint32_t i = 0; i < n; i++) put_char(rd8(p + 1 + i));+ R.HL = p + 1 + n;+ return true;+ }+ case 0x207F0: new_line(); return true; /* NewLine */+ case 0x207F4: if (rd8(CUR_ROW) + 1 < HOME_ROWS) wr8(CUR_ROW, rd8(CUR_ROW) + 1); return true; /* MoveDown */+ case 0x20800: if (rd8(CUR_ROW)) wr8(CUR_ROW, rd8(CUR_ROW) - 1); return true; /* MoveUp */+ case 0x20808: case 0x2080C: text_flush(), vram_fill(0, 240, 0xFFFF), emu_charge(330000); return true; /* ClrLCD(Full) */+ case 0x20814: case 0x20810: /* ClrScrn(Full) */+ text_flush(), clear_home(), vram_fill(30, 240, 0xFFFF), emu_charge(300000);+ return true;+ case 0x20818: clear_home(); return true; /* ClrTxtShd */+ case 0x20828: text_flush(), wr8(CUR_ROW, 0), wr8(CUR_COL, 0); return true; /* HomeUp */+ case 0x20844: case 0x20848: case 0x21134: case 0x21138: return true; /* RunIndic, APD */+ case 0x21A3C: vram_fill(0, 30, 0x52AA), emu_charge(150000); return true; /* DrawStatusBar */+ case 0x21D2C: case 0x21D30: /* os_PutStrFull, os_PutStrLine */+ put_string(arg(0), pc == 0x21D2C), R.HL = 1;+ return true;+ case 0x21D34: wr8(CUR_ROW, arg(0)), wr8(CUR_COL, arg(1)); return true; /* os_SetCursorPos */+ case 0x21D28: /* os_GetCursorPos */+ if (arg(0)) wr24(arg(0), rd8(CUR_ROW));+ if (arg(1)) wr24(arg(1), rd8(CUR_COL));+ return true;+ case 0x20164: /* JForceCmd: an app's end */+ emu_program_exited(0);+ return true;++ /* variables */+ case 0x2050C: /* ChkFindSym */+ case 0x20510: /* FindSym */+ if (pc == 0x20510) {+ op1_name(name);+ uint8_t t = rd8(OP1) & 0x3F;+ bool ok = find(prog_type(t) ? 0 : t, name, 3, &e);+ if (ok) ret_found(&e);+ else flag(F_C, true);+ } else if (find_op1(&e)) {+ ret_found(&e);+ } else {+ flag(F_C, true);+ }+ emu_charge(400 + 120 * ent_count);+ return true;+ case 0x21F98: /* ChkInRam: z if DE is in RAM */+ flag(F_Z, in_ram(R.DE & 0xFFFFFF)), flag(F_C, !in_ram(R.DE & 0xFFFFFF));+ return true;+ case 0x20FF4: /* AnsName */+ wr8(OP1, 0), wr8(OP1 + 1, 0x72);+ for (int i = 2; i < 9; i++) wr8(OP1 + i, 0);+ return true;+ case 0x204FC: R.HL = ram_free(), R.DE = rd24(FPS); return true; /* MemChk */+ case 0x2051C: /* EnoughMem: carry if HL bytes aren't free */+ R.DE = R.HL;+ flag(F_C, !chk_mem(R.HL & 0xFFFFFF));+ return true;+ case 0x2072C: /* ErrNotEnoughMem */+ R.DE = R.HL;+ if (!chk_mem(R.HL & 0xFFFFFF)) os_throw(E_MEMORY);+ flag(F_C, false);+ return true;+ case 0x20768: os_throw(E_MEMORY); return true; /* ErrMemory */+ case 0x20790: os_throw(R.A); return true; /* JError */+ case 0x20514: ram_insert(R.DE & 0xFFFFFF, R.HL & 0xFFFFFF); return true; /* InsertMem */+ case 0x20590: ram_delete(R.HL & 0xFFFFFF, R.DE & 0xFFFFFF); return true; /* DelMem */+ case 0x205AC: R.DE = data_size(R.A, R.HL & 0xFFFFFF); return true; /* DataSize */+ case 0x20798: { /* PushErrorHandler: a frame under the return address */+ uint32_t sp = R.SPL, ret = rd24(sp), fs = sp + 3 - 12;+ wr24(fs + 9, R.HL & 0xFFFFFF);+ wr24(fs + 6, rd24(FPS) - rd24(FPS_BASE));+ wr24(fs + 3, rd24(OP_BASE) - rd24(OPS));+ wr24(fs, rd24(ERR_SP));+ wr24(ERR_SP, fs);+ wr24(fs - 3, ret);+ R.SPL = fs - 3;+ return true;+ }+ case 0x2079C: { /* PopErrorHandler */+ uint32_t sp = R.SPL, ret = rd24(sp), frame = sp + 3;+ if (rd24(ERR_SP) != frame) emu_warn("PopErrorHandler without its PushErrorHandler's frame on top");+ wr24(ERR_SP, rd24(frame));+ wr24(frame + 9, ret);+ R.SPL = frame + 9;+ return true;+ }+ case 0x21338: { /* CreateVar: A type, OP1 name, HL size */+ uint8_t t = R.A & 0x3F;+ int n = op1_name(name);+ uint32_t size = R.HL & 0xFFFF, total = fixed_size(t) ? fixed_size(t) : size + 2;+ if (prog_type(t) && !n) {+ emu_stop("crash", "CreateVar with an empty name");+ return true;+ }+ if (total + 7 + n > ram_free()) {+ os_throw(E_MEMORY);+ return true;+ }+ uint32_t at = rd24(FPS_BASE);+ ram_insert(at, total);+ if (total == size + 2) wr16(at, size);+ else memset(mem_at(at, total), 0, total);+ uint32_t vat = vat_write(t, 0, name, prog_type(t) ? n : 3, at);+ for (int i = 0; i < 9; i++) wr8(OP4 + i, rd8(OP1 + i));+ R.HL = vat, R.DE = at, R.BC = size;+ emu_charge(3000);+ return true;+ }+ case 0x21434: /* DelVarArc: HL VAT entry, DE data */+ case 0x21430: { /* DelVar */+ uint32_t vat = R.HL & 0xFFFFFF;+ bool prog = vat <= rd24(PROG_PTR);+ ent_read(vat, prog, &e);+ if (archived(&e)) {+ uint8_t deleted = 0xF0;+ flash_write(e.data, &deleted, 1);+ } else {+ ram_delete(e.data, data_size(e.type, e.data));+ }+ vat_close(&e);+ emu_charge(5000);+ return true;+ }+ case 0x21448: { /* Arc_Unarc: the variable named by OP1 */+ if (!find_op1(&e)) {+ os_throw(E_UNDEFINED);+ return true;+ }+ if (archived(&e)) {+ uint32_t d = arc_data(&e), size = data_size(e.type, d);+ if (size > ram_free()) {+ os_throw(E_MEMORY);+ return true;+ }+ uint32_t at = rd24(FPS_BASE), entry = e.data;+ ram_insert(at, size);+ memcpy(mem_at(at, size), mem_at(d, size), size);+ find_op1(&e);+ ent_set_data(&e, at);+ uint8_t deleted = 0xF0;+ flash_write(entry, &deleted, 1);+ emu_charge(20000 + 8 * size);+ } else {+ uint32_t size = data_size(e.type, e.data), n = arc_entry_len(&e, size);+ if (!arc_has_room(n)) arc_collect(), find_op1(&e);+ if (!arc_has_room(n)) {+ os_throw(E_ARCH_FULL);+ return true;+ }+ uint32_t at = arc_put(&e, mem_at(e.data, size), size);+ ram_delete(e.data, size);+ find_op1(&e);+ ent_set_data(&e, at);+ }+ return true;+ }+ case 0x22078: /* FindFreeArcSpot: nz if BC bytes fit without a garbage collection */+ flag(F_Z, !arc_has_room(R.BC & 0xFFFFFF));+ R.DE = arc_spot(R.BC & 0xFFFFFF);+ return true;+ case 0x21FF0: /* os_MemChk(void **free) */+ if (arg(0)) wr24(arg(0), rd24(FPS));+ R.HL = ram_free();+ return true;+ case 0x22040: /* os_ArcChk */+ R.HL = ARC_END - arc_free;+ return true;++ /* the C library's float functions in the OS */+ case 0x220D8: { int ex; float m = frexpf(as_float(arg32(0)), &ex); if (arg(2)) wr24(arg(2), (uint32_t)ex); ret_float(m); emu_charge(300); return true; }+ case 0x220DC: ret_float(ldexpf(as_float(arg32(0)), (int)((arg(2) ^ 0x800000) - 0x800000))), emu_charge(300); return true;+ case 0x220E0: case 0x22110: { /* strtof, atof */+ char s[128];+ int k = 0;+ uint32_t p = arg(0);+ while (k < 127 && (s[k] = rd8(p + k))) k++;+ s[k] = 0;+ char *end;+ float v = strtof(s, &end);+ if (pc == 0x220E0 && arg(1)) wr24(arg(1), p + (uint32_t)(end - s));+ ret_float(v), emu_charge(4000);+ return true;+ }+ case 0x220E4: ret_float(logf(as_float(arg32(0)))), emu_charge(5000); return true;+ case 0x220E8: ret_float(log10f(as_float(arg32(0)))), emu_charge(5500); return true;+ case 0x220EC: { float ip, fr = modff(as_float(arg32(0)), &ip); if (arg(2)) { uint32_t b = bits_of(ip); wr24(arg(2), b & 0xFFFFFF), wr8(arg(2) + 3, b >> 24); } ret_float(fr); emu_charge(300); return true; }+ case 0x220F0: ret_float(fabsf(as_float(arg32(0)))), emu_charge(60); return true;+ case 0x220F4: ret_float(floorf(as_float(arg32(0)))), emu_charge(300); return true;+ case 0x220F8: ret_float(powf(as_float(arg32(0)), as_float(arg32(2)))), emu_charge(12000); return true;+ case 0x220FC: ret_float(fmodf(as_float(arg32(0)), as_float(arg32(2)))), emu_charge(1500); return true;+ case 0x22100: ret_float(acosf(as_float(arg32(0)))), emu_charge(6000); return true;+ case 0x22104: ret_float(asinf(as_float(arg32(0)))), emu_charge(6000); return true;+ case 0x22108: ret_float(atanf(as_float(arg32(0)))), emu_charge(5000); return true;+ case 0x2210C: ret_float(atan2f(as_float(arg32(0)), as_float(arg32(2)))), emu_charge(6000); return true;+ case 0x22114: ret_float(ceilf(as_float(arg32(0)))), emu_charge(300); return true;+ case 0x22118: ret_float(sinf(as_float(arg32(0)))), emu_charge(5000); return true;+ case 0x2211C: ret_float(cosf(as_float(arg32(0)))), emu_charge(5000); return true;+ case 0x22120: ret_float(tanf(as_float(arg32(0)))), emu_charge(9000); return true;+ case 0x22124: ret_float(expf(as_float(arg32(0)))), emu_charge(5000); return true;+ case 0x22130: ret_float(sinhf(as_float(arg32(0)))), emu_charge(7000); return true;+ case 0x22134: ret_float(coshf(as_float(arg32(0)))), emu_charge(7000); return true;+ case 0x22138: ret_float(tanhf(as_float(arg32(0)))), emu_charge(8000); return true;+ }+ unknown_calls++;+ emu_stop("unimplemented", "the program called %s %s at %06X, which ce_emu's OS doesn't do yet (from %06X)",+ boot ? "boot code routine" : "OS routine", os_name(pc), pc, rd24(R.SPL));+ return true;+}++void os_report(FILE *f) {+ int n = 0;+ fprintf(f, " \"os_calls\": {");+ for (uint32_t i = 0; i < sizeof calls / sizeof calls[0]; i++)+ if (calls[i] && (i * 4 < HLE_BASE || i * 4 >= HLE_BASE + 4 * HLE_SLOTS))+ fprintf(f, "%s\"%s\": %u", n++ ? ", " : "", os_name(i * 4), calls[i]);+ fprintf(f, "},\n \"stack_bytes\": %d,\n \"free_ram\": %u,\n \"archive_used\": %u,\n \"garbage_collects\": %d,\n",+ os_stack_used(), ram_free(), arc_free - ARC_START, arc_gcs);+}++/* the appvars and programs at the end, as .8xv/.8xp files */+int os_save_vars(const char *dir) {+ ent_t e;+ int k = 0;+ for (bool ok = ent_next(&e, true); ok; ok = ent_next(&e, false)) {+ if (!e.prog || ((e.type & 0x3F) != 0x15 && (e.type & 0x3F) != 5 && (e.type & 0x3F) != 6)) continue;+ uint32_t d = data_of(&e), size = data_size(e.type, d);+ char path[1024], nm[9] = {0};+ memcpy(nm, e.name, e.namelen);+ snprintf(path, sizeof path, "%s/%s.%s", dir, nm, (e.type & 0x3F) == 0x15 ? "8xv" : "8xp");+ FILE *f = fopen(path, "wb");+ if (!f) continue;+ uint8_t hdr[55] = "**TI83F*\x1a\x0a";+ memcpy(hdr + 11, "ce_emu", 6);+ uint32_t entry = 2 + 13 + 2 + size;+ hdr[53] = entry, hdr[54] = entry >> 8;+ uint8_t vh[17] = {13, 0, size, size >> 8, e.type & 0x3F};+ memcpy(vh + 5, e.name, e.namelen);+ vh[13] = e.ver, vh[14] = archived(&e) ? 0x80 : 0, vh[15] = size, vh[16] = size >> 8;+ uint8_t *data = mem_at(d, size);+ uint32_t sum = 0;+ for (int i = 0; i < 17; i++) sum += vh[i];+ for (uint32_t i = 0; i < size; i++) sum += data[i];+ uint8_t cs[2] = {sum, sum >> 8};+ fwrite(hdr, 1, 55, f), fwrite(vh, 1, 17, f), fwrite(data, 1, size, f), fwrite(cs, 1, 2, f);+ fclose(f);+ k++;+ }+ return k;+}diff --git a/tools/ce_emu/rom.S b/tools/ce_emu/rom.Snew file mode 100644index 00000000..556a0d6d--- /dev/null+++ b/tools/ce_emu/rom.S@@ -0,0 +1,586 @@+; The flash image ce_emu runs instead of TI's: a boot that sets the hardware up as TI-OS leaves it for a+; program, then the boot code's and the OS's jump tables. A slot is a jump to code here (the C library and+; runtime of the CE toolchain, linked in) or a ret that the host traps (os.c): every slot of the tables that+; holds C9 is the host's, and those it doesn't know stop the run with the routine's name.+;+; Built with the CE toolchain's binutils (Makefile), linked at 0 with its libcrt.a and libc.a (LGPL-3.0).++ .assume adl=1++ .equ OP1, 0xD005F8+ .equ OP2, 0xD00603+ .equ FPS, 0xD0258D+ .equ flags, 0xD00080+ .equ stackTop, 0xD1A87E+ .equ userMem, 0xD1A881+ .equ HLE, 0x023000 ; the host's own entry points (os.c: HLE_*)++;-------------------------------------------------------------------------------+; boot code: vectors and its jump table+;-------------------------------------------------------------------------------+ .section .boot, "ax", @progbits++ .byte 0x5B, 0xC3 ; jp.lil boot (the eZ80 starts in Z80 mode)+ .d24 boot++ .org 0x38, 0xC9+ jp int_handler+ .org 0x66, 0xC9 ; NMI: the host's (a protection fault)+ .org 0x80, 0xC9++ .macro slot addr, target+ .org \addr, 0xC9+ jp \target+ .endm++ slot 0x098, my_longjmp+ slot 0x09C, _memchr+ slot 0x0A0, _memcmp+ slot 0x0A4, _memcpy+ slot 0x0A8, _memmove+ slot 0x0AC, _memset+ slot 0x0B0, _bzero ; memclear+ slot 0x0B8, my_setjmp+ slot 0x0C0, _strcat+ slot 0x0C4, _strchr+ slot 0x0C8, _strcmp+ slot 0x0CC, _strcpy+ slot 0x0D0, _strcspn+ slot 0x0D4, _strlen+ slot 0x0D8, _strncat+ slot 0x0DC, _strncmp+ slot 0x0E0, _strncpy+ slot 0x0E4, _strpbrk+ slot 0x0E8, _strrchr+ slot 0x0EC, _strspn+ slot 0x0F0, _strstr+ slot 0x0F4, _strtok+ slot 0x100, __bshl+ slot 0x104, __bshru+ slot 0x12C, __frameset+ slot 0x130, __frameset0+ slot 0x134, __iand+ slot 0x138, __icmpzero+ slot 0x13C, __idivs+ slot 0x140, __idivu+ slot 0x144, __idvrmu+ slot 0x150, __imul_b+ slot 0x154, __imulu+ slot 0x158, __imuls+ slot 0x15C, my_indcall+ slot 0x160, __ineg+ slot 0x164, __inot+ slot 0x168, __ior+ slot 0x16C, __irems+ slot 0x170, __iremu+ slot 0x174, __ishl+ slot 0x178, my_ishl_b+ slot 0x17C, __ishrs+ slot 0x180, my_ishrs_b+ slot 0x184, __ishru+ slot 0x188, my_ishru_b+ slot 0x194, my_itol+ slot 0x198, __ixor+ slot 0x19C, __ladd+ slot 0x1A0, __ladd_b+ slot 0x1A4, __land+ slot 0x1A8, __lcmps+ slot 0x1AC, __lcmpu+ slot 0x1B0, __lcmpzero+ slot 0x1B4, __ldivs+ slot 0x1B8, __ldivu+ slot 0x1BC, __ldvrmu+ slot 0x1C8, __lmuls+ slot 0x1CC, __lmulu+ slot 0x1D0, __lneg+ slot 0x1D4, __lnot+ slot 0x1D8, __lor+ slot 0x1DC, __lrems+ slot 0x1E0, __lremu+ slot 0x1E4, __lshl+ slot 0x1E8, __lshrs+ slot 0x1EC, __lshru+ slot 0x1F8, __lsub+ slot 0x1FC, __lxor+ slot 0x200, __sand+ slot 0x204, __scmpzero+ slot 0x208, __sdivs+ slot 0x20C, __sdivu+ slot 0x218, __setflag+ slot 0x224, __smuls+ slot 0x228, __smulu+ slot 0x22C, __sneg+ slot 0x230, __snot+ slot 0x234, __sor+ slot 0x238, __srems+ slot 0x23C, __sremu+ slot 0x240, __sshl+ slot 0x244, my_sshl_b+ slot 0x248, __sshrs+ slot 0x24C, my_sshrs_b+ slot 0x250, __sshru+ slot 0x254, my_sshru_b+ slot 0x260, my_stoi+ slot 0x264, my_stoiu+ slot 0x268, __sxor+ slot 0x28C, __fneg+ slot 0x39C, set6mhz+ slot 0x3A0, set48mhz+ slot 0x3A4, set6mhz+ slot 0x3A8, set48mhz+ slot 0x4F0, noop ; usb_ResetTimer+ slot 0x4F4, noop ; usb_DisableTimer+ slot 0x4F8, noop ; usb_EnableTimer+ .org 0x800, 0xC9++;-------------------------------------------------------------------------------+; the boot: hardware as TI-OS sets it, then the program+;-------------------------------------------------------------------------------+boot:+ di+ ld sp, stackTop+ im 1+ ld a, 3 ; 48 MHz+ out0 (0x01), a+ ; LCD controller: TI-OS's timings, 16 bpp 5:6:5 BGR, the screen at 0xD40000+ ld hl, lcd_regs+ ld de, 0xE30000+ ld bc, 28+ ldir+ call panel_init+ ld a, 0x7F ; the backlight+ ld (0xF60024), a+ ; keypad: kb_Reset's timings, scanning all the time as under TI-OS+ ld hl, 0x000F03+ ld (0xF50000), hl+ ld hl, 0x08080F+ ld (0xF50003), hl+ ; interrupts: the ON key (latched) and the OS timer+ ld hl, 0x000011+ ld (0xF00004), hl+ ld (0xF0000C), hl+ ld (0xF00008), hl+ ld a, 1+ ld (0xF0002C), a ; ON latch (kb_EnableOnLatch's)+ ; memory protection as on the calculator: code past the OS is unprivileged, a stack overflow faults+ ld a, 0x0B+ out0 (0x1F), a+ ld a, 0xFF+ out0 (0x1E), a+ out0 (0x1D), a ; privileged up to 0x0BFFFF+ ld a, 0x7D+ out0 (0x3A), a+ ld a, 0x98+ out0 (0x3B), a+ ld a, 0xD1+ out0 (0x3C), a ; stack limit 0xD1987D, just under stackBot+ ld iy, flags+ call HLE + 0 * 4 ; the host: the variables, the program copied to userMem, OP1 its name+ ld iy, flags+ ei+ call userMem+ di+ call HLE + 1 * 4 ; the host: the program returned (HL its code)+.L.boot.done:+ halt+ jr .L.boot.done++lcd_regs: ; timing 0-3, upbase, lpbase, control+ .d24 0x0A0338+ .byte 0x1F+ .d24 0x02013F+ .byte 0x04+ .d24 0xEF7802+ .byte 0x00+ .d24 0x000000+ .byte 0x00+ .d24 0xD40000+ .byte 0x00+ .d24 0xD40000+ .byte 0x00+ .d24 0x00092D+ .byte 0x00++; the panel over SPI with TI-OS's settings (lcddrvce.h names them): sleep out, BGR, 18 bpp, the RGB interface+panel_init:+ ld a, 0x0B ; master, clock phase and polarity+ ld (0xF80000), a+ ld hl, 0x080001 ; 9-bit frames+ ld (0xF80004), hl+ ld hl, 0x00010D ; TX on, FIFOs cleared, chip on+ ld (0xF80008), hl+ ld hl, panel_cmds+.L.panel_init.next:+ ld a, (hl)+ inc hl+ or a, a+ ret z+ ld b, a ; number of parameters + 1+ ld c, 0 ; command+.L.panel_init.frame:+ push hl+ ld hl, 0xF8000D+.L.panel_init.wait:+ ld a, 0xEF+ cp a, (hl)+ jr c, .L.panel_init.wait+ pop hl+ ld a, c+ ld (0xF80019), a ; 0: command, 1: parameter+ ld a, (hl)+ inc hl+ ld (0xF80018), a+ ld c, 1+ djnz .L.panel_init.frame+ jr .L.panel_init.next++panel_cmds: ; count (1 + parameters), command, parameters+ .byte 1, 0x11 ; SLPOUT+ .byte 2, 0x36, 0x08 ; MADCTL: BGR+ .byte 2, 0x3A, 0x66 ; COLMOD: 18 bpp+ .byte 3, 0xB0, 0x11, 0xF0 ; RAMCTRL: RGB interface+ .byte 4, 0xB1, 0x01, 5, 20 ; RGBCTRL+ .byte 2, 0xC0, 0x22 ; LCMCTRL: XMV, XBGR+ .byte 5, 0x2A, 0, 0, 0x01, 0x3F ; CASET 0-319 (rows and columns exchanged)+ .byte 5, 0x2B, 0, 0, 0, 0xEF ; RASET 0-239+ .byte 1, 0x29 ; DISPON+ .byte 0++int_handler: ; acknowledge; what can't be (not latched) is masked off+ push af+ push bc+ push de+ push hl+ ld de, 0xF00014+ ld hl, 0xF00008+ ld b, 3+.L.int_handler.ack:+ ld a, (de)+ ld (hl), a+ inc de+ inc hl+ djnz .L.int_handler.ack+ ld de, 0xF00014+ ld hl, 0xF00004+ ld b, 3+.L.int_handler.mask:+ ld a, (de)+ cpl+ and a, (hl)+ ld (hl), a+ inc de+ inc hl+ djnz .L.int_handler.mask+ pop hl+ pop de+ pop bc+ pop af+ ei+ reti++noop:+ ret++set6mhz:+ push af+ xor a, a+ out0 (0x01), a+ pop af+ ret++set48mhz:+ push af+ ld a, 3+ out0 (0x01), a+ pop af+ ret++;-------------------------------------------------------------------------------+; the runtime routines TI's boot code has and the toolchain's libcrt.a doesn't+;-------------------------------------------------------------------------------+my_indcall:+ jp (iy)++my_ishl_b: ; uhl <<= a+ push af+ and a, 31+ jr z, .L.my_ishl_b.end+.L.my_ishl_b.loop:+ add hl, hl+ dec a+ jr nz, .L.my_ishl_b.loop+.L.my_ishl_b.end:+ pop af+ ret++my_ishru_b: ; uhl >>= a (unsigned)+ push bc+ ld c, a+ call __ishru+ pop bc+ ret++my_ishrs_b: ; uhl >>= a (signed)+ push bc+ ld c, a+ call __ishrs+ pop bc+ ret++my_sshl_b: ; hl <<= a (16 bits)+ push bc+ ld c, a+ call __sshl+ pop bc+ ret++my_sshru_b:+ push bc+ ld c, a+ call __sshru+ pop bc+ ret++my_sshrs_b:+ push bc+ ld c, a+ call __sshrs+ pop bc+ ret++my_itol: ; e:uhl = (long)uhl+ push af+ push hl+ add hl, hl ; carry = sign+ sbc a, a+ ld e, a+ pop hl+ pop af+ ret++my_stoi: ; uhl = (int)(short)hl+ push de+ push af+ ex de, hl+ ld a, d+ rla+ sbc hl, hl ; 0 or -1: the upper byte+ ld h, d+ ld l, e+ pop af+ pop de+ ret++my_stoiu: ; uhl = (unsigned)(unsigned short)hl+ push de+ ex de, hl+ ld hl, 0+ ld h, d+ ld l, e+ pop de+ ret++; jmp_buf: sp after the return, ix, the return address, iy+my_setjmp:+ pop bc ; return address+ pop hl ; env+ push hl+ push bc+ ex de, hl+ ld hl, 3+ add hl, sp+ ex de, hl+ ld (hl), de+ inc hl+ inc hl+ inc hl+ ld (hl), ix+ inc hl+ inc hl+ inc hl+ ld (hl), bc+ inc hl+ inc hl+ inc hl+ ld (hl), iy+ or a, a+ sbc hl, hl+ ret++my_longjmp:+ pop bc+ pop ix ; env+ pop hl ; val (0 returns 1)+ ld de, 0+ or a, a+ sbc hl, de+ jr nz, .L.my_longjmp.nz+ inc hl+.L.my_longjmp.nz:+ ex de, hl+ ld hl, (ix + 0)+ ld iy, (ix + 9)+ ld bc, (ix + 6)+ ld ix, (ix + 3)+ ld sp, hl+ push bc+ ex de, hl+ ret++;-------------------------------------------------------------------------------+; the OS jump table+;-------------------------------------------------------------------------------+ .section .os, "ax", @progbits+ .org 0x100, 0xC9++ slot 0x020274 - 0x20000, HLTimes9+ slot 0x0202FC - 0x20000, Mov9b+ slot 0x020304 - 0x20000, Mov8b+ slot 0x020320 - 0x20000, Mov9ToOP1+ slot 0x020324 - 0x20000, Mov9OP1OP2+ slot 0x02032C - 0x20000, MovFrOP1+ slot 0x0205C4 - 0x20000, PopOP1+ slot 0x0205DC - 0x20000, PopRealO1+ slot 0x020614 - 0x20000, PushRealO1+ slot 0x020628 - 0x20000, PushOP1+ slot 0x020D8C - 0x20000, GetKey+ slot 0x0210DC - 0x20000, MemClear+ slot 0x021D38 - 0x20000, os_GetKey+ slot 0x021D3C - 0x20000, 0x02014C ; os_GetCSC+ slot 0x021D48 - 0x20000, ChkBCIs0+ slot 0x021D68 - 0x20000, SetDEUToA+ slot 0x021D9C - 0x20000, LoadDEInd_s+ .org 0x3000, 0xC9 ; HLE: the host's own entry points (64 slots)+ .org 0x3100, 0xC9++HLTimes9: ; hl *= 9+ push bc+ push hl+ pop bc+ add hl, hl+ add hl, hl+ add hl, hl+ add hl, bc+ pop bc+ ret++Mov9ToOP1:+ ld de, OP1+Mov9b:+ ld bc, 9+ ldir+ ret++Mov8b:+ ld bc, 8+ ldir+ ret++Mov9OP1OP2:+ ld hl, OP1+ ld de, OP2+ jr Mov9b++MovFrOP1:+ ld hl, OP1+ jr Mov9b++PushRealO1: ; 9 bytes onto the FPS+ ld bc, 9+ jr push_op1+PushOP1: ; 11+ ld bc, 11+push_op1:+ push af+ push de+ push hl+ ld de, (FPS)+ ld hl, OP1+ ldir+ ld (FPS), de+ pop hl+ pop de+ pop af+ ret++PopRealO1:+ ld bc, 9+ jr pop_op1+PopOP1:+ ld bc, 11+pop_op1:+ push af+ push de+ push hl+ ld hl, (FPS)+ or a, a+ sbc hl, bc+ ld (FPS), hl+ ld de, OP1+ ldir+ pop hl+ pop de+ pop af+ ret++MemClear: ; bc bytes at hl+ push de+ push hl+ or a, a+ sbc hl, hl+ adc hl, bc+ pop hl+ jr z, .L.MemClear.end+ ld (hl), 0+ dec bc+ push hl+ or a, a+ sbc hl, hl+ adc hl, bc+ pop hl+ jr z, .L.MemClear.end+ push hl+ pop de+ inc de+ ldir+.L.MemClear.end:+ pop de+ ret++ChkBCIs0: ; z if bc is 0+ push hl+ or a, a+ sbc hl, hl+ adc hl, bc+ pop hl+ ret++SetDEUToA: ; the upper byte of de = a+ push hl+ push de+ ld hl, 2+ add hl, sp+ ld (hl), a+ pop de+ pop hl+ ret++LoadDEInd_s: ; de = (hl) on 16 bits, hl += 2+ ld de, 0+ ld e, (hl)+ inc hl+ ld d, (hl)+ inc hl+ ret++GetKey: ; waits for a key, as TI's (its code from GetCSC's, by the host)+ call 0x02014C+ or a, a+ jr z, GetKey+ jp HLE + 2 * 4++os_GetKey: ; the C library's: the key in hl+ call GetKey+ ld hl, 0+ ld l, a+ retdiff --git a/tools/ce_emu/rom.ld b/tools/ce_emu/rom.ldnew file mode 100644index 00000000..cd749667--- /dev/null+++ b/tools/ce_emu/rom.ld@@ -0,0 +1,11 @@+/* ce_emu's flash image: the boot code at 0, the OS's jump table at 0x20000, the code linked in after it */+SECTIONS+{+ .boot 0x000000 : { KEEP(*(.boot)) }+ .os 0x020000 : { KEEP(*(.os)) }+ .text 0x024000 : { *(.text .text.*) *(.rodata .rodata.*) }+ .data : { *(.data .data.*) *(.bss .bss.*) *(COMMON) }+ ASSERT(SIZEOF(.data) == 0, "rom: code with data of its own can't run from flash")+ ASSERT(. < 0x0C0000, "rom: past the OS's space")+ /DISCARD/ : { *(.comment) *(.note*) }+}