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