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  		B = self.val['B']
   164  		buckets = self.val['buckets']
   165  		oldbuckets = self.val['oldbuckets']
   166  		flags = self.val['flags']
   167  		inttype = self.val['hash0'].type
   168  		cnt = 0
   169  		for bucket in xrange(2 ** int(B)):
   170  			bp = buckets + bucket
   171  			if oldbuckets:
   172  				oldbucket = bucket & (2 ** (B - 1) - 1)
   173  				oldbp = oldbuckets + oldbucket
   174  				oldb = oldbp.dereference()
   175  				if (oldb['overflow'].cast(inttype) & 1) == 0:  # old bucket not evacuated yet
   176  					if bucket >= 2 ** (B - 1):
   177  						continue    # already did old bucket
   178  					bp = oldbp
   179  			while bp:
   180  				b = bp.dereference()
   181  				for i in xrange(8):
   182  					if b['tophash'][i] != 0:
   183  						k = b['keys'][i]
   184  						v = b['values'][i]
   185  						if flags & 1:
   186  							k = k.dereference()
   187  						if flags & 2:
   188  							v = v.dereference()
   189  						yield str(cnt), k
   190  						yield str(cnt + 1), v
   191  						cnt += 2
   192  				bp = b['overflow']
   193  
   194  
   195  class ChanTypePrinter:
   196  	"""Pretty print chan[T] types.
   197  
   198  	Chan-typed go variables are really pointers. dereference them in gdb
   199  	to inspect their contents with this pretty printer.
   200  	"""
   201  
   202  	pattern = re.compile(r'^chan ')
   203  
   204  	def __init__(self, val):
   205  		self.val = val
   206  
   207  	def display_hint(self):
   208  		return 'array'
   209  
   210  	def to_string(self):
   211  		return str(self.val.type)
   212  
   213  	def children(self):
   214  		# see chan.c chanbuf(). et is the type stolen from hchan<T>::recvq->first->elem
   215  		et = [x.type for x in self.val['recvq']['first'].type.target().fields() if x.name == 'elem'][0]
   216  		ptr = (self.val.address["buf"]).cast(et)
   217  		for i in range(self.val["qcount"]):
   218  			j = (self.val["recvx"] + i) % self.val["dataqsiz"]
   219  			yield ('[{0}]'.format(i), (ptr + j).dereference())
   220  
   221  
   222  def paramtypematch(t, pattern):
   223  	return t.code == gdb.TYPE_CODE_TYPEDEF and str(t).startswith(".param") and pattern.match(str(t.target()))
   224  
   225  #
   226  #  Register all the *Printer classes above.
   227  #
   228  
   229  def makematcher(klass):
   230  	def matcher(val):
   231  		try:
   232  			if klass.pattern.match(str(val.type)):
   233  				return klass(val)
   234  			elif paramtypematch(val.type, klass.pattern):
   235  				return klass(val.cast(val.type.target()))
   236  		except Exception:
   237  			pass
   238  	return matcher
   239  
   240  goobjfile.pretty_printers.extend([makematcher(var) for var in vars().values() if hasattr(var, 'pattern')])
   241  #
   242  #  Utilities
   243  #
   244  
   245  def pc_to_int(pc):
   246  	# python2 will not cast pc (type void*) to an int cleanly
   247  	# instead python2 and python3 work with the hex string representation
   248  	# of the void pointer which we can parse back into an int.
   249  	# int(pc) will not work.
   250  	try:
   251  		# python3 / newer versions of gdb
   252  		pc = int(pc)
   253  	except gdb.error:
   254  		# str(pc) can return things like
   255  		# "0x429d6c <runtime.gopark+284>", so
   256  		# chop at first space.
   257  		pc = int(str(pc).split(None, 1)[0], 16)
   258  	return pc
   259  
   260  
   261  #
   262  #  For reference, this is what we're trying to do:
   263  #  eface: p *(*(struct 'runtime.rtype'*)'main.e'->type_->data)->string
   264  #  iface: p *(*(struct 'runtime.rtype'*)'main.s'->tab->Type->data)->string
   265  #
   266  # interface types can't be recognized by their name, instead we check
   267  # if they have the expected fields.  Unfortunately the mapping of
   268  # fields to python attributes in gdb.py isn't complete: you can't test
   269  # for presence other than by trapping.
   270  
   271  
   272  def is_iface(val):
   273  	try:
   274  		return str(val['tab'].type) == "struct runtime.itab *" and str(val['data'].type) == "void *"
   275  	except gdb.error:
   276  		pass
   277  
   278  
   279  def is_eface(val):
   280  	try:
   281  		return str(val['_type'].type) == "struct runtime._type *" and str(val['data'].type) == "void *"
   282  	except gdb.error:
   283  		pass
   284  
   285  
   286  def lookup_type(name):
   287  	try:
   288  		return gdb.lookup_type(name)
   289  	except gdb.error:
   290  		pass
   291  	try:
   292  		return gdb.lookup_type('struct ' + name)
   293  	except gdb.error:
   294  		pass
   295  	try:
   296  		return gdb.lookup_type('struct ' + name[1:]).pointer()
   297  	except gdb.error:
   298  		pass
   299  
   300  
   301  def iface_commontype(obj):
   302  	if is_iface(obj):
   303  		go_type_ptr = obj['tab']['_type']
   304  	elif is_eface(obj):
   305  		go_type_ptr = obj['_type']
   306  	else:
   307  		return
   308  
   309  	return go_type_ptr.cast(gdb.lookup_type("struct reflect.rtype").pointer()).dereference()
   310  
   311  
   312  def iface_dtype(obj):
   313  	"Decode type of the data field of an eface or iface struct."
   314  	# known issue: dtype_name decoded from runtime.rtype is "nested.Foo"
   315  	# but the dwarf table lists it as "full/path/to/nested.Foo"
   316  
   317  	dynamic_go_type = iface_commontype(obj)
   318  	if dynamic_go_type is None:
   319  		return
   320  	dtype_name = dynamic_go_type['string'].dereference()['str'].string()
   321  
   322  	dynamic_gdb_type = lookup_type(dtype_name)
   323  	if dynamic_gdb_type is None:
   324  		return
   325  
   326  	type_size = int(dynamic_go_type['size'])
   327  	uintptr_size = int(dynamic_go_type['size'].type.sizeof)	 # size is itself an uintptr
   328  	if type_size > uintptr_size:
   329  			dynamic_gdb_type = dynamic_gdb_type.pointer()
   330  
   331  	return dynamic_gdb_type
   332  
   333  
   334  def iface_dtype_name(obj):
   335  	"Decode type name of the data field of an eface or iface struct."
   336  
   337  	dynamic_go_type = iface_commontype(obj)
   338  	if dynamic_go_type is None:
   339  		return
   340  	return dynamic_go_type['string'].dereference()['str'].string()
   341  
   342  
   343  class IfacePrinter:
   344  	"""Pretty print interface values
   345  
   346  	Casts the data field to the appropriate dynamic type."""
   347  
   348  	def __init__(self, val):
   349  		self.val = val
   350  
   351  	def display_hint(self):
   352  		return 'string'
   353  
   354  	def to_string(self):
   355  		if self.val['data'] == 0:
   356  			return 0x0
   357  		try:
   358  			dtype = iface_dtype(self.val)
   359  		except Exception:
   360  			return "<bad dynamic type>"
   361  
   362  		if dtype is None:  # trouble looking up, print something reasonable
   363  			return "({typename}){data}".format(
   364  				typename=iface_dtype_name(self.val), data=self.val['data'])
   365  
   366  		try:
   367  			return self.val['data'].cast(dtype).dereference()
   368  		except Exception:
   369  			pass
   370  		return self.val['data'].cast(dtype)
   371  
   372  
   373  def ifacematcher(val):
   374  	if is_iface(val) or is_eface(val):
   375  		return IfacePrinter(val)
   376  
   377  goobjfile.pretty_printers.append(ifacematcher)
   378  
   379  #
   380  #  Convenience Functions
   381  #
   382  
   383  
   384  class GoLenFunc(gdb.Function):
   385  	"Length of strings, slices, maps or channels"
   386  
   387  	how = ((StringTypePrinter, 'len'), (SliceTypePrinter, 'len'), (MapTypePrinter, 'count'), (ChanTypePrinter, 'qcount'))
   388  
   389  	def __init__(self):
   390  		gdb.Function.__init__(self, "len")
   391  
   392  	def invoke(self, obj):
   393  		typename = str(obj.type)
   394  		for klass, fld in self.how:
   395  			if klass.pattern.match(typename) or paramtypematch(obj.type, klass.pattern):
   396  				return obj[fld]
   397  
   398  
   399  class GoCapFunc(gdb.Function):
   400  	"Capacity of slices or channels"
   401  
   402  	how = ((SliceTypePrinter, 'cap'), (ChanTypePrinter, 'dataqsiz'))
   403  
   404  	def __init__(self):
   405  		gdb.Function.__init__(self, "cap")
   406  
   407  	def invoke(self, obj):
   408  		typename = str(obj.type)
   409  		for klass, fld in self.how:
   410  			if klass.pattern.match(typename) or paramtypematch(obj.type, klass.pattern):
   411  				return obj[fld]
   412  
   413  
   414  class DTypeFunc(gdb.Function):
   415  	"""Cast Interface values to their dynamic type.
   416  
   417  	For non-interface types this behaves as the identity operation.
   418  	"""
   419  
   420  	def __init__(self):
   421  		gdb.Function.__init__(self, "dtype")
   422  
   423  	def invoke(self, obj):
   424  		try:
   425  			return obj['data'].cast(iface_dtype(obj))
   426  		except gdb.error:
   427  			pass
   428  		return obj
   429  
   430  #
   431  #  Commands
   432  #
   433  
   434  def linked_list(ptr, linkfield):
   435  	while ptr:
   436  		yield ptr
   437  		ptr = ptr[linkfield]
   438  
   439  
   440  class GoroutinesCmd(gdb.Command):
   441  	"List all goroutines."
   442  
   443  	def __init__(self):
   444  		gdb.Command.__init__(self, "info goroutines", gdb.COMMAND_STACK, gdb.COMPLETE_NONE)
   445  
   446  	def invoke(self, _arg, _from_tty):
   447  		# args = gdb.string_to_argv(arg)
   448  		vp = gdb.lookup_type('void').pointer()
   449  		for ptr in SliceValue(gdb.parse_and_eval("'runtime.allgs'")):
   450  			if ptr['atomicstatus'] == G_DEAD:
   451  				continue
   452  			s = ' '
   453  			if ptr['m']:
   454  				s = '*'
   455  			pc = ptr['sched']['pc'].cast(vp)
   456  			pc = pc_to_int(pc)
   457  			blk = gdb.block_for_pc(pc)
   458  			status = int(ptr['atomicstatus'])
   459  			st = sts.get(status, "unknown(%d)" % status)
   460  			print(s, ptr['goid'], "{0:8s}".format(st), blk.function)
   461  
   462  
   463  def find_goroutine(goid):
   464  	"""
   465  	find_goroutine attempts to find the goroutine identified by goid.
   466  	It returns a tuple of gdb.Value's representing the stack pointer
   467  	and program counter pointer for the goroutine.
   468  
   469  	@param int goid
   470  
   471  	@return tuple (gdb.Value, gdb.Value)
   472  	"""
   473  	vp = gdb.lookup_type('void').pointer()
   474  	for ptr in SliceValue(gdb.parse_and_eval("'runtime.allgs'")):
   475  		if ptr['atomicstatus'] == G_DEAD:
   476  			continue
   477  		if ptr['goid'] == goid:
   478  			break
   479  	else:
   480  		return None, None
   481  	# Get the goroutine's saved state.
   482  	pc, sp = ptr['sched']['pc'], ptr['sched']['sp']
   483  	status = ptr['atomicstatus']&~G_SCAN
   484  	# Goroutine is not running nor in syscall, so use the info in goroutine
   485  	if status != G_RUNNING and status != G_SYSCALL:
   486  		return pc.cast(vp), sp.cast(vp)
   487  
   488  	# If the goroutine is in a syscall, use syscallpc/sp.
   489  	pc, sp = ptr['syscallpc'], ptr['syscallsp']
   490  	if sp != 0:
   491  		return pc.cast(vp), sp.cast(vp)
   492  	# Otherwise, the goroutine is running, so it doesn't have
   493  	# saved scheduler state. Find G's OS thread.
   494  	m = ptr['m']
   495  	if m == 0:
   496  		return None, None
   497  	for thr in gdb.selected_inferior().threads():
   498  		if thr.ptid[1] == m['procid']:
   499  			break
   500  	else:
   501  		return None, None
   502  	# Get scheduler state from the G's OS thread state.
   503  	curthr = gdb.selected_thread()
   504  	try:
   505  		thr.switch()
   506  		pc = gdb.parse_and_eval('$pc')
   507  		sp = gdb.parse_and_eval('$sp')
   508  	finally:
   509  		curthr.switch()
   510  	return pc.cast(vp), sp.cast(vp)
   511  
   512  
   513  class GoroutineCmd(gdb.Command):
   514  	"""Execute gdb command in the context of goroutine <goid>.
   515  
   516  	Switch PC and SP to the ones in the goroutine's G structure,
   517  	execute an arbitrary gdb command, and restore PC and SP.
   518  
   519  	Usage: (gdb) goroutine <goid> <gdbcmd>
   520  
   521  	You could pass "all" as <goid> to apply <gdbcmd> to all goroutines.
   522  
   523  	For example: (gdb) goroutine all <gdbcmd>
   524  
   525  	Note that it is ill-defined to modify state in the context of a goroutine.
   526  	Restrict yourself to inspecting values.
   527  	"""
   528  
   529  	def __init__(self):
   530  		gdb.Command.__init__(self, "goroutine", gdb.COMMAND_STACK, gdb.COMPLETE_NONE)
   531  
   532  	def invoke(self, arg, _from_tty):
   533  		goid_str, cmd = arg.split(None, 1)
   534  		goids = []
   535  
   536  		if goid_str == 'all':
   537  			for ptr in SliceValue(gdb.parse_and_eval("'runtime.allgs'")):
   538  				goids.append(int(ptr['goid']))
   539  		else:
   540  			goids = [int(gdb.parse_and_eval(goid_str))]
   541  
   542  		for goid in goids:
   543  			self.invoke_per_goid(goid, cmd)
   544  
   545  	def invoke_per_goid(self, goid, cmd):
   546  		pc, sp = find_goroutine(goid)
   547  		if not pc:
   548  			print("No such goroutine: ", goid)
   549  			return
   550  		pc = pc_to_int(pc)
   551  		save_frame = gdb.selected_frame()
   552  		gdb.parse_and_eval('$save_sp = $sp')
   553  		gdb.parse_and_eval('$save_pc = $pc')
   554  		# In GDB, assignments to sp must be done from the
   555  		# top-most frame, so select frame 0 first.
   556  		gdb.execute('select-frame 0')
   557  		gdb.parse_and_eval('$sp = {0}'.format(str(sp)))
   558  		gdb.parse_and_eval('$pc = {0}'.format(str(pc)))
   559  		try:
   560  			gdb.execute(cmd)
   561  		finally:
   562  			# In GDB, assignments to sp must be done from the
   563  			# top-most frame, so select frame 0 first.
   564  			gdb.execute('select-frame 0')
   565  			gdb.parse_and_eval('$pc = $save_pc')
   566  			gdb.parse_and_eval('$sp = $save_sp')
   567  			save_frame.select()
   568  
   569  
   570  class GoIfaceCmd(gdb.Command):
   571  	"Print Static and dynamic interface types"
   572  
   573  	def __init__(self):
   574  		gdb.Command.__init__(self, "iface", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)
   575  
   576  	def invoke(self, arg, _from_tty):
   577  		for obj in gdb.string_to_argv(arg):
   578  			try:
   579  				#TODO fix quoting for qualified variable names
   580  				obj = gdb.parse_and_eval(str(obj))
   581  			except Exception as e:
   582  				print("Can't parse ", obj, ": ", e)
   583  				continue
   584  
   585  			if obj['data'] == 0:
   586  				dtype = "nil"
   587  			else:
   588  				dtype = iface_dtype(obj)
   589  
   590  			if dtype is None:
   591  				print("Not an interface: ", obj.type)
   592  				continue
   593  
   594  			print("{0}: {1}".format(obj.type, dtype))
   595  
   596  # TODO: print interface's methods and dynamic type's func pointers thereof.
   597  #rsc: "to find the number of entries in the itab's Fn field look at
   598  # itab.inter->numMethods
   599  # i am sure i have the names wrong but look at the interface type
   600  # and its method count"
   601  # so Itype will start with a commontype which has kind = interface
   602  
   603  #
   604  # Register all convenience functions and CLI commands
   605  #
   606  GoLenFunc()
   607  GoCapFunc()
   608  DTypeFunc()
   609  GoroutinesCmd()
   610  GoroutineCmd()
   611  GoIfaceCmd()
   612  

View as plain text