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