source: mainline/uspace/lib/posix/time.c@ 56b308e

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 56b308e was 56b308e, checked in by Maurizio Lombardi <m.lombardi85@…>, 13 years ago

libc: move ctime() from libposix to libc

  • Property mode set to 100644
File size: 13.5 KB
Line 
1/*
2 * Copyright (c) 2011 Petr Koupy
3 * Copyright (c) 2011 Jiri Zarevucky
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30/** @addtogroup libposix
31 * @{
32 */
33/** @file Time measurement support.
34 */
35
36#define LIBPOSIX_INTERNAL
37
38/* Must be first. */
39#include "stdbool.h"
40
41#include "internal/common.h"
42#include "time.h"
43
44#include "ctype.h"
45#include "errno.h"
46#include "signal.h"
47
48#include "libc/malloc.h"
49#include "libc/task.h"
50#include "libc/stats.h"
51#include "libc/sys/time.h"
52
53// TODO: test everything in this file
54
55/* In some places in this file, phrase "normalized broken-down time" is used.
56 * This means time broken down to components (year, month, day, hour, min, sec),
57 * in which every component is in its proper bounds. Non-normalized time could
58 * e.g. be 2011-54-5 29:13:-5, which would semantically mean start of year 2011
59 * + 53 months + 4 days + 29 hours + 13 minutes - 5 seconds.
60 */
61
62
63
64/* Helper functions ***********************************************************/
65
66#define HOURS_PER_DAY (24)
67#define MINS_PER_HOUR (60)
68#define SECS_PER_MIN (60)
69#define MINS_PER_DAY (MINS_PER_HOUR * HOURS_PER_DAY)
70#define SECS_PER_HOUR (SECS_PER_MIN * MINS_PER_HOUR)
71#define SECS_PER_DAY (SECS_PER_HOUR * HOURS_PER_DAY)
72
73/**
74 * Checks whether the year is a leap year.
75 *
76 * @param year Year since 1900 (e.g. for 1970, the value is 70).
77 * @return true if year is a leap year, false otherwise
78 */
79static bool _is_leap_year(time_t year)
80{
81 year += 1900;
82
83 if (year % 400 == 0)
84 return true;
85 if (year % 100 == 0)
86 return false;
87 if (year % 4 == 0)
88 return true;
89 return false;
90}
91
92/**
93 * Returns how many days there are in the given month of the given year.
94 * Note that year is only taken into account if month is February.
95 *
96 * @param year Year since 1900 (can be negative).
97 * @param mon Month of the year. 0 for January, 11 for December.
98 * @return Number of days in the specified month.
99 */
100static int _days_in_month(time_t year, time_t mon)
101{
102 assert(mon >= 0 && mon <= 11);
103
104 static int month_days[] =
105 { 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
106
107 if (mon == 1) {
108 year += 1900;
109 /* february */
110 return _is_leap_year(year) ? 29 : 28;
111 } else {
112 return month_days[mon];
113 }
114}
115
116/**
117 * For specified year, month and day of month, returns which day of that year
118 * it is.
119 *
120 * For example, given date 2011-01-03, the corresponding expression is:
121 * _day_of_year(111, 0, 3) == 2
122 *
123 * @param year Year (year 1900 = 0, can be negative).
124 * @param mon Month (January = 0).
125 * @param mday Day of month (First day is 1).
126 * @return Day of year (First day is 0).
127 */
128static int _day_of_year(time_t year, time_t mon, time_t mday)
129{
130 static int mdays[] =
131 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
132 static int leap_mdays[] =
133 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
134
135 return (_is_leap_year(year) ? leap_mdays[mon] : mdays[mon]) + mday - 1;
136}
137
138/**
139 * Integer division that rounds to negative infinity.
140 * Used by some functions in this file.
141 *
142 * @param op1 Dividend.
143 * @param op2 Divisor.
144 * @return Rounded quotient.
145 */
146static time_t _floor_div(time_t op1, time_t op2)
147{
148 if (op1 >= 0 || op1 % op2 == 0) {
149 return op1 / op2;
150 } else {
151 return op1 / op2 - 1;
152 }
153}
154
155/**
156 * Modulo that rounds to negative infinity.
157 * Used by some functions in this file.
158 *
159 * @param op1 Dividend.
160 * @param op2 Divisor.
161 * @return Remainder.
162 */
163static time_t _floor_mod(time_t op1, time_t op2)
164{
165 int div = _floor_div(op1, op2);
166
167 /* (a / b) * b + a % b == a */
168 /* thus, a % b == a - (a / b) * b */
169
170 int result = op1 - div * op2;
171
172 /* Some paranoid checking to ensure I didn't make a mistake here. */
173 assert(result >= 0);
174 assert(result < op2);
175 assert(div * op2 + result == op1);
176
177 return result;
178}
179
180/**
181 * Number of days since the Epoch.
182 * Epoch is 1970-01-01, which is also equal to day 0.
183 *
184 * @param year Year (year 1900 = 0, may be negative).
185 * @param mon Month (January = 0).
186 * @param mday Day of month (first day = 1).
187 * @return Number of days since the Epoch.
188 */
189static time_t _days_since_epoch(time_t year, time_t mon, time_t mday)
190{
191 return (year - 70) * 365 + _floor_div(year - 69, 4) -
192 _floor_div(year - 1, 100) + _floor_div(year + 299, 400) +
193 _day_of_year(year, mon, mday);
194}
195
196/**
197 * Which day of week the specified date is.
198 *
199 * @param year Year (year 1900 = 0).
200 * @param mon Month (January = 0).
201 * @param mday Day of month (first = 1).
202 * @return Day of week (Sunday = 0).
203 */
204static int _day_of_week(time_t year, time_t mon, time_t mday)
205{
206 /* 1970-01-01 is Thursday */
207 return _floor_mod((_days_since_epoch(year, mon, mday) + 4), 7);
208}
209
210/**
211 * Normalizes the broken-down time and optionally adds specified amount of
212 * seconds.
213 *
214 * @param tm Broken-down time to normalize.
215 * @param sec_add Seconds to add.
216 * @return 0 on success, -1 on overflow
217 */
218static int _normalize_time(struct tm *tm, time_t sec_add)
219{
220 // TODO: DST correction
221
222 /* Set initial values. */
223 time_t sec = tm->tm_sec + sec_add;
224 time_t min = tm->tm_min;
225 time_t hour = tm->tm_hour;
226 time_t day = tm->tm_mday - 1;
227 time_t mon = tm->tm_mon;
228 time_t year = tm->tm_year;
229
230 /* Adjust time. */
231 min += _floor_div(sec, SECS_PER_MIN);
232 sec = _floor_mod(sec, SECS_PER_MIN);
233 hour += _floor_div(min, MINS_PER_HOUR);
234 min = _floor_mod(min, MINS_PER_HOUR);
235 day += _floor_div(hour, HOURS_PER_DAY);
236 hour = _floor_mod(hour, HOURS_PER_DAY);
237
238 /* Adjust month. */
239 year += _floor_div(mon, 12);
240 mon = _floor_mod(mon, 12);
241
242 /* Now the difficult part - days of month. */
243
244 /* First, deal with whole cycles of 400 years = 146097 days. */
245 year += _floor_div(day, 146097) * 400;
246 day = _floor_mod(day, 146097);
247
248 /* Then, go in one year steps. */
249 if (mon <= 1) {
250 /* January and February. */
251 while (day > 365) {
252 day -= _is_leap_year(year) ? 366 : 365;
253 year++;
254 }
255 } else {
256 /* Rest of the year. */
257 while (day > 365) {
258 day -= _is_leap_year(year + 1) ? 366 : 365;
259 year++;
260 }
261 }
262
263 /* Finally, finish it off month per month. */
264 while (day >= _days_in_month(year, mon)) {
265 day -= _days_in_month(year, mon);
266 mon++;
267 if (mon >= 12) {
268 mon -= 12;
269 year++;
270 }
271 }
272
273 /* Calculate the remaining two fields. */
274 tm->tm_yday = _day_of_year(year, mon, day + 1);
275 tm->tm_wday = _day_of_week(year, mon, day + 1);
276
277 /* And put the values back to the struct. */
278 tm->tm_sec = (int) sec;
279 tm->tm_min = (int) min;
280 tm->tm_hour = (int) hour;
281 tm->tm_mday = (int) day + 1;
282 tm->tm_mon = (int) mon;
283
284 /* Casts to work around libc brain-damage. */
285 if (year > ((int)INT_MAX) || year < ((int)INT_MIN)) {
286 tm->tm_year = (year < 0) ? ((int)INT_MIN) : ((int)INT_MAX);
287 return -1;
288 }
289
290 tm->tm_year = (int) year;
291 return 0;
292}
293
294/******************************************************************************/
295
296int posix_daylight;
297long posix_timezone;
298char *posix_tzname[2];
299
300/**
301 * Set timezone conversion information.
302 */
303void posix_tzset(void)
304{
305 // TODO: read environment
306 posix_tzname[0] = (char *) "GMT";
307 posix_tzname[1] = (char *) "GMT";
308 posix_daylight = 0;
309 posix_timezone = 0;
310}
311
312/**
313 * Calculate the difference between two times, in seconds.
314 *
315 * @param time1 First time.
316 * @param time0 Second time.
317 * @return Time in seconds.
318 */
319double posix_difftime(time_t time1, time_t time0)
320{
321 return (double) (time1 - time0);
322}
323
324/**
325 * Converts a time value to a broken-down UTC time.
326 *
327 * @param timer Time to convert.
328 * @param result Structure to store the result to.
329 * @return Value of result on success, NULL on overflow.
330 */
331struct tm *posix_gmtime_r(const time_t *restrict timer,
332 struct tm *restrict result)
333{
334 assert(timer != NULL);
335 assert(result != NULL);
336
337 /* Set result to epoch. */
338 result->tm_sec = 0;
339 result->tm_min = 0;
340 result->tm_hour = 0;
341 result->tm_mday = 1;
342 result->tm_mon = 0;
343 result->tm_year = 70; /* 1970 */
344
345 if (_normalize_time(result, *timer) == -1) {
346 errno = EOVERFLOW;
347 return NULL;
348 }
349
350 return result;
351}
352
353/**
354 * Converts a time value to a broken-down local time.
355 *
356 * @param timer Time to convert.
357 * @param result Structure to store the result to.
358 * @return Value of result on success, NULL on overflow.
359 */
360struct tm *posix_localtime_r(const time_t *restrict timer,
361 struct tm *restrict result)
362{
363 // TODO: deal with timezone
364 // currently assumes system and all times are in GMT
365 return posix_gmtime_r(timer, result);
366}
367
368/**
369 * Converts broken-down time to a string in format
370 * "Sun Jan 1 00:00:00 1970\n". (Obsolete)
371 *
372 * @param timeptr Broken-down time structure.
373 * @param buf Buffer to store string to, must be at least ASCTIME_BUF_LEN
374 * bytes long.
375 * @return Value of buf.
376 */
377char *posix_asctime_r(const struct tm *restrict timeptr,
378 char *restrict buf)
379{
380 assert(timeptr != NULL);
381 assert(buf != NULL);
382
383 static const char *wday[] = {
384 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
385 };
386 static const char *mon[] = {
387 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
388 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
389 };
390
391 snprintf(buf, ASCTIME_BUF_LEN, "%s %s %2d %02d:%02d:%02d %d\n",
392 wday[timeptr->tm_wday],
393 mon[timeptr->tm_mon],
394 timeptr->tm_mday, timeptr->tm_hour,
395 timeptr->tm_min, timeptr->tm_sec,
396 1900 + timeptr->tm_year);
397
398 return buf;
399}
400
401/**
402 * Reentrant variant of ctime().
403 *
404 * @param timer Time to convert.
405 * @param buf Buffer to store string to. Must be at least ASCTIME_BUF_LEN
406 * bytes long.
407 * @return Pointer to buf on success, NULL on falure.
408 */
409char *posix_ctime_r(const time_t *timer, char *buf)
410{
411 struct tm loctime;
412 if (posix_localtime_r(timer, &loctime) == NULL) {
413 return NULL;
414 }
415 return posix_asctime_r(&loctime, buf);
416}
417
418/**
419 * Get clock resolution. Only CLOCK_REALTIME is supported.
420 *
421 * @param clock_id Clock ID.
422 * @param res Pointer to the variable where the resolution is to be written.
423 * @return 0 on success, -1 with errno set on failure.
424 */
425int posix_clock_getres(posix_clockid_t clock_id, struct posix_timespec *res)
426{
427 assert(res != NULL);
428
429 switch (clock_id) {
430 case CLOCK_REALTIME:
431 res->tv_sec = 0;
432 res->tv_nsec = 1000; /* Microsecond resolution. */
433 return 0;
434 default:
435 errno = EINVAL;
436 return -1;
437 }
438}
439
440/**
441 * Get time. Only CLOCK_REALTIME is supported.
442 *
443 * @param clock_id ID of the clock to query.
444 * @param tp Pointer to the variable where the time is to be written.
445 * @return 0 on success, -1 with errno on failure.
446 */
447int posix_clock_gettime(posix_clockid_t clock_id, struct posix_timespec *tp)
448{
449 assert(tp != NULL);
450
451 switch (clock_id) {
452 case CLOCK_REALTIME:
453 ;
454 struct timeval tv;
455 gettimeofday(&tv, NULL);
456 tp->tv_sec = tv.tv_sec;
457 tp->tv_nsec = tv.tv_usec * 1000;
458 return 0;
459 default:
460 errno = EINVAL;
461 return -1;
462 }
463}
464
465/**
466 * Set time on a specified clock. As HelenOS doesn't support this yet,
467 * this function always fails.
468 *
469 * @param clock_id ID of the clock to set.
470 * @param tp Time to set.
471 * @return 0 on success, -1 with errno on failure.
472 */
473int posix_clock_settime(posix_clockid_t clock_id,
474 const struct posix_timespec *tp)
475{
476 assert(tp != NULL);
477
478 switch (clock_id) {
479 case CLOCK_REALTIME:
480 // TODO: setting clock
481 // FIXME: HelenOS doesn't actually support hardware
482 // clock yet
483 errno = EPERM;
484 return -1;
485 default:
486 errno = EINVAL;
487 return -1;
488 }
489}
490
491/**
492 * Sleep on a specified clock.
493 *
494 * @param clock_id ID of the clock to sleep on (only CLOCK_REALTIME supported).
495 * @param flags Flags (none supported).
496 * @param rqtp Sleep time.
497 * @param rmtp Remaining time is written here if sleep is interrupted.
498 * @return 0 on success, -1 with errno set on failure.
499 */
500int posix_clock_nanosleep(posix_clockid_t clock_id, int flags,
501 const struct posix_timespec *rqtp, struct posix_timespec *rmtp)
502{
503 assert(rqtp != NULL);
504 assert(rmtp != NULL);
505
506 switch (clock_id) {
507 case CLOCK_REALTIME:
508 // TODO: interruptible sleep
509 if (rqtp->tv_sec != 0) {
510 sleep(rqtp->tv_sec);
511 }
512 if (rqtp->tv_nsec != 0) {
513 usleep(rqtp->tv_nsec / 1000);
514 }
515 return 0;
516 default:
517 errno = EINVAL;
518 return -1;
519 }
520}
521
522/**
523 * Get CPU time used since the process invocation.
524 *
525 * @return Consumed CPU cycles by this process or -1 if not available.
526 */
527posix_clock_t posix_clock(void)
528{
529 posix_clock_t total_cycles = -1;
530 stats_task_t *task_stats = stats_get_task(task_get_id());
531 if (task_stats) {
532 total_cycles = (posix_clock_t) (task_stats->kcycles +
533 task_stats->ucycles);
534 free(task_stats);
535 task_stats = 0;
536 }
537
538 return total_cycles;
539}
540
541/** @}
542 */
Note: See TracBrowser for help on using the repository browser.