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/LTO/LTOModule.h" 16 #include "llvm/Object/COFF.h" 17 #include "llvm/Support/COFF.h" 18 #include "llvm/Support/Debug.h" 19 #include "llvm/Support/Endian.h" 20 #include "llvm/Support/raw_ostream.h" 21 22 using namespace llvm::COFF; 23 using namespace llvm::object; 24 using namespace llvm::support::endian; 25 using llvm::RoundUpToAlignment; 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 36 // Returns the last element of a path, which is supposed to be a filename. 37 static 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)". 45 std::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 53 void 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 size_t BufSize = NumSyms * sizeof(Lazy); 62 Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>()); 63 LazySymbols.reserve(NumSyms); 64 65 // Read the symbol table to construct Lazy objects. 66 for (const Archive::Symbol &Sym : File->symbols()) 67 LazySymbols.push_back(new (Buf++) Lazy(this, Sym)); 68 69 // Seen is a map from member files to boolean values. Initially 70 // all members are mapped to false, which indicates all these files 71 // are not read yet. 72 for (const Archive::Child &Child : File->children()) 73 Seen[Child.getChildOffset()].clear(); 74 } 75 76 // Returns a buffer pointing to a member file containing a given symbol. 77 // This function is thread-safe. 78 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) { 79 auto ItOrErr = Sym->getMember(); 80 error(ItOrErr, 81 Twine("Could not get the member for symbol ") + Sym->getName()); 82 Archive::child_iterator It = *ItOrErr; 83 84 // Return an empty buffer if we have already returned the same buffer. 85 if (Seen[It->getChildOffset()].test_and_set()) 86 return MemoryBufferRef(); 87 ErrorOr<MemoryBufferRef> Ret = It->getMemoryBufferRef(); 88 error(Ret, Twine("Could not get the buffer for the member defining symbol ") + 89 Sym->getName()); 90 return *Ret; 91 } 92 93 void 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 112 void 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: ") + Name); 121 EC = COFFObj->getSectionName(Sec, Name); 122 error(EC, Twine("getSectionName failed: ") + Name); 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 148 void 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 186 Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) { 187 StringRef Name; 188 COFFObj->getSymbolName(Sym, Name); 189 return new (Alloc) Undefined(Name); 190 } 191 192 Undefined *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 201 Defined *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 associative sections 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 } 238 239 auto *B = new (Alloc) DefinedRegular(this, Sym, SC); 240 if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP) 241 SC->setSymbol(B); 242 243 return B; 244 } 245 246 void ObjectFile::initializeSEH() { 247 if (!SEHCompat || !SXData) 248 return; 249 ArrayRef<uint8_t> A; 250 COFFObj->getSectionContents(SXData, A); 251 if (A.size() % 4 != 0) 252 error(".sxdata must be an array of symbol table indices"); 253 auto *I = reinterpret_cast<const ulittle32_t *>(A.data()); 254 auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size()); 255 for (; I != E; ++I) 256 SEHandlers.insert(SparseSymbolBodies[*I]); 257 } 258 259 MachineTypes ObjectFile::getMachineType() { 260 if (COFFObj) 261 return static_cast<MachineTypes>(COFFObj->getMachine()); 262 return IMAGE_FILE_MACHINE_UNKNOWN; 263 } 264 265 StringRef ltrim1(StringRef S, const char *Chars) { 266 if (!S.empty() && strchr(Chars, S[0])) 267 return S.substr(1); 268 return S; 269 } 270 271 void ImportFile::parse() { 272 const char *Buf = MB.getBufferStart(); 273 const char *End = MB.getBufferEnd(); 274 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf); 275 276 // Check if the total size is valid. 277 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) 278 error("broken import library"); 279 280 // Read names and create an __imp_ symbol. 281 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr))); 282 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name); 283 const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1; 284 DLLName = StringRef(NameStart).lower(); 285 StringRef ExtName; 286 switch (Hdr->getNameType()) { 287 case IMPORT_ORDINAL: 288 ExtName = ""; 289 break; 290 case IMPORT_NAME: 291 ExtName = Name; 292 break; 293 case IMPORT_NAME_NOPREFIX: 294 ExtName = ltrim1(Name, "?@_"); 295 break; 296 case IMPORT_NAME_UNDECORATE: 297 ExtName = ltrim1(Name, "?@_"); 298 ExtName = ExtName.substr(0, ExtName.find('@')); 299 break; 300 } 301 ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr); 302 SymbolBodies.push_back(ImpSym); 303 304 // If type is function, we need to create a thunk which jump to an 305 // address pointed by the __imp_ symbol. (This allows you to call 306 // DLL functions just like regular non-DLL functions.) 307 if (Hdr->getType() != llvm::COFF::IMPORT_CODE) 308 return; 309 ThunkSym = new (Alloc) DefinedImportThunk(Name, ImpSym, Hdr->Machine); 310 SymbolBodies.push_back(ThunkSym); 311 } 312 313 void BitcodeFile::parse() { 314 std::string Err; 315 M.reset(LTOModule::createFromBuffer(MB.getBufferStart(), 316 MB.getBufferSize(), 317 llvm::TargetOptions(), Err)); 318 if (!Err.empty()) 319 error(Err); 320 321 llvm::StringSaver Saver(Alloc); 322 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) { 323 lto_symbol_attributes Attrs = M->getSymbolAttributes(I); 324 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL) 325 continue; 326 327 StringRef SymName = Saver.save(M->getSymbolName(I)); 328 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK; 329 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) { 330 SymbolBodies.push_back(new (Alloc) Undefined(SymName)); 331 } else { 332 bool Replaceable = 333 (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common 334 (Attrs & LTO_SYMBOL_COMDAT) || // comdat 335 (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK && // weak external 336 (Attrs & LTO_SYMBOL_ALIAS))); 337 SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName, 338 Replaceable)); 339 } 340 } 341 342 Directives = M->getLinkerOpts(); 343 } 344 345 MachineTypes BitcodeFile::getMachineType() { 346 if (!M) 347 return IMAGE_FILE_MACHINE_UNKNOWN; 348 switch (Triple(M->getTargetTriple()).getArch()) { 349 case Triple::x86_64: 350 return AMD64; 351 case Triple::x86: 352 return I386; 353 case Triple::arm: 354 return ARMNT; 355 default: 356 return IMAGE_FILE_MACHINE_UNKNOWN; 357 } 358 } 359 360 } // namespace coff 361 } // namespace lld 362