Black Lives Matter. Support the Equal Justice Initiative.

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

Documentation: cmd/link/internal/ld

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

View as plain text