github.com/gagliardetto/golang-go@v0.0.0-20201020153340-53909ea70814/cmd/internal/obj/link.go (about)

     1  // Derived from Inferno utils/6l/l.h and related files.
     2  // https://bitbucket.org/inferno-os/inferno-os/src/default/utils/6l/l.h
     3  //
     4  //	Copyright © 1994-1999 Lucent Technologies Inc.  All rights reserved.
     5  //	Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
     6  //	Portions Copyright © 1997-1999 Vita Nuova Limited
     7  //	Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
     8  //	Portions Copyright © 2004,2006 Bruce Ellis
     9  //	Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
    10  //	Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
    11  //	Portions Copyright © 2009 The Go Authors. All rights reserved.
    12  //
    13  // Permission is hereby granted, free of charge, to any person obtaining a copy
    14  // of this software and associated documentation files (the "Software"), to deal
    15  // in the Software without restriction, including without limitation the rights
    16  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    17  // copies of the Software, and to permit persons to whom the Software is
    18  // furnished to do so, subject to the following conditions:
    19  //
    20  // The above copyright notice and this permission notice shall be included in
    21  // all copies or substantial portions of the Software.
    22  //
    23  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    24  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    25  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
    26  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    27  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    28  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    29  // THE SOFTWARE.
    30  
    31  package obj
    32  
    33  import (
    34  	"bufio"
    35  	"github.com/gagliardetto/golang-go/cmd/internal/dwarf"
    36  	"github.com/gagliardetto/golang-go/cmd/internal/objabi"
    37  	"github.com/gagliardetto/golang-go/cmd/internal/src"
    38  	"github.com/gagliardetto/golang-go/cmd/internal/sys"
    39  	"fmt"
    40  	"sync"
    41  )
    42  
    43  // An Addr is an argument to an instruction.
    44  // The general forms and their encodings are:
    45  //
    46  //	sym±offset(symkind)(reg)(index*scale)
    47  //		Memory reference at address &sym(symkind) + offset + reg + index*scale.
    48  //		Any of sym(symkind), ±offset, (reg), (index*scale), and *scale can be omitted.
    49  //		If (reg) and *scale are both omitted, the resulting expression (index) is parsed as (reg).
    50  //		To force a parsing as index*scale, write (index*1).
    51  //		Encoding:
    52  //			type = TYPE_MEM
    53  //			name = symkind (NAME_AUTO, ...) or 0 (NAME_NONE)
    54  //			sym = sym
    55  //			offset = ±offset
    56  //			reg = reg (REG_*)
    57  //			index = index (REG_*)
    58  //			scale = scale (1, 2, 4, 8)
    59  //
    60  //	$<mem>
    61  //		Effective address of memory reference <mem>, defined above.
    62  //		Encoding: same as memory reference, but type = TYPE_ADDR.
    63  //
    64  //	$<±integer value>
    65  //		This is a special case of $<mem>, in which only ±offset is present.
    66  //		It has a separate type for easy recognition.
    67  //		Encoding:
    68  //			type = TYPE_CONST
    69  //			offset = ±integer value
    70  //
    71  //	*<mem>
    72  //		Indirect reference through memory reference <mem>, defined above.
    73  //		Only used on x86 for CALL/JMP *sym(SB), which calls/jumps to a function
    74  //		pointer stored in the data word sym(SB), not a function named sym(SB).
    75  //		Encoding: same as above, but type = TYPE_INDIR.
    76  //
    77  //	$*$<mem>
    78  //		No longer used.
    79  //		On machines with actual SB registers, $*$<mem> forced the
    80  //		instruction encoding to use a full 32-bit constant, never a
    81  //		reference relative to SB.
    82  //
    83  //	$<floating point literal>
    84  //		Floating point constant value.
    85  //		Encoding:
    86  //			type = TYPE_FCONST
    87  //			val = floating point value
    88  //
    89  //	$<string literal, up to 8 chars>
    90  //		String literal value (raw bytes used for DATA instruction).
    91  //		Encoding:
    92  //			type = TYPE_SCONST
    93  //			val = string
    94  //
    95  //	<register name>
    96  //		Any register: integer, floating point, control, segment, and so on.
    97  //		If looking for specific register kind, must check type and reg value range.
    98  //		Encoding:
    99  //			type = TYPE_REG
   100  //			reg = reg (REG_*)
   101  //
   102  //	x(PC)
   103  //		Encoding:
   104  //			type = TYPE_BRANCH
   105  //			val = Prog* reference OR ELSE offset = target pc (branch takes priority)
   106  //
   107  //	$±x-±y
   108  //		Final argument to TEXT, specifying local frame size x and argument size y.
   109  //		In this form, x and y are integer literals only, not arbitrary expressions.
   110  //		This avoids parsing ambiguities due to the use of - as a separator.
   111  //		The ± are optional.
   112  //		If the final argument to TEXT omits the -±y, the encoding should still
   113  //		use TYPE_TEXTSIZE (not TYPE_CONST), with u.argsize = ArgsSizeUnknown.
   114  //		Encoding:
   115  //			type = TYPE_TEXTSIZE
   116  //			offset = x
   117  //			val = int32(y)
   118  //
   119  //	reg<<shift, reg>>shift, reg->shift, reg@>shift
   120  //		Shifted register value, for ARM and ARM64.
   121  //		In this form, reg must be a register and shift can be a register or an integer constant.
   122  //		Encoding:
   123  //			type = TYPE_SHIFT
   124  //		On ARM:
   125  //			offset = (reg&15) | shifttype<<5 | count
   126  //			shifttype = 0, 1, 2, 3 for <<, >>, ->, @>
   127  //			count = (reg&15)<<8 | 1<<4 for a register shift count, (n&31)<<7 for an integer constant.
   128  //		On ARM64:
   129  //			offset = (reg&31)<<16 | shifttype<<22 | (count&63)<<10
   130  //			shifttype = 0, 1, 2 for <<, >>, ->
   131  //
   132  //	(reg, reg)
   133  //		A destination register pair. When used as the last argument of an instruction,
   134  //		this form makes clear that both registers are destinations.
   135  //		Encoding:
   136  //			type = TYPE_REGREG
   137  //			reg = first register
   138  //			offset = second register
   139  //
   140  //	[reg, reg, reg-reg]
   141  //		Register list for ARM, ARM64, 386/AMD64.
   142  //		Encoding:
   143  //			type = TYPE_REGLIST
   144  //		On ARM:
   145  //			offset = bit mask of registers in list; R0 is low bit.
   146  //		On ARM64:
   147  //			offset = register count (Q:size) | arrangement (opcode) | first register
   148  //		On 386/AMD64:
   149  //			reg = range low register
   150  //			offset = 2 packed registers + kind tag (see x86.EncodeRegisterRange)
   151  //
   152  //	reg, reg
   153  //		Register pair for ARM.
   154  //		TYPE_REGREG2
   155  //
   156  //	(reg+reg)
   157  //		Register pair for PPC64.
   158  //		Encoding:
   159  //			type = TYPE_MEM
   160  //			reg = first register
   161  //			index = second register
   162  //			scale = 1
   163  //
   164  //	reg.[US]XT[BHWX]
   165  //		Register extension for ARM64
   166  //		Encoding:
   167  //			type = TYPE_REG
   168  //			reg = REG_[US]XT[BHWX] + register + shift amount
   169  //			offset = ((reg&31) << 16) | (exttype << 13) | (amount<<10)
   170  //
   171  //	reg.<T>
   172  //		Register arrangement for ARM64 SIMD register
   173  //		e.g.: V1.S4, V2.S2, V7.D2, V2.H4, V6.B16
   174  //		Encoding:
   175  //			type = TYPE_REG
   176  //			reg = REG_ARNG + register + arrangement
   177  //
   178  //	reg.<T>[index]
   179  //		Register element for ARM64
   180  //		Encoding:
   181  //			type = TYPE_REG
   182  //			reg = REG_ELEM + register + arrangement
   183  //			index = element index
   184  
   185  type Addr struct {
   186  	Reg    int16
   187  	Index  int16
   188  	Scale  int16 // Sometimes holds a register.
   189  	Type   AddrType
   190  	Name   AddrName
   191  	Class  int8
   192  	Offset int64
   193  	Sym    *LSym
   194  
   195  	// argument value:
   196  	//	for TYPE_SCONST, a string
   197  	//	for TYPE_FCONST, a float64
   198  	//	for TYPE_BRANCH, a *Prog (optional)
   199  	//	for TYPE_TEXTSIZE, an int32 (optional)
   200  	Val interface{}
   201  }
   202  
   203  type AddrName int8
   204  
   205  const (
   206  	NAME_NONE AddrName = iota
   207  	NAME_EXTERN
   208  	NAME_STATIC
   209  	NAME_AUTO
   210  	NAME_PARAM
   211  	// A reference to name@GOT(SB) is a reference to the entry in the global offset
   212  	// table for 'name'.
   213  	NAME_GOTREF
   214  	// Indicates that this is a reference to a TOC anchor.
   215  	NAME_TOCREF
   216  )
   217  
   218  //go:generate stringer -type AddrType
   219  
   220  type AddrType uint8
   221  
   222  const (
   223  	TYPE_NONE AddrType = iota
   224  	TYPE_BRANCH
   225  	TYPE_TEXTSIZE
   226  	TYPE_MEM
   227  	TYPE_CONST
   228  	TYPE_FCONST
   229  	TYPE_SCONST
   230  	TYPE_REG
   231  	TYPE_ADDR
   232  	TYPE_SHIFT
   233  	TYPE_REGREG
   234  	TYPE_REGREG2
   235  	TYPE_INDIR
   236  	TYPE_REGLIST
   237  )
   238  
   239  // Prog describes a single machine instruction.
   240  //
   241  // The general instruction form is:
   242  //
   243  //	(1) As.Scond From [, ...RestArgs], To
   244  //	(2) As.Scond From, Reg [, ...RestArgs], To, RegTo2
   245  //
   246  // where As is an opcode and the others are arguments:
   247  // From, Reg are sources, and To, RegTo2 are destinations.
   248  // RestArgs can hold additional sources and destinations.
   249  // Usually, not all arguments are present.
   250  // For example, MOVL R1, R2 encodes using only As=MOVL, From=R1, To=R2.
   251  // The Scond field holds additional condition bits for systems (like arm)
   252  // that have generalized conditional execution.
   253  // (2) form is present for compatibility with older code,
   254  // to avoid too much changes in a single swing.
   255  // (1) scheme is enough to express any kind of operand combination.
   256  //
   257  // Jump instructions use the Pcond field to point to the target instruction,
   258  // which must be in the same linked list as the jump instruction.
   259  //
   260  // The Progs for a given function are arranged in a list linked through the Link field.
   261  //
   262  // Each Prog is charged to a specific source line in the debug information,
   263  // specified by Pos.Line().
   264  // Every Prog has a Ctxt field that defines its context.
   265  // For performance reasons, Progs usually are usually bulk allocated, cached, and reused;
   266  // those bulk allocators should always be used, rather than new(Prog).
   267  //
   268  // The other fields not yet mentioned are for use by the back ends and should
   269  // be left zeroed by creators of Prog lists.
   270  type Prog struct {
   271  	Ctxt     *Link    // linker context
   272  	Link     *Prog    // next Prog in linked list
   273  	From     Addr     // first source operand
   274  	RestArgs []Addr   // can pack any operands that not fit into {Prog.From, Prog.To}
   275  	To       Addr     // destination operand (second is RegTo2 below)
   276  	Pcond    *Prog    // target of conditional jump
   277  	Forwd    *Prog    // for x86 back end
   278  	Rel      *Prog    // for x86, arm back ends
   279  	Pc       int64    // for back ends or assembler: virtual or actual program counter, depending on phase
   280  	Pos      src.XPos // source position of this instruction
   281  	Spadj    int32    // effect of instruction on stack pointer (increment or decrement amount)
   282  	As       As       // assembler opcode
   283  	Reg      int16    // 2nd source operand
   284  	RegTo2   int16    // 2nd destination operand
   285  	Mark     uint16   // bitmask of arch-specific items
   286  	Optab    uint16   // arch-specific opcode index
   287  	Scond    uint8    // bits that describe instruction suffixes (e.g. ARM conditions)
   288  	Back     uint8    // for x86 back end: backwards branch state
   289  	Ft       uint8    // for x86 back end: type index of Prog.From
   290  	Tt       uint8    // for x86 back end: type index of Prog.To
   291  	Isize    uint8    // for x86 back end: size of the instruction in bytes
   292  }
   293  
   294  // From3Type returns p.GetFrom3().Type, or TYPE_NONE when
   295  // p.GetFrom3() returns nil.
   296  //
   297  // Deprecated: for the same reasons as Prog.GetFrom3.
   298  func (p *Prog) From3Type() AddrType {
   299  	if p.RestArgs == nil {
   300  		return TYPE_NONE
   301  	}
   302  	return p.RestArgs[0].Type
   303  }
   304  
   305  // GetFrom3 returns second source operand (the first is Prog.From).
   306  // In combination with Prog.From and Prog.To it makes common 3 operand
   307  // case easier to use.
   308  //
   309  // Should be used only when RestArgs is set with SetFrom3.
   310  //
   311  // Deprecated: better use RestArgs directly or define backend-specific getters.
   312  // Introduced to simplify transition to []Addr.
   313  // Usage of this is discouraged due to fragility and lack of guarantees.
   314  func (p *Prog) GetFrom3() *Addr {
   315  	if p.RestArgs == nil {
   316  		return nil
   317  	}
   318  	return &p.RestArgs[0]
   319  }
   320  
   321  // SetFrom3 assigns []Addr{a} to p.RestArgs.
   322  // In pair with Prog.GetFrom3 it can help in emulation of Prog.From3.
   323  //
   324  // Deprecated: for the same reasons as Prog.GetFrom3.
   325  func (p *Prog) SetFrom3(a Addr) {
   326  	p.RestArgs = []Addr{a}
   327  }
   328  
   329  // An As denotes an assembler opcode.
   330  // There are some portable opcodes, declared here in package obj,
   331  // that are common to all architectures.
   332  // However, the majority of opcodes are arch-specific
   333  // and are declared in their respective architecture's subpackage.
   334  type As int16
   335  
   336  // These are the portable opcodes.
   337  const (
   338  	AXXX As = iota
   339  	ACALL
   340  	ADUFFCOPY
   341  	ADUFFZERO
   342  	AEND
   343  	AFUNCDATA
   344  	AJMP
   345  	ANOP
   346  	APCALIGN
   347  	APCDATA
   348  	ARET
   349  	AGETCALLERPC
   350  	ATEXT
   351  	AUNDEF
   352  	A_ARCHSPECIFIC
   353  )
   354  
   355  // Each architecture is allotted a distinct subspace of opcode values
   356  // for declaring its arch-specific opcodes.
   357  // Within this subspace, the first arch-specific opcode should be
   358  // at offset A_ARCHSPECIFIC.
   359  //
   360  // Subspaces are aligned to a power of two so opcodes can be masked
   361  // with AMask and used as compact array indices.
   362  const (
   363  	ABase386 = (1 + iota) << 11
   364  	ABaseARM
   365  	ABaseAMD64
   366  	ABasePPC64
   367  	ABaseARM64
   368  	ABaseMIPS
   369  	ABaseRISCV
   370  	ABaseS390X
   371  	ABaseWasm
   372  
   373  	AllowedOpCodes = 1 << 11            // The number of opcodes available for any given architecture.
   374  	AMask          = AllowedOpCodes - 1 // AND with this to use the opcode as an array index.
   375  )
   376  
   377  // An LSym is the sort of symbol that is written to an object file.
   378  // It represents Go symbols in a flat pkg+"."+name namespace.
   379  type LSym struct {
   380  	Name string
   381  	Type objabi.SymKind
   382  	Attribute
   383  
   384  	RefIdx int // Index of this symbol in the symbol reference list.
   385  	Size   int64
   386  	Gotype *LSym
   387  	P      []byte
   388  	R      []Reloc
   389  
   390  	Func *FuncInfo
   391  
   392  	Pkg    string
   393  	PkgIdx int32
   394  	SymIdx int32 // TODO: replace RefIdx
   395  }
   396  
   397  // A FuncInfo contains extra fields for STEXT symbols.
   398  type FuncInfo struct {
   399  	Args     int32
   400  	Locals   int32
   401  	Text     *Prog
   402  	Autot    map[*LSym]struct{}
   403  	Pcln     Pcln
   404  	InlMarks []InlMark
   405  
   406  	dwarfInfoSym       *LSym
   407  	dwarfLocSym        *LSym
   408  	dwarfRangesSym     *LSym
   409  	dwarfAbsFnSym      *LSym
   410  	dwarfDebugLinesSym *LSym
   411  
   412  	GCArgs             *LSym
   413  	GCLocals           *LSym
   414  	GCRegs             *LSym
   415  	StackObjects       *LSym
   416  	OpenCodedDeferInfo *LSym
   417  
   418  	FuncInfoSym *LSym
   419  }
   420  
   421  type InlMark struct {
   422  	// When unwinding from an instruction in an inlined body, mark
   423  	// where we should unwind to.
   424  	// id records the global inlining id of the inlined body.
   425  	// p records the location of an instruction in the parent (inliner) frame.
   426  	p  *Prog
   427  	id int32
   428  }
   429  
   430  // Mark p as the instruction to set as the pc when
   431  // "unwinding" the inlining global frame id. Usually it should be
   432  // instruction with a file:line at the callsite, and occur
   433  // just before the body of the inlined function.
   434  func (fi *FuncInfo) AddInlMark(p *Prog, id int32) {
   435  	fi.InlMarks = append(fi.InlMarks, InlMark{p: p, id: id})
   436  }
   437  
   438  // Record the type symbol for an auto variable so that the linker
   439  // an emit DWARF type information for the type.
   440  func (fi *FuncInfo) RecordAutoType(gotype *LSym) {
   441  	if fi.Autot == nil {
   442  		fi.Autot = make(map[*LSym]struct{})
   443  	}
   444  	fi.Autot[gotype] = struct{}{}
   445  }
   446  
   447  //go:generate stringer -type ABI
   448  
   449  // ABI is the calling convention of a text symbol.
   450  type ABI uint8
   451  
   452  const (
   453  	// ABI0 is the stable stack-based ABI. It's important that the
   454  	// value of this is "0": we can't distinguish between
   455  	// references to data and ABI0 text symbols in assembly code,
   456  	// and hence this doesn't distinguish between symbols without
   457  	// an ABI and text symbols with ABI0.
   458  	ABI0 ABI = iota
   459  
   460  	// ABIInternal is the internal ABI that may change between Go
   461  	// versions. All Go functions use the internal ABI and the
   462  	// compiler generates wrappers for calls to and from other
   463  	// ABIs.
   464  	ABIInternal
   465  
   466  	ABICount
   467  )
   468  
   469  // Attribute is a set of symbol attributes.
   470  type Attribute uint32
   471  
   472  const (
   473  	AttrDuplicateOK Attribute = 1 << iota
   474  	AttrCFunc
   475  	AttrNoSplit
   476  	AttrLeaf
   477  	AttrWrapper
   478  	AttrNeedCtxt
   479  	AttrNoFrame
   480  	AttrSeenGlobl
   481  	AttrOnList
   482  	AttrStatic
   483  
   484  	// MakeTypelink means that the type should have an entry in the typelink table.
   485  	AttrMakeTypelink
   486  
   487  	// ReflectMethod means the function may call reflect.Type.Method or
   488  	// reflect.Type.MethodByName. Matching is imprecise (as reflect.Type
   489  	// can be used through a custom interface), so ReflectMethod may be
   490  	// set in some cases when the reflect package is not called.
   491  	//
   492  	// Used by the linker to determine what methods can be pruned.
   493  	AttrReflectMethod
   494  
   495  	// Local means make the symbol local even when compiling Go code to reference Go
   496  	// symbols in other shared libraries, as in this mode symbols are global by
   497  	// default. "local" here means in the sense of the dynamic linker, i.e. not
   498  	// visible outside of the module (shared library or executable) that contains its
   499  	// definition. (When not compiling to support Go shared libraries, all symbols are
   500  	// local in this sense unless there is a cgo_export_* directive).
   501  	AttrLocal
   502  
   503  	// For function symbols; indicates that the specified function was the
   504  	// target of an inline during compilation
   505  	AttrWasInlined
   506  
   507  	// TopFrame means that this function is an entry point and unwinders should not
   508  	// keep unwinding beyond this frame.
   509  	AttrTopFrame
   510  
   511  	// Indexed indicates this symbol has been assigned with an index (when using the
   512  	// new object file format).
   513  	AttrIndexed
   514  
   515  	// attrABIBase is the value at which the ABI is encoded in
   516  	// Attribute. This must be last; all bits after this are
   517  	// assumed to be an ABI value.
   518  	//
   519  	// MUST BE LAST since all bits above this comprise the ABI.
   520  	attrABIBase
   521  )
   522  
   523  func (a Attribute) DuplicateOK() bool   { return a&AttrDuplicateOK != 0 }
   524  func (a Attribute) MakeTypelink() bool  { return a&AttrMakeTypelink != 0 }
   525  func (a Attribute) CFunc() bool         { return a&AttrCFunc != 0 }
   526  func (a Attribute) NoSplit() bool       { return a&AttrNoSplit != 0 }
   527  func (a Attribute) Leaf() bool          { return a&AttrLeaf != 0 }
   528  func (a Attribute) SeenGlobl() bool     { return a&AttrSeenGlobl != 0 }
   529  func (a Attribute) OnList() bool        { return a&AttrOnList != 0 }
   530  func (a Attribute) ReflectMethod() bool { return a&AttrReflectMethod != 0 }
   531  func (a Attribute) Local() bool         { return a&AttrLocal != 0 }
   532  func (a Attribute) Wrapper() bool       { return a&AttrWrapper != 0 }
   533  func (a Attribute) NeedCtxt() bool      { return a&AttrNeedCtxt != 0 }
   534  func (a Attribute) NoFrame() bool       { return a&AttrNoFrame != 0 }
   535  func (a Attribute) Static() bool        { return a&AttrStatic != 0 }
   536  func (a Attribute) WasInlined() bool    { return a&AttrWasInlined != 0 }
   537  func (a Attribute) TopFrame() bool      { return a&AttrTopFrame != 0 }
   538  func (a Attribute) Indexed() bool       { return a&AttrIndexed != 0 }
   539  
   540  func (a *Attribute) Set(flag Attribute, value bool) {
   541  	if value {
   542  		*a |= flag
   543  	} else {
   544  		*a &^= flag
   545  	}
   546  }
   547  
   548  func (a Attribute) ABI() ABI { return ABI(a / attrABIBase) }
   549  func (a *Attribute) SetABI(abi ABI) {
   550  	const mask = 1 // Only one ABI bit for now.
   551  	*a = (*a &^ (mask * attrABIBase)) | Attribute(abi)*attrABIBase
   552  }
   553  
   554  var textAttrStrings = [...]struct {
   555  	bit Attribute
   556  	s   string
   557  }{
   558  	{bit: AttrDuplicateOK, s: "DUPOK"},
   559  	{bit: AttrMakeTypelink, s: ""},
   560  	{bit: AttrCFunc, s: "CFUNC"},
   561  	{bit: AttrNoSplit, s: "NOSPLIT"},
   562  	{bit: AttrLeaf, s: "LEAF"},
   563  	{bit: AttrSeenGlobl, s: ""},
   564  	{bit: AttrOnList, s: ""},
   565  	{bit: AttrReflectMethod, s: "REFLECTMETHOD"},
   566  	{bit: AttrLocal, s: "LOCAL"},
   567  	{bit: AttrWrapper, s: "WRAPPER"},
   568  	{bit: AttrNeedCtxt, s: "NEEDCTXT"},
   569  	{bit: AttrNoFrame, s: "NOFRAME"},
   570  	{bit: AttrStatic, s: "STATIC"},
   571  	{bit: AttrWasInlined, s: ""},
   572  	{bit: AttrTopFrame, s: "TOPFRAME"},
   573  	{bit: AttrIndexed, s: ""},
   574  }
   575  
   576  // TextAttrString formats a for printing in as part of a TEXT prog.
   577  func (a Attribute) TextAttrString() string {
   578  	var s string
   579  	for _, x := range textAttrStrings {
   580  		if a&x.bit != 0 {
   581  			if x.s != "" {
   582  				s += x.s + "|"
   583  			}
   584  			a &^= x.bit
   585  		}
   586  	}
   587  	switch a.ABI() {
   588  	case ABI0:
   589  	case ABIInternal:
   590  		s += "ABIInternal|"
   591  		a.SetABI(0) // Clear ABI so we don't print below.
   592  	}
   593  	if a != 0 {
   594  		s += fmt.Sprintf("UnknownAttribute(%d)|", a)
   595  	}
   596  	// Chop off trailing |, if present.
   597  	if len(s) > 0 {
   598  		s = s[:len(s)-1]
   599  	}
   600  	return s
   601  }
   602  
   603  // The compiler needs LSym to satisfy fmt.Stringer, because it stores
   604  // an LSym in ssa.ExternSymbol.
   605  func (s *LSym) String() string {
   606  	return s.Name
   607  }
   608  
   609  type Pcln struct {
   610  	Pcsp        Pcdata
   611  	Pcfile      Pcdata
   612  	Pcline      Pcdata
   613  	Pcinline    Pcdata
   614  	Pcdata      []Pcdata
   615  	Funcdata    []*LSym
   616  	Funcdataoff []int64
   617  	File        []string
   618  	Lastfile    string
   619  	Lastindex   int
   620  	InlTree     InlTree // per-function inlining tree extracted from the global tree
   621  }
   622  
   623  type Reloc struct {
   624  	Off  int32
   625  	Siz  uint8
   626  	Type objabi.RelocType
   627  	Add  int64
   628  	Sym  *LSym
   629  }
   630  
   631  type Auto struct {
   632  	Asym    *LSym
   633  	Aoffset int32
   634  	Name    AddrName
   635  	Gotype  *LSym
   636  }
   637  
   638  type Pcdata struct {
   639  	P []byte
   640  }
   641  
   642  // Link holds the context for writing object code from a compiler
   643  // to be linker input or for reading that input into the linker.
   644  type Link struct {
   645  	Headtype           objabi.HeadType
   646  	Arch               *LinkArch
   647  	Debugasm           int
   648  	Debugvlog          bool
   649  	Debugpcln          string
   650  	Flag_shared        bool
   651  	Flag_dynlink       bool
   652  	Flag_linkshared    bool
   653  	Flag_optimize      bool
   654  	Flag_locationlists bool
   655  	Flag_newobj        bool // use new object file format
   656  	Bso                *bufio.Writer
   657  	Pathname           string
   658  	hashmu             sync.Mutex       // protects hash, funchash
   659  	hash               map[string]*LSym // name -> sym mapping
   660  	funchash           map[string]*LSym // name -> sym mapping for ABIInternal syms
   661  	statichash         map[string]*LSym // name -> sym mapping for static syms
   662  	PosTable           src.PosTable
   663  	InlTree            InlTree // global inlining tree used by gc/inl.go
   664  	DwFixups           *DwarfFixupTable
   665  	Imports            []string
   666  	DiagFunc           func(string, ...interface{})
   667  	DiagFlush          func()
   668  	DebugInfo          func(fn *LSym, info *LSym, curfn interface{}) ([]dwarf.Scope, dwarf.InlCalls) // if non-nil, curfn is a *gc.Node
   669  	GenAbstractFunc    func(fn *LSym)
   670  	Errors             int
   671  
   672  	InParallel           bool // parallel backend phase in effect
   673  	Framepointer_enabled bool
   674  	UseBASEntries        bool // Use Base Address Selection Entries in location lists and PC ranges
   675  
   676  	// state for writing objects
   677  	Text []*LSym
   678  	Data []*LSym
   679  
   680  	// ABIAliases are text symbols that should be aliased to all
   681  	// ABIs. These symbols may only be referenced and not defined
   682  	// by this object, since the need for an alias may appear in a
   683  	// different object than the definition. Hence, this
   684  	// information can't be carried in the symbol definition.
   685  	//
   686  	// TODO(austin): Replace this with ABI wrappers once the ABIs
   687  	// actually diverge.
   688  	ABIAliases []*LSym
   689  
   690  	// pkgIdx maps package path to index. The index is used for
   691  	// symbol reference in the object file.
   692  	pkgIdx map[string]int32
   693  
   694  	defs       []*LSym // list of defined symbols in the current package
   695  	nonpkgdefs []*LSym // list of defined non-package symbols
   696  	nonpkgrefs []*LSym // list of referenced non-package symbols
   697  }
   698  
   699  func (ctxt *Link) Diag(format string, args ...interface{}) {
   700  	ctxt.Errors++
   701  	ctxt.DiagFunc(format, args...)
   702  }
   703  
   704  func (ctxt *Link) Logf(format string, args ...interface{}) {
   705  	fmt.Fprintf(ctxt.Bso, format, args...)
   706  	ctxt.Bso.Flush()
   707  }
   708  
   709  // The smallest possible offset from the hardware stack pointer to a local
   710  // variable on the stack. Architectures that use a link register save its value
   711  // on the stack in the function prologue and so always have a pointer between
   712  // the hardware stack pointer and the local variable area.
   713  func (ctxt *Link) FixedFrameSize() int64 {
   714  	switch ctxt.Arch.Family {
   715  	case sys.AMD64, sys.I386, sys.Wasm:
   716  		return 0
   717  	case sys.PPC64:
   718  		// PIC code on ppc64le requires 32 bytes of stack, and it's easier to
   719  		// just use that much stack always on ppc64x.
   720  		return int64(4 * ctxt.Arch.PtrSize)
   721  	default:
   722  		return int64(ctxt.Arch.PtrSize)
   723  	}
   724  }
   725  
   726  // LinkArch is the definition of a single architecture.
   727  type LinkArch struct {
   728  	*sys.Arch
   729  	Init           func(*Link)
   730  	Preprocess     func(*Link, *LSym, ProgAlloc)
   731  	Assemble       func(*Link, *LSym, ProgAlloc)
   732  	Progedit       func(*Link, *Prog, ProgAlloc)
   733  	UnaryDst       map[As]bool // Instruction takes one operand, a destination.
   734  	DWARFRegisters map[int16]int16
   735  }