blob: 4498198b341565df85b68d0c97026cec4a3072da [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
Andreas Gampedf878922015-08-13 16:44:54 -070056FdFile::FdFile(const std::string& path, int flags, mode_t mode, bool check_usage)
57 : fd_(-1), auto_close_(true) {
58 Open(path, flags, mode);
59 if (!check_usage || !IsOpened()) {
60 guard_state_ = GuardState::kNoCheck;
61 }
62}
63
64void FdFile::Destroy() {
Andreas Gampe4303ba92014-11-06 01:00:46 -080065 if (kCheckSafeUsage && (guard_state_ < GuardState::kNoCheck)) {
66 if (guard_state_ < GuardState::kFlushed) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -070067 LOG(ERROR) << "File " << file_path_ << " wasn't explicitly flushed before destruction.";
Andreas Gampe4303ba92014-11-06 01:00:46 -080068 }
69 if (guard_state_ < GuardState::kClosed) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -070070 LOG(ERROR) << "File " << file_path_ << " wasn't explicitly closed before destruction.";
Andreas Gampe4303ba92014-11-06 01:00:46 -080071 }
72 CHECK_GE(guard_state_, GuardState::kClosed);
73 }
Elliott Hughes76160052012-12-12 16:31:20 -080074 if (auto_close_ && fd_ != -1) {
Andreas Gampe4303ba92014-11-06 01:00:46 -080075 if (Close() != 0) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -070076 PLOG(WARNING) << "Failed to close file " << file_path_;
Andreas Gampe4303ba92014-11-06 01:00:46 -080077 }
78 }
79}
80
Andreas Gampedf878922015-08-13 16:44:54 -070081FdFile& FdFile::operator=(FdFile&& other) {
82 if (this == &other) {
83 return *this;
84 }
85
86 if (this->fd_ != other.fd_) {
87 Destroy(); // Free old state.
88 }
89
90 guard_state_ = other.guard_state_;
91 fd_ = other.fd_;
92 file_path_ = std::move(other.file_path_);
93 auto_close_ = other.auto_close_;
94 other.Release(); // Release other.
95
96 return *this;
97}
98
99FdFile::~FdFile() {
100 Destroy();
101}
102
Andreas Gampe4303ba92014-11-06 01:00:46 -0800103void FdFile::moveTo(GuardState target, GuardState warn_threshold, const char* warning) {
104 if (kCheckSafeUsage) {
105 if (guard_state_ < GuardState::kNoCheck) {
106 if (warn_threshold < GuardState::kNoCheck && guard_state_ >= warn_threshold) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700107 LOG(ERROR) << warning;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800108 }
109 guard_state_ = target;
110 }
111 }
112}
113
114void FdFile::moveUp(GuardState target, const char* warning) {
115 if (kCheckSafeUsage) {
116 if (guard_state_ < GuardState::kNoCheck) {
117 if (guard_state_ < target) {
118 guard_state_ = target;
119 } else if (target < guard_state_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700120 LOG(ERROR) << warning;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800121 }
122 }
Elliott Hughes76160052012-12-12 16:31:20 -0800123 }
124}
125
126void FdFile::DisableAutoClose() {
127 auto_close_ = false;
128}
129
130bool FdFile::Open(const std::string& path, int flags) {
131 return Open(path, flags, 0640);
132}
133
134bool FdFile::Open(const std::string& path, int flags, mode_t mode) {
David Brazdilb64decd2016-08-09 12:10:56 +0100135 static_assert(O_RDONLY == 0, "Readonly flag has unexpected value.");
Elliott Hughes76160052012-12-12 16:31:20 -0800136 CHECK_EQ(fd_, -1) << path;
David Brazdilb64decd2016-08-09 12:10:56 +0100137 read_only_mode_ = ((flags & O_ACCMODE) == O_RDONLY);
Elliott Hughes76160052012-12-12 16:31:20 -0800138 fd_ = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
139 if (fd_ == -1) {
140 return false;
141 }
142 file_path_ = path;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800143 if (kCheckSafeUsage && (flags & (O_RDWR | O_CREAT | O_WRONLY)) != 0) {
144 // Start in the base state (not flushed, not closed).
145 guard_state_ = GuardState::kBase;
146 } else {
147 // We are not concerned with read-only files. In that case, proper flushing and closing is
148 // not important.
149 guard_state_ = GuardState::kNoCheck;
150 }
Elliott Hughes76160052012-12-12 16:31:20 -0800151 return true;
152}
153
154int FdFile::Close() {
Elliott Hughes6a887d62015-05-15 08:25:58 -0700155 int result = close(fd_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800156
157 // Test here, so the file is closed and not leaked.
158 if (kCheckSafeUsage) {
159 CHECK_GE(guard_state_, GuardState::kFlushed) << "File " << file_path_
160 << " has not been flushed before closing.";
161 moveUp(GuardState::kClosed, nullptr);
162 }
163
Elliott Hughes76160052012-12-12 16:31:20 -0800164 if (result == -1) {
165 return -errno;
166 } else {
167 fd_ = -1;
168 file_path_ = "";
169 return 0;
170 }
171}
172
173int FdFile::Flush() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000174 DCHECK(!read_only_mode_);
Ian Rogersc5f17732014-06-05 20:48:42 -0700175#ifdef __linux__
Elliott Hughes76160052012-12-12 16:31:20 -0800176 int rc = TEMP_FAILURE_RETRY(fdatasync(fd_));
Ian Rogersc5f17732014-06-05 20:48:42 -0700177#else
178 int rc = TEMP_FAILURE_RETRY(fsync(fd_));
179#endif
Andreas Gampe4303ba92014-11-06 01:00:46 -0800180 moveUp(GuardState::kFlushed, "Flushing closed file.");
Elliott Hughes76160052012-12-12 16:31:20 -0800181 return (rc == -1) ? -errno : rc;
182}
183
184int64_t FdFile::Read(char* buf, int64_t byte_count, int64_t offset) const {
Ian Rogersc5f17732014-06-05 20:48:42 -0700185#ifdef __linux__
Elliott Hughes76160052012-12-12 16:31:20 -0800186 int rc = TEMP_FAILURE_RETRY(pread64(fd_, buf, byte_count, offset));
Ian Rogersc5f17732014-06-05 20:48:42 -0700187#else
188 int rc = TEMP_FAILURE_RETRY(pread(fd_, buf, byte_count, offset));
189#endif
Elliott Hughes76160052012-12-12 16:31:20 -0800190 return (rc == -1) ? -errno : rc;
191}
192
193int FdFile::SetLength(int64_t new_length) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000194 DCHECK(!read_only_mode_);
Ian Rogersc5f17732014-06-05 20:48:42 -0700195#ifdef __linux__
Elliott Hughes76160052012-12-12 16:31:20 -0800196 int rc = TEMP_FAILURE_RETRY(ftruncate64(fd_, new_length));
Ian Rogersc5f17732014-06-05 20:48:42 -0700197#else
198 int rc = TEMP_FAILURE_RETRY(ftruncate(fd_, new_length));
199#endif
Andreas Gampe4303ba92014-11-06 01:00:46 -0800200 moveTo(GuardState::kBase, GuardState::kClosed, "Truncating closed file.");
Elliott Hughes76160052012-12-12 16:31:20 -0800201 return (rc == -1) ? -errno : rc;
202}
203
204int64_t FdFile::GetLength() const {
205 struct stat s;
206 int rc = TEMP_FAILURE_RETRY(fstat(fd_, &s));
207 return (rc == -1) ? -errno : s.st_size;
208}
209
210int64_t FdFile::Write(const char* buf, int64_t byte_count, int64_t offset) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000211 DCHECK(!read_only_mode_);
Ian Rogersc5f17732014-06-05 20:48:42 -0700212#ifdef __linux__
Elliott Hughes76160052012-12-12 16:31:20 -0800213 int rc = TEMP_FAILURE_RETRY(pwrite64(fd_, buf, byte_count, offset));
Ian Rogersc5f17732014-06-05 20:48:42 -0700214#else
215 int rc = TEMP_FAILURE_RETRY(pwrite(fd_, buf, byte_count, offset));
216#endif
Andreas Gampe4303ba92014-11-06 01:00:46 -0800217 moveTo(GuardState::kBase, GuardState::kClosed, "Writing into closed file.");
Elliott Hughes76160052012-12-12 16:31:20 -0800218 return (rc == -1) ? -errno : rc;
219}
220
221int FdFile::Fd() const {
222 return fd_;
223}
224
Calin Juravle2e2db782016-02-23 12:00:03 +0000225bool FdFile::ReadOnlyMode() const {
226 return read_only_mode_;
227}
228
229bool FdFile::CheckUsage() const {
230 return guard_state_ != GuardState::kNoCheck;
231}
232
Elliott Hughes76160052012-12-12 16:31:20 -0800233bool FdFile::IsOpened() const {
234 return fd_ >= 0;
235}
236
Igor Murashkin37743352014-11-13 14:38:00 -0800237static ssize_t ReadIgnoreOffset(int fd, void *buf, size_t count, off_t offset) {
238 DCHECK_EQ(offset, 0);
239 return read(fd, buf, count);
240}
241
242template <ssize_t (*read_func)(int, void*, size_t, off_t)>
243static bool ReadFullyGeneric(int fd, void* buffer, size_t byte_count, size_t offset) {
Elliott Hughes76160052012-12-12 16:31:20 -0800244 char* ptr = static_cast<char*>(buffer);
245 while (byte_count > 0) {
Igor Murashkin37743352014-11-13 14:38:00 -0800246 ssize_t bytes_read = TEMP_FAILURE_RETRY(read_func(fd, ptr, byte_count, offset));
Andreas Gampe825201e2014-06-20 10:45:30 -0700247 if (bytes_read <= 0) {
248 // 0: end of file
249 // -1: error
Elliott Hughes76160052012-12-12 16:31:20 -0800250 return false;
251 }
252 byte_count -= bytes_read; // Reduce the number of remaining bytes.
253 ptr += bytes_read; // Move the buffer forward.
Igor Murashkin37743352014-11-13 14:38:00 -0800254 offset += static_cast<size_t>(bytes_read); // Move the offset forward.
Elliott Hughes76160052012-12-12 16:31:20 -0800255 }
256 return true;
257}
258
Igor Murashkin37743352014-11-13 14:38:00 -0800259bool FdFile::ReadFully(void* buffer, size_t byte_count) {
260 return ReadFullyGeneric<ReadIgnoreOffset>(fd_, buffer, byte_count, 0);
261}
262
263bool FdFile::PreadFully(void* buffer, size_t byte_count, size_t offset) {
264 return ReadFullyGeneric<pread>(fd_, buffer, byte_count, offset);
265}
266
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800267template <bool kUseOffset>
268bool FdFile::WriteFullyGeneric(const void* buffer, size_t byte_count, size_t offset) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000269 DCHECK(!read_only_mode_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800270 moveTo(GuardState::kBase, GuardState::kClosed, "Writing into closed file.");
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800271 DCHECK(kUseOffset || offset == 0u);
272 const char* ptr = static_cast<const char*>(buffer);
Elliott Hughes76160052012-12-12 16:31:20 -0800273 while (byte_count > 0) {
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800274 ssize_t bytes_written = kUseOffset
275 ? TEMP_FAILURE_RETRY(pwrite(fd_, ptr, byte_count, offset))
276 : TEMP_FAILURE_RETRY(write(fd_, ptr, byte_count));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800277 if (bytes_written == -1) {
Elliott Hughes76160052012-12-12 16:31:20 -0800278 return false;
279 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800280 byte_count -= bytes_written; // Reduce the number of remaining bytes.
281 ptr += bytes_written; // Move the buffer forward.
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800282 offset += static_cast<size_t>(bytes_written);
Elliott Hughes76160052012-12-12 16:31:20 -0800283 }
284 return true;
285}
286
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800287bool FdFile::PwriteFully(const void* buffer, size_t byte_count, size_t offset) {
288 return WriteFullyGeneric<true>(buffer, byte_count, offset);
289}
290
291bool FdFile::WriteFully(const void* buffer, size_t byte_count) {
292 return WriteFullyGeneric<false>(buffer, byte_count, 0u);
293}
294
Vladimir Marko5096e662015-12-08 19:25:49 +0000295bool FdFile::Copy(FdFile* input_file, int64_t offset, int64_t size) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000296 DCHECK(!read_only_mode_);
Vladimir Marko5096e662015-12-08 19:25:49 +0000297 off_t off = static_cast<off_t>(offset);
298 off_t sz = static_cast<off_t>(size);
299 if (offset < 0 || static_cast<int64_t>(off) != offset ||
300 size < 0 || static_cast<int64_t>(sz) != size ||
301 sz > std::numeric_limits<off_t>::max() - off) {
302 errno = EINVAL;
303 return false;
304 }
305 if (size == 0) {
306 return true;
307 }
308#ifdef __linux__
309 // Use sendfile(), available for files since linux kernel 2.6.33.
310 off_t end = off + sz;
311 while (off != end) {
312 int result = TEMP_FAILURE_RETRY(
313 sendfile(Fd(), input_file->Fd(), &off, end - off));
314 if (result == -1) {
315 return false;
316 }
317 // Ignore the number of bytes in `result`, sendfile() already updated `off`.
318 }
319#else
320 if (lseek(input_file->Fd(), off, SEEK_SET) != off) {
321 return false;
322 }
323 constexpr size_t kMaxBufferSize = 4 * ::art::kPageSize;
324 const size_t buffer_size = std::min<uint64_t>(size, kMaxBufferSize);
325 art::UniqueCPtr<void> buffer(malloc(buffer_size));
326 if (buffer == nullptr) {
327 errno = ENOMEM;
328 return false;
329 }
330 while (size != 0) {
331 size_t chunk_size = std::min<uint64_t>(buffer_size, size);
332 if (!input_file->ReadFully(buffer.get(), chunk_size) ||
333 !WriteFully(buffer.get(), chunk_size)) {
334 return false;
335 }
336 size -= chunk_size;
337 }
338#endif
339 return true;
340}
341
Andreas Gampe4303ba92014-11-06 01:00:46 -0800342void FdFile::Erase() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000343 DCHECK(!read_only_mode_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800344 TEMP_FAILURE_RETRY(SetLength(0));
345 TEMP_FAILURE_RETRY(Flush());
346 TEMP_FAILURE_RETRY(Close());
347}
348
349int FdFile::FlushCloseOrErase() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000350 DCHECK(!read_only_mode_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800351 int flush_result = TEMP_FAILURE_RETRY(Flush());
352 if (flush_result != 0) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700353 LOG(ERROR) << "CloseOrErase failed while flushing a file.";
Andreas Gampe4303ba92014-11-06 01:00:46 -0800354 Erase();
355 return flush_result;
356 }
357 int close_result = TEMP_FAILURE_RETRY(Close());
358 if (close_result != 0) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700359 LOG(ERROR) << "CloseOrErase failed while closing a file.";
Andreas Gampe4303ba92014-11-06 01:00:46 -0800360 Erase();
361 return close_result;
362 }
363 return 0;
364}
365
366int FdFile::FlushClose() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000367 DCHECK(!read_only_mode_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800368 int flush_result = TEMP_FAILURE_RETRY(Flush());
369 if (flush_result != 0) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700370 LOG(ERROR) << "FlushClose failed while flushing a file.";
Andreas Gampe4303ba92014-11-06 01:00:46 -0800371 }
372 int close_result = TEMP_FAILURE_RETRY(Close());
373 if (close_result != 0) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700374 LOG(ERROR) << "FlushClose failed while closing a file.";
Andreas Gampe4303ba92014-11-06 01:00:46 -0800375 }
376 return (flush_result != 0) ? flush_result : close_result;
377}
378
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800379void FdFile::MarkUnchecked() {
380 guard_state_ = GuardState::kNoCheck;
381}
382
Calin Juravle877fd962016-01-05 14:29:29 +0000383bool FdFile::ClearContent() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000384 DCHECK(!read_only_mode_);
Calin Juravle877fd962016-01-05 14:29:29 +0000385 if (SetLength(0) < 0) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700386 PLOG(ERROR) << "Failed to reset the length";
Calin Juravle877fd962016-01-05 14:29:29 +0000387 return false;
388 }
389 return ResetOffset();
390}
391
392bool FdFile::ResetOffset() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000393 DCHECK(!read_only_mode_);
Calin Juravle877fd962016-01-05 14:29:29 +0000394 off_t rc = TEMP_FAILURE_RETRY(lseek(fd_, 0, SEEK_SET));
395 if (rc == static_cast<off_t>(-1)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700396 PLOG(ERROR) << "Failed to reset the offset";
Calin Juravle877fd962016-01-05 14:29:29 +0000397 return false;
398 }
399 return true;
400}
401
Elliott Hughes76160052012-12-12 16:31:20 -0800402} // namespace unix_file