← Back to Pull requests

[libc++] Assert that the position passed to insert and emplace is in [begin(), end()] #230490

Open
ilyas-mallah opened this pull request with 442 lines diff across 8 files
View on GitHub
ilyas-mallah ilyas-mallah commented on Oct 09, 2026 13:10 UTC
Author

vector, vector<bool>, basic_string and deque turn the position passed to insert and emplace into an offset from begin() and write there without checking it. An iterator into another container, or one left dangling by a reallocation or a pop_back, becomes an out-of-bounds write, even in the fast and extensive hardening modes, which already catch erase(end()) and an out-of-range operator[].

This asserts the position at the start of every insert and emplace path in those containers, as _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS. It costs a few pointer compares, and with hardening disabled the generated code doesn't change.

Each container gets an assert.insert.invalid_position.pass.cpp that calls every insert and emplace overload with a foreign iterator and with iterators invalidated by a reallocation or a pop. string::insert(const_iterator, char) is instantiated in the dylib, so the string test is XFAIL'd against older dylibs.

erase is left alone, since #90919 covers it for vector and string and #116213 tracks it.

AI usage: Claude Code helped with the test runs and test scaffolding. I traced the issue, made the fix, and validated every change.

Diff: 442 lines (+442 / -0) across 8 files Reviewer: frederick-vs-ja Review duration: 80995m
All Vouch review confidence checks passed
Residual risk 0.06 = Change Risk (0.57) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.57 · 442 lines diff across 8 files
0.57
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.91 · 5 substantive comment(s)
0.91
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
89%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.365
Real PR Conversation Timeline
19 items
github-actions[bot] github-actions[bot] commented on Oct 09, 2026 13:11 UTC
Bot

<!--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.

  • Our LLVM Developer Policy describes our expectations for code quality, commit summaries and contains notes on our CI system.
  • 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

    llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Oct 09, 2026 13:11 UTC
    Bot

    <!--LLVM PR SUMMARY COMMENT-->

    @llvm/pr-subscribers-libcxx

    Author: Ilyas Mallah (ilyas-mallah)

    <details>
    <summary>Changes</summary>

    vector, vector&lt;bool&gt;, basic_string and deque turn the position passed to insert and emplace into an offset from begin() and write there without checking it. An iterator into another container, or one left dangling by a reallocation or a pop_back, becomes an out-of-bounds write, even in the fast and extensive hardening modes, which already catch erase(end()) and an out-of-range operator[].

    This asserts the position at the start of every insert and emplace path in those containers, as _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS. It costs two pointer or iterator compares, and with hardening disabled the generated code doesn't change.

    Each container gets an assert.insert.invalid_position.pass.cpp that calls every insert and emplace overload with a foreign iterator and with iterators invalidated by a reallocation or a pop. string::insert(const_iterator, char) is instantiated in the dylib, so the string test is XFAIL'd against older dylibs.

    erase is left alone, since #<!-- -->90919 covers it for vector and string and #<!-- -->116213 tracks it.

    AI usage: Claude Code helped with the test runs and test scaffolding. I traced the issue, made the fix, and validated every change.

    ---

    Patch is 24.05 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/230490.diff

    8 Files Affected:

  • (modified) libcxx/include/__vector/vector.h (+15)

  • (modified) libcxx/include/__vector/vector_bool.h (+13)

  • (modified) libcxx/include/deque (+10)

  • (modified) libcxx/include/string (+10)

  • (added) libcxx/test/libcxx/containers/sequences/deque/assert.insert.invalid_position.pass.cpp (+82)

  • (added) libcxx/test/libcxx/containers/sequences/vector.bool/assert.insert.invalid_position.pass.cpp (+82)

  • (added) libcxx/test/libcxx/containers/sequences/vector/assert.insert.invalid_position.pass.cpp (+82)

  • (added) libcxx/test/libcxx/strings/basic.string/string.modifiers/assert.insert.invalid_position.pass.cpp (+86)
  • ``````

    diff --git a/libcxx/include/__vector/vector.h b/libcxx/include/__vector/vector.h
    index aa8441e3f95544..92c559d49747d0 100644
    --- a/libcxx/include/__vector/vector.h
    +++ b/libcxx/include/__vector/vector.h
    @@ -766,6 +766,13 @@ class _LIBCPP_WARN_UNUSED vector {
     #endif // _LIBCPP_ABI_BOUNDED_ITERATORS_IN_VECTOR
       }
     
    +  _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI bool
    +  __is_valid_insert_position(const_iterator __position) const _NOEXCEPT {
    +    auto __pos = std::__to_address(__position);
    +    auto __end = std::__to_address(__layout_.__end_ptr());
    +    return std::__is_pointer_in_range(std::__to_address(__layout_.__begin_ptr()), __end, __pos) || __pos == __end;
    +  }
    +
       _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI void
       __move_range(pointer __from_s, pointer __from_e, pointer __to);
     
    @@ -1110,6 +1117,8 @@ template <class _Tp, class _Allocator>
     template <class... _Args>
     _LIBCPP_CONSTEXPR_SINCE_CXX20 typename vector<_Tp, _Allocator>::iterator
     vector<_Tp, _Allocator>::emplace(const_iterator __position, _Args&&... __args) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__is_valid_insert_position(__position),
    +                                      "vector::insert/emplace called with an iterator outside [begin(), end()]");
       pointer __p = this->__layout_.__begin_ptr() + (__position - begin());
       if (size() != capacity()) {
         pointer __end = __layout_.__end_ptr();
    @@ -1131,6 +1140,8 @@ vector<_Tp, _Allocator>::emplace(const_iterator __position, _Args&&... __args) {
     template <class _Tp, class _Allocator>
     _LIBCPP_CONSTEXPR_SINCE_CXX20 typename vector<_Tp, _Allocator>::iterator
     vector<_Tp, _Allocator>::insert(const_iterator __position, size_type __n, const_reference __x) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__is_valid_insert_position(__position),
    +                                      "vector::insert/emplace called with an iterator outside [begin(), end()]");
       pointer __p = this->__layout_.__begin_ptr() + (__position - begin());
       if (__n > 0) {
         if (__n <= __layout_.__remaining_capacity()) {
    @@ -1162,6 +1173,8 @@ template <class _Tp, class _Allocator>
     template <class _InputIterator, class _Sentinel>
     _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI typename vector<_Tp, _Allocator>::iterator
     vector<_Tp, _Allocator>::__insert_with_sentinel(const_iterator __position, _InputIterator __first, _Sentinel __last) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__is_valid_insert_position(__position),
    +                                      "vector::insert/emplace called with an iterator outside [begin(), end()]");
       difference_type __off = __position - begin();
       pointer __p           = this->__layout_.__begin_ptr() + __off;
       pointer __old_last    = __layout_.__end_ptr();
    @@ -1203,6 +1216,8 @@ template <class _Tp, class _Allocator>
     template <class _AlgPolicy, class _Iterator>
     _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI typename vector<_Tp, _Allocator>::iterator
     vector<_Tp, _Allocator>::__insert_with_size(const_iterator __position, _Iterator __first, difference_type __n) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__is_valid_insert_position(__position),
    +                                      "vector::insert/emplace called with an iterator outside [begin(), end()]");
       pointer __p = this->__layout_.__begin_ptr() + (__position - begin());
       if (__n > 0) {
         if (__n <= static_cast<difference_type>(__layout_.__remaining_capacity())) {
    diff --git a/libcxx/include/__vector/vector_bool.h b/libcxx/include/__vector/vector_bool.h
    index 12938a90be3aa5..c6f306cdce8a9c 100644
    --- a/libcxx/include/__vector/vector_bool.h
    +++ b/libcxx/include/__vector/vector_bool.h
    @@ -453,6 +453,11 @@ class _LIBCPP_WARN_UNUSED vector<bool, _Allocator> {
       _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI iterator
       __insert_with_size(const_iterator __position, _Iterator __first, _Sentinel __last, difference_type __n);
     
    +  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 bool
    +  __is_valid_insert_position(const_iterator __position) const _NOEXCEPT {
    +    return begin() <= __position && __position <= end();
    +  }
    +
       //  Allocate space for __n objects
       //  throws length_error if __n > max_size()
       //  throws (probably bad_alloc) if memory run out
    @@ -895,6 +900,8 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 void vector<bool, _Allocator>::push_back(const val
     template <class _Allocator>
     _LIBCPP_CONSTEXPR_SINCE_CXX20 typename vector<bool, _Allocator>::iterator
     vector<bool, _Allocator>::insert(const_iterator __position, const value_type& __x) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__is_valid_insert_position(__position),
    +                                      "vector<bool>::insert/emplace called with an iterator outside [begin(), end()]");
       iterator __r;
       if (size() < capacity()) {
         const_iterator __old_end = end();
    @@ -916,6 +923,8 @@ vector<bool, _Allocator>::insert(const_iterator __position, const value_type& __
     template <class _Allocator>
     _LIBCPP_CONSTEXPR_SINCE_CXX20 typename vector<bool, _Allocator>::iterator
     vector<bool, _Allocator>::insert(const_iterator __position, size_type __n, const value_type& __x) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__is_valid_insert_position(__position),
    +                                      "vector<bool>::insert/emplace called with an iterator outside [begin(), end()]");
       iterator __r;
       size_type __c = capacity();
       if (__n <= __c && size() <= __c - __n) {
    @@ -946,6 +955,8 @@ template <class _Allocator>
     template <class _InputIterator, class _Sentinel>
     _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI typename vector<bool, _Allocator>::iterator
     vector<bool, _Allocator>::__insert_with_sentinel(const_iterator __position, _InputIterator __first, _Sentinel __last) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__is_valid_insert_position(__position),
    +                                      "vector<bool>::insert/emplace called with an iterator outside [begin(), end()]");
       difference_type __off = __position - begin();
       iterator __p          = __const_iterator_cast(__position);
       iterator __old_end    = end();
    @@ -981,6 +992,8 @@ template <class _Iterator, class _Sentinel>
     _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI typename vector<bool, _Allocator>::iterator
     vector<bool, _Allocator>::__insert_with_size(
         const_iterator __position, _Iterator __first, _Sentinel __last, difference_type __n_signed) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__is_valid_insert_position(__position),
    +                                      "vector<bool>::insert/emplace called with an iterator outside [begin(), end()]");
       _LIBCPP_ASSERT_VALID_INPUT_RANGE(__n_signed >= 0, "invalid range specified");
       const size_type __n = static_cast<size_type>(__n_signed);
       iterator __r;
    diff --git a/libcxx/include/deque b/libcxx/include/deque
    index ba4d00f81e95e7..c790986537969c 100644
    --- a/libcxx/include/deque
    +++ b/libcxx/include/deque
    @@ -1243,6 +1243,10 @@ private:
       template <class _BiIter>
       _LIBCPP_HIDE_FROM_ABI iterator __insert_bidirectional(const_iterator __p, _BiIter __f, _BiIter __l, size_type __n);
     
    +  _LIBCPP_HIDE_FROM_ABI bool __is_valid_insert_position(const_iterator __p) const {
    +    return begin() <= __p && __p <= end();
    +  }
    +
       template <class _InpIter, __enable_if_t<__has_exactly_input_iterator_category<_InpIter>::value, int> = 0>
       _LIBCPP_HIDE_FROM_ABI void __append(_InpIter __f, _InpIter __l);
       template <class _ForIter, __enable_if_t<__has_forward_iterator_category<_ForIter>::value, int> = 0>
    @@ -1683,6 +1687,8 @@ deque<_Tp, _Allocator>::emplace_front(_Args&&... __args) {
     template <class _Tp, class _Allocator>
     template <class... _Args>
     typename deque<_Tp, _Allocator>::iterator deque<_Tp, _Allocator>::__emplace(const_iterator __p, _Args&&... __args) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
    +      __is_valid_insert_position(__p), "deque::insert/emplace called with an iterator outside [begin(), end()]");
       size_type __pos     = __p - begin();
       size_type __to_end  = size() - __pos;
       allocator_type& __a = __alloc();
    @@ -1732,6 +1738,8 @@ typename deque<_Tp, _Allocator>::iterator deque<_Tp, _Allocator>::__emplace(cons
     template <class _Tp, class _Allocator>
     typename deque<_Tp, _Allocator>::iterator
     deque<_Tp, _Allocator>::insert(const_iterator __p, size_type __n, const value_type& __v) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
    +      __is_valid_insert_position(__p), "deque::insert/emplace called with an iterator outside [begin(), end()]");
       size_type __pos     = __p - begin();
       size_type __to_end  = __size() - __pos;
       allocator_type& __a = __alloc();
    @@ -1832,6 +1840,8 @@ template <class _Tp, class _Allocator>
     template <class _BiIter>
     _LIBCPP_HIDE_FROM_ABI typename deque<_Tp, _Allocator>::iterator
     deque<_Tp, _Allocator>::__insert_bidirectional(const_iterator __p, _BiIter __f, _BiIter __l, size_type __n) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
    +      __is_valid_insert_position(__p), "deque::insert/emplace called with an iterator outside [begin(), end()]");
       size_type __pos     = __p - begin();
       size_type __to_end  = size() - __pos;
       allocator_type& __a = __alloc();
    diff --git a/libcxx/include/string b/libcxx/include/string
    index a27f9344916d1b..6b73cf109def35 100644
    --- a/libcxx/include/string
    +++ b/libcxx/include/string
    @@ -1567,6 +1567,8 @@ public:
     
       _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 iterator
       insert(const_iterator __pos, size_type __n, value_type __c) {
    +    _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
    +        __is_valid_insert_position(__pos), "string::insert called with an iterator outside [begin(), end()]");
         difference_type __p = __pos - begin();
         insert(static_cast<size_type>(__p), __n, __c);
         return begin() + __p;
    @@ -2477,6 +2479,10 @@ private:
         return std::__is_pointer_in_range(data(), data() + size() + 1, std::addressof(__v));
       }
     
    +  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 bool __is_valid_insert_position(const_iterator __pos) const {
    +    return std::__is_pointer_in_range(data(), data() + size() + 1, std::__to_address(__pos));
    +  }
    +
       [[__noreturn__]] _LIBCPP_HIDE_FROM_ABI static void __throw_length_error() {
         std::__throw_length_error("basic_string");
       }
    @@ -3144,6 +3150,8 @@ template <class _Iterator, class _Sentinel>
     _LIBCPP_CONSTEXPR_SINCE_CXX20 typename basic_string<_CharT, _Traits, _Allocator>::iterator
     basic_string<_CharT, _Traits, _Allocator>::__insert_with_size(
         const_iterator __pos, _Iterator __first, _Sentinel __last, size_type __n) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
    +      __is_valid_insert_position(__pos), "string::insert called with an iterator outside [begin(), end()]");
       size_type __ip = static_cast<size_type>(__pos - begin());
       if (__n == 0)
         return begin() + __ip;
    @@ -3176,6 +3184,8 @@ basic_string<_CharT, _Traits, _Allocator>::insert(size_type __pos, const value_t
     template <class _CharT, class _Traits, class _Allocator>
     _LIBCPP_CONSTEXPR_SINCE_CXX20 typename basic_string<_CharT, _Traits, _Allocator>::iterator
     basic_string<_CharT, _Traits, _Allocator>::insert(const_iterator __pos, value_type __c) {
    +  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
    +      __is_valid_insert_position(__pos), "string::insert called with an iterator outside [begin(), end()]");
       size_type __ip  = static_cast<size_type>(__pos - begin());
       size_type __sz  = size();
       size_type __cap = capacity();
    diff --git a/libcxx/test/libcxx/containers/sequences/deque/assert.insert.invalid_position.pass.cpp b/libcxx/test/libcxx/containers/sequences/deque/assert.insert.invalid_position.pass.cpp
    new file mode 100644
    index 00000000000000..c40ddb5c54600c
    --- /dev/null
    +++ b/libcxx/test/libcxx/containers/sequences/deque/assert.insert.invalid_position.pass.cpp
    @@ -0,0 +1,82 @@
    +//===----------------------------------------------------------------------===//
    +//
    +// 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
    +//
    +//===----------------------------------------------------------------------===//
    +
    +// <deque>
    +
    +// Make sure insert and emplace catch a position that isn't in [begin(), end()], such as an iterator
    +// into another deque or an iterator to an element that was removed.
    +
    +// REQUIRES: can-test-hardening-assertions-fast
    +// UNSUPPORTED: libcpp-assertion-semantic={{ignore|observe}}
    +
    +#include <deque>
    +#include <vector>
    +
    +#include "check_assertion.h"
    +#include "min_allocator.h"
    +#include "test_iterators.h"
    +#include "test_macros.h"
    +
    +template <class Deque>
    +void test_invalid_position(Deque& d, typename Deque::const_iterator pos) {
    +  [[maybe_unused]] const char* message = "deque::insert/emplace called with an iterator outside [begin(), end()]";
    +  int a[]                              = {1, 2, 3};
    +  const int x                          = 4;
    +  TEST_LIBCPP_ASSERT_FAILURE(d.insert(pos, x), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(d.insert(pos, 4), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(d.insert(pos, 2, x), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(d.insert(pos, a, a + 3), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(d.insert(pos, forward_iterator<int*>(a), forward_iterator<int*>(a + 3)), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(d.insert(pos, cpp17_input_iterator<int*>(a), cpp17_input_iterator<int*>(a + 3)), message);
    +  TEST_LIBCPP_ASSERT_FAILURE((d.insert(pos, {1, 2, 3})), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(d.emplace(pos, 4), message);
    +#if TEST_STD_VER >= 23
    +  TEST_LIBCPP_ASSERT_FAILURE((d.insert_range(pos, std::vector<int>{1, 2, 3})), message);
    +#endif
    +}
    +
    +template <class Deque>
    +void test() {
    +  // An iterator into another deque.
    +  {
    +    Deque d     = {1, 2, 3};
    +    Deque other = {4, 5, 6};
    +    test_invalid_position(d, other.begin());
    +    test_invalid_position(d, other.end());
    +  }
    +
    +  // An iterator into another deque, inserting into an empty one.
    +  {
    +    Deque d;
    +    Deque other = {4, 5, 6};
    +    test_invalid_position(d, other.begin());
    +  }
    +
    +  // An iterator to an element removed by pop_front().
    +  {
    +    Deque d                              = {1, 2, 3};
    +    typename Deque::const_iterator stale = d.begin();
    +    d.pop_front();
    +    test_invalid_position(d, stale);
    +  }
    +
    +  // An iterator past end() after pop_back().
    +  {
    +    Deque d                              = {1, 2, 3};
    +    typename Deque::const_iterator stale = d.end();
    +    d.pop_back();
    +    test_invalid_position(d, stale);
    +  }
    +}
    +
    +int main(int, char**) {
    +  test<std::deque<int> >();
    +  test<std::deque<int, min_allocator<int> > >();
    +
    +  return 0;
    +}
    diff --git a/libcxx/test/libcxx/containers/sequences/vector.bool/assert.insert.invalid_position.pass.cpp b/libcxx/test/libcxx/containers/sequences/vector.bool/assert.insert.invalid_position.pass.cpp
    new file mode 100644
    index 00000000000000..e50a868c97267b
    --- /dev/null
    +++ b/libcxx/test/libcxx/containers/sequences/vector.bool/assert.insert.invalid_position.pass.cpp
    @@ -0,0 +1,82 @@
    +//===----------------------------------------------------------------------===//
    +//
    +// 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
    +//
    +//===----------------------------------------------------------------------===//
    +
    +// <vector>
    +
    +// Make sure vector<bool>::insert and emplace catch a position that isn't in [begin(), end()], such as
    +// an iterator into another vector or an iterator invalidated by a reallocation.
    +
    +// REQUIRES: can-test-hardening-assertions-fast
    +// UNSUPPORTED: libcpp-assertion-semantic={{ignore|observe}}
    +
    +#include <vector>
    +
    +#include "check_assertion.h"
    +#include "min_allocator.h"
    +#include "test_iterators.h"
    +#include "test_macros.h"
    +
    +template <class Vector>
    +void test_invalid_position(Vector& v, typename Vector::const_iterator pos) {
    +  [[maybe_unused]] const char* message =
    +      "vector<bool>::insert/emplace called with an iterator outside [begin(), end()]";
    +  bool a[]     = {true, false, true};
    +  const bool x = true;
    +  TEST_LIBCPP_ASSERT_FAILURE(v.insert(pos, x), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(v.insert(pos, 2, x), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(v.insert(pos, a, a + 3), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(v.insert(pos, forward_iterator<bool*>(a), forward_iterator<bool*>(a + 3)), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(
    +      v.insert(pos, cpp17_input_iterator<bool*>(a), cpp17_input_iterator<bool*>(a + 3)), message);
    +  TEST_LIBCPP_ASSERT_FAILURE((v.insert(pos, {true, false, true})), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(v.emplace(pos, true), message);
    +#if TEST_STD_VER >= 23
    +  TEST_LIBCPP_ASSERT_FAILURE((v.insert_range(pos, std::vector<bool>{true, false, true})), message);
    +#endif
    +}
    +
    +template <class Vector>
    +void test() {
    +  // An iterator into another vector.
    +  {
    +    Vector v     = {true, false, true};
    +    Vector other = {false, true, false};
    +    test_invalid_position(v, other.begin());
    +    test_invalid_position(v, other.end());
    +  }
    +
    +  // An iterator into another vector, inserting into an empty one.
    +  {
    +    Vector v;
    +    Vector other = {false, true, false};
    +    test_invalid_position(v, other.begin());
    +  }
    +
    +  // An iterator invalidated by a reallocation.
    +  {
    +    Vector v                              = {true, false, true};
    +    typename Vector::const_iterator stale = v.begin();
    +    v.reserve(v.capacity() + 1);
    +    test_invalid_position(v, stale);
    +  }
    +
    +  // An iterator past end() that is still inside the allocation.
    +  {
    +    Vector v                              = {true, false, true};
    +    typename Vector::const_iterator stale = v.end();
    +    v.pop_back();
    +    test_invalid_position(v, stale);
    +  }
    +}
    +
    +int main(int, char**) {
    +  test<std::vector<bool> >();
    +  test<std::vector<bool, min_allocator<bool> > >();
    +
    +  return 0;
    +}
    diff --git a/libcxx/test/libcxx/containers/sequences/vector/assert.insert.invalid_position.pass.cpp b/libcxx/test/libcxx/containers/sequences/vector/assert.insert.invalid_position.pass.cpp
    new file mode 100644
    index 00000000000000..c9c8a6b41d6bcf
    --- /dev/null
    +++ b/libcxx/test/libcxx/containers/sequences/vector/assert.insert.invalid_position.pass.cpp
    @@ -0,0 +1,82 @@
    +//===----------------------------------------------------------------------===//
    +//
    +// 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
    +//
    +//===----------------------------------------------------------------------===//
    +
    +// <vector>
    +
    +// Make sure insert and emplace catch a position that isn't in [begin(), end()], such as an iterator
    +// into another vector or an iterator invalidated by a reallocation.
    +
    +// REQUIRES: can-test-hardening-assertions-fast
    +// UNSUPPORTED: libcpp-assertion-semantic={{ignore|observe}}
    +
    +#include <vector>
    +
    +#include "check_assertion.h"
    +#include "min_allocator.h"
    +#include "test_iterators.h"
    +#include "test_macros.h"
    +
    +template <class Vector>
    +void test_invalid_position(Vector& v, typename Vector::const_iterator pos) {
    +  [[maybe_unused]] const char* message = "vector::insert/emplace called with an iterator outside [begin(), end()]";
    +  int a[]                              = {1, 2, 3};
    +  const int x                          = 4;
    +  TEST_LIBCPP_ASSERT_FAILURE(v.insert(pos, x), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(v.insert(pos, 4), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(v.insert(pos, 2, x), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(v.insert(pos, a, a + 3), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(v.insert(pos, forward_iterator<int*>(a), forward_iterator<int*>(a + 3)), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(v.insert(pos, cpp17_input_iterator<int*>(a), cpp17_input_iterator<int*>(a + 3)), message);
    +  TEST_LIBCPP_ASSERT_FAILURE((v.insert(pos, {1, 2, 3})), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(v.emplace(pos, 4), message);
    +#if TEST_STD_VER >= 23
    +  TEST_LIBCPP_ASSERT_FAILURE((v.insert_range(pos, std::vector<int>{1, 2, 3})), message);
    +#endif
    +}
    +
    +template <class Vector>
    +void test() {
    +  // An iterator into another vector.
    +  {
    +    Vector v     = {1, 2, 3};
    +    Vector other = {4, 5, 6};
    +    test_invalid_position(v, other.begin());
    +    test_invalid_position(v, other.end());
    +  }
    +
    +  // An iterator into another vector, inserting into an empty one.
    +  {
    +    Vector v;
    +    V...
    [truncated]
    
    
    ``````

    </details>

    ilyas-mallah ilyas-mallah commented on Oct 09, 2026 19:42 UTC
    Author

    The Windows clang-cl job failed before building anything: Chocolatey returned a 503 while installing LLVM (log). I've since pushed a commit that moves the lit lines to the top of the new tests, the order Zingam asked for on #230605, and as a first-time contributor its CI is waiting for approval. Could someone approve the run?

    frederick-vs-ja frederick-vs-ja commented on code on Oct 13, 2026 03:48 UTC
    Code Review
    libcxx/include/__vector/vector_bool.h:1
    @@ -453,6 +453,11 @@ class _LIBCPP_WARN_UNUSED vector<bool, _Allocator> {
       _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI iterator
       __insert_with_size(const_iterator __position, _Iterator __first, _Sentinel __last, difference_type __n);
     
    +  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 bool
    +  __is_valid_insert_position(const_iterator __position) const _NOEXCEPT {
    +    return begin() <= __position && __position <= end();

    Can we transform this into something using __is_pointer_in_range?

    frederick-vs-ja frederick-vs-ja commented on code on Oct 13, 2026 03:53 UTC
    Code Review
    libcxx/include/deque:1
    @@ -1243,6 +1243,10 @@ private:
       template <class _BiIter>
       _LIBCPP_HIDE_FROM_ABI iterator __insert_bidirectional(const_iterator __p, _BiIter __f, _BiIter __l, size_type __n);
     
    +  _LIBCPP_HIDE_FROM_ABI bool __is_valid_insert_position(const_iterator __p) const {
    +    return begin() <= __p && __p <= end();

    I guess we should inspect the iterator's __m_iter_ member here. I'm a bit afraid that when __p points into another deque, the relation operators don't always work well.

    ilyas-mallah ilyas-mallah commented on code on Oct 13, 2026 10:21 UTC
    Code Review
    libcxx/include/__vector/vector_bool.h:1
    @@ -453,6 +453,11 @@ class _LIBCPP_WARN_UNUSED vector<bool, _Allocator> {
       _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI iterator
       __insert_with_size(const_iterator __position, _Iterator __first, _Sentinel __last, difference_type __n);
     
    +  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 bool
    +  __is_valid_insert_position(const_iterator __position) const _NOEXCEPT {
    +    return begin() <= __position && __position <= end();

    Done in 862260a705. In constant evaluation a position from another vector now reaches the assertion, where it used to stop on clang's unrelated-objects note. I added a test for a full vector and a constexpr check that every valid position is accepted.

    ilyas-mallah ilyas-mallah commented on code on Oct 13, 2026 10:22 UTC
    Code Review
    libcxx/include/deque:1
    @@ -1243,6 +1243,10 @@ private:
       template <class _BiIter>
       _LIBCPP_HIDE_FROM_ABI iterator __insert_bidirectional(const_iterator __p, _BiIter __f, _BiIter __l, size_type __n);
     
    +  _LIBCPP_HIDE_FROM_ABI bool __is_valid_insert_position(const_iterator __p) const {
    +    return begin() <= __p && __p <= end();

    Done in c5af97ea9d. I didn't see the old <= misfire, and the change only stops relying on how iterators from different deques compare. The same check would let deque::erase verify the iterator belongs to the deque, which #90919 leaves out, and I can do that in a separate PR if it's useful.

    ilyas-mallah ilyas-mallah commented on Oct 19, 2026 22:01 UTC
    Author

    @frederick-vs-ja I addressed your comments. @philnik777 could you take a look?

    ilyas-mallah ilyas-mallah commented on Oct 28, 2026 16:55 UTC
    Author

    @philnik777 @frederick-vs-ja The CI run is waiting for a maintainer to approve it. frederick-vs-ja's two comments are addressed, the vector<bool> position now goes through __is_pointer_in_range. Is anything else needed before this can go in?

    ilyas-mallah ilyas-mallah commented on Nov 04, 2026 09:29 UTC
    Author

    @frederick-vs-ja @ldionne I merged main, and the full CI has run on the current head. It's green. frederick-vs-ja, both points from your 10-13 review are in: vector<bool> uses __is_pointer_in_range, and deque compares __m_iter_. ldionne, could you look at the vector and string parts? Each check is two compares at the top of an insert path.

    frederick-vs-ja frederick-vs-ja commented on code on Nov 26, 2026 12:48 UTC
    Code Review
    libcxx/test/libcxx/containers/sequences/deque/assert.insert.invalid_position.pass.cpp:1
    @@ -0,0 +1,100 @@
    +//===----------------------------------------------------------------------===//
    +//
    +// 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
    +//
    +//===----------------------------------------------------------------------===//
    +
    +// REQUIRES: can-test-hardening-assertions-fast
    +// UNSUPPORTED: libcpp-assertion-semantic={{ignore|observe}}
    +
    +// <deque>
    +
    +// Make sure insert and emplace catch a position that isn't in [begin(), end()], such as an iterator
    +// into another deque or an iterator to an element that was removed.
    +
    +#include <deque>
    +#include <vector>

    It seems that we don't need to use vector and we can just insert an build-in array instead to verify insert_range.

    frederick-vs-ja frederick-vs-ja commented on code on Nov 26, 2026 12:54 UTC
    Code Review
    libcxx/test/libcxx/strings/basic.string/string.modifiers/assert.insert.invalid_position.pass.cpp:1
    @@ -0,0 +1,86 @@
    +//===----------------------------------------------------------------------===//
    +//
    +// 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
    +//
    +//===----------------------------------------------------------------------===//
    +
    +// REQUIRES: can-test-hardening-assertions-fast
    +// UNSUPPORTED: libcpp-assertion-semantic={{ignore|observe}}
    +
    +// std::string::insert(const_iterator, char) is instantiated in the dylib, so we need an up-to-date one
    +// XFAIL: using-built-library-before-llvm-24
    +
    +// <string>
    +
    +// Make sure insert catches a position that isn't in [begin(), end()], such as an iterator into
    +// another string or an iterator invalidated by a reallocation.
    +
    +#include <string>
    +
    +#include "check_assertion.h"
    +#include "min_allocator.h"
    +#include "test_iterators.h"
    +#include "test_macros.h"
    +
    +#if TEST_STD_VER >= 23
    +#  include <string_view>
    +#endif

    Let's unconditionally verify insertion of basic_string_view.

    #include <string>
    #include <string_view>
    
    #include "check_assertion.h"
    #include "min_allocator.h"
    #include "test_iterators.h"
    #include "test_macros.h"
    

    frederick-vs-ja frederick-vs-ja commented on code on Nov 26, 2026 12:56 UTC
    Code Review
    libcxx/test/libcxx/strings/basic.string/string.modifiers/assert.insert.invalid_position.pass.cpp:1
    @@ -0,0 +1,86 @@
    +//===----------------------------------------------------------------------===//
    +//
    +// 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
    +//
    +//===----------------------------------------------------------------------===//
    +
    +// REQUIRES: can-test-hardening-assertions-fast
    +// UNSUPPORTED: libcpp-assertion-semantic={{ignore|observe}}
    +
    +// std::string::insert(const_iterator, char) is instantiated in the dylib, so we need an up-to-date one
    +// XFAIL: using-built-library-before-llvm-24
    +
    +// <string>
    +
    +// Make sure insert catches a position that isn't in [begin(), end()], such as an iterator into
    +// another string or an iterator invalidated by a reallocation.
    +
    +#include <string>
    +
    +#include "check_assertion.h"
    +#include "min_allocator.h"
    +#include "test_iterators.h"
    +#include "test_macros.h"
    +
    +#if TEST_STD_VER >= 23
    +#  include <string_view>
    +#endif
    +
    +template <class String>
    +void test_invalid_position(String& s, typename String::const_iterator pos) {
    +  [[maybe_unused]] const char* message = "string::insert called with an iterator outside [begin(), end()]";
    +  const char a[]                       = "abc";
    +  TEST_LIBCPP_ASSERT_FAILURE(s.insert(pos, 'x'), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(s.insert(pos, 2, 'x'), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(s.insert(pos, a, a + 3), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(
    +      s.insert(pos, forward_iterator<const char*>(a), forward_iterator<const char*>(a + 3)), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(
    +      s.insert(pos, cpp17_input_iterator<const char*>(a), cpp17_input_iterator<const char*>(a + 3)), message);
    +  TEST_LIBCPP_ASSERT_FAILURE((s.insert(pos, {'a', 'b', 'c'})), message);
    +#if TEST_STD_VER >= 23
    +  TEST_LIBCPP_ASSERT_FAILURE(s.insert_range(pos, std::string_view("abc")), message);
    +#endif

    It would be better to test all insert overloads. Also, we should test string_view in old modes because libc++ backports it to C++03.

    frederick-vs-ja frederick-vs-ja commented on Nov 26, 2026 12:58 UTC
    Reviewer

    ldionne, could you look at the vector and string parts?

    These parts are correct to me (somehow obviously). But I'd wait @ldionne for the final approval.

    Also, it seems that we should improve the tests.

    ilyas-mallah ilyas-mallah commented on code on Nov 26, 2026 14:10 UTC
    Code Review
    libcxx/test/libcxx/strings/basic.string/string.modifiers/assert.insert.invalid_position.pass.cpp:1
    @@ -0,0 +1,86 @@
    +//===----------------------------------------------------------------------===//
    +//
    +// 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
    +//
    +//===----------------------------------------------------------------------===//
    +
    +// REQUIRES: can-test-hardening-assertions-fast
    +// UNSUPPORTED: libcpp-assertion-semantic={{ignore|observe}}
    +
    +// std::string::insert(const_iterator, char) is instantiated in the dylib, so we need an up-to-date one
    +// XFAIL: using-built-library-before-llvm-24
    +
    +// <string>
    +
    +// Make sure insert catches a position that isn't in [begin(), end()], such as an iterator into
    +// another string or an iterator invalidated by a reallocation.
    +
    +#include <string>
    +
    +#include "check_assertion.h"
    +#include "min_allocator.h"
    +#include "test_iterators.h"
    +#include "test_macros.h"
    +
    +#if TEST_STD_VER >= 23
    +#  include <string_view>
    +#endif
    +
    +template <class String>
    +void test_invalid_position(String& s, typename String::const_iterator pos) {
    +  [[maybe_unused]] const char* message = "string::insert called with an iterator outside [begin(), end()]";
    +  const char a[]                       = "abc";
    +  TEST_LIBCPP_ASSERT_FAILURE(s.insert(pos, 'x'), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(s.insert(pos, 2, 'x'), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(s.insert(pos, a, a + 3), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(
    +      s.insert(pos, forward_iterator<const char*>(a), forward_iterator<const char*>(a + 3)), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(
    +      s.insert(pos, cpp17_input_iterator<const char*>(a), cpp17_input_iterator<const char*>(a + 3)), message);
    +  TEST_LIBCPP_ASSERT_FAILURE((s.insert(pos, {'a', 'b', 'c'})), message);
    +#if TEST_STD_VER >= 23
    +  TEST_LIBCPP_ASSERT_FAILURE(s.insert_range(pos, std::string_view("abc")), message);
    +#endif

    The test already calls every insert overload that takes an iterator. The ones taking an index throw out_of_range and never reach the assertion.

    string_view is now tested from C++11 on in https://github.com/llvm/llvm-project/commit/f245ab72bb5cef7f42e453dd899165314460cbe8. Not in C++03 though, because can-test-hardening-assertions excludes it and check_assertion.h needs C++11.

    frederick-vs-ja frederick-vs-ja commented on code on Nov 26, 2026 14:33 UTC
    Code Review
    libcxx/test/libcxx/strings/basic.string/string.modifiers/assert.insert.invalid_position.pass.cpp:1
    @@ -0,0 +1,86 @@
    +//===----------------------------------------------------------------------===//
    +//
    +// 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
    +//
    +//===----------------------------------------------------------------------===//
    +
    +// REQUIRES: can-test-hardening-assertions-fast
    +// UNSUPPORTED: libcpp-assertion-semantic={{ignore|observe}}
    +
    +// std::string::insert(const_iterator, char) is instantiated in the dylib, so we need an up-to-date one
    +// XFAIL: using-built-library-before-llvm-24
    +
    +// <string>
    +
    +// Make sure insert catches a position that isn't in [begin(), end()], such as an iterator into
    +// another string or an iterator invalidated by a reallocation.
    +
    +#include <string>
    +
    +#include "check_assertion.h"
    +#include "min_allocator.h"
    +#include "test_iterators.h"
    +#include "test_macros.h"
    +
    +#if TEST_STD_VER >= 23
    +#  include <string_view>
    +#endif
    +
    +template <class String>
    +void test_invalid_position(String& s, typename String::const_iterator pos) {
    +  [[maybe_unused]] const char* message = "string::insert called with an iterator outside [begin(), end()]";
    +  const char a[]                       = "abc";
    +  TEST_LIBCPP_ASSERT_FAILURE(s.insert(pos, 'x'), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(s.insert(pos, 2, 'x'), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(s.insert(pos, a, a + 3), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(
    +      s.insert(pos, forward_iterator<const char*>(a), forward_iterator<const char*>(a + 3)), message);
    +  TEST_LIBCPP_ASSERT_FAILURE(
    +      s.insert(pos, cpp17_input_iterator<const char*>(a), cpp17_input_iterator<const char*>(a + 3)), message);
    +  TEST_LIBCPP_ASSERT_FAILURE((s.insert(pos, {'a', 'b', 'c'})), message);
    +#if TEST_STD_VER >= 23
    +  TEST_LIBCPP_ASSERT_FAILURE(s.insert_range(pos, std::string_view("abc")), message);
    +#endif

    Oh, I was confused by other overloads taking positions. Never mind.

    ilyas-mallah ilyas-mallah commented on Nov 26, 2026 19:41 UTC
    Author

    @ldionne frederick-vs-ja found the vector and string parts correct and is waiting for your final approval. The test changes from that review are in https://github.com/llvm/llvm-project/commit/f245ab72bb5cef7f42e453dd899165314460cbe8. Could you take a look?

    #232661 is waiting for your re-review too, and the numbers from your benchmark run are there now.

    ilyas-mallah ilyas-mallah commented on Dec 03, 2026 19:50 UTC
    Author

    @ldionne I merged main after #240378 in https://github.com/llvm/llvm-project/commit/acd361c013642cd927006e53bb0b480df79caca5. vector::insert(pos, n, x) and deque::insert(pos, n, x) now forward to the iterator overloads, so their position check comes from __insert_with_size and __insert_bidirectional, and the PR no longer touches them. The tests still cover both. frederick-vs-ja found the vector and string parts correct. Could you take a look? #232661 also still shows your change request, and the test split you asked for is in.

    Assignees
    ilyas-mallah ilyas-mallah
    Labels
    risk: low confidence: 89.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 56.7% (MEDIUM) · Higher = larger blast radius
    56.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.5% · Lower = rushed or shallow review
    89.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.0% · Safe to merge
    6.0%