blob: 7eaa1a5d6dae3571eb5dc59481506d24a5edc0ee [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
9dis(pickle, out=None, indentlevel=4)
10 Print a symbolic disassembly of a pickle.
Skip Montanaro54455942003-01-29 15:41:33 +000011'''
Tim Peters8ecfc8e2003-01-27 18:51:48 +000012
13# Other ideas:
14#
15# - A pickle verifier: read a pickle and check it exhaustively for
Tim Petersc1c2b3e2003-01-29 20:12:21 +000016# well-formedness. dis() does a lot of this already.
Tim Peters8ecfc8e2003-01-27 18:51:48 +000017#
18# - A protocol identifier: examine a pickle and return its protocol number
19# (== the highest .proto attr value among all the opcodes in the pickle).
Tim Petersc1c2b3e2003-01-29 20:12:21 +000020# dis() already prints this info at the end.
Tim Peters8ecfc8e2003-01-27 18:51:48 +000021#
22# - A pickle optimizer: for example, tuple-building code is sometimes more
23# elaborate than necessary, catering for the possibility that the tuple
24# is recursive. Or lots of times a PUT is generated that's never accessed
25# by a later GET.
26
27
28"""
29"A pickle" is a program for a virtual pickle machine (PM, but more accurately
30called an unpickling machine). It's a sequence of opcodes, interpreted by the
31PM, building an arbitrarily complex Python object.
32
33For the most part, the PM is very simple: there are no looping, testing, or
34conditional instructions, no arithmetic and no function calls. Opcodes are
35executed once each, from first to last, until a STOP opcode is reached.
36
37The PM has two data areas, "the stack" and "the memo".
38
39Many opcodes push Python objects onto the stack; e.g., INT pushes a Python
40integer object on the stack, whose value is gotten from a decimal string
41literal immediately following the INT opcode in the pickle bytestream. Other
42opcodes take Python objects off the stack. The result of unpickling is
43whatever object is left on the stack when the final STOP opcode is executed.
44
45The memo is simply an array of objects, or it can be implemented as a dict
46mapping little integers to objects. The memo serves as the PM's "long term
47memory", and the little integers indexing the memo are akin to variable
48names. Some opcodes pop a stack object into the memo at a given index,
49and others push a memo object at a given index onto the stack again.
50
51At heart, that's all the PM has. Subtleties arise for these reasons:
52
53+ Object identity. Objects can be arbitrarily complex, and subobjects
54 may be shared (for example, the list [a, a] refers to the same object a
55 twice). It can be vital that unpickling recreate an isomorphic object
56 graph, faithfully reproducing sharing.
57
58+ Recursive objects. For example, after "L = []; L.append(L)", L is a
59 list, and L[0] is the same list. This is related to the object identity
60 point, and some sequences of pickle opcodes are subtle in order to
61 get the right result in all cases.
62
63+ Things pickle doesn't know everything about. Examples of things pickle
64 does know everything about are Python's builtin scalar and container
65 types, like ints and tuples. They generally have opcodes dedicated to
66 them. For things like module references and instances of user-defined
67 classes, pickle's knowledge is limited. Historically, many enhancements
68 have been made to the pickle protocol in order to do a better (faster,
69 and/or more compact) job on those.
70
71+ Backward compatibility and micro-optimization. As explained below,
72 pickle opcodes never go away, not even when better ways to do a thing
73 get invented. The repertoire of the PM just keeps growing over time.
Tim Petersfdc03462003-01-28 04:56:33 +000074 For example, protocol 0 had two opcodes for building Python integers (INT
75 and LONG), protocol 1 added three more for more-efficient pickling of short
76 integers, and protocol 2 added two more for more-efficient pickling of
77 long integers (before protocol 2, the only ways to pickle a Python long
78 took time quadratic in the number of digits, for both pickling and
79 unpickling). "Opcode bloat" isn't so much a subtlety as a source of
Tim Peters8ecfc8e2003-01-27 18:51:48 +000080 wearying complication.
81
82
83Pickle protocols:
84
85For compatibility, the meaning of a pickle opcode never changes. Instead new
86pickle opcodes get added, and each version's unpickler can handle all the
87pickle opcodes in all protocol versions to date. So old pickles continue to
88be readable forever. The pickler can generally be told to restrict itself to
89the subset of opcodes available under previous protocol versions too, so that
90users can create pickles under the current version readable by older
91versions. However, a pickle does not contain its version number embedded
92within it. If an older unpickler tries to read a pickle using a later
93protocol, the result is most likely an exception due to seeing an unknown (in
94the older unpickler) opcode.
95
96The original pickle used what's now called "protocol 0", and what was called
97"text mode" before Python 2.3. The entire pickle bytestream is made up of
98printable 7-bit ASCII characters, plus the newline character, in protocol 0.
Tim Petersfdc03462003-01-28 04:56:33 +000099That's why it was called text mode. Protocol 0 is small and elegant, but
100sometimes painfully inefficient.
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000101
102The second major set of additions is now called "protocol 1", and was called
103"binary mode" before Python 2.3. This added many opcodes with arguments
104consisting of arbitrary bytes, including NUL bytes and unprintable "high bit"
105bytes. Binary mode pickles can be substantially smaller than equivalent
106text mode pickles, and sometimes faster too; e.g., BININT represents a 4-byte
107int as 4 bytes following the opcode, which is cheaper to unpickle than the
Tim Petersfdc03462003-01-28 04:56:33 +0000108(perhaps) 11-character decimal string attached to INT. Protocol 1 also added
109a number of opcodes that operate on many stack elements at once (like APPENDS
Tim Peters81098ac2003-01-28 05:12:08 +0000110and SETITEMS), and "shortcut" opcodes (like EMPTY_DICT and EMPTY_TUPLE).
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000111
112The third major set of additions came in Python 2.3, and is called "protocol
Tim Petersfdc03462003-01-28 04:56:33 +00001132". This added:
114
115- A better way to pickle instances of new-style classes (NEWOBJ).
116
117- A way for a pickle to identify its protocol (PROTO).
118
119- Time- and space- efficient pickling of long ints (LONG{1,4}).
120
121- Shortcuts for small tuples (TUPLE{1,2,3}}.
122
123- Dedicated opcodes for bools (NEWTRUE, NEWFALSE).
124
125- The "extension registry", a vector of popular objects that can be pushed
126 efficiently by index (EXT{1,2,4}). This is akin to the memo and GET, but
127 the registry contents are predefined (there's nothing akin to the memo's
128 PUT).
Guido van Rossumecb11042003-01-29 06:24:30 +0000129
Skip Montanaro54455942003-01-29 15:41:33 +0000130Another independent change with Python 2.3 is the abandonment of any
131pretense that it might be safe to load pickles received from untrusted
Guido van Rossumecb11042003-01-29 06:24:30 +0000132parties -- no sufficient security analysis has been done to guarantee
Skip Montanaro54455942003-01-29 15:41:33 +0000133this and there isn't a use case that warrants the expense of such an
Guido van Rossumecb11042003-01-29 06:24:30 +0000134analysis.
135
136To this end, all tests for __safe_for_unpickling__ or for
137copy_reg.safe_constructors are removed from the unpickling code.
138References to these variables in the descriptions below are to be seen
139as describing unpickling in Python 2.2 and before.
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000140"""
141
142# Meta-rule: Descriptions are stored in instances of descriptor objects,
143# with plain constructors. No meta-language is defined from which
144# descriptors could be constructed. If you want, e.g., XML, write a little
145# program to generate XML from the objects.
146
147##############################################################################
148# Some pickle opcodes have an argument, following the opcode in the
149# bytestream. An argument is of a specific type, described by an instance
150# of ArgumentDescriptor. These are not to be confused with arguments taken
151# off the stack -- ArgumentDescriptor applies only to arguments embedded in
152# the opcode stream, immediately following an opcode.
153
154# Represents the number of bytes consumed by an argument delimited by the
155# next newline character.
156UP_TO_NEWLINE = -1
157
158# Represents the number of bytes consumed by a two-argument opcode where
159# the first argument gives the number of bytes in the second argument.
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000160TAKEN_FROM_ARGUMENT1 = -2 # num bytes is 1-byte unsigned int
161TAKEN_FROM_ARGUMENT4 = -3 # num bytes is 4-byte signed little-endian int
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000162
163class ArgumentDescriptor(object):
164 __slots__ = (
165 # name of descriptor record, also a module global name; a string
166 'name',
167
168 # length of argument, in bytes; an int; UP_TO_NEWLINE and
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000169 # TAKEN_FROM_ARGUMENT{1,4} are negative values for variable-length
170 # cases
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000171 'n',
172
173 # a function taking a file-like object, reading this kind of argument
174 # from the object at the current position, advancing the current
175 # position by n bytes, and returning the value of the argument
176 'reader',
177
178 # human-readable docs for this arg descriptor; a string
179 'doc',
180 )
181
182 def __init__(self, name, n, reader, doc):
183 assert isinstance(name, str)
184 self.name = name
185
186 assert isinstance(n, int) and (n >= 0 or
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000187 n in (UP_TO_NEWLINE,
188 TAKEN_FROM_ARGUMENT1,
189 TAKEN_FROM_ARGUMENT4))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000190 self.n = n
191
192 self.reader = reader
193
194 assert isinstance(doc, str)
195 self.doc = doc
196
197from struct import unpack as _unpack
198
199def read_uint1(f):
Tim Peters55762f52003-01-28 16:01:25 +0000200 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000201 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000202 >>> read_uint1(StringIO.StringIO('\xff'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000203 255
204 """
205
206 data = f.read(1)
207 if data:
208 return ord(data)
209 raise ValueError("not enough data in stream to read uint1")
210
211uint1 = ArgumentDescriptor(
212 name='uint1',
213 n=1,
214 reader=read_uint1,
215 doc="One-byte unsigned integer.")
216
217
218def read_uint2(f):
Tim Peters55762f52003-01-28 16:01:25 +0000219 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000220 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000221 >>> read_uint2(StringIO.StringIO('\xff\x00'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000222 255
Tim Peters55762f52003-01-28 16:01:25 +0000223 >>> read_uint2(StringIO.StringIO('\xff\xff'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000224 65535
225 """
226
227 data = f.read(2)
228 if len(data) == 2:
229 return _unpack("<H", data)[0]
230 raise ValueError("not enough data in stream to read uint2")
231
232uint2 = ArgumentDescriptor(
233 name='uint2',
234 n=2,
235 reader=read_uint2,
236 doc="Two-byte unsigned integer, little-endian.")
237
238
239def read_int4(f):
Tim Peters55762f52003-01-28 16:01:25 +0000240 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000241 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000242 >>> read_int4(StringIO.StringIO('\xff\x00\x00\x00'))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000243 255
Tim Peters55762f52003-01-28 16:01:25 +0000244 >>> read_int4(StringIO.StringIO('\x00\x00\x00\x80')) == -(2**31)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000245 True
246 """
247
248 data = f.read(4)
249 if len(data) == 4:
250 return _unpack("<i", data)[0]
251 raise ValueError("not enough data in stream to read int4")
252
253int4 = ArgumentDescriptor(
254 name='int4',
255 n=4,
256 reader=read_int4,
257 doc="Four-byte signed integer, little-endian, 2's complement.")
258
259
260def read_stringnl(f, decode=True, stripquotes=True):
Tim Peters55762f52003-01-28 16:01:25 +0000261 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000262 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000263 >>> read_stringnl(StringIO.StringIO("'abcd'\nefg\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000264 'abcd'
265
Tim Peters55762f52003-01-28 16:01:25 +0000266 >>> read_stringnl(StringIO.StringIO("\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000267 Traceback (most recent call last):
268 ...
269 ValueError: no string quotes around ''
270
Tim Peters55762f52003-01-28 16:01:25 +0000271 >>> read_stringnl(StringIO.StringIO("\n"), stripquotes=False)
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000272 ''
273
Tim Peters55762f52003-01-28 16:01:25 +0000274 >>> read_stringnl(StringIO.StringIO("''\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000275 ''
276
277 >>> read_stringnl(StringIO.StringIO('"abcd"'))
278 Traceback (most recent call last):
279 ...
280 ValueError: no newline found when trying to read stringnl
281
282 Embedded escapes are undone in the result.
Tim Peters55762f52003-01-28 16:01:25 +0000283 >>> read_stringnl(StringIO.StringIO(r"'a\n\\b\x00c\td'" + "\n'e'"))
284 'a\n\\b\x00c\td'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000285 """
286
287 data = f.readline()
288 if not data.endswith('\n'):
289 raise ValueError("no newline found when trying to read stringnl")
290 data = data[:-1] # lose the newline
291
292 if stripquotes:
293 for q in "'\"":
294 if data.startswith(q):
295 if not data.endswith(q):
296 raise ValueError("strinq quote %r not found at both "
297 "ends of %r" % (q, data))
298 data = data[1:-1]
299 break
300 else:
301 raise ValueError("no string quotes around %r" % data)
302
303 # I'm not sure when 'string_escape' was added to the std codecs; it's
304 # crazy not to use it if it's there.
305 if decode:
306 data = data.decode('string_escape')
307 return data
308
309stringnl = ArgumentDescriptor(
310 name='stringnl',
311 n=UP_TO_NEWLINE,
312 reader=read_stringnl,
313 doc="""A newline-terminated string.
314
315 This is a repr-style string, with embedded escapes, and
316 bracketing quotes.
317 """)
318
319def read_stringnl_noescape(f):
320 return read_stringnl(f, decode=False, stripquotes=False)
321
322stringnl_noescape = ArgumentDescriptor(
323 name='stringnl_noescape',
324 n=UP_TO_NEWLINE,
325 reader=read_stringnl_noescape,
326 doc="""A newline-terminated string.
327
328 This is a str-style string, without embedded escapes,
329 or bracketing quotes. It should consist solely of
330 printable ASCII characters.
331 """)
332
333def read_stringnl_noescape_pair(f):
Tim Peters55762f52003-01-28 16:01:25 +0000334 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000335 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000336 >>> read_stringnl_noescape_pair(StringIO.StringIO("Queue\nEmpty\njunk"))
Tim Petersd916cf42003-01-27 19:01:47 +0000337 'Queue Empty'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000338 """
339
Tim Petersd916cf42003-01-27 19:01:47 +0000340 return "%s %s" % (read_stringnl_noescape(f), read_stringnl_noescape(f))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000341
342stringnl_noescape_pair = ArgumentDescriptor(
343 name='stringnl_noescape_pair',
344 n=UP_TO_NEWLINE,
345 reader=read_stringnl_noescape_pair,
346 doc="""A pair of newline-terminated strings.
347
348 These are str-style strings, without embedded
349 escapes, or bracketing quotes. They should
350 consist solely of printable ASCII characters.
351 The pair is returned as a single string, with
Tim Petersd916cf42003-01-27 19:01:47 +0000352 a single blank separating the two strings.
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000353 """)
354
355def read_string4(f):
Tim Peters55762f52003-01-28 16:01:25 +0000356 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000357 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000358 >>> read_string4(StringIO.StringIO("\x00\x00\x00\x00abc"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000359 ''
Tim Peters55762f52003-01-28 16:01:25 +0000360 >>> read_string4(StringIO.StringIO("\x03\x00\x00\x00abcdef"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000361 'abc'
Tim Peters55762f52003-01-28 16:01:25 +0000362 >>> read_string4(StringIO.StringIO("\x00\x00\x00\x03abcdef"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000363 Traceback (most recent call last):
364 ...
365 ValueError: expected 50331648 bytes in a string4, but only 6 remain
366 """
367
368 n = read_int4(f)
369 if n < 0:
370 raise ValueError("string4 byte count < 0: %d" % n)
371 data = f.read(n)
372 if len(data) == n:
373 return data
374 raise ValueError("expected %d bytes in a string4, but only %d remain" %
375 (n, len(data)))
376
377string4 = ArgumentDescriptor(
378 name="string4",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000379 n=TAKEN_FROM_ARGUMENT4,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000380 reader=read_string4,
381 doc="""A counted string.
382
383 The first argument is a 4-byte little-endian signed int giving
384 the number of bytes in the string, and the second argument is
385 that many bytes.
386 """)
387
388
389def read_string1(f):
Tim Peters55762f52003-01-28 16:01:25 +0000390 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000391 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000392 >>> read_string1(StringIO.StringIO("\x00"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000393 ''
Tim Peters55762f52003-01-28 16:01:25 +0000394 >>> read_string1(StringIO.StringIO("\x03abcdef"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000395 'abc'
396 """
397
398 n = read_uint1(f)
399 assert n >= 0
400 data = f.read(n)
401 if len(data) == n:
402 return data
403 raise ValueError("expected %d bytes in a string1, but only %d remain" %
404 (n, len(data)))
405
406string1 = ArgumentDescriptor(
407 name="string1",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000408 n=TAKEN_FROM_ARGUMENT1,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000409 reader=read_string1,
410 doc="""A counted string.
411
412 The first argument is a 1-byte unsigned int giving the number
413 of bytes in the string, and the second argument is that many
414 bytes.
415 """)
416
417
418def read_unicodestringnl(f):
Tim Peters55762f52003-01-28 16:01:25 +0000419 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000420 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000421 >>> read_unicodestringnl(StringIO.StringIO("abc\uabcd\njunk"))
422 u'abc\uabcd'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000423 """
424
425 data = f.readline()
426 if not data.endswith('\n'):
427 raise ValueError("no newline found when trying to read "
428 "unicodestringnl")
429 data = data[:-1] # lose the newline
430 return unicode(data, 'raw-unicode-escape')
431
432unicodestringnl = ArgumentDescriptor(
433 name='unicodestringnl',
434 n=UP_TO_NEWLINE,
435 reader=read_unicodestringnl,
436 doc="""A newline-terminated Unicode string.
437
438 This is raw-unicode-escape encoded, so consists of
439 printable ASCII characters, and may contain embedded
440 escape sequences.
441 """)
442
443def read_unicodestring4(f):
Tim Peters55762f52003-01-28 16:01:25 +0000444 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000445 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000446 >>> s = u'abcd\uabcd'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000447 >>> enc = s.encode('utf-8')
448 >>> enc
Tim Peters55762f52003-01-28 16:01:25 +0000449 'abcd\xea\xaf\x8d'
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000450 >>> n = chr(len(enc)) + chr(0) * 3 # little-endian 4-byte length
451 >>> t = read_unicodestring4(StringIO.StringIO(n + enc + 'junk'))
452 >>> s == t
453 True
454
455 >>> read_unicodestring4(StringIO.StringIO(n + enc[:-1]))
456 Traceback (most recent call last):
457 ...
458 ValueError: expected 7 bytes in a unicodestring4, but only 6 remain
459 """
460
461 n = read_int4(f)
462 if n < 0:
463 raise ValueError("unicodestring4 byte count < 0: %d" % n)
464 data = f.read(n)
465 if len(data) == n:
466 return unicode(data, 'utf-8')
467 raise ValueError("expected %d bytes in a unicodestring4, but only %d "
468 "remain" % (n, len(data)))
469
470unicodestring4 = ArgumentDescriptor(
471 name="unicodestring4",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000472 n=TAKEN_FROM_ARGUMENT4,
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000473 reader=read_unicodestring4,
474 doc="""A counted Unicode string.
475
476 The first argument is a 4-byte little-endian signed int
477 giving the number of bytes in the string, and the second
478 argument-- the UTF-8 encoding of the Unicode string --
479 contains that many bytes.
480 """)
481
482
483def read_decimalnl_short(f):
Tim Peters55762f52003-01-28 16:01:25 +0000484 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000485 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000486 >>> read_decimalnl_short(StringIO.StringIO("1234\n56"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000487 1234
488
Tim Peters55762f52003-01-28 16:01:25 +0000489 >>> read_decimalnl_short(StringIO.StringIO("1234L\n56"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000490 Traceback (most recent call last):
491 ...
492 ValueError: trailing 'L' not allowed in '1234L'
493 """
494
495 s = read_stringnl(f, decode=False, stripquotes=False)
496 if s.endswith("L"):
497 raise ValueError("trailing 'L' not allowed in %r" % s)
498
499 # It's not necessarily true that the result fits in a Python short int:
500 # the pickle may have been written on a 64-bit box. There's also a hack
501 # for True and False here.
502 if s == "00":
503 return False
504 elif s == "01":
505 return True
506
507 try:
508 return int(s)
509 except OverflowError:
510 return long(s)
511
512def read_decimalnl_long(f):
Tim Peters55762f52003-01-28 16:01:25 +0000513 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000514 >>> import StringIO
515
Tim Peters55762f52003-01-28 16:01:25 +0000516 >>> read_decimalnl_long(StringIO.StringIO("1234\n56"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000517 Traceback (most recent call last):
518 ...
519 ValueError: trailing 'L' required in '1234'
520
521 Someday the trailing 'L' will probably go away from this output.
522
Tim Peters55762f52003-01-28 16:01:25 +0000523 >>> read_decimalnl_long(StringIO.StringIO("1234L\n56"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000524 1234L
525
Tim Peters55762f52003-01-28 16:01:25 +0000526 >>> read_decimalnl_long(StringIO.StringIO("123456789012345678901234L\n6"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000527 123456789012345678901234L
528 """
529
530 s = read_stringnl(f, decode=False, stripquotes=False)
531 if not s.endswith("L"):
532 raise ValueError("trailing 'L' required in %r" % s)
533 return long(s)
534
535
536decimalnl_short = ArgumentDescriptor(
537 name='decimalnl_short',
538 n=UP_TO_NEWLINE,
539 reader=read_decimalnl_short,
540 doc="""A newline-terminated decimal integer literal.
541
542 This never has a trailing 'L', and the integer fit
543 in a short Python int on the box where the pickle
544 was written -- but there's no guarantee it will fit
545 in a short Python int on the box where the pickle
546 is read.
547 """)
548
549decimalnl_long = ArgumentDescriptor(
550 name='decimalnl_long',
551 n=UP_TO_NEWLINE,
552 reader=read_decimalnl_long,
553 doc="""A newline-terminated decimal integer literal.
554
555 This has a trailing 'L', and can represent integers
556 of any size.
557 """)
558
559
560def read_floatnl(f):
Tim Peters55762f52003-01-28 16:01:25 +0000561 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000562 >>> import StringIO
Tim Peters55762f52003-01-28 16:01:25 +0000563 >>> read_floatnl(StringIO.StringIO("-1.25\n6"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000564 -1.25
565 """
566 s = read_stringnl(f, decode=False, stripquotes=False)
567 return float(s)
568
569floatnl = ArgumentDescriptor(
570 name='floatnl',
571 n=UP_TO_NEWLINE,
572 reader=read_floatnl,
573 doc="""A newline-terminated decimal floating literal.
574
575 In general this requires 17 significant digits for roundtrip
576 identity, and pickling then unpickling infinities, NaNs, and
577 minus zero doesn't work across boxes, or on some boxes even
578 on itself (e.g., Windows can't read the strings it produces
579 for infinities or NaNs).
580 """)
581
582def read_float8(f):
Tim Peters55762f52003-01-28 16:01:25 +0000583 r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000584 >>> import StringIO, struct
585 >>> raw = struct.pack(">d", -1.25)
586 >>> raw
Tim Peters55762f52003-01-28 16:01:25 +0000587 '\xbf\xf4\x00\x00\x00\x00\x00\x00'
588 >>> read_float8(StringIO.StringIO(raw + "\n"))
Tim Peters8ecfc8e2003-01-27 18:51:48 +0000589 -1.25
590 """
591
592 data = f.read(8)
593 if len(data) == 8:
594 return _unpack(">d", data)[0]
595 raise ValueError("not enough data in stream to read float8")
596
597
598float8 = ArgumentDescriptor(
599 name='float8',
600 n=8,
601 reader=read_float8,
602 doc="""An 8-byte binary representation of a float, big-endian.
603
604 The format is unique to Python, and shared with the struct
605 module (format string '>d') "in theory" (the struct and cPickle
606 implementations don't share the code -- they should). It's
607 strongly related to the IEEE-754 double format, and, in normal
608 cases, is in fact identical to the big-endian 754 double format.
609 On other boxes the dynamic range is limited to that of a 754
610 double, and "add a half and chop" rounding is used to reduce
611 the precision to 53 bits. However, even on a 754 box,
612 infinities, NaNs, and minus zero may not be handled correctly
613 (may not survive roundtrip pickling intact).
614 """)
615
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000616# Protocol 2 formats
617
Tim Petersc0c12b52003-01-29 00:56:17 +0000618from pickle import decode_long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000619
620def read_long1(f):
621 r"""
622 >>> import StringIO
623 >>> read_long1(StringIO.StringIO("\x02\xff\x00"))
624 255L
625 >>> read_long1(StringIO.StringIO("\x02\xff\x7f"))
626 32767L
627 >>> read_long1(StringIO.StringIO("\x02\x00\xff"))
628 -256L
629 >>> read_long1(StringIO.StringIO("\x02\x00\x80"))
630 -32768L
Tim Peters5eed3402003-01-27 23:51:36 +0000631 >>>
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000632 """
633
634 n = read_uint1(f)
635 data = f.read(n)
636 if len(data) != n:
637 raise ValueError("not enough data in stream to read long1")
638 return decode_long(data)
639
640long1 = ArgumentDescriptor(
641 name="long1",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000642 n=TAKEN_FROM_ARGUMENT1,
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000643 reader=read_long1,
644 doc="""A binary long, little-endian, using 1-byte size.
645
646 This first reads one byte as an unsigned size, then reads that
Tim Petersbdbe7412003-01-27 23:54:04 +0000647 many bytes and interprets them as a little-endian 2's-complement long.
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000648 """)
649
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000650def read_long4(f):
651 r"""
652 >>> import StringIO
653 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00"))
654 255L
655 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f"))
656 32767L
657 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff"))
658 -256L
659 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80"))
660 -32768L
Tim Peters5eed3402003-01-27 23:51:36 +0000661 >>>
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000662 """
663
664 n = read_int4(f)
665 if n < 0:
Neal Norwitz784a3f52003-01-28 00:20:41 +0000666 raise ValueError("long4 byte count < 0: %d" % n)
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000667 data = f.read(n)
668 if len(data) != n:
Neal Norwitz784a3f52003-01-28 00:20:41 +0000669 raise ValueError("not enough data in stream to read long4")
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000670 return decode_long(data)
671
672long4 = ArgumentDescriptor(
673 name="long4",
Tim Petersfdb8cfa2003-01-28 00:13:19 +0000674 n=TAKEN_FROM_ARGUMENT4,
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000675 reader=read_long4,
676 doc="""A binary representation of a long, little-endian.
677
678 This first reads four bytes as a signed size (but requires the
679 size to be >= 0), then reads that many bytes and interprets them
Tim Petersbdbe7412003-01-27 23:54:04 +0000680 as a little-endian 2's-complement long.
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',
727 obtype=long,
728 doc="A long (as opposed to short) Python integer object.")
729
730pyinteger_or_bool = StackObject(
731 name='int_or_bool',
732 obtype=(int, long, bool),
733 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',
753 obtype=unicode,
754 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
1520 There are lots of special cases here. The argtuple can be None, in
1521 which case callable.__basicnew__() is called instead to produce the
1522 object to be pushed on the stack. This appears to be a trick unique
1523 to ExtensionClasses, and is deprecated regardless.
1524
1525 If type(callable) is not ClassType, REDUCE complains unless the
1526 callable has been registered with the copy_reg module's
1527 safe_constructors dict, or the callable has a magic
1528 '__safe_for_unpickling__' attribute with a true value. I'm not sure
1529 why it does this, but I've sure seen this complaint often enough when
1530 I didn't want to <wink>.
1531 """),
1532
1533 I(name='BUILD',
1534 code='b',
1535 arg=None,
1536 stack_before=[anyobject, anyobject],
1537 stack_after=[anyobject],
1538 proto=0,
1539 doc="""Finish building an object, via __setstate__ or dict update.
1540
1541 Stack before: ... anyobject argument
1542 Stack after: ... anyobject
1543
1544 where anyobject may have been mutated, as follows:
1545
1546 If the object has a __setstate__ method,
1547
1548 anyobject.__setstate__(argument)
1549
1550 is called.
1551
1552 Else the argument must be a dict, the object must have a __dict__, and
1553 the object is updated via
1554
1555 anyobject.__dict__.update(argument)
1556
1557 This may raise RuntimeError in restricted execution mode (which
1558 disallows access to __dict__ directly); in that case, the object
1559 is updated instead via
1560
1561 for k, v in argument.items():
1562 anyobject[k] = v
1563 """),
1564
1565 I(name='INST',
1566 code='i',
1567 arg=stringnl_noescape_pair,
1568 stack_before=[markobject, stackslice],
1569 stack_after=[anyobject],
1570 proto=0,
1571 doc="""Build a class instance.
1572
1573 This is the protocol 0 version of protocol 1's OBJ opcode.
1574 INST is followed by two newline-terminated strings, giving a
1575 module and class name, just as for the GLOBAL opcode (and see
1576 GLOBAL for more details about that). self.find_class(module, name)
1577 is used to get a class object.
1578
1579 In addition, all the objects on the stack following the topmost
1580 markobject are gathered into a tuple and popped (along with the
1581 topmost markobject), just as for the TUPLE opcode.
1582
1583 Now it gets complicated. If all of these are true:
1584
1585 + The argtuple is empty (markobject was at the top of the stack
1586 at the start).
1587
1588 + It's an old-style class object (the type of the class object is
1589 ClassType).
1590
1591 + The class object does not have a __getinitargs__ attribute.
1592
1593 then we want to create an old-style class instance without invoking
1594 its __init__() method (pickle has waffled on this over the years; not
1595 calling __init__() is current wisdom). In this case, an instance of
1596 an old-style dummy class is created, and then we try to rebind its
1597 __class__ attribute to the desired class object. If this succeeds,
1598 the new instance object is pushed on the stack, and we're done. In
1599 restricted execution mode it can fail (assignment to __class__ is
1600 disallowed), and I'm not really sure what happens then -- it looks
1601 like the code ends up calling the class object's __init__ anyway,
1602 via falling into the next case.
1603
1604 Else (the argtuple is not empty, it's not an old-style class object,
1605 or the class object does have a __getinitargs__ attribute), the code
1606 first insists that the class object have a __safe_for_unpickling__
1607 attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE,
1608 it doesn't matter whether this attribute has a true or false value, it
Guido van Rossumecb11042003-01-29 06:24:30 +00001609 only matters whether it exists (XXX this is a bug; cPickle
1610 requires the attribute to be true). If __safe_for_unpickling__
1611 doesn't exist, UnpicklingError is raised.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001612
1613 Else (the class object does have a __safe_for_unpickling__ attr),
1614 the class object obtained from INST's arguments is applied to the
1615 argtuple obtained from the stack, and the resulting instance object
1616 is pushed on the stack.
1617 """),
1618
1619 I(name='OBJ',
1620 code='o',
1621 arg=None,
1622 stack_before=[markobject, anyobject, stackslice],
1623 stack_after=[anyobject],
1624 proto=1,
1625 doc="""Build a class instance.
1626
1627 This is the protocol 1 version of protocol 0's INST opcode, and is
1628 very much like it. The major difference is that the class object
1629 is taken off the stack, allowing it to be retrieved from the memo
1630 repeatedly if several instances of the same class are created. This
1631 can be much more efficient (in both time and space) than repeatedly
1632 embedding the module and class names in INST opcodes.
1633
1634 Unlike INST, OBJ takes no arguments from the opcode stream. Instead
1635 the class object is taken off the stack, immediately above the
1636 topmost markobject:
1637
1638 Stack before: ... markobject classobject stackslice
1639 Stack after: ... new_instance_object
1640
1641 As for INST, the remainder of the stack above the markobject is
1642 gathered into an argument tuple, and then the logic seems identical,
Guido van Rossumecb11042003-01-29 06:24:30 +00001643 except that no __safe_for_unpickling__ check is done (XXX this is
1644 a bug; cPickle does test __safe_for_unpickling__). See INST for
1645 the gory details.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001646 """),
1647
Tim Petersfdc03462003-01-28 04:56:33 +00001648 I(name='NEWOBJ',
1649 code='\x81',
1650 arg=None,
1651 stack_before=[anyobject, anyobject],
1652 stack_after=[anyobject],
1653 proto=2,
1654 doc="""Build an object instance.
1655
1656 The stack before should be thought of as containing a class
1657 object followed by an argument tuple (the tuple being the stack
1658 top). Call these cls and args. They are popped off the stack,
1659 and the value returned by cls.__new__(cls, *args) is pushed back
1660 onto the stack.
1661 """),
1662
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001663 # Machine control.
1664
Tim Petersfdc03462003-01-28 04:56:33 +00001665 I(name='PROTO',
1666 code='\x80',
1667 arg=uint1,
1668 stack_before=[],
1669 stack_after=[],
1670 proto=2,
1671 doc="""Protocol version indicator.
1672
1673 For protocol 2 and above, a pickle must start with this opcode.
1674 The argument is the protocol version, an int in range(2, 256).
1675 """),
1676
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001677 I(name='STOP',
1678 code='.',
1679 arg=None,
1680 stack_before=[anyobject],
1681 stack_after=[],
1682 proto=0,
1683 doc="""Stop the unpickling machine.
1684
1685 Every pickle ends with this opcode. The object at the top of the stack
1686 is popped, and that's the result of unpickling. The stack should be
1687 empty then.
1688 """),
1689
1690 # Ways to deal with persistent IDs.
1691
1692 I(name='PERSID',
1693 code='P',
1694 arg=stringnl_noescape,
1695 stack_before=[],
1696 stack_after=[anyobject],
1697 proto=0,
1698 doc="""Push an object identified by a persistent ID.
1699
1700 The pickle module doesn't define what a persistent ID means. PERSID's
1701 argument is a newline-terminated str-style (no embedded escapes, no
1702 bracketing quote characters) string, which *is* "the persistent ID".
1703 The unpickler passes this string to self.persistent_load(). Whatever
1704 object that returns is pushed on the stack. There is no implementation
1705 of persistent_load() in Python's unpickler: it must be supplied by an
1706 unpickler subclass.
1707 """),
1708
1709 I(name='BINPERSID',
1710 code='Q',
1711 arg=None,
1712 stack_before=[anyobject],
1713 stack_after=[anyobject],
1714 proto=1,
1715 doc="""Push an object identified by a persistent ID.
1716
1717 Like PERSID, except the persistent ID is popped off the stack (instead
1718 of being a string embedded in the opcode bytestream). The persistent
1719 ID is passed to self.persistent_load(), and whatever object that
1720 returns is pushed on the stack. See PERSID for more detail.
1721 """),
1722]
1723del I
1724
1725# Verify uniqueness of .name and .code members.
1726name2i = {}
1727code2i = {}
1728
1729for i, d in enumerate(opcodes):
1730 if d.name in name2i:
1731 raise ValueError("repeated name %r at indices %d and %d" %
1732 (d.name, name2i[d.name], i))
1733 if d.code in code2i:
1734 raise ValueError("repeated code %r at indices %d and %d" %
1735 (d.code, code2i[d.code], i))
1736
1737 name2i[d.name] = i
1738 code2i[d.code] = i
1739
1740del name2i, code2i, i, d
1741
1742##############################################################################
1743# Build a code2op dict, mapping opcode characters to OpcodeInfo records.
1744# Also ensure we've got the same stuff as pickle.py, although the
1745# introspection here is dicey.
1746
1747code2op = {}
1748for d in opcodes:
1749 code2op[d.code] = d
1750del d
1751
1752def assure_pickle_consistency(verbose=False):
1753 import pickle, re
1754
1755 copy = code2op.copy()
1756 for name in pickle.__all__:
1757 if not re.match("[A-Z][A-Z0-9_]+$", name):
1758 if verbose:
1759 print "skipping %r: it doesn't look like an opcode name" % name
1760 continue
1761 picklecode = getattr(pickle, name)
1762 if not isinstance(picklecode, str) or len(picklecode) != 1:
1763 if verbose:
1764 print ("skipping %r: value %r doesn't look like a pickle "
1765 "code" % (name, picklecode))
1766 continue
1767 if picklecode in copy:
1768 if verbose:
1769 print "checking name %r w/ code %r for consistency" % (
1770 name, picklecode)
1771 d = copy[picklecode]
1772 if d.name != name:
1773 raise ValueError("for pickle code %r, pickle.py uses name %r "
1774 "but we're using name %r" % (picklecode,
1775 name,
1776 d.name))
1777 # Forget this one. Any left over in copy at the end are a problem
1778 # of a different kind.
1779 del copy[picklecode]
1780 else:
1781 raise ValueError("pickle.py appears to have a pickle opcode with "
1782 "name %r and code %r, but we don't" %
1783 (name, picklecode))
1784 if copy:
1785 msg = ["we appear to have pickle opcodes that pickle.py doesn't have:"]
1786 for code, d in copy.items():
1787 msg.append(" name %r with code %r" % (d.name, code))
1788 raise ValueError("\n".join(msg))
1789
1790assure_pickle_consistency()
Tim Petersc0c12b52003-01-29 00:56:17 +00001791del assure_pickle_consistency
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001792
1793##############################################################################
1794# A pickle opcode generator.
1795
1796def genops(pickle):
Guido van Rossuma72ded92003-01-27 19:40:47 +00001797 """Generate all the opcodes in a pickle.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001798
1799 'pickle' is a file-like object, or string, containing the pickle.
1800
1801 Each opcode in the pickle is generated, from the current pickle position,
1802 stopping after a STOP opcode is delivered. A triple is generated for
1803 each opcode:
1804
1805 opcode, arg, pos
1806
1807 opcode is an OpcodeInfo record, describing the current opcode.
1808
1809 If the opcode has an argument embedded in the pickle, arg is its decoded
1810 value, as a Python object. If the opcode doesn't have an argument, arg
1811 is None.
1812
1813 If the pickle has a tell() method, pos was the value of pickle.tell()
1814 before reading the current opcode. If the pickle is a string object,
1815 it's wrapped in a StringIO object, and the latter's tell() result is
1816 used. Else (the pickle doesn't have a tell(), and it's not obvious how
1817 to query its current position) pos is None.
1818 """
1819
1820 import cStringIO as StringIO
1821
1822 if isinstance(pickle, str):
1823 pickle = StringIO.StringIO(pickle)
1824
1825 if hasattr(pickle, "tell"):
1826 getpos = pickle.tell
1827 else:
1828 getpos = lambda: None
1829
1830 while True:
1831 pos = getpos()
1832 code = pickle.read(1)
1833 opcode = code2op.get(code)
1834 if opcode is None:
1835 if code == "":
1836 raise ValueError("pickle exhausted before seeing STOP")
1837 else:
1838 raise ValueError("at position %s, opcode %r unknown" % (
1839 pos is None and "<unknown>" or pos,
1840 code))
1841 if opcode.arg is None:
1842 arg = None
1843 else:
1844 arg = opcode.arg.reader(pickle)
1845 yield opcode, arg, pos
1846 if code == '.':
1847 assert opcode.name == 'STOP'
1848 break
1849
1850##############################################################################
1851# A symbolic pickle disassembler.
1852
1853def dis(pickle, out=None, indentlevel=4):
1854 """Produce a symbolic disassembly of a pickle.
1855
1856 'pickle' is a file-like object, or string, containing a (at least one)
1857 pickle. The pickle is disassembled from the current position, through
1858 the first STOP opcode encountered.
1859
1860 Optional arg 'out' is a file-like object to which the disassembly is
1861 printed. It defaults to sys.stdout.
1862
1863 Optional arg indentlevel is the number of blanks by which to indent
1864 a new MARK level. It defaults to 4.
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001865
1866 In addition to printing the disassembly, some sanity checks are made:
1867
1868 + All embedded opcode arguments "make sense".
1869
1870 + Explicit and implicit pop operations have enough items on the stack.
1871
1872 + When an opcode implicitly refers to a markobject, a markobject is
1873 actually on the stack.
1874
1875 + A memo entry isn't referenced before it's defined.
1876
1877 + The markobject isn't stored in the memo.
1878
1879 + A memo entry isn't redefined.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001880 """
1881
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001882 # Most of the hair here is for sanity checks, but most of it is needed
1883 # anyway to detect when a protocol 0 POP takes a MARK off the stack
1884 # (which in turn is needed to indent MARK blocks correctly).
1885
1886 stack = [] # crude emulation of unpickler stack
1887 memo = {} # crude emulation of unpicker memo
1888 maxproto = -1 # max protocol number seen
1889 markstack = [] # bytecode positions of MARK opcodes
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001890 indentchunk = ' ' * indentlevel
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001891 errormsg = None
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001892 for opcode, arg, pos in genops(pickle):
1893 if pos is not None:
1894 print >> out, "%5d:" % pos,
1895
Tim Petersd0f7c862003-01-28 15:27:57 +00001896 line = "%-4s %s%s" % (repr(opcode.code)[1:-1],
1897 indentchunk * len(markstack),
1898 opcode.name)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001899
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001900 maxproto = max(maxproto, opcode.proto)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001901 before = opcode.stack_before # don't mutate
1902 after = opcode.stack_after # don't mutate
Tim Peters43277d62003-01-30 15:02:12 +00001903 numtopop = len(before)
1904
1905 # See whether a MARK should be popped.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001906 markmsg = None
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001907 if markobject in before or (opcode.name == "POP" and
1908 stack and
1909 stack[-1] is markobject):
1910 assert markobject not in after
Tim Peters43277d62003-01-30 15:02:12 +00001911 if __debug__:
1912 if markobject in before:
1913 assert before[-1] is stackslice
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001914 if markstack:
1915 markpos = markstack.pop()
1916 if markpos is None:
1917 markmsg = "(MARK at unknown opcode offset)"
1918 else:
1919 markmsg = "(MARK at %d)" % markpos
1920 # Pop everything at and after the topmost markobject.
1921 while stack[-1] is not markobject:
1922 stack.pop()
1923 stack.pop()
Tim Peters43277d62003-01-30 15:02:12 +00001924 # Stop later code from popping too much.
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001925 try:
Tim Peters43277d62003-01-30 15:02:12 +00001926 numtopop = before.index(markobject)
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001927 except ValueError:
1928 assert opcode.name == "POP"
Tim Peters43277d62003-01-30 15:02:12 +00001929 numtopop = 0
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001930 else:
1931 errormsg = markmsg = "no MARK exists on stack"
1932
1933 # Check for correct memo usage.
1934 if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"):
Tim Peters43277d62003-01-30 15:02:12 +00001935 assert arg is not None
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001936 if arg in memo:
1937 errormsg = "memo key %r already defined" % arg
1938 elif not stack:
1939 errormsg = "stack is empty -- can't store into memo"
1940 elif stack[-1] is markobject:
1941 errormsg = "can't store markobject in the memo"
1942 else:
1943 memo[arg] = stack[-1]
1944
1945 elif opcode.name in ("GET", "BINGET", "LONG_BINGET"):
1946 if arg in memo:
1947 assert len(after) == 1
1948 after = [memo[arg]] # for better stack emulation
1949 else:
1950 errormsg = "memo key %r has never been stored into" % arg
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001951
1952 if arg is not None or markmsg:
1953 # make a mild effort to align arguments
1954 line += ' ' * (10 - len(opcode.name))
1955 if arg is not None:
1956 line += ' ' + repr(arg)
1957 if markmsg:
1958 line += ' ' + markmsg
1959 print >> out, line
1960
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001961 if errormsg:
1962 # Note that we delayed complaining until the offending opcode
1963 # was printed.
1964 raise ValueError(errormsg)
1965
1966 # Emulate the stack effects.
Tim Peters43277d62003-01-30 15:02:12 +00001967 if len(stack) < numtopop:
1968 raise ValueError("tries to pop %d items from stack with "
1969 "only %d items" % (numtopop, len(stack)))
1970 if numtopop:
1971 del stack[-numtopop:]
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001972 if markobject in after:
Tim Peters43277d62003-01-30 15:02:12 +00001973 assert markobject not in before
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001974 markstack.append(pos)
1975
Tim Petersc1c2b3e2003-01-29 20:12:21 +00001976 stack.extend(after)
1977
1978 print >> out, "highest protocol among opcodes =", maxproto
1979 if stack:
1980 raise ValueError("stack not empty after STOP: %r" % stack)
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001981
Guido van Rossum03e35322003-01-28 15:37:13 +00001982_dis_test = r"""
Tim Peters8ecfc8e2003-01-27 18:51:48 +00001983>>> import pickle
1984>>> x = [1, 2, (3, 4), {'abc': u"def"}]
Guido van Rossum57028352003-01-28 15:09:10 +00001985>>> pkl = pickle.dumps(x, 0)
1986>>> dis(pkl)
Tim Petersd0f7c862003-01-28 15:27:57 +00001987 0: ( MARK
1988 1: l LIST (MARK at 0)
1989 2: p PUT 0
1990 5: I INT 1
1991 8: a APPEND
1992 9: I INT 2
1993 12: a APPEND
1994 13: ( MARK
1995 14: I INT 3
1996 17: I INT 4
1997 20: t TUPLE (MARK at 13)
1998 21: p PUT 1
1999 24: a APPEND
2000 25: ( MARK
2001 26: d DICT (MARK at 25)
2002 27: p PUT 2
2003 30: S STRING 'abc'
2004 37: p PUT 3
2005 40: V UNICODE u'def'
2006 45: p PUT 4
2007 48: s SETITEM
2008 49: a APPEND
2009 50: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002010highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002011
2012Try again with a "binary" pickle.
2013
Guido van Rossum57028352003-01-28 15:09:10 +00002014>>> pkl = pickle.dumps(x, 1)
2015>>> dis(pkl)
Tim Petersd0f7c862003-01-28 15:27:57 +00002016 0: ] EMPTY_LIST
2017 1: q BINPUT 0
2018 3: ( MARK
2019 4: K BININT1 1
2020 6: K BININT1 2
2021 8: ( MARK
2022 9: K BININT1 3
2023 11: K BININT1 4
2024 13: t TUPLE (MARK at 8)
2025 14: q BINPUT 1
2026 16: } EMPTY_DICT
2027 17: q BINPUT 2
2028 19: U SHORT_BINSTRING 'abc'
2029 24: q BINPUT 3
2030 26: X BINUNICODE u'def'
2031 34: q BINPUT 4
2032 36: s SETITEM
2033 37: e APPENDS (MARK at 3)
2034 38: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002035highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002036
2037Exercise the INST/OBJ/BUILD family.
2038
2039>>> import random
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002040>>> dis(pickle.dumps(random.random, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002041 0: c GLOBAL 'random random'
2042 15: p PUT 0
2043 18: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002044highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002045
2046>>> x = [pickle.PicklingError()] * 2
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002047>>> dis(pickle.dumps(x, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002048 0: ( MARK
2049 1: l LIST (MARK at 0)
2050 2: p PUT 0
2051 5: ( MARK
2052 6: i INST 'pickle PicklingError' (MARK at 5)
2053 28: p PUT 1
2054 31: ( MARK
2055 32: d DICT (MARK at 31)
2056 33: p PUT 2
2057 36: S STRING 'args'
2058 44: p PUT 3
2059 47: ( MARK
2060 48: t TUPLE (MARK at 47)
2061 49: s SETITEM
2062 50: b BUILD
2063 51: a APPEND
2064 52: g GET 1
2065 55: a APPEND
2066 56: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002067highest protocol among opcodes = 0
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002068
2069>>> dis(pickle.dumps(x, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002070 0: ] EMPTY_LIST
2071 1: q BINPUT 0
2072 3: ( MARK
2073 4: ( MARK
2074 5: c GLOBAL 'pickle PicklingError'
2075 27: q BINPUT 1
2076 29: o OBJ (MARK at 4)
2077 30: q BINPUT 2
2078 32: } EMPTY_DICT
2079 33: q BINPUT 3
2080 35: U SHORT_BINSTRING 'args'
2081 41: q BINPUT 4
2082 43: ) EMPTY_TUPLE
2083 44: s SETITEM
2084 45: b BUILD
2085 46: h BINGET 2
2086 48: e APPENDS (MARK at 3)
2087 49: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002088highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002089
2090Try "the canonical" recursive-object test.
2091
2092>>> L = []
2093>>> T = L,
2094>>> L.append(T)
2095>>> L[0] is T
2096True
2097>>> T[0] is L
2098True
2099>>> L[0][0] is L
2100True
2101>>> T[0][0] is T
2102True
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002103>>> dis(pickle.dumps(L, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002104 0: ( MARK
2105 1: l LIST (MARK at 0)
2106 2: p PUT 0
2107 5: ( MARK
2108 6: g GET 0
2109 9: t TUPLE (MARK at 5)
2110 10: p PUT 1
2111 13: a APPEND
2112 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002113highest protocol among opcodes = 0
2114
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002115>>> dis(pickle.dumps(L, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002116 0: ] EMPTY_LIST
2117 1: q BINPUT 0
2118 3: ( MARK
2119 4: h BINGET 0
2120 6: t TUPLE (MARK at 3)
2121 7: q BINPUT 1
2122 9: a APPEND
2123 10: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002124highest protocol among opcodes = 1
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002125
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002126Note that, in the protocol 0 pickle of the recursive tuple, the disassembler
2127has to emulate the stack in order to realize that the POP opcode at 16 gets
2128rid of the MARK at 0.
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002129
Guido van Rossumf29d3d62003-01-27 22:47:53 +00002130>>> dis(pickle.dumps(T, 0))
Tim Petersd0f7c862003-01-28 15:27:57 +00002131 0: ( MARK
2132 1: ( MARK
2133 2: l LIST (MARK at 1)
2134 3: p PUT 0
2135 6: ( MARK
2136 7: g GET 0
2137 10: t TUPLE (MARK at 6)
2138 11: p PUT 1
2139 14: a APPEND
2140 15: 0 POP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002141 16: 0 POP (MARK at 0)
2142 17: g GET 1
2143 20: . STOP
2144highest protocol among opcodes = 0
2145
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002146>>> dis(pickle.dumps(T, 1))
Tim Petersd0f7c862003-01-28 15:27:57 +00002147 0: ( MARK
2148 1: ] EMPTY_LIST
2149 2: q BINPUT 0
2150 4: ( MARK
2151 5: h BINGET 0
2152 7: t TUPLE (MARK at 4)
2153 8: q BINPUT 1
2154 10: a APPEND
2155 11: 1 POP_MARK (MARK at 0)
2156 12: h BINGET 1
2157 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002158highest protocol among opcodes = 1
Tim Petersd0f7c862003-01-28 15:27:57 +00002159
2160Try protocol 2.
2161
2162>>> dis(pickle.dumps(L, 2))
2163 0: \x80 PROTO 2
2164 2: ] EMPTY_LIST
2165 3: q BINPUT 0
2166 5: h BINGET 0
2167 7: \x85 TUPLE1
2168 8: q BINPUT 1
2169 10: a APPEND
2170 11: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002171highest protocol among opcodes = 2
Tim Petersd0f7c862003-01-28 15:27:57 +00002172
2173>>> dis(pickle.dumps(T, 2))
2174 0: \x80 PROTO 2
2175 2: ] EMPTY_LIST
2176 3: q BINPUT 0
2177 5: h BINGET 0
2178 7: \x85 TUPLE1
2179 8: q BINPUT 1
2180 10: a APPEND
2181 11: 0 POP
2182 12: h BINGET 1
2183 14: . STOP
Tim Petersc1c2b3e2003-01-29 20:12:21 +00002184highest protocol among opcodes = 2
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002185"""
2186
Guido van Rossum57028352003-01-28 15:09:10 +00002187__test__ = {'disassembler_test': _dis_test,
Tim Peters8ecfc8e2003-01-27 18:51:48 +00002188 }
2189
2190def _test():
2191 import doctest
2192 return doctest.testmod()
2193
2194if __name__ == "__main__":
2195 _test()