time.cpp 15 KB

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