]> gcc.gnu.org Git - gcc.git/commitdiff
libstdc++: Check for size overflow in constexpr allocation [PR105957]
authorJonathan Wakely <jwakely@redhat.com>
Tue, 14 Jun 2022 13:37:25 +0000 (14:37 +0100)
committerJonathan Wakely <jwakely@redhat.com>
Wed, 3 Aug 2022 11:30:01 +0000 (12:30 +0100)
libstdc++-v3/ChangeLog:

PR libstdc++/105957
* include/bits/allocator.h (allocator::allocate): Check for
overflow in constexpr allocation.
* testsuite/20_util/allocator/105975.cc: New test.

(cherry picked from commit 0a9af7b4ef1b8aa85cc8820acf54d41d1569fc10)

libstdc++-v3/include/bits/allocator.h
libstdc++-v3/testsuite/20_util/allocator/105975.cc [new file with mode: 0644]

index f7770165273591d2d59a832209474d10dfbf3275..a4b80d924d64e333a73e15ee9e6fea491069a80e 100644 (file)
@@ -179,7 +179,12 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
       allocate(size_t __n)
       {
        if (std::__is_constant_evaluated())
-         return static_cast<_Tp*>(::operator new(__n * sizeof(_Tp)));
+         {
+           if (__builtin_mul_overflow(__n, sizeof(_Tp), &__n))
+             std::__throw_bad_array_new_length();
+           return static_cast<_Tp*>(::operator new(__n));
+         }
+
        return __allocator_base<_Tp>::allocate(__n, 0);
       }
 
diff --git a/libstdc++-v3/testsuite/20_util/allocator/105975.cc b/libstdc++-v3/testsuite/20_util/allocator/105975.cc
new file mode 100644 (file)
index 0000000..4342aea
--- /dev/null
@@ -0,0 +1,18 @@
+// { dg-options "-std=gnu++20" }
+// { dg-do compile { target c++20 } }
+
+// PR libstdc++/105957
+
+#include <memory>
+
+consteval bool test_pr105957()
+{
+  std::allocator<long long> a;
+  auto n = std::size_t(-1) / (sizeof(long long) - 1);
+  auto p = a.allocate(n); // { dg-error "constexpr" }
+  a.deallocate(p, n);
+  return true;
+}
+static_assert( test_pr105957() );
+
+// { dg-error "throw_bad_array_new_length" "" { target *-*-* } 0 }
This page took 0.066611 seconds and 5 git commands to generate.