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