1 //===- InputFiles.cpp -----------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
13 #include "InputFiles.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/LTO/legacy/LTOModule.h"
20 #include "llvm/Object/Binary.h"
21 #include "llvm/Object/COFF.h"
22 #include "llvm/Support/COFF.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/Error.h"
26 #include "llvm/Support/ErrorOr.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm-c/lto.h"
31 #include <system_error>
34 using namespace llvm::COFF;
35 using namespace llvm::object;
36 using namespace llvm::support::endian;
39 using llvm::support::ulittle32_t;
44 int InputFile::NextIndex = 0;
45 llvm::LLVMContext BitcodeFile::Context;
47 // Returns the last element of a path, which is supposed to be a filename.
48 static StringRef getBasename(StringRef Path) {
49 size_t Pos = Path.find_last_of("\\/");
50 if (Pos == StringRef::npos)
52 return Path.substr(Pos + 1);
55 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
56 std::string InputFile::getShortName() {
58 return getName().lower();
59 std::string Res = (getBasename(ParentName) + "(" +
60 getBasename(getName()) + ")").str();
61 return StringRef(Res).lower();
64 void ArchiveFile::parse() {
65 // Parse a MemoryBufferRef as an archive file.
66 File = check(Archive::create(MB), "failed to parse static library");
68 // Allocate a buffer for Lazy objects.
69 size_t NumSyms = File->getNumberOfSymbols();
70 LazySymbols.reserve(NumSyms);
72 // Read the symbol table to construct Lazy objects.
73 for (const Archive::Symbol &Sym : File->symbols())
74 LazySymbols.emplace_back(this, Sym);
76 // Seen is a map from member files to boolean values. Initially
77 // all members are mapped to false, which indicates all these files
80 for (auto &Child : File->children(Err))
81 Seen[Child.getChildOffset()].clear();
83 fatal(Err, "failed to parse static library");
86 // Returns a buffer pointing to a member file containing a given symbol.
87 // This function is thread-safe.
88 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) {
89 const Archive::Child &C =
90 check(Sym->getMember(),
91 "could not get the member for symbol " + Sym->getName());
93 // Return an empty buffer if we have already returned the same buffer.
94 if (Seen[C.getChildOffset()].test_and_set())
95 return MemoryBufferRef();
96 return check(C.getMemoryBufferRef(),
97 "could not get the buffer for the member defining symbol " +
101 void ObjectFile::parse() {
102 // Parse a memory buffer as a COFF file.
103 std::unique_ptr<Binary> Bin =
104 check(createBinary(MB), "failed to parse object file");
106 if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
110 fatal(getName() + " is not a COFF file");
113 // Read section and symbol tables.
119 void ObjectFile::initializeChunks() {
120 uint32_t NumSections = COFFObj->getNumberOfSections();
121 Chunks.reserve(NumSections);
122 SparseChunks.resize(NumSections + 1);
123 for (uint32_t I = 1; I < NumSections + 1; ++I) {
124 const coff_section *Sec;
126 if (auto EC = COFFObj->getSection(I, Sec))
127 fatal(EC, "getSection failed: #" + Twine(I));
128 if (auto EC = COFFObj->getSectionName(Sec, Name))
129 fatal(EC, "getSectionName failed: #" + Twine(I));
130 if (Name == ".sxdata") {
134 if (Name == ".drectve") {
135 ArrayRef<uint8_t> Data;
136 COFFObj->getSectionContents(Sec, Data);
137 Directives = std::string((const char *)Data.data(), Data.size());
140 // Skip non-DWARF debug info. MSVC linker converts the sections into
141 // a PDB file, but we don't support that.
142 if (Name == ".debug" || Name.startswith(".debug$"))
144 // We want to preserve DWARF debug sections only when /debug is on.
145 if (!Config->Debug && Name.startswith(".debug"))
147 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
149 auto *C = new (Alloc) SectionChunk(this, Sec);
155 void ObjectFile::initializeSymbols() {
156 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
157 SymbolBodies.reserve(NumSymbols);
158 SparseSymbolBodies.resize(NumSymbols);
159 llvm::SmallVector<std::pair<Undefined *, uint32_t>, 8> WeakAliases;
160 int32_t LastSectionNumber = 0;
161 for (uint32_t I = 0; I < NumSymbols; ++I) {
162 // Get a COFFSymbolRef object.
164 check(COFFObj->getSymbol(I), "broken object file: " + getName());
166 const void *AuxP = nullptr;
167 if (Sym.getNumberOfAuxSymbols())
168 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
169 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
171 SymbolBody *Body = nullptr;
172 if (Sym.isUndefined()) {
173 Body = createUndefined(Sym);
174 } else if (Sym.isWeakExternal()) {
175 Body = createUndefined(Sym);
177 static_cast<const coff_aux_weak_external *>(AuxP)->TagIndex;
178 WeakAliases.emplace_back((Undefined *)Body, TagIndex);
180 Body = createDefined(Sym, AuxP, IsFirst);
183 SymbolBodies.push_back(Body);
184 SparseSymbolBodies[I] = Body;
186 I += Sym.getNumberOfAuxSymbols();
187 LastSectionNumber = Sym.getSectionNumber();
189 for (auto WeakAlias : WeakAliases)
190 WeakAlias.first->WeakAlias = SparseSymbolBodies[WeakAlias.second];
193 Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
195 COFFObj->getSymbolName(Sym, Name);
196 return new (Alloc) Undefined(Name);
199 Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
202 if (Sym.isCommon()) {
203 auto *C = new (Alloc) CommonChunk(Sym);
205 return new (Alloc) DefinedCommon(this, Sym, C);
207 if (Sym.isAbsolute()) {
208 COFFObj->getSymbolName(Sym, Name);
209 // Skip special symbols.
210 if (Name == "@comp.id")
212 // COFF spec 5.10.1. The .sxdata section.
213 if (Name == "@feat.00") {
214 if (Sym.getValue() & 1)
218 return new (Alloc) DefinedAbsolute(Name, Sym);
220 int32_t SectionNumber = Sym.getSectionNumber();
221 if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
224 // Reserved sections numbers don't have contents.
225 if (llvm::COFF::isReservedSectionNumber(SectionNumber))
226 fatal("broken object file: " + getName());
228 // This symbol references a section which is not present in the section
230 if ((uint32_t)SectionNumber >= SparseChunks.size())
231 fatal("broken object file: " + getName());
233 // Nothing else to do without a section chunk.
234 auto *SC = cast_or_null<SectionChunk>(SparseChunks[SectionNumber]);
238 // Handle section definitions
239 if (IsFirst && AuxP) {
240 auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
241 if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
242 if (auto *ParentSC = cast_or_null<SectionChunk>(
243 SparseChunks[Aux->getNumber(Sym.isBigObj())]))
244 ParentSC->addAssociative(SC);
245 SC->Checksum = Aux->CheckSum;
248 auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
249 if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
255 void ObjectFile::initializeSEH() {
256 if (!SEHCompat || !SXData)
259 COFFObj->getSectionContents(SXData, A);
260 if (A.size() % 4 != 0)
261 fatal(".sxdata must be an array of symbol table indices");
262 auto *I = reinterpret_cast<const ulittle32_t *>(A.data());
263 auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size());
265 SEHandlers.insert(SparseSymbolBodies[*I]);
268 MachineTypes ObjectFile::getMachineType() {
270 return static_cast<MachineTypes>(COFFObj->getMachine());
271 return IMAGE_FILE_MACHINE_UNKNOWN;
274 StringRef ltrim1(StringRef S, const char *Chars) {
275 if (!S.empty() && strchr(Chars, S[0]))
280 void ImportFile::parse() {
281 const char *Buf = MB.getBufferStart();
282 const char *End = MB.getBufferEnd();
283 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
285 // Check if the total size is valid.
286 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
287 fatal("broken import library");
289 // Read names and create an __imp_ symbol.
290 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
291 StringRef ImpName = StringAlloc.save("__imp_" + Name);
292 const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
293 DLLName = StringRef(NameStart);
295 switch (Hdr->getNameType()) {
302 case IMPORT_NAME_NOPREFIX:
303 ExtName = ltrim1(Name, "?@_");
305 case IMPORT_NAME_UNDECORATE:
306 ExtName = ltrim1(Name, "?@_");
307 ExtName = ExtName.substr(0, ExtName.find('@'));
310 ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
311 SymbolBodies.push_back(ImpSym);
313 // If type is function, we need to create a thunk which jump to an
314 // address pointed by the __imp_ symbol. (This allows you to call
315 // DLL functions just like regular non-DLL functions.)
316 if (Hdr->getType() != llvm::COFF::IMPORT_CODE)
318 ThunkSym = new (Alloc) DefinedImportThunk(Name, ImpSym, Hdr->Machine);
319 SymbolBodies.push_back(ThunkSym);
322 void BitcodeFile::parse() {
323 // Usually parse() is thread-safe, but bitcode file is an exception.
324 std::lock_guard<std::mutex> Lock(Mu);
326 Context.enableDebugTypeODRUniquing();
327 ErrorOr<std::unique_ptr<LTOModule>> ModOrErr = LTOModule::createFromBuffer(
328 Context, MB.getBufferStart(), MB.getBufferSize(), llvm::TargetOptions());
329 M = check(std::move(ModOrErr), "could not create LTO module");
331 llvm::StringSaver Saver(Alloc);
332 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
333 lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
334 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
337 StringRef SymName = Saver.save(M->getSymbolName(I));
338 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
339 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
340 SymbolBodies.push_back(new (Alloc) Undefined(SymName));
343 (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
344 (Attrs & LTO_SYMBOL_COMDAT) || // comdat
345 (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK && // weak external
346 (Attrs & LTO_SYMBOL_ALIAS)));
347 SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
352 Directives = M->getLinkerOpts();
355 MachineTypes BitcodeFile::getMachineType() {
357 return IMAGE_FILE_MACHINE_UNKNOWN;
358 switch (Triple(M->getTargetTriple()).getArch()) {
366 return IMAGE_FILE_MACHINE_UNKNOWN;
370 std::mutex BitcodeFile::Mu;