Skip to content
Open
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
13 changes: 11 additions & 2 deletions include/boost/json/impl/monotonic_resource.ipp
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
#include <boost/json/monotonic_resource.hpp>
#include <boost/json/detail/except.hpp>
#include <boost/core/max_align.hpp>
#include <boost/throw_exception.hpp>

#include <memory>
#include <new>

namespace boost {
namespace json {
Expand Down Expand Up @@ -128,8 +130,15 @@ do_allocate(
return p;
}

if(next_size_ < n)
next_size_ = round_pow2(n);
// a new block is only aligned to alignof(block), so an
// over-aligned request may need up to align - alignof(block)
// bytes of padding in addition to n
std::size_t const pad = align > alignof(block)
? align - alignof(block) : 0;
if(n > max_size() - pad)
throw_exception( std::bad_alloc(), BOOST_CURRENT_LOCATION );
if(next_size_ < n + pad)
next_size_ = round_pow2(n + pad);
auto b = ::new(upstream_->allocate(
sizeof(block) + next_size_)) block;
b->p = b + 1;
Expand Down
25 changes: 25 additions & 0 deletions test/monotonic_resource.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include <boost/json/serialize.hpp>
#include <boost/core/max_align.hpp>
#include <iostream>
#include <new>

#include "checking_resource.hpp"
#include "test_suite.hpp"
Expand Down Expand Up @@ -317,13 +318,37 @@ R"xx({
(void)mr.allocate(1, alignof(core::max_align_t));
}

void
testOverAligned()
{
// an over-aligned request that fills a fresh block needs
// room for the padding in addition to the requested size
for(std::size_t align = 2 * alignof(core::max_align_t);
align <= 4096; align *= 2)
{
monotonic_resource mr;
void* p = mr.allocate(1024, align);
BOOST_TEST(p != nullptr);
BOOST_TEST(
!(reinterpret_cast<std::uintptr_t>(p) % align));
}
// the padding must not make the request overflow
{
monotonic_resource mr;
BOOST_TEST_THROWS(
mr.allocate(std::size_t(-1) - 100, 4096),
std::bad_alloc);
}
}

void
run()
{
testMembers();
testStorage();
testGeneral();
testAllocation();
testOverAligned();
}
};

Expand Down
Loading