InputFiles.cpp revision 293846
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 "Chunks.h" 11#include "Error.h" 12#include "InputFiles.h" 13#include "Symbols.h" 14#include "llvm/ADT/STLExtras.h" 15#include "llvm/IR/LLVMContext.h" 16#include "llvm/LTO/LTOModule.h" 17#include "llvm/Object/COFF.h" 18#include "llvm/Support/COFF.h" 19#include "llvm/Support/Debug.h" 20#include "llvm/Support/Endian.h" 21#include "llvm/Support/raw_ostream.h" 22 23using namespace llvm::COFF; 24using namespace llvm::object; 25using namespace llvm::support::endian; 26using llvm::Triple; 27using llvm::support::ulittle32_t; 28using llvm::sys::fs::file_magic; 29using llvm::sys::fs::identify_magic; 30 31namespace lld { 32namespace coff { 33 34int InputFile::NextIndex = 0; 35 36// Returns the last element of a path, which is supposed to be a filename. 37static StringRef getBasename(StringRef Path) { 38 size_t Pos = Path.find_last_of("\\/"); 39 if (Pos == StringRef::npos) 40 return Path; 41 return Path.substr(Pos + 1); 42} 43 44// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)". 45std::string InputFile::getShortName() { 46 if (ParentName == "") 47 return getName().lower(); 48 std::string Res = (getBasename(ParentName) + "(" + 49 getBasename(getName()) + ")").str(); 50 return StringRef(Res).lower(); 51} 52 53void ArchiveFile::parse() { 54 // Parse a MemoryBufferRef as an archive file. 55 auto ArchiveOrErr = Archive::create(MB); 56 error(ArchiveOrErr, "Failed to parse static library"); 57 File = std::move(*ArchiveOrErr); 58 59 // Allocate a buffer for Lazy objects. 60 size_t NumSyms = File->getNumberOfSymbols(); 61 LazySymbols.reserve(NumSyms); 62 63 // Read the symbol table to construct Lazy objects. 64 for (const Archive::Symbol &Sym : File->symbols()) 65 LazySymbols.emplace_back(this, Sym); 66 67 // Seen is a map from member files to boolean values. Initially 68 // all members are mapped to false, which indicates all these files 69 // are not read yet. 70 for (auto &ChildOrErr : File->children()) { 71 error(ChildOrErr, "Failed to parse static library"); 72 const Archive::Child &Child = *ChildOrErr; 73 Seen[Child.getChildOffset()].clear(); 74 } 75} 76 77// Returns a buffer pointing to a member file containing a given symbol. 78// This function is thread-safe. 79MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) { 80 auto COrErr = Sym->getMember(); 81 error(COrErr, Twine("Could not get the member for symbol ") + Sym->getName()); 82 const Archive::Child &C = *COrErr; 83 84 // Return an empty buffer if we have already returned the same buffer. 85 if (Seen[C.getChildOffset()].test_and_set()) 86 return MemoryBufferRef(); 87 ErrorOr<MemoryBufferRef> Ret = C.getMemoryBufferRef(); 88 error(Ret, Twine("Could not get the buffer for the member defining symbol ") + 89 Sym->getName()); 90 return *Ret; 91} 92 93void ObjectFile::parse() { 94 // Parse a memory buffer as a COFF file. 95 auto BinOrErr = createBinary(MB); 96 error(BinOrErr, "Failed to parse object file"); 97 std::unique_ptr<Binary> Bin = std::move(*BinOrErr); 98 99 if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) { 100 Bin.release(); 101 COFFObj.reset(Obj); 102 } else { 103 error(Twine(getName()) + " is not a COFF file."); 104 } 105 106 // Read section and symbol tables. 107 initializeChunks(); 108 initializeSymbols(); 109 initializeSEH(); 110} 111 112void ObjectFile::initializeChunks() { 113 uint32_t NumSections = COFFObj->getNumberOfSections(); 114 Chunks.reserve(NumSections); 115 SparseChunks.resize(NumSections + 1); 116 for (uint32_t I = 1; I < NumSections + 1; ++I) { 117 const coff_section *Sec; 118 StringRef Name; 119 std::error_code EC = COFFObj->getSection(I, Sec); 120 error(EC, Twine("getSection failed: #") + Twine(I)); 121 EC = COFFObj->getSectionName(Sec, Name); 122 error(EC, Twine("getSectionName failed: #") + Twine(I)); 123 if (Name == ".sxdata") { 124 SXData = Sec; 125 continue; 126 } 127 if (Name == ".drectve") { 128 ArrayRef<uint8_t> Data; 129 COFFObj->getSectionContents(Sec, Data); 130 Directives = std::string((const char *)Data.data(), Data.size()); 131 continue; 132 } 133 // Skip non-DWARF debug info. MSVC linker converts the sections into 134 // a PDB file, but we don't support that. 135 if (Name == ".debug" || Name.startswith(".debug$")) 136 continue; 137 // We want to preserve DWARF debug sections only when /debug is on. 138 if (!Config->Debug && Name.startswith(".debug")) 139 continue; 140 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE) 141 continue; 142 auto *C = new (Alloc) SectionChunk(this, Sec); 143 Chunks.push_back(C); 144 SparseChunks[I] = C; 145 } 146} 147 148void ObjectFile::initializeSymbols() { 149 uint32_t NumSymbols = COFFObj->getNumberOfSymbols(); 150 SymbolBodies.reserve(NumSymbols); 151 SparseSymbolBodies.resize(NumSymbols); 152 llvm::SmallVector<Undefined *, 8> WeakAliases; 153 int32_t LastSectionNumber = 0; 154 for (uint32_t I = 0; I < NumSymbols; ++I) { 155 // Get a COFFSymbolRef object. 156 auto SymOrErr = COFFObj->getSymbol(I); 157 error(SymOrErr, Twine("broken object file: ") + getName()); 158 159 COFFSymbolRef Sym = *SymOrErr; 160 161 const void *AuxP = nullptr; 162 if (Sym.getNumberOfAuxSymbols()) 163 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr(); 164 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber()); 165 166 SymbolBody *Body = nullptr; 167 if (Sym.isUndefined()) { 168 Body = createUndefined(Sym); 169 } else if (Sym.isWeakExternal()) { 170 Body = createWeakExternal(Sym, AuxP); 171 WeakAliases.push_back((Undefined *)Body); 172 } else { 173 Body = createDefined(Sym, AuxP, IsFirst); 174 } 175 if (Body) { 176 SymbolBodies.push_back(Body); 177 SparseSymbolBodies[I] = Body; 178 } 179 I += Sym.getNumberOfAuxSymbols(); 180 LastSectionNumber = Sym.getSectionNumber(); 181 } 182 for (Undefined *U : WeakAliases) 183 U->WeakAlias = SparseSymbolBodies[(uintptr_t)U->WeakAlias]; 184} 185 186Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) { 187 StringRef Name; 188 COFFObj->getSymbolName(Sym, Name); 189 return new (Alloc) Undefined(Name); 190} 191 192Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) { 193 StringRef Name; 194 COFFObj->getSymbolName(Sym, Name); 195 auto *U = new (Alloc) Undefined(Name); 196 auto *Aux = (const coff_aux_weak_external *)AuxP; 197 U->WeakAlias = (Undefined *)(uintptr_t)Aux->TagIndex; 198 return U; 199} 200 201Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP, 202 bool IsFirst) { 203 StringRef Name; 204 if (Sym.isCommon()) { 205 auto *C = new (Alloc) CommonChunk(Sym); 206 Chunks.push_back(C); 207 return new (Alloc) DefinedCommon(this, Sym, C); 208 } 209 if (Sym.isAbsolute()) { 210 COFFObj->getSymbolName(Sym, Name); 211 // Skip special symbols. 212 if (Name == "@comp.id") 213 return nullptr; 214 // COFF spec 5.10.1. The .sxdata section. 215 if (Name == "@feat.00") { 216 if (Sym.getValue() & 1) 217 SEHCompat = true; 218 return nullptr; 219 } 220 return new (Alloc) DefinedAbsolute(Name, Sym); 221 } 222 if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG) 223 return nullptr; 224 225 // Nothing else to do without a section chunk. 226 auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]); 227 if (!SC) 228 return nullptr; 229 230 // Handle section definitions 231 if (IsFirst && AuxP) { 232 auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP); 233 if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE) 234 if (auto *ParentSC = cast_or_null<SectionChunk>( 235 SparseChunks[Aux->getNumber(Sym.isBigObj())])) 236 ParentSC->addAssociative(SC); 237 SC->Checksum = Aux->CheckSum; 238 } 239 240 auto *B = new (Alloc) DefinedRegular(this, Sym, SC); 241 if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP) 242 SC->setSymbol(B); 243 244 return B; 245} 246 247void ObjectFile::initializeSEH() { 248 if (!SEHCompat || !SXData) 249 return; 250 ArrayRef<uint8_t> A; 251 COFFObj->getSectionContents(SXData, A); 252 if (A.size() % 4 != 0) 253 error(".sxdata must be an array of symbol table indices"); 254 auto *I = reinterpret_cast<const ulittle32_t *>(A.data()); 255 auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size()); 256 for (; I != E; ++I) 257 SEHandlers.insert(SparseSymbolBodies[*I]); 258} 259 260MachineTypes ObjectFile::getMachineType() { 261 if (COFFObj) 262 return static_cast<MachineTypes>(COFFObj->getMachine()); 263 return IMAGE_FILE_MACHINE_UNKNOWN; 264} 265 266StringRef ltrim1(StringRef S, const char *Chars) { 267 if (!S.empty() && strchr(Chars, S[0])) 268 return S.substr(1); 269 return S; 270} 271 272void ImportFile::parse() { 273 const char *Buf = MB.getBufferStart(); 274 const char *End = MB.getBufferEnd(); 275 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf); 276 277 // Check if the total size is valid. 278 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) 279 error("broken import library"); 280 281 // Read names and create an __imp_ symbol. 282 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr))); 283 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name); 284 const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1; 285 DLLName = StringRef(NameStart); 286 StringRef ExtName; 287 switch (Hdr->getNameType()) { 288 case IMPORT_ORDINAL: 289 ExtName = ""; 290 break; 291 case IMPORT_NAME: 292 ExtName = Name; 293 break; 294 case IMPORT_NAME_NOPREFIX: 295 ExtName = ltrim1(Name, "?@_"); 296 break; 297 case IMPORT_NAME_UNDECORATE: 298 ExtName = ltrim1(Name, "?@_"); 299 ExtName = ExtName.substr(0, ExtName.find('@')); 300 break; 301 } 302 ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr); 303 SymbolBodies.push_back(ImpSym); 304 305 // If type is function, we need to create a thunk which jump to an 306 // address pointed by the __imp_ symbol. (This allows you to call 307 // DLL functions just like regular non-DLL functions.) 308 if (Hdr->getType() != llvm::COFF::IMPORT_CODE) 309 return; 310 ThunkSym = new (Alloc) DefinedImportThunk(Name, ImpSym, Hdr->Machine); 311 SymbolBodies.push_back(ThunkSym); 312} 313 314void BitcodeFile::parse() { 315 // Usually parse() is thread-safe, but bitcode file is an exception. 316 std::lock_guard<std::mutex> Lock(Mu); 317 318 ErrorOr<std::unique_ptr<LTOModule>> ModOrErr = 319 LTOModule::createFromBuffer(llvm::getGlobalContext(), MB.getBufferStart(), 320 MB.getBufferSize(), llvm::TargetOptions()); 321 error(ModOrErr, "Could not create lto module"); 322 M = std::move(*ModOrErr); 323 324 llvm::StringSaver Saver(Alloc); 325 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) { 326 lto_symbol_attributes Attrs = M->getSymbolAttributes(I); 327 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL) 328 continue; 329 330 StringRef SymName = Saver.save(M->getSymbolName(I)); 331 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK; 332 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) { 333 SymbolBodies.push_back(new (Alloc) Undefined(SymName)); 334 } else { 335 bool Replaceable = 336 (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common 337 (Attrs & LTO_SYMBOL_COMDAT) || // comdat 338 (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK && // weak external 339 (Attrs & LTO_SYMBOL_ALIAS))); 340 SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName, 341 Replaceable)); 342 } 343 } 344 345 Directives = M->getLinkerOpts(); 346} 347 348MachineTypes BitcodeFile::getMachineType() { 349 if (!M) 350 return IMAGE_FILE_MACHINE_UNKNOWN; 351 switch (Triple(M->getTargetTriple()).getArch()) { 352 case Triple::x86_64: 353 return AMD64; 354 case Triple::x86: 355 return I386; 356 case Triple::arm: 357 return ARMNT; 358 default: 359 return IMAGE_FILE_MACHINE_UNKNOWN; 360 } 361} 362 363std::mutex BitcodeFile::Mu; 364 365} // namespace coff 366} // namespace lld 367