Skip to content

Commit

Permalink
GH-36913: [C++] Skip empty buffer concatenation to fix UBSan error (#…
Browse files Browse the repository at this point in the history
…36914)

### Rationale for this change

This is a trivial fix for a UBSan error in calls to `ConcatenateBuffers` with an empty buffer that has a null data pointer.

### What changes are included in this PR?

Conditional call to `std::memcpy` based on whether the buffer's length is 0.

### Are these changes tested?

Test added in buffer_test.cc.

### Are there any user-facing changes?

No
* Closes: #36913

Lead-authored-by: Elliott Brossard <elliott.brossard@snowflake.com>
Co-authored-by: Elliott Brossard <64754120+sfc-gh-ebrossard@users.noreply.github.com>
Co-authored-by: Antoine Pitrou <pitrou@free.fr>
Signed-off-by: Antoine Pitrou <antoine@python.org>
  • Loading branch information
2 people authored and raulcd committed Jul 28, 2023
1 parent 7ea78a9 commit 4d22851
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
7 changes: 5 additions & 2 deletions cpp/src/arrow/buffer.cc
Expand Up @@ -209,8 +209,11 @@ Result<std::shared_ptr<Buffer>> ConcatenateBuffers(
ARROW_ASSIGN_OR_RAISE(auto out, AllocateBuffer(out_length, pool));
auto out_data = out->mutable_data();
for (const auto& buffer : buffers) {
std::memcpy(out_data, buffer->data(), buffer->size());
out_data += buffer->size();
// Passing nullptr to std::memcpy is undefined behavior, so skip empty buffers
if (buffer->size() != 0) {
std::memcpy(out_data, buffer->data(), buffer->size());
out_data += buffer->size();
}
}
return std::move(out);
}
Expand Down
9 changes: 9 additions & 0 deletions cpp/src/arrow/buffer_test.cc
Expand Up @@ -1000,4 +1000,13 @@ TYPED_TEST(TypedTestBuffer, ResizeOOM) {
#endif
}

TEST(TestBufferConcatenation, EmptyBuffer) {
// GH-36913: UB shouldn't be triggered by copying from a null pointer
const std::string contents = "hello, world";
auto buffer = std::make_shared<Buffer>(contents);
auto empty_buffer = std::make_shared<Buffer>(/*data=*/nullptr, /*size=*/0);
ASSERT_OK_AND_ASSIGN(auto result, ConcatenateBuffers({buffer, empty_buffer}));
AssertMyBufferEqual(*result, contents);
}

} // namespace arrow

0 comments on commit 4d22851

Please sign in to comment.