Fix 32-bit overflow in mktime() when time_t is 64-bits long

Message ID a7fdafbf65c6d1612c5ded423378133d01061362.camel@op.pl
State New
Headers show
Series
  • Fix 32-bit overflow in mktime() when time_t is 64-bits long
Related show

Commit Message

Freddie Chopin May 15, 2018, 7:08 p.m.
Hello!

Currently when time_t is configured to be 64-bits long, mktime() will
fail for years above 2038. For example converting 01.01.2040 00:00:00
gives -2085978496 instead of the expected 2208988800. Patch which fixes
this behaviour is attached.

I'll try to post an improved version of mktime() in a few days.

Regards,
FCh

Comments

Corinna Vinschen May 29, 2018, 1:27 p.m. | #1
On May 15 21:08, Freddie Chopin wrote:
> Hello!

> 

> Currently when time_t is configured to be 64-bits long, mktime() will

> fail for years above 2038. For example converting 01.01.2040 00:00:00

> gives -2085978496 instead of the expected 2208988800. Patch which fixes

> this behaviour is attached.

> 

> I'll try to post an improved version of mktime() in a few days.

> 

> Regards,

> FCh


> From 08f891e37a850c1229d33460f0846c2cbcc08245 Mon Sep 17 00:00:00 2001

> From: Freddie Chopin <freddie.chopin@gmail.com>

> Date: Tue, 15 May 2018 20:58:08 +0200

> Subject: [PATCH] Fix 32-bit overflow in mktime() when time_t is 64-bits long

> 

> When converting number of days since epoch (32-bits) to seconds,

> calculations using 32-bit `long` overflow for years above 2038. Solve

> this by casting number of days to `time_t` just before final

> multiplication.

> 

> Signed-off-by: Freddie Chopin <freddie.chopin@gmail.com>


Pushed.


Thanks,
Corinna

-- 
Corinna Vinschen
Cygwin Maintainer
Red Hat

Patch

From 08f891e37a850c1229d33460f0846c2cbcc08245 Mon Sep 17 00:00:00 2001
From: Freddie Chopin <freddie.chopin@gmail.com>
Date: Tue, 15 May 2018 20:58:08 +0200
Subject: [PATCH] Fix 32-bit overflow in mktime() when time_t is 64-bits long

When converting number of days since epoch (32-bits) to seconds,
calculations using 32-bit `long` overflow for years above 2038. Solve
this by casting number of days to `time_t` just before final
multiplication.

Signed-off-by: Freddie Chopin <freddie.chopin@gmail.com>
---
 newlib/libc/time/mktime.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/newlib/libc/time/mktime.c b/newlib/libc/time/mktime.c
index 9bcef3268..02032599a 100644
--- a/newlib/libc/time/mktime.c
+++ b/newlib/libc/time/mktime.c
@@ -188,7 +188,7 @@  mktime (struct tm *tim_p)
     }
 
   /* compute total seconds */
-  tim += (days * _SEC_IN_DAY);
+  tim += (time_t)days * _SEC_IN_DAY;
 
   TZ_LOCK;
 
-- 
2.17.0