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