You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

os.cc 11KB

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