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     // For MinGW symbols named .weak.* that point to a discarded section,
387     // don't create an Undefined symbol. If nothing ever refers to the symbol,
388     // everything should be fine. If something actually refers to the symbol
389     // (e.g. the undefined weak alias), linking will fail due to undefined
390     // references at the end.
391     if (config->mingw && name.startswith(".weak."))
392       return nullptr;
393     return symtab->addUndefined(name, this, false);
394   }
395   if (sc)
396     return make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
397                                 /*IsExternal*/ false, sym.getGeneric(), sc);
398   return nullptr;
399 }
400 
401 void ObjFile::initializeSymbols() {
402   uint32_t numSymbols = coffObj->getNumberOfSymbols();
403   symbols.resize(numSymbols);
404 
405   SmallVector<std::pair<Symbol *, uint32_t>, 8> weakAliases;
406   std::vector<uint32_t> pendingIndexes;
407   pendingIndexes.reserve(numSymbols);
408 
409   DenseMap<StringRef, uint32_t> prevailingSectionMap;
410   std::vector<const coff_aux_section_definition *> comdatDefs(
411       coffObj->getNumberOfSections() + 1);
412 
413   for (uint32_t i = 0; i < numSymbols; ++i) {
414     COFFSymbolRef coffSym = check(coffObj->getSymbol(i));
415     bool prevailingComdat;
416     if (coffSym.isUndefined()) {
417       symbols[i] = createUndefined(coffSym);
418     } else if (coffSym.isWeakExternal()) {
419       symbols[i] = createUndefined(coffSym);
420       uint32_t tagIndex = coffSym.getAux<coff_aux_weak_external>()->TagIndex;
421       weakAliases.emplace_back(symbols[i], tagIndex);
422     } else if (Optional<Symbol *> optSym =
423                    createDefined(coffSym, comdatDefs, prevailingComdat)) {
424       symbols[i] = *optSym;
425       if (config->mingw && prevailingComdat)
426         recordPrevailingSymbolForMingw(coffSym, prevailingSectionMap);
427     } else {
428       // createDefined() returns None if a symbol belongs to a section that
429       // was pending at the point when the symbol was read. This can happen in
430       // two cases:
431       // 1) section definition symbol for a comdat leader;
432       // 2) symbol belongs to a comdat section associated with another section.
433       // In both of these cases, we can expect the section to be resolved by
434       // the time we finish visiting the remaining symbols in the symbol
435       // table. So we postpone the handling of this symbol until that time.
436       pendingIndexes.push_back(i);
437     }
438     i += coffSym.getNumberOfAuxSymbols();
439   }
440 
441   for (uint32_t i : pendingIndexes) {
442     COFFSymbolRef sym = check(coffObj->getSymbol(i));
443     if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {
444       if (def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
445         readAssociativeDefinition(sym, def);
446       else if (config->mingw)
447         maybeAssociateSEHForMingw(sym, def, prevailingSectionMap);
448     }
449     if (sparseChunks[sym.getSectionNumber()] == pendingComdat) {
450       StringRef name;
451       coffObj->getSymbolName(sym, name);
452       log("comdat section " + name +
453           " without leader and unassociated, discarding");
454       continue;
455     }
456     symbols[i] = createRegular(sym);
457   }
458 
459   for (auto &kv : weakAliases) {
460     Symbol *sym = kv.first;
461     uint32_t idx = kv.second;
462     checkAndSetWeakAlias(symtab, this, sym, symbols[idx]);
463   }
464 }
465 
466 Symbol *ObjFile::createUndefined(COFFSymbolRef sym) {
467   StringRef name;
468   coffObj->getSymbolName(sym, name);
469   return symtab->addUndefined(name, this, sym.isWeakExternal());
470 }
471 
472 void ObjFile::handleComdatSelection(COFFSymbolRef sym, COMDATType &selection,
473                                     bool &prevailing, DefinedRegular *leader) {
474   if (prevailing)
475     return;
476   // There's already an existing comdat for this symbol: `Leader`.
477   // Use the comdats's selection field to determine if the new
478   // symbol in `Sym` should be discarded, produce a duplicate symbol
479   // error, etc.
480 
481   SectionChunk *leaderChunk = nullptr;
482   COMDATType leaderSelection = IMAGE_COMDAT_SELECT_ANY;
483 
484   if (leader->data) {
485     leaderChunk = leader->getChunk();
486     leaderSelection = leaderChunk->selection;
487   } else {
488     // FIXME: comdats from LTO files don't know their selection; treat them
489     // as "any".
490     selection = leaderSelection;
491   }
492 
493   if ((selection == IMAGE_COMDAT_SELECT_ANY &&
494        leaderSelection == IMAGE_COMDAT_SELECT_LARGEST) ||
495       (selection == IMAGE_COMDAT_SELECT_LARGEST &&
496        leaderSelection == IMAGE_COMDAT_SELECT_ANY)) {
497     // cl.exe picks "any" for vftables when building with /GR- and
498     // "largest" when building with /GR. To be able to link object files
499     // compiled with each flag, "any" and "largest" are merged as "largest".
500     leaderSelection = selection = IMAGE_COMDAT_SELECT_LARGEST;
501   }
502 
503   // Other than that, comdat selections must match.  This is a bit more
504   // strict than link.exe which allows merging "any" and "largest" if "any"
505   // is the first symbol the linker sees, and it allows merging "largest"
506   // with everything (!) if "largest" is the first symbol the linker sees.
507   // Making this symmetric independent of which selection is seen first
508   // seems better though.
509   // (This behavior matches ModuleLinker::getComdatResult().)
510   if (selection != leaderSelection) {
511     log(("conflicting comdat type for " + toString(*leader) + ": " +
512          Twine((int)leaderSelection) + " in " + toString(leader->getFile()) +
513          " and " + Twine((int)selection) + " in " + toString(this))
514             .str());
515     symtab->reportDuplicate(leader, this);
516     return;
517   }
518 
519   switch (selection) {
520   case IMAGE_COMDAT_SELECT_NODUPLICATES:
521     symtab->reportDuplicate(leader, this);
522     break;
523 
524   case IMAGE_COMDAT_SELECT_ANY:
525     // Nothing to do.
526     break;
527 
528   case IMAGE_COMDAT_SELECT_SAME_SIZE:
529     if (leaderChunk->getSize() != getSection(sym)->SizeOfRawData)
530       symtab->reportDuplicate(leader, this);
531     break;
532 
533   case IMAGE_COMDAT_SELECT_EXACT_MATCH: {
534     SectionChunk newChunk(this, getSection(sym));
535     // link.exe only compares section contents here and doesn't complain
536     // if the two comdat sections have e.g. different alignment.
537     // Match that.
538     if (leaderChunk->getContents() != newChunk.getContents())
539       symtab->reportDuplicate(leader, this);
540     break;
541   }
542 
543   case IMAGE_COMDAT_SELECT_ASSOCIATIVE:
544     // createDefined() is never called for IMAGE_COMDAT_SELECT_ASSOCIATIVE.
545     // (This means lld-link doesn't produce duplicate symbol errors for
546     // associative comdats while link.exe does, but associate comdats
547     // are never extern in practice.)
548     llvm_unreachable("createDefined not called for associative comdats");
549 
550   case IMAGE_COMDAT_SELECT_LARGEST:
551     if (leaderChunk->getSize() < getSection(sym)->SizeOfRawData) {
552       // Replace the existing comdat symbol with the new one.
553       StringRef name;
554       coffObj->getSymbolName(sym, name);
555       // FIXME: This is incorrect: With /opt:noref, the previous sections
556       // make it into the final executable as well. Correct handling would
557       // be to undo reading of the whole old section that's being replaced,
558       // or doing one pass that determines what the final largest comdat
559       // is for all IMAGE_COMDAT_SELECT_LARGEST comdats and then reading
560       // only the largest one.
561       replaceSymbol<DefinedRegular>(leader, this, name, /*IsCOMDAT*/ true,
562                                     /*IsExternal*/ true, sym.getGeneric(),
563                                     nullptr);
564       prevailing = true;
565     }
566     break;
567 
568   case IMAGE_COMDAT_SELECT_NEWEST:
569     llvm_unreachable("should have been rejected earlier");
570   }
571 }
572 
573 Optional<Symbol *> ObjFile::createDefined(
574     COFFSymbolRef sym,
575     std::vector<const coff_aux_section_definition *> &comdatDefs,
576     bool &prevailing) {
577   prevailing = false;
578   auto getName = [&]() {
579     StringRef s;
580     coffObj->getSymbolName(sym, s);
581     return s;
582   };
583 
584   if (sym.isCommon()) {
585     auto *c = make<CommonChunk>(sym);
586     chunks.push_back(c);
587     return symtab->addCommon(this, getName(), sym.getValue(), sym.getGeneric(),
588                              c);
589   }
590 
591   if (sym.isAbsolute()) {
592     StringRef name = getName();
593 
594     if (name == "@feat.00")
595       feat00Flags = sym.getValue();
596     // Skip special symbols.
597     if (ignoredSymbolName(name))
598       return nullptr;
599 
600     if (sym.isExternal())
601       return symtab->addAbsolute(name, sym);
602     return make<DefinedAbsolute>(name, sym);
603   }
604 
605   int32_t sectionNumber = sym.getSectionNumber();
606   if (sectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
607     return nullptr;
608 
609   if (llvm::COFF::isReservedSectionNumber(sectionNumber))
610     fatal(toString(this) + ": " + getName() +
611           " should not refer to special section " + Twine(sectionNumber));
612 
613   if ((uint32_t)sectionNumber >= sparseChunks.size())
614     fatal(toString(this) + ": " + getName() +
615           " should not refer to non-existent section " + Twine(sectionNumber));
616 
617   // Comdat handling.
618   // A comdat symbol consists of two symbol table entries.
619   // The first symbol entry has the name of the section (e.g. .text), fixed
620   // values for the other fields, and one auxiliary record.
621   // The second symbol entry has the name of the comdat symbol, called the
622   // "comdat leader".
623   // When this function is called for the first symbol entry of a comdat,
624   // it sets comdatDefs and returns None, and when it's called for the second
625   // symbol entry it reads comdatDefs and then sets it back to nullptr.
626 
627   // Handle comdat leader.
628   if (const coff_aux_section_definition *def = comdatDefs[sectionNumber]) {
629     comdatDefs[sectionNumber] = nullptr;
630     DefinedRegular *leader;
631 
632     if (sym.isExternal()) {
633       std::tie(leader, prevailing) =
634           symtab->addComdat(this, getName(), sym.getGeneric());
635     } else {
636       leader = make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
637                                     /*IsExternal*/ false, sym.getGeneric());
638       prevailing = true;
639     }
640 
641     if (def->Selection < (int)IMAGE_COMDAT_SELECT_NODUPLICATES ||
642         // Intentionally ends at IMAGE_COMDAT_SELECT_LARGEST: link.exe
643         // doesn't understand IMAGE_COMDAT_SELECT_NEWEST either.
644         def->Selection > (int)IMAGE_COMDAT_SELECT_LARGEST) {
645       fatal("unknown comdat type " + std::to_string((int)def->Selection) +
646             " for " + getName() + " in " + toString(this));
647     }
648     COMDATType selection = (COMDATType)def->Selection;
649 
650     if (leader->isCOMDAT)
651       handleComdatSelection(sym, selection, prevailing, leader);
652 
653     if (prevailing) {
654       SectionChunk *c = readSection(sectionNumber, def, getName());
655       sparseChunks[sectionNumber] = c;
656       c->sym = cast<DefinedRegular>(leader);
657       c->selection = selection;
658       cast<DefinedRegular>(leader)->data = &c->repl;
659     } else {
660       sparseChunks[sectionNumber] = nullptr;
661     }
662     return leader;
663   }
664 
665   // Prepare to handle the comdat leader symbol by setting the section's
666   // ComdatDefs pointer if we encounter a non-associative comdat.
667   if (sparseChunks[sectionNumber] == pendingComdat) {
668     if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {
669       if (def->Selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE)
670         comdatDefs[sectionNumber] = def;
671     }
672     return None;
673   }
674 
675   return createRegular(sym);
676 }
677 
678 MachineTypes ObjFile::getMachineType() {
679   if (coffObj)
680     return static_cast<MachineTypes>(coffObj->getMachine());
681   return IMAGE_FILE_MACHINE_UNKNOWN;
682 }
683 
684 ArrayRef<uint8_t> ObjFile::getDebugSection(StringRef secName) {
685   if (SectionChunk *sec = SectionChunk::findByName(debugChunks, secName))
686     return sec->consumeDebugMagic();
687   return {};
688 }
689 
690 // OBJ files systematically store critical information in a .debug$S stream,
691 // even if the TU was compiled with no debug info. At least two records are
692 // always there. S_OBJNAME stores a 32-bit signature, which is loaded into the
693 // PCHSignature member. S_COMPILE3 stores compile-time cmd-line flags. This is
694 // currently used to initialize the hotPatchable member.
695 void ObjFile::initializeFlags() {
696   ArrayRef<uint8_t> data = getDebugSection(".debug$S");
697   if (data.empty())
698     return;
699 
700   DebugSubsectionArray subsections;
701 
702   BinaryStreamReader reader(data, support::little);
703   ExitOnError exitOnErr;
704   exitOnErr(reader.readArray(subsections, data.size()));
705 
706   for (const DebugSubsectionRecord &ss : subsections) {
707     if (ss.kind() != DebugSubsectionKind::Symbols)
708       continue;
709 
710     unsigned offset = 0;
711 
712     // Only parse the first two records. We are only looking for S_OBJNAME
713     // and S_COMPILE3, and they usually appear at the beginning of the
714     // stream.
715     for (unsigned i = 0; i < 2; ++i) {
716       Expected<CVSymbol> sym = readSymbolFromStream(ss.getRecordData(), offset);
717       if (!sym) {
718         consumeError(sym.takeError());
719         return;
720       }
721       if (sym->kind() == SymbolKind::S_COMPILE3) {
722         auto cs =
723             cantFail(SymbolDeserializer::deserializeAs<Compile3Sym>(sym.get()));
724         hotPatchable =
725             (cs.Flags & CompileSym3Flags::HotPatch) != CompileSym3Flags::None;
726       }
727       if (sym->kind() == SymbolKind::S_OBJNAME) {
728         auto objName = cantFail(SymbolDeserializer::deserializeAs<ObjNameSym>(
729             sym.get()));
730         pchSignature = objName.Signature;
731       }
732       offset += sym->length();
733     }
734   }
735 }
736 
737 // Depending on the compilation flags, OBJs can refer to external files,
738 // necessary to merge this OBJ into the final PDB. We currently support two
739 // types of external files: Precomp/PCH OBJs, when compiling with /Yc and /Yu.
740 // And PDB type servers, when compiling with /Zi. This function extracts these
741 // dependencies and makes them available as a TpiSource interface (see
742 // DebugTypes.h). Both cases only happen with cl.exe: clang-cl produces regular
743 // output even with /Yc and /Yu and with /Zi.
744 void ObjFile::initializeDependencies() {
745   if (!config->debug)
746     return;
747 
748   bool isPCH = false;
749 
750   ArrayRef<uint8_t> data = getDebugSection(".debug$P");
751   if (!data.empty())
752     isPCH = true;
753   else
754     data = getDebugSection(".debug$T");
755 
756   if (data.empty())
757     return;
758 
759   CVTypeArray types;
760   BinaryStreamReader reader(data, support::little);
761   cantFail(reader.readArray(types, reader.getLength()));
762 
763   CVTypeArray::Iterator firstType = types.begin();
764   if (firstType == types.end())
765     return;
766 
767   debugTypes.emplace(types);
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 StringRef ltrim1(StringRef s, const char *chars) {
792   if (!s.empty() && strchr(chars, s[0]))
793     return s.substr(1);
794   return s;
795 }
796 
797 void ImportFile::parse() {
798   const char *buf = mb.getBufferStart();
799   const auto *hdr = reinterpret_cast<const coff_import_header *>(buf);
800 
801   // Check if the total size is valid.
802   if (mb.getBufferSize() != sizeof(*hdr) + hdr->SizeOfData)
803     fatal("broken import library");
804 
805   // Read names and create an __imp_ symbol.
806   StringRef name = saver.save(StringRef(buf + sizeof(*hdr)));
807   StringRef impName = saver.save("__imp_" + name);
808   const char *nameStart = buf + sizeof(coff_import_header) + name.size() + 1;
809   dllName = StringRef(nameStart);
810   StringRef extName;
811   switch (hdr->getNameType()) {
812   case IMPORT_ORDINAL:
813     extName = "";
814     break;
815   case IMPORT_NAME:
816     extName = name;
817     break;
818   case IMPORT_NAME_NOPREFIX:
819     extName = ltrim1(name, "?@_");
820     break;
821   case IMPORT_NAME_UNDECORATE:
822     extName = ltrim1(name, "?@_");
823     extName = extName.substr(0, extName.find('@'));
824     break;
825   }
826 
827   this->hdr = hdr;
828   externalName = extName;
829 
830   impSym = symtab->addImportData(impName, this);
831   // If this was a duplicate, we logged an error but may continue;
832   // in this case, impSym is nullptr.
833   if (!impSym)
834     return;
835 
836   if (hdr->getType() == llvm::COFF::IMPORT_CONST)
837     static_cast<void>(symtab->addImportData(name, this));
838 
839   // If type is function, we need to create a thunk which jump to an
840   // address pointed by the __imp_ symbol. (This allows you to call
841   // DLL functions just like regular non-DLL functions.)
842   if (hdr->getType() == llvm::COFF::IMPORT_CODE)
843     thunkSym = symtab->addImportThunk(
844         name, cast_or_null<DefinedImportData>(impSym), hdr->Machine);
845 }
846 
847 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
848                          uint64_t offsetInArchive,
849                          std::vector<Symbol *> &&symbols)
850     : InputFile(BitcodeKind, mb), symbols(std::move(symbols)) {
851   std::string path = mb.getBufferIdentifier().str();
852   if (config->thinLTOIndexOnly)
853     path = replaceThinLTOSuffix(mb.getBufferIdentifier());
854 
855   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
856   // name. If two archives define two members with the same name, this
857   // causes a collision which result in only one of the objects being taken
858   // into consideration at LTO time (which very likely causes undefined
859   // symbols later in the link stage). So we append file offset to make
860   // filename unique.
861   MemoryBufferRef mbref(
862       mb.getBuffer(),
863       saver.save(archiveName + path +
864                  (archiveName.empty() ? "" : utostr(offsetInArchive))));
865 
866   obj = check(lto::InputFile::create(mbref));
867 }
868 
869 void BitcodeFile::parse() {
870   std::vector<std::pair<Symbol *, bool>> comdat(obj->getComdatTable().size());
871   for (size_t i = 0; i != obj->getComdatTable().size(); ++i)
872     // FIXME: lto::InputFile doesn't keep enough data to do correct comdat
873     // selection handling.
874     comdat[i] = symtab->addComdat(this, saver.save(obj->getComdatTable()[i]));
875   for (const lto::InputFile::Symbol &objSym : obj->symbols()) {
876     StringRef symName = saver.save(objSym.getName());
877     int comdatIndex = objSym.getComdatIndex();
878     Symbol *sym;
879     if (objSym.isUndefined()) {
880       sym = symtab->addUndefined(symName, this, false);
881     } else if (objSym.isCommon()) {
882       sym = symtab->addCommon(this, symName, objSym.getCommonSize());
883     } else if (objSym.isWeak() && objSym.isIndirect()) {
884       // Weak external.
885       sym = symtab->addUndefined(symName, this, true);
886       std::string fallback = objSym.getCOFFWeakExternalFallback();
887       Symbol *alias = symtab->addUndefined(saver.save(fallback));
888       checkAndSetWeakAlias(symtab, this, sym, alias);
889     } else if (comdatIndex != -1) {
890       if (symName == obj->getComdatTable()[comdatIndex])
891         sym = comdat[comdatIndex].first;
892       else if (comdat[comdatIndex].second)
893         sym = symtab->addRegular(this, symName);
894       else
895         sym = symtab->addUndefined(symName, this, false);
896     } else {
897       sym = symtab->addRegular(this, symName);
898     }
899     symbols.push_back(sym);
900     if (objSym.isUsed())
901       config->gcroot.push_back(sym);
902   }
903   directives = obj->getCOFFLinkerOpts();
904 }
905 
906 MachineTypes BitcodeFile::getMachineType() {
907   switch (Triple(obj->getTargetTriple()).getArch()) {
908   case Triple::x86_64:
909     return AMD64;
910   case Triple::x86:
911     return I386;
912   case Triple::arm:
913     return ARMNT;
914   case Triple::aarch64:
915     return ARM64;
916   default:
917     return IMAGE_FILE_MACHINE_UNKNOWN;
918   }
919 }
920 
921 std::string replaceThinLTOSuffix(StringRef path) {
922   StringRef suffix = config->thinLTOObjectSuffixReplace.first;
923   StringRef repl = config->thinLTOObjectSuffixReplace.second;
924 
925   if (path.consume_back(suffix))
926     return (path + repl).str();
927   return path;
928 }
929 
930 } // namespace coff
931 } // namespace lld
932