Move most of runtime/base to libartbase/base
Enforce the layering that code in runtime/base should not depend on
runtime by separating it into libartbase. Some of the code in
runtime/base depends on the Runtime class, so it cannot be moved yet.
Also, some of the tests depend on CommonRuntimeTest, which itself needs
to be factored (in a subsequent CL).
Bug: 22322814
Test: make -j 50 checkbuild
make -j 50 test-art-host
Change-Id: I8b096c1e2542f829eb456b4b057c71421b77d7e2
diff --git a/libartbase/base/unix_file/README b/libartbase/base/unix_file/README
new file mode 100644
index 0000000..e9aec22
--- /dev/null
+++ b/libartbase/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/libartbase/base/unix_file/fd_file.cc b/libartbase/base/unix_file/fd_file.cc
new file mode 100644
index 0000000..f9da178
--- /dev/null
+++ b/libartbase/base/unix_file/fd_file.cc
@@ -0,0 +1,481 @@
+/*
+ * 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 <limits>
+
+#include <android-base/logging.h>
+
+// Includes needed for FdFile::Copy().
+#ifdef __linux__
+#include <sys/sendfile.h>
+#else
+#include <algorithm>
+#include "base/stl_util.h"
+#include "globals.h"
+#endif
+
+namespace unix_file {
+
+FdFile::FdFile()
+ : guard_state_(GuardState::kClosed), fd_(-1), auto_close_(true), read_only_mode_(false) {
+}
+
+FdFile::FdFile(int fd, bool check_usage)
+ : guard_state_(check_usage ? GuardState::kBase : GuardState::kNoCheck),
+ fd_(fd), auto_close_(true), read_only_mode_(false) {
+}
+
+FdFile::FdFile(int fd, const std::string& path, bool check_usage)
+ : FdFile(fd, path, check_usage, false) {
+}
+
+FdFile::FdFile(int fd, const std::string& path, bool check_usage, bool read_only_mode)
+ : guard_state_(check_usage ? GuardState::kBase : GuardState::kNoCheck),
+ fd_(fd), file_path_(path), auto_close_(true), read_only_mode_(read_only_mode) {
+}
+
+FdFile::FdFile(const std::string& path, int flags, mode_t mode, bool check_usage)
+ : fd_(-1), auto_close_(true) {
+ Open(path, flags, mode);
+ if (!check_usage || !IsOpened()) {
+ guard_state_ = GuardState::kNoCheck;
+ }
+}
+
+void FdFile::Destroy() {
+ if (kCheckSafeUsage && (guard_state_ < GuardState::kNoCheck)) {
+ if (guard_state_ < GuardState::kFlushed) {
+ LOG(ERROR) << "File " << file_path_ << " wasn't explicitly flushed before destruction.";
+ }
+ if (guard_state_ < GuardState::kClosed) {
+ LOG(ERROR) << "File " << file_path_ << " wasn't explicitly closed before destruction.";
+ }
+ DCHECK_GE(guard_state_, GuardState::kClosed);
+ }
+ if (auto_close_ && fd_ != -1) {
+ if (Close() != 0) {
+ PLOG(WARNING) << "Failed to close file with fd=" << fd_ << " path=" << file_path_;
+ }
+ }
+}
+
+FdFile& FdFile::operator=(FdFile&& other) {
+ if (this == &other) {
+ return *this;
+ }
+
+ if (this->fd_ != other.fd_) {
+ Destroy(); // Free old state.
+ }
+
+ guard_state_ = other.guard_state_;
+ fd_ = other.fd_;
+ file_path_ = std::move(other.file_path_);
+ auto_close_ = other.auto_close_;
+ read_only_mode_ = other.read_only_mode_;
+ other.Release(); // Release other.
+
+ return *this;
+}
+
+FdFile::~FdFile() {
+ Destroy();
+}
+
+void FdFile::moveTo(GuardState target, GuardState warn_threshold, const char* warning) {
+ if (kCheckSafeUsage) {
+ if (guard_state_ < GuardState::kNoCheck) {
+ if (warn_threshold < GuardState::kNoCheck && guard_state_ >= warn_threshold) {
+ LOG(ERROR) << warning;
+ }
+ guard_state_ = target;
+ }
+ }
+}
+
+void FdFile::moveUp(GuardState target, const char* warning) {
+ if (kCheckSafeUsage) {
+ if (guard_state_ < GuardState::kNoCheck) {
+ if (guard_state_ < target) {
+ guard_state_ = target;
+ } else if (target < guard_state_) {
+ LOG(ERROR) << warning;
+ }
+ }
+ }
+}
+
+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) {
+ static_assert(O_RDONLY == 0, "Readonly flag has unexpected value.");
+ DCHECK_EQ(fd_, -1) << path;
+ read_only_mode_ = ((flags & O_ACCMODE) == O_RDONLY);
+ fd_ = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
+ if (fd_ == -1) {
+ return false;
+ }
+ file_path_ = path;
+ if (kCheckSafeUsage && (flags & (O_RDWR | O_CREAT | O_WRONLY)) != 0) {
+ // Start in the base state (not flushed, not closed).
+ guard_state_ = GuardState::kBase;
+ } else {
+ // We are not concerned with read-only files. In that case, proper flushing and closing is
+ // not important.
+ guard_state_ = GuardState::kNoCheck;
+ }
+ return true;
+}
+
+int FdFile::Close() {
+ int result = close(fd_);
+
+ // Test here, so the file is closed and not leaked.
+ if (kCheckSafeUsage) {
+ DCHECK_GE(guard_state_, GuardState::kFlushed) << "File " << file_path_
+ << " has not been flushed before closing.";
+ moveUp(GuardState::kClosed, nullptr);
+ }
+
+#if defined(__linux__)
+ // close always succeeds on linux, even if failure is reported.
+ UNUSED(result);
+#else
+ if (result == -1) {
+ return -errno;
+ }
+#endif
+
+ fd_ = -1;
+ file_path_ = "";
+ return 0;
+}
+
+int FdFile::Flush() {
+ DCHECK(!read_only_mode_);
+
+#ifdef __linux__
+ int rc = TEMP_FAILURE_RETRY(fdatasync(fd_));
+#else
+ int rc = TEMP_FAILURE_RETRY(fsync(fd_));
+#endif
+
+ moveUp(GuardState::kFlushed, "Flushing closed file.");
+ if (rc == 0) {
+ return 0;
+ }
+
+ // Don't report failure if we just tried to flush a pipe or socket.
+ return errno == EINVAL ? 0 : -errno;
+}
+
+int64_t FdFile::Read(char* buf, int64_t byte_count, int64_t offset) const {
+#ifdef __linux__
+ int rc = TEMP_FAILURE_RETRY(pread64(fd_, buf, byte_count, offset));
+#else
+ int rc = TEMP_FAILURE_RETRY(pread(fd_, buf, byte_count, offset));
+#endif
+ return (rc == -1) ? -errno : rc;
+}
+
+int FdFile::SetLength(int64_t new_length) {
+ DCHECK(!read_only_mode_);
+#ifdef __linux__
+ int rc = TEMP_FAILURE_RETRY(ftruncate64(fd_, new_length));
+#else
+ int rc = TEMP_FAILURE_RETRY(ftruncate(fd_, new_length));
+#endif
+ moveTo(GuardState::kBase, GuardState::kClosed, "Truncating closed file.");
+ 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) {
+ DCHECK(!read_only_mode_);
+#ifdef __linux__
+ int rc = TEMP_FAILURE_RETRY(pwrite64(fd_, buf, byte_count, offset));
+#else
+ int rc = TEMP_FAILURE_RETRY(pwrite(fd_, buf, byte_count, offset));
+#endif
+ moveTo(GuardState::kBase, GuardState::kClosed, "Writing into closed file.");
+ return (rc == -1) ? -errno : rc;
+}
+
+int FdFile::Fd() const {
+ return fd_;
+}
+
+bool FdFile::ReadOnlyMode() const {
+ return read_only_mode_;
+}
+
+bool FdFile::CheckUsage() const {
+ return guard_state_ != GuardState::kNoCheck;
+}
+
+bool FdFile::IsOpened() const {
+ return fd_ >= 0;
+}
+
+static ssize_t ReadIgnoreOffset(int fd, void *buf, size_t count, off_t offset) {
+ DCHECK_EQ(offset, 0);
+ return read(fd, buf, count);
+}
+
+template <ssize_t (*read_func)(int, void*, size_t, off_t)>
+static bool ReadFullyGeneric(int fd, void* buffer, size_t byte_count, size_t offset) {
+ char* ptr = static_cast<char*>(buffer);
+ while (byte_count > 0) {
+ ssize_t bytes_read = TEMP_FAILURE_RETRY(read_func(fd, ptr, byte_count, offset));
+ if (bytes_read <= 0) {
+ // 0: end of file
+ // -1: error
+ return false;
+ }
+ byte_count -= bytes_read; // Reduce the number of remaining bytes.
+ ptr += bytes_read; // Move the buffer forward.
+ offset += static_cast<size_t>(bytes_read); // Move the offset forward.
+ }
+ return true;
+}
+
+bool FdFile::ReadFully(void* buffer, size_t byte_count) {
+ return ReadFullyGeneric<ReadIgnoreOffset>(fd_, buffer, byte_count, 0);
+}
+
+bool FdFile::PreadFully(void* buffer, size_t byte_count, size_t offset) {
+ return ReadFullyGeneric<pread>(fd_, buffer, byte_count, offset);
+}
+
+template <bool kUseOffset>
+bool FdFile::WriteFullyGeneric(const void* buffer, size_t byte_count, size_t offset) {
+ DCHECK(!read_only_mode_);
+ moveTo(GuardState::kBase, GuardState::kClosed, "Writing into closed file.");
+ DCHECK(kUseOffset || offset == 0u);
+ const char* ptr = static_cast<const char*>(buffer);
+ while (byte_count > 0) {
+ ssize_t bytes_written = kUseOffset
+ ? TEMP_FAILURE_RETRY(pwrite(fd_, ptr, byte_count, offset))
+ : TEMP_FAILURE_RETRY(write(fd_, ptr, byte_count));
+ if (bytes_written == -1) {
+ return false;
+ }
+ byte_count -= bytes_written; // Reduce the number of remaining bytes.
+ ptr += bytes_written; // Move the buffer forward.
+ offset += static_cast<size_t>(bytes_written);
+ }
+ return true;
+}
+
+bool FdFile::PwriteFully(const void* buffer, size_t byte_count, size_t offset) {
+ return WriteFullyGeneric<true>(buffer, byte_count, offset);
+}
+
+bool FdFile::WriteFully(const void* buffer, size_t byte_count) {
+ return WriteFullyGeneric<false>(buffer, byte_count, 0u);
+}
+
+bool FdFile::Copy(FdFile* input_file, int64_t offset, int64_t size) {
+ DCHECK(!read_only_mode_);
+ off_t off = static_cast<off_t>(offset);
+ off_t sz = static_cast<off_t>(size);
+ if (offset < 0 || static_cast<int64_t>(off) != offset ||
+ size < 0 || static_cast<int64_t>(sz) != size ||
+ sz > std::numeric_limits<off_t>::max() - off) {
+ errno = EINVAL;
+ return false;
+ }
+ if (size == 0) {
+ return true;
+ }
+#ifdef __linux__
+ // Use sendfile(), available for files since linux kernel 2.6.33.
+ off_t end = off + sz;
+ while (off != end) {
+ int result = TEMP_FAILURE_RETRY(
+ sendfile(Fd(), input_file->Fd(), &off, end - off));
+ if (result == -1) {
+ return false;
+ }
+ // Ignore the number of bytes in `result`, sendfile() already updated `off`.
+ }
+#else
+ if (lseek(input_file->Fd(), off, SEEK_SET) != off) {
+ return false;
+ }
+ constexpr size_t kMaxBufferSize = 4 * ::art::kPageSize;
+ const size_t buffer_size = std::min<uint64_t>(size, kMaxBufferSize);
+ art::UniqueCPtr<void> buffer(malloc(buffer_size));
+ if (buffer == nullptr) {
+ errno = ENOMEM;
+ return false;
+ }
+ while (size != 0) {
+ size_t chunk_size = std::min<uint64_t>(buffer_size, size);
+ if (!input_file->ReadFully(buffer.get(), chunk_size) ||
+ !WriteFully(buffer.get(), chunk_size)) {
+ return false;
+ }
+ size -= chunk_size;
+ }
+#endif
+ return true;
+}
+
+bool FdFile::Unlink() {
+ if (file_path_.empty()) {
+ return false;
+ }
+
+ // Try to figure out whether this file is still referring to the one on disk.
+ bool is_current = false;
+ {
+ struct stat this_stat, current_stat;
+ int cur_fd = TEMP_FAILURE_RETRY(open(file_path_.c_str(), O_RDONLY));
+ if (cur_fd > 0) {
+ // File still exists.
+ if (fstat(fd_, &this_stat) == 0 && fstat(cur_fd, ¤t_stat) == 0) {
+ is_current = (this_stat.st_dev == current_stat.st_dev) &&
+ (this_stat.st_ino == current_stat.st_ino);
+ }
+ close(cur_fd);
+ }
+ }
+
+ if (is_current) {
+ unlink(file_path_.c_str());
+ }
+
+ return is_current;
+}
+
+bool FdFile::Erase(bool unlink) {
+ DCHECK(!read_only_mode_);
+
+ bool ret_result = true;
+ if (unlink) {
+ ret_result = Unlink();
+ }
+
+ int result;
+ result = SetLength(0);
+ result = Flush();
+ result = Close();
+ // Ignore the errors.
+
+ return ret_result;
+}
+
+int FdFile::FlushCloseOrErase() {
+ DCHECK(!read_only_mode_);
+ int flush_result = Flush();
+ if (flush_result != 0) {
+ LOG(ERROR) << "CloseOrErase failed while flushing a file.";
+ Erase();
+ return flush_result;
+ }
+ int close_result = Close();
+ if (close_result != 0) {
+ LOG(ERROR) << "CloseOrErase failed while closing a file.";
+ Erase();
+ return close_result;
+ }
+ return 0;
+}
+
+int FdFile::FlushClose() {
+ DCHECK(!read_only_mode_);
+ int flush_result = Flush();
+ if (flush_result != 0) {
+ LOG(ERROR) << "FlushClose failed while flushing a file.";
+ }
+ int close_result = Close();
+ if (close_result != 0) {
+ LOG(ERROR) << "FlushClose failed while closing a file.";
+ }
+ return (flush_result != 0) ? flush_result : close_result;
+}
+
+void FdFile::MarkUnchecked() {
+ guard_state_ = GuardState::kNoCheck;
+}
+
+bool FdFile::ClearContent() {
+ DCHECK(!read_only_mode_);
+ if (SetLength(0) < 0) {
+ PLOG(ERROR) << "Failed to reset the length";
+ return false;
+ }
+ return ResetOffset();
+}
+
+bool FdFile::ResetOffset() {
+ DCHECK(!read_only_mode_);
+ off_t rc = TEMP_FAILURE_RETRY(lseek(fd_, 0, SEEK_SET));
+ if (rc == static_cast<off_t>(-1)) {
+ PLOG(ERROR) << "Failed to reset the offset";
+ return false;
+ }
+ return true;
+}
+
+int FdFile::Compare(FdFile* other) {
+ int64_t length = GetLength();
+ int64_t length2 = other->GetLength();
+ if (length != length2) {
+ return length < length2 ? -1 : 1;
+ }
+ static const size_t kBufferSize = 4096;
+ std::unique_ptr<uint8_t[]> buffer1(new uint8_t[kBufferSize]);
+ std::unique_ptr<uint8_t[]> buffer2(new uint8_t[kBufferSize]);
+ size_t offset = 0;
+ while (length > 0) {
+ size_t len = std::min(kBufferSize, static_cast<size_t>(length));
+ if (!PreadFully(&buffer1[0], len, offset)) {
+ return -1;
+ }
+ if (!other->PreadFully(&buffer2[0], len, offset)) {
+ return 1;
+ }
+ int result = memcmp(&buffer1[0], &buffer2[0], len);
+ if (result != 0) {
+ return result;
+ }
+ length -= len;
+ offset += len;
+ }
+ return 0;
+}
+
+} // namespace unix_file
diff --git a/libartbase/base/unix_file/fd_file.h b/libartbase/base/unix_file/fd_file.h
new file mode 100644
index 0000000..fe3317f
--- /dev/null
+++ b/libartbase/base/unix_file/fd_file.h
@@ -0,0 +1,195 @@
+/*
+ * 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 ART_LIBARTBASE_BASE_UNIX_FILE_FD_FILE_H_
+#define ART_LIBARTBASE_BASE_UNIX_FILE_FD_FILE_H_
+
+#include <fcntl.h>
+
+#include <string>
+
+#include "base/macros.h"
+#include "base/unix_file/random_access_file.h"
+
+namespace unix_file {
+
+// If true, check whether Flush and Close are called before destruction.
+static constexpr bool kCheckSafeUsage = true;
+
+// 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.)
+ FdFile(int fd, bool checkUsage);
+ FdFile(int fd, const std::string& path, bool checkUsage);
+ FdFile(int fd, const std::string& path, bool checkUsage, bool read_only_mode);
+
+ FdFile(const std::string& path, int flags, bool checkUsage)
+ : FdFile(path, flags, 0640, checkUsage) {}
+ FdFile(const std::string& path, int flags, mode_t mode, bool checkUsage);
+
+ // Move constructor.
+ FdFile(FdFile&& other)
+ : guard_state_(other.guard_state_),
+ fd_(other.fd_),
+ file_path_(std::move(other.file_path_)),
+ auto_close_(other.auto_close_),
+ read_only_mode_(other.read_only_mode_) {
+ other.Release(); // Release the src.
+ }
+
+ // Move assignment operator.
+ FdFile& operator=(FdFile&& other);
+
+ // Release the file descriptor. This will make further accesses to this FdFile invalid. Disables
+ // all further state checking.
+ int Release() {
+ int tmp_fd = fd_;
+ fd_ = -1;
+ guard_state_ = GuardState::kNoCheck;
+ auto_close_ = false;
+ return tmp_fd;
+ }
+
+ void Reset(int fd, bool check_usage) {
+ if (fd_ != -1 && fd_ != fd) {
+ Destroy();
+ }
+ fd_ = fd;
+ if (check_usage) {
+ guard_state_ = fd == -1 ? GuardState::kNoCheck : GuardState::kBase;
+ } else {
+ guard_state_ = GuardState::kNoCheck;
+ }
+ // Keep the auto_close_ state.
+ }
+
+ // 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();
+
+ // RandomAccessFile API.
+ int Close() OVERRIDE WARN_UNUSED;
+ int64_t Read(char* buf, int64_t byte_count, int64_t offset) const OVERRIDE WARN_UNUSED;
+ int SetLength(int64_t new_length) OVERRIDE WARN_UNUSED;
+ int64_t GetLength() const OVERRIDE;
+ int64_t Write(const char* buf, int64_t byte_count, int64_t offset) OVERRIDE WARN_UNUSED;
+
+ int Flush() OVERRIDE WARN_UNUSED;
+
+ // Short for SetLength(0); Flush(); Close();
+ // If the file was opened with a path name and unlink = true, also calls Unlink() on the path.
+ // Note that it is the the caller's responsibility to avoid races.
+ bool Erase(bool unlink = false);
+
+ // Call unlink() if the file was opened with a path, and if open() with the name shows that
+ // the file descriptor of this file is still up-to-date. This is still racy, though, and it
+ // is up to the caller to ensure correctness in a multi-process setup.
+ bool Unlink();
+
+ // Try to Flush(), then try to Close(); If either fails, call Erase().
+ int FlushCloseOrErase() WARN_UNUSED;
+
+ // Try to Flush and Close(). Attempts both, but returns the first error.
+ int FlushClose() WARN_UNUSED;
+
+ // Bonus API.
+ int Fd() const;
+ bool ReadOnlyMode() const;
+ bool CheckUsage() const;
+ bool IsOpened() const;
+ const std::string& GetPath() const {
+ return file_path_;
+ }
+ void DisableAutoClose();
+ bool ReadFully(void* buffer, size_t byte_count) WARN_UNUSED;
+ bool PreadFully(void* buffer, size_t byte_count, size_t offset) WARN_UNUSED;
+ bool WriteFully(const void* buffer, size_t byte_count) WARN_UNUSED;
+ bool PwriteFully(const void* buffer, size_t byte_count, size_t offset) WARN_UNUSED;
+
+ // Copy data from another file.
+ bool Copy(FdFile* input_file, int64_t offset, int64_t size);
+ // Clears the file content and resets the file offset to 0.
+ // Returns true upon success, false otherwise.
+ bool ClearContent();
+ // Resets the file offset to the beginning of the file.
+ bool ResetOffset();
+
+ // This enum is public so that we can define the << operator over it.
+ enum class GuardState {
+ kBase, // Base, file has not been flushed or closed.
+ kFlushed, // File has been flushed, but not closed.
+ kClosed, // File has been flushed and closed.
+ kNoCheck // Do not check for the current file instance.
+ };
+
+ // WARNING: Only use this when you know what you're doing!
+ void MarkUnchecked();
+
+ // Compare against another file. Returns 0 if the files are equivalent, otherwise returns -1 or 1
+ // depending on if the lenghts are different. If the lengths are the same, the function returns
+ // the difference of the first byte that differs.
+ int Compare(FdFile* other);
+
+ protected:
+ // If the guard state indicates checking (!=kNoCheck), go to the target state "target". Print the
+ // given warning if the current state is or exceeds warn_threshold.
+ void moveTo(GuardState target, GuardState warn_threshold, const char* warning);
+
+ // If the guard state indicates checking (<kNoCheck), and is below the target state "target", go
+ // to "target." If the current state is higher (excluding kNoCheck) than the trg state, print the
+ // warning.
+ void moveUp(GuardState target, const char* warning);
+
+ // Forcefully sets the state to the given one. This can overwrite kNoCheck.
+ void resetGuard(GuardState new_state) {
+ if (kCheckSafeUsage) {
+ guard_state_ = new_state;
+ }
+ }
+
+ GuardState guard_state_;
+
+ // 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);
+
+ private:
+ template <bool kUseOffset>
+ bool WriteFullyGeneric(const void* buffer, size_t byte_count, size_t offset);
+
+ void Destroy(); // For ~FdFile and operator=(&&).
+
+ int fd_;
+ std::string file_path_;
+ bool auto_close_;
+ bool read_only_mode_;
+
+ DISALLOW_COPY_AND_ASSIGN(FdFile);
+};
+
+std::ostream& operator<<(std::ostream& os, const FdFile::GuardState& kind);
+
+} // namespace unix_file
+
+#endif // ART_LIBARTBASE_BASE_UNIX_FILE_FD_FILE_H_
diff --git a/libartbase/base/unix_file/fd_file_test.cc b/libartbase/base/unix_file/fd_file_test.cc
new file mode 100644
index 0000000..042fbc9
--- /dev/null
+++ b/libartbase/base/unix_file/fd_file_test.cc
@@ -0,0 +1,288 @@
+/*
+ * 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 "common_runtime_test.h" // For ScratchFile
+#include "gtest/gtest.h"
+
+namespace unix_file {
+
+class FdFileTest : public RandomAccessFileTest {
+ protected:
+ virtual RandomAccessFile* MakeTestFile() {
+ return new FdFile(fileno(tmpfile()), false);
+ }
+};
+
+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(good_path, O_CREAT | O_WRONLY, true);
+ ASSERT_TRUE(file.IsOpened());
+ EXPECT_GE(file.Fd(), 0);
+ EXPECT_TRUE(file.IsOpened());
+ EXPECT_FALSE(file.ReadOnlyMode());
+ EXPECT_EQ(0, file.Flush());
+ EXPECT_EQ(0, file.Close());
+ EXPECT_EQ(-1, file.Fd());
+ EXPECT_FALSE(file.IsOpened());
+ FdFile file2(good_path, O_RDONLY, true);
+ EXPECT_TRUE(file2.IsOpened());
+ EXPECT_TRUE(file2.ReadOnlyMode());
+ EXPECT_GE(file2.Fd(), 0);
+
+ ASSERT_EQ(file2.Close(), 0);
+ ASSERT_EQ(unlink(good_path.c_str()), 0);
+}
+
+TEST_F(FdFileTest, ReadFullyEmptyFile) {
+ // New scratch file, zero-length.
+ art::ScratchFile tmp;
+ FdFile file(tmp.GetFilename(), O_RDONLY, false);
+ ASSERT_TRUE(file.IsOpened());
+ EXPECT_TRUE(file.ReadOnlyMode());
+ EXPECT_GE(file.Fd(), 0);
+ uint8_t buffer[16];
+ EXPECT_FALSE(file.ReadFully(&buffer, 4));
+}
+
+template <size_t Size>
+static void NullTerminateCharArray(char (&array)[Size]) {
+ array[Size - 1] = '\0';
+}
+
+TEST_F(FdFileTest, ReadFullyWithOffset) {
+ // New scratch file, zero-length.
+ art::ScratchFile tmp;
+ FdFile file(tmp.GetFilename(), O_RDWR, false);
+ ASSERT_TRUE(file.IsOpened());
+ EXPECT_GE(file.Fd(), 0);
+ EXPECT_FALSE(file.ReadOnlyMode());
+
+ char ignore_prefix[20] = {'a', };
+ NullTerminateCharArray(ignore_prefix);
+ char read_suffix[10] = {'b', };
+ NullTerminateCharArray(read_suffix);
+
+ off_t offset = 0;
+ // Write scratch data to file that we can read back into.
+ EXPECT_TRUE(file.Write(ignore_prefix, sizeof(ignore_prefix), offset));
+ offset += sizeof(ignore_prefix);
+ EXPECT_TRUE(file.Write(read_suffix, sizeof(read_suffix), offset));
+
+ ASSERT_EQ(file.Flush(), 0);
+
+ // Reading at an offset should only produce 'bbbb...', since we ignore the 'aaa...' prefix.
+ char buffer[sizeof(read_suffix)];
+ EXPECT_TRUE(file.PreadFully(buffer, sizeof(read_suffix), offset));
+ EXPECT_STREQ(&read_suffix[0], &buffer[0]);
+
+ ASSERT_EQ(file.Close(), 0);
+}
+
+TEST_F(FdFileTest, ReadWriteFullyWithOffset) {
+ // New scratch file, zero-length.
+ art::ScratchFile tmp;
+ FdFile file(tmp.GetFilename(), O_RDWR, false);
+ ASSERT_GE(file.Fd(), 0);
+ EXPECT_TRUE(file.IsOpened());
+ EXPECT_FALSE(file.ReadOnlyMode());
+
+ const char* test_string = "This is a test string";
+ size_t length = strlen(test_string) + 1;
+ const size_t offset = 12;
+ std::unique_ptr<char[]> offset_read_string(new char[length]);
+ std::unique_ptr<char[]> read_string(new char[length]);
+
+ // Write scratch data to file that we can read back into.
+ EXPECT_TRUE(file.PwriteFully(test_string, length, offset));
+ ASSERT_EQ(file.Flush(), 0);
+
+ // Test reading both the offsets.
+ EXPECT_TRUE(file.PreadFully(&offset_read_string[0], length, offset));
+ EXPECT_STREQ(test_string, &offset_read_string[0]);
+
+ EXPECT_TRUE(file.PreadFully(&read_string[0], length, 0u));
+ EXPECT_NE(memcmp(&read_string[0], test_string, length), 0);
+
+ ASSERT_EQ(file.Close(), 0);
+}
+
+TEST_F(FdFileTest, Copy) {
+ art::ScratchFile src_tmp;
+ FdFile src(src_tmp.GetFilename(), O_RDWR, false);
+ ASSERT_GE(src.Fd(), 0);
+ ASSERT_TRUE(src.IsOpened());
+
+ char src_data[] = "Some test data.";
+ ASSERT_TRUE(src.WriteFully(src_data, sizeof(src_data))); // Including the zero terminator.
+ ASSERT_EQ(0, src.Flush());
+ ASSERT_EQ(static_cast<int64_t>(sizeof(src_data)), src.GetLength());
+
+ art::ScratchFile dest_tmp;
+ FdFile dest(src_tmp.GetFilename(), O_RDWR, false);
+ ASSERT_GE(dest.Fd(), 0);
+ ASSERT_TRUE(dest.IsOpened());
+
+ ASSERT_TRUE(dest.Copy(&src, 0, sizeof(src_data)));
+ ASSERT_EQ(0, dest.Flush());
+ ASSERT_EQ(static_cast<int64_t>(sizeof(src_data)), dest.GetLength());
+
+ char check_data[sizeof(src_data)];
+ ASSERT_TRUE(dest.PreadFully(check_data, sizeof(src_data), 0u));
+ CHECK_EQ(0, memcmp(check_data, src_data, sizeof(src_data)));
+
+ ASSERT_EQ(0, dest.Close());
+ ASSERT_EQ(0, src.Close());
+}
+
+TEST_F(FdFileTest, MoveConstructor) {
+ // New scratch file, zero-length.
+ art::ScratchFile tmp;
+ FdFile file(tmp.GetFilename(), O_RDWR, false);
+ ASSERT_TRUE(file.IsOpened());
+ EXPECT_GE(file.Fd(), 0);
+
+ int old_fd = file.Fd();
+
+ FdFile file2(std::move(file));
+ EXPECT_FALSE(file.IsOpened());
+ EXPECT_TRUE(file2.IsOpened());
+ EXPECT_EQ(old_fd, file2.Fd());
+
+ ASSERT_EQ(file2.Flush(), 0);
+ ASSERT_EQ(file2.Close(), 0);
+}
+
+TEST_F(FdFileTest, OperatorMoveEquals) {
+ // Make sure the read_only_ flag is correctly copied
+ // over.
+ art::ScratchFile tmp;
+ FdFile file(tmp.GetFilename(), O_RDONLY, false);
+ ASSERT_TRUE(file.ReadOnlyMode());
+
+ FdFile file2(tmp.GetFilename(), O_RDWR, false);
+ ASSERT_FALSE(file2.ReadOnlyMode());
+
+ file2 = std::move(file);
+ ASSERT_TRUE(file2.ReadOnlyMode());
+}
+
+TEST_F(FdFileTest, EraseWithPathUnlinks) {
+ // New scratch file, zero-length.
+ art::ScratchFile tmp;
+ std::string filename = tmp.GetFilename();
+ tmp.Close(); // This is required because of the unlink race between the scratch file and the
+ // FdFile, which leads to close-guard breakage.
+ FdFile file(filename, O_RDWR, false);
+ ASSERT_TRUE(file.IsOpened());
+ EXPECT_GE(file.Fd(), 0);
+ uint8_t buffer[16] = { 0 };
+ EXPECT_TRUE(file.WriteFully(&buffer, sizeof(buffer)));
+ EXPECT_EQ(file.Flush(), 0);
+
+ EXPECT_TRUE(file.Erase(true));
+
+ EXPECT_FALSE(file.IsOpened());
+
+ EXPECT_FALSE(art::OS::FileExists(filename.c_str())) << filename;
+}
+
+TEST_F(FdFileTest, Compare) {
+ std::vector<uint8_t> buffer;
+ constexpr int64_t length = 17 * art::KB;
+ for (size_t i = 0; i < length; ++i) {
+ buffer.push_back(static_cast<uint8_t>(i));
+ }
+
+ auto reset_compare = [&](art::ScratchFile& a, art::ScratchFile& b) {
+ a.GetFile()->ResetOffset();
+ b.GetFile()->ResetOffset();
+ return a.GetFile()->Compare(b.GetFile());
+ };
+
+ art::ScratchFile tmp;
+ EXPECT_TRUE(tmp.GetFile()->WriteFully(&buffer[0], length));
+ EXPECT_EQ(tmp.GetFile()->GetLength(), length);
+
+ art::ScratchFile tmp2;
+ EXPECT_TRUE(tmp2.GetFile()->WriteFully(&buffer[0], length));
+ EXPECT_EQ(tmp2.GetFile()->GetLength(), length);
+
+ // Basic equality check.
+ tmp.GetFile()->ResetOffset();
+ tmp2.GetFile()->ResetOffset();
+ // Files should be the same.
+ EXPECT_EQ(reset_compare(tmp, tmp2), 0);
+
+ // Change a byte near the start.
+ ++buffer[2];
+ art::ScratchFile tmp3;
+ EXPECT_TRUE(tmp3.GetFile()->WriteFully(&buffer[0], length));
+ --buffer[2];
+ EXPECT_NE(reset_compare(tmp, tmp3), 0);
+
+ // Change a byte near the middle.
+ ++buffer[length / 2];
+ art::ScratchFile tmp4;
+ EXPECT_TRUE(tmp4.GetFile()->WriteFully(&buffer[0], length));
+ --buffer[length / 2];
+ EXPECT_NE(reset_compare(tmp, tmp4), 0);
+
+ // Change a byte near the end.
+ ++buffer[length - 5];
+ art::ScratchFile tmp5;
+ EXPECT_TRUE(tmp5.GetFile()->WriteFully(&buffer[0], length));
+ --buffer[length - 5];
+ EXPECT_NE(reset_compare(tmp, tmp5), 0);
+
+ // Reference check
+ art::ScratchFile tmp6;
+ EXPECT_TRUE(tmp6.GetFile()->WriteFully(&buffer[0], length));
+ EXPECT_EQ(reset_compare(tmp, tmp6), 0);
+}
+
+TEST_F(FdFileTest, PipeFlush) {
+ int pipefd[2];
+ ASSERT_EQ(0, pipe2(pipefd, O_CLOEXEC));
+
+ FdFile file(pipefd[1], true);
+ ASSERT_TRUE(file.WriteFully("foo", 3));
+ ASSERT_EQ(0, file.Flush());
+ ASSERT_EQ(0, file.FlushCloseOrErase());
+ close(pipefd[0]);
+}
+
+} // namespace unix_file
diff --git a/libartbase/base/unix_file/random_access_file.h b/libartbase/base/unix_file/random_access_file.h
new file mode 100644
index 0000000..d2124cc
--- /dev/null
+++ b/libartbase/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 ART_LIBARTBASE_BASE_UNIX_FILE_RANDOM_ACCESS_FILE_H_
+#define ART_LIBARTBASE_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 // ART_LIBARTBASE_BASE_UNIX_FILE_RANDOM_ACCESS_FILE_H_
diff --git a/libartbase/base/unix_file/random_access_file_test.h b/libartbase/base/unix_file/random_access_file_test.h
new file mode 100644
index 0000000..1de5f7b
--- /dev/null
+++ b/libartbase/base/unix_file/random_access_file_test.h
@@ -0,0 +1,183 @@
+/*
+ * 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 ART_LIBARTBASE_BASE_UNIX_FILE_RANDOM_ACCESS_FILE_TEST_H_
+#define ART_LIBARTBASE_BASE_UNIX_FILE_RANDOM_ACCESS_FILE_TEST_H_
+
+#include <errno.h>
+#include <memory>
+#include <string>
+
+#include "common_runtime_test.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::CommonRuntimeTest::SetUpAndroidData(android_data_);
+ }
+
+ virtual void TearDown() {
+ art::CommonRuntimeTest::TearDownAndroidData(android_data_, true);
+ }
+
+ 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];
+ std::unique_ptr<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(), static_cast<uint64_t>(file->Write(content.data(), content.size(), 0)));
+
+ TestReadContent(content, file.get());
+
+ CleanUp(file.get());
+ }
+
+ void TestReadContent(const std::string& content, RandomAccessFile* file) {
+ const int buf_size = content.size() + 10;
+ std::unique_ptr<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(), static_cast<uint64_t>(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, static_cast<uint64_t>(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, static_cast<uint64_t>(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");
+ std::unique_ptr<RandomAccessFile> file(MakeTestFile());
+ ASSERT_EQ(content.size(), static_cast<uint64_t>(file->Write(content.data(), content.size(), 0)));
+ ASSERT_EQ(content.size(), static_cast<uint64_t>(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]);
+
+ CleanUp(file.get());
+ }
+
+ void TestWrite() {
+ const std::string content("hello");
+ std::unique_ptr<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(), static_cast<uint64_t>(file->Write(content.data(), content.size(), 0)));
+ ASSERT_EQ(content.size(), static_cast<uint64_t>(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(), static_cast<uint64_t>(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(), static_cast<uint64_t>(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);
+
+ CleanUp(file.get());
+ }
+
+ virtual void CleanUp(RandomAccessFile* file ATTRIBUTE_UNUSED) {
+ }
+
+ protected:
+ std::string android_data_;
+};
+
+} // namespace unix_file
+
+#endif // ART_LIBARTBASE_BASE_UNIX_FILE_RANDOM_ACCESS_FILE_TEST_H_
diff --git a/libartbase/base/unix_file/random_access_file_utils.cc b/libartbase/base/unix_file/random_access_file_utils.cc
new file mode 100644
index 0000000..aae65c1
--- /dev/null
+++ b/libartbase/base/unix_file/random_access_file_utils.cc
@@ -0,0 +1,40 @@
+/*
+ * 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 <vector>
+
+#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/libartbase/base/unix_file/random_access_file_utils.h b/libartbase/base/unix_file/random_access_file_utils.h
new file mode 100644
index 0000000..47c4c2a
--- /dev/null
+++ b/libartbase/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 ART_LIBARTBASE_BASE_UNIX_FILE_RANDOM_ACCESS_FILE_UTILS_H_
+#define ART_LIBARTBASE_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 // ART_LIBARTBASE_BASE_UNIX_FILE_RANDOM_ACCESS_FILE_UTILS_H_