Switch over to the google3 unix_file File*.
I also moved macros.h to base/macros.h to ease google3 porting, at
the expense of a larger than necessary change. (I learned my lesson,
though, and didn't make the equivalent base/logging.h change.)
I'm not sure whether we want to keep the unix_file MappedFile given
our existing MemMap, but it's easier to bring it over and then remove
it (and possibly revert the removal) than to bring it over later.
Change-Id: Id50a66faa5ab17b9bc936cc9043dbc26f791f0ca
diff --git a/src/base/unix_file/README b/src/base/unix_file/README
new file mode 100644
index 0000000..e9aec22
--- /dev/null
+++ b/src/base/unix_file/README
@@ -0,0 +1,15 @@
+A simple C++ wrapper for Unix file I/O.
+
+This is intended to be lightweight and easy to use, similar to Java's
+RandomAccessFile and related classes. The usual C++ idioms of RAII and "you
+don't pay for what you don't use" apply.
+
+In particular, the basic RandomAccessFile interface is kept small and simple so
+it's trivial to add new implementations.
+
+This code will not log, because it can't know whether that's appropriate in
+your application.
+
+This code will, in general, return -errno on failure. If an operation consisted
+of multiple sub-operations, it will return the errno corresponding to the most
+relevant operation.
diff --git a/src/base/unix_file/fd_file.cc b/src/base/unix_file/fd_file.cc
new file mode 100644
index 0000000..73130a3
--- /dev/null
+++ b/src/base/unix_file/fd_file.cc
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "base/unix_file/fd_file.h"
+#include <errno.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include "logging.h"
+
+namespace unix_file {
+
+FdFile::FdFile() : fd_(-1), auto_close_(true) {
+}
+
+FdFile::FdFile(int fd) : fd_(fd), auto_close_(true) {
+}
+
+FdFile::FdFile(int fd, const std::string& path) : fd_(fd), file_path_(path), auto_close_(true) {
+}
+
+FdFile::~FdFile() {
+ if (auto_close_ && fd_ != -1) {
+ Close();
+ }
+}
+
+void FdFile::DisableAutoClose() {
+ auto_close_ = false;
+}
+
+bool FdFile::Open(const std::string& path, int flags) {
+ return Open(path, flags, 0640);
+}
+
+bool FdFile::Open(const std::string& path, int flags, mode_t mode) {
+ CHECK_EQ(fd_, -1) << path;
+ fd_ = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
+ if (fd_ == -1) {
+ return false;
+ }
+ file_path_ = path;
+ return true;
+}
+
+int FdFile::Close() {
+ int result = TEMP_FAILURE_RETRY(close(fd_));
+ if (result == -1) {
+ return -errno;
+ } else {
+ fd_ = -1;
+ file_path_ = "";
+ return 0;
+ }
+}
+
+int FdFile::Flush() {
+ int rc = TEMP_FAILURE_RETRY(fdatasync(fd_));
+ return (rc == -1) ? -errno : rc;
+}
+
+int64_t FdFile::Read(char* buf, int64_t byte_count, int64_t offset) const {
+ int rc = TEMP_FAILURE_RETRY(pread64(fd_, buf, byte_count, offset));
+ return (rc == -1) ? -errno : rc;
+}
+
+int FdFile::SetLength(int64_t new_length) {
+ int rc = TEMP_FAILURE_RETRY(ftruncate64(fd_, new_length));
+ return (rc == -1) ? -errno : rc;
+}
+
+int64_t FdFile::GetLength() const {
+ struct stat s;
+ int rc = TEMP_FAILURE_RETRY(fstat(fd_, &s));
+ return (rc == -1) ? -errno : s.st_size;
+}
+
+int64_t FdFile::Write(const char* buf, int64_t byte_count, int64_t offset) {
+ int rc = TEMP_FAILURE_RETRY(pwrite64(fd_, buf, byte_count, offset));
+ return (rc == -1) ? -errno : rc;
+}
+
+int FdFile::Fd() const {
+ return fd_;
+}
+
+bool FdFile::IsOpened() const {
+ return fd_ >= 0;
+}
+
+std::string FdFile::GetPath() const {
+ return file_path_;
+}
+
+bool FdFile::ReadFully(void* buffer, int64_t byte_count) {
+ char* ptr = static_cast<char*>(buffer);
+ while (byte_count > 0) {
+ int bytes_read = TEMP_FAILURE_RETRY(read(fd_, ptr, byte_count));
+ if (bytes_read <= 0) {
+ return false;
+ }
+ byte_count -= bytes_read; // Reduce the number of remaining bytes.
+ ptr += bytes_read; // Move the buffer forward.
+ }
+ return true;
+}
+
+bool FdFile::WriteFully(const void* buffer, int64_t byte_count) {
+ const char* ptr = static_cast<const char*>(buffer);
+ while (byte_count > 0) {
+ int bytes_read = TEMP_FAILURE_RETRY(write(fd_, ptr, byte_count));
+ if (bytes_read < 0) {
+ return false;
+ }
+ byte_count -= bytes_read; // Reduce the number of remaining bytes.
+ ptr += bytes_read; // Move the buffer forward.
+ }
+ return true;
+}
+
+} // namespace unix_file
diff --git a/src/base/unix_file/fd_file.h b/src/base/unix_file/fd_file.h
new file mode 100644
index 0000000..2b33961
--- /dev/null
+++ b/src/base/unix_file/fd_file.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef BASE_UNIX_FILE_FD_FILE_H_
+#define BASE_UNIX_FILE_FD_FILE_H_
+
+#include <fcntl.h>
+#include <string>
+#include "base/unix_file/random_access_file.h"
+#include "base/macros.h"
+
+namespace unix_file {
+
+// A RandomAccessFile implementation backed by a file descriptor.
+//
+// Not thread safe.
+class FdFile : public RandomAccessFile {
+ public:
+ FdFile();
+ // Creates an FdFile using the given file descriptor. Takes ownership of the
+ // file descriptor. (Use DisableAutoClose to retain ownership.)
+ explicit FdFile(int fd);
+ explicit FdFile(int fd, const std::string& path);
+
+ // Destroys an FdFile, closing the file descriptor if Close hasn't already
+ // been called. (If you care about the return value of Close, call it
+ // yourself; this is meant to handle failure cases and read-only accesses.
+ // Note though that calling Close and checking its return value is still no
+ // guarantee that data actually made it to stable storage.)
+ virtual ~FdFile();
+
+ // Opens file 'file_path' using 'flags' and 'mode'.
+ bool Open(const std::string& file_path, int flags);
+ bool Open(const std::string& file_path, int flags, mode_t mode);
+
+ // RandomAccessFile API.
+ virtual int Close();
+ virtual int64_t Read(char* buf, int64_t byte_count, int64_t offset) const;
+ virtual int SetLength(int64_t new_length);
+ virtual int64_t GetLength() const;
+ virtual int64_t Write(const char* buf, int64_t byte_count, int64_t offset);
+ virtual int Flush();
+
+ // Bonus API.
+ int Fd() const;
+ bool IsOpened() const;
+ std::string GetPath() const;
+ void DisableAutoClose();
+ bool ReadFully(void* buffer, int64_t byte_count);
+ bool WriteFully(const void* buffer, int64_t byte_count);
+
+ private:
+ int fd_;
+ std::string file_path_;
+ bool auto_close_;
+
+ DISALLOW_COPY_AND_ASSIGN(FdFile);
+};
+
+} // namespace unix_file
+
+#endif // BASE_UNIX_FILE_FD_FILE_H_
diff --git a/src/base/unix_file/fd_file_test.cc b/src/base/unix_file/fd_file_test.cc
new file mode 100644
index 0000000..d620666
--- /dev/null
+++ b/src/base/unix_file/fd_file_test.cc
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "base/unix_file/fd_file.h"
+#include "base/unix_file/random_access_file_test.h"
+#include "gtest/gtest.h"
+
+namespace unix_file {
+
+class FdFileTest : public RandomAccessFileTest {
+ protected:
+ virtual RandomAccessFile* MakeTestFile() {
+ return new FdFile(fileno(tmpfile()));
+ }
+};
+
+TEST_F(FdFileTest, Read) {
+ TestRead();
+}
+
+TEST_F(FdFileTest, SetLength) {
+ TestSetLength();
+}
+
+TEST_F(FdFileTest, Write) {
+ TestWrite();
+}
+
+TEST_F(FdFileTest, UnopenedFile) {
+ FdFile file;
+ EXPECT_EQ(-1, file.Fd());
+ EXPECT_FALSE(file.IsOpened());
+ EXPECT_TRUE(file.GetPath().empty());
+}
+
+TEST_F(FdFileTest, OpenClose) {
+ std::string good_path(GetTmpPath("some-file.txt"));
+ FdFile file;
+ ASSERT_TRUE(file.Open(good_path, O_CREAT | O_WRONLY));
+ EXPECT_GE(file.Fd(), 0);
+ EXPECT_TRUE(file.IsOpened());
+ EXPECT_EQ(0, file.Close());
+ EXPECT_EQ(-1, file.Fd());
+ EXPECT_FALSE(file.IsOpened());
+ EXPECT_TRUE(file.Open(good_path, O_RDONLY));
+ EXPECT_GE(file.Fd(), 0);
+ EXPECT_TRUE(file.IsOpened());
+}
+
+} // namespace unix_file
diff --git a/src/base/unix_file/mapped_file.cc b/src/base/unix_file/mapped_file.cc
new file mode 100644
index 0000000..84629b3
--- /dev/null
+++ b/src/base/unix_file/mapped_file.cc
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "base/unix_file/mapped_file.h"
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <algorithm>
+#include <string>
+#include "logging.h"
+
+namespace unix_file {
+
+MappedFile::~MappedFile() {
+}
+
+int MappedFile::Close() {
+ if (IsMapped()) {
+ Unmap();
+ }
+ return FdFile::Close();
+}
+
+bool MappedFile::MapReadOnly() {
+ CHECK(IsOpened());
+ CHECK(!IsMapped());
+ struct stat st;
+ int result = TEMP_FAILURE_RETRY(fstat(Fd(), &st));
+ if (result == -1) {
+ PLOG(WARNING) << "Failed to stat file '" << GetPath() << "'";
+ return false;
+ }
+ file_size_ = st.st_size;
+ do {
+ mapped_file_ = mmap(NULL, file_size_, PROT_READ, MAP_PRIVATE, Fd(), 0);
+ } while (mapped_file_ == MAP_FAILED && errno == EINTR);
+ if (mapped_file_ == MAP_FAILED) {
+ PLOG(WARNING) << "Failed to mmap file '" << GetPath() << "' of size "
+ << file_size_ << " bytes to memory";
+ return false;
+ }
+ map_mode_ = kMapReadOnly;
+ return true;
+}
+
+bool MappedFile::MapReadWrite(int64_t file_size) {
+ CHECK(IsOpened());
+ CHECK(!IsMapped());
+ int result = TEMP_FAILURE_RETRY(ftruncate64(Fd(), file_size));
+ if (result == -1) {
+ PLOG(ERROR) << "Failed to truncate file '" << GetPath()
+ << "' to size " << file_size;
+ return false;
+ }
+ file_size_ = file_size;
+ do {
+ mapped_file_ =
+ mmap(NULL, file_size_, PROT_READ | PROT_WRITE, MAP_SHARED, Fd(), 0);
+ } while (mapped_file_ == MAP_FAILED && errno == EINTR);
+ if (mapped_file_ == MAP_FAILED) {
+ PLOG(WARNING) << "Failed to mmap file '" << GetPath() << "' of size "
+ << file_size_ << " bytes to memory";
+ return false;
+ }
+ map_mode_ = kMapReadWrite;
+ return true;
+}
+
+bool MappedFile::Unmap() {
+ CHECK(IsMapped());
+ int result = TEMP_FAILURE_RETRY(munmap(mapped_file_, file_size_));
+ if (result == -1) {
+ PLOG(WARNING) << "Failed unmap file '" << GetPath() << "' of size "
+ << file_size_;
+ return false;
+ } else {
+ mapped_file_ = NULL;
+ file_size_ = -1;
+ return true;
+ }
+}
+
+int64_t MappedFile::Read(char* buf, int64_t byte_count, int64_t offset) const {
+ if (IsMapped()) {
+ if (offset < 0) {
+ errno = EINVAL;
+ return -errno;
+ }
+ int64_t read_size = std::max(0LL, std::min(byte_count, file_size_ - offset));
+ if (read_size > 0) {
+ memcpy(buf, data() + offset, read_size);
+ }
+ return read_size;
+ } else {
+ return FdFile::Read(buf, byte_count, offset);
+ }
+}
+
+int MappedFile::SetLength(int64_t new_length) {
+ CHECK(!IsMapped());
+ return FdFile::SetLength(new_length);
+}
+
+int64_t MappedFile::GetLength() const {
+ if (IsMapped()) {
+ return file_size_;
+ } else {
+ return FdFile::GetLength();
+ }
+}
+
+int MappedFile::Flush() {
+ int rc = IsMapped() ? TEMP_FAILURE_RETRY(msync(mapped_file_, file_size_, 0)) : FdFile::Flush();
+ return rc == -1 ? -errno : 0;
+}
+
+int64_t MappedFile::Write(const char* buf, int64_t byte_count, int64_t offset) {
+ if (IsMapped()) {
+ CHECK_EQ(kMapReadWrite, map_mode_);
+ if (offset < 0) {
+ errno = EINVAL;
+ return -errno;
+ }
+ int64_t write_size = std::max(0LL, std::min(byte_count, file_size_ - offset));
+ if (write_size > 0) {
+ memcpy(data() + offset, buf, write_size);
+ }
+ return write_size;
+ } else {
+ return FdFile::Write(buf, byte_count, offset);
+ }
+}
+
+int64_t MappedFile::size() const {
+ return GetLength();
+}
+
+bool MappedFile::IsMapped() const {
+ return mapped_file_ != NULL && mapped_file_ != MAP_FAILED;
+}
+
+char* MappedFile::data() const {
+ CHECK(IsMapped());
+ return static_cast<char*>(mapped_file_);
+}
+
+} // namespace unix_file
diff --git a/src/base/unix_file/mapped_file.h b/src/base/unix_file/mapped_file.h
new file mode 100644
index 0000000..161100b
--- /dev/null
+++ b/src/base/unix_file/mapped_file.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef BASE_UNIX_FILE_MAPPED_FILE_H_
+#define BASE_UNIX_FILE_MAPPED_FILE_H_
+
+#include <fcntl.h>
+#include <string>
+#include "base/unix_file/fd_file.h"
+
+namespace unix_file {
+
+// Random access file which handles an mmap(2), munmap(2) pair in C++
+// RAII style. When a file is mmapped, the random access file
+// interface accesses the mmapped memory directly; otherwise, the
+// standard file I/O is used. Whenever a function fails, it returns
+// false and errno is set to the corresponding error code.
+class MappedFile : public FdFile {
+ public:
+ // File modes used in Open().
+ enum FileMode {
+ kReadOnlyMode = O_RDONLY | O_LARGEFILE,
+ kReadWriteMode = O_CREAT | O_RDWR | O_LARGEFILE,
+ };
+
+ MappedFile() : FdFile(), file_size_(-1), mapped_file_(NULL) {
+ }
+ // Creates a MappedFile using the given file descriptor. Takes ownership of
+ // the file descriptor.
+ explicit MappedFile(int fd) : FdFile(fd), file_size_(-1), mapped_file_(NULL) {
+ }
+
+ // Unmaps and closes the file if needed.
+ virtual ~MappedFile();
+
+ // Maps an opened file to memory in the read-only mode.
+ bool MapReadOnly();
+
+ // Maps an opened file to memory in the read-write mode. Before the
+ // file is mapped, it is truncated to 'file_size' bytes.
+ bool MapReadWrite(int64_t file_size);
+
+ // Unmaps a mapped file so that, e.g., SetLength() may be invoked.
+ bool Unmap();
+
+ // RandomAccessFile API.
+ // The functions below require that the file is open, but it doesn't
+ // have to be mapped.
+ virtual int Close();
+ virtual int64_t Read(char* buf, int64_t byte_count, int64_t offset) const;
+ // SetLength() requires that the file is not mmapped.
+ virtual int SetLength(int64_t new_length);
+ virtual int64_t GetLength() const;
+ virtual int Flush();
+ // Write() requires that, if the file is mmapped, it is mmapped in
+ // the read-write mode. Writes past the end of file are discarded.
+ virtual int64_t Write(const char* buf, int64_t byte_count, int64_t offset);
+
+ // A convenience method equivalent to GetLength().
+ int64_t size() const;
+
+ // Returns true if the file has been mmapped.
+ bool IsMapped() const;
+
+ // Returns a pointer to the start of the memory mapping once the
+ // file is successfully mapped; crashes otherwise.
+ char* data() const;
+
+ private:
+ enum MapMode {
+ kMapReadOnly = 1,
+ kMapReadWrite = 2,
+ };
+
+ mutable int64_t file_size_; // May be updated in GetLength().
+ void* mapped_file_;
+ MapMode map_mode_;
+
+ DISALLOW_COPY_AND_ASSIGN(MappedFile);
+};
+
+} // namespace unix_file
+
+#endif // BASE_UNIX_FILE_MAPPED_FILE_H_
diff --git a/src/base/unix_file/mapped_file_test.cc b/src/base/unix_file/mapped_file_test.cc
new file mode 100644
index 0000000..f61ed3b
--- /dev/null
+++ b/src/base/unix_file/mapped_file_test.cc
@@ -0,0 +1,265 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "base/unix_file/mapped_file.h"
+#include "base/unix_file/fd_file.h"
+#include "base/unix_file/random_access_file_test.h"
+#include "base/unix_file/random_access_file_utils.h"
+#include "base/unix_file/string_file.h"
+#include "gtest/gtest.h"
+#include "logging.h"
+
+namespace unix_file {
+
+class MappedFileTest : public RandomAccessFileTest {
+ protected:
+ MappedFileTest() : kContent("some content") {
+ }
+
+ void SetUp() {
+ art::CommonTest::SetEnvironmentVariables(android_data_);
+
+ good_path_ = GetTmpPath("some-file.txt");
+ int fd = TEMP_FAILURE_RETRY(open(good_path_.c_str(), O_CREAT|O_RDWR, 0666));
+ FdFile dst(fd);
+
+ StringFile src;
+ src.Assign(kContent);
+
+ ASSERT_TRUE(CopyFile(src, &dst));
+ }
+
+ virtual RandomAccessFile* MakeTestFile() {
+ TEMP_FAILURE_RETRY(truncate(good_path_.c_str(), 0));
+ MappedFile* f = new MappedFile;
+ CHECK(f->Open(good_path_, MappedFile::kReadWriteMode));
+ return f;
+ }
+
+ const std::string kContent;
+ std::string good_path_;
+};
+
+TEST_F(MappedFileTest, OkayToNotUse) {
+ MappedFile file;
+ EXPECT_EQ(-1, file.Fd());
+ EXPECT_FALSE(file.IsOpened());
+ EXPECT_FALSE(file.IsMapped());
+}
+
+TEST_F(MappedFileTest, OpenClose) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode));
+ EXPECT_GE(file.Fd(), 0);
+ EXPECT_TRUE(file.IsOpened());
+ EXPECT_EQ(kContent.size(), file.size());
+ EXPECT_EQ(0, file.Close());
+ EXPECT_EQ(-1, file.Fd());
+ EXPECT_FALSE(file.IsOpened());
+}
+
+TEST_F(MappedFileTest, OpenFdClose) {
+ FILE* f = tmpfile();
+ ASSERT_TRUE(f != NULL);
+ MappedFile file(fileno(f));
+ EXPECT_GE(file.Fd(), 0);
+ EXPECT_TRUE(file.IsOpened());
+ EXPECT_EQ(0, file.Close());
+}
+
+TEST_F(MappedFileTest, CanUseAfterMapReadOnly) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode));
+ EXPECT_FALSE(file.IsMapped());
+ EXPECT_TRUE(file.MapReadOnly());
+ EXPECT_TRUE(file.IsMapped());
+ EXPECT_EQ(kContent.size(), file.size());
+ ASSERT_TRUE(file.data());
+ EXPECT_EQ(0, memcmp(kContent.c_str(), file.data(), file.size()));
+ EXPECT_EQ(0, file.Flush());
+}
+
+TEST_F(MappedFileTest, CanUseAfterMapReadWrite) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadWriteMode));
+ EXPECT_FALSE(file.IsMapped());
+ EXPECT_TRUE(file.MapReadWrite(1));
+ EXPECT_TRUE(file.IsMapped());
+ EXPECT_EQ(1, file.size());
+ ASSERT_TRUE(file.data());
+ EXPECT_EQ(kContent[0], *file.data());
+ EXPECT_EQ(0, file.Flush());
+}
+
+TEST_F(MappedFileTest, CanWriteNewData) {
+ const std::string new_path(GetTmpPath("new-file.txt"));
+ ASSERT_EQ(-1, unlink(new_path.c_str()));
+ ASSERT_EQ(ENOENT, errno);
+
+ MappedFile file;
+ ASSERT_TRUE(file.Open(new_path, MappedFile::kReadWriteMode));
+ EXPECT_TRUE(file.MapReadWrite(kContent.size()));
+ EXPECT_TRUE(file.IsMapped());
+ EXPECT_EQ(kContent.size(), file.size());
+ ASSERT_TRUE(file.data());
+ memcpy(file.data(), kContent.c_str(), kContent.size());
+ EXPECT_EQ(0, file.Close());
+ EXPECT_FALSE(file.IsMapped());
+
+ FdFile new_file(TEMP_FAILURE_RETRY(open(new_path.c_str(), O_RDONLY)));
+ StringFile buffer;
+ ASSERT_TRUE(CopyFile(new_file, &buffer));
+ EXPECT_EQ(kContent, buffer.ToStringPiece());
+ EXPECT_EQ(0, unlink(new_path.c_str()));
+}
+
+TEST_F(MappedFileTest, FileMustExist) {
+ const std::string bad_path(GetTmpPath("does-not-exist.txt"));
+ MappedFile file;
+ EXPECT_FALSE(file.Open(bad_path, MappedFile::kReadOnlyMode));
+ EXPECT_EQ(-1, file.Fd());
+}
+
+TEST_F(MappedFileTest, FileMustBeWritable) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode));
+ EXPECT_FALSE(file.MapReadWrite(10));
+}
+
+TEST_F(MappedFileTest, RemappingAllowedUntilSuccess) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode));
+ EXPECT_FALSE(file.MapReadWrite(10));
+ EXPECT_FALSE(file.MapReadWrite(10));
+}
+
+TEST_F(MappedFileTest, ResizeMappedFile) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadWriteMode));
+ ASSERT_TRUE(file.MapReadWrite(10));
+ EXPECT_EQ(10, file.GetLength());
+ EXPECT_TRUE(file.Unmap());
+ EXPECT_TRUE(file.MapReadWrite(20));
+ EXPECT_EQ(20, file.GetLength());
+ EXPECT_EQ(0, file.Flush());
+ EXPECT_TRUE(file.Unmap());
+ EXPECT_EQ(0, file.Flush());
+ EXPECT_EQ(0, file.SetLength(5));
+ EXPECT_TRUE(file.MapReadOnly());
+ EXPECT_EQ(5, file.GetLength());
+}
+
+TEST_F(MappedFileTest, ReadNotMapped) {
+ TestRead();
+}
+
+TEST_F(MappedFileTest, SetLengthNotMapped) {
+ TestSetLength();
+}
+
+TEST_F(MappedFileTest, WriteNotMapped) {
+ TestWrite();
+}
+
+TEST_F(MappedFileTest, ReadMappedReadOnly) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode));
+ ASSERT_TRUE(file.MapReadOnly());
+ TestReadContent(kContent, &file);
+}
+
+TEST_F(MappedFileTest, ReadMappedReadWrite) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadWriteMode));
+ ASSERT_TRUE(file.MapReadWrite(kContent.size()));
+ TestReadContent(kContent, &file);
+}
+
+TEST_F(MappedFileTest, WriteMappedReadWrite) {
+ TEMP_FAILURE_RETRY(unlink(good_path_.c_str()));
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadWriteMode));
+ ASSERT_TRUE(file.MapReadWrite(kContent.size()));
+
+ // Can't write to a negative offset.
+ EXPECT_EQ(-EINVAL, file.Write(kContent.c_str(), 0, -123));
+
+ // A zero-length write is a no-op.
+ EXPECT_EQ(0, file.Write(kContent.c_str(), 0, 0));
+ // But the file size is as given when mapped.
+ EXPECT_EQ(kContent.size(), file.GetLength());
+
+ // Data written past the end are discarded.
+ EXPECT_EQ(kContent.size() - 1,
+ file.Write(kContent.c_str(), kContent.size(), 1));
+ EXPECT_EQ(0, memcmp(kContent.c_str(), file.data() + 1, kContent.size() - 1));
+
+ // Data can be overwritten.
+ EXPECT_EQ(kContent.size(), file.Write(kContent.c_str(), kContent.size(), 0));
+ EXPECT_EQ(0, memcmp(kContent.c_str(), file.data(), kContent.size()));
+}
+
+#if 0 // death tests don't work on android yet
+
+class MappedFileDeathTest : public MappedFileTest {};
+
+TEST_F(MappedFileDeathTest, MustMapBeforeUse) {
+ MappedFile file;
+ EXPECT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode));
+ EXPECT_DEATH(file.data(), "mapped_");
+}
+
+TEST_F(MappedFileDeathTest, RemappingNotAllowedReadOnly) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode));
+ ASSERT_TRUE(file.MapReadOnly());
+ EXPECT_DEATH(file.MapReadOnly(), "mapped_");
+}
+
+TEST_F(MappedFileDeathTest, RemappingNotAllowedReadWrite) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadWriteMode));
+ ASSERT_TRUE(file.MapReadWrite(10));
+ EXPECT_DEATH(file.MapReadWrite(10), "mapped_");
+}
+
+TEST_F(MappedFileDeathTest, SetLengthMappedReadWrite) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadWriteMode));
+ ASSERT_TRUE(file.MapReadWrite(10));
+ EXPECT_EQ(10, file.GetLength());
+ EXPECT_DEATH(file.SetLength(0), ".*");
+}
+
+TEST_F(MappedFileDeathTest, SetLengthMappedReadOnly) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode));
+ ASSERT_TRUE(file.MapReadOnly());
+ EXPECT_EQ(kContent.size(), file.GetLength());
+ EXPECT_DEATH(file.SetLength(0), ".*");
+}
+
+TEST_F(MappedFileDeathTest, WriteMappedReadOnly) {
+ MappedFile file;
+ ASSERT_TRUE(file.Open(good_path_, MappedFile::kReadOnlyMode));
+ ASSERT_TRUE(file.MapReadOnly());
+ char buf[10];
+ EXPECT_DEATH(file.Write(buf, 0, 0), ".*");
+}
+
+#endif
+
+} // namespace unix_file
diff --git a/src/base/unix_file/null_file.cc b/src/base/unix_file/null_file.cc
new file mode 100644
index 0000000..050decb
--- /dev/null
+++ b/src/base/unix_file/null_file.cc
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "base/unix_file/null_file.h"
+#include <errno.h>
+
+namespace unix_file {
+
+NullFile::NullFile() {
+}
+
+NullFile::~NullFile() {
+}
+
+int NullFile::Close() {
+ return 0;
+}
+
+int NullFile::Flush() {
+ return 0;
+}
+
+int64_t NullFile::Read(char* buf, int64_t byte_count, int64_t offset) const {
+ if (offset < 0) {
+ return -EINVAL;
+ }
+ return 0;
+}
+
+int NullFile::SetLength(int64_t new_length) {
+ if (new_length < 0) {
+ return -EINVAL;
+ }
+ return 0;
+}
+
+int64_t NullFile::GetLength() const {
+ return 0;
+}
+
+int64_t NullFile::Write(const char* buf, int64_t byte_count, int64_t offset) {
+ if (offset < 0) {
+ return -EINVAL;
+ }
+ return byte_count;
+}
+
+} // namespace unix_file
diff --git a/src/base/unix_file/null_file.h b/src/base/unix_file/null_file.h
new file mode 100644
index 0000000..e716603
--- /dev/null
+++ b/src/base/unix_file/null_file.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef BASE_UNIX_FILE_NULL_FILE_H_
+#define BASE_UNIX_FILE_NULL_FILE_H_
+
+#include "base/unix_file/random_access_file.h"
+#include "base/macros.h"
+
+namespace unix_file {
+
+// A RandomAccessFile implementation equivalent to /dev/null. Writes are
+// discarded, and there's no data to be read. Callers could use FdFile in
+// conjunction with /dev/null, but that's not portable and costs a file
+// descriptor. NullFile is "free".
+//
+// Thread safe.
+class NullFile : public RandomAccessFile {
+ public:
+ NullFile();
+ virtual ~NullFile();
+
+ // RandomAccessFile API.
+ virtual int Close();
+ virtual int Flush();
+ virtual int64_t Read(char* buf, int64_t byte_count, int64_t offset) const;
+ virtual int SetLength(int64_t new_length);
+ virtual int64_t GetLength() const;
+ virtual int64_t Write(const char* buf, int64_t byte_count, int64_t offset);
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(NullFile);
+};
+
+} // namespace unix_file
+
+#endif // BASE_UNIX_FILE_NULL_FILE_H_
diff --git a/src/base/unix_file/null_file_test.cc b/src/base/unix_file/null_file_test.cc
new file mode 100644
index 0000000..0f20acd
--- /dev/null
+++ b/src/base/unix_file/null_file_test.cc
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "base/unix_file/null_file.h"
+
+#include <errno.h>
+
+#include "gtest/gtest.h"
+
+namespace unix_file {
+
+class NullFileTest : public testing::Test { };
+
+TEST_F(NullFileTest, Read) {
+ NullFile f;
+ char buf[256];
+ // You can't read a negative number of bytes...
+ ASSERT_EQ(-EINVAL, f.Read(buf, 0, -1));
+ // ...but everything else is fine (though you'll get no data).
+ ASSERT_EQ(0, f.Read(buf, 128, 0));
+ ASSERT_EQ(0, f.Read(buf, 128, 128));
+}
+
+TEST_F(NullFileTest, SetLength) {
+ NullFile f;
+ // You can't set a negative length...
+ ASSERT_EQ(-EINVAL, f.SetLength(-1));
+ // ...but everything else is fine.
+ ASSERT_EQ(0, f.SetLength(0));
+ ASSERT_EQ(0, f.SetLength(128));
+}
+
+TEST_F(NullFileTest, GetLength) {
+ const std::string content("hello");
+ NullFile f;
+ // The length is always 0.
+ ASSERT_EQ(0, f.GetLength());
+ ASSERT_EQ(content.size(), f.Write(content.data(), content.size(), 0));
+ ASSERT_EQ(0, f.GetLength());
+}
+
+TEST_F(NullFileTest, Write) {
+ const std::string content("hello");
+ NullFile f;
+ // You can't write at a negative offset...
+ ASSERT_EQ(-EINVAL, f.Write(content.data(), content.size(), -128));
+ // But you can write anywhere else...
+ ASSERT_EQ(content.size(), f.Write(content.data(), content.size(), 0));
+ ASSERT_EQ(content.size(), f.Write(content.data(), content.size(), 128));
+ // ...though the file will remain empty.
+ ASSERT_EQ(0, f.GetLength());
+}
+
+} // namespace unix_file
diff --git a/src/base/unix_file/random_access_file.h b/src/base/unix_file/random_access_file.h
new file mode 100644
index 0000000..22da37f
--- /dev/null
+++ b/src/base/unix_file/random_access_file.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef BASE_UNIX_FILE_RANDOM_ACCESS_FILE_H_
+#define BASE_UNIX_FILE_RANDOM_ACCESS_FILE_H_
+
+#include <stdint.h>
+
+namespace unix_file {
+
+// A file interface supporting random-access reading and writing of content,
+// along with the ability to set the length of a file (smaller or greater than
+// its current extent).
+//
+// This interface does not support a stream position (i.e. every read or write
+// must specify an offset). This interface does not imply any buffering policy.
+//
+// All operations return >= 0 on success or -errno on failure.
+//
+// Implementations never return EINTR; callers are spared the need to manually
+// retry interrupted operations.
+//
+// Any concurrent access to files should be externally synchronized.
+class RandomAccessFile {
+ public:
+ virtual ~RandomAccessFile() { }
+
+ virtual int Close() = 0;
+
+ // Reads 'byte_count' bytes into 'buf' starting at offset 'offset' in the
+ // file. Returns the number of bytes actually read.
+ virtual int64_t Read(char* buf, int64_t byte_count, int64_t offset) const = 0;
+
+ // Sets the length of the file to 'new_length'. If this is smaller than the
+ // file's current extent, data is discarded. If this is greater than the
+ // file's current extent, it is as if a write of the relevant number of zero
+ // bytes occurred. Returns 0 on success.
+ virtual int SetLength(int64_t new_length) = 0;
+
+ // Returns the current size of this file.
+ virtual int64_t GetLength() const = 0;
+
+ // Writes 'byte_count' bytes from 'buf' starting at offset 'offset' in the
+ // file. Zero-byte writes are acceptable, and writes past the end are as if
+ // a write of the relevant number of zero bytes also occurred. Returns the
+ // number of bytes actually written.
+ virtual int64_t Write(const char* buf, int64_t byte_count, int64_t offset) = 0;
+
+ // Flushes file data.
+ virtual int Flush() = 0;
+};
+
+} // namespace unix_file
+
+#endif // BASE_UNIX_FILE_RANDOM_ACCESS_FILE_H_
diff --git a/src/base/unix_file/random_access_file_test.h b/src/base/unix_file/random_access_file_test.h
new file mode 100644
index 0000000..3baaeae
--- /dev/null
+++ b/src/base/unix_file/random_access_file_test.h
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef BASE_UNIX_FILE_RANDOM_ACCESS_FILE_TEST_H_
+#define BASE_UNIX_FILE_RANDOM_ACCESS_FILE_TEST_H_
+
+#include <errno.h>
+
+#include <string>
+
+#include "common_test.h"
+#include "gtest/gtest.h"
+#include "UniquePtr.h"
+
+namespace unix_file {
+
+class RandomAccessFileTest : public testing::Test {
+ protected:
+ virtual ~RandomAccessFileTest() {
+ }
+
+ // Override this to return an instance of the subclass under test that's
+ // backed by a temporary file.
+ virtual RandomAccessFile* MakeTestFile() = 0;
+
+ virtual void SetUp() {
+ art::CommonTest::SetEnvironmentVariables(android_data_);
+ }
+
+ std::string GetTmpPath(const std::string& name) {
+ std::string path;
+ path = android_data_;
+ path += "/";
+ path += name;
+ return path;
+ }
+
+ // TODO(enh): ReadString (and WriteString) might be generally useful.
+ static bool ReadString(RandomAccessFile* f, std::string* s) {
+ s->clear();
+ char buf[256];
+ int64_t n = 0;
+ int64_t offset = 0;
+ while ((n = f->Read(buf, sizeof(buf), offset)) > 0) {
+ s->append(buf, n);
+ offset += n;
+ }
+ return n != -1;
+ }
+
+ void TestRead() {
+ char buf[256];
+ UniquePtr<RandomAccessFile> file(MakeTestFile());
+
+ // Reading from the start of an empty file gets you zero bytes, however many
+ // you ask for.
+ ASSERT_EQ(0, file->Read(buf, 0, 0));
+ ASSERT_EQ(0, file->Read(buf, 123, 0));
+
+ const std::string content("hello");
+ ASSERT_EQ(content.size(), file->Write(content.data(), content.size(), 0));
+
+ TestReadContent(content, file.get());
+ }
+
+ void TestReadContent(const std::string& content, RandomAccessFile* file) {
+ const int buf_size = content.size() + 10;
+ UniquePtr<char> buf(new char[buf_size]);
+ // Can't read from a negative offset.
+ ASSERT_EQ(-EINVAL, file->Read(buf.get(), 0, -123));
+
+ // Reading too much gets us just what's in the file.
+ ASSERT_EQ(content.size(), file->Read(buf.get(), buf_size, 0));
+ ASSERT_EQ(std::string(buf.get(), content.size()), content);
+
+ // We only get as much as we ask for.
+ const size_t short_request = 2;
+ ASSERT_LT(short_request, content.size());
+ ASSERT_EQ(short_request, file->Read(buf.get(), short_request, 0));
+ ASSERT_EQ(std::string(buf.get(), short_request),
+ content.substr(0, short_request));
+
+ // We don't have to start at the beginning.
+ const int non_zero_offset = 2;
+ ASSERT_GT(non_zero_offset, 0);
+ ASSERT_EQ(short_request,
+ file->Read(buf.get(), short_request, non_zero_offset));
+ ASSERT_EQ(std::string(buf.get(), short_request),
+ content.substr(non_zero_offset, short_request));
+
+ // Reading past the end gets us nothing.
+ ASSERT_EQ(0, file->Read(buf.get(), buf_size, file->GetLength()));
+ ASSERT_EQ(0, file->Read(buf.get(), buf_size, file->GetLength() + 1));
+ }
+
+ void TestSetLength() {
+ const std::string content("hello");
+ UniquePtr<RandomAccessFile> file(MakeTestFile());
+ ASSERT_EQ(content.size(), file->Write(content.data(), content.size(), 0));
+ ASSERT_EQ(content.size(), file->GetLength());
+
+ // Can't give a file a negative length.
+ ASSERT_EQ(-EINVAL, file->SetLength(-123));
+
+ // Can truncate the file.
+ int64_t new_length = 2;
+ ASSERT_EQ(0, file->SetLength(new_length));
+ ASSERT_EQ(new_length, file->GetLength());
+ std::string new_content;
+ ASSERT_TRUE(ReadString(file.get(), &new_content));
+ ASSERT_EQ(content.substr(0, 2), new_content);
+
+ // Expanding the file appends zero bytes.
+ new_length = file->GetLength() + 1;
+ ASSERT_EQ(0, file->SetLength(new_length));
+ ASSERT_EQ(new_length, file->GetLength());
+ ASSERT_TRUE(ReadString(file.get(), &new_content));
+ ASSERT_EQ('\0', new_content[new_length - 1]);
+ }
+
+ void TestWrite() {
+ const std::string content("hello");
+ UniquePtr<RandomAccessFile> file(MakeTestFile());
+
+ // Can't write to a negative offset.
+ ASSERT_EQ(-EINVAL, file->Write(content.data(), 0, -123));
+
+ // Writing zero bytes of data is a no-op.
+ ASSERT_EQ(0, file->Write(content.data(), 0, 0));
+ ASSERT_EQ(0, file->GetLength());
+
+ // We can write data.
+ ASSERT_EQ(content.size(), file->Write(content.data(), content.size(), 0));
+ ASSERT_EQ(content.size(), file->GetLength());
+ std::string new_content;
+ ASSERT_TRUE(ReadString(file.get(), &new_content));
+ ASSERT_EQ(new_content, content);
+
+ // We can read it back.
+ char buf[256];
+ ASSERT_EQ(content.size(), file->Read(buf, sizeof(buf), 0));
+ ASSERT_EQ(std::string(buf, content.size()), content);
+
+ // We can append data past the end.
+ ASSERT_EQ(content.size(),
+ file->Write(content.data(), content.size(), file->GetLength() + 1));
+ int64_t new_length = 2*content.size() + 1;
+ ASSERT_EQ(file->GetLength(), new_length);
+ ASSERT_TRUE(ReadString(file.get(), &new_content));
+ ASSERT_EQ(std::string("hello\0hello", new_length), new_content);
+ }
+
+ protected:
+ std::string android_data_;
+};
+
+} // namespace unix_file
+
+#endif // BASE_UNIX_FILE_RANDOM_ACCESS_FILE_TEST_H_
diff --git a/src/base/unix_file/random_access_file_utils.cc b/src/base/unix_file/random_access_file_utils.cc
new file mode 100644
index 0000000..df3b308
--- /dev/null
+++ b/src/base/unix_file/random_access_file_utils.cc
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vector>
+#include "base/unix_file/random_access_file_utils.h"
+#include "base/unix_file/random_access_file.h"
+
+namespace unix_file {
+
+bool CopyFile(const RandomAccessFile& src, RandomAccessFile* dst) {
+ // We don't call src->GetLength because some files (those in /proc, say)
+ // don't know how long they are. We just read until there's nothing left.
+ std::vector<char> buf(4096);
+ int64_t offset = 0;
+ int64_t n;
+ while ((n = src.Read(&buf[0], buf.size(), offset)) > 0) {
+ if (dst->Write(&buf[0], n, offset) != n) {
+ return false;
+ }
+ offset += n;
+ }
+ return n >= 0;
+}
+
+} // namespace unix_file
diff --git a/src/base/unix_file/random_access_file_utils.h b/src/base/unix_file/random_access_file_utils.h
new file mode 100644
index 0000000..0535ead
--- /dev/null
+++ b/src/base/unix_file/random_access_file_utils.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef BASE_UNIX_FILE_RANDOM_ACCESS_FILE_UTILS_H_
+#define BASE_UNIX_FILE_RANDOM_ACCESS_FILE_UTILS_H_
+
+namespace unix_file {
+
+class RandomAccessFile;
+
+// Copies from 'src' to 'dst'. Reads all the data from 'src', and writes it
+// to 'dst'. Not thread-safe. Neither file will be closed.
+bool CopyFile(const RandomAccessFile& src, RandomAccessFile* dst);
+
+} // namespace unix_file
+
+#endif // BASE_UNIX_FILE_RANDOM_ACCESS_FILE_UTILS_H_
diff --git a/src/base/unix_file/random_access_file_utils_test.cc b/src/base/unix_file/random_access_file_utils_test.cc
new file mode 100644
index 0000000..6317922
--- /dev/null
+++ b/src/base/unix_file/random_access_file_utils_test.cc
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "base/unix_file/random_access_file_utils.h"
+#include "base/unix_file/fd_file.h"
+#include "base/unix_file/string_file.h"
+#include "gtest/gtest.h"
+
+namespace unix_file {
+
+class RandomAccessFileUtilsTest : public testing::Test { };
+
+TEST_F(RandomAccessFileUtilsTest, CopyFile) {
+ StringFile src;
+ StringFile dst;
+
+ const std::string content("hello");
+ src.Assign(content);
+ ASSERT_EQ(src.ToStringPiece(), content);
+ ASSERT_EQ(dst.ToStringPiece(), "");
+
+ ASSERT_TRUE(CopyFile(src, &dst));
+ ASSERT_EQ(src.ToStringPiece(), dst.ToStringPiece());
+}
+
+TEST_F(RandomAccessFileUtilsTest, BadSrc) {
+ FdFile src(-1);
+ StringFile dst;
+ ASSERT_FALSE(CopyFile(src, &dst));
+}
+
+TEST_F(RandomAccessFileUtilsTest, BadDst) {
+ StringFile src;
+ FdFile dst(-1);
+
+ // We need some source content to trigger a write.
+ // Copying an empty file is a no-op.
+ src.Assign("hello");
+
+ ASSERT_FALSE(CopyFile(src, &dst));
+}
+
+} // namespace unix_file
diff --git a/src/base/unix_file/string_file.cc b/src/base/unix_file/string_file.cc
new file mode 100644
index 0000000..5d47b17
--- /dev/null
+++ b/src/base/unix_file/string_file.cc
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "base/unix_file/string_file.h"
+#include <errno.h>
+#include <algorithm>
+#include "logging.h"
+
+namespace unix_file {
+
+StringFile::StringFile() {
+}
+
+StringFile::~StringFile() {
+}
+
+int StringFile::Close() {
+ return 0;
+}
+
+int StringFile::Flush() {
+ return 0;
+}
+
+int64_t StringFile::Read(char *buf, int64_t byte_count, int64_t offset) const {
+ CHECK(buf);
+ CHECK_GE(byte_count, 0);
+
+ if (offset < 0) {
+ return -EINVAL;
+ }
+
+ const int64_t available_bytes = std::min(byte_count, GetLength() - offset);
+ if (available_bytes < 0) {
+ return 0; // Not an error, but nothing for us to do, either.
+ }
+ memcpy(buf, data_.data() + offset, available_bytes);
+ return available_bytes;
+}
+
+int StringFile::SetLength(int64_t new_length) {
+ if (new_length < 0) {
+ return -EINVAL;
+ }
+ data_.resize(new_length);
+ return 0;
+}
+
+int64_t StringFile::GetLength() const {
+ return data_.size();
+}
+
+int64_t StringFile::Write(const char *buf, int64_t byte_count, int64_t offset) {
+ CHECK(buf);
+ CHECK_GE(byte_count, 0);
+
+ if (offset < 0) {
+ return -EINVAL;
+ }
+
+ if (byte_count == 0) {
+ return 0;
+ }
+
+ // FUSE seems happy to allow writes past the end. (I'd guess it doesn't
+ // synthesize a write of zero bytes so that we're free to implement sparse
+ // files.) GNU as(1) seems to require such writes. Those files are small.
+ const int64_t bytes_past_end = offset - GetLength();
+ if (bytes_past_end > 0) {
+ data_.append(bytes_past_end, '\0');
+ }
+
+ data_.replace(offset, byte_count, buf, byte_count);
+ return byte_count;
+}
+
+void StringFile::Assign(const art::StringPiece &new_data) {
+ data_.assign(new_data.data(), new_data.size());
+}
+
+const art::StringPiece StringFile::ToStringPiece() const {
+ return data_;
+}
+
+} // namespace unix_file
diff --git a/src/base/unix_file/string_file.h b/src/base/unix_file/string_file.h
new file mode 100644
index 0000000..4277dc2
--- /dev/null
+++ b/src/base/unix_file/string_file.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef BASE_UNIX_FILE_STRING_FILE_H_
+#define BASE_UNIX_FILE_STRING_FILE_H_
+
+#include <stdint.h>
+
+#include <string>
+
+#include "base/macros.h"
+#include "base/unix_file/random_access_file.h"
+#include "stringpiece.h"
+
+namespace unix_file {
+
+// A RandomAccessFile implementation backed by a std::string. (That is, all data is
+// kept in memory.)
+//
+// Not thread safe.
+class StringFile : public RandomAccessFile {
+ public:
+ StringFile();
+ virtual ~StringFile();
+
+ // RandomAccessFile API.
+ virtual int Close();
+ virtual int Flush();
+ virtual int64_t Read(char* buf, int64_t byte_count, int64_t offset) const;
+ virtual int SetLength(int64_t new_length);
+ virtual int64_t GetLength() const;
+ virtual int64_t Write(const char* buf, int64_t byte_count, int64_t offset);
+
+ // Bonus API.
+ void Assign(const art::StringPiece& new_data);
+ const art::StringPiece ToStringPiece() const;
+
+ private:
+ std::string data_;
+
+ DISALLOW_COPY_AND_ASSIGN(StringFile);
+};
+
+} // namespace unix_file
+
+#endif // BASE_UNIX_FILE_STRING_FILE_H_
diff --git a/src/base/unix_file/string_file_test.cc b/src/base/unix_file/string_file_test.cc
new file mode 100644
index 0000000..8821461
--- /dev/null
+++ b/src/base/unix_file/string_file_test.cc
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "base/unix_file/string_file.h"
+#include "base/unix_file/random_access_file_test.h"
+#include "gtest/gtest.h"
+
+namespace unix_file {
+
+class StringFileTest : public RandomAccessFileTest {
+ protected:
+ virtual RandomAccessFile* MakeTestFile() {
+ return new StringFile;
+ }
+};
+
+TEST_F(StringFileTest, Read) {
+ TestRead();
+}
+
+TEST_F(StringFileTest, SetLength) {
+ TestSetLength();
+}
+
+TEST_F(StringFileTest, Write) {
+ TestWrite();
+}
+
+} // namespace unix_file