github.com/go-asm/go@v1.21.1-0.20240213172139-40c5ead50c48/cmd/link/ld/dwarf.go (about)

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