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 // 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 : getShtGroupEntries(Sec)) { 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 if (Sec.sh_link >= this->Sections.size()) 482 fatal(toString(this) + 483 ": invalid sh_link index: " + Twine(Sec.sh_link)); 484 485 InputSectionBase *LinkSec = this->Sections[Sec.sh_link]; 486 InputSection *IS = cast<InputSection>(this->Sections[I]); 487 LinkSec->DependentSections.push_back(IS); 488 if (!isa<InputSection>(LinkSec)) 489 error("a section " + IS->Name + 490 " with SHF_LINK_ORDER should not refer a non-regular " 491 "section: " + 492 toString(LinkSec)); 493 } 494 } 495 } 496 497 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD 498 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how 499 // the input objects have been compiled. 500 static void updateARMVFPArgs(const ARMAttributeParser &Attributes, 501 const InputFile *F) { 502 if (!Attributes.hasAttribute(ARMBuildAttrs::ABI_VFP_args)) 503 // If an ABI tag isn't present then it is implicitly given the value of 0 504 // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files, 505 // including some in glibc that don't use FP args (and should have value 3) 506 // don't have the attribute so we do not consider an implicit value of 0 507 // as a clash. 508 return; 509 510 unsigned VFPArgs = Attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args); 511 ARMVFPArgKind Arg; 512 switch (VFPArgs) { 513 case ARMBuildAttrs::BaseAAPCS: 514 Arg = ARMVFPArgKind::Base; 515 break; 516 case ARMBuildAttrs::HardFPAAPCS: 517 Arg = ARMVFPArgKind::VFP; 518 break; 519 case ARMBuildAttrs::ToolChainFPPCS: 520 // Tool chain specific convention that conforms to neither AAPCS variant. 521 Arg = ARMVFPArgKind::ToolChain; 522 break; 523 case ARMBuildAttrs::CompatibleFPAAPCS: 524 // Object compatible with all conventions. 525 return; 526 default: 527 error(toString(F) + ": unknown Tag_ABI_VFP_args value: " + Twine(VFPArgs)); 528 return; 529 } 530 // Follow ld.bfd and error if there is a mix of calling conventions. 531 if (Config->ARMVFPArgs != Arg && Config->ARMVFPArgs != ARMVFPArgKind::Default) 532 error(toString(F) + ": incompatible Tag_ABI_VFP_args"); 533 else 534 Config->ARMVFPArgs = Arg; 535 } 536 537 // The ARM support in lld makes some use of instructions that are not available 538 // on all ARM architectures. Namely: 539 // - Use of BLX instruction for interworking between ARM and Thumb state. 540 // - Use of the extended Thumb branch encoding in relocation. 541 // - Use of the MOVT/MOVW instructions in Thumb Thunks. 542 // The ARM Attributes section contains information about the architecture chosen 543 // at compile time. We follow the convention that if at least one input object 544 // is compiled with an architecture that supports these features then lld is 545 // permitted to use them. 546 static void updateSupportedARMFeatures(const ARMAttributeParser &Attributes) { 547 if (!Attributes.hasAttribute(ARMBuildAttrs::CPU_arch)) 548 return; 549 auto Arch = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch); 550 switch (Arch) { 551 case ARMBuildAttrs::Pre_v4: 552 case ARMBuildAttrs::v4: 553 case ARMBuildAttrs::v4T: 554 // Architectures prior to v5 do not support BLX instruction 555 break; 556 case ARMBuildAttrs::v5T: 557 case ARMBuildAttrs::v5TE: 558 case ARMBuildAttrs::v5TEJ: 559 case ARMBuildAttrs::v6: 560 case ARMBuildAttrs::v6KZ: 561 case ARMBuildAttrs::v6K: 562 Config->ARMHasBlx = true; 563 // Architectures used in pre-Cortex processors do not support 564 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception 565 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do. 566 break; 567 default: 568 // All other Architectures have BLX and extended branch encoding 569 Config->ARMHasBlx = true; 570 Config->ARMJ1J2BranchEncoding = true; 571 if (Arch != ARMBuildAttrs::v6_M && Arch != ARMBuildAttrs::v6S_M) 572 // All Architectures used in Cortex processors with the exception 573 // of v6-M and v6S-M have the MOVT and MOVW instructions. 574 Config->ARMHasMovtMovw = true; 575 break; 576 } 577 } 578 579 template <class ELFT> 580 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) { 581 uint32_t Idx = Sec.sh_info; 582 if (Idx >= this->Sections.size()) 583 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx)); 584 InputSectionBase *Target = this->Sections[Idx]; 585 586 // Strictly speaking, a relocation section must be included in the 587 // group of the section it relocates. However, LLVM 3.3 and earlier 588 // would fail to do so, so we gracefully handle that case. 589 if (Target == &InputSection::Discarded) 590 return nullptr; 591 592 if (!Target) 593 fatal(toString(this) + ": unsupported relocation reference"); 594 return Target; 595 } 596 597 // Create a regular InputSection class that has the same contents 598 // as a given section. 599 static InputSection *toRegularSection(MergeInputSection *Sec) { 600 return make<InputSection>(Sec->File, Sec->Flags, Sec->Type, Sec->Alignment, 601 Sec->Data, Sec->Name); 602 } 603 604 template <class ELFT> 605 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) { 606 StringRef Name = getSectionName(Sec); 607 608 switch (Sec.sh_type) { 609 case SHT_ARM_ATTRIBUTES: { 610 if (Config->EMachine != EM_ARM) 611 break; 612 ARMAttributeParser Attributes; 613 ArrayRef<uint8_t> Contents = check(this->getObj().getSectionContents(&Sec)); 614 Attributes.Parse(Contents, /*isLittle*/ Config->EKind == ELF32LEKind); 615 updateSupportedARMFeatures(Attributes); 616 updateARMVFPArgs(Attributes, this); 617 618 // FIXME: Retain the first attribute section we see. The eglibc ARM 619 // dynamic loaders require the presence of an attribute section for dlopen 620 // to work. In a full implementation we would merge all attribute sections. 621 if (InX::ARMAttributes == nullptr) { 622 InX::ARMAttributes = make<InputSection>(*this, Sec, Name); 623 return InX::ARMAttributes; 624 } 625 return &InputSection::Discarded; 626 } 627 case SHT_RELA: 628 case SHT_REL: { 629 // Find a relocation target section and associate this section with that. 630 // Target may have been discarded if it is in a different section group 631 // and the group is discarded, even though it's a violation of the 632 // spec. We handle that situation gracefully by discarding dangling 633 // relocation sections. 634 InputSectionBase *Target = getRelocTarget(Sec); 635 if (!Target) 636 return nullptr; 637 638 // This section contains relocation information. 639 // If -r is given, we do not interpret or apply relocation 640 // but just copy relocation sections to output. 641 if (Config->Relocatable) 642 return make<InputSection>(*this, Sec, Name); 643 644 if (Target->FirstRelocation) 645 fatal(toString(this) + 646 ": multiple relocation sections to one section are not supported"); 647 648 // ELF spec allows mergeable sections with relocations, but they are 649 // rare, and it is in practice hard to merge such sections by contents, 650 // because applying relocations at end of linking changes section 651 // contents. So, we simply handle such sections as non-mergeable ones. 652 // Degrading like this is acceptable because section merging is optional. 653 if (auto *MS = dyn_cast<MergeInputSection>(Target)) { 654 Target = toRegularSection(MS); 655 this->Sections[Sec.sh_info] = Target; 656 } 657 658 if (Sec.sh_type == SHT_RELA) { 659 ArrayRef<Elf_Rela> Rels = CHECK(this->getObj().relas(&Sec), this); 660 Target->FirstRelocation = Rels.begin(); 661 Target->NumRelocations = Rels.size(); 662 Target->AreRelocsRela = true; 663 } else { 664 ArrayRef<Elf_Rel> Rels = CHECK(this->getObj().rels(&Sec), this); 665 Target->FirstRelocation = Rels.begin(); 666 Target->NumRelocations = Rels.size(); 667 Target->AreRelocsRela = false; 668 } 669 assert(isUInt<31>(Target->NumRelocations)); 670 671 // Relocation sections processed by the linker are usually removed 672 // from the output, so returning `nullptr` for the normal case. 673 // However, if -emit-relocs is given, we need to leave them in the output. 674 // (Some post link analysis tools need this information.) 675 if (Config->EmitRelocs) { 676 InputSection *RelocSec = make<InputSection>(*this, Sec, Name); 677 // We will not emit relocation section if target was discarded. 678 Target->DependentSections.push_back(RelocSec); 679 return RelocSec; 680 } 681 return nullptr; 682 } 683 } 684 685 // The GNU linker uses .note.GNU-stack section as a marker indicating 686 // that the code in the object file does not expect that the stack is 687 // executable (in terms of NX bit). If all input files have the marker, 688 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to 689 // make the stack non-executable. Most object files have this section as 690 // of 2017. 691 // 692 // But making the stack non-executable is a norm today for security 693 // reasons. Failure to do so may result in a serious security issue. 694 // Therefore, we make LLD always add PT_GNU_STACK unless it is 695 // explicitly told to do otherwise (by -z execstack). Because the stack 696 // executable-ness is controlled solely by command line options, 697 // .note.GNU-stack sections are simply ignored. 698 if (Name == ".note.GNU-stack") 699 return &InputSection::Discarded; 700 701 // Split stacks is a feature to support a discontiguous stack, 702 // commonly used in the programming language Go. For the details, 703 // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled 704 // for split stack will include a .note.GNU-split-stack section. 705 if (Name == ".note.GNU-split-stack") { 706 if (Config->Relocatable) { 707 error("Cannot mix split-stack and non-split-stack in a relocatable link"); 708 return &InputSection::Discarded; 709 } 710 this->SplitStack = true; 711 return &InputSection::Discarded; 712 } 713 714 // An object file cmpiled for split stack, but where some of the 715 // functions were compiled with the no_split_stack_attribute will 716 // include a .note.GNU-no-split-stack section. 717 if (Name == ".note.GNU-no-split-stack") { 718 this->SomeNoSplitStack = true; 719 return &InputSection::Discarded; 720 } 721 722 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object 723 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce 724 // sections. Drop those sections to avoid duplicate symbol errors. 725 // FIXME: This is glibc PR20543, we should remove this hack once that has been 726 // fixed for a while. 727 if (Name.startswith(".gnu.linkonce.")) 728 return &InputSection::Discarded; 729 730 // If we are creating a new .build-id section, strip existing .build-id 731 // sections so that the output won't have more than one .build-id. 732 // This is not usually a problem because input object files normally don't 733 // have .build-id sections, but you can create such files by 734 // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it. 735 if (Name == ".note.gnu.build-id" && Config->BuildId != BuildIdKind::None) 736 return &InputSection::Discarded; 737 738 // The linker merges EH (exception handling) frames and creates a 739 // .eh_frame_hdr section for runtime. So we handle them with a special 740 // class. For relocatable outputs, they are just passed through. 741 if (Name == ".eh_frame" && !Config->Relocatable) 742 return make<EhInputSection>(*this, Sec, Name); 743 744 if (shouldMerge(Sec)) 745 return make<MergeInputSection>(*this, Sec, Name); 746 return make<InputSection>(*this, Sec, Name); 747 } 748 749 template <class ELFT> 750 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) { 751 return CHECK(this->getObj().getSectionName(&Sec, SectionStringTable), this); 752 } 753 754 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() { 755 this->Symbols.reserve(this->ELFSyms.size()); 756 for (const Elf_Sym &Sym : this->ELFSyms) 757 this->Symbols.push_back(createSymbol(&Sym)); 758 } 759 760 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) { 761 int Binding = Sym->getBinding(); 762 763 uint32_t SecIdx = this->getSectionIndex(*Sym); 764 if (SecIdx >= this->Sections.size()) 765 fatal(toString(this) + ": invalid section index: " + Twine(SecIdx)); 766 767 InputSectionBase *Sec = this->Sections[SecIdx]; 768 uint8_t StOther = Sym->st_other; 769 uint8_t Type = Sym->getType(); 770 uint64_t Value = Sym->st_value; 771 uint64_t Size = Sym->st_size; 772 773 if (Binding == STB_LOCAL) { 774 if (Sym->getType() == STT_FILE) 775 SourceFile = CHECK(Sym->getName(this->StringTable), this); 776 777 if (this->StringTable.size() <= Sym->st_name) 778 fatal(toString(this) + ": invalid symbol name offset"); 779 780 StringRefZ Name = this->StringTable.data() + Sym->st_name; 781 if (Sym->st_shndx == SHN_UNDEF) 782 return make<Undefined>(this, Name, Binding, StOther, Type); 783 784 return make<Defined>(this, Name, Binding, StOther, Type, Value, Size, Sec); 785 } 786 787 StringRef Name = CHECK(Sym->getName(this->StringTable), this); 788 789 switch (Sym->st_shndx) { 790 case SHN_UNDEF: 791 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type, 792 /*CanOmitFromDynSym=*/false, this); 793 case SHN_COMMON: 794 if (Value == 0 || Value >= UINT32_MAX) 795 fatal(toString(this) + ": common symbol '" + Name + 796 "' has invalid alignment: " + Twine(Value)); 797 return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, *this); 798 } 799 800 switch (Binding) { 801 default: 802 fatal(toString(this) + ": unexpected binding: " + Twine(Binding)); 803 case STB_GLOBAL: 804 case STB_WEAK: 805 case STB_GNU_UNIQUE: 806 if (Sec == &InputSection::Discarded) 807 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type, 808 /*CanOmitFromDynSym=*/false, this); 809 return Symtab->addRegular(Name, StOther, Type, Value, Size, Binding, Sec, 810 this); 811 } 812 } 813 814 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File) 815 : InputFile(ArchiveKind, File->getMemoryBufferRef()), 816 File(std::move(File)) {} 817 818 template <class ELFT> void ArchiveFile::parse() { 819 for (const Archive::Symbol &Sym : File->symbols()) 820 Symtab->addLazyArchive<ELFT>(Sym.getName(), *this, Sym); 821 } 822 823 // Returns a buffer pointing to a member file containing a given symbol. 824 InputFile *ArchiveFile::fetch(const Archive::Symbol &Sym) { 825 Archive::Child C = 826 CHECK(Sym.getMember(), toString(this) + 827 ": could not get the member for symbol " + 828 Sym.getName()); 829 830 if (!Seen.insert(C.getChildOffset()).second) 831 return nullptr; 832 833 MemoryBufferRef MB = 834 CHECK(C.getMemoryBufferRef(), 835 toString(this) + 836 ": could not get the buffer for the member defining symbol " + 837 Sym.getName()); 838 839 if (Tar && C.getParent()->isThin()) 840 Tar->append(relativeToRoot(CHECK(C.getFullName(), this)), MB.getBuffer()); 841 842 InputFile *File = createObjectFile( 843 MB, getName(), C.getParent()->isThin() ? 0 : C.getChildOffset()); 844 File->GroupId = GroupId; 845 return File; 846 } 847 848 template <class ELFT> 849 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName) 850 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName), 851 IsNeeded(!Config->AsNeeded) {} 852 853 // Partially parse the shared object file so that we can call 854 // getSoName on this object. 855 template <class ELFT> void SharedFile<ELFT>::parseSoName() { 856 const Elf_Shdr *DynamicSec = nullptr; 857 const ELFFile<ELFT> Obj = this->getObj(); 858 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this); 859 860 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d. 861 for (const Elf_Shdr &Sec : Sections) { 862 switch (Sec.sh_type) { 863 default: 864 continue; 865 case SHT_DYNSYM: 866 this->initSymtab(Sections, &Sec); 867 break; 868 case SHT_DYNAMIC: 869 DynamicSec = &Sec; 870 break; 871 case SHT_SYMTAB_SHNDX: 872 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, Sections), this); 873 break; 874 case SHT_GNU_versym: 875 this->VersymSec = &Sec; 876 break; 877 case SHT_GNU_verdef: 878 this->VerdefSec = &Sec; 879 break; 880 } 881 } 882 883 if (this->VersymSec && this->ELFSyms.empty()) 884 error("SHT_GNU_versym should be associated with symbol table"); 885 886 // Search for a DT_SONAME tag to initialize this->SoName. 887 if (!DynamicSec) 888 return; 889 ArrayRef<Elf_Dyn> Arr = 890 CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), this); 891 for (const Elf_Dyn &Dyn : Arr) { 892 if (Dyn.d_tag == DT_SONAME) { 893 uint64_t Val = Dyn.getVal(); 894 if (Val >= this->StringTable.size()) 895 fatal(toString(this) + ": invalid DT_SONAME entry"); 896 SoName = this->StringTable.data() + Val; 897 return; 898 } 899 } 900 } 901 902 // Parses ".gnu.version" section which is a parallel array for the symbol table. 903 // If a given file doesn't have ".gnu.version" section, returns VER_NDX_GLOBAL. 904 template <class ELFT> std::vector<uint32_t> SharedFile<ELFT>::parseVersyms() { 905 size_t Size = this->ELFSyms.size() - this->FirstGlobal; 906 if (!VersymSec) 907 return std::vector<uint32_t>(Size, VER_NDX_GLOBAL); 908 909 const char *Base = this->MB.getBuffer().data(); 910 const Elf_Versym *Versym = 911 reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) + 912 this->FirstGlobal; 913 914 std::vector<uint32_t> Ret(Size); 915 for (size_t I = 0; I < Size; ++I) 916 Ret[I] = Versym[I].vs_index; 917 return Ret; 918 } 919 920 // Parse the version definitions in the object file if present. Returns a vector 921 // whose nth element contains a pointer to the Elf_Verdef for version identifier 922 // n. Version identifiers that are not definitions map to nullptr. 923 template <class ELFT> 924 std::vector<const typename ELFT::Verdef *> SharedFile<ELFT>::parseVerdefs() { 925 if (!VerdefSec) 926 return {}; 927 928 // We cannot determine the largest verdef identifier without inspecting 929 // every Elf_Verdef, but both bfd and gold assign verdef identifiers 930 // sequentially starting from 1, so we predict that the largest identifier 931 // will be VerdefCount. 932 unsigned VerdefCount = VerdefSec->sh_info; 933 std::vector<const Elf_Verdef *> Verdefs(VerdefCount + 1); 934 935 // Build the Verdefs array by following the chain of Elf_Verdef objects 936 // from the start of the .gnu.version_d section. 937 const char *Base = this->MB.getBuffer().data(); 938 const char *Verdef = Base + VerdefSec->sh_offset; 939 for (unsigned I = 0; I != VerdefCount; ++I) { 940 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef); 941 Verdef += CurVerdef->vd_next; 942 unsigned VerdefIndex = CurVerdef->vd_ndx; 943 Verdefs.resize(VerdefIndex + 1); 944 Verdefs[VerdefIndex] = CurVerdef; 945 } 946 947 return Verdefs; 948 } 949 950 // We do not usually care about alignments of data in shared object 951 // files because the loader takes care of it. However, if we promote a 952 // DSO symbol to point to .bss due to copy relocation, we need to keep 953 // the original alignment requirements. We infer it in this function. 954 template <class ELFT> 955 uint32_t SharedFile<ELFT>::getAlignment(ArrayRef<Elf_Shdr> Sections, 956 const Elf_Sym &Sym) { 957 uint64_t Ret = UINT64_MAX; 958 if (Sym.st_value) 959 Ret = 1ULL << countTrailingZeros((uint64_t)Sym.st_value); 960 if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) 961 Ret = std::min<uint64_t>(Ret, Sections[Sym.st_shndx].sh_addralign); 962 return (Ret > UINT32_MAX) ? 0 : Ret; 963 } 964 965 // Fully parse the shared object file. This must be called after parseSoName(). 966 // 967 // This function parses symbol versions. If a DSO has version information, 968 // the file has a ".gnu.version_d" section which contains symbol version 969 // definitions. Each symbol is associated to one version through a table in 970 // ".gnu.version" section. That table is a parallel array for the symbol 971 // table, and each table entry contains an index in ".gnu.version_d". 972 // 973 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for 974 // VER_NDX_GLOBAL. There's no table entry for these special versions in 975 // ".gnu.version_d". 976 // 977 // The file format for symbol versioning is perhaps a bit more complicated 978 // than necessary, but you can easily understand the code if you wrap your 979 // head around the data structure described above. 980 template <class ELFT> void SharedFile<ELFT>::parseRest() { 981 Verdefs = parseVerdefs(); // parse .gnu.version_d 982 std::vector<uint32_t> Versyms = parseVersyms(); // parse .gnu.version 983 ArrayRef<Elf_Shdr> Sections = CHECK(this->getObj().sections(), this); 984 985 // System libraries can have a lot of symbols with versions. Using a 986 // fixed buffer for computing the versions name (foo@ver) can save a 987 // lot of allocations. 988 SmallString<0> VersionedNameBuffer; 989 990 // Add symbols to the symbol table. 991 ArrayRef<Elf_Sym> Syms = this->getGlobalELFSyms(); 992 for (size_t I = 0; I < Syms.size(); ++I) { 993 const Elf_Sym &Sym = Syms[I]; 994 995 StringRef Name = CHECK(Sym.getName(this->StringTable), this); 996 if (Sym.isUndefined()) { 997 Symbol *S = Symtab->addUndefined<ELFT>(Name, Sym.getBinding(), 998 Sym.st_other, Sym.getType(), 999 /*CanOmitFromDynSym=*/false, this); 1000 S->ExportDynamic = true; 1001 continue; 1002 } 1003 1004 // ELF spec requires that all local symbols precede weak or global 1005 // symbols in each symbol table, and the index of first non-local symbol 1006 // is stored to sh_info. If a local symbol appears after some non-local 1007 // symbol, that's a violation of the spec. 1008 if (Sym.getBinding() == STB_LOCAL) { 1009 warn("found local symbol '" + Name + 1010 "' in global part of symbol table in file " + toString(this)); 1011 continue; 1012 } 1013 1014 // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly 1015 // assigns VER_NDX_LOCAL to this section global symbol. Here is a 1016 // workaround for this bug. 1017 uint32_t Idx = Versyms[I] & ~VERSYM_HIDDEN; 1018 if (Config->EMachine == EM_MIPS && Idx == VER_NDX_LOCAL && 1019 Name == "_gp_disp") 1020 continue; 1021 1022 uint64_t Alignment = getAlignment(Sections, Sym); 1023 if (!(Versyms[I] & VERSYM_HIDDEN)) 1024 Symtab->addShared(Name, *this, Sym, Alignment, Idx); 1025 1026 // Also add the symbol with the versioned name to handle undefined symbols 1027 // with explicit versions. 1028 if (Idx == VER_NDX_GLOBAL) 1029 continue; 1030 1031 if (Idx >= Verdefs.size() || Idx == VER_NDX_LOCAL) { 1032 error("corrupt input file: version definition index " + Twine(Idx) + 1033 " for symbol " + Name + " is out of bounds\n>>> defined in " + 1034 toString(this)); 1035 continue; 1036 } 1037 1038 StringRef VerName = 1039 this->StringTable.data() + Verdefs[Idx]->getAux()->vda_name; 1040 VersionedNameBuffer.clear(); 1041 Name = (Name + "@" + VerName).toStringRef(VersionedNameBuffer); 1042 Symtab->addShared(Saver.save(Name), *this, Sym, Alignment, Idx); 1043 } 1044 } 1045 1046 static ELFKind getBitcodeELFKind(const Triple &T) { 1047 if (T.isLittleEndian()) 1048 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind; 1049 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind; 1050 } 1051 1052 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) { 1053 switch (T.getArch()) { 1054 case Triple::aarch64: 1055 return EM_AARCH64; 1056 case Triple::arm: 1057 case Triple::thumb: 1058 return EM_ARM; 1059 case Triple::avr: 1060 return EM_AVR; 1061 case Triple::mips: 1062 case Triple::mipsel: 1063 case Triple::mips64: 1064 case Triple::mips64el: 1065 return EM_MIPS; 1066 case Triple::ppc: 1067 return EM_PPC; 1068 case Triple::ppc64: 1069 return EM_PPC64; 1070 case Triple::x86: 1071 return T.isOSIAMCU() ? EM_IAMCU : EM_386; 1072 case Triple::x86_64: 1073 return EM_X86_64; 1074 default: 1075 error(Path + ": could not infer e_machine from bitcode target triple " + 1076 T.str()); 1077 return EM_NONE; 1078 } 1079 } 1080 1081 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName, 1082 uint64_t OffsetInArchive) 1083 : InputFile(BitcodeKind, MB) { 1084 this->ArchiveName = ArchiveName; 1085 1086 std::string Path = MB.getBufferIdentifier().str(); 1087 if (Config->ThinLTOIndexOnly) 1088 Path = replaceThinLTOSuffix(MB.getBufferIdentifier()); 1089 1090 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 1091 // name. If two archives define two members with the same name, this 1092 // causes a collision which result in only one of the objects being taken 1093 // into consideration at LTO time (which very likely causes undefined 1094 // symbols later in the link stage). So we append file offset to make 1095 // filename unique. 1096 MemoryBufferRef MBRef( 1097 MB.getBuffer(), 1098 Saver.save(ArchiveName + Path + 1099 (ArchiveName.empty() ? "" : utostr(OffsetInArchive)))); 1100 1101 Obj = CHECK(lto::InputFile::create(MBRef), this); 1102 1103 Triple T(Obj->getTargetTriple()); 1104 EKind = getBitcodeELFKind(T); 1105 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T); 1106 } 1107 1108 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) { 1109 switch (GvVisibility) { 1110 case GlobalValue::DefaultVisibility: 1111 return STV_DEFAULT; 1112 case GlobalValue::HiddenVisibility: 1113 return STV_HIDDEN; 1114 case GlobalValue::ProtectedVisibility: 1115 return STV_PROTECTED; 1116 } 1117 llvm_unreachable("unknown visibility"); 1118 } 1119 1120 template <class ELFT> 1121 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats, 1122 const lto::InputFile::Symbol &ObjSym, 1123 BitcodeFile &F) { 1124 StringRef Name = Saver.save(ObjSym.getName()); 1125 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL; 1126 1127 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE; 1128 uint8_t Visibility = mapVisibility(ObjSym.getVisibility()); 1129 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable(); 1130 1131 int C = ObjSym.getComdatIndex(); 1132 if (C != -1 && !KeptComdats[C]) 1133 return Symtab->addUndefined<ELFT>(Name, Binding, Visibility, Type, 1134 CanOmitFromDynSym, &F); 1135 1136 if (ObjSym.isUndefined()) 1137 return Symtab->addUndefined<ELFT>(Name, Binding, Visibility, Type, 1138 CanOmitFromDynSym, &F); 1139 1140 if (ObjSym.isCommon()) 1141 return Symtab->addCommon(Name, ObjSym.getCommonSize(), 1142 ObjSym.getCommonAlignment(), Binding, Visibility, 1143 STT_OBJECT, F); 1144 1145 return Symtab->addBitcode(Name, Binding, Visibility, Type, CanOmitFromDynSym, 1146 F); 1147 } 1148 1149 template <class ELFT> 1150 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) { 1151 std::vector<bool> KeptComdats; 1152 for (StringRef S : Obj->getComdatTable()) 1153 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second); 1154 1155 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) 1156 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, *this)); 1157 } 1158 1159 static ELFKind getELFKind(MemoryBufferRef MB) { 1160 unsigned char Size; 1161 unsigned char Endian; 1162 std::tie(Size, Endian) = getElfArchType(MB.getBuffer()); 1163 1164 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB) 1165 fatal(MB.getBufferIdentifier() + ": invalid data encoding"); 1166 if (Size != ELFCLASS32 && Size != ELFCLASS64) 1167 fatal(MB.getBufferIdentifier() + ": invalid file class"); 1168 1169 size_t BufSize = MB.getBuffer().size(); 1170 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) || 1171 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr))) 1172 fatal(MB.getBufferIdentifier() + ": file is too short"); 1173 1174 if (Size == ELFCLASS32) 1175 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind; 1176 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind; 1177 } 1178 1179 void BinaryFile::parse() { 1180 ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer()); 1181 auto *Section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 1182 8, Data, ".data"); 1183 Sections.push_back(Section); 1184 1185 // For each input file foo that is embedded to a result as a binary 1186 // blob, we define _binary_foo_{start,end,size} symbols, so that 1187 // user programs can access blobs by name. Non-alphanumeric 1188 // characters in a filename are replaced with underscore. 1189 std::string S = "_binary_" + MB.getBufferIdentifier().str(); 1190 for (size_t I = 0; I < S.size(); ++I) 1191 if (!isAlnum(S[I])) 1192 S[I] = '_'; 1193 1194 Symtab->addRegular(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT, 0, 0, 1195 STB_GLOBAL, Section, nullptr); 1196 Symtab->addRegular(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT, 1197 Data.size(), 0, STB_GLOBAL, Section, nullptr); 1198 Symtab->addRegular(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT, 1199 Data.size(), 0, STB_GLOBAL, nullptr, nullptr); 1200 } 1201 1202 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName, 1203 uint64_t OffsetInArchive) { 1204 if (isBitcode(MB)) 1205 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive); 1206 1207 switch (getELFKind(MB)) { 1208 case ELF32LEKind: 1209 return make<ObjFile<ELF32LE>>(MB, ArchiveName); 1210 case ELF32BEKind: 1211 return make<ObjFile<ELF32BE>>(MB, ArchiveName); 1212 case ELF64LEKind: 1213 return make<ObjFile<ELF64LE>>(MB, ArchiveName); 1214 case ELF64BEKind: 1215 return make<ObjFile<ELF64BE>>(MB, ArchiveName); 1216 default: 1217 llvm_unreachable("getELFKind"); 1218 } 1219 } 1220 1221 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) { 1222 switch (getELFKind(MB)) { 1223 case ELF32LEKind: 1224 return make<SharedFile<ELF32LE>>(MB, DefaultSoName); 1225 case ELF32BEKind: 1226 return make<SharedFile<ELF32BE>>(MB, DefaultSoName); 1227 case ELF64LEKind: 1228 return make<SharedFile<ELF64LE>>(MB, DefaultSoName); 1229 case ELF64BEKind: 1230 return make<SharedFile<ELF64BE>>(MB, DefaultSoName); 1231 default: 1232 llvm_unreachable("getELFKind"); 1233 } 1234 } 1235 1236 MemoryBufferRef LazyObjFile::getBuffer() { 1237 if (AddedToLink) 1238 return MemoryBufferRef(); 1239 AddedToLink = true; 1240 return MB; 1241 } 1242 1243 InputFile *LazyObjFile::fetch() { 1244 MemoryBufferRef MBRef = getBuffer(); 1245 if (MBRef.getBuffer().empty()) 1246 return nullptr; 1247 1248 InputFile *File = createObjectFile(MBRef, ArchiveName, OffsetInArchive); 1249 File->GroupId = GroupId; 1250 return File; 1251 } 1252 1253 template <class ELFT> void LazyObjFile::parse() { 1254 // A lazy object file wraps either a bitcode file or an ELF file. 1255 if (isBitcode(this->MB)) { 1256 std::unique_ptr<lto::InputFile> Obj = 1257 CHECK(lto::InputFile::create(this->MB), this); 1258 for (const lto::InputFile::Symbol &Sym : Obj->symbols()) 1259 if (!Sym.isUndefined()) 1260 Symtab->addLazyObject<ELFT>(Saver.save(Sym.getName()), *this); 1261 return; 1262 } 1263 1264 switch (getELFKind(this->MB)) { 1265 case ELF32LEKind: 1266 addElfSymbols<ELF32LE>(); 1267 return; 1268 case ELF32BEKind: 1269 addElfSymbols<ELF32BE>(); 1270 return; 1271 case ELF64LEKind: 1272 addElfSymbols<ELF64LE>(); 1273 return; 1274 case ELF64BEKind: 1275 addElfSymbols<ELF64BE>(); 1276 return; 1277 default: 1278 llvm_unreachable("getELFKind"); 1279 } 1280 } 1281 1282 template <class ELFT> void LazyObjFile::addElfSymbols() { 1283 ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(MB.getBuffer())); 1284 ArrayRef<typename ELFT::Shdr> Sections = CHECK(Obj.sections(), this); 1285 1286 for (const typename ELFT::Shdr &Sec : Sections) { 1287 if (Sec.sh_type != SHT_SYMTAB) 1288 continue; 1289 1290 typename ELFT::SymRange Syms = CHECK(Obj.symbols(&Sec), this); 1291 uint32_t FirstGlobal = Sec.sh_info; 1292 StringRef StringTable = 1293 CHECK(Obj.getStringTableForSymtab(Sec, Sections), this); 1294 1295 for (const typename ELFT::Sym &Sym : Syms.slice(FirstGlobal)) 1296 if (Sym.st_shndx != SHN_UNDEF) 1297 Symtab->addLazyObject<ELFT>(CHECK(Sym.getName(StringTable), this), 1298 *this); 1299 return; 1300 } 1301 } 1302 1303 std::string elf::replaceThinLTOSuffix(StringRef Path) { 1304 StringRef Suffix = Config->ThinLTOObjectSuffixReplace.first; 1305 StringRef Repl = Config->ThinLTOObjectSuffixReplace.second; 1306 1307 if (!Path.endswith(Suffix)) { 1308 error("-thinlto-object-suffix-replace=" + Suffix + ";" + Repl + 1309 " was given, but " + Path + " does not end with the suffix"); 1310 return ""; 1311 } 1312 return (Path.drop_back(Suffix.size()) + Repl).str(); 1313 } 1314 1315 template void ArchiveFile::parse<ELF32LE>(); 1316 template void ArchiveFile::parse<ELF32BE>(); 1317 template void ArchiveFile::parse<ELF64LE>(); 1318 template void ArchiveFile::parse<ELF64BE>(); 1319 1320 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &); 1321 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &); 1322 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &); 1323 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &); 1324 1325 template void LazyObjFile::parse<ELF32LE>(); 1326 template void LazyObjFile::parse<ELF32BE>(); 1327 template void LazyObjFile::parse<ELF64LE>(); 1328 template void LazyObjFile::parse<ELF64BE>(); 1329 1330 template class elf::ELFFileBase<ELF32LE>; 1331 template class elf::ELFFileBase<ELF32BE>; 1332 template class elf::ELFFileBase<ELF64LE>; 1333 template class elf::ELFFileBase<ELF64BE>; 1334 1335 template class elf::ObjFile<ELF32LE>; 1336 template class elf::ObjFile<ELF32BE>; 1337 template class elf::ObjFile<ELF64LE>; 1338 template class elf::ObjFile<ELF64BE>; 1339 1340 template class elf::SharedFile<ELF32LE>; 1341 template class elf::SharedFile<ELF32BE>; 1342 template class elf::SharedFile<ELF64LE>; 1343 template class elf::SharedFile<ELF64BE>; 1344