1 //
2 // Copyright(c) 2015 Gabi Melman.
3 // Distributed under the MIT License (http://opensource.org/licenses/MIT)
4 //
5 #pragma once
6 
7 #include "../common.h"
8 
9 #include <algorithm>
10 #include <chrono>
11 #include <cstdio>
12 #include <cstdlib>
13 #include <cstring>
14 #include <ctime>
15 #include <functional>
16 #include <string>
17 #include <sys/stat.h>
18 #include <sys/types.h>
19 #include <thread>
20 
21 #ifdef _WIN32
22 
23 #ifndef NOMINMAX
24 #define NOMINMAX // prevent windows redefining min/max
25 #endif
26 
27 #ifndef WIN32_LEAN_AND_MEAN
28 #define WIN32_LEAN_AND_MEAN
29 #endif
30 #include <io.h>      // _get_osfhandle and _isatty support
31 #include <process.h> //  _get_pid support
32 #include <windows.h>
33 
34 #ifdef __MINGW32__
35 #include <share.h>
36 #endif
37 
38 #else // unix
39 
40 #include <fcntl.h>
41 #include <unistd.h>
42 
43 #ifdef __linux__
44 #include <sys/syscall.h> //Use gettid() syscall under linux to get thread id
45 
46 #elif __FreeBSD__
47 #include <sys/thr.h> //Use thr_self() syscall under FreeBSD to get thread id
48 #endif
49 
50 #endif // unix
51 
52 #ifndef __has_feature      // Clang - feature checking macros.
53 #define __has_feature(x) 0 // Compatibility with non-clang compilers.
54 #endif
55 
56 namespace spdlog {
57 namespace details {
58 namespace os {
59 
now()60 inline spdlog::log_clock::time_point now()
61 {
62 
63 #if defined __linux__ && defined SPDLOG_CLOCK_COARSE
64     timespec ts;
65     ::clock_gettime(CLOCK_REALTIME_COARSE, &ts);
66     return std::chrono::time_point<log_clock, typename log_clock::duration>(
67         std::chrono::duration_cast<typename log_clock::duration>(std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec)));
68 
69 #else
70     return log_clock::now();
71 #endif
72 }
localtime(const std::time_t &time_tt)73 inline std::tm localtime(const std::time_t &time_tt)
74 {
75 
76 #ifdef _WIN32
77     std::tm tm;
78     localtime_s(&tm, &time_tt);
79 #else
80     std::tm tm;
81     localtime_r(&time_tt, &tm);
82 #endif
83     return tm;
84 }
85 
localtime()86 inline std::tm localtime()
87 {
88     std::time_t now_t = time(nullptr);
89     return localtime(now_t);
90 }
91 
gmtime(const std::time_t &time_tt)92 inline std::tm gmtime(const std::time_t &time_tt)
93 {
94 
95 #ifdef _WIN32
96     std::tm tm;
97     gmtime_s(&tm, &time_tt);
98 #else
99     std::tm tm;
100     gmtime_r(&time_tt, &tm);
101 #endif
102     return tm;
103 }
104 
gmtime()105 inline std::tm gmtime()
106 {
107     std::time_t now_t = time(nullptr);
108     return gmtime(now_t);
109 }
operator ==(const std::tm &tm1, const std::tm &tm2)110 inline bool operator==(const std::tm &tm1, const std::tm &tm2)
111 {
112     return (tm1.tm_sec == tm2.tm_sec && tm1.tm_min == tm2.tm_min && tm1.tm_hour == tm2.tm_hour && tm1.tm_mday == tm2.tm_mday &&
113             tm1.tm_mon == tm2.tm_mon && tm1.tm_year == tm2.tm_year && tm1.tm_isdst == tm2.tm_isdst);
114 }
115 
operator !=(const std::tm &tm1, const std::tm &tm2)116 inline bool operator!=(const std::tm &tm1, const std::tm &tm2)
117 {
118     return !(tm1 == tm2);
119 }
120 
121 // eol definition
122 #if !defined(SPDLOG_EOL)
123 #ifdef _WIN32
124 #define SPDLOG_EOL "\r\n"
125 #else
126 #define SPDLOG_EOL "\n"
127 #endif
128 #endif
129 
130 SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL;
131 
132 // folder separator
133 #ifdef _WIN32
134 SPDLOG_CONSTEXPR static const char folder_sep = '\\';
135 #else
136 SPDLOG_CONSTEXPR static const char folder_sep = '/';
137 #endif
138 
prevent_child_fd(FILE *f)139 inline void prevent_child_fd(FILE *f)
140 {
141 
142 #ifdef _WIN32
143 #if !defined(__cplusplus_winrt)
144     auto file_handle = (HANDLE)_get_osfhandle(_fileno(f));
145     if (!::SetHandleInformation(file_handle, HANDLE_FLAG_INHERIT, 0))
146         throw spdlog_ex("SetHandleInformation failed", errno);
147 #endif
148 #else
149     auto fd = fileno(f);
150     if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
151     {
152         throw spdlog_ex("fcntl with FD_CLOEXEC failed", errno);
153     }
154 #endif
155 }
156 
157 // fopen_s on non windows for writing
fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode)158 inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode)
159 {
160 #ifdef _WIN32
161 #ifdef SPDLOG_WCHAR_FILENAMES
162     *fp = _wfsopen((filename.c_str()), mode.c_str(), _SH_DENYWR);
163 #else
164     *fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYWR);
165 #endif
166 #else // unix
167     *fp = fopen((filename.c_str()), mode.c_str());
168 #endif
169 
170 #ifdef SPDLOG_PREVENT_CHILD_FD
171     if (*fp != nullptr)
172     {
173         prevent_child_fd(*fp);
174     }
175 #endif
176     return *fp == nullptr;
177 }
178 
remove(const filename_t &filename)179 inline int remove(const filename_t &filename)
180 {
181 #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
182     return _wremove(filename.c_str());
183 #else
184     return std::remove(filename.c_str());
185 #endif
186 }
187 
rename(const filename_t &filename1, const filename_t &filename2)188 inline int rename(const filename_t &filename1, const filename_t &filename2)
189 {
190 #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
191     return _wrename(filename1.c_str(), filename2.c_str());
192 #else
193     return std::rename(filename1.c_str(), filename2.c_str());
194 #endif
195 }
196 
197 // Return if file exists
file_exists(const filename_t &filename)198 inline bool file_exists(const filename_t &filename)
199 {
200 #ifdef _WIN32
201 #ifdef SPDLOG_WCHAR_FILENAMES
202     auto attribs = GetFileAttributesW(filename.c_str());
203 #else
204     auto attribs = GetFileAttributesA(filename.c_str());
205 #endif
206     return (attribs != INVALID_FILE_ATTRIBUTES && !(attribs & FILE_ATTRIBUTE_DIRECTORY));
207 #else // common linux/unix all have the stat system call
208     struct stat buffer;
209     return (stat(filename.c_str(), &buffer) == 0);
210 #endif
211 }
212 
213 // Return file size according to open FILE* object
filesize(FILE *f)214 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 _WIN64 // 64 bits
223     struct _stat64 st;
224     if (_fstat64(fd, &st) == 0)
225     {
226         return st.st_size;
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     int fd = fileno(f);
239 // 64 bits(but not in osx or cygwin, where fstat64 is deprecated)
240 #if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__)
241     struct stat64 st;
242     if (fstat64(fd, &st) == 0)
243     {
244         return static_cast<size_t>(st.st_size);
245     }
246 #else // unix 32 bits or cygwin
247     struct stat st;
248 
249     if (fstat(fd, &st) == 0)
250     {
251         return static_cast<size_t>(st.st_size);
252     }
253 #endif
254 #endif
255     throw spdlog_ex("Failed getting file size from fd", errno);
256 }
257 
258 // Return utc offset in minutes or throw spdlog_ex on failure
utc_minutes_offset(const std::tm &tm = details::os::localtime())259 inline int utc_minutes_offset(const std::tm &tm = details::os::localtime())
260 {
261 
262 #ifdef _WIN32
263 #if _WIN32_WINNT < _WIN32_WINNT_WS08
264     TIME_ZONE_INFORMATION tzinfo;
265     auto rv = GetTimeZoneInformation(&tzinfo);
266 #else
267     DYNAMIC_TIME_ZONE_INFORMATION tzinfo;
268     auto rv = GetDynamicTimeZoneInformation(&tzinfo);
269 #endif
270     if (rv == TIME_ZONE_ID_INVALID)
271         throw spdlog::spdlog_ex("Failed getting timezone info. ", errno);
272 
273     int offset = -tzinfo.Bias;
274     if (tm.tm_isdst)
275     {
276         offset -= tzinfo.DaylightBias;
277     }
278     else
279     {
280         offset -= tzinfo.StandardBias;
281     }
282     return offset;
283 #else
284 
285 #if defined(sun) || defined(__sun) || defined(_AIX)
286     // 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
287     struct helper
288     {
289         static long int calculate_gmt_offset(const std::tm &localtm = details::os::localtime(), const std::tm &gmtm = details::os::gmtime())
290         {
291             int local_year = localtm.tm_year + (1900 - 1);
292             int gmt_year = gmtm.tm_year + (1900 - 1);
293 
294             long int days = (
295                 // difference in day of year
296                 localtm.tm_yday -
297                 gmtm.tm_yday
298 
299                 // + intervening leap days
300                 + ((local_year >> 2) - (gmt_year >> 2)) - (local_year / 100 - gmt_year / 100) +
301                 ((local_year / 100 >> 2) - (gmt_year / 100 >> 2))
302 
303                 // + difference in years * 365 */
304                 + (long int)(local_year - gmt_year) * 365);
305 
306             long int hours = (24 * days) + (localtm.tm_hour - gmtm.tm_hour);
307             long int mins = (60 * hours) + (localtm.tm_min - gmtm.tm_min);
308             long int secs = (60 * mins) + (localtm.tm_sec - gmtm.tm_sec);
309 
310             return secs;
311         }
312     };
313 
314     auto offset_seconds = helper::calculate_gmt_offset(tm);
315 #else
316     auto offset_seconds = tm.tm_gmtoff;
317 #endif
318 
319     return static_cast<int>(offset_seconds / 60);
320 #endif
321 }
322 
323 // Return current thread id as size_t
324 // It exists because the std::this_thread::get_id() is much slower(especially
325 // under VS 2013)
_thread_id()326 inline size_t _thread_id()
327 {
328 #ifdef _WIN32
329     return static_cast<size_t>(::GetCurrentThreadId());
330 #elif __linux__
331 #if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
332 #define SYS_gettid __NR_gettid
333 #endif
334     return static_cast<size_t>(syscall(SYS_gettid));
335 #elif __FreeBSD__
336     long tid;
337     thr_self(&tid);
338     return static_cast<size_t>(tid);
339 #elif __APPLE__
340     uint64_t tid;
341     pthread_threadid_np(nullptr, &tid);
342     return static_cast<size_t>(tid);
343 #else // Default to standard C++11 (other Unix)
344     return static_cast<size_t>(std::hash<std::thread::id>()(std::this_thread::get_id()));
345 #endif
346 }
347 
348 // Return current thread id as size_t (from thread local storage)
thread_id()349 inline size_t thread_id()
350 {
351 #if defined(SPDLOG_DISABLE_TID_CACHING) || (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt) ||                       \
352     (defined(__clang__) && !__has_feature(cxx_thread_local))
353     return _thread_id();
354 #else // cache thread id in tls
355     static thread_local const size_t tid = _thread_id();
356     return tid;
357 #endif
358 }
359 
360 // This is avoid msvc issue in sleep_for that happens if the clock changes.
361 // See https://github.com/gabime/spdlog/issues/609
sleep_for_millis(int milliseconds)362 inline void sleep_for_millis(int milliseconds)
363 {
364 #if defined(_WIN32)
365     ::Sleep(milliseconds);
366 #else
367     std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
368 #endif
369 }
370 
371 // wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined)
372 #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
373 #define SPDLOG_FILENAME_T(s) L##s
filename_to_str(const filename_t &filename)374 inline std::string filename_to_str(const filename_t &filename)
375 {
376     std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> c;
377     return c.to_bytes(filename);
378 }
379 #else
380 #define SPDLOG_FILENAME_T(s) s
filename_to_str(const filename_t &filename)381 inline std::string filename_to_str(const filename_t &filename)
382 {
383     return filename;
384 }
385 #endif
386 
pid()387 inline int pid()
388 {
389 
390 #ifdef _WIN32
391     return static_cast<int>(::GetCurrentProcessId());
392 #else
393     return static_cast<int>(::getpid());
394 #endif
395 }
396 
397 // Determine if the terminal supports colors
398 // Source: https://github.com/agauniyal/rang/
is_color_terminal()399 inline bool is_color_terminal()
400 {
401 #ifdef _WIN32
402     return true;
403 #else
404     static constexpr const char *Terms[] = {
405         "ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"};
406 
407     const char *env_p = std::getenv("TERM");
408     if (env_p == nullptr)
409     {
410         return false;
411     }
412 
413     static const bool result =
414         std::any_of(std::begin(Terms), std::end(Terms), [&](const char *term) { return std::strstr(env_p, term) != nullptr; });
415     return result;
416 #endif
417 }
418 
419 // Detrmine if the terminal attached
420 // Source: https://github.com/agauniyal/rang/
in_terminal(FILE *file)421 inline bool in_terminal(FILE *file)
422 {
423 
424 #ifdef _WIN32
425     return _isatty(_fileno(file)) != 0;
426 #else
427     return isatty(fileno(file)) != 0;
428 #endif
429 }
430 } // namespace os
431 } // namespace details
432 } // namespace spdlog
433