[PATCH] D77601: Make SmallVector assert if it cannot grow.

Andrew via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Mon Apr 6 15:49:15 PDT 2020


browneee created this revision.
browneee added a reviewer: echristo.
Herald added subscribers: llvm-commits, hiraditya.
Herald added a project: LLVM.

Context:

  /// Double the size of the allocated memory, guaranteeing space for at
  /// least one more element or MinSize if specified.
  void grow(size_t MinSize = 0) { this->grow_pod(MinSize, sizeof(T)); }
  
  void push_back(const T &Elt) {
    if (LLVM_UNLIKELY(this->size() >= this->capacity()))
      this->grow();
    memcpy(reinterpret_cast<void *>(this->end()), &Elt, sizeof(T));
    this->set_size(this->size() + 1);
  }

When grow is called in push_back() without a MinSize specified, this is
relying on the guarantee of space for at least one more element.

There is an edge case bug where the SmallVector is already at its maximum size
and push_back() calls grow() with default MinSize of zero. Grow is unable to
provide space for one more element, but push_back() assumes the additional
element it will be available. This can result in silent memory corruption, as
this->end() will be an invalid pointer and the program may continue executing.

Another alternative to fix would be to remove the default argument from
grow(), which would mean several changing grow() to grow(this->size()+1)
in several places.

No test case added because it would require allocating ~4GB.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77601

Files:
  llvm/lib/Support/SmallVector.cpp


Index: llvm/lib/Support/SmallVector.cpp
===================================================================
--- llvm/lib/Support/SmallVector.cpp
+++ llvm/lib/Support/SmallVector.cpp
@@ -45,6 +45,12 @@
   if (MinCapacity > UINT32_MAX)
     report_bad_alloc_error("SmallVector capacity overflow during allocation");
 
+  // Ensure we can meet the guarantee of space for at least one more element.
+  // The above check alone will not catch the case where grow is called with a
+  // default MinCapacity of 0, but the current capacity cannot be increased.
+  if (capacity() == size_t(UINT32_MAX))
+    report_bad_alloc_error("SmallVector capacity unable to grow");
+
   size_t NewCapacity = 2 * capacity() + 1; // Always grow.
   NewCapacity =
       std::min(std::max(NewCapacity, MinCapacity), size_t(UINT32_MAX));


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D77601.255517.patch
Type: text/x-patch
Size: 814 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20200406/8d953d6d/attachment.bin>


More information about the llvm-commits mailing list