1 // A C++ interface to POSIX functions.
2 //
3 // Copyright (c) 2012 - 2016, Victor Zverovich
4 // All rights reserved.
5 //
6 // For the license information refer to format.h.
7
8 // Disable bogus MSVC warnings.
9 #if !defined(_CRT_SECURE_NO_WARNINGS) && defined(_MSC_VER)
10 # define _CRT_SECURE_NO_WARNINGS
11 #endif
12
13 #include "fmt/posix.h"
14
15 #include <climits>
16
17 #if FMT_USE_FCNTL
18 #include <sys/stat.h>
19 #include <sys/types.h>
20
21 #ifndef _WIN32
22 # include <unistd.h>
23 #else
24 # ifndef WIN32_LEAN_AND_MEAN
25 # define WIN32_LEAN_AND_MEAN
26 # endif
27 # include <io.h>
28 # include <windows.h>
29
30 # define O_CREAT _O_CREAT
31 # define O_TRUNC _O_TRUNC
32
33 # ifndef S_IRUSR
34 # define S_IRUSR _S_IREAD
35 # endif
36
37 # ifndef S_IWUSR
38 # define S_IWUSR _S_IWRITE
39 # endif
40
41 # ifdef __MINGW32__
42 # define _SH_DENYNO 0x40
43 # endif
44 #endif // _WIN32
45 #endif // FMT_USE_FCNTL
46
47 #ifdef fileno
48 # undef fileno
49 #endif
50
51 namespace {
52 #ifdef _WIN32
53 // Return type of read and write functions.
54 using RWResult = int;
55
56 // On Windows the count argument to read and write is unsigned, so convert
57 // it from size_t preventing integer overflow.
convert_rwcount(std::size_t count)58 inline unsigned convert_rwcount(std::size_t count) {
59 return count <= UINT_MAX ? static_cast<unsigned>(count) : UINT_MAX;
60 }
61 #else
62 // Return type of read and write functions.
63 using RWResult = ssize_t;
64
65 inline std::size_t convert_rwcount(std::size_t count) { return count; }
66 #endif
67 } // namespace
68
69 FMT_BEGIN_NAMESPACE
70
~buffered_file()71 buffered_file::~buffered_file() FMT_NOEXCEPT {
72 if (file_ && FMT_SYSTEM(fclose(file_)) != 0)
73 report_system_error(errno, "cannot close file");
74 }
75
buffered_file(cstring_view filename,cstring_view mode)76 buffered_file::buffered_file(cstring_view filename, cstring_view mode) {
77 FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())),
78 nullptr);
79 if (!file_)
80 FMT_THROW(system_error(errno, "cannot open file {}", filename.c_str()));
81 }
82
close()83 void buffered_file::close() {
84 if (!file_) return;
85 int result = FMT_SYSTEM(fclose(file_));
86 file_ = nullptr;
87 if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
88 }
89
90 // A macro used to prevent expansion of fileno on broken versions of MinGW.
91 #define FMT_ARGS
92
fileno() const93 int buffered_file::fileno() const {
94 int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_));
95 if (fd == -1) FMT_THROW(system_error(errno, "cannot get file descriptor"));
96 return fd;
97 }
98
99 #if FMT_USE_FCNTL
file(cstring_view path,int oflag)100 file::file(cstring_view path, int oflag) {
101 int mode = S_IRUSR | S_IWUSR;
102 #if defined(_WIN32) && !defined(__MINGW32__)
103 fd_ = -1;
104 FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode));
105 #else
106 FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode)));
107 #endif
108 if (fd_ == -1)
109 FMT_THROW(system_error(errno, "cannot open file {}", path.c_str()));
110 }
111
~file()112 file::~file() FMT_NOEXCEPT {
113 // Don't retry close in case of EINTR!
114 // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
115 if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0)
116 report_system_error(errno, "cannot close file");
117 }
118
close()119 void file::close() {
120 if (fd_ == -1) return;
121 // Don't retry close in case of EINTR!
122 // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
123 int result = FMT_POSIX_CALL(close(fd_));
124 fd_ = -1;
125 if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
126 }
127
size() const128 long long file::size() const {
129 #ifdef _WIN32
130 // Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT
131 // is less than 0x0500 as is the case with some default MinGW builds.
132 // Both functions support large file sizes.
133 DWORD size_upper = 0;
134 HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_));
135 DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper));
136 if (size_lower == INVALID_FILE_SIZE) {
137 DWORD error = GetLastError();
138 if (error != NO_ERROR)
139 FMT_THROW(windows_error(GetLastError(), "cannot get file size"));
140 }
141 unsigned long long long_size = size_upper;
142 return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower;
143 #else
144 using Stat = struct stat;
145 Stat file_stat = Stat();
146 if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1)
147 FMT_THROW(system_error(errno, "cannot get file attributes"));
148 static_assert(sizeof(long long) >= sizeof(file_stat.st_size),
149 "return type of file::size is not large enough");
150 return file_stat.st_size;
151 #endif
152 }
153
read(void * buffer,std::size_t count)154 std::size_t file::read(void* buffer, std::size_t count) {
155 RWResult result = 0;
156 FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count))));
157 if (result < 0) FMT_THROW(system_error(errno, "cannot read from file"));
158 return internal::to_unsigned(result);
159 }
160
write(const void * buffer,std::size_t count)161 std::size_t file::write(const void* buffer, std::size_t count) {
162 RWResult result = 0;
163 FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count))));
164 if (result < 0) FMT_THROW(system_error(errno, "cannot write to file"));
165 return internal::to_unsigned(result);
166 }
167
dup(int fd)168 file file::dup(int fd) {
169 // Don't retry as dup doesn't return EINTR.
170 // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html
171 int new_fd = FMT_POSIX_CALL(dup(fd));
172 if (new_fd == -1)
173 FMT_THROW(system_error(errno, "cannot duplicate file descriptor {}", fd));
174 return file(new_fd);
175 }
176
dup2(int fd)177 void file::dup2(int fd) {
178 int result = 0;
179 FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
180 if (result == -1) {
181 FMT_THROW(system_error(errno, "cannot duplicate file descriptor {} to {}",
182 fd_, fd));
183 }
184 }
185
dup2(int fd,error_code & ec)186 void file::dup2(int fd, error_code& ec) FMT_NOEXCEPT {
187 int result = 0;
188 FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
189 if (result == -1) ec = error_code(errno);
190 }
191
pipe(file & read_end,file & write_end)192 void file::pipe(file& read_end, file& write_end) {
193 // Close the descriptors first to make sure that assignments don't throw
194 // and there are no leaks.
195 read_end.close();
196 write_end.close();
197 int fds[2] = {};
198 #ifdef _WIN32
199 // Make the default pipe capacity same as on Linux 2.6.11+.
200 enum { DEFAULT_CAPACITY = 65536 };
201 int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY));
202 #else
203 // Don't retry as the pipe function doesn't return EINTR.
204 // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html
205 int result = FMT_POSIX_CALL(pipe(fds));
206 #endif
207 if (result != 0) FMT_THROW(system_error(errno, "cannot create pipe"));
208 // The following assignments don't throw because read_fd and write_fd
209 // are closed.
210 read_end = file(fds[0]);
211 write_end = file(fds[1]);
212 }
213
fdopen(const char * mode)214 buffered_file file::fdopen(const char* mode) {
215 // Don't retry as fdopen doesn't return EINTR.
216 FILE* f = FMT_POSIX_CALL(fdopen(fd_, mode));
217 if (!f)
218 FMT_THROW(
219 system_error(errno, "cannot associate stream with file descriptor"));
220 buffered_file bf(f);
221 fd_ = -1;
222 return bf;
223 }
224
getpagesize()225 long getpagesize() {
226 #ifdef _WIN32
227 SYSTEM_INFO si;
228 GetSystemInfo(&si);
229 return si.dwPageSize;
230 #else
231 long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE));
232 if (size < 0) FMT_THROW(system_error(errno, "cannot get memory page size"));
233 return size;
234 #endif
235 }
236 #endif // FMT_USE_FCNTL
237 FMT_END_NAMESPACE
238