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