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