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