Skip to content

Commit ab29053

Browse files
[3.13] gh-123431: Harmonize extension code checks in pickle (GH-123434) (#123459)
gh-123431: Harmonize extension code checks in pickle (GH-123434) This checks are redundant in normal circumstances and can only work if the extension registry was intentionally broken. * The Python implementation now raises exception for the extension code with false boolean value. * Simplify the C code. RuntimeError is now raised in explicit checks. * Add many tests. (cherry picked from commit 0c3ea30) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 5c408e3 commit ab29053

File tree

3 files changed

+73
-28
lines changed

3 files changed

+73
-28
lines changed

Lib/pickle.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1093,11 +1093,16 @@ def save_global(self, obj, name=None):
10931093
(obj, module_name, name))
10941094

10951095
if self.proto >= 2:
1096-
code = _extension_registry.get((module_name, name))
1097-
if code:
1098-
assert code > 0
1096+
code = _extension_registry.get((module_name, name), _NoValue)
1097+
if code is not _NoValue:
10991098
if code <= 0xff:
1100-
write(EXT1 + pack("<B", code))
1099+
data = pack("<B", code)
1100+
if data == b'\0':
1101+
# Should never happen in normal circumstances,
1102+
# since the type and the value of the code are
1103+
# checked in copyreg.add_extension().
1104+
raise RuntimeError("extension code 0 is out of range")
1105+
write(EXT1 + data)
11011106
elif code <= 0xffff:
11021107
write(EXT2 + pack("<H", code))
11031108
else:
@@ -1591,9 +1596,8 @@ def load_ext4(self):
15911596
dispatch[EXT4[0]] = load_ext4
15921597

15931598
def get_extension(self, code):
1594-
nil = []
1595-
obj = _extension_cache.get(code, nil)
1596-
if obj is not nil:
1599+
obj = _extension_cache.get(code, _NoValue)
1600+
if obj is not _NoValue:
15971601
self.append(obj)
15981602
return
15991603
key = _inverted_registry.get(code)

Lib/test/pickletester.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1297,6 +1297,35 @@ def find_class(module_name, global_name):
12971297
self.assertEqual(loads(b'cmath\nlog\n.'), ('math', 'log'))
12981298
self.assertEqual(loads(b'\x8c\x04math\x8c\x03log\x93.'), ('math', 'log'))
12991299

1300+
def test_bad_ext_code(self):
1301+
# unregistered extension code
1302+
self.check_unpickling_error(ValueError, b'\x82\x01.')
1303+
self.check_unpickling_error(ValueError, b'\x82\xff.')
1304+
self.check_unpickling_error(ValueError, b'\x83\x01\x00.')
1305+
self.check_unpickling_error(ValueError, b'\x83\xff\xff.')
1306+
self.check_unpickling_error(ValueError, b'\x84\x01\x00\x00\x00.')
1307+
self.check_unpickling_error(ValueError, b'\x84\xff\xff\xff\x7f.')
1308+
# EXT specifies code <= 0
1309+
self.check_unpickling_error(pickle.UnpicklingError, b'\x82\x00.')
1310+
self.check_unpickling_error(pickle.UnpicklingError, b'\x83\x00\x00.')
1311+
self.check_unpickling_error(pickle.UnpicklingError, b'\x84\x00\x00\x00\x00.')
1312+
self.check_unpickling_error(pickle.UnpicklingError, b'\x84\x00\x00\x00\x80.')
1313+
self.check_unpickling_error(pickle.UnpicklingError, b'\x84\xff\xff\xff\xff.')
1314+
1315+
@support.cpython_only
1316+
def test_bad_ext_inverted_registry(self):
1317+
code = 1
1318+
def check(key, exc):
1319+
with support.swap_item(copyreg._inverted_registry, code, key):
1320+
with self.assertRaises(exc):
1321+
self.loads(b'\x82\x01.')
1322+
check(None, ValueError)
1323+
check((), ValueError)
1324+
check((__name__,), (TypeError, ValueError))
1325+
check((__name__, "MyList", "x"), (TypeError, ValueError))
1326+
check((__name__, None), (TypeError, ValueError))
1327+
check((None, "MyList"), (TypeError, ValueError))
1328+
13001329
def test_bad_reduce(self):
13011330
self.assertEqual(self.loads(b'cbuiltins\nint\n)R.'), 0)
13021331
self.check_unpickling_error(TypeError, b'N)R.')
@@ -2031,6 +2060,28 @@ def persistent_id(self, obj):
20312060
check({Clearer(): 1, Clearer(): 2})
20322061
check({1: Clearer(), 2: Clearer()})
20332062

2063+
@support.cpython_only
2064+
def test_bad_ext_code(self):
2065+
# This should never happen in normal circumstances, because the type
2066+
# and the value of the extesion code is checked in copyreg.add_extension().
2067+
key = (__name__, 'MyList')
2068+
def check(code, exc):
2069+
assert key not in copyreg._extension_registry
2070+
assert code not in copyreg._inverted_registry
2071+
with (support.swap_item(copyreg._extension_registry, key, code),
2072+
support.swap_item(copyreg._inverted_registry, code, key)):
2073+
for proto in protocols[2:]:
2074+
with self.assertRaises(exc):
2075+
self.dumps(MyList, proto)
2076+
2077+
check(object(), TypeError)
2078+
check(None, TypeError)
2079+
check(-1, (RuntimeError, struct.error))
2080+
check(0, RuntimeError)
2081+
check(2**31, (RuntimeError, OverflowError, struct.error))
2082+
check(2**1000, (OverflowError, struct.error))
2083+
check(-2**1000, (OverflowError, struct.error))
2084+
20342085

20352086
class AbstractPickleTests:
20362087
# Subclass must define self.dumps, self.loads.

Modules/_pickle.c

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3663,34 +3663,24 @@ save_global(PickleState *st, PicklerObject *self, PyObject *obj,
36633663
if (extension_key == NULL) {
36643664
goto error;
36653665
}
3666-
code_obj = PyDict_GetItemWithError(st->extension_registry,
3667-
extension_key);
3666+
if (PyDict_GetItemRef(st->extension_registry, extension_key, &code_obj) < 0) {
3667+
Py_DECREF(extension_key);
3668+
goto error;
3669+
}
36683670
Py_DECREF(extension_key);
3669-
/* The object is not registered in the extension registry.
3670-
This is the most likely code path. */
36713671
if (code_obj == NULL) {
3672-
if (PyErr_Occurred()) {
3673-
goto error;
3674-
}
3672+
/* The object is not registered in the extension registry.
3673+
This is the most likely code path. */
36753674
goto gen_global;
36763675
}
36773676

3678-
/* XXX: pickle.py doesn't check neither the type, nor the range
3679-
of the value returned by the extension_registry. It should for
3680-
consistency. */
3681-
3682-
/* Verify code_obj has the right type and value. */
3683-
if (!PyLong_Check(code_obj)) {
3684-
PyErr_Format(st->PicklingError,
3685-
"Can't pickle %R: extension code %R isn't an integer",
3686-
obj, code_obj);
3687-
goto error;
3688-
}
3689-
code = PyLong_AS_LONG(code_obj);
3677+
code = PyLong_AsLong(code_obj);
3678+
Py_DECREF(code_obj);
36903679
if (code <= 0 || code > 0x7fffffffL) {
3680+
/* Should never happen in normal circumstances, since the type and
3681+
the value of the code are checked in copyreg.add_extension(). */
36913682
if (!PyErr_Occurred())
3692-
PyErr_Format(st->PicklingError, "Can't pickle %R: extension "
3693-
"code %ld is out of range", obj, code);
3683+
PyErr_Format(PyExc_RuntimeError, "extension code %ld is out of range", code);
36943684
goto error;
36953685
}
36963686

0 commit comments

Comments
 (0)