pickle.py 63 KB

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