github.com/zebozhuang/go@v0.0.0-20200207033046-f8a98f6f5c5d/src/cmd/link/internal/ld/dwarf.go (about)

     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/objabi"
    19  	"fmt"
    20  	"log"
    21  	"os"
    22  	"strings"
    23  )
    24  
    25  type dwctxt struct {
    26  	linkctxt *Link
    27  }
    28  
    29  func (c dwctxt) PtrSize() int {
    30  	return SysArch.PtrSize
    31  }
    32  func (c dwctxt) AddInt(s dwarf.Sym, size int, i int64) {
    33  	ls := s.(*Symbol)
    34  	adduintxx(c.linkctxt, ls, uint64(i), size)
    35  }
    36  func (c dwctxt) AddBytes(s dwarf.Sym, b []byte) {
    37  	ls := s.(*Symbol)
    38  	Addbytes(ls, b)
    39  }
    40  func (c dwctxt) AddString(s dwarf.Sym, v string) {
    41  	Addstring(s.(*Symbol), v)
    42  }
    43  func (c dwctxt) SymValue(s dwarf.Sym) int64 {
    44  	return s.(*Symbol).Value
    45  }
    46  
    47  func (c dwctxt) AddAddress(s dwarf.Sym, data interface{}, value int64) {
    48  	if value != 0 {
    49  		value -= (data.(*Symbol)).Value
    50  	}
    51  	Addaddrplus(c.linkctxt, s.(*Symbol), data.(*Symbol), value)
    52  }
    53  
    54  func (c dwctxt) AddSectionOffset(s dwarf.Sym, size int, t interface{}, ofs int64) {
    55  	ls := s.(*Symbol)
    56  	switch size {
    57  	default:
    58  		Errorf(ls, "invalid size %d in adddwarfref\n", size)
    59  		fallthrough
    60  	case SysArch.PtrSize:
    61  		Addaddr(c.linkctxt, ls, t.(*Symbol))
    62  	case 4:
    63  		addaddrplus4(c.linkctxt, ls, t.(*Symbol), 0)
    64  	}
    65  	r := &ls.R[len(ls.R)-1]
    66  	r.Type = objabi.R_DWARFREF
    67  	r.Add = ofs
    68  }
    69  
    70  /*
    71   * Offsets and sizes of the debug_* sections in the cout file.
    72   */
    73  var abbrevsym *Symbol
    74  var arangessec *Symbol
    75  var framesec *Symbol
    76  var infosec *Symbol
    77  var linesec *Symbol
    78  var rangesec *Symbol
    79  
    80  var gdbscript string
    81  
    82  var dwarfp []*Symbol
    83  
    84  func writeabbrev(ctxt *Link, syms []*Symbol) []*Symbol {
    85  	s := ctxt.Syms.Lookup(".debug_abbrev", 0)
    86  	s.Type = SDWARFSECT
    87  	abbrevsym = s
    88  	Addbytes(s, dwarf.GetAbbrev())
    89  	return append(syms, s)
    90  }
    91  
    92  /*
    93   * Root DIEs for compilation units, types and global variables.
    94   */
    95  var dwroot dwarf.DWDie
    96  
    97  var dwtypes dwarf.DWDie
    98  
    99  var dwglobals dwarf.DWDie
   100  
   101  func newattr(die *dwarf.DWDie, attr uint16, cls int, value int64, data interface{}) *dwarf.DWAttr {
   102  	a := new(dwarf.DWAttr)
   103  	a.Link = die.Attr
   104  	die.Attr = a
   105  	a.Atr = attr
   106  	a.Cls = uint8(cls)
   107  	a.Value = value
   108  	a.Data = data
   109  	return a
   110  }
   111  
   112  // Each DIE (except the root ones) has at least 1 attribute: its
   113  // name. getattr moves the desired one to the front so
   114  // frequently searched ones are found faster.
   115  func getattr(die *dwarf.DWDie, attr uint16) *dwarf.DWAttr {
   116  	if die.Attr.Atr == attr {
   117  		return die.Attr
   118  	}
   119  
   120  	a := die.Attr
   121  	b := a.Link
   122  	for b != nil {
   123  		if b.Atr == attr {
   124  			a.Link = b.Link
   125  			b.Link = die.Attr
   126  			die.Attr = b
   127  			return b
   128  		}
   129  
   130  		a = b
   131  		b = b.Link
   132  	}
   133  
   134  	return nil
   135  }
   136  
   137  // Every DIE has at least a AT_name attribute (but it will only be
   138  // written out if it is listed in the abbrev).
   139  func newdie(ctxt *Link, parent *dwarf.DWDie, abbrev int, name string, version int) *dwarf.DWDie {
   140  	die := new(dwarf.DWDie)
   141  	die.Abbrev = abbrev
   142  	die.Link = parent.Child
   143  	parent.Child = die
   144  
   145  	newattr(die, dwarf.DW_AT_name, dwarf.DW_CLS_STRING, int64(len(name)), name)
   146  
   147  	if name != "" && (abbrev <= dwarf.DW_ABRV_VARIABLE || abbrev >= dwarf.DW_ABRV_NULLTYPE) {
   148  		if abbrev != dwarf.DW_ABRV_VARIABLE || version == 0 {
   149  			sym := ctxt.Syms.Lookup(dwarf.InfoPrefix+name, version)
   150  			sym.Attr |= AttrNotInSymbolTable
   151  			sym.Type = SDWARFINFO
   152  			die.Sym = sym
   153  		}
   154  	}
   155  
   156  	return die
   157  }
   158  
   159  func walktypedef(die *dwarf.DWDie) *dwarf.DWDie {
   160  	if die == nil {
   161  		return nil
   162  	}
   163  	// Resolve typedef if present.
   164  	if die.Abbrev == dwarf.DW_ABRV_TYPEDECL {
   165  		for attr := die.Attr; attr != nil; attr = attr.Link {
   166  			if attr.Atr == dwarf.DW_AT_type && attr.Cls == dwarf.DW_CLS_REFERENCE && attr.Data != nil {
   167  				return attr.Data.(*dwarf.DWDie)
   168  			}
   169  		}
   170  	}
   171  
   172  	return die
   173  }
   174  
   175  func walksymtypedef(ctxt *Link, s *Symbol) *Symbol {
   176  	if t := ctxt.Syms.ROLookup(s.Name+"..def", int(s.Version)); t != nil {
   177  		return t
   178  	}
   179  	return s
   180  }
   181  
   182  // Find child by AT_name using hashtable if available or linear scan
   183  // if not.
   184  func findchild(die *dwarf.DWDie, name string) *dwarf.DWDie {
   185  	var prev *dwarf.DWDie
   186  	for ; die != prev; prev, die = die, walktypedef(die) {
   187  		for a := die.Child; a != nil; a = a.Link {
   188  			if name == getattr(a, dwarf.DW_AT_name).Data {
   189  				return a
   190  			}
   191  		}
   192  		continue
   193  	}
   194  	return nil
   195  }
   196  
   197  // Used to avoid string allocation when looking up dwarf symbols
   198  var prefixBuf = []byte(dwarf.InfoPrefix)
   199  
   200  func find(ctxt *Link, name string) *Symbol {
   201  	n := append(prefixBuf, name...)
   202  	// The string allocation below is optimized away because it is only used in a map lookup.
   203  	s := ctxt.Syms.ROLookup(string(n), 0)
   204  	prefixBuf = n[:len(dwarf.InfoPrefix)]
   205  	if s != nil && s.Type == SDWARFINFO {
   206  		return s
   207  	}
   208  	return nil
   209  }
   210  
   211  func mustFind(ctxt *Link, name string) *Symbol {
   212  	r := find(ctxt, name)
   213  	if r == nil {
   214  		Exitf("dwarf find: cannot find %s", name)
   215  	}
   216  	return r
   217  }
   218  
   219  func adddwarfref(ctxt *Link, s *Symbol, t *Symbol, size int) int64 {
   220  	var result int64
   221  	switch size {
   222  	default:
   223  		Errorf(s, "invalid size %d in adddwarfref\n", size)
   224  		fallthrough
   225  	case SysArch.PtrSize:
   226  		result = Addaddr(ctxt, s, t)
   227  	case 4:
   228  		result = addaddrplus4(ctxt, s, t, 0)
   229  	}
   230  	r := &s.R[len(s.R)-1]
   231  	r.Type = objabi.R_DWARFREF
   232  	return result
   233  }
   234  
   235  func newrefattr(die *dwarf.DWDie, attr uint16, ref *Symbol) *dwarf.DWAttr {
   236  	if ref == nil {
   237  		return nil
   238  	}
   239  	return newattr(die, attr, dwarf.DW_CLS_REFERENCE, 0, ref)
   240  }
   241  
   242  func putdies(linkctxt *Link, ctxt dwarf.Context, syms []*Symbol, die *dwarf.DWDie) []*Symbol {
   243  	for ; die != nil; die = die.Link {
   244  		syms = putdie(linkctxt, ctxt, syms, die)
   245  	}
   246  	Adduint8(linkctxt, syms[len(syms)-1], 0)
   247  
   248  	return syms
   249  }
   250  
   251  func dtolsym(s dwarf.Sym) *Symbol {
   252  	if s == nil {
   253  		return nil
   254  	}
   255  	return s.(*Symbol)
   256  }
   257  
   258  func putdie(linkctxt *Link, ctxt dwarf.Context, syms []*Symbol, die *dwarf.DWDie) []*Symbol {
   259  	s := dtolsym(die.Sym)
   260  	if s == nil {
   261  		s = syms[len(syms)-1]
   262  	} else {
   263  		if s.Attr.OnList() {
   264  			log.Fatalf("symbol %s listed multiple times", s.Name)
   265  		}
   266  		s.Attr |= AttrOnList
   267  		syms = append(syms, s)
   268  	}
   269  	dwarf.Uleb128put(ctxt, s, int64(die.Abbrev))
   270  	dwarf.PutAttrs(ctxt, s, die.Abbrev, die.Attr)
   271  	if dwarf.HasChildren(die) {
   272  		return putdies(linkctxt, ctxt, syms, die.Child)
   273  	}
   274  	return syms
   275  }
   276  
   277  func reverselist(list **dwarf.DWDie) {
   278  	curr := *list
   279  	var prev *dwarf.DWDie
   280  	for curr != nil {
   281  		var next *dwarf.DWDie = curr.Link
   282  		curr.Link = prev
   283  		prev = curr
   284  		curr = next
   285  	}
   286  
   287  	*list = prev
   288  }
   289  
   290  func reversetree(list **dwarf.DWDie) {
   291  	reverselist(list)
   292  	for die := *list; die != nil; die = die.Link {
   293  		if dwarf.HasChildren(die) {
   294  			reversetree(&die.Child)
   295  		}
   296  	}
   297  }
   298  
   299  func newmemberoffsetattr(die *dwarf.DWDie, offs int32) {
   300  	var block [20]byte
   301  	b := append(block[:0], dwarf.DW_OP_plus_uconst)
   302  	b = dwarf.AppendUleb128(b, uint64(offs))
   303  	newattr(die, dwarf.DW_AT_data_member_location, dwarf.DW_CLS_BLOCK, int64(len(b)), b)
   304  }
   305  
   306  // GDB doesn't like FORM_addr for AT_location, so emit a
   307  // location expression that evals to a const.
   308  func newabslocexprattr(die *dwarf.DWDie, addr int64, sym *Symbol) {
   309  	newattr(die, dwarf.DW_AT_location, dwarf.DW_CLS_ADDRESS, addr, sym)
   310  	// below
   311  }
   312  
   313  // Lookup predefined types
   314  func lookupOrDiag(ctxt *Link, n string) *Symbol {
   315  	s := ctxt.Syms.ROLookup(n, 0)
   316  	if s == nil || s.Size == 0 {
   317  		Exitf("dwarf: missing type: %s", n)
   318  	}
   319  
   320  	return s
   321  }
   322  
   323  func dotypedef(ctxt *Link, parent *dwarf.DWDie, name string, def *dwarf.DWDie) {
   324  	// Only emit typedefs for real names.
   325  	if strings.HasPrefix(name, "map[") {
   326  		return
   327  	}
   328  	if strings.HasPrefix(name, "struct {") {
   329  		return
   330  	}
   331  	if strings.HasPrefix(name, "chan ") {
   332  		return
   333  	}
   334  	if name[0] == '[' || name[0] == '*' {
   335  		return
   336  	}
   337  	if def == nil {
   338  		Errorf(nil, "dwarf: bad def in dotypedef")
   339  	}
   340  
   341  	sym := ctxt.Syms.Lookup(dtolsym(def.Sym).Name+"..def", 0)
   342  	sym.Attr |= AttrNotInSymbolTable
   343  	sym.Type = SDWARFINFO
   344  	def.Sym = sym
   345  
   346  	// The typedef entry must be created after the def,
   347  	// so that future lookups will find the typedef instead
   348  	// of the real definition. This hooks the typedef into any
   349  	// circular definition loops, so that gdb can understand them.
   350  	die := newdie(ctxt, parent, dwarf.DW_ABRV_TYPEDECL, name, 0)
   351  
   352  	newrefattr(die, dwarf.DW_AT_type, sym)
   353  }
   354  
   355  // Define gotype, for composite ones recurse into constituents.
   356  func defgotype(ctxt *Link, gotype *Symbol) *Symbol {
   357  	if gotype == nil {
   358  		return mustFind(ctxt, "<unspecified>")
   359  	}
   360  
   361  	if !strings.HasPrefix(gotype.Name, "type.") {
   362  		Errorf(gotype, "dwarf: type name doesn't start with \"type.\"")
   363  		return mustFind(ctxt, "<unspecified>")
   364  	}
   365  
   366  	name := gotype.Name[5:] // could also decode from Type.string
   367  
   368  	sdie := find(ctxt, name)
   369  
   370  	if sdie != nil {
   371  		return sdie
   372  	}
   373  
   374  	return newtype(ctxt, gotype).Sym.(*Symbol)
   375  }
   376  
   377  func newtype(ctxt *Link, gotype *Symbol) *dwarf.DWDie {
   378  	name := gotype.Name[5:] // could also decode from Type.string
   379  	kind := decodetypeKind(gotype)
   380  	bytesize := decodetypeSize(ctxt.Arch, gotype)
   381  
   382  	var die *dwarf.DWDie
   383  	switch kind {
   384  	case objabi.KindBool:
   385  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_BASETYPE, name, 0)
   386  		newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_boolean, 0)
   387  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   388  
   389  	case objabi.KindInt,
   390  		objabi.KindInt8,
   391  		objabi.KindInt16,
   392  		objabi.KindInt32,
   393  		objabi.KindInt64:
   394  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_BASETYPE, name, 0)
   395  		newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_signed, 0)
   396  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   397  
   398  	case objabi.KindUint,
   399  		objabi.KindUint8,
   400  		objabi.KindUint16,
   401  		objabi.KindUint32,
   402  		objabi.KindUint64,
   403  		objabi.KindUintptr:
   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_unsigned, 0)
   406  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   407  
   408  	case objabi.KindFloat32,
   409  		objabi.KindFloat64:
   410  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_BASETYPE, name, 0)
   411  		newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_float, 0)
   412  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   413  
   414  	case objabi.KindComplex64,
   415  		objabi.KindComplex128:
   416  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_BASETYPE, name, 0)
   417  		newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_complex_float, 0)
   418  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   419  
   420  	case objabi.KindArray:
   421  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_ARRAYTYPE, name, 0)
   422  		dotypedef(ctxt, &dwtypes, name, die)
   423  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   424  		s := decodetypeArrayElem(gotype)
   425  		newrefattr(die, dwarf.DW_AT_type, defgotype(ctxt, s))
   426  		fld := newdie(ctxt, die, dwarf.DW_ABRV_ARRAYRANGE, "range", 0)
   427  
   428  		// use actual length not upper bound; correct for 0-length arrays.
   429  		newattr(fld, dwarf.DW_AT_count, dwarf.DW_CLS_CONSTANT, decodetypeArrayLen(ctxt.Arch, gotype), 0)
   430  
   431  		newrefattr(fld, dwarf.DW_AT_type, mustFind(ctxt, "uintptr"))
   432  
   433  	case objabi.KindChan:
   434  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_CHANTYPE, name, 0)
   435  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   436  		s := decodetypeChanElem(gotype)
   437  		newrefattr(die, dwarf.DW_AT_go_elem, defgotype(ctxt, s))
   438  		// Save elem type for synthesizechantypes. We could synthesize here
   439  		// but that would change the order of DIEs we output.
   440  		newrefattr(die, dwarf.DW_AT_type, s)
   441  
   442  	case objabi.KindFunc:
   443  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_FUNCTYPE, name, 0)
   444  		dotypedef(ctxt, &dwtypes, name, die)
   445  		newrefattr(die, dwarf.DW_AT_type, mustFind(ctxt, "void"))
   446  		nfields := decodetypeFuncInCount(ctxt.Arch, gotype)
   447  		var fld *dwarf.DWDie
   448  		var s *Symbol
   449  		for i := 0; i < nfields; i++ {
   450  			s = decodetypeFuncInType(gotype, i)
   451  			fld = newdie(ctxt, die, dwarf.DW_ABRV_FUNCTYPEPARAM, s.Name[5:], 0)
   452  			newrefattr(fld, dwarf.DW_AT_type, defgotype(ctxt, s))
   453  		}
   454  
   455  		if decodetypeFuncDotdotdot(ctxt.Arch, gotype) {
   456  			newdie(ctxt, die, dwarf.DW_ABRV_DOTDOTDOT, "...", 0)
   457  		}
   458  		nfields = decodetypeFuncOutCount(ctxt.Arch, gotype)
   459  		for i := 0; i < nfields; i++ {
   460  			s = decodetypeFuncOutType(ctxt.Arch, gotype, i)
   461  			fld = newdie(ctxt, die, dwarf.DW_ABRV_FUNCTYPEPARAM, s.Name[5:], 0)
   462  			newrefattr(fld, dwarf.DW_AT_type, defptrto(ctxt, defgotype(ctxt, s)))
   463  		}
   464  
   465  	case objabi.KindInterface:
   466  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_IFACETYPE, name, 0)
   467  		dotypedef(ctxt, &dwtypes, name, die)
   468  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   469  		nfields := int(decodetypeIfaceMethodCount(ctxt.Arch, gotype))
   470  		var s *Symbol
   471  		if nfields == 0 {
   472  			s = lookupOrDiag(ctxt, "type.runtime.eface")
   473  		} else {
   474  			s = lookupOrDiag(ctxt, "type.runtime.iface")
   475  		}
   476  		newrefattr(die, dwarf.DW_AT_type, defgotype(ctxt, s))
   477  
   478  	case objabi.KindMap:
   479  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_MAPTYPE, name, 0)
   480  		s := decodetypeMapKey(gotype)
   481  		newrefattr(die, dwarf.DW_AT_go_key, defgotype(ctxt, s))
   482  		s = decodetypeMapValue(gotype)
   483  		newrefattr(die, dwarf.DW_AT_go_elem, defgotype(ctxt, s))
   484  		// Save gotype for use in synthesizemaptypes. We could synthesize here,
   485  		// but that would change the order of the DIEs.
   486  		newrefattr(die, dwarf.DW_AT_type, gotype)
   487  
   488  	case objabi.KindPtr:
   489  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_PTRTYPE, name, 0)
   490  		dotypedef(ctxt, &dwtypes, name, die)
   491  		s := decodetypePtrElem(gotype)
   492  		newrefattr(die, dwarf.DW_AT_type, defgotype(ctxt, s))
   493  
   494  	case objabi.KindSlice:
   495  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_SLICETYPE, name, 0)
   496  		dotypedef(ctxt, &dwtypes, name, die)
   497  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   498  		s := decodetypeArrayElem(gotype)
   499  		elem := defgotype(ctxt, s)
   500  		newrefattr(die, dwarf.DW_AT_go_elem, elem)
   501  
   502  	case objabi.KindString:
   503  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_STRINGTYPE, name, 0)
   504  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   505  
   506  	case objabi.KindStruct:
   507  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_STRUCTTYPE, name, 0)
   508  		dotypedef(ctxt, &dwtypes, name, die)
   509  		newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
   510  		nfields := decodetypeStructFieldCount(ctxt.Arch, gotype)
   511  		for i := 0; i < nfields; i++ {
   512  			f := decodetypeStructFieldName(gotype, i)
   513  			s := decodetypeStructFieldType(gotype, i)
   514  			if f == "" {
   515  				f = s.Name[5:] // skip "type."
   516  			}
   517  			fld := newdie(ctxt, die, dwarf.DW_ABRV_STRUCTFIELD, f, 0)
   518  			newrefattr(fld, dwarf.DW_AT_type, defgotype(ctxt, s))
   519  			offsetAnon := decodetypeStructFieldOffsAnon(ctxt.Arch, gotype, i)
   520  			newmemberoffsetattr(fld, int32(offsetAnon>>1))
   521  			if offsetAnon&1 != 0 { // is embedded field
   522  				newattr(fld, dwarf.DW_AT_go_embedded_field, dwarf.DW_CLS_FLAG, 1, 0)
   523  			}
   524  		}
   525  
   526  	case objabi.KindUnsafePointer:
   527  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_BARE_PTRTYPE, name, 0)
   528  
   529  	default:
   530  		Errorf(gotype, "dwarf: definition of unknown kind %d", kind)
   531  		die = newdie(ctxt, &dwtypes, dwarf.DW_ABRV_TYPEDECL, name, 0)
   532  		newrefattr(die, dwarf.DW_AT_type, mustFind(ctxt, "<unspecified>"))
   533  	}
   534  
   535  	newattr(die, dwarf.DW_AT_go_kind, dwarf.DW_CLS_CONSTANT, int64(kind), 0)
   536  
   537  	if _, ok := prototypedies[gotype.Name]; ok {
   538  		prototypedies[gotype.Name] = die
   539  	}
   540  
   541  	return die
   542  }
   543  
   544  func nameFromDIESym(dwtype *Symbol) string {
   545  	return strings.TrimSuffix(dwtype.Name[len(dwarf.InfoPrefix):], "..def")
   546  }
   547  
   548  // Find or construct *T given T.
   549  func defptrto(ctxt *Link, dwtype *Symbol) *Symbol {
   550  	ptrname := "*" + nameFromDIESym(dwtype)
   551  	die := find(ctxt, ptrname)
   552  	if die == nil {
   553  		pdie := newdie(ctxt, &dwtypes, dwarf.DW_ABRV_PTRTYPE, ptrname, 0)
   554  		newrefattr(pdie, dwarf.DW_AT_type, dwtype)
   555  		return dtolsym(pdie.Sym)
   556  	}
   557  
   558  	return die
   559  }
   560  
   561  // Copies src's children into dst. Copies attributes by value.
   562  // DWAttr.data is copied as pointer only. If except is one of
   563  // the top-level children, it will not be copied.
   564  func copychildrenexcept(ctxt *Link, dst *dwarf.DWDie, src *dwarf.DWDie, except *dwarf.DWDie) {
   565  	for src = src.Child; src != nil; src = src.Link {
   566  		if src == except {
   567  			continue
   568  		}
   569  		c := newdie(ctxt, dst, src.Abbrev, getattr(src, dwarf.DW_AT_name).Data.(string), 0)
   570  		for a := src.Attr; a != nil; a = a.Link {
   571  			newattr(c, a.Atr, int(a.Cls), a.Value, a.Data)
   572  		}
   573  		copychildrenexcept(ctxt, c, src, nil)
   574  	}
   575  
   576  	reverselist(&dst.Child)
   577  }
   578  
   579  func copychildren(ctxt *Link, dst *dwarf.DWDie, src *dwarf.DWDie) {
   580  	copychildrenexcept(ctxt, dst, src, nil)
   581  }
   582  
   583  // Search children (assumed to have TAG_member) for the one named
   584  // field and set its AT_type to dwtype
   585  func substitutetype(structdie *dwarf.DWDie, field string, dwtype *Symbol) {
   586  	child := findchild(structdie, field)
   587  	if child == nil {
   588  		Exitf("dwarf substitutetype: %s does not have member %s",
   589  			getattr(structdie, dwarf.DW_AT_name).Data, field)
   590  		return
   591  	}
   592  
   593  	a := getattr(child, dwarf.DW_AT_type)
   594  	if a != nil {
   595  		a.Data = dwtype
   596  	} else {
   597  		newrefattr(child, dwarf.DW_AT_type, dwtype)
   598  	}
   599  }
   600  
   601  func findprotodie(ctxt *Link, name string) *dwarf.DWDie {
   602  	die, ok := prototypedies[name]
   603  	if ok && die == nil {
   604  		defgotype(ctxt, lookupOrDiag(ctxt, name))
   605  		die = prototypedies[name]
   606  	}
   607  	return die
   608  }
   609  
   610  func synthesizestringtypes(ctxt *Link, die *dwarf.DWDie) {
   611  	prototype := walktypedef(findprotodie(ctxt, "type.runtime.stringStructDWARF"))
   612  	if prototype == nil {
   613  		return
   614  	}
   615  
   616  	for ; die != nil; die = die.Link {
   617  		if die.Abbrev != dwarf.DW_ABRV_STRINGTYPE {
   618  			continue
   619  		}
   620  		copychildren(ctxt, die, prototype)
   621  	}
   622  }
   623  
   624  func synthesizeslicetypes(ctxt *Link, die *dwarf.DWDie) {
   625  	prototype := walktypedef(findprotodie(ctxt, "type.runtime.slice"))
   626  	if prototype == nil {
   627  		return
   628  	}
   629  
   630  	for ; die != nil; die = die.Link {
   631  		if die.Abbrev != dwarf.DW_ABRV_SLICETYPE {
   632  			continue
   633  		}
   634  		copychildren(ctxt, die, prototype)
   635  		elem := getattr(die, dwarf.DW_AT_go_elem).Data.(*Symbol)
   636  		substitutetype(die, "array", defptrto(ctxt, elem))
   637  	}
   638  }
   639  
   640  func mkinternaltypename(base string, arg1 string, arg2 string) string {
   641  	var buf string
   642  
   643  	if arg2 == "" {
   644  		buf = fmt.Sprintf("%s<%s>", base, arg1)
   645  	} else {
   646  		buf = fmt.Sprintf("%s<%s,%s>", base, arg1, arg2)
   647  	}
   648  	n := buf
   649  	return n
   650  }
   651  
   652  // synthesizemaptypes is way too closely married to runtime/hashmap.c
   653  const (
   654  	MaxKeySize = 128
   655  	MaxValSize = 128
   656  	BucketSize = 8
   657  )
   658  
   659  func mkinternaltype(ctxt *Link, abbrev int, typename, keyname, valname string, f func(*dwarf.DWDie)) *Symbol {
   660  	name := mkinternaltypename(typename, keyname, valname)
   661  	symname := dwarf.InfoPrefix + name
   662  	s := ctxt.Syms.ROLookup(symname, 0)
   663  	if s != nil && s.Type == SDWARFINFO {
   664  		return s
   665  	}
   666  	die := newdie(ctxt, &dwtypes, abbrev, name, 0)
   667  	f(die)
   668  	return dtolsym(die.Sym)
   669  }
   670  
   671  func synthesizemaptypes(ctxt *Link, die *dwarf.DWDie) {
   672  	hash := walktypedef(findprotodie(ctxt, "type.runtime.hmap"))
   673  	bucket := walktypedef(findprotodie(ctxt, "type.runtime.bmap"))
   674  
   675  	if hash == nil {
   676  		return
   677  	}
   678  
   679  	for ; die != nil; die = die.Link {
   680  		if die.Abbrev != dwarf.DW_ABRV_MAPTYPE {
   681  			continue
   682  		}
   683  		gotype := getattr(die, dwarf.DW_AT_type).Data.(*Symbol)
   684  		keytype := decodetypeMapKey(gotype)
   685  		valtype := decodetypeMapValue(gotype)
   686  		keysize, valsize := decodetypeSize(ctxt.Arch, keytype), decodetypeSize(ctxt.Arch, valtype)
   687  		keytype, valtype = walksymtypedef(ctxt, defgotype(ctxt, keytype)), walksymtypedef(ctxt, defgotype(ctxt, valtype))
   688  
   689  		// compute size info like hashmap.c does.
   690  		indirectKey, indirectVal := false, false
   691  		if keysize > MaxKeySize {
   692  			keysize = int64(SysArch.PtrSize)
   693  			indirectKey = true
   694  		}
   695  		if valsize > MaxValSize {
   696  			valsize = int64(SysArch.PtrSize)
   697  			indirectVal = true
   698  		}
   699  
   700  		// Construct type to represent an array of BucketSize keys
   701  		keyname := nameFromDIESym(keytype)
   702  		dwhks := mkinternaltype(ctxt, dwarf.DW_ABRV_ARRAYTYPE, "[]key", keyname, "", func(dwhk *dwarf.DWDie) {
   703  			newattr(dwhk, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, BucketSize*keysize, 0)
   704  			t := keytype
   705  			if indirectKey {
   706  				t = defptrto(ctxt, keytype)
   707  			}
   708  			newrefattr(dwhk, dwarf.DW_AT_type, t)
   709  			fld := newdie(ctxt, dwhk, dwarf.DW_ABRV_ARRAYRANGE, "size", 0)
   710  			newattr(fld, dwarf.DW_AT_count, dwarf.DW_CLS_CONSTANT, BucketSize, 0)
   711  			newrefattr(fld, dwarf.DW_AT_type, mustFind(ctxt, "uintptr"))
   712  		})
   713  
   714  		// Construct type to represent an array of BucketSize values
   715  		valname := nameFromDIESym(valtype)
   716  		dwhvs := mkinternaltype(ctxt, dwarf.DW_ABRV_ARRAYTYPE, "[]val", valname, "", func(dwhv *dwarf.DWDie) {
   717  			newattr(dwhv, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, BucketSize*valsize, 0)
   718  			t := valtype
   719  			if indirectVal {
   720  				t = defptrto(ctxt, valtype)
   721  			}
   722  			newrefattr(dwhv, dwarf.DW_AT_type, t)
   723  			fld := newdie(ctxt, dwhv, dwarf.DW_ABRV_ARRAYRANGE, "size", 0)
   724  			newattr(fld, dwarf.DW_AT_count, dwarf.DW_CLS_CONSTANT, BucketSize, 0)
   725  			newrefattr(fld, dwarf.DW_AT_type, mustFind(ctxt, "uintptr"))
   726  		})
   727  
   728  		// Construct bucket<K,V>
   729  		dwhbs := mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "bucket", keyname, valname, func(dwhb *dwarf.DWDie) {
   730  			// Copy over all fields except the field "data" from the generic
   731  			// bucket. "data" will be replaced with keys/values below.
   732  			copychildrenexcept(ctxt, dwhb, bucket, findchild(bucket, "data"))
   733  
   734  			fld := newdie(ctxt, dwhb, dwarf.DW_ABRV_STRUCTFIELD, "keys", 0)
   735  			newrefattr(fld, dwarf.DW_AT_type, dwhks)
   736  			newmemberoffsetattr(fld, BucketSize)
   737  			fld = newdie(ctxt, dwhb, dwarf.DW_ABRV_STRUCTFIELD, "values", 0)
   738  			newrefattr(fld, dwarf.DW_AT_type, dwhvs)
   739  			newmemberoffsetattr(fld, BucketSize+BucketSize*int32(keysize))
   740  			fld = newdie(ctxt, dwhb, dwarf.DW_ABRV_STRUCTFIELD, "overflow", 0)
   741  			newrefattr(fld, dwarf.DW_AT_type, defptrto(ctxt, dtolsym(dwhb.Sym)))
   742  			newmemberoffsetattr(fld, BucketSize+BucketSize*(int32(keysize)+int32(valsize)))
   743  			if SysArch.RegSize > SysArch.PtrSize {
   744  				fld = newdie(ctxt, dwhb, dwarf.DW_ABRV_STRUCTFIELD, "pad", 0)
   745  				newrefattr(fld, dwarf.DW_AT_type, mustFind(ctxt, "uintptr"))
   746  				newmemberoffsetattr(fld, BucketSize+BucketSize*(int32(keysize)+int32(valsize))+int32(SysArch.PtrSize))
   747  			}
   748  
   749  			newattr(dwhb, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, BucketSize+BucketSize*keysize+BucketSize*valsize+int64(SysArch.RegSize), 0)
   750  		})
   751  
   752  		// Construct hash<K,V>
   753  		dwhs := mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "hash", keyname, valname, func(dwh *dwarf.DWDie) {
   754  			copychildren(ctxt, dwh, hash)
   755  			substitutetype(dwh, "buckets", defptrto(ctxt, dwhbs))
   756  			substitutetype(dwh, "oldbuckets", defptrto(ctxt, dwhbs))
   757  			newattr(dwh, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, getattr(hash, dwarf.DW_AT_byte_size).Value, nil)
   758  		})
   759  
   760  		// make map type a pointer to hash<K,V>
   761  		newrefattr(die, dwarf.DW_AT_type, defptrto(ctxt, dwhs))
   762  	}
   763  }
   764  
   765  func synthesizechantypes(ctxt *Link, die *dwarf.DWDie) {
   766  	sudog := walktypedef(findprotodie(ctxt, "type.runtime.sudog"))
   767  	waitq := walktypedef(findprotodie(ctxt, "type.runtime.waitq"))
   768  	hchan := walktypedef(findprotodie(ctxt, "type.runtime.hchan"))
   769  	if sudog == nil || waitq == nil || hchan == nil {
   770  		return
   771  	}
   772  
   773  	sudogsize := int(getattr(sudog, dwarf.DW_AT_byte_size).Value)
   774  
   775  	for ; die != nil; die = die.Link {
   776  		if die.Abbrev != dwarf.DW_ABRV_CHANTYPE {
   777  			continue
   778  		}
   779  		elemgotype := getattr(die, dwarf.DW_AT_type).Data.(*Symbol)
   780  		elemsize := decodetypeSize(ctxt.Arch, elemgotype)
   781  		elemname := elemgotype.Name[5:]
   782  		elemtype := walksymtypedef(ctxt, defgotype(ctxt, elemgotype))
   783  
   784  		// sudog<T>
   785  		dwss := mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "sudog", elemname, "", func(dws *dwarf.DWDie) {
   786  			copychildren(ctxt, dws, sudog)
   787  			substitutetype(dws, "elem", elemtype)
   788  			if elemsize > 8 {
   789  				elemsize -= 8
   790  			} else {
   791  				elemsize = 0
   792  			}
   793  			newattr(dws, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, int64(sudogsize)+elemsize, nil)
   794  		})
   795  
   796  		// waitq<T>
   797  		dwws := mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "waitq", elemname, "", func(dww *dwarf.DWDie) {
   798  
   799  			copychildren(ctxt, dww, waitq)
   800  			substitutetype(dww, "first", defptrto(ctxt, dwss))
   801  			substitutetype(dww, "last", defptrto(ctxt, dwss))
   802  			newattr(dww, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, getattr(waitq, dwarf.DW_AT_byte_size).Value, nil)
   803  		})
   804  
   805  		// hchan<T>
   806  		dwhs := mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "hchan", elemname, "", func(dwh *dwarf.DWDie) {
   807  			copychildren(ctxt, dwh, hchan)
   808  			substitutetype(dwh, "recvq", dwws)
   809  			substitutetype(dwh, "sendq", dwws)
   810  			newattr(dwh, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, getattr(hchan, dwarf.DW_AT_byte_size).Value, nil)
   811  		})
   812  
   813  		newrefattr(die, dwarf.DW_AT_type, defptrto(ctxt, dwhs))
   814  	}
   815  }
   816  
   817  // For use with pass.c::genasmsym
   818  func defdwsymb(ctxt *Link, sym *Symbol, s string, t SymbolType, v int64, gotype *Symbol) {
   819  	if strings.HasPrefix(s, "go.string.") {
   820  		return
   821  	}
   822  	if strings.HasPrefix(s, "runtime.gcbits.") {
   823  		return
   824  	}
   825  
   826  	if strings.HasPrefix(s, "type.") && s != "type.*" && !strings.HasPrefix(s, "type..") {
   827  		defgotype(ctxt, sym)
   828  		return
   829  	}
   830  
   831  	var dv *dwarf.DWDie
   832  
   833  	var dt *Symbol
   834  	switch t {
   835  	default:
   836  		return
   837  
   838  	case DataSym, BSSSym:
   839  		dv = newdie(ctxt, &dwglobals, dwarf.DW_ABRV_VARIABLE, s, int(sym.Version))
   840  		newabslocexprattr(dv, v, sym)
   841  		if sym.Version == 0 {
   842  			newattr(dv, dwarf.DW_AT_external, dwarf.DW_CLS_FLAG, 1, 0)
   843  		}
   844  		fallthrough
   845  
   846  	case AutoSym, ParamSym:
   847  		dt = defgotype(ctxt, gotype)
   848  	}
   849  
   850  	if dv != nil {
   851  		newrefattr(dv, dwarf.DW_AT_type, dt)
   852  	}
   853  }
   854  
   855  func movetomodule(parent *dwarf.DWDie) {
   856  	die := dwroot.Child.Child
   857  	if die == nil {
   858  		dwroot.Child.Child = parent.Child
   859  		return
   860  	}
   861  	for die.Link != nil {
   862  		die = die.Link
   863  	}
   864  	die.Link = parent.Child
   865  }
   866  
   867  // If the pcln table contains runtime/runtime.go, use that to set gdbscript path.
   868  func finddebugruntimepath(s *Symbol) {
   869  	if gdbscript != "" {
   870  		return
   871  	}
   872  
   873  	for i := range s.FuncInfo.File {
   874  		f := s.FuncInfo.File[i]
   875  		if i := strings.Index(f.Name, "runtime/debug.go"); i >= 0 {
   876  			gdbscript = f.Name[:i] + "runtime/runtime-gdb.py"
   877  			break
   878  		}
   879  	}
   880  }
   881  
   882  /*
   883   * Generate a sequence of opcodes that is as short as possible.
   884   * See section 6.2.5
   885   */
   886  const (
   887  	LINE_BASE   = -4
   888  	LINE_RANGE  = 10
   889  	PC_RANGE    = (255 - OPCODE_BASE) / LINE_RANGE
   890  	OPCODE_BASE = 10
   891  )
   892  
   893  func putpclcdelta(linkctxt *Link, ctxt dwarf.Context, s *Symbol, deltaPC uint64, deltaLC int64) {
   894  	// Choose a special opcode that minimizes the number of bytes needed to
   895  	// encode the remaining PC delta and LC delta.
   896  	var opcode int64
   897  	if deltaLC < LINE_BASE {
   898  		if deltaPC >= PC_RANGE {
   899  			opcode = OPCODE_BASE + (LINE_RANGE * PC_RANGE)
   900  		} else {
   901  			opcode = OPCODE_BASE + (LINE_RANGE * int64(deltaPC))
   902  		}
   903  	} else if deltaLC < LINE_BASE+LINE_RANGE {
   904  		if deltaPC >= PC_RANGE {
   905  			opcode = OPCODE_BASE + (deltaLC - LINE_BASE) + (LINE_RANGE * PC_RANGE)
   906  			if opcode > 255 {
   907  				opcode -= LINE_RANGE
   908  			}
   909  		} else {
   910  			opcode = OPCODE_BASE + (deltaLC - LINE_BASE) + (LINE_RANGE * int64(deltaPC))
   911  		}
   912  	} else {
   913  		if deltaPC <= PC_RANGE {
   914  			opcode = OPCODE_BASE + (LINE_RANGE - 1) + (LINE_RANGE * int64(deltaPC))
   915  			if opcode > 255 {
   916  				opcode = 255
   917  			}
   918  		} else {
   919  			// Use opcode 249 (pc+=23, lc+=5) or 255 (pc+=24, lc+=1).
   920  			//
   921  			// Let x=deltaPC-PC_RANGE.  If we use opcode 255, x will be the remaining
   922  			// deltaPC that we need to encode separately before emitting 255.  If we
   923  			// use opcode 249, we will need to encode x+1.  If x+1 takes one more
   924  			// byte to encode than x, then we use opcode 255.
   925  			//
   926  			// In all other cases x and x+1 take the same number of bytes to encode,
   927  			// so we use opcode 249, which may save us a byte in encoding deltaLC,
   928  			// for similar reasons.
   929  			switch deltaPC - PC_RANGE {
   930  			// PC_RANGE is the largest deltaPC we can encode in one byte, using
   931  			// DW_LNS_const_add_pc.
   932  			//
   933  			// (1<<16)-1 is the largest deltaPC we can encode in three bytes, using
   934  			// DW_LNS_fixed_advance_pc.
   935  			//
   936  			// (1<<(7n))-1 is the largest deltaPC we can encode in n+1 bytes for
   937  			// n=1,3,4,5,..., using DW_LNS_advance_pc.
   938  			case PC_RANGE, (1 << 7) - 1, (1 << 16) - 1, (1 << 21) - 1, (1 << 28) - 1,
   939  				(1 << 35) - 1, (1 << 42) - 1, (1 << 49) - 1, (1 << 56) - 1, (1 << 63) - 1:
   940  				opcode = 255
   941  			default:
   942  				opcode = OPCODE_BASE + LINE_RANGE*PC_RANGE - 1 // 249
   943  			}
   944  		}
   945  	}
   946  	if opcode < OPCODE_BASE || opcode > 255 {
   947  		panic(fmt.Sprintf("produced invalid special opcode %d", opcode))
   948  	}
   949  
   950  	// Subtract from deltaPC and deltaLC the amounts that the opcode will add.
   951  	deltaPC -= uint64((opcode - OPCODE_BASE) / LINE_RANGE)
   952  	deltaLC -= int64((opcode-OPCODE_BASE)%LINE_RANGE + LINE_BASE)
   953  
   954  	// Encode deltaPC.
   955  	if deltaPC != 0 {
   956  		if deltaPC <= PC_RANGE {
   957  			// Adjust the opcode so that we can use the 1-byte DW_LNS_const_add_pc
   958  			// instruction.
   959  			opcode -= LINE_RANGE * int64(PC_RANGE-deltaPC)
   960  			if opcode < OPCODE_BASE {
   961  				panic(fmt.Sprintf("produced invalid special opcode %d", opcode))
   962  			}
   963  			Adduint8(linkctxt, s, dwarf.DW_LNS_const_add_pc)
   964  		} else if (1<<14) <= deltaPC && deltaPC < (1<<16) {
   965  			Adduint8(linkctxt, s, dwarf.DW_LNS_fixed_advance_pc)
   966  			Adduint16(linkctxt, s, uint16(deltaPC))
   967  		} else {
   968  			Adduint8(linkctxt, s, dwarf.DW_LNS_advance_pc)
   969  			dwarf.Uleb128put(ctxt, s, int64(deltaPC))
   970  		}
   971  	}
   972  
   973  	// Encode deltaLC.
   974  	if deltaLC != 0 {
   975  		Adduint8(linkctxt, s, dwarf.DW_LNS_advance_line)
   976  		dwarf.Sleb128put(ctxt, s, deltaLC)
   977  	}
   978  
   979  	// Output the special opcode.
   980  	Adduint8(linkctxt, s, uint8(opcode))
   981  }
   982  
   983  /*
   984   * Walk prog table, emit line program and build DIE tree.
   985   */
   986  
   987  func getCompilationDir() string {
   988  	if dir, err := os.Getwd(); err == nil {
   989  		return dir
   990  	}
   991  	return "/"
   992  }
   993  
   994  func writelines(ctxt *Link, syms []*Symbol) ([]*Symbol, []*Symbol) {
   995  	var dwarfctxt dwarf.Context = dwctxt{ctxt}
   996  	if linesec == nil {
   997  		linesec = ctxt.Syms.Lookup(".debug_line", 0)
   998  	}
   999  	linesec.Type = SDWARFSECT
  1000  	linesec.R = linesec.R[:0]
  1001  
  1002  	ls := linesec
  1003  	syms = append(syms, ls)
  1004  	var funcs []*Symbol
  1005  
  1006  	unitstart := int64(-1)
  1007  	headerstart := int64(-1)
  1008  	headerend := int64(-1)
  1009  	epc := int64(0)
  1010  	var epcs *Symbol
  1011  	var dwinfo *dwarf.DWDie
  1012  
  1013  	lang := dwarf.DW_LANG_Go
  1014  
  1015  	s := ctxt.Textp[0]
  1016  	if ctxt.DynlinkingGo() && Headtype == objabi.Hdarwin {
  1017  		s = ctxt.Textp[1] // skip runtime.text
  1018  	}
  1019  
  1020  	dwinfo = newdie(ctxt, &dwroot, dwarf.DW_ABRV_COMPUNIT, "go", 0)
  1021  	newattr(dwinfo, dwarf.DW_AT_language, dwarf.DW_CLS_CONSTANT, int64(lang), 0)
  1022  	newattr(dwinfo, dwarf.DW_AT_stmt_list, dwarf.DW_CLS_PTR, 0, linesec)
  1023  	newattr(dwinfo, dwarf.DW_AT_low_pc, dwarf.DW_CLS_ADDRESS, s.Value, s)
  1024  	// OS X linker requires compilation dir or absolute path in comp unit name to output debug info.
  1025  	compDir := getCompilationDir()
  1026  	newattr(dwinfo, dwarf.DW_AT_comp_dir, dwarf.DW_CLS_STRING, int64(len(compDir)), compDir)
  1027  	producer := "Go cmd/compile " + objabi.Version
  1028  	newattr(dwinfo, dwarf.DW_AT_producer, dwarf.DW_CLS_STRING, int64(len(producer)), producer)
  1029  
  1030  	// Write .debug_line Line Number Program Header (sec 6.2.4)
  1031  	// Fields marked with (*) must be changed for 64-bit dwarf
  1032  	unitLengthOffset := ls.Size
  1033  	Adduint32(ctxt, ls, 0) // unit_length (*), filled in at end.
  1034  	unitstart = ls.Size
  1035  	Adduint16(ctxt, ls, 2) // dwarf version (appendix F)
  1036  	headerLengthOffset := ls.Size
  1037  	Adduint32(ctxt, ls, 0) // header_length (*), filled in at end.
  1038  	headerstart = ls.Size
  1039  
  1040  	// cpos == unitstart + 4 + 2 + 4
  1041  	Adduint8(ctxt, ls, 1)              // minimum_instruction_length
  1042  	Adduint8(ctxt, ls, 1)              // default_is_stmt
  1043  	Adduint8(ctxt, ls, LINE_BASE&0xFF) // line_base
  1044  	Adduint8(ctxt, ls, LINE_RANGE)     // line_range
  1045  	Adduint8(ctxt, ls, OPCODE_BASE)    // opcode_base
  1046  	Adduint8(ctxt, ls, 0)              // standard_opcode_lengths[1]
  1047  	Adduint8(ctxt, ls, 1)              // standard_opcode_lengths[2]
  1048  	Adduint8(ctxt, ls, 1)              // standard_opcode_lengths[3]
  1049  	Adduint8(ctxt, ls, 1)              // standard_opcode_lengths[4]
  1050  	Adduint8(ctxt, ls, 1)              // standard_opcode_lengths[5]
  1051  	Adduint8(ctxt, ls, 0)              // standard_opcode_lengths[6]
  1052  	Adduint8(ctxt, ls, 0)              // standard_opcode_lengths[7]
  1053  	Adduint8(ctxt, ls, 0)              // standard_opcode_lengths[8]
  1054  	Adduint8(ctxt, ls, 1)              // standard_opcode_lengths[9]
  1055  	Adduint8(ctxt, ls, 0)              // include_directories  (empty)
  1056  
  1057  	for _, f := range ctxt.Filesyms {
  1058  		Addstring(ls, f.Name)
  1059  		Adduint8(ctxt, ls, 0)
  1060  		Adduint8(ctxt, ls, 0)
  1061  		Adduint8(ctxt, ls, 0)
  1062  	}
  1063  
  1064  	// 4 zeros: the string termination + 3 fields.
  1065  	Adduint8(ctxt, ls, 0)
  1066  	// terminate file_names.
  1067  	headerend = ls.Size
  1068  
  1069  	Adduint8(ctxt, ls, 0) // start extended opcode
  1070  	dwarf.Uleb128put(dwarfctxt, ls, 1+int64(SysArch.PtrSize))
  1071  	Adduint8(ctxt, ls, dwarf.DW_LNE_set_address)
  1072  
  1073  	pc := s.Value
  1074  	line := 1
  1075  	file := 1
  1076  	Addaddr(ctxt, ls, s)
  1077  
  1078  	var pcfile Pciter
  1079  	var pcline Pciter
  1080  	for _, s := range ctxt.Textp {
  1081  
  1082  		epc = s.Value + s.Size
  1083  		epcs = s
  1084  
  1085  		dsym := ctxt.Syms.Lookup(dwarf.InfoPrefix+s.Name, int(s.Version))
  1086  		dsym.Attr |= AttrNotInSymbolTable | AttrReachable
  1087  		dsym.Type = SDWARFINFO
  1088  		for _, r := range dsym.R {
  1089  			if r.Type == objabi.R_DWARFREF && r.Sym.Size == 0 {
  1090  				if Buildmode == BuildmodeShared {
  1091  					// These type symbols may not be present in BuildmodeShared. Skip.
  1092  					continue
  1093  				}
  1094  				n := nameFromDIESym(r.Sym)
  1095  				defgotype(ctxt, ctxt.Syms.Lookup("type."+n, 0))
  1096  			}
  1097  		}
  1098  		funcs = append(funcs, dsym)
  1099  
  1100  		if s.FuncInfo == nil {
  1101  			continue
  1102  		}
  1103  
  1104  		finddebugruntimepath(s)
  1105  
  1106  		pciterinit(ctxt, &pcfile, &s.FuncInfo.Pcfile)
  1107  		pciterinit(ctxt, &pcline, &s.FuncInfo.Pcline)
  1108  		epc = pc
  1109  		for pcfile.done == 0 && pcline.done == 0 {
  1110  			if epc-s.Value >= int64(pcfile.nextpc) {
  1111  				pciternext(&pcfile)
  1112  				continue
  1113  			}
  1114  
  1115  			if epc-s.Value >= int64(pcline.nextpc) {
  1116  				pciternext(&pcline)
  1117  				continue
  1118  			}
  1119  
  1120  			if int32(file) != pcfile.value {
  1121  				Adduint8(ctxt, ls, dwarf.DW_LNS_set_file)
  1122  				dwarf.Uleb128put(dwarfctxt, ls, int64(pcfile.value))
  1123  				file = int(pcfile.value)
  1124  			}
  1125  
  1126  			putpclcdelta(ctxt, dwarfctxt, ls, uint64(s.Value+int64(pcline.pc)-pc), int64(pcline.value)-int64(line))
  1127  
  1128  			pc = s.Value + int64(pcline.pc)
  1129  			line = int(pcline.value)
  1130  			if pcfile.nextpc < pcline.nextpc {
  1131  				epc = int64(pcfile.nextpc)
  1132  			} else {
  1133  				epc = int64(pcline.nextpc)
  1134  			}
  1135  			epc += s.Value
  1136  		}
  1137  	}
  1138  
  1139  	Adduint8(ctxt, ls, 0) // start extended opcode
  1140  	dwarf.Uleb128put(dwarfctxt, ls, 1)
  1141  	Adduint8(ctxt, ls, dwarf.DW_LNE_end_sequence)
  1142  
  1143  	newattr(dwinfo, dwarf.DW_AT_high_pc, dwarf.DW_CLS_ADDRESS, epc+1, epcs)
  1144  
  1145  	setuint32(ctxt, ls, unitLengthOffset, uint32(ls.Size-unitstart))
  1146  	setuint32(ctxt, ls, headerLengthOffset, uint32(headerend-headerstart))
  1147  
  1148  	return syms, funcs
  1149  }
  1150  
  1151  /*
  1152   *  Emit .debug_frame
  1153   */
  1154  const (
  1155  	dataAlignmentFactor = -4
  1156  )
  1157  
  1158  // appendPCDeltaCFA appends per-PC CFA deltas to b and returns the final slice.
  1159  func appendPCDeltaCFA(b []byte, deltapc, cfa int64) []byte {
  1160  	b = append(b, dwarf.DW_CFA_def_cfa_offset_sf)
  1161  	b = dwarf.AppendSleb128(b, cfa/dataAlignmentFactor)
  1162  
  1163  	switch {
  1164  	case deltapc < 0x40:
  1165  		b = append(b, uint8(dwarf.DW_CFA_advance_loc+deltapc))
  1166  	case deltapc < 0x100:
  1167  		b = append(b, dwarf.DW_CFA_advance_loc1)
  1168  		b = append(b, uint8(deltapc))
  1169  	case deltapc < 0x10000:
  1170  		b = append(b, dwarf.DW_CFA_advance_loc2)
  1171  		b = Thearch.Append16(b, uint16(deltapc))
  1172  	default:
  1173  		b = append(b, dwarf.DW_CFA_advance_loc4)
  1174  		b = Thearch.Append32(b, uint32(deltapc))
  1175  	}
  1176  	return b
  1177  }
  1178  
  1179  func writeframes(ctxt *Link, syms []*Symbol) []*Symbol {
  1180  	var dwarfctxt dwarf.Context = dwctxt{ctxt}
  1181  	if framesec == nil {
  1182  		framesec = ctxt.Syms.Lookup(".debug_frame", 0)
  1183  	}
  1184  	framesec.Type = SDWARFSECT
  1185  	framesec.R = framesec.R[:0]
  1186  	fs := framesec
  1187  	syms = append(syms, fs)
  1188  
  1189  	// Emit the CIE, Section 6.4.1
  1190  	cieReserve := uint32(16)
  1191  	if haslinkregister(ctxt) {
  1192  		cieReserve = 32
  1193  	}
  1194  	Adduint32(ctxt, fs, cieReserve)                            // initial length, must be multiple of thearch.ptrsize
  1195  	Adduint32(ctxt, fs, 0xffffffff)                            // cid.
  1196  	Adduint8(ctxt, fs, 3)                                      // dwarf version (appendix F)
  1197  	Adduint8(ctxt, fs, 0)                                      // augmentation ""
  1198  	dwarf.Uleb128put(dwarfctxt, fs, 1)                         // code_alignment_factor
  1199  	dwarf.Sleb128put(dwarfctxt, fs, dataAlignmentFactor)       // all CFI offset calculations include multiplication with this factor
  1200  	dwarf.Uleb128put(dwarfctxt, fs, int64(Thearch.Dwarfreglr)) // return_address_register
  1201  
  1202  	Adduint8(ctxt, fs, dwarf.DW_CFA_def_cfa)                   // Set the current frame address..
  1203  	dwarf.Uleb128put(dwarfctxt, fs, int64(Thearch.Dwarfregsp)) // ...to use the value in the platform's SP register (defined in l.go)...
  1204  	if haslinkregister(ctxt) {
  1205  		dwarf.Uleb128put(dwarfctxt, fs, int64(0)) // ...plus a 0 offset.
  1206  
  1207  		Adduint8(ctxt, fs, dwarf.DW_CFA_same_value) // The platform's link register is unchanged during the prologue.
  1208  		dwarf.Uleb128put(dwarfctxt, fs, int64(Thearch.Dwarfreglr))
  1209  
  1210  		Adduint8(ctxt, fs, dwarf.DW_CFA_val_offset)                // The previous value...
  1211  		dwarf.Uleb128put(dwarfctxt, fs, int64(Thearch.Dwarfregsp)) // ...of the platform's SP register...
  1212  		dwarf.Uleb128put(dwarfctxt, fs, int64(0))                  // ...is CFA+0.
  1213  	} else {
  1214  		dwarf.Uleb128put(dwarfctxt, fs, int64(SysArch.PtrSize)) // ...plus the word size (because the call instruction implicitly adds one word to the frame).
  1215  
  1216  		Adduint8(ctxt, fs, dwarf.DW_CFA_offset_extended)                             // The previous value...
  1217  		dwarf.Uleb128put(dwarfctxt, fs, int64(Thearch.Dwarfreglr))                   // ...of the return address...
  1218  		dwarf.Uleb128put(dwarfctxt, fs, int64(-SysArch.PtrSize)/dataAlignmentFactor) // ...is saved at [CFA - (PtrSize/4)].
  1219  	}
  1220  
  1221  	// 4 is to exclude the length field.
  1222  	pad := int64(cieReserve) + 4 - fs.Size
  1223  
  1224  	if pad < 0 {
  1225  		Exitf("dwarf: cieReserve too small by %d bytes.", -pad)
  1226  	}
  1227  
  1228  	Addbytes(fs, zeros[:pad])
  1229  
  1230  	var deltaBuf []byte
  1231  	var pcsp Pciter
  1232  	for _, s := range ctxt.Textp {
  1233  		if s.FuncInfo == nil {
  1234  			continue
  1235  		}
  1236  
  1237  		// Emit a FDE, Section 6.4.1.
  1238  		// First build the section contents into a byte buffer.
  1239  		deltaBuf = deltaBuf[:0]
  1240  		for pciterinit(ctxt, &pcsp, &s.FuncInfo.Pcsp); pcsp.done == 0; pciternext(&pcsp) {
  1241  			nextpc := pcsp.nextpc
  1242  
  1243  			// pciterinit goes up to the end of the function,
  1244  			// but DWARF expects us to stop just before the end.
  1245  			if int64(nextpc) == s.Size {
  1246  				nextpc--
  1247  				if nextpc < pcsp.pc {
  1248  					continue
  1249  				}
  1250  			}
  1251  
  1252  			if haslinkregister(ctxt) {
  1253  				// TODO(bryanpkc): This is imprecise. In general, the instruction
  1254  				// that stores the return address to the stack frame is not the
  1255  				// same one that allocates the frame.
  1256  				if pcsp.value > 0 {
  1257  					// The return address is preserved at (CFA-frame_size)
  1258  					// after a stack frame has been allocated.
  1259  					deltaBuf = append(deltaBuf, dwarf.DW_CFA_offset_extended_sf)
  1260  					deltaBuf = dwarf.AppendUleb128(deltaBuf, uint64(Thearch.Dwarfreglr))
  1261  					deltaBuf = dwarf.AppendSleb128(deltaBuf, -int64(pcsp.value)/dataAlignmentFactor)
  1262  				} else {
  1263  					// The return address is restored into the link register
  1264  					// when a stack frame has been de-allocated.
  1265  					deltaBuf = append(deltaBuf, dwarf.DW_CFA_same_value)
  1266  					deltaBuf = dwarf.AppendUleb128(deltaBuf, uint64(Thearch.Dwarfreglr))
  1267  				}
  1268  				deltaBuf = appendPCDeltaCFA(deltaBuf, int64(nextpc)-int64(pcsp.pc), int64(pcsp.value))
  1269  			} else {
  1270  				deltaBuf = appendPCDeltaCFA(deltaBuf, int64(nextpc)-int64(pcsp.pc), int64(SysArch.PtrSize)+int64(pcsp.value))
  1271  			}
  1272  		}
  1273  		pad := int(Rnd(int64(len(deltaBuf)), int64(SysArch.PtrSize))) - len(deltaBuf)
  1274  		deltaBuf = append(deltaBuf, zeros[:pad]...)
  1275  
  1276  		// Emit the FDE header, Section 6.4.1.
  1277  		//	4 bytes: length, must be multiple of thearch.ptrsize
  1278  		//	4 bytes: Pointer to the CIE above, at offset 0
  1279  		//	ptrsize: initial location
  1280  		//	ptrsize: address range
  1281  		Adduint32(ctxt, fs, uint32(4+2*SysArch.PtrSize+len(deltaBuf))) // length (excludes itself)
  1282  		if Linkmode == LinkExternal {
  1283  			adddwarfref(ctxt, fs, framesec, 4)
  1284  		} else {
  1285  			Adduint32(ctxt, fs, 0) // CIE offset
  1286  		}
  1287  		Addaddr(ctxt, fs, s)
  1288  		adduintxx(ctxt, fs, uint64(s.Size), SysArch.PtrSize) // address range
  1289  		Addbytes(fs, deltaBuf)
  1290  	}
  1291  	return syms
  1292  }
  1293  
  1294  func writeranges(ctxt *Link, syms []*Symbol) []*Symbol {
  1295  	if rangesec == nil {
  1296  		rangesec = ctxt.Syms.Lookup(".debug_ranges", 0)
  1297  	}
  1298  	rangesec.Type = SDWARFSECT
  1299  	rangesec.Attr |= AttrReachable
  1300  	rangesec.R = rangesec.R[:0]
  1301  
  1302  	for _, s := range ctxt.Textp {
  1303  		rangeSym := ctxt.Syms.Lookup(dwarf.RangePrefix+s.Name, int(s.Version))
  1304  		rangeSym.Attr |= AttrReachable
  1305  		rangeSym.Type = SDWARFRANGE
  1306  		rangeSym.Value = rangesec.Size
  1307  		rangesec.P = append(rangesec.P, rangeSym.P...)
  1308  		for _, r := range rangeSym.R {
  1309  			r.Off += int32(rangesec.Size)
  1310  			rangesec.R = append(rangesec.R, r)
  1311  		}
  1312  		rangesec.Size += rangeSym.Size
  1313  	}
  1314  	if rangesec.Size > 0 {
  1315  		// PE does not like empty sections
  1316  		syms = append(syms, rangesec)
  1317  	}
  1318  	return syms
  1319  }
  1320  
  1321  /*
  1322   *  Walk DWarfDebugInfoEntries, and emit .debug_info
  1323   */
  1324  const (
  1325  	COMPUNITHEADERSIZE = 4 + 2 + 4 + 1
  1326  )
  1327  
  1328  func writeinfo(ctxt *Link, syms []*Symbol, funcs []*Symbol) []*Symbol {
  1329  	if infosec == nil {
  1330  		infosec = ctxt.Syms.Lookup(".debug_info", 0)
  1331  	}
  1332  	infosec.R = infosec.R[:0]
  1333  	infosec.Type = SDWARFINFO
  1334  	infosec.Attr |= AttrReachable
  1335  	syms = append(syms, infosec)
  1336  
  1337  	if arangessec == nil {
  1338  		arangessec = ctxt.Syms.Lookup(".dwarfaranges", 0)
  1339  	}
  1340  	arangessec.R = arangessec.R[:0]
  1341  
  1342  	var dwarfctxt dwarf.Context = dwctxt{ctxt}
  1343  
  1344  	for compunit := dwroot.Child; compunit != nil; compunit = compunit.Link {
  1345  		s := dtolsym(compunit.Sym)
  1346  
  1347  		// Write .debug_info Compilation Unit Header (sec 7.5.1)
  1348  		// Fields marked with (*) must be changed for 64-bit dwarf
  1349  		// This must match COMPUNITHEADERSIZE above.
  1350  		Adduint32(ctxt, s, 0) // unit_length (*), will be filled in later.
  1351  		Adduint16(ctxt, s, 4) // dwarf version (appendix F)
  1352  
  1353  		// debug_abbrev_offset (*)
  1354  		adddwarfref(ctxt, s, abbrevsym, 4)
  1355  
  1356  		Adduint8(ctxt, s, uint8(SysArch.PtrSize)) // address_size
  1357  
  1358  		dwarf.Uleb128put(dwarfctxt, s, int64(compunit.Abbrev))
  1359  		dwarf.PutAttrs(dwarfctxt, s, compunit.Abbrev, compunit.Attr)
  1360  
  1361  		cu := []*Symbol{s}
  1362  		if funcs != nil {
  1363  			cu = append(cu, funcs...)
  1364  			funcs = nil
  1365  		}
  1366  		cu = putdies(ctxt, dwarfctxt, cu, compunit.Child)
  1367  		var cusize int64
  1368  		for _, child := range cu {
  1369  			cusize += child.Size
  1370  		}
  1371  		cusize -= 4 // exclude the length field.
  1372  		setuint32(ctxt, s, 0, uint32(cusize))
  1373  		newattr(compunit, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, cusize, 0)
  1374  		syms = append(syms, cu...)
  1375  	}
  1376  	return syms
  1377  }
  1378  
  1379  /*
  1380   *  Emit .debug_pubnames/_types.  _info must have been written before,
  1381   *  because we need die->offs and infoo/infosize;
  1382   */
  1383  func ispubname(die *dwarf.DWDie) bool {
  1384  	switch die.Abbrev {
  1385  	case dwarf.DW_ABRV_FUNCTION, dwarf.DW_ABRV_VARIABLE:
  1386  		a := getattr(die, dwarf.DW_AT_external)
  1387  		return a != nil && a.Value != 0
  1388  	}
  1389  
  1390  	return false
  1391  }
  1392  
  1393  func ispubtype(die *dwarf.DWDie) bool {
  1394  	return die.Abbrev >= dwarf.DW_ABRV_NULLTYPE
  1395  }
  1396  
  1397  func writepub(ctxt *Link, sname string, ispub func(*dwarf.DWDie) bool, syms []*Symbol) []*Symbol {
  1398  	s := ctxt.Syms.Lookup(sname, 0)
  1399  	s.Type = SDWARFSECT
  1400  	syms = append(syms, s)
  1401  
  1402  	for compunit := dwroot.Child; compunit != nil; compunit = compunit.Link {
  1403  		sectionstart := s.Size
  1404  		culength := uint32(getattr(compunit, dwarf.DW_AT_byte_size).Value) + 4
  1405  
  1406  		// Write .debug_pubnames/types	Header (sec 6.1.1)
  1407  		Adduint32(ctxt, s, 0)                          // unit_length (*), will be filled in later.
  1408  		Adduint16(ctxt, s, 2)                          // dwarf version (appendix F)
  1409  		adddwarfref(ctxt, s, dtolsym(compunit.Sym), 4) // debug_info_offset (of the Comp unit Header)
  1410  		Adduint32(ctxt, s, culength)                   // debug_info_length
  1411  
  1412  		for die := compunit.Child; die != nil; die = die.Link {
  1413  			if !ispub(die) {
  1414  				continue
  1415  			}
  1416  			dwa := getattr(die, dwarf.DW_AT_name)
  1417  			name := dwa.Data.(string)
  1418  			if die.Sym == nil {
  1419  				fmt.Println("Missing sym for ", name)
  1420  			}
  1421  			adddwarfref(ctxt, s, dtolsym(die.Sym), 4)
  1422  			Addstring(s, name)
  1423  		}
  1424  
  1425  		Adduint32(ctxt, s, 0)
  1426  
  1427  		setuint32(ctxt, s, sectionstart, uint32(s.Size-sectionstart)-4) // exclude the length field.
  1428  	}
  1429  
  1430  	return syms
  1431  }
  1432  
  1433  /*
  1434   *  emit .debug_aranges.  _info must have been written before,
  1435   *  because we need die->offs of dwarf.DW_globals.
  1436   */
  1437  func writearanges(ctxt *Link, syms []*Symbol) []*Symbol {
  1438  	s := ctxt.Syms.Lookup(".debug_aranges", 0)
  1439  	s.Type = SDWARFSECT
  1440  	// The first tuple is aligned to a multiple of the size of a single tuple
  1441  	// (twice the size of an address)
  1442  	headersize := int(Rnd(4+2+4+1+1, int64(SysArch.PtrSize*2))) // don't count unit_length field itself
  1443  
  1444  	for compunit := dwroot.Child; compunit != nil; compunit = compunit.Link {
  1445  		b := getattr(compunit, dwarf.DW_AT_low_pc)
  1446  		if b == nil {
  1447  			continue
  1448  		}
  1449  		e := getattr(compunit, dwarf.DW_AT_high_pc)
  1450  		if e == nil {
  1451  			continue
  1452  		}
  1453  
  1454  		// Write .debug_aranges	 Header + entry	 (sec 6.1.2)
  1455  		unitlength := uint32(headersize) + 4*uint32(SysArch.PtrSize) - 4
  1456  		Adduint32(ctxt, s, unitlength) // unit_length (*)
  1457  		Adduint16(ctxt, s, 2)          // dwarf version (appendix F)
  1458  
  1459  		adddwarfref(ctxt, s, dtolsym(compunit.Sym), 4)
  1460  
  1461  		Adduint8(ctxt, s, uint8(SysArch.PtrSize)) // address_size
  1462  		Adduint8(ctxt, s, 0)                      // segment_size
  1463  		padding := headersize - (4 + 2 + 4 + 1 + 1)
  1464  		for i := 0; i < padding; i++ {
  1465  			Adduint8(ctxt, s, 0)
  1466  		}
  1467  
  1468  		Addaddrplus(ctxt, s, b.Data.(*Symbol), b.Value-(b.Data.(*Symbol)).Value)
  1469  		adduintxx(ctxt, s, uint64(e.Value-b.Value), SysArch.PtrSize)
  1470  		adduintxx(ctxt, s, 0, SysArch.PtrSize)
  1471  		adduintxx(ctxt, s, 0, SysArch.PtrSize)
  1472  	}
  1473  	if s.Size > 0 {
  1474  		syms = append(syms, s)
  1475  	}
  1476  	return syms
  1477  }
  1478  
  1479  func writegdbscript(ctxt *Link, syms []*Symbol) []*Symbol {
  1480  	if Linkmode == LinkExternal && Headtype == objabi.Hwindows && Buildmode == BuildmodeCArchive {
  1481  		// gcc on Windows places .debug_gdb_scripts in the wrong location, which
  1482  		// causes the program not to run. See https://golang.org/issue/20183
  1483  		// Non c-archives can avoid this issue via a linker script
  1484  		// (see fix near writeGDBLinkerScript).
  1485  		// c-archive users would need to specify the linker script manually.
  1486  		// For UX it's better not to deal with this.
  1487  		return syms
  1488  	}
  1489  
  1490  	if gdbscript != "" {
  1491  		s := ctxt.Syms.Lookup(".debug_gdb_scripts", 0)
  1492  		s.Type = SDWARFSECT
  1493  		syms = append(syms, s)
  1494  		Adduint8(ctxt, s, 1) // magic 1 byte?
  1495  		Addstring(s, gdbscript)
  1496  	}
  1497  
  1498  	return syms
  1499  }
  1500  
  1501  var prototypedies map[string]*dwarf.DWDie
  1502  
  1503  /*
  1504   * This is the main entry point for generating dwarf.  After emitting
  1505   * the mandatory debug_abbrev section, it calls writelines() to set up
  1506   * the per-compilation unit part of the DIE tree, while simultaneously
  1507   * emitting the debug_line section.  When the final tree contains
  1508   * forward references, it will write the debug_info section in 2
  1509   * passes.
  1510   *
  1511   */
  1512  func dwarfgeneratedebugsyms(ctxt *Link) {
  1513  	if *FlagW { // disable dwarf
  1514  		return
  1515  	}
  1516  	if *FlagS && Headtype != objabi.Hdarwin {
  1517  		return
  1518  	}
  1519  	if Headtype == objabi.Hplan9 {
  1520  		return
  1521  	}
  1522  
  1523  	if Linkmode == LinkExternal {
  1524  		switch {
  1525  		case Iself:
  1526  		case Headtype == objabi.Hdarwin:
  1527  		case Headtype == objabi.Hwindows:
  1528  		default:
  1529  			return
  1530  		}
  1531  	}
  1532  
  1533  	if ctxt.Debugvlog != 0 {
  1534  		ctxt.Logf("%5.2f dwarf\n", Cputime())
  1535  	}
  1536  
  1537  	// Forctxt.Diagnostic messages.
  1538  	newattr(&dwtypes, dwarf.DW_AT_name, dwarf.DW_CLS_STRING, int64(len("dwtypes")), "dwtypes")
  1539  
  1540  	// Some types that must exist to define other ones.
  1541  	newdie(ctxt, &dwtypes, dwarf.DW_ABRV_NULLTYPE, "<unspecified>", 0)
  1542  
  1543  	newdie(ctxt, &dwtypes, dwarf.DW_ABRV_NULLTYPE, "void", 0)
  1544  	newdie(ctxt, &dwtypes, dwarf.DW_ABRV_BARE_PTRTYPE, "unsafe.Pointer", 0)
  1545  
  1546  	die := newdie(ctxt, &dwtypes, dwarf.DW_ABRV_BASETYPE, "uintptr", 0) // needed for array size
  1547  	newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_unsigned, 0)
  1548  	newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, int64(SysArch.PtrSize), 0)
  1549  	newattr(die, dwarf.DW_AT_go_kind, dwarf.DW_CLS_CONSTANT, objabi.KindUintptr, 0)
  1550  
  1551  	// Prototypes needed for type synthesis.
  1552  	prototypedies = map[string]*dwarf.DWDie{
  1553  		"type.runtime.stringStructDWARF": nil,
  1554  		"type.runtime.slice":             nil,
  1555  		"type.runtime.hmap":              nil,
  1556  		"type.runtime.bmap":              nil,
  1557  		"type.runtime.sudog":             nil,
  1558  		"type.runtime.waitq":             nil,
  1559  		"type.runtime.hchan":             nil,
  1560  	}
  1561  
  1562  	// Needed by the prettyprinter code for interface inspection.
  1563  	for _, typ := range []string{
  1564  		"type.runtime._type",
  1565  		"type.runtime.arraytype",
  1566  		"type.runtime.chantype",
  1567  		"type.runtime.functype",
  1568  		"type.runtime.maptype",
  1569  		"type.runtime.ptrtype",
  1570  		"type.runtime.slicetype",
  1571  		"type.runtime.structtype",
  1572  		"type.runtime.interfacetype",
  1573  		"type.runtime.itab",
  1574  		"type.runtime.imethod"} {
  1575  		defgotype(ctxt, lookupOrDiag(ctxt, typ))
  1576  	}
  1577  
  1578  	genasmsym(ctxt, defdwsymb)
  1579  
  1580  	syms := writeabbrev(ctxt, nil)
  1581  	syms, funcs := writelines(ctxt, syms)
  1582  	syms = writeframes(ctxt, syms)
  1583  	syms = writeranges(ctxt, syms)
  1584  
  1585  	synthesizestringtypes(ctxt, dwtypes.Child)
  1586  	synthesizeslicetypes(ctxt, dwtypes.Child)
  1587  	synthesizemaptypes(ctxt, dwtypes.Child)
  1588  	synthesizechantypes(ctxt, dwtypes.Child)
  1589  
  1590  	reversetree(&dwroot.Child)
  1591  	reversetree(&dwtypes.Child)
  1592  	reversetree(&dwglobals.Child)
  1593  
  1594  	movetomodule(&dwtypes)
  1595  	movetomodule(&dwglobals)
  1596  
  1597  	// Need to reorder symbols so SDWARFINFO is after all SDWARFSECT
  1598  	// (but we need to generate dies before writepub)
  1599  	infosyms := writeinfo(ctxt, nil, funcs)
  1600  
  1601  	syms = writepub(ctxt, ".debug_pubnames", ispubname, syms)
  1602  	syms = writepub(ctxt, ".debug_pubtypes", ispubtype, syms)
  1603  	syms = writearanges(ctxt, syms)
  1604  	syms = writegdbscript(ctxt, syms)
  1605  	syms = append(syms, infosyms...)
  1606  	dwarfp = syms
  1607  }
  1608  
  1609  /*
  1610   *  Elf.
  1611   */
  1612  func dwarfaddshstrings(ctxt *Link, shstrtab *Symbol) {
  1613  	if *FlagW { // disable dwarf
  1614  		return
  1615  	}
  1616  
  1617  	Addstring(shstrtab, ".debug_abbrev")
  1618  	Addstring(shstrtab, ".debug_aranges")
  1619  	Addstring(shstrtab, ".debug_frame")
  1620  	Addstring(shstrtab, ".debug_info")
  1621  	Addstring(shstrtab, ".debug_line")
  1622  	Addstring(shstrtab, ".debug_pubnames")
  1623  	Addstring(shstrtab, ".debug_pubtypes")
  1624  	Addstring(shstrtab, ".debug_gdb_scripts")
  1625  	Addstring(shstrtab, ".debug_ranges")
  1626  	if Linkmode == LinkExternal {
  1627  		Addstring(shstrtab, elfRelType+".debug_info")
  1628  		Addstring(shstrtab, elfRelType+".debug_aranges")
  1629  		Addstring(shstrtab, elfRelType+".debug_line")
  1630  		Addstring(shstrtab, elfRelType+".debug_frame")
  1631  		Addstring(shstrtab, elfRelType+".debug_pubnames")
  1632  		Addstring(shstrtab, elfRelType+".debug_pubtypes")
  1633  		Addstring(shstrtab, elfRelType+".debug_ranges")
  1634  	}
  1635  }
  1636  
  1637  // Add section symbols for DWARF debug info.  This is called before
  1638  // dwarfaddelfheaders.
  1639  func dwarfaddelfsectionsyms(ctxt *Link) {
  1640  	if *FlagW { // disable dwarf
  1641  		return
  1642  	}
  1643  	if Linkmode != LinkExternal {
  1644  		return
  1645  	}
  1646  	sym := ctxt.Syms.Lookup(".debug_info", 0)
  1647  	putelfsectionsym(sym, sym.Sect.Elfsect.shnum)
  1648  	sym = ctxt.Syms.Lookup(".debug_abbrev", 0)
  1649  	putelfsectionsym(sym, sym.Sect.Elfsect.shnum)
  1650  	sym = ctxt.Syms.Lookup(".debug_line", 0)
  1651  	putelfsectionsym(sym, sym.Sect.Elfsect.shnum)
  1652  	sym = ctxt.Syms.Lookup(".debug_frame", 0)
  1653  	putelfsectionsym(sym, sym.Sect.Elfsect.shnum)
  1654  	sym = ctxt.Syms.Lookup(".debug_ranges", 0)
  1655  	if sym.Sect != nil {
  1656  		putelfsectionsym(sym, sym.Sect.Elfsect.shnum)
  1657  	}
  1658  }
  1659  
  1660  /*
  1661   * Windows PE
  1662   */
  1663  func dwarfaddpeheaders(ctxt *Link) {
  1664  	if *FlagW { // disable dwarf
  1665  		return
  1666  	}
  1667  	for _, sect := range Segdwarf.Sections {
  1668  		h := newPEDWARFSection(ctxt, sect.Name, int64(sect.Length))
  1669  		fileoff := sect.Vaddr - Segdwarf.Vaddr + Segdwarf.Fileoff
  1670  		if uint64(h.PointerToRawData) != fileoff {
  1671  			Exitf("%s.PointerToRawData = %#x, want %#x", sect.Name, h.PointerToRawData, fileoff)
  1672  		}
  1673  	}
  1674  }