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   if (Name == ".llvm_addrsig") {
165     AddrsigSec = Sec;
166     return nullptr;
167   }
168 
169   // Object files may have DWARF debug info or MS CodeView debug info
170   // (or both).
171   //
172   // DWARF sections don't need any special handling from the perspective
173   // of the linker; they are just a data section containing relocations.
174   // We can just link them to complete debug info.
175   //
176   // CodeView needs a linker support. We need to interpret and debug
177   // info, and then write it to a separate .pdb file.
178 
179   // Ignore DWARF debug info unless /debug is given.
180   if (!Config->Debug && Name.startswith(".debug_"))
181     return nullptr;
182 
183   if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
184     return nullptr;
185   auto *C = make<SectionChunk>(this, Sec);
186   if (Def)
187     C->Checksum = Def->CheckSum;
188 
189   // CodeView sections are stored to a different vector because they are not
190   // linked in the regular manner.
191   if (C->isCodeView())
192     DebugChunks.push_back(C);
193   else if (Config->GuardCF != GuardCFLevel::Off && Name == ".gfids$y")
194     GuardFidChunks.push_back(C);
195   else if (Config->GuardCF != GuardCFLevel::Off && Name == ".gljmp$y")
196     GuardLJmpChunks.push_back(C);
197   else if (Name == ".sxdata")
198     SXDataChunks.push_back(C);
199   else if (Config->TailMerge && Sec->NumberOfRelocations == 0 &&
200            Name == ".rdata" && LeaderName.startswith("??_C@"))
201     // COFF sections that look like string literal sections (i.e. no
202     // relocations, in .rdata, leader symbol name matches the MSVC name mangling
203     // for string literals) are subject to string tail merging.
204     MergeChunk::addSection(C);
205   else
206     Chunks.push_back(C);
207 
208   return C;
209 }
210 
211 void ObjFile::readAssociativeDefinition(
212     COFFSymbolRef Sym, const coff_aux_section_definition *Def) {
213   readAssociativeDefinition(Sym, Def, Def->getNumber(Sym.isBigObj()));
214 }
215 
216 void ObjFile::readAssociativeDefinition(COFFSymbolRef Sym,
217                                         const coff_aux_section_definition *Def,
218                                         uint32_t ParentSection) {
219   SectionChunk *Parent = SparseChunks[ParentSection];
220 
221   // If the parent is pending, it probably means that its section definition
222   // appears after us in the symbol table. Leave the associated section as
223   // pending; we will handle it during the second pass in initializeSymbols().
224   if (Parent == PendingComdat)
225     return;
226 
227   // Check whether the parent is prevailing. If it is, so are we, and we read
228   // the section; otherwise mark it as discarded.
229   int32_t SectionNumber = Sym.getSectionNumber();
230   if (Parent) {
231     SparseChunks[SectionNumber] = readSection(SectionNumber, Def, "");
232     if (SparseChunks[SectionNumber])
233       Parent->addAssociative(SparseChunks[SectionNumber]);
234   } else {
235     SparseChunks[SectionNumber] = nullptr;
236   }
237 }
238 
239 void ObjFile::recordPrevailingSymbolForMingw(
240     COFFSymbolRef Sym, DenseMap<StringRef, uint32_t> &PrevailingSectionMap) {
241   // For comdat symbols in executable sections, where this is the copy
242   // of the section chunk we actually include instead of discarding it,
243   // add the symbol to a map to allow using it for implicitly
244   // associating .[px]data$<func> sections to it.
245   int32_t SectionNumber = Sym.getSectionNumber();
246   SectionChunk *SC = SparseChunks[SectionNumber];
247   if (SC && SC->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE) {
248     StringRef Name;
249     COFFObj->getSymbolName(Sym, Name);
250     PrevailingSectionMap[Name] = SectionNumber;
251   }
252 }
253 
254 void ObjFile::maybeAssociateSEHForMingw(
255     COFFSymbolRef Sym, const coff_aux_section_definition *Def,
256     const DenseMap<StringRef, uint32_t> &PrevailingSectionMap) {
257   StringRef Name;
258   COFFObj->getSymbolName(Sym, Name);
259   if (Name.consume_front(".pdata$") || Name.consume_front(".xdata$")) {
260     // For MinGW, treat .[px]data$<func> as implicitly associative to
261     // the symbol <func>.
262     auto ParentSym = PrevailingSectionMap.find(Name);
263     if (ParentSym != PrevailingSectionMap.end())
264       readAssociativeDefinition(Sym, Def, ParentSym->second);
265   }
266 }
267 
268 Symbol *ObjFile::createRegular(COFFSymbolRef Sym) {
269   SectionChunk *SC = SparseChunks[Sym.getSectionNumber()];
270   if (Sym.isExternal()) {
271     StringRef Name;
272     COFFObj->getSymbolName(Sym, Name);
273     if (SC)
274       return Symtab->addRegular(this, Name, Sym.getGeneric(), SC);
275     return Symtab->addUndefined(Name, this, false);
276   }
277   if (SC)
278     return make<DefinedRegular>(this, /*Name*/ "", false,
279                                 /*IsExternal*/ false, Sym.getGeneric(), SC);
280   return nullptr;
281 }
282 
283 void ObjFile::initializeSymbols() {
284   uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
285   Symbols.resize(NumSymbols);
286 
287   SmallVector<std::pair<Symbol *, uint32_t>, 8> WeakAliases;
288   std::vector<uint32_t> PendingIndexes;
289   PendingIndexes.reserve(NumSymbols);
290 
291   DenseMap<StringRef, uint32_t> PrevailingSectionMap;
292   std::vector<const coff_aux_section_definition *> ComdatDefs(
293       COFFObj->getNumberOfSections() + 1);
294 
295   for (uint32_t I = 0; I < NumSymbols; ++I) {
296     COFFSymbolRef COFFSym = check(COFFObj->getSymbol(I));
297     bool PrevailingComdat;
298     if (COFFSym.isUndefined()) {
299       Symbols[I] = createUndefined(COFFSym);
300     } else if (COFFSym.isWeakExternal()) {
301       Symbols[I] = createUndefined(COFFSym);
302       uint32_t TagIndex = COFFSym.getAux<coff_aux_weak_external>()->TagIndex;
303       WeakAliases.emplace_back(Symbols[I], TagIndex);
304     } else if (Optional<Symbol *> OptSym =
305                    createDefined(COFFSym, ComdatDefs, PrevailingComdat)) {
306       Symbols[I] = *OptSym;
307       if (Config->MinGW && PrevailingComdat)
308         recordPrevailingSymbolForMingw(COFFSym, PrevailingSectionMap);
309     } else {
310       // createDefined() returns None if a symbol belongs to a section that
311       // was pending at the point when the symbol was read. This can happen in
312       // two cases:
313       // 1) section definition symbol for a comdat leader;
314       // 2) symbol belongs to a comdat section associated with a section whose
315       //    section definition symbol appears later in the symbol table.
316       // In both of these cases, we can expect the section to be resolved by
317       // the time we finish visiting the remaining symbols in the symbol
318       // table. So we postpone the handling of this symbol until that time.
319       PendingIndexes.push_back(I);
320     }
321     I += COFFSym.getNumberOfAuxSymbols();
322   }
323 
324   for (uint32_t I : PendingIndexes) {
325     COFFSymbolRef Sym = check(COFFObj->getSymbol(I));
326     if (auto *Def = Sym.getSectionDefinition()) {
327       if (Def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
328         readAssociativeDefinition(Sym, Def);
329       else if (Config->MinGW)
330         maybeAssociateSEHForMingw(Sym, Def, PrevailingSectionMap);
331     }
332     if (SparseChunks[Sym.getSectionNumber()] == PendingComdat) {
333       StringRef Name;
334       COFFObj->getSymbolName(Sym, Name);
335       log("comdat section " + Name +
336           " without leader and unassociated, discarding");
337       continue;
338     }
339     Symbols[I] = createRegular(Sym);
340   }
341 
342   for (auto &KV : WeakAliases) {
343     Symbol *Sym = KV.first;
344     uint32_t Idx = KV.second;
345     checkAndSetWeakAlias(Symtab, this, Sym, Symbols[Idx]);
346   }
347 }
348 
349 Symbol *ObjFile::createUndefined(COFFSymbolRef Sym) {
350   StringRef Name;
351   COFFObj->getSymbolName(Sym, Name);
352   return Symtab->addUndefined(Name, this, Sym.isWeakExternal());
353 }
354 
355 Optional<Symbol *> ObjFile::createDefined(
356     COFFSymbolRef Sym,
357     std::vector<const coff_aux_section_definition *> &ComdatDefs,
358     bool &Prevailing) {
359   Prevailing = false;
360   auto GetName = [&]() {
361     StringRef S;
362     COFFObj->getSymbolName(Sym, S);
363     return S;
364   };
365 
366   if (Sym.isCommon()) {
367     auto *C = make<CommonChunk>(Sym);
368     Chunks.push_back(C);
369     return Symtab->addCommon(this, GetName(), Sym.getValue(), Sym.getGeneric(),
370                              C);
371   }
372 
373   if (Sym.isAbsolute()) {
374     StringRef Name = GetName();
375 
376     // Skip special symbols.
377     if (Name == "@comp.id")
378       return nullptr;
379     if (Name == "@feat.00") {
380       Feat00Flags = Sym.getValue();
381       return nullptr;
382     }
383 
384     if (Sym.isExternal())
385       return Symtab->addAbsolute(Name, Sym);
386     return make<DefinedAbsolute>(Name, Sym);
387   }
388 
389   int32_t SectionNumber = Sym.getSectionNumber();
390   if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
391     return nullptr;
392 
393   if (llvm::COFF::isReservedSectionNumber(SectionNumber))
394     fatal(toString(this) + ": " + GetName() +
395           " should not refer to special section " + Twine(SectionNumber));
396 
397   if ((uint32_t)SectionNumber >= SparseChunks.size())
398     fatal(toString(this) + ": " + GetName() +
399           " should not refer to non-existent section " + Twine(SectionNumber));
400 
401   // Handle comdat leader symbols.
402   if (const coff_aux_section_definition *Def = ComdatDefs[SectionNumber]) {
403     ComdatDefs[SectionNumber] = nullptr;
404     Symbol *Leader;
405     if (Sym.isExternal()) {
406       std::tie(Leader, Prevailing) =
407           Symtab->addComdat(this, GetName(), Sym.getGeneric());
408     } else {
409       Leader = make<DefinedRegular>(this, /*Name*/ "", false,
410                                     /*IsExternal*/ false, Sym.getGeneric());
411       Prevailing = true;
412     }
413 
414     if (Prevailing) {
415       SectionChunk *C = readSection(SectionNumber, Def, GetName());
416       SparseChunks[SectionNumber] = C;
417       C->Sym = cast<DefinedRegular>(Leader);
418       cast<DefinedRegular>(Leader)->Data = &C->Repl;
419     } else {
420       SparseChunks[SectionNumber] = nullptr;
421     }
422     return Leader;
423   }
424 
425   // Read associative section definitions and prepare to handle the comdat
426   // leader symbol by setting the section's ComdatDefs pointer if we encounter a
427   // non-associative comdat.
428   if (SparseChunks[SectionNumber] == PendingComdat) {
429     if (auto *Def = Sym.getSectionDefinition()) {
430       if (Def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
431         readAssociativeDefinition(Sym, Def);
432       else
433         ComdatDefs[SectionNumber] = Def;
434     }
435   }
436 
437   if (SparseChunks[SectionNumber] == PendingComdat)
438     return None;
439   return createRegular(Sym);
440 }
441 
442 MachineTypes ObjFile::getMachineType() {
443   if (COFFObj)
444     return static_cast<MachineTypes>(COFFObj->getMachine());
445   return IMAGE_FILE_MACHINE_UNKNOWN;
446 }
447 
448 StringRef ltrim1(StringRef S, const char *Chars) {
449   if (!S.empty() && strchr(Chars, S[0]))
450     return S.substr(1);
451   return S;
452 }
453 
454 void ImportFile::parse() {
455   const char *Buf = MB.getBufferStart();
456   const char *End = MB.getBufferEnd();
457   const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
458 
459   // Check if the total size is valid.
460   if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
461     fatal("broken import library");
462 
463   // Read names and create an __imp_ symbol.
464   StringRef Name = Saver.save(StringRef(Buf + sizeof(*Hdr)));
465   StringRef ImpName = Saver.save("__imp_" + Name);
466   const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
467   DLLName = StringRef(NameStart);
468   StringRef ExtName;
469   switch (Hdr->getNameType()) {
470   case IMPORT_ORDINAL:
471     ExtName = "";
472     break;
473   case IMPORT_NAME:
474     ExtName = Name;
475     break;
476   case IMPORT_NAME_NOPREFIX:
477     ExtName = ltrim1(Name, "?@_");
478     break;
479   case IMPORT_NAME_UNDECORATE:
480     ExtName = ltrim1(Name, "?@_");
481     ExtName = ExtName.substr(0, ExtName.find('@'));
482     break;
483   }
484 
485   this->Hdr = Hdr;
486   ExternalName = ExtName;
487 
488   ImpSym = Symtab->addImportData(ImpName, this);
489 
490   if (Hdr->getType() == llvm::COFF::IMPORT_CONST)
491     static_cast<void>(Symtab->addImportData(Name, this));
492 
493   // If type is function, we need to create a thunk which jump to an
494   // address pointed by the __imp_ symbol. (This allows you to call
495   // DLL functions just like regular non-DLL functions.)
496   if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
497     ThunkSym = Symtab->addImportThunk(
498         Name, cast_or_null<DefinedImportData>(ImpSym), Hdr->Machine);
499 }
500 
501 void BitcodeFile::parse() {
502   Obj = check(lto::InputFile::create(MemoryBufferRef(
503       MB.getBuffer(), Saver.save(ParentName + MB.getBufferIdentifier()))));
504   std::vector<std::pair<Symbol *, bool>> Comdat(Obj->getComdatTable().size());
505   for (size_t I = 0; I != Obj->getComdatTable().size(); ++I)
506     Comdat[I] = Symtab->addComdat(this, Saver.save(Obj->getComdatTable()[I]));
507   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) {
508     StringRef SymName = Saver.save(ObjSym.getName());
509     int ComdatIndex = ObjSym.getComdatIndex();
510     Symbol *Sym;
511     if (ObjSym.isUndefined()) {
512       Sym = Symtab->addUndefined(SymName, this, false);
513     } else if (ObjSym.isCommon()) {
514       Sym = Symtab->addCommon(this, SymName, ObjSym.getCommonSize());
515     } else if (ObjSym.isWeak() && ObjSym.isIndirect()) {
516       // Weak external.
517       Sym = Symtab->addUndefined(SymName, this, true);
518       std::string Fallback = ObjSym.getCOFFWeakExternalFallback();
519       Symbol *Alias = Symtab->addUndefined(Saver.save(Fallback));
520       checkAndSetWeakAlias(Symtab, this, Sym, Alias);
521     } else if (ComdatIndex != -1) {
522       if (SymName == Obj->getComdatTable()[ComdatIndex])
523         Sym = Comdat[ComdatIndex].first;
524       else if (Comdat[ComdatIndex].second)
525         Sym = Symtab->addRegular(this, SymName);
526       else
527         Sym = Symtab->addUndefined(SymName, this, false);
528     } else {
529       Sym = Symtab->addRegular(this, SymName);
530     }
531     Symbols.push_back(Sym);
532   }
533   Directives = Obj->getCOFFLinkerOpts();
534 }
535 
536 MachineTypes BitcodeFile::getMachineType() {
537   switch (Triple(Obj->getTargetTriple()).getArch()) {
538   case Triple::x86_64:
539     return AMD64;
540   case Triple::x86:
541     return I386;
542   case Triple::arm:
543     return ARMNT;
544   case Triple::aarch64:
545     return ARM64;
546   default:
547     return IMAGE_FILE_MACHINE_UNKNOWN;
548   }
549 }
550 } // namespace coff
551 } // namespace lld
552 
553 // Returns the last element of a path, which is supposed to be a filename.
554 static StringRef getBasename(StringRef Path) {
555   return sys::path::filename(Path, sys::path::Style::windows);
556 }
557 
558 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
559 std::string lld::toString(const coff::InputFile *File) {
560   if (!File)
561     return "<internal>";
562   if (File->ParentName.empty())
563     return File->getName();
564 
565   return (getBasename(File->ParentName) + "(" + getBasename(File->getName()) +
566           ")")
567       .str();
568 }
569