Bug in UTC -> localtime conversion after 2038

Richard Damon Richard@Damon-Family.org
Wed Nov 4 12:59:26 GMT 2020


On 11/4/20 6:36 AM, Udo de Boer wrote:
> Hi,
>
> UTC time to local timezone conversion did not work for years after
> 2038. Daylight saving in the timezone was not recognized. Tested on
> 32bit xtensa architecture with GCC 8.4 (esp32) and with 64bit time_t
> enabled.
>
> The struct tm is filled correct. So year, day etc are all filled with
> the correct values. But the tm.tm_isdst is 0 and no daylight saving is
> applied.
>
> It was caused by the following calculation in time/tzcalc_limits.c at
> line 68
>
>        /* store the change-over time in GMT form by adding offset */
>        tz->__tzrule[i].change = days * SECSPERDAY +
>        tz->__tzrule[i].s + tz->__tzrule[i].offset;
>
> Here tz->__tzrule[i].change is a time_t (64bit). For some reason the
> compiler does the calculation in 32 bit. All variables used in the
> calculation are 32bit.
>
> I solved this locally by changing the lines to.
>
>        /* store the change-over time in GMT form by adding offset */
>        tz->__tzrule[i].change = (time_t)days * SECSPERDAY +
>        tz->__tzrule[i].s + tz->__tzrule[i].offset;
>
> Adding the cast time_t should not cause a problem when time_t is still
> 32bit.
>
> I don't know if this is correct solution. I also only needed this
> function. So more bugs like this could be hidden away in the time code.
>
C arithmetic is defined based on the size of the operands, not the
destination, so math on 32 bit quantities is done at 32 bits (unless int
is bigger, as int is the smallest size used).

The casting of one of the operands to the bigger size is the right solution.

-- 
Richard Damon



More information about the Newlib mailing list