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