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 "Chunks.h" 12 #include "Config.h" 13 #include "Driver.h" 14 #include "SymbolTable.h" 15 #include "Symbols.h" 16 #include "lld/Common/ErrorHandler.h" 17 #include "lld/Common/Memory.h" 18 #include "llvm-c/lto.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/Triple.h" 21 #include "llvm/ADT/Twine.h" 22 #include "llvm/BinaryFormat/COFF.h" 23 #include "llvm/Object/Binary.h" 24 #include "llvm/Object/COFF.h" 25 #include "llvm/Support/Casting.h" 26 #include "llvm/Support/Endian.h" 27 #include "llvm/Support/Error.h" 28 #include "llvm/Support/ErrorOr.h" 29 #include "llvm/Support/FileSystem.h" 30 #include "llvm/Target/TargetOptions.h" 31 #include <cstring> 32 #include <system_error> 33 #include <utility> 34 35 using namespace llvm; 36 using namespace llvm::COFF; 37 using namespace llvm::object; 38 using namespace llvm::support::endian; 39 40 using llvm::Triple; 41 using llvm::support::ulittle32_t; 42 43 namespace lld { 44 namespace coff { 45 46 std::vector<ObjFile *> ObjFile::Instances; 47 std::vector<ImportFile *> ImportFile::Instances; 48 std::vector<BitcodeFile *> BitcodeFile::Instances; 49 50 /// Checks that Source is compatible with being a weak alias to Target. 51 /// If Source is Undefined and has no weak alias set, makes it a weak 52 /// alias to Target. 53 static void checkAndSetWeakAlias(SymbolTable *Symtab, InputFile *F, 54 Symbol *Source, Symbol *Target) { 55 if (auto *U = dyn_cast<Undefined>(Source)) { 56 if (U->WeakAlias && U->WeakAlias != Target) 57 Symtab->reportDuplicate(Source, F); 58 U->WeakAlias = Target; 59 } 60 } 61 62 ArchiveFile::ArchiveFile(MemoryBufferRef M) : InputFile(ArchiveKind, M) {} 63 64 void ArchiveFile::parse() { 65 // Parse a MemoryBufferRef as an archive file. 66 File = CHECK(Archive::create(MB), this); 67 68 // Read the symbol table to construct Lazy objects. 69 for (const Archive::Symbol &Sym : File->symbols()) 70 Symtab->addLazy(this, Sym); 71 } 72 73 // Returns a buffer pointing to a member file containing a given symbol. 74 void ArchiveFile::addMember(const Archive::Symbol *Sym) { 75 const Archive::Child &C = 76 CHECK(Sym->getMember(), 77 "could not get the member for symbol " + Sym->getName()); 78 79 // Return an empty buffer if we have already returned the same buffer. 80 if (!Seen.insert(C.getChildOffset()).second) 81 return; 82 83 Driver->enqueueArchiveMember(C, Sym->getName(), getName()); 84 } 85 86 std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) { 87 std::vector<MemoryBufferRef> V; 88 Error Err = Error::success(); 89 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) { 90 Archive::Child C = 91 CHECK(COrErr, 92 File->getFileName() + ": could not get the child of the archive"); 93 MemoryBufferRef MBRef = 94 CHECK(C.getMemoryBufferRef(), 95 File->getFileName() + 96 ": could not get the buffer for a child of the archive"); 97 V.push_back(MBRef); 98 } 99 if (Err) 100 fatal(File->getFileName() + 101 ": Archive::children failed: " + toString(std::move(Err))); 102 return V; 103 } 104 105 void ObjFile::parse() { 106 // Parse a memory buffer as a COFF file. 107 std::unique_ptr<Binary> Bin = CHECK(createBinary(MB), this); 108 109 if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) { 110 Bin.release(); 111 COFFObj.reset(Obj); 112 } else { 113 fatal(toString(this) + " is not a COFF file"); 114 } 115 116 // Read section and symbol tables. 117 initializeChunks(); 118 initializeSymbols(); 119 } 120 121 // We set SectionChunk pointers in the SparseChunks vector to this value 122 // temporarily to mark comdat sections as having an unknown resolution. As we 123 // walk the object file's symbol table, once we visit either a leader symbol or 124 // an associative section definition together with the parent comdat's leader, 125 // we set the pointer to either nullptr (to mark the section as discarded) or a 126 // valid SectionChunk for that section. 127 static SectionChunk *const PendingComdat = reinterpret_cast<SectionChunk *>(1); 128 129 void ObjFile::initializeChunks() { 130 uint32_t NumSections = COFFObj->getNumberOfSections(); 131 Chunks.reserve(NumSections); 132 SparseChunks.resize(NumSections + 1); 133 for (uint32_t I = 1; I < NumSections + 1; ++I) { 134 const coff_section *Sec; 135 if (auto EC = COFFObj->getSection(I, Sec)) 136 fatal("getSection failed: #" + Twine(I) + ": " + EC.message()); 137 138 if (Sec->Characteristics & IMAGE_SCN_LNK_COMDAT) 139 SparseChunks[I] = PendingComdat; 140 else 141 SparseChunks[I] = readSection(I, nullptr); 142 } 143 } 144 145 SectionChunk *ObjFile::readSection(uint32_t SectionNumber, 146 const coff_aux_section_definition *Def) { 147 const coff_section *Sec; 148 StringRef Name; 149 if (auto EC = COFFObj->getSection(SectionNumber, Sec)) 150 fatal("getSection failed: #" + Twine(SectionNumber) + ": " + EC.message()); 151 if (auto EC = COFFObj->getSectionName(Sec, Name)) 152 fatal("getSectionName failed: #" + Twine(SectionNumber) + ": " + 153 EC.message()); 154 155 if (Name == ".drectve") { 156 ArrayRef<uint8_t> Data; 157 COFFObj->getSectionContents(Sec, Data); 158 Directives = std::string((const char *)Data.data(), Data.size()); 159 return nullptr; 160 } 161 162 // Object files may have DWARF debug info or MS CodeView debug info 163 // (or both). 164 // 165 // DWARF sections don't need any special handling from the perspective 166 // of the linker; they are just a data section containing relocations. 167 // We can just link them to complete debug info. 168 // 169 // CodeView needs a linker support. We need to interpret and debug 170 // info, and then write it to a separate .pdb file. 171 172 // Ignore debug info unless /debug is given. 173 if (!Config->Debug && Name.startswith(".debug")) 174 return nullptr; 175 176 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE) 177 return nullptr; 178 auto *C = make<SectionChunk>(this, Sec); 179 if (Def) 180 C->Checksum = Def->CheckSum; 181 182 // CodeView sections are stored to a different vector because they are not 183 // linked in the regular manner. 184 if (C->isCodeView()) 185 DebugChunks.push_back(C); 186 else if (Config->GuardCF && Name == ".gfids$y") 187 GuardFidChunks.push_back(C); 188 else if (Name == ".sxdata") 189 SXDataChunks.push_back(C); 190 else 191 Chunks.push_back(C); 192 193 return C; 194 } 195 196 void ObjFile::readAssociativeDefinition( 197 COFFSymbolRef Sym, const coff_aux_section_definition *Def) { 198 SectionChunk *Parent = SparseChunks[Def->getNumber(Sym.isBigObj())]; 199 200 // If the parent is pending, it probably means that its section definition 201 // appears after us in the symbol table. Leave the associated section as 202 // pending; we will handle it during the second pass in initializeSymbols(). 203 if (Parent == PendingComdat) 204 return; 205 206 // Check whether the parent is prevailing. If it is, so are we, and we read 207 // the section; otherwise mark it as discarded. 208 int32_t SectionNumber = Sym.getSectionNumber(); 209 if (Parent) { 210 SparseChunks[SectionNumber] = readSection(SectionNumber, Def); 211 if (SparseChunks[SectionNumber]) 212 Parent->addAssociative(SparseChunks[SectionNumber]); 213 } else { 214 SparseChunks[SectionNumber] = nullptr; 215 } 216 } 217 218 Symbol *ObjFile::createRegular(COFFSymbolRef Sym) { 219 SectionChunk *SC = SparseChunks[Sym.getSectionNumber()]; 220 if (Sym.isExternal()) { 221 StringRef Name; 222 COFFObj->getSymbolName(Sym, Name); 223 if (SC) 224 return Symtab->addRegular(this, Name, Sym.getGeneric(), SC); 225 return Symtab->addUndefined(Name, this, false); 226 } 227 if (SC) 228 return make<DefinedRegular>(this, /*Name*/ "", false, 229 /*IsExternal*/ false, Sym.getGeneric(), SC); 230 return nullptr; 231 } 232 233 void ObjFile::initializeSymbols() { 234 uint32_t NumSymbols = COFFObj->getNumberOfSymbols(); 235 Symbols.resize(NumSymbols); 236 237 SmallVector<std::pair<Symbol *, uint32_t>, 8> WeakAliases; 238 std::vector<uint32_t> PendingIndexes; 239 PendingIndexes.reserve(NumSymbols); 240 241 std::vector<const coff_aux_section_definition *> ComdatDefs( 242 COFFObj->getNumberOfSections() + 1); 243 244 for (uint32_t I = 0; I < NumSymbols; ++I) { 245 COFFSymbolRef COFFSym = check(COFFObj->getSymbol(I)); 246 if (COFFSym.isUndefined()) { 247 Symbols[I] = createUndefined(COFFSym); 248 } else if (COFFSym.isWeakExternal()) { 249 Symbols[I] = createUndefined(COFFSym); 250 uint32_t TagIndex = COFFSym.getAux<coff_aux_weak_external>()->TagIndex; 251 WeakAliases.emplace_back(Symbols[I], TagIndex); 252 } else if (Optional<Symbol *> OptSym = createDefined(COFFSym, ComdatDefs)) { 253 Symbols[I] = *OptSym; 254 } else { 255 // createDefined() returns None if a symbol belongs to a section that 256 // was pending at the point when the symbol was read. This can happen in 257 // two cases: 258 // 1) section definition symbol for a comdat leader; 259 // 2) symbol belongs to a comdat section associated with a section whose 260 // section definition symbol appears later in the symbol table. 261 // In both of these cases, we can expect the section to be resolved by 262 // the time we finish visiting the remaining symbols in the symbol 263 // table. So we postpone the handling of this symbol until that time. 264 PendingIndexes.push_back(I); 265 } 266 I += COFFSym.getNumberOfAuxSymbols(); 267 } 268 269 for (uint32_t I : PendingIndexes) { 270 COFFSymbolRef Sym = check(COFFObj->getSymbol(I)); 271 if (auto *Def = Sym.getSectionDefinition()) 272 if (Def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE) 273 readAssociativeDefinition(Sym, Def); 274 Symbols[I] = createRegular(Sym); 275 } 276 277 for (auto &KV : WeakAliases) { 278 Symbol *Sym = KV.first; 279 uint32_t Idx = KV.second; 280 checkAndSetWeakAlias(Symtab, this, Sym, Symbols[Idx]); 281 } 282 } 283 284 Symbol *ObjFile::createUndefined(COFFSymbolRef Sym) { 285 StringRef Name; 286 COFFObj->getSymbolName(Sym, Name); 287 return Symtab->addUndefined(Name, this, Sym.isWeakExternal()); 288 } 289 290 Optional<Symbol *> ObjFile::createDefined( 291 COFFSymbolRef Sym, 292 std::vector<const coff_aux_section_definition *> &ComdatDefs) { 293 StringRef Name; 294 if (Sym.isCommon()) { 295 auto *C = make<CommonChunk>(Sym); 296 Chunks.push_back(C); 297 COFFObj->getSymbolName(Sym, Name); 298 Symbol *S = 299 Symtab->addCommon(this, Name, Sym.getValue(), Sym.getGeneric(), C); 300 return S; 301 } 302 if (Sym.isAbsolute()) { 303 COFFObj->getSymbolName(Sym, Name); 304 // Skip special symbols. 305 if (Name == "@comp.id") 306 return nullptr; 307 if (Name == "@feat.00") { 308 Feat00Flags = Sym.getValue(); 309 return nullptr; 310 } 311 if (Sym.isExternal()) 312 return Symtab->addAbsolute(Name, Sym); 313 else 314 return make<DefinedAbsolute>(Name, Sym); 315 } 316 int32_t SectionNumber = Sym.getSectionNumber(); 317 if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG) 318 return nullptr; 319 320 // Reserved sections numbers don't have contents. 321 if (llvm::COFF::isReservedSectionNumber(SectionNumber)) 322 fatal("broken object file: " + toString(this)); 323 324 // This symbol references a section which is not present in the section 325 // header. 326 if ((uint32_t)SectionNumber >= SparseChunks.size()) 327 fatal("broken object file: " + toString(this)); 328 329 // Handle comdat leader symbols. 330 if (const coff_aux_section_definition *Def = ComdatDefs[SectionNumber]) { 331 ComdatDefs[SectionNumber] = nullptr; 332 Symbol *Leader; 333 bool Prevailing; 334 if (Sym.isExternal()) { 335 COFFObj->getSymbolName(Sym, Name); 336 std::tie(Leader, Prevailing) = 337 Symtab->addComdat(this, Name, Sym.getGeneric()); 338 } else { 339 Leader = make<DefinedRegular>(this, /*Name*/ "", false, 340 /*IsExternal*/ false, Sym.getGeneric()); 341 Prevailing = true; 342 } 343 if (Prevailing) { 344 SectionChunk *C = readSection(SectionNumber, Def); 345 SparseChunks[SectionNumber] = C; 346 C->Sym = cast<DefinedRegular>(Leader); 347 cast<DefinedRegular>(Leader)->Data = &C->Repl; 348 } else { 349 SparseChunks[SectionNumber] = nullptr; 350 } 351 return Leader; 352 } 353 354 // Read associative section definitions and prepare to handle the comdat 355 // leader symbol by setting the section's ComdatDefs pointer if we encounter a 356 // non-associative comdat. 357 if (SparseChunks[SectionNumber] == PendingComdat) { 358 if (auto *Def = Sym.getSectionDefinition()) { 359 if (Def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE) 360 readAssociativeDefinition(Sym, Def); 361 else 362 ComdatDefs[SectionNumber] = Def; 363 } 364 } 365 366 if (SparseChunks[SectionNumber] == PendingComdat) 367 return None; 368 return createRegular(Sym); 369 } 370 371 MachineTypes ObjFile::getMachineType() { 372 if (COFFObj) 373 return static_cast<MachineTypes>(COFFObj->getMachine()); 374 return IMAGE_FILE_MACHINE_UNKNOWN; 375 } 376 377 StringRef ltrim1(StringRef S, const char *Chars) { 378 if (!S.empty() && strchr(Chars, S[0])) 379 return S.substr(1); 380 return S; 381 } 382 383 void ImportFile::parse() { 384 const char *Buf = MB.getBufferStart(); 385 const char *End = MB.getBufferEnd(); 386 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf); 387 388 // Check if the total size is valid. 389 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) 390 fatal("broken import library"); 391 392 // Read names and create an __imp_ symbol. 393 StringRef Name = Saver.save(StringRef(Buf + sizeof(*Hdr))); 394 StringRef ImpName = Saver.save("__imp_" + Name); 395 const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1; 396 DLLName = StringRef(NameStart); 397 StringRef ExtName; 398 switch (Hdr->getNameType()) { 399 case IMPORT_ORDINAL: 400 ExtName = ""; 401 break; 402 case IMPORT_NAME: 403 ExtName = Name; 404 break; 405 case IMPORT_NAME_NOPREFIX: 406 ExtName = ltrim1(Name, "?@_"); 407 break; 408 case IMPORT_NAME_UNDECORATE: 409 ExtName = ltrim1(Name, "?@_"); 410 ExtName = ExtName.substr(0, ExtName.find('@')); 411 break; 412 } 413 414 this->Hdr = Hdr; 415 ExternalName = ExtName; 416 417 ImpSym = Symtab->addImportData(ImpName, this); 418 419 if (Hdr->getType() == llvm::COFF::IMPORT_CONST) 420 static_cast<void>(Symtab->addImportData(Name, this)); 421 422 // If type is function, we need to create a thunk which jump to an 423 // address pointed by the __imp_ symbol. (This allows you to call 424 // DLL functions just like regular non-DLL functions.) 425 if (Hdr->getType() == llvm::COFF::IMPORT_CODE) 426 ThunkSym = Symtab->addImportThunk(Name, ImpSym, Hdr->Machine); 427 } 428 429 void BitcodeFile::parse() { 430 Obj = check(lto::InputFile::create(MemoryBufferRef( 431 MB.getBuffer(), Saver.save(ParentName + MB.getBufferIdentifier())))); 432 std::vector<std::pair<Symbol *, bool>> Comdat(Obj->getComdatTable().size()); 433 for (size_t I = 0; I != Obj->getComdatTable().size(); ++I) 434 Comdat[I] = Symtab->addComdat(this, Saver.save(Obj->getComdatTable()[I])); 435 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) { 436 StringRef SymName = Saver.save(ObjSym.getName()); 437 int ComdatIndex = ObjSym.getComdatIndex(); 438 Symbol *Sym; 439 if (ObjSym.isUndefined()) { 440 Sym = Symtab->addUndefined(SymName, this, false); 441 } else if (ObjSym.isCommon()) { 442 Sym = Symtab->addCommon(this, SymName, ObjSym.getCommonSize()); 443 } else if (ObjSym.isWeak() && ObjSym.isIndirect()) { 444 // Weak external. 445 Sym = Symtab->addUndefined(SymName, this, true); 446 std::string Fallback = ObjSym.getCOFFWeakExternalFallback(); 447 Symbol *Alias = Symtab->addUndefined(Saver.save(Fallback)); 448 checkAndSetWeakAlias(Symtab, this, Sym, Alias); 449 } else if (ComdatIndex != -1) { 450 if (SymName == Obj->getComdatTable()[ComdatIndex]) 451 Sym = Comdat[ComdatIndex].first; 452 else if (Comdat[ComdatIndex].second) 453 Sym = Symtab->addRegular(this, SymName); 454 else 455 Sym = Symtab->addUndefined(SymName, this, false); 456 } else { 457 Sym = Symtab->addRegular(this, SymName); 458 } 459 SymbolBodies.push_back(Sym); 460 } 461 Directives = Obj->getCOFFLinkerOpts(); 462 } 463 464 MachineTypes BitcodeFile::getMachineType() { 465 switch (Triple(Obj->getTargetTriple()).getArch()) { 466 case Triple::x86_64: 467 return AMD64; 468 case Triple::x86: 469 return I386; 470 case Triple::arm: 471 return ARMNT; 472 case Triple::aarch64: 473 return ARM64; 474 default: 475 return IMAGE_FILE_MACHINE_UNKNOWN; 476 } 477 } 478 } // namespace coff 479 } // namespace lld 480 481 // Returns the last element of a path, which is supposed to be a filename. 482 static StringRef getBasename(StringRef Path) { 483 size_t Pos = Path.find_last_of("\\/"); 484 if (Pos == StringRef::npos) 485 return Path; 486 return Path.substr(Pos + 1); 487 } 488 489 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)". 490 std::string lld::toString(const coff::InputFile *File) { 491 if (!File) 492 return "<internal>"; 493 if (File->ParentName.empty()) 494 return File->getName(); 495 496 return (getBasename(File->ParentName) + "(" + getBasename(File->getName()) + 497 ")") 498 .str(); 499 } 500