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 #ifdef __DragonFly__
57 #include <sys/syscall.h>
58 #endif
59 
60 namespace spdlog {
61 namespace details {
62 namespace os {
63 
now()64 inline spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT
65 {
66 
67 #if defined __linux__ && defined SPDLOG_CLOCK_COARSE
68     timespec ts;
69     ::clock_gettime(CLOCK_REALTIME_COARSE, &ts);
70     return std::chrono::time_point<log_clock, typename log_clock::duration>(
71         std::chrono::duration_cast<typename log_clock::duration>(std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec)));
72 
73 #else
74     return log_clock::now();
75 #endif
76 }
localtime(const std::time_t & time_tt)77 inline std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
78 {
79 
80 #ifdef _WIN32
81     std::tm tm;
82     localtime_s(&tm, &time_tt);
83 #else
84     std::tm tm;
85     localtime_r(&time_tt, &tm);
86 #endif
87     return tm;
88 }
89 
localtime()90 inline std::tm localtime() SPDLOG_NOEXCEPT
91 {
92     std::time_t now_t = time(nullptr);
93     return localtime(now_t);
94 }
95 
gmtime(const std::time_t & time_tt)96 inline std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
97 {
98 
99 #ifdef _WIN32
100     std::tm tm;
101     gmtime_s(&tm, &time_tt);
102 #else
103     std::tm tm;
104     gmtime_r(&time_tt, &tm);
105 #endif
106     return tm;
107 }
108 
gmtime()109 inline std::tm gmtime() SPDLOG_NOEXCEPT
110 {
111     std::time_t now_t = time(nullptr);
112     return gmtime(now_t);
113 }
114 
115 // eol definition
116 #if !defined(SPDLOG_EOL)
117 #ifdef _WIN32
118 #define SPDLOG_EOL "\r\n"
119 #else
120 #define SPDLOG_EOL "\n"
121 #endif
122 #endif
123 
124 SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL;
125 
126 // folder separator
127 #ifdef _WIN32
128 SPDLOG_CONSTEXPR static const char folder_sep = '\\';
129 #else
130 SPDLOG_CONSTEXPR static const char folder_sep = '/';
131 #endif
132 
prevent_child_fd(FILE * f)133 inline void prevent_child_fd(FILE *f)
134 {
135 
136 #ifdef _WIN32
137 #if !defined(__cplusplus_winrt)
138     auto file_handle = (HANDLE)_get_osfhandle(_fileno(f));
139     if (!::SetHandleInformation(file_handle, HANDLE_FLAG_INHERIT, 0))
140         throw spdlog_ex("SetHandleInformation failed", errno);
141 #endif
142 #else
143     auto fd = fileno(f);
144     if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
145     {
146         throw spdlog_ex("fcntl with FD_CLOEXEC failed", errno);
147     }
148 #endif
149 }
150 
151 // fopen_s on non windows for writing
fopen_s(FILE ** fp,const filename_t & filename,const filename_t & mode)152 inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode)
153 {
154 #ifdef _WIN32
155 #ifdef SPDLOG_WCHAR_FILENAMES
156     *fp = _wfsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
157 #else
158     *fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
159 #endif
160 #else // unix
161     *fp = fopen((filename.c_str()), mode.c_str());
162 #endif
163 
164 #ifdef SPDLOG_PREVENT_CHILD_FD
165     if (*fp != nullptr)
166     {
167         prevent_child_fd(*fp);
168     }
169 #endif
170     return *fp == nullptr;
171 }
172 
remove(const filename_t & filename)173 inline int remove(const filename_t &filename) SPDLOG_NOEXCEPT
174 {
175 #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
176     return _wremove(filename.c_str());
177 #else
178     return std::remove(filename.c_str());
179 #endif
180 }
181 
rename(const filename_t & filename1,const filename_t & filename2)182 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 if file exists
file_exists(const filename_t & filename)192 inline bool file_exists(const filename_t &filename) SPDLOG_NOEXCEPT
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 && !(attribs & FILE_ATTRIBUTE_DIRECTORY));
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 // Return file size according to open FILE* object
filesize(FILE * f)208 inline size_t filesize(FILE *f)
209 {
210     if (f == nullptr)
211     {
212         throw spdlog_ex("Failed getting file size. fd is null");
213     }
214 #if defined(_WIN32) && !defined(__CYGWIN__)
215     int fd = _fileno(f);
216 #if _WIN64 // 64 bits
217     __int64 ret = _filelengthi64(fd);
218     if (ret >= 0)
219     {
220         return static_cast<size_t>(ret);
221     }
222 
223 #else // windows 32 bits
224     long ret = _filelength(fd);
225     if (ret >= 0)
226     {
227         return static_cast<size_t>(ret);
228     }
229 #endif
230 
231 #else // unix
232     int fd = fileno(f);
233 // 64 bits(but not in osx or cygwin, where fstat64 is deprecated)
234 #if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__) && !defined(__HAIKU__) && !defined(__DragonFly__)
235     struct stat64 st;
236     if (fstat64(fd, &st) == 0)
237     {
238         return static_cast<size_t>(st.st_size);
239     }
240 #else // unix 32 bits or cygwin
241     struct stat st;
242 
243     if (fstat(fd, &st) == 0)
244     {
245         return static_cast<size_t>(st.st_size);
246     }
247 #endif
248 #endif
249     throw spdlog_ex("Failed getting file size from fd", errno);
250 }
251 
252 // Return utc offset in minutes or throw spdlog_ex on failure
253 inline int utc_minutes_offset(const std::tm &tm = details::os::localtime())
254 {
255 
256 #ifdef _WIN32
257 #if _WIN32_WINNT < _WIN32_WINNT_WS08
258     TIME_ZONE_INFORMATION tzinfo;
259     auto rv = GetTimeZoneInformation(&tzinfo);
260 #else
261     DYNAMIC_TIME_ZONE_INFORMATION tzinfo;
262     auto rv = GetDynamicTimeZoneInformation(&tzinfo);
263 #endif
264     if (rv == TIME_ZONE_ID_INVALID)
265         throw spdlog::spdlog_ex("Failed getting timezone info. ", errno);
266 
267     int offset = -tzinfo.Bias;
268     if (tm.tm_isdst)
269     {
270         offset -= tzinfo.DaylightBias;
271     }
272     else
273     {
274         offset -= tzinfo.StandardBias;
275     }
276     return offset;
277 #else
278 
279 #if defined(sun) || defined(__sun) || defined(_AIX) || defined(__VITA__) || defined(__SWITCH__)
280     // 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
281     struct helper
282     {
283         static long int calculate_gmt_offset(const std::tm &localtm = details::os::localtime(), const std::tm &gmtm = details::os::gmtime())
284         {
285             int local_year = localtm.tm_year + (1900 - 1);
286             int gmt_year = gmtm.tm_year + (1900 - 1);
287 
288             long int days = (
289                 // difference in day of year
290                 localtm.tm_yday -
291                 gmtm.tm_yday
292 
293                 // + intervening leap days
294                 + ((local_year >> 2) - (gmt_year >> 2)) - (local_year / 100 - gmt_year / 100) +
295                 ((local_year / 100 >> 2) - (gmt_year / 100 >> 2))
296 
297                 // + difference in years * 365 */
298                 + (long int)(local_year - gmt_year) * 365);
299 
300             long int hours = (24 * days) + (localtm.tm_hour - gmtm.tm_hour);
301             long int mins = (60 * hours) + (localtm.tm_min - gmtm.tm_min);
302             long int secs = (60 * mins) + (localtm.tm_sec - gmtm.tm_sec);
303 
304             return secs;
305         }
306     };
307 
308     auto offset_seconds = helper::calculate_gmt_offset(tm);
309 #else
310     auto offset_seconds = tm.tm_gmtoff;
311 #endif
312 
313     return static_cast<int>(offset_seconds / 60);
314 #endif
315 }
316 
317 // Return current thread id as size_t
318 // It exists because the std::this_thread::get_id() is much slower(especially
319 // under VS 2013)
_thread_id()320 inline size_t _thread_id() SPDLOG_NOEXCEPT
321 {
322 #ifdef _WIN32
323     return static_cast<size_t>(::GetCurrentThreadId());
324 #elif __linux__
325 #if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
326 #define SYS_gettid __NR_gettid
327 #endif
328     return static_cast<size_t>(syscall(SYS_gettid));
329 #elif __FreeBSD__
330     long tid;
331     thr_self(&tid);
332     return static_cast<size_t>(tid);
333 #elif __DragonFly__
334     return static_cast<size_t>(syscall(SYS_lwp_gettid));
335 #elif __APPLE__
336     uint64_t tid;
337     pthread_threadid_np(nullptr, &tid);
338     return static_cast<size_t>(tid);
339 #else // Default to standard C++11 (other Unix)
340     return static_cast<size_t>(std::hash<std::thread::id>()(std::this_thread::get_id()));
341 #endif
342 }
343 
344 // Return current thread id as size_t (from thread local storage)
thread_id()345 inline size_t thread_id() SPDLOG_NOEXCEPT
346 {
347 #if defined(SPDLOG_NO_TLS)
348     return _thread_id();
349 #else // cache thread id in tls
350     static thread_local const size_t tid = _thread_id();
351     return tid;
352 #endif
353 }
354 
355 // This is avoid msvc issue in sleep_for that happens if the clock changes.
356 // See https://github.com/gabime/spdlog/issues/609
sleep_for_millis(int milliseconds)357 inline void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT
358 {
359 #if defined(_WIN32)
360     ::Sleep(milliseconds);
361 #else
362     std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
363 #endif
364 }
365 
366 // wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined)
367 #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
368 #define SPDLOG_FILENAME_T(s) L##s
filename_to_str(const filename_t & filename)369 inline std::string filename_to_str(const filename_t &filename)
370 {
371     std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> c;
372     return c.to_bytes(filename);
373 }
374 #else
375 #define SPDLOG_FILENAME_T(s) s
filename_to_str(const filename_t & filename)376 inline std::string filename_to_str(const filename_t &filename)
377 {
378     return filename;
379 }
380 #endif
381 
pid()382 inline int pid()
383 {
384 
385 #ifdef _WIN32
386     return static_cast<int>(::GetCurrentProcessId());
387 #else
388     return static_cast<int>(::getpid());
389 #endif
390 }
391 
392 // Determine if the terminal supports colors
393 // Source: https://github.com/agauniyal/rang/
is_color_terminal()394 inline bool is_color_terminal() SPDLOG_NOEXCEPT
395 {
396 #ifdef _WIN32
397     return true;
398 #else
399     static constexpr const char *Terms[] = {
400         "ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"};
401 
402     const char *env_p = std::getenv("TERM");
403     if (env_p == nullptr)
404     {
405         return false;
406     }
407 
408     static const bool result =
409         std::any_of(std::begin(Terms), std::end(Terms), [&](const char *term) { return std::strstr(env_p, term) != nullptr; });
410     return result;
411 #endif
412 }
413 
414 // Detrmine if the terminal attached
415 // Source: https://github.com/agauniyal/rang/
in_terminal(FILE * file)416 inline bool in_terminal(FILE *file) SPDLOG_NOEXCEPT
417 {
418 
419 #ifdef _WIN32
420     return _isatty(_fileno(file)) != 0;
421 #else
422     return isatty(fileno(file)) != 0;
423 #endif
424 }
425 } // namespace os
426 } // namespace details
427 } // namespace spdlog
428