blob: 23c186a6f44553f44eabc11bfde743b6d67ad85a [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
14
Tim Peters90cf2122004-11-06 23:45:48 +000015__all__ = ['dis',
16 'genops',
17 ]
18
Tim Peters8ecfc8e2003-01-27 18:51:48 +000019# Other ideas:
20#
21# - A pickle verifier: read a pickle and check it exhaustively for
Tim Petersc1c2b3e2003-01-29 20:12:21 +000022# well-formedness. dis() does a lot of this already.
Tim Peters8ecfc8e2003-01-27 18:51:48 +000023#
24# - A protocol identifier: examine a pickle and return its protocol number
25# (== the highest .proto attr value among all the opcodes in the pickle).
Tim Petersc1c2b3e2003-01-29 20:12:21 +000026# dis() already prints this info at the end.
Tim Peters8ecfc8e2003-01-27 18:51:48 +000027#
28# - A pickle optimizer: for example, tuple-building code is sometimes more
29# elaborate than necessary, catering for the possibility that the tuple
30# is recursive. Or lots of times a PUT is generated that's never accessed
31# by a later GET.
32
33
34"""
35"A pickle" is a program for a virtual pickle machine (PM, but more accurately
36called an unpickling machine). It's a sequence of opcodes, interpreted by the
37PM, building an arbitrarily complex Python object.
38
39For the most part, the PM is very simple: there are no looping, testing, or
40conditional instructions, no arithmetic and no function calls. Opcodes are
41executed once each, from first to last, until a STOP opcode is reached.
42
43The PM has two data areas, "the stack" and "the memo".
44
45Many opcodes push Python objects onto the stack; e.g., INT pushes a Python
46integer object on the stack, whose value is gotten from a decimal string
47literal immediately following the INT opcode in the pickle bytestream. Other
48opcodes take Python objects off the stack. The result of unpickling is
49whatever object is left on the stack when the final STOP opcode is executed.
50
51The memo is simply an array of objects, or it can be implemented as a dict
52mapping little integers to objects. The memo serves as the PM's "long term
53memory", and the little integers indexing the memo are akin to variable
54names. Some opcodes pop a stack object into the memo at a given index,
55and others push a memo object at a given index onto the stack again.
56
57At heart, that's all the PM has. Subtleties arise for these reasons:
58
59+ Object identity. Objects can be arbitrarily complex, and subobjects
60 may be shared (for example, the list [a, a] refers to the same object a
61 twice). It can be vital that unpickling recreate an isomorphic object
62 graph, faithfully reproducing sharing.
63
64+ Recursive objects. For example, after "L = []; L.append(L)", L is a
65 list, and L[0] is the same list. This is related to the object identity
66 point, and some sequences of pickle opcodes are subtle in order to
67 get the right result in all cases.
68
69+ Things pickle doesn't know everything about. Examples of things pickle
70 does know everything about are Python's builtin scalar and container
71 types, like ints and tuples. They generally have opcodes dedicated to
72 them. For things like module references and instances of user-defined
73 classes, pickle's knowledge is limited. Historically, many enhancements
74 have been made to the pickle protocol in order to do a better (faster,
75 and/or more compact) job on those.
76
77+ Backward compatibility and micro-optimization. As explained below,
78 pickle opcodes never go away, not even when better ways to do a thing
79 get invented. The repertoire of the PM just keeps growing over time.
Tim Petersfdc03462003-01-28 04:56:33 +000080 For example, protocol 0 had two opcodes for building Python integers (INT
81 and LONG), protocol 1 added three more for more-efficient pickling of short
82 integers, and protocol 2 added two more for more-efficient pickling of
83 long integers (before protocol 2, the only ways to pickle a Python long
84 took time quadratic in the number of digits, for both pickling and
85 unpickling). "Opcode bloat" isn't so much a subtlety as a source of
Tim Peters8ecfc8e2003-01-27 18:51:48 +000086 wearying complication.
87
88
89Pickle protocols:
90
91For compatibility, the meaning of a pickle opcode never changes. Instead new
92pickle opcodes get added, and each version's unpickler can handle all the
93pickle opcodes in all protocol versions to date. So old pickles continue to
94be readable forever. The pickler can generally be told to restrict itself to
95the subset of opcodes available under previous protocol versions too, so that
96users can create pickles under the current version readable by older
97versions. However, a pickle does not contain its version number embedded
98within it. If an older unpickler tries to read a pickle using a later
99protocol, the result is most likely an exception due to seeing an unknown (in
100the older unpickler) opcode.
101
102The original pickle used what's now called "protocol 0", and what was called
103"text mode" before Python 2.3. The entire pickle bytestream is made up of
104printable 7-bit ASCII characters, plus the newline character, in protocol 0.
Tim Petersfdc03462003-01-28 04:56:33 +0000105That's why it was called text mode. Protocol 0 is small and elegant, but
106sometimes painfully inefficient.
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000107
108The second major set of additions is now called "protocol 1", and was called
109"binary mode" before Python 2.3. This added many opcodes with arguments
110consisting of arbitrary bytes, including NUL bytes and unprintable "high bit"
111bytes. Binary mode pickles can be substantially smaller than equivalent
112text mode pickles, and sometimes faster too; e.g., BININT represents a 4-byte
113int as 4 bytes following the opcode, which is cheaper to unpickle than the
Tim Petersfdc03462003-01-28 04:56:33 +0000114(perhaps) 11-character decimal string attached to INT. Protocol 1 also added
115a number of opcodes that operate on many stack elements at once (like APPENDS
Tim Peters81098ac2003-01-28 05:12:08 +0000116and SETITEMS), and "shortcut" opcodes (like EMPTY_DICT and EMPTY_TUPLE).
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000117
118The third major set of additions came in Python 2.3, and is called "protocol
Tim Petersfdc03462003-01-28 04:56:33 +00001192". This added:
120
121- A better way to pickle instances of new-style classes (NEWOBJ).
122
123- A way for a pickle to identify its protocol (PROTO).
124
125- Time- and space- efficient pickling of long ints (LONG{1,4}).
126
127- Shortcuts for small tuples (TUPLE{1,2,3}}.
128
129- Dedicated opcodes for bools (NEWTRUE, NEWFALSE).
130
131- The "extension registry", a vector of popular objects that can be pushed
132 efficiently by index (EXT{1,2,4}). This is akin to the memo and GET, but
133 the registry contents are predefined (there's nothing akin to the memo's
134 PUT).
Guido van Rossumecb11042003-01-29 06:24:30 +0000135
Skip Montanaro54455942003-01-29 15:41:33 +0000136Another independent change with Python 2.3 is the abandonment of any
137pretense that it might be safe to load pickles received from untrusted
Guido van Rossumecb11042003-01-29 06:24:30 +0000138parties -- no sufficient security analysis has been done to guarantee
Skip Montanaro54455942003-01-29 15:41:33 +0000139this and there isn't a use case that warrants the expense of such an
Guido van Rossumecb11042003-01-29 06:24:30 +0000140analysis.
141
142To this end, all tests for __safe_for_unpickling__ or for
143copy_reg.safe_constructors are removed from the unpickling code.
144References to these variables in the descriptions below are to be seen
145as describing unpickling in Python 2.2 and before.
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000146"""
147
148# Meta-rule: Descriptions are stored in instances of descriptor objects,
149# with plain constructors. No meta-language is defined from which
150# descriptors could be constructed. If you want, e.g., XML, write a little
151# program to generate XML from the objects.
152
153##############################################################################
154# Some pickle opcodes have an argument, following the opcode in the
155# bytestream. An argument is of a specific type, described by an instance
156# of ArgumentDescriptor. These are not to be confused with arguments taken
157# off the stack -- ArgumentDescriptor applies only to arguments embedded in
158# the opcode stream, immediately following an opcode.
159
160# Represents the number of bytes consumed by an argument delimited by the
161# next newline character.
162UP_TO_NEWLINE = -1
163
164# Represents the number of bytes consumed by a two-argument opcode where
165# the first argument gives the number of bytes in the second argument.
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000166TAKEN_FROM_ARGUMENT1 = -2 # num bytes is 1-byte unsigned int
167TAKEN_FROM_ARGUMENT4 = -3 # num bytes is 4-byte signed little-endian int
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000168
169class ArgumentDescriptor(object):
170 __slots__ = (
171 # name of descriptor record, also a module global name; a string
172 'name',
173
174 # length of argument, in bytes; an int; UP_TO_NEWLINE and
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000175 # TAKEN_FROM_ARGUMENT{1,4} are negative values for variable-length
176 # cases
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000177 'n',
178
179 # a function taking a file-like object, reading this kind of argument
180 # from the object at the current position, advancing the current
181 # position by n bytes, and returning the value of the argument
182 'reader',
183
184 # human-readable docs for this arg descriptor; a string
185 'doc',
186 )
187
188 def __init__(self, name, n, reader, doc):
189 assert isinstance(name, str)
190 self.name = name
191
192 assert isinstance(n, int) and (n >= 0 or
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000193 n in (UP_TO_NEWLINE,
194 TAKEN_FROM_ARGUMENT1,
195 TAKEN_FROM_ARGUMENT4))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000196 self.n = n
197
198 self.reader = reader
199
200 assert isinstance(doc, str)
201 self.doc = doc
202
203from struct import unpack as _unpack
204
205def read_uint1(f):
Tim Peters55762f52003-01-28 16:01:25 +0000206 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000207 >>> import io
208 >>> read_uint1(io.BytesIO(b'\xff'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000209 255
210 """
211
212 data = f.read(1)
213 if data:
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000214 return data[0]
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000215 raise ValueError("not enough data in stream to read uint1")
216
217uint1 = ArgumentDescriptor(
218 name='uint1',
219 n=1,
220 reader=read_uint1,
221 doc="One-byte unsigned integer.")
222
223
224def read_uint2(f):
Tim Peters55762f52003-01-28 16:01:25 +0000225 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000226 >>> import io
227 >>> read_uint2(io.BytesIO(b'\xff\x00'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000228 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000229 >>> read_uint2(io.BytesIO(b'\xff\xff'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000230 65535
231 """
232
233 data = f.read(2)
234 if len(data) == 2:
235 return _unpack("<H", data)[0]
236 raise ValueError("not enough data in stream to read uint2")
237
238uint2 = ArgumentDescriptor(
239 name='uint2',
240 n=2,
241 reader=read_uint2,
242 doc="Two-byte unsigned integer, little-endian.")
243
244
245def read_int4(f):
Tim Peters55762f52003-01-28 16:01:25 +0000246 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000247 >>> import io
248 >>> read_int4(io.BytesIO(b'\xff\x00\x00\x00'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000249 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000250 >>> read_int4(io.BytesIO(b'\x00\x00\x00\x80')) == -(2**31)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000251 True
252 """
253
254 data = f.read(4)
255 if len(data) == 4:
256 return _unpack("<i", data)[0]
257 raise ValueError("not enough data in stream to read int4")
258
259int4 = ArgumentDescriptor(
260 name='int4',
261 n=4,
262 reader=read_int4,
263 doc="Four-byte signed integer, little-endian, 2's complement.")
264
265
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000266def readline(f):
267 """Read a line from a binary file."""
268 # XXX Slow but at least correct
269 b = bytes()
270 while True:
271 c = f.read(1)
272 if not c:
273 break
274 b += c
275 if c == b'\n':
276 break
277 return b
278
279
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000280def read_stringnl(f, decode=True, stripquotes=True):
Tim Peters55762f52003-01-28 16:01:25 +0000281 r"""
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000282 >>> import io
283 >>> read_stringnl(io.BytesIO(b"'abcd'\nefg\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000284 'abcd'
285
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000286 >>> read_stringnl(io.BytesIO(b"\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000287 Traceback (most recent call last):
288 ...
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000289 ValueError: no string quotes around b''
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000290
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000291 >>> read_stringnl(io.BytesIO(b"\n"), stripquotes=False)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000292 ''
293
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000294 >>> read_stringnl(io.BytesIO(b"''\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000295 ''
296
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000297 >>> read_stringnl(io.BytesIO(b'"abcd"'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000298 Traceback (most recent call last):
299 ...
300 ValueError: no newline found when trying to read stringnl
301
302 Embedded escapes are undone in the result.
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000303 >>> read_stringnl(io.BytesIO(br"'a\n\\b\x00c\td'" + b"\n'e'"))
Tim Peters55762f52003-01-28 16:01:25 +0000304 'a\n\\b\x00c\td'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000305 """
306
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000307 data = readline(f)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000308 if not data.endswith('\n'):
309 raise ValueError("no newline found when trying to read stringnl")
310 data = data[:-1] # lose the newline
311
312 if stripquotes:
313 for q in "'\"":
314 if data.startswith(q):
315 if not data.endswith(q):
316 raise ValueError("strinq quote %r not found at both "
317 "ends of %r" % (q, data))
318 data = data[1:-1]
319 break
320 else:
321 raise ValueError("no string quotes around %r" % data)
322
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000323 if decode:
Walter Dörwald42748a82007-06-12 16:40:17 +0000324 data = codecs.escape_decode(data)[0]
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000325 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
Guido van Rossum13257902007-06-07 23:15:56 +00001534 If not isinstance(callable, type), REDUCE complains unless the
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001535 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)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001565 """),
1566
1567 I(name='INST',
1568 code='i',
1569 arg=stringnl_noescape_pair,
1570 stack_before=[markobject, stackslice],
1571 stack_after=[anyobject],
1572 proto=0,
1573 doc="""Build a class instance.
1574
1575 This is the protocol 0 version of protocol 1's OBJ opcode.
1576 INST is followed by two newline-terminated strings, giving a
1577 module and class name, just as for the GLOBAL opcode (and see
1578 GLOBAL for more details about that). self.find_class(module, name)
1579 is used to get a class object.
1580
1581 In addition, all the objects on the stack following the topmost
1582 markobject are gathered into a tuple and popped (along with the
1583 topmost markobject), just as for the TUPLE opcode.
1584
1585 Now it gets complicated. If all of these are true:
1586
1587 + The argtuple is empty (markobject was at the top of the stack
1588 at the start).
1589
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001590 + The class object does not have a __getinitargs__ attribute.
1591
1592 then we want to create an old-style class instance without invoking
1593 its __init__() method (pickle has waffled on this over the years; not
1594 calling __init__() is current wisdom). In this case, an instance of
1595 an old-style dummy class is created, and then we try to rebind its
1596 __class__ attribute to the desired class object. If this succeeds,
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001597 the new instance object is pushed on the stack, and we're done.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001598
1599 Else (the argtuple is not empty, it's not an old-style class object,
1600 or the class object does have a __getinitargs__ attribute), the code
1601 first insists that the class object have a __safe_for_unpickling__
1602 attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE,
1603 it doesn't matter whether this attribute has a true or false value, it
Guido van Rossumecb11042003-01-29 06:24:30 +00001604 only matters whether it exists (XXX this is a bug; cPickle
1605 requires the attribute to be true). If __safe_for_unpickling__
1606 doesn't exist, UnpicklingError is raised.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001607
1608 Else (the class object does have a __safe_for_unpickling__ attr),
1609 the class object obtained from INST's arguments is applied to the
1610 argtuple obtained from the stack, and the resulting instance object
1611 is pushed on the stack.
Tim Peters2b93c4c2003-01-30 16:35:08 +00001612
1613 NOTE: checks for __safe_for_unpickling__ went away in Python 2.3.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001614 """),
1615
1616 I(name='OBJ',
1617 code='o',
1618 arg=None,
1619 stack_before=[markobject, anyobject, stackslice],
1620 stack_after=[anyobject],
1621 proto=1,
1622 doc="""Build a class instance.
1623
1624 This is the protocol 1 version of protocol 0's INST opcode, and is
1625 very much like it. The major difference is that the class object
1626 is taken off the stack, allowing it to be retrieved from the memo
1627 repeatedly if several instances of the same class are created. This
1628 can be much more efficient (in both time and space) than repeatedly
1629 embedding the module and class names in INST opcodes.
1630
1631 Unlike INST, OBJ takes no arguments from the opcode stream. Instead
1632 the class object is taken off the stack, immediately above the
1633 topmost markobject:
1634
1635 Stack before: ... markobject classobject stackslice
1636 Stack after: ... new_instance_object
1637
1638 As for INST, the remainder of the stack above the markobject is
1639 gathered into an argument tuple, and then the logic seems identical,
Guido van Rossumecb11042003-01-29 06:24:30 +00001640 except that no __safe_for_unpickling__ check is done (XXX this is
1641 a bug; cPickle does test __safe_for_unpickling__). See INST for
1642 the gory details.
Tim Peters2b93c4c2003-01-30 16:35:08 +00001643
1644 NOTE: In Python 2.3, INST and OBJ are identical except for how they
1645 get the class object. That was always the intent; the implementations
1646 had diverged for accidental reasons.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001647 """),
1648
Tim Petersfdc03462003-01-28 04:56:33 +00001649 I(name='NEWOBJ',
1650 code='\x81',
1651 arg=None,
1652 stack_before=[anyobject, anyobject],
1653 stack_after=[anyobject],
1654 proto=2,
1655 doc="""Build an object instance.
1656
1657 The stack before should be thought of as containing a class
1658 object followed by an argument tuple (the tuple being the stack
1659 top). Call these cls and args. They are popped off the stack,
1660 and the value returned by cls.__new__(cls, *args) is pushed back
1661 onto the stack.
1662 """),
1663
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001664 # Machine control.
1665
Tim Petersfdc03462003-01-28 04:56:33 +00001666 I(name='PROTO',
1667 code='\x80',
1668 arg=uint1,
1669 stack_before=[],
1670 stack_after=[],
1671 proto=2,
1672 doc="""Protocol version indicator.
1673
1674 For protocol 2 and above, a pickle must start with this opcode.
1675 The argument is the protocol version, an int in range(2, 256).
1676 """),
1677
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001678 I(name='STOP',
1679 code='.',
1680 arg=None,
1681 stack_before=[anyobject],
1682 stack_after=[],
1683 proto=0,
1684 doc="""Stop the unpickling machine.
1685
1686 Every pickle ends with this opcode. The object at the top of the stack
1687 is popped, and that's the result of unpickling. The stack should be
1688 empty then.
1689 """),
1690
1691 # Ways to deal with persistent IDs.
1692
1693 I(name='PERSID',
1694 code='P',
1695 arg=stringnl_noescape,
1696 stack_before=[],
1697 stack_after=[anyobject],
1698 proto=0,
1699 doc="""Push an object identified by a persistent ID.
1700
1701 The pickle module doesn't define what a persistent ID means. PERSID's
1702 argument is a newline-terminated str-style (no embedded escapes, no
1703 bracketing quote characters) string, which *is* "the persistent ID".
1704 The unpickler passes this string to self.persistent_load(). Whatever
1705 object that returns is pushed on the stack. There is no implementation
1706 of persistent_load() in Python's unpickler: it must be supplied by an
1707 unpickler subclass.
1708 """),
1709
1710 I(name='BINPERSID',
1711 code='Q',
1712 arg=None,
1713 stack_before=[anyobject],
1714 stack_after=[anyobject],
1715 proto=1,
1716 doc="""Push an object identified by a persistent ID.
1717
1718 Like PERSID, except the persistent ID is popped off the stack (instead
1719 of being a string embedded in the opcode bytestream). The persistent
1720 ID is passed to self.persistent_load(), and whatever object that
1721 returns is pushed on the stack. See PERSID for more detail.
1722 """),
1723]
1724del I
1725
1726# Verify uniqueness of .name and .code members.
1727name2i = {}
1728code2i = {}
1729
1730for i, d in enumerate(opcodes):
1731 if d.name in name2i:
1732 raise ValueError("repeated name %r at indices %d and %d" %
1733 (d.name, name2i[d.name], i))
1734 if d.code in code2i:
1735 raise ValueError("repeated code %r at indices %d and %d" %
1736 (d.code, code2i[d.code], i))
1737
1738 name2i[d.name] = i
1739 code2i[d.code] = i
1740
1741del name2i, code2i, i, d
1742
1743##############################################################################
1744# Build a code2op dict, mapping opcode characters to OpcodeInfo records.
1745# Also ensure we've got the same stuff as pickle.py, although the
1746# introspection here is dicey.
1747
1748code2op = {}
1749for d in opcodes:
1750 code2op[d.code] = d
1751del d
1752
1753def assure_pickle_consistency(verbose=False):
1754 import pickle, re
1755
1756 copy = code2op.copy()
1757 for name in pickle.__all__:
1758 if not re.match("[A-Z][A-Z0-9_]+$", name):
1759 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001760 print("skipping %r: it doesn't look like an opcode name" % name)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001761 continue
1762 picklecode = getattr(pickle, name)
Guido van Rossum617dbc42007-05-07 23:57:08 +00001763 if not isinstance(picklecode, bytes) or len(picklecode) != 1:
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001764 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001765 print(("skipping %r: value %r doesn't look like a pickle "
1766 "code" % (name, picklecode)))
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001767 continue
Guido van Rossum617dbc42007-05-07 23:57:08 +00001768 picklecode = picklecode.decode("latin-1")
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001769 if picklecode in copy:
1770 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001771 print("checking name %r w/ code %r for consistency" % (
1772 name, picklecode))
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001773 d = copy[picklecode]
1774 if d.name != name:
1775 raise ValueError("for pickle code %r, pickle.py uses name %r "
1776 "but we're using name %r" % (picklecode,
1777 name,
1778 d.name))
1779 # Forget this one. Any left over in copy at the end are a problem
1780 # of a different kind.
1781 del copy[picklecode]
1782 else:
1783 raise ValueError("pickle.py appears to have a pickle opcode with "
1784 "name %r and code %r, but we don't" %
1785 (name, picklecode))
1786 if copy:
1787 msg = ["we appear to have pickle opcodes that pickle.py doesn't have:"]
1788 for code, d in copy.items():
1789 msg.append(" name %r with code %r" % (d.name, code))
1790 raise ValueError("\n".join(msg))
1791
1792assure_pickle_consistency()
Tim Petersc0c12b52003-01-29 00:56:17 +00001793del assure_pickle_consistency
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001794
1795##############################################################################
1796# A pickle opcode generator.
1797
1798def genops(pickle):
Guido van Rossuma72ded92003-01-27 19:40:47 +00001799 """Generate all the opcodes in a pickle.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001800
1801 'pickle' is a file-like object, or string, containing the pickle.
1802
1803 Each opcode in the pickle is generated, from the current pickle position,
1804 stopping after a STOP opcode is delivered. A triple is generated for
1805 each opcode:
1806
1807 opcode, arg, pos
1808
1809 opcode is an OpcodeInfo record, describing the current opcode.
1810
1811 If the opcode has an argument embedded in the pickle, arg is its decoded
1812 value, as a Python object. If the opcode doesn't have an argument, arg
1813 is None.
1814
1815 If the pickle has a tell() method, pos was the value of pickle.tell()
1816 before reading the current opcode. If the pickle is a string object,
1817 it's wrapped in a StringIO object, and the latter's tell() result is
1818 used. Else (the pickle doesn't have a tell(), and it's not obvious how
1819 to query its current position) pos is None.
1820 """
1821
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001822 if isinstance(pickle, bytes):
1823 import io
1824 pickle = io.BytesIO(pickle)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001825
1826 if hasattr(pickle, "tell"):
1827 getpos = pickle.tell
1828 else:
1829 getpos = lambda: None
1830
1831 while True:
1832 pos = getpos()
1833 code = pickle.read(1)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001834 opcode = code2op.get(code.decode("latin-1"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001835 if opcode is None:
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001836 if code == b"":
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001837 raise ValueError("pickle exhausted before seeing STOP")
1838 else:
1839 raise ValueError("at position %s, opcode %r unknown" % (
1840 pos is None and "<unknown>" or pos,
1841 code))
1842 if opcode.arg is None:
1843 arg = None
1844 else:
1845 arg = opcode.arg.reader(pickle)
1846 yield opcode, arg, pos
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001847 if code == b'.':
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001848 assert opcode.name == 'STOP'
1849 break
1850
1851##############################################################################
1852# A symbolic pickle disassembler.
1853
Tim Peters62235e72003-02-05 19:55:53 +00001854def dis(pickle, out=None, memo=None, indentlevel=4):
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001855 """Produce a symbolic disassembly of a pickle.
1856
1857 'pickle' is a file-like object, or string, containing a (at least one)
1858 pickle. The pickle is disassembled from the current position, through
1859 the first STOP opcode encountered.
1860
1861 Optional arg 'out' is a file-like object to which the disassembly is
1862 printed. It defaults to sys.stdout.
1863
Tim Peters62235e72003-02-05 19:55:53 +00001864 Optional arg 'memo' is a Python dict, used as the pickle's memo. It
1865 may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes.
1866 Passing the same memo object to another dis() call then allows disassembly
1867 to proceed across multiple pickles that were all created by the same
1868 pickler with the same memo. Ordinarily you don't need to worry about this.
1869
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001870 Optional arg indentlevel is the number of blanks by which to indent
1871 a new MARK level. It defaults to 4.
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001872
1873 In addition to printing the disassembly, some sanity checks are made:
1874
1875 + All embedded opcode arguments "make sense".
1876
1877 + Explicit and implicit pop operations have enough items on the stack.
1878
1879 + When an opcode implicitly refers to a markobject, a markobject is
1880 actually on the stack.
1881
1882 + A memo entry isn't referenced before it's defined.
1883
1884 + The markobject isn't stored in the memo.
1885
1886 + A memo entry isn't redefined.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001887 """
1888
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001889 # Most of the hair here is for sanity checks, but most of it is needed
1890 # anyway to detect when a protocol 0 POP takes a MARK off the stack
1891 # (which in turn is needed to indent MARK blocks correctly).
1892
1893 stack = [] # crude emulation of unpickler stack
Tim Peters62235e72003-02-05 19:55:53 +00001894 if memo is None:
1895 memo = {} # crude emulation of unpicker memo
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001896 maxproto = -1 # max protocol number seen
1897 markstack = [] # bytecode positions of MARK opcodes
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001898 indentchunk = ' ' * indentlevel
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001899 errormsg = None
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001900 for opcode, arg, pos in genops(pickle):
1901 if pos is not None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001902 print("%5d:" % pos, end=' ', file=out)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001903
Tim Petersd0f7c862003-01-28 15:27:57 +00001904 line = "%-4s %s%s" % (repr(opcode.code)[1:-1],
1905 indentchunk * len(markstack),
1906 opcode.name)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001907
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001908 maxproto = max(maxproto, opcode.proto)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001909 before = opcode.stack_before # don't mutate
1910 after = opcode.stack_after # don't mutate
Tim Peters43277d62003-01-30 15:02:12 +00001911 numtopop = len(before)
1912
1913 # See whether a MARK should be popped.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001914 markmsg = None
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001915 if markobject in before or (opcode.name == "POP" and
1916 stack and
1917 stack[-1] is markobject):
1918 assert markobject not in after
Tim Peters43277d62003-01-30 15:02:12 +00001919 if __debug__:
1920 if markobject in before:
1921 assert before[-1] is stackslice
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001922 if markstack:
1923 markpos = markstack.pop()
1924 if markpos is None:
1925 markmsg = "(MARK at unknown opcode offset)"
1926 else:
1927 markmsg = "(MARK at %d)" % markpos
1928 # Pop everything at and after the topmost markobject.
1929 while stack[-1] is not markobject:
1930 stack.pop()
1931 stack.pop()
Tim Peters43277d62003-01-30 15:02:12 +00001932 # Stop later code from popping too much.
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001933 try:
Tim Peters43277d62003-01-30 15:02:12 +00001934 numtopop = before.index(markobject)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001935 except ValueError:
1936 assert opcode.name == "POP"
Tim Peters43277d62003-01-30 15:02:12 +00001937 numtopop = 0
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001938 else:
1939 errormsg = markmsg = "no MARK exists on stack"
1940
1941 # Check for correct memo usage.
1942 if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"):
Tim Peters43277d62003-01-30 15:02:12 +00001943 assert arg is not None
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001944 if arg in memo:
1945 errormsg = "memo key %r already defined" % arg
1946 elif not stack:
1947 errormsg = "stack is empty -- can't store into memo"
1948 elif stack[-1] is markobject:
1949 errormsg = "can't store markobject in the memo"
1950 else:
1951 memo[arg] = stack[-1]
1952
1953 elif opcode.name in ("GET", "BINGET", "LONG_BINGET"):
1954 if arg in memo:
1955 assert len(after) == 1
1956 after = [memo[arg]] # for better stack emulation
1957 else:
1958 errormsg = "memo key %r has never been stored into" % arg
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001959
1960 if arg is not None or markmsg:
1961 # make a mild effort to align arguments
1962 line += ' ' * (10 - len(opcode.name))
1963 if arg is not None:
1964 line += ' ' + repr(arg)
1965 if markmsg:
1966 line += ' ' + markmsg
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001967 print(line, file=out)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001968
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001969 if errormsg:
1970 # Note that we delayed complaining until the offending opcode
1971 # was printed.
1972 raise ValueError(errormsg)
1973
1974 # Emulate the stack effects.
Tim Peters43277d62003-01-30 15:02:12 +00001975 if len(stack) < numtopop:
1976 raise ValueError("tries to pop %d items from stack with "
1977 "only %d items" % (numtopop, len(stack)))
1978 if numtopop:
1979 del stack[-numtopop:]
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001980 if markobject in after:
Tim Peters43277d62003-01-30 15:02:12 +00001981 assert markobject not in before
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001982 markstack.append(pos)
1983
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001984 stack.extend(after)
1985
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001986 print("highest protocol among opcodes =", maxproto, file=out)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001987 if stack:
1988 raise ValueError("stack not empty after STOP: %r" % stack)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001989
Tim Peters90718a42005-02-15 16:22:34 +00001990# For use in the doctest, simply as an example of a class to pickle.
1991class _Example:
1992 def __init__(self, value):
1993 self.value = value
1994
Guido van Rossum03e35322003-01-28 15:37:13 +00001995_dis_test = r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001996>>> import pickle
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001997>>> x = [1, 2, (3, 4), {str8('abc'): "def"}]
Guido van Rossum57028352003-01-28 15:09:10 +00001998>>> pkl = pickle.dumps(x, 0)
1999>>> dis(pkl)
Tim Petersd0f7c862003-01-28 15:27:57 +00002000 0: ( MARK
2001 1: l LIST (MARK at 0)
2002 2: p PUT 0
Guido van Rossumf4100002007-01-15 00:21:46 +00002003 5: L LONG 1
Tim Petersd0f7c862003-01-28 15:27:57 +00002004 8: a APPEND
Guido van Rossumf4100002007-01-15 00:21:46 +00002005 9: L LONG 2
Tim Petersd0f7c862003-01-28 15:27:57 +00002006 12: a APPEND
2007 13: ( MARK
Guido van Rossumf4100002007-01-15 00:21:46 +00002008 14: L LONG 3
2009 17: L LONG 4
Tim Petersd0f7c862003-01-28 15:27:57 +00002010 20: t TUPLE (MARK at 13)
2011 21: p PUT 1
2012 24: a APPEND
2013 25: ( MARK
2014 26: d DICT (MARK at 25)
2015 27: p PUT 2
2016 30: S STRING 'abc'
2017 37: p PUT 3
Guido van Rossumcfe5f202007-05-08 21:26:54 +00002018 40: V UNICODE 'def'
Tim Petersd0f7c862003-01-28 15:27:57 +00002019 45: p PUT 4
2020 48: s SETITEM
2021 49: a APPEND
2022 50: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002023highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002024
2025Try again with a "binary" pickle.
2026
Guido van Rossum57028352003-01-28 15:09:10 +00002027>>> pkl = pickle.dumps(x, 1)
2028>>> dis(pkl)
Tim Petersd0f7c862003-01-28 15:27:57 +00002029 0: ] EMPTY_LIST
2030 1: q BINPUT 0
2031 3: ( MARK
2032 4: K BININT1 1
2033 6: K BININT1 2
2034 8: ( MARK
2035 9: K BININT1 3
2036 11: K BININT1 4
2037 13: t TUPLE (MARK at 8)
2038 14: q BINPUT 1
2039 16: } EMPTY_DICT
2040 17: q BINPUT 2
2041 19: U SHORT_BINSTRING 'abc'
2042 24: q BINPUT 3
Guido van Rossumcfe5f202007-05-08 21:26:54 +00002043 26: X BINUNICODE 'def'
Tim Petersd0f7c862003-01-28 15:27:57 +00002044 34: q BINPUT 4
2045 36: s SETITEM
2046 37: e APPENDS (MARK at 3)
2047 38: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002048highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002049
2050Exercise the INST/OBJ/BUILD family.
2051
2052>>> import random
Guido van Rossum4f7ac2e2007-02-26 15:59:50 +00002053>>> dis(pickle.dumps(random.getrandbits, 0))
2054 0: c GLOBAL 'random getrandbits'
2055 20: p PUT 0
2056 23: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002057highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002058
Tim Peters90718a42005-02-15 16:22:34 +00002059>>> from pickletools import _Example
2060>>> x = [_Example(42)] * 2
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002061>>> dis(pickle.dumps(x, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002062 0: ( MARK
2063 1: l LIST (MARK at 0)
2064 2: p PUT 0
Guido van Rossum65810fe2006-05-26 19:12:38 +00002065 5: c GLOBAL 'copy_reg _reconstructor'
2066 30: p PUT 1
2067 33: ( MARK
2068 34: c GLOBAL 'pickletools _Example'
2069 56: p PUT 2
2070 59: c GLOBAL '__builtin__ object'
2071 79: p PUT 3
2072 82: N NONE
2073 83: t TUPLE (MARK at 33)
2074 84: p PUT 4
2075 87: R REDUCE
2076 88: p PUT 5
2077 91: ( MARK
2078 92: d DICT (MARK at 91)
2079 93: p PUT 6
2080 96: S STRING 'value'
2081 105: p PUT 7
Guido van Rossumf4100002007-01-15 00:21:46 +00002082 108: L LONG 42
Guido van Rossum65810fe2006-05-26 19:12:38 +00002083 112: s SETITEM
2084 113: b BUILD
2085 114: a APPEND
2086 115: g GET 5
2087 118: a APPEND
2088 119: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002089highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002090
2091>>> dis(pickle.dumps(x, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002092 0: ] EMPTY_LIST
2093 1: q BINPUT 0
2094 3: ( MARK
Guido van Rossum65810fe2006-05-26 19:12:38 +00002095 4: c GLOBAL 'copy_reg _reconstructor'
2096 29: q BINPUT 1
2097 31: ( MARK
2098 32: c GLOBAL 'pickletools _Example'
2099 54: q BINPUT 2
2100 56: c GLOBAL '__builtin__ object'
2101 76: q BINPUT 3
2102 78: N NONE
2103 79: t TUPLE (MARK at 31)
2104 80: q BINPUT 4
2105 82: R REDUCE
2106 83: q BINPUT 5
2107 85: } EMPTY_DICT
2108 86: q BINPUT 6
2109 88: U SHORT_BINSTRING 'value'
2110 95: q BINPUT 7
2111 97: K BININT1 42
2112 99: s SETITEM
2113 100: b BUILD
2114 101: h BINGET 5
2115 103: e APPENDS (MARK at 3)
2116 104: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002117highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002118
2119Try "the canonical" recursive-object test.
2120
2121>>> L = []
2122>>> T = L,
2123>>> L.append(T)
2124>>> L[0] is T
2125True
2126>>> T[0] is L
2127True
2128>>> L[0][0] is L
2129True
2130>>> T[0][0] is T
2131True
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002132>>> dis(pickle.dumps(L, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002133 0: ( MARK
2134 1: l LIST (MARK at 0)
2135 2: p PUT 0
2136 5: ( MARK
2137 6: g GET 0
2138 9: t TUPLE (MARK at 5)
2139 10: p PUT 1
2140 13: a APPEND
2141 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002142highest protocol among opcodes = 0
2143
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002144>>> dis(pickle.dumps(L, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002145 0: ] EMPTY_LIST
2146 1: q BINPUT 0
2147 3: ( MARK
2148 4: h BINGET 0
2149 6: t TUPLE (MARK at 3)
2150 7: q BINPUT 1
2151 9: a APPEND
2152 10: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002153highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002154
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002155Note that, in the protocol 0 pickle of the recursive tuple, the disassembler
2156has to emulate the stack in order to realize that the POP opcode at 16 gets
2157rid of the MARK at 0.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002158
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002159>>> dis(pickle.dumps(T, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002160 0: ( MARK
2161 1: ( MARK
2162 2: l LIST (MARK at 1)
2163 3: p PUT 0
2164 6: ( MARK
2165 7: g GET 0
2166 10: t TUPLE (MARK at 6)
2167 11: p PUT 1
2168 14: a APPEND
2169 15: 0 POP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002170 16: 0 POP (MARK at 0)
2171 17: g GET 1
2172 20: . STOP
2173highest protocol among opcodes = 0
2174
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002175>>> dis(pickle.dumps(T, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002176 0: ( MARK
2177 1: ] EMPTY_LIST
2178 2: q BINPUT 0
2179 4: ( MARK
2180 5: h BINGET 0
2181 7: t TUPLE (MARK at 4)
2182 8: q BINPUT 1
2183 10: a APPEND
2184 11: 1 POP_MARK (MARK at 0)
2185 12: h BINGET 1
2186 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002187highest protocol among opcodes = 1
Tim Petersd0f7c862003-01-28 15:27:57 +00002188
2189Try protocol 2.
2190
2191>>> dis(pickle.dumps(L, 2))
2192 0: \x80 PROTO 2
2193 2: ] EMPTY_LIST
2194 3: q BINPUT 0
2195 5: h BINGET 0
2196 7: \x85 TUPLE1
2197 8: q BINPUT 1
2198 10: a APPEND
2199 11: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002200highest protocol among opcodes = 2
Tim Petersd0f7c862003-01-28 15:27:57 +00002201
2202>>> dis(pickle.dumps(T, 2))
2203 0: \x80 PROTO 2
2204 2: ] EMPTY_LIST
2205 3: q BINPUT 0
2206 5: h BINGET 0
2207 7: \x85 TUPLE1
2208 8: q BINPUT 1
2209 10: a APPEND
2210 11: 0 POP
2211 12: h BINGET 1
2212 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002213highest protocol among opcodes = 2
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002214"""
2215
Tim Peters62235e72003-02-05 19:55:53 +00002216_memo_test = r"""
2217>>> import pickle
Guido van Rossumcfe5f202007-05-08 21:26:54 +00002218>>> import io
2219>>> f = io.BytesIO()
Tim Peters62235e72003-02-05 19:55:53 +00002220>>> p = pickle.Pickler(f, 2)
2221>>> x = [1, 2, 3]
2222>>> p.dump(x)
2223>>> p.dump(x)
2224>>> f.seek(0)
Guido van Rossumcfe5f202007-05-08 21:26:54 +000022250
Tim Peters62235e72003-02-05 19:55:53 +00002226>>> memo = {}
2227>>> dis(f, memo=memo)
2228 0: \x80 PROTO 2
2229 2: ] EMPTY_LIST
2230 3: q BINPUT 0
2231 5: ( MARK
2232 6: K BININT1 1
2233 8: K BININT1 2
2234 10: K BININT1 3
2235 12: e APPENDS (MARK at 5)
2236 13: . STOP
2237highest protocol among opcodes = 2
2238>>> dis(f, memo=memo)
2239 14: \x80 PROTO 2
2240 16: h BINGET 0
2241 18: . STOP
2242highest protocol among opcodes = 2
2243"""
2244
Guido van Rossum57028352003-01-28 15:09:10 +00002245__test__ = {'disassembler_test': _dis_test,
Tim Peters62235e72003-02-05 19:55:53 +00002246 'disassembler_memo_test': _memo_test,
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002247 }
2248
2249def _test():
2250 import doctest
2251 return doctest.testmod()
2252
2253if __name__ == "__main__":
2254 _test()