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