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