time.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. time_to_tm(tm, *t - timezone);
  140. return tm;
  141. }
  142. time_t timegm(struct tm* tm)
  143. {
  144. return tm_to_time(tm, 0);
  145. }
  146. struct tm* gmtime(const time_t* t)
  147. {
  148. static struct tm tm_buf;
  149. return gmtime_r(t, &tm_buf);
  150. }
  151. struct tm* gmtime_r(const time_t* t, struct tm* tm)
  152. {
  153. if (!t)
  154. return nullptr;
  155. time_to_tm(tm, *t);
  156. return tm;
  157. }
  158. char* asctime(const struct tm* tm)
  159. {
  160. static char buffer[69];
  161. return asctime_r(tm, buffer);
  162. }
  163. char* asctime_r(const struct tm* tm, char* buffer)
  164. {
  165. // Spec states buffer must be at least 26 bytes.
  166. constexpr size_t assumed_len = 26;
  167. size_t filled_size = strftime(buffer, assumed_len, "%a %b %e %T %Y\n", tm);
  168. // Verify that the buffer was large enough.
  169. VERIFY(filled_size != 0);
  170. return buffer;
  171. }
  172. // FIXME: Some formats are not supported.
  173. size_t strftime(char* destination, size_t max_size, const char* format, const struct tm* tm)
  174. {
  175. tzset();
  176. const char wday_short_names[7][4] = {
  177. "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
  178. };
  179. const char wday_long_names[7][10] = {
  180. "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
  181. };
  182. const char mon_short_names[12][4] = {
  183. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  185. };
  186. const char mon_long_names[12][10] = {
  187. "January", "February", "March", "April", "May", "June",
  188. "July", "August", "September", "October", "November", "December"
  189. };
  190. StringBuilder builder { max_size };
  191. const int format_len = strlen(format);
  192. for (int i = 0; i < format_len; ++i) {
  193. if (format[i] != '%') {
  194. builder.append(format[i]);
  195. } else {
  196. if (++i >= format_len)
  197. return 0;
  198. switch (format[i]) {
  199. case 'a':
  200. builder.append(wday_short_names[tm->tm_wday]);
  201. break;
  202. case 'A':
  203. builder.append(wday_long_names[tm->tm_wday]);
  204. break;
  205. case 'b':
  206. builder.append(mon_short_names[tm->tm_mon]);
  207. break;
  208. case 'B':
  209. builder.append(mon_long_names[tm->tm_mon]);
  210. break;
  211. case 'C':
  212. builder.appendff("{:02}", (tm->tm_year + 1900) / 100);
  213. break;
  214. case 'd':
  215. builder.appendff("{:02}", tm->tm_mday);
  216. break;
  217. case 'D':
  218. builder.appendff("{:02}/{:02}/{:02}", tm->tm_mon + 1, tm->tm_mday, (tm->tm_year + 1900) % 100);
  219. break;
  220. case 'e':
  221. builder.appendff("{:2}", tm->tm_mday);
  222. break;
  223. case 'h':
  224. builder.append(mon_short_names[tm->tm_mon]);
  225. break;
  226. case 'H':
  227. builder.appendff("{:02}", tm->tm_hour);
  228. break;
  229. case 'I':
  230. builder.appendff("{:02}", tm->tm_hour % 12);
  231. break;
  232. case 'j':
  233. builder.appendff("{:03}", tm->tm_yday + 1);
  234. break;
  235. case 'm':
  236. builder.appendff("{:02}", tm->tm_mon + 1);
  237. break;
  238. case 'M':
  239. builder.appendff("{:02}", tm->tm_min);
  240. break;
  241. case 'n':
  242. builder.append('\n');
  243. break;
  244. case 'p':
  245. builder.append(tm->tm_hour < 12 ? "a.m." : "p.m.");
  246. break;
  247. case 'r':
  248. builder.appendff("{:02}:{:02}:{:02} {}", tm->tm_hour % 12, tm->tm_min, tm->tm_sec, tm->tm_hour < 12 ? "a.m." : "p.m.");
  249. break;
  250. case 'R':
  251. builder.appendff("{:02}:{:02}", tm->tm_hour, tm->tm_min);
  252. break;
  253. case 'S':
  254. builder.appendff("{:02}", tm->tm_sec);
  255. break;
  256. case 't':
  257. builder.append('\t');
  258. break;
  259. case 'T':
  260. builder.appendff("{:02}:{:02}:{:02}", tm->tm_hour, tm->tm_min, tm->tm_sec);
  261. break;
  262. case 'u':
  263. builder.appendff("{}", tm->tm_wday ? tm->tm_wday : 7);
  264. break;
  265. case 'U': {
  266. const int wday_of_year_beginning = (tm->tm_wday + 6 * tm->tm_yday) % 7;
  267. const int week_number = (tm->tm_yday + wday_of_year_beginning) / 7;
  268. builder.appendff("{:02}", week_number);
  269. break;
  270. }
  271. case 'V': {
  272. const int wday_of_year_beginning = (tm->tm_wday + 6 + 6 * tm->tm_yday) % 7;
  273. int week_number = (tm->tm_yday + wday_of_year_beginning) / 7 + 1;
  274. if (wday_of_year_beginning > 3) {
  275. if (tm->tm_yday >= 7 - wday_of_year_beginning)
  276. --week_number;
  277. else {
  278. const int days_of_last_year = days_in_year(tm->tm_year + 1900 - 1);
  279. const int wday_of_last_year_beginning = (wday_of_year_beginning + 6 * days_of_last_year) % 7;
  280. week_number = (days_of_last_year + wday_of_last_year_beginning) / 7 + 1;
  281. if (wday_of_last_year_beginning > 3)
  282. --week_number;
  283. }
  284. }
  285. builder.appendff("{:02}", week_number);
  286. break;
  287. }
  288. case 'w':
  289. builder.appendff("{}", tm->tm_wday);
  290. break;
  291. case 'W': {
  292. const int wday_of_year_beginning = (tm->tm_wday + 6 + 6 * tm->tm_yday) % 7;
  293. const int week_number = (tm->tm_yday + wday_of_year_beginning) / 7;
  294. builder.appendff("{:02}", week_number);
  295. break;
  296. }
  297. case 'y':
  298. builder.appendff("{:02}", (tm->tm_year + 1900) % 100);
  299. break;
  300. case 'Y':
  301. builder.appendff("{}", tm->tm_year + 1900);
  302. break;
  303. case '%':
  304. builder.append('%');
  305. break;
  306. default:
  307. return 0;
  308. }
  309. }
  310. if (builder.length() + 1 > max_size)
  311. return 0;
  312. }
  313. auto str = builder.build();
  314. bool fits = str.copy_characters_to_buffer(destination, max_size);
  315. return fits ? str.length() : 0;
  316. }
  317. static char __tzname_standard[TZNAME_MAX];
  318. static char __tzname_daylight[TZNAME_MAX];
  319. constexpr const char* __utc = "UTC";
  320. long timezone = 0;
  321. long altzone = 0;
  322. char* tzname[2] = { const_cast<char*>(__utc), const_cast<char*>(__utc) };
  323. int daylight = 0;
  324. void tzset()
  325. {
  326. // FIXME: Actually parse the TZ environment variable, described here:
  327. // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08
  328. StringView time_zone;
  329. if (char* tz = getenv("TZ"); tz != nullptr)
  330. time_zone = tz;
  331. else
  332. time_zone = TimeZone::current_time_zone();
  333. auto set_default_values = []() {
  334. timezone = 0;
  335. altzone = 0;
  336. daylight = 0;
  337. tzname[0] = const_cast<char*>(__utc);
  338. tzname[1] = const_cast<char*>(__utc);
  339. };
  340. if (auto offsets = TimeZone::get_named_time_zone_offsets(time_zone, AK::Time::now_realtime()); offsets.has_value()) {
  341. if (!offsets->at(0).name.copy_characters_to_buffer(__tzname_standard, TZNAME_MAX))
  342. return set_default_values();
  343. if (!offsets->at(1).name.copy_characters_to_buffer(__tzname_daylight, TZNAME_MAX))
  344. return set_default_values();
  345. // timezone and altzone are seconds west of UTC, i.e. the offsets are negated.
  346. timezone = -offsets->at(0).seconds;
  347. altzone = -offsets->at(1).seconds;
  348. daylight = timezone != altzone;
  349. tzname[0] = __tzname_standard;
  350. tzname[1] = __tzname_daylight;
  351. } else {
  352. set_default_values();
  353. }
  354. }
  355. clock_t clock()
  356. {
  357. struct tms tms;
  358. times(&tms);
  359. return tms.tms_utime + tms.tms_stime;
  360. }
  361. static Kernel::TimePage* get_kernel_time_page()
  362. {
  363. static Kernel::TimePage* s_kernel_time_page;
  364. // FIXME: Thread safety
  365. if (!s_kernel_time_page) {
  366. auto rc = syscall(SC_map_time_page);
  367. if ((int)rc < 0 && (int)rc > -EMAXERRNO) {
  368. errno = -(int)rc;
  369. return nullptr;
  370. }
  371. s_kernel_time_page = (Kernel::TimePage*)rc;
  372. }
  373. return s_kernel_time_page;
  374. }
  375. int clock_gettime(clockid_t clock_id, struct timespec* ts)
  376. {
  377. if (Kernel::time_page_supports(clock_id)) {
  378. if (!ts) {
  379. errno = EFAULT;
  380. return -1;
  381. }
  382. if (auto* kernel_time_page = get_kernel_time_page()) {
  383. u32 update_iteration;
  384. do {
  385. update_iteration = AK::atomic_load(&kernel_time_page->update1, AK::memory_order_acquire);
  386. *ts = kernel_time_page->clocks[clock_id];
  387. } while (update_iteration != AK::atomic_load(&kernel_time_page->update2, AK::memory_order_acquire));
  388. return 0;
  389. }
  390. }
  391. int rc = syscall(SC_clock_gettime, clock_id, ts);
  392. __RETURN_WITH_ERRNO(rc, rc, -1);
  393. }
  394. int clock_settime(clockid_t clock_id, struct timespec* ts)
  395. {
  396. int rc = syscall(SC_clock_settime, clock_id, ts);
  397. __RETURN_WITH_ERRNO(rc, rc, -1);
  398. }
  399. int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec* requested_sleep, struct timespec* remaining_sleep)
  400. {
  401. Syscall::SC_clock_nanosleep_params params { clock_id, flags, requested_sleep, remaining_sleep };
  402. int rc = syscall(SC_clock_nanosleep, &params);
  403. __RETURN_WITH_ERRNO(rc, rc, -1);
  404. }
  405. int nanosleep(const struct timespec* requested_sleep, struct timespec* remaining_sleep)
  406. {
  407. return clock_nanosleep(CLOCK_REALTIME, 0, requested_sleep, remaining_sleep);
  408. }
  409. int clock_getres(clockid_t, struct timespec*)
  410. {
  411. dbgln("FIXME: Implement clock_getres()");
  412. auto rc = -ENOSYS;
  413. __RETURN_WITH_ERRNO(rc, rc, -1);
  414. }
  415. double difftime(time_t t1, time_t t0)
  416. {
  417. return (double)(t1 - t0);
  418. }
  419. }