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