time.cpp 14 KB

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