https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128264

            Bug ID: 128264
           Summary: pmr::unsynchronized_pool_resource::allocate crashes
                    instead of throwing when upstream fails in
                    _Pool::replenish
           Product: gcc
           Version: 14.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: fobostm at gmail dot com
  Target Milestone: ---

Created attachment 66024
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=66024&action=edit
Preprocessed testcase

If the upstream resource throws while _Pool::replenish grows the _M_chunks
vector, the exception is swallowed and _Pool::allocate continues as if a chunk
had been added. Instead of propagating std::bad_alloc, the pool segfaults (or
returns a null pointer).

libstdc++-v3/src/c++17/memory_resource.cc, _Pool::replenish:

      void* __p = __r->allocate(__bytes, __alignment);
      __try
        {
          size_t __n = __blocks * __block_size;
          void* __pwords = static_cast<char*>(__p) + __n;
          _M_chunks.insert(chunk(__p, __bytes, __pwords, __blocks), __r);
        }
      __catch (...)
        {
          __r->deallocate(__p, __bytes, __alignment);
        }

The exception is not rethrown, and _Pool::allocate then does:

      replenish(r, opts);
      return _M_chunks.back().reserve(block_size());

1) If _M_chunks was empty, _Pool::vector::insert has already set capacity
   before the allocation that threw:

            data = __alloc.allocate(capacity = 8);

   so data == nullptr and size == 0. _M_chunks.back() returns data[size - 1]
   with the unsigned size wrapping to UINT_MAX, and reserve() reads through
   it, which segfaults. The pool is also left with capacity == 8 and
   data == nullptr, so a later insert would write through a null pointer.

2) If _M_chunks was full (size == capacity > 0), the reallocation in insert
   throws before anything is modified, back() is an existing full chunk,
   reserve() returns nullptr, and allocate() returns nullptr to the caller
   instead of throwing, although memory_resource::allocate is declared
   __returns_nonnull__. (Found by reading the code, not reproduced.)

The same code is in releases/gcc-14, releases/gcc-15 and master (checked by
reading the source, not by running those versions).

Testcase
--------

#include <cstdio>
#include <memory_resource>
#include <new>

// Upstream resource that succeeds for the first N allocations and then throws.
struct failing_resource : std::pmr::memory_resource
{
  explicit failing_resource(int n) : remaining(n) { }

  int remaining;

  void* do_allocate(std::size_t bytes, std::size_t align) override
  {
    if (remaining-- <= 0)
      throw std::bad_alloc();
    return std::pmr::new_delete_resource()->allocate(bytes, align);
  }

  void do_deallocate(void* p, std::size_t bytes, std::size_t align) override
  { std::pmr::new_delete_resource()->deallocate(p, bytes, align); }

  bool do_is_equal(const std::pmr::memory_resource& r) const noexcept override
  { return this == &r; }
};

int main()
{
  // 1st upstream allocation: the array of pools (in the constructor),
  // 2nd: the chunk in _Pool::replenish,
  // 3rd (throws): the _Pool::vector storage in _M_chunks.insert.
  failing_resource upstream(2);
  std::pmr::unsynchronized_pool_resource pool(&upstream);
  try
  {
    void* p = pool.allocate(40, 8);
    std::printf("allocate returned %p, expected std::bad_alloc\n", p);
  }
  catch (const std::bad_alloc&)
  {
    std::printf("std::bad_alloc, OK\n");
  }
}

Expected output: std::bad_alloc, OK
Actual: segmentation fault.

Command line and output
-----------------------

$ g++ -v -save-temps -std=c++17 -O2 -Wall -Wextra pr.cc -o pr
(no warnings)
$ ./pr
Segmentation fault (core dumped)

The crash does not depend on compile options: the same result with
-D_GLIBCXX_ASSERTIONS, -D_GLIBCXX_DEBUG,
-fno-strict-aliasing -fwrapv -fno-aggressive-loop-optimizations.
With -fsanitize=address,undefined there are no other diagnostics before the
crash:

==ERROR: AddressSanitizer: SEGV on unknown address 0x0017fffffff0
The signal is caused by a READ memory access.
    #0 in std::pmr::unsynchronized_pool_resource::do_allocate(unsigned long,
unsigned long) (libstdc++.so.6+0x1b7945)
    #1 in std::pmr::memory_resource::allocate(unsigned long, unsigned long)
/usr/include/c++/13/bits/memory_resource.h:76
    #2 in main pr.cc:35

Library versions tested:
- shared libstdc++.so.6.0.33 from libstdc++6 14.2.0-4ubuntu2~24.04.1 (default
  dynamic link above);
- static libstdc++.a of GCC 13.3.0 (g++ -static-libstdc++);
- static libstdc++.a of GCC 11.5.0 (g++-11 -static-libstdc++).
All three crash.

gcc -v
------

Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-linux-gnu/13/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu
13.3.0-6ubuntu2~24.04.1' --with-bugurl=file:///usr/share/doc/gcc-13/README.Bugs
--enable-languages=c,ada,c++,go,d,fortran,objc,obj-c++,m2 --prefix=/usr
--with-gcc-major-version-only --program-suffix=-13
--program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id
--libexecdir=/usr/libexec --without-included-gettext --enable-threads=posix
--libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu
--enable-libstdcxx-debug --enable-libstdcxx-time=yes
--with-default-libstdcxx-abi=new --enable-libstdcxx-backtrace
--enable-gnu-unique-object --disable-vtable-verify --enable-plugin
--enable-default-pie --with-system-zlib --enable-libphobos-checking=release
--with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch
--disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64
--with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic
--enable-offload-targets=nvptx-none=/build/gcc-13-EldibY/gcc-13-13.3.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-13-EldibY/gcc-13-13.3.0/debian/tmp-gcn/usr
--enable-offload-defaulted --without-cuda-driver --enable-checking=release
--build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
--with-build-config=bootstrap-lto-lean --enable-link-serialization=2
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 13.3.0 (Ubuntu 13.3.0-6ubuntu2~24.04.1)

Possible fix
------------

Rethrow in the __catch block of _Pool::replenish (__throw_exception_again),
and in _Pool::vector::insert assign capacity only after the allocation
succeeds. synchronized_pool_resource uses the same _Pool code, so it is
probably affected too (not tested). See also PR 124551 for a related
exception-safety issue in synchronized_pool_resource, and PR 94160 for an
earlier case of pool resources returning null pointers.

The analysis and testcase were prepared with the help of an AI assistant;
I have reproduced the crash and checked the quoted code myself.

Reply via email to