[libcxx-commits] [libcxx] [libc++][hardening] Reclassify string_view(ptr, len)'s size assertion (PR #79297)

David Benjamin via libcxx-commits libcxx-commits at lists.llvm.org
Wed Jan 24 06:43:04 PST 2024


https://github.com/davidben created https://github.com/llvm/llvm-project/pull/79297

The comment makes this error condition sound less problematic than it is. If the length does not match the pointer's bounds, all bounds-checking in string_view goes wrong. A length over PTRDIFF_MAX cannot possibly be a correct bounds and was mostly an underflowed negative number cast to a size_t.

The documentation for _LIBCPP_ASSERT_VALID_INPUT_RANGE discusses ranges being valid, including an iterator and a count, which seemed appropriate here.

>From b03e685e382224e3a8a6f16e5909188559d6b580 Mon Sep 17 00:00:00 2001
From: David Benjamin <davidben at google.com>
Date: Wed, 24 Jan 2024 09:38:32 -0500
Subject: [PATCH] [libc++][hardening] Reclassify string_view(ptr, len)'s size
 assertion

The comment makes this error condition sound less problematic than it
is. If the length does not match the pointer's bounds, all
bounds-checking in string_view goes wrong. A length over PTRDIFF_MAX
cannot possibly be a correct bounds and was mostly an underflowed
negative number cast to a size_t.

The documentation for _LIBCPP_ASSERT_VALID_INPUT_RANGE discusses ranges
being valid, including an iterator and a count, which seemed appropriate
here.
---
 libcxx/include/string_view | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/libcxx/include/string_view b/libcxx/include/string_view
index e414507a7933b68..9740aac1fca78b7 100644
--- a/libcxx/include/string_view
+++ b/libcxx/include/string_view
@@ -307,9 +307,10 @@ public:
       : __data_(__s),
         __size_(__len) {
 #if _LIBCPP_STD_VER >= 14
-    // This will result in creating an invalid `string_view` object -- some calculations involving `size` would
-    // overflow, making it effectively truncated.
-    _LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(
+    // Allocations must fit in `ptrdiff_t` for pointer arithmetic to work. If `__len` exceeds it, the input
+    // range could not have been valid. Most likely the caller underflowed some arithmetic and inadvertently
+    // passed in a negative length.
+    _LIBCPP_ASSERT_VALID_INPUT_RANGE(
         __len <= static_cast<size_type>(numeric_limits<difference_type>::max()),
         "string_view::string_view(_CharT *, size_t): length does not fit in difference_type");
     _LIBCPP_ASSERT_NON_NULL(



More information about the libcxx-commits mailing list