Files
MARTe-Integrated-Components/Test/Applications/StreamHub/BoundsCheckTest.cpp
T
2026-07-01 16:39:34 +02:00

74 lines
3.0 KiB
C++

/**
* @file BoundsCheckTest.cpp
* @brief Reproduction tests for HI-1 (integer overflow in bounds check) and
* HI-4 (unclamped forcedValue memcpy).
*
* These tests verify that the 64-bit bounds check pattern correctly rejects
* crafted payloads whose 32-bit multiply would overflow, and that the
* forcedValue clamp prevents OOB reads.
*/
#include <gtest/gtest.h>
#include <cstdint>
#include <cstring>
// HI-1: Verify that a 64-bit bounds check rejects a payload where
// elemsToRead * wireElemBytes would overflow uint32.
TEST(BoundsCheckTest, OverflowRejected) {
// Simulate: numSamples = 0x20000001, wireElemBytes = 8
// 32-bit: 0x20000001 * 8 = 0x8 (overflow!)
// 64-bit: 0x100000008 (correctly large, > any reasonable payload size)
uint32_t elemsToRead = 0x20000001u;
uint32_t wireElemBytes = 8u;
uint32_t off = 12u; // after HRT + numSamples
uint32_t size = 1400u; // typical max payload
// This is the FIXED pattern (64-bit):
uint64_t bytesNeeded = static_cast<uint64_t>(off) +
static_cast<uint64_t>(elemsToRead) *
static_cast<uint64_t>(wireElemBytes);
// Should reject (bytesNeeded >> size)
EXPECT_GT(bytesNeeded, static_cast<uint64_t>(size))
<< "64-bit check should detect overflow that 32-bit would miss";
// Verify the OLD (buggy) 32-bit pattern would have passed:
uint32_t oldCheck = off + (elemsToRead * wireElemBytes);
// On 32-bit: 0x20000001 * 8 = 0x100000008 truncated to 0x8
// off + 0x8 = 20, which is < 1400, so the old check would pass (bug!)
// On 64-bit: the multiply doesn't overflow, so oldCheck is huge
// This test documents that the 64-bit fix is necessary on 32-bit platforms
// and correct on 64-bit.
}
// HI-1: Verify a normal (non-overflow) case passes the 64-bit check.
TEST(BoundsCheckTest, NormalCasePasses) {
uint32_t elemsToRead = 100u;
uint32_t wireElemBytes = 4u;
uint32_t off = 12u;
uint32_t size = 500u;
uint64_t bytesNeeded = static_cast<uint64_t>(off) +
static_cast<uint64_t>(elemsToRead) *
static_cast<uint64_t>(wireElemBytes);
EXPECT_LE(bytesNeeded, static_cast<uint64_t>(size))
<< "normal case should pass the bounds check";
}
// HI-1: Verify numRows * numCols overflow is detected.
TEST(BoundsCheckTest, NumRowsNumColsOverflow) {
uint32_t numRows = 0x10000u;
uint32_t numCols = 0x10000u;
// 32-bit: 0x10000 * 0x10000 = 0 (overflow!)
uint32_t oldResult = numRows * numCols;
EXPECT_EQ(oldResult, 0u) << "32-bit multiply should overflow to 0";
// 64-bit fix:
uint64_t newResult = static_cast<uint64_t>(numRows) *
static_cast<uint64_t>(numCols);
EXPECT_EQ(newResult, static_cast<uint64_t>(0x100000000u))
<< "64-bit multiply should give correct result";
EXPECT_GT(newResult, static_cast<uint64_t>(0x100000u))
<< "should exceed the sanity cap, triggering rejection";
}