time.cpp 12 KB

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