[libcxx-commits] [libcxx] [libc++] Honor __SANITIZER_DISABLE_CONTAINER_OVERFLOW__ in libc++ (PR #168955)
Louis Dionne via libcxx-commits
libcxx-commits at lists.llvm.org
Thu Dec 4 09:05:54 PST 2025
================
@@ -0,0 +1,75 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+// XFAIL: FROZEN-CXX03-HEADERS-FIXME
+// REQUIRES: asan
+
+// Check that libc++ honors when __SANITIZER_DISABLE_CONTAINER_OVERFLOW__ is set
+// and disables the container overflow checks.
+
+// ADDITIONAL_COMPILE_FLAGS: -D__SANITIZER_DISABLE_CONTAINER_OVERFLOW__
+
+#include <deque>
+#include <string>
+#include <vector>
+
+// This check is somewhat weak because it would pass if we renamed the libc++-internal
+// macro and forgot to update this test. But it doesn't hurt to check it in addition to
+// the tests below.
+#if _LIBCPP_ENABLE_ASAN_CONTAINER_CHECKS
+# error "Container overflow checks should be disabled in libc++"
+#endif
+
+void vector() {
+ std::vector<int> v;
+ v.reserve(100);
+ int* data = v.data();
+
+ // This is illegal with respect to std::vector, but legal from the core language perspective since
+ // we do own that allocated memory and `int` is an implicit lifetime type. If container overflow
+ // checks are enabled, this would fail.
+ data[4] = 42;
+}
+
+// For std::string, we must use a custom char_traits class to reliably test this behavior. Since
----------------
ldionne wrote:
Thinking about this some more, we could actually "prevent" the invalid/surprising behaviour in `std::string`. We could say that attempting to disable container overflow checks when using a `libc++.dylib` that has been built with ASAN enabled is just not valid, and produce an error. Something like:
```c++
#if __has_feature(address_sanitizer) && !defined(__SANITIZER_DISABLE_CONTAINER_OVERFLOW__)
# define _LIBCPP_ENABLE_ASAN_CONTAINER_CHECKS 1
#else
# define _LIBCPP_ENABLE_ASAN_CONTAINER_CHECKS 0
#endif
#if _LIBCPP_INSTRUMENTED_WITH_ASAN && !_LIBCPP_ENABLE_ASAN_CONTAINER_CHECKS
# error "We can't disable ASAN container checks when the library has been built with these checks enable"
#endif
```
That way, we catch the potential misuse immediately. In practice, this should affect a much smaller number of users since I'm not aware of anyone shipping a sanitized version of libc++ in their toolchain.
WDYT?
https://github.com/llvm/llvm-project/pull/168955
More information about the libcxx-commits
mailing list