github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/src/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 "cmd/internal/dwarf" 36 "cmd/internal/objabi" 37 "cmd/internal/src" 38 "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 and ARM64. 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 // 149 // reg, reg 150 // Register pair for ARM. 151 // TYPE_REGREG2 152 // 153 // (reg+reg) 154 // Register pair for PPC64. 155 // Encoding: 156 // type = TYPE_MEM 157 // reg = first register 158 // index = second register 159 // scale = 1 160 // 161 // reg.[US]XT[BHWX] 162 // Register extension for ARM64 163 // Encoding: 164 // type = TYPE_REG 165 // reg = REG_[US]XT[BHWX] + register + shift amount 166 // offset = ((reg&31) << 16) | (exttype << 13) | (amount<<10) 167 // 168 // reg.<T> 169 // Register arrangement for ARM64 SIMD register 170 // e.g.: V1.S4, V2.S2, V7.D2, V2.H4, V6.B16 171 // Encoding: 172 // type = TYPE_REG 173 // reg = REG_ARNG + register + arrangement 174 // 175 // reg.<T>[index] 176 // Register element for ARM64 177 // Encoding: 178 // type = TYPE_REG 179 // reg = REG_ELEM + register + arrangement 180 // index = element index 181 182 type Addr struct { 183 Reg int16 184 Index int16 185 Scale int16 // Sometimes holds a register. 186 Type AddrType 187 Name AddrName 188 Class int8 189 Offset int64 190 Sym *LSym 191 192 // argument value: 193 // for TYPE_SCONST, a string 194 // for TYPE_FCONST, a float64 195 // for TYPE_BRANCH, a *Prog (optional) 196 // for TYPE_TEXTSIZE, an int32 (optional) 197 Val interface{} 198 } 199 200 type AddrName int8 201 202 const ( 203 NAME_NONE AddrName = iota 204 NAME_EXTERN 205 NAME_STATIC 206 NAME_AUTO 207 NAME_PARAM 208 // A reference to name@GOT(SB) is a reference to the entry in the global offset 209 // table for 'name'. 210 NAME_GOTREF 211 ) 212 213 type AddrType uint8 214 215 const ( 216 TYPE_NONE AddrType = iota 217 TYPE_BRANCH 218 TYPE_TEXTSIZE 219 TYPE_MEM 220 TYPE_CONST 221 TYPE_FCONST 222 TYPE_SCONST 223 TYPE_REG 224 TYPE_ADDR 225 TYPE_SHIFT 226 TYPE_REGREG 227 TYPE_REGREG2 228 TYPE_INDIR 229 TYPE_REGLIST 230 ) 231 232 // Prog describes a single machine instruction. 233 // 234 // The general instruction form is: 235 // 236 // (1) As.Scond From [, ...RestArgs], To 237 // (2) As.Scond From, Reg [, ...RestArgs], To, RegTo2 238 // 239 // where As is an opcode and the others are arguments: 240 // From, Reg are sources, and To, RegTo2 are destinations. 241 // RestArgs can hold additional sources and destinations. 242 // Usually, not all arguments are present. 243 // For example, MOVL R1, R2 encodes using only As=MOVL, From=R1, To=R2. 244 // The Scond field holds additional condition bits for systems (like arm) 245 // that have generalized conditional execution. 246 // (2) form is present for compatibility with older code, 247 // to avoid too much changes in a single swing. 248 // (1) scheme is enough to express any kind of operand combination. 249 // 250 // Jump instructions use the Pcond field to point to the target instruction, 251 // which must be in the same linked list as the jump instruction. 252 // 253 // The Progs for a given function are arranged in a list linked through the Link field. 254 // 255 // Each Prog is charged to a specific source line in the debug information, 256 // specified by Pos.Line(). 257 // Every Prog has a Ctxt field that defines its context. 258 // For performance reasons, Progs usually are usually bulk allocated, cached, and reused; 259 // those bulk allocators should always be used, rather than new(Prog). 260 // 261 // The other fields not yet mentioned are for use by the back ends and should 262 // be left zeroed by creators of Prog lists. 263 type Prog struct { 264 Ctxt *Link // linker context 265 Link *Prog // next Prog in linked list 266 From Addr // first source operand 267 RestArgs []Addr // can pack any operands that not fit into {Prog.From, Prog.To} 268 To Addr // destination operand (second is RegTo2 below) 269 Pcond *Prog // target of conditional jump 270 Forwd *Prog // for x86 back end 271 Rel *Prog // for x86, arm back ends 272 Pc int64 // for back ends or assembler: virtual or actual program counter, depending on phase 273 Pos src.XPos // source position of this instruction 274 Spadj int32 // effect of instruction on stack pointer (increment or decrement amount) 275 As As // assembler opcode 276 Reg int16 // 2nd source operand 277 RegTo2 int16 // 2nd destination operand 278 Mark uint16 // bitmask of arch-specific items 279 Optab uint16 // arch-specific opcode index 280 Scond uint8 // condition bits for conditional instruction (e.g., on ARM) 281 Back uint8 // for x86 back end: backwards branch state 282 Ft uint8 // for x86 back end: type index of Prog.From 283 Tt uint8 // for x86 back end: type index of Prog.To 284 Isize uint8 // for x86 back end: size of the instruction in bytes 285 } 286 287 // From3Type returns p.GetFrom3().Type, or TYPE_NONE when 288 // p.GetFrom3() returns nil. 289 // 290 // Deprecated: for the same reasons as Prog.GetFrom3. 291 func (p *Prog) From3Type() AddrType { 292 if p.RestArgs == nil { 293 return TYPE_NONE 294 } 295 return p.RestArgs[0].Type 296 } 297 298 // GetFrom3 returns second source operand (the first is Prog.From). 299 // In combination with Prog.From and Prog.To it makes common 3 operand 300 // case easier to use. 301 // 302 // Should be used only when RestArgs is set with SetFrom3. 303 // 304 // Deprecated: better use RestArgs directly or define backend-specific getters. 305 // Introduced to simplify transition to []Addr. 306 // Usage of this is discouraged due to fragility and lack of guarantees. 307 func (p *Prog) GetFrom3() *Addr { 308 if p.RestArgs == nil { 309 return nil 310 } 311 return &p.RestArgs[0] 312 } 313 314 // SetFrom3 assigns []Addr{a} to p.RestArgs. 315 // In pair with Prog.GetFrom3 it can help in emulation of Prog.From3. 316 // 317 // Deprecated: for the same reasons as Prog.GetFrom3. 318 func (p *Prog) SetFrom3(a Addr) { 319 p.RestArgs = []Addr{a} 320 } 321 322 // An As denotes an assembler opcode. 323 // There are some portable opcodes, declared here in package obj, 324 // that are common to all architectures. 325 // However, the majority of opcodes are arch-specific 326 // and are declared in their respective architecture's subpackage. 327 type As int16 328 329 // These are the portable opcodes. 330 const ( 331 AXXX As = iota 332 ACALL 333 ADUFFCOPY 334 ADUFFZERO 335 AEND 336 AFUNCDATA 337 AJMP 338 ANOP 339 APCDATA 340 ARET 341 ATEXT 342 AUNDEF 343 A_ARCHSPECIFIC 344 ) 345 346 // Each architecture is allotted a distinct subspace of opcode values 347 // for declaring its arch-specific opcodes. 348 // Within this subspace, the first arch-specific opcode should be 349 // at offset A_ARCHSPECIFIC. 350 // 351 // Subspaces are aligned to a power of two so opcodes can be masked 352 // with AMask and used as compact array indices. 353 const ( 354 ABase386 = (1 + iota) << 11 355 ABaseARM 356 ABaseAMD64 357 ABasePPC64 358 ABaseARM64 359 ABaseMIPS 360 ABaseS390X 361 362 AllowedOpCodes = 1 << 11 // The number of opcodes available for any given architecture. 363 AMask = AllowedOpCodes - 1 // AND with this to use the opcode as an array index. 364 ) 365 366 // An LSym is the sort of symbol that is written to an object file. 367 type LSym struct { 368 Name string 369 Type objabi.SymKind 370 Attribute 371 372 RefIdx int // Index of this symbol in the symbol reference list. 373 Size int64 374 Gotype *LSym 375 P []byte 376 R []Reloc 377 378 Func *FuncInfo 379 } 380 381 // A FuncInfo contains extra fields for STEXT symbols. 382 type FuncInfo struct { 383 Args int32 384 Locals int32 385 Text *Prog 386 Autom []*Auto 387 Pcln Pcln 388 389 dwarfInfoSym *LSym 390 dwarfLocSym *LSym 391 dwarfRangesSym *LSym 392 393 GCArgs LSym 394 GCLocals LSym 395 } 396 397 // Attribute is a set of symbol attributes. 398 type Attribute int16 399 400 const ( 401 AttrDuplicateOK Attribute = 1 << iota 402 AttrCFunc 403 AttrNoSplit 404 AttrLeaf 405 AttrWrapper 406 AttrNeedCtxt 407 AttrNoFrame 408 AttrSeenGlobl 409 AttrOnList 410 AttrStatic 411 412 // MakeTypelink means that the type should have an entry in the typelink table. 413 AttrMakeTypelink 414 415 // ReflectMethod means the function may call reflect.Type.Method or 416 // reflect.Type.MethodByName. Matching is imprecise (as reflect.Type 417 // can be used through a custom interface), so ReflectMethod may be 418 // set in some cases when the reflect package is not called. 419 // 420 // Used by the linker to determine what methods can be pruned. 421 AttrReflectMethod 422 423 // Local means make the symbol local even when compiling Go code to reference Go 424 // symbols in other shared libraries, as in this mode symbols are global by 425 // default. "local" here means in the sense of the dynamic linker, i.e. not 426 // visible outside of the module (shared library or executable) that contains its 427 // definition. (When not compiling to support Go shared libraries, all symbols are 428 // local in this sense unless there is a cgo_export_* directive). 429 AttrLocal 430 ) 431 432 func (a Attribute) DuplicateOK() bool { return a&AttrDuplicateOK != 0 } 433 func (a Attribute) MakeTypelink() bool { return a&AttrMakeTypelink != 0 } 434 func (a Attribute) CFunc() bool { return a&AttrCFunc != 0 } 435 func (a Attribute) NoSplit() bool { return a&AttrNoSplit != 0 } 436 func (a Attribute) Leaf() bool { return a&AttrLeaf != 0 } 437 func (a Attribute) SeenGlobl() bool { return a&AttrSeenGlobl != 0 } 438 func (a Attribute) OnList() bool { return a&AttrOnList != 0 } 439 func (a Attribute) ReflectMethod() bool { return a&AttrReflectMethod != 0 } 440 func (a Attribute) Local() bool { return a&AttrLocal != 0 } 441 func (a Attribute) Wrapper() bool { return a&AttrWrapper != 0 } 442 func (a Attribute) NeedCtxt() bool { return a&AttrNeedCtxt != 0 } 443 func (a Attribute) NoFrame() bool { return a&AttrNoFrame != 0 } 444 func (a Attribute) Static() bool { return a&AttrStatic != 0 } 445 446 func (a *Attribute) Set(flag Attribute, value bool) { 447 if value { 448 *a |= flag 449 } else { 450 *a &^= flag 451 } 452 } 453 454 var textAttrStrings = [...]struct { 455 bit Attribute 456 s string 457 }{ 458 {bit: AttrDuplicateOK, s: "DUPOK"}, 459 {bit: AttrMakeTypelink, s: ""}, 460 {bit: AttrCFunc, s: "CFUNC"}, 461 {bit: AttrNoSplit, s: "NOSPLIT"}, 462 {bit: AttrLeaf, s: "LEAF"}, 463 {bit: AttrSeenGlobl, s: ""}, 464 {bit: AttrOnList, s: ""}, 465 {bit: AttrReflectMethod, s: "REFLECTMETHOD"}, 466 {bit: AttrLocal, s: "LOCAL"}, 467 {bit: AttrWrapper, s: "WRAPPER"}, 468 {bit: AttrNeedCtxt, s: "NEEDCTXT"}, 469 {bit: AttrNoFrame, s: "NOFRAME"}, 470 {bit: AttrStatic, s: "STATIC"}, 471 } 472 473 // TextAttrString formats a for printing in as part of a TEXT prog. 474 func (a Attribute) TextAttrString() string { 475 var s string 476 for _, x := range textAttrStrings { 477 if a&x.bit != 0 { 478 if x.s != "" { 479 s += x.s + "|" 480 } 481 a &^= x.bit 482 } 483 } 484 if a != 0 { 485 s += fmt.Sprintf("UnknownAttribute(%d)|", a) 486 } 487 // Chop off trailing |, if present. 488 if len(s) > 0 { 489 s = s[:len(s)-1] 490 } 491 return s 492 } 493 494 // The compiler needs LSym to satisfy fmt.Stringer, because it stores 495 // an LSym in ssa.ExternSymbol. 496 func (s *LSym) String() string { 497 return s.Name 498 } 499 500 type Pcln struct { 501 Pcsp Pcdata 502 Pcfile Pcdata 503 Pcline Pcdata 504 Pcinline Pcdata 505 Pcdata []Pcdata 506 Funcdata []*LSym 507 Funcdataoff []int64 508 File []string 509 Lastfile string 510 Lastindex int 511 InlTree InlTree // per-function inlining tree extracted from the global tree 512 } 513 514 type Reloc struct { 515 Off int32 516 Siz uint8 517 Type objabi.RelocType 518 Add int64 519 Sym *LSym 520 } 521 522 type Auto struct { 523 Asym *LSym 524 Aoffset int32 525 Name AddrName 526 Gotype *LSym 527 } 528 529 type Pcdata struct { 530 P []byte 531 } 532 533 // Link holds the context for writing object code from a compiler 534 // to be linker input or for reading that input into the linker. 535 type Link struct { 536 Headtype objabi.HeadType 537 Arch *LinkArch 538 Debugasm bool 539 Debugvlog bool 540 Debugpcln string 541 Flag_shared bool 542 Flag_dynlink bool 543 Flag_optimize bool 544 Flag_locationlists bool 545 Bso *bufio.Writer 546 Pathname string 547 hashmu sync.Mutex // protects hash 548 hash map[string]*LSym // name -> sym mapping 549 statichash map[string]*LSym // name -> sym mapping for static syms 550 PosTable src.PosTable 551 InlTree InlTree // global inlining tree used by gc/inl.go 552 Imports []string 553 DiagFunc func(string, ...interface{}) 554 DiagFlush func() 555 DebugInfo func(fn *LSym, curfn interface{}) []dwarf.Scope // if non-nil, curfn is a *gc.Node 556 Errors int 557 558 Framepointer_enabled bool 559 560 // state for writing objects 561 Text []*LSym 562 Data []*LSym 563 } 564 565 func (ctxt *Link) Diag(format string, args ...interface{}) { 566 ctxt.Errors++ 567 ctxt.DiagFunc(format, args...) 568 } 569 570 func (ctxt *Link) Logf(format string, args ...interface{}) { 571 fmt.Fprintf(ctxt.Bso, format, args...) 572 ctxt.Bso.Flush() 573 } 574 575 // The smallest possible offset from the hardware stack pointer to a local 576 // variable on the stack. Architectures that use a link register save its value 577 // on the stack in the function prologue and so always have a pointer between 578 // the hardware stack pointer and the local variable area. 579 func (ctxt *Link) FixedFrameSize() int64 { 580 switch ctxt.Arch.Family { 581 case sys.AMD64, sys.I386: 582 return 0 583 case sys.PPC64: 584 // PIC code on ppc64le requires 32 bytes of stack, and it's easier to 585 // just use that much stack always on ppc64x. 586 return int64(4 * ctxt.Arch.PtrSize) 587 default: 588 return int64(ctxt.Arch.PtrSize) 589 } 590 } 591 592 // LinkArch is the definition of a single architecture. 593 type LinkArch struct { 594 *sys.Arch 595 Init func(*Link) 596 Preprocess func(*Link, *LSym, ProgAlloc) 597 Assemble func(*Link, *LSym, ProgAlloc) 598 Progedit func(*Link, *Prog, ProgAlloc) 599 UnaryDst map[As]bool // Instruction takes one operand, a destination. 600 DWARFRegisters map[int16]int16 601 }