time.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/DateConstants.h>
  7. #include <AK/StringBuilder.h>
  8. #include <AK/Time.h>
  9. #include <Kernel/API/TimePage.h>
  10. #include <LibTimeZone/TimeZone.h>
  11. #include <assert.h>
  12. #include <bits/pthread_cancel.h>
  13. #include <errno.h>
  14. #include <limits.h>
  15. #include <stdio.h>
  16. #include <string.h>
  17. #include <sys/time.h>
  18. #include <sys/times.h>
  19. #include <syscall.h>
  20. #include <time.h>
  21. #include <utime.h>
  22. extern "C" {
  23. static constexpr char const* __utc = "UTC";
  24. static StringView __tzname { __utc, __builtin_strlen(__utc) };
  25. static char __tzname_standard[TZNAME_MAX];
  26. static char __tzname_daylight[TZNAME_MAX];
  27. long timezone = 0;
  28. long altzone = 0;
  29. char* tzname[2] = { const_cast<char*>(__utc), const_cast<char*>(__utc) };
  30. int daylight = 0;
  31. time_t time(time_t* tloc)
  32. {
  33. struct timeval tv;
  34. struct timezone tz;
  35. if (gettimeofday(&tv, &tz) < 0)
  36. return (time_t)-1;
  37. if (tloc)
  38. *tloc = tv.tv_sec;
  39. return tv.tv_sec;
  40. }
  41. int adjtime(const struct timeval* delta, struct timeval* old_delta)
  42. {
  43. int rc = syscall(SC_adjtime, delta, old_delta);
  44. __RETURN_WITH_ERRNO(rc, rc, -1);
  45. }
  46. int gettimeofday(struct timeval* __restrict__ tv, void* __restrict__)
  47. {
  48. if (!tv) {
  49. errno = EFAULT;
  50. return -1;
  51. }
  52. struct timespec ts = {};
  53. if (clock_gettime(CLOCK_REALTIME_COARSE, &ts) < 0)
  54. return -1;
  55. TIMESPEC_TO_TIMEVAL(tv, &ts);
  56. return 0;
  57. }
  58. int settimeofday(struct timeval* __restrict__ tv, void* __restrict__)
  59. {
  60. if (!tv) {
  61. errno = EFAULT;
  62. return -1;
  63. }
  64. timespec ts;
  65. TIMEVAL_TO_TIMESPEC(tv, &ts);
  66. return clock_settime(CLOCK_REALTIME, &ts);
  67. }
  68. int utimes(char const* pathname, const struct timeval times[2])
  69. {
  70. if (!times) {
  71. return utime(pathname, nullptr);
  72. }
  73. // FIXME: implement support for tv_usec in the utime (or a new) syscall
  74. utimbuf buf = { times[0].tv_sec, times[1].tv_sec };
  75. return utime(pathname, &buf);
  76. }
  77. char* ctime(time_t const* t)
  78. {
  79. return asctime(localtime(t));
  80. }
  81. char* ctime_r(time_t const* t, char* buf)
  82. {
  83. struct tm tm_buf;
  84. return asctime_r(localtime_r(t, &tm_buf), buf);
  85. }
  86. static int const __seconds_per_day = 60 * 60 * 24;
  87. static bool is_valid_time(time_t timestamp)
  88. {
  89. // Note: these correspond to the number of seconds from epoch to the dates "Jan 1 00:00:00 -2147483648" and "Dec 31 23:59:59 2147483647",
  90. // respectively, which are the smallest and biggest representable dates without overflowing tm->tm_year, if it is an int.
  91. constexpr time_t smallest_possible_time = -67768040609740800;
  92. constexpr time_t biggest_possible_time = 67768036191676799;
  93. return (timestamp >= smallest_possible_time) && (timestamp <= biggest_possible_time);
  94. }
  95. static struct tm* time_to_tm(struct tm* tm, time_t t, StringView time_zone)
  96. {
  97. if (!is_valid_time(t)) {
  98. errno = EOVERFLOW;
  99. return nullptr;
  100. }
  101. if (auto offset = TimeZone::get_time_zone_offset(time_zone, AK::Time::from_seconds(t)); offset.has_value()) {
  102. tm->tm_isdst = offset->in_dst == TimeZone::InDST::Yes;
  103. t += offset->seconds;
  104. }
  105. int year = 1970;
  106. for (; t >= days_in_year(year) * __seconds_per_day; ++year)
  107. t -= days_in_year(year) * __seconds_per_day;
  108. for (; t < 0; --year)
  109. t += days_in_year(year - 1) * __seconds_per_day;
  110. tm->tm_year = year - 1900;
  111. VERIFY(t >= 0);
  112. int days = t / __seconds_per_day;
  113. tm->tm_yday = days;
  114. int remaining = t % __seconds_per_day;
  115. tm->tm_sec = remaining % 60;
  116. remaining /= 60;
  117. tm->tm_min = remaining % 60;
  118. tm->tm_hour = remaining / 60;
  119. int month;
  120. for (month = 1; month < 12 && days >= days_in_month(year, month); ++month)
  121. days -= days_in_month(year, month);
  122. tm->tm_mday = days + 1;
  123. tm->tm_wday = day_of_week(year, month, tm->tm_mday);
  124. tm->tm_mon = month - 1;
  125. return tm;
  126. }
  127. static time_t tm_to_time(struct tm* tm, StringView time_zone)
  128. {
  129. // "The original values of the tm_wday and tm_yday components of the structure are ignored,
  130. // and the original values of the other components are not restricted to the ranges described in <time.h>.
  131. // [...]
  132. // Upon successful completion, the values of the tm_wday and tm_yday components of the structure shall be set appropriately,
  133. // and the other components are set to represent the specified time since the Epoch,
  134. // but with their values forced to the ranges indicated in the <time.h> entry;
  135. // the final value of tm_mday shall not be set until tm_mon and tm_year are determined."
  136. tm->tm_year += tm->tm_mon / 12;
  137. tm->tm_mon %= 12;
  138. if (tm->tm_mon < 0) {
  139. tm->tm_year--;
  140. tm->tm_mon += 12;
  141. }
  142. tm->tm_yday = day_of_year(1900 + tm->tm_year, tm->tm_mon + 1, tm->tm_mday);
  143. time_t days_since_epoch = years_to_days_since_epoch(1900 + tm->tm_year) + tm->tm_yday;
  144. auto timestamp = ((days_since_epoch * 24 + tm->tm_hour) * 60 + tm->tm_min) * 60 + tm->tm_sec;
  145. if (tm->tm_isdst < 0) {
  146. if (auto offset = TimeZone::get_time_zone_offset(time_zone, AK::Time::from_seconds(timestamp)); offset.has_value())
  147. timestamp -= offset->seconds;
  148. } else {
  149. auto index = tm->tm_isdst == 0 ? 0 : 1;
  150. if (auto offsets = TimeZone::get_named_time_zone_offsets(time_zone, AK::Time::from_seconds(timestamp)); offsets.has_value())
  151. timestamp -= offsets->at(index).seconds;
  152. }
  153. if (!is_valid_time(timestamp)) {
  154. errno = EOVERFLOW;
  155. return -1;
  156. }
  157. return timestamp;
  158. }
  159. time_t mktime(struct tm* tm)
  160. {
  161. tzset();
  162. return tm_to_time(tm, __tzname);
  163. }
  164. struct tm* localtime(time_t const* t)
  165. {
  166. tzset();
  167. static struct tm tm_buf;
  168. return localtime_r(t, &tm_buf);
  169. }
  170. struct tm* localtime_r(time_t const* t, struct tm* tm)
  171. {
  172. if (!t)
  173. return nullptr;
  174. return time_to_tm(tm, *t, __tzname);
  175. }
  176. time_t timegm(struct tm* tm)
  177. {
  178. tm->tm_isdst = 0;
  179. return tm_to_time(tm, { __utc, __builtin_strlen(__utc) });
  180. }
  181. struct tm* gmtime(time_t const* t)
  182. {
  183. static struct tm tm_buf;
  184. return gmtime_r(t, &tm_buf);
  185. }
  186. struct tm* gmtime_r(time_t const* t, struct tm* tm)
  187. {
  188. if (!t)
  189. return nullptr;
  190. return time_to_tm(tm, *t, { __utc, __builtin_strlen(__utc) });
  191. }
  192. char* asctime(const struct tm* tm)
  193. {
  194. static char buffer[69];
  195. return asctime_r(tm, buffer);
  196. }
  197. char* asctime_r(const struct tm* tm, char* buffer)
  198. {
  199. // Spec states buffer must be at least 26 bytes.
  200. constexpr size_t assumed_len = 26;
  201. size_t filled_size = strftime(buffer, assumed_len, "%a %b %e %T %Y\n", tm);
  202. // If the buffer was not large enough, set EOVERFLOW and return null.
  203. if (filled_size == 0) {
  204. errno = EOVERFLOW;
  205. return nullptr;
  206. }
  207. return buffer;
  208. }
  209. // FIXME: Some formats are not supported.
  210. size_t strftime(char* destination, size_t max_size, char const* format, const struct tm* tm)
  211. {
  212. tzset();
  213. StringBuilder builder { max_size };
  214. int const format_len = strlen(format);
  215. for (int i = 0; i < format_len; ++i) {
  216. if (format[i] != '%') {
  217. builder.append(format[i]);
  218. } else {
  219. if (++i >= format_len)
  220. return 0;
  221. switch (format[i]) {
  222. case 'a':
  223. builder.append(short_day_names[tm->tm_wday]);
  224. break;
  225. case 'A':
  226. builder.append(long_day_names[tm->tm_wday]);
  227. break;
  228. case 'b':
  229. builder.append(short_month_names[tm->tm_mon]);
  230. break;
  231. case 'B':
  232. builder.append(long_month_names[tm->tm_mon]);
  233. break;
  234. case 'C':
  235. builder.appendff("{:02}", (tm->tm_year + 1900) / 100);
  236. break;
  237. case 'd':
  238. builder.appendff("{:02}", tm->tm_mday);
  239. break;
  240. case 'D':
  241. builder.appendff("{:02}/{:02}/{:02}", tm->tm_mon + 1, tm->tm_mday, (tm->tm_year + 1900) % 100);
  242. break;
  243. case 'e':
  244. builder.appendff("{:2}", tm->tm_mday);
  245. break;
  246. case 'h':
  247. builder.append(short_month_names[tm->tm_mon]);
  248. break;
  249. case 'H':
  250. builder.appendff("{:02}", tm->tm_hour);
  251. break;
  252. case 'I': {
  253. int display_hour = tm->tm_hour % 12;
  254. if (display_hour == 0)
  255. display_hour = 12;
  256. builder.appendff("{:02}", display_hour);
  257. break;
  258. }
  259. case 'j':
  260. builder.appendff("{:03}", tm->tm_yday + 1);
  261. break;
  262. case 'm':
  263. builder.appendff("{:02}", tm->tm_mon + 1);
  264. break;
  265. case 'M':
  266. builder.appendff("{:02}", tm->tm_min);
  267. break;
  268. case 'n':
  269. builder.append('\n');
  270. break;
  271. case 'p':
  272. builder.append(tm->tm_hour < 12 ? "AM"sv : "PM"sv);
  273. break;
  274. case 'r': {
  275. int display_hour = tm->tm_hour % 12;
  276. if (display_hour == 0)
  277. display_hour = 12;
  278. builder.appendff("{:02}:{:02}:{:02} {}", display_hour, tm->tm_min, tm->tm_sec, tm->tm_hour < 12 ? "AM" : "PM");
  279. break;
  280. }
  281. case 'R':
  282. builder.appendff("{:02}:{:02}", tm->tm_hour, tm->tm_min);
  283. break;
  284. case 'S':
  285. builder.appendff("{:02}", tm->tm_sec);
  286. break;
  287. case 't':
  288. builder.append('\t');
  289. break;
  290. case 'T':
  291. builder.appendff("{:02}:{:02}:{:02}", tm->tm_hour, tm->tm_min, tm->tm_sec);
  292. break;
  293. case 'u':
  294. builder.appendff("{}", tm->tm_wday ? tm->tm_wday : 7);
  295. break;
  296. case 'U': {
  297. int const wday_of_year_beginning = (tm->tm_wday + 6 * tm->tm_yday) % 7;
  298. int const week_number = (tm->tm_yday + wday_of_year_beginning) / 7;
  299. builder.appendff("{:02}", week_number);
  300. break;
  301. }
  302. case 'V': {
  303. int const wday_of_year_beginning = (tm->tm_wday + 6 + 6 * tm->tm_yday) % 7;
  304. int week_number = (tm->tm_yday + wday_of_year_beginning) / 7 + 1;
  305. if (wday_of_year_beginning > 3) {
  306. if (tm->tm_yday >= 7 - wday_of_year_beginning)
  307. --week_number;
  308. else {
  309. int const days_of_last_year = days_in_year(tm->tm_year + 1900 - 1);
  310. int const wday_of_last_year_beginning = (wday_of_year_beginning + 6 * days_of_last_year) % 7;
  311. week_number = (days_of_last_year + wday_of_last_year_beginning) / 7 + 1;
  312. if (wday_of_last_year_beginning > 3)
  313. --week_number;
  314. }
  315. }
  316. builder.appendff("{:02}", week_number);
  317. break;
  318. }
  319. case 'w':
  320. builder.appendff("{}", tm->tm_wday);
  321. break;
  322. case 'W': {
  323. int const wday_of_year_beginning = (tm->tm_wday + 6 + 6 * tm->tm_yday) % 7;
  324. int const week_number = (tm->tm_yday + wday_of_year_beginning) / 7;
  325. builder.appendff("{:02}", week_number);
  326. break;
  327. }
  328. case 'y':
  329. builder.appendff("{:02}", (tm->tm_year + 1900) % 100);
  330. break;
  331. case 'Y':
  332. builder.appendff("{}", tm->tm_year + 1900);
  333. break;
  334. case '%':
  335. builder.append('%');
  336. break;
  337. default:
  338. return 0;
  339. }
  340. }
  341. if (builder.length() + 1 > max_size)
  342. return 0;
  343. }
  344. auto str = builder.to_deprecated_string();
  345. bool fits = str.copy_characters_to_buffer(destination, max_size);
  346. return fits ? str.length() : 0;
  347. }
  348. void tzset()
  349. {
  350. __tzname = TimeZone::current_time_zone();
  351. auto set_default_values = []() {
  352. timezone = 0;
  353. altzone = 0;
  354. daylight = 0;
  355. __tzname = StringView { __utc, __builtin_strlen(__utc) };
  356. tzname[0] = const_cast<char*>(__utc);
  357. tzname[1] = const_cast<char*>(__utc);
  358. };
  359. if (auto offsets = TimeZone::get_named_time_zone_offsets(__tzname, AK::Time::now_realtime()); offsets.has_value()) {
  360. if (!offsets->at(0).name.copy_characters_to_buffer(__tzname_standard, TZNAME_MAX))
  361. return set_default_values();
  362. if (!offsets->at(1).name.copy_characters_to_buffer(__tzname_daylight, TZNAME_MAX))
  363. return set_default_values();
  364. // timezone and altzone are seconds west of UTC, i.e. the offsets are negated.
  365. timezone = -offsets->at(0).seconds;
  366. altzone = -offsets->at(1).seconds;
  367. daylight = timezone != altzone;
  368. tzname[0] = __tzname_standard;
  369. tzname[1] = __tzname_daylight;
  370. } else {
  371. set_default_values();
  372. }
  373. }
  374. clock_t clock()
  375. {
  376. struct tms tms;
  377. times(&tms);
  378. return tms.tms_utime + tms.tms_stime;
  379. }
  380. static Kernel::TimePage* get_kernel_time_page()
  381. {
  382. static Kernel::TimePage* s_kernel_time_page;
  383. // FIXME: Thread safety
  384. if (!s_kernel_time_page) {
  385. auto rc = syscall(SC_map_time_page);
  386. if ((int)rc < 0 && (int)rc > -EMAXERRNO) {
  387. errno = -(int)rc;
  388. return nullptr;
  389. }
  390. s_kernel_time_page = (Kernel::TimePage*)rc;
  391. }
  392. return s_kernel_time_page;
  393. }
  394. int clock_gettime(clockid_t clock_id, struct timespec* ts)
  395. {
  396. if (Kernel::time_page_supports(clock_id)) {
  397. if (!ts) {
  398. errno = EFAULT;
  399. return -1;
  400. }
  401. if (auto* kernel_time_page = get_kernel_time_page()) {
  402. u32 update_iteration;
  403. do {
  404. update_iteration = AK::atomic_load(&kernel_time_page->update1, AK::memory_order_acquire);
  405. *ts = kernel_time_page->clocks[clock_id];
  406. } while (update_iteration != AK::atomic_load(&kernel_time_page->update2, AK::memory_order_acquire));
  407. return 0;
  408. }
  409. }
  410. int rc = syscall(SC_clock_gettime, clock_id, ts);
  411. __RETURN_WITH_ERRNO(rc, rc, -1);
  412. }
  413. int clock_settime(clockid_t clock_id, struct timespec* ts)
  414. {
  415. int rc = syscall(SC_clock_settime, clock_id, ts);
  416. __RETURN_WITH_ERRNO(rc, rc, -1);
  417. }
  418. int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec* requested_sleep, struct timespec* remaining_sleep)
  419. {
  420. __pthread_maybe_cancel();
  421. Syscall::SC_clock_nanosleep_params params { clock_id, flags, requested_sleep, remaining_sleep };
  422. int rc = syscall(SC_clock_nanosleep, &params);
  423. __RETURN_WITH_ERRNO(rc, rc, -1);
  424. }
  425. int nanosleep(const struct timespec* requested_sleep, struct timespec* remaining_sleep)
  426. {
  427. return clock_nanosleep(CLOCK_REALTIME, 0, requested_sleep, remaining_sleep);
  428. }
  429. int clock_getres(clockid_t clock_id, struct timespec* result)
  430. {
  431. Syscall::SC_clock_getres_params params { clock_id, result };
  432. int rc = syscall(SC_clock_getres, &params);
  433. __RETURN_WITH_ERRNO(rc, rc, -1);
  434. }
  435. double difftime(time_t t1, time_t t0)
  436. {
  437. return (double)(t1 - t0);
  438. }
  439. }