1 //===- InputFiles.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 "InputFiles.h" 11 #include "InputSection.h" 12 #include "LinkerScript.h" 13 #include "SymbolTable.h" 14 #include "Symbols.h" 15 #include "SyntheticSections.h" 16 #include "lld/Common/ErrorHandler.h" 17 #include "lld/Common/Memory.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/CodeGen/Analysis.h" 20 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 21 #include "llvm/IR/LLVMContext.h" 22 #include "llvm/IR/Module.h" 23 #include "llvm/LTO/LTO.h" 24 #include "llvm/MC/StringTableBuilder.h" 25 #include "llvm/Object/ELFObjectFile.h" 26 #include "llvm/Support/ARMAttributeParser.h" 27 #include "llvm/Support/ARMBuildAttributes.h" 28 #include "llvm/Support/Path.h" 29 #include "llvm/Support/TarWriter.h" 30 #include "llvm/Support/raw_ostream.h" 31 32 using namespace llvm; 33 using namespace llvm::ELF; 34 using namespace llvm::object; 35 using namespace llvm::sys; 36 using namespace llvm::sys::fs; 37 38 using namespace lld; 39 using namespace lld::elf; 40 41 bool InputFile::IsInGroup; 42 uint32_t InputFile::NextGroupId; 43 std::vector<BinaryFile *> elf::BinaryFiles; 44 std::vector<BitcodeFile *> elf::BitcodeFiles; 45 std::vector<LazyObjFile *> elf::LazyObjFiles; 46 std::vector<InputFile *> elf::ObjectFiles; 47 std::vector<InputFile *> elf::SharedFiles; 48 49 TarWriter *elf::Tar; 50 51 InputFile::InputFile(Kind K, MemoryBufferRef M) 52 : MB(M), GroupId(NextGroupId), FileKind(K) { 53 // All files within the same --{start,end}-group get the same group ID. 54 // Otherwise, a new file will get a new group ID. 55 if (!IsInGroup) 56 ++NextGroupId; 57 } 58 59 Optional<MemoryBufferRef> elf::readFile(StringRef Path) { 60 // The --chroot option changes our virtual root directory. 61 // This is useful when you are dealing with files created by --reproduce. 62 if (!Config->Chroot.empty() && Path.startswith("/")) 63 Path = Saver.save(Config->Chroot + Path); 64 65 log(Path); 66 67 auto MBOrErr = MemoryBuffer::getFile(Path, -1, false); 68 if (auto EC = MBOrErr.getError()) { 69 error("cannot open " + Path + ": " + EC.message()); 70 return None; 71 } 72 73 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr; 74 MemoryBufferRef MBRef = MB->getMemBufferRef(); 75 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership 76 77 if (Tar) 78 Tar->append(relativeToRoot(Path), MBRef.getBuffer()); 79 return MBRef; 80 } 81 82 // Concatenates arguments to construct a string representing an error location. 83 static std::string createFileLineMsg(StringRef Path, unsigned Line) { 84 std::string Filename = path::filename(Path); 85 std::string Lineno = ":" + std::to_string(Line); 86 if (Filename == Path) 87 return Filename + Lineno; 88 return Filename + Lineno + " (" + Path.str() + Lineno + ")"; 89 } 90 91 template <class ELFT> 92 static std::string getSrcMsgAux(ObjFile<ELFT> &File, const Symbol &Sym, 93 InputSectionBase &Sec, uint64_t Offset) { 94 // In DWARF, functions and variables are stored to different places. 95 // First, lookup a function for a given offset. 96 if (Optional<DILineInfo> Info = File.getDILineInfo(&Sec, Offset)) 97 return createFileLineMsg(Info->FileName, Info->Line); 98 99 // If it failed, lookup again as a variable. 100 if (Optional<std::pair<std::string, unsigned>> FileLine = 101 File.getVariableLoc(Sym.getName())) 102 return createFileLineMsg(FileLine->first, FileLine->second); 103 104 // File.SourceFile contains STT_FILE symbol, and that is a last resort. 105 return File.SourceFile; 106 } 107 108 std::string InputFile::getSrcMsg(const Symbol &Sym, InputSectionBase &Sec, 109 uint64_t Offset) { 110 if (kind() != ObjKind) 111 return ""; 112 switch (Config->EKind) { 113 default: 114 llvm_unreachable("Invalid kind"); 115 case ELF32LEKind: 116 return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), Sym, Sec, Offset); 117 case ELF32BEKind: 118 return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), Sym, Sec, Offset); 119 case ELF64LEKind: 120 return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), Sym, Sec, Offset); 121 case ELF64BEKind: 122 return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), Sym, Sec, Offset); 123 } 124 } 125 126 template <class ELFT> void ObjFile<ELFT>::initializeDwarf() { 127 Dwarf = llvm::make_unique<DWARFContext>(make_unique<LLDDwarfObj<ELFT>>(this)); 128 const DWARFObject &Obj = Dwarf->getDWARFObj(); 129 DwarfLine.reset(new DWARFDebugLine); 130 DWARFDataExtractor LineData(Obj, Obj.getLineSection(), Config->IsLE, 131 Config->Wordsize); 132 133 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf->compile_units()) { 134 auto Report = [](Error Err) { 135 handleAllErrors(std::move(Err), 136 [](ErrorInfoBase &Info) { warn(Info.message()); }); 137 }; 138 Expected<const DWARFDebugLine::LineTable *> ExpectedLT = 139 Dwarf->getLineTableForUnit(CU.get(), Report); 140 const DWARFDebugLine::LineTable *LT = nullptr; 141 if (ExpectedLT) 142 LT = *ExpectedLT; 143 else 144 Report(ExpectedLT.takeError()); 145 if (!LT) 146 continue; 147 LineTables.push_back(LT); 148 149 // Loop over variable records and insert them to VariableLoc. 150 for (const auto &Entry : CU->dies()) { 151 DWARFDie Die(CU.get(), &Entry); 152 // Skip all tags that are not variables. 153 if (Die.getTag() != dwarf::DW_TAG_variable) 154 continue; 155 156 // Skip if a local variable because we don't need them for generating 157 // error messages. In general, only non-local symbols can fail to be 158 // linked. 159 if (!dwarf::toUnsigned(Die.find(dwarf::DW_AT_external), 0)) 160 continue; 161 162 // Get the source filename index for the variable. 163 unsigned File = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_file), 0); 164 if (!LT->hasFileAtIndex(File)) 165 continue; 166 167 // Get the line number on which the variable is declared. 168 unsigned Line = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_line), 0); 169 170 // Get the name of the variable and add the collected information to 171 // VariableLoc. Usually Name is non-empty, but it can be empty if the 172 // input object file lacks some debug info. 173 StringRef Name = dwarf::toString(Die.find(dwarf::DW_AT_name), ""); 174 if (!Name.empty()) 175 VariableLoc.insert({Name, {LT, File, Line}}); 176 } 177 } 178 } 179 180 // Returns the pair of file name and line number describing location of data 181 // object (variable, array, etc) definition. 182 template <class ELFT> 183 Optional<std::pair<std::string, unsigned>> 184 ObjFile<ELFT>::getVariableLoc(StringRef Name) { 185 llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); }); 186 187 // Return if we have no debug information about data object. 188 auto It = VariableLoc.find(Name); 189 if (It == VariableLoc.end()) 190 return None; 191 192 // Take file name string from line table. 193 std::string FileName; 194 if (!It->second.LT->getFileNameByIndex( 195 It->second.File, nullptr, 196 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FileName)) 197 return None; 198 199 return std::make_pair(FileName, It->second.Line); 200 } 201 202 // Returns source line information for a given offset 203 // using DWARF debug info. 204 template <class ELFT> 205 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *S, 206 uint64_t Offset) { 207 llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); }); 208 209 // Use fake address calcuated by adding section file offset and offset in 210 // section. See comments for ObjectInfo class. 211 DILineInfo Info; 212 for (const llvm::DWARFDebugLine::LineTable *LT : LineTables) 213 if (LT->getFileLineInfoForAddress( 214 S->getOffsetInFile() + Offset, nullptr, 215 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info)) 216 return Info; 217 return None; 218 } 219 220 // Returns source line information for a given offset using DWARF debug info. 221 template <class ELFT> 222 std::string ObjFile<ELFT>::getLineInfo(InputSectionBase *S, uint64_t Offset) { 223 if (Optional<DILineInfo> Info = getDILineInfo(S, Offset)) 224 return Info->FileName + ":" + std::to_string(Info->Line); 225 return ""; 226 } 227 228 // Returns "<internal>", "foo.a(bar.o)" or "baz.o". 229 std::string lld::toString(const InputFile *F) { 230 if (!F) 231 return "<internal>"; 232 233 if (F->ToStringCache.empty()) { 234 if (F->ArchiveName.empty()) 235 F->ToStringCache = F->getName(); 236 else 237 F->ToStringCache = (F->ArchiveName + "(" + F->getName() + ")").str(); 238 } 239 return F->ToStringCache; 240 } 241 242 template <class ELFT> 243 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) { 244 if (ELFT::TargetEndianness == support::little) 245 EKind = ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind; 246 else 247 EKind = ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind; 248 249 EMachine = getObj().getHeader()->e_machine; 250 OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI]; 251 } 252 253 template <class ELFT> 254 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalELFSyms() { 255 return makeArrayRef(ELFSyms.begin() + FirstGlobal, ELFSyms.end()); 256 } 257 258 template <class ELFT> 259 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const { 260 return CHECK(getObj().getSectionIndex(&Sym, ELFSyms, SymtabSHNDX), this); 261 } 262 263 template <class ELFT> 264 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections, 265 const Elf_Shdr *Symtab) { 266 FirstGlobal = Symtab->sh_info; 267 ELFSyms = CHECK(getObj().symbols(Symtab), this); 268 if (FirstGlobal == 0 || FirstGlobal > ELFSyms.size()) 269 fatal(toString(this) + ": invalid sh_info in symbol table"); 270 271 StringTable = 272 CHECK(getObj().getStringTableForSymtab(*Symtab, Sections), this); 273 } 274 275 template <class ELFT> 276 ObjFile<ELFT>::ObjFile(MemoryBufferRef M, StringRef ArchiveName) 277 : ELFFileBase<ELFT>(Base::ObjKind, M) { 278 this->ArchiveName = ArchiveName; 279 } 280 281 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() { 282 if (this->Symbols.empty()) 283 return {}; 284 return makeArrayRef(this->Symbols).slice(1, this->FirstGlobal - 1); 285 } 286 287 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() { 288 return makeArrayRef(this->Symbols).slice(this->FirstGlobal); 289 } 290 291 template <class ELFT> 292 void ObjFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) { 293 // Read a section table. JustSymbols is usually false. 294 if (this->JustSymbols) 295 initializeJustSymbols(); 296 else 297 initializeSections(ComdatGroups); 298 299 // Read a symbol table. 300 initializeSymbols(); 301 } 302 303 // Sections with SHT_GROUP and comdat bits define comdat section groups. 304 // They are identified and deduplicated by group name. This function 305 // returns a group name. 306 template <class ELFT> 307 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections, 308 const Elf_Shdr &Sec) { 309 // Group signatures are stored as symbol names in object files. 310 // sh_info contains a symbol index, so we fetch a symbol and read its name. 311 if (this->ELFSyms.empty()) 312 this->initSymtab( 313 Sections, CHECK(object::getSection<ELFT>(Sections, Sec.sh_link), this)); 314 315 const Elf_Sym *Sym = 316 CHECK(object::getSymbol<ELFT>(this->ELFSyms, Sec.sh_info), this); 317 StringRef Signature = CHECK(Sym->getName(this->StringTable), this); 318 319 // As a special case, if a symbol is a section symbol and has no name, 320 // we use a section name as a signature. 321 // 322 // Such SHT_GROUP sections are invalid from the perspective of the ELF 323 // standard, but GNU gold 1.14 (the newest version as of July 2017) or 324 // older produce such sections as outputs for the -r option, so we need 325 // a bug-compatibility. 326 if (Signature.empty() && Sym->getType() == STT_SECTION) 327 return getSectionName(Sec); 328 return Signature; 329 } 330 331 template <class ELFT> 332 ArrayRef<typename ObjFile<ELFT>::Elf_Word> 333 ObjFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) { 334 const ELFFile<ELFT> &Obj = this->getObj(); 335 ArrayRef<Elf_Word> Entries = 336 CHECK(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), this); 337 if (Entries.empty() || Entries[0] != GRP_COMDAT) 338 fatal(toString(this) + ": unsupported SHT_GROUP format"); 339 return Entries.slice(1); 340 } 341 342 template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) { 343 // On a regular link we don't merge sections if -O0 (default is -O1). This 344 // sometimes makes the linker significantly faster, although the output will 345 // be bigger. 346 // 347 // Doing the same for -r would create a problem as it would combine sections 348 // with different sh_entsize. One option would be to just copy every SHF_MERGE 349 // section as is to the output. While this would produce a valid ELF file with 350 // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when 351 // they see two .debug_str. We could have separate logic for combining 352 // SHF_MERGE sections based both on their name and sh_entsize, but that seems 353 // to be more trouble than it is worth. Instead, we just use the regular (-O1) 354 // logic for -r. 355 if (Config->Optimize == 0 && !Config->Relocatable) 356 return false; 357 358 // A mergeable section with size 0 is useless because they don't have 359 // any data to merge. A mergeable string section with size 0 can be 360 // argued as invalid because it doesn't end with a null character. 361 // We'll avoid a mess by handling them as if they were non-mergeable. 362 if (Sec.sh_size == 0) 363 return false; 364 365 // Check for sh_entsize. The ELF spec is not clear about the zero 366 // sh_entsize. It says that "the member [sh_entsize] contains 0 if 367 // the section does not hold a table of fixed-size entries". We know 368 // that Rust 1.13 produces a string mergeable section with a zero 369 // sh_entsize. Here we just accept it rather than being picky about it. 370 uint64_t EntSize = Sec.sh_entsize; 371 if (EntSize == 0) 372 return false; 373 if (Sec.sh_size % EntSize) 374 fatal(toString(this) + 375 ": SHF_MERGE section size must be a multiple of sh_entsize"); 376 377 uint64_t Flags = Sec.sh_flags; 378 if (!(Flags & SHF_MERGE)) 379 return false; 380 if (Flags & SHF_WRITE) 381 fatal(toString(this) + ": writable SHF_MERGE section is not supported"); 382 383 return true; 384 } 385 386 // This is for --just-symbols. 387 // 388 // --just-symbols is a very minor feature that allows you to link your 389 // output against other existing program, so that if you load both your 390 // program and the other program into memory, your output can refer the 391 // other program's symbols. 392 // 393 // When the option is given, we link "just symbols". The section table is 394 // initialized with null pointers. 395 template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() { 396 ArrayRef<Elf_Shdr> ObjSections = CHECK(this->getObj().sections(), this); 397 this->Sections.resize(ObjSections.size()); 398 399 for (const Elf_Shdr &Sec : ObjSections) { 400 if (Sec.sh_type != SHT_SYMTAB) 401 continue; 402 this->initSymtab(ObjSections, &Sec); 403 return; 404 } 405 } 406 407 template <class ELFT> 408 void ObjFile<ELFT>::initializeSections( 409 DenseSet<CachedHashStringRef> &ComdatGroups) { 410 const ELFFile<ELFT> &Obj = this->getObj(); 411 412 ArrayRef<Elf_Shdr> ObjSections = CHECK(Obj.sections(), this); 413 uint64_t Size = ObjSections.size(); 414 this->Sections.resize(Size); 415 this->SectionStringTable = 416 CHECK(Obj.getSectionStringTable(ObjSections), this); 417 418 for (size_t I = 0, E = ObjSections.size(); I < E; I++) { 419 if (this->Sections[I] == &InputSection::Discarded) 420 continue; 421 const Elf_Shdr &Sec = ObjSections[I]; 422 423 // SHF_EXCLUDE'ed sections are discarded by the linker. However, 424 // if -r is given, we'll let the final link discard such sections. 425 // This is compatible with GNU. 426 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) { 427 this->Sections[I] = &InputSection::Discarded; 428 continue; 429 } 430 431 switch (Sec.sh_type) { 432 case SHT_GROUP: { 433 // De-duplicate section groups by their signatures. 434 StringRef Signature = getShtGroupSignature(ObjSections, Sec); 435 bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second; 436 this->Sections[I] = &InputSection::Discarded; 437 438 // If it is a new section group, we want to keep group members. 439 // Group leader sections, which contain indices of group members, are 440 // discarded because they are useless beyond this point. The only 441 // exception is the -r option because in order to produce re-linkable 442 // object files, we want to pass through basically everything. 443 if (IsNew) { 444 if (Config->Relocatable) 445 this->Sections[I] = createInputSection(Sec); 446 continue; 447 } 448 449 // Otherwise, discard group members. 450 for (uint32_t SecIndex : getShtGroupEntries(Sec)) { 451 if (SecIndex >= Size) 452 fatal(toString(this) + 453 ": invalid section index in group: " + Twine(SecIndex)); 454 this->Sections[SecIndex] = &InputSection::Discarded; 455 } 456 break; 457 } 458 case SHT_SYMTAB: 459 this->initSymtab(ObjSections, &Sec); 460 break; 461 case SHT_SYMTAB_SHNDX: 462 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, ObjSections), this); 463 break; 464 case SHT_STRTAB: 465 case SHT_NULL: 466 break; 467 default: 468 this->Sections[I] = createInputSection(Sec); 469 } 470 471 // .ARM.exidx sections have a reverse dependency on the InputSection they 472 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link. 473 if (Sec.sh_flags & SHF_LINK_ORDER) { 474 if (Sec.sh_link >= this->Sections.size()) 475 fatal(toString(this) + 476 ": invalid sh_link index: " + Twine(Sec.sh_link)); 477 478 InputSectionBase *LinkSec = this->Sections[Sec.sh_link]; 479 InputSection *IS = cast<InputSection>(this->Sections[I]); 480 LinkSec->DependentSections.push_back(IS); 481 if (!isa<InputSection>(LinkSec)) 482 error("a section " + IS->Name + 483 " with SHF_LINK_ORDER should not refer a non-regular " 484 "section: " + 485 toString(LinkSec)); 486 } 487 } 488 } 489 490 // The ARM support in lld makes some use of instructions that are not available 491 // on all ARM architectures. Namely: 492 // - Use of BLX instruction for interworking between ARM and Thumb state. 493 // - Use of the extended Thumb branch encoding in relocation. 494 // - Use of the MOVT/MOVW instructions in Thumb Thunks. 495 // The ARM Attributes section contains information about the architecture chosen 496 // at compile time. We follow the convention that if at least one input object 497 // is compiled with an architecture that supports these features then lld is 498 // permitted to use them. 499 static void updateSupportedARMFeatures(const ARMAttributeParser &Attributes) { 500 if (!Attributes.hasAttribute(ARMBuildAttrs::CPU_arch)) 501 return; 502 auto Arch = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch); 503 switch (Arch) { 504 case ARMBuildAttrs::Pre_v4: 505 case ARMBuildAttrs::v4: 506 case ARMBuildAttrs::v4T: 507 // Architectures prior to v5 do not support BLX instruction 508 break; 509 case ARMBuildAttrs::v5T: 510 case ARMBuildAttrs::v5TE: 511 case ARMBuildAttrs::v5TEJ: 512 case ARMBuildAttrs::v6: 513 case ARMBuildAttrs::v6KZ: 514 case ARMBuildAttrs::v6K: 515 Config->ARMHasBlx = true; 516 // Architectures used in pre-Cortex processors do not support 517 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception 518 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do. 519 break; 520 default: 521 // All other Architectures have BLX and extended branch encoding 522 Config->ARMHasBlx = true; 523 Config->ARMJ1J2BranchEncoding = true; 524 if (Arch != ARMBuildAttrs::v6_M && Arch != ARMBuildAttrs::v6S_M) 525 // All Architectures used in Cortex processors with the exception 526 // of v6-M and v6S-M have the MOVT and MOVW instructions. 527 Config->ARMHasMovtMovw = true; 528 break; 529 } 530 } 531 532 template <class ELFT> 533 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) { 534 uint32_t Idx = Sec.sh_info; 535 if (Idx >= this->Sections.size()) 536 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx)); 537 InputSectionBase *Target = this->Sections[Idx]; 538 539 // Strictly speaking, a relocation section must be included in the 540 // group of the section it relocates. However, LLVM 3.3 and earlier 541 // would fail to do so, so we gracefully handle that case. 542 if (Target == &InputSection::Discarded) 543 return nullptr; 544 545 if (!Target) 546 fatal(toString(this) + ": unsupported relocation reference"); 547 return Target; 548 } 549 550 // Create a regular InputSection class that has the same contents 551 // as a given section. 552 static InputSection *toRegularSection(MergeInputSection *Sec) { 553 return make<InputSection>(Sec->File, Sec->Flags, Sec->Type, Sec->Alignment, 554 Sec->Data, Sec->Name); 555 } 556 557 template <class ELFT> 558 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) { 559 StringRef Name = getSectionName(Sec); 560 561 switch (Sec.sh_type) { 562 case SHT_ARM_ATTRIBUTES: { 563 if (Config->EMachine != EM_ARM) 564 break; 565 ARMAttributeParser Attributes; 566 ArrayRef<uint8_t> Contents = check(this->getObj().getSectionContents(&Sec)); 567 Attributes.Parse(Contents, /*isLittle*/ Config->EKind == ELF32LEKind); 568 updateSupportedARMFeatures(Attributes); 569 // FIXME: Retain the first attribute section we see. The eglibc ARM 570 // dynamic loaders require the presence of an attribute section for dlopen 571 // to work. In a full implementation we would merge all attribute sections. 572 if (InX::ARMAttributes == nullptr) { 573 InX::ARMAttributes = make<InputSection>(*this, Sec, Name); 574 return InX::ARMAttributes; 575 } 576 return &InputSection::Discarded; 577 } 578 case SHT_RELA: 579 case SHT_REL: { 580 // Find a relocation target section and associate this section with that. 581 // Target may have been discarded if it is in a different section group 582 // and the group is discarded, even though it's a violation of the 583 // spec. We handle that situation gracefully by discarding dangling 584 // relocation sections. 585 InputSectionBase *Target = getRelocTarget(Sec); 586 if (!Target) 587 return nullptr; 588 589 // This section contains relocation information. 590 // If -r is given, we do not interpret or apply relocation 591 // but just copy relocation sections to output. 592 if (Config->Relocatable) 593 return make<InputSection>(*this, Sec, Name); 594 595 if (Target->FirstRelocation) 596 fatal(toString(this) + 597 ": multiple relocation sections to one section are not supported"); 598 599 // ELF spec allows mergeable sections with relocations, but they are 600 // rare, and it is in practice hard to merge such sections by contents, 601 // because applying relocations at end of linking changes section 602 // contents. So, we simply handle such sections as non-mergeable ones. 603 // Degrading like this is acceptable because section merging is optional. 604 if (auto *MS = dyn_cast<MergeInputSection>(Target)) { 605 Target = toRegularSection(MS); 606 this->Sections[Sec.sh_info] = Target; 607 } 608 609 if (Sec.sh_type == SHT_RELA) { 610 ArrayRef<Elf_Rela> Rels = CHECK(this->getObj().relas(&Sec), this); 611 Target->FirstRelocation = Rels.begin(); 612 Target->NumRelocations = Rels.size(); 613 Target->AreRelocsRela = true; 614 } else { 615 ArrayRef<Elf_Rel> Rels = CHECK(this->getObj().rels(&Sec), this); 616 Target->FirstRelocation = Rels.begin(); 617 Target->NumRelocations = Rels.size(); 618 Target->AreRelocsRela = false; 619 } 620 assert(isUInt<31>(Target->NumRelocations)); 621 622 // Relocation sections processed by the linker are usually removed 623 // from the output, so returning `nullptr` for the normal case. 624 // However, if -emit-relocs is given, we need to leave them in the output. 625 // (Some post link analysis tools need this information.) 626 if (Config->EmitRelocs) { 627 InputSection *RelocSec = make<InputSection>(*this, Sec, Name); 628 // We will not emit relocation section if target was discarded. 629 Target->DependentSections.push_back(RelocSec); 630 return RelocSec; 631 } 632 return nullptr; 633 } 634 } 635 636 // The GNU linker uses .note.GNU-stack section as a marker indicating 637 // that the code in the object file does not expect that the stack is 638 // executable (in terms of NX bit). If all input files have the marker, 639 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to 640 // make the stack non-executable. Most object files have this section as 641 // of 2017. 642 // 643 // But making the stack non-executable is a norm today for security 644 // reasons. Failure to do so may result in a serious security issue. 645 // Therefore, we make LLD always add PT_GNU_STACK unless it is 646 // explicitly told to do otherwise (by -z execstack). Because the stack 647 // executable-ness is controlled solely by command line options, 648 // .note.GNU-stack sections are simply ignored. 649 if (Name == ".note.GNU-stack") 650 return &InputSection::Discarded; 651 652 // Split stacks is a feature to support a discontiguous stack. At least 653 // as of 2017, it seems that the feature is not being used widely. 654 // Only GNU gold supports that. We don't. For the details about that, 655 // see https://gcc.gnu.org/wiki/SplitStacks 656 if (Name == ".note.GNU-split-stack") { 657 error(toString(this) + 658 ": object file compiled with -fsplit-stack is not supported"); 659 return &InputSection::Discarded; 660 } 661 662 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object 663 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce 664 // sections. Drop those sections to avoid duplicate symbol errors. 665 // FIXME: This is glibc PR20543, we should remove this hack once that has been 666 // fixed for a while. 667 if (Name.startswith(".gnu.linkonce.")) 668 return &InputSection::Discarded; 669 670 // If we are creating a new .build-id section, strip existing .build-id 671 // sections so that the output won't have more than one .build-id. 672 // This is not usually a problem because input object files normally don't 673 // have .build-id sections, but you can create such files by 674 // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it. 675 if (Name == ".note.gnu.build-id" && Config->BuildId != BuildIdKind::None) 676 return &InputSection::Discarded; 677 678 // The linker merges EH (exception handling) frames and creates a 679 // .eh_frame_hdr section for runtime. So we handle them with a special 680 // class. For relocatable outputs, they are just passed through. 681 if (Name == ".eh_frame" && !Config->Relocatable) 682 return make<EhInputSection>(*this, Sec, Name); 683 684 if (shouldMerge(Sec)) 685 return make<MergeInputSection>(*this, Sec, Name); 686 return make<InputSection>(*this, Sec, Name); 687 } 688 689 template <class ELFT> 690 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) { 691 return CHECK(this->getObj().getSectionName(&Sec, SectionStringTable), this); 692 } 693 694 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() { 695 this->Symbols.reserve(this->ELFSyms.size()); 696 for (const Elf_Sym &Sym : this->ELFSyms) 697 this->Symbols.push_back(createSymbol(&Sym)); 698 } 699 700 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) { 701 int Binding = Sym->getBinding(); 702 703 uint32_t SecIdx = this->getSectionIndex(*Sym); 704 if (SecIdx >= this->Sections.size()) 705 fatal(toString(this) + ": invalid section index: " + Twine(SecIdx)); 706 707 InputSectionBase *Sec = this->Sections[SecIdx]; 708 uint8_t StOther = Sym->st_other; 709 uint8_t Type = Sym->getType(); 710 uint64_t Value = Sym->st_value; 711 uint64_t Size = Sym->st_size; 712 713 if (Binding == STB_LOCAL) { 714 if (Sym->getType() == STT_FILE) 715 SourceFile = CHECK(Sym->getName(this->StringTable), this); 716 717 if (this->StringTable.size() <= Sym->st_name) 718 fatal(toString(this) + ": invalid symbol name offset"); 719 720 StringRefZ Name = this->StringTable.data() + Sym->st_name; 721 if (Sym->st_shndx == SHN_UNDEF) 722 return make<Undefined>(this, Name, Binding, StOther, Type); 723 724 return make<Defined>(this, Name, Binding, StOther, Type, Value, Size, Sec); 725 } 726 727 StringRef Name = CHECK(Sym->getName(this->StringTable), this); 728 729 switch (Sym->st_shndx) { 730 case SHN_UNDEF: 731 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type, 732 /*CanOmitFromDynSym=*/false, this); 733 case SHN_COMMON: 734 if (Value == 0 || Value >= UINT32_MAX) 735 fatal(toString(this) + ": common symbol '" + Name + 736 "' has invalid alignment: " + Twine(Value)); 737 return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, *this); 738 } 739 740 switch (Binding) { 741 default: 742 fatal(toString(this) + ": unexpected binding: " + Twine(Binding)); 743 case STB_GLOBAL: 744 case STB_WEAK: 745 case STB_GNU_UNIQUE: 746 if (Sec == &InputSection::Discarded) 747 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type, 748 /*CanOmitFromDynSym=*/false, this); 749 return Symtab->addRegular(Name, StOther, Type, Value, Size, Binding, Sec, 750 this); 751 } 752 } 753 754 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File) 755 : InputFile(ArchiveKind, File->getMemoryBufferRef()), 756 File(std::move(File)) {} 757 758 template <class ELFT> void ArchiveFile::parse() { 759 for (const Archive::Symbol &Sym : File->symbols()) 760 Symtab->addLazyArchive<ELFT>(Sym.getName(), *this, Sym); 761 } 762 763 // Returns a buffer pointing to a member file containing a given symbol. 764 InputFile *ArchiveFile::fetch(const Archive::Symbol &Sym) { 765 Archive::Child C = 766 CHECK(Sym.getMember(), toString(this) + 767 ": could not get the member for symbol " + 768 Sym.getName()); 769 770 if (!Seen.insert(C.getChildOffset()).second) 771 return nullptr; 772 773 MemoryBufferRef MB = 774 CHECK(C.getMemoryBufferRef(), 775 toString(this) + 776 ": could not get the buffer for the member defining symbol " + 777 Sym.getName()); 778 779 if (Tar && C.getParent()->isThin()) 780 Tar->append(relativeToRoot(CHECK(C.getFullName(), this)), MB.getBuffer()); 781 782 InputFile *File = createObjectFile( 783 MB, getName(), C.getParent()->isThin() ? 0 : C.getChildOffset()); 784 File->GroupId = GroupId; 785 return File; 786 } 787 788 template <class ELFT> 789 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName) 790 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName), 791 IsNeeded(!Config->AsNeeded) {} 792 793 // Partially parse the shared object file so that we can call 794 // getSoName on this object. 795 template <class ELFT> void SharedFile<ELFT>::parseSoName() { 796 const Elf_Shdr *DynamicSec = nullptr; 797 const ELFFile<ELFT> Obj = this->getObj(); 798 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this); 799 800 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d. 801 for (const Elf_Shdr &Sec : Sections) { 802 switch (Sec.sh_type) { 803 default: 804 continue; 805 case SHT_DYNSYM: 806 this->initSymtab(Sections, &Sec); 807 break; 808 case SHT_DYNAMIC: 809 DynamicSec = &Sec; 810 break; 811 case SHT_SYMTAB_SHNDX: 812 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, Sections), this); 813 break; 814 case SHT_GNU_versym: 815 this->VersymSec = &Sec; 816 break; 817 case SHT_GNU_verdef: 818 this->VerdefSec = &Sec; 819 break; 820 } 821 } 822 823 if (this->VersymSec && this->ELFSyms.empty()) 824 error("SHT_GNU_versym should be associated with symbol table"); 825 826 // Search for a DT_SONAME tag to initialize this->SoName. 827 if (!DynamicSec) 828 return; 829 ArrayRef<Elf_Dyn> Arr = 830 CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), this); 831 for (const Elf_Dyn &Dyn : Arr) { 832 if (Dyn.d_tag == DT_SONAME) { 833 uint64_t Val = Dyn.getVal(); 834 if (Val >= this->StringTable.size()) 835 fatal(toString(this) + ": invalid DT_SONAME entry"); 836 SoName = this->StringTable.data() + Val; 837 return; 838 } 839 } 840 } 841 842 // Parses ".gnu.version" section which is a parallel array for the symbol table. 843 // If a given file doesn't have ".gnu.version" section, returns VER_NDX_GLOBAL. 844 template <class ELFT> std::vector<uint32_t> SharedFile<ELFT>::parseVersyms() { 845 size_t Size = this->ELFSyms.size() - this->FirstGlobal; 846 if (!VersymSec) 847 return std::vector<uint32_t>(Size, VER_NDX_GLOBAL); 848 849 const char *Base = this->MB.getBuffer().data(); 850 const Elf_Versym *Versym = 851 reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) + 852 this->FirstGlobal; 853 854 std::vector<uint32_t> Ret(Size); 855 for (size_t I = 0; I < Size; ++I) 856 Ret[I] = Versym[I].vs_index; 857 return Ret; 858 } 859 860 // Parse the version definitions in the object file if present. Returns a vector 861 // whose nth element contains a pointer to the Elf_Verdef for version identifier 862 // n. Version identifiers that are not definitions map to nullptr. 863 template <class ELFT> 864 std::vector<const typename ELFT::Verdef *> SharedFile<ELFT>::parseVerdefs() { 865 if (!VerdefSec) 866 return {}; 867 868 // We cannot determine the largest verdef identifier without inspecting 869 // every Elf_Verdef, but both bfd and gold assign verdef identifiers 870 // sequentially starting from 1, so we predict that the largest identifier 871 // will be VerdefCount. 872 unsigned VerdefCount = VerdefSec->sh_info; 873 std::vector<const Elf_Verdef *> Verdefs(VerdefCount + 1); 874 875 // Build the Verdefs array by following the chain of Elf_Verdef objects 876 // from the start of the .gnu.version_d section. 877 const char *Base = this->MB.getBuffer().data(); 878 const char *Verdef = Base + VerdefSec->sh_offset; 879 for (unsigned I = 0; I != VerdefCount; ++I) { 880 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef); 881 Verdef += CurVerdef->vd_next; 882 unsigned VerdefIndex = CurVerdef->vd_ndx; 883 if (Verdefs.size() <= VerdefIndex) 884 Verdefs.resize(VerdefIndex + 1); 885 Verdefs[VerdefIndex] = CurVerdef; 886 } 887 888 return Verdefs; 889 } 890 891 // We do not usually care about alignments of data in shared object 892 // files because the loader takes care of it. However, if we promote a 893 // DSO symbol to point to .bss due to copy relocation, we need to keep 894 // the original alignment requirements. We infer it in this function. 895 template <class ELFT> 896 uint32_t SharedFile<ELFT>::getAlignment(ArrayRef<Elf_Shdr> Sections, 897 const Elf_Sym &Sym) { 898 uint64_t Ret = 1; 899 if (Sym.st_value) 900 Ret = 1ULL << countTrailingZeros((uint64_t)Sym.st_value); 901 if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) 902 Ret = std::min<uint64_t>(Ret, Sections[Sym.st_shndx].sh_addralign); 903 904 if (Ret > UINT32_MAX) 905 error(toString(this) + ": alignment too large: " + 906 CHECK(Sym.getName(this->StringTable), this)); 907 return Ret; 908 } 909 910 // Fully parse the shared object file. This must be called after parseSoName(). 911 // 912 // This function parses symbol versions. If a DSO has version information, 913 // the file has a ".gnu.version_d" section which contains symbol version 914 // definitions. Each symbol is associated to one version through a table in 915 // ".gnu.version" section. That table is a parallel array for the symbol 916 // table, and each table entry contains an index in ".gnu.version_d". 917 // 918 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for 919 // VER_NDX_GLOBAL. There's no table entry for these special versions in 920 // ".gnu.version_d". 921 // 922 // The file format for symbol versioning is perhaps a bit more complicated 923 // than necessary, but you can easily understand the code if you wrap your 924 // head around the data structure described above. 925 template <class ELFT> void SharedFile<ELFT>::parseRest() { 926 Verdefs = parseVerdefs(); // parse .gnu.version_d 927 std::vector<uint32_t> Versyms = parseVersyms(); // parse .gnu.version 928 ArrayRef<Elf_Shdr> Sections = CHECK(this->getObj().sections(), this); 929 930 // System libraries can have a lot of symbols with versions. Using a 931 // fixed buffer for computing the versions name (foo@ver) can save a 932 // lot of allocations. 933 SmallString<0> VersionedNameBuffer; 934 935 // Add symbols to the symbol table. 936 ArrayRef<Elf_Sym> Syms = this->getGlobalELFSyms(); 937 for (size_t I = 0; I < Syms.size(); ++I) { 938 const Elf_Sym &Sym = Syms[I]; 939 940 StringRef Name = CHECK(Sym.getName(this->StringTable), this); 941 if (Sym.isUndefined()) { 942 Symbol *S = Symtab->addUndefined<ELFT>(Name, Sym.getBinding(), 943 Sym.st_other, Sym.getType(), 944 /*CanOmitFromDynSym=*/false, this); 945 S->ExportDynamic = true; 946 continue; 947 } 948 949 // ELF spec requires that all local symbols precede weak or global 950 // symbols in each symbol table, and the index of first non-local symbol 951 // is stored to sh_info. If a local symbol appears after some non-local 952 // symbol, that's a violation of the spec. 953 if (Sym.getBinding() == STB_LOCAL) { 954 warn("found local symbol '" + Name + 955 "' in global part of symbol table in file " + toString(this)); 956 continue; 957 } 958 959 // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly 960 // assigns VER_NDX_LOCAL to this section global symbol. Here is a 961 // workaround for this bug. 962 uint32_t Idx = Versyms[I] & ~VERSYM_HIDDEN; 963 if (Config->EMachine == EM_MIPS && Idx == VER_NDX_LOCAL && 964 Name == "_gp_disp") 965 continue; 966 967 uint64_t Alignment = getAlignment(Sections, Sym); 968 if (!(Versyms[I] & VERSYM_HIDDEN)) 969 Symtab->addShared(Name, *this, Sym, Alignment, Idx); 970 971 // Also add the symbol with the versioned name to handle undefined symbols 972 // with explicit versions. 973 if (Idx == VER_NDX_GLOBAL) 974 continue; 975 976 if (Idx >= Verdefs.size() || Idx == VER_NDX_LOCAL) { 977 error("corrupt input file: version definition index " + Twine(Idx) + 978 " for symbol " + Name + " is out of bounds\n>>> defined in " + 979 toString(this)); 980 continue; 981 } 982 983 StringRef VerName = 984 this->StringTable.data() + Verdefs[Idx]->getAux()->vda_name; 985 VersionedNameBuffer.clear(); 986 Name = (Name + "@" + VerName).toStringRef(VersionedNameBuffer); 987 Symtab->addShared(Saver.save(Name), *this, Sym, Alignment, Idx); 988 } 989 } 990 991 static ELFKind getBitcodeELFKind(const Triple &T) { 992 if (T.isLittleEndian()) 993 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind; 994 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind; 995 } 996 997 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) { 998 switch (T.getArch()) { 999 case Triple::aarch64: 1000 return EM_AARCH64; 1001 case Triple::arm: 1002 case Triple::thumb: 1003 return EM_ARM; 1004 case Triple::avr: 1005 return EM_AVR; 1006 case Triple::mips: 1007 case Triple::mipsel: 1008 case Triple::mips64: 1009 case Triple::mips64el: 1010 return EM_MIPS; 1011 case Triple::ppc: 1012 return EM_PPC; 1013 case Triple::ppc64: 1014 return EM_PPC64; 1015 case Triple::x86: 1016 return T.isOSIAMCU() ? EM_IAMCU : EM_386; 1017 case Triple::x86_64: 1018 return EM_X86_64; 1019 default: 1020 error(Path + ": could not infer e_machine from bitcode target triple " + 1021 T.str()); 1022 return EM_NONE; 1023 } 1024 } 1025 1026 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName, 1027 uint64_t OffsetInArchive) 1028 : InputFile(BitcodeKind, MB) { 1029 this->ArchiveName = ArchiveName; 1030 1031 std::string Path = MB.getBufferIdentifier().str(); 1032 if (Config->ThinLTOIndexOnly) 1033 Path = replaceThinLTOSuffix(MB.getBufferIdentifier()); 1034 1035 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 1036 // name. If two archives define two members with the same name, this 1037 // causes a collision which result in only one of the objects being taken 1038 // into consideration at LTO time (which very likely causes undefined 1039 // symbols later in the link stage). So we append file offset to make 1040 // filename unique. 1041 MemoryBufferRef MBRef( 1042 MB.getBuffer(), 1043 Saver.save(ArchiveName + Path + 1044 (ArchiveName.empty() ? "" : utostr(OffsetInArchive)))); 1045 1046 Obj = CHECK(lto::InputFile::create(MBRef), this); 1047 1048 Triple T(Obj->getTargetTriple()); 1049 EKind = getBitcodeELFKind(T); 1050 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T); 1051 } 1052 1053 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) { 1054 switch (GvVisibility) { 1055 case GlobalValue::DefaultVisibility: 1056 return STV_DEFAULT; 1057 case GlobalValue::HiddenVisibility: 1058 return STV_HIDDEN; 1059 case GlobalValue::ProtectedVisibility: 1060 return STV_PROTECTED; 1061 } 1062 llvm_unreachable("unknown visibility"); 1063 } 1064 1065 template <class ELFT> 1066 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats, 1067 const lto::InputFile::Symbol &ObjSym, 1068 BitcodeFile &F) { 1069 StringRef Name = Saver.save(ObjSym.getName()); 1070 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL; 1071 1072 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE; 1073 uint8_t Visibility = mapVisibility(ObjSym.getVisibility()); 1074 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable(); 1075 1076 int C = ObjSym.getComdatIndex(); 1077 if (C != -1 && !KeptComdats[C]) 1078 return Symtab->addUndefined<ELFT>(Name, Binding, Visibility, Type, 1079 CanOmitFromDynSym, &F); 1080 1081 if (ObjSym.isUndefined()) 1082 return Symtab->addUndefined<ELFT>(Name, Binding, Visibility, Type, 1083 CanOmitFromDynSym, &F); 1084 1085 if (ObjSym.isCommon()) 1086 return Symtab->addCommon(Name, ObjSym.getCommonSize(), 1087 ObjSym.getCommonAlignment(), Binding, Visibility, 1088 STT_OBJECT, F); 1089 1090 return Symtab->addBitcode(Name, Binding, Visibility, Type, CanOmitFromDynSym, 1091 F); 1092 } 1093 1094 template <class ELFT> 1095 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) { 1096 std::vector<bool> KeptComdats; 1097 for (StringRef S : Obj->getComdatTable()) 1098 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second); 1099 1100 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) 1101 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, *this)); 1102 } 1103 1104 static ELFKind getELFKind(MemoryBufferRef MB) { 1105 unsigned char Size; 1106 unsigned char Endian; 1107 std::tie(Size, Endian) = getElfArchType(MB.getBuffer()); 1108 1109 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB) 1110 fatal(MB.getBufferIdentifier() + ": invalid data encoding"); 1111 if (Size != ELFCLASS32 && Size != ELFCLASS64) 1112 fatal(MB.getBufferIdentifier() + ": invalid file class"); 1113 1114 size_t BufSize = MB.getBuffer().size(); 1115 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) || 1116 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr))) 1117 fatal(MB.getBufferIdentifier() + ": file is too short"); 1118 1119 if (Size == ELFCLASS32) 1120 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind; 1121 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind; 1122 } 1123 1124 void BinaryFile::parse() { 1125 ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer()); 1126 auto *Section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 1127 8, Data, ".data"); 1128 Sections.push_back(Section); 1129 1130 // For each input file foo that is embedded to a result as a binary 1131 // blob, we define _binary_foo_{start,end,size} symbols, so that 1132 // user programs can access blobs by name. Non-alphanumeric 1133 // characters in a filename are replaced with underscore. 1134 std::string S = "_binary_" + MB.getBufferIdentifier().str(); 1135 for (size_t I = 0; I < S.size(); ++I) 1136 if (!isAlnum(S[I])) 1137 S[I] = '_'; 1138 1139 Symtab->addRegular(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT, 0, 0, 1140 STB_GLOBAL, Section, nullptr); 1141 Symtab->addRegular(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT, 1142 Data.size(), 0, STB_GLOBAL, Section, nullptr); 1143 Symtab->addRegular(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT, 1144 Data.size(), 0, STB_GLOBAL, nullptr, nullptr); 1145 } 1146 1147 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName, 1148 uint64_t OffsetInArchive) { 1149 if (isBitcode(MB)) 1150 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive); 1151 1152 switch (getELFKind(MB)) { 1153 case ELF32LEKind: 1154 return make<ObjFile<ELF32LE>>(MB, ArchiveName); 1155 case ELF32BEKind: 1156 return make<ObjFile<ELF32BE>>(MB, ArchiveName); 1157 case ELF64LEKind: 1158 return make<ObjFile<ELF64LE>>(MB, ArchiveName); 1159 case ELF64BEKind: 1160 return make<ObjFile<ELF64BE>>(MB, ArchiveName); 1161 default: 1162 llvm_unreachable("getELFKind"); 1163 } 1164 } 1165 1166 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) { 1167 switch (getELFKind(MB)) { 1168 case ELF32LEKind: 1169 return make<SharedFile<ELF32LE>>(MB, DefaultSoName); 1170 case ELF32BEKind: 1171 return make<SharedFile<ELF32BE>>(MB, DefaultSoName); 1172 case ELF64LEKind: 1173 return make<SharedFile<ELF64LE>>(MB, DefaultSoName); 1174 case ELF64BEKind: 1175 return make<SharedFile<ELF64BE>>(MB, DefaultSoName); 1176 default: 1177 llvm_unreachable("getELFKind"); 1178 } 1179 } 1180 1181 MemoryBufferRef LazyObjFile::getBuffer() { 1182 if (AddedToLink) 1183 return MemoryBufferRef(); 1184 AddedToLink = true; 1185 return MB; 1186 } 1187 1188 InputFile *LazyObjFile::fetch() { 1189 MemoryBufferRef MBRef = getBuffer(); 1190 if (MBRef.getBuffer().empty()) 1191 return nullptr; 1192 1193 InputFile *File = createObjectFile(MBRef, ArchiveName, OffsetInArchive); 1194 File->GroupId = GroupId; 1195 return File; 1196 } 1197 1198 template <class ELFT> void LazyObjFile::parse() { 1199 // A lazy object file wraps either a bitcode file or an ELF file. 1200 if (isBitcode(this->MB)) { 1201 std::unique_ptr<lto::InputFile> Obj = 1202 CHECK(lto::InputFile::create(this->MB), this); 1203 for (const lto::InputFile::Symbol &Sym : Obj->symbols()) 1204 if (!Sym.isUndefined()) 1205 Symtab->addLazyObject<ELFT>(Saver.save(Sym.getName()), *this); 1206 return; 1207 } 1208 1209 switch (getELFKind(this->MB)) { 1210 case ELF32LEKind: 1211 addElfSymbols<ELF32LE>(); 1212 return; 1213 case ELF32BEKind: 1214 addElfSymbols<ELF32BE>(); 1215 return; 1216 case ELF64LEKind: 1217 addElfSymbols<ELF64LE>(); 1218 return; 1219 case ELF64BEKind: 1220 addElfSymbols<ELF64BE>(); 1221 return; 1222 default: 1223 llvm_unreachable("getELFKind"); 1224 } 1225 } 1226 1227 template <class ELFT> void LazyObjFile::addElfSymbols() { 1228 ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(MB.getBuffer())); 1229 ArrayRef<typename ELFT::Shdr> Sections = CHECK(Obj.sections(), this); 1230 1231 for (const typename ELFT::Shdr &Sec : Sections) { 1232 if (Sec.sh_type != SHT_SYMTAB) 1233 continue; 1234 1235 typename ELFT::SymRange Syms = CHECK(Obj.symbols(&Sec), this); 1236 uint32_t FirstGlobal = Sec.sh_info; 1237 StringRef StringTable = 1238 CHECK(Obj.getStringTableForSymtab(Sec, Sections), this); 1239 1240 for (const typename ELFT::Sym &Sym : Syms.slice(FirstGlobal)) 1241 if (Sym.st_shndx != SHN_UNDEF) 1242 Symtab->addLazyObject<ELFT>(CHECK(Sym.getName(StringTable), this), 1243 *this); 1244 return; 1245 } 1246 } 1247 1248 std::string elf::replaceThinLTOSuffix(StringRef Path) { 1249 StringRef Suffix = Config->ThinLTOObjectSuffixReplace.first; 1250 StringRef Repl = Config->ThinLTOObjectSuffixReplace.second; 1251 1252 if (!Path.endswith(Suffix)) { 1253 error("-thinlto-object-suffix-replace=" + Suffix + ";" + Repl + 1254 " was given, but " + Path + " does not end with the suffix"); 1255 return ""; 1256 } 1257 return (Path.drop_back(Suffix.size()) + Repl).str(); 1258 } 1259 1260 template void ArchiveFile::parse<ELF32LE>(); 1261 template void ArchiveFile::parse<ELF32BE>(); 1262 template void ArchiveFile::parse<ELF64LE>(); 1263 template void ArchiveFile::parse<ELF64BE>(); 1264 1265 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &); 1266 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &); 1267 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &); 1268 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &); 1269 1270 template void LazyObjFile::parse<ELF32LE>(); 1271 template void LazyObjFile::parse<ELF32BE>(); 1272 template void LazyObjFile::parse<ELF64LE>(); 1273 template void LazyObjFile::parse<ELF64BE>(); 1274 1275 template class elf::ELFFileBase<ELF32LE>; 1276 template class elf::ELFFileBase<ELF32BE>; 1277 template class elf::ELFFileBase<ELF64LE>; 1278 template class elf::ELFFileBase<ELF64BE>; 1279 1280 template class elf::ObjFile<ELF32LE>; 1281 template class elf::ObjFile<ELF32BE>; 1282 template class elf::ObjFile<ELF64LE>; 1283 template class elf::ObjFile<ELF64BE>; 1284 1285 template class elf::SharedFile<ELF32LE>; 1286 template class elf::SharedFile<ELF32BE>; 1287 template class elf::SharedFile<ELF64LE>; 1288 template class elf::SharedFile<ELF64BE>; 1289