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 "DebugTypes.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/DebugInfo/CodeView/DebugSubsectionRecord.h"
24 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
25 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
26 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
27 #include "llvm/Object/Binary.h"
28 #include "llvm/Object/COFF.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/Endian.h"
31 #include "llvm/Support/Error.h"
32 #include "llvm/Support/ErrorOr.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include <cstring>
37 #include <system_error>
38 #include <utility>
39 
40 using namespace llvm;
41 using namespace llvm::COFF;
42 using namespace llvm::codeview;
43 using namespace llvm::object;
44 using namespace llvm::support::endian;
45 
46 using llvm::Triple;
47 using llvm::support::ulittle32_t;
48 
49 namespace lld {
50 namespace coff {
51 
52 std::vector<ObjFile *> ObjFile::instances;
53 std::vector<ImportFile *> ImportFile::instances;
54 std::vector<BitcodeFile *> BitcodeFile::instances;
55 
56 /// Checks that Source is compatible with being a weak alias to Target.
57 /// If Source is Undefined and has no weak alias set, makes it a weak
58 /// alias to Target.
59 static void checkAndSetWeakAlias(SymbolTable *symtab, InputFile *f,
60                                  Symbol *source, Symbol *target) {
61   if (auto *u = dyn_cast<Undefined>(source)) {
62     if (u->weakAlias && u->weakAlias != target) {
63       // Weak aliases as produced by GCC are named in the form
64       // .weak.<weaksymbol>.<othersymbol>, where <othersymbol> is the name
65       // of another symbol emitted near the weak symbol.
66       // Just use the definition from the first object file that defined
67       // this weak symbol.
68       if (config->mingw)
69         return;
70       symtab->reportDuplicate(source, f);
71     }
72     u->weakAlias = target;
73   }
74 }
75 
76 static bool ignoredSymbolName(StringRef name) {
77   return name == "@feat.00" || name == "@comp.id";
78 }
79 
80 ArchiveFile::ArchiveFile(MemoryBufferRef m) : InputFile(ArchiveKind, m) {}
81 
82 void ArchiveFile::parse() {
83   // Parse a MemoryBufferRef as an archive file.
84   file = CHECK(Archive::create(mb), this);
85 
86   // Read the symbol table to construct Lazy objects.
87   for (const Archive::Symbol &sym : file->symbols())
88     symtab->addLazyArchive(this, sym);
89 }
90 
91 // Returns a buffer pointing to a member file containing a given symbol.
92 void ArchiveFile::addMember(const Archive::Symbol &sym) {
93   const Archive::Child &c =
94       CHECK(sym.getMember(),
95             "could not get the member for symbol " + toCOFFString(sym));
96 
97   // Return an empty buffer if we have already returned the same buffer.
98   if (!seen.insert(c.getChildOffset()).second)
99     return;
100 
101   driver->enqueueArchiveMember(c, sym, getName());
102 }
103 
104 std::vector<MemoryBufferRef> getArchiveMembers(Archive *file) {
105   std::vector<MemoryBufferRef> v;
106   Error err = Error::success();
107   for (const ErrorOr<Archive::Child> &cOrErr : file->children(err)) {
108     Archive::Child c =
109         CHECK(cOrErr,
110               file->getFileName() + ": could not get the child of the archive");
111     MemoryBufferRef mbref =
112         CHECK(c.getMemoryBufferRef(),
113               file->getFileName() +
114                   ": could not get the buffer for a child of the archive");
115     v.push_back(mbref);
116   }
117   if (err)
118     fatal(file->getFileName() +
119           ": Archive::children failed: " + toString(std::move(err)));
120   return v;
121 }
122 
123 void LazyObjFile::fetch() {
124   if (mb.getBuffer().empty())
125     return;
126 
127   InputFile *file;
128   if (isBitcode(mb))
129     file = make<BitcodeFile>(mb, "", 0, std::move(symbols));
130   else
131     file = make<ObjFile>(mb, std::move(symbols));
132   mb = {};
133   symtab->addFile(file);
134 }
135 
136 void LazyObjFile::parse() {
137   if (isBitcode(this->mb)) {
138     // Bitcode file.
139     std::unique_ptr<lto::InputFile> obj =
140         CHECK(lto::InputFile::create(this->mb), this);
141     for (const lto::InputFile::Symbol &sym : obj->symbols()) {
142       if (!sym.isUndefined())
143         symtab->addLazyObject(this, sym.getName());
144     }
145     return;
146   }
147 
148   // Native object file.
149   std::unique_ptr<Binary> coffObjPtr = CHECK(createBinary(mb), this);
150   COFFObjectFile *coffObj = cast<COFFObjectFile>(coffObjPtr.get());
151   uint32_t numSymbols = coffObj->getNumberOfSymbols();
152   for (uint32_t i = 0; i < numSymbols; ++i) {
153     COFFSymbolRef coffSym = check(coffObj->getSymbol(i));
154     if (coffSym.isUndefined() || !coffSym.isExternal() ||
155         coffSym.isWeakExternal())
156       continue;
157     StringRef name;
158     coffObj->getSymbolName(coffSym, name);
159     if (coffSym.isAbsolute() && ignoredSymbolName(name))
160       continue;
161     symtab->addLazyObject(this, name);
162     i += coffSym.getNumberOfAuxSymbols();
163   }
164 }
165 
166 void ObjFile::parse() {
167   // Parse a memory buffer as a COFF file.
168   std::unique_ptr<Binary> bin = CHECK(createBinary(mb), this);
169 
170   if (auto *obj = dyn_cast<COFFObjectFile>(bin.get())) {
171     bin.release();
172     coffObj.reset(obj);
173   } else {
174     fatal(toString(this) + " is not a COFF file");
175   }
176 
177   // Read section and symbol tables.
178   initializeChunks();
179   initializeSymbols();
180   initializeFlags();
181   initializeDependencies();
182 }
183 
184 const coff_section* ObjFile::getSection(uint32_t i) {
185   const coff_section *sec;
186   if (auto ec = coffObj->getSection(i, sec))
187     fatal("getSection failed: #" + Twine(i) + ": " + ec.message());
188   return sec;
189 }
190 
191 // We set SectionChunk pointers in the SparseChunks vector to this value
192 // temporarily to mark comdat sections as having an unknown resolution. As we
193 // walk the object file's symbol table, once we visit either a leader symbol or
194 // an associative section definition together with the parent comdat's leader,
195 // we set the pointer to either nullptr (to mark the section as discarded) or a
196 // valid SectionChunk for that section.
197 static SectionChunk *const pendingComdat = reinterpret_cast<SectionChunk *>(1);
198 
199 void ObjFile::initializeChunks() {
200   uint32_t numSections = coffObj->getNumberOfSections();
201   chunks.reserve(numSections);
202   sparseChunks.resize(numSections + 1);
203   for (uint32_t i = 1; i < numSections + 1; ++i) {
204     const coff_section *sec = getSection(i);
205     if (sec->Characteristics & IMAGE_SCN_LNK_COMDAT)
206       sparseChunks[i] = pendingComdat;
207     else
208       sparseChunks[i] = readSection(i, nullptr, "");
209   }
210 }
211 
212 SectionChunk *ObjFile::readSection(uint32_t sectionNumber,
213                                    const coff_aux_section_definition *def,
214                                    StringRef leaderName) {
215   const coff_section *sec = getSection(sectionNumber);
216 
217   StringRef name;
218   if (Expected<StringRef> e = coffObj->getSectionName(sec))
219     name = *e;
220   else
221     fatal("getSectionName failed: #" + Twine(sectionNumber) + ": " +
222           toString(e.takeError()));
223 
224   if (name == ".drectve") {
225     ArrayRef<uint8_t> data;
226     cantFail(coffObj->getSectionContents(sec, data));
227     directives = StringRef((const char *)data.data(), data.size());
228     return nullptr;
229   }
230 
231   if (name == ".llvm_addrsig") {
232     addrsigSec = sec;
233     return nullptr;
234   }
235 
236   // Object files may have DWARF debug info or MS CodeView debug info
237   // (or both).
238   //
239   // DWARF sections don't need any special handling from the perspective
240   // of the linker; they are just a data section containing relocations.
241   // We can just link them to complete debug info.
242   //
243   // CodeView needs linker support. We need to interpret debug info,
244   // and then write it to a separate .pdb file.
245 
246   // Ignore DWARF debug info unless /debug is given.
247   if (!config->debug && name.startswith(".debug_"))
248     return nullptr;
249 
250   if (sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
251     return nullptr;
252   auto *c = make<SectionChunk>(this, sec);
253   if (def)
254     c->checksum = def->CheckSum;
255 
256   // CodeView sections are stored to a different vector because they are not
257   // linked in the regular manner.
258   if (c->isCodeView())
259     debugChunks.push_back(c);
260   else if (name == ".gfids$y")
261     guardFidChunks.push_back(c);
262   else if (name == ".gljmp$y")
263     guardLJmpChunks.push_back(c);
264   else if (name == ".sxdata")
265     sXDataChunks.push_back(c);
266   else if (config->tailMerge && sec->NumberOfRelocations == 0 &&
267            name == ".rdata" && leaderName.startswith("??_C@"))
268     // COFF sections that look like string literal sections (i.e. no
269     // relocations, in .rdata, leader symbol name matches the MSVC name mangling
270     // for string literals) are subject to string tail merging.
271     MergeChunk::addSection(c);
272   else if (name == ".rsrc" || name.startswith(".rsrc$"))
273     resourceChunks.push_back(c);
274   else
275     chunks.push_back(c);
276 
277   return c;
278 }
279 
280 void ObjFile::includeResourceChunks() {
281   chunks.insert(chunks.end(), resourceChunks.begin(), resourceChunks.end());
282 }
283 
284 void ObjFile::readAssociativeDefinition(
285     COFFSymbolRef sym, const coff_aux_section_definition *def) {
286   readAssociativeDefinition(sym, def, def->getNumber(sym.isBigObj()));
287 }
288 
289 void ObjFile::readAssociativeDefinition(COFFSymbolRef sym,
290                                         const coff_aux_section_definition *def,
291                                         uint32_t parentIndex) {
292   SectionChunk *parent = sparseChunks[parentIndex];
293   int32_t sectionNumber = sym.getSectionNumber();
294 
295   auto diag = [&]() {
296     StringRef name, parentName;
297     coffObj->getSymbolName(sym, name);
298 
299     const coff_section *parentSec = getSection(parentIndex);
300     if (Expected<StringRef> e = coffObj->getSectionName(parentSec))
301       parentName = *e;
302     error(toString(this) + ": associative comdat " + name + " (sec " +
303           Twine(sectionNumber) + ") has invalid reference to section " +
304           parentName + " (sec " + Twine(parentIndex) + ")");
305   };
306 
307   if (parent == pendingComdat) {
308     // This can happen if an associative comdat refers to another associative
309     // comdat that appears after it (invalid per COFF spec) or to a section
310     // without any symbols.
311     diag();
312     return;
313   }
314 
315   // Check whether the parent is prevailing. If it is, so are we, and we read
316   // the section; otherwise mark it as discarded.
317   if (parent) {
318     SectionChunk *c = readSection(sectionNumber, def, "");
319     sparseChunks[sectionNumber] = c;
320     if (c) {
321       c->selection = IMAGE_COMDAT_SELECT_ASSOCIATIVE;
322       parent->addAssociative(c);
323     }
324   } else {
325     sparseChunks[sectionNumber] = nullptr;
326   }
327 }
328 
329 void ObjFile::recordPrevailingSymbolForMingw(
330     COFFSymbolRef sym, DenseMap<StringRef, uint32_t> &prevailingSectionMap) {
331   // For comdat symbols in executable sections, where this is the copy
332   // of the section chunk we actually include instead of discarding it,
333   // add the symbol to a map to allow using it for implicitly
334   // associating .[px]data$<func> sections to it.
335   int32_t sectionNumber = sym.getSectionNumber();
336   SectionChunk *sc = sparseChunks[sectionNumber];
337   if (sc && sc->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE) {
338     StringRef name;
339     coffObj->getSymbolName(sym, name);
340     if (getMachineType() == I386)
341       name.consume_front("_");
342     prevailingSectionMap[name] = sectionNumber;
343   }
344 }
345 
346 void ObjFile::maybeAssociateSEHForMingw(
347     COFFSymbolRef sym, const coff_aux_section_definition *def,
348     const DenseMap<StringRef, uint32_t> &prevailingSectionMap) {
349   StringRef name;
350   coffObj->getSymbolName(sym, name);
351   if (name.consume_front(".pdata$") || name.consume_front(".xdata$") ||
352       name.consume_front(".eh_frame$")) {
353     // For MinGW, treat .[px]data$<func> and .eh_frame$<func> as implicitly
354     // associative to the symbol <func>.
355     auto parentSym = prevailingSectionMap.find(name);
356     if (parentSym != prevailingSectionMap.end())
357       readAssociativeDefinition(sym, def, parentSym->second);
358   }
359 }
360 
361 Symbol *ObjFile::createRegular(COFFSymbolRef sym) {
362   SectionChunk *sc = sparseChunks[sym.getSectionNumber()];
363   if (sym.isExternal()) {
364     StringRef name;
365     coffObj->getSymbolName(sym, name);
366     if (sc)
367       return symtab->addRegular(this, name, sym.getGeneric(), sc);
368     // For MinGW symbols named .weak.* that point to a discarded section,
369     // don't create an Undefined symbol. If nothing ever refers to the symbol,
370     // everything should be fine. If something actually refers to the symbol
371     // (e.g. the undefined weak alias), linking will fail due to undefined
372     // references at the end.
373     if (config->mingw && name.startswith(".weak."))
374       return nullptr;
375     return symtab->addUndefined(name, this, false);
376   }
377   if (sc)
378     return make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
379                                 /*IsExternal*/ false, sym.getGeneric(), sc);
380   return nullptr;
381 }
382 
383 void ObjFile::initializeSymbols() {
384   uint32_t numSymbols = coffObj->getNumberOfSymbols();
385   symbols.resize(numSymbols);
386 
387   SmallVector<std::pair<Symbol *, uint32_t>, 8> weakAliases;
388   std::vector<uint32_t> pendingIndexes;
389   pendingIndexes.reserve(numSymbols);
390 
391   DenseMap<StringRef, uint32_t> prevailingSectionMap;
392   std::vector<const coff_aux_section_definition *> comdatDefs(
393       coffObj->getNumberOfSections() + 1);
394 
395   for (uint32_t i = 0; i < numSymbols; ++i) {
396     COFFSymbolRef coffSym = check(coffObj->getSymbol(i));
397     bool prevailingComdat;
398     if (coffSym.isUndefined()) {
399       symbols[i] = createUndefined(coffSym);
400     } else if (coffSym.isWeakExternal()) {
401       symbols[i] = createUndefined(coffSym);
402       uint32_t tagIndex = coffSym.getAux<coff_aux_weak_external>()->TagIndex;
403       weakAliases.emplace_back(symbols[i], tagIndex);
404     } else if (Optional<Symbol *> optSym =
405                    createDefined(coffSym, comdatDefs, prevailingComdat)) {
406       symbols[i] = *optSym;
407       if (config->mingw && prevailingComdat)
408         recordPrevailingSymbolForMingw(coffSym, prevailingSectionMap);
409     } else {
410       // createDefined() returns None if a symbol belongs to a section that
411       // was pending at the point when the symbol was read. This can happen in
412       // two cases:
413       // 1) section definition symbol for a comdat leader;
414       // 2) symbol belongs to a comdat section associated with another section.
415       // In both of these cases, we can expect the section to be resolved by
416       // the time we finish visiting the remaining symbols in the symbol
417       // table. So we postpone the handling of this symbol until that time.
418       pendingIndexes.push_back(i);
419     }
420     i += coffSym.getNumberOfAuxSymbols();
421   }
422 
423   for (uint32_t i : pendingIndexes) {
424     COFFSymbolRef sym = check(coffObj->getSymbol(i));
425     if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {
426       if (def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
427         readAssociativeDefinition(sym, def);
428       else if (config->mingw)
429         maybeAssociateSEHForMingw(sym, def, prevailingSectionMap);
430     }
431     if (sparseChunks[sym.getSectionNumber()] == pendingComdat) {
432       StringRef name;
433       coffObj->getSymbolName(sym, name);
434       log("comdat section " + name +
435           " without leader and unassociated, discarding");
436       continue;
437     }
438     symbols[i] = createRegular(sym);
439   }
440 
441   for (auto &kv : weakAliases) {
442     Symbol *sym = kv.first;
443     uint32_t idx = kv.second;
444     checkAndSetWeakAlias(symtab, this, sym, symbols[idx]);
445   }
446 }
447 
448 Symbol *ObjFile::createUndefined(COFFSymbolRef sym) {
449   StringRef name;
450   coffObj->getSymbolName(sym, name);
451   return symtab->addUndefined(name, this, sym.isWeakExternal());
452 }
453 
454 void ObjFile::handleComdatSelection(COFFSymbolRef sym, COMDATType &selection,
455                                     bool &prevailing, DefinedRegular *leader) {
456   if (prevailing)
457     return;
458   // There's already an existing comdat for this symbol: `Leader`.
459   // Use the comdats's selection field to determine if the new
460   // symbol in `Sym` should be discarded, produce a duplicate symbol
461   // error, etc.
462 
463   SectionChunk *leaderChunk = nullptr;
464   COMDATType leaderSelection = IMAGE_COMDAT_SELECT_ANY;
465 
466   if (leader->data) {
467     leaderChunk = leader->getChunk();
468     leaderSelection = leaderChunk->selection;
469   } else {
470     // FIXME: comdats from LTO files don't know their selection; treat them
471     // as "any".
472     selection = leaderSelection;
473   }
474 
475   if ((selection == IMAGE_COMDAT_SELECT_ANY &&
476        leaderSelection == IMAGE_COMDAT_SELECT_LARGEST) ||
477       (selection == IMAGE_COMDAT_SELECT_LARGEST &&
478        leaderSelection == IMAGE_COMDAT_SELECT_ANY)) {
479     // cl.exe picks "any" for vftables when building with /GR- and
480     // "largest" when building with /GR. To be able to link object files
481     // compiled with each flag, "any" and "largest" are merged as "largest".
482     leaderSelection = selection = IMAGE_COMDAT_SELECT_LARGEST;
483   }
484 
485   // Other than that, comdat selections must match.  This is a bit more
486   // strict than link.exe which allows merging "any" and "largest" if "any"
487   // is the first symbol the linker sees, and it allows merging "largest"
488   // with everything (!) if "largest" is the first symbol the linker sees.
489   // Making this symmetric independent of which selection is seen first
490   // seems better though.
491   // (This behavior matches ModuleLinker::getComdatResult().)
492   if (selection != leaderSelection) {
493     log(("conflicting comdat type for " + toString(*leader) + ": " +
494          Twine((int)leaderSelection) + " in " + toString(leader->getFile()) +
495          " and " + Twine((int)selection) + " in " + toString(this))
496             .str());
497     symtab->reportDuplicate(leader, this);
498     return;
499   }
500 
501   switch (selection) {
502   case IMAGE_COMDAT_SELECT_NODUPLICATES:
503     symtab->reportDuplicate(leader, this);
504     break;
505 
506   case IMAGE_COMDAT_SELECT_ANY:
507     // Nothing to do.
508     break;
509 
510   case IMAGE_COMDAT_SELECT_SAME_SIZE:
511     if (leaderChunk->getSize() != getSection(sym)->SizeOfRawData)
512       symtab->reportDuplicate(leader, this);
513     break;
514 
515   case IMAGE_COMDAT_SELECT_EXACT_MATCH: {
516     SectionChunk newChunk(this, getSection(sym));
517     // link.exe only compares section contents here and doesn't complain
518     // if the two comdat sections have e.g. different alignment.
519     // Match that.
520     if (leaderChunk->getContents() != newChunk.getContents())
521       symtab->reportDuplicate(leader, this);
522     break;
523   }
524 
525   case IMAGE_COMDAT_SELECT_ASSOCIATIVE:
526     // createDefined() is never called for IMAGE_COMDAT_SELECT_ASSOCIATIVE.
527     // (This means lld-link doesn't produce duplicate symbol errors for
528     // associative comdats while link.exe does, but associate comdats
529     // are never extern in practice.)
530     llvm_unreachable("createDefined not called for associative comdats");
531 
532   case IMAGE_COMDAT_SELECT_LARGEST:
533     if (leaderChunk->getSize() < getSection(sym)->SizeOfRawData) {
534       // Replace the existing comdat symbol with the new one.
535       StringRef name;
536       coffObj->getSymbolName(sym, name);
537       // FIXME: This is incorrect: With /opt:noref, the previous sections
538       // make it into the final executable as well. Correct handling would
539       // be to undo reading of the whole old section that's being replaced,
540       // or doing one pass that determines what the final largest comdat
541       // is for all IMAGE_COMDAT_SELECT_LARGEST comdats and then reading
542       // only the largest one.
543       replaceSymbol<DefinedRegular>(leader, this, name, /*IsCOMDAT*/ true,
544                                     /*IsExternal*/ true, sym.getGeneric(),
545                                     nullptr);
546       prevailing = true;
547     }
548     break;
549 
550   case IMAGE_COMDAT_SELECT_NEWEST:
551     llvm_unreachable("should have been rejected earlier");
552   }
553 }
554 
555 Optional<Symbol *> ObjFile::createDefined(
556     COFFSymbolRef sym,
557     std::vector<const coff_aux_section_definition *> &comdatDefs,
558     bool &prevailing) {
559   prevailing = false;
560   auto getName = [&]() {
561     StringRef s;
562     coffObj->getSymbolName(sym, s);
563     return s;
564   };
565 
566   if (sym.isCommon()) {
567     auto *c = make<CommonChunk>(sym);
568     chunks.push_back(c);
569     return symtab->addCommon(this, getName(), sym.getValue(), sym.getGeneric(),
570                              c);
571   }
572 
573   if (sym.isAbsolute()) {
574     StringRef name = getName();
575 
576     if (name == "@feat.00")
577       feat00Flags = sym.getValue();
578     // Skip special symbols.
579     if (ignoredSymbolName(name))
580       return nullptr;
581 
582     if (sym.isExternal())
583       return symtab->addAbsolute(name, sym);
584     return make<DefinedAbsolute>(name, sym);
585   }
586 
587   int32_t sectionNumber = sym.getSectionNumber();
588   if (sectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
589     return nullptr;
590 
591   if (llvm::COFF::isReservedSectionNumber(sectionNumber))
592     fatal(toString(this) + ": " + getName() +
593           " should not refer to special section " + Twine(sectionNumber));
594 
595   if ((uint32_t)sectionNumber >= sparseChunks.size())
596     fatal(toString(this) + ": " + getName() +
597           " should not refer to non-existent section " + Twine(sectionNumber));
598 
599   // Comdat handling.
600   // A comdat symbol consists of two symbol table entries.
601   // The first symbol entry has the name of the section (e.g. .text), fixed
602   // values for the other fields, and one auxilliary record.
603   // The second symbol entry has the name of the comdat symbol, called the
604   // "comdat leader".
605   // When this function is called for the first symbol entry of a comdat,
606   // it sets comdatDefs and returns None, and when it's called for the second
607   // symbol entry it reads comdatDefs and then sets it back to nullptr.
608 
609   // Handle comdat leader.
610   if (const coff_aux_section_definition *def = comdatDefs[sectionNumber]) {
611     comdatDefs[sectionNumber] = nullptr;
612     DefinedRegular *leader;
613 
614     if (sym.isExternal()) {
615       std::tie(leader, prevailing) =
616           symtab->addComdat(this, getName(), sym.getGeneric());
617     } else {
618       leader = make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
619                                     /*IsExternal*/ false, sym.getGeneric());
620       prevailing = true;
621     }
622 
623     if (def->Selection < (int)IMAGE_COMDAT_SELECT_NODUPLICATES ||
624         // Intentionally ends at IMAGE_COMDAT_SELECT_LARGEST: link.exe
625         // doesn't understand IMAGE_COMDAT_SELECT_NEWEST either.
626         def->Selection > (int)IMAGE_COMDAT_SELECT_LARGEST) {
627       fatal("unknown comdat type " + std::to_string((int)def->Selection) +
628             " for " + getName() + " in " + toString(this));
629     }
630     COMDATType selection = (COMDATType)def->Selection;
631 
632     if (leader->isCOMDAT)
633       handleComdatSelection(sym, selection, prevailing, leader);
634 
635     if (prevailing) {
636       SectionChunk *c = readSection(sectionNumber, def, getName());
637       sparseChunks[sectionNumber] = c;
638       c->sym = cast<DefinedRegular>(leader);
639       c->selection = selection;
640       cast<DefinedRegular>(leader)->data = &c->repl;
641     } else {
642       sparseChunks[sectionNumber] = nullptr;
643     }
644     return leader;
645   }
646 
647   // Prepare to handle the comdat leader symbol by setting the section's
648   // ComdatDefs pointer if we encounter a non-associative comdat.
649   if (sparseChunks[sectionNumber] == pendingComdat) {
650     if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {
651       if (def->Selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE)
652         comdatDefs[sectionNumber] = def;
653     }
654     return None;
655   }
656 
657   return createRegular(sym);
658 }
659 
660 MachineTypes ObjFile::getMachineType() {
661   if (coffObj)
662     return static_cast<MachineTypes>(coffObj->getMachine());
663   return IMAGE_FILE_MACHINE_UNKNOWN;
664 }
665 
666 ArrayRef<uint8_t> ObjFile::getDebugSection(StringRef secName) {
667   if (SectionChunk *sec = SectionChunk::findByName(debugChunks, secName))
668     return sec->consumeDebugMagic();
669   return {};
670 }
671 
672 // OBJ files systematically store critical informations in a .debug$S stream,
673 // even if the TU was compiled with no debug info. At least two records are
674 // always there. S_OBJNAME stores a 32-bit signature, which is loaded into the
675 // PCHSignature member. S_COMPILE3 stores compile-time cmd-line flags. This is
676 // currently used to initialize the hotPatchable member.
677 void ObjFile::initializeFlags() {
678   ArrayRef<uint8_t> data = getDebugSection(".debug$S");
679   if (data.empty())
680     return;
681 
682   DebugSubsectionArray subsections;
683 
684   BinaryStreamReader reader(data, support::little);
685   ExitOnError exitOnErr;
686   exitOnErr(reader.readArray(subsections, data.size()));
687 
688   for (const DebugSubsectionRecord &ss : subsections) {
689     if (ss.kind() != DebugSubsectionKind::Symbols)
690       continue;
691 
692     unsigned offset = 0;
693 
694     // Only parse the first two records. We are only looking for S_OBJNAME
695     // and S_COMPILE3, and they usually appear at the beginning of the
696     // stream.
697     for (unsigned i = 0; i < 2; ++i) {
698       Expected<CVSymbol> sym = readSymbolFromStream(ss.getRecordData(), offset);
699       if (!sym) {
700         consumeError(sym.takeError());
701         return;
702       }
703       if (sym->kind() == SymbolKind::S_COMPILE3) {
704         auto cs =
705             cantFail(SymbolDeserializer::deserializeAs<Compile3Sym>(sym.get()));
706         hotPatchable =
707             (cs.Flags & CompileSym3Flags::HotPatch) != CompileSym3Flags::None;
708       }
709       if (sym->kind() == SymbolKind::S_OBJNAME) {
710         auto objName = cantFail(SymbolDeserializer::deserializeAs<ObjNameSym>(
711             sym.get()));
712         pchSignature = objName.Signature;
713       }
714       offset += sym->length();
715     }
716   }
717 }
718 
719 // Depending on the compilation flags, OBJs can refer to external files,
720 // necessary to merge this OBJ into the final PDB. We currently support two
721 // types of external files: Precomp/PCH OBJs, when compiling with /Yc and /Yu.
722 // And PDB type servers, when compiling with /Zi. This function extracts these
723 // dependencies and makes them available as a TpiSource interface (see
724 // DebugTypes.h). Both cases only happen with cl.exe: clang-cl produces regular
725 // output even with /Yc and /Yu and with /Zi.
726 void ObjFile::initializeDependencies() {
727   if (!config->debug)
728     return;
729 
730   bool isPCH = false;
731 
732   ArrayRef<uint8_t> data = getDebugSection(".debug$P");
733   if (!data.empty())
734     isPCH = true;
735   else
736     data = getDebugSection(".debug$T");
737 
738   if (data.empty())
739     return;
740 
741   CVTypeArray types;
742   BinaryStreamReader reader(data, support::little);
743   cantFail(reader.readArray(types, reader.getLength()));
744 
745   CVTypeArray::Iterator firstType = types.begin();
746   if (firstType == types.end())
747     return;
748 
749   debugTypes.emplace(types);
750 
751   if (isPCH) {
752     debugTypesObj = makePrecompSource(this);
753     return;
754   }
755 
756   if (firstType->kind() == LF_TYPESERVER2) {
757     TypeServer2Record ts = cantFail(
758         TypeDeserializer::deserializeAs<TypeServer2Record>(firstType->data()));
759     debugTypesObj = makeUseTypeServerSource(this, &ts);
760     return;
761   }
762 
763   if (firstType->kind() == LF_PRECOMP) {
764     PrecompRecord precomp = cantFail(
765         TypeDeserializer::deserializeAs<PrecompRecord>(firstType->data()));
766     debugTypesObj = makeUsePrecompSource(this, &precomp);
767     return;
768   }
769 
770   debugTypesObj = makeTpiSource(this);
771 }
772 
773 StringRef ltrim1(StringRef s, const char *chars) {
774   if (!s.empty() && strchr(chars, s[0]))
775     return s.substr(1);
776   return s;
777 }
778 
779 void ImportFile::parse() {
780   const char *buf = mb.getBufferStart();
781   const auto *hdr = reinterpret_cast<const coff_import_header *>(buf);
782 
783   // Check if the total size is valid.
784   if (mb.getBufferSize() != sizeof(*hdr) + hdr->SizeOfData)
785     fatal("broken import library");
786 
787   // Read names and create an __imp_ symbol.
788   StringRef name = saver.save(StringRef(buf + sizeof(*hdr)));
789   StringRef impName = saver.save("__imp_" + name);
790   const char *nameStart = buf + sizeof(coff_import_header) + name.size() + 1;
791   dllName = StringRef(nameStart);
792   StringRef extName;
793   switch (hdr->getNameType()) {
794   case IMPORT_ORDINAL:
795     extName = "";
796     break;
797   case IMPORT_NAME:
798     extName = name;
799     break;
800   case IMPORT_NAME_NOPREFIX:
801     extName = ltrim1(name, "?@_");
802     break;
803   case IMPORT_NAME_UNDECORATE:
804     extName = ltrim1(name, "?@_");
805     extName = extName.substr(0, extName.find('@'));
806     break;
807   }
808 
809   this->hdr = hdr;
810   externalName = extName;
811 
812   impSym = symtab->addImportData(impName, this);
813   // If this was a duplicate, we logged an error but may continue;
814   // in this case, impSym is nullptr.
815   if (!impSym)
816     return;
817 
818   if (hdr->getType() == llvm::COFF::IMPORT_CONST)
819     static_cast<void>(symtab->addImportData(name, this));
820 
821   // If type is function, we need to create a thunk which jump to an
822   // address pointed by the __imp_ symbol. (This allows you to call
823   // DLL functions just like regular non-DLL functions.)
824   if (hdr->getType() == llvm::COFF::IMPORT_CODE)
825     thunkSym = symtab->addImportThunk(
826         name, cast_or_null<DefinedImportData>(impSym), hdr->Machine);
827 }
828 
829 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
830                          uint64_t offsetInArchive,
831                          std::vector<Symbol *> &&symbols)
832     : InputFile(BitcodeKind, mb), symbols(std::move(symbols)) {
833   std::string path = mb.getBufferIdentifier().str();
834   if (config->thinLTOIndexOnly)
835     path = replaceThinLTOSuffix(mb.getBufferIdentifier());
836 
837   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
838   // name. If two archives define two members with the same name, this
839   // causes a collision which result in only one of the objects being taken
840   // into consideration at LTO time (which very likely causes undefined
841   // symbols later in the link stage). So we append file offset to make
842   // filename unique.
843   MemoryBufferRef mbref(
844       mb.getBuffer(),
845       saver.save(archiveName + path +
846                  (archiveName.empty() ? "" : utostr(offsetInArchive))));
847 
848   obj = check(lto::InputFile::create(mbref));
849 }
850 
851 void BitcodeFile::parse() {
852   std::vector<std::pair<Symbol *, bool>> comdat(obj->getComdatTable().size());
853   for (size_t i = 0; i != obj->getComdatTable().size(); ++i)
854     // FIXME: lto::InputFile doesn't keep enough data to do correct comdat
855     // selection handling.
856     comdat[i] = symtab->addComdat(this, saver.save(obj->getComdatTable()[i]));
857   for (const lto::InputFile::Symbol &objSym : obj->symbols()) {
858     StringRef symName = saver.save(objSym.getName());
859     int comdatIndex = objSym.getComdatIndex();
860     Symbol *sym;
861     if (objSym.isUndefined()) {
862       sym = symtab->addUndefined(symName, this, false);
863     } else if (objSym.isCommon()) {
864       sym = symtab->addCommon(this, symName, objSym.getCommonSize());
865     } else if (objSym.isWeak() && objSym.isIndirect()) {
866       // Weak external.
867       sym = symtab->addUndefined(symName, this, true);
868       std::string fallback = objSym.getCOFFWeakExternalFallback();
869       Symbol *alias = symtab->addUndefined(saver.save(fallback));
870       checkAndSetWeakAlias(symtab, this, sym, alias);
871     } else if (comdatIndex != -1) {
872       if (symName == obj->getComdatTable()[comdatIndex])
873         sym = comdat[comdatIndex].first;
874       else if (comdat[comdatIndex].second)
875         sym = symtab->addRegular(this, symName);
876       else
877         sym = symtab->addUndefined(symName, this, false);
878     } else {
879       sym = symtab->addRegular(this, symName);
880     }
881     symbols.push_back(sym);
882     if (objSym.isUsed())
883       config->gcroot.push_back(sym);
884   }
885   directives = obj->getCOFFLinkerOpts();
886 }
887 
888 MachineTypes BitcodeFile::getMachineType() {
889   switch (Triple(obj->getTargetTriple()).getArch()) {
890   case Triple::x86_64:
891     return AMD64;
892   case Triple::x86:
893     return I386;
894   case Triple::arm:
895     return ARMNT;
896   case Triple::aarch64:
897     return ARM64;
898   default:
899     return IMAGE_FILE_MACHINE_UNKNOWN;
900   }
901 }
902 
903 std::string replaceThinLTOSuffix(StringRef path) {
904   StringRef suffix = config->thinLTOObjectSuffixReplace.first;
905   StringRef repl = config->thinLTOObjectSuffixReplace.second;
906 
907   if (path.consume_back(suffix))
908     return (path + repl).str();
909   return path;
910 }
911 } // namespace coff
912 } // namespace lld
913 
914 // Returns the last element of a path, which is supposed to be a filename.
915 static StringRef getBasename(StringRef path) {
916   return sys::path::filename(path, sys::path::Style::windows);
917 }
918 
919 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
920 std::string lld::toString(const coff::InputFile *file) {
921   if (!file)
922     return "<internal>";
923   if (file->parentName.empty() || file->kind() == coff::InputFile::ImportKind)
924     return file->getName();
925 
926   return (getBasename(file->parentName) + "(" + getBasename(file->getName()) +
927           ")")
928       .str();
929 }
930