1 '''"Executable documentation" for the pickle module.
3 Extensive comments about the pickle protocols and pickle-machine opcodes
4 can be found here. Some functions meant for external use:
7 Generate all the opcodes in a pickle, as (opcode, arg, position) triples.
9 dis(pickle, out=None, memo=None, indentlevel=4)
10 Print a symbolic disassembly of a pickle.
19 # - A pickle verifier: read a pickle and check it exhaustively for
20 # well-formedness. dis() does a lot of this already.
22 # - A protocol identifier: examine a pickle and return its protocol number
23 # (== the highest .proto attr value among all the opcodes in the pickle).
24 # dis() already prints this info at the end.
26 # - A pickle optimizer: for example, tuple-building code is sometimes more
27 # elaborate than necessary, catering for the possibility that the tuple
28 # is recursive. Or lots of times a PUT is generated that's never accessed
33 "A pickle" is a program for a virtual pickle machine (PM, but more accurately
34 called an unpickling machine). It's a sequence of opcodes, interpreted by the
35 PM, building an arbitrarily complex Python object.
37 For the most part, the PM is very simple: there are no looping, testing, or
38 conditional instructions, no arithmetic and no function calls. Opcodes are
39 executed once each, from first to last, until a STOP opcode is reached.
41 The PM has two data areas, "the stack" and "the memo".
43 Many opcodes push Python objects onto the stack; e.g., INT pushes a Python
44 integer object on the stack, whose value is gotten from a decimal string
45 literal immediately following the INT opcode in the pickle bytestream. Other
46 opcodes take Python objects off the stack. The result of unpickling is
47 whatever object is left on the stack when the final STOP opcode is executed.
49 The memo is simply an array of objects, or it can be implemented as a dict
50 mapping little integers to objects. The memo serves as the PM's "long term
51 memory", and the little integers indexing the memo are akin to variable
52 names. Some opcodes pop a stack object into the memo at a given index,
53 and others push a memo object at a given index onto the stack again.
55 At heart, that's all the PM has. Subtleties arise for these reasons:
57 + Object identity. Objects can be arbitrarily complex, and subobjects
58 may be shared (for example, the list [a, a] refers to the same object a
59 twice). It can be vital that unpickling recreate an isomorphic object
60 graph, faithfully reproducing sharing.
62 + Recursive objects. For example, after "L = []; L.append(L)", L is a
63 list, and L[0] is the same list. This is related to the object identity
64 point, and some sequences of pickle opcodes are subtle in order to
65 get the right result in all cases.
67 + Things pickle doesn't know everything about. Examples of things pickle
68 does know everything about are Python's builtin scalar and container
69 types, like ints and tuples. They generally have opcodes dedicated to
70 them. For things like module references and instances of user-defined
71 classes, pickle's knowledge is limited. Historically, many enhancements
72 have been made to the pickle protocol in order to do a better (faster,
73 and/or more compact) job on those.
75 + Backward compatibility and micro-optimization. As explained below,
76 pickle opcodes never go away, not even when better ways to do a thing
77 get invented. The repertoire of the PM just keeps growing over time.
78 For example, protocol 0 had two opcodes for building Python integers (INT
79 and LONG), protocol 1 added three more for more-efficient pickling of short
80 integers, and protocol 2 added two more for more-efficient pickling of
81 long integers (before protocol 2, the only ways to pickle a Python long
82 took time quadratic in the number of digits, for both pickling and
83 unpickling). "Opcode bloat" isn't so much a subtlety as a source of
84 wearying complication.
89 For compatibility, the meaning of a pickle opcode never changes. Instead new
90 pickle opcodes get added, and each version's unpickler can handle all the
91 pickle opcodes in all protocol versions to date. So old pickles continue to
92 be readable forever. The pickler can generally be told to restrict itself to
93 the subset of opcodes available under previous protocol versions too, so that
94 users can create pickles under the current version readable by older
95 versions. However, a pickle does not contain its version number embedded
96 within it. If an older unpickler tries to read a pickle using a later
97 protocol, the result is most likely an exception due to seeing an unknown (in
98 the older unpickler) opcode.
100 The original pickle used what's now called "protocol 0", and what was called
101 "text mode" before Python 2.3. The entire pickle bytestream is made up of
102 printable 7-bit ASCII characters, plus the newline character, in protocol 0.
103 That's why it was called text mode. Protocol 0 is small and elegant, but
104 sometimes painfully inefficient.
106 The second major set of additions is now called "protocol 1", and was called
107 "binary mode" before Python 2.3. This added many opcodes with arguments
108 consisting of arbitrary bytes, including NUL bytes and unprintable "high bit"
109 bytes. Binary mode pickles can be substantially smaller than equivalent
110 text mode pickles, and sometimes faster too; e.g., BININT represents a 4-byte
111 int as 4 bytes following the opcode, which is cheaper to unpickle than the
112 (perhaps) 11-character decimal string attached to INT. Protocol 1 also added
113 a number of opcodes that operate on many stack elements at once (like APPENDS
114 and SETITEMS), and "shortcut" opcodes (like EMPTY_DICT and EMPTY_TUPLE).
116 The third major set of additions came in Python 2.3, and is called "protocol
119 - A better way to pickle instances of new-style classes (NEWOBJ).
121 - A way for a pickle to identify its protocol (PROTO).
123 - Time- and space- efficient pickling of long ints (LONG{1,4}).
125 - Shortcuts for small tuples (TUPLE{1,2,3}}.
127 - Dedicated opcodes for bools (NEWTRUE, NEWFALSE).
129 - The "extension registry", a vector of popular objects that can be pushed
130 efficiently by index (EXT{1,2,4}). This is akin to the memo and GET, but
131 the registry contents are predefined (there's nothing akin to the memo's
134 Another independent change with Python 2.3 is the abandonment of any
135 pretense that it might be safe to load pickles received from untrusted
136 parties -- no sufficient security analysis has been done to guarantee
137 this and there isn't a use case that warrants the expense of such an
140 To this end, all tests for __safe_for_unpickling__ or for
141 copy_reg.safe_constructors are removed from the unpickling code.
142 References to these variables in the descriptions below are to be seen
143 as describing unpickling in Python 2.2 and before.
146 # Meta-rule: Descriptions are stored in instances of descriptor objects,
147 # with plain constructors. No meta-language is defined from which
148 # descriptors could be constructed. If you want, e.g., XML, write a little
149 # program to generate XML from the objects.
151 ##############################################################################
152 # Some pickle opcodes have an argument, following the opcode in the
153 # bytestream. An argument is of a specific type, described by an instance
154 # of ArgumentDescriptor. These are not to be confused with arguments taken
155 # off the stack -- ArgumentDescriptor applies only to arguments embedded in
156 # the opcode stream, immediately following an opcode.
158 # Represents the number of bytes consumed by an argument delimited by the
159 # next newline character.
162 # Represents the number of bytes consumed by a two-argument opcode where
163 # the first argument gives the number of bytes in the second argument.
164 TAKEN_FROM_ARGUMENT1
= -2 # num bytes is 1-byte unsigned int
165 TAKEN_FROM_ARGUMENT4
= -3 # num bytes is 4-byte signed little-endian int
167 class ArgumentDescriptor(object):
169 # name of descriptor record, also a module global name; a string
172 # length of argument, in bytes; an int; UP_TO_NEWLINE and
173 # TAKEN_FROM_ARGUMENT{1,4} are negative values for variable-length
177 # a function taking a file-like object, reading this kind of argument
178 # from the object at the current position, advancing the current
179 # position by n bytes, and returning the value of the argument
182 # human-readable docs for this arg descriptor; a string
186 def __init__(self
, name
, n
, reader
, doc
):
187 assert isinstance(name
, str)
190 assert isinstance(n
, int) and (n
>= 0 or
192 TAKEN_FROM_ARGUMENT1
,
193 TAKEN_FROM_ARGUMENT4
))
198 assert isinstance(doc
, str)
201 from struct
import unpack
as _unpack
206 >>> read_uint1(StringIO.StringIO('\xff'))
213 raise ValueError("not enough data in stream to read uint1")
215 uint1
= ArgumentDescriptor(
219 doc
="One-byte unsigned integer.")
225 >>> read_uint2(StringIO.StringIO('\xff\x00'))
227 >>> read_uint2(StringIO.StringIO('\xff\xff'))
233 return _unpack("<H", data
)[0]
234 raise ValueError("not enough data in stream to read uint2")
236 uint2
= ArgumentDescriptor(
240 doc
="Two-byte unsigned integer, little-endian.")
246 >>> read_int4(StringIO.StringIO('\xff\x00\x00\x00'))
248 >>> read_int4(StringIO.StringIO('\x00\x00\x00\x80')) == -(2**31)
254 return _unpack("<i", data
)[0]
255 raise ValueError("not enough data in stream to read int4")
257 int4
= ArgumentDescriptor(
261 doc
="Four-byte signed integer, little-endian, 2's complement.")
264 def read_stringnl(f
, decode
=True, stripquotes
=True):
267 >>> read_stringnl(StringIO.StringIO("'abcd'\nefg\n"))
270 >>> read_stringnl(StringIO.StringIO("\n"))
271 Traceback (most recent call last):
273 ValueError: no string quotes around ''
275 >>> read_stringnl(StringIO.StringIO("\n"), stripquotes=False)
278 >>> read_stringnl(StringIO.StringIO("''\n"))
281 >>> read_stringnl(StringIO.StringIO('"abcd"'))
282 Traceback (most recent call last):
284 ValueError: no newline found when trying to read stringnl
286 Embedded escapes are undone in the result.
287 >>> read_stringnl(StringIO.StringIO(r"'a\n\\b\x00c\td'" + "\n'e'"))
292 if not data
.endswith('\n'):
293 raise ValueError("no newline found when trying to read stringnl")
294 data
= data
[:-1] # lose the newline
298 if data
.startswith(q
):
299 if not data
.endswith(q
):
300 raise ValueError("strinq quote %r not found at both "
301 "ends of %r" % (q
, data
))
305 raise ValueError("no string quotes around %r" % data
)
307 # I'm not sure when 'string_escape' was added to the std codecs; it's
308 # crazy not to use it if it's there.
310 data
= data
.decode('string_escape')
313 stringnl
= ArgumentDescriptor(
316 reader
=read_stringnl
,
317 doc
="""A newline-terminated string.
319 This is a repr-style string, with embedded escapes, and
323 def read_stringnl_noescape(f
):
324 return read_stringnl(f
, decode
=False, stripquotes
=False)
326 stringnl_noescape
= ArgumentDescriptor(
327 name
='stringnl_noescape',
329 reader
=read_stringnl_noescape
,
330 doc
="""A newline-terminated string.
332 This is a str-style string, without embedded escapes,
333 or bracketing quotes. It should consist solely of
334 printable ASCII characters.
337 def read_stringnl_noescape_pair(f
):
340 >>> read_stringnl_noescape_pair(StringIO.StringIO("Queue\nEmpty\njunk"))
344 return "%s %s" % (read_stringnl_noescape(f
), read_stringnl_noescape(f
))
346 stringnl_noescape_pair
= ArgumentDescriptor(
347 name
='stringnl_noescape_pair',
349 reader
=read_stringnl_noescape_pair
,
350 doc
="""A pair of newline-terminated strings.
352 These are str-style strings, without embedded
353 escapes, or bracketing quotes. They should
354 consist solely of printable ASCII characters.
355 The pair is returned as a single string, with
356 a single blank separating the two strings.
362 >>> read_string4(StringIO.StringIO("\x00\x00\x00\x00abc"))
364 >>> read_string4(StringIO.StringIO("\x03\x00\x00\x00abcdef"))
366 >>> read_string4(StringIO.StringIO("\x00\x00\x00\x03abcdef"))
367 Traceback (most recent call last):
369 ValueError: expected 50331648 bytes in a string4, but only 6 remain
374 raise ValueError("string4 byte count < 0: %d" % n
)
378 raise ValueError("expected %d bytes in a string4, but only %d remain" %
381 string4
= ArgumentDescriptor(
383 n
=TAKEN_FROM_ARGUMENT4
,
385 doc
="""A counted string.
387 The first argument is a 4-byte little-endian signed int giving
388 the number of bytes in the string, and the second argument is
396 >>> read_string1(StringIO.StringIO("\x00"))
398 >>> read_string1(StringIO.StringIO("\x03abcdef"))
407 raise ValueError("expected %d bytes in a string1, but only %d remain" %
410 string1
= ArgumentDescriptor(
412 n
=TAKEN_FROM_ARGUMENT1
,
414 doc
="""A counted string.
416 The first argument is a 1-byte unsigned int giving the number
417 of bytes in the string, and the second argument is that many
422 def read_unicodestringnl(f
):
425 >>> read_unicodestringnl(StringIO.StringIO("abc\uabcd\njunk"))
430 if not data
.endswith('\n'):
431 raise ValueError("no newline found when trying to read "
433 data
= data
[:-1] # lose the newline
434 return unicode(data
, 'raw-unicode-escape')
436 unicodestringnl
= ArgumentDescriptor(
437 name
='unicodestringnl',
439 reader
=read_unicodestringnl
,
440 doc
="""A newline-terminated Unicode string.
442 This is raw-unicode-escape encoded, so consists of
443 printable ASCII characters, and may contain embedded
447 def read_unicodestring4(f
):
450 >>> s = u'abcd\uabcd'
451 >>> enc = s.encode('utf-8')
454 >>> n = chr(len(enc)) + chr(0) * 3 # little-endian 4-byte length
455 >>> t = read_unicodestring4(StringIO.StringIO(n + enc + 'junk'))
459 >>> read_unicodestring4(StringIO.StringIO(n + enc[:-1]))
460 Traceback (most recent call last):
462 ValueError: expected 7 bytes in a unicodestring4, but only 6 remain
467 raise ValueError("unicodestring4 byte count < 0: %d" % n
)
470 return unicode(data
, 'utf-8')
471 raise ValueError("expected %d bytes in a unicodestring4, but only %d "
472 "remain" % (n
, len(data
)))
474 unicodestring4
= ArgumentDescriptor(
475 name
="unicodestring4",
476 n
=TAKEN_FROM_ARGUMENT4
,
477 reader
=read_unicodestring4
,
478 doc
="""A counted Unicode string.
480 The first argument is a 4-byte little-endian signed int
481 giving the number of bytes in the string, and the second
482 argument-- the UTF-8 encoding of the Unicode string --
483 contains that many bytes.
487 def read_decimalnl_short(f
):
490 >>> read_decimalnl_short(StringIO.StringIO("1234\n56"))
493 >>> read_decimalnl_short(StringIO.StringIO("1234L\n56"))
494 Traceback (most recent call last):
496 ValueError: trailing 'L' not allowed in '1234L'
499 s
= read_stringnl(f
, decode
=False, stripquotes
=False)
501 raise ValueError("trailing 'L' not allowed in %r" % s
)
503 # It's not necessarily true that the result fits in a Python short int:
504 # the pickle may have been written on a 64-bit box. There's also a hack
505 # for True and False here.
513 except OverflowError:
516 def read_decimalnl_long(f
):
520 >>> read_decimalnl_long(StringIO.StringIO("1234\n56"))
521 Traceback (most recent call last):
523 ValueError: trailing 'L' required in '1234'
525 Someday the trailing 'L' will probably go away from this output.
527 >>> read_decimalnl_long(StringIO.StringIO("1234L\n56"))
530 >>> read_decimalnl_long(StringIO.StringIO("123456789012345678901234L\n6"))
531 123456789012345678901234L
534 s
= read_stringnl(f
, decode
=False, stripquotes
=False)
535 if not s
.endswith("L"):
536 raise ValueError("trailing 'L' required in %r" % s
)
540 decimalnl_short
= ArgumentDescriptor(
541 name
='decimalnl_short',
543 reader
=read_decimalnl_short
,
544 doc
="""A newline-terminated decimal integer literal.
546 This never has a trailing 'L', and the integer fit
547 in a short Python int on the box where the pickle
548 was written -- but there's no guarantee it will fit
549 in a short Python int on the box where the pickle
553 decimalnl_long
= ArgumentDescriptor(
554 name
='decimalnl_long',
556 reader
=read_decimalnl_long
,
557 doc
="""A newline-terminated decimal integer literal.
559 This has a trailing 'L', and can represent integers
567 >>> read_floatnl(StringIO.StringIO("-1.25\n6"))
570 s
= read_stringnl(f
, decode
=False, stripquotes
=False)
573 floatnl
= ArgumentDescriptor(
577 doc
="""A newline-terminated decimal floating literal.
579 In general this requires 17 significant digits for roundtrip
580 identity, and pickling then unpickling infinities, NaNs, and
581 minus zero doesn't work across boxes, or on some boxes even
582 on itself (e.g., Windows can't read the strings it produces
583 for infinities or NaNs).
588 >>> import StringIO, struct
589 >>> raw = struct.pack(">d", -1.25)
591 '\xbf\xf4\x00\x00\x00\x00\x00\x00'
592 >>> read_float8(StringIO.StringIO(raw + "\n"))
598 return _unpack(">d", data
)[0]
599 raise ValueError("not enough data in stream to read float8")
602 float8
= ArgumentDescriptor(
606 doc
="""An 8-byte binary representation of a float, big-endian.
608 The format is unique to Python, and shared with the struct
609 module (format string '>d') "in theory" (the struct and cPickle
610 implementations don't share the code -- they should). It's
611 strongly related to the IEEE-754 double format, and, in normal
612 cases, is in fact identical to the big-endian 754 double format.
613 On other boxes the dynamic range is limited to that of a 754
614 double, and "add a half and chop" rounding is used to reduce
615 the precision to 53 bits. However, even on a 754 box,
616 infinities, NaNs, and minus zero may not be handled correctly
617 (may not survive roundtrip pickling intact).
622 from pickle
import decode_long
627 >>> read_long1(StringIO.StringIO("\x00"))
629 >>> read_long1(StringIO.StringIO("\x02\xff\x00"))
631 >>> read_long1(StringIO.StringIO("\x02\xff\x7f"))
633 >>> read_long1(StringIO.StringIO("\x02\x00\xff"))
635 >>> read_long1(StringIO.StringIO("\x02\x00\x80"))
642 raise ValueError("not enough data in stream to read long1")
643 return decode_long(data
)
645 long1
= ArgumentDescriptor(
647 n
=TAKEN_FROM_ARGUMENT1
,
649 doc
="""A binary long, little-endian, using 1-byte size.
651 This first reads one byte as an unsigned size, then reads that
652 many bytes and interprets them as a little-endian 2's-complement long.
653 If the size is 0, that's taken as a shortcut for the long 0L.
659 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00"))
661 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f"))
663 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff"))
665 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80"))
667 >>> read_long1(StringIO.StringIO("\x00\x00\x00\x00"))
673 raise ValueError("long4 byte count < 0: %d" % n
)
676 raise ValueError("not enough data in stream to read long4")
677 return decode_long(data
)
679 long4
= ArgumentDescriptor(
681 n
=TAKEN_FROM_ARGUMENT4
,
683 doc
="""A binary representation of a long, little-endian.
685 This first reads four bytes as a signed size (but requires the
686 size to be >= 0), then reads that many bytes and interprets them
687 as a little-endian 2's-complement long. If the size is 0, that's taken
688 as a shortcut for the long 0L, although LONG1 should really be used
689 then instead (and in any case where # of bytes < 256).
693 ##############################################################################
694 # Object descriptors. The stack used by the pickle machine holds objects,
695 # and in the stack_before and stack_after attributes of OpcodeInfo
696 # descriptors we need names to describe the various types of objects that can
697 # appear on the stack.
699 class StackObject(object):
701 # name of descriptor record, for info only
704 # type of object, or tuple of type objects (meaning the object can
705 # be of any type in the tuple)
708 # human-readable docs for this kind of stack object; a string
712 def __init__(self
, name
, obtype
, doc
):
713 assert isinstance(name
, str)
716 assert isinstance(obtype
, type) or isinstance(obtype
, tuple)
717 if isinstance(obtype
, tuple):
718 for contained
in obtype
:
719 assert isinstance(contained
, type)
722 assert isinstance(doc
, str)
732 doc
="A short (as opposed to long) Python integer object.")
734 pylong
= StackObject(
737 doc
="A long (as opposed to short) Python integer object.")
739 pyinteger_or_bool
= StackObject(
741 obtype
=(int, long, bool),
742 doc
="A Python integer object (short or long), or "
745 pybool
= StackObject(
748 doc
="A Python bool object.")
750 pyfloat
= StackObject(
753 doc
="A Python float object.")
755 pystring
= StackObject(
758 doc
="A Python string object.")
760 pyunicode
= StackObject(
763 doc
="A Python Unicode string object.")
765 pynone
= StackObject(
768 doc
="The Python None object.")
770 pytuple
= StackObject(
773 doc
="A Python tuple object.")
775 pylist
= StackObject(
778 doc
="A Python list object.")
780 pydict
= StackObject(
783 doc
="A Python dict object.")
785 anyobject
= StackObject(
788 doc
="Any kind of object whatsoever.")
790 markobject
= StackObject(
793 doc
="""'The mark' is a unique object.
795 Opcodes that operate on a variable number of objects
796 generally don't embed the count of objects in the opcode,
797 or pull it off the stack. Instead the MARK opcode is used
798 to push a special marker object on the stack, and then
799 some other opcodes grab all the objects from the top of
800 the stack down to (but not including) the topmost marker
804 stackslice
= StackObject(
807 doc
="""An object representing a contiguous slice of the stack.
809 This is used in conjuction with markobject, to represent all
810 of the stack following the topmost markobject. For example,
811 the POP_MARK opcode changes the stack from
813 [..., markobject, stackslice]
817 No matter how many object are on the stack after the topmost
818 markobject, POP_MARK gets rid of all of them (including the
819 topmost markobject too).
822 ##############################################################################
823 # Descriptors for pickle opcodes.
825 class OpcodeInfo(object):
828 # symbolic name of opcode; a string
831 # the code used in a bytestream to represent the opcode; a
832 # one-character string
835 # If the opcode has an argument embedded in the byte string, an
836 # instance of ArgumentDescriptor specifying its type. Note that
837 # arg.reader(s) can be used to read and decode the argument from
838 # the bytestream s, and arg.doc documents the format of the raw
839 # argument bytes. If the opcode doesn't have an argument embedded
840 # in the bytestream, arg should be None.
843 # what the stack looks like before this opcode runs; a list
846 # what the stack looks like after this opcode runs; a list
849 # the protocol number in which this opcode was introduced; an int
852 # human-readable docs for this opcode; a string
856 def __init__(self
, name
, code
, arg
,
857 stack_before
, stack_after
, proto
, doc
):
858 assert isinstance(name
, str)
861 assert isinstance(code
, str)
862 assert len(code
) == 1
865 assert arg
is None or isinstance(arg
, ArgumentDescriptor
)
868 assert isinstance(stack_before
, list)
869 for x
in stack_before
:
870 assert isinstance(x
, StackObject
)
871 self
.stack_before
= stack_before
873 assert isinstance(stack_after
, list)
874 for x
in stack_after
:
875 assert isinstance(x
, StackObject
)
876 self
.stack_after
= stack_after
878 assert isinstance(proto
, int) and 0 <= proto
<= 2
881 assert isinstance(doc
, str)
887 # Ways to spell integers.
893 stack_after
=[pyinteger_or_bool
],
895 doc
="""Push an integer or bool.
897 The argument is a newline-terminated decimal literal string.
899 The intent may have been that this always fit in a short Python int,
900 but INT can be generated in pickles written on a 64-bit box that
901 require a Python long on a 32-bit box. The difference between this
902 and LONG then is that INT skips a trailing 'L', and produces a short
903 int whenever possible.
905 Another difference is due to that, when bool was introduced as a
906 distinct type in 2.3, builtin names True and False were also added to
907 2.2.2, mapping to ints 1 and 0. For compatibility in both directions,
908 True gets pickled as INT + "I01\\n", and False as INT + "I00\\n".
909 Leading zeroes are never produced for a genuine integer. The 2.3
910 (and later) unpicklers special-case these and return bool instead;
911 earlier unpicklers ignore the leading "0" and return the int.
920 doc
="""Push a four-byte signed integer.
922 This handles the full range of Python (short) integers on a 32-bit
923 box, directly as binary bytes (1 for the opcode and 4 for the integer).
924 If the integer is non-negative and fits in 1 or 2 bytes, pickling via
925 BININT1 or BININT2 saves space.
934 doc
="""Push a one-byte unsigned integer.
936 This is a space optimization for pickling very small non-negative ints,
946 doc
="""Push a two-byte unsigned integer.
948 This is a space optimization for pickling small positive ints, in
949 range(256, 2**16). Integers in range(256) can also be pickled via
950 BININT2, but BININT1 instead saves a byte.
957 stack_after
=[pylong
],
959 doc
="""Push a long integer.
961 The same as INT, except that the literal ends with 'L', and always
962 unpickles to a Python long. There doesn't seem a real purpose to the
965 Note that LONG takes time quadratic in the number of digits when
966 unpickling (this is simply due to the nature of decimal->binary
967 conversion). Proto 2 added linear-time (in C; still quadratic-time
968 in Python) LONG1 and LONG4 opcodes.
975 stack_after
=[pylong
],
977 doc
="""Long integer using one-byte length.
979 A more efficient encoding of a Python long; the long1 encoding
986 stack_after
=[pylong
],
988 doc
="""Long integer using found-byte length.
990 A more efficient encoding of a Python long; the long4 encoding
993 # Ways to spell strings (8-bit, not Unicode).
999 stack_after
=[pystring
],
1001 doc
="""Push a Python string object.
1003 The argument is a repr-style string, with bracketing quote characters,
1004 and perhaps embedded escapes. The argument extends until the next
1012 stack_after
=[pystring
],
1014 doc
="""Push a Python string object.
1016 There are two arguments: the first is a 4-byte little-endian signed int
1017 giving the number of bytes in the string, and the second is that many
1018 bytes, which are taken literally as the string content.
1021 I(name
='SHORT_BINSTRING',
1025 stack_after
=[pystring
],
1027 doc
="""Push a Python string object.
1029 There are two arguments: the first is a 1-byte unsigned int giving
1030 the number of bytes in the string, and the second is that many bytes,
1031 which are taken literally as the string content.
1034 # Ways to spell None.
1040 stack_after
=[pynone
],
1042 doc
="Push None on the stack."),
1044 # Ways to spell bools, starting with proto 2. See INT for how this was
1045 # done before proto 2.
1051 stack_after
=[pybool
],
1055 Push True onto the stack."""),
1061 stack_after
=[pybool
],
1065 Push False onto the stack."""),
1067 # Ways to spell Unicode strings.
1071 arg
=unicodestringnl
,
1073 stack_after
=[pyunicode
],
1074 proto
=0, # this may be pure-text, but it's a later addition
1075 doc
="""Push a Python Unicode string object.
1077 The argument is a raw-unicode-escape encoding of a Unicode string,
1078 and so may contain embedded escape sequences. The argument extends
1079 until the next newline character.
1082 I(name
='BINUNICODE',
1086 stack_after
=[pyunicode
],
1088 doc
="""Push a Python Unicode string object.
1090 There are two arguments: the first is a 4-byte little-endian signed int
1091 giving the number of bytes in the string. The second is that many
1092 bytes, and is the UTF-8 encoding of the Unicode string.
1095 # Ways to spell floats.
1101 stack_after
=[pyfloat
],
1103 doc
="""Newline-terminated decimal float literal.
1105 The argument is repr(a_float), and in general requires 17 significant
1106 digits for roundtrip conversion to be an identity (this is so for
1107 IEEE-754 double precision values, which is what Python float maps to
1110 In general, FLOAT cannot be used to transport infinities, NaNs, or
1111 minus zero across boxes (or even on a single box, if the platform C
1112 library can't read the strings it produces for such things -- Windows
1113 is like that), but may do less damage than BINFLOAT on boxes with
1114 greater precision or dynamic range than IEEE-754 double.
1121 stack_after
=[pyfloat
],
1123 doc
="""Float stored in binary form, with 8 bytes of data.
1125 This generally requires less than half the space of FLOAT encoding.
1126 In general, BINFLOAT cannot be used to transport infinities, NaNs, or
1127 minus zero, raises an exception if the exponent exceeds the range of
1128 an IEEE-754 double, and retains no more than 53 bits of precision (if
1129 there are more than that, "add a half and chop" rounding is used to
1130 cut it back to 53 significant bits).
1133 # Ways to build lists.
1135 I(name
='EMPTY_LIST',
1139 stack_after
=[pylist
],
1141 doc
="Push an empty list."),
1146 stack_before
=[pylist
, anyobject
],
1147 stack_after
=[pylist
],
1149 doc
="""Append an object to a list.
1151 Stack before: ... pylist anyobject
1152 Stack after: ... pylist+[anyobject]
1154 although pylist is really extended in-place.
1160 stack_before
=[pylist
, markobject
, stackslice
],
1161 stack_after
=[pylist
],
1163 doc
="""Extend a list by a slice of stack objects.
1165 Stack before: ... pylist markobject stackslice
1166 Stack after: ... pylist+stackslice
1168 although pylist is really extended in-place.
1174 stack_before
=[markobject
, stackslice
],
1175 stack_after
=[pylist
],
1177 doc
="""Build a list out of the topmost stack slice, after markobject.
1179 All the stack entries following the topmost markobject are placed into
1180 a single Python list, which single list object replaces all of the
1181 stack from the topmost markobject onward. For example,
1183 Stack before: ... markobject 1 2 3 'abc'
1184 Stack after: ... [1, 2, 3, 'abc']
1187 # Ways to build tuples.
1189 I(name
='EMPTY_TUPLE',
1193 stack_after
=[pytuple
],
1195 doc
="Push an empty tuple."),
1200 stack_before
=[markobject
, stackslice
],
1201 stack_after
=[pytuple
],
1203 doc
="""Build a tuple out of the topmost stack slice, after markobject.
1205 All the stack entries following the topmost markobject are placed into
1206 a single Python tuple, which single tuple object replaces all of the
1207 stack from the topmost markobject onward. For example,
1209 Stack before: ... markobject 1 2 3 'abc'
1210 Stack after: ... (1, 2, 3, 'abc')
1216 stack_before
=[anyobject
],
1217 stack_after
=[pytuple
],
1221 This code pops one value off the stack and pushes a tuple of
1222 length 1 whose one item is that value back onto it. IOW:
1224 stack[-1] = tuple(stack[-1:])
1230 stack_before
=[anyobject
, anyobject
],
1231 stack_after
=[pytuple
],
1235 This code pops two values off the stack and pushes a tuple
1236 of length 2 whose items are those values back onto it. IOW:
1238 stack[-2:] = [tuple(stack[-2:])]
1244 stack_before
=[anyobject
, anyobject
, anyobject
],
1245 stack_after
=[pytuple
],
1249 This code pops three values off the stack and pushes a tuple
1250 of length 3 whose items are those values back onto it. IOW:
1252 stack[-3:] = [tuple(stack[-3:])]
1255 # Ways to build dicts.
1257 I(name
='EMPTY_DICT',
1261 stack_after
=[pydict
],
1263 doc
="Push an empty dict."),
1268 stack_before
=[markobject
, stackslice
],
1269 stack_after
=[pydict
],
1271 doc
="""Build a dict out of the topmost stack slice, after markobject.
1273 All the stack entries following the topmost markobject are placed into
1274 a single Python dict, which single dict object replaces all of the
1275 stack from the topmost markobject onward. The stack slice alternates
1276 key, value, key, value, .... For example,
1278 Stack before: ... markobject 1 2 3 'abc'
1279 Stack after: ... {1: 2, 3: 'abc'}
1285 stack_before
=[pydict
, anyobject
, anyobject
],
1286 stack_after
=[pydict
],
1288 doc
="""Add a key+value pair to an existing dict.
1290 Stack before: ... pydict key value
1291 Stack after: ... pydict
1293 where pydict has been modified via pydict[key] = value.
1299 stack_before
=[pydict
, markobject
, stackslice
],
1300 stack_after
=[pydict
],
1302 doc
="""Add an arbitrary number of key+value pairs to an existing dict.
1304 The slice of the stack following the topmost markobject is taken as
1305 an alternating sequence of keys and values, added to the dict
1306 immediately under the topmost markobject. Everything at and after the
1307 topmost markobject is popped, leaving the mutated dict at the top
1310 Stack before: ... pydict markobject key_1 value_1 ... key_n value_n
1311 Stack after: ... pydict
1313 where pydict has been modified via pydict[key_i] = value_i for i in
1314 1, 2, ..., n, and in that order.
1317 # Stack manipulation.
1322 stack_before
=[anyobject
],
1325 doc
="Discard the top stack item, shrinking the stack by one item."),
1330 stack_before
=[anyobject
],
1331 stack_after
=[anyobject
, anyobject
],
1333 doc
="Push the top stack item onto the stack again, duplicating it."),
1339 stack_after
=[markobject
],
1341 doc
="""Push markobject onto the stack.
1343 markobject is a unique object, used by other opcodes to identify a
1344 region of the stack containing a variable number of objects for them
1345 to work on. See markobject.doc for more detail.
1351 stack_before
=[markobject
, stackslice
],
1354 doc
="""Pop all the stack objects at and above the topmost markobject.
1356 When an opcode using a variable number of stack objects is done,
1357 POP_MARK is used to remove those objects, and to remove the markobject
1358 that delimited their starting position on the stack.
1361 # Memo manipulation. There are really only two operations (get and put),
1362 # each in all-text, "short binary", and "long binary" flavors.
1366 arg
=decimalnl_short
,
1368 stack_after
=[anyobject
],
1370 doc
="""Read an object from the memo and push it on the stack.
1372 The index of the memo object to push is given by the newline-teriminated
1373 decimal string following. BINGET and LONG_BINGET are space-optimized
1381 stack_after
=[anyobject
],
1383 doc
="""Read an object from the memo and push it on the stack.
1385 The index of the memo object to push is given by the 1-byte unsigned
1389 I(name
='LONG_BINGET',
1393 stack_after
=[anyobject
],
1395 doc
="""Read an object from the memo and push it on the stack.
1397 The index of the memo object to push is given by the 4-byte signed
1398 little-endian integer following.
1403 arg
=decimalnl_short
,
1407 doc
="""Store the stack top into the memo. The stack is not popped.
1409 The index of the memo location to write into is given by the newline-
1410 terminated decimal string following. BINPUT and LONG_BINPUT are
1411 space-optimized versions.
1420 doc
="""Store the stack top into the memo. The stack is not popped.
1422 The index of the memo location to write into is given by the 1-byte
1423 unsigned integer following.
1426 I(name
='LONG_BINPUT',
1432 doc
="""Store the stack top into the memo. The stack is not popped.
1434 The index of the memo location to write into is given by the 4-byte
1435 signed little-endian integer following.
1438 # Access the extension registry (predefined objects). Akin to the GET
1445 stack_after
=[anyobject
],
1447 doc
="""Extension code.
1449 This code and the similar EXT2 and EXT4 allow using a registry
1450 of popular objects that are pickled by name, typically classes.
1451 It is envisioned that through a global negotiation and
1452 registration process, third parties can set up a mapping between
1453 ints and object names.
1455 In order to guarantee pickle interchangeability, the extension
1456 code registry ought to be global, although a range of codes may
1457 be reserved for private use.
1459 EXT1 has a 1-byte integer argument. This is used to index into the
1460 extension registry, and the object at that index is pushed on the stack.
1467 stack_after
=[anyobject
],
1469 doc
="""Extension code.
1471 See EXT1. EXT2 has a two-byte integer argument.
1478 stack_after
=[anyobject
],
1480 doc
="""Extension code.
1482 See EXT1. EXT4 has a four-byte integer argument.
1485 # Push a class object, or module function, on the stack, via its module
1490 arg
=stringnl_noescape_pair
,
1492 stack_after
=[anyobject
],
1494 doc
="""Push a global object (module.attr) on the stack.
1496 Two newline-terminated strings follow the GLOBAL opcode. The first is
1497 taken as a module name, and the second as a class name. The class
1498 object module.class is pushed on the stack. More accurately, the
1499 object returned by self.find_class(module, class) is pushed on the
1500 stack, so unpickling subclasses can override this form of lookup.
1503 # Ways to build objects of classes pickle doesn't know about directly
1504 # (user-defined classes). I despair of documenting this accurately
1505 # and comprehensibly -- you really have to read the pickle code to
1506 # find all the special cases.
1511 stack_before
=[anyobject
, anyobject
],
1512 stack_after
=[anyobject
],
1514 doc
="""Push an object built from a callable and an argument tuple.
1516 The opcode is named to remind of the __reduce__() method.
1518 Stack before: ... callable pytuple
1519 Stack after: ... callable(*pytuple)
1521 The callable and the argument tuple are the first two items returned
1522 by a __reduce__ method. Applying the callable to the argtuple is
1523 supposed to reproduce the original object, or at least get it started.
1524 If the __reduce__ method returns a 3-tuple, the last component is an
1525 argument to be passed to the object's __setstate__, and then the REDUCE
1526 opcode is followed by code to create setstate's argument, and then a
1527 BUILD opcode to apply __setstate__ to that argument.
1529 If type(callable) is not ClassType, REDUCE complains unless the
1530 callable has been registered with the copy_reg module's
1531 safe_constructors dict, or the callable has a magic
1532 '__safe_for_unpickling__' attribute with a true value. I'm not sure
1533 why it does this, but I've sure seen this complaint often enough when
1534 I didn't want to <wink>.
1540 stack_before
=[anyobject
, anyobject
],
1541 stack_after
=[anyobject
],
1543 doc
="""Finish building an object, via __setstate__ or dict update.
1545 Stack before: ... anyobject argument
1546 Stack after: ... anyobject
1548 where anyobject may have been mutated, as follows:
1550 If the object has a __setstate__ method,
1552 anyobject.__setstate__(argument)
1556 Else the argument must be a dict, the object must have a __dict__, and
1557 the object is updated via
1559 anyobject.__dict__.update(argument)
1561 This may raise RuntimeError in restricted execution mode (which
1562 disallows access to __dict__ directly); in that case, the object
1563 is updated instead via
1565 for k, v in argument.items():
1571 arg
=stringnl_noescape_pair
,
1572 stack_before
=[markobject
, stackslice
],
1573 stack_after
=[anyobject
],
1575 doc
="""Build a class instance.
1577 This is the protocol 0 version of protocol 1's OBJ opcode.
1578 INST is followed by two newline-terminated strings, giving a
1579 module and class name, just as for the GLOBAL opcode (and see
1580 GLOBAL for more details about that). self.find_class(module, name)
1581 is used to get a class object.
1583 In addition, all the objects on the stack following the topmost
1584 markobject are gathered into a tuple and popped (along with the
1585 topmost markobject), just as for the TUPLE opcode.
1587 Now it gets complicated. If all of these are true:
1589 + The argtuple is empty (markobject was at the top of the stack
1592 + It's an old-style class object (the type of the class object is
1595 + The class object does not have a __getinitargs__ attribute.
1597 then we want to create an old-style class instance without invoking
1598 its __init__() method (pickle has waffled on this over the years; not
1599 calling __init__() is current wisdom). In this case, an instance of
1600 an old-style dummy class is created, and then we try to rebind its
1601 __class__ attribute to the desired class object. If this succeeds,
1602 the new instance object is pushed on the stack, and we're done. In
1603 restricted execution mode it can fail (assignment to __class__ is
1604 disallowed), and I'm not really sure what happens then -- it looks
1605 like the code ends up calling the class object's __init__ anyway,
1606 via falling into the next case.
1608 Else (the argtuple is not empty, it's not an old-style class object,
1609 or the class object does have a __getinitargs__ attribute), the code
1610 first insists that the class object have a __safe_for_unpickling__
1611 attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE,
1612 it doesn't matter whether this attribute has a true or false value, it
1613 only matters whether it exists (XXX this is a bug; cPickle
1614 requires the attribute to be true). If __safe_for_unpickling__
1615 doesn't exist, UnpicklingError is raised.
1617 Else (the class object does have a __safe_for_unpickling__ attr),
1618 the class object obtained from INST's arguments is applied to the
1619 argtuple obtained from the stack, and the resulting instance object
1620 is pushed on the stack.
1622 NOTE: checks for __safe_for_unpickling__ went away in Python 2.3.
1628 stack_before
=[markobject
, anyobject
, stackslice
],
1629 stack_after
=[anyobject
],
1631 doc
="""Build a class instance.
1633 This is the protocol 1 version of protocol 0's INST opcode, and is
1634 very much like it. The major difference is that the class object
1635 is taken off the stack, allowing it to be retrieved from the memo
1636 repeatedly if several instances of the same class are created. This
1637 can be much more efficient (in both time and space) than repeatedly
1638 embedding the module and class names in INST opcodes.
1640 Unlike INST, OBJ takes no arguments from the opcode stream. Instead
1641 the class object is taken off the stack, immediately above the
1644 Stack before: ... markobject classobject stackslice
1645 Stack after: ... new_instance_object
1647 As for INST, the remainder of the stack above the markobject is
1648 gathered into an argument tuple, and then the logic seems identical,
1649 except that no __safe_for_unpickling__ check is done (XXX this is
1650 a bug; cPickle does test __safe_for_unpickling__). See INST for
1653 NOTE: In Python 2.3, INST and OBJ are identical except for how they
1654 get the class object. That was always the intent; the implementations
1655 had diverged for accidental reasons.
1661 stack_before
=[anyobject
, anyobject
],
1662 stack_after
=[anyobject
],
1664 doc
="""Build an object instance.
1666 The stack before should be thought of as containing a class
1667 object followed by an argument tuple (the tuple being the stack
1668 top). Call these cls and args. They are popped off the stack,
1669 and the value returned by cls.__new__(cls, *args) is pushed back
1681 doc
="""Protocol version indicator.
1683 For protocol 2 and above, a pickle must start with this opcode.
1684 The argument is the protocol version, an int in range(2, 256).
1690 stack_before
=[anyobject
],
1693 doc
="""Stop the unpickling machine.
1695 Every pickle ends with this opcode. The object at the top of the stack
1696 is popped, and that's the result of unpickling. The stack should be
1700 # Ways to deal with persistent IDs.
1704 arg
=stringnl_noescape
,
1706 stack_after
=[anyobject
],
1708 doc
="""Push an object identified by a persistent ID.
1710 The pickle module doesn't define what a persistent ID means. PERSID's
1711 argument is a newline-terminated str-style (no embedded escapes, no
1712 bracketing quote characters) string, which *is* "the persistent ID".
1713 The unpickler passes this string to self.persistent_load(). Whatever
1714 object that returns is pushed on the stack. There is no implementation
1715 of persistent_load() in Python's unpickler: it must be supplied by an
1722 stack_before
=[anyobject
],
1723 stack_after
=[anyobject
],
1725 doc
="""Push an object identified by a persistent ID.
1727 Like PERSID, except the persistent ID is popped off the stack (instead
1728 of being a string embedded in the opcode bytestream). The persistent
1729 ID is passed to self.persistent_load(), and whatever object that
1730 returns is pushed on the stack. See PERSID for more detail.
1735 # Verify uniqueness of .name and .code members.
1739 for i
, d
in enumerate(opcodes
):
1740 if d
.name
in name2i
:
1741 raise ValueError("repeated name %r at indices %d and %d" %
1742 (d
.name
, name2i
[d
.name
], i
))
1743 if d
.code
in code2i
:
1744 raise ValueError("repeated code %r at indices %d and %d" %
1745 (d
.code
, code2i
[d
.code
], i
))
1750 del name2i
, code2i
, i
, d
1752 ##############################################################################
1753 # Build a code2op dict, mapping opcode characters to OpcodeInfo records.
1754 # Also ensure we've got the same stuff as pickle.py, although the
1755 # introspection here is dicey.
1762 def assure_pickle_consistency(verbose
=False):
1765 copy
= code2op
.copy()
1766 for name
in pickle
.__all
__:
1767 if not re
.match("[A-Z][A-Z0-9_]+$", name
):
1769 print "skipping %r: it doesn't look like an opcode name" % name
1771 picklecode
= getattr(pickle
, name
)
1772 if not isinstance(picklecode
, str) or len(picklecode
) != 1:
1774 print ("skipping %r: value %r doesn't look like a pickle "
1775 "code" % (name
, picklecode
))
1777 if picklecode
in copy
:
1779 print "checking name %r w/ code %r for consistency" % (
1781 d
= copy
[picklecode
]
1783 raise ValueError("for pickle code %r, pickle.py uses name %r "
1784 "but we're using name %r" % (picklecode
,
1787 # Forget this one. Any left over in copy at the end are a problem
1788 # of a different kind.
1789 del copy
[picklecode
]
1791 raise ValueError("pickle.py appears to have a pickle opcode with "
1792 "name %r and code %r, but we don't" %
1795 msg
= ["we appear to have pickle opcodes that pickle.py doesn't have:"]
1796 for code
, d
in copy
.items():
1797 msg
.append(" name %r with code %r" % (d
.name
, code
))
1798 raise ValueError("\n".join(msg
))
1800 assure_pickle_consistency()
1801 del assure_pickle_consistency
1803 ##############################################################################
1804 # A pickle opcode generator.
1807 """Generate all the opcodes in a pickle.
1809 'pickle' is a file-like object, or string, containing the pickle.
1811 Each opcode in the pickle is generated, from the current pickle position,
1812 stopping after a STOP opcode is delivered. A triple is generated for
1817 opcode is an OpcodeInfo record, describing the current opcode.
1819 If the opcode has an argument embedded in the pickle, arg is its decoded
1820 value, as a Python object. If the opcode doesn't have an argument, arg
1823 If the pickle has a tell() method, pos was the value of pickle.tell()
1824 before reading the current opcode. If the pickle is a string object,
1825 it's wrapped in a StringIO object, and the latter's tell() result is
1826 used. Else (the pickle doesn't have a tell(), and it's not obvious how
1827 to query its current position) pos is None.
1830 import cStringIO
as StringIO
1832 if isinstance(pickle
, str):
1833 pickle
= StringIO
.StringIO(pickle
)
1835 if hasattr(pickle
, "tell"):
1836 getpos
= pickle
.tell
1838 getpos
= lambda: None
1842 code
= pickle
.read(1)
1843 opcode
= code2op
.get(code
)
1846 raise ValueError("pickle exhausted before seeing STOP")
1848 raise ValueError("at position %s, opcode %r unknown" % (
1849 pos
is None and "<unknown>" or pos
,
1851 if opcode
.arg
is None:
1854 arg
= opcode
.arg
.reader(pickle
)
1855 yield opcode
, arg
, pos
1857 assert opcode
.name
== 'STOP'
1860 ##############################################################################
1861 # A symbolic pickle disassembler.
1863 def dis(pickle
, out
=None, memo
=None, indentlevel
=4):
1864 """Produce a symbolic disassembly of a pickle.
1866 'pickle' is a file-like object, or string, containing a (at least one)
1867 pickle. The pickle is disassembled from the current position, through
1868 the first STOP opcode encountered.
1870 Optional arg 'out' is a file-like object to which the disassembly is
1871 printed. It defaults to sys.stdout.
1873 Optional arg 'memo' is a Python dict, used as the pickle's memo. It
1874 may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes.
1875 Passing the same memo object to another dis() call then allows disassembly
1876 to proceed across multiple pickles that were all created by the same
1877 pickler with the same memo. Ordinarily you don't need to worry about this.
1879 Optional arg indentlevel is the number of blanks by which to indent
1880 a new MARK level. It defaults to 4.
1882 In addition to printing the disassembly, some sanity checks are made:
1884 + All embedded opcode arguments "make sense".
1886 + Explicit and implicit pop operations have enough items on the stack.
1888 + When an opcode implicitly refers to a markobject, a markobject is
1889 actually on the stack.
1891 + A memo entry isn't referenced before it's defined.
1893 + The markobject isn't stored in the memo.
1895 + A memo entry isn't redefined.
1898 # Most of the hair here is for sanity checks, but most of it is needed
1899 # anyway to detect when a protocol 0 POP takes a MARK off the stack
1900 # (which in turn is needed to indent MARK blocks correctly).
1902 stack
= [] # crude emulation of unpickler stack
1904 memo
= {} # crude emulation of unpicker memo
1905 maxproto
= -1 # max protocol number seen
1906 markstack
= [] # bytecode positions of MARK opcodes
1907 indentchunk
= ' ' * indentlevel
1909 for opcode
, arg
, pos
in genops(pickle
):
1911 print >> out
, "%5d:" % pos
,
1913 line
= "%-4s %s%s" % (repr(opcode
.code
)[1:-1],
1914 indentchunk
* len(markstack
),
1917 maxproto
= max(maxproto
, opcode
.proto
)
1918 before
= opcode
.stack_before
# don't mutate
1919 after
= opcode
.stack_after
# don't mutate
1920 numtopop
= len(before
)
1922 # See whether a MARK should be popped.
1924 if markobject
in before
or (opcode
.name
== "POP" and
1926 stack
[-1] is markobject
):
1927 assert markobject
not in after
1929 if markobject
in before
:
1930 assert before
[-1] is stackslice
1932 markpos
= markstack
.pop()
1934 markmsg
= "(MARK at unknown opcode offset)"
1936 markmsg
= "(MARK at %d)" % markpos
1937 # Pop everything at and after the topmost markobject.
1938 while stack
[-1] is not markobject
:
1941 # Stop later code from popping too much.
1943 numtopop
= before
.index(markobject
)
1945 assert opcode
.name
== "POP"
1948 errormsg
= markmsg
= "no MARK exists on stack"
1950 # Check for correct memo usage.
1951 if opcode
.name
in ("PUT", "BINPUT", "LONG_BINPUT"):
1952 assert arg
is not None
1954 errormsg
= "memo key %r already defined" % arg
1956 errormsg
= "stack is empty -- can't store into memo"
1957 elif stack
[-1] is markobject
:
1958 errormsg
= "can't store markobject in the memo"
1960 memo
[arg
] = stack
[-1]
1962 elif opcode
.name
in ("GET", "BINGET", "LONG_BINGET"):
1964 assert len(after
) == 1
1965 after
= [memo
[arg
]] # for better stack emulation
1967 errormsg
= "memo key %r has never been stored into" % arg
1969 if arg
is not None or markmsg
:
1970 # make a mild effort to align arguments
1971 line
+= ' ' * (10 - len(opcode
.name
))
1973 line
+= ' ' + repr(arg
)
1975 line
+= ' ' + markmsg
1979 # Note that we delayed complaining until the offending opcode
1981 raise ValueError(errormsg
)
1983 # Emulate the stack effects.
1984 if len(stack
) < numtopop
:
1985 raise ValueError("tries to pop %d items from stack with "
1986 "only %d items" % (numtopop
, len(stack
)))
1988 del stack
[-numtopop
:]
1989 if markobject
in after
:
1990 assert markobject
not in before
1991 markstack
.append(pos
)
1995 print >> out
, "highest protocol among opcodes =", maxproto
1997 raise ValueError("stack not empty after STOP: %r" % stack
)
1999 # For use in the doctest, simply as an example of a class to pickle.
2001 def __init__(self
, value
):
2006 >>> x = [1, 2, (3, 4), {'abc': u"def"}]
2007 >>> pkl = pickle.dumps(x, 0)
2010 1: l LIST (MARK at 0)
2019 20: t TUPLE (MARK at 13)
2023 26: d DICT (MARK at 25)
2027 40: V UNICODE u'def'
2032 highest protocol among opcodes = 0
2034 Try again with a "binary" pickle.
2036 >>> pkl = pickle.dumps(x, 1)
2046 13: t TUPLE (MARK at 8)
2050 19: U SHORT_BINSTRING 'abc'
2052 26: X BINUNICODE u'def'
2055 37: e APPENDS (MARK at 3)
2057 highest protocol among opcodes = 1
2059 Exercise the INST/OBJ/BUILD family.
2062 >>> dis(pickle.dumps(random.random, 0))
2063 0: c GLOBAL 'random random'
2066 highest protocol among opcodes = 0
2068 >>> from pickletools import _Example
2069 >>> x = [_Example(42)] * 2
2070 >>> dis(pickle.dumps(x, 0))
2072 1: l LIST (MARK at 0)
2075 6: i INST 'pickletools _Example' (MARK at 5)
2078 32: d DICT (MARK at 31)
2080 36: S STRING 'value'
2089 highest protocol among opcodes = 0
2091 >>> dis(pickle.dumps(x, 1))
2096 5: c GLOBAL 'pickletools _Example'
2098 29: o OBJ (MARK at 4)
2102 35: U SHORT_BINSTRING 'value'
2108 50: e APPENDS (MARK at 3)
2110 highest protocol among opcodes = 1
2112 Try "the canonical" recursive-object test.
2125 >>> dis(pickle.dumps(L, 0))
2127 1: l LIST (MARK at 0)
2131 9: t TUPLE (MARK at 5)
2135 highest protocol among opcodes = 0
2137 >>> dis(pickle.dumps(L, 1))
2142 6: t TUPLE (MARK at 3)
2146 highest protocol among opcodes = 1
2148 Note that, in the protocol 0 pickle of the recursive tuple, the disassembler
2149 has to emulate the stack in order to realize that the POP opcode at 16 gets
2150 rid of the MARK at 0.
2152 >>> dis(pickle.dumps(T, 0))
2155 2: l LIST (MARK at 1)
2159 10: t TUPLE (MARK at 6)
2163 16: 0 POP (MARK at 0)
2166 highest protocol among opcodes = 0
2168 >>> dis(pickle.dumps(T, 1))
2174 7: t TUPLE (MARK at 4)
2177 11: 1 POP_MARK (MARK at 0)
2180 highest protocol among opcodes = 1
2184 >>> dis(pickle.dumps(L, 2))
2193 highest protocol among opcodes = 2
2195 >>> dis(pickle.dumps(T, 2))
2206 highest protocol among opcodes = 2
2211 >>> from StringIO import StringIO
2213 >>> p = pickle.Pickler(f, 2)
2219 >>> dis(f, memo=memo)
2227 12: e APPENDS (MARK at 5)
2229 highest protocol among opcodes = 2
2230 >>> dis(f, memo=memo)
2234 highest protocol among opcodes = 2
2237 __test__
= {'disassembler_test': _dis_test
,
2238 'disassembler_memo_test': _memo_test
,
2243 return doctest
.testmod()
2245 if __name__
== "__main__":