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