]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/link/internal/ld/dwarf.go
cmd/link/internal/ld: use strings.TrimPrefix in expandFile
[gostls13.git] / src / cmd / link / internal / ld / dwarf.go
1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // TODO/NICETOHAVE:
6 //   - eliminate DW_CLS_ if not used
7 //   - package info in compilation units
8 //   - assign types to their packages
9 //   - gdb uses c syntax, meaning clumsy quoting is needed for go identifiers. eg
10 //     ptype struct '[]uint8' and qualifiers need to be quoted away
11 //   - file:line info for variables
12 //   - make strings a typedef so prettyprinters can see the underlying string type
13
14 package ld
15
16 import (
17         "cmd/internal/dwarf"
18         "cmd/internal/obj"
19         "cmd/internal/objabi"
20         "cmd/internal/src"
21         "cmd/internal/sys"
22         "cmd/link/internal/loader"
23         "cmd/link/internal/sym"
24         "fmt"
25         "internal/abi"
26         "internal/buildcfg"
27         "log"
28         "path"
29         "runtime"
30         "sort"
31         "strings"
32         "sync"
33 )
34
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).
41 type dwctxt struct {
42         linkctxt *Link
43         ldr      *loader.Loader
44         arch     *sys.Arch
45
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
49
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
52         // ("type:uintptr").
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
56
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
60
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
65
66         // Used at various points in that parallel portion of DWARF gen to
67         // protect against conflicting updates to globals (such as "gdbscript")
68         dwmu *sync.Mutex
69 }
70
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.
74 type dwSym loader.Sym
75
76 func (c dwctxt) PtrSize() int {
77         return c.arch.PtrSize
78 }
79
80 func (c dwctxt) Size(s dwarf.Sym) int64 {
81         return int64(len(c.ldr.Data(loader.Sym(s.(dwSym)))))
82 }
83
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)
88 }
89
90 func (c dwctxt) AddBytes(s dwarf.Sym, b []byte) {
91         ds := loader.Sym(s.(dwSym))
92         dsu := c.ldr.MakeSymbolUpdater(ds)
93         dsu.AddBytes(b)
94 }
95
96 func (c dwctxt) AddString(s dwarf.Sym, v string) {
97         ds := loader.Sym(s.(dwSym))
98         dsu := c.ldr.MakeSymbolUpdater(ds)
99         dsu.Addstring(v)
100 }
101
102 func (c dwctxt) AddAddress(s dwarf.Sym, data interface{}, value int64) {
103         ds := loader.Sym(s.(dwSym))
104         dsu := c.ldr.MakeSymbolUpdater(ds)
105         if value != 0 {
106                 value -= dsu.Value()
107         }
108         tgtds := loader.Sym(data.(dwSym))
109         dsu.AddAddrPlus(c.arch, tgtds, value)
110 }
111
112 func (c dwctxt) AddCURelativeAddress(s dwarf.Sym, data interface{}, value int64) {
113         ds := loader.Sym(s.(dwSym))
114         dsu := c.ldr.MakeSymbolUpdater(ds)
115         if value != 0 {
116                 value -= dsu.Value()
117         }
118         tgtds := loader.Sym(data.(dwSym))
119         dsu.AddCURelativeAddrPlus(c.arch, tgtds, value)
120 }
121
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))
126         switch size {
127         default:
128                 c.linkctxt.Errorf(ds, "invalid size %d in adddwarfref\n", size)
129         case c.arch.PtrSize, 4:
130         }
131         dsu.AddSymRef(c.arch, tds, ofs, objabi.R_ADDROFF, size)
132 }
133
134 func (c dwctxt) AddDWARFAddrSectionOffset(s dwarf.Sym, t interface{}, ofs int64) {
135         size := 4
136         if isDwarf64(c.linkctxt) {
137                 size = 8
138         }
139         ds := loader.Sym(s.(dwSym))
140         dsu := c.ldr.MakeSymbolUpdater(ds)
141         tds := loader.Sym(t.(dwSym))
142         switch size {
143         default:
144                 c.linkctxt.Errorf(ds, "invalid size %d in adddwarfref\n", size)
145         case c.arch.PtrSize, 4:
146         }
147         dsu.AddSymRef(c.arch, tds, ofs, objabi.R_DWARFSECREF, size)
148 }
149
150 func (c dwctxt) Logf(format string, args ...interface{}) {
151         c.linkctxt.Logf(format, args...)
152 }
153
154 // At the moment these interfaces are only used in the compiler.
155
156 func (c dwctxt) CurrentOffset(s dwarf.Sym) int64 {
157         panic("should be used only in the compiler")
158 }
159
160 func (c dwctxt) RecordDclReference(s dwarf.Sym, t dwarf.Sym, dclIdx int, inlIndex int) {
161         panic("should be used only in the compiler")
162 }
163
164 func (c dwctxt) RecordChildDieOffsets(s dwarf.Sym, vars []*dwarf.Var, offsets []int32) {
165         panic("should be used only in the compiler")
166 }
167
168 func isDwarf64(ctxt *Link) bool {
169         return ctxt.HeadType == objabi.Haix
170 }
171
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:
175 const (
176         GdbScriptPythonFileId = 1
177         GdbScriptSchemeFileId = 3
178         GdbScriptPythonTextId = 4
179         GdbScriptSchemeTextId = 6
180 )
181
182 var gdbscript string
183
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 {
195         syms []loader.Sym
196 }
197
198 // secSym returns the section symbol for the section.
199 func (dsi *dwarfSecInfo) secSym() loader.Sym {
200         if len(dsi.syms) == 0 {
201                 return 0
202         }
203         return dsi.syms[0]
204 }
205
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{}
210         }
211         return dsi.syms[1:]
212 }
213
214 // dwarfp stores the collected DWARF symbols created during
215 // dwarf generation.
216 var dwarfp []dwarfSecInfo
217
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()}}
223 }
224
225 var dwtypes dwarf.DWDie
226
227 // newattr attaches a new attribute to the specified DIE.
228 //
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)
236         a.Link = die.Attr
237         die.Attr = a
238         a.Atr = attr
239         a.Cls = uint8(cls)
240         a.Value = value
241         a.Data = data
242 }
243
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 {
249                 return die.Attr
250         }
251
252         a := die.Attr
253         b := a.Link
254         for b != nil {
255                 if b.Atr == attr {
256                         a.Link = b.Link
257                         b.Link = die.Attr
258                         die.Attr = b
259                         return b
260                 }
261
262                 a = b
263                 b = b.Link
264         }
265
266         return nil
267 }
268
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
272 // instance).
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)
276         die.Abbrev = abbrev
277         die.Link = parent.Child
278         parent.Child = die
279
280         newattr(die, dwarf.DW_AT_name, dwarf.DW_CLS_STRING, int64(len(name)), name)
281
282         // Sanity check: all DIEs created in the linker should be named.
283         if name == "" {
284                 panic("nameless DWARF DIE")
285         }
286
287         var st sym.SymKind
288         switch abbrev {
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.
292                 return die
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:
298                 st = sym.SDWARFVAR
299         default:
300                 // Everything else is assigned a type of SDWARFTYPE. that
301                 // this also includes loose ends such as STRUCT_FIELD.
302                 st = sym.SDWARFTYPE
303         }
304         ds := d.ldr.LookupOrCreateSym(dwarf.InfoPrefix+name, 0)
305         dsu := d.ldr.MakeSymbolUpdater(ds)
306         dsu.SetType(st)
307         d.ldr.SetAttrNotInSymbolTable(ds, true)
308         d.ldr.SetAttrReachable(ds, true)
309         die.Sym = dwSym(ds)
310         if abbrev >= dwarf.DW_ABRV_NULLTYPE && abbrev <= dwarf.DW_ABRV_TYPEDECL {
311                 d.tmap[name] = ds
312         }
313
314         return die
315 }
316
317 func walktypedef(die *dwarf.DWDie) *dwarf.DWDie {
318         if die == nil {
319                 return nil
320         }
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)
326                         }
327                 }
328         }
329
330         return die
331 }
332
333 func (d *dwctxt) walksymtypedef(symIdx loader.Sym) loader.Sym {
334
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.
339
340         if ts, ok := d.rtmap[symIdx]; ok {
341                 if def, ok := d.tdmap[ts]; ok {
342                         return def
343                 }
344                 d.linkctxt.Errorf(ts, "internal error: no entry for sym %d in tdmap\n", ts)
345                 return 0
346         }
347         d.linkctxt.Errorf(symIdx, "internal error: no entry for sym %d in rtmap\n", symIdx)
348         return 0
349 }
350
351 // Find child by AT_name using hashtable if available or linear scan
352 // if not.
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 {
358                                 return a
359                         }
360                 }
361                 continue
362         }
363         return nil
364 }
365
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 {
369         return d.tmap[name]
370 }
371
372 func (d *dwctxt) mustFind(name string) loader.Sym {
373         r := d.find(name)
374         if r == 0 {
375                 Exitf("dwarf find: cannot find %s", name)
376         }
377         return r
378 }
379
380 func (d *dwctxt) adddwarfref(sb *loader.SymbolBuilder, t loader.Sym, size int) {
381         switch size {
382         default:
383                 d.linkctxt.Errorf(sb.Sym(), "invalid size %d in adddwarfref\n", size)
384         case d.arch.PtrSize, 4:
385         }
386         sb.AddSymRef(d.arch, t, 0, objabi.R_DWARFSECREF, size)
387 }
388
389 func (d *dwctxt) newrefattr(die *dwarf.DWDie, attr uint16, ref loader.Sym) {
390         if ref == 0 {
391                 return
392         }
393         newattr(die, attr, dwarf.DW_CLS_REFERENCE, 0, dwSym(ref))
394 }
395
396 func (d *dwctxt) dtolsym(s dwarf.Sym) loader.Sym {
397         if s == nil {
398                 return 0
399         }
400         dws := loader.Sym(s.(dwSym))
401         return dws
402 }
403
404 func (d *dwctxt) putdie(syms []loader.Sym, die *dwarf.DWDie) []loader.Sym {
405         s := d.dtolsym(die.Sym)
406         if s == 0 {
407                 s = syms[len(syms)-1]
408         } else {
409                 syms = append(syms, s)
410         }
411         sDwsym := dwSym(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)
417                 }
418                 dsu := d.ldr.MakeSymbolUpdater(syms[len(syms)-1])
419                 dsu.AddUint8(0)
420         }
421         return syms
422 }
423
424 func reverselist(list **dwarf.DWDie) {
425         curr := *list
426         var prev *dwarf.DWDie
427         for curr != nil {
428                 next := curr.Link
429                 curr.Link = prev
430                 prev = curr
431                 curr = next
432         }
433
434         *list = prev
435 }
436
437 func reversetree(list **dwarf.DWDie) {
438         reverselist(list)
439         for die := *list; die != nil; die = die.Link {
440                 if dwarf.HasChildren(die) {
441                         reversetree(&die.Child)
442                 }
443         }
444 }
445
446 func newmemberoffsetattr(die *dwarf.DWDie, offs int32) {
447         newattr(die, dwarf.DW_AT_data_member_location, dwarf.DW_CLS_CONSTANT, int64(offs), nil)
448 }
449
450 func (d *dwctxt) lookupOrDiag(n string) loader.Sym {
451         symIdx := d.ldr.Lookup(n, 0)
452         if symIdx == 0 {
453                 Exitf("dwarf: missing type: %s", n)
454         }
455         if len(d.ldr.Data(symIdx)) == 0 {
456                 Exitf("dwarf: missing type (no data): %s", n)
457         }
458
459         return symIdx
460 }
461
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[") {
465                 return nil
466         }
467         if strings.HasPrefix(name, "struct {") {
468                 return nil
469         }
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 {") {
473                 return nil
474         }
475         if strings.HasPrefix(name, "chan ") {
476                 return nil
477         }
478         if name[0] == '[' || name[0] == '*' {
479                 return nil
480         }
481         if def == nil {
482                 Errorf(nil, "dwarf: bad def in dotypedef")
483         }
484
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)
491         def.Sym = dwSym(tds)
492         d.ldr.SetAttrNotInSymbolTable(tds, true)
493         d.ldr.SetAttrReachable(tds, true)
494
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)
500
501         d.newrefattr(die, dwarf.DW_AT_type, tds)
502
503         return die
504 }
505
506 // Define gotype, for composite ones recurse into constituents.
507 func (d *dwctxt) defgotype(gotype loader.Sym) loader.Sym {
508         if gotype == 0 {
509                 return d.mustFind("<unspecified>")
510         }
511
512         // If we already have a tdmap entry for the gotype, return it.
513         if ds, ok := d.tdmap[gotype]; ok {
514                 return ds
515         }
516
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>")
521         }
522         name := sn[5:] // could also decode from Type.string
523
524         sdie := d.find(name)
525         if sdie != 0 {
526                 return sdie
527         }
528
529         gtdwSym := d.newtype(gotype)
530         d.tdmap[gotype] = loader.Sym(gtdwSym.Sym.(dwSym))
531         return loader.Sym(gtdwSym.Sym.(dwSym))
532 }
533
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)
538         if len(tdata) == 0 {
539                 d.linkctxt.Errorf(gotype, "missing type")
540         }
541         kind := decodetypeKind(d.arch, tdata)
542         bytesize := decodetypeSize(d.arch, tdata)
543
544         var die, typedefdie *dwarf.DWDie
545         switch kind {
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)
550
551         case objabi.KindInt,
552                 objabi.KindInt8,
553                 objabi.KindInt16,
554                 objabi.KindInt32,
555                 objabi.KindInt64:
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)
559
560         case objabi.KindUint,
561                 objabi.KindUint8,
562                 objabi.KindUint16,
563                 objabi.KindUint32,
564                 objabi.KindUint64,
565                 objabi.KindUintptr:
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)
569
570         case objabi.KindFloat32,
571                 objabi.KindFloat64:
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)
575
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)
581
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")
589
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)
592
593                 d.newrefattr(fld, dwarf.DW_AT_type, d.uintptrInfoSym)
594
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)
602
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))
616                 }
617
618                 if decodetypeFuncDotdotdot(d.arch, data) {
619                         d.newdie(die, dwarf.DW_ABRV_DOTDOTDOT, "...")
620                 }
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)))
627                 }
628
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))
634                 var s loader.Sym
635                 if nfields == 0 {
636                         s = d.typeRuntimeEface
637                 } else {
638                         s = d.typeRuntimeIface
639                 }
640                 d.newrefattr(die, dwarf.DW_AT_type, d.defgotype(s))
641
642         case objabi.KindMap:
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)
651
652         case objabi.KindPtr:
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))
657
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)
665
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)
669
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)
678                         if f == "" {
679                                 sn := d.ldr.SymName(s)
680                                 f = sn[5:] // skip "type:"
681                         }
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)
688                         }
689                 }
690
691         case objabi.KindUnsafePointer:
692                 die = d.newdie(&dwtypes, dwarf.DW_ABRV_BARE_PTRTYPE, name)
693
694         default:
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>"))
698         }
699
700         newattr(die, dwarf.DW_AT_go_kind, dwarf.DW_CLS_CONSTANT, int64(kind), 0)
701
702         if d.ldr.AttrReachable(gotype) {
703                 newattr(die, dwarf.DW_AT_go_runtime_type, dwarf.DW_CLS_GO_TYPEREF, 0, dwSym(gotype))
704         }
705
706         // Sanity check.
707         if _, ok := d.rtmap[gotype]; ok {
708                 log.Fatalf("internal error: rtmap entry already installed\n")
709         }
710
711         ds := loader.Sym(die.Sym.(dwSym))
712         if typedefdie != nil {
713                 ds = loader.Sym(typedefdie.Sym.(dwSym))
714         }
715         d.rtmap[ds] = gotype
716
717         if _, ok := prototypedies[sn]; ok {
718                 prototypedies[sn] = die
719         }
720
721         if typedefdie != nil {
722                 return typedefdie
723         }
724         return die
725 }
726
727 func (d *dwctxt) nameFromDIESym(dwtypeDIESym loader.Sym) string {
728         sn := d.ldr.SymName(dwtypeDIESym)
729         return sn[len(dwarf.InfoPrefix):]
730 }
731
732 func (d *dwctxt) defptrto(dwtype loader.Sym) loader.Sym {
733
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.
737
738         ptrname := "*" + d.nameFromDIESym(dwtype)
739         if die := d.find(ptrname); die != 0 {
740                 return die
741         }
742
743         pdie := d.newdie(&dwtypes, dwarf.DW_ABRV_PTRTYPE, ptrname)
744         d.newrefattr(pdie, dwarf.DW_AT_type, dwtype)
745
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))
752         }
753
754         if gts != 0 {
755                 ds := loader.Sym(pdie.Sym.(dwSym))
756                 d.rtmap[ds] = gts
757                 d.tdmap[gts] = ds
758         }
759
760         return d.dtolsym(pdie.Sym)
761 }
762
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 {
768                 if src == except {
769                         continue
770                 }
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)
774                 }
775                 d.copychildrenexcept(ctxt, c, src, nil)
776         }
777
778         reverselist(&dst.Child)
779 }
780
781 func (d *dwctxt) copychildren(ctxt *Link, dst *dwarf.DWDie, src *dwarf.DWDie) {
782         d.copychildrenexcept(ctxt, dst, src, nil)
783 }
784
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)
789         if child == nil {
790                 Exitf("dwarf substitutetype: %s does not have member %s",
791                         getattr(structdie, dwarf.DW_AT_name).Data, field)
792                 return
793         }
794
795         a := getattr(child, dwarf.DW_AT_type)
796         if a != nil {
797                 a.Data = dwSym(dwtype)
798         } else {
799                 d.newrefattr(child, dwarf.DW_AT_type, dwtype)
800         }
801 }
802
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]
808         }
809         if die == nil {
810                 log.Fatalf("internal error: DIE generation failed for %s\n", name)
811         }
812         return die
813 }
814
815 func (d *dwctxt) synthesizestringtypes(ctxt *Link, die *dwarf.DWDie) {
816         prototype := walktypedef(d.findprotodie(ctxt, "type:runtime.stringStructDWARF"))
817         if prototype == nil {
818                 return
819         }
820
821         for ; die != nil; die = die.Link {
822                 if die.Abbrev != dwarf.DW_ABRV_STRINGTYPE {
823                         continue
824                 }
825                 d.copychildren(ctxt, die, prototype)
826         }
827 }
828
829 func (d *dwctxt) synthesizeslicetypes(ctxt *Link, die *dwarf.DWDie) {
830         prototype := walktypedef(d.findprotodie(ctxt, "type:runtime.slice"))
831         if prototype == nil {
832                 return
833         }
834
835         for ; die != nil; die = die.Link {
836                 if die.Abbrev != dwarf.DW_ABRV_SLICETYPE {
837                         continue
838                 }
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))
842         }
843 }
844
845 func mkinternaltypename(base string, arg1 string, arg2 string) string {
846         if arg2 == "" {
847                 return fmt.Sprintf("%s<%s>", base, arg1)
848         }
849         return fmt.Sprintf("%s<%s,%s>", base, arg1, arg2)
850 }
851
852 // synthesizemaptypes is way too closely married to runtime/hashmap.c
853 const (
854         MaxKeySize = abi.MapMaxKeyBytes
855         MaxValSize = abi.MapMaxElemBytes
856         BucketSize = abi.MapBucketCount
857 )
858
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 {
864                 return s
865         }
866         die := d.newdie(&dwtypes, abbrev, name)
867         f(die)
868         return d.dtolsym(die.Sym)
869 }
870
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"))
874
875         if hash == nil {
876                 return
877         }
878
879         for ; die != nil; die = die.Link {
880                 if die.Abbrev != dwarf.DW_ABRV_MAPTYPE {
881                         continue
882                 }
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))
890
891                 // compute size info like hashmap.c does.
892                 indirectKey, indirectVal := false, false
893                 if keysize > MaxKeySize {
894                         keysize = int64(d.arch.PtrSize)
895                         indirectKey = true
896                 }
897                 if valsize > MaxValSize {
898                         valsize = int64(d.arch.PtrSize)
899                         indirectVal = true
900                 }
901
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)
906                         t := keytype
907                         if indirectKey {
908                                 t = d.defptrto(keytype)
909                         }
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)
914                 })
915
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)
920                         t := valtype
921                         if indirectVal {
922                                 t = d.defptrto(valtype)
923                         }
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)
928                 })
929
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"))
935
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))
949                         }
950
951                         newattr(dwhb, dwarf.DW_AT_byte_size, dwarf.DW_CLS_CONSTANT, BucketSize+BucketSize*keysize+BucketSize*valsize+int64(d.arch.RegSize), 0)
952                 })
953
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)
960                 })
961
962                 // make map type a pointer to hash<K,V>
963                 d.newrefattr(die, dwarf.DW_AT_type, d.defptrto(dwhs))
964         }
965 }
966
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 {
972                 return
973         }
974
975         sudogsize := int(getattr(sudog, dwarf.DW_AT_byte_size).Value)
976
977         for ; die != nil; die = die.Link {
978                 if die.Abbrev != dwarf.DW_ABRV_CHANTYPE {
979                         continue
980                 }
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)))
985
986                 // sudog<T>
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)
991                 })
992
993                 // waitq<T>
994                 dwws := d.mkinternaltype(ctxt, dwarf.DW_ABRV_STRUCTTYPE, "waitq", elemname, "", func(dww *dwarf.DWDie) {
995
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)
1000                 })
1001
1002                 // hchan<T>
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)
1008                 })
1009
1010                 d.newrefattr(die, dwarf.DW_AT_type, d.defptrto(dwhs))
1011         }
1012 }
1013
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)
1019         }
1020         d.addDwarfAddrField(su, v)
1021 }
1022
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)
1027         } else {
1028                 sb.AddUint32(d.arch, uint32(v))
1029         }
1030 }
1031
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)
1036         } else {
1037                 d.adddwarfref(sb, t, 4)
1038         }
1039 }
1040
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)
1046
1047                 fi := d.ldr.FuncInfo(sym)
1048                 if !fi.Valid() {
1049                         continue
1050                 }
1051
1052                 // Skip linker-created functions (ex: runtime.addmoduledata), since they
1053                 // don't have DWARF to begin with.
1054                 unit := d.ldr.SymUnit(sym)
1055                 if unit == nil {
1056                         continue
1057                 }
1058
1059                 // Update PC ranges.
1060                 //
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
1065                 // different units.
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})
1070                         prevUnit = unit
1071                 }
1072                 unit.PCs[len(unit.PCs)-1].End = sval - u0val + int64(len(d.ldr.Data(sym)))
1073         }
1074 }
1075
1076 func movetomodule(ctxt *Link, parent *dwarf.DWDie) {
1077         die := ctxt.runtimeCU.DWInfo.Child
1078         if die == nil {
1079                 ctxt.runtimeCU.DWInfo.Child = parent.Child
1080                 return
1081         }
1082         for die.Link != nil {
1083                 die = die.Link
1084         }
1085         die.Link = parent.Child
1086 }
1087
1088 /*
1089  * Generate a sequence of opcodes that is as short as possible.
1090  * See section 6.2.5
1091  */
1092 const (
1093         LINE_BASE   = -4
1094         LINE_RANGE  = 10
1095         PC_RANGE    = (255 - OPCODE_BASE) / LINE_RANGE
1096         OPCODE_BASE = 11
1097 )
1098
1099 /*
1100  * Walk prog table, emit line program and build DIE tree.
1101  */
1102
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.
1110         return "."
1111 }
1112
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())
1119         }
1120         relocs := d.ldr.Relocs(dsym)
1121         for i := 0; i < relocs.Count(); i++ {
1122                 r := relocs.At(i)
1123                 if r.Type() != objabi.R_DWARFSECREF {
1124                         continue
1125                 }
1126                 rsym := r.Sym()
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
1131                         continue
1132                 }
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)
1138                 d.defgotype(ts)
1139         }
1140 }
1141
1142 func expandFile(fname string) string {
1143         fname = strings.TrimPrefix(fname, src.FileSymPrefix)
1144         return expandGoroot(fname)
1145 }
1146
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 {
1155                 base string
1156                 dir  int
1157         }
1158         dirNums := make(map[string]int)
1159         dirs := []string{""}
1160         files := []fileDir{}
1161
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)
1166                 if len(name) == 0 {
1167                         // Can't have empty filenames, and having a unique
1168                         // filename is quite useful for debugging.
1169                         name = fmt.Sprintf("<missing>_%d", i)
1170                 }
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)
1181                 }
1182                 files = append(files, fileDir{base: file, dir: dirIdx})
1183
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" {
1188                         d.dwmu.Lock()
1189                         if gdbscript == "" {
1190                                 k := strings.Index(name, "runtime/proc.go")
1191                                 gdbscript = name[:k] + "runtime/runtime-gdb.py"
1192                         }
1193                         d.dwmu.Unlock()
1194                 }
1195         }
1196
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])
1202         }
1203         lsu.AddUint8(0) // terminator
1204
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
1211         }
1212         lsu.AddUint8(0) // terminator
1213 }
1214
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.
1225
1226         unitstart := int64(-1)
1227         headerstart := int64(-1)
1228         headerend := int64(-1)
1229
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)
1235
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()
1245
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]
1262
1263         // Call helper to emit dir and file sections.
1264         d.writeDirFileTables(unit, lsu)
1265
1266         // capture length at end of file names.
1267         headerend = lsu.Size()
1268         unitlen := lsu.Size() - unitstart
1269
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)
1274
1275                 // Chain the line symbol onto the list.
1276                 if lines != 0 {
1277                         syms = append(syms, lines)
1278                         unitlen += int64(len(d.ldr.Data(lines)))
1279                 }
1280         }
1281
1282         if d.linkctxt.HeadType == objabi.Haix {
1283                 addDwsectCUSize(".debug_line", unit.Lib.Pkg, uint64(unitlen))
1284         }
1285
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))
1289         } else {
1290                 lsu.SetUint32(d.arch, unitLengthOffset, uint32(unitlen))
1291                 lsu.SetUint32(d.arch, headerLengthOffset, uint32(headerend-headerstart))
1292         }
1293
1294         return syms
1295 }
1296
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 {
1301
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)
1306
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)
1311
1312         // Collect up the ranges for functions in the unit.
1313         rsize := uint64(rsu.Size())
1314         for _, ls := range unit.RangeSyms {
1315                 s := loader.Sym(ls)
1316                 syms = append(syms, s)
1317                 rsize += uint64(d.ldr.SymSize(s))
1318         }
1319
1320         if d.linkctxt.HeadType == objabi.Haix {
1321                 addDwsectCUSize(".debug_ranges", unit.Lib.Pkg, rsize)
1322         }
1323
1324         return syms
1325 }
1326
1327 /*
1328  *  Emit .debug_frame
1329  */
1330 const (
1331         dataAlignmentFactor = -4
1332 )
1333
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)
1338
1339         switch {
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))
1348         default:
1349                 b = append(b, dwarf.DW_CFA_advance_loc4, 0, 0, 0, 0)
1350                 arch.ByteOrder.PutUint32(b[len(b)-4:], uint32(deltapc))
1351         }
1352         return b
1353 }
1354
1355 func (d *dwctxt) writeframes(fs loader.Sym) dwarfSecInfo {
1356         fsd := dwSym(fs)
1357         fsu := d.ldr.MakeSymbolUpdater(fs)
1358         fsu.SetType(sym.SDWARFSECT)
1359         isdw64 := isDwarf64(d.linkctxt)
1360         haslr := d.linkctxt.Arch.HasLR
1361
1362         // Length field is 4 bytes on Dwarf32 and 12 bytes on Dwarf64
1363         lengthFieldSize := int64(4)
1364         if isdw64 {
1365                 lengthFieldSize += 8
1366         }
1367
1368         // Emit the CIE, Section 6.4.1
1369         cieReserve := uint32(16)
1370         if haslr {
1371                 cieReserve = 32
1372         }
1373         if isdw64 {
1374                 cieReserve += 4 // 4 bytes added for cid
1375         }
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
1383
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)...
1386         if haslr {
1387                 dwarf.Uleb128put(d, fsd, int64(0)) // ...plus a 0 offset.
1388
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))
1391
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.
1395         } else {
1396                 dwarf.Uleb128put(d, fsd, int64(d.arch.PtrSize)) // ...plus the word size (because the call instruction implicitly adds one word to the frame).
1397
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)].
1401         }
1402
1403         pad := int64(cieReserve) + lengthFieldSize - int64(len(d.ldr.Data(fs)))
1404
1405         if pad < 0 {
1406                 Exitf("dwarf: cieReserve too small by %d bytes.", -pad)
1407         }
1408
1409         internalExec := d.linkctxt.BuildMode == BuildModeExe && d.linkctxt.IsInternal()
1410         addAddrPlus := loader.GenAddAddrPlusFunc(internalExec)
1411
1412         fsu.AddBytes(zeros[:pad])
1413
1414         var deltaBuf []byte
1415         pcsp := obj.NewPCIter(uint32(d.arch.MinLC))
1416         for _, s := range d.linkctxt.Textp {
1417                 fn := loader.Sym(s)
1418                 fi := d.ldr.FuncInfo(fn)
1419                 if !fi.Valid() {
1420                         continue
1421                 }
1422                 fpcsp := d.ldr.Pcsp(s)
1423
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))
1433                 }
1434
1435                 for pcsp.Init(d.linkctxt.loader.Data(fpcsp)); !pcsp.Done; pcsp.Next() {
1436                         nextpc := pcsp.NextPC
1437
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))) {
1441                                 nextpc--
1442                                 if nextpc < pcsp.PC {
1443                                         continue
1444                                 }
1445                         }
1446
1447                         spdelta := int64(pcsp.Value)
1448                         if !haslr {
1449                                 // Return address has been pushed onto stack.
1450                                 spdelta += int64(d.arch.PtrSize)
1451                         }
1452
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.
1457                                 if pcsp.Value > 0 {
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)
1463                                 } else {
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))
1468                                 }
1469                         }
1470
1471                         deltaBuf = appendPCDeltaCFA(d.arch, deltaBuf, int64(nextpc)-int64(pcsp.PC), spdelta)
1472                 }
1473                 pad := int(Rnd(int64(len(deltaBuf)), int64(d.arch.PtrSize))) - len(deltaBuf)
1474                 deltaBuf = append(deltaBuf, zeros[:pad]...)
1475
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
1481
1482                 fdeLength := uint64(4 + 2*d.arch.PtrSize + len(deltaBuf))
1483                 if isdw64 {
1484                         fdeLength += 4 // 4 bytes added for CIE pointer
1485                 }
1486                 d.createUnitLength(fsu, fdeLength)
1487
1488                 if d.linkctxt.LinkMode == LinkExternal {
1489                         d.addDwarfAddrRef(fsu, fs)
1490                 } else {
1491                         d.addDwarfAddrField(fsu, 0) // CIE offset
1492                 }
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)
1496
1497                 if d.linkctxt.HeadType == objabi.Haix {
1498                         addDwsectCUSize(".debug_frame", d.ldr.SymPkg(fn), fdeLength+uint64(lengthFieldSize))
1499                 }
1500         }
1501
1502         return dwarfSecInfo{syms: []loader.Sym{fs}}
1503 }
1504
1505 /*
1506  *  Walk DWarfDebugInfoEntries, and emit .debug_info
1507  */
1508
1509 const (
1510         COMPUNITHEADERSIZE = 4 + 2 + 4 + 1
1511 )
1512
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 {
1516                 return syms
1517         }
1518
1519         compunit := u.DWInfo
1520         s := d.dtolsym(compunit.Sym)
1521         su := d.ldr.MakeSymbolUpdater(s)
1522
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)
1528
1529         // debug_abbrev_offset (*)
1530         d.addDwarfAddrRef(su, abbrevsym)
1531
1532         su.AddUint8(uint8(d.arch.PtrSize)) // address_size
1533
1534         ds := dwSym(s)
1535         dwarf.Uleb128put(d, ds, int64(compunit.Abbrev))
1536         dwarf.PutAttrs(d, ds, compunit.Abbrev, compunit.Attr)
1537
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))
1540         cu = append(cu, s)
1541         cu = append(cu, u.AbsFnDIEs...)
1542         cu = append(cu, u.FuncDIEs...)
1543         if u.Consts != 0 {
1544                 cu = append(cu, loader.Sym(u.Consts))
1545         }
1546         cu = append(cu, u.VarDIEs...)
1547         var cusize int64
1548         for _, child := range cu {
1549                 cusize += int64(len(d.ldr.Data(child)))
1550         }
1551
1552         for die := compunit.Child; die != nil; die = die.Link {
1553                 l := len(cu)
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])))
1559                 }
1560                 for _, child := range cu[l:] {
1561                         cusize += int64(len(d.ldr.Data(child)))
1562                 }
1563         }
1564
1565         culu := d.ldr.MakeSymbolUpdater(infoEpilog)
1566         culu.AddUint8(0) // closes compilation unit DIE
1567         cu = append(cu, infoEpilog)
1568         cusize++
1569
1570         // Save size for AIX symbol table.
1571         if d.linkctxt.HeadType == objabi.Haix {
1572                 addDwsectCUSize(".debug_info", d.getPkgFromCUSym(s), uint64(cusize))
1573         }
1574         if isDwarf64(d.linkctxt) {
1575                 cusize -= 12                          // exclude the length field.
1576                 su.SetUint(d.arch, 4, uint64(cusize)) // 4 because of 0XFFFFFFFF
1577         } else {
1578                 cusize -= 4 // exclude the length field.
1579                 su.SetUint32(d.arch, 0, uint32(cusize))
1580         }
1581         return append(syms, cu...)
1582 }
1583
1584 func (d *dwctxt) writegdbscript() dwarfSecInfo {
1585         // TODO (aix): make it available
1586         if d.linkctxt.HeadType == objabi.Haix {
1587                 return dwarfSecInfo{}
1588         }
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{}
1597         }
1598         if gdbscript == "" {
1599                 return dwarfSecInfo{}
1600         }
1601
1602         gs := d.ldr.CreateSymForUpdate(".debug_gdb_scripts", 0)
1603         gs.SetType(sym.SDWARFSECT)
1604
1605         gs.AddUint8(GdbScriptPythonFileId)
1606         gs.Addstring(gdbscript)
1607         return dwarfSecInfo{syms: []loader.Sym{gs.Sym()}}
1608 }
1609
1610 // FIXME: might be worth looking replacing this map with a function
1611 // that switches based on symbol instead.
1612
1613 var prototypedies map[string]*dwarf.DWDie
1614
1615 func dwarfEnabled(ctxt *Link) bool {
1616         if *FlagW { // disable dwarf
1617                 return false
1618         }
1619         if ctxt.HeadType == objabi.Hplan9 || ctxt.HeadType == objabi.Hjs || ctxt.HeadType == objabi.Hwasip1 {
1620                 return false
1621         }
1622
1623         if ctxt.LinkMode == LinkExternal {
1624                 switch {
1625                 case ctxt.IsELF:
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())
1630                         if err != nil {
1631                                 Exitf("%v", err)
1632                         }
1633                         return res
1634                 default:
1635                         return false
1636                 }
1637         }
1638
1639         return true
1640 }
1641
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 {
1645         // create type DIE
1646         die := d.newdie(&dwtypes, abrv, tname)
1647
1648         // Look up type symbol.
1649         gotype := d.lookupOrDiag("type:" + tname)
1650
1651         // Map from die sym to type sym
1652         ds := loader.Sym(die.Sym.(dwSym))
1653         d.rtmap[ds] = gotype
1654
1655         // Map from type to def sym
1656         d.tdmap[gotype] = ds
1657
1658         return die
1659 }
1660
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)
1669         if infosym == 0 {
1670                 return
1671         }
1672         d.ldr.SetAttrNotInSymbolTable(infosym, true)
1673         d.ldr.SetAttrReachable(infosym, true)
1674         unit.FuncDIEs = append(unit.FuncDIEs, sym.LoaderSym(infosym))
1675         if rangesym != 0 {
1676                 d.ldr.SetAttrNotInSymbolTable(rangesym, true)
1677                 d.ldr.SetAttrReachable(rangesym, true)
1678                 unit.RangeSyms = append(unit.RangeSyms, sym.LoaderSym(rangesym))
1679         }
1680
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++ {
1687                 r := drelocs.At(ri)
1688                 // Look for "use type" relocs.
1689                 if r.Type() == objabi.R_USETYPE {
1690                         d.defgotype(r.Sym())
1691                         continue
1692                 }
1693                 if r.Type() != objabi.R_DWARFSECREF {
1694                         continue
1695                 }
1696
1697                 rsym := r.Sym()
1698                 rst := d.ldr.SymType(rsym)
1699
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)
1707                         }
1708                         continue
1709                 }
1710
1711                 // Look for type references.
1712                 if rst != sym.SDWARFTYPE && rst != sym.Sxxx {
1713                         continue
1714                 }
1715                 if _, ok := d.rtmap[rsym]; ok {
1716                         // type already generated
1717                         continue
1718                 }
1719
1720                 rsn := d.ldr.SymName(rsym)
1721                 tn := rsn[len(dwarf.InfoPrefix):]
1722                 ts := d.ldr.Lookup("type:"+tn, 0)
1723                 d.defgotype(ts)
1724         }
1725 }
1726
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
1733 // text symbols.
1734 func dwarfGenerateDebugInfo(ctxt *Link) {
1735         if !dwarfEnabled(ctxt) {
1736                 return
1737         }
1738
1739         d := &dwctxt{
1740                 linkctxt: ctxt,
1741                 ldr:      ctxt.loader,
1742                 arch:     ctxt.Arch,
1743                 tmap:     make(map[string]loader.Sym),
1744                 tdmap:    make(map[loader.Sym]loader.Sym),
1745                 rtmap:    make(map[loader.Sym]loader.Sym),
1746         }
1747         d.typeRuntimeEface = d.lookupOrDiag("type:runtime.eface")
1748         d.typeRuntimeIface = d.lookupOrDiag("type:runtime.iface")
1749
1750         if ctxt.HeadType == objabi.Haix {
1751                 // Initial map used to store package size for each DWARF section.
1752                 dwsectCUSize = make(map[string]uint64)
1753         }
1754
1755         // For ctxt.Diagnostic messages.
1756         newattr(&dwtypes, dwarf.DW_AT_name, dwarf.DW_CLS_STRING, int64(len("dwtypes")), "dwtypes")
1757
1758         // Unspecified type. There are no references to this in the symbol table.
1759         d.newdie(&dwtypes, dwarf.DW_ABRV_NULLTYPE, "<unspecified>")
1760
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")))
1769
1770         d.uintptrInfoSym = d.mustFind("uintptr")
1771
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,
1781         }
1782
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))
1797         }
1798
1799         // fake root DIE for compile unit DIEs
1800         var dwroot dwarf.DWDie
1801         flagVariants := make(map[string]bool)
1802
1803         for _, lib := range ctxt.Library {
1804
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.
1808                         if consts != 0 {
1809                                 unit.Consts = sym.LoaderSym(consts)
1810                                 d.importInfoSymbol(consts)
1811                                 consts = 0
1812                         }
1813                         ctxt.compUnits = append(ctxt.compUnits, unit)
1814
1815                         // We need at least one runtime unit.
1816                         if unit.Lib.Pkg == "runtime" {
1817                                 ctxt.runtimeCU = unit
1818                         }
1819
1820                         cuabrv := dwarf.DW_ABRV_COMPUNIT
1821                         if len(unit.Textp) == 0 {
1822                                 cuabrv = dwarf.DW_ABRV_COMPUNIT_TEXTLESS
1823                         }
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)
1832
1833                         var peData []byte
1834                         if producerExtra := d.ldr.Lookup(dwarf.CUInfoPrefix+"producer."+unit.Lib.Pkg, 0); producerExtra != 0 {
1835                                 peData = d.ldr.Data(producerExtra)
1836                         }
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
1847                         } else {
1848                                 flagVariants[""] = true
1849                         }
1850
1851                         newattr(unit.DWInfo, dwarf.DW_AT_producer, dwarf.DW_CLS_STRING, int64(len(producer)), producer)
1852
1853                         var pkgname string
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)
1857                         }
1858                         newattr(unit.DWInfo, dwarf.DW_AT_go_package_name, dwarf.DW_CLS_STRING, int64(len(pkgname)), pkgname)
1859
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)
1866                         }
1867                 }
1868         }
1869
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 {
1874                 checkStrictDups = 1
1875         }
1876
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 {
1888                         continue
1889                 }
1890                 t := d.ldr.SymType(idx)
1891                 switch t {
1892                 case sym.SRODATA, sym.SDATA, sym.SNOPTRDATA, sym.STYPE, sym.SBSS, sym.SNOPTRBSS, sym.STLSBSS:
1893                         // ok
1894                 default:
1895                         continue
1896                 }
1897                 // Skip things with no type, unless it's a dictionary
1898                 gt := d.ldr.SymGoType(idx)
1899                 if gt == 0 {
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())
1908                                                 }
1909                                         }
1910                                 }
1911                         }
1912                         continue
1913                 }
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) {
1917                         continue
1918                 }
1919
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)
1926                 if varDIE != 0 {
1927                         unit := d.ldr.SymUnit(idx)
1928                         d.defgotype(gt)
1929                         unit.VarDIEs = append(unit.VarDIEs, sym.LoaderSym(varDIE))
1930                 }
1931         }
1932
1933         d.synthesizestringtypes(ctxt, dwtypes.Child)
1934         d.synthesizeslicetypes(ctxt, dwtypes.Child)
1935         d.synthesizemaptypes(ctxt, dwtypes.Child)
1936         d.synthesizechantypes(ctxt, dwtypes.Child)
1937 }
1938
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) {
1944                 return
1945         }
1946         d := &dwctxt{
1947                 linkctxt: ctxt,
1948                 ldr:      ctxt.loader,
1949                 arch:     ctxt.Arch,
1950                 dwmu:     new(sync.Mutex),
1951         }
1952         d.dwarfGenerateDebugSyms()
1953 }
1954
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
1962
1963         // Outputs for a given unit.
1964         linesyms   []loader.Sym
1965         infosyms   []loader.Sym
1966         locsyms    []loader.Sym
1967         rangessyms []loader.Sym
1968 }
1969
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)
1981         }
1982         us.infosyms = d.writeUnitInfo(u, abbrevsym, us.infoEpilog)
1983 }
1984
1985 func (d *dwctxt) dwarfGenerateDebugSyms() {
1986         abbrevSec := d.writeabbrev()
1987         dwarfp = append(dwarfp, abbrevSec)
1988         d.calcCompUnitRanges()
1989         sort.Sort(compilationUnitByStartPC(d.linkctxt.compUnits))
1990
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)
1996         }
1997         reversetree(&dwtypes.Child)
1998         movetomodule(d.linkctxt, &dwtypes)
1999
2000         mkSecSym := func(name string) loader.Sym {
2001                 s := d.ldr.CreateSymForUpdate(name, 0)
2002                 s.SetType(sym.SDWARFSECT)
2003                 s.SetReachable(true)
2004                 return s.Sym()
2005         }
2006         mkAnonSym := func(kind sym.SymKind) loader.Sym {
2007                 s := d.ldr.MakeSymbolUpdater(d.ldr.CreateExtSym("", 0))
2008                 s.SetType(kind)
2009                 s.SetReachable(true)
2010                 return s.Sym()
2011         }
2012
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")
2019
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}}
2026
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++ {
2032                 us := &unitSyms[i]
2033                 us.lineProlog = mkAnonSym(sym.SDWARFLINES)
2034                 us.rangeProlog = mkAnonSym(sym.SDWARFRANGE)
2035                 us.infoEpilog = mkAnonSym(sym.SDWARFFCN)
2036         }
2037
2038         var wg sync.WaitGroup
2039         sema := make(chan struct{}, runtime.GOMAXPROCS(0))
2040
2041         // Kick off generation of .debug_frame, since it doesn't have
2042         // any entanglements and can be started right away.
2043         wg.Add(1)
2044         go func() {
2045                 sema <- struct{}{}
2046                 defer func() {
2047                         <-sema
2048                         wg.Done()
2049                 }()
2050                 frameSec = d.writeframes(frameSym)
2051         }()
2052
2053         // Create a goroutine per comp unit to handle the generation that
2054         // unit's portion of .debug_line, .debug_loc, .debug_ranges, and
2055         // .debug_info.
2056         wg.Add(len(d.linkctxt.compUnits))
2057         for i := 0; i < ncu; i++ {
2058                 go func(u *sym.CompilationUnit, us *dwUnitSyms) {
2059                         sema <- struct{}{}
2060                         defer func() {
2061                                 <-sema
2062                                 wg.Done()
2063                         }()
2064                         d.dwUnitPortion(u, abbrevSec.secSym(), us)
2065                 }(d.linkctxt.compUnits[i], &unitSyms[i])
2066         }
2067         wg.Wait()
2068
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)
2073                 }
2074                 return syms
2075         }
2076
2077         // Stitch together the results.
2078         for i := 0; i < ncu; i++ {
2079                 r := &unitSyms[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)...)
2084         }
2085         dwarfp = append(dwarfp, lineSec)
2086         dwarfp = append(dwarfp, frameSec)
2087         gdbScriptSec := d.writegdbscript()
2088         if gdbScriptSec.secSym() != 0 {
2089                 dwarfp = append(dwarfp, gdbScriptSec)
2090         }
2091         dwarfp = append(dwarfp, infoSec)
2092         if len(locSec.syms) > 1 {
2093                 dwarfp = append(dwarfp, locSec)
2094         }
2095         dwarfp = append(dwarfp, rangesSec)
2096
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 {
2103                 if seen.Has(s) {
2104                         log.Fatalf("symbol %s listed multiple times", d.ldr.SymName(s))
2105                 }
2106                 seen.Set(s)
2107         }
2108 }
2109
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 {
2117                                 continue
2118                         }
2119                         rsym := reloc.Sym()
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.
2123                                 break
2124                         }
2125                 }
2126         }
2127         return syms
2128 }
2129
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
2134                 return
2135         }
2136
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)
2142                 }
2143         }
2144 }
2145
2146 func dwarfaddelfsectionsyms(ctxt *Link) {
2147         if *FlagW { // disable dwarf
2148                 return
2149         }
2150         if ctxt.LinkMode != LinkExternal {
2151                 return
2152         }
2153
2154         ldr := ctxt.loader
2155         for _, si := range dwarfp {
2156                 s := si.secSym()
2157                 sect := ldr.SymSect(si.secSym())
2158                 putelfsectionsym(ctxt, ctxt.Out, s, sect.Elfsect.(*ElfShdr).shnum)
2159         }
2160 }
2161
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 {
2168                 index      int
2169                 compressed []byte
2170                 syms       []loader.Sym
2171         }
2172
2173         supported := ctxt.IsELF || ctxt.IsWindows() || ctxt.IsDarwin()
2174         if !ctxt.compressDWARF || !supported || ctxt.IsExternal() {
2175                 return
2176         }
2177
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)
2184                 compressedCount++
2185         }
2186         res := make([]compressedSect, compressedCount)
2187         for ; compressedCount > 0; compressedCount-- {
2188                 r := <-resChannel
2189                 res[r.index] = r
2190         }
2191
2192         ldr := ctxt.loader
2193         var newDwarfp []dwarfSecInfo
2194         Segdwarf.Sections = Segdwarf.Sections[:0]
2195         for _, z := range res {
2196                 s := z.syms[0]
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))
2202                 } else {
2203                         var compressedSegName string
2204                         if ctxt.IsELF {
2205                                 compressedSegName = ldr.SymSect(s).Name
2206                         } else {
2207                                 compressedSegName = ".zdebug_" + ldr.SymSect(s).Name[len(".debug_"):]
2208                         }
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)
2220
2221                         // compressed symbols are no longer needed.
2222                         for _, s := range z.syms {
2223                                 ldr.SetAttrReachable(s, false)
2224                                 ldr.FreeSym(s)
2225                         }
2226                 }
2227         }
2228         dwarfp = newDwarfp
2229
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)
2241                                 prevSect = sect
2242                         }
2243                         if ldr.SubSym(s) != 0 {
2244                                 log.Fatalf("%s: unexpected sub-symbols", ldr.SymName(s))
2245                         }
2246                         pos += uint64(ldr.SymSize(s))
2247                         if ctxt.IsWindows() {
2248                                 pos = uint64(Rnd(int64(pos), PEFILEALIGN))
2249                         }
2250                 }
2251         }
2252         Segdwarf.Length = pos - Segdwarf.Vaddr
2253 }
2254
2255 type compilationUnitByStartPC []*sym.CompilationUnit
2256
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] }
2259
2260 func (v compilationUnitByStartPC) Less(i, j int) bool {
2261         switch {
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:
2265                 return true
2266         case len(v[i].Textp) == 0 && len(v[j].Textp) != 0:
2267                 return false
2268         default:
2269                 return v[i].PCs[0].Start < v[j].PCs[0].Start
2270         }
2271 }
2272
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.")
2279 }
2280
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
2288
2289 // getDwsectCUSize retrieves the corresponding package size inside the current section.
2290 func getDwsectCUSize(sname string, pkgname string) uint64 {
2291         return dwsectCUSize[sname+"."+pkgname]
2292 }
2293
2294 func addDwsectCUSize(sname string, pkgname string, size uint64) {
2295         dwsectCUSizeMu.Lock()
2296         defer dwsectCUSizeMu.Unlock()
2297         dwsectCUSize[sname+"."+pkgname] += size
2298 }