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