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