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