github.com/hikaru7719/go@v0.0.0-20181025140707-c8b2ac68906a/src/cmd/link/internal/ld/data.go (about) 1 // Derived from Inferno utils/6l/obj.c and utils/6l/span.c 2 // https://bitbucket.org/inferno-os/inferno-os/src/default/utils/6l/obj.c 3 // https://bitbucket.org/inferno-os/inferno-os/src/default/utils/6l/span.c 4 // 5 // Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved. 6 // Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net) 7 // Portions Copyright © 1997-1999 Vita Nuova Limited 8 // Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com) 9 // Portions Copyright © 2004,2006 Bruce Ellis 10 // Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net) 11 // Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others 12 // Portions Copyright © 2009 The Go Authors. All rights reserved. 13 // 14 // Permission is hereby granted, free of charge, to any person obtaining a copy 15 // of this software and associated documentation files (the "Software"), to deal 16 // in the Software without restriction, including without limitation the rights 17 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 18 // copies of the Software, and to permit persons to whom the Software is 19 // furnished to do so, subject to the following conditions: 20 // 21 // The above copyright notice and this permission notice shall be included in 22 // all copies or substantial portions of the Software. 23 // 24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 25 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 26 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 27 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 28 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 29 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 30 // THE SOFTWARE. 31 32 package ld 33 34 import ( 35 "bytes" 36 "cmd/internal/gcprog" 37 "cmd/internal/objabi" 38 "cmd/internal/sys" 39 "cmd/link/internal/sym" 40 "compress/zlib" 41 "encoding/binary" 42 "fmt" 43 "log" 44 "os" 45 "sort" 46 "strconv" 47 "strings" 48 "sync" 49 ) 50 51 // isRuntimeDepPkg returns whether pkg is the runtime package or its dependency 52 func isRuntimeDepPkg(pkg string) bool { 53 switch pkg { 54 case "runtime", 55 "sync/atomic", // runtime may call to sync/atomic, due to go:linkname 56 "internal/bytealg", // for IndexByte 57 "internal/cpu": // for cpu features 58 return true 59 } 60 return strings.HasPrefix(pkg, "runtime/internal/") && !strings.HasSuffix(pkg, "_test") 61 } 62 63 // Estimate the max size needed to hold any new trampolines created for this function. This 64 // is used to determine when the section can be split if it becomes too large, to ensure that 65 // the trampolines are in the same section as the function that uses them. 66 func maxSizeTrampolinesPPC64(s *sym.Symbol, isTramp bool) uint64 { 67 // If thearch.Trampoline is nil, then trampoline support is not available on this arch. 68 // A trampoline does not need any dependent trampolines. 69 if thearch.Trampoline == nil || isTramp { 70 return 0 71 } 72 73 n := uint64(0) 74 for ri := range s.R { 75 r := &s.R[ri] 76 if r.Type.IsDirectJump() { 77 n++ 78 } 79 } 80 // Trampolines in ppc64 are 4 instructions. 81 return n * 16 82 } 83 84 // detect too-far jumps in function s, and add trampolines if necessary 85 // ARM, PPC64 & PPC64LE support trampoline insertion for internal and external linking 86 // On PPC64 & PPC64LE the text sections might be split but will still insert trampolines 87 // where necessary. 88 func trampoline(ctxt *Link, s *sym.Symbol) { 89 if thearch.Trampoline == nil { 90 return // no need or no support of trampolines on this arch 91 } 92 93 for ri := range s.R { 94 r := &s.R[ri] 95 if !r.Type.IsDirectJump() { 96 continue 97 } 98 if Symaddr(r.Sym) == 0 && r.Sym.Type != sym.SDYNIMPORT { 99 if r.Sym.File != s.File { 100 if !isRuntimeDepPkg(s.File) || !isRuntimeDepPkg(r.Sym.File) { 101 ctxt.ErrorUnresolved(s, r) 102 } 103 // runtime and its dependent packages may call to each other. 104 // they are fine, as they will be laid down together. 105 } 106 continue 107 } 108 109 thearch.Trampoline(ctxt, r, s) 110 } 111 112 } 113 114 // relocsym resolve relocations in "s". The main loop walks through 115 // the list of relocations attached to "s" and resolves them where 116 // applicable. Relocations are often architecture-specific, requiring 117 // calls into the 'archreloc' and/or 'archrelocvariant' functions for 118 // the architecture. When external linking is in effect, it may not be 119 // possible to completely resolve the address/offset for a symbol, in 120 // which case the goal is to lay the groundwork for turning a given 121 // relocation into an external reloc (to be applied by the external 122 // linker). For more on how relocations work in general, see 123 // 124 // "Linkers and Loaders", by John R. Levine (Morgan Kaufmann, 1999), ch. 7 125 // 126 // This is a performance-critical function for the linker; be careful 127 // to avoid introducing unnecessary allocations in the main loop. 128 func relocsym(ctxt *Link, s *sym.Symbol) { 129 for ri := int32(0); ri < int32(len(s.R)); ri++ { 130 r := &s.R[ri] 131 if r.Done { 132 // Relocation already processed by an earlier phase. 133 continue 134 } 135 r.Done = true 136 off := r.Off 137 siz := int32(r.Siz) 138 if off < 0 || off+siz > int32(len(s.P)) { 139 rname := "" 140 if r.Sym != nil { 141 rname = r.Sym.Name 142 } 143 Errorf(s, "invalid relocation %s: %d+%d not in [%d,%d)", rname, off, siz, 0, len(s.P)) 144 continue 145 } 146 147 if r.Sym != nil && ((r.Sym.Type == sym.Sxxx && !r.Sym.Attr.VisibilityHidden()) || r.Sym.Type == sym.SXREF) { 148 // When putting the runtime but not main into a shared library 149 // these symbols are undefined and that's OK. 150 if ctxt.BuildMode == BuildModeShared { 151 if r.Sym.Name == "main.main" || r.Sym.Name == "main.init" { 152 r.Sym.Type = sym.SDYNIMPORT 153 } else if strings.HasPrefix(r.Sym.Name, "go.info.") { 154 // Skip go.info symbols. They are only needed to communicate 155 // DWARF info between the compiler and linker. 156 continue 157 } 158 } else { 159 ctxt.ErrorUnresolved(s, r) 160 continue 161 } 162 } 163 164 if r.Type >= 256 { 165 continue 166 } 167 if r.Siz == 0 { // informational relocation - no work to do 168 continue 169 } 170 if r.Type == objabi.R_DWARFFILEREF { 171 // These should have been processed previously during 172 // line table writing. 173 Errorf(s, "orphan R_DWARFFILEREF reloc to %v", r.Sym.Name) 174 continue 175 } 176 177 // We need to be able to reference dynimport symbols when linking against 178 // shared libraries, and Solaris and Darwin need it always 179 if ctxt.HeadType != objabi.Hsolaris && ctxt.HeadType != objabi.Hdarwin && r.Sym != nil && r.Sym.Type == sym.SDYNIMPORT && !ctxt.DynlinkingGo() && !r.Sym.Attr.SubSymbol() { 180 if !(ctxt.Arch.Family == sys.PPC64 && ctxt.LinkMode == LinkExternal && r.Sym.Name == ".TOC.") { 181 Errorf(s, "unhandled relocation for %s (type %d (%s) rtype %d (%s))", r.Sym.Name, r.Sym.Type, r.Sym.Type, r.Type, sym.RelocName(ctxt.Arch, r.Type)) 182 } 183 } 184 if r.Sym != nil && r.Sym.Type != sym.STLSBSS && r.Type != objabi.R_WEAKADDROFF && !r.Sym.Attr.Reachable() { 185 Errorf(s, "unreachable sym in relocation: %s", r.Sym.Name) 186 } 187 188 // TODO(mundaym): remove this special case - see issue 14218. 189 if ctxt.Arch.Family == sys.S390X { 190 switch r.Type { 191 case objabi.R_PCRELDBL: 192 r.Type = objabi.R_PCREL 193 r.Variant = sym.RV_390_DBL 194 case objabi.R_CALL: 195 r.Variant = sym.RV_390_DBL 196 } 197 } 198 199 var o int64 200 switch r.Type { 201 default: 202 switch siz { 203 default: 204 Errorf(s, "bad reloc size %#x for %s", uint32(siz), r.Sym.Name) 205 case 1: 206 o = int64(s.P[off]) 207 case 2: 208 o = int64(ctxt.Arch.ByteOrder.Uint16(s.P[off:])) 209 case 4: 210 o = int64(ctxt.Arch.ByteOrder.Uint32(s.P[off:])) 211 case 8: 212 o = int64(ctxt.Arch.ByteOrder.Uint64(s.P[off:])) 213 } 214 if offset, ok := thearch.Archreloc(ctxt, r, s, o); ok { 215 o = offset 216 } else { 217 Errorf(s, "unknown reloc to %v: %d (%s)", r.Sym.Name, r.Type, sym.RelocName(ctxt.Arch, r.Type)) 218 } 219 case objabi.R_TLS_LE: 220 isAndroidX86 := objabi.GOOS == "android" && (ctxt.Arch.InFamily(sys.AMD64, sys.I386)) 221 222 if ctxt.LinkMode == LinkExternal && ctxt.IsELF && !isAndroidX86 { 223 r.Done = false 224 if r.Sym == nil { 225 r.Sym = ctxt.Tlsg 226 } 227 r.Xsym = r.Sym 228 r.Xadd = r.Add 229 o = 0 230 if ctxt.Arch.Family != sys.AMD64 { 231 o = r.Add 232 } 233 break 234 } 235 236 if ctxt.IsELF && ctxt.Arch.Family == sys.ARM { 237 // On ELF ARM, the thread pointer is 8 bytes before 238 // the start of the thread-local data block, so add 8 239 // to the actual TLS offset (r->sym->value). 240 // This 8 seems to be a fundamental constant of 241 // ELF on ARM (or maybe Glibc on ARM); it is not 242 // related to the fact that our own TLS storage happens 243 // to take up 8 bytes. 244 o = 8 + r.Sym.Value 245 } else if ctxt.IsELF || ctxt.HeadType == objabi.Hplan9 || ctxt.HeadType == objabi.Hdarwin || isAndroidX86 { 246 o = int64(ctxt.Tlsoffset) + r.Add 247 } else if ctxt.HeadType == objabi.Hwindows { 248 o = r.Add 249 } else { 250 log.Fatalf("unexpected R_TLS_LE relocation for %v", ctxt.HeadType) 251 } 252 case objabi.R_TLS_IE: 253 isAndroidX86 := objabi.GOOS == "android" && (ctxt.Arch.InFamily(sys.AMD64, sys.I386)) 254 255 if ctxt.LinkMode == LinkExternal && ctxt.IsELF && !isAndroidX86 { 256 r.Done = false 257 if r.Sym == nil { 258 r.Sym = ctxt.Tlsg 259 } 260 r.Xsym = r.Sym 261 r.Xadd = r.Add 262 o = 0 263 if ctxt.Arch.Family != sys.AMD64 { 264 o = r.Add 265 } 266 break 267 } 268 if ctxt.BuildMode == BuildModePIE && ctxt.IsELF { 269 // We are linking the final executable, so we 270 // can optimize any TLS IE relocation to LE. 271 if thearch.TLSIEtoLE == nil { 272 log.Fatalf("internal linking of TLS IE not supported on %v", ctxt.Arch.Family) 273 } 274 thearch.TLSIEtoLE(s, int(off), int(r.Siz)) 275 o = int64(ctxt.Tlsoffset) 276 // TODO: o += r.Add when ctxt.Arch.Family != sys.AMD64? 277 // Why do we treat r.Add differently on AMD64? 278 // Is the external linker using Xadd at all? 279 } else { 280 log.Fatalf("cannot handle R_TLS_IE (sym %s) when linking internally", s.Name) 281 } 282 case objabi.R_ADDR: 283 if ctxt.LinkMode == LinkExternal && r.Sym.Type != sym.SCONST { 284 r.Done = false 285 286 // set up addend for eventual relocation via outer symbol. 287 rs := r.Sym 288 289 r.Xadd = r.Add 290 for rs.Outer != nil { 291 r.Xadd += Symaddr(rs) - Symaddr(rs.Outer) 292 rs = rs.Outer 293 } 294 295 if rs.Type != sym.SHOSTOBJ && rs.Type != sym.SDYNIMPORT && rs.Sect == nil { 296 Errorf(s, "missing section for relocation target %s", rs.Name) 297 } 298 r.Xsym = rs 299 300 o = r.Xadd 301 if ctxt.IsELF { 302 if ctxt.Arch.Family == sys.AMD64 { 303 o = 0 304 } 305 } else if ctxt.HeadType == objabi.Hdarwin { 306 if rs.Type != sym.SHOSTOBJ { 307 o += Symaddr(rs) 308 } 309 } else if ctxt.HeadType == objabi.Hwindows { 310 // nothing to do 311 } else { 312 Errorf(s, "unhandled pcrel relocation to %s on %v", rs.Name, ctxt.HeadType) 313 } 314 315 break 316 } 317 // On AIX, if a relocated symbol is in .data, a second relocation 318 // must be done by the loader, as the section .data will be moved. 319 // The "default" symbol address is still needed by the loader so 320 // the current relocation can't be skipped. 321 // runtime.algarray is different because it will end up in .rodata section 322 if ctxt.HeadType == objabi.Haix && r.Sym.Sect.Seg == &Segdata && r.Sym.Name != "runtime.algarray" { 323 // It's not possible to make a loader relocation to a DWARF section. 324 // FIXME 325 if s.Sect.Seg != &Segdwarf { 326 xcoffaddloaderreloc(ctxt, s, r) 327 } 328 } 329 330 o = Symaddr(r.Sym) + r.Add 331 332 // On amd64, 4-byte offsets will be sign-extended, so it is impossible to 333 // access more than 2GB of static data; fail at link time is better than 334 // fail at runtime. See https://golang.org/issue/7980. 335 // Instead of special casing only amd64, we treat this as an error on all 336 // 64-bit architectures so as to be future-proof. 337 if int32(o) < 0 && ctxt.Arch.PtrSize > 4 && siz == 4 { 338 Errorf(s, "non-pc-relative relocation address for %s is too big: %#x (%#x + %#x)", r.Sym.Name, uint64(o), Symaddr(r.Sym), r.Add) 339 errorexit() 340 } 341 case objabi.R_DWARFSECREF: 342 if r.Sym.Sect == nil { 343 Errorf(s, "missing DWARF section for relocation target %s", r.Sym.Name) 344 } 345 346 if ctxt.LinkMode == LinkExternal { 347 r.Done = false 348 349 // On most platforms, the external linker needs to adjust DWARF references 350 // as it combines DWARF sections. However, on Darwin, dsymutil does the 351 // DWARF linking, and it understands how to follow section offsets. 352 // Leaving in the relocation records confuses it (see 353 // https://golang.org/issue/22068) so drop them for Darwin. 354 if ctxt.HeadType == objabi.Hdarwin { 355 r.Done = true 356 } 357 358 // PE code emits IMAGE_REL_I386_SECREL and IMAGE_REL_AMD64_SECREL 359 // for R_DWARFSECREF relocations, while R_ADDR is replaced with 360 // IMAGE_REL_I386_DIR32, IMAGE_REL_AMD64_ADDR64 and IMAGE_REL_AMD64_ADDR32. 361 // Do not replace R_DWARFSECREF with R_ADDR for windows - 362 // let PE code emit correct relocations. 363 if ctxt.HeadType != objabi.Hwindows { 364 r.Type = objabi.R_ADDR 365 } 366 367 r.Xsym = ctxt.Syms.ROLookup(r.Sym.Sect.Name, 0) 368 r.Xadd = r.Add + Symaddr(r.Sym) - int64(r.Sym.Sect.Vaddr) 369 370 o = r.Xadd 371 if ctxt.IsELF && ctxt.Arch.Family == sys.AMD64 { 372 o = 0 373 } 374 break 375 } 376 o = Symaddr(r.Sym) + r.Add - int64(r.Sym.Sect.Vaddr) 377 case objabi.R_WEAKADDROFF: 378 if !r.Sym.Attr.Reachable() { 379 continue 380 } 381 fallthrough 382 case objabi.R_ADDROFF: 383 // The method offset tables using this relocation expect the offset to be relative 384 // to the start of the first text section, even if there are multiple. 385 if r.Sym.Sect.Name == ".text" { 386 o = Symaddr(r.Sym) - int64(Segtext.Sections[0].Vaddr) + r.Add 387 } else { 388 o = Symaddr(r.Sym) - int64(r.Sym.Sect.Vaddr) + r.Add 389 } 390 391 case objabi.R_ADDRCUOFF: 392 // debug_range and debug_loc elements use this relocation type to get an 393 // offset from the start of the compile unit. 394 o = Symaddr(r.Sym) + r.Add - Symaddr(r.Sym.Lib.Textp[0]) 395 396 // r->sym can be null when CALL $(constant) is transformed from absolute PC to relative PC call. 397 case objabi.R_GOTPCREL: 398 if ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin && r.Sym != nil && r.Sym.Type != sym.SCONST { 399 r.Done = false 400 r.Xadd = r.Add 401 r.Xadd -= int64(r.Siz) // relative to address after the relocated chunk 402 r.Xsym = r.Sym 403 404 o = r.Xadd 405 o += int64(r.Siz) 406 break 407 } 408 fallthrough 409 case objabi.R_CALL, objabi.R_PCREL: 410 if ctxt.LinkMode == LinkExternal && r.Sym != nil && r.Sym.Type != sym.SCONST && (r.Sym.Sect != s.Sect || r.Type == objabi.R_GOTPCREL) { 411 r.Done = false 412 413 // set up addend for eventual relocation via outer symbol. 414 rs := r.Sym 415 416 r.Xadd = r.Add 417 for rs.Outer != nil { 418 r.Xadd += Symaddr(rs) - Symaddr(rs.Outer) 419 rs = rs.Outer 420 } 421 422 r.Xadd -= int64(r.Siz) // relative to address after the relocated chunk 423 if rs.Type != sym.SHOSTOBJ && rs.Type != sym.SDYNIMPORT && rs.Sect == nil { 424 Errorf(s, "missing section for relocation target %s", rs.Name) 425 } 426 r.Xsym = rs 427 428 o = r.Xadd 429 if ctxt.IsELF { 430 if ctxt.Arch.Family == sys.AMD64 { 431 o = 0 432 } 433 } else if ctxt.HeadType == objabi.Hdarwin { 434 if r.Type == objabi.R_CALL { 435 if ctxt.LinkMode == LinkExternal && rs.Type == sym.SDYNIMPORT { 436 switch ctxt.Arch.Family { 437 case sys.AMD64: 438 // AMD64 dynamic relocations are relative to the end of the relocation. 439 o += int64(r.Siz) 440 case sys.I386: 441 // I386 dynamic relocations are relative to the start of the section. 442 o -= int64(r.Off) // offset in symbol 443 o -= int64(s.Value - int64(s.Sect.Vaddr)) // offset of symbol in section 444 } 445 } else { 446 if rs.Type != sym.SHOSTOBJ { 447 o += int64(uint64(Symaddr(rs)) - rs.Sect.Vaddr) 448 } 449 o -= int64(r.Off) // relative to section offset, not symbol 450 } 451 } else if ctxt.Arch.Family == sys.ARM { 452 // see ../arm/asm.go:/machoreloc1 453 o += Symaddr(rs) - s.Value - int64(r.Off) 454 } else { 455 o += int64(r.Siz) 456 } 457 } else if ctxt.HeadType == objabi.Hwindows && ctxt.Arch.Family == sys.AMD64 { // only amd64 needs PCREL 458 // PE/COFF's PC32 relocation uses the address after the relocated 459 // bytes as the base. Compensate by skewing the addend. 460 o += int64(r.Siz) 461 } else { 462 Errorf(s, "unhandled pcrel relocation to %s on %v", rs.Name, ctxt.HeadType) 463 } 464 465 break 466 } 467 468 o = 0 469 if r.Sym != nil { 470 o += Symaddr(r.Sym) 471 } 472 473 o += r.Add - (s.Value + int64(r.Off) + int64(r.Siz)) 474 case objabi.R_SIZE: 475 o = r.Sym.Size + r.Add 476 } 477 478 if r.Variant != sym.RV_NONE { 479 o = thearch.Archrelocvariant(ctxt, r, s, o) 480 } 481 482 if false { 483 nam := "<nil>" 484 var addr int64 485 if r.Sym != nil { 486 nam = r.Sym.Name 487 addr = Symaddr(r.Sym) 488 } 489 xnam := "<nil>" 490 if r.Xsym != nil { 491 xnam = r.Xsym.Name 492 } 493 fmt.Printf("relocate %s %#x (%#x+%#x, size %d) => %s %#x +%#x (xsym: %s +%#x) [type %d (%s)/%d, %x]\n", s.Name, s.Value+int64(off), s.Value, r.Off, r.Siz, nam, addr, r.Add, xnam, r.Xadd, r.Type, sym.RelocName(ctxt.Arch, r.Type), r.Variant, o) 494 } 495 switch siz { 496 default: 497 Errorf(s, "bad reloc size %#x for %s", uint32(siz), r.Sym.Name) 498 fallthrough 499 500 // TODO(rsc): Remove. 501 case 1: 502 s.P[off] = byte(int8(o)) 503 case 2: 504 if o != int64(int16(o)) { 505 Errorf(s, "relocation address for %s is too big: %#x", r.Sym.Name, o) 506 } 507 i16 := int16(o) 508 ctxt.Arch.ByteOrder.PutUint16(s.P[off:], uint16(i16)) 509 case 4: 510 if r.Type == objabi.R_PCREL || r.Type == objabi.R_CALL { 511 if o != int64(int32(o)) { 512 Errorf(s, "pc-relative relocation address for %s is too big: %#x", r.Sym.Name, o) 513 } 514 } else { 515 if o != int64(int32(o)) && o != int64(uint32(o)) { 516 Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", r.Sym.Name, uint64(o)) 517 } 518 } 519 520 fl := int32(o) 521 ctxt.Arch.ByteOrder.PutUint32(s.P[off:], uint32(fl)) 522 case 8: 523 ctxt.Arch.ByteOrder.PutUint64(s.P[off:], uint64(o)) 524 } 525 } 526 } 527 528 func (ctxt *Link) reloc() { 529 if ctxt.Debugvlog != 0 { 530 ctxt.Logf("%5.2f reloc\n", Cputime()) 531 } 532 533 for _, s := range ctxt.Textp { 534 relocsym(ctxt, s) 535 } 536 for _, s := range datap { 537 relocsym(ctxt, s) 538 } 539 for _, s := range dwarfp { 540 relocsym(ctxt, s) 541 } 542 } 543 544 func windynrelocsym(ctxt *Link, rel, s *sym.Symbol) { 545 for ri := range s.R { 546 r := &s.R[ri] 547 targ := r.Sym 548 if targ == nil { 549 continue 550 } 551 if !targ.Attr.Reachable() { 552 if r.Type == objabi.R_WEAKADDROFF { 553 continue 554 } 555 Errorf(s, "dynamic relocation to unreachable symbol %s", targ.Name) 556 } 557 if r.Sym.Plt() == -2 && r.Sym.Got() != -2 { // make dynimport JMP table for PE object files. 558 targ.SetPlt(int32(rel.Size)) 559 r.Sym = rel 560 r.Add = int64(targ.Plt()) 561 562 // jmp *addr 563 switch ctxt.Arch.Family { 564 default: 565 Errorf(s, "unsupported arch %v", ctxt.Arch.Family) 566 return 567 case sys.I386: 568 rel.AddUint8(0xff) 569 rel.AddUint8(0x25) 570 rel.AddAddr(ctxt.Arch, targ) 571 rel.AddUint8(0x90) 572 rel.AddUint8(0x90) 573 case sys.AMD64: 574 rel.AddUint8(0xff) 575 rel.AddUint8(0x24) 576 rel.AddUint8(0x25) 577 rel.AddAddrPlus4(targ, 0) 578 rel.AddUint8(0x90) 579 } 580 } else if r.Sym.Plt() >= 0 { 581 r.Sym = rel 582 r.Add = int64(targ.Plt()) 583 } 584 } 585 } 586 587 // windynrelocsyms generates jump table to C library functions that will be 588 // added later. windynrelocsyms writes the table into .rel symbol. 589 func (ctxt *Link) windynrelocsyms() { 590 if !(ctxt.HeadType == objabi.Hwindows && iscgo && ctxt.LinkMode == LinkInternal) { 591 return 592 } 593 if ctxt.Debugvlog != 0 { 594 ctxt.Logf("%5.2f windynrelocsyms\n", Cputime()) 595 } 596 597 /* relocation table */ 598 rel := ctxt.Syms.Lookup(".rel", 0) 599 rel.Attr |= sym.AttrReachable 600 rel.Type = sym.STEXT 601 ctxt.Textp = append(ctxt.Textp, rel) 602 603 for _, s := range ctxt.Textp { 604 if s == rel { 605 continue 606 } 607 windynrelocsym(ctxt, rel, s) 608 } 609 } 610 611 func dynrelocsym(ctxt *Link, s *sym.Symbol) { 612 for ri := range s.R { 613 r := &s.R[ri] 614 if ctxt.BuildMode == BuildModePIE && ctxt.LinkMode == LinkInternal { 615 // It's expected that some relocations will be done 616 // later by relocsym (R_TLS_LE, R_ADDROFF), so 617 // don't worry if Adddynrel returns false. 618 thearch.Adddynrel(ctxt, s, r) 619 continue 620 } 621 622 if r.Sym != nil && r.Sym.Type == sym.SDYNIMPORT || r.Type >= 256 { 623 if r.Sym != nil && !r.Sym.Attr.Reachable() { 624 Errorf(s, "dynamic relocation to unreachable symbol %s", r.Sym.Name) 625 } 626 if !thearch.Adddynrel(ctxt, s, r) { 627 Errorf(s, "unsupported dynamic relocation for symbol %s (type=%d (%s) stype=%d (%s))", r.Sym.Name, r.Type, sym.RelocName(ctxt.Arch, r.Type), r.Sym.Type, r.Sym.Type) 628 } 629 } 630 } 631 } 632 633 func dynreloc(ctxt *Link, data *[sym.SXREF][]*sym.Symbol) { 634 if ctxt.HeadType == objabi.Hwindows { 635 return 636 } 637 // -d suppresses dynamic loader format, so we may as well not 638 // compute these sections or mark their symbols as reachable. 639 if *FlagD { 640 return 641 } 642 if ctxt.Debugvlog != 0 { 643 ctxt.Logf("%5.2f dynreloc\n", Cputime()) 644 } 645 646 for _, s := range ctxt.Textp { 647 dynrelocsym(ctxt, s) 648 } 649 for _, syms := range data { 650 for _, s := range syms { 651 dynrelocsym(ctxt, s) 652 } 653 } 654 if ctxt.IsELF { 655 elfdynhash(ctxt) 656 } 657 } 658 659 func Codeblk(ctxt *Link, addr int64, size int64) { 660 CodeblkPad(ctxt, addr, size, zeros[:]) 661 } 662 func CodeblkPad(ctxt *Link, addr int64, size int64, pad []byte) { 663 if *flagA { 664 ctxt.Logf("codeblk [%#x,%#x) at offset %#x\n", addr, addr+size, ctxt.Out.Offset()) 665 } 666 667 blk(ctxt, ctxt.Textp, addr, size, pad) 668 669 /* again for printing */ 670 if !*flagA { 671 return 672 } 673 674 syms := ctxt.Textp 675 for i, s := range syms { 676 if !s.Attr.Reachable() { 677 continue 678 } 679 if s.Value >= addr { 680 syms = syms[i:] 681 break 682 } 683 } 684 685 eaddr := addr + size 686 for _, s := range syms { 687 if !s.Attr.Reachable() { 688 continue 689 } 690 if s.Value >= eaddr { 691 break 692 } 693 694 if addr < s.Value { 695 ctxt.Logf("%-20s %.8x|", "_", uint64(addr)) 696 for ; addr < s.Value; addr++ { 697 ctxt.Logf(" %.2x", 0) 698 } 699 ctxt.Logf("\n") 700 } 701 702 ctxt.Logf("%.6x\t%-20s\n", uint64(addr), s.Name) 703 q := s.P 704 705 for len(q) >= 16 { 706 ctxt.Logf("%.6x\t% x\n", uint64(addr), q[:16]) 707 addr += 16 708 q = q[16:] 709 } 710 711 if len(q) > 0 { 712 ctxt.Logf("%.6x\t% x\n", uint64(addr), q) 713 addr += int64(len(q)) 714 } 715 } 716 717 if addr < eaddr { 718 ctxt.Logf("%-20s %.8x|", "_", uint64(addr)) 719 for ; addr < eaddr; addr++ { 720 ctxt.Logf(" %.2x", 0) 721 } 722 } 723 } 724 725 func blk(ctxt *Link, syms []*sym.Symbol, addr, size int64, pad []byte) { 726 for i, s := range syms { 727 if !s.Attr.SubSymbol() && s.Value >= addr { 728 syms = syms[i:] 729 break 730 } 731 } 732 733 // This doesn't distinguish the memory size from the file 734 // size, and it lays out the file based on Symbol.Value, which 735 // is the virtual address. DWARF compression changes file sizes, 736 // so dwarfcompress will fix this up later if necessary. 737 eaddr := addr + size 738 for _, s := range syms { 739 if s.Attr.SubSymbol() { 740 continue 741 } 742 if s.Value >= eaddr { 743 break 744 } 745 if s.Value < addr { 746 Errorf(s, "phase error: addr=%#x but sym=%#x type=%d", addr, s.Value, s.Type) 747 errorexit() 748 } 749 if addr < s.Value { 750 ctxt.Out.WriteStringPad("", int(s.Value-addr), pad) 751 addr = s.Value 752 } 753 ctxt.Out.Write(s.P) 754 addr += int64(len(s.P)) 755 if addr < s.Value+s.Size { 756 ctxt.Out.WriteStringPad("", int(s.Value+s.Size-addr), pad) 757 addr = s.Value + s.Size 758 } 759 if addr != s.Value+s.Size { 760 Errorf(s, "phase error: addr=%#x value+size=%#x", addr, s.Value+s.Size) 761 errorexit() 762 } 763 if s.Value+s.Size >= eaddr { 764 break 765 } 766 } 767 768 if addr < eaddr { 769 ctxt.Out.WriteStringPad("", int(eaddr-addr), pad) 770 } 771 ctxt.Out.Flush() 772 } 773 774 func Datblk(ctxt *Link, addr int64, size int64) { 775 if *flagA { 776 ctxt.Logf("datblk [%#x,%#x) at offset %#x\n", addr, addr+size, ctxt.Out.Offset()) 777 } 778 779 blk(ctxt, datap, addr, size, zeros[:]) 780 781 /* again for printing */ 782 if !*flagA { 783 return 784 } 785 786 syms := datap 787 for i, sym := range syms { 788 if sym.Value >= addr { 789 syms = syms[i:] 790 break 791 } 792 } 793 794 eaddr := addr + size 795 for _, sym := range syms { 796 if sym.Value >= eaddr { 797 break 798 } 799 if addr < sym.Value { 800 ctxt.Logf("\t%.8x| 00 ...\n", uint64(addr)) 801 addr = sym.Value 802 } 803 804 ctxt.Logf("%s\n\t%.8x|", sym.Name, uint64(addr)) 805 for i, b := range sym.P { 806 if i > 0 && i%16 == 0 { 807 ctxt.Logf("\n\t%.8x|", uint64(addr)+uint64(i)) 808 } 809 ctxt.Logf(" %.2x", b) 810 } 811 812 addr += int64(len(sym.P)) 813 for ; addr < sym.Value+sym.Size; addr++ { 814 ctxt.Logf(" %.2x", 0) 815 } 816 ctxt.Logf("\n") 817 818 if ctxt.LinkMode != LinkExternal { 819 continue 820 } 821 for i := range sym.R { 822 r := &sym.R[i] // Copying sym.Reloc has measurable impact on performance 823 rsname := "" 824 if r.Sym != nil { 825 rsname = r.Sym.Name 826 } 827 typ := "?" 828 switch r.Type { 829 case objabi.R_ADDR: 830 typ = "addr" 831 case objabi.R_PCREL: 832 typ = "pcrel" 833 case objabi.R_CALL: 834 typ = "call" 835 } 836 ctxt.Logf("\treloc %.8x/%d %s %s+%#x [%#x]\n", uint(sym.Value+int64(r.Off)), r.Siz, typ, rsname, r.Add, r.Sym.Value+r.Add) 837 } 838 } 839 840 if addr < eaddr { 841 ctxt.Logf("\t%.8x| 00 ...\n", uint(addr)) 842 } 843 ctxt.Logf("\t%.8x|\n", uint(eaddr)) 844 } 845 846 func Dwarfblk(ctxt *Link, addr int64, size int64) { 847 if *flagA { 848 ctxt.Logf("dwarfblk [%#x,%#x) at offset %#x\n", addr, addr+size, ctxt.Out.Offset()) 849 } 850 851 blk(ctxt, dwarfp, addr, size, zeros[:]) 852 } 853 854 var zeros [512]byte 855 856 var ( 857 strdata = make(map[string]string) 858 strnames []string 859 ) 860 861 func addstrdata1(ctxt *Link, arg string) { 862 eq := strings.Index(arg, "=") 863 dot := strings.LastIndex(arg[:eq+1], ".") 864 if eq < 0 || dot < 0 { 865 Exitf("-X flag requires argument of the form importpath.name=value") 866 } 867 pkg := arg[:dot] 868 if ctxt.BuildMode == BuildModePlugin && pkg == "main" { 869 pkg = *flagPluginPath 870 } 871 pkg = objabi.PathToPrefix(pkg) 872 name := pkg + arg[dot:eq] 873 value := arg[eq+1:] 874 if _, ok := strdata[name]; !ok { 875 strnames = append(strnames, name) 876 } 877 strdata[name] = value 878 } 879 880 // addstrdata sets the initial value of the string variable name to value. 881 func addstrdata(ctxt *Link, name, value string) { 882 s := ctxt.Syms.ROLookup(name, 0) 883 if s == nil || s.Gotype == nil { 884 // Not defined in the loaded packages. 885 return 886 } 887 if s.Gotype.Name != "type.string" { 888 Errorf(s, "cannot set with -X: not a var of type string (%s)", s.Gotype.Name) 889 return 890 } 891 if s.Type == sym.SBSS { 892 s.Type = sym.SDATA 893 } 894 895 p := fmt.Sprintf("%s.str", s.Name) 896 sp := ctxt.Syms.Lookup(p, 0) 897 898 Addstring(sp, value) 899 sp.Type = sym.SRODATA 900 901 s.Size = 0 902 s.P = s.P[:0] 903 s.R = s.R[:0] 904 reachable := s.Attr.Reachable() 905 s.AddAddr(ctxt.Arch, sp) 906 s.AddUint(ctxt.Arch, uint64(len(value))) 907 908 // addstring, addaddr, etc., mark the symbols as reachable. 909 // In this case that is not necessarily true, so stick to what 910 // we know before entering this function. 911 s.Attr.Set(sym.AttrReachable, reachable) 912 913 sp.Attr.Set(sym.AttrReachable, reachable) 914 } 915 916 func (ctxt *Link) dostrdata() { 917 for _, name := range strnames { 918 addstrdata(ctxt, name, strdata[name]) 919 } 920 } 921 922 func Addstring(s *sym.Symbol, str string) int64 { 923 if s.Type == 0 { 924 s.Type = sym.SNOPTRDATA 925 } 926 s.Attr |= sym.AttrReachable 927 r := s.Size 928 if s.Name == ".shstrtab" { 929 elfsetstring(s, str, int(r)) 930 } 931 s.P = append(s.P, str...) 932 s.P = append(s.P, 0) 933 s.Size = int64(len(s.P)) 934 return r 935 } 936 937 // addgostring adds str, as a Go string value, to s. symname is the name of the 938 // symbol used to define the string data and must be unique per linked object. 939 func addgostring(ctxt *Link, s *sym.Symbol, symname, str string) { 940 sdata := ctxt.Syms.Lookup(symname, 0) 941 if sdata.Type != sym.Sxxx { 942 Errorf(s, "duplicate symname in addgostring: %s", symname) 943 } 944 sdata.Attr |= sym.AttrReachable 945 sdata.Attr |= sym.AttrLocal 946 sdata.Type = sym.SRODATA 947 sdata.Size = int64(len(str)) 948 sdata.P = []byte(str) 949 s.AddAddr(ctxt.Arch, sdata) 950 s.AddUint(ctxt.Arch, uint64(len(str))) 951 } 952 953 func addinitarrdata(ctxt *Link, s *sym.Symbol) { 954 p := s.Name + ".ptr" 955 sp := ctxt.Syms.Lookup(p, 0) 956 sp.Type = sym.SINITARR 957 sp.Size = 0 958 sp.Attr |= sym.AttrDuplicateOK 959 sp.AddAddr(ctxt.Arch, s) 960 } 961 962 func dosymtype(ctxt *Link) { 963 switch ctxt.BuildMode { 964 case BuildModeCArchive, BuildModeCShared: 965 for _, s := range ctxt.Syms.Allsym { 966 // Create a new entry in the .init_array section that points to the 967 // library initializer function. 968 if s.Name == *flagEntrySymbol { 969 addinitarrdata(ctxt, s) 970 } 971 } 972 } 973 } 974 975 // symalign returns the required alignment for the given symbol s. 976 func symalign(s *sym.Symbol) int32 { 977 min := int32(thearch.Minalign) 978 if s.Align >= min { 979 return s.Align 980 } else if s.Align != 0 { 981 return min 982 } 983 if strings.HasPrefix(s.Name, "go.string.") || strings.HasPrefix(s.Name, "type..namedata.") { 984 // String data is just bytes. 985 // If we align it, we waste a lot of space to padding. 986 return min 987 } 988 align := int32(thearch.Maxalign) 989 for int64(align) > s.Size && align > min { 990 align >>= 1 991 } 992 return align 993 } 994 995 func aligndatsize(datsize int64, s *sym.Symbol) int64 { 996 return Rnd(datsize, int64(symalign(s))) 997 } 998 999 const debugGCProg = false 1000 1001 type GCProg struct { 1002 ctxt *Link 1003 sym *sym.Symbol 1004 w gcprog.Writer 1005 } 1006 1007 func (p *GCProg) Init(ctxt *Link, name string) { 1008 p.ctxt = ctxt 1009 p.sym = ctxt.Syms.Lookup(name, 0) 1010 p.w.Init(p.writeByte(ctxt)) 1011 if debugGCProg { 1012 fmt.Fprintf(os.Stderr, "ld: start GCProg %s\n", name) 1013 p.w.Debug(os.Stderr) 1014 } 1015 } 1016 1017 func (p *GCProg) writeByte(ctxt *Link) func(x byte) { 1018 return func(x byte) { 1019 p.sym.AddUint8(x) 1020 } 1021 } 1022 1023 func (p *GCProg) End(size int64) { 1024 p.w.ZeroUntil(size / int64(p.ctxt.Arch.PtrSize)) 1025 p.w.End() 1026 if debugGCProg { 1027 fmt.Fprintf(os.Stderr, "ld: end GCProg\n") 1028 } 1029 } 1030 1031 func (p *GCProg) AddSym(s *sym.Symbol) { 1032 typ := s.Gotype 1033 // Things without pointers should be in sym.SNOPTRDATA or sym.SNOPTRBSS; 1034 // everything we see should have pointers and should therefore have a type. 1035 if typ == nil { 1036 switch s.Name { 1037 case "runtime.data", "runtime.edata", "runtime.bss", "runtime.ebss": 1038 // Ignore special symbols that are sometimes laid out 1039 // as real symbols. See comment about dyld on darwin in 1040 // the address function. 1041 return 1042 } 1043 Errorf(s, "missing Go type information for global symbol: size %d", s.Size) 1044 return 1045 } 1046 1047 ptrsize := int64(p.ctxt.Arch.PtrSize) 1048 nptr := decodetypePtrdata(p.ctxt.Arch, typ) / ptrsize 1049 1050 if debugGCProg { 1051 fmt.Fprintf(os.Stderr, "gcprog sym: %s at %d (ptr=%d+%d)\n", s.Name, s.Value, s.Value/ptrsize, nptr) 1052 } 1053 1054 if decodetypeUsegcprog(p.ctxt.Arch, typ) == 0 { 1055 // Copy pointers from mask into program. 1056 mask := decodetypeGcmask(p.ctxt, typ) 1057 for i := int64(0); i < nptr; i++ { 1058 if (mask[i/8]>>uint(i%8))&1 != 0 { 1059 p.w.Ptr(s.Value/ptrsize + i) 1060 } 1061 } 1062 return 1063 } 1064 1065 // Copy program. 1066 prog := decodetypeGcprog(p.ctxt, typ) 1067 p.w.ZeroUntil(s.Value / ptrsize) 1068 p.w.Append(prog[4:], nptr) 1069 } 1070 1071 // dataSortKey is used to sort a slice of data symbol *sym.Symbol pointers. 1072 // The sort keys are kept inline to improve cache behavior while sorting. 1073 type dataSortKey struct { 1074 size int64 1075 name string 1076 sym *sym.Symbol 1077 } 1078 1079 type bySizeAndName []dataSortKey 1080 1081 func (d bySizeAndName) Len() int { return len(d) } 1082 func (d bySizeAndName) Swap(i, j int) { d[i], d[j] = d[j], d[i] } 1083 func (d bySizeAndName) Less(i, j int) bool { 1084 s1, s2 := d[i], d[j] 1085 if s1.size != s2.size { 1086 return s1.size < s2.size 1087 } 1088 return s1.name < s2.name 1089 } 1090 1091 // cutoff is the maximum data section size permitted by the linker 1092 // (see issue #9862). 1093 const cutoff = 2e9 // 2 GB (or so; looks better in errors than 2^31) 1094 1095 func checkdatsize(ctxt *Link, datsize int64, symn sym.SymKind) { 1096 if datsize > cutoff { 1097 Errorf(nil, "too much data in section %v (over %v bytes)", symn, cutoff) 1098 } 1099 } 1100 1101 // datap is a collection of reachable data symbols in address order. 1102 // Generated by dodata. 1103 var datap []*sym.Symbol 1104 1105 func (ctxt *Link) dodata() { 1106 if ctxt.Debugvlog != 0 { 1107 ctxt.Logf("%5.2f dodata\n", Cputime()) 1108 } 1109 1110 if ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin { 1111 // The values in moduledata are filled out by relocations 1112 // pointing to the addresses of these special symbols. 1113 // Typically these symbols have no size and are not laid 1114 // out with their matching section. 1115 // 1116 // However on darwin, dyld will find the special symbol 1117 // in the first loaded module, even though it is local. 1118 // 1119 // (An hypothesis, formed without looking in the dyld sources: 1120 // these special symbols have no size, so their address 1121 // matches a real symbol. The dynamic linker assumes we 1122 // want the normal symbol with the same address and finds 1123 // it in the other module.) 1124 // 1125 // To work around this we lay out the symbls whose 1126 // addresses are vital for multi-module programs to work 1127 // as normal symbols, and give them a little size. 1128 bss := ctxt.Syms.Lookup("runtime.bss", 0) 1129 bss.Size = 8 1130 bss.Attr.Set(sym.AttrSpecial, false) 1131 1132 ctxt.Syms.Lookup("runtime.ebss", 0).Attr.Set(sym.AttrSpecial, false) 1133 1134 data := ctxt.Syms.Lookup("runtime.data", 0) 1135 data.Size = 8 1136 data.Attr.Set(sym.AttrSpecial, false) 1137 1138 ctxt.Syms.Lookup("runtime.edata", 0).Attr.Set(sym.AttrSpecial, false) 1139 1140 types := ctxt.Syms.Lookup("runtime.types", 0) 1141 types.Type = sym.STYPE 1142 types.Size = 8 1143 types.Attr.Set(sym.AttrSpecial, false) 1144 1145 etypes := ctxt.Syms.Lookup("runtime.etypes", 0) 1146 etypes.Type = sym.SFUNCTAB 1147 etypes.Attr.Set(sym.AttrSpecial, false) 1148 } 1149 1150 // Collect data symbols by type into data. 1151 var data [sym.SXREF][]*sym.Symbol 1152 for _, s := range ctxt.Syms.Allsym { 1153 if !s.Attr.Reachable() || s.Attr.Special() || s.Attr.SubSymbol() { 1154 continue 1155 } 1156 if s.Type <= sym.STEXT || s.Type >= sym.SXREF { 1157 continue 1158 } 1159 data[s.Type] = append(data[s.Type], s) 1160 } 1161 1162 // Now that we have the data symbols, but before we start 1163 // to assign addresses, record all the necessary 1164 // dynamic relocations. These will grow the relocation 1165 // symbol, which is itself data. 1166 // 1167 // On darwin, we need the symbol table numbers for dynreloc. 1168 if ctxt.HeadType == objabi.Hdarwin { 1169 machosymorder(ctxt) 1170 } 1171 dynreloc(ctxt, &data) 1172 1173 if ctxt.UseRelro() { 1174 // "read only" data with relocations needs to go in its own section 1175 // when building a shared library. We do this by boosting objects of 1176 // type SXXX with relocations to type SXXXRELRO. 1177 for _, symnro := range sym.ReadOnly { 1178 symnrelro := sym.RelROMap[symnro] 1179 1180 ro := []*sym.Symbol{} 1181 relro := data[symnrelro] 1182 1183 for _, s := range data[symnro] { 1184 isRelro := len(s.R) > 0 1185 switch s.Type { 1186 case sym.STYPE, sym.STYPERELRO, sym.SGOFUNCRELRO: 1187 // Symbols are not sorted yet, so it is possible 1188 // that an Outer symbol has been changed to a 1189 // relro Type before it reaches here. 1190 isRelro = true 1191 } 1192 if isRelro { 1193 s.Type = symnrelro 1194 if s.Outer != nil { 1195 s.Outer.Type = s.Type 1196 } 1197 relro = append(relro, s) 1198 } else { 1199 ro = append(ro, s) 1200 } 1201 } 1202 1203 // Check that we haven't made two symbols with the same .Outer into 1204 // different types (because references two symbols with non-nil Outer 1205 // become references to the outer symbol + offset it's vital that the 1206 // symbol and the outer end up in the same section). 1207 for _, s := range relro { 1208 if s.Outer != nil && s.Outer.Type != s.Type { 1209 Errorf(s, "inconsistent types for symbol and its Outer %s (%v != %v)", 1210 s.Outer.Name, s.Type, s.Outer.Type) 1211 } 1212 } 1213 1214 data[symnro] = ro 1215 data[symnrelro] = relro 1216 } 1217 } 1218 1219 // Sort symbols. 1220 var dataMaxAlign [sym.SXREF]int32 1221 var wg sync.WaitGroup 1222 for symn := range data { 1223 symn := sym.SymKind(symn) 1224 wg.Add(1) 1225 go func() { 1226 data[symn], dataMaxAlign[symn] = dodataSect(ctxt, symn, data[symn]) 1227 wg.Done() 1228 }() 1229 } 1230 wg.Wait() 1231 1232 // Allocate sections. 1233 // Data is processed before segtext, because we need 1234 // to see all symbols in the .data and .bss sections in order 1235 // to generate garbage collection information. 1236 datsize := int64(0) 1237 1238 // Writable data sections that do not need any specialized handling. 1239 writable := []sym.SymKind{ 1240 sym.SELFSECT, 1241 sym.SMACHO, 1242 sym.SMACHOGOT, 1243 sym.SWINDOWS, 1244 } 1245 for _, symn := range writable { 1246 for _, s := range data[symn] { 1247 sect := addsection(ctxt.Arch, &Segdata, s.Name, 06) 1248 sect.Align = symalign(s) 1249 datsize = Rnd(datsize, int64(sect.Align)) 1250 sect.Vaddr = uint64(datsize) 1251 s.Sect = sect 1252 s.Type = sym.SDATA 1253 s.Value = int64(uint64(datsize) - sect.Vaddr) 1254 datsize += s.Size 1255 sect.Length = uint64(datsize) - sect.Vaddr 1256 } 1257 checkdatsize(ctxt, datsize, symn) 1258 } 1259 1260 // .got (and .toc on ppc64) 1261 if len(data[sym.SELFGOT]) > 0 { 1262 sect := addsection(ctxt.Arch, &Segdata, ".got", 06) 1263 sect.Align = dataMaxAlign[sym.SELFGOT] 1264 datsize = Rnd(datsize, int64(sect.Align)) 1265 sect.Vaddr = uint64(datsize) 1266 for _, s := range data[sym.SELFGOT] { 1267 datsize = aligndatsize(datsize, s) 1268 s.Sect = sect 1269 s.Type = sym.SDATA 1270 s.Value = int64(uint64(datsize) - sect.Vaddr) 1271 1272 // Resolve .TOC. symbol for this object file (ppc64) 1273 toc := ctxt.Syms.ROLookup(".TOC.", int(s.Version)) 1274 if toc != nil { 1275 toc.Sect = sect 1276 toc.Outer = s 1277 toc.Sub = s.Sub 1278 s.Sub = toc 1279 1280 toc.Value = 0x8000 1281 } 1282 1283 datsize += s.Size 1284 } 1285 checkdatsize(ctxt, datsize, sym.SELFGOT) 1286 sect.Length = uint64(datsize) - sect.Vaddr 1287 } 1288 1289 /* pointer-free data */ 1290 sect := addsection(ctxt.Arch, &Segdata, ".noptrdata", 06) 1291 sect.Align = dataMaxAlign[sym.SNOPTRDATA] 1292 datsize = Rnd(datsize, int64(sect.Align)) 1293 sect.Vaddr = uint64(datsize) 1294 ctxt.Syms.Lookup("runtime.noptrdata", 0).Sect = sect 1295 ctxt.Syms.Lookup("runtime.enoptrdata", 0).Sect = sect 1296 for _, s := range data[sym.SNOPTRDATA] { 1297 datsize = aligndatsize(datsize, s) 1298 s.Sect = sect 1299 s.Type = sym.SDATA 1300 s.Value = int64(uint64(datsize) - sect.Vaddr) 1301 datsize += s.Size 1302 } 1303 checkdatsize(ctxt, datsize, sym.SNOPTRDATA) 1304 sect.Length = uint64(datsize) - sect.Vaddr 1305 1306 hasinitarr := ctxt.linkShared 1307 1308 /* shared library initializer */ 1309 switch ctxt.BuildMode { 1310 case BuildModeCArchive, BuildModeCShared, BuildModeShared, BuildModePlugin: 1311 hasinitarr = true 1312 } 1313 if hasinitarr { 1314 sect := addsection(ctxt.Arch, &Segdata, ".init_array", 06) 1315 sect.Align = dataMaxAlign[sym.SINITARR] 1316 datsize = Rnd(datsize, int64(sect.Align)) 1317 sect.Vaddr = uint64(datsize) 1318 for _, s := range data[sym.SINITARR] { 1319 datsize = aligndatsize(datsize, s) 1320 s.Sect = sect 1321 s.Value = int64(uint64(datsize) - sect.Vaddr) 1322 datsize += s.Size 1323 } 1324 sect.Length = uint64(datsize) - sect.Vaddr 1325 checkdatsize(ctxt, datsize, sym.SINITARR) 1326 } 1327 1328 /* data */ 1329 sect = addsection(ctxt.Arch, &Segdata, ".data", 06) 1330 sect.Align = dataMaxAlign[sym.SDATA] 1331 datsize = Rnd(datsize, int64(sect.Align)) 1332 sect.Vaddr = uint64(datsize) 1333 ctxt.Syms.Lookup("runtime.data", 0).Sect = sect 1334 ctxt.Syms.Lookup("runtime.edata", 0).Sect = sect 1335 var gc GCProg 1336 gc.Init(ctxt, "runtime.gcdata") 1337 for _, s := range data[sym.SDATA] { 1338 s.Sect = sect 1339 s.Type = sym.SDATA 1340 datsize = aligndatsize(datsize, s) 1341 s.Value = int64(uint64(datsize) - sect.Vaddr) 1342 gc.AddSym(s) 1343 datsize += s.Size 1344 } 1345 // On AIX, TOC entries must be the last of .data 1346 for _, s := range data[sym.SXCOFFTOC] { 1347 s.Sect = sect 1348 s.Type = sym.SDATA 1349 datsize = aligndatsize(datsize, s) 1350 s.Value = int64(uint64(datsize) - sect.Vaddr) 1351 datsize += s.Size 1352 } 1353 checkdatsize(ctxt, datsize, sym.SDATA) 1354 sect.Length = uint64(datsize) - sect.Vaddr 1355 gc.End(int64(sect.Length)) 1356 1357 /* bss */ 1358 sect = addsection(ctxt.Arch, &Segdata, ".bss", 06) 1359 sect.Align = dataMaxAlign[sym.SBSS] 1360 datsize = Rnd(datsize, int64(sect.Align)) 1361 sect.Vaddr = uint64(datsize) 1362 ctxt.Syms.Lookup("runtime.bss", 0).Sect = sect 1363 ctxt.Syms.Lookup("runtime.ebss", 0).Sect = sect 1364 gc = GCProg{} 1365 gc.Init(ctxt, "runtime.gcbss") 1366 for _, s := range data[sym.SBSS] { 1367 s.Sect = sect 1368 datsize = aligndatsize(datsize, s) 1369 s.Value = int64(uint64(datsize) - sect.Vaddr) 1370 gc.AddSym(s) 1371 datsize += s.Size 1372 } 1373 checkdatsize(ctxt, datsize, sym.SBSS) 1374 sect.Length = uint64(datsize) - sect.Vaddr 1375 gc.End(int64(sect.Length)) 1376 1377 /* pointer-free bss */ 1378 sect = addsection(ctxt.Arch, &Segdata, ".noptrbss", 06) 1379 sect.Align = dataMaxAlign[sym.SNOPTRBSS] 1380 datsize = Rnd(datsize, int64(sect.Align)) 1381 sect.Vaddr = uint64(datsize) 1382 ctxt.Syms.Lookup("runtime.noptrbss", 0).Sect = sect 1383 ctxt.Syms.Lookup("runtime.enoptrbss", 0).Sect = sect 1384 for _, s := range data[sym.SNOPTRBSS] { 1385 datsize = aligndatsize(datsize, s) 1386 s.Sect = sect 1387 s.Value = int64(uint64(datsize) - sect.Vaddr) 1388 datsize += s.Size 1389 } 1390 1391 sect.Length = uint64(datsize) - sect.Vaddr 1392 ctxt.Syms.Lookup("runtime.end", 0).Sect = sect 1393 checkdatsize(ctxt, datsize, sym.SNOPTRBSS) 1394 1395 if len(data[sym.STLSBSS]) > 0 { 1396 var sect *sym.Section 1397 if ctxt.IsELF && (ctxt.LinkMode == LinkExternal || !*FlagD) { 1398 sect = addsection(ctxt.Arch, &Segdata, ".tbss", 06) 1399 sect.Align = int32(ctxt.Arch.PtrSize) 1400 sect.Vaddr = 0 1401 } 1402 datsize = 0 1403 1404 for _, s := range data[sym.STLSBSS] { 1405 datsize = aligndatsize(datsize, s) 1406 s.Sect = sect 1407 s.Value = datsize 1408 datsize += s.Size 1409 } 1410 checkdatsize(ctxt, datsize, sym.STLSBSS) 1411 1412 if sect != nil { 1413 sect.Length = uint64(datsize) 1414 } 1415 } 1416 1417 /* 1418 * We finished data, begin read-only data. 1419 * Not all systems support a separate read-only non-executable data section. 1420 * ELF and Windows PE systems do. 1421 * OS X and Plan 9 do not. 1422 * And if we're using external linking mode, the point is moot, 1423 * since it's not our decision; that code expects the sections in 1424 * segtext. 1425 */ 1426 var segro *sym.Segment 1427 if ctxt.IsELF && ctxt.LinkMode == LinkInternal { 1428 segro = &Segrodata 1429 } else if ctxt.HeadType == objabi.Hwindows { 1430 segro = &Segrodata 1431 } else { 1432 segro = &Segtext 1433 } 1434 1435 datsize = 0 1436 1437 /* read-only executable ELF, Mach-O sections */ 1438 if len(data[sym.STEXT]) != 0 { 1439 Errorf(nil, "dodata found an sym.STEXT symbol: %s", data[sym.STEXT][0].Name) 1440 } 1441 for _, s := range data[sym.SELFRXSECT] { 1442 sect := addsection(ctxt.Arch, &Segtext, s.Name, 04) 1443 sect.Align = symalign(s) 1444 datsize = Rnd(datsize, int64(sect.Align)) 1445 sect.Vaddr = uint64(datsize) 1446 s.Sect = sect 1447 s.Type = sym.SRODATA 1448 s.Value = int64(uint64(datsize) - sect.Vaddr) 1449 datsize += s.Size 1450 sect.Length = uint64(datsize) - sect.Vaddr 1451 checkdatsize(ctxt, datsize, sym.SELFRXSECT) 1452 } 1453 1454 /* read-only data */ 1455 sect = addsection(ctxt.Arch, segro, ".rodata", 04) 1456 1457 sect.Vaddr = 0 1458 ctxt.Syms.Lookup("runtime.rodata", 0).Sect = sect 1459 ctxt.Syms.Lookup("runtime.erodata", 0).Sect = sect 1460 if !ctxt.UseRelro() { 1461 ctxt.Syms.Lookup("runtime.types", 0).Sect = sect 1462 ctxt.Syms.Lookup("runtime.etypes", 0).Sect = sect 1463 } 1464 for _, symn := range sym.ReadOnly { 1465 align := dataMaxAlign[symn] 1466 if sect.Align < align { 1467 sect.Align = align 1468 } 1469 } 1470 datsize = Rnd(datsize, int64(sect.Align)) 1471 for _, symn := range sym.ReadOnly { 1472 for _, s := range data[symn] { 1473 datsize = aligndatsize(datsize, s) 1474 s.Sect = sect 1475 s.Type = sym.SRODATA 1476 s.Value = int64(uint64(datsize) - sect.Vaddr) 1477 datsize += s.Size 1478 } 1479 checkdatsize(ctxt, datsize, symn) 1480 } 1481 sect.Length = uint64(datsize) - sect.Vaddr 1482 1483 /* read-only ELF, Mach-O sections */ 1484 for _, s := range data[sym.SELFROSECT] { 1485 sect = addsection(ctxt.Arch, segro, s.Name, 04) 1486 sect.Align = symalign(s) 1487 datsize = Rnd(datsize, int64(sect.Align)) 1488 sect.Vaddr = uint64(datsize) 1489 s.Sect = sect 1490 s.Type = sym.SRODATA 1491 s.Value = int64(uint64(datsize) - sect.Vaddr) 1492 datsize += s.Size 1493 sect.Length = uint64(datsize) - sect.Vaddr 1494 } 1495 checkdatsize(ctxt, datsize, sym.SELFROSECT) 1496 1497 for _, s := range data[sym.SMACHOPLT] { 1498 sect = addsection(ctxt.Arch, segro, s.Name, 04) 1499 sect.Align = symalign(s) 1500 datsize = Rnd(datsize, int64(sect.Align)) 1501 sect.Vaddr = uint64(datsize) 1502 s.Sect = sect 1503 s.Type = sym.SRODATA 1504 s.Value = int64(uint64(datsize) - sect.Vaddr) 1505 datsize += s.Size 1506 sect.Length = uint64(datsize) - sect.Vaddr 1507 } 1508 checkdatsize(ctxt, datsize, sym.SMACHOPLT) 1509 1510 // There is some data that are conceptually read-only but are written to by 1511 // relocations. On GNU systems, we can arrange for the dynamic linker to 1512 // mprotect sections after relocations are applied by giving them write 1513 // permissions in the object file and calling them ".data.rel.ro.FOO". We 1514 // divide the .rodata section between actual .rodata and .data.rel.ro.rodata, 1515 // but for the other sections that this applies to, we just write a read-only 1516 // .FOO section or a read-write .data.rel.ro.FOO section depending on the 1517 // situation. 1518 // TODO(mwhudson): It would make sense to do this more widely, but it makes 1519 // the system linker segfault on darwin. 1520 addrelrosection := func(suffix string) *sym.Section { 1521 return addsection(ctxt.Arch, segro, suffix, 04) 1522 } 1523 1524 if ctxt.UseRelro() { 1525 addrelrosection = func(suffix string) *sym.Section { 1526 seg := &Segrelrodata 1527 if ctxt.LinkMode == LinkExternal { 1528 // Using a separate segment with an external 1529 // linker results in some programs moving 1530 // their data sections unexpectedly, which 1531 // corrupts the moduledata. So we use the 1532 // rodata segment and let the external linker 1533 // sort out a rel.ro segment. 1534 seg = &Segrodata 1535 } 1536 return addsection(ctxt.Arch, seg, ".data.rel.ro"+suffix, 06) 1537 } 1538 /* data only written by relocations */ 1539 sect = addrelrosection("") 1540 1541 sect.Vaddr = 0 1542 ctxt.Syms.Lookup("runtime.types", 0).Sect = sect 1543 ctxt.Syms.Lookup("runtime.etypes", 0).Sect = sect 1544 for _, symnro := range sym.ReadOnly { 1545 symn := sym.RelROMap[symnro] 1546 align := dataMaxAlign[symn] 1547 if sect.Align < align { 1548 sect.Align = align 1549 } 1550 } 1551 datsize = Rnd(datsize, int64(sect.Align)) 1552 for _, symnro := range sym.ReadOnly { 1553 symn := sym.RelROMap[symnro] 1554 for _, s := range data[symn] { 1555 datsize = aligndatsize(datsize, s) 1556 if s.Outer != nil && s.Outer.Sect != nil && s.Outer.Sect != sect { 1557 Errorf(s, "s.Outer (%s) in different section from s, %s != %s", s.Outer.Name, s.Outer.Sect.Name, sect.Name) 1558 } 1559 s.Sect = sect 1560 s.Type = sym.SRODATA 1561 s.Value = int64(uint64(datsize) - sect.Vaddr) 1562 datsize += s.Size 1563 } 1564 checkdatsize(ctxt, datsize, symn) 1565 } 1566 1567 sect.Length = uint64(datsize) - sect.Vaddr 1568 } 1569 1570 /* typelink */ 1571 sect = addrelrosection(".typelink") 1572 sect.Align = dataMaxAlign[sym.STYPELINK] 1573 datsize = Rnd(datsize, int64(sect.Align)) 1574 sect.Vaddr = uint64(datsize) 1575 typelink := ctxt.Syms.Lookup("runtime.typelink", 0) 1576 typelink.Sect = sect 1577 typelink.Type = sym.SRODATA 1578 datsize += typelink.Size 1579 checkdatsize(ctxt, datsize, sym.STYPELINK) 1580 sect.Length = uint64(datsize) - sect.Vaddr 1581 1582 /* itablink */ 1583 sect = addrelrosection(".itablink") 1584 sect.Align = dataMaxAlign[sym.SITABLINK] 1585 datsize = Rnd(datsize, int64(sect.Align)) 1586 sect.Vaddr = uint64(datsize) 1587 ctxt.Syms.Lookup("runtime.itablink", 0).Sect = sect 1588 ctxt.Syms.Lookup("runtime.eitablink", 0).Sect = sect 1589 for _, s := range data[sym.SITABLINK] { 1590 datsize = aligndatsize(datsize, s) 1591 s.Sect = sect 1592 s.Type = sym.SRODATA 1593 s.Value = int64(uint64(datsize) - sect.Vaddr) 1594 datsize += s.Size 1595 } 1596 checkdatsize(ctxt, datsize, sym.SITABLINK) 1597 sect.Length = uint64(datsize) - sect.Vaddr 1598 1599 /* gosymtab */ 1600 sect = addrelrosection(".gosymtab") 1601 sect.Align = dataMaxAlign[sym.SSYMTAB] 1602 datsize = Rnd(datsize, int64(sect.Align)) 1603 sect.Vaddr = uint64(datsize) 1604 ctxt.Syms.Lookup("runtime.symtab", 0).Sect = sect 1605 ctxt.Syms.Lookup("runtime.esymtab", 0).Sect = sect 1606 for _, s := range data[sym.SSYMTAB] { 1607 datsize = aligndatsize(datsize, s) 1608 s.Sect = sect 1609 s.Type = sym.SRODATA 1610 s.Value = int64(uint64(datsize) - sect.Vaddr) 1611 datsize += s.Size 1612 } 1613 checkdatsize(ctxt, datsize, sym.SSYMTAB) 1614 sect.Length = uint64(datsize) - sect.Vaddr 1615 1616 /* gopclntab */ 1617 sect = addrelrosection(".gopclntab") 1618 sect.Align = dataMaxAlign[sym.SPCLNTAB] 1619 datsize = Rnd(datsize, int64(sect.Align)) 1620 sect.Vaddr = uint64(datsize) 1621 ctxt.Syms.Lookup("runtime.pclntab", 0).Sect = sect 1622 ctxt.Syms.Lookup("runtime.epclntab", 0).Sect = sect 1623 for _, s := range data[sym.SPCLNTAB] { 1624 datsize = aligndatsize(datsize, s) 1625 s.Sect = sect 1626 s.Type = sym.SRODATA 1627 s.Value = int64(uint64(datsize) - sect.Vaddr) 1628 datsize += s.Size 1629 } 1630 checkdatsize(ctxt, datsize, sym.SRODATA) 1631 sect.Length = uint64(datsize) - sect.Vaddr 1632 1633 // 6g uses 4-byte relocation offsets, so the entire segment must fit in 32 bits. 1634 if datsize != int64(uint32(datsize)) { 1635 Errorf(nil, "read-only data segment too large: %d", datsize) 1636 } 1637 1638 for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ { 1639 datap = append(datap, data[symn]...) 1640 } 1641 1642 dwarfGenerateDebugSyms(ctxt) 1643 1644 var i int 1645 for ; i < len(dwarfp); i++ { 1646 s := dwarfp[i] 1647 if s.Type != sym.SDWARFSECT { 1648 break 1649 } 1650 1651 sect = addsection(ctxt.Arch, &Segdwarf, s.Name, 04) 1652 sect.Align = 1 1653 datsize = Rnd(datsize, int64(sect.Align)) 1654 sect.Vaddr = uint64(datsize) 1655 s.Sect = sect 1656 s.Type = sym.SRODATA 1657 s.Value = int64(uint64(datsize) - sect.Vaddr) 1658 datsize += s.Size 1659 sect.Length = uint64(datsize) - sect.Vaddr 1660 } 1661 checkdatsize(ctxt, datsize, sym.SDWARFSECT) 1662 1663 for i < len(dwarfp) { 1664 curType := dwarfp[i].Type 1665 var sect *sym.Section 1666 switch curType { 1667 case sym.SDWARFINFO: 1668 sect = addsection(ctxt.Arch, &Segdwarf, ".debug_info", 04) 1669 case sym.SDWARFRANGE: 1670 sect = addsection(ctxt.Arch, &Segdwarf, ".debug_ranges", 04) 1671 case sym.SDWARFLOC: 1672 sect = addsection(ctxt.Arch, &Segdwarf, ".debug_loc", 04) 1673 default: 1674 Errorf(dwarfp[i], "unknown DWARF section %v", curType) 1675 } 1676 1677 sect.Align = 1 1678 datsize = Rnd(datsize, int64(sect.Align)) 1679 sect.Vaddr = uint64(datsize) 1680 for ; i < len(dwarfp); i++ { 1681 s := dwarfp[i] 1682 if s.Type != curType { 1683 break 1684 } 1685 s.Sect = sect 1686 s.Type = sym.SRODATA 1687 s.Value = int64(uint64(datsize) - sect.Vaddr) 1688 s.Attr |= sym.AttrLocal 1689 datsize += s.Size 1690 } 1691 sect.Length = uint64(datsize) - sect.Vaddr 1692 checkdatsize(ctxt, datsize, curType) 1693 } 1694 1695 /* number the sections */ 1696 n := int32(1) 1697 1698 for _, sect := range Segtext.Sections { 1699 sect.Extnum = int16(n) 1700 n++ 1701 } 1702 for _, sect := range Segrodata.Sections { 1703 sect.Extnum = int16(n) 1704 n++ 1705 } 1706 for _, sect := range Segrelrodata.Sections { 1707 sect.Extnum = int16(n) 1708 n++ 1709 } 1710 for _, sect := range Segdata.Sections { 1711 sect.Extnum = int16(n) 1712 if ctxt.HeadType == objabi.Haix && (sect.Name == ".noptrdata" || sect.Name == ".bss") { 1713 // On AIX, "noptr" sections are merged with their "ptr" section 1714 continue 1715 } 1716 n++ 1717 } 1718 for _, sect := range Segdwarf.Sections { 1719 sect.Extnum = int16(n) 1720 n++ 1721 } 1722 } 1723 1724 func dodataSect(ctxt *Link, symn sym.SymKind, syms []*sym.Symbol) (result []*sym.Symbol, maxAlign int32) { 1725 if ctxt.HeadType == objabi.Hdarwin { 1726 // Some symbols may no longer belong in syms 1727 // due to movement in machosymorder. 1728 newSyms := make([]*sym.Symbol, 0, len(syms)) 1729 for _, s := range syms { 1730 if s.Type == symn { 1731 newSyms = append(newSyms, s) 1732 } 1733 } 1734 syms = newSyms 1735 } 1736 1737 var head, tail *sym.Symbol 1738 symsSort := make([]dataSortKey, 0, len(syms)) 1739 for _, s := range syms { 1740 if s.Attr.OnList() { 1741 log.Fatalf("symbol %s listed multiple times", s.Name) 1742 } 1743 s.Attr |= sym.AttrOnList 1744 switch { 1745 case s.Size < int64(len(s.P)): 1746 Errorf(s, "initialize bounds (%d < %d)", s.Size, len(s.P)) 1747 case s.Size < 0: 1748 Errorf(s, "negative size (%d bytes)", s.Size) 1749 case s.Size > cutoff: 1750 Errorf(s, "symbol too large (%d bytes)", s.Size) 1751 } 1752 1753 // If the usually-special section-marker symbols are being laid 1754 // out as regular symbols, put them either at the beginning or 1755 // end of their section. 1756 if ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin { 1757 switch s.Name { 1758 case "runtime.text", "runtime.bss", "runtime.data", "runtime.types": 1759 head = s 1760 continue 1761 case "runtime.etext", "runtime.ebss", "runtime.edata", "runtime.etypes": 1762 tail = s 1763 continue 1764 } 1765 } 1766 1767 key := dataSortKey{ 1768 size: s.Size, 1769 name: s.Name, 1770 sym: s, 1771 } 1772 1773 switch s.Type { 1774 case sym.SELFGOT: 1775 // For ppc64, we want to interleave the .got and .toc sections 1776 // from input files. Both are type sym.SELFGOT, so in that case 1777 // we skip size comparison and fall through to the name 1778 // comparison (conveniently, .got sorts before .toc). 1779 key.size = 0 1780 } 1781 1782 symsSort = append(symsSort, key) 1783 } 1784 1785 sort.Sort(bySizeAndName(symsSort)) 1786 1787 off := 0 1788 if head != nil { 1789 syms[0] = head 1790 off++ 1791 } 1792 for i, symSort := range symsSort { 1793 syms[i+off] = symSort.sym 1794 align := symalign(symSort.sym) 1795 if maxAlign < align { 1796 maxAlign = align 1797 } 1798 } 1799 if tail != nil { 1800 syms[len(syms)-1] = tail 1801 } 1802 1803 if ctxt.IsELF && symn == sym.SELFROSECT { 1804 // Make .rela and .rela.plt contiguous, the ELF ABI requires this 1805 // and Solaris actually cares. 1806 reli, plti := -1, -1 1807 for i, s := range syms { 1808 switch s.Name { 1809 case ".rel.plt", ".rela.plt": 1810 plti = i 1811 case ".rel", ".rela": 1812 reli = i 1813 } 1814 } 1815 if reli >= 0 && plti >= 0 && plti != reli+1 { 1816 var first, second int 1817 if plti > reli { 1818 first, second = reli, plti 1819 } else { 1820 first, second = plti, reli 1821 } 1822 rel, plt := syms[reli], syms[plti] 1823 copy(syms[first+2:], syms[first+1:second]) 1824 syms[first+0] = rel 1825 syms[first+1] = plt 1826 1827 // Make sure alignment doesn't introduce a gap. 1828 // Setting the alignment explicitly prevents 1829 // symalign from basing it on the size and 1830 // getting it wrong. 1831 rel.Align = int32(ctxt.Arch.RegSize) 1832 plt.Align = int32(ctxt.Arch.RegSize) 1833 } 1834 } 1835 1836 return syms, maxAlign 1837 } 1838 1839 // Add buildid to beginning of text segment, on non-ELF systems. 1840 // Non-ELF binary formats are not always flexible enough to 1841 // give us a place to put the Go build ID. On those systems, we put it 1842 // at the very beginning of the text segment. 1843 // This ``header'' is read by cmd/go. 1844 func (ctxt *Link) textbuildid() { 1845 if ctxt.IsELF || ctxt.BuildMode == BuildModePlugin || *flagBuildid == "" { 1846 return 1847 } 1848 1849 s := ctxt.Syms.Lookup("go.buildid", 0) 1850 s.Attr |= sym.AttrReachable 1851 // The \xff is invalid UTF-8, meant to make it less likely 1852 // to find one of these accidentally. 1853 data := "\xff Go build ID: " + strconv.Quote(*flagBuildid) + "\n \xff" 1854 s.Type = sym.STEXT 1855 s.P = []byte(data) 1856 s.Size = int64(len(s.P)) 1857 1858 ctxt.Textp = append(ctxt.Textp, nil) 1859 copy(ctxt.Textp[1:], ctxt.Textp) 1860 ctxt.Textp[0] = s 1861 } 1862 1863 // assign addresses to text 1864 func (ctxt *Link) textaddress() { 1865 addsection(ctxt.Arch, &Segtext, ".text", 05) 1866 1867 // Assign PCs in text segment. 1868 // Could parallelize, by assigning to text 1869 // and then letting threads copy down, but probably not worth it. 1870 sect := Segtext.Sections[0] 1871 1872 sect.Align = int32(Funcalign) 1873 1874 text := ctxt.Syms.Lookup("runtime.text", 0) 1875 text.Sect = sect 1876 1877 if ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin { 1878 etext := ctxt.Syms.Lookup("runtime.etext", 0) 1879 etext.Sect = sect 1880 1881 ctxt.Textp = append(ctxt.Textp, etext, nil) 1882 copy(ctxt.Textp[1:], ctxt.Textp) 1883 ctxt.Textp[0] = text 1884 } 1885 1886 va := uint64(*FlagTextAddr) 1887 n := 1 1888 sect.Vaddr = va 1889 ntramps := 0 1890 for _, s := range ctxt.Textp { 1891 sect, n, va = assignAddress(ctxt, sect, n, s, va, false) 1892 1893 trampoline(ctxt, s) // resolve jumps, may add trampolines if jump too far 1894 1895 // lay down trampolines after each function 1896 for ; ntramps < len(ctxt.tramps); ntramps++ { 1897 tramp := ctxt.tramps[ntramps] 1898 sect, n, va = assignAddress(ctxt, sect, n, tramp, va, true) 1899 } 1900 } 1901 1902 sect.Length = va - sect.Vaddr 1903 ctxt.Syms.Lookup("runtime.etext", 0).Sect = sect 1904 1905 // merge tramps into Textp, keeping Textp in address order 1906 if ntramps != 0 { 1907 newtextp := make([]*sym.Symbol, 0, len(ctxt.Textp)+ntramps) 1908 i := 0 1909 for _, s := range ctxt.Textp { 1910 for ; i < ntramps && ctxt.tramps[i].Value < s.Value; i++ { 1911 newtextp = append(newtextp, ctxt.tramps[i]) 1912 } 1913 newtextp = append(newtextp, s) 1914 } 1915 newtextp = append(newtextp, ctxt.tramps[i:ntramps]...) 1916 1917 ctxt.Textp = newtextp 1918 } 1919 } 1920 1921 // assigns address for a text symbol, returns (possibly new) section, its number, and the address 1922 // Note: once we have trampoline insertion support for external linking, this function 1923 // will not need to create new text sections, and so no need to return sect and n. 1924 func assignAddress(ctxt *Link, sect *sym.Section, n int, s *sym.Symbol, va uint64, isTramp bool) (*sym.Section, int, uint64) { 1925 if thearch.AssignAddress != nil { 1926 return thearch.AssignAddress(ctxt, sect, n, s, va, isTramp) 1927 } 1928 1929 s.Sect = sect 1930 if s.Attr.SubSymbol() { 1931 return sect, n, va 1932 } 1933 if s.Align != 0 { 1934 va = uint64(Rnd(int64(va), int64(s.Align))) 1935 } else { 1936 va = uint64(Rnd(int64(va), int64(Funcalign))) 1937 } 1938 s.Value = 0 1939 for sub := s; sub != nil; sub = sub.Sub { 1940 sub.Value += int64(va) 1941 } 1942 1943 funcsize := uint64(MINFUNC) // spacing required for findfunctab 1944 if s.Size > MINFUNC { 1945 funcsize = uint64(s.Size) 1946 } 1947 1948 // On ppc64x a text section should not be larger than 2^26 bytes due to the size of 1949 // call target offset field in the bl instruction. Splitting into smaller text 1950 // sections smaller than this limit allows the GNU linker to modify the long calls 1951 // appropriately. The limit allows for the space needed for tables inserted by the linker. 1952 1953 // If this function doesn't fit in the current text section, then create a new one. 1954 1955 // Only break at outermost syms. 1956 1957 if ctxt.Arch.InFamily(sys.PPC64) && s.Outer == nil && ctxt.IsELF && ctxt.LinkMode == LinkExternal && va-sect.Vaddr+funcsize+maxSizeTrampolinesPPC64(s, isTramp) > 0x1c00000 { 1958 // Set the length for the previous text section 1959 sect.Length = va - sect.Vaddr 1960 1961 // Create new section, set the starting Vaddr 1962 sect = addsection(ctxt.Arch, &Segtext, ".text", 05) 1963 sect.Vaddr = va 1964 s.Sect = sect 1965 1966 // Create a symbol for the start of the secondary text sections 1967 ctxt.Syms.Lookup(fmt.Sprintf("runtime.text.%d", n), 0).Sect = sect 1968 n++ 1969 } 1970 va += funcsize 1971 1972 return sect, n, va 1973 } 1974 1975 // address assigns virtual addresses to all segments and sections and 1976 // returns all segments in file order. 1977 func (ctxt *Link) address() []*sym.Segment { 1978 var order []*sym.Segment // Layout order 1979 1980 va := uint64(*FlagTextAddr) 1981 order = append(order, &Segtext) 1982 Segtext.Rwx = 05 1983 Segtext.Vaddr = va 1984 for _, s := range Segtext.Sections { 1985 va = uint64(Rnd(int64(va), int64(s.Align))) 1986 s.Vaddr = va 1987 va += s.Length 1988 } 1989 1990 Segtext.Length = va - uint64(*FlagTextAddr) 1991 if ctxt.HeadType == objabi.Hnacl { 1992 va += 32 // room for the "halt sled" 1993 } 1994 1995 if len(Segrodata.Sections) > 0 { 1996 // align to page boundary so as not to mix 1997 // rodata and executable text. 1998 // 1999 // Note: gold or GNU ld will reduce the size of the executable 2000 // file by arranging for the relro segment to end at a page 2001 // boundary, and overlap the end of the text segment with the 2002 // start of the relro segment in the file. The PT_LOAD segments 2003 // will be such that the last page of the text segment will be 2004 // mapped twice, once r-x and once starting out rw- and, after 2005 // relocation processing, changed to r--. 2006 // 2007 // Ideally the last page of the text segment would not be 2008 // writable even for this short period. 2009 va = uint64(Rnd(int64(va), int64(*FlagRound))) 2010 2011 order = append(order, &Segrodata) 2012 Segrodata.Rwx = 04 2013 Segrodata.Vaddr = va 2014 for _, s := range Segrodata.Sections { 2015 va = uint64(Rnd(int64(va), int64(s.Align))) 2016 s.Vaddr = va 2017 va += s.Length 2018 } 2019 2020 Segrodata.Length = va - Segrodata.Vaddr 2021 } 2022 if len(Segrelrodata.Sections) > 0 { 2023 // align to page boundary so as not to mix 2024 // rodata, rel-ro data, and executable text. 2025 va = uint64(Rnd(int64(va), int64(*FlagRound))) 2026 2027 order = append(order, &Segrelrodata) 2028 Segrelrodata.Rwx = 06 2029 Segrelrodata.Vaddr = va 2030 for _, s := range Segrelrodata.Sections { 2031 va = uint64(Rnd(int64(va), int64(s.Align))) 2032 s.Vaddr = va 2033 va += s.Length 2034 } 2035 2036 Segrelrodata.Length = va - Segrelrodata.Vaddr 2037 } 2038 2039 va = uint64(Rnd(int64(va), int64(*FlagRound))) 2040 order = append(order, &Segdata) 2041 Segdata.Rwx = 06 2042 Segdata.Vaddr = va 2043 var data *sym.Section 2044 var noptr *sym.Section 2045 var bss *sym.Section 2046 var noptrbss *sym.Section 2047 for i, s := range Segdata.Sections { 2048 if ctxt.IsELF && s.Name == ".tbss" { 2049 continue 2050 } 2051 vlen := int64(s.Length) 2052 if i+1 < len(Segdata.Sections) && !(ctxt.IsELF && Segdata.Sections[i+1].Name == ".tbss") { 2053 vlen = int64(Segdata.Sections[i+1].Vaddr - s.Vaddr) 2054 } 2055 s.Vaddr = va 2056 va += uint64(vlen) 2057 Segdata.Length = va - Segdata.Vaddr 2058 if s.Name == ".data" { 2059 data = s 2060 } 2061 if s.Name == ".noptrdata" { 2062 noptr = s 2063 } 2064 if s.Name == ".bss" { 2065 bss = s 2066 } 2067 if s.Name == ".noptrbss" { 2068 noptrbss = s 2069 } 2070 } 2071 2072 // Assign Segdata's Filelen omitting the BSS. We do this here 2073 // simply because right now we know where the BSS starts. 2074 Segdata.Filelen = bss.Vaddr - Segdata.Vaddr 2075 2076 va = uint64(Rnd(int64(va), int64(*FlagRound))) 2077 order = append(order, &Segdwarf) 2078 Segdwarf.Rwx = 06 2079 Segdwarf.Vaddr = va 2080 for i, s := range Segdwarf.Sections { 2081 vlen := int64(s.Length) 2082 if i+1 < len(Segdwarf.Sections) { 2083 vlen = int64(Segdwarf.Sections[i+1].Vaddr - s.Vaddr) 2084 } 2085 s.Vaddr = va 2086 va += uint64(vlen) 2087 if ctxt.HeadType == objabi.Hwindows { 2088 va = uint64(Rnd(int64(va), PEFILEALIGN)) 2089 } 2090 Segdwarf.Length = va - Segdwarf.Vaddr 2091 } 2092 2093 var ( 2094 text = Segtext.Sections[0] 2095 rodata = ctxt.Syms.Lookup("runtime.rodata", 0).Sect 2096 itablink = ctxt.Syms.Lookup("runtime.itablink", 0).Sect 2097 symtab = ctxt.Syms.Lookup("runtime.symtab", 0).Sect 2098 pclntab = ctxt.Syms.Lookup("runtime.pclntab", 0).Sect 2099 types = ctxt.Syms.Lookup("runtime.types", 0).Sect 2100 ) 2101 lasttext := text 2102 // Could be multiple .text sections 2103 for _, sect := range Segtext.Sections { 2104 if sect.Name == ".text" { 2105 lasttext = sect 2106 } 2107 } 2108 2109 for _, s := range datap { 2110 if s.Sect != nil { 2111 s.Value += int64(s.Sect.Vaddr) 2112 } 2113 for sub := s.Sub; sub != nil; sub = sub.Sub { 2114 sub.Value += s.Value 2115 } 2116 } 2117 2118 for _, s := range dwarfp { 2119 if s.Sect != nil { 2120 s.Value += int64(s.Sect.Vaddr) 2121 } 2122 for sub := s.Sub; sub != nil; sub = sub.Sub { 2123 sub.Value += s.Value 2124 } 2125 } 2126 2127 if ctxt.BuildMode == BuildModeShared { 2128 s := ctxt.Syms.Lookup("go.link.abihashbytes", 0) 2129 sectSym := ctxt.Syms.Lookup(".note.go.abihash", 0) 2130 s.Sect = sectSym.Sect 2131 s.Value = int64(sectSym.Sect.Vaddr + 16) 2132 } 2133 2134 ctxt.xdefine("runtime.text", sym.STEXT, int64(text.Vaddr)) 2135 ctxt.xdefine("runtime.etext", sym.STEXT, int64(lasttext.Vaddr+lasttext.Length)) 2136 2137 // If there are multiple text sections, create runtime.text.n for 2138 // their section Vaddr, using n for index 2139 n := 1 2140 for _, sect := range Segtext.Sections[1:] { 2141 if sect.Name != ".text" { 2142 break 2143 } 2144 symname := fmt.Sprintf("runtime.text.%d", n) 2145 ctxt.xdefine(symname, sym.STEXT, int64(sect.Vaddr)) 2146 n++ 2147 } 2148 2149 ctxt.xdefine("runtime.rodata", sym.SRODATA, int64(rodata.Vaddr)) 2150 ctxt.xdefine("runtime.erodata", sym.SRODATA, int64(rodata.Vaddr+rodata.Length)) 2151 ctxt.xdefine("runtime.types", sym.SRODATA, int64(types.Vaddr)) 2152 ctxt.xdefine("runtime.etypes", sym.SRODATA, int64(types.Vaddr+types.Length)) 2153 ctxt.xdefine("runtime.itablink", sym.SRODATA, int64(itablink.Vaddr)) 2154 ctxt.xdefine("runtime.eitablink", sym.SRODATA, int64(itablink.Vaddr+itablink.Length)) 2155 2156 s := ctxt.Syms.Lookup("runtime.gcdata", 0) 2157 s.Attr |= sym.AttrLocal 2158 ctxt.xdefine("runtime.egcdata", sym.SRODATA, Symaddr(s)+s.Size) 2159 ctxt.Syms.Lookup("runtime.egcdata", 0).Sect = s.Sect 2160 2161 s = ctxt.Syms.Lookup("runtime.gcbss", 0) 2162 s.Attr |= sym.AttrLocal 2163 ctxt.xdefine("runtime.egcbss", sym.SRODATA, Symaddr(s)+s.Size) 2164 ctxt.Syms.Lookup("runtime.egcbss", 0).Sect = s.Sect 2165 2166 ctxt.xdefine("runtime.symtab", sym.SRODATA, int64(symtab.Vaddr)) 2167 ctxt.xdefine("runtime.esymtab", sym.SRODATA, int64(symtab.Vaddr+symtab.Length)) 2168 ctxt.xdefine("runtime.pclntab", sym.SRODATA, int64(pclntab.Vaddr)) 2169 ctxt.xdefine("runtime.epclntab", sym.SRODATA, int64(pclntab.Vaddr+pclntab.Length)) 2170 ctxt.xdefine("runtime.noptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr)) 2171 ctxt.xdefine("runtime.enoptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr+noptr.Length)) 2172 ctxt.xdefine("runtime.bss", sym.SBSS, int64(bss.Vaddr)) 2173 ctxt.xdefine("runtime.ebss", sym.SBSS, int64(bss.Vaddr+bss.Length)) 2174 ctxt.xdefine("runtime.data", sym.SDATA, int64(data.Vaddr)) 2175 ctxt.xdefine("runtime.edata", sym.SDATA, int64(data.Vaddr+data.Length)) 2176 ctxt.xdefine("runtime.noptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr)) 2177 ctxt.xdefine("runtime.enoptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr+noptrbss.Length)) 2178 ctxt.xdefine("runtime.end", sym.SBSS, int64(Segdata.Vaddr+Segdata.Length)) 2179 2180 return order 2181 } 2182 2183 // layout assigns file offsets and lengths to the segments in order. 2184 func (ctxt *Link) layout(order []*sym.Segment) { 2185 var prev *sym.Segment 2186 for _, seg := range order { 2187 if prev == nil { 2188 seg.Fileoff = uint64(HEADR) 2189 } else { 2190 switch ctxt.HeadType { 2191 default: 2192 // Assuming the previous segment was 2193 // aligned, the following rounding 2194 // should ensure that this segment's 2195 // VA ≡ Fileoff mod FlagRound. 2196 seg.Fileoff = uint64(Rnd(int64(prev.Fileoff+prev.Filelen), int64(*FlagRound))) 2197 if seg.Vaddr%uint64(*FlagRound) != seg.Fileoff%uint64(*FlagRound) { 2198 Exitf("bad segment rounding (Vaddr=%#x Fileoff=%#x FlagRound=%#x)", seg.Vaddr, seg.Fileoff, *FlagRound) 2199 } 2200 case objabi.Hwindows: 2201 seg.Fileoff = prev.Fileoff + uint64(Rnd(int64(prev.Filelen), PEFILEALIGN)) 2202 case objabi.Hplan9: 2203 seg.Fileoff = prev.Fileoff + prev.Filelen 2204 } 2205 } 2206 if seg != &Segdata { 2207 // Link.address already set Segdata.Filelen to 2208 // account for BSS. 2209 seg.Filelen = seg.Length 2210 } 2211 prev = seg 2212 } 2213 2214 } 2215 2216 // add a trampoline with symbol s (to be laid down after the current function) 2217 func (ctxt *Link) AddTramp(s *sym.Symbol) { 2218 s.Type = sym.STEXT 2219 s.Attr |= sym.AttrReachable 2220 s.Attr |= sym.AttrOnList 2221 ctxt.tramps = append(ctxt.tramps, s) 2222 if *FlagDebugTramp > 0 && ctxt.Debugvlog > 0 { 2223 ctxt.Logf("trampoline %s inserted\n", s) 2224 } 2225 } 2226 2227 // compressSyms compresses syms and returns the contents of the 2228 // compressed section. If the section would get larger, it returns nil. 2229 func compressSyms(ctxt *Link, syms []*sym.Symbol) []byte { 2230 var total int64 2231 for _, sym := range syms { 2232 total += sym.Size 2233 } 2234 2235 var buf bytes.Buffer 2236 buf.Write([]byte("ZLIB")) 2237 var sizeBytes [8]byte 2238 binary.BigEndian.PutUint64(sizeBytes[:], uint64(total)) 2239 buf.Write(sizeBytes[:]) 2240 2241 // Using zlib.BestSpeed achieves very nearly the same 2242 // compression levels of zlib.DefaultCompression, but takes 2243 // substantially less time. This is important because DWARF 2244 // compression can be a significant fraction of link time. 2245 z, err := zlib.NewWriterLevel(&buf, zlib.BestSpeed) 2246 if err != nil { 2247 log.Fatalf("NewWriterLevel failed: %s", err) 2248 } 2249 for _, sym := range syms { 2250 if _, err := z.Write(sym.P); err != nil { 2251 log.Fatalf("compression failed: %s", err) 2252 } 2253 for i := sym.Size - int64(len(sym.P)); i > 0; { 2254 b := zeros[:] 2255 if i < int64(len(b)) { 2256 b = b[:i] 2257 } 2258 n, err := z.Write(b) 2259 if err != nil { 2260 log.Fatalf("compression failed: %s", err) 2261 } 2262 i -= int64(n) 2263 } 2264 } 2265 if err := z.Close(); err != nil { 2266 log.Fatalf("compression failed: %s", err) 2267 } 2268 if int64(buf.Len()) >= total { 2269 // Compression didn't save any space. 2270 return nil 2271 } 2272 return buf.Bytes() 2273 }