time.cpp 13 KB

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