Commit da41b65e authored by Orvid King's avatar Orvid King Committed by Facebook Github Bot

Use checked math when allocating in folly/memory/Arena.h

Summary: To prevent ultra large allocations from causing out of bounds read & writes.

Reviewed By: yfeldblum

Differential Revision: D15610028

fbshipit-source-id: 5adaec121c1fc8a0f0d3d0e56b85fabb2ec89d4c
parent b9807709
......@@ -45,7 +45,10 @@ void* Arena<Alloc>::allocateSlow(size_t size) {
std::pair<Block*, size_t> p;
char* start;
size_t allocSize = std::max(size, minBlockSize()) + sizeof(Block);
size_t allocSize;
if (!checked_add(&allocSize, std::max(size, minBlockSize()), sizeof(Block))) {
throw_exception<std::bad_alloc>();
}
if (sizeLimit_ != kNoSizeLimit &&
allocSize > sizeLimit_ - totalAllocatedSize_) {
throw_exception(std::bad_alloc());
......
......@@ -28,6 +28,7 @@
#include <folly/Likely.h>
#include <folly/Memory.h>
#include <folly/lang/Align.h>
#include <folly/lang/CheckedMath.h>
#include <folly/lang/Exception.h>
#include <folly/memory/Malloc.h>
......@@ -165,7 +166,12 @@ class Arena {
// Round up size so it's properly aligned
size_t roundUp(size_t size) const {
return (size + maxAlign_ - 1) & ~(maxAlign_ - 1);
auto maxAl = maxAlign_ - 1;
size_t realSize;
if (!checked_add<size_t>(&realSize, size, maxAl)) {
throw_exception<std::bad_alloc>();
}
return realSize & ~maxAl;
}
// cache_last<true> makes the list keep a pointer to the last element, so we
......
......@@ -158,6 +158,16 @@ TEST(Arena, SizeLimit) {
EXPECT_THROW(arena.allocate(maxSize + 1), std::bad_alloc);
}
TEST(Arena, ExtremeSize) {
static const size_t requestedBlockSize = sizeof(size_t);
SysArena arena(requestedBlockSize);
void* a = arena.allocate(sizeof(size_t));
EXPECT_TRUE(a != nullptr);
EXPECT_THROW(arena.allocate(SIZE_MAX - 2), std::bad_alloc);
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
gflags::ParseCommandLineFlags(&argc, &argv, true);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment