Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pickletools_3.py 80KB

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