bpo-13312: Avoid int underflow in time year. (GH-8912) · python/cpython@c47acc2 (original) (raw)

3 files changed

lines changed

Original file line number Diff line number Diff line change
@@ -21,7 +21,7 @@
21 21 # Max year is only limited by the size of C int.
22 22 SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
23 23 TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
24 -TIME_MINYEAR = -TIME_MAXYEAR - 1
24 +TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900
25 25
26 26 SEC_TO_US = 10 ** 6
27 27 US_TO_NS = 10 ** 3
@@ -614,12 +614,11 @@ def test_negative(self):
614 614 self.assertEqual(self.yearstr(-123456), '-123456')
615 615 self.assertEqual(self.yearstr(-123456789), str(-123456789))
616 616 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
622 619 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
620 +with self.assertRaises(OverflowError):
621 +self.yearstr(-TIME_MAXYEAR - 1)
623 622
624 623
625 624 class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Original file line number Diff line number Diff 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.
Original file line number Diff line number Diff line change
@@ -433,6 +433,12 @@ gettmarg(PyObject *args, struct tm *p)
433 433 &p->tm_hour, &p->tm_min, &p->tm_sec,
434 434 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
435 435 return 0;
436 +
437 +if (y < INT_MIN + 1900) {
438 +PyErr_SetString(PyExc_OverflowError, "year out of range");
439 +return 0;
440 + }
441 +
436 442 p->tm_year = y - 1900;
437 443 p->tm_mon--;
438 444 p->tm_wday = (p->tm_wday + 1) % 7;