Text file
src/runtime/runtime-gdb.py
1 # Copyright 2010 The Go Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style
3 # license that can be found in the LICENSE file.
4
5 """GDB Pretty printers and convenience functions for Go's runtime structures.
6
7 This script is loaded by GDB when it finds a .debug_gdb_scripts
8 section in the compiled binary. The [68]l linkers emit this with a
9 path to this file based on the path to the runtime package.
10 """
11
12 # Known issues:
13 # - pretty printing only works for the 'native' strings. E.g. 'type
14 # foo string' will make foo a plain struct in the eyes of gdb,
15 # circumventing the pretty print triggering.
16
17
18 from __future__ import print_function
19 import re
20 import sys
21 import gdb
22
23 print("Loading Go Runtime support.", file=sys.stderr)
24 #http://python3porting.com/differences.html
25 if sys.version > '3':
26 xrange = range
27 # allow to manually reload while developing
28 goobjfile = gdb.current_objfile() or gdb.objfiles()[0]
29 goobjfile.pretty_printers = []
30
31 # G state (runtime2.go)
32
33 def read_runtime_const(varname, default):
34 try:
35 return int(gdb.parse_and_eval(varname))
36 except Exception:
37 return int(default)
38
39
40 G_IDLE = read_runtime_const("'runtime._Gidle'", 0)
41 G_RUNNABLE = read_runtime_const("'runtime._Grunnable'", 1)
42 G_RUNNING = read_runtime_const("'runtime._Grunning'", 2)
43 G_SYSCALL = read_runtime_const("'runtime._Gsyscall'", 3)
44 G_WAITING = read_runtime_const("'runtime._Gwaiting'", 4)
45 G_MORIBUND_UNUSED = read_runtime_const("'runtime._Gmoribund_unused'", 5)
46 G_DEAD = read_runtime_const("'runtime._Gdead'", 6)
47 G_ENQUEUE_UNUSED = read_runtime_const("'runtime._Genqueue_unused'", 7)
48 G_COPYSTACK = read_runtime_const("'runtime._Gcopystack'", 8)
49 G_SCAN = read_runtime_const("'runtime._Gscan'", 0x1000)
50 G_SCANRUNNABLE = G_SCAN+G_RUNNABLE
51 G_SCANRUNNING = G_SCAN+G_RUNNING
52 G_SCANSYSCALL = G_SCAN+G_SYSCALL
53 G_SCANWAITING = G_SCAN+G_WAITING
54
55 sts = {
56 G_IDLE: 'idle',
57 G_RUNNABLE: 'runnable',
58 G_RUNNING: 'running',
59 G_SYSCALL: 'syscall',
60 G_WAITING: 'waiting',
61 G_MORIBUND_UNUSED: 'moribund',
62 G_DEAD: 'dead',
63 G_ENQUEUE_UNUSED: 'enqueue',
64 G_COPYSTACK: 'copystack',
65 G_SCAN: 'scan',
66 G_SCANRUNNABLE: 'runnable+s',
67 G_SCANRUNNING: 'running+s',
68 G_SCANSYSCALL: 'syscall+s',
69 G_SCANWAITING: 'waiting+s',
70 }
71
72
73 #
74 # Value wrappers
75 #
76
77 class SliceValue:
78 "Wrapper for slice values."
79
80 def __init__(self, val):
81 self.val = val
82
83 @property
84 def len(self):
85 return int(self.val['len'])
86
87 @property
88 def cap(self):
89 return int(self.val['cap'])
90
91 def __getitem__(self, i):
92 if i < 0 or i >= self.len:
93 raise IndexError(i)
94 ptr = self.val["array"]
95 return (ptr + i).dereference()
96
97
98 #
99 # Pretty Printers
100 #
101
102 # The patterns for matching types are permissive because gdb 8.2 switched to matching on (we think) typedef names instead of C syntax names.
103 class StringTypePrinter:
104 "Pretty print Go strings."
105
106 pattern = re.compile(r'^(struct string( \*)?|string)$')
107
108 def __init__(self, val):
109 self.val = val
110
111 def display_hint(self):
112 return 'string'
113
114 def to_string(self):
115 l = int(self.val['len'])
116 return self.val['str'].string("utf-8", "ignore", l)
117
118
119 class SliceTypePrinter:
120 "Pretty print slices."
121
122 pattern = re.compile(r'^(struct \[\]|\[\])')
123
124 def __init__(self, val):
125 self.val = val
126
127 def display_hint(self):
128 return 'array'
129
130 def to_string(self):
131 t = str(self.val.type)
132 if (t.startswith("struct ")):
133 return t[len("struct "):]
134 return t
135
136 def children(self):
137 sval = SliceValue(self.val)
138 if sval.len > sval.cap:
139 return
140 for idx, item in enumerate(sval):
141 yield ('[{0}]'.format(idx), item)
142
143
144 class MapTypePrinter:
145 """Pretty print map[K]V types.
146
147 Map-typed go variables are really pointers. dereference them in gdb
148 to inspect their contents with this pretty printer.
149 """
150
151 pattern = re.compile(r'^map\[.*\].*$')
152
153 def __init__(self, val):
154 self.val = val
155
156 def display_hint(self):
157 return 'map'
158
159 def to_string(self):
160 return str(self.val.type)
161
162 def children(self):
163 MapGroupSlots = 8 # see internal/abi:MapGroupSlots
164
165 cnt = 0
166 # Yield keys and elements in group.
167 # group is a value of type *group[K,V]
168 def group_slots(group):
169 ctrl = group['ctrl']
170
171 for i in xrange(MapGroupSlots):
172 c = (ctrl >> (8*i)) & 0xff
173 if (c & 0x80) != 0:
174 # Empty or deleted
175 continue
176
177 # Full
178 yield str(cnt), group['slots'][i]['key']
179 yield str(cnt+1), group['slots'][i]['elem']
180
181 # The linker DWARF generation
182 # (cmd/link/internal/ld.(*dwctxt).synthesizemaptypes) records
183 # dirPtr as a **table[K,V], but it may actually be two different types:
184 #
185 # For "full size" maps (dirLen > 0), dirPtr is actually a pointer to
186 # variable length array *[dirLen]*table[K,V]. In other words, dirPtr +
187 # dirLen are a deconstructed slice []*table[K,V].
188 #
189 # For "small" maps (dirLen <= 0), dirPtr is a pointer directly to a
190 # single group *group[K,V] containing the map slots.
191 #
192 # N.B. array() takes an _inclusive_ upper bound.
193
194 # table[K,V]
195 table_type = self.val['dirPtr'].type.target().target()
196
197 if self.val['dirLen'] <= 0:
198 # Small map
199
200 # We need to find the group type we'll cast to. Since dirPtr isn't
201 # actually **table[K,V], we can't use the nice API of
202 # obj['field'].type, as that actually wants to dereference obj.
203 # Instead, search only via the type API.
204 ptr_group_type = None
205 for tf in table_type.fields():
206 if tf.name != 'groups':
207 continue
208 groups_type = tf.type
209 for gf in groups_type.fields():
210 if gf.name != 'data':
211 continue
212 # *group[K,V]
213 ptr_group_type = gf.type
214
215 if ptr_group_type is None:
216 raise TypeError("unable to find table[K,V].groups.data")
217
218 # group = (*group[K,V])(dirPtr)
219 group = self.val['dirPtr'].cast(ptr_group_type)
220
221 yield from group_slots(group)
222
223 return
224
225 # Full size map.
226
227 # *table[K,V]
228 ptr_table_type = table_type.pointer()
229 # [dirLen]*table[K,V]
230 array_ptr_table_type = ptr_table_type.array(self.val['dirLen']-1)
231 # *[dirLen]*table[K,V]
232 ptr_array_ptr_table_type = array_ptr_table_type.pointer()
233 # tables = (*[dirLen]*table[K,V])(dirPtr)
234 tables = self.val['dirPtr'].cast(ptr_array_ptr_table_type)
235
236 cnt = 0
237 for t in xrange(self.val['dirLen']):
238 table = tables[t]
239 table = table.dereference()
240
241 groups = table['groups']['data']
242 length = table['groups']['lengthMask'] + 1
243
244 # The linker DWARF generation
245 # (cmd/link/internal/ld.(*dwctxt).synthesizemaptypes) records
246 # groups.data as a *group[K,V], but it is actually a pointer to
247 # variable length array *[length]group[K,V].
248 #
249 # N.B. array() takes an _inclusive_ upper bound.
250
251 # group[K,V]
252 group_type = groups.type.target()
253 # [length]group[K,V]
254 array_group_type = group_type.array(length-1)
255 # *[length]group[K,V]
256 ptr_array_group_type = array_group_type.pointer()
257 # groups = (*[length]group[K,V])(groups.data)
258 groups = groups.cast(ptr_array_group_type)
259 groups = groups.dereference()
260
261 for i in xrange(length):
262 group = groups[i]
263 yield from group_slots(group)
264
265
266 class ChanTypePrinter:
267 """Pretty print chan[T] types.
268
269 Chan-typed go variables are really pointers. dereference them in gdb
270 to inspect their contents with this pretty printer.
271 """
272
273 pattern = re.compile(r'^chan ')
274
275 def __init__(self, val):
276 self.val = val
277
278 def display_hint(self):
279 return 'array'
280
281 def to_string(self):
282 return str(self.val.type)
283
284 def children(self):
285 # see chan.c chanbuf(). et is the type stolen from hchan<T>::recvq->first->elem
286 et = [x.type for x in self.val['recvq']['first'].type.target().fields() if x.name == 'elem'][0]
287 ptr = (self.val.address["buf"]).cast(et)
288 for i in range(self.val["qcount"]):
289 j = (self.val["recvx"] + i) % self.val["dataqsiz"]
290 yield ('[{0}]'.format(i), (ptr + j).dereference())
291
292
293 def paramtypematch(t, pattern):
294 return t.code == gdb.TYPE_CODE_TYPEDEF and str(t).startswith(".param") and pattern.match(str(t.target()))
295
296 #
297 # Register all the *Printer classes above.
298 #
299
300 def makematcher(klass):
301 def matcher(val):
302 try:
303 if klass.pattern.match(str(val.type)):
304 return klass(val)
305 elif paramtypematch(val.type, klass.pattern):
306 return klass(val.cast(val.type.target()))
307 except Exception:
308 pass
309 return matcher
310
311 goobjfile.pretty_printers.extend([makematcher(var) for var in vars().values() if hasattr(var, 'pattern')])
312 #
313 # Utilities
314 #
315
316 def pc_to_int(pc):
317 # python2 will not cast pc (type void*) to an int cleanly
318 # instead python2 and python3 work with the hex string representation
319 # of the void pointer which we can parse back into an int.
320 # int(pc) will not work.
321 try:
322 # python3 / newer versions of gdb
323 pc = int(pc)
324 except gdb.error:
325 # str(pc) can return things like
326 # "0x429d6c <runtime.gopark+284>", so
327 # chop at first space.
328 pc = int(str(pc).split(None, 1)[0], 16)
329 return pc
330
331
332 #
333 # For reference, this is what we're trying to do:
334 # eface: p *(*(struct 'runtime.rtype'*)'main.e'->type_->data)->string
335 # iface: p *(*(struct 'runtime.rtype'*)'main.s'->tab->Type->data)->string
336 #
337 # interface types can't be recognized by their name, instead we check
338 # if they have the expected fields. Unfortunately the mapping of
339 # fields to python attributes in gdb.py isn't complete: you can't test
340 # for presence other than by trapping.
341
342
343 def is_iface(val):
344 try:
345 return str(val['tab'].type) == "struct runtime.itab *" and str(val['data'].type) == "void *"
346 except gdb.error:
347 pass
348
349
350 def is_eface(val):
351 try:
352 return str(val['_type'].type) == "struct runtime._type *" and str(val['data'].type) == "void *"
353 except gdb.error:
354 pass
355
356
357 def lookup_type(name):
358 try:
359 return gdb.lookup_type(name)
360 except gdb.error:
361 pass
362 try:
363 return gdb.lookup_type('struct ' + name)
364 except gdb.error:
365 pass
366 try:
367 return gdb.lookup_type('struct ' + name[1:]).pointer()
368 except gdb.error:
369 pass
370
371
372 def iface_commontype(obj):
373 if is_iface(obj):
374 go_type_ptr = obj['tab']['_type']
375 elif is_eface(obj):
376 go_type_ptr = obj['_type']
377 else:
378 return
379
380 return go_type_ptr.cast(gdb.lookup_type("struct reflect.rtype").pointer()).dereference()
381
382
383 def iface_dtype(obj):
384 "Decode type of the data field of an eface or iface struct."
385 # known issue: dtype_name decoded from runtime.rtype is "nested.Foo"
386 # but the dwarf table lists it as "full/path/to/nested.Foo"
387
388 dynamic_go_type = iface_commontype(obj)
389 if dynamic_go_type is None:
390 return
391 dtype_name = dynamic_go_type['string'].dereference()['str'].string()
392
393 dynamic_gdb_type = lookup_type(dtype_name)
394 if dynamic_gdb_type is None:
395 return
396
397 type_size = int(dynamic_go_type['size'])
398 uintptr_size = int(dynamic_go_type['size'].type.sizeof) # size is itself a uintptr
399 if type_size > uintptr_size:
400 dynamic_gdb_type = dynamic_gdb_type.pointer()
401
402 return dynamic_gdb_type
403
404
405 def iface_dtype_name(obj):
406 "Decode type name of the data field of an eface or iface struct."
407
408 dynamic_go_type = iface_commontype(obj)
409 if dynamic_go_type is None:
410 return
411 return dynamic_go_type['string'].dereference()['str'].string()
412
413
414 class IfacePrinter:
415 """Pretty print interface values
416
417 Casts the data field to the appropriate dynamic type."""
418
419 def __init__(self, val):
420 self.val = val
421
422 def display_hint(self):
423 return 'string'
424
425 def to_string(self):
426 if self.val['data'] == 0:
427 return 0x0
428 try:
429 dtype = iface_dtype(self.val)
430 except Exception:
431 return "<bad dynamic type>"
432
433 if dtype is None: # trouble looking up, print something reasonable
434 return "({typename}){data}".format(
435 typename=iface_dtype_name(self.val), data=self.val['data'])
436
437 try:
438 return self.val['data'].cast(dtype).dereference()
439 except Exception:
440 pass
441 return self.val['data'].cast(dtype)
442
443
444 def ifacematcher(val):
445 if is_iface(val) or is_eface(val):
446 return IfacePrinter(val)
447
448 goobjfile.pretty_printers.append(ifacematcher)
449
450 #
451 # Convenience Functions
452 #
453
454
455 class GoLenFunc(gdb.Function):
456 "Length of strings, slices, maps or channels"
457
458 how = ((StringTypePrinter, 'len'), (SliceTypePrinter, 'len'), (MapTypePrinter, 'used'), (ChanTypePrinter, 'qcount'))
459
460 def __init__(self):
461 gdb.Function.__init__(self, "len")
462
463 def invoke(self, obj):
464 typename = str(obj.type)
465 for klass, fld in self.how:
466 if klass.pattern.match(typename) or paramtypematch(obj.type, klass.pattern):
467 if klass == MapTypePrinter:
468 fields = [f.name for f in self.val.type.strip_typedefs().target().fields()]
469 if 'buckets' in fields:
470 # Old maps.
471 fld = 'count'
472
473 return obj[fld]
474
475
476 class GoCapFunc(gdb.Function):
477 "Capacity of slices or channels"
478
479 how = ((SliceTypePrinter, 'cap'), (ChanTypePrinter, 'dataqsiz'))
480
481 def __init__(self):
482 gdb.Function.__init__(self, "cap")
483
484 def invoke(self, obj):
485 typename = str(obj.type)
486 for klass, fld in self.how:
487 if klass.pattern.match(typename) or paramtypematch(obj.type, klass.pattern):
488 return obj[fld]
489
490
491 class DTypeFunc(gdb.Function):
492 """Cast Interface values to their dynamic type.
493
494 For non-interface types this behaves as the identity operation.
495 """
496
497 def __init__(self):
498 gdb.Function.__init__(self, "dtype")
499
500 def invoke(self, obj):
501 try:
502 return obj['data'].cast(iface_dtype(obj))
503 except gdb.error:
504 pass
505 return obj
506
507 #
508 # Commands
509 #
510
511 def linked_list(ptr, linkfield):
512 while ptr:
513 yield ptr
514 ptr = ptr[linkfield]
515
516
517 class GoroutinesCmd(gdb.Command):
518 "List all goroutines."
519
520 def __init__(self):
521 gdb.Command.__init__(self, "info goroutines", gdb.COMMAND_STACK, gdb.COMPLETE_NONE)
522
523 def invoke(self, _arg, _from_tty):
524 # args = gdb.string_to_argv(arg)
525 vp = gdb.lookup_type('void').pointer()
526 for ptr in SliceValue(gdb.parse_and_eval("'runtime.allgs'")):
527 if ptr['atomicstatus']['value'] == G_DEAD:
528 continue
529 s = ' '
530 if ptr['m']:
531 s = '*'
532 pc = ptr['sched']['pc'].cast(vp)
533 pc = pc_to_int(pc)
534 blk = gdb.block_for_pc(pc)
535 status = int(ptr['atomicstatus']['value'])
536 st = sts.get(status, "unknown(%d)" % status)
537 print(s, ptr['goid'], "{0:8s}".format(st), blk.function)
538
539
540 def find_goroutine(goid):
541 """
542 find_goroutine attempts to find the goroutine identified by goid.
543 It returns a tuple of gdb.Value's representing the stack pointer
544 and program counter pointer for the goroutine.
545
546 @param int goid
547
548 @return tuple (gdb.Value, gdb.Value)
549 """
550 vp = gdb.lookup_type('void').pointer()
551 for ptr in SliceValue(gdb.parse_and_eval("'runtime.allgs'")):
552 if ptr['atomicstatus']['value'] == G_DEAD:
553 continue
554 if ptr['goid'] == goid:
555 break
556 else:
557 return None, None
558 # Get the goroutine's saved state.
559 pc, sp = ptr['sched']['pc'], ptr['sched']['sp']
560 status = ptr['atomicstatus']['value']&~G_SCAN
561 # Goroutine is not running nor in syscall, so use the info in goroutine
562 if status != G_RUNNING and status != G_SYSCALL:
563 return pc.cast(vp), sp.cast(vp)
564
565 # If the goroutine is in a syscall, use syscallpc/sp.
566 pc, sp = ptr['syscallpc'], ptr['syscallsp']
567 if sp != 0:
568 return pc.cast(vp), sp.cast(vp)
569 # Otherwise, the goroutine is running, so it doesn't have
570 # saved scheduler state. Find G's OS thread.
571 m = ptr['m']
572 if m == 0:
573 return None, None
574 for thr in gdb.selected_inferior().threads():
575 if thr.ptid[1] == m['procid']:
576 break
577 else:
578 return None, None
579 # Get scheduler state from the G's OS thread state.
580 curthr = gdb.selected_thread()
581 try:
582 thr.switch()
583 pc = gdb.parse_and_eval('$pc')
584 sp = gdb.parse_and_eval('$sp')
585 finally:
586 curthr.switch()
587 return pc.cast(vp), sp.cast(vp)
588
589
590 class GoroutineCmd(gdb.Command):
591 """Execute gdb command in the context of goroutine <goid>.
592
593 Switch PC and SP to the ones in the goroutine's G structure,
594 execute an arbitrary gdb command, and restore PC and SP.
595
596 Usage: (gdb) goroutine <goid> <gdbcmd>
597
598 You could pass "all" as <goid> to apply <gdbcmd> to all goroutines.
599
600 For example: (gdb) goroutine all <gdbcmd>
601
602 Note that it is ill-defined to modify state in the context of a goroutine.
603 Restrict yourself to inspecting values.
604 """
605
606 def __init__(self):
607 gdb.Command.__init__(self, "goroutine", gdb.COMMAND_STACK, gdb.COMPLETE_NONE)
608
609 def invoke(self, arg, _from_tty):
610 goid_str, cmd = arg.split(None, 1)
611 goids = []
612
613 if goid_str == 'all':
614 for ptr in SliceValue(gdb.parse_and_eval("'runtime.allgs'")):
615 goids.append(int(ptr['goid']))
616 else:
617 goids = [int(gdb.parse_and_eval(goid_str))]
618
619 for goid in goids:
620 self.invoke_per_goid(goid, cmd)
621
622 def invoke_per_goid(self, goid, cmd):
623 pc, sp = find_goroutine(goid)
624 if not pc:
625 print("No such goroutine: ", goid)
626 return
627 pc = pc_to_int(pc)
628 save_frame = gdb.selected_frame()
629 gdb.parse_and_eval('$save_sp = $sp')
630 gdb.parse_and_eval('$save_pc = $pc')
631 # In GDB, assignments to sp must be done from the
632 # top-most frame, so select frame 0 first.
633 gdb.execute('select-frame 0')
634 gdb.parse_and_eval('$sp = {0}'.format(str(sp)))
635 gdb.parse_and_eval('$pc = {0}'.format(str(pc)))
636 try:
637 gdb.execute(cmd)
638 finally:
639 # In GDB, assignments to sp must be done from the
640 # top-most frame, so select frame 0 first.
641 gdb.execute('select-frame 0')
642 gdb.parse_and_eval('$pc = $save_pc')
643 gdb.parse_and_eval('$sp = $save_sp')
644 save_frame.select()
645
646
647 class GoIfaceCmd(gdb.Command):
648 "Print Static and dynamic interface types"
649
650 def __init__(self):
651 gdb.Command.__init__(self, "iface", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)
652
653 def invoke(self, arg, _from_tty):
654 for obj in gdb.string_to_argv(arg):
655 try:
656 #TODO fix quoting for qualified variable names
657 obj = gdb.parse_and_eval(str(obj))
658 except Exception as e:
659 print("Can't parse ", obj, ": ", e)
660 continue
661
662 if obj['data'] == 0:
663 dtype = "nil"
664 else:
665 dtype = iface_dtype(obj)
666
667 if dtype is None:
668 print("Not an interface: ", obj.type)
669 continue
670
671 print("{0}: {1}".format(obj.type, dtype))
672
673 # TODO: print interface's methods and dynamic type's func pointers thereof.
674 #rsc: "to find the number of entries in the itab's Fn field look at
675 # itab.inter->numMethods
676 # i am sure i have the names wrong but look at the interface type
677 # and its method count"
678 # so Itype will start with a commontype which has kind = interface
679
680 #
681 # Register all convenience functions and CLI commands
682 #
683 GoLenFunc()
684 GoCapFunc()
685 DTypeFunc()
686 GoroutinesCmd()
687 GoroutineCmd()
688 GoIfaceCmd()
689
View as plain text