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