pickletools.py 90 KB

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