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