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