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