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 #else
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 internal::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 internal::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   internal::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(internal::buffer<char> & out,int error_code,string_view message)113 void internal::format_windows_error(internal::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           internal::writer w(out);
128           w.write(message);
129           w.write(": ");
130           w.write(utf8_message);
131           return;
132         }
133         break;
134       }
135       if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
136         break;  // Can't get error message, report error code instead.
137       buf.resize(buf.size() * 2);
138     }
139   }
140   FMT_CATCH(...) {}
141   format_error_code(out, error_code, message);
142 }
143 
report_windows_error(int error_code,fmt::string_view message)144 void report_windows_error(int error_code,
145                           fmt::string_view message) FMT_NOEXCEPT {
146   report_error(internal::format_windows_error, error_code, message);
147 }
148 #endif  // _WIN32
149 
~buffered_file()150 buffered_file::~buffered_file() FMT_NOEXCEPT {
151   if (file_ && FMT_SYSTEM(fclose(file_)) != 0)
152     report_system_error(errno, "cannot close file");
153 }
154 
buffered_file(cstring_view filename,cstring_view mode)155 buffered_file::buffered_file(cstring_view filename, cstring_view mode) {
156   FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())),
157                 nullptr);
158   if (!file_)
159     FMT_THROW(system_error(errno, "cannot open file {}", filename.c_str()));
160 }
161 
close()162 void buffered_file::close() {
163   if (!file_) return;
164   int result = FMT_SYSTEM(fclose(file_));
165   file_ = nullptr;
166   if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
167 }
168 
169 // A macro used to prevent expansion of fileno on broken versions of MinGW.
170 #define FMT_ARGS
171 
fileno() const172 int buffered_file::fileno() const {
173   int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_));
174   if (fd == -1) FMT_THROW(system_error(errno, "cannot get file descriptor"));
175   return fd;
176 }
177 
178 #if FMT_USE_FCNTL
file(cstring_view path,int oflag)179 file::file(cstring_view path, int oflag) {
180   int mode = S_IRUSR | S_IWUSR;
181 #  if defined(_WIN32) && !defined(__MINGW32__)
182   fd_ = -1;
183   FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode));
184 #  else
185   FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode)));
186 #  endif
187   if (fd_ == -1)
188     FMT_THROW(system_error(errno, "cannot open file {}", path.c_str()));
189 }
190 
~file()191 file::~file() FMT_NOEXCEPT {
192   // Don't retry close in case of EINTR!
193   // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
194   if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0)
195     report_system_error(errno, "cannot close file");
196 }
197 
close()198 void file::close() {
199   if (fd_ == -1) return;
200   // Don't retry close in case of EINTR!
201   // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
202   int result = FMT_POSIX_CALL(close(fd_));
203   fd_ = -1;
204   if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
205 }
206 
size() const207 long long file::size() const {
208 #  ifdef _WIN32
209   // Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT
210   // is less than 0x0500 as is the case with some default MinGW builds.
211   // Both functions support large file sizes.
212   DWORD size_upper = 0;
213   HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_));
214   DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper));
215   if (size_lower == INVALID_FILE_SIZE) {
216     DWORD error = GetLastError();
217     if (error != NO_ERROR)
218       FMT_THROW(windows_error(GetLastError(), "cannot get file size"));
219   }
220   unsigned long long long_size = size_upper;
221   return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower;
222 #  else
223   using Stat = struct stat;
224   Stat file_stat = Stat();
225   if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1)
226     FMT_THROW(system_error(errno, "cannot get file attributes"));
227   static_assert(sizeof(long long) >= sizeof(file_stat.st_size),
228                 "return type of file::size is not large enough");
229   return file_stat.st_size;
230 #  endif
231 }
232 
read(void * buffer,std::size_t count)233 std::size_t file::read(void* buffer, std::size_t count) {
234   RWResult result = 0;
235   FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count))));
236   if (result < 0) FMT_THROW(system_error(errno, "cannot read from file"));
237   return internal::to_unsigned(result);
238 }
239 
write(const void * buffer,std::size_t count)240 std::size_t file::write(const void* buffer, std::size_t count) {
241   RWResult result = 0;
242   FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count))));
243   if (result < 0) FMT_THROW(system_error(errno, "cannot write to file"));
244   return internal::to_unsigned(result);
245 }
246 
dup(int fd)247 file file::dup(int fd) {
248   // Don't retry as dup doesn't return EINTR.
249   // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html
250   int new_fd = FMT_POSIX_CALL(dup(fd));
251   if (new_fd == -1)
252     FMT_THROW(system_error(errno, "cannot duplicate file descriptor {}", fd));
253   return file(new_fd);
254 }
255 
dup2(int fd)256 void file::dup2(int fd) {
257   int result = 0;
258   FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
259   if (result == -1) {
260     FMT_THROW(system_error(errno, "cannot duplicate file descriptor {} to {}",
261                            fd_, fd));
262   }
263 }
264 
dup2(int fd,error_code & ec)265 void file::dup2(int fd, error_code& ec) FMT_NOEXCEPT {
266   int result = 0;
267   FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
268   if (result == -1) ec = error_code(errno);
269 }
270 
pipe(file & read_end,file & write_end)271 void file::pipe(file& read_end, file& write_end) {
272   // Close the descriptors first to make sure that assignments don't throw
273   // and there are no leaks.
274   read_end.close();
275   write_end.close();
276   int fds[2] = {};
277 #  ifdef _WIN32
278   // Make the default pipe capacity same as on Linux 2.6.11+.
279   enum { DEFAULT_CAPACITY = 65536 };
280   int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY));
281 #  else
282   // Don't retry as the pipe function doesn't return EINTR.
283   // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html
284   int result = FMT_POSIX_CALL(pipe(fds));
285 #  endif
286   if (result != 0) FMT_THROW(system_error(errno, "cannot create pipe"));
287   // The following assignments don't throw because read_fd and write_fd
288   // are closed.
289   read_end = file(fds[0]);
290   write_end = file(fds[1]);
291 }
292 
fdopen(const char * mode)293 buffered_file file::fdopen(const char* mode) {
294   // Don't retry as fdopen doesn't return EINTR.
295   FILE* f = FMT_POSIX_CALL(fdopen(fd_, mode));
296   if (!f)
297     FMT_THROW(
298         system_error(errno, "cannot associate stream with file descriptor"));
299   buffered_file bf(f);
300   fd_ = -1;
301   return bf;
302 }
303 
getpagesize()304 long getpagesize() {
305 #  ifdef _WIN32
306   SYSTEM_INFO si;
307   GetSystemInfo(&si);
308   return si.dwPageSize;
309 #  else
310   long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE));
311   if (size < 0) FMT_THROW(system_error(errno, "cannot get memory page size"));
312   return size;
313 #  endif
314 }
315 #endif  // FMT_USE_FCNTL
316 FMT_END_NAMESPACE
317