blob: e4097dd3de6adc62e8550a0043c880a10ec3bafa [file] [log] [blame]
Elliott Hughes76160052012-12-12 16:31:20 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "base/unix_file/fd_file.h"
Andreas Gampe4303ba92014-11-06 01:00:46 -080018
Elliott Hughes76160052012-12-12 16:31:20 -080019#include <errno.h>
Vladimir Marko5096e662015-12-08 19:25:49 +000020#include <limits>
Elliott Hughes76160052012-12-12 16:31:20 -080021#include <sys/stat.h>
22#include <sys/types.h>
23#include <unistd.h>
Elliott Hughes76160052012-12-12 16:31:20 -080024
Andreas Gampe4303ba92014-11-06 01:00:46 -080025#include "base/logging.h"
26
Vladimir Marko5096e662015-12-08 19:25:49 +000027// Includes needed for FdFile::Copy().
28#ifdef __linux__
29#include <sys/sendfile.h>
30#else
31#include <algorithm>
32#include "base/stl_util.h"
33#include "globals.h"
34#endif
35
Elliott Hughes76160052012-12-12 16:31:20 -080036namespace unix_file {
37
Calin Juravle2e2db782016-02-23 12:00:03 +000038FdFile::FdFile()
39 : guard_state_(GuardState::kClosed), fd_(-1), auto_close_(true), read_only_mode_(false) {
Elliott Hughes76160052012-12-12 16:31:20 -080040}
41
Andreas Gampe4303ba92014-11-06 01:00:46 -080042FdFile::FdFile(int fd, bool check_usage)
43 : guard_state_(check_usage ? GuardState::kBase : GuardState::kNoCheck),
Calin Juravle2e2db782016-02-23 12:00:03 +000044 fd_(fd), auto_close_(true), read_only_mode_(false) {
Elliott Hughes76160052012-12-12 16:31:20 -080045}
46
Andreas Gampe4303ba92014-11-06 01:00:46 -080047FdFile::FdFile(int fd, const std::string& path, bool check_usage)
Calin Juravle2e2db782016-02-23 12:00:03 +000048 : FdFile(fd, path, check_usage, false) {
49}
50
51FdFile::FdFile(int fd, const std::string& path, bool check_usage, bool read_only_mode)
Andreas Gampe4303ba92014-11-06 01:00:46 -080052 : guard_state_(check_usage ? GuardState::kBase : GuardState::kNoCheck),
Calin Juravle2e2db782016-02-23 12:00:03 +000053 fd_(fd), file_path_(path), auto_close_(true), read_only_mode_(read_only_mode) {
Elliott Hughes76160052012-12-12 16:31:20 -080054}
55
56FdFile::~FdFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -080057 if (kCheckSafeUsage && (guard_state_ < GuardState::kNoCheck)) {
58 if (guard_state_ < GuardState::kFlushed) {
59 LOG(::art::ERROR) << "File " << file_path_ << " wasn't explicitly flushed before destruction.";
60 }
61 if (guard_state_ < GuardState::kClosed) {
62 LOG(::art::ERROR) << "File " << file_path_ << " wasn't explicitly closed before destruction.";
63 }
64 CHECK_GE(guard_state_, GuardState::kClosed);
65 }
Elliott Hughes76160052012-12-12 16:31:20 -080066 if (auto_close_ && fd_ != -1) {
Andreas Gampe4303ba92014-11-06 01:00:46 -080067 if (Close() != 0) {
68 PLOG(::art::WARNING) << "Failed to close file " << file_path_;
69 }
70 }
71}
72
73void FdFile::moveTo(GuardState target, GuardState warn_threshold, const char* warning) {
74 if (kCheckSafeUsage) {
75 if (guard_state_ < GuardState::kNoCheck) {
76 if (warn_threshold < GuardState::kNoCheck && guard_state_ >= warn_threshold) {
77 LOG(::art::ERROR) << warning;
78 }
79 guard_state_ = target;
80 }
81 }
82}
83
84void FdFile::moveUp(GuardState target, const char* warning) {
85 if (kCheckSafeUsage) {
86 if (guard_state_ < GuardState::kNoCheck) {
87 if (guard_state_ < target) {
88 guard_state_ = target;
89 } else if (target < guard_state_) {
90 LOG(::art::ERROR) << warning;
91 }
92 }
Elliott Hughes76160052012-12-12 16:31:20 -080093 }
94}
95
96void FdFile::DisableAutoClose() {
97 auto_close_ = false;
98}
99
100bool FdFile::Open(const std::string& path, int flags) {
101 return Open(path, flags, 0640);
102}
103
104bool FdFile::Open(const std::string& path, int flags, mode_t mode) {
105 CHECK_EQ(fd_, -1) << path;
Calin Juravle2e2db782016-02-23 12:00:03 +0000106 read_only_mode_ = (flags & O_RDONLY) != 0;
Elliott Hughes76160052012-12-12 16:31:20 -0800107 fd_ = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
108 if (fd_ == -1) {
109 return false;
110 }
111 file_path_ = path;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800112 static_assert(O_RDONLY == 0, "Readonly flag has unexpected value.");
113 if (kCheckSafeUsage && (flags & (O_RDWR | O_CREAT | O_WRONLY)) != 0) {
114 // Start in the base state (not flushed, not closed).
115 guard_state_ = GuardState::kBase;
116 } else {
117 // We are not concerned with read-only files. In that case, proper flushing and closing is
118 // not important.
119 guard_state_ = GuardState::kNoCheck;
120 }
Elliott Hughes76160052012-12-12 16:31:20 -0800121 return true;
122}
123
124int FdFile::Close() {
Elliott Hughes6a887d62015-05-15 08:25:58 -0700125 int result = close(fd_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800126
127 // Test here, so the file is closed and not leaked.
128 if (kCheckSafeUsage) {
129 CHECK_GE(guard_state_, GuardState::kFlushed) << "File " << file_path_
130 << " has not been flushed before closing.";
131 moveUp(GuardState::kClosed, nullptr);
132 }
133
Elliott Hughes76160052012-12-12 16:31:20 -0800134 if (result == -1) {
135 return -errno;
136 } else {
137 fd_ = -1;
138 file_path_ = "";
139 return 0;
140 }
141}
142
143int FdFile::Flush() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000144 DCHECK(!read_only_mode_);
Ian Rogersc5f17732014-06-05 20:48:42 -0700145#ifdef __linux__
Elliott Hughes76160052012-12-12 16:31:20 -0800146 int rc = TEMP_FAILURE_RETRY(fdatasync(fd_));
Ian Rogersc5f17732014-06-05 20:48:42 -0700147#else
148 int rc = TEMP_FAILURE_RETRY(fsync(fd_));
149#endif
Andreas Gampe4303ba92014-11-06 01:00:46 -0800150 moveUp(GuardState::kFlushed, "Flushing closed file.");
Elliott Hughes76160052012-12-12 16:31:20 -0800151 return (rc == -1) ? -errno : rc;
152}
153
154int64_t FdFile::Read(char* buf, int64_t byte_count, int64_t offset) const {
Ian Rogersc5f17732014-06-05 20:48:42 -0700155#ifdef __linux__
Elliott Hughes76160052012-12-12 16:31:20 -0800156 int rc = TEMP_FAILURE_RETRY(pread64(fd_, buf, byte_count, offset));
Ian Rogersc5f17732014-06-05 20:48:42 -0700157#else
158 int rc = TEMP_FAILURE_RETRY(pread(fd_, buf, byte_count, offset));
159#endif
Elliott Hughes76160052012-12-12 16:31:20 -0800160 return (rc == -1) ? -errno : rc;
161}
162
163int FdFile::SetLength(int64_t new_length) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000164 DCHECK(!read_only_mode_);
Ian Rogersc5f17732014-06-05 20:48:42 -0700165#ifdef __linux__
Elliott Hughes76160052012-12-12 16:31:20 -0800166 int rc = TEMP_FAILURE_RETRY(ftruncate64(fd_, new_length));
Ian Rogersc5f17732014-06-05 20:48:42 -0700167#else
168 int rc = TEMP_FAILURE_RETRY(ftruncate(fd_, new_length));
169#endif
Andreas Gampe4303ba92014-11-06 01:00:46 -0800170 moveTo(GuardState::kBase, GuardState::kClosed, "Truncating closed file.");
Elliott Hughes76160052012-12-12 16:31:20 -0800171 return (rc == -1) ? -errno : rc;
172}
173
174int64_t FdFile::GetLength() const {
175 struct stat s;
176 int rc = TEMP_FAILURE_RETRY(fstat(fd_, &s));
177 return (rc == -1) ? -errno : s.st_size;
178}
179
180int64_t FdFile::Write(const char* buf, int64_t byte_count, int64_t offset) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000181 DCHECK(!read_only_mode_);
Ian Rogersc5f17732014-06-05 20:48:42 -0700182#ifdef __linux__
Elliott Hughes76160052012-12-12 16:31:20 -0800183 int rc = TEMP_FAILURE_RETRY(pwrite64(fd_, buf, byte_count, offset));
Ian Rogersc5f17732014-06-05 20:48:42 -0700184#else
185 int rc = TEMP_FAILURE_RETRY(pwrite(fd_, buf, byte_count, offset));
186#endif
Andreas Gampe4303ba92014-11-06 01:00:46 -0800187 moveTo(GuardState::kBase, GuardState::kClosed, "Writing into closed file.");
Elliott Hughes76160052012-12-12 16:31:20 -0800188 return (rc == -1) ? -errno : rc;
189}
190
191int FdFile::Fd() const {
192 return fd_;
193}
194
Calin Juravle2e2db782016-02-23 12:00:03 +0000195bool FdFile::ReadOnlyMode() const {
196 return read_only_mode_;
197}
198
199bool FdFile::CheckUsage() const {
200 return guard_state_ != GuardState::kNoCheck;
201}
202
Elliott Hughes76160052012-12-12 16:31:20 -0800203bool FdFile::IsOpened() const {
204 return fd_ >= 0;
205}
206
Igor Murashkin37743352014-11-13 14:38:00 -0800207static ssize_t ReadIgnoreOffset(int fd, void *buf, size_t count, off_t offset) {
208 DCHECK_EQ(offset, 0);
209 return read(fd, buf, count);
210}
211
212template <ssize_t (*read_func)(int, void*, size_t, off_t)>
213static bool ReadFullyGeneric(int fd, void* buffer, size_t byte_count, size_t offset) {
Elliott Hughes76160052012-12-12 16:31:20 -0800214 char* ptr = static_cast<char*>(buffer);
215 while (byte_count > 0) {
Igor Murashkin37743352014-11-13 14:38:00 -0800216 ssize_t bytes_read = TEMP_FAILURE_RETRY(read_func(fd, ptr, byte_count, offset));
Andreas Gampe825201e2014-06-20 10:45:30 -0700217 if (bytes_read <= 0) {
218 // 0: end of file
219 // -1: error
Elliott Hughes76160052012-12-12 16:31:20 -0800220 return false;
221 }
222 byte_count -= bytes_read; // Reduce the number of remaining bytes.
223 ptr += bytes_read; // Move the buffer forward.
Igor Murashkin37743352014-11-13 14:38:00 -0800224 offset += static_cast<size_t>(bytes_read); // Move the offset forward.
Elliott Hughes76160052012-12-12 16:31:20 -0800225 }
226 return true;
227}
228
Igor Murashkin37743352014-11-13 14:38:00 -0800229bool FdFile::ReadFully(void* buffer, size_t byte_count) {
230 return ReadFullyGeneric<ReadIgnoreOffset>(fd_, buffer, byte_count, 0);
231}
232
233bool FdFile::PreadFully(void* buffer, size_t byte_count, size_t offset) {
234 return ReadFullyGeneric<pread>(fd_, buffer, byte_count, offset);
235}
236
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800237template <bool kUseOffset>
238bool FdFile::WriteFullyGeneric(const void* buffer, size_t byte_count, size_t offset) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000239 DCHECK(!read_only_mode_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800240 moveTo(GuardState::kBase, GuardState::kClosed, "Writing into closed file.");
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800241 DCHECK(kUseOffset || offset == 0u);
242 const char* ptr = static_cast<const char*>(buffer);
Elliott Hughes76160052012-12-12 16:31:20 -0800243 while (byte_count > 0) {
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800244 ssize_t bytes_written = kUseOffset
245 ? TEMP_FAILURE_RETRY(pwrite(fd_, ptr, byte_count, offset))
246 : TEMP_FAILURE_RETRY(write(fd_, ptr, byte_count));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800247 if (bytes_written == -1) {
Elliott Hughes76160052012-12-12 16:31:20 -0800248 return false;
249 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800250 byte_count -= bytes_written; // Reduce the number of remaining bytes.
251 ptr += bytes_written; // Move the buffer forward.
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800252 offset += static_cast<size_t>(bytes_written);
Elliott Hughes76160052012-12-12 16:31:20 -0800253 }
254 return true;
255}
256
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800257bool FdFile::PwriteFully(const void* buffer, size_t byte_count, size_t offset) {
258 return WriteFullyGeneric<true>(buffer, byte_count, offset);
259}
260
261bool FdFile::WriteFully(const void* buffer, size_t byte_count) {
262 return WriteFullyGeneric<false>(buffer, byte_count, 0u);
263}
264
Vladimir Marko5096e662015-12-08 19:25:49 +0000265bool FdFile::Copy(FdFile* input_file, int64_t offset, int64_t size) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000266 DCHECK(!read_only_mode_);
Vladimir Marko5096e662015-12-08 19:25:49 +0000267 off_t off = static_cast<off_t>(offset);
268 off_t sz = static_cast<off_t>(size);
269 if (offset < 0 || static_cast<int64_t>(off) != offset ||
270 size < 0 || static_cast<int64_t>(sz) != size ||
271 sz > std::numeric_limits<off_t>::max() - off) {
272 errno = EINVAL;
273 return false;
274 }
275 if (size == 0) {
276 return true;
277 }
278#ifdef __linux__
279 // Use sendfile(), available for files since linux kernel 2.6.33.
280 off_t end = off + sz;
281 while (off != end) {
282 int result = TEMP_FAILURE_RETRY(
283 sendfile(Fd(), input_file->Fd(), &off, end - off));
284 if (result == -1) {
285 return false;
286 }
287 // Ignore the number of bytes in `result`, sendfile() already updated `off`.
288 }
289#else
290 if (lseek(input_file->Fd(), off, SEEK_SET) != off) {
291 return false;
292 }
293 constexpr size_t kMaxBufferSize = 4 * ::art::kPageSize;
294 const size_t buffer_size = std::min<uint64_t>(size, kMaxBufferSize);
295 art::UniqueCPtr<void> buffer(malloc(buffer_size));
296 if (buffer == nullptr) {
297 errno = ENOMEM;
298 return false;
299 }
300 while (size != 0) {
301 size_t chunk_size = std::min<uint64_t>(buffer_size, size);
302 if (!input_file->ReadFully(buffer.get(), chunk_size) ||
303 !WriteFully(buffer.get(), chunk_size)) {
304 return false;
305 }
306 size -= chunk_size;
307 }
308#endif
309 return true;
310}
311
Andreas Gampe4303ba92014-11-06 01:00:46 -0800312void FdFile::Erase() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000313 DCHECK(!read_only_mode_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800314 TEMP_FAILURE_RETRY(SetLength(0));
315 TEMP_FAILURE_RETRY(Flush());
316 TEMP_FAILURE_RETRY(Close());
317}
318
319int FdFile::FlushCloseOrErase() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000320 DCHECK(!read_only_mode_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800321 int flush_result = TEMP_FAILURE_RETRY(Flush());
322 if (flush_result != 0) {
323 LOG(::art::ERROR) << "CloseOrErase failed while flushing a file.";
324 Erase();
325 return flush_result;
326 }
327 int close_result = TEMP_FAILURE_RETRY(Close());
328 if (close_result != 0) {
329 LOG(::art::ERROR) << "CloseOrErase failed while closing a file.";
330 Erase();
331 return close_result;
332 }
333 return 0;
334}
335
336int FdFile::FlushClose() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000337 DCHECK(!read_only_mode_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800338 int flush_result = TEMP_FAILURE_RETRY(Flush());
339 if (flush_result != 0) {
340 LOG(::art::ERROR) << "FlushClose failed while flushing a file.";
341 }
342 int close_result = TEMP_FAILURE_RETRY(Close());
343 if (close_result != 0) {
344 LOG(::art::ERROR) << "FlushClose failed while closing a file.";
345 }
346 return (flush_result != 0) ? flush_result : close_result;
347}
348
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800349void FdFile::MarkUnchecked() {
350 guard_state_ = GuardState::kNoCheck;
351}
352
Calin Juravle877fd962016-01-05 14:29:29 +0000353bool FdFile::ClearContent() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000354 DCHECK(!read_only_mode_);
Calin Juravle877fd962016-01-05 14:29:29 +0000355 if (SetLength(0) < 0) {
356 PLOG(art::ERROR) << "Failed to reset the length";
357 return false;
358 }
359 return ResetOffset();
360}
361
362bool FdFile::ResetOffset() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000363 DCHECK(!read_only_mode_);
Calin Juravle877fd962016-01-05 14:29:29 +0000364 off_t rc = TEMP_FAILURE_RETRY(lseek(fd_, 0, SEEK_SET));
365 if (rc == static_cast<off_t>(-1)) {
366 PLOG(art::ERROR) << "Failed to reset the offset";
367 return false;
368 }
369 return true;
370}
371
Elliott Hughes76160052012-12-12 16:31:20 -0800372} // namespace unix_file