This is an automated email from the ASF dual-hosted git repository.

pitrou pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow.git


The following commit(s) were added to refs/heads/main by this push:
     new 16900e3b0f3 GH-49884: [C++] Fix integer overflow in BufferBuilder 
reachable from JSON parsing (#49883)
16900e3b0f3 is described below

commit 16900e3b0f3867f0fefe0e70e769516644d07902
Author: metsw24-max <[email protected]>
AuthorDate: Tue Nov 10 19:48:40 2026 +0530

    GH-49884: [C++] Fix integer overflow in BufferBuilder reachable from JSON 
parsing (#49883)
    
    ### Rationale for this change
    
    `BufferBuilder` and `TypedBufferBuilder` perform size calculations that are 
reachable from JSON parsing of untrusted input. These calculations previously 
used unchecked integer arithmetic (e.g., `size_ + additional_bytes`, 
`num_elements * sizeof(T)`), which can overflow.
    
    Since the JSON parser constructs arrays, strings, and offsets based on 
input data, an attacker can influence these values. Overflow in these 
calculations can result in incorrect buffer sizing and unsafe memory operations.
    
    ### What changes are included in this PR?
    
    - Added overflow-safe arithmetic using `internal::AddWithOverflow` and 
`internal::MultiplyWithOverflow` for:
      - `size_ + additional_bytes`
      - `num_elements * sizeof(T)`
      - capacity growth logic
    
    - Centralised the negative / too-large capacity check in a single 
`ValidateBufferCapacity` helper in `memory_pool.cc`, used by 
`PoolBuffer::Reserve`, `PoolBuffer::Resize` and `AllocateResizableBuffer`
    
    - Hardened `GrowByFactor` to prevent overflow when doubling capacity
    
    - Updated `TypedBufferBuilder` to safely compute byte sizes from element 
counts
    
    - Added regression tests covering:
      - addition overflow
      - multiplication overflow
    
    ### Are these changes tested?
    
    Yes.
    
    New tests were added to:
    - Detect overflow conditions in both `BufferBuilder` and 
`TypedBufferBuilder`
    - Ensure proper error handling (`CapacityError`, `OutOfMemory`) instead of 
undefined behavior
    
    ### Are there any user-facing changes?
    
    No functional changes for valid inputs.
    
    Sizes that overflow `int64_t` during these calculations, which previously 
resulted in undefined behavior, are now explicitly rejected with clear error 
statuses. Negative arguments are still treated as a caller error and are not 
checked in the builders.
    
    **This PR contains a "Critical Fix".**
    
    Unchecked integer arithmetic in buffer size calculations could overflow 
when processing untrusted JSON input. This may result in under-allocation of 
buffers followed by writes of larger logical sizes, leading to potential 
out-of-bounds memory writes and undefined behavior.
    
    This patch ensures all such arithmetic is validated, preventing incorrect 
buffer sizing and eliminating this class of memory safety issues.
    * GitHub Issue: #49884
    
    Lead-authored-by: Sayed Kaif <[email protected]>
    Co-authored-by: metsw24-max <[email protected]>
    Signed-off-by: Antoine Pitrou <[email protected]>
---
 cpp/src/arrow/buffer_builder.h | 68 +++++++++++++++++++++++++++++++++---------
 cpp/src/arrow/buffer_test.cc   | 24 +++++++++++++++
 cpp/src/arrow/memory_pool.cc   | 23 ++++++++------
 3 files changed, 92 insertions(+), 23 deletions(-)

diff --git a/cpp/src/arrow/buffer_builder.h b/cpp/src/arrow/buffer_builder.h
index e9177c656c0..5ad46b05559 100644
--- a/cpp/src/arrow/buffer_builder.h
+++ b/cpp/src/arrow/buffer_builder.h
@@ -29,6 +29,7 @@
 #include "arrow/util/bit_util.h"
 #include "arrow/util/bitmap_generate.h"
 #include "arrow/util/bitmap_ops.h"
+#include "arrow/util/int_util_overflow.h"
 #include "arrow/util/macros.h"
 #include "arrow/util/ubsan.h"
 #include "arrow/util/visibility.h"
@@ -91,7 +92,12 @@ class ARROW_EXPORT BufferBuilder {
   /// \param[in] additional_bytes number of additional bytes to make space for
   /// \return Status
   Status Reserve(const int64_t additional_bytes) {
-    auto min_capacity = size_ + additional_bytes;
+    int64_t min_capacity;
+    if (ARROW_PREDICT_FALSE(
+            internal::AddWithOverflow(size_, additional_bytes, 
&min_capacity))) {
+      return Status::CapacityError("Reserve: capacity overflow: ", size_, " + 
",
+                                   additional_bytes);
+    }
     if (min_capacity <= capacity_) {
       return Status::OK();
     }
@@ -104,15 +110,24 @@ class ARROW_EXPORT BufferBuilder {
     // (versus 1.5x) seems to have slightly better performance when using
     // jemalloc, but significantly better performance when using the system
     // allocator. See ARROW-6450 for further discussion
-    return std::max(new_capacity, current_capacity * 2);
+    int64_t doubled;
+    if (ARROW_PREDICT_FALSE(
+            internal::AddWithOverflow(current_capacity, current_capacity, 
&doubled))) {
+      return new_capacity;
+    }
+    return std::max(new_capacity, doubled);
   }
 
   /// \brief Append the given data to the buffer
   ///
   /// The buffer is automatically expanded if necessary.
   Status Append(const void* data, const int64_t length) {
-    if (ARROW_PREDICT_FALSE(size_ + length > capacity_)) {
-      ARROW_RETURN_NOT_OK(Resize(GrowByFactor(capacity_, size_ + length), 
false));
+    int64_t new_size;
+    if (ARROW_PREDICT_FALSE(internal::AddWithOverflow(size_, length, 
&new_size))) {
+      return Status::CapacityError("Append: size overflow: ", size_, " + ", 
length);
+    }
+    if (ARROW_PREDICT_FALSE(new_size > capacity_)) {
+      ARROW_RETURN_NOT_OK(Resize(GrowByFactor(capacity_, new_size), false));
     }
     UnsafeAppend(data, length);
     return Status::OK();
@@ -250,12 +265,13 @@ class TypedBufferBuilder<
   }
 
   Status Append(const T* values, int64_t num_elements) {
-    return bytes_builder_.Append(reinterpret_cast<const uint8_t*>(values),
-                                 num_elements * sizeof(T));
+    int64_t num_bytes = 0;
+    ARROW_RETURN_NOT_OK(ElementsToBytes("Append", num_elements, &num_bytes));
+    return bytes_builder_.Append(reinterpret_cast<const uint8_t*>(values), 
num_bytes);
   }
 
   Status Append(const int64_t num_copies, T value) {
-    ARROW_RETURN_NOT_OK(Reserve(num_copies + length()));
+    ARROW_RETURN_NOT_OK(Reserve(num_copies));
     UnsafeAppend(num_copies, value);
     return Status::OK();
   }
@@ -284,15 +300,21 @@ class TypedBufferBuilder<
   }
 
   Status Resize(const int64_t new_capacity, bool shrink_to_fit = true) {
-    return bytes_builder_.Resize(new_capacity * sizeof(T), shrink_to_fit);
+    int64_t num_bytes = 0;
+    ARROW_RETURN_NOT_OK(ElementsToBytes("Resize", new_capacity, &num_bytes));
+    return bytes_builder_.Resize(num_bytes, shrink_to_fit);
   }
 
   Status Reserve(const int64_t additional_elements) {
-    return bytes_builder_.Reserve(additional_elements * sizeof(T));
+    int64_t num_bytes = 0;
+    ARROW_RETURN_NOT_OK(ElementsToBytes("Reserve", additional_elements, 
&num_bytes));
+    return bytes_builder_.Reserve(num_bytes);
   }
 
   Status Advance(const int64_t length) {
-    return bytes_builder_.Advance(length * sizeof(T));
+    int64_t num_bytes = 0;
+    ARROW_RETURN_NOT_OK(ElementsToBytes("Advance", length, &num_bytes));
+    return bytes_builder_.Advance(num_bytes);
   }
 
   void UnsafeAdvance(const int64_t length) {
@@ -316,7 +338,9 @@ class TypedBufferBuilder<
   /// only for memory allocation).
   Result<std::shared_ptr<Buffer>> FinishWithLength(int64_t final_length,
                                                    bool shrink_to_fit = true) {
-    return bytes_builder_.FinishWithLength(final_length * sizeof(T), 
shrink_to_fit);
+    int64_t num_bytes = 0;
+    ARROW_RETURN_NOT_OK(ElementsToBytes("FinishWithLength", final_length, 
&num_bytes));
+    return bytes_builder_.FinishWithLength(num_bytes, shrink_to_fit);
   }
 
   void Reset() { bytes_builder_.Reset(); }
@@ -327,6 +351,18 @@ class TypedBufferBuilder<
   T* mutable_data() { return 
reinterpret_cast<T*>(bytes_builder_.mutable_data()); }
 
  private:
+  // Convert a number of elements to a number of bytes, erroring out on
+  // byte size overflow.
+  static Status ElementsToBytes(const char* operation, int64_t num_elements,
+                                int64_t* num_bytes) {
+    if (ARROW_PREDICT_FALSE(internal::MultiplyWithOverflow(
+            num_elements, static_cast<int64_t>(sizeof(T)), num_bytes))) {
+      return Status::CapacityError(operation, ": byte size overflow: ", 
num_elements,
+                                   " * ", sizeof(T));
+    }
+    return Status::OK();
+  }
+
   BufferBuilder bytes_builder_;
 };
 
@@ -429,9 +465,13 @@ class TypedBufferBuilder<bool> {
   }
 
   Status Reserve(const int64_t additional_elements) {
-    return Resize(
-        BufferBuilder::GrowByFactor(bit_length_, bit_length_ + 
additional_elements),
-        false);
+    int64_t min_length;
+    if (ARROW_PREDICT_FALSE(
+            internal::AddWithOverflow(bit_length_, additional_elements, 
&min_length))) {
+      return Status::CapacityError("Reserve: capacity overflow: ", 
bit_length_, " + ",
+                                   additional_elements);
+    }
+    return Resize(BufferBuilder::GrowByFactor(bit_length_, min_length), false);
   }
 
   Status Advance(const int64_t length) {
diff --git a/cpp/src/arrow/buffer_test.cc b/cpp/src/arrow/buffer_test.cc
index bdda0b4a747..230a091734a 100644
--- a/cpp/src/arrow/buffer_test.cc
+++ b/cpp/src/arrow/buffer_test.cc
@@ -726,6 +726,21 @@ TEST(TestBufferBuilder, ResizeReserve) {
   ASSERT_EQ(9, builder.length());
 }
 
+TEST(TestBufferBuilder, ReserveAndAppendOverflow) {
+  const std::string data = "x";
+  auto data_ptr = data.c_str();
+  BufferBuilder builder;
+
+  const int64_t overflow_add = std::numeric_limits<int64_t>::max() - 8;
+  ASSERT_RAISES(OutOfMemory, builder.Reserve(overflow_add));
+
+  ASSERT_OK(builder.Append(data_ptr, 1));
+  constexpr int64_t kMaxLength = std::numeric_limits<int64_t>::max();
+  ASSERT_RAISES(CapacityError, builder.Reserve(kMaxLength));
+  ASSERT_RAISES(CapacityError, builder.Append(data_ptr, kMaxLength));
+  ASSERT_EQ(1, builder.length());
+}
+
 TEST(TestBufferBuilder, Alignment) {
   const std::string data = "some data";
   auto data_ptr = data.c_str();
@@ -862,6 +877,15 @@ TYPED_TEST(TypedTestBufferBuilder, AppendCopies) {
   }
 }
 
+TYPED_TEST(TypedTestBufferBuilder, OverflowAppend) {
+  TypedBufferBuilder<TypeParam> builder;
+
+  const int64_t max_num_elements =
+      std::numeric_limits<int64_t>::max() / 
static_cast<int64_t>(sizeof(TypeParam)) + 1;
+  ASSERT_RAISES(CapacityError,
+                builder.Append(max_num_elements, static_cast<TypeParam>(0)));
+}
+
 TEST(TestBoolBufferBuilder, Basics) {
   TypedBufferBuilder<bool> builder;
 
diff --git a/cpp/src/arrow/memory_pool.cc b/cpp/src/arrow/memory_pool.cc
index 0b4843bec35..8801ac312c4 100644
--- a/cpp/src/arrow/memory_pool.cc
+++ b/cpp/src/arrow/memory_pool.cc
@@ -64,6 +64,17 @@ namespace {
 
 constexpr char kDefaultBackendEnvVar[] = "ARROW_DEFAULT_MEMORY_POOL";
 constexpr char kDebugMemoryEnvVar[] = "ARROW_DEBUG_MEMORY_POOL";
+constexpr int64_t kMaxBufferCapacity = std::numeric_limits<int64_t>::max() - 
63;
+
+Status ValidateBufferCapacity(int64_t capacity, const char* operation) {
+  if (ARROW_PREDICT_FALSE(capacity < 0)) {
+    return Status::Invalid(operation, ": negative capacity: ", capacity);
+  }
+  if (ARROW_PREDICT_FALSE(capacity > kMaxBufferCapacity)) {
+    return Status::OutOfMemory(operation, ": capacity too large: ", capacity);
+  }
+  return Status::OK();
+}
 
 enum class MemoryPoolBackend : uint8_t { System, Jemalloc, Mimalloc };
 
@@ -915,9 +926,7 @@ class PoolBuffer final : public ResizableBuffer {
   }
 
   Status Reserve(const int64_t capacity) override {
-    if (capacity < 0) {
-      return Status::Invalid("Negative buffer capacity: ", capacity);
-    }
+    RETURN_NOT_OK(ValidateBufferCapacity(capacity, "Reserve"));
     uint8_t* ptr = mutable_data();
     if (!ptr || capacity > capacity_) {
       ARROW_ASSIGN_OR_RAISE(int64_t new_capacity, RoundCapacity(capacity));
@@ -933,9 +942,7 @@ class PoolBuffer final : public ResizableBuffer {
   }
 
   Status Resize(const int64_t new_size, bool shrink_to_fit = true) override {
-    if (ARROW_PREDICT_FALSE(new_size < 0)) {
-      return Status::Invalid("Negative buffer resize: ", new_size);
-    }
+    RETURN_NOT_OK(ValidateBufferCapacity(new_size, "Resize"));
     uint8_t* ptr = mutable_data();
     if (ptr && shrink_to_fit && new_size <= size_) {
       // Buffer is non-null and is not growing, so shrink to the requested 
size without
@@ -979,9 +986,7 @@ class PoolBuffer final : public ResizableBuffer {
 
  private:
   static Result<int64_t> RoundCapacity(int64_t capacity) {
-    if (capacity > std::numeric_limits<int64_t>::max() - 63) {
-      return Status::OutOfMemory("capacity too large");
-    }
+    DCHECK_LE(capacity, kMaxBufferCapacity);
     return bit_util::RoundUpToMultipleOf64(capacity);
   }
 

Reply via email to