time.cpp 14 KB

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