Debian Codegraph @

Tools/gdb/libpython.py

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