| Issue |
234974
|
| Summary |
[libc++] `std::shared_ptr<T[]>(Y*)` uses scalar `delete` instead of `delete[]` when control block allocation throws
|
| Labels |
libc++
|
| Assignees |
|
| Reporter |
slotosch
|
During qualification of the C++STL we found that constructor shared_ptr([]T) we found out that in case of low memory (exception) a crash can occur caused by undefined behaviour.
Since this is very similar issue like the php2Shell bug (also caused by a low memory during initialization) from this week, please check if there is a security impact.
If the control block allocation in `std::shared_ptr<T[]>::shared_ptr(Y*)` throws `std::bad_alloc`, libc++ releases the array with scalar `delete`. This is undefined behavior. [util.smartptr.shared.const] requires `delete[] p` when `T` is an array type.
With a non-trivial element type, the pointer passed to `operator delete` is not the one returned by `operator new[]` (it is offset by the array cookie), so the program crashes:
```
munmap_chunk(): invalid pointer
```
ASan reports `attempting free on address which was not malloc()-ed`.
The constructor in `libcxx/include/__memory/shared_ptr.h` guards the pointer with `unique_ptr<_Yp>`, which uses `default_delete<_Yp>` (scalar `delete`). The control block itself correctly uses `__shared_ptr_default_delete<_Tp, _Yp>`. The same code is on `main`.
## Reproducer
```cpp
#include <cstdlib>
#include <iostream>
#include <memory>
#include <new>
static bool fail_next = false;
void* operator new(std::size_t s) {
if (fail_next) { fail_next = false; throw std::bad_alloc{}; }
if (void* p = std::malloc(s)) return p;
throw std::bad_alloc{};
}
void operator delete(void* p) noexcept { std::free(p); }
void operator delete[](void* p) noexcept { std::free(p); }
struct Elem {
virtual ~Elem() = default; // non-trivial destructor => array cookie
int v = 0;
};
int main() {
Elem* arr = new Elem[10];
fail_next = true; // make the control block allocation throw
try {
std::shared_ptr<Elem[]> sp(arr);
} catch (const std::bad_alloc&) {
std::cout << "caught bad_alloc\n";
}
}
```
```
clang++ -std=c++17 -stdlib=libc++ repro.cpp -o repro && ./repro
```
## Expected
`operator delete[]` is called with the pointer from `operator new[]`, then `bad_alloc` propagates (libstdc++ behaves this way).
## Actual
libc++ calls scalar `delete` on the element pointer and aborts with `munmap_chunk(): invalid pointer`.
## Environment
- Clang 22.0.0 (Ubuntu), x86_64-pc-linux-gnu
- libc++ `_LIBCPP_VERSION` 180100
- `-std=c++17` and `-std=c++20`
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs