cmTimestamp.cxx 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #if !defined(_WIN32) && !defined(__sun) && !defined(__OpenBSD__)
  4. // POSIX APIs are needed
  5. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  6. # define _POSIX_C_SOURCE 200809L
  7. #endif
  8. #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__QNX__)
  9. // For isascii
  10. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  11. # define _XOPEN_SOURCE 700
  12. #endif
  13. #include "cmTimestamp.h"
  14. #include <cstdlib>
  15. #include <cstring>
  16. #include <sstream>
  17. #include <utility>
  18. #ifdef __MINGW32__
  19. # include <libloaderapi.h>
  20. #endif
  21. #include <cm3p/uv.h>
  22. #include "cmStringAlgorithms.h"
  23. #include "cmSystemTools.h"
  24. std::string cmTimestamp::CurrentTime(const std::string& formatString,
  25. bool utcFlag) const
  26. {
  27. // get current time with microsecond resolution
  28. uv_timeval64_t timeval;
  29. uv_gettimeofday(&timeval);
  30. auto currentTimeT = static_cast<time_t>(timeval.tv_sec);
  31. auto microseconds = static_cast<uint32_t>(timeval.tv_usec);
  32. // check for override via SOURCE_DATE_EPOCH for reproducible builds
  33. std::string source_date_epoch;
  34. cmSystemTools::GetEnv("SOURCE_DATE_EPOCH", source_date_epoch);
  35. if (!source_date_epoch.empty()) {
  36. std::istringstream iss(source_date_epoch);
  37. iss >> currentTimeT;
  38. if (iss.fail() || !iss.eof()) {
  39. cmSystemTools::Error("Cannot parse SOURCE_DATE_EPOCH as integer");
  40. exit(27);
  41. }
  42. // SOURCE_DATE_EPOCH has only a resolution in the seconds range
  43. microseconds = 0;
  44. }
  45. if (currentTimeT == static_cast<time_t>(-1)) {
  46. return std::string();
  47. }
  48. return this->CreateTimestampFromTimeT(currentTimeT, microseconds,
  49. formatString, utcFlag);
  50. }
  51. std::string cmTimestamp::FileModificationTime(const char* path,
  52. const std::string& formatString,
  53. bool utcFlag) const
  54. {
  55. std::string real_path =
  56. cmSystemTools::GetRealPathResolvingWindowsSubst(path);
  57. if (!cmsys::SystemTools::FileExists(real_path)) {
  58. return std::string();
  59. }
  60. // use libuv's implementation of stat(2) to get the file information
  61. time_t mtime = 0;
  62. uint32_t microseconds = 0;
  63. uv_fs_t req;
  64. if (uv_fs_stat(nullptr, &req, real_path.c_str(), nullptr) == 0) {
  65. mtime = static_cast<time_t>(req.statbuf.st_mtim.tv_sec);
  66. // tv_nsec has nanosecond resolution, but we truncate it to microsecond
  67. // resolution in order to be consistent with cmTimestamp::CurrentTime()
  68. microseconds = static_cast<uint32_t>(req.statbuf.st_mtim.tv_nsec / 1000);
  69. }
  70. uv_fs_req_cleanup(&req);
  71. return this->CreateTimestampFromTimeT(mtime, microseconds, formatString,
  72. utcFlag);
  73. }
  74. std::string cmTimestamp::CreateTimestampFromTimeT(time_t timeT,
  75. std::string formatString,
  76. bool utcFlag) const
  77. {
  78. return this->CreateTimestampFromTimeT(timeT, 0, std::move(formatString),
  79. utcFlag);
  80. }
  81. std::string cmTimestamp::CreateTimestampFromTimeT(time_t timeT,
  82. const uint32_t microseconds,
  83. std::string formatString,
  84. bool utcFlag) const
  85. {
  86. if (formatString.empty()) {
  87. formatString = "%Y-%m-%dT%H:%M:%S";
  88. if (utcFlag) {
  89. formatString += "Z";
  90. }
  91. }
  92. struct tm timeStruct;
  93. memset(&timeStruct, 0, sizeof(timeStruct));
  94. struct tm* ptr = nullptr;
  95. if (utcFlag) {
  96. ptr = gmtime(&timeT);
  97. } else {
  98. ptr = localtime(&timeT);
  99. }
  100. if (!ptr) {
  101. return std::string();
  102. }
  103. timeStruct = *ptr;
  104. std::string result;
  105. for (std::string::size_type i = 0; i < formatString.size(); ++i) {
  106. char c1 = formatString[i];
  107. char c2 = (i + 1 < formatString.size()) ? formatString[i + 1]
  108. : static_cast<char>(0);
  109. if (c1 == '%' && c2 != 0) {
  110. result += this->AddTimestampComponent(c2, timeStruct, timeT, utcFlag,
  111. microseconds);
  112. ++i;
  113. } else {
  114. result += c1;
  115. }
  116. }
  117. return result;
  118. }
  119. time_t cmTimestamp::CreateUtcTimeTFromTm(struct tm& tm) const
  120. {
  121. #if defined(_MSC_VER) && _MSC_VER >= 1400
  122. return _mkgmtime(&tm);
  123. #else
  124. // From Linux timegm() manpage.
  125. std::string tz_old;
  126. bool const tz_was_set = cmSystemTools::GetEnv("TZ", tz_old);
  127. tz_old = "TZ=" + tz_old;
  128. // The standard says that "TZ=" or "TZ=[UNRECOGNIZED_TZ]" means UTC.
  129. // It seems that "TZ=" does NOT work, at least under Windows
  130. // with neither MSVC nor MinGW, so let's use explicit "TZ=UTC"
  131. cmSystemTools::PutEnv("TZ=UTC");
  132. tzset();
  133. time_t result = mktime(&tm);
  134. # ifndef CMAKE_BOOTSTRAP
  135. if (tz_was_set) {
  136. cmSystemTools::PutEnv(tz_old);
  137. } else {
  138. cmSystemTools::UnsetEnv("TZ");
  139. }
  140. # else
  141. // No UnsetEnv during bootstrap. This is good enough for CMake itself.
  142. cmSystemTools::PutEnv(tz_old);
  143. static_cast<void>(tz_was_set);
  144. # endif
  145. tzset();
  146. return result;
  147. #endif
  148. }
  149. std::string cmTimestamp::AddTimestampComponent(
  150. char flag, struct tm& timeStruct, const time_t timeT, const bool utcFlag,
  151. const uint32_t microseconds) const
  152. {
  153. std::string formatString = cmStrCat('%', flag);
  154. switch (flag) {
  155. case 'a':
  156. case 'A':
  157. case 'b':
  158. case 'B':
  159. case 'd':
  160. case 'H':
  161. case 'I':
  162. case 'j':
  163. case 'm':
  164. case 'M':
  165. case 'S':
  166. case 'U':
  167. case 'V':
  168. case 'w':
  169. case 'y':
  170. case 'Y':
  171. case '%':
  172. break;
  173. case 'Z':
  174. #if defined(__GLIBC__)
  175. // 'struct tm' has the time zone, so strftime can honor UTC.
  176. static_cast<void>(utcFlag);
  177. #else
  178. // 'struct tm' may not have the time zone, so strftime may
  179. // use local time. Hard-code the UTC result.
  180. if (utcFlag) {
  181. return std::string("GMT");
  182. }
  183. #endif
  184. break;
  185. case 'z': {
  186. #if defined(__GLIBC__)
  187. // 'struct tm' has the time zone, so strftime can honor UTC.
  188. static_cast<void>(utcFlag);
  189. #else
  190. // 'struct tm' may not have the time zone, so strftime may
  191. // use local time. Hard-code the UTC result.
  192. if (utcFlag) {
  193. return std::string("+0000");
  194. }
  195. #endif
  196. #ifndef _AIX
  197. break;
  198. #else
  199. std::string xpg_sus_old;
  200. bool const xpg_sus_was_set =
  201. cmSystemTools::GetEnv("XPG_SUS_ENV", xpg_sus_old);
  202. if (xpg_sus_was_set && xpg_sus_old == "ON") {
  203. break;
  204. }
  205. xpg_sus_old = "XPG_SUS_ENV=" + xpg_sus_old;
  206. // On AIX systems, %z requires XPG_SUS_ENV=ON to work as desired.
  207. cmSystemTools::PutEnv("XPG_SUS_ENV=ON");
  208. tzset();
  209. char buffer[16];
  210. size_t size = strftime(buffer, sizeof(buffer), "%z", &timeStruct);
  211. # ifndef CMAKE_BOOTSTRAP
  212. if (xpg_sus_was_set) {
  213. cmSystemTools::PutEnv(xpg_sus_old);
  214. } else {
  215. cmSystemTools::UnsetEnv("XPG_SUS_ENV");
  216. }
  217. # else
  218. // No UnsetEnv during bootstrap. This is good enough for CMake itself.
  219. cmSystemTools::PutEnv(xpg_sus_old);
  220. static_cast<void>(xpg_sus_was_set);
  221. # endif
  222. tzset();
  223. return std::string(buffer, size);
  224. #endif
  225. }
  226. case 's': // Seconds since UNIX epoch (midnight 1-jan-1970)
  227. {
  228. // Build a time_t for UNIX epoch and subtract from the input "timeT":
  229. struct tm tmUnixEpoch;
  230. memset(&tmUnixEpoch, 0, sizeof(tmUnixEpoch));
  231. tmUnixEpoch.tm_mday = 1;
  232. tmUnixEpoch.tm_year = 1970 - 1900;
  233. const time_t unixEpoch = this->CreateUtcTimeTFromTm(tmUnixEpoch);
  234. if (unixEpoch == -1) {
  235. cmSystemTools::Error(
  236. "Error generating UNIX epoch in string(TIMESTAMP ...) or "
  237. "file(TIMESTAMP ...). Please, file a bug report against CMake");
  238. return std::string();
  239. }
  240. return std::to_string(static_cast<long int>(difftime(timeT, unixEpoch)));
  241. }
  242. case 'f': // microseconds
  243. {
  244. // clip number to 6 digits and pad with leading zeros
  245. std::string microsecs = std::to_string(microseconds % 1000000);
  246. return std::string(6 - microsecs.length(), '0') + microsecs;
  247. }
  248. default: {
  249. return formatString;
  250. }
  251. }
  252. char buffer[16];
  253. #ifdef __MINGW32__
  254. /* See a bug in MinGW: https://sourceforge.net/p/mingw-w64/bugs/793/. A work
  255. * around is to try to use strftime() from ucrtbase.dll. */
  256. using T = size_t(__cdecl*)(char*, size_t, const char*, const struct tm*);
  257. auto loadUcrtStrftime = []() -> T {
  258. auto handle =
  259. LoadLibraryExA("ucrtbase.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
  260. if (handle) {
  261. # pragma GCC diagnostic push
  262. # pragma GCC diagnostic ignored "-Wcast-function-type"
  263. return reinterpret_cast<T>(GetProcAddress(handle, "strftime"));
  264. # pragma GCC diagnostic pop
  265. }
  266. return nullptr;
  267. };
  268. static T ucrtStrftime = loadUcrtStrftime();
  269. if (ucrtStrftime) {
  270. size_t size =
  271. ucrtStrftime(buffer, sizeof(buffer), formatString.c_str(), &timeStruct);
  272. return std::string(buffer, size);
  273. }
  274. #endif
  275. size_t size =
  276. strftime(buffer, sizeof(buffer), formatString.c_str(), &timeStruct);
  277. return std::string(buffer, size);
  278. }