foxygit / fake-08-xbox360 Log in
commit db4465ae4195c9714d8d4055e6a9c04aded65def
Author:     Jon Bell <j.to.the.bell@gmail.com>
AuthorDate: Wed Dec 31 13:26:12 2025 -0700
Commit:     Jon Bell <j.to.the.bell@gmail.com>
CommitDate: Wed Dec 31 13:26:12 2025 -0700

    Fix off by one bounds checking in mset

    Fixes intermittent crash in terra
---
 source/graphics.cpp    |  7 +++++--
 test/graphicstests.cpp | 34 ++++++++++++++++++++++++++++++++++
 2 files changed, 39 insertions(+), 2 deletions(-)

diff --git a/source/graphics.cpp b/source/graphics.cpp
index e68644e..f88e6a5 100644
--- a/source/graphics.cpp
+++ b/source/graphics.cpp
@@ -1756,12 +1756,15 @@ void Graphics::mset(int celx, int cely, uint8_t snum){
 	const int mapW = _memory->hwState.widthOfTheMap == 0 ? 256 : _memory->hwState.widthOfTheMap;
 	const int mapH = mapSize / mapW;

-	const int idx = cely * mapW + celx;
+	const int maxXIdx = mapW - 1;
+	const int maxYIdx = mapH - 1;

-	if (celx < 0 || celx > mapW || cely < 0 || cely > mapH) {
+	if (celx < 0 || celx > maxXIdx || cely < 0 || cely > maxYIdx) {
         return;
 	}

+	const int idx = cely * mapW + celx;
+
 	if (bigMap){
 		const int offset = 0x8000 - mapSize;
 		_memory->userData[offset + idx] = snum;
diff --git a/test/graphicstests.cpp b/test/graphicstests.cpp
index 4c1c265..2a7b696 100644
--- a/test/graphicstests.cpp
+++ b/test/graphicstests.cpp
@@ -1629,6 +1629,40 @@ TEST_CASE("graphics class behaves as expected") {

         CHECK_EQ(251, result);
     }
+    SUBCASE("mset out of bounds does nothing"){
+        graphics->mset(-1, 16, 1);
+        graphics->mset(128, 16, 1);
+        graphics->mset(10, -1, 1);
+        graphics->mset(10, 64, 1);
+        graphics->mset(128, 64, 1);
+
+        auto result1 = graphics->mget(-1, 16);
+        auto result2 = graphics->mget(128, 16);
+        auto result3 = graphics->mget(10, -1);
+        auto result4 = graphics->mget(10, 64);
+        auto result5 = graphics->mget(128, 64);
+
+        CHECK_EQ(0, result1);
+        CHECK_EQ(0, result2);
+        CHECK_EQ(0, result3);
+        CHECK_EQ(0, result4);
+        CHECK_EQ(0, result5);
+    }
+    SUBCASE("mset out of bounds of big map doesn't crash"){
+        picoRam.data[0x5f56] = 0x80;
+        const int cely = 128;
+        const int celx = 128; //128 is out of bounds, but the index is inbounds
+        const int mapW = 128;
+        const int idx = cely * mapW + celx;
+
+        auto resultBefore = picoRam.userData[idx];
+
+        graphics->mset(celx, cely, resultBefore + 1);
+
+        auto resultAfter = picoRam.userData[idx];
+
+        CHECK_EQ(resultBefore, resultAfter);
+    }
     SUBCASE("map with no layer argument draws map cell sprite"){
         for(int i = 0; i < 128; i++) {
             for (int j = 0; j < 32; j++)