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