Black Lives Matter. Support the Equal Justice Initiative.

Text file src/runtime/runtime-gdb.py

Documentation: runtime

     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
     7This script is loaded by GDB when it finds a .debug_gdb_scripts
     8section in the compiled binary. The [68]l linkers emit this with a
     9path 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
    18from __future__ import print_function
    19import re
    20import sys
    21import gdb
    22
    23print("Loading Go Runtime support.", file=sys.stderr)
    24#http://python3porting.com/differences.html
    25if sys.version > '3':
    26	xrange = range
    27# allow to manually reload while developing
    28goobjfile = gdb.current_objfile() or gdb.objfiles()[0]
    29goobjfile.pretty_printers = []
    30
    31# G state (runtime2.go)
    32
    33def read_runtime_const(varname, default):
    34  try:
    35    return int(gdb.parse_and_eval(varname))
    36  except Exception:
    37    return int(default)
    38
    39
    40G_IDLE = read_runtime_const("'runtime._Gidle'", 0)
    41G_RUNNABLE = read_runtime_const("'runtime._Grunnable'", 1)
    42G_RUNNING = read_runtime_const("'runtime._Grunning'", 2)
    43G_SYSCALL = read_runtime_const("'runtime._Gsyscall'", 3)
    44G_WAITING = read_runtime_const("'runtime._Gwaiting'", 4)
    45G_MORIBUND_UNUSED = read_runtime_const("'runtime._Gmoribund_unused'", 5)
    46G_DEAD = read_runtime_const("'runtime._Gdead'", 6)
    47G_ENQUEUE_UNUSED = read_runtime_const("'runtime._Genqueue_unused'", 7)
    48G_COPYSTACK = read_runtime_const("'runtime._Gcopystack'", 8)
    49G_SCAN = read_runtime_const("'runtime._Gscan'", 0x1000)
    50G_SCANRUNNABLE = G_SCAN+G_RUNNABLE
    51G_SCANRUNNING = G_SCAN+G_RUNNING
    52G_SCANSYSCALL = G_SCAN+G_SYSCALL
    53G_SCANWAITING = G_SCAN+G_WAITING
    54
    55sts = {
    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
    77class 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.
   103class 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
   119class 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
   144class 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
   195class 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#
   223#  Register all the *Printer classes above.
   224#
   225
   226def makematcher(klass):
   227	def matcher(val):
   228		try:
   229			if klass.pattern.match(str(val.type)):
   230				return klass(val)
   231		except Exception:
   232			pass
   233	return matcher
   234
   235goobjfile.pretty_printers.extend([makematcher(var) for var in vars().values() if hasattr(var, 'pattern')])
   236#
   237#  Utilities
   238#
   239
   240def pc_to_int(pc):
   241	# python2 will not cast pc (type void*) to an int cleanly
   242	# instead python2 and python3 work with the hex string representation
   243	# of the void pointer which we can parse back into an int.
   244	# int(pc) will not work.
   245	try:
   246		# python3 / newer versions of gdb
   247		pc = int(pc)
   248	except gdb.error:
   249		# str(pc) can return things like
   250		# "0x429d6c <runtime.gopark+284>", so
   251		# chop at first space.
   252		pc = int(str(pc).split(None, 1)[0], 16)
   253	return pc
   254
   255
   256#
   257#  For reference, this is what we're trying to do:
   258#  eface: p *(*(struct 'runtime.rtype'*)'main.e'->type_->data)->string
   259#  iface: p *(*(struct 'runtime.rtype'*)'main.s'->tab->Type->data)->string
   260#
   261# interface types can't be recognized by their name, instead we check
   262# if they have the expected fields.  Unfortunately the mapping of
   263# fields to python attributes in gdb.py isn't complete: you can't test
   264# for presence other than by trapping.
   265
   266
   267def is_iface(val):
   268	try:
   269		return str(val['tab'].type) == "struct runtime.itab *" and str(val['data'].type) == "void *"
   270	except gdb.error:
   271		pass
   272
   273
   274def is_eface(val):
   275	try:
   276		return str(val['_type'].type) == "struct runtime._type *" and str(val['data'].type) == "void *"
   277	except gdb.error:
   278		pass
   279
   280
   281def lookup_type(name):
   282	try:
   283		return gdb.lookup_type(name)
   284	except gdb.error:
   285		pass
   286	try:
   287		return gdb.lookup_type('struct ' + name)
   288	except gdb.error:
   289		pass
   290	try:
   291		return gdb.lookup_type('struct ' + name[1:]).pointer()
   292	except gdb.error:
   293		pass
   294
   295
   296def iface_commontype(obj):
   297	if is_iface(obj):
   298		go_type_ptr = obj['tab']['_type']
   299	elif is_eface(obj):
   300		go_type_ptr = obj['_type']
   301	else:
   302		return
   303
   304	return go_type_ptr.cast(gdb.lookup_type("struct reflect.rtype").pointer()).dereference()
   305
   306
   307def iface_dtype(obj):
   308	"Decode type of the data field of an eface or iface struct."
   309	# known issue: dtype_name decoded from runtime.rtype is "nested.Foo"
   310	# but the dwarf table lists it as "full/path/to/nested.Foo"
   311
   312	dynamic_go_type = iface_commontype(obj)
   313	if dynamic_go_type is None:
   314		return
   315	dtype_name = dynamic_go_type['string'].dereference()['str'].string()
   316
   317	dynamic_gdb_type = lookup_type(dtype_name)
   318	if dynamic_gdb_type is None:
   319		return
   320
   321	type_size = int(dynamic_go_type['size'])
   322	uintptr_size = int(dynamic_go_type['size'].type.sizeof)	 # size is itself an uintptr
   323	if type_size > uintptr_size:
   324			dynamic_gdb_type = dynamic_gdb_type.pointer()
   325
   326	return dynamic_gdb_type
   327
   328
   329def iface_dtype_name(obj):
   330	"Decode type name of the data field of an eface or iface struct."
   331
   332	dynamic_go_type = iface_commontype(obj)
   333	if dynamic_go_type is None:
   334		return
   335	return dynamic_go_type['string'].dereference()['str'].string()
   336
   337
   338class IfacePrinter:
   339	"""Pretty print interface values
   340
   341	Casts the data field to the appropriate dynamic type."""
   342
   343	def __init__(self, val):
   344		self.val = val
   345
   346	def display_hint(self):
   347		return 'string'
   348
   349	def to_string(self):
   350		if self.val['data'] == 0:
   351			return 0x0
   352		try:
   353			dtype = iface_dtype(self.val)
   354		except Exception:
   355			return "<bad dynamic type>"
   356
   357		if dtype is None:  # trouble looking up, print something reasonable
   358			return "({typename}){data}".format(
   359				typename=iface_dtype_name(self.val), data=self.val['data'])
   360
   361		try:
   362			return self.val['data'].cast(dtype).dereference()
   363		except Exception:
   364			pass
   365		return self.val['data'].cast(dtype)
   366
   367
   368def ifacematcher(val):
   369	if is_iface(val) or is_eface(val):
   370		return IfacePrinter(val)
   371
   372goobjfile.pretty_printers.append(ifacematcher)
   373
   374#
   375#  Convenience Functions
   376#
   377
   378
   379class GoLenFunc(gdb.Function):
   380	"Length of strings, slices, maps or channels"
   381
   382	how = ((StringTypePrinter, 'len'), (SliceTypePrinter, 'len'), (MapTypePrinter, 'count'), (ChanTypePrinter, 'qcount'))
   383
   384	def __init__(self):
   385		gdb.Function.__init__(self, "len")
   386
   387	def invoke(self, obj):
   388		typename = str(obj.type)
   389		for klass, fld in self.how:
   390			if klass.pattern.match(typename):
   391				return obj[fld]
   392
   393
   394class GoCapFunc(gdb.Function):
   395	"Capacity of slices or channels"
   396
   397	how = ((SliceTypePrinter, 'cap'), (ChanTypePrinter, 'dataqsiz'))
   398
   399	def __init__(self):
   400		gdb.Function.__init__(self, "cap")
   401
   402	def invoke(self, obj):
   403		typename = str(obj.type)
   404		for klass, fld in self.how:
   405			if klass.pattern.match(typename):
   406				return obj[fld]
   407
   408
   409class DTypeFunc(gdb.Function):
   410	"""Cast Interface values to their dynamic type.
   411
   412	For non-interface types this behaves as the identity operation.
   413	"""
   414
   415	def __init__(self):
   416		gdb.Function.__init__(self, "dtype")
   417
   418	def invoke(self, obj):
   419		try:
   420			return obj['data'].cast(iface_dtype(obj))
   421		except gdb.error:
   422			pass
   423		return obj
   424
   425#
   426#  Commands
   427#
   428
   429def linked_list(ptr, linkfield):
   430	while ptr:
   431		yield ptr
   432		ptr = ptr[linkfield]
   433
   434
   435class GoroutinesCmd(gdb.Command):
   436	"List all goroutines."
   437
   438	def __init__(self):
   439		gdb.Command.__init__(self, "info goroutines", gdb.COMMAND_STACK, gdb.COMPLETE_NONE)
   440
   441	def invoke(self, _arg, _from_tty):
   442		# args = gdb.string_to_argv(arg)
   443		vp = gdb.lookup_type('void').pointer()
   444		for ptr in SliceValue(gdb.parse_and_eval("'runtime.allgs'")):
   445			if ptr['atomicstatus'] == G_DEAD:
   446				continue
   447			s = ' '
   448			if ptr['m']:
   449				s = '*'
   450			pc = ptr['sched']['pc'].cast(vp)
   451			pc = pc_to_int(pc)
   452			blk = gdb.block_for_pc(pc)
   453			status = int(ptr['atomicstatus'])
   454			st = sts.get(status, "unknown(%d)" % status)
   455			print(s, ptr['goid'], "{0:8s}".format(st), blk.function)
   456
   457
   458def find_goroutine(goid):
   459	"""
   460	find_goroutine attempts to find the goroutine identified by goid.
   461	It returns a tuple of gdb.Value's representing the stack pointer
   462	and program counter pointer for the goroutine.
   463
   464	@param int goid
   465
   466	@return tuple (gdb.Value, gdb.Value)
   467	"""
   468	vp = gdb.lookup_type('void').pointer()
   469	for ptr in SliceValue(gdb.parse_and_eval("'runtime.allgs'")):
   470		if ptr['atomicstatus'] == G_DEAD:
   471			continue
   472		if ptr['goid'] == goid:
   473			break
   474	else:
   475		return None, None
   476	# Get the goroutine's saved state.
   477	pc, sp = ptr['sched']['pc'], ptr['sched']['sp']
   478	status = ptr['atomicstatus']&~G_SCAN
   479	# Goroutine is not running nor in syscall, so use the info in goroutine
   480	if status != G_RUNNING and status != G_SYSCALL:
   481		return pc.cast(vp), sp.cast(vp)
   482
   483	# If the goroutine is in a syscall, use syscallpc/sp.
   484	pc, sp = ptr['syscallpc'], ptr['syscallsp']
   485	if sp != 0:
   486		return pc.cast(vp), sp.cast(vp)
   487	# Otherwise, the goroutine is running, so it doesn't have
   488	# saved scheduler state. Find G's OS thread.
   489	m = ptr['m']
   490	if m == 0:
   491		return None, None
   492	for thr in gdb.selected_inferior().threads():
   493		if thr.ptid[1] == m['procid']:
   494			break
   495	else:
   496		return None, None
   497	# Get scheduler state from the G's OS thread state.
   498	curthr = gdb.selected_thread()
   499	try:
   500		thr.switch()
   501		pc = gdb.parse_and_eval('$pc')
   502		sp = gdb.parse_and_eval('$sp')
   503	finally:
   504		curthr.switch()
   505	return pc.cast(vp), sp.cast(vp)
   506
   507
   508class GoroutineCmd(gdb.Command):
   509	"""Execute gdb command in the context of goroutine <goid>.
   510
   511	Switch PC and SP to the ones in the goroutine's G structure,
   512	execute an arbitrary gdb command, and restore PC and SP.
   513
   514	Usage: (gdb) goroutine <goid> <gdbcmd>
   515
   516	You could pass "all" as <goid> to apply <gdbcmd> to all goroutines.
   517
   518	For example: (gdb) goroutine all <gdbcmd>
   519
   520	Note that it is ill-defined to modify state in the context of a goroutine.
   521	Restrict yourself to inspecting values.
   522	"""
   523
   524	def __init__(self):
   525		gdb.Command.__init__(self, "goroutine", gdb.COMMAND_STACK, gdb.COMPLETE_NONE)
   526
   527	def invoke(self, arg, _from_tty):
   528		goid_str, cmd = arg.split(None, 1)
   529		goids = []
   530
   531		if goid_str == 'all':
   532			for ptr in SliceValue(gdb.parse_and_eval("'runtime.allgs'")):
   533				goids.append(int(ptr['goid']))
   534		else:
   535			goids = [int(gdb.parse_and_eval(goid_str))]
   536
   537		for goid in goids:
   538			self.invoke_per_goid(goid, cmd)
   539
   540	def invoke_per_goid(self, goid, cmd):
   541		pc, sp = find_goroutine(goid)
   542		if not pc:
   543			print("No such goroutine: ", goid)
   544			return
   545		pc = pc_to_int(pc)
   546		save_frame = gdb.selected_frame()
   547		gdb.parse_and_eval('$save_sp = $sp')
   548		gdb.parse_and_eval('$save_pc = $pc')
   549		# In GDB, assignments to sp must be done from the
   550		# top-most frame, so select frame 0 first.
   551		gdb.execute('select-frame 0')
   552		gdb.parse_and_eval('$sp = {0}'.format(str(sp)))
   553		gdb.parse_and_eval('$pc = {0}'.format(str(pc)))
   554		try:
   555			gdb.execute(cmd)
   556		finally:
   557			# In GDB, assignments to sp must be done from the
   558			# top-most frame, so select frame 0 first.
   559			gdb.execute('select-frame 0')
   560			gdb.parse_and_eval('$pc = $save_pc')
   561			gdb.parse_and_eval('$sp = $save_sp')
   562			save_frame.select()
   563
   564
   565class GoIfaceCmd(gdb.Command):
   566	"Print Static and dynamic interface types"
   567
   568	def __init__(self):
   569		gdb.Command.__init__(self, "iface", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)
   570
   571	def invoke(self, arg, _from_tty):
   572		for obj in gdb.string_to_argv(arg):
   573			try:
   574				#TODO fix quoting for qualified variable names
   575				obj = gdb.parse_and_eval(str(obj))
   576			except Exception as e:
   577				print("Can't parse ", obj, ": ", e)
   578				continue
   579
   580			if obj['data'] == 0:
   581				dtype = "nil"
   582			else:
   583				dtype = iface_dtype(obj)
   584
   585			if dtype is None:
   586				print("Not an interface: ", obj.type)
   587				continue
   588
   589			print("{0}: {1}".format(obj.type, dtype))
   590
   591# TODO: print interface's methods and dynamic type's func pointers thereof.
   592#rsc: "to find the number of entries in the itab's Fn field look at
   593# itab.inter->numMethods
   594# i am sure i have the names wrong but look at the interface type
   595# and its method count"
   596# so Itype will start with a commontype which has kind = interface
   597
   598#
   599# Register all convenience functions and CLI commands
   600#
   601GoLenFunc()
   602GoCapFunc()
   603DTypeFunc()
   604GoroutinesCmd()
   605GoroutineCmd()
   606GoIfaceCmd()

View as plain text