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