You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1619 lines
55 KiB

cPickle.c: Full support for the new LONG1 and LONG4. Added comments. Assorted code cleanups; e.g., sizeof(char) is 1 by definition, so there's no need to do things like multiply by sizeof(char) in hairy malloc arguments. Fixed an undetected-overflow bug in readline_file(). longobject.c: Fixed a really stupid bug in the new _PyLong_NumBits. pickle.py: Fixed stupid bug in save_long(): When proto is 2, it wrote LONG1 or LONG4, but forgot to return then -- it went on to append the proto 1 LONG opcode too. Fixed equally stupid cancelling bugs in load_long1() and load_long4(): they *returned* the unpickled long instead of pushing it on the stack. The return values were ignored. Tests passed before only because save_long() pickled the long twice. Fixed bugs in encode_long(). Noted that decode_long() is quadratic-time despite our hopes, because long(string, 16) is still quadratic-time in len(string). It's hex() that's linear-time. I don't know a way to make decode_long() linear-time in Python, short of maybe transforming the 256's-complement bytes into marshal's funky internal format, and letting marshal decode that. It would be more valuable to make long(string, 16) linear time. pickletester.py: Added a global "protocols" vector so tests can try all the protocols in a sane way. Changed test_ints() and test_unicode() to do so. Added a new test_long(), but the tail end of it is disabled because it "takes forever" under pickle.py (but runs very quickly under cPickle: cPickle proto 2 for longs is linear-time).
23 years ago
23 years ago
17 years ago
  1. """Create portable serialized representations of Python objects.
  2. See module copyreg for a mechanism for registering custom picklers.
  3. See module pickletools source for extensive comments.
  4. Classes:
  5. Pickler
  6. Unpickler
  7. Functions:
  8. dump(object, file)
  9. dumps(object) -> string
  10. load(file) -> object
  11. loads(string) -> object
  12. Misc variables:
  13. __version__
  14. format_version
  15. compatible_formats
  16. """
  17. from types import FunctionType
  18. from copyreg import dispatch_table
  19. from copyreg import _extension_registry, _inverted_registry, _extension_cache
  20. from itertools import islice
  21. from functools import partial
  22. import sys
  23. from sys import maxsize
  24. from struct import pack, unpack
  25. import re
  26. import io
  27. import codecs
  28. import _compat_pickle
  29. __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
  30. "Unpickler", "dump", "dumps", "load", "loads"]
  31. # Shortcut for use in isinstance testing
  32. bytes_types = (bytes, bytearray)
  33. # These are purely informational; no code uses these.
  34. format_version = "4.0" # File format version we write
  35. compatible_formats = ["1.0", # Original protocol 0
  36. "1.1", # Protocol 0 with INST added
  37. "1.2", # Original protocol 1
  38. "1.3", # Protocol 1 with BINFLOAT added
  39. "2.0", # Protocol 2
  40. "3.0", # Protocol 3
  41. "4.0", # Protocol 4
  42. ] # Old format versions we can read
  43. # This is the highest protocol number we know how to read.
  44. HIGHEST_PROTOCOL = 4
  45. # The protocol we write by default. May be less than HIGHEST_PROTOCOL.
  46. # We intentionally write a protocol that Python 2.x cannot read;
  47. # there are too many issues with that.
  48. DEFAULT_PROTOCOL = 3
  49. class PickleError(Exception):
  50. """A common base class for the other pickling exceptions."""
  51. pass
  52. class PicklingError(PickleError):
  53. """This exception is raised when an unpicklable object is passed to the
  54. dump() method.
  55. """
  56. pass
  57. class UnpicklingError(PickleError):
  58. """This exception is raised when there is a problem unpickling an object,
  59. such as a security violation.
  60. Note that other exceptions may also be raised during unpickling, including
  61. (but not necessarily limited to) AttributeError, EOFError, ImportError,
  62. and IndexError.
  63. """
  64. pass
  65. # An instance of _Stop is raised by Unpickler.load_stop() in response to
  66. # the STOP opcode, passing the object that is the result of unpickling.
  67. class _Stop(Exception):
  68. def __init__(self, value):
  69. self.value = value
  70. # Jython has PyStringMap; it's a dict subclass with string keys
  71. try:
  72. from org.python.core import PyStringMap
  73. except ImportError:
  74. PyStringMap = None
  75. # Pickle opcodes. See pickletools.py for extensive docs. The listing
  76. # here is in kind-of alphabetical order of 1-character pickle code.
  77. # pickletools groups them by purpose.
  78. MARK = b'(' # push special markobject on stack
  79. STOP = b'.' # every pickle ends with STOP
  80. POP = b'0' # discard topmost stack item
  81. POP_MARK = b'1' # discard stack top through topmost markobject
  82. DUP = b'2' # duplicate top stack item
  83. FLOAT = b'F' # push float object; decimal string argument
  84. INT = b'I' # push integer or bool; decimal string argument
  85. BININT = b'J' # push four-byte signed int
  86. BININT1 = b'K' # push 1-byte unsigned int
  87. LONG = b'L' # push long; decimal string argument
  88. BININT2 = b'M' # push 2-byte unsigned int
  89. NONE = b'N' # push None
  90. PERSID = b'P' # push persistent object; id is taken from string arg
  91. BINPERSID = b'Q' # " " " ; " " " " stack
  92. REDUCE = b'R' # apply callable to argtuple, both on stack
  93. STRING = b'S' # push string; NL-terminated string argument
  94. BINSTRING = b'T' # push string; counted binary string argument
  95. SHORT_BINSTRING= b'U' # " " ; " " " " < 256 bytes
  96. UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument
  97. BINUNICODE = b'X' # " " " ; counted UTF-8 string argument
  98. APPEND = b'a' # append stack top to list below it
  99. BUILD = b'b' # call __setstate__ or __dict__.update()
  100. GLOBAL = b'c' # push self.find_class(modname, name); 2 string args
  101. DICT = b'd' # build a dict from stack items
  102. EMPTY_DICT = b'}' # push empty dict
  103. APPENDS = b'e' # extend list on stack by topmost stack slice
  104. GET = b'g' # push item from memo on stack; index is string arg
  105. BINGET = b'h' # " " " " " " ; " " 1-byte arg
  106. INST = b'i' # build & push class instance
  107. LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg
  108. LIST = b'l' # build list from topmost stack items
  109. EMPTY_LIST = b']' # push empty list
  110. OBJ = b'o' # build & push class instance
  111. PUT = b'p' # store stack top in memo; index is string arg
  112. BINPUT = b'q' # " " " " " ; " " 1-byte arg
  113. LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg
  114. SETITEM = b's' # add key+value pair to dict
  115. TUPLE = b't' # build tuple from topmost stack items
  116. EMPTY_TUPLE = b')' # push empty tuple
  117. SETITEMS = b'u' # modify dict by adding topmost key+value pairs
  118. BINFLOAT = b'G' # push float; arg is 8-byte float encoding
  119. TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py
  120. FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py
  121. # Protocol 2
  122. PROTO = b'\x80' # identify pickle protocol
  123. NEWOBJ = b'\x81' # build object by applying cls.__new__ to argtuple
  124. EXT1 = b'\x82' # push object from extension registry; 1-byte index
  125. EXT2 = b'\x83' # ditto, but 2-byte index
  126. EXT4 = b'\x84' # ditto, but 4-byte index
  127. TUPLE1 = b'\x85' # build 1-tuple from stack top
  128. TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items
  129. TUPLE3 = b'\x87' # build 3-tuple from three topmost stack items
  130. NEWTRUE = b'\x88' # push True
  131. NEWFALSE = b'\x89' # push False
  132. LONG1 = b'\x8a' # push long from < 256 bytes
  133. LONG4 = b'\x8b' # push really big long
  134. _tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
  135. # Protocol 3 (Python 3.x)
  136. BINBYTES = b'B' # push bytes; counted binary string argument
  137. SHORT_BINBYTES = b'C' # " " ; " " " " < 256 bytes
  138. # Protocol 4
  139. SHORT_BINUNICODE = b'\x8c' # push short string; UTF-8 length < 256 bytes
  140. BINUNICODE8 = b'\x8d' # push very long string
  141. BINBYTES8 = b'\x8e' # push very long bytes string
  142. EMPTY_SET = b'\x8f' # push empty set on the stack
  143. ADDITEMS = b'\x90' # modify set by adding topmost stack items
  144. FROZENSET = b'\x91' # build frozenset from topmost stack items
  145. NEWOBJ_EX = b'\x92' # like NEWOBJ but work with keyword only arguments
  146. STACK_GLOBAL = b'\x93' # same as GLOBAL but using names on the stacks
  147. MEMOIZE = b'\x94' # store top of the stack in memo
  148. FRAME = b'\x95' # indicate the beginning of a new frame
  149. __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$", x)])
  150. class _Framer:
  151. _FRAME_SIZE_TARGET = 64 * 1024
  152. def __init__(self, file_write):
  153. self.file_write = file_write
  154. self.current_frame = None
  155. def start_framing(self):
  156. self.current_frame = io.BytesIO()
  157. def end_framing(self):
  158. if self.current_frame and self.current_frame.tell() > 0:
  159. self.commit_frame(force=True)
  160. self.current_frame = None
  161. def commit_frame(self, force=False):
  162. if self.current_frame:
  163. f = self.current_frame
  164. if f.tell() >= self._FRAME_SIZE_TARGET or force:
  165. with f.getbuffer() as data:
  166. n = len(data)
  167. write = self.file_write
  168. write(FRAME)
  169. write(pack("<Q", n))
  170. write(data)
  171. f.seek(0)
  172. f.truncate()
  173. def write(self, data):
  174. if self.current_frame:
  175. return self.current_frame.write(data)
  176. else:
  177. return self.file_write(data)
  178. class _Unframer:
  179. def __init__(self, file_read, file_readline, file_tell=None):
  180. self.file_read = file_read
  181. self.file_readline = file_readline
  182. self.current_frame = None
  183. def read(self, n):
  184. if self.current_frame:
  185. data = self.current_frame.read(n)
  186. if not data and n != 0:
  187. self.current_frame = None
  188. return self.file_read(n)
  189. if len(data) < n:
  190. raise UnpicklingError(
  191. "pickle exhausted before end of frame")
  192. return data
  193. else:
  194. return self.file_read(n)
  195. def readline(self):
  196. if self.current_frame:
  197. data = self.current_frame.readline()
  198. if not data:
  199. self.current_frame = None
  200. return self.file_readline()
  201. if data[-1] != b'\n'[0]:
  202. raise UnpicklingError(
  203. "pickle exhausted before end of frame")
  204. return data
  205. else:
  206. return self.file_readline()
  207. def load_frame(self, frame_size):
  208. if self.current_frame and self.current_frame.read() != b'':
  209. raise UnpicklingError(
  210. "beginning of a new frame before end of current frame")
  211. self.current_frame = io.BytesIO(self.file_read(frame_size))
  212. # Tools used for pickling.
  213. def _getattribute(obj, name):
  214. for subpath in name.split('.'):
  215. if subpath == '<locals>':
  216. raise AttributeError("Can't get local attribute {!r} on {!r}"
  217. .format(name, obj))
  218. try:
  219. parent = obj
  220. obj = getattr(obj, subpath)
  221. except AttributeError:
  222. raise AttributeError("Can't get attribute {!r} on {!r}"
  223. .format(name, obj))
  224. return obj, parent
  225. def whichmodule(obj, name):
  226. """Find the module an object belong to."""
  227. module_name = getattr(obj, '__module__', None)
  228. if module_name is not None:
  229. return module_name
  230. # Protect the iteration by using a list copy of sys.modules against dynamic
  231. # modules that trigger imports of other modules upon calls to getattr.
  232. for module_name, module in list(sys.modules.items()):
  233. if module_name == '__main__' or module is None:
  234. continue
  235. try:
  236. if _getattribute(module, name)[0] is obj:
  237. return module_name
  238. except AttributeError:
  239. pass
  240. return '__main__'
  241. def encode_long(x):
  242. r"""Encode a long to a two's complement little-endian binary string.
  243. Note that 0 is a special case, returning an empty string, to save a
  244. byte in the LONG1 pickling context.
  245. >>> encode_long(0)
  246. b''
  247. >>> encode_long(255)
  248. b'\xff\x00'
  249. >>> encode_long(32767)
  250. b'\xff\x7f'
  251. >>> encode_long(-256)
  252. b'\x00\xff'
  253. >>> encode_long(-32768)
  254. b'\x00\x80'
  255. >>> encode_long(-128)
  256. b'\x80'
  257. >>> encode_long(127)
  258. b'\x7f'
  259. >>>
  260. """
  261. if x == 0:
  262. return b''
  263. nbytes = (x.bit_length() >> 3) + 1
  264. result = x.to_bytes(nbytes, byteorder='little', signed=True)
  265. if x < 0 and nbytes > 1:
  266. if result[-1] == 0xff and (result[-2] & 0x80) != 0:
  267. result = result[:-1]
  268. return result
  269. def decode_long(data):
  270. r"""Decode a long from a two's complement little-endian binary string.
  271. >>> decode_long(b'')
  272. 0
  273. >>> decode_long(b"\xff\x00")
  274. 255
  275. >>> decode_long(b"\xff\x7f")
  276. 32767
  277. >>> decode_long(b"\x00\xff")
  278. -256
  279. >>> decode_long(b"\x00\x80")
  280. -32768
  281. >>> decode_long(b"\x80")
  282. -128
  283. >>> decode_long(b"\x7f")
  284. 127
  285. """
  286. return int.from_bytes(data, byteorder='little', signed=True)
  287. # Pickling machinery
  288. class _Pickler:
  289. def __init__(self, file, protocol=None, *, fix_imports=True):
  290. """This takes a binary file for writing a pickle data stream.
  291. The optional *protocol* argument tells the pickler to use the
  292. given protocol; supported protocols are 0, 1, 2, 3 and 4. The
  293. default protocol is 3; a backward-incompatible protocol designed
  294. for Python 3.
  295. Specifying a negative protocol version selects the highest
  296. protocol version supported. The higher the protocol used, the
  297. more recent the version of Python needed to read the pickle
  298. produced.
  299. The *file* argument must have a write() method that accepts a
  300. single bytes argument. It can thus be a file object opened for
  301. binary writing, a io.BytesIO instance, or any other custom
  302. object that meets this interface.
  303. If *fix_imports* is True and *protocol* is less than 3, pickle
  304. will try to map the new Python 3 names to the old module names
  305. used in Python 2, so that the pickle data stream is readable
  306. with Python 2.
  307. """
  308. if protocol is None:
  309. protocol = DEFAULT_PROTOCOL
  310. if protocol < 0:
  311. protocol = HIGHEST_PROTOCOL
  312. elif not 0 <= protocol <= HIGHEST_PROTOCOL:
  313. raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
  314. try:
  315. self._file_write = file.write
  316. except AttributeError:
  317. raise TypeError("file must have a 'write' attribute")
  318. self.framer = _Framer(self._file_write)
  319. self.write = self.framer.write
  320. self.memo = {}
  321. self.proto = int(protocol)
  322. self.bin = protocol >= 1
  323. self.fast = 0
  324. self.fix_imports = fix_imports and protocol < 3
  325. def clear_memo(self):
  326. """Clears the pickler's "memo".
  327. The memo is the data structure that remembers which objects the
  328. pickler has already seen, so that shared or recursive objects
  329. are pickled by reference and not by value. This method is
  330. useful when re-using picklers.
  331. """
  332. self.memo.clear()
  333. def dump(self, obj):
  334. """Write a pickled representation of obj to the open file."""
  335. # Check whether Pickler was initialized correctly. This is
  336. # only needed to mimic the behavior of _pickle.Pickler.dump().
  337. if not hasattr(self, "_file_write"):
  338. raise PicklingError("Pickler.__init__() was not called by "
  339. "%s.__init__()" % (self.__class__.__name__,))
  340. if self.proto >= 2:
  341. self.write(PROTO + pack("<B", self.proto))
  342. if self.proto >= 4:
  343. self.framer.start_framing()
  344. self.save(obj)
  345. self.write(STOP)
  346. self.framer.end_framing()
  347. def memoize(self, obj):
  348. """Store an object in the memo."""
  349. # The Pickler memo is a dictionary mapping object ids to 2-tuples
  350. # that contain the Unpickler memo key and the object being memoized.
  351. # The memo key is written to the pickle and will become
  352. # the key in the Unpickler's memo. The object is stored in the
  353. # Pickler memo so that transient objects are kept alive during
  354. # pickling.
  355. # The use of the Unpickler memo length as the memo key is just a
  356. # convention. The only requirement is that the memo values be unique.
  357. # But there appears no advantage to any other scheme, and this
  358. # scheme allows the Unpickler memo to be implemented as a plain (but
  359. # growable) array, indexed by memo key.
  360. if self.fast:
  361. return
  362. assert id(obj) not in self.memo
  363. idx = len(self.memo)
  364. self.write(self.put(idx))
  365. self.memo[id(obj)] = idx, obj
  366. # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
  367. def put(self, idx):
  368. if self.proto >= 4:
  369. return MEMOIZE
  370. elif self.bin:
  371. if idx < 256:
  372. return BINPUT + pack("<B", idx)
  373. else:
  374. return LONG_BINPUT + pack("<I", idx)
  375. else:
  376. return PUT + repr(idx).encode("ascii") + b'\n'
  377. # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
  378. def get(self, i):
  379. if self.bin:
  380. if i < 256:
  381. return BINGET + pack("<B", i)
  382. else:
  383. return LONG_BINGET + pack("<I", i)
  384. return GET + repr(i).encode("ascii") + b'\n'
  385. def save(self, obj, save_persistent_id=True):
  386. self.framer.commit_frame()
  387. # Check for persistent id (defined by a subclass)
  388. pid = self.persistent_id(obj)
  389. if pid is not None and save_persistent_id:
  390. self.save_pers(pid)
  391. return
  392. # Check the memo
  393. x = self.memo.get(id(obj))
  394. if x is not None:
  395. self.write(self.get(x[0]))
  396. return
  397. # Check the type dispatch table
  398. t = type(obj)
  399. f = self.dispatch.get(t)
  400. if f is not None:
  401. f(self, obj) # Call unbound method with explicit self
  402. return
  403. # Check private dispatch table if any, or else copyreg.dispatch_table
  404. reduce = getattr(self, 'dispatch_table', dispatch_table).get(t)
  405. if reduce is not None:
  406. rv = reduce(obj)
  407. else:
  408. # Check for a class with a custom metaclass; treat as regular class
  409. try:
  410. issc = issubclass(t, type)
  411. except TypeError: # t is not a class (old Boost; see SF #502085)
  412. issc = False
  413. if issc:
  414. self.save_global(obj)
  415. return
  416. # Check for a __reduce_ex__ method, fall back to __reduce__
  417. reduce = getattr(obj, "__reduce_ex__", None)
  418. if reduce is not None:
  419. rv = reduce(self.proto)
  420. else:
  421. reduce = getattr(obj, "__reduce__", None)
  422. if reduce is not None:
  423. rv = reduce()
  424. else:
  425. raise PicklingError("Can't pickle %r object: %r" %
  426. (t.__name__, obj))
  427. # Check for string returned by reduce(), meaning "save as global"
  428. if isinstance(rv, str):
  429. self.save_global(obj, rv)
  430. return
  431. # Assert that reduce() returned a tuple
  432. if not isinstance(rv, tuple):
  433. raise PicklingError("%s must return string or tuple" % reduce)
  434. # Assert that it returned an appropriately sized tuple
  435. l = len(rv)
  436. if not (2 <= l <= 5):
  437. raise PicklingError("Tuple returned by %s must have "
  438. "two to five elements" % reduce)
  439. # Save the reduce() output and finally memoize the object
  440. self.save_reduce(obj=obj, *rv)
  441. def persistent_id(self, obj):
  442. # This exists so a subclass can override it
  443. return None
  444. def save_pers(self, pid):
  445. # Save a persistent id reference
  446. if self.bin:
  447. self.save(pid, save_persistent_id=False)
  448. self.write(BINPERSID)
  449. else:
  450. self.write(PERSID + str(pid).encode("ascii") + b'\n')
  451. def save_reduce(self, func, args, state=None, listitems=None,
  452. dictitems=None, obj=None):
  453. # This API is called by some subclasses
  454. if not isinstance(args, tuple):
  455. raise PicklingError("args from save_reduce() must be a tuple")
  456. if not callable(func):
  457. raise PicklingError("func from save_reduce() must be callable")
  458. save = self.save
  459. write = self.write
  460. func_name = getattr(func, "__name__", "")
  461. if self.proto >= 2 and func_name == "__newobj_ex__":
  462. cls, args, kwargs = args
  463. if not hasattr(cls, "__new__"):
  464. raise PicklingError("args[0] from {} args has no __new__"
  465. .format(func_name))
  466. if obj is not None and cls is not obj.__class__:
  467. raise PicklingError("args[0] from {} args has the wrong class"
  468. .format(func_name))
  469. if self.proto >= 4:
  470. save(cls)
  471. save(args)
  472. save(kwargs)
  473. write(NEWOBJ_EX)
  474. else:
  475. func = partial(cls.__new__, cls, *args, **kwargs)
  476. save(func)
  477. save(())
  478. write(REDUCE)
  479. elif self.proto >= 2 and func_name == "__newobj__":
  480. # A __reduce__ implementation can direct protocol 2 or newer to
  481. # use the more efficient NEWOBJ opcode, while still
  482. # allowing protocol 0 and 1 to work normally. For this to
  483. # work, the function returned by __reduce__ should be
  484. # called __newobj__, and its first argument should be a
  485. # class. The implementation for __newobj__
  486. # should be as follows, although pickle has no way to
  487. # verify this:
  488. #
  489. # def __newobj__(cls, *args):
  490. # return cls.__new__(cls, *args)
  491. #
  492. # Protocols 0 and 1 will pickle a reference to __newobj__,
  493. # while protocol 2 (and above) will pickle a reference to
  494. # cls, the remaining args tuple, and the NEWOBJ code,
  495. # which calls cls.__new__(cls, *args) at unpickling time
  496. # (see load_newobj below). If __reduce__ returns a
  497. # three-tuple, the state from the third tuple item will be
  498. # pickled regardless of the protocol, calling __setstate__
  499. # at unpickling time (see load_build below).
  500. #
  501. # Note that no standard __newobj__ implementation exists;
  502. # you have to provide your own. This is to enforce
  503. # compatibility with Python 2.2 (pickles written using
  504. # protocol 0 or 1 in Python 2.3 should be unpicklable by
  505. # Python 2.2).
  506. cls = args[0]
  507. if not hasattr(cls, "__new__"):
  508. raise PicklingError(
  509. "args[0] from __newobj__ args has no __new__")
  510. if obj is not None and cls is not obj.__class__:
  511. raise PicklingError(
  512. "args[0] from __newobj__ args has the wrong class")
  513. args = args[1:]
  514. save(cls)
  515. save(args)
  516. write(NEWOBJ)
  517. else:
  518. save(func)
  519. save(args)
  520. write(REDUCE)
  521. if obj is not None:
  522. # If the object is already in the memo, this means it is
  523. # recursive. In this case, throw away everything we put on the
  524. # stack, and fetch the object back from the memo.
  525. if id(obj) in self.memo:
  526. write(POP + self.get(self.memo[id(obj)][0]))
  527. else:
  528. self.memoize(obj)
  529. # More new special cases (that work with older protocols as
  530. # well): when __reduce__ returns a tuple with 4 or 5 items,
  531. # the 4th and 5th item should be iterators that provide list
  532. # items and dict items (as (key, value) tuples), or None.
  533. if listitems is not None:
  534. self._batch_appends(listitems)
  535. if dictitems is not None:
  536. self._batch_setitems(dictitems)
  537. if state is not None:
  538. save(state)
  539. write(BUILD)
  540. # Methods below this point are dispatched through the dispatch table
  541. dispatch = {}
  542. def save_none(self, obj):
  543. self.write(NONE)
  544. dispatch[type(None)] = save_none
  545. def save_bool(self, obj):
  546. if self.proto >= 2:
  547. self.write(NEWTRUE if obj else NEWFALSE)
  548. else:
  549. self.write(TRUE if obj else FALSE)
  550. dispatch[bool] = save_bool
  551. def save_long(self, obj):
  552. if self.bin:
  553. # If the int is small enough to fit in a signed 4-byte 2's-comp
  554. # format, we can store it more efficiently than the general
  555. # case.
  556. # First one- and two-byte unsigned ints:
  557. if obj >= 0:
  558. if obj <= 0xff:
  559. self.write(BININT1 + pack("<B", obj))
  560. return
  561. if obj <= 0xffff:
  562. self.write(BININT2 + pack("<H", obj))
  563. return
  564. # Next check for 4-byte signed ints:
  565. if -0x80000000 <= obj <= 0x7fffffff:
  566. self.write(BININT + pack("<i", obj))
  567. return
  568. if self.proto >= 2:
  569. encoded = encode_long(obj)
  570. n = len(encoded)
  571. if n < 256:
  572. self.write(LONG1 + pack("<B", n) + encoded)
  573. else:
  574. self.write(LONG4 + pack("<i", n) + encoded)
  575. return
  576. self.write(LONG + repr(obj).encode("ascii") + b'L\n')
  577. dispatch[int] = save_long
  578. def save_float(self, obj):
  579. if self.bin:
  580. self.write(BINFLOAT + pack('>d', obj))
  581. else:
  582. self.write(FLOAT + repr(obj).encode("ascii") + b'\n')
  583. dispatch[float] = save_float
  584. def save_bytes(self, obj):
  585. if self.proto < 3:
  586. if not obj: # bytes object is empty
  587. self.save_reduce(bytes, (), obj=obj)
  588. else:
  589. self.save_reduce(codecs.encode,
  590. (str(obj, 'latin1'), 'latin1'), obj=obj)
  591. return
  592. n = len(obj)
  593. if n <= 0xff:
  594. self.write(SHORT_BINBYTES + pack("<B", n) + obj)
  595. elif n > 0xffffffff and self.proto >= 4:
  596. self.write(BINBYTES8 + pack("<Q", n) + obj)
  597. else:
  598. self.write(BINBYTES + pack("<I", n) + obj)
  599. self.memoize(obj)
  600. dispatch[bytes] = save_bytes
  601. def save_str(self, obj):
  602. if self.bin:
  603. encoded = obj.encode('utf-8', 'surrogatepass')
  604. n = len(encoded)
  605. if n <= 0xff and self.proto >= 4:
  606. self.write(SHORT_BINUNICODE + pack("<B", n) + encoded)
  607. elif n > 0xffffffff and self.proto >= 4:
  608. self.write(BINUNICODE8 + pack("<Q", n) + encoded)
  609. else:
  610. self.write(BINUNICODE + pack("<I", n) + encoded)
  611. else:
  612. obj = obj.replace("\\", "\\u005c")
  613. obj = obj.replace("\n", "\\u000a")
  614. self.write(UNICODE + obj.encode('raw-unicode-escape') +
  615. b'\n')
  616. self.memoize(obj)
  617. dispatch[str] = save_str
  618. def save_tuple(self, obj):
  619. if not obj: # tuple is empty
  620. if self.bin:
  621. self.write(EMPTY_TUPLE)
  622. else:
  623. self.write(MARK + TUPLE)
  624. return
  625. n = len(obj)
  626. save = self.save
  627. memo = self.memo
  628. if n <= 3 and self.proto >= 2:
  629. for element in obj:
  630. save(element)
  631. # Subtle. Same as in the big comment below.
  632. if id(obj) in memo:
  633. get = self.get(memo[id(obj)][0])
  634. self.write(POP * n + get)
  635. else:
  636. self.write(_tuplesize2code[n])
  637. self.memoize(obj)
  638. return
  639. # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
  640. # has more than 3 elements.
  641. write = self.write
  642. write(MARK)
  643. for element in obj:
  644. save(element)
  645. if id(obj) in memo:
  646. # Subtle. d was not in memo when we entered save_tuple(), so
  647. # the process of saving the tuple's elements must have saved
  648. # the tuple itself: the tuple is recursive. The proper action
  649. # now is to throw away everything we put on the stack, and
  650. # simply GET the tuple (it's already constructed). This check
  651. # could have been done in the "for element" loop instead, but
  652. # recursive tuples are a rare thing.
  653. get = self.get(memo[id(obj)][0])
  654. if self.bin:
  655. write(POP_MARK + get)
  656. else: # proto 0 -- POP_MARK not available
  657. write(POP * (n+1) + get)
  658. return
  659. # No recursion.
  660. write(TUPLE)
  661. self.memoize(obj)
  662. dispatch[tuple] = save_tuple
  663. def save_list(self, obj):
  664. if self.bin:
  665. self.write(EMPTY_LIST)
  666. else: # proto 0 -- can't use EMPTY_LIST
  667. self.write(MARK + LIST)
  668. self.memoize(obj)
  669. self._batch_appends(obj)
  670. dispatch[list] = save_list
  671. _BATCHSIZE = 1000
  672. def _batch_appends(self, items):
  673. # Helper to batch up APPENDS sequences
  674. save = self.save
  675. write = self.write
  676. if not self.bin:
  677. for x in items:
  678. save(x)
  679. write(APPEND)
  680. return
  681. it = iter(items)
  682. while True:
  683. tmp = list(islice(it, self._BATCHSIZE))
  684. n = len(tmp)
  685. if n > 1:
  686. write(MARK)
  687. for x in tmp:
  688. save(x)
  689. write(APPENDS)
  690. elif n:
  691. save(tmp[0])
  692. write(APPEND)
  693. # else tmp is empty, and we're done
  694. if n < self._BATCHSIZE:
  695. return
  696. def save_dict(self, obj):
  697. if self.bin:
  698. self.write(EMPTY_DICT)
  699. else: # proto 0 -- can't use EMPTY_DICT
  700. self.write(MARK + DICT)
  701. self.memoize(obj)
  702. self._batch_setitems(obj.items())
  703. dispatch[dict] = save_dict
  704. if PyStringMap is not None:
  705. dispatch[PyStringMap] = save_dict
  706. def _batch_setitems(self, items):
  707. # Helper to batch up SETITEMS sequences; proto >= 1 only
  708. save = self.save
  709. write = self.write
  710. if not self.bin:
  711. for k, v in items:
  712. save(k)
  713. save(v)
  714. write(SETITEM)
  715. return
  716. it = iter(items)
  717. while True:
  718. tmp = list(islice(it, self._BATCHSIZE))
  719. n = len(tmp)
  720. if n > 1:
  721. write(MARK)
  722. for k, v in tmp:
  723. save(k)
  724. save(v)
  725. write(SETITEMS)
  726. elif n:
  727. k, v = tmp[0]
  728. save(k)
  729. save(v)
  730. write(SETITEM)
  731. # else tmp is empty, and we're done
  732. if n < self._BATCHSIZE:
  733. return
  734. def save_set(self, obj):
  735. save = self.save
  736. write = self.write
  737. if self.proto < 4:
  738. self.save_reduce(set, (list(obj),), obj=obj)
  739. return
  740. write(EMPTY_SET)
  741. self.memoize(obj)
  742. it = iter(obj)
  743. while True:
  744. batch = list(islice(it, self._BATCHSIZE))
  745. n = len(batch)
  746. if n > 0:
  747. write(MARK)
  748. for item in batch:
  749. save(item)
  750. write(ADDITEMS)
  751. if n < self._BATCHSIZE:
  752. return
  753. dispatch[set] = save_set
  754. def save_frozenset(self, obj):
  755. save = self.save
  756. write = self.write
  757. if self.proto < 4:
  758. self.save_reduce(frozenset, (list(obj),), obj=obj)
  759. return
  760. write(MARK)
  761. for item in obj:
  762. save(item)
  763. if id(obj) in self.memo:
  764. # If the object is already in the memo, this means it is
  765. # recursive. In this case, throw away everything we put on the
  766. # stack, and fetch the object back from the memo.
  767. write(POP_MARK + self.get(self.memo[id(obj)][0]))
  768. return
  769. write(FROZENSET)
  770. self.memoize(obj)
  771. dispatch[frozenset] = save_frozenset
  772. def save_global(self, obj, name=None):
  773. write = self.write
  774. memo = self.memo
  775. if name is None:
  776. name = getattr(obj, '__qualname__', None)
  777. if name is None:
  778. name = obj.__name__
  779. module_name = whichmodule(obj, name)
  780. try:
  781. __import__(module_name, level=0)
  782. module = sys.modules[module_name]
  783. obj2, parent = _getattribute(module, name)
  784. except (ImportError, KeyError, AttributeError):
  785. raise PicklingError(
  786. "Can't pickle %r: it's not found as %s.%s" %
  787. (obj, module_name, name))
  788. else:
  789. if obj2 is not obj:
  790. raise PicklingError(
  791. "Can't pickle %r: it's not the same object as %s.%s" %
  792. (obj, module_name, name))
  793. if self.proto >= 2:
  794. code = _extension_registry.get((module_name, name))
  795. if code:
  796. assert code > 0
  797. if code <= 0xff:
  798. write(EXT1 + pack("<B", code))
  799. elif code <= 0xffff:
  800. write(EXT2 + pack("<H", code))
  801. else:
  802. write(EXT4 + pack("<i", code))
  803. return
  804. lastname = name.rpartition('.')[2]
  805. if parent is module:
  806. name = lastname
  807. # Non-ASCII identifiers are supported only with protocols >= 3.
  808. if self.proto >= 4:
  809. self.save(module_name)
  810. self.save(name)
  811. write(STACK_GLOBAL)
  812. elif parent is not module:
  813. self.save_reduce(getattr, (parent, lastname))
  814. elif self.proto >= 3:
  815. write(GLOBAL + bytes(module_name, "utf-8") + b'\n' +
  816. bytes(name, "utf-8") + b'\n')
  817. else:
  818. if self.fix_imports:
  819. r_name_mapping = _compat_pickle.REVERSE_NAME_MAPPING
  820. r_import_mapping = _compat_pickle.REVERSE_IMPORT_MAPPING
  821. if (module_name, name) in r_name_mapping:
  822. module_name, name = r_name_mapping[(module_name, name)]
  823. elif module_name in r_import_mapping:
  824. module_name = r_import_mapping[module_name]
  825. try:
  826. write(GLOBAL + bytes(module_name, "ascii") + b'\n' +
  827. bytes(name, "ascii") + b'\n')
  828. except UnicodeEncodeError:
  829. raise PicklingError(
  830. "can't pickle global identifier '%s.%s' using "
  831. "pickle protocol %i" % (module, name, self.proto))
  832. self.memoize(obj)
  833. def save_type(self, obj):
  834. if obj is type(None):
  835. return self.save_reduce(type, (None,), obj=obj)
  836. elif obj is type(NotImplemented):
  837. return self.save_reduce(type, (NotImplemented,), obj=obj)
  838. elif obj is type(...):
  839. return self.save_reduce(type, (...,), obj=obj)
  840. return self.save_global(obj)
  841. dispatch[FunctionType] = save_global
  842. dispatch[type] = save_type
  843. # Unpickling machinery
  844. class _Unpickler:
  845. def __init__(self, file, *, fix_imports=True,
  846. encoding="ASCII", errors="strict"):
  847. """This takes a binary file for reading a pickle data stream.
  848. The protocol version of the pickle is detected automatically, so
  849. no proto argument is needed.
  850. The argument *file* must have two methods, a read() method that
  851. takes an integer argument, and a readline() method that requires
  852. no arguments. Both methods should return bytes. Thus *file*
  853. can be a binary file object opened for reading, a io.BytesIO
  854. object, or any other custom object that meets this interface.
  855. The file-like object must have two methods, a read() method
  856. that takes an integer argument, and a readline() method that
  857. requires no arguments. Both methods should return bytes.
  858. Thus file-like object can be a binary file object opened for
  859. reading, a BytesIO object, or any other custom object that
  860. meets this interface.
  861. Optional keyword arguments are *fix_imports*, *encoding* and
  862. *errors*, which are used to control compatiblity support for
  863. pickle stream generated by Python 2. If *fix_imports* is True,
  864. pickle will try to map the old Python 2 names to the new names
  865. used in Python 3. The *encoding* and *errors* tell pickle how
  866. to decode 8-bit string instances pickled by Python 2; these
  867. default to 'ASCII' and 'strict', respectively. *encoding* can be
  868. 'bytes' to read theses 8-bit string instances as bytes objects.
  869. """
  870. self._file_readline = file.readline
  871. self._file_read = file.read
  872. self.memo = {}
  873. self.encoding = encoding
  874. self.errors = errors
  875. self.proto = 0
  876. self.fix_imports = fix_imports
  877. def load(self):
  878. """Read a pickled object representation from the open file.
  879. Return the reconstituted object hierarchy specified in the file.
  880. """
  881. # Check whether Unpickler was initialized correctly. This is
  882. # only needed to mimic the behavior of _pickle.Unpickler.dump().
  883. if not hasattr(self, "_file_read"):
  884. raise UnpicklingError("Unpickler.__init__() was not called by "
  885. "%s.__init__()" % (self.__class__.__name__,))
  886. self._unframer = _Unframer(self._file_read, self._file_readline)
  887. self.read = self._unframer.read
  888. self.readline = self._unframer.readline
  889. self.mark = object() # any new unique object
  890. self.stack = []
  891. self.append = self.stack.append
  892. self.proto = 0
  893. read = self.read
  894. dispatch = self.dispatch
  895. try:
  896. while True:
  897. key = read(1)
  898. if not key:
  899. raise EOFError
  900. assert isinstance(key, bytes_types)
  901. dispatch[key[0]](self)
  902. except _Stop as stopinst:
  903. return stopinst.value
  904. # Return largest index k such that self.stack[k] is self.mark.
  905. # If the stack doesn't contain a mark, eventually raises IndexError.
  906. # This could be sped by maintaining another stack, of indices at which
  907. # the mark appears. For that matter, the latter stack would suffice,
  908. # and we wouldn't need to push mark objects on self.stack at all.
  909. # Doing so is probably a good thing, though, since if the pickle is
  910. # corrupt (or hostile) we may get a clue from finding self.mark embedded
  911. # in unpickled objects.
  912. def marker(self):
  913. stack = self.stack
  914. mark = self.mark
  915. k = len(stack)-1
  916. while stack[k] is not mark: k = k-1
  917. return k
  918. def persistent_load(self, pid):
  919. raise UnpicklingError("unsupported persistent id encountered")
  920. dispatch = {}
  921. def load_proto(self):
  922. proto = self.read(1)[0]
  923. if not 0 <= proto <= HIGHEST_PROTOCOL:
  924. raise ValueError("unsupported pickle protocol: %d" % proto)
  925. self.proto = proto
  926. dispatch[PROTO[0]] = load_proto
  927. def load_frame(self):
  928. frame_size, = unpack('<Q', self.read(8))
  929. if frame_size > sys.maxsize:
  930. raise ValueError("frame size > sys.maxsize: %d" % frame_size)
  931. self._unframer.load_frame(frame_size)
  932. dispatch[FRAME[0]] = load_frame
  933. def load_persid(self):
  934. pid = self.readline()[:-1].decode("ascii")
  935. self.append(self.persistent_load(pid))
  936. dispatch[PERSID[0]] = load_persid
  937. def load_binpersid(self):
  938. pid = self.stack.pop()
  939. self.append(self.persistent_load(pid))
  940. dispatch[BINPERSID[0]] = load_binpersid
  941. def load_none(self):
  942. self.append(None)
  943. dispatch[NONE[0]] = load_none
  944. def load_false(self):
  945. self.append(False)
  946. dispatch[NEWFALSE[0]] = load_false
  947. def load_true(self):
  948. self.append(True)
  949. dispatch[NEWTRUE[0]] = load_true
  950. def load_int(self):
  951. data = self.readline()
  952. if data == FALSE[1:]:
  953. val = False
  954. elif data == TRUE[1:]:
  955. val = True
  956. else:
  957. val = int(data, 0)
  958. self.append(val)
  959. dispatch[INT[0]] = load_int
  960. def load_binint(self):
  961. self.append(unpack('<i', self.read(4))[0])
  962. dispatch[BININT[0]] = load_binint
  963. def load_binint1(self):
  964. self.append(self.read(1)[0])
  965. dispatch[BININT1[0]] = load_binint1
  966. def load_binint2(self):
  967. self.append(unpack('<H', self.read(2))[0])
  968. dispatch[BININT2[0]] = load_binint2
  969. def load_long(self):
  970. val = self.readline()[:-1]
  971. if val and val[-1] == b'L'[0]:
  972. val = val[:-1]
  973. self.append(int(val, 0))
  974. dispatch[LONG[0]] = load_long
  975. def load_long1(self):
  976. n = self.read(1)[0]
  977. data = self.read(n)
  978. self.append(decode_long(data))
  979. dispatch[LONG1[0]] = load_long1
  980. def load_long4(self):
  981. n, = unpack('<i', self.read(4))
  982. if n < 0:
  983. # Corrupt or hostile pickle -- we never write one like this
  984. raise UnpicklingError("LONG pickle has negative byte count")
  985. data = self.read(n)
  986. self.append(decode_long(data))
  987. dispatch[LONG4[0]] = load_long4
  988. def load_float(self):
  989. self.append(float(self.readline()[:-1]))
  990. dispatch[FLOAT[0]] = load_float
  991. def load_binfloat(self):
  992. self.append(unpack('>d', self.read(8))[0])
  993. dispatch[BINFLOAT[0]] = load_binfloat
  994. def _decode_string(self, value):
  995. # Used to allow strings from Python 2 to be decoded either as
  996. # bytes or Unicode strings. This should be used only with the
  997. # STRING, BINSTRING and SHORT_BINSTRING opcodes.
  998. if self.encoding == "bytes":
  999. return value
  1000. else:
  1001. return value.decode(self.encoding, self.errors)
  1002. def load_string(self):
  1003. data = self.readline()[:-1]
  1004. # Strip outermost quotes
  1005. if len(data) >= 2 and data[0] == data[-1] and data[0] in b'"\'':
  1006. data = data[1:-1]
  1007. else:
  1008. raise UnpicklingError("the STRING opcode argument must be quoted")
  1009. self.append(self._decode_string(codecs.escape_decode(data)[0]))
  1010. dispatch[STRING[0]] = load_string
  1011. def load_binstring(self):
  1012. # Deprecated BINSTRING uses signed 32-bit length
  1013. len, = unpack('<i', self.read(4))
  1014. if len < 0:
  1015. raise UnpicklingError("BINSTRING pickle has negative byte count")
  1016. data = self.read(len)
  1017. self.append(self._decode_string(data))
  1018. dispatch[BINSTRING[0]] = load_binstring
  1019. def load_binbytes(self):
  1020. len, = unpack('<I', self.read(4))
  1021. if len > maxsize:
  1022. raise UnpicklingError("BINBYTES exceeds system's maximum size "
  1023. "of %d bytes" % maxsize)
  1024. self.append(self.read(len))
  1025. dispatch[BINBYTES[0]] = load_binbytes
  1026. def load_unicode(self):
  1027. self.append(str(self.readline()[:-1], 'raw-unicode-escape'))
  1028. dispatch[UNICODE[0]] = load_unicode
  1029. def load_binunicode(self):
  1030. len, = unpack('<I', self.read(4))
  1031. if len > maxsize:
  1032. raise UnpicklingError("BINUNICODE exceeds system's maximum size "
  1033. "of %d bytes" % maxsize)
  1034. self.append(str(self.read(len), 'utf-8', 'surrogatepass'))
  1035. dispatch[BINUNICODE[0]] = load_binunicode
  1036. def load_binunicode8(self):
  1037. len, = unpack('<Q', self.read(8))
  1038. if len > maxsize:
  1039. raise UnpicklingError("BINUNICODE8 exceeds system's maximum size "
  1040. "of %d bytes" % maxsize)
  1041. self.append(str(self.read(len), 'utf-8', 'surrogatepass'))
  1042. dispatch[BINUNICODE8[0]] = load_binunicode8
  1043. def load_binbytes8(self):
  1044. len, = unpack('<Q', self.read(8))
  1045. if len > maxsize:
  1046. raise UnpicklingError("BINBYTES8 exceeds system's maximum size "
  1047. "of %d bytes" % maxsize)
  1048. self.append(self.read(len))
  1049. dispatch[BINBYTES8[0]] = load_binbytes8
  1050. def load_short_binstring(self):
  1051. len = self.read(1)[0]
  1052. data = self.read(len)
  1053. self.append(self._decode_string(data))
  1054. dispatch[SHORT_BINSTRING[0]] = load_short_binstring
  1055. def load_short_binbytes(self):
  1056. len = self.read(1)[0]
  1057. self.append(self.read(len))
  1058. dispatch[SHORT_BINBYTES[0]] = load_short_binbytes
  1059. def load_short_binunicode(self):
  1060. len = self.read(1)[0]
  1061. self.append(str(self.read(len), 'utf-8', 'surrogatepass'))
  1062. dispatch[SHORT_BINUNICODE[0]] = load_short_binunicode
  1063. def load_tuple(self):
  1064. k = self.marker()
  1065. self.stack[k:] = [tuple(self.stack[k+1:])]
  1066. dispatch[TUPLE[0]] = load_tuple
  1067. def load_empty_tuple(self):
  1068. self.append(())
  1069. dispatch[EMPTY_TUPLE[0]] = load_empty_tuple
  1070. def load_tuple1(self):
  1071. self.stack[-1] = (self.stack[-1],)
  1072. dispatch[TUPLE1[0]] = load_tuple1
  1073. def load_tuple2(self):
  1074. self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
  1075. dispatch[TUPLE2[0]] = load_tuple2
  1076. def load_tuple3(self):
  1077. self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
  1078. dispatch[TUPLE3[0]] = load_tuple3
  1079. def load_empty_list(self):
  1080. self.append([])
  1081. dispatch[EMPTY_LIST[0]] = load_empty_list
  1082. def load_empty_dictionary(self):
  1083. self.append({})
  1084. dispatch[EMPTY_DICT[0]] = load_empty_dictionary
  1085. def load_empty_set(self):
  1086. self.append(set())
  1087. dispatch[EMPTY_SET[0]] = load_empty_set
  1088. def load_frozenset(self):
  1089. k = self.marker()
  1090. self.stack[k:] = [frozenset(self.stack[k+1:])]
  1091. dispatch[FROZENSET[0]] = load_frozenset
  1092. def load_list(self):
  1093. k = self.marker()
  1094. self.stack[k:] = [self.stack[k+1:]]
  1095. dispatch[LIST[0]] = load_list
  1096. def load_dict(self):
  1097. k = self.marker()
  1098. items = self.stack[k+1:]
  1099. d = {items[i]: items[i+1]
  1100. for i in range(0, len(items), 2)}
  1101. self.stack[k:] = [d]
  1102. dispatch[DICT[0]] = load_dict
  1103. # INST and OBJ differ only in how they get a class object. It's not
  1104. # only sensible to do the rest in a common routine, the two routines
  1105. # previously diverged and grew different bugs.
  1106. # klass is the class to instantiate, and k points to the topmost mark
  1107. # object, following which are the arguments for klass.__init__.
  1108. def _instantiate(self, klass, k):
  1109. args = tuple(self.stack[k+1:])
  1110. del self.stack[k:]
  1111. if (args or not isinstance(klass, type) or
  1112. hasattr(klass, "__getinitargs__")):
  1113. try:
  1114. value = klass(*args)
  1115. except TypeError as err:
  1116. raise TypeError("in constructor for %s: %s" %
  1117. (klass.__name__, str(err)), sys.exc_info()[2])
  1118. else:
  1119. value = klass.__new__(klass)
  1120. self.append(value)
  1121. def load_inst(self):
  1122. module = self.readline()[:-1].decode("ascii")
  1123. name = self.readline()[:-1].decode("ascii")
  1124. klass = self.find_class(module, name)
  1125. self._instantiate(klass, self.marker())
  1126. dispatch[INST[0]] = load_inst
  1127. def load_obj(self):
  1128. # Stack is ... markobject classobject arg1 arg2 ...
  1129. k = self.marker()
  1130. klass = self.stack.pop(k+1)
  1131. self._instantiate(klass, k)
  1132. dispatch[OBJ[0]] = load_obj
  1133. def load_newobj(self):
  1134. args = self.stack.pop()
  1135. cls = self.stack.pop()
  1136. obj = cls.__new__(cls, *args)
  1137. self.append(obj)
  1138. dispatch[NEWOBJ[0]] = load_newobj
  1139. def load_newobj_ex(self):
  1140. kwargs = self.stack.pop()
  1141. args = self.stack.pop()
  1142. cls = self.stack.pop()
  1143. obj = cls.__new__(cls, *args, **kwargs)
  1144. self.append(obj)
  1145. dispatch[NEWOBJ_EX[0]] = load_newobj_ex
  1146. def load_global(self):
  1147. module = self.readline()[:-1].decode("utf-8")
  1148. name = self.readline()[:-1].decode("utf-8")
  1149. klass = self.find_class(module, name)
  1150. self.append(klass)
  1151. dispatch[GLOBAL[0]] = load_global
  1152. def load_stack_global(self):
  1153. name = self.stack.pop()
  1154. module = self.stack.pop()
  1155. if type(name) is not str or type(module) is not str:
  1156. raise UnpicklingError("STACK_GLOBAL requires str")
  1157. self.append(self.find_class(module, name))
  1158. dispatch[STACK_GLOBAL[0]] = load_stack_global
  1159. def load_ext1(self):
  1160. code = self.read(1)[0]
  1161. self.get_extension(code)
  1162. dispatch[EXT1[0]] = load_ext1
  1163. def load_ext2(self):
  1164. code, = unpack('<H', self.read(2))
  1165. self.get_extension(code)
  1166. dispatch[EXT2[0]] = load_ext2
  1167. def load_ext4(self):
  1168. code, = unpack('<i', self.read(4))
  1169. self.get_extension(code)
  1170. dispatch[EXT4[0]] = load_ext4
  1171. def get_extension(self, code):
  1172. nil = []
  1173. obj = _extension_cache.get(code, nil)
  1174. if obj is not nil:
  1175. self.append(obj)
  1176. return
  1177. key = _inverted_registry.get(code)
  1178. if not key:
  1179. if code <= 0: # note that 0 is forbidden
  1180. # Corrupt or hostile pickle.
  1181. raise UnpicklingError("EXT specifies code <= 0")
  1182. raise ValueError("unregistered extension code %d" % code)
  1183. obj = self.find_class(*key)
  1184. _extension_cache[code] = obj
  1185. self.append(obj)
  1186. def find_class(self, module, name):
  1187. # Subclasses may override this.
  1188. if self.proto < 3 and self.fix_imports:
  1189. if (module, name) in _compat_pickle.NAME_MAPPING:
  1190. module, name = _compat_pickle.NAME_MAPPING[(module, name)]
  1191. elif module in _compat_pickle.IMPORT_MAPPING:
  1192. module = _compat_pickle.IMPORT_MAPPING[module]
  1193. __import__(module, level=0)
  1194. if self.proto >= 4:
  1195. return _getattribute(sys.modules[module], name)[0]
  1196. else:
  1197. return getattr(sys.modules[module], name)
  1198. def load_reduce(self):
  1199. stack = self.stack
  1200. args = stack.pop()
  1201. func = stack[-1]
  1202. try:
  1203. value = func(*args)
  1204. except:
  1205. print(sys.exc_info())
  1206. print(func, args)
  1207. raise
  1208. stack[-1] = value
  1209. dispatch[REDUCE[0]] = load_reduce
  1210. def load_pop(self):
  1211. del self.stack[-1]
  1212. dispatch[POP[0]] = load_pop
  1213. def load_pop_mark(self):
  1214. k = self.marker()
  1215. del self.stack[k:]
  1216. dispatch[POP_MARK[0]] = load_pop_mark
  1217. def load_dup(self):
  1218. self.append(self.stack[-1])
  1219. dispatch[DUP[0]] = load_dup
  1220. def load_get(self):
  1221. i = int(self.readline()[:-1])
  1222. self.append(self.memo[i])
  1223. dispatch[GET[0]] = load_get
  1224. def load_binget(self):
  1225. i = self.read(1)[0]
  1226. self.append(self.memo[i])
  1227. dispatch[BINGET[0]] = load_binget
  1228. def load_long_binget(self):
  1229. i, = unpack('<I', self.read(4))
  1230. self.append(self.memo[i])
  1231. dispatch[LONG_BINGET[0]] = load_long_binget
  1232. def load_put(self):
  1233. i = int(self.readline()[:-1])
  1234. if i < 0:
  1235. raise ValueError("negative PUT argument")
  1236. self.memo[i] = self.stack[-1]
  1237. dispatch[PUT[0]] = load_put
  1238. def load_binput(self):
  1239. i = self.read(1)[0]
  1240. if i < 0:
  1241. raise ValueError("negative BINPUT argument")
  1242. self.memo[i] = self.stack[-1]
  1243. dispatch[BINPUT[0]] = load_binput
  1244. def load_long_binput(self):
  1245. i, = unpack('<I', self.read(4))
  1246. if i > maxsize:
  1247. raise ValueError("negative LONG_BINPUT argument")
  1248. self.memo[i] = self.stack[-1]
  1249. dispatch[LONG_BINPUT[0]] = load_long_binput
  1250. def load_memoize(self):
  1251. memo = self.memo
  1252. memo[len(memo)] = self.stack[-1]
  1253. dispatch[MEMOIZE[0]] = load_memoize
  1254. def load_append(self):
  1255. stack = self.stack
  1256. value = stack.pop()
  1257. list = stack[-1]
  1258. list.append(value)
  1259. dispatch[APPEND[0]] = load_append
  1260. def load_appends(self):
  1261. stack = self.stack
  1262. mark = self.marker()
  1263. list_obj = stack[mark - 1]
  1264. items = stack[mark + 1:]
  1265. if isinstance(list_obj, list):
  1266. list_obj.extend(items)
  1267. else:
  1268. append = list_obj.append
  1269. for item in items:
  1270. append(item)
  1271. del stack[mark:]
  1272. dispatch[APPENDS[0]] = load_appends
  1273. def load_setitem(self):
  1274. stack = self.stack
  1275. value = stack.pop()
  1276. key = stack.pop()
  1277. dict = stack[-1]
  1278. dict[key] = value
  1279. dispatch[SETITEM[0]] = load_setitem
  1280. def load_setitems(self):
  1281. stack = self.stack
  1282. mark = self.marker()
  1283. dict = stack[mark - 1]
  1284. for i in range(mark + 1, len(stack), 2):
  1285. dict[stack[i]] = stack[i + 1]
  1286. del stack[mark:]
  1287. dispatch[SETITEMS[0]] = load_setitems
  1288. def load_additems(self):
  1289. stack = self.stack
  1290. mark = self.marker()
  1291. set_obj = stack[mark - 1]
  1292. items = stack[mark + 1:]
  1293. if isinstance(set_obj, set):
  1294. set_obj.update(items)
  1295. else:
  1296. add = set_obj.add
  1297. for item in items:
  1298. add(item)
  1299. del stack[mark:]
  1300. dispatch[ADDITEMS[0]] = load_additems
  1301. def load_build(self):
  1302. stack = self.stack
  1303. state = stack.pop()
  1304. inst = stack[-1]
  1305. setstate = getattr(inst, "__setstate__", None)
  1306. if setstate is not None:
  1307. setstate(state)
  1308. return
  1309. slotstate = None
  1310. if isinstance(state, tuple) and len(state) == 2:
  1311. state, slotstate = state
  1312. if state:
  1313. inst_dict = inst.__dict__
  1314. intern = sys.intern
  1315. for k, v in state.items():
  1316. if type(k) is str:
  1317. inst_dict[intern(k)] = v
  1318. else:
  1319. inst_dict[k] = v
  1320. if slotstate:
  1321. for k, v in slotstate.items():
  1322. setattr(inst, k, v)
  1323. dispatch[BUILD[0]] = load_build
  1324. def load_mark(self):
  1325. self.append(self.mark)
  1326. dispatch[MARK[0]] = load_mark
  1327. def load_stop(self):
  1328. value = self.stack.pop()
  1329. raise _Stop(value)
  1330. dispatch[STOP[0]] = load_stop
  1331. # Shorthands
  1332. def _dump(obj, file, protocol=None, *, fix_imports=True):
  1333. _Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
  1334. def _dumps(obj, protocol=None, *, fix_imports=True):
  1335. f = io.BytesIO()
  1336. _Pickler(f, protocol, fix_imports=fix_imports).dump(obj)
  1337. res = f.getvalue()
  1338. assert isinstance(res, bytes_types)
  1339. return res
  1340. def _load(file, *, fix_imports=True, encoding="ASCII", errors="strict"):
  1341. return _Unpickler(file, fix_imports=fix_imports,
  1342. encoding=encoding, errors=errors).load()
  1343. def _loads(s, *, fix_imports=True, encoding="ASCII", errors="strict"):
  1344. if isinstance(s, str):
  1345. raise TypeError("Can't load pickle from unicode string")
  1346. file = io.BytesIO(s)
  1347. return _Unpickler(file, fix_imports=fix_imports,
  1348. encoding=encoding, errors=errors).load()
  1349. # Use the faster _pickle if possible
  1350. try:
  1351. from _pickle import (
  1352. PickleError,
  1353. PicklingError,
  1354. UnpicklingError,
  1355. Pickler,
  1356. Unpickler,
  1357. dump,
  1358. dumps,
  1359. load,
  1360. loads
  1361. )
  1362. except ImportError:
  1363. Pickler, Unpickler = _Pickler, _Unpickler
  1364. dump, dumps, load, loads = _dump, _dumps, _load, _loads
  1365. # Doctest
  1366. def _test():
  1367. import doctest
  1368. return doctest.testmod()
  1369. if __name__ == "__main__":
  1370. import argparse
  1371. parser = argparse.ArgumentParser(
  1372. description='display contents of the pickle files')
  1373. parser.add_argument(
  1374. 'pickle_file', type=argparse.FileType('br'),
  1375. nargs='*', help='the pickle file')
  1376. parser.add_argument(
  1377. '-t', '--test', action='store_true',
  1378. help='run self-test suite')
  1379. parser.add_argument(
  1380. '-v', action='store_true',
  1381. help='run verbosely; only affects self-test run')
  1382. args = parser.parse_args()
  1383. if args.test:
  1384. _test()
  1385. else:
  1386. if not args.pickle_file:
  1387. parser.print_help()
  1388. else:
  1389. import pprint
  1390. for f in args.pickle_file:
  1391. obj = load(f)
  1392. pprint.pprint(obj)