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