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 | |
54 | namespace { |
55 | #ifdef _WIN32 |
56 | // Return type of read and write functions. |
57 | using 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. |
61 | inline 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. |
66 | using rwresult = ssize_t; |
67 | |
68 | inline std::size_t convert_rwcount(std::size_t count) { return count; } |
69 | #endif |
70 | } // namespace |
71 | |
72 | FMT_BEGIN_NAMESPACE |
73 | |
74 | #ifdef _WIN32 |
75 | detail::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 | |
82 | int 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 | |
103 | namespace detail { |
104 | |
105 | class 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 | |
137 | class 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 | |
154 | FMT_API const std::error_category& system_category() noexcept { |
155 | static const detail::utf8_system_category category; |
156 | return category; |
157 | } |
158 | |
159 | std::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 | |
165 | void 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, |
173 | utf8_message); |
174 | return; |
175 | } |
176 | } |
177 | } |
178 | FMT_CATCH(...) {} |
179 | format_error_code(out, error_code, message); |
180 | } |
181 | |
182 | void report_windows_error(int error_code, const char* message) noexcept { |
183 | report_error(detail::format_windows_error, error_code, message); |
184 | } |
185 | #endif // _WIN32 |
186 | |
187 | buffered_file::~buffered_file() noexcept { |
188 | if (file_ && FMT_SYSTEM(fclose(file_)) != 0) |
189 | report_system_error(errno, "cannot close file" ); |
190 | } |
191 | |
192 | buffered_file::buffered_file(cstring_view filename, cstring_view mode) { |
193 | FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), |
194 | nullptr); |
195 | if (!file_) |
196 | FMT_THROW(system_error(errno, FMT_STRING("cannot open file {}" ), |
197 | filename.c_str())); |
198 | } |
199 | |
200 | void buffered_file::close() { |
201 | if (!file_) return; |
202 | int result = FMT_SYSTEM(fclose(file_)); |
203 | file_ = nullptr; |
204 | if (result != 0) |
205 | FMT_THROW(system_error(errno, FMT_STRING("cannot close file" ))); |
206 | } |
207 | |
208 | int buffered_file::descriptor() const { |
209 | int fd = FMT_POSIX_CALL(fileno(file_)); |
210 | if (fd == -1) |
211 | FMT_THROW(system_error(errno, FMT_STRING("cannot get file descriptor" ))); |
212 | return fd; |
213 | } |
214 | |
215 | #if FMT_USE_FCNTL |
216 | file::file(cstring_view path, int oflag) { |
217 | # ifdef _WIN32 |
218 | using mode_t = int; |
219 | # endif |
220 | constexpr mode_t mode = |
221 | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; |
222 | # if defined(_WIN32) && !defined(__MINGW32__) |
223 | fd_ = -1; |
224 | FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode)); |
225 | # else |
226 | FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode))); |
227 | # endif |
228 | if (fd_ == -1) |
229 | FMT_THROW( |
230 | system_error(errno, FMT_STRING("cannot open file {}" ), path.c_str())); |
231 | } |
232 | |
233 | file::~file() noexcept { |
234 | // Don't retry close in case of EINTR! |
235 | // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html |
236 | if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0) |
237 | report_system_error(errno, "cannot close file" ); |
238 | } |
239 | |
240 | void file::close() { |
241 | if (fd_ == -1) return; |
242 | // Don't retry close in case of EINTR! |
243 | // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html |
244 | int result = FMT_POSIX_CALL(close(fd_)); |
245 | fd_ = -1; |
246 | if (result != 0) |
247 | FMT_THROW(system_error(errno, FMT_STRING("cannot close file" ))); |
248 | } |
249 | |
250 | long long file::size() const { |
251 | # ifdef _WIN32 |
252 | // Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT |
253 | // is less than 0x0500 as is the case with some default MinGW builds. |
254 | // Both functions support large file sizes. |
255 | DWORD size_upper = 0; |
256 | HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_)); |
257 | DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper)); |
258 | if (size_lower == INVALID_FILE_SIZE) { |
259 | DWORD error = GetLastError(); |
260 | if (error != NO_ERROR) |
261 | FMT_THROW(windows_error(GetLastError(), "cannot get file size" )); |
262 | } |
263 | unsigned long long long_size = size_upper; |
264 | return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower; |
265 | # else |
266 | using Stat = struct stat; |
267 | Stat file_stat = Stat(); |
268 | if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1) |
269 | FMT_THROW(system_error(errno, FMT_STRING("cannot get file attributes" ))); |
270 | static_assert(sizeof(long long) >= sizeof(file_stat.st_size), |
271 | "return type of file::size is not large enough" ); |
272 | return file_stat.st_size; |
273 | # endif |
274 | } |
275 | |
276 | std::size_t file::read(void* buffer, std::size_t count) { |
277 | rwresult result = 0; |
278 | FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count)))); |
279 | if (result < 0) |
280 | FMT_THROW(system_error(errno, FMT_STRING("cannot read from file" ))); |
281 | return detail::to_unsigned(result); |
282 | } |
283 | |
284 | std::size_t file::write(const void* buffer, std::size_t count) { |
285 | rwresult result = 0; |
286 | FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count)))); |
287 | if (result < 0) |
288 | FMT_THROW(system_error(errno, FMT_STRING("cannot write to file" ))); |
289 | return detail::to_unsigned(result); |
290 | } |
291 | |
292 | file file::dup(int fd) { |
293 | // Don't retry as dup doesn't return EINTR. |
294 | // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html |
295 | int new_fd = FMT_POSIX_CALL(dup(fd)); |
296 | if (new_fd == -1) |
297 | FMT_THROW(system_error( |
298 | errno, FMT_STRING("cannot duplicate file descriptor {}" ), fd)); |
299 | return file(new_fd); |
300 | } |
301 | |
302 | void file::dup2(int fd) { |
303 | int result = 0; |
304 | FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); |
305 | if (result == -1) { |
306 | FMT_THROW(system_error( |
307 | errno, FMT_STRING("cannot duplicate file descriptor {} to {}" ), fd_, |
308 | fd)); |
309 | } |
310 | } |
311 | |
312 | void file::dup2(int fd, std::error_code& ec) noexcept { |
313 | int result = 0; |
314 | FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); |
315 | if (result == -1) ec = std::error_code(errno, std::generic_category()); |
316 | } |
317 | |
318 | void file::pipe(file& read_end, file& write_end) { |
319 | // Close the descriptors first to make sure that assignments don't throw |
320 | // and there are no leaks. |
321 | read_end.close(); |
322 | write_end.close(); |
323 | int fds[2] = {}; |
324 | # ifdef _WIN32 |
325 | // Make the default pipe capacity same as on Linux 2.6.11+. |
326 | enum { DEFAULT_CAPACITY = 65536 }; |
327 | int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY)); |
328 | # else |
329 | // Don't retry as the pipe function doesn't return EINTR. |
330 | // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html |
331 | int result = FMT_POSIX_CALL(pipe(fds)); |
332 | # endif |
333 | if (result != 0) |
334 | FMT_THROW(system_error(errno, FMT_STRING("cannot create pipe" ))); |
335 | // The following assignments don't throw because read_fd and write_fd |
336 | // are closed. |
337 | read_end = file(fds[0]); |
338 | write_end = file(fds[1]); |
339 | } |
340 | |
341 | buffered_file file::fdopen(const char* mode) { |
342 | // Don't retry as fdopen doesn't return EINTR. |
343 | # if defined(__MINGW32__) && defined(_POSIX_) |
344 | FILE* f = ::fdopen(fd_, mode); |
345 | # else |
346 | FILE* f = FMT_POSIX_CALL(fdopen(fd_, mode)); |
347 | # endif |
348 | if (!f) |
349 | FMT_THROW(system_error( |
350 | errno, FMT_STRING("cannot associate stream with file descriptor" ))); |
351 | buffered_file bf(f); |
352 | fd_ = -1; |
353 | return bf; |
354 | } |
355 | |
356 | long getpagesize() { |
357 | # ifdef _WIN32 |
358 | SYSTEM_INFO si; |
359 | GetSystemInfo(&si); |
360 | return si.dwPageSize; |
361 | # else |
362 | long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE)); |
363 | if (size < 0) |
364 | FMT_THROW(system_error(errno, FMT_STRING("cannot get memory page size" ))); |
365 | return size; |
366 | # endif |
367 | } |
368 | |
369 | FMT_API void ostream::grow(size_t) { |
370 | if (this->size() == this->capacity()) flush(); |
371 | } |
372 | #endif // FMT_USE_FCNTL |
373 | FMT_END_NAMESPACE |
374 | |