source: mainline/uspace/lib/posix/time.c@ 8219eb9

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

libc: move asctime() from libposix to libc

  • Property mode set to 100644
File size: 14.1 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 * @return Normalized broken-down time in local timezone, NULL on overflow.
358 */
359struct tm *posix_localtime(const time_t *timer)
360{
361 static struct tm result;
362 return posix_localtime_r(timer, &result);
363}
364
365/**
366 * Converts a time value to a broken-down local time.
367 *
368 * @param timer Time to convert.
369 * @param result Structure to store the result to.
370 * @return Value of result on success, NULL on overflow.
371 */
372struct tm *posix_localtime_r(const time_t *restrict timer,
373 struct tm *restrict result)
374{
375 // TODO: deal with timezone
376 // currently assumes system and all times are in GMT
377 return posix_gmtime_r(timer, result);
378}
379
380/**
381 * Converts broken-down time to a string in format
382 * "Sun Jan 1 00:00:00 1970\n". (Obsolete)
383 *
384 * @param timeptr Broken-down time structure.
385 * @param buf Buffer to store string to, must be at least ASCTIME_BUF_LEN
386 * bytes long.
387 * @return Value of buf.
388 */
389char *posix_asctime_r(const struct tm *restrict timeptr,
390 char *restrict buf)
391{
392 assert(timeptr != NULL);
393 assert(buf != NULL);
394
395 static const char *wday[] = {
396 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
397 };
398 static const char *mon[] = {
399 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
400 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
401 };
402
403 snprintf(buf, ASCTIME_BUF_LEN, "%s %s %2d %02d:%02d:%02d %d\n",
404 wday[timeptr->tm_wday],
405 mon[timeptr->tm_mon],
406 timeptr->tm_mday, timeptr->tm_hour,
407 timeptr->tm_min, timeptr->tm_sec,
408 1900 + timeptr->tm_year);
409
410 return buf;
411}
412
413/**
414 * Equivalent to asctime(localtime(clock)).
415 *
416 * @param timer Time to convert.
417 * @return Pointer to a statically allocated string holding the date.
418 */
419char *posix_ctime(const time_t *timer)
420{
421 struct tm *loctime = posix_localtime(timer);
422 if (loctime == NULL) {
423 return NULL;
424 }
425 return asctime(loctime);
426}
427
428/**
429 * Reentrant variant of ctime().
430 *
431 * @param timer Time to convert.
432 * @param buf Buffer to store string to. Must be at least ASCTIME_BUF_LEN
433 * bytes long.
434 * @return Pointer to buf on success, NULL on falure.
435 */
436char *posix_ctime_r(const time_t *timer, char *buf)
437{
438 struct tm loctime;
439 if (posix_localtime_r(timer, &loctime) == NULL) {
440 return NULL;
441 }
442 return posix_asctime_r(&loctime, buf);
443}
444
445/**
446 * Get clock resolution. Only CLOCK_REALTIME is supported.
447 *
448 * @param clock_id Clock ID.
449 * @param res Pointer to the variable where the resolution is to be written.
450 * @return 0 on success, -1 with errno set on failure.
451 */
452int posix_clock_getres(posix_clockid_t clock_id, struct posix_timespec *res)
453{
454 assert(res != NULL);
455
456 switch (clock_id) {
457 case CLOCK_REALTIME:
458 res->tv_sec = 0;
459 res->tv_nsec = 1000; /* Microsecond resolution. */
460 return 0;
461 default:
462 errno = EINVAL;
463 return -1;
464 }
465}
466
467/**
468 * Get time. Only CLOCK_REALTIME is supported.
469 *
470 * @param clock_id ID of the clock to query.
471 * @param tp Pointer to the variable where the time is to be written.
472 * @return 0 on success, -1 with errno on failure.
473 */
474int posix_clock_gettime(posix_clockid_t clock_id, struct posix_timespec *tp)
475{
476 assert(tp != NULL);
477
478 switch (clock_id) {
479 case CLOCK_REALTIME:
480 ;
481 struct timeval tv;
482 gettimeofday(&tv, NULL);
483 tp->tv_sec = tv.tv_sec;
484 tp->tv_nsec = tv.tv_usec * 1000;
485 return 0;
486 default:
487 errno = EINVAL;
488 return -1;
489 }
490}
491
492/**
493 * Set time on a specified clock. As HelenOS doesn't support this yet,
494 * this function always fails.
495 *
496 * @param clock_id ID of the clock to set.
497 * @param tp Time to set.
498 * @return 0 on success, -1 with errno on failure.
499 */
500int posix_clock_settime(posix_clockid_t clock_id,
501 const struct posix_timespec *tp)
502{
503 assert(tp != NULL);
504
505 switch (clock_id) {
506 case CLOCK_REALTIME:
507 // TODO: setting clock
508 // FIXME: HelenOS doesn't actually support hardware
509 // clock yet
510 errno = EPERM;
511 return -1;
512 default:
513 errno = EINVAL;
514 return -1;
515 }
516}
517
518/**
519 * Sleep on a specified clock.
520 *
521 * @param clock_id ID of the clock to sleep on (only CLOCK_REALTIME supported).
522 * @param flags Flags (none supported).
523 * @param rqtp Sleep time.
524 * @param rmtp Remaining time is written here if sleep is interrupted.
525 * @return 0 on success, -1 with errno set on failure.
526 */
527int posix_clock_nanosleep(posix_clockid_t clock_id, int flags,
528 const struct posix_timespec *rqtp, struct posix_timespec *rmtp)
529{
530 assert(rqtp != NULL);
531 assert(rmtp != NULL);
532
533 switch (clock_id) {
534 case CLOCK_REALTIME:
535 // TODO: interruptible sleep
536 if (rqtp->tv_sec != 0) {
537 sleep(rqtp->tv_sec);
538 }
539 if (rqtp->tv_nsec != 0) {
540 usleep(rqtp->tv_nsec / 1000);
541 }
542 return 0;
543 default:
544 errno = EINVAL;
545 return -1;
546 }
547}
548
549/**
550 * Get CPU time used since the process invocation.
551 *
552 * @return Consumed CPU cycles by this process or -1 if not available.
553 */
554posix_clock_t posix_clock(void)
555{
556 posix_clock_t total_cycles = -1;
557 stats_task_t *task_stats = stats_get_task(task_get_id());
558 if (task_stats) {
559 total_cycles = (posix_clock_t) (task_stats->kcycles +
560 task_stats->ucycles);
561 free(task_stats);
562 task_stats = 0;
563 }
564
565 return total_cycles;
566}
567
568/** @}
569 */
Note: See TracBrowser for help on using the repository browser.