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 #    define O_CREAT _O_CREAT
30 #    define O_TRUNC _O_TRUNC
31 
32 #    ifndef S_IRUSR
33 #      define S_IRUSR _S_IREAD
34 #    endif
35 
36 #    ifndef S_IWUSR
37 #      define S_IWUSR _S_IWRITE
38 #    endif
39 
40 #    ifdef __MINGW32__
41 #      define _SH_DENYNO 0x40
42 #    endif
43 #  endif  // _WIN32
44 #endif    // FMT_USE_FCNTL
45 
46 #ifdef _WIN32
47 #  include <windows.h>
48 #endif
49 
50 #ifdef fileno
51 #  undef fileno
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.
convert_rwcount(std::size_t count)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
utf16_to_utf8(basic_string_view<wchar_t> s)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 
convert(basic_string_view<wchar_t> s)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 
is_whitespace(wchar_t c)112   static bool is_whitespace(wchar_t c) FMT_NOEXCEPT {
113     return c == L' ' || c == L'\n' || c == L'\r' || c == L'\t' || c == L'\0';
114   }
115 
116  public:
system_message(unsigned long error_code)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   }
~system_message()130   ~system_message() { LocalFree(message_); }
operator bool() const131   explicit operator bool() const FMT_NOEXCEPT { return result_ != 0; }
operator basic_string_view<wchar_t>() const132   operator basic_string_view<wchar_t>() const FMT_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:
name() const139   const char* name() const FMT_NOEXCEPT override { return "system"; }
message(int error_code) const140   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 
system_category()154 FMT_API const std::error_category& system_category() FMT_NOEXCEPT {
155   static const detail::utf8_system_category category;
156   return category;
157 }
158 
vwindows_error(int err_code,string_view format_str,format_args args)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 
format_windows_error(detail::buffer<char> & out,int error_code,const char * message)165 void detail::format_windows_error(detail::buffer<char>& out, int error_code,
166                                   const char* message) FMT_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         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 
report_windows_error(int error_code,const char * message)181 void report_windows_error(int error_code, const char* message) FMT_NOEXCEPT {
182   report_error(detail::format_windows_error, error_code, message);
183 }
184 #endif  // _WIN32
185 
~buffered_file()186 buffered_file::~buffered_file() FMT_NOEXCEPT {
187   if (file_ && FMT_SYSTEM(fclose(file_)) != 0)
188     report_system_error(errno, "cannot close file");
189 }
190 
buffered_file(cstring_view filename,cstring_view mode)191 buffered_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 
close()198 void 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 
205 // A macro used to prevent expansion of fileno on broken versions of MinGW.
206 #define FMT_ARGS
207 
fileno() const208 int buffered_file::fileno() const {
209   int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_));
210   if (fd == -1) FMT_THROW(system_error(errno, "cannot get file descriptor"));
211   return fd;
212 }
213 
214 #if FMT_USE_FCNTL
file(cstring_view path,int oflag)215 file::file(cstring_view path, int oflag) {
216   int mode = S_IRUSR | S_IWUSR;
217 #  if defined(_WIN32) && !defined(__MINGW32__)
218   fd_ = -1;
219   FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode));
220 #  else
221   FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode)));
222 #  endif
223   if (fd_ == -1)
224     FMT_THROW(system_error(errno, "cannot open file {}", path.c_str()));
225 }
226 
~file()227 file::~file() FMT_NOEXCEPT {
228   // Don't retry close in case of EINTR!
229   // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
230   if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0)
231     report_system_error(errno, "cannot close file");
232 }
233 
close()234 void file::close() {
235   if (fd_ == -1) return;
236   // Don't retry close in case of EINTR!
237   // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
238   int result = FMT_POSIX_CALL(close(fd_));
239   fd_ = -1;
240   if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
241 }
242 
size() const243 long long file::size() const {
244 #  ifdef _WIN32
245   // Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT
246   // is less than 0x0500 as is the case with some default MinGW builds.
247   // Both functions support large file sizes.
248   DWORD size_upper = 0;
249   HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_));
250   DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper));
251   if (size_lower == INVALID_FILE_SIZE) {
252     DWORD error = GetLastError();
253     if (error != NO_ERROR)
254       FMT_THROW(windows_error(GetLastError(), "cannot get file size"));
255   }
256   unsigned long long long_size = size_upper;
257   return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower;
258 #  else
259   using Stat = struct stat;
260   Stat file_stat = Stat();
261   if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1)
262     FMT_THROW(system_error(errno, "cannot get file attributes"));
263   static_assert(sizeof(long long) >= sizeof(file_stat.st_size),
264                 "return type of file::size is not large enough");
265   return file_stat.st_size;
266 #  endif
267 }
268 
read(void * buffer,std::size_t count)269 std::size_t file::read(void* buffer, std::size_t count) {
270   rwresult result = 0;
271   FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count))));
272   if (result < 0) FMT_THROW(system_error(errno, "cannot read from file"));
273   return detail::to_unsigned(result);
274 }
275 
write(const void * buffer,std::size_t count)276 std::size_t file::write(const void* buffer, std::size_t count) {
277   rwresult result = 0;
278   FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count))));
279   if (result < 0) FMT_THROW(system_error(errno, "cannot write to file"));
280   return detail::to_unsigned(result);
281 }
282 
dup(int fd)283 file file::dup(int fd) {
284   // Don't retry as dup doesn't return EINTR.
285   // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html
286   int new_fd = FMT_POSIX_CALL(dup(fd));
287   if (new_fd == -1)
288     FMT_THROW(system_error(errno, "cannot duplicate file descriptor {}", fd));
289   return file(new_fd);
290 }
291 
dup2(int fd)292 void file::dup2(int fd) {
293   int result = 0;
294   FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
295   if (result == -1) {
296     FMT_THROW(system_error(errno, "cannot duplicate file descriptor {} to {}",
297                            fd_, fd));
298   }
299 }
300 
dup2(int fd,std::error_code & ec)301 void file::dup2(int fd, std::error_code& ec) FMT_NOEXCEPT {
302   int result = 0;
303   FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
304   if (result == -1) ec = std::error_code(errno, std::generic_category());
305 }
306 
pipe(file & read_end,file & write_end)307 void file::pipe(file& read_end, file& write_end) {
308   // Close the descriptors first to make sure that assignments don't throw
309   // and there are no leaks.
310   read_end.close();
311   write_end.close();
312   int fds[2] = {};
313 #  ifdef _WIN32
314   // Make the default pipe capacity same as on Linux 2.6.11+.
315   enum { DEFAULT_CAPACITY = 65536 };
316   int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY));
317 #  else
318   // Don't retry as the pipe function doesn't return EINTR.
319   // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html
320   int result = FMT_POSIX_CALL(pipe(fds));
321 #  endif
322   if (result != 0) FMT_THROW(system_error(errno, "cannot create pipe"));
323   // The following assignments don't throw because read_fd and write_fd
324   // are closed.
325   read_end = file(fds[0]);
326   write_end = file(fds[1]);
327 }
328 
fdopen(const char * mode)329 buffered_file file::fdopen(const char* mode) {
330 // Don't retry as fdopen doesn't return EINTR.
331 #  if defined(__MINGW32__) && defined(_POSIX_)
332   FILE* f = ::fdopen(fd_, mode);
333 #  else
334   FILE* f = FMT_POSIX_CALL(fdopen(fd_, mode));
335 #  endif
336   if (!f)
337     FMT_THROW(
338         system_error(errno, "cannot associate stream with file descriptor"));
339   buffered_file bf(f);
340   fd_ = -1;
341   return bf;
342 }
343 
getpagesize()344 long getpagesize() {
345 #  ifdef _WIN32
346   SYSTEM_INFO si;
347   GetSystemInfo(&si);
348   return si.dwPageSize;
349 #  else
350   long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE));
351   if (size < 0) FMT_THROW(system_error(errno, "cannot get memory page size"));
352   return size;
353 #  endif
354 }
355 
grow(size_t)356 FMT_API void ostream::grow(size_t) {
357   if (this->size() == this->capacity()) flush();
358 }
359 #endif  // FMT_USE_FCNTL
360 FMT_END_NAMESPACE
361