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