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