From 5e8ac2432d5d1b327be9b8d406b78f008c77bcd5 Mon Sep 17 00:00:00 2001
From: Thomas Voss <mail@thomasvoss.com>
Date: Fri, 16 Feb 2024 21:05:28 +0100
Subject: Add extra bounds checking

---
 src/ahoy/emulator.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

(limited to 'src')

diff --git a/src/ahoy/emulator.c b/src/ahoy/emulator.c
index cffc4a9..f774b54 100644
--- a/src/ahoy/emulator.c
+++ b/src/ahoy/emulator.c
@@ -66,6 +66,8 @@ emuinit(struct u8view prog, const char *fn)
 void
 emutick(void)
 {
+	if ((size_t)c8.PC + 1 >= lengthof(mem))
+		diex("%s: attempted to read instruction beyond end of RAM", filename);
 	opexec((mem[c8.PC] << 8) | mem[c8.PC + 1]);
 	c8.PC += 2;
 }
@@ -209,8 +211,10 @@ opexec(uint16_t op)
 		unsigned y = (op & 0x00F0) >> 4;
 		unsigned n = (op & 0x000F) >> 0;
 
+		if (c8.I + n > lengthof(mem))
+			diex("%s: attempted to draw sprite beyond bounds of RAM", filename);
+
 		for (unsigned i = 0; i < n; i++) {
-			/* TODO: bounds check? */
 			uint8_t spr_row = mem[c8.I + i];
 			uint8_t scr_row = c8.V[y] + i;
 			uint64_t msk;
-- 
cgit v1.2.3