From db6f0897236cfe6a5e36f3ff5f107e97c0fff327 Mon Sep 17 00:00:00 2001 From: Abdallah Abdelhafeez <166307169+Abdallahs70@users.noreply.github.com> Date: Tue, 23 Apr 2024 14:45:51 +0200 Subject: [PATCH] libc/time: Fix `mktime()` wrong behavior when time can not be represented Part 7.23.2.3 requires mktime() function to return -1 in case of the calendar time cannot be represented. and if year is negative that's wrong representation as part 7.23.2.1 specify the year component to be, quoting, > int tm_year; // years since 1900 So it can only represent years after 1900 which can only be indicated by positive value. Signed-off-by: Abdallah Abdelhafeez --- newlib/libc/time/mktime.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/newlib/libc/time/mktime.c b/newlib/libc/time/mktime.c index de426dfeaa..0c1336012d 100644 --- a/newlib/libc/time/mktime.c +++ b/newlib/libc/time/mktime.c @@ -191,6 +191,10 @@ mktime_utc (struct tm *tim_p, long *days_p) /* validate structure */ validate_structure (tim_p); + /* check if year has valid value */ + if (tim_p->tm_year > 10000 || tim_p->tm_year < 0) + return (time_t) -1; + /* compute hours, minutes, seconds */ tim += tim_p->tm_sec + (tim_p->tm_min * SECSPERMIN) + (tim_p->tm_hour * SECSPERHOUR); @@ -204,9 +208,6 @@ mktime_utc (struct tm *tim_p, long *days_p) /* compute day of the year */ tim_p->tm_yday = days; - if (tim_p->tm_year > 10000 || tim_p->tm_year < -10000) - return (time_t) -1; - /* compute days in other years */ if ((year = tim_p->tm_year) > 70) {