1// Formatting library for C++ - optional OS-specific functionality
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/os.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
29# ifndef S_IRUSR
30# define S_IRUSR _S_IREAD
31# endif
32# ifndef S_IWUSR
33# define S_IWUSR _S_IWRITE
34# endif
35# ifndef S_IRGRP
36# define S_IRGRP 0
37# endif
38# ifndef S_IWGRP
39# define S_IWGRP 0
40# endif
41# ifndef S_IROTH
42# define S_IROTH 0
43# endif
44# ifndef S_IWOTH
45# define S_IWOTH 0
46# endif
47# endif // _WIN32
48#endif // FMT_USE_FCNTL
49
50#ifdef _WIN32
51# include <windows.h>
52#endif
53
54namespace {
55#ifdef _WIN32
56// Return type of read and write functions.
57using rwresult = int;
58
59// On Windows the count argument to read and write is unsigned, so convert
60// it from size_t preventing integer overflow.
61inline unsigned convert_rwcount(std::size_t count) {
62 return count <= UINT_MAX ? static_cast<unsigned>(count) : UINT_MAX;
63}
64#elif FMT_USE_FCNTL
65// Return type of read and write functions.
66using rwresult = ssize_t;
67
68inline std::size_t convert_rwcount(std::size_t count) { return count; }
69#endif
70} // namespace
71
72FMT_BEGIN_NAMESPACE
73
74#ifdef _WIN32
75detail::utf16_to_utf8::utf16_to_utf8(basic_string_view<wchar_t> s) {
76 if (int error_code = convert(s)) {
77 FMT_THROW(windows_error(error_code,
78 "cannot convert string from UTF-16 to UTF-8"));
79 }
80}
81
82int detail::utf16_to_utf8::convert(basic_string_view<wchar_t> s) {
83 if (s.size() > INT_MAX) return ERROR_INVALID_PARAMETER;
84 int s_size = static_cast<int>(s.size());
85 if (s_size == 0) {
86 // WideCharToMultiByte does not support zero length, handle separately.
87 buffer_.resize(1);
88 buffer_[0] = 0;
89 return 0;
90 }
91
92 int length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, nullptr, 0,
93 nullptr, nullptr);
94 if (length == 0) return GetLastError();
95 buffer_.resize(length + 1);
96 length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, &buffer_[0],
97 length, nullptr, nullptr);
98 if (length == 0) return GetLastError();
99 buffer_[length] = 0;
100 return 0;
101}
102
103namespace detail {
104
105class system_message {
106 system_message(const system_message&) = delete;
107 void operator=(const system_message&) = delete;
108
109 unsigned long result_;
110 wchar_t* message_;
111
112 static bool is_whitespace(wchar_t c) noexcept {
113 return c == L' ' || c == L'\n' || c == L'\r' || c == L'\t' || c == L'\0';
114 }
115
116 public:
117 explicit system_message(unsigned long error_code)
118 : result_(0), message_(nullptr) {
119 result_ = FormatMessageW(
120 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
121 FORMAT_MESSAGE_IGNORE_INSERTS,
122 nullptr, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
123 reinterpret_cast<wchar_t*>(&message_), 0, nullptr);
124 if (result_ != 0) {
125 while (result_ != 0 && is_whitespace(message_[result_ - 1])) {
126 --result_;
127 }
128 }
129 }
130 ~system_message() { LocalFree(message_); }
131 explicit operator bool() const noexcept { return result_ != 0; }
132 operator basic_string_view<wchar_t>() const noexcept {
133 return basic_string_view<wchar_t>(message_, result_);
134 }
135};
136
137class utf8_system_category final : public std::error_category {
138 public:
139 const char* name() const noexcept override { return "system"; }
140 std::string message(int error_code) const override {
141 system_message msg(error_code);
142 if (msg) {
143 utf16_to_utf8 utf8_message;
144 if (utf8_message.convert(msg) == ERROR_SUCCESS) {
145 return utf8_message.str();
146 }
147 }
148 return "unknown error";
149 }
150};
151
152} // namespace detail
153
154FMT_API const std::error_category& system_category() noexcept {
155 static const detail::utf8_system_category category;
156 return category;
157}
158
159std::system_error vwindows_error(int err_code, string_view format_str,
160 format_args args) {
161 auto ec = std::error_code(err_code, system_category());
162 return std::system_error(ec, vformat(format_str, args));
163}
164
165void detail::format_windows_error(detail::buffer<char>& out, int error_code,
166 const char* message) noexcept {
167 FMT_TRY {
168 system_message msg(error_code);
169 if (msg) {
170 utf16_to_utf8 utf8_message;
171 if (utf8_message.convert(msg) == ERROR_SUCCESS) {
172 fmt::format_to(buffer_appender<char>(out), "{}: {}", message, utf8_message);
173 return;
174 }
175 }
176 }
177 FMT_CATCH(...) {}
178 format_error_code(out, error_code, message);
179}
180
181void report_windows_error(int error_code, const char* message) noexcept {
182 report_error(detail::format_windows_error, error_code, message);
183}
184#endif // _WIN32
185
186buffered_file::~buffered_file() noexcept {
187 if (file_ && FMT_SYSTEM(fclose(file_)) != 0)
188 report_system_error(errno, "cannot close file");
189}
190
191buffered_file::buffered_file(cstring_view filename, cstring_view mode) {
192 FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())),
193 nullptr);
194 if (!file_)
195 FMT_THROW(system_error(errno, "cannot open file {}", filename.c_str()));
196}
197
198void buffered_file::close() {
199 if (!file_) return;
200 int result = FMT_SYSTEM(fclose(file_));
201 file_ = nullptr;
202 if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
203}
204
205int buffered_file::descriptor() const {
206 int fd = FMT_POSIX_CALL(fileno(file_));
207 if (fd == -1) FMT_THROW(system_error(errno, "cannot get file descriptor"));
208 return fd;
209}
210
211#if FMT_USE_FCNTL
212file::file(cstring_view path, int oflag) {
213# ifdef _WIN32
214 using mode_t = int;
215# endif
216 constexpr mode_t mode =
217 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
218# if defined(_WIN32) && !defined(__MINGW32__)
219 fd_ = -1;
220 FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode));
221# else
222 FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode)));
223# endif
224 if (fd_ == -1)
225 FMT_THROW(system_error(errno, "cannot open file {}", path.c_str()));
226}
227
228file::~file() noexcept {
229 // Don't retry close in case of EINTR!
230 // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
231 if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0)
232 report_system_error(errno, "cannot close file");
233}
234
235void file::close() {
236 if (fd_ == -1) return;
237 // Don't retry close in case of EINTR!
238 // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
239 int result = FMT_POSIX_CALL(close(fd_));
240 fd_ = -1;
241 if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
242}
243
244long long file::size() const {
245# ifdef _WIN32
246 // Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT
247 // is less than 0x0500 as is the case with some default MinGW builds.
248 // Both functions support large file sizes.
249 DWORD size_upper = 0;
250 HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_));
251 DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper));
252 if (size_lower == INVALID_FILE_SIZE) {
253 DWORD error = GetLastError();
254 if (error != NO_ERROR)
255 FMT_THROW(windows_error(GetLastError(), "cannot get file size"));
256 }
257 unsigned long long long_size = size_upper;
258 return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower;
259# else
260 using Stat = struct stat;
261 Stat file_stat = Stat();
262 if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1)
263 FMT_THROW(system_error(errno, "cannot get file attributes"));
264 static_assert(sizeof(long long) >= sizeof(file_stat.st_size),
265 "return type of file::size is not large enough");
266 return file_stat.st_size;
267# endif
268}
269
270std::size_t file::read(void* buffer, std::size_t count) {
271 rwresult result = 0;
272 FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count))));
273 if (result < 0) FMT_THROW(system_error(errno, "cannot read from file"));
274 return detail::to_unsigned(result);
275}
276
277std::size_t file::write(const void* buffer, std::size_t count) {
278 rwresult result = 0;
279 FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count))));
280 if (result < 0) FMT_THROW(system_error(errno, "cannot write to file"));
281 return detail::to_unsigned(result);
282}
283
284file file::dup(int fd) {
285 // Don't retry as dup doesn't return EINTR.
286 // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html
287 int new_fd = FMT_POSIX_CALL(dup(fd));
288 if (new_fd == -1)
289 FMT_THROW(system_error(errno, "cannot duplicate file descriptor {}", fd));
290 return file(new_fd);
291}
292
293void file::dup2(int fd) {
294 int result = 0;
295 FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
296 if (result == -1) {
297 FMT_THROW(system_error(errno, "cannot duplicate file descriptor {} to {}",
298 fd_, fd));
299 }
300}
301
302void file::dup2(int fd, std::error_code& ec) noexcept {
303 int result = 0;
304 FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
305 if (result == -1) ec = std::error_code(errno, std::generic_category());
306}
307
308void file::pipe(file& read_end, file& write_end) {
309 // Close the descriptors first to make sure that assignments don't throw
310 // and there are no leaks.
311 read_end.close();
312 write_end.close();
313 int fds[2] = {};
314# ifdef _WIN32
315 // Make the default pipe capacity same as on Linux 2.6.11+.
316 enum { DEFAULT_CAPACITY = 65536 };
317 int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY));
318# else
319 // Don't retry as the pipe function doesn't return EINTR.
320 // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html
321 int result = FMT_POSIX_CALL(pipe(fds));
322# endif
323 if (result != 0) FMT_THROW(system_error(errno, "cannot create pipe"));
324 // The following assignments don't throw because read_fd and write_fd
325 // are closed.
326 read_end = file(fds[0]);
327 write_end = file(fds[1]);
328}
329
330buffered_file file::fdopen(const char* mode) {
331// Don't retry as fdopen doesn't return EINTR.
332# if defined(__MINGW32__) && defined(_POSIX_)
333 FILE* f = ::fdopen(fd_, mode);
334# else
335 FILE* f = FMT_POSIX_CALL(fdopen(fd_, mode));
336# endif
337 if (!f)
338 FMT_THROW(
339 system_error(errno, "cannot associate stream with file descriptor"));
340 buffered_file bf(f);
341 fd_ = -1;
342 return bf;
343}
344
345long getpagesize() {
346# ifdef _WIN32
347 SYSTEM_INFO si;
348 GetSystemInfo(&si);
349 return si.dwPageSize;
350# else
351 long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE));
352 if (size < 0) FMT_THROW(system_error(errno, "cannot get memory page size"));
353 return size;
354# endif
355}
356
357FMT_API void ostream::grow(size_t) {
358 if (this->size() == this->capacity()) flush();
359}
360#endif // FMT_USE_FCNTL
361FMT_END_NAMESPACE
362