blob: 78bc3d5f9f75a17639789ce17956682920322a5c [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
Andreas Gampe4303ba92014-11-06 01:00:46 -080038FdFile::FdFile() : guard_state_(GuardState::kClosed), fd_(-1), auto_close_(true) {
Elliott Hughes76160052012-12-12 16:31:20 -080039}
40
Andreas Gampe4303ba92014-11-06 01:00:46 -080041FdFile::FdFile(int fd, bool check_usage)
42 : guard_state_(check_usage ? GuardState::kBase : GuardState::kNoCheck),
43 fd_(fd), auto_close_(true) {
Elliott Hughes76160052012-12-12 16:31:20 -080044}
45
Andreas Gampe4303ba92014-11-06 01:00:46 -080046FdFile::FdFile(int fd, const std::string& path, bool check_usage)
47 : guard_state_(check_usage ? GuardState::kBase : GuardState::kNoCheck),
48 fd_(fd), file_path_(path), auto_close_(true) {
Brian Carlstromb45ccbf2013-03-13 15:14:24 -070049 CHECK_NE(0U, path.size());
Elliott Hughes76160052012-12-12 16:31:20 -080050}
51
52FdFile::~FdFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -080053 if (kCheckSafeUsage && (guard_state_ < GuardState::kNoCheck)) {
54 if (guard_state_ < GuardState::kFlushed) {
55 LOG(::art::ERROR) << "File " << file_path_ << " wasn't explicitly flushed before destruction.";
56 }
57 if (guard_state_ < GuardState::kClosed) {
58 LOG(::art::ERROR) << "File " << file_path_ << " wasn't explicitly closed before destruction.";
59 }
60 CHECK_GE(guard_state_, GuardState::kClosed);
61 }
Elliott Hughes76160052012-12-12 16:31:20 -080062 if (auto_close_ && fd_ != -1) {
Andreas Gampe4303ba92014-11-06 01:00:46 -080063 if (Close() != 0) {
64 PLOG(::art::WARNING) << "Failed to close file " << file_path_;
65 }
66 }
67}
68
69void FdFile::moveTo(GuardState target, GuardState warn_threshold, const char* warning) {
70 if (kCheckSafeUsage) {
71 if (guard_state_ < GuardState::kNoCheck) {
72 if (warn_threshold < GuardState::kNoCheck && guard_state_ >= warn_threshold) {
73 LOG(::art::ERROR) << warning;
74 }
75 guard_state_ = target;
76 }
77 }
78}
79
80void FdFile::moveUp(GuardState target, const char* warning) {
81 if (kCheckSafeUsage) {
82 if (guard_state_ < GuardState::kNoCheck) {
83 if (guard_state_ < target) {
84 guard_state_ = target;
85 } else if (target < guard_state_) {
86 LOG(::art::ERROR) << warning;
87 }
88 }
Elliott Hughes76160052012-12-12 16:31:20 -080089 }
90}
91
92void FdFile::DisableAutoClose() {
93 auto_close_ = false;
94}
95
96bool FdFile::Open(const std::string& path, int flags) {
97 return Open(path, flags, 0640);
98}
99
100bool FdFile::Open(const std::string& path, int flags, mode_t mode) {
101 CHECK_EQ(fd_, -1) << path;
102 fd_ = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
103 if (fd_ == -1) {
104 return false;
105 }
106 file_path_ = path;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800107 static_assert(O_RDONLY == 0, "Readonly flag has unexpected value.");
108 if (kCheckSafeUsage && (flags & (O_RDWR | O_CREAT | O_WRONLY)) != 0) {
109 // Start in the base state (not flushed, not closed).
110 guard_state_ = GuardState::kBase;
111 } else {
112 // We are not concerned with read-only files. In that case, proper flushing and closing is
113 // not important.
114 guard_state_ = GuardState::kNoCheck;
115 }
Elliott Hughes76160052012-12-12 16:31:20 -0800116 return true;
117}
118
119int FdFile::Close() {
Elliott Hughes6a887d62015-05-15 08:25:58 -0700120 int result = close(fd_);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800121
122 // Test here, so the file is closed and not leaked.
123 if (kCheckSafeUsage) {
124 CHECK_GE(guard_state_, GuardState::kFlushed) << "File " << file_path_
125 << " has not been flushed before closing.";
126 moveUp(GuardState::kClosed, nullptr);
127 }
128
Elliott Hughes76160052012-12-12 16:31:20 -0800129 if (result == -1) {
130 return -errno;
131 } else {
132 fd_ = -1;
133 file_path_ = "";
134 return 0;
135 }
136}
137
138int FdFile::Flush() {
Ian Rogersc5f17732014-06-05 20:48:42 -0700139#ifdef __linux__
Elliott Hughes76160052012-12-12 16:31:20 -0800140 int rc = TEMP_FAILURE_RETRY(fdatasync(fd_));
Ian Rogersc5f17732014-06-05 20:48:42 -0700141#else
142 int rc = TEMP_FAILURE_RETRY(fsync(fd_));
143#endif
Andreas Gampe4303ba92014-11-06 01:00:46 -0800144 moveUp(GuardState::kFlushed, "Flushing closed file.");
Elliott Hughes76160052012-12-12 16:31:20 -0800145 return (rc == -1) ? -errno : rc;
146}
147
148int64_t FdFile::Read(char* buf, int64_t byte_count, int64_t offset) const {
Ian Rogersc5f17732014-06-05 20:48:42 -0700149#ifdef __linux__
Elliott Hughes76160052012-12-12 16:31:20 -0800150 int rc = TEMP_FAILURE_RETRY(pread64(fd_, buf, byte_count, offset));
Ian Rogersc5f17732014-06-05 20:48:42 -0700151#else
152 int rc = TEMP_FAILURE_RETRY(pread(fd_, buf, byte_count, offset));
153#endif
Elliott Hughes76160052012-12-12 16:31:20 -0800154 return (rc == -1) ? -errno : rc;
155}
156
157int FdFile::SetLength(int64_t new_length) {
Ian Rogersc5f17732014-06-05 20:48:42 -0700158#ifdef __linux__
Elliott Hughes76160052012-12-12 16:31:20 -0800159 int rc = TEMP_FAILURE_RETRY(ftruncate64(fd_, new_length));
Ian Rogersc5f17732014-06-05 20:48:42 -0700160#else
161 int rc = TEMP_FAILURE_RETRY(ftruncate(fd_, new_length));
162#endif
Andreas Gampe4303ba92014-11-06 01:00:46 -0800163 moveTo(GuardState::kBase, GuardState::kClosed, "Truncating closed file.");
Elliott Hughes76160052012-12-12 16:31:20 -0800164 return (rc == -1) ? -errno : rc;
165}
166
167int64_t FdFile::GetLength() const {
168 struct stat s;
169 int rc = TEMP_FAILURE_RETRY(fstat(fd_, &s));
170 return (rc == -1) ? -errno : s.st_size;
171}
172
173int64_t FdFile::Write(const char* buf, int64_t byte_count, int64_t offset) {
Ian Rogersc5f17732014-06-05 20:48:42 -0700174#ifdef __linux__
Elliott Hughes76160052012-12-12 16:31:20 -0800175 int rc = TEMP_FAILURE_RETRY(pwrite64(fd_, buf, byte_count, offset));
Ian Rogersc5f17732014-06-05 20:48:42 -0700176#else
177 int rc = TEMP_FAILURE_RETRY(pwrite(fd_, buf, byte_count, offset));
178#endif
Andreas Gampe4303ba92014-11-06 01:00:46 -0800179 moveTo(GuardState::kBase, GuardState::kClosed, "Writing into closed file.");
Elliott Hughes76160052012-12-12 16:31:20 -0800180 return (rc == -1) ? -errno : rc;
181}
182
183int FdFile::Fd() const {
184 return fd_;
185}
186
187bool FdFile::IsOpened() const {
188 return fd_ >= 0;
189}
190
Igor Murashkin37743352014-11-13 14:38:00 -0800191static ssize_t ReadIgnoreOffset(int fd, void *buf, size_t count, off_t offset) {
192 DCHECK_EQ(offset, 0);
193 return read(fd, buf, count);
194}
195
196template <ssize_t (*read_func)(int, void*, size_t, off_t)>
197static bool ReadFullyGeneric(int fd, void* buffer, size_t byte_count, size_t offset) {
Elliott Hughes76160052012-12-12 16:31:20 -0800198 char* ptr = static_cast<char*>(buffer);
199 while (byte_count > 0) {
Igor Murashkin37743352014-11-13 14:38:00 -0800200 ssize_t bytes_read = TEMP_FAILURE_RETRY(read_func(fd, ptr, byte_count, offset));
Andreas Gampe825201e2014-06-20 10:45:30 -0700201 if (bytes_read <= 0) {
202 // 0: end of file
203 // -1: error
Elliott Hughes76160052012-12-12 16:31:20 -0800204 return false;
205 }
206 byte_count -= bytes_read; // Reduce the number of remaining bytes.
207 ptr += bytes_read; // Move the buffer forward.
Igor Murashkin37743352014-11-13 14:38:00 -0800208 offset += static_cast<size_t>(bytes_read); // Move the offset forward.
Elliott Hughes76160052012-12-12 16:31:20 -0800209 }
210 return true;
211}
212
Igor Murashkin37743352014-11-13 14:38:00 -0800213bool FdFile::ReadFully(void* buffer, size_t byte_count) {
214 return ReadFullyGeneric<ReadIgnoreOffset>(fd_, buffer, byte_count, 0);
215}
216
217bool FdFile::PreadFully(void* buffer, size_t byte_count, size_t offset) {
218 return ReadFullyGeneric<pread>(fd_, buffer, byte_count, offset);
219}
220
Ian Rogersef7d42f2014-01-06 12:55:46 -0800221bool FdFile::WriteFully(const void* buffer, size_t byte_count) {
Elliott Hughes76160052012-12-12 16:31:20 -0800222 const char* ptr = static_cast<const char*>(buffer);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800223 moveTo(GuardState::kBase, GuardState::kClosed, "Writing into closed file.");
Elliott Hughes76160052012-12-12 16:31:20 -0800224 while (byte_count > 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800225 ssize_t bytes_written = TEMP_FAILURE_RETRY(write(fd_, ptr, byte_count));
226 if (bytes_written == -1) {
Elliott Hughes76160052012-12-12 16:31:20 -0800227 return false;
228 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800229 byte_count -= bytes_written; // Reduce the number of remaining bytes.
230 ptr += bytes_written; // Move the buffer forward.
Elliott Hughes76160052012-12-12 16:31:20 -0800231 }
232 return true;
233}
234
Vladimir Marko5096e662015-12-08 19:25:49 +0000235bool FdFile::Copy(FdFile* input_file, int64_t offset, int64_t size) {
236 off_t off = static_cast<off_t>(offset);
237 off_t sz = static_cast<off_t>(size);
238 if (offset < 0 || static_cast<int64_t>(off) != offset ||
239 size < 0 || static_cast<int64_t>(sz) != size ||
240 sz > std::numeric_limits<off_t>::max() - off) {
241 errno = EINVAL;
242 return false;
243 }
244 if (size == 0) {
245 return true;
246 }
247#ifdef __linux__
248 // Use sendfile(), available for files since linux kernel 2.6.33.
249 off_t end = off + sz;
250 while (off != end) {
251 int result = TEMP_FAILURE_RETRY(
252 sendfile(Fd(), input_file->Fd(), &off, end - off));
253 if (result == -1) {
254 return false;
255 }
256 // Ignore the number of bytes in `result`, sendfile() already updated `off`.
257 }
258#else
259 if (lseek(input_file->Fd(), off, SEEK_SET) != off) {
260 return false;
261 }
262 constexpr size_t kMaxBufferSize = 4 * ::art::kPageSize;
263 const size_t buffer_size = std::min<uint64_t>(size, kMaxBufferSize);
264 art::UniqueCPtr<void> buffer(malloc(buffer_size));
265 if (buffer == nullptr) {
266 errno = ENOMEM;
267 return false;
268 }
269 while (size != 0) {
270 size_t chunk_size = std::min<uint64_t>(buffer_size, size);
271 if (!input_file->ReadFully(buffer.get(), chunk_size) ||
272 !WriteFully(buffer.get(), chunk_size)) {
273 return false;
274 }
275 size -= chunk_size;
276 }
277#endif
278 return true;
279}
280
Andreas Gampe4303ba92014-11-06 01:00:46 -0800281void FdFile::Erase() {
282 TEMP_FAILURE_RETRY(SetLength(0));
283 TEMP_FAILURE_RETRY(Flush());
284 TEMP_FAILURE_RETRY(Close());
285}
286
287int FdFile::FlushCloseOrErase() {
288 int flush_result = TEMP_FAILURE_RETRY(Flush());
289 if (flush_result != 0) {
290 LOG(::art::ERROR) << "CloseOrErase failed while flushing a file.";
291 Erase();
292 return flush_result;
293 }
294 int close_result = TEMP_FAILURE_RETRY(Close());
295 if (close_result != 0) {
296 LOG(::art::ERROR) << "CloseOrErase failed while closing a file.";
297 Erase();
298 return close_result;
299 }
300 return 0;
301}
302
303int FdFile::FlushClose() {
304 int flush_result = TEMP_FAILURE_RETRY(Flush());
305 if (flush_result != 0) {
306 LOG(::art::ERROR) << "FlushClose failed while flushing a file.";
307 }
308 int close_result = TEMP_FAILURE_RETRY(Close());
309 if (close_result != 0) {
310 LOG(::art::ERROR) << "FlushClose failed while closing a file.";
311 }
312 return (flush_result != 0) ? flush_result : close_result;
313}
314
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800315void FdFile::MarkUnchecked() {
316 guard_state_ = GuardState::kNoCheck;
317}
318
Elliott Hughes76160052012-12-12 16:31:20 -0800319} // namespace unix_file