[libc++] Assert that the resize_and_overwrite operation returns a size in [0, n] #230605
<!--LLVM NEW CONTRIBUTOR COMMENT-->
Hello @ilyas-mallah :wave:
Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is your first PR, here are a few useful links covering our main contribution policies and review practices.
All contributions to LLVM must follow our LLVM AI Tool Use Policy. In particular, if you used AI while working on this PR, remember to add a note to the PR description.
The LLVM Code-Review Policy and Practices document contains practical information about the PR process, including how patches are reviewed and accepted, and who can review a PR.
Please reply to this message to confirm that you have read these policies, especially the LLVM AI Tool Use Policy, and that any AI tool usage has been noted in the PR description.
---
Frequently asked questions
How do I add reviewers?
This PR will be automatically labeled, and the relevant teams will be notified. For some parts of the project, reviewers may also be added automatically.
You can also add reviewers manually using the Reviewers section on this page. If you cannot use that section, it is probably because you do not have write permissions for the repository. In that case, you can request a review by tagging reviewers in a comment using @ followed by their GitHub username.
What if there are no comments?
If you have not received any comments on your PR after a week, you can request a review by pinging the PR with a comment such as “Ping”. The common courtesy ping rate is once a week. Please remember that you are asking for volunteer time from other developers.
Are any special GitHub settings required to contribute to LLVM?
We only require contributors to have a public email address associated with their GitHub commits, see this section of LLVM Developer Policy for details.
---
If you have questions, feel free to leave a comment on this PR, or ask on LLVM Discord or LLVM Discourse.
Thank you,
The LLVM Community
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-libcxx
Author: Ilyas Mallah (ilyas-mallah)
<details>
<summary>Changes</summary>
basic_string::resize_and_overwrite(n, op) makes the value r returned by op the new size of the string, and [string.capacity] requires 0 <= r <= n. The only check in libc++ is an internal assertion that r is within capacity(), and it runs only in the debug mode. An operation that writes 4 bytes and returns 40 leaves 36 stale bytes in the string, and no sanitizer reports it. If r is above the capacity, the null terminator is written past the allocation.
This checks both bounds with _LIBCPP_ASSERT_VALID_INPUT_RANGE, the category string_view uses for invalid lengths. The operation can return any integer-like type, so the sign is only checked for signed types and the upper bound is compared in the result's unsigned type. That way a signed char -1 isn't read as 255, and a 128-bit result isn't truncated.
AI usage: Claude Code helped with the test runs and test scaffolding. I traced the issue, made the fix, and validated every change.
---
Full diff: https://github.com/llvm/llvm-project/pull/230605.diff
2 Files Affected:
````````````diff --git a/libcxx/include/string b/libcxx/include/string
index a27f9344916d1b..fcd27483e13964 100644
--- a/libcxx/include/string
+++ b/libcxx/include/string
@@ -639,9 +639,11 @@ basic_string<char32_t> operator""s( const char32_t *str, size_t len );
# include <__type_traits/is_nothrow_constructible.h>
# include <__type_traits/is_relocatable.h>
# include <__type_traits/is_same.h>
+# include <__type_traits/is_signed.h>
# include <__type_traits/is_standard_layout.h>
# include <__type_traits/is_trivially_constructible.h>
# include <__type_traits/is_trivially_copyable.h>
+# include <__type_traits/make_unsigned.h>
# include <__type_traits/remove_cv.h>
# include <__type_traits/remove_cvref.h>
# include <__utility/assume.h>
@@ -1250,7 +1252,15 @@ public:
__annotate_delete();
__set_size(__n);
__annotate_new(__n);
- __erase_to_end(std::move(__op)(data(), auto(__n)));
+ __result_type __r = std::move(__op)(data(), auto(__n));
+ if constexpr (__integer_like<__result_type>) { // Avoid extra errors after a failed static_assert
+ if constexpr (is_signed_v<__result_type>)
+ _LIBCPP_ASSERT_VALID_INPUT_RANGE(
+ __r >= 0, "string::resize_and_overwrite: the operation returned a negative size");
+ _LIBCPP_ASSERT_VALID_INPUT_RANGE(std::__to_unsigned_like(__r) <= __n,
+ "string::resize_and_overwrite: the operation returned a size larger than n");
+ }
+ __erase_to_end(__r);
}
# endif
diff --git a/libcxx/test/libcxx/strings/basic.string/string.capacity/assert.resize_and_overwrite.pass.cpp b/libcxx/test/libcxx/strings/basic.string/string.capacity/assert.resize_and_overwrite.pass.cpp
new file mode 100644
index 00000000000000..35d901f8da3bd0
--- /dev/null
+++ b/libcxx/test/libcxx/strings/basic.string/string.capacity/assert.resize_and_overwrite.pass.cpp
@@ -0,0 +1,71 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <string>
+
+// template<class Operation>
+// constexpr void resize_and_overwrite(size_type n, Operation op); // since C++23
+
+// The result r of the operation must satisfy 0 <= r <= n.
+
+// REQUIRES: std-at-least-c++23
+// REQUIRES: can-test-hardening-assertions-fast
+// Execution would continue into an out-of-bounds write.
+// UNSUPPORTED: libcpp-assertion-semantic={{ignore|observe}}
+
+#include <cstddef>
+#include <string>
+
+#include "check_assertion.h"
+#include "min_allocator.h"
+#include "test_macros.h"
+
+template <class S>
+void test() {
+ {
+ S s;
+ TEST_LIBCPP_ASSERT_FAILURE(s.resize_and_overwrite(5, [](auto*, std::size_t n) { return n + 1; }),
+ "string::resize_and_overwrite: the operation returned a size larger than n");
+ }
+ {
+ S s(40, 'x');
+ TEST_LIBCPP_ASSERT_FAILURE(s.resize_and_overwrite(40, [](auto*, std::size_t n) { return n + 4096; }),
+ "string::resize_and_overwrite: the operation returned a size larger than n");
+ }
+ {
+ S s(40, 'x');
+ TEST_LIBCPP_ASSERT_FAILURE(s.resize_and_overwrite(40, [](auto*, std::size_t) { return -1; }),
+ "string::resize_and_overwrite: the operation returned a negative size");
+ }
+ {
+ // A narrow signed result must not be compared as its unsigned counterpart, where -1 would be 255.
+ S s;
+ TEST_LIBCPP_ASSERT_FAILURE(
+ s.resize_and_overwrite(300, [](auto*, std::size_t) { return static_cast<signed char>(-1); }),
+ "string::resize_and_overwrite: the operation returned a negative size");
+ }
+#ifndef TEST_HAS_NO_INT128
+ {
+ // A wide result must not be truncated to size_type before the comparison, where 2^64 + 1 would be 1.
+ S s;
+ TEST_LIBCPP_ASSERT_FAILURE(
+ s.resize_and_overwrite(5, [](auto*, std::size_t) { return (static_cast<__int128_t>(1) << 64) + 1; }),
+ "string::resize_and_overwrite: the operation returned a size larger than n");
+ }
+#endif
+}
+
+int main(int, char**) {
+ test<std::string>();
+ test<std::basic_string<char, std::char_traits<char>, min_allocator<char> > >();
+#ifndef TEST_HAS_NO_WIDE_CHARACTERS
+ test<std::wstring>();
+#endif
+
+ return 0;
+}
</details>
// REQUIRES: std-at-least-c++23
// REQUIRES: can-test-hardening-assertions-fast
// Execution would continue into an out-of-bounds write.
// UNSUPPORTED: libcpp-assertion-semantic={{ignore|observe}}
// <string>
// template<class Operation>
// constexpr void resize_and_overwrite(size_type n, Operation op); // since C++23
// The result r of the operation must satisfy 0 <= r <= n.
This order is more typical.
Done, thank you!
We don't usually do this, and I don't think we want it here either. I'm also not sure which static_assert you're talking about.
CC @var-const
Removed. The static_assert I meant is this one: https://github.com/llvm/llvm-project/blob/ae751639f3ef54440accf4c6769de630c3ec5931/libcxx/include/string#L1246
@philnik777 I removed the guard in string. Could you take another look?
@philnik777 The CI run is waiting for a maintainer to approve it. One question is left: the check uses the valid-input-range category, as string_view(const char*, size_t) does. Would you rather have valid-element-access?
<!--LLVM CODE FORMAT COMMENT: {clang-format}-->
:white_check_mark: With the latest revision this PR passed the C/C++ code formatter.
@philnik777 Thanks for the 10-13 review and for questioning that guard. It's removed in the current head, https://github.com/llvm/llvm-project/commit/3853b3b240378099ba27cc001df8bb2db97b59be, and CI is green. Could you take another look?
@philnik777 @frederick-vs-ja This is two assertions in resize_and_overwrite, with tests. The one open choice is the category. I used valid-input-range, as string_view does for a length that's too large. Is that the right one, and if so, could one of you approve it?
test<std::wstring>();
test<std::basic_string<wchar_t, std::char_traits<wchar_t>, min_allocator<wchar_t> > >();
Why not perform consistent checks?
(I _guess_ it would more conventional to test charN_t together, but that won't bring much value.)
Maybe it's better to test _BitInt together. But I'm not sure whether this will make much sense.
I don't exactly know what does this comment say. Also, it's better to group lit comments together.
if constexpr (__integer_like<__result_type>) {
_LIBCPP_ASSERT_VALID_INPUT_RANGE(
__r >= 0, "string::resize_and_overwrite: the operation returned a negative size");
_LIBCPP_ASSERT_VALID_INPUT_RANGE(std::__to_unsigned_like(__r) <= __n,
"string::resize_and_overwrite: the operation returned a size larger than n");
}
This will make the error messages cleaner and avoid modifying resize_and_overwrite.verify.cpp.
Edit: It might be better to make the if constexpr guard the function body after the first static_assert, if we want it.
I took the guard out because philnik777 asked for that in his October 13 review. Without it, the verify test needs six extra lines for the additional diagnostics of a call that's already rejected. I can put it back if philnik777 agrees.
I tried it and the checks already handle _BitInt. -1 as _BitInt(8) trips the negative size check, and _BitInt(80) and unsigned _BitInt(7) results above n trip the other one. It would repeat the signed char and __int128 cases, so I left it out. I can add it behind TEST_HAS_BITINT if you'd like it in.
Zingam
ilyas-mallah
basic_string::resize_and_overwrite(n, op)makes the valuerreturned byopthe new size of the string, and [string.capacity] requires0 <= r <= n. The only check in libc++ is an internal assertion thatris withincapacity(), and it runs only in the debug mode. An operation that writes 4 bytes and returns 40 leaves 36 stale bytes in the string, and no sanitizer reports it. Ifris above the capacity, the null terminator is written past the allocation.This checks both bounds with
_LIBCPP_ASSERT_VALID_INPUT_RANGE, the categorystring_viewuses for invalid lengths. The operation can return any integer-like type, so the upper bound is compared in the result's unsigned type after the sign check. That way asigned char-1 isn't read as 255, and a 128-bit result isn't truncated.AI usage: Claude Code helped with the test runs and test scaffolding. I traced the issue, made the fix, and validated every change.