Skip to content

Commit b6ece3a

Browse files
author
neal.norwitz
committed
Fix problem spotted by Coverity that occurs if tzinfo.tzname().replace()
returns a non-string when converting %Z. Will backport. git-svn-id: http://svn.python.org/projects/python/trunk@43147 6015fed2-1504-0410-9fe1-9d1591cc4771
1 parent b0576a7 commit b6ece3a

2 files changed

Lines changed: 20 additions & 4 deletions

File tree

Lib/test/test_datetime.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1168,6 +1168,17 @@ def test_tz_independent_comparing(self):
11681168
self.assertEqual(dt2 - dt1, us)
11691169
self.assert_(dt1 < dt2)
11701170

1171+
def test_strftime_with_bad_tzname_replace(self):
1172+
# verify ok if tzinfo.tzname().replace() returns a non-string
1173+
class MyTzInfo(FixedOffset):
1174+
def tzname(self, dt):
1175+
class MyStr(str):
1176+
def replace(self, *args):
1177+
return None
1178+
return MyStr('name')
1179+
t = self.theclass(2005, 3, 2, 0, 0, 0, 0, MyTzInfo(3, 'name'))
1180+
self.assertRaises(TypeError, t.strftime, '%Z')
1181+
11711182
def test_bad_constructor_arguments(self):
11721183
# bad years
11731184
self.theclass(MINYEAR, 1, 1) # no exception

Modules/datetimemodule.c

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1228,8 +1228,8 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
12281228
}
12291229
}
12301230
assert(zreplacement != NULL);
1231-
ptoappend = PyString_AsString(zreplacement);
1232-
ntoappend = PyString_Size(zreplacement);
1231+
ptoappend = PyString_AS_STRING(zreplacement);
1232+
ntoappend = PyString_GET_SIZE(zreplacement);
12331233
}
12341234
else if (ch == 'Z') {
12351235
/* format tzname */
@@ -1257,14 +1257,18 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
12571257
Py_DECREF(temp);
12581258
if (Zreplacement == NULL)
12591259
goto Done;
1260+
if (!PyString_Check(Zreplacement)) {
1261+
PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1262+
goto Done;
1263+
}
12601264
}
12611265
else
12621266
Py_DECREF(temp);
12631267
}
12641268
}
12651269
assert(Zreplacement != NULL);
1266-
ptoappend = PyString_AsString(Zreplacement);
1267-
ntoappend = PyString_Size(Zreplacement);
1270+
ptoappend = PyString_AS_STRING(Zreplacement);
1271+
ntoappend = PyString_GET_SIZE(Zreplacement);
12681272
}
12691273
else {
12701274
/* percent followed by neither z nor Z */
@@ -1275,6 +1279,7 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
12751279
/* Append the ntoappend chars starting at ptoappend to
12761280
* the new format.
12771281
*/
1282+
assert(ptoappend != NULL);
12781283
assert(ntoappend >= 0);
12791284
if (ntoappend == 0)
12801285
continue;

0 commit comments

Comments
 (0)