Skip to content

Commit f4c1e87

Browse files
authored
[libc++][hardening] Reclassify string_view(ptr, len)'s size assertion (#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.
1 parent 4d21e75 commit f4c1e87

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

libcxx/include/string_view

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -310,9 +310,10 @@ public:
310310
: __data_(__s),
311311
__size_(__len) {
312312
#if _LIBCPP_STD_VER >= 14
313-
// This will result in creating an invalid `string_view` object -- some calculations involving `size` would
314-
// overflow, making it effectively truncated.
315-
_LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(
313+
// Allocations must fit in `ptrdiff_t` for pointer arithmetic to work. If `__len` exceeds it, the input
314+
// range could not have been valid. Most likely the caller underflowed some arithmetic and inadvertently
315+
// passed in a negative length.
316+
_LIBCPP_ASSERT_VALID_INPUT_RANGE(
316317
__len <= static_cast<size_type>(numeric_limits<difference_type>::max()),
317318
"string_view::string_view(_CharT *, size_t): length does not fit in difference_type");
318319
_LIBCPP_ASSERT_NON_NULL(

0 commit comments

Comments
 (0)