1 //===- InputFiles.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "InputFiles.h"
10 #include "Chunks.h"
11 #include "Config.h"
12 #include "Driver.h"
13 #include "SymbolTable.h"
14 #include "Symbols.h"
15 #include "lld/Common/ErrorHandler.h"
16 #include "lld/Common/Memory.h"
17 #include "llvm-c/lto.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/BinaryFormat/COFF.h"
22 #include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
23 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
24 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
25 #include "llvm/Object/Binary.h"
26 #include "llvm/Object/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/Support/Path.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include <cstring>
35 #include <system_error>
36 #include <utility>
37 
38 using namespace llvm;
39 using namespace llvm::COFF;
40 using namespace llvm::codeview;
41 using namespace llvm::object;
42 using namespace llvm::support::endian;
43 
44 using llvm::Triple;
45 using llvm::support::ulittle32_t;
46 
47 namespace lld {
48 namespace coff {
49 
50 std::vector<ObjFile *> ObjFile::Instances;
51 std::vector<ImportFile *> ImportFile::Instances;
52 std::vector<BitcodeFile *> BitcodeFile::Instances;
53 
54 /// Checks that Source is compatible with being a weak alias to Target.
55 /// If Source is Undefined and has no weak alias set, makes it a weak
56 /// alias to Target.
57 static void checkAndSetWeakAlias(SymbolTable *Symtab, InputFile *F,
58                                  Symbol *Source, Symbol *Target) {
59   if (auto *U = dyn_cast<Undefined>(Source)) {
60     if (U->WeakAlias && U->WeakAlias != Target) {
61       // Weak aliases as produced by GCC are named in the form
62       // .weak.<weaksymbol>.<othersymbol>, where <othersymbol> is the name
63       // of another symbol emitted near the weak symbol.
64       // Just use the definition from the first object file that defined
65       // this weak symbol.
66       if (Config->MinGW)
67         return;
68       Symtab->reportDuplicate(Source, F);
69     }
70     U->WeakAlias = Target;
71   }
72 }
73 
74 ArchiveFile::ArchiveFile(MemoryBufferRef M) : InputFile(ArchiveKind, M) {}
75 
76 void ArchiveFile::parse() {
77   // Parse a MemoryBufferRef as an archive file.
78   File = CHECK(Archive::create(MB), this);
79 
80   // Read the symbol table to construct Lazy objects.
81   for (const Archive::Symbol &Sym : File->symbols())
82     Symtab->addLazy(this, Sym);
83 }
84 
85 // Returns a buffer pointing to a member file containing a given symbol.
86 void ArchiveFile::addMember(const Archive::Symbol *Sym) {
87   const Archive::Child &C =
88       CHECK(Sym->getMember(),
89             "could not get the member for symbol " + Sym->getName());
90 
91   // Return an empty buffer if we have already returned the same buffer.
92   if (!Seen.insert(C.getChildOffset()).second)
93     return;
94 
95   Driver->enqueueArchiveMember(C, Sym->getName(), getName());
96 }
97 
98 std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
99   std::vector<MemoryBufferRef> V;
100   Error Err = Error::success();
101   for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
102     Archive::Child C =
103         CHECK(COrErr,
104               File->getFileName() + ": could not get the child of the archive");
105     MemoryBufferRef MBRef =
106         CHECK(C.getMemoryBufferRef(),
107               File->getFileName() +
108                   ": could not get the buffer for a child of the archive");
109     V.push_back(MBRef);
110   }
111   if (Err)
112     fatal(File->getFileName() +
113           ": Archive::children failed: " + toString(std::move(Err)));
114   return V;
115 }
116 
117 void ObjFile::parse() {
118   // Parse a memory buffer as a COFF file.
119   std::unique_ptr<Binary> Bin = CHECK(createBinary(MB), this);
120 
121   if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
122     Bin.release();
123     COFFObj.reset(Obj);
124   } else {
125     fatal(toString(this) + " is not a COFF file");
126   }
127 
128   // Read section and symbol tables.
129   initializeChunks();
130   initializeSymbols();
131   initializeFlags();
132 }
133 
134 const coff_section* ObjFile::getSection(uint32_t I) {
135   const coff_section *Sec;
136   if (auto EC = COFFObj->getSection(I, Sec))
137     fatal("getSection failed: #" + Twine(I) + ": " + EC.message());
138   return Sec;
139 }
140 
141 // We set SectionChunk pointers in the SparseChunks vector to this value
142 // temporarily to mark comdat sections as having an unknown resolution. As we
143 // walk the object file's symbol table, once we visit either a leader symbol or
144 // an associative section definition together with the parent comdat's leader,
145 // we set the pointer to either nullptr (to mark the section as discarded) or a
146 // valid SectionChunk for that section.
147 static SectionChunk *const PendingComdat = reinterpret_cast<SectionChunk *>(1);
148 
149 void ObjFile::initializeChunks() {
150   uint32_t NumSections = COFFObj->getNumberOfSections();
151   Chunks.reserve(NumSections);
152   SparseChunks.resize(NumSections + 1);
153   for (uint32_t I = 1; I < NumSections + 1; ++I) {
154     const coff_section *Sec = getSection(I);
155     if (Sec->Characteristics & IMAGE_SCN_LNK_COMDAT)
156       SparseChunks[I] = PendingComdat;
157     else
158       SparseChunks[I] = readSection(I, nullptr, "");
159   }
160 }
161 
162 SectionChunk *ObjFile::readSection(uint32_t SectionNumber,
163                                    const coff_aux_section_definition *Def,
164                                    StringRef LeaderName) {
165   const coff_section *Sec = getSection(SectionNumber);
166 
167   StringRef Name;
168   if (auto EC = COFFObj->getSectionName(Sec, Name))
169     fatal("getSectionName failed: #" + Twine(SectionNumber) + ": " +
170           EC.message());
171 
172   if (Name == ".drectve") {
173     ArrayRef<uint8_t> Data;
174     COFFObj->getSectionContents(Sec, Data);
175     Directives = std::string((const char *)Data.data(), Data.size());
176     return nullptr;
177   }
178 
179   if (Name == ".llvm_addrsig") {
180     AddrsigSec = Sec;
181     return nullptr;
182   }
183 
184   // Object files may have DWARF debug info or MS CodeView debug info
185   // (or both).
186   //
187   // DWARF sections don't need any special handling from the perspective
188   // of the linker; they are just a data section containing relocations.
189   // We can just link them to complete debug info.
190   //
191   // CodeView needs linker support. We need to interpret debug info,
192   // and then write it to a separate .pdb file.
193 
194   // Ignore DWARF debug info unless /debug is given.
195   if (!Config->Debug && Name.startswith(".debug_"))
196     return nullptr;
197 
198   if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
199     return nullptr;
200   auto *C = make<SectionChunk>(this, Sec);
201   if (Def)
202     C->Checksum = Def->CheckSum;
203 
204   // CodeView sections are stored to a different vector because they are not
205   // linked in the regular manner.
206   if (C->isCodeView())
207     DebugChunks.push_back(C);
208   else if (Config->GuardCF != GuardCFLevel::Off && Name == ".gfids$y")
209     GuardFidChunks.push_back(C);
210   else if (Config->GuardCF != GuardCFLevel::Off && Name == ".gljmp$y")
211     GuardLJmpChunks.push_back(C);
212   else if (Name == ".sxdata")
213     SXDataChunks.push_back(C);
214   else if (Config->TailMerge && Sec->NumberOfRelocations == 0 &&
215            Name == ".rdata" && LeaderName.startswith("??_C@"))
216     // COFF sections that look like string literal sections (i.e. no
217     // relocations, in .rdata, leader symbol name matches the MSVC name mangling
218     // for string literals) are subject to string tail merging.
219     MergeChunk::addSection(C);
220   else
221     Chunks.push_back(C);
222 
223   return C;
224 }
225 
226 void ObjFile::readAssociativeDefinition(
227     COFFSymbolRef Sym, const coff_aux_section_definition *Def) {
228   readAssociativeDefinition(Sym, Def, Def->getNumber(Sym.isBigObj()));
229 }
230 
231 void ObjFile::readAssociativeDefinition(COFFSymbolRef Sym,
232                                         const coff_aux_section_definition *Def,
233                                         uint32_t ParentIndex) {
234   SectionChunk *Parent = SparseChunks[ParentIndex];
235   int32_t SectionNumber = Sym.getSectionNumber();
236 
237   auto Diag = [&]() {
238     StringRef Name, ParentName;
239     COFFObj->getSymbolName(Sym, Name);
240 
241     const coff_section *ParentSec = getSection(ParentIndex);
242     COFFObj->getSectionName(ParentSec, ParentName);
243     error(toString(this) + ": associative comdat " + Name + " (sec " +
244           Twine(SectionNumber) + ") has invalid reference to section " +
245           ParentName + " (sec " + Twine(ParentIndex) + ")");
246   };
247 
248   if (Parent == PendingComdat) {
249     // This can happen if an associative comdat refers to another associative
250     // comdat that appears after it (invalid per COFF spec) or to a section
251     // without any symbols.
252     Diag();
253     return;
254   }
255 
256   // Check whether the parent is prevailing. If it is, so are we, and we read
257   // the section; otherwise mark it as discarded.
258   if (Parent) {
259     SectionChunk *C = readSection(SectionNumber, Def, "");
260     SparseChunks[SectionNumber] = C;
261     if (C) {
262       C->Selection = IMAGE_COMDAT_SELECT_ASSOCIATIVE;
263       Parent->addAssociative(C);
264     }
265   } else {
266     SparseChunks[SectionNumber] = nullptr;
267   }
268 }
269 
270 void ObjFile::recordPrevailingSymbolForMingw(
271     COFFSymbolRef Sym, DenseMap<StringRef, uint32_t> &PrevailingSectionMap) {
272   // For comdat symbols in executable sections, where this is the copy
273   // of the section chunk we actually include instead of discarding it,
274   // add the symbol to a map to allow using it for implicitly
275   // associating .[px]data$<func> sections to it.
276   int32_t SectionNumber = Sym.getSectionNumber();
277   SectionChunk *SC = SparseChunks[SectionNumber];
278   if (SC && SC->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE) {
279     StringRef Name;
280     COFFObj->getSymbolName(Sym, Name);
281     PrevailingSectionMap[Name] = SectionNumber;
282   }
283 }
284 
285 void ObjFile::maybeAssociateSEHForMingw(
286     COFFSymbolRef Sym, const coff_aux_section_definition *Def,
287     const DenseMap<StringRef, uint32_t> &PrevailingSectionMap) {
288   StringRef Name;
289   COFFObj->getSymbolName(Sym, Name);
290   if (Name.consume_front(".pdata$") || Name.consume_front(".xdata$")) {
291     // For MinGW, treat .[px]data$<func> as implicitly associative to
292     // the symbol <func>.
293     auto ParentSym = PrevailingSectionMap.find(Name);
294     if (ParentSym != PrevailingSectionMap.end())
295       readAssociativeDefinition(Sym, Def, ParentSym->second);
296   }
297 }
298 
299 Symbol *ObjFile::createRegular(COFFSymbolRef Sym) {
300   SectionChunk *SC = SparseChunks[Sym.getSectionNumber()];
301   if (Sym.isExternal()) {
302     StringRef Name;
303     COFFObj->getSymbolName(Sym, Name);
304     if (SC)
305       return Symtab->addRegular(this, Name, Sym.getGeneric(), SC);
306     // For MinGW symbols named .weak.* that point to a discarded section,
307     // don't create an Undefined symbol. If nothing ever refers to the symbol,
308     // everything should be fine. If something actually refers to the symbol
309     // (e.g. the undefined weak alias), linking will fail due to undefined
310     // references at the end.
311     if (Config->MinGW && Name.startswith(".weak."))
312       return nullptr;
313     return Symtab->addUndefined(Name, this, false);
314   }
315   if (SC)
316     return make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
317                                 /*IsExternal*/ false, Sym.getGeneric(), SC);
318   return nullptr;
319 }
320 
321 void ObjFile::initializeSymbols() {
322   uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
323   Symbols.resize(NumSymbols);
324 
325   SmallVector<std::pair<Symbol *, uint32_t>, 8> WeakAliases;
326   std::vector<uint32_t> PendingIndexes;
327   PendingIndexes.reserve(NumSymbols);
328 
329   DenseMap<StringRef, uint32_t> PrevailingSectionMap;
330   std::vector<const coff_aux_section_definition *> ComdatDefs(
331       COFFObj->getNumberOfSections() + 1);
332 
333   for (uint32_t I = 0; I < NumSymbols; ++I) {
334     COFFSymbolRef COFFSym = check(COFFObj->getSymbol(I));
335     bool PrevailingComdat;
336     if (COFFSym.isUndefined()) {
337       Symbols[I] = createUndefined(COFFSym);
338     } else if (COFFSym.isWeakExternal()) {
339       Symbols[I] = createUndefined(COFFSym);
340       uint32_t TagIndex = COFFSym.getAux<coff_aux_weak_external>()->TagIndex;
341       WeakAliases.emplace_back(Symbols[I], TagIndex);
342     } else if (Optional<Symbol *> OptSym =
343                    createDefined(COFFSym, ComdatDefs, PrevailingComdat)) {
344       Symbols[I] = *OptSym;
345       if (Config->MinGW && PrevailingComdat)
346         recordPrevailingSymbolForMingw(COFFSym, PrevailingSectionMap);
347     } else {
348       // createDefined() returns None if a symbol belongs to a section that
349       // was pending at the point when the symbol was read. This can happen in
350       // two cases:
351       // 1) section definition symbol for a comdat leader;
352       // 2) symbol belongs to a comdat section associated with another section.
353       // In both of these cases, we can expect the section to be resolved by
354       // the time we finish visiting the remaining symbols in the symbol
355       // table. So we postpone the handling of this symbol until that time.
356       PendingIndexes.push_back(I);
357     }
358     I += COFFSym.getNumberOfAuxSymbols();
359   }
360 
361   for (uint32_t I : PendingIndexes) {
362     COFFSymbolRef Sym = check(COFFObj->getSymbol(I));
363     if (const coff_aux_section_definition *Def = Sym.getSectionDefinition()) {
364       if (Def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
365         readAssociativeDefinition(Sym, Def);
366       else if (Config->MinGW)
367         maybeAssociateSEHForMingw(Sym, Def, PrevailingSectionMap);
368     }
369     if (SparseChunks[Sym.getSectionNumber()] == PendingComdat) {
370       StringRef Name;
371       COFFObj->getSymbolName(Sym, Name);
372       log("comdat section " + Name +
373           " without leader and unassociated, discarding");
374       continue;
375     }
376     Symbols[I] = createRegular(Sym);
377   }
378 
379   for (auto &KV : WeakAliases) {
380     Symbol *Sym = KV.first;
381     uint32_t Idx = KV.second;
382     checkAndSetWeakAlias(Symtab, this, Sym, Symbols[Idx]);
383   }
384 }
385 
386 Symbol *ObjFile::createUndefined(COFFSymbolRef Sym) {
387   StringRef Name;
388   COFFObj->getSymbolName(Sym, Name);
389   return Symtab->addUndefined(Name, this, Sym.isWeakExternal());
390 }
391 
392 void ObjFile::handleComdatSelection(COFFSymbolRef Sym, COMDATType &Selection,
393                                     bool &Prevailing, DefinedRegular *Leader) {
394   if (Prevailing)
395     return;
396   // There's already an existing comdat for this symbol: `Leader`.
397   // Use the comdats's selection field to determine if the new
398   // symbol in `Sym` should be discarded, produce a duplicate symbol
399   // error, etc.
400 
401   SectionChunk *LeaderChunk = nullptr;
402   COMDATType LeaderSelection = IMAGE_COMDAT_SELECT_ANY;
403 
404   if (Leader->Data) {
405     LeaderChunk = Leader->getChunk();
406     LeaderSelection = LeaderChunk->Selection;
407   } else {
408     // FIXME: comdats from LTO files don't know their selection; treat them
409     // as "any".
410     Selection = LeaderSelection;
411   }
412 
413   if ((Selection == IMAGE_COMDAT_SELECT_ANY &&
414        LeaderSelection == IMAGE_COMDAT_SELECT_LARGEST) ||
415       (Selection == IMAGE_COMDAT_SELECT_LARGEST &&
416        LeaderSelection == IMAGE_COMDAT_SELECT_ANY)) {
417     // cl.exe picks "any" for vftables when building with /GR- and
418     // "largest" when building with /GR. To be able to link object files
419     // compiled with each flag, "any" and "largest" are merged as "largest".
420     LeaderSelection = Selection = IMAGE_COMDAT_SELECT_LARGEST;
421   }
422 
423   // Other than that, comdat selections must match.  This is a bit more
424   // strict than link.exe which allows merging "any" and "largest" if "any"
425   // is the first symbol the linker sees, and it allows merging "largest"
426   // with everything (!) if "largest" is the first symbol the linker sees.
427   // Making this symmetric independent of which selection is seen first
428   // seems better though.
429   // (This behavior matches ModuleLinker::getComdatResult().)
430   if (Selection != LeaderSelection) {
431     log(("conflicting comdat type for " + toString(*Leader) + ": " +
432          Twine((int)LeaderSelection) + " in " + toString(Leader->getFile()) +
433          " and " + Twine((int)Selection) + " in " + toString(this))
434             .str());
435     Symtab->reportDuplicate(Leader, this);
436     return;
437   }
438 
439   switch (Selection) {
440   case IMAGE_COMDAT_SELECT_NODUPLICATES:
441     Symtab->reportDuplicate(Leader, this);
442     break;
443 
444   case IMAGE_COMDAT_SELECT_ANY:
445     // Nothing to do.
446     break;
447 
448   case IMAGE_COMDAT_SELECT_SAME_SIZE:
449     if (LeaderChunk->getSize() != getSection(Sym)->SizeOfRawData)
450       Symtab->reportDuplicate(Leader, this);
451     break;
452 
453   case IMAGE_COMDAT_SELECT_EXACT_MATCH: {
454     SectionChunk NewChunk(this, getSection(Sym));
455     // link.exe only compares section contents here and doesn't complain
456     // if the two comdat sections have e.g. different alignment.
457     // Match that.
458     if (LeaderChunk->getContents() != NewChunk.getContents())
459       Symtab->reportDuplicate(Leader, this);
460     break;
461   }
462 
463   case IMAGE_COMDAT_SELECT_ASSOCIATIVE:
464     // createDefined() is never called for IMAGE_COMDAT_SELECT_ASSOCIATIVE.
465     // (This means lld-link doesn't produce duplicate symbol errors for
466     // associative comdats while link.exe does, but associate comdats
467     // are never extern in practice.)
468     llvm_unreachable("createDefined not called for associative comdats");
469 
470   case IMAGE_COMDAT_SELECT_LARGEST:
471     if (LeaderChunk->getSize() < getSection(Sym)->SizeOfRawData) {
472       // Replace the existing comdat symbol with the new one.
473       StringRef Name;
474       COFFObj->getSymbolName(Sym, Name);
475       // FIXME: This is incorrect: With /opt:noref, the previous sections
476       // make it into the final executable as well. Correct handling would
477       // be to undo reading of the whole old section that's being replaced,
478       // or doing one pass that determines what the final largest comdat
479       // is for all IMAGE_COMDAT_SELECT_LARGEST comdats and then reading
480       // only the largest one.
481       replaceSymbol<DefinedRegular>(Leader, this, Name, /*IsCOMDAT*/ true,
482                                     /*IsExternal*/ true, Sym.getGeneric(),
483                                     nullptr);
484       Prevailing = true;
485     }
486     break;
487 
488   case IMAGE_COMDAT_SELECT_NEWEST:
489     llvm_unreachable("should have been rejected earlier");
490   }
491 }
492 
493 Optional<Symbol *> ObjFile::createDefined(
494     COFFSymbolRef Sym,
495     std::vector<const coff_aux_section_definition *> &ComdatDefs,
496     bool &Prevailing) {
497   Prevailing = false;
498   auto GetName = [&]() {
499     StringRef S;
500     COFFObj->getSymbolName(Sym, S);
501     return S;
502   };
503 
504   if (Sym.isCommon()) {
505     auto *C = make<CommonChunk>(Sym);
506     Chunks.push_back(C);
507     return Symtab->addCommon(this, GetName(), Sym.getValue(), Sym.getGeneric(),
508                              C);
509   }
510 
511   if (Sym.isAbsolute()) {
512     StringRef Name = GetName();
513 
514     // Skip special symbols.
515     if (Name == "@comp.id")
516       return nullptr;
517     if (Name == "@feat.00") {
518       Feat00Flags = Sym.getValue();
519       return nullptr;
520     }
521 
522     if (Sym.isExternal())
523       return Symtab->addAbsolute(Name, Sym);
524     return make<DefinedAbsolute>(Name, Sym);
525   }
526 
527   int32_t SectionNumber = Sym.getSectionNumber();
528   if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
529     return nullptr;
530 
531   if (llvm::COFF::isReservedSectionNumber(SectionNumber))
532     fatal(toString(this) + ": " + GetName() +
533           " should not refer to special section " + Twine(SectionNumber));
534 
535   if ((uint32_t)SectionNumber >= SparseChunks.size())
536     fatal(toString(this) + ": " + GetName() +
537           " should not refer to non-existent section " + Twine(SectionNumber));
538 
539   // Comdat handling.
540   // A comdat symbol consists of two symbol table entries.
541   // The first symbol entry has the name of the section (e.g. .text), fixed
542   // values for the other fields, and one auxilliary record.
543   // The second symbol entry has the name of the comdat symbol, called the
544   // "comdat leader".
545   // When this function is called for the first symbol entry of a comdat,
546   // it sets ComdatDefs and returns None, and when it's called for the second
547   // symbol entry it reads ComdatDefs and then sets it back to nullptr.
548 
549   // Handle comdat leader.
550   if (const coff_aux_section_definition *Def = ComdatDefs[SectionNumber]) {
551     ComdatDefs[SectionNumber] = nullptr;
552     DefinedRegular *Leader;
553 
554     if (Sym.isExternal()) {
555       std::tie(Leader, Prevailing) =
556           Symtab->addComdat(this, GetName(), Sym.getGeneric());
557     } else {
558       Leader = make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
559                                     /*IsExternal*/ false, Sym.getGeneric());
560       Prevailing = true;
561     }
562 
563     if (Def->Selection < (int)IMAGE_COMDAT_SELECT_NODUPLICATES ||
564         // Intentionally ends at IMAGE_COMDAT_SELECT_LARGEST: link.exe
565         // doesn't understand IMAGE_COMDAT_SELECT_NEWEST either.
566         Def->Selection > (int)IMAGE_COMDAT_SELECT_LARGEST) {
567       fatal("unknown comdat type " + std::to_string((int)Def->Selection) +
568             " for " + GetName() + " in " + toString(this));
569     }
570     COMDATType Selection = (COMDATType)Def->Selection;
571 
572     if (Leader->isCOMDAT())
573       handleComdatSelection(Sym, Selection, Prevailing, Leader);
574 
575     if (Prevailing) {
576       SectionChunk *C = readSection(SectionNumber, Def, GetName());
577       SparseChunks[SectionNumber] = C;
578       C->Sym = cast<DefinedRegular>(Leader);
579       C->Selection = Selection;
580       cast<DefinedRegular>(Leader)->Data = &C->Repl;
581     } else {
582       SparseChunks[SectionNumber] = nullptr;
583     }
584     return Leader;
585   }
586 
587   // Prepare to handle the comdat leader symbol by setting the section's
588   // ComdatDefs pointer if we encounter a non-associative comdat.
589   if (SparseChunks[SectionNumber] == PendingComdat) {
590     if (const coff_aux_section_definition *Def = Sym.getSectionDefinition()) {
591       if (Def->Selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE)
592         ComdatDefs[SectionNumber] = Def;
593     }
594     return None;
595   }
596 
597   return createRegular(Sym);
598 }
599 
600 MachineTypes ObjFile::getMachineType() {
601   if (COFFObj)
602     return static_cast<MachineTypes>(COFFObj->getMachine());
603   return IMAGE_FILE_MACHINE_UNKNOWN;
604 }
605 
606 ArrayRef<uint8_t> ObjFile::getDebugSection(StringRef SecName) {
607   if (SectionChunk *Sec = SectionChunk::findByName(DebugChunks, SecName))
608     return Sec->consumeDebugMagic();
609   return {};
610 }
611 
612 // OBJ files systematically store critical informations in a .debug$S stream,
613 // even if the TU was compiled with no debug info. At least two records are
614 // always there. S_OBJNAME stores a 32-bit signature, which is loaded into the
615 // PCHSignature member. S_COMPILE3 stores compile-time cmd-line flags. This is
616 // currently used to initialize the HotPatchable member.
617 void ObjFile::initializeFlags() {
618   ArrayRef<uint8_t> Data = getDebugSection(".debug$S");
619   if (Data.empty())
620     return;
621 
622   DebugSubsectionArray Subsections;
623 
624   BinaryStreamReader Reader(Data, support::little);
625   ExitOnError ExitOnErr;
626   ExitOnErr(Reader.readArray(Subsections, Data.size()));
627 
628   for (const DebugSubsectionRecord &SS : Subsections) {
629     if (SS.kind() != DebugSubsectionKind::Symbols)
630       continue;
631 
632     unsigned Offset = 0;
633 
634     // Only parse the first two records. We are only looking for S_OBJNAME
635     // and S_COMPILE3, and they usually appear at the beginning of the
636     // stream.
637     for (unsigned I = 0; I < 2; ++I) {
638       Expected<CVSymbol> Sym = readSymbolFromStream(SS.getRecordData(), Offset);
639       if (!Sym) {
640         consumeError(Sym.takeError());
641         return;
642       }
643       if (Sym->kind() == SymbolKind::S_COMPILE3) {
644         auto CS =
645             cantFail(SymbolDeserializer::deserializeAs<Compile3Sym>(Sym.get()));
646         HotPatchable =
647             (CS.Flags & CompileSym3Flags::HotPatch) != CompileSym3Flags::None;
648       }
649       if (Sym->kind() == SymbolKind::S_OBJNAME) {
650         auto ObjName = cantFail(SymbolDeserializer::deserializeAs<ObjNameSym>(
651             Sym.get()));
652         PCHSignature = ObjName.Signature;
653       }
654       Offset += Sym->length();
655     }
656   }
657 }
658 
659 StringRef ltrim1(StringRef S, const char *Chars) {
660   if (!S.empty() && strchr(Chars, S[0]))
661     return S.substr(1);
662   return S;
663 }
664 
665 void ImportFile::parse() {
666   const char *Buf = MB.getBufferStart();
667   const char *End = MB.getBufferEnd();
668   const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
669 
670   // Check if the total size is valid.
671   if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
672     fatal("broken import library");
673 
674   // Read names and create an __imp_ symbol.
675   StringRef Name = Saver.save(StringRef(Buf + sizeof(*Hdr)));
676   StringRef ImpName = Saver.save("__imp_" + Name);
677   const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
678   DLLName = StringRef(NameStart);
679   StringRef ExtName;
680   switch (Hdr->getNameType()) {
681   case IMPORT_ORDINAL:
682     ExtName = "";
683     break;
684   case IMPORT_NAME:
685     ExtName = Name;
686     break;
687   case IMPORT_NAME_NOPREFIX:
688     ExtName = ltrim1(Name, "?@_");
689     break;
690   case IMPORT_NAME_UNDECORATE:
691     ExtName = ltrim1(Name, "?@_");
692     ExtName = ExtName.substr(0, ExtName.find('@'));
693     break;
694   }
695 
696   this->Hdr = Hdr;
697   ExternalName = ExtName;
698 
699   ImpSym = Symtab->addImportData(ImpName, this);
700   // If this was a duplicate, we logged an error but may continue;
701   // in this case, ImpSym is nullptr.
702   if (!ImpSym)
703     return;
704 
705   if (Hdr->getType() == llvm::COFF::IMPORT_CONST)
706     static_cast<void>(Symtab->addImportData(Name, this));
707 
708   // If type is function, we need to create a thunk which jump to an
709   // address pointed by the __imp_ symbol. (This allows you to call
710   // DLL functions just like regular non-DLL functions.)
711   if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
712     ThunkSym = Symtab->addImportThunk(
713         Name, cast_or_null<DefinedImportData>(ImpSym), Hdr->Machine);
714 }
715 
716 void BitcodeFile::parse() {
717   Obj = check(lto::InputFile::create(MemoryBufferRef(
718       MB.getBuffer(), Saver.save(ParentName + MB.getBufferIdentifier()))));
719   std::vector<std::pair<Symbol *, bool>> Comdat(Obj->getComdatTable().size());
720   for (size_t I = 0; I != Obj->getComdatTable().size(); ++I)
721     // FIXME: lto::InputFile doesn't keep enough data to do correct comdat
722     // selection handling.
723     Comdat[I] = Symtab->addComdat(this, Saver.save(Obj->getComdatTable()[I]));
724   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) {
725     StringRef SymName = Saver.save(ObjSym.getName());
726     int ComdatIndex = ObjSym.getComdatIndex();
727     Symbol *Sym;
728     if (ObjSym.isUndefined()) {
729       Sym = Symtab->addUndefined(SymName, this, false);
730     } else if (ObjSym.isCommon()) {
731       Sym = Symtab->addCommon(this, SymName, ObjSym.getCommonSize());
732     } else if (ObjSym.isWeak() && ObjSym.isIndirect()) {
733       // Weak external.
734       Sym = Symtab->addUndefined(SymName, this, true);
735       std::string Fallback = ObjSym.getCOFFWeakExternalFallback();
736       Symbol *Alias = Symtab->addUndefined(Saver.save(Fallback));
737       checkAndSetWeakAlias(Symtab, this, Sym, Alias);
738     } else if (ComdatIndex != -1) {
739       if (SymName == Obj->getComdatTable()[ComdatIndex])
740         Sym = Comdat[ComdatIndex].first;
741       else if (Comdat[ComdatIndex].second)
742         Sym = Symtab->addRegular(this, SymName);
743       else
744         Sym = Symtab->addUndefined(SymName, this, false);
745     } else {
746       Sym = Symtab->addRegular(this, SymName);
747     }
748     Symbols.push_back(Sym);
749     if (ObjSym.isUsed())
750       Config->GCRoot.push_back(Sym);
751   }
752   Directives = Obj->getCOFFLinkerOpts();
753 }
754 
755 MachineTypes BitcodeFile::getMachineType() {
756   switch (Triple(Obj->getTargetTriple()).getArch()) {
757   case Triple::x86_64:
758     return AMD64;
759   case Triple::x86:
760     return I386;
761   case Triple::arm:
762     return ARMNT;
763   case Triple::aarch64:
764     return ARM64;
765   default:
766     return IMAGE_FILE_MACHINE_UNKNOWN;
767   }
768 }
769 } // namespace coff
770 } // namespace lld
771 
772 // Returns the last element of a path, which is supposed to be a filename.
773 static StringRef getBasename(StringRef Path) {
774   return sys::path::filename(Path, sys::path::Style::windows);
775 }
776 
777 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
778 std::string lld::toString(const coff::InputFile *File) {
779   if (!File)
780     return "<internal>";
781   if (File->ParentName.empty())
782     return File->getName();
783 
784   return (getBasename(File->ParentName) + "(" + getBasename(File->getName()) +
785           ")")
786       .str();
787 }
788