1292934Sdim//===- InputFiles.cpp -----------------------------------------------------===//
2292934Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6292934Sdim//
7292934Sdim//===----------------------------------------------------------------------===//
8292934Sdim
9314564Sdim#include "InputFiles.h"
10292934Sdim#include "Chunks.h"
11303239Sdim#include "Config.h"
12353358Sdim#include "DebugTypes.h"
13314564Sdim#include "Driver.h"
14314564Sdim#include "SymbolTable.h"
15292934Sdim#include "Symbols.h"
16360784Sdim#include "lld/Common/DWARF.h"
17327952Sdim#include "lld/Common/ErrorHandler.h"
18327952Sdim#include "lld/Common/Memory.h"
19314564Sdim#include "llvm-c/lto.h"
20303239Sdim#include "llvm/ADT/SmallVector.h"
21303239Sdim#include "llvm/ADT/Triple.h"
22303239Sdim#include "llvm/ADT/Twine.h"
23321369Sdim#include "llvm/BinaryFormat/COFF.h"
24353358Sdim#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
25353358Sdim#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
26353358Sdim#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
27353358Sdim#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
28360784Sdim#include "llvm/LTO/LTO.h"
29303239Sdim#include "llvm/Object/Binary.h"
30292934Sdim#include "llvm/Object/COFF.h"
31303239Sdim#include "llvm/Support/Casting.h"
32292934Sdim#include "llvm/Support/Endian.h"
33303239Sdim#include "llvm/Support/Error.h"
34303239Sdim#include "llvm/Support/ErrorOr.h"
35303239Sdim#include "llvm/Support/FileSystem.h"
36341825Sdim#include "llvm/Support/Path.h"
37303239Sdim#include "llvm/Target/TargetOptions.h"
38303239Sdim#include <cstring>
39303239Sdim#include <system_error>
40303239Sdim#include <utility>
41292934Sdim
42314564Sdimusing namespace llvm;
43292934Sdimusing namespace llvm::COFF;
44353358Sdimusing namespace llvm::codeview;
45292934Sdimusing namespace llvm::object;
46292934Sdimusing namespace llvm::support::endian;
47303239Sdim
48292934Sdimusing llvm::Triple;
49292934Sdimusing llvm::support::ulittle32_t;
50292934Sdim
51292934Sdimnamespace lld {
52360784Sdim
53360784Sdim// Returns the last element of a path, which is supposed to be a filename.
54360784Sdimstatic StringRef getBasename(StringRef path) {
55360784Sdim  return sys::path::filename(path, sys::path::Style::windows);
56360784Sdim}
57360784Sdim
58360784Sdim// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
59360784Sdimstd::string toString(const coff::InputFile *file) {
60360784Sdim  if (!file)
61360784Sdim    return "<internal>";
62360784Sdim  if (file->parentName.empty() || file->kind() == coff::InputFile::ImportKind)
63360784Sdim    return file->getName();
64360784Sdim
65360784Sdim  return (getBasename(file->parentName) + "(" + getBasename(file->getName()) +
66360784Sdim          ")")
67360784Sdim      .str();
68360784Sdim}
69360784Sdim
70292934Sdimnamespace coff {
71292934Sdim
72353358Sdimstd::vector<ObjFile *> ObjFile::instances;
73353358Sdimstd::vector<ImportFile *> ImportFile::instances;
74353358Sdimstd::vector<BitcodeFile *> BitcodeFile::instances;
75327952Sdim
76321369Sdim/// Checks that Source is compatible with being a weak alias to Target.
77321369Sdim/// If Source is Undefined and has no weak alias set, makes it a weak
78321369Sdim/// alias to Target.
79353358Sdimstatic void checkAndSetWeakAlias(SymbolTable *symtab, InputFile *f,
80353358Sdim                                 Symbol *source, Symbol *target) {
81353358Sdim  if (auto *u = dyn_cast<Undefined>(source)) {
82353358Sdim    if (u->weakAlias && u->weakAlias != target) {
83344779Sdim      // Weak aliases as produced by GCC are named in the form
84344779Sdim      // .weak.<weaksymbol>.<othersymbol>, where <othersymbol> is the name
85344779Sdim      // of another symbol emitted near the weak symbol.
86344779Sdim      // Just use the definition from the first object file that defined
87344779Sdim      // this weak symbol.
88353358Sdim      if (config->mingw)
89344779Sdim        return;
90353358Sdim      symtab->reportDuplicate(source, f);
91344779Sdim    }
92353358Sdim    u->weakAlias = target;
93321369Sdim  }
94321369Sdim}
95292934Sdim
96360784Sdimstatic bool ignoredSymbolName(StringRef name) {
97360784Sdim  return name == "@feat.00" || name == "@comp.id";
98360784Sdim}
99360784Sdim
100353358SdimArchiveFile::ArchiveFile(MemoryBufferRef m) : InputFile(ArchiveKind, m) {}
101292934Sdim
102292934Sdimvoid ArchiveFile::parse() {
103292934Sdim  // Parse a MemoryBufferRef as an archive file.
104353358Sdim  file = CHECK(Archive::create(mb), this);
105292934Sdim
106292934Sdim  // Read the symbol table to construct Lazy objects.
107353358Sdim  for (const Archive::Symbol &sym : file->symbols())
108360784Sdim    symtab->addLazyArchive(this, sym);
109292934Sdim}
110292934Sdim
111292934Sdim// Returns a buffer pointing to a member file containing a given symbol.
112353358Sdimvoid ArchiveFile::addMember(const Archive::Symbol &sym) {
113353358Sdim  const Archive::Child &c =
114353358Sdim      CHECK(sym.getMember(),
115353358Sdim            "could not get the member for symbol " + toCOFFString(sym));
116292934Sdim
117292934Sdim  // Return an empty buffer if we have already returned the same buffer.
118353358Sdim  if (!seen.insert(c.getChildOffset()).second)
119314564Sdim    return;
120314564Sdim
121353358Sdim  driver->enqueueArchiveMember(c, sym, getName());
122292934Sdim}
123292934Sdim
124353358Sdimstd::vector<MemoryBufferRef> getArchiveMembers(Archive *file) {
125353358Sdim  std::vector<MemoryBufferRef> v;
126353358Sdim  Error err = Error::success();
127360784Sdim  for (const Archive::Child &c : file->children(err)) {
128353358Sdim    MemoryBufferRef mbref =
129353358Sdim        CHECK(c.getMemoryBufferRef(),
130353358Sdim              file->getFileName() +
131327952Sdim                  ": could not get the buffer for a child of the archive");
132353358Sdim    v.push_back(mbref);
133327952Sdim  }
134353358Sdim  if (err)
135353358Sdim    fatal(file->getFileName() +
136353358Sdim          ": Archive::children failed: " + toString(std::move(err)));
137353358Sdim  return v;
138327952Sdim}
139327952Sdim
140360784Sdimvoid LazyObjFile::fetch() {
141360784Sdim  if (mb.getBuffer().empty())
142360784Sdim    return;
143360784Sdim
144360784Sdim  InputFile *file;
145360784Sdim  if (isBitcode(mb))
146360784Sdim    file = make<BitcodeFile>(mb, "", 0, std::move(symbols));
147360784Sdim  else
148360784Sdim    file = make<ObjFile>(mb, std::move(symbols));
149360784Sdim  mb = {};
150360784Sdim  symtab->addFile(file);
151360784Sdim}
152360784Sdim
153360784Sdimvoid LazyObjFile::parse() {
154360784Sdim  if (isBitcode(this->mb)) {
155360784Sdim    // Bitcode file.
156360784Sdim    std::unique_ptr<lto::InputFile> obj =
157360784Sdim        CHECK(lto::InputFile::create(this->mb), this);
158360784Sdim    for (const lto::InputFile::Symbol &sym : obj->symbols()) {
159360784Sdim      if (!sym.isUndefined())
160360784Sdim        symtab->addLazyObject(this, sym.getName());
161360784Sdim    }
162360784Sdim    return;
163360784Sdim  }
164360784Sdim
165360784Sdim  // Native object file.
166360784Sdim  std::unique_ptr<Binary> coffObjPtr = CHECK(createBinary(mb), this);
167360784Sdim  COFFObjectFile *coffObj = cast<COFFObjectFile>(coffObjPtr.get());
168360784Sdim  uint32_t numSymbols = coffObj->getNumberOfSymbols();
169360784Sdim  for (uint32_t i = 0; i < numSymbols; ++i) {
170360784Sdim    COFFSymbolRef coffSym = check(coffObj->getSymbol(i));
171360784Sdim    if (coffSym.isUndefined() || !coffSym.isExternal() ||
172360784Sdim        coffSym.isWeakExternal())
173360784Sdim      continue;
174360784Sdim    StringRef name;
175360784Sdim    coffObj->getSymbolName(coffSym, name);
176360784Sdim    if (coffSym.isAbsolute() && ignoredSymbolName(name))
177360784Sdim      continue;
178360784Sdim    symtab->addLazyObject(this, name);
179360784Sdim    i += coffSym.getNumberOfAuxSymbols();
180360784Sdim  }
181360784Sdim}
182360784Sdim
183327952Sdimvoid ObjFile::parse() {
184292934Sdim  // Parse a memory buffer as a COFF file.
185353358Sdim  std::unique_ptr<Binary> bin = CHECK(createBinary(mb), this);
186292934Sdim
187353358Sdim  if (auto *obj = dyn_cast<COFFObjectFile>(bin.get())) {
188353358Sdim    bin.release();
189353358Sdim    coffObj.reset(obj);
190292934Sdim  } else {
191314564Sdim    fatal(toString(this) + " is not a COFF file");
192292934Sdim  }
193292934Sdim
194292934Sdim  // Read section and symbol tables.
195292934Sdim  initializeChunks();
196292934Sdim  initializeSymbols();
197353358Sdim  initializeFlags();
198353358Sdim  initializeDependencies();
199292934Sdim}
200292934Sdim
201353358Sdimconst coff_section* ObjFile::getSection(uint32_t i) {
202353358Sdim  const coff_section *sec;
203353358Sdim  if (auto ec = coffObj->getSection(i, sec))
204353358Sdim    fatal("getSection failed: #" + Twine(i) + ": " + ec.message());
205353358Sdim  return sec;
206353358Sdim}
207353358Sdim
208327952Sdim// We set SectionChunk pointers in the SparseChunks vector to this value
209327952Sdim// temporarily to mark comdat sections as having an unknown resolution. As we
210327952Sdim// walk the object file's symbol table, once we visit either a leader symbol or
211327952Sdim// an associative section definition together with the parent comdat's leader,
212327952Sdim// we set the pointer to either nullptr (to mark the section as discarded) or a
213327952Sdim// valid SectionChunk for that section.
214353358Sdimstatic SectionChunk *const pendingComdat = reinterpret_cast<SectionChunk *>(1);
215327952Sdim
216327952Sdimvoid ObjFile::initializeChunks() {
217353358Sdim  uint32_t numSections = coffObj->getNumberOfSections();
218353358Sdim  chunks.reserve(numSections);
219353358Sdim  sparseChunks.resize(numSections + 1);
220353358Sdim  for (uint32_t i = 1; i < numSections + 1; ++i) {
221353358Sdim    const coff_section *sec = getSection(i);
222353358Sdim    if (sec->Characteristics & IMAGE_SCN_LNK_COMDAT)
223353358Sdim      sparseChunks[i] = pendingComdat;
224327952Sdim    else
225353358Sdim      sparseChunks[i] = readSection(i, nullptr, "");
226327952Sdim  }
227327952Sdim}
228314564Sdim
229353358SdimSectionChunk *ObjFile::readSection(uint32_t sectionNumber,
230353358Sdim                                   const coff_aux_section_definition *def,
231353358Sdim                                   StringRef leaderName) {
232353358Sdim  const coff_section *sec = getSection(sectionNumber);
233344779Sdim
234353358Sdim  StringRef name;
235353358Sdim  if (Expected<StringRef> e = coffObj->getSectionName(sec))
236353358Sdim    name = *e;
237353358Sdim  else
238353358Sdim    fatal("getSectionName failed: #" + Twine(sectionNumber) + ": " +
239353358Sdim          toString(e.takeError()));
240341825Sdim
241353358Sdim  if (name == ".drectve") {
242353358Sdim    ArrayRef<uint8_t> data;
243353358Sdim    cantFail(coffObj->getSectionContents(sec, data));
244353358Sdim    directives = StringRef((const char *)data.data(), data.size());
245327952Sdim    return nullptr;
246327952Sdim  }
247314564Sdim
248353358Sdim  if (name == ".llvm_addrsig") {
249353358Sdim    addrsigSec = sec;
250344779Sdim    return nullptr;
251344779Sdim  }
252344779Sdim
253327952Sdim  // Object files may have DWARF debug info or MS CodeView debug info
254327952Sdim  // (or both).
255327952Sdim  //
256327952Sdim  // DWARF sections don't need any special handling from the perspective
257327952Sdim  // of the linker; they are just a data section containing relocations.
258327952Sdim  // We can just link them to complete debug info.
259327952Sdim  //
260344779Sdim  // CodeView needs linker support. We need to interpret debug info,
261344779Sdim  // and then write it to a separate .pdb file.
262314564Sdim
263341825Sdim  // Ignore DWARF debug info unless /debug is given.
264353358Sdim  if (!config->debug && name.startswith(".debug_"))
265327952Sdim    return nullptr;
266321369Sdim
267353358Sdim  if (sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
268327952Sdim    return nullptr;
269353358Sdim  auto *c = make<SectionChunk>(this, sec);
270353358Sdim  if (def)
271353358Sdim    c->checksum = def->CheckSum;
272327952Sdim
273327952Sdim  // CodeView sections are stored to a different vector because they are not
274327952Sdim  // linked in the regular manner.
275353358Sdim  if (c->isCodeView())
276353358Sdim    debugChunks.push_back(c);
277353358Sdim  else if (name == ".gfids$y")
278353358Sdim    guardFidChunks.push_back(c);
279353358Sdim  else if (name == ".gljmp$y")
280353358Sdim    guardLJmpChunks.push_back(c);
281353358Sdim  else if (name == ".sxdata")
282353358Sdim    sXDataChunks.push_back(c);
283353358Sdim  else if (config->tailMerge && sec->NumberOfRelocations == 0 &&
284353358Sdim           name == ".rdata" && leaderName.startswith("??_C@"))
285341825Sdim    // COFF sections that look like string literal sections (i.e. no
286341825Sdim    // relocations, in .rdata, leader symbol name matches the MSVC name mangling
287341825Sdim    // for string literals) are subject to string tail merging.
288353358Sdim    MergeChunk::addSection(c);
289360784Sdim  else if (name == ".rsrc" || name.startswith(".rsrc$"))
290360784Sdim    resourceChunks.push_back(c);
291327952Sdim  else
292353358Sdim    chunks.push_back(c);
293327952Sdim
294353358Sdim  return c;
295327952Sdim}
296327952Sdim
297360784Sdimvoid ObjFile::includeResourceChunks() {
298360784Sdim  chunks.insert(chunks.end(), resourceChunks.begin(), resourceChunks.end());
299360784Sdim}
300360784Sdim
301327952Sdimvoid ObjFile::readAssociativeDefinition(
302353358Sdim    COFFSymbolRef sym, const coff_aux_section_definition *def) {
303353358Sdim  readAssociativeDefinition(sym, def, def->getNumber(sym.isBigObj()));
304341825Sdim}
305327952Sdim
306353358Sdimvoid ObjFile::readAssociativeDefinition(COFFSymbolRef sym,
307353358Sdim                                        const coff_aux_section_definition *def,
308353358Sdim                                        uint32_t parentIndex) {
309353358Sdim  SectionChunk *parent = sparseChunks[parentIndex];
310353358Sdim  int32_t sectionNumber = sym.getSectionNumber();
311341825Sdim
312353358Sdim  auto diag = [&]() {
313353358Sdim    StringRef name, parentName;
314353358Sdim    coffObj->getSymbolName(sym, name);
315353358Sdim
316353358Sdim    const coff_section *parentSec = getSection(parentIndex);
317353358Sdim    if (Expected<StringRef> e = coffObj->getSectionName(parentSec))
318353358Sdim      parentName = *e;
319353358Sdim    error(toString(this) + ": associative comdat " + name + " (sec " +
320353358Sdim          Twine(sectionNumber) + ") has invalid reference to section " +
321353358Sdim          parentName + " (sec " + Twine(parentIndex) + ")");
322353358Sdim  };
323353358Sdim
324353358Sdim  if (parent == pendingComdat) {
325353358Sdim    // This can happen if an associative comdat refers to another associative
326353358Sdim    // comdat that appears after it (invalid per COFF spec) or to a section
327353358Sdim    // without any symbols.
328353358Sdim    diag();
329327952Sdim    return;
330353358Sdim  }
331327952Sdim
332327952Sdim  // Check whether the parent is prevailing. If it is, so are we, and we read
333327952Sdim  // the section; otherwise mark it as discarded.
334353358Sdim  if (parent) {
335353358Sdim    SectionChunk *c = readSection(sectionNumber, def, "");
336353358Sdim    sparseChunks[sectionNumber] = c;
337353358Sdim    if (c) {
338353358Sdim      c->selection = IMAGE_COMDAT_SELECT_ASSOCIATIVE;
339353358Sdim      parent->addAssociative(c);
340353358Sdim    }
341327952Sdim  } else {
342353358Sdim    sparseChunks[sectionNumber] = nullptr;
343292934Sdim  }
344292934Sdim}
345292934Sdim
346341825Sdimvoid ObjFile::recordPrevailingSymbolForMingw(
347353358Sdim    COFFSymbolRef sym, DenseMap<StringRef, uint32_t> &prevailingSectionMap) {
348341825Sdim  // For comdat symbols in executable sections, where this is the copy
349341825Sdim  // of the section chunk we actually include instead of discarding it,
350341825Sdim  // add the symbol to a map to allow using it for implicitly
351341825Sdim  // associating .[px]data$<func> sections to it.
352353358Sdim  int32_t sectionNumber = sym.getSectionNumber();
353353358Sdim  SectionChunk *sc = sparseChunks[sectionNumber];
354353358Sdim  if (sc && sc->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE) {
355353358Sdim    StringRef name;
356353358Sdim    coffObj->getSymbolName(sym, name);
357353358Sdim    if (getMachineType() == I386)
358353358Sdim      name.consume_front("_");
359353358Sdim    prevailingSectionMap[name] = sectionNumber;
360341825Sdim  }
361341825Sdim}
362341825Sdim
363341825Sdimvoid ObjFile::maybeAssociateSEHForMingw(
364353358Sdim    COFFSymbolRef sym, const coff_aux_section_definition *def,
365353358Sdim    const DenseMap<StringRef, uint32_t> &prevailingSectionMap) {
366353358Sdim  StringRef name;
367353358Sdim  coffObj->getSymbolName(sym, name);
368353358Sdim  if (name.consume_front(".pdata$") || name.consume_front(".xdata$") ||
369353358Sdim      name.consume_front(".eh_frame$")) {
370353358Sdim    // For MinGW, treat .[px]data$<func> and .eh_frame$<func> as implicitly
371353358Sdim    // associative to the symbol <func>.
372353358Sdim    auto parentSym = prevailingSectionMap.find(name);
373353358Sdim    if (parentSym != prevailingSectionMap.end())
374353358Sdim      readAssociativeDefinition(sym, def, parentSym->second);
375341825Sdim  }
376341825Sdim}
377341825Sdim
378353358SdimSymbol *ObjFile::createRegular(COFFSymbolRef sym) {
379353358Sdim  SectionChunk *sc = sparseChunks[sym.getSectionNumber()];
380353358Sdim  if (sym.isExternal()) {
381353358Sdim    StringRef name;
382353358Sdim    coffObj->getSymbolName(sym, name);
383353358Sdim    if (sc)
384360784Sdim      return symtab->addRegular(this, name, sym.getGeneric(), sc,
385360784Sdim                                sym.getValue());
386344779Sdim    // For MinGW symbols named .weak.* that point to a discarded section,
387344779Sdim    // don't create an Undefined symbol. If nothing ever refers to the symbol,
388344779Sdim    // everything should be fine. If something actually refers to the symbol
389344779Sdim    // (e.g. the undefined weak alias), linking will fail due to undefined
390344779Sdim    // references at the end.
391353358Sdim    if (config->mingw && name.startswith(".weak."))
392344779Sdim      return nullptr;
393353358Sdim    return symtab->addUndefined(name, this, false);
394327952Sdim  }
395353358Sdim  if (sc)
396344779Sdim    return make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
397353358Sdim                                /*IsExternal*/ false, sym.getGeneric(), sc);
398327952Sdim  return nullptr;
399327952Sdim}
400327952Sdim
401327952Sdimvoid ObjFile::initializeSymbols() {
402353358Sdim  uint32_t numSymbols = coffObj->getNumberOfSymbols();
403353358Sdim  symbols.resize(numSymbols);
404321369Sdim
405353358Sdim  SmallVector<std::pair<Symbol *, uint32_t>, 8> weakAliases;
406353358Sdim  std::vector<uint32_t> pendingIndexes;
407353358Sdim  pendingIndexes.reserve(numSymbols);
408321369Sdim
409353358Sdim  DenseMap<StringRef, uint32_t> prevailingSectionMap;
410353358Sdim  std::vector<const coff_aux_section_definition *> comdatDefs(
411353358Sdim      coffObj->getNumberOfSections() + 1);
412327952Sdim
413353358Sdim  for (uint32_t i = 0; i < numSymbols; ++i) {
414353358Sdim    COFFSymbolRef coffSym = check(coffObj->getSymbol(i));
415353358Sdim    bool prevailingComdat;
416353358Sdim    if (coffSym.isUndefined()) {
417353358Sdim      symbols[i] = createUndefined(coffSym);
418353358Sdim    } else if (coffSym.isWeakExternal()) {
419353358Sdim      symbols[i] = createUndefined(coffSym);
420353358Sdim      uint32_t tagIndex = coffSym.getAux<coff_aux_weak_external>()->TagIndex;
421353358Sdim      weakAliases.emplace_back(symbols[i], tagIndex);
422353358Sdim    } else if (Optional<Symbol *> optSym =
423353358Sdim                   createDefined(coffSym, comdatDefs, prevailingComdat)) {
424353358Sdim      symbols[i] = *optSym;
425353358Sdim      if (config->mingw && prevailingComdat)
426353358Sdim        recordPrevailingSymbolForMingw(coffSym, prevailingSectionMap);
427292934Sdim    } else {
428327952Sdim      // createDefined() returns None if a symbol belongs to a section that
429327952Sdim      // was pending at the point when the symbol was read. This can happen in
430327952Sdim      // two cases:
431327952Sdim      // 1) section definition symbol for a comdat leader;
432353358Sdim      // 2) symbol belongs to a comdat section associated with another section.
433327952Sdim      // In both of these cases, we can expect the section to be resolved by
434327952Sdim      // the time we finish visiting the remaining symbols in the symbol
435327952Sdim      // table. So we postpone the handling of this symbol until that time.
436353358Sdim      pendingIndexes.push_back(i);
437292934Sdim    }
438353358Sdim    i += coffSym.getNumberOfAuxSymbols();
439292934Sdim  }
440321369Sdim
441353358Sdim  for (uint32_t i : pendingIndexes) {
442353358Sdim    COFFSymbolRef sym = check(coffObj->getSymbol(i));
443353358Sdim    if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {
444353358Sdim      if (def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
445353358Sdim        readAssociativeDefinition(sym, def);
446353358Sdim      else if (config->mingw)
447353358Sdim        maybeAssociateSEHForMingw(sym, def, prevailingSectionMap);
448341825Sdim    }
449353358Sdim    if (sparseChunks[sym.getSectionNumber()] == pendingComdat) {
450353358Sdim      StringRef name;
451353358Sdim      coffObj->getSymbolName(sym, name);
452353358Sdim      log("comdat section " + name +
453341825Sdim          " without leader and unassociated, discarding");
454341825Sdim      continue;
455341825Sdim    }
456353358Sdim    symbols[i] = createRegular(sym);
457327952Sdim  }
458327952Sdim
459353358Sdim  for (auto &kv : weakAliases) {
460353358Sdim    Symbol *sym = kv.first;
461353358Sdim    uint32_t idx = kv.second;
462353358Sdim    checkAndSetWeakAlias(symtab, this, sym, symbols[idx]);
463314564Sdim  }
464292934Sdim}
465292934Sdim
466353358SdimSymbol *ObjFile::createUndefined(COFFSymbolRef sym) {
467353358Sdim  StringRef name;
468353358Sdim  coffObj->getSymbolName(sym, name);
469353358Sdim  return symtab->addUndefined(name, this, sym.isWeakExternal());
470292934Sdim}
471292934Sdim
472353358Sdimvoid ObjFile::handleComdatSelection(COFFSymbolRef sym, COMDATType &selection,
473353358Sdim                                    bool &prevailing, DefinedRegular *leader) {
474353358Sdim  if (prevailing)
475353358Sdim    return;
476353358Sdim  // There's already an existing comdat for this symbol: `Leader`.
477353358Sdim  // Use the comdats's selection field to determine if the new
478353358Sdim  // symbol in `Sym` should be discarded, produce a duplicate symbol
479353358Sdim  // error, etc.
480353358Sdim
481353358Sdim  SectionChunk *leaderChunk = nullptr;
482353358Sdim  COMDATType leaderSelection = IMAGE_COMDAT_SELECT_ANY;
483353358Sdim
484353358Sdim  if (leader->data) {
485353358Sdim    leaderChunk = leader->getChunk();
486353358Sdim    leaderSelection = leaderChunk->selection;
487353358Sdim  } else {
488353358Sdim    // FIXME: comdats from LTO files don't know their selection; treat them
489353358Sdim    // as "any".
490353358Sdim    selection = leaderSelection;
491353358Sdim  }
492353358Sdim
493353358Sdim  if ((selection == IMAGE_COMDAT_SELECT_ANY &&
494353358Sdim       leaderSelection == IMAGE_COMDAT_SELECT_LARGEST) ||
495353358Sdim      (selection == IMAGE_COMDAT_SELECT_LARGEST &&
496353358Sdim       leaderSelection == IMAGE_COMDAT_SELECT_ANY)) {
497353358Sdim    // cl.exe picks "any" for vftables when building with /GR- and
498353358Sdim    // "largest" when building with /GR. To be able to link object files
499353358Sdim    // compiled with each flag, "any" and "largest" are merged as "largest".
500353358Sdim    leaderSelection = selection = IMAGE_COMDAT_SELECT_LARGEST;
501353358Sdim  }
502353358Sdim
503360784Sdim  // GCCs __declspec(selectany) doesn't actually pick "any" but "same size as".
504360784Sdim  // Clang on the other hand picks "any". To be able to link two object files
505360784Sdim  // with a __declspec(selectany) declaration, one compiled with gcc and the
506360784Sdim  // other with clang, we merge them as proper "same size as"
507360784Sdim  if (config->mingw && ((selection == IMAGE_COMDAT_SELECT_ANY &&
508360784Sdim                         leaderSelection == IMAGE_COMDAT_SELECT_SAME_SIZE) ||
509360784Sdim                        (selection == IMAGE_COMDAT_SELECT_SAME_SIZE &&
510360784Sdim                         leaderSelection == IMAGE_COMDAT_SELECT_ANY))) {
511360784Sdim    leaderSelection = selection = IMAGE_COMDAT_SELECT_SAME_SIZE;
512360784Sdim  }
513360784Sdim
514353358Sdim  // Other than that, comdat selections must match.  This is a bit more
515353358Sdim  // strict than link.exe which allows merging "any" and "largest" if "any"
516353358Sdim  // is the first symbol the linker sees, and it allows merging "largest"
517353358Sdim  // with everything (!) if "largest" is the first symbol the linker sees.
518353358Sdim  // Making this symmetric independent of which selection is seen first
519353358Sdim  // seems better though.
520353358Sdim  // (This behavior matches ModuleLinker::getComdatResult().)
521353358Sdim  if (selection != leaderSelection) {
522353358Sdim    log(("conflicting comdat type for " + toString(*leader) + ": " +
523353358Sdim         Twine((int)leaderSelection) + " in " + toString(leader->getFile()) +
524353358Sdim         " and " + Twine((int)selection) + " in " + toString(this))
525353358Sdim            .str());
526353358Sdim    symtab->reportDuplicate(leader, this);
527353358Sdim    return;
528353358Sdim  }
529353358Sdim
530353358Sdim  switch (selection) {
531353358Sdim  case IMAGE_COMDAT_SELECT_NODUPLICATES:
532353358Sdim    symtab->reportDuplicate(leader, this);
533353358Sdim    break;
534353358Sdim
535353358Sdim  case IMAGE_COMDAT_SELECT_ANY:
536353358Sdim    // Nothing to do.
537353358Sdim    break;
538353358Sdim
539353358Sdim  case IMAGE_COMDAT_SELECT_SAME_SIZE:
540353358Sdim    if (leaderChunk->getSize() != getSection(sym)->SizeOfRawData)
541353358Sdim      symtab->reportDuplicate(leader, this);
542353358Sdim    break;
543353358Sdim
544353358Sdim  case IMAGE_COMDAT_SELECT_EXACT_MATCH: {
545353358Sdim    SectionChunk newChunk(this, getSection(sym));
546353358Sdim    // link.exe only compares section contents here and doesn't complain
547353358Sdim    // if the two comdat sections have e.g. different alignment.
548353358Sdim    // Match that.
549353358Sdim    if (leaderChunk->getContents() != newChunk.getContents())
550360784Sdim      symtab->reportDuplicate(leader, this, &newChunk, sym.getValue());
551353358Sdim    break;
552353358Sdim  }
553353358Sdim
554353358Sdim  case IMAGE_COMDAT_SELECT_ASSOCIATIVE:
555353358Sdim    // createDefined() is never called for IMAGE_COMDAT_SELECT_ASSOCIATIVE.
556353358Sdim    // (This means lld-link doesn't produce duplicate symbol errors for
557353358Sdim    // associative comdats while link.exe does, but associate comdats
558353358Sdim    // are never extern in practice.)
559353358Sdim    llvm_unreachable("createDefined not called for associative comdats");
560353358Sdim
561353358Sdim  case IMAGE_COMDAT_SELECT_LARGEST:
562353358Sdim    if (leaderChunk->getSize() < getSection(sym)->SizeOfRawData) {
563353358Sdim      // Replace the existing comdat symbol with the new one.
564353358Sdim      StringRef name;
565353358Sdim      coffObj->getSymbolName(sym, name);
566353358Sdim      // FIXME: This is incorrect: With /opt:noref, the previous sections
567353358Sdim      // make it into the final executable as well. Correct handling would
568353358Sdim      // be to undo reading of the whole old section that's being replaced,
569353358Sdim      // or doing one pass that determines what the final largest comdat
570353358Sdim      // is for all IMAGE_COMDAT_SELECT_LARGEST comdats and then reading
571353358Sdim      // only the largest one.
572353358Sdim      replaceSymbol<DefinedRegular>(leader, this, name, /*IsCOMDAT*/ true,
573353358Sdim                                    /*IsExternal*/ true, sym.getGeneric(),
574353358Sdim                                    nullptr);
575353358Sdim      prevailing = true;
576353358Sdim    }
577353358Sdim    break;
578353358Sdim
579353358Sdim  case IMAGE_COMDAT_SELECT_NEWEST:
580353358Sdim    llvm_unreachable("should have been rejected earlier");
581353358Sdim  }
582353358Sdim}
583353358Sdim
584327952SdimOptional<Symbol *> ObjFile::createDefined(
585353358Sdim    COFFSymbolRef sym,
586353358Sdim    std::vector<const coff_aux_section_definition *> &comdatDefs,
587353358Sdim    bool &prevailing) {
588353358Sdim  prevailing = false;
589353358Sdim  auto getName = [&]() {
590353358Sdim    StringRef s;
591353358Sdim    coffObj->getSymbolName(sym, s);
592353358Sdim    return s;
593341825Sdim  };
594341825Sdim
595353358Sdim  if (sym.isCommon()) {
596353358Sdim    auto *c = make<CommonChunk>(sym);
597353358Sdim    chunks.push_back(c);
598353358Sdim    return symtab->addCommon(this, getName(), sym.getValue(), sym.getGeneric(),
599353358Sdim                             c);
600292934Sdim  }
601341825Sdim
602353358Sdim  if (sym.isAbsolute()) {
603353358Sdim    StringRef name = getName();
604341825Sdim
605360784Sdim    if (name == "@feat.00")
606360784Sdim      feat00Flags = sym.getValue();
607292934Sdim    // Skip special symbols.
608360784Sdim    if (ignoredSymbolName(name))
609292934Sdim      return nullptr;
610341825Sdim
611353358Sdim    if (sym.isExternal())
612353358Sdim      return symtab->addAbsolute(name, sym);
613353358Sdim    return make<DefinedAbsolute>(name, sym);
614292934Sdim  }
615341825Sdim
616353358Sdim  int32_t sectionNumber = sym.getSectionNumber();
617353358Sdim  if (sectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
618292934Sdim    return nullptr;
619292934Sdim
620353358Sdim  if (llvm::COFF::isReservedSectionNumber(sectionNumber))
621353358Sdim    fatal(toString(this) + ": " + getName() +
622353358Sdim          " should not refer to special section " + Twine(sectionNumber));
623303239Sdim
624353358Sdim  if ((uint32_t)sectionNumber >= sparseChunks.size())
625353358Sdim    fatal(toString(this) + ": " + getName() +
626353358Sdim          " should not refer to non-existent section " + Twine(sectionNumber));
627303239Sdim
628353358Sdim  // Comdat handling.
629353358Sdim  // A comdat symbol consists of two symbol table entries.
630353358Sdim  // The first symbol entry has the name of the section (e.g. .text), fixed
631360784Sdim  // values for the other fields, and one auxiliary record.
632353358Sdim  // The second symbol entry has the name of the comdat symbol, called the
633353358Sdim  // "comdat leader".
634353358Sdim  // When this function is called for the first symbol entry of a comdat,
635353358Sdim  // it sets comdatDefs and returns None, and when it's called for the second
636353358Sdim  // symbol entry it reads comdatDefs and then sets it back to nullptr.
637353358Sdim
638353358Sdim  // Handle comdat leader.
639353358Sdim  if (const coff_aux_section_definition *def = comdatDefs[sectionNumber]) {
640353358Sdim    comdatDefs[sectionNumber] = nullptr;
641353358Sdim    DefinedRegular *leader;
642353358Sdim
643353358Sdim    if (sym.isExternal()) {
644353358Sdim      std::tie(leader, prevailing) =
645353358Sdim          symtab->addComdat(this, getName(), sym.getGeneric());
646327952Sdim    } else {
647353358Sdim      leader = make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
648353358Sdim                                    /*IsExternal*/ false, sym.getGeneric());
649353358Sdim      prevailing = true;
650327952Sdim    }
651341825Sdim
652353358Sdim    if (def->Selection < (int)IMAGE_COMDAT_SELECT_NODUPLICATES ||
653353358Sdim        // Intentionally ends at IMAGE_COMDAT_SELECT_LARGEST: link.exe
654353358Sdim        // doesn't understand IMAGE_COMDAT_SELECT_NEWEST either.
655353358Sdim        def->Selection > (int)IMAGE_COMDAT_SELECT_LARGEST) {
656353358Sdim      fatal("unknown comdat type " + std::to_string((int)def->Selection) +
657353358Sdim            " for " + getName() + " in " + toString(this));
658353358Sdim    }
659353358Sdim    COMDATType selection = (COMDATType)def->Selection;
660353358Sdim
661353358Sdim    if (leader->isCOMDAT)
662353358Sdim      handleComdatSelection(sym, selection, prevailing, leader);
663353358Sdim
664353358Sdim    if (prevailing) {
665353358Sdim      SectionChunk *c = readSection(sectionNumber, def, getName());
666353358Sdim      sparseChunks[sectionNumber] = c;
667353358Sdim      c->sym = cast<DefinedRegular>(leader);
668353358Sdim      c->selection = selection;
669353358Sdim      cast<DefinedRegular>(leader)->data = &c->repl;
670327952Sdim    } else {
671353358Sdim      sparseChunks[sectionNumber] = nullptr;
672327952Sdim    }
673353358Sdim    return leader;
674327952Sdim  }
675292934Sdim
676353358Sdim  // Prepare to handle the comdat leader symbol by setting the section's
677353358Sdim  // ComdatDefs pointer if we encounter a non-associative comdat.
678353358Sdim  if (sparseChunks[sectionNumber] == pendingComdat) {
679353358Sdim    if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {
680353358Sdim      if (def->Selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE)
681353358Sdim        comdatDefs[sectionNumber] = def;
682327952Sdim    }
683353358Sdim    return None;
684292934Sdim  }
685292934Sdim
686353358Sdim  return createRegular(sym);
687292934Sdim}
688292934Sdim
689327952SdimMachineTypes ObjFile::getMachineType() {
690353358Sdim  if (coffObj)
691353358Sdim    return static_cast<MachineTypes>(coffObj->getMachine());
692292934Sdim  return IMAGE_FILE_MACHINE_UNKNOWN;
693292934Sdim}
694292934Sdim
695353358SdimArrayRef<uint8_t> ObjFile::getDebugSection(StringRef secName) {
696353358Sdim  if (SectionChunk *sec = SectionChunk::findByName(debugChunks, secName))
697353358Sdim    return sec->consumeDebugMagic();
698353358Sdim  return {};
699292934Sdim}
700292934Sdim
701360784Sdim// OBJ files systematically store critical information in a .debug$S stream,
702353358Sdim// even if the TU was compiled with no debug info. At least two records are
703353358Sdim// always there. S_OBJNAME stores a 32-bit signature, which is loaded into the
704353358Sdim// PCHSignature member. S_COMPILE3 stores compile-time cmd-line flags. This is
705353358Sdim// currently used to initialize the hotPatchable member.
706353358Sdimvoid ObjFile::initializeFlags() {
707353358Sdim  ArrayRef<uint8_t> data = getDebugSection(".debug$S");
708353358Sdim  if (data.empty())
709353358Sdim    return;
710353358Sdim
711353358Sdim  DebugSubsectionArray subsections;
712353358Sdim
713353358Sdim  BinaryStreamReader reader(data, support::little);
714353358Sdim  ExitOnError exitOnErr;
715353358Sdim  exitOnErr(reader.readArray(subsections, data.size()));
716353358Sdim
717353358Sdim  for (const DebugSubsectionRecord &ss : subsections) {
718353358Sdim    if (ss.kind() != DebugSubsectionKind::Symbols)
719353358Sdim      continue;
720353358Sdim
721353358Sdim    unsigned offset = 0;
722353358Sdim
723353358Sdim    // Only parse the first two records. We are only looking for S_OBJNAME
724353358Sdim    // and S_COMPILE3, and they usually appear at the beginning of the
725353358Sdim    // stream.
726353358Sdim    for (unsigned i = 0; i < 2; ++i) {
727353358Sdim      Expected<CVSymbol> sym = readSymbolFromStream(ss.getRecordData(), offset);
728353358Sdim      if (!sym) {
729353358Sdim        consumeError(sym.takeError());
730353358Sdim        return;
731353358Sdim      }
732353358Sdim      if (sym->kind() == SymbolKind::S_COMPILE3) {
733353358Sdim        auto cs =
734353358Sdim            cantFail(SymbolDeserializer::deserializeAs<Compile3Sym>(sym.get()));
735353358Sdim        hotPatchable =
736353358Sdim            (cs.Flags & CompileSym3Flags::HotPatch) != CompileSym3Flags::None;
737353358Sdim      }
738353358Sdim      if (sym->kind() == SymbolKind::S_OBJNAME) {
739353358Sdim        auto objName = cantFail(SymbolDeserializer::deserializeAs<ObjNameSym>(
740353358Sdim            sym.get()));
741353358Sdim        pchSignature = objName.Signature;
742353358Sdim      }
743353358Sdim      offset += sym->length();
744353358Sdim    }
745353358Sdim  }
746353358Sdim}
747353358Sdim
748353358Sdim// Depending on the compilation flags, OBJs can refer to external files,
749353358Sdim// necessary to merge this OBJ into the final PDB. We currently support two
750353358Sdim// types of external files: Precomp/PCH OBJs, when compiling with /Yc and /Yu.
751353358Sdim// And PDB type servers, when compiling with /Zi. This function extracts these
752353358Sdim// dependencies and makes them available as a TpiSource interface (see
753353358Sdim// DebugTypes.h). Both cases only happen with cl.exe: clang-cl produces regular
754353358Sdim// output even with /Yc and /Yu and with /Zi.
755353358Sdimvoid ObjFile::initializeDependencies() {
756353358Sdim  if (!config->debug)
757353358Sdim    return;
758353358Sdim
759353358Sdim  bool isPCH = false;
760353358Sdim
761353358Sdim  ArrayRef<uint8_t> data = getDebugSection(".debug$P");
762353358Sdim  if (!data.empty())
763353358Sdim    isPCH = true;
764353358Sdim  else
765353358Sdim    data = getDebugSection(".debug$T");
766353358Sdim
767353358Sdim  if (data.empty())
768353358Sdim    return;
769353358Sdim
770353358Sdim  CVTypeArray types;
771353358Sdim  BinaryStreamReader reader(data, support::little);
772353358Sdim  cantFail(reader.readArray(types, reader.getLength()));
773353358Sdim
774353358Sdim  CVTypeArray::Iterator firstType = types.begin();
775353358Sdim  if (firstType == types.end())
776353358Sdim    return;
777353358Sdim
778360784Sdim  // Remember the .debug$T or .debug$P section.
779360784Sdim  debugTypes = data;
780353358Sdim
781353358Sdim  if (isPCH) {
782353358Sdim    debugTypesObj = makePrecompSource(this);
783353358Sdim    return;
784353358Sdim  }
785353358Sdim
786353358Sdim  if (firstType->kind() == LF_TYPESERVER2) {
787353358Sdim    TypeServer2Record ts = cantFail(
788353358Sdim        TypeDeserializer::deserializeAs<TypeServer2Record>(firstType->data()));
789353358Sdim    debugTypesObj = makeUseTypeServerSource(this, &ts);
790353358Sdim    return;
791353358Sdim  }
792353358Sdim
793353358Sdim  if (firstType->kind() == LF_PRECOMP) {
794353358Sdim    PrecompRecord precomp = cantFail(
795353358Sdim        TypeDeserializer::deserializeAs<PrecompRecord>(firstType->data()));
796353358Sdim    debugTypesObj = makeUsePrecompSource(this, &precomp);
797353358Sdim    return;
798353358Sdim  }
799353358Sdim
800353358Sdim  debugTypesObj = makeTpiSource(this);
801353358Sdim}
802353358Sdim
803360784Sdim// Used only for DWARF debug info, which is not common (except in MinGW
804360784Sdim// environments). This returns an optional pair of file name and line
805360784Sdim// number for where the variable was defined.
806360784SdimOptional<std::pair<StringRef, uint32_t>>
807360784SdimObjFile::getVariableLocation(StringRef var) {
808360784Sdim  if (!dwarf) {
809360784Sdim    dwarf = make<DWARFCache>(DWARFContext::create(*getCOFFObj()));
810360784Sdim    if (!dwarf)
811360784Sdim      return None;
812360784Sdim  }
813360784Sdim  if (config->machine == I386)
814360784Sdim    var.consume_front("_");
815360784Sdim  Optional<std::pair<std::string, unsigned>> ret = dwarf->getVariableLoc(var);
816360784Sdim  if (!ret)
817360784Sdim    return None;
818360784Sdim  return std::make_pair(saver.save(ret->first), ret->second);
819360784Sdim}
820360784Sdim
821360784Sdim// Used only for DWARF debug info, which is not common (except in MinGW
822360784Sdim// environments).
823360784SdimOptional<DILineInfo> ObjFile::getDILineInfo(uint32_t offset,
824360784Sdim                                            uint32_t sectionIndex) {
825360784Sdim  if (!dwarf) {
826360784Sdim    dwarf = make<DWARFCache>(DWARFContext::create(*getCOFFObj()));
827360784Sdim    if (!dwarf)
828360784Sdim      return None;
829360784Sdim  }
830360784Sdim
831360784Sdim  return dwarf->getDILineInfo(offset, sectionIndex);
832360784Sdim}
833360784Sdim
834353358SdimStringRef ltrim1(StringRef s, const char *chars) {
835353358Sdim  if (!s.empty() && strchr(chars, s[0]))
836353358Sdim    return s.substr(1);
837353358Sdim  return s;
838353358Sdim}
839353358Sdim
840292934Sdimvoid ImportFile::parse() {
841353358Sdim  const char *buf = mb.getBufferStart();
842353358Sdim  const auto *hdr = reinterpret_cast<const coff_import_header *>(buf);
843292934Sdim
844292934Sdim  // Check if the total size is valid.
845353358Sdim  if (mb.getBufferSize() != sizeof(*hdr) + hdr->SizeOfData)
846303239Sdim    fatal("broken import library");
847292934Sdim
848292934Sdim  // Read names and create an __imp_ symbol.
849353358Sdim  StringRef name = saver.save(StringRef(buf + sizeof(*hdr)));
850353358Sdim  StringRef impName = saver.save("__imp_" + name);
851353358Sdim  const char *nameStart = buf + sizeof(coff_import_header) + name.size() + 1;
852353358Sdim  dllName = StringRef(nameStart);
853353358Sdim  StringRef extName;
854353358Sdim  switch (hdr->getNameType()) {
855292934Sdim  case IMPORT_ORDINAL:
856353358Sdim    extName = "";
857292934Sdim    break;
858292934Sdim  case IMPORT_NAME:
859353358Sdim    extName = name;
860292934Sdim    break;
861292934Sdim  case IMPORT_NAME_NOPREFIX:
862353358Sdim    extName = ltrim1(name, "?@_");
863292934Sdim    break;
864292934Sdim  case IMPORT_NAME_UNDECORATE:
865353358Sdim    extName = ltrim1(name, "?@_");
866353358Sdim    extName = extName.substr(0, extName.find('@'));
867292934Sdim    break;
868292934Sdim  }
869292934Sdim
870353358Sdim  this->hdr = hdr;
871353358Sdim  externalName = extName;
872314564Sdim
873353358Sdim  impSym = symtab->addImportData(impName, this);
874344779Sdim  // If this was a duplicate, we logged an error but may continue;
875353358Sdim  // in this case, impSym is nullptr.
876353358Sdim  if (!impSym)
877344779Sdim    return;
878327952Sdim
879353358Sdim  if (hdr->getType() == llvm::COFF::IMPORT_CONST)
880353358Sdim    static_cast<void>(symtab->addImportData(name, this));
881314564Sdim
882292934Sdim  // If type is function, we need to create a thunk which jump to an
883292934Sdim  // address pointed by the __imp_ symbol. (This allows you to call
884292934Sdim  // DLL functions just like regular non-DLL functions.)
885353358Sdim  if (hdr->getType() == llvm::COFF::IMPORT_CODE)
886353358Sdim    thunkSym = symtab->addImportThunk(
887353358Sdim        name, cast_or_null<DefinedImportData>(impSym), hdr->Machine);
888292934Sdim}
889292934Sdim
890353358SdimBitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
891353358Sdim                         uint64_t offsetInArchive)
892360784Sdim    : BitcodeFile(mb, archiveName, offsetInArchive, {}) {}
893360784Sdim
894360784SdimBitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
895360784Sdim                         uint64_t offsetInArchive,
896360784Sdim                         std::vector<Symbol *> &&symbols)
897360784Sdim    : InputFile(BitcodeKind, mb), symbols(std::move(symbols)) {
898353358Sdim  std::string path = mb.getBufferIdentifier().str();
899353358Sdim  if (config->thinLTOIndexOnly)
900353358Sdim    path = replaceThinLTOSuffix(mb.getBufferIdentifier());
901353358Sdim
902353358Sdim  // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
903353358Sdim  // name. If two archives define two members with the same name, this
904353358Sdim  // causes a collision which result in only one of the objects being taken
905353358Sdim  // into consideration at LTO time (which very likely causes undefined
906353358Sdim  // symbols later in the link stage). So we append file offset to make
907353358Sdim  // filename unique.
908353358Sdim  MemoryBufferRef mbref(
909353358Sdim      mb.getBuffer(),
910353358Sdim      saver.save(archiveName + path +
911353358Sdim                 (archiveName.empty() ? "" : utostr(offsetInArchive))));
912353358Sdim
913353358Sdim  obj = check(lto::InputFile::create(mbref));
914353358Sdim}
915353358Sdim
916360784SdimBitcodeFile::~BitcodeFile() = default;
917360784Sdim
918292934Sdimvoid BitcodeFile::parse() {
919353358Sdim  std::vector<std::pair<Symbol *, bool>> comdat(obj->getComdatTable().size());
920353358Sdim  for (size_t i = 0; i != obj->getComdatTable().size(); ++i)
921353358Sdim    // FIXME: lto::InputFile doesn't keep enough data to do correct comdat
922353358Sdim    // selection handling.
923353358Sdim    comdat[i] = symtab->addComdat(this, saver.save(obj->getComdatTable()[i]));
924353358Sdim  for (const lto::InputFile::Symbol &objSym : obj->symbols()) {
925353358Sdim    StringRef symName = saver.save(objSym.getName());
926353358Sdim    int comdatIndex = objSym.getComdatIndex();
927353358Sdim    Symbol *sym;
928353358Sdim    if (objSym.isUndefined()) {
929353358Sdim      sym = symtab->addUndefined(symName, this, false);
930353358Sdim    } else if (objSym.isCommon()) {
931353358Sdim      sym = symtab->addCommon(this, symName, objSym.getCommonSize());
932353358Sdim    } else if (objSym.isWeak() && objSym.isIndirect()) {
933321369Sdim      // Weak external.
934353358Sdim      sym = symtab->addUndefined(symName, this, true);
935353358Sdim      std::string fallback = objSym.getCOFFWeakExternalFallback();
936353358Sdim      Symbol *alias = symtab->addUndefined(saver.save(fallback));
937353358Sdim      checkAndSetWeakAlias(symtab, this, sym, alias);
938353358Sdim    } else if (comdatIndex != -1) {
939353358Sdim      if (symName == obj->getComdatTable()[comdatIndex])
940353358Sdim        sym = comdat[comdatIndex].first;
941353358Sdim      else if (comdat[comdatIndex].second)
942353358Sdim        sym = symtab->addRegular(this, symName);
943327952Sdim      else
944353358Sdim        sym = symtab->addUndefined(symName, this, false);
945292934Sdim    } else {
946353358Sdim      sym = symtab->addRegular(this, symName);
947292934Sdim    }
948353358Sdim    symbols.push_back(sym);
949353358Sdim    if (objSym.isUsed())
950353358Sdim      config->gcroot.push_back(sym);
951292934Sdim  }
952353358Sdim  directives = obj->getCOFFLinkerOpts();
953292934Sdim}
954292934Sdim
955292934SdimMachineTypes BitcodeFile::getMachineType() {
956353358Sdim  switch (Triple(obj->getTargetTriple()).getArch()) {
957292934Sdim  case Triple::x86_64:
958292934Sdim    return AMD64;
959292934Sdim  case Triple::x86:
960292934Sdim    return I386;
961292934Sdim  case Triple::arm:
962292934Sdim    return ARMNT;
963321369Sdim  case Triple::aarch64:
964321369Sdim    return ARM64;
965292934Sdim  default:
966292934Sdim    return IMAGE_FILE_MACHINE_UNKNOWN;
967292934Sdim  }
968292934Sdim}
969353358Sdim
970353358Sdimstd::string replaceThinLTOSuffix(StringRef path) {
971353358Sdim  StringRef suffix = config->thinLTOObjectSuffixReplace.first;
972353358Sdim  StringRef repl = config->thinLTOObjectSuffixReplace.second;
973353358Sdim
974353358Sdim  if (path.consume_back(suffix))
975353358Sdim    return (path + repl).str();
976353358Sdim  return path;
977353358Sdim}
978360784Sdim
979314564Sdim} // namespace coff
980314564Sdim} // namespace lld
981