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