From bec11bcaa748947d6e227490800d2dfb5b899c7b Mon Sep 17 00:00:00 2001 From: Rangi <35663410+Rangi42@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:50:34 -0500 Subject: [PATCH] Validate section patch sizes in case object files are invalid (#2242) --- include/link/section.hpp | 13 ++++++++++++- src/link/object.cpp | 9 +++++++++ src/link/patch.cpp | 10 +--------- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/include/link/section.hpp b/include/link/section.hpp index 4b69dc5a..9b081218 100644 --- a/include/link/section.hpp +++ b/include/link/section.hpp @@ -8,7 +8,7 @@ #include #include -#include "helpers.hpp" // QualifiedEquivalent +#include "helpers.hpp" // assume, QualifiedEquivalent #include "linkdefs.hpp" struct FileStackNode; @@ -28,6 +28,17 @@ struct Patch { Expression rpn; uint32_t offset; PatchType type; + + uint8_t typeSize() const { + assume(type < PATCHTYPE_INVALID); + uint8_t typeSizes[PATCHTYPE_INVALID] = { + 1, // PATCHTYPE_BYTE + 2, // PATCHTYPE_WORD + 4, // PATCHTYPE_LONG + 1, // PATCHTYPE_JR + }; + return typeSizes[type]; + } }; struct Section { diff --git a/src/link/object.cpp b/src/link/object.cpp index 184701f0..be0133f8 100644 --- a/src/link/object.cpp +++ b/src/link/object.cpp @@ -383,6 +383,15 @@ static void readSection( patch.type = PatchType(type); } + if (patch.offset > section.size || patch.offset + patch.typeSize() > section.size) { + fatal( + "%s: \"%s\"'s patch #%" PRIu32 " overflows the section", + fileName, + section.name.c_str(), + patchID + ); + } + uint32_t rpnSize; tryReadLong( rpnSize, diff --git a/src/link/patch.cpp b/src/link/patch.cpp index 8b9aca04..69bb51b2 100644 --- a/src/link/patch.cpp +++ b/src/link/patch.cpp @@ -560,15 +560,7 @@ static void applyFilePatches(Section §ion, Section &dataSection) { for (Patch &patch : section.patches) { int32_t value = computeRPNExpr(patch.rpn, *section.fileSymbols); uint32_t offset = patch.offset + section.offset; - - uint8_t typeSizes[PATCHTYPE_INVALID] = { - 1, // PATCHTYPE_BYTE - 2, // PATCHTYPE_WORD - 4, // PATCHTYPE_LONG - 1, // PATCHTYPE_JR - }; - uint8_t typeSize = typeSizes[patch.type]; - + uint8_t typeSize = patch.typeSize(); if (dataSection.data.size() < offset + typeSize) { rpnErrorAt( patch.rpn,