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