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::COFF;
36 using namespace llvm::object;
37 using namespace llvm::support::endian;
38 
39 using llvm::Triple;
40 using llvm::support::ulittle32_t;
41 
42 namespace lld {
43 namespace coff {
44 
45 int InputFile::NextIndex = 0;
46 llvm::LLVMContext BitcodeFile::Context;
47 
48 // Returns the last element of a path, which is supposed to be a filename.
49 static StringRef getBasename(StringRef Path) {
50   size_t Pos = Path.find_last_of("\\/");
51   if (Pos == StringRef::npos)
52     return Path;
53   return Path.substr(Pos + 1);
54 }
55 
56 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
57 std::string InputFile::getShortName() {
58   if (ParentName == "")
59     return getName().lower();
60   std::string Res = (getBasename(ParentName) + "(" +
61                      getBasename(getName()) + ")").str();
62   return StringRef(Res).lower();
63 }
64 
65 void ArchiveFile::parse() {
66   // Parse a MemoryBufferRef as an archive file.
67   File = check(Archive::create(MB), getShortName());
68 
69   // Allocate a buffer for Lazy objects.
70   size_t NumSyms = File->getNumberOfSymbols();
71   LazySymbols.reserve(NumSyms);
72 
73   // Read the symbol table to construct Lazy objects.
74   for (const Archive::Symbol &Sym : File->symbols())
75     LazySymbols.emplace_back(this, Sym);
76 
77   // Seen is a map from member files to boolean values. Initially
78   // all members are mapped to false, which indicates all these files
79   // are not read yet.
80   Error Err;
81   for (auto &Child : File->children(Err))
82     Seen[Child.getChildOffset()].clear();
83   if (Err)
84     fatal(Err, getShortName());
85 }
86 
87 // Returns a buffer pointing to a member file containing a given symbol.
88 // This function is thread-safe.
89 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) {
90   const Archive::Child &C =
91       check(Sym->getMember(),
92             "could not get the member for symbol " + Sym->getName());
93 
94   // Return an empty buffer if we have already returned the same buffer.
95   if (Seen[C.getChildOffset()].test_and_set())
96     return MemoryBufferRef();
97 
98   MemoryBufferRef MB =
99       check(C.getMemoryBufferRef(),
100             "could not get the buffer for the member defining symbol " +
101                 Sym->getName());
102   if (C.getParent()->isThin() && Driver->Cpio)
103     Driver->Cpio->append(relativeToRoot(check(C.getFullName())),
104                          MB.getBuffer());
105 
106   return MB;
107 }
108 
109 void ObjectFile::parse() {
110   // Parse a memory buffer as a COFF file.
111   std::unique_ptr<Binary> Bin =
112       check(createBinary(MB), getShortName());
113 
114   if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
115     Bin.release();
116     COFFObj.reset(Obj);
117   } else {
118     fatal(getShortName() + " is not a COFF file");
119   }
120 
121   // Read section and symbol tables.
122   initializeChunks();
123   initializeSymbols();
124   initializeSEH();
125 }
126 
127 void ObjectFile::initializeChunks() {
128   uint32_t NumSections = COFFObj->getNumberOfSections();
129   Chunks.reserve(NumSections);
130   SparseChunks.resize(NumSections + 1);
131   for (uint32_t I = 1; I < NumSections + 1; ++I) {
132     const coff_section *Sec;
133     StringRef Name;
134     if (auto EC = COFFObj->getSection(I, Sec))
135       fatal(EC, "getSection failed: #" + Twine(I));
136     if (auto EC = COFFObj->getSectionName(Sec, Name))
137       fatal(EC, "getSectionName failed: #" + Twine(I));
138     if (Name == ".sxdata") {
139       SXData = Sec;
140       continue;
141     }
142     if (Name == ".drectve") {
143       ArrayRef<uint8_t> Data;
144       COFFObj->getSectionContents(Sec, Data);
145       Directives = std::string((const char *)Data.data(), Data.size());
146       continue;
147     }
148     // Skip non-DWARF debug info. MSVC linker converts the sections into
149     // a PDB file, but we don't support that.
150     if (Name == ".debug" || Name.startswith(".debug$"))
151       continue;
152     // We want to preserve DWARF debug sections only when /debug is on.
153     if (!Config->Debug && Name.startswith(".debug"))
154       continue;
155     if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
156       continue;
157     auto *C = new (Alloc) SectionChunk(this, Sec);
158     Chunks.push_back(C);
159     SparseChunks[I] = C;
160   }
161 }
162 
163 void ObjectFile::initializeSymbols() {
164   uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
165   SymbolBodies.reserve(NumSymbols);
166   SparseSymbolBodies.resize(NumSymbols);
167   llvm::SmallVector<std::pair<Undefined *, uint32_t>, 8> WeakAliases;
168   int32_t LastSectionNumber = 0;
169   for (uint32_t I = 0; I < NumSymbols; ++I) {
170     // Get a COFFSymbolRef object.
171     COFFSymbolRef Sym =
172         check(COFFObj->getSymbol(I), "broken object file: " + getShortName());
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     fatal("broken object file: " + getShortName());
235 
236   // This symbol references a section which is not present in the section
237   // header.
238   if ((uint32_t)SectionNumber >= SparseChunks.size())
239     fatal("broken object file: " + getShortName());
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     fatal(".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     fatal("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("__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   M = check(std::move(ModOrErr), "could not create LTO module");
338 
339   llvm::StringSaver Saver(Alloc);
340   for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
341     lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
342     if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
343       continue;
344 
345     StringRef SymName = Saver.save(M->getSymbolName(I));
346     int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
347     if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
348       SymbolBodies.push_back(new (Alloc) Undefined(SymName));
349     } else {
350       bool Replaceable =
351           (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
352            (Attrs & LTO_SYMBOL_COMDAT) ||                  // comdat
353            (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK &&     // weak external
354             (Attrs & LTO_SYMBOL_ALIAS)));
355       SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
356                                                         Replaceable));
357     }
358   }
359 
360   Directives = M->getLinkerOpts();
361 }
362 
363 MachineTypes BitcodeFile::getMachineType() {
364   if (!M)
365     return IMAGE_FILE_MACHINE_UNKNOWN;
366   switch (Triple(M->getTargetTriple()).getArch()) {
367   case Triple::x86_64:
368     return AMD64;
369   case Triple::x86:
370     return I386;
371   case Triple::arm:
372     return ARMNT;
373   default:
374     return IMAGE_FILE_MACHINE_UNKNOWN;
375   }
376 }
377 
378 std::mutex BitcodeFile::Mu;
379 
380 } // namespace coff
381 } // namespace lld
382