pickletools.py 74 KB

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