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, indentlevel=4)
10 Print a symbolic disassembly of a pickle.
15 # - A pickle verifier: read a pickle and check it exhaustively for
16 # well-formedness. dis() does a lot of this already.
18 # - A protocol identifier: examine a pickle and return its protocol number
19 # (== the highest .proto attr value among all the opcodes in the pickle).
20 # dis() already prints this info at the end.
22 # - A pickle optimizer: for example, tuple-building code is sometimes more
23 # elaborate than necessary, catering for the possibility that the tuple
24 # is recursive. Or lots of times a PUT is generated that's never accessed
29 "A pickle" is a program for a virtual pickle machine (PM, but more accurately
30 called an unpickling machine). It's a sequence of opcodes, interpreted by the
31 PM, building an arbitrarily complex Python object.
33 For the most part, the PM is very simple: there are no looping, testing, or
34 conditional instructions, no arithmetic and no function calls. Opcodes are
35 executed once each, from first to last, until a STOP opcode is reached.
37 The PM has two data areas, "the stack" and "the memo".
39 Many opcodes push Python objects onto the stack; e.g., INT pushes a Python
40 integer object on the stack, whose value is gotten from a decimal string
41 literal immediately following the INT opcode in the pickle bytestream. Other
42 opcodes take Python objects off the stack. The result of unpickling is
43 whatever object is left on the stack when the final STOP opcode is executed.
45 The memo is simply an array of objects, or it can be implemented as a dict
46 mapping little integers to objects. The memo serves as the PM's "long term
47 memory", and the little integers indexing the memo are akin to variable
48 names. Some opcodes pop a stack object into the memo at a given index,
49 and others push a memo object at a given index onto the stack again.
51 At heart, that's all the PM has. Subtleties arise for these reasons:
53 + Object identity. Objects can be arbitrarily complex, and subobjects
54 may be shared (for example, the list [a, a] refers to the same object a
55 twice). It can be vital that unpickling recreate an isomorphic object
56 graph, faithfully reproducing sharing.
58 + Recursive objects. For example, after "L = []; L.append(L)", L is a
59 list, and L[0] is the same list. This is related to the object identity
60 point, and some sequences of pickle opcodes are subtle in order to
61 get the right result in all cases.
63 + Things pickle doesn't know everything about. Examples of things pickle
64 does know everything about are Python's builtin scalar and container
65 types, like ints and tuples. They generally have opcodes dedicated to
66 them. For things like module references and instances of user-defined
67 classes, pickle's knowledge is limited. Historically, many enhancements
68 have been made to the pickle protocol in order to do a better (faster,
69 and/or more compact) job on those.
71 + Backward compatibility and micro-optimization. As explained below,
72 pickle opcodes never go away, not even when better ways to do a thing
73 get invented. The repertoire of the PM just keeps growing over time.
74 For example, protocol 0 had two opcodes for building Python integers (INT
75 and LONG), protocol 1 added three more for more-efficient pickling of short
76 integers, and protocol 2 added two more for more-efficient pickling of
77 long integers (before protocol 2, the only ways to pickle a Python long
78 took time quadratic in the number of digits, for both pickling and
79 unpickling). "Opcode bloat" isn't so much a subtlety as a source of
80 wearying complication.
85 For compatibility, the meaning of a pickle opcode never changes. Instead new
86 pickle opcodes get added, and each version's unpickler can handle all the
87 pickle opcodes in all protocol versions to date. So old pickles continue to
88 be readable forever. The pickler can generally be told to restrict itself to
89 the subset of opcodes available under previous protocol versions too, so that
90 users can create pickles under the current version readable by older
91 versions. However, a pickle does not contain its version number embedded
92 within it. If an older unpickler tries to read a pickle using a later
93 protocol, the result is most likely an exception due to seeing an unknown (in
94 the older unpickler) opcode.
96 The original pickle used what's now called "protocol 0", and what was called
97 "text mode" before Python 2.3. The entire pickle bytestream is made up of
98 printable 7-bit ASCII characters, plus the newline character, in protocol 0.
99 That's why it was called text mode. Protocol 0 is small and elegant, but
100 sometimes painfully inefficient.
102 The second major set of additions is now called "protocol 1", and was called
103 "binary mode" before Python 2.3. This added many opcodes with arguments
104 consisting of arbitrary bytes, including NUL bytes and unprintable "high bit"
105 bytes. Binary mode pickles can be substantially smaller than equivalent
106 text mode pickles, and sometimes faster too; e.g., BININT represents a 4-byte
107 int as 4 bytes following the opcode, which is cheaper to unpickle than the
108 (perhaps) 11-character decimal string attached to INT. Protocol 1 also added
109 a number of opcodes that operate on many stack elements at once (like APPENDS
110 and SETITEMS), and "shortcut" opcodes (like EMPTY_DICT and EMPTY_TUPLE).
112 The third major set of additions came in Python 2.3, and is called "protocol
115 - A better way to pickle instances of new-style classes (NEWOBJ).
117 - A way for a pickle to identify its protocol (PROTO).
119 - Time- and space- efficient pickling of long ints (LONG{1,4}).
121 - Shortcuts for small tuples (TUPLE{1,2,3}}.
123 - Dedicated opcodes for bools (NEWTRUE, NEWFALSE).
125 - The "extension registry", a vector of popular objects that can be pushed
126 efficiently by index (EXT{1,2,4}). This is akin to the memo and GET, but
127 the registry contents are predefined (there's nothing akin to the memo's
130 Another independent change with Python 2.3 is the abandonment of any
131 pretense that it might be safe to load pickles received from untrusted
132 parties -- no sufficient security analysis has been done to guarantee
133 this and there isn't a use case that warrants the expense of such an
136 To this end, all tests for __safe_for_unpickling__ or for
137 copy_reg.safe_constructors are removed from the unpickling code.
138 References to these variables in the descriptions below are to be seen
139 as describing unpickling in Python 2.2 and before.
142 # Meta-rule: Descriptions are stored in instances of descriptor objects,
143 # with plain constructors. No meta-language is defined from which
144 # descriptors could be constructed. If you want, e.g., XML, write a little
145 # program to generate XML from the objects.
147 ##############################################################################
148 # Some pickle opcodes have an argument, following the opcode in the
149 # bytestream. An argument is of a specific type, described by an instance
150 # of ArgumentDescriptor. These are not to be confused with arguments taken
151 # off the stack -- ArgumentDescriptor applies only to arguments embedded in
152 # the opcode stream, immediately following an opcode.
154 # Represents the number of bytes consumed by an argument delimited by the
155 # next newline character.
158 # Represents the number of bytes consumed by a two-argument opcode where
159 # the first argument gives the number of bytes in the second argument.
160 TAKEN_FROM_ARGUMENT1
= -2 # num bytes is 1-byte unsigned int
161 TAKEN_FROM_ARGUMENT4
= -3 # num bytes is 4-byte signed little-endian int
163 class ArgumentDescriptor(object):
165 # name of descriptor record, also a module global name; a string
168 # length of argument, in bytes; an int; UP_TO_NEWLINE and
169 # TAKEN_FROM_ARGUMENT{1,4} are negative values for variable-length
173 # a function taking a file-like object, reading this kind of argument
174 # from the object at the current position, advancing the current
175 # position by n bytes, and returning the value of the argument
178 # human-readable docs for this arg descriptor; a string
182 def __init__(self
, name
, n
, reader
, doc
):
183 assert isinstance(name
, str)
186 assert isinstance(n
, int) and (n
>= 0 or
188 TAKEN_FROM_ARGUMENT1
,
189 TAKEN_FROM_ARGUMENT4
))
194 assert isinstance(doc
, str)
197 from struct
import unpack
as _unpack
202 >>> read_uint1(StringIO.StringIO('\xff'))
209 raise ValueError("not enough data in stream to read uint1")
211 uint1
= ArgumentDescriptor(
215 doc
="One-byte unsigned integer.")
221 >>> read_uint2(StringIO.StringIO('\xff\x00'))
223 >>> read_uint2(StringIO.StringIO('\xff\xff'))
229 return _unpack("<H", data
)[0]
230 raise ValueError("not enough data in stream to read uint2")
232 uint2
= ArgumentDescriptor(
236 doc
="Two-byte unsigned integer, little-endian.")
242 >>> read_int4(StringIO.StringIO('\xff\x00\x00\x00'))
244 >>> read_int4(StringIO.StringIO('\x00\x00\x00\x80')) == -(2**31)
250 return _unpack("<i", data
)[0]
251 raise ValueError("not enough data in stream to read int4")
253 int4
= ArgumentDescriptor(
257 doc
="Four-byte signed integer, little-endian, 2's complement.")
260 def read_stringnl(f
, decode
=True, stripquotes
=True):
263 >>> read_stringnl(StringIO.StringIO("'abcd'\nefg\n"))
266 >>> read_stringnl(StringIO.StringIO("\n"))
267 Traceback (most recent call last):
269 ValueError: no string quotes around ''
271 >>> read_stringnl(StringIO.StringIO("\n"), stripquotes=False)
274 >>> read_stringnl(StringIO.StringIO("''\n"))
277 >>> read_stringnl(StringIO.StringIO('"abcd"'))
278 Traceback (most recent call last):
280 ValueError: no newline found when trying to read stringnl
282 Embedded escapes are undone in the result.
283 >>> read_stringnl(StringIO.StringIO(r"'a\n\\b\x00c\td'" + "\n'e'"))
288 if not data
.endswith('\n'):
289 raise ValueError("no newline found when trying to read stringnl")
290 data
= data
[:-1] # lose the newline
294 if data
.startswith(q
):
295 if not data
.endswith(q
):
296 raise ValueError("strinq quote %r not found at both "
297 "ends of %r" % (q
, data
))
301 raise ValueError("no string quotes around %r" % data
)
303 # I'm not sure when 'string_escape' was added to the std codecs; it's
304 # crazy not to use it if it's there.
306 data
= data
.decode('string_escape')
309 stringnl
= ArgumentDescriptor(
312 reader
=read_stringnl
,
313 doc
="""A newline-terminated string.
315 This is a repr-style string, with embedded escapes, and
319 def read_stringnl_noescape(f
):
320 return read_stringnl(f
, decode
=False, stripquotes
=False)
322 stringnl_noescape
= ArgumentDescriptor(
323 name
='stringnl_noescape',
325 reader
=read_stringnl_noescape
,
326 doc
="""A newline-terminated string.
328 This is a str-style string, without embedded escapes,
329 or bracketing quotes. It should consist solely of
330 printable ASCII characters.
333 def read_stringnl_noescape_pair(f
):
336 >>> read_stringnl_noescape_pair(StringIO.StringIO("Queue\nEmpty\njunk"))
340 return "%s %s" % (read_stringnl_noescape(f
), read_stringnl_noescape(f
))
342 stringnl_noescape_pair
= ArgumentDescriptor(
343 name
='stringnl_noescape_pair',
345 reader
=read_stringnl_noescape_pair
,
346 doc
="""A pair of newline-terminated strings.
348 These are str-style strings, without embedded
349 escapes, or bracketing quotes. They should
350 consist solely of printable ASCII characters.
351 The pair is returned as a single string, with
352 a single blank separating the two strings.
358 >>> read_string4(StringIO.StringIO("\x00\x00\x00\x00abc"))
360 >>> read_string4(StringIO.StringIO("\x03\x00\x00\x00abcdef"))
362 >>> read_string4(StringIO.StringIO("\x00\x00\x00\x03abcdef"))
363 Traceback (most recent call last):
365 ValueError: expected 50331648 bytes in a string4, but only 6 remain
370 raise ValueError("string4 byte count < 0: %d" % n
)
374 raise ValueError("expected %d bytes in a string4, but only %d remain" %
377 string4
= ArgumentDescriptor(
379 n
=TAKEN_FROM_ARGUMENT4
,
381 doc
="""A counted string.
383 The first argument is a 4-byte little-endian signed int giving
384 the number of bytes in the string, and the second argument is
392 >>> read_string1(StringIO.StringIO("\x00"))
394 >>> read_string1(StringIO.StringIO("\x03abcdef"))
403 raise ValueError("expected %d bytes in a string1, but only %d remain" %
406 string1
= ArgumentDescriptor(
408 n
=TAKEN_FROM_ARGUMENT1
,
410 doc
="""A counted string.
412 The first argument is a 1-byte unsigned int giving the number
413 of bytes in the string, and the second argument is that many
418 def read_unicodestringnl(f
):
421 >>> read_unicodestringnl(StringIO.StringIO("abc\uabcd\njunk"))
426 if not data
.endswith('\n'):
427 raise ValueError("no newline found when trying to read "
429 data
= data
[:-1] # lose the newline
430 return unicode(data
, 'raw-unicode-escape')
432 unicodestringnl
= ArgumentDescriptor(
433 name
='unicodestringnl',
435 reader
=read_unicodestringnl
,
436 doc
="""A newline-terminated Unicode string.
438 This is raw-unicode-escape encoded, so consists of
439 printable ASCII characters, and may contain embedded
443 def read_unicodestring4(f
):
446 >>> s = u'abcd\uabcd'
447 >>> enc = s.encode('utf-8')
450 >>> n = chr(len(enc)) + chr(0) * 3 # little-endian 4-byte length
451 >>> t = read_unicodestring4(StringIO.StringIO(n + enc + 'junk'))
455 >>> read_unicodestring4(StringIO.StringIO(n + enc[:-1]))
456 Traceback (most recent call last):
458 ValueError: expected 7 bytes in a unicodestring4, but only 6 remain
463 raise ValueError("unicodestring4 byte count < 0: %d" % n
)
466 return unicode(data
, 'utf-8')
467 raise ValueError("expected %d bytes in a unicodestring4, but only %d "
468 "remain" % (n
, len(data
)))
470 unicodestring4
= ArgumentDescriptor(
471 name
="unicodestring4",
472 n
=TAKEN_FROM_ARGUMENT4
,
473 reader
=read_unicodestring4
,
474 doc
="""A counted Unicode string.
476 The first argument is a 4-byte little-endian signed int
477 giving the number of bytes in the string, and the second
478 argument-- the UTF-8 encoding of the Unicode string --
479 contains that many bytes.
483 def read_decimalnl_short(f
):
486 >>> read_decimalnl_short(StringIO.StringIO("1234\n56"))
489 >>> read_decimalnl_short(StringIO.StringIO("1234L\n56"))
490 Traceback (most recent call last):
492 ValueError: trailing 'L' not allowed in '1234L'
495 s
= read_stringnl(f
, decode
=False, stripquotes
=False)
497 raise ValueError("trailing 'L' not allowed in %r" % s
)
499 # It's not necessarily true that the result fits in a Python short int:
500 # the pickle may have been written on a 64-bit box. There's also a hack
501 # for True and False here.
509 except OverflowError:
512 def read_decimalnl_long(f
):
516 >>> read_decimalnl_long(StringIO.StringIO("1234\n56"))
517 Traceback (most recent call last):
519 ValueError: trailing 'L' required in '1234'
521 Someday the trailing 'L' will probably go away from this output.
523 >>> read_decimalnl_long(StringIO.StringIO("1234L\n56"))
526 >>> read_decimalnl_long(StringIO.StringIO("123456789012345678901234L\n6"))
527 123456789012345678901234L
530 s
= read_stringnl(f
, decode
=False, stripquotes
=False)
531 if not s
.endswith("L"):
532 raise ValueError("trailing 'L' required in %r" % s
)
536 decimalnl_short
= ArgumentDescriptor(
537 name
='decimalnl_short',
539 reader
=read_decimalnl_short
,
540 doc
="""A newline-terminated decimal integer literal.
542 This never has a trailing 'L', and the integer fit
543 in a short Python int on the box where the pickle
544 was written -- but there's no guarantee it will fit
545 in a short Python int on the box where the pickle
549 decimalnl_long
= ArgumentDescriptor(
550 name
='decimalnl_long',
552 reader
=read_decimalnl_long
,
553 doc
="""A newline-terminated decimal integer literal.
555 This has a trailing 'L', and can represent integers
563 >>> read_floatnl(StringIO.StringIO("-1.25\n6"))
566 s
= read_stringnl(f
, decode
=False, stripquotes
=False)
569 floatnl
= ArgumentDescriptor(
573 doc
="""A newline-terminated decimal floating literal.
575 In general this requires 17 significant digits for roundtrip
576 identity, and pickling then unpickling infinities, NaNs, and
577 minus zero doesn't work across boxes, or on some boxes even
578 on itself (e.g., Windows can't read the strings it produces
579 for infinities or NaNs).
584 >>> import StringIO, struct
585 >>> raw = struct.pack(">d", -1.25)
587 '\xbf\xf4\x00\x00\x00\x00\x00\x00'
588 >>> read_float8(StringIO.StringIO(raw + "\n"))
594 return _unpack(">d", data
)[0]
595 raise ValueError("not enough data in stream to read float8")
598 float8
= ArgumentDescriptor(
602 doc
="""An 8-byte binary representation of a float, big-endian.
604 The format is unique to Python, and shared with the struct
605 module (format string '>d') "in theory" (the struct and cPickle
606 implementations don't share the code -- they should). It's
607 strongly related to the IEEE-754 double format, and, in normal
608 cases, is in fact identical to the big-endian 754 double format.
609 On other boxes the dynamic range is limited to that of a 754
610 double, and "add a half and chop" rounding is used to reduce
611 the precision to 53 bits. However, even on a 754 box,
612 infinities, NaNs, and minus zero may not be handled correctly
613 (may not survive roundtrip pickling intact).
618 from pickle
import decode_long
623 >>> read_long1(StringIO.StringIO("\x00"))
625 >>> read_long1(StringIO.StringIO("\x02\xff\x00"))
627 >>> read_long1(StringIO.StringIO("\x02\xff\x7f"))
629 >>> read_long1(StringIO.StringIO("\x02\x00\xff"))
631 >>> read_long1(StringIO.StringIO("\x02\x00\x80"))
638 raise ValueError("not enough data in stream to read long1")
639 return decode_long(data
)
641 long1
= ArgumentDescriptor(
643 n
=TAKEN_FROM_ARGUMENT1
,
645 doc
="""A binary long, little-endian, using 1-byte size.
647 This first reads one byte as an unsigned size, then reads that
648 many bytes and interprets them as a little-endian 2's-complement long.
649 If the size is 0, that's taken as a shortcut for the long 0L.
655 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00"))
657 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f"))
659 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff"))
661 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80"))
663 >>> read_long1(StringIO.StringIO("\x00\x00\x00\x00"))
669 raise ValueError("long4 byte count < 0: %d" % n
)
672 raise ValueError("not enough data in stream to read long4")
673 return decode_long(data
)
675 long4
= ArgumentDescriptor(
677 n
=TAKEN_FROM_ARGUMENT4
,
679 doc
="""A binary representation of a long, little-endian.
681 This first reads four bytes as a signed size (but requires the
682 size to be >= 0), then reads that many bytes and interprets them
683 as a little-endian 2's-complement long. If the size is 0, that's taken
684 as a shortcut for the long 0L, although LONG1 should really be used
685 then instead (and in any case where # of bytes < 256).
689 ##############################################################################
690 # Object descriptors. The stack used by the pickle machine holds objects,
691 # and in the stack_before and stack_after attributes of OpcodeInfo
692 # descriptors we need names to describe the various types of objects that can
693 # appear on the stack.
695 class StackObject(object):
697 # name of descriptor record, for info only
700 # type of object, or tuple of type objects (meaning the object can
701 # be of any type in the tuple)
704 # human-readable docs for this kind of stack object; a string
708 def __init__(self
, name
, obtype
, doc
):
709 assert isinstance(name
, str)
712 assert isinstance(obtype
, type) or isinstance(obtype
, tuple)
713 if isinstance(obtype
, tuple):
714 for contained
in obtype
:
715 assert isinstance(contained
, type)
718 assert isinstance(doc
, str)
728 doc
="A short (as opposed to long) Python integer object.")
730 pylong
= StackObject(
733 doc
="A long (as opposed to short) Python integer object.")
735 pyinteger_or_bool
= StackObject(
737 obtype
=(int, long, bool),
738 doc
="A Python integer object (short or long), or "
741 pybool
= StackObject(
744 doc
="A Python bool object.")
746 pyfloat
= StackObject(
749 doc
="A Python float object.")
751 pystring
= StackObject(
754 doc
="A Python string object.")
756 pyunicode
= StackObject(
759 doc
="A Python Unicode string object.")
761 pynone
= StackObject(
764 doc
="The Python None object.")
766 pytuple
= StackObject(
769 doc
="A Python tuple object.")
771 pylist
= StackObject(
774 doc
="A Python list object.")
776 pydict
= StackObject(
779 doc
="A Python dict object.")
781 anyobject
= StackObject(
784 doc
="Any kind of object whatsoever.")
786 markobject
= StackObject(
789 doc
="""'The mark' is a unique object.
791 Opcodes that operate on a variable number of objects
792 generally don't embed the count of objects in the opcode,
793 or pull it off the stack. Instead the MARK opcode is used
794 to push a special marker object on the stack, and then
795 some other opcodes grab all the objects from the top of
796 the stack down to (but not including) the topmost marker
800 stackslice
= StackObject(
803 doc
="""An object representing a contiguous slice of the stack.
805 This is used in conjuction with markobject, to represent all
806 of the stack following the topmost markobject. For example,
807 the POP_MARK opcode changes the stack from
809 [..., markobject, stackslice]
813 No matter how many object are on the stack after the topmost
814 markobject, POP_MARK gets rid of all of them (including the
815 topmost markobject too).
818 ##############################################################################
819 # Descriptors for pickle opcodes.
821 class OpcodeInfo(object):
824 # symbolic name of opcode; a string
827 # the code used in a bytestream to represent the opcode; a
828 # one-character string
831 # If the opcode has an argument embedded in the byte string, an
832 # instance of ArgumentDescriptor specifying its type. Note that
833 # arg.reader(s) can be used to read and decode the argument from
834 # the bytestream s, and arg.doc documents the format of the raw
835 # argument bytes. If the opcode doesn't have an argument embedded
836 # in the bytestream, arg should be None.
839 # what the stack looks like before this opcode runs; a list
842 # what the stack looks like after this opcode runs; a list
845 # the protocol number in which this opcode was introduced; an int
848 # human-readable docs for this opcode; a string
852 def __init__(self
, name
, code
, arg
,
853 stack_before
, stack_after
, proto
, doc
):
854 assert isinstance(name
, str)
857 assert isinstance(code
, str)
858 assert len(code
) == 1
861 assert arg
is None or isinstance(arg
, ArgumentDescriptor
)
864 assert isinstance(stack_before
, list)
865 for x
in stack_before
:
866 assert isinstance(x
, StackObject
)
867 self
.stack_before
= stack_before
869 assert isinstance(stack_after
, list)
870 for x
in stack_after
:
871 assert isinstance(x
, StackObject
)
872 self
.stack_after
= stack_after
874 assert isinstance(proto
, int) and 0 <= proto
<= 2
877 assert isinstance(doc
, str)
883 # Ways to spell integers.
889 stack_after
=[pyinteger_or_bool
],
891 doc
="""Push an integer or bool.
893 The argument is a newline-terminated decimal literal string.
895 The intent may have been that this always fit in a short Python int,
896 but INT can be generated in pickles written on a 64-bit box that
897 require a Python long on a 32-bit box. The difference between this
898 and LONG then is that INT skips a trailing 'L', and produces a short
899 int whenever possible.
901 Another difference is due to that, when bool was introduced as a
902 distinct type in 2.3, builtin names True and False were also added to
903 2.2.2, mapping to ints 1 and 0. For compatibility in both directions,
904 True gets pickled as INT + "I01\\n", and False as INT + "I00\\n".
905 Leading zeroes are never produced for a genuine integer. The 2.3
906 (and later) unpicklers special-case these and return bool instead;
907 earlier unpicklers ignore the leading "0" and return the int.
916 doc
="""Push a four-byte signed integer.
918 This handles the full range of Python (short) integers on a 32-bit
919 box, directly as binary bytes (1 for the opcode and 4 for the integer).
920 If the integer is non-negative and fits in 1 or 2 bytes, pickling via
921 BININT1 or BININT2 saves space.
930 doc
="""Push a one-byte unsigned integer.
932 This is a space optimization for pickling very small non-negative ints,
942 doc
="""Push a two-byte unsigned integer.
944 This is a space optimization for pickling small positive ints, in
945 range(256, 2**16). Integers in range(256) can also be pickled via
946 BININT2, but BININT1 instead saves a byte.
953 stack_after
=[pylong
],
955 doc
="""Push a long integer.
957 The same as INT, except that the literal ends with 'L', and always
958 unpickles to a Python long. There doesn't seem a real purpose to the
961 Note that LONG takes time quadratic in the number of digits when
962 unpickling (this is simply due to the nature of decimal->binary
963 conversion). Proto 2 added linear-time (in C; still quadratic-time
964 in Python) LONG1 and LONG4 opcodes.
971 stack_after
=[pylong
],
973 doc
="""Long integer using one-byte length.
975 A more efficient encoding of a Python long; the long1 encoding
982 stack_after
=[pylong
],
984 doc
="""Long integer using found-byte length.
986 A more efficient encoding of a Python long; the long4 encoding
989 # Ways to spell strings (8-bit, not Unicode).
995 stack_after
=[pystring
],
997 doc
="""Push a Python string object.
999 The argument is a repr-style string, with bracketing quote characters,
1000 and perhaps embedded escapes. The argument extends until the next
1008 stack_after
=[pystring
],
1010 doc
="""Push a Python string object.
1012 There are two arguments: the first is a 4-byte little-endian signed int
1013 giving the number of bytes in the string, and the second is that many
1014 bytes, which are taken literally as the string content.
1017 I(name
='SHORT_BINSTRING',
1021 stack_after
=[pystring
],
1023 doc
="""Push a Python string object.
1025 There are two arguments: the first is a 1-byte unsigned int giving
1026 the number of bytes in the string, and the second is that many bytes,
1027 which are taken literally as the string content.
1030 # Ways to spell None.
1036 stack_after
=[pynone
],
1038 doc
="Push None on the stack."),
1040 # Ways to spell bools, starting with proto 2. See INT for how this was
1041 # done before proto 2.
1047 stack_after
=[pybool
],
1051 Push True onto the stack."""),
1057 stack_after
=[pybool
],
1061 Push False onto the stack."""),
1063 # Ways to spell Unicode strings.
1067 arg
=unicodestringnl
,
1069 stack_after
=[pyunicode
],
1070 proto
=0, # this may be pure-text, but it's a later addition
1071 doc
="""Push a Python Unicode string object.
1073 The argument is a raw-unicode-escape encoding of a Unicode string,
1074 and so may contain embedded escape sequences. The argument extends
1075 until the next newline character.
1078 I(name
='BINUNICODE',
1082 stack_after
=[pyunicode
],
1084 doc
="""Push a Python Unicode string object.
1086 There are two arguments: the first is a 4-byte little-endian signed int
1087 giving the number of bytes in the string. The second is that many
1088 bytes, and is the UTF-8 encoding of the Unicode string.
1091 # Ways to spell floats.
1097 stack_after
=[pyfloat
],
1099 doc
="""Newline-terminated decimal float literal.
1101 The argument is repr(a_float), and in general requires 17 significant
1102 digits for roundtrip conversion to be an identity (this is so for
1103 IEEE-754 double precision values, which is what Python float maps to
1106 In general, FLOAT cannot be used to transport infinities, NaNs, or
1107 minus zero across boxes (or even on a single box, if the platform C
1108 library can't read the strings it produces for such things -- Windows
1109 is like that), but may do less damage than BINFLOAT on boxes with
1110 greater precision or dynamic range than IEEE-754 double.
1117 stack_after
=[pyfloat
],
1119 doc
="""Float stored in binary form, with 8 bytes of data.
1121 This generally requires less than half the space of FLOAT encoding.
1122 In general, BINFLOAT cannot be used to transport infinities, NaNs, or
1123 minus zero, raises an exception if the exponent exceeds the range of
1124 an IEEE-754 double, and retains no more than 53 bits of precision (if
1125 there are more than that, "add a half and chop" rounding is used to
1126 cut it back to 53 significant bits).
1129 # Ways to build lists.
1131 I(name
='EMPTY_LIST',
1135 stack_after
=[pylist
],
1137 doc
="Push an empty list."),
1142 stack_before
=[pylist
, anyobject
],
1143 stack_after
=[pylist
],
1145 doc
="""Append an object to a list.
1147 Stack before: ... pylist anyobject
1148 Stack after: ... pylist+[anyobject]
1150 although pylist is really extended in-place.
1156 stack_before
=[pylist
, markobject
, stackslice
],
1157 stack_after
=[pylist
],
1159 doc
="""Extend a list by a slice of stack objects.
1161 Stack before: ... pylist markobject stackslice
1162 Stack after: ... pylist+stackslice
1164 although pylist is really extended in-place.
1170 stack_before
=[markobject
, stackslice
],
1171 stack_after
=[pylist
],
1173 doc
="""Build a list out of the topmost stack slice, after markobject.
1175 All the stack entries following the topmost markobject are placed into
1176 a single Python list, which single list object replaces all of the
1177 stack from the topmost markobject onward. For example,
1179 Stack before: ... markobject 1 2 3 'abc'
1180 Stack after: ... [1, 2, 3, 'abc']
1183 # Ways to build tuples.
1185 I(name
='EMPTY_TUPLE',
1189 stack_after
=[pytuple
],
1191 doc
="Push an empty tuple."),
1196 stack_before
=[markobject
, stackslice
],
1197 stack_after
=[pytuple
],
1199 doc
="""Build a tuple out of the topmost stack slice, after markobject.
1201 All the stack entries following the topmost markobject are placed into
1202 a single Python tuple, which single tuple object replaces all of the
1203 stack from the topmost markobject onward. For example,
1205 Stack before: ... markobject 1 2 3 'abc'
1206 Stack after: ... (1, 2, 3, 'abc')
1212 stack_before
=[anyobject
],
1213 stack_after
=[pytuple
],
1217 This code pops one value off the stack and pushes a tuple of
1218 length 1 whose one item is that value back onto it. IOW:
1220 stack[-1] = tuple(stack[-1:])
1226 stack_before
=[anyobject
, anyobject
],
1227 stack_after
=[pytuple
],
1231 This code pops two values off the stack and pushes a tuple
1232 of length 2 whose items are those values back onto it. IOW:
1234 stack[-2:] = [tuple(stack[-2:])]
1240 stack_before
=[anyobject
, anyobject
, anyobject
],
1241 stack_after
=[pytuple
],
1245 This code pops three values off the stack and pushes a tuple
1246 of length 3 whose items are those values back onto it. IOW:
1248 stack[-3:] = [tuple(stack[-3:])]
1251 # Ways to build dicts.
1253 I(name
='EMPTY_DICT',
1257 stack_after
=[pydict
],
1259 doc
="Push an empty dict."),
1264 stack_before
=[markobject
, stackslice
],
1265 stack_after
=[pydict
],
1267 doc
="""Build a dict out of the topmost stack slice, after markobject.
1269 All the stack entries following the topmost markobject are placed into
1270 a single Python dict, which single dict object replaces all of the
1271 stack from the topmost markobject onward. The stack slice alternates
1272 key, value, key, value, .... For example,
1274 Stack before: ... markobject 1 2 3 'abc'
1275 Stack after: ... {1: 2, 3: 'abc'}
1281 stack_before
=[pydict
, anyobject
, anyobject
],
1282 stack_after
=[pydict
],
1284 doc
="""Add a key+value pair to an existing dict.
1286 Stack before: ... pydict key value
1287 Stack after: ... pydict
1289 where pydict has been modified via pydict[key] = value.
1295 stack_before
=[pydict
, markobject
, stackslice
],
1296 stack_after
=[pydict
],
1298 doc
="""Add an arbitrary number of key+value pairs to an existing dict.
1300 The slice of the stack following the topmost markobject is taken as
1301 an alternating sequence of keys and values, added to the dict
1302 immediately under the topmost markobject. Everything at and after the
1303 topmost markobject is popped, leaving the mutated dict at the top
1306 Stack before: ... pydict markobject key_1 value_1 ... key_n value_n
1307 Stack after: ... pydict
1309 where pydict has been modified via pydict[key_i] = value_i for i in
1310 1, 2, ..., n, and in that order.
1313 # Stack manipulation.
1318 stack_before
=[anyobject
],
1321 doc
="Discard the top stack item, shrinking the stack by one item."),
1326 stack_before
=[anyobject
],
1327 stack_after
=[anyobject
, anyobject
],
1329 doc
="Push the top stack item onto the stack again, duplicating it."),
1335 stack_after
=[markobject
],
1337 doc
="""Push markobject onto the stack.
1339 markobject is a unique object, used by other opcodes to identify a
1340 region of the stack containing a variable number of objects for them
1341 to work on. See markobject.doc for more detail.
1347 stack_before
=[markobject
, stackslice
],
1350 doc
="""Pop all the stack objects at and above the topmost markobject.
1352 When an opcode using a variable number of stack objects is done,
1353 POP_MARK is used to remove those objects, and to remove the markobject
1354 that delimited their starting position on the stack.
1357 # Memo manipulation. There are really only two operations (get and put),
1358 # each in all-text, "short binary", and "long binary" flavors.
1362 arg
=decimalnl_short
,
1364 stack_after
=[anyobject
],
1366 doc
="""Read an object from the memo and push it on the stack.
1368 The index of the memo object to push is given by the newline-teriminated
1369 decimal string following. BINGET and LONG_BINGET are space-optimized
1377 stack_after
=[anyobject
],
1379 doc
="""Read an object from the memo and push it on the stack.
1381 The index of the memo object to push is given by the 1-byte unsigned
1385 I(name
='LONG_BINGET',
1389 stack_after
=[anyobject
],
1391 doc
="""Read an object from the memo and push it on the stack.
1393 The index of the memo object to push is given by the 4-byte signed
1394 little-endian integer following.
1399 arg
=decimalnl_short
,
1403 doc
="""Store the stack top into the memo. The stack is not popped.
1405 The index of the memo location to write into is given by the newline-
1406 terminated decimal string following. BINPUT and LONG_BINPUT are
1407 space-optimized versions.
1416 doc
="""Store the stack top into the memo. The stack is not popped.
1418 The index of the memo location to write into is given by the 1-byte
1419 unsigned integer following.
1422 I(name
='LONG_BINPUT',
1428 doc
="""Store the stack top into the memo. The stack is not popped.
1430 The index of the memo location to write into is given by the 4-byte
1431 signed little-endian integer following.
1434 # Access the extension registry (predefined objects). Akin to the GET
1441 stack_after
=[anyobject
],
1443 doc
="""Extension code.
1445 This code and the similar EXT2 and EXT4 allow using a registry
1446 of popular objects that are pickled by name, typically classes.
1447 It is envisioned that through a global negotiation and
1448 registration process, third parties can set up a mapping between
1449 ints and object names.
1451 In order to guarantee pickle interchangeability, the extension
1452 code registry ought to be global, although a range of codes may
1453 be reserved for private use.
1455 EXT1 has a 1-byte integer argument. This is used to index into the
1456 extension registry, and the object at that index is pushed on the stack.
1463 stack_after
=[anyobject
],
1465 doc
="""Extension code.
1467 See EXT1. EXT2 has a two-byte integer argument.
1474 stack_after
=[anyobject
],
1476 doc
="""Extension code.
1478 See EXT1. EXT4 has a four-byte integer argument.
1481 # Push a class object, or module function, on the stack, via its module
1486 arg
=stringnl_noescape_pair
,
1488 stack_after
=[anyobject
],
1490 doc
="""Push a global object (module.attr) on the stack.
1492 Two newline-terminated strings follow the GLOBAL opcode. The first is
1493 taken as a module name, and the second as a class name. The class
1494 object module.class is pushed on the stack. More accurately, the
1495 object returned by self.find_class(module, class) is pushed on the
1496 stack, so unpickling subclasses can override this form of lookup.
1499 # Ways to build objects of classes pickle doesn't know about directly
1500 # (user-defined classes). I despair of documenting this accurately
1501 # and comprehensibly -- you really have to read the pickle code to
1502 # find all the special cases.
1507 stack_before
=[anyobject
, anyobject
],
1508 stack_after
=[anyobject
],
1510 doc
="""Push an object built from a callable and an argument tuple.
1512 The opcode is named to remind of the __reduce__() method.
1514 Stack before: ... callable pytuple
1515 Stack after: ... callable(*pytuple)
1517 The callable and the argument tuple are the first two items returned
1518 by a __reduce__ method. Applying the callable to the argtuple is
1519 supposed to reproduce the original object, or at least get it started.
1520 If the __reduce__ method returns a 3-tuple, the last component is an
1521 argument to be passed to the object's __setstate__, and then the REDUCE
1522 opcode is followed by code to create setstate's argument, and then a
1523 BUILD opcode to apply __setstate__ to that argument.
1525 There are lots of special cases here. The argtuple can be None, in
1526 which case callable.__basicnew__() is called instead to produce the
1527 object to be pushed on the stack. This appears to be a trick unique
1528 to ExtensionClasses, and is deprecated regardless.
1530 If type(callable) is not ClassType, REDUCE complains unless the
1531 callable has been registered with the copy_reg module's
1532 safe_constructors dict, or the callable has a magic
1533 '__safe_for_unpickling__' attribute with a true value. I'm not sure
1534 why it does this, but I've sure seen this complaint often enough when
1535 I didn't want to <wink>.
1541 stack_before
=[anyobject
, anyobject
],
1542 stack_after
=[anyobject
],
1544 doc
="""Finish building an object, via __setstate__ or dict update.
1546 Stack before: ... anyobject argument
1547 Stack after: ... anyobject
1549 where anyobject may have been mutated, as follows:
1551 If the object has a __setstate__ method,
1553 anyobject.__setstate__(argument)
1557 Else the argument must be a dict, the object must have a __dict__, and
1558 the object is updated via
1560 anyobject.__dict__.update(argument)
1562 This may raise RuntimeError in restricted execution mode (which
1563 disallows access to __dict__ directly); in that case, the object
1564 is updated instead via
1566 for k, v in argument.items():
1572 arg
=stringnl_noescape_pair
,
1573 stack_before
=[markobject
, stackslice
],
1574 stack_after
=[anyobject
],
1576 doc
="""Build a class instance.
1578 This is the protocol 0 version of protocol 1's OBJ opcode.
1579 INST is followed by two newline-terminated strings, giving a
1580 module and class name, just as for the GLOBAL opcode (and see
1581 GLOBAL for more details about that). self.find_class(module, name)
1582 is used to get a class object.
1584 In addition, all the objects on the stack following the topmost
1585 markobject are gathered into a tuple and popped (along with the
1586 topmost markobject), just as for the TUPLE opcode.
1588 Now it gets complicated. If all of these are true:
1590 + The argtuple is empty (markobject was at the top of the stack
1593 + It's an old-style class object (the type of the class object is
1596 + The class object does not have a __getinitargs__ attribute.
1598 then we want to create an old-style class instance without invoking
1599 its __init__() method (pickle has waffled on this over the years; not
1600 calling __init__() is current wisdom). In this case, an instance of
1601 an old-style dummy class is created, and then we try to rebind its
1602 __class__ attribute to the desired class object. If this succeeds,
1603 the new instance object is pushed on the stack, and we're done. In
1604 restricted execution mode it can fail (assignment to __class__ is
1605 disallowed), and I'm not really sure what happens then -- it looks
1606 like the code ends up calling the class object's __init__ anyway,
1607 via falling into the next case.
1609 Else (the argtuple is not empty, it's not an old-style class object,
1610 or the class object does have a __getinitargs__ attribute), the code
1611 first insists that the class object have a __safe_for_unpickling__
1612 attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE,
1613 it doesn't matter whether this attribute has a true or false value, it
1614 only matters whether it exists (XXX this is a bug; cPickle
1615 requires the attribute to be true). If __safe_for_unpickling__
1616 doesn't exist, UnpicklingError is raised.
1618 Else (the class object does have a __safe_for_unpickling__ attr),
1619 the class object obtained from INST's arguments is applied to the
1620 argtuple obtained from the stack, and the resulting instance object
1621 is pushed on the stack.
1623 NOTE: checks for __safe_for_unpickling__ went away in Python 2.3.
1629 stack_before
=[markobject
, anyobject
, stackslice
],
1630 stack_after
=[anyobject
],
1632 doc
="""Build a class instance.
1634 This is the protocol 1 version of protocol 0's INST opcode, and is
1635 very much like it. The major difference is that the class object
1636 is taken off the stack, allowing it to be retrieved from the memo
1637 repeatedly if several instances of the same class are created. This
1638 can be much more efficient (in both time and space) than repeatedly
1639 embedding the module and class names in INST opcodes.
1641 Unlike INST, OBJ takes no arguments from the opcode stream. Instead
1642 the class object is taken off the stack, immediately above the
1645 Stack before: ... markobject classobject stackslice
1646 Stack after: ... new_instance_object
1648 As for INST, the remainder of the stack above the markobject is
1649 gathered into an argument tuple, and then the logic seems identical,
1650 except that no __safe_for_unpickling__ check is done (XXX this is
1651 a bug; cPickle does test __safe_for_unpickling__). See INST for
1654 NOTE: In Python 2.3, INST and OBJ are identical except for how they
1655 get the class object. That was always the intent; the implementations
1656 had diverged for accidental reasons.
1662 stack_before
=[anyobject
, anyobject
],
1663 stack_after
=[anyobject
],
1665 doc
="""Build an object instance.
1667 The stack before should be thought of as containing a class
1668 object followed by an argument tuple (the tuple being the stack
1669 top). Call these cls and args. They are popped off the stack,
1670 and the value returned by cls.__new__(cls, *args) is pushed back
1682 doc
="""Protocol version indicator.
1684 For protocol 2 and above, a pickle must start with this opcode.
1685 The argument is the protocol version, an int in range(2, 256).
1691 stack_before
=[anyobject
],
1694 doc
="""Stop the unpickling machine.
1696 Every pickle ends with this opcode. The object at the top of the stack
1697 is popped, and that's the result of unpickling. The stack should be
1701 # Ways to deal with persistent IDs.
1705 arg
=stringnl_noescape
,
1707 stack_after
=[anyobject
],
1709 doc
="""Push an object identified by a persistent ID.
1711 The pickle module doesn't define what a persistent ID means. PERSID's
1712 argument is a newline-terminated str-style (no embedded escapes, no
1713 bracketing quote characters) string, which *is* "the persistent ID".
1714 The unpickler passes this string to self.persistent_load(). Whatever
1715 object that returns is pushed on the stack. There is no implementation
1716 of persistent_load() in Python's unpickler: it must be supplied by an
1723 stack_before
=[anyobject
],
1724 stack_after
=[anyobject
],
1726 doc
="""Push an object identified by a persistent ID.
1728 Like PERSID, except the persistent ID is popped off the stack (instead
1729 of being a string embedded in the opcode bytestream). The persistent
1730 ID is passed to self.persistent_load(), and whatever object that
1731 returns is pushed on the stack. See PERSID for more detail.
1736 # Verify uniqueness of .name and .code members.
1740 for i
, d
in enumerate(opcodes
):
1741 if d
.name
in name2i
:
1742 raise ValueError("repeated name %r at indices %d and %d" %
1743 (d
.name
, name2i
[d
.name
], i
))
1744 if d
.code
in code2i
:
1745 raise ValueError("repeated code %r at indices %d and %d" %
1746 (d
.code
, code2i
[d
.code
], i
))
1751 del name2i
, code2i
, i
, d
1753 ##############################################################################
1754 # Build a code2op dict, mapping opcode characters to OpcodeInfo records.
1755 # Also ensure we've got the same stuff as pickle.py, although the
1756 # introspection here is dicey.
1763 def assure_pickle_consistency(verbose
=False):
1766 copy
= code2op
.copy()
1767 for name
in pickle
.__all
__:
1768 if not re
.match("[A-Z][A-Z0-9_]+$", name
):
1770 print "skipping %r: it doesn't look like an opcode name" % name
1772 picklecode
= getattr(pickle
, name
)
1773 if not isinstance(picklecode
, str) or len(picklecode
) != 1:
1775 print ("skipping %r: value %r doesn't look like a pickle "
1776 "code" % (name
, picklecode
))
1778 if picklecode
in copy
:
1780 print "checking name %r w/ code %r for consistency" % (
1782 d
= copy
[picklecode
]
1784 raise ValueError("for pickle code %r, pickle.py uses name %r "
1785 "but we're using name %r" % (picklecode
,
1788 # Forget this one. Any left over in copy at the end are a problem
1789 # of a different kind.
1790 del copy
[picklecode
]
1792 raise ValueError("pickle.py appears to have a pickle opcode with "
1793 "name %r and code %r, but we don't" %
1796 msg
= ["we appear to have pickle opcodes that pickle.py doesn't have:"]
1797 for code
, d
in copy
.items():
1798 msg
.append(" name %r with code %r" % (d
.name
, code
))
1799 raise ValueError("\n".join(msg
))
1801 assure_pickle_consistency()
1802 del assure_pickle_consistency
1804 ##############################################################################
1805 # A pickle opcode generator.
1808 """Generate all the opcodes in a pickle.
1810 'pickle' is a file-like object, or string, containing the pickle.
1812 Each opcode in the pickle is generated, from the current pickle position,
1813 stopping after a STOP opcode is delivered. A triple is generated for
1818 opcode is an OpcodeInfo record, describing the current opcode.
1820 If the opcode has an argument embedded in the pickle, arg is its decoded
1821 value, as a Python object. If the opcode doesn't have an argument, arg
1824 If the pickle has a tell() method, pos was the value of pickle.tell()
1825 before reading the current opcode. If the pickle is a string object,
1826 it's wrapped in a StringIO object, and the latter's tell() result is
1827 used. Else (the pickle doesn't have a tell(), and it's not obvious how
1828 to query its current position) pos is None.
1831 import cStringIO
as StringIO
1833 if isinstance(pickle
, str):
1834 pickle
= StringIO
.StringIO(pickle
)
1836 if hasattr(pickle
, "tell"):
1837 getpos
= pickle
.tell
1839 getpos
= lambda: None
1843 code
= pickle
.read(1)
1844 opcode
= code2op
.get(code
)
1847 raise ValueError("pickle exhausted before seeing STOP")
1849 raise ValueError("at position %s, opcode %r unknown" % (
1850 pos
is None and "<unknown>" or pos
,
1852 if opcode
.arg
is None:
1855 arg
= opcode
.arg
.reader(pickle
)
1856 yield opcode
, arg
, pos
1858 assert opcode
.name
== 'STOP'
1861 ##############################################################################
1862 # A symbolic pickle disassembler.
1864 def dis(pickle
, out
=None, memo
=None, indentlevel
=4):
1865 """Produce a symbolic disassembly of a pickle.
1867 'pickle' is a file-like object, or string, containing a (at least one)
1868 pickle. The pickle is disassembled from the current position, through
1869 the first STOP opcode encountered.
1871 Optional arg 'out' is a file-like object to which the disassembly is
1872 printed. It defaults to sys.stdout.
1874 Optional arg 'memo' is a Python dict, used as the pickle's memo. It
1875 may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes.
1876 Passing the same memo object to another dis() call then allows disassembly
1877 to proceed across multiple pickles that were all created by the same
1878 pickler with the same memo. Ordinarily you don't need to worry about this.
1880 Optional arg indentlevel is the number of blanks by which to indent
1881 a new MARK level. It defaults to 4.
1883 In addition to printing the disassembly, some sanity checks are made:
1885 + All embedded opcode arguments "make sense".
1887 + Explicit and implicit pop operations have enough items on the stack.
1889 + When an opcode implicitly refers to a markobject, a markobject is
1890 actually on the stack.
1892 + A memo entry isn't referenced before it's defined.
1894 + The markobject isn't stored in the memo.
1896 + A memo entry isn't redefined.
1899 # Most of the hair here is for sanity checks, but most of it is needed
1900 # anyway to detect when a protocol 0 POP takes a MARK off the stack
1901 # (which in turn is needed to indent MARK blocks correctly).
1903 stack
= [] # crude emulation of unpickler stack
1905 memo
= {} # crude emulation of unpicker memo
1906 maxproto
= -1 # max protocol number seen
1907 markstack
= [] # bytecode positions of MARK opcodes
1908 indentchunk
= ' ' * indentlevel
1910 for opcode
, arg
, pos
in genops(pickle
):
1912 print >> out
, "%5d:" % pos
,
1914 line
= "%-4s %s%s" % (repr(opcode
.code
)[1:-1],
1915 indentchunk
* len(markstack
),
1918 maxproto
= max(maxproto
, opcode
.proto
)
1919 before
= opcode
.stack_before
# don't mutate
1920 after
= opcode
.stack_after
# don't mutate
1921 numtopop
= len(before
)
1923 # See whether a MARK should be popped.
1925 if markobject
in before
or (opcode
.name
== "POP" and
1927 stack
[-1] is markobject
):
1928 assert markobject
not in after
1930 if markobject
in before
:
1931 assert before
[-1] is stackslice
1933 markpos
= markstack
.pop()
1935 markmsg
= "(MARK at unknown opcode offset)"
1937 markmsg
= "(MARK at %d)" % markpos
1938 # Pop everything at and after the topmost markobject.
1939 while stack
[-1] is not markobject
:
1942 # Stop later code from popping too much.
1944 numtopop
= before
.index(markobject
)
1946 assert opcode
.name
== "POP"
1949 errormsg
= markmsg
= "no MARK exists on stack"
1951 # Check for correct memo usage.
1952 if opcode
.name
in ("PUT", "BINPUT", "LONG_BINPUT"):
1953 assert arg
is not None
1955 errormsg
= "memo key %r already defined" % arg
1957 errormsg
= "stack is empty -- can't store into memo"
1958 elif stack
[-1] is markobject
:
1959 errormsg
= "can't store markobject in the memo"
1961 memo
[arg
] = stack
[-1]
1963 elif opcode
.name
in ("GET", "BINGET", "LONG_BINGET"):
1965 assert len(after
) == 1
1966 after
= [memo
[arg
]] # for better stack emulation
1968 errormsg
= "memo key %r has never been stored into" % arg
1970 if arg
is not None or markmsg
:
1971 # make a mild effort to align arguments
1972 line
+= ' ' * (10 - len(opcode
.name
))
1974 line
+= ' ' + repr(arg
)
1976 line
+= ' ' + markmsg
1980 # Note that we delayed complaining until the offending opcode
1982 raise ValueError(errormsg
)
1984 # Emulate the stack effects.
1985 if len(stack
) < numtopop
:
1986 raise ValueError("tries to pop %d items from stack with "
1987 "only %d items" % (numtopop
, len(stack
)))
1989 del stack
[-numtopop
:]
1990 if markobject
in after
:
1991 assert markobject
not in before
1992 markstack
.append(pos
)
1996 print >> out
, "highest protocol among opcodes =", maxproto
1998 raise ValueError("stack not empty after STOP: %r" % stack
)
2002 >>> x = [1, 2, (3, 4), {'abc': u"def"}]
2003 >>> pkl = pickle.dumps(x, 0)
2006 1: l LIST (MARK at 0)
2015 20: t TUPLE (MARK at 13)
2019 26: d DICT (MARK at 25)
2023 40: V UNICODE u'def'
2028 highest protocol among opcodes = 0
2030 Try again with a "binary" pickle.
2032 >>> pkl = pickle.dumps(x, 1)
2042 13: t TUPLE (MARK at 8)
2046 19: U SHORT_BINSTRING 'abc'
2048 26: X BINUNICODE u'def'
2051 37: e APPENDS (MARK at 3)
2053 highest protocol among opcodes = 1
2055 Exercise the INST/OBJ/BUILD family.
2058 >>> dis(pickle.dumps(random.random, 0))
2059 0: c GLOBAL 'random random'
2062 highest protocol among opcodes = 0
2064 >>> x = [pickle.PicklingError()] * 2
2065 >>> dis(pickle.dumps(x, 0))
2067 1: l LIST (MARK at 0)
2070 6: i INST 'pickle PicklingError' (MARK at 5)
2073 32: d DICT (MARK at 31)
2078 48: t TUPLE (MARK at 47)
2085 highest protocol among opcodes = 0
2087 >>> dis(pickle.dumps(x, 1))
2092 5: c GLOBAL 'pickle PicklingError'
2094 29: o OBJ (MARK at 4)
2098 35: U SHORT_BINSTRING 'args'
2104 48: e APPENDS (MARK at 3)
2106 highest protocol among opcodes = 1
2108 Try "the canonical" recursive-object test.
2121 >>> dis(pickle.dumps(L, 0))
2123 1: l LIST (MARK at 0)
2127 9: t TUPLE (MARK at 5)
2131 highest protocol among opcodes = 0
2133 >>> dis(pickle.dumps(L, 1))
2138 6: t TUPLE (MARK at 3)
2142 highest protocol among opcodes = 1
2144 Note that, in the protocol 0 pickle of the recursive tuple, the disassembler
2145 has to emulate the stack in order to realize that the POP opcode at 16 gets
2146 rid of the MARK at 0.
2148 >>> dis(pickle.dumps(T, 0))
2151 2: l LIST (MARK at 1)
2155 10: t TUPLE (MARK at 6)
2159 16: 0 POP (MARK at 0)
2162 highest protocol among opcodes = 0
2164 >>> dis(pickle.dumps(T, 1))
2170 7: t TUPLE (MARK at 4)
2173 11: 1 POP_MARK (MARK at 0)
2176 highest protocol among opcodes = 1
2180 >>> dis(pickle.dumps(L, 2))
2189 highest protocol among opcodes = 2
2191 >>> dis(pickle.dumps(T, 2))
2202 highest protocol among opcodes = 2
2207 >>> from StringIO import StringIO
2209 >>> p = pickle.Pickler(f, 2)
2215 >>> dis(f, memo=memo)
2223 12: e APPENDS (MARK at 5)
2225 highest protocol among opcodes = 2
2226 >>> dis(f, memo=memo)
2230 highest protocol among opcodes = 2
2233 __test__
= {'disassembler_test': _dis_test
,
2234 'disassembler_memo_test': _memo_test
,
2239 return doctest
.testmod()
2241 if __name__
== "__main__":