]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
libstdc++: Validate user-provided stride values for layout_stride.
authorTomasz Kamiński <tkaminsk@redhat.com>
Fri, 3 Jul 2026 12:41:02 +0000 (14:41 +0200)
committerTomasz Kamiński <tkaminsk@redhat.com>
Tue, 7 Jul 2026 13:06:45 +0000 (15:06 +0200)
Converting the __strides values using __index_type_cast asserts
that they are non-negative and each value is representable as
index_type.

libstdc++-v3/ChangeLog:

* include/std/mdspan
(layout_stride::mapping::mapping(const extent_type&, span<...>)):
Convert strides using __index_type_cast, which bring asserts
for negative and unrepresentable values.
* testsuite/23_containers/mdspan/layouts/stride_neg.cc: New test.

Reviewed-by: Jonathan Wakely <jwakely@redhat.com>
Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
libstdc++-v3/include/std/mdspan
libstdc++-v3/testsuite/23_containers/mdspan/layouts/stride_neg.cc [new file with mode: 0644]

index f5556f35fa1497f2bbd1c4debd822841ec5f05c3..23304e71b9df7be65c36898019b992f3dc9d1b12 100644 (file)
@@ -1891,7 +1891,8 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
        : _M_extents(__exts)
        {
          for (size_t __i = 0; __i < extents_type::rank(); ++__i)
-           _M_strides[__i] = index_type(as_const(__strides[__i]));
+           _M_strides[__i] =
+             __mdspan::__index_type_cast<index_type>(as_const(__strides[__i]));
        }
 
       template<typename _OIndexType>
diff --git a/libstdc++-v3/testsuite/23_containers/mdspan/layouts/stride_neg.cc b/libstdc++-v3/testsuite/23_containers/mdspan/layouts/stride_neg.cc
new file mode 100644 (file)
index 0000000..153560b
--- /dev/null
@@ -0,0 +1,31 @@
+// { dg-do compile { target c++23 } }
+#include <mdspan>
+
+#include "../layout_traits.h"
+#include <cstdint>
+
+constexpr size_t dyn = std::dynamic_extent;
+
+constexpr bool
+test_stride_overflow()
+{
+  auto exts = std::extents<uint8_t, dyn, dyn>(1, 3);
+  auto n = size_t(1) << 9;
+  auto m = std::layout_stride::mapping(exts, std::array{n, 1zu}); // { dg-error "expansion of" }
+  (void) m;
+  return true;
+}
+static_assert(test_stride_overflow()); // { dg-error "expansion of" }
+
+constexpr bool
+test_stride_negative()
+{
+  auto exts = std::extents<std::size_t, dyn, dyn>(1, 3);
+  auto m = std::layout_stride::mapping(exts, std::array{1, -4}); // { dg-error "expansion of" } 
+  (void) m;
+  return true;
+}
+static_assert(test_stride_negative()); // { dg-error "expansion of" } 
+
+// { dg-prune-output "non-constant condition for static assertion" }
+// { dg-prune-output "__glibcxx_assert_fail()" }