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