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/SmallPtrSet.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 30 static uint32_t toPhdrFlags(uint64_t Flags) { 31 uint32_t Ret = PF_R; 32 if (Flags & SHF_WRITE) 33 Ret |= PF_W; 34 if (Flags & SHF_EXECINSTR) 35 Ret |= PF_X; 36 return Ret; 37 } 38 39 // The writer writes a SymbolTable result to a file. 40 template <class ELFT> class Writer { 41 public: 42 typedef typename ELFFile<ELFT>::uintX_t uintX_t; 43 typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr; 44 typedef typename ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr; 45 typedef typename ELFFile<ELFT>::Elf_Phdr Elf_Phdr; 46 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym; 47 typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range; 48 typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela; 49 Writer(SymbolTable<ELFT> &S) : Symtab(S) {} 50 void run(); 51 52 private: 53 void copyLocalSymbols(); 54 void createSections(); 55 template <bool isRela> 56 void scanRelocs(const InputSection<ELFT> &C, 57 iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels); 58 void scanRelocs(const InputSection<ELFT> &C); 59 void assignAddresses(); 60 void openFile(StringRef OutputPath); 61 void writeHeader(); 62 void writeSections(); 63 bool needsInterpSection() const { 64 return !Symtab.getSharedFiles().empty() && !Config->DynamicLinker.empty(); 65 } 66 bool isOutputDynamic() const { 67 return !Symtab.getSharedFiles().empty() || Config->Shared; 68 } 69 uintX_t getVAStart() const { return Config->Shared ? 0 : Target->getVAStart(); } 70 71 std::unique_ptr<llvm::FileOutputBuffer> Buffer; 72 73 SpecificBumpPtrAllocator<OutputSection<ELFT>> SecAlloc; 74 BumpPtrAllocator Alloc; 75 std::vector<OutputSectionBase<ELFT::Is64Bits> *> OutputSections; 76 unsigned getNumSections() const { return OutputSections.size() + 1; } 77 78 void addStartStopSymbols(OutputSectionBase<ELFT::Is64Bits> *Sec); 79 void setPhdr(Elf_Phdr *PH, uint32_t Type, uint32_t Flags, uintX_t FileOff, 80 uintX_t VA, uintX_t Align); 81 void copyPhdr(Elf_Phdr *PH, OutputSectionBase<ELFT::Is64Bits> *From); 82 83 SymbolTable<ELFT> &Symtab; 84 std::vector<Elf_Phdr> Phdrs; 85 86 uintX_t FileSize; 87 uintX_t SectionHeaderOff; 88 }; 89 } // anonymous namespace 90 91 template <class ELFT> void lld::elf2::writeResult(SymbolTable<ELFT> *Symtab) { 92 // Initialize output sections that are handled by Writer specially. 93 // Don't reorder because the order of initialization matters. 94 InterpSection<ELFT::Is64Bits> Interp; 95 Out<ELFT>::Interp = &Interp; 96 StringTableSection<ELFT::Is64Bits> StrTab(false); 97 Out<ELFT>::StrTab = &StrTab; 98 StringTableSection<ELFT::Is64Bits> DynStrTab(true); 99 Out<ELFT>::DynStrTab = &DynStrTab; 100 OutputSection<ELFT> Bss(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE); 101 Out<ELFT>::Bss = &Bss; 102 GotSection<ELFT> Got; 103 Out<ELFT>::Got = &Got; 104 PltSection<ELFT> Plt; 105 Out<ELFT>::Plt = &Plt; 106 SymbolTableSection<ELFT> SymTab(*Symtab, *Out<ELFT>::StrTab); 107 Out<ELFT>::SymTab = &SymTab; 108 SymbolTableSection<ELFT> DynSymTab(*Symtab, *Out<ELFT>::DynStrTab); 109 Out<ELFT>::DynSymTab = &DynSymTab; 110 HashTableSection<ELFT> HashTab; 111 Out<ELFT>::HashTab = &HashTab; 112 RelocationSection<ELFT> RelaDyn(Symtab->shouldUseRela()); 113 Out<ELFT>::RelaDyn = &RelaDyn; 114 DynamicSection<ELFT> Dynamic(*Symtab); 115 Out<ELFT>::Dynamic = &Dynamic; 116 117 Writer<ELFT>(*Symtab).run(); 118 } 119 120 // The main function of the writer. 121 template <class ELFT> void Writer<ELFT>::run() { 122 if (!Config->DiscardAll) 123 copyLocalSymbols(); 124 createSections(); 125 assignAddresses(); 126 openFile(Config->OutputFile); 127 writeHeader(); 128 writeSections(); 129 error(Buffer->commit()); 130 } 131 132 namespace { 133 template <bool Is64Bits> struct SectionKey { 134 typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t; 135 StringRef Name; 136 uint32_t Type; 137 uintX_t Flags; 138 }; 139 } 140 namespace llvm { 141 template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> { 142 static SectionKey<Is64Bits> getEmptyKey() { 143 return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0}; 144 } 145 static SectionKey<Is64Bits> getTombstoneKey() { 146 return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 147 0}; 148 } 149 static unsigned getHashValue(const SectionKey<Is64Bits> &Val) { 150 return hash_combine(Val.Name, Val.Type, Val.Flags); 151 } 152 static bool isEqual(const SectionKey<Is64Bits> &LHS, 153 const SectionKey<Is64Bits> &RHS) { 154 return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) && 155 LHS.Type == RHS.Type && LHS.Flags == RHS.Flags; 156 } 157 }; 158 } 159 160 // The reason we have to do this early scan is as follows 161 // * To mmap the output file, we need to know the size 162 // * For that, we need to know how many dynamic relocs we will have. 163 // It might be possible to avoid this by outputting the file with write: 164 // * Write the allocated output sections, computing addresses. 165 // * Apply relocations, recording which ones require a dynamic reloc. 166 // * Write the dynamic relocations. 167 // * Write the rest of the file. 168 template <class ELFT> 169 template <bool isRela> 170 void Writer<ELFT>::scanRelocs( 171 const InputSection<ELFT> &C, 172 iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels) { 173 typedef Elf_Rel_Impl<ELFT, isRela> RelType; 174 const ObjectFile<ELFT> &File = *C.getFile(); 175 bool IsMips64EL = File.getObj().isMips64EL(); 176 for (const RelType &RI : Rels) { 177 uint32_t SymIndex = RI.getSymbol(IsMips64EL); 178 SymbolBody *Body = File.getSymbolBody(SymIndex); 179 uint32_t Type = RI.getType(IsMips64EL); 180 181 // Set "used" bit for --as-needed. 182 if (Body && Body->isUndefined() && !Body->isWeak()) 183 if (auto *S = dyn_cast<SharedSymbol<ELFT>>(Body->repl())) 184 S->File->IsUsed = true; 185 186 if (Body) 187 Body = Body->repl(); 188 bool NeedsGot = false; 189 if (Body) { 190 if (Target->relocNeedsPlt(Type, *Body)) { 191 if (Body->isInPlt()) 192 continue; 193 Out<ELFT>::Plt->addEntry(Body); 194 } 195 NeedsGot = Target->relocNeedsGot(Type, *Body); 196 if (NeedsGot) { 197 if (Body->isInGot()) 198 continue; 199 Out<ELFT>::Got->addEntry(Body); 200 } 201 } 202 203 bool CBP = canBePreempted(Body, NeedsGot); 204 if (!CBP && (!Config->Shared || Target->isRelRelative(Type))) 205 continue; 206 if (CBP) 207 Body->setUsedInDynamicReloc(); 208 Out<ELFT>::RelaDyn->addReloc({C, RI}); 209 } 210 } 211 212 template <class ELFT> 213 void Writer<ELFT>::scanRelocs(const InputSection<ELFT> &C) { 214 ObjectFile<ELFT> *File = C.getFile(); 215 ELFFile<ELFT> &EObj = File->getObj(); 216 217 if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC)) 218 return; 219 220 for (const Elf_Shdr *RelSec : C.RelocSections) { 221 if (RelSec->sh_type == SHT_RELA) 222 scanRelocs(C, EObj.relas(RelSec)); 223 else 224 scanRelocs(C, EObj.rels(RelSec)); 225 } 226 } 227 228 template <class ELFT> 229 static void reportUndefined(const SymbolTable<ELFT> &S, const SymbolBody &Sym) { 230 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym; 231 typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range; 232 233 if (Config->Shared && !Config->NoUndefined) 234 return; 235 236 const Elf_Sym &SymE = cast<ELFSymbolBody<ELFT>>(Sym).Sym; 237 ELFFileBase<ELFT> *SymFile = nullptr; 238 239 for (const std::unique_ptr<ObjectFile<ELFT>> &File : S.getObjectFiles()) { 240 Elf_Sym_Range Syms = File->getObj().symbols(File->getSymbolTable()); 241 if (&SymE > Syms.begin() && &SymE < Syms.end()) 242 SymFile = File.get(); 243 } 244 245 std::string Message = "undefined symbol: " + Sym.getName().str(); 246 if (SymFile) 247 Message += " in " + SymFile->getName().str(); 248 if (Config->NoInhibitExec) 249 warning(Message); 250 else 251 error(Message); 252 } 253 254 // Local symbols are not in the linker's symbol table. This function scans 255 // each object file's symbol table to copy local symbols to the output. 256 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() { 257 for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) { 258 for (const Elf_Sym &Sym : F->getLocalSymbols()) { 259 ErrorOr<StringRef> SymNameOrErr = Sym.getName(F->getStringTable()); 260 error(SymNameOrErr); 261 StringRef SymName = *SymNameOrErr; 262 if (!shouldKeepInSymtab<ELFT>(*F, SymName, Sym)) 263 continue; 264 Out<ELFT>::SymTab->addSymbol(SymName, true); 265 } 266 } 267 } 268 269 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that 270 // we would like to make sure appear is a specific order to maximize their 271 // coverage by a single signed 16-bit offset from the TOC base pointer. 272 // Conversely, the special .tocbss section should be first among all SHT_NOBITS 273 // sections. This will put it next to the loaded special PPC64 sections (and, 274 // thus, within reach of the TOC base pointer). 275 static int getPPC64SectionRank(StringRef SectionName) { 276 return StringSwitch<int>(SectionName) 277 .Case(".tocbss", 0) 278 .Case(".branch_lt", 2) 279 .Case(".toc", 3) 280 .Case(".toc1", 4) 281 .Case(".opd", 5) 282 .Default(1); 283 } 284 285 // Output section ordering is determined by this function. 286 template <class ELFT> 287 static bool compareOutputSections(OutputSectionBase<ELFT::Is64Bits> *A, 288 OutputSectionBase<ELFT::Is64Bits> *B) { 289 typedef typename ELFFile<ELFT>::uintX_t uintX_t; 290 291 uintX_t AFlags = A->getFlags(); 292 uintX_t BFlags = B->getFlags(); 293 294 // Allocatable sections go first to reduce the total PT_LOAD size and 295 // so debug info doesn't change addresses in actual code. 296 bool AIsAlloc = AFlags & SHF_ALLOC; 297 bool BIsAlloc = BFlags & SHF_ALLOC; 298 if (AIsAlloc != BIsAlloc) 299 return AIsAlloc; 300 301 // We don't have any special requirements for the relative order of 302 // two non allocatable sections. 303 if (!AIsAlloc) 304 return false; 305 306 // We want the read only sections first so that they go in the PT_LOAD 307 // covering the program headers at the start of the file. 308 bool AIsWritable = AFlags & SHF_WRITE; 309 bool BIsWritable = BFlags & SHF_WRITE; 310 if (AIsWritable != BIsWritable) 311 return BIsWritable; 312 313 // For a corresponding reason, put non exec sections first (the program 314 // header PT_LOAD is not executable). 315 bool AIsExec = AFlags & SHF_EXECINSTR; 316 bool BIsExec = BFlags & SHF_EXECINSTR; 317 if (AIsExec != BIsExec) 318 return BIsExec; 319 320 // If we got here we know that both A and B are in the same PT_LOAD. 321 // The next requirement we have is to put nobits sections last. The 322 // reason is that the only thing the dynamic linker will see about 323 // them is a p_memsz that is larger than p_filesz. Seeing that it 324 // zeros the end of the PT_LOAD, so that has to correspond to the 325 // nobits sections. 326 bool AIsNoBits = A->getType() == SHT_NOBITS; 327 bool BIsNoBits = B->getType() == SHT_NOBITS; 328 if (AIsNoBits != BIsNoBits) 329 return BIsNoBits; 330 331 // Some architectures have additional ordering restrictions for sections 332 // within the same PT_LOAD. 333 if (Config->EMachine == EM_PPC64) 334 return getPPC64SectionRank(A->getName()) < 335 getPPC64SectionRank(B->getName()); 336 337 return false; 338 } 339 340 // Until this function is called, common symbols do not belong to any section. 341 // This function adds them to end of BSS section. 342 template <class ELFT> 343 static void addCommonSymbols(std::vector<DefinedCommon<ELFT> *> &Syms) { 344 typedef typename ELFFile<ELFT>::uintX_t uintX_t; 345 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym; 346 347 // Sort the common symbols by alignment as an heuristic to pack them better. 348 std::stable_sort( 349 Syms.begin(), Syms.end(), 350 [](const DefinedCommon<ELFT> *A, const DefinedCommon<ELFT> *B) { 351 return A->MaxAlignment > B->MaxAlignment; 352 }); 353 354 uintX_t Off = Out<ELFT>::Bss->getSize(); 355 for (DefinedCommon<ELFT> *C : Syms) { 356 const Elf_Sym &Sym = C->Sym; 357 uintX_t Align = C->MaxAlignment; 358 Off = RoundUpToAlignment(Off, Align); 359 C->OffsetInBSS = Off; 360 Off += Sym.st_size; 361 } 362 363 Out<ELFT>::Bss->setSize(Off); 364 } 365 366 static StringRef getOutputName(StringRef S) { 367 if (S.startswith(".text.")) 368 return ".text"; 369 if (S.startswith(".rodata.")) 370 return ".rodata"; 371 if (S.startswith(".data.")) 372 return ".data"; 373 if (S.startswith(".bss.")) 374 return ".bss"; 375 return S; 376 } 377 378 // Create output section objects and add them to OutputSections. 379 template <class ELFT> void Writer<ELFT>::createSections() { 380 // .interp needs to be on the first page in the output file. 381 if (needsInterpSection()) 382 OutputSections.push_back(Out<ELFT>::Interp); 383 384 SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSection<ELFT> *> Map; 385 386 OutputSections.push_back(Out<ELFT>::Bss); 387 Map[{Out<ELFT>::Bss->getName(), Out<ELFT>::Bss->getType(), 388 Out<ELFT>::Bss->getFlags()}] = Out<ELFT>::Bss; 389 390 // Declare linker generated symbols. 391 // This must be done before the relocation scan to make sure we can correctly 392 // decide if a dynamic relocation is needed or not. 393 // FIXME: Make this more declarative. 394 for (StringRef Name : 395 {"__preinit_array_start", "__preinit_array_end", "__init_array_start", 396 "__init_array_end", "__fini_array_start", "__fini_array_end"}) 397 Symtab.addIgnoredSym(Name); 398 399 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For 400 // static linking the linker is required to optimize away any references to 401 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition 402 // to avoid the undefined symbol error. 403 if (!isOutputDynamic()) 404 Symtab.addIgnoredSym("__tls_get_addr"); 405 406 std::vector<OutputSectionBase<ELFT::Is64Bits> *> RegularSections; 407 408 for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) { 409 for (InputSection<ELFT> *C : F->getSections()) { 410 if (!C || C == &InputSection<ELFT>::Discarded) 411 continue; 412 const Elf_Shdr *H = C->getSectionHdr(); 413 uintX_t OutFlags = H->sh_flags & ~SHF_GROUP; 414 SectionKey<ELFT::Is64Bits> Key{getOutputName(C->getSectionName()), 415 H->sh_type, OutFlags}; 416 OutputSection<ELFT> *&Sec = Map[Key]; 417 if (!Sec) { 418 Sec = new (SecAlloc.Allocate()) 419 OutputSection<ELFT>(Key.Name, Key.Type, Key.Flags); 420 OutputSections.push_back(Sec); 421 RegularSections.push_back(Sec); 422 } 423 Sec->addSection(C); 424 scanRelocs(*C); 425 } 426 } 427 428 for (OutputSectionBase<ELFT::Is64Bits> *Sec : RegularSections) 429 addStartStopSymbols(Sec); 430 431 Out<ELFT>::Dynamic->PreInitArraySec = 432 Map.lookup({".preinit_array", SHT_PREINIT_ARRAY, SHF_WRITE | SHF_ALLOC}); 433 Out<ELFT>::Dynamic->InitArraySec = 434 Map.lookup({".init_array", SHT_INIT_ARRAY, SHF_WRITE | SHF_ALLOC}); 435 Out<ELFT>::Dynamic->FiniArraySec = 436 Map.lookup({".fini_array", SHT_FINI_ARRAY, SHF_WRITE | SHF_ALLOC}); 437 438 auto AddStartEnd = [&](StringRef Start, StringRef End, 439 OutputSectionBase<ELFT::Is64Bits> *OS) { 440 if (OS) { 441 Symtab.addSyntheticSym(Start, *OS, 0); 442 Symtab.addSyntheticSym(End, *OS, OS->getSize()); 443 } 444 }; 445 446 AddStartEnd("__preinit_array_start", "__preinit_array_end", 447 Out<ELFT>::Dynamic->PreInitArraySec); 448 AddStartEnd("__init_array_start", "__init_array_end", 449 Out<ELFT>::Dynamic->InitArraySec); 450 AddStartEnd("__fini_array_start", "__fini_array_end", 451 Out<ELFT>::Dynamic->FiniArraySec); 452 453 // FIXME: Try to avoid the extra walk over all global symbols. 454 std::vector<DefinedCommon<ELFT> *> CommonSymbols; 455 for (auto &P : Symtab.getSymbols()) { 456 StringRef Name = P.first; 457 SymbolBody *Body = P.second->Body; 458 if (auto *U = dyn_cast<Undefined<ELFT>>(Body)) { 459 if (!U->isWeak() && !U->canKeepUndefined()) 460 reportUndefined<ELFT>(Symtab, *Body); 461 } 462 463 if (auto *C = dyn_cast<DefinedCommon<ELFT>>(Body)) 464 CommonSymbols.push_back(C); 465 if (!includeInSymtab<ELFT>(*Body)) 466 continue; 467 Out<ELFT>::SymTab->addSymbol(Name); 468 469 if (isOutputDynamic() && includeInDynamicSymtab(*Body)) 470 Out<ELFT>::HashTab->addSymbol(Body); 471 } 472 addCommonSymbols(CommonSymbols); 473 474 OutputSections.push_back(Out<ELFT>::SymTab); 475 if (isOutputDynamic()) { 476 OutputSections.push_back(Out<ELFT>::DynSymTab); 477 OutputSections.push_back(Out<ELFT>::HashTab); 478 OutputSections.push_back(Out<ELFT>::Dynamic); 479 OutputSections.push_back(Out<ELFT>::DynStrTab); 480 if (Out<ELFT>::RelaDyn->hasRelocs()) 481 OutputSections.push_back(Out<ELFT>::RelaDyn); 482 } 483 if (!Out<ELFT>::Got->empty()) 484 OutputSections.push_back(Out<ELFT>::Got); 485 if (!Out<ELFT>::Plt->empty()) 486 OutputSections.push_back(Out<ELFT>::Plt); 487 488 std::stable_sort(OutputSections.begin(), OutputSections.end(), 489 compareOutputSections<ELFT>); 490 491 // Always put StrTabSec last so that no section names are added to it after 492 // it's finalized. 493 OutputSections.push_back(Out<ELFT>::StrTab); 494 495 for (unsigned I = 0, N = OutputSections.size(); I < N; ++I) 496 OutputSections[I]->setSectionIndex(I + 1); 497 498 // Fill the DynStrTab early. 499 Out<ELFT>::Dynamic->finalize(); 500 501 // Fix each section's header (e.g. sh_size, sh_link, etc.) 502 for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections) { 503 Out<ELFT>::StrTab->add(Sec->getName()); 504 Sec->finalize(); 505 } 506 507 // If we have a .opd section (used under PPC64 for function descriptors), 508 // store a pointer to it here so that we can use it later when processing 509 // relocations. 510 Out<ELFT>::Opd = Map.lookup({".opd", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC}); 511 } 512 513 static bool isAlpha(char C) { 514 return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_'; 515 } 516 517 static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); } 518 519 // Returns true if S is valid as a C language identifier. 520 static bool isValidCIdentifier(StringRef S) { 521 if (S.empty() || !isAlpha(S[0])) 522 return false; 523 return std::all_of(S.begin() + 1, S.end(), isAlnum); 524 } 525 526 // If a section name is valid as a C identifier (which is rare because of 527 // the leading '.'), linkers are expected to define __start_<secname> and 528 // __stop_<secname> symbols. They are at beginning and end of the section, 529 // respectively. This is not requested by the ELF standard, but GNU ld and 530 // gold provide the feature, and used by many programs. 531 template <class ELFT> 532 void Writer<ELFT>::addStartStopSymbols(OutputSectionBase<ELFT::Is64Bits> *Sec) { 533 StringRef S = Sec->getName(); 534 if (!isValidCIdentifier(S)) 535 return; 536 StringSaver Saver(Alloc); 537 StringRef Start = Saver.save("__start_" + S); 538 StringRef Stop = Saver.save("__stop_" + S); 539 if (Symtab.isUndefined(Start)) 540 Symtab.addSyntheticSym(Start, *Sec, 0); 541 if (Symtab.isUndefined(Stop)) 542 Symtab.addSyntheticSym(Stop, *Sec, Sec->getSize()); 543 } 544 545 template <class ELFT> 546 static bool needsPhdr(OutputSectionBase<ELFT::Is64Bits> *Sec) { 547 return Sec->getFlags() & SHF_ALLOC; 548 } 549 550 // Visits all sections to assign incremental, non-overlapping RVAs and 551 // file offsets. 552 template <class ELFT> void Writer<ELFT>::assignAddresses() { 553 assert(!OutputSections.empty() && "No output sections to layout!"); 554 uintX_t VA = getVAStart() + sizeof(Elf_Ehdr); 555 uintX_t FileOff = sizeof(Elf_Ehdr); 556 557 // Reserve space for Phdrs. 558 int NumPhdrs = 2; // 2 for PhdrPhdr and FileHeaderPhdr 559 if (needsInterpSection()) 560 ++NumPhdrs; 561 if (isOutputDynamic()) 562 ++NumPhdrs; 563 uintX_t Last = PF_R; 564 for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections) { 565 if (!Sec->getSize() || !needsPhdr<ELFT>(Sec)) 566 continue; 567 uintX_t Flags = toPhdrFlags(Sec->getFlags()); 568 if (Last != Flags) { 569 Last = Flags; 570 ++NumPhdrs; 571 } 572 } 573 574 // Reserve space needed for the program header so that the array 575 // will never be resized. 576 Phdrs.reserve(NumPhdrs); 577 578 // The first Phdr entry is PT_PHDR which describes the program header itself. 579 Phdrs.emplace_back(); 580 Elf_Phdr *PhdrPhdr = &Phdrs.back(); 581 setPhdr(PhdrPhdr, PT_PHDR, PF_R, FileOff, VA, /*Align=*/8); 582 583 FileOff += sizeof(Elf_Phdr) * NumPhdrs; 584 VA += sizeof(Elf_Phdr) * NumPhdrs; 585 586 Elf_Phdr *Interp = nullptr; 587 if (needsInterpSection()) { 588 Phdrs.emplace_back(); 589 Interp = &Phdrs.back(); 590 } 591 592 // Create a Phdr for the file header. 593 Phdrs.emplace_back(); 594 Elf_Phdr *FileHeader = &Phdrs.back(); 595 setPhdr(FileHeader, PT_LOAD, PF_R, 0, getVAStart(), Target->getPageSize()); 596 597 SmallPtrSet<Elf_Phdr *, 8> Closed; 598 for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections) { 599 if (Sec->getSize()) { 600 uintX_t Flags = toPhdrFlags(Sec->getFlags()); 601 Elf_Phdr *Last = &Phdrs.back(); 602 if (Last->p_flags != Flags || !needsPhdr<ELFT>(Sec)) { 603 // Flags changed. End current Phdr and potentially create a new one. 604 if (Closed.insert(Last).second) { 605 Last->p_filesz = FileOff - Last->p_offset; 606 Last->p_memsz = VA - Last->p_vaddr; 607 } 608 609 if (needsPhdr<ELFT>(Sec)) { 610 VA = RoundUpToAlignment(VA, Target->getPageSize()); 611 FileOff = RoundUpToAlignment(FileOff, Target->getPageSize()); 612 Phdrs.emplace_back(); 613 Elf_Phdr *PH = &Phdrs.back(); 614 setPhdr(PH, PT_LOAD, Flags, FileOff, VA, Target->getPageSize()); 615 } 616 } 617 } 618 619 uintX_t Align = Sec->getAlign(); 620 uintX_t Size = Sec->getSize(); 621 if (Sec->getFlags() & SHF_ALLOC) { 622 VA = RoundUpToAlignment(VA, Align); 623 Sec->setVA(VA); 624 VA += Size; 625 } 626 FileOff = RoundUpToAlignment(FileOff, Align); 627 Sec->setFileOffset(FileOff); 628 if (Sec->getType() != SHT_NOBITS) 629 FileOff += Size; 630 } 631 632 if (Interp) { 633 Interp->p_type = PT_INTERP; 634 copyPhdr(Interp, Out<ELFT>::Interp); 635 } 636 if (isOutputDynamic()) { 637 Phdrs.emplace_back(); 638 Elf_Phdr *PH = &Phdrs.back(); 639 PH->p_type = PT_DYNAMIC; 640 copyPhdr(PH, Out<ELFT>::Dynamic); 641 } 642 643 // Fix up the first entry's size. 644 PhdrPhdr->p_filesz = sizeof(Elf_Phdr) * Phdrs.size(); 645 PhdrPhdr->p_memsz = sizeof(Elf_Phdr) * Phdrs.size(); 646 647 // If nothing was merged into the file header PT_LOAD, set the size correctly. 648 if (FileHeader->p_filesz == Target->getPageSize()) { 649 uint64_t Size = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * Phdrs.size(); 650 FileHeader->p_filesz = Size; 651 FileHeader->p_memsz = Size; 652 } 653 654 // Add space for section headers. 655 FileOff = RoundUpToAlignment(FileOff, ELFT::Is64Bits ? 8 : 4); 656 SectionHeaderOff = FileOff; 657 FileOff += getNumSections() * sizeof(Elf_Shdr); 658 FileSize = FileOff; 659 } 660 661 template <class ELFT> void Writer<ELFT>::writeHeader() { 662 uint8_t *Buf = Buffer->getBufferStart(); 663 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf); 664 EHdr->e_ident[EI_MAG0] = 0x7F; 665 EHdr->e_ident[EI_MAG1] = 0x45; 666 EHdr->e_ident[EI_MAG2] = 0x4C; 667 EHdr->e_ident[EI_MAG3] = 0x46; 668 EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32; 669 EHdr->e_ident[EI_DATA] = ELFT::TargetEndianness == llvm::support::little 670 ? ELFDATA2LSB 671 : ELFDATA2MSB; 672 EHdr->e_ident[EI_VERSION] = EV_CURRENT; 673 674 auto &FirstObj = cast<ELFFileBase<ELFT>>(*Config->FirstElf); 675 EHdr->e_ident[EI_OSABI] = FirstObj.getOSABI(); 676 677 // FIXME: Generalize the segment construction similar to how we create 678 // output sections. 679 680 EHdr->e_type = Config->Shared ? ET_DYN : ET_EXEC; 681 EHdr->e_machine = FirstObj.getEMachine(); 682 EHdr->e_version = EV_CURRENT; 683 if (Config->EntrySym) { 684 if (auto *E = dyn_cast<ELFSymbolBody<ELFT>>(Config->EntrySym->repl())) 685 EHdr->e_entry = getSymVA<ELFT>(*E); 686 } else if (Config->EntryAddr != uint64_t(-1)) { 687 EHdr->e_entry = Config->EntryAddr; 688 } 689 EHdr->e_phoff = sizeof(Elf_Ehdr); 690 EHdr->e_shoff = SectionHeaderOff; 691 EHdr->e_ehsize = sizeof(Elf_Ehdr); 692 EHdr->e_phentsize = sizeof(Elf_Phdr); 693 EHdr->e_phnum = Phdrs.size(); 694 EHdr->e_shentsize = sizeof(Elf_Shdr); 695 EHdr->e_shnum = getNumSections(); 696 EHdr->e_shstrndx = Out<ELFT>::StrTab->getSectionIndex(); 697 memcpy(Buf + EHdr->e_phoff, &Phdrs[0], Phdrs.size() * sizeof(Phdrs[0])); 698 699 auto SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff); 700 // First entry is null. 701 ++SHdrs; 702 for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections) { 703 Sec->setNameOffset(Out<ELFT>::StrTab->getFileOff(Sec->getName())); 704 Sec->template writeHeaderTo<ELFT::TargetEndianness>(SHdrs++); 705 } 706 } 707 708 template <class ELFT> void Writer<ELFT>::openFile(StringRef Path) { 709 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr = 710 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable); 711 error(BufferOrErr, Twine("failed to open ") + Path); 712 Buffer = std::move(*BufferOrErr); 713 } 714 715 // Write section contents to a mmap'ed file. 716 template <class ELFT> void Writer<ELFT>::writeSections() { 717 uint8_t *Buf = Buffer->getBufferStart(); 718 719 // PPC64 needs to process relocations in the .opd section before processing 720 // relocations in code-containing sections. 721 if (OutputSectionBase<ELFT::Is64Bits> *Sec = Out<ELFT>::Opd) { 722 Out<ELFT>::OpdBuf = Buf + Sec->getFileOff(); 723 Sec->writeTo(Buf + Sec->getFileOff()); 724 } 725 726 for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections) 727 if (Sec != Out<ELFT>::Opd) 728 Sec->writeTo(Buf + Sec->getFileOff()); 729 } 730 731 template <class ELFT> 732 void Writer<ELFT>::setPhdr(Elf_Phdr *PH, uint32_t Type, uint32_t Flags, 733 uintX_t FileOff, uintX_t VA, uintX_t Align) { 734 PH->p_type = Type; 735 PH->p_flags = Flags; 736 PH->p_offset = FileOff; 737 PH->p_vaddr = VA; 738 PH->p_paddr = VA; 739 PH->p_align = Align; 740 } 741 742 template <class ELFT> 743 void Writer<ELFT>::copyPhdr(Elf_Phdr *PH, 744 OutputSectionBase<ELFT::Is64Bits> *From) { 745 PH->p_flags = toPhdrFlags(From->getFlags()); 746 PH->p_offset = From->getFileOff(); 747 PH->p_vaddr = From->getVA(); 748 PH->p_paddr = From->getVA(); 749 PH->p_filesz = From->getSize(); 750 PH->p_memsz = From->getSize(); 751 PH->p_align = From->getAlign(); 752 } 753 754 template void lld::elf2::writeResult<ELF32LE>(SymbolTable<ELF32LE> *Symtab); 755 template void lld::elf2::writeResult<ELF32BE>(SymbolTable<ELF32BE> *Symtab); 756 template void lld::elf2::writeResult<ELF64LE>(SymbolTable<ELF64LE> *Symtab); 757 template void lld::elf2::writeResult<ELF64BE>(SymbolTable<ELF64BE> *Symtab); 758