1 //===- Writer.cpp ---------------------------------------------------------===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "Writer.h" 11 #include "Config.h" 12 #include "OutputSections.h" 13 #include "SymbolTable.h" 14 #include "Target.h" 15 16 #include "llvm/ADT/StringMap.h" 17 #include "llvm/ADT/StringSwitch.h" 18 #include "llvm/Support/FileOutputBuffer.h" 19 #include "llvm/Support/StringSaver.h" 20 21 using namespace llvm; 22 using namespace llvm::ELF; 23 using namespace llvm::object; 24 25 using namespace lld; 26 using namespace lld::elf2; 27 28 namespace { 29 // The writer writes a SymbolTable result to a file. 30 template <class ELFT> class Writer { 31 public: 32 typedef typename ELFFile<ELFT>::uintX_t uintX_t; 33 typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr; 34 typedef typename ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr; 35 typedef typename ELFFile<ELFT>::Elf_Phdr Elf_Phdr; 36 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym; 37 typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range; 38 typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela; 39 Writer(SymbolTable<ELFT> &S) : Symtab(S) {} 40 void run(); 41 42 private: 43 void copyLocalSymbols(); 44 void createSections(); 45 template <bool isRela> 46 void scanRelocs(InputSectionBase<ELFT> &C, 47 iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels); 48 void scanRelocs(InputSection<ELFT> &C); 49 void scanRelocs(InputSectionBase<ELFT> &S, const Elf_Shdr &RelSec); 50 void assignAddresses(); 51 void buildSectionMap(); 52 void openFile(StringRef OutputPath); 53 void writeHeader(); 54 void writeSections(); 55 bool isDiscarded(InputSectionBase<ELFT> *IS) const; 56 StringRef getOutputSectionName(StringRef S) const; 57 bool needsInterpSection() const { 58 return !Symtab.getSharedFiles().empty() && !Config->DynamicLinker.empty(); 59 } 60 bool isOutputDynamic() const { 61 return !Symtab.getSharedFiles().empty() || Config->Shared; 62 } 63 uintX_t getEntryAddr() const; 64 int getPhdrsNum() const; 65 66 OutputSection<ELFT> *getBSS(); 67 void addCommonSymbols(std::vector<DefinedCommon<ELFT> *> &Syms); 68 void addSharedCopySymbols(std::vector<SharedSymbol<ELFT> *> &Syms); 69 70 std::unique_ptr<llvm::FileOutputBuffer> Buffer; 71 72 SpecificBumpPtrAllocator<OutputSection<ELFT>> SecAlloc; 73 SpecificBumpPtrAllocator<MergeOutputSection<ELFT>> MSecAlloc; 74 SpecificBumpPtrAllocator<EHOutputSection<ELFT>> EHSecAlloc; 75 BumpPtrAllocator Alloc; 76 std::vector<OutputSectionBase<ELFT> *> OutputSections; 77 unsigned getNumSections() const { return OutputSections.size() + 1; } 78 79 void addStartStopSymbols(OutputSectionBase<ELFT> *Sec); 80 void setPhdr(Elf_Phdr *PH, uint32_t Type, uint32_t Flags, uintX_t FileOff, 81 uintX_t VA, uintX_t Size, uintX_t Align); 82 void copyPhdr(Elf_Phdr *PH, OutputSectionBase<ELFT> *From); 83 84 SymbolTable<ELFT> &Symtab; 85 std::vector<Elf_Phdr> Phdrs; 86 87 uintX_t FileSize; 88 uintX_t SectionHeaderOff; 89 90 llvm::StringMap<llvm::StringRef> InputToOutputSection; 91 }; 92 } // anonymous namespace 93 94 template <class ELFT> void lld::elf2::writeResult(SymbolTable<ELFT> *Symtab) { 95 // Initialize output sections that are handled by Writer specially. 96 // Don't reorder because the order of initialization matters. 97 InterpSection<ELFT> Interp; 98 Out<ELFT>::Interp = &Interp; 99 StringTableSection<ELFT> ShStrTab(".shstrtab", false); 100 Out<ELFT>::ShStrTab = &ShStrTab; 101 StringTableSection<ELFT> StrTab(".strtab", false); 102 if (!Config->StripAll) 103 Out<ELFT>::StrTab = &StrTab; 104 StringTableSection<ELFT> DynStrTab(".dynstr", true); 105 Out<ELFT>::DynStrTab = &DynStrTab; 106 GotSection<ELFT> Got; 107 Out<ELFT>::Got = &Got; 108 GotPltSection<ELFT> GotPlt; 109 if (Target->supportsLazyRelocations()) 110 Out<ELFT>::GotPlt = &GotPlt; 111 PltSection<ELFT> Plt; 112 Out<ELFT>::Plt = &Plt; 113 std::unique_ptr<SymbolTableSection<ELFT>> SymTab; 114 if (!Config->StripAll) { 115 SymTab.reset(new SymbolTableSection<ELFT>(*Symtab, *Out<ELFT>::StrTab)); 116 Out<ELFT>::SymTab = SymTab.get(); 117 } 118 SymbolTableSection<ELFT> DynSymTab(*Symtab, *Out<ELFT>::DynStrTab); 119 Out<ELFT>::DynSymTab = &DynSymTab; 120 HashTableSection<ELFT> HashTab; 121 if (Config->SysvHash) 122 Out<ELFT>::HashTab = &HashTab; 123 GnuHashTableSection<ELFT> GnuHashTab; 124 if (Config->GnuHash) 125 Out<ELFT>::GnuHashTab = &GnuHashTab; 126 bool IsRela = Symtab->shouldUseRela(); 127 RelocationSection<ELFT> RelaDyn(IsRela ? ".rela.dyn" : ".rel.dyn", IsRela); 128 Out<ELFT>::RelaDyn = &RelaDyn; 129 RelocationSection<ELFT> RelaPlt(IsRela ? ".rela.plt" : ".rel.plt", IsRela); 130 if (Target->supportsLazyRelocations()) 131 Out<ELFT>::RelaPlt = &RelaPlt; 132 DynamicSection<ELFT> Dynamic(*Symtab); 133 Out<ELFT>::Dynamic = &Dynamic; 134 135 Writer<ELFT>(*Symtab).run(); 136 } 137 138 // The main function of the writer. 139 template <class ELFT> void Writer<ELFT>::run() { 140 buildSectionMap(); 141 if (!Config->DiscardAll) 142 copyLocalSymbols(); 143 createSections(); 144 assignAddresses(); 145 openFile(Config->OutputFile); 146 writeHeader(); 147 writeSections(); 148 error(Buffer->commit()); 149 } 150 151 namespace { 152 template <bool Is64Bits> struct SectionKey { 153 typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t; 154 StringRef Name; 155 uint32_t Type; 156 uintX_t Flags; 157 uintX_t EntSize; 158 }; 159 } 160 namespace llvm { 161 template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> { 162 static SectionKey<Is64Bits> getEmptyKey() { 163 return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0, 164 0}; 165 } 166 static SectionKey<Is64Bits> getTombstoneKey() { 167 return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 168 0, 0}; 169 } 170 static unsigned getHashValue(const SectionKey<Is64Bits> &Val) { 171 return hash_combine(Val.Name, Val.Type, Val.Flags, Val.EntSize); 172 } 173 static bool isEqual(const SectionKey<Is64Bits> &LHS, 174 const SectionKey<Is64Bits> &RHS) { 175 return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) && 176 LHS.Type == RHS.Type && LHS.Flags == RHS.Flags && 177 LHS.EntSize == RHS.EntSize; 178 } 179 }; 180 } 181 182 // The reason we have to do this early scan is as follows 183 // * To mmap the output file, we need to know the size 184 // * For that, we need to know how many dynamic relocs we will have. 185 // It might be possible to avoid this by outputting the file with write: 186 // * Write the allocated output sections, computing addresses. 187 // * Apply relocations, recording which ones require a dynamic reloc. 188 // * Write the dynamic relocations. 189 // * Write the rest of the file. 190 template <class ELFT> 191 template <bool isRela> 192 void Writer<ELFT>::scanRelocs( 193 InputSectionBase<ELFT> &C, 194 iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels) { 195 typedef Elf_Rel_Impl<ELFT, isRela> RelType; 196 const ObjectFile<ELFT> &File = *C.getFile(); 197 for (const RelType &RI : Rels) { 198 uint32_t SymIndex = RI.getSymbol(Config->Mips64EL); 199 SymbolBody *Body = File.getSymbolBody(SymIndex); 200 uint32_t Type = RI.getType(Config->Mips64EL); 201 202 if (Target->isTlsLocalDynamicReloc(Type)) { 203 if (Out<ELFT>::LocalModuleTlsIndexOffset == uint32_t(-1)) { 204 Out<ELFT>::LocalModuleTlsIndexOffset = 205 Out<ELFT>::Got->addLocalModuleTlsIndex(); 206 Out<ELFT>::RelaDyn->addReloc({&C, &RI}); 207 } 208 continue; 209 } 210 211 // Set "used" bit for --as-needed. 212 if (Body && Body->isUndefined() && !Body->isWeak()) 213 if (auto *S = dyn_cast<SharedSymbol<ELFT>>(Body->repl())) 214 S->File->IsUsed = true; 215 216 if (Body) 217 Body = Body->repl(); 218 219 if (Body && Body->isTLS() && Target->isTlsGlobalDynamicReloc(Type)) { 220 if (Body->isInGot()) 221 continue; 222 Out<ELFT>::Got->addDynTlsEntry(Body); 223 Out<ELFT>::RelaDyn->addReloc({&C, &RI}); 224 Out<ELFT>::RelaDyn->addReloc({nullptr, nullptr}); 225 Body->setUsedInDynamicReloc(); 226 continue; 227 } 228 229 if ((Body && Body->isTLS()) && Type != Target->getTlsPcRelGotReloc()) 230 continue; 231 232 bool NeedsGot = false; 233 bool NeedsPlt = false; 234 if (Body) { 235 if (auto *E = dyn_cast<SharedSymbol<ELFT>>(Body)) { 236 if (E->needsCopy()) 237 continue; 238 if (Target->relocNeedsCopy(Type, *Body)) 239 E->OffsetInBSS = 0; 240 } 241 NeedsPlt = Target->relocNeedsPlt(Type, *Body); 242 if (NeedsPlt) { 243 if (Body->isInPlt()) 244 continue; 245 Out<ELFT>::Plt->addEntry(Body); 246 } 247 NeedsGot = Target->relocNeedsGot(Type, *Body); 248 if (NeedsGot) { 249 if (NeedsPlt && Target->supportsLazyRelocations()) { 250 Out<ELFT>::GotPlt->addEntry(Body); 251 } else { 252 if (Body->isInGot()) 253 continue; 254 Out<ELFT>::Got->addEntry(Body); 255 } 256 } 257 } 258 259 if (Config->EMachine == EM_MIPS && NeedsGot) { 260 // MIPS ABI has special rules to process GOT entries 261 // and doesn't require relocation entries for them. 262 // See "Global Offset Table" in Chapter 5 in the following document 263 // for detailed description: 264 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 265 Body->setUsedInDynamicReloc(); 266 continue; 267 } 268 bool CBP = canBePreempted(Body, NeedsGot); 269 if (!CBP && (!Config->Shared || Target->isRelRelative(Type))) 270 continue; 271 if (CBP) 272 Body->setUsedInDynamicReloc(); 273 if (NeedsPlt && Target->supportsLazyRelocations()) 274 Out<ELFT>::RelaPlt->addReloc({&C, &RI}); 275 else 276 Out<ELFT>::RelaDyn->addReloc({&C, &RI}); 277 } 278 } 279 280 template <class ELFT> void Writer<ELFT>::scanRelocs(InputSection<ELFT> &C) { 281 if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC)) 282 return; 283 284 for (const Elf_Shdr *RelSec : C.RelocSections) 285 scanRelocs(C, *RelSec); 286 } 287 288 template <class ELFT> 289 void Writer<ELFT>::scanRelocs(InputSectionBase<ELFT> &S, 290 const Elf_Shdr &RelSec) { 291 ELFFile<ELFT> &EObj = S.getFile()->getObj(); 292 if (RelSec.sh_type == SHT_RELA) 293 scanRelocs(S, EObj.relas(&RelSec)); 294 else 295 scanRelocs(S, EObj.rels(&RelSec)); 296 } 297 298 template <class ELFT> 299 static void reportUndefined(const SymbolTable<ELFT> &S, const SymbolBody &Sym) { 300 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym; 301 typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range; 302 303 if (Config->Shared && !Config->NoUndefined) 304 return; 305 306 const Elf_Sym &SymE = cast<ELFSymbolBody<ELFT>>(Sym).Sym; 307 ELFFileBase<ELFT> *SymFile = nullptr; 308 309 for (const std::unique_ptr<ObjectFile<ELFT>> &File : S.getObjectFiles()) { 310 Elf_Sym_Range Syms = File->getObj().symbols(File->getSymbolTable()); 311 if (&SymE > Syms.begin() && &SymE < Syms.end()) 312 SymFile = File.get(); 313 } 314 315 std::string Message = "undefined symbol: " + Sym.getName().str(); 316 if (SymFile) 317 Message += " in " + SymFile->getName().str(); 318 if (Config->NoInhibitExec) 319 warning(Message); 320 else 321 error(Message); 322 } 323 324 // Local symbols are not in the linker's symbol table. This function scans 325 // each object file's symbol table to copy local symbols to the output. 326 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() { 327 for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) { 328 for (const Elf_Sym &Sym : F->getLocalSymbols()) { 329 ErrorOr<StringRef> SymNameOrErr = Sym.getName(F->getStringTable()); 330 error(SymNameOrErr); 331 StringRef SymName = *SymNameOrErr; 332 if (!shouldKeepInSymtab<ELFT>(*F, SymName, Sym)) 333 continue; 334 if (Out<ELFT>::SymTab) 335 Out<ELFT>::SymTab->addLocalSymbol(SymName); 336 } 337 } 338 } 339 340 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that 341 // we would like to make sure appear is a specific order to maximize their 342 // coverage by a single signed 16-bit offset from the TOC base pointer. 343 // Conversely, the special .tocbss section should be first among all SHT_NOBITS 344 // sections. This will put it next to the loaded special PPC64 sections (and, 345 // thus, within reach of the TOC base pointer). 346 static int getPPC64SectionRank(StringRef SectionName) { 347 return StringSwitch<int>(SectionName) 348 .Case(".tocbss", 0) 349 .Case(".branch_lt", 2) 350 .Case(".toc", 3) 351 .Case(".toc1", 4) 352 .Case(".opd", 5) 353 .Default(1); 354 } 355 356 // Output section ordering is determined by this function. 357 template <class ELFT> 358 static bool compareOutputSections(OutputSectionBase<ELFT> *A, 359 OutputSectionBase<ELFT> *B) { 360 typedef typename ELFFile<ELFT>::uintX_t uintX_t; 361 362 uintX_t AFlags = A->getFlags(); 363 uintX_t BFlags = B->getFlags(); 364 365 // Allocatable sections go first to reduce the total PT_LOAD size and 366 // so debug info doesn't change addresses in actual code. 367 bool AIsAlloc = AFlags & SHF_ALLOC; 368 bool BIsAlloc = BFlags & SHF_ALLOC; 369 if (AIsAlloc != BIsAlloc) 370 return AIsAlloc; 371 372 // We don't have any special requirements for the relative order of 373 // two non allocatable sections. 374 if (!AIsAlloc) 375 return false; 376 377 // We want the read only sections first so that they go in the PT_LOAD 378 // covering the program headers at the start of the file. 379 bool AIsWritable = AFlags & SHF_WRITE; 380 bool BIsWritable = BFlags & SHF_WRITE; 381 if (AIsWritable != BIsWritable) 382 return BIsWritable; 383 384 // For a corresponding reason, put non exec sections first (the program 385 // header PT_LOAD is not executable). 386 bool AIsExec = AFlags & SHF_EXECINSTR; 387 bool BIsExec = BFlags & SHF_EXECINSTR; 388 if (AIsExec != BIsExec) 389 return BIsExec; 390 391 // If we got here we know that both A and B are in the same PT_LOAD. 392 393 // The TLS initialization block needs to be a single contiguous block in a R/W 394 // PT_LOAD, so stick TLS sections directly before R/W sections. The TLS NOBITS 395 // sections are placed here as they don't take up virtual address space in the 396 // PT_LOAD. 397 bool AIsTLS = AFlags & SHF_TLS; 398 bool BIsTLS = BFlags & SHF_TLS; 399 if (AIsTLS != BIsTLS) 400 return AIsTLS; 401 402 // The next requirement we have is to put nobits sections last. The 403 // reason is that the only thing the dynamic linker will see about 404 // them is a p_memsz that is larger than p_filesz. Seeing that it 405 // zeros the end of the PT_LOAD, so that has to correspond to the 406 // nobits sections. 407 bool AIsNoBits = A->getType() == SHT_NOBITS; 408 bool BIsNoBits = B->getType() == SHT_NOBITS; 409 if (AIsNoBits != BIsNoBits) 410 return BIsNoBits; 411 412 // Some architectures have additional ordering restrictions for sections 413 // within the same PT_LOAD. 414 if (Config->EMachine == EM_PPC64) 415 return getPPC64SectionRank(A->getName()) < 416 getPPC64SectionRank(B->getName()); 417 418 return false; 419 } 420 421 template <class ELFT> OutputSection<ELFT> *Writer<ELFT>::getBSS() { 422 if (!Out<ELFT>::Bss) { 423 Out<ELFT>::Bss = new (SecAlloc.Allocate()) 424 OutputSection<ELFT>(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE); 425 OutputSections.push_back(Out<ELFT>::Bss); 426 } 427 return Out<ELFT>::Bss; 428 } 429 430 // Until this function is called, common symbols do not belong to any section. 431 // This function adds them to end of BSS section. 432 template <class ELFT> 433 void Writer<ELFT>::addCommonSymbols(std::vector<DefinedCommon<ELFT> *> &Syms) { 434 typedef typename ELFFile<ELFT>::uintX_t uintX_t; 435 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym; 436 437 if (Syms.empty()) 438 return; 439 440 // Sort the common symbols by alignment as an heuristic to pack them better. 441 std::stable_sort( 442 Syms.begin(), Syms.end(), 443 [](const DefinedCommon<ELFT> *A, const DefinedCommon<ELFT> *B) { 444 return A->MaxAlignment > B->MaxAlignment; 445 }); 446 447 uintX_t Off = getBSS()->getSize(); 448 for (DefinedCommon<ELFT> *C : Syms) { 449 const Elf_Sym &Sym = C->Sym; 450 uintX_t Align = C->MaxAlignment; 451 Off = RoundUpToAlignment(Off, Align); 452 C->OffsetInBSS = Off; 453 Off += Sym.st_size; 454 } 455 456 Out<ELFT>::Bss->setSize(Off); 457 } 458 459 template <class ELFT> 460 void Writer<ELFT>::addSharedCopySymbols( 461 std::vector<SharedSymbol<ELFT> *> &Syms) { 462 typedef typename ELFFile<ELFT>::uintX_t uintX_t; 463 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym; 464 typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr; 465 466 if (Syms.empty()) 467 return; 468 469 uintX_t Off = getBSS()->getSize(); 470 for (SharedSymbol<ELFT> *C : Syms) { 471 const Elf_Sym &Sym = C->Sym; 472 const Elf_Shdr *Sec = C->File->getSection(Sym); 473 uintX_t SecAlign = Sec->sh_addralign; 474 uintX_t Align = Sym.st_value % SecAlign; 475 if (Align == 0) 476 Align = SecAlign; 477 Out<ELFT>::Bss->updateAlign(Align); 478 Off = RoundUpToAlignment(Off, Align); 479 C->OffsetInBSS = Off; 480 Off += Sym.st_size; 481 } 482 Out<ELFT>::Bss->setSize(Off); 483 } 484 485 template <class ELFT> 486 StringRef Writer<ELFT>::getOutputSectionName(StringRef S) const { 487 auto It = InputToOutputSection.find(S); 488 if (It != std::end(InputToOutputSection)) 489 return It->second; 490 491 if (S.startswith(".text.")) 492 return ".text"; 493 if (S.startswith(".rodata.")) 494 return ".rodata"; 495 if (S.startswith(".data.rel.ro")) 496 return ".data.rel.ro"; 497 if (S.startswith(".data.")) 498 return ".data"; 499 if (S.startswith(".bss.")) 500 return ".bss"; 501 return S; 502 } 503 504 template <class ELFT> 505 bool Writer<ELFT>::isDiscarded(InputSectionBase<ELFT> *IS) const { 506 if (!IS || !IS->isLive() || IS == &InputSection<ELFT>::Discarded) 507 return true; 508 return InputToOutputSection.lookup(IS->getSectionName()) == "/DISCARD/"; 509 } 510 511 template <class ELFT> 512 static bool compareSections(OutputSectionBase<ELFT> *A, 513 OutputSectionBase<ELFT> *B) { 514 auto ItA = Config->OutputSections.find(A->getName()); 515 auto ItEnd = std::end(Config->OutputSections); 516 if (ItA == ItEnd) 517 return compareOutputSections(A, B); 518 auto ItB = Config->OutputSections.find(B->getName()); 519 if (ItB == ItEnd) 520 return compareOutputSections(A, B); 521 522 return std::distance(ItA, ItB) > 0; 523 } 524 525 // Create output section objects and add them to OutputSections. 526 template <class ELFT> void Writer<ELFT>::createSections() { 527 // .interp needs to be on the first page in the output file. 528 if (needsInterpSection()) 529 OutputSections.push_back(Out<ELFT>::Interp); 530 531 SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSectionBase<ELFT> *> Map; 532 533 std::vector<OutputSectionBase<ELFT> *> RegularSections; 534 535 for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) { 536 for (InputSectionBase<ELFT> *C : F->getSections()) { 537 if (isDiscarded(C)) 538 continue; 539 const Elf_Shdr *H = C->getSectionHdr(); 540 uintX_t OutFlags = H->sh_flags & ~SHF_GROUP; 541 // For SHF_MERGE we create different output sections for each sh_entsize. 542 // This makes each output section simple and keeps a single level 543 // mapping from input to output. 544 typename InputSectionBase<ELFT>::Kind K = C->SectionKind; 545 uintX_t EntSize = K != InputSectionBase<ELFT>::Merge ? 0 : H->sh_entsize; 546 uint32_t OutType = H->sh_type; 547 if (OutType == SHT_PROGBITS && C->getSectionName() == ".eh_frame" && 548 Config->EMachine == EM_X86_64) 549 OutType = SHT_X86_64_UNWIND; 550 SectionKey<ELFT::Is64Bits> Key{getOutputSectionName(C->getSectionName()), 551 OutType, OutFlags, EntSize}; 552 OutputSectionBase<ELFT> *&Sec = Map[Key]; 553 if (!Sec) { 554 switch (K) { 555 case InputSectionBase<ELFT>::Regular: 556 Sec = new (SecAlloc.Allocate()) 557 OutputSection<ELFT>(Key.Name, Key.Type, Key.Flags); 558 break; 559 case InputSectionBase<ELFT>::EHFrame: 560 Sec = new (EHSecAlloc.Allocate()) 561 EHOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags); 562 break; 563 case InputSectionBase<ELFT>::Merge: 564 Sec = new (MSecAlloc.Allocate()) 565 MergeOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags); 566 break; 567 } 568 OutputSections.push_back(Sec); 569 RegularSections.push_back(Sec); 570 } 571 switch (K) { 572 case InputSectionBase<ELFT>::Regular: 573 static_cast<OutputSection<ELFT> *>(Sec) 574 ->addSection(cast<InputSection<ELFT>>(C)); 575 break; 576 case InputSectionBase<ELFT>::EHFrame: 577 static_cast<EHOutputSection<ELFT> *>(Sec) 578 ->addSection(cast<EHInputSection<ELFT>>(C)); 579 break; 580 case InputSectionBase<ELFT>::Merge: 581 static_cast<MergeOutputSection<ELFT> *>(Sec) 582 ->addSection(cast<MergeInputSection<ELFT>>(C)); 583 break; 584 } 585 } 586 } 587 588 Out<ELFT>::Bss = static_cast<OutputSection<ELFT> *>( 589 Map[{".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE, 0}]); 590 591 Out<ELFT>::Dynamic->PreInitArraySec = Map.lookup( 592 {".preinit_array", SHT_PREINIT_ARRAY, SHF_WRITE | SHF_ALLOC, 0}); 593 Out<ELFT>::Dynamic->InitArraySec = 594 Map.lookup({".init_array", SHT_INIT_ARRAY, SHF_WRITE | SHF_ALLOC, 0}); 595 Out<ELFT>::Dynamic->FiniArraySec = 596 Map.lookup({".fini_array", SHT_FINI_ARRAY, SHF_WRITE | SHF_ALLOC, 0}); 597 598 auto AddStartEnd = [&](StringRef Start, StringRef End, 599 OutputSectionBase<ELFT> *OS) { 600 if (OS) { 601 Symtab.addSyntheticSym(Start, *OS, 0); 602 Symtab.addSyntheticSym(End, *OS, OS->getSize()); 603 } else { 604 Symtab.addIgnoredSym(Start); 605 Symtab.addIgnoredSym(End); 606 } 607 }; 608 609 AddStartEnd("__preinit_array_start", "__preinit_array_end", 610 Out<ELFT>::Dynamic->PreInitArraySec); 611 AddStartEnd("__init_array_start", "__init_array_end", 612 Out<ELFT>::Dynamic->InitArraySec); 613 AddStartEnd("__fini_array_start", "__fini_array_end", 614 Out<ELFT>::Dynamic->FiniArraySec); 615 616 for (OutputSectionBase<ELFT> *Sec : RegularSections) 617 addStartStopSymbols(Sec); 618 619 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For 620 // static linking the linker is required to optimize away any references to 621 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition 622 // to avoid the undefined symbol error. 623 if (!isOutputDynamic()) 624 Symtab.addIgnoredSym("__tls_get_addr"); 625 626 // If the "_end" symbol is referenced, it is expected to point to the address 627 // right after the data segment. Usually, this symbol points to the end 628 // of .bss section or to the end of .data section if .bss section is absent. 629 // The order of the sections can be affected by linker script, 630 // so it is hard to predict which section will be the last one. 631 // So, if this symbol is referenced, we just add the placeholder here 632 // and update its value later. 633 if (Symtab.find("_end")) 634 Symtab.addAbsoluteSym("_end", DefinedAbsolute<ELFT>::End); 635 636 // If there is an undefined symbol "end", we should initialize it 637 // with the same value as "_end". In any other case it should stay intact, 638 // because it is an allowable name for a user symbol. 639 if (SymbolBody *B = Symtab.find("end")) 640 if (B->isUndefined()) 641 Symtab.addAbsoluteSym("end", DefinedAbsolute<ELFT>::End); 642 643 // Scan relocations. This must be done after every symbol is declared so that 644 // we can correctly decide if a dynamic relocation is needed. 645 for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) { 646 for (InputSectionBase<ELFT> *C : F->getSections()) { 647 if (isDiscarded(C)) 648 continue; 649 if (auto *S = dyn_cast<InputSection<ELFT>>(C)) 650 scanRelocs(*S); 651 else if (auto *S = dyn_cast<EHInputSection<ELFT>>(C)) 652 if (S->RelocSection) 653 scanRelocs(*S, *S->RelocSection); 654 } 655 } 656 657 std::vector<DefinedCommon<ELFT> *> CommonSymbols; 658 std::vector<SharedSymbol<ELFT> *> SharedCopySymbols; 659 for (auto &P : Symtab.getSymbols()) { 660 SymbolBody *Body = P.second->Body; 661 if (auto *U = dyn_cast<Undefined<ELFT>>(Body)) 662 if (!U->isWeak() && !U->canKeepUndefined()) 663 reportUndefined<ELFT>(Symtab, *Body); 664 665 if (auto *C = dyn_cast<DefinedCommon<ELFT>>(Body)) 666 CommonSymbols.push_back(C); 667 if (auto *SC = dyn_cast<SharedSymbol<ELFT>>(Body)) 668 if (SC->needsCopy()) 669 SharedCopySymbols.push_back(SC); 670 671 if (!includeInSymtab<ELFT>(*Body)) 672 continue; 673 if (Out<ELFT>::SymTab) 674 Out<ELFT>::SymTab->addSymbol(Body); 675 676 if (isOutputDynamic() && includeInDynamicSymtab(*Body)) 677 Out<ELFT>::DynSymTab->addSymbol(Body); 678 } 679 addCommonSymbols(CommonSymbols); 680 addSharedCopySymbols(SharedCopySymbols); 681 682 // This order is not the same as the final output order 683 // because we sort the sections using their attributes below. 684 if (Out<ELFT>::SymTab) 685 OutputSections.push_back(Out<ELFT>::SymTab); 686 OutputSections.push_back(Out<ELFT>::ShStrTab); 687 if (Out<ELFT>::StrTab) 688 OutputSections.push_back(Out<ELFT>::StrTab); 689 if (isOutputDynamic()) { 690 OutputSections.push_back(Out<ELFT>::DynSymTab); 691 if (Out<ELFT>::GnuHashTab) 692 OutputSections.push_back(Out<ELFT>::GnuHashTab); 693 if (Out<ELFT>::HashTab) 694 OutputSections.push_back(Out<ELFT>::HashTab); 695 OutputSections.push_back(Out<ELFT>::Dynamic); 696 OutputSections.push_back(Out<ELFT>::DynStrTab); 697 if (Out<ELFT>::RelaDyn->hasRelocs()) 698 OutputSections.push_back(Out<ELFT>::RelaDyn); 699 if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) 700 OutputSections.push_back(Out<ELFT>::RelaPlt); 701 // This is a MIPS specific section to hold a space within the data segment 702 // of executable file which is pointed to by the DT_MIPS_RLD_MAP entry. 703 // See "Dynamic section" in Chapter 5 in the following document: 704 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 705 if (Config->EMachine == EM_MIPS && !Config->Shared) { 706 Out<ELFT>::MipsRldMap = new (SecAlloc.Allocate()) 707 OutputSection<ELFT>(".rld_map", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE); 708 Out<ELFT>::MipsRldMap->setSize(ELFT::Is64Bits ? 8 : 4); 709 Out<ELFT>::MipsRldMap->updateAlign(ELFT::Is64Bits ? 8 : 4); 710 OutputSections.push_back(Out<ELFT>::MipsRldMap); 711 } 712 } 713 714 // We add the .got section to the result for dynamic MIPS target because 715 // its address and properties are mentioned in the .dynamic section. 716 if (!Out<ELFT>::Got->empty() || 717 (isOutputDynamic() && Config->EMachine == EM_MIPS)) 718 OutputSections.push_back(Out<ELFT>::Got); 719 if (Out<ELFT>::GotPlt && !Out<ELFT>::GotPlt->empty()) 720 OutputSections.push_back(Out<ELFT>::GotPlt); 721 if (!Out<ELFT>::Plt->empty()) 722 OutputSections.push_back(Out<ELFT>::Plt); 723 724 std::stable_sort(OutputSections.begin(), OutputSections.end(), 725 compareSections<ELFT>); 726 727 for (unsigned I = 0, N = OutputSections.size(); I < N; ++I) 728 OutputSections[I]->SectionIndex = I + 1; 729 730 for (OutputSectionBase<ELFT> *Sec : OutputSections) 731 Out<ELFT>::ShStrTab->add(Sec->getName()); 732 733 // Finalizers fix each section's size. 734 // .dynamic section's finalizer may add strings to .dynstr, 735 // so finalize that early. 736 // Likewise, .dynsym is finalized early since that may fill up .gnu.hash. 737 Out<ELFT>::Dynamic->finalize(); 738 if (isOutputDynamic()) 739 Out<ELFT>::DynSymTab->finalize(); 740 741 // Fill other section headers. 742 for (OutputSectionBase<ELFT> *Sec : OutputSections) 743 Sec->finalize(); 744 745 // If we have a .opd section (used under PPC64 for function descriptors), 746 // store a pointer to it here so that we can use it later when processing 747 // relocations. 748 Out<ELFT>::Opd = Map.lookup({".opd", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC, 0}); 749 } 750 751 static bool isAlpha(char C) { 752 return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_'; 753 } 754 755 static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); } 756 757 // Returns true if S is valid as a C language identifier. 758 static bool isValidCIdentifier(StringRef S) { 759 if (S.empty() || !isAlpha(S[0])) 760 return false; 761 return std::all_of(S.begin() + 1, S.end(), isAlnum); 762 } 763 764 // If a section name is valid as a C identifier (which is rare because of 765 // the leading '.'), linkers are expected to define __start_<secname> and 766 // __stop_<secname> symbols. They are at beginning and end of the section, 767 // respectively. This is not requested by the ELF standard, but GNU ld and 768 // gold provide the feature, and used by many programs. 769 template <class ELFT> 770 void Writer<ELFT>::addStartStopSymbols(OutputSectionBase<ELFT> *Sec) { 771 StringRef S = Sec->getName(); 772 if (!isValidCIdentifier(S)) 773 return; 774 StringSaver Saver(Alloc); 775 StringRef Start = Saver.save("__start_" + S); 776 StringRef Stop = Saver.save("__stop_" + S); 777 if (Symtab.isUndefined(Start)) 778 Symtab.addSyntheticSym(Start, *Sec, 0); 779 if (Symtab.isUndefined(Stop)) 780 Symtab.addSyntheticSym(Stop, *Sec, Sec->getSize()); 781 } 782 783 template <class ELFT> static bool needsPhdr(OutputSectionBase<ELFT> *Sec) { 784 return Sec->getFlags() & SHF_ALLOC; 785 } 786 787 static uint32_t toPhdrFlags(uint64_t Flags) { 788 uint32_t Ret = PF_R; 789 if (Flags & SHF_WRITE) 790 Ret |= PF_W; 791 if (Flags & SHF_EXECINSTR) 792 Ret |= PF_X; 793 return Ret; 794 } 795 796 // Visits all sections to create PHDRs and to assign incremental, 797 // non-overlapping addresses to output sections. 798 template <class ELFT> void Writer<ELFT>::assignAddresses() { 799 uintX_t VA = Target->getVAStart() + sizeof(Elf_Ehdr); 800 uintX_t FileOff = sizeof(Elf_Ehdr); 801 802 // Calculate and reserve the space for the program header first so that 803 // the first section can start right after the program header. 804 Phdrs.resize(getPhdrsNum()); 805 size_t PhdrSize = sizeof(Elf_Phdr) * Phdrs.size(); 806 807 // The first phdr entry is PT_PHDR which describes the program header itself. 808 setPhdr(&Phdrs[0], PT_PHDR, PF_R, FileOff, VA, PhdrSize, /*Align=*/8); 809 FileOff += PhdrSize; 810 VA += PhdrSize; 811 812 // PT_INTERP must be the second entry if exists. 813 int PhdrIdx = 0; 814 Elf_Phdr *Interp = nullptr; 815 if (needsInterpSection()) 816 Interp = &Phdrs[++PhdrIdx]; 817 818 // Add the first PT_LOAD segment for regular output sections. 819 setPhdr(&Phdrs[++PhdrIdx], PT_LOAD, PF_R, 0, Target->getVAStart(), FileOff, 820 Target->getPageSize()); 821 822 Elf_Phdr TlsPhdr{}; 823 uintX_t ThreadBSSOffset = 0; 824 // Create phdrs as we assign VAs and file offsets to all output sections. 825 for (OutputSectionBase<ELFT> *Sec : OutputSections) { 826 if (needsPhdr<ELFT>(Sec)) { 827 uintX_t Flags = toPhdrFlags(Sec->getFlags()); 828 if (Phdrs[PhdrIdx].p_flags != Flags) { 829 // Flags changed. Create a new PT_LOAD. 830 VA = RoundUpToAlignment(VA, Target->getPageSize()); 831 FileOff = RoundUpToAlignment(FileOff, Target->getPageSize()); 832 Elf_Phdr *PH = &Phdrs[++PhdrIdx]; 833 setPhdr(PH, PT_LOAD, Flags, FileOff, VA, 0, Target->getPageSize()); 834 } 835 836 if (Sec->getFlags() & SHF_TLS) { 837 if (!TlsPhdr.p_vaddr) 838 setPhdr(&TlsPhdr, PT_TLS, PF_R, FileOff, VA, 0, Sec->getAlign()); 839 if (Sec->getType() != SHT_NOBITS) 840 VA = RoundUpToAlignment(VA, Sec->getAlign()); 841 uintX_t TVA = RoundUpToAlignment(VA + ThreadBSSOffset, Sec->getAlign()); 842 Sec->setVA(TVA); 843 TlsPhdr.p_memsz += Sec->getSize(); 844 if (Sec->getType() == SHT_NOBITS) { 845 ThreadBSSOffset = TVA - VA + Sec->getSize(); 846 } else { 847 TlsPhdr.p_filesz += Sec->getSize(); 848 VA += Sec->getSize(); 849 } 850 TlsPhdr.p_align = std::max<uintX_t>(TlsPhdr.p_align, Sec->getAlign()); 851 } else { 852 VA = RoundUpToAlignment(VA, Sec->getAlign()); 853 Sec->setVA(VA); 854 VA += Sec->getSize(); 855 } 856 } 857 858 FileOff = RoundUpToAlignment(FileOff, Sec->getAlign()); 859 Sec->setFileOffset(FileOff); 860 if (Sec->getType() != SHT_NOBITS) 861 FileOff += Sec->getSize(); 862 if (needsPhdr<ELFT>(Sec)) { 863 Elf_Phdr *Cur = &Phdrs[PhdrIdx]; 864 Cur->p_filesz = FileOff - Cur->p_offset; 865 Cur->p_memsz = VA - Cur->p_vaddr; 866 } 867 } 868 869 if (TlsPhdr.p_vaddr) { 870 // The TLS pointer goes after PT_TLS. At least glibc will align it, 871 // so round up the size to make sure the offsets are correct. 872 TlsPhdr.p_memsz = RoundUpToAlignment(TlsPhdr.p_memsz, TlsPhdr.p_align); 873 Phdrs[++PhdrIdx] = TlsPhdr; 874 Out<ELFT>::TlsPhdr = &Phdrs[PhdrIdx]; 875 } 876 877 // Add an entry for .dynamic. 878 if (isOutputDynamic()) { 879 Elf_Phdr *PH = &Phdrs[++PhdrIdx]; 880 PH->p_type = PT_DYNAMIC; 881 copyPhdr(PH, Out<ELFT>::Dynamic); 882 } 883 884 // PT_GNU_STACK is a special section to tell the loader to make the 885 // pages for the stack non-executable. 886 if (!Config->ZExecStack) { 887 Elf_Phdr *PH = &Phdrs[++PhdrIdx]; 888 PH->p_type = PT_GNU_STACK; 889 PH->p_flags = PF_R | PF_W; 890 } 891 892 // Fix up PT_INTERP as we now know the address of .interp section. 893 if (Interp) { 894 Interp->p_type = PT_INTERP; 895 copyPhdr(Interp, Out<ELFT>::Interp); 896 } 897 898 // Add space for section headers. 899 SectionHeaderOff = RoundUpToAlignment(FileOff, ELFT::Is64Bits ? 8 : 4); 900 FileSize = SectionHeaderOff + getNumSections() * sizeof(Elf_Shdr); 901 902 // Update "_end" and "end" symbols so that they 903 // point to the end of the data segment. 904 DefinedAbsolute<ELFT>::End.st_value = VA; 905 906 // Update MIPS _gp absolute symbol so that it points to the static data. 907 if (Config->EMachine == EM_MIPS) 908 DefinedAbsolute<ELFT>::MipsGp.st_value = getMipsGpAddr<ELFT>(); 909 } 910 911 // Returns the number of PHDR entries. 912 template <class ELFT> int Writer<ELFT>::getPhdrsNum() const { 913 bool Tls = false; 914 int I = 2; // 2 for PT_PHDR and first PT_LOAD 915 if (needsInterpSection()) 916 ++I; 917 if (isOutputDynamic()) 918 ++I; 919 if (!Config->ZExecStack) 920 ++I; 921 uintX_t Last = PF_R; 922 for (OutputSectionBase<ELFT> *Sec : OutputSections) { 923 if (!needsPhdr<ELFT>(Sec)) 924 continue; 925 if (Sec->getFlags() & SHF_TLS) 926 Tls = true; 927 uintX_t Flags = toPhdrFlags(Sec->getFlags()); 928 if (Last != Flags) { 929 Last = Flags; 930 ++I; 931 } 932 } 933 if (Tls) 934 ++I; 935 return I; 936 } 937 938 template <class ELFT> void Writer<ELFT>::writeHeader() { 939 uint8_t *Buf = Buffer->getBufferStart(); 940 memcpy(Buf, "\177ELF", 4); 941 942 // Write the ELF header. 943 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf); 944 EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32; 945 EHdr->e_ident[EI_DATA] = ELFT::TargetEndianness == llvm::support::little 946 ? ELFDATA2LSB 947 : ELFDATA2MSB; 948 EHdr->e_ident[EI_VERSION] = EV_CURRENT; 949 950 auto &FirstObj = cast<ELFFileBase<ELFT>>(*Config->FirstElf); 951 EHdr->e_ident[EI_OSABI] = FirstObj.getOSABI(); 952 953 EHdr->e_type = Config->Shared ? ET_DYN : ET_EXEC; 954 EHdr->e_machine = FirstObj.getEMachine(); 955 EHdr->e_version = EV_CURRENT; 956 EHdr->e_entry = getEntryAddr(); 957 EHdr->e_phoff = sizeof(Elf_Ehdr); 958 EHdr->e_shoff = SectionHeaderOff; 959 EHdr->e_ehsize = sizeof(Elf_Ehdr); 960 EHdr->e_phentsize = sizeof(Elf_Phdr); 961 EHdr->e_phnum = Phdrs.size(); 962 EHdr->e_shentsize = sizeof(Elf_Shdr); 963 EHdr->e_shnum = getNumSections(); 964 EHdr->e_shstrndx = Out<ELFT>::ShStrTab->SectionIndex; 965 966 // Write the program header table. 967 memcpy(Buf + EHdr->e_phoff, &Phdrs[0], Phdrs.size() * sizeof(Phdrs[0])); 968 969 // Write the section header table. Note that the first table entry is null. 970 auto SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff); 971 for (OutputSectionBase<ELFT> *Sec : OutputSections) 972 Sec->writeHeaderTo(++SHdrs); 973 } 974 975 template <class ELFT> void Writer<ELFT>::openFile(StringRef Path) { 976 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr = 977 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable); 978 error(BufferOrErr, Twine("failed to open ") + Path); 979 Buffer = std::move(*BufferOrErr); 980 } 981 982 // Write section contents to a mmap'ed file. 983 template <class ELFT> void Writer<ELFT>::writeSections() { 984 uint8_t *Buf = Buffer->getBufferStart(); 985 986 // PPC64 needs to process relocations in the .opd section before processing 987 // relocations in code-containing sections. 988 if (OutputSectionBase<ELFT> *Sec = Out<ELFT>::Opd) { 989 Out<ELFT>::OpdBuf = Buf + Sec->getFileOff(); 990 Sec->writeTo(Buf + Sec->getFileOff()); 991 } 992 993 for (OutputSectionBase<ELFT> *Sec : OutputSections) 994 if (Sec != Out<ELFT>::Opd) 995 Sec->writeTo(Buf + Sec->getFileOff()); 996 } 997 998 template <class ELFT> 999 typename ELFFile<ELFT>::uintX_t Writer<ELFT>::getEntryAddr() const { 1000 if (Config->EntrySym) { 1001 if (auto *E = dyn_cast<ELFSymbolBody<ELFT>>(Config->EntrySym->repl())) 1002 return getSymVA<ELFT>(*E); 1003 return 0; 1004 } 1005 if (Config->EntryAddr != uint64_t(-1)) 1006 return Config->EntryAddr; 1007 return 0; 1008 } 1009 1010 template <class ELFT> 1011 void Writer<ELFT>::setPhdr(Elf_Phdr *PH, uint32_t Type, uint32_t Flags, 1012 uintX_t FileOff, uintX_t VA, uintX_t Size, 1013 uintX_t Align) { 1014 PH->p_type = Type; 1015 PH->p_flags = Flags; 1016 PH->p_offset = FileOff; 1017 PH->p_vaddr = VA; 1018 PH->p_paddr = VA; 1019 PH->p_filesz = Size; 1020 PH->p_memsz = Size; 1021 PH->p_align = Align; 1022 } 1023 1024 template <class ELFT> 1025 void Writer<ELFT>::copyPhdr(Elf_Phdr *PH, OutputSectionBase<ELFT> *From) { 1026 PH->p_flags = toPhdrFlags(From->getFlags()); 1027 PH->p_offset = From->getFileOff(); 1028 PH->p_vaddr = From->getVA(); 1029 PH->p_paddr = From->getVA(); 1030 PH->p_filesz = From->getSize(); 1031 PH->p_memsz = From->getSize(); 1032 PH->p_align = From->getAlign(); 1033 } 1034 1035 template <class ELFT> void Writer<ELFT>::buildSectionMap() { 1036 for (const std::pair<StringRef, std::vector<StringRef>> &OutSec : 1037 Config->OutputSections) 1038 for (StringRef Name : OutSec.second) 1039 InputToOutputSection[Name] = OutSec.first; 1040 } 1041 1042 template void lld::elf2::writeResult<ELF32LE>(SymbolTable<ELF32LE> *Symtab); 1043 template void lld::elf2::writeResult<ELF32BE>(SymbolTable<ELF32BE> *Symtab); 1044 template void lld::elf2::writeResult<ELF64LE>(SymbolTable<ELF64LE> *Symtab); 1045 template void lld::elf2::writeResult<ELF64BE>(SymbolTable<ELF64BE> *Symtab); 1046