1 //===- InputFiles.cpp -----------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "InputFiles.h"
16 #include "SymbolTable.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/IR/LLVMContext.h"
23 #include "llvm/LTO/legacy/LTOModule.h"
24 #include "llvm/Object/Binary.h"
25 #include "llvm/Object/COFF.h"
26 #include "llvm/Support/COFF.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/Endian.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/ErrorOr.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Target/TargetOptions.h"
34 #include <system_error>
38 using namespace llvm::COFF;
39 using namespace llvm::object;
40 using namespace llvm::support::endian;
43 using llvm::support::ulittle32_t;
44 using llvm::sys::fs::file_magic;
45 using llvm::sys::fs::identify_magic;
50 LLVMContext BitcodeFile::Context;
52 ArchiveFile::ArchiveFile(MemoryBufferRef M) : InputFile(ArchiveKind, M) {}
54 void ArchiveFile::parse() {
55 // Parse a MemoryBufferRef as an archive file.
56 File = check(Archive::create(MB), toString(this));
58 // Read the symbol table to construct Lazy objects.
59 for (const Archive::Symbol &Sym : File->symbols())
60 Symtab->addLazy(this, Sym);
63 // Returns a buffer pointing to a member file containing a given symbol.
64 void ArchiveFile::addMember(const Archive::Symbol *Sym) {
65 const Archive::Child &C =
66 check(Sym->getMember(),
67 "could not get the member for symbol " + Sym->getName());
69 // Return an empty buffer if we have already returned the same buffer.
70 if (!Seen.insert(C.getChildOffset()).second)
73 Driver->enqueueArchiveMember(C, Sym->getName(), getName());
76 void ObjectFile::parse() {
77 // Parse a memory buffer as a COFF file.
78 std::unique_ptr<Binary> Bin = check(createBinary(MB), toString(this));
80 if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
84 fatal(toString(this) + " is not a COFF file");
87 // Read section and symbol tables.
93 void ObjectFile::initializeChunks() {
94 uint32_t NumSections = COFFObj->getNumberOfSections();
95 Chunks.reserve(NumSections);
96 SparseChunks.resize(NumSections + 1);
97 for (uint32_t I = 1; I < NumSections + 1; ++I) {
98 const coff_section *Sec;
100 if (auto EC = COFFObj->getSection(I, Sec))
101 fatal(EC, "getSection failed: #" + Twine(I));
102 if (auto EC = COFFObj->getSectionName(Sec, Name))
103 fatal(EC, "getSectionName failed: #" + Twine(I));
104 if (Name == ".sxdata") {
108 if (Name == ".drectve") {
109 ArrayRef<uint8_t> Data;
110 COFFObj->getSectionContents(Sec, Data);
111 Directives = std::string((const char *)Data.data(), Data.size());
115 // Object files may have DWARF debug info or MS CodeView debug info
118 // DWARF sections don't need any special handling from the perspective
119 // of the linker; they are just a data section containing relocations.
120 // We can just link them to complete debug info.
122 // CodeView needs a linker support. We need to interpret and debug
123 // info, and then write it to a separate .pdb file.
125 // Ignore debug info unless /debug is given.
126 if (!Config->Debug && Name.startswith(".debug"))
129 // CodeView sections are stored to a different vector because they are
130 // not linked in the regular manner.
131 if (Name == ".debug" || Name.startswith(".debug$")) {
132 DebugChunks.push_back(new (Alloc) SectionChunk(this, Sec));
136 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
138 auto *C = new (Alloc) SectionChunk(this, Sec);
144 void ObjectFile::initializeSymbols() {
145 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
146 SymbolBodies.reserve(NumSymbols);
147 SparseSymbolBodies.resize(NumSymbols);
148 SmallVector<std::pair<SymbolBody *, uint32_t>, 8> WeakAliases;
149 int32_t LastSectionNumber = 0;
150 for (uint32_t I = 0; I < NumSymbols; ++I) {
151 // Get a COFFSymbolRef object.
152 ErrorOr<COFFSymbolRef> SymOrErr = COFFObj->getSymbol(I);
154 fatal(SymOrErr.getError(), "broken object file: " + toString(this));
155 COFFSymbolRef Sym = *SymOrErr;
157 const void *AuxP = nullptr;
158 if (Sym.getNumberOfAuxSymbols())
159 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
160 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
162 SymbolBody *Body = nullptr;
163 if (Sym.isUndefined()) {
164 Body = createUndefined(Sym);
165 } else if (Sym.isWeakExternal()) {
166 Body = createUndefined(Sym);
168 static_cast<const coff_aux_weak_external *>(AuxP)->TagIndex;
169 WeakAliases.emplace_back(Body, TagIndex);
171 Body = createDefined(Sym, AuxP, IsFirst);
174 SymbolBodies.push_back(Body);
175 SparseSymbolBodies[I] = Body;
177 I += Sym.getNumberOfAuxSymbols();
178 LastSectionNumber = Sym.getSectionNumber();
180 for (auto WeakAlias : WeakAliases) {
181 auto *U = dyn_cast<Undefined>(WeakAlias.first);
184 // Report an error if two undefined symbols have different weak aliases.
185 if (U->WeakAlias && U->WeakAlias != SparseSymbolBodies[WeakAlias.second])
186 Symtab->reportDuplicate(U->symbol(), this);
187 U->WeakAlias = SparseSymbolBodies[WeakAlias.second];
191 SymbolBody *ObjectFile::createUndefined(COFFSymbolRef Sym) {
193 COFFObj->getSymbolName(Sym, Name);
194 return Symtab->addUndefined(Name, this, Sym.isWeakExternal())->body();
197 SymbolBody *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
200 if (Sym.isCommon()) {
201 auto *C = new (Alloc) CommonChunk(Sym);
203 return Symtab->addCommon(this, Sym, C)->body();
205 if (Sym.isAbsolute()) {
206 COFFObj->getSymbolName(Sym, Name);
207 // Skip special symbols.
208 if (Name == "@comp.id")
210 // COFF spec 5.10.1. The .sxdata section.
211 if (Name == "@feat.00") {
212 if (Sym.getValue() & 1)
216 if (Sym.isExternal())
217 return Symtab->addAbsolute(Name, Sym)->body();
219 return new (Alloc) DefinedAbsolute(Name, Sym);
221 int32_t SectionNumber = Sym.getSectionNumber();
222 if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
225 // Reserved sections numbers don't have contents.
226 if (llvm::COFF::isReservedSectionNumber(SectionNumber))
227 fatal("broken object file: " + toString(this));
229 // This symbol references a section which is not present in the section
231 if ((uint32_t)SectionNumber >= SparseChunks.size())
232 fatal("broken object file: " + toString(this));
234 // Nothing else to do without a section chunk.
235 auto *SC = cast_or_null<SectionChunk>(SparseChunks[SectionNumber]);
239 // Handle section definitions
240 if (IsFirst && AuxP) {
241 auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
242 if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
243 if (auto *ParentSC = cast_or_null<SectionChunk>(
244 SparseChunks[Aux->getNumber(Sym.isBigObj())]))
245 ParentSC->addAssociative(SC);
246 SC->Checksum = Aux->CheckSum;
250 if (Sym.isExternal())
251 B = cast<DefinedRegular>(Symtab->addRegular(this, Sym, SC)->body());
253 B = new (Alloc) DefinedRegular(this, Sym, SC);
254 if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
260 void ObjectFile::initializeSEH() {
261 if (!SEHCompat || !SXData)
264 COFFObj->getSectionContents(SXData, A);
265 if (A.size() % 4 != 0)
266 fatal(".sxdata must be an array of symbol table indices");
267 auto *I = reinterpret_cast<const ulittle32_t *>(A.data());
268 auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size());
270 SEHandlers.insert(SparseSymbolBodies[*I]);
273 MachineTypes ObjectFile::getMachineType() {
275 return static_cast<MachineTypes>(COFFObj->getMachine());
276 return IMAGE_FILE_MACHINE_UNKNOWN;
279 StringRef ltrim1(StringRef S, const char *Chars) {
280 if (!S.empty() && strchr(Chars, S[0]))
285 void ImportFile::parse() {
286 const char *Buf = MB.getBufferStart();
287 const char *End = MB.getBufferEnd();
288 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
290 // Check if the total size is valid.
291 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
292 fatal("broken import library");
294 // Read names and create an __imp_ symbol.
295 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
296 StringRef ImpName = StringAlloc.save("__imp_" + Name);
297 const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
298 DLLName = StringRef(NameStart);
300 switch (Hdr->getNameType()) {
307 case IMPORT_NAME_NOPREFIX:
308 ExtName = ltrim1(Name, "?@_");
310 case IMPORT_NAME_UNDECORATE:
311 ExtName = ltrim1(Name, "?@_");
312 ExtName = ExtName.substr(0, ExtName.find('@'));
317 ExternalName = ExtName;
319 ImpSym = cast<DefinedImportData>(
320 Symtab->addImportData(ImpName, this)->body());
322 // If type is function, we need to create a thunk which jump to an
323 // address pointed by the __imp_ symbol. (This allows you to call
324 // DLL functions just like regular non-DLL functions.)
325 if (Hdr->getType() != llvm::COFF::IMPORT_CODE)
327 ThunkSym = cast<DefinedImportThunk>(
328 Symtab->addImportThunk(Name, ImpSym, Hdr->Machine)->body());
331 void BitcodeFile::parse() {
332 Context.enableDebugTypeODRUniquing();
333 ErrorOr<std::unique_ptr<LTOModule>> ModOrErr = LTOModule::createFromBuffer(
334 Context, MB.getBufferStart(), MB.getBufferSize(), llvm::TargetOptions());
335 M = check(std::move(ModOrErr), "could not create LTO module");
337 StringSaver Saver(Alloc);
338 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
339 lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
340 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
343 StringRef SymName = Saver.save(M->getSymbolName(I));
344 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
345 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
346 SymbolBodies.push_back(Symtab->addUndefined(SymName, this, false)->body());
349 (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
350 (Attrs & LTO_SYMBOL_COMDAT) || // comdat
351 (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK && // weak external
352 (Attrs & LTO_SYMBOL_ALIAS)));
353 SymbolBodies.push_back(
354 Symtab->addBitcode(this, SymName, Replaceable)->body());
358 Directives = M->getLinkerOpts();
361 MachineTypes BitcodeFile::getMachineType() {
363 return IMAGE_FILE_MACHINE_UNKNOWN;
364 switch (Triple(M->getTargetTriple()).getArch()) {
372 return IMAGE_FILE_MACHINE_UNKNOWN;
378 // Returns the last element of a path, which is supposed to be a filename.
379 static StringRef getBasename(StringRef Path) {
380 size_t Pos = Path.find_last_of("\\/");
381 if (Pos == StringRef::npos)
383 return Path.substr(Pos + 1);
386 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
387 std::string lld::toString(coff::InputFile *File) {
390 if (File->ParentName.empty())
391 return File->getName().lower();
394 (getBasename(File->ParentName) + "(" + getBasename(File->getName()) + ")")
396 return StringRef(Res).lower();