From 36f429127f3b5cf28a8dc198f5fc585ca33e5b0c Mon Sep 17 00:00:00 2001 From: Rick Altherr Date: Mon, 20 Nov 2017 11:47:32 -0800 Subject: [PATCH] lib: Return a valid MemoryMappedFile for zero-length files mmap() will fail for a zero-length mapping. A valid object should still be returned to signal that the file was opened to the caller but it should have a nullptr for data and zero for size. Signed-off-by: Rick Altherr Signed-off-by: Tim 'mithro' Ansell --- lib/memory_mapped_file.cc | 10 ++++++++++ lib/memory_mapped_file_test.cc | 7 +++++++ lib/test_data/empty_file | 0 3 files changed, 17 insertions(+) create mode 100644 lib/test_data/empty_file diff --git a/lib/memory_mapped_file.cc b/lib/memory_mapped_file.cc index e01a5a3e..b1ab18fc 100644 --- a/lib/memory_mapped_file.cc +++ b/lib/memory_mapped_file.cc @@ -17,6 +17,16 @@ std::unique_ptr MemoryMappedFile::InitWithFile( struct stat statbuf; if (fstat(fd, &statbuf) < 0) { close(fd); + return nullptr; + } + + // mmap() will fail with EINVAL if length==0. If this file is + // zero-length, return an object (to indicate the file exists) but + // load it with a nullptr and zero length. + if (statbuf.st_size == 0) { + close(fd); + return std::unique_ptr( + new MemoryMappedFile(nullptr, 0)); } void *file_map = mmap(NULL, statbuf.st_size, PROT_READ, diff --git a/lib/memory_mapped_file_test.cc b/lib/memory_mapped_file_test.cc index 0c61d41e..6a4477d6 100644 --- a/lib/memory_mapped_file_test.cc +++ b/lib/memory_mapped_file_test.cc @@ -6,6 +6,13 @@ TEST(MemoryMappedFileTest, NonExistantFile) { EXPECT_FALSE(prjxray::MemoryMappedFile::InitWithFile("does_not_exist")); } +TEST(MemoryMappedFileTest, ZeroLengthFileReturnObjectWithZeroLength) { + auto file = prjxray::MemoryMappedFile::InitWithFile("empty_file"); + ASSERT_TRUE(file); + EXPECT_EQ(nullptr, file->data()); + EXPECT_EQ(static_cast(0), file->size()); +} + TEST(MemoryMappedFileTest, ExistingFile) { auto file = prjxray::MemoryMappedFile::InitWithFile("small_file"); ASSERT_TRUE(file); diff --git a/lib/test_data/empty_file b/lib/test_data/empty_file new file mode 100644 index 00000000..e69de29b