Source file src/cmd/link/internal/ld/dwarf.go

     1  // Copyright 2019 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  // TODO/NICETOHAVE:
     6  //   - eliminate DW_CLS_ if not used
     7  //   - package info in compilation units
     8  //   - assign types to their packages
     9  //   - gdb uses c syntax, meaning clumsy quoting is needed for go identifiers. eg
    10  //     ptype struct '[]uint8' and qualifiers need to be quoted away
    11  //   - file:line info for variables
    12  //   - make strings a typedef so prettyprinters can see the underlying string type
    13  
    14  package ld
    15  
    16  import (
    17  	"cmd/internal/dwarf"
    18  	"cmd/internal/obj"
    19  	"cmd/internal/objabi"
    20  	"cmd/internal/src"
    21  	"cmd/internal/sys"
    22  	"cmd/link/internal/loader"
    23  	"cmd/link/internal/sym"
    24  	"fmt"
    25  	"internal/buildcfg"
    26  	"log"
    27  	"path"
    28  	"runtime"
    29  	"sort"
    30  	"strings"
    31  	"sync"
    32  )
    33  
    34  // dwctxt is a wrapper intended to satisfy the method set of
    35  // dwarf.Context, so that functions like dwarf.PutAttrs will work with
    36  // DIEs that use loader.Sym as opposed to *sym.Symbol. It is also
    37  // being used as a place to store tables/maps that are useful as part
    38  // of type conversion (this is just a convenience; it would be easy to
    39  // split these things out into another type if need be).
    40  type dwctxt struct {
    41  	linkctxt *Link
    42  	ldr      *loader.Loader
    43  	arch     *sys.Arch
    44  
    45  	// This maps type name string (e.g. "uintptr") to loader symbol for
    46  	// the DWARF DIE for that type (e.g. "go.info.type.uintptr")
    47  	tmap map[string]loader.Sym
    48  
    49  	// This maps loader symbol for the DWARF DIE symbol generated for
    50  	// a type (e.g. "go.info.uintptr") to the type symbol itself
    51  	// ("type.uintptr").
    52  	// FIXME: try converting this map (and the next one) to a single
    53  	// array indexed by loader.Sym -- this may perform better.
    54  	rtmap map[loader.Sym]loader.Sym
    55  
    56  	// This maps Go type symbol (e.g. "type.XXX") to loader symbol for
    57  	// the typedef DIE for that type (e.g. "go.info.XXX..def")
    58  	tdmap map[loader.Sym]loader.Sym
    59  
    60  	// Cache these type symbols, so as to avoid repeatedly looking them up
    61  	typeRuntimeEface loader.Sym
    62  	typeRuntimeIface loader.Sym
    63  	uintptrInfoSym   loader.Sym
    64  
    65  	// Used at various points in that parallel portion of DWARF gen to
    66  	// protect against conflicting updates to globals (such as "gdbscript")
    67  	dwmu *sync.Mutex
    68  }
    69  
    70  // dwSym wraps a loader.Sym; this type is meant to obey the interface
    71  // rules for dwarf.Sym from the cmd/internal/dwarf package. DwDie and
    72  // DwAttr objects contain references to symbols via this type.
    73  type dwSym loader.Sym
    74  
    75  func (s dwSym) Length(dwarfContext interface{}) int64 {
    76  	l := dwarfContext.(dwctxt).ldr
    77  	return int64(len(l.Data(loader.Sym(s))))
    78  }
    79  
    80  func (c dwctxt) PtrSize() int {
    81  	return c.arch.PtrSize
    82  }
    83  
    84  func (c dwctxt) AddInt(s dwarf.Sym, size int, i int64) {
    85  	ds := loader.Sym(s.(dwSym))
    86  	dsu := c.ldr.MakeSymbolUpdater(ds)
    87  	dsu.AddUintXX(c.arch, uint64(i), size)
    88  }
    89  
    90  func (c dwctxt) AddBytes(s dwarf.Sym, b []byte) {
    91  	ds := loader.Sym(s.(dwSym))
    92  	dsu := c.ldr.MakeSymbolUpdater(ds)
    93  	dsu.AddBytes(b)
    94  }
    95  
    96  func (c dwctxt) AddString(s dwarf.Sym, v string) {
    97  	ds := loader.Sym(s.(dwSym))
    98  	dsu := c.ldr.MakeSymbolUpdater(ds)
    99  	dsu.Addstring(v)
   100  }
   101  
   102  func (c dwctxt) AddAddress(s dwarf.Sym, data interface{}, value int64) {
   103  	ds := loader.Sym(s.(dwSym))
   104  	dsu := c.ldr.MakeSymbolUpdater(ds)
   105  	if value != 0 {
   106  		value -= dsu.Value()
   107  	}
   108  	tgtds := loader.Sym(data.(dwSym))
   109  	dsu.AddAddrPlus(c.arch, tgtds, value)
   110  }
   111  
   112  func (c dwctxt) AddCURelativeAddress(s dwarf.Sym, data interface{}, value int64) {
   113  	ds := loader.Sym(s.(dwSym))
   114  	dsu := c.ldr.MakeSymbolUpdater(ds)
   115  	if value != 0 {
   116  		value -= dsu.Value()
   117  	}
   118  	tgtds := loader.Sym(data.(dwSym))
   119  	dsu.AddCURelativeAddrPlus(c.arch, tgtds, value)
   120  }
   121  
   122  func (c dwctxt) AddSectionOffset(s dwarf.Sym, size int, t interface{}, ofs int64) {
   123  	ds := loader.Sym(s.(dwSym))
   124  	dsu := c.ldr.MakeSymbolUpdater(ds)
   125  	tds := loader.Sym(t.(dwSym))
   126  	switch size {
   127  	default:
   128  		c.linkctxt.Errorf(ds, "invalid size %d in adddwarfref\n", size)
   129  	case c.arch.PtrSize, 4:
   130  	}
   131  	dsu.AddSymRef(c.arch, tds, ofs, objabi.R_ADDROFF, size)
   132  }
   133  
   134  func (c dwctxt) AddDWARFAddrSectionOffset(s dwarf.Sym, t interface{}, ofs int64) {
   135  	size := 4
   136  	if isDwarf64(c.linkctxt) {
   137  		size = 8
   138  	}
   139  	ds := loader.Sym(s.(dwSym))
   140  	dsu := c.ldr.MakeSymbolUpdater(ds)
   141  	tds := loader.Sym(t.(dwSym))
   142  	switch size {
   143  	default:
   144  		c.linkctxt.Errorf(ds, "invalid size %d in adddwarfref\n", size)
   145  	case c.arch.PtrSize, 4:
   146  	}
   147  	dsu.AddSymRef(c.arch, tds, ofs, objabi.R_DWARFSECREF, size)
   148  }
   149  
   150  func (c dwctxt) Logf(format string, args ...interface{}) {
   151  	c.linkctxt.Logf(format, args...)
   152  }
   153  
   154  // At the moment these interfaces are only used in the compiler.
   155  
   156  func (c dwctxt) AddFileRef(s dwarf.Sym, f interface{}) {
   157  	panic("should be used only in the compiler")
   158  }
   159  
   160  func (c dwctxt) CurrentOffset(s dwarf.Sym) int64 {
   161  	panic("should be used only in the compiler")
   162  }
   163  
   164  func (c dwctxt) RecordDclReference(s dwarf.Sym, t dwarf.Sym, dclIdx int, inlIndex int) {
   165  	panic("should be used only in the compiler")
   166  }
   167  
   168  func (c dwctxt) RecordChildDieOffsets(s dwarf.Sym, vars []*dwarf.Var, offsets []int32) {
   169  	panic("should be used only in the compiler")
   170  }
   171  
   172  func isDwarf64(ctxt *Link) bool {
   173  	return ctxt.HeadType == objabi.Haix
   174  }
   175  
   176  // https://sourceware.org/gdb/onlinedocs/gdb/dotdebug_005fgdb_005fscripts-section.html
   177  // Each entry inside .debug_gdb_scripts section begins with a non-null prefix
   178  // byte that specifies the kind of entry. The following entries are supported:
   179  const (
   180  	GdbScriptPythonFileId = 1
   181  	GdbScriptSchemeFileId = 3
   182  	GdbScriptPythonTextId = 4
   183  	GdbScriptSchemeTextId = 6
   184  )
   185  
   186  var gdbscript string
   187  
   188  // dwarfSecInfo holds information about a DWARF output section,
   189  // specifically a section symbol and a list of symbols contained in
   190  // that section. On the syms list, the first symbol will always be the
   191  // section symbol, then any remaining symbols (if any) will be
   192  // sub-symbols in that section. Note that for some sections (eg:
   193  // .debug_abbrev), the section symbol is all there is (all content is
   194  // contained in it). For other sections (eg: .debug_info), the section
   195  // symbol is empty and all the content is in the sub-symbols. Finally
   196  // there are some sections (eg: .debug_ranges) where it is a mix (both
   197  // the section symbol and the sub-symbols have content)
   198  type dwarfSecInfo struct {
   199  	syms []loader.Sym
   200  }
   201  
   202  // secSym returns the section symbol for the section.
   203  func (dsi *dwarfSecInfo) secSym() loader.Sym {
   204  	if len(dsi.syms) == 0 {
   205  		return 0
   206  	}
   207  	return dsi.syms[0]
   208  }
   209  
   210  // subSyms returns a list of sub-symbols for the section.
   211  func (dsi *dwarfSecInfo) subSyms() []loader.Sym {
   212  	if len(dsi.syms) == 0 {
   213  		return []loader.Sym{}
   214  	}
   215  	return dsi.syms[1:]
   216  }
   217  
   218  // dwarfp stores the collected DWARF symbols created during
   219  // dwarf generation.
   220  var dwarfp []dwarfSecInfo
   221  
   222  func (d *dwctxt) writeabbrev() dwarfSecInfo {
   223  	abrvs := d.ldr.CreateSymForUpdate(".debug_abbrev", 0)
   224  	abrvs.SetType(sym.SDWARFSECT)
   225  	abrvs.AddBytes(dwarf.GetAbbrev())
   226  	return dwarfSecInfo{syms: []loader.Sym{abrvs.Sym()}}
   227  }
   228  
   229  var dwtypes dwarf.DWDie
   230  
   231  // newattr attaches a new attribute to the specified DIE.
   232  //
   233  // FIXME: at the moment attributes are stored in a linked list in a
   234  // fairly space-inefficient way -- it might be better to instead look
   235  // up all attrs in a single large table, then store indices into the
   236  // table in the DIE. This would allow us to common up storage for
   237  // attributes that are shared by many DIEs (ex: byte size of N).
   238  func newattr(die *dwarf.DWDie, attr uint16, cls int, value int64, data interface{}) {
   239  	a := new(dwarf.DWAttr)
   240  	a.Link = die.Attr
   241  	die.Attr = a
   242  	a.Atr = attr
   243  	a.Cls = uint8(cls)
   244  	a.Value = value
   245  	a.Data = data
   246  }
   247  
   248  // Each DIE (except the root ones) has at least 1 attribute: its
   249  // name. getattr moves the desired one to the front so
   250  // frequently searched ones are found faster.
   251  func getattr(die *dwarf.DWDie, attr uint16) *dwarf.DWAttr {
   252  	if die.Attr.Atr == attr {
   253  		return die.Attr
   254  	}
   255  
   256  	a := die.Attr
   257  	b := a.Link
   258  	for b != nil {
   259  		if b.Atr == attr {
   260  			a.Link = b.Link
   261  			b.Link = die.Attr
   262  			die.Attr = b
   263  			return b
   264  		}
   265  
   266  		a = b
   267  		b = b.Link
   268  	}
   269  
   270  	return nil
   271  }
   272  
   273  // Every DIE manufactured by the linker has at least an AT_name
   274  // attribute (but it will only be written out if it is listed in the abbrev).
   275  // The compiler does create nameless DWARF DIEs (ex: concrete subprogram
   276  // instance).
   277  // FIXME: it would be more efficient to bulk-allocate DIEs.
   278  func (d *dwctxt) newdie(parent *dwarf.DWDie, abbrev int, name string) *dwarf.DWDie {
   279  	die := new(dwarf.DWDie)
   280  	die.Abbrev = abbrev
   281  	die.Link = parent.Child
   282  	parent.Child = die
   283  
   284  	newattr(die, dwarf.DW_AT_name, dwarf.DW_CLS_STRING, int64(len(name)), name)
   285  
   286  	// Sanity check: all DIEs created in the linker should be named.
   287  	if name == "" {
   288  		panic("nameless DWARF DIE")
   289  	}
   290  
   291  	var st sym.SymKind
   292  	switch abbrev {
   293  	case dwarf.DW_ABRV_FUNCTYPEPARAM, dwarf.DW_ABRV_DOTDOTDOT, dwarf.DW_ABRV_STRUCTFIELD, dwarf.DW_ABRV_ARRAYRANGE:
   294  		// There are no relocations against these dies, and their names
   295  		// are not unique, so don't create a symbol.
   296  		return die
   297  	case dwarf.DW_ABRV_COMPUNIT, dwarf.DW_ABRV_COMPUNIT_TEXTLESS:
   298  		// Avoid collisions with "real" symbol names.
   299  		name = fmt.Sprintf(".pkg.%s.%d", name, len(d.linkctxt.compUnits))
   300  		st = sym.SDWARFCUINFO
   301  	case dwarf.DW_ABRV_VARIABLE:
   302  		st = sym.SDWARFVAR
   303  	default:
   304  		// Everything else is assigned a type of SDWARFTYPE. that
   305  		// this also includes loose ends such as STRUCT_FIELD.
   306  		st = sym.SDWARFTYPE
   307  	}
   308  	ds := d.ldr.LookupOrCreateSym(dwarf.InfoPrefix+name, 0)
   309  	dsu := d.ldr.MakeSymbolUpdater(ds)
   310  	dsu.SetType(st)
   311  	d.ldr.SetAttrNotInSymbolTable(ds, true)
   312  	d.ldr.SetAttrReachable(ds, true)
   313  	die.Sym = dwSym(ds)
   314  	if abbrev >= dwarf.DW_ABRV_NULLTYPE && abbrev <= dwarf.DW_ABRV_TYPEDECL {
   315  		d.tmap[name] = ds
   316  	}
   317  
   318  	return die
   319  }
   320  
   321  func walktypedef(die *dwarf.DWDie) *dwarf.DWDie {
   322  	if die == nil {
   323  		return nil
   324  	}
   325  	// Resolve typedef if present.
   326  	if die.Abbrev == dwarf.DW_ABRV_TYPEDECL {
   327  		for attr := die.Attr; attr != nil; attr = attr.Link {
   328  			if attr.Atr == dwarf.DW_AT_type && attr.Cls == dwarf.DW_CLS_REFERENCE && attr.Data != nil {
   329  				return attr.Data.(*dwarf.DWDie)
   330  			}
   331  		}
   332  	}
   333  
   334  	return die
   335  }
   336  
   337  func (d *dwctxt) walksymtypedef(symIdx loader.Sym) loader.Sym {
   338  
   339  	// We're being given the loader symbol for the type DIE, e.g.
   340  	// "go.info.type.uintptr". Map that first to the type symbol (e.g.
   341  	// "type.uintptr") and then to the typedef DIE for the type.
   342  	// FIXME: this seems clunky, maybe there is a better way to do this.
   343  
   344  	if ts, ok := d.rtmap[symIdx]; ok {
   345  		if def, ok := d.tdmap[ts]; ok {
   346  			return def
   347  		}
   348  		d.linkctxt.Errorf(ts, "internal error: no entry for sym %d in tdmap\n", ts)
   349  		return 0
   350  	}
   351  	d.linkctxt.Errorf(symIdx, "internal error: no entry for sym %d in rtmap\n", symIdx)
   352  	return 0
   353  }
   354  
   355  // Find child by AT_name using hashtable if available or linear scan
   356  // if not.
   357  func findchild(die *dwarf.DWDie, name string) *dwarf.DWDie {
   358  	var prev *dwarf.DWDie
   359  	for ; die != prev; prev, die = die, walktypedef(die) {
   360  		for a := die.Child; a != nil; a = a.Link {
   361  			if name == getattr(a, dwarf.DW_AT_name).Data {
   362  				return a
   363  			}
   364  		}
   365  		continue
   366  	}
   367  	return nil
   368  }
   369  
   370  // find looks up the loader symbol for the DWARF DIE generated for the
   371  // type with the specified name.
   372  func (d *dwctxt) find(name string) loader.Sym {
   373  	return d.tmap[name]
   374  }
   375  
   376  func (d *dwctxt) mustFind(name string) loader.Sym {
   377  	r := d.find(name)
   378  	if r == 0 {
   379  		Exitf("dwarf find: cannot find %s", name)
   380  	}
   381  	return r
   382  }
   383  
   384  func (d *dwctxt) adddwarfref(sb *loader.SymbolBuilder, t loader.Sym, size int) {
   385  	switch size {
   386  	default:
   387  		d.linkctxt.Errorf(sb.Sym(), "invalid size %d in adddwarfref\n", size)
   388  	case d.arch.PtrSize, 4:
   389  	}
   390  	sb.AddSymRef(d.arch, t, 0, objabi.R_DWARFSECREF, size)
   391  }
   392  
   393  func (d *dwctxt) newrefattr(die *dwarf.DWDie, attr uint16, ref loader.Sym) {
   394  	if ref == 0 {
   395  		return
   396  	}
   397  	newattr(die, attr, dwarf.DW_CLS_REFERENCE, 0, dwSym(ref))
   398  }
   399  
   400  func (d *dwctxt) dtolsym(s dwarf.Sym) loader.Sym {
   401  	if s == nil {
   402  		return 0
   403  	}
   404  	dws := loader.Sym(s.(dwSym))
   405  	return dws
   406  }
   407  
   408  func (d *dwctxt) putdie(syms []loader.Sym, die *dwarf.DWDie) []loader.Sym {
   409  	s := d.dtolsym(die.Sym)
   410  	if s == 0 {
   411  		s = syms[len(syms)-1]
   412  	} else {
   413  		syms = append(syms, s)
   414  	}
   415  	sDwsym := dwSym(s)
   416  	dwarf.Uleb128put(d, sDwsym, int64(die.Abbrev))
   417  	dwarf.PutAttrs(d, sDwsym, die.Abbrev, die.Attr)
   418  	if dwarf.HasChildren(die) {
   419  		for die := die.Child; die != nil; die = die.Link {
   420  			syms = d.putdie(syms, die)
   421  		}
   422  		dsu := d.ldr.MakeSymbolUpdater(syms[len(syms)-1])
   423  		dsu.AddUint8(0)
   424  	}
   425  	return syms
   426  }
   427  
   428  func reverselist(list **dwarf.DWDie) {
   429  	curr := *list
   430  	var prev *dwarf.DWDie
   431  	for curr != nil {
   432  		next := curr.Link
   433  		curr.Link = prev
   434  		prev = curr
   435  		curr = next
   436  	}
   437  
   438  	*list = prev
   439  }
   440  
   441  func reversetree(list **dwarf.DWDie) {
   442  	reverselist(list)
   443  	for die := *list; die != nil; die = die.Link {
   444  		if dwarf.HasChildren(die) {
   445  			reversetree(&die.Child)
   446  		}
   447  	}
   448  }
   449  
   450  func newmemberoffsetattr(die *dwarf.DWDie, offs int32) {
   451  	newattr(die, dwarf.DW_AT_data_member_location, dwarf.DW_CLS_CONSTANT, int64(offs), nil)
   452  }
   453  
   454  func (d *dwctxt) lookupOrDiag(n string) loader.Sym {
   455  	symIdx := d.ldr.Lookup(n, 0)
   456  	if symIdx == 0 {
   457  		Exitf("dwarf: missing type: %s", n)
   458  	}
   459  	if len(d.ldr.Data(symIdx)) == 0 {
   460  		Exitf("dwarf: missing type (no data): %s", n)
   461  	}
   462  
   463  	return symIdx
   464  }
   465  
   466  func (d *dwctxt) dotypedef(parent *dwarf.DWDie, name string, def *dwarf.DWDie) *dwarf.DWDie {
   467  	// Only emit typedefs for real names.
   468  	if strings.HasPrefix(name, "map[") {
   469  		return nil
   470  	}
   471  	if strings.HasPrefix(name, "struct {") {
   472  		return nil
   473  	}
   474  	// cmd/compile uses "noalg.struct {...}" as type name when hash and eq algorithm generation of
   475  	// this struct type is suppressed.
   476  	if strings.HasPrefix(name, "noalg.struct {") {
   477  		return nil
   478  	}
   479  	if strings.HasPrefix(name, "chan ") {
   480  		return nil
   481  	}
   482  	if name[0] == '[' || name[0] == '*' {
   483  		return nil
   484  	}
   485  	if def == nil {
   486  		Errorf(nil, "dwarf: bad def in dotypedef")
   487  	}
   488  
   489  	// Create a new loader symbol for the typedef. We no longer
   490  	// do lookups of typedef symbols by name, so this is going
   491  	// to be an anonymous symbol (we want this for perf reasons).
   492  	tds := d.ldr.CreateExtSym("", 0)
   493  	tdsu := d.ldr.MakeSymbolUpdater(tds)
   494  	tdsu.SetType(sym.SDWARFTYPE)
   495  	def.Sym = dwSym(tds)
   496  	d.ldr.SetAttrNotInSymbolTable(tds, true)
   497  	d.ldr.SetAttrReachable(tds, true)
   498  
   499  	// The typedef entry must be created after the def,
   500  	// so that future lookups will find the typedef instead
   501  	// of the real definition. This hooks the typedef into any
   502  	// circular definition loops, so that gdb can understand them.
   503  	die := d.newdie(parent, dwarf.DW_ABRV_TYPEDECL, name)
   504  
   505  	d.newrefattr(die, dwarf.DW_AT_type, tds)
   506  
   507  	return die
   508  }
   509  
   510  // Define gotype, for composite ones recurse into constituents.
   511  func (d *dwctxt) defgotype(gotype loader.Sym) loader.Sym {
   512  	if gotype == 0 {
   513  		return d.mustFind("<unspecified>")
   514  	}
   515  
   516  	// If we already have a tdmap entry for the gotype, return it.
   517  	if ds, ok := d.tdmap[gotype]; ok {
   518  		return ds
   519  	}
   520  
   521  	sn := d.ldr.SymName(gotype)
   522  	if !strings.HasPrefix(sn, "type.") {
   523  		d.linkctxt.Errorf(gotype, "dwarf: type name doesn't start with \"type.\"")
   524  		return d.mustFind("<unspecified>")
   525  	}
   526  	name := sn[5:] // could also decode from Type.string
   527  
   528  	sdie := d.find(name)
   529  	if sdie != 0 {
   530  		return sdie
   531  	}
   532  
   533  	gtdwSym := d.newtype(gotype)
   534  	d.tdmap[gotype] = loader.Sym(gtdwSym.Sym.(dwSym))
   535  	return loader.Sym(gtdwSym.Sym.(dwSym))
   536  }
   537  
   538  func (d *dwctxt) newtype(gotype loader.Sym) *dwarf.DWDie {
   539  	sn := d.ldr.SymName(gotype)
   540  	name := sn[5:] // could also decode from Type.string
   541  	tdata := d.ldr.Data(gotype)
   542  	kind := decodetypeKind(d.arch, tdata)
   543  	bytesize := decodetypeSize(d.arch, tdata)
   544  
   545  	var die, typedefdie *dwarf.DWDie
   546  	switch kind {
   547  	case objabi.KindBool:
   548  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_BASETYPE, name)
   549  		newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_boolean, 0)
   550  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   551  
   552  	case objabi.KindInt,
   553  		objabi.KindInt8,
   554  		objabi.KindInt16,
   555  		objabi.KindInt32,
   556  		objabi.KindInt64:
   557  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_BASETYPE, name)
   558  		newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_signed, 0)
   559  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   560  
   561  	case objabi.KindUint,
   562  		objabi.KindUint8,
   563  		objabi.KindUint16,
   564  		objabi.KindUint32,
   565  		objabi.KindUint64,
   566  		objabi.KindUintptr:
   567  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_BASETYPE, name)
   568  		newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_unsigned, 0)
   569  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   570  
   571  	case objabi.KindFloat32,
   572  		objabi.KindFloat64:
   573  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_BASETYPE, name)
   574  		newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_float, 0)
   575  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   576  
   577  	case objabi.KindComplex64,
   578  		objabi.KindComplex128:
   579  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_BASETYPE, name)
   580  		newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_complex_float, 0)
   581  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   582  
   583  	case objabi.KindArray:
   584  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_ARRAYTYPE, name)
   585  		typedefdie = d.dotypedef(&dwtypes, name, die)
   586  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   587  		s := decodetypeArrayElem(d.ldr, d.arch, gotype)
   588  		d.newrefattr(die, dwarf.DW_AT_type, d.defgotype(s))
   589  		fld := d.newdie(die, dwarf.DW_ABRV_ARRAYRANGE, "range")
   590  
   591  		// use actual length not upper bound; correct for 0-length arrays.
   592  		newattr(fld, dwarf.DW_AT_count, dwarf.DW_CLS_CONSTANT, decodetypeArrayLen(d.ldr, d.arch, gotype), 0)
   593  
   594  		d.newrefattr(fld, dwarf.DW_AT_type, d.uintptrInfoSym)
   595  
   596  	case objabi.KindChan:
   597  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_CHANTYPE, name)
   598  		s := decodetypeChanElem(d.ldr, d.arch, gotype)
   599  		d.newrefattr(die, dwarf.DW_AT_go_elem, d.defgotype(s))
   600  		// Save elem type for synthesizechantypes. We could synthesize here
   601  		// but that would change the order of DIEs we output.
   602  		d.newrefattr(die, dwarf.DW_AT_type, s)
   603  
   604  	case objabi.KindFunc:
   605  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_FUNCTYPE, name)
   606  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   607  		typedefdie = d.dotypedef(&dwtypes, name, die)
   608  		data := d.ldr.Data(gotype)
   609  		// FIXME: add caching or reuse reloc slice.
   610  		relocs := d.ldr.Relocs(gotype)
   611  		nfields := decodetypeFuncInCount(d.arch, data)
   612  		for i := 0; i < nfields; i++ {
   613  			s := decodetypeFuncInType(d.ldr, d.arch, gotype, &relocs, i)
   614  			sn := d.ldr.SymName(s)
   615  			fld := d.newdie(die, dwarf.DW_ABRV_FUNCTYPEPARAM, sn[5:])
   616  			d.newrefattr(fld, dwarf.DW_AT_type, d.defgotype(s))
   617  		}
   618  
   619  		if decodetypeFuncDotdotdot(d.arch, data) {
   620  			d.newdie(die, dwarf.DW_ABRV_DOTDOTDOT, "...")
   621  		}
   622  		nfields = decodetypeFuncOutCount(d.arch, data)
   623  		for i := 0; i < nfields; i++ {
   624  			s := decodetypeFuncOutType(d.ldr, d.arch, gotype, &relocs, i)
   625  			sn := d.ldr.SymName(s)
   626  			fld := d.newdie(die, dwarf.DW_ABRV_FUNCTYPEPARAM, sn[5:])
   627  			d.newrefattr(fld, dwarf.DW_AT_type, d.defptrto(d.defgotype(s)))
   628  		}
   629  
   630  	case objabi.KindInterface:
   631  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_IFACETYPE, name)
   632  		typedefdie = d.dotypedef(&dwtypes, name, die)
   633  		data := d.ldr.Data(gotype)
   634  		nfields := int(decodetypeIfaceMethodCount(d.arch, data))
   635  		var s loader.Sym
   636  		if nfields == 0 {
   637  			s = d.typeRuntimeEface
   638  		} else {
   639  			s = d.typeRuntimeIface
   640  		}
   641  		d.newrefattr(die, dwarf.DW_AT_type, d.defgotype(s))
   642  
   643  	case objabi.KindMap:
   644  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_MAPTYPE, name)
   645  		s := decodetypeMapKey(d.ldr, d.arch, gotype)
   646  		d.newrefattr(die, dwarf.DW_AT_go_key, d.defgotype(s))
   647  		s = decodetypeMapValue(d.ldr, d.arch, gotype)
   648  		d.newrefattr(die, dwarf.DW_AT_go_elem, d.defgotype(s))
   649  		// Save gotype for use in synthesizemaptypes. We could synthesize here,
   650  		// but that would change the order of the DIEs.
   651  		d.newrefattr(die, dwarf.DW_AT_type, gotype)
   652  
   653  	case objabi.KindPtr:
   654  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_PTRTYPE, name)
   655  		typedefdie = d.dotypedef(&dwtypes, name, die)
   656  		s := decodetypePtrElem(d.ldr, d.arch, gotype)
   657  		d.newrefattr(die, dwarf.DW_AT_type, d.defgotype(s))
   658  
   659  	case objabi.KindSlice:
   660  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_SLICETYPE, name)
   661  		typedefdie = d.dotypedef(&dwtypes, name, die)
   662  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   663  		s := decodetypeArrayElem(d.ldr, d.arch, gotype)
   664  		elem := d.defgotype(s)
   665  		d.newrefattr(die, dwarf.DW_AT_go_elem, elem)
   666  
   667  	case objabi.KindString:
   668  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_STRINGTYPE, name)
   669  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   670  
   671  	case objabi.KindStruct:
   672  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_STRUCTTYPE, name)
   673  		typedefdie = d.dotypedef(&dwtypes, name, die)
   674  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   675  		nfields := decodetypeStructFieldCount(d.ldr, d.arch, gotype)
   676  		for i := 0; i < nfields; i++ {
   677  			f := decodetypeStructFieldName(d.ldr, d.arch, gotype, i)
   678  			s := decodetypeStructFieldType(d.ldr, d.arch, gotype, i)
   679  			if f == "" {
   680  				sn := d.ldr.SymName(s)
   681  				f = sn[5:] // skip "type."
   682  			}
   683  			fld := d.newdie(die, dwarf.DW_ABRV_STRUCTFIELD, f)
   684  			d.newrefattr(fld, dwarf.DW_AT_type, d.defgotype(s))
   685  			offset := decodetypeStructFieldOffset(d.ldr, d.arch, gotype, i)
   686  			newmemberoffsetattr(fld, int32(offset))
   687  			if decodetypeStructFieldEmbedded(d.ldr, d.arch, gotype, i) {
   688  				newattr(fld, dwarf.DW_AT_go_embedded_field, dwarf.DW_CLS_FLAG, 1, 0)
   689  			}
   690  		}
   691  
   692  	case objabi.KindUnsafePointer:
   693  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_BARE_PTRTYPE, name)
   694  
   695  	default:
   696  		d.linkctxt.Errorf(gotype, "dwarf: definition of unknown kind %d", kind)
   697  		die = d.newdie(&dwtypes, dwarf.DW_ABRV_TYPEDECL, name)
   698  		d.newrefattr(die, dwarf.DW_AT_type, d.mustFind("<unspecified>"))
   699  	}
   700  
   701  	newattr(die, dwarf.DW_AT_go_kind, dwarf.DW_CLS_CONSTANT, int64(kind), 0)
   702  
   703  	if d.ldr.AttrReachable(gotype) {
   704  		newattr(die, dwarf.DW_AT_go_runtime_type, dwarf.DW_CLS_GO_TYPEREF, 0, dwSym(gotype))
   705  	}
   706  
   707  	// Sanity check.
   708  	if _, ok := d.rtmap[gotype]; ok {
   709  		log.Fatalf("internal error: rtmap entry already installed\n")
   710  	}
   711  
   712  	ds := loader.Sym(die.Sym.(dwSym))
   713  	if typedefdie != nil {
   714  		ds = loader.Sym(typedefdie.Sym.(dwSym))
   715  	}
   716  	d.rtmap[ds] = gotype
   717  
   718  	if _, ok := prototypedies[sn]; ok {
   719  		prototypedies[sn] = die
   720  	}
   721  
   722  	if typedefdie != nil {
   723  		return typedefdie
   724  	}
   725  	return die
   726  }
   727  
   728  func (d *dwctxt) nameFromDIESym(dwtypeDIESym loader.Sym) string {
   729  	sn := d.ldr.SymName(dwtypeDIESym)
   730  	return sn[len(dwarf.InfoPrefix):]
   731  }
   732  
   733  func (d *dwctxt) defptrto(dwtype loader.Sym) loader.Sym {
   734  
   735  	// FIXME: it would be nice if the compiler attached an aux symbol
   736  	// ref from the element type to the pointer type -- it would be
   737  	// more efficient to do it this way as opposed to via name lookups.
   738  
   739  	ptrname := "*" + d.nameFromDIESym(dwtype)
   740  	if die := d.find(ptrname); die != 0 {
   741  		return die
   742  	}
   743  
   744  	pdie := d.newdie(&dwtypes, dwarf.DW_ABRV_PTRTYPE, ptrname)
   745  	d.newrefattr(pdie, dwarf.DW_AT_type, dwtype)
   746  
   747  	// The DWARF info synthesizes pointer types that don't exist at the
   748  	// language level, like *hash<...> and *bucket<...>, and the data
   749  	// pointers of slices. Link to the ones we can find.
   750  	gts := d.ldr.Lookup("type."+ptrname, 0)
   751  	if gts != 0 && d.ldr.AttrReachable(gts) {
   752  		newattr(pdie, dwarf.DW_AT_go_runtime_type, dwarf.DW_CLS_GO_TYPEREF, 0, dwSym(gts))
   753  	}
   754  
   755  	if gts != 0 {
   756  		ds := loader.Sym(pdie.Sym.(dwSym))
   757  		d.rtmap[ds] = gts
   758  		d.tdmap[gts] = ds
   759  	}
   760  
   761  	return d.dtolsym(pdie.Sym)
   762  }
   763  
   764  // Copies src's children into dst. Copies attributes by value.
   765  // DWAttr.data is copied as pointer only. If except is one of
   766  // the top-level children, it will not be copied.
   767  func (d *dwctxt) copychildrenexcept(ctxt *Link, dst *dwarf.DWDie, src *dwarf.DWDie, except *dwarf.DWDie) {
   768  	for src = src.Child; src != nil; src = src.Link {
   769  		if src == except {
   770  			continue
   771  		}
   772  		c := d.newdie(dst, src.Abbrev, getattr(src, dwarf.DW_AT_name).Data.(string))
   773  		for a := src.Attr; a != nil; a = a.Link {
   774  			newattr(c, a.Atr, int(a.Cls), a.Value, a.Data)
   775  		}
   776  		d.copychildrenexcept(ctxt, c, src, nil)
   777  	}
   778  
   779  	reverselist(&dst.Child)
   780  }
   781  
   782  func (d *dwctxt) copychildren(ctxt *Link, dst *dwarf.DWDie, src *dwarf.DWDie) {
   783  	d.copychildrenexcept(ctxt, dst, src, nil)
   784  }
   785  
   786  // Search children (assumed to have TAG_member) for the one named
   787  // field and set its AT_type to dwtype
   788  func (d *dwctxt) substitutetype(structdie *dwarf.DWDie, field string, dwtype loader.Sym) {
   789  	child := findchild(structdie, field)
   790  	if child == nil {
   791  		Exitf("dwarf substitutetype: %s does not have member %s",
   792  			getattr(structdie, dwarf.DW_AT_name).Data, field)
   793  		return
   794  	}
   795  
   796  	a := getattr(child, dwarf.DW_AT_type)
   797  	if a != nil {
   798  		a.Data = dwSym(dwtype)
   799  	} else {
   800  		d.newrefattr(child, dwarf.DW_AT_type, dwtype)
   801  	}
   802  }
   803  
   804  func (d *dwctxt) findprotodie(ctxt *Link, name string) *dwarf.DWDie {
   805  	die, ok := prototypedies[name]
   806  	if ok && die == nil {
   807  		d.defgotype(d.lookupOrDiag(name))
   808  		die = prototypedies[name]
   809  	}
   810  	if die == nil {
   811  		log.Fatalf("internal error: DIE generation failed for %s\n", name)
   812  	}
   813  	return die
   814  }
   815  
   816  func (d *dwctxt) synthesizestringtypes(ctxt *Link, die *dwarf.DWDie) {
   817  	prototype := walktypedef(d.findprotodie(ctxt, "type.runtime.stringStructDWARF"))
   818  	if prototype == nil {
   819  		return
   820  	}
   821  
   822  	for ; die != nil; die = die.Link {
   823  		if die.Abbrev != dwarf.DW_ABRV_STRINGTYPE {
   824  			continue
   825  		}
   826  		d.copychildren(ctxt, die, prototype)
   827  	}
   828  }
   829  
   830  func (d *dwctxt) synthesizeslicetypes(ctxt *Link, die *dwarf.DWDie) {
   831  	prototype := walktypedef(d.findprotodie(ctxt, "type.runtime.slice"))
   832  	if prototype == nil {
   833  		return
   834  	}
   835  
   836  	for ; die != nil; die = die.Link {
   837  		if die.Abbrev != dwarf.DW_ABRV_SLICETYPE {
   838  			continue
   839  		}
   840  		d.copychildren(ctxt, die, prototype)
   841  		elem := loader.Sym(getattr(die, dwarf.DW_AT_go_elem).Data.(dwSym))
   842  		d.substitutetype(die, "array", d.defptrto(elem))
   843  	}
   844  }
   845  
   846  func mkinternaltypename(base string, arg1 string, arg2 string) string {
   847  	if arg2 == "" {
   848  		return fmt.Sprintf("%s<%s>", base, arg1)
   849  	}
   850  	return fmt.Sprintf("%s<%s,%s>", base, arg1, arg2)
   851  }
   852  
   853  // synthesizemaptypes is way too closely married to runtime/hashmap.c
   854  const (
   855  	MaxKeySize = 128
   856  	MaxValSize = 128
   857  	BucketSize = 8
   858  )
   859  
   860  func (d *dwctxt) mkinternaltype(ctxt *Link, abbrev int, typename, keyname, valname string, f func(*dwarf.DWDie)) loader.Sym {
   861  	name := mkinternaltypename(typename, keyname, valname)
   862  	symname := dwarf.InfoPrefix + name
   863  	s := d.ldr.Lookup(symname, 0)
   864  	if s != 0 && d.ldr.SymType(s) == sym.SDWARFTYPE {
   865  		return s
   866  	}
   867  	die := d.newdie(&dwtypes, abbrev, name)
   868  	f(die)
   869  	return d.dtolsym(die.Sym)
   870  }
   871  
   872  func (d *dwctxt) synthesizemaptypes(ctxt *Link, die *dwarf.DWDie) {
   873  	hash := walktypedef(d.findprotodie(ctxt, "type.runtime.hmap"))
   874  	bucket := walktypedef(d.findprotodie(ctxt, "type.runtime.bmap"))
   875  
   876  	if hash == nil {
   877  		return
   878  	}
   879  
   880  	for ; die != nil; die = die.Link {
   881  		if die.Abbrev != dwarf.DW_ABRV_MAPTYPE {
   882  			continue
   883  		}
   884  		gotype := loader.Sym(getattr(die, dwarf.DW_AT_type).Data.(dwSym))
   885  		keytype := decodetypeMapKey(d.ldr, d.arch, gotype)
   886  		valtype := decodetypeMapValue(d.ldr, d.arch, gotype)
   887  		keydata := d.ldr.Data(keytype)
   888  		valdata := d.ldr.Data(valtype)
   889  		keysize, valsize := decodetypeSize(d.arch, keydata), decodetypeSize(d.arch, valdata)
   890  		keytype, valtype = d.walksymtypedef(d.defgotype(keytype)), d.walksymtypedef(d.defgotype(valtype))
   891  
   892  		// compute size info like hashmap.c does.
   893  		indirectKey, indirectVal := false, false
   894  		if keysize > MaxKeySize {
   895  			keysize = int64(d.arch.PtrSize)
   896  			indirectKey = true
   897  		}
   898  		if valsize > MaxValSize {
   899  			valsize = int64(d.arch.PtrSize)
   900  			indirectVal = true
   901  		}
   902  
   903  		// Construct type to represent an array of BucketSize keys
   904  		keyname := d.nameFromDIESym(keytype)
   905  		dwhks := d.mkinternaltype(ctxt, dwarf.DW_ABRV_ARRAYTYPE, "[]key", keyname, "", func(dwhk *dwarf.DWDie) {
   906  			newattr(dwhk, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, BucketSize*keysize, 0)
   907  			t := keytype
   908  			if indirectKey {
   909  				t = d.defptrto(keytype)
   910  			}
   911  			d.newrefattr(dwhk, dwarf.DW_AT_type, t)
   912  			fld := d.newdie(dwhk, dwarf.DW_ABRV_ARRAYRANGE, "size")
   913  			newattr(fld, dwarf.DW_AT_count, dwarf.DW_CLS_CONSTANT, BucketSize, 0)
   914  			d.newrefattr(fld, dwarf.DW_AT_type, d.uintptrInfoSym)
   915  		})
   916  
   917  		// Construct type to represent an array of BucketSize values
   918  		valname := d.nameFromDIESym(valtype)
   919  		dwhvs := d.mkinternaltype(ctxt, dwarf.DW_ABRV_ARRAYTYPE, "[]val", valname, "", func(dwhv *dwarf.DWDie) {
   920  			newattr(dwhv, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, BucketSize*valsize, 0)
   921  			t := valtype
   922  			if indirectVal {
   923  				t = d.defptrto(valtype)
   924  			}
   925  			d.newrefattr(dwhv, dwarf.DW_AT_type, t)
   926  			fld := d.newdie(dwhv, dwarf.DW_ABRV_ARRAYRANGE, "size")
   927  			newattr(fld, dwarf.DW_AT_count, dwarf.DW_CLS_CONSTANT, BucketSize, 0)
   928  			d.newrefattr(fld, dwarf.DW_AT_type, d.uintptrInfoSym)
   929  		})
   930  
   931  		// Construct bucket<K,V>
   932  		dwhbs := d.mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "bucket", keyname, valname, func(dwhb *dwarf.DWDie) {
   933  			// Copy over all fields except the field "data" from the generic
   934  			// bucket. "data" will be replaced with keys/values below.
   935  			d.copychildrenexcept(ctxt, dwhb, bucket, findchild(bucket, "data"))
   936  
   937  			fld := d.newdie(dwhb, dwarf.DW_ABRV_STRUCTFIELD, "keys")
   938  			d.newrefattr(fld, dwarf.DW_AT_type, dwhks)
   939  			newmemberoffsetattr(fld, BucketSize)
   940  			fld = d.newdie(dwhb, dwarf.DW_ABRV_STRUCTFIELD, "values")
   941  			d.newrefattr(fld, dwarf.DW_AT_type, dwhvs)
   942  			newmemberoffsetattr(fld, BucketSize+BucketSize*int32(keysize))
   943  			fld = d.newdie(dwhb, dwarf.DW_ABRV_STRUCTFIELD, "overflow")
   944  			d.newrefattr(fld, dwarf.DW_AT_type, d.defptrto(d.dtolsym(dwhb.Sym)))
   945  			newmemberoffsetattr(fld, BucketSize+BucketSize*(int32(keysize)+int32(valsize)))
   946  			if d.arch.RegSize > d.arch.PtrSize {
   947  				fld = d.newdie(dwhb, dwarf.DW_ABRV_STRUCTFIELD, "pad")
   948  				d.newrefattr(fld, dwarf.DW_AT_type, d.uintptrInfoSym)
   949  				newmemberoffsetattr(fld, BucketSize+BucketSize*(int32(keysize)+int32(valsize))+int32(d.arch.PtrSize))
   950  			}
   951  
   952  			newattr(dwhb, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, BucketSize+BucketSize*keysize+BucketSize*valsize+int64(d.arch.RegSize), 0)
   953  		})
   954  
   955  		// Construct hash<K,V>
   956  		dwhs := d.mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "hash", keyname, valname, func(dwh *dwarf.DWDie) {
   957  			d.copychildren(ctxt, dwh, hash)
   958  			d.substitutetype(dwh, "buckets", d.defptrto(dwhbs))
   959  			d.substitutetype(dwh, "oldbuckets", d.defptrto(dwhbs))
   960  			newattr(dwh, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, getattr(hash, dwarf.DW_AT_byte_size).Value, nil)
   961  		})
   962  
   963  		// make map type a pointer to hash<K,V>
   964  		d.newrefattr(die, dwarf.DW_AT_type, d.defptrto(dwhs))
   965  	}
   966  }
   967  
   968  func (d *dwctxt) synthesizechantypes(ctxt *Link, die *dwarf.DWDie) {
   969  	sudog := walktypedef(d.findprotodie(ctxt, "type.runtime.sudog"))
   970  	waitq := walktypedef(d.findprotodie(ctxt, "type.runtime.waitq"))
   971  	hchan := walktypedef(d.findprotodie(ctxt, "type.runtime.hchan"))
   972  	if sudog == nil || waitq == nil || hchan == nil {
   973  		return
   974  	}
   975  
   976  	sudogsize := int(getattr(sudog, dwarf.DW_AT_byte_size).Value)
   977  
   978  	for ; die != nil; die = die.Link {
   979  		if die.Abbrev != dwarf.DW_ABRV_CHANTYPE {
   980  			continue
   981  		}
   982  		elemgotype := loader.Sym(getattr(die, dwarf.DW_AT_type).Data.(dwSym))
   983  		tname := d.ldr.SymName(elemgotype)
   984  		elemname := tname[5:]
   985  		elemtype := d.walksymtypedef(d.defgotype(d.lookupOrDiag(tname)))
   986  
   987  		// sudog<T>
   988  		dwss := d.mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "sudog", elemname, "", func(dws *dwarf.DWDie) {
   989  			d.copychildren(ctxt, dws, sudog)
   990  			d.substitutetype(dws, "elem", d.defptrto(elemtype))
   991  			newattr(dws, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, int64(sudogsize), nil)
   992  		})
   993  
   994  		// waitq<T>
   995  		dwws := d.mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "waitq", elemname, "", func(dww *dwarf.DWDie) {
   996  
   997  			d.copychildren(ctxt, dww, waitq)
   998  			d.substitutetype(dww, "first", d.defptrto(dwss))
   999  			d.substitutetype(dww, "last", d.defptrto(dwss))
  1000  			newattr(dww, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, getattr(waitq, dwarf.DW_AT_byte_size).Value, nil)
  1001  		})
  1002  
  1003  		// hchan<T>
  1004  		dwhs := d.mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "hchan", elemname, "", func(dwh *dwarf.DWDie) {
  1005  			d.copychildren(ctxt, dwh, hchan)
  1006  			d.substitutetype(dwh, "recvq", dwws)
  1007  			d.substitutetype(dwh, "sendq", dwws)
  1008  			newattr(dwh, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, getattr(hchan, dwarf.DW_AT_byte_size).Value, nil)
  1009  		})
  1010  
  1011  		d.newrefattr(die, dwarf.DW_AT_type, d.defptrto(dwhs))
  1012  	}
  1013  }
  1014  
  1015  // createUnitLength creates the initial length field with value v and update
  1016  // offset of unit_length if needed.
  1017  func (d *dwctxt) createUnitLength(su *loader.SymbolBuilder, v uint64) {
  1018  	if isDwarf64(d.linkctxt) {
  1019  		su.AddUint32(d.arch, 0xFFFFFFFF)
  1020  	}
  1021  	d.addDwarfAddrField(su, v)
  1022  }
  1023  
  1024  // addDwarfAddrField adds a DWARF field in DWARF 64bits or 32bits.
  1025  func (d *dwctxt) addDwarfAddrField(sb *loader.SymbolBuilder, v uint64) {
  1026  	if isDwarf64(d.linkctxt) {
  1027  		sb.AddUint(d.arch, v)
  1028  	} else {
  1029  		sb.AddUint32(d.arch, uint32(v))
  1030  	}
  1031  }
  1032  
  1033  // addDwarfAddrRef adds a DWARF pointer in DWARF 64bits or 32bits.
  1034  func (d *dwctxt) addDwarfAddrRef(sb *loader.SymbolBuilder, t loader.Sym) {
  1035  	if isDwarf64(d.linkctxt) {
  1036  		d.adddwarfref(sb, t, 8)
  1037  	} else {
  1038  		d.adddwarfref(sb, t, 4)
  1039  	}
  1040  }
  1041  
  1042  // calcCompUnitRanges calculates the PC ranges of the compilation units.
  1043  func (d *dwctxt) calcCompUnitRanges() {
  1044  	var prevUnit *sym.CompilationUnit
  1045  	for _, s := range d.linkctxt.Textp {
  1046  		sym := loader.Sym(s)
  1047  
  1048  		fi := d.ldr.FuncInfo(sym)
  1049  		if !fi.Valid() {
  1050  			continue
  1051  		}
  1052  
  1053  		// Skip linker-created functions (ex: runtime.addmoduledata), since they
  1054  		// don't have DWARF to begin with.
  1055  		unit := d.ldr.SymUnit(sym)
  1056  		if unit == nil {
  1057  			continue
  1058  		}
  1059  
  1060  		// Update PC ranges.
  1061  		//
  1062  		// We don't simply compare the end of the previous
  1063  		// symbol with the start of the next because there's
  1064  		// often a little padding between them. Instead, we
  1065  		// only create boundaries between symbols from
  1066  		// different units.
  1067  		sval := d.ldr.SymValue(sym)
  1068  		u0val := d.ldr.SymValue(loader.Sym(unit.Textp[0]))
  1069  		if prevUnit != unit {
  1070  			unit.PCs = append(unit.PCs, dwarf.Range{Start: sval - u0val})
  1071  			prevUnit = unit
  1072  		}
  1073  		unit.PCs[len(unit.PCs)-1].End = sval - u0val + int64(len(d.ldr.Data(sym)))
  1074  	}
  1075  }
  1076  
  1077  func movetomodule(ctxt *Link, parent *dwarf.DWDie) {
  1078  	die := ctxt.runtimeCU.DWInfo.Child
  1079  	if die == nil {
  1080  		ctxt.runtimeCU.DWInfo.Child = parent.Child
  1081  		return
  1082  	}
  1083  	for die.Link != nil {
  1084  		die = die.Link
  1085  	}
  1086  	die.Link = parent.Child
  1087  }
  1088  
  1089  /*
  1090   * Generate a sequence of opcodes that is as short as possible.
  1091   * See section 6.2.5
  1092   */
  1093  const (
  1094  	LINE_BASE   = -4
  1095  	LINE_RANGE  = 10
  1096  	PC_RANGE    = (255 - OPCODE_BASE) / LINE_RANGE
  1097  	OPCODE_BASE = 11
  1098  )
  1099  
  1100  /*
  1101   * Walk prog table, emit line program and build DIE tree.
  1102   */
  1103  
  1104  func getCompilationDir() string {
  1105  	// OSX requires this be set to something, but it's not easy to choose
  1106  	// a value. Linking takes place in a temporary directory, so there's
  1107  	// no point including it here. Paths in the file table are usually
  1108  	// absolute, in which case debuggers will ignore this value. -trimpath
  1109  	// produces relative paths, but we don't know where they start, so
  1110  	// all we can do here is try not to make things worse.
  1111  	return "."
  1112  }
  1113  
  1114  func (d *dwctxt) importInfoSymbol(dsym loader.Sym) {
  1115  	d.ldr.SetAttrReachable(dsym, true)
  1116  	d.ldr.SetAttrNotInSymbolTable(dsym, true)
  1117  	dst := d.ldr.SymType(dsym)
  1118  	if dst != sym.SDWARFCONST && dst != sym.SDWARFABSFCN {
  1119  		log.Fatalf("error: DWARF info sym %d/%s with incorrect type %s", dsym, d.ldr.SymName(dsym), d.ldr.SymType(dsym).String())
  1120  	}
  1121  	relocs := d.ldr.Relocs(dsym)
  1122  	for i := 0; i < relocs.Count(); i++ {
  1123  		r := relocs.At(i)
  1124  		if r.Type() != objabi.R_DWARFSECREF {
  1125  			continue
  1126  		}
  1127  		rsym := r.Sym()
  1128  		// If there is an entry for the symbol in our rtmap, then it
  1129  		// means we've processed the type already, and can skip this one.
  1130  		if _, ok := d.rtmap[rsym]; ok {
  1131  			// type already generated
  1132  			continue
  1133  		}
  1134  		// FIXME: is there a way we could avoid materializing the
  1135  		// symbol name here?
  1136  		sn := d.ldr.SymName(rsym)
  1137  		tn := sn[len(dwarf.InfoPrefix):]
  1138  		ts := d.ldr.Lookup("type."+tn, 0)
  1139  		d.defgotype(ts)
  1140  	}
  1141  }
  1142  
  1143  func expandFile(fname string) string {
  1144  	if strings.HasPrefix(fname, src.FileSymPrefix) {
  1145  		fname = fname[len(src.FileSymPrefix):]
  1146  	}
  1147  	return expandGoroot(fname)
  1148  }
  1149  
  1150  // writeDirFileTables emits the portion of the DWARF line table
  1151  // prologue containing the include directories and file names,
  1152  // described in section 6.2.4 of the DWARF 4 standard. It walks the
  1153  // filepaths for the unit to discover any common directories, which
  1154  // are emitted to the directory table first, then the file table is
  1155  // emitted after that.
  1156  func (d *dwctxt) writeDirFileTables(unit *sym.CompilationUnit, lsu *loader.SymbolBuilder) {
  1157  	type fileDir struct {
  1158  		base string
  1159  		dir  int
  1160  	}
  1161  	dirNums := make(map[string]int)
  1162  	dirs := []string{""}
  1163  	files := []fileDir{}
  1164  
  1165  	// Preprocess files to collect directories. This assumes that the
  1166  	// file table is already de-duped.
  1167  	for i, name := range unit.FileTable {
  1168  		name := expandFile(name)
  1169  		if len(name) == 0 {
  1170  			// Can't have empty filenames, and having a unique
  1171  			// filename is quite useful for debugging.
  1172  			name = fmt.Sprintf("<missing>_%d", i)
  1173  		}
  1174  		// Note the use of "path" here and not "filepath". The compiler
  1175  		// hard-codes to use "/" in DWARF paths (even for Windows), so we
  1176  		// want to maintain that here.
  1177  		file := path.Base(name)
  1178  		dir := path.Dir(name)
  1179  		dirIdx, ok := dirNums[dir]
  1180  		if !ok && dir != "." {
  1181  			dirIdx = len(dirNums) + 1
  1182  			dirNums[dir] = dirIdx
  1183  			dirs = append(dirs, dir)
  1184  		}
  1185  		files = append(files, fileDir{base: file, dir: dirIdx})
  1186  
  1187  		// We can't use something that may be dead-code
  1188  		// eliminated from a binary here. proc.go contains
  1189  		// main and the scheduler, so it's not going anywhere.
  1190  		if i := strings.Index(name, "runtime/proc.go"); i >= 0 && unit.Lib.Pkg == "runtime" {
  1191  			d.dwmu.Lock()
  1192  			if gdbscript == "" {
  1193  				k := strings.Index(name, "runtime/proc.go")
  1194  				gdbscript = name[:k] + "runtime/runtime-gdb.py"
  1195  			}
  1196  			d.dwmu.Unlock()
  1197  		}
  1198  	}
  1199  
  1200  	// Emit directory section. This is a series of nul terminated
  1201  	// strings, followed by a single zero byte.
  1202  	lsDwsym := dwSym(lsu.Sym())
  1203  	for k := 1; k < len(dirs); k++ {
  1204  		d.AddString(lsDwsym, dirs[k])
  1205  	}
  1206  	lsu.AddUint8(0) // terminator
  1207  
  1208  	// Emit file section.
  1209  	for k := 0; k < len(files); k++ {
  1210  		d.AddString(lsDwsym, files[k].base)
  1211  		dwarf.Uleb128put(d, lsDwsym, int64(files[k].dir))
  1212  		lsu.AddUint8(0) // mtime
  1213  		lsu.AddUint8(0) // length
  1214  	}
  1215  	lsu.AddUint8(0) // terminator
  1216  }
  1217  
  1218  // writelines collects up and chains together the symbols needed to
  1219  // form the DWARF line table for the specified compilation unit,
  1220  // returning a list of symbols. The returned list will include an
  1221  // initial symbol containing the line table header and prologue (with
  1222  // file table), then a series of compiler-emitted line table symbols
  1223  // (one per live function), and finally an epilog symbol containing an
  1224  // end-of-sequence operator. The prologue and epilog symbols are passed
  1225  // in (having been created earlier); here we add content to them.
  1226  func (d *dwctxt) writelines(unit *sym.CompilationUnit, lineProlog loader.Sym) []loader.Sym {
  1227  	is_stmt := uint8(1) // initially = recommended default_is_stmt = 1, tracks is_stmt toggles.
  1228  
  1229  	unitstart := int64(-1)
  1230  	headerstart := int64(-1)
  1231  	headerend := int64(-1)
  1232  
  1233  	syms := make([]loader.Sym, 0, len(unit.Textp)+2)
  1234  	syms = append(syms, lineProlog)
  1235  	lsu := d.ldr.MakeSymbolUpdater(lineProlog)
  1236  	lsDwsym := dwSym(lineProlog)
  1237  	newattr(unit.DWInfo, dwarf.DW_AT_stmt_list, dwarf.DW_CLS_PTR, 0, lsDwsym)
  1238  
  1239  	// Write .debug_line Line Number Program Header (sec 6.2.4)
  1240  	// Fields marked with (*) must be changed for 64-bit dwarf
  1241  	unitLengthOffset := lsu.Size()
  1242  	d.createUnitLength(lsu, 0) // unit_length (*), filled in at end
  1243  	unitstart = lsu.Size()
  1244  	lsu.AddUint16(d.arch, 2) // dwarf version (appendix F) -- version 3 is incompatible w/ XCode 9.0's dsymutil, latest supported on OSX 10.12 as of 2018-05
  1245  	headerLengthOffset := lsu.Size()
  1246  	d.addDwarfAddrField(lsu, 0) // header_length (*), filled in at end
  1247  	headerstart = lsu.Size()
  1248  
  1249  	// cpos == unitstart + 4 + 2 + 4
  1250  	lsu.AddUint8(1)                // minimum_instruction_length
  1251  	lsu.AddUint8(is_stmt)          // default_is_stmt
  1252  	lsu.AddUint8(LINE_BASE & 0xFF) // line_base
  1253  	lsu.AddUint8(LINE_RANGE)       // line_range
  1254  	lsu.AddUint8(OPCODE_BASE)      // opcode_base
  1255  	lsu.AddUint8(0)                // standard_opcode_lengths[1]
  1256  	lsu.AddUint8(1)                // standard_opcode_lengths[2]
  1257  	lsu.AddUint8(1)                // standard_opcode_lengths[3]
  1258  	lsu.AddUint8(1)                // standard_opcode_lengths[4]
  1259  	lsu.AddUint8(1)                // standard_opcode_lengths[5]
  1260  	lsu.AddUint8(0)                // standard_opcode_lengths[6]
  1261  	lsu.AddUint8(0)                // standard_opcode_lengths[7]
  1262  	lsu.AddUint8(0)                // standard_opcode_lengths[8]
  1263  	lsu.AddUint8(1)                // standard_opcode_lengths[9]
  1264  	lsu.AddUint8(0)                // standard_opcode_lengths[10]
  1265  
  1266  	// Call helper to emit dir and file sections.
  1267  	d.writeDirFileTables(unit, lsu)
  1268  
  1269  	// capture length at end of file names.
  1270  	headerend = lsu.Size()
  1271  	unitlen := lsu.Size() - unitstart
  1272  
  1273  	// Output the state machine for each function remaining.
  1274  	for _, s := range unit.Textp {
  1275  		fnSym := loader.Sym(s)
  1276  		_, _, _, lines := d.ldr.GetFuncDwarfAuxSyms(fnSym)
  1277  
  1278  		// Chain the line symbol onto the list.
  1279  		if lines != 0 {
  1280  			syms = append(syms, lines)
  1281  			unitlen += int64(len(d.ldr.Data(lines)))
  1282  		}
  1283  	}
  1284  
  1285  	if d.linkctxt.HeadType == objabi.Haix {
  1286  		addDwsectCUSize(".debug_line", unit.Lib.Pkg, uint64(unitlen))
  1287  	}
  1288  
  1289  	if isDwarf64(d.linkctxt) {
  1290  		lsu.SetUint(d.arch, unitLengthOffset+4, uint64(unitlen)) // +4 because of 0xFFFFFFFF
  1291  		lsu.SetUint(d.arch, headerLengthOffset, uint64(headerend-headerstart))
  1292  	} else {
  1293  		lsu.SetUint32(d.arch, unitLengthOffset, uint32(unitlen))
  1294  		lsu.SetUint32(d.arch, headerLengthOffset, uint32(headerend-headerstart))
  1295  	}
  1296  
  1297  	return syms
  1298  }
  1299  
  1300  // writepcranges generates the DW_AT_ranges table for compilation unit
  1301  // "unit", and returns a collection of ranges symbols (one for the
  1302  // compilation unit DIE itself and the remainder from functions in the unit).
  1303  func (d *dwctxt) writepcranges(unit *sym.CompilationUnit, base loader.Sym, pcs []dwarf.Range, rangeProlog loader.Sym) []loader.Sym {
  1304  
  1305  	syms := make([]loader.Sym, 0, len(unit.RangeSyms)+1)
  1306  	syms = append(syms, rangeProlog)
  1307  	rsu := d.ldr.MakeSymbolUpdater(rangeProlog)
  1308  	rDwSym := dwSym(rangeProlog)
  1309  
  1310  	// Create PC ranges for the compilation unit DIE.
  1311  	newattr(unit.DWInfo, dwarf.DW_AT_ranges, dwarf.DW_CLS_PTR, rsu.Size(), rDwSym)
  1312  	newattr(unit.DWInfo, dwarf.DW_AT_low_pc, dwarf.DW_CLS_ADDRESS, 0, dwSym(base))
  1313  	dwarf.PutBasedRanges(d, rDwSym, pcs)
  1314  
  1315  	// Collect up the ranges for functions in the unit.
  1316  	rsize := uint64(rsu.Size())
  1317  	for _, ls := range unit.RangeSyms {
  1318  		s := loader.Sym(ls)
  1319  		syms = append(syms, s)
  1320  		rsize += uint64(d.ldr.SymSize(s))
  1321  	}
  1322  
  1323  	if d.linkctxt.HeadType == objabi.Haix {
  1324  		addDwsectCUSize(".debug_ranges", unit.Lib.Pkg, rsize)
  1325  	}
  1326  
  1327  	return syms
  1328  }
  1329  
  1330  /*
  1331   *  Emit .debug_frame
  1332   */
  1333  const (
  1334  	dataAlignmentFactor = -4
  1335  )
  1336  
  1337  // appendPCDeltaCFA appends per-PC CFA deltas to b and returns the final slice.
  1338  func appendPCDeltaCFA(arch *sys.Arch, b []byte, deltapc, cfa int64) []byte {
  1339  	b = append(b, dwarf.DW_CFA_def_cfa_offset_sf)
  1340  	b = dwarf.AppendSleb128(b, cfa/dataAlignmentFactor)
  1341  
  1342  	switch {
  1343  	case deltapc < 0x40:
  1344  		b = append(b, uint8(dwarf.DW_CFA_advance_loc+deltapc))
  1345  	case deltapc < 0x100:
  1346  		b = append(b, dwarf.DW_CFA_advance_loc1)
  1347  		b = append(b, uint8(deltapc))
  1348  	case deltapc < 0x10000:
  1349  		b = append(b, dwarf.DW_CFA_advance_loc2, 0, 0)
  1350  		arch.ByteOrder.PutUint16(b[len(b)-2:], uint16(deltapc))
  1351  	default:
  1352  		b = append(b, dwarf.DW_CFA_advance_loc4, 0, 0, 0, 0)
  1353  		arch.ByteOrder.PutUint32(b[len(b)-4:], uint32(deltapc))
  1354  	}
  1355  	return b
  1356  }
  1357  
  1358  func (d *dwctxt) writeframes(fs loader.Sym) dwarfSecInfo {
  1359  	fsd := dwSym(fs)
  1360  	fsu := d.ldr.MakeSymbolUpdater(fs)
  1361  	fsu.SetType(sym.SDWARFSECT)
  1362  	isdw64 := isDwarf64(d.linkctxt)
  1363  	haslr := d.linkctxt.Arch.HasLR
  1364  
  1365  	// Length field is 4 bytes on Dwarf32 and 12 bytes on Dwarf64
  1366  	lengthFieldSize := int64(4)
  1367  	if isdw64 {
  1368  		lengthFieldSize += 8
  1369  	}
  1370  
  1371  	// Emit the CIE, Section 6.4.1
  1372  	cieReserve := uint32(16)
  1373  	if haslr {
  1374  		cieReserve = 32
  1375  	}
  1376  	if isdw64 {
  1377  		cieReserve += 4 // 4 bytes added for cid
  1378  	}
  1379  	d.createUnitLength(fsu, uint64(cieReserve))         // initial length, must be multiple of thearch.ptrsize
  1380  	d.addDwarfAddrField(fsu, ^uint64(0))                // cid
  1381  	fsu.AddUint8(3)                                     // dwarf version (appendix F)
  1382  	fsu.AddUint8(0)                                     // augmentation ""
  1383  	dwarf.Uleb128put(d, fsd, 1)                         // code_alignment_factor
  1384  	dwarf.Sleb128put(d, fsd, dataAlignmentFactor)       // all CFI offset calculations include multiplication with this factor
  1385  	dwarf.Uleb128put(d, fsd, int64(thearch.Dwarfreglr)) // return_address_register
  1386  
  1387  	fsu.AddUint8(dwarf.DW_CFA_def_cfa)                  // Set the current frame address..
  1388  	dwarf.Uleb128put(d, fsd, int64(thearch.Dwarfregsp)) // ...to use the value in the platform's SP register (defined in l.go)...
  1389  	if haslr {
  1390  		dwarf.Uleb128put(d, fsd, int64(0)) // ...plus a 0 offset.
  1391  
  1392  		fsu.AddUint8(dwarf.DW_CFA_same_value) // The platform's link register is unchanged during the prologue.
  1393  		dwarf.Uleb128put(d, fsd, int64(thearch.Dwarfreglr))
  1394  
  1395  		fsu.AddUint8(dwarf.DW_CFA_val_offset)               // The previous value...
  1396  		dwarf.Uleb128put(d, fsd, int64(thearch.Dwarfregsp)) // ...of the platform's SP register...
  1397  		dwarf.Uleb128put(d, fsd, int64(0))                  // ...is CFA+0.
  1398  	} else {
  1399  		dwarf.Uleb128put(d, fsd, int64(d.arch.PtrSize)) // ...plus the word size (because the call instruction implicitly adds one word to the frame).
  1400  
  1401  		fsu.AddUint8(dwarf.DW_CFA_offset_extended)                           // The previous value...
  1402  		dwarf.Uleb128put(d, fsd, int64(thearch.Dwarfreglr))                  // ...of the return address...
  1403  		dwarf.Uleb128put(d, fsd, int64(-d.arch.PtrSize)/dataAlignmentFactor) // ...is saved at [CFA - (PtrSize/4)].
  1404  	}
  1405  
  1406  	pad := int64(cieReserve) + lengthFieldSize - int64(len(d.ldr.Data(fs)))
  1407  
  1408  	if pad < 0 {
  1409  		Exitf("dwarf: cieReserve too small by %d bytes.", -pad)
  1410  	}
  1411  
  1412  	internalExec := d.linkctxt.BuildMode == BuildModeExe && d.linkctxt.IsInternal()
  1413  	addAddrPlus := loader.GenAddAddrPlusFunc(internalExec)
  1414  
  1415  	fsu.AddBytes(zeros[:pad])
  1416  
  1417  	var deltaBuf []byte
  1418  	pcsp := obj.NewPCIter(uint32(d.arch.MinLC))
  1419  	for _, s := range d.linkctxt.Textp {
  1420  		fn := loader.Sym(s)
  1421  		fi := d.ldr.FuncInfo(fn)
  1422  		if !fi.Valid() {
  1423  			continue
  1424  		}
  1425  		fpcsp := d.ldr.Pcsp(s)
  1426  
  1427  		// Emit a FDE, Section 6.4.1.
  1428  		// First build the section contents into a byte buffer.
  1429  		deltaBuf = deltaBuf[:0]
  1430  		if haslr && fi.TopFrame() {
  1431  			// Mark the link register as having an undefined value.
  1432  			// This stops call stack unwinders progressing any further.
  1433  			// TODO: similar mark on non-LR architectures.
  1434  			deltaBuf = append(deltaBuf, dwarf.DW_CFA_undefined)
  1435  			deltaBuf = dwarf.AppendUleb128(deltaBuf, uint64(thearch.Dwarfreglr))
  1436  		}
  1437  
  1438  		for pcsp.Init(d.linkctxt.loader.Data(fpcsp)); !pcsp.Done; pcsp.Next() {
  1439  			nextpc := pcsp.NextPC
  1440  
  1441  			// pciterinit goes up to the end of the function,
  1442  			// but DWARF expects us to stop just before the end.
  1443  			if int64(nextpc) == int64(len(d.ldr.Data(fn))) {
  1444  				nextpc--
  1445  				if nextpc < pcsp.PC {
  1446  					continue
  1447  				}
  1448  			}
  1449  
  1450  			spdelta := int64(pcsp.Value)
  1451  			if !haslr {
  1452  				// Return address has been pushed onto stack.
  1453  				spdelta += int64(d.arch.PtrSize)
  1454  			}
  1455  
  1456  			if haslr && !fi.TopFrame() {
  1457  				// TODO(bryanpkc): This is imprecise. In general, the instruction
  1458  				// that stores the return address to the stack frame is not the
  1459  				// same one that allocates the frame.
  1460  				if pcsp.Value > 0 {
  1461  					// The return address is preserved at (CFA-frame_size)
  1462  					// after a stack frame has been allocated.
  1463  					deltaBuf = append(deltaBuf, dwarf.DW_CFA_offset_extended_sf)
  1464  					deltaBuf = dwarf.AppendUleb128(deltaBuf, uint64(thearch.Dwarfreglr))
  1465  					deltaBuf = dwarf.AppendSleb128(deltaBuf, -spdelta/dataAlignmentFactor)
  1466  				} else {
  1467  					// The return address is restored into the link register
  1468  					// when a stack frame has been de-allocated.
  1469  					deltaBuf = append(deltaBuf, dwarf.DW_CFA_same_value)
  1470  					deltaBuf = dwarf.AppendUleb128(deltaBuf, uint64(thearch.Dwarfreglr))
  1471  				}
  1472  			}
  1473  
  1474  			deltaBuf = appendPCDeltaCFA(d.arch, deltaBuf, int64(nextpc)-int64(pcsp.PC), spdelta)
  1475  		}
  1476  		pad := int(Rnd(int64(len(deltaBuf)), int64(d.arch.PtrSize))) - len(deltaBuf)
  1477  		deltaBuf = append(deltaBuf, zeros[:pad]...)
  1478  
  1479  		// Emit the FDE header, Section 6.4.1.
  1480  		//	4 bytes: length, must be multiple of thearch.ptrsize
  1481  		//	4/8 bytes: Pointer to the CIE above, at offset 0
  1482  		//	ptrsize: initial location
  1483  		//	ptrsize: address range
  1484  
  1485  		fdeLength := uint64(4 + 2*d.arch.PtrSize + len(deltaBuf))
  1486  		if isdw64 {
  1487  			fdeLength += 4 // 4 bytes added for CIE pointer
  1488  		}
  1489  		d.createUnitLength(fsu, fdeLength)
  1490  
  1491  		if d.linkctxt.LinkMode == LinkExternal {
  1492  			d.addDwarfAddrRef(fsu, fs)
  1493  		} else {
  1494  			d.addDwarfAddrField(fsu, 0) // CIE offset
  1495  		}
  1496  		addAddrPlus(fsu, d.arch, s, 0)
  1497  		fsu.AddUintXX(d.arch, uint64(len(d.ldr.Data(fn))), d.arch.PtrSize) // address range
  1498  		fsu.AddBytes(deltaBuf)
  1499  
  1500  		if d.linkctxt.HeadType == objabi.Haix {
  1501  			addDwsectCUSize(".debug_frame", d.ldr.SymPkg(fn), fdeLength+uint64(lengthFieldSize))
  1502  		}
  1503  	}
  1504  
  1505  	return dwarfSecInfo{syms: []loader.Sym{fs}}
  1506  }
  1507  
  1508  /*
  1509   *  Walk DWarfDebugInfoEntries, and emit .debug_info
  1510   */
  1511  
  1512  const (
  1513  	COMPUNITHEADERSIZE = 4 + 2 + 4 + 1
  1514  )
  1515  
  1516  // appendSyms appends the syms from 'src' into 'syms' and returns the
  1517  // result. This can go away once we do away with sym.LoaderSym
  1518  // entirely.
  1519  func appendSyms(syms []loader.Sym, src []sym.LoaderSym) []loader.Sym {
  1520  	for _, s := range src {
  1521  		syms = append(syms, loader.Sym(s))
  1522  	}
  1523  	return syms
  1524  }
  1525  
  1526  func (d *dwctxt) writeUnitInfo(u *sym.CompilationUnit, abbrevsym loader.Sym, infoEpilog loader.Sym) []loader.Sym {
  1527  	syms := []loader.Sym{}
  1528  	if len(u.Textp) == 0 && u.DWInfo.Child == nil && len(u.VarDIEs) == 0 {
  1529  		return syms
  1530  	}
  1531  
  1532  	compunit := u.DWInfo
  1533  	s := d.dtolsym(compunit.Sym)
  1534  	su := d.ldr.MakeSymbolUpdater(s)
  1535  
  1536  	// Write .debug_info Compilation Unit Header (sec 7.5.1)
  1537  	// Fields marked with (*) must be changed for 64-bit dwarf
  1538  	// This must match COMPUNITHEADERSIZE above.
  1539  	d.createUnitLength(su, 0) // unit_length (*), will be filled in later.
  1540  	su.AddUint16(d.arch, 4)   // dwarf version (appendix F)
  1541  
  1542  	// debug_abbrev_offset (*)
  1543  	d.addDwarfAddrRef(su, abbrevsym)
  1544  
  1545  	su.AddUint8(uint8(d.arch.PtrSize)) // address_size
  1546  
  1547  	ds := dwSym(s)
  1548  	dwarf.Uleb128put(d, ds, int64(compunit.Abbrev))
  1549  	dwarf.PutAttrs(d, ds, compunit.Abbrev, compunit.Attr)
  1550  
  1551  	// This is an under-estimate; more will be needed for type DIEs.
  1552  	cu := make([]loader.Sym, 0, len(u.AbsFnDIEs)+len(u.FuncDIEs))
  1553  	cu = append(cu, s)
  1554  	cu = appendSyms(cu, u.AbsFnDIEs)
  1555  	cu = appendSyms(cu, u.FuncDIEs)
  1556  	if u.Consts != 0 {
  1557  		cu = append(cu, loader.Sym(u.Consts))
  1558  	}
  1559  	cu = appendSyms(cu, u.VarDIEs)
  1560  	var cusize int64
  1561  	for _, child := range cu {
  1562  		cusize += int64(len(d.ldr.Data(child)))
  1563  	}
  1564  
  1565  	for die := compunit.Child; die != nil; die = die.Link {
  1566  		l := len(cu)
  1567  		lastSymSz := int64(len(d.ldr.Data(cu[l-1])))
  1568  		cu = d.putdie(cu, die)
  1569  		if lastSymSz != int64(len(d.ldr.Data(cu[l-1]))) {
  1570  			// putdie will sometimes append directly to the last symbol of the list
  1571  			cusize = cusize - lastSymSz + int64(len(d.ldr.Data(cu[l-1])))
  1572  		}
  1573  		for _, child := range cu[l:] {
  1574  			cusize += int64(len(d.ldr.Data(child)))
  1575  		}
  1576  	}
  1577  
  1578  	culu := d.ldr.MakeSymbolUpdater(infoEpilog)
  1579  	culu.AddUint8(0) // closes compilation unit DIE
  1580  	cu = append(cu, infoEpilog)
  1581  	cusize++
  1582  
  1583  	// Save size for AIX symbol table.
  1584  	if d.linkctxt.HeadType == objabi.Haix {
  1585  		addDwsectCUSize(".debug_info", d.getPkgFromCUSym(s), uint64(cusize))
  1586  	}
  1587  	if isDwarf64(d.linkctxt) {
  1588  		cusize -= 12                          // exclude the length field.
  1589  		su.SetUint(d.arch, 4, uint64(cusize)) // 4 because of 0XFFFFFFFF
  1590  	} else {
  1591  		cusize -= 4 // exclude the length field.
  1592  		su.SetUint32(d.arch, 0, uint32(cusize))
  1593  	}
  1594  	return append(syms, cu...)
  1595  }
  1596  
  1597  func (d *dwctxt) writegdbscript() dwarfSecInfo {
  1598  	// TODO (aix): make it available
  1599  	if d.linkctxt.HeadType == objabi.Haix {
  1600  		return dwarfSecInfo{}
  1601  	}
  1602  	if d.linkctxt.LinkMode == LinkExternal && d.linkctxt.HeadType == objabi.Hwindows && d.linkctxt.BuildMode == BuildModeCArchive {
  1603  		// gcc on Windows places .debug_gdb_scripts in the wrong location, which
  1604  		// causes the program not to run. See https://golang.org/issue/20183
  1605  		// Non c-archives can avoid this issue via a linker script
  1606  		// (see fix near writeGDBLinkerScript).
  1607  		// c-archive users would need to specify the linker script manually.
  1608  		// For UX it's better not to deal with this.
  1609  		return dwarfSecInfo{}
  1610  	}
  1611  	if gdbscript == "" {
  1612  		return dwarfSecInfo{}
  1613  	}
  1614  
  1615  	gs := d.ldr.CreateSymForUpdate(".debug_gdb_scripts", 0)
  1616  	gs.SetType(sym.SDWARFSECT)
  1617  
  1618  	gs.AddUint8(GdbScriptPythonFileId)
  1619  	gs.Addstring(gdbscript)
  1620  	return dwarfSecInfo{syms: []loader.Sym{gs.Sym()}}
  1621  }
  1622  
  1623  // FIXME: might be worth looking replacing this map with a function
  1624  // that switches based on symbol instead.
  1625  
  1626  var prototypedies map[string]*dwarf.DWDie
  1627  
  1628  func dwarfEnabled(ctxt *Link) bool {
  1629  	if *FlagW { // disable dwarf
  1630  		return false
  1631  	}
  1632  	if *FlagS && ctxt.HeadType != objabi.Hdarwin {
  1633  		return false
  1634  	}
  1635  	if ctxt.HeadType == objabi.Hplan9 || ctxt.HeadType == objabi.Hjs {
  1636  		return false
  1637  	}
  1638  
  1639  	if ctxt.LinkMode == LinkExternal {
  1640  		switch {
  1641  		case ctxt.IsELF:
  1642  		case ctxt.HeadType == objabi.Hdarwin:
  1643  		case ctxt.HeadType == objabi.Hwindows:
  1644  		case ctxt.HeadType == objabi.Haix:
  1645  			res, err := dwarf.IsDWARFEnabledOnAIXLd(ctxt.extld())
  1646  			if err != nil {
  1647  				Exitf("%v", err)
  1648  			}
  1649  			return res
  1650  		default:
  1651  			return false
  1652  		}
  1653  	}
  1654  
  1655  	return true
  1656  }
  1657  
  1658  // mkBuiltinType populates the dwctxt2 sym lookup maps for the
  1659  // newly created builtin type DIE 'typeDie'.
  1660  func (d *dwctxt) mkBuiltinType(ctxt *Link, abrv int, tname string) *dwarf.DWDie {
  1661  	// create type DIE
  1662  	die := d.newdie(&dwtypes, abrv, tname)
  1663  
  1664  	// Look up type symbol.
  1665  	gotype := d.lookupOrDiag("type." + tname)
  1666  
  1667  	// Map from die sym to type sym
  1668  	ds := loader.Sym(die.Sym.(dwSym))
  1669  	d.rtmap[ds] = gotype
  1670  
  1671  	// Map from type to def sym
  1672  	d.tdmap[gotype] = ds
  1673  
  1674  	return die
  1675  }
  1676  
  1677  // dwarfVisitFunction takes a function (text) symbol and processes the
  1678  // subprogram DIE for the function and picks up any other DIEs
  1679  // (absfns, types) that it references.
  1680  func (d *dwctxt) dwarfVisitFunction(fnSym loader.Sym, unit *sym.CompilationUnit) {
  1681  	// The DWARF subprogram DIE symbol is listed as an aux sym
  1682  	// of the text (fcn) symbol, so ask the loader to retrieve it,
  1683  	// as well as the associated range symbol.
  1684  	infosym, _, rangesym, _ := d.ldr.GetFuncDwarfAuxSyms(fnSym)
  1685  	if infosym == 0 {
  1686  		return
  1687  	}
  1688  	d.ldr.SetAttrNotInSymbolTable(infosym, true)
  1689  	d.ldr.SetAttrReachable(infosym, true)
  1690  	unit.FuncDIEs = append(unit.FuncDIEs, sym.LoaderSym(infosym))
  1691  	if rangesym != 0 {
  1692  		d.ldr.SetAttrNotInSymbolTable(rangesym, true)
  1693  		d.ldr.SetAttrReachable(rangesym, true)
  1694  		unit.RangeSyms = append(unit.RangeSyms, sym.LoaderSym(rangesym))
  1695  	}
  1696  
  1697  	// Walk the relocations of the subprogram DIE symbol to discover
  1698  	// references to abstract function DIEs, Go type DIES, and
  1699  	// (via R_USETYPE relocs) types that were originally assigned to
  1700  	// locals/params but were optimized away.
  1701  	drelocs := d.ldr.Relocs(infosym)
  1702  	for ri := 0; ri < drelocs.Count(); ri++ {
  1703  		r := drelocs.At(ri)
  1704  		// Look for "use type" relocs.
  1705  		if r.Type() == objabi.R_USETYPE {
  1706  			d.defgotype(r.Sym())
  1707  			continue
  1708  		}
  1709  		if r.Type() != objabi.R_DWARFSECREF {
  1710  			continue
  1711  		}
  1712  
  1713  		rsym := r.Sym()
  1714  		rst := d.ldr.SymType(rsym)
  1715  
  1716  		// Look for abstract function references.
  1717  		if rst == sym.SDWARFABSFCN {
  1718  			if !d.ldr.AttrOnList(rsym) {
  1719  				// abstract function
  1720  				d.ldr.SetAttrOnList(rsym, true)
  1721  				unit.AbsFnDIEs = append(unit.AbsFnDIEs, sym.LoaderSym(rsym))
  1722  				d.importInfoSymbol(rsym)
  1723  			}
  1724  			continue
  1725  		}
  1726  
  1727  		// Look for type references.
  1728  		if rst != sym.SDWARFTYPE && rst != sym.Sxxx {
  1729  			continue
  1730  		}
  1731  		if _, ok := d.rtmap[rsym]; ok {
  1732  			// type already generated
  1733  			continue
  1734  		}
  1735  
  1736  		rsn := d.ldr.SymName(rsym)
  1737  		tn := rsn[len(dwarf.InfoPrefix):]
  1738  		ts := d.ldr.Lookup("type."+tn, 0)
  1739  		d.defgotype(ts)
  1740  	}
  1741  }
  1742  
  1743  // dwarfGenerateDebugInfo generated debug info entries for all types,
  1744  // variables and functions in the program.
  1745  // Along with dwarfGenerateDebugSyms they are the two main entry points into
  1746  // dwarf generation: dwarfGenerateDebugInfo does all the work that should be
  1747  // done before symbol names are mangled while dwarfGenerateDebugSyms does
  1748  // all the work that can only be done after addresses have been assigned to
  1749  // text symbols.
  1750  func dwarfGenerateDebugInfo(ctxt *Link) {
  1751  	if !dwarfEnabled(ctxt) {
  1752  		return
  1753  	}
  1754  
  1755  	d := &dwctxt{
  1756  		linkctxt: ctxt,
  1757  		ldr:      ctxt.loader,
  1758  		arch:     ctxt.Arch,
  1759  		tmap:     make(map[string]loader.Sym),
  1760  		tdmap:    make(map[loader.Sym]loader.Sym),
  1761  		rtmap:    make(map[loader.Sym]loader.Sym),
  1762  	}
  1763  	d.typeRuntimeEface = d.lookupOrDiag("type.runtime.eface")
  1764  	d.typeRuntimeIface = d.lookupOrDiag("type.runtime.iface")
  1765  
  1766  	if ctxt.HeadType == objabi.Haix {
  1767  		// Initial map used to store package size for each DWARF section.
  1768  		dwsectCUSize = make(map[string]uint64)
  1769  	}
  1770  
  1771  	// For ctxt.Diagnostic messages.
  1772  	newattr(&dwtypes, dwarf.DW_AT_name, dwarf.DW_CLS_STRING, int64(len("dwtypes")), "dwtypes")
  1773  
  1774  	// Unspecified type. There are no references to this in the symbol table.
  1775  	d.newdie(&dwtypes, dwarf.DW_ABRV_NULLTYPE, "<unspecified>")
  1776  
  1777  	// Some types that must exist to define other ones (uintptr in particular
  1778  	// is needed for array size)
  1779  	d.mkBuiltinType(ctxt, dwarf.DW_ABRV_BARE_PTRTYPE, "unsafe.Pointer")
  1780  	die := d.mkBuiltinType(ctxt, dwarf.DW_ABRV_BASETYPE, "uintptr")
  1781  	newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_unsigned, 0)
  1782  	newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, int64(d.arch.PtrSize), 0)
  1783  	newattr(die, dwarf.DW_AT_go_kind, dwarf.DW_CLS_CONSTANT, objabi.KindUintptr, 0)
  1784  	newattr(die, dwarf.DW_AT_go_runtime_type, dwarf.DW_CLS_ADDRESS, 0, dwSym(d.lookupOrDiag("type.uintptr")))
  1785  
  1786  	d.uintptrInfoSym = d.mustFind("uintptr")
  1787  
  1788  	// Prototypes needed for type synthesis.
  1789  	prototypedies = map[string]*dwarf.DWDie{
  1790  		"type.runtime.stringStructDWARF": nil,
  1791  		"type.runtime.slice":             nil,
  1792  		"type.runtime.hmap":              nil,
  1793  		"type.runtime.bmap":              nil,
  1794  		"type.runtime.sudog":             nil,
  1795  		"type.runtime.waitq":             nil,
  1796  		"type.runtime.hchan":             nil,
  1797  	}
  1798  
  1799  	// Needed by the prettyprinter code for interface inspection.
  1800  	for _, typ := range []string{
  1801  		"type.runtime._type",
  1802  		"type.runtime.arraytype",
  1803  		"type.runtime.chantype",
  1804  		"type.runtime.functype",
  1805  		"type.runtime.maptype",
  1806  		"type.runtime.ptrtype",
  1807  		"type.runtime.slicetype",
  1808  		"type.runtime.structtype",
  1809  		"type.runtime.interfacetype",
  1810  		"type.runtime.itab",
  1811  		"type.runtime.imethod"} {
  1812  		d.defgotype(d.lookupOrDiag(typ))
  1813  	}
  1814  
  1815  	// fake root DIE for compile unit DIEs
  1816  	var dwroot dwarf.DWDie
  1817  	flagVariants := make(map[string]bool)
  1818  
  1819  	for _, lib := range ctxt.Library {
  1820  
  1821  		consts := d.ldr.Lookup(dwarf.ConstInfoPrefix+lib.Pkg, 0)
  1822  		for _, unit := range lib.Units {
  1823  			// We drop the constants into the first CU.
  1824  			if consts != 0 {
  1825  				unit.Consts = sym.LoaderSym(consts)
  1826  				d.importInfoSymbol(consts)
  1827  				consts = 0
  1828  			}
  1829  			ctxt.compUnits = append(ctxt.compUnits, unit)
  1830  
  1831  			// We need at least one runtime unit.
  1832  			if unit.Lib.Pkg == "runtime" {
  1833  				ctxt.runtimeCU = unit
  1834  			}
  1835  
  1836  			cuabrv := dwarf.DW_ABRV_COMPUNIT
  1837  			if len(unit.Textp) == 0 {
  1838  				cuabrv = dwarf.DW_ABRV_COMPUNIT_TEXTLESS
  1839  			}
  1840  			unit.DWInfo = d.newdie(&dwroot, cuabrv, unit.Lib.Pkg)
  1841  			newattr(unit.DWInfo, dwarf.DW_AT_language, dwarf.DW_CLS_CONSTANT, int64(dwarf.DW_LANG_Go), 0)
  1842  			// OS X linker requires compilation dir or absolute path in comp unit name to output debug info.
  1843  			compDir := getCompilationDir()
  1844  			// TODO: Make this be the actual compilation directory, not
  1845  			// the linker directory. If we move CU construction into the
  1846  			// compiler, this should happen naturally.
  1847  			newattr(unit.DWInfo, dwarf.DW_AT_comp_dir, dwarf.DW_CLS_STRING, int64(len(compDir)), compDir)
  1848  
  1849  			var peData []byte
  1850  			if producerExtra := d.ldr.Lookup(dwarf.CUInfoPrefix+"producer."+unit.Lib.Pkg, 0); producerExtra != 0 {
  1851  				peData = d.ldr.Data(producerExtra)
  1852  			}
  1853  			producer := "Go cmd/compile " + buildcfg.Version
  1854  			if len(peData) > 0 {
  1855  				// We put a semicolon before the flags to clearly
  1856  				// separate them from the version, which can be long
  1857  				// and have lots of weird things in it in development
  1858  				// versions. We promise not to put a semicolon in the
  1859  				// version, so it should be safe for readers to scan
  1860  				// forward to the semicolon.
  1861  				producer += "; " + string(peData)
  1862  				flagVariants[string(peData)] = true
  1863  			} else {
  1864  				flagVariants[""] = true
  1865  			}
  1866  
  1867  			newattr(unit.DWInfo, dwarf.DW_AT_producer, dwarf.DW_CLS_STRING, int64(len(producer)), producer)
  1868  
  1869  			var pkgname string
  1870  			if pnSymIdx := d.ldr.Lookup(dwarf.CUInfoPrefix+"packagename."+unit.Lib.Pkg, 0); pnSymIdx != 0 {
  1871  				pnsData := d.ldr.Data(pnSymIdx)
  1872  				pkgname = string(pnsData)
  1873  			}
  1874  			newattr(unit.DWInfo, dwarf.DW_AT_go_package_name, dwarf.DW_CLS_STRING, int64(len(pkgname)), pkgname)
  1875  
  1876  			// Scan all functions in this compilation unit, create
  1877  			// DIEs for all referenced types, find all referenced
  1878  			// abstract functions, visit range symbols. Note that
  1879  			// Textp has been dead-code-eliminated already.
  1880  			for _, s := range unit.Textp {
  1881  				d.dwarfVisitFunction(loader.Sym(s), unit)
  1882  			}
  1883  		}
  1884  	}
  1885  
  1886  	// Fix for 31034: if the objects feeding into this link were compiled
  1887  	// with different sets of flags, then don't issue an error if
  1888  	// the -strictdups checks fail.
  1889  	if checkStrictDups > 1 && len(flagVariants) > 1 {
  1890  		checkStrictDups = 1
  1891  	}
  1892  
  1893  	// Make a pass through all data symbols, looking for those
  1894  	// corresponding to reachable, Go-generated, user-visible
  1895  	// global variables. For each global of this sort, locate
  1896  	// the corresponding compiler-generated DIE symbol and tack
  1897  	// it onto the list associated with the unit.
  1898  	// Also looks for dictionary symbols and generates DIE symbols for each
  1899  	// type they reference.
  1900  	for idx := loader.Sym(1); idx < loader.Sym(d.ldr.NDef()); idx++ {
  1901  		if !d.ldr.AttrReachable(idx) ||
  1902  			d.ldr.AttrNotInSymbolTable(idx) ||
  1903  			d.ldr.SymVersion(idx) >= sym.SymVerStatic {
  1904  			continue
  1905  		}
  1906  		t := d.ldr.SymType(idx)
  1907  		switch t {
  1908  		case sym.SRODATA, sym.SDATA, sym.SNOPTRDATA, sym.STYPE, sym.SBSS, sym.SNOPTRBSS, sym.STLSBSS:
  1909  			// ok
  1910  		default:
  1911  			continue
  1912  		}
  1913  		// Skip things with no type, unless it's a dictionary
  1914  		gt := d.ldr.SymGoType(idx)
  1915  		if gt == 0 {
  1916  			if t == sym.SRODATA {
  1917  				if d.ldr.IsDict(idx) {
  1918  					// This is a dictionary, make sure that all types referenced by this dictionary are reachable
  1919  					relocs := d.ldr.Relocs(idx)
  1920  					for i := 0; i < relocs.Count(); i++ {
  1921  						reloc := relocs.At(i)
  1922  						if reloc.Type() == objabi.R_USEIFACE {
  1923  							d.defgotype(reloc.Sym())
  1924  						}
  1925  					}
  1926  				}
  1927  			}
  1928  			continue
  1929  		}
  1930  		// Skip file local symbols (this includes static tmps, stack
  1931  		// object symbols, and local symbols in assembler src files).
  1932  		if d.ldr.IsFileLocal(idx) {
  1933  			continue
  1934  		}
  1935  		sn := d.ldr.SymName(idx)
  1936  		if sn == "" {
  1937  			// skip aux symbols
  1938  			continue
  1939  		}
  1940  
  1941  		// Find compiler-generated DWARF info sym for global in question,
  1942  		// and tack it onto the appropriate unit.  Note that there are
  1943  		// circumstances under which we can't find the compiler-generated
  1944  		// symbol-- this typically happens as a result of compiler options
  1945  		// (e.g. compile package X with "-dwarf=0").
  1946  
  1947  		// FIXME: use an aux sym or a relocation here instead of a
  1948  		// name lookup.
  1949  		varDIE := d.ldr.Lookup(dwarf.InfoPrefix+sn, 0)
  1950  		if varDIE != 0 {
  1951  			unit := d.ldr.SymUnit(idx)
  1952  			d.defgotype(gt)
  1953  			unit.VarDIEs = append(unit.VarDIEs, sym.LoaderSym(varDIE))
  1954  		}
  1955  	}
  1956  
  1957  	d.synthesizestringtypes(ctxt, dwtypes.Child)
  1958  	d.synthesizeslicetypes(ctxt, dwtypes.Child)
  1959  	d.synthesizemaptypes(ctxt, dwtypes.Child)
  1960  	d.synthesizechantypes(ctxt, dwtypes.Child)
  1961  }
  1962  
  1963  // dwarfGenerateDebugSyms constructs debug_line, debug_frame, and
  1964  // debug_loc. It also writes out the debug_info section using symbols
  1965  // generated in dwarfGenerateDebugInfo2.
  1966  func dwarfGenerateDebugSyms(ctxt *Link) {
  1967  	if !dwarfEnabled(ctxt) {
  1968  		return
  1969  	}
  1970  	d := &dwctxt{
  1971  		linkctxt: ctxt,
  1972  		ldr:      ctxt.loader,
  1973  		arch:     ctxt.Arch,
  1974  		dwmu:     new(sync.Mutex),
  1975  	}
  1976  	d.dwarfGenerateDebugSyms()
  1977  }
  1978  
  1979  // dwUnitSyms stores input and output symbols for DWARF generation
  1980  // for a given compilation unit.
  1981  type dwUnitSyms struct {
  1982  	// Inputs for a given unit.
  1983  	lineProlog  loader.Sym
  1984  	rangeProlog loader.Sym
  1985  	infoEpilog  loader.Sym
  1986  
  1987  	// Outputs for a given unit.
  1988  	linesyms   []loader.Sym
  1989  	infosyms   []loader.Sym
  1990  	locsyms    []loader.Sym
  1991  	rangessyms []loader.Sym
  1992  }
  1993  
  1994  // dwUnitPortion assembles the DWARF content for a given compilation
  1995  // unit: debug_info, debug_lines, debug_ranges, debug_loc (debug_frame
  1996  // is handled elsewere). Order is important; the calls to writelines
  1997  // and writepcranges below make updates to the compilation unit DIE,
  1998  // hence they have to happen before the call to writeUnitInfo.
  1999  func (d *dwctxt) dwUnitPortion(u *sym.CompilationUnit, abbrevsym loader.Sym, us *dwUnitSyms) {
  2000  	if u.DWInfo.Abbrev != dwarf.DW_ABRV_COMPUNIT_TEXTLESS {
  2001  		us.linesyms = d.writelines(u, us.lineProlog)
  2002  		base := loader.Sym(u.Textp[0])
  2003  		us.rangessyms = d.writepcranges(u, base, u.PCs, us.rangeProlog)
  2004  		us.locsyms = d.collectUnitLocs(u)
  2005  	}
  2006  	us.infosyms = d.writeUnitInfo(u, abbrevsym, us.infoEpilog)
  2007  }
  2008  
  2009  func (d *dwctxt) dwarfGenerateDebugSyms() {
  2010  	abbrevSec := d.writeabbrev()
  2011  	dwarfp = append(dwarfp, abbrevSec)
  2012  	d.calcCompUnitRanges()
  2013  	sort.Sort(compilationUnitByStartPC(d.linkctxt.compUnits))
  2014  
  2015  	// newdie adds DIEs to the *beginning* of the parent's DIE list.
  2016  	// Now that we're done creating DIEs, reverse the trees so DIEs
  2017  	// appear in the order they were created.
  2018  	for _, u := range d.linkctxt.compUnits {
  2019  		reversetree(&u.DWInfo.Child)
  2020  	}
  2021  	reversetree(&dwtypes.Child)
  2022  	movetomodule(d.linkctxt, &dwtypes)
  2023  
  2024  	mkSecSym := func(name string) loader.Sym {
  2025  		s := d.ldr.CreateSymForUpdate(name, 0)
  2026  		s.SetType(sym.SDWARFSECT)
  2027  		s.SetReachable(true)
  2028  		return s.Sym()
  2029  	}
  2030  	mkAnonSym := func(kind sym.SymKind) loader.Sym {
  2031  		s := d.ldr.MakeSymbolUpdater(d.ldr.CreateExtSym("", 0))
  2032  		s.SetType(kind)
  2033  		s.SetReachable(true)
  2034  		return s.Sym()
  2035  	}
  2036  
  2037  	// Create the section symbols.
  2038  	frameSym := mkSecSym(".debug_frame")
  2039  	locSym := mkSecSym(".debug_loc")
  2040  	lineSym := mkSecSym(".debug_line")
  2041  	rangesSym := mkSecSym(".debug_ranges")
  2042  	infoSym := mkSecSym(".debug_info")
  2043  
  2044  	// Create the section objects
  2045  	lineSec := dwarfSecInfo{syms: []loader.Sym{lineSym}}
  2046  	locSec := dwarfSecInfo{syms: []loader.Sym{locSym}}
  2047  	rangesSec := dwarfSecInfo{syms: []loader.Sym{rangesSym}}
  2048  	frameSec := dwarfSecInfo{syms: []loader.Sym{frameSym}}
  2049  	infoSec := dwarfSecInfo{syms: []loader.Sym{infoSym}}
  2050  
  2051  	// Create any new symbols that will be needed during the
  2052  	// parallel portion below.
  2053  	ncu := len(d.linkctxt.compUnits)
  2054  	unitSyms := make([]dwUnitSyms, ncu)
  2055  	for i := 0; i < ncu; i++ {
  2056  		us := &unitSyms[i]
  2057  		us.lineProlog = mkAnonSym(sym.SDWARFLINES)
  2058  		us.rangeProlog = mkAnonSym(sym.SDWARFRANGE)
  2059  		us.infoEpilog = mkAnonSym(sym.SDWARFFCN)
  2060  	}
  2061  
  2062  	var wg sync.WaitGroup
  2063  	sema := make(chan struct{}, runtime.GOMAXPROCS(0))
  2064  
  2065  	// Kick off generation of .debug_frame, since it doesn't have
  2066  	// any entanglements and can be started right away.
  2067  	wg.Add(1)
  2068  	go func() {
  2069  		sema <- struct{}{}
  2070  		defer func() {
  2071  			<-sema
  2072  			wg.Done()
  2073  		}()
  2074  		frameSec = d.writeframes(frameSym)
  2075  	}()
  2076  
  2077  	// Create a goroutine per comp unit to handle the generation that
  2078  	// unit's portion of .debug_line, .debug_loc, .debug_ranges, and
  2079  	// .debug_info.
  2080  	wg.Add(len(d.linkctxt.compUnits))
  2081  	for i := 0; i < ncu; i++ {
  2082  		go func(u *sym.CompilationUnit, us *dwUnitSyms) {
  2083  			sema <- struct{}{}
  2084  			defer func() {
  2085  				<-sema
  2086  				wg.Done()
  2087  			}()
  2088  			d.dwUnitPortion(u, abbrevSec.secSym(), us)
  2089  		}(d.linkctxt.compUnits[i], &unitSyms[i])
  2090  	}
  2091  	wg.Wait()
  2092  
  2093  	markReachable := func(syms []loader.Sym) []loader.Sym {
  2094  		for _, s := range syms {
  2095  			d.ldr.SetAttrNotInSymbolTable(s, true)
  2096  			d.ldr.SetAttrReachable(s, true)
  2097  		}
  2098  		return syms
  2099  	}
  2100  
  2101  	// Stitch together the results.
  2102  	for i := 0; i < ncu; i++ {
  2103  		r := &unitSyms[i]
  2104  		lineSec.syms = append(lineSec.syms, markReachable(r.linesyms)...)
  2105  		infoSec.syms = append(infoSec.syms, markReachable(r.infosyms)...)
  2106  		locSec.syms = append(locSec.syms, markReachable(r.locsyms)...)
  2107  		rangesSec.syms = append(rangesSec.syms, markReachable(r.rangessyms)...)
  2108  	}
  2109  	dwarfp = append(dwarfp, lineSec)
  2110  	dwarfp = append(dwarfp, frameSec)
  2111  	gdbScriptSec := d.writegdbscript()
  2112  	if gdbScriptSec.secSym() != 0 {
  2113  		dwarfp = append(dwarfp, gdbScriptSec)
  2114  	}
  2115  	dwarfp = append(dwarfp, infoSec)
  2116  	if len(locSec.syms) > 1 {
  2117  		dwarfp = append(dwarfp, locSec)
  2118  	}
  2119  	dwarfp = append(dwarfp, rangesSec)
  2120  
  2121  	// Check to make sure we haven't listed any symbols more than once
  2122  	// in the info section. This used to be done by setting and
  2123  	// checking the OnList attribute in "putdie", but that strategy
  2124  	// was not friendly for concurrency.
  2125  	seen := loader.MakeBitmap(d.ldr.NSym())
  2126  	for _, s := range infoSec.syms {
  2127  		if seen.Has(s) {
  2128  			log.Fatalf("symbol %s listed multiple times", d.ldr.SymName(s))
  2129  		}
  2130  		seen.Set(s)
  2131  	}
  2132  }
  2133  
  2134  func (d *dwctxt) collectUnitLocs(u *sym.CompilationUnit) []loader.Sym {
  2135  	syms := []loader.Sym{}
  2136  	for _, fn := range u.FuncDIEs {
  2137  		relocs := d.ldr.Relocs(loader.Sym(fn))
  2138  		for i := 0; i < relocs.Count(); i++ {
  2139  			reloc := relocs.At(i)
  2140  			if reloc.Type() != objabi.R_DWARFSECREF {
  2141  				continue
  2142  			}
  2143  			rsym := reloc.Sym()
  2144  			if d.ldr.SymType(rsym) == sym.SDWARFLOC {
  2145  				syms = append(syms, rsym)
  2146  				// One location list entry per function, but many relocations to it. Don't duplicate.
  2147  				break
  2148  			}
  2149  		}
  2150  	}
  2151  	return syms
  2152  }
  2153  
  2154  /*
  2155   *  Elf.
  2156   */
  2157  func dwarfaddshstrings(ctxt *Link, shstrtab *loader.SymbolBuilder) {
  2158  	if *FlagW { // disable dwarf
  2159  		return
  2160  	}
  2161  
  2162  	secs := []string{"abbrev", "frame", "info", "loc", "line", "gdb_scripts", "ranges"}
  2163  	for _, sec := range secs {
  2164  		shstrtab.Addstring(".debug_" + sec)
  2165  		if ctxt.IsExternal() {
  2166  			shstrtab.Addstring(elfRelType + ".debug_" + sec)
  2167  		} else {
  2168  			shstrtab.Addstring(".zdebug_" + sec)
  2169  		}
  2170  	}
  2171  }
  2172  
  2173  func dwarfaddelfsectionsyms(ctxt *Link) {
  2174  	if *FlagW { // disable dwarf
  2175  		return
  2176  	}
  2177  	if ctxt.LinkMode != LinkExternal {
  2178  		return
  2179  	}
  2180  
  2181  	ldr := ctxt.loader
  2182  	for _, si := range dwarfp {
  2183  		s := si.secSym()
  2184  		sect := ldr.SymSect(si.secSym())
  2185  		putelfsectionsym(ctxt, ctxt.Out, s, sect.Elfsect.(*ElfShdr).shnum)
  2186  	}
  2187  }
  2188  
  2189  // dwarfcompress compresses the DWARF sections. Relocations are applied
  2190  // on the fly. After this, dwarfp will contain a different (new) set of
  2191  // symbols, and sections may have been replaced.
  2192  func dwarfcompress(ctxt *Link) {
  2193  	// compressedSect is a helper type for parallelizing compression.
  2194  	type compressedSect struct {
  2195  		index      int
  2196  		compressed []byte
  2197  		syms       []loader.Sym
  2198  	}
  2199  
  2200  	supported := ctxt.IsELF || ctxt.IsWindows() || ctxt.IsDarwin()
  2201  	if !ctxt.compressDWARF || !supported || ctxt.IsExternal() {
  2202  		return
  2203  	}
  2204  
  2205  	var compressedCount int
  2206  	resChannel := make(chan compressedSect)
  2207  	for i := range dwarfp {
  2208  		go func(resIndex int, syms []loader.Sym) {
  2209  			resChannel <- compressedSect{resIndex, compressSyms(ctxt, syms), syms}
  2210  		}(compressedCount, dwarfp[i].syms)
  2211  		compressedCount++
  2212  	}
  2213  	res := make([]compressedSect, compressedCount)
  2214  	for ; compressedCount > 0; compressedCount-- {
  2215  		r := <-resChannel
  2216  		res[r.index] = r
  2217  	}
  2218  
  2219  	ldr := ctxt.loader
  2220  	var newDwarfp []dwarfSecInfo
  2221  	Segdwarf.Sections = Segdwarf.Sections[:0]
  2222  	for _, z := range res {
  2223  		s := z.syms[0]
  2224  		if z.compressed == nil {
  2225  			// Compression didn't help.
  2226  			ds := dwarfSecInfo{syms: z.syms}
  2227  			newDwarfp = append(newDwarfp, ds)
  2228  			Segdwarf.Sections = append(Segdwarf.Sections, ldr.SymSect(s))
  2229  		} else {
  2230  			var compressedSegName string
  2231  			if ctxt.IsELF {
  2232  				compressedSegName = ldr.SymSect(s).Name
  2233  			} else {
  2234  				compressedSegName = ".zdebug_" + ldr.SymSect(s).Name[len(".debug_"):]
  2235  			}
  2236  			sect := addsection(ctxt.loader, ctxt.Arch, &Segdwarf, compressedSegName, 04)
  2237  			sect.Align = int32(ctxt.Arch.Alignment)
  2238  			sect.Length = uint64(len(z.compressed))
  2239  			sect.Compressed = true
  2240  			newSym := ldr.MakeSymbolBuilder(compressedSegName)
  2241  			ldr.SetAttrReachable(s, true)
  2242  			newSym.SetData(z.compressed)
  2243  			newSym.SetSize(int64(len(z.compressed)))
  2244  			ldr.SetSymSect(newSym.Sym(), sect)
  2245  			ds := dwarfSecInfo{syms: []loader.Sym{newSym.Sym()}}
  2246  			newDwarfp = append(newDwarfp, ds)
  2247  
  2248  			// compressed symbols are no longer needed.
  2249  			for _, s := range z.syms {
  2250  				ldr.SetAttrReachable(s, false)
  2251  				ldr.FreeSym(s)
  2252  			}
  2253  		}
  2254  	}
  2255  	dwarfp = newDwarfp
  2256  
  2257  	// Re-compute the locations of the compressed DWARF symbols
  2258  	// and sections, since the layout of these within the file is
  2259  	// based on Section.Vaddr and Symbol.Value.
  2260  	pos := Segdwarf.Vaddr
  2261  	var prevSect *sym.Section
  2262  	for _, si := range dwarfp {
  2263  		for _, s := range si.syms {
  2264  			ldr.SetSymValue(s, int64(pos))
  2265  			sect := ldr.SymSect(s)
  2266  			if sect != prevSect {
  2267  				sect.Vaddr = uint64(pos)
  2268  				prevSect = sect
  2269  			}
  2270  			if ldr.SubSym(s) != 0 {
  2271  				log.Fatalf("%s: unexpected sub-symbols", ldr.SymName(s))
  2272  			}
  2273  			pos += uint64(ldr.SymSize(s))
  2274  			if ctxt.IsWindows() {
  2275  				pos = uint64(Rnd(int64(pos), PEFILEALIGN))
  2276  			}
  2277  		}
  2278  	}
  2279  	Segdwarf.Length = pos - Segdwarf.Vaddr
  2280  }
  2281  
  2282  type compilationUnitByStartPC []*sym.CompilationUnit
  2283  
  2284  func (v compilationUnitByStartPC) Len() int      { return len(v) }
  2285  func (v compilationUnitByStartPC) Swap(i, j int) { v[i], v[j] = v[j], v[i] }
  2286  
  2287  func (v compilationUnitByStartPC) Less(i, j int) bool {
  2288  	switch {
  2289  	case len(v[i].Textp) == 0 && len(v[j].Textp) == 0:
  2290  		return v[i].Lib.Pkg < v[j].Lib.Pkg
  2291  	case len(v[i].Textp) != 0 && len(v[j].Textp) == 0:
  2292  		return true
  2293  	case len(v[i].Textp) == 0 && len(v[j].Textp) != 0:
  2294  		return false
  2295  	default:
  2296  		return v[i].PCs[0].Start < v[j].PCs[0].Start
  2297  	}
  2298  }
  2299  
  2300  // getPkgFromCUSym returns the package name for the compilation unit
  2301  // represented by s.
  2302  // The prefix dwarf.InfoPrefix+".pkg." needs to be removed in order to get
  2303  // the package name.
  2304  func (d *dwctxt) getPkgFromCUSym(s loader.Sym) string {
  2305  	return strings.TrimPrefix(d.ldr.SymName(s), dwarf.InfoPrefix+".pkg.")
  2306  }
  2307  
  2308  // On AIX, the symbol table needs to know where are the compilation units parts
  2309  // for a specific package in each .dw section.
  2310  // dwsectCUSize map will save the size of a compilation unit for
  2311  // the corresponding .dw section.
  2312  // This size can later be retrieved with the index "sectionName.pkgName".
  2313  var dwsectCUSizeMu sync.Mutex
  2314  var dwsectCUSize map[string]uint64
  2315  
  2316  // getDwsectCUSize retrieves the corresponding package size inside the current section.
  2317  func getDwsectCUSize(sname string, pkgname string) uint64 {
  2318  	return dwsectCUSize[sname+"."+pkgname]
  2319  }
  2320  
  2321  func addDwsectCUSize(sname string, pkgname string, size uint64) {
  2322  	dwsectCUSizeMu.Lock()
  2323  	defer dwsectCUSizeMu.Unlock()
  2324  	dwsectCUSize[sname+"."+pkgname] += size
  2325  }
  2326  

View as plain text