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 "SymbolTable.h"
15 #include "Symbols.h"
16 #include "lld/Common/ErrorHandler.h"
17 #include "lld/Common/Memory.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/Support/Path.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include <cstring>
33 #include <system_error>
34 #include <utility>
35 
36 using namespace llvm;
37 using namespace llvm::COFF;
38 using namespace llvm::object;
39 using namespace llvm::support::endian;
40 
41 using llvm::Triple;
42 using llvm::support::ulittle32_t;
43 
44 namespace lld {
45 namespace coff {
46 
47 std::vector<ObjFile *> ObjFile::Instances;
48 std::vector<ImportFile *> ImportFile::Instances;
49 std::vector<BitcodeFile *> BitcodeFile::Instances;
50 
51 /// Checks that Source is compatible with being a weak alias to Target.
52 /// If Source is Undefined and has no weak alias set, makes it a weak
53 /// alias to Target.
54 static void checkAndSetWeakAlias(SymbolTable *Symtab, InputFile *F,
55                                  Symbol *Source, Symbol *Target) {
56   if (auto *U = dyn_cast<Undefined>(Source)) {
57     if (U->WeakAlias && U->WeakAlias != Target)
58       Symtab->reportDuplicate(Source, F);
59     U->WeakAlias = Target;
60   }
61 }
62 
63 ArchiveFile::ArchiveFile(MemoryBufferRef M) : InputFile(ArchiveKind, M) {}
64 
65 void ArchiveFile::parse() {
66   // Parse a MemoryBufferRef as an archive file.
67   File = CHECK(Archive::create(MB), this);
68 
69   // Read the symbol table to construct Lazy objects.
70   for (const Archive::Symbol &Sym : File->symbols())
71     Symtab->addLazy(this, Sym);
72 }
73 
74 // Returns a buffer pointing to a member file containing a given symbol.
75 void ArchiveFile::addMember(const Archive::Symbol *Sym) {
76   const Archive::Child &C =
77       CHECK(Sym->getMember(),
78             "could not get the member for symbol " + Sym->getName());
79 
80   // Return an empty buffer if we have already returned the same buffer.
81   if (!Seen.insert(C.getChildOffset()).second)
82     return;
83 
84   Driver->enqueueArchiveMember(C, Sym->getName(), getName());
85 }
86 
87 std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
88   std::vector<MemoryBufferRef> V;
89   Error Err = Error::success();
90   for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
91     Archive::Child C =
92         CHECK(COrErr,
93               File->getFileName() + ": could not get the child of the archive");
94     MemoryBufferRef MBRef =
95         CHECK(C.getMemoryBufferRef(),
96               File->getFileName() +
97                   ": could not get the buffer for a child of the archive");
98     V.push_back(MBRef);
99   }
100   if (Err)
101     fatal(File->getFileName() +
102           ": Archive::children failed: " + toString(std::move(Err)));
103   return V;
104 }
105 
106 void ObjFile::parse() {
107   // Parse a memory buffer as a COFF file.
108   std::unique_ptr<Binary> Bin = CHECK(createBinary(MB), this);
109 
110   if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
111     Bin.release();
112     COFFObj.reset(Obj);
113   } else {
114     fatal(toString(this) + " is not a COFF file");
115   }
116 
117   // Read section and symbol tables.
118   initializeChunks();
119   initializeSymbols();
120 }
121 
122 // We set SectionChunk pointers in the SparseChunks vector to this value
123 // temporarily to mark comdat sections as having an unknown resolution. As we
124 // walk the object file's symbol table, once we visit either a leader symbol or
125 // an associative section definition together with the parent comdat's leader,
126 // we set the pointer to either nullptr (to mark the section as discarded) or a
127 // valid SectionChunk for that section.
128 static SectionChunk *const PendingComdat = reinterpret_cast<SectionChunk *>(1);
129 
130 void ObjFile::initializeChunks() {
131   uint32_t NumSections = COFFObj->getNumberOfSections();
132   Chunks.reserve(NumSections);
133   SparseChunks.resize(NumSections + 1);
134   for (uint32_t I = 1; I < NumSections + 1; ++I) {
135     const coff_section *Sec;
136     if (auto EC = COFFObj->getSection(I, Sec))
137       fatal("getSection failed: #" + Twine(I) + ": " + EC.message());
138 
139     if (Sec->Characteristics & IMAGE_SCN_LNK_COMDAT)
140       SparseChunks[I] = PendingComdat;
141     else
142       SparseChunks[I] = readSection(I, nullptr, "");
143   }
144 }
145 
146 SectionChunk *ObjFile::readSection(uint32_t SectionNumber,
147                                    const coff_aux_section_definition *Def,
148                                    StringRef LeaderName) {
149   const coff_section *Sec;
150   StringRef Name;
151   if (auto EC = COFFObj->getSection(SectionNumber, Sec))
152     fatal("getSection failed: #" + Twine(SectionNumber) + ": " + EC.message());
153   if (auto EC = COFFObj->getSectionName(Sec, Name))
154     fatal("getSectionName failed: #" + Twine(SectionNumber) + ": " +
155           EC.message());
156 
157   if (Name == ".drectve") {
158     ArrayRef<uint8_t> Data;
159     COFFObj->getSectionContents(Sec, Data);
160     Directives = std::string((const char *)Data.data(), Data.size());
161     return nullptr;
162   }
163 
164   // Object files may have DWARF debug info or MS CodeView debug info
165   // (or both).
166   //
167   // DWARF sections don't need any special handling from the perspective
168   // of the linker; they are just a data section containing relocations.
169   // We can just link them to complete debug info.
170   //
171   // CodeView needs a linker support. We need to interpret and debug
172   // info, and then write it to a separate .pdb file.
173 
174   // Ignore DWARF debug info unless /debug is given.
175   if (!Config->Debug && Name.startswith(".debug_"))
176     return nullptr;
177 
178   if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
179     return nullptr;
180   auto *C = make<SectionChunk>(this, Sec);
181   if (Def)
182     C->Checksum = Def->CheckSum;
183 
184   // CodeView sections are stored to a different vector because they are not
185   // linked in the regular manner.
186   if (C->isCodeView())
187     DebugChunks.push_back(C);
188   else if (Config->GuardCF != GuardCFLevel::Off && Name == ".gfids$y")
189     GuardFidChunks.push_back(C);
190   else if (Config->GuardCF != GuardCFLevel::Off && Name == ".gljmp$y")
191     GuardLJmpChunks.push_back(C);
192   else if (Name == ".sxdata")
193     SXDataChunks.push_back(C);
194   else if (Config->TailMerge && Sec->NumberOfRelocations == 0 &&
195            Name == ".rdata" && LeaderName.startswith("??_C@"))
196     // COFF sections that look like string literal sections (i.e. no
197     // relocations, in .rdata, leader symbol name matches the MSVC name mangling
198     // for string literals) are subject to string tail merging.
199     MergeChunk::addSection(C);
200   else
201     Chunks.push_back(C);
202 
203   return C;
204 }
205 
206 void ObjFile::readAssociativeDefinition(
207     COFFSymbolRef Sym, const coff_aux_section_definition *Def) {
208   SectionChunk *Parent = SparseChunks[Def->getNumber(Sym.isBigObj())];
209 
210   // If the parent is pending, it probably means that its section definition
211   // appears after us in the symbol table. Leave the associated section as
212   // pending; we will handle it during the second pass in initializeSymbols().
213   if (Parent == PendingComdat)
214     return;
215 
216   // Check whether the parent is prevailing. If it is, so are we, and we read
217   // the section; otherwise mark it as discarded.
218   int32_t SectionNumber = Sym.getSectionNumber();
219   if (Parent) {
220     SparseChunks[SectionNumber] = readSection(SectionNumber, Def, "");
221     if (SparseChunks[SectionNumber])
222       Parent->addAssociative(SparseChunks[SectionNumber]);
223   } else {
224     SparseChunks[SectionNumber] = nullptr;
225   }
226 }
227 
228 Symbol *ObjFile::createRegular(COFFSymbolRef Sym) {
229   SectionChunk *SC = SparseChunks[Sym.getSectionNumber()];
230   if (Sym.isExternal()) {
231     StringRef Name;
232     COFFObj->getSymbolName(Sym, Name);
233     if (SC)
234       return Symtab->addRegular(this, Name, Sym.getGeneric(), SC);
235     return Symtab->addUndefined(Name, this, false);
236   }
237   if (SC)
238     return make<DefinedRegular>(this, /*Name*/ "", false,
239                                 /*IsExternal*/ false, Sym.getGeneric(), SC);
240   return nullptr;
241 }
242 
243 void ObjFile::initializeSymbols() {
244   uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
245   Symbols.resize(NumSymbols);
246 
247   SmallVector<std::pair<Symbol *, uint32_t>, 8> WeakAliases;
248   std::vector<uint32_t> PendingIndexes;
249   PendingIndexes.reserve(NumSymbols);
250 
251   std::vector<const coff_aux_section_definition *> ComdatDefs(
252       COFFObj->getNumberOfSections() + 1);
253 
254   for (uint32_t I = 0; I < NumSymbols; ++I) {
255     COFFSymbolRef COFFSym = check(COFFObj->getSymbol(I));
256     if (COFFSym.isUndefined()) {
257       Symbols[I] = createUndefined(COFFSym);
258     } else if (COFFSym.isWeakExternal()) {
259       Symbols[I] = createUndefined(COFFSym);
260       uint32_t TagIndex = COFFSym.getAux<coff_aux_weak_external>()->TagIndex;
261       WeakAliases.emplace_back(Symbols[I], TagIndex);
262     } else if (Optional<Symbol *> OptSym = createDefined(COFFSym, ComdatDefs)) {
263       Symbols[I] = *OptSym;
264     } else {
265       // createDefined() returns None if a symbol belongs to a section that
266       // was pending at the point when the symbol was read. This can happen in
267       // two cases:
268       // 1) section definition symbol for a comdat leader;
269       // 2) symbol belongs to a comdat section associated with a section whose
270       //    section definition symbol appears later in the symbol table.
271       // In both of these cases, we can expect the section to be resolved by
272       // the time we finish visiting the remaining symbols in the symbol
273       // table. So we postpone the handling of this symbol until that time.
274       PendingIndexes.push_back(I);
275     }
276     I += COFFSym.getNumberOfAuxSymbols();
277   }
278 
279   for (uint32_t I : PendingIndexes) {
280     COFFSymbolRef Sym = check(COFFObj->getSymbol(I));
281     if (auto *Def = Sym.getSectionDefinition())
282       if (Def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
283         readAssociativeDefinition(Sym, Def);
284     if (SparseChunks[Sym.getSectionNumber()] == PendingComdat) {
285       StringRef Name;
286       COFFObj->getSymbolName(Sym, Name);
287       log("comdat section " + Name +
288           " without leader and unassociated, discarding");
289       continue;
290     }
291     Symbols[I] = createRegular(Sym);
292   }
293 
294   for (auto &KV : WeakAliases) {
295     Symbol *Sym = KV.first;
296     uint32_t Idx = KV.second;
297     checkAndSetWeakAlias(Symtab, this, Sym, Symbols[Idx]);
298   }
299 }
300 
301 Symbol *ObjFile::createUndefined(COFFSymbolRef Sym) {
302   StringRef Name;
303   COFFObj->getSymbolName(Sym, Name);
304   return Symtab->addUndefined(Name, this, Sym.isWeakExternal());
305 }
306 
307 Optional<Symbol *> ObjFile::createDefined(
308     COFFSymbolRef Sym,
309     std::vector<const coff_aux_section_definition *> &ComdatDefs) {
310   auto GetName = [&]() {
311     StringRef S;
312     COFFObj->getSymbolName(Sym, S);
313     return S;
314   };
315 
316   if (Sym.isCommon()) {
317     auto *C = make<CommonChunk>(Sym);
318     Chunks.push_back(C);
319     return Symtab->addCommon(this, GetName(), Sym.getValue(), Sym.getGeneric(),
320                              C);
321   }
322 
323   if (Sym.isAbsolute()) {
324     StringRef Name = GetName();
325 
326     // Skip special symbols.
327     if (Name == "@comp.id")
328       return nullptr;
329     if (Name == "@feat.00") {
330       Feat00Flags = Sym.getValue();
331       return nullptr;
332     }
333 
334     if (Sym.isExternal())
335       return Symtab->addAbsolute(Name, Sym);
336     return make<DefinedAbsolute>(Name, Sym);
337   }
338 
339   int32_t SectionNumber = Sym.getSectionNumber();
340   if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
341     return nullptr;
342 
343   if (llvm::COFF::isReservedSectionNumber(SectionNumber))
344     fatal(toString(this) + ": " + GetName() +
345           " should not refer to special section " + Twine(SectionNumber));
346 
347   if ((uint32_t)SectionNumber >= SparseChunks.size())
348     fatal(toString(this) + ": " + GetName() +
349           " should not refer to non-existent section " + Twine(SectionNumber));
350 
351   // Handle comdat leader symbols.
352   if (const coff_aux_section_definition *Def = ComdatDefs[SectionNumber]) {
353     ComdatDefs[SectionNumber] = nullptr;
354     Symbol *Leader;
355     bool Prevailing;
356     if (Sym.isExternal()) {
357       std::tie(Leader, Prevailing) =
358           Symtab->addComdat(this, GetName(), Sym.getGeneric());
359     } else {
360       Leader = make<DefinedRegular>(this, /*Name*/ "", false,
361                                     /*IsExternal*/ false, Sym.getGeneric());
362       Prevailing = true;
363     }
364 
365     if (Prevailing) {
366       SectionChunk *C = readSection(SectionNumber, Def, GetName());
367       SparseChunks[SectionNumber] = C;
368       C->Sym = cast<DefinedRegular>(Leader);
369       cast<DefinedRegular>(Leader)->Data = &C->Repl;
370     } else {
371       SparseChunks[SectionNumber] = nullptr;
372     }
373     return Leader;
374   }
375 
376   // Read associative section definitions and prepare to handle the comdat
377   // leader symbol by setting the section's ComdatDefs pointer if we encounter a
378   // non-associative comdat.
379   if (SparseChunks[SectionNumber] == PendingComdat) {
380     if (auto *Def = Sym.getSectionDefinition()) {
381       if (Def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
382         readAssociativeDefinition(Sym, Def);
383       else
384         ComdatDefs[SectionNumber] = Def;
385     }
386   }
387 
388   if (SparseChunks[SectionNumber] == PendingComdat)
389     return None;
390   return createRegular(Sym);
391 }
392 
393 MachineTypes ObjFile::getMachineType() {
394   if (COFFObj)
395     return static_cast<MachineTypes>(COFFObj->getMachine());
396   return IMAGE_FILE_MACHINE_UNKNOWN;
397 }
398 
399 StringRef ltrim1(StringRef S, const char *Chars) {
400   if (!S.empty() && strchr(Chars, S[0]))
401     return S.substr(1);
402   return S;
403 }
404 
405 void ImportFile::parse() {
406   const char *Buf = MB.getBufferStart();
407   const char *End = MB.getBufferEnd();
408   const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
409 
410   // Check if the total size is valid.
411   if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
412     fatal("broken import library");
413 
414   // Read names and create an __imp_ symbol.
415   StringRef Name = Saver.save(StringRef(Buf + sizeof(*Hdr)));
416   StringRef ImpName = Saver.save("__imp_" + Name);
417   const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
418   DLLName = StringRef(NameStart);
419   StringRef ExtName;
420   switch (Hdr->getNameType()) {
421   case IMPORT_ORDINAL:
422     ExtName = "";
423     break;
424   case IMPORT_NAME:
425     ExtName = Name;
426     break;
427   case IMPORT_NAME_NOPREFIX:
428     ExtName = ltrim1(Name, "?@_");
429     break;
430   case IMPORT_NAME_UNDECORATE:
431     ExtName = ltrim1(Name, "?@_");
432     ExtName = ExtName.substr(0, ExtName.find('@'));
433     break;
434   }
435 
436   this->Hdr = Hdr;
437   ExternalName = ExtName;
438 
439   ImpSym = Symtab->addImportData(ImpName, this);
440 
441   if (Hdr->getType() == llvm::COFF::IMPORT_CONST)
442     static_cast<void>(Symtab->addImportData(Name, this));
443 
444   // If type is function, we need to create a thunk which jump to an
445   // address pointed by the __imp_ symbol. (This allows you to call
446   // DLL functions just like regular non-DLL functions.)
447   if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
448     ThunkSym = Symtab->addImportThunk(
449         Name, cast_or_null<DefinedImportData>(ImpSym), Hdr->Machine);
450 }
451 
452 void BitcodeFile::parse() {
453   Obj = check(lto::InputFile::create(MemoryBufferRef(
454       MB.getBuffer(), Saver.save(ParentName + MB.getBufferIdentifier()))));
455   std::vector<std::pair<Symbol *, bool>> Comdat(Obj->getComdatTable().size());
456   for (size_t I = 0; I != Obj->getComdatTable().size(); ++I)
457     Comdat[I] = Symtab->addComdat(this, Saver.save(Obj->getComdatTable()[I]));
458   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) {
459     StringRef SymName = Saver.save(ObjSym.getName());
460     int ComdatIndex = ObjSym.getComdatIndex();
461     Symbol *Sym;
462     if (ObjSym.isUndefined()) {
463       Sym = Symtab->addUndefined(SymName, this, false);
464     } else if (ObjSym.isCommon()) {
465       Sym = Symtab->addCommon(this, SymName, ObjSym.getCommonSize());
466     } else if (ObjSym.isWeak() && ObjSym.isIndirect()) {
467       // Weak external.
468       Sym = Symtab->addUndefined(SymName, this, true);
469       std::string Fallback = ObjSym.getCOFFWeakExternalFallback();
470       Symbol *Alias = Symtab->addUndefined(Saver.save(Fallback));
471       checkAndSetWeakAlias(Symtab, this, Sym, Alias);
472     } else if (ComdatIndex != -1) {
473       if (SymName == Obj->getComdatTable()[ComdatIndex])
474         Sym = Comdat[ComdatIndex].first;
475       else if (Comdat[ComdatIndex].second)
476         Sym = Symtab->addRegular(this, SymName);
477       else
478         Sym = Symtab->addUndefined(SymName, this, false);
479     } else {
480       Sym = Symtab->addRegular(this, SymName);
481     }
482     Symbols.push_back(Sym);
483   }
484   Directives = Obj->getCOFFLinkerOpts();
485 }
486 
487 MachineTypes BitcodeFile::getMachineType() {
488   switch (Triple(Obj->getTargetTriple()).getArch()) {
489   case Triple::x86_64:
490     return AMD64;
491   case Triple::x86:
492     return I386;
493   case Triple::arm:
494     return ARMNT;
495   case Triple::aarch64:
496     return ARM64;
497   default:
498     return IMAGE_FILE_MACHINE_UNKNOWN;
499   }
500 }
501 } // namespace coff
502 } // namespace lld
503 
504 // Returns the last element of a path, which is supposed to be a filename.
505 static StringRef getBasename(StringRef Path) {
506   return sys::path::filename(Path, sys::path::Style::windows);
507 }
508 
509 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
510 std::string lld::toString(const coff::InputFile *File) {
511   if (!File)
512     return "<internal>";
513   if (File->ParentName.empty())
514     return File->getName();
515 
516   return (getBasename(File->ParentName) + "(" + getBasename(File->getName()) +
517           ")")
518       .str();
519 }
520