1 /*
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"
18 
19 #include <errno.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 
24 #include "base/logging.h"
25 
26 namespace unix_file {
27 
FdFile()28 FdFile::FdFile() : guard_state_(GuardState::kClosed), fd_(-1), auto_close_(true) {
29 }
30 
FdFile(int fd,bool check_usage)31 FdFile::FdFile(int fd, bool check_usage)
32     : guard_state_(check_usage ? GuardState::kBase : GuardState::kNoCheck),
33       fd_(fd), auto_close_(true) {
34 }
35 
FdFile(int fd,const std::string & path,bool check_usage)36 FdFile::FdFile(int fd, const std::string& path, bool check_usage)
37     : guard_state_(check_usage ? GuardState::kBase : GuardState::kNoCheck),
38       fd_(fd), file_path_(path), auto_close_(true) {
39   CHECK_NE(0U, path.size());
40 }
41 
~FdFile()42 FdFile::~FdFile() {
43   if (kCheckSafeUsage && (guard_state_ < GuardState::kNoCheck)) {
44     if (guard_state_ < GuardState::kFlushed) {
45       LOG(ERROR) << "File " << file_path_ << " wasn't explicitly flushed before destruction.";
46     }
47     if (guard_state_ < GuardState::kClosed) {
48       LOG(ERROR) << "File " << file_path_ << " wasn't explicitly closed before destruction.";
49     }
50     CHECK_GE(guard_state_, GuardState::kClosed);
51   }
52   if (auto_close_ && fd_ != -1) {
53     if (Close() != 0) {
54       PLOG(WARNING) << "Failed to close file " << file_path_;
55     }
56   }
57 }
58 
moveTo(GuardState target,GuardState warn_threshold,const char * warning)59 void FdFile::moveTo(GuardState target, GuardState warn_threshold, const char* warning) {
60   if (kCheckSafeUsage) {
61     if (guard_state_ < GuardState::kNoCheck) {
62       if (warn_threshold < GuardState::kNoCheck && guard_state_ >= warn_threshold) {
63         LOG(ERROR) << warning;
64       }
65       guard_state_ = target;
66     }
67   }
68 }
69 
moveUp(GuardState target,const char * warning)70 void FdFile::moveUp(GuardState target, const char* warning) {
71   if (kCheckSafeUsage) {
72     if (guard_state_ < GuardState::kNoCheck) {
73       if (guard_state_ < target) {
74         guard_state_ = target;
75       } else if (target < guard_state_) {
76         LOG(ERROR) << warning;
77       }
78     }
79   }
80 }
81 
DisableAutoClose()82 void FdFile::DisableAutoClose() {
83   auto_close_ = false;
84 }
85 
Open(const std::string & path,int flags)86 bool FdFile::Open(const std::string& path, int flags) {
87   return Open(path, flags, 0640);
88 }
89 
Open(const std::string & path,int flags,mode_t mode)90 bool FdFile::Open(const std::string& path, int flags, mode_t mode) {
91   CHECK_EQ(fd_, -1) << path;
92   fd_ = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
93   if (fd_ == -1) {
94     return false;
95   }
96   file_path_ = path;
97   static_assert(O_RDONLY == 0, "Readonly flag has unexpected value.");
98   if (kCheckSafeUsage && (flags & (O_RDWR | O_CREAT | O_WRONLY)) != 0) {
99     // Start in the base state (not flushed, not closed).
100     guard_state_ = GuardState::kBase;
101   } else {
102     // We are not concerned with read-only files. In that case, proper flushing and closing is
103     // not important.
104     guard_state_ = GuardState::kNoCheck;
105   }
106   return true;
107 }
108 
Close()109 int FdFile::Close() {
110   int result = TEMP_FAILURE_RETRY(close(fd_));
111 
112   // Test here, so the file is closed and not leaked.
113   if (kCheckSafeUsage) {
114     CHECK_GE(guard_state_, GuardState::kFlushed) << "File " << file_path_
115         << " has not been flushed before closing.";
116     moveUp(GuardState::kClosed, nullptr);
117   }
118 
119   if (result == -1) {
120     return -errno;
121   } else {
122     fd_ = -1;
123     file_path_ = "";
124     return 0;
125   }
126 }
127 
Flush()128 int FdFile::Flush() {
129 #ifdef __linux__
130   int rc = TEMP_FAILURE_RETRY(fdatasync(fd_));
131 #else
132   int rc = TEMP_FAILURE_RETRY(fsync(fd_));
133 #endif
134   moveUp(GuardState::kFlushed, "Flushing closed file.");
135   return (rc == -1) ? -errno : rc;
136 }
137 
Read(char * buf,int64_t byte_count,int64_t offset) const138 int64_t FdFile::Read(char* buf, int64_t byte_count, int64_t offset) const {
139 #ifdef __linux__
140   int rc = TEMP_FAILURE_RETRY(pread64(fd_, buf, byte_count, offset));
141 #else
142   int rc = TEMP_FAILURE_RETRY(pread(fd_, buf, byte_count, offset));
143 #endif
144   return (rc == -1) ? -errno : rc;
145 }
146 
SetLength(int64_t new_length)147 int FdFile::SetLength(int64_t new_length) {
148 #ifdef __linux__
149   int rc = TEMP_FAILURE_RETRY(ftruncate64(fd_, new_length));
150 #else
151   int rc = TEMP_FAILURE_RETRY(ftruncate(fd_, new_length));
152 #endif
153   moveTo(GuardState::kBase, GuardState::kClosed, "Truncating closed file.");
154   return (rc == -1) ? -errno : rc;
155 }
156 
GetLength() const157 int64_t FdFile::GetLength() const {
158   struct stat s;
159   int rc = TEMP_FAILURE_RETRY(fstat(fd_, &s));
160   return (rc == -1) ? -errno : s.st_size;
161 }
162 
Write(const char * buf,int64_t byte_count,int64_t offset)163 int64_t FdFile::Write(const char* buf, int64_t byte_count, int64_t offset) {
164 #ifdef __linux__
165   int rc = TEMP_FAILURE_RETRY(pwrite64(fd_, buf, byte_count, offset));
166 #else
167   int rc = TEMP_FAILURE_RETRY(pwrite(fd_, buf, byte_count, offset));
168 #endif
169   moveTo(GuardState::kBase, GuardState::kClosed, "Writing into closed file.");
170   return (rc == -1) ? -errno : rc;
171 }
172 
Fd() const173 int FdFile::Fd() const {
174   return fd_;
175 }
176 
IsOpened() const177 bool FdFile::IsOpened() const {
178   return fd_ >= 0;
179 }
180 
ReadFully(void * buffer,size_t byte_count)181 bool FdFile::ReadFully(void* buffer, size_t byte_count) {
182   char* ptr = static_cast<char*>(buffer);
183   while (byte_count > 0) {
184     ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd_, ptr, byte_count));
185     if (bytes_read <= 0) {
186       // 0: end of file
187       // -1: error
188       return false;
189     }
190     byte_count -= bytes_read;  // Reduce the number of remaining bytes.
191     ptr += bytes_read;  // Move the buffer forward.
192   }
193   return true;
194 }
195 
WriteFully(const void * buffer,size_t byte_count)196 bool FdFile::WriteFully(const void* buffer, size_t byte_count) {
197   const char* ptr = static_cast<const char*>(buffer);
198   moveTo(GuardState::kBase, GuardState::kClosed, "Writing into closed file.");
199   while (byte_count > 0) {
200     ssize_t bytes_written = TEMP_FAILURE_RETRY(write(fd_, ptr, byte_count));
201     if (bytes_written == -1) {
202       return false;
203     }
204     byte_count -= bytes_written;  // Reduce the number of remaining bytes.
205     ptr += bytes_written;  // Move the buffer forward.
206   }
207   return true;
208 }
209 
Erase()210 void FdFile::Erase() {
211   TEMP_FAILURE_RETRY(SetLength(0));
212   TEMP_FAILURE_RETRY(Flush());
213   TEMP_FAILURE_RETRY(Close());
214 }
215 
FlushCloseOrErase()216 int FdFile::FlushCloseOrErase() {
217   int flush_result = TEMP_FAILURE_RETRY(Flush());
218   if (flush_result != 0) {
219     LOG(ERROR) << "CloseOrErase failed while flushing a file.";
220     Erase();
221     return flush_result;
222   }
223   int close_result = TEMP_FAILURE_RETRY(Close());
224   if (close_result != 0) {
225     LOG(ERROR) << "CloseOrErase failed while closing a file.";
226     Erase();
227     return close_result;
228   }
229   return 0;
230 }
231 
FlushClose()232 int FdFile::FlushClose() {
233   int flush_result = TEMP_FAILURE_RETRY(Flush());
234   if (flush_result != 0) {
235     LOG(ERROR) << "FlushClose failed while flushing a file.";
236   }
237   int close_result = TEMP_FAILURE_RETRY(Close());
238   if (close_result != 0) {
239     LOG(ERROR) << "FlushClose failed while closing a file.";
240   }
241   return (flush_result != 0) ? flush_result : close_result;
242 }
243 
MarkUnchecked()244 void FdFile::MarkUnchecked() {
245   guard_state_ = GuardState::kNoCheck;
246 }
247 
248 }  // namespace unix_file
249