F´ Flight Software - C/C++ Documentation
A framework for building embedded system applications to NASA flight quality standards.
File.cpp
Go to the documentation of this file.
1 // ======================================================================
2 // \title Os/Posix/File.cpp
3 // \brief posix implementation for Os::File
4 // ======================================================================
5 #include <fcntl.h>
6 #include <unistd.h>
7 #include <cerrno>
8 #include <limits>
9 #include <type_traits>
10 
11 #include <Fw/Types/Assert.hpp>
12 #include <Os/File.hpp>
13 #include <Os/Posix/File.hpp>
14 #include <Os/Posix/error.hpp>
15 
16 namespace Os {
17 namespace Posix {
18 namespace File {
19 
20 // O_SYNC is not defined on every system. This will set up the SYNC_FLAGS variable to be O_SYNC when defined and
21 // (0) when not defined. This allows OPEN_SYNC_WRITE to fall-back to OPEN_WRITE on those systems.
22 #if defined(O_SYNC)
23 #define SYNC_FLAGS O_SYNC
24 #else
25 #define SYNC_FLAGS (0)
26 #endif
27 
28 // Create constants for the max limits of the signed types
29 // These constants are used for comparisons with complementary unsigned types to avoid sign-compare warning
30 using UnsignedOffT = std::make_unsigned<off_t>::type;
31 static const UnsignedOffT OFF_T_MAX_LIMIT = static_cast<UnsignedOffT>(std::numeric_limits<off_t>::max());
32 using UnsignedSSizeT = std::make_unsigned<ssize_t>::type;
33 static const UnsignedSSizeT SSIZE_T_MAX_LIMIT = static_cast<UnsignedSSizeT>(std::numeric_limits<ssize_t>::max());
34 
35 // Ensure size of FwSizeType is large enough to fit eh necessary range
36 static_assert(sizeof(FwSignedSizeType) >= sizeof(off_t),
37  "FwSignedSizeType is not large enough to store values of type off_t");
38 static_assert(sizeof(FwSignedSizeType) >= sizeof(ssize_t),
39  "FwSignedSizeType is not large enough to store values of type ssize_t");
40 static_assert(sizeof(FwSizeType) >= sizeof(size_t), "FwSizeType is not large enough to store values of type size_t");
41 
42 // Now check ranges of FwSizeType
43 static_assert(std::numeric_limits<FwSignedSizeType>::max() >= std::numeric_limits<off_t>::max(),
44  "Maximum value of FwSignedSizeType less than the maximum value of off_t. Configure a larger type.");
45 static_assert(std::numeric_limits<FwSizeType>::max() >= OFF_T_MAX_LIMIT,
46  "Maximum value of FwSizeType less than the maximum value of off_t. Configure a larger type.");
47 static_assert(std::numeric_limits<FwSignedSizeType>::max() >= std::numeric_limits<ssize_t>::max(),
48  "Maximum value of FwSignedSizeType less than the maximum value of ssize_t. Configure a larger type.");
50  "Minimum value of FwSignedSizeType larger than the minimum value of off_t. Configure a larger type.");
52  "Minimum value of FwSizeType larger than the minimum value of ssize_t. Configure a larger type.");
53 static_assert(std::numeric_limits<FwSizeType>::max() >= std::numeric_limits<size_t>::max(),
54  "Maximum value of FwSizeType less than the maximum value of size_t. Configure a larger type.");
55 
58  // Must properly duplicate the file handle
59  this->m_handle.m_file_descriptor = fcntl(other.m_handle.m_file_descriptor, F_DUPFD, 0);
60 }
61 
63  if (this != &other) {
64  this->m_handle.m_file_descriptor = fcntl(other.m_handle.m_file_descriptor, F_DUPFD, 0);
65  }
66  return *this;
67 }
68 
69 mode_t PosixFile::map_open_create_mode(const U32 create_mode) {
70  mode_t out_mode = 0;
71 
72  // Some posix systems (e.g. Darwin) use the older S_IREAD and S_IWRITE flags
73  // while other systems (e.g. Linux) use the newer S_IRUSR and S_IWUSR flags.
74 #if defined(S_IREAD)
75  out_mode |= (create_mode & Os::FILE_MODE_IRUSR) ? S_IREAD : 0;
76  out_mode |= (create_mode & Os::FILE_MODE_IWUSR) ? S_IWRITE : 0;
77  out_mode |= (create_mode & Os::FILE_MODE_IXUSR) ? S_IEXEC : 0;
78 #else
79  out_mode |= (create_mode & Os::FILE_MODE_IRUSR) ? S_IRUSR : 0;
80  out_mode |= (create_mode & Os::FILE_MODE_IWUSR) ? S_IWUSR : 0;
81  out_mode |= (create_mode & Os::FILE_MODE_IXUSR) ? S_IXUSR : 0;
82 #endif
83 
84  out_mode |= (create_mode & Os::FILE_MODE_IRGRP) ? S_IRGRP : 0;
85  out_mode |= (create_mode & Os::FILE_MODE_IWGRP) ? S_IWGRP : 0;
86  out_mode |= (create_mode & Os::FILE_MODE_IXGRP) ? S_IXGRP : 0;
87 
88  out_mode |= (create_mode & Os::FILE_MODE_IROTH) ? S_IROTH : 0;
89  out_mode |= (create_mode & Os::FILE_MODE_IWOTH) ? S_IWOTH : 0;
90  out_mode |= (create_mode & Os::FILE_MODE_IXOTH) ? S_IXOTH : 0;
91 
92  out_mode |= (create_mode & Os::FILE_MODE_ISUID) ? S_ISUID : 0;
93  out_mode |= (create_mode & Os::FILE_MODE_ISGID) ? S_ISGID : 0;
94  out_mode |= (create_mode & Os::FILE_MODE_ISVTX) ? S_ISVTX : 0;
95 
96  return out_mode;
97 }
98 
99 PosixFile::Status PosixFile::open(const char* filepath,
100  PosixFile::Mode requested_mode,
101  PosixFile::OverwriteType overwrite) {
102  int mode_flags = 0;
103  Status status = OP_OK;
104  switch (requested_mode) {
105  case OPEN_READ:
106  mode_flags = O_RDONLY;
107  break;
108  case OPEN_WRITE:
109  mode_flags = O_WRONLY | O_CREAT;
110  break;
111  case OPEN_SYNC_WRITE:
112  mode_flags = O_WRONLY | O_CREAT | SYNC_FLAGS;
113  break;
114  case OPEN_CREATE:
115  mode_flags =
116  O_WRONLY | O_CREAT | O_TRUNC | ((overwrite == PosixFile::OverwriteType::OVERWRITE) ? 0 : O_EXCL);
117  break;
118  case OPEN_APPEND:
119  mode_flags = O_WRONLY | O_CREAT | O_APPEND;
120  break;
121  default:
122  FW_ASSERT(0, requested_mode);
123  break;
124  }
125  int descriptor = ::open(filepath, mode_flags, map_open_create_mode(Os::FILE_DEFAULT_CREATE_MODE));
126  if (PosixFileHandle::INVALID_FILE_DESCRIPTOR == descriptor) {
127  int errno_store = errno;
128  status = Os::Posix::errno_to_file_status(errno_store);
129  }
130  this->m_handle.m_file_descriptor = descriptor;
131  return status;
132 }
133 
135  // Only close file handles that are not open
137  (void)::close(this->m_handle.m_file_descriptor);
139  }
140 }
141 
143  FwSizeType current_position = 0;
144  Status status = this->position(current_position);
145  size_result = 0;
146  if (Os::File::Status::OP_OK == status) {
147  // Must be a coding error if current_position is larger than off_t max in Posix File
148  FW_ASSERT(current_position <= OFF_T_MAX_LIMIT);
149  // Seek to the end of the file to determine size
150  off_t end_of_file = ::lseek(this->m_handle.m_file_descriptor, 0, SEEK_END);
151  if (PosixFileHandle::ERROR_RETURN_VALUE == end_of_file) {
152  int errno_store = errno;
153  status = Os::Posix::errno_to_file_status(errno_store);
154  }
155  // Return to original position
156  (void)::lseek(this->m_handle.m_file_descriptor, static_cast<off_t>(current_position), SEEK_SET);
157  size_result = static_cast<FwSizeType>(end_of_file);
158  }
159  return status;
160 }
161 
163  Status status = OP_OK;
164  position_result = 0;
165  off_t actual = ::lseek(this->m_handle.m_file_descriptor, 0, SEEK_CUR);
166  if (PosixFileHandle::ERROR_RETURN_VALUE == actual) {
167  int errno_store = errno;
168  status = Os::Posix::errno_to_file_status(errno_store);
169  }
170  // Protected by static assertion (FwSizeType >= off_t)
171  position_result = static_cast<FwSizeType>(actual);
172  return status;
173 }
174 
176  PosixFile::Status status = Os::File::Status::NOT_SUPPORTED;
177  // Check for larger size than posix supports
178  if ((length > OFF_T_MAX_LIMIT) || (offset > OFF_T_MAX_LIMIT) ||
179  (std::numeric_limits<off_t>::max() - length) < offset) {
180  status = Os::File::Status::BAD_SIZE;
181  }
182  // posix_fallocate is only available with the posix C-API post version 200112L, however; it is not guaranteed that
183  // this call is properly implemented. This code starts with a status of "NOT_SUPPORTED". When the standard is met
184  // an attempt will be made to called posix_fallocate, and should that still return NOT_SUPPORTED then fallback
185  // code is engaged to synthesize this behavior.
186 #if _POSIX_C_SOURCE >= 200112L && !(defined(FPRIME_SYNTHETIC_FALLOCATE) && FPRIME_SYNTHETIC_FALLOCATE)
187  else {
188  int errno_status =
189  ::posix_fallocate(this->m_handle.m_file_descriptor, static_cast<off_t>(offset), static_cast<off_t>(length));
190  status = Os::Posix::errno_to_file_status(errno_status);
191  }
192 #endif
193  // When the operation is not supported or posix-API is not sufficient, fallback to a slower algorithm
194  if (Os::File::Status::NOT_SUPPORTED == status) {
195  // Calculate size
196  FwSizeType file_size = 0;
197  status = this->size(file_size);
198  if (Os::File::Status::OP_OK == status) {
199  // Calculate current position
200  FwSizeType file_position = 0;
201  status = this->position(file_position);
202  // Check for overflow in seek calls
203  if (file_position > static_cast<FwSizeType>(std::numeric_limits<FwSignedSizeType>::max()) ||
204  file_size > static_cast<FwSizeType>(std::numeric_limits<FwSignedSizeType>::max())) {
205  status = Os::File::Status::BAD_SIZE;
206  }
207  // Only allocate when the file is smaller than the allocation
208  else if ((Os::File::Status::OP_OK == status) && (file_size < (offset + length))) {
209  const FwSizeType write_length = (offset + length) - file_size;
210  status = this->seek(static_cast<FwSignedSizeType>(file_size), PosixFile::SeekType::ABSOLUTE);
211  if (Os::File::Status::OP_OK == status) {
212  // Fill in zeros past size of file to ensure compatibility with fallocate
213  for (FwSizeType i = 0; i < write_length; i++) {
214  FwSizeType write_size = 1;
215  status =
216  this->write(reinterpret_cast<const U8*>("\0"), write_size, PosixFile::WaitType::NO_WAIT);
217  if (Status::OP_OK != status || write_size != 1) {
218  break;
219  }
220  }
221  // Return to original position
222  if (Os::File::Status::OP_OK == status) {
223  status =
224  this->seek(static_cast<FwSignedSizeType>(file_position), PosixFile::SeekType::ABSOLUTE);
225  }
226  }
227  }
228  }
229  }
230  return status;
231 }
232 
234  Status status = OP_OK;
235  if (offset > std::numeric_limits<off_t>::max()) {
236  status = BAD_SIZE;
237  } else {
238  off_t actual = ::lseek(this->m_handle.m_file_descriptor, static_cast<off_t>(offset),
239  (seekType == SeekType::ABSOLUTE) ? SEEK_SET : SEEK_CUR);
240  int errno_store = errno;
241  if (actual == PosixFileHandle::ERROR_RETURN_VALUE) {
242  status = Os::Posix::errno_to_file_status(errno_store);
243  } else if ((seekType == SeekType::ABSOLUTE) && (actual != offset)) {
245  }
246  }
247  return status;
248 }
249 
251  PosixFile::Status status = OP_OK;
252  if (PosixFileHandle::ERROR_RETURN_VALUE == ::fsync(this->m_handle.m_file_descriptor)) {
253  int errno_store = errno;
254  status = Os::Posix::errno_to_file_status(errno_store);
255  }
256  return status;
257 }
258 
260  Status status = OP_OK;
261  FwSizeType accumulated = 0;
262  // Loop up to 2 times for each by, bounded to prevent overflow
263  const FwSizeType maximum =
264  (size > (std::numeric_limits<FwSizeType>::max() / 2)) ? std::numeric_limits<FwSizeType>::max() : size * 2;
265  // POSIX APIs are implementation dependent when dealing with sizes larger than the signed return value
266  // thus we ensure a clear decision: BAD_SIZE
267  if (size > SSIZE_T_MAX_LIMIT) {
268  return BAD_SIZE;
269  }
270 
271  for (FwSizeType i = 0; i < maximum && accumulated < size; i++) {
272  // char* for some posix implementations
273  ssize_t read_size = ::read(this->m_handle.m_file_descriptor, reinterpret_cast<CHAR*>(&buffer[accumulated]),
274  static_cast<size_t>(size - accumulated));
275  // Non-interrupt error
276  if (PosixFileHandle::ERROR_RETURN_VALUE == read_size) {
277  int errno_store = errno;
278  // Interrupted w/o read, try again
279  if (EINTR != errno_store) {
280  continue;
281  }
282  status = Os::Posix::errno_to_file_status(errno_store);
283  break;
284  }
285  // End-of-file
286  else if (read_size == 0) {
287  break;
288  }
289  accumulated += static_cast<FwSizeType>(read_size);
290  // Stop looping when we had a good read and are not waiting
291  if (not wait) {
292  break;
293  }
294  }
295  size = accumulated;
296  return status;
297 }
298 
300  Status status = OP_OK;
301  FwSizeType accumulated = 0;
302  // Loop up to 2 times for each by, bounded to prevent overflow
303  const FwSizeType maximum =
304  (size > (std::numeric_limits<FwSizeType>::max() / 2)) ? std::numeric_limits<FwSizeType>::max() : size * 2;
305  // POSIX APIs are implementation dependent when dealing with sizes larger than the signed return value
306  // thus we ensure a clear decision: BAD_SIZE
307  if (size > SSIZE_T_MAX_LIMIT) {
308  return BAD_SIZE;
309  }
310 
311  for (FwSizeType i = 0; i < maximum && accumulated < size; i++) {
312  // char* for some posix implementations
313  ssize_t write_size =
314  ::write(this->m_handle.m_file_descriptor, reinterpret_cast<const CHAR*>(&buffer[accumulated]),
315  static_cast<size_t>(size - accumulated));
316  // Non-interrupt error
317  if (PosixFileHandle::ERROR_RETURN_VALUE == write_size || write_size < 0) {
318  int errno_store = errno;
319  // Interrupted w/o write, try again
320  if (EINTR != errno_store) {
321  continue;
322  }
323  status = Os::Posix::errno_to_file_status(errno_store);
324  break;
325  }
326  accumulated += static_cast<FwSizeType>(write_size);
327  }
328  size = accumulated;
329  // When waiting, sync to disk
330  if (wait) {
331  int fsync_return = ::fsync(this->m_handle.m_file_descriptor);
332  if (PosixFileHandle::ERROR_RETURN_VALUE == fsync_return) {
333  int errno_store = errno;
334  status = Os::Posix::errno_to_file_status(errno_store);
335  }
336  }
337  return status;
338 }
339 
341  return &this->m_handle;
342 }
343 
344 } // namespace File
345 } // namespace Posix
346 } // namespace Os
Status size(FwSizeType &size_result) override
get size of currently open file
Definition: File.cpp:142
base implementation of FileHandle
Definition: File.hpp:24
Status preallocate(FwSizeType offset, FwSizeType length) override
pre-allocate file storage
Definition: File.cpp:175
Operation succeeded.
Definition: Os.hpp:26
A catch-all for other errors. Have to look in implementation-specific code.
PlatformSizeType FwSizeType
PosixFile()=default
constructor
static const UnsignedSSizeT SSIZE_T_MAX_LIMIT
Definition: File.cpp:33
Open file for writing; writes don&#39;t return until data is on disk.
Definition: File.hpp:34
int m_file_descriptor
Posix file descriptor.
Definition: File.hpp:22
Open file for writing.
Definition: File.hpp:33
PlatformSignedSizeType FwSignedSizeType
#define SYNC_FLAGS
Definition: File.cpp:25
posix implementation of Os::File
Definition: File.hpp:31
Status write(const U8 *buffer, FwSizeType &size, WaitType wait) override
read data from this file into supplied buffer bounded by size
Definition: File.cpp:299
Open file for appending.
Definition: File.hpp:35
static constexpr int ERROR_RETURN_VALUE
Definition: File.hpp:19
static constexpr int INVALID_FILE_DESCRIPTOR
Definition: File.hpp:18
Status read(U8 *buffer, FwSizeType &size, WaitType wait) override
read data from this file into supplied buffer bounded by size
Definition: File.cpp:259
void close() override
close the file, if not opened then do nothing
Definition: File.cpp:134
uint8_t U8
8-bit unsigned integer
Definition: BasicTypes.h:53
PosixFile & operator=(const PosixFile &other)
assignment operator that copies the internal representation
Definition: File.cpp:62
static U32 min(const U32 a, const U32 b)
Definition: Checksum.cpp:16
Operation was successful.
Definition: File.hpp:40
Status seek(FwSignedSizeType offset, SeekType seekType) override
seek the file pointer to the given offset
Definition: File.cpp:233
Open file for reading.
Definition: File.hpp:31
File::Status errno_to_file_status(int errno_input)
Definition: error.cpp:11
std::make_unsigned< ssize_t >::type UnsignedSSizeT
Definition: File.cpp:32
static const UnsignedOffT OFF_T_MAX_LIMIT
Definition: File.cpp:31
Invalid size parameter.
Definition: File.hpp:44
Status flush() override
flush file contents to storage
Definition: File.cpp:250
FileHandle * getHandle() override
returns the raw file handle
Definition: File.cpp:340
Status position(FwSizeType &position_result) override
get file pointer position of the currently open file
Definition: File.cpp:162
std::make_unsigned< off_t >::type UnsignedOffT
Definition: File.cpp:30
Os::FileInterface::Status open(const char *path, Mode mode, OverwriteType overwrite) override
open file with supplied path and mode
Definition: File.cpp:99
#define FW_ASSERT(...)
Definition: Assert.hpp:14
Open file for writing and truncates file if it exists, ie same flags as creat()
Definition: File.hpp:32