...
Run Format

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

View as plain text