libpython.py 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760
  1. #!/usr/bin/python
  2. # NOTE: this file is taken from the Python source distribution
  3. # It can be found under Tools/gdb/libpython.py. It is shipped with Cython
  4. # because it's not installed as a python module, and because changes are only
  5. # merged into new python versions (v3.2+).
  6. '''
  7. From gdb 7 onwards, gdb's build can be configured --with-python, allowing gdb
  8. to be extended with Python code e.g. for library-specific data visualizations,
  9. such as for the C++ STL types. Documentation on this API can be seen at:
  10. http://sourceware.org/gdb/current/onlinedocs/gdb/Python-API.html
  11. This python module deals with the case when the process being debugged (the
  12. "inferior process" in gdb parlance) is itself python, or more specifically,
  13. linked against libpython. In this situation, almost every item of data is a
  14. (PyObject*), and having the debugger merely print their addresses is not very
  15. enlightening.
  16. This module embeds knowledge about the implementation details of libpython so
  17. that we can emit useful visualizations e.g. a string, a list, a dict, a frame
  18. giving file/line information and the state of local variables
  19. In particular, given a gdb.Value corresponding to a PyObject* in the inferior
  20. process, we can generate a "proxy value" within the gdb process. For example,
  21. given a PyObject* in the inferior process that is in fact a PyListObject*
  22. holding three PyObject* that turn out to be PyBytesObject* instances, we can
  23. generate a proxy value within the gdb process that is a list of bytes
  24. instances:
  25. [b"foo", b"bar", b"baz"]
  26. Doing so can be expensive for complicated graphs of objects, and could take
  27. some time, so we also have a "write_repr" method that writes a representation
  28. of the data to a file-like object. This allows us to stop the traversal by
  29. having the file-like object raise an exception if it gets too much data.
  30. With both "proxyval" and "write_repr" we keep track of the set of all addresses
  31. visited so far in the traversal, to avoid infinite recursion due to cycles in
  32. the graph of object references.
  33. We try to defer gdb.lookup_type() invocations for python types until as late as
  34. possible: for a dynamically linked python binary, when the process starts in
  35. the debugger, the libpython.so hasn't been dynamically loaded yet, so none of
  36. the type names are known to the debugger
  37. The module also extends gdb with some python-specific commands.
  38. '''
  39. # NOTE: some gdbs are linked with Python 3, so this file should be dual-syntax
  40. # compatible (2.6+ and 3.0+). See #19308.
  41. from __future__ import print_function
  42. import gdb
  43. import os
  44. import locale
  45. import sys
  46. if sys.version_info[0] >= 3:
  47. unichr = chr
  48. xrange = range
  49. long = int
  50. # Look up the gdb.Type for some standard types:
  51. # Those need to be refreshed as types (pointer sizes) may change when
  52. # gdb loads different executables
  53. def _type_char_ptr():
  54. return gdb.lookup_type('char').pointer() # char*
  55. def _type_unsigned_char_ptr():
  56. return gdb.lookup_type('unsigned char').pointer() # unsigned char*
  57. def _type_unsigned_short_ptr():
  58. return gdb.lookup_type('unsigned short').pointer()
  59. def _type_unsigned_int_ptr():
  60. return gdb.lookup_type('unsigned int').pointer()
  61. def _sizeof_void_p():
  62. return gdb.lookup_type('void').pointer().sizeof
  63. # value computed later, see PyUnicodeObjectPtr.proxy()
  64. _is_pep393 = None
  65. Py_TPFLAGS_HEAPTYPE = (1 << 9)
  66. Py_TPFLAGS_LONG_SUBCLASS = (1 << 24)
  67. Py_TPFLAGS_LIST_SUBCLASS = (1 << 25)
  68. Py_TPFLAGS_TUPLE_SUBCLASS = (1 << 26)
  69. Py_TPFLAGS_BYTES_SUBCLASS = (1 << 27)
  70. Py_TPFLAGS_UNICODE_SUBCLASS = (1 << 28)
  71. Py_TPFLAGS_DICT_SUBCLASS = (1 << 29)
  72. Py_TPFLAGS_BASE_EXC_SUBCLASS = (1 << 30)
  73. Py_TPFLAGS_TYPE_SUBCLASS = (1 << 31)
  74. MAX_OUTPUT_LEN=1024
  75. hexdigits = "0123456789abcdef"
  76. ENCODING = locale.getpreferredencoding()
  77. EVALFRAME = '_PyEval_EvalFrameDefault'
  78. class NullPyObjectPtr(RuntimeError):
  79. pass
  80. def safety_limit(val):
  81. # Given an integer value from the process being debugged, limit it to some
  82. # safety threshold so that arbitrary breakage within said process doesn't
  83. # break the gdb process too much (e.g. sizes of iterations, sizes of lists)
  84. return min(val, 1000)
  85. def safe_range(val):
  86. # As per range, but don't trust the value too much: cap it to a safety
  87. # threshold in case the data was corrupted
  88. return xrange(safety_limit(int(val)))
  89. if sys.version_info[0] >= 3:
  90. def write_unicode(file, text):
  91. file.write(text)
  92. else:
  93. def write_unicode(file, text):
  94. # Write a byte or unicode string to file. Unicode strings are encoded to
  95. # ENCODING encoding with 'backslashreplace' error handler to avoid
  96. # UnicodeEncodeError.
  97. if isinstance(text, unicode):
  98. text = text.encode(ENCODING, 'backslashreplace')
  99. file.write(text)
  100. try:
  101. os_fsencode = os.fsencode
  102. except AttributeError:
  103. def os_fsencode(filename):
  104. if not isinstance(filename, unicode):
  105. return filename
  106. encoding = sys.getfilesystemencoding()
  107. if encoding == 'mbcs':
  108. # mbcs doesn't support surrogateescape
  109. return filename.encode(encoding)
  110. encoded = []
  111. for char in filename:
  112. # surrogateescape error handler
  113. if 0xDC80 <= ord(char) <= 0xDCFF:
  114. byte = chr(ord(char) - 0xDC00)
  115. else:
  116. byte = char.encode(encoding)
  117. encoded.append(byte)
  118. return ''.join(encoded)
  119. class StringTruncated(RuntimeError):
  120. pass
  121. class TruncatedStringIO(object):
  122. '''Similar to io.StringIO, but can truncate the output by raising a
  123. StringTruncated exception'''
  124. def __init__(self, maxlen=None):
  125. self._val = ''
  126. self.maxlen = maxlen
  127. def write(self, data):
  128. if self.maxlen:
  129. if len(data) + len(self._val) > self.maxlen:
  130. # Truncation:
  131. self._val += data[0:self.maxlen - len(self._val)]
  132. raise StringTruncated()
  133. self._val += data
  134. def getvalue(self):
  135. return self._val
  136. class PyObjectPtr(object):
  137. """
  138. Class wrapping a gdb.Value that's either a (PyObject*) within the
  139. inferior process, or some subclass pointer e.g. (PyBytesObject*)
  140. There will be a subclass for every refined PyObject type that we care
  141. about.
  142. Note that at every stage the underlying pointer could be NULL, point
  143. to corrupt data, etc; this is the debugger, after all.
  144. """
  145. _typename = 'PyObject'
  146. def __init__(self, gdbval, cast_to=None):
  147. if cast_to:
  148. self._gdbval = gdbval.cast(cast_to)
  149. else:
  150. self._gdbval = gdbval
  151. def field(self, name):
  152. '''
  153. Get the gdb.Value for the given field within the PyObject, coping with
  154. some python 2 versus python 3 differences.
  155. Various libpython types are defined using the "PyObject_HEAD" and
  156. "PyObject_VAR_HEAD" macros.
  157. In Python 2, this these are defined so that "ob_type" and (for a var
  158. object) "ob_size" are fields of the type in question.
  159. In Python 3, this is defined as an embedded PyVarObject type thus:
  160. PyVarObject ob_base;
  161. so that the "ob_size" field is located insize the "ob_base" field, and
  162. the "ob_type" is most easily accessed by casting back to a (PyObject*).
  163. '''
  164. if self.is_null():
  165. raise NullPyObjectPtr(self)
  166. if name == 'ob_type':
  167. pyo_ptr = self._gdbval.cast(PyObjectPtr.get_gdb_type())
  168. return pyo_ptr.dereference()[name]
  169. if name == 'ob_size':
  170. pyo_ptr = self._gdbval.cast(PyVarObjectPtr.get_gdb_type())
  171. return pyo_ptr.dereference()[name]
  172. # General case: look it up inside the object:
  173. return self._gdbval.dereference()[name]
  174. def pyop_field(self, name):
  175. '''
  176. Get a PyObjectPtr for the given PyObject* field within this PyObject,
  177. coping with some python 2 versus python 3 differences.
  178. '''
  179. return PyObjectPtr.from_pyobject_ptr(self.field(name))
  180. def write_field_repr(self, name, out, visited):
  181. '''
  182. Extract the PyObject* field named "name", and write its representation
  183. to file-like object "out"
  184. '''
  185. field_obj = self.pyop_field(name)
  186. field_obj.write_repr(out, visited)
  187. def get_truncated_repr(self, maxlen):
  188. '''
  189. Get a repr-like string for the data, but truncate it at "maxlen" bytes
  190. (ending the object graph traversal as soon as you do)
  191. '''
  192. out = TruncatedStringIO(maxlen)
  193. try:
  194. self.write_repr(out, set())
  195. except StringTruncated:
  196. # Truncation occurred:
  197. return out.getvalue() + '...(truncated)'
  198. # No truncation occurred:
  199. return out.getvalue()
  200. def type(self):
  201. return PyTypeObjectPtr(self.field('ob_type'))
  202. def is_null(self):
  203. return 0 == long(self._gdbval)
  204. def is_optimized_out(self):
  205. '''
  206. Is the value of the underlying PyObject* visible to the debugger?
  207. This can vary with the precise version of the compiler used to build
  208. Python, and the precise version of gdb.
  209. See e.g. https://bugzilla.redhat.com/show_bug.cgi?id=556975 with
  210. PyEval_EvalFrameEx's "f"
  211. '''
  212. return self._gdbval.is_optimized_out
  213. def safe_tp_name(self):
  214. try:
  215. return self.type().field('tp_name').string()
  216. except NullPyObjectPtr:
  217. # NULL tp_name?
  218. return 'unknown'
  219. except RuntimeError:
  220. # Can't even read the object at all?
  221. return 'unknown'
  222. def proxyval(self, visited):
  223. '''
  224. Scrape a value from the inferior process, and try to represent it
  225. within the gdb process, whilst (hopefully) avoiding crashes when
  226. the remote data is corrupt.
  227. Derived classes will override this.
  228. For example, a PyIntObject* with ob_ival 42 in the inferior process
  229. should result in an int(42) in this process.
  230. visited: a set of all gdb.Value pyobject pointers already visited
  231. whilst generating this value (to guard against infinite recursion when
  232. visiting object graphs with loops). Analogous to Py_ReprEnter and
  233. Py_ReprLeave
  234. '''
  235. class FakeRepr(object):
  236. """
  237. Class representing a non-descript PyObject* value in the inferior
  238. process for when we don't have a custom scraper, intended to have
  239. a sane repr().
  240. """
  241. def __init__(self, tp_name, address):
  242. self.tp_name = tp_name
  243. self.address = address
  244. def __repr__(self):
  245. # For the NULL pointer, we have no way of knowing a type, so
  246. # special-case it as per
  247. # http://bugs.python.org/issue8032#msg100882
  248. if self.address == 0:
  249. return '0x0'
  250. return '<%s at remote 0x%x>' % (self.tp_name, self.address)
  251. return FakeRepr(self.safe_tp_name(),
  252. long(self._gdbval))
  253. def write_repr(self, out, visited):
  254. '''
  255. Write a string representation of the value scraped from the inferior
  256. process to "out", a file-like object.
  257. '''
  258. # Default implementation: generate a proxy value and write its repr
  259. # However, this could involve a lot of work for complicated objects,
  260. # so for derived classes we specialize this
  261. return out.write(repr(self.proxyval(visited)))
  262. @classmethod
  263. def subclass_from_type(cls, t):
  264. '''
  265. Given a PyTypeObjectPtr instance wrapping a gdb.Value that's a
  266. (PyTypeObject*), determine the corresponding subclass of PyObjectPtr
  267. to use
  268. Ideally, we would look up the symbols for the global types, but that
  269. isn't working yet:
  270. (gdb) python print gdb.lookup_symbol('PyList_Type')[0].value
  271. Traceback (most recent call last):
  272. File "<string>", line 1, in <module>
  273. NotImplementedError: Symbol type not yet supported in Python scripts.
  274. Error while executing Python code.
  275. For now, we use tp_flags, after doing some string comparisons on the
  276. tp_name for some special-cases that don't seem to be visible through
  277. flags
  278. '''
  279. try:
  280. tp_name = t.field('tp_name').string()
  281. tp_flags = int(t.field('tp_flags'))
  282. except RuntimeError:
  283. # Handle any kind of error e.g. NULL ptrs by simply using the base
  284. # class
  285. return cls
  286. #print('tp_flags = 0x%08x' % tp_flags)
  287. #print('tp_name = %r' % tp_name)
  288. name_map = {'bool': PyBoolObjectPtr,
  289. 'classobj': PyClassObjectPtr,
  290. 'NoneType': PyNoneStructPtr,
  291. 'frame': PyFrameObjectPtr,
  292. 'set' : PySetObjectPtr,
  293. 'frozenset' : PySetObjectPtr,
  294. 'builtin_function_or_method' : PyCFunctionObjectPtr,
  295. 'method-wrapper': wrapperobject,
  296. }
  297. if tp_name in name_map:
  298. return name_map[tp_name]
  299. if tp_flags & Py_TPFLAGS_HEAPTYPE:
  300. return HeapTypeObjectPtr
  301. if tp_flags & Py_TPFLAGS_LONG_SUBCLASS:
  302. return PyLongObjectPtr
  303. if tp_flags & Py_TPFLAGS_LIST_SUBCLASS:
  304. return PyListObjectPtr
  305. if tp_flags & Py_TPFLAGS_TUPLE_SUBCLASS:
  306. return PyTupleObjectPtr
  307. if tp_flags & Py_TPFLAGS_BYTES_SUBCLASS:
  308. return PyBytesObjectPtr
  309. if tp_flags & Py_TPFLAGS_UNICODE_SUBCLASS:
  310. return PyUnicodeObjectPtr
  311. if tp_flags & Py_TPFLAGS_DICT_SUBCLASS:
  312. return PyDictObjectPtr
  313. if tp_flags & Py_TPFLAGS_BASE_EXC_SUBCLASS:
  314. return PyBaseExceptionObjectPtr
  315. #if tp_flags & Py_TPFLAGS_TYPE_SUBCLASS:
  316. # return PyTypeObjectPtr
  317. # Use the base class:
  318. return cls
  319. @classmethod
  320. def from_pyobject_ptr(cls, gdbval):
  321. '''
  322. Try to locate the appropriate derived class dynamically, and cast
  323. the pointer accordingly.
  324. '''
  325. try:
  326. p = PyObjectPtr(gdbval)
  327. cls = cls.subclass_from_type(p.type())
  328. return cls(gdbval, cast_to=cls.get_gdb_type())
  329. except RuntimeError:
  330. # Handle any kind of error e.g. NULL ptrs by simply using the base
  331. # class
  332. pass
  333. return cls(gdbval)
  334. @classmethod
  335. def get_gdb_type(cls):
  336. return gdb.lookup_type(cls._typename).pointer()
  337. def as_address(self):
  338. return long(self._gdbval)
  339. class PyVarObjectPtr(PyObjectPtr):
  340. _typename = 'PyVarObject'
  341. class ProxyAlreadyVisited(object):
  342. '''
  343. Placeholder proxy to use when protecting against infinite recursion due to
  344. loops in the object graph.
  345. Analogous to the values emitted by the users of Py_ReprEnter and Py_ReprLeave
  346. '''
  347. def __init__(self, rep):
  348. self._rep = rep
  349. def __repr__(self):
  350. return self._rep
  351. def _write_instance_repr(out, visited, name, pyop_attrdict, address):
  352. '''Shared code for use by all classes:
  353. write a representation to file-like object "out"'''
  354. out.write('<')
  355. out.write(name)
  356. # Write dictionary of instance attributes:
  357. if isinstance(pyop_attrdict, PyDictObjectPtr):
  358. out.write('(')
  359. first = True
  360. for pyop_arg, pyop_val in pyop_attrdict.iteritems():
  361. if not first:
  362. out.write(', ')
  363. first = False
  364. out.write(pyop_arg.proxyval(visited))
  365. out.write('=')
  366. pyop_val.write_repr(out, visited)
  367. out.write(')')
  368. out.write(' at remote 0x%x>' % address)
  369. class InstanceProxy(object):
  370. def __init__(self, cl_name, attrdict, address):
  371. self.cl_name = cl_name
  372. self.attrdict = attrdict
  373. self.address = address
  374. def __repr__(self):
  375. if isinstance(self.attrdict, dict):
  376. kwargs = ', '.join(["%s=%r" % (arg, val)
  377. for arg, val in self.attrdict.iteritems()])
  378. return '<%s(%s) at remote 0x%x>' % (self.cl_name,
  379. kwargs, self.address)
  380. else:
  381. return '<%s at remote 0x%x>' % (self.cl_name,
  382. self.address)
  383. def _PyObject_VAR_SIZE(typeobj, nitems):
  384. if _PyObject_VAR_SIZE._type_size_t is None:
  385. _PyObject_VAR_SIZE._type_size_t = gdb.lookup_type('size_t')
  386. return ( ( typeobj.field('tp_basicsize') +
  387. nitems * typeobj.field('tp_itemsize') +
  388. (_sizeof_void_p() - 1)
  389. ) & ~(_sizeof_void_p() - 1)
  390. ).cast(_PyObject_VAR_SIZE._type_size_t)
  391. _PyObject_VAR_SIZE._type_size_t = None
  392. class HeapTypeObjectPtr(PyObjectPtr):
  393. _typename = 'PyObject'
  394. def get_attr_dict(self):
  395. '''
  396. Get the PyDictObject ptr representing the attribute dictionary
  397. (or None if there's a problem)
  398. '''
  399. try:
  400. typeobj = self.type()
  401. dictoffset = int_from_int(typeobj.field('tp_dictoffset'))
  402. if dictoffset != 0:
  403. if dictoffset < 0:
  404. type_PyVarObject_ptr = gdb.lookup_type('PyVarObject').pointer()
  405. tsize = int_from_int(self._gdbval.cast(type_PyVarObject_ptr)['ob_size'])
  406. if tsize < 0:
  407. tsize = -tsize
  408. size = _PyObject_VAR_SIZE(typeobj, tsize)
  409. dictoffset += size
  410. assert dictoffset > 0
  411. assert dictoffset % _sizeof_void_p() == 0
  412. dictptr = self._gdbval.cast(_type_char_ptr()) + dictoffset
  413. PyObjectPtrPtr = PyObjectPtr.get_gdb_type().pointer()
  414. dictptr = dictptr.cast(PyObjectPtrPtr)
  415. return PyObjectPtr.from_pyobject_ptr(dictptr.dereference())
  416. except RuntimeError:
  417. # Corrupt data somewhere; fail safe
  418. pass
  419. # Not found, or some kind of error:
  420. return None
  421. def proxyval(self, visited):
  422. '''
  423. Support for classes.
  424. Currently we just locate the dictionary using a transliteration to
  425. python of _PyObject_GetDictPtr, ignoring descriptors
  426. '''
  427. # Guard against infinite loops:
  428. if self.as_address() in visited:
  429. return ProxyAlreadyVisited('<...>')
  430. visited.add(self.as_address())
  431. pyop_attr_dict = self.get_attr_dict()
  432. if pyop_attr_dict:
  433. attr_dict = pyop_attr_dict.proxyval(visited)
  434. else:
  435. attr_dict = {}
  436. tp_name = self.safe_tp_name()
  437. # Class:
  438. return InstanceProxy(tp_name, attr_dict, long(self._gdbval))
  439. def write_repr(self, out, visited):
  440. # Guard against infinite loops:
  441. if self.as_address() in visited:
  442. out.write('<...>')
  443. return
  444. visited.add(self.as_address())
  445. pyop_attrdict = self.get_attr_dict()
  446. _write_instance_repr(out, visited,
  447. self.safe_tp_name(), pyop_attrdict, self.as_address())
  448. class ProxyException(Exception):
  449. def __init__(self, tp_name, args):
  450. self.tp_name = tp_name
  451. self.args = args
  452. def __repr__(self):
  453. return '%s%r' % (self.tp_name, self.args)
  454. class PyBaseExceptionObjectPtr(PyObjectPtr):
  455. """
  456. Class wrapping a gdb.Value that's a PyBaseExceptionObject* i.e. an exception
  457. within the process being debugged.
  458. """
  459. _typename = 'PyBaseExceptionObject'
  460. def proxyval(self, visited):
  461. # Guard against infinite loops:
  462. if self.as_address() in visited:
  463. return ProxyAlreadyVisited('(...)')
  464. visited.add(self.as_address())
  465. arg_proxy = self.pyop_field('args').proxyval(visited)
  466. return ProxyException(self.safe_tp_name(),
  467. arg_proxy)
  468. def write_repr(self, out, visited):
  469. # Guard against infinite loops:
  470. if self.as_address() in visited:
  471. out.write('(...)')
  472. return
  473. visited.add(self.as_address())
  474. out.write(self.safe_tp_name())
  475. self.write_field_repr('args', out, visited)
  476. class PyClassObjectPtr(PyObjectPtr):
  477. """
  478. Class wrapping a gdb.Value that's a PyClassObject* i.e. a <classobj>
  479. instance within the process being debugged.
  480. """
  481. _typename = 'PyClassObject'
  482. class BuiltInFunctionProxy(object):
  483. def __init__(self, ml_name):
  484. self.ml_name = ml_name
  485. def __repr__(self):
  486. return "<built-in function %s>" % self.ml_name
  487. class BuiltInMethodProxy(object):
  488. def __init__(self, ml_name, pyop_m_self):
  489. self.ml_name = ml_name
  490. self.pyop_m_self = pyop_m_self
  491. def __repr__(self):
  492. return ('<built-in method %s of %s object at remote 0x%x>'
  493. % (self.ml_name,
  494. self.pyop_m_self.safe_tp_name(),
  495. self.pyop_m_self.as_address())
  496. )
  497. class PyCFunctionObjectPtr(PyObjectPtr):
  498. """
  499. Class wrapping a gdb.Value that's a PyCFunctionObject*
  500. (see Include/methodobject.h and Objects/methodobject.c)
  501. """
  502. _typename = 'PyCFunctionObject'
  503. def proxyval(self, visited):
  504. m_ml = self.field('m_ml') # m_ml is a (PyMethodDef*)
  505. ml_name = m_ml['ml_name'].string()
  506. pyop_m_self = self.pyop_field('m_self')
  507. if pyop_m_self.is_null():
  508. return BuiltInFunctionProxy(ml_name)
  509. else:
  510. return BuiltInMethodProxy(ml_name, pyop_m_self)
  511. class PyCodeObjectPtr(PyObjectPtr):
  512. """
  513. Class wrapping a gdb.Value that's a PyCodeObject* i.e. a <code> instance
  514. within the process being debugged.
  515. """
  516. _typename = 'PyCodeObject'
  517. def addr2line(self, addrq):
  518. '''
  519. Get the line number for a given bytecode offset
  520. Analogous to PyCode_Addr2Line; translated from pseudocode in
  521. Objects/lnotab_notes.txt
  522. '''
  523. co_lnotab = self.pyop_field('co_lnotab').proxyval(set())
  524. # Initialize lineno to co_firstlineno as per PyCode_Addr2Line
  525. # not 0, as lnotab_notes.txt has it:
  526. lineno = int_from_int(self.field('co_firstlineno'))
  527. addr = 0
  528. for addr_incr, line_incr in zip(co_lnotab[::2], co_lnotab[1::2]):
  529. addr += ord(addr_incr)
  530. if addr > addrq:
  531. return lineno
  532. lineno += ord(line_incr)
  533. return lineno
  534. class PyDictObjectPtr(PyObjectPtr):
  535. """
  536. Class wrapping a gdb.Value that's a PyDictObject* i.e. a dict instance
  537. within the process being debugged.
  538. """
  539. _typename = 'PyDictObject'
  540. def iteritems(self):
  541. '''
  542. Yields a sequence of (PyObjectPtr key, PyObjectPtr value) pairs,
  543. analogous to dict.iteritems()
  544. '''
  545. keys = self.field('ma_keys')
  546. values = self.field('ma_values')
  547. entries, nentries = self._get_entries(keys)
  548. for i in safe_range(nentries):
  549. ep = entries[i]
  550. if long(values):
  551. pyop_value = PyObjectPtr.from_pyobject_ptr(values[i])
  552. else:
  553. pyop_value = PyObjectPtr.from_pyobject_ptr(ep['me_value'])
  554. if not pyop_value.is_null():
  555. pyop_key = PyObjectPtr.from_pyobject_ptr(ep['me_key'])
  556. yield (pyop_key, pyop_value)
  557. def proxyval(self, visited):
  558. # Guard against infinite loops:
  559. if self.as_address() in visited:
  560. return ProxyAlreadyVisited('{...}')
  561. visited.add(self.as_address())
  562. result = {}
  563. for pyop_key, pyop_value in self.iteritems():
  564. proxy_key = pyop_key.proxyval(visited)
  565. proxy_value = pyop_value.proxyval(visited)
  566. result[proxy_key] = proxy_value
  567. return result
  568. def write_repr(self, out, visited):
  569. # Guard against infinite loops:
  570. if self.as_address() in visited:
  571. out.write('{...}')
  572. return
  573. visited.add(self.as_address())
  574. out.write('{')
  575. first = True
  576. for pyop_key, pyop_value in self.iteritems():
  577. if not first:
  578. out.write(', ')
  579. first = False
  580. pyop_key.write_repr(out, visited)
  581. out.write(': ')
  582. pyop_value.write_repr(out, visited)
  583. out.write('}')
  584. def _get_entries(self, keys):
  585. dk_nentries = int(keys['dk_nentries'])
  586. dk_size = int(keys['dk_size'])
  587. try:
  588. # <= Python 3.5
  589. return keys['dk_entries'], dk_size
  590. except RuntimeError:
  591. # >= Python 3.6
  592. pass
  593. if dk_size <= 0xFF:
  594. offset = dk_size
  595. elif dk_size <= 0xFFFF:
  596. offset = 2 * dk_size
  597. elif dk_size <= 0xFFFFFFFF:
  598. offset = 4 * dk_size
  599. else:
  600. offset = 8 * dk_size
  601. ent_addr = keys['dk_indices']['as_1'].address
  602. ent_addr = ent_addr.cast(_type_unsigned_char_ptr()) + offset
  603. ent_ptr_t = gdb.lookup_type('PyDictKeyEntry').pointer()
  604. ent_addr = ent_addr.cast(ent_ptr_t)
  605. return ent_addr, dk_nentries
  606. class PyListObjectPtr(PyObjectPtr):
  607. _typename = 'PyListObject'
  608. def __getitem__(self, i):
  609. # Get the gdb.Value for the (PyObject*) with the given index:
  610. field_ob_item = self.field('ob_item')
  611. return field_ob_item[i]
  612. def proxyval(self, visited):
  613. # Guard against infinite loops:
  614. if self.as_address() in visited:
  615. return ProxyAlreadyVisited('[...]')
  616. visited.add(self.as_address())
  617. result = [PyObjectPtr.from_pyobject_ptr(self[i]).proxyval(visited)
  618. for i in safe_range(int_from_int(self.field('ob_size')))]
  619. return result
  620. def write_repr(self, out, visited):
  621. # Guard against infinite loops:
  622. if self.as_address() in visited:
  623. out.write('[...]')
  624. return
  625. visited.add(self.as_address())
  626. out.write('[')
  627. for i in safe_range(int_from_int(self.field('ob_size'))):
  628. if i > 0:
  629. out.write(', ')
  630. element = PyObjectPtr.from_pyobject_ptr(self[i])
  631. element.write_repr(out, visited)
  632. out.write(']')
  633. class PyLongObjectPtr(PyObjectPtr):
  634. _typename = 'PyLongObject'
  635. def proxyval(self, visited):
  636. '''
  637. Python's Include/longobjrep.h has this declaration:
  638. struct _longobject {
  639. PyObject_VAR_HEAD
  640. digit ob_digit[1];
  641. };
  642. with this description:
  643. The absolute value of a number is equal to
  644. SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
  645. Negative numbers are represented with ob_size < 0;
  646. zero is represented by ob_size == 0.
  647. where SHIFT can be either:
  648. #define PyLong_SHIFT 30
  649. #define PyLong_SHIFT 15
  650. '''
  651. ob_size = long(self.field('ob_size'))
  652. if ob_size == 0:
  653. return 0
  654. ob_digit = self.field('ob_digit')
  655. if gdb.lookup_type('digit').sizeof == 2:
  656. SHIFT = 15
  657. else:
  658. SHIFT = 30
  659. digits = [long(ob_digit[i]) * 2**(SHIFT*i)
  660. for i in safe_range(abs(ob_size))]
  661. result = sum(digits)
  662. if ob_size < 0:
  663. result = -result
  664. return result
  665. def write_repr(self, out, visited):
  666. # Write this out as a Python 3 int literal, i.e. without the "L" suffix
  667. proxy = self.proxyval(visited)
  668. out.write("%s" % proxy)
  669. class PyBoolObjectPtr(PyLongObjectPtr):
  670. """
  671. Class wrapping a gdb.Value that's a PyBoolObject* i.e. one of the two
  672. <bool> instances (Py_True/Py_False) within the process being debugged.
  673. """
  674. def proxyval(self, visited):
  675. if PyLongObjectPtr.proxyval(self, visited):
  676. return True
  677. else:
  678. return False
  679. class PyNoneStructPtr(PyObjectPtr):
  680. """
  681. Class wrapping a gdb.Value that's a PyObject* pointing to the
  682. singleton (we hope) _Py_NoneStruct with ob_type PyNone_Type
  683. """
  684. _typename = 'PyObject'
  685. def proxyval(self, visited):
  686. return None
  687. class PyFrameObjectPtr(PyObjectPtr):
  688. _typename = 'PyFrameObject'
  689. def __init__(self, gdbval, cast_to=None):
  690. PyObjectPtr.__init__(self, gdbval, cast_to)
  691. if not self.is_optimized_out():
  692. self.co = PyCodeObjectPtr.from_pyobject_ptr(self.field('f_code'))
  693. self.co_name = self.co.pyop_field('co_name')
  694. self.co_filename = self.co.pyop_field('co_filename')
  695. self.f_lineno = int_from_int(self.field('f_lineno'))
  696. self.f_lasti = int_from_int(self.field('f_lasti'))
  697. self.co_nlocals = int_from_int(self.co.field('co_nlocals'))
  698. self.co_varnames = PyTupleObjectPtr.from_pyobject_ptr(self.co.field('co_varnames'))
  699. def iter_locals(self):
  700. '''
  701. Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
  702. the local variables of this frame
  703. '''
  704. if self.is_optimized_out():
  705. return
  706. f_localsplus = self.field('f_localsplus')
  707. for i in safe_range(self.co_nlocals):
  708. pyop_value = PyObjectPtr.from_pyobject_ptr(f_localsplus[i])
  709. if not pyop_value.is_null():
  710. pyop_name = PyObjectPtr.from_pyobject_ptr(self.co_varnames[i])
  711. yield (pyop_name, pyop_value)
  712. def iter_globals(self):
  713. '''
  714. Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
  715. the global variables of this frame
  716. '''
  717. if self.is_optimized_out():
  718. return ()
  719. pyop_globals = self.pyop_field('f_globals')
  720. return pyop_globals.iteritems()
  721. def iter_builtins(self):
  722. '''
  723. Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
  724. the builtin variables
  725. '''
  726. if self.is_optimized_out():
  727. return ()
  728. pyop_builtins = self.pyop_field('f_builtins')
  729. return pyop_builtins.iteritems()
  730. def get_var_by_name(self, name):
  731. '''
  732. Look for the named local variable, returning a (PyObjectPtr, scope) pair
  733. where scope is a string 'local', 'global', 'builtin'
  734. If not found, return (None, None)
  735. '''
  736. for pyop_name, pyop_value in self.iter_locals():
  737. if name == pyop_name.proxyval(set()):
  738. return pyop_value, 'local'
  739. for pyop_name, pyop_value in self.iter_globals():
  740. if name == pyop_name.proxyval(set()):
  741. return pyop_value, 'global'
  742. for pyop_name, pyop_value in self.iter_builtins():
  743. if name == pyop_name.proxyval(set()):
  744. return pyop_value, 'builtin'
  745. return None, None
  746. def filename(self):
  747. '''Get the path of the current Python source file, as a string'''
  748. if self.is_optimized_out():
  749. return '(frame information optimized out)'
  750. return self.co_filename.proxyval(set())
  751. def current_line_num(self):
  752. '''Get current line number as an integer (1-based)
  753. Translated from PyFrame_GetLineNumber and PyCode_Addr2Line
  754. See Objects/lnotab_notes.txt
  755. '''
  756. if self.is_optimized_out():
  757. return None
  758. f_trace = self.field('f_trace')
  759. if long(f_trace) != 0:
  760. # we have a non-NULL f_trace:
  761. return self.f_lineno
  762. else:
  763. #try:
  764. return self.co.addr2line(self.f_lasti)
  765. #except ValueError:
  766. # return self.f_lineno
  767. def current_line(self):
  768. '''Get the text of the current source line as a string, with a trailing
  769. newline character'''
  770. if self.is_optimized_out():
  771. return '(frame information optimized out)'
  772. filename = self.filename()
  773. try:
  774. f = open(os_fsencode(filename), 'r')
  775. except IOError:
  776. return None
  777. with f:
  778. all_lines = f.readlines()
  779. # Convert from 1-based current_line_num to 0-based list offset:
  780. return all_lines[self.current_line_num()-1]
  781. def write_repr(self, out, visited):
  782. if self.is_optimized_out():
  783. out.write('(frame information optimized out)')
  784. return
  785. out.write('Frame 0x%x, for file %s, line %i, in %s ('
  786. % (self.as_address(),
  787. self.co_filename.proxyval(visited),
  788. self.current_line_num(),
  789. self.co_name.proxyval(visited)))
  790. first = True
  791. for pyop_name, pyop_value in self.iter_locals():
  792. if not first:
  793. out.write(', ')
  794. first = False
  795. out.write(pyop_name.proxyval(visited))
  796. out.write('=')
  797. pyop_value.write_repr(out, visited)
  798. out.write(')')
  799. def print_traceback(self):
  800. if self.is_optimized_out():
  801. sys.stdout.write(' (frame information optimized out)\n')
  802. return
  803. visited = set()
  804. sys.stdout.write(' File "%s", line %i, in %s\n'
  805. % (self.co_filename.proxyval(visited),
  806. self.current_line_num(),
  807. self.co_name.proxyval(visited)))
  808. class PySetObjectPtr(PyObjectPtr):
  809. _typename = 'PySetObject'
  810. @classmethod
  811. def _dummy_key(self):
  812. return gdb.lookup_global_symbol('_PySet_Dummy').value()
  813. def __iter__(self):
  814. dummy_ptr = self._dummy_key()
  815. table = self.field('table')
  816. for i in safe_range(self.field('mask') + 1):
  817. setentry = table[i]
  818. key = setentry['key']
  819. if key != 0 and key != dummy_ptr:
  820. yield PyObjectPtr.from_pyobject_ptr(key)
  821. def proxyval(self, visited):
  822. # Guard against infinite loops:
  823. if self.as_address() in visited:
  824. return ProxyAlreadyVisited('%s(...)' % self.safe_tp_name())
  825. visited.add(self.as_address())
  826. members = (key.proxyval(visited) for key in self)
  827. if self.safe_tp_name() == 'frozenset':
  828. return frozenset(members)
  829. else:
  830. return set(members)
  831. def write_repr(self, out, visited):
  832. # Emulate Python 3's set_repr
  833. tp_name = self.safe_tp_name()
  834. # Guard against infinite loops:
  835. if self.as_address() in visited:
  836. out.write('(...)')
  837. return
  838. visited.add(self.as_address())
  839. # Python 3's set_repr special-cases the empty set:
  840. if not self.field('used'):
  841. out.write(tp_name)
  842. out.write('()')
  843. return
  844. # Python 3 uses {} for set literals:
  845. if tp_name != 'set':
  846. out.write(tp_name)
  847. out.write('(')
  848. out.write('{')
  849. first = True
  850. for key in self:
  851. if not first:
  852. out.write(', ')
  853. first = False
  854. key.write_repr(out, visited)
  855. out.write('}')
  856. if tp_name != 'set':
  857. out.write(')')
  858. class PyBytesObjectPtr(PyObjectPtr):
  859. _typename = 'PyBytesObject'
  860. def __str__(self):
  861. field_ob_size = self.field('ob_size')
  862. field_ob_sval = self.field('ob_sval')
  863. char_ptr = field_ob_sval.address.cast(_type_unsigned_char_ptr())
  864. return ''.join([chr(char_ptr[i]) for i in safe_range(field_ob_size)])
  865. def proxyval(self, visited):
  866. return str(self)
  867. def write_repr(self, out, visited):
  868. # Write this out as a Python 3 bytes literal, i.e. with a "b" prefix
  869. # Get a PyStringObject* within the Python 2 gdb process:
  870. proxy = self.proxyval(visited)
  871. # Transliteration of Python 3's Objects/bytesobject.c:PyBytes_Repr
  872. # to Python 2 code:
  873. quote = "'"
  874. if "'" in proxy and not '"' in proxy:
  875. quote = '"'
  876. out.write('b')
  877. out.write(quote)
  878. for byte in proxy:
  879. if byte == quote or byte == '\\':
  880. out.write('\\')
  881. out.write(byte)
  882. elif byte == '\t':
  883. out.write('\\t')
  884. elif byte == '\n':
  885. out.write('\\n')
  886. elif byte == '\r':
  887. out.write('\\r')
  888. elif byte < ' ' or ord(byte) >= 0x7f:
  889. out.write('\\x')
  890. out.write(hexdigits[(ord(byte) & 0xf0) >> 4])
  891. out.write(hexdigits[ord(byte) & 0xf])
  892. else:
  893. out.write(byte)
  894. out.write(quote)
  895. class PyStringObjectPtr(PyBytesObjectPtr):
  896. _typename = 'PyStringObject'
  897. class PyTupleObjectPtr(PyObjectPtr):
  898. _typename = 'PyTupleObject'
  899. def __getitem__(self, i):
  900. # Get the gdb.Value for the (PyObject*) with the given index:
  901. field_ob_item = self.field('ob_item')
  902. return field_ob_item[i]
  903. def proxyval(self, visited):
  904. # Guard against infinite loops:
  905. if self.as_address() in visited:
  906. return ProxyAlreadyVisited('(...)')
  907. visited.add(self.as_address())
  908. result = tuple(PyObjectPtr.from_pyobject_ptr(self[i]).proxyval(visited)
  909. for i in safe_range(int_from_int(self.field('ob_size'))))
  910. return result
  911. def write_repr(self, out, visited):
  912. # Guard against infinite loops:
  913. if self.as_address() in visited:
  914. out.write('(...)')
  915. return
  916. visited.add(self.as_address())
  917. out.write('(')
  918. for i in safe_range(int_from_int(self.field('ob_size'))):
  919. if i > 0:
  920. out.write(', ')
  921. element = PyObjectPtr.from_pyobject_ptr(self[i])
  922. element.write_repr(out, visited)
  923. if self.field('ob_size') == 1:
  924. out.write(',)')
  925. else:
  926. out.write(')')
  927. class PyTypeObjectPtr(PyObjectPtr):
  928. _typename = 'PyTypeObject'
  929. def _unichr_is_printable(char):
  930. # Logic adapted from Python 3's Tools/unicode/makeunicodedata.py
  931. if char == u" ":
  932. return True
  933. import unicodedata
  934. return unicodedata.category(char) not in ("C", "Z")
  935. if sys.maxunicode >= 0x10000:
  936. _unichr = unichr
  937. else:
  938. # Needed for proper surrogate support if sizeof(Py_UNICODE) is 2 in gdb
  939. def _unichr(x):
  940. if x < 0x10000:
  941. return unichr(x)
  942. x -= 0x10000
  943. ch1 = 0xD800 | (x >> 10)
  944. ch2 = 0xDC00 | (x & 0x3FF)
  945. return unichr(ch1) + unichr(ch2)
  946. class PyUnicodeObjectPtr(PyObjectPtr):
  947. _typename = 'PyUnicodeObject'
  948. def char_width(self):
  949. _type_Py_UNICODE = gdb.lookup_type('Py_UNICODE')
  950. return _type_Py_UNICODE.sizeof
  951. def proxyval(self, visited):
  952. global _is_pep393
  953. if _is_pep393 is None:
  954. fields = gdb.lookup_type('PyUnicodeObject').target().fields()
  955. _is_pep393 = 'data' in [f.name for f in fields]
  956. if _is_pep393:
  957. # Python 3.3 and newer
  958. may_have_surrogates = False
  959. compact = self.field('_base')
  960. ascii = compact['_base']
  961. state = ascii['state']
  962. is_compact_ascii = (int(state['ascii']) and int(state['compact']))
  963. if not int(state['ready']):
  964. # string is not ready
  965. field_length = long(compact['wstr_length'])
  966. may_have_surrogates = True
  967. field_str = ascii['wstr']
  968. else:
  969. field_length = long(ascii['length'])
  970. if is_compact_ascii:
  971. field_str = ascii.address + 1
  972. elif int(state['compact']):
  973. field_str = compact.address + 1
  974. else:
  975. field_str = self.field('data')['any']
  976. repr_kind = int(state['kind'])
  977. if repr_kind == 1:
  978. field_str = field_str.cast(_type_unsigned_char_ptr())
  979. elif repr_kind == 2:
  980. field_str = field_str.cast(_type_unsigned_short_ptr())
  981. elif repr_kind == 4:
  982. field_str = field_str.cast(_type_unsigned_int_ptr())
  983. else:
  984. # Python 3.2 and earlier
  985. field_length = long(self.field('length'))
  986. field_str = self.field('str')
  987. may_have_surrogates = self.char_width() == 2
  988. # Gather a list of ints from the Py_UNICODE array; these are either
  989. # UCS-1, UCS-2 or UCS-4 code points:
  990. if not may_have_surrogates:
  991. Py_UNICODEs = [int(field_str[i]) for i in safe_range(field_length)]
  992. else:
  993. # A more elaborate routine if sizeof(Py_UNICODE) is 2 in the
  994. # inferior process: we must join surrogate pairs.
  995. Py_UNICODEs = []
  996. i = 0
  997. limit = safety_limit(field_length)
  998. while i < limit:
  999. ucs = int(field_str[i])
  1000. i += 1
  1001. if ucs < 0xD800 or ucs >= 0xDC00 or i == field_length:
  1002. Py_UNICODEs.append(ucs)
  1003. continue
  1004. # This could be a surrogate pair.
  1005. ucs2 = int(field_str[i])
  1006. if ucs2 < 0xDC00 or ucs2 > 0xDFFF:
  1007. continue
  1008. code = (ucs & 0x03FF) << 10
  1009. code |= ucs2 & 0x03FF
  1010. code += 0x00010000
  1011. Py_UNICODEs.append(code)
  1012. i += 1
  1013. # Convert the int code points to unicode characters, and generate a
  1014. # local unicode instance.
  1015. # This splits surrogate pairs if sizeof(Py_UNICODE) is 2 here (in gdb).
  1016. result = u''.join([
  1017. (_unichr(ucs) if ucs <= 0x10ffff else '\ufffd')
  1018. for ucs in Py_UNICODEs])
  1019. return result
  1020. def write_repr(self, out, visited):
  1021. # Write this out as a Python 3 str literal, i.e. without a "u" prefix
  1022. # Get a PyUnicodeObject* within the Python 2 gdb process:
  1023. proxy = self.proxyval(visited)
  1024. # Transliteration of Python 3's Object/unicodeobject.c:unicode_repr
  1025. # to Python 2:
  1026. if "'" in proxy and '"' not in proxy:
  1027. quote = '"'
  1028. else:
  1029. quote = "'"
  1030. out.write(quote)
  1031. i = 0
  1032. while i < len(proxy):
  1033. ch = proxy[i]
  1034. i += 1
  1035. # Escape quotes and backslashes
  1036. if ch == quote or ch == '\\':
  1037. out.write('\\')
  1038. out.write(ch)
  1039. # Map special whitespace to '\t', \n', '\r'
  1040. elif ch == '\t':
  1041. out.write('\\t')
  1042. elif ch == '\n':
  1043. out.write('\\n')
  1044. elif ch == '\r':
  1045. out.write('\\r')
  1046. # Map non-printable US ASCII to '\xhh' */
  1047. elif ch < ' ' or ch == 0x7F:
  1048. out.write('\\x')
  1049. out.write(hexdigits[(ord(ch) >> 4) & 0x000F])
  1050. out.write(hexdigits[ord(ch) & 0x000F])
  1051. # Copy ASCII characters as-is
  1052. elif ord(ch) < 0x7F:
  1053. out.write(ch)
  1054. # Non-ASCII characters
  1055. else:
  1056. ucs = ch
  1057. ch2 = None
  1058. if sys.maxunicode < 0x10000:
  1059. # If sizeof(Py_UNICODE) is 2 here (in gdb), join
  1060. # surrogate pairs before calling _unichr_is_printable.
  1061. if (i < len(proxy)
  1062. and 0xD800 <= ord(ch) < 0xDC00 \
  1063. and 0xDC00 <= ord(proxy[i]) <= 0xDFFF):
  1064. ch2 = proxy[i]
  1065. ucs = ch + ch2
  1066. i += 1
  1067. # Unfortuately, Python 2's unicode type doesn't seem
  1068. # to expose the "isprintable" method
  1069. printable = _unichr_is_printable(ucs)
  1070. if printable:
  1071. try:
  1072. ucs.encode(ENCODING)
  1073. except UnicodeEncodeError:
  1074. printable = False
  1075. # Map Unicode whitespace and control characters
  1076. # (categories Z* and C* except ASCII space)
  1077. if not printable:
  1078. if ch2 is not None:
  1079. # Match Python 3's representation of non-printable
  1080. # wide characters.
  1081. code = (ord(ch) & 0x03FF) << 10
  1082. code |= ord(ch2) & 0x03FF
  1083. code += 0x00010000
  1084. else:
  1085. code = ord(ucs)
  1086. # Map 8-bit characters to '\\xhh'
  1087. if code <= 0xff:
  1088. out.write('\\x')
  1089. out.write(hexdigits[(code >> 4) & 0x000F])
  1090. out.write(hexdigits[code & 0x000F])
  1091. # Map 21-bit characters to '\U00xxxxxx'
  1092. elif code >= 0x10000:
  1093. out.write('\\U')
  1094. out.write(hexdigits[(code >> 28) & 0x0000000F])
  1095. out.write(hexdigits[(code >> 24) & 0x0000000F])
  1096. out.write(hexdigits[(code >> 20) & 0x0000000F])
  1097. out.write(hexdigits[(code >> 16) & 0x0000000F])
  1098. out.write(hexdigits[(code >> 12) & 0x0000000F])
  1099. out.write(hexdigits[(code >> 8) & 0x0000000F])
  1100. out.write(hexdigits[(code >> 4) & 0x0000000F])
  1101. out.write(hexdigits[code & 0x0000000F])
  1102. # Map 16-bit characters to '\uxxxx'
  1103. else:
  1104. out.write('\\u')
  1105. out.write(hexdigits[(code >> 12) & 0x000F])
  1106. out.write(hexdigits[(code >> 8) & 0x000F])
  1107. out.write(hexdigits[(code >> 4) & 0x000F])
  1108. out.write(hexdigits[code & 0x000F])
  1109. else:
  1110. # Copy characters as-is
  1111. out.write(ch)
  1112. if ch2 is not None:
  1113. out.write(ch2)
  1114. out.write(quote)
  1115. class wrapperobject(PyObjectPtr):
  1116. _typename = 'wrapperobject'
  1117. def safe_name(self):
  1118. try:
  1119. name = self.field('descr')['d_base']['name'].string()
  1120. return repr(name)
  1121. except (NullPyObjectPtr, RuntimeError):
  1122. return '<unknown name>'
  1123. def safe_tp_name(self):
  1124. try:
  1125. return self.field('self')['ob_type']['tp_name'].string()
  1126. except (NullPyObjectPtr, RuntimeError):
  1127. return '<unknown tp_name>'
  1128. def safe_self_addresss(self):
  1129. try:
  1130. address = long(self.field('self'))
  1131. return '%#x' % address
  1132. except (NullPyObjectPtr, RuntimeError):
  1133. return '<failed to get self address>'
  1134. def proxyval(self, visited):
  1135. name = self.safe_name()
  1136. tp_name = self.safe_tp_name()
  1137. self_address = self.safe_self_addresss()
  1138. return ("<method-wrapper %s of %s object at %s>"
  1139. % (name, tp_name, self_address))
  1140. def write_repr(self, out, visited):
  1141. proxy = self.proxyval(visited)
  1142. out.write(proxy)
  1143. def int_from_int(gdbval):
  1144. return int(str(gdbval))
  1145. def stringify(val):
  1146. # TODO: repr() puts everything on one line; pformat can be nicer, but
  1147. # can lead to v.long results; this function isolates the choice
  1148. if True:
  1149. return repr(val)
  1150. else:
  1151. from pprint import pformat
  1152. return pformat(val)
  1153. class PyObjectPtrPrinter:
  1154. "Prints a (PyObject*)"
  1155. def __init__ (self, gdbval):
  1156. self.gdbval = gdbval
  1157. def to_string (self):
  1158. pyop = PyObjectPtr.from_pyobject_ptr(self.gdbval)
  1159. if True:
  1160. return pyop.get_truncated_repr(MAX_OUTPUT_LEN)
  1161. else:
  1162. # Generate full proxy value then stringify it.
  1163. # Doing so could be expensive
  1164. proxyval = pyop.proxyval(set())
  1165. return stringify(proxyval)
  1166. def pretty_printer_lookup(gdbval):
  1167. type = gdbval.type.unqualified()
  1168. if type.code != gdb.TYPE_CODE_PTR:
  1169. return None
  1170. type = type.target().unqualified()
  1171. t = str(type)
  1172. if t in ("PyObject", "PyFrameObject", "PyUnicodeObject", "wrapperobject"):
  1173. return PyObjectPtrPrinter(gdbval)
  1174. """
  1175. During development, I've been manually invoking the code in this way:
  1176. (gdb) python
  1177. import sys
  1178. sys.path.append('/home/david/coding/python-gdb')
  1179. import libpython
  1180. end
  1181. then reloading it after each edit like this:
  1182. (gdb) python reload(libpython)
  1183. The following code should ensure that the prettyprinter is registered
  1184. if the code is autoloaded by gdb when visiting libpython.so, provided
  1185. that this python file is installed to the same path as the library (or its
  1186. .debug file) plus a "-gdb.py" suffix, e.g:
  1187. /usr/lib/libpython2.6.so.1.0-gdb.py
  1188. /usr/lib/debug/usr/lib/libpython2.6.so.1.0.debug-gdb.py
  1189. """
  1190. def register (obj):
  1191. if obj is None:
  1192. obj = gdb
  1193. # Wire up the pretty-printer
  1194. obj.pretty_printers.append(pretty_printer_lookup)
  1195. register (gdb.current_objfile ())
  1196. # Unfortunately, the exact API exposed by the gdb module varies somewhat
  1197. # from build to build
  1198. # See http://bugs.python.org/issue8279?#msg102276
  1199. class Frame(object):
  1200. '''
  1201. Wrapper for gdb.Frame, adding various methods
  1202. '''
  1203. def __init__(self, gdbframe):
  1204. self._gdbframe = gdbframe
  1205. def older(self):
  1206. older = self._gdbframe.older()
  1207. if older:
  1208. return Frame(older)
  1209. else:
  1210. return None
  1211. def newer(self):
  1212. newer = self._gdbframe.newer()
  1213. if newer:
  1214. return Frame(newer)
  1215. else:
  1216. return None
  1217. def select(self):
  1218. '''If supported, select this frame and return True; return False if unsupported
  1219. Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
  1220. onwards, but absent on Ubuntu buildbot'''
  1221. if not hasattr(self._gdbframe, 'select'):
  1222. print ('Unable to select frame: '
  1223. 'this build of gdb does not expose a gdb.Frame.select method')
  1224. return False
  1225. self._gdbframe.select()
  1226. return True
  1227. def get_index(self):
  1228. '''Calculate index of frame, starting at 0 for the newest frame within
  1229. this thread'''
  1230. index = 0
  1231. # Go down until you reach the newest frame:
  1232. iter_frame = self
  1233. while iter_frame.newer():
  1234. index += 1
  1235. iter_frame = iter_frame.newer()
  1236. return index
  1237. # We divide frames into:
  1238. # - "python frames":
  1239. # - "bytecode frames" i.e. PyEval_EvalFrameEx
  1240. # - "other python frames": things that are of interest from a python
  1241. # POV, but aren't bytecode (e.g. GC, GIL)
  1242. # - everything else
  1243. def is_python_frame(self):
  1244. '''Is this a _PyEval_EvalFrameDefault frame, or some other important
  1245. frame? (see is_other_python_frame for what "important" means in this
  1246. context)'''
  1247. if self.is_evalframe():
  1248. return True
  1249. if self.is_other_python_frame():
  1250. return True
  1251. return False
  1252. def is_evalframe(self):
  1253. '''Is this a _PyEval_EvalFrameDefault frame?'''
  1254. if self._gdbframe.name() == EVALFRAME:
  1255. '''
  1256. I believe we also need to filter on the inline
  1257. struct frame_id.inline_depth, only regarding frames with
  1258. an inline depth of 0 as actually being this function
  1259. So we reject those with type gdb.INLINE_FRAME
  1260. '''
  1261. if self._gdbframe.type() == gdb.NORMAL_FRAME:
  1262. # We have a _PyEval_EvalFrameDefault frame:
  1263. return True
  1264. return False
  1265. def is_other_python_frame(self):
  1266. '''Is this frame worth displaying in python backtraces?
  1267. Examples:
  1268. - waiting on the GIL
  1269. - garbage-collecting
  1270. - within a CFunction
  1271. If it is, return a descriptive string
  1272. For other frames, return False
  1273. '''
  1274. if self.is_waiting_for_gil():
  1275. return 'Waiting for the GIL'
  1276. if self.is_gc_collect():
  1277. return 'Garbage-collecting'
  1278. # Detect invocations of PyCFunction instances:
  1279. frame = self._gdbframe
  1280. caller = frame.name()
  1281. if not caller:
  1282. return False
  1283. if caller in ('_PyCFunction_FastCallDict',
  1284. '_PyCFunction_FastCallKeywords'):
  1285. arg_name = 'func'
  1286. # Within that frame:
  1287. # "func" is the local containing the PyObject* of the
  1288. # PyCFunctionObject instance
  1289. # "f" is the same value, but cast to (PyCFunctionObject*)
  1290. # "self" is the (PyObject*) of the 'self'
  1291. try:
  1292. # Use the prettyprinter for the func:
  1293. func = frame.read_var(arg_name)
  1294. return str(func)
  1295. except RuntimeError:
  1296. return 'PyCFunction invocation (unable to read %s)' % arg_name
  1297. if caller == 'wrapper_call':
  1298. try:
  1299. func = frame.read_var('wp')
  1300. return str(func)
  1301. except RuntimeError:
  1302. return '<wrapper_call invocation>'
  1303. # This frame isn't worth reporting:
  1304. return False
  1305. def is_waiting_for_gil(self):
  1306. '''Is this frame waiting on the GIL?'''
  1307. # This assumes the _POSIX_THREADS version of Python/ceval_gil.h:
  1308. name = self._gdbframe.name()
  1309. if name:
  1310. return 'pthread_cond_timedwait' in name
  1311. def is_gc_collect(self):
  1312. '''Is this frame "collect" within the garbage-collector?'''
  1313. return self._gdbframe.name() == 'collect'
  1314. def get_pyop(self):
  1315. try:
  1316. f = self._gdbframe.read_var('f')
  1317. frame = PyFrameObjectPtr.from_pyobject_ptr(f)
  1318. if not frame.is_optimized_out():
  1319. return frame
  1320. # gdb is unable to get the "f" argument of PyEval_EvalFrameEx()
  1321. # because it was "optimized out". Try to get "f" from the frame
  1322. # of the caller, PyEval_EvalCodeEx().
  1323. orig_frame = frame
  1324. caller = self._gdbframe.older()
  1325. if caller:
  1326. f = caller.read_var('f')
  1327. frame = PyFrameObjectPtr.from_pyobject_ptr(f)
  1328. if not frame.is_optimized_out():
  1329. return frame
  1330. return orig_frame
  1331. except ValueError:
  1332. return None
  1333. @classmethod
  1334. def get_selected_frame(cls):
  1335. _gdbframe = gdb.selected_frame()
  1336. if _gdbframe:
  1337. return Frame(_gdbframe)
  1338. return None
  1339. @classmethod
  1340. def get_selected_python_frame(cls):
  1341. '''Try to obtain the Frame for the python-related code in the selected
  1342. frame, or None'''
  1343. try:
  1344. frame = cls.get_selected_frame()
  1345. except gdb.error:
  1346. # No frame: Python didn't start yet
  1347. return None
  1348. while frame:
  1349. if frame.is_python_frame():
  1350. return frame
  1351. frame = frame.older()
  1352. # Not found:
  1353. return None
  1354. @classmethod
  1355. def get_selected_bytecode_frame(cls):
  1356. '''Try to obtain the Frame for the python bytecode interpreter in the
  1357. selected GDB frame, or None'''
  1358. frame = cls.get_selected_frame()
  1359. while frame:
  1360. if frame.is_evalframe():
  1361. return frame
  1362. frame = frame.older()
  1363. # Not found:
  1364. return None
  1365. def print_summary(self):
  1366. if self.is_evalframe():
  1367. pyop = self.get_pyop()
  1368. if pyop:
  1369. line = pyop.get_truncated_repr(MAX_OUTPUT_LEN)
  1370. write_unicode(sys.stdout, '#%i %s\n' % (self.get_index(), line))
  1371. if not pyop.is_optimized_out():
  1372. line = pyop.current_line()
  1373. if line is not None:
  1374. sys.stdout.write(' %s\n' % line.strip())
  1375. else:
  1376. sys.stdout.write('#%i (unable to read python frame information)\n' % self.get_index())
  1377. else:
  1378. info = self.is_other_python_frame()
  1379. if info:
  1380. sys.stdout.write('#%i %s\n' % (self.get_index(), info))
  1381. else:
  1382. sys.stdout.write('#%i\n' % self.get_index())
  1383. def print_traceback(self):
  1384. if self.is_evalframe():
  1385. pyop = self.get_pyop()
  1386. if pyop:
  1387. pyop.print_traceback()
  1388. if not pyop.is_optimized_out():
  1389. line = pyop.current_line()
  1390. if line is not None:
  1391. sys.stdout.write(' %s\n' % line.strip())
  1392. else:
  1393. sys.stdout.write(' (unable to read python frame information)\n')
  1394. else:
  1395. info = self.is_other_python_frame()
  1396. if info:
  1397. sys.stdout.write(' %s\n' % info)
  1398. else:
  1399. sys.stdout.write(' (not a python frame)\n')
  1400. class PyList(gdb.Command):
  1401. '''List the current Python source code, if any
  1402. Use
  1403. py-list START
  1404. to list at a different line number within the python source.
  1405. Use
  1406. py-list START, END
  1407. to list a specific range of lines within the python source.
  1408. '''
  1409. def __init__(self):
  1410. gdb.Command.__init__ (self,
  1411. "py-list",
  1412. gdb.COMMAND_FILES,
  1413. gdb.COMPLETE_NONE)
  1414. def invoke(self, args, from_tty):
  1415. import re
  1416. start = None
  1417. end = None
  1418. m = re.match(r'\s*(\d+)\s*', args)
  1419. if m:
  1420. start = int(m.group(0))
  1421. end = start + 10
  1422. m = re.match(r'\s*(\d+)\s*,\s*(\d+)\s*', args)
  1423. if m:
  1424. start, end = map(int, m.groups())
  1425. # py-list requires an actual PyEval_EvalFrameEx frame:
  1426. frame = Frame.get_selected_bytecode_frame()
  1427. if not frame:
  1428. print('Unable to locate gdb frame for python bytecode interpreter')
  1429. return
  1430. pyop = frame.get_pyop()
  1431. if not pyop or pyop.is_optimized_out():
  1432. print('Unable to read information on python frame')
  1433. return
  1434. filename = pyop.filename()
  1435. lineno = pyop.current_line_num()
  1436. if start is None:
  1437. start = lineno - 5
  1438. end = lineno + 5
  1439. if start<1:
  1440. start = 1
  1441. try:
  1442. f = open(os_fsencode(filename), 'r')
  1443. except IOError as err:
  1444. sys.stdout.write('Unable to open %s: %s\n'
  1445. % (filename, err))
  1446. return
  1447. with f:
  1448. all_lines = f.readlines()
  1449. # start and end are 1-based, all_lines is 0-based;
  1450. # so [start-1:end] as a python slice gives us [start, end] as a
  1451. # closed interval
  1452. for i, line in enumerate(all_lines[start-1:end]):
  1453. linestr = str(i+start)
  1454. # Highlight current line:
  1455. if i + start == lineno:
  1456. linestr = '>' + linestr
  1457. sys.stdout.write('%4s %s' % (linestr, line))
  1458. # ...and register the command:
  1459. PyList()
  1460. def move_in_stack(move_up):
  1461. '''Move up or down the stack (for the py-up/py-down command)'''
  1462. frame = Frame.get_selected_python_frame()
  1463. if not frame:
  1464. print('Unable to locate python frame')
  1465. return
  1466. while frame:
  1467. if move_up:
  1468. iter_frame = frame.older()
  1469. else:
  1470. iter_frame = frame.newer()
  1471. if not iter_frame:
  1472. break
  1473. if iter_frame.is_python_frame():
  1474. # Result:
  1475. if iter_frame.select():
  1476. iter_frame.print_summary()
  1477. return
  1478. frame = iter_frame
  1479. if move_up:
  1480. print('Unable to find an older python frame')
  1481. else:
  1482. print('Unable to find a newer python frame')
  1483. class PyUp(gdb.Command):
  1484. 'Select and print the python stack frame that called this one (if any)'
  1485. def __init__(self):
  1486. gdb.Command.__init__ (self,
  1487. "py-up",
  1488. gdb.COMMAND_STACK,
  1489. gdb.COMPLETE_NONE)
  1490. def invoke(self, args, from_tty):
  1491. move_in_stack(move_up=True)
  1492. class PyDown(gdb.Command):
  1493. 'Select and print the python stack frame called by this one (if any)'
  1494. def __init__(self):
  1495. gdb.Command.__init__ (self,
  1496. "py-down",
  1497. gdb.COMMAND_STACK,
  1498. gdb.COMPLETE_NONE)
  1499. def invoke(self, args, from_tty):
  1500. move_in_stack(move_up=False)
  1501. # Not all builds of gdb have gdb.Frame.select
  1502. if hasattr(gdb.Frame, 'select'):
  1503. PyUp()
  1504. PyDown()
  1505. class PyBacktraceFull(gdb.Command):
  1506. 'Display the current python frame and all the frames within its call stack (if any)'
  1507. def __init__(self):
  1508. gdb.Command.__init__ (self,
  1509. "py-bt-full",
  1510. gdb.COMMAND_STACK,
  1511. gdb.COMPLETE_NONE)
  1512. def invoke(self, args, from_tty):
  1513. frame = Frame.get_selected_python_frame()
  1514. if not frame:
  1515. print('Unable to locate python frame')
  1516. return
  1517. while frame:
  1518. if frame.is_python_frame():
  1519. frame.print_summary()
  1520. frame = frame.older()
  1521. PyBacktraceFull()
  1522. class PyBacktrace(gdb.Command):
  1523. 'Display the current python frame and all the frames within its call stack (if any)'
  1524. def __init__(self):
  1525. gdb.Command.__init__ (self,
  1526. "py-bt",
  1527. gdb.COMMAND_STACK,
  1528. gdb.COMPLETE_NONE)
  1529. def invoke(self, args, from_tty):
  1530. frame = Frame.get_selected_python_frame()
  1531. if not frame:
  1532. print('Unable to locate python frame')
  1533. return
  1534. sys.stdout.write('Traceback (most recent call first):\n')
  1535. while frame:
  1536. if frame.is_python_frame():
  1537. frame.print_traceback()
  1538. frame = frame.older()
  1539. PyBacktrace()
  1540. class PyPrint(gdb.Command):
  1541. 'Look up the given python variable name, and print it'
  1542. def __init__(self):
  1543. gdb.Command.__init__ (self,
  1544. "py-print",
  1545. gdb.COMMAND_DATA,
  1546. gdb.COMPLETE_NONE)
  1547. def invoke(self, args, from_tty):
  1548. name = str(args)
  1549. frame = Frame.get_selected_python_frame()
  1550. if not frame:
  1551. print('Unable to locate python frame')
  1552. return
  1553. pyop_frame = frame.get_pyop()
  1554. if not pyop_frame:
  1555. print('Unable to read information on python frame')
  1556. return
  1557. pyop_var, scope = pyop_frame.get_var_by_name(name)
  1558. if pyop_var:
  1559. print('%s %r = %s'
  1560. % (scope,
  1561. name,
  1562. pyop_var.get_truncated_repr(MAX_OUTPUT_LEN)))
  1563. else:
  1564. print('%r not found' % name)
  1565. PyPrint()
  1566. class PyLocals(gdb.Command):
  1567. 'Look up the given python variable name, and print it'
  1568. def __init__(self, command="py-locals"):
  1569. gdb.Command.__init__ (self,
  1570. command,
  1571. gdb.COMMAND_DATA,
  1572. gdb.COMPLETE_NONE)
  1573. def invoke(self, args, from_tty):
  1574. name = str(args)
  1575. frame = Frame.get_selected_python_frame()
  1576. if not frame:
  1577. print('Unable to locate python frame')
  1578. return
  1579. pyop_frame = frame.get_pyop()
  1580. if not pyop_frame:
  1581. print('Unable to read information on python frame')
  1582. return
  1583. namespace = self.get_namespace(pyop_frame)
  1584. namespace = [(name.proxyval(set()), val) for name, val in namespace]
  1585. if namespace:
  1586. name, val = max(namespace, key=lambda item: len(item[0]))
  1587. max_name_length = len(name)
  1588. for name, pyop_value in namespace:
  1589. value = pyop_value.get_truncated_repr(MAX_OUTPUT_LEN)
  1590. print('%-*s = %s' % (max_name_length, name, value))
  1591. def get_namespace(self, pyop_frame):
  1592. return pyop_frame.iter_locals()
  1593. PyLocals()
  1594. ##################################################################
  1595. ## added, not in CPython
  1596. ##################################################################
  1597. import re
  1598. import warnings
  1599. import tempfile
  1600. import textwrap
  1601. import itertools
  1602. class PyGlobals(PyLocals):
  1603. 'List all the globals in the currently select Python frame'
  1604. def get_namespace(self, pyop_frame):
  1605. return pyop_frame.iter_globals()
  1606. PyGlobals("py-globals")
  1607. class PyNameEquals(gdb.Function):
  1608. def _get_pycurframe_attr(self, attr):
  1609. frame = Frame(gdb.selected_frame())
  1610. if frame.is_evalframeex():
  1611. pyframe = frame.get_pyop()
  1612. if pyframe is None:
  1613. warnings.warn("Use a Python debug build, Python breakpoints "
  1614. "won't work otherwise.")
  1615. return None
  1616. return getattr(pyframe, attr).proxyval(set())
  1617. return None
  1618. def invoke(self, funcname):
  1619. attr = self._get_pycurframe_attr('co_name')
  1620. return attr is not None and attr == funcname.string()
  1621. PyNameEquals("pyname_equals")
  1622. class PyModEquals(PyNameEquals):
  1623. def invoke(self, modname):
  1624. attr = self._get_pycurframe_attr('co_filename')
  1625. if attr is not None:
  1626. filename, ext = os.path.splitext(os.path.basename(attr))
  1627. return filename == modname.string()
  1628. return False
  1629. PyModEquals("pymod_equals")
  1630. class PyBreak(gdb.Command):
  1631. """
  1632. Set a Python breakpoint. Examples:
  1633. Break on any function or method named 'func' in module 'modname'
  1634. py-break modname.func
  1635. Break on any function or method named 'func'
  1636. py-break func
  1637. """
  1638. def invoke(self, funcname, from_tty):
  1639. if '.' in funcname:
  1640. modname, dot, funcname = funcname.rpartition('.')
  1641. cond = '$pyname_equals("%s") && $pymod_equals("%s")' % (funcname,
  1642. modname)
  1643. else:
  1644. cond = '$pyname_equals("%s")' % funcname
  1645. gdb.execute('break PyEval_EvalFrameEx if ' + cond)
  1646. PyBreak("py-break", gdb.COMMAND_RUNNING, gdb.COMPLETE_NONE)
  1647. class _LoggingState(object):
  1648. """
  1649. State that helps to provide a reentrant gdb.execute() function.
  1650. """
  1651. def __init__(self):
  1652. f = tempfile.NamedTemporaryFile('r+')
  1653. self.file = f
  1654. self.filename = f.name
  1655. self.fd = f.fileno()
  1656. _execute("set logging file %s" % self.filename)
  1657. self.file_position_stack = []
  1658. def __enter__(self):
  1659. if not self.file_position_stack:
  1660. _execute("set logging redirect on")
  1661. _execute("set logging on")
  1662. _execute("set pagination off")
  1663. self.file_position_stack.append(os.fstat(self.fd).st_size)
  1664. return self
  1665. def getoutput(self):
  1666. gdb.flush()
  1667. self.file.seek(self.file_position_stack[-1])
  1668. result = self.file.read()
  1669. return result
  1670. def __exit__(self, exc_type, exc_val, tb):
  1671. startpos = self.file_position_stack.pop()
  1672. self.file.seek(startpos)
  1673. self.file.truncate()
  1674. if not self.file_position_stack:
  1675. _execute("set logging off")
  1676. _execute("set logging redirect off")
  1677. _execute("set pagination on")
  1678. def execute(command, from_tty=False, to_string=False):
  1679. """
  1680. Replace gdb.execute() with this function and have it accept a 'to_string'
  1681. argument (new in 7.2). Have it properly capture stderr also. Ensure
  1682. reentrancy.
  1683. """
  1684. if to_string:
  1685. with _logging_state as state:
  1686. _execute(command, from_tty)
  1687. return state.getoutput()
  1688. else:
  1689. _execute(command, from_tty)
  1690. _execute = gdb.execute
  1691. gdb.execute = execute
  1692. _logging_state = _LoggingState()
  1693. def get_selected_inferior():
  1694. """
  1695. Return the selected inferior in gdb.
  1696. """
  1697. # Woooh, another bug in gdb! Is there an end in sight?
  1698. # http://sourceware.org/bugzilla/show_bug.cgi?id=12212
  1699. return gdb.inferiors()[0]
  1700. selected_thread = gdb.selected_thread()
  1701. for inferior in gdb.inferiors():
  1702. for thread in inferior.threads():
  1703. if thread == selected_thread:
  1704. return inferior
  1705. def source_gdb_script(script_contents, to_string=False):
  1706. """
  1707. Source a gdb script with script_contents passed as a string. This is useful
  1708. to provide defines for py-step and py-next to make them repeatable (this is
  1709. not possible with gdb.execute()). See
  1710. http://sourceware.org/bugzilla/show_bug.cgi?id=12216
  1711. """
  1712. fd, filename = tempfile.mkstemp()
  1713. f = os.fdopen(fd, 'w')
  1714. f.write(script_contents)
  1715. f.close()
  1716. gdb.execute("source %s" % filename, to_string=to_string)
  1717. os.remove(filename)
  1718. def register_defines():
  1719. source_gdb_script(textwrap.dedent("""\
  1720. define py-step
  1721. -py-step
  1722. end
  1723. define py-next
  1724. -py-next
  1725. end
  1726. document py-step
  1727. %s
  1728. end
  1729. document py-next
  1730. %s
  1731. end
  1732. """) % (PyStep.__doc__, PyNext.__doc__))
  1733. def stackdepth(frame):
  1734. "Tells the stackdepth of a gdb frame."
  1735. depth = 0
  1736. while frame:
  1737. frame = frame.older()
  1738. depth += 1
  1739. return depth
  1740. class ExecutionControlCommandBase(gdb.Command):
  1741. """
  1742. Superclass for language specific execution control. Language specific
  1743. features should be implemented by lang_info using the LanguageInfo
  1744. interface. 'name' is the name of the command.
  1745. """
  1746. def __init__(self, name, lang_info):
  1747. super(ExecutionControlCommandBase, self).__init__(
  1748. name, gdb.COMMAND_RUNNING, gdb.COMPLETE_NONE)
  1749. self.lang_info = lang_info
  1750. def install_breakpoints(self):
  1751. all_locations = itertools.chain(
  1752. self.lang_info.static_break_functions(),
  1753. self.lang_info.runtime_break_functions())
  1754. for location in all_locations:
  1755. result = gdb.execute('break %s' % location, to_string=True)
  1756. yield re.search(r'Breakpoint (\d+)', result).group(1)
  1757. def delete_breakpoints(self, breakpoint_list):
  1758. for bp in breakpoint_list:
  1759. gdb.execute("delete %s" % bp)
  1760. def filter_output(self, result):
  1761. reflags = re.MULTILINE
  1762. output_on_halt = [
  1763. (r'^Program received signal .*', reflags|re.DOTALL),
  1764. (r'.*[Ww]arning.*', 0),
  1765. (r'^Program exited .*', reflags),
  1766. ]
  1767. output_always = [
  1768. # output when halting on a watchpoint
  1769. (r'^(Old|New) value = .*', reflags),
  1770. # output from the 'display' command
  1771. (r'^\d+: \w+ = .*', reflags),
  1772. ]
  1773. def filter_output(regexes):
  1774. output = []
  1775. for regex, flags in regexes:
  1776. for match in re.finditer(regex, result, flags):
  1777. output.append(match.group(0))
  1778. return '\n'.join(output)
  1779. # Filter the return value output of the 'finish' command
  1780. match_finish = re.search(r'^Value returned is \$\d+ = (.*)', result,
  1781. re.MULTILINE)
  1782. if match_finish:
  1783. finish_output = 'Value returned: %s\n' % match_finish.group(1)
  1784. else:
  1785. finish_output = ''
  1786. return (filter_output(output_on_halt),
  1787. finish_output + filter_output(output_always))
  1788. def stopped(self):
  1789. return get_selected_inferior().pid == 0
  1790. def finish_executing(self, result):
  1791. """
  1792. After doing some kind of code running in the inferior, print the line
  1793. of source code or the result of the last executed gdb command (passed
  1794. in as the `result` argument).
  1795. """
  1796. output_on_halt, output_always = self.filter_output(result)
  1797. if self.stopped():
  1798. print(output_always)
  1799. print(output_on_halt)
  1800. else:
  1801. frame = gdb.selected_frame()
  1802. source_line = self.lang_info.get_source_line(frame)
  1803. if self.lang_info.is_relevant_function(frame):
  1804. raised_exception = self.lang_info.exc_info(frame)
  1805. if raised_exception:
  1806. print(raised_exception)
  1807. if source_line:
  1808. if output_always.rstrip():
  1809. print(output_always.rstrip())
  1810. print(source_line)
  1811. else:
  1812. print(result)
  1813. def _finish(self):
  1814. """
  1815. Execute until the function returns (or until something else makes it
  1816. stop)
  1817. """
  1818. if gdb.selected_frame().older() is not None:
  1819. return gdb.execute('finish', to_string=True)
  1820. else:
  1821. # outermost frame, continue
  1822. return gdb.execute('cont', to_string=True)
  1823. def _finish_frame(self):
  1824. """
  1825. Execute until the function returns to a relevant caller.
  1826. """
  1827. while True:
  1828. result = self._finish()
  1829. try:
  1830. frame = gdb.selected_frame()
  1831. except RuntimeError:
  1832. break
  1833. hitbp = re.search(r'Breakpoint (\d+)', result)
  1834. is_relevant = self.lang_info.is_relevant_function(frame)
  1835. if hitbp or is_relevant or self.stopped():
  1836. break
  1837. return result
  1838. def finish(self, *args):
  1839. "Implements the finish command."
  1840. result = self._finish_frame()
  1841. self.finish_executing(result)
  1842. def step(self, stepinto, stepover_command='next'):
  1843. """
  1844. Do a single step or step-over. Returns the result of the last gdb
  1845. command that made execution stop.
  1846. This implementation, for stepping, sets (conditional) breakpoints for
  1847. all functions that are deemed relevant. It then does a step over until
  1848. either something halts execution, or until the next line is reached.
  1849. If, however, stepover_command is given, it should be a string gdb
  1850. command that continues execution in some way. The idea is that the
  1851. caller has set a (conditional) breakpoint or watchpoint that can work
  1852. more efficiently than the step-over loop. For Python this means setting
  1853. a watchpoint for f->f_lasti, which means we can then subsequently
  1854. "finish" frames.
  1855. We want f->f_lasti instead of f->f_lineno, because the latter only
  1856. works properly with local trace functions, see
  1857. PyFrameObjectPtr.current_line_num and PyFrameObjectPtr.addr2line.
  1858. """
  1859. if stepinto:
  1860. breakpoint_list = list(self.install_breakpoints())
  1861. beginframe = gdb.selected_frame()
  1862. if self.lang_info.is_relevant_function(beginframe):
  1863. # If we start in a relevant frame, initialize stuff properly. If
  1864. # we don't start in a relevant frame, the loop will halt
  1865. # immediately. So don't call self.lang_info.lineno() as it may
  1866. # raise for irrelevant frames.
  1867. beginline = self.lang_info.lineno(beginframe)
  1868. if not stepinto:
  1869. depth = stackdepth(beginframe)
  1870. newframe = beginframe
  1871. while True:
  1872. if self.lang_info.is_relevant_function(newframe):
  1873. result = gdb.execute(stepover_command, to_string=True)
  1874. else:
  1875. result = self._finish_frame()
  1876. if self.stopped():
  1877. break
  1878. newframe = gdb.selected_frame()
  1879. is_relevant_function = self.lang_info.is_relevant_function(newframe)
  1880. try:
  1881. framename = newframe.name()
  1882. except RuntimeError:
  1883. framename = None
  1884. m = re.search(r'Breakpoint (\d+)', result)
  1885. if m:
  1886. if is_relevant_function and m.group(1) in breakpoint_list:
  1887. # although we hit a breakpoint, we still need to check
  1888. # that the function, in case hit by a runtime breakpoint,
  1889. # is in the right context
  1890. break
  1891. if newframe != beginframe:
  1892. # new function
  1893. if not stepinto:
  1894. # see if we returned to the caller
  1895. newdepth = stackdepth(newframe)
  1896. is_relevant_function = (newdepth < depth and
  1897. is_relevant_function)
  1898. if is_relevant_function:
  1899. break
  1900. else:
  1901. # newframe equals beginframe, check for a difference in the
  1902. # line number
  1903. lineno = self.lang_info.lineno(newframe)
  1904. if lineno and lineno != beginline:
  1905. break
  1906. if stepinto:
  1907. self.delete_breakpoints(breakpoint_list)
  1908. self.finish_executing(result)
  1909. def run(self, args, from_tty):
  1910. self.finish_executing(gdb.execute('run ' + args, to_string=True))
  1911. def cont(self, *args):
  1912. self.finish_executing(gdb.execute('cont', to_string=True))
  1913. class LanguageInfo(object):
  1914. """
  1915. This class defines the interface that ExecutionControlCommandBase needs to
  1916. provide language-specific execution control.
  1917. Classes that implement this interface should implement:
  1918. lineno(frame)
  1919. Tells the current line number (only called for a relevant frame).
  1920. If lineno is a false value it is not checked for a difference.
  1921. is_relevant_function(frame)
  1922. tells whether we care about frame 'frame'
  1923. get_source_line(frame)
  1924. get the line of source code for the current line (only called for a
  1925. relevant frame). If the source code cannot be retrieved this
  1926. function should return None
  1927. exc_info(frame) -- optional
  1928. tells whether an exception was raised, if so, it should return a
  1929. string representation of the exception value, None otherwise.
  1930. static_break_functions()
  1931. returns an iterable of function names that are considered relevant
  1932. and should halt step-into execution. This is needed to provide a
  1933. performing step-into
  1934. runtime_break_functions() -- optional
  1935. list of functions that we should break into depending on the
  1936. context
  1937. """
  1938. def exc_info(self, frame):
  1939. "See this class' docstring."
  1940. def runtime_break_functions(self):
  1941. """
  1942. Implement this if the list of step-into functions depends on the
  1943. context.
  1944. """
  1945. return ()
  1946. class PythonInfo(LanguageInfo):
  1947. def pyframe(self, frame):
  1948. pyframe = Frame(frame).get_pyop()
  1949. if pyframe:
  1950. return pyframe
  1951. else:
  1952. raise gdb.RuntimeError(
  1953. "Unable to find the Python frame, run your code with a debug "
  1954. "build (configure with --with-pydebug or compile with -g).")
  1955. def lineno(self, frame):
  1956. return self.pyframe(frame).current_line_num()
  1957. def is_relevant_function(self, frame):
  1958. return Frame(frame).is_evalframeex()
  1959. def get_source_line(self, frame):
  1960. try:
  1961. pyframe = self.pyframe(frame)
  1962. return '%4d %s' % (pyframe.current_line_num(),
  1963. pyframe.current_line().rstrip())
  1964. except IOError:
  1965. return None
  1966. def exc_info(self, frame):
  1967. try:
  1968. tstate = frame.read_var('tstate').dereference()
  1969. if gdb.parse_and_eval('tstate->frame == f'):
  1970. # tstate local variable initialized, check for an exception
  1971. inf_type = tstate['curexc_type']
  1972. inf_value = tstate['curexc_value']
  1973. if inf_type:
  1974. return 'An exception was raised: %s' % (inf_value,)
  1975. except (ValueError, RuntimeError):
  1976. # Could not read the variable tstate or it's memory, it's ok
  1977. pass
  1978. def static_break_functions(self):
  1979. yield 'PyEval_EvalFrameEx'
  1980. class PythonStepperMixin(object):
  1981. """
  1982. Make this a mixin so CyStep can also inherit from this and use a
  1983. CythonCodeStepper at the same time.
  1984. """
  1985. def python_step(self, stepinto):
  1986. """
  1987. Set a watchpoint on the Python bytecode instruction pointer and try
  1988. to finish the frame
  1989. """
  1990. output = gdb.execute('watch f->f_lasti', to_string=True)
  1991. watchpoint = int(re.search(r'[Ww]atchpoint (\d+):', output).group(1))
  1992. self.step(stepinto=stepinto, stepover_command='finish')
  1993. gdb.execute('delete %s' % watchpoint)
  1994. class PyStep(ExecutionControlCommandBase, PythonStepperMixin):
  1995. "Step through Python code."
  1996. stepinto = True
  1997. def invoke(self, args, from_tty):
  1998. self.python_step(stepinto=self.stepinto)
  1999. class PyNext(PyStep):
  2000. "Step-over Python code."
  2001. stepinto = False
  2002. class PyFinish(ExecutionControlCommandBase):
  2003. "Execute until function returns to a caller."
  2004. invoke = ExecutionControlCommandBase.finish
  2005. class PyRun(ExecutionControlCommandBase):
  2006. "Run the program."
  2007. invoke = ExecutionControlCommandBase.run
  2008. class PyCont(ExecutionControlCommandBase):
  2009. invoke = ExecutionControlCommandBase.cont
  2010. def _pointervalue(gdbval):
  2011. """
  2012. Return the value of the pointer as a Python int.
  2013. gdbval.type must be a pointer type
  2014. """
  2015. # don't convert with int() as it will raise a RuntimeError
  2016. if gdbval.address is not None:
  2017. return int(gdbval.address)
  2018. else:
  2019. # the address attribute is None sometimes, in which case we can
  2020. # still convert the pointer to an int
  2021. return int(gdbval)
  2022. def pointervalue(gdbval):
  2023. pointer = _pointervalue(gdbval)
  2024. try:
  2025. if pointer < 0:
  2026. raise gdb.GdbError("Negative pointer value, presumably a bug "
  2027. "in gdb, aborting.")
  2028. except RuntimeError:
  2029. # work around yet another bug in gdb where you get random behaviour
  2030. # and tracebacks
  2031. pass
  2032. return pointer
  2033. def get_inferior_unicode_postfix():
  2034. try:
  2035. gdb.parse_and_eval('PyUnicode_FromEncodedObject')
  2036. except RuntimeError:
  2037. try:
  2038. gdb.parse_and_eval('PyUnicodeUCS2_FromEncodedObject')
  2039. except RuntimeError:
  2040. return 'UCS4'
  2041. else:
  2042. return 'UCS2'
  2043. else:
  2044. return ''
  2045. class PythonCodeExecutor(object):
  2046. Py_single_input = 256
  2047. Py_file_input = 257
  2048. Py_eval_input = 258
  2049. def malloc(self, size):
  2050. chunk = (gdb.parse_and_eval("(void *) malloc((size_t) %d)" % size))
  2051. pointer = pointervalue(chunk)
  2052. if pointer == 0:
  2053. raise gdb.GdbError("No memory could be allocated in the inferior.")
  2054. return pointer
  2055. def alloc_string(self, string):
  2056. pointer = self.malloc(len(string))
  2057. get_selected_inferior().write_memory(pointer, string)
  2058. return pointer
  2059. def alloc_pystring(self, string):
  2060. stringp = self.alloc_string(string)
  2061. PyString_FromStringAndSize = 'PyString_FromStringAndSize'
  2062. try:
  2063. gdb.parse_and_eval(PyString_FromStringAndSize)
  2064. except RuntimeError:
  2065. # Python 3
  2066. PyString_FromStringAndSize = ('PyUnicode%s_FromStringAndSize' %
  2067. (get_inferior_unicode_postfix(),))
  2068. try:
  2069. result = gdb.parse_and_eval(
  2070. '(PyObject *) %s((char *) %d, (size_t) %d)' % (
  2071. PyString_FromStringAndSize, stringp, len(string)))
  2072. finally:
  2073. self.free(stringp)
  2074. pointer = pointervalue(result)
  2075. if pointer == 0:
  2076. raise gdb.GdbError("Unable to allocate Python string in "
  2077. "the inferior.")
  2078. return pointer
  2079. def free(self, pointer):
  2080. gdb.parse_and_eval("free((void *) %d)" % pointer)
  2081. def incref(self, pointer):
  2082. "Increment the reference count of a Python object in the inferior."
  2083. gdb.parse_and_eval('Py_IncRef((PyObject *) %d)' % pointer)
  2084. def xdecref(self, pointer):
  2085. "Decrement the reference count of a Python object in the inferior."
  2086. # Py_DecRef is like Py_XDECREF, but a function. So we don't have
  2087. # to check for NULL. This should also decref all our allocated
  2088. # Python strings.
  2089. gdb.parse_and_eval('Py_DecRef((PyObject *) %d)' % pointer)
  2090. def evalcode(self, code, input_type, global_dict=None, local_dict=None):
  2091. """
  2092. Evaluate python code `code` given as a string in the inferior and
  2093. return the result as a gdb.Value. Returns a new reference in the
  2094. inferior.
  2095. Of course, executing any code in the inferior may be dangerous and may
  2096. leave the debuggee in an unsafe state or terminate it altogether.
  2097. """
  2098. if '\0' in code:
  2099. raise gdb.GdbError("String contains NUL byte.")
  2100. code += '\0'
  2101. pointer = self.alloc_string(code)
  2102. globalsp = pointervalue(global_dict)
  2103. localsp = pointervalue(local_dict)
  2104. if globalsp == 0 or localsp == 0:
  2105. raise gdb.GdbError("Unable to obtain or create locals or globals.")
  2106. code = """
  2107. PyRun_String(
  2108. (char *) %(code)d,
  2109. (int) %(start)d,
  2110. (PyObject *) %(globals)s,
  2111. (PyObject *) %(locals)d)
  2112. """ % dict(code=pointer, start=input_type,
  2113. globals=globalsp, locals=localsp)
  2114. with FetchAndRestoreError():
  2115. try:
  2116. pyobject_return_value = gdb.parse_and_eval(code)
  2117. finally:
  2118. self.free(pointer)
  2119. return pyobject_return_value
  2120. class FetchAndRestoreError(PythonCodeExecutor):
  2121. """
  2122. Context manager that fetches the error indicator in the inferior and
  2123. restores it on exit.
  2124. """
  2125. def __init__(self):
  2126. self.sizeof_PyObjectPtr = gdb.lookup_type('PyObject').pointer().sizeof
  2127. self.pointer = self.malloc(self.sizeof_PyObjectPtr * 3)
  2128. type = self.pointer
  2129. value = self.pointer + self.sizeof_PyObjectPtr
  2130. traceback = self.pointer + self.sizeof_PyObjectPtr * 2
  2131. self.errstate = type, value, traceback
  2132. def __enter__(self):
  2133. gdb.parse_and_eval("PyErr_Fetch(%d, %d, %d)" % self.errstate)
  2134. def __exit__(self, *args):
  2135. if gdb.parse_and_eval("(int) PyErr_Occurred()"):
  2136. gdb.parse_and_eval("PyErr_Print()")
  2137. pyerr_restore = ("PyErr_Restore("
  2138. "(PyObject *) *%d,"
  2139. "(PyObject *) *%d,"
  2140. "(PyObject *) *%d)")
  2141. try:
  2142. gdb.parse_and_eval(pyerr_restore % self.errstate)
  2143. finally:
  2144. self.free(self.pointer)
  2145. class FixGdbCommand(gdb.Command):
  2146. def __init__(self, command, actual_command):
  2147. super(FixGdbCommand, self).__init__(command, gdb.COMMAND_DATA,
  2148. gdb.COMPLETE_NONE)
  2149. self.actual_command = actual_command
  2150. def fix_gdb(self):
  2151. """
  2152. It seems that invoking either 'cy exec' and 'py-exec' work perfectly
  2153. fine, but after this gdb's python API is entirely broken.
  2154. Maybe some uncleared exception value is still set?
  2155. sys.exc_clear() didn't help. A demonstration:
  2156. (gdb) cy exec 'hello'
  2157. 'hello'
  2158. (gdb) python gdb.execute('cont')
  2159. RuntimeError: Cannot convert value to int.
  2160. Error while executing Python code.
  2161. (gdb) python gdb.execute('cont')
  2162. [15148 refs]
  2163. Program exited normally.
  2164. """
  2165. warnings.filterwarnings('ignore', r'.*', RuntimeWarning,
  2166. re.escape(__name__))
  2167. try:
  2168. int(gdb.parse_and_eval("(void *) 0")) == 0
  2169. except RuntimeError:
  2170. pass
  2171. # warnings.resetwarnings()
  2172. def invoke(self, args, from_tty):
  2173. self.fix_gdb()
  2174. try:
  2175. gdb.execute('%s %s' % (self.actual_command, args))
  2176. except RuntimeError as e:
  2177. raise gdb.GdbError(str(e))
  2178. self.fix_gdb()
  2179. def _evalcode_python(executor, code, input_type):
  2180. """
  2181. Execute Python code in the most recent stack frame.
  2182. """
  2183. global_dict = gdb.parse_and_eval('PyEval_GetGlobals()')
  2184. local_dict = gdb.parse_and_eval('PyEval_GetLocals()')
  2185. if (pointervalue(global_dict) == 0 or pointervalue(local_dict) == 0):
  2186. raise gdb.GdbError("Unable to find the locals or globals of the "
  2187. "most recent Python function (relative to the "
  2188. "selected frame).")
  2189. return executor.evalcode(code, input_type, global_dict, local_dict)
  2190. class PyExec(gdb.Command):
  2191. def readcode(self, expr):
  2192. if expr:
  2193. return expr, PythonCodeExecutor.Py_single_input
  2194. else:
  2195. lines = []
  2196. while True:
  2197. try:
  2198. line = input('>')
  2199. except EOFError:
  2200. break
  2201. else:
  2202. if line.rstrip() == 'end':
  2203. break
  2204. lines.append(line)
  2205. return '\n'.join(lines), PythonCodeExecutor.Py_file_input
  2206. def invoke(self, expr, from_tty):
  2207. expr, input_type = self.readcode(expr)
  2208. executor = PythonCodeExecutor()
  2209. executor.xdecref(_evalcode_python(executor, input_type, global_dict, local_dict))
  2210. gdb.execute('set breakpoint pending on')
  2211. if hasattr(gdb, 'GdbError'):
  2212. # Wrap py-step and py-next in gdb defines to make them repeatable.
  2213. py_step = PyStep('-py-step', PythonInfo())
  2214. py_next = PyNext('-py-next', PythonInfo())
  2215. register_defines()
  2216. py_finish = PyFinish('py-finish', PythonInfo())
  2217. py_run = PyRun('py-run', PythonInfo())
  2218. py_cont = PyCont('py-cont', PythonInfo())
  2219. py_exec = FixGdbCommand('py-exec', '-py-exec')
  2220. _py_exec = PyExec("-py-exec", gdb.COMMAND_DATA, gdb.COMPLETE_NONE)
  2221. else:
  2222. warnings.warn("Use gdb 7.2 or higher to use the py-exec command.")