Source file src/cmd/internal/obj/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  // Writes dwarf information to object files.
     6  
     7  package obj
     8  
     9  import (
    10  	"cmd/internal/dwarf"
    11  	"cmd/internal/objabi"
    12  	"cmd/internal/src"
    13  	"fmt"
    14  	"slices"
    15  	"strings"
    16  	"sync"
    17  )
    18  
    19  // Generate a sequence of opcodes that is as short as possible.
    20  // See section 6.2.5
    21  const (
    22  	LINE_BASE   = -4
    23  	LINE_RANGE  = 10
    24  	PC_RANGE    = (255 - OPCODE_BASE) / LINE_RANGE
    25  	OPCODE_BASE = 11
    26  )
    27  
    28  // generateDebugLinesSymbol fills the debug lines symbol of a given function.
    29  //
    30  // It's worth noting that this function doesn't generate the full debug_lines
    31  // DWARF section, saving that for the linker. This function just generates the
    32  // state machine part of debug_lines. The full table is generated by the
    33  // linker.  Also, we use the file numbers from the full package (not just the
    34  // function in question) when generating the state machine. We do this so we
    35  // don't have to do a fixup on the indices when writing the full section.
    36  func (ctxt *Link) generateDebugLinesSymbol(s, lines *LSym) {
    37  	dctxt := dwCtxt{ctxt}
    38  
    39  	// Emit a LNE_set_address extended opcode, so as to establish the
    40  	// starting text address of this function.
    41  	dctxt.AddUint8(lines, 0)
    42  	dwarf.Uleb128put(dctxt, lines, 1+int64(ctxt.Arch.PtrSize))
    43  	dctxt.AddUint8(lines, dwarf.DW_LNE_set_address)
    44  	dctxt.AddAddress(lines, s, 0)
    45  
    46  	// Set up the debug_lines state machine to the default values
    47  	// we expect at the start of a new sequence.
    48  	stmt := true
    49  	line := int64(1)
    50  	pc := s.Func().Text.Pc
    51  	var lastpc int64 // last PC written to line table, not last PC in func
    52  	fileIndex := 1
    53  	prologue, wrotePrologue := false, false
    54  	// Walk the progs, generating the DWARF table.
    55  	for p := s.Func().Text; p != nil; p = p.Link {
    56  		prologue = prologue || (p.Pos.Xlogue() == src.PosPrologueEnd)
    57  		// If we're not at a real instruction, keep looping!
    58  		if p.Pos.Line() == 0 || (p.Link != nil && p.Link.Pc == p.Pc) {
    59  			continue
    60  		}
    61  		newStmt := p.Pos.IsStmt() != src.PosNotStmt
    62  		newFileIndex, newLine := ctxt.getFileIndexAndLine(p.Pos)
    63  		newFileIndex++ // 1 indexing for the table
    64  
    65  		// Output debug info.
    66  		wrote := false
    67  		if newFileIndex != fileIndex {
    68  			dctxt.AddUint8(lines, dwarf.DW_LNS_set_file)
    69  			dwarf.Uleb128put(dctxt, lines, int64(newFileIndex))
    70  			fileIndex = newFileIndex
    71  			wrote = true
    72  		}
    73  		if prologue && !wrotePrologue {
    74  			dctxt.AddUint8(lines, uint8(dwarf.DW_LNS_set_prologue_end))
    75  			wrotePrologue = true
    76  			wrote = true
    77  		}
    78  		if stmt != newStmt {
    79  			dctxt.AddUint8(lines, uint8(dwarf.DW_LNS_negate_stmt))
    80  			stmt = newStmt
    81  			wrote = true
    82  		}
    83  
    84  		if line != int64(newLine) || wrote {
    85  			pcdelta := p.Pc - pc
    86  			lastpc = p.Pc
    87  			putpclcdelta(ctxt, dctxt, lines, uint64(pcdelta), int64(newLine)-line)
    88  			line, pc = int64(newLine), p.Pc
    89  		}
    90  	}
    91  
    92  	// Because these symbols will be concatenated together by the
    93  	// linker, we need to reset the state machine that controls the
    94  	// debug symbols. Do this using an end-of-sequence operator.
    95  	//
    96  	// Note: at one point in time, Delve did not support multiple end
    97  	// sequence ops within a compilation unit (bug for this:
    98  	// https://github.com/go-delve/delve/issues/1694), however the bug
    99  	// has since been fixed (Oct 2019).
   100  	//
   101  	// Issue 38192: the DWARF standard specifies that when you issue
   102  	// an end-sequence op, the PC value should be one past the last
   103  	// text address in the translation unit, so apply a delta to the
   104  	// text address before the end sequence op. If this isn't done,
   105  	// GDB will assign a line number of zero the last row in the line
   106  	// table, which we don't want.
   107  	lastlen := uint64(s.Size - (lastpc - s.Func().Text.Pc))
   108  	dctxt.AddUint8(lines, dwarf.DW_LNS_advance_pc)
   109  	dwarf.Uleb128put(dctxt, lines, int64(lastlen))
   110  	dctxt.AddUint8(lines, 0) // start extended opcode
   111  	dwarf.Uleb128put(dctxt, lines, 1)
   112  	dctxt.AddUint8(lines, dwarf.DW_LNE_end_sequence)
   113  }
   114  
   115  func putpclcdelta(linkctxt *Link, dctxt dwCtxt, s *LSym, deltaPC uint64, deltaLC int64) {
   116  	// Choose a special opcode that minimizes the number of bytes needed to
   117  	// encode the remaining PC delta and LC delta.
   118  	var opcode int64
   119  	if deltaLC < LINE_BASE {
   120  		if deltaPC >= PC_RANGE {
   121  			opcode = OPCODE_BASE + (LINE_RANGE * PC_RANGE)
   122  		} else {
   123  			opcode = OPCODE_BASE + (LINE_RANGE * int64(deltaPC))
   124  		}
   125  	} else if deltaLC < LINE_BASE+LINE_RANGE {
   126  		if deltaPC >= PC_RANGE {
   127  			opcode = OPCODE_BASE + (deltaLC - LINE_BASE) + (LINE_RANGE * PC_RANGE)
   128  			if opcode > 255 {
   129  				opcode -= LINE_RANGE
   130  			}
   131  		} else {
   132  			opcode = OPCODE_BASE + (deltaLC - LINE_BASE) + (LINE_RANGE * int64(deltaPC))
   133  		}
   134  	} else {
   135  		if deltaPC <= PC_RANGE {
   136  			opcode = OPCODE_BASE + (LINE_RANGE - 1) + (LINE_RANGE * int64(deltaPC))
   137  			if opcode > 255 {
   138  				opcode = 255
   139  			}
   140  		} else {
   141  			// Use opcode 249 (pc+=23, lc+=5) or 255 (pc+=24, lc+=1).
   142  			//
   143  			// Let x=deltaPC-PC_RANGE.  If we use opcode 255, x will be the remaining
   144  			// deltaPC that we need to encode separately before emitting 255.  If we
   145  			// use opcode 249, we will need to encode x+1.  If x+1 takes one more
   146  			// byte to encode than x, then we use opcode 255.
   147  			//
   148  			// In all other cases x and x+1 take the same number of bytes to encode,
   149  			// so we use opcode 249, which may save us a byte in encoding deltaLC,
   150  			// for similar reasons.
   151  			switch deltaPC - PC_RANGE {
   152  			// PC_RANGE is the largest deltaPC we can encode in one byte, using
   153  			// DW_LNS_const_add_pc.
   154  			//
   155  			// (1<<16)-1 is the largest deltaPC we can encode in three bytes, using
   156  			// DW_LNS_fixed_advance_pc.
   157  			//
   158  			// (1<<(7n))-1 is the largest deltaPC we can encode in n+1 bytes for
   159  			// n=1,3,4,5,..., using DW_LNS_advance_pc.
   160  			case PC_RANGE, (1 << 7) - 1, (1 << 16) - 1, (1 << 21) - 1, (1 << 28) - 1,
   161  				(1 << 35) - 1, (1 << 42) - 1, (1 << 49) - 1, (1 << 56) - 1, (1 << 63) - 1:
   162  				opcode = 255
   163  			default:
   164  				opcode = OPCODE_BASE + LINE_RANGE*PC_RANGE - 1 // 249
   165  			}
   166  		}
   167  	}
   168  	if opcode < OPCODE_BASE || opcode > 255 {
   169  		panic(fmt.Sprintf("produced invalid special opcode %d", opcode))
   170  	}
   171  
   172  	// Subtract from deltaPC and deltaLC the amounts that the opcode will add.
   173  	deltaPC -= uint64((opcode - OPCODE_BASE) / LINE_RANGE)
   174  	deltaLC -= (opcode-OPCODE_BASE)%LINE_RANGE + LINE_BASE
   175  
   176  	// Encode deltaPC.
   177  	if deltaPC != 0 {
   178  		if deltaPC <= PC_RANGE {
   179  			// Adjust the opcode so that we can use the 1-byte DW_LNS_const_add_pc
   180  			// instruction.
   181  			opcode -= LINE_RANGE * int64(PC_RANGE-deltaPC)
   182  			if opcode < OPCODE_BASE {
   183  				panic(fmt.Sprintf("produced invalid special opcode %d", opcode))
   184  			}
   185  			dctxt.AddUint8(s, dwarf.DW_LNS_const_add_pc)
   186  		} else if (1<<14) <= deltaPC && deltaPC < (1<<16) {
   187  			dctxt.AddUint8(s, dwarf.DW_LNS_fixed_advance_pc)
   188  			dctxt.AddUint16(s, uint16(deltaPC))
   189  		} else {
   190  			dctxt.AddUint8(s, dwarf.DW_LNS_advance_pc)
   191  			dwarf.Uleb128put(dctxt, s, int64(deltaPC))
   192  		}
   193  	}
   194  
   195  	// Encode deltaLC.
   196  	if deltaLC != 0 {
   197  		dctxt.AddUint8(s, dwarf.DW_LNS_advance_line)
   198  		dwarf.Sleb128put(dctxt, s, deltaLC)
   199  	}
   200  
   201  	// Output the special opcode.
   202  	dctxt.AddUint8(s, uint8(opcode))
   203  }
   204  
   205  // implement dwarf.Context
   206  type dwCtxt struct{ *Link }
   207  
   208  func (c dwCtxt) PtrSize() int {
   209  	return c.Arch.PtrSize
   210  }
   211  func (c dwCtxt) Size(s dwarf.Sym) int64 {
   212  	return s.(*LSym).Size
   213  }
   214  func (c dwCtxt) AddInt(s dwarf.Sym, size int, i int64) {
   215  	ls := s.(*LSym)
   216  	ls.WriteInt(c.Link, ls.Size, size, i)
   217  }
   218  func (c dwCtxt) AddUint16(s dwarf.Sym, i uint16) {
   219  	c.AddInt(s, 2, int64(i))
   220  }
   221  func (c dwCtxt) AddUint8(s dwarf.Sym, i uint8) {
   222  	b := []byte{byte(i)}
   223  	c.AddBytes(s, b)
   224  }
   225  func (c dwCtxt) AddBytes(s dwarf.Sym, b []byte) {
   226  	ls := s.(*LSym)
   227  	ls.WriteBytes(c.Link, ls.Size, b)
   228  }
   229  func (c dwCtxt) AddString(s dwarf.Sym, v string) {
   230  	ls := s.(*LSym)
   231  	ls.WriteString(c.Link, ls.Size, len(v), v)
   232  	ls.WriteInt(c.Link, ls.Size, 1, 0)
   233  }
   234  func (c dwCtxt) AddAddress(s dwarf.Sym, data interface{}, value int64) {
   235  	ls := s.(*LSym)
   236  	size := c.PtrSize()
   237  	if data != nil {
   238  		rsym := data.(*LSym)
   239  		ls.WriteAddr(c.Link, ls.Size, size, rsym, value)
   240  	} else {
   241  		ls.WriteInt(c.Link, ls.Size, size, value)
   242  	}
   243  }
   244  func (c dwCtxt) AddCURelativeAddress(s dwarf.Sym, data interface{}, value int64) {
   245  	ls := s.(*LSym)
   246  	rsym := data.(*LSym)
   247  	ls.WriteCURelativeAddr(c.Link, ls.Size, rsym, value)
   248  }
   249  func (c dwCtxt) AddSectionOffset(s dwarf.Sym, size int, t interface{}, ofs int64) {
   250  	panic("should be used only in the linker")
   251  }
   252  func (c dwCtxt) AddDWARFAddrSectionOffset(s dwarf.Sym, t interface{}, ofs int64) {
   253  	size := 4
   254  	if isDwarf64(c.Link) {
   255  		size = 8
   256  	}
   257  
   258  	ls := s.(*LSym)
   259  	rsym := t.(*LSym)
   260  	ls.WriteAddr(c.Link, ls.Size, size, rsym, ofs)
   261  	r := &ls.R[len(ls.R)-1]
   262  	r.Type = objabi.R_DWARFSECREF
   263  }
   264  
   265  func (c dwCtxt) CurrentOffset(s dwarf.Sym) int64 {
   266  	ls := s.(*LSym)
   267  	return ls.Size
   268  }
   269  
   270  // Here "from" is a symbol corresponding to an inlined or concrete
   271  // function, "to" is the symbol for the corresponding abstract
   272  // function, and "dclIdx" is the index of the symbol of interest with
   273  // respect to the Dcl slice of the original pre-optimization version
   274  // of the inlined function.
   275  func (c dwCtxt) RecordDclReference(from dwarf.Sym, to dwarf.Sym, dclIdx int, inlIndex int) {
   276  	ls := from.(*LSym)
   277  	tls := to.(*LSym)
   278  	ridx := len(ls.R) - 1
   279  	c.Link.DwFixups.ReferenceChildDIE(ls, ridx, tls, dclIdx, inlIndex)
   280  }
   281  
   282  func (c dwCtxt) RecordChildDieOffsets(s dwarf.Sym, vars []*dwarf.Var, offsets []int32) {
   283  	ls := s.(*LSym)
   284  	c.Link.DwFixups.RegisterChildDIEOffsets(ls, vars, offsets)
   285  }
   286  
   287  func (c dwCtxt) Logf(format string, args ...interface{}) {
   288  	c.Link.Logf(format, args...)
   289  }
   290  
   291  func isDwarf64(ctxt *Link) bool {
   292  	return ctxt.Headtype == objabi.Haix
   293  }
   294  
   295  func (ctxt *Link) dwarfSym(s *LSym) (dwarfInfoSym, dwarfLocSym, dwarfRangesSym, dwarfAbsFnSym, dwarfDebugLines *LSym) {
   296  	if !s.Type.IsText() {
   297  		ctxt.Diag("dwarfSym of non-TEXT %v", s)
   298  	}
   299  	fn := s.Func()
   300  	if fn.dwarfInfoSym == nil {
   301  		fn.dwarfInfoSym = &LSym{
   302  			Type: objabi.SDWARFFCN,
   303  		}
   304  		if ctxt.Flag_locationlists {
   305  			fn.dwarfLocSym = &LSym{
   306  				Type: objabi.SDWARFLOC,
   307  			}
   308  		}
   309  		fn.dwarfRangesSym = &LSym{
   310  			Type: objabi.SDWARFRANGE,
   311  		}
   312  		fn.dwarfDebugLinesSym = &LSym{
   313  			Type: objabi.SDWARFLINES,
   314  		}
   315  		if s.WasInlined() {
   316  			fn.dwarfAbsFnSym = ctxt.DwFixups.AbsFuncDwarfSym(s)
   317  		}
   318  	}
   319  	return fn.dwarfInfoSym, fn.dwarfLocSym, fn.dwarfRangesSym, fn.dwarfAbsFnSym, fn.dwarfDebugLinesSym
   320  }
   321  
   322  // textPos returns the source position of the first instruction (prog)
   323  // of the specified function.
   324  func textPos(fn *LSym) src.XPos {
   325  	if p := fn.Func().Text; p != nil {
   326  		return p.Pos
   327  	}
   328  	return src.NoXPos
   329  }
   330  
   331  // populateDWARF fills in the DWARF Debugging Information Entries for
   332  // TEXT symbol 's'. The various DWARF symbols must already have been
   333  // initialized in InitTextSym.
   334  func (ctxt *Link) populateDWARF(curfn Func, s *LSym) {
   335  	myimportpath := ctxt.Pkgpath
   336  	if myimportpath == "" {
   337  		return
   338  	}
   339  
   340  	info, loc, ranges, absfunc, lines := ctxt.dwarfSym(s)
   341  	if info.Size != 0 {
   342  		ctxt.Diag("makeFuncDebugEntry double process %v", s)
   343  	}
   344  	var scopes []dwarf.Scope
   345  	var inlcalls dwarf.InlCalls
   346  	if ctxt.DebugInfo != nil {
   347  		scopes, inlcalls = ctxt.DebugInfo(ctxt, s, info, curfn)
   348  	}
   349  	var err error
   350  	dwctxt := dwCtxt{ctxt}
   351  	startPos := ctxt.InnermostPos(textPos(s))
   352  	if !startPos.IsKnown() || startPos.RelLine() != uint(s.Func().StartLine) {
   353  		panic("bad startPos")
   354  	}
   355  	fnstate := &dwarf.FnState{
   356  		Name:          s.Name,
   357  		Info:          info,
   358  		Loc:           loc,
   359  		Ranges:        ranges,
   360  		Absfn:         absfunc,
   361  		StartPC:       s,
   362  		Size:          s.Size,
   363  		StartPos:      startPos,
   364  		External:      !s.Static(),
   365  		Scopes:        scopes,
   366  		InlCalls:      inlcalls,
   367  		UseBASEntries: ctxt.UseBASEntries,
   368  	}
   369  	if absfunc != nil {
   370  		err = dwarf.PutAbstractFunc(dwctxt, fnstate)
   371  		if err != nil {
   372  			ctxt.Diag("emitting DWARF for %s failed: %v", s.Name, err)
   373  		}
   374  		err = dwarf.PutConcreteFunc(dwctxt, fnstate, s.Wrapper())
   375  	} else {
   376  		err = dwarf.PutDefaultFunc(dwctxt, fnstate, s.Wrapper())
   377  	}
   378  	if err != nil {
   379  		ctxt.Diag("emitting DWARF for %s failed: %v", s.Name, err)
   380  	}
   381  	// Fill in the debug lines symbol.
   382  	ctxt.generateDebugLinesSymbol(s, lines)
   383  }
   384  
   385  // DwarfIntConst creates a link symbol for an integer constant with the
   386  // given name, type and value.
   387  func (ctxt *Link) DwarfIntConst(name, typename string, val int64) {
   388  	myimportpath := ctxt.Pkgpath
   389  	if myimportpath == "" {
   390  		return
   391  	}
   392  	s := ctxt.LookupInit(dwarf.ConstInfoPrefix+myimportpath, func(s *LSym) {
   393  		s.Type = objabi.SDWARFCONST
   394  		ctxt.Data = append(ctxt.Data, s)
   395  	})
   396  	dwarf.PutIntConst(dwCtxt{ctxt}, s, ctxt.Lookup(dwarf.InfoPrefix+typename), myimportpath+"."+name, val)
   397  }
   398  
   399  // DwarfGlobal creates a link symbol containing a DWARF entry for
   400  // a global variable.
   401  func (ctxt *Link) DwarfGlobal(typename string, varSym *LSym) {
   402  	myimportpath := ctxt.Pkgpath
   403  	if myimportpath == "" || varSym.Local() {
   404  		return
   405  	}
   406  	varname := varSym.Name
   407  	dieSym := &LSym{
   408  		Type: objabi.SDWARFVAR,
   409  	}
   410  	varSym.NewVarInfo().dwarfInfoSym = dieSym
   411  	ctxt.Data = append(ctxt.Data, dieSym)
   412  	typeSym := ctxt.Lookup(dwarf.InfoPrefix + typename)
   413  	dwarf.PutGlobal(dwCtxt{ctxt}, dieSym, typeSym, varSym, varname)
   414  }
   415  
   416  func (ctxt *Link) DwarfAbstractFunc(curfn Func, s *LSym) {
   417  	absfn := ctxt.DwFixups.AbsFuncDwarfSym(s)
   418  	if absfn.Size != 0 {
   419  		ctxt.Diag("internal error: DwarfAbstractFunc double process %v", s)
   420  	}
   421  	if s.Func() == nil {
   422  		s.NewFuncInfo()
   423  	}
   424  	scopes, _ := ctxt.DebugInfo(ctxt, s, absfn, curfn)
   425  	dwctxt := dwCtxt{ctxt}
   426  	fnstate := dwarf.FnState{
   427  		Name:          s.Name,
   428  		Info:          absfn,
   429  		Absfn:         absfn,
   430  		StartPos:      ctxt.InnermostPos(curfn.Pos()),
   431  		External:      !s.Static(),
   432  		Scopes:        scopes,
   433  		UseBASEntries: ctxt.UseBASEntries,
   434  	}
   435  	if err := dwarf.PutAbstractFunc(dwctxt, &fnstate); err != nil {
   436  		ctxt.Diag("emitting DWARF for %s failed: %v", s.Name, err)
   437  	}
   438  }
   439  
   440  // This table is designed to aid in the creation of references between
   441  // DWARF subprogram DIEs.
   442  //
   443  // In most cases when one DWARF DIE has to refer to another DWARF DIE,
   444  // the target of the reference has an LSym, which makes it easy to use
   445  // the existing relocation mechanism. For DWARF inlined routine DIEs,
   446  // however, the subprogram DIE has to refer to a child
   447  // parameter/variable DIE of the abstract subprogram. This child DIE
   448  // doesn't have an LSym, and also of interest is the fact that when
   449  // DWARF generation is happening for inlined function F within caller
   450  // G, it's possible that DWARF generation hasn't happened yet for F,
   451  // so there is no way to know the offset of a child DIE within F's
   452  // abstract function. Making matters more complex, each inlined
   453  // instance of F may refer to a subset of the original F's variables
   454  // (depending on what happens with optimization, some vars may be
   455  // eliminated).
   456  //
   457  // The fixup table below helps overcome this hurdle. At the point
   458  // where a parameter/variable reference is made (via a call to
   459  // "ReferenceChildDIE"), a fixup record is generate that records
   460  // the relocation that is targeting that child variable. At a later
   461  // point when the abstract function DIE is emitted, there will be
   462  // a call to "RegisterChildDIEOffsets", at which point the offsets
   463  // needed to apply fixups are captured. Finally, once the parallel
   464  // portion of the compilation is done, fixups can actually be applied
   465  // during the "Finalize" method (this can't be done during the
   466  // parallel portion of the compile due to the possibility of data
   467  // races).
   468  //
   469  // This table is also used to record the "precursor" function node for
   470  // each function that is the target of an inline -- child DIE references
   471  // have to be made with respect to the original pre-optimization
   472  // version of the function (to allow for the fact that each inlined
   473  // body may be optimized differently).
   474  type DwarfFixupTable struct {
   475  	ctxt      *Link
   476  	mu        sync.Mutex
   477  	symtab    map[*LSym]int // maps abstract fn LSYM to index in svec
   478  	svec      []symFixups
   479  	precursor map[*LSym]fnState // maps fn Lsym to precursor Node, absfn sym
   480  }
   481  
   482  type symFixups struct {
   483  	fixups   []relFixup
   484  	doffsets []declOffset
   485  	inlIndex int32
   486  	defseen  bool
   487  }
   488  
   489  type declOffset struct {
   490  	// Index of variable within DCL list of pre-optimization function
   491  	dclIdx int32
   492  	// Offset of var's child DIE with respect to containing subprogram DIE
   493  	offset int32
   494  }
   495  
   496  type relFixup struct {
   497  	refsym *LSym
   498  	relidx int32
   499  	dclidx int32
   500  }
   501  
   502  type fnState struct {
   503  	// precursor function
   504  	precursor Func
   505  	// abstract function symbol
   506  	absfn *LSym
   507  }
   508  
   509  func NewDwarfFixupTable(ctxt *Link) *DwarfFixupTable {
   510  	return &DwarfFixupTable{
   511  		ctxt:      ctxt,
   512  		symtab:    make(map[*LSym]int),
   513  		precursor: make(map[*LSym]fnState),
   514  	}
   515  }
   516  
   517  func (ft *DwarfFixupTable) GetPrecursorFunc(s *LSym) Func {
   518  	if fnstate, found := ft.precursor[s]; found {
   519  		return fnstate.precursor
   520  	}
   521  	return nil
   522  }
   523  
   524  func (ft *DwarfFixupTable) SetPrecursorFunc(s *LSym, fn Func) {
   525  	if _, found := ft.precursor[s]; found {
   526  		ft.ctxt.Diag("internal error: DwarfFixupTable.SetPrecursorFunc double call on %v", s)
   527  	}
   528  
   529  	// initialize abstract function symbol now. This is done here so
   530  	// as to avoid data races later on during the parallel portion of
   531  	// the back end.
   532  	absfn := ft.ctxt.LookupDerived(s, dwarf.InfoPrefix+s.Name+dwarf.AbstractFuncSuffix)
   533  	absfn.Set(AttrDuplicateOK, true)
   534  	absfn.Type = objabi.SDWARFABSFCN
   535  	ft.ctxt.Data = append(ft.ctxt.Data, absfn)
   536  
   537  	// In the case of "late" inlining (inlines that happen during
   538  	// wrapper generation as opposed to the main inlining phase) it's
   539  	// possible that we didn't cache the abstract function sym for the
   540  	// text symbol -- do so now if needed. See issue 38068.
   541  	if fn := s.Func(); fn != nil && fn.dwarfAbsFnSym == nil {
   542  		fn.dwarfAbsFnSym = absfn
   543  	}
   544  
   545  	ft.precursor[s] = fnState{precursor: fn, absfn: absfn}
   546  }
   547  
   548  // Make a note of a child DIE reference: relocation 'ridx' within symbol 's'
   549  // is targeting child 'c' of DIE with symbol 'tgt'.
   550  func (ft *DwarfFixupTable) ReferenceChildDIE(s *LSym, ridx int, tgt *LSym, dclidx int, inlIndex int) {
   551  	// Protect against concurrent access if multiple backend workers
   552  	ft.mu.Lock()
   553  	defer ft.mu.Unlock()
   554  
   555  	// Create entry for symbol if not already present.
   556  	idx, found := ft.symtab[tgt]
   557  	if !found {
   558  		ft.svec = append(ft.svec, symFixups{inlIndex: int32(inlIndex)})
   559  		idx = len(ft.svec) - 1
   560  		ft.symtab[tgt] = idx
   561  	}
   562  
   563  	// Do we have child DIE offsets available? If so, then apply them,
   564  	// otherwise create a fixup record.
   565  	sf := &ft.svec[idx]
   566  	if len(sf.doffsets) > 0 {
   567  		found := false
   568  		for _, do := range sf.doffsets {
   569  			if do.dclIdx == int32(dclidx) {
   570  				off := do.offset
   571  				s.R[ridx].Add += int64(off)
   572  				found = true
   573  				break
   574  			}
   575  		}
   576  		if !found {
   577  			ft.ctxt.Diag("internal error: DwarfFixupTable.ReferenceChildDIE unable to locate child DIE offset for dclIdx=%d src=%v tgt=%v", dclidx, s, tgt)
   578  		}
   579  	} else {
   580  		sf.fixups = append(sf.fixups, relFixup{s, int32(ridx), int32(dclidx)})
   581  	}
   582  }
   583  
   584  // Called once DWARF generation is complete for a given abstract function,
   585  // whose children might have been referenced via a call above. Stores
   586  // the offsets for any child DIEs (vars, params) so that they can be
   587  // consumed later in on DwarfFixupTable.Finalize, which applies any
   588  // outstanding fixups.
   589  func (ft *DwarfFixupTable) RegisterChildDIEOffsets(s *LSym, vars []*dwarf.Var, coffsets []int32) {
   590  	// Length of these two slices should agree
   591  	if len(vars) != len(coffsets) {
   592  		ft.ctxt.Diag("internal error: RegisterChildDIEOffsets vars/offsets length mismatch")
   593  		return
   594  	}
   595  
   596  	// Generate the slice of declOffset's based in vars/coffsets
   597  	doffsets := make([]declOffset, len(coffsets))
   598  	for i := range coffsets {
   599  		doffsets[i].dclIdx = vars[i].ChildIndex
   600  		doffsets[i].offset = coffsets[i]
   601  	}
   602  
   603  	ft.mu.Lock()
   604  	defer ft.mu.Unlock()
   605  
   606  	// Store offsets for this symbol.
   607  	idx, found := ft.symtab[s]
   608  	if !found {
   609  		sf := symFixups{inlIndex: -1, defseen: true, doffsets: doffsets}
   610  		ft.svec = append(ft.svec, sf)
   611  		ft.symtab[s] = len(ft.svec) - 1
   612  	} else {
   613  		sf := &ft.svec[idx]
   614  		sf.doffsets = doffsets
   615  		sf.defseen = true
   616  	}
   617  }
   618  
   619  func (ft *DwarfFixupTable) processFixups(slot int, s *LSym) {
   620  	sf := &ft.svec[slot]
   621  	for _, f := range sf.fixups {
   622  		dfound := false
   623  		for _, doffset := range sf.doffsets {
   624  			if doffset.dclIdx == f.dclidx {
   625  				f.refsym.R[f.relidx].Add += int64(doffset.offset)
   626  				dfound = true
   627  				break
   628  			}
   629  		}
   630  		if !dfound {
   631  			ft.ctxt.Diag("internal error: DwarfFixupTable has orphaned fixup on %v targeting %v relidx=%d dclidx=%d", f.refsym, s, f.relidx, f.dclidx)
   632  		}
   633  	}
   634  }
   635  
   636  // return the LSym corresponding to the 'abstract subprogram' DWARF
   637  // info entry for a function.
   638  func (ft *DwarfFixupTable) AbsFuncDwarfSym(fnsym *LSym) *LSym {
   639  	// Protect against concurrent access if multiple backend workers
   640  	ft.mu.Lock()
   641  	defer ft.mu.Unlock()
   642  
   643  	if fnstate, found := ft.precursor[fnsym]; found {
   644  		return fnstate.absfn
   645  	}
   646  	ft.ctxt.Diag("internal error: AbsFuncDwarfSym requested for %v, not seen during inlining", fnsym)
   647  	return nil
   648  }
   649  
   650  // Called after all functions have been compiled; the main job of this
   651  // function is to identify cases where there are outstanding fixups.
   652  // This scenario crops up when we have references to variables of an
   653  // inlined routine, but that routine is defined in some other package.
   654  // This helper walks through and locate these fixups, then invokes a
   655  // helper to create an abstract subprogram DIE for each one.
   656  func (ft *DwarfFixupTable) Finalize(myimportpath string, trace bool) {
   657  	if trace {
   658  		ft.ctxt.Logf("DwarfFixupTable.Finalize invoked for %s\n", myimportpath)
   659  	}
   660  
   661  	// Collect up the keys from the precursor map, then sort the
   662  	// resulting list (don't want to rely on map ordering here).
   663  	fns := make([]*LSym, len(ft.precursor))
   664  	idx := 0
   665  	for fn := range ft.precursor {
   666  		fns[idx] = fn
   667  		idx++
   668  	}
   669  	slices.SortFunc(fns, func(a, b *LSym) int {
   670  		return strings.Compare(a.Name, b.Name)
   671  	})
   672  
   673  	// Should not be called during parallel portion of compilation.
   674  	if ft.ctxt.InParallel {
   675  		ft.ctxt.Diag("internal error: DwarfFixupTable.Finalize call during parallel backend")
   676  	}
   677  
   678  	// Generate any missing abstract functions.
   679  	for _, s := range fns {
   680  		absfn := ft.AbsFuncDwarfSym(s)
   681  		slot, found := ft.symtab[absfn]
   682  		if !found || !ft.svec[slot].defseen {
   683  			ft.ctxt.GenAbstractFunc(s)
   684  		}
   685  	}
   686  
   687  	// Apply fixups.
   688  	for _, s := range fns {
   689  		absfn := ft.AbsFuncDwarfSym(s)
   690  		slot, found := ft.symtab[absfn]
   691  		if !found {
   692  			ft.ctxt.Diag("internal error: DwarfFixupTable.Finalize orphan abstract function for %v", s)
   693  		} else {
   694  			ft.processFixups(slot, s)
   695  		}
   696  	}
   697  }
   698  

View as plain text