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

View as plain text