1 // clang-format off
2 // Formatting library for C++ - optional OS-specific functionality
3 //
4 // Copyright (c) 2012 - 2016, Victor Zverovich
5 // All rights reserved.
6 //
7 // For the license information refer to format.h.
8
9 // Disable bogus MSVC warnings.
10 #if !defined(_CRT_SECURE_NO_WARNINGS) && defined(_MSC_VER)
11 # define _CRT_SECURE_NO_WARNINGS
12 #endif
13
14 #include "fmt/os.h"
15
16 #include <climits>
17
18 #if FMT_USE_FCNTL
19 # include <sys/stat.h>
20 # include <sys/types.h>
21
22 # ifndef _WIN32
23 # include <unistd.h>
24 # else
25 # ifndef WIN32_LEAN_AND_MEAN
26 # define WIN32_LEAN_AND_MEAN
27 # endif
28 # include <io.h>
29 # include <windows.h>
30
31 # define O_CREAT _O_CREAT
32 # define O_TRUNC _O_TRUNC
33
34 # ifndef S_IRUSR
35 # define S_IRUSR _S_IREAD
36 # endif
37
38 # ifndef S_IWUSR
39 # define S_IWUSR _S_IWRITE
40 # endif
41
42 # ifdef __MINGW32__
43 # define _SH_DENYNO 0x40
44 # endif
45 # endif // _WIN32
46 #endif // FMT_USE_FCNTL
47
48 #ifdef _WIN32
49 # include <windows.h>
50 #endif
51
52 #ifdef fileno
53 # undef fileno
54 #endif
55
56 namespace {
57 #ifdef _WIN32
58 // Return type of read and write functions.
59 using RWResult = int;
60
61 // On Windows the count argument to read and write is unsigned, so convert
62 // it from size_t preventing integer overflow.
convert_rwcount(std::size_t count)63 inline unsigned convert_rwcount(std::size_t count) {
64 return count <= UINT_MAX ? static_cast<unsigned>(count) : UINT_MAX;
65 }
66 #elif FMT_USE_FCNTL
67 // Return type of read and write functions.
68 using RWResult = ssize_t;
69
70 inline std::size_t convert_rwcount(std::size_t count) { return count; }
71 #endif
72 } // namespace
73
74 FMT_BEGIN_NAMESPACE
75
76 #ifdef _WIN32
utf16_to_utf8(wstring_view s)77 detail::utf16_to_utf8::utf16_to_utf8(wstring_view s) {
78 if (int error_code = convert(s)) {
79 FMT_THROW(windows_error(error_code,
80 "cannot convert string from UTF-16 to UTF-8"));
81 }
82 }
83
convert(wstring_view s)84 int detail::utf16_to_utf8::convert(wstring_view s) {
85 if (s.size() > INT_MAX) return ERROR_INVALID_PARAMETER;
86 int s_size = static_cast<int>(s.size());
87 if (s_size == 0) {
88 // WideCharToMultiByte does not support zero length, handle separately.
89 buffer_.resize(1);
90 buffer_[0] = 0;
91 return 0;
92 }
93
94 int length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, nullptr, 0,
95 nullptr, nullptr);
96 if (length == 0) return GetLastError();
97 buffer_.resize(length + 1);
98 length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, &buffer_[0],
99 length, nullptr, nullptr);
100 if (length == 0) return GetLastError();
101 buffer_[length] = 0;
102 return 0;
103 }
104
init(int err_code,string_view format_str,format_args args)105 void windows_error::init(int err_code, string_view format_str,
106 format_args args) {
107 error_code_ = err_code;
108 memory_buffer buffer;
109 detail::format_windows_error(buffer, err_code, vformat(format_str, args));
110 std::runtime_error& base = *this;
111 base = std::runtime_error(to_string(buffer));
112 }
113
format_windows_error(detail::buffer<char> & out,int error_code,string_view message)114 void detail::format_windows_error(detail::buffer<char>& out, int error_code,
115 string_view message) FMT_NOEXCEPT {
116 FMT_TRY {
117 wmemory_buffer buf;
118 buf.resize(inline_buffer_size);
119 for (;;) {
120 wchar_t* system_message = &buf[0];
121 int result = FormatMessageW(
122 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
123 error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), system_message,
124 static_cast<uint32_t>(buf.size()), nullptr);
125 if (result != 0) {
126 utf16_to_utf8 utf8_message;
127 if (utf8_message.convert(system_message) == ERROR_SUCCESS) {
128 format_to(buffer_appender<char>(out), "{}: {}", message,
129 utf8_message);
130 return;
131 }
132 break;
133 }
134 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
135 break; // Can't get error message, report error code instead.
136 buf.resize(buf.size() * 2);
137 }
138 }
139 FMT_CATCH(...) {}
140 format_error_code(out, error_code, message);
141 }
142
report_windows_error(int error_code,fmt::string_view message)143 void report_windows_error(int error_code,
144 fmt::string_view message) FMT_NOEXCEPT {
145 report_error(detail::format_windows_error, error_code, message);
146 }
147 #endif // _WIN32
148
~buffered_file()149 buffered_file::~buffered_file() FMT_NOEXCEPT {
150 if (file_ && FMT_SYSTEM(fclose(file_)) != 0)
151 report_system_error(errno, "cannot close file");
152 }
153
buffered_file(cstring_view filename,cstring_view mode)154 buffered_file::buffered_file(cstring_view filename, cstring_view mode) {
155 FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())),
156 nullptr);
157 if (!file_)
158 FMT_THROW(system_error(errno, "cannot open file {}", filename.c_str()));
159 }
160
close()161 void buffered_file::close() {
162 if (!file_) return;
163 int result = FMT_SYSTEM(fclose(file_));
164 file_ = nullptr;
165 if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
166 }
167
168 // A macro used to prevent expansion of fileno on broken versions of MinGW.
169 #define FMT_ARGS
170
fileno() const171 int buffered_file::fileno() const {
172 int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_));
173 if (fd == -1) FMT_THROW(system_error(errno, "cannot get file descriptor"));
174 return fd;
175 }
176
177 #if FMT_USE_FCNTL
file(cstring_view path,int oflag)178 file::file(cstring_view path, int oflag) {
179 int mode = S_IRUSR | S_IWUSR;
180 # if defined(_WIN32) && !defined(__MINGW32__)
181 fd_ = -1;
182 FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode));
183 # else
184 FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode)));
185 # endif
186 if (fd_ == -1)
187 FMT_THROW(system_error(errno, "cannot open file {}", path.c_str()));
188 }
189
~file()190 file::~file() FMT_NOEXCEPT {
191 // Don't retry close in case of EINTR!
192 // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
193 if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0)
194 report_system_error(errno, "cannot close file");
195 }
196
close()197 void file::close() {
198 if (fd_ == -1) return;
199 // Don't retry close in case of EINTR!
200 // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
201 int result = FMT_POSIX_CALL(close(fd_));
202 fd_ = -1;
203 if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
204 }
205
size() const206 long long file::size() const {
207 # ifdef _WIN32
208 // Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT
209 // is less than 0x0500 as is the case with some default MinGW builds.
210 // Both functions support large file sizes.
211 DWORD size_upper = 0;
212 HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_));
213 DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper));
214 if (size_lower == INVALID_FILE_SIZE) {
215 DWORD error = GetLastError();
216 if (error != NO_ERROR)
217 FMT_THROW(windows_error(GetLastError(), "cannot get file size"));
218 }
219 unsigned long long long_size = size_upper;
220 return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower;
221 # else
222 using Stat = struct stat;
223 Stat file_stat = Stat();
224 if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1)
225 FMT_THROW(system_error(errno, "cannot get file attributes"));
226 static_assert(sizeof(long long) >= sizeof(file_stat.st_size),
227 "return type of file::size is not large enough");
228 return file_stat.st_size;
229 # endif
230 }
231
read(void * buffer,std::size_t count)232 std::size_t file::read(void* buffer, std::size_t count) {
233 RWResult result = 0;
234 FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count))));
235 if (result < 0) FMT_THROW(system_error(errno, "cannot read from file"));
236 return detail::to_unsigned(result);
237 }
238
write(const void * buffer,std::size_t count)239 std::size_t file::write(const void* buffer, std::size_t count) {
240 RWResult result = 0;
241 FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count))));
242 if (result < 0) FMT_THROW(system_error(errno, "cannot write to file"));
243 return detail::to_unsigned(result);
244 }
245
dup(int fd)246 file file::dup(int fd) {
247 // Don't retry as dup doesn't return EINTR.
248 // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html
249 int new_fd = FMT_POSIX_CALL(dup(fd));
250 if (new_fd == -1)
251 FMT_THROW(system_error(errno, "cannot duplicate file descriptor {}", fd));
252 return file(new_fd);
253 }
254
dup2(int fd)255 void file::dup2(int fd) {
256 int result = 0;
257 FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
258 if (result == -1) {
259 FMT_THROW(system_error(errno, "cannot duplicate file descriptor {} to {}",
260 fd_, fd));
261 }
262 }
263
dup2(int fd,error_code & ec)264 void file::dup2(int fd, error_code& ec) FMT_NOEXCEPT {
265 int result = 0;
266 FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
267 if (result == -1) ec = error_code(errno);
268 }
269
pipe(file & read_end,file & write_end)270 void file::pipe(file& read_end, file& write_end) {
271 // Close the descriptors first to make sure that assignments don't throw
272 // and there are no leaks.
273 read_end.close();
274 write_end.close();
275 int fds[2] = {};
276 # ifdef _WIN32
277 // Make the default pipe capacity same as on Linux 2.6.11+.
278 enum { DEFAULT_CAPACITY = 65536 };
279 int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY));
280 # else
281 // Don't retry as the pipe function doesn't return EINTR.
282 // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html
283 int result = FMT_POSIX_CALL(pipe(fds));
284 # endif
285 if (result != 0) FMT_THROW(system_error(errno, "cannot create pipe"));
286 // The following assignments don't throw because read_fd and write_fd
287 // are closed.
288 read_end = file(fds[0]);
289 write_end = file(fds[1]);
290 }
291
fdopen(const char * mode)292 buffered_file file::fdopen(const char* mode) {
293 // Don't retry as fdopen doesn't return EINTR.
294 # if defined(__MINGW32__) && defined(_POSIX_)
295 FILE* f = ::fdopen(fd_, mode);
296 # else
297 FILE* f = FMT_POSIX_CALL(fdopen(fd_, mode));
298 # endif
299 if (!f)
300 FMT_THROW(
301 system_error(errno, "cannot associate stream with file descriptor"));
302 buffered_file bf(f);
303 fd_ = -1;
304 return bf;
305 }
306
getpagesize()307 long getpagesize() {
308 # ifdef _WIN32
309 SYSTEM_INFO si;
310 GetSystemInfo(&si);
311 return si.dwPageSize;
312 # else
313 long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE));
314 if (size < 0) FMT_THROW(system_error(errno, "cannot get memory page size"));
315 return size;
316 # endif
317 }
318
grow(size_t)319 FMT_API void ostream::grow(size_t) {
320 if (this->size() == this->capacity()) flush();
321 }
322 #endif // FMT_USE_FCNTL
323 FMT_END_NAMESPACE
324