bitz-server  2.0.3
os.h
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 
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 }
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 
86 inline std::tm localtime()
87 {
88  std::time_t now_t = time(nullptr);
89  return localtime(now_t);
90 }
91 
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 
105 inline std::tm gmtime()
106 {
107  std::time_t now_t = time(nullptr);
108  return gmtime(now_t);
109 }
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 
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 
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
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 
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 
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
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
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
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 under VS 2013)
325 inline size_t _thread_id()
326 {
327 #ifdef _WIN32
328  return static_cast<size_t>(::GetCurrentThreadId());
329 #elif __linux__
330 #if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
331 #define SYS_gettid __NR_gettid
332 #endif
333  return static_cast<size_t>(syscall(SYS_gettid));
334 #elif __FreeBSD__
335  long tid;
336  thr_self(&tid);
337  return static_cast<size_t>(tid);
338 #elif __APPLE__
339  uint64_t tid;
340  pthread_threadid_np(nullptr, &tid);
341  return static_cast<size_t>(tid);
342 #else // Default to standard C++11 (other Unix)
343  return static_cast<size_t>(std::hash<std::thread::id>()(std::this_thread::get_id()));
344 #endif
345 }
346 
347 // Return current thread id as size_t (from thread local storage)
348 inline size_t thread_id()
349 {
350 #if defined(SPDLOG_DISABLE_TID_CACHING) || (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt) || \
351  (defined(__clang__) && !__has_feature(cxx_thread_local))
352  return _thread_id();
353 #else // cache thread id in tls
354  static thread_local const size_t tid = _thread_id();
355  return tid;
356 #endif
357 }
358 
359 // This is avoid msvc issue in sleep_for that happens if the clock changes.
360 // See https://github.com/gabime/spdlog/issues/609
361 inline void sleep_for_millis(int milliseconds)
362 {
363 #if defined(_WIN32)
364  ::Sleep(milliseconds);
365 #else
366  std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
367 #endif
368 }
369 
370 // wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined)
371 #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
372 #define SPDLOG_FILENAME_T(s) L##s
373 inline std::string filename_to_str(const filename_t &filename)
374 {
375  std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> c;
376  return c.to_bytes(filename);
377 }
378 #else
379 #define SPDLOG_FILENAME_T(s) s
380 inline std::string filename_to_str(const filename_t &filename)
381 {
382  return filename;
383 }
384 #endif
385 
386 inline int pid()
387 {
388 
389 #ifdef _WIN32
390  return static_cast<int>(::GetCurrentProcessId());
391 #else
392  return static_cast<int>(::getpid());
393 #endif
394 }
395 
396 // Determine if the terminal supports colors
397 // Source: https://github.com/agauniyal/rang/
398 inline bool is_color_terminal()
399 {
400 #ifdef _WIN32
401  return true;
402 #else
403  static constexpr const char *Terms[] = {
404  "ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"};
405 
406  const char *env_p = std::getenv("TERM");
407  if (env_p == nullptr)
408  {
409  return false;
410  }
411 
412  static const bool result =
413  std::any_of(std::begin(Terms), std::end(Terms), [&](const char *term) { return std::strstr(env_p, term) != nullptr; });
414  return result;
415 #endif
416 }
417 
418 // Detrmine if the terminal attached
419 // Source: https://github.com/agauniyal/rang/
420 inline bool in_terminal(FILE *file)
421 {
422 
423 #ifdef _WIN32
424  return _isatty(_fileno(file)) != 0;
425 #else
426  return isatty(fileno(file)) != 0;
427 #endif
428 }
429 } // namespace os
430 } // namespace details
431 } // namespace spdlog
Definition: lib/spdlog/common.h:146
Definition: async_logger.h:26