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 "Error.h" 13 #include "Symbols.h" 14 #include "llvm/ADT/STLExtras.h" 15 16 using namespace llvm; 17 using namespace llvm::ELF; 18 using namespace llvm::object; 19 using namespace llvm::sys::fs; 20 21 using namespace lld; 22 using namespace lld::elf2; 23 24 namespace { 25 class ECRAII { 26 std::error_code EC; 27 28 public: 29 std::error_code &getEC() { return EC; } 30 ~ECRAII() { error(EC); } 31 }; 32 } 33 34 template <class ELFT> 35 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef M) 36 : InputFile(K, M), ELFObj(MB.getBuffer(), ECRAII().getEC()) {} 37 38 template <class ELFT> 39 ELFKind ELFFileBase<ELFT>::getELFKind() { 40 using llvm::support::little; 41 if (ELFT::Is64Bits) 42 return ELFT::TargetEndianness == little ? ELF64LEKind : ELF64BEKind; 43 return ELFT::TargetEndianness == little ? ELF32LEKind : ELF32BEKind; 44 } 45 46 template <class ELFT> 47 typename ELFFileBase<ELFT>::Elf_Sym_Range 48 ELFFileBase<ELFT>::getSymbolsHelper(bool Local) { 49 if (!Symtab) 50 return Elf_Sym_Range(nullptr, nullptr); 51 Elf_Sym_Range Syms = ELFObj.symbols(Symtab); 52 uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end()); 53 uint32_t FirstNonLocal = Symtab->sh_info; 54 if (FirstNonLocal > NumSymbols) 55 error("Invalid sh_info in symbol table"); 56 if (!Local) 57 return make_range(Syms.begin() + FirstNonLocal, Syms.end()); 58 // +1 to skip over dummy symbol. 59 return make_range(Syms.begin() + 1, Syms.begin() + FirstNonLocal); 60 } 61 62 template <class ELFT> 63 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const { 64 uint32_t Index = Sym.st_shndx; 65 if (Index == ELF::SHN_XINDEX) 66 Index = this->ELFObj.getExtendedSymbolTableIndex(&Sym, this->Symtab, 67 SymtabSHNDX); 68 else if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE) 69 return 0; 70 71 if (!Index) 72 error("Invalid section index"); 73 return Index; 74 } 75 76 template <class ELFT> void ELFFileBase<ELFT>::initStringTable() { 77 if (!Symtab) 78 return; 79 ErrorOr<StringRef> StringTableOrErr = ELFObj.getStringTableForSymtab(*Symtab); 80 error(StringTableOrErr.getError()); 81 StringTable = *StringTableOrErr; 82 } 83 84 template <class ELFT> 85 typename ELFFileBase<ELFT>::Elf_Sym_Range 86 ELFFileBase<ELFT>::getNonLocalSymbols() { 87 return getSymbolsHelper(false); 88 } 89 90 template <class ELFT> 91 ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M) 92 : ELFFileBase<ELFT>(Base::ObjectKind, M) {} 93 94 template <class ELFT> 95 typename ObjectFile<ELFT>::Elf_Sym_Range ObjectFile<ELFT>::getLocalSymbols() { 96 return this->getSymbolsHelper(true); 97 } 98 99 template <class ELFT> 100 const typename ObjectFile<ELFT>::Elf_Sym * 101 ObjectFile<ELFT>::getLocalSymbol(uintX_t SymIndex) { 102 uint32_t FirstNonLocal = this->Symtab->sh_info; 103 if (SymIndex >= FirstNonLocal) 104 return nullptr; 105 Elf_Sym_Range Syms = this->ELFObj.symbols(this->Symtab); 106 return Syms.begin() + SymIndex; 107 } 108 109 template <class ELFT> 110 void elf2::ObjectFile<ELFT>::parse(DenseSet<StringRef> &Comdats) { 111 // Read section and symbol tables. 112 initializeSections(Comdats); 113 initializeSymbols(); 114 } 115 116 template <class ELFT> 117 StringRef ObjectFile<ELFT>::getShtGroupSignature(const Elf_Shdr &Sec) { 118 const ELFFile<ELFT> &Obj = this->ELFObj; 119 uint32_t SymtabdSectionIndex = Sec.sh_link; 120 ErrorOr<const Elf_Shdr *> SecOrErr = Obj.getSection(SymtabdSectionIndex); 121 error(SecOrErr); 122 const Elf_Shdr *SymtabSec = *SecOrErr; 123 uint32_t SymIndex = Sec.sh_info; 124 const Elf_Sym *Sym = Obj.getSymbol(SymtabSec, SymIndex); 125 ErrorOr<StringRef> StringTableOrErr = Obj.getStringTableForSymtab(*SymtabSec); 126 error(StringTableOrErr); 127 ErrorOr<StringRef> SignatureOrErr = Sym->getName(*StringTableOrErr); 128 error(SignatureOrErr); 129 return *SignatureOrErr; 130 } 131 132 template <class ELFT> 133 ArrayRef<typename ObjectFile<ELFT>::GroupEntryType> 134 ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) { 135 const ELFFile<ELFT> &Obj = this->ELFObj; 136 ErrorOr<ArrayRef<GroupEntryType>> EntriesOrErr = 137 Obj.template getSectionContentsAsArray<GroupEntryType>(&Sec); 138 error(EntriesOrErr.getError()); 139 ArrayRef<GroupEntryType> Entries = *EntriesOrErr; 140 if (Entries.empty() || Entries[0] != GRP_COMDAT) 141 error("Unsupported SHT_GROUP format"); 142 return Entries.slice(1); 143 } 144 145 template <class ELFT> 146 static bool shouldMerge(const typename ELFFile<ELFT>::Elf_Shdr &Sec) { 147 typedef typename ELFFile<ELFT>::uintX_t uintX_t; 148 uintX_t Flags = Sec.sh_flags; 149 if (!(Flags & SHF_MERGE)) 150 return false; 151 if (Flags & SHF_WRITE) 152 error("Writable SHF_MERGE sections are not supported"); 153 uintX_t EntSize = Sec.sh_entsize; 154 if (!EntSize || Sec.sh_size % EntSize) 155 error("SHF_MERGE section size must be a multiple of sh_entsize"); 156 157 // Don't try to merge if the aligment is larger than the sh_entsize. 158 // 159 // If this is not a SHF_STRINGS, we would need to pad after every entity. It 160 // would be equivalent for the producer of the .o to just set a larger 161 // sh_entsize. 162 // 163 // If this is a SHF_STRINGS, the larger alignment makes sense. Unfortunately 164 // it would complicate tail merging. This doesn't seem that common to 165 // justify the effort. 166 if (Sec.sh_addralign > EntSize) 167 return false; 168 169 return true; 170 } 171 172 template <class ELFT> 173 void elf2::ObjectFile<ELFT>::initializeSections(DenseSet<StringRef> &Comdats) { 174 uint64_t Size = this->ELFObj.getNumSections(); 175 Sections.resize(Size); 176 unsigned I = -1; 177 const ELFFile<ELFT> &Obj = this->ELFObj; 178 for (const Elf_Shdr &Sec : Obj.sections()) { 179 ++I; 180 if (Sections[I] == &InputSection<ELFT>::Discarded) 181 continue; 182 183 switch (Sec.sh_type) { 184 case SHT_GROUP: 185 Sections[I] = &InputSection<ELFT>::Discarded; 186 if (Comdats.insert(getShtGroupSignature(Sec)).second) 187 continue; 188 for (GroupEntryType E : getShtGroupEntries(Sec)) { 189 uint32_t SecIndex = E; 190 if (SecIndex >= Size) 191 error("Invalid section index in group"); 192 Sections[SecIndex] = &InputSection<ELFT>::Discarded; 193 } 194 break; 195 case SHT_SYMTAB: 196 this->Symtab = &Sec; 197 break; 198 case SHT_SYMTAB_SHNDX: { 199 ErrorOr<ArrayRef<Elf_Word>> ErrorOrTable = Obj.getSHNDXTable(Sec); 200 error(ErrorOrTable); 201 this->SymtabSHNDX = *ErrorOrTable; 202 break; 203 } 204 case SHT_STRTAB: 205 case SHT_NULL: 206 break; 207 case SHT_RELA: 208 case SHT_REL: { 209 uint32_t RelocatedSectionIndex = Sec.sh_info; 210 if (RelocatedSectionIndex >= Size) 211 error("Invalid relocated section index"); 212 InputSectionBase<ELFT> *RelocatedSection = 213 Sections[RelocatedSectionIndex]; 214 if (!RelocatedSection) 215 error("Unsupported relocation reference"); 216 if (auto *S = dyn_cast<InputSection<ELFT>>(RelocatedSection)) { 217 S->RelocSections.push_back(&Sec); 218 } else if (auto *S = dyn_cast<EHInputSection<ELFT>>(RelocatedSection)) { 219 if (S->RelocSection) 220 error("Multiple relocation sections to .eh_frame are not supported"); 221 S->RelocSection = &Sec; 222 } else { 223 error("Relocations pointing to SHF_MERGE are not supported"); 224 } 225 break; 226 } 227 default: 228 ErrorOr<StringRef> NameOrErr = this->ELFObj.getSectionName(&Sec); 229 error(NameOrErr); 230 StringRef Name = *NameOrErr; 231 if (Name == ".note.GNU-stack") 232 Sections[I] = &InputSection<ELFT>::Discarded; 233 else if (Name == ".eh_frame") 234 Sections[I] = new (this->Alloc) EHInputSection<ELFT>(this, &Sec); 235 else if (shouldMerge<ELFT>(Sec)) 236 Sections[I] = new (this->Alloc) MergeInputSection<ELFT>(this, &Sec); 237 else 238 Sections[I] = new (this->Alloc) InputSection<ELFT>(this, &Sec); 239 break; 240 } 241 } 242 } 243 244 template <class ELFT> void elf2::ObjectFile<ELFT>::initializeSymbols() { 245 this->initStringTable(); 246 Elf_Sym_Range Syms = this->getNonLocalSymbols(); 247 uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end()); 248 this->SymbolBodies.reserve(NumSymbols); 249 for (const Elf_Sym &Sym : Syms) 250 this->SymbolBodies.push_back(createSymbolBody(this->StringTable, &Sym)); 251 } 252 253 template <class ELFT> 254 InputSectionBase<ELFT> * 255 elf2::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const { 256 uint32_t Index = this->getSectionIndex(Sym); 257 if (Index == 0) 258 return nullptr; 259 if (Index >= Sections.size() || !Sections[Index]) 260 error("Invalid section index"); 261 return Sections[Index]; 262 } 263 264 template <class ELFT> 265 SymbolBody *elf2::ObjectFile<ELFT>::createSymbolBody(StringRef StringTable, 266 const Elf_Sym *Sym) { 267 ErrorOr<StringRef> NameOrErr = Sym->getName(StringTable); 268 error(NameOrErr.getError()); 269 StringRef Name = *NameOrErr; 270 271 switch (Sym->st_shndx) { 272 case SHN_ABS: 273 return new (this->Alloc) DefinedAbsolute<ELFT>(Name, *Sym); 274 case SHN_UNDEF: 275 return new (this->Alloc) Undefined<ELFT>(Name, *Sym); 276 case SHN_COMMON: 277 return new (this->Alloc) DefinedCommon<ELFT>(Name, *Sym); 278 } 279 280 switch (Sym->getBinding()) { 281 default: 282 error("unexpected binding"); 283 case STB_GLOBAL: 284 case STB_WEAK: 285 case STB_GNU_UNIQUE: { 286 InputSectionBase<ELFT> *Sec = getSection(*Sym); 287 if (Sec == &InputSection<ELFT>::Discarded) 288 return new (this->Alloc) Undefined<ELFT>(Name, *Sym); 289 return new (this->Alloc) DefinedRegular<ELFT>(Name, *Sym, *Sec); 290 } 291 } 292 } 293 294 static std::unique_ptr<Archive> openArchive(MemoryBufferRef MB) { 295 ErrorOr<std::unique_ptr<Archive>> ArchiveOrErr = Archive::create(MB); 296 error(ArchiveOrErr, "Failed to parse archive"); 297 return std::move(*ArchiveOrErr); 298 } 299 300 void ArchiveFile::parse() { 301 File = openArchive(MB); 302 303 // Allocate a buffer for Lazy objects. 304 size_t NumSyms = File->getNumberOfSymbols(); 305 LazySymbols.reserve(NumSyms); 306 307 // Read the symbol table to construct Lazy objects. 308 for (const Archive::Symbol &Sym : File->symbols()) 309 LazySymbols.emplace_back(this, Sym); 310 } 311 312 // Returns a buffer pointing to a member file containing a given symbol. 313 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) { 314 ErrorOr<Archive::Child> COrErr = Sym->getMember(); 315 error(COrErr, "Could not get the member for symbol " + Sym->getName()); 316 const Archive::Child &C = *COrErr; 317 318 if (!Seen.insert(C.getChildOffset()).second) 319 return MemoryBufferRef(); 320 321 ErrorOr<MemoryBufferRef> Ret = C.getMemoryBufferRef(); 322 error(Ret, "Could not get the buffer for the member defining symbol " + 323 Sym->getName()); 324 return *Ret; 325 } 326 327 std::vector<MemoryBufferRef> ArchiveFile::getMembers() { 328 File = openArchive(MB); 329 330 std::vector<MemoryBufferRef> Result; 331 for (auto &ChildOrErr : File->children()) { 332 error(ChildOrErr, 333 "Could not get the child of the archive " + File->getFileName()); 334 const Archive::Child Child(*ChildOrErr); 335 ErrorOr<MemoryBufferRef> MbOrErr = Child.getMemoryBufferRef(); 336 error(MbOrErr, "Could not get the buffer for a child of the archive " + 337 File->getFileName()); 338 Result.push_back(MbOrErr.get()); 339 } 340 return Result; 341 } 342 343 template <class ELFT> 344 SharedFile<ELFT>::SharedFile(MemoryBufferRef M) 345 : ELFFileBase<ELFT>(Base::SharedKind, M) { 346 AsNeeded = Config->AsNeeded; 347 } 348 349 template <class ELFT> 350 const typename ELFFile<ELFT>::Elf_Shdr * 351 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const { 352 uint32_t Index = this->getSectionIndex(Sym); 353 if (Index == 0) 354 return nullptr; 355 ErrorOr<const Elf_Shdr *> Ret = this->ELFObj.getSection(Index); 356 error(Ret); 357 return *Ret; 358 } 359 360 template <class ELFT> void SharedFile<ELFT>::parseSoName() { 361 typedef typename ELFFile<ELFT>::Elf_Dyn Elf_Dyn; 362 typedef typename ELFFile<ELFT>::uintX_t uintX_t; 363 const Elf_Shdr *DynamicSec = nullptr; 364 365 const ELFFile<ELFT> Obj = this->ELFObj; 366 for (const Elf_Shdr &Sec : Obj.sections()) { 367 switch (Sec.sh_type) { 368 default: 369 continue; 370 case SHT_DYNSYM: 371 this->Symtab = &Sec; 372 break; 373 case SHT_DYNAMIC: 374 DynamicSec = &Sec; 375 break; 376 case SHT_SYMTAB_SHNDX: { 377 ErrorOr<ArrayRef<Elf_Word>> ErrorOrTable = Obj.getSHNDXTable(Sec); 378 error(ErrorOrTable); 379 this->SymtabSHNDX = *ErrorOrTable; 380 break; 381 } 382 } 383 } 384 385 this->initStringTable(); 386 this->SoName = this->getName(); 387 388 if (!DynamicSec) 389 return; 390 auto *Begin = 391 reinterpret_cast<const Elf_Dyn *>(Obj.base() + DynamicSec->sh_offset); 392 const Elf_Dyn *End = Begin + DynamicSec->sh_size / sizeof(Elf_Dyn); 393 394 for (const Elf_Dyn &Dyn : make_range(Begin, End)) { 395 if (Dyn.d_tag == DT_SONAME) { 396 uintX_t Val = Dyn.getVal(); 397 if (Val >= this->StringTable.size()) 398 error("Invalid DT_SONAME entry"); 399 this->SoName = StringRef(this->StringTable.data() + Val); 400 return; 401 } 402 } 403 } 404 405 template <class ELFT> void SharedFile<ELFT>::parse() { 406 Elf_Sym_Range Syms = this->getNonLocalSymbols(); 407 uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end()); 408 SymbolBodies.reserve(NumSymbols); 409 for (const Elf_Sym &Sym : Syms) { 410 ErrorOr<StringRef> NameOrErr = Sym.getName(this->StringTable); 411 error(NameOrErr.getError()); 412 StringRef Name = *NameOrErr; 413 414 if (Sym.isUndefined()) 415 Undefs.push_back(Name); 416 else 417 SymbolBodies.emplace_back(this, Name, Sym); 418 } 419 } 420 421 template <typename T> 422 static std::unique_ptr<InputFile> createELFFileAux(MemoryBufferRef MB) { 423 std::unique_ptr<T> Ret = llvm::make_unique<T>(MB); 424 425 if (!Config->FirstElf) 426 Config->FirstElf = Ret.get(); 427 428 if (Config->EKind == ELFNoneKind) { 429 Config->EKind = Ret->getELFKind(); 430 Config->EMachine = Ret->getEMachine(); 431 } 432 433 return std::move(Ret); 434 } 435 436 template <template <class> class T> 437 std::unique_ptr<InputFile> lld::elf2::createELFFile(MemoryBufferRef MB) { 438 std::pair<unsigned char, unsigned char> Type = getElfArchType(MB.getBuffer()); 439 if (Type.second != ELF::ELFDATA2LSB && Type.second != ELF::ELFDATA2MSB) 440 error("Invalid data encoding: " + MB.getBufferIdentifier()); 441 442 if (Type.first == ELF::ELFCLASS32) { 443 if (Type.second == ELF::ELFDATA2LSB) 444 return createELFFileAux<T<ELF32LE>>(MB); 445 return createELFFileAux<T<ELF32BE>>(MB); 446 } 447 if (Type.first == ELF::ELFCLASS64) { 448 if (Type.second == ELF::ELFDATA2LSB) 449 return createELFFileAux<T<ELF64LE>>(MB); 450 return createELFFileAux<T<ELF64BE>>(MB); 451 } 452 error("Invalid file class: " + MB.getBufferIdentifier()); 453 } 454 455 template class elf2::ELFFileBase<ELF32LE>; 456 template class elf2::ELFFileBase<ELF32BE>; 457 template class elf2::ELFFileBase<ELF64LE>; 458 template class elf2::ELFFileBase<ELF64BE>; 459 460 template class elf2::ObjectFile<ELF32LE>; 461 template class elf2::ObjectFile<ELF32BE>; 462 template class elf2::ObjectFile<ELF64LE>; 463 template class elf2::ObjectFile<ELF64BE>; 464 465 template class elf2::SharedFile<ELF32LE>; 466 template class elf2::SharedFile<ELF32BE>; 467 template class elf2::SharedFile<ELF64LE>; 468 template class elf2::SharedFile<ELF64BE>; 469 470 template std::unique_ptr<InputFile> 471 elf2::createELFFile<ObjectFile>(MemoryBufferRef); 472 473 template std::unique_ptr<InputFile> 474 elf2::createELFFile<SharedFile>(MemoryBufferRef); 475