github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/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/master/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 "github.com/shogo82148/std/bufio" 35 "github.com/shogo82148/std/cmd/internal/dwarf" 36 "github.com/shogo82148/std/cmd/internal/goobj" 37 "github.com/shogo82148/std/cmd/internal/objabi" 38 "github.com/shogo82148/std/cmd/internal/src" 39 "github.com/shogo82148/std/cmd/internal/sys" 40 "github.com/shogo82148/std/internal/abi" 41 "github.com/shogo82148/std/sync" 42 ) 43 44 type Addr struct { 45 Reg int16 46 Index int16 47 Scale int16 48 Type AddrType 49 Name AddrName 50 Class int8 51 Offset int64 52 Sym *LSym 53 54 // argument value: 55 // for TYPE_SCONST, a string 56 // for TYPE_FCONST, a float64 57 // for TYPE_BRANCH, a *Prog (optional) 58 // for TYPE_TEXTSIZE, an int32 (optional) 59 Val interface{} 60 } 61 62 type AddrName int8 63 64 const ( 65 NAME_NONE AddrName = iota 66 NAME_EXTERN 67 NAME_STATIC 68 NAME_AUTO 69 NAME_PARAM 70 // A reference to name@GOT(SB) is a reference to the entry in the global offset 71 // table for 'name'. 72 NAME_GOTREF 73 // Indicates that this is a reference to a TOC anchor. 74 NAME_TOCREF 75 ) 76 77 type AddrType uint8 78 79 const ( 80 TYPE_NONE AddrType = iota 81 TYPE_BRANCH 82 TYPE_TEXTSIZE 83 TYPE_MEM 84 TYPE_CONST 85 TYPE_FCONST 86 TYPE_SCONST 87 TYPE_REG 88 TYPE_ADDR 89 TYPE_SHIFT 90 TYPE_REGREG 91 TYPE_REGREG2 92 TYPE_INDIR 93 TYPE_REGLIST 94 TYPE_SPECIAL 95 ) 96 97 func (a *Addr) Target() *Prog 98 99 func (a *Addr) SetTarget(t *Prog) 100 101 func (a *Addr) SetConst(v int64) 102 103 // Prog describes a single machine instruction. 104 // 105 // The general instruction form is: 106 // 107 // (1) As.Scond From [, ...RestArgs], To 108 // (2) As.Scond From, Reg [, ...RestArgs], To, RegTo2 109 // 110 // where As is an opcode and the others are arguments: 111 // From, Reg are sources, and To, RegTo2 are destinations. 112 // RestArgs can hold additional sources and destinations. 113 // Usually, not all arguments are present. 114 // For example, MOVL R1, R2 encodes using only As=MOVL, From=R1, To=R2. 115 // The Scond field holds additional condition bits for systems (like arm) 116 // that have generalized conditional execution. 117 // (2) form is present for compatibility with older code, 118 // to avoid too much changes in a single swing. 119 // (1) scheme is enough to express any kind of operand combination. 120 // 121 // Jump instructions use the To.Val field to point to the target *Prog, 122 // which must be in the same linked list as the jump instruction. 123 // 124 // The Progs for a given function are arranged in a list linked through the Link field. 125 // 126 // Each Prog is charged to a specific source line in the debug information, 127 // specified by Pos.Line(). 128 // Every Prog has a Ctxt field that defines its context. 129 // For performance reasons, Progs are usually bulk allocated, cached, and reused; 130 // those bulk allocators should always be used, rather than new(Prog). 131 // 132 // The other fields not yet mentioned are for use by the back ends and should 133 // be left zeroed by creators of Prog lists. 134 type Prog struct { 135 Ctxt *Link 136 Link *Prog 137 From Addr 138 RestArgs []AddrPos 139 To Addr 140 Pool *Prog 141 Forwd *Prog 142 Rel *Prog 143 Pc int64 144 Pos src.XPos 145 Spadj int32 146 As As 147 Reg int16 148 RegTo2 int16 149 Mark uint16 150 Optab uint16 151 Scond uint8 152 Back uint8 153 Ft uint8 154 Tt uint8 155 Isize uint8 156 } 157 158 // AddrPos indicates whether the operand is the source or the destination. 159 type AddrPos struct { 160 Addr 161 Pos OperandPos 162 } 163 164 type OperandPos int8 165 166 const ( 167 Source OperandPos = iota 168 Destination 169 ) 170 171 // From3Type returns p.GetFrom3().Type, or TYPE_NONE when 172 // p.GetFrom3() returns nil. 173 func (p *Prog) From3Type() AddrType 174 175 // GetFrom3 returns second source operand (the first is Prog.From). 176 // The same kinds of operands are saved in order so GetFrom3 actually 177 // return the first source operand in p.RestArgs. 178 // In combination with Prog.From and Prog.To it makes common 3 operand 179 // case easier to use. 180 func (p *Prog) GetFrom3() *Addr 181 182 // AddRestSource assigns []Args{{a, Source}} to p.RestArgs. 183 func (p *Prog) AddRestSource(a Addr) 184 185 // AddRestSourceReg calls p.AddRestSource with a register Addr containing reg. 186 func (p *Prog) AddRestSourceReg(reg int16) 187 188 // AddRestSourceConst calls p.AddRestSource with a const Addr containing off. 189 func (p *Prog) AddRestSourceConst(off int64) 190 191 // AddRestDest assigns []Args{{a, Destination}} to p.RestArgs when the second destination 192 // operand does not fit into prog.RegTo2. 193 func (p *Prog) AddRestDest(a Addr) 194 195 // GetTo2 returns the second destination operand. 196 // The same kinds of operands are saved in order so GetTo2 actually 197 // return the first destination operand in Prog.RestArgs[] 198 func (p *Prog) GetTo2() *Addr 199 200 // AddRestSourceArgs assigns more than one source operands to p.RestArgs. 201 func (p *Prog) AddRestSourceArgs(args []Addr) 202 203 // An As denotes an assembler opcode. 204 // There are some portable opcodes, declared here in package obj, 205 // that are common to all architectures. 206 // However, the majority of opcodes are arch-specific 207 // and are declared in their respective architecture's subpackage. 208 type As int16 209 210 // These are the portable opcodes. 211 const ( 212 AXXX As = iota 213 ACALL 214 ADUFFCOPY 215 ADUFFZERO 216 AEND 217 AFUNCDATA 218 AJMP 219 ANOP 220 APCALIGN 221 APCDATA 222 ARET 223 AGETCALLERPC 224 ATEXT 225 AUNDEF 226 A_ARCHSPECIFIC 227 ) 228 229 // Each architecture is allotted a distinct subspace of opcode values 230 // for declaring its arch-specific opcodes. 231 // Within this subspace, the first arch-specific opcode should be 232 // at offset A_ARCHSPECIFIC. 233 // 234 // Subspaces are aligned to a power of two so opcodes can be masked 235 // with AMask and used as compact array indices. 236 const ( 237 ABase386 = (1 + iota) << 11 238 ABaseARM 239 ABaseAMD64 240 ABasePPC64 241 ABaseARM64 242 ABaseMIPS 243 ABaseLoong64 244 ABaseRISCV 245 ABaseS390X 246 ABaseWasm 247 248 AllowedOpCodes = 1 << 11 249 AMask = AllowedOpCodes - 1 250 ) 251 252 // An LSym is the sort of symbol that is written to an object file. 253 // It represents Go symbols in a flat pkg+"."+name namespace. 254 type LSym struct { 255 Name string 256 Type objabi.SymKind 257 Attribute 258 259 Size int64 260 Gotype *LSym 261 P []byte 262 R []Reloc 263 264 Extra *interface{} 265 266 Pkg string 267 PkgIdx int32 268 SymIdx int32 269 } 270 271 // A FuncInfo contains extra fields for STEXT symbols. 272 type FuncInfo struct { 273 Args int32 274 Locals int32 275 Align int32 276 FuncID abi.FuncID 277 FuncFlag abi.FuncFlag 278 StartLine int32 279 Text *Prog 280 Autot map[*LSym]struct{} 281 Pcln Pcln 282 InlMarks []InlMark 283 spills []RegSpill 284 285 dwarfInfoSym *LSym 286 dwarfLocSym *LSym 287 dwarfRangesSym *LSym 288 dwarfAbsFnSym *LSym 289 dwarfDebugLinesSym *LSym 290 291 GCArgs *LSym 292 GCLocals *LSym 293 StackObjects *LSym 294 OpenCodedDeferInfo *LSym 295 ArgInfo *LSym 296 ArgLiveInfo *LSym 297 WrapInfo *LSym 298 JumpTables []JumpTable 299 300 FuncInfoSym *LSym 301 WasmImportSym *LSym 302 WasmImport *WasmImport 303 304 sehUnwindInfoSym *LSym 305 } 306 307 // JumpTable represents a table used for implementing multi-way 308 // computed branching, used typically for implementing switches. 309 // Sym is the table itself, and Targets is a list of target 310 // instructions to go to for the computed branch index. 311 type JumpTable struct { 312 Sym *LSym 313 Targets []*Prog 314 } 315 316 // NewFuncInfo allocates and returns a FuncInfo for LSym. 317 func (s *LSym) NewFuncInfo() *FuncInfo 318 319 // Func returns the *FuncInfo associated with s, or else nil. 320 func (s *LSym) Func() *FuncInfo 321 322 type VarInfo struct { 323 dwarfInfoSym *LSym 324 } 325 326 // NewVarInfo allocates and returns a VarInfo for LSym. 327 func (s *LSym) NewVarInfo() *VarInfo 328 329 // VarInfo returns the *VarInfo associated with s, or else nil. 330 func (s *LSym) VarInfo() *VarInfo 331 332 // A FileInfo contains extra fields for SDATA symbols backed by files. 333 // (If LSym.Extra is a *FileInfo, LSym.P == nil.) 334 type FileInfo struct { 335 Name string 336 Size int64 337 } 338 339 // NewFileInfo allocates and returns a FileInfo for LSym. 340 func (s *LSym) NewFileInfo() *FileInfo 341 342 // File returns the *FileInfo associated with s, or else nil. 343 func (s *LSym) File() *FileInfo 344 345 // A TypeInfo contains information for a symbol 346 // that contains a runtime._type. 347 type TypeInfo struct { 348 Type interface{} 349 } 350 351 func (s *LSym) NewTypeInfo() *TypeInfo 352 353 // WasmImport represents a WebAssembly (WASM) imported function with 354 // parameters and results translated into WASM types based on the Go function 355 // declaration. 356 type WasmImport struct { 357 // Module holds the WASM module name specified by the //go:wasmimport 358 // directive. 359 Module string 360 // Name holds the WASM imported function name specified by the 361 // //go:wasmimport directive. 362 Name string 363 // Params holds the imported function parameter fields. 364 Params []WasmField 365 // Results holds the imported function result fields. 366 Results []WasmField 367 } 368 369 func (wi *WasmImport) CreateSym(ctxt *Link) *LSym 370 371 type WasmField struct { 372 Type WasmFieldType 373 // Offset holds the frame-pointer-relative locations for Go's stack-based 374 // ABI. This is used by the src/cmd/internal/wasm package to map WASM 375 // import parameters to the Go stack in a wrapper function. 376 Offset int64 377 } 378 379 type WasmFieldType byte 380 381 const ( 382 WasmI32 WasmFieldType = iota 383 WasmI64 384 WasmF32 385 WasmF64 386 WasmPtr 387 ) 388 389 type InlMark struct { 390 // When unwinding from an instruction in an inlined body, mark 391 // where we should unwind to. 392 // id records the global inlining id of the inlined body. 393 // p records the location of an instruction in the parent (inliner) frame. 394 p *Prog 395 id int32 396 } 397 398 // Mark p as the instruction to set as the pc when 399 // "unwinding" the inlining global frame id. Usually it should be 400 // instruction with a file:line at the callsite, and occur 401 // just before the body of the inlined function. 402 func (fi *FuncInfo) AddInlMark(p *Prog, id int32) 403 404 // AddSpill appends a spill record to the list for FuncInfo fi 405 func (fi *FuncInfo) AddSpill(s RegSpill) 406 407 // Record the type symbol for an auto variable so that the linker 408 // an emit DWARF type information for the type. 409 func (fi *FuncInfo) RecordAutoType(gotype *LSym) 410 411 // ABI is the calling convention of a text symbol. 412 type ABI uint8 413 414 const ( 415 // ABI0 is the stable stack-based ABI. It's important that the 416 // value of this is "0": we can't distinguish between 417 // references to data and ABI0 text symbols in assembly code, 418 // and hence this doesn't distinguish between symbols without 419 // an ABI and text symbols with ABI0. 420 ABI0 ABI = iota 421 422 // ABIInternal is the internal ABI that may change between Go 423 // versions. All Go functions use the internal ABI and the 424 // compiler generates wrappers for calls to and from other 425 // ABIs. 426 ABIInternal 427 428 ABICount 429 ) 430 431 // ParseABI converts from a string representation in 'abistr' to the 432 // corresponding ABI value. Second return value is TRUE if the 433 // abi string is recognized, FALSE otherwise. 434 func ParseABI(abistr string) (ABI, bool) 435 436 // ABISet is a bit set of ABI values. 437 type ABISet uint8 438 439 const ( 440 // ABISetCallable is the set of all ABIs any function could 441 // potentially be called using. 442 ABISetCallable ABISet = (1 << ABI0) | (1 << ABIInternal) 443 ) 444 445 // Ensure ABISet is big enough to hold all ABIs. 446 var _ ABISet = 1 << (ABICount - 1) 447 448 func ABISetOf(abi ABI) ABISet 449 450 func (a *ABISet) Set(abi ABI, value bool) 451 452 func (a *ABISet) Get(abi ABI) bool 453 454 func (a ABISet) String() string 455 456 // Attribute is a set of symbol attributes. 457 type Attribute uint32 458 459 const ( 460 AttrDuplicateOK Attribute = 1 << iota 461 AttrCFunc 462 AttrNoSplit 463 AttrLeaf 464 AttrWrapper 465 AttrNeedCtxt 466 AttrNoFrame 467 AttrOnList 468 AttrStatic 469 470 // MakeTypelink means that the type should have an entry in the typelink table. 471 AttrMakeTypelink 472 473 // ReflectMethod means the function may call reflect.Type.Method or 474 // reflect.Type.MethodByName. Matching is imprecise (as reflect.Type 475 // can be used through a custom interface), so ReflectMethod may be 476 // set in some cases when the reflect package is not called. 477 // 478 // Used by the linker to determine what methods can be pruned. 479 AttrReflectMethod 480 481 // Local means make the symbol local even when compiling Go code to reference Go 482 // symbols in other shared libraries, as in this mode symbols are global by 483 // default. "local" here means in the sense of the dynamic linker, i.e. not 484 // visible outside of the module (shared library or executable) that contains its 485 // definition. (When not compiling to support Go shared libraries, all symbols are 486 // local in this sense unless there is a cgo_export_* directive). 487 AttrLocal 488 489 // For function symbols; indicates that the specified function was the 490 // target of an inline during compilation 491 AttrWasInlined 492 493 // Indexed indicates this symbol has been assigned with an index (when using the 494 // new object file format). 495 AttrIndexed 496 497 // Only applied on type descriptor symbols, UsedInIface indicates this type is 498 // converted to an interface. 499 // 500 // Used by the linker to determine what methods can be pruned. 501 AttrUsedInIface 502 503 // ContentAddressable indicates this is a content-addressable symbol. 504 AttrContentAddressable 505 506 // ABI wrapper is set for compiler-generated text symbols that 507 // convert between ABI0 and ABIInternal calling conventions. 508 AttrABIWrapper 509 510 // IsPcdata indicates this is a pcdata symbol. 511 AttrPcdata 512 513 // PkgInit indicates this is a compiler-generated package init func. 514 AttrPkgInit 515 ) 516 517 func (a *Attribute) DuplicateOK() bool 518 func (a *Attribute) MakeTypelink() bool 519 func (a *Attribute) CFunc() bool 520 func (a *Attribute) NoSplit() bool 521 func (a *Attribute) Leaf() bool 522 func (a *Attribute) OnList() bool 523 func (a *Attribute) ReflectMethod() bool 524 func (a *Attribute) Local() bool 525 func (a *Attribute) Wrapper() bool 526 func (a *Attribute) NeedCtxt() bool 527 func (a *Attribute) NoFrame() bool 528 func (a *Attribute) Static() bool 529 func (a *Attribute) WasInlined() bool 530 func (a *Attribute) Indexed() bool 531 func (a *Attribute) UsedInIface() bool 532 func (a *Attribute) ContentAddressable() bool 533 func (a *Attribute) ABIWrapper() bool 534 func (a *Attribute) IsPcdata() bool 535 func (a *Attribute) IsPkgInit() bool 536 537 func (a *Attribute) Set(flag Attribute, value bool) 538 539 func (a *Attribute) ABI() ABI 540 func (a *Attribute) SetABI(abi ABI) 541 542 // String formats a for printing in as part of a TEXT prog. 543 func (a Attribute) String() string 544 545 // TextAttrString formats the symbol attributes for printing in as part of a TEXT prog. 546 func (s *LSym) TextAttrString() string 547 548 func (s *LSym) String() string 549 550 // The compiler needs *LSym to be assignable to cmd/compile/internal/ssa.Sym. 551 func (*LSym) CanBeAnSSASym() 552 func (*LSym) CanBeAnSSAAux() 553 554 type Pcln struct { 555 // Aux symbols for pcln 556 Pcsp *LSym 557 Pcfile *LSym 558 Pcline *LSym 559 Pcinline *LSym 560 Pcdata []*LSym 561 Funcdata []*LSym 562 UsedFiles map[goobj.CUFileIndex]struct{} 563 InlTree InlTree 564 } 565 566 type Reloc struct { 567 Off int32 568 Siz uint8 569 Type objabi.RelocType 570 Add int64 571 Sym *LSym 572 } 573 574 type Auto struct { 575 Asym *LSym 576 Aoffset int32 577 Name AddrName 578 Gotype *LSym 579 } 580 581 // RegSpill provides spill/fill information for a register-resident argument 582 // to a function. These need spilling/filling in the safepoint/stackgrowth case. 583 // At the time of fill/spill, the offset must be adjusted by the architecture-dependent 584 // adjustment to hardware SP that occurs in a call instruction. E.g., for AMD64, 585 // at Offset+8 because the return address was pushed. 586 type RegSpill struct { 587 Addr Addr 588 Reg int16 589 Spill, Unspill As 590 } 591 592 // A Func represents a Go function. If non-nil, it must be a *ir.Func. 593 type Func interface { 594 Pos() src.XPos 595 } 596 597 // Link holds the context for writing object code from a compiler 598 // to be linker input or for reading that input into the linker. 599 type Link struct { 600 Headtype objabi.HeadType 601 Arch *LinkArch 602 Debugasm int 603 Debugvlog bool 604 Debugpcln string 605 Flag_shared bool 606 Flag_dynlink bool 607 Flag_linkshared bool 608 Flag_optimize bool 609 Flag_locationlists bool 610 Flag_noRefName bool 611 Retpoline bool 612 Flag_maymorestack string 613 Bso *bufio.Writer 614 Pathname string 615 Pkgpath string 616 hashmu sync.Mutex 617 hash map[string]*LSym 618 funchash map[string]*LSym 619 statichash map[string]*LSym 620 PosTable src.PosTable 621 InlTree InlTree 622 DwFixups *DwarfFixupTable 623 Imports []goobj.ImportedPkg 624 DiagFunc func(string, ...interface{}) 625 DiagFlush func() 626 DebugInfo func(fn *LSym, info *LSym, curfn Func) ([]dwarf.Scope, dwarf.InlCalls) 627 GenAbstractFunc func(fn *LSym) 628 Errors int 629 630 InParallel bool 631 UseBASEntries bool 632 IsAsm bool 633 634 // state for writing objects 635 Text []*LSym 636 Data []*LSym 637 638 // Constant symbols (e.g. $i64.*) are data symbols created late 639 // in the concurrent phase. To ensure a deterministic order, we 640 // add them to a separate list, sort at the end, and append it 641 // to Data. 642 constSyms []*LSym 643 644 // pkgIdx maps package path to index. The index is used for 645 // symbol reference in the object file. 646 pkgIdx map[string]int32 647 648 defs []*LSym 649 hashed64defs []*LSym 650 hasheddefs []*LSym 651 nonpkgdefs []*LSym 652 nonpkgrefs []*LSym 653 654 Fingerprint goobj.FingerprintType 655 } 656 657 func (ctxt *Link) Diag(format string, args ...interface{}) 658 659 func (ctxt *Link) Logf(format string, args ...interface{}) 660 661 // SpillRegisterArgs emits the code to spill register args into whatever 662 // locations the spill records specify. 663 func (fi *FuncInfo) SpillRegisterArgs(last *Prog, pa ProgAlloc) *Prog 664 665 // UnspillRegisterArgs emits the code to restore register args from whatever 666 // locations the spill records specify. 667 func (fi *FuncInfo) UnspillRegisterArgs(last *Prog, pa ProgAlloc) *Prog 668 669 // LinkArch is the definition of a single architecture. 670 type LinkArch struct { 671 *sys.Arch 672 Init func(*Link) 673 ErrorCheck func(*Link, *LSym) 674 Preprocess func(*Link, *LSym, ProgAlloc) 675 Assemble func(*Link, *LSym, ProgAlloc) 676 Progedit func(*Link, *Prog, ProgAlloc) 677 SEH func(*Link, *LSym) *LSym 678 UnaryDst map[As]bool 679 DWARFRegisters map[int16]int16 680 }