From 3f658c2d781eb6f64f06438d6caf46d773deef1d Mon Sep 17 00:00:00 2001 From: Dmitry Rantovov Date: Sat, 24 Oct 2026 02:20:46 +0300 Subject: [PATCH] Reject allocation size overflow in memory resource adaptor Signed-off-by: Dmitry Rantovov --- include/exec/__memory_resource_adaptor.hpp | 5 ++++ test/exec/test_memory_resource_adaptor.cpp | 27 ++++++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/include/exec/__memory_resource_adaptor.hpp b/include/exec/__memory_resource_adaptor.hpp index e629966c9..cb6b20901 100644 --- a/include/exec/__memory_resource_adaptor.hpp +++ b/include/exec/__memory_resource_adaptor.hpp @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -178,6 +179,10 @@ namespace experimental::execution // end of the buffer. To make room for the possible rightward shift // and the copy of a pointer, we need to allocate extra space, and // __bytes + __align - 1 + sizeof(void *) is the most we might need. + if (__bytes > (std::numeric_limits::max)() - (__align - 1) - sizeof(void *)) + { + STDEXEC_THROW(std::bad_alloc()); + } std::size_t __upstreamSize = __bytes + __align - 1 + sizeof(void *); void *const __buffer = __traits::allocate(__alloc_, __upstreamSize); diff --git a/test/exec/test_memory_resource_adaptor.cpp b/test/exec/test_memory_resource_adaptor.cpp index 5c319b44c..13a417c9d 100644 --- a/test/exec/test_memory_resource_adaptor.cpp +++ b/test/exec/test_memory_resource_adaptor.cpp @@ -15,14 +15,15 @@ * limitations under the License. */ -#include - #include #include +#include + #include #include +#include #include namespace ex = STDEXEC; @@ -85,6 +86,28 @@ namespace template using alignment = std::integral_constant; +#if !STDEXEC_NO_STDCPP_EXCEPTIONS() + TEMPLATE_TEST_CASE("exec::__memory_resource_adaptor rejects allocation size overflow", + "[types][memory_resource_adaptor]", + custom_allocator, + custom_allocator) + { + using adaptor_t = exec::__memory_resource_adaptor_t; + + auto underlying = make_underlying_resource(); + adaptor_t rsc(adaptor_arg_from_resource(&underlying)); + std::pmr::polymorphic_allocator<> alloc(&rsc); + + auto const align = GENERATE(std::size_t{1}, std::size_t{16}, std::size_t{64}); + auto const max_size = (std::numeric_limits::max)(); + auto const bytes = GENERATE_COPY(max_size, + max_size - (align - 1), + max_size - (align - 1) - sizeof(void*) + 1); + + CHECK_THROWS_AS(alloc.allocate_bytes(bytes, align), std::bad_alloc); + } +#endif + TEMPLATE_TEST_CASE("exec::__memory_resource_adaptor supports over-alignment", "[types][memory_resource_adaptor]", std::allocator,