blob: 7bc9c678ad7fcd6934719d5736375e9c21944e26 [file] [log] [blame]
Skip Montanaro54455942003-01-29 15:41:33 +00001'''"Executable documentation" for the pickle module.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002
3Extensive comments about the pickle protocols and pickle-machine opcodes
4can be found here. Some functions meant for external use:
5
6genops(pickle)
7 Generate all the opcodes in a pickle, as (opcode, arg, position) triples.
8
Andrew M. Kuchlingd0c53fe2004-08-07 16:51:30 +00009dis(pickle, out=None, memo=None, indentlevel=4)
Tim Peters8ecfc8e2003-01-27 18:51:48 +000010 Print a symbolic disassembly of a pickle.
Skip Montanaro54455942003-01-29 15:41:33 +000011'''
Tim Peters8ecfc8e2003-01-27 18:51:48 +000012
Walter Dörwald42748a82007-06-12 16:40:17 +000013import codecs
Guido van Rossum98297ee2007-11-06 21:34:58 +000014import pickle
15import re
Walter Dörwald42748a82007-06-12 16:40:17 +000016
Christian Heimes3feef612008-02-11 06:19:17 +000017__all__ = ['dis', 'genops', 'optimize']
Tim Peters90cf2122004-11-06 23:45:48 +000018
Guido van Rossum98297ee2007-11-06 21:34:58 +000019bytes_types = pickle.bytes_types
20
Tim Peters8ecfc8e2003-01-27 18:51:48 +000021# Other ideas:
22#
23# - A pickle verifier: read a pickle and check it exhaustively for
Tim Petersc1c2b3e2003-01-29 20:12:21 +000024# well-formedness. dis() does a lot of this already.
Tim Peters8ecfc8e2003-01-27 18:51:48 +000025#
26# - A protocol identifier: examine a pickle and return its protocol number
27# (== the highest .proto attr value among all the opcodes in the pickle).
Tim Petersc1c2b3e2003-01-29 20:12:21 +000028# dis() already prints this info at the end.
Tim Peters8ecfc8e2003-01-27 18:51:48 +000029#
30# - A pickle optimizer: for example, tuple-building code is sometimes more
31# elaborate than necessary, catering for the possibility that the tuple
32# is recursive. Or lots of times a PUT is generated that's never accessed
33# by a later GET.
34
35
36"""
37"A pickle" is a program for a virtual pickle machine (PM, but more accurately
38called an unpickling machine). It's a sequence of opcodes, interpreted by the
39PM, building an arbitrarily complex Python object.
40
41For the most part, the PM is very simple: there are no looping, testing, or
42conditional instructions, no arithmetic and no function calls. Opcodes are
43executed once each, from first to last, until a STOP opcode is reached.
44
45The PM has two data areas, "the stack" and "the memo".
46
47Many opcodes push Python objects onto the stack; e.g., INT pushes a Python
48integer object on the stack, whose value is gotten from a decimal string
49literal immediately following the INT opcode in the pickle bytestream. Other
50opcodes take Python objects off the stack. The result of unpickling is
51whatever object is left on the stack when the final STOP opcode is executed.
52
53The memo is simply an array of objects, or it can be implemented as a dict
54mapping little integers to objects. The memo serves as the PM's "long term
55memory", and the little integers indexing the memo are akin to variable
56names. Some opcodes pop a stack object into the memo at a given index,
57and others push a memo object at a given index onto the stack again.
58
59At heart, that's all the PM has. Subtleties arise for these reasons:
60
61+ Object identity. Objects can be arbitrarily complex, and subobjects
62 may be shared (for example, the list [a, a] refers to the same object a
63 twice). It can be vital that unpickling recreate an isomorphic object
64 graph, faithfully reproducing sharing.
65
66+ Recursive objects. For example, after "L = []; L.append(L)", L is a
67 list, and L[0] is the same list. This is related to the object identity
68 point, and some sequences of pickle opcodes are subtle in order to
69 get the right result in all cases.
70
71+ Things pickle doesn't know everything about. Examples of things pickle
72 does know everything about are Python's builtin scalar and container
73 types, like ints and tuples. They generally have opcodes dedicated to
74 them. For things like module references and instances of user-defined
75 classes, pickle's knowledge is limited. Historically, many enhancements
76 have been made to the pickle protocol in order to do a better (faster,
77 and/or more compact) job on those.
78
79+ Backward compatibility and micro-optimization. As explained below,
80 pickle opcodes never go away, not even when better ways to do a thing
81 get invented. The repertoire of the PM just keeps growing over time.
Tim Petersfdc03462003-01-28 04:56:33 +000082 For example, protocol 0 had two opcodes for building Python integers (INT
83 and LONG), protocol 1 added three more for more-efficient pickling of short
84 integers, and protocol 2 added two more for more-efficient pickling of
85 long integers (before protocol 2, the only ways to pickle a Python long
86 took time quadratic in the number of digits, for both pickling and
87 unpickling). "Opcode bloat" isn't so much a subtlety as a source of
Tim Peters8ecfc8e2003-01-27 18:51:48 +000088 wearying complication.
89
90
91Pickle protocols:
92
93For compatibility, the meaning of a pickle opcode never changes. Instead new
94pickle opcodes get added, and each version's unpickler can handle all the
95pickle opcodes in all protocol versions to date. So old pickles continue to
96be readable forever. The pickler can generally be told to restrict itself to
97the subset of opcodes available under previous protocol versions too, so that
98users can create pickles under the current version readable by older
99versions. However, a pickle does not contain its version number embedded
100within it. If an older unpickler tries to read a pickle using a later
101protocol, the result is most likely an exception due to seeing an unknown (in
102the older unpickler) opcode.
103
104The original pickle used what's now called "protocol 0", and what was called
105"text mode" before Python 2.3. The entire pickle bytestream is made up of
106printable 7-bit ASCII characters, plus the newline character, in protocol 0.
Tim Petersfdc03462003-01-28 04:56:33 +0000107That's why it was called text mode. Protocol 0 is small and elegant, but
108sometimes painfully inefficient.
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000109
110The second major set of additions is now called "protocol 1", and was called
111"binary mode" before Python 2.3. This added many opcodes with arguments
112consisting of arbitrary bytes, including NUL bytes and unprintable "high bit"
113bytes. Binary mode pickles can be substantially smaller than equivalent
114text mode pickles, and sometimes faster too; e.g., BININT represents a 4-byte
115int as 4 bytes following the opcode, which is cheaper to unpickle than the
Tim Petersfdc03462003-01-28 04:56:33 +0000116(perhaps) 11-character decimal string attached to INT. Protocol 1 also added
117a number of opcodes that operate on many stack elements at once (like APPENDS
Tim Peters81098ac2003-01-28 05:12:08 +0000118and SETITEMS), and "shortcut" opcodes (like EMPTY_DICT and EMPTY_TUPLE).
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000119
120The third major set of additions came in Python 2.3, and is called "protocol
Tim Petersfdc03462003-01-28 04:56:33 +00001212". This added:
122
123- A better way to pickle instances of new-style classes (NEWOBJ).
124
125- A way for a pickle to identify its protocol (PROTO).
126
127- Time- and space- efficient pickling of long ints (LONG{1,4}).
128
129- Shortcuts for small tuples (TUPLE{1,2,3}}.
130
131- Dedicated opcodes for bools (NEWTRUE, NEWFALSE).
132
133- The "extension registry", a vector of popular objects that can be pushed
134 efficiently by index (EXT{1,2,4}). This is akin to the memo and GET, but
135 the registry contents are predefined (there's nothing akin to the memo's
136 PUT).
Guido van Rossumecb11042003-01-29 06:24:30 +0000137
Skip Montanaro54455942003-01-29 15:41:33 +0000138Another independent change with Python 2.3 is the abandonment of any
139pretense that it might be safe to load pickles received from untrusted
Guido van Rossumecb11042003-01-29 06:24:30 +0000140parties -- no sufficient security analysis has been done to guarantee
Skip Montanaro54455942003-01-29 15:41:33 +0000141this and there isn't a use case that warrants the expense of such an
Guido van Rossumecb11042003-01-29 06:24:30 +0000142analysis.
143
144To this end, all tests for __safe_for_unpickling__ or for
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000145copyreg.safe_constructors are removed from the unpickling code.
Guido van Rossumecb11042003-01-29 06:24:30 +0000146References to these variables in the descriptions below are to be seen
147as describing unpickling in Python 2.2 and before.
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000148"""
149
150# Meta-rule: Descriptions are stored in instances of descriptor objects,
151# with plain constructors. No meta-language is defined from which
152# descriptors could be constructed. If you want, e.g., XML, write a little
153# program to generate XML from the objects.
154
155##############################################################################
156# Some pickle opcodes have an argument, following the opcode in the
157# bytestream. An argument is of a specific type, described by an instance
158# of ArgumentDescriptor. These are not to be confused with arguments taken
159# off the stack -- ArgumentDescriptor applies only to arguments embedded in
160# the opcode stream, immediately following an opcode.
161
162# Represents the number of bytes consumed by an argument delimited by the
163# next newline character.
164UP_TO_NEWLINE = -1
165
166# Represents the number of bytes consumed by a two-argument opcode where
167# the first argument gives the number of bytes in the second argument.
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000168TAKEN_FROM_ARGUMENT1 = -2 # num bytes is 1-byte unsigned int
169TAKEN_FROM_ARGUMENT4 = -3 # num bytes is 4-byte signed little-endian int
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000170
171class ArgumentDescriptor(object):
172 __slots__ = (
173 # name of descriptor record, also a module global name; a string
174 'name',
175
176 # length of argument, in bytes; an int; UP_TO_NEWLINE and
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000177 # TAKEN_FROM_ARGUMENT{1,4} are negative values for variable-length
178 # cases
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000179 'n',
180
181 # a function taking a file-like object, reading this kind of argument
182 # from the object at the current position, advancing the current
183 # position by n bytes, and returning the value of the argument
184 'reader',
185
186 # human-readable docs for this arg descriptor; a string
187 'doc',
188 )
189
190 def __init__(self, name, n, reader, doc):
191 assert isinstance(name, str)
192 self.name = name
193
194 assert isinstance(n, int) and (n >= 0 or
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000195 n in (UP_TO_NEWLINE,
196 TAKEN_FROM_ARGUMENT1,
197 TAKEN_FROM_ARGUMENT4))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000198 self.n = n
199
200 self.reader = reader
201
202 assert isinstance(doc, str)
203 self.doc = doc
204
205from struct import unpack as _unpack
206
207def read_uint1(f):
Tim Peters55762f52003-01-28 16:01:25 +0000208 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000209 >>> import io
210 >>> read_uint1(io.BytesIO(b'\xff'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000211 255
212 """
213
214 data = f.read(1)
215 if data:
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000216 return data[0]
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000217 raise ValueError("not enough data in stream to read uint1")
218
219uint1 = ArgumentDescriptor(
220 name='uint1',
221 n=1,
222 reader=read_uint1,
223 doc="One-byte unsigned integer.")
224
225
226def read_uint2(f):
Tim Peters55762f52003-01-28 16:01:25 +0000227 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000228 >>> import io
229 >>> read_uint2(io.BytesIO(b'\xff\x00'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000230 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000231 >>> read_uint2(io.BytesIO(b'\xff\xff'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000232 65535
233 """
234
235 data = f.read(2)
236 if len(data) == 2:
237 return _unpack("<H", data)[0]
238 raise ValueError("not enough data in stream to read uint2")
239
240uint2 = ArgumentDescriptor(
241 name='uint2',
242 n=2,
243 reader=read_uint2,
244 doc="Two-byte unsigned integer, little-endian.")
245
246
247def read_int4(f):
Tim Peters55762f52003-01-28 16:01:25 +0000248 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000249 >>> import io
250 >>> read_int4(io.BytesIO(b'\xff\x00\x00\x00'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000251 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000252 >>> read_int4(io.BytesIO(b'\x00\x00\x00\x80')) == -(2**31)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000253 True
254 """
255
256 data = f.read(4)
257 if len(data) == 4:
258 return _unpack("<i", data)[0]
259 raise ValueError("not enough data in stream to read int4")
260
261int4 = ArgumentDescriptor(
262 name='int4',
263 n=4,
264 reader=read_int4,
265 doc="Four-byte signed integer, little-endian, 2's complement.")
266
267
268def read_stringnl(f, decode=True, stripquotes=True):
Tim Peters55762f52003-01-28 16:01:25 +0000269 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000270 >>> import io
271 >>> read_stringnl(io.BytesIO(b"'abcd'\nefg\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000272 'abcd'
273
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000274 >>> read_stringnl(io.BytesIO(b"\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000275 Traceback (most recent call last):
276 ...
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000277 ValueError: no string quotes around b''
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000278
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000279 >>> read_stringnl(io.BytesIO(b"\n"), stripquotes=False)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000280 ''
281
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000282 >>> read_stringnl(io.BytesIO(b"''\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000283 ''
284
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000285 >>> read_stringnl(io.BytesIO(b'"abcd"'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000286 Traceback (most recent call last):
287 ...
288 ValueError: no newline found when trying to read stringnl
289
290 Embedded escapes are undone in the result.
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000291 >>> read_stringnl(io.BytesIO(br"'a\n\\b\x00c\td'" + b"\n'e'"))
Tim Peters55762f52003-01-28 16:01:25 +0000292 'a\n\\b\x00c\td'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000293 """
294
Guido van Rossum26986312007-07-17 00:19:46 +0000295 data = f.readline()
Guido van Rossum26d95c32007-08-27 23:18:54 +0000296 if not data.endswith(b'\n'):
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000297 raise ValueError("no newline found when trying to read stringnl")
298 data = data[:-1] # lose the newline
299
300 if stripquotes:
Guido van Rossum26d95c32007-08-27 23:18:54 +0000301 for q in (b'"', b"'"):
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000302 if data.startswith(q):
303 if not data.endswith(q):
304 raise ValueError("strinq quote %r not found at both "
305 "ends of %r" % (q, data))
306 data = data[1:-1]
307 break
308 else:
309 raise ValueError("no string quotes around %r" % data)
310
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000311 if decode:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000312 data = codecs.escape_decode(data)[0].decode("ascii")
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000313 return data
314
315stringnl = ArgumentDescriptor(
316 name='stringnl',
317 n=UP_TO_NEWLINE,
318 reader=read_stringnl,
319 doc="""A newline-terminated string.
320
321 This is a repr-style string, with embedded escapes, and
322 bracketing quotes.
323 """)
324
325def read_stringnl_noescape(f):
Guido van Rossum98297ee2007-11-06 21:34:58 +0000326 return read_stringnl(f, stripquotes=False)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000327
328stringnl_noescape = ArgumentDescriptor(
329 name='stringnl_noescape',
330 n=UP_TO_NEWLINE,
331 reader=read_stringnl_noescape,
332 doc="""A newline-terminated string.
333
334 This is a str-style string, without embedded escapes,
335 or bracketing quotes. It should consist solely of
336 printable ASCII characters.
337 """)
338
339def read_stringnl_noescape_pair(f):
Tim Peters55762f52003-01-28 16:01:25 +0000340 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000341 >>> import io
342 >>> read_stringnl_noescape_pair(io.BytesIO(b"Queue\nEmpty\njunk"))
Tim Petersd916cf42003-01-27 19:01:47 +0000343 'Queue Empty'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000344 """
345
Tim Petersd916cf42003-01-27 19:01:47 +0000346 return "%s %s" % (read_stringnl_noescape(f), read_stringnl_noescape(f))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000347
348stringnl_noescape_pair = ArgumentDescriptor(
349 name='stringnl_noescape_pair',
350 n=UP_TO_NEWLINE,
351 reader=read_stringnl_noescape_pair,
352 doc="""A pair of newline-terminated strings.
353
354 These are str-style strings, without embedded
355 escapes, or bracketing quotes. They should
356 consist solely of printable ASCII characters.
357 The pair is returned as a single string, with
Tim Petersd916cf42003-01-27 19:01:47 +0000358 a single blank separating the two strings.
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000359 """)
360
361def read_string4(f):
Tim Peters55762f52003-01-28 16:01:25 +0000362 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000363 >>> import io
364 >>> read_string4(io.BytesIO(b"\x00\x00\x00\x00abc"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000365 ''
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000366 >>> read_string4(io.BytesIO(b"\x03\x00\x00\x00abcdef"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000367 'abc'
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000368 >>> read_string4(io.BytesIO(b"\x00\x00\x00\x03abcdef"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000369 Traceback (most recent call last):
370 ...
371 ValueError: expected 50331648 bytes in a string4, but only 6 remain
372 """
373
374 n = read_int4(f)
375 if n < 0:
376 raise ValueError("string4 byte count < 0: %d" % n)
377 data = f.read(n)
378 if len(data) == n:
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000379 return data.decode("latin-1")
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000380 raise ValueError("expected %d bytes in a string4, but only %d remain" %
381 (n, len(data)))
382
383string4 = ArgumentDescriptor(
384 name="string4",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000385 n=TAKEN_FROM_ARGUMENT4,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000386 reader=read_string4,
387 doc="""A counted string.
388
389 The first argument is a 4-byte little-endian signed int giving
390 the number of bytes in the string, and the second argument is
391 that many bytes.
392 """)
393
394
395def read_string1(f):
Tim Peters55762f52003-01-28 16:01:25 +0000396 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000397 >>> import io
398 >>> read_string1(io.BytesIO(b"\x00"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000399 ''
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000400 >>> read_string1(io.BytesIO(b"\x03abcdef"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000401 'abc'
402 """
403
404 n = read_uint1(f)
405 assert n >= 0
406 data = f.read(n)
407 if len(data) == n:
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000408 return data.decode("latin-1")
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000409 raise ValueError("expected %d bytes in a string1, but only %d remain" %
410 (n, len(data)))
411
412string1 = ArgumentDescriptor(
413 name="string1",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000414 n=TAKEN_FROM_ARGUMENT1,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000415 reader=read_string1,
416 doc="""A counted string.
417
418 The first argument is a 1-byte unsigned int giving the number
419 of bytes in the string, and the second argument is that many
420 bytes.
421 """)
422
423
424def read_unicodestringnl(f):
Tim Peters55762f52003-01-28 16:01:25 +0000425 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000426 >>> import io
427 >>> read_unicodestringnl(io.BytesIO(b"abc\\uabcd\njunk")) == 'abc\uabcd'
428 True
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000429 """
430
Guido van Rossum26986312007-07-17 00:19:46 +0000431 data = f.readline()
Guido van Rossum26d95c32007-08-27 23:18:54 +0000432 if not data.endswith(b'\n'):
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000433 raise ValueError("no newline found when trying to read "
434 "unicodestringnl")
435 data = data[:-1] # lose the newline
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000436 return str(data, 'raw-unicode-escape')
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000437
438unicodestringnl = ArgumentDescriptor(
439 name='unicodestringnl',
440 n=UP_TO_NEWLINE,
441 reader=read_unicodestringnl,
442 doc="""A newline-terminated Unicode string.
443
444 This is raw-unicode-escape encoded, so consists of
445 printable ASCII characters, and may contain embedded
446 escape sequences.
447 """)
448
449def read_unicodestring4(f):
Tim Peters55762f52003-01-28 16:01:25 +0000450 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000451 >>> import io
452 >>> s = 'abcd\uabcd'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000453 >>> enc = s.encode('utf-8')
454 >>> enc
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000455 b'abcd\xea\xaf\x8d'
456 >>> n = bytes([len(enc), 0, 0, 0]) # little-endian 4-byte length
457 >>> t = read_unicodestring4(io.BytesIO(n + enc + b'junk'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000458 >>> s == t
459 True
460
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000461 >>> read_unicodestring4(io.BytesIO(n + enc[:-1]))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000462 Traceback (most recent call last):
463 ...
464 ValueError: expected 7 bytes in a unicodestring4, but only 6 remain
465 """
466
467 n = read_int4(f)
468 if n < 0:
469 raise ValueError("unicodestring4 byte count < 0: %d" % n)
470 data = f.read(n)
471 if len(data) == n:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000472 return str(data, 'utf-8')
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000473 raise ValueError("expected %d bytes in a unicodestring4, but only %d "
474 "remain" % (n, len(data)))
475
476unicodestring4 = ArgumentDescriptor(
477 name="unicodestring4",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000478 n=TAKEN_FROM_ARGUMENT4,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000479 reader=read_unicodestring4,
480 doc="""A counted Unicode string.
481
482 The first argument is a 4-byte little-endian signed int
483 giving the number of bytes in the string, and the second
484 argument-- the UTF-8 encoding of the Unicode string --
485 contains that many bytes.
486 """)
487
488
489def read_decimalnl_short(f):
Tim Peters55762f52003-01-28 16:01:25 +0000490 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000491 >>> import io
492 >>> read_decimalnl_short(io.BytesIO(b"1234\n56"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000493 1234
494
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000495 >>> read_decimalnl_short(io.BytesIO(b"1234L\n56"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000496 Traceback (most recent call last):
497 ...
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000498 ValueError: trailing 'L' not allowed in b'1234L'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000499 """
500
501 s = read_stringnl(f, decode=False, stripquotes=False)
Guido van Rossum26d95c32007-08-27 23:18:54 +0000502 if s.endswith(b"L"):
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000503 raise ValueError("trailing 'L' not allowed in %r" % s)
504
505 # It's not necessarily true that the result fits in a Python short int:
506 # the pickle may have been written on a 64-bit box. There's also a hack
507 # for True and False here.
Jeremy Hyltona5dc3db2007-08-29 19:07:40 +0000508 if s == b"00":
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000509 return False
Jeremy Hyltona5dc3db2007-08-29 19:07:40 +0000510 elif s == b"01":
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000511 return True
512
513 try:
514 return int(s)
515 except OverflowError:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000516 return int(s)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000517
518def read_decimalnl_long(f):
Tim Peters55762f52003-01-28 16:01:25 +0000519 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000520 >>> import io
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000521
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000522 >>> read_decimalnl_long(io.BytesIO(b"1234L\n56"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000523 1234
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000524
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000525 >>> read_decimalnl_long(io.BytesIO(b"123456789012345678901234L\n6"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000526 123456789012345678901234
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000527 """
528
529 s = read_stringnl(f, decode=False, stripquotes=False)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000530 return int(s)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000531
532
533decimalnl_short = ArgumentDescriptor(
534 name='decimalnl_short',
535 n=UP_TO_NEWLINE,
536 reader=read_decimalnl_short,
537 doc="""A newline-terminated decimal integer literal.
538
539 This never has a trailing 'L', and the integer fit
540 in a short Python int on the box where the pickle
541 was written -- but there's no guarantee it will fit
542 in a short Python int on the box where the pickle
543 is read.
544 """)
545
546decimalnl_long = ArgumentDescriptor(
547 name='decimalnl_long',
548 n=UP_TO_NEWLINE,
549 reader=read_decimalnl_long,
550 doc="""A newline-terminated decimal integer literal.
551
552 This has a trailing 'L', and can represent integers
553 of any size.
554 """)
555
556
557def read_floatnl(f):
Tim Peters55762f52003-01-28 16:01:25 +0000558 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000559 >>> import io
560 >>> read_floatnl(io.BytesIO(b"-1.25\n6"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000561 -1.25
562 """
563 s = read_stringnl(f, decode=False, stripquotes=False)
564 return float(s)
565
566floatnl = ArgumentDescriptor(
567 name='floatnl',
568 n=UP_TO_NEWLINE,
569 reader=read_floatnl,
570 doc="""A newline-terminated decimal floating literal.
571
572 In general this requires 17 significant digits for roundtrip
573 identity, and pickling then unpickling infinities, NaNs, and
574 minus zero doesn't work across boxes, or on some boxes even
575 on itself (e.g., Windows can't read the strings it produces
576 for infinities or NaNs).
577 """)
578
579def read_float8(f):
Tim Peters55762f52003-01-28 16:01:25 +0000580 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000581 >>> import io, struct
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000582 >>> raw = struct.pack(">d", -1.25)
583 >>> raw
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000584 b'\xbf\xf4\x00\x00\x00\x00\x00\x00'
585 >>> read_float8(io.BytesIO(raw + b"\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000586 -1.25
587 """
588
589 data = f.read(8)
590 if len(data) == 8:
591 return _unpack(">d", data)[0]
592 raise ValueError("not enough data in stream to read float8")
593
594
595float8 = ArgumentDescriptor(
596 name='float8',
597 n=8,
598 reader=read_float8,
599 doc="""An 8-byte binary representation of a float, big-endian.
600
601 The format is unique to Python, and shared with the struct
Guido van Rossum99603b02007-07-20 00:22:32 +0000602 module (format string '>d') "in theory" (the struct and pickle
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000603 implementations don't share the code -- they should). It's
604 strongly related to the IEEE-754 double format, and, in normal
605 cases, is in fact identical to the big-endian 754 double format.
606 On other boxes the dynamic range is limited to that of a 754
607 double, and "add a half and chop" rounding is used to reduce
608 the precision to 53 bits. However, even on a 754 box,
609 infinities, NaNs, and minus zero may not be handled correctly
610 (may not survive roundtrip pickling intact).
611 """)
612
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000613# Protocol 2 formats
614
Tim Petersc0c12b52003-01-29 00:56:17 +0000615from pickle import decode_long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000616
617def read_long1(f):
618 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000619 >>> import io
620 >>> read_long1(io.BytesIO(b"\x00"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000621 0
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000622 >>> read_long1(io.BytesIO(b"\x02\xff\x00"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000623 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000624 >>> read_long1(io.BytesIO(b"\x02\xff\x7f"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000625 32767
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000626 >>> read_long1(io.BytesIO(b"\x02\x00\xff"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000627 -256
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000628 >>> read_long1(io.BytesIO(b"\x02\x00\x80"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000629 -32768
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000630 """
631
632 n = read_uint1(f)
633 data = f.read(n)
634 if len(data) != n:
635 raise ValueError("not enough data in stream to read long1")
636 return decode_long(data)
637
638long1 = ArgumentDescriptor(
639 name="long1",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000640 n=TAKEN_FROM_ARGUMENT1,
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000641 reader=read_long1,
642 doc="""A binary long, little-endian, using 1-byte size.
643
644 This first reads one byte as an unsigned size, then reads that
Tim Petersbdbe7412003-01-27 23:54:04 +0000645 many bytes and interprets them as a little-endian 2's-complement long.
Tim Peters4b23f2b2003-01-31 16:43:39 +0000646 If the size is 0, that's taken as a shortcut for the long 0L.
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000647 """)
648
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000649def read_long4(f):
650 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000651 >>> import io
652 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\xff\x00"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000653 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000654 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\xff\x7f"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000655 32767
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000656 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\x00\xff"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000657 -256
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000658 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\x00\x80"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000659 -32768
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000660 >>> read_long1(io.BytesIO(b"\x00\x00\x00\x00"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000661 0
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000662 """
663
664 n = read_int4(f)
665 if n < 0:
Neal Norwitz784a3f52003-01-28 00:20:41 +0000666 raise ValueError("long4 byte count < 0: %d" % n)
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000667 data = f.read(n)
668 if len(data) != n:
Neal Norwitz784a3f52003-01-28 00:20:41 +0000669 raise ValueError("not enough data in stream to read long4")
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000670 return decode_long(data)
671
672long4 = ArgumentDescriptor(
673 name="long4",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000674 n=TAKEN_FROM_ARGUMENT4,
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000675 reader=read_long4,
676 doc="""A binary representation of a long, little-endian.
677
678 This first reads four bytes as a signed size (but requires the
679 size to be >= 0), then reads that many bytes and interprets them
Tim Peters4b23f2b2003-01-31 16:43:39 +0000680 as a little-endian 2's-complement long. If the size is 0, that's taken
Guido van Rossume2a383d2007-01-15 16:59:06 +0000681 as a shortcut for the int 0, although LONG1 should really be used
Tim Peters4b23f2b2003-01-31 16:43:39 +0000682 then instead (and in any case where # of bytes < 256).
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000683 """)
684
685
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000686##############################################################################
687# Object descriptors. The stack used by the pickle machine holds objects,
688# and in the stack_before and stack_after attributes of OpcodeInfo
689# descriptors we need names to describe the various types of objects that can
690# appear on the stack.
691
692class StackObject(object):
693 __slots__ = (
694 # name of descriptor record, for info only
695 'name',
696
697 # type of object, or tuple of type objects (meaning the object can
698 # be of any type in the tuple)
699 'obtype',
700
701 # human-readable docs for this kind of stack object; a string
702 'doc',
703 )
704
705 def __init__(self, name, obtype, doc):
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000706 assert isinstance(name, str)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000707 self.name = name
708
709 assert isinstance(obtype, type) or isinstance(obtype, tuple)
710 if isinstance(obtype, tuple):
711 for contained in obtype:
712 assert isinstance(contained, type)
713 self.obtype = obtype
714
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000715 assert isinstance(doc, str)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000716 self.doc = doc
717
Tim Petersc1c2b3e2003-01-29 20:12:21 +0000718 def __repr__(self):
719 return self.name
720
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000721
722pyint = StackObject(
723 name='int',
724 obtype=int,
725 doc="A short (as opposed to long) Python integer object.")
726
727pylong = StackObject(
728 name='long',
Guido van Rossume2a383d2007-01-15 16:59:06 +0000729 obtype=int,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000730 doc="A long (as opposed to short) Python integer object.")
731
732pyinteger_or_bool = StackObject(
733 name='int_or_bool',
Guido van Rossume2a383d2007-01-15 16:59:06 +0000734 obtype=(int, int, bool),
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000735 doc="A Python integer object (short or long), or "
736 "a Python bool.")
737
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000738pybool = StackObject(
739 name='bool',
740 obtype=(bool,),
741 doc="A Python bool object.")
742
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000743pyfloat = StackObject(
744 name='float',
745 obtype=float,
746 doc="A Python float object.")
747
748pystring = StackObject(
Guido van Rossumf4169812008-03-17 22:56:06 +0000749 name='string',
750 obtype=bytes,
751 doc="A Python (8-bit) string object.")
752
753pybytes = StackObject(
Guido van Rossum98297ee2007-11-06 21:34:58 +0000754 name='bytes',
755 obtype=bytes,
756 doc="A Python bytes object.")
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000757
758pyunicode = StackObject(
Guido van Rossum98297ee2007-11-06 21:34:58 +0000759 name='str',
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000760 obtype=str,
Guido van Rossumf4169812008-03-17 22:56:06 +0000761 doc="A Python (Unicode) string object.")
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000762
763pynone = StackObject(
764 name="None",
765 obtype=type(None),
766 doc="The Python None object.")
767
768pytuple = StackObject(
769 name="tuple",
770 obtype=tuple,
771 doc="A Python tuple object.")
772
773pylist = StackObject(
774 name="list",
775 obtype=list,
776 doc="A Python list object.")
777
778pydict = StackObject(
779 name="dict",
780 obtype=dict,
781 doc="A Python dict object.")
782
783anyobject = StackObject(
784 name='any',
785 obtype=object,
786 doc="Any kind of object whatsoever.")
787
788markobject = StackObject(
789 name="mark",
790 obtype=StackObject,
791 doc="""'The mark' is a unique object.
792
793 Opcodes that operate on a variable number of objects
794 generally don't embed the count of objects in the opcode,
795 or pull it off the stack. Instead the MARK opcode is used
796 to push a special marker object on the stack, and then
797 some other opcodes grab all the objects from the top of
798 the stack down to (but not including) the topmost marker
799 object.
800 """)
801
802stackslice = StackObject(
803 name="stackslice",
804 obtype=StackObject,
805 doc="""An object representing a contiguous slice of the stack.
806
807 This is used in conjuction with markobject, to represent all
808 of the stack following the topmost markobject. For example,
809 the POP_MARK opcode changes the stack from
810
811 [..., markobject, stackslice]
812 to
813 [...]
814
815 No matter how many object are on the stack after the topmost
816 markobject, POP_MARK gets rid of all of them (including the
817 topmost markobject too).
818 """)
819
820##############################################################################
821# Descriptors for pickle opcodes.
822
823class OpcodeInfo(object):
824
825 __slots__ = (
826 # symbolic name of opcode; a string
827 'name',
828
829 # the code used in a bytestream to represent the opcode; a
830 # one-character string
831 'code',
832
833 # If the opcode has an argument embedded in the byte string, an
834 # instance of ArgumentDescriptor specifying its type. Note that
835 # arg.reader(s) can be used to read and decode the argument from
836 # the bytestream s, and arg.doc documents the format of the raw
837 # argument bytes. If the opcode doesn't have an argument embedded
838 # in the bytestream, arg should be None.
839 'arg',
840
841 # what the stack looks like before this opcode runs; a list
842 'stack_before',
843
844 # what the stack looks like after this opcode runs; a list
845 'stack_after',
846
847 # the protocol number in which this opcode was introduced; an int
848 'proto',
849
850 # human-readable docs for this opcode; a string
851 'doc',
852 )
853
854 def __init__(self, name, code, arg,
855 stack_before, stack_after, proto, doc):
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000856 assert isinstance(name, str)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000857 self.name = name
858
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000859 assert isinstance(code, str)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000860 assert len(code) == 1
861 self.code = code
862
863 assert arg is None or isinstance(arg, ArgumentDescriptor)
864 self.arg = arg
865
866 assert isinstance(stack_before, list)
867 for x in stack_before:
868 assert isinstance(x, StackObject)
869 self.stack_before = stack_before
870
871 assert isinstance(stack_after, list)
872 for x in stack_after:
873 assert isinstance(x, StackObject)
874 self.stack_after = stack_after
875
Guido van Rossumf4169812008-03-17 22:56:06 +0000876 assert isinstance(proto, int) and 0 <= proto <= 3
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000877 self.proto = proto
878
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000879 assert isinstance(doc, str)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000880 self.doc = doc
881
882I = OpcodeInfo
883opcodes = [
884
885 # Ways to spell integers.
886
887 I(name='INT',
888 code='I',
889 arg=decimalnl_short,
890 stack_before=[],
891 stack_after=[pyinteger_or_bool],
892 proto=0,
893 doc="""Push an integer or bool.
894
895 The argument is a newline-terminated decimal literal string.
896
897 The intent may have been that this always fit in a short Python int,
898 but INT can be generated in pickles written on a 64-bit box that
899 require a Python long on a 32-bit box. The difference between this
900 and LONG then is that INT skips a trailing 'L', and produces a short
901 int whenever possible.
902
903 Another difference is due to that, when bool was introduced as a
904 distinct type in 2.3, builtin names True and False were also added to
905 2.2.2, mapping to ints 1 and 0. For compatibility in both directions,
906 True gets pickled as INT + "I01\\n", and False as INT + "I00\\n".
907 Leading zeroes are never produced for a genuine integer. The 2.3
908 (and later) unpicklers special-case these and return bool instead;
909 earlier unpicklers ignore the leading "0" and return the int.
910 """),
911
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000912 I(name='BININT',
913 code='J',
914 arg=int4,
915 stack_before=[],
916 stack_after=[pyint],
917 proto=1,
918 doc="""Push a four-byte signed integer.
919
920 This handles the full range of Python (short) integers on a 32-bit
921 box, directly as binary bytes (1 for the opcode and 4 for the integer).
922 If the integer is non-negative and fits in 1 or 2 bytes, pickling via
923 BININT1 or BININT2 saves space.
924 """),
925
926 I(name='BININT1',
927 code='K',
928 arg=uint1,
929 stack_before=[],
930 stack_after=[pyint],
931 proto=1,
932 doc="""Push a one-byte unsigned integer.
933
934 This is a space optimization for pickling very small non-negative ints,
935 in range(256).
936 """),
937
938 I(name='BININT2',
939 code='M',
940 arg=uint2,
941 stack_before=[],
942 stack_after=[pyint],
943 proto=1,
944 doc="""Push a two-byte unsigned integer.
945
946 This is a space optimization for pickling small positive ints, in
947 range(256, 2**16). Integers in range(256) can also be pickled via
948 BININT2, but BININT1 instead saves a byte.
949 """),
950
Tim Petersfdc03462003-01-28 04:56:33 +0000951 I(name='LONG',
952 code='L',
953 arg=decimalnl_long,
954 stack_before=[],
955 stack_after=[pylong],
956 proto=0,
957 doc="""Push a long integer.
958
959 The same as INT, except that the literal ends with 'L', and always
960 unpickles to a Python long. There doesn't seem a real purpose to the
961 trailing 'L'.
962
963 Note that LONG takes time quadratic in the number of digits when
964 unpickling (this is simply due to the nature of decimal->binary
965 conversion). Proto 2 added linear-time (in C; still quadratic-time
966 in Python) LONG1 and LONG4 opcodes.
967 """),
968
969 I(name="LONG1",
970 code='\x8a',
971 arg=long1,
972 stack_before=[],
973 stack_after=[pylong],
974 proto=2,
975 doc="""Long integer using one-byte length.
976
977 A more efficient encoding of a Python long; the long1 encoding
978 says it all."""),
979
980 I(name="LONG4",
981 code='\x8b',
982 arg=long4,
983 stack_before=[],
984 stack_after=[pylong],
985 proto=2,
986 doc="""Long integer using found-byte length.
987
988 A more efficient encoding of a Python long; the long4 encoding
989 says it all."""),
990
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000991 # Ways to spell strings (8-bit, not Unicode).
992
993 I(name='STRING',
994 code='S',
995 arg=stringnl,
996 stack_before=[],
997 stack_after=[pystring],
998 proto=0,
999 doc="""Push a Python string object.
1000
1001 The argument is a repr-style string, with bracketing quote characters,
1002 and perhaps embedded escapes. The argument extends until the next
Guido van Rossumf4169812008-03-17 22:56:06 +00001003 newline character. (Actually, they are decoded into a str instance
1004 using the encoding given to the Unpickler constructor. or the default,
1005 'ASCII'.)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001006 """),
1007
1008 I(name='BINSTRING',
1009 code='T',
1010 arg=string4,
1011 stack_before=[],
1012 stack_after=[pystring],
1013 proto=1,
1014 doc="""Push a Python string object.
1015
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
Guido van Rossumf4169812008-03-17 22:56:06 +00001018 bytes, which are taken literally as the string content. (Actually,
1019 they are decoded into a str instance using the encoding given to the
1020 Unpickler constructor. or the default, 'ASCII'.)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001021 """),
1022
1023 I(name='SHORT_BINSTRING',
1024 code='U',
1025 arg=string1,
1026 stack_before=[],
1027 stack_after=[pystring],
1028 proto=1,
1029 doc="""Push a Python string object.
1030
1031 There are two arguments: the first is a 1-byte unsigned int giving
1032 the number of bytes in the string, and the second is that many bytes,
Guido van Rossumf4169812008-03-17 22:56:06 +00001033 which are taken literally as the string content. (Actually, they
1034 are decoded into a str instance using the encoding given to the
1035 Unpickler constructor. or the default, 'ASCII'.)
1036 """),
1037
1038 # Bytes (protocol 3 only; older protocols don't support bytes at all)
1039
1040 I(name='BINBYTES',
1041 code='B',
1042 arg=string4,
1043 stack_before=[],
1044 stack_after=[pybytes],
1045 proto=3,
1046 doc="""Push a Python bytes object.
1047
1048 There are two arguments: the first is a 4-byte little-endian signed int
1049 giving the number of bytes in the string, and the second is that many
1050 bytes, which are taken literally as the bytes content.
1051 """),
1052
1053 I(name='SHORT_BINBYTES',
1054 code='C',
1055 arg=string1,
1056 stack_before=[],
1057 stack_after=[pybytes],
1058 proto=1,
1059 doc="""Push a Python string object.
1060
1061 There are two arguments: the first is a 1-byte unsigned int giving
1062 the number of bytes in the string, and the second is that many bytes,
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001063 which are taken literally as the string content.
1064 """),
1065
1066 # Ways to spell None.
1067
1068 I(name='NONE',
1069 code='N',
1070 arg=None,
1071 stack_before=[],
1072 stack_after=[pynone],
1073 proto=0,
1074 doc="Push None on the stack."),
1075
Tim Petersfdc03462003-01-28 04:56:33 +00001076 # Ways to spell bools, starting with proto 2. See INT for how this was
1077 # done before proto 2.
1078
1079 I(name='NEWTRUE',
1080 code='\x88',
1081 arg=None,
1082 stack_before=[],
1083 stack_after=[pybool],
1084 proto=2,
1085 doc="""True.
1086
1087 Push True onto the stack."""),
1088
1089 I(name='NEWFALSE',
1090 code='\x89',
1091 arg=None,
1092 stack_before=[],
1093 stack_after=[pybool],
1094 proto=2,
1095 doc="""True.
1096
1097 Push False onto the stack."""),
1098
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001099 # Ways to spell Unicode strings.
1100
1101 I(name='UNICODE',
1102 code='V',
1103 arg=unicodestringnl,
1104 stack_before=[],
1105 stack_after=[pyunicode],
1106 proto=0, # this may be pure-text, but it's a later addition
1107 doc="""Push a Python Unicode string object.
1108
1109 The argument is a raw-unicode-escape encoding of a Unicode string,
1110 and so may contain embedded escape sequences. The argument extends
1111 until the next newline character.
1112 """),
1113
1114 I(name='BINUNICODE',
1115 code='X',
1116 arg=unicodestring4,
1117 stack_before=[],
1118 stack_after=[pyunicode],
1119 proto=1,
1120 doc="""Push a Python Unicode string object.
1121
1122 There are two arguments: the first is a 4-byte little-endian signed int
1123 giving the number of bytes in the string. The second is that many
1124 bytes, and is the UTF-8 encoding of the Unicode string.
1125 """),
1126
1127 # Ways to spell floats.
1128
1129 I(name='FLOAT',
1130 code='F',
1131 arg=floatnl,
1132 stack_before=[],
1133 stack_after=[pyfloat],
1134 proto=0,
1135 doc="""Newline-terminated decimal float literal.
1136
1137 The argument is repr(a_float), and in general requires 17 significant
1138 digits for roundtrip conversion to be an identity (this is so for
1139 IEEE-754 double precision values, which is what Python float maps to
1140 on most boxes).
1141
1142 In general, FLOAT cannot be used to transport infinities, NaNs, or
1143 minus zero across boxes (or even on a single box, if the platform C
1144 library can't read the strings it produces for such things -- Windows
1145 is like that), but may do less damage than BINFLOAT on boxes with
1146 greater precision or dynamic range than IEEE-754 double.
1147 """),
1148
1149 I(name='BINFLOAT',
1150 code='G',
1151 arg=float8,
1152 stack_before=[],
1153 stack_after=[pyfloat],
1154 proto=1,
1155 doc="""Float stored in binary form, with 8 bytes of data.
1156
1157 This generally requires less than half the space of FLOAT encoding.
1158 In general, BINFLOAT cannot be used to transport infinities, NaNs, or
1159 minus zero, raises an exception if the exponent exceeds the range of
1160 an IEEE-754 double, and retains no more than 53 bits of precision (if
1161 there are more than that, "add a half and chop" rounding is used to
1162 cut it back to 53 significant bits).
1163 """),
1164
1165 # Ways to build lists.
1166
1167 I(name='EMPTY_LIST',
1168 code=']',
1169 arg=None,
1170 stack_before=[],
1171 stack_after=[pylist],
1172 proto=1,
1173 doc="Push an empty list."),
1174
1175 I(name='APPEND',
1176 code='a',
1177 arg=None,
1178 stack_before=[pylist, anyobject],
1179 stack_after=[pylist],
1180 proto=0,
1181 doc="""Append an object to a list.
1182
1183 Stack before: ... pylist anyobject
1184 Stack after: ... pylist+[anyobject]
Tim Peters81098ac2003-01-28 05:12:08 +00001185
1186 although pylist is really extended in-place.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001187 """),
1188
1189 I(name='APPENDS',
1190 code='e',
1191 arg=None,
1192 stack_before=[pylist, markobject, stackslice],
1193 stack_after=[pylist],
1194 proto=1,
1195 doc="""Extend a list by a slice of stack objects.
1196
1197 Stack before: ... pylist markobject stackslice
1198 Stack after: ... pylist+stackslice
Tim Peters81098ac2003-01-28 05:12:08 +00001199
1200 although pylist is really extended in-place.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001201 """),
1202
1203 I(name='LIST',
1204 code='l',
1205 arg=None,
1206 stack_before=[markobject, stackslice],
1207 stack_after=[pylist],
1208 proto=0,
1209 doc="""Build a list out of the topmost stack slice, after markobject.
1210
1211 All the stack entries following the topmost markobject are placed into
1212 a single Python list, which single list object replaces all of the
1213 stack from the topmost markobject onward. For example,
1214
1215 Stack before: ... markobject 1 2 3 'abc'
1216 Stack after: ... [1, 2, 3, 'abc']
1217 """),
1218
1219 # Ways to build tuples.
1220
1221 I(name='EMPTY_TUPLE',
1222 code=')',
1223 arg=None,
1224 stack_before=[],
1225 stack_after=[pytuple],
1226 proto=1,
1227 doc="Push an empty tuple."),
1228
1229 I(name='TUPLE',
1230 code='t',
1231 arg=None,
1232 stack_before=[markobject, stackslice],
1233 stack_after=[pytuple],
1234 proto=0,
1235 doc="""Build a tuple out of the topmost stack slice, after markobject.
1236
1237 All the stack entries following the topmost markobject are placed into
1238 a single Python tuple, which single tuple object replaces all of the
1239 stack from the topmost markobject onward. For example,
1240
1241 Stack before: ... markobject 1 2 3 'abc'
1242 Stack after: ... (1, 2, 3, 'abc')
1243 """),
1244
Tim Petersfdc03462003-01-28 04:56:33 +00001245 I(name='TUPLE1',
1246 code='\x85',
1247 arg=None,
1248 stack_before=[anyobject],
1249 stack_after=[pytuple],
1250 proto=2,
1251 doc="""One-tuple.
1252
1253 This code pops one value off the stack and pushes a tuple of
1254 length 1 whose one item is that value back onto it. IOW:
1255
1256 stack[-1] = tuple(stack[-1:])
1257 """),
1258
1259 I(name='TUPLE2',
1260 code='\x86',
1261 arg=None,
1262 stack_before=[anyobject, anyobject],
1263 stack_after=[pytuple],
1264 proto=2,
1265 doc="""One-tuple.
1266
1267 This code pops two values off the stack and pushes a tuple
1268 of length 2 whose items are those values back onto it. IOW:
1269
1270 stack[-2:] = [tuple(stack[-2:])]
1271 """),
1272
1273 I(name='TUPLE3',
1274 code='\x87',
1275 arg=None,
1276 stack_before=[anyobject, anyobject, anyobject],
1277 stack_after=[pytuple],
1278 proto=2,
1279 doc="""One-tuple.
1280
1281 This code pops three values off the stack and pushes a tuple
1282 of length 3 whose items are those values back onto it. IOW:
1283
1284 stack[-3:] = [tuple(stack[-3:])]
1285 """),
1286
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001287 # Ways to build dicts.
1288
1289 I(name='EMPTY_DICT',
1290 code='}',
1291 arg=None,
1292 stack_before=[],
1293 stack_after=[pydict],
1294 proto=1,
1295 doc="Push an empty dict."),
1296
1297 I(name='DICT',
1298 code='d',
1299 arg=None,
1300 stack_before=[markobject, stackslice],
1301 stack_after=[pydict],
1302 proto=0,
1303 doc="""Build a dict out of the topmost stack slice, after markobject.
1304
1305 All the stack entries following the topmost markobject are placed into
1306 a single Python dict, which single dict object replaces all of the
1307 stack from the topmost markobject onward. The stack slice alternates
1308 key, value, key, value, .... For example,
1309
1310 Stack before: ... markobject 1 2 3 'abc'
1311 Stack after: ... {1: 2, 3: 'abc'}
1312 """),
1313
1314 I(name='SETITEM',
1315 code='s',
1316 arg=None,
1317 stack_before=[pydict, anyobject, anyobject],
1318 stack_after=[pydict],
1319 proto=0,
1320 doc="""Add a key+value pair to an existing dict.
1321
1322 Stack before: ... pydict key value
1323 Stack after: ... pydict
1324
1325 where pydict has been modified via pydict[key] = value.
1326 """),
1327
1328 I(name='SETITEMS',
1329 code='u',
1330 arg=None,
1331 stack_before=[pydict, markobject, stackslice],
1332 stack_after=[pydict],
1333 proto=1,
1334 doc="""Add an arbitrary number of key+value pairs to an existing dict.
1335
1336 The slice of the stack following the topmost markobject is taken as
1337 an alternating sequence of keys and values, added to the dict
1338 immediately under the topmost markobject. Everything at and after the
1339 topmost markobject is popped, leaving the mutated dict at the top
1340 of the stack.
1341
1342 Stack before: ... pydict markobject key_1 value_1 ... key_n value_n
1343 Stack after: ... pydict
1344
1345 where pydict has been modified via pydict[key_i] = value_i for i in
1346 1, 2, ..., n, and in that order.
1347 """),
1348
1349 # Stack manipulation.
1350
1351 I(name='POP',
1352 code='0',
1353 arg=None,
1354 stack_before=[anyobject],
1355 stack_after=[],
1356 proto=0,
1357 doc="Discard the top stack item, shrinking the stack by one item."),
1358
1359 I(name='DUP',
1360 code='2',
1361 arg=None,
1362 stack_before=[anyobject],
1363 stack_after=[anyobject, anyobject],
1364 proto=0,
1365 doc="Push the top stack item onto the stack again, duplicating it."),
1366
1367 I(name='MARK',
1368 code='(',
1369 arg=None,
1370 stack_before=[],
1371 stack_after=[markobject],
1372 proto=0,
1373 doc="""Push markobject onto the stack.
1374
1375 markobject is a unique object, used by other opcodes to identify a
1376 region of the stack containing a variable number of objects for them
1377 to work on. See markobject.doc for more detail.
1378 """),
1379
1380 I(name='POP_MARK',
1381 code='1',
1382 arg=None,
1383 stack_before=[markobject, stackslice],
1384 stack_after=[],
1385 proto=0,
1386 doc="""Pop all the stack objects at and above the topmost markobject.
1387
1388 When an opcode using a variable number of stack objects is done,
1389 POP_MARK is used to remove those objects, and to remove the markobject
1390 that delimited their starting position on the stack.
1391 """),
1392
1393 # Memo manipulation. There are really only two operations (get and put),
1394 # each in all-text, "short binary", and "long binary" flavors.
1395
1396 I(name='GET',
1397 code='g',
1398 arg=decimalnl_short,
1399 stack_before=[],
1400 stack_after=[anyobject],
1401 proto=0,
1402 doc="""Read an object from the memo and push it on the stack.
1403
1404 The index of the memo object to push is given by the newline-teriminated
1405 decimal string following. BINGET and LONG_BINGET are space-optimized
1406 versions.
1407 """),
1408
1409 I(name='BINGET',
1410 code='h',
1411 arg=uint1,
1412 stack_before=[],
1413 stack_after=[anyobject],
1414 proto=1,
1415 doc="""Read an object from the memo and push it on the stack.
1416
1417 The index of the memo object to push is given by the 1-byte unsigned
1418 integer following.
1419 """),
1420
1421 I(name='LONG_BINGET',
1422 code='j',
1423 arg=int4,
1424 stack_before=[],
1425 stack_after=[anyobject],
1426 proto=1,
1427 doc="""Read an object from the memo and push it on the stack.
1428
1429 The index of the memo object to push is given by the 4-byte signed
1430 little-endian integer following.
1431 """),
1432
1433 I(name='PUT',
1434 code='p',
1435 arg=decimalnl_short,
1436 stack_before=[],
1437 stack_after=[],
1438 proto=0,
1439 doc="""Store the stack top into the memo. The stack is not popped.
1440
1441 The index of the memo location to write into is given by the newline-
1442 terminated decimal string following. BINPUT and LONG_BINPUT are
1443 space-optimized versions.
1444 """),
1445
1446 I(name='BINPUT',
1447 code='q',
1448 arg=uint1,
1449 stack_before=[],
1450 stack_after=[],
1451 proto=1,
1452 doc="""Store the stack top into the memo. The stack is not popped.
1453
1454 The index of the memo location to write into is given by the 1-byte
1455 unsigned integer following.
1456 """),
1457
1458 I(name='LONG_BINPUT',
1459 code='r',
1460 arg=int4,
1461 stack_before=[],
1462 stack_after=[],
1463 proto=1,
1464 doc="""Store the stack top into the memo. The stack is not popped.
1465
1466 The index of the memo location to write into is given by the 4-byte
1467 signed little-endian integer following.
1468 """),
1469
Tim Petersfdc03462003-01-28 04:56:33 +00001470 # Access the extension registry (predefined objects). Akin to the GET
1471 # family.
1472
1473 I(name='EXT1',
1474 code='\x82',
1475 arg=uint1,
1476 stack_before=[],
1477 stack_after=[anyobject],
1478 proto=2,
1479 doc="""Extension code.
1480
1481 This code and the similar EXT2 and EXT4 allow using a registry
1482 of popular objects that are pickled by name, typically classes.
1483 It is envisioned that through a global negotiation and
1484 registration process, third parties can set up a mapping between
1485 ints and object names.
1486
1487 In order to guarantee pickle interchangeability, the extension
1488 code registry ought to be global, although a range of codes may
1489 be reserved for private use.
1490
1491 EXT1 has a 1-byte integer argument. This is used to index into the
1492 extension registry, and the object at that index is pushed on the stack.
1493 """),
1494
1495 I(name='EXT2',
1496 code='\x83',
1497 arg=uint2,
1498 stack_before=[],
1499 stack_after=[anyobject],
1500 proto=2,
1501 doc="""Extension code.
1502
1503 See EXT1. EXT2 has a two-byte integer argument.
1504 """),
1505
1506 I(name='EXT4',
1507 code='\x84',
1508 arg=int4,
1509 stack_before=[],
1510 stack_after=[anyobject],
1511 proto=2,
1512 doc="""Extension code.
1513
1514 See EXT1. EXT4 has a four-byte integer argument.
1515 """),
1516
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001517 # Push a class object, or module function, on the stack, via its module
1518 # and name.
1519
1520 I(name='GLOBAL',
1521 code='c',
1522 arg=stringnl_noescape_pair,
1523 stack_before=[],
1524 stack_after=[anyobject],
1525 proto=0,
1526 doc="""Push a global object (module.attr) on the stack.
1527
1528 Two newline-terminated strings follow the GLOBAL opcode. The first is
1529 taken as a module name, and the second as a class name. The class
1530 object module.class is pushed on the stack. More accurately, the
1531 object returned by self.find_class(module, class) is pushed on the
1532 stack, so unpickling subclasses can override this form of lookup.
1533 """),
1534
1535 # Ways to build objects of classes pickle doesn't know about directly
1536 # (user-defined classes). I despair of documenting this accurately
1537 # and comprehensibly -- you really have to read the pickle code to
1538 # find all the special cases.
1539
1540 I(name='REDUCE',
1541 code='R',
1542 arg=None,
1543 stack_before=[anyobject, anyobject],
1544 stack_after=[anyobject],
1545 proto=0,
1546 doc="""Push an object built from a callable and an argument tuple.
1547
1548 The opcode is named to remind of the __reduce__() method.
1549
1550 Stack before: ... callable pytuple
1551 Stack after: ... callable(*pytuple)
1552
1553 The callable and the argument tuple are the first two items returned
1554 by a __reduce__ method. Applying the callable to the argtuple is
1555 supposed to reproduce the original object, or at least get it started.
1556 If the __reduce__ method returns a 3-tuple, the last component is an
1557 argument to be passed to the object's __setstate__, and then the REDUCE
1558 opcode is followed by code to create setstate's argument, and then a
1559 BUILD opcode to apply __setstate__ to that argument.
1560
Guido van Rossum13257902007-06-07 23:15:56 +00001561 If not isinstance(callable, type), REDUCE complains unless the
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001562 callable has been registered with the copyreg module's
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001563 safe_constructors dict, or the callable has a magic
1564 '__safe_for_unpickling__' attribute with a true value. I'm not sure
1565 why it does this, but I've sure seen this complaint often enough when
1566 I didn't want to <wink>.
1567 """),
1568
1569 I(name='BUILD',
1570 code='b',
1571 arg=None,
1572 stack_before=[anyobject, anyobject],
1573 stack_after=[anyobject],
1574 proto=0,
1575 doc="""Finish building an object, via __setstate__ or dict update.
1576
1577 Stack before: ... anyobject argument
1578 Stack after: ... anyobject
1579
1580 where anyobject may have been mutated, as follows:
1581
1582 If the object has a __setstate__ method,
1583
1584 anyobject.__setstate__(argument)
1585
1586 is called.
1587
1588 Else the argument must be a dict, the object must have a __dict__, and
1589 the object is updated via
1590
1591 anyobject.__dict__.update(argument)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001592 """),
1593
1594 I(name='INST',
1595 code='i',
1596 arg=stringnl_noescape_pair,
1597 stack_before=[markobject, stackslice],
1598 stack_after=[anyobject],
1599 proto=0,
1600 doc="""Build a class instance.
1601
1602 This is the protocol 0 version of protocol 1's OBJ opcode.
1603 INST is followed by two newline-terminated strings, giving a
1604 module and class name, just as for the GLOBAL opcode (and see
1605 GLOBAL for more details about that). self.find_class(module, name)
1606 is used to get a class object.
1607
1608 In addition, all the objects on the stack following the topmost
1609 markobject are gathered into a tuple and popped (along with the
1610 topmost markobject), just as for the TUPLE opcode.
1611
1612 Now it gets complicated. If all of these are true:
1613
1614 + The argtuple is empty (markobject was at the top of the stack
1615 at the start).
1616
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001617 + The class object does not have a __getinitargs__ attribute.
1618
1619 then we want to create an old-style class instance without invoking
1620 its __init__() method (pickle has waffled on this over the years; not
1621 calling __init__() is current wisdom). In this case, an instance of
1622 an old-style dummy class is created, and then we try to rebind its
1623 __class__ attribute to the desired class object. If this succeeds,
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001624 the new instance object is pushed on the stack, and we're done.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001625
1626 Else (the argtuple is not empty, it's not an old-style class object,
1627 or the class object does have a __getinitargs__ attribute), the code
1628 first insists that the class object have a __safe_for_unpickling__
1629 attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE,
1630 it doesn't matter whether this attribute has a true or false value, it
Guido van Rossum99603b02007-07-20 00:22:32 +00001631 only matters whether it exists (XXX this is a bug). If
1632 __safe_for_unpickling__ doesn't exist, UnpicklingError is raised.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001633
1634 Else (the class object does have a __safe_for_unpickling__ attr),
1635 the class object obtained from INST's arguments is applied to the
1636 argtuple obtained from the stack, and the resulting instance object
1637 is pushed on the stack.
Tim Peters2b93c4c2003-01-30 16:35:08 +00001638
1639 NOTE: checks for __safe_for_unpickling__ went away in Python 2.3.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001640 """),
1641
1642 I(name='OBJ',
1643 code='o',
1644 arg=None,
1645 stack_before=[markobject, anyobject, stackslice],
1646 stack_after=[anyobject],
1647 proto=1,
1648 doc="""Build a class instance.
1649
1650 This is the protocol 1 version of protocol 0's INST opcode, and is
1651 very much like it. The major difference is that the class object
1652 is taken off the stack, allowing it to be retrieved from the memo
1653 repeatedly if several instances of the same class are created. This
1654 can be much more efficient (in both time and space) than repeatedly
1655 embedding the module and class names in INST opcodes.
1656
1657 Unlike INST, OBJ takes no arguments from the opcode stream. Instead
1658 the class object is taken off the stack, immediately above the
1659 topmost markobject:
1660
1661 Stack before: ... markobject classobject stackslice
1662 Stack after: ... new_instance_object
1663
1664 As for INST, the remainder of the stack above the markobject is
1665 gathered into an argument tuple, and then the logic seems identical,
Guido van Rossumecb11042003-01-29 06:24:30 +00001666 except that no __safe_for_unpickling__ check is done (XXX this is
Guido van Rossum99603b02007-07-20 00:22:32 +00001667 a bug). See INST for the gory details.
Tim Peters2b93c4c2003-01-30 16:35:08 +00001668
1669 NOTE: In Python 2.3, INST and OBJ are identical except for how they
1670 get the class object. That was always the intent; the implementations
1671 had diverged for accidental reasons.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001672 """),
1673
Tim Petersfdc03462003-01-28 04:56:33 +00001674 I(name='NEWOBJ',
1675 code='\x81',
1676 arg=None,
1677 stack_before=[anyobject, anyobject],
1678 stack_after=[anyobject],
1679 proto=2,
1680 doc="""Build an object instance.
1681
1682 The stack before should be thought of as containing a class
1683 object followed by an argument tuple (the tuple being the stack
1684 top). Call these cls and args. They are popped off the stack,
1685 and the value returned by cls.__new__(cls, *args) is pushed back
1686 onto the stack.
1687 """),
1688
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001689 # Machine control.
1690
Tim Petersfdc03462003-01-28 04:56:33 +00001691 I(name='PROTO',
1692 code='\x80',
1693 arg=uint1,
1694 stack_before=[],
1695 stack_after=[],
1696 proto=2,
1697 doc="""Protocol version indicator.
1698
1699 For protocol 2 and above, a pickle must start with this opcode.
1700 The argument is the protocol version, an int in range(2, 256).
1701 """),
1702
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001703 I(name='STOP',
1704 code='.',
1705 arg=None,
1706 stack_before=[anyobject],
1707 stack_after=[],
1708 proto=0,
1709 doc="""Stop the unpickling machine.
1710
1711 Every pickle ends with this opcode. The object at the top of the stack
1712 is popped, and that's the result of unpickling. The stack should be
1713 empty then.
1714 """),
1715
1716 # Ways to deal with persistent IDs.
1717
1718 I(name='PERSID',
1719 code='P',
1720 arg=stringnl_noescape,
1721 stack_before=[],
1722 stack_after=[anyobject],
1723 proto=0,
1724 doc="""Push an object identified by a persistent ID.
1725
1726 The pickle module doesn't define what a persistent ID means. PERSID's
1727 argument is a newline-terminated str-style (no embedded escapes, no
1728 bracketing quote characters) string, which *is* "the persistent ID".
1729 The unpickler passes this string to self.persistent_load(). Whatever
1730 object that returns is pushed on the stack. There is no implementation
1731 of persistent_load() in Python's unpickler: it must be supplied by an
1732 unpickler subclass.
1733 """),
1734
1735 I(name='BINPERSID',
1736 code='Q',
1737 arg=None,
1738 stack_before=[anyobject],
1739 stack_after=[anyobject],
1740 proto=1,
1741 doc="""Push an object identified by a persistent ID.
1742
1743 Like PERSID, except the persistent ID is popped off the stack (instead
1744 of being a string embedded in the opcode bytestream). The persistent
1745 ID is passed to self.persistent_load(), and whatever object that
1746 returns is pushed on the stack. See PERSID for more detail.
1747 """),
1748]
1749del I
1750
1751# Verify uniqueness of .name and .code members.
1752name2i = {}
1753code2i = {}
1754
1755for i, d in enumerate(opcodes):
1756 if d.name in name2i:
1757 raise ValueError("repeated name %r at indices %d and %d" %
1758 (d.name, name2i[d.name], i))
1759 if d.code in code2i:
1760 raise ValueError("repeated code %r at indices %d and %d" %
1761 (d.code, code2i[d.code], i))
1762
1763 name2i[d.name] = i
1764 code2i[d.code] = i
1765
1766del name2i, code2i, i, d
1767
1768##############################################################################
1769# Build a code2op dict, mapping opcode characters to OpcodeInfo records.
1770# Also ensure we've got the same stuff as pickle.py, although the
1771# introspection here is dicey.
1772
1773code2op = {}
1774for d in opcodes:
1775 code2op[d.code] = d
1776del d
1777
1778def assure_pickle_consistency(verbose=False):
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001779
1780 copy = code2op.copy()
1781 for name in pickle.__all__:
1782 if not re.match("[A-Z][A-Z0-9_]+$", name):
1783 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001784 print("skipping %r: it doesn't look like an opcode name" % name)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001785 continue
1786 picklecode = getattr(pickle, name)
Guido van Rossum617dbc42007-05-07 23:57:08 +00001787 if not isinstance(picklecode, bytes) or len(picklecode) != 1:
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001788 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001789 print(("skipping %r: value %r doesn't look like a pickle "
1790 "code" % (name, picklecode)))
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001791 continue
Guido van Rossum617dbc42007-05-07 23:57:08 +00001792 picklecode = picklecode.decode("latin-1")
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001793 if picklecode in copy:
1794 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001795 print("checking name %r w/ code %r for consistency" % (
1796 name, picklecode))
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001797 d = copy[picklecode]
1798 if d.name != name:
1799 raise ValueError("for pickle code %r, pickle.py uses name %r "
1800 "but we're using name %r" % (picklecode,
1801 name,
1802 d.name))
1803 # Forget this one. Any left over in copy at the end are a problem
1804 # of a different kind.
1805 del copy[picklecode]
1806 else:
1807 raise ValueError("pickle.py appears to have a pickle opcode with "
1808 "name %r and code %r, but we don't" %
1809 (name, picklecode))
1810 if copy:
1811 msg = ["we appear to have pickle opcodes that pickle.py doesn't have:"]
1812 for code, d in copy.items():
1813 msg.append(" name %r with code %r" % (d.name, code))
1814 raise ValueError("\n".join(msg))
1815
1816assure_pickle_consistency()
Tim Petersc0c12b52003-01-29 00:56:17 +00001817del assure_pickle_consistency
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001818
1819##############################################################################
1820# A pickle opcode generator.
1821
1822def genops(pickle):
Guido van Rossuma72ded92003-01-27 19:40:47 +00001823 """Generate all the opcodes in a pickle.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001824
1825 'pickle' is a file-like object, or string, containing the pickle.
1826
1827 Each opcode in the pickle is generated, from the current pickle position,
1828 stopping after a STOP opcode is delivered. A triple is generated for
1829 each opcode:
1830
1831 opcode, arg, pos
1832
1833 opcode is an OpcodeInfo record, describing the current opcode.
1834
1835 If the opcode has an argument embedded in the pickle, arg is its decoded
1836 value, as a Python object. If the opcode doesn't have an argument, arg
1837 is None.
1838
1839 If the pickle has a tell() method, pos was the value of pickle.tell()
Guido van Rossum34d19282007-08-09 01:03:29 +00001840 before reading the current opcode. If the pickle is a bytes object,
1841 it's wrapped in a BytesIO object, and the latter's tell() result is
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001842 used. Else (the pickle doesn't have a tell(), and it's not obvious how
1843 to query its current position) pos is None.
1844 """
1845
Guido van Rossum98297ee2007-11-06 21:34:58 +00001846 if isinstance(pickle, bytes_types):
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001847 import io
1848 pickle = io.BytesIO(pickle)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001849
1850 if hasattr(pickle, "tell"):
1851 getpos = pickle.tell
1852 else:
1853 getpos = lambda: None
1854
1855 while True:
1856 pos = getpos()
1857 code = pickle.read(1)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001858 opcode = code2op.get(code.decode("latin-1"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001859 if opcode is None:
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001860 if code == b"":
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001861 raise ValueError("pickle exhausted before seeing STOP")
1862 else:
1863 raise ValueError("at position %s, opcode %r unknown" % (
1864 pos is None and "<unknown>" or pos,
1865 code))
1866 if opcode.arg is None:
1867 arg = None
1868 else:
1869 arg = opcode.arg.reader(pickle)
1870 yield opcode, arg, pos
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001871 if code == b'.':
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001872 assert opcode.name == 'STOP'
1873 break
1874
1875##############################################################################
Christian Heimes3feef612008-02-11 06:19:17 +00001876# A pickle optimizer.
1877
1878def optimize(p):
1879 'Optimize a pickle string by removing unused PUT opcodes'
1880 gets = set() # set of args used by a GET opcode
1881 puts = [] # (arg, startpos, stoppos) for the PUT opcodes
1882 prevpos = None # set to pos if previous opcode was a PUT
1883 for opcode, arg, pos in genops(p):
1884 if prevpos is not None:
1885 puts.append((prevarg, prevpos, pos))
1886 prevpos = None
1887 if 'PUT' in opcode.name:
1888 prevarg, prevpos = arg, pos
1889 elif 'GET' in opcode.name:
1890 gets.add(arg)
1891
1892 # Copy the pickle string except for PUTS without a corresponding GET
1893 s = []
1894 i = 0
1895 for arg, start, stop in puts:
1896 j = stop if (arg in gets) else start
1897 s.append(p[i:j])
1898 i = stop
1899 s.append(p[i:])
Christian Heimes126d29a2008-02-11 22:57:17 +00001900 return b''.join(s)
Christian Heimes3feef612008-02-11 06:19:17 +00001901
1902##############################################################################
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001903# A symbolic pickle disassembler.
1904
Tim Peters62235e72003-02-05 19:55:53 +00001905def dis(pickle, out=None, memo=None, indentlevel=4):
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001906 """Produce a symbolic disassembly of a pickle.
1907
1908 'pickle' is a file-like object, or string, containing a (at least one)
1909 pickle. The pickle is disassembled from the current position, through
1910 the first STOP opcode encountered.
1911
1912 Optional arg 'out' is a file-like object to which the disassembly is
1913 printed. It defaults to sys.stdout.
1914
Tim Peters62235e72003-02-05 19:55:53 +00001915 Optional arg 'memo' is a Python dict, used as the pickle's memo. It
1916 may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes.
1917 Passing the same memo object to another dis() call then allows disassembly
1918 to proceed across multiple pickles that were all created by the same
1919 pickler with the same memo. Ordinarily you don't need to worry about this.
1920
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001921 Optional arg indentlevel is the number of blanks by which to indent
1922 a new MARK level. It defaults to 4.
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001923
1924 In addition to printing the disassembly, some sanity checks are made:
1925
1926 + All embedded opcode arguments "make sense".
1927
1928 + Explicit and implicit pop operations have enough items on the stack.
1929
1930 + When an opcode implicitly refers to a markobject, a markobject is
1931 actually on the stack.
1932
1933 + A memo entry isn't referenced before it's defined.
1934
1935 + The markobject isn't stored in the memo.
1936
1937 + A memo entry isn't redefined.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001938 """
1939
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001940 # Most of the hair here is for sanity checks, but most of it is needed
1941 # anyway to detect when a protocol 0 POP takes a MARK off the stack
1942 # (which in turn is needed to indent MARK blocks correctly).
1943
1944 stack = [] # crude emulation of unpickler stack
Tim Peters62235e72003-02-05 19:55:53 +00001945 if memo is None:
1946 memo = {} # crude emulation of unpicker memo
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001947 maxproto = -1 # max protocol number seen
1948 markstack = [] # bytecode positions of MARK opcodes
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001949 indentchunk = ' ' * indentlevel
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001950 errormsg = None
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001951 for opcode, arg, pos in genops(pickle):
1952 if pos is not None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001953 print("%5d:" % pos, end=' ', file=out)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001954
Tim Petersd0f7c862003-01-28 15:27:57 +00001955 line = "%-4s %s%s" % (repr(opcode.code)[1:-1],
1956 indentchunk * len(markstack),
1957 opcode.name)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001958
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001959 maxproto = max(maxproto, opcode.proto)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001960 before = opcode.stack_before # don't mutate
1961 after = opcode.stack_after # don't mutate
Tim Peters43277d62003-01-30 15:02:12 +00001962 numtopop = len(before)
1963
1964 # See whether a MARK should be popped.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001965 markmsg = None
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001966 if markobject in before or (opcode.name == "POP" and
1967 stack and
1968 stack[-1] is markobject):
1969 assert markobject not in after
Tim Peters43277d62003-01-30 15:02:12 +00001970 if __debug__:
1971 if markobject in before:
1972 assert before[-1] is stackslice
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001973 if markstack:
1974 markpos = markstack.pop()
1975 if markpos is None:
1976 markmsg = "(MARK at unknown opcode offset)"
1977 else:
1978 markmsg = "(MARK at %d)" % markpos
1979 # Pop everything at and after the topmost markobject.
1980 while stack[-1] is not markobject:
1981 stack.pop()
1982 stack.pop()
Tim Peters43277d62003-01-30 15:02:12 +00001983 # Stop later code from popping too much.
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001984 try:
Tim Peters43277d62003-01-30 15:02:12 +00001985 numtopop = before.index(markobject)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001986 except ValueError:
1987 assert opcode.name == "POP"
Tim Peters43277d62003-01-30 15:02:12 +00001988 numtopop = 0
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001989 else:
1990 errormsg = markmsg = "no MARK exists on stack"
1991
1992 # Check for correct memo usage.
1993 if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"):
Tim Peters43277d62003-01-30 15:02:12 +00001994 assert arg is not None
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001995 if arg in memo:
1996 errormsg = "memo key %r already defined" % arg
1997 elif not stack:
1998 errormsg = "stack is empty -- can't store into memo"
1999 elif stack[-1] is markobject:
2000 errormsg = "can't store markobject in the memo"
2001 else:
2002 memo[arg] = stack[-1]
2003
2004 elif opcode.name in ("GET", "BINGET", "LONG_BINGET"):
2005 if arg in memo:
2006 assert len(after) == 1
2007 after = [memo[arg]] # for better stack emulation
2008 else:
2009 errormsg = "memo key %r has never been stored into" % arg
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002010
2011 if arg is not None or markmsg:
2012 # make a mild effort to align arguments
2013 line += ' ' * (10 - len(opcode.name))
2014 if arg is not None:
2015 line += ' ' + repr(arg)
2016 if markmsg:
2017 line += ' ' + markmsg
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002018 print(line, file=out)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002019
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002020 if errormsg:
2021 # Note that we delayed complaining until the offending opcode
2022 # was printed.
2023 raise ValueError(errormsg)
2024
2025 # Emulate the stack effects.
Tim Peters43277d62003-01-30 15:02:12 +00002026 if len(stack) < numtopop:
2027 raise ValueError("tries to pop %d items from stack with "
2028 "only %d items" % (numtopop, len(stack)))
2029 if numtopop:
2030 del stack[-numtopop:]
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002031 if markobject in after:
Tim Peters43277d62003-01-30 15:02:12 +00002032 assert markobject not in before
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002033 markstack.append(pos)
2034
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002035 stack.extend(after)
2036
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002037 print("highest protocol among opcodes =", maxproto, file=out)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002038 if stack:
2039 raise ValueError("stack not empty after STOP: %r" % stack)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002040
Tim Peters90718a42005-02-15 16:22:34 +00002041# For use in the doctest, simply as an example of a class to pickle.
2042class _Example:
2043 def __init__(self, value):
2044 self.value = value
2045
Guido van Rossum03e35322003-01-28 15:37:13 +00002046_dis_test = r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002047>>> import pickle
Guido van Rossumf4169812008-03-17 22:56:06 +00002048>>> x = [1, 2, (3, 4), {b'abc': "def"}]
2049>>> pkl0 = pickle.dumps(x, 0)
2050>>> dis(pkl0)
Tim Petersd0f7c862003-01-28 15:27:57 +00002051 0: ( MARK
2052 1: l LIST (MARK at 0)
2053 2: p PUT 0
Guido van Rossumf4100002007-01-15 00:21:46 +00002054 5: L LONG 1
Tim Petersd0f7c862003-01-28 15:27:57 +00002055 8: a APPEND
Guido van Rossumf4100002007-01-15 00:21:46 +00002056 9: L LONG 2
Tim Petersd0f7c862003-01-28 15:27:57 +00002057 12: a APPEND
2058 13: ( MARK
Guido van Rossumf4100002007-01-15 00:21:46 +00002059 14: L LONG 3
2060 17: L LONG 4
Tim Petersd0f7c862003-01-28 15:27:57 +00002061 20: t TUPLE (MARK at 13)
2062 21: p PUT 1
2063 24: a APPEND
2064 25: ( MARK
2065 26: d DICT (MARK at 25)
2066 27: p PUT 2
Guido van Rossumf4169812008-03-17 22:56:06 +00002067 30: c GLOBAL 'builtins bytes'
2068 46: p PUT 3
2069 49: ( MARK
2070 50: ( MARK
2071 51: l LIST (MARK at 50)
2072 52: p PUT 4
2073 55: L LONG 97
2074 59: a APPEND
2075 60: L LONG 98
2076 64: a APPEND
2077 65: L LONG 99
2078 69: a APPEND
2079 70: t TUPLE (MARK at 49)
2080 71: p PUT 5
2081 74: R REDUCE
2082 75: V UNICODE 'def'
2083 80: p PUT 6
2084 83: s SETITEM
2085 84: a APPEND
2086 85: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002087highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002088
2089Try again with a "binary" pickle.
2090
Guido van Rossumf4169812008-03-17 22:56:06 +00002091>>> pkl1 = pickle.dumps(x, 1)
2092>>> dis(pkl1)
Tim Petersd0f7c862003-01-28 15:27:57 +00002093 0: ] EMPTY_LIST
2094 1: q BINPUT 0
2095 3: ( MARK
2096 4: K BININT1 1
2097 6: K BININT1 2
2098 8: ( MARK
2099 9: K BININT1 3
2100 11: K BININT1 4
2101 13: t TUPLE (MARK at 8)
2102 14: q BINPUT 1
2103 16: } EMPTY_DICT
2104 17: q BINPUT 2
Guido van Rossumf4169812008-03-17 22:56:06 +00002105 19: c GLOBAL 'builtins bytes'
2106 35: q BINPUT 3
2107 37: ( MARK
2108 38: ] EMPTY_LIST
2109 39: q BINPUT 4
2110 41: ( MARK
2111 42: K BININT1 97
2112 44: K BININT1 98
2113 46: K BININT1 99
2114 48: e APPENDS (MARK at 41)
2115 49: t TUPLE (MARK at 37)
2116 50: q BINPUT 5
2117 52: R REDUCE
2118 53: X BINUNICODE 'def'
2119 61: q BINPUT 6
2120 63: s SETITEM
2121 64: e APPENDS (MARK at 3)
2122 65: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002123highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002124
2125Exercise the INST/OBJ/BUILD family.
2126
2127>>> import random
Guido van Rossum4f7ac2e2007-02-26 15:59:50 +00002128>>> dis(pickle.dumps(random.getrandbits, 0))
2129 0: c GLOBAL 'random getrandbits'
2130 20: p PUT 0
2131 23: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002132highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002133
Tim Peters90718a42005-02-15 16:22:34 +00002134>>> from pickletools import _Example
2135>>> x = [_Example(42)] * 2
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002136>>> dis(pickle.dumps(x, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002137 0: ( MARK
2138 1: l LIST (MARK at 0)
2139 2: p PUT 0
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002140 5: c GLOBAL 'copyreg _reconstructor'
2141 29: p PUT 1
2142 32: ( MARK
2143 33: c GLOBAL 'pickletools _Example'
2144 55: p PUT 2
2145 58: c GLOBAL 'builtins object'
2146 75: p PUT 3
2147 78: N NONE
2148 79: t TUPLE (MARK at 32)
2149 80: p PUT 4
2150 83: R REDUCE
2151 84: p PUT 5
2152 87: ( MARK
2153 88: d DICT (MARK at 87)
2154 89: p PUT 6
2155 92: V UNICODE 'value'
2156 99: p PUT 7
2157 102: L LONG 42
2158 106: s SETITEM
2159 107: b BUILD
2160 108: a APPEND
2161 109: g GET 5
2162 112: a APPEND
2163 113: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002164highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002165
2166>>> dis(pickle.dumps(x, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002167 0: ] EMPTY_LIST
2168 1: q BINPUT 0
2169 3: ( MARK
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00002170 4: c GLOBAL 'copyreg _reconstructor'
2171 28: q BINPUT 1
2172 30: ( MARK
2173 31: c GLOBAL 'pickletools _Example'
2174 53: q BINPUT 2
2175 55: c GLOBAL 'builtins object'
2176 72: q BINPUT 3
2177 74: N NONE
2178 75: t TUPLE (MARK at 30)
2179 76: q BINPUT 4
2180 78: R REDUCE
2181 79: q BINPUT 5
2182 81: } EMPTY_DICT
2183 82: q BINPUT 6
2184 84: X BINUNICODE 'value'
2185 94: q BINPUT 7
2186 96: K BININT1 42
2187 98: s SETITEM
2188 99: b BUILD
2189 100: h BINGET 5
2190 102: e APPENDS (MARK at 3)
2191 103: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002192highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002193
2194Try "the canonical" recursive-object test.
2195
2196>>> L = []
2197>>> T = L,
2198>>> L.append(T)
2199>>> L[0] is T
2200True
2201>>> T[0] is L
2202True
2203>>> L[0][0] is L
2204True
2205>>> T[0][0] is T
2206True
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002207>>> dis(pickle.dumps(L, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002208 0: ( MARK
2209 1: l LIST (MARK at 0)
2210 2: p PUT 0
2211 5: ( MARK
2212 6: g GET 0
2213 9: t TUPLE (MARK at 5)
2214 10: p PUT 1
2215 13: a APPEND
2216 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002217highest protocol among opcodes = 0
2218
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002219>>> dis(pickle.dumps(L, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002220 0: ] EMPTY_LIST
2221 1: q BINPUT 0
2222 3: ( MARK
2223 4: h BINGET 0
2224 6: t TUPLE (MARK at 3)
2225 7: q BINPUT 1
2226 9: a APPEND
2227 10: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002228highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002229
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002230Note that, in the protocol 0 pickle of the recursive tuple, the disassembler
2231has to emulate the stack in order to realize that the POP opcode at 16 gets
2232rid of the MARK at 0.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002233
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002234>>> dis(pickle.dumps(T, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002235 0: ( MARK
2236 1: ( MARK
2237 2: l LIST (MARK at 1)
2238 3: p PUT 0
2239 6: ( MARK
2240 7: g GET 0
2241 10: t TUPLE (MARK at 6)
2242 11: p PUT 1
2243 14: a APPEND
2244 15: 0 POP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002245 16: 0 POP (MARK at 0)
2246 17: g GET 1
2247 20: . STOP
2248highest protocol among opcodes = 0
2249
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002250>>> dis(pickle.dumps(T, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002251 0: ( MARK
2252 1: ] EMPTY_LIST
2253 2: q BINPUT 0
2254 4: ( MARK
2255 5: h BINGET 0
2256 7: t TUPLE (MARK at 4)
2257 8: q BINPUT 1
2258 10: a APPEND
2259 11: 1 POP_MARK (MARK at 0)
2260 12: h BINGET 1
2261 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002262highest protocol among opcodes = 1
Tim Petersd0f7c862003-01-28 15:27:57 +00002263
2264Try protocol 2.
2265
2266>>> dis(pickle.dumps(L, 2))
2267 0: \x80 PROTO 2
2268 2: ] EMPTY_LIST
2269 3: q BINPUT 0
2270 5: h BINGET 0
2271 7: \x85 TUPLE1
2272 8: q BINPUT 1
2273 10: a APPEND
2274 11: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002275highest protocol among opcodes = 2
Tim Petersd0f7c862003-01-28 15:27:57 +00002276
2277>>> dis(pickle.dumps(T, 2))
2278 0: \x80 PROTO 2
2279 2: ] EMPTY_LIST
2280 3: q BINPUT 0
2281 5: h BINGET 0
2282 7: \x85 TUPLE1
2283 8: q BINPUT 1
2284 10: a APPEND
2285 11: 0 POP
2286 12: h BINGET 1
2287 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002288highest protocol among opcodes = 2
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002289"""
2290
Tim Peters62235e72003-02-05 19:55:53 +00002291_memo_test = r"""
2292>>> import pickle
Guido van Rossumcfe5f202007-05-08 21:26:54 +00002293>>> import io
2294>>> f = io.BytesIO()
Tim Peters62235e72003-02-05 19:55:53 +00002295>>> p = pickle.Pickler(f, 2)
2296>>> x = [1, 2, 3]
2297>>> p.dump(x)
2298>>> p.dump(x)
2299>>> f.seek(0)
Guido van Rossumcfe5f202007-05-08 21:26:54 +000023000
Tim Peters62235e72003-02-05 19:55:53 +00002301>>> memo = {}
2302>>> dis(f, memo=memo)
2303 0: \x80 PROTO 2
2304 2: ] EMPTY_LIST
2305 3: q BINPUT 0
2306 5: ( MARK
2307 6: K BININT1 1
2308 8: K BININT1 2
2309 10: K BININT1 3
2310 12: e APPENDS (MARK at 5)
2311 13: . STOP
2312highest protocol among opcodes = 2
2313>>> dis(f, memo=memo)
2314 14: \x80 PROTO 2
2315 16: h BINGET 0
2316 18: . STOP
2317highest protocol among opcodes = 2
2318"""
2319
Guido van Rossum57028352003-01-28 15:09:10 +00002320__test__ = {'disassembler_test': _dis_test,
Tim Peters62235e72003-02-05 19:55:53 +00002321 'disassembler_memo_test': _memo_test,
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002322 }
2323
2324def _test():
2325 import doctest
2326 return doctest.testmod()
2327
2328if __name__ == "__main__":
2329 _test()