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