blob: 1b6967ae463865ca4e24d1aad4f91d0b64141264 [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
145copy_reg.safe_constructors are removed from the unpickling code.
146References 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 Rossum98297ee2007-11-06 21:34:58 +0000749 name='bytes',
750 obtype=bytes,
751 doc="A Python bytes object.")
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000752
753pyunicode = StackObject(
Guido van Rossum98297ee2007-11-06 21:34:58 +0000754 name='str',
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000755 obtype=str,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000756 doc="A Python string object.")
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000757
758pynone = StackObject(
759 name="None",
760 obtype=type(None),
761 doc="The Python None object.")
762
763pytuple = StackObject(
764 name="tuple",
765 obtype=tuple,
766 doc="A Python tuple object.")
767
768pylist = StackObject(
769 name="list",
770 obtype=list,
771 doc="A Python list object.")
772
773pydict = StackObject(
774 name="dict",
775 obtype=dict,
776 doc="A Python dict object.")
777
778anyobject = StackObject(
779 name='any',
780 obtype=object,
781 doc="Any kind of object whatsoever.")
782
783markobject = StackObject(
784 name="mark",
785 obtype=StackObject,
786 doc="""'The mark' is a unique object.
787
788 Opcodes that operate on a variable number of objects
789 generally don't embed the count of objects in the opcode,
790 or pull it off the stack. Instead the MARK opcode is used
791 to push a special marker object on the stack, and then
792 some other opcodes grab all the objects from the top of
793 the stack down to (but not including) the topmost marker
794 object.
795 """)
796
797stackslice = StackObject(
798 name="stackslice",
799 obtype=StackObject,
800 doc="""An object representing a contiguous slice of the stack.
801
802 This is used in conjuction with markobject, to represent all
803 of the stack following the topmost markobject. For example,
804 the POP_MARK opcode changes the stack from
805
806 [..., markobject, stackslice]
807 to
808 [...]
809
810 No matter how many object are on the stack after the topmost
811 markobject, POP_MARK gets rid of all of them (including the
812 topmost markobject too).
813 """)
814
815##############################################################################
816# Descriptors for pickle opcodes.
817
818class OpcodeInfo(object):
819
820 __slots__ = (
821 # symbolic name of opcode; a string
822 'name',
823
824 # the code used in a bytestream to represent the opcode; a
825 # one-character string
826 'code',
827
828 # If the opcode has an argument embedded in the byte string, an
829 # instance of ArgumentDescriptor specifying its type. Note that
830 # arg.reader(s) can be used to read and decode the argument from
831 # the bytestream s, and arg.doc documents the format of the raw
832 # argument bytes. If the opcode doesn't have an argument embedded
833 # in the bytestream, arg should be None.
834 'arg',
835
836 # what the stack looks like before this opcode runs; a list
837 'stack_before',
838
839 # what the stack looks like after this opcode runs; a list
840 'stack_after',
841
842 # the protocol number in which this opcode was introduced; an int
843 'proto',
844
845 # human-readable docs for this opcode; a string
846 'doc',
847 )
848
849 def __init__(self, name, code, arg,
850 stack_before, stack_after, proto, doc):
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000851 assert isinstance(name, str)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000852 self.name = name
853
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000854 assert isinstance(code, str)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000855 assert len(code) == 1
856 self.code = code
857
858 assert arg is None or isinstance(arg, ArgumentDescriptor)
859 self.arg = arg
860
861 assert isinstance(stack_before, list)
862 for x in stack_before:
863 assert isinstance(x, StackObject)
864 self.stack_before = stack_before
865
866 assert isinstance(stack_after, list)
867 for x in stack_after:
868 assert isinstance(x, StackObject)
869 self.stack_after = stack_after
870
871 assert isinstance(proto, int) and 0 <= proto <= 2
872 self.proto = proto
873
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000874 assert isinstance(doc, str)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000875 self.doc = doc
876
877I = OpcodeInfo
878opcodes = [
879
880 # Ways to spell integers.
881
882 I(name='INT',
883 code='I',
884 arg=decimalnl_short,
885 stack_before=[],
886 stack_after=[pyinteger_or_bool],
887 proto=0,
888 doc="""Push an integer or bool.
889
890 The argument is a newline-terminated decimal literal string.
891
892 The intent may have been that this always fit in a short Python int,
893 but INT can be generated in pickles written on a 64-bit box that
894 require a Python long on a 32-bit box. The difference between this
895 and LONG then is that INT skips a trailing 'L', and produces a short
896 int whenever possible.
897
898 Another difference is due to that, when bool was introduced as a
899 distinct type in 2.3, builtin names True and False were also added to
900 2.2.2, mapping to ints 1 and 0. For compatibility in both directions,
901 True gets pickled as INT + "I01\\n", and False as INT + "I00\\n".
902 Leading zeroes are never produced for a genuine integer. The 2.3
903 (and later) unpicklers special-case these and return bool instead;
904 earlier unpicklers ignore the leading "0" and return the int.
905 """),
906
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000907 I(name='BININT',
908 code='J',
909 arg=int4,
910 stack_before=[],
911 stack_after=[pyint],
912 proto=1,
913 doc="""Push a four-byte signed integer.
914
915 This handles the full range of Python (short) integers on a 32-bit
916 box, directly as binary bytes (1 for the opcode and 4 for the integer).
917 If the integer is non-negative and fits in 1 or 2 bytes, pickling via
918 BININT1 or BININT2 saves space.
919 """),
920
921 I(name='BININT1',
922 code='K',
923 arg=uint1,
924 stack_before=[],
925 stack_after=[pyint],
926 proto=1,
927 doc="""Push a one-byte unsigned integer.
928
929 This is a space optimization for pickling very small non-negative ints,
930 in range(256).
931 """),
932
933 I(name='BININT2',
934 code='M',
935 arg=uint2,
936 stack_before=[],
937 stack_after=[pyint],
938 proto=1,
939 doc="""Push a two-byte unsigned integer.
940
941 This is a space optimization for pickling small positive ints, in
942 range(256, 2**16). Integers in range(256) can also be pickled via
943 BININT2, but BININT1 instead saves a byte.
944 """),
945
Tim Petersfdc03462003-01-28 04:56:33 +0000946 I(name='LONG',
947 code='L',
948 arg=decimalnl_long,
949 stack_before=[],
950 stack_after=[pylong],
951 proto=0,
952 doc="""Push a long integer.
953
954 The same as INT, except that the literal ends with 'L', and always
955 unpickles to a Python long. There doesn't seem a real purpose to the
956 trailing 'L'.
957
958 Note that LONG takes time quadratic in the number of digits when
959 unpickling (this is simply due to the nature of decimal->binary
960 conversion). Proto 2 added linear-time (in C; still quadratic-time
961 in Python) LONG1 and LONG4 opcodes.
962 """),
963
964 I(name="LONG1",
965 code='\x8a',
966 arg=long1,
967 stack_before=[],
968 stack_after=[pylong],
969 proto=2,
970 doc="""Long integer using one-byte length.
971
972 A more efficient encoding of a Python long; the long1 encoding
973 says it all."""),
974
975 I(name="LONG4",
976 code='\x8b',
977 arg=long4,
978 stack_before=[],
979 stack_after=[pylong],
980 proto=2,
981 doc="""Long integer using found-byte length.
982
983 A more efficient encoding of a Python long; the long4 encoding
984 says it all."""),
985
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000986 # Ways to spell strings (8-bit, not Unicode).
987
988 I(name='STRING',
989 code='S',
990 arg=stringnl,
991 stack_before=[],
992 stack_after=[pystring],
993 proto=0,
994 doc="""Push a Python string object.
995
996 The argument is a repr-style string, with bracketing quote characters,
997 and perhaps embedded escapes. The argument extends until the next
998 newline character.
999 """),
1000
1001 I(name='BINSTRING',
1002 code='T',
1003 arg=string4,
1004 stack_before=[],
1005 stack_after=[pystring],
1006 proto=1,
1007 doc="""Push a Python string object.
1008
1009 There are two arguments: the first is a 4-byte little-endian signed int
1010 giving the number of bytes in the string, and the second is that many
1011 bytes, which are taken literally as the string content.
1012 """),
1013
1014 I(name='SHORT_BINSTRING',
1015 code='U',
1016 arg=string1,
1017 stack_before=[],
1018 stack_after=[pystring],
1019 proto=1,
1020 doc="""Push a Python string object.
1021
1022 There are two arguments: the first is a 1-byte unsigned int giving
1023 the number of bytes in the string, and the second is that many bytes,
1024 which are taken literally as the string content.
1025 """),
1026
1027 # Ways to spell None.
1028
1029 I(name='NONE',
1030 code='N',
1031 arg=None,
1032 stack_before=[],
1033 stack_after=[pynone],
1034 proto=0,
1035 doc="Push None on the stack."),
1036
Tim Petersfdc03462003-01-28 04:56:33 +00001037 # Ways to spell bools, starting with proto 2. See INT for how this was
1038 # done before proto 2.
1039
1040 I(name='NEWTRUE',
1041 code='\x88',
1042 arg=None,
1043 stack_before=[],
1044 stack_after=[pybool],
1045 proto=2,
1046 doc="""True.
1047
1048 Push True onto the stack."""),
1049
1050 I(name='NEWFALSE',
1051 code='\x89',
1052 arg=None,
1053 stack_before=[],
1054 stack_after=[pybool],
1055 proto=2,
1056 doc="""True.
1057
1058 Push False onto the stack."""),
1059
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001060 # Ways to spell Unicode strings.
1061
1062 I(name='UNICODE',
1063 code='V',
1064 arg=unicodestringnl,
1065 stack_before=[],
1066 stack_after=[pyunicode],
1067 proto=0, # this may be pure-text, but it's a later addition
1068 doc="""Push a Python Unicode string object.
1069
1070 The argument is a raw-unicode-escape encoding of a Unicode string,
1071 and so may contain embedded escape sequences. The argument extends
1072 until the next newline character.
1073 """),
1074
1075 I(name='BINUNICODE',
1076 code='X',
1077 arg=unicodestring4,
1078 stack_before=[],
1079 stack_after=[pyunicode],
1080 proto=1,
1081 doc="""Push a Python Unicode string object.
1082
1083 There are two arguments: the first is a 4-byte little-endian signed int
1084 giving the number of bytes in the string. The second is that many
1085 bytes, and is the UTF-8 encoding of the Unicode string.
1086 """),
1087
1088 # Ways to spell floats.
1089
1090 I(name='FLOAT',
1091 code='F',
1092 arg=floatnl,
1093 stack_before=[],
1094 stack_after=[pyfloat],
1095 proto=0,
1096 doc="""Newline-terminated decimal float literal.
1097
1098 The argument is repr(a_float), and in general requires 17 significant
1099 digits for roundtrip conversion to be an identity (this is so for
1100 IEEE-754 double precision values, which is what Python float maps to
1101 on most boxes).
1102
1103 In general, FLOAT cannot be used to transport infinities, NaNs, or
1104 minus zero across boxes (or even on a single box, if the platform C
1105 library can't read the strings it produces for such things -- Windows
1106 is like that), but may do less damage than BINFLOAT on boxes with
1107 greater precision or dynamic range than IEEE-754 double.
1108 """),
1109
1110 I(name='BINFLOAT',
1111 code='G',
1112 arg=float8,
1113 stack_before=[],
1114 stack_after=[pyfloat],
1115 proto=1,
1116 doc="""Float stored in binary form, with 8 bytes of data.
1117
1118 This generally requires less than half the space of FLOAT encoding.
1119 In general, BINFLOAT cannot be used to transport infinities, NaNs, or
1120 minus zero, raises an exception if the exponent exceeds the range of
1121 an IEEE-754 double, and retains no more than 53 bits of precision (if
1122 there are more than that, "add a half and chop" rounding is used to
1123 cut it back to 53 significant bits).
1124 """),
1125
1126 # Ways to build lists.
1127
1128 I(name='EMPTY_LIST',
1129 code=']',
1130 arg=None,
1131 stack_before=[],
1132 stack_after=[pylist],
1133 proto=1,
1134 doc="Push an empty list."),
1135
1136 I(name='APPEND',
1137 code='a',
1138 arg=None,
1139 stack_before=[pylist, anyobject],
1140 stack_after=[pylist],
1141 proto=0,
1142 doc="""Append an object to a list.
1143
1144 Stack before: ... pylist anyobject
1145 Stack after: ... pylist+[anyobject]
Tim Peters81098ac2003-01-28 05:12:08 +00001146
1147 although pylist is really extended in-place.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001148 """),
1149
1150 I(name='APPENDS',
1151 code='e',
1152 arg=None,
1153 stack_before=[pylist, markobject, stackslice],
1154 stack_after=[pylist],
1155 proto=1,
1156 doc="""Extend a list by a slice of stack objects.
1157
1158 Stack before: ... pylist markobject stackslice
1159 Stack after: ... pylist+stackslice
Tim Peters81098ac2003-01-28 05:12:08 +00001160
1161 although pylist is really extended in-place.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001162 """),
1163
1164 I(name='LIST',
1165 code='l',
1166 arg=None,
1167 stack_before=[markobject, stackslice],
1168 stack_after=[pylist],
1169 proto=0,
1170 doc="""Build a list out of the topmost stack slice, after markobject.
1171
1172 All the stack entries following the topmost markobject are placed into
1173 a single Python list, which single list object replaces all of the
1174 stack from the topmost markobject onward. For example,
1175
1176 Stack before: ... markobject 1 2 3 'abc'
1177 Stack after: ... [1, 2, 3, 'abc']
1178 """),
1179
1180 # Ways to build tuples.
1181
1182 I(name='EMPTY_TUPLE',
1183 code=')',
1184 arg=None,
1185 stack_before=[],
1186 stack_after=[pytuple],
1187 proto=1,
1188 doc="Push an empty tuple."),
1189
1190 I(name='TUPLE',
1191 code='t',
1192 arg=None,
1193 stack_before=[markobject, stackslice],
1194 stack_after=[pytuple],
1195 proto=0,
1196 doc="""Build a tuple out of the topmost stack slice, after markobject.
1197
1198 All the stack entries following the topmost markobject are placed into
1199 a single Python tuple, which single tuple object replaces all of the
1200 stack from the topmost markobject onward. For example,
1201
1202 Stack before: ... markobject 1 2 3 'abc'
1203 Stack after: ... (1, 2, 3, 'abc')
1204 """),
1205
Tim Petersfdc03462003-01-28 04:56:33 +00001206 I(name='TUPLE1',
1207 code='\x85',
1208 arg=None,
1209 stack_before=[anyobject],
1210 stack_after=[pytuple],
1211 proto=2,
1212 doc="""One-tuple.
1213
1214 This code pops one value off the stack and pushes a tuple of
1215 length 1 whose one item is that value back onto it. IOW:
1216
1217 stack[-1] = tuple(stack[-1:])
1218 """),
1219
1220 I(name='TUPLE2',
1221 code='\x86',
1222 arg=None,
1223 stack_before=[anyobject, anyobject],
1224 stack_after=[pytuple],
1225 proto=2,
1226 doc="""One-tuple.
1227
1228 This code pops two values off the stack and pushes a tuple
1229 of length 2 whose items are those values back onto it. IOW:
1230
1231 stack[-2:] = [tuple(stack[-2:])]
1232 """),
1233
1234 I(name='TUPLE3',
1235 code='\x87',
1236 arg=None,
1237 stack_before=[anyobject, anyobject, anyobject],
1238 stack_after=[pytuple],
1239 proto=2,
1240 doc="""One-tuple.
1241
1242 This code pops three values off the stack and pushes a tuple
1243 of length 3 whose items are those values back onto it. IOW:
1244
1245 stack[-3:] = [tuple(stack[-3:])]
1246 """),
1247
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001248 # Ways to build dicts.
1249
1250 I(name='EMPTY_DICT',
1251 code='}',
1252 arg=None,
1253 stack_before=[],
1254 stack_after=[pydict],
1255 proto=1,
1256 doc="Push an empty dict."),
1257
1258 I(name='DICT',
1259 code='d',
1260 arg=None,
1261 stack_before=[markobject, stackslice],
1262 stack_after=[pydict],
1263 proto=0,
1264 doc="""Build a dict out of the topmost stack slice, after markobject.
1265
1266 All the stack entries following the topmost markobject are placed into
1267 a single Python dict, which single dict object replaces all of the
1268 stack from the topmost markobject onward. The stack slice alternates
1269 key, value, key, value, .... For example,
1270
1271 Stack before: ... markobject 1 2 3 'abc'
1272 Stack after: ... {1: 2, 3: 'abc'}
1273 """),
1274
1275 I(name='SETITEM',
1276 code='s',
1277 arg=None,
1278 stack_before=[pydict, anyobject, anyobject],
1279 stack_after=[pydict],
1280 proto=0,
1281 doc="""Add a key+value pair to an existing dict.
1282
1283 Stack before: ... pydict key value
1284 Stack after: ... pydict
1285
1286 where pydict has been modified via pydict[key] = value.
1287 """),
1288
1289 I(name='SETITEMS',
1290 code='u',
1291 arg=None,
1292 stack_before=[pydict, markobject, stackslice],
1293 stack_after=[pydict],
1294 proto=1,
1295 doc="""Add an arbitrary number of key+value pairs to an existing dict.
1296
1297 The slice of the stack following the topmost markobject is taken as
1298 an alternating sequence of keys and values, added to the dict
1299 immediately under the topmost markobject. Everything at and after the
1300 topmost markobject is popped, leaving the mutated dict at the top
1301 of the stack.
1302
1303 Stack before: ... pydict markobject key_1 value_1 ... key_n value_n
1304 Stack after: ... pydict
1305
1306 where pydict has been modified via pydict[key_i] = value_i for i in
1307 1, 2, ..., n, and in that order.
1308 """),
1309
1310 # Stack manipulation.
1311
1312 I(name='POP',
1313 code='0',
1314 arg=None,
1315 stack_before=[anyobject],
1316 stack_after=[],
1317 proto=0,
1318 doc="Discard the top stack item, shrinking the stack by one item."),
1319
1320 I(name='DUP',
1321 code='2',
1322 arg=None,
1323 stack_before=[anyobject],
1324 stack_after=[anyobject, anyobject],
1325 proto=0,
1326 doc="Push the top stack item onto the stack again, duplicating it."),
1327
1328 I(name='MARK',
1329 code='(',
1330 arg=None,
1331 stack_before=[],
1332 stack_after=[markobject],
1333 proto=0,
1334 doc="""Push markobject onto the stack.
1335
1336 markobject is a unique object, used by other opcodes to identify a
1337 region of the stack containing a variable number of objects for them
1338 to work on. See markobject.doc for more detail.
1339 """),
1340
1341 I(name='POP_MARK',
1342 code='1',
1343 arg=None,
1344 stack_before=[markobject, stackslice],
1345 stack_after=[],
1346 proto=0,
1347 doc="""Pop all the stack objects at and above the topmost markobject.
1348
1349 When an opcode using a variable number of stack objects is done,
1350 POP_MARK is used to remove those objects, and to remove the markobject
1351 that delimited their starting position on the stack.
1352 """),
1353
1354 # Memo manipulation. There are really only two operations (get and put),
1355 # each in all-text, "short binary", and "long binary" flavors.
1356
1357 I(name='GET',
1358 code='g',
1359 arg=decimalnl_short,
1360 stack_before=[],
1361 stack_after=[anyobject],
1362 proto=0,
1363 doc="""Read an object from the memo and push it on the stack.
1364
1365 The index of the memo object to push is given by the newline-teriminated
1366 decimal string following. BINGET and LONG_BINGET are space-optimized
1367 versions.
1368 """),
1369
1370 I(name='BINGET',
1371 code='h',
1372 arg=uint1,
1373 stack_before=[],
1374 stack_after=[anyobject],
1375 proto=1,
1376 doc="""Read an object from the memo and push it on the stack.
1377
1378 The index of the memo object to push is given by the 1-byte unsigned
1379 integer following.
1380 """),
1381
1382 I(name='LONG_BINGET',
1383 code='j',
1384 arg=int4,
1385 stack_before=[],
1386 stack_after=[anyobject],
1387 proto=1,
1388 doc="""Read an object from the memo and push it on the stack.
1389
1390 The index of the memo object to push is given by the 4-byte signed
1391 little-endian integer following.
1392 """),
1393
1394 I(name='PUT',
1395 code='p',
1396 arg=decimalnl_short,
1397 stack_before=[],
1398 stack_after=[],
1399 proto=0,
1400 doc="""Store the stack top into the memo. The stack is not popped.
1401
1402 The index of the memo location to write into is given by the newline-
1403 terminated decimal string following. BINPUT and LONG_BINPUT are
1404 space-optimized versions.
1405 """),
1406
1407 I(name='BINPUT',
1408 code='q',
1409 arg=uint1,
1410 stack_before=[],
1411 stack_after=[],
1412 proto=1,
1413 doc="""Store the stack top into the memo. The stack is not popped.
1414
1415 The index of the memo location to write into is given by the 1-byte
1416 unsigned integer following.
1417 """),
1418
1419 I(name='LONG_BINPUT',
1420 code='r',
1421 arg=int4,
1422 stack_before=[],
1423 stack_after=[],
1424 proto=1,
1425 doc="""Store the stack top into the memo. The stack is not popped.
1426
1427 The index of the memo location to write into is given by the 4-byte
1428 signed little-endian integer following.
1429 """),
1430
Tim Petersfdc03462003-01-28 04:56:33 +00001431 # Access the extension registry (predefined objects). Akin to the GET
1432 # family.
1433
1434 I(name='EXT1',
1435 code='\x82',
1436 arg=uint1,
1437 stack_before=[],
1438 stack_after=[anyobject],
1439 proto=2,
1440 doc="""Extension code.
1441
1442 This code and the similar EXT2 and EXT4 allow using a registry
1443 of popular objects that are pickled by name, typically classes.
1444 It is envisioned that through a global negotiation and
1445 registration process, third parties can set up a mapping between
1446 ints and object names.
1447
1448 In order to guarantee pickle interchangeability, the extension
1449 code registry ought to be global, although a range of codes may
1450 be reserved for private use.
1451
1452 EXT1 has a 1-byte integer argument. This is used to index into the
1453 extension registry, and the object at that index is pushed on the stack.
1454 """),
1455
1456 I(name='EXT2',
1457 code='\x83',
1458 arg=uint2,
1459 stack_before=[],
1460 stack_after=[anyobject],
1461 proto=2,
1462 doc="""Extension code.
1463
1464 See EXT1. EXT2 has a two-byte integer argument.
1465 """),
1466
1467 I(name='EXT4',
1468 code='\x84',
1469 arg=int4,
1470 stack_before=[],
1471 stack_after=[anyobject],
1472 proto=2,
1473 doc="""Extension code.
1474
1475 See EXT1. EXT4 has a four-byte integer argument.
1476 """),
1477
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001478 # Push a class object, or module function, on the stack, via its module
1479 # and name.
1480
1481 I(name='GLOBAL',
1482 code='c',
1483 arg=stringnl_noescape_pair,
1484 stack_before=[],
1485 stack_after=[anyobject],
1486 proto=0,
1487 doc="""Push a global object (module.attr) on the stack.
1488
1489 Two newline-terminated strings follow the GLOBAL opcode. The first is
1490 taken as a module name, and the second as a class name. The class
1491 object module.class is pushed on the stack. More accurately, the
1492 object returned by self.find_class(module, class) is pushed on the
1493 stack, so unpickling subclasses can override this form of lookup.
1494 """),
1495
1496 # Ways to build objects of classes pickle doesn't know about directly
1497 # (user-defined classes). I despair of documenting this accurately
1498 # and comprehensibly -- you really have to read the pickle code to
1499 # find all the special cases.
1500
1501 I(name='REDUCE',
1502 code='R',
1503 arg=None,
1504 stack_before=[anyobject, anyobject],
1505 stack_after=[anyobject],
1506 proto=0,
1507 doc="""Push an object built from a callable and an argument tuple.
1508
1509 The opcode is named to remind of the __reduce__() method.
1510
1511 Stack before: ... callable pytuple
1512 Stack after: ... callable(*pytuple)
1513
1514 The callable and the argument tuple are the first two items returned
1515 by a __reduce__ method. Applying the callable to the argtuple is
1516 supposed to reproduce the original object, or at least get it started.
1517 If the __reduce__ method returns a 3-tuple, the last component is an
1518 argument to be passed to the object's __setstate__, and then the REDUCE
1519 opcode is followed by code to create setstate's argument, and then a
1520 BUILD opcode to apply __setstate__ to that argument.
1521
Guido van Rossum13257902007-06-07 23:15:56 +00001522 If not isinstance(callable, type), REDUCE complains unless the
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001523 callable has been registered with the copy_reg module's
1524 safe_constructors dict, or the callable has a magic
1525 '__safe_for_unpickling__' attribute with a true value. I'm not sure
1526 why it does this, but I've sure seen this complaint often enough when
1527 I didn't want to <wink>.
1528 """),
1529
1530 I(name='BUILD',
1531 code='b',
1532 arg=None,
1533 stack_before=[anyobject, anyobject],
1534 stack_after=[anyobject],
1535 proto=0,
1536 doc="""Finish building an object, via __setstate__ or dict update.
1537
1538 Stack before: ... anyobject argument
1539 Stack after: ... anyobject
1540
1541 where anyobject may have been mutated, as follows:
1542
1543 If the object has a __setstate__ method,
1544
1545 anyobject.__setstate__(argument)
1546
1547 is called.
1548
1549 Else the argument must be a dict, the object must have a __dict__, and
1550 the object is updated via
1551
1552 anyobject.__dict__.update(argument)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001553 """),
1554
1555 I(name='INST',
1556 code='i',
1557 arg=stringnl_noescape_pair,
1558 stack_before=[markobject, stackslice],
1559 stack_after=[anyobject],
1560 proto=0,
1561 doc="""Build a class instance.
1562
1563 This is the protocol 0 version of protocol 1's OBJ opcode.
1564 INST is followed by two newline-terminated strings, giving a
1565 module and class name, just as for the GLOBAL opcode (and see
1566 GLOBAL for more details about that). self.find_class(module, name)
1567 is used to get a class object.
1568
1569 In addition, all the objects on the stack following the topmost
1570 markobject are gathered into a tuple and popped (along with the
1571 topmost markobject), just as for the TUPLE opcode.
1572
1573 Now it gets complicated. If all of these are true:
1574
1575 + The argtuple is empty (markobject was at the top of the stack
1576 at the start).
1577
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001578 + The class object does not have a __getinitargs__ attribute.
1579
1580 then we want to create an old-style class instance without invoking
1581 its __init__() method (pickle has waffled on this over the years; not
1582 calling __init__() is current wisdom). In this case, an instance of
1583 an old-style dummy class is created, and then we try to rebind its
1584 __class__ attribute to the desired class object. If this succeeds,
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001585 the new instance object is pushed on the stack, and we're done.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001586
1587 Else (the argtuple is not empty, it's not an old-style class object,
1588 or the class object does have a __getinitargs__ attribute), the code
1589 first insists that the class object have a __safe_for_unpickling__
1590 attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE,
1591 it doesn't matter whether this attribute has a true or false value, it
Guido van Rossum99603b02007-07-20 00:22:32 +00001592 only matters whether it exists (XXX this is a bug). If
1593 __safe_for_unpickling__ doesn't exist, UnpicklingError is raised.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001594
1595 Else (the class object does have a __safe_for_unpickling__ attr),
1596 the class object obtained from INST's arguments is applied to the
1597 argtuple obtained from the stack, and the resulting instance object
1598 is pushed on the stack.
Tim Peters2b93c4c2003-01-30 16:35:08 +00001599
1600 NOTE: checks for __safe_for_unpickling__ went away in Python 2.3.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001601 """),
1602
1603 I(name='OBJ',
1604 code='o',
1605 arg=None,
1606 stack_before=[markobject, anyobject, stackslice],
1607 stack_after=[anyobject],
1608 proto=1,
1609 doc="""Build a class instance.
1610
1611 This is the protocol 1 version of protocol 0's INST opcode, and is
1612 very much like it. The major difference is that the class object
1613 is taken off the stack, allowing it to be retrieved from the memo
1614 repeatedly if several instances of the same class are created. This
1615 can be much more efficient (in both time and space) than repeatedly
1616 embedding the module and class names in INST opcodes.
1617
1618 Unlike INST, OBJ takes no arguments from the opcode stream. Instead
1619 the class object is taken off the stack, immediately above the
1620 topmost markobject:
1621
1622 Stack before: ... markobject classobject stackslice
1623 Stack after: ... new_instance_object
1624
1625 As for INST, the remainder of the stack above the markobject is
1626 gathered into an argument tuple, and then the logic seems identical,
Guido van Rossumecb11042003-01-29 06:24:30 +00001627 except that no __safe_for_unpickling__ check is done (XXX this is
Guido van Rossum99603b02007-07-20 00:22:32 +00001628 a bug). See INST for the gory details.
Tim Peters2b93c4c2003-01-30 16:35:08 +00001629
1630 NOTE: In Python 2.3, INST and OBJ are identical except for how they
1631 get the class object. That was always the intent; the implementations
1632 had diverged for accidental reasons.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001633 """),
1634
Tim Petersfdc03462003-01-28 04:56:33 +00001635 I(name='NEWOBJ',
1636 code='\x81',
1637 arg=None,
1638 stack_before=[anyobject, anyobject],
1639 stack_after=[anyobject],
1640 proto=2,
1641 doc="""Build an object instance.
1642
1643 The stack before should be thought of as containing a class
1644 object followed by an argument tuple (the tuple being the stack
1645 top). Call these cls and args. They are popped off the stack,
1646 and the value returned by cls.__new__(cls, *args) is pushed back
1647 onto the stack.
1648 """),
1649
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001650 # Machine control.
1651
Tim Petersfdc03462003-01-28 04:56:33 +00001652 I(name='PROTO',
1653 code='\x80',
1654 arg=uint1,
1655 stack_before=[],
1656 stack_after=[],
1657 proto=2,
1658 doc="""Protocol version indicator.
1659
1660 For protocol 2 and above, a pickle must start with this opcode.
1661 The argument is the protocol version, an int in range(2, 256).
1662 """),
1663
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001664 I(name='STOP',
1665 code='.',
1666 arg=None,
1667 stack_before=[anyobject],
1668 stack_after=[],
1669 proto=0,
1670 doc="""Stop the unpickling machine.
1671
1672 Every pickle ends with this opcode. The object at the top of the stack
1673 is popped, and that's the result of unpickling. The stack should be
1674 empty then.
1675 """),
1676
1677 # Ways to deal with persistent IDs.
1678
1679 I(name='PERSID',
1680 code='P',
1681 arg=stringnl_noescape,
1682 stack_before=[],
1683 stack_after=[anyobject],
1684 proto=0,
1685 doc="""Push an object identified by a persistent ID.
1686
1687 The pickle module doesn't define what a persistent ID means. PERSID's
1688 argument is a newline-terminated str-style (no embedded escapes, no
1689 bracketing quote characters) string, which *is* "the persistent ID".
1690 The unpickler passes this string to self.persistent_load(). Whatever
1691 object that returns is pushed on the stack. There is no implementation
1692 of persistent_load() in Python's unpickler: it must be supplied by an
1693 unpickler subclass.
1694 """),
1695
1696 I(name='BINPERSID',
1697 code='Q',
1698 arg=None,
1699 stack_before=[anyobject],
1700 stack_after=[anyobject],
1701 proto=1,
1702 doc="""Push an object identified by a persistent ID.
1703
1704 Like PERSID, except the persistent ID is popped off the stack (instead
1705 of being a string embedded in the opcode bytestream). The persistent
1706 ID is passed to self.persistent_load(), and whatever object that
1707 returns is pushed on the stack. See PERSID for more detail.
1708 """),
1709]
1710del I
1711
1712# Verify uniqueness of .name and .code members.
1713name2i = {}
1714code2i = {}
1715
1716for i, d in enumerate(opcodes):
1717 if d.name in name2i:
1718 raise ValueError("repeated name %r at indices %d and %d" %
1719 (d.name, name2i[d.name], i))
1720 if d.code in code2i:
1721 raise ValueError("repeated code %r at indices %d and %d" %
1722 (d.code, code2i[d.code], i))
1723
1724 name2i[d.name] = i
1725 code2i[d.code] = i
1726
1727del name2i, code2i, i, d
1728
1729##############################################################################
1730# Build a code2op dict, mapping opcode characters to OpcodeInfo records.
1731# Also ensure we've got the same stuff as pickle.py, although the
1732# introspection here is dicey.
1733
1734code2op = {}
1735for d in opcodes:
1736 code2op[d.code] = d
1737del d
1738
1739def assure_pickle_consistency(verbose=False):
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001740
1741 copy = code2op.copy()
1742 for name in pickle.__all__:
1743 if not re.match("[A-Z][A-Z0-9_]+$", name):
1744 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001745 print("skipping %r: it doesn't look like an opcode name" % name)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001746 continue
1747 picklecode = getattr(pickle, name)
Guido van Rossum617dbc42007-05-07 23:57:08 +00001748 if not isinstance(picklecode, bytes) or len(picklecode) != 1:
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001749 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001750 print(("skipping %r: value %r doesn't look like a pickle "
1751 "code" % (name, picklecode)))
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001752 continue
Guido van Rossum617dbc42007-05-07 23:57:08 +00001753 picklecode = picklecode.decode("latin-1")
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001754 if picklecode in copy:
1755 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001756 print("checking name %r w/ code %r for consistency" % (
1757 name, picklecode))
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001758 d = copy[picklecode]
1759 if d.name != name:
1760 raise ValueError("for pickle code %r, pickle.py uses name %r "
1761 "but we're using name %r" % (picklecode,
1762 name,
1763 d.name))
1764 # Forget this one. Any left over in copy at the end are a problem
1765 # of a different kind.
1766 del copy[picklecode]
1767 else:
1768 raise ValueError("pickle.py appears to have a pickle opcode with "
1769 "name %r and code %r, but we don't" %
1770 (name, picklecode))
1771 if copy:
1772 msg = ["we appear to have pickle opcodes that pickle.py doesn't have:"]
1773 for code, d in copy.items():
1774 msg.append(" name %r with code %r" % (d.name, code))
1775 raise ValueError("\n".join(msg))
1776
1777assure_pickle_consistency()
Tim Petersc0c12b52003-01-29 00:56:17 +00001778del assure_pickle_consistency
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001779
1780##############################################################################
1781# A pickle opcode generator.
1782
1783def genops(pickle):
Guido van Rossuma72ded92003-01-27 19:40:47 +00001784 """Generate all the opcodes in a pickle.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001785
1786 'pickle' is a file-like object, or string, containing the pickle.
1787
1788 Each opcode in the pickle is generated, from the current pickle position,
1789 stopping after a STOP opcode is delivered. A triple is generated for
1790 each opcode:
1791
1792 opcode, arg, pos
1793
1794 opcode is an OpcodeInfo record, describing the current opcode.
1795
1796 If the opcode has an argument embedded in the pickle, arg is its decoded
1797 value, as a Python object. If the opcode doesn't have an argument, arg
1798 is None.
1799
1800 If the pickle has a tell() method, pos was the value of pickle.tell()
Guido van Rossum34d19282007-08-09 01:03:29 +00001801 before reading the current opcode. If the pickle is a bytes object,
1802 it's wrapped in a BytesIO object, and the latter's tell() result is
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001803 used. Else (the pickle doesn't have a tell(), and it's not obvious how
1804 to query its current position) pos is None.
1805 """
1806
Guido van Rossum98297ee2007-11-06 21:34:58 +00001807 if isinstance(pickle, bytes_types):
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001808 import io
1809 pickle = io.BytesIO(pickle)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001810
1811 if hasattr(pickle, "tell"):
1812 getpos = pickle.tell
1813 else:
1814 getpos = lambda: None
1815
1816 while True:
1817 pos = getpos()
1818 code = pickle.read(1)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001819 opcode = code2op.get(code.decode("latin-1"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001820 if opcode is None:
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001821 if code == b"":
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001822 raise ValueError("pickle exhausted before seeing STOP")
1823 else:
1824 raise ValueError("at position %s, opcode %r unknown" % (
1825 pos is None and "<unknown>" or pos,
1826 code))
1827 if opcode.arg is None:
1828 arg = None
1829 else:
1830 arg = opcode.arg.reader(pickle)
1831 yield opcode, arg, pos
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001832 if code == b'.':
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001833 assert opcode.name == 'STOP'
1834 break
1835
1836##############################################################################
Christian Heimes3feef612008-02-11 06:19:17 +00001837# A pickle optimizer.
1838
1839def optimize(p):
1840 'Optimize a pickle string by removing unused PUT opcodes'
1841 gets = set() # set of args used by a GET opcode
1842 puts = [] # (arg, startpos, stoppos) for the PUT opcodes
1843 prevpos = None # set to pos if previous opcode was a PUT
1844 for opcode, arg, pos in genops(p):
1845 if prevpos is not None:
1846 puts.append((prevarg, prevpos, pos))
1847 prevpos = None
1848 if 'PUT' in opcode.name:
1849 prevarg, prevpos = arg, pos
1850 elif 'GET' in opcode.name:
1851 gets.add(arg)
1852
1853 # Copy the pickle string except for PUTS without a corresponding GET
1854 s = []
1855 i = 0
1856 for arg, start, stop in puts:
1857 j = stop if (arg in gets) else start
1858 s.append(p[i:j])
1859 i = stop
1860 s.append(p[i:])
1861 return ''.join(s)
1862
1863##############################################################################
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001864# A symbolic pickle disassembler.
1865
Tim Peters62235e72003-02-05 19:55:53 +00001866def dis(pickle, out=None, memo=None, indentlevel=4):
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001867 """Produce a symbolic disassembly of a pickle.
1868
1869 'pickle' is a file-like object, or string, containing a (at least one)
1870 pickle. The pickle is disassembled from the current position, through
1871 the first STOP opcode encountered.
1872
1873 Optional arg 'out' is a file-like object to which the disassembly is
1874 printed. It defaults to sys.stdout.
1875
Tim Peters62235e72003-02-05 19:55:53 +00001876 Optional arg 'memo' is a Python dict, used as the pickle's memo. It
1877 may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes.
1878 Passing the same memo object to another dis() call then allows disassembly
1879 to proceed across multiple pickles that were all created by the same
1880 pickler with the same memo. Ordinarily you don't need to worry about this.
1881
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001882 Optional arg indentlevel is the number of blanks by which to indent
1883 a new MARK level. It defaults to 4.
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001884
1885 In addition to printing the disassembly, some sanity checks are made:
1886
1887 + All embedded opcode arguments "make sense".
1888
1889 + Explicit and implicit pop operations have enough items on the stack.
1890
1891 + When an opcode implicitly refers to a markobject, a markobject is
1892 actually on the stack.
1893
1894 + A memo entry isn't referenced before it's defined.
1895
1896 + The markobject isn't stored in the memo.
1897
1898 + A memo entry isn't redefined.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001899 """
1900
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001901 # Most of the hair here is for sanity checks, but most of it is needed
1902 # anyway to detect when a protocol 0 POP takes a MARK off the stack
1903 # (which in turn is needed to indent MARK blocks correctly).
1904
1905 stack = [] # crude emulation of unpickler stack
Tim Peters62235e72003-02-05 19:55:53 +00001906 if memo is None:
1907 memo = {} # crude emulation of unpicker memo
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001908 maxproto = -1 # max protocol number seen
1909 markstack = [] # bytecode positions of MARK opcodes
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001910 indentchunk = ' ' * indentlevel
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001911 errormsg = None
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001912 for opcode, arg, pos in genops(pickle):
1913 if pos is not None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001914 print("%5d:" % pos, end=' ', file=out)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001915
Tim Petersd0f7c862003-01-28 15:27:57 +00001916 line = "%-4s %s%s" % (repr(opcode.code)[1:-1],
1917 indentchunk * len(markstack),
1918 opcode.name)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001919
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001920 maxproto = max(maxproto, opcode.proto)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001921 before = opcode.stack_before # don't mutate
1922 after = opcode.stack_after # don't mutate
Tim Peters43277d62003-01-30 15:02:12 +00001923 numtopop = len(before)
1924
1925 # See whether a MARK should be popped.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001926 markmsg = None
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001927 if markobject in before or (opcode.name == "POP" and
1928 stack and
1929 stack[-1] is markobject):
1930 assert markobject not in after
Tim Peters43277d62003-01-30 15:02:12 +00001931 if __debug__:
1932 if markobject in before:
1933 assert before[-1] is stackslice
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001934 if markstack:
1935 markpos = markstack.pop()
1936 if markpos is None:
1937 markmsg = "(MARK at unknown opcode offset)"
1938 else:
1939 markmsg = "(MARK at %d)" % markpos
1940 # Pop everything at and after the topmost markobject.
1941 while stack[-1] is not markobject:
1942 stack.pop()
1943 stack.pop()
Tim Peters43277d62003-01-30 15:02:12 +00001944 # Stop later code from popping too much.
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001945 try:
Tim Peters43277d62003-01-30 15:02:12 +00001946 numtopop = before.index(markobject)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001947 except ValueError:
1948 assert opcode.name == "POP"
Tim Peters43277d62003-01-30 15:02:12 +00001949 numtopop = 0
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001950 else:
1951 errormsg = markmsg = "no MARK exists on stack"
1952
1953 # Check for correct memo usage.
1954 if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"):
Tim Peters43277d62003-01-30 15:02:12 +00001955 assert arg is not None
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001956 if arg in memo:
1957 errormsg = "memo key %r already defined" % arg
1958 elif not stack:
1959 errormsg = "stack is empty -- can't store into memo"
1960 elif stack[-1] is markobject:
1961 errormsg = "can't store markobject in the memo"
1962 else:
1963 memo[arg] = stack[-1]
1964
1965 elif opcode.name in ("GET", "BINGET", "LONG_BINGET"):
1966 if arg in memo:
1967 assert len(after) == 1
1968 after = [memo[arg]] # for better stack emulation
1969 else:
1970 errormsg = "memo key %r has never been stored into" % arg
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001971
1972 if arg is not None or markmsg:
1973 # make a mild effort to align arguments
1974 line += ' ' * (10 - len(opcode.name))
1975 if arg is not None:
1976 line += ' ' + repr(arg)
1977 if markmsg:
1978 line += ' ' + markmsg
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001979 print(line, file=out)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001980
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001981 if errormsg:
1982 # Note that we delayed complaining until the offending opcode
1983 # was printed.
1984 raise ValueError(errormsg)
1985
1986 # Emulate the stack effects.
Tim Peters43277d62003-01-30 15:02:12 +00001987 if len(stack) < numtopop:
1988 raise ValueError("tries to pop %d items from stack with "
1989 "only %d items" % (numtopop, len(stack)))
1990 if numtopop:
1991 del stack[-numtopop:]
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001992 if markobject in after:
Tim Peters43277d62003-01-30 15:02:12 +00001993 assert markobject not in before
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001994 markstack.append(pos)
1995
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001996 stack.extend(after)
1997
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001998 print("highest protocol among opcodes =", maxproto, file=out)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001999 if stack:
2000 raise ValueError("stack not empty after STOP: %r" % stack)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002001
Tim Peters90718a42005-02-15 16:22:34 +00002002# For use in the doctest, simply as an example of a class to pickle.
2003class _Example:
2004 def __init__(self, value):
2005 self.value = value
2006
Guido van Rossum03e35322003-01-28 15:37:13 +00002007_dis_test = r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002008>>> import pickle
Guido van Rossum98297ee2007-11-06 21:34:58 +00002009>>> x = [1, 2, (3, 4), {bytes(b'abc'): "def"}]
Guido van Rossum57028352003-01-28 15:09:10 +00002010>>> pkl = pickle.dumps(x, 0)
2011>>> dis(pkl)
Tim Petersd0f7c862003-01-28 15:27:57 +00002012 0: ( MARK
2013 1: l LIST (MARK at 0)
2014 2: p PUT 0
Guido van Rossumf4100002007-01-15 00:21:46 +00002015 5: L LONG 1
Tim Petersd0f7c862003-01-28 15:27:57 +00002016 8: a APPEND
Guido van Rossumf4100002007-01-15 00:21:46 +00002017 9: L LONG 2
Tim Petersd0f7c862003-01-28 15:27:57 +00002018 12: a APPEND
2019 13: ( MARK
Guido van Rossumf4100002007-01-15 00:21:46 +00002020 14: L LONG 3
2021 17: L LONG 4
Tim Petersd0f7c862003-01-28 15:27:57 +00002022 20: t TUPLE (MARK at 13)
2023 21: p PUT 1
2024 24: a APPEND
2025 25: ( MARK
2026 26: d DICT (MARK at 25)
2027 27: p PUT 2
2028 30: S STRING 'abc'
2029 37: p PUT 3
Guido van Rossumcfe5f202007-05-08 21:26:54 +00002030 40: V UNICODE 'def'
Tim Petersd0f7c862003-01-28 15:27:57 +00002031 45: p PUT 4
2032 48: s SETITEM
2033 49: a APPEND
2034 50: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002035highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002036
2037Try again with a "binary" pickle.
2038
Guido van Rossum57028352003-01-28 15:09:10 +00002039>>> pkl = pickle.dumps(x, 1)
2040>>> dis(pkl)
Tim Petersd0f7c862003-01-28 15:27:57 +00002041 0: ] EMPTY_LIST
2042 1: q BINPUT 0
2043 3: ( MARK
2044 4: K BININT1 1
2045 6: K BININT1 2
2046 8: ( MARK
2047 9: K BININT1 3
2048 11: K BININT1 4
2049 13: t TUPLE (MARK at 8)
2050 14: q BINPUT 1
2051 16: } EMPTY_DICT
2052 17: q BINPUT 2
2053 19: U SHORT_BINSTRING 'abc'
2054 24: q BINPUT 3
Guido van Rossumcfe5f202007-05-08 21:26:54 +00002055 26: X BINUNICODE 'def'
Tim Petersd0f7c862003-01-28 15:27:57 +00002056 34: q BINPUT 4
2057 36: s SETITEM
2058 37: e APPENDS (MARK at 3)
2059 38: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002060highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002061
2062Exercise the INST/OBJ/BUILD family.
2063
2064>>> import random
Guido van Rossum4f7ac2e2007-02-26 15:59:50 +00002065>>> dis(pickle.dumps(random.getrandbits, 0))
2066 0: c GLOBAL 'random getrandbits'
2067 20: p PUT 0
2068 23: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002069highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002070
Tim Peters90718a42005-02-15 16:22:34 +00002071>>> from pickletools import _Example
2072>>> x = [_Example(42)] * 2
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002073>>> dis(pickle.dumps(x, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002074 0: ( MARK
2075 1: l LIST (MARK at 0)
2076 2: p PUT 0
Guido van Rossum65810fe2006-05-26 19:12:38 +00002077 5: c GLOBAL 'copy_reg _reconstructor'
2078 30: p PUT 1
2079 33: ( MARK
2080 34: c GLOBAL 'pickletools _Example'
2081 56: p PUT 2
Georg Brandl1a3284e2007-12-02 09:40:06 +00002082 59: c GLOBAL 'builtins object'
2083 76: p PUT 3
2084 79: N NONE
2085 80: t TUPLE (MARK at 33)
2086 81: p PUT 4
2087 84: R REDUCE
2088 85: p PUT 5
2089 88: ( MARK
2090 89: d DICT (MARK at 88)
2091 90: p PUT 6
2092 93: V UNICODE 'value'
2093 100: p PUT 7
2094 103: L LONG 42
2095 107: s SETITEM
2096 108: b BUILD
2097 109: a APPEND
2098 110: g GET 5
2099 113: a APPEND
2100 114: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002101highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002102
2103>>> dis(pickle.dumps(x, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002104 0: ] EMPTY_LIST
2105 1: q BINPUT 0
2106 3: ( MARK
Guido van Rossum65810fe2006-05-26 19:12:38 +00002107 4: c GLOBAL 'copy_reg _reconstructor'
2108 29: q BINPUT 1
2109 31: ( MARK
2110 32: c GLOBAL 'pickletools _Example'
2111 54: q BINPUT 2
Georg Brandl1a3284e2007-12-02 09:40:06 +00002112 56: c GLOBAL 'builtins object'
2113 73: q BINPUT 3
2114 75: N NONE
2115 76: t TUPLE (MARK at 31)
2116 77: q BINPUT 4
2117 79: R REDUCE
2118 80: q BINPUT 5
2119 82: } EMPTY_DICT
2120 83: q BINPUT 6
2121 85: X BINUNICODE 'value'
2122 95: q BINPUT 7
2123 97: K BININT1 42
2124 99: s SETITEM
2125 100: b BUILD
2126 101: h BINGET 5
2127 103: e APPENDS (MARK at 3)
2128 104: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002129highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002130
2131Try "the canonical" recursive-object test.
2132
2133>>> L = []
2134>>> T = L,
2135>>> L.append(T)
2136>>> L[0] is T
2137True
2138>>> T[0] is L
2139True
2140>>> L[0][0] is L
2141True
2142>>> T[0][0] is T
2143True
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002144>>> dis(pickle.dumps(L, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002145 0: ( MARK
2146 1: l LIST (MARK at 0)
2147 2: p PUT 0
2148 5: ( MARK
2149 6: g GET 0
2150 9: t TUPLE (MARK at 5)
2151 10: p PUT 1
2152 13: a APPEND
2153 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002154highest protocol among opcodes = 0
2155
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002156>>> dis(pickle.dumps(L, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002157 0: ] EMPTY_LIST
2158 1: q BINPUT 0
2159 3: ( MARK
2160 4: h BINGET 0
2161 6: t TUPLE (MARK at 3)
2162 7: q BINPUT 1
2163 9: a APPEND
2164 10: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002165highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002166
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002167Note that, in the protocol 0 pickle of the recursive tuple, the disassembler
2168has to emulate the stack in order to realize that the POP opcode at 16 gets
2169rid of the MARK at 0.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002170
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002171>>> dis(pickle.dumps(T, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002172 0: ( MARK
2173 1: ( MARK
2174 2: l LIST (MARK at 1)
2175 3: p PUT 0
2176 6: ( MARK
2177 7: g GET 0
2178 10: t TUPLE (MARK at 6)
2179 11: p PUT 1
2180 14: a APPEND
2181 15: 0 POP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002182 16: 0 POP (MARK at 0)
2183 17: g GET 1
2184 20: . STOP
2185highest protocol among opcodes = 0
2186
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002187>>> dis(pickle.dumps(T, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002188 0: ( MARK
2189 1: ] EMPTY_LIST
2190 2: q BINPUT 0
2191 4: ( MARK
2192 5: h BINGET 0
2193 7: t TUPLE (MARK at 4)
2194 8: q BINPUT 1
2195 10: a APPEND
2196 11: 1 POP_MARK (MARK at 0)
2197 12: h BINGET 1
2198 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002199highest protocol among opcodes = 1
Tim Petersd0f7c862003-01-28 15:27:57 +00002200
2201Try protocol 2.
2202
2203>>> dis(pickle.dumps(L, 2))
2204 0: \x80 PROTO 2
2205 2: ] EMPTY_LIST
2206 3: q BINPUT 0
2207 5: h BINGET 0
2208 7: \x85 TUPLE1
2209 8: q BINPUT 1
2210 10: a APPEND
2211 11: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002212highest protocol among opcodes = 2
Tim Petersd0f7c862003-01-28 15:27:57 +00002213
2214>>> dis(pickle.dumps(T, 2))
2215 0: \x80 PROTO 2
2216 2: ] EMPTY_LIST
2217 3: q BINPUT 0
2218 5: h BINGET 0
2219 7: \x85 TUPLE1
2220 8: q BINPUT 1
2221 10: a APPEND
2222 11: 0 POP
2223 12: h BINGET 1
2224 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002225highest protocol among opcodes = 2
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002226"""
2227
Tim Peters62235e72003-02-05 19:55:53 +00002228_memo_test = r"""
2229>>> import pickle
Guido van Rossumcfe5f202007-05-08 21:26:54 +00002230>>> import io
2231>>> f = io.BytesIO()
Tim Peters62235e72003-02-05 19:55:53 +00002232>>> p = pickle.Pickler(f, 2)
2233>>> x = [1, 2, 3]
2234>>> p.dump(x)
2235>>> p.dump(x)
2236>>> f.seek(0)
Guido van Rossumcfe5f202007-05-08 21:26:54 +000022370
Tim Peters62235e72003-02-05 19:55:53 +00002238>>> memo = {}
2239>>> dis(f, memo=memo)
2240 0: \x80 PROTO 2
2241 2: ] EMPTY_LIST
2242 3: q BINPUT 0
2243 5: ( MARK
2244 6: K BININT1 1
2245 8: K BININT1 2
2246 10: K BININT1 3
2247 12: e APPENDS (MARK at 5)
2248 13: . STOP
2249highest protocol among opcodes = 2
2250>>> dis(f, memo=memo)
2251 14: \x80 PROTO 2
2252 16: h BINGET 0
2253 18: . STOP
2254highest protocol among opcodes = 2
2255"""
2256
Guido van Rossum57028352003-01-28 15:09:10 +00002257__test__ = {'disassembler_test': _dis_test,
Tim Peters62235e72003-02-05 19:55:53 +00002258 'disassembler_memo_test': _memo_test,
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002259 }
2260
2261def _test():
2262 import doctest
2263 return doctest.testmod()
2264
2265if __name__ == "__main__":
2266 _test()