8000 bpo-13312: Avoid int underflow in time year. (GH-8912) · python/cpython@c47acc2 · GitHub
[go: up one dir, main page]

Skip to content

Commit c47acc2

Browse files
bpo-13312: Avoid int underflow in time year. (GH-8912)
Avoids an integer underflow in the time module's year handling code. (cherry picked from commit 76be0ff) Co-authored-by: Gregory P. Smith <greg@krypto.org>
1 parent 2443766 commit c47acc2

File tree

3 files changed

+13
-6
lines changed

3 files changed

+13
-6
lines changed

Lib/test/test_time.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
# Max year is only limited by the size of C int.
2222
SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
2323
TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
24-
TIME_MINYEAR = -TIME_MAXYEAR - 1
24+
TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900
2525

2626
SEC_TO_US = 10 ** 6
2727
US_TO_NS = 10 ** 3
@@ -614,12 +614,11 @@ def test_negative(self):
614614
self.assertEqual(self.yearstr(-123456), '-123456')
615615
self.assertEqual(self.yearstr(-123456789), str(-123456789))
616616
self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
617-
self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
618-
# Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
619-
# Skip the value test, but check that no error is raised
620-
self.yearstr(TIME_MINYEAR)
621-
# self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
617+
self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
618+
# Modules/timemodule.c checks for underflow
622619
self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
620+
with self.assertRaises(OverflowError):
621+
self.yearstr(-TIME_MAXYEAR - 1)
623622

624623

625624
class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Avoids a possible integer underflow (undefined behavior) in the time
2+
module's year handling code when passed a very low negative year value.

Modules/timemodule.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,12 @@ gettmarg(PyObject *args, struct tm *p)
433433
&p->tm_hour, &p->tm_min, &p->tm_sec,
434434
&p->tm_wday, &p->tm_yday, &p->tm_isdst))
435435
return 0;
436+
437+
if (y < INT_MIN + 1900) {
438+
PyErr_SetString(PyExc_OverflowError, "year out of range");
439+
return 0;
440+
}
441+
436442
p->tm_year = y - 1900;
437443
p->tm_mon--;
438444
p->tm_wday = (p->tm_wday + 1) % 7;

0 commit comments

Comments
 (0)
0