blob: b23a22e393827fa039aaf39965071f6160d77d0b [file] [log] [blame]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001#!/usr/bin/python
2'''
3From gdb 7 onwards, gdb's build can be configured --with-python, allowing gdb
4to be extended with Python code e.g. for library-specific data visualizations,
5such as for the C++ STL types. Documentation on this API can be seen at:
6http://sourceware.org/gdb/current/onlinedocs/gdb/Python-API.html
7
8
9This python module deals with the case when the process being debugged (the
10"inferior process" in gdb parlance) is itself python, or more specifically,
11linked against libpython. In this situation, almost every item of data is a
12(PyObject*), and having the debugger merely print their addresses is not very
13enlightening.
14
15This module embeds knowledge about the implementation details of libpython so
16that we can emit useful visualizations e.g. a string, a list, a dict, a frame
17giving file/line information and the state of local variables
18
19In particular, given a gdb.Value corresponding to a PyObject* in the inferior
20process, we can generate a "proxy value" within the gdb process. For example,
21given a PyObject* in the inferior process that is in fact a PyListObject*
Victor Stinner67df3a42010-04-21 13:53:05 +000022holding three PyObject* that turn out to be PyBytesObject* instances, we can
Martin v. Löwis5ae68102010-04-21 22:38:42 +000023generate a proxy value within the gdb process that is a list of bytes
24instances:
25 [b"foo", b"bar", b"baz"]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000026
27Doing so can be expensive for complicated graphs of objects, and could take
28some time, so we also have a "write_repr" method that writes a representation
29of the data to a file-like object. This allows us to stop the traversal by
30having the file-like object raise an exception if it gets too much data.
31
32With both "proxyval" and "write_repr" we keep track of the set of all addresses
33visited so far in the traversal, to avoid infinite recursion due to cycles in
34the graph of object references.
35
36We try to defer gdb.lookup_type() invocations for python types until as late as
37possible: for a dynamically linked python binary, when the process starts in
38the debugger, the libpython.so hasn't been dynamically loaded yet, so none of
39the type names are known to the debugger
40
41The module also extends gdb with some python-specific commands.
42'''
43from __future__ import with_statement
44import gdb
Victor Stinner150016f2010-05-19 23:04:56 +000045import locale
Georg Brandlb639c142010-07-14 08:54:40 +000046import sys
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000047
48# Look up the gdb.Type for some standard types:
49_type_char_ptr = gdb.lookup_type('char').pointer() # char*
50_type_unsigned_char_ptr = gdb.lookup_type('unsigned char').pointer() # unsigned char*
51_type_void_ptr = gdb.lookup_type('void').pointer() # void*
52_type_size_t = gdb.lookup_type('size_t')
53
54SIZEOF_VOID_P = _type_void_ptr.sizeof
55
56
57Py_TPFLAGS_HEAPTYPE = (1L << 9)
58
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000059Py_TPFLAGS_LONG_SUBCLASS = (1L << 24)
60Py_TPFLAGS_LIST_SUBCLASS = (1L << 25)
61Py_TPFLAGS_TUPLE_SUBCLASS = (1L << 26)
Martin v. Löwis5ae68102010-04-21 22:38:42 +000062Py_TPFLAGS_BYTES_SUBCLASS = (1L << 27)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000063Py_TPFLAGS_UNICODE_SUBCLASS = (1L << 28)
64Py_TPFLAGS_DICT_SUBCLASS = (1L << 29)
65Py_TPFLAGS_BASE_EXC_SUBCLASS = (1L << 30)
66Py_TPFLAGS_TYPE_SUBCLASS = (1L << 31)
67
68
69MAX_OUTPUT_LEN=1024
70
Martin v. Löwis5ae68102010-04-21 22:38:42 +000071hexdigits = "0123456789abcdef"
72
Victor Stinner150016f2010-05-19 23:04:56 +000073ENCODING = locale.getpreferredencoding()
Martin v. Löwis5ae68102010-04-21 22:38:42 +000074
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000075class NullPyObjectPtr(RuntimeError):
76 pass
77
78
79def safety_limit(val):
80 # Given a integer value from the process being debugged, limit it to some
81 # safety threshold so that arbitrary breakage within said process doesn't
82 # break the gdb process too much (e.g. sizes of iterations, sizes of lists)
83 return min(val, 1000)
84
85
86def safe_range(val):
87 # As per range, but don't trust the value too much: cap it to a safety
88 # threshold in case the data was corrupted
89 return xrange(safety_limit(val))
90
Victor Stinner0e5a41b2010-08-17 22:49:25 +000091def write_unicode(file, text):
92 # Write a byte or unicode string to file. Unicode strings are encoded to
93 # ENCODING encoding with 'backslashreplace' error handler to avoid
94 # UnicodeEncodeError.
95 if isinstance(text, unicode):
96 text = text.encode(ENCODING, 'backslashreplace')
97 file.write(text)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000098
99class StringTruncated(RuntimeError):
100 pass
101
102class TruncatedStringIO(object):
103 '''Similar to cStringIO, but can truncate the output by raising a
104 StringTruncated exception'''
105 def __init__(self, maxlen=None):
106 self._val = ''
107 self.maxlen = maxlen
108
109 def write(self, data):
110 if self.maxlen:
111 if len(data) + len(self._val) > self.maxlen:
112 # Truncation:
113 self._val += data[0:self.maxlen - len(self._val)]
114 raise StringTruncated()
115
116 self._val += data
117
118 def getvalue(self):
119 return self._val
120
121class PyObjectPtr(object):
122 """
123 Class wrapping a gdb.Value that's a either a (PyObject*) within the
Victor Stinner67df3a42010-04-21 13:53:05 +0000124 inferior process, or some subclass pointer e.g. (PyBytesObject*)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000125
126 There will be a subclass for every refined PyObject type that we care
127 about.
128
129 Note that at every stage the underlying pointer could be NULL, point
130 to corrupt data, etc; this is the debugger, after all.
131 """
132 _typename = 'PyObject'
133
134 def __init__(self, gdbval, cast_to=None):
135 if cast_to:
136 self._gdbval = gdbval.cast(cast_to)
137 else:
138 self._gdbval = gdbval
139
140 def field(self, name):
141 '''
142 Get the gdb.Value for the given field within the PyObject, coping with
143 some python 2 versus python 3 differences.
144
145 Various libpython types are defined using the "PyObject_HEAD" and
146 "PyObject_VAR_HEAD" macros.
147
148 In Python 2, this these are defined so that "ob_type" and (for a var
149 object) "ob_size" are fields of the type in question.
150
151 In Python 3, this is defined as an embedded PyVarObject type thus:
152 PyVarObject ob_base;
153 so that the "ob_size" field is located insize the "ob_base" field, and
154 the "ob_type" is most easily accessed by casting back to a (PyObject*).
155 '''
156 if self.is_null():
157 raise NullPyObjectPtr(self)
158
159 if name == 'ob_type':
160 pyo_ptr = self._gdbval.cast(PyObjectPtr.get_gdb_type())
161 return pyo_ptr.dereference()[name]
162
163 if name == 'ob_size':
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000164 pyo_ptr = self._gdbval.cast(PyVarObjectPtr.get_gdb_type())
165 return pyo_ptr.dereference()[name]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000166
167 # General case: look it up inside the object:
168 return self._gdbval.dereference()[name]
169
170 def pyop_field(self, name):
171 '''
172 Get a PyObjectPtr for the given PyObject* field within this PyObject,
173 coping with some python 2 versus python 3 differences.
174 '''
175 return PyObjectPtr.from_pyobject_ptr(self.field(name))
176
177 def write_field_repr(self, name, out, visited):
178 '''
179 Extract the PyObject* field named "name", and write its representation
180 to file-like object "out"
181 '''
182 field_obj = self.pyop_field(name)
183 field_obj.write_repr(out, visited)
184
185 def get_truncated_repr(self, maxlen):
186 '''
187 Get a repr-like string for the data, but truncate it at "maxlen" bytes
188 (ending the object graph traversal as soon as you do)
189 '''
190 out = TruncatedStringIO(maxlen)
191 try:
192 self.write_repr(out, set())
193 except StringTruncated:
194 # Truncation occurred:
195 return out.getvalue() + '...(truncated)'
196
197 # No truncation occurred:
198 return out.getvalue()
199
200 def type(self):
201 return PyTypeObjectPtr(self.field('ob_type'))
202
203 def is_null(self):
204 return 0 == long(self._gdbval)
205
206 def is_optimized_out(self):
207 '''
208 Is the value of the underlying PyObject* visible to the debugger?
209
210 This can vary with the precise version of the compiler used to build
211 Python, and the precise version of gdb.
212
213 See e.g. https://bugzilla.redhat.com/show_bug.cgi?id=556975 with
214 PyEval_EvalFrameEx's "f"
215 '''
216 return self._gdbval.is_optimized_out
217
218 def safe_tp_name(self):
219 try:
220 return self.type().field('tp_name').string()
221 except NullPyObjectPtr:
222 # NULL tp_name?
223 return 'unknown'
224 except RuntimeError:
225 # Can't even read the object at all?
226 return 'unknown'
227
228 def proxyval(self, visited):
229 '''
230 Scrape a value from the inferior process, and try to represent it
231 within the gdb process, whilst (hopefully) avoiding crashes when
232 the remote data is corrupt.
233
234 Derived classes will override this.
235
236 For example, a PyIntObject* with ob_ival 42 in the inferior process
237 should result in an int(42) in this process.
238
239 visited: a set of all gdb.Value pyobject pointers already visited
240 whilst generating this value (to guard against infinite recursion when
241 visiting object graphs with loops). Analogous to Py_ReprEnter and
242 Py_ReprLeave
243 '''
244
245 class FakeRepr(object):
246 """
247 Class representing a non-descript PyObject* value in the inferior
248 process for when we don't have a custom scraper, intended to have
249 a sane repr().
250 """
251
252 def __init__(self, tp_name, address):
253 self.tp_name = tp_name
254 self.address = address
255
256 def __repr__(self):
257 # For the NULL pointer, we have no way of knowing a type, so
258 # special-case it as per
259 # http://bugs.python.org/issue8032#msg100882
260 if self.address == 0:
261 return '0x0'
262 return '<%s at remote 0x%x>' % (self.tp_name, self.address)
263
264 return FakeRepr(self.safe_tp_name(),
265 long(self._gdbval))
266
267 def write_repr(self, out, visited):
268 '''
269 Write a string representation of the value scraped from the inferior
270 process to "out", a file-like object.
271 '''
272 # Default implementation: generate a proxy value and write its repr
273 # However, this could involve a lot of work for complicated objects,
274 # so for derived classes we specialize this
275 return out.write(repr(self.proxyval(visited)))
276
277 @classmethod
278 def subclass_from_type(cls, t):
279 '''
280 Given a PyTypeObjectPtr instance wrapping a gdb.Value that's a
281 (PyTypeObject*), determine the corresponding subclass of PyObjectPtr
282 to use
283
284 Ideally, we would look up the symbols for the global types, but that
285 isn't working yet:
286 (gdb) python print gdb.lookup_symbol('PyList_Type')[0].value
287 Traceback (most recent call last):
288 File "<string>", line 1, in <module>
289 NotImplementedError: Symbol type not yet supported in Python scripts.
290 Error while executing Python code.
291
292 For now, we use tp_flags, after doing some string comparisons on the
293 tp_name for some special-cases that don't seem to be visible through
294 flags
295 '''
296 try:
297 tp_name = t.field('tp_name').string()
298 tp_flags = int(t.field('tp_flags'))
299 except RuntimeError:
300 # Handle any kind of error e.g. NULL ptrs by simply using the base
301 # class
302 return cls
303
304 #print 'tp_flags = 0x%08x' % tp_flags
305 #print 'tp_name = %r' % tp_name
306
307 name_map = {'bool': PyBoolObjectPtr,
308 'classobj': PyClassObjectPtr,
309 'instance': PyInstanceObjectPtr,
310 'NoneType': PyNoneStructPtr,
311 'frame': PyFrameObjectPtr,
312 'set' : PySetObjectPtr,
313 'frozenset' : PySetObjectPtr,
314 'builtin_function_or_method' : PyCFunctionObjectPtr,
315 }
316 if tp_name in name_map:
317 return name_map[tp_name]
318
319 if tp_flags & Py_TPFLAGS_HEAPTYPE:
320 return HeapTypeObjectPtr
321
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000322 if tp_flags & Py_TPFLAGS_LONG_SUBCLASS:
323 return PyLongObjectPtr
324 if tp_flags & Py_TPFLAGS_LIST_SUBCLASS:
325 return PyListObjectPtr
326 if tp_flags & Py_TPFLAGS_TUPLE_SUBCLASS:
327 return PyTupleObjectPtr
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000328 if tp_flags & Py_TPFLAGS_BYTES_SUBCLASS:
Victor Stinner67df3a42010-04-21 13:53:05 +0000329 return PyBytesObjectPtr
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000330 if tp_flags & Py_TPFLAGS_UNICODE_SUBCLASS:
331 return PyUnicodeObjectPtr
332 if tp_flags & Py_TPFLAGS_DICT_SUBCLASS:
333 return PyDictObjectPtr
334 if tp_flags & Py_TPFLAGS_BASE_EXC_SUBCLASS:
335 return PyBaseExceptionObjectPtr
336 #if tp_flags & Py_TPFLAGS_TYPE_SUBCLASS:
337 # return PyTypeObjectPtr
338
339 # Use the base class:
340 return cls
341
342 @classmethod
343 def from_pyobject_ptr(cls, gdbval):
344 '''
345 Try to locate the appropriate derived class dynamically, and cast
346 the pointer accordingly.
347 '''
348 try:
349 p = PyObjectPtr(gdbval)
350 cls = cls.subclass_from_type(p.type())
351 return cls(gdbval, cast_to=cls.get_gdb_type())
352 except RuntimeError:
353 # Handle any kind of error e.g. NULL ptrs by simply using the base
354 # class
355 pass
356 return cls(gdbval)
357
358 @classmethod
359 def get_gdb_type(cls):
360 return gdb.lookup_type(cls._typename).pointer()
361
362 def as_address(self):
363 return long(self._gdbval)
364
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000365class PyVarObjectPtr(PyObjectPtr):
366 _typename = 'PyVarObject'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000367
368class ProxyAlreadyVisited(object):
369 '''
370 Placeholder proxy to use when protecting against infinite recursion due to
371 loops in the object graph.
372
373 Analogous to the values emitted by the users of Py_ReprEnter and Py_ReprLeave
374 '''
375 def __init__(self, rep):
376 self._rep = rep
377
378 def __repr__(self):
379 return self._rep
380
381
382def _write_instance_repr(out, visited, name, pyop_attrdict, address):
383 '''Shared code for use by old-style and new-style classes:
384 write a representation to file-like object "out"'''
385 out.write('<')
386 out.write(name)
387
388 # Write dictionary of instance attributes:
389 if isinstance(pyop_attrdict, PyDictObjectPtr):
390 out.write('(')
391 first = True
392 for pyop_arg, pyop_val in pyop_attrdict.iteritems():
393 if not first:
394 out.write(', ')
395 first = False
396 out.write(pyop_arg.proxyval(visited))
397 out.write('=')
398 pyop_val.write_repr(out, visited)
399 out.write(')')
400 out.write(' at remote 0x%x>' % address)
401
402
403class InstanceProxy(object):
404
405 def __init__(self, cl_name, attrdict, address):
406 self.cl_name = cl_name
407 self.attrdict = attrdict
408 self.address = address
409
410 def __repr__(self):
411 if isinstance(self.attrdict, dict):
412 kwargs = ', '.join(["%s=%r" % (arg, val)
413 for arg, val in self.attrdict.iteritems()])
414 return '<%s(%s) at remote 0x%x>' % (self.cl_name,
415 kwargs, self.address)
416 else:
417 return '<%s at remote 0x%x>' % (self.cl_name,
418 self.address)
419
420def _PyObject_VAR_SIZE(typeobj, nitems):
421 return ( ( typeobj.field('tp_basicsize') +
422 nitems * typeobj.field('tp_itemsize') +
423 (SIZEOF_VOID_P - 1)
424 ) & ~(SIZEOF_VOID_P - 1)
425 ).cast(_type_size_t)
426
427class HeapTypeObjectPtr(PyObjectPtr):
428 _typename = 'PyObject'
429
430 def get_attr_dict(self):
431 '''
432 Get the PyDictObject ptr representing the attribute dictionary
433 (or None if there's a problem)
434 '''
435 try:
436 typeobj = self.type()
437 dictoffset = int_from_int(typeobj.field('tp_dictoffset'))
438 if dictoffset != 0:
439 if dictoffset < 0:
440 type_PyVarObject_ptr = gdb.lookup_type('PyVarObject').pointer()
441 tsize = int_from_int(self._gdbval.cast(type_PyVarObject_ptr)['ob_size'])
442 if tsize < 0:
443 tsize = -tsize
444 size = _PyObject_VAR_SIZE(typeobj, tsize)
445 dictoffset += size
446 assert dictoffset > 0
447 assert dictoffset % SIZEOF_VOID_P == 0
448
449 dictptr = self._gdbval.cast(_type_char_ptr) + dictoffset
450 PyObjectPtrPtr = PyObjectPtr.get_gdb_type().pointer()
451 dictptr = dictptr.cast(PyObjectPtrPtr)
452 return PyObjectPtr.from_pyobject_ptr(dictptr.dereference())
453 except RuntimeError:
454 # Corrupt data somewhere; fail safe
455 pass
456
457 # Not found, or some kind of error:
458 return None
459
460 def proxyval(self, visited):
461 '''
462 Support for new-style classes.
463
464 Currently we just locate the dictionary using a transliteration to
465 python of _PyObject_GetDictPtr, ignoring descriptors
466 '''
467 # Guard against infinite loops:
468 if self.as_address() in visited:
469 return ProxyAlreadyVisited('<...>')
470 visited.add(self.as_address())
471
472 pyop_attr_dict = self.get_attr_dict()
473 if pyop_attr_dict:
474 attr_dict = pyop_attr_dict.proxyval(visited)
475 else:
476 attr_dict = {}
477 tp_name = self.safe_tp_name()
478
479 # New-style class:
480 return InstanceProxy(tp_name, attr_dict, long(self._gdbval))
481
482 def write_repr(self, out, visited):
483 # Guard against infinite loops:
484 if self.as_address() in visited:
485 out.write('<...>')
486 return
487 visited.add(self.as_address())
488
489 pyop_attrdict = self.get_attr_dict()
490 _write_instance_repr(out, visited,
491 self.safe_tp_name(), pyop_attrdict, self.as_address())
492
493class ProxyException(Exception):
494 def __init__(self, tp_name, args):
495 self.tp_name = tp_name
496 self.args = args
497
498 def __repr__(self):
499 return '%s%r' % (self.tp_name, self.args)
500
501class PyBaseExceptionObjectPtr(PyObjectPtr):
502 """
503 Class wrapping a gdb.Value that's a PyBaseExceptionObject* i.e. an exception
504 within the process being debugged.
505 """
506 _typename = 'PyBaseExceptionObject'
507
508 def proxyval(self, visited):
509 # Guard against infinite loops:
510 if self.as_address() in visited:
511 return ProxyAlreadyVisited('(...)')
512 visited.add(self.as_address())
513 arg_proxy = self.pyop_field('args').proxyval(visited)
514 return ProxyException(self.safe_tp_name(),
515 arg_proxy)
516
517 def write_repr(self, out, visited):
518 # Guard against infinite loops:
519 if self.as_address() in visited:
520 out.write('(...)')
521 return
522 visited.add(self.as_address())
523
524 out.write(self.safe_tp_name())
525 self.write_field_repr('args', out, visited)
526
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000527class PyClassObjectPtr(PyObjectPtr):
528 """
529 Class wrapping a gdb.Value that's a PyClassObject* i.e. a <classobj>
530 instance within the process being debugged.
531 """
532 _typename = 'PyClassObject'
533
534
535class BuiltInFunctionProxy(object):
536 def __init__(self, ml_name):
537 self.ml_name = ml_name
538
539 def __repr__(self):
540 return "<built-in function %s>" % self.ml_name
541
542class BuiltInMethodProxy(object):
543 def __init__(self, ml_name, pyop_m_self):
544 self.ml_name = ml_name
545 self.pyop_m_self = pyop_m_self
546
547 def __repr__(self):
548 return ('<built-in method %s of %s object at remote 0x%x>'
549 % (self.ml_name,
550 self.pyop_m_self.safe_tp_name(),
551 self.pyop_m_self.as_address())
552 )
553
554class PyCFunctionObjectPtr(PyObjectPtr):
555 """
556 Class wrapping a gdb.Value that's a PyCFunctionObject*
557 (see Include/methodobject.h and Objects/methodobject.c)
558 """
559 _typename = 'PyCFunctionObject'
560
561 def proxyval(self, visited):
562 m_ml = self.field('m_ml') # m_ml is a (PyMethodDef*)
563 ml_name = m_ml['ml_name'].string()
564
565 pyop_m_self = self.pyop_field('m_self')
566 if pyop_m_self.is_null():
567 return BuiltInFunctionProxy(ml_name)
568 else:
569 return BuiltInMethodProxy(ml_name, pyop_m_self)
570
571
572class PyCodeObjectPtr(PyObjectPtr):
573 """
574 Class wrapping a gdb.Value that's a PyCodeObject* i.e. a <code> instance
575 within the process being debugged.
576 """
577 _typename = 'PyCodeObject'
578
579 def addr2line(self, addrq):
580 '''
581 Get the line number for a given bytecode offset
582
583 Analogous to PyCode_Addr2Line; translated from pseudocode in
584 Objects/lnotab_notes.txt
585 '''
586 co_lnotab = self.pyop_field('co_lnotab').proxyval(set())
587
588 # Initialize lineno to co_firstlineno as per PyCode_Addr2Line
589 # not 0, as lnotab_notes.txt has it:
590 lineno = int_from_int(self.field('co_firstlineno'))
591
592 addr = 0
593 for addr_incr, line_incr in zip(co_lnotab[::2], co_lnotab[1::2]):
594 addr += ord(addr_incr)
595 if addr > addrq:
596 return lineno
597 lineno += ord(line_incr)
598 return lineno
599
600
601class PyDictObjectPtr(PyObjectPtr):
602 """
603 Class wrapping a gdb.Value that's a PyDictObject* i.e. a dict instance
604 within the process being debugged.
605 """
606 _typename = 'PyDictObject'
607
608 def iteritems(self):
609 '''
610 Yields a sequence of (PyObjectPtr key, PyObjectPtr value) pairs,
611 analagous to dict.iteritems()
612 '''
613 for i in safe_range(self.field('ma_mask') + 1):
614 ep = self.field('ma_table') + i
615 pyop_value = PyObjectPtr.from_pyobject_ptr(ep['me_value'])
616 if not pyop_value.is_null():
617 pyop_key = PyObjectPtr.from_pyobject_ptr(ep['me_key'])
618 yield (pyop_key, pyop_value)
619
620 def proxyval(self, visited):
621 # Guard against infinite loops:
622 if self.as_address() in visited:
623 return ProxyAlreadyVisited('{...}')
624 visited.add(self.as_address())
625
626 result = {}
627 for pyop_key, pyop_value in self.iteritems():
628 proxy_key = pyop_key.proxyval(visited)
629 proxy_value = pyop_value.proxyval(visited)
630 result[proxy_key] = proxy_value
631 return result
632
633 def write_repr(self, out, visited):
634 # Guard against infinite loops:
635 if self.as_address() in visited:
636 out.write('{...}')
637 return
638 visited.add(self.as_address())
639
640 out.write('{')
641 first = True
642 for pyop_key, pyop_value in self.iteritems():
643 if not first:
644 out.write(', ')
645 first = False
646 pyop_key.write_repr(out, visited)
647 out.write(': ')
648 pyop_value.write_repr(out, visited)
649 out.write('}')
650
651class PyInstanceObjectPtr(PyObjectPtr):
652 _typename = 'PyInstanceObject'
653
654 def proxyval(self, visited):
655 # Guard against infinite loops:
656 if self.as_address() in visited:
657 return ProxyAlreadyVisited('<...>')
658 visited.add(self.as_address())
659
660 # Get name of class:
661 in_class = self.pyop_field('in_class')
662 cl_name = in_class.pyop_field('cl_name').proxyval(visited)
663
664 # Get dictionary of instance attributes:
665 in_dict = self.pyop_field('in_dict').proxyval(visited)
666
667 # Old-style class:
668 return InstanceProxy(cl_name, in_dict, long(self._gdbval))
669
670 def write_repr(self, out, visited):
671 # Guard against infinite loops:
672 if self.as_address() in visited:
673 out.write('<...>')
674 return
675 visited.add(self.as_address())
676
677 # Old-style class:
678
679 # Get name of class:
680 in_class = self.pyop_field('in_class')
681 cl_name = in_class.pyop_field('cl_name').proxyval(visited)
682
683 # Get dictionary of instance attributes:
684 pyop_in_dict = self.pyop_field('in_dict')
685
686 _write_instance_repr(out, visited,
687 cl_name, pyop_in_dict, self.as_address())
688
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000689class PyListObjectPtr(PyObjectPtr):
690 _typename = 'PyListObject'
691
692 def __getitem__(self, i):
693 # Get the gdb.Value for the (PyObject*) with the given index:
694 field_ob_item = self.field('ob_item')
695 return field_ob_item[i]
696
697 def proxyval(self, visited):
698 # Guard against infinite loops:
699 if self.as_address() in visited:
700 return ProxyAlreadyVisited('[...]')
701 visited.add(self.as_address())
702
703 result = [PyObjectPtr.from_pyobject_ptr(self[i]).proxyval(visited)
704 for i in safe_range(int_from_int(self.field('ob_size')))]
705 return result
706
707 def write_repr(self, out, visited):
708 # Guard against infinite loops:
709 if self.as_address() in visited:
710 out.write('[...]')
711 return
712 visited.add(self.as_address())
713
714 out.write('[')
715 for i in safe_range(int_from_int(self.field('ob_size'))):
716 if i > 0:
717 out.write(', ')
718 element = PyObjectPtr.from_pyobject_ptr(self[i])
719 element.write_repr(out, visited)
720 out.write(']')
721
722class PyLongObjectPtr(PyObjectPtr):
723 _typename = 'PyLongObject'
724
725 def proxyval(self, visited):
726 '''
727 Python's Include/longobjrep.h has this declaration:
728 struct _longobject {
729 PyObject_VAR_HEAD
730 digit ob_digit[1];
731 };
732
733 with this description:
734 The absolute value of a number is equal to
735 SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
736 Negative numbers are represented with ob_size < 0;
737 zero is represented by ob_size == 0.
738
739 where SHIFT can be either:
740 #define PyLong_SHIFT 30
741 #define PyLong_SHIFT 15
742 '''
743 ob_size = long(self.field('ob_size'))
744 if ob_size == 0:
745 return 0L
746
747 ob_digit = self.field('ob_digit')
748
749 if gdb.lookup_type('digit').sizeof == 2:
750 SHIFT = 15L
751 else:
752 SHIFT = 30L
753
754 digits = [long(ob_digit[i]) * 2**(SHIFT*i)
755 for i in safe_range(abs(ob_size))]
756 result = sum(digits)
757 if ob_size < 0:
758 result = -result
759 return result
760
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000761 def write_repr(self, out, visited):
762 # Write this out as a Python 3 int literal, i.e. without the "L" suffix
763 proxy = self.proxyval(visited)
764 out.write("%s" % proxy)
765
766
767class PyBoolObjectPtr(PyLongObjectPtr):
768 """
769 Class wrapping a gdb.Value that's a PyBoolObject* i.e. one of the two
770 <bool> instances (Py_True/Py_False) within the process being debugged.
771 """
772 def proxyval(self, visited):
773 if PyLongObjectPtr.proxyval(self, visited):
774 return True
775 else:
776 return False
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000777
778class PyNoneStructPtr(PyObjectPtr):
779 """
780 Class wrapping a gdb.Value that's a PyObject* pointing to the
781 singleton (we hope) _Py_NoneStruct with ob_type PyNone_Type
782 """
783 _typename = 'PyObject'
784
785 def proxyval(self, visited):
786 return None
787
788
789class PyFrameObjectPtr(PyObjectPtr):
790 _typename = 'PyFrameObject'
791
792 def __init__(self, gdbval, cast_to):
793 PyObjectPtr.__init__(self, gdbval, cast_to)
794
795 if not self.is_optimized_out():
796 self.co = PyCodeObjectPtr.from_pyobject_ptr(self.field('f_code'))
797 self.co_name = self.co.pyop_field('co_name')
798 self.co_filename = self.co.pyop_field('co_filename')
799
800 self.f_lineno = int_from_int(self.field('f_lineno'))
801 self.f_lasti = int_from_int(self.field('f_lasti'))
802 self.co_nlocals = int_from_int(self.co.field('co_nlocals'))
803 self.co_varnames = PyTupleObjectPtr.from_pyobject_ptr(self.co.field('co_varnames'))
804
805 def iter_locals(self):
806 '''
807 Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
808 the local variables of this frame
809 '''
810 if self.is_optimized_out():
811 return
812
813 f_localsplus = self.field('f_localsplus')
814 for i in safe_range(self.co_nlocals):
815 pyop_value = PyObjectPtr.from_pyobject_ptr(f_localsplus[i])
816 if not pyop_value.is_null():
817 pyop_name = PyObjectPtr.from_pyobject_ptr(self.co_varnames[i])
818 yield (pyop_name, pyop_value)
819
820 def iter_globals(self):
821 '''
822 Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
823 the global variables of this frame
824 '''
825 if self.is_optimized_out():
826 return
827
828 pyop_globals = self.pyop_field('f_globals')
829 return pyop_globals.iteritems()
830
831 def iter_builtins(self):
832 '''
833 Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
834 the builtin variables
835 '''
836 if self.is_optimized_out():
837 return
838
839 pyop_builtins = self.pyop_field('f_builtins')
840 return pyop_builtins.iteritems()
841
842 def get_var_by_name(self, name):
843 '''
844 Look for the named local variable, returning a (PyObjectPtr, scope) pair
845 where scope is a string 'local', 'global', 'builtin'
846
847 If not found, return (None, None)
848 '''
849 for pyop_name, pyop_value in self.iter_locals():
850 if name == pyop_name.proxyval(set()):
851 return pyop_value, 'local'
852 for pyop_name, pyop_value in self.iter_globals():
853 if name == pyop_name.proxyval(set()):
854 return pyop_value, 'global'
855 for pyop_name, pyop_value in self.iter_builtins():
856 if name == pyop_name.proxyval(set()):
857 return pyop_value, 'builtin'
858 return None, None
859
860 def filename(self):
861 '''Get the path of the current Python source file, as a string'''
862 if self.is_optimized_out():
863 return '(frame information optimized out)'
864 return self.co_filename.proxyval(set())
865
866 def current_line_num(self):
867 '''Get current line number as an integer (1-based)
868
869 Translated from PyFrame_GetLineNumber and PyCode_Addr2Line
870
871 See Objects/lnotab_notes.txt
872 '''
873 if self.is_optimized_out():
874 return None
875 f_trace = self.field('f_trace')
876 if long(f_trace) != 0:
877 # we have a non-NULL f_trace:
878 return self.f_lineno
879 else:
880 #try:
881 return self.co.addr2line(self.f_lasti)
882 #except ValueError:
883 # return self.f_lineno
884
885 def current_line(self):
886 '''Get the text of the current source line as a string, with a trailing
887 newline character'''
888 if self.is_optimized_out():
889 return '(frame information optimized out)'
890 with open(self.filename(), 'r') as f:
891 all_lines = f.readlines()
892 # Convert from 1-based current_line_num to 0-based list offset:
893 return all_lines[self.current_line_num()-1]
894
895 def write_repr(self, out, visited):
896 if self.is_optimized_out():
897 out.write('(frame information optimized out)')
898 return
899 out.write('Frame 0x%x, for file %s, line %i, in %s ('
900 % (self.as_address(),
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000901 self.co_filename.proxyval(visited),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000902 self.current_line_num(),
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000903 self.co_name.proxyval(visited)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000904 first = True
905 for pyop_name, pyop_value in self.iter_locals():
906 if not first:
907 out.write(', ')
908 first = False
909
910 out.write(pyop_name.proxyval(visited))
911 out.write('=')
912 pyop_value.write_repr(out, visited)
913
914 out.write(')')
915
916class PySetObjectPtr(PyObjectPtr):
917 _typename = 'PySetObject'
918
919 def proxyval(self, visited):
920 # Guard against infinite loops:
921 if self.as_address() in visited:
922 return ProxyAlreadyVisited('%s(...)' % self.safe_tp_name())
923 visited.add(self.as_address())
924
925 members = []
926 table = self.field('table')
927 for i in safe_range(self.field('mask')+1):
928 setentry = table[i]
929 key = setentry['key']
930 if key != 0:
931 key_proxy = PyObjectPtr.from_pyobject_ptr(key).proxyval(visited)
932 if key_proxy != '<dummy key>':
933 members.append(key_proxy)
934 if self.safe_tp_name() == 'frozenset':
935 return frozenset(members)
936 else:
937 return set(members)
938
939 def write_repr(self, out, visited):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000940 # Emulate Python 3's set_repr
941 tp_name = self.safe_tp_name()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000942
943 # Guard against infinite loops:
944 if self.as_address() in visited:
945 out.write('(...)')
946 return
947 visited.add(self.as_address())
948
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000949 # Python 3's set_repr special-cases the empty set:
950 if not self.field('used'):
951 out.write(tp_name)
952 out.write('()')
953 return
954
955 # Python 3 uses {} for set literals:
956 if tp_name != 'set':
957 out.write(tp_name)
958 out.write('(')
959
960 out.write('{')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000961 first = True
962 table = self.field('table')
963 for i in safe_range(self.field('mask')+1):
964 setentry = table[i]
965 key = setentry['key']
966 if key != 0:
967 pyop_key = PyObjectPtr.from_pyobject_ptr(key)
968 key_proxy = pyop_key.proxyval(visited) # FIXME!
969 if key_proxy != '<dummy key>':
970 if not first:
971 out.write(', ')
972 first = False
973 pyop_key.write_repr(out, visited)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000974 out.write('}')
975
976 if tp_name != 'set':
977 out.write(')')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000978
979
Victor Stinner67df3a42010-04-21 13:53:05 +0000980class PyBytesObjectPtr(PyObjectPtr):
981 _typename = 'PyBytesObject'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000982
983 def __str__(self):
984 field_ob_size = self.field('ob_size')
985 field_ob_sval = self.field('ob_sval')
986 char_ptr = field_ob_sval.address.cast(_type_unsigned_char_ptr)
987 return ''.join([chr(char_ptr[i]) for i in safe_range(field_ob_size)])
988
989 def proxyval(self, visited):
990 return str(self)
991
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000992 def write_repr(self, out, visited):
993 # Write this out as a Python 3 bytes literal, i.e. with a "b" prefix
994
995 # Get a PyStringObject* within the Python 2 gdb process:
996 proxy = self.proxyval(visited)
997
998 # Transliteration of Python 3's Objects/bytesobject.c:PyBytes_Repr
999 # to Python 2 code:
1000 quote = "'"
1001 if "'" in proxy and not '"' in proxy:
1002 quote = '"'
1003 out.write('b')
1004 out.write(quote)
1005 for byte in proxy:
1006 if byte == quote or byte == '\\':
1007 out.write('\\')
1008 out.write(byte)
1009 elif byte == '\t':
1010 out.write('\\t')
1011 elif byte == '\n':
1012 out.write('\\n')
1013 elif byte == '\r':
1014 out.write('\\r')
1015 elif byte < ' ' or ord(byte) >= 0x7f:
1016 out.write('\\x')
1017 out.write(hexdigits[(ord(byte) & 0xf0) >> 4])
1018 out.write(hexdigits[ord(byte) & 0xf])
1019 else:
1020 out.write(byte)
1021 out.write(quote)
1022
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001023class PyTupleObjectPtr(PyObjectPtr):
1024 _typename = 'PyTupleObject'
1025
1026 def __getitem__(self, i):
1027 # Get the gdb.Value for the (PyObject*) with the given index:
1028 field_ob_item = self.field('ob_item')
1029 return field_ob_item[i]
1030
1031 def proxyval(self, visited):
1032 # Guard against infinite loops:
1033 if self.as_address() in visited:
1034 return ProxyAlreadyVisited('(...)')
1035 visited.add(self.as_address())
1036
1037 result = tuple([PyObjectPtr.from_pyobject_ptr(self[i]).proxyval(visited)
1038 for i in safe_range(int_from_int(self.field('ob_size')))])
1039 return result
1040
1041 def write_repr(self, out, visited):
1042 # Guard against infinite loops:
1043 if self.as_address() in visited:
1044 out.write('(...)')
1045 return
1046 visited.add(self.as_address())
1047
1048 out.write('(')
1049 for i in safe_range(int_from_int(self.field('ob_size'))):
1050 if i > 0:
1051 out.write(', ')
1052 element = PyObjectPtr.from_pyobject_ptr(self[i])
1053 element.write_repr(out, visited)
1054 if self.field('ob_size') == 1:
1055 out.write(',)')
1056 else:
1057 out.write(')')
1058
1059class PyTypeObjectPtr(PyObjectPtr):
1060 _typename = 'PyTypeObject'
1061
1062
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001063def _unichr_is_printable(char):
1064 # Logic adapted from Python 3's Tools/unicode/makeunicodedata.py
1065 if char == u" ":
1066 return True
1067 import unicodedata
1068 return unicodedata.category(char)[0] not in ("C", "Z")
1069
1070
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001071class PyUnicodeObjectPtr(PyObjectPtr):
1072 _typename = 'PyUnicodeObject'
1073
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001074 def char_width(self):
1075 _type_Py_UNICODE = gdb.lookup_type('Py_UNICODE')
1076 return _type_Py_UNICODE.sizeof
1077
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001078 def proxyval(self, visited):
1079 # From unicodeobject.h:
1080 # Py_ssize_t length; /* Length of raw Unicode data in buffer */
1081 # Py_UNICODE *str; /* Raw Unicode buffer */
1082 field_length = long(self.field('length'))
1083 field_str = self.field('str')
1084
1085 # Gather a list of ints from the Py_UNICODE array; these are either
1086 # UCS-2 or UCS-4 code points:
1087 Py_UNICODEs = [int(field_str[i]) for i in safe_range(field_length)]
1088
1089 # Convert the int code points to unicode characters, and generate a
1090 # local unicode instance:
1091 result = u''.join([unichr(ucs) for ucs in Py_UNICODEs])
1092 return result
1093
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001094 def write_repr(self, out, visited):
1095 # Write this out as a Python 3 str literal, i.e. without a "u" prefix
1096
1097 # Get a PyUnicodeObject* within the Python 2 gdb process:
1098 proxy = self.proxyval(visited)
1099
1100 # Transliteration of Python 3's Object/unicodeobject.c:unicode_repr
1101 # to Python 2:
1102 if "'" in proxy and '"' not in proxy:
1103 quote = '"'
1104 else:
1105 quote = "'"
1106 out.write(quote)
1107
1108 i = 0
1109 while i < len(proxy):
1110 ch = proxy[i]
1111 i += 1
1112
1113 # Escape quotes and backslashes
1114 if ch == quote or ch == '\\':
1115 out.write('\\')
1116 out.write(ch)
1117
1118 # Map special whitespace to '\t', \n', '\r'
1119 elif ch == '\t':
1120 out.write('\\t')
1121 elif ch == '\n':
1122 out.write('\\n')
1123 elif ch == '\r':
1124 out.write('\\r')
1125
1126 # Map non-printable US ASCII to '\xhh' */
1127 elif ch < ' ' or ch == 0x7F:
1128 out.write('\\x')
1129 out.write(hexdigits[(ord(ch) >> 4) & 0x000F])
1130 out.write(hexdigits[ord(ch) & 0x000F])
1131
1132 # Copy ASCII characters as-is
1133 elif ord(ch) < 0x7F:
1134 out.write(ch)
1135
1136 # Non-ASCII characters
1137 else:
Victor Stinner150016f2010-05-19 23:04:56 +00001138 ucs = ch
1139 orig_ucs = None
1140 if self.char_width() == 2:
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001141 # Get code point from surrogate pair
Victor Stinner150016f2010-05-19 23:04:56 +00001142 if (i < len(proxy)
1143 and 0xD800 <= ord(ch) < 0xDC00 \
1144 and 0xDC00 <= ord(proxy[i]) <= 0xDFFF):
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001145 ch2 = proxy[i]
Victor Stinner150016f2010-05-19 23:04:56 +00001146 code = (ord(ch) & 0x03FF) << 10
1147 code |= ord(ch2) & 0x03FF
1148 code += 0x00010000
1149 orig_ucs = ucs
1150 ucs = unichr(code)
1151 i += 1
1152 else:
1153 ch2 = None
1154
1155 printable = _unichr_is_printable(ucs)
1156 if printable:
1157 try:
1158 ucs.encode(ENCODING)
1159 except UnicodeEncodeError:
1160 printable = False
1161 if orig_ucs is not None:
1162 ucs = orig_ucs
1163 i -= 1
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001164
1165 # Map Unicode whitespace and control characters
1166 # (categories Z* and C* except ASCII space)
Victor Stinner150016f2010-05-19 23:04:56 +00001167 if not printable:
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001168 # Unfortuately, Python 2's unicode type doesn't seem
1169 # to expose the "isprintable" method
Victor Stinner150016f2010-05-19 23:04:56 +00001170 code = ord(ucs)
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001171
1172 # Map 8-bit characters to '\\xhh'
Victor Stinner150016f2010-05-19 23:04:56 +00001173 if code <= 0xff:
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001174 out.write('\\x')
Victor Stinner150016f2010-05-19 23:04:56 +00001175 out.write(hexdigits[(code >> 4) & 0x000F])
1176 out.write(hexdigits[code & 0x000F])
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001177 # Map 21-bit characters to '\U00xxxxxx'
Victor Stinner150016f2010-05-19 23:04:56 +00001178 elif code >= 0x10000:
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001179 out.write('\\U')
Victor Stinner150016f2010-05-19 23:04:56 +00001180 out.write(hexdigits[(code >> 28) & 0x0000000F])
1181 out.write(hexdigits[(code >> 24) & 0x0000000F])
1182 out.write(hexdigits[(code >> 20) & 0x0000000F])
1183 out.write(hexdigits[(code >> 16) & 0x0000000F])
1184 out.write(hexdigits[(code >> 12) & 0x0000000F])
1185 out.write(hexdigits[(code >> 8) & 0x0000000F])
1186 out.write(hexdigits[(code >> 4) & 0x0000000F])
1187 out.write(hexdigits[code & 0x0000000F])
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001188 # Map 16-bit characters to '\uxxxx'
1189 else:
1190 out.write('\\u')
Victor Stinner150016f2010-05-19 23:04:56 +00001191 out.write(hexdigits[(code >> 12) & 0x000F])
1192 out.write(hexdigits[(code >> 8) & 0x000F])
1193 out.write(hexdigits[(code >> 4) & 0x000F])
1194 out.write(hexdigits[code & 0x000F])
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001195 else:
1196 # Copy characters as-is
1197 out.write(ch)
Victor Stinner150016f2010-05-19 23:04:56 +00001198 if self.char_width() == 2 and (ch2 is not None):
1199 out.write(ch2)
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001200
1201 out.write(quote)
1202
1203
1204
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001205
1206def int_from_int(gdbval):
1207 return int(str(gdbval))
1208
1209
1210def stringify(val):
1211 # TODO: repr() puts everything on one line; pformat can be nicer, but
1212 # can lead to v.long results; this function isolates the choice
1213 if True:
1214 return repr(val)
1215 else:
1216 from pprint import pformat
1217 return pformat(val)
1218
1219
1220class PyObjectPtrPrinter:
1221 "Prints a (PyObject*)"
1222
1223 def __init__ (self, gdbval):
1224 self.gdbval = gdbval
1225
1226 def to_string (self):
1227 pyop = PyObjectPtr.from_pyobject_ptr(self.gdbval)
1228 if True:
1229 return pyop.get_truncated_repr(MAX_OUTPUT_LEN)
1230 else:
1231 # Generate full proxy value then stringify it.
1232 # Doing so could be expensive
1233 proxyval = pyop.proxyval(set())
1234 return stringify(proxyval)
1235
1236def pretty_printer_lookup(gdbval):
1237 type = gdbval.type.unqualified()
1238 if type.code == gdb.TYPE_CODE_PTR:
1239 type = type.target().unqualified()
1240 t = str(type)
Martin v. Löwis5ae68102010-04-21 22:38:42 +00001241 if t in ("PyObject", "PyFrameObject", "PyUnicodeObject"):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001242 return PyObjectPtrPrinter(gdbval)
1243
1244"""
1245During development, I've been manually invoking the code in this way:
1246(gdb) python
1247
1248import sys
1249sys.path.append('/home/david/coding/python-gdb')
1250import libpython
1251end
1252
1253then reloading it after each edit like this:
1254(gdb) python reload(libpython)
1255
1256The following code should ensure that the prettyprinter is registered
1257if the code is autoloaded by gdb when visiting libpython.so, provided
1258that this python file is installed to the same path as the library (or its
1259.debug file) plus a "-gdb.py" suffix, e.g:
1260 /usr/lib/libpython2.6.so.1.0-gdb.py
1261 /usr/lib/debug/usr/lib/libpython2.6.so.1.0.debug-gdb.py
1262"""
1263def register (obj):
1264 if obj == None:
1265 obj = gdb
1266
1267 # Wire up the pretty-printer
1268 obj.pretty_printers.append(pretty_printer_lookup)
1269
1270register (gdb.current_objfile ())
1271
1272
Martin v. Löwis5226fd62010-04-21 06:05:58 +00001273
1274# Unfortunately, the exact API exposed by the gdb module varies somewhat
1275# from build to build
1276# See http://bugs.python.org/issue8279?#msg102276
1277
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001278class Frame(object):
1279 '''
1280 Wrapper for gdb.Frame, adding various methods
1281 '''
1282 def __init__(self, gdbframe):
1283 self._gdbframe = gdbframe
1284
1285 def older(self):
1286 older = self._gdbframe.older()
1287 if older:
1288 return Frame(older)
1289 else:
1290 return None
1291
1292 def newer(self):
1293 newer = self._gdbframe.newer()
1294 if newer:
1295 return Frame(newer)
1296 else:
1297 return None
1298
1299 def select(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +00001300 '''If supported, select this frame and return True; return False if unsupported
1301
1302 Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
1303 onwards, but absent on Ubuntu buildbot'''
1304 if not hasattr(self._gdbframe, 'select'):
1305 print ('Unable to select frame: '
1306 'this build of gdb does not expose a gdb.Frame.select method')
1307 return False
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001308 self._gdbframe.select()
Martin v. Löwis5226fd62010-04-21 06:05:58 +00001309 return True
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001310
1311 def get_index(self):
1312 '''Calculate index of frame, starting at 0 for the newest frame within
1313 this thread'''
1314 index = 0
1315 # Go down until you reach the newest frame:
1316 iter_frame = self
1317 while iter_frame.newer():
1318 index += 1
1319 iter_frame = iter_frame.newer()
1320 return index
1321
1322 def is_evalframeex(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +00001323 '''Is this a PyEval_EvalFrameEx frame?'''
Victor Stinner50eb60e2010-04-20 22:32:07 +00001324 if self._gdbframe.name() == 'PyEval_EvalFrameEx':
1325 '''
1326 I believe we also need to filter on the inline
1327 struct frame_id.inline_depth, only regarding frames with
1328 an inline depth of 0 as actually being this function
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001329
Victor Stinner50eb60e2010-04-20 22:32:07 +00001330 So we reject those with type gdb.INLINE_FRAME
1331 '''
1332 if self._gdbframe.type() == gdb.NORMAL_FRAME:
1333 # We have a PyEval_EvalFrameEx frame:
1334 return True
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001335
1336 return False
1337
1338 def get_pyop(self):
1339 try:
1340 f = self._gdbframe.read_var('f')
1341 return PyFrameObjectPtr.from_pyobject_ptr(f)
1342 except ValueError:
1343 return None
1344
1345 @classmethod
1346 def get_selected_frame(cls):
1347 _gdbframe = gdb.selected_frame()
1348 if _gdbframe:
1349 return Frame(_gdbframe)
1350 return None
1351
1352 @classmethod
1353 def get_selected_python_frame(cls):
1354 '''Try to obtain the Frame for the python code in the selected frame,
1355 or None'''
1356 frame = cls.get_selected_frame()
1357
1358 while frame:
1359 if frame.is_evalframeex():
1360 return frame
1361 frame = frame.older()
1362
1363 # Not found:
1364 return None
1365
1366 def print_summary(self):
1367 if self.is_evalframeex():
1368 pyop = self.get_pyop()
1369 if pyop:
Victor Stinner0e5a41b2010-08-17 22:49:25 +00001370 line = pyop.get_truncated_repr(MAX_OUTPUT_LEN)
1371 write_unicode(sys.stdout, '#%i %s\n' % (self.get_index(), line))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001372 sys.stdout.write(pyop.current_line())
1373 else:
1374 sys.stdout.write('#%i (unable to read python frame information)\n' % self.get_index())
1375 else:
1376 sys.stdout.write('#%i\n' % self.get_index())
1377
1378class PyList(gdb.Command):
1379 '''List the current Python source code, if any
1380
1381 Use
1382 py-list START
1383 to list at a different line number within the python source.
1384
1385 Use
1386 py-list START, END
1387 to list a specific range of lines within the python source.
1388 '''
1389
1390 def __init__(self):
1391 gdb.Command.__init__ (self,
1392 "py-list",
1393 gdb.COMMAND_FILES,
1394 gdb.COMPLETE_NONE)
1395
1396
1397 def invoke(self, args, from_tty):
1398 import re
1399
1400 start = None
1401 end = None
1402
1403 m = re.match(r'\s*(\d+)\s*', args)
1404 if m:
1405 start = int(m.group(0))
1406 end = start + 10
1407
1408 m = re.match(r'\s*(\d+)\s*,\s*(\d+)\s*', args)
1409 if m:
1410 start, end = map(int, m.groups())
1411
1412 frame = Frame.get_selected_python_frame()
1413 if not frame:
1414 print 'Unable to locate python frame'
1415 return
1416
1417 pyop = frame.get_pyop()
1418 if not pyop:
1419 print 'Unable to read information on python frame'
1420 return
1421
1422 filename = pyop.filename()
1423 lineno = pyop.current_line_num()
1424
1425 if start is None:
1426 start = lineno - 5
1427 end = lineno + 5
1428
1429 if start<1:
1430 start = 1
1431
1432 with open(filename, 'r') as f:
1433 all_lines = f.readlines()
1434 # start and end are 1-based, all_lines is 0-based;
1435 # so [start-1:end] as a python slice gives us [start, end] as a
1436 # closed interval
1437 for i, line in enumerate(all_lines[start-1:end]):
1438 linestr = str(i+start)
1439 # Highlight current line:
1440 if i + start == lineno:
1441 linestr = '>' + linestr
1442 sys.stdout.write('%4s %s' % (linestr, line))
1443
1444
1445# ...and register the command:
1446PyList()
1447
1448def move_in_stack(move_up):
1449 '''Move up or down the stack (for the py-up/py-down command)'''
1450 frame = Frame.get_selected_python_frame()
1451 while frame:
1452 if move_up:
1453 iter_frame = frame.older()
1454 else:
1455 iter_frame = frame.newer()
1456
1457 if not iter_frame:
1458 break
1459
1460 if iter_frame.is_evalframeex():
1461 # Result:
Martin v. Löwis5226fd62010-04-21 06:05:58 +00001462 if iter_frame.select():
1463 iter_frame.print_summary()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001464 return
1465
1466 frame = iter_frame
1467
1468 if move_up:
1469 print 'Unable to find an older python frame'
1470 else:
1471 print 'Unable to find a newer python frame'
1472
1473class PyUp(gdb.Command):
1474 'Select and print the python stack frame that called this one (if any)'
1475 def __init__(self):
1476 gdb.Command.__init__ (self,
1477 "py-up",
1478 gdb.COMMAND_STACK,
1479 gdb.COMPLETE_NONE)
1480
1481
1482 def invoke(self, args, from_tty):
1483 move_in_stack(move_up=True)
1484
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001485class PyDown(gdb.Command):
1486 'Select and print the python stack frame called by this one (if any)'
1487 def __init__(self):
1488 gdb.Command.__init__ (self,
1489 "py-down",
1490 gdb.COMMAND_STACK,
1491 gdb.COMPLETE_NONE)
1492
1493
1494 def invoke(self, args, from_tty):
1495 move_in_stack(move_up=False)
1496
Victor Stinner50eb60e2010-04-20 22:32:07 +00001497# Not all builds of gdb have gdb.Frame.select
1498if hasattr(gdb.Frame, 'select'):
1499 PyUp()
1500 PyDown()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001501
1502class PyBacktrace(gdb.Command):
1503 'Display the current python frame and all the frames within its call stack (if any)'
1504 def __init__(self):
1505 gdb.Command.__init__ (self,
1506 "py-bt",
1507 gdb.COMMAND_STACK,
1508 gdb.COMPLETE_NONE)
1509
1510
1511 def invoke(self, args, from_tty):
1512 frame = Frame.get_selected_python_frame()
1513 while frame:
1514 if frame.is_evalframeex():
1515 frame.print_summary()
1516 frame = frame.older()
1517
1518PyBacktrace()
1519
1520class PyPrint(gdb.Command):
1521 'Look up the given python variable name, and print it'
1522 def __init__(self):
1523 gdb.Command.__init__ (self,
1524 "py-print",
1525 gdb.COMMAND_DATA,
1526 gdb.COMPLETE_NONE)
1527
1528
1529 def invoke(self, args, from_tty):
1530 name = str(args)
1531
1532 frame = Frame.get_selected_python_frame()
1533 if not frame:
1534 print 'Unable to locate python frame'
1535 return
1536
1537 pyop_frame = frame.get_pyop()
1538 if not pyop_frame:
1539 print 'Unable to read information on python frame'
1540 return
1541
1542 pyop_var, scope = pyop_frame.get_var_by_name(name)
1543
1544 if pyop_var:
1545 print ('%s %r = %s'
1546 % (scope,
1547 name,
1548 pyop_var.get_truncated_repr(MAX_OUTPUT_LEN)))
1549 else:
1550 print '%r not found' % name
1551
1552PyPrint()
1553
1554class PyLocals(gdb.Command):
1555 'Look up the given python variable name, and print it'
1556 def __init__(self):
1557 gdb.Command.__init__ (self,
1558 "py-locals",
1559 gdb.COMMAND_DATA,
1560 gdb.COMPLETE_NONE)
1561
1562
1563 def invoke(self, args, from_tty):
1564 name = str(args)
1565
1566 frame = Frame.get_selected_python_frame()
1567 if not frame:
1568 print 'Unable to locate python frame'
1569 return
1570
1571 pyop_frame = frame.get_pyop()
1572 if not pyop_frame:
1573 print 'Unable to read information on python frame'
1574 return
1575
1576 for pyop_name, pyop_value in pyop_frame.iter_locals():
1577 print ('%s = %s'
1578 % (pyop_name.proxyval(set()),
1579 pyop_value.get_truncated_repr(MAX_OUTPUT_LEN)))
1580
1581PyLocals()