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

Documentation: cmd/link/internal/ld

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

View as plain text