1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
6 // - eliminate DW_CLS_ if not used
7 // - package info in compilation units
8 // - assign types to their packages
9 // - gdb uses c syntax, meaning clumsy quoting is needed for go identifiers. eg
10 // ptype struct '[]uint8' and qualifiers need to be quoted away
11 // - file:line info for variables
12 // - make strings a typedef so prettyprinters can see the underlying string type
22 "cmd/link/internal/loader"
23 "cmd/link/internal/sym"
35 // dwctxt is a wrapper intended to satisfy the method set of
36 // dwarf.Context, so that functions like dwarf.PutAttrs will work with
37 // DIEs that use loader.Sym as opposed to *sym.Symbol. It is also
38 // being used as a place to store tables/maps that are useful as part
39 // of type conversion (this is just a convenience; it would be easy to
40 // split these things out into another type if need be).
46 // This maps type name string (e.g. "uintptr") to loader symbol for
47 // the DWARF DIE for that type (e.g. "go:info.type.uintptr")
48 tmap map[string]loader.Sym
50 // This maps loader symbol for the DWARF DIE symbol generated for
51 // a type (e.g. "go:info.uintptr") to the type symbol itself
53 // FIXME: try converting this map (and the next one) to a single
54 // array indexed by loader.Sym -- this may perform better.
55 rtmap map[loader.Sym]loader.Sym
57 // This maps Go type symbol (e.g. "type:XXX") to loader symbol for
58 // the typedef DIE for that type (e.g. "go:info.XXX..def")
59 tdmap map[loader.Sym]loader.Sym
61 // Cache these type symbols, so as to avoid repeatedly looking them up
62 typeRuntimeEface loader.Sym
63 typeRuntimeIface loader.Sym
64 uintptrInfoSym loader.Sym
66 // Used at various points in that parallel portion of DWARF gen to
67 // protect against conflicting updates to globals (such as "gdbscript")
71 // dwSym wraps a loader.Sym; this type is meant to obey the interface
72 // rules for dwarf.Sym from the cmd/internal/dwarf package. DwDie and
73 // DwAttr objects contain references to symbols via this type.
76 func (c dwctxt) PtrSize() int {
80 func (c dwctxt) Size(s dwarf.Sym) int64 {
81 return int64(len(c.ldr.Data(loader.Sym(s.(dwSym)))))
84 func (c dwctxt) AddInt(s dwarf.Sym, size int, i int64) {
85 ds := loader.Sym(s.(dwSym))
86 dsu := c.ldr.MakeSymbolUpdater(ds)
87 dsu.AddUintXX(c.arch, uint64(i), size)
90 func (c dwctxt) AddBytes(s dwarf.Sym, b []byte) {
91 ds := loader.Sym(s.(dwSym))
92 dsu := c.ldr.MakeSymbolUpdater(ds)
96 func (c dwctxt) AddString(s dwarf.Sym, v string) {
97 ds := loader.Sym(s.(dwSym))
98 dsu := c.ldr.MakeSymbolUpdater(ds)
102 func (c dwctxt) AddAddress(s dwarf.Sym, data interface{}, value int64) {
103 ds := loader.Sym(s.(dwSym))
104 dsu := c.ldr.MakeSymbolUpdater(ds)
108 tgtds := loader.Sym(data.(dwSym))
109 dsu.AddAddrPlus(c.arch, tgtds, value)
112 func (c dwctxt) AddCURelativeAddress(s dwarf.Sym, data interface{}, value int64) {
113 ds := loader.Sym(s.(dwSym))
114 dsu := c.ldr.MakeSymbolUpdater(ds)
118 tgtds := loader.Sym(data.(dwSym))
119 dsu.AddCURelativeAddrPlus(c.arch, tgtds, value)
122 func (c dwctxt) AddSectionOffset(s dwarf.Sym, size int, t interface{}, ofs int64) {
123 ds := loader.Sym(s.(dwSym))
124 dsu := c.ldr.MakeSymbolUpdater(ds)
125 tds := loader.Sym(t.(dwSym))
128 c.linkctxt.Errorf(ds, "invalid size %d in adddwarfref\n", size)
129 case c.arch.PtrSize, 4:
131 dsu.AddSymRef(c.arch, tds, ofs, objabi.R_ADDROFF, size)
134 func (c dwctxt) AddDWARFAddrSectionOffset(s dwarf.Sym, t interface{}, ofs int64) {
136 if isDwarf64(c.linkctxt) {
139 ds := loader.Sym(s.(dwSym))
140 dsu := c.ldr.MakeSymbolUpdater(ds)
141 tds := loader.Sym(t.(dwSym))
144 c.linkctxt.Errorf(ds, "invalid size %d in adddwarfref\n", size)
145 case c.arch.PtrSize, 4:
147 dsu.AddSymRef(c.arch, tds, ofs, objabi.R_DWARFSECREF, size)
150 func (c dwctxt) Logf(format string, args ...interface{}) {
151 c.linkctxt.Logf(format, args...)
154 // At the moment these interfaces are only used in the compiler.
156 func (c dwctxt) CurrentOffset(s dwarf.Sym) int64 {
157 panic("should be used only in the compiler")
160 func (c dwctxt) RecordDclReference(s dwarf.Sym, t dwarf.Sym, dclIdx int, inlIndex int) {
161 panic("should be used only in the compiler")
164 func (c dwctxt) RecordChildDieOffsets(s dwarf.Sym, vars []*dwarf.Var, offsets []int32) {
165 panic("should be used only in the compiler")
168 func isDwarf64(ctxt *Link) bool {
169 return ctxt.HeadType == objabi.Haix
172 // https://sourceware.org/gdb/onlinedocs/gdb/dotdebug_005fgdb_005fscripts-section.html
173 // Each entry inside .debug_gdb_scripts section begins with a non-null prefix
174 // byte that specifies the kind of entry. The following entries are supported:
176 GdbScriptPythonFileId = 1
177 GdbScriptSchemeFileId = 3
178 GdbScriptPythonTextId = 4
179 GdbScriptSchemeTextId = 6
184 // dwarfSecInfo holds information about a DWARF output section,
185 // specifically a section symbol and a list of symbols contained in
186 // that section. On the syms list, the first symbol will always be the
187 // section symbol, then any remaining symbols (if any) will be
188 // sub-symbols in that section. Note that for some sections (eg:
189 // .debug_abbrev), the section symbol is all there is (all content is
190 // contained in it). For other sections (eg: .debug_info), the section
191 // symbol is empty and all the content is in the sub-symbols. Finally
192 // there are some sections (eg: .debug_ranges) where it is a mix (both
193 // the section symbol and the sub-symbols have content)
194 type dwarfSecInfo struct {
198 // secSym returns the section symbol for the section.
199 func (dsi *dwarfSecInfo) secSym() loader.Sym {
200 if len(dsi.syms) == 0 {
206 // subSyms returns a list of sub-symbols for the section.
207 func (dsi *dwarfSecInfo) subSyms() []loader.Sym {
208 if len(dsi.syms) == 0 {
209 return []loader.Sym{}
214 // dwarfp stores the collected DWARF symbols created during
216 var dwarfp []dwarfSecInfo
218 func (d *dwctxt) writeabbrev() dwarfSecInfo {
219 abrvs := d.ldr.CreateSymForUpdate(".debug_abbrev", 0)
220 abrvs.SetType(sym.SDWARFSECT)
221 abrvs.AddBytes(dwarf.GetAbbrev())
222 return dwarfSecInfo{syms: []loader.Sym{abrvs.Sym()}}
225 var dwtypes dwarf.DWDie
227 // newattr attaches a new attribute to the specified DIE.
229 // FIXME: at the moment attributes are stored in a linked list in a
230 // fairly space-inefficient way -- it might be better to instead look
231 // up all attrs in a single large table, then store indices into the
232 // table in the DIE. This would allow us to common up storage for
233 // attributes that are shared by many DIEs (ex: byte size of N).
234 func newattr(die *dwarf.DWDie, attr uint16, cls int, value int64, data interface{}) {
235 a := new(dwarf.DWAttr)
244 // Each DIE (except the root ones) has at least 1 attribute: its
245 // name. getattr moves the desired one to the front so
246 // frequently searched ones are found faster.
247 func getattr(die *dwarf.DWDie, attr uint16) *dwarf.DWAttr {
248 if die.Attr.Atr == attr {
269 // Every DIE manufactured by the linker has at least an AT_name
270 // attribute (but it will only be written out if it is listed in the abbrev).
271 // The compiler does create nameless DWARF DIEs (ex: concrete subprogram
273 // FIXME: it would be more efficient to bulk-allocate DIEs.
274 func (d *dwctxt) newdie(parent *dwarf.DWDie, abbrev int, name string) *dwarf.DWDie {
275 die := new(dwarf.DWDie)
277 die.Link = parent.Child
280 newattr(die, dwarf.DW_AT_name, dwarf.DW_CLS_STRING, int64(len(name)), name)
282 // Sanity check: all DIEs created in the linker should be named.
284 panic("nameless DWARF DIE")
289 case dwarf.DW_ABRV_FUNCTYPEPARAM, dwarf.DW_ABRV_DOTDOTDOT, dwarf.DW_ABRV_STRUCTFIELD, dwarf.DW_ABRV_ARRAYRANGE:
290 // There are no relocations against these dies, and their names
291 // are not unique, so don't create a symbol.
293 case dwarf.DW_ABRV_COMPUNIT, dwarf.DW_ABRV_COMPUNIT_TEXTLESS:
294 // Avoid collisions with "real" symbol names.
295 name = fmt.Sprintf(".pkg.%s.%d", name, len(d.linkctxt.compUnits))
296 st = sym.SDWARFCUINFO
297 case dwarf.DW_ABRV_VARIABLE:
300 // Everything else is assigned a type of SDWARFTYPE. that
301 // this also includes loose ends such as STRUCT_FIELD.
304 ds := d.ldr.LookupOrCreateSym(dwarf.InfoPrefix+name, 0)
305 dsu := d.ldr.MakeSymbolUpdater(ds)
307 d.ldr.SetAttrNotInSymbolTable(ds, true)
308 d.ldr.SetAttrReachable(ds, true)
310 if abbrev >= dwarf.DW_ABRV_NULLTYPE && abbrev <= dwarf.DW_ABRV_TYPEDECL {
317 func walktypedef(die *dwarf.DWDie) *dwarf.DWDie {
321 // Resolve typedef if present.
322 if die.Abbrev == dwarf.DW_ABRV_TYPEDECL {
323 for attr := die.Attr; attr != nil; attr = attr.Link {
324 if attr.Atr == dwarf.DW_AT_type && attr.Cls == dwarf.DW_CLS_REFERENCE && attr.Data != nil {
325 return attr.Data.(*dwarf.DWDie)
333 func (d *dwctxt) walksymtypedef(symIdx loader.Sym) loader.Sym {
335 // We're being given the loader symbol for the type DIE, e.g.
336 // "go:info.type.uintptr". Map that first to the type symbol (e.g.
337 // "type:uintptr") and then to the typedef DIE for the type.
338 // FIXME: this seems clunky, maybe there is a better way to do this.
340 if ts, ok := d.rtmap[symIdx]; ok {
341 if def, ok := d.tdmap[ts]; ok {
344 d.linkctxt.Errorf(ts, "internal error: no entry for sym %d in tdmap\n", ts)
347 d.linkctxt.Errorf(symIdx, "internal error: no entry for sym %d in rtmap\n", symIdx)
351 // Find child by AT_name using hashtable if available or linear scan
353 func findchild(die *dwarf.DWDie, name string) *dwarf.DWDie {
354 var prev *dwarf.DWDie
355 for ; die != prev; prev, die = die, walktypedef(die) {
356 for a := die.Child; a != nil; a = a.Link {
357 if name == getattr(a, dwarf.DW_AT_name).Data {
366 // find looks up the loader symbol for the DWARF DIE generated for the
367 // type with the specified name.
368 func (d *dwctxt) find(name string) loader.Sym {
372 func (d *dwctxt) mustFind(name string) loader.Sym {
375 Exitf("dwarf find: cannot find %s", name)
380 func (d *dwctxt) adddwarfref(sb *loader.SymbolBuilder, t loader.Sym, size int) {
383 d.linkctxt.Errorf(sb.Sym(), "invalid size %d in adddwarfref\n", size)
384 case d.arch.PtrSize, 4:
386 sb.AddSymRef(d.arch, t, 0, objabi.R_DWARFSECREF, size)
389 func (d *dwctxt) newrefattr(die *dwarf.DWDie, attr uint16, ref loader.Sym) {
393 newattr(die, attr, dwarf.DW_CLS_REFERENCE, 0, dwSym(ref))
396 func (d *dwctxt) dtolsym(s dwarf.Sym) loader.Sym {
400 dws := loader.Sym(s.(dwSym))
404 func (d *dwctxt) putdie(syms []loader.Sym, die *dwarf.DWDie) []loader.Sym {
405 s := d.dtolsym(die.Sym)
407 s = syms[len(syms)-1]
409 syms = append(syms, s)
412 dwarf.Uleb128put(d, sDwsym, int64(die.Abbrev))
413 dwarf.PutAttrs(d, sDwsym, die.Abbrev, die.Attr)
414 if dwarf.HasChildren(die) {
415 for die := die.Child; die != nil; die = die.Link {
416 syms = d.putdie(syms, die)
418 dsu := d.ldr.MakeSymbolUpdater(syms[len(syms)-1])
424 func reverselist(list **dwarf.DWDie) {
426 var prev *dwarf.DWDie
437 func reversetree(list **dwarf.DWDie) {
439 for die := *list; die != nil; die = die.Link {
440 if dwarf.HasChildren(die) {
441 reversetree(&die.Child)
446 func newmemberoffsetattr(die *dwarf.DWDie, offs int32) {
447 newattr(die, dwarf.DW_AT_data_member_location, dwarf.DW_CLS_CONSTANT, int64(offs), nil)
450 func (d *dwctxt) lookupOrDiag(n string) loader.Sym {
451 symIdx := d.ldr.Lookup(n, 0)
453 Exitf("dwarf: missing type: %s", n)
455 if len(d.ldr.Data(symIdx)) == 0 {
456 Exitf("dwarf: missing type (no data): %s", n)
462 func (d *dwctxt) dotypedef(parent *dwarf.DWDie, name string, def *dwarf.DWDie) *dwarf.DWDie {
463 // Only emit typedefs for real names.
464 if strings.HasPrefix(name, "map[") {
467 if strings.HasPrefix(name, "struct {") {
470 // cmd/compile uses "noalg.struct {...}" as type name when hash and eq algorithm generation of
471 // this struct type is suppressed.
472 if strings.HasPrefix(name, "noalg.struct {") {
475 if strings.HasPrefix(name, "chan ") {
478 if name[0] == '[' || name[0] == '*' {
482 Errorf(nil, "dwarf: bad def in dotypedef")
485 // Create a new loader symbol for the typedef. We no longer
486 // do lookups of typedef symbols by name, so this is going
487 // to be an anonymous symbol (we want this for perf reasons).
488 tds := d.ldr.CreateExtSym("", 0)
489 tdsu := d.ldr.MakeSymbolUpdater(tds)
490 tdsu.SetType(sym.SDWARFTYPE)
492 d.ldr.SetAttrNotInSymbolTable(tds, true)
493 d.ldr.SetAttrReachable(tds, true)
495 // The typedef entry must be created after the def,
496 // so that future lookups will find the typedef instead
497 // of the real definition. This hooks the typedef into any
498 // circular definition loops, so that gdb can understand them.
499 die := d.newdie(parent, dwarf.DW_ABRV_TYPEDECL, name)
501 d.newrefattr(die, dwarf.DW_AT_type, tds)
506 // Define gotype, for composite ones recurse into constituents.
507 func (d *dwctxt) defgotype(gotype loader.Sym) loader.Sym {
509 return d.mustFind("<unspecified>")
512 // If we already have a tdmap entry for the gotype, return it.
513 if ds, ok := d.tdmap[gotype]; ok {
517 sn := d.ldr.SymName(gotype)
518 if !strings.HasPrefix(sn, "type:") {
519 d.linkctxt.Errorf(gotype, "dwarf: type name doesn't start with \"type:\"")
520 return d.mustFind("<unspecified>")
522 name := sn[5:] // could also decode from Type.string
529 gtdwSym := d.newtype(gotype)
530 d.tdmap[gotype] = loader.Sym(gtdwSym.Sym.(dwSym))
531 return loader.Sym(gtdwSym.Sym.(dwSym))
534 func (d *dwctxt) newtype(gotype loader.Sym) *dwarf.DWDie {
535 sn := d.ldr.SymName(gotype)
536 name := sn[5:] // could also decode from Type.string
537 tdata := d.ldr.Data(gotype)
539 d.linkctxt.Errorf(gotype, "missing type")
541 kind := decodetypeKind(d.arch, tdata)
542 bytesize := decodetypeSize(d.arch, tdata)
544 var die, typedefdie *dwarf.DWDie
546 case objabi.KindBool:
547 die = d.newdie(&dwtypes, dwarf.DW_ABRV_BASETYPE, name)
548 newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_boolean, 0)
549 newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
556 die = d.newdie(&dwtypes, dwarf.DW_ABRV_BASETYPE, name)
557 newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_signed, 0)
558 newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
560 case objabi.KindUint,
566 die = d.newdie(&dwtypes, dwarf.DW_ABRV_BASETYPE, name)
567 newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_unsigned, 0)
568 newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
570 case objabi.KindFloat32,
572 die = d.newdie(&dwtypes, dwarf.DW_ABRV_BASETYPE, name)
573 newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_float, 0)
574 newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
576 case objabi.KindComplex64,
577 objabi.KindComplex128:
578 die = d.newdie(&dwtypes, dwarf.DW_ABRV_BASETYPE, name)
579 newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_complex_float, 0)
580 newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
582 case objabi.KindArray:
583 die = d.newdie(&dwtypes, dwarf.DW_ABRV_ARRAYTYPE, name)
584 typedefdie = d.dotypedef(&dwtypes, name, die)
585 newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
586 s := decodetypeArrayElem(d.ldr, d.arch, gotype)
587 d.newrefattr(die, dwarf.DW_AT_type, d.defgotype(s))
588 fld := d.newdie(die, dwarf.DW_ABRV_ARRAYRANGE, "range")
590 // use actual length not upper bound; correct for 0-length arrays.
591 newattr(fld, dwarf.DW_AT_count, dwarf.DW_CLS_CONSTANT, decodetypeArrayLen(d.ldr, d.arch, gotype), 0)
593 d.newrefattr(fld, dwarf.DW_AT_type, d.uintptrInfoSym)
595 case objabi.KindChan:
596 die = d.newdie(&dwtypes, dwarf.DW_ABRV_CHANTYPE, name)
597 s := decodetypeChanElem(d.ldr, d.arch, gotype)
598 d.newrefattr(die, dwarf.DW_AT_go_elem, d.defgotype(s))
599 // Save elem type for synthesizechantypes. We could synthesize here
600 // but that would change the order of DIEs we output.
601 d.newrefattr(die, dwarf.DW_AT_type, s)
603 case objabi.KindFunc:
604 die = d.newdie(&dwtypes, dwarf.DW_ABRV_FUNCTYPE, name)
605 newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
606 typedefdie = d.dotypedef(&dwtypes, name, die)
607 data := d.ldr.Data(gotype)
608 // FIXME: add caching or reuse reloc slice.
609 relocs := d.ldr.Relocs(gotype)
610 nfields := decodetypeFuncInCount(d.arch, data)
611 for i := 0; i < nfields; i++ {
612 s := decodetypeFuncInType(d.ldr, d.arch, gotype, &relocs, i)
613 sn := d.ldr.SymName(s)
614 fld := d.newdie(die, dwarf.DW_ABRV_FUNCTYPEPARAM, sn[5:])
615 d.newrefattr(fld, dwarf.DW_AT_type, d.defgotype(s))
618 if decodetypeFuncDotdotdot(d.arch, data) {
619 d.newdie(die, dwarf.DW_ABRV_DOTDOTDOT, "...")
621 nfields = decodetypeFuncOutCount(d.arch, data)
622 for i := 0; i < nfields; i++ {
623 s := decodetypeFuncOutType(d.ldr, d.arch, gotype, &relocs, i)
624 sn := d.ldr.SymName(s)
625 fld := d.newdie(die, dwarf.DW_ABRV_FUNCTYPEPARAM, sn[5:])
626 d.newrefattr(fld, dwarf.DW_AT_type, d.defptrto(d.defgotype(s)))
629 case objabi.KindInterface:
630 die = d.newdie(&dwtypes, dwarf.DW_ABRV_IFACETYPE, name)
631 typedefdie = d.dotypedef(&dwtypes, name, die)
632 data := d.ldr.Data(gotype)
633 nfields := int(decodetypeIfaceMethodCount(d.arch, data))
636 s = d.typeRuntimeEface
638 s = d.typeRuntimeIface
640 d.newrefattr(die, dwarf.DW_AT_type, d.defgotype(s))
643 die = d.newdie(&dwtypes, dwarf.DW_ABRV_MAPTYPE, name)
644 s := decodetypeMapKey(d.ldr, d.arch, gotype)
645 d.newrefattr(die, dwarf.DW_AT_go_key, d.defgotype(s))
646 s = decodetypeMapValue(d.ldr, d.arch, gotype)
647 d.newrefattr(die, dwarf.DW_AT_go_elem, d.defgotype(s))
648 // Save gotype for use in synthesizemaptypes. We could synthesize here,
649 // but that would change the order of the DIEs.
650 d.newrefattr(die, dwarf.DW_AT_type, gotype)
653 die = d.newdie(&dwtypes, dwarf.DW_ABRV_PTRTYPE, name)
654 typedefdie = d.dotypedef(&dwtypes, name, die)
655 s := decodetypePtrElem(d.ldr, d.arch, gotype)
656 d.newrefattr(die, dwarf.DW_AT_type, d.defgotype(s))
658 case objabi.KindSlice:
659 die = d.newdie(&dwtypes, dwarf.DW_ABRV_SLICETYPE, name)
660 typedefdie = d.dotypedef(&dwtypes, name, die)
661 newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
662 s := decodetypeArrayElem(d.ldr, d.arch, gotype)
663 elem := d.defgotype(s)
664 d.newrefattr(die, dwarf.DW_AT_go_elem, elem)
666 case objabi.KindString:
667 die = d.newdie(&dwtypes, dwarf.DW_ABRV_STRINGTYPE, name)
668 newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
670 case objabi.KindStruct:
671 die = d.newdie(&dwtypes, dwarf.DW_ABRV_STRUCTTYPE, name)
672 typedefdie = d.dotypedef(&dwtypes, name, die)
673 newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, bytesize, 0)
674 nfields := decodetypeStructFieldCount(d.ldr, d.arch, gotype)
675 for i := 0; i < nfields; i++ {
676 f := decodetypeStructFieldName(d.ldr, d.arch, gotype, i)
677 s := decodetypeStructFieldType(d.ldr, d.arch, gotype, i)
679 sn := d.ldr.SymName(s)
680 f = sn[5:] // skip "type:"
682 fld := d.newdie(die, dwarf.DW_ABRV_STRUCTFIELD, f)
683 d.newrefattr(fld, dwarf.DW_AT_type, d.defgotype(s))
684 offset := decodetypeStructFieldOffset(d.ldr, d.arch, gotype, i)
685 newmemberoffsetattr(fld, int32(offset))
686 if decodetypeStructFieldEmbedded(d.ldr, d.arch, gotype, i) {
687 newattr(fld, dwarf.DW_AT_go_embedded_field, dwarf.DW_CLS_FLAG, 1, 0)
691 case objabi.KindUnsafePointer:
692 die = d.newdie(&dwtypes, dwarf.DW_ABRV_BARE_PTRTYPE, name)
695 d.linkctxt.Errorf(gotype, "dwarf: definition of unknown kind %d", kind)
696 die = d.newdie(&dwtypes, dwarf.DW_ABRV_TYPEDECL, name)
697 d.newrefattr(die, dwarf.DW_AT_type, d.mustFind("<unspecified>"))
700 newattr(die, dwarf.DW_AT_go_kind, dwarf.DW_CLS_CONSTANT, int64(kind), 0)
702 if d.ldr.AttrReachable(gotype) {
703 newattr(die, dwarf.DW_AT_go_runtime_type, dwarf.DW_CLS_GO_TYPEREF, 0, dwSym(gotype))
707 if _, ok := d.rtmap[gotype]; ok {
708 log.Fatalf("internal error: rtmap entry already installed\n")
711 ds := loader.Sym(die.Sym.(dwSym))
712 if typedefdie != nil {
713 ds = loader.Sym(typedefdie.Sym.(dwSym))
717 if _, ok := prototypedies[sn]; ok {
718 prototypedies[sn] = die
721 if typedefdie != nil {
727 func (d *dwctxt) nameFromDIESym(dwtypeDIESym loader.Sym) string {
728 sn := d.ldr.SymName(dwtypeDIESym)
729 return sn[len(dwarf.InfoPrefix):]
732 func (d *dwctxt) defptrto(dwtype loader.Sym) loader.Sym {
734 // FIXME: it would be nice if the compiler attached an aux symbol
735 // ref from the element type to the pointer type -- it would be
736 // more efficient to do it this way as opposed to via name lookups.
738 ptrname := "*" + d.nameFromDIESym(dwtype)
739 if die := d.find(ptrname); die != 0 {
743 pdie := d.newdie(&dwtypes, dwarf.DW_ABRV_PTRTYPE, ptrname)
744 d.newrefattr(pdie, dwarf.DW_AT_type, dwtype)
746 // The DWARF info synthesizes pointer types that don't exist at the
747 // language level, like *hash<...> and *bucket<...>, and the data
748 // pointers of slices. Link to the ones we can find.
749 gts := d.ldr.Lookup("type:"+ptrname, 0)
750 if gts != 0 && d.ldr.AttrReachable(gts) {
751 newattr(pdie, dwarf.DW_AT_go_runtime_type, dwarf.DW_CLS_GO_TYPEREF, 0, dwSym(gts))
755 ds := loader.Sym(pdie.Sym.(dwSym))
760 return d.dtolsym(pdie.Sym)
763 // Copies src's children into dst. Copies attributes by value.
764 // DWAttr.data is copied as pointer only. If except is one of
765 // the top-level children, it will not be copied.
766 func (d *dwctxt) copychildrenexcept(ctxt *Link, dst *dwarf.DWDie, src *dwarf.DWDie, except *dwarf.DWDie) {
767 for src = src.Child; src != nil; src = src.Link {
771 c := d.newdie(dst, src.Abbrev, getattr(src, dwarf.DW_AT_name).Data.(string))
772 for a := src.Attr; a != nil; a = a.Link {
773 newattr(c, a.Atr, int(a.Cls), a.Value, a.Data)
775 d.copychildrenexcept(ctxt, c, src, nil)
778 reverselist(&dst.Child)
781 func (d *dwctxt) copychildren(ctxt *Link, dst *dwarf.DWDie, src *dwarf.DWDie) {
782 d.copychildrenexcept(ctxt, dst, src, nil)
785 // Search children (assumed to have TAG_member) for the one named
786 // field and set its AT_type to dwtype
787 func (d *dwctxt) substitutetype(structdie *dwarf.DWDie, field string, dwtype loader.Sym) {
788 child := findchild(structdie, field)
790 Exitf("dwarf substitutetype: %s does not have member %s",
791 getattr(structdie, dwarf.DW_AT_name).Data, field)
795 a := getattr(child, dwarf.DW_AT_type)
797 a.Data = dwSym(dwtype)
799 d.newrefattr(child, dwarf.DW_AT_type, dwtype)
803 func (d *dwctxt) findprotodie(ctxt *Link, name string) *dwarf.DWDie {
804 die, ok := prototypedies[name]
805 if ok && die == nil {
806 d.defgotype(d.lookupOrDiag(name))
807 die = prototypedies[name]
810 log.Fatalf("internal error: DIE generation failed for %s\n", name)
815 func (d *dwctxt) synthesizestringtypes(ctxt *Link, die *dwarf.DWDie) {
816 prototype := walktypedef(d.findprotodie(ctxt, "type:runtime.stringStructDWARF"))
817 if prototype == nil {
821 for ; die != nil; die = die.Link {
822 if die.Abbrev != dwarf.DW_ABRV_STRINGTYPE {
825 d.copychildren(ctxt, die, prototype)
829 func (d *dwctxt) synthesizeslicetypes(ctxt *Link, die *dwarf.DWDie) {
830 prototype := walktypedef(d.findprotodie(ctxt, "type:runtime.slice"))
831 if prototype == nil {
835 for ; die != nil; die = die.Link {
836 if die.Abbrev != dwarf.DW_ABRV_SLICETYPE {
839 d.copychildren(ctxt, die, prototype)
840 elem := loader.Sym(getattr(die, dwarf.DW_AT_go_elem).Data.(dwSym))
841 d.substitutetype(die, "array", d.defptrto(elem))
845 func mkinternaltypename(base string, arg1 string, arg2 string) string {
847 return fmt.Sprintf("%s<%s>", base, arg1)
849 return fmt.Sprintf("%s<%s,%s>", base, arg1, arg2)
852 // synthesizemaptypes is way too closely married to runtime/hashmap.c
854 MaxKeySize = abi.MapMaxKeyBytes
855 MaxValSize = abi.MapMaxElemBytes
856 BucketSize = abi.MapBucketCount
859 func (d *dwctxt) mkinternaltype(ctxt *Link, abbrev int, typename, keyname, valname string, f func(*dwarf.DWDie)) loader.Sym {
860 name := mkinternaltypename(typename, keyname, valname)
861 symname := dwarf.InfoPrefix + name
862 s := d.ldr.Lookup(symname, 0)
863 if s != 0 && d.ldr.SymType(s) == sym.SDWARFTYPE {
866 die := d.newdie(&dwtypes, abbrev, name)
868 return d.dtolsym(die.Sym)
871 func (d *dwctxt) synthesizemaptypes(ctxt *Link, die *dwarf.DWDie) {
872 hash := walktypedef(d.findprotodie(ctxt, "type:runtime.hmap"))
873 bucket := walktypedef(d.findprotodie(ctxt, "type:runtime.bmap"))
879 for ; die != nil; die = die.Link {
880 if die.Abbrev != dwarf.DW_ABRV_MAPTYPE {
883 gotype := loader.Sym(getattr(die, dwarf.DW_AT_type).Data.(dwSym))
884 keytype := decodetypeMapKey(d.ldr, d.arch, gotype)
885 valtype := decodetypeMapValue(d.ldr, d.arch, gotype)
886 keydata := d.ldr.Data(keytype)
887 valdata := d.ldr.Data(valtype)
888 keysize, valsize := decodetypeSize(d.arch, keydata), decodetypeSize(d.arch, valdata)
889 keytype, valtype = d.walksymtypedef(d.defgotype(keytype)), d.walksymtypedef(d.defgotype(valtype))
891 // compute size info like hashmap.c does.
892 indirectKey, indirectVal := false, false
893 if keysize > MaxKeySize {
894 keysize = int64(d.arch.PtrSize)
897 if valsize > MaxValSize {
898 valsize = int64(d.arch.PtrSize)
902 // Construct type to represent an array of BucketSize keys
903 keyname := d.nameFromDIESym(keytype)
904 dwhks := d.mkinternaltype(ctxt, dwarf.DW_ABRV_ARRAYTYPE, "[]key", keyname, "", func(dwhk *dwarf.DWDie) {
905 newattr(dwhk, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, BucketSize*keysize, 0)
908 t = d.defptrto(keytype)
910 d.newrefattr(dwhk, dwarf.DW_AT_type, t)
911 fld := d.newdie(dwhk, dwarf.DW_ABRV_ARRAYRANGE, "size")
912 newattr(fld, dwarf.DW_AT_count, dwarf.DW_CLS_CONSTANT, BucketSize, 0)
913 d.newrefattr(fld, dwarf.DW_AT_type, d.uintptrInfoSym)
916 // Construct type to represent an array of BucketSize values
917 valname := d.nameFromDIESym(valtype)
918 dwhvs := d.mkinternaltype(ctxt, dwarf.DW_ABRV_ARRAYTYPE, "[]val", valname, "", func(dwhv *dwarf.DWDie) {
919 newattr(dwhv, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, BucketSize*valsize, 0)
922 t = d.defptrto(valtype)
924 d.newrefattr(dwhv, dwarf.DW_AT_type, t)
925 fld := d.newdie(dwhv, dwarf.DW_ABRV_ARRAYRANGE, "size")
926 newattr(fld, dwarf.DW_AT_count, dwarf.DW_CLS_CONSTANT, BucketSize, 0)
927 d.newrefattr(fld, dwarf.DW_AT_type, d.uintptrInfoSym)
930 // Construct bucket<K,V>
931 dwhbs := d.mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "bucket", keyname, valname, func(dwhb *dwarf.DWDie) {
932 // Copy over all fields except the field "data" from the generic
933 // bucket. "data" will be replaced with keys/values below.
934 d.copychildrenexcept(ctxt, dwhb, bucket, findchild(bucket, "data"))
936 fld := d.newdie(dwhb, dwarf.DW_ABRV_STRUCTFIELD, "keys")
937 d.newrefattr(fld, dwarf.DW_AT_type, dwhks)
938 newmemberoffsetattr(fld, BucketSize)
939 fld = d.newdie(dwhb, dwarf.DW_ABRV_STRUCTFIELD, "values")
940 d.newrefattr(fld, dwarf.DW_AT_type, dwhvs)
941 newmemberoffsetattr(fld, BucketSize+BucketSize*int32(keysize))
942 fld = d.newdie(dwhb, dwarf.DW_ABRV_STRUCTFIELD, "overflow")
943 d.newrefattr(fld, dwarf.DW_AT_type, d.defptrto(d.dtolsym(dwhb.Sym)))
944 newmemberoffsetattr(fld, BucketSize+BucketSize*(int32(keysize)+int32(valsize)))
945 if d.arch.RegSize > d.arch.PtrSize {
946 fld = d.newdie(dwhb, dwarf.DW_ABRV_STRUCTFIELD, "pad")
947 d.newrefattr(fld, dwarf.DW_AT_type, d.uintptrInfoSym)
948 newmemberoffsetattr(fld, BucketSize+BucketSize*(int32(keysize)+int32(valsize))+int32(d.arch.PtrSize))
951 newattr(dwhb, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, BucketSize+BucketSize*keysize+BucketSize*valsize+int64(d.arch.RegSize), 0)
954 // Construct hash<K,V>
955 dwhs := d.mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "hash", keyname, valname, func(dwh *dwarf.DWDie) {
956 d.copychildren(ctxt, dwh, hash)
957 d.substitutetype(dwh, "buckets", d.defptrto(dwhbs))
958 d.substitutetype(dwh, "oldbuckets", d.defptrto(dwhbs))
959 newattr(dwh, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, getattr(hash, dwarf.DW_AT_byte_size).Value, nil)
962 // make map type a pointer to hash<K,V>
963 d.newrefattr(die, dwarf.DW_AT_type, d.defptrto(dwhs))
967 func (d *dwctxt) synthesizechantypes(ctxt *Link, die *dwarf.DWDie) {
968 sudog := walktypedef(d.findprotodie(ctxt, "type:runtime.sudog"))
969 waitq := walktypedef(d.findprotodie(ctxt, "type:runtime.waitq"))
970 hchan := walktypedef(d.findprotodie(ctxt, "type:runtime.hchan"))
971 if sudog == nil || waitq == nil || hchan == nil {
975 sudogsize := int(getattr(sudog, dwarf.DW_AT_byte_size).Value)
977 for ; die != nil; die = die.Link {
978 if die.Abbrev != dwarf.DW_ABRV_CHANTYPE {
981 elemgotype := loader.Sym(getattr(die, dwarf.DW_AT_type).Data.(dwSym))
982 tname := d.ldr.SymName(elemgotype)
983 elemname := tname[5:]
984 elemtype := d.walksymtypedef(d.defgotype(d.lookupOrDiag(tname)))
987 dwss := d.mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "sudog", elemname, "", func(dws *dwarf.DWDie) {
988 d.copychildren(ctxt, dws, sudog)
989 d.substitutetype(dws, "elem", d.defptrto(elemtype))
990 newattr(dws, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, int64(sudogsize), nil)
994 dwws := d.mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "waitq", elemname, "", func(dww *dwarf.DWDie) {
996 d.copychildren(ctxt, dww, waitq)
997 d.substitutetype(dww, "first", d.defptrto(dwss))
998 d.substitutetype(dww, "last", d.defptrto(dwss))
999 newattr(dww, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, getattr(waitq, dwarf.DW_AT_byte_size).Value, nil)
1003 dwhs := d.mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "hchan", elemname, "", func(dwh *dwarf.DWDie) {
1004 d.copychildren(ctxt, dwh, hchan)
1005 d.substitutetype(dwh, "recvq", dwws)
1006 d.substitutetype(dwh, "sendq", dwws)
1007 newattr(dwh, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, getattr(hchan, dwarf.DW_AT_byte_size).Value, nil)
1010 d.newrefattr(die, dwarf.DW_AT_type, d.defptrto(dwhs))
1014 // createUnitLength creates the initial length field with value v and update
1015 // offset of unit_length if needed.
1016 func (d *dwctxt) createUnitLength(su *loader.SymbolBuilder, v uint64) {
1017 if isDwarf64(d.linkctxt) {
1018 su.AddUint32(d.arch, 0xFFFFFFFF)
1020 d.addDwarfAddrField(su, v)
1023 // addDwarfAddrField adds a DWARF field in DWARF 64bits or 32bits.
1024 func (d *dwctxt) addDwarfAddrField(sb *loader.SymbolBuilder, v uint64) {
1025 if isDwarf64(d.linkctxt) {
1026 sb.AddUint(d.arch, v)
1028 sb.AddUint32(d.arch, uint32(v))
1032 // addDwarfAddrRef adds a DWARF pointer in DWARF 64bits or 32bits.
1033 func (d *dwctxt) addDwarfAddrRef(sb *loader.SymbolBuilder, t loader.Sym) {
1034 if isDwarf64(d.linkctxt) {
1035 d.adddwarfref(sb, t, 8)
1037 d.adddwarfref(sb, t, 4)
1041 // calcCompUnitRanges calculates the PC ranges of the compilation units.
1042 func (d *dwctxt) calcCompUnitRanges() {
1043 var prevUnit *sym.CompilationUnit
1044 for _, s := range d.linkctxt.Textp {
1045 sym := loader.Sym(s)
1047 fi := d.ldr.FuncInfo(sym)
1052 // Skip linker-created functions (ex: runtime.addmoduledata), since they
1053 // don't have DWARF to begin with.
1054 unit := d.ldr.SymUnit(sym)
1059 // Update PC ranges.
1061 // We don't simply compare the end of the previous
1062 // symbol with the start of the next because there's
1063 // often a little padding between them. Instead, we
1064 // only create boundaries between symbols from
1066 sval := d.ldr.SymValue(sym)
1067 u0val := d.ldr.SymValue(loader.Sym(unit.Textp[0]))
1068 if prevUnit != unit {
1069 unit.PCs = append(unit.PCs, dwarf.Range{Start: sval - u0val})
1072 unit.PCs[len(unit.PCs)-1].End = sval - u0val + int64(len(d.ldr.Data(sym)))
1076 func movetomodule(ctxt *Link, parent *dwarf.DWDie) {
1077 die := ctxt.runtimeCU.DWInfo.Child
1079 ctxt.runtimeCU.DWInfo.Child = parent.Child
1082 for die.Link != nil {
1085 die.Link = parent.Child
1089 * Generate a sequence of opcodes that is as short as possible.
1095 PC_RANGE = (255 - OPCODE_BASE) / LINE_RANGE
1100 * Walk prog table, emit line program and build DIE tree.
1103 func getCompilationDir() string {
1104 // OSX requires this be set to something, but it's not easy to choose
1105 // a value. Linking takes place in a temporary directory, so there's
1106 // no point including it here. Paths in the file table are usually
1107 // absolute, in which case debuggers will ignore this value. -trimpath
1108 // produces relative paths, but we don't know where they start, so
1109 // all we can do here is try not to make things worse.
1113 func (d *dwctxt) importInfoSymbol(dsym loader.Sym) {
1114 d.ldr.SetAttrReachable(dsym, true)
1115 d.ldr.SetAttrNotInSymbolTable(dsym, true)
1116 dst := d.ldr.SymType(dsym)
1117 if dst != sym.SDWARFCONST && dst != sym.SDWARFABSFCN {
1118 log.Fatalf("error: DWARF info sym %d/%s with incorrect type %s", dsym, d.ldr.SymName(dsym), d.ldr.SymType(dsym).String())
1120 relocs := d.ldr.Relocs(dsym)
1121 for i := 0; i < relocs.Count(); i++ {
1123 if r.Type() != objabi.R_DWARFSECREF {
1127 // If there is an entry for the symbol in our rtmap, then it
1128 // means we've processed the type already, and can skip this one.
1129 if _, ok := d.rtmap[rsym]; ok {
1130 // type already generated
1133 // FIXME: is there a way we could avoid materializing the
1134 // symbol name here?
1135 sn := d.ldr.SymName(rsym)
1136 tn := sn[len(dwarf.InfoPrefix):]
1137 ts := d.ldr.Lookup("type:"+tn, 0)
1142 func expandFile(fname string) string {
1143 fname = strings.TrimPrefix(fname, src.FileSymPrefix)
1144 return expandGoroot(fname)
1147 // writeDirFileTables emits the portion of the DWARF line table
1148 // prologue containing the include directories and file names,
1149 // described in section 6.2.4 of the DWARF 4 standard. It walks the
1150 // filepaths for the unit to discover any common directories, which
1151 // are emitted to the directory table first, then the file table is
1152 // emitted after that.
1153 func (d *dwctxt) writeDirFileTables(unit *sym.CompilationUnit, lsu *loader.SymbolBuilder) {
1154 type fileDir struct {
1158 dirNums := make(map[string]int)
1159 dirs := []string{""}
1160 files := []fileDir{}
1162 // Preprocess files to collect directories. This assumes that the
1163 // file table is already de-duped.
1164 for i, name := range unit.FileTable {
1165 name := expandFile(name)
1167 // Can't have empty filenames, and having a unique
1168 // filename is quite useful for debugging.
1169 name = fmt.Sprintf("<missing>_%d", i)
1171 // Note the use of "path" here and not "filepath". The compiler
1172 // hard-codes to use "/" in DWARF paths (even for Windows), so we
1173 // want to maintain that here.
1174 file := path.Base(name)
1175 dir := path.Dir(name)
1176 dirIdx, ok := dirNums[dir]
1177 if !ok && dir != "." {
1178 dirIdx = len(dirNums) + 1
1179 dirNums[dir] = dirIdx
1180 dirs = append(dirs, dir)
1182 files = append(files, fileDir{base: file, dir: dirIdx})
1184 // We can't use something that may be dead-code
1185 // eliminated from a binary here. proc.go contains
1186 // main and the scheduler, so it's not going anywhere.
1187 if i := strings.Index(name, "runtime/proc.go"); i >= 0 && unit.Lib.Pkg == "runtime" {
1189 if gdbscript == "" {
1190 k := strings.Index(name, "runtime/proc.go")
1191 gdbscript = name[:k] + "runtime/runtime-gdb.py"
1197 // Emit directory section. This is a series of nul terminated
1198 // strings, followed by a single zero byte.
1199 lsDwsym := dwSym(lsu.Sym())
1200 for k := 1; k < len(dirs); k++ {
1201 d.AddString(lsDwsym, dirs[k])
1203 lsu.AddUint8(0) // terminator
1205 // Emit file section.
1206 for k := 0; k < len(files); k++ {
1207 d.AddString(lsDwsym, files[k].base)
1208 dwarf.Uleb128put(d, lsDwsym, int64(files[k].dir))
1209 lsu.AddUint8(0) // mtime
1210 lsu.AddUint8(0) // length
1212 lsu.AddUint8(0) // terminator
1215 // writelines collects up and chains together the symbols needed to
1216 // form the DWARF line table for the specified compilation unit,
1217 // returning a list of symbols. The returned list will include an
1218 // initial symbol containing the line table header and prologue (with
1219 // file table), then a series of compiler-emitted line table symbols
1220 // (one per live function), and finally an epilog symbol containing an
1221 // end-of-sequence operator. The prologue and epilog symbols are passed
1222 // in (having been created earlier); here we add content to them.
1223 func (d *dwctxt) writelines(unit *sym.CompilationUnit, lineProlog loader.Sym) []loader.Sym {
1224 is_stmt := uint8(1) // initially = recommended default_is_stmt = 1, tracks is_stmt toggles.
1226 unitstart := int64(-1)
1227 headerstart := int64(-1)
1228 headerend := int64(-1)
1230 syms := make([]loader.Sym, 0, len(unit.Textp)+2)
1231 syms = append(syms, lineProlog)
1232 lsu := d.ldr.MakeSymbolUpdater(lineProlog)
1233 lsDwsym := dwSym(lineProlog)
1234 newattr(unit.DWInfo, dwarf.DW_AT_stmt_list, dwarf.DW_CLS_PTR, 0, lsDwsym)
1236 // Write .debug_line Line Number Program Header (sec 6.2.4)
1237 // Fields marked with (*) must be changed for 64-bit dwarf
1238 unitLengthOffset := lsu.Size()
1239 d.createUnitLength(lsu, 0) // unit_length (*), filled in at end
1240 unitstart = lsu.Size()
1241 lsu.AddUint16(d.arch, 2) // dwarf version (appendix F) -- version 3 is incompatible w/ XCode 9.0's dsymutil, latest supported on OSX 10.12 as of 2018-05
1242 headerLengthOffset := lsu.Size()
1243 d.addDwarfAddrField(lsu, 0) // header_length (*), filled in at end
1244 headerstart = lsu.Size()
1246 // cpos == unitstart + 4 + 2 + 4
1247 lsu.AddUint8(1) // minimum_instruction_length
1248 lsu.AddUint8(is_stmt) // default_is_stmt
1249 lsu.AddUint8(LINE_BASE & 0xFF) // line_base
1250 lsu.AddUint8(LINE_RANGE) // line_range
1251 lsu.AddUint8(OPCODE_BASE) // opcode_base
1252 lsu.AddUint8(0) // standard_opcode_lengths[1]
1253 lsu.AddUint8(1) // standard_opcode_lengths[2]
1254 lsu.AddUint8(1) // standard_opcode_lengths[3]
1255 lsu.AddUint8(1) // standard_opcode_lengths[4]
1256 lsu.AddUint8(1) // standard_opcode_lengths[5]
1257 lsu.AddUint8(0) // standard_opcode_lengths[6]
1258 lsu.AddUint8(0) // standard_opcode_lengths[7]
1259 lsu.AddUint8(0) // standard_opcode_lengths[8]
1260 lsu.AddUint8(1) // standard_opcode_lengths[9]
1261 lsu.AddUint8(0) // standard_opcode_lengths[10]
1263 // Call helper to emit dir and file sections.
1264 d.writeDirFileTables(unit, lsu)
1266 // capture length at end of file names.
1267 headerend = lsu.Size()
1268 unitlen := lsu.Size() - unitstart
1270 // Output the state machine for each function remaining.
1271 for _, s := range unit.Textp {
1272 fnSym := loader.Sym(s)
1273 _, _, _, lines := d.ldr.GetFuncDwarfAuxSyms(fnSym)
1275 // Chain the line symbol onto the list.
1277 syms = append(syms, lines)
1278 unitlen += int64(len(d.ldr.Data(lines)))
1282 if d.linkctxt.HeadType == objabi.Haix {
1283 addDwsectCUSize(".debug_line", unit.Lib.Pkg, uint64(unitlen))
1286 if isDwarf64(d.linkctxt) {
1287 lsu.SetUint(d.arch, unitLengthOffset+4, uint64(unitlen)) // +4 because of 0xFFFFFFFF
1288 lsu.SetUint(d.arch, headerLengthOffset, uint64(headerend-headerstart))
1290 lsu.SetUint32(d.arch, unitLengthOffset, uint32(unitlen))
1291 lsu.SetUint32(d.arch, headerLengthOffset, uint32(headerend-headerstart))
1297 // writepcranges generates the DW_AT_ranges table for compilation unit
1298 // "unit", and returns a collection of ranges symbols (one for the
1299 // compilation unit DIE itself and the remainder from functions in the unit).
1300 func (d *dwctxt) writepcranges(unit *sym.CompilationUnit, base loader.Sym, pcs []dwarf.Range, rangeProlog loader.Sym) []loader.Sym {
1302 syms := make([]loader.Sym, 0, len(unit.RangeSyms)+1)
1303 syms = append(syms, rangeProlog)
1304 rsu := d.ldr.MakeSymbolUpdater(rangeProlog)
1305 rDwSym := dwSym(rangeProlog)
1307 // Create PC ranges for the compilation unit DIE.
1308 newattr(unit.DWInfo, dwarf.DW_AT_ranges, dwarf.DW_CLS_PTR, rsu.Size(), rDwSym)
1309 newattr(unit.DWInfo, dwarf.DW_AT_low_pc, dwarf.DW_CLS_ADDRESS, 0, dwSym(base))
1310 dwarf.PutBasedRanges(d, rDwSym, pcs)
1312 // Collect up the ranges for functions in the unit.
1313 rsize := uint64(rsu.Size())
1314 for _, ls := range unit.RangeSyms {
1316 syms = append(syms, s)
1317 rsize += uint64(d.ldr.SymSize(s))
1320 if d.linkctxt.HeadType == objabi.Haix {
1321 addDwsectCUSize(".debug_ranges", unit.Lib.Pkg, rsize)
1331 dataAlignmentFactor = -4
1334 // appendPCDeltaCFA appends per-PC CFA deltas to b and returns the final slice.
1335 func appendPCDeltaCFA(arch *sys.Arch, b []byte, deltapc, cfa int64) []byte {
1336 b = append(b, dwarf.DW_CFA_def_cfa_offset_sf)
1337 b = dwarf.AppendSleb128(b, cfa/dataAlignmentFactor)
1340 case deltapc < 0x40:
1341 b = append(b, uint8(dwarf.DW_CFA_advance_loc+deltapc))
1342 case deltapc < 0x100:
1343 b = append(b, dwarf.DW_CFA_advance_loc1)
1344 b = append(b, uint8(deltapc))
1345 case deltapc < 0x10000:
1346 b = append(b, dwarf.DW_CFA_advance_loc2, 0, 0)
1347 arch.ByteOrder.PutUint16(b[len(b)-2:], uint16(deltapc))
1349 b = append(b, dwarf.DW_CFA_advance_loc4, 0, 0, 0, 0)
1350 arch.ByteOrder.PutUint32(b[len(b)-4:], uint32(deltapc))
1355 func (d *dwctxt) writeframes(fs loader.Sym) dwarfSecInfo {
1357 fsu := d.ldr.MakeSymbolUpdater(fs)
1358 fsu.SetType(sym.SDWARFSECT)
1359 isdw64 := isDwarf64(d.linkctxt)
1360 haslr := d.linkctxt.Arch.HasLR
1362 // Length field is 4 bytes on Dwarf32 and 12 bytes on Dwarf64
1363 lengthFieldSize := int64(4)
1365 lengthFieldSize += 8
1368 // Emit the CIE, Section 6.4.1
1369 cieReserve := uint32(16)
1374 cieReserve += 4 // 4 bytes added for cid
1376 d.createUnitLength(fsu, uint64(cieReserve)) // initial length, must be multiple of thearch.ptrsize
1377 d.addDwarfAddrField(fsu, ^uint64(0)) // cid
1378 fsu.AddUint8(3) // dwarf version (appendix F)
1379 fsu.AddUint8(0) // augmentation ""
1380 dwarf.Uleb128put(d, fsd, 1) // code_alignment_factor
1381 dwarf.Sleb128put(d, fsd, dataAlignmentFactor) // all CFI offset calculations include multiplication with this factor
1382 dwarf.Uleb128put(d, fsd, int64(thearch.Dwarfreglr)) // return_address_register
1384 fsu.AddUint8(dwarf.DW_CFA_def_cfa) // Set the current frame address..
1385 dwarf.Uleb128put(d, fsd, int64(thearch.Dwarfregsp)) // ...to use the value in the platform's SP register (defined in l.go)...
1387 dwarf.Uleb128put(d, fsd, int64(0)) // ...plus a 0 offset.
1389 fsu.AddUint8(dwarf.DW_CFA_same_value) // The platform's link register is unchanged during the prologue.
1390 dwarf.Uleb128put(d, fsd, int64(thearch.Dwarfreglr))
1392 fsu.AddUint8(dwarf.DW_CFA_val_offset) // The previous value...
1393 dwarf.Uleb128put(d, fsd, int64(thearch.Dwarfregsp)) // ...of the platform's SP register...
1394 dwarf.Uleb128put(d, fsd, int64(0)) // ...is CFA+0.
1396 dwarf.Uleb128put(d, fsd, int64(d.arch.PtrSize)) // ...plus the word size (because the call instruction implicitly adds one word to the frame).
1398 fsu.AddUint8(dwarf.DW_CFA_offset_extended) // The previous value...
1399 dwarf.Uleb128put(d, fsd, int64(thearch.Dwarfreglr)) // ...of the return address...
1400 dwarf.Uleb128put(d, fsd, int64(-d.arch.PtrSize)/dataAlignmentFactor) // ...is saved at [CFA - (PtrSize/4)].
1403 pad := int64(cieReserve) + lengthFieldSize - int64(len(d.ldr.Data(fs)))
1406 Exitf("dwarf: cieReserve too small by %d bytes.", -pad)
1409 internalExec := d.linkctxt.BuildMode == BuildModeExe && d.linkctxt.IsInternal()
1410 addAddrPlus := loader.GenAddAddrPlusFunc(internalExec)
1412 fsu.AddBytes(zeros[:pad])
1415 pcsp := obj.NewPCIter(uint32(d.arch.MinLC))
1416 for _, s := range d.linkctxt.Textp {
1418 fi := d.ldr.FuncInfo(fn)
1422 fpcsp := d.ldr.Pcsp(s)
1424 // Emit a FDE, Section 6.4.1.
1425 // First build the section contents into a byte buffer.
1426 deltaBuf = deltaBuf[:0]
1427 if haslr && fi.TopFrame() {
1428 // Mark the link register as having an undefined value.
1429 // This stops call stack unwinders progressing any further.
1430 // TODO: similar mark on non-LR architectures.
1431 deltaBuf = append(deltaBuf, dwarf.DW_CFA_undefined)
1432 deltaBuf = dwarf.AppendUleb128(deltaBuf, uint64(thearch.Dwarfreglr))
1435 for pcsp.Init(d.linkctxt.loader.Data(fpcsp)); !pcsp.Done; pcsp.Next() {
1436 nextpc := pcsp.NextPC
1438 // pciterinit goes up to the end of the function,
1439 // but DWARF expects us to stop just before the end.
1440 if int64(nextpc) == int64(len(d.ldr.Data(fn))) {
1442 if nextpc < pcsp.PC {
1447 spdelta := int64(pcsp.Value)
1449 // Return address has been pushed onto stack.
1450 spdelta += int64(d.arch.PtrSize)
1453 if haslr && !fi.TopFrame() {
1454 // TODO(bryanpkc): This is imprecise. In general, the instruction
1455 // that stores the return address to the stack frame is not the
1456 // same one that allocates the frame.
1458 // The return address is preserved at (CFA-frame_size)
1459 // after a stack frame has been allocated.
1460 deltaBuf = append(deltaBuf, dwarf.DW_CFA_offset_extended_sf)
1461 deltaBuf = dwarf.AppendUleb128(deltaBuf, uint64(thearch.Dwarfreglr))
1462 deltaBuf = dwarf.AppendSleb128(deltaBuf, -spdelta/dataAlignmentFactor)
1464 // The return address is restored into the link register
1465 // when a stack frame has been de-allocated.
1466 deltaBuf = append(deltaBuf, dwarf.DW_CFA_same_value)
1467 deltaBuf = dwarf.AppendUleb128(deltaBuf, uint64(thearch.Dwarfreglr))
1471 deltaBuf = appendPCDeltaCFA(d.arch, deltaBuf, int64(nextpc)-int64(pcsp.PC), spdelta)
1473 pad := int(Rnd(int64(len(deltaBuf)), int64(d.arch.PtrSize))) - len(deltaBuf)
1474 deltaBuf = append(deltaBuf, zeros[:pad]...)
1476 // Emit the FDE header, Section 6.4.1.
1477 // 4 bytes: length, must be multiple of thearch.ptrsize
1478 // 4/8 bytes: Pointer to the CIE above, at offset 0
1479 // ptrsize: initial location
1480 // ptrsize: address range
1482 fdeLength := uint64(4 + 2*d.arch.PtrSize + len(deltaBuf))
1484 fdeLength += 4 // 4 bytes added for CIE pointer
1486 d.createUnitLength(fsu, fdeLength)
1488 if d.linkctxt.LinkMode == LinkExternal {
1489 d.addDwarfAddrRef(fsu, fs)
1491 d.addDwarfAddrField(fsu, 0) // CIE offset
1493 addAddrPlus(fsu, d.arch, s, 0)
1494 fsu.AddUintXX(d.arch, uint64(len(d.ldr.Data(fn))), d.arch.PtrSize) // address range
1495 fsu.AddBytes(deltaBuf)
1497 if d.linkctxt.HeadType == objabi.Haix {
1498 addDwsectCUSize(".debug_frame", d.ldr.SymPkg(fn), fdeLength+uint64(lengthFieldSize))
1502 return dwarfSecInfo{syms: []loader.Sym{fs}}
1506 * Walk DWarfDebugInfoEntries, and emit .debug_info
1510 COMPUNITHEADERSIZE = 4 + 2 + 4 + 1
1513 func (d *dwctxt) writeUnitInfo(u *sym.CompilationUnit, abbrevsym loader.Sym, infoEpilog loader.Sym) []loader.Sym {
1514 syms := []loader.Sym{}
1515 if len(u.Textp) == 0 && u.DWInfo.Child == nil && len(u.VarDIEs) == 0 {
1519 compunit := u.DWInfo
1520 s := d.dtolsym(compunit.Sym)
1521 su := d.ldr.MakeSymbolUpdater(s)
1523 // Write .debug_info Compilation Unit Header (sec 7.5.1)
1524 // Fields marked with (*) must be changed for 64-bit dwarf
1525 // This must match COMPUNITHEADERSIZE above.
1526 d.createUnitLength(su, 0) // unit_length (*), will be filled in later.
1527 su.AddUint16(d.arch, 4) // dwarf version (appendix F)
1529 // debug_abbrev_offset (*)
1530 d.addDwarfAddrRef(su, abbrevsym)
1532 su.AddUint8(uint8(d.arch.PtrSize)) // address_size
1535 dwarf.Uleb128put(d, ds, int64(compunit.Abbrev))
1536 dwarf.PutAttrs(d, ds, compunit.Abbrev, compunit.Attr)
1538 // This is an under-estimate; more will be needed for type DIEs.
1539 cu := make([]loader.Sym, 0, len(u.AbsFnDIEs)+len(u.FuncDIEs))
1541 cu = append(cu, u.AbsFnDIEs...)
1542 cu = append(cu, u.FuncDIEs...)
1544 cu = append(cu, loader.Sym(u.Consts))
1546 cu = append(cu, u.VarDIEs...)
1548 for _, child := range cu {
1549 cusize += int64(len(d.ldr.Data(child)))
1552 for die := compunit.Child; die != nil; die = die.Link {
1554 lastSymSz := int64(len(d.ldr.Data(cu[l-1])))
1555 cu = d.putdie(cu, die)
1556 if lastSymSz != int64(len(d.ldr.Data(cu[l-1]))) {
1557 // putdie will sometimes append directly to the last symbol of the list
1558 cusize = cusize - lastSymSz + int64(len(d.ldr.Data(cu[l-1])))
1560 for _, child := range cu[l:] {
1561 cusize += int64(len(d.ldr.Data(child)))
1565 culu := d.ldr.MakeSymbolUpdater(infoEpilog)
1566 culu.AddUint8(0) // closes compilation unit DIE
1567 cu = append(cu, infoEpilog)
1570 // Save size for AIX symbol table.
1571 if d.linkctxt.HeadType == objabi.Haix {
1572 addDwsectCUSize(".debug_info", d.getPkgFromCUSym(s), uint64(cusize))
1574 if isDwarf64(d.linkctxt) {
1575 cusize -= 12 // exclude the length field.
1576 su.SetUint(d.arch, 4, uint64(cusize)) // 4 because of 0XFFFFFFFF
1578 cusize -= 4 // exclude the length field.
1579 su.SetUint32(d.arch, 0, uint32(cusize))
1581 return append(syms, cu...)
1584 func (d *dwctxt) writegdbscript() dwarfSecInfo {
1585 // TODO (aix): make it available
1586 if d.linkctxt.HeadType == objabi.Haix {
1587 return dwarfSecInfo{}
1589 if d.linkctxt.LinkMode == LinkExternal && d.linkctxt.HeadType == objabi.Hwindows && d.linkctxt.BuildMode == BuildModeCArchive {
1590 // gcc on Windows places .debug_gdb_scripts in the wrong location, which
1591 // causes the program not to run. See https://golang.org/issue/20183
1592 // Non c-archives can avoid this issue via a linker script
1593 // (see fix near writeGDBLinkerScript).
1594 // c-archive users would need to specify the linker script manually.
1595 // For UX it's better not to deal with this.
1596 return dwarfSecInfo{}
1598 if gdbscript == "" {
1599 return dwarfSecInfo{}
1602 gs := d.ldr.CreateSymForUpdate(".debug_gdb_scripts", 0)
1603 gs.SetType(sym.SDWARFSECT)
1605 gs.AddUint8(GdbScriptPythonFileId)
1606 gs.Addstring(gdbscript)
1607 return dwarfSecInfo{syms: []loader.Sym{gs.Sym()}}
1610 // FIXME: might be worth looking replacing this map with a function
1611 // that switches based on symbol instead.
1613 var prototypedies map[string]*dwarf.DWDie
1615 func dwarfEnabled(ctxt *Link) bool {
1616 if *FlagW { // disable dwarf
1619 if ctxt.HeadType == objabi.Hplan9 || ctxt.HeadType == objabi.Hjs || ctxt.HeadType == objabi.Hwasip1 {
1623 if ctxt.LinkMode == LinkExternal {
1626 case ctxt.HeadType == objabi.Hdarwin:
1627 case ctxt.HeadType == objabi.Hwindows:
1628 case ctxt.HeadType == objabi.Haix:
1629 res, err := dwarf.IsDWARFEnabledOnAIXLd(ctxt.extld())
1642 // mkBuiltinType populates the dwctxt2 sym lookup maps for the
1643 // newly created builtin type DIE 'typeDie'.
1644 func (d *dwctxt) mkBuiltinType(ctxt *Link, abrv int, tname string) *dwarf.DWDie {
1646 die := d.newdie(&dwtypes, abrv, tname)
1648 // Look up type symbol.
1649 gotype := d.lookupOrDiag("type:" + tname)
1651 // Map from die sym to type sym
1652 ds := loader.Sym(die.Sym.(dwSym))
1653 d.rtmap[ds] = gotype
1655 // Map from type to def sym
1656 d.tdmap[gotype] = ds
1661 // dwarfVisitFunction takes a function (text) symbol and processes the
1662 // subprogram DIE for the function and picks up any other DIEs
1663 // (absfns, types) that it references.
1664 func (d *dwctxt) dwarfVisitFunction(fnSym loader.Sym, unit *sym.CompilationUnit) {
1665 // The DWARF subprogram DIE symbol is listed as an aux sym
1666 // of the text (fcn) symbol, so ask the loader to retrieve it,
1667 // as well as the associated range symbol.
1668 infosym, _, rangesym, _ := d.ldr.GetFuncDwarfAuxSyms(fnSym)
1672 d.ldr.SetAttrNotInSymbolTable(infosym, true)
1673 d.ldr.SetAttrReachable(infosym, true)
1674 unit.FuncDIEs = append(unit.FuncDIEs, sym.LoaderSym(infosym))
1676 d.ldr.SetAttrNotInSymbolTable(rangesym, true)
1677 d.ldr.SetAttrReachable(rangesym, true)
1678 unit.RangeSyms = append(unit.RangeSyms, sym.LoaderSym(rangesym))
1681 // Walk the relocations of the subprogram DIE symbol to discover
1682 // references to abstract function DIEs, Go type DIES, and
1683 // (via R_USETYPE relocs) types that were originally assigned to
1684 // locals/params but were optimized away.
1685 drelocs := d.ldr.Relocs(infosym)
1686 for ri := 0; ri < drelocs.Count(); ri++ {
1688 // Look for "use type" relocs.
1689 if r.Type() == objabi.R_USETYPE {
1690 d.defgotype(r.Sym())
1693 if r.Type() != objabi.R_DWARFSECREF {
1698 rst := d.ldr.SymType(rsym)
1700 // Look for abstract function references.
1701 if rst == sym.SDWARFABSFCN {
1702 if !d.ldr.AttrOnList(rsym) {
1703 // abstract function
1704 d.ldr.SetAttrOnList(rsym, true)
1705 unit.AbsFnDIEs = append(unit.AbsFnDIEs, sym.LoaderSym(rsym))
1706 d.importInfoSymbol(rsym)
1711 // Look for type references.
1712 if rst != sym.SDWARFTYPE && rst != sym.Sxxx {
1715 if _, ok := d.rtmap[rsym]; ok {
1716 // type already generated
1720 rsn := d.ldr.SymName(rsym)
1721 tn := rsn[len(dwarf.InfoPrefix):]
1722 ts := d.ldr.Lookup("type:"+tn, 0)
1727 // dwarfGenerateDebugInfo generated debug info entries for all types,
1728 // variables and functions in the program.
1729 // Along with dwarfGenerateDebugSyms they are the two main entry points into
1730 // dwarf generation: dwarfGenerateDebugInfo does all the work that should be
1731 // done before symbol names are mangled while dwarfGenerateDebugSyms does
1732 // all the work that can only be done after addresses have been assigned to
1734 func dwarfGenerateDebugInfo(ctxt *Link) {
1735 if !dwarfEnabled(ctxt) {
1743 tmap: make(map[string]loader.Sym),
1744 tdmap: make(map[loader.Sym]loader.Sym),
1745 rtmap: make(map[loader.Sym]loader.Sym),
1747 d.typeRuntimeEface = d.lookupOrDiag("type:runtime.eface")
1748 d.typeRuntimeIface = d.lookupOrDiag("type:runtime.iface")
1750 if ctxt.HeadType == objabi.Haix {
1751 // Initial map used to store package size for each DWARF section.
1752 dwsectCUSize = make(map[string]uint64)
1755 // For ctxt.Diagnostic messages.
1756 newattr(&dwtypes, dwarf.DW_AT_name, dwarf.DW_CLS_STRING, int64(len("dwtypes")), "dwtypes")
1758 // Unspecified type. There are no references to this in the symbol table.
1759 d.newdie(&dwtypes, dwarf.DW_ABRV_NULLTYPE, "<unspecified>")
1761 // Some types that must exist to define other ones (uintptr in particular
1762 // is needed for array size)
1763 d.mkBuiltinType(ctxt, dwarf.DW_ABRV_BARE_PTRTYPE, "unsafe.Pointer")
1764 die := d.mkBuiltinType(ctxt, dwarf.DW_ABRV_BASETYPE, "uintptr")
1765 newattr(die, dwarf.DW_AT_encoding, dwarf.DW_CLS_CONSTANT, dwarf.DW_ATE_unsigned, 0)
1766 newattr(die, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, int64(d.arch.PtrSize), 0)
1767 newattr(die, dwarf.DW_AT_go_kind, dwarf.DW_CLS_CONSTANT, objabi.KindUintptr, 0)
1768 newattr(die, dwarf.DW_AT_go_runtime_type, dwarf.DW_CLS_ADDRESS, 0, dwSym(d.lookupOrDiag("type:uintptr")))
1770 d.uintptrInfoSym = d.mustFind("uintptr")
1772 // Prototypes needed for type synthesis.
1773 prototypedies = map[string]*dwarf.DWDie{
1774 "type:runtime.stringStructDWARF": nil,
1775 "type:runtime.slice": nil,
1776 "type:runtime.hmap": nil,
1777 "type:runtime.bmap": nil,
1778 "type:runtime.sudog": nil,
1779 "type:runtime.waitq": nil,
1780 "type:runtime.hchan": nil,
1783 // Needed by the prettyprinter code for interface inspection.
1784 for _, typ := range []string{
1785 "type:internal/abi.Type",
1786 "type:internal/abi.ArrayType",
1787 "type:internal/abi.ChanType",
1788 "type:internal/abi.FuncType",
1789 "type:internal/abi.MapType",
1790 "type:internal/abi.PtrType",
1791 "type:internal/abi.SliceType",
1792 "type:internal/abi.StructType",
1793 "type:internal/abi.InterfaceType",
1794 "type:runtime.itab",
1795 "type:internal/abi.Imethod"} {
1796 d.defgotype(d.lookupOrDiag(typ))
1799 // fake root DIE for compile unit DIEs
1800 var dwroot dwarf.DWDie
1801 flagVariants := make(map[string]bool)
1803 for _, lib := range ctxt.Library {
1805 consts := d.ldr.Lookup(dwarf.ConstInfoPrefix+lib.Pkg, 0)
1806 for _, unit := range lib.Units {
1807 // We drop the constants into the first CU.
1809 unit.Consts = sym.LoaderSym(consts)
1810 d.importInfoSymbol(consts)
1813 ctxt.compUnits = append(ctxt.compUnits, unit)
1815 // We need at least one runtime unit.
1816 if unit.Lib.Pkg == "runtime" {
1817 ctxt.runtimeCU = unit
1820 cuabrv := dwarf.DW_ABRV_COMPUNIT
1821 if len(unit.Textp) == 0 {
1822 cuabrv = dwarf.DW_ABRV_COMPUNIT_TEXTLESS
1824 unit.DWInfo = d.newdie(&dwroot, cuabrv, unit.Lib.Pkg)
1825 newattr(unit.DWInfo, dwarf.DW_AT_language, dwarf.DW_CLS_CONSTANT, int64(dwarf.DW_LANG_Go), 0)
1826 // OS X linker requires compilation dir or absolute path in comp unit name to output debug info.
1827 compDir := getCompilationDir()
1828 // TODO: Make this be the actual compilation directory, not
1829 // the linker directory. If we move CU construction into the
1830 // compiler, this should happen naturally.
1831 newattr(unit.DWInfo, dwarf.DW_AT_comp_dir, dwarf.DW_CLS_STRING, int64(len(compDir)), compDir)
1834 if producerExtra := d.ldr.Lookup(dwarf.CUInfoPrefix+"producer."+unit.Lib.Pkg, 0); producerExtra != 0 {
1835 peData = d.ldr.Data(producerExtra)
1837 producer := "Go cmd/compile " + buildcfg.Version
1838 if len(peData) > 0 {
1839 // We put a semicolon before the flags to clearly
1840 // separate them from the version, which can be long
1841 // and have lots of weird things in it in development
1842 // versions. We promise not to put a semicolon in the
1843 // version, so it should be safe for readers to scan
1844 // forward to the semicolon.
1845 producer += "; " + string(peData)
1846 flagVariants[string(peData)] = true
1848 flagVariants[""] = true
1851 newattr(unit.DWInfo, dwarf.DW_AT_producer, dwarf.DW_CLS_STRING, int64(len(producer)), producer)
1854 if pnSymIdx := d.ldr.Lookup(dwarf.CUInfoPrefix+"packagename."+unit.Lib.Pkg, 0); pnSymIdx != 0 {
1855 pnsData := d.ldr.Data(pnSymIdx)
1856 pkgname = string(pnsData)
1858 newattr(unit.DWInfo, dwarf.DW_AT_go_package_name, dwarf.DW_CLS_STRING, int64(len(pkgname)), pkgname)
1860 // Scan all functions in this compilation unit, create
1861 // DIEs for all referenced types, find all referenced
1862 // abstract functions, visit range symbols. Note that
1863 // Textp has been dead-code-eliminated already.
1864 for _, s := range unit.Textp {
1865 d.dwarfVisitFunction(loader.Sym(s), unit)
1870 // Fix for 31034: if the objects feeding into this link were compiled
1871 // with different sets of flags, then don't issue an error if
1872 // the -strictdups checks fail.
1873 if checkStrictDups > 1 && len(flagVariants) > 1 {
1877 // Make a pass through all data symbols, looking for those
1878 // corresponding to reachable, Go-generated, user-visible
1879 // global variables. For each global of this sort, locate
1880 // the corresponding compiler-generated DIE symbol and tack
1881 // it onto the list associated with the unit.
1882 // Also looks for dictionary symbols and generates DIE symbols for each
1883 // type they reference.
1884 for idx := loader.Sym(1); idx < loader.Sym(d.ldr.NDef()); idx++ {
1885 if !d.ldr.AttrReachable(idx) ||
1886 d.ldr.AttrNotInSymbolTable(idx) ||
1887 d.ldr.SymVersion(idx) >= sym.SymVerStatic {
1890 t := d.ldr.SymType(idx)
1892 case sym.SRODATA, sym.SDATA, sym.SNOPTRDATA, sym.STYPE, sym.SBSS, sym.SNOPTRBSS, sym.STLSBSS:
1897 // Skip things with no type, unless it's a dictionary
1898 gt := d.ldr.SymGoType(idx)
1900 if t == sym.SRODATA {
1901 if d.ldr.IsDict(idx) {
1902 // This is a dictionary, make sure that all types referenced by this dictionary are reachable
1903 relocs := d.ldr.Relocs(idx)
1904 for i := 0; i < relocs.Count(); i++ {
1905 reloc := relocs.At(i)
1906 if reloc.Type() == objabi.R_USEIFACE {
1907 d.defgotype(reloc.Sym())
1914 // Skip file local symbols (this includes static tmps, stack
1915 // object symbols, and local symbols in assembler src files).
1916 if d.ldr.IsFileLocal(idx) {
1920 // Find compiler-generated DWARF info sym for global in question,
1921 // and tack it onto the appropriate unit. Note that there are
1922 // circumstances under which we can't find the compiler-generated
1923 // symbol-- this typically happens as a result of compiler options
1924 // (e.g. compile package X with "-dwarf=0").
1925 varDIE := d.ldr.GetVarDwarfAuxSym(idx)
1927 unit := d.ldr.SymUnit(idx)
1929 unit.VarDIEs = append(unit.VarDIEs, sym.LoaderSym(varDIE))
1933 d.synthesizestringtypes(ctxt, dwtypes.Child)
1934 d.synthesizeslicetypes(ctxt, dwtypes.Child)
1935 d.synthesizemaptypes(ctxt, dwtypes.Child)
1936 d.synthesizechantypes(ctxt, dwtypes.Child)
1939 // dwarfGenerateDebugSyms constructs debug_line, debug_frame, and
1940 // debug_loc. It also writes out the debug_info section using symbols
1941 // generated in dwarfGenerateDebugInfo2.
1942 func dwarfGenerateDebugSyms(ctxt *Link) {
1943 if !dwarfEnabled(ctxt) {
1950 dwmu: new(sync.Mutex),
1952 d.dwarfGenerateDebugSyms()
1955 // dwUnitSyms stores input and output symbols for DWARF generation
1956 // for a given compilation unit.
1957 type dwUnitSyms struct {
1958 // Inputs for a given unit.
1959 lineProlog loader.Sym
1960 rangeProlog loader.Sym
1961 infoEpilog loader.Sym
1963 // Outputs for a given unit.
1964 linesyms []loader.Sym
1965 infosyms []loader.Sym
1966 locsyms []loader.Sym
1967 rangessyms []loader.Sym
1970 // dwUnitPortion assembles the DWARF content for a given compilation
1971 // unit: debug_info, debug_lines, debug_ranges, debug_loc (debug_frame
1972 // is handled elsewhere). Order is important; the calls to writelines
1973 // and writepcranges below make updates to the compilation unit DIE,
1974 // hence they have to happen before the call to writeUnitInfo.
1975 func (d *dwctxt) dwUnitPortion(u *sym.CompilationUnit, abbrevsym loader.Sym, us *dwUnitSyms) {
1976 if u.DWInfo.Abbrev != dwarf.DW_ABRV_COMPUNIT_TEXTLESS {
1977 us.linesyms = d.writelines(u, us.lineProlog)
1978 base := loader.Sym(u.Textp[0])
1979 us.rangessyms = d.writepcranges(u, base, u.PCs, us.rangeProlog)
1980 us.locsyms = d.collectUnitLocs(u)
1982 us.infosyms = d.writeUnitInfo(u, abbrevsym, us.infoEpilog)
1985 func (d *dwctxt) dwarfGenerateDebugSyms() {
1986 abbrevSec := d.writeabbrev()
1987 dwarfp = append(dwarfp, abbrevSec)
1988 d.calcCompUnitRanges()
1989 sort.Sort(compilationUnitByStartPC(d.linkctxt.compUnits))
1991 // newdie adds DIEs to the *beginning* of the parent's DIE list.
1992 // Now that we're done creating DIEs, reverse the trees so DIEs
1993 // appear in the order they were created.
1994 for _, u := range d.linkctxt.compUnits {
1995 reversetree(&u.DWInfo.Child)
1997 reversetree(&dwtypes.Child)
1998 movetomodule(d.linkctxt, &dwtypes)
2000 mkSecSym := func(name string) loader.Sym {
2001 s := d.ldr.CreateSymForUpdate(name, 0)
2002 s.SetType(sym.SDWARFSECT)
2003 s.SetReachable(true)
2006 mkAnonSym := func(kind sym.SymKind) loader.Sym {
2007 s := d.ldr.MakeSymbolUpdater(d.ldr.CreateExtSym("", 0))
2009 s.SetReachable(true)
2013 // Create the section symbols.
2014 frameSym := mkSecSym(".debug_frame")
2015 locSym := mkSecSym(".debug_loc")
2016 lineSym := mkSecSym(".debug_line")
2017 rangesSym := mkSecSym(".debug_ranges")
2018 infoSym := mkSecSym(".debug_info")
2020 // Create the section objects
2021 lineSec := dwarfSecInfo{syms: []loader.Sym{lineSym}}
2022 locSec := dwarfSecInfo{syms: []loader.Sym{locSym}}
2023 rangesSec := dwarfSecInfo{syms: []loader.Sym{rangesSym}}
2024 frameSec := dwarfSecInfo{syms: []loader.Sym{frameSym}}
2025 infoSec := dwarfSecInfo{syms: []loader.Sym{infoSym}}
2027 // Create any new symbols that will be needed during the
2028 // parallel portion below.
2029 ncu := len(d.linkctxt.compUnits)
2030 unitSyms := make([]dwUnitSyms, ncu)
2031 for i := 0; i < ncu; i++ {
2033 us.lineProlog = mkAnonSym(sym.SDWARFLINES)
2034 us.rangeProlog = mkAnonSym(sym.SDWARFRANGE)
2035 us.infoEpilog = mkAnonSym(sym.SDWARFFCN)
2038 var wg sync.WaitGroup
2039 sema := make(chan struct{}, runtime.GOMAXPROCS(0))
2041 // Kick off generation of .debug_frame, since it doesn't have
2042 // any entanglements and can be started right away.
2050 frameSec = d.writeframes(frameSym)
2053 // Create a goroutine per comp unit to handle the generation that
2054 // unit's portion of .debug_line, .debug_loc, .debug_ranges, and
2056 wg.Add(len(d.linkctxt.compUnits))
2057 for i := 0; i < ncu; i++ {
2058 go func(u *sym.CompilationUnit, us *dwUnitSyms) {
2064 d.dwUnitPortion(u, abbrevSec.secSym(), us)
2065 }(d.linkctxt.compUnits[i], &unitSyms[i])
2069 markReachable := func(syms []loader.Sym) []loader.Sym {
2070 for _, s := range syms {
2071 d.ldr.SetAttrNotInSymbolTable(s, true)
2072 d.ldr.SetAttrReachable(s, true)
2077 // Stitch together the results.
2078 for i := 0; i < ncu; i++ {
2080 lineSec.syms = append(lineSec.syms, markReachable(r.linesyms)...)
2081 infoSec.syms = append(infoSec.syms, markReachable(r.infosyms)...)
2082 locSec.syms = append(locSec.syms, markReachable(r.locsyms)...)
2083 rangesSec.syms = append(rangesSec.syms, markReachable(r.rangessyms)...)
2085 dwarfp = append(dwarfp, lineSec)
2086 dwarfp = append(dwarfp, frameSec)
2087 gdbScriptSec := d.writegdbscript()
2088 if gdbScriptSec.secSym() != 0 {
2089 dwarfp = append(dwarfp, gdbScriptSec)
2091 dwarfp = append(dwarfp, infoSec)
2092 if len(locSec.syms) > 1 {
2093 dwarfp = append(dwarfp, locSec)
2095 dwarfp = append(dwarfp, rangesSec)
2097 // Check to make sure we haven't listed any symbols more than once
2098 // in the info section. This used to be done by setting and
2099 // checking the OnList attribute in "putdie", but that strategy
2100 // was not friendly for concurrency.
2101 seen := loader.MakeBitmap(d.ldr.NSym())
2102 for _, s := range infoSec.syms {
2104 log.Fatalf("symbol %s listed multiple times", d.ldr.SymName(s))
2110 func (d *dwctxt) collectUnitLocs(u *sym.CompilationUnit) []loader.Sym {
2111 syms := []loader.Sym{}
2112 for _, fn := range u.FuncDIEs {
2113 relocs := d.ldr.Relocs(loader.Sym(fn))
2114 for i := 0; i < relocs.Count(); i++ {
2115 reloc := relocs.At(i)
2116 if reloc.Type() != objabi.R_DWARFSECREF {
2120 if d.ldr.SymType(rsym) == sym.SDWARFLOC {
2121 syms = append(syms, rsym)
2122 // One location list entry per function, but many relocations to it. Don't duplicate.
2130 // Add DWARF section names to the section header string table, by calling add
2131 // on each name. ELF only.
2132 func dwarfaddshstrings(ctxt *Link, add func(string)) {
2133 if *FlagW { // disable dwarf
2137 secs := []string{"abbrev", "frame", "info", "loc", "line", "gdb_scripts", "ranges"}
2138 for _, sec := range secs {
2139 add(".debug_" + sec)
2140 if ctxt.IsExternal() {
2141 add(elfRelType + ".debug_" + sec)
2146 func dwarfaddelfsectionsyms(ctxt *Link) {
2147 if *FlagW { // disable dwarf
2150 if ctxt.LinkMode != LinkExternal {
2155 for _, si := range dwarfp {
2157 sect := ldr.SymSect(si.secSym())
2158 putelfsectionsym(ctxt, ctxt.Out, s, sect.Elfsect.(*ElfShdr).shnum)
2162 // dwarfcompress compresses the DWARF sections. Relocations are applied
2163 // on the fly. After this, dwarfp will contain a different (new) set of
2164 // symbols, and sections may have been replaced.
2165 func dwarfcompress(ctxt *Link) {
2166 // compressedSect is a helper type for parallelizing compression.
2167 type compressedSect struct {
2173 supported := ctxt.IsELF || ctxt.IsWindows() || ctxt.IsDarwin()
2174 if !ctxt.compressDWARF || !supported || ctxt.IsExternal() {
2178 var compressedCount int
2179 resChannel := make(chan compressedSect)
2180 for i := range dwarfp {
2181 go func(resIndex int, syms []loader.Sym) {
2182 resChannel <- compressedSect{resIndex, compressSyms(ctxt, syms), syms}
2183 }(compressedCount, dwarfp[i].syms)
2186 res := make([]compressedSect, compressedCount)
2187 for ; compressedCount > 0; compressedCount-- {
2193 var newDwarfp []dwarfSecInfo
2194 Segdwarf.Sections = Segdwarf.Sections[:0]
2195 for _, z := range res {
2197 if z.compressed == nil {
2198 // Compression didn't help.
2199 ds := dwarfSecInfo{syms: z.syms}
2200 newDwarfp = append(newDwarfp, ds)
2201 Segdwarf.Sections = append(Segdwarf.Sections, ldr.SymSect(s))
2203 var compressedSegName string
2205 compressedSegName = ldr.SymSect(s).Name
2207 compressedSegName = ".zdebug_" + ldr.SymSect(s).Name[len(".debug_"):]
2209 sect := addsection(ctxt.loader, ctxt.Arch, &Segdwarf, compressedSegName, 04)
2210 sect.Align = int32(ctxt.Arch.Alignment)
2211 sect.Length = uint64(len(z.compressed))
2212 sect.Compressed = true
2213 newSym := ldr.MakeSymbolBuilder(compressedSegName)
2214 ldr.SetAttrReachable(s, true)
2215 newSym.SetData(z.compressed)
2216 newSym.SetSize(int64(len(z.compressed)))
2217 ldr.SetSymSect(newSym.Sym(), sect)
2218 ds := dwarfSecInfo{syms: []loader.Sym{newSym.Sym()}}
2219 newDwarfp = append(newDwarfp, ds)
2221 // compressed symbols are no longer needed.
2222 for _, s := range z.syms {
2223 ldr.SetAttrReachable(s, false)
2230 // Re-compute the locations of the compressed DWARF symbols
2231 // and sections, since the layout of these within the file is
2232 // based on Section.Vaddr and Symbol.Value.
2233 pos := Segdwarf.Vaddr
2234 var prevSect *sym.Section
2235 for _, si := range dwarfp {
2236 for _, s := range si.syms {
2237 ldr.SetSymValue(s, int64(pos))
2238 sect := ldr.SymSect(s)
2239 if sect != prevSect {
2240 sect.Vaddr = uint64(pos)
2243 if ldr.SubSym(s) != 0 {
2244 log.Fatalf("%s: unexpected sub-symbols", ldr.SymName(s))
2246 pos += uint64(ldr.SymSize(s))
2247 if ctxt.IsWindows() {
2248 pos = uint64(Rnd(int64(pos), PEFILEALIGN))
2252 Segdwarf.Length = pos - Segdwarf.Vaddr
2255 type compilationUnitByStartPC []*sym.CompilationUnit
2257 func (v compilationUnitByStartPC) Len() int { return len(v) }
2258 func (v compilationUnitByStartPC) Swap(i, j int) { v[i], v[j] = v[j], v[i] }
2260 func (v compilationUnitByStartPC) Less(i, j int) bool {
2262 case len(v[i].Textp) == 0 && len(v[j].Textp) == 0:
2263 return v[i].Lib.Pkg < v[j].Lib.Pkg
2264 case len(v[i].Textp) != 0 && len(v[j].Textp) == 0:
2266 case len(v[i].Textp) == 0 && len(v[j].Textp) != 0:
2269 return v[i].PCs[0].Start < v[j].PCs[0].Start
2273 // getPkgFromCUSym returns the package name for the compilation unit
2274 // represented by s.
2275 // The prefix dwarf.InfoPrefix+".pkg." needs to be removed in order to get
2276 // the package name.
2277 func (d *dwctxt) getPkgFromCUSym(s loader.Sym) string {
2278 return strings.TrimPrefix(d.ldr.SymName(s), dwarf.InfoPrefix+".pkg.")
2281 // On AIX, the symbol table needs to know where are the compilation units parts
2282 // for a specific package in each .dw section.
2283 // dwsectCUSize map will save the size of a compilation unit for
2284 // the corresponding .dw section.
2285 // This size can later be retrieved with the index "sectionName.pkgName".
2286 var dwsectCUSizeMu sync.Mutex
2287 var dwsectCUSize map[string]uint64
2289 // getDwsectCUSize retrieves the corresponding package size inside the current section.
2290 func getDwsectCUSize(sname string, pkgname string) uint64 {
2291 return dwsectCUSize[sname+"."+pkgname]
2294 func addDwsectCUSize(sname string, pkgname string, size uint64) {
2295 dwsectCUSizeMu.Lock()
2296 defer dwsectCUSizeMu.Unlock()
2297 dwsectCUSize[sname+"."+pkgname] += size