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