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