# Copyright 2010 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""GDB Pretty printers and convenience functions for Go's runtime structures.
This script is loaded by GDB when it finds a .debug_gdb_scripts
section in the compiled binary. The [68]l linkers emit this with a
path to this file based on the path to the runtime package.
# - pretty printing only works for the 'native' strings. E.g. 'type
# foo string' will make foo a plain struct in the eyes of gdb,
# circumventing the pretty print triggering.
from __future__ import print_function
print("Loading Go Runtime support.", file=sys.stderr)
#http://python3porting.com/differences.html
# allow to manually reload while developing
goobjfile = gdb.current_objfile() or gdb.objfiles()[0]
goobjfile.pretty_printers = []
def read_runtime_const(varname, default):
return int(gdb.parse_and_eval(varname))
G_IDLE = read_runtime_const("'runtime._Gidle'", 0)
G_RUNNABLE = read_runtime_const("'runtime._Grunnable'", 1)
G_RUNNING = read_runtime_const("'runtime._Grunning'", 2)
G_SYSCALL = read_runtime_const("'runtime._Gsyscall'", 3)
G_WAITING = read_runtime_const("'runtime._Gwaiting'", 4)
G_MORIBUND_UNUSED = read_runtime_const("'runtime._Gmoribund_unused'", 5)
G_DEAD = read_runtime_const("'runtime._Gdead'", 6)
G_ENQUEUE_UNUSED = read_runtime_const("'runtime._Genqueue_unused'", 7)
G_COPYSTACK = read_runtime_const("'runtime._Gcopystack'", 8)
G_SCAN = read_runtime_const("'runtime._Gscan'", 0x1000)
G_SCANRUNNABLE = G_SCAN+G_RUNNABLE
G_SCANRUNNING = G_SCAN+G_RUNNING
G_SCANSYSCALL = G_SCAN+G_SYSCALL
G_SCANWAITING = G_SCAN+G_WAITING
G_MORIBUND_UNUSED: 'moribund',
G_ENQUEUE_UNUSED: 'enqueue',
G_COPYSTACK: 'copystack',
G_SCANRUNNABLE: 'runnable+s',
G_SCANRUNNING: 'running+s',
G_SCANSYSCALL: 'syscall+s',
G_SCANWAITING: 'waiting+s',
"Wrapper for slice values."
return int(self.val['len'])
return int(self.val['cap'])
def __getitem__(self, i):
if i < 0 or i >= self.len:
return (ptr + i).dereference()
# The patterns for matching types are permissive because gdb 8.2 switched to matching on (we think) typedef names instead of C syntax names.
"Pretty print Go strings."
pattern = re.compile(r'^(struct string( \*)?|string)$')
return self.val['str'].string("utf-8", "ignore", l)
pattern = re.compile(r'^(struct \[\]|\[\])')
if (t.startswith("struct ")):
return t[len("struct "):]
sval = SliceValue(self.val)
for idx, item in enumerate(sval):
yield ('[{0}]'.format(idx), item)
"""Pretty print map[K]V types.
Map-typed go variables are really pointers. dereference them in gdb
to inspect their contents with this pretty printer.
pattern = re.compile(r'^map\[.*\].*$')
return str(self.val.type)
MapBucketCount = 8 # see internal/abi.go:MapBucketCount
buckets = self.val['buckets']
oldbuckets = self.val['oldbuckets']
flags = self.val['flags']
inttype = self.val['hash0'].type
for bucket in xrange(2 ** int(B)):
oldbucket = bucket & (2 ** (B - 1) - 1)
oldbp = oldbuckets + oldbucket
oldb = oldbp.dereference()
if (oldb['overflow'].cast(inttype) & 1) == 0: # old bucket not evacuated yet
if bucket >= 2 ** (B - 1):
continue # already did old bucket
for i in xrange(MapBucketCount):
"""Pretty print chan[T] types.
Chan-typed go variables are really pointers. dereference them in gdb
to inspect their contents with this pretty printer.
pattern = re.compile(r'^chan ')
return str(self.val.type)
# see chan.c chanbuf(). et is the type stolen from hchan<T>::recvq->first->elem
et = [x.type for x in self.val['recvq']['first'].type.target().fields() if x.name == 'elem'][0]
ptr = (self.val.address["buf"]).cast(et)
for i in range(self.val["qcount"]):
j = (self.val["recvx"] + i) % self.val["dataqsiz"]
yield ('[{0}]'.format(i), (ptr + j).dereference())
def paramtypematch(t, pattern):
return t.code == gdb.TYPE_CODE_TYPEDEF and str(t).startswith(".param") and pattern.match(str(t.target()))
# Register all the *Printer classes above.
if klass.pattern.match(str(val.type)):
elif paramtypematch(val.type, klass.pattern):
return klass(val.cast(val.type.target()))
goobjfile.pretty_printers.extend([makematcher(var) for var in vars().values() if hasattr(var, 'pattern')])
# python2 will not cast pc (type void*) to an int cleanly
# instead python2 and python3 work with the hex string representation
# of the void pointer which we can parse back into an int.
# python3 / newer versions of gdb
# str(pc) can return things like
# "0x429d6c <runtime.gopark+284>", so
pc = int(str(pc).split(None, 1)[0], 16)
# For reference, this is what we're trying to do:
# eface: p *(*(struct 'runtime.rtype'*)'main.e'->type_->data)->string
# iface: p *(*(struct 'runtime.rtype'*)'main.s'->tab->Type->data)->string
# interface types can't be recognized by their name, instead we check
# if they have the expected fields. Unfortunately the mapping of
# fields to python attributes in gdb.py isn't complete: you can't test
# for presence other than by trapping.
return str(val['tab'].type) == "struct runtime.itab *" and str(val['data'].type) == "void *"
return str(val['_type'].type) == "struct runtime._type *" and str(val['data'].type) == "void *"
return gdb.lookup_type(name)
return gdb.lookup_type('struct ' + name)
return gdb.lookup_type('struct ' + name[1:]).pointer()
def iface_commontype(obj):
go_type_ptr = obj['tab']['_type']
go_type_ptr = obj['_type']
return go_type_ptr.cast(gdb.lookup_type("struct reflect.rtype").pointer()).dereference()
"Decode type of the data field of an eface or iface struct."
# known issue: dtype_name decoded from runtime.rtype is "nested.Foo"
# but the dwarf table lists it as "full/path/to/nested.Foo"
dynamic_go_type = iface_commontype(obj)
if dynamic_go_type is None:
dtype_name = dynamic_go_type['string'].dereference()['str'].string()
dynamic_gdb_type = lookup_type(dtype_name)
if dynamic_gdb_type is None:
type_size = int(dynamic_go_type['size'])
uintptr_size = int(dynamic_go_type['size'].type.sizeof) # size is itself a uintptr
if type_size > uintptr_size:
dynamic_gdb_type = dynamic_gdb_type.pointer()
def iface_dtype_name(obj):
"Decode type name of the data field of an eface or iface struct."
dynamic_go_type = iface_commontype(obj)
if dynamic_go_type is None:
return dynamic_go_type['string'].dereference()['str'].string()
"""Pretty print interface values
Casts the data field to the appropriate dynamic type."""
if self.val['data'] == 0:
dtype = iface_dtype(self.val)
return "<bad dynamic type>"
if dtype is None: # trouble looking up, print something reasonable
return "({typename}){data}".format(
typename=iface_dtype_name(self.val), data=self.val['data'])
return self.val['data'].cast(dtype).dereference()
return self.val['data'].cast(dtype)
if is_iface(val) or is_eface(val):
goobjfile.pretty_printers.append(ifacematcher)
class GoLenFunc(gdb.Function):
"Length of strings, slices, maps or channels"
how = ((StringTypePrinter, 'len'), (SliceTypePrinter, 'len'), (MapTypePrinter, 'count'), (ChanTypePrinter, 'qcount'))
gdb.Function.__init__(self, "len")
for klass, fld in self.how:
if klass.pattern.match(typename) or paramtypematch(obj.type, klass.pattern):
class GoCapFunc(gdb.Function):
"Capacity of slices or channels"
how = ((SliceTypePrinter, 'cap'), (ChanTypePrinter, 'dataqsiz'))
gdb.Function.__init__(self, "cap")
for klass, fld in self.how:
if klass.pattern.match(typename) or paramtypematch(obj.type, klass.pattern):
class DTypeFunc(gdb.Function):
"""Cast Interface values to their dynamic type.
For non-interface types this behaves as the identity operation.
gdb.Function.__init__(self, "dtype")
return obj['data'].cast(iface_dtype(obj))
def linked_list(ptr, linkfield):
class GoroutinesCmd(gdb.Command):
gdb.Command.__init__(self, "info goroutines", gdb.COMMAND_STACK, gdb.COMPLETE_NONE)
def invoke(self, _arg, _from_tty):
# args = gdb.string_to_argv(arg)
vp = gdb.lookup_type('void').pointer()
for ptr in SliceValue(gdb.parse_and_eval("'runtime.allgs'")):
if ptr['atomicstatus']['value'] == G_DEAD:
pc = ptr['sched']['pc'].cast(vp)
blk = gdb.block_for_pc(pc)
status = int(ptr['atomicstatus']['value'])
st = sts.get(status, "unknown(%d)" % status)
print(s, ptr['goid'], "{0:8s}".format(st), blk.function)
def find_goroutine(goid):
find_goroutine attempts to find the goroutine identified by goid.
It returns a tuple of gdb.Value's representing the stack pointer
and program counter pointer for the goroutine.
@return tuple (gdb.Value, gdb.Value)
vp = gdb.lookup_type('void').pointer()
for ptr in SliceValue(gdb.parse_and_eval("'runtime.allgs'")):
if ptr['atomicstatus']['value'] == G_DEAD:
# Get the goroutine's saved state.
pc, sp = ptr['sched']['pc'], ptr['sched']['sp']
status = ptr['atomicstatus']['value']&~G_SCAN
# Goroutine is not running nor in syscall, so use the info in goroutine
if status != G_RUNNING and status != G_SYSCALL:
return pc.cast(vp), sp.cast(vp)
# If the goroutine is in a syscall, use syscallpc/sp.
pc, sp = ptr['syscallpc'], ptr['syscallsp']
return pc.cast(vp), sp.cast(vp)
# Otherwise, the goroutine is running, so it doesn't have
# saved scheduler state. Find G's OS thread.
for thr in gdb.selected_inferior().threads():
if thr.ptid[1] == m['procid']: