blob: c050fc526aefeefa40c3bd308661d30543302765 [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"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000205 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000206 >>> read_uint1(StringIO.StringIO('\xff'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000207 255
208 """
209
210 data = f.read(1)
211 if data:
212 return ord(data)
213 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"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000224 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000225 >>> read_uint2(StringIO.StringIO('\xff\x00'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000226 255
Tim Peters55762f52003-01-28 16:01:25 +0000227 >>> read_uint2(StringIO.StringIO('\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"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000245 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000246 >>> read_int4(StringIO.StringIO('\xff\x00\x00\x00'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000247 255
Tim Peters55762f52003-01-28 16:01:25 +0000248 >>> read_int4(StringIO.StringIO('\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
264def read_stringnl(f, decode=True, stripquotes=True):
Tim Peters55762f52003-01-28 16:01:25 +0000265 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000266 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000267 >>> read_stringnl(StringIO.StringIO("'abcd'\nefg\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000268 'abcd'
269
Tim Peters55762f52003-01-28 16:01:25 +0000270 >>> read_stringnl(StringIO.StringIO("\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000271 Traceback (most recent call last):
272 ...
273 ValueError: no string quotes around ''
274
Tim Peters55762f52003-01-28 16:01:25 +0000275 >>> read_stringnl(StringIO.StringIO("\n"), stripquotes=False)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000276 ''
277
Tim Peters55762f52003-01-28 16:01:25 +0000278 >>> read_stringnl(StringIO.StringIO("''\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000279 ''
280
281 >>> read_stringnl(StringIO.StringIO('"abcd"'))
282 Traceback (most recent call last):
283 ...
284 ValueError: no newline found when trying to read stringnl
285
286 Embedded escapes are undone in the result.
Tim Peters55762f52003-01-28 16:01:25 +0000287 >>> read_stringnl(StringIO.StringIO(r"'a\n\\b\x00c\td'" + "\n'e'"))
288 'a\n\\b\x00c\td'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000289 """
290
291 data = f.readline()
292 if not data.endswith('\n'):
293 raise ValueError("no newline found when trying to read stringnl")
294 data = data[:-1] # lose the newline
295
296 if stripquotes:
297 for q in "'\"":
298 if data.startswith(q):
299 if not data.endswith(q):
300 raise ValueError("strinq quote %r not found at both "
301 "ends of %r" % (q, data))
302 data = data[1:-1]
303 break
304 else:
305 raise ValueError("no string quotes around %r" % data)
306
307 # I'm not sure when 'string_escape' was added to the std codecs; it's
308 # crazy not to use it if it's there.
309 if decode:
310 data = data.decode('string_escape')
311 return data
312
313stringnl = ArgumentDescriptor(
314 name='stringnl',
315 n=UP_TO_NEWLINE,
316 reader=read_stringnl,
317 doc="""A newline-terminated string.
318
319 This is a repr-style string, with embedded escapes, and
320 bracketing quotes.
321 """)
322
323def read_stringnl_noescape(f):
324 return read_stringnl(f, decode=False, stripquotes=False)
325
326stringnl_noescape = ArgumentDescriptor(
327 name='stringnl_noescape',
328 n=UP_TO_NEWLINE,
329 reader=read_stringnl_noescape,
330 doc="""A newline-terminated string.
331
332 This is a str-style string, without embedded escapes,
333 or bracketing quotes. It should consist solely of
334 printable ASCII characters.
335 """)
336
337def read_stringnl_noescape_pair(f):
Tim Peters55762f52003-01-28 16:01:25 +0000338 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000339 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000340 >>> read_stringnl_noescape_pair(StringIO.StringIO("Queue\nEmpty\njunk"))
Tim Petersd916cf42003-01-27 19:01:47 +0000341 'Queue Empty'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000342 """
343
Tim Petersd916cf42003-01-27 19:01:47 +0000344 return "%s %s" % (read_stringnl_noescape(f), read_stringnl_noescape(f))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000345
346stringnl_noescape_pair = ArgumentDescriptor(
347 name='stringnl_noescape_pair',
348 n=UP_TO_NEWLINE,
349 reader=read_stringnl_noescape_pair,
350 doc="""A pair of newline-terminated strings.
351
352 These are str-style strings, without embedded
353 escapes, or bracketing quotes. They should
354 consist solely of printable ASCII characters.
355 The pair is returned as a single string, with
Tim Petersd916cf42003-01-27 19:01:47 +0000356 a single blank separating the two strings.
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000357 """)
358
359def read_string4(f):
Tim Peters55762f52003-01-28 16:01:25 +0000360 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000361 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000362 >>> read_string4(StringIO.StringIO("\x00\x00\x00\x00abc"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000363 ''
Tim Peters55762f52003-01-28 16:01:25 +0000364 >>> read_string4(StringIO.StringIO("\x03\x00\x00\x00abcdef"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000365 'abc'
Tim Peters55762f52003-01-28 16:01:25 +0000366 >>> read_string4(StringIO.StringIO("\x00\x00\x00\x03abcdef"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000367 Traceback (most recent call last):
368 ...
369 ValueError: expected 50331648 bytes in a string4, but only 6 remain
370 """
371
372 n = read_int4(f)
373 if n < 0:
374 raise ValueError("string4 byte count < 0: %d" % n)
375 data = f.read(n)
376 if len(data) == n:
377 return data
378 raise ValueError("expected %d bytes in a string4, but only %d remain" %
379 (n, len(data)))
380
381string4 = ArgumentDescriptor(
382 name="string4",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000383 n=TAKEN_FROM_ARGUMENT4,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000384 reader=read_string4,
385 doc="""A counted string.
386
387 The first argument is a 4-byte little-endian signed int giving
388 the number of bytes in the string, and the second argument is
389 that many bytes.
390 """)
391
392
393def read_string1(f):
Tim Peters55762f52003-01-28 16:01:25 +0000394 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000395 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000396 >>> read_string1(StringIO.StringIO("\x00"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000397 ''
Tim Peters55762f52003-01-28 16:01:25 +0000398 >>> read_string1(StringIO.StringIO("\x03abcdef"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000399 'abc'
400 """
401
402 n = read_uint1(f)
403 assert n >= 0
404 data = f.read(n)
405 if len(data) == n:
406 return data
407 raise ValueError("expected %d bytes in a string1, but only %d remain" %
408 (n, len(data)))
409
410string1 = ArgumentDescriptor(
411 name="string1",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000412 n=TAKEN_FROM_ARGUMENT1,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000413 reader=read_string1,
414 doc="""A counted string.
415
416 The first argument is a 1-byte unsigned int giving the number
417 of bytes in the string, and the second argument is that many
418 bytes.
419 """)
420
421
422def read_unicodestringnl(f):
Tim Peters55762f52003-01-28 16:01:25 +0000423 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000424 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000425 >>> read_unicodestringnl(StringIO.StringIO("abc\uabcd\njunk"))
426 u'abc\uabcd'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000427 """
428
429 data = f.readline()
430 if not data.endswith('\n'):
431 raise ValueError("no newline found when trying to read "
432 "unicodestringnl")
433 data = data[:-1] # lose the newline
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000434 return str(data, 'raw-unicode-escape')
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000435
436unicodestringnl = ArgumentDescriptor(
437 name='unicodestringnl',
438 n=UP_TO_NEWLINE,
439 reader=read_unicodestringnl,
440 doc="""A newline-terminated Unicode string.
441
442 This is raw-unicode-escape encoded, so consists of
443 printable ASCII characters, and may contain embedded
444 escape sequences.
445 """)
446
447def read_unicodestring4(f):
Tim Peters55762f52003-01-28 16:01:25 +0000448 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000449 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000450 >>> s = u'abcd\uabcd'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000451 >>> enc = s.encode('utf-8')
452 >>> enc
Tim Peters55762f52003-01-28 16:01:25 +0000453 'abcd\xea\xaf\x8d'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000454 >>> n = chr(len(enc)) + chr(0) * 3 # little-endian 4-byte length
455 >>> t = read_unicodestring4(StringIO.StringIO(n + enc + 'junk'))
456 >>> s == t
457 True
458
459 >>> read_unicodestring4(StringIO.StringIO(n + enc[:-1]))
460 Traceback (most recent call last):
461 ...
462 ValueError: expected 7 bytes in a unicodestring4, but only 6 remain
463 """
464
465 n = read_int4(f)
466 if n < 0:
467 raise ValueError("unicodestring4 byte count < 0: %d" % n)
468 data = f.read(n)
469 if len(data) == n:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000470 return str(data, 'utf-8')
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000471 raise ValueError("expected %d bytes in a unicodestring4, but only %d "
472 "remain" % (n, len(data)))
473
474unicodestring4 = ArgumentDescriptor(
475 name="unicodestring4",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000476 n=TAKEN_FROM_ARGUMENT4,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000477 reader=read_unicodestring4,
478 doc="""A counted Unicode string.
479
480 The first argument is a 4-byte little-endian signed int
481 giving the number of bytes in the string, and the second
482 argument-- the UTF-8 encoding of the Unicode string --
483 contains that many bytes.
484 """)
485
486
487def read_decimalnl_short(f):
Tim Peters55762f52003-01-28 16:01:25 +0000488 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000489 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000490 >>> read_decimalnl_short(StringIO.StringIO("1234\n56"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000491 1234
492
Tim Peters55762f52003-01-28 16:01:25 +0000493 >>> read_decimalnl_short(StringIO.StringIO("1234L\n56"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000494 Traceback (most recent call last):
495 ...
496 ValueError: trailing 'L' not allowed in '1234L'
497 """
498
499 s = read_stringnl(f, decode=False, stripquotes=False)
500 if s.endswith("L"):
501 raise ValueError("trailing 'L' not allowed in %r" % s)
502
503 # It's not necessarily true that the result fits in a Python short int:
504 # the pickle may have been written on a 64-bit box. There's also a hack
505 # for True and False here.
506 if s == "00":
507 return False
508 elif s == "01":
509 return True
510
511 try:
512 return int(s)
513 except OverflowError:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000514 return int(s)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000515
516def read_decimalnl_long(f):
Tim Peters55762f52003-01-28 16:01:25 +0000517 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000518 >>> import StringIO
519
Tim Peters55762f52003-01-28 16:01:25 +0000520 >>> read_decimalnl_long(StringIO.StringIO("1234L\n56"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000521 1234
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000522
Tim Peters55762f52003-01-28 16:01:25 +0000523 >>> read_decimalnl_long(StringIO.StringIO("123456789012345678901234L\n6"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000524 123456789012345678901234
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000525 """
526
527 s = read_stringnl(f, decode=False, stripquotes=False)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000528 return int(s)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000529
530
531decimalnl_short = ArgumentDescriptor(
532 name='decimalnl_short',
533 n=UP_TO_NEWLINE,
534 reader=read_decimalnl_short,
535 doc="""A newline-terminated decimal integer literal.
536
537 This never has a trailing 'L', and the integer fit
538 in a short Python int on the box where the pickle
539 was written -- but there's no guarantee it will fit
540 in a short Python int on the box where the pickle
541 is read.
542 """)
543
544decimalnl_long = ArgumentDescriptor(
545 name='decimalnl_long',
546 n=UP_TO_NEWLINE,
547 reader=read_decimalnl_long,
548 doc="""A newline-terminated decimal integer literal.
549
550 This has a trailing 'L', and can represent integers
551 of any size.
552 """)
553
554
555def read_floatnl(f):
Tim Peters55762f52003-01-28 16:01:25 +0000556 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000557 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000558 >>> read_floatnl(StringIO.StringIO("-1.25\n6"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000559 -1.25
560 """
561 s = read_stringnl(f, decode=False, stripquotes=False)
562 return float(s)
563
564floatnl = ArgumentDescriptor(
565 name='floatnl',
566 n=UP_TO_NEWLINE,
567 reader=read_floatnl,
568 doc="""A newline-terminated decimal floating literal.
569
570 In general this requires 17 significant digits for roundtrip
571 identity, and pickling then unpickling infinities, NaNs, and
572 minus zero doesn't work across boxes, or on some boxes even
573 on itself (e.g., Windows can't read the strings it produces
574 for infinities or NaNs).
575 """)
576
577def read_float8(f):
Tim Peters55762f52003-01-28 16:01:25 +0000578 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000579 >>> import StringIO, struct
580 >>> raw = struct.pack(">d", -1.25)
581 >>> raw
Tim Peters55762f52003-01-28 16:01:25 +0000582 '\xbf\xf4\x00\x00\x00\x00\x00\x00'
583 >>> read_float8(StringIO.StringIO(raw + "\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000584 -1.25
585 """
586
587 data = f.read(8)
588 if len(data) == 8:
589 return _unpack(">d", data)[0]
590 raise ValueError("not enough data in stream to read float8")
591
592
593float8 = ArgumentDescriptor(
594 name='float8',
595 n=8,
596 reader=read_float8,
597 doc="""An 8-byte binary representation of a float, big-endian.
598
599 The format is unique to Python, and shared with the struct
600 module (format string '>d') "in theory" (the struct and cPickle
601 implementations don't share the code -- they should). It's
602 strongly related to the IEEE-754 double format, and, in normal
603 cases, is in fact identical to the big-endian 754 double format.
604 On other boxes the dynamic range is limited to that of a 754
605 double, and "add a half and chop" rounding is used to reduce
606 the precision to 53 bits. However, even on a 754 box,
607 infinities, NaNs, and minus zero may not be handled correctly
608 (may not survive roundtrip pickling intact).
609 """)
610
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000611# Protocol 2 formats
612
Tim Petersc0c12b52003-01-29 00:56:17 +0000613from pickle import decode_long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000614
615def read_long1(f):
616 r"""
617 >>> import StringIO
Tim Peters4b23f2b2003-01-31 16:43:39 +0000618 >>> read_long1(StringIO.StringIO("\x00"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000619 0
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000620 >>> read_long1(StringIO.StringIO("\x02\xff\x00"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000621 255
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000622 >>> read_long1(StringIO.StringIO("\x02\xff\x7f"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000623 32767
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000624 >>> read_long1(StringIO.StringIO("\x02\x00\xff"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000625 -256
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000626 >>> read_long1(StringIO.StringIO("\x02\x00\x80"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000627 -32768
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000628 """
629
630 n = read_uint1(f)
631 data = f.read(n)
632 if len(data) != n:
633 raise ValueError("not enough data in stream to read long1")
634 return decode_long(data)
635
636long1 = ArgumentDescriptor(
637 name="long1",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000638 n=TAKEN_FROM_ARGUMENT1,
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000639 reader=read_long1,
640 doc="""A binary long, little-endian, using 1-byte size.
641
642 This first reads one byte as an unsigned size, then reads that
Tim Petersbdbe7412003-01-27 23:54:04 +0000643 many bytes and interprets them as a little-endian 2's-complement long.
Tim Peters4b23f2b2003-01-31 16:43:39 +0000644 If the size is 0, that's taken as a shortcut for the long 0L.
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000645 """)
646
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000647def read_long4(f):
648 r"""
649 >>> import StringIO
650 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000651 255
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000652 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000653 32767
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000654 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000655 -256
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000656 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000657 -32768
Tim Peters4b23f2b2003-01-31 16:43:39 +0000658 >>> read_long1(StringIO.StringIO("\x00\x00\x00\x00"))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000659 0
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000660 """
661
662 n = read_int4(f)
663 if n < 0:
Neal Norwitz784a3f52003-01-28 00:20:41 +0000664 raise ValueError("long4 byte count < 0: %d" % n)
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000665 data = f.read(n)
666 if len(data) != n:
Neal Norwitz784a3f52003-01-28 00:20:41 +0000667 raise ValueError("not enough data in stream to read long4")
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000668 return decode_long(data)
669
670long4 = ArgumentDescriptor(
671 name="long4",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000672 n=TAKEN_FROM_ARGUMENT4,
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000673 reader=read_long4,
674 doc="""A binary representation of a long, little-endian.
675
676 This first reads four bytes as a signed size (but requires the
677 size to be >= 0), then reads that many bytes and interprets them
Tim Peters4b23f2b2003-01-31 16:43:39 +0000678 as a little-endian 2's-complement long. If the size is 0, that's taken
Guido van Rossume2a383d2007-01-15 16:59:06 +0000679 as a shortcut for the int 0, although LONG1 should really be used
Tim Peters4b23f2b2003-01-31 16:43:39 +0000680 then instead (and in any case where # of bytes < 256).
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000681 """)
682
683
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000684##############################################################################
685# Object descriptors. The stack used by the pickle machine holds objects,
686# and in the stack_before and stack_after attributes of OpcodeInfo
687# descriptors we need names to describe the various types of objects that can
688# appear on the stack.
689
690class StackObject(object):
691 __slots__ = (
692 # name of descriptor record, for info only
693 'name',
694
695 # type of object, or tuple of type objects (meaning the object can
696 # be of any type in the tuple)
697 'obtype',
698
699 # human-readable docs for this kind of stack object; a string
700 'doc',
701 )
702
703 def __init__(self, name, obtype, doc):
704 assert isinstance(name, str)
705 self.name = name
706
707 assert isinstance(obtype, type) or isinstance(obtype, tuple)
708 if isinstance(obtype, tuple):
709 for contained in obtype:
710 assert isinstance(contained, type)
711 self.obtype = obtype
712
713 assert isinstance(doc, str)
714 self.doc = doc
715
Tim Petersc1c2b3e2003-01-29 20:12:21 +0000716 def __repr__(self):
717 return self.name
718
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000719
720pyint = StackObject(
721 name='int',
722 obtype=int,
723 doc="A short (as opposed to long) Python integer object.")
724
725pylong = StackObject(
726 name='long',
Guido van Rossume2a383d2007-01-15 16:59:06 +0000727 obtype=int,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000728 doc="A long (as opposed to short) Python integer object.")
729
730pyinteger_or_bool = StackObject(
731 name='int_or_bool',
Guido van Rossume2a383d2007-01-15 16:59:06 +0000732 obtype=(int, int, bool),
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000733 doc="A Python integer object (short or long), or "
734 "a Python bool.")
735
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000736pybool = StackObject(
737 name='bool',
738 obtype=(bool,),
739 doc="A Python bool object.")
740
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000741pyfloat = StackObject(
742 name='float',
743 obtype=float,
744 doc="A Python float object.")
745
746pystring = StackObject(
747 name='str',
748 obtype=str,
749 doc="A Python string object.")
750
751pyunicode = StackObject(
752 name='unicode',
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000753 obtype=str,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000754 doc="A Python Unicode string object.")
755
756pynone = StackObject(
757 name="None",
758 obtype=type(None),
759 doc="The Python None object.")
760
761pytuple = StackObject(
762 name="tuple",
763 obtype=tuple,
764 doc="A Python tuple object.")
765
766pylist = StackObject(
767 name="list",
768 obtype=list,
769 doc="A Python list object.")
770
771pydict = StackObject(
772 name="dict",
773 obtype=dict,
774 doc="A Python dict object.")
775
776anyobject = StackObject(
777 name='any',
778 obtype=object,
779 doc="Any kind of object whatsoever.")
780
781markobject = StackObject(
782 name="mark",
783 obtype=StackObject,
784 doc="""'The mark' is a unique object.
785
786 Opcodes that operate on a variable number of objects
787 generally don't embed the count of objects in the opcode,
788 or pull it off the stack. Instead the MARK opcode is used
789 to push a special marker object on the stack, and then
790 some other opcodes grab all the objects from the top of
791 the stack down to (but not including) the topmost marker
792 object.
793 """)
794
795stackslice = StackObject(
796 name="stackslice",
797 obtype=StackObject,
798 doc="""An object representing a contiguous slice of the stack.
799
800 This is used in conjuction with markobject, to represent all
801 of the stack following the topmost markobject. For example,
802 the POP_MARK opcode changes the stack from
803
804 [..., markobject, stackslice]
805 to
806 [...]
807
808 No matter how many object are on the stack after the topmost
809 markobject, POP_MARK gets rid of all of them (including the
810 topmost markobject too).
811 """)
812
813##############################################################################
814# Descriptors for pickle opcodes.
815
816class OpcodeInfo(object):
817
818 __slots__ = (
819 # symbolic name of opcode; a string
820 'name',
821
822 # the code used in a bytestream to represent the opcode; a
823 # one-character string
824 'code',
825
826 # If the opcode has an argument embedded in the byte string, an
827 # instance of ArgumentDescriptor specifying its type. Note that
828 # arg.reader(s) can be used to read and decode the argument from
829 # the bytestream s, and arg.doc documents the format of the raw
830 # argument bytes. If the opcode doesn't have an argument embedded
831 # in the bytestream, arg should be None.
832 'arg',
833
834 # what the stack looks like before this opcode runs; a list
835 'stack_before',
836
837 # what the stack looks like after this opcode runs; a list
838 'stack_after',
839
840 # the protocol number in which this opcode was introduced; an int
841 'proto',
842
843 # human-readable docs for this opcode; a string
844 'doc',
845 )
846
847 def __init__(self, name, code, arg,
848 stack_before, stack_after, proto, doc):
849 assert isinstance(name, str)
850 self.name = name
851
852 assert isinstance(code, str)
853 assert len(code) == 1
854 self.code = code
855
856 assert arg is None or isinstance(arg, ArgumentDescriptor)
857 self.arg = arg
858
859 assert isinstance(stack_before, list)
860 for x in stack_before:
861 assert isinstance(x, StackObject)
862 self.stack_before = stack_before
863
864 assert isinstance(stack_after, list)
865 for x in stack_after:
866 assert isinstance(x, StackObject)
867 self.stack_after = stack_after
868
869 assert isinstance(proto, int) and 0 <= proto <= 2
870 self.proto = proto
871
872 assert isinstance(doc, str)
873 self.doc = doc
874
875I = OpcodeInfo
876opcodes = [
877
878 # Ways to spell integers.
879
880 I(name='INT',
881 code='I',
882 arg=decimalnl_short,
883 stack_before=[],
884 stack_after=[pyinteger_or_bool],
885 proto=0,
886 doc="""Push an integer or bool.
887
888 The argument is a newline-terminated decimal literal string.
889
890 The intent may have been that this always fit in a short Python int,
891 but INT can be generated in pickles written on a 64-bit box that
892 require a Python long on a 32-bit box. The difference between this
893 and LONG then is that INT skips a trailing 'L', and produces a short
894 int whenever possible.
895
896 Another difference is due to that, when bool was introduced as a
897 distinct type in 2.3, builtin names True and False were also added to
898 2.2.2, mapping to ints 1 and 0. For compatibility in both directions,
899 True gets pickled as INT + "I01\\n", and False as INT + "I00\\n".
900 Leading zeroes are never produced for a genuine integer. The 2.3
901 (and later) unpicklers special-case these and return bool instead;
902 earlier unpicklers ignore the leading "0" and return the int.
903 """),
904
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000905 I(name='BININT',
906 code='J',
907 arg=int4,
908 stack_before=[],
909 stack_after=[pyint],
910 proto=1,
911 doc="""Push a four-byte signed integer.
912
913 This handles the full range of Python (short) integers on a 32-bit
914 box, directly as binary bytes (1 for the opcode and 4 for the integer).
915 If the integer is non-negative and fits in 1 or 2 bytes, pickling via
916 BININT1 or BININT2 saves space.
917 """),
918
919 I(name='BININT1',
920 code='K',
921 arg=uint1,
922 stack_before=[],
923 stack_after=[pyint],
924 proto=1,
925 doc="""Push a one-byte unsigned integer.
926
927 This is a space optimization for pickling very small non-negative ints,
928 in range(256).
929 """),
930
931 I(name='BININT2',
932 code='M',
933 arg=uint2,
934 stack_before=[],
935 stack_after=[pyint],
936 proto=1,
937 doc="""Push a two-byte unsigned integer.
938
939 This is a space optimization for pickling small positive ints, in
940 range(256, 2**16). Integers in range(256) can also be pickled via
941 BININT2, but BININT1 instead saves a byte.
942 """),
943
Tim Petersfdc03462003-01-28 04:56:33 +0000944 I(name='LONG',
945 code='L',
946 arg=decimalnl_long,
947 stack_before=[],
948 stack_after=[pylong],
949 proto=0,
950 doc="""Push a long integer.
951
952 The same as INT, except that the literal ends with 'L', and always
953 unpickles to a Python long. There doesn't seem a real purpose to the
954 trailing 'L'.
955
956 Note that LONG takes time quadratic in the number of digits when
957 unpickling (this is simply due to the nature of decimal->binary
958 conversion). Proto 2 added linear-time (in C; still quadratic-time
959 in Python) LONG1 and LONG4 opcodes.
960 """),
961
962 I(name="LONG1",
963 code='\x8a',
964 arg=long1,
965 stack_before=[],
966 stack_after=[pylong],
967 proto=2,
968 doc="""Long integer using one-byte length.
969
970 A more efficient encoding of a Python long; the long1 encoding
971 says it all."""),
972
973 I(name="LONG4",
974 code='\x8b',
975 arg=long4,
976 stack_before=[],
977 stack_after=[pylong],
978 proto=2,
979 doc="""Long integer using found-byte length.
980
981 A more efficient encoding of a Python long; the long4 encoding
982 says it all."""),
983
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000984 # Ways to spell strings (8-bit, not Unicode).
985
986 I(name='STRING',
987 code='S',
988 arg=stringnl,
989 stack_before=[],
990 stack_after=[pystring],
991 proto=0,
992 doc="""Push a Python string object.
993
994 The argument is a repr-style string, with bracketing quote characters,
995 and perhaps embedded escapes. The argument extends until the next
996 newline character.
997 """),
998
999 I(name='BINSTRING',
1000 code='T',
1001 arg=string4,
1002 stack_before=[],
1003 stack_after=[pystring],
1004 proto=1,
1005 doc="""Push a Python string object.
1006
1007 There are two arguments: the first is a 4-byte little-endian signed int
1008 giving the number of bytes in the string, and the second is that many
1009 bytes, which are taken literally as the string content.
1010 """),
1011
1012 I(name='SHORT_BINSTRING',
1013 code='U',
1014 arg=string1,
1015 stack_before=[],
1016 stack_after=[pystring],
1017 proto=1,
1018 doc="""Push a Python string object.
1019
1020 There are two arguments: the first is a 1-byte unsigned int giving
1021 the number of bytes in the string, and the second is that many bytes,
1022 which are taken literally as the string content.
1023 """),
1024
1025 # Ways to spell None.
1026
1027 I(name='NONE',
1028 code='N',
1029 arg=None,
1030 stack_before=[],
1031 stack_after=[pynone],
1032 proto=0,
1033 doc="Push None on the stack."),
1034
Tim Petersfdc03462003-01-28 04:56:33 +00001035 # Ways to spell bools, starting with proto 2. See INT for how this was
1036 # done before proto 2.
1037
1038 I(name='NEWTRUE',
1039 code='\x88',
1040 arg=None,
1041 stack_before=[],
1042 stack_after=[pybool],
1043 proto=2,
1044 doc="""True.
1045
1046 Push True onto the stack."""),
1047
1048 I(name='NEWFALSE',
1049 code='\x89',
1050 arg=None,
1051 stack_before=[],
1052 stack_after=[pybool],
1053 proto=2,
1054 doc="""True.
1055
1056 Push False onto the stack."""),
1057
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001058 # Ways to spell Unicode strings.
1059
1060 I(name='UNICODE',
1061 code='V',
1062 arg=unicodestringnl,
1063 stack_before=[],
1064 stack_after=[pyunicode],
1065 proto=0, # this may be pure-text, but it's a later addition
1066 doc="""Push a Python Unicode string object.
1067
1068 The argument is a raw-unicode-escape encoding of a Unicode string,
1069 and so may contain embedded escape sequences. The argument extends
1070 until the next newline character.
1071 """),
1072
1073 I(name='BINUNICODE',
1074 code='X',
1075 arg=unicodestring4,
1076 stack_before=[],
1077 stack_after=[pyunicode],
1078 proto=1,
1079 doc="""Push a Python Unicode string object.
1080
1081 There are two arguments: the first is a 4-byte little-endian signed int
1082 giving the number of bytes in the string. The second is that many
1083 bytes, and is the UTF-8 encoding of the Unicode string.
1084 """),
1085
1086 # Ways to spell floats.
1087
1088 I(name='FLOAT',
1089 code='F',
1090 arg=floatnl,
1091 stack_before=[],
1092 stack_after=[pyfloat],
1093 proto=0,
1094 doc="""Newline-terminated decimal float literal.
1095
1096 The argument is repr(a_float), and in general requires 17 significant
1097 digits for roundtrip conversion to be an identity (this is so for
1098 IEEE-754 double precision values, which is what Python float maps to
1099 on most boxes).
1100
1101 In general, FLOAT cannot be used to transport infinities, NaNs, or
1102 minus zero across boxes (or even on a single box, if the platform C
1103 library can't read the strings it produces for such things -- Windows
1104 is like that), but may do less damage than BINFLOAT on boxes with
1105 greater precision or dynamic range than IEEE-754 double.
1106 """),
1107
1108 I(name='BINFLOAT',
1109 code='G',
1110 arg=float8,
1111 stack_before=[],
1112 stack_after=[pyfloat],
1113 proto=1,
1114 doc="""Float stored in binary form, with 8 bytes of data.
1115
1116 This generally requires less than half the space of FLOAT encoding.
1117 In general, BINFLOAT cannot be used to transport infinities, NaNs, or
1118 minus zero, raises an exception if the exponent exceeds the range of
1119 an IEEE-754 double, and retains no more than 53 bits of precision (if
1120 there are more than that, "add a half and chop" rounding is used to
1121 cut it back to 53 significant bits).
1122 """),
1123
1124 # Ways to build lists.
1125
1126 I(name='EMPTY_LIST',
1127 code=']',
1128 arg=None,
1129 stack_before=[],
1130 stack_after=[pylist],
1131 proto=1,
1132 doc="Push an empty list."),
1133
1134 I(name='APPEND',
1135 code='a',
1136 arg=None,
1137 stack_before=[pylist, anyobject],
1138 stack_after=[pylist],
1139 proto=0,
1140 doc="""Append an object to a list.
1141
1142 Stack before: ... pylist anyobject
1143 Stack after: ... pylist+[anyobject]
Tim Peters81098ac2003-01-28 05:12:08 +00001144
1145 although pylist is really extended in-place.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001146 """),
1147
1148 I(name='APPENDS',
1149 code='e',
1150 arg=None,
1151 stack_before=[pylist, markobject, stackslice],
1152 stack_after=[pylist],
1153 proto=1,
1154 doc="""Extend a list by a slice of stack objects.
1155
1156 Stack before: ... pylist markobject stackslice
1157 Stack after: ... pylist+stackslice
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='LIST',
1163 code='l',
1164 arg=None,
1165 stack_before=[markobject, stackslice],
1166 stack_after=[pylist],
1167 proto=0,
1168 doc="""Build a list out of the topmost stack slice, after markobject.
1169
1170 All the stack entries following the topmost markobject are placed into
1171 a single Python list, which single list object replaces all of the
1172 stack from the topmost markobject onward. For example,
1173
1174 Stack before: ... markobject 1 2 3 'abc'
1175 Stack after: ... [1, 2, 3, 'abc']
1176 """),
1177
1178 # Ways to build tuples.
1179
1180 I(name='EMPTY_TUPLE',
1181 code=')',
1182 arg=None,
1183 stack_before=[],
1184 stack_after=[pytuple],
1185 proto=1,
1186 doc="Push an empty tuple."),
1187
1188 I(name='TUPLE',
1189 code='t',
1190 arg=None,
1191 stack_before=[markobject, stackslice],
1192 stack_after=[pytuple],
1193 proto=0,
1194 doc="""Build a tuple out of the topmost stack slice, after markobject.
1195
1196 All the stack entries following the topmost markobject are placed into
1197 a single Python tuple, which single tuple object replaces all of the
1198 stack from the topmost markobject onward. For example,
1199
1200 Stack before: ... markobject 1 2 3 'abc'
1201 Stack after: ... (1, 2, 3, 'abc')
1202 """),
1203
Tim Petersfdc03462003-01-28 04:56:33 +00001204 I(name='TUPLE1',
1205 code='\x85',
1206 arg=None,
1207 stack_before=[anyobject],
1208 stack_after=[pytuple],
1209 proto=2,
1210 doc="""One-tuple.
1211
1212 This code pops one value off the stack and pushes a tuple of
1213 length 1 whose one item is that value back onto it. IOW:
1214
1215 stack[-1] = tuple(stack[-1:])
1216 """),
1217
1218 I(name='TUPLE2',
1219 code='\x86',
1220 arg=None,
1221 stack_before=[anyobject, anyobject],
1222 stack_after=[pytuple],
1223 proto=2,
1224 doc="""One-tuple.
1225
1226 This code pops two values off the stack and pushes a tuple
1227 of length 2 whose items are those values back onto it. IOW:
1228
1229 stack[-2:] = [tuple(stack[-2:])]
1230 """),
1231
1232 I(name='TUPLE3',
1233 code='\x87',
1234 arg=None,
1235 stack_before=[anyobject, anyobject, anyobject],
1236 stack_after=[pytuple],
1237 proto=2,
1238 doc="""One-tuple.
1239
1240 This code pops three values off the stack and pushes a tuple
1241 of length 3 whose items are those values back onto it. IOW:
1242
1243 stack[-3:] = [tuple(stack[-3:])]
1244 """),
1245
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001246 # Ways to build dicts.
1247
1248 I(name='EMPTY_DICT',
1249 code='}',
1250 arg=None,
1251 stack_before=[],
1252 stack_after=[pydict],
1253 proto=1,
1254 doc="Push an empty dict."),
1255
1256 I(name='DICT',
1257 code='d',
1258 arg=None,
1259 stack_before=[markobject, stackslice],
1260 stack_after=[pydict],
1261 proto=0,
1262 doc="""Build a dict out of the topmost stack slice, after markobject.
1263
1264 All the stack entries following the topmost markobject are placed into
1265 a single Python dict, which single dict object replaces all of the
1266 stack from the topmost markobject onward. The stack slice alternates
1267 key, value, key, value, .... For example,
1268
1269 Stack before: ... markobject 1 2 3 'abc'
1270 Stack after: ... {1: 2, 3: 'abc'}
1271 """),
1272
1273 I(name='SETITEM',
1274 code='s',
1275 arg=None,
1276 stack_before=[pydict, anyobject, anyobject],
1277 stack_after=[pydict],
1278 proto=0,
1279 doc="""Add a key+value pair to an existing dict.
1280
1281 Stack before: ... pydict key value
1282 Stack after: ... pydict
1283
1284 where pydict has been modified via pydict[key] = value.
1285 """),
1286
1287 I(name='SETITEMS',
1288 code='u',
1289 arg=None,
1290 stack_before=[pydict, markobject, stackslice],
1291 stack_after=[pydict],
1292 proto=1,
1293 doc="""Add an arbitrary number of key+value pairs to an existing dict.
1294
1295 The slice of the stack following the topmost markobject is taken as
1296 an alternating sequence of keys and values, added to the dict
1297 immediately under the topmost markobject. Everything at and after the
1298 topmost markobject is popped, leaving the mutated dict at the top
1299 of the stack.
1300
1301 Stack before: ... pydict markobject key_1 value_1 ... key_n value_n
1302 Stack after: ... pydict
1303
1304 where pydict has been modified via pydict[key_i] = value_i for i in
1305 1, 2, ..., n, and in that order.
1306 """),
1307
1308 # Stack manipulation.
1309
1310 I(name='POP',
1311 code='0',
1312 arg=None,
1313 stack_before=[anyobject],
1314 stack_after=[],
1315 proto=0,
1316 doc="Discard the top stack item, shrinking the stack by one item."),
1317
1318 I(name='DUP',
1319 code='2',
1320 arg=None,
1321 stack_before=[anyobject],
1322 stack_after=[anyobject, anyobject],
1323 proto=0,
1324 doc="Push the top stack item onto the stack again, duplicating it."),
1325
1326 I(name='MARK',
1327 code='(',
1328 arg=None,
1329 stack_before=[],
1330 stack_after=[markobject],
1331 proto=0,
1332 doc="""Push markobject onto the stack.
1333
1334 markobject is a unique object, used by other opcodes to identify a
1335 region of the stack containing a variable number of objects for them
1336 to work on. See markobject.doc for more detail.
1337 """),
1338
1339 I(name='POP_MARK',
1340 code='1',
1341 arg=None,
1342 stack_before=[markobject, stackslice],
1343 stack_after=[],
1344 proto=0,
1345 doc="""Pop all the stack objects at and above the topmost markobject.
1346
1347 When an opcode using a variable number of stack objects is done,
1348 POP_MARK is used to remove those objects, and to remove the markobject
1349 that delimited their starting position on the stack.
1350 """),
1351
1352 # Memo manipulation. There are really only two operations (get and put),
1353 # each in all-text, "short binary", and "long binary" flavors.
1354
1355 I(name='GET',
1356 code='g',
1357 arg=decimalnl_short,
1358 stack_before=[],
1359 stack_after=[anyobject],
1360 proto=0,
1361 doc="""Read an object from the memo and push it on the stack.
1362
1363 The index of the memo object to push is given by the newline-teriminated
1364 decimal string following. BINGET and LONG_BINGET are space-optimized
1365 versions.
1366 """),
1367
1368 I(name='BINGET',
1369 code='h',
1370 arg=uint1,
1371 stack_before=[],
1372 stack_after=[anyobject],
1373 proto=1,
1374 doc="""Read an object from the memo and push it on the stack.
1375
1376 The index of the memo object to push is given by the 1-byte unsigned
1377 integer following.
1378 """),
1379
1380 I(name='LONG_BINGET',
1381 code='j',
1382 arg=int4,
1383 stack_before=[],
1384 stack_after=[anyobject],
1385 proto=1,
1386 doc="""Read an object from the memo and push it on the stack.
1387
1388 The index of the memo object to push is given by the 4-byte signed
1389 little-endian integer following.
1390 """),
1391
1392 I(name='PUT',
1393 code='p',
1394 arg=decimalnl_short,
1395 stack_before=[],
1396 stack_after=[],
1397 proto=0,
1398 doc="""Store the stack top into the memo. The stack is not popped.
1399
1400 The index of the memo location to write into is given by the newline-
1401 terminated decimal string following. BINPUT and LONG_BINPUT are
1402 space-optimized versions.
1403 """),
1404
1405 I(name='BINPUT',
1406 code='q',
1407 arg=uint1,
1408 stack_before=[],
1409 stack_after=[],
1410 proto=1,
1411 doc="""Store the stack top into the memo. The stack is not popped.
1412
1413 The index of the memo location to write into is given by the 1-byte
1414 unsigned integer following.
1415 """),
1416
1417 I(name='LONG_BINPUT',
1418 code='r',
1419 arg=int4,
1420 stack_before=[],
1421 stack_after=[],
1422 proto=1,
1423 doc="""Store the stack top into the memo. The stack is not popped.
1424
1425 The index of the memo location to write into is given by the 4-byte
1426 signed little-endian integer following.
1427 """),
1428
Tim Petersfdc03462003-01-28 04:56:33 +00001429 # Access the extension registry (predefined objects). Akin to the GET
1430 # family.
1431
1432 I(name='EXT1',
1433 code='\x82',
1434 arg=uint1,
1435 stack_before=[],
1436 stack_after=[anyobject],
1437 proto=2,
1438 doc="""Extension code.
1439
1440 This code and the similar EXT2 and EXT4 allow using a registry
1441 of popular objects that are pickled by name, typically classes.
1442 It is envisioned that through a global negotiation and
1443 registration process, third parties can set up a mapping between
1444 ints and object names.
1445
1446 In order to guarantee pickle interchangeability, the extension
1447 code registry ought to be global, although a range of codes may
1448 be reserved for private use.
1449
1450 EXT1 has a 1-byte integer argument. This is used to index into the
1451 extension registry, and the object at that index is pushed on the stack.
1452 """),
1453
1454 I(name='EXT2',
1455 code='\x83',
1456 arg=uint2,
1457 stack_before=[],
1458 stack_after=[anyobject],
1459 proto=2,
1460 doc="""Extension code.
1461
1462 See EXT1. EXT2 has a two-byte integer argument.
1463 """),
1464
1465 I(name='EXT4',
1466 code='\x84',
1467 arg=int4,
1468 stack_before=[],
1469 stack_after=[anyobject],
1470 proto=2,
1471 doc="""Extension code.
1472
1473 See EXT1. EXT4 has a four-byte integer argument.
1474 """),
1475
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001476 # Push a class object, or module function, on the stack, via its module
1477 # and name.
1478
1479 I(name='GLOBAL',
1480 code='c',
1481 arg=stringnl_noescape_pair,
1482 stack_before=[],
1483 stack_after=[anyobject],
1484 proto=0,
1485 doc="""Push a global object (module.attr) on the stack.
1486
1487 Two newline-terminated strings follow the GLOBAL opcode. The first is
1488 taken as a module name, and the second as a class name. The class
1489 object module.class is pushed on the stack. More accurately, the
1490 object returned by self.find_class(module, class) is pushed on the
1491 stack, so unpickling subclasses can override this form of lookup.
1492 """),
1493
1494 # Ways to build objects of classes pickle doesn't know about directly
1495 # (user-defined classes). I despair of documenting this accurately
1496 # and comprehensibly -- you really have to read the pickle code to
1497 # find all the special cases.
1498
1499 I(name='REDUCE',
1500 code='R',
1501 arg=None,
1502 stack_before=[anyobject, anyobject],
1503 stack_after=[anyobject],
1504 proto=0,
1505 doc="""Push an object built from a callable and an argument tuple.
1506
1507 The opcode is named to remind of the __reduce__() method.
1508
1509 Stack before: ... callable pytuple
1510 Stack after: ... callable(*pytuple)
1511
1512 The callable and the argument tuple are the first two items returned
1513 by a __reduce__ method. Applying the callable to the argtuple is
1514 supposed to reproduce the original object, or at least get it started.
1515 If the __reduce__ method returns a 3-tuple, the last component is an
1516 argument to be passed to the object's __setstate__, and then the REDUCE
1517 opcode is followed by code to create setstate's argument, and then a
1518 BUILD opcode to apply __setstate__ to that argument.
1519
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001520 If type(callable) is not ClassType, REDUCE complains unless the
1521 callable has been registered with the copy_reg module's
1522 safe_constructors dict, or the callable has a magic
1523 '__safe_for_unpickling__' attribute with a true value. I'm not sure
1524 why it does this, but I've sure seen this complaint often enough when
1525 I didn't want to <wink>.
1526 """),
1527
1528 I(name='BUILD',
1529 code='b',
1530 arg=None,
1531 stack_before=[anyobject, anyobject],
1532 stack_after=[anyobject],
1533 proto=0,
1534 doc="""Finish building an object, via __setstate__ or dict update.
1535
1536 Stack before: ... anyobject argument
1537 Stack after: ... anyobject
1538
1539 where anyobject may have been mutated, as follows:
1540
1541 If the object has a __setstate__ method,
1542
1543 anyobject.__setstate__(argument)
1544
1545 is called.
1546
1547 Else the argument must be a dict, the object must have a __dict__, and
1548 the object is updated via
1549
1550 anyobject.__dict__.update(argument)
1551
1552 This may raise RuntimeError in restricted execution mode (which
1553 disallows access to __dict__ directly); in that case, the object
1554 is updated instead via
1555
1556 for k, v in argument.items():
1557 anyobject[k] = v
1558 """),
1559
1560 I(name='INST',
1561 code='i',
1562 arg=stringnl_noescape_pair,
1563 stack_before=[markobject, stackslice],
1564 stack_after=[anyobject],
1565 proto=0,
1566 doc="""Build a class instance.
1567
1568 This is the protocol 0 version of protocol 1's OBJ opcode.
1569 INST is followed by two newline-terminated strings, giving a
1570 module and class name, just as for the GLOBAL opcode (and see
1571 GLOBAL for more details about that). self.find_class(module, name)
1572 is used to get a class object.
1573
1574 In addition, all the objects on the stack following the topmost
1575 markobject are gathered into a tuple and popped (along with the
1576 topmost markobject), just as for the TUPLE opcode.
1577
1578 Now it gets complicated. If all of these are true:
1579
1580 + The argtuple is empty (markobject was at the top of the stack
1581 at the start).
1582
1583 + It's an old-style class object (the type of the class object is
1584 ClassType).
1585
1586 + The class object does not have a __getinitargs__ attribute.
1587
1588 then we want to create an old-style class instance without invoking
1589 its __init__() method (pickle has waffled on this over the years; not
1590 calling __init__() is current wisdom). In this case, an instance of
1591 an old-style dummy class is created, and then we try to rebind its
1592 __class__ attribute to the desired class object. If this succeeds,
1593 the new instance object is pushed on the stack, and we're done. In
1594 restricted execution mode it can fail (assignment to __class__ is
1595 disallowed), and I'm not really sure what happens then -- it looks
1596 like the code ends up calling the class object's __init__ anyway,
1597 via falling into the next case.
1598
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
1822 import cStringIO as StringIO
1823
1824 if isinstance(pickle, str):
1825 pickle = StringIO.StringIO(pickle)
1826
1827 if hasattr(pickle, "tell"):
1828 getpos = pickle.tell
1829 else:
1830 getpos = lambda: None
1831
1832 while True:
1833 pos = getpos()
1834 code = pickle.read(1)
1835 opcode = code2op.get(code)
1836 if opcode is None:
1837 if code == "":
1838 raise ValueError("pickle exhausted before seeing STOP")
1839 else:
1840 raise ValueError("at position %s, opcode %r unknown" % (
1841 pos is None and "<unknown>" or pos,
1842 code))
1843 if opcode.arg is None:
1844 arg = None
1845 else:
1846 arg = opcode.arg.reader(pickle)
1847 yield opcode, arg, pos
1848 if code == '.':
1849 assert opcode.name == 'STOP'
1850 break
1851
1852##############################################################################
1853# A symbolic pickle disassembler.
1854
Tim Peters62235e72003-02-05 19:55:53 +00001855def dis(pickle, out=None, memo=None, indentlevel=4):
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001856 """Produce a symbolic disassembly of a pickle.
1857
1858 'pickle' is a file-like object, or string, containing a (at least one)
1859 pickle. The pickle is disassembled from the current position, through
1860 the first STOP opcode encountered.
1861
1862 Optional arg 'out' is a file-like object to which the disassembly is
1863 printed. It defaults to sys.stdout.
1864
Tim Peters62235e72003-02-05 19:55:53 +00001865 Optional arg 'memo' is a Python dict, used as the pickle's memo. It
1866 may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes.
1867 Passing the same memo object to another dis() call then allows disassembly
1868 to proceed across multiple pickles that were all created by the same
1869 pickler with the same memo. Ordinarily you don't need to worry about this.
1870
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001871 Optional arg indentlevel is the number of blanks by which to indent
1872 a new MARK level. It defaults to 4.
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001873
1874 In addition to printing the disassembly, some sanity checks are made:
1875
1876 + All embedded opcode arguments "make sense".
1877
1878 + Explicit and implicit pop operations have enough items on the stack.
1879
1880 + When an opcode implicitly refers to a markobject, a markobject is
1881 actually on the stack.
1882
1883 + A memo entry isn't referenced before it's defined.
1884
1885 + The markobject isn't stored in the memo.
1886
1887 + A memo entry isn't redefined.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001888 """
1889
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001890 # Most of the hair here is for sanity checks, but most of it is needed
1891 # anyway to detect when a protocol 0 POP takes a MARK off the stack
1892 # (which in turn is needed to indent MARK blocks correctly).
1893
1894 stack = [] # crude emulation of unpickler stack
Tim Peters62235e72003-02-05 19:55:53 +00001895 if memo is None:
1896 memo = {} # crude emulation of unpicker memo
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001897 maxproto = -1 # max protocol number seen
1898 markstack = [] # bytecode positions of MARK opcodes
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001899 indentchunk = ' ' * indentlevel
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001900 errormsg = None
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001901 for opcode, arg, pos in genops(pickle):
1902 if pos is not None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001903 print("%5d:" % pos, end=' ', file=out)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001904
Tim Petersd0f7c862003-01-28 15:27:57 +00001905 line = "%-4s %s%s" % (repr(opcode.code)[1:-1],
1906 indentchunk * len(markstack),
1907 opcode.name)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001908
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001909 maxproto = max(maxproto, opcode.proto)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001910 before = opcode.stack_before # don't mutate
1911 after = opcode.stack_after # don't mutate
Tim Peters43277d62003-01-30 15:02:12 +00001912 numtopop = len(before)
1913
1914 # See whether a MARK should be popped.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001915 markmsg = None
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001916 if markobject in before or (opcode.name == "POP" and
1917 stack and
1918 stack[-1] is markobject):
1919 assert markobject not in after
Tim Peters43277d62003-01-30 15:02:12 +00001920 if __debug__:
1921 if markobject in before:
1922 assert before[-1] is stackslice
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001923 if markstack:
1924 markpos = markstack.pop()
1925 if markpos is None:
1926 markmsg = "(MARK at unknown opcode offset)"
1927 else:
1928 markmsg = "(MARK at %d)" % markpos
1929 # Pop everything at and after the topmost markobject.
1930 while stack[-1] is not markobject:
1931 stack.pop()
1932 stack.pop()
Tim Peters43277d62003-01-30 15:02:12 +00001933 # Stop later code from popping too much.
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001934 try:
Tim Peters43277d62003-01-30 15:02:12 +00001935 numtopop = before.index(markobject)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001936 except ValueError:
1937 assert opcode.name == "POP"
Tim Peters43277d62003-01-30 15:02:12 +00001938 numtopop = 0
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001939 else:
1940 errormsg = markmsg = "no MARK exists on stack"
1941
1942 # Check for correct memo usage.
1943 if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"):
Tim Peters43277d62003-01-30 15:02:12 +00001944 assert arg is not None
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001945 if arg in memo:
1946 errormsg = "memo key %r already defined" % arg
1947 elif not stack:
1948 errormsg = "stack is empty -- can't store into memo"
1949 elif stack[-1] is markobject:
1950 errormsg = "can't store markobject in the memo"
1951 else:
1952 memo[arg] = stack[-1]
1953
1954 elif opcode.name in ("GET", "BINGET", "LONG_BINGET"):
1955 if arg in memo:
1956 assert len(after) == 1
1957 after = [memo[arg]] # for better stack emulation
1958 else:
1959 errormsg = "memo key %r has never been stored into" % arg
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001960
1961 if arg is not None or markmsg:
1962 # make a mild effort to align arguments
1963 line += ' ' * (10 - len(opcode.name))
1964 if arg is not None:
1965 line += ' ' + repr(arg)
1966 if markmsg:
1967 line += ' ' + markmsg
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001968 print(line, file=out)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001969
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001970 if errormsg:
1971 # Note that we delayed complaining until the offending opcode
1972 # was printed.
1973 raise ValueError(errormsg)
1974
1975 # Emulate the stack effects.
Tim Peters43277d62003-01-30 15:02:12 +00001976 if len(stack) < numtopop:
1977 raise ValueError("tries to pop %d items from stack with "
1978 "only %d items" % (numtopop, len(stack)))
1979 if numtopop:
1980 del stack[-numtopop:]
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001981 if markobject in after:
Tim Peters43277d62003-01-30 15:02:12 +00001982 assert markobject not in before
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001983 markstack.append(pos)
1984
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001985 stack.extend(after)
1986
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001987 print("highest protocol among opcodes =", maxproto, file=out)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001988 if stack:
1989 raise ValueError("stack not empty after STOP: %r" % stack)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001990
Tim Peters90718a42005-02-15 16:22:34 +00001991# For use in the doctest, simply as an example of a class to pickle.
1992class _Example:
1993 def __init__(self, value):
1994 self.value = value
1995
Guido van Rossum03e35322003-01-28 15:37:13 +00001996_dis_test = r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001997>>> import pickle
1998>>> x = [1, 2, (3, 4), {'abc': u"def"}]
Guido van Rossum57028352003-01-28 15:09:10 +00001999>>> pkl = pickle.dumps(x, 0)
2000>>> dis(pkl)
Tim Petersd0f7c862003-01-28 15:27:57 +00002001 0: ( MARK
2002 1: l LIST (MARK at 0)
2003 2: p PUT 0
Guido van Rossumf4100002007-01-15 00:21:46 +00002004 5: L LONG 1
Tim Petersd0f7c862003-01-28 15:27:57 +00002005 8: a APPEND
Guido van Rossumf4100002007-01-15 00:21:46 +00002006 9: L LONG 2
Tim Petersd0f7c862003-01-28 15:27:57 +00002007 12: a APPEND
2008 13: ( MARK
Guido van Rossumf4100002007-01-15 00:21:46 +00002009 14: L LONG 3
2010 17: L LONG 4
Tim Petersd0f7c862003-01-28 15:27:57 +00002011 20: t TUPLE (MARK at 13)
2012 21: p PUT 1
2013 24: a APPEND
2014 25: ( MARK
2015 26: d DICT (MARK at 25)
2016 27: p PUT 2
2017 30: S STRING 'abc'
2018 37: p PUT 3
2019 40: V UNICODE u'def'
2020 45: p PUT 4
2021 48: s SETITEM
2022 49: a APPEND
2023 50: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002024highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002025
2026Try again with a "binary" pickle.
2027
Guido van Rossum57028352003-01-28 15:09:10 +00002028>>> pkl = pickle.dumps(x, 1)
2029>>> dis(pkl)
Tim Petersd0f7c862003-01-28 15:27:57 +00002030 0: ] EMPTY_LIST
2031 1: q BINPUT 0
2032 3: ( MARK
2033 4: K BININT1 1
2034 6: K BININT1 2
2035 8: ( MARK
2036 9: K BININT1 3
2037 11: K BININT1 4
2038 13: t TUPLE (MARK at 8)
2039 14: q BINPUT 1
2040 16: } EMPTY_DICT
2041 17: q BINPUT 2
2042 19: U SHORT_BINSTRING 'abc'
2043 24: q BINPUT 3
2044 26: X BINUNICODE u'def'
2045 34: q BINPUT 4
2046 36: s SETITEM
2047 37: e APPENDS (MARK at 3)
2048 38: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002049highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002050
2051Exercise the INST/OBJ/BUILD family.
2052
2053>>> import random
Guido van Rossum4f7ac2e2007-02-26 15:59:50 +00002054>>> dis(pickle.dumps(random.getrandbits, 0))
2055 0: c GLOBAL 'random getrandbits'
2056 20: p PUT 0
2057 23: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002058highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002059
Tim Peters90718a42005-02-15 16:22:34 +00002060>>> from pickletools import _Example
2061>>> x = [_Example(42)] * 2
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002062>>> dis(pickle.dumps(x, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002063 0: ( MARK
2064 1: l LIST (MARK at 0)
2065 2: p PUT 0
Guido van Rossum65810fe2006-05-26 19:12:38 +00002066 5: c GLOBAL 'copy_reg _reconstructor'
2067 30: p PUT 1
2068 33: ( MARK
2069 34: c GLOBAL 'pickletools _Example'
2070 56: p PUT 2
2071 59: c GLOBAL '__builtin__ object'
2072 79: p PUT 3
2073 82: N NONE
2074 83: t TUPLE (MARK at 33)
2075 84: p PUT 4
2076 87: R REDUCE
2077 88: p PUT 5
2078 91: ( MARK
2079 92: d DICT (MARK at 91)
2080 93: p PUT 6
2081 96: S STRING 'value'
2082 105: p PUT 7
Guido van Rossumf4100002007-01-15 00:21:46 +00002083 108: L LONG 42
Guido van Rossum65810fe2006-05-26 19:12:38 +00002084 112: s SETITEM
2085 113: b BUILD
2086 114: a APPEND
2087 115: g GET 5
2088 118: a APPEND
2089 119: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002090highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002091
2092>>> dis(pickle.dumps(x, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002093 0: ] EMPTY_LIST
2094 1: q BINPUT 0
2095 3: ( MARK
Guido van Rossum65810fe2006-05-26 19:12:38 +00002096 4: c GLOBAL 'copy_reg _reconstructor'
2097 29: q BINPUT 1
2098 31: ( MARK
2099 32: c GLOBAL 'pickletools _Example'
2100 54: q BINPUT 2
2101 56: c GLOBAL '__builtin__ object'
2102 76: q BINPUT 3
2103 78: N NONE
2104 79: t TUPLE (MARK at 31)
2105 80: q BINPUT 4
2106 82: R REDUCE
2107 83: q BINPUT 5
2108 85: } EMPTY_DICT
2109 86: q BINPUT 6
2110 88: U SHORT_BINSTRING 'value'
2111 95: q BINPUT 7
2112 97: K BININT1 42
2113 99: s SETITEM
2114 100: b BUILD
2115 101: h BINGET 5
2116 103: e APPENDS (MARK at 3)
2117 104: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002118highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002119
2120Try "the canonical" recursive-object test.
2121
2122>>> L = []
2123>>> T = L,
2124>>> L.append(T)
2125>>> L[0] is T
2126True
2127>>> T[0] is L
2128True
2129>>> L[0][0] is L
2130True
2131>>> T[0][0] is T
2132True
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002133>>> dis(pickle.dumps(L, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002134 0: ( MARK
2135 1: l LIST (MARK at 0)
2136 2: p PUT 0
2137 5: ( MARK
2138 6: g GET 0
2139 9: t TUPLE (MARK at 5)
2140 10: p PUT 1
2141 13: a APPEND
2142 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002143highest protocol among opcodes = 0
2144
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002145>>> dis(pickle.dumps(L, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002146 0: ] EMPTY_LIST
2147 1: q BINPUT 0
2148 3: ( MARK
2149 4: h BINGET 0
2150 6: t TUPLE (MARK at 3)
2151 7: q BINPUT 1
2152 9: a APPEND
2153 10: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002154highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002155
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002156Note that, in the protocol 0 pickle of the recursive tuple, the disassembler
2157has to emulate the stack in order to realize that the POP opcode at 16 gets
2158rid of the MARK at 0.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002159
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002160>>> dis(pickle.dumps(T, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002161 0: ( MARK
2162 1: ( MARK
2163 2: l LIST (MARK at 1)
2164 3: p PUT 0
2165 6: ( MARK
2166 7: g GET 0
2167 10: t TUPLE (MARK at 6)
2168 11: p PUT 1
2169 14: a APPEND
2170 15: 0 POP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002171 16: 0 POP (MARK at 0)
2172 17: g GET 1
2173 20: . STOP
2174highest protocol among opcodes = 0
2175
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002176>>> dis(pickle.dumps(T, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002177 0: ( MARK
2178 1: ] EMPTY_LIST
2179 2: q BINPUT 0
2180 4: ( MARK
2181 5: h BINGET 0
2182 7: t TUPLE (MARK at 4)
2183 8: q BINPUT 1
2184 10: a APPEND
2185 11: 1 POP_MARK (MARK at 0)
2186 12: h BINGET 1
2187 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002188highest protocol among opcodes = 1
Tim Petersd0f7c862003-01-28 15:27:57 +00002189
2190Try protocol 2.
2191
2192>>> dis(pickle.dumps(L, 2))
2193 0: \x80 PROTO 2
2194 2: ] EMPTY_LIST
2195 3: q BINPUT 0
2196 5: h BINGET 0
2197 7: \x85 TUPLE1
2198 8: q BINPUT 1
2199 10: a APPEND
2200 11: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002201highest protocol among opcodes = 2
Tim Petersd0f7c862003-01-28 15:27:57 +00002202
2203>>> dis(pickle.dumps(T, 2))
2204 0: \x80 PROTO 2
2205 2: ] EMPTY_LIST
2206 3: q BINPUT 0
2207 5: h BINGET 0
2208 7: \x85 TUPLE1
2209 8: q BINPUT 1
2210 10: a APPEND
2211 11: 0 POP
2212 12: h BINGET 1
2213 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002214highest protocol among opcodes = 2
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002215"""
2216
Tim Peters62235e72003-02-05 19:55:53 +00002217_memo_test = r"""
2218>>> import pickle
2219>>> from StringIO import StringIO
2220>>> f = StringIO()
2221>>> p = pickle.Pickler(f, 2)
2222>>> x = [1, 2, 3]
2223>>> p.dump(x)
2224>>> p.dump(x)
2225>>> f.seek(0)
2226>>> 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()