blob: 4672948f31e5ca37c7ffb56f55781632ee6baef2 [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
Ian Rogersef7d42f2014-01-06 12:55:46 -0800237bool FdFile::WriteFully(const void* buffer, size_t byte_count) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000238 DCHECK(!read_only_mode_);
Elliott Hughes76160052012-12-12 16:31:20 -0800239 const char* ptr = static_cast<const char*>(buffer);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800240 moveTo(GuardState::kBase, GuardState::kClosed, "Writing into closed file.");
Elliott Hughes76160052012-12-12 16:31:20 -0800241 while (byte_count > 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800242 ssize_t bytes_written = TEMP_FAILURE_RETRY(write(fd_, ptr, byte_count));
243 if (bytes_written == -1) {
Elliott Hughes76160052012-12-12 16:31:20 -0800244 return false;
245 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800246 byte_count -= bytes_written; // Reduce the number of remaining bytes.
247 ptr += bytes_written; // Move the buffer forward.
Elliott Hughes76160052012-12-12 16:31:20 -0800248 }
249 return true;
250}
251
Vladimir Marko5096e662015-12-08 19:25:49 +0000252bool FdFile::Copy(FdFile* input_file, int64_t offset, int64_t size) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000253 DCHECK(!read_only_mode_);
Vladimir Marko5096e662015-12-08 19:25:49 +0000254 off_t off = static_cast<off_t>(offset);
255 off_t sz = static_cast<off_t>(size);
256 if (offset < 0 || static_cast<int64_t>(off) != offset ||
257 size < 0 || static_cast<int64_t>(sz) != size ||
258 sz > std::numeric_limits<off_t>::max() - off) {
259 errno = EINVAL;
260 return false;
261 }
262 if (size == 0) {
263 return true;
264 }
265#ifdef __linux__
266 // Use sendfile(), available for files since linux kernel 2.6.33.
267 off_t end = off + sz;
268 while (off != end) {
269 int result = TEMP_FAILURE_RETRY(
270 sendfile(Fd(), input_file->Fd(), &off, end - off));
271 if (result == -1) {
272 return false;
273 }
274 // Ignore the number of bytes in `result`, sendfile() already updated `off`.
275 }
276#else
277 if (lseek(input_file->Fd(), off, SEEK_SET) != off) {
278 return false;
279 }
280 constexpr size_t kMaxBufferSize = 4 * ::art::kPageSize;
281 const size_t buffer_size = std::min<uint64_t>(size, kMaxBufferSize);
282 art::UniqueCPtr<void> buffer(malloc(buffer_size));
283 if (buffer == nullptr) {
284 errno = ENOMEM;
285 return false;
286 }
287 while (size != 0) {
288 size_t chunk_size = std::min<uint64_t>(buffer_size, size);
289 if (!input_file->ReadFully(buffer.get(), chunk_size) ||
290 !WriteFully(buffer.get(), chunk_size)) {
291 return false;
292 }
293 size -= chunk_size;
294 }
295#endif
296 return true;
297}
298
Andreas Gampe4303ba92014-11-06 01:00:46 -0800299void FdFile::Erase() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000300 DCHECK(!read_only_mode_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800301 TEMP_FAILURE_RETRY(SetLength(0));
302 TEMP_FAILURE_RETRY(Flush());
303 TEMP_FAILURE_RETRY(Close());
304}
305
306int FdFile::FlushCloseOrErase() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000307 DCHECK(!read_only_mode_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800308 int flush_result = TEMP_FAILURE_RETRY(Flush());
309 if (flush_result != 0) {
310 LOG(::art::ERROR) << "CloseOrErase failed while flushing a file.";
311 Erase();
312 return flush_result;
313 }
314 int close_result = TEMP_FAILURE_RETRY(Close());
315 if (close_result != 0) {
316 LOG(::art::ERROR) << "CloseOrErase failed while closing a file.";
317 Erase();
318 return close_result;
319 }
320 return 0;
321}
322
323int FdFile::FlushClose() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000324 DCHECK(!read_only_mode_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800325 int flush_result = TEMP_FAILURE_RETRY(Flush());
326 if (flush_result != 0) {
327 LOG(::art::ERROR) << "FlushClose failed while flushing a file.";
328 }
329 int close_result = TEMP_FAILURE_RETRY(Close());
330 if (close_result != 0) {
331 LOG(::art::ERROR) << "FlushClose failed while closing a file.";
332 }
333 return (flush_result != 0) ? flush_result : close_result;
334}
335
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800336void FdFile::MarkUnchecked() {
337 guard_state_ = GuardState::kNoCheck;
338}
339
Calin Juravle877fd962016-01-05 14:29:29 +0000340bool FdFile::ClearContent() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000341 DCHECK(!read_only_mode_);
Calin Juravle877fd962016-01-05 14:29:29 +0000342 if (SetLength(0) < 0) {
343 PLOG(art::ERROR) << "Failed to reset the length";
344 return false;
345 }
346 return ResetOffset();
347}
348
349bool FdFile::ResetOffset() {
Calin Juravle2e2db782016-02-23 12:00:03 +0000350 DCHECK(!read_only_mode_);
Calin Juravle877fd962016-01-05 14:29:29 +0000351 off_t rc = TEMP_FAILURE_RETRY(lseek(fd_, 0, SEEK_SET));
352 if (rc == static_cast<off_t>(-1)) {
353 PLOG(art::ERROR) << "Failed to reset the offset";
354 return false;
355 }
356 return true;
357}
358
Elliott Hughes76160052012-12-12 16:31:20 -0800359} // namespace unix_file