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