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