time.cpp 13 KB

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