pickle.py 63 KB

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