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 "COFFLinkerContext.h"
11 #include "Chunks.h"
12 #include "Config.h"
13 #include "DebugTypes.h"
14 #include "Driver.h"
15 #include "SymbolTable.h"
16 #include "Symbols.h"
17 #include "lld/Common/DWARF.h"
18 #include "lld/Common/ErrorHandler.h"
19 #include "lld/Common/Memory.h"
20 #include "llvm-c/lto.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/BinaryFormat/COFF.h"
25 #include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
26 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
27 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
28 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
29 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
30 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
31 #include "llvm/LTO/LTO.h"
32 #include "llvm/Object/Binary.h"
33 #include "llvm/Object/COFF.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/Error.h"
37 #include "llvm/Support/ErrorOr.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include <cstring>
42 #include <system_error>
43 #include <utility>
44 
45 using namespace llvm;
46 using namespace llvm::COFF;
47 using namespace llvm::codeview;
48 using namespace llvm::object;
49 using namespace llvm::support::endian;
50 using namespace lld;
51 using namespace lld::coff;
52 
53 using llvm::Triple;
54 using llvm::support::ulittle32_t;
55 
56 // Returns the last element of a path, which is supposed to be a filename.
57 static StringRef getBasename(StringRef path) {
58   return sys::path::filename(path, sys::path::Style::windows);
59 }
60 
61 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
62 std::string lld::toString(const coff::InputFile *file) {
63   if (!file)
64     return "<internal>";
65   if (file->parentName.empty() || file->kind() == coff::InputFile::ImportKind)
66     return std::string(file->getName());
67 
68   return (getBasename(file->parentName) + "(" + getBasename(file->getName()) +
69           ")")
70       .str();
71 }
72 
73 /// Checks that Source is compatible with being a weak alias to Target.
74 /// If Source is Undefined and has no weak alias set, makes it a weak
75 /// alias to Target.
76 static void checkAndSetWeakAlias(SymbolTable *symtab, InputFile *f,
77                                  Symbol *source, Symbol *target) {
78   if (auto *u = dyn_cast<Undefined>(source)) {
79     if (u->weakAlias && u->weakAlias != target) {
80       // Weak aliases as produced by GCC are named in the form
81       // .weak.<weaksymbol>.<othersymbol>, where <othersymbol> is the name
82       // of another symbol emitted near the weak symbol.
83       // Just use the definition from the first object file that defined
84       // this weak symbol.
85       if (config->mingw)
86         return;
87       symtab->reportDuplicate(source, f);
88     }
89     u->weakAlias = target;
90   }
91 }
92 
93 static bool ignoredSymbolName(StringRef name) {
94   return name == "@feat.00" || name == "@comp.id";
95 }
96 
97 ArchiveFile::ArchiveFile(COFFLinkerContext &ctx, MemoryBufferRef m)
98     : InputFile(ctx, 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     ctx.symtab.addLazyArchive(this, sym);
107 }
108 
109 // Returns a buffer pointing to a member file containing a given symbol.
110 void ArchiveFile::addMember(const Archive::Symbol &sym) {
111   const Archive::Child &c =
112       CHECK(sym.getMember(),
113             "could not get the member for symbol " + toCOFFString(sym));
114 
115   // Return an empty buffer if we have already returned the same buffer.
116   if (!seen.insert(c.getChildOffset()).second)
117     return;
118 
119   driver->enqueueArchiveMember(c, sym, getName());
120 }
121 
122 std::vector<MemoryBufferRef> lld::coff::getArchiveMembers(Archive *file) {
123   std::vector<MemoryBufferRef> v;
124   Error err = Error::success();
125   for (const Archive::Child &c : file->children(err)) {
126     MemoryBufferRef mbref =
127         CHECK(c.getMemoryBufferRef(),
128               file->getFileName() +
129                   ": could not get the buffer for a child of the archive");
130     v.push_back(mbref);
131   }
132   if (err)
133     fatal(file->getFileName() +
134           ": Archive::children failed: " + toString(std::move(err)));
135   return v;
136 }
137 
138 void ObjFile::parseLazy() {
139   // Native object file.
140   std::unique_ptr<Binary> coffObjPtr = CHECK(createBinary(mb), this);
141   COFFObjectFile *coffObj = cast<COFFObjectFile>(coffObjPtr.get());
142   uint32_t numSymbols = coffObj->getNumberOfSymbols();
143   for (uint32_t i = 0; i < numSymbols; ++i) {
144     COFFSymbolRef coffSym = check(coffObj->getSymbol(i));
145     if (coffSym.isUndefined() || !coffSym.isExternal() ||
146         coffSym.isWeakExternal())
147       continue;
148     StringRef name = check(coffObj->getSymbolName(coffSym));
149     if (coffSym.isAbsolute() && ignoredSymbolName(name))
150       continue;
151     ctx.symtab.addLazyObject(this, name);
152     i += coffSym.getNumberOfAuxSymbols();
153   }
154 }
155 
156 void ObjFile::parse() {
157   // Parse a memory buffer as a COFF file.
158   std::unique_ptr<Binary> bin = CHECK(createBinary(mb), this);
159 
160   if (auto *obj = dyn_cast<COFFObjectFile>(bin.get())) {
161     bin.release();
162     coffObj.reset(obj);
163   } else {
164     fatal(toString(this) + " is not a COFF file");
165   }
166 
167   // Read section and symbol tables.
168   initializeChunks();
169   initializeSymbols();
170   initializeFlags();
171   initializeDependencies();
172 }
173 
174 const coff_section *ObjFile::getSection(uint32_t i) {
175   auto sec = coffObj->getSection(i);
176   if (!sec)
177     fatal("getSection failed: #" + Twine(i) + ": " + toString(sec.takeError()));
178   return *sec;
179 }
180 
181 // We set SectionChunk pointers in the SparseChunks vector to this value
182 // temporarily to mark comdat sections as having an unknown resolution. As we
183 // walk the object file's symbol table, once we visit either a leader symbol or
184 // an associative section definition together with the parent comdat's leader,
185 // we set the pointer to either nullptr (to mark the section as discarded) or a
186 // valid SectionChunk for that section.
187 static SectionChunk *const pendingComdat = reinterpret_cast<SectionChunk *>(1);
188 
189 void ObjFile::initializeChunks() {
190   uint32_t numSections = coffObj->getNumberOfSections();
191   sparseChunks.resize(numSections + 1);
192   for (uint32_t i = 1; i < numSections + 1; ++i) {
193     const coff_section *sec = getSection(i);
194     if (sec->Characteristics & IMAGE_SCN_LNK_COMDAT)
195       sparseChunks[i] = pendingComdat;
196     else
197       sparseChunks[i] = readSection(i, nullptr, "");
198   }
199 }
200 
201 SectionChunk *ObjFile::readSection(uint32_t sectionNumber,
202                                    const coff_aux_section_definition *def,
203                                    StringRef leaderName) {
204   const coff_section *sec = getSection(sectionNumber);
205 
206   StringRef name;
207   if (Expected<StringRef> e = coffObj->getSectionName(sec))
208     name = *e;
209   else
210     fatal("getSectionName failed: #" + Twine(sectionNumber) + ": " +
211           toString(e.takeError()));
212 
213   if (name == ".drectve") {
214     ArrayRef<uint8_t> data;
215     cantFail(coffObj->getSectionContents(sec, data));
216     directives = StringRef((const char *)data.data(), data.size());
217     return nullptr;
218   }
219 
220   if (name == ".llvm_addrsig") {
221     addrsigSec = sec;
222     return nullptr;
223   }
224 
225   if (name == ".llvm.call-graph-profile") {
226     callgraphSec = sec;
227     return nullptr;
228   }
229 
230   // Object files may have DWARF debug info or MS CodeView debug info
231   // (or both).
232   //
233   // DWARF sections don't need any special handling from the perspective
234   // of the linker; they are just a data section containing relocations.
235   // We can just link them to complete debug info.
236   //
237   // CodeView needs linker support. We need to interpret debug info,
238   // and then write it to a separate .pdb file.
239 
240   // Ignore DWARF debug info unless /debug is given.
241   if (!config->debug && name.startswith(".debug_"))
242     return nullptr;
243 
244   if (sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
245     return nullptr;
246   auto *c = make<SectionChunk>(this, sec);
247   if (def)
248     c->checksum = def->CheckSum;
249 
250   // CodeView sections are stored to a different vector because they are not
251   // linked in the regular manner.
252   if (c->isCodeView())
253     debugChunks.push_back(c);
254   else if (name == ".gfids$y")
255     guardFidChunks.push_back(c);
256   else if (name == ".giats$y")
257     guardIATChunks.push_back(c);
258   else if (name == ".gljmp$y")
259     guardLJmpChunks.push_back(c);
260   else if (name == ".gehcont$y")
261     guardEHContChunks.push_back(c);
262   else if (name == ".sxdata")
263     sxDataChunks.push_back(c);
264   else if (config->tailMerge && sec->NumberOfRelocations == 0 &&
265            name == ".rdata" && leaderName.startswith("??_C@"))
266     // COFF sections that look like string literal sections (i.e. no
267     // relocations, in .rdata, leader symbol name matches the MSVC name mangling
268     // for string literals) are subject to string tail merging.
269     MergeChunk::addSection(ctx, c);
270   else if (name == ".rsrc" || name.startswith(".rsrc$"))
271     resourceChunks.push_back(c);
272   else
273     chunks.push_back(c);
274 
275   return c;
276 }
277 
278 void ObjFile::includeResourceChunks() {
279   chunks.insert(chunks.end(), resourceChunks.begin(), resourceChunks.end());
280 }
281 
282 void ObjFile::readAssociativeDefinition(
283     COFFSymbolRef sym, const coff_aux_section_definition *def) {
284   readAssociativeDefinition(sym, def, def->getNumber(sym.isBigObj()));
285 }
286 
287 void ObjFile::readAssociativeDefinition(COFFSymbolRef sym,
288                                         const coff_aux_section_definition *def,
289                                         uint32_t parentIndex) {
290   SectionChunk *parent = sparseChunks[parentIndex];
291   int32_t sectionNumber = sym.getSectionNumber();
292 
293   auto diag = [&]() {
294     StringRef name = check(coffObj->getSymbolName(sym));
295 
296     StringRef parentName;
297     const coff_section *parentSec = getSection(parentIndex);
298     if (Expected<StringRef> e = coffObj->getSectionName(parentSec))
299       parentName = *e;
300     error(toString(this) + ": associative comdat " + name + " (sec " +
301           Twine(sectionNumber) + ") has invalid reference to section " +
302           parentName + " (sec " + Twine(parentIndex) + ")");
303   };
304 
305   if (parent == pendingComdat) {
306     // This can happen if an associative comdat refers to another associative
307     // comdat that appears after it (invalid per COFF spec) or to a section
308     // without any symbols.
309     diag();
310     return;
311   }
312 
313   // Check whether the parent is prevailing. If it is, so are we, and we read
314   // the section; otherwise mark it as discarded.
315   if (parent) {
316     SectionChunk *c = readSection(sectionNumber, def, "");
317     sparseChunks[sectionNumber] = c;
318     if (c) {
319       c->selection = IMAGE_COMDAT_SELECT_ASSOCIATIVE;
320       parent->addAssociative(c);
321     }
322   } else {
323     sparseChunks[sectionNumber] = nullptr;
324   }
325 }
326 
327 void ObjFile::recordPrevailingSymbolForMingw(
328     COFFSymbolRef sym, DenseMap<StringRef, uint32_t> &prevailingSectionMap) {
329   // For comdat symbols in executable sections, where this is the copy
330   // of the section chunk we actually include instead of discarding it,
331   // add the symbol to a map to allow using it for implicitly
332   // associating .[px]data$<func> sections to it.
333   // Use the suffix from the .text$<func> instead of the leader symbol
334   // name, for cases where the names differ (i386 mangling/decorations,
335   // cases where the leader is a weak symbol named .weak.func.default*).
336   int32_t sectionNumber = sym.getSectionNumber();
337   SectionChunk *sc = sparseChunks[sectionNumber];
338   if (sc && sc->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE) {
339     StringRef name = sc->getSectionName().split('$').second;
340     prevailingSectionMap[name] = sectionNumber;
341   }
342 }
343 
344 void ObjFile::maybeAssociateSEHForMingw(
345     COFFSymbolRef sym, const coff_aux_section_definition *def,
346     const DenseMap<StringRef, uint32_t> &prevailingSectionMap) {
347   StringRef name = check(coffObj->getSymbolName(sym));
348   if (name.consume_front(".pdata$") || name.consume_front(".xdata$") ||
349       name.consume_front(".eh_frame$")) {
350     // For MinGW, treat .[px]data$<func> and .eh_frame$<func> as implicitly
351     // associative to the symbol <func>.
352     auto parentSym = prevailingSectionMap.find(name);
353     if (parentSym != prevailingSectionMap.end())
354       readAssociativeDefinition(sym, def, parentSym->second);
355   }
356 }
357 
358 Symbol *ObjFile::createRegular(COFFSymbolRef sym) {
359   SectionChunk *sc = sparseChunks[sym.getSectionNumber()];
360   if (sym.isExternal()) {
361     StringRef name = check(coffObj->getSymbolName(sym));
362     if (sc)
363       return ctx.symtab.addRegular(this, name, sym.getGeneric(), sc,
364                                    sym.getValue());
365     // For MinGW symbols named .weak.* that point to a discarded section,
366     // don't create an Undefined symbol. If nothing ever refers to the symbol,
367     // everything should be fine. If something actually refers to the symbol
368     // (e.g. the undefined weak alias), linking will fail due to undefined
369     // references at the end.
370     if (config->mingw && name.startswith(".weak."))
371       return nullptr;
372     return ctx.symtab.addUndefined(name, this, false);
373   }
374   if (sc)
375     return make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
376                                 /*IsExternal*/ false, sym.getGeneric(), sc);
377   return nullptr;
378 }
379 
380 void ObjFile::initializeSymbols() {
381   uint32_t numSymbols = coffObj->getNumberOfSymbols();
382   symbols.resize(numSymbols);
383 
384   SmallVector<std::pair<Symbol *, uint32_t>, 8> weakAliases;
385   std::vector<uint32_t> pendingIndexes;
386   pendingIndexes.reserve(numSymbols);
387 
388   DenseMap<StringRef, uint32_t> prevailingSectionMap;
389   std::vector<const coff_aux_section_definition *> comdatDefs(
390       coffObj->getNumberOfSections() + 1);
391 
392   for (uint32_t i = 0; i < numSymbols; ++i) {
393     COFFSymbolRef coffSym = check(coffObj->getSymbol(i));
394     bool prevailingComdat;
395     if (coffSym.isUndefined()) {
396       symbols[i] = createUndefined(coffSym);
397     } else if (coffSym.isWeakExternal()) {
398       symbols[i] = createUndefined(coffSym);
399       uint32_t tagIndex = coffSym.getAux<coff_aux_weak_external>()->TagIndex;
400       weakAliases.emplace_back(symbols[i], tagIndex);
401     } else if (Optional<Symbol *> optSym =
402                    createDefined(coffSym, comdatDefs, prevailingComdat)) {
403       symbols[i] = *optSym;
404       if (config->mingw && prevailingComdat)
405         recordPrevailingSymbolForMingw(coffSym, prevailingSectionMap);
406     } else {
407       // createDefined() returns None if a symbol belongs to a section that
408       // was pending at the point when the symbol was read. This can happen in
409       // two cases:
410       // 1) section definition symbol for a comdat leader;
411       // 2) symbol belongs to a comdat section associated with another section.
412       // In both of these cases, we can expect the section to be resolved by
413       // the time we finish visiting the remaining symbols in the symbol
414       // table. So we postpone the handling of this symbol until that time.
415       pendingIndexes.push_back(i);
416     }
417     i += coffSym.getNumberOfAuxSymbols();
418   }
419 
420   for (uint32_t i : pendingIndexes) {
421     COFFSymbolRef sym = check(coffObj->getSymbol(i));
422     if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {
423       if (def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
424         readAssociativeDefinition(sym, def);
425       else if (config->mingw)
426         maybeAssociateSEHForMingw(sym, def, prevailingSectionMap);
427     }
428     if (sparseChunks[sym.getSectionNumber()] == pendingComdat) {
429       StringRef name = check(coffObj->getSymbolName(sym));
430       log("comdat section " + name +
431           " without leader and unassociated, discarding");
432       continue;
433     }
434     symbols[i] = createRegular(sym);
435   }
436 
437   for (auto &kv : weakAliases) {
438     Symbol *sym = kv.first;
439     uint32_t idx = kv.second;
440     checkAndSetWeakAlias(&ctx.symtab, this, sym, symbols[idx]);
441   }
442 
443   // Free the memory used by sparseChunks now that symbol loading is finished.
444   decltype(sparseChunks)().swap(sparseChunks);
445 }
446 
447 Symbol *ObjFile::createUndefined(COFFSymbolRef sym) {
448   StringRef name = check(coffObj->getSymbolName(sym));
449   return ctx.symtab.addUndefined(name, this, sym.isWeakExternal());
450 }
451 
452 static const coff_aux_section_definition *findSectionDef(COFFObjectFile *obj,
453                                                          int32_t section) {
454   uint32_t numSymbols = obj->getNumberOfSymbols();
455   for (uint32_t i = 0; i < numSymbols; ++i) {
456     COFFSymbolRef sym = check(obj->getSymbol(i));
457     if (sym.getSectionNumber() != section)
458       continue;
459     if (const coff_aux_section_definition *def = sym.getSectionDefinition())
460       return def;
461   }
462   return nullptr;
463 }
464 
465 void ObjFile::handleComdatSelection(
466     COFFSymbolRef sym, COMDATType &selection, bool &prevailing,
467     DefinedRegular *leader,
468     const llvm::object::coff_aux_section_definition *def) {
469   if (prevailing)
470     return;
471   // There's already an existing comdat for this symbol: `Leader`.
472   // Use the comdats's selection field to determine if the new
473   // symbol in `Sym` should be discarded, produce a duplicate symbol
474   // error, etc.
475 
476   SectionChunk *leaderChunk = leader->getChunk();
477   COMDATType leaderSelection = leaderChunk->selection;
478 
479   assert(leader->data && "Comdat leader without SectionChunk?");
480   if (isa<BitcodeFile>(leader->file)) {
481     // If the leader is only a LTO symbol, we don't know e.g. its final size
482     // yet, so we can't do the full strict comdat selection checking yet.
483     selection = leaderSelection = IMAGE_COMDAT_SELECT_ANY;
484   }
485 
486   if ((selection == IMAGE_COMDAT_SELECT_ANY &&
487        leaderSelection == IMAGE_COMDAT_SELECT_LARGEST) ||
488       (selection == IMAGE_COMDAT_SELECT_LARGEST &&
489        leaderSelection == IMAGE_COMDAT_SELECT_ANY)) {
490     // cl.exe picks "any" for vftables when building with /GR- and
491     // "largest" when building with /GR. To be able to link object files
492     // compiled with each flag, "any" and "largest" are merged as "largest".
493     leaderSelection = selection = IMAGE_COMDAT_SELECT_LARGEST;
494   }
495 
496   // GCCs __declspec(selectany) doesn't actually pick "any" but "same size as".
497   // Clang on the other hand picks "any". To be able to link two object files
498   // with a __declspec(selectany) declaration, one compiled with gcc and the
499   // other with clang, we merge them as proper "same size as"
500   if (config->mingw && ((selection == IMAGE_COMDAT_SELECT_ANY &&
501                          leaderSelection == IMAGE_COMDAT_SELECT_SAME_SIZE) ||
502                         (selection == IMAGE_COMDAT_SELECT_SAME_SIZE &&
503                          leaderSelection == IMAGE_COMDAT_SELECT_ANY))) {
504     leaderSelection = selection = IMAGE_COMDAT_SELECT_SAME_SIZE;
505   }
506 
507   // Other than that, comdat selections must match.  This is a bit more
508   // strict than link.exe which allows merging "any" and "largest" if "any"
509   // is the first symbol the linker sees, and it allows merging "largest"
510   // with everything (!) if "largest" is the first symbol the linker sees.
511   // Making this symmetric independent of which selection is seen first
512   // seems better though.
513   // (This behavior matches ModuleLinker::getComdatResult().)
514   if (selection != leaderSelection) {
515     log(("conflicting comdat type for " + toString(*leader) + ": " +
516          Twine((int)leaderSelection) + " in " + toString(leader->getFile()) +
517          " and " + Twine((int)selection) + " in " + toString(this))
518             .str());
519     ctx.symtab.reportDuplicate(leader, this);
520     return;
521   }
522 
523   switch (selection) {
524   case IMAGE_COMDAT_SELECT_NODUPLICATES:
525     ctx.symtab.reportDuplicate(leader, this);
526     break;
527 
528   case IMAGE_COMDAT_SELECT_ANY:
529     // Nothing to do.
530     break;
531 
532   case IMAGE_COMDAT_SELECT_SAME_SIZE:
533     if (leaderChunk->getSize() != getSection(sym)->SizeOfRawData) {
534       if (!config->mingw) {
535         ctx.symtab.reportDuplicate(leader, this);
536       } else {
537         const coff_aux_section_definition *leaderDef = nullptr;
538         if (leaderChunk->file)
539           leaderDef = findSectionDef(leaderChunk->file->getCOFFObj(),
540                                      leaderChunk->getSectionNumber());
541         if (!leaderDef || leaderDef->Length != def->Length)
542           ctx.symtab.reportDuplicate(leader, this);
543       }
544     }
545     break;
546 
547   case IMAGE_COMDAT_SELECT_EXACT_MATCH: {
548     SectionChunk newChunk(this, getSection(sym));
549     // link.exe only compares section contents here and doesn't complain
550     // if the two comdat sections have e.g. different alignment.
551     // Match that.
552     if (leaderChunk->getContents() != newChunk.getContents())
553       ctx.symtab.reportDuplicate(leader, this, &newChunk, sym.getValue());
554     break;
555   }
556 
557   case IMAGE_COMDAT_SELECT_ASSOCIATIVE:
558     // createDefined() is never called for IMAGE_COMDAT_SELECT_ASSOCIATIVE.
559     // (This means lld-link doesn't produce duplicate symbol errors for
560     // associative comdats while link.exe does, but associate comdats
561     // are never extern in practice.)
562     llvm_unreachable("createDefined not called for associative comdats");
563 
564   case IMAGE_COMDAT_SELECT_LARGEST:
565     if (leaderChunk->getSize() < getSection(sym)->SizeOfRawData) {
566       // Replace the existing comdat symbol with the new one.
567       StringRef name = check(coffObj->getSymbolName(sym));
568       // FIXME: This is incorrect: With /opt:noref, the previous sections
569       // make it into the final executable as well. Correct handling would
570       // be to undo reading of the whole old section that's being replaced,
571       // or doing one pass that determines what the final largest comdat
572       // is for all IMAGE_COMDAT_SELECT_LARGEST comdats and then reading
573       // only the largest one.
574       replaceSymbol<DefinedRegular>(leader, this, name, /*IsCOMDAT*/ true,
575                                     /*IsExternal*/ true, sym.getGeneric(),
576                                     nullptr);
577       prevailing = true;
578     }
579     break;
580 
581   case IMAGE_COMDAT_SELECT_NEWEST:
582     llvm_unreachable("should have been rejected earlier");
583   }
584 }
585 
586 Optional<Symbol *> ObjFile::createDefined(
587     COFFSymbolRef sym,
588     std::vector<const coff_aux_section_definition *> &comdatDefs,
589     bool &prevailing) {
590   prevailing = false;
591   auto getName = [&]() { return check(coffObj->getSymbolName(sym)); };
592 
593   if (sym.isCommon()) {
594     auto *c = make<CommonChunk>(sym);
595     chunks.push_back(c);
596     return ctx.symtab.addCommon(this, getName(), sym.getValue(),
597                                 sym.getGeneric(), c);
598   }
599 
600   if (sym.isAbsolute()) {
601     StringRef name = getName();
602 
603     if (name == "@feat.00")
604       feat00Flags = sym.getValue();
605     // Skip special symbols.
606     if (ignoredSymbolName(name))
607       return nullptr;
608 
609     if (sym.isExternal())
610       return ctx.symtab.addAbsolute(name, sym);
611     return make<DefinedAbsolute>(name, sym);
612   }
613 
614   int32_t sectionNumber = sym.getSectionNumber();
615   if (sectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
616     return nullptr;
617 
618   if (llvm::COFF::isReservedSectionNumber(sectionNumber))
619     fatal(toString(this) + ": " + getName() +
620           " should not refer to special section " + Twine(sectionNumber));
621 
622   if ((uint32_t)sectionNumber >= sparseChunks.size())
623     fatal(toString(this) + ": " + getName() +
624           " should not refer to non-existent section " + Twine(sectionNumber));
625 
626   // Comdat handling.
627   // A comdat symbol consists of two symbol table entries.
628   // The first symbol entry has the name of the section (e.g. .text), fixed
629   // values for the other fields, and one auxiliary record.
630   // The second symbol entry has the name of the comdat symbol, called the
631   // "comdat leader".
632   // When this function is called for the first symbol entry of a comdat,
633   // it sets comdatDefs and returns None, and when it's called for the second
634   // symbol entry it reads comdatDefs and then sets it back to nullptr.
635 
636   // Handle comdat leader.
637   if (const coff_aux_section_definition *def = comdatDefs[sectionNumber]) {
638     comdatDefs[sectionNumber] = nullptr;
639     DefinedRegular *leader;
640 
641     if (sym.isExternal()) {
642       std::tie(leader, prevailing) =
643           ctx.symtab.addComdat(this, getName(), sym.getGeneric());
644     } else {
645       leader = make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
646                                     /*IsExternal*/ false, sym.getGeneric());
647       prevailing = true;
648     }
649 
650     if (def->Selection < (int)IMAGE_COMDAT_SELECT_NODUPLICATES ||
651         // Intentionally ends at IMAGE_COMDAT_SELECT_LARGEST: link.exe
652         // doesn't understand IMAGE_COMDAT_SELECT_NEWEST either.
653         def->Selection > (int)IMAGE_COMDAT_SELECT_LARGEST) {
654       fatal("unknown comdat type " + std::to_string((int)def->Selection) +
655             " for " + getName() + " in " + toString(this));
656     }
657     COMDATType selection = (COMDATType)def->Selection;
658 
659     if (leader->isCOMDAT)
660       handleComdatSelection(sym, selection, prevailing, leader, def);
661 
662     if (prevailing) {
663       SectionChunk *c = readSection(sectionNumber, def, getName());
664       sparseChunks[sectionNumber] = c;
665       c->sym = cast<DefinedRegular>(leader);
666       c->selection = selection;
667       cast<DefinedRegular>(leader)->data = &c->repl;
668     } else {
669       sparseChunks[sectionNumber] = nullptr;
670     }
671     return leader;
672   }
673 
674   // Prepare to handle the comdat leader symbol by setting the section's
675   // ComdatDefs pointer if we encounter a non-associative comdat.
676   if (sparseChunks[sectionNumber] == pendingComdat) {
677     if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {
678       if (def->Selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE)
679         comdatDefs[sectionNumber] = def;
680     }
681     return None;
682   }
683 
684   return createRegular(sym);
685 }
686 
687 MachineTypes ObjFile::getMachineType() {
688   if (coffObj)
689     return static_cast<MachineTypes>(coffObj->getMachine());
690   return IMAGE_FILE_MACHINE_UNKNOWN;
691 }
692 
693 ArrayRef<uint8_t> ObjFile::getDebugSection(StringRef secName) {
694   if (SectionChunk *sec = SectionChunk::findByName(debugChunks, secName))
695     return sec->consumeDebugMagic();
696   return {};
697 }
698 
699 // OBJ files systematically store critical information in a .debug$S stream,
700 // even if the TU was compiled with no debug info. At least two records are
701 // always there. S_OBJNAME stores a 32-bit signature, which is loaded into the
702 // PCHSignature member. S_COMPILE3 stores compile-time cmd-line flags. This is
703 // currently used to initialize the hotPatchable member.
704 void ObjFile::initializeFlags() {
705   ArrayRef<uint8_t> data = getDebugSection(".debug$S");
706   if (data.empty())
707     return;
708 
709   DebugSubsectionArray subsections;
710 
711   BinaryStreamReader reader(data, support::little);
712   ExitOnError exitOnErr;
713   exitOnErr(reader.readArray(subsections, data.size()));
714 
715   for (const DebugSubsectionRecord &ss : subsections) {
716     if (ss.kind() != DebugSubsectionKind::Symbols)
717       continue;
718 
719     unsigned offset = 0;
720 
721     // Only parse the first two records. We are only looking for S_OBJNAME
722     // and S_COMPILE3, and they usually appear at the beginning of the
723     // stream.
724     for (unsigned i = 0; i < 2; ++i) {
725       Expected<CVSymbol> sym = readSymbolFromStream(ss.getRecordData(), offset);
726       if (!sym) {
727         consumeError(sym.takeError());
728         return;
729       }
730       if (sym->kind() == SymbolKind::S_COMPILE3) {
731         auto cs =
732             cantFail(SymbolDeserializer::deserializeAs<Compile3Sym>(sym.get()));
733         hotPatchable =
734             (cs.Flags & CompileSym3Flags::HotPatch) != CompileSym3Flags::None;
735       }
736       if (sym->kind() == SymbolKind::S_OBJNAME) {
737         auto objName = cantFail(SymbolDeserializer::deserializeAs<ObjNameSym>(
738             sym.get()));
739         pchSignature = objName.Signature;
740       }
741       offset += sym->length();
742     }
743   }
744 }
745 
746 // Depending on the compilation flags, OBJs can refer to external files,
747 // necessary to merge this OBJ into the final PDB. We currently support two
748 // types of external files: Precomp/PCH OBJs, when compiling with /Yc and /Yu.
749 // And PDB type servers, when compiling with /Zi. This function extracts these
750 // dependencies and makes them available as a TpiSource interface (see
751 // DebugTypes.h). Both cases only happen with cl.exe: clang-cl produces regular
752 // output even with /Yc and /Yu and with /Zi.
753 void ObjFile::initializeDependencies() {
754   if (!config->debug)
755     return;
756 
757   bool isPCH = false;
758 
759   ArrayRef<uint8_t> data = getDebugSection(".debug$P");
760   if (!data.empty())
761     isPCH = true;
762   else
763     data = getDebugSection(".debug$T");
764 
765   // symbols but no types, make a plain, empty TpiSource anyway, because it
766   // simplifies adding the symbols later.
767   if (data.empty()) {
768     if (!debugChunks.empty())
769       debugTypesObj = makeTpiSource(ctx, this);
770     return;
771   }
772 
773   // Get the first type record. It will indicate if this object uses a type
774   // server (/Zi) or a PCH file (/Yu).
775   CVTypeArray types;
776   BinaryStreamReader reader(data, support::little);
777   cantFail(reader.readArray(types, reader.getLength()));
778   CVTypeArray::Iterator firstType = types.begin();
779   if (firstType == types.end())
780     return;
781 
782   // Remember the .debug$T or .debug$P section.
783   debugTypes = data;
784 
785   // This object file is a PCH file that others will depend on.
786   if (isPCH) {
787     debugTypesObj = makePrecompSource(ctx, this);
788     return;
789   }
790 
791   // This object file was compiled with /Zi. Enqueue the PDB dependency.
792   if (firstType->kind() == LF_TYPESERVER2) {
793     TypeServer2Record ts = cantFail(
794         TypeDeserializer::deserializeAs<TypeServer2Record>(firstType->data()));
795     debugTypesObj = makeUseTypeServerSource(ctx, this, ts);
796     enqueuePdbFile(ts.getName(), this);
797     return;
798   }
799 
800   // This object was compiled with /Yu. It uses types from another object file
801   // with a matching signature.
802   if (firstType->kind() == LF_PRECOMP) {
803     PrecompRecord precomp = cantFail(
804         TypeDeserializer::deserializeAs<PrecompRecord>(firstType->data()));
805     debugTypesObj = makeUsePrecompSource(ctx, this, precomp);
806     // Drop the LF_PRECOMP record from the input stream.
807     debugTypes = debugTypes.drop_front(firstType->RecordData.size());
808     return;
809   }
810 
811   // This is a plain old object file.
812   debugTypesObj = makeTpiSource(ctx, this);
813 }
814 
815 // Make a PDB path assuming the PDB is in the same folder as the OBJ
816 static std::string getPdbBaseName(ObjFile *file, StringRef tSPath) {
817   StringRef localPath =
818       !file->parentName.empty() ? file->parentName : file->getName();
819   SmallString<128> path = sys::path::parent_path(localPath);
820 
821   // Currently, type server PDBs are only created by MSVC cl, which only runs
822   // on Windows, so we can assume type server paths are Windows style.
823   sys::path::append(path,
824                     sys::path::filename(tSPath, sys::path::Style::windows));
825   return std::string(path.str());
826 }
827 
828 // The casing of the PDB path stamped in the OBJ can differ from the actual path
829 // on disk. With this, we ensure to always use lowercase as a key for the
830 // pdbInputFileInstances map, at least on Windows.
831 static std::string normalizePdbPath(StringRef path) {
832 #if defined(_WIN32)
833   return path.lower();
834 #else // LINUX
835   return std::string(path);
836 #endif
837 }
838 
839 // If existing, return the actual PDB path on disk.
840 static Optional<std::string> findPdbPath(StringRef pdbPath,
841                                          ObjFile *dependentFile) {
842   // Ensure the file exists before anything else. In some cases, if the path
843   // points to a removable device, Driver::enqueuePath() would fail with an
844   // error (EAGAIN, "resource unavailable try again") which we want to skip
845   // silently.
846   if (llvm::sys::fs::exists(pdbPath))
847     return normalizePdbPath(pdbPath);
848   std::string ret = getPdbBaseName(dependentFile, pdbPath);
849   if (llvm::sys::fs::exists(ret))
850     return normalizePdbPath(ret);
851   return None;
852 }
853 
854 PDBInputFile::PDBInputFile(COFFLinkerContext &ctx, MemoryBufferRef m)
855     : InputFile(ctx, PDBKind, m) {}
856 
857 PDBInputFile::~PDBInputFile() = default;
858 
859 PDBInputFile *PDBInputFile::findFromRecordPath(const COFFLinkerContext &ctx,
860                                                StringRef path,
861                                                ObjFile *fromFile) {
862   auto p = findPdbPath(path.str(), fromFile);
863   if (!p)
864     return nullptr;
865   auto it = ctx.pdbInputFileInstances.find(*p);
866   if (it != ctx.pdbInputFileInstances.end())
867     return it->second;
868   return nullptr;
869 }
870 
871 void PDBInputFile::parse() {
872   ctx.pdbInputFileInstances[mb.getBufferIdentifier().str()] = this;
873 
874   std::unique_ptr<pdb::IPDBSession> thisSession;
875   loadErr.emplace(pdb::NativeSession::createFromPdb(
876       MemoryBuffer::getMemBuffer(mb, false), thisSession));
877   if (*loadErr)
878     return; // fail silently at this point - the error will be handled later,
879             // when merging the debug type stream
880 
881   session.reset(static_cast<pdb::NativeSession *>(thisSession.release()));
882 
883   pdb::PDBFile &pdbFile = session->getPDBFile();
884   auto expectedInfo = pdbFile.getPDBInfoStream();
885   // All PDB Files should have an Info stream.
886   if (!expectedInfo) {
887     loadErr.emplace(expectedInfo.takeError());
888     return;
889   }
890   debugTypesObj = makeTypeServerSource(ctx, this);
891 }
892 
893 // Used only for DWARF debug info, which is not common (except in MinGW
894 // environments). This returns an optional pair of file name and line
895 // number for where the variable was defined.
896 Optional<std::pair<StringRef, uint32_t>>
897 ObjFile::getVariableLocation(StringRef var) {
898   if (!dwarf) {
899     dwarf = make<DWARFCache>(DWARFContext::create(*getCOFFObj()));
900     if (!dwarf)
901       return None;
902   }
903   if (config->machine == I386)
904     var.consume_front("_");
905   Optional<std::pair<std::string, unsigned>> ret = dwarf->getVariableLoc(var);
906   if (!ret)
907     return None;
908   return std::make_pair(saver.save(ret->first), ret->second);
909 }
910 
911 // Used only for DWARF debug info, which is not common (except in MinGW
912 // environments).
913 Optional<DILineInfo> ObjFile::getDILineInfo(uint32_t offset,
914                                             uint32_t sectionIndex) {
915   if (!dwarf) {
916     dwarf = make<DWARFCache>(DWARFContext::create(*getCOFFObj()));
917     if (!dwarf)
918       return None;
919   }
920 
921   return dwarf->getDILineInfo(offset, sectionIndex);
922 }
923 
924 void ObjFile::enqueuePdbFile(StringRef path, ObjFile *fromFile) {
925   auto p = findPdbPath(path.str(), fromFile);
926   if (!p)
927     return;
928   auto it = ctx.pdbInputFileInstances.emplace(*p, nullptr);
929   if (!it.second)
930     return; // already scheduled for load
931   driver->enqueuePDB(*p);
932 }
933 
934 void ImportFile::parse() {
935   const char *buf = mb.getBufferStart();
936   const auto *hdr = reinterpret_cast<const coff_import_header *>(buf);
937 
938   // Check if the total size is valid.
939   if (mb.getBufferSize() != sizeof(*hdr) + hdr->SizeOfData)
940     fatal("broken import library");
941 
942   // Read names and create an __imp_ symbol.
943   StringRef name = saver.save(StringRef(buf + sizeof(*hdr)));
944   StringRef impName = saver.save("__imp_" + name);
945   const char *nameStart = buf + sizeof(coff_import_header) + name.size() + 1;
946   dllName = std::string(StringRef(nameStart));
947   StringRef extName;
948   switch (hdr->getNameType()) {
949   case IMPORT_ORDINAL:
950     extName = "";
951     break;
952   case IMPORT_NAME:
953     extName = name;
954     break;
955   case IMPORT_NAME_NOPREFIX:
956     extName = ltrim1(name, "?@_");
957     break;
958   case IMPORT_NAME_UNDECORATE:
959     extName = ltrim1(name, "?@_");
960     extName = extName.substr(0, extName.find('@'));
961     break;
962   }
963 
964   this->hdr = hdr;
965   externalName = extName;
966 
967   impSym = ctx.symtab.addImportData(impName, this);
968   // If this was a duplicate, we logged an error but may continue;
969   // in this case, impSym is nullptr.
970   if (!impSym)
971     return;
972 
973   if (hdr->getType() == llvm::COFF::IMPORT_CONST)
974     static_cast<void>(ctx.symtab.addImportData(name, this));
975 
976   // If type is function, we need to create a thunk which jump to an
977   // address pointed by the __imp_ symbol. (This allows you to call
978   // DLL functions just like regular non-DLL functions.)
979   if (hdr->getType() == llvm::COFF::IMPORT_CODE)
980     thunkSym = ctx.symtab.addImportThunk(
981         name, cast_or_null<DefinedImportData>(impSym), hdr->Machine);
982 }
983 
984 BitcodeFile::BitcodeFile(COFFLinkerContext &ctx, MemoryBufferRef mb,
985                          StringRef archiveName, uint64_t offsetInArchive,
986                          bool lazy)
987     : InputFile(ctx, BitcodeKind, mb, lazy) {
988   std::string path = mb.getBufferIdentifier().str();
989   if (config->thinLTOIndexOnly)
990     path = replaceThinLTOSuffix(mb.getBufferIdentifier());
991 
992   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
993   // name. If two archives define two members with the same name, this
994   // causes a collision which result in only one of the objects being taken
995   // into consideration at LTO time (which very likely causes undefined
996   // symbols later in the link stage). So we append file offset to make
997   // filename unique.
998   MemoryBufferRef mbref(
999       mb.getBuffer(),
1000       saver.save(archiveName.empty() ? path
1001                                      : archiveName + sys::path::filename(path) +
1002                                            utostr(offsetInArchive)));
1003 
1004   obj = check(lto::InputFile::create(mbref));
1005 }
1006 
1007 BitcodeFile::~BitcodeFile() = default;
1008 
1009 namespace {
1010 // Convenience class for initializing a coff_section with specific flags.
1011 class FakeSection {
1012 public:
1013   FakeSection(int c) { section.Characteristics = c; }
1014 
1015   coff_section section;
1016 };
1017 
1018 // Convenience class for initializing a SectionChunk with specific flags.
1019 class FakeSectionChunk {
1020 public:
1021   FakeSectionChunk(const coff_section *section) : chunk(nullptr, section) {
1022     // Comdats from LTO files can't be fully treated as regular comdats
1023     // at this point; we don't know what size or contents they are going to
1024     // have, so we can't do proper checking of such aspects of them.
1025     chunk.selection = IMAGE_COMDAT_SELECT_ANY;
1026   }
1027 
1028   SectionChunk chunk;
1029 };
1030 
1031 FakeSection ltoTextSection(IMAGE_SCN_MEM_EXECUTE);
1032 FakeSection ltoDataSection(IMAGE_SCN_CNT_INITIALIZED_DATA);
1033 FakeSectionChunk ltoTextSectionChunk(&ltoTextSection.section);
1034 FakeSectionChunk ltoDataSectionChunk(&ltoDataSection.section);
1035 } // namespace
1036 
1037 void BitcodeFile::parse() {
1038   std::vector<std::pair<Symbol *, bool>> comdat(obj->getComdatTable().size());
1039   for (size_t i = 0; i != obj->getComdatTable().size(); ++i)
1040     // FIXME: Check nodeduplicate
1041     comdat[i] =
1042         ctx.symtab.addComdat(this, saver.save(obj->getComdatTable()[i].first));
1043   for (const lto::InputFile::Symbol &objSym : obj->symbols()) {
1044     StringRef symName = saver.save(objSym.getName());
1045     int comdatIndex = objSym.getComdatIndex();
1046     Symbol *sym;
1047     SectionChunk *fakeSC = nullptr;
1048     if (objSym.isExecutable())
1049       fakeSC = &ltoTextSectionChunk.chunk;
1050     else
1051       fakeSC = &ltoDataSectionChunk.chunk;
1052     if (objSym.isUndefined()) {
1053       sym = ctx.symtab.addUndefined(symName, this, false);
1054     } else if (objSym.isCommon()) {
1055       sym = ctx.symtab.addCommon(this, symName, objSym.getCommonSize());
1056     } else if (objSym.isWeak() && objSym.isIndirect()) {
1057       // Weak external.
1058       sym = ctx.symtab.addUndefined(symName, this, true);
1059       std::string fallback = std::string(objSym.getCOFFWeakExternalFallback());
1060       Symbol *alias = ctx.symtab.addUndefined(saver.save(fallback));
1061       checkAndSetWeakAlias(&ctx.symtab, this, sym, alias);
1062     } else if (comdatIndex != -1) {
1063       if (symName == obj->getComdatTable()[comdatIndex].first) {
1064         sym = comdat[comdatIndex].first;
1065         if (cast<DefinedRegular>(sym)->data == nullptr)
1066           cast<DefinedRegular>(sym)->data = &fakeSC->repl;
1067       } else if (comdat[comdatIndex].second) {
1068         sym = ctx.symtab.addRegular(this, symName, nullptr, fakeSC);
1069       } else {
1070         sym = ctx.symtab.addUndefined(symName, this, false);
1071       }
1072     } else {
1073       sym = ctx.symtab.addRegular(this, symName, nullptr, fakeSC);
1074     }
1075     symbols.push_back(sym);
1076     if (objSym.isUsed())
1077       config->gcroot.push_back(sym);
1078   }
1079   directives = obj->getCOFFLinkerOpts();
1080 }
1081 
1082 void BitcodeFile::parseLazy() {
1083   for (const lto::InputFile::Symbol &sym : obj->symbols())
1084     if (!sym.isUndefined())
1085       ctx.symtab.addLazyObject(this, sym.getName());
1086 }
1087 
1088 MachineTypes BitcodeFile::getMachineType() {
1089   switch (Triple(obj->getTargetTriple()).getArch()) {
1090   case Triple::x86_64:
1091     return AMD64;
1092   case Triple::x86:
1093     return I386;
1094   case Triple::arm:
1095     return ARMNT;
1096   case Triple::aarch64:
1097     return ARM64;
1098   default:
1099     return IMAGE_FILE_MACHINE_UNKNOWN;
1100   }
1101 }
1102 
1103 std::string lld::coff::replaceThinLTOSuffix(StringRef path) {
1104   StringRef suffix = config->thinLTOObjectSuffixReplace.first;
1105   StringRef repl = config->thinLTOObjectSuffixReplace.second;
1106 
1107   if (path.consume_back(suffix))
1108     return (path + repl).str();
1109   return std::string(path);
1110 }
1111 
1112 static bool isRVACode(COFFObjectFile *coffObj, uint64_t rva, InputFile *file) {
1113   for (size_t i = 1, e = coffObj->getNumberOfSections(); i <= e; i++) {
1114     const coff_section *sec = CHECK(coffObj->getSection(i), file);
1115     if (rva >= sec->VirtualAddress &&
1116         rva <= sec->VirtualAddress + sec->VirtualSize) {
1117       return (sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE) != 0;
1118     }
1119   }
1120   return false;
1121 }
1122 
1123 void DLLFile::parse() {
1124   // Parse a memory buffer as a PE-COFF executable.
1125   std::unique_ptr<Binary> bin = CHECK(createBinary(mb), this);
1126 
1127   if (auto *obj = dyn_cast<COFFObjectFile>(bin.get())) {
1128     bin.release();
1129     coffObj.reset(obj);
1130   } else {
1131     error(toString(this) + " is not a COFF file");
1132     return;
1133   }
1134 
1135   if (!coffObj->getPE32Header() && !coffObj->getPE32PlusHeader()) {
1136     error(toString(this) + " is not a PE-COFF executable");
1137     return;
1138   }
1139 
1140   for (const auto &exp : coffObj->export_directories()) {
1141     StringRef dllName, symbolName;
1142     uint32_t exportRVA;
1143     checkError(exp.getDllName(dllName));
1144     checkError(exp.getSymbolName(symbolName));
1145     checkError(exp.getExportRVA(exportRVA));
1146 
1147     if (symbolName.empty())
1148       continue;
1149 
1150     bool code = isRVACode(coffObj.get(), exportRVA, this);
1151 
1152     Symbol *s = make<Symbol>();
1153     s->dllName = dllName;
1154     s->symbolName = symbolName;
1155     s->importType = code ? ImportType::IMPORT_CODE : ImportType::IMPORT_DATA;
1156     s->nameType = ImportNameType::IMPORT_NAME;
1157 
1158     if (coffObj->getMachine() == I386) {
1159       s->symbolName = symbolName = saver.save("_" + symbolName);
1160       s->nameType = ImportNameType::IMPORT_NAME_NOPREFIX;
1161     }
1162 
1163     StringRef impName = saver.save("__imp_" + symbolName);
1164     ctx.symtab.addLazyDLLSymbol(this, s, impName);
1165     if (code)
1166       ctx.symtab.addLazyDLLSymbol(this, s, symbolName);
1167   }
1168 }
1169 
1170 MachineTypes DLLFile::getMachineType() {
1171   if (coffObj)
1172     return static_cast<MachineTypes>(coffObj->getMachine());
1173   return IMAGE_FILE_MACHINE_UNKNOWN;
1174 }
1175 
1176 void DLLFile::makeImport(DLLFile::Symbol *s) {
1177   if (!seen.insert(s->symbolName).second)
1178     return;
1179 
1180   size_t impSize = s->dllName.size() + s->symbolName.size() + 2; // +2 for NULs
1181   size_t size = sizeof(coff_import_header) + impSize;
1182   char *buf = bAlloc.Allocate<char>(size);
1183   memset(buf, 0, size);
1184   char *p = buf;
1185   auto *imp = reinterpret_cast<coff_import_header *>(p);
1186   p += sizeof(*imp);
1187   imp->Sig2 = 0xFFFF;
1188   imp->Machine = coffObj->getMachine();
1189   imp->SizeOfData = impSize;
1190   imp->OrdinalHint = 0; // Only linking by name
1191   imp->TypeInfo = (s->nameType << 2) | s->importType;
1192 
1193   // Write symbol name and DLL name.
1194   memcpy(p, s->symbolName.data(), s->symbolName.size());
1195   p += s->symbolName.size() + 1;
1196   memcpy(p, s->dllName.data(), s->dllName.size());
1197   MemoryBufferRef mbref = MemoryBufferRef(StringRef(buf, size), s->dllName);
1198   ImportFile *impFile = make<ImportFile>(ctx, mbref);
1199   ctx.symtab.addFile(impFile);
1200 }
1201