Skip to content
This repository has been archived by the owner on Sep 1, 2023. It is now read-only.

Fix sp compute unchecked input #1389

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/nupic/algorithms/SpatialPooler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,11 @@ void SpatialPooler::initialize(vector<UInt> inputDimensions,
void SpatialPooler::compute(UInt inputArray[], bool learn,
UInt activeArray[])
{
// check size of input/output arrays
//TODO since c++17 there is std::size() in <iterator> for arrays
// NTA_ASSERT(this->getNumInputs() == std::vector<UInt>(inputArray).size()); //FIXME get size of the array (T*) ?
// NTA_ASSERT(this->getNumColumns() == sizeof(*activeArray)/sizeof(UInt));
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How can we overcome that inputArray[] is of type T*? We need the size of the passed array.


updateBookeepingVars_(learn);
calculateOverlap_(inputArray, overlaps_);
calculateOverlapPct_(overlaps_, overlapsPct_);
Expand Down
21 changes: 21 additions & 0 deletions src/test/unit/algorithms/SpatialPoolerTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2222,6 +2222,27 @@ namespace {
EXPECT_EQ(0, countNonzero(activeColumns));
}


TEST(SpatialPoolerTest, testComputeWrongInput)
{
/** this test checks behavior when user passes arrays of incorrect
size to the compute() */
SpatialPooler sp{std::vector<UInt>{5} /* input*/, std::vector<UInt>{10}/* SP output cols */};
std::vector<UInt> inputOK = {1, 2, 3, 4, 5}; //true size is 5
std::vector<UInt> inputFail = {1,2};


std::vector<UInt> outOK(sp.getNumColumns(), 0); //true size is 10
std::vector<UInt> outFail(4, 0); //fails size is 4 < 10, this could write to other data memory -> crash
std::vector<UInt> outFailButNoFail(100, 0); //wrong size, but 100>10 so no address space violation (just wasteful), should pass

EXPECT_NO_THROW(sp.compute(inputOK.data(), true, outOK.data()));
//FIXME EXPECT_ANY does not handle the malloc fail caused here, crashes!
//! EXPECT_ANY_THROW(sp.compute(inputFail.data(), true, outOK.data()));
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the test crashes (malloc) even though we know it'd crash and want to check for it. Is there a way how to achieve this?

//! EXPECT_ANY_THROW(sp.compute(inputOK.data(), true, outFail.data()));
EXPECT_NO_THROW(sp.compute(inputOK.data(), true, outFailButNoFail.data()));
}

TEST(SpatialPoolerTest, testSaveLoad)
{
const char* filename = "SpatialPoolerSerialization.tmp";
Expand Down