From d06839811d31b376d35dd373082ccce21666f44d Mon Sep 17 00:00:00 2001 From: Kyle Nekritz Date: Mon, 27 Feb 2017 10:48:39 -0800 Subject: [PATCH] Don't call memcpy with empty buffer in IOBuf::copyBuffer(). Summary: Fixes "undefined behavior" in ubsan builds when using an empty ByteRange. Reviewed By: siyengar Differential Revision: D4613663 fbshipit-source-id: 4b53ba764609acc986340f10613f84585fa697cf --- folly/io/IOBuf.h | 4 +++- folly/io/test/IOBufTest.cpp | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/folly/io/IOBuf.h b/folly/io/IOBuf.h index 621d3933..87a3ec9e 100644 --- a/folly/io/IOBuf.h +++ b/folly/io/IOBuf.h @@ -1439,7 +1439,9 @@ inline std::unique_ptr IOBuf::copyBuffer( uint64_t capacity = headroom + size + minTailroom; std::unique_ptr buf = create(capacity); buf->advance(headroom); - memcpy(buf->writableData(), data, size); + if (size != 0) { + memcpy(buf->writableData(), data, size); + } buf->append(size); return buf; } diff --git a/folly/io/test/IOBufTest.cpp b/folly/io/test/IOBufTest.cpp index 85b9dcb3..6e0cf441 100644 --- a/folly/io/test/IOBufTest.cpp +++ b/folly/io/test/IOBufTest.cpp @@ -717,6 +717,11 @@ TEST(IOBuf, maybeCopyBuffer) { EXPECT_EQ(nullptr, buf.get()); } +TEST(IOBuf, copyEmptyBuffer) { + auto buf = IOBuf::copyBuffer(nullptr, 0); + EXPECT_EQ(buf->length(), 0); +} + namespace { int customDeleterCount = 0; -- 2.34.1