Skip Montanaro | 5445594 | 2003-01-29 15:41:33 +0000 | [diff] [blame] | 1 | '''"Executable documentation" for the pickle module. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2 | |
| 3 | Extensive comments about the pickle protocols and pickle-machine opcodes |
| 4 | can be found here. Some functions meant for external use: |
| 5 | |
| 6 | genops(pickle) |
| 7 | Generate all the opcodes in a pickle, as (opcode, arg, position) triples. |
| 8 | |
Andrew M. Kuchling | d0c53fe | 2004-08-07 16:51:30 +0000 | [diff] [blame] | 9 | dis(pickle, out=None, memo=None, indentlevel=4) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 10 | Print a symbolic disassembly of a pickle. |
Skip Montanaro | 5445594 | 2003-01-29 15:41:33 +0000 | [diff] [blame] | 11 | ''' |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 12 | |
Walter Dörwald | 42748a8 | 2007-06-12 16:40:17 +0000 | [diff] [blame] | 13 | import codecs |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 14 | import io |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 15 | import pickle |
| 16 | import re |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 17 | import sys |
Walter Dörwald | 42748a8 | 2007-06-12 16:40:17 +0000 | [diff] [blame] | 18 | |
Christian Heimes | 3feef61 | 2008-02-11 06:19:17 +0000 | [diff] [blame] | 19 | __all__ = ['dis', 'genops', 'optimize'] |
Tim Peters | 90cf212 | 2004-11-06 23:45:48 +0000 | [diff] [blame] | 20 | |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 21 | bytes_types = pickle.bytes_types |
| 22 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 23 | # Other ideas: |
| 24 | # |
| 25 | # - A pickle verifier: read a pickle and check it exhaustively for |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 26 | # well-formedness. dis() does a lot of this already. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 27 | # |
| 28 | # - A protocol identifier: examine a pickle and return its protocol number |
| 29 | # (== the highest .proto attr value among all the opcodes in the pickle). |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 30 | # dis() already prints this info at the end. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 31 | # |
| 32 | # - A pickle optimizer: for example, tuple-building code is sometimes more |
| 33 | # elaborate than necessary, catering for the possibility that the tuple |
| 34 | # is recursive. Or lots of times a PUT is generated that's never accessed |
| 35 | # by a later GET. |
| 36 | |
| 37 | |
Victor Stinner | 765531d | 2013-03-26 01:11:54 +0100 | [diff] [blame] | 38 | # "A pickle" is a program for a virtual pickle machine (PM, but more accurately |
| 39 | # called an unpickling machine). It's a sequence of opcodes, interpreted by the |
| 40 | # PM, building an arbitrarily complex Python object. |
| 41 | # |
| 42 | # For the most part, the PM is very simple: there are no looping, testing, or |
| 43 | # conditional instructions, no arithmetic and no function calls. Opcodes are |
| 44 | # executed once each, from first to last, until a STOP opcode is reached. |
| 45 | # |
| 46 | # The PM has two data areas, "the stack" and "the memo". |
| 47 | # |
| 48 | # Many opcodes push Python objects onto the stack; e.g., INT pushes a Python |
| 49 | # integer object on the stack, whose value is gotten from a decimal string |
| 50 | # literal immediately following the INT opcode in the pickle bytestream. Other |
| 51 | # opcodes take Python objects off the stack. The result of unpickling is |
| 52 | # whatever object is left on the stack when the final STOP opcode is executed. |
| 53 | # |
| 54 | # The memo is simply an array of objects, or it can be implemented as a dict |
| 55 | # mapping little integers to objects. The memo serves as the PM's "long term |
| 56 | # memory", and the little integers indexing the memo are akin to variable |
| 57 | # names. Some opcodes pop a stack object into the memo at a given index, |
| 58 | # and others push a memo object at a given index onto the stack again. |
| 59 | # |
| 60 | # At heart, that's all the PM has. Subtleties arise for these reasons: |
| 61 | # |
| 62 | # + Object identity. Objects can be arbitrarily complex, and subobjects |
| 63 | # may be shared (for example, the list [a, a] refers to the same object a |
| 64 | # twice). It can be vital that unpickling recreate an isomorphic object |
| 65 | # graph, faithfully reproducing sharing. |
| 66 | # |
| 67 | # + Recursive objects. For example, after "L = []; L.append(L)", L is a |
| 68 | # list, and L[0] is the same list. This is related to the object identity |
| 69 | # point, and some sequences of pickle opcodes are subtle in order to |
| 70 | # get the right result in all cases. |
| 71 | # |
| 72 | # + Things pickle doesn't know everything about. Examples of things pickle |
| 73 | # does know everything about are Python's builtin scalar and container |
| 74 | # types, like ints and tuples. They generally have opcodes dedicated to |
| 75 | # them. For things like module references and instances of user-defined |
| 76 | # classes, pickle's knowledge is limited. Historically, many enhancements |
| 77 | # have been made to the pickle protocol in order to do a better (faster, |
| 78 | # and/or more compact) job on those. |
| 79 | # |
| 80 | # + Backward compatibility and micro-optimization. As explained below, |
| 81 | # pickle opcodes never go away, not even when better ways to do a thing |
| 82 | # get invented. The repertoire of the PM just keeps growing over time. |
| 83 | # For example, protocol 0 had two opcodes for building Python integers (INT |
| 84 | # and LONG), protocol 1 added three more for more-efficient pickling of short |
| 85 | # integers, and protocol 2 added two more for more-efficient pickling of |
| 86 | # long integers (before protocol 2, the only ways to pickle a Python long |
| 87 | # took time quadratic in the number of digits, for both pickling and |
| 88 | # unpickling). "Opcode bloat" isn't so much a subtlety as a source of |
| 89 | # wearying complication. |
| 90 | # |
| 91 | # |
| 92 | # Pickle protocols: |
| 93 | # |
| 94 | # For compatibility, the meaning of a pickle opcode never changes. Instead new |
| 95 | # pickle opcodes get added, and each version's unpickler can handle all the |
| 96 | # pickle opcodes in all protocol versions to date. So old pickles continue to |
| 97 | # be readable forever. The pickler can generally be told to restrict itself to |
| 98 | # the subset of opcodes available under previous protocol versions too, so that |
| 99 | # users can create pickles under the current version readable by older |
| 100 | # versions. However, a pickle does not contain its version number embedded |
| 101 | # within it. If an older unpickler tries to read a pickle using a later |
| 102 | # protocol, the result is most likely an exception due to seeing an unknown (in |
| 103 | # the older unpickler) opcode. |
| 104 | # |
| 105 | # The original pickle used what's now called "protocol 0", and what was called |
| 106 | # "text mode" before Python 2.3. The entire pickle bytestream is made up of |
| 107 | # printable 7-bit ASCII characters, plus the newline character, in protocol 0. |
| 108 | # That's why it was called text mode. Protocol 0 is small and elegant, but |
| 109 | # sometimes painfully inefficient. |
| 110 | # |
| 111 | # The second major set of additions is now called "protocol 1", and was called |
| 112 | # "binary mode" before Python 2.3. This added many opcodes with arguments |
| 113 | # consisting of arbitrary bytes, including NUL bytes and unprintable "high bit" |
| 114 | # bytes. Binary mode pickles can be substantially smaller than equivalent |
| 115 | # text mode pickles, and sometimes faster too; e.g., BININT represents a 4-byte |
| 116 | # int as 4 bytes following the opcode, which is cheaper to unpickle than the |
| 117 | # (perhaps) 11-character decimal string attached to INT. Protocol 1 also added |
| 118 | # a number of opcodes that operate on many stack elements at once (like APPENDS |
| 119 | # and SETITEMS), and "shortcut" opcodes (like EMPTY_DICT and EMPTY_TUPLE). |
| 120 | # |
| 121 | # The third major set of additions came in Python 2.3, and is called "protocol |
| 122 | # 2". This added: |
| 123 | # |
| 124 | # - A better way to pickle instances of new-style classes (NEWOBJ). |
| 125 | # |
| 126 | # - A way for a pickle to identify its protocol (PROTO). |
| 127 | # |
| 128 | # - Time- and space- efficient pickling of long ints (LONG{1,4}). |
| 129 | # |
| 130 | # - Shortcuts for small tuples (TUPLE{1,2,3}}. |
| 131 | # |
| 132 | # - Dedicated opcodes for bools (NEWTRUE, NEWFALSE). |
| 133 | # |
| 134 | # - The "extension registry", a vector of popular objects that can be pushed |
| 135 | # efficiently by index (EXT{1,2,4}). This is akin to the memo and GET, but |
| 136 | # the registry contents are predefined (there's nothing akin to the memo's |
| 137 | # PUT). |
| 138 | # |
| 139 | # Another independent change with Python 2.3 is the abandonment of any |
| 140 | # pretense that it might be safe to load pickles received from untrusted |
| 141 | # parties -- no sufficient security analysis has been done to guarantee |
| 142 | # this and there isn't a use case that warrants the expense of such an |
| 143 | # analysis. |
| 144 | # |
| 145 | # To this end, all tests for __safe_for_unpickling__ or for |
| 146 | # copyreg.safe_constructors are removed from the unpickling code. |
| 147 | # References to these variables in the descriptions below are to be seen |
| 148 | # as describing unpickling in Python 2.2 and before. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 149 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 150 | |
| 151 | # Meta-rule: Descriptions are stored in instances of descriptor objects, |
| 152 | # with plain constructors. No meta-language is defined from which |
| 153 | # descriptors could be constructed. If you want, e.g., XML, write a little |
| 154 | # program to generate XML from the objects. |
| 155 | |
| 156 | ############################################################################## |
| 157 | # Some pickle opcodes have an argument, following the opcode in the |
| 158 | # bytestream. An argument is of a specific type, described by an instance |
| 159 | # of ArgumentDescriptor. These are not to be confused with arguments taken |
| 160 | # off the stack -- ArgumentDescriptor applies only to arguments embedded in |
| 161 | # the opcode stream, immediately following an opcode. |
| 162 | |
| 163 | # Represents the number of bytes consumed by an argument delimited by the |
| 164 | # next newline character. |
| 165 | UP_TO_NEWLINE = -1 |
| 166 | |
| 167 | # Represents the number of bytes consumed by a two-argument opcode where |
| 168 | # the first argument gives the number of bytes in the second argument. |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 169 | TAKEN_FROM_ARGUMENT1 = -2 # num bytes is 1-byte unsigned int |
| 170 | TAKEN_FROM_ARGUMENT4 = -3 # num bytes is 4-byte signed little-endian int |
| 171 | TAKEN_FROM_ARGUMENT4U = -4 # num bytes is 4-byte unsigned little-endian int |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 172 | TAKEN_FROM_ARGUMENT8U = -5 # num bytes is 8-byte unsigned little-endian int |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 173 | |
| 174 | class ArgumentDescriptor(object): |
| 175 | __slots__ = ( |
| 176 | # name of descriptor record, also a module global name; a string |
| 177 | 'name', |
| 178 | |
| 179 | # length of argument, in bytes; an int; UP_TO_NEWLINE and |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 180 | # TAKEN_FROM_ARGUMENT{1,4,8} are negative values for variable-length |
Tim Peters | fdb8cfa | 2003-01-28 00:13:19 +0000 | [diff] [blame] | 181 | # cases |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 182 | 'n', |
| 183 | |
| 184 | # a function taking a file-like object, reading this kind of argument |
| 185 | # from the object at the current position, advancing the current |
| 186 | # position by n bytes, and returning the value of the argument |
| 187 | 'reader', |
| 188 | |
| 189 | # human-readable docs for this arg descriptor; a string |
| 190 | 'doc', |
| 191 | ) |
| 192 | |
| 193 | def __init__(self, name, n, reader, doc): |
| 194 | assert isinstance(name, str) |
| 195 | self.name = name |
| 196 | |
| 197 | assert isinstance(n, int) and (n >= 0 or |
Tim Peters | fdb8cfa | 2003-01-28 00:13:19 +0000 | [diff] [blame] | 198 | n in (UP_TO_NEWLINE, |
| 199 | TAKEN_FROM_ARGUMENT1, |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 200 | TAKEN_FROM_ARGUMENT4, |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 201 | TAKEN_FROM_ARGUMENT4U, |
| 202 | TAKEN_FROM_ARGUMENT8U)) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 203 | self.n = n |
| 204 | |
| 205 | self.reader = reader |
| 206 | |
| 207 | assert isinstance(doc, str) |
| 208 | self.doc = doc |
| 209 | |
| 210 | from struct import unpack as _unpack |
| 211 | |
| 212 | def read_uint1(f): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 213 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 214 | >>> import io |
| 215 | >>> read_uint1(io.BytesIO(b'\xff')) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 216 | 255 |
| 217 | """ |
| 218 | |
| 219 | data = f.read(1) |
| 220 | if data: |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 221 | return data[0] |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 222 | raise ValueError("not enough data in stream to read uint1") |
| 223 | |
| 224 | uint1 = ArgumentDescriptor( |
| 225 | name='uint1', |
| 226 | n=1, |
| 227 | reader=read_uint1, |
| 228 | doc="One-byte unsigned integer.") |
| 229 | |
| 230 | |
| 231 | def read_uint2(f): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 232 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 233 | >>> import io |
| 234 | >>> read_uint2(io.BytesIO(b'\xff\x00')) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 235 | 255 |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 236 | >>> read_uint2(io.BytesIO(b'\xff\xff')) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 237 | 65535 |
| 238 | """ |
| 239 | |
| 240 | data = f.read(2) |
| 241 | if len(data) == 2: |
| 242 | return _unpack("<H", data)[0] |
| 243 | raise ValueError("not enough data in stream to read uint2") |
| 244 | |
| 245 | uint2 = ArgumentDescriptor( |
| 246 | name='uint2', |
| 247 | n=2, |
| 248 | reader=read_uint2, |
| 249 | doc="Two-byte unsigned integer, little-endian.") |
| 250 | |
| 251 | |
| 252 | def read_int4(f): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 253 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 254 | >>> import io |
| 255 | >>> read_int4(io.BytesIO(b'\xff\x00\x00\x00')) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 256 | 255 |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 257 | >>> read_int4(io.BytesIO(b'\x00\x00\x00\x80')) == -(2**31) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 258 | True |
| 259 | """ |
| 260 | |
| 261 | data = f.read(4) |
| 262 | if len(data) == 4: |
| 263 | return _unpack("<i", data)[0] |
| 264 | raise ValueError("not enough data in stream to read int4") |
| 265 | |
| 266 | int4 = ArgumentDescriptor( |
| 267 | name='int4', |
| 268 | n=4, |
| 269 | reader=read_int4, |
| 270 | doc="Four-byte signed integer, little-endian, 2's complement.") |
| 271 | |
| 272 | |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 273 | def read_uint4(f): |
| 274 | r""" |
| 275 | >>> import io |
| 276 | >>> read_uint4(io.BytesIO(b'\xff\x00\x00\x00')) |
| 277 | 255 |
| 278 | >>> read_uint4(io.BytesIO(b'\x00\x00\x00\x80')) == 2**31 |
| 279 | True |
| 280 | """ |
| 281 | |
| 282 | data = f.read(4) |
| 283 | if len(data) == 4: |
| 284 | return _unpack("<I", data)[0] |
| 285 | raise ValueError("not enough data in stream to read uint4") |
| 286 | |
| 287 | uint4 = ArgumentDescriptor( |
| 288 | name='uint4', |
| 289 | n=4, |
| 290 | reader=read_uint4, |
| 291 | doc="Four-byte unsigned integer, little-endian.") |
| 292 | |
| 293 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 294 | def read_uint8(f): |
| 295 | r""" |
| 296 | >>> import io |
| 297 | >>> read_uint8(io.BytesIO(b'\xff\x00\x00\x00\x00\x00\x00\x00')) |
| 298 | 255 |
| 299 | >>> read_uint8(io.BytesIO(b'\xff' * 8)) == 2**64-1 |
| 300 | True |
| 301 | """ |
| 302 | |
| 303 | data = f.read(8) |
| 304 | if len(data) == 8: |
| 305 | return _unpack("<Q", data)[0] |
| 306 | raise ValueError("not enough data in stream to read uint8") |
| 307 | |
| 308 | uint8 = ArgumentDescriptor( |
| 309 | name='uint8', |
| 310 | n=8, |
| 311 | reader=read_uint8, |
| 312 | doc="Eight-byte unsigned integer, little-endian.") |
| 313 | |
| 314 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 315 | def read_stringnl(f, decode=True, stripquotes=True): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 316 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 317 | >>> import io |
| 318 | >>> read_stringnl(io.BytesIO(b"'abcd'\nefg\n")) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 319 | 'abcd' |
| 320 | |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 321 | >>> read_stringnl(io.BytesIO(b"\n")) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 322 | Traceback (most recent call last): |
| 323 | ... |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 324 | ValueError: no string quotes around b'' |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 325 | |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 326 | >>> read_stringnl(io.BytesIO(b"\n"), stripquotes=False) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 327 | '' |
| 328 | |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 329 | >>> read_stringnl(io.BytesIO(b"''\n")) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 330 | '' |
| 331 | |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 332 | >>> read_stringnl(io.BytesIO(b'"abcd"')) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 333 | Traceback (most recent call last): |
| 334 | ... |
| 335 | ValueError: no newline found when trying to read stringnl |
| 336 | |
| 337 | Embedded escapes are undone in the result. |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 338 | >>> read_stringnl(io.BytesIO(br"'a\n\\b\x00c\td'" + b"\n'e'")) |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 339 | 'a\n\\b\x00c\td' |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 340 | """ |
| 341 | |
Guido van Rossum | 2698631 | 2007-07-17 00:19:46 +0000 | [diff] [blame] | 342 | data = f.readline() |
Guido van Rossum | 26d95c3 | 2007-08-27 23:18:54 +0000 | [diff] [blame] | 343 | if not data.endswith(b'\n'): |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 344 | raise ValueError("no newline found when trying to read stringnl") |
| 345 | data = data[:-1] # lose the newline |
| 346 | |
| 347 | if stripquotes: |
Guido van Rossum | 26d95c3 | 2007-08-27 23:18:54 +0000 | [diff] [blame] | 348 | for q in (b'"', b"'"): |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 349 | if data.startswith(q): |
| 350 | if not data.endswith(q): |
| 351 | raise ValueError("strinq quote %r not found at both " |
| 352 | "ends of %r" % (q, data)) |
| 353 | data = data[1:-1] |
| 354 | break |
| 355 | else: |
| 356 | raise ValueError("no string quotes around %r" % data) |
| 357 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 358 | if decode: |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 359 | data = codecs.escape_decode(data)[0].decode("ascii") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 360 | return data |
| 361 | |
| 362 | stringnl = ArgumentDescriptor( |
| 363 | name='stringnl', |
| 364 | n=UP_TO_NEWLINE, |
| 365 | reader=read_stringnl, |
| 366 | doc="""A newline-terminated string. |
| 367 | |
| 368 | This is a repr-style string, with embedded escapes, and |
| 369 | bracketing quotes. |
| 370 | """) |
| 371 | |
| 372 | def read_stringnl_noescape(f): |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 373 | return read_stringnl(f, stripquotes=False) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 374 | |
| 375 | stringnl_noescape = ArgumentDescriptor( |
| 376 | name='stringnl_noescape', |
| 377 | n=UP_TO_NEWLINE, |
| 378 | reader=read_stringnl_noescape, |
| 379 | doc="""A newline-terminated string. |
| 380 | |
| 381 | This is a str-style string, without embedded escapes, |
| 382 | or bracketing quotes. It should consist solely of |
| 383 | printable ASCII characters. |
| 384 | """) |
| 385 | |
| 386 | def read_stringnl_noescape_pair(f): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 387 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 388 | >>> import io |
| 389 | >>> read_stringnl_noescape_pair(io.BytesIO(b"Queue\nEmpty\njunk")) |
Tim Peters | d916cf4 | 2003-01-27 19:01:47 +0000 | [diff] [blame] | 390 | 'Queue Empty' |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 391 | """ |
| 392 | |
Tim Peters | d916cf4 | 2003-01-27 19:01:47 +0000 | [diff] [blame] | 393 | return "%s %s" % (read_stringnl_noescape(f), read_stringnl_noescape(f)) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 394 | |
| 395 | stringnl_noescape_pair = ArgumentDescriptor( |
| 396 | name='stringnl_noescape_pair', |
| 397 | n=UP_TO_NEWLINE, |
| 398 | reader=read_stringnl_noescape_pair, |
| 399 | doc="""A pair of newline-terminated strings. |
| 400 | |
| 401 | These are str-style strings, without embedded |
| 402 | escapes, or bracketing quotes. They should |
| 403 | consist solely of printable ASCII characters. |
| 404 | The pair is returned as a single string, with |
Tim Peters | d916cf4 | 2003-01-27 19:01:47 +0000 | [diff] [blame] | 405 | a single blank separating the two strings. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 406 | """) |
| 407 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 408 | |
| 409 | def read_string1(f): |
| 410 | r""" |
| 411 | >>> import io |
| 412 | >>> read_string1(io.BytesIO(b"\x00")) |
| 413 | '' |
| 414 | >>> read_string1(io.BytesIO(b"\x03abcdef")) |
| 415 | 'abc' |
| 416 | """ |
| 417 | |
| 418 | n = read_uint1(f) |
| 419 | assert n >= 0 |
| 420 | data = f.read(n) |
| 421 | if len(data) == n: |
| 422 | return data.decode("latin-1") |
| 423 | raise ValueError("expected %d bytes in a string1, but only %d remain" % |
| 424 | (n, len(data))) |
| 425 | |
| 426 | string1 = ArgumentDescriptor( |
| 427 | name="string1", |
| 428 | n=TAKEN_FROM_ARGUMENT1, |
| 429 | reader=read_string1, |
| 430 | doc="""A counted string. |
| 431 | |
| 432 | The first argument is a 1-byte unsigned int giving the number |
| 433 | of bytes in the string, and the second argument is that many |
| 434 | bytes. |
| 435 | """) |
| 436 | |
| 437 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 438 | def read_string4(f): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 439 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 440 | >>> import io |
| 441 | >>> read_string4(io.BytesIO(b"\x00\x00\x00\x00abc")) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 442 | '' |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 443 | >>> read_string4(io.BytesIO(b"\x03\x00\x00\x00abcdef")) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 444 | 'abc' |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 445 | >>> read_string4(io.BytesIO(b"\x00\x00\x00\x03abcdef")) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 446 | Traceback (most recent call last): |
| 447 | ... |
| 448 | ValueError: expected 50331648 bytes in a string4, but only 6 remain |
| 449 | """ |
| 450 | |
| 451 | n = read_int4(f) |
| 452 | if n < 0: |
| 453 | raise ValueError("string4 byte count < 0: %d" % n) |
| 454 | data = f.read(n) |
| 455 | if len(data) == n: |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 456 | return data.decode("latin-1") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 457 | raise ValueError("expected %d bytes in a string4, but only %d remain" % |
| 458 | (n, len(data))) |
| 459 | |
| 460 | string4 = ArgumentDescriptor( |
| 461 | name="string4", |
Tim Peters | fdb8cfa | 2003-01-28 00:13:19 +0000 | [diff] [blame] | 462 | n=TAKEN_FROM_ARGUMENT4, |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 463 | reader=read_string4, |
| 464 | doc="""A counted string. |
| 465 | |
| 466 | The first argument is a 4-byte little-endian signed int giving |
| 467 | the number of bytes in the string, and the second argument is |
| 468 | that many bytes. |
| 469 | """) |
| 470 | |
| 471 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 472 | def read_bytes1(f): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 473 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 474 | >>> import io |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 475 | >>> read_bytes1(io.BytesIO(b"\x00")) |
| 476 | b'' |
| 477 | >>> read_bytes1(io.BytesIO(b"\x03abcdef")) |
| 478 | b'abc' |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 479 | """ |
| 480 | |
| 481 | n = read_uint1(f) |
| 482 | assert n >= 0 |
| 483 | data = f.read(n) |
| 484 | if len(data) == n: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 485 | return data |
| 486 | raise ValueError("expected %d bytes in a bytes1, but only %d remain" % |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 487 | (n, len(data))) |
| 488 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 489 | bytes1 = ArgumentDescriptor( |
| 490 | name="bytes1", |
Tim Peters | fdb8cfa | 2003-01-28 00:13:19 +0000 | [diff] [blame] | 491 | n=TAKEN_FROM_ARGUMENT1, |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 492 | reader=read_bytes1, |
| 493 | doc="""A counted bytes string. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 494 | |
| 495 | The first argument is a 1-byte unsigned int giving the number |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 496 | of bytes, and the second argument is that many bytes. |
| 497 | """) |
| 498 | |
| 499 | |
| 500 | def read_bytes4(f): |
| 501 | r""" |
| 502 | >>> import io |
| 503 | >>> read_bytes4(io.BytesIO(b"\x00\x00\x00\x00abc")) |
| 504 | b'' |
| 505 | >>> read_bytes4(io.BytesIO(b"\x03\x00\x00\x00abcdef")) |
| 506 | b'abc' |
| 507 | >>> read_bytes4(io.BytesIO(b"\x00\x00\x00\x03abcdef")) |
| 508 | Traceback (most recent call last): |
| 509 | ... |
| 510 | ValueError: expected 50331648 bytes in a bytes4, but only 6 remain |
| 511 | """ |
| 512 | |
| 513 | n = read_uint4(f) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 514 | assert n >= 0 |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 515 | if n > sys.maxsize: |
| 516 | raise ValueError("bytes4 byte count > sys.maxsize: %d" % n) |
| 517 | data = f.read(n) |
| 518 | if len(data) == n: |
| 519 | return data |
| 520 | raise ValueError("expected %d bytes in a bytes4, but only %d remain" % |
| 521 | (n, len(data))) |
| 522 | |
| 523 | bytes4 = ArgumentDescriptor( |
| 524 | name="bytes4", |
| 525 | n=TAKEN_FROM_ARGUMENT4U, |
| 526 | reader=read_bytes4, |
| 527 | doc="""A counted bytes string. |
| 528 | |
| 529 | The first argument is a 4-byte little-endian unsigned int giving |
| 530 | the number of bytes, and the second argument is that many bytes. |
| 531 | """) |
| 532 | |
| 533 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 534 | def read_bytes8(f): |
| 535 | r""" |
Gregory P. Smith | 057e58d | 2013-11-23 20:40:46 +0000 | [diff] [blame] | 536 | >>> import io, struct, sys |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 537 | >>> read_bytes8(io.BytesIO(b"\x00\x00\x00\x00\x00\x00\x00\x00abc")) |
| 538 | b'' |
| 539 | >>> read_bytes8(io.BytesIO(b"\x03\x00\x00\x00\x00\x00\x00\x00abcdef")) |
| 540 | b'abc' |
Gregory P. Smith | 057e58d | 2013-11-23 20:40:46 +0000 | [diff] [blame] | 541 | >>> bigsize8 = struct.pack("<Q", sys.maxsize//3) |
| 542 | >>> read_bytes8(io.BytesIO(bigsize8 + b"abcdef")) #doctest: +ELLIPSIS |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 543 | Traceback (most recent call last): |
| 544 | ... |
Gregory P. Smith | 057e58d | 2013-11-23 20:40:46 +0000 | [diff] [blame] | 545 | ValueError: expected ... bytes in a bytes8, but only 6 remain |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 546 | """ |
| 547 | |
| 548 | n = read_uint8(f) |
| 549 | assert n >= 0 |
| 550 | if n > sys.maxsize: |
| 551 | raise ValueError("bytes8 byte count > sys.maxsize: %d" % n) |
| 552 | data = f.read(n) |
| 553 | if len(data) == n: |
| 554 | return data |
| 555 | raise ValueError("expected %d bytes in a bytes8, but only %d remain" % |
| 556 | (n, len(data))) |
| 557 | |
| 558 | bytes8 = ArgumentDescriptor( |
| 559 | name="bytes8", |
| 560 | n=TAKEN_FROM_ARGUMENT8U, |
| 561 | reader=read_bytes8, |
| 562 | doc="""A counted bytes string. |
| 563 | |
Martin Panter | 4c35964 | 2016-05-08 13:53:41 +0000 | [diff] [blame] | 564 | The first argument is an 8-byte little-endian unsigned int giving |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 565 | the number of bytes, and the second argument is that many bytes. |
| 566 | """) |
| 567 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 568 | def read_unicodestringnl(f): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 569 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 570 | >>> import io |
| 571 | >>> read_unicodestringnl(io.BytesIO(b"abc\\uabcd\njunk")) == 'abc\uabcd' |
| 572 | True |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 573 | """ |
| 574 | |
Guido van Rossum | 2698631 | 2007-07-17 00:19:46 +0000 | [diff] [blame] | 575 | data = f.readline() |
Guido van Rossum | 26d95c3 | 2007-08-27 23:18:54 +0000 | [diff] [blame] | 576 | if not data.endswith(b'\n'): |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 577 | raise ValueError("no newline found when trying to read " |
| 578 | "unicodestringnl") |
| 579 | data = data[:-1] # lose the newline |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 580 | return str(data, 'raw-unicode-escape') |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 581 | |
| 582 | unicodestringnl = ArgumentDescriptor( |
| 583 | name='unicodestringnl', |
| 584 | n=UP_TO_NEWLINE, |
| 585 | reader=read_unicodestringnl, |
| 586 | doc="""A newline-terminated Unicode string. |
| 587 | |
| 588 | This is raw-unicode-escape encoded, so consists of |
| 589 | printable ASCII characters, and may contain embedded |
| 590 | escape sequences. |
| 591 | """) |
| 592 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 593 | |
| 594 | def read_unicodestring1(f): |
| 595 | r""" |
| 596 | >>> import io |
| 597 | >>> s = 'abcd\uabcd' |
| 598 | >>> enc = s.encode('utf-8') |
| 599 | >>> enc |
| 600 | b'abcd\xea\xaf\x8d' |
| 601 | >>> n = bytes([len(enc)]) # little-endian 1-byte length |
| 602 | >>> t = read_unicodestring1(io.BytesIO(n + enc + b'junk')) |
| 603 | >>> s == t |
| 604 | True |
| 605 | |
| 606 | >>> read_unicodestring1(io.BytesIO(n + enc[:-1])) |
| 607 | Traceback (most recent call last): |
| 608 | ... |
| 609 | ValueError: expected 7 bytes in a unicodestring1, but only 6 remain |
| 610 | """ |
| 611 | |
| 612 | n = read_uint1(f) |
| 613 | assert n >= 0 |
| 614 | data = f.read(n) |
| 615 | if len(data) == n: |
| 616 | return str(data, 'utf-8', 'surrogatepass') |
| 617 | raise ValueError("expected %d bytes in a unicodestring1, but only %d " |
| 618 | "remain" % (n, len(data))) |
| 619 | |
| 620 | unicodestring1 = ArgumentDescriptor( |
| 621 | name="unicodestring1", |
| 622 | n=TAKEN_FROM_ARGUMENT1, |
| 623 | reader=read_unicodestring1, |
| 624 | doc="""A counted Unicode string. |
| 625 | |
| 626 | The first argument is a 1-byte little-endian signed int |
| 627 | giving the number of bytes in the string, and the second |
| 628 | argument-- the UTF-8 encoding of the Unicode string -- |
| 629 | contains that many bytes. |
| 630 | """) |
| 631 | |
| 632 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 633 | def read_unicodestring4(f): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 634 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 635 | >>> import io |
| 636 | >>> s = 'abcd\uabcd' |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 637 | >>> enc = s.encode('utf-8') |
| 638 | >>> enc |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 639 | b'abcd\xea\xaf\x8d' |
| 640 | >>> n = bytes([len(enc), 0, 0, 0]) # little-endian 4-byte length |
| 641 | >>> t = read_unicodestring4(io.BytesIO(n + enc + b'junk')) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 642 | >>> s == t |
| 643 | True |
| 644 | |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 645 | >>> read_unicodestring4(io.BytesIO(n + enc[:-1])) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 646 | Traceback (most recent call last): |
| 647 | ... |
| 648 | ValueError: expected 7 bytes in a unicodestring4, but only 6 remain |
| 649 | """ |
| 650 | |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 651 | n = read_uint4(f) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 652 | assert n >= 0 |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 653 | if n > sys.maxsize: |
| 654 | raise ValueError("unicodestring4 byte count > sys.maxsize: %d" % n) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 655 | data = f.read(n) |
| 656 | if len(data) == n: |
Victor Stinner | 485fb56 | 2010-04-13 11:07:24 +0000 | [diff] [blame] | 657 | return str(data, 'utf-8', 'surrogatepass') |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 658 | raise ValueError("expected %d bytes in a unicodestring4, but only %d " |
| 659 | "remain" % (n, len(data))) |
| 660 | |
| 661 | unicodestring4 = ArgumentDescriptor( |
| 662 | name="unicodestring4", |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 663 | n=TAKEN_FROM_ARGUMENT4U, |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 664 | reader=read_unicodestring4, |
| 665 | doc="""A counted Unicode string. |
| 666 | |
| 667 | The first argument is a 4-byte little-endian signed int |
| 668 | giving the number of bytes in the string, and the second |
| 669 | argument-- the UTF-8 encoding of the Unicode string -- |
| 670 | contains that many bytes. |
| 671 | """) |
| 672 | |
| 673 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 674 | def read_unicodestring8(f): |
| 675 | r""" |
| 676 | >>> import io |
| 677 | >>> s = 'abcd\uabcd' |
| 678 | >>> enc = s.encode('utf-8') |
| 679 | >>> enc |
| 680 | b'abcd\xea\xaf\x8d' |
Serhiy Storchaka | 5f1a518 | 2016-09-11 14:41:02 +0300 | [diff] [blame] | 681 | >>> n = bytes([len(enc)]) + b'\0' * 7 # little-endian 8-byte length |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 682 | >>> t = read_unicodestring8(io.BytesIO(n + enc + b'junk')) |
| 683 | >>> s == t |
| 684 | True |
| 685 | |
| 686 | >>> read_unicodestring8(io.BytesIO(n + enc[:-1])) |
| 687 | Traceback (most recent call last): |
| 688 | ... |
| 689 | ValueError: expected 7 bytes in a unicodestring8, but only 6 remain |
| 690 | """ |
| 691 | |
| 692 | n = read_uint8(f) |
| 693 | assert n >= 0 |
| 694 | if n > sys.maxsize: |
| 695 | raise ValueError("unicodestring8 byte count > sys.maxsize: %d" % n) |
| 696 | data = f.read(n) |
| 697 | if len(data) == n: |
| 698 | return str(data, 'utf-8', 'surrogatepass') |
| 699 | raise ValueError("expected %d bytes in a unicodestring8, but only %d " |
| 700 | "remain" % (n, len(data))) |
| 701 | |
| 702 | unicodestring8 = ArgumentDescriptor( |
| 703 | name="unicodestring8", |
| 704 | n=TAKEN_FROM_ARGUMENT8U, |
| 705 | reader=read_unicodestring8, |
| 706 | doc="""A counted Unicode string. |
| 707 | |
Martin Panter | 4c35964 | 2016-05-08 13:53:41 +0000 | [diff] [blame] | 708 | The first argument is an 8-byte little-endian signed int |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 709 | giving the number of bytes in the string, and the second |
| 710 | argument-- the UTF-8 encoding of the Unicode string -- |
| 711 | contains that many bytes. |
| 712 | """) |
| 713 | |
| 714 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 715 | def read_decimalnl_short(f): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 716 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 717 | >>> import io |
| 718 | >>> read_decimalnl_short(io.BytesIO(b"1234\n56")) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 719 | 1234 |
| 720 | |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 721 | >>> read_decimalnl_short(io.BytesIO(b"1234L\n56")) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 722 | Traceback (most recent call last): |
| 723 | ... |
Serhiy Storchaka | 9594942 | 2013-08-27 19:40:23 +0300 | [diff] [blame] | 724 | ValueError: invalid literal for int() with base 10: b'1234L' |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 725 | """ |
| 726 | |
| 727 | s = read_stringnl(f, decode=False, stripquotes=False) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 728 | |
Serhiy Storchaka | 9594942 | 2013-08-27 19:40:23 +0300 | [diff] [blame] | 729 | # There's a hack for True and False here. |
Jeremy Hylton | a5dc3db | 2007-08-29 19:07:40 +0000 | [diff] [blame] | 730 | if s == b"00": |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 731 | return False |
Jeremy Hylton | a5dc3db | 2007-08-29 19:07:40 +0000 | [diff] [blame] | 732 | elif s == b"01": |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 733 | return True |
| 734 | |
Florent Xicluna | 2bb96f5 | 2011-10-23 22:11:00 +0200 | [diff] [blame] | 735 | return int(s) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 736 | |
| 737 | def read_decimalnl_long(f): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 738 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 739 | >>> import io |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 740 | |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 741 | >>> read_decimalnl_long(io.BytesIO(b"1234L\n56")) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 742 | 1234 |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 743 | |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 744 | >>> read_decimalnl_long(io.BytesIO(b"123456789012345678901234L\n6")) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 745 | 123456789012345678901234 |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 746 | """ |
| 747 | |
| 748 | s = read_stringnl(f, decode=False, stripquotes=False) |
Mark Dickinson | 8dd0514 | 2009-01-20 20:43:58 +0000 | [diff] [blame] | 749 | if s[-1:] == b'L': |
| 750 | s = s[:-1] |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 751 | return int(s) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 752 | |
| 753 | |
| 754 | decimalnl_short = ArgumentDescriptor( |
| 755 | name='decimalnl_short', |
| 756 | n=UP_TO_NEWLINE, |
| 757 | reader=read_decimalnl_short, |
| 758 | doc="""A newline-terminated decimal integer literal. |
| 759 | |
| 760 | This never has a trailing 'L', and the integer fit |
| 761 | in a short Python int on the box where the pickle |
| 762 | was written -- but there's no guarantee it will fit |
| 763 | in a short Python int on the box where the pickle |
| 764 | is read. |
| 765 | """) |
| 766 | |
| 767 | decimalnl_long = ArgumentDescriptor( |
| 768 | name='decimalnl_long', |
| 769 | n=UP_TO_NEWLINE, |
| 770 | reader=read_decimalnl_long, |
| 771 | doc="""A newline-terminated decimal integer literal. |
| 772 | |
| 773 | This has a trailing 'L', and can represent integers |
| 774 | of any size. |
| 775 | """) |
| 776 | |
| 777 | |
| 778 | def read_floatnl(f): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 779 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 780 | >>> import io |
| 781 | >>> read_floatnl(io.BytesIO(b"-1.25\n6")) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 782 | -1.25 |
| 783 | """ |
| 784 | s = read_stringnl(f, decode=False, stripquotes=False) |
| 785 | return float(s) |
| 786 | |
| 787 | floatnl = ArgumentDescriptor( |
| 788 | name='floatnl', |
| 789 | n=UP_TO_NEWLINE, |
| 790 | reader=read_floatnl, |
| 791 | doc="""A newline-terminated decimal floating literal. |
| 792 | |
| 793 | In general this requires 17 significant digits for roundtrip |
| 794 | identity, and pickling then unpickling infinities, NaNs, and |
| 795 | minus zero doesn't work across boxes, or on some boxes even |
| 796 | on itself (e.g., Windows can't read the strings it produces |
| 797 | for infinities or NaNs). |
| 798 | """) |
| 799 | |
| 800 | def read_float8(f): |
Tim Peters | 55762f5 | 2003-01-28 16:01:25 +0000 | [diff] [blame] | 801 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 802 | >>> import io, struct |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 803 | >>> raw = struct.pack(">d", -1.25) |
| 804 | >>> raw |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 805 | b'\xbf\xf4\x00\x00\x00\x00\x00\x00' |
| 806 | >>> read_float8(io.BytesIO(raw + b"\n")) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 807 | -1.25 |
| 808 | """ |
| 809 | |
| 810 | data = f.read(8) |
| 811 | if len(data) == 8: |
| 812 | return _unpack(">d", data)[0] |
| 813 | raise ValueError("not enough data in stream to read float8") |
| 814 | |
| 815 | |
| 816 | float8 = ArgumentDescriptor( |
| 817 | name='float8', |
| 818 | n=8, |
| 819 | reader=read_float8, |
| 820 | doc="""An 8-byte binary representation of a float, big-endian. |
| 821 | |
| 822 | The format is unique to Python, and shared with the struct |
Guido van Rossum | 99603b0 | 2007-07-20 00:22:32 +0000 | [diff] [blame] | 823 | module (format string '>d') "in theory" (the struct and pickle |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 824 | implementations don't share the code -- they should). It's |
| 825 | strongly related to the IEEE-754 double format, and, in normal |
| 826 | cases, is in fact identical to the big-endian 754 double format. |
| 827 | On other boxes the dynamic range is limited to that of a 754 |
| 828 | double, and "add a half and chop" rounding is used to reduce |
| 829 | the precision to 53 bits. However, even on a 754 box, |
| 830 | infinities, NaNs, and minus zero may not be handled correctly |
| 831 | (may not survive roundtrip pickling intact). |
| 832 | """) |
| 833 | |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 834 | # Protocol 2 formats |
| 835 | |
Tim Peters | c0c12b5 | 2003-01-29 00:56:17 +0000 | [diff] [blame] | 836 | from pickle import decode_long |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 837 | |
| 838 | def read_long1(f): |
| 839 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 840 | >>> import io |
| 841 | >>> read_long1(io.BytesIO(b"\x00")) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 842 | 0 |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 843 | >>> read_long1(io.BytesIO(b"\x02\xff\x00")) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 844 | 255 |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 845 | >>> read_long1(io.BytesIO(b"\x02\xff\x7f")) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 846 | 32767 |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 847 | >>> read_long1(io.BytesIO(b"\x02\x00\xff")) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 848 | -256 |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 849 | >>> read_long1(io.BytesIO(b"\x02\x00\x80")) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 850 | -32768 |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 851 | """ |
| 852 | |
| 853 | n = read_uint1(f) |
| 854 | data = f.read(n) |
| 855 | if len(data) != n: |
| 856 | raise ValueError("not enough data in stream to read long1") |
| 857 | return decode_long(data) |
| 858 | |
| 859 | long1 = ArgumentDescriptor( |
| 860 | name="long1", |
Tim Peters | fdb8cfa | 2003-01-28 00:13:19 +0000 | [diff] [blame] | 861 | n=TAKEN_FROM_ARGUMENT1, |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 862 | reader=read_long1, |
| 863 | doc="""A binary long, little-endian, using 1-byte size. |
| 864 | |
| 865 | This first reads one byte as an unsigned size, then reads that |
Tim Peters | bdbe741 | 2003-01-27 23:54:04 +0000 | [diff] [blame] | 866 | many bytes and interprets them as a little-endian 2's-complement long. |
Tim Peters | 4b23f2b | 2003-01-31 16:43:39 +0000 | [diff] [blame] | 867 | If the size is 0, that's taken as a shortcut for the long 0L. |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 868 | """) |
| 869 | |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 870 | def read_long4(f): |
| 871 | r""" |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 872 | >>> import io |
| 873 | >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\xff\x00")) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 874 | 255 |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 875 | >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\xff\x7f")) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 876 | 32767 |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 877 | >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\x00\xff")) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 878 | -256 |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 879 | >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\x00\x80")) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 880 | -32768 |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 881 | >>> read_long1(io.BytesIO(b"\x00\x00\x00\x00")) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 882 | 0 |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 883 | """ |
| 884 | |
| 885 | n = read_int4(f) |
| 886 | if n < 0: |
Neal Norwitz | 784a3f5 | 2003-01-28 00:20:41 +0000 | [diff] [blame] | 887 | raise ValueError("long4 byte count < 0: %d" % n) |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 888 | data = f.read(n) |
| 889 | if len(data) != n: |
Neal Norwitz | 784a3f5 | 2003-01-28 00:20:41 +0000 | [diff] [blame] | 890 | raise ValueError("not enough data in stream to read long4") |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 891 | return decode_long(data) |
| 892 | |
| 893 | long4 = ArgumentDescriptor( |
| 894 | name="long4", |
Tim Peters | fdb8cfa | 2003-01-28 00:13:19 +0000 | [diff] [blame] | 895 | n=TAKEN_FROM_ARGUMENT4, |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 896 | reader=read_long4, |
| 897 | doc="""A binary representation of a long, little-endian. |
| 898 | |
| 899 | This first reads four bytes as a signed size (but requires the |
| 900 | size to be >= 0), then reads that many bytes and interprets them |
Tim Peters | 4b23f2b | 2003-01-31 16:43:39 +0000 | [diff] [blame] | 901 | as a little-endian 2's-complement long. If the size is 0, that's taken |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 902 | as a shortcut for the int 0, although LONG1 should really be used |
Tim Peters | 4b23f2b | 2003-01-31 16:43:39 +0000 | [diff] [blame] | 903 | then instead (and in any case where # of bytes < 256). |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 904 | """) |
| 905 | |
| 906 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 907 | ############################################################################## |
| 908 | # Object descriptors. The stack used by the pickle machine holds objects, |
| 909 | # and in the stack_before and stack_after attributes of OpcodeInfo |
| 910 | # descriptors we need names to describe the various types of objects that can |
| 911 | # appear on the stack. |
| 912 | |
| 913 | class StackObject(object): |
| 914 | __slots__ = ( |
| 915 | # name of descriptor record, for info only |
| 916 | 'name', |
| 917 | |
| 918 | # type of object, or tuple of type objects (meaning the object can |
| 919 | # be of any type in the tuple) |
| 920 | 'obtype', |
| 921 | |
| 922 | # human-readable docs for this kind of stack object; a string |
| 923 | 'doc', |
| 924 | ) |
| 925 | |
| 926 | def __init__(self, name, obtype, doc): |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 927 | assert isinstance(name, str) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 928 | self.name = name |
| 929 | |
| 930 | assert isinstance(obtype, type) or isinstance(obtype, tuple) |
| 931 | if isinstance(obtype, tuple): |
| 932 | for contained in obtype: |
| 933 | assert isinstance(contained, type) |
| 934 | self.obtype = obtype |
| 935 | |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 936 | assert isinstance(doc, str) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 937 | self.doc = doc |
| 938 | |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 939 | def __repr__(self): |
| 940 | return self.name |
| 941 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 942 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 943 | pyint = pylong = StackObject( |
| 944 | name='int', |
| 945 | obtype=int, |
| 946 | doc="A Python integer object.") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 947 | |
| 948 | pyinteger_or_bool = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 949 | name='int_or_bool', |
| 950 | obtype=(int, bool), |
| 951 | doc="A Python integer or boolean object.") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 952 | |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 953 | pybool = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 954 | name='bool', |
| 955 | obtype=bool, |
| 956 | doc="A Python boolean object.") |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 957 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 958 | pyfloat = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 959 | name='float', |
| 960 | obtype=float, |
| 961 | doc="A Python float object.") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 962 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 963 | pybytes_or_str = pystring = StackObject( |
| 964 | name='bytes_or_str', |
| 965 | obtype=(bytes, str), |
| 966 | doc="A Python bytes or (Unicode) string object.") |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 967 | |
| 968 | pybytes = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 969 | name='bytes', |
| 970 | obtype=bytes, |
| 971 | doc="A Python bytes object.") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 972 | |
| 973 | pyunicode = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 974 | name='str', |
| 975 | obtype=str, |
| 976 | doc="A Python (Unicode) string object.") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 977 | |
| 978 | pynone = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 979 | name="None", |
| 980 | obtype=type(None), |
| 981 | doc="The Python None object.") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 982 | |
| 983 | pytuple = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 984 | name="tuple", |
| 985 | obtype=tuple, |
| 986 | doc="A Python tuple object.") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 987 | |
| 988 | pylist = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 989 | name="list", |
| 990 | obtype=list, |
| 991 | doc="A Python list object.") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 992 | |
| 993 | pydict = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 994 | name="dict", |
| 995 | obtype=dict, |
| 996 | doc="A Python dict object.") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 997 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 998 | pyset = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 999 | name="set", |
| 1000 | obtype=set, |
| 1001 | doc="A Python set object.") |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1002 | |
| 1003 | pyfrozenset = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1004 | name="frozenset", |
| 1005 | obtype=set, |
| 1006 | doc="A Python frozenset object.") |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1007 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1008 | anyobject = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1009 | name='any', |
| 1010 | obtype=object, |
| 1011 | doc="Any kind of object whatsoever.") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1012 | |
| 1013 | markobject = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1014 | name="mark", |
| 1015 | obtype=StackObject, |
| 1016 | doc="""'The mark' is a unique object. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1017 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1018 | Opcodes that operate on a variable number of objects |
| 1019 | generally don't embed the count of objects in the opcode, |
| 1020 | or pull it off the stack. Instead the MARK opcode is used |
| 1021 | to push a special marker object on the stack, and then |
| 1022 | some other opcodes grab all the objects from the top of |
| 1023 | the stack down to (but not including) the topmost marker |
| 1024 | object. |
| 1025 | """) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1026 | |
| 1027 | stackslice = StackObject( |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1028 | name="stackslice", |
| 1029 | obtype=StackObject, |
| 1030 | doc="""An object representing a contiguous slice of the stack. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1031 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1032 | This is used in conjunction with markobject, to represent all |
| 1033 | of the stack following the topmost markobject. For example, |
| 1034 | the POP_MARK opcode changes the stack from |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1035 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1036 | [..., markobject, stackslice] |
| 1037 | to |
| 1038 | [...] |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1039 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1040 | No matter how many object are on the stack after the topmost |
| 1041 | markobject, POP_MARK gets rid of all of them (including the |
| 1042 | topmost markobject too). |
| 1043 | """) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1044 | |
| 1045 | ############################################################################## |
| 1046 | # Descriptors for pickle opcodes. |
| 1047 | |
| 1048 | class OpcodeInfo(object): |
| 1049 | |
| 1050 | __slots__ = ( |
| 1051 | # symbolic name of opcode; a string |
| 1052 | 'name', |
| 1053 | |
| 1054 | # the code used in a bytestream to represent the opcode; a |
| 1055 | # one-character string |
| 1056 | 'code', |
| 1057 | |
| 1058 | # If the opcode has an argument embedded in the byte string, an |
| 1059 | # instance of ArgumentDescriptor specifying its type. Note that |
| 1060 | # arg.reader(s) can be used to read and decode the argument from |
| 1061 | # the bytestream s, and arg.doc documents the format of the raw |
| 1062 | # argument bytes. If the opcode doesn't have an argument embedded |
| 1063 | # in the bytestream, arg should be None. |
| 1064 | 'arg', |
| 1065 | |
| 1066 | # what the stack looks like before this opcode runs; a list |
| 1067 | 'stack_before', |
| 1068 | |
| 1069 | # what the stack looks like after this opcode runs; a list |
| 1070 | 'stack_after', |
| 1071 | |
| 1072 | # the protocol number in which this opcode was introduced; an int |
| 1073 | 'proto', |
| 1074 | |
| 1075 | # human-readable docs for this opcode; a string |
| 1076 | 'doc', |
| 1077 | ) |
| 1078 | |
| 1079 | def __init__(self, name, code, arg, |
| 1080 | stack_before, stack_after, proto, doc): |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 1081 | assert isinstance(name, str) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1082 | self.name = name |
| 1083 | |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 1084 | assert isinstance(code, str) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1085 | assert len(code) == 1 |
| 1086 | self.code = code |
| 1087 | |
| 1088 | assert arg is None or isinstance(arg, ArgumentDescriptor) |
| 1089 | self.arg = arg |
| 1090 | |
| 1091 | assert isinstance(stack_before, list) |
| 1092 | for x in stack_before: |
| 1093 | assert isinstance(x, StackObject) |
| 1094 | self.stack_before = stack_before |
| 1095 | |
| 1096 | assert isinstance(stack_after, list) |
| 1097 | for x in stack_after: |
| 1098 | assert isinstance(x, StackObject) |
| 1099 | self.stack_after = stack_after |
| 1100 | |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 1101 | assert isinstance(proto, int) and 0 <= proto <= pickle.HIGHEST_PROTOCOL |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1102 | self.proto = proto |
| 1103 | |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 1104 | assert isinstance(doc, str) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1105 | self.doc = doc |
| 1106 | |
| 1107 | I = OpcodeInfo |
| 1108 | opcodes = [ |
| 1109 | |
| 1110 | # Ways to spell integers. |
| 1111 | |
| 1112 | I(name='INT', |
| 1113 | code='I', |
| 1114 | arg=decimalnl_short, |
| 1115 | stack_before=[], |
| 1116 | stack_after=[pyinteger_or_bool], |
| 1117 | proto=0, |
| 1118 | doc="""Push an integer or bool. |
| 1119 | |
| 1120 | The argument is a newline-terminated decimal literal string. |
| 1121 | |
| 1122 | The intent may have been that this always fit in a short Python int, |
| 1123 | but INT can be generated in pickles written on a 64-bit box that |
| 1124 | require a Python long on a 32-bit box. The difference between this |
| 1125 | and LONG then is that INT skips a trailing 'L', and produces a short |
| 1126 | int whenever possible. |
| 1127 | |
| 1128 | Another difference is due to that, when bool was introduced as a |
| 1129 | distinct type in 2.3, builtin names True and False were also added to |
| 1130 | 2.2.2, mapping to ints 1 and 0. For compatibility in both directions, |
| 1131 | True gets pickled as INT + "I01\\n", and False as INT + "I00\\n". |
| 1132 | Leading zeroes are never produced for a genuine integer. The 2.3 |
| 1133 | (and later) unpicklers special-case these and return bool instead; |
| 1134 | earlier unpicklers ignore the leading "0" and return the int. |
| 1135 | """), |
| 1136 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1137 | I(name='BININT', |
| 1138 | code='J', |
| 1139 | arg=int4, |
| 1140 | stack_before=[], |
| 1141 | stack_after=[pyint], |
| 1142 | proto=1, |
| 1143 | doc="""Push a four-byte signed integer. |
| 1144 | |
| 1145 | This handles the full range of Python (short) integers on a 32-bit |
| 1146 | box, directly as binary bytes (1 for the opcode and 4 for the integer). |
| 1147 | If the integer is non-negative and fits in 1 or 2 bytes, pickling via |
| 1148 | BININT1 or BININT2 saves space. |
| 1149 | """), |
| 1150 | |
| 1151 | I(name='BININT1', |
| 1152 | code='K', |
| 1153 | arg=uint1, |
| 1154 | stack_before=[], |
| 1155 | stack_after=[pyint], |
| 1156 | proto=1, |
| 1157 | doc="""Push a one-byte unsigned integer. |
| 1158 | |
| 1159 | This is a space optimization for pickling very small non-negative ints, |
| 1160 | in range(256). |
| 1161 | """), |
| 1162 | |
| 1163 | I(name='BININT2', |
| 1164 | code='M', |
| 1165 | arg=uint2, |
| 1166 | stack_before=[], |
| 1167 | stack_after=[pyint], |
| 1168 | proto=1, |
| 1169 | doc="""Push a two-byte unsigned integer. |
| 1170 | |
| 1171 | This is a space optimization for pickling small positive ints, in |
| 1172 | range(256, 2**16). Integers in range(256) can also be pickled via |
| 1173 | BININT2, but BININT1 instead saves a byte. |
| 1174 | """), |
| 1175 | |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1176 | I(name='LONG', |
| 1177 | code='L', |
| 1178 | arg=decimalnl_long, |
| 1179 | stack_before=[], |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1180 | stack_after=[pyint], |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1181 | proto=0, |
| 1182 | doc="""Push a long integer. |
| 1183 | |
| 1184 | The same as INT, except that the literal ends with 'L', and always |
| 1185 | unpickles to a Python long. There doesn't seem a real purpose to the |
| 1186 | trailing 'L'. |
| 1187 | |
| 1188 | Note that LONG takes time quadratic in the number of digits when |
| 1189 | unpickling (this is simply due to the nature of decimal->binary |
| 1190 | conversion). Proto 2 added linear-time (in C; still quadratic-time |
| 1191 | in Python) LONG1 and LONG4 opcodes. |
| 1192 | """), |
| 1193 | |
| 1194 | I(name="LONG1", |
| 1195 | code='\x8a', |
| 1196 | arg=long1, |
| 1197 | stack_before=[], |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1198 | stack_after=[pyint], |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1199 | proto=2, |
| 1200 | doc="""Long integer using one-byte length. |
| 1201 | |
| 1202 | A more efficient encoding of a Python long; the long1 encoding |
| 1203 | says it all."""), |
| 1204 | |
| 1205 | I(name="LONG4", |
| 1206 | code='\x8b', |
| 1207 | arg=long4, |
| 1208 | stack_before=[], |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1209 | stack_after=[pyint], |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1210 | proto=2, |
| 1211 | doc="""Long integer using found-byte length. |
| 1212 | |
| 1213 | A more efficient encoding of a Python long; the long4 encoding |
| 1214 | says it all."""), |
| 1215 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1216 | # Ways to spell strings (8-bit, not Unicode). |
| 1217 | |
| 1218 | I(name='STRING', |
| 1219 | code='S', |
| 1220 | arg=stringnl, |
| 1221 | stack_before=[], |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1222 | stack_after=[pybytes_or_str], |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1223 | proto=0, |
| 1224 | doc="""Push a Python string object. |
| 1225 | |
| 1226 | The argument is a repr-style string, with bracketing quote characters, |
| 1227 | and perhaps embedded escapes. The argument extends until the next |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1228 | newline character. These are usually decoded into a str instance |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 1229 | using the encoding given to the Unpickler constructor. or the default, |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1230 | 'ASCII'. If the encoding given was 'bytes' however, they will be |
| 1231 | decoded as bytes object instead. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1232 | """), |
| 1233 | |
| 1234 | I(name='BINSTRING', |
| 1235 | code='T', |
| 1236 | arg=string4, |
| 1237 | stack_before=[], |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1238 | stack_after=[pybytes_or_str], |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1239 | proto=1, |
| 1240 | doc="""Push a Python string object. |
| 1241 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1242 | There are two arguments: the first is a 4-byte little-endian |
| 1243 | signed int giving the number of bytes in the string, and the |
| 1244 | second is that many bytes, which are taken literally as the string |
| 1245 | content. These are usually decoded into a str instance using the |
| 1246 | encoding given to the Unpickler constructor. or the default, |
| 1247 | 'ASCII'. If the encoding given was 'bytes' however, they will be |
| 1248 | decoded as bytes object instead. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1249 | """), |
| 1250 | |
| 1251 | I(name='SHORT_BINSTRING', |
| 1252 | code='U', |
| 1253 | arg=string1, |
| 1254 | stack_before=[], |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1255 | stack_after=[pybytes_or_str], |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1256 | proto=1, |
| 1257 | doc="""Push a Python string object. |
| 1258 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1259 | There are two arguments: the first is a 1-byte unsigned int giving |
| 1260 | the number of bytes in the string, and the second is that many |
| 1261 | bytes, which are taken literally as the string content. These are |
| 1262 | usually decoded into a str instance using the encoding given to |
| 1263 | the Unpickler constructor. or the default, 'ASCII'. If the |
| 1264 | encoding given was 'bytes' however, they will be decoded as bytes |
| 1265 | object instead. |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 1266 | """), |
| 1267 | |
| 1268 | # Bytes (protocol 3 only; older protocols don't support bytes at all) |
| 1269 | |
| 1270 | I(name='BINBYTES', |
| 1271 | code='B', |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 1272 | arg=bytes4, |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 1273 | stack_before=[], |
| 1274 | stack_after=[pybytes], |
| 1275 | proto=3, |
| 1276 | doc="""Push a Python bytes object. |
| 1277 | |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 1278 | There are two arguments: the first is a 4-byte little-endian unsigned int |
| 1279 | giving the number of bytes, and the second is that many bytes, which are |
| 1280 | taken literally as the bytes content. |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 1281 | """), |
| 1282 | |
| 1283 | I(name='SHORT_BINBYTES', |
| 1284 | code='C', |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 1285 | arg=bytes1, |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 1286 | stack_before=[], |
| 1287 | stack_after=[pybytes], |
Collin Winter | e61d437 | 2009-05-20 17:46:47 +0000 | [diff] [blame] | 1288 | proto=3, |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 1289 | doc="""Push a Python bytes object. |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 1290 | |
| 1291 | There are two arguments: the first is a 1-byte unsigned int giving |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 1292 | the number of bytes, and the second is that many bytes, which are taken |
| 1293 | literally as the string content. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1294 | """), |
| 1295 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1296 | I(name='BINBYTES8', |
| 1297 | code='\x8e', |
| 1298 | arg=bytes8, |
| 1299 | stack_before=[], |
| 1300 | stack_after=[pybytes], |
| 1301 | proto=4, |
| 1302 | doc="""Push a Python bytes object. |
| 1303 | |
Martin Panter | 4c35964 | 2016-05-08 13:53:41 +0000 | [diff] [blame] | 1304 | There are two arguments: the first is an 8-byte unsigned int giving |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1305 | the number of bytes in the string, and the second is that many bytes, |
| 1306 | which are taken literally as the string content. |
| 1307 | """), |
| 1308 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1309 | # Ways to spell None. |
| 1310 | |
| 1311 | I(name='NONE', |
| 1312 | code='N', |
| 1313 | arg=None, |
| 1314 | stack_before=[], |
| 1315 | stack_after=[pynone], |
| 1316 | proto=0, |
| 1317 | doc="Push None on the stack."), |
| 1318 | |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1319 | # Ways to spell bools, starting with proto 2. See INT for how this was |
| 1320 | # done before proto 2. |
| 1321 | |
| 1322 | I(name='NEWTRUE', |
| 1323 | code='\x88', |
| 1324 | arg=None, |
| 1325 | stack_before=[], |
| 1326 | stack_after=[pybool], |
| 1327 | proto=2, |
| 1328 | doc="""True. |
| 1329 | |
| 1330 | Push True onto the stack."""), |
| 1331 | |
| 1332 | I(name='NEWFALSE', |
| 1333 | code='\x89', |
| 1334 | arg=None, |
| 1335 | stack_before=[], |
| 1336 | stack_after=[pybool], |
| 1337 | proto=2, |
| 1338 | doc="""True. |
| 1339 | |
| 1340 | Push False onto the stack."""), |
| 1341 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1342 | # Ways to spell Unicode strings. |
| 1343 | |
| 1344 | I(name='UNICODE', |
| 1345 | code='V', |
| 1346 | arg=unicodestringnl, |
| 1347 | stack_before=[], |
| 1348 | stack_after=[pyunicode], |
| 1349 | proto=0, # this may be pure-text, but it's a later addition |
| 1350 | doc="""Push a Python Unicode string object. |
| 1351 | |
| 1352 | The argument is a raw-unicode-escape encoding of a Unicode string, |
| 1353 | and so may contain embedded escape sequences. The argument extends |
| 1354 | until the next newline character. |
| 1355 | """), |
| 1356 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1357 | I(name='SHORT_BINUNICODE', |
| 1358 | code='\x8c', |
| 1359 | arg=unicodestring1, |
| 1360 | stack_before=[], |
| 1361 | stack_after=[pyunicode], |
| 1362 | proto=4, |
| 1363 | doc="""Push a Python Unicode string object. |
| 1364 | |
| 1365 | There are two arguments: the first is a 1-byte little-endian signed int |
| 1366 | giving the number of bytes in the string. The second is that many |
| 1367 | bytes, and is the UTF-8 encoding of the Unicode string. |
| 1368 | """), |
| 1369 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1370 | I(name='BINUNICODE', |
| 1371 | code='X', |
| 1372 | arg=unicodestring4, |
| 1373 | stack_before=[], |
| 1374 | stack_after=[pyunicode], |
| 1375 | proto=1, |
| 1376 | doc="""Push a Python Unicode string object. |
| 1377 | |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 1378 | There are two arguments: the first is a 4-byte little-endian unsigned int |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1379 | giving the number of bytes in the string. The second is that many |
| 1380 | bytes, and is the UTF-8 encoding of the Unicode string. |
| 1381 | """), |
| 1382 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1383 | I(name='BINUNICODE8', |
| 1384 | code='\x8d', |
| 1385 | arg=unicodestring8, |
| 1386 | stack_before=[], |
| 1387 | stack_after=[pyunicode], |
| 1388 | proto=4, |
| 1389 | doc="""Push a Python Unicode string object. |
| 1390 | |
Martin Panter | 4c35964 | 2016-05-08 13:53:41 +0000 | [diff] [blame] | 1391 | There are two arguments: the first is an 8-byte little-endian signed int |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1392 | giving the number of bytes in the string. The second is that many |
| 1393 | bytes, and is the UTF-8 encoding of the Unicode string. |
| 1394 | """), |
| 1395 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1396 | # Ways to spell floats. |
| 1397 | |
| 1398 | I(name='FLOAT', |
| 1399 | code='F', |
| 1400 | arg=floatnl, |
| 1401 | stack_before=[], |
| 1402 | stack_after=[pyfloat], |
| 1403 | proto=0, |
| 1404 | doc="""Newline-terminated decimal float literal. |
| 1405 | |
| 1406 | The argument is repr(a_float), and in general requires 17 significant |
| 1407 | digits for roundtrip conversion to be an identity (this is so for |
| 1408 | IEEE-754 double precision values, which is what Python float maps to |
| 1409 | on most boxes). |
| 1410 | |
| 1411 | In general, FLOAT cannot be used to transport infinities, NaNs, or |
| 1412 | minus zero across boxes (or even on a single box, if the platform C |
| 1413 | library can't read the strings it produces for such things -- Windows |
| 1414 | is like that), but may do less damage than BINFLOAT on boxes with |
| 1415 | greater precision or dynamic range than IEEE-754 double. |
| 1416 | """), |
| 1417 | |
| 1418 | I(name='BINFLOAT', |
| 1419 | code='G', |
| 1420 | arg=float8, |
| 1421 | stack_before=[], |
| 1422 | stack_after=[pyfloat], |
| 1423 | proto=1, |
| 1424 | doc="""Float stored in binary form, with 8 bytes of data. |
| 1425 | |
| 1426 | This generally requires less than half the space of FLOAT encoding. |
| 1427 | In general, BINFLOAT cannot be used to transport infinities, NaNs, or |
| 1428 | minus zero, raises an exception if the exponent exceeds the range of |
| 1429 | an IEEE-754 double, and retains no more than 53 bits of precision (if |
| 1430 | there are more than that, "add a half and chop" rounding is used to |
| 1431 | cut it back to 53 significant bits). |
| 1432 | """), |
| 1433 | |
| 1434 | # Ways to build lists. |
| 1435 | |
| 1436 | I(name='EMPTY_LIST', |
| 1437 | code=']', |
| 1438 | arg=None, |
| 1439 | stack_before=[], |
| 1440 | stack_after=[pylist], |
| 1441 | proto=1, |
| 1442 | doc="Push an empty list."), |
| 1443 | |
| 1444 | I(name='APPEND', |
| 1445 | code='a', |
| 1446 | arg=None, |
| 1447 | stack_before=[pylist, anyobject], |
| 1448 | stack_after=[pylist], |
| 1449 | proto=0, |
| 1450 | doc="""Append an object to a list. |
| 1451 | |
| 1452 | Stack before: ... pylist anyobject |
| 1453 | Stack after: ... pylist+[anyobject] |
Tim Peters | 81098ac | 2003-01-28 05:12:08 +0000 | [diff] [blame] | 1454 | |
| 1455 | although pylist is really extended in-place. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1456 | """), |
| 1457 | |
| 1458 | I(name='APPENDS', |
| 1459 | code='e', |
| 1460 | arg=None, |
| 1461 | stack_before=[pylist, markobject, stackslice], |
| 1462 | stack_after=[pylist], |
| 1463 | proto=1, |
| 1464 | doc="""Extend a list by a slice of stack objects. |
| 1465 | |
| 1466 | Stack before: ... pylist markobject stackslice |
| 1467 | Stack after: ... pylist+stackslice |
Tim Peters | 81098ac | 2003-01-28 05:12:08 +0000 | [diff] [blame] | 1468 | |
| 1469 | although pylist is really extended in-place. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1470 | """), |
| 1471 | |
| 1472 | I(name='LIST', |
| 1473 | code='l', |
| 1474 | arg=None, |
| 1475 | stack_before=[markobject, stackslice], |
| 1476 | stack_after=[pylist], |
| 1477 | proto=0, |
| 1478 | doc="""Build a list out of the topmost stack slice, after markobject. |
| 1479 | |
| 1480 | All the stack entries following the topmost markobject are placed into |
| 1481 | a single Python list, which single list object replaces all of the |
| 1482 | stack from the topmost markobject onward. For example, |
| 1483 | |
| 1484 | Stack before: ... markobject 1 2 3 'abc' |
| 1485 | Stack after: ... [1, 2, 3, 'abc'] |
| 1486 | """), |
| 1487 | |
| 1488 | # Ways to build tuples. |
| 1489 | |
| 1490 | I(name='EMPTY_TUPLE', |
| 1491 | code=')', |
| 1492 | arg=None, |
| 1493 | stack_before=[], |
| 1494 | stack_after=[pytuple], |
| 1495 | proto=1, |
| 1496 | doc="Push an empty tuple."), |
| 1497 | |
| 1498 | I(name='TUPLE', |
| 1499 | code='t', |
| 1500 | arg=None, |
| 1501 | stack_before=[markobject, stackslice], |
| 1502 | stack_after=[pytuple], |
| 1503 | proto=0, |
| 1504 | doc="""Build a tuple out of the topmost stack slice, after markobject. |
| 1505 | |
| 1506 | All the stack entries following the topmost markobject are placed into |
| 1507 | a single Python tuple, which single tuple object replaces all of the |
| 1508 | stack from the topmost markobject onward. For example, |
| 1509 | |
| 1510 | Stack before: ... markobject 1 2 3 'abc' |
| 1511 | Stack after: ... (1, 2, 3, 'abc') |
| 1512 | """), |
| 1513 | |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1514 | I(name='TUPLE1', |
| 1515 | code='\x85', |
| 1516 | arg=None, |
| 1517 | stack_before=[anyobject], |
| 1518 | stack_after=[pytuple], |
| 1519 | proto=2, |
Alexander Belopolsky | 44c2ffd | 2010-07-16 14:39:45 +0000 | [diff] [blame] | 1520 | doc="""Build a one-tuple out of the topmost item on the stack. |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1521 | |
| 1522 | This code pops one value off the stack and pushes a tuple of |
Alexander Belopolsky | 44c2ffd | 2010-07-16 14:39:45 +0000 | [diff] [blame] | 1523 | length 1 whose one item is that value back onto it. In other |
| 1524 | words: |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1525 | |
| 1526 | stack[-1] = tuple(stack[-1:]) |
| 1527 | """), |
| 1528 | |
| 1529 | I(name='TUPLE2', |
| 1530 | code='\x86', |
| 1531 | arg=None, |
| 1532 | stack_before=[anyobject, anyobject], |
| 1533 | stack_after=[pytuple], |
| 1534 | proto=2, |
Alexander Belopolsky | 44c2ffd | 2010-07-16 14:39:45 +0000 | [diff] [blame] | 1535 | doc="""Build a two-tuple out of the top two items on the stack. |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1536 | |
Alexander Belopolsky | 44c2ffd | 2010-07-16 14:39:45 +0000 | [diff] [blame] | 1537 | This code pops two values off the stack and pushes a tuple of |
| 1538 | length 2 whose items are those values back onto it. In other |
| 1539 | words: |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1540 | |
| 1541 | stack[-2:] = [tuple(stack[-2:])] |
| 1542 | """), |
| 1543 | |
| 1544 | I(name='TUPLE3', |
| 1545 | code='\x87', |
| 1546 | arg=None, |
| 1547 | stack_before=[anyobject, anyobject, anyobject], |
| 1548 | stack_after=[pytuple], |
| 1549 | proto=2, |
Alexander Belopolsky | 44c2ffd | 2010-07-16 14:39:45 +0000 | [diff] [blame] | 1550 | doc="""Build a three-tuple out of the top three items on the stack. |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1551 | |
Alexander Belopolsky | 44c2ffd | 2010-07-16 14:39:45 +0000 | [diff] [blame] | 1552 | This code pops three values off the stack and pushes a tuple of |
| 1553 | length 3 whose items are those values back onto it. In other |
| 1554 | words: |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1555 | |
| 1556 | stack[-3:] = [tuple(stack[-3:])] |
| 1557 | """), |
| 1558 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1559 | # Ways to build dicts. |
| 1560 | |
| 1561 | I(name='EMPTY_DICT', |
| 1562 | code='}', |
| 1563 | arg=None, |
| 1564 | stack_before=[], |
| 1565 | stack_after=[pydict], |
| 1566 | proto=1, |
| 1567 | doc="Push an empty dict."), |
| 1568 | |
| 1569 | I(name='DICT', |
| 1570 | code='d', |
| 1571 | arg=None, |
| 1572 | stack_before=[markobject, stackslice], |
| 1573 | stack_after=[pydict], |
| 1574 | proto=0, |
| 1575 | doc="""Build a dict out of the topmost stack slice, after markobject. |
| 1576 | |
| 1577 | All the stack entries following the topmost markobject are placed into |
| 1578 | a single Python dict, which single dict object replaces all of the |
| 1579 | stack from the topmost markobject onward. The stack slice alternates |
| 1580 | key, value, key, value, .... For example, |
| 1581 | |
| 1582 | Stack before: ... markobject 1 2 3 'abc' |
| 1583 | Stack after: ... {1: 2, 3: 'abc'} |
| 1584 | """), |
| 1585 | |
| 1586 | I(name='SETITEM', |
| 1587 | code='s', |
| 1588 | arg=None, |
| 1589 | stack_before=[pydict, anyobject, anyobject], |
| 1590 | stack_after=[pydict], |
| 1591 | proto=0, |
| 1592 | doc="""Add a key+value pair to an existing dict. |
| 1593 | |
| 1594 | Stack before: ... pydict key value |
| 1595 | Stack after: ... pydict |
| 1596 | |
| 1597 | where pydict has been modified via pydict[key] = value. |
| 1598 | """), |
| 1599 | |
| 1600 | I(name='SETITEMS', |
| 1601 | code='u', |
| 1602 | arg=None, |
| 1603 | stack_before=[pydict, markobject, stackslice], |
| 1604 | stack_after=[pydict], |
| 1605 | proto=1, |
| 1606 | doc="""Add an arbitrary number of key+value pairs to an existing dict. |
| 1607 | |
| 1608 | The slice of the stack following the topmost markobject is taken as |
| 1609 | an alternating sequence of keys and values, added to the dict |
| 1610 | immediately under the topmost markobject. Everything at and after the |
| 1611 | topmost markobject is popped, leaving the mutated dict at the top |
| 1612 | of the stack. |
| 1613 | |
| 1614 | Stack before: ... pydict markobject key_1 value_1 ... key_n value_n |
| 1615 | Stack after: ... pydict |
| 1616 | |
| 1617 | where pydict has been modified via pydict[key_i] = value_i for i in |
| 1618 | 1, 2, ..., n, and in that order. |
| 1619 | """), |
| 1620 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1621 | # Ways to build sets |
| 1622 | |
| 1623 | I(name='EMPTY_SET', |
| 1624 | code='\x8f', |
| 1625 | arg=None, |
| 1626 | stack_before=[], |
| 1627 | stack_after=[pyset], |
| 1628 | proto=4, |
| 1629 | doc="Push an empty set."), |
| 1630 | |
| 1631 | I(name='ADDITEMS', |
| 1632 | code='\x90', |
| 1633 | arg=None, |
| 1634 | stack_before=[pyset, markobject, stackslice], |
| 1635 | stack_after=[pyset], |
| 1636 | proto=4, |
| 1637 | doc="""Add an arbitrary number of items to an existing set. |
| 1638 | |
| 1639 | The slice of the stack following the topmost markobject is taken as |
| 1640 | a sequence of items, added to the set immediately under the topmost |
| 1641 | markobject. Everything at and after the topmost markobject is popped, |
| 1642 | leaving the mutated set at the top of the stack. |
| 1643 | |
| 1644 | Stack before: ... pyset markobject item_1 ... item_n |
| 1645 | Stack after: ... pyset |
| 1646 | |
| 1647 | where pyset has been modified via pyset.add(item_i) = item_i for i in |
| 1648 | 1, 2, ..., n, and in that order. |
| 1649 | """), |
| 1650 | |
| 1651 | # Way to build frozensets |
| 1652 | |
| 1653 | I(name='FROZENSET', |
| 1654 | code='\x91', |
| 1655 | arg=None, |
| 1656 | stack_before=[markobject, stackslice], |
| 1657 | stack_after=[pyfrozenset], |
| 1658 | proto=4, |
| 1659 | doc="""Build a frozenset out of the topmost slice, after markobject. |
| 1660 | |
| 1661 | All the stack entries following the topmost markobject are placed into |
| 1662 | a single Python frozenset, which single frozenset object replaces all |
| 1663 | of the stack from the topmost markobject onward. For example, |
| 1664 | |
| 1665 | Stack before: ... markobject 1 2 3 |
| 1666 | Stack after: ... frozenset({1, 2, 3}) |
| 1667 | """), |
| 1668 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1669 | # Stack manipulation. |
| 1670 | |
| 1671 | I(name='POP', |
| 1672 | code='0', |
| 1673 | arg=None, |
| 1674 | stack_before=[anyobject], |
| 1675 | stack_after=[], |
| 1676 | proto=0, |
| 1677 | doc="Discard the top stack item, shrinking the stack by one item."), |
| 1678 | |
| 1679 | I(name='DUP', |
| 1680 | code='2', |
| 1681 | arg=None, |
| 1682 | stack_before=[anyobject], |
| 1683 | stack_after=[anyobject, anyobject], |
| 1684 | proto=0, |
| 1685 | doc="Push the top stack item onto the stack again, duplicating it."), |
| 1686 | |
| 1687 | I(name='MARK', |
| 1688 | code='(', |
| 1689 | arg=None, |
| 1690 | stack_before=[], |
| 1691 | stack_after=[markobject], |
| 1692 | proto=0, |
| 1693 | doc="""Push markobject onto the stack. |
| 1694 | |
| 1695 | markobject is a unique object, used by other opcodes to identify a |
| 1696 | region of the stack containing a variable number of objects for them |
| 1697 | to work on. See markobject.doc for more detail. |
| 1698 | """), |
| 1699 | |
| 1700 | I(name='POP_MARK', |
| 1701 | code='1', |
| 1702 | arg=None, |
| 1703 | stack_before=[markobject, stackslice], |
| 1704 | stack_after=[], |
Collin Winter | e61d437 | 2009-05-20 17:46:47 +0000 | [diff] [blame] | 1705 | proto=1, |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1706 | doc="""Pop all the stack objects at and above the topmost markobject. |
| 1707 | |
| 1708 | When an opcode using a variable number of stack objects is done, |
| 1709 | POP_MARK is used to remove those objects, and to remove the markobject |
| 1710 | that delimited their starting position on the stack. |
| 1711 | """), |
| 1712 | |
| 1713 | # Memo manipulation. There are really only two operations (get and put), |
| 1714 | # each in all-text, "short binary", and "long binary" flavors. |
| 1715 | |
| 1716 | I(name='GET', |
| 1717 | code='g', |
| 1718 | arg=decimalnl_short, |
| 1719 | stack_before=[], |
| 1720 | stack_after=[anyobject], |
| 1721 | proto=0, |
| 1722 | doc="""Read an object from the memo and push it on the stack. |
| 1723 | |
Ezio Melotti | 1392500 | 2011-03-16 11:05:33 +0200 | [diff] [blame] | 1724 | The index of the memo object to push is given by the newline-terminated |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1725 | decimal string following. BINGET and LONG_BINGET are space-optimized |
| 1726 | versions. |
| 1727 | """), |
| 1728 | |
| 1729 | I(name='BINGET', |
| 1730 | code='h', |
| 1731 | arg=uint1, |
| 1732 | stack_before=[], |
| 1733 | stack_after=[anyobject], |
| 1734 | proto=1, |
| 1735 | doc="""Read an object from the memo and push it on the stack. |
| 1736 | |
| 1737 | The index of the memo object to push is given by the 1-byte unsigned |
| 1738 | integer following. |
| 1739 | """), |
| 1740 | |
| 1741 | I(name='LONG_BINGET', |
| 1742 | code='j', |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 1743 | arg=uint4, |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1744 | stack_before=[], |
| 1745 | stack_after=[anyobject], |
| 1746 | proto=1, |
| 1747 | doc="""Read an object from the memo and push it on the stack. |
| 1748 | |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 1749 | The index of the memo object to push is given by the 4-byte unsigned |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1750 | little-endian integer following. |
| 1751 | """), |
| 1752 | |
| 1753 | I(name='PUT', |
| 1754 | code='p', |
| 1755 | arg=decimalnl_short, |
| 1756 | stack_before=[], |
| 1757 | stack_after=[], |
| 1758 | proto=0, |
| 1759 | doc="""Store the stack top into the memo. The stack is not popped. |
| 1760 | |
| 1761 | The index of the memo location to write into is given by the newline- |
| 1762 | terminated decimal string following. BINPUT and LONG_BINPUT are |
| 1763 | space-optimized versions. |
| 1764 | """), |
| 1765 | |
| 1766 | I(name='BINPUT', |
| 1767 | code='q', |
| 1768 | arg=uint1, |
| 1769 | stack_before=[], |
| 1770 | stack_after=[], |
| 1771 | proto=1, |
| 1772 | doc="""Store the stack top into the memo. The stack is not popped. |
| 1773 | |
| 1774 | The index of the memo location to write into is given by the 1-byte |
| 1775 | unsigned integer following. |
| 1776 | """), |
| 1777 | |
| 1778 | I(name='LONG_BINPUT', |
| 1779 | code='r', |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 1780 | arg=uint4, |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1781 | stack_before=[], |
| 1782 | stack_after=[], |
| 1783 | proto=1, |
| 1784 | doc="""Store the stack top into the memo. The stack is not popped. |
| 1785 | |
| 1786 | The index of the memo location to write into is given by the 4-byte |
Alexandre Vassalotti | 8db89ca | 2013-04-14 03:30:35 -0700 | [diff] [blame] | 1787 | unsigned little-endian integer following. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1788 | """), |
| 1789 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1790 | I(name='MEMOIZE', |
| 1791 | code='\x94', |
| 1792 | arg=None, |
| 1793 | stack_before=[anyobject], |
| 1794 | stack_after=[anyobject], |
| 1795 | proto=4, |
| 1796 | doc="""Store the stack top into the memo. The stack is not popped. |
| 1797 | |
| 1798 | The index of the memo location to write is the number of |
| 1799 | elements currently present in the memo. |
| 1800 | """), |
| 1801 | |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 1802 | # Access the extension registry (predefined objects). Akin to the GET |
| 1803 | # family. |
| 1804 | |
| 1805 | I(name='EXT1', |
| 1806 | code='\x82', |
| 1807 | arg=uint1, |
| 1808 | stack_before=[], |
| 1809 | stack_after=[anyobject], |
| 1810 | proto=2, |
| 1811 | doc="""Extension code. |
| 1812 | |
| 1813 | This code and the similar EXT2 and EXT4 allow using a registry |
| 1814 | of popular objects that are pickled by name, typically classes. |
| 1815 | It is envisioned that through a global negotiation and |
| 1816 | registration process, third parties can set up a mapping between |
| 1817 | ints and object names. |
| 1818 | |
| 1819 | In order to guarantee pickle interchangeability, the extension |
| 1820 | code registry ought to be global, although a range of codes may |
| 1821 | be reserved for private use. |
| 1822 | |
| 1823 | EXT1 has a 1-byte integer argument. This is used to index into the |
| 1824 | extension registry, and the object at that index is pushed on the stack. |
| 1825 | """), |
| 1826 | |
| 1827 | I(name='EXT2', |
| 1828 | code='\x83', |
| 1829 | arg=uint2, |
| 1830 | stack_before=[], |
| 1831 | stack_after=[anyobject], |
| 1832 | proto=2, |
| 1833 | doc="""Extension code. |
| 1834 | |
| 1835 | See EXT1. EXT2 has a two-byte integer argument. |
| 1836 | """), |
| 1837 | |
| 1838 | I(name='EXT4', |
| 1839 | code='\x84', |
| 1840 | arg=int4, |
| 1841 | stack_before=[], |
| 1842 | stack_after=[anyobject], |
| 1843 | proto=2, |
| 1844 | doc="""Extension code. |
| 1845 | |
| 1846 | See EXT1. EXT4 has a four-byte integer argument. |
| 1847 | """), |
| 1848 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1849 | # Push a class object, or module function, on the stack, via its module |
| 1850 | # and name. |
| 1851 | |
| 1852 | I(name='GLOBAL', |
| 1853 | code='c', |
| 1854 | arg=stringnl_noescape_pair, |
| 1855 | stack_before=[], |
| 1856 | stack_after=[anyobject], |
| 1857 | proto=0, |
| 1858 | doc="""Push a global object (module.attr) on the stack. |
| 1859 | |
| 1860 | Two newline-terminated strings follow the GLOBAL opcode. The first is |
| 1861 | taken as a module name, and the second as a class name. The class |
| 1862 | object module.class is pushed on the stack. More accurately, the |
| 1863 | object returned by self.find_class(module, class) is pushed on the |
| 1864 | stack, so unpickling subclasses can override this form of lookup. |
| 1865 | """), |
| 1866 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1867 | I(name='STACK_GLOBAL', |
| 1868 | code='\x93', |
| 1869 | arg=None, |
| 1870 | stack_before=[pyunicode, pyunicode], |
| 1871 | stack_after=[anyobject], |
Serhiy Storchaka | 5805dde | 2015-10-13 21:12:32 +0300 | [diff] [blame] | 1872 | proto=4, |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1873 | doc="""Push a global object (module.attr) on the stack. |
| 1874 | """), |
| 1875 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1876 | # Ways to build objects of classes pickle doesn't know about directly |
| 1877 | # (user-defined classes). I despair of documenting this accurately |
| 1878 | # and comprehensibly -- you really have to read the pickle code to |
| 1879 | # find all the special cases. |
| 1880 | |
| 1881 | I(name='REDUCE', |
| 1882 | code='R', |
| 1883 | arg=None, |
| 1884 | stack_before=[anyobject, anyobject], |
| 1885 | stack_after=[anyobject], |
| 1886 | proto=0, |
| 1887 | doc="""Push an object built from a callable and an argument tuple. |
| 1888 | |
| 1889 | The opcode is named to remind of the __reduce__() method. |
| 1890 | |
| 1891 | Stack before: ... callable pytuple |
| 1892 | Stack after: ... callable(*pytuple) |
| 1893 | |
| 1894 | The callable and the argument tuple are the first two items returned |
| 1895 | by a __reduce__ method. Applying the callable to the argtuple is |
| 1896 | supposed to reproduce the original object, or at least get it started. |
| 1897 | If the __reduce__ method returns a 3-tuple, the last component is an |
| 1898 | argument to be passed to the object's __setstate__, and then the REDUCE |
| 1899 | opcode is followed by code to create setstate's argument, and then a |
| 1900 | BUILD opcode to apply __setstate__ to that argument. |
| 1901 | |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 1902 | If not isinstance(callable, type), REDUCE complains unless the |
Alexandre Vassalotti | f7fa63d | 2008-05-11 08:55:36 +0000 | [diff] [blame] | 1903 | callable has been registered with the copyreg module's |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1904 | safe_constructors dict, or the callable has a magic |
| 1905 | '__safe_for_unpickling__' attribute with a true value. I'm not sure |
| 1906 | why it does this, but I've sure seen this complaint often enough when |
| 1907 | I didn't want to <wink>. |
| 1908 | """), |
| 1909 | |
| 1910 | I(name='BUILD', |
| 1911 | code='b', |
| 1912 | arg=None, |
| 1913 | stack_before=[anyobject, anyobject], |
| 1914 | stack_after=[anyobject], |
| 1915 | proto=0, |
| 1916 | doc="""Finish building an object, via __setstate__ or dict update. |
| 1917 | |
| 1918 | Stack before: ... anyobject argument |
| 1919 | Stack after: ... anyobject |
| 1920 | |
| 1921 | where anyobject may have been mutated, as follows: |
| 1922 | |
| 1923 | If the object has a __setstate__ method, |
| 1924 | |
| 1925 | anyobject.__setstate__(argument) |
| 1926 | |
| 1927 | is called. |
| 1928 | |
| 1929 | Else the argument must be a dict, the object must have a __dict__, and |
| 1930 | the object is updated via |
| 1931 | |
| 1932 | anyobject.__dict__.update(argument) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1933 | """), |
| 1934 | |
| 1935 | I(name='INST', |
| 1936 | code='i', |
| 1937 | arg=stringnl_noescape_pair, |
| 1938 | stack_before=[markobject, stackslice], |
| 1939 | stack_after=[anyobject], |
| 1940 | proto=0, |
| 1941 | doc="""Build a class instance. |
| 1942 | |
| 1943 | This is the protocol 0 version of protocol 1's OBJ opcode. |
| 1944 | INST is followed by two newline-terminated strings, giving a |
| 1945 | module and class name, just as for the GLOBAL opcode (and see |
| 1946 | GLOBAL for more details about that). self.find_class(module, name) |
| 1947 | is used to get a class object. |
| 1948 | |
| 1949 | In addition, all the objects on the stack following the topmost |
| 1950 | markobject are gathered into a tuple and popped (along with the |
| 1951 | topmost markobject), just as for the TUPLE opcode. |
| 1952 | |
| 1953 | Now it gets complicated. If all of these are true: |
| 1954 | |
| 1955 | + The argtuple is empty (markobject was at the top of the stack |
| 1956 | at the start). |
| 1957 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1958 | + The class object does not have a __getinitargs__ attribute. |
| 1959 | |
| 1960 | then we want to create an old-style class instance without invoking |
| 1961 | its __init__() method (pickle has waffled on this over the years; not |
| 1962 | calling __init__() is current wisdom). In this case, an instance of |
| 1963 | an old-style dummy class is created, and then we try to rebind its |
| 1964 | __class__ attribute to the desired class object. If this succeeds, |
Guido van Rossum | a8add0e | 2007-05-14 22:03:55 +0000 | [diff] [blame] | 1965 | the new instance object is pushed on the stack, and we're done. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1966 | |
| 1967 | Else (the argtuple is not empty, it's not an old-style class object, |
| 1968 | or the class object does have a __getinitargs__ attribute), the code |
| 1969 | first insists that the class object have a __safe_for_unpickling__ |
| 1970 | attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE, |
| 1971 | it doesn't matter whether this attribute has a true or false value, it |
Guido van Rossum | 99603b0 | 2007-07-20 00:22:32 +0000 | [diff] [blame] | 1972 | only matters whether it exists (XXX this is a bug). If |
| 1973 | __safe_for_unpickling__ doesn't exist, UnpicklingError is raised. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1974 | |
| 1975 | Else (the class object does have a __safe_for_unpickling__ attr), |
| 1976 | the class object obtained from INST's arguments is applied to the |
| 1977 | argtuple obtained from the stack, and the resulting instance object |
| 1978 | is pushed on the stack. |
Tim Peters | 2b93c4c | 2003-01-30 16:35:08 +0000 | [diff] [blame] | 1979 | |
| 1980 | NOTE: checks for __safe_for_unpickling__ went away in Python 2.3. |
Florent Xicluna | aa6c1d2 | 2011-12-12 18:54:29 +0100 | [diff] [blame] | 1981 | NOTE: the distinction between old-style and new-style classes does |
| 1982 | not make sense in Python 3. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 1983 | """), |
| 1984 | |
| 1985 | I(name='OBJ', |
| 1986 | code='o', |
| 1987 | arg=None, |
| 1988 | stack_before=[markobject, anyobject, stackslice], |
| 1989 | stack_after=[anyobject], |
| 1990 | proto=1, |
| 1991 | doc="""Build a class instance. |
| 1992 | |
| 1993 | This is the protocol 1 version of protocol 0's INST opcode, and is |
| 1994 | very much like it. The major difference is that the class object |
| 1995 | is taken off the stack, allowing it to be retrieved from the memo |
| 1996 | repeatedly if several instances of the same class are created. This |
| 1997 | can be much more efficient (in both time and space) than repeatedly |
| 1998 | embedding the module and class names in INST opcodes. |
| 1999 | |
| 2000 | Unlike INST, OBJ takes no arguments from the opcode stream. Instead |
| 2001 | the class object is taken off the stack, immediately above the |
| 2002 | topmost markobject: |
| 2003 | |
| 2004 | Stack before: ... markobject classobject stackslice |
| 2005 | Stack after: ... new_instance_object |
| 2006 | |
| 2007 | As for INST, the remainder of the stack above the markobject is |
| 2008 | gathered into an argument tuple, and then the logic seems identical, |
Guido van Rossum | ecb1104 | 2003-01-29 06:24:30 +0000 | [diff] [blame] | 2009 | except that no __safe_for_unpickling__ check is done (XXX this is |
Guido van Rossum | 99603b0 | 2007-07-20 00:22:32 +0000 | [diff] [blame] | 2010 | a bug). See INST for the gory details. |
Tim Peters | 2b93c4c | 2003-01-30 16:35:08 +0000 | [diff] [blame] | 2011 | |
| 2012 | NOTE: In Python 2.3, INST and OBJ are identical except for how they |
| 2013 | get the class object. That was always the intent; the implementations |
| 2014 | had diverged for accidental reasons. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2015 | """), |
| 2016 | |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 2017 | I(name='NEWOBJ', |
| 2018 | code='\x81', |
| 2019 | arg=None, |
| 2020 | stack_before=[anyobject, anyobject], |
| 2021 | stack_after=[anyobject], |
| 2022 | proto=2, |
| 2023 | doc="""Build an object instance. |
| 2024 | |
| 2025 | The stack before should be thought of as containing a class |
| 2026 | object followed by an argument tuple (the tuple being the stack |
| 2027 | top). Call these cls and args. They are popped off the stack, |
| 2028 | and the value returned by cls.__new__(cls, *args) is pushed back |
| 2029 | onto the stack. |
| 2030 | """), |
| 2031 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2032 | I(name='NEWOBJ_EX', |
| 2033 | code='\x92', |
| 2034 | arg=None, |
| 2035 | stack_before=[anyobject, anyobject, anyobject], |
| 2036 | stack_after=[anyobject], |
| 2037 | proto=4, |
| 2038 | doc="""Build an object instance. |
| 2039 | |
| 2040 | The stack before should be thought of as containing a class |
| 2041 | object followed by an argument tuple and by a keyword argument dict |
| 2042 | (the dict being the stack top). Call these cls and args. They are |
| 2043 | popped off the stack, and the value returned by |
| 2044 | cls.__new__(cls, *args, *kwargs) is pushed back onto the stack. |
| 2045 | """), |
| 2046 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2047 | # Machine control. |
| 2048 | |
Tim Peters | fdc0346 | 2003-01-28 04:56:33 +0000 | [diff] [blame] | 2049 | I(name='PROTO', |
| 2050 | code='\x80', |
| 2051 | arg=uint1, |
| 2052 | stack_before=[], |
| 2053 | stack_after=[], |
| 2054 | proto=2, |
| 2055 | doc="""Protocol version indicator. |
| 2056 | |
| 2057 | For protocol 2 and above, a pickle must start with this opcode. |
| 2058 | The argument is the protocol version, an int in range(2, 256). |
| 2059 | """), |
| 2060 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2061 | I(name='STOP', |
| 2062 | code='.', |
| 2063 | arg=None, |
| 2064 | stack_before=[anyobject], |
| 2065 | stack_after=[], |
| 2066 | proto=0, |
| 2067 | doc="""Stop the unpickling machine. |
| 2068 | |
| 2069 | Every pickle ends with this opcode. The object at the top of the stack |
| 2070 | is popped, and that's the result of unpickling. The stack should be |
| 2071 | empty then. |
| 2072 | """), |
| 2073 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2074 | # Framing support. |
| 2075 | |
| 2076 | I(name='FRAME', |
| 2077 | code='\x95', |
| 2078 | arg=uint8, |
| 2079 | stack_before=[], |
| 2080 | stack_after=[], |
| 2081 | proto=4, |
| 2082 | doc="""Indicate the beginning of a new frame. |
| 2083 | |
| 2084 | The unpickler may use this opcode to safely prefetch data from its |
| 2085 | underlying stream. |
| 2086 | """), |
| 2087 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2088 | # Ways to deal with persistent IDs. |
| 2089 | |
| 2090 | I(name='PERSID', |
| 2091 | code='P', |
| 2092 | arg=stringnl_noescape, |
| 2093 | stack_before=[], |
| 2094 | stack_after=[anyobject], |
| 2095 | proto=0, |
| 2096 | doc="""Push an object identified by a persistent ID. |
| 2097 | |
| 2098 | The pickle module doesn't define what a persistent ID means. PERSID's |
| 2099 | argument is a newline-terminated str-style (no embedded escapes, no |
| 2100 | bracketing quote characters) string, which *is* "the persistent ID". |
| 2101 | The unpickler passes this string to self.persistent_load(). Whatever |
| 2102 | object that returns is pushed on the stack. There is no implementation |
| 2103 | of persistent_load() in Python's unpickler: it must be supplied by an |
| 2104 | unpickler subclass. |
| 2105 | """), |
| 2106 | |
| 2107 | I(name='BINPERSID', |
| 2108 | code='Q', |
| 2109 | arg=None, |
| 2110 | stack_before=[anyobject], |
| 2111 | stack_after=[anyobject], |
| 2112 | proto=1, |
| 2113 | doc="""Push an object identified by a persistent ID. |
| 2114 | |
| 2115 | Like PERSID, except the persistent ID is popped off the stack (instead |
| 2116 | of being a string embedded in the opcode bytestream). The persistent |
| 2117 | ID is passed to self.persistent_load(), and whatever object that |
| 2118 | returns is pushed on the stack. See PERSID for more detail. |
| 2119 | """), |
| 2120 | ] |
| 2121 | del I |
| 2122 | |
| 2123 | # Verify uniqueness of .name and .code members. |
| 2124 | name2i = {} |
| 2125 | code2i = {} |
| 2126 | |
| 2127 | for i, d in enumerate(opcodes): |
| 2128 | if d.name in name2i: |
| 2129 | raise ValueError("repeated name %r at indices %d and %d" % |
| 2130 | (d.name, name2i[d.name], i)) |
| 2131 | if d.code in code2i: |
| 2132 | raise ValueError("repeated code %r at indices %d and %d" % |
| 2133 | (d.code, code2i[d.code], i)) |
| 2134 | |
| 2135 | name2i[d.name] = i |
| 2136 | code2i[d.code] = i |
| 2137 | |
| 2138 | del name2i, code2i, i, d |
| 2139 | |
| 2140 | ############################################################################## |
| 2141 | # Build a code2op dict, mapping opcode characters to OpcodeInfo records. |
| 2142 | # Also ensure we've got the same stuff as pickle.py, although the |
| 2143 | # introspection here is dicey. |
| 2144 | |
| 2145 | code2op = {} |
| 2146 | for d in opcodes: |
| 2147 | code2op[d.code] = d |
| 2148 | del d |
| 2149 | |
| 2150 | def assure_pickle_consistency(verbose=False): |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2151 | |
| 2152 | copy = code2op.copy() |
| 2153 | for name in pickle.__all__: |
| 2154 | if not re.match("[A-Z][A-Z0-9_]+$", name): |
| 2155 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 2156 | print("skipping %r: it doesn't look like an opcode name" % name) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2157 | continue |
| 2158 | picklecode = getattr(pickle, name) |
Guido van Rossum | 617dbc4 | 2007-05-07 23:57:08 +0000 | [diff] [blame] | 2159 | if not isinstance(picklecode, bytes) or len(picklecode) != 1: |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2160 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 2161 | print(("skipping %r: value %r doesn't look like a pickle " |
| 2162 | "code" % (name, picklecode))) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2163 | continue |
Guido van Rossum | 617dbc4 | 2007-05-07 23:57:08 +0000 | [diff] [blame] | 2164 | picklecode = picklecode.decode("latin-1") |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2165 | if picklecode in copy: |
| 2166 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 2167 | print("checking name %r w/ code %r for consistency" % ( |
| 2168 | name, picklecode)) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2169 | d = copy[picklecode] |
| 2170 | if d.name != name: |
| 2171 | raise ValueError("for pickle code %r, pickle.py uses name %r " |
| 2172 | "but we're using name %r" % (picklecode, |
| 2173 | name, |
| 2174 | d.name)) |
| 2175 | # Forget this one. Any left over in copy at the end are a problem |
| 2176 | # of a different kind. |
| 2177 | del copy[picklecode] |
| 2178 | else: |
| 2179 | raise ValueError("pickle.py appears to have a pickle opcode with " |
| 2180 | "name %r and code %r, but we don't" % |
| 2181 | (name, picklecode)) |
| 2182 | if copy: |
| 2183 | msg = ["we appear to have pickle opcodes that pickle.py doesn't have:"] |
| 2184 | for code, d in copy.items(): |
| 2185 | msg.append(" name %r with code %r" % (d.name, code)) |
| 2186 | raise ValueError("\n".join(msg)) |
| 2187 | |
| 2188 | assure_pickle_consistency() |
Tim Peters | c0c12b5 | 2003-01-29 00:56:17 +0000 | [diff] [blame] | 2189 | del assure_pickle_consistency |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2190 | |
| 2191 | ############################################################################## |
| 2192 | # A pickle opcode generator. |
| 2193 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2194 | def _genops(data, yield_end_pos=False): |
| 2195 | if isinstance(data, bytes_types): |
| 2196 | data = io.BytesIO(data) |
| 2197 | |
| 2198 | if hasattr(data, "tell"): |
| 2199 | getpos = data.tell |
| 2200 | else: |
| 2201 | getpos = lambda: None |
| 2202 | |
| 2203 | while True: |
| 2204 | pos = getpos() |
| 2205 | code = data.read(1) |
| 2206 | opcode = code2op.get(code.decode("latin-1")) |
| 2207 | if opcode is None: |
| 2208 | if code == b"": |
| 2209 | raise ValueError("pickle exhausted before seeing STOP") |
| 2210 | else: |
| 2211 | raise ValueError("at position %s, opcode %r unknown" % ( |
| 2212 | "<unknown>" if pos is None else pos, |
| 2213 | code)) |
| 2214 | if opcode.arg is None: |
| 2215 | arg = None |
| 2216 | else: |
| 2217 | arg = opcode.arg.reader(data) |
| 2218 | if yield_end_pos: |
| 2219 | yield opcode, arg, pos, getpos() |
| 2220 | else: |
| 2221 | yield opcode, arg, pos |
| 2222 | if code == b'.': |
| 2223 | assert opcode.name == 'STOP' |
| 2224 | break |
| 2225 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2226 | def genops(pickle): |
Guido van Rossum | a72ded9 | 2003-01-27 19:40:47 +0000 | [diff] [blame] | 2227 | """Generate all the opcodes in a pickle. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2228 | |
| 2229 | 'pickle' is a file-like object, or string, containing the pickle. |
| 2230 | |
| 2231 | Each opcode in the pickle is generated, from the current pickle position, |
| 2232 | stopping after a STOP opcode is delivered. A triple is generated for |
| 2233 | each opcode: |
| 2234 | |
| 2235 | opcode, arg, pos |
| 2236 | |
| 2237 | opcode is an OpcodeInfo record, describing the current opcode. |
| 2238 | |
| 2239 | If the opcode has an argument embedded in the pickle, arg is its decoded |
| 2240 | value, as a Python object. If the opcode doesn't have an argument, arg |
| 2241 | is None. |
| 2242 | |
| 2243 | If the pickle has a tell() method, pos was the value of pickle.tell() |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 2244 | before reading the current opcode. If the pickle is a bytes object, |
| 2245 | it's wrapped in a BytesIO object, and the latter's tell() result is |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2246 | used. Else (the pickle doesn't have a tell(), and it's not obvious how |
| 2247 | to query its current position) pos is None. |
| 2248 | """ |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2249 | return _genops(pickle) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2250 | |
| 2251 | ############################################################################## |
Christian Heimes | 3feef61 | 2008-02-11 06:19:17 +0000 | [diff] [blame] | 2252 | # A pickle optimizer. |
| 2253 | |
| 2254 | def optimize(p): |
| 2255 | 'Optimize a pickle string by removing unused PUT opcodes' |
Serhiy Storchaka | 05dadcf | 2014-12-16 18:00:56 +0200 | [diff] [blame] | 2256 | put = 'PUT' |
| 2257 | get = 'GET' |
| 2258 | oldids = set() # set of all PUT ids |
| 2259 | newids = {} # set of ids used by a GET opcode |
| 2260 | opcodes = [] # (op, idx) or (pos, end_pos) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2261 | proto = 0 |
Serhiy Storchaka | 05dadcf | 2014-12-16 18:00:56 +0200 | [diff] [blame] | 2262 | protoheader = b'' |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2263 | for opcode, arg, pos, end_pos in _genops(p, yield_end_pos=True): |
Christian Heimes | 3feef61 | 2008-02-11 06:19:17 +0000 | [diff] [blame] | 2264 | if 'PUT' in opcode.name: |
Serhiy Storchaka | 05dadcf | 2014-12-16 18:00:56 +0200 | [diff] [blame] | 2265 | oldids.add(arg) |
| 2266 | opcodes.append((put, arg)) |
| 2267 | elif opcode.name == 'MEMOIZE': |
| 2268 | idx = len(oldids) |
| 2269 | oldids.add(idx) |
| 2270 | opcodes.append((put, idx)) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2271 | elif 'FRAME' in opcode.name: |
| 2272 | pass |
Serhiy Storchaka | 05dadcf | 2014-12-16 18:00:56 +0200 | [diff] [blame] | 2273 | elif 'GET' in opcode.name: |
| 2274 | if opcode.proto > proto: |
| 2275 | proto = opcode.proto |
| 2276 | newids[arg] = None |
| 2277 | opcodes.append((get, arg)) |
| 2278 | elif opcode.name == 'PROTO': |
| 2279 | if arg > proto: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2280 | proto = arg |
Serhiy Storchaka | 05dadcf | 2014-12-16 18:00:56 +0200 | [diff] [blame] | 2281 | if pos == 0: |
| 2282 | protoheader = p[pos: end_pos] |
| 2283 | else: |
| 2284 | opcodes.append((pos, end_pos)) |
| 2285 | else: |
| 2286 | opcodes.append((pos, end_pos)) |
| 2287 | del oldids |
Christian Heimes | 3feef61 | 2008-02-11 06:19:17 +0000 | [diff] [blame] | 2288 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2289 | # Copy the opcodes except for PUTS without a corresponding GET |
| 2290 | out = io.BytesIO() |
Serhiy Storchaka | 05dadcf | 2014-12-16 18:00:56 +0200 | [diff] [blame] | 2291 | # Write the PROTO header before any framing |
| 2292 | out.write(protoheader) |
| 2293 | pickler = pickle._Pickler(out, proto) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2294 | if proto >= 4: |
Serhiy Storchaka | 05dadcf | 2014-12-16 18:00:56 +0200 | [diff] [blame] | 2295 | pickler.framer.start_framing() |
| 2296 | idx = 0 |
| 2297 | for op, arg in opcodes: |
| 2298 | if op is put: |
| 2299 | if arg not in newids: |
| 2300 | continue |
| 2301 | data = pickler.put(idx) |
| 2302 | newids[arg] = idx |
| 2303 | idx += 1 |
| 2304 | elif op is get: |
| 2305 | data = pickler.get(newids[arg]) |
| 2306 | else: |
| 2307 | data = p[op:arg] |
| 2308 | pickler.framer.commit_frame() |
| 2309 | pickler.write(data) |
| 2310 | pickler.framer.end_framing() |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2311 | return out.getvalue() |
Christian Heimes | 3feef61 | 2008-02-11 06:19:17 +0000 | [diff] [blame] | 2312 | |
| 2313 | ############################################################################## |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2314 | # A symbolic pickle disassembler. |
| 2315 | |
Alexander Belopolsky | 929d384 | 2010-07-17 15:51:21 +0000 | [diff] [blame] | 2316 | def dis(pickle, out=None, memo=None, indentlevel=4, annotate=0): |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2317 | """Produce a symbolic disassembly of a pickle. |
| 2318 | |
| 2319 | 'pickle' is a file-like object, or string, containing a (at least one) |
| 2320 | pickle. The pickle is disassembled from the current position, through |
| 2321 | the first STOP opcode encountered. |
| 2322 | |
| 2323 | Optional arg 'out' is a file-like object to which the disassembly is |
| 2324 | printed. It defaults to sys.stdout. |
| 2325 | |
Tim Peters | 62235e7 | 2003-02-05 19:55:53 +0000 | [diff] [blame] | 2326 | Optional arg 'memo' is a Python dict, used as the pickle's memo. It |
| 2327 | may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. |
| 2328 | Passing the same memo object to another dis() call then allows disassembly |
| 2329 | to proceed across multiple pickles that were all created by the same |
| 2330 | pickler with the same memo. Ordinarily you don't need to worry about this. |
| 2331 | |
Alexander Belopolsky | 929d384 | 2010-07-17 15:51:21 +0000 | [diff] [blame] | 2332 | Optional arg 'indentlevel' is the number of blanks by which to indent |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2333 | a new MARK level. It defaults to 4. |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2334 | |
Alexander Belopolsky | 929d384 | 2010-07-17 15:51:21 +0000 | [diff] [blame] | 2335 | Optional arg 'annotate' if nonzero instructs dis() to add short |
| 2336 | description of the opcode on each line of disassembled output. |
| 2337 | The value given to 'annotate' must be an integer and is used as a |
| 2338 | hint for the column where annotation should start. The default |
| 2339 | value is 0, meaning no annotations. |
| 2340 | |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2341 | In addition to printing the disassembly, some sanity checks are made: |
| 2342 | |
| 2343 | + All embedded opcode arguments "make sense". |
| 2344 | |
| 2345 | + Explicit and implicit pop operations have enough items on the stack. |
| 2346 | |
| 2347 | + When an opcode implicitly refers to a markobject, a markobject is |
| 2348 | actually on the stack. |
| 2349 | |
| 2350 | + A memo entry isn't referenced before it's defined. |
| 2351 | |
| 2352 | + The markobject isn't stored in the memo. |
| 2353 | |
| 2354 | + A memo entry isn't redefined. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2355 | """ |
| 2356 | |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2357 | # Most of the hair here is for sanity checks, but most of it is needed |
| 2358 | # anyway to detect when a protocol 0 POP takes a MARK off the stack |
| 2359 | # (which in turn is needed to indent MARK blocks correctly). |
| 2360 | |
| 2361 | stack = [] # crude emulation of unpickler stack |
Tim Peters | 62235e7 | 2003-02-05 19:55:53 +0000 | [diff] [blame] | 2362 | if memo is None: |
Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 2363 | memo = {} # crude emulation of unpickler memo |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2364 | maxproto = -1 # max protocol number seen |
| 2365 | markstack = [] # bytecode positions of MARK opcodes |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2366 | indentchunk = ' ' * indentlevel |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2367 | errormsg = None |
Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 2368 | annocol = annotate # column hint for annotations |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2369 | for opcode, arg, pos in genops(pickle): |
| 2370 | if pos is not None: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 2371 | print("%5d:" % pos, end=' ', file=out) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2372 | |
Tim Peters | d0f7c86 | 2003-01-28 15:27:57 +0000 | [diff] [blame] | 2373 | line = "%-4s %s%s" % (repr(opcode.code)[1:-1], |
| 2374 | indentchunk * len(markstack), |
| 2375 | opcode.name) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2376 | |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2377 | maxproto = max(maxproto, opcode.proto) |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2378 | before = opcode.stack_before # don't mutate |
| 2379 | after = opcode.stack_after # don't mutate |
Tim Peters | 43277d6 | 2003-01-30 15:02:12 +0000 | [diff] [blame] | 2380 | numtopop = len(before) |
| 2381 | |
| 2382 | # See whether a MARK should be popped. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2383 | markmsg = None |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2384 | if markobject in before or (opcode.name == "POP" and |
| 2385 | stack and |
| 2386 | stack[-1] is markobject): |
| 2387 | assert markobject not in after |
Tim Peters | 43277d6 | 2003-01-30 15:02:12 +0000 | [diff] [blame] | 2388 | if __debug__: |
| 2389 | if markobject in before: |
| 2390 | assert before[-1] is stackslice |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2391 | if markstack: |
| 2392 | markpos = markstack.pop() |
| 2393 | if markpos is None: |
| 2394 | markmsg = "(MARK at unknown opcode offset)" |
| 2395 | else: |
| 2396 | markmsg = "(MARK at %d)" % markpos |
| 2397 | # Pop everything at and after the topmost markobject. |
| 2398 | while stack[-1] is not markobject: |
| 2399 | stack.pop() |
| 2400 | stack.pop() |
Tim Peters | 43277d6 | 2003-01-30 15:02:12 +0000 | [diff] [blame] | 2401 | # Stop later code from popping too much. |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2402 | try: |
Tim Peters | 43277d6 | 2003-01-30 15:02:12 +0000 | [diff] [blame] | 2403 | numtopop = before.index(markobject) |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2404 | except ValueError: |
| 2405 | assert opcode.name == "POP" |
Tim Peters | 43277d6 | 2003-01-30 15:02:12 +0000 | [diff] [blame] | 2406 | numtopop = 0 |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2407 | else: |
| 2408 | errormsg = markmsg = "no MARK exists on stack" |
| 2409 | |
| 2410 | # Check for correct memo usage. |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2411 | if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT", "MEMOIZE"): |
| 2412 | if opcode.name == "MEMOIZE": |
| 2413 | memo_idx = len(memo) |
Serhiy Storchaka | dbc517c | 2015-10-13 21:20:14 +0300 | [diff] [blame] | 2414 | markmsg = "(as %d)" % memo_idx |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2415 | else: |
| 2416 | assert arg is not None |
| 2417 | memo_idx = arg |
| 2418 | if memo_idx in memo: |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2419 | errormsg = "memo key %r already defined" % arg |
| 2420 | elif not stack: |
| 2421 | errormsg = "stack is empty -- can't store into memo" |
| 2422 | elif stack[-1] is markobject: |
| 2423 | errormsg = "can't store markobject in the memo" |
| 2424 | else: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 2425 | memo[memo_idx] = stack[-1] |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2426 | elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): |
| 2427 | if arg in memo: |
| 2428 | assert len(after) == 1 |
| 2429 | after = [memo[arg]] # for better stack emulation |
| 2430 | else: |
| 2431 | errormsg = "memo key %r has never been stored into" % arg |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2432 | |
| 2433 | if arg is not None or markmsg: |
| 2434 | # make a mild effort to align arguments |
| 2435 | line += ' ' * (10 - len(opcode.name)) |
| 2436 | if arg is not None: |
| 2437 | line += ' ' + repr(arg) |
| 2438 | if markmsg: |
| 2439 | line += ' ' + markmsg |
Alexander Belopolsky | 929d384 | 2010-07-17 15:51:21 +0000 | [diff] [blame] | 2440 | if annotate: |
| 2441 | line += ' ' * (annocol - len(line)) |
| 2442 | # make a mild effort to align annotations |
| 2443 | annocol = len(line) |
| 2444 | if annocol > 50: |
| 2445 | annocol = annotate |
| 2446 | line += ' ' + opcode.doc.split('\n', 1)[0] |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 2447 | print(line, file=out) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2448 | |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2449 | if errormsg: |
| 2450 | # Note that we delayed complaining until the offending opcode |
| 2451 | # was printed. |
| 2452 | raise ValueError(errormsg) |
| 2453 | |
| 2454 | # Emulate the stack effects. |
Tim Peters | 43277d6 | 2003-01-30 15:02:12 +0000 | [diff] [blame] | 2455 | if len(stack) < numtopop: |
| 2456 | raise ValueError("tries to pop %d items from stack with " |
| 2457 | "only %d items" % (numtopop, len(stack))) |
| 2458 | if numtopop: |
| 2459 | del stack[-numtopop:] |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2460 | if markobject in after: |
Tim Peters | 43277d6 | 2003-01-30 15:02:12 +0000 | [diff] [blame] | 2461 | assert markobject not in before |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2462 | markstack.append(pos) |
| 2463 | |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2464 | stack.extend(after) |
| 2465 | |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 2466 | print("highest protocol among opcodes =", maxproto, file=out) |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2467 | if stack: |
| 2468 | raise ValueError("stack not empty after STOP: %r" % stack) |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2469 | |
Tim Peters | 90718a4 | 2005-02-15 16:22:34 +0000 | [diff] [blame] | 2470 | # For use in the doctest, simply as an example of a class to pickle. |
| 2471 | class _Example: |
| 2472 | def __init__(self, value): |
| 2473 | self.value = value |
| 2474 | |
Guido van Rossum | 03e3532 | 2003-01-28 15:37:13 +0000 | [diff] [blame] | 2475 | _dis_test = r""" |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2476 | >>> import pickle |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 2477 | >>> x = [1, 2, (3, 4), {b'abc': "def"}] |
| 2478 | >>> pkl0 = pickle.dumps(x, 0) |
| 2479 | >>> dis(pkl0) |
Tim Peters | d0f7c86 | 2003-01-28 15:27:57 +0000 | [diff] [blame] | 2480 | 0: ( MARK |
| 2481 | 1: l LIST (MARK at 0) |
| 2482 | 2: p PUT 0 |
Guido van Rossum | f410000 | 2007-01-15 00:21:46 +0000 | [diff] [blame] | 2483 | 5: L LONG 1 |
Mark Dickinson | 8dd0514 | 2009-01-20 20:43:58 +0000 | [diff] [blame] | 2484 | 9: a APPEND |
| 2485 | 10: L LONG 2 |
| 2486 | 14: a APPEND |
| 2487 | 15: ( MARK |
| 2488 | 16: L LONG 3 |
| 2489 | 20: L LONG 4 |
| 2490 | 24: t TUPLE (MARK at 15) |
| 2491 | 25: p PUT 1 |
| 2492 | 28: a APPEND |
| 2493 | 29: ( MARK |
| 2494 | 30: d DICT (MARK at 29) |
| 2495 | 31: p PUT 2 |
Alexandre Vassalotti | 3bfc65a | 2011-12-13 13:08:09 -0500 | [diff] [blame] | 2496 | 34: c GLOBAL '_codecs encode' |
| 2497 | 50: p PUT 3 |
| 2498 | 53: ( MARK |
| 2499 | 54: V UNICODE 'abc' |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 2500 | 59: p PUT 4 |
Alexandre Vassalotti | 3bfc65a | 2011-12-13 13:08:09 -0500 | [diff] [blame] | 2501 | 62: V UNICODE 'latin1' |
| 2502 | 70: p PUT 5 |
| 2503 | 73: t TUPLE (MARK at 53) |
| 2504 | 74: p PUT 6 |
| 2505 | 77: R REDUCE |
| 2506 | 78: p PUT 7 |
| 2507 | 81: V UNICODE 'def' |
| 2508 | 86: p PUT 8 |
| 2509 | 89: s SETITEM |
| 2510 | 90: a APPEND |
| 2511 | 91: . STOP |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2512 | highest protocol among opcodes = 0 |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2513 | |
| 2514 | Try again with a "binary" pickle. |
| 2515 | |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 2516 | >>> pkl1 = pickle.dumps(x, 1) |
| 2517 | >>> dis(pkl1) |
Tim Peters | d0f7c86 | 2003-01-28 15:27:57 +0000 | [diff] [blame] | 2518 | 0: ] EMPTY_LIST |
| 2519 | 1: q BINPUT 0 |
| 2520 | 3: ( MARK |
| 2521 | 4: K BININT1 1 |
| 2522 | 6: K BININT1 2 |
| 2523 | 8: ( MARK |
| 2524 | 9: K BININT1 3 |
| 2525 | 11: K BININT1 4 |
| 2526 | 13: t TUPLE (MARK at 8) |
| 2527 | 14: q BINPUT 1 |
| 2528 | 16: } EMPTY_DICT |
| 2529 | 17: q BINPUT 2 |
Alexandre Vassalotti | 3bfc65a | 2011-12-13 13:08:09 -0500 | [diff] [blame] | 2530 | 19: c GLOBAL '_codecs encode' |
| 2531 | 35: q BINPUT 3 |
| 2532 | 37: ( MARK |
| 2533 | 38: X BINUNICODE 'abc' |
| 2534 | 46: q BINPUT 4 |
| 2535 | 48: X BINUNICODE 'latin1' |
| 2536 | 59: q BINPUT 5 |
| 2537 | 61: t TUPLE (MARK at 37) |
| 2538 | 62: q BINPUT 6 |
| 2539 | 64: R REDUCE |
| 2540 | 65: q BINPUT 7 |
| 2541 | 67: X BINUNICODE 'def' |
| 2542 | 75: q BINPUT 8 |
| 2543 | 77: s SETITEM |
| 2544 | 78: e APPENDS (MARK at 3) |
| 2545 | 79: . STOP |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2546 | highest protocol among opcodes = 1 |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2547 | |
| 2548 | Exercise the INST/OBJ/BUILD family. |
| 2549 | |
Mark Dickinson | cddcf44 | 2009-01-24 21:46:33 +0000 | [diff] [blame] | 2550 | >>> import pickletools |
| 2551 | >>> dis(pickle.dumps(pickletools.dis, 0)) |
| 2552 | 0: c GLOBAL 'pickletools dis' |
| 2553 | 17: p PUT 0 |
| 2554 | 20: . STOP |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2555 | highest protocol among opcodes = 0 |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2556 | |
Tim Peters | 90718a4 | 2005-02-15 16:22:34 +0000 | [diff] [blame] | 2557 | >>> from pickletools import _Example |
| 2558 | >>> x = [_Example(42)] * 2 |
Guido van Rossum | f29d3d6 | 2003-01-27 22:47:53 +0000 | [diff] [blame] | 2559 | >>> dis(pickle.dumps(x, 0)) |
Tim Peters | d0f7c86 | 2003-01-28 15:27:57 +0000 | [diff] [blame] | 2560 | 0: ( MARK |
| 2561 | 1: l LIST (MARK at 0) |
| 2562 | 2: p PUT 0 |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 2563 | 5: c GLOBAL 'copy_reg _reconstructor' |
| 2564 | 30: p PUT 1 |
| 2565 | 33: ( MARK |
| 2566 | 34: c GLOBAL 'pickletools _Example' |
| 2567 | 56: p PUT 2 |
| 2568 | 59: c GLOBAL '__builtin__ object' |
| 2569 | 79: p PUT 3 |
| 2570 | 82: N NONE |
| 2571 | 83: t TUPLE (MARK at 33) |
| 2572 | 84: p PUT 4 |
| 2573 | 87: R REDUCE |
| 2574 | 88: p PUT 5 |
| 2575 | 91: ( MARK |
| 2576 | 92: d DICT (MARK at 91) |
| 2577 | 93: p PUT 6 |
| 2578 | 96: V UNICODE 'value' |
| 2579 | 103: p PUT 7 |
| 2580 | 106: L LONG 42 |
| 2581 | 111: s SETITEM |
| 2582 | 112: b BUILD |
Mark Dickinson | 8dd0514 | 2009-01-20 20:43:58 +0000 | [diff] [blame] | 2583 | 113: a APPEND |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 2584 | 114: g GET 5 |
| 2585 | 117: a APPEND |
| 2586 | 118: . STOP |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2587 | highest protocol among opcodes = 0 |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2588 | |
| 2589 | >>> dis(pickle.dumps(x, 1)) |
Tim Peters | d0f7c86 | 2003-01-28 15:27:57 +0000 | [diff] [blame] | 2590 | 0: ] EMPTY_LIST |
| 2591 | 1: q BINPUT 0 |
| 2592 | 3: ( MARK |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 2593 | 4: c GLOBAL 'copy_reg _reconstructor' |
| 2594 | 29: q BINPUT 1 |
| 2595 | 31: ( MARK |
| 2596 | 32: c GLOBAL 'pickletools _Example' |
| 2597 | 54: q BINPUT 2 |
| 2598 | 56: c GLOBAL '__builtin__ object' |
| 2599 | 76: q BINPUT 3 |
| 2600 | 78: N NONE |
| 2601 | 79: t TUPLE (MARK at 31) |
| 2602 | 80: q BINPUT 4 |
| 2603 | 82: R REDUCE |
| 2604 | 83: q BINPUT 5 |
| 2605 | 85: } EMPTY_DICT |
| 2606 | 86: q BINPUT 6 |
| 2607 | 88: X BINUNICODE 'value' |
| 2608 | 98: q BINPUT 7 |
| 2609 | 100: K BININT1 42 |
| 2610 | 102: s SETITEM |
| 2611 | 103: b BUILD |
| 2612 | 104: h BINGET 5 |
| 2613 | 106: e APPENDS (MARK at 3) |
| 2614 | 107: . STOP |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2615 | highest protocol among opcodes = 1 |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2616 | |
| 2617 | Try "the canonical" recursive-object test. |
| 2618 | |
| 2619 | >>> L = [] |
| 2620 | >>> T = L, |
| 2621 | >>> L.append(T) |
| 2622 | >>> L[0] is T |
| 2623 | True |
| 2624 | >>> T[0] is L |
| 2625 | True |
| 2626 | >>> L[0][0] is L |
| 2627 | True |
| 2628 | >>> T[0][0] is T |
| 2629 | True |
Guido van Rossum | f29d3d6 | 2003-01-27 22:47:53 +0000 | [diff] [blame] | 2630 | >>> dis(pickle.dumps(L, 0)) |
Tim Peters | d0f7c86 | 2003-01-28 15:27:57 +0000 | [diff] [blame] | 2631 | 0: ( MARK |
| 2632 | 1: l LIST (MARK at 0) |
| 2633 | 2: p PUT 0 |
| 2634 | 5: ( MARK |
| 2635 | 6: g GET 0 |
| 2636 | 9: t TUPLE (MARK at 5) |
| 2637 | 10: p PUT 1 |
| 2638 | 13: a APPEND |
| 2639 | 14: . STOP |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2640 | highest protocol among opcodes = 0 |
| 2641 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2642 | >>> dis(pickle.dumps(L, 1)) |
Tim Peters | d0f7c86 | 2003-01-28 15:27:57 +0000 | [diff] [blame] | 2643 | 0: ] EMPTY_LIST |
| 2644 | 1: q BINPUT 0 |
| 2645 | 3: ( MARK |
| 2646 | 4: h BINGET 0 |
| 2647 | 6: t TUPLE (MARK at 3) |
| 2648 | 7: q BINPUT 1 |
| 2649 | 9: a APPEND |
| 2650 | 10: . STOP |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2651 | highest protocol among opcodes = 1 |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2652 | |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2653 | Note that, in the protocol 0 pickle of the recursive tuple, the disassembler |
| 2654 | has to emulate the stack in order to realize that the POP opcode at 16 gets |
| 2655 | rid of the MARK at 0. |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2656 | |
Guido van Rossum | f29d3d6 | 2003-01-27 22:47:53 +0000 | [diff] [blame] | 2657 | >>> dis(pickle.dumps(T, 0)) |
Tim Peters | d0f7c86 | 2003-01-28 15:27:57 +0000 | [diff] [blame] | 2658 | 0: ( MARK |
| 2659 | 1: ( MARK |
| 2660 | 2: l LIST (MARK at 1) |
| 2661 | 3: p PUT 0 |
| 2662 | 6: ( MARK |
| 2663 | 7: g GET 0 |
| 2664 | 10: t TUPLE (MARK at 6) |
| 2665 | 11: p PUT 1 |
| 2666 | 14: a APPEND |
| 2667 | 15: 0 POP |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2668 | 16: 0 POP (MARK at 0) |
| 2669 | 17: g GET 1 |
| 2670 | 20: . STOP |
| 2671 | highest protocol among opcodes = 0 |
| 2672 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2673 | >>> dis(pickle.dumps(T, 1)) |
Tim Peters | d0f7c86 | 2003-01-28 15:27:57 +0000 | [diff] [blame] | 2674 | 0: ( MARK |
| 2675 | 1: ] EMPTY_LIST |
| 2676 | 2: q BINPUT 0 |
| 2677 | 4: ( MARK |
| 2678 | 5: h BINGET 0 |
| 2679 | 7: t TUPLE (MARK at 4) |
| 2680 | 8: q BINPUT 1 |
| 2681 | 10: a APPEND |
| 2682 | 11: 1 POP_MARK (MARK at 0) |
| 2683 | 12: h BINGET 1 |
| 2684 | 14: . STOP |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2685 | highest protocol among opcodes = 1 |
Tim Peters | d0f7c86 | 2003-01-28 15:27:57 +0000 | [diff] [blame] | 2686 | |
| 2687 | Try protocol 2. |
| 2688 | |
| 2689 | >>> dis(pickle.dumps(L, 2)) |
| 2690 | 0: \x80 PROTO 2 |
| 2691 | 2: ] EMPTY_LIST |
| 2692 | 3: q BINPUT 0 |
| 2693 | 5: h BINGET 0 |
| 2694 | 7: \x85 TUPLE1 |
| 2695 | 8: q BINPUT 1 |
| 2696 | 10: a APPEND |
| 2697 | 11: . STOP |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2698 | highest protocol among opcodes = 2 |
Tim Peters | d0f7c86 | 2003-01-28 15:27:57 +0000 | [diff] [blame] | 2699 | |
| 2700 | >>> dis(pickle.dumps(T, 2)) |
| 2701 | 0: \x80 PROTO 2 |
| 2702 | 2: ] EMPTY_LIST |
| 2703 | 3: q BINPUT 0 |
| 2704 | 5: h BINGET 0 |
| 2705 | 7: \x85 TUPLE1 |
| 2706 | 8: q BINPUT 1 |
| 2707 | 10: a APPEND |
| 2708 | 11: 0 POP |
| 2709 | 12: h BINGET 1 |
| 2710 | 14: . STOP |
Tim Peters | c1c2b3e | 2003-01-29 20:12:21 +0000 | [diff] [blame] | 2711 | highest protocol among opcodes = 2 |
Alexander Belopolsky | 929d384 | 2010-07-17 15:51:21 +0000 | [diff] [blame] | 2712 | |
| 2713 | Try protocol 3 with annotations: |
| 2714 | |
| 2715 | >>> dis(pickle.dumps(T, 3), annotate=1) |
| 2716 | 0: \x80 PROTO 3 Protocol version indicator. |
| 2717 | 2: ] EMPTY_LIST Push an empty list. |
| 2718 | 3: q BINPUT 0 Store the stack top into the memo. The stack is not popped. |
| 2719 | 5: h BINGET 0 Read an object from the memo and push it on the stack. |
| 2720 | 7: \x85 TUPLE1 Build a one-tuple out of the topmost item on the stack. |
| 2721 | 8: q BINPUT 1 Store the stack top into the memo. The stack is not popped. |
| 2722 | 10: a APPEND Append an object to a list. |
| 2723 | 11: 0 POP Discard the top stack item, shrinking the stack by one item. |
| 2724 | 12: h BINGET 1 Read an object from the memo and push it on the stack. |
| 2725 | 14: . STOP Stop the unpickling machine. |
| 2726 | highest protocol among opcodes = 2 |
| 2727 | |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2728 | """ |
| 2729 | |
Tim Peters | 62235e7 | 2003-02-05 19:55:53 +0000 | [diff] [blame] | 2730 | _memo_test = r""" |
| 2731 | >>> import pickle |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 2732 | >>> import io |
| 2733 | >>> f = io.BytesIO() |
Tim Peters | 62235e7 | 2003-02-05 19:55:53 +0000 | [diff] [blame] | 2734 | >>> p = pickle.Pickler(f, 2) |
| 2735 | >>> x = [1, 2, 3] |
| 2736 | >>> p.dump(x) |
| 2737 | >>> p.dump(x) |
| 2738 | >>> f.seek(0) |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 2739 | 0 |
Tim Peters | 62235e7 | 2003-02-05 19:55:53 +0000 | [diff] [blame] | 2740 | >>> memo = {} |
| 2741 | >>> dis(f, memo=memo) |
| 2742 | 0: \x80 PROTO 2 |
| 2743 | 2: ] EMPTY_LIST |
| 2744 | 3: q BINPUT 0 |
| 2745 | 5: ( MARK |
| 2746 | 6: K BININT1 1 |
| 2747 | 8: K BININT1 2 |
| 2748 | 10: K BININT1 3 |
| 2749 | 12: e APPENDS (MARK at 5) |
| 2750 | 13: . STOP |
| 2751 | highest protocol among opcodes = 2 |
| 2752 | >>> dis(f, memo=memo) |
| 2753 | 14: \x80 PROTO 2 |
| 2754 | 16: h BINGET 0 |
| 2755 | 18: . STOP |
| 2756 | highest protocol among opcodes = 2 |
| 2757 | """ |
| 2758 | |
Guido van Rossum | 5702835 | 2003-01-28 15:09:10 +0000 | [diff] [blame] | 2759 | __test__ = {'disassembler_test': _dis_test, |
Tim Peters | 62235e7 | 2003-02-05 19:55:53 +0000 | [diff] [blame] | 2760 | 'disassembler_memo_test': _memo_test, |
Tim Peters | 8ecfc8e | 2003-01-27 18:51:48 +0000 | [diff] [blame] | 2761 | } |
| 2762 | |
| 2763 | def _test(): |
| 2764 | import doctest |
| 2765 | return doctest.testmod() |
| 2766 | |
| 2767 | if __name__ == "__main__": |
Benjamin Peterson | 669ff66 | 2015-10-28 23:15:13 -0700 | [diff] [blame] | 2768 | import argparse |
Alexander Belopolsky | 60c762b | 2010-07-03 20:35:53 +0000 | [diff] [blame] | 2769 | parser = argparse.ArgumentParser( |
| 2770 | description='disassemble one or more pickle files') |
| 2771 | parser.add_argument( |
| 2772 | 'pickle_file', type=argparse.FileType('br'), |
| 2773 | nargs='*', help='the pickle file') |
| 2774 | parser.add_argument( |
| 2775 | '-o', '--output', default=sys.stdout, type=argparse.FileType('w'), |
| 2776 | help='the file where the output should be written') |
| 2777 | parser.add_argument( |
| 2778 | '-m', '--memo', action='store_true', |
| 2779 | help='preserve memo between disassemblies') |
| 2780 | parser.add_argument( |
| 2781 | '-l', '--indentlevel', default=4, type=int, |
| 2782 | help='the number of blanks by which to indent a new MARK level') |
| 2783 | parser.add_argument( |
Alexander Belopolsky | 929d384 | 2010-07-17 15:51:21 +0000 | [diff] [blame] | 2784 | '-a', '--annotate', action='store_true', |
| 2785 | help='annotate each line with a short opcode description') |
| 2786 | parser.add_argument( |
Alexander Belopolsky | 60c762b | 2010-07-03 20:35:53 +0000 | [diff] [blame] | 2787 | '-p', '--preamble', default="==> {name} <==", |
| 2788 | help='if more than one pickle file is specified, print this before' |
| 2789 | ' each disassembly') |
| 2790 | parser.add_argument( |
| 2791 | '-t', '--test', action='store_true', |
| 2792 | help='run self-test suite') |
| 2793 | parser.add_argument( |
| 2794 | '-v', action='store_true', |
| 2795 | help='run verbosely; only affects self-test run') |
| 2796 | args = parser.parse_args() |
| 2797 | if args.test: |
| 2798 | _test() |
| 2799 | else: |
Alexander Belopolsky | 929d384 | 2010-07-17 15:51:21 +0000 | [diff] [blame] | 2800 | annotate = 30 if args.annotate else 0 |
Alexander Belopolsky | 60c762b | 2010-07-03 20:35:53 +0000 | [diff] [blame] | 2801 | if not args.pickle_file: |
| 2802 | parser.print_help() |
| 2803 | elif len(args.pickle_file) == 1: |
Alexander Belopolsky | 929d384 | 2010-07-17 15:51:21 +0000 | [diff] [blame] | 2804 | dis(args.pickle_file[0], args.output, None, |
| 2805 | args.indentlevel, annotate) |
Alexander Belopolsky | 60c762b | 2010-07-03 20:35:53 +0000 | [diff] [blame] | 2806 | else: |
| 2807 | memo = {} if args.memo else None |
| 2808 | for f in args.pickle_file: |
| 2809 | preamble = args.preamble.format(name=f.name) |
| 2810 | args.output.write(preamble + '\n') |
Alexander Belopolsky | 929d384 | 2010-07-17 15:51:21 +0000 | [diff] [blame] | 2811 | dis(f, args.output, memo, args.indentlevel, annotate) |