blob: c5c45eb657d848fb5d991b956821a417a5db4feb [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
Tim Peters90cf2122004-11-06 23:45:48 +000013__all__ = ['dis',
14 'genops',
15 ]
16
Tim Peters8ecfc8e2003-01-27 18:51:48 +000017# Other ideas:
18#
19# - A pickle verifier: read a pickle and check it exhaustively for
Tim Petersc1c2b3e2003-01-29 20:12:21 +000020# well-formedness. dis() does a lot of this already.
Tim Peters8ecfc8e2003-01-27 18:51:48 +000021#
22# - A protocol identifier: examine a pickle and return its protocol number
23# (== the highest .proto attr value among all the opcodes in the pickle).
Tim Petersc1c2b3e2003-01-29 20:12:21 +000024# dis() already prints this info at the end.
Tim Peters8ecfc8e2003-01-27 18:51:48 +000025#
26# - A pickle optimizer: for example, tuple-building code is sometimes more
27# elaborate than necessary, catering for the possibility that the tuple
28# is recursive. Or lots of times a PUT is generated that's never accessed
29# by a later GET.
30
31
32"""
33"A pickle" is a program for a virtual pickle machine (PM, but more accurately
34called an unpickling machine). It's a sequence of opcodes, interpreted by the
35PM, building an arbitrarily complex Python object.
36
37For the most part, the PM is very simple: there are no looping, testing, or
38conditional instructions, no arithmetic and no function calls. Opcodes are
39executed once each, from first to last, until a STOP opcode is reached.
40
41The PM has two data areas, "the stack" and "the memo".
42
43Many opcodes push Python objects onto the stack; e.g., INT pushes a Python
44integer object on the stack, whose value is gotten from a decimal string
45literal immediately following the INT opcode in the pickle bytestream. Other
46opcodes take Python objects off the stack. The result of unpickling is
47whatever object is left on the stack when the final STOP opcode is executed.
48
49The memo is simply an array of objects, or it can be implemented as a dict
50mapping little integers to objects. The memo serves as the PM's "long term
51memory", and the little integers indexing the memo are akin to variable
52names. Some opcodes pop a stack object into the memo at a given index,
53and others push a memo object at a given index onto the stack again.
54
55At heart, that's all the PM has. Subtleties arise for these reasons:
56
57+ Object identity. Objects can be arbitrarily complex, and subobjects
58 may be shared (for example, the list [a, a] refers to the same object a
59 twice). It can be vital that unpickling recreate an isomorphic object
60 graph, faithfully reproducing sharing.
61
62+ Recursive objects. For example, after "L = []; L.append(L)", L is a
63 list, and L[0] is the same list. This is related to the object identity
64 point, and some sequences of pickle opcodes are subtle in order to
65 get the right result in all cases.
66
67+ Things pickle doesn't know everything about. Examples of things pickle
68 does know everything about are Python's builtin scalar and container
69 types, like ints and tuples. They generally have opcodes dedicated to
70 them. For things like module references and instances of user-defined
71 classes, pickle's knowledge is limited. Historically, many enhancements
72 have been made to the pickle protocol in order to do a better (faster,
73 and/or more compact) job on those.
74
75+ Backward compatibility and micro-optimization. As explained below,
76 pickle opcodes never go away, not even when better ways to do a thing
77 get invented. The repertoire of the PM just keeps growing over time.
Tim Petersfdc03462003-01-28 04:56:33 +000078 For example, protocol 0 had two opcodes for building Python integers (INT
79 and LONG), protocol 1 added three more for more-efficient pickling of short
80 integers, and protocol 2 added two more for more-efficient pickling of
81 long integers (before protocol 2, the only ways to pickle a Python long
82 took time quadratic in the number of digits, for both pickling and
83 unpickling). "Opcode bloat" isn't so much a subtlety as a source of
Tim Peters8ecfc8e2003-01-27 18:51:48 +000084 wearying complication.
85
86
87Pickle protocols:
88
89For compatibility, the meaning of a pickle opcode never changes. Instead new
90pickle opcodes get added, and each version's unpickler can handle all the
91pickle opcodes in all protocol versions to date. So old pickles continue to
92be readable forever. The pickler can generally be told to restrict itself to
93the subset of opcodes available under previous protocol versions too, so that
94users can create pickles under the current version readable by older
95versions. However, a pickle does not contain its version number embedded
96within it. If an older unpickler tries to read a pickle using a later
97protocol, the result is most likely an exception due to seeing an unknown (in
98the older unpickler) opcode.
99
100The original pickle used what's now called "protocol 0", and what was called
101"text mode" before Python 2.3. The entire pickle bytestream is made up of
102printable 7-bit ASCII characters, plus the newline character, in protocol 0.
Tim Petersfdc03462003-01-28 04:56:33 +0000103That's why it was called text mode. Protocol 0 is small and elegant, but
104sometimes painfully inefficient.
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000105
106The second major set of additions is now called "protocol 1", and was called
107"binary mode" before Python 2.3. This added many opcodes with arguments
108consisting of arbitrary bytes, including NUL bytes and unprintable "high bit"
109bytes. Binary mode pickles can be substantially smaller than equivalent
110text mode pickles, and sometimes faster too; e.g., BININT represents a 4-byte
111int as 4 bytes following the opcode, which is cheaper to unpickle than the
Tim Petersfdc03462003-01-28 04:56:33 +0000112(perhaps) 11-character decimal string attached to INT. Protocol 1 also added
113a number of opcodes that operate on many stack elements at once (like APPENDS
Tim Peters81098ac2003-01-28 05:12:08 +0000114and SETITEMS), and "shortcut" opcodes (like EMPTY_DICT and EMPTY_TUPLE).
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000115
116The third major set of additions came in Python 2.3, and is called "protocol
Tim Petersfdc03462003-01-28 04:56:33 +00001172". This added:
118
119- A better way to pickle instances of new-style classes (NEWOBJ).
120
121- A way for a pickle to identify its protocol (PROTO).
122
123- Time- and space- efficient pickling of long ints (LONG{1,4}).
124
125- Shortcuts for small tuples (TUPLE{1,2,3}}.
126
127- Dedicated opcodes for bools (NEWTRUE, NEWFALSE).
128
129- The "extension registry", a vector of popular objects that can be pushed
130 efficiently by index (EXT{1,2,4}). This is akin to the memo and GET, but
131 the registry contents are predefined (there's nothing akin to the memo's
132 PUT).
Guido van Rossumecb11042003-01-29 06:24:30 +0000133
Skip Montanaro54455942003-01-29 15:41:33 +0000134Another independent change with Python 2.3 is the abandonment of any
135pretense that it might be safe to load pickles received from untrusted
Guido van Rossumecb11042003-01-29 06:24:30 +0000136parties -- no sufficient security analysis has been done to guarantee
Skip Montanaro54455942003-01-29 15:41:33 +0000137this and there isn't a use case that warrants the expense of such an
Guido van Rossumecb11042003-01-29 06:24:30 +0000138analysis.
139
140To this end, all tests for __safe_for_unpickling__ or for
141copy_reg.safe_constructors are removed from the unpickling code.
142References to these variables in the descriptions below are to be seen
143as describing unpickling in Python 2.2 and before.
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000144"""
145
146# Meta-rule: Descriptions are stored in instances of descriptor objects,
147# with plain constructors. No meta-language is defined from which
148# descriptors could be constructed. If you want, e.g., XML, write a little
149# program to generate XML from the objects.
150
151##############################################################################
152# Some pickle opcodes have an argument, following the opcode in the
153# bytestream. An argument is of a specific type, described by an instance
154# of ArgumentDescriptor. These are not to be confused with arguments taken
155# off the stack -- ArgumentDescriptor applies only to arguments embedded in
156# the opcode stream, immediately following an opcode.
157
158# Represents the number of bytes consumed by an argument delimited by the
159# next newline character.
160UP_TO_NEWLINE = -1
161
162# Represents the number of bytes consumed by a two-argument opcode where
163# the first argument gives the number of bytes in the second argument.
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000164TAKEN_FROM_ARGUMENT1 = -2 # num bytes is 1-byte unsigned int
165TAKEN_FROM_ARGUMENT4 = -3 # num bytes is 4-byte signed little-endian int
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000166
167class ArgumentDescriptor(object):
168 __slots__ = (
169 # name of descriptor record, also a module global name; a string
170 'name',
171
172 # length of argument, in bytes; an int; UP_TO_NEWLINE and
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000173 # TAKEN_FROM_ARGUMENT{1,4} are negative values for variable-length
174 # cases
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000175 'n',
176
177 # a function taking a file-like object, reading this kind of argument
178 # from the object at the current position, advancing the current
179 # position by n bytes, and returning the value of the argument
180 'reader',
181
182 # human-readable docs for this arg descriptor; a string
183 'doc',
184 )
185
186 def __init__(self, name, n, reader, doc):
187 assert isinstance(name, str)
188 self.name = name
189
190 assert isinstance(n, int) and (n >= 0 or
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000191 n in (UP_TO_NEWLINE,
192 TAKEN_FROM_ARGUMENT1,
193 TAKEN_FROM_ARGUMENT4))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000194 self.n = n
195
196 self.reader = reader
197
198 assert isinstance(doc, str)
199 self.doc = doc
200
201from struct import unpack as _unpack
202
203def read_uint1(f):
Tim Peters55762f52003-01-28 16:01:25 +0000204 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000205 >>> import io
206 >>> read_uint1(io.BytesIO(b'\xff'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000207 255
208 """
209
210 data = f.read(1)
211 if data:
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000212 return data[0]
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000213 raise ValueError("not enough data in stream to read uint1")
214
215uint1 = ArgumentDescriptor(
216 name='uint1',
217 n=1,
218 reader=read_uint1,
219 doc="One-byte unsigned integer.")
220
221
222def read_uint2(f):
Tim Peters55762f52003-01-28 16:01:25 +0000223 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000224 >>> import io
225 >>> read_uint2(io.BytesIO(b'\xff\x00'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000226 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000227 >>> read_uint2(io.BytesIO(b'\xff\xff'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000228 65535
229 """
230
231 data = f.read(2)
232 if len(data) == 2:
233 return _unpack("<H", data)[0]
234 raise ValueError("not enough data in stream to read uint2")
235
236uint2 = ArgumentDescriptor(
237 name='uint2',
238 n=2,
239 reader=read_uint2,
240 doc="Two-byte unsigned integer, little-endian.")
241
242
243def read_int4(f):
Tim Peters55762f52003-01-28 16:01:25 +0000244 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000245 >>> import io
246 >>> read_int4(io.BytesIO(b'\xff\x00\x00\x00'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000247 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000248 >>> read_int4(io.BytesIO(b'\x00\x00\x00\x80')) == -(2**31)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000249 True
250 """
251
252 data = f.read(4)
253 if len(data) == 4:
254 return _unpack("<i", data)[0]
255 raise ValueError("not enough data in stream to read int4")
256
257int4 = ArgumentDescriptor(
258 name='int4',
259 n=4,
260 reader=read_int4,
261 doc="Four-byte signed integer, little-endian, 2's complement.")
262
263
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000264def readline(f):
265 """Read a line from a binary file."""
266 # XXX Slow but at least correct
267 b = bytes()
268 while True:
269 c = f.read(1)
270 if not c:
271 break
272 b += c
273 if c == b'\n':
274 break
275 return b
276
277
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000278def read_stringnl(f, decode=True, stripquotes=True):
Tim Peters55762f52003-01-28 16:01:25 +0000279 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000280 >>> import io
281 >>> read_stringnl(io.BytesIO(b"'abcd'\nefg\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000282 'abcd'
283
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000284 >>> read_stringnl(io.BytesIO(b"\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000285 Traceback (most recent call last):
286 ...
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000287 ValueError: no string quotes around b''
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000288
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000289 >>> read_stringnl(io.BytesIO(b"\n"), stripquotes=False)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000290 ''
291
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000292 >>> read_stringnl(io.BytesIO(b"''\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000293 ''
294
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000295 >>> read_stringnl(io.BytesIO(b'"abcd"'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000296 Traceback (most recent call last):
297 ...
298 ValueError: no newline found when trying to read stringnl
299
300 Embedded escapes are undone in the result.
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000301 >>> read_stringnl(io.BytesIO(br"'a\n\\b\x00c\td'" + b"\n'e'"))
Tim Peters55762f52003-01-28 16:01:25 +0000302 'a\n\\b\x00c\td'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000303 """
304
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000305 data = readline(f)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000306 if not data.endswith('\n'):
307 raise ValueError("no newline found when trying to read stringnl")
308 data = data[:-1] # lose the newline
309
310 if stripquotes:
311 for q in "'\"":
312 if data.startswith(q):
313 if not data.endswith(q):
314 raise ValueError("strinq quote %r not found at both "
315 "ends of %r" % (q, data))
316 data = data[1:-1]
317 break
318 else:
319 raise ValueError("no string quotes around %r" % data)
320
321 # I'm not sure when 'string_escape' was added to the std codecs; it's
322 # crazy not to use it if it's there.
323 if decode:
324 data = data.decode('string_escape')
325 return data
326
327stringnl = ArgumentDescriptor(
328 name='stringnl',
329 n=UP_TO_NEWLINE,
330 reader=read_stringnl,
331 doc="""A newline-terminated string.
332
333 This is a repr-style string, with embedded escapes, and
334 bracketing quotes.
335 """)
336
337def read_stringnl_noescape(f):
338 return read_stringnl(f, decode=False, stripquotes=False)
339
340stringnl_noescape = ArgumentDescriptor(
341 name='stringnl_noescape',
342 n=UP_TO_NEWLINE,
343 reader=read_stringnl_noescape,
344 doc="""A newline-terminated string.
345
346 This is a str-style string, without embedded escapes,
347 or bracketing quotes. It should consist solely of
348 printable ASCII characters.
349 """)
350
351def read_stringnl_noescape_pair(f):
Tim Peters55762f52003-01-28 16:01:25 +0000352 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000353 >>> import io
354 >>> read_stringnl_noescape_pair(io.BytesIO(b"Queue\nEmpty\njunk"))
Tim Petersd916cf42003-01-27 19:01:47 +0000355 'Queue Empty'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000356 """
357
Tim Petersd916cf42003-01-27 19:01:47 +0000358 return "%s %s" % (read_stringnl_noescape(f), read_stringnl_noescape(f))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000359
360stringnl_noescape_pair = ArgumentDescriptor(
361 name='stringnl_noescape_pair',
362 n=UP_TO_NEWLINE,
363 reader=read_stringnl_noescape_pair,
364 doc="""A pair of newline-terminated strings.
365
366 These are str-style strings, without embedded
367 escapes, or bracketing quotes. They should
368 consist solely of printable ASCII characters.
369 The pair is returned as a single string, with
Tim Petersd916cf42003-01-27 19:01:47 +0000370 a single blank separating the two strings.
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000371 """)
372
373def read_string4(f):
Tim Peters55762f52003-01-28 16:01:25 +0000374 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000375 >>> import io
376 >>> read_string4(io.BytesIO(b"\x00\x00\x00\x00abc"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000377 ''
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000378 >>> read_string4(io.BytesIO(b"\x03\x00\x00\x00abcdef"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000379 'abc'
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000380 >>> read_string4(io.BytesIO(b"\x00\x00\x00\x03abcdef"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000381 Traceback (most recent call last):
382 ...
383 ValueError: expected 50331648 bytes in a string4, but only 6 remain
384 """
385
386 n = read_int4(f)
387 if n < 0:
388 raise ValueError("string4 byte count < 0: %d" % n)
389 data = f.read(n)
390 if len(data) == n:
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000391 return data.decode("latin-1")
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000392 raise ValueError("expected %d bytes in a string4, but only %d remain" %
393 (n, len(data)))
394
395string4 = ArgumentDescriptor(
396 name="string4",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000397 n=TAKEN_FROM_ARGUMENT4,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000398 reader=read_string4,
399 doc="""A counted string.
400
401 The first argument is a 4-byte little-endian signed int giving
402 the number of bytes in the string, and the second argument is
403 that many bytes.
404 """)
405
406
407def read_string1(f):
Tim Peters55762f52003-01-28 16:01:25 +0000408 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000409 >>> import io
410 >>> read_string1(io.BytesIO(b"\x00"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000411 ''
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000412 >>> read_string1(io.BytesIO(b"\x03abcdef"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000413 'abc'
414 """
415
416 n = read_uint1(f)
417 assert n >= 0
418 data = f.read(n)
419 if len(data) == n:
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000420 return data.decode("latin-1")
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000421 raise ValueError("expected %d bytes in a string1, but only %d remain" %
422 (n, len(data)))
423
424string1 = ArgumentDescriptor(
425 name="string1",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000426 n=TAKEN_FROM_ARGUMENT1,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000427 reader=read_string1,
428 doc="""A counted string.
429
430 The first argument is a 1-byte unsigned int giving the number
431 of bytes in the string, and the second argument is that many
432 bytes.
433 """)
434
435
436def read_unicodestringnl(f):
Tim Peters55762f52003-01-28 16:01:25 +0000437 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000438 >>> import io
439 >>> read_unicodestringnl(io.BytesIO(b"abc\\uabcd\njunk")) == 'abc\uabcd'
440 True
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000441 """
442
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000443 data = readline(f)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000444 if not data.endswith('\n'):
445 raise ValueError("no newline found when trying to read "
446 "unicodestringnl")
447 data = data[:-1] # lose the newline
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000448 return str(data, 'raw-unicode-escape')
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000449
450unicodestringnl = ArgumentDescriptor(
451 name='unicodestringnl',
452 n=UP_TO_NEWLINE,
453 reader=read_unicodestringnl,
454 doc="""A newline-terminated Unicode string.
455
456 This is raw-unicode-escape encoded, so consists of
457 printable ASCII characters, and may contain embedded
458 escape sequences.
459 """)
460
461def read_unicodestring4(f):
Tim Peters55762f52003-01-28 16:01:25 +0000462 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000463 >>> import io
464 >>> s = 'abcd\uabcd'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000465 >>> enc = s.encode('utf-8')
466 >>> enc
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000467 b'abcd\xea\xaf\x8d'
468 >>> n = bytes([len(enc), 0, 0, 0]) # little-endian 4-byte length
469 >>> t = read_unicodestring4(io.BytesIO(n + enc + b'junk'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000470 >>> s == t
471 True
472
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000473 >>> read_unicodestring4(io.BytesIO(n + enc[:-1]))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000474 Traceback (most recent call last):
475 ...
476 ValueError: expected 7 bytes in a unicodestring4, but only 6 remain
477 """
478
479 n = read_int4(f)
480 if n < 0:
481 raise ValueError("unicodestring4 byte count < 0: %d" % n)
482 data = f.read(n)
483 if len(data) == n:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000484 return str(data, 'utf-8')
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000485 raise ValueError("expected %d bytes in a unicodestring4, but only %d "
486 "remain" % (n, len(data)))
487
488unicodestring4 = ArgumentDescriptor(
489 name="unicodestring4",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000490 n=TAKEN_FROM_ARGUMENT4,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000491 reader=read_unicodestring4,
492 doc="""A counted Unicode string.
493
494 The first argument is a 4-byte little-endian signed int
495 giving the number of bytes in the string, and the second
496 argument-- the UTF-8 encoding of the Unicode string --
497 contains that many bytes.
498 """)
499
500
501def read_decimalnl_short(f):
Tim Peters55762f52003-01-28 16:01:25 +0000502 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000503 >>> import io
504 >>> read_decimalnl_short(io.BytesIO(b"1234\n56"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000505 1234
506
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000507 >>> read_decimalnl_short(io.BytesIO(b"1234L\n56"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000508 Traceback (most recent call last):
509 ...
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000510 ValueError: trailing 'L' not allowed in b'1234L'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000511 """
512
513 s = read_stringnl(f, decode=False, stripquotes=False)
514 if s.endswith("L"):
515 raise ValueError("trailing 'L' not allowed in %r" % s)
516
517 # It's not necessarily true that the result fits in a Python short int:
518 # the pickle may have been written on a 64-bit box. There's also a hack
519 # for True and False here.
520 if s == "00":
521 return False
522 elif s == "01":
523 return True
524
525 try:
526 return int(s)
527 except OverflowError:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000528 return int(s)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000529
530def read_decimalnl_long(f):
Tim Peters55762f52003-01-28 16:01:25 +0000531 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000532 >>> import io
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000533
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000534 >>> read_decimalnl_long(io.BytesIO(b"1234L\n56"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000535 1234
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000536
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000537 >>> read_decimalnl_long(io.BytesIO(b"123456789012345678901234L\n6"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000538 123456789012345678901234
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000539 """
540
541 s = read_stringnl(f, decode=False, stripquotes=False)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000542 return int(s)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000543
544
545decimalnl_short = ArgumentDescriptor(
546 name='decimalnl_short',
547 n=UP_TO_NEWLINE,
548 reader=read_decimalnl_short,
549 doc="""A newline-terminated decimal integer literal.
550
551 This never has a trailing 'L', and the integer fit
552 in a short Python int on the box where the pickle
553 was written -- but there's no guarantee it will fit
554 in a short Python int on the box where the pickle
555 is read.
556 """)
557
558decimalnl_long = ArgumentDescriptor(
559 name='decimalnl_long',
560 n=UP_TO_NEWLINE,
561 reader=read_decimalnl_long,
562 doc="""A newline-terminated decimal integer literal.
563
564 This has a trailing 'L', and can represent integers
565 of any size.
566 """)
567
568
569def read_floatnl(f):
Tim Peters55762f52003-01-28 16:01:25 +0000570 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000571 >>> import io
572 >>> read_floatnl(io.BytesIO(b"-1.25\n6"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000573 -1.25
574 """
575 s = read_stringnl(f, decode=False, stripquotes=False)
576 return float(s)
577
578floatnl = ArgumentDescriptor(
579 name='floatnl',
580 n=UP_TO_NEWLINE,
581 reader=read_floatnl,
582 doc="""A newline-terminated decimal floating literal.
583
584 In general this requires 17 significant digits for roundtrip
585 identity, and pickling then unpickling infinities, NaNs, and
586 minus zero doesn't work across boxes, or on some boxes even
587 on itself (e.g., Windows can't read the strings it produces
588 for infinities or NaNs).
589 """)
590
591def read_float8(f):
Tim Peters55762f52003-01-28 16:01:25 +0000592 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000593 >>> import io, struct
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000594 >>> raw = struct.pack(">d", -1.25)
595 >>> raw
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000596 b'\xbf\xf4\x00\x00\x00\x00\x00\x00'
597 >>> read_float8(io.BytesIO(raw + b"\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000598 -1.25
599 """
600
601 data = f.read(8)
602 if len(data) == 8:
603 return _unpack(">d", data)[0]
604 raise ValueError("not enough data in stream to read float8")
605
606
607float8 = ArgumentDescriptor(
608 name='float8',
609 n=8,
610 reader=read_float8,
611 doc="""An 8-byte binary representation of a float, big-endian.
612
613 The format is unique to Python, and shared with the struct
614 module (format string '>d') "in theory" (the struct and cPickle
615 implementations don't share the code -- they should). It's
616 strongly related to the IEEE-754 double format, and, in normal
617 cases, is in fact identical to the big-endian 754 double format.
618 On other boxes the dynamic range is limited to that of a 754
619 double, and "add a half and chop" rounding is used to reduce
620 the precision to 53 bits. However, even on a 754 box,
621 infinities, NaNs, and minus zero may not be handled correctly
622 (may not survive roundtrip pickling intact).
623 """)
624
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000625# Protocol 2 formats
626
Tim Petersc0c12b52003-01-29 00:56:17 +0000627from pickle import decode_long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000628
629def read_long1(f):
630 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000631 >>> import io
632 >>> read_long1(io.BytesIO(b"\x00"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000633 0
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000634 >>> read_long1(io.BytesIO(b"\x02\xff\x00"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000635 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000636 >>> read_long1(io.BytesIO(b"\x02\xff\x7f"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000637 32767
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000638 >>> read_long1(io.BytesIO(b"\x02\x00\xff"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000639 -256
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000640 >>> read_long1(io.BytesIO(b"\x02\x00\x80"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000641 -32768
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000642 """
643
644 n = read_uint1(f)
645 data = f.read(n)
646 if len(data) != n:
647 raise ValueError("not enough data in stream to read long1")
648 return decode_long(data)
649
650long1 = ArgumentDescriptor(
651 name="long1",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000652 n=TAKEN_FROM_ARGUMENT1,
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000653 reader=read_long1,
654 doc="""A binary long, little-endian, using 1-byte size.
655
656 This first reads one byte as an unsigned size, then reads that
Tim Petersbdbe7412003-01-27 23:54:04 +0000657 many bytes and interprets them as a little-endian 2's-complement long.
Tim Peters4b23f2b2003-01-31 16:43:39 +0000658 If the size is 0, that's taken as a shortcut for the long 0L.
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000659 """)
660
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000661def read_long4(f):
662 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000663 >>> import io
664 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\xff\x00"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000665 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000666 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\xff\x7f"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000667 32767
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000668 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\x00\xff"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000669 -256
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000670 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\x00\x80"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000671 -32768
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000672 >>> read_long1(io.BytesIO(b"\x00\x00\x00\x00"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000673 0
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000674 """
675
676 n = read_int4(f)
677 if n < 0:
Neal Norwitz784a3f52003-01-28 00:20:41 +0000678 raise ValueError("long4 byte count < 0: %d" % n)
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000679 data = f.read(n)
680 if len(data) != n:
Neal Norwitz784a3f52003-01-28 00:20:41 +0000681 raise ValueError("not enough data in stream to read long4")
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000682 return decode_long(data)
683
684long4 = ArgumentDescriptor(
685 name="long4",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000686 n=TAKEN_FROM_ARGUMENT4,
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000687 reader=read_long4,
688 doc="""A binary representation of a long, little-endian.
689
690 This first reads four bytes as a signed size (but requires the
691 size to be >= 0), then reads that many bytes and interprets them
Tim Peters4b23f2b2003-01-31 16:43:39 +0000692 as a little-endian 2's-complement long. If the size is 0, that's taken
Guido van Rossume2a383d2007-01-15 16:59:06 +0000693 as a shortcut for the int 0, although LONG1 should really be used
Tim Peters4b23f2b2003-01-31 16:43:39 +0000694 then instead (and in any case where # of bytes < 256).
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000695 """)
696
697
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000698##############################################################################
699# Object descriptors. The stack used by the pickle machine holds objects,
700# and in the stack_before and stack_after attributes of OpcodeInfo
701# descriptors we need names to describe the various types of objects that can
702# appear on the stack.
703
704class StackObject(object):
705 __slots__ = (
706 # name of descriptor record, for info only
707 'name',
708
709 # type of object, or tuple of type objects (meaning the object can
710 # be of any type in the tuple)
711 'obtype',
712
713 # human-readable docs for this kind of stack object; a string
714 'doc',
715 )
716
717 def __init__(self, name, obtype, doc):
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000718 assert isinstance(name, basestring)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000719 self.name = name
720
721 assert isinstance(obtype, type) or isinstance(obtype, tuple)
722 if isinstance(obtype, tuple):
723 for contained in obtype:
724 assert isinstance(contained, type)
725 self.obtype = obtype
726
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000727 assert isinstance(doc, basestring)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000728 self.doc = doc
729
Tim Petersc1c2b3e2003-01-29 20:12:21 +0000730 def __repr__(self):
731 return self.name
732
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000733
734pyint = StackObject(
735 name='int',
736 obtype=int,
737 doc="A short (as opposed to long) Python integer object.")
738
739pylong = StackObject(
740 name='long',
Guido van Rossume2a383d2007-01-15 16:59:06 +0000741 obtype=int,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000742 doc="A long (as opposed to short) Python integer object.")
743
744pyinteger_or_bool = StackObject(
745 name='int_or_bool',
Guido van Rossume2a383d2007-01-15 16:59:06 +0000746 obtype=(int, int, bool),
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000747 doc="A Python integer object (short or long), or "
748 "a Python bool.")
749
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000750pybool = StackObject(
751 name='bool',
752 obtype=(bool,),
753 doc="A Python bool object.")
754
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000755pyfloat = StackObject(
756 name='float',
757 obtype=float,
758 doc="A Python float object.")
759
760pystring = StackObject(
761 name='str',
762 obtype=str,
763 doc="A Python string object.")
764
765pyunicode = StackObject(
766 name='unicode',
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000767 obtype=str,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000768 doc="A Python Unicode string object.")
769
770pynone = StackObject(
771 name="None",
772 obtype=type(None),
773 doc="The Python None object.")
774
775pytuple = StackObject(
776 name="tuple",
777 obtype=tuple,
778 doc="A Python tuple object.")
779
780pylist = StackObject(
781 name="list",
782 obtype=list,
783 doc="A Python list object.")
784
785pydict = StackObject(
786 name="dict",
787 obtype=dict,
788 doc="A Python dict object.")
789
790anyobject = StackObject(
791 name='any',
792 obtype=object,
793 doc="Any kind of object whatsoever.")
794
795markobject = StackObject(
796 name="mark",
797 obtype=StackObject,
798 doc="""'The mark' is a unique object.
799
800 Opcodes that operate on a variable number of objects
801 generally don't embed the count of objects in the opcode,
802 or pull it off the stack. Instead the MARK opcode is used
803 to push a special marker object on the stack, and then
804 some other opcodes grab all the objects from the top of
805 the stack down to (but not including) the topmost marker
806 object.
807 """)
808
809stackslice = StackObject(
810 name="stackslice",
811 obtype=StackObject,
812 doc="""An object representing a contiguous slice of the stack.
813
814 This is used in conjuction with markobject, to represent all
815 of the stack following the topmost markobject. For example,
816 the POP_MARK opcode changes the stack from
817
818 [..., markobject, stackslice]
819 to
820 [...]
821
822 No matter how many object are on the stack after the topmost
823 markobject, POP_MARK gets rid of all of them (including the
824 topmost markobject too).
825 """)
826
827##############################################################################
828# Descriptors for pickle opcodes.
829
830class OpcodeInfo(object):
831
832 __slots__ = (
833 # symbolic name of opcode; a string
834 'name',
835
836 # the code used in a bytestream to represent the opcode; a
837 # one-character string
838 'code',
839
840 # If the opcode has an argument embedded in the byte string, an
841 # instance of ArgumentDescriptor specifying its type. Note that
842 # arg.reader(s) can be used to read and decode the argument from
843 # the bytestream s, and arg.doc documents the format of the raw
844 # argument bytes. If the opcode doesn't have an argument embedded
845 # in the bytestream, arg should be None.
846 'arg',
847
848 # what the stack looks like before this opcode runs; a list
849 'stack_before',
850
851 # what the stack looks like after this opcode runs; a list
852 'stack_after',
853
854 # the protocol number in which this opcode was introduced; an int
855 'proto',
856
857 # human-readable docs for this opcode; a string
858 'doc',
859 )
860
861 def __init__(self, name, code, arg,
862 stack_before, stack_after, proto, doc):
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000863 assert isinstance(name, basestring)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000864 self.name = name
865
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000866 assert isinstance(code, basestring)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000867 assert len(code) == 1
868 self.code = code
869
870 assert arg is None or isinstance(arg, ArgumentDescriptor)
871 self.arg = arg
872
873 assert isinstance(stack_before, list)
874 for x in stack_before:
875 assert isinstance(x, StackObject)
876 self.stack_before = stack_before
877
878 assert isinstance(stack_after, list)
879 for x in stack_after:
880 assert isinstance(x, StackObject)
881 self.stack_after = stack_after
882
883 assert isinstance(proto, int) and 0 <= proto <= 2
884 self.proto = proto
885
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000886 assert isinstance(doc, basestring)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000887 self.doc = doc
888
889I = OpcodeInfo
890opcodes = [
891
892 # Ways to spell integers.
893
894 I(name='INT',
895 code='I',
896 arg=decimalnl_short,
897 stack_before=[],
898 stack_after=[pyinteger_or_bool],
899 proto=0,
900 doc="""Push an integer or bool.
901
902 The argument is a newline-terminated decimal literal string.
903
904 The intent may have been that this always fit in a short Python int,
905 but INT can be generated in pickles written on a 64-bit box that
906 require a Python long on a 32-bit box. The difference between this
907 and LONG then is that INT skips a trailing 'L', and produces a short
908 int whenever possible.
909
910 Another difference is due to that, when bool was introduced as a
911 distinct type in 2.3, builtin names True and False were also added to
912 2.2.2, mapping to ints 1 and 0. For compatibility in both directions,
913 True gets pickled as INT + "I01\\n", and False as INT + "I00\\n".
914 Leading zeroes are never produced for a genuine integer. The 2.3
915 (and later) unpicklers special-case these and return bool instead;
916 earlier unpicklers ignore the leading "0" and return the int.
917 """),
918
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000919 I(name='BININT',
920 code='J',
921 arg=int4,
922 stack_before=[],
923 stack_after=[pyint],
924 proto=1,
925 doc="""Push a four-byte signed integer.
926
927 This handles the full range of Python (short) integers on a 32-bit
928 box, directly as binary bytes (1 for the opcode and 4 for the integer).
929 If the integer is non-negative and fits in 1 or 2 bytes, pickling via
930 BININT1 or BININT2 saves space.
931 """),
932
933 I(name='BININT1',
934 code='K',
935 arg=uint1,
936 stack_before=[],
937 stack_after=[pyint],
938 proto=1,
939 doc="""Push a one-byte unsigned integer.
940
941 This is a space optimization for pickling very small non-negative ints,
942 in range(256).
943 """),
944
945 I(name='BININT2',
946 code='M',
947 arg=uint2,
948 stack_before=[],
949 stack_after=[pyint],
950 proto=1,
951 doc="""Push a two-byte unsigned integer.
952
953 This is a space optimization for pickling small positive ints, in
954 range(256, 2**16). Integers in range(256) can also be pickled via
955 BININT2, but BININT1 instead saves a byte.
956 """),
957
Tim Petersfdc03462003-01-28 04:56:33 +0000958 I(name='LONG',
959 code='L',
960 arg=decimalnl_long,
961 stack_before=[],
962 stack_after=[pylong],
963 proto=0,
964 doc="""Push a long integer.
965
966 The same as INT, except that the literal ends with 'L', and always
967 unpickles to a Python long. There doesn't seem a real purpose to the
968 trailing 'L'.
969
970 Note that LONG takes time quadratic in the number of digits when
971 unpickling (this is simply due to the nature of decimal->binary
972 conversion). Proto 2 added linear-time (in C; still quadratic-time
973 in Python) LONG1 and LONG4 opcodes.
974 """),
975
976 I(name="LONG1",
977 code='\x8a',
978 arg=long1,
979 stack_before=[],
980 stack_after=[pylong],
981 proto=2,
982 doc="""Long integer using one-byte length.
983
984 A more efficient encoding of a Python long; the long1 encoding
985 says it all."""),
986
987 I(name="LONG4",
988 code='\x8b',
989 arg=long4,
990 stack_before=[],
991 stack_after=[pylong],
992 proto=2,
993 doc="""Long integer using found-byte length.
994
995 A more efficient encoding of a Python long; the long4 encoding
996 says it all."""),
997
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000998 # Ways to spell strings (8-bit, not Unicode).
999
1000 I(name='STRING',
1001 code='S',
1002 arg=stringnl,
1003 stack_before=[],
1004 stack_after=[pystring],
1005 proto=0,
1006 doc="""Push a Python string object.
1007
1008 The argument is a repr-style string, with bracketing quote characters,
1009 and perhaps embedded escapes. The argument extends until the next
1010 newline character.
1011 """),
1012
1013 I(name='BINSTRING',
1014 code='T',
1015 arg=string4,
1016 stack_before=[],
1017 stack_after=[pystring],
1018 proto=1,
1019 doc="""Push a Python string object.
1020
1021 There are two arguments: the first is a 4-byte little-endian signed int
1022 giving the number of bytes in the string, and the second is that many
1023 bytes, which are taken literally as the string content.
1024 """),
1025
1026 I(name='SHORT_BINSTRING',
1027 code='U',
1028 arg=string1,
1029 stack_before=[],
1030 stack_after=[pystring],
1031 proto=1,
1032 doc="""Push a Python string object.
1033
1034 There are two arguments: the first is a 1-byte unsigned int giving
1035 the number of bytes in the string, and the second is that many bytes,
1036 which are taken literally as the string content.
1037 """),
1038
1039 # Ways to spell None.
1040
1041 I(name='NONE',
1042 code='N',
1043 arg=None,
1044 stack_before=[],
1045 stack_after=[pynone],
1046 proto=0,
1047 doc="Push None on the stack."),
1048
Tim Petersfdc03462003-01-28 04:56:33 +00001049 # Ways to spell bools, starting with proto 2. See INT for how this was
1050 # done before proto 2.
1051
1052 I(name='NEWTRUE',
1053 code='\x88',
1054 arg=None,
1055 stack_before=[],
1056 stack_after=[pybool],
1057 proto=2,
1058 doc="""True.
1059
1060 Push True onto the stack."""),
1061
1062 I(name='NEWFALSE',
1063 code='\x89',
1064 arg=None,
1065 stack_before=[],
1066 stack_after=[pybool],
1067 proto=2,
1068 doc="""True.
1069
1070 Push False onto the stack."""),
1071
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001072 # Ways to spell Unicode strings.
1073
1074 I(name='UNICODE',
1075 code='V',
1076 arg=unicodestringnl,
1077 stack_before=[],
1078 stack_after=[pyunicode],
1079 proto=0, # this may be pure-text, but it's a later addition
1080 doc="""Push a Python Unicode string object.
1081
1082 The argument is a raw-unicode-escape encoding of a Unicode string,
1083 and so may contain embedded escape sequences. The argument extends
1084 until the next newline character.
1085 """),
1086
1087 I(name='BINUNICODE',
1088 code='X',
1089 arg=unicodestring4,
1090 stack_before=[],
1091 stack_after=[pyunicode],
1092 proto=1,
1093 doc="""Push a Python Unicode string object.
1094
1095 There are two arguments: the first is a 4-byte little-endian signed int
1096 giving the number of bytes in the string. The second is that many
1097 bytes, and is the UTF-8 encoding of the Unicode string.
1098 """),
1099
1100 # Ways to spell floats.
1101
1102 I(name='FLOAT',
1103 code='F',
1104 arg=floatnl,
1105 stack_before=[],
1106 stack_after=[pyfloat],
1107 proto=0,
1108 doc="""Newline-terminated decimal float literal.
1109
1110 The argument is repr(a_float), and in general requires 17 significant
1111 digits for roundtrip conversion to be an identity (this is so for
1112 IEEE-754 double precision values, which is what Python float maps to
1113 on most boxes).
1114
1115 In general, FLOAT cannot be used to transport infinities, NaNs, or
1116 minus zero across boxes (or even on a single box, if the platform C
1117 library can't read the strings it produces for such things -- Windows
1118 is like that), but may do less damage than BINFLOAT on boxes with
1119 greater precision or dynamic range than IEEE-754 double.
1120 """),
1121
1122 I(name='BINFLOAT',
1123 code='G',
1124 arg=float8,
1125 stack_before=[],
1126 stack_after=[pyfloat],
1127 proto=1,
1128 doc="""Float stored in binary form, with 8 bytes of data.
1129
1130 This generally requires less than half the space of FLOAT encoding.
1131 In general, BINFLOAT cannot be used to transport infinities, NaNs, or
1132 minus zero, raises an exception if the exponent exceeds the range of
1133 an IEEE-754 double, and retains no more than 53 bits of precision (if
1134 there are more than that, "add a half and chop" rounding is used to
1135 cut it back to 53 significant bits).
1136 """),
1137
1138 # Ways to build lists.
1139
1140 I(name='EMPTY_LIST',
1141 code=']',
1142 arg=None,
1143 stack_before=[],
1144 stack_after=[pylist],
1145 proto=1,
1146 doc="Push an empty list."),
1147
1148 I(name='APPEND',
1149 code='a',
1150 arg=None,
1151 stack_before=[pylist, anyobject],
1152 stack_after=[pylist],
1153 proto=0,
1154 doc="""Append an object to a list.
1155
1156 Stack before: ... pylist anyobject
1157 Stack after: ... pylist+[anyobject]
Tim Peters81098ac2003-01-28 05:12:08 +00001158
1159 although pylist is really extended in-place.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001160 """),
1161
1162 I(name='APPENDS',
1163 code='e',
1164 arg=None,
1165 stack_before=[pylist, markobject, stackslice],
1166 stack_after=[pylist],
1167 proto=1,
1168 doc="""Extend a list by a slice of stack objects.
1169
1170 Stack before: ... pylist markobject stackslice
1171 Stack after: ... pylist+stackslice
Tim Peters81098ac2003-01-28 05:12:08 +00001172
1173 although pylist is really extended in-place.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001174 """),
1175
1176 I(name='LIST',
1177 code='l',
1178 arg=None,
1179 stack_before=[markobject, stackslice],
1180 stack_after=[pylist],
1181 proto=0,
1182 doc="""Build a list out of the topmost stack slice, after markobject.
1183
1184 All the stack entries following the topmost markobject are placed into
1185 a single Python list, which single list object replaces all of the
1186 stack from the topmost markobject onward. For example,
1187
1188 Stack before: ... markobject 1 2 3 'abc'
1189 Stack after: ... [1, 2, 3, 'abc']
1190 """),
1191
1192 # Ways to build tuples.
1193
1194 I(name='EMPTY_TUPLE',
1195 code=')',
1196 arg=None,
1197 stack_before=[],
1198 stack_after=[pytuple],
1199 proto=1,
1200 doc="Push an empty tuple."),
1201
1202 I(name='TUPLE',
1203 code='t',
1204 arg=None,
1205 stack_before=[markobject, stackslice],
1206 stack_after=[pytuple],
1207 proto=0,
1208 doc="""Build a tuple out of the topmost stack slice, after markobject.
1209
1210 All the stack entries following the topmost markobject are placed into
1211 a single Python tuple, which single tuple object replaces all of the
1212 stack from the topmost markobject onward. For example,
1213
1214 Stack before: ... markobject 1 2 3 'abc'
1215 Stack after: ... (1, 2, 3, 'abc')
1216 """),
1217
Tim Petersfdc03462003-01-28 04:56:33 +00001218 I(name='TUPLE1',
1219 code='\x85',
1220 arg=None,
1221 stack_before=[anyobject],
1222 stack_after=[pytuple],
1223 proto=2,
1224 doc="""One-tuple.
1225
1226 This code pops one value off the stack and pushes a tuple of
1227 length 1 whose one item is that value back onto it. IOW:
1228
1229 stack[-1] = tuple(stack[-1:])
1230 """),
1231
1232 I(name='TUPLE2',
1233 code='\x86',
1234 arg=None,
1235 stack_before=[anyobject, anyobject],
1236 stack_after=[pytuple],
1237 proto=2,
1238 doc="""One-tuple.
1239
1240 This code pops two values off the stack and pushes a tuple
1241 of length 2 whose items are those values back onto it. IOW:
1242
1243 stack[-2:] = [tuple(stack[-2:])]
1244 """),
1245
1246 I(name='TUPLE3',
1247 code='\x87',
1248 arg=None,
1249 stack_before=[anyobject, anyobject, anyobject],
1250 stack_after=[pytuple],
1251 proto=2,
1252 doc="""One-tuple.
1253
1254 This code pops three values off the stack and pushes a tuple
1255 of length 3 whose items are those values back onto it. IOW:
1256
1257 stack[-3:] = [tuple(stack[-3:])]
1258 """),
1259
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001260 # Ways to build dicts.
1261
1262 I(name='EMPTY_DICT',
1263 code='}',
1264 arg=None,
1265 stack_before=[],
1266 stack_after=[pydict],
1267 proto=1,
1268 doc="Push an empty dict."),
1269
1270 I(name='DICT',
1271 code='d',
1272 arg=None,
1273 stack_before=[markobject, stackslice],
1274 stack_after=[pydict],
1275 proto=0,
1276 doc="""Build a dict out of the topmost stack slice, after markobject.
1277
1278 All the stack entries following the topmost markobject are placed into
1279 a single Python dict, which single dict object replaces all of the
1280 stack from the topmost markobject onward. The stack slice alternates
1281 key, value, key, value, .... For example,
1282
1283 Stack before: ... markobject 1 2 3 'abc'
1284 Stack after: ... {1: 2, 3: 'abc'}
1285 """),
1286
1287 I(name='SETITEM',
1288 code='s',
1289 arg=None,
1290 stack_before=[pydict, anyobject, anyobject],
1291 stack_after=[pydict],
1292 proto=0,
1293 doc="""Add a key+value pair to an existing dict.
1294
1295 Stack before: ... pydict key value
1296 Stack after: ... pydict
1297
1298 where pydict has been modified via pydict[key] = value.
1299 """),
1300
1301 I(name='SETITEMS',
1302 code='u',
1303 arg=None,
1304 stack_before=[pydict, markobject, stackslice],
1305 stack_after=[pydict],
1306 proto=1,
1307 doc="""Add an arbitrary number of key+value pairs to an existing dict.
1308
1309 The slice of the stack following the topmost markobject is taken as
1310 an alternating sequence of keys and values, added to the dict
1311 immediately under the topmost markobject. Everything at and after the
1312 topmost markobject is popped, leaving the mutated dict at the top
1313 of the stack.
1314
1315 Stack before: ... pydict markobject key_1 value_1 ... key_n value_n
1316 Stack after: ... pydict
1317
1318 where pydict has been modified via pydict[key_i] = value_i for i in
1319 1, 2, ..., n, and in that order.
1320 """),
1321
1322 # Stack manipulation.
1323
1324 I(name='POP',
1325 code='0',
1326 arg=None,
1327 stack_before=[anyobject],
1328 stack_after=[],
1329 proto=0,
1330 doc="Discard the top stack item, shrinking the stack by one item."),
1331
1332 I(name='DUP',
1333 code='2',
1334 arg=None,
1335 stack_before=[anyobject],
1336 stack_after=[anyobject, anyobject],
1337 proto=0,
1338 doc="Push the top stack item onto the stack again, duplicating it."),
1339
1340 I(name='MARK',
1341 code='(',
1342 arg=None,
1343 stack_before=[],
1344 stack_after=[markobject],
1345 proto=0,
1346 doc="""Push markobject onto the stack.
1347
1348 markobject is a unique object, used by other opcodes to identify a
1349 region of the stack containing a variable number of objects for them
1350 to work on. See markobject.doc for more detail.
1351 """),
1352
1353 I(name='POP_MARK',
1354 code='1',
1355 arg=None,
1356 stack_before=[markobject, stackslice],
1357 stack_after=[],
1358 proto=0,
1359 doc="""Pop all the stack objects at and above the topmost markobject.
1360
1361 When an opcode using a variable number of stack objects is done,
1362 POP_MARK is used to remove those objects, and to remove the markobject
1363 that delimited their starting position on the stack.
1364 """),
1365
1366 # Memo manipulation. There are really only two operations (get and put),
1367 # each in all-text, "short binary", and "long binary" flavors.
1368
1369 I(name='GET',
1370 code='g',
1371 arg=decimalnl_short,
1372 stack_before=[],
1373 stack_after=[anyobject],
1374 proto=0,
1375 doc="""Read an object from the memo and push it on the stack.
1376
1377 The index of the memo object to push is given by the newline-teriminated
1378 decimal string following. BINGET and LONG_BINGET are space-optimized
1379 versions.
1380 """),
1381
1382 I(name='BINGET',
1383 code='h',
1384 arg=uint1,
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 1-byte unsigned
1391 integer following.
1392 """),
1393
1394 I(name='LONG_BINGET',
1395 code='j',
1396 arg=int4,
1397 stack_before=[],
1398 stack_after=[anyobject],
1399 proto=1,
1400 doc="""Read an object from the memo and push it on the stack.
1401
1402 The index of the memo object to push is given by the 4-byte signed
1403 little-endian integer following.
1404 """),
1405
1406 I(name='PUT',
1407 code='p',
1408 arg=decimalnl_short,
1409 stack_before=[],
1410 stack_after=[],
1411 proto=0,
1412 doc="""Store the stack top into the memo. The stack is not popped.
1413
1414 The index of the memo location to write into is given by the newline-
1415 terminated decimal string following. BINPUT and LONG_BINPUT are
1416 space-optimized versions.
1417 """),
1418
1419 I(name='BINPUT',
1420 code='q',
1421 arg=uint1,
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 1-byte
1428 unsigned integer following.
1429 """),
1430
1431 I(name='LONG_BINPUT',
1432 code='r',
1433 arg=int4,
1434 stack_before=[],
1435 stack_after=[],
1436 proto=1,
1437 doc="""Store the stack top into the memo. The stack is not popped.
1438
1439 The index of the memo location to write into is given by the 4-byte
1440 signed little-endian integer following.
1441 """),
1442
Tim Petersfdc03462003-01-28 04:56:33 +00001443 # Access the extension registry (predefined objects). Akin to the GET
1444 # family.
1445
1446 I(name='EXT1',
1447 code='\x82',
1448 arg=uint1,
1449 stack_before=[],
1450 stack_after=[anyobject],
1451 proto=2,
1452 doc="""Extension code.
1453
1454 This code and the similar EXT2 and EXT4 allow using a registry
1455 of popular objects that are pickled by name, typically classes.
1456 It is envisioned that through a global negotiation and
1457 registration process, third parties can set up a mapping between
1458 ints and object names.
1459
1460 In order to guarantee pickle interchangeability, the extension
1461 code registry ought to be global, although a range of codes may
1462 be reserved for private use.
1463
1464 EXT1 has a 1-byte integer argument. This is used to index into the
1465 extension registry, and the object at that index is pushed on the stack.
1466 """),
1467
1468 I(name='EXT2',
1469 code='\x83',
1470 arg=uint2,
1471 stack_before=[],
1472 stack_after=[anyobject],
1473 proto=2,
1474 doc="""Extension code.
1475
1476 See EXT1. EXT2 has a two-byte integer argument.
1477 """),
1478
1479 I(name='EXT4',
1480 code='\x84',
1481 arg=int4,
1482 stack_before=[],
1483 stack_after=[anyobject],
1484 proto=2,
1485 doc="""Extension code.
1486
1487 See EXT1. EXT4 has a four-byte integer argument.
1488 """),
1489
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001490 # Push a class object, or module function, on the stack, via its module
1491 # and name.
1492
1493 I(name='GLOBAL',
1494 code='c',
1495 arg=stringnl_noescape_pair,
1496 stack_before=[],
1497 stack_after=[anyobject],
1498 proto=0,
1499 doc="""Push a global object (module.attr) on the stack.
1500
1501 Two newline-terminated strings follow the GLOBAL opcode. The first is
1502 taken as a module name, and the second as a class name. The class
1503 object module.class is pushed on the stack. More accurately, the
1504 object returned by self.find_class(module, class) is pushed on the
1505 stack, so unpickling subclasses can override this form of lookup.
1506 """),
1507
1508 # Ways to build objects of classes pickle doesn't know about directly
1509 # (user-defined classes). I despair of documenting this accurately
1510 # and comprehensibly -- you really have to read the pickle code to
1511 # find all the special cases.
1512
1513 I(name='REDUCE',
1514 code='R',
1515 arg=None,
1516 stack_before=[anyobject, anyobject],
1517 stack_after=[anyobject],
1518 proto=0,
1519 doc="""Push an object built from a callable and an argument tuple.
1520
1521 The opcode is named to remind of the __reduce__() method.
1522
1523 Stack before: ... callable pytuple
1524 Stack after: ... callable(*pytuple)
1525
1526 The callable and the argument tuple are the first two items returned
1527 by a __reduce__ method. Applying the callable to the argtuple is
1528 supposed to reproduce the original object, or at least get it started.
1529 If the __reduce__ method returns a 3-tuple, the last component is an
1530 argument to be passed to the object's __setstate__, and then the REDUCE
1531 opcode is followed by code to create setstate's argument, and then a
1532 BUILD opcode to apply __setstate__ to that argument.
1533
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001534 If type(callable) is not ClassType, REDUCE complains unless the
1535 callable has been registered with the copy_reg module's
1536 safe_constructors dict, or the callable has a magic
1537 '__safe_for_unpickling__' attribute with a true value. I'm not sure
1538 why it does this, but I've sure seen this complaint often enough when
1539 I didn't want to <wink>.
1540 """),
1541
1542 I(name='BUILD',
1543 code='b',
1544 arg=None,
1545 stack_before=[anyobject, anyobject],
1546 stack_after=[anyobject],
1547 proto=0,
1548 doc="""Finish building an object, via __setstate__ or dict update.
1549
1550 Stack before: ... anyobject argument
1551 Stack after: ... anyobject
1552
1553 where anyobject may have been mutated, as follows:
1554
1555 If the object has a __setstate__ method,
1556
1557 anyobject.__setstate__(argument)
1558
1559 is called.
1560
1561 Else the argument must be a dict, the object must have a __dict__, and
1562 the object is updated via
1563
1564 anyobject.__dict__.update(argument)
1565
1566 This may raise RuntimeError in restricted execution mode (which
1567 disallows access to __dict__ directly); in that case, the object
1568 is updated instead via
1569
1570 for k, v in argument.items():
1571 anyobject[k] = v
1572 """),
1573
1574 I(name='INST',
1575 code='i',
1576 arg=stringnl_noescape_pair,
1577 stack_before=[markobject, stackslice],
1578 stack_after=[anyobject],
1579 proto=0,
1580 doc="""Build a class instance.
1581
1582 This is the protocol 0 version of protocol 1's OBJ opcode.
1583 INST is followed by two newline-terminated strings, giving a
1584 module and class name, just as for the GLOBAL opcode (and see
1585 GLOBAL for more details about that). self.find_class(module, name)
1586 is used to get a class object.
1587
1588 In addition, all the objects on the stack following the topmost
1589 markobject are gathered into a tuple and popped (along with the
1590 topmost markobject), just as for the TUPLE opcode.
1591
1592 Now it gets complicated. If all of these are true:
1593
1594 + The argtuple is empty (markobject was at the top of the stack
1595 at the start).
1596
1597 + It's an old-style class object (the type of the class object is
1598 ClassType).
1599
1600 + The class object does not have a __getinitargs__ attribute.
1601
1602 then we want to create an old-style class instance without invoking
1603 its __init__() method (pickle has waffled on this over the years; not
1604 calling __init__() is current wisdom). In this case, an instance of
1605 an old-style dummy class is created, and then we try to rebind its
1606 __class__ attribute to the desired class object. If this succeeds,
1607 the new instance object is pushed on the stack, and we're done. In
1608 restricted execution mode it can fail (assignment to __class__ is
1609 disallowed), and I'm not really sure what happens then -- it looks
1610 like the code ends up calling the class object's __init__ anyway,
1611 via falling into the next case.
1612
1613 Else (the argtuple is not empty, it's not an old-style class object,
1614 or the class object does have a __getinitargs__ attribute), the code
1615 first insists that the class object have a __safe_for_unpickling__
1616 attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE,
1617 it doesn't matter whether this attribute has a true or false value, it
Guido van Rossumecb11042003-01-29 06:24:30 +00001618 only matters whether it exists (XXX this is a bug; cPickle
1619 requires the attribute to be true). If __safe_for_unpickling__
1620 doesn't exist, UnpicklingError is raised.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001621
1622 Else (the class object does have a __safe_for_unpickling__ attr),
1623 the class object obtained from INST's arguments is applied to the
1624 argtuple obtained from the stack, and the resulting instance object
1625 is pushed on the stack.
Tim Peters2b93c4c2003-01-30 16:35:08 +00001626
1627 NOTE: checks for __safe_for_unpickling__ went away in Python 2.3.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001628 """),
1629
1630 I(name='OBJ',
1631 code='o',
1632 arg=None,
1633 stack_before=[markobject, anyobject, stackslice],
1634 stack_after=[anyobject],
1635 proto=1,
1636 doc="""Build a class instance.
1637
1638 This is the protocol 1 version of protocol 0's INST opcode, and is
1639 very much like it. The major difference is that the class object
1640 is taken off the stack, allowing it to be retrieved from the memo
1641 repeatedly if several instances of the same class are created. This
1642 can be much more efficient (in both time and space) than repeatedly
1643 embedding the module and class names in INST opcodes.
1644
1645 Unlike INST, OBJ takes no arguments from the opcode stream. Instead
1646 the class object is taken off the stack, immediately above the
1647 topmost markobject:
1648
1649 Stack before: ... markobject classobject stackslice
1650 Stack after: ... new_instance_object
1651
1652 As for INST, the remainder of the stack above the markobject is
1653 gathered into an argument tuple, and then the logic seems identical,
Guido van Rossumecb11042003-01-29 06:24:30 +00001654 except that no __safe_for_unpickling__ check is done (XXX this is
1655 a bug; cPickle does test __safe_for_unpickling__). See INST for
1656 the gory details.
Tim Peters2b93c4c2003-01-30 16:35:08 +00001657
1658 NOTE: In Python 2.3, INST and OBJ are identical except for how they
1659 get the class object. That was always the intent; the implementations
1660 had diverged for accidental reasons.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001661 """),
1662
Tim Petersfdc03462003-01-28 04:56:33 +00001663 I(name='NEWOBJ',
1664 code='\x81',
1665 arg=None,
1666 stack_before=[anyobject, anyobject],
1667 stack_after=[anyobject],
1668 proto=2,
1669 doc="""Build an object instance.
1670
1671 The stack before should be thought of as containing a class
1672 object followed by an argument tuple (the tuple being the stack
1673 top). Call these cls and args. They are popped off the stack,
1674 and the value returned by cls.__new__(cls, *args) is pushed back
1675 onto the stack.
1676 """),
1677
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001678 # Machine control.
1679
Tim Petersfdc03462003-01-28 04:56:33 +00001680 I(name='PROTO',
1681 code='\x80',
1682 arg=uint1,
1683 stack_before=[],
1684 stack_after=[],
1685 proto=2,
1686 doc="""Protocol version indicator.
1687
1688 For protocol 2 and above, a pickle must start with this opcode.
1689 The argument is the protocol version, an int in range(2, 256).
1690 """),
1691
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001692 I(name='STOP',
1693 code='.',
1694 arg=None,
1695 stack_before=[anyobject],
1696 stack_after=[],
1697 proto=0,
1698 doc="""Stop the unpickling machine.
1699
1700 Every pickle ends with this opcode. The object at the top of the stack
1701 is popped, and that's the result of unpickling. The stack should be
1702 empty then.
1703 """),
1704
1705 # Ways to deal with persistent IDs.
1706
1707 I(name='PERSID',
1708 code='P',
1709 arg=stringnl_noescape,
1710 stack_before=[],
1711 stack_after=[anyobject],
1712 proto=0,
1713 doc="""Push an object identified by a persistent ID.
1714
1715 The pickle module doesn't define what a persistent ID means. PERSID's
1716 argument is a newline-terminated str-style (no embedded escapes, no
1717 bracketing quote characters) string, which *is* "the persistent ID".
1718 The unpickler passes this string to self.persistent_load(). Whatever
1719 object that returns is pushed on the stack. There is no implementation
1720 of persistent_load() in Python's unpickler: it must be supplied by an
1721 unpickler subclass.
1722 """),
1723
1724 I(name='BINPERSID',
1725 code='Q',
1726 arg=None,
1727 stack_before=[anyobject],
1728 stack_after=[anyobject],
1729 proto=1,
1730 doc="""Push an object identified by a persistent ID.
1731
1732 Like PERSID, except the persistent ID is popped off the stack (instead
1733 of being a string embedded in the opcode bytestream). The persistent
1734 ID is passed to self.persistent_load(), and whatever object that
1735 returns is pushed on the stack. See PERSID for more detail.
1736 """),
1737]
1738del I
1739
1740# Verify uniqueness of .name and .code members.
1741name2i = {}
1742code2i = {}
1743
1744for i, d in enumerate(opcodes):
1745 if d.name in name2i:
1746 raise ValueError("repeated name %r at indices %d and %d" %
1747 (d.name, name2i[d.name], i))
1748 if d.code in code2i:
1749 raise ValueError("repeated code %r at indices %d and %d" %
1750 (d.code, code2i[d.code], i))
1751
1752 name2i[d.name] = i
1753 code2i[d.code] = i
1754
1755del name2i, code2i, i, d
1756
1757##############################################################################
1758# Build a code2op dict, mapping opcode characters to OpcodeInfo records.
1759# Also ensure we've got the same stuff as pickle.py, although the
1760# introspection here is dicey.
1761
1762code2op = {}
1763for d in opcodes:
1764 code2op[d.code] = d
1765del d
1766
1767def assure_pickle_consistency(verbose=False):
1768 import pickle, re
1769
1770 copy = code2op.copy()
1771 for name in pickle.__all__:
1772 if not re.match("[A-Z][A-Z0-9_]+$", name):
1773 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001774 print("skipping %r: it doesn't look like an opcode name" % name)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001775 continue
1776 picklecode = getattr(pickle, name)
Guido van Rossum617dbc42007-05-07 23:57:08 +00001777 if not isinstance(picklecode, bytes) or len(picklecode) != 1:
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001778 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001779 print(("skipping %r: value %r doesn't look like a pickle "
1780 "code" % (name, picklecode)))
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001781 continue
Guido van Rossum617dbc42007-05-07 23:57:08 +00001782 picklecode = picklecode.decode("latin-1")
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001783 if picklecode in copy:
1784 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001785 print("checking name %r w/ code %r for consistency" % (
1786 name, picklecode))
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001787 d = copy[picklecode]
1788 if d.name != name:
1789 raise ValueError("for pickle code %r, pickle.py uses name %r "
1790 "but we're using name %r" % (picklecode,
1791 name,
1792 d.name))
1793 # Forget this one. Any left over in copy at the end are a problem
1794 # of a different kind.
1795 del copy[picklecode]
1796 else:
1797 raise ValueError("pickle.py appears to have a pickle opcode with "
1798 "name %r and code %r, but we don't" %
1799 (name, picklecode))
1800 if copy:
1801 msg = ["we appear to have pickle opcodes that pickle.py doesn't have:"]
1802 for code, d in copy.items():
1803 msg.append(" name %r with code %r" % (d.name, code))
1804 raise ValueError("\n".join(msg))
1805
1806assure_pickle_consistency()
Tim Petersc0c12b52003-01-29 00:56:17 +00001807del assure_pickle_consistency
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001808
1809##############################################################################
1810# A pickle opcode generator.
1811
1812def genops(pickle):
Guido van Rossuma72ded92003-01-27 19:40:47 +00001813 """Generate all the opcodes in a pickle.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001814
1815 'pickle' is a file-like object, or string, containing the pickle.
1816
1817 Each opcode in the pickle is generated, from the current pickle position,
1818 stopping after a STOP opcode is delivered. A triple is generated for
1819 each opcode:
1820
1821 opcode, arg, pos
1822
1823 opcode is an OpcodeInfo record, describing the current opcode.
1824
1825 If the opcode has an argument embedded in the pickle, arg is its decoded
1826 value, as a Python object. If the opcode doesn't have an argument, arg
1827 is None.
1828
1829 If the pickle has a tell() method, pos was the value of pickle.tell()
1830 before reading the current opcode. If the pickle is a string object,
1831 it's wrapped in a StringIO object, and the latter's tell() result is
1832 used. Else (the pickle doesn't have a tell(), and it's not obvious how
1833 to query its current position) pos is None.
1834 """
1835
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001836 if isinstance(pickle, bytes):
1837 import io
1838 pickle = io.BytesIO(pickle)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001839
1840 if hasattr(pickle, "tell"):
1841 getpos = pickle.tell
1842 else:
1843 getpos = lambda: None
1844
1845 while True:
1846 pos = getpos()
1847 code = pickle.read(1)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001848 opcode = code2op.get(code.decode("latin-1"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001849 if opcode is None:
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001850 if code == b"":
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001851 raise ValueError("pickle exhausted before seeing STOP")
1852 else:
1853 raise ValueError("at position %s, opcode %r unknown" % (
1854 pos is None and "<unknown>" or pos,
1855 code))
1856 if opcode.arg is None:
1857 arg = None
1858 else:
1859 arg = opcode.arg.reader(pickle)
1860 yield opcode, arg, pos
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001861 if code == b'.':
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001862 assert opcode.name == 'STOP'
1863 break
1864
1865##############################################################################
1866# A symbolic pickle disassembler.
1867
Tim Peters62235e72003-02-05 19:55:53 +00001868def dis(pickle, out=None, memo=None, indentlevel=4):
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001869 """Produce a symbolic disassembly of a pickle.
1870
1871 'pickle' is a file-like object, or string, containing a (at least one)
1872 pickle. The pickle is disassembled from the current position, through
1873 the first STOP opcode encountered.
1874
1875 Optional arg 'out' is a file-like object to which the disassembly is
1876 printed. It defaults to sys.stdout.
1877
Tim Peters62235e72003-02-05 19:55:53 +00001878 Optional arg 'memo' is a Python dict, used as the pickle's memo. It
1879 may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes.
1880 Passing the same memo object to another dis() call then allows disassembly
1881 to proceed across multiple pickles that were all created by the same
1882 pickler with the same memo. Ordinarily you don't need to worry about this.
1883
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001884 Optional arg indentlevel is the number of blanks by which to indent
1885 a new MARK level. It defaults to 4.
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001886
1887 In addition to printing the disassembly, some sanity checks are made:
1888
1889 + All embedded opcode arguments "make sense".
1890
1891 + Explicit and implicit pop operations have enough items on the stack.
1892
1893 + When an opcode implicitly refers to a markobject, a markobject is
1894 actually on the stack.
1895
1896 + A memo entry isn't referenced before it's defined.
1897
1898 + The markobject isn't stored in the memo.
1899
1900 + A memo entry isn't redefined.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001901 """
1902
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001903 # Most of the hair here is for sanity checks, but most of it is needed
1904 # anyway to detect when a protocol 0 POP takes a MARK off the stack
1905 # (which in turn is needed to indent MARK blocks correctly).
1906
1907 stack = [] # crude emulation of unpickler stack
Tim Peters62235e72003-02-05 19:55:53 +00001908 if memo is None:
1909 memo = {} # crude emulation of unpicker memo
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001910 maxproto = -1 # max protocol number seen
1911 markstack = [] # bytecode positions of MARK opcodes
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001912 indentchunk = ' ' * indentlevel
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001913 errormsg = None
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001914 for opcode, arg, pos in genops(pickle):
1915 if pos is not None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001916 print("%5d:" % pos, end=' ', file=out)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001917
Tim Petersd0f7c862003-01-28 15:27:57 +00001918 line = "%-4s %s%s" % (repr(opcode.code)[1:-1],
1919 indentchunk * len(markstack),
1920 opcode.name)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001921
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001922 maxproto = max(maxproto, opcode.proto)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001923 before = opcode.stack_before # don't mutate
1924 after = opcode.stack_after # don't mutate
Tim Peters43277d62003-01-30 15:02:12 +00001925 numtopop = len(before)
1926
1927 # See whether a MARK should be popped.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001928 markmsg = None
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001929 if markobject in before or (opcode.name == "POP" and
1930 stack and
1931 stack[-1] is markobject):
1932 assert markobject not in after
Tim Peters43277d62003-01-30 15:02:12 +00001933 if __debug__:
1934 if markobject in before:
1935 assert before[-1] is stackslice
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001936 if markstack:
1937 markpos = markstack.pop()
1938 if markpos is None:
1939 markmsg = "(MARK at unknown opcode offset)"
1940 else:
1941 markmsg = "(MARK at %d)" % markpos
1942 # Pop everything at and after the topmost markobject.
1943 while stack[-1] is not markobject:
1944 stack.pop()
1945 stack.pop()
Tim Peters43277d62003-01-30 15:02:12 +00001946 # Stop later code from popping too much.
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001947 try:
Tim Peters43277d62003-01-30 15:02:12 +00001948 numtopop = before.index(markobject)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001949 except ValueError:
1950 assert opcode.name == "POP"
Tim Peters43277d62003-01-30 15:02:12 +00001951 numtopop = 0
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001952 else:
1953 errormsg = markmsg = "no MARK exists on stack"
1954
1955 # Check for correct memo usage.
1956 if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"):
Tim Peters43277d62003-01-30 15:02:12 +00001957 assert arg is not None
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001958 if arg in memo:
1959 errormsg = "memo key %r already defined" % arg
1960 elif not stack:
1961 errormsg = "stack is empty -- can't store into memo"
1962 elif stack[-1] is markobject:
1963 errormsg = "can't store markobject in the memo"
1964 else:
1965 memo[arg] = stack[-1]
1966
1967 elif opcode.name in ("GET", "BINGET", "LONG_BINGET"):
1968 if arg in memo:
1969 assert len(after) == 1
1970 after = [memo[arg]] # for better stack emulation
1971 else:
1972 errormsg = "memo key %r has never been stored into" % arg
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001973
1974 if arg is not None or markmsg:
1975 # make a mild effort to align arguments
1976 line += ' ' * (10 - len(opcode.name))
1977 if arg is not None:
1978 line += ' ' + repr(arg)
1979 if markmsg:
1980 line += ' ' + markmsg
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001981 print(line, file=out)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001982
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001983 if errormsg:
1984 # Note that we delayed complaining until the offending opcode
1985 # was printed.
1986 raise ValueError(errormsg)
1987
1988 # Emulate the stack effects.
Tim Peters43277d62003-01-30 15:02:12 +00001989 if len(stack) < numtopop:
1990 raise ValueError("tries to pop %d items from stack with "
1991 "only %d items" % (numtopop, len(stack)))
1992 if numtopop:
1993 del stack[-numtopop:]
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001994 if markobject in after:
Tim Peters43277d62003-01-30 15:02:12 +00001995 assert markobject not in before
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001996 markstack.append(pos)
1997
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001998 stack.extend(after)
1999
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002000 print("highest protocol among opcodes =", maxproto, file=out)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002001 if stack:
2002 raise ValueError("stack not empty after STOP: %r" % stack)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002003
Tim Peters90718a42005-02-15 16:22:34 +00002004# For use in the doctest, simply as an example of a class to pickle.
2005class _Example:
2006 def __init__(self, value):
2007 self.value = value
2008
Guido van Rossum03e35322003-01-28 15:37:13 +00002009_dis_test = r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002010>>> import pickle
Guido van Rossumcfe5f202007-05-08 21:26:54 +00002011>>> x = [1, 2, (3, 4), {str8('abc'): "def"}]
Guido van Rossum57028352003-01-28 15:09:10 +00002012>>> pkl = pickle.dumps(x, 0)
2013>>> dis(pkl)
Tim Petersd0f7c862003-01-28 15:27:57 +00002014 0: ( MARK
2015 1: l LIST (MARK at 0)
2016 2: p PUT 0
Guido van Rossumf4100002007-01-15 00:21:46 +00002017 5: L LONG 1
Tim Petersd0f7c862003-01-28 15:27:57 +00002018 8: a APPEND
Guido van Rossumf4100002007-01-15 00:21:46 +00002019 9: L LONG 2
Tim Petersd0f7c862003-01-28 15:27:57 +00002020 12: a APPEND
2021 13: ( MARK
Guido van Rossumf4100002007-01-15 00:21:46 +00002022 14: L LONG 3
2023 17: L LONG 4
Tim Petersd0f7c862003-01-28 15:27:57 +00002024 20: t TUPLE (MARK at 13)
2025 21: p PUT 1
2026 24: a APPEND
2027 25: ( MARK
2028 26: d DICT (MARK at 25)
2029 27: p PUT 2
2030 30: S STRING 'abc'
2031 37: p PUT 3
Guido van Rossumcfe5f202007-05-08 21:26:54 +00002032 40: V UNICODE 'def'
Tim Petersd0f7c862003-01-28 15:27:57 +00002033 45: p PUT 4
2034 48: s SETITEM
2035 49: a APPEND
2036 50: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002037highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002038
2039Try again with a "binary" pickle.
2040
Guido van Rossum57028352003-01-28 15:09:10 +00002041>>> pkl = pickle.dumps(x, 1)
2042>>> dis(pkl)
Tim Petersd0f7c862003-01-28 15:27:57 +00002043 0: ] EMPTY_LIST
2044 1: q BINPUT 0
2045 3: ( MARK
2046 4: K BININT1 1
2047 6: K BININT1 2
2048 8: ( MARK
2049 9: K BININT1 3
2050 11: K BININT1 4
2051 13: t TUPLE (MARK at 8)
2052 14: q BINPUT 1
2053 16: } EMPTY_DICT
2054 17: q BINPUT 2
2055 19: U SHORT_BINSTRING 'abc'
2056 24: q BINPUT 3
Guido van Rossumcfe5f202007-05-08 21:26:54 +00002057 26: X BINUNICODE 'def'
Tim Petersd0f7c862003-01-28 15:27:57 +00002058 34: q BINPUT 4
2059 36: s SETITEM
2060 37: e APPENDS (MARK at 3)
2061 38: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002062highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002063
2064Exercise the INST/OBJ/BUILD family.
2065
2066>>> import random
Guido van Rossum4f7ac2e2007-02-26 15:59:50 +00002067>>> dis(pickle.dumps(random.getrandbits, 0))
2068 0: c GLOBAL 'random getrandbits'
2069 20: p PUT 0
2070 23: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002071highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002072
Tim Peters90718a42005-02-15 16:22:34 +00002073>>> from pickletools import _Example
2074>>> x = [_Example(42)] * 2
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002075>>> dis(pickle.dumps(x, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002076 0: ( MARK
2077 1: l LIST (MARK at 0)
2078 2: p PUT 0
Guido van Rossum65810fe2006-05-26 19:12:38 +00002079 5: c GLOBAL 'copy_reg _reconstructor'
2080 30: p PUT 1
2081 33: ( MARK
2082 34: c GLOBAL 'pickletools _Example'
2083 56: p PUT 2
2084 59: c GLOBAL '__builtin__ object'
2085 79: p PUT 3
2086 82: N NONE
2087 83: t TUPLE (MARK at 33)
2088 84: p PUT 4
2089 87: R REDUCE
2090 88: p PUT 5
2091 91: ( MARK
2092 92: d DICT (MARK at 91)
2093 93: p PUT 6
2094 96: S STRING 'value'
2095 105: p PUT 7
Guido van Rossumf4100002007-01-15 00:21:46 +00002096 108: L LONG 42
Guido van Rossum65810fe2006-05-26 19:12:38 +00002097 112: s SETITEM
2098 113: b BUILD
2099 114: a APPEND
2100 115: g GET 5
2101 118: a APPEND
2102 119: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002103highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002104
2105>>> dis(pickle.dumps(x, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002106 0: ] EMPTY_LIST
2107 1: q BINPUT 0
2108 3: ( MARK
Guido van Rossum65810fe2006-05-26 19:12:38 +00002109 4: c GLOBAL 'copy_reg _reconstructor'
2110 29: q BINPUT 1
2111 31: ( MARK
2112 32: c GLOBAL 'pickletools _Example'
2113 54: q BINPUT 2
2114 56: c GLOBAL '__builtin__ object'
2115 76: q BINPUT 3
2116 78: N NONE
2117 79: t TUPLE (MARK at 31)
2118 80: q BINPUT 4
2119 82: R REDUCE
2120 83: q BINPUT 5
2121 85: } EMPTY_DICT
2122 86: q BINPUT 6
2123 88: U SHORT_BINSTRING 'value'
2124 95: q BINPUT 7
2125 97: K BININT1 42
2126 99: s SETITEM
2127 100: b BUILD
2128 101: h BINGET 5
2129 103: e APPENDS (MARK at 3)
2130 104: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002131highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002132
2133Try "the canonical" recursive-object test.
2134
2135>>> L = []
2136>>> T = L,
2137>>> L.append(T)
2138>>> L[0] is T
2139True
2140>>> T[0] is L
2141True
2142>>> L[0][0] is L
2143True
2144>>> T[0][0] is T
2145True
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002146>>> dis(pickle.dumps(L, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002147 0: ( MARK
2148 1: l LIST (MARK at 0)
2149 2: p PUT 0
2150 5: ( MARK
2151 6: g GET 0
2152 9: t TUPLE (MARK at 5)
2153 10: p PUT 1
2154 13: a APPEND
2155 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002156highest protocol among opcodes = 0
2157
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002158>>> dis(pickle.dumps(L, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002159 0: ] EMPTY_LIST
2160 1: q BINPUT 0
2161 3: ( MARK
2162 4: h BINGET 0
2163 6: t TUPLE (MARK at 3)
2164 7: q BINPUT 1
2165 9: a APPEND
2166 10: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002167highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002168
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002169Note that, in the protocol 0 pickle of the recursive tuple, the disassembler
2170has to emulate the stack in order to realize that the POP opcode at 16 gets
2171rid of the MARK at 0.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002172
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002173>>> dis(pickle.dumps(T, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002174 0: ( MARK
2175 1: ( MARK
2176 2: l LIST (MARK at 1)
2177 3: p PUT 0
2178 6: ( MARK
2179 7: g GET 0
2180 10: t TUPLE (MARK at 6)
2181 11: p PUT 1
2182 14: a APPEND
2183 15: 0 POP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002184 16: 0 POP (MARK at 0)
2185 17: g GET 1
2186 20: . STOP
2187highest protocol among opcodes = 0
2188
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002189>>> dis(pickle.dumps(T, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002190 0: ( MARK
2191 1: ] EMPTY_LIST
2192 2: q BINPUT 0
2193 4: ( MARK
2194 5: h BINGET 0
2195 7: t TUPLE (MARK at 4)
2196 8: q BINPUT 1
2197 10: a APPEND
2198 11: 1 POP_MARK (MARK at 0)
2199 12: h BINGET 1
2200 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002201highest protocol among opcodes = 1
Tim Petersd0f7c862003-01-28 15:27:57 +00002202
2203Try protocol 2.
2204
2205>>> dis(pickle.dumps(L, 2))
2206 0: \x80 PROTO 2
2207 2: ] EMPTY_LIST
2208 3: q BINPUT 0
2209 5: h BINGET 0
2210 7: \x85 TUPLE1
2211 8: q BINPUT 1
2212 10: a APPEND
2213 11: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002214highest protocol among opcodes = 2
Tim Petersd0f7c862003-01-28 15:27:57 +00002215
2216>>> dis(pickle.dumps(T, 2))
2217 0: \x80 PROTO 2
2218 2: ] EMPTY_LIST
2219 3: q BINPUT 0
2220 5: h BINGET 0
2221 7: \x85 TUPLE1
2222 8: q BINPUT 1
2223 10: a APPEND
2224 11: 0 POP
2225 12: h BINGET 1
2226 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002227highest protocol among opcodes = 2
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002228"""
2229
Tim Peters62235e72003-02-05 19:55:53 +00002230_memo_test = r"""
2231>>> import pickle
Guido van Rossumcfe5f202007-05-08 21:26:54 +00002232>>> import io
2233>>> f = io.BytesIO()
Tim Peters62235e72003-02-05 19:55:53 +00002234>>> p = pickle.Pickler(f, 2)
2235>>> x = [1, 2, 3]
2236>>> p.dump(x)
2237>>> p.dump(x)
2238>>> f.seek(0)
Guido van Rossumcfe5f202007-05-08 21:26:54 +000022390
Tim Peters62235e72003-02-05 19:55:53 +00002240>>> memo = {}
2241>>> dis(f, memo=memo)
2242 0: \x80 PROTO 2
2243 2: ] EMPTY_LIST
2244 3: q BINPUT 0
2245 5: ( MARK
2246 6: K BININT1 1
2247 8: K BININT1 2
2248 10: K BININT1 3
2249 12: e APPENDS (MARK at 5)
2250 13: . STOP
2251highest protocol among opcodes = 2
2252>>> dis(f, memo=memo)
2253 14: \x80 PROTO 2
2254 16: h BINGET 0
2255 18: . STOP
2256highest protocol among opcodes = 2
2257"""
2258
Guido van Rossum57028352003-01-28 15:09:10 +00002259__test__ = {'disassembler_test': _dis_test,
Tim Peters62235e72003-02-05 19:55:53 +00002260 'disassembler_memo_test': _memo_test,
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002261 }
2262
2263def _test():
2264 import doctest
2265 return doctest.testmod()
2266
2267if __name__ == "__main__":
2268 _test()