/Lib/pickletools.py

http://unladen-swallow.googlecode.com/ · Python · 2271 lines · 1943 code · 192 blank · 136 comment · 68 complexity · b6b9de2d5986fc864ed0e3e5c39bb97f MD5 · raw file

Large files are truncated click here to view the full file

  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_co