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