Skip to content

Fix SP compute unchecked input #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
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
@@ -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));

updateBookeepingVars_(learn);
calculateOverlap_(inputArray, overlaps_);
calculateOverlapPct_(overlaps_, overlapsPct_);
21 changes: 21 additions & 0 deletions src/test/unit/algorithms/SpatialPoolerTest.cpp
Original file line number Diff line number Diff line change
@@ -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()));
//! 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";