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