Skip to content

Commit ba71202

Browse files
committed
gh-141749 fix pure python pickle.py error handling
This fix addresses error handling inconsistencies in CPython's pure Python `pickle.py` implementation to match the behavior of the C `_pickle` module. The changes make the pure Python implementation raise proper `UnpicklingError` exceptions for invalid pickle data instead of low-level `KeyError` and `IndexError` exceptions.
1 parent e217874 commit ba71202

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

Lib/pickle.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1322,12 +1322,18 @@ def load(self):
13221322
if not key:
13231323
raise EOFError
13241324
assert isinstance(key, bytes_types)
1325-
dispatch[key[0]](self)
1325+
try:
1326+
dispatch[key[0]](self)
1327+
except KeyError:
1328+
raise UnpicklingError(
1329+
f"invalid load key, '\\x{key[0]:02x}'.")
13261330
except _Stop as stopinst:
13271331
return stopinst.value
13281332

13291333
# Return a list of items pushed in the stack after last MARK instruction.
13301334
def pop_mark(self):
1335+
if not self.metastack:
1336+
raise UnpicklingError("could not find MARK")
13311337
items = self.stack
13321338
self.stack = self.metastack.pop()
13331339
self.append = self.stack.append

Lib/test/test_pickle.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ class PyPickleTests(AbstractPickleModuleTests, unittest.TestCase):
5555
class PyUnpicklerTests(AbstractUnpickleTests, unittest.TestCase):
5656

5757
unpickler = pickle._Unpickler
58-
bad_stack_errors = (IndexError,)
58+
bad_stack_errors = (pickle.UnpicklingError, IndexError)
5959
truncated_errors = (pickle.UnpicklingError, EOFError,
6060
AttributeError, ValueError,
6161
struct.error, IndexError, ImportError)

0 commit comments

Comments
 (0)