os-inl.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. // Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
  2. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
  3. #pragma once
  4. #ifndef SPDLOG_HEADER_ONLY
  5. # include <spdlog/details/os.h>
  6. #endif
  7. #include <spdlog/common.h>
  8. #include <algorithm>
  9. #include <chrono>
  10. #include <cstdio>
  11. #include <cstdlib>
  12. #include <cstring>
  13. #include <ctime>
  14. #include <string>
  15. #include <thread>
  16. #include <array>
  17. #include <sys/stat.h>
  18. #include <sys/types.h>
  19. #ifdef _WIN32
  20. # include <io.h> // _get_osfhandle and _isatty support
  21. # include <process.h> // _get_pid support
  22. # include <spdlog/details/windows_include.h>
  23. # ifdef __MINGW32__
  24. # include <share.h>
  25. # endif
  26. # if defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)
  27. # include <limits>
  28. # endif
  29. # include <direct.h> // for _mkdir/_wmkdir
  30. #else // unix
  31. # include <fcntl.h>
  32. # include <unistd.h>
  33. # ifdef __linux__
  34. # include <sys/syscall.h> //Use gettid() syscall under linux to get thread id
  35. # elif defined(_AIX)
  36. # include <pthread.h> // for pthread_getthrds_np
  37. # elif defined(__DragonFly__) || defined(__FreeBSD__)
  38. # include <pthread_np.h> // for pthread_getthreadid_np
  39. # elif defined(__NetBSD__)
  40. # include <lwp.h> // for _lwp_self
  41. # elif defined(__sun)
  42. # include <thread.h> // for thr_self
  43. # endif
  44. #endif // unix
  45. #ifndef __has_feature // Clang - feature checking macros.
  46. # define __has_feature(x) 0 // Compatibility with non-clang compilers.
  47. #endif
  48. namespace spdlog {
  49. namespace details {
  50. namespace os {
  51. SPDLOG_INLINE spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT
  52. {
  53. #if defined __linux__ && defined SPDLOG_CLOCK_COARSE
  54. timespec ts;
  55. ::clock_gettime(CLOCK_REALTIME_COARSE, &ts);
  56. return std::chrono::time_point<log_clock, typename log_clock::duration>(
  57. std::chrono::duration_cast<typename log_clock::duration>(std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec)));
  58. #else
  59. return log_clock::now();
  60. #endif
  61. }
  62. SPDLOG_INLINE std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
  63. {
  64. #ifdef _WIN32
  65. std::tm tm;
  66. ::localtime_s(&tm, &time_tt);
  67. #else
  68. std::tm tm;
  69. ::localtime_r(&time_tt, &tm);
  70. #endif
  71. return tm;
  72. }
  73. SPDLOG_INLINE std::tm localtime() SPDLOG_NOEXCEPT
  74. {
  75. std::time_t now_t = ::time(nullptr);
  76. return localtime(now_t);
  77. }
  78. SPDLOG_INLINE std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
  79. {
  80. #ifdef _WIN32
  81. std::tm tm;
  82. ::gmtime_s(&tm, &time_tt);
  83. #else
  84. std::tm tm;
  85. ::gmtime_r(&time_tt, &tm);
  86. #endif
  87. return tm;
  88. }
  89. SPDLOG_INLINE std::tm gmtime() SPDLOG_NOEXCEPT
  90. {
  91. std::time_t now_t = ::time(nullptr);
  92. return gmtime(now_t);
  93. }
  94. // fopen_s on non windows for writing
  95. SPDLOG_INLINE bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode)
  96. {
  97. #ifdef _WIN32
  98. # ifdef SPDLOG_WCHAR_FILENAMES
  99. *fp = ::_wfsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
  100. # else
  101. *fp = ::_fsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
  102. # endif
  103. # if defined(SPDLOG_PREVENT_CHILD_FD)
  104. if (*fp != nullptr)
  105. {
  106. auto file_handle = reinterpret_cast<HANDLE>(_get_osfhandle(::_fileno(*fp)));
  107. if (!::SetHandleInformation(file_handle, HANDLE_FLAG_INHERIT, 0))
  108. {
  109. ::fclose(*fp);
  110. *fp = nullptr;
  111. }
  112. }
  113. # endif
  114. #else // unix
  115. # if defined(SPDLOG_PREVENT_CHILD_FD)
  116. const int mode_flag = mode == SPDLOG_FILENAME_T("ab") ? O_APPEND : O_TRUNC;
  117. const int fd = ::open((filename.c_str()), O_CREAT | O_WRONLY | O_CLOEXEC | mode_flag, mode_t(0644));
  118. if (fd == -1)
  119. {
  120. return true;
  121. }
  122. *fp = ::fdopen(fd, mode.c_str());
  123. if (*fp == nullptr)
  124. {
  125. ::close(fd);
  126. }
  127. # else
  128. *fp = ::fopen((filename.c_str()), mode.c_str());
  129. # endif
  130. #endif
  131. return *fp == nullptr;
  132. }
  133. SPDLOG_INLINE int remove(const filename_t &filename) SPDLOG_NOEXCEPT
  134. {
  135. #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
  136. return ::_wremove(filename.c_str());
  137. #else
  138. return std::remove(filename.c_str());
  139. #endif
  140. }
  141. SPDLOG_INLINE int remove_if_exists(const filename_t &filename) SPDLOG_NOEXCEPT
  142. {
  143. return path_exists(filename) ? remove(filename) : 0;
  144. }
  145. SPDLOG_INLINE int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT
  146. {
  147. #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
  148. return ::_wrename(filename1.c_str(), filename2.c_str());
  149. #else
  150. return std::rename(filename1.c_str(), filename2.c_str());
  151. #endif
  152. }
  153. // Return true if path exists (file or directory)
  154. SPDLOG_INLINE bool path_exists(const filename_t &filename) SPDLOG_NOEXCEPT
  155. {
  156. #ifdef _WIN32
  157. # ifdef SPDLOG_WCHAR_FILENAMES
  158. auto attribs = ::GetFileAttributesW(filename.c_str());
  159. # else
  160. auto attribs = ::GetFileAttributesA(filename.c_str());
  161. # endif
  162. return attribs != INVALID_FILE_ATTRIBUTES;
  163. #else // common linux/unix all have the stat system call
  164. struct stat buffer;
  165. return (::stat(filename.c_str(), &buffer) == 0);
  166. #endif
  167. }
  168. #ifdef _MSC_VER
  169. // avoid warning about unreachable statement at the end of filesize()
  170. # pragma warning(push)
  171. # pragma warning(disable : 4702)
  172. #endif
  173. // Return file size according to open FILE* object
  174. SPDLOG_INLINE size_t filesize(FILE *f)
  175. {
  176. if (f == nullptr)
  177. {
  178. throw_spdlog_ex("Failed getting file size. fd is null");
  179. }
  180. #if defined(_WIN32) && !defined(__CYGWIN__)
  181. int fd = ::_fileno(f);
  182. # if defined(_WIN64) // 64 bits
  183. __int64 ret = ::_filelengthi64(fd);
  184. if (ret >= 0)
  185. {
  186. return static_cast<size_t>(ret);
  187. }
  188. # else // windows 32 bits
  189. long ret = ::_filelength(fd);
  190. if (ret >= 0)
  191. {
  192. return static_cast<size_t>(ret);
  193. }
  194. # endif
  195. #else // unix
  196. // OpenBSD and AIX doesn't compile with :: before the fileno(..)
  197. # if defined(__OpenBSD__) || defined(_AIX)
  198. int fd = fileno(f);
  199. # else
  200. int fd = ::fileno(f);
  201. # endif
  202. // 64 bits(but not in osx or cygwin, where fstat64 is deprecated)
  203. # if (defined(__linux__) || defined(__sun) || defined(_AIX)) && (defined(__LP64__) || defined(_LP64))
  204. struct stat64 st;
  205. if (::fstat64(fd, &st) == 0)
  206. {
  207. return static_cast<size_t>(st.st_size);
  208. }
  209. # else // other unix or linux 32 bits or cygwin
  210. struct stat st;
  211. if (::fstat(fd, &st) == 0)
  212. {
  213. return static_cast<size_t>(st.st_size);
  214. }
  215. # endif
  216. #endif
  217. throw_spdlog_ex("Failed getting file size from fd", errno);
  218. return 0; // will not be reached.
  219. }
  220. #ifdef _MSC_VER
  221. # pragma warning(pop)
  222. #endif
  223. // Return utc offset in minutes or throw spdlog_ex on failure
  224. SPDLOG_INLINE int utc_minutes_offset(const std::tm &tm)
  225. {
  226. #ifdef _WIN32
  227. # if _WIN32_WINNT < _WIN32_WINNT_WS08
  228. TIME_ZONE_INFORMATION tzinfo;
  229. auto rv = ::GetTimeZoneInformation(&tzinfo);
  230. # else
  231. DYNAMIC_TIME_ZONE_INFORMATION tzinfo;
  232. auto rv = ::GetDynamicTimeZoneInformation(&tzinfo);
  233. # endif
  234. if (rv == TIME_ZONE_ID_INVALID)
  235. throw_spdlog_ex("Failed getting timezone info. ", errno);
  236. int offset = -tzinfo.Bias;
  237. if (tm.tm_isdst)
  238. {
  239. offset -= tzinfo.DaylightBias;
  240. }
  241. else
  242. {
  243. offset -= tzinfo.StandardBias;
  244. }
  245. return offset;
  246. #else
  247. # if defined(sun) || defined(__sun) || defined(_AIX) || (!defined(_BSD_SOURCE) && !defined(_GNU_SOURCE))
  248. // 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
  249. struct helper
  250. {
  251. static long int calculate_gmt_offset(const std::tm &localtm = details::os::localtime(), const std::tm &gmtm = details::os::gmtime())
  252. {
  253. int local_year = localtm.tm_year + (1900 - 1);
  254. int gmt_year = gmtm.tm_year + (1900 - 1);
  255. long int days = (
  256. // difference in day of year
  257. localtm.tm_yday -
  258. gmtm.tm_yday
  259. // + intervening leap days
  260. + ((local_year >> 2) - (gmt_year >> 2)) - (local_year / 100 - gmt_year / 100) +
  261. ((local_year / 100 >> 2) - (gmt_year / 100 >> 2))
  262. // + difference in years * 365 */
  263. + static_cast<long int>(local_year - gmt_year) * 365);
  264. long int hours = (24 * days) + (localtm.tm_hour - gmtm.tm_hour);
  265. long int mins = (60 * hours) + (localtm.tm_min - gmtm.tm_min);
  266. long int secs = (60 * mins) + (localtm.tm_sec - gmtm.tm_sec);
  267. return secs;
  268. }
  269. };
  270. auto offset_seconds = helper::calculate_gmt_offset(tm);
  271. # else
  272. auto offset_seconds = tm.tm_gmtoff;
  273. # endif
  274. return static_cast<int>(offset_seconds / 60);
  275. #endif
  276. }
  277. // Return current thread id as size_t
  278. // It exists because the std::this_thread::get_id() is much slower(especially
  279. // under VS 2013)
  280. SPDLOG_INLINE size_t _thread_id() SPDLOG_NOEXCEPT
  281. {
  282. #ifdef _WIN32
  283. return static_cast<size_t>(::GetCurrentThreadId());
  284. #elif defined(__linux__)
  285. # if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
  286. # define SYS_gettid __NR_gettid
  287. # endif
  288. return static_cast<size_t>(::syscall(SYS_gettid));
  289. #elif defined(_AIX)
  290. struct __pthrdsinfo buf;
  291. int reg_size = 0;
  292. pthread_t pt = pthread_self();
  293. int retval = pthread_getthrds_np(&pt, PTHRDSINFO_QUERY_TID, &buf, sizeof(buf), NULL, &reg_size);
  294. int tid = (!retval) ? buf.__pi_tid : 0;
  295. return static_cast<size_t>(tid);
  296. #elif defined(__DragonFly__) || defined(__FreeBSD__)
  297. return static_cast<size_t>(::pthread_getthreadid_np());
  298. #elif defined(__NetBSD__)
  299. return static_cast<size_t>(::_lwp_self());
  300. #elif defined(__OpenBSD__)
  301. return static_cast<size_t>(::getthrid());
  302. #elif defined(__sun)
  303. return static_cast<size_t>(::thr_self());
  304. #elif __APPLE__
  305. uint64_t tid;
  306. pthread_threadid_np(nullptr, &tid);
  307. return static_cast<size_t>(tid);
  308. #else // Default to standard C++11 (other Unix)
  309. return static_cast<size_t>(std::hash<std::thread::id>()(std::this_thread::get_id()));
  310. #endif
  311. }
  312. // Return current thread id as size_t (from thread local storage)
  313. SPDLOG_INLINE size_t thread_id() SPDLOG_NOEXCEPT
  314. {
  315. #if defined(SPDLOG_NO_TLS)
  316. return _thread_id();
  317. #else // cache thread id in tls
  318. static thread_local const size_t tid = _thread_id();
  319. return tid;
  320. #endif
  321. }
  322. // This is avoid msvc issue in sleep_for that happens if the clock changes.
  323. // See https://github.com/gabime/spdlog/issues/609
  324. SPDLOG_INLINE void sleep_for_millis(unsigned int milliseconds) SPDLOG_NOEXCEPT
  325. {
  326. #if defined(_WIN32)
  327. ::Sleep(milliseconds);
  328. #else
  329. std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
  330. #endif
  331. }
  332. // wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined)
  333. #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
  334. SPDLOG_INLINE std::string filename_to_str(const filename_t &filename)
  335. {
  336. memory_buf_t buf;
  337. wstr_to_utf8buf(filename, buf);
  338. return SPDLOG_BUF_TO_STRING(buf);
  339. }
  340. #else
  341. SPDLOG_INLINE std::string filename_to_str(const filename_t &filename)
  342. {
  343. return filename;
  344. }
  345. #endif
  346. SPDLOG_INLINE int pid() SPDLOG_NOEXCEPT
  347. {
  348. #ifdef _WIN32
  349. return conditional_static_cast<int>(::GetCurrentProcessId());
  350. #else
  351. return conditional_static_cast<int>(::getpid());
  352. #endif
  353. }
  354. // Determine if the terminal supports colors
  355. // Based on: https://github.com/agauniyal/rang/
  356. SPDLOG_INLINE bool is_color_terminal() SPDLOG_NOEXCEPT
  357. {
  358. #ifdef _WIN32
  359. return true;
  360. #else
  361. static const bool result = []() {
  362. const char *env_colorterm_p = std::getenv("COLORTERM");
  363. if (env_colorterm_p != nullptr)
  364. {
  365. return true;
  366. }
  367. static constexpr std::array<const char *, 16> terms = {{"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux",
  368. "msys", "putty", "rxvt", "screen", "vt100", "xterm", "alacritty", "vt102"}};
  369. const char *env_term_p = std::getenv("TERM");
  370. if (env_term_p == nullptr)
  371. {
  372. return false;
  373. }
  374. return std::any_of(terms.begin(), terms.end(), [&](const char *term) { return std::strstr(env_term_p, term) != nullptr; });
  375. }();
  376. return result;
  377. #endif
  378. }
  379. // Determine if the terminal attached
  380. // Source: https://github.com/agauniyal/rang/
  381. SPDLOG_INLINE bool in_terminal(FILE *file) SPDLOG_NOEXCEPT
  382. {
  383. #ifdef _WIN32
  384. return ::_isatty(_fileno(file)) != 0;
  385. #else
  386. return ::isatty(fileno(file)) != 0;
  387. #endif
  388. }
  389. #if (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && defined(_WIN32)
  390. SPDLOG_INLINE void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target)
  391. {
  392. if (wstr.size() > static_cast<size_t>((std::numeric_limits<int>::max)()) / 2 - 1)
  393. {
  394. throw_spdlog_ex("UTF-16 string is too big to be converted to UTF-8");
  395. }
  396. int wstr_size = static_cast<int>(wstr.size());
  397. if (wstr_size == 0)
  398. {
  399. target.resize(0);
  400. return;
  401. }
  402. int result_size = static_cast<int>(target.capacity());
  403. if ((wstr_size + 1) * 2 > result_size)
  404. {
  405. result_size = ::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, NULL, 0, NULL, NULL);
  406. }
  407. if (result_size > 0)
  408. {
  409. target.resize(result_size);
  410. result_size = ::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, target.data(), result_size, NULL, NULL);
  411. if (result_size > 0)
  412. {
  413. target.resize(result_size);
  414. return;
  415. }
  416. }
  417. throw_spdlog_ex(fmt_lib::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError()));
  418. }
  419. SPDLOG_INLINE void utf8_to_wstrbuf(string_view_t str, wmemory_buf_t &target)
  420. {
  421. if (str.size() > static_cast<size_t>((std::numeric_limits<int>::max)()) - 1)
  422. {
  423. throw_spdlog_ex("UTF-8 string is too big to be converted to UTF-16");
  424. }
  425. int str_size = static_cast<int>(str.size());
  426. if (str_size == 0)
  427. {
  428. target.resize(0);
  429. return;
  430. }
  431. int result_size = static_cast<int>(target.capacity());
  432. if (str_size + 1 > result_size)
  433. {
  434. result_size = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.data(), str_size, NULL, 0);
  435. }
  436. if (result_size > 0)
  437. {
  438. target.resize(result_size);
  439. result_size = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.data(), str_size, target.data(), result_size);
  440. if (result_size > 0)
  441. {
  442. target.resize(result_size);
  443. return;
  444. }
  445. }
  446. throw_spdlog_ex(fmt_lib::format("MultiByteToWideChar failed. Last error: {}", ::GetLastError()));
  447. }
  448. #endif // (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && defined(_WIN32)
  449. // return true on success
  450. static SPDLOG_INLINE bool mkdir_(const filename_t &path)
  451. {
  452. #ifdef _WIN32
  453. # ifdef SPDLOG_WCHAR_FILENAMES
  454. return ::_wmkdir(path.c_str()) == 0;
  455. # else
  456. return ::_mkdir(path.c_str()) == 0;
  457. # endif
  458. #else
  459. return ::mkdir(path.c_str(), mode_t(0755)) == 0;
  460. #endif
  461. }
  462. // create the given directory - and all directories leading to it
  463. // return true on success or if the directory already exists
  464. SPDLOG_INLINE bool create_dir(const filename_t &path)
  465. {
  466. if (path_exists(path))
  467. {
  468. return true;
  469. }
  470. if (path.empty())
  471. {
  472. return false;
  473. }
  474. size_t search_offset = 0;
  475. do
  476. {
  477. auto token_pos = path.find_first_of(folder_seps_filename, search_offset);
  478. // treat the entire path as a folder if no folder separator not found
  479. if (token_pos == filename_t::npos)
  480. {
  481. token_pos = path.size();
  482. }
  483. auto subdir = path.substr(0, token_pos);
  484. if (!subdir.empty() && !path_exists(subdir) && !mkdir_(subdir))
  485. {
  486. return false; // return error if failed creating dir
  487. }
  488. search_offset = token_pos + 1;
  489. } while (search_offset < path.size());
  490. return true;
  491. }
  492. // Return directory name from given path or empty string
  493. // "abc/file" => "abc"
  494. // "abc/" => "abc"
  495. // "abc" => ""
  496. // "abc///" => "abc//"
  497. SPDLOG_INLINE filename_t dir_name(const filename_t &path)
  498. {
  499. auto pos = path.find_last_of(folder_seps_filename);
  500. return pos != filename_t::npos ? path.substr(0, pos) : filename_t{};
  501. }
  502. std::string SPDLOG_INLINE getenv(const char *field)
  503. {
  504. #if defined(_MSC_VER)
  505. # if defined(__cplusplus_winrt)
  506. return std::string{}; // not supported under uwp
  507. # else
  508. size_t len = 0;
  509. char buf[128];
  510. bool ok = ::getenv_s(&len, buf, sizeof(buf), field) == 0;
  511. return ok ? buf : std::string{};
  512. # endif
  513. #else // revert to getenv
  514. char *buf = ::getenv(field);
  515. return buf ? buf : std::string{};
  516. #endif
  517. }
  518. } // namespace os
  519. } // namespace details
  520. } // namespace spdlog