time.cpp 15 KB

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