Debian Codegraph @

pypy/tool/gdb_pypy.py

raw symbols SCIP
1 """
2 Some convenience macros for gdb. If you have pypy in your path, you can simply do:
3
4 (gdb) python import pypy.tool.gdb_pypy
5
6 Or, alternatively:
7
8 (gdb) python exec(open('/path/to/gdb_pypy.py').read())
9 """
10
11 import re
12 import sys
13 import os.path
14
15 try:
16 # when running inside gdb
17 from gdb import Command
18 except ImportError:
19 # whenn running outside gdb: mock class for testing
20 class Command(object):
21 def __init__(self, name, command_class):
22 pass
23
24 MAX_DISPLAY_LENGTH = 100 # maximum number of characters displayed in rpy_string
25
26 def find_field_with_suffix(val, suffix):
27 """
28 Return ``val[field]``, where ``field`` is the only one whose name ends
29 with ``suffix``. If there is no such field, or more than one, raise KeyError.
30 """
31 names = []
32 for field in val.type.fields():
33 if field.name.endswith(suffix):
34 names.append(field.name)
35 #
36 if len(names) == 1:
37 return val[names[0]]
38 elif len(names) == 0:
39 raise KeyError("cannot find field *%s" % suffix)
40 else:
41 raise KeyError("too many matching fields: %s" % ', '.join(names))
42
43 def lookup(val, suffix):
44 """
45 Lookup a field which ends with ``suffix`` following the rpython struct
46 inheritance hierarchy (i.e., looking both at ``val`` and
47 ``val['*_super']``, recursively.
48 """
49 try:
50 return find_field_with_suffix(val, suffix)
51 except KeyError:
52 baseobj = find_field_with_suffix(val, '_super')
53 return lookup(baseobj, suffix)
54
55
56 class RPyType(Command):
57 """
58 Prints the RPython type of the expression.
59 E.g.:
60
61 (gdb) rpy_type l_v123
62 GcStruct pypy.foo.Bar { super, inst_xxx, inst_yyy }
63 """
64
65 prog2typeids = {}
66
67 def __init__(self, gdb=None):
68 # dependency injection, for tests
69 if gdb is None:
70 import gdb
71 self.gdb = gdb
72 Command.__init__(self, "rpy_type", self.gdb.COMMAND_NONE)
73
74 def invoke(self, arg, from_tty):
75 # some magic code to automatically reload the python file while developing
76 try:
77 from pypy.tool import gdb_pypy
78 try:
79 reload(gdb_pypy)
80 except:
81 import imp
82 imp.reload(gdb_pypy)
83 gdb_pypy.RPyType.prog2typeids = self.prog2typeids # persist the cache
84 self.__class__ = gdb_pypy.RPyType
85 result = self.do_invoke(arg, from_tty)
86 if not isinstance(result, str):
87 result = result.decode('latin-1')
88 print(result)
89 except:
90 import traceback
91 traceback.print_exc()
92
93 def do_invoke(self, arg, from_tty):
94 try:
95 offset = int(arg)
96 except ValueError:
97 obj = self.gdb.parse_and_eval(arg)
98 if obj.type.code == self.gdb.TYPE_CODE_PTR:
99 obj = obj.dereference()
100 hdr = lookup(obj, '_gcheader')
101 tid = hdr['h_tid']
102 if tid == -42: # forwarded?
103 return 'Forwarded'
104 if sys.maxsize < 2**32:
105 offset = tid & 0xFFFF # 32bit
106 else:
107 offset = tid & 0xFFFFFFFF # 64bit
108 offset = int(offset) # convert from gdb.Value to python int
109
110 typeids = self.get_typeids()
111 if offset in typeids:
112 return typeids[offset]
113 else:
114 return 'Cannot find the type with offset 0x%x' % offset
115
116 def get_typeids(self):
117 try:
118 progspace = self.gdb.current_progspace()
119 except AttributeError:
120 progspace = None
121 try:
122 return self.prog2typeids[progspace]
123 except KeyError:
124 typeids = self.load_typeids(progspace)
125 self.prog2typeids[progspace] = typeids
126 return typeids
127
128 def load_typeids(self, progspace=None):
129 """
130 Returns a mapping offset --> description
131 """
132 import tempfile
133 import zlib
134 vname = 'pypy_g_rpython_memory_gctypelayout_GCData.gcd_inst_typeids_z'
135 length = int(self.gdb.parse_and_eval('*(long*)%s' % vname))
136 vstart = '(char*)(((long*)%s)+1)' % vname
137 fname = tempfile.mktemp()
138 try:
139 self.gdb.execute('dump binary memory %s %s %s+%d' %
140 (fname, vstart, vstart, length))
141 with open(fname, 'rb') as fobj:
142 data = fobj.read()
143 return TypeIdsMap(zlib.decompress(data).splitlines(True), self.gdb)
144 finally:
145 os.remove(fname)
146
147
148 class TypeIdsMap(object):
149 def __init__(self, lines, gdb):
150 self.lines = lines
151 self.gdb = gdb
152 self.line2offset = {0: 0}
153 self.offset2descr = {0: "(null typeid)"}
154
155 def __getitem__(self, key):
156 value = self.get(key)
157 if value is None:
158 raise KeyError(key)
159 return value
160
161 def __contains__(self, key):
162 return self.get(key) is not None
163
164 def _fetchline(self, linenum):
165 if linenum in self.line2offset:
166 return self.line2offset[linenum]
167 line = self.lines[linenum]
168 member, descr = [x.strip() for x in line.split(None, 1)]
169 if sys.maxsize < 2**32:
170 TIDT = "int*"
171 else:
172 TIDT = "char*"
173 expr = ("((%s)(&pypy_g_typeinfo.%s)) - (%s)&pypy_g_typeinfo"
174 % (TIDT, member.decode("latin-1"), TIDT))
175 offset = int(self.gdb.parse_and_eval(expr))
176 self.line2offset[linenum] = offset
177 self.offset2descr[offset] = descr
178 #print '%r -> %r -> %r' % (linenum, offset, descr)
179 return offset
180
181 def get(self, offset, default=None):
182 # binary search through the lines, asking gdb to parse stuff lazily
183 if offset in self.offset2descr:
184 return self.offset2descr[offset]
185 if not (0 < offset < sys.maxsize):
186 return None
187 linerange = (0, len(self.lines))
188 while linerange[0] < linerange[1]:
189 linemiddle = (linerange[0] + linerange[1]) >> 1
190 offsetmiddle = self._fetchline(linemiddle)
191 if offsetmiddle == offset:
192 return self.offset2descr[offset]
193 elif offsetmiddle < offset:
194 linerange = (linemiddle + 1, linerange[1])
195 else:
196 linerange = (linerange[0], linemiddle)
197 return None
198
199
200 def is_ptr(type, gdb):
201 if gdb is None:
202 import gdb # so we can pass a fake one from the tests
203 return type.code == gdb.TYPE_CODE_PTR
204
205
206 class RPyStringPrinter(object):
207 """
208 Pretty printer for rpython strings.
209
210 Note that this pretty prints *pointers* to strings: this way you can do "p
211 val" and see the nice string, and "p *val" to see the underyling struct
212 fields
213 """
214
215 def __init__(self, val):
216 self.val = val
217
218 @classmethod
219 def lookup(cls, val, gdb=None):
220 t = val.type
221 if is_ptr(t, gdb) and t.target().tag == 'pypy_rpy_string0':
222 return cls(val)
223 return None
224
225 def to_string(self):
226 chars = self.val['rs_chars']
227 length = int(chars['length'])
228 items = chars['items']
229 res = []
230 for i in range(min(length, MAX_DISPLAY_LENGTH)):
231 c = items[i]
232 try:
233 res.append(chr(c))
234 except ValueError:
235 # it's a gdb.Value so it has "121 'y'" as repr
236 try:
237 res.append(chr(int(str(c).split(" ")[0])))
238 except ValueError:
239 # meh?
240 res.append(repr(c))
241 if length > MAX_DISPLAY_LENGTH:
242 res.append('...')
243 string = ''.join(res)
244 return 'r' + repr(string)
245
246
247 class RPyListPrinter(object):
248 """
249 Pretty printer for rpython lists
250
251 Note that this pretty prints *pointers* to lists: this way you can do "p
252 val" and see the nice repr, and "p *val" to see the underyling struct
253 fields
254 """
255
256 recursive = False
257
258 def __init__(self, val):
259 self.val = val
260
261 @classmethod
262 def lookup(cls, val, gdb=None):
263 t = val.type
264 if (is_ptr(t, gdb) and t.target().tag is not None and
265 re.match(r'pypy_(list|array)\d*', t.target().tag)):
266 return cls(val)
267 return None
268
269 def to_string(self):
270 t = self.val.type
271 if t.target().tag.startswith(r'pypy_array'):
272 if not self.val:
273 return 'r(null_array)'
274 length = int(self.val['length'])
275 items = self.val['items']
276 allocstr = ''
277 else:
278 if not self.val:
279 return 'r(null_list)'
280 length = int(self.val['l_length'])
281 array = self.val['l_items']
282 allocated = int(array['length'])
283 items = array['items']
284 allocstr = ', alloc=%d' % allocated
285 if RPyListPrinter.recursive:
286 str_items = '...'
287 else:
288 RPyListPrinter.recursive = True
289 try:
290 itemlist = []
291 for i in range(min(length, MAX_DISPLAY_LENGTH)):
292 item = items[i]
293 itemlist.append(str(item)) # may recurse here
294 if length > MAX_DISPLAY_LENGTH:
295 itemlist.append("...")
296 str_items = ', '.join(itemlist)
297 finally:
298 RPyListPrinter.recursive = False
299 return 'r[%s] (len=%d%s)' % (str_items, length, allocstr)
300
301
302 try:
303 import gdb
304 RPyType() # side effects
305 gdb.pretty_printers = [
306 RPyStringPrinter.lookup,
307 RPyListPrinter.lookup
308 ] + gdb.pretty_printers
309 except ImportError:
310 pass