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