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 == ".gljmp$y")
284     guardLJmpChunks.push_back(c);
285   else if (name == ".sxdata")
286     sxDataChunks.push_back(c);
287   else if (config->tailMerge && sec->NumberOfRelocations == 0 &&
288            name == ".rdata" && leaderName.startswith("??_C@"))
289     // COFF sections that look like string literal sections (i.e. no
290     // relocations, in .rdata, leader symbol name matches the MSVC name mangling
291     // for string literals) are subject to string tail merging.
292     MergeChunk::addSection(c);
293   else if (name == ".rsrc" || name.startswith(".rsrc$"))
294     resourceChunks.push_back(c);
295   else
296     chunks.push_back(c);
297 
298   return c;
299 }
300 
301 void ObjFile::includeResourceChunks() {
302   chunks.insert(chunks.end(), resourceChunks.begin(), resourceChunks.end());
303 }
304 
305 void ObjFile::readAssociativeDefinition(
306     COFFSymbolRef sym, const coff_aux_section_definition *def) {
307   readAssociativeDefinition(sym, def, def->getNumber(sym.isBigObj()));
308 }
309 
310 void ObjFile::readAssociativeDefinition(COFFSymbolRef sym,
311                                         const coff_aux_section_definition *def,
312                                         uint32_t parentIndex) {
313   SectionChunk *parent = sparseChunks[parentIndex];
314   int32_t sectionNumber = sym.getSectionNumber();
315 
316   auto diag = [&]() {
317     StringRef name = check(coffObj->getSymbolName(sym));
318 
319     StringRef parentName;
320     const coff_section *parentSec = getSection(parentIndex);
321     if (Expected<StringRef> e = coffObj->getSectionName(parentSec))
322       parentName = *e;
323     error(toString(this) + ": associative comdat " + name + " (sec " +
324           Twine(sectionNumber) + ") has invalid reference to section " +
325           parentName + " (sec " + Twine(parentIndex) + ")");
326   };
327 
328   if (parent == pendingComdat) {
329     // This can happen if an associative comdat refers to another associative
330     // comdat that appears after it (invalid per COFF spec) or to a section
331     // without any symbols.
332     diag();
333     return;
334   }
335 
336   // Check whether the parent is prevailing. If it is, so are we, and we read
337   // the section; otherwise mark it as discarded.
338   if (parent) {
339     SectionChunk *c = readSection(sectionNumber, def, "");
340     sparseChunks[sectionNumber] = c;
341     if (c) {
342       c->selection = IMAGE_COMDAT_SELECT_ASSOCIATIVE;
343       parent->addAssociative(c);
344     }
345   } else {
346     sparseChunks[sectionNumber] = nullptr;
347   }
348 }
349 
350 void ObjFile::recordPrevailingSymbolForMingw(
351     COFFSymbolRef sym, DenseMap<StringRef, uint32_t> &prevailingSectionMap) {
352   // For comdat symbols in executable sections, where this is the copy
353   // of the section chunk we actually include instead of discarding it,
354   // add the symbol to a map to allow using it for implicitly
355   // associating .[px]data$<func> sections to it.
356   // Use the suffix from the .text$<func> instead of the leader symbol
357   // name, for cases where the names differ (i386 mangling/decorations,
358   // cases where the leader is a weak symbol named .weak.func.default*).
359   int32_t sectionNumber = sym.getSectionNumber();
360   SectionChunk *sc = sparseChunks[sectionNumber];
361   if (sc && sc->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE) {
362     StringRef name = sc->getSectionName().split('$').second;
363     prevailingSectionMap[name] = sectionNumber;
364   }
365 }
366 
367 void ObjFile::maybeAssociateSEHForMingw(
368     COFFSymbolRef sym, const coff_aux_section_definition *def,
369     const DenseMap<StringRef, uint32_t> &prevailingSectionMap) {
370   StringRef name = check(coffObj->getSymbolName(sym));
371   if (name.consume_front(".pdata$") || name.consume_front(".xdata$") ||
372       name.consume_front(".eh_frame$")) {
373     // For MinGW, treat .[px]data$<func> and .eh_frame$<func> as implicitly
374     // associative to the symbol <func>.
375     auto parentSym = prevailingSectionMap.find(name);
376     if (parentSym != prevailingSectionMap.end())
377       readAssociativeDefinition(sym, def, parentSym->second);
378   }
379 }
380 
381 Symbol *ObjFile::createRegular(COFFSymbolRef sym) {
382   SectionChunk *sc = sparseChunks[sym.getSectionNumber()];
383   if (sym.isExternal()) {
384     StringRef name = check(coffObj->getSymbolName(sym));
385     if (sc)
386       return symtab->addRegular(this, name, sym.getGeneric(), sc,
387                                 sym.getValue());
388     // For MinGW symbols named .weak.* that point to a discarded section,
389     // don't create an Undefined symbol. If nothing ever refers to the symbol,
390     // everything should be fine. If something actually refers to the symbol
391     // (e.g. the undefined weak alias), linking will fail due to undefined
392     // references at the end.
393     if (config->mingw && name.startswith(".weak."))
394       return nullptr;
395     return symtab->addUndefined(name, this, false);
396   }
397   if (sc)
398     return make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
399                                 /*IsExternal*/ false, sym.getGeneric(), sc);
400   return nullptr;
401 }
402 
403 void ObjFile::initializeSymbols() {
404   uint32_t numSymbols = coffObj->getNumberOfSymbols();
405   symbols.resize(numSymbols);
406 
407   SmallVector<std::pair<Symbol *, uint32_t>, 8> weakAliases;
408   std::vector<uint32_t> pendingIndexes;
409   pendingIndexes.reserve(numSymbols);
410 
411   DenseMap<StringRef, uint32_t> prevailingSectionMap;
412   std::vector<const coff_aux_section_definition *> comdatDefs(
413       coffObj->getNumberOfSections() + 1);
414 
415   for (uint32_t i = 0; i < numSymbols; ++i) {
416     COFFSymbolRef coffSym = check(coffObj->getSymbol(i));
417     bool prevailingComdat;
418     if (coffSym.isUndefined()) {
419       symbols[i] = createUndefined(coffSym);
420     } else if (coffSym.isWeakExternal()) {
421       symbols[i] = createUndefined(coffSym);
422       uint32_t tagIndex = coffSym.getAux<coff_aux_weak_external>()->TagIndex;
423       weakAliases.emplace_back(symbols[i], tagIndex);
424     } else if (Optional<Symbol *> optSym =
425                    createDefined(coffSym, comdatDefs, prevailingComdat)) {
426       symbols[i] = *optSym;
427       if (config->mingw && prevailingComdat)
428         recordPrevailingSymbolForMingw(coffSym, prevailingSectionMap);
429     } else {
430       // createDefined() returns None if a symbol belongs to a section that
431       // was pending at the point when the symbol was read. This can happen in
432       // two cases:
433       // 1) section definition symbol for a comdat leader;
434       // 2) symbol belongs to a comdat section associated with another section.
435       // In both of these cases, we can expect the section to be resolved by
436       // the time we finish visiting the remaining symbols in the symbol
437       // table. So we postpone the handling of this symbol until that time.
438       pendingIndexes.push_back(i);
439     }
440     i += coffSym.getNumberOfAuxSymbols();
441   }
442 
443   for (uint32_t i : pendingIndexes) {
444     COFFSymbolRef sym = check(coffObj->getSymbol(i));
445     if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {
446       if (def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
447         readAssociativeDefinition(sym, def);
448       else if (config->mingw)
449         maybeAssociateSEHForMingw(sym, def, prevailingSectionMap);
450     }
451     if (sparseChunks[sym.getSectionNumber()] == pendingComdat) {
452       StringRef name = check(coffObj->getSymbolName(sym));
453       log("comdat section " + name +
454           " without leader and unassociated, discarding");
455       continue;
456     }
457     symbols[i] = createRegular(sym);
458   }
459 
460   for (auto &kv : weakAliases) {
461     Symbol *sym = kv.first;
462     uint32_t idx = kv.second;
463     checkAndSetWeakAlias(symtab, this, sym, symbols[idx]);
464   }
465 
466   // Free the memory used by sparseChunks now that symbol loading is finished.
467   decltype(sparseChunks)().swap(sparseChunks);
468 }
469 
470 Symbol *ObjFile::createUndefined(COFFSymbolRef sym) {
471   StringRef name = check(coffObj->getSymbolName(sym));
472   return symtab->addUndefined(name, this, sym.isWeakExternal());
473 }
474 
475 void ObjFile::handleComdatSelection(COFFSymbolRef sym, COMDATType &selection,
476                                     bool &prevailing, DefinedRegular *leader) {
477   if (prevailing)
478     return;
479   // There's already an existing comdat for this symbol: `Leader`.
480   // Use the comdats's selection field to determine if the new
481   // symbol in `Sym` should be discarded, produce a duplicate symbol
482   // error, etc.
483 
484   SectionChunk *leaderChunk = nullptr;
485   COMDATType leaderSelection = IMAGE_COMDAT_SELECT_ANY;
486 
487   if (leader->data) {
488     leaderChunk = leader->getChunk();
489     leaderSelection = leaderChunk->selection;
490   } else {
491     // FIXME: comdats from LTO files don't know their selection; treat them
492     // as "any".
493     selection = leaderSelection;
494   }
495 
496   if ((selection == IMAGE_COMDAT_SELECT_ANY &&
497        leaderSelection == IMAGE_COMDAT_SELECT_LARGEST) ||
498       (selection == IMAGE_COMDAT_SELECT_LARGEST &&
499        leaderSelection == IMAGE_COMDAT_SELECT_ANY)) {
500     // cl.exe picks "any" for vftables when building with /GR- and
501     // "largest" when building with /GR. To be able to link object files
502     // compiled with each flag, "any" and "largest" are merged as "largest".
503     leaderSelection = selection = IMAGE_COMDAT_SELECT_LARGEST;
504   }
505 
506   // GCCs __declspec(selectany) doesn't actually pick "any" but "same size as".
507   // Clang on the other hand picks "any". To be able to link two object files
508   // with a __declspec(selectany) declaration, one compiled with gcc and the
509   // other with clang, we merge them as proper "same size as"
510   if (config->mingw && ((selection == IMAGE_COMDAT_SELECT_ANY &&
511                          leaderSelection == IMAGE_COMDAT_SELECT_SAME_SIZE) ||
512                         (selection == IMAGE_COMDAT_SELECT_SAME_SIZE &&
513                          leaderSelection == IMAGE_COMDAT_SELECT_ANY))) {
514     leaderSelection = selection = IMAGE_COMDAT_SELECT_SAME_SIZE;
515   }
516 
517   // Other than that, comdat selections must match.  This is a bit more
518   // strict than link.exe which allows merging "any" and "largest" if "any"
519   // is the first symbol the linker sees, and it allows merging "largest"
520   // with everything (!) if "largest" is the first symbol the linker sees.
521   // Making this symmetric independent of which selection is seen first
522   // seems better though.
523   // (This behavior matches ModuleLinker::getComdatResult().)
524   if (selection != leaderSelection) {
525     log(("conflicting comdat type for " + toString(*leader) + ": " +
526          Twine((int)leaderSelection) + " in " + toString(leader->getFile()) +
527          " and " + Twine((int)selection) + " in " + toString(this))
528             .str());
529     symtab->reportDuplicate(leader, this);
530     return;
531   }
532 
533   switch (selection) {
534   case IMAGE_COMDAT_SELECT_NODUPLICATES:
535     symtab->reportDuplicate(leader, this);
536     break;
537 
538   case IMAGE_COMDAT_SELECT_ANY:
539     // Nothing to do.
540     break;
541 
542   case IMAGE_COMDAT_SELECT_SAME_SIZE:
543     if (leaderChunk->getSize() != getSection(sym)->SizeOfRawData)
544       symtab->reportDuplicate(leader, this);
545     break;
546 
547   case IMAGE_COMDAT_SELECT_EXACT_MATCH: {
548     SectionChunk newChunk(this, getSection(sym));
549     // link.exe only compares section contents here and doesn't complain
550     // if the two comdat sections have e.g. different alignment.
551     // Match that.
552     if (leaderChunk->getContents() != newChunk.getContents())
553       symtab->reportDuplicate(leader, this, &newChunk, sym.getValue());
554     break;
555   }
556 
557   case IMAGE_COMDAT_SELECT_ASSOCIATIVE:
558     // createDefined() is never called for IMAGE_COMDAT_SELECT_ASSOCIATIVE.
559     // (This means lld-link doesn't produce duplicate symbol errors for
560     // associative comdats while link.exe does, but associate comdats
561     // are never extern in practice.)
562     llvm_unreachable("createDefined not called for associative comdats");
563 
564   case IMAGE_COMDAT_SELECT_LARGEST:
565     if (leaderChunk->getSize() < getSection(sym)->SizeOfRawData) {
566       // Replace the existing comdat symbol with the new one.
567       StringRef name = check(coffObj->getSymbolName(sym));
568       // FIXME: This is incorrect: With /opt:noref, the previous sections
569       // make it into the final executable as well. Correct handling would
570       // be to undo reading of the whole old section that's being replaced,
571       // or doing one pass that determines what the final largest comdat
572       // is for all IMAGE_COMDAT_SELECT_LARGEST comdats and then reading
573       // only the largest one.
574       replaceSymbol<DefinedRegular>(leader, this, name, /*IsCOMDAT*/ true,
575                                     /*IsExternal*/ true, sym.getGeneric(),
576                                     nullptr);
577       prevailing = true;
578     }
579     break;
580 
581   case IMAGE_COMDAT_SELECT_NEWEST:
582     llvm_unreachable("should have been rejected earlier");
583   }
584 }
585 
586 Optional<Symbol *> ObjFile::createDefined(
587     COFFSymbolRef sym,
588     std::vector<const coff_aux_section_definition *> &comdatDefs,
589     bool &prevailing) {
590   prevailing = false;
591   auto getName = [&]() { return check(coffObj->getSymbolName(sym)); };
592 
593   if (sym.isCommon()) {
594     auto *c = make<CommonChunk>(sym);
595     chunks.push_back(c);
596     return symtab->addCommon(this, getName(), sym.getValue(), sym.getGeneric(),
597                              c);
598   }
599 
600   if (sym.isAbsolute()) {
601     StringRef name = getName();
602 
603     if (name == "@feat.00")
604       feat00Flags = sym.getValue();
605     // Skip special symbols.
606     if (ignoredSymbolName(name))
607       return nullptr;
608 
609     if (sym.isExternal())
610       return symtab->addAbsolute(name, sym);
611     return make<DefinedAbsolute>(name, sym);
612   }
613 
614   int32_t sectionNumber = sym.getSectionNumber();
615   if (sectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
616     return nullptr;
617 
618   if (llvm::COFF::isReservedSectionNumber(sectionNumber))
619     fatal(toString(this) + ": " + getName() +
620           " should not refer to special section " + Twine(sectionNumber));
621 
622   if ((uint32_t)sectionNumber >= sparseChunks.size())
623     fatal(toString(this) + ": " + getName() +
624           " should not refer to non-existent section " + Twine(sectionNumber));
625 
626   // Comdat handling.
627   // A comdat symbol consists of two symbol table entries.
628   // The first symbol entry has the name of the section (e.g. .text), fixed
629   // values for the other fields, and one auxiliary record.
630   // The second symbol entry has the name of the comdat symbol, called the
631   // "comdat leader".
632   // When this function is called for the first symbol entry of a comdat,
633   // it sets comdatDefs and returns None, and when it's called for the second
634   // symbol entry it reads comdatDefs and then sets it back to nullptr.
635 
636   // Handle comdat leader.
637   if (const coff_aux_section_definition *def = comdatDefs[sectionNumber]) {
638     comdatDefs[sectionNumber] = nullptr;
639     DefinedRegular *leader;
640 
641     if (sym.isExternal()) {
642       std::tie(leader, prevailing) =
643           symtab->addComdat(this, getName(), sym.getGeneric());
644     } else {
645       leader = make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
646                                     /*IsExternal*/ false, sym.getGeneric());
647       prevailing = true;
648     }
649 
650     if (def->Selection < (int)IMAGE_COMDAT_SELECT_NODUPLICATES ||
651         // Intentionally ends at IMAGE_COMDAT_SELECT_LARGEST: link.exe
652         // doesn't understand IMAGE_COMDAT_SELECT_NEWEST either.
653         def->Selection > (int)IMAGE_COMDAT_SELECT_LARGEST) {
654       fatal("unknown comdat type " + std::to_string((int)def->Selection) +
655             " for " + getName() + " in " + toString(this));
656     }
657     COMDATType selection = (COMDATType)def->Selection;
658 
659     if (leader->isCOMDAT)
660       handleComdatSelection(sym, selection, prevailing, leader);
661 
662     if (prevailing) {
663       SectionChunk *c = readSection(sectionNumber, def, getName());
664       sparseChunks[sectionNumber] = c;
665       c->sym = cast<DefinedRegular>(leader);
666       c->selection = selection;
667       cast<DefinedRegular>(leader)->data = &c->repl;
668     } else {
669       sparseChunks[sectionNumber] = nullptr;
670     }
671     return leader;
672   }
673 
674   // Prepare to handle the comdat leader symbol by setting the section's
675   // ComdatDefs pointer if we encounter a non-associative comdat.
676   if (sparseChunks[sectionNumber] == pendingComdat) {
677     if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {
678       if (def->Selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE)
679         comdatDefs[sectionNumber] = def;
680     }
681     return None;
682   }
683 
684   return createRegular(sym);
685 }
686 
687 MachineTypes ObjFile::getMachineType() {
688   if (coffObj)
689     return static_cast<MachineTypes>(coffObj->getMachine());
690   return IMAGE_FILE_MACHINE_UNKNOWN;
691 }
692 
693 ArrayRef<uint8_t> ObjFile::getDebugSection(StringRef secName) {
694   if (SectionChunk *sec = SectionChunk::findByName(debugChunks, secName))
695     return sec->consumeDebugMagic();
696   return {};
697 }
698 
699 // OBJ files systematically store critical information in a .debug$S stream,
700 // even if the TU was compiled with no debug info. At least two records are
701 // always there. S_OBJNAME stores a 32-bit signature, which is loaded into the
702 // PCHSignature member. S_COMPILE3 stores compile-time cmd-line flags. This is
703 // currently used to initialize the hotPatchable member.
704 void ObjFile::initializeFlags() {
705   ArrayRef<uint8_t> data = getDebugSection(".debug$S");
706   if (data.empty())
707     return;
708 
709   DebugSubsectionArray subsections;
710 
711   BinaryStreamReader reader(data, support::little);
712   ExitOnError exitOnErr;
713   exitOnErr(reader.readArray(subsections, data.size()));
714 
715   for (const DebugSubsectionRecord &ss : subsections) {
716     if (ss.kind() != DebugSubsectionKind::Symbols)
717       continue;
718 
719     unsigned offset = 0;
720 
721     // Only parse the first two records. We are only looking for S_OBJNAME
722     // and S_COMPILE3, and they usually appear at the beginning of the
723     // stream.
724     for (unsigned i = 0; i < 2; ++i) {
725       Expected<CVSymbol> sym = readSymbolFromStream(ss.getRecordData(), offset);
726       if (!sym) {
727         consumeError(sym.takeError());
728         return;
729       }
730       if (sym->kind() == SymbolKind::S_COMPILE3) {
731         auto cs =
732             cantFail(SymbolDeserializer::deserializeAs<Compile3Sym>(sym.get()));
733         hotPatchable =
734             (cs.Flags & CompileSym3Flags::HotPatch) != CompileSym3Flags::None;
735       }
736       if (sym->kind() == SymbolKind::S_OBJNAME) {
737         auto objName = cantFail(SymbolDeserializer::deserializeAs<ObjNameSym>(
738             sym.get()));
739         pchSignature = objName.Signature;
740       }
741       offset += sym->length();
742     }
743   }
744 }
745 
746 // Depending on the compilation flags, OBJs can refer to external files,
747 // necessary to merge this OBJ into the final PDB. We currently support two
748 // types of external files: Precomp/PCH OBJs, when compiling with /Yc and /Yu.
749 // And PDB type servers, when compiling with /Zi. This function extracts these
750 // dependencies and makes them available as a TpiSource interface (see
751 // DebugTypes.h). Both cases only happen with cl.exe: clang-cl produces regular
752 // output even with /Yc and /Yu and with /Zi.
753 void ObjFile::initializeDependencies() {
754   if (!config->debug)
755     return;
756 
757   bool isPCH = false;
758 
759   ArrayRef<uint8_t> data = getDebugSection(".debug$P");
760   if (!data.empty())
761     isPCH = true;
762   else
763     data = getDebugSection(".debug$T");
764 
765   if (data.empty())
766     return;
767 
768   // Get the first type record. It will indicate if this object uses a type
769   // server (/Zi) or a PCH file (/Yu).
770   CVTypeArray types;
771   BinaryStreamReader reader(data, support::little);
772   cantFail(reader.readArray(types, reader.getLength()));
773   CVTypeArray::Iterator firstType = types.begin();
774   if (firstType == types.end())
775     return;
776 
777   // Remember the .debug$T or .debug$P section.
778   debugTypes = data;
779 
780   // This object file is a PCH file that others will depend on.
781   if (isPCH) {
782     debugTypesObj = makePrecompSource(this);
783     return;
784   }
785 
786   // This object file was compiled with /Zi. Enqueue the PDB dependency.
787   if (firstType->kind() == LF_TYPESERVER2) {
788     TypeServer2Record ts = cantFail(
789         TypeDeserializer::deserializeAs<TypeServer2Record>(firstType->data()));
790     debugTypesObj = makeUseTypeServerSource(this, ts);
791     PDBInputFile::enqueue(ts.getName(), this);
792     return;
793   }
794 
795   // This object was compiled with /Yu. It uses types from another object file
796   // with a matching signature.
797   if (firstType->kind() == LF_PRECOMP) {
798     PrecompRecord precomp = cantFail(
799         TypeDeserializer::deserializeAs<PrecompRecord>(firstType->data()));
800     debugTypesObj = makeUsePrecompSource(this, precomp);
801     return;
802   }
803 
804   // This is a plain old object file.
805   debugTypesObj = makeTpiSource(this);
806 }
807 
808 // Make a PDB path assuming the PDB is in the same folder as the OBJ
809 static std::string getPdbBaseName(ObjFile *file, StringRef tSPath) {
810   StringRef localPath =
811       !file->parentName.empty() ? file->parentName : file->getName();
812   SmallString<128> path = sys::path::parent_path(localPath);
813 
814   // Currently, type server PDBs are only created by MSVC cl, which only runs
815   // on Windows, so we can assume type server paths are Windows style.
816   sys::path::append(path,
817                     sys::path::filename(tSPath, sys::path::Style::windows));
818   return std::string(path.str());
819 }
820 
821 // The casing of the PDB path stamped in the OBJ can differ from the actual path
822 // on disk. With this, we ensure to always use lowercase as a key for the
823 // PDBInputFile::instances map, at least on Windows.
824 static std::string normalizePdbPath(StringRef path) {
825 #if defined(_WIN32)
826   return path.lower();
827 #else // LINUX
828   return std::string(path);
829 #endif
830 }
831 
832 // If existing, return the actual PDB path on disk.
833 static Optional<std::string> findPdbPath(StringRef pdbPath,
834                                          ObjFile *dependentFile) {
835   // Ensure the file exists before anything else. In some cases, if the path
836   // points to a removable device, Driver::enqueuePath() would fail with an
837   // error (EAGAIN, "resource unavailable try again") which we want to skip
838   // silently.
839   if (llvm::sys::fs::exists(pdbPath))
840     return normalizePdbPath(pdbPath);
841   std::string ret = getPdbBaseName(dependentFile, pdbPath);
842   if (llvm::sys::fs::exists(ret))
843     return normalizePdbPath(ret);
844   return None;
845 }
846 
847 PDBInputFile::PDBInputFile(MemoryBufferRef m) : InputFile(PDBKind, m) {}
848 
849 PDBInputFile::~PDBInputFile() = default;
850 
851 PDBInputFile *PDBInputFile::findFromRecordPath(StringRef path,
852                                                ObjFile *fromFile) {
853   auto p = findPdbPath(path.str(), fromFile);
854   if (!p)
855     return nullptr;
856   auto it = PDBInputFile::instances.find(*p);
857   if (it != PDBInputFile::instances.end())
858     return it->second;
859   return nullptr;
860 }
861 
862 void PDBInputFile::enqueue(StringRef path, ObjFile *fromFile) {
863   auto p = findPdbPath(path.str(), fromFile);
864   if (!p)
865     return;
866   auto it = PDBInputFile::instances.emplace(*p, nullptr);
867   if (!it.second)
868     return; // already scheduled for load
869   driver->enqueuePDB(*p);
870 }
871 
872 void PDBInputFile::parse() {
873   PDBInputFile::instances[mb.getBufferIdentifier().str()] = this;
874 
875   std::unique_ptr<pdb::IPDBSession> thisSession;
876   loadErr.emplace(pdb::NativeSession::createFromPdb(
877       MemoryBuffer::getMemBuffer(mb, false), thisSession));
878   if (*loadErr)
879     return; // fail silently at this point - the error will be handled later,
880             // when merging the debug type stream
881 
882   session.reset(static_cast<pdb::NativeSession *>(thisSession.release()));
883 
884   pdb::PDBFile &pdbFile = session->getPDBFile();
885   auto expectedInfo = pdbFile.getPDBInfoStream();
886   // All PDB Files should have an Info stream.
887   if (!expectedInfo) {
888     loadErr.emplace(expectedInfo.takeError());
889     return;
890   }
891   debugTypesObj = makeTypeServerSource(this);
892 }
893 
894 // Used only for DWARF debug info, which is not common (except in MinGW
895 // environments). This returns an optional pair of file name and line
896 // number for where the variable was defined.
897 Optional<std::pair<StringRef, uint32_t>>
898 ObjFile::getVariableLocation(StringRef var) {
899   if (!dwarf) {
900     dwarf = make<DWARFCache>(DWARFContext::create(*getCOFFObj()));
901     if (!dwarf)
902       return None;
903   }
904   if (config->machine == I386)
905     var.consume_front("_");
906   Optional<std::pair<std::string, unsigned>> ret = dwarf->getVariableLoc(var);
907   if (!ret)
908     return None;
909   return std::make_pair(saver.save(ret->first), ret->second);
910 }
911 
912 // Used only for DWARF debug info, which is not common (except in MinGW
913 // environments).
914 Optional<DILineInfo> ObjFile::getDILineInfo(uint32_t offset,
915                                             uint32_t sectionIndex) {
916   if (!dwarf) {
917     dwarf = make<DWARFCache>(DWARFContext::create(*getCOFFObj()));
918     if (!dwarf)
919       return None;
920   }
921 
922   return dwarf->getDILineInfo(offset, sectionIndex);
923 }
924 
925 static StringRef ltrim1(StringRef s, const char *chars) {
926   if (!s.empty() && strchr(chars, s[0]))
927     return s.substr(1);
928   return s;
929 }
930 
931 void ImportFile::parse() {
932   const char *buf = mb.getBufferStart();
933   const auto *hdr = reinterpret_cast<const coff_import_header *>(buf);
934 
935   // Check if the total size is valid.
936   if (mb.getBufferSize() != sizeof(*hdr) + hdr->SizeOfData)
937     fatal("broken import library");
938 
939   // Read names and create an __imp_ symbol.
940   StringRef name = saver.save(StringRef(buf + sizeof(*hdr)));
941   StringRef impName = saver.save("__imp_" + name);
942   const char *nameStart = buf + sizeof(coff_import_header) + name.size() + 1;
943   dllName = std::string(StringRef(nameStart));
944   StringRef extName;
945   switch (hdr->getNameType()) {
946   case IMPORT_ORDINAL:
947     extName = "";
948     break;
949   case IMPORT_NAME:
950     extName = name;
951     break;
952   case IMPORT_NAME_NOPREFIX:
953     extName = ltrim1(name, "?@_");
954     break;
955   case IMPORT_NAME_UNDECORATE:
956     extName = ltrim1(name, "?@_");
957     extName = extName.substr(0, extName.find('@'));
958     break;
959   }
960 
961   this->hdr = hdr;
962   externalName = extName;
963 
964   impSym = symtab->addImportData(impName, this);
965   // If this was a duplicate, we logged an error but may continue;
966   // in this case, impSym is nullptr.
967   if (!impSym)
968     return;
969 
970   if (hdr->getType() == llvm::COFF::IMPORT_CONST)
971     static_cast<void>(symtab->addImportData(name, this));
972 
973   // If type is function, we need to create a thunk which jump to an
974   // address pointed by the __imp_ symbol. (This allows you to call
975   // DLL functions just like regular non-DLL functions.)
976   if (hdr->getType() == llvm::COFF::IMPORT_CODE)
977     thunkSym = symtab->addImportThunk(
978         name, cast_or_null<DefinedImportData>(impSym), hdr->Machine);
979 }
980 
981 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
982                          uint64_t offsetInArchive)
983     : BitcodeFile(mb, archiveName, offsetInArchive, {}) {}
984 
985 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
986                          uint64_t offsetInArchive,
987                          std::vector<Symbol *> &&symbols)
988     : InputFile(BitcodeKind, mb), symbols(std::move(symbols)) {
989   std::string path = mb.getBufferIdentifier().str();
990   if (config->thinLTOIndexOnly)
991     path = replaceThinLTOSuffix(mb.getBufferIdentifier());
992 
993   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
994   // name. If two archives define two members with the same name, this
995   // causes a collision which result in only one of the objects being taken
996   // into consideration at LTO time (which very likely causes undefined
997   // symbols later in the link stage). So we append file offset to make
998   // filename unique.
999   MemoryBufferRef mbref(
1000       mb.getBuffer(),
1001       saver.save(archiveName.empty() ? path
1002                                      : archiveName + sys::path::filename(path) +
1003                                            utostr(offsetInArchive)));
1004 
1005   obj = check(lto::InputFile::create(mbref));
1006 }
1007 
1008 BitcodeFile::~BitcodeFile() = default;
1009 
1010 void BitcodeFile::parse() {
1011   std::vector<std::pair<Symbol *, bool>> comdat(obj->getComdatTable().size());
1012   for (size_t i = 0; i != obj->getComdatTable().size(); ++i)
1013     // FIXME: lto::InputFile doesn't keep enough data to do correct comdat
1014     // selection handling.
1015     comdat[i] = symtab->addComdat(this, saver.save(obj->getComdatTable()[i]));
1016   for (const lto::InputFile::Symbol &objSym : obj->symbols()) {
1017     StringRef symName = saver.save(objSym.getName());
1018     int comdatIndex = objSym.getComdatIndex();
1019     Symbol *sym;
1020     if (objSym.isUndefined()) {
1021       sym = symtab->addUndefined(symName, this, false);
1022     } else if (objSym.isCommon()) {
1023       sym = symtab->addCommon(this, symName, objSym.getCommonSize());
1024     } else if (objSym.isWeak() && objSym.isIndirect()) {
1025       // Weak external.
1026       sym = symtab->addUndefined(symName, this, true);
1027       std::string fallback = std::string(objSym.getCOFFWeakExternalFallback());
1028       Symbol *alias = symtab->addUndefined(saver.save(fallback));
1029       checkAndSetWeakAlias(symtab, this, sym, alias);
1030     } else if (comdatIndex != -1) {
1031       if (symName == obj->getComdatTable()[comdatIndex])
1032         sym = comdat[comdatIndex].first;
1033       else if (comdat[comdatIndex].second)
1034         sym = symtab->addRegular(this, symName);
1035       else
1036         sym = symtab->addUndefined(symName, this, false);
1037     } else {
1038       sym = symtab->addRegular(this, symName);
1039     }
1040     symbols.push_back(sym);
1041     if (objSym.isUsed())
1042       config->gcroot.push_back(sym);
1043   }
1044   directives = obj->getCOFFLinkerOpts();
1045 }
1046 
1047 MachineTypes BitcodeFile::getMachineType() {
1048   switch (Triple(obj->getTargetTriple()).getArch()) {
1049   case Triple::x86_64:
1050     return AMD64;
1051   case Triple::x86:
1052     return I386;
1053   case Triple::arm:
1054     return ARMNT;
1055   case Triple::aarch64:
1056     return ARM64;
1057   default:
1058     return IMAGE_FILE_MACHINE_UNKNOWN;
1059   }
1060 }
1061 
1062 std::string lld::coff::replaceThinLTOSuffix(StringRef path) {
1063   StringRef suffix = config->thinLTOObjectSuffixReplace.first;
1064   StringRef repl = config->thinLTOObjectSuffixReplace.second;
1065 
1066   if (path.consume_back(suffix))
1067     return (path + repl).str();
1068   return std::string(path);
1069 }
1070