PageRenderTime 67ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/pickletools.py

http://unladen-swallow.googlecode.com/
Python | 2271 lines | 2254 code | 6 blank | 11 comment | 11 complexity | b6b9de2d5986fc864ed0e3e5c39bb97f MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. '''"Executable documentation" for the pickle module.
  2. Extensive comments about the pickle protocols and pickle-machine opcodes
  3. can be found here. Some functions meant for external use:
  4. genops(pickle)
  5. Generate all the opcodes in a pickle, as (opcode, arg, position) triples.
  6. dis(pickle, out=None, memo=None, indentlevel=4)
  7. Print a symbolic disassembly of a pickle.
  8. '''
  9. __all__ = ['dis', 'genops', 'optimize']
  10. # Other ideas:
  11. #
  12. # - A pickle verifier: read a pickle and check it exhaustively for
  13. # well-formedness. dis() does a lot of this already.
  14. #
  15. # - A protocol identifier: examine a pickle and return its protocol number
  16. # (== the highest .proto attr value among all the opcodes in the pickle).
  17. # dis() already prints this info at the end.
  18. #
  19. # - A pickle optimizer: for example, tuple-building code is sometimes more
  20. # elaborate than necessary, catering for the possibility that the tuple
  21. # is recursive. Or lots of times a PUT is generated that's never accessed
  22. # by a later GET.
  23. """
  24. "A pickle" is a program for a virtual pickle machine (PM, but more accurately
  25. called an unpickling machine). It's a sequence of opcodes, interpreted by the
  26. PM, building an arbitrarily complex Python object.
  27. For the most part, the PM is very simple: there are no looping, testing, or
  28. conditional instructions, no arithmetic and no function calls. Opcodes are
  29. executed once each, from first to last, until a STOP opcode is reached.
  30. The PM has two data areas, "the stack" and "the memo".
  31. Many opcodes push Python objects onto the stack; e.g., INT pushes a Python
  32. integer object on the stack, whose value is gotten from a decimal string
  33. literal immediately following the INT opcode in the pickle bytestream. Other
  34. opcodes take Python objects off the stack. The result of unpickling is
  35. whatever object is left on the stack when the final STOP opcode is executed.
  36. The memo is simply an array of objects, or it can be implemented as a dict
  37. mapping little integers to objects. The memo serves as the PM's "long term
  38. memory", and the little integers indexing the memo are akin to variable
  39. names. Some opcodes pop a stack object into the memo at a given index,
  40. and others push a memo object at a given index onto the stack again.
  41. At heart, that's all the PM has. Subtleties arise for these reasons:
  42. + Object identity. Objects can be arbitrarily complex, and subobjects
  43. may be shared (for example, the list [a, a] refers to the same object a
  44. twice). It can be vital that unpickling recreate an isomorphic object
  45. graph, faithfully reproducing sharing.
  46. + Recursive objects. For example, after "L = []; L.append(L)", L is a
  47. list, and L[0] is the same list. This is related to the object identity
  48. point, and some sequences of pickle opcodes are subtle in order to
  49. get the right result in all cases.
  50. + Things pickle doesn't know everything about. Examples of things pickle
  51. does know everything about are Python's builtin scalar and container
  52. types, like ints and tuples. They generally have opcodes dedicated to
  53. them. For things like module references and instances of user-defined
  54. classes, pickle's knowledge is limited. Historically, many enhancements
  55. have been made to the pickle protocol in order to do a better (faster,
  56. and/or more compact) job on those.
  57. + Backward compatibility and micro-optimization. As explained below,
  58. pickle opcodes never go away, not even when better ways to do a thing
  59. get invented. The repertoire of the PM just keeps growing over time.
  60. For example, protocol 0 had two opcodes for building Python integers (INT
  61. and LONG), protocol 1 added three more for more-efficient pickling of short
  62. integers, and protocol 2 added two more for more-efficient pickling of
  63. long integers (before protocol 2, the only ways to pickle a Python long
  64. took time quadratic in the number of digits, for both pickling and
  65. unpickling). "Opcode bloat" isn't so much a subtlety as a source of
  66. wearying complication.
  67. Pickle protocols:
  68. For compatibility, the meaning of a pickle opcode never changes. Instead new
  69. pickle opcodes get added, and each version's unpickler can handle all the
  70. pickle opcodes in all protocol versions to date. So old pickles continue to
  71. be readable forever. The pickler can generally be told to restrict itself to
  72. the subset of opcodes available under previous protocol versions too, so that
  73. users can create pickles under the current version readable by older
  74. versions. However, a pickle does not contain its version number embedded
  75. within it. If an older unpickler tries to read a pickle using a later
  76. protocol, the result is most likely an exception due to seeing an unknown (in
  77. the older unpickler) opcode.
  78. The original pickle used what's now called "protocol 0", and what was called
  79. "text mode" before Python 2.3. The entire pickle bytestream is made up of
  80. printable 7-bit ASCII characters, plus the newline character, in protocol 0.
  81. That's why it was called text mode. Protocol 0 is small and elegant, but
  82. sometimes painfully inefficient.
  83. The second major set of additions is now called "protocol 1", and was called
  84. "binary mode" before Python 2.3. This added many opcodes with arguments
  85. consisting of arbitrary bytes, including NUL bytes and unprintable "high bit"
  86. bytes. Binary mode pickles can be substantially smaller than equivalent
  87. text mode pickles, and sometimes faster too; e.g., BININT represents a 4-byte
  88. int as 4 bytes following the opcode, which is cheaper to unpickle than the
  89. (perhaps) 11-character decimal string attached to INT. Protocol 1 also added
  90. a number of opcodes that operate on many stack elements at once (like APPENDS
  91. and SETITEMS), and "shortcut" opcodes (like EMPTY_DICT and EMPTY_TUPLE).
  92. The third major set of additions came in Python 2.3, and is called "protocol
  93. 2". This added:
  94. - A better way to pickle instances of new-style classes (NEWOBJ).
  95. - A way for a pickle to identify its protocol (PROTO).
  96. - Time- and space- efficient pickling of long ints (LONG{1,4}).
  97. - Shortcuts for small tuples (TUPLE{1,2,3}}.
  98. - Dedicated opcodes for bools (NEWTRUE, NEWFALSE).
  99. - The "extension registry", a vector of popular objects that can be pushed
  100. efficiently by index (EXT{1,2,4}). This is akin to the memo and GET, but
  101. the registry contents are predefined (there's nothing akin to the memo's
  102. PUT).
  103. Another independent change with Python 2.3 is the abandonment of any
  104. pretense that it might be safe to load pickles received from untrusted
  105. parties -- no sufficient security analysis has been done to guarantee
  106. this and there isn't a use case that warrants the expense of such an
  107. analysis.
  108. To this end, all tests for __safe_for_unpickling__ or for
  109. copy_reg.safe_constructors are removed from the unpickling code.
  110. References to these variables in the descriptions below are to be seen
  111. as describing unpickling in Python 2.2 and before.
  112. """
  113. # Meta-rule: Descriptions are stored in instances of descriptor objects,
  114. # with plain constructors. No meta-language is defined from which
  115. # descriptors could be constructed. If you want, e.g., XML, write a little
  116. # program to generate XML from the objects.
  117. ##############################################################################
  118. # Some pickle opcodes have an argument, following the opcode in the
  119. # bytestream. An argument is of a specific type, described by an instance
  120. # of ArgumentDescriptor. These are not to be confused with arguments taken
  121. # off the stack -- ArgumentDescriptor applies only to arguments embedded in
  122. # the opcode stream, immediately following an opcode.
  123. # Represents the number of bytes consumed by an argument delimited by the
  124. # next newline character.
  125. UP_TO_NEWLINE = -1
  126. # Represents the number of bytes consumed by a two-argument opcode where
  127. # the first argument gives the number of bytes in the second argument.
  128. TAKEN_FROM_ARGUMENT1 = -2 # num bytes is 1-byte unsigned int
  129. TAKEN_FROM_ARGUMENT4 = -3 # num bytes is 4-byte signed little-endian int
  130. class ArgumentDescriptor(object):
  131. __slots__ = (
  132. # name of descriptor record, also a module global name; a string
  133. 'name',
  134. # length of argument, in bytes; an int; UP_TO_NEWLINE and
  135. # TAKEN_FROM_ARGUMENT{1,4} are negative values for variable-length
  136. # cases
  137. 'n',
  138. # a function taking a file-like object, reading this kind of argument
  139. # from the object at the current position, advancing the current
  140. # position by n bytes, and returning the value of the argument
  141. 'reader',
  142. # human-readable docs for this arg descriptor; a string
  143. 'doc',
  144. )
  145. def __init__(self, name, n, reader, doc):
  146. assert isinstance(name, str)
  147. self.name = name
  148. assert isinstance(n, int) and (n >= 0 or
  149. n in (UP_TO_NEWLINE,
  150. TAKEN_FROM_ARGUMENT1,
  151. TAKEN_FROM_ARGUMENT4))
  152. self.n = n
  153. self.reader = reader
  154. assert isinstance(doc, str)
  155. self.doc = doc
  156. from struct import unpack as _unpack
  157. def read_uint1(f):
  158. r"""
  159. >>> import StringIO
  160. >>> read_uint1(StringIO.StringIO('\xff'))
  161. 255
  162. """
  163. data = f.read(1)
  164. if data:
  165. return ord(data)
  166. raise ValueError("not enough data in stream to read uint1")
  167. uint1 = ArgumentDescriptor(
  168. name='uint1',
  169. n=1,
  170. reader=read_uint1,
  171. doc="One-byte unsigned integer.")
  172. def read_uint2(f):
  173. r"""
  174. >>> import StringIO
  175. >>> read_uint2(StringIO.StringIO('\xff\x00'))
  176. 255
  177. >>> read_uint2(StringIO.StringIO('\xff\xff'))
  178. 65535
  179. """
  180. data = f.read(2)
  181. if len(data) == 2:
  182. return _unpack("<H", data)[0]
  183. raise ValueError("not enough data in stream to read uint2")
  184. uint2 = ArgumentDescriptor(
  185. name='uint2',
  186. n=2,
  187. reader=read_uint2,
  188. doc="Two-byte unsigned integer, little-endian.")
  189. def read_int4(f):
  190. r"""
  191. >>> import StringIO
  192. >>> read_int4(StringIO.StringIO('\xff\x00\x00\x00'))
  193. 255
  194. >>> read_int4(StringIO.StringIO('\x00\x00\x00\x80')) == -(2**31)
  195. True
  196. """
  197. data = f.read(4)
  198. if len(data) == 4:
  199. return _unpack("<i", data)[0]
  200. raise ValueError("not enough data in stream to read int4")
  201. int4 = ArgumentDescriptor(
  202. name='int4',
  203. n=4,
  204. reader=read_int4,
  205. doc="Four-byte signed integer, little-endian, 2's complement.")
  206. def read_stringnl(f, decode=True, stripquotes=True):
  207. r"""
  208. >>> import StringIO
  209. >>> read_stringnl(StringIO.StringIO("'abcd'\nefg\n"))
  210. 'abcd'
  211. >>> read_stringnl(StringIO.StringIO("\n"))
  212. Traceback (most recent call last):
  213. ...
  214. ValueError: no string quotes around ''
  215. >>> read_stringnl(StringIO.StringIO("\n"), stripquotes=False)
  216. ''
  217. >>> read_stringnl(StringIO.StringIO("''\n"))
  218. ''
  219. >>> read_stringnl(StringIO.StringIO('"abcd"'))
  220. Traceback (most recent call last):
  221. ...
  222. ValueError: no newline found when trying to read stringnl
  223. Embedded escapes are undone in the result.
  224. >>> read_stringnl(StringIO.StringIO(r"'a\n\\b\x00c\td'" + "\n'e'"))
  225. 'a\n\\b\x00c\td'
  226. """
  227. data = f.readline()
  228. if not data.endswith('\n'):
  229. raise ValueError("no newline found when trying to read stringnl")
  230. data = data[:-1] # lose the newline
  231. if stripquotes:
  232. for q in "'\"":
  233. if data.startswith(q):
  234. if not data.endswith(q):
  235. raise ValueError("strinq quote %r not found at both "
  236. "ends of %r" % (q, data))
  237. data = data[1:-1]
  238. break
  239. else:
  240. raise ValueError("no string quotes around %r" % data)
  241. # I'm not sure when 'string_escape' was added to the std codecs; it's
  242. # crazy not to use it if it's there.
  243. if decode:
  244. data = data.decode('string_escape')
  245. return data
  246. stringnl = ArgumentDescriptor(
  247. name='stringnl',
  248. n=UP_TO_NEWLINE,
  249. reader=read_stringnl,
  250. doc="""A newline-terminated string.
  251. This is a repr-style string, with embedded escapes, and
  252. bracketing quotes.
  253. """)
  254. def read_stringnl_noescape(f):
  255. return read_stringnl(f, decode=False, stripquotes=False)
  256. stringnl_noescape = ArgumentDescriptor(
  257. name='stringnl_noescape',
  258. n=UP_TO_NEWLINE,
  259. reader=read_stringnl_noescape,
  260. doc="""A newline-terminated string.
  261. This is a str-style string, without embedded escapes,
  262. or bracketing quotes. It should consist solely of
  263. printable ASCII characters.
  264. """)
  265. def read_stringnl_noescape_pair(f):
  266. r"""
  267. >>> import StringIO
  268. >>> read_stringnl_noescape_pair(StringIO.StringIO("Queue\nEmpty\njunk"))
  269. 'Queue Empty'
  270. """
  271. return "%s %s" % (read_stringnl_noescape(f), read_stringnl_noescape(f))
  272. stringnl_noescape_pair = ArgumentDescriptor(
  273. name='stringnl_noescape_pair',
  274. n=UP_TO_NEWLINE,
  275. reader=read_stringnl_noescape_pair,
  276. doc="""A pair of newline-terminated strings.
  277. These are str-style strings, without embedded
  278. escapes, or bracketing quotes. They should
  279. consist solely of printable ASCII characters.
  280. The pair is returned as a single string, with
  281. a single blank separating the two strings.
  282. """)
  283. def read_string4(f):
  284. r"""
  285. >>> import StringIO
  286. >>> read_string4(StringIO.StringIO("\x00\x00\x00\x00abc"))
  287. ''
  288. >>> read_string4(StringIO.StringIO("\x03\x00\x00\x00abcdef"))
  289. 'abc'
  290. >>> read_string4(StringIO.StringIO("\x00\x00\x00\x03abcdef"))
  291. Traceback (most recent call last):
  292. ...
  293. ValueError: expected 50331648 bytes in a string4, but only 6 remain
  294. """
  295. n = read_int4(f)
  296. if n < 0:
  297. raise ValueError("string4 byte count < 0: %d" % n)
  298. data = f.read(n)
  299. if len(data) == n:
  300. return data
  301. raise ValueError("expected %d bytes in a string4, but only %d remain" %
  302. (n, len(data)))
  303. string4 = ArgumentDescriptor(
  304. name="string4",
  305. n=TAKEN_FROM_ARGUMENT4,
  306. reader=read_string4,
  307. doc="""A counted string.
  308. The first argument is a 4-byte little-endian signed int giving
  309. the number of bytes in the string, and the second argument is
  310. that many bytes.
  311. """)
  312. def read_string1(f):
  313. r"""
  314. >>> import StringIO
  315. >>> read_string1(StringIO.StringIO("\x00"))
  316. ''
  317. >>> read_string1(StringIO.StringIO("\x03abcdef"))
  318. 'abc'
  319. """
  320. n = read_uint1(f)
  321. assert n >= 0
  322. data = f.read(n)
  323. if len(data) == n:
  324. return data
  325. raise ValueError("expected %d bytes in a string1, but only %d remain" %
  326. (n, len(data)))
  327. string1 = ArgumentDescriptor(
  328. name="string1",
  329. n=TAKEN_FROM_ARGUMENT1,
  330. reader=read_string1,
  331. doc="""A counted string.
  332. The first argument is a 1-byte unsigned int giving the number
  333. of bytes in the string, and the second argument is that many
  334. bytes.
  335. """)
  336. def read_unicodestringnl(f):
  337. r"""
  338. >>> import StringIO
  339. >>> read_unicodestringnl(StringIO.StringIO("abc\uabcd\njunk"))
  340. u'abc\uabcd'
  341. """
  342. data = f.readline()
  343. if not data.endswith('\n'):
  344. raise ValueError("no newline found when trying to read "
  345. "unicodestringnl")
  346. data = data[:-1] # lose the newline
  347. return unicode(data, 'raw-unicode-escape')
  348. unicodestringnl = ArgumentDescriptor(
  349. name='unicodestringnl',
  350. n=UP_TO_NEWLINE,
  351. reader=read_unicodestringnl,
  352. doc="""A newline-terminated Unicode string.
  353. This is raw-unicode-escape encoded, so consists of
  354. printable ASCII characters, and may contain embedded
  355. escape sequences.
  356. """)
  357. def read_unicodestring4(f):
  358. r"""
  359. >>> import StringIO
  360. >>> s = u'abcd\uabcd'
  361. >>> enc = s.encode('utf-8')
  362. >>> enc
  363. 'abcd\xea\xaf\x8d'
  364. >>> n = chr(len(enc)) + chr(0) * 3 # little-endian 4-byte length
  365. >>> t = read_unicodestring4(StringIO.StringIO(n + enc + 'junk'))
  366. >>> s == t
  367. True
  368. >>> read_unicodestring4(StringIO.StringIO(n + enc[:-1]))
  369. Traceback (most recent call last):
  370. ...
  371. ValueError: expected 7 bytes in a unicodestring4, but only 6 remain
  372. """
  373. n = read_int4(f)
  374. if n < 0:
  375. raise ValueError("unicodestring4 byte count < 0: %d" % n)
  376. data = f.read(n)
  377. if len(data) == n:
  378. return unicode(data, 'utf-8')
  379. raise ValueError("expected %d bytes in a unicodestring4, but only %d "
  380. "remain" % (n, len(data)))
  381. unicodestring4 = ArgumentDescriptor(
  382. name="unicodestring4",
  383. n=TAKEN_FROM_ARGUMENT4,
  384. reader=read_unicodestring4,
  385. doc="""A counted Unicode string.
  386. The first argument is a 4-byte little-endian signed int
  387. giving the number of bytes in the string, and the second
  388. argument-- the UTF-8 encoding of the Unicode string --
  389. contains that many bytes.
  390. """)
  391. def read_decimalnl_short(f):
  392. r"""
  393. >>> import StringIO
  394. >>> read_decimalnl_short(StringIO.StringIO("1234\n56"))
  395. 1234
  396. >>> read_decimalnl_short(StringIO.StringIO("1234L\n56"))
  397. Traceback (most recent call last):
  398. ...
  399. ValueError: trailing 'L' not allowed in '1234L'
  400. """
  401. s = read_stringnl(f, decode=False, stripquotes=False)
  402. if s.endswith("L"):
  403. raise ValueError("trailing 'L' not allowed in %r" % s)
  404. # It's not necessarily true that the result fits in a Python short int:
  405. # the pickle may have been written on a 64-bit box. There's also a hack
  406. # for True and False here.
  407. if s == "00":
  408. return False
  409. elif s == "01":
  410. return True
  411. try:
  412. return int(s)
  413. except OverflowError:
  414. return long(s)
  415. def read_decimalnl_long(f):
  416. r"""
  417. >>> import StringIO
  418. >>> read_decimalnl_long(StringIO.StringIO("1234\n56"))
  419. Traceback (most recent call last):
  420. ...
  421. ValueError: trailing 'L' required in '1234'
  422. Someday the trailing 'L' will probably go away from this output.
  423. >>> read_decimalnl_long(StringIO.StringIO("1234L\n56"))
  424. 1234L
  425. >>> read_decimalnl_long(StringIO.StringIO("123456789012345678901234L\n6"))
  426. 123456789012345678901234L
  427. """
  428. s = read_stringnl(f, decode=False, stripquotes=False)
  429. if not s.endswith("L"):
  430. raise ValueError("trailing 'L' required in %r" % s)
  431. return long(s)
  432. decimalnl_short = ArgumentDescriptor(
  433. name='decimalnl_short',
  434. n=UP_TO_NEWLINE,
  435. reader=read_decimalnl_short,
  436. doc="""A newline-terminated decimal integer literal.
  437. This never has a trailing 'L', and the integer fit
  438. in a short Python int on the box where the pickle
  439. was written -- but there's no guarantee it will fit
  440. in a short Python int on the box where the pickle
  441. is read.
  442. """)
  443. decimalnl_long = ArgumentDescriptor(
  444. name='decimalnl_long',
  445. n=UP_TO_NEWLINE,
  446. reader=read_decimalnl_long,
  447. doc="""A newline-terminated decimal integer literal.
  448. This has a trailing 'L', and can represent integers
  449. of any size.
  450. """)
  451. def read_floatnl(f):
  452. r"""
  453. >>> import StringIO
  454. >>> read_floatnl(StringIO.StringIO("-1.25\n6"))
  455. -1.25
  456. """
  457. s = read_stringnl(f, decode=False, stripquotes=False)
  458. return float(s)
  459. floatnl = ArgumentDescriptor(
  460. name='floatnl',
  461. n=UP_TO_NEWLINE,
  462. reader=read_floatnl,
  463. doc="""A newline-terminated decimal floating literal.
  464. In general this requires 17 significant digits for roundtrip
  465. identity, and pickling then unpickling infinities, NaNs, and
  466. minus zero doesn't work across boxes, or on some boxes even
  467. on itself (e.g., Windows can't read the strings it produces
  468. for infinities or NaNs).
  469. """)
  470. def read_float8(f):
  471. r"""
  472. >>> import StringIO, struct
  473. >>> raw = struct.pack(">d", -1.25)
  474. >>> raw
  475. '\xbf\xf4\x00\x00\x00\x00\x00\x00'
  476. >>> read_float8(StringIO.StringIO(raw + "\n"))
  477. -1.25
  478. """
  479. data = f.read(8)
  480. if len(data) == 8:
  481. return _unpack(">d", data)[0]
  482. raise ValueError("not enough data in stream to read float8")
  483. float8 = ArgumentDescriptor(
  484. name='float8',
  485. n=8,
  486. reader=read_float8,
  487. doc="""An 8-byte binary representation of a float, big-endian.
  488. The format is unique to Python, and shared with the struct
  489. module (format string '>d') "in theory" (the struct and cPickle
  490. implementations don't share the code -- they should). It's
  491. strongly related to the IEEE-754 double format, and, in normal
  492. cases, is in fact identical to the big-endian 754 double format.
  493. On other boxes the dynamic range is limited to that of a 754
  494. double, and "add a half and chop" rounding is used to reduce
  495. the precision to 53 bits. However, even on a 754 box,
  496. infinities, NaNs, and minus zero may not be handled correctly
  497. (may not survive roundtrip pickling intact).
  498. """)
  499. # Protocol 2 formats
  500. from pickle import decode_long
  501. def read_long1(f):
  502. r"""
  503. >>> import StringIO
  504. >>> read_long1(StringIO.StringIO("\x00"))
  505. 0L
  506. >>> read_long1(StringIO.StringIO("\x02\xff\x00"))
  507. 255L
  508. >>> read_long1(StringIO.StringIO("\x02\xff\x7f"))
  509. 32767L
  510. >>> read_long1(StringIO.StringIO("\x02\x00\xff"))
  511. -256L
  512. >>> read_long1(StringIO.StringIO("\x02\x00\x80"))
  513. -32768L
  514. """
  515. n = read_uint1(f)
  516. data = f.read(n)
  517. if len(data) != n:
  518. raise ValueError("not enough data in stream to read long1")
  519. return decode_long(data)
  520. long1 = ArgumentDescriptor(
  521. name="long1",
  522. n=TAKEN_FROM_ARGUMENT1,
  523. reader=read_long1,
  524. doc="""A binary long, little-endian, using 1-byte size.
  525. This first reads one byte as an unsigned size, then reads that
  526. many bytes and interprets them as a little-endian 2's-complement long.
  527. If the size is 0, that's taken as a shortcut for the long 0L.
  528. """)
  529. def read_long4(f):
  530. r"""
  531. >>> import StringIO
  532. >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00"))
  533. 255L
  534. >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f"))
  535. 32767L
  536. >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff"))
  537. -256L
  538. >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80"))
  539. -32768L
  540. >>> read_long1(StringIO.StringIO("\x00\x00\x00\x00"))
  541. 0L
  542. """
  543. n = read_int4(f)
  544. if n < 0:
  545. raise ValueError("long4 byte count < 0: %d" % n)
  546. data = f.read(n)
  547. if len(data) != n:
  548. raise ValueError("not enough data in stream to read long4")
  549. return decode_long(data)
  550. long4 = ArgumentDescriptor(
  551. name="long4",
  552. n=TAKEN_FROM_ARGUMENT4,
  553. reader=read_long4,
  554. doc="""A binary representation of a long, little-endian.
  555. This first reads four bytes as a signed size (but requires the
  556. size to be >= 0), then reads that many bytes and interprets them
  557. as a little-endian 2's-complement long. If the size is 0, that's taken
  558. as a shortcut for the long 0L, although LONG1 should really be used
  559. then instead (and in any case where # of bytes < 256).
  560. """)
  561. ##############################################################################
  562. # Object descriptors. The stack used by the pickle machine holds objects,
  563. # and in the stack_before and stack_after attributes of OpcodeInfo
  564. # descriptors we need names to describe the various types of objects that can
  565. # appear on the stack.
  566. class StackObject(object):
  567. __slots__ = (
  568. # name of descriptor record, for info only
  569. 'name',
  570. # type of object, or tuple of type objects (meaning the object can
  571. # be of any type in the tuple)
  572. 'obtype',
  573. # human-readable docs for this kind of stack object; a string
  574. 'doc',
  575. )
  576. def __init__(self, name, obtype, doc):
  577. assert isinstance(name, str)
  578. self.name = name
  579. assert isinstance(obtype, type) or isinstance(obtype, tuple)
  580. if isinstance(obtype, tuple):
  581. for contained in obtype:
  582. assert isinstance(contained, type)
  583. self.obtype = obtype
  584. assert isinstance(doc, str)
  585. self.doc = doc
  586. def __repr__(self):
  587. return self.name
  588. pyint = StackObject(
  589. name='int',
  590. obtype=int,
  591. doc="A short (as opposed to long) Python integer object.")
  592. pylong = StackObject(
  593. name='long',
  594. obtype=long,
  595. doc="A long (as opposed to short) Python integer object.")
  596. pyinteger_or_bool = StackObject(
  597. name='int_or_bool',
  598. obtype=(int, long, bool),
  599. doc="A Python integer object (short or long), or "
  600. "a Python bool.")
  601. pybool = StackObject(
  602. name='bool',
  603. obtype=(bool,),
  604. doc="A Python bool object.")
  605. pyfloat = StackObject(
  606. name='float',
  607. obtype=float,
  608. doc="A Python float object.")
  609. pystring = StackObject(
  610. name='str',
  611. obtype=str,
  612. doc="A Python string object.")
  613. pyunicode = StackObject(
  614. name='unicode',
  615. obtype=unicode,
  616. doc="A Python Unicode string object.")
  617. pynone = StackObject(
  618. name="None",
  619. obtype=type(None),
  620. doc="The Python None object.")
  621. pytuple = StackObject(
  622. name="tuple",
  623. obtype=tuple,
  624. doc="A Python tuple object.")
  625. pylist = StackObject(
  626. name="list",
  627. obtype=list,
  628. doc="A Python list object.")
  629. pydict = StackObject(
  630. name="dict",
  631. obtype=dict,
  632. doc="A Python dict object.")
  633. anyobject = StackObject(
  634. name='any',
  635. obtype=object,
  636. doc="Any kind of object whatsoever.")
  637. markobject = StackObject(
  638. name="mark",
  639. obtype=StackObject,
  640. doc="""'The mark' is a unique object.
  641. Opcodes that operate on a variable number of objects
  642. generally don't embed the count of objects in the opcode,
  643. or pull it off the stack. Instead the MARK opcode is used
  644. to push a special marker object on the stack, and then
  645. some other opcodes grab all the objects from the top of
  646. the stack down to (but not including) the topmost marker
  647. object.
  648. """)
  649. stackslice = StackObject(
  650. name="stackslice",
  651. obtype=StackObject,
  652. doc="""An object representing a contiguous slice of the stack.
  653. This is used in conjuction with markobject, to represent all
  654. of the stack following the topmost markobject. For example,
  655. the POP_MARK opcode changes the stack from
  656. [..., markobject, stackslice]
  657. to
  658. [...]
  659. No matter how many object are on the stack after the topmost
  660. markobject, POP_MARK gets rid of all of them (including the
  661. topmost markobject too).
  662. """)
  663. ##############################################################################
  664. # Descriptors for pickle opcodes.
  665. class OpcodeInfo(object):
  666. __slots__ = (
  667. # symbolic name of opcode; a string
  668. 'name',
  669. # the code used in a bytestream to represent the opcode; a
  670. # one-character string
  671. 'code',
  672. # If the opcode has an argument embedded in the byte string, an
  673. # instance of ArgumentDescriptor specifying its type. Note that
  674. # arg.reader(s) can be used to read and decode the argument from
  675. # the bytestream s, and arg.doc documents the format of the raw
  676. # argument bytes. If the opcode doesn't have an argument embedded
  677. # in the bytestream, arg should be None.
  678. 'arg',
  679. # what the stack looks like before this opcode runs; a list
  680. 'stack_before',
  681. # what the stack looks like after this opcode runs; a list
  682. 'stack_after',
  683. # the protocol number in which this opcode was introduced; an int
  684. 'proto',
  685. # human-readable docs for this opcode; a string
  686. 'doc',
  687. )
  688. def __init__(self, name, code, arg,
  689. stack_before, stack_after, proto, doc):
  690. assert isinstance(name, str)
  691. self.name = name
  692. assert isinstance(code, str)
  693. assert len(code) == 1
  694. self.code = code
  695. assert arg is None or isinstance(arg, ArgumentDescriptor)
  696. self.arg = arg
  697. assert isinstance(stack_before, list)
  698. for x in stack_before:
  699. assert isinstance(x, StackObject)
  700. self.stack_before = stack_before
  701. assert isinstance(stack_after, list)
  702. for x in stack_after:
  703. assert isinstance(x, StackObject)
  704. self.stack_after = stack_after
  705. assert isinstance(proto, int) and 0 <= proto <= 2
  706. self.proto = proto
  707. assert isinstance(doc, str)
  708. self.doc = doc
  709. I = OpcodeInfo
  710. opcodes = [
  711. # Ways to spell integers.
  712. I(name='INT',
  713. code='I',
  714. arg=decimalnl_short,
  715. stack_before=[],
  716. stack_after=[pyinteger_or_bool],
  717. proto=0,
  718. doc="""Push an integer or bool.
  719. The argument is a newline-terminated decimal literal string.
  720. The intent may have been that this always fit in a short Python int,
  721. but INT can be generated in pickles written on a 64-bit box that
  722. require a Python long on a 32-bit box. The difference between this
  723. and LONG then is that INT skips a trailing 'L', and produces a short
  724. int whenever possible.
  725. Another difference is due to that, when bool was introduced as a
  726. distinct type in 2.3, builtin names True and False were also added to
  727. 2.2.2, mapping to ints 1 and 0. For compatibility in both directions,
  728. True gets pickled as INT + "I01\\n", and False as INT + "I00\\n".
  729. Leading zeroes are never produced for a genuine integer. The 2.3
  730. (and later) unpicklers special-case these and return bool instead;
  731. earlier unpicklers ignore the leading "0" and return the int.
  732. """),
  733. I(name='BININT',
  734. code='J',
  735. arg=int4,
  736. stack_before=[],
  737. stack_after=[pyint],
  738. proto=1,
  739. doc="""Push a four-byte signed integer.
  740. This handles the full range of Python (short) integers on a 32-bit
  741. box, directly as binary bytes (1 for the opcode and 4 for the integer).
  742. If the integer is non-negative and fits in 1 or 2 bytes, pickling via
  743. BININT1 or BININT2 saves space.
  744. """),
  745. I(name='BININT1',
  746. code='K',
  747. arg=uint1,
  748. stack_before=[],
  749. stack_after=[pyint],
  750. proto=1,
  751. doc="""Push a one-byte unsigned integer.
  752. This is a space optimization for pickling very small non-negative ints,
  753. in range(256).
  754. """),
  755. I(name='BININT2',
  756. code='M',
  757. arg=uint2,
  758. stack_before=[],
  759. stack_after=[pyint],
  760. proto=1,
  761. doc="""Push a two-byte unsigned integer.
  762. This is a space optimization for pickling small positive ints, in
  763. range(256, 2**16). Integers in range(256) can also be pickled via
  764. BININT2, but BININT1 instead saves a byte.
  765. """),
  766. I(name='LONG',
  767. code='L',
  768. arg=decimalnl_long,
  769. stack_before=[],
  770. stack_after=[pylong],
  771. proto=0,
  772. doc="""Push a long integer.
  773. The same as INT, except that the literal ends with 'L', and always
  774. unpickles to a Python long. There doesn't seem a real purpose to the
  775. trailing 'L'.
  776. Note that LONG takes time quadratic in the number of digits when
  777. unpickling (this is simply due to the nature of decimal->binary
  778. conversion). Proto 2 added linear-time (in C; still quadratic-time
  779. in Python) LONG1 and LONG4 opcodes.
  780. """),
  781. I(name="LONG1",
  782. code='\x8a',
  783. arg=long1,
  784. stack_before=[],
  785. stack_after=[pylong],
  786. proto=2,
  787. doc="""Long integer using one-byte length.
  788. A more efficient encoding of a Python long; the long1 encoding
  789. says it all."""),
  790. I(name="LONG4",
  791. code='\x8b',
  792. arg=long4,
  793. stack_before=[],
  794. stack_after=[pylong],
  795. proto=2,
  796. doc="""Long integer using found-byte length.
  797. A more efficient encoding of a Python long; the long4 encoding
  798. says it all."""),
  799. # Ways to spell strings (8-bit, not Unicode).
  800. I(name='STRING',
  801. code='S',
  802. arg=stringnl,
  803. stack_before=[],
  804. stack_after=[pystring],
  805. proto=0,
  806. doc="""Push a Python string object.
  807. The argument is a repr-style string, with bracketing quote characters,
  808. and perhaps embedded escapes. The argument extends until the next
  809. newline character.
  810. """),
  811. I(name='BINSTRING',
  812. code='T',
  813. arg=string4,
  814. stack_before=[],
  815. stack_after=[pystring],
  816. proto=1,
  817. doc="""Push a Python string object.
  818. There are two arguments: the first is a 4-byte little-endian signed int
  819. giving the number of bytes in the string, and the second is that many
  820. bytes, which are taken literally as the string content.
  821. """),
  822. I(name='SHORT_BINSTRING',
  823. code='U',
  824. arg=string1,
  825. stack_before=[],
  826. stack_after=[pystring],
  827. proto=1,
  828. doc="""Push a Python string object.
  829. There are two arguments: the first is a 1-byte unsigned int giving
  830. the number of bytes in the string, and the second is that many bytes,
  831. which are taken literally as the string content.
  832. """),
  833. # Ways to spell None.
  834. I(name='NONE',
  835. code='N',
  836. arg=None,
  837. stack_before=[],
  838. stack_after=[pynone],
  839. proto=0,
  840. doc="Push None on the stack."),
  841. # Ways to spell bools, starting with proto 2. See INT for how this was
  842. # done before proto 2.
  843. I(name='NEWTRUE',
  844. code='\x88',
  845. arg=None,
  846. stack_before=[],
  847. stack_after=[pybool],
  848. proto=2,
  849. doc="""True.
  850. Push True onto the stack."""),
  851. I(name='NEWFALSE',
  852. code='\x89',
  853. arg=None,
  854. stack_before=[],
  855. stack_after=[pybool],
  856. proto=2,
  857. doc="""True.
  858. Push False onto the stack."""),
  859. # Ways to spell Unicode strings.
  860. I(name='UNICODE',
  861. code='V',
  862. arg=unicodestringnl,
  863. stack_before=[],
  864. stack_after=[pyunicode],
  865. proto=0, # this may be pure-text, but it's a later addition
  866. doc="""Push a Python Unicode string object.
  867. The argument is a raw-unicode-escape encoding of a Unicode string,
  868. and so may contain embedded escape sequences. The argument extends
  869. until the next newline character.
  870. """),
  871. I(name='BINUNICODE',
  872. code='X',
  873. arg=unicodestring4,
  874. stack_before=[],
  875. stack_after=[pyunicode],
  876. proto=1,
  877. doc="""Push a Python Unicode string object.
  878. There are two arguments: the first is a 4-byte little-endian signed int
  879. giving the number of bytes in the string. The second is that many
  880. bytes, and is the UTF-8 encoding of the Unicode string.
  881. """),
  882. # Ways to spell floats.
  883. I(name='FLOAT',
  884. code='F',
  885. arg=floatnl,
  886. stack_before=[],
  887. stack_after=[pyfloat],
  888. proto=0,
  889. doc="""Newline-terminated decimal float literal.
  890. The argument is repr(a_float), and in general requires 17 significant
  891. digits for roundtrip conversion to be an identity (this is so for
  892. IEEE-754 double precision values, which is what Python float maps to
  893. on most boxes).
  894. In general, FLOAT cannot be used to transport infinities, NaNs, or
  895. minus zero across boxes (or even on a single box, if the platform C
  896. library can't read the strings it produces for such things -- Windows
  897. is like that), but may do less damage than BINFLOAT on boxes with
  898. greater precision or dynamic range than IEEE-754 double.
  899. """),
  900. I(name='BINFLOAT',
  901. code='G',
  902. arg=float8,
  903. stack_before=[],
  904. stack_after=[pyfloat],
  905. proto=1,
  906. doc="""Float stored in binary form, with 8 bytes of data.
  907. This generally requires less than half the space of FLOAT encoding.
  908. In general, BINFLOAT cannot be used to transport infinities, NaNs, or
  909. minus zero, raises an exception if the exponent exceeds the range of
  910. an IEEE-754 double, and retains no more than 53 bits of precision (if
  911. there are more than that, "add a half and chop" rounding is used to
  912. cut it back to 53 significant bits).
  913. """),
  914. # Ways to build lists.
  915. I(name='EMPTY_LIST',
  916. code=']',
  917. arg=None,
  918. stack_before=[],
  919. stack_after=[pylist],
  920. proto=1,
  921. doc="Push an empty list."),
  922. I(name='APPEND',
  923. code='a',
  924. arg=None,
  925. stack_before=[pylist, anyobject],
  926. stack_after=[pylist],
  927. proto=0,
  928. doc="""Append an object to a list.
  929. Stack before: ... pylist anyobject
  930. Stack after: ... pylist+[anyobject]
  931. although pylist is really extended in-place.
  932. """),
  933. I(name='APPENDS',
  934. code='e',
  935. arg=None,
  936. stack_before=[pylist, markobject, stackslice],
  937. stack_after=[pylist],
  938. proto=1,
  939. doc="""Extend a list by a slice of stack objects.
  940. Stack before: ... pylist markobject stackslice
  941. Stack after: ... pylist+stackslice
  942. although pylist is really extended in-place.
  943. """),
  944. I(name='LIST',
  945. code='l',
  946. arg=None,
  947. stack_before=[markobject, stackslice],
  948. stack_after=[pylist],
  949. proto=0,
  950. doc="""Build a list out of the topmost stack slice, after markobject.
  951. All the stack entries following the topmost markobject are placed into
  952. a single Python list, which single list object replaces all of the
  953. stack from the topmost markobject onward. For example,
  954. Stack before: ... markobject 1 2 3 'abc'
  955. Stack after: ... [1, 2, 3, 'abc']
  956. """),
  957. # Ways to build tuples.
  958. I(name='EMPTY_TUPLE',
  959. code=')',
  960. arg=None,
  961. stack_before=[],
  962. stack_after=[pytuple],
  963. proto=1,
  964. doc="Push an empty tuple."),
  965. I(name='TUPLE',
  966. code='t',
  967. arg=None,
  968. stack_before=[markobject, stackslice],
  969. stack_after=[pytuple],
  970. proto=0,
  971. doc="""Build a tuple out of the topmost stack slice, after markobject.
  972. All the stack entries following the topmost markobject are placed into
  973. a single Python tuple, which single tuple object replaces all of the
  974. stack from the topmost markobject onward. For example,
  975. Stack before: ... markobject 1 2 3 'abc'
  976. Stack after: ... (1, 2, 3, 'abc')
  977. """),
  978. I(name='TUPLE1',
  979. code='\x85',
  980. arg=None,
  981. stack_before=[anyobject],
  982. stack_after=[pytuple],
  983. proto=2,
  984. doc="""One-tuple.
  985. This code pops one value off the stack and pushes a tuple of
  986. length 1 whose one item is that value back onto it. IOW:
  987. stack[-1] = tuple(stack[-1:])
  988. """),
  989. I(name='TUPLE2',
  990. code='\x86',
  991. arg=None,
  992. stack_before=[anyobject, anyobject],
  993. stack_after=[pytuple],
  994. proto=2,
  995. doc="""One-tuple.
  996. This code pops two values off the stack and pushes a tuple
  997. of length 2 whose items are those values back onto it. IOW:
  998. stack[-2:] = [tuple(stack[-2:])]
  999. """),
  1000. I(name='TUPLE3',
  1001. code='\x87',
  1002. arg=None,
  1003. stack_before=[anyobject, anyobject, anyobject],
  1004. stack_after=[pytuple],
  1005. proto=2,
  1006. doc="""One-tuple.
  1007. This code pops three values off the stack and pushes a tuple
  1008. of length 3 whose items are those values back onto it. IOW:
  1009. stack[-3:] = [tuple(stack[-3:])]
  1010. """),
  1011. # Ways to build dicts.
  1012. I(name='EMPTY_DICT',
  1013. code='}',
  1014. arg=None,
  1015. stack_before=[],
  1016. stack_after=[pydict],
  1017. proto=1,
  1018. doc="Push an empty dict."),
  1019. I(name='DICT',
  1020. code='d',
  1021. arg=None,
  1022. stack_before=[markobject, stackslice],
  1023. stack_after=[pydict],
  1024. proto=0,
  1025. doc="""Build a dict out of the topmost stack slice, after markobject.
  1026. All the stack entries following the topmost markobject are placed into
  1027. a single Python dict, which single dict object replaces all of the
  1028. stack from the topmost markobject onward. The stack slice alternates
  1029. key, value, key, value, .... For example,
  1030. Stack before: ... markobject 1 2 3 'abc'
  1031. Stack after: ... {1: 2, 3: 'abc'}
  1032. """),
  1033. I(name='SETITEM',
  1034. code='s',
  1035. arg=None,
  1036. stack_before=[pydict, anyobject, anyobject],
  1037. stack_after=[pydict],
  1038. proto=0,
  1039. doc="""Add a key+value pair to an existing dict.
  1040. Stack before: ... pydict key value
  1041. Stack after: ... pydict
  1042. where pydict has been modified via pydict[key] = value.
  1043. """),
  1044. I(name='SETITEMS',
  1045. code='u',
  1046. arg=None,
  1047. stack_before=[pydict, markobject, stackslice],
  1048. stack_after=[pydict],
  1049. proto=1,
  1050. doc="""Add an arbitrary number of key+value pairs to an existing dict.
  1051. The slice of the stack following the topmost markobject is taken as
  1052. an alternating sequence of keys and values, added to the dict
  1053. immediately under the topmost markobject. Everything at and after the
  1054. topmost markobject is popped, leaving the mutated dict at the top
  1055. of the stack.
  1056. Stack before: ... pydict markobject key_1 value_1 ... key_n value_n
  1057. Stack after: ... pydict
  1058. where pydict has been modified via pydict[key_i] = value_i for i in
  1059. 1, 2, ..., n, and in that order.
  1060. """),
  1061. # Stack manipulation.
  1062. I(name='POP',
  1063. code='0',
  1064. arg=None,
  1065. stack_before=[anyobject],
  1066. stack_after=[],
  1067. proto=0,
  1068. doc="Discard the top stack item, shrinking the stack by one item."),
  1069. I(name='DUP',
  1070. code='2',
  1071. arg=None,
  1072. stack_before=[anyobject],
  1073. stack_after=[anyobject, anyobject],
  1074. proto=0,
  1075. doc="Push the top stack item onto the stack again, duplicating it."),
  1076. I(name='MARK',
  1077. code='(',
  1078. arg=None,
  1079. stack_before=[],
  1080. stack_after=[markobject],
  1081. proto=0,
  1082. doc="""Push markobject onto the stack.
  1083. markobject is a unique object, used by other opcodes to identify a
  1084. region of the stack containing a variable number of objects for them
  1085. to work on. See markobject.doc for more detail.
  1086. """),
  1087. I(name='POP_MARK',
  1088. code='1',
  1089. arg=None,
  1090. stack_before=[markobject, stackslice],
  1091. stack_after=[],
  1092. proto=1,
  1093. doc="""Pop all the stack objects at and above the topmost markobject.
  1094. When an opcode using a variable number of stack objects is done,
  1095. POP_MARK is used to remove those objects, and to remove the markobject
  1096. that delimited their starting position on the stack.
  1097. """),
  1098. # Memo manipulation. There are really only two operations (get and put),
  1099. # each in all-text, "short binary", and "long binary" flavors.
  1100. I(name='GET',
  1101. code='g',
  1102. arg=decimalnl_short,
  1103. stack_before=[],
  1104. stack_after=[anyobject],
  1105. proto=0,
  1106. doc="""Read an object from the memo and push it on the stack.
  1107. The index of the memo object to push is given by the newline-teriminated
  1108. decimal string following. BINGET and LONG_BINGET are space-optimized
  1109. versions.
  1110. """),
  1111. I(name='BINGET',
  1112. code='h',
  1113. arg=uint1,
  1114. stack_before=[],
  1115. stack_after=[anyobject],
  1116. proto=1,
  1117. doc="""Read an object from the memo and push it on the stack.
  1118. The index of the memo object to push is given by the 1-byte unsigned
  1119. integer following.
  1120. """),
  1121. I(name='LONG_BINGET',
  1122. code='j',
  1123. arg=int4,
  1124. stack_before=[],
  1125. stack_after=[anyobject],
  1126. proto=1,
  1127. doc="""Read an object from the memo and push it on the stack.
  1128. The index of the memo object to push is given by the 4-byte signed
  1129. little-endian integer following.
  1130. """),
  1131. I(name='PUT',
  1132. code='p',
  1133. arg=decimalnl_short,
  1134. stack_before=[],
  1135. stack_after=[],
  1136. proto=0,
  1137. doc="""Store the stack top into the memo. The stack is not popped.
  1138. The index of the memo location to write into is given by the newline-
  1139. terminated decimal string following. BINPUT and LONG_BINPUT are
  1140. space-optimized versions.
  1141. """),
  1142. I(name='BINPUT',
  1143. code='q',
  1144. arg=uint1,
  1145. stack_before=[],
  1146. stack_after=[],
  1147. proto=1,
  1148. doc="""Store the stack top into the memo. The stack is not popped.
  1149. The index of the memo location to write into is given by the 1-byte
  1150. unsigned integer following.
  1151. """),
  1152. I(name='LONG_BINPUT',
  1153. code='r',
  1154. arg=int4,
  1155. stack_before=[],
  1156. stack_after=[],
  1157. proto=1,
  1158. doc="""Store the stack top into the memo. The stack is not popped.
  1159. The index of the memo location to write into is given by the 4-byte
  1160. signed little-endian integer following.
  1161. """),
  1162. # Access the extension registry (predefined objects). Akin to the GET
  1163. # family.
  1164. I(name='EXT1',
  1165. code='\x82',
  1166. arg=uint1,
  1167. stack_before=[],
  1168. stack_after=[anyobject],
  1169. proto=2,
  1170. doc="""Extension code.
  1171. This code and the similar EXT2 and EXT4 allow using a registry
  1172. of popular objects that are pickled by name, typically classes.
  1173. It is envisioned that through a global negotiation and
  1174. registration process, third parties can set up a mapping between
  1175. ints and object names.
  1176. In order to guarantee pickle interchangeability, the extension
  1177. code registry ought to be global, although a range of codes may
  1178. be reserved for private use.
  1179. EXT1 has a 1-byte integer argument. This is used to index into the
  1180. extension registry, and the object at that index is pushed on the stack.
  1181. """),
  1182. I(name='EXT2',
  1183. code='\x83',
  1184. arg=uint2,
  1185. stack_before=[],
  1186. stack_after=[anyobject],
  1187. proto=2,
  1188. doc="""Extension code.
  1189. See EXT1. EXT2 has a two-byte integer argument.
  1190. """),
  1191. I(name='EXT4',
  1192. code='\x84',
  1193. arg=int4,
  1194. stack_before=[],
  1195. stack_after=[anyobject],
  1196. proto=2,
  1197. doc="""Extension code.
  1198. See EXT1. EXT4 has a four-byte integer argument.
  1199. """),
  1200. # Push a class object, or module function, on the stack, via its module
  1201. # and name.
  1202. I(name='GLOBAL',
  1203. code='c',
  1204. arg=stringnl_noescape_pair,
  1205. stack_before=[],
  1206. stack_after=[anyobject],
  1207. proto=0,
  1208. doc="""Push a global object (module.attr) on the stack.
  1209. Two newline-terminated strings follow the GLOBAL opcode. The first is
  1210. taken as a module name, and the second as a class name. The class
  1211. object module.class is pushed on the stack. More accurately, the
  1212. object returned by self.find_class(module, class) is pushed on the
  1213. stack, so unpickling subclasses can override this form of lookup.
  1214. """),
  1215. # Ways to build objects of classes pickle doesn't know about directly
  1216. # (user-defined classes). I despair of documenting this accurately
  1217. # and comprehensibly -- you really have to read the pickle code to
  1218. # find all the special cases.
  1219. I(name='REDUCE',
  1220. code='R',
  1221. arg=None,
  1222. stack_before=[anyobject, anyobject],
  1223. stack_after=[anyobject],
  1224. proto=0,
  1225. doc="""Push an object built from a callable and an argument tuple.
  1226. The opcode is named to remind of the __reduce__() method.
  1227. Stack before: ... callable pytuple
  1228. Stack after: ... callable(*pytuple)
  1229. The callable and the argument tuple are the first two items returned
  1230. by a __reduce__ method. Applying the callable to the argtuple is
  1231. supposed to reproduce the original object, or at least get it started.
  1232. If the __reduce__ method returns a 3-tuple, the last component is an
  1233. argument to be passed to the object's __setstate__, and then the REDUCE
  1234. opcode is followed by code to create setstate's argument, and then a
  1235. BUILD opcode to apply __setstate__ to that argument.
  1236. If type(callable) is not ClassType, REDUCE complains unless the
  1237. callable has been registered with the copy_reg module's
  1238. safe_constructors dict, or the callable has a magic
  1239. '__safe_for_unpickling__' attribute with a true value. I'm not sure
  1240. why it does this, but I've sure seen this complaint often enough when
  1241. I didn't want to <wink>.
  1242. """),
  1243. I(name='BUILD',
  1244. code='b',
  1245. arg=None,
  1246. stack_before=[anyobject, anyobject],
  1247. stack_after=[anyobject],
  1248. proto=0,
  1249. doc="""Finish building an object, via __setstate__ or dict update.
  1250. Stack before: ... anyobject argument
  1251. Stack after: ... anyobject
  1252. where anyobject may have been mutated, as follows:
  1253. If the object has a __setstate__ method,
  1254. anyobject.__setstate__(argument)
  1255. is called.
  1256. Else the argument must be a dict, the object must have a __dict__, and
  1257. the object is updated via
  1258. anyobject.__dict__.update(argument)
  1259. This may raise RuntimeError in restricted execution mode (which
  1260. disallows access to __dict__ directly); in that case, the object
  1261. is updated instead via
  1262. for k, v in argument.items():
  1263. anyobject[k] = v
  1264. """),
  1265. I(name='INST',
  1266. code='i',
  1267. arg=stringnl_noescape_pair,
  1268. stack_before=[markobject, stackslice],
  1269. stack_after=[anyobject],
  1270. proto=0,
  1271. doc="""Build a class instance.
  1272. This is the protocol 0 version of protocol 1's OBJ opcode.
  1273. INST is followed by two newline-terminated strings, giving a
  1274. module and class name, just as for the GLOBAL opcode (and see
  1275. GLOBAL for more details about that). self.find_class(module, name)
  1276. is used to get a class object.
  1277. In addition, all the objects on the stack following the topmost
  1278. markobject are gathered into a tuple and popped (along with the
  1279. topmost markobject), just as for the TUPLE opcode.
  1280. Now it gets complicated. If all of these are true:
  1281. + The argtuple is empty (markobject was at the top of the stack
  1282. at the start).
  1283. + It's an old-style class object (the type of the class object is
  1284. ClassType).
  1285. + The class object does not have a __getinitargs__ attribute.
  1286. then we want to create an old-style class instance without invoking
  1287. its __init__() method (pickle has waffled on this over the years; not
  1288. calling __init__() is current wisdom). In this case, an instance of
  1289. an old-style dummy class is created, and then we try to rebind its
  1290. __class__ attribute to the desired class object. If this succeeds,
  1291. the new instance object is pushed on the stack, and we're done. In
  1292. restricted execution mode it can fail (assignment to __class__ is
  1293. disallowed), and I'm not really sure what happens then -- it looks
  1294. like the code ends up calling the class object's __init__ anyway,
  1295. via falling into the next case.
  1296. Else (the argtuple is not empty, it's not an old-style class object,
  1297. or the class object does have a __getinitargs__ attribute), the code
  1298. first insists that the class object have a __safe_for_unpickling__
  1299. attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE,
  1300. it doesn't matter whether this attribute has a true or false value, it
  1301. only matters whether it exists (XXX this is a bug; cPickle
  1302. requires the attribute to be true). If __safe_for_unpickling__
  1303. doesn't exist, UnpicklingError is raised.
  1304. Else (the class object does have a __safe_for_unpickling__ attr),
  1305. the class object obtained from INST's arguments is applied to the
  1306. argtuple obtained from the stack, and the resulting instance object
  1307. is pushed on the stack.
  1308. NOTE: checks for __safe_for_unpickling__ went away in Python 2.3.
  1309. """),
  1310. I(name='OBJ',
  1311. code='o',
  1312. arg=None,
  1313. stack_before=[markobject, anyobject, stackslice],
  1314. stack_after=[anyobject],
  1315. proto=1,
  1316. doc="""Build a class instance.
  1317. This is the protocol 1 version of protocol 0's INST opcode, and is
  1318. very much like it. The major difference is that the class object
  1319. is taken off the stack, allowing it to be retrieved from the memo
  1320. repeatedly if several instances of the same class are created. This
  1321. can be much more efficient (in both time and space) than repeatedly
  1322. embedding the module and class names in INST opcodes.
  1323. Unlike INST, OBJ takes no arguments from the opcode stream. Instead
  1324. the class object is taken off the stack, immediately above the
  1325. topmost markobject:
  1326. Stack before: ... markobject classobject stackslice
  1327. Stack after: ... new_instance_object
  1328. As for INST, the remainder of the stack above the markobject is
  1329. gathered into an argument tuple, and then the logic seems identical,
  1330. except that no __safe_for_unpickling__ check is done (XXX this is
  1331. a bug; cPickle does test __safe_for_unpickling__). See INST for
  1332. the gory details.
  1333. NOTE: In Python 2.3, INST and OBJ are identical except for how they
  1334. get the class object. That was always the intent; the implementations
  1335. had diverged for accidental reasons.
  1336. """),
  1337. I(name='NEWOBJ',
  1338. code='\x81',
  1339. arg=None,
  1340. stack_before=[anyobject, anyobject],
  1341. stack_after=[anyobject],
  1342. proto=2,
  1343. doc="""Build an object instance.
  1344. The stack before should be thought of as containing a class
  1345. object followed by an argument tuple (the tuple being the stack
  1346. top). Call these cls and args. They are popped off the stack,
  1347. and the value returned by cls.__new__(cls, *args) is pushed back
  1348. onto the stack.
  1349. """),
  1350. # Machine control.
  1351. I(name='PROTO',
  1352. code='\x80',
  1353. arg=uint1,
  1354. stack_before=[],
  1355. stack_after=[],
  1356. proto=2,
  1357. doc="""Protocol version indicator.
  1358. For protocol 2 and above, a pickle must start with this opcode.
  1359. The argument is the protocol version, an int in range(2, 256).
  1360. """),
  1361. I(name='STOP',
  1362. code='.',
  1363. arg=None,
  1364. stack_before=[anyobject],
  1365. stack_after=[],
  1366. proto=0,
  1367. doc="""Stop the unpickling machine.
  1368. Every pickle ends with this opcode. The object at the top of the stack
  1369. is popped, and that's the result of unpickling. The stack should be
  1370. empty then.
  1371. """),
  1372. # Ways to deal with persistent IDs.
  1373. I(name='PERSID',
  1374. code='P',
  1375. arg=stringnl_noescape,
  1376. stack_before=[],
  1377. stack_after=[anyobject],
  1378. proto=0,
  1379. doc="""Push an object identified by a persistent ID.
  1380. The pickle module doesn't define what a persistent ID means. PERSID's
  1381. argument is a newline-terminated str-style (no embedded escapes, no
  1382. bracketing quote characters) string, which *is* "the persistent ID".
  1383. The unpickler passes this string to self.persistent_load(). Whatever
  1384. object that returns is pushed on the stack. There is no implementation
  1385. of persistent_load() in Python's unpickler: it must be supplied by an
  1386. unpickler subclass.
  1387. """),
  1388. I(name='BINPERSID',
  1389. code='Q',
  1390. arg=None,
  1391. stack_before=[anyobject],
  1392. stack_after=[anyobject],
  1393. proto=1,
  1394. doc="""Push an object identified by a persistent ID.
  1395. Like PERSID, except the persistent ID is popped off the stack (instead
  1396. of being a string embedded in the opcode bytestream). The persistent
  1397. ID is passed to self.persistent_load(), and whatever object that
  1398. returns is pushed on the stack. See PERSID for more detail.
  1399. """),
  1400. ]
  1401. del I
  1402. # Verify uniqueness of .name and .code members.
  1403. name2i = {}
  1404. code2i = {}
  1405. for i, d in enumerate(opcodes):
  1406. if d.name in name2i:
  1407. raise ValueError("repeated name %r at indices %d and %d" %
  1408. (d.name, name2i[d.name], i))
  1409. if d.code in code2i:
  1410. raise ValueError("repeated code %r at indices %d and %d" %
  1411. (d.code, code2i[d.code], i))
  1412. name2i[d.name] = i
  1413. code2i[d.code] = i
  1414. del name2i, code2i, i, d
  1415. ##############################################################################
  1416. # Build a code2op dict, mapping opcode characters to OpcodeInfo records.
  1417. # Also ensure we've got the same stuff as pickle.py, although the
  1418. # introspection here is dicey.
  1419. code2op = {}
  1420. for d in opcodes:
  1421. code2op[d.code] = d
  1422. del d
  1423. def assure_pickle_consistency(verbose=False):
  1424. import pickle, re
  1425. copy = code2op.copy()
  1426. for name in pickle.__all__:
  1427. if not re.match("[A-Z][A-Z0-9_]+$", name):
  1428. if verbose:
  1429. print "skipping %r: it doesn't look like an opcode name" % name
  1430. continue
  1431. picklecode = getattr(pickle, name)
  1432. if not isinstance(picklecode, str) or len(picklecode) != 1:
  1433. if verbose:
  1434. print ("skipping %r: value %r doesn't look like a pickle "
  1435. "code" % (name, picklecode))
  1436. continue
  1437. if picklecode in copy:
  1438. if verbose:
  1439. print "checking name %r w/ code %r for consistency" % (
  1440. name, picklecode)
  1441. d = copy[picklecode]
  1442. if d.name != name:
  1443. raise ValueError("for pickle code %r, pickle.py uses name %r "
  1444. "but we're using name %r" % (picklecode,
  1445. name,
  1446. d.name))
  1447. # Forget this one. Any left over in copy at the end are a problem
  1448. # of a different kind.
  1449. del copy[picklecode]
  1450. else:
  1451. raise ValueError("pickle.py appears to have a pickle opcode with "
  1452. "name %r and code %r, but we don't" %
  1453. (name, picklecode))
  1454. if copy:
  1455. msg = ["we appear to have pickle opcodes that pickle.py doesn't have:"]
  1456. for code, d in copy.items():
  1457. msg.append(" name %r with code %r" % (d.name, code))
  1458. raise ValueError("\n".join(msg))
  1459. assure_pickle_consistency()
  1460. del assure_pickle_consistency
  1461. ##############################################################################
  1462. # A pickle opcode generator.
  1463. def genops(pickle):
  1464. """Generate all the opcodes in a pickle.
  1465. 'pickle' is a file-like object, or string, containing the pickle.
  1466. Each opcode in the pickle is generated, from the current pickle position,
  1467. stopping after a STOP opcode is delivered. A triple is generated for
  1468. each opcode:
  1469. opcode, arg, pos
  1470. opcode is an OpcodeInfo record, describing the current opcode.
  1471. If the opcode has an argument embedded in the pickle, arg is its decoded
  1472. value, as a Python object. If the opcode doesn't have an argument, arg
  1473. is None.
  1474. If the pickle has a tell() method, pos was the value of pickle.tell()
  1475. before reading the current opcode. If the pickle is a string object,
  1476. it's wrapped in a StringIO object, and the latter's tell() result is
  1477. used. Else (the pickle doesn't have a tell(), and it's not obvious how
  1478. to query its current position) pos is None.
  1479. """
  1480. import cStringIO as StringIO
  1481. if isinstance(pickle, str):
  1482. pickle = StringIO.StringIO(pickle)
  1483. if hasattr(pickle, "tell"):
  1484. getpos = pickle.tell
  1485. else:
  1486. getpos = lambda: None
  1487. while True:
  1488. pos = getpos()
  1489. code = pickle.read(1)
  1490. opcode = code2op.get(code)
  1491. if opcode is None:
  1492. if code == "":
  1493. raise ValueError("pickle exhausted before seeing STOP")
  1494. else:
  1495. raise ValueError("at position %s, opcode %r unknown" % (
  1496. pos is None and "<unknown>" or pos,
  1497. code))
  1498. if opcode.arg is None:
  1499. arg = None
  1500. else:
  1501. arg = opcode.arg.reader(pickle)
  1502. yield opcode, arg, pos
  1503. if code == '.':
  1504. assert opcode.name == 'STOP'
  1505. break
  1506. ##############################################################################
  1507. # A pickle optimizer.
  1508. def optimize(p):
  1509. 'Optimize a pickle string by removing unused PUT opcodes'
  1510. gets = set() # set of args used by a GET opcode
  1511. puts = [] # (arg, startpos, stoppos) for the PUT opcodes
  1512. prevpos = None # set to pos if previous opcode was a PUT
  1513. for opcode, arg, pos in genops(p):
  1514. if prevpos is not None:
  1515. puts.append((prevarg, prevpos, pos))
  1516. prevpos = None
  1517. if 'PUT' in opcode.name:
  1518. prevarg, prevpos = arg, pos
  1519. elif 'GET' in opcode.name:
  1520. gets.add(arg)
  1521. # Copy the pickle string except for PUTS without a corresponding GET
  1522. s = []
  1523. i = 0
  1524. for arg, start, stop in puts:
  1525. j = stop if (arg in gets) else start
  1526. s.append(p[i:j])
  1527. i = stop
  1528. s.append(p[i:])
  1529. return ''.join(s)
  1530. ##############################################################################
  1531. # A symbolic pickle disassembler.
  1532. def dis(pickle, out=None, memo=None, indentlevel=4):
  1533. """Produce a symbolic disassembly of a pickle.
  1534. 'pickle' is a file-like object, or string, containing a (at least one)
  1535. pickle. The pickle is disassembled from the current position, through
  1536. the first STOP opcode encountered.
  1537. Optional arg 'out' is a file-like object to which the disassembly is
  1538. printed. It defaults to sys.stdout.
  1539. Optional arg 'memo' is a Python dict, used as the pickle's memo. It
  1540. may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes.
  1541. Passing the same memo object to another dis() call then allows disassembly
  1542. to proceed across multiple pickles that were all created by the same
  1543. pickler with the same memo. Ordinarily you don't need to worry about this.
  1544. Optional arg indentlevel is the number of blanks by which to indent
  1545. a new MARK level. It defaults to 4.
  1546. In addition to printing the disassembly, some sanity checks are made:
  1547. + All embedded opcode arguments "make sense".
  1548. + Explicit and implicit pop operations have enough items on the stack.
  1549. + When an opcode implicitly refers to a markobject, a markobject is
  1550. actually on the stack.
  1551. + A memo entry isn't referenced before it's defined.
  1552. + The markobject isn't stored in the memo.
  1553. + A memo entry isn't redefined.
  1554. """
  1555. # Most of the hair here is for sanity checks, but most of it is needed
  1556. # anyway to detect when a protocol 0 POP takes a MARK off the stack
  1557. # (which in turn is needed to indent MARK blocks correctly).
  1558. stack = [] # crude emulation of unpickler stack
  1559. if memo is None:
  1560. memo = {} # crude emulation of unpicker memo
  1561. maxproto = -1 # max protocol number seen
  1562. markstack = [] # bytecode positions of MARK opcodes
  1563. indentchunk = ' ' * indentlevel
  1564. errormsg = None
  1565. for opcode, arg, pos in genops(pickle):
  1566. if pos is not None:
  1567. print >> out, "%5d:" % pos,
  1568. line = "%-4s %s%s" % (repr(opcode.code)[1:-1],
  1569. indentchunk * len(markstack),
  1570. opcode.name)
  1571. maxproto = max(maxproto, opcode.proto)
  1572. before = opcode.stack_before # don't mutate
  1573. after = opcode.stack_after # don't mutate
  1574. numtopop = len(before)
  1575. # See whether a MARK should be popped.
  1576. markmsg = None
  1577. if markobject in before or (opcode.name == "POP" and
  1578. stack and
  1579. stack[-1] is markobject):
  1580. assert markobject not in after
  1581. if __debug__:
  1582. if markobject in before:
  1583. assert before[-1] is stackslice
  1584. if markstack:
  1585. markpos = markstack.pop()
  1586. if markpos is None:
  1587. markmsg = "(MARK at unknown opcode offset)"
  1588. else:
  1589. markmsg = "(MARK at %d)" % markpos
  1590. # Pop everything at and after the topmost markobject.
  1591. while stack[-1] is not markobject:
  1592. stack.pop()
  1593. stack.pop()
  1594. # Stop later code from popping too much.
  1595. try:
  1596. numtopop = before.index(markobject)
  1597. except ValueError:
  1598. assert opcode.name == "POP"
  1599. numtopop = 0
  1600. else:
  1601. errormsg = markmsg = "no MARK exists on stack"
  1602. # Check for correct memo usage.
  1603. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"):
  1604. assert arg is not None
  1605. if arg in memo:
  1606. errormsg = "memo key %r already defined" % arg
  1607. elif not stack:
  1608. errormsg = "stack is empty -- can't store into memo"
  1609. elif stack[-1] is markobject:
  1610. errormsg = "can't store markobject in the memo"
  1611. else:
  1612. memo[arg] = stack[-1]
  1613. elif opcode.name in ("GET", "BINGET", "LONG_BINGET"):
  1614. if arg in memo:
  1615. assert len(after) == 1
  1616. after = [memo[arg]] # for better stack emulation
  1617. else:
  1618. errormsg = "memo key %r has never been stored into" % arg
  1619. if arg is not None or markmsg:
  1620. # make a mild effort to align arguments
  1621. line += ' ' * (10 - len(opcode.name))
  1622. if arg is not None:
  1623. line += ' ' + repr(arg)
  1624. if markmsg:
  1625. line += ' ' + markmsg
  1626. print >> out, line
  1627. if errormsg:
  1628. # Note that we delayed complaining until the offending opcode
  1629. # was printed.
  1630. raise ValueError(errormsg)
  1631. # Emulate the stack effects.
  1632. if len(stack) < numtopop:
  1633. raise ValueError("tries to pop %d items from stack with "
  1634. "only %d items" % (numtopop, len(stack)))
  1635. if numtopop:
  1636. del stack[-numtopop:]
  1637. if markobject in after:
  1638. assert markobject not in before
  1639. markstack.append(pos)
  1640. stack.extend(after)
  1641. print >> out, "highest protocol among opcodes =", maxproto
  1642. if stack:
  1643. raise ValueError("stack not empty after STOP: %r" % stack)
  1644. # For use in the doctest, simply as an example of a class to pickle.
  1645. class _Example:
  1646. def __init__(self, value):
  1647. self.value = value
  1648. _dis_test = r"""
  1649. >>> import pickle
  1650. >>> x = [1, 2, (3, 4), {'abc': u"def"}]
  1651. >>> pkl = pickle.dumps(x, 0)
  1652. >>> dis(pkl)
  1653. 0: ( MARK
  1654. 1: l LIST (MARK at 0)
  1655. 2: p PUT 0
  1656. 5: I INT 1
  1657. 8: a APPEND
  1658. 9: I INT 2
  1659. 12: a APPEND
  1660. 13: ( MARK
  1661. 14: I INT 3
  1662. 17: I INT 4
  1663. 20: t TUPLE (MARK at 13)
  1664. 21: p PUT 1
  1665. 24: a APPEND
  1666. 25: ( MARK
  1667. 26: d DICT (MARK at 25)
  1668. 27: p PUT 2
  1669. 30: S STRING 'abc'
  1670. 37: p PUT 3
  1671. 40: V UNICODE u'def'
  1672. 45: p PUT 4
  1673. 48: s SETITEM
  1674. 49: a APPEND
  1675. 50: . STOP
  1676. highest protocol among opcodes = 0
  1677. Try again with a "binary" pickle.
  1678. >>> pkl = pickle.dumps(x, 1)
  1679. >>> dis(pkl)
  1680. 0: ] EMPTY_LIST
  1681. 1: q BINPUT 0
  1682. 3: ( MARK
  1683. 4: K BININT1 1
  1684. 6: K BININT1 2
  1685. 8: ( MARK
  1686. 9: K BININT1 3
  1687. 11: K BININT1 4
  1688. 13: t TUPLE (MARK at 8)
  1689. 14: q BINPUT 1
  1690. 16: } EMPTY_DICT
  1691. 17: q BINPUT 2
  1692. 19: U SHORT_BINSTRING 'abc'
  1693. 24: q BINPUT 3
  1694. 26: X BINUNICODE u'def'
  1695. 34: q BINPUT 4
  1696. 36: s SETITEM
  1697. 37: e APPENDS (MARK at 3)
  1698. 38: . STOP
  1699. highest protocol among opcodes = 1
  1700. Exercise the INST/OBJ/BUILD family.
  1701. >>> import pickletools
  1702. >>> dis(pickle.dumps(pickletools.dis, 0))
  1703. 0: c GLOBAL 'pickletools dis'
  1704. 17: p PUT 0
  1705. 20: . STOP
  1706. highest protocol among opcodes = 0
  1707. >>> from pickletools import _Example
  1708. >>> x = [_Example(42)] * 2
  1709. >>> dis(pickle.dumps(x, 0))
  1710. 0: ( MARK
  1711. 1: l LIST (MARK at 0)
  1712. 2: p PUT 0
  1713. 5: ( MARK
  1714. 6: i INST 'pickletools _Example' (MARK at 5)
  1715. 28: p PUT 1
  1716. 31: ( MARK
  1717. 32: d DICT (MARK at 31)
  1718. 33: p PUT 2
  1719. 36: S STRING 'value'
  1720. 45: p PUT 3
  1721. 48: I INT 42
  1722. 52: s SETITEM
  1723. 53: b BUILD
  1724. 54: a APPEND
  1725. 55: g GET 1
  1726. 58: a APPEND
  1727. 59: . STOP
  1728. highest protocol among opcodes = 0
  1729. >>> dis(pickle.dumps(x, 1))
  1730. 0: ] EMPTY_LIST
  1731. 1: q BINPUT 0
  1732. 3: ( MARK
  1733. 4: ( MARK
  1734. 5: c GLOBAL 'pickletools _Example'
  1735. 27: q BINPUT 1
  1736. 29: o OBJ (MARK at 4)
  1737. 30: q BINPUT 2
  1738. 32: } EMPTY_DICT
  1739. 33: q BINPUT 3
  1740. 35: U SHORT_BINSTRING 'value'
  1741. 42: q BINPUT 4
  1742. 44: K BININT1 42
  1743. 46: s SETITEM
  1744. 47: b BUILD
  1745. 48: h BINGET 2
  1746. 50: e APPENDS (MARK at 3)
  1747. 51: . STOP
  1748. highest protocol among opcodes = 1
  1749. Try "the canonical" recursive-object test.
  1750. >>> L = []
  1751. >>> T = L,
  1752. >>> L.append(T)
  1753. >>> L[0] is T
  1754. True
  1755. >>> T[0] is L
  1756. True
  1757. >>> L[0][0] is L
  1758. True
  1759. >>> T[0][0] is T
  1760. True
  1761. >>> dis(pickle.dumps(L, 0))
  1762. 0: ( MARK
  1763. 1: l LIST (MARK at 0)
  1764. 2: p PUT 0
  1765. 5: ( MARK
  1766. 6: g GET 0
  1767. 9: t TUPLE (MARK at 5)
  1768. 10: p PUT 1
  1769. 13: a APPEND
  1770. 14: . STOP
  1771. highest protocol among opcodes = 0
  1772. >>> dis(pickle.dumps(L, 1))
  1773. 0: ] EMPTY_LIST
  1774. 1: q BINPUT 0
  1775. 3: ( MARK
  1776. 4: h BINGET 0
  1777. 6: t TUPLE (MARK at 3)
  1778. 7: q BINPUT 1
  1779. 9: a APPEND
  1780. 10: . STOP
  1781. highest protocol among opcodes = 1
  1782. Note that, in the protocol 0 pickle of the recursive tuple, the disassembler
  1783. has to emulate the stack in order to realize that the POP opcode at 16 gets
  1784. rid of the MARK at 0.
  1785. >>> dis(pickle.dumps(T, 0))
  1786. 0: ( MARK
  1787. 1: ( MARK
  1788. 2: l LIST (MARK at 1)
  1789. 3: p PUT 0
  1790. 6: ( MARK
  1791. 7: g GET 0
  1792. 10: t TUPLE (MARK at 6)
  1793. 11: p PUT 1
  1794. 14: a APPEND
  1795. 15: 0 POP
  1796. 16: 0 POP (MARK at 0)
  1797. 17: g GET 1
  1798. 20: . STOP
  1799. highest protocol among opcodes = 0
  1800. >>> dis(pickle.dumps(T, 1))
  1801. 0: ( MARK
  1802. 1: ] EMPTY_LIST
  1803. 2: q BINPUT 0
  1804. 4: ( MARK
  1805. 5: h BINGET 0
  1806. 7: t TUPLE (MARK at 4)
  1807. 8: q BINPUT 1
  1808. 10: a APPEND
  1809. 11: 1 POP_MARK (MARK at 0)
  1810. 12: h BINGET 1
  1811. 14: . STOP
  1812. highest protocol among opcodes = 1
  1813. Try protocol 2.
  1814. >>> dis(pickle.dumps(L, 2))
  1815. 0: \x80 PROTO 2
  1816. 2: ] EMPTY_LIST
  1817. 3: q BINPUT 0
  1818. 5: h BINGET 0
  1819. 7: \x85 TUPLE1
  1820. 8: q BINPUT 1
  1821. 10: a APPEND
  1822. 11: . STOP
  1823. highest protocol among opcodes = 2
  1824. >>> dis(pickle.dumps(T, 2))
  1825. 0: \x80 PROTO 2
  1826. 2: ] EMPTY_LIST
  1827. 3: q BINPUT 0
  1828. 5: h BINGET 0
  1829. 7: \x85 TUPLE1
  1830. 8: q BINPUT 1
  1831. 10: a APPEND
  1832. 11: 0 POP
  1833. 12: h BINGET 1
  1834. 14: . STOP
  1835. highest protocol among opcodes = 2
  1836. """
  1837. _memo_test = r"""
  1838. >>> import pickle
  1839. >>> from StringIO import StringIO
  1840. >>> f = StringIO()
  1841. >>> p = pickle.Pickler(f, 2)
  1842. >>> x = [1, 2, 3]
  1843. >>> p.dump(x)
  1844. >>> p.dump(x)
  1845. >>> f.seek(0)
  1846. >>> memo = {}
  1847. >>> dis(f, memo=memo)
  1848. 0: \x80 PROTO 2
  1849. 2: ] EMPTY_LIST
  1850. 3: q BINPUT 0
  1851. 5: ( MARK
  1852. 6: K BININT1 1
  1853. 8: K BININT1 2
  1854. 10: K BININT1 3
  1855. 12: e APPENDS (MARK at 5)
  1856. 13: . STOP
  1857. highest protocol among opcodes = 2
  1858. >>> dis(f, memo=memo)
  1859. 14: \x80 PROTO 2
  1860. 16: h BINGET 0
  1861. 18: . STOP
  1862. highest protocol among opcodes = 2
  1863. """
  1864. __test__ = {'disassembler_test': _dis_test,
  1865. 'disassembler_memo_test': _memo_test,
  1866. }
  1867. def _test():
  1868. import doctest
  1869. return doctest.testmod()
  1870. if __name__ == "__main__":
  1871. _test()