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