1ece8a530Spatrick //===- InputFiles.cpp -----------------------------------------------------===//
2ece8a530Spatrick //
3ece8a530Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4ece8a530Spatrick // See https://llvm.org/LICENSE.txt for license information.
5ece8a530Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ece8a530Spatrick //
7ece8a530Spatrick //===----------------------------------------------------------------------===//
8ece8a530Spatrick
9ece8a530Spatrick #include "InputFiles.h"
10ece8a530Spatrick #include "Config.h"
11ece8a530Spatrick #include "InputChunks.h"
121cf9926bSpatrick #include "InputElement.h"
131cf9926bSpatrick #include "OutputSegment.h"
14ece8a530Spatrick #include "SymbolTable.h"
15*dfe94b16Srobert #include "lld/Common/Args.h"
16*dfe94b16Srobert #include "lld/Common/CommonLinkerContext.h"
17ece8a530Spatrick #include "lld/Common/Reproduce.h"
18ece8a530Spatrick #include "llvm/Object/Binary.h"
19ece8a530Spatrick #include "llvm/Object/Wasm.h"
20*dfe94b16Srobert #include "llvm/Support/Path.h"
21ece8a530Spatrick #include "llvm/Support/TarWriter.h"
22ece8a530Spatrick #include "llvm/Support/raw_ostream.h"
23*dfe94b16Srobert #include <optional>
24ece8a530Spatrick
25ece8a530Spatrick #define DEBUG_TYPE "lld"
26ece8a530Spatrick
27ece8a530Spatrick using namespace llvm;
28ece8a530Spatrick using namespace llvm::object;
29ece8a530Spatrick using namespace llvm::wasm;
30*dfe94b16Srobert using namespace llvm::sys;
31ece8a530Spatrick
32ece8a530Spatrick namespace lld {
33ece8a530Spatrick
34ece8a530Spatrick // Returns a string in the format of "foo.o" or "foo.a(bar.o)".
toString(const wasm::InputFile * file)35ece8a530Spatrick std::string toString(const wasm::InputFile *file) {
36ece8a530Spatrick if (!file)
37ece8a530Spatrick return "<internal>";
38ece8a530Spatrick
39ece8a530Spatrick if (file->archiveName.empty())
40bb684c34Spatrick return std::string(file->getName());
41ece8a530Spatrick
42ece8a530Spatrick return (file->archiveName + "(" + file->getName() + ")").str();
43ece8a530Spatrick }
44ece8a530Spatrick
45ece8a530Spatrick namespace wasm {
461cf9926bSpatrick
checkArch(Triple::ArchType arch) const471cf9926bSpatrick void InputFile::checkArch(Triple::ArchType arch) const {
481cf9926bSpatrick bool is64 = arch == Triple::wasm64;
49*dfe94b16Srobert if (is64 && !config->is64) {
501cf9926bSpatrick fatal(toString(this) +
511cf9926bSpatrick ": must specify -mwasm64 to process wasm64 object files");
52*dfe94b16Srobert } else if (config->is64.value_or(false) != is64) {
531cf9926bSpatrick fatal(toString(this) +
541cf9926bSpatrick ": wasm32 object file can't be linked in wasm64 mode");
551cf9926bSpatrick }
561cf9926bSpatrick }
571cf9926bSpatrick
58ece8a530Spatrick std::unique_ptr<llvm::TarWriter> tar;
59ece8a530Spatrick
readFile(StringRef path)60*dfe94b16Srobert std::optional<MemoryBufferRef> readFile(StringRef path) {
61ece8a530Spatrick log("Loading: " + path);
62ece8a530Spatrick
63ece8a530Spatrick auto mbOrErr = MemoryBuffer::getFile(path);
64ece8a530Spatrick if (auto ec = mbOrErr.getError()) {
65ece8a530Spatrick error("cannot open " + path + ": " + ec.message());
66*dfe94b16Srobert return std::nullopt;
67ece8a530Spatrick }
68ece8a530Spatrick std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
69ece8a530Spatrick MemoryBufferRef mbref = mb->getMemBufferRef();
70ece8a530Spatrick make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
71ece8a530Spatrick
72ece8a530Spatrick if (tar)
73ece8a530Spatrick tar->append(relativeToRoot(path), mbref.getBuffer());
74ece8a530Spatrick return mbref;
75ece8a530Spatrick }
76ece8a530Spatrick
createObjectFile(MemoryBufferRef mb,StringRef archiveName,uint64_t offsetInArchive)77*dfe94b16Srobert InputFile *createObjectFile(MemoryBufferRef mb, StringRef archiveName,
78*dfe94b16Srobert uint64_t offsetInArchive) {
79ece8a530Spatrick file_magic magic = identify_magic(mb.getBuffer());
80ece8a530Spatrick if (magic == file_magic::wasm_object) {
81ece8a530Spatrick std::unique_ptr<Binary> bin =
82ece8a530Spatrick CHECK(createBinary(mb), mb.getBufferIdentifier());
83ece8a530Spatrick auto *obj = cast<WasmObjectFile>(bin.get());
84ece8a530Spatrick if (obj->isSharedObject())
85ece8a530Spatrick return make<SharedFile>(mb);
86ece8a530Spatrick return make<ObjFile>(mb, archiveName);
87ece8a530Spatrick }
88ece8a530Spatrick
89ece8a530Spatrick if (magic == file_magic::bitcode)
90*dfe94b16Srobert return make<BitcodeFile>(mb, archiveName, offsetInArchive);
91ece8a530Spatrick
92*dfe94b16Srobert std::string name = mb.getBufferIdentifier().str();
93*dfe94b16Srobert if (!archiveName.empty()) {
94*dfe94b16Srobert name = archiveName.str() + "(" + name + ")";
95ece8a530Spatrick }
96ece8a530Spatrick
97*dfe94b16Srobert fatal("unknown file type: " + name);
98ece8a530Spatrick }
99ece8a530Spatrick
100ece8a530Spatrick // Relocations contain either symbol or type indices. This function takes a
101ece8a530Spatrick // relocation and returns relocated index (i.e. translates from the input
102ece8a530Spatrick // symbol/type space to the output symbol/type space).
calcNewIndex(const WasmRelocation & reloc) const103ece8a530Spatrick uint32_t ObjFile::calcNewIndex(const WasmRelocation &reloc) const {
104ece8a530Spatrick if (reloc.Type == R_WASM_TYPE_INDEX_LEB) {
105ece8a530Spatrick assert(typeIsUsed[reloc.Index]);
106ece8a530Spatrick return typeMap[reloc.Index];
107ece8a530Spatrick }
108ece8a530Spatrick const Symbol *sym = symbols[reloc.Index];
109ece8a530Spatrick if (auto *ss = dyn_cast<SectionSymbol>(sym))
110ece8a530Spatrick sym = ss->getOutputSectionSymbol();
111ece8a530Spatrick return sym->getOutputSymbolIndex();
112ece8a530Spatrick }
113ece8a530Spatrick
114ece8a530Spatrick // Relocations can contain addend for combined sections. This function takes a
115ece8a530Spatrick // relocation and returns updated addend by offset in the output section.
calcNewAddend(const WasmRelocation & reloc) const116*dfe94b16Srobert int64_t ObjFile::calcNewAddend(const WasmRelocation &reloc) const {
117ece8a530Spatrick switch (reloc.Type) {
118ece8a530Spatrick case R_WASM_MEMORY_ADDR_LEB:
119bb684c34Spatrick case R_WASM_MEMORY_ADDR_LEB64:
120bb684c34Spatrick case R_WASM_MEMORY_ADDR_SLEB64:
121ece8a530Spatrick case R_WASM_MEMORY_ADDR_SLEB:
122ece8a530Spatrick case R_WASM_MEMORY_ADDR_REL_SLEB:
123bb684c34Spatrick case R_WASM_MEMORY_ADDR_REL_SLEB64:
124ece8a530Spatrick case R_WASM_MEMORY_ADDR_I32:
125bb684c34Spatrick case R_WASM_MEMORY_ADDR_I64:
1261cf9926bSpatrick case R_WASM_MEMORY_ADDR_TLS_SLEB:
1271cf9926bSpatrick case R_WASM_MEMORY_ADDR_TLS_SLEB64:
128ece8a530Spatrick case R_WASM_FUNCTION_OFFSET_I32:
1291cf9926bSpatrick case R_WASM_FUNCTION_OFFSET_I64:
1301cf9926bSpatrick case R_WASM_MEMORY_ADDR_LOCREL_I32:
131ece8a530Spatrick return reloc.Addend;
132ece8a530Spatrick case R_WASM_SECTION_OFFSET_I32:
1331cf9926bSpatrick return getSectionSymbol(reloc.Index)->section->getOffset(reloc.Addend);
134ece8a530Spatrick default:
135ece8a530Spatrick llvm_unreachable("unexpected relocation type");
136ece8a530Spatrick }
137ece8a530Spatrick }
138ece8a530Spatrick
139ece8a530Spatrick // Translate from the relocation's index into the final linked output value.
calcNewValue(const WasmRelocation & reloc,uint64_t tombstone,const InputChunk * chunk) const1401cf9926bSpatrick uint64_t ObjFile::calcNewValue(const WasmRelocation &reloc, uint64_t tombstone,
1411cf9926bSpatrick const InputChunk *chunk) const {
142ece8a530Spatrick const Symbol* sym = nullptr;
143ece8a530Spatrick if (reloc.Type != R_WASM_TYPE_INDEX_LEB) {
144ece8a530Spatrick sym = symbols[reloc.Index];
145ece8a530Spatrick
146ece8a530Spatrick // We can end up with relocations against non-live symbols. For example
1471cf9926bSpatrick // in debug sections. We return a tombstone value in debug symbol sections
1481cf9926bSpatrick // so this will not produce a valid range conflicting with ranges of actual
1491cf9926bSpatrick // code. In other sections we return reloc.Addend.
1501cf9926bSpatrick
1511cf9926bSpatrick if (!isa<SectionSymbol>(sym) && !sym->isLive())
1521cf9926bSpatrick return tombstone ? tombstone : reloc.Addend;
153ece8a530Spatrick }
154ece8a530Spatrick
155ece8a530Spatrick switch (reloc.Type) {
156ece8a530Spatrick case R_WASM_TABLE_INDEX_I32:
1571cf9926bSpatrick case R_WASM_TABLE_INDEX_I64:
158ece8a530Spatrick case R_WASM_TABLE_INDEX_SLEB:
1591cf9926bSpatrick case R_WASM_TABLE_INDEX_SLEB64:
1601cf9926bSpatrick case R_WASM_TABLE_INDEX_REL_SLEB:
1611cf9926bSpatrick case R_WASM_TABLE_INDEX_REL_SLEB64: {
162ece8a530Spatrick if (!getFunctionSymbol(reloc.Index)->hasTableIndex())
163ece8a530Spatrick return 0;
164ece8a530Spatrick uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex();
1651cf9926bSpatrick if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB ||
1661cf9926bSpatrick reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB64)
167ece8a530Spatrick index -= config->tableBase;
168ece8a530Spatrick return index;
169ece8a530Spatrick }
170ece8a530Spatrick case R_WASM_MEMORY_ADDR_LEB:
171bb684c34Spatrick case R_WASM_MEMORY_ADDR_LEB64:
172bb684c34Spatrick case R_WASM_MEMORY_ADDR_SLEB:
173bb684c34Spatrick case R_WASM_MEMORY_ADDR_SLEB64:
174ece8a530Spatrick case R_WASM_MEMORY_ADDR_REL_SLEB:
175bb684c34Spatrick case R_WASM_MEMORY_ADDR_REL_SLEB64:
176bb684c34Spatrick case R_WASM_MEMORY_ADDR_I32:
177bb684c34Spatrick case R_WASM_MEMORY_ADDR_I64:
178*dfe94b16Srobert case R_WASM_MEMORY_ADDR_TLS_SLEB:
179*dfe94b16Srobert case R_WASM_MEMORY_ADDR_TLS_SLEB64:
1801cf9926bSpatrick case R_WASM_MEMORY_ADDR_LOCREL_I32: {
181ece8a530Spatrick if (isa<UndefinedData>(sym) || sym->isUndefWeak())
182ece8a530Spatrick return 0;
1831cf9926bSpatrick auto D = cast<DefinedData>(sym);
1841cf9926bSpatrick uint64_t value = D->getVA() + reloc.Addend;
1851cf9926bSpatrick if (reloc.Type == R_WASM_MEMORY_ADDR_LOCREL_I32) {
1861cf9926bSpatrick const auto *segment = cast<InputSegment>(chunk);
1871cf9926bSpatrick uint64_t p = segment->outputSeg->startVA + segment->outputSegmentOffset +
1881cf9926bSpatrick reloc.Offset - segment->getInputSectionOffset();
1891cf9926bSpatrick value -= p;
1901cf9926bSpatrick }
1911cf9926bSpatrick return value;
1921cf9926bSpatrick }
193ece8a530Spatrick case R_WASM_TYPE_INDEX_LEB:
194ece8a530Spatrick return typeMap[reloc.Index];
195ece8a530Spatrick case R_WASM_FUNCTION_INDEX_LEB:
196ece8a530Spatrick return getFunctionSymbol(reloc.Index)->getFunctionIndex();
197ece8a530Spatrick case R_WASM_GLOBAL_INDEX_LEB:
198bb684c34Spatrick case R_WASM_GLOBAL_INDEX_I32:
199ece8a530Spatrick if (auto gs = dyn_cast<GlobalSymbol>(sym))
200ece8a530Spatrick return gs->getGlobalIndex();
201ece8a530Spatrick return sym->getGOTIndex();
2021cf9926bSpatrick case R_WASM_TAG_INDEX_LEB:
2031cf9926bSpatrick return getTagSymbol(reloc.Index)->getTagIndex();
2041cf9926bSpatrick case R_WASM_FUNCTION_OFFSET_I32:
2051cf9926bSpatrick case R_WASM_FUNCTION_OFFSET_I64: {
206*dfe94b16Srobert if (isa<UndefinedFunction>(sym)) {
207*dfe94b16Srobert return tombstone ? tombstone : reloc.Addend;
208*dfe94b16Srobert }
209ece8a530Spatrick auto *f = cast<DefinedFunction>(sym);
2101cf9926bSpatrick return f->function->getOffset(f->function->getFunctionCodeOffset() +
2111cf9926bSpatrick reloc.Addend);
212ece8a530Spatrick }
213ece8a530Spatrick case R_WASM_SECTION_OFFSET_I32:
2141cf9926bSpatrick return getSectionSymbol(reloc.Index)->section->getOffset(reloc.Addend);
2151cf9926bSpatrick case R_WASM_TABLE_NUMBER_LEB:
2161cf9926bSpatrick return getTableSymbol(reloc.Index)->getTableNumber();
217ece8a530Spatrick default:
218ece8a530Spatrick llvm_unreachable("unknown relocation type");
219ece8a530Spatrick }
220ece8a530Spatrick }
221ece8a530Spatrick
222ece8a530Spatrick template <class T>
setRelocs(const std::vector<T * > & chunks,const WasmSection * section)223ece8a530Spatrick static void setRelocs(const std::vector<T *> &chunks,
224ece8a530Spatrick const WasmSection *section) {
225ece8a530Spatrick if (!section)
226ece8a530Spatrick return;
227ece8a530Spatrick
228ece8a530Spatrick ArrayRef<WasmRelocation> relocs = section->Relocations;
229bb684c34Spatrick assert(llvm::is_sorted(
230bb684c34Spatrick relocs, [](const WasmRelocation &r1, const WasmRelocation &r2) {
231ece8a530Spatrick return r1.Offset < r2.Offset;
232ece8a530Spatrick }));
233bb684c34Spatrick assert(llvm::is_sorted(chunks, [](InputChunk *c1, InputChunk *c2) {
234ece8a530Spatrick return c1->getInputSectionOffset() < c2->getInputSectionOffset();
235ece8a530Spatrick }));
236ece8a530Spatrick
237ece8a530Spatrick auto relocsNext = relocs.begin();
238ece8a530Spatrick auto relocsEnd = relocs.end();
239ece8a530Spatrick auto relocLess = [](const WasmRelocation &r, uint32_t val) {
240ece8a530Spatrick return r.Offset < val;
241ece8a530Spatrick };
242ece8a530Spatrick for (InputChunk *c : chunks) {
243ece8a530Spatrick auto relocsStart = std::lower_bound(relocsNext, relocsEnd,
244ece8a530Spatrick c->getInputSectionOffset(), relocLess);
245ece8a530Spatrick relocsNext = std::lower_bound(
246ece8a530Spatrick relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(),
247ece8a530Spatrick relocLess);
248ece8a530Spatrick c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext));
249ece8a530Spatrick }
250ece8a530Spatrick }
251ece8a530Spatrick
2521cf9926bSpatrick // An object file can have two approaches to tables. With the reference-types
2531cf9926bSpatrick // feature enabled, input files that define or use tables declare the tables
2541cf9926bSpatrick // using symbols, and record each use with a relocation. This way when the
2551cf9926bSpatrick // linker combines inputs, it can collate the tables used by the inputs,
2561cf9926bSpatrick // assigning them distinct table numbers, and renumber all the uses as
2571cf9926bSpatrick // appropriate. At the same time, the linker has special logic to build the
2581cf9926bSpatrick // indirect function table if it is needed.
2591cf9926bSpatrick //
2601cf9926bSpatrick // However, MVP object files (those that target WebAssembly 1.0, the "minimum
2611cf9926bSpatrick // viable product" version of WebAssembly) neither write table symbols nor
2621cf9926bSpatrick // record relocations. These files can have at most one table, the indirect
2631cf9926bSpatrick // function table used by call_indirect and which is the address space for
2641cf9926bSpatrick // function pointers. If this table is present, it is always an import. If we
2651cf9926bSpatrick // have a file with a table import but no table symbols, it is an MVP object
2661cf9926bSpatrick // file. synthesizeMVPIndirectFunctionTableSymbolIfNeeded serves as a shim when
2671cf9926bSpatrick // loading these input files, defining the missing symbol to allow the indirect
2681cf9926bSpatrick // function table to be built.
2691cf9926bSpatrick //
2701cf9926bSpatrick // As indirect function table table usage in MVP objects cannot be relocated,
2711cf9926bSpatrick // the linker must ensure that this table gets assigned index zero.
addLegacyIndirectFunctionTableIfNeeded(uint32_t tableSymbolCount)2721cf9926bSpatrick void ObjFile::addLegacyIndirectFunctionTableIfNeeded(
2731cf9926bSpatrick uint32_t tableSymbolCount) {
2741cf9926bSpatrick uint32_t tableCount = wasmObj->getNumImportedTables() + tables.size();
2751cf9926bSpatrick
2761cf9926bSpatrick // If there are symbols for all tables, then all is good.
2771cf9926bSpatrick if (tableCount == tableSymbolCount)
2781cf9926bSpatrick return;
2791cf9926bSpatrick
2801cf9926bSpatrick // It's possible for an input to define tables and also use the indirect
2811cf9926bSpatrick // function table, but forget to compile with -mattr=+reference-types.
2821cf9926bSpatrick // For these newer files, we require symbols for all tables, and
2831cf9926bSpatrick // relocations for all of their uses.
2841cf9926bSpatrick if (tableSymbolCount != 0) {
2851cf9926bSpatrick error(toString(this) +
2861cf9926bSpatrick ": expected one symbol table entry for each of the " +
2871cf9926bSpatrick Twine(tableCount) + " table(s) present, but got " +
2881cf9926bSpatrick Twine(tableSymbolCount) + " symbol(s) instead.");
2891cf9926bSpatrick return;
2901cf9926bSpatrick }
2911cf9926bSpatrick
2921cf9926bSpatrick // An MVP object file can have up to one table import, for the indirect
2931cf9926bSpatrick // function table, but will have no table definitions.
2941cf9926bSpatrick if (tables.size()) {
2951cf9926bSpatrick error(toString(this) +
2961cf9926bSpatrick ": unexpected table definition(s) without corresponding "
2971cf9926bSpatrick "symbol-table entries.");
2981cf9926bSpatrick return;
2991cf9926bSpatrick }
3001cf9926bSpatrick
3011cf9926bSpatrick // An MVP object file can have only one table import.
3021cf9926bSpatrick if (tableCount != 1) {
3031cf9926bSpatrick error(toString(this) +
3041cf9926bSpatrick ": multiple table imports, but no corresponding symbol-table "
3051cf9926bSpatrick "entries.");
3061cf9926bSpatrick return;
3071cf9926bSpatrick }
3081cf9926bSpatrick
3091cf9926bSpatrick const WasmImport *tableImport = nullptr;
3101cf9926bSpatrick for (const auto &import : wasmObj->imports()) {
3111cf9926bSpatrick if (import.Kind == WASM_EXTERNAL_TABLE) {
3121cf9926bSpatrick assert(!tableImport);
3131cf9926bSpatrick tableImport = &import;
3141cf9926bSpatrick }
3151cf9926bSpatrick }
3161cf9926bSpatrick assert(tableImport);
3171cf9926bSpatrick
3181cf9926bSpatrick // We can only synthesize a symtab entry for the indirect function table; if
3191cf9926bSpatrick // it has an unexpected name or type, assume that it's not actually the
3201cf9926bSpatrick // indirect function table.
3211cf9926bSpatrick if (tableImport->Field != functionTableName ||
3221cf9926bSpatrick tableImport->Table.ElemType != uint8_t(ValType::FUNCREF)) {
3231cf9926bSpatrick error(toString(this) + ": table import " + Twine(tableImport->Field) +
3241cf9926bSpatrick " is missing a symbol table entry.");
3251cf9926bSpatrick return;
3261cf9926bSpatrick }
3271cf9926bSpatrick
3281cf9926bSpatrick auto *info = make<WasmSymbolInfo>();
3291cf9926bSpatrick info->Name = tableImport->Field;
3301cf9926bSpatrick info->Kind = WASM_SYMBOL_TYPE_TABLE;
3311cf9926bSpatrick info->ImportModule = tableImport->Module;
3321cf9926bSpatrick info->ImportName = tableImport->Field;
3331cf9926bSpatrick info->Flags = WASM_SYMBOL_UNDEFINED;
3341cf9926bSpatrick info->Flags |= WASM_SYMBOL_NO_STRIP;
3351cf9926bSpatrick info->ElementIndex = 0;
3361cf9926bSpatrick LLVM_DEBUG(dbgs() << "Synthesizing symbol for table import: " << info->Name
3371cf9926bSpatrick << "\n");
3381cf9926bSpatrick const WasmGlobalType *globalType = nullptr;
3391cf9926bSpatrick const WasmSignature *signature = nullptr;
340*dfe94b16Srobert auto *wasmSym =
341*dfe94b16Srobert make<WasmSymbol>(*info, globalType, &tableImport->Table, signature);
3421cf9926bSpatrick Symbol *sym = createUndefined(*wasmSym, false);
3431cf9926bSpatrick // We're only sure it's a TableSymbol if the createUndefined succeeded.
3441cf9926bSpatrick if (errorCount())
3451cf9926bSpatrick return;
3461cf9926bSpatrick symbols.push_back(sym);
3471cf9926bSpatrick // Because there are no TABLE_NUMBER relocs, we can't compute accurate
3481cf9926bSpatrick // liveness info; instead, just mark the symbol as always live.
3491cf9926bSpatrick sym->markLive();
3501cf9926bSpatrick
3511cf9926bSpatrick // We assume that this compilation unit has unrelocatable references to
3521cf9926bSpatrick // this table.
3531cf9926bSpatrick config->legacyFunctionTable = true;
3541cf9926bSpatrick }
3551cf9926bSpatrick
shouldMerge(const WasmSection & sec)3561cf9926bSpatrick static bool shouldMerge(const WasmSection &sec) {
3571cf9926bSpatrick if (config->optimize == 0)
3581cf9926bSpatrick return false;
3591cf9926bSpatrick // Sadly we don't have section attributes yet for custom sections, so we
3601cf9926bSpatrick // currently go by the name alone.
3611cf9926bSpatrick // TODO(sbc): Add ability for wasm sections to carry flags so we don't
3621cf9926bSpatrick // need to use names here.
3631cf9926bSpatrick // For now, keep in sync with uses of wasm::WASM_SEG_FLAG_STRINGS in
3641cf9926bSpatrick // MCObjectFileInfo::initWasmMCObjectFileInfo which creates these custom
3651cf9926bSpatrick // sections.
3661cf9926bSpatrick return sec.Name == ".debug_str" || sec.Name == ".debug_str.dwo" ||
3671cf9926bSpatrick sec.Name == ".debug_line_str";
3681cf9926bSpatrick }
3691cf9926bSpatrick
shouldMerge(const WasmSegment & seg)3701cf9926bSpatrick static bool shouldMerge(const WasmSegment &seg) {
3711cf9926bSpatrick // As of now we only support merging strings, and only with single byte
3721cf9926bSpatrick // alignment (2^0).
3731cf9926bSpatrick if (!(seg.Data.LinkingFlags & WASM_SEG_FLAG_STRINGS) ||
3741cf9926bSpatrick (seg.Data.Alignment != 0))
3751cf9926bSpatrick return false;
3761cf9926bSpatrick
3771cf9926bSpatrick // On a regular link we don't merge sections if -O0 (default is -O1). This
3781cf9926bSpatrick // sometimes makes the linker significantly faster, although the output will
3791cf9926bSpatrick // be bigger.
3801cf9926bSpatrick if (config->optimize == 0)
3811cf9926bSpatrick return false;
3821cf9926bSpatrick
3831cf9926bSpatrick // A mergeable section with size 0 is useless because they don't have
3841cf9926bSpatrick // any data to merge. A mergeable string section with size 0 can be
3851cf9926bSpatrick // argued as invalid because it doesn't end with a null character.
3861cf9926bSpatrick // We'll avoid a mess by handling them as if they were non-mergeable.
3871cf9926bSpatrick if (seg.Data.Content.size() == 0)
3881cf9926bSpatrick return false;
3891cf9926bSpatrick
3901cf9926bSpatrick return true;
3911cf9926bSpatrick }
3921cf9926bSpatrick
parse(bool ignoreComdats)393ece8a530Spatrick void ObjFile::parse(bool ignoreComdats) {
394ece8a530Spatrick // Parse a memory buffer as a wasm file.
395ece8a530Spatrick LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
396ece8a530Spatrick std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this));
397ece8a530Spatrick
398ece8a530Spatrick auto *obj = dyn_cast<WasmObjectFile>(bin.get());
399ece8a530Spatrick if (!obj)
400ece8a530Spatrick fatal(toString(this) + ": not a wasm file");
401ece8a530Spatrick if (!obj->isRelocatableObject())
402ece8a530Spatrick fatal(toString(this) + ": not a relocatable wasm file");
403ece8a530Spatrick
404ece8a530Spatrick bin.release();
405ece8a530Spatrick wasmObj.reset(obj);
406ece8a530Spatrick
4071cf9926bSpatrick checkArch(obj->getArch());
4081cf9926bSpatrick
409ece8a530Spatrick // Build up a map of function indices to table indices for use when
410ece8a530Spatrick // verifying the existing table index relocations
411ece8a530Spatrick uint32_t totalFunctions =
412ece8a530Spatrick wasmObj->getNumImportedFunctions() + wasmObj->functions().size();
413bb684c34Spatrick tableEntriesRel.resize(totalFunctions);
414ece8a530Spatrick tableEntries.resize(totalFunctions);
415ece8a530Spatrick for (const WasmElemSegment &seg : wasmObj->elements()) {
416bb684c34Spatrick int64_t offset;
417*dfe94b16Srobert if (seg.Offset.Extended)
418*dfe94b16Srobert fatal(toString(this) + ": extended init exprs not supported");
419*dfe94b16Srobert else if (seg.Offset.Inst.Opcode == WASM_OPCODE_I32_CONST)
420*dfe94b16Srobert offset = seg.Offset.Inst.Value.Int32;
421*dfe94b16Srobert else if (seg.Offset.Inst.Opcode == WASM_OPCODE_I64_CONST)
422*dfe94b16Srobert offset = seg.Offset.Inst.Value.Int64;
423bb684c34Spatrick else
424ece8a530Spatrick fatal(toString(this) + ": invalid table elements");
425bb684c34Spatrick for (size_t index = 0; index < seg.Functions.size(); index++) {
426bb684c34Spatrick auto functionIndex = seg.Functions[index];
427bb684c34Spatrick tableEntriesRel[functionIndex] = index;
428ece8a530Spatrick tableEntries[functionIndex] = offset + index;
429ece8a530Spatrick }
430ece8a530Spatrick }
431ece8a530Spatrick
4321cf9926bSpatrick ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats;
4331cf9926bSpatrick for (StringRef comdat : comdats) {
4341cf9926bSpatrick bool isNew = ignoreComdats || symtab->addComdat(comdat);
4351cf9926bSpatrick keptComdats.push_back(isNew);
4361cf9926bSpatrick }
4371cf9926bSpatrick
438ece8a530Spatrick uint32_t sectionIndex = 0;
439ece8a530Spatrick
440ece8a530Spatrick // Bool for each symbol, true if called directly. This allows us to implement
441ece8a530Spatrick // a weaker form of signature checking where undefined functions that are not
442ece8a530Spatrick // called directly (i.e. only address taken) don't have to match the defined
443ece8a530Spatrick // function's signature. We cannot do this for directly called functions
444ece8a530Spatrick // because those signatures are checked at validation times.
445ece8a530Spatrick // See https://bugs.llvm.org/show_bug.cgi?id=40412
446ece8a530Spatrick std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false);
447ece8a530Spatrick for (const SectionRef &sec : wasmObj->sections()) {
448ece8a530Spatrick const WasmSection §ion = wasmObj->getWasmSection(sec);
449ece8a530Spatrick // Wasm objects can have at most one code and one data section.
450ece8a530Spatrick if (section.Type == WASM_SEC_CODE) {
451ece8a530Spatrick assert(!codeSection);
452ece8a530Spatrick codeSection = §ion;
453ece8a530Spatrick } else if (section.Type == WASM_SEC_DATA) {
454ece8a530Spatrick assert(!dataSection);
455ece8a530Spatrick dataSection = §ion;
456ece8a530Spatrick } else if (section.Type == WASM_SEC_CUSTOM) {
4571cf9926bSpatrick InputChunk *customSec;
4581cf9926bSpatrick if (shouldMerge(section))
4591cf9926bSpatrick customSec = make<MergeInputChunk>(section, this);
4601cf9926bSpatrick else
4611cf9926bSpatrick customSec = make<InputSection>(section, this);
4621cf9926bSpatrick customSec->discarded = isExcludedByComdat(customSec);
4631cf9926bSpatrick customSections.emplace_back(customSec);
464ece8a530Spatrick customSections.back()->setRelocations(section.Relocations);
465ece8a530Spatrick customSectionsByIndex[sectionIndex] = customSections.back();
466ece8a530Spatrick }
467ece8a530Spatrick sectionIndex++;
468ece8a530Spatrick // Scans relocations to determine if a function symbol is called directly.
469ece8a530Spatrick for (const WasmRelocation &reloc : section.Relocations)
470ece8a530Spatrick if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB)
471ece8a530Spatrick isCalledDirectly[reloc.Index] = true;
472ece8a530Spatrick }
473ece8a530Spatrick
474ece8a530Spatrick typeMap.resize(getWasmObj()->types().size());
475ece8a530Spatrick typeIsUsed.resize(getWasmObj()->types().size(), false);
476ece8a530Spatrick
477ece8a530Spatrick
478ece8a530Spatrick // Populate `Segments`.
479ece8a530Spatrick for (const WasmSegment &s : wasmObj->dataSegments()) {
4801cf9926bSpatrick InputChunk *seg;
481*dfe94b16Srobert if (shouldMerge(s))
4821cf9926bSpatrick seg = make<MergeInputChunk>(s, this);
483*dfe94b16Srobert else
4841cf9926bSpatrick seg = make<InputSegment>(s, this);
485ece8a530Spatrick seg->discarded = isExcludedByComdat(seg);
486*dfe94b16Srobert // Older object files did not include WASM_SEG_FLAG_TLS and instead
487*dfe94b16Srobert // relied on the naming convention. To maintain compat with such objects
488*dfe94b16Srobert // we still imply the TLS flag based on the name of the segment.
489*dfe94b16Srobert if (!seg->isTLS() &&
490*dfe94b16Srobert (seg->name.startswith(".tdata") || seg->name.startswith(".tbss")))
491*dfe94b16Srobert seg->flags |= WASM_SEG_FLAG_TLS;
492ece8a530Spatrick segments.emplace_back(seg);
493ece8a530Spatrick }
494ece8a530Spatrick setRelocs(segments, dataSection);
495ece8a530Spatrick
496ece8a530Spatrick // Populate `Functions`.
497ece8a530Spatrick ArrayRef<WasmFunction> funcs = wasmObj->functions();
498ece8a530Spatrick ArrayRef<WasmSignature> types = wasmObj->types();
499ece8a530Spatrick functions.reserve(funcs.size());
500ece8a530Spatrick
501*dfe94b16Srobert for (auto &f : funcs) {
502*dfe94b16Srobert auto *func = make<InputFunction>(types[f.SigIndex], &f, this);
503ece8a530Spatrick func->discarded = isExcludedByComdat(func);
504ece8a530Spatrick functions.emplace_back(func);
505ece8a530Spatrick }
506ece8a530Spatrick setRelocs(functions, codeSection);
507ece8a530Spatrick
5081cf9926bSpatrick // Populate `Tables`.
5091cf9926bSpatrick for (const WasmTable &t : wasmObj->tables())
5101cf9926bSpatrick tables.emplace_back(make<InputTable>(t, this));
5111cf9926bSpatrick
512ece8a530Spatrick // Populate `Globals`.
513ece8a530Spatrick for (const WasmGlobal &g : wasmObj->globals())
514ece8a530Spatrick globals.emplace_back(make<InputGlobal>(g, this));
515ece8a530Spatrick
5161cf9926bSpatrick // Populate `Tags`.
5171cf9926bSpatrick for (const WasmTag &t : wasmObj->tags())
518*dfe94b16Srobert tags.emplace_back(make<InputTag>(types[t.SigIndex], t, this));
519ece8a530Spatrick
520ece8a530Spatrick // Populate `Symbols` based on the symbols in the object.
521ece8a530Spatrick symbols.reserve(wasmObj->getNumberOfSymbols());
5221cf9926bSpatrick uint32_t tableSymbolCount = 0;
523ece8a530Spatrick for (const SymbolRef &sym : wasmObj->symbols()) {
524ece8a530Spatrick const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl());
5251cf9926bSpatrick if (wasmSym.isTypeTable())
5261cf9926bSpatrick tableSymbolCount++;
527ece8a530Spatrick if (wasmSym.isDefined()) {
528ece8a530Spatrick // createDefined may fail if the symbol is comdat excluded in which case
529ece8a530Spatrick // we fall back to creating an undefined symbol
530ece8a530Spatrick if (Symbol *d = createDefined(wasmSym)) {
531ece8a530Spatrick symbols.push_back(d);
532ece8a530Spatrick continue;
533ece8a530Spatrick }
534ece8a530Spatrick }
535ece8a530Spatrick size_t idx = symbols.size();
536ece8a530Spatrick symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx]));
537ece8a530Spatrick }
5381cf9926bSpatrick
5391cf9926bSpatrick addLegacyIndirectFunctionTableIfNeeded(tableSymbolCount);
540ece8a530Spatrick }
541ece8a530Spatrick
isExcludedByComdat(const InputChunk * chunk) const542*dfe94b16Srobert bool ObjFile::isExcludedByComdat(const InputChunk *chunk) const {
543ece8a530Spatrick uint32_t c = chunk->getComdat();
544ece8a530Spatrick if (c == UINT32_MAX)
545ece8a530Spatrick return false;
546ece8a530Spatrick return !keptComdats[c];
547ece8a530Spatrick }
548ece8a530Spatrick
getFunctionSymbol(uint32_t index) const549ece8a530Spatrick FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const {
550ece8a530Spatrick return cast<FunctionSymbol>(symbols[index]);
551ece8a530Spatrick }
552ece8a530Spatrick
getGlobalSymbol(uint32_t index) const553ece8a530Spatrick GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const {
554ece8a530Spatrick return cast<GlobalSymbol>(symbols[index]);
555ece8a530Spatrick }
556ece8a530Spatrick
getTagSymbol(uint32_t index) const5571cf9926bSpatrick TagSymbol *ObjFile::getTagSymbol(uint32_t index) const {
5581cf9926bSpatrick return cast<TagSymbol>(symbols[index]);
5591cf9926bSpatrick }
5601cf9926bSpatrick
getTableSymbol(uint32_t index) const5611cf9926bSpatrick TableSymbol *ObjFile::getTableSymbol(uint32_t index) const {
5621cf9926bSpatrick return cast<TableSymbol>(symbols[index]);
563ece8a530Spatrick }
564ece8a530Spatrick
getSectionSymbol(uint32_t index) const565ece8a530Spatrick SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const {
566ece8a530Spatrick return cast<SectionSymbol>(symbols[index]);
567ece8a530Spatrick }
568ece8a530Spatrick
getDataSymbol(uint32_t index) const569ece8a530Spatrick DataSymbol *ObjFile::getDataSymbol(uint32_t index) const {
570ece8a530Spatrick return cast<DataSymbol>(symbols[index]);
571ece8a530Spatrick }
572ece8a530Spatrick
createDefined(const WasmSymbol & sym)573ece8a530Spatrick Symbol *ObjFile::createDefined(const WasmSymbol &sym) {
574ece8a530Spatrick StringRef name = sym.Info.Name;
575ece8a530Spatrick uint32_t flags = sym.Info.Flags;
576ece8a530Spatrick
577ece8a530Spatrick switch (sym.Info.Kind) {
578ece8a530Spatrick case WASM_SYMBOL_TYPE_FUNCTION: {
579ece8a530Spatrick InputFunction *func =
580ece8a530Spatrick functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
581ece8a530Spatrick if (sym.isBindingLocal())
582ece8a530Spatrick return make<DefinedFunction>(name, flags, this, func);
583ece8a530Spatrick if (func->discarded)
584ece8a530Spatrick return nullptr;
585ece8a530Spatrick return symtab->addDefinedFunction(name, flags, this, func);
586ece8a530Spatrick }
587ece8a530Spatrick case WASM_SYMBOL_TYPE_DATA: {
5881cf9926bSpatrick InputChunk *seg = segments[sym.Info.DataRef.Segment];
589bb684c34Spatrick auto offset = sym.Info.DataRef.Offset;
590bb684c34Spatrick auto size = sym.Info.DataRef.Size;
591*dfe94b16Srobert // Support older (e.g. llvm 13) object files that pre-date the per-symbol
592*dfe94b16Srobert // TLS flag, and symbols were assumed to be TLS by being defined in a TLS
593*dfe94b16Srobert // segment.
594*dfe94b16Srobert if (!(flags & WASM_SYMBOL_TLS) && seg->isTLS())
595*dfe94b16Srobert flags |= WASM_SYMBOL_TLS;
596ece8a530Spatrick if (sym.isBindingLocal())
597ece8a530Spatrick return make<DefinedData>(name, flags, this, seg, offset, size);
598ece8a530Spatrick if (seg->discarded)
599ece8a530Spatrick return nullptr;
600ece8a530Spatrick return symtab->addDefinedData(name, flags, this, seg, offset, size);
601ece8a530Spatrick }
602ece8a530Spatrick case WASM_SYMBOL_TYPE_GLOBAL: {
603ece8a530Spatrick InputGlobal *global =
604ece8a530Spatrick globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()];
605ece8a530Spatrick if (sym.isBindingLocal())
606ece8a530Spatrick return make<DefinedGlobal>(name, flags, this, global);
607ece8a530Spatrick return symtab->addDefinedGlobal(name, flags, this, global);
608ece8a530Spatrick }
609ece8a530Spatrick case WASM_SYMBOL_TYPE_SECTION: {
6101cf9926bSpatrick InputChunk *section = customSectionsByIndex[sym.Info.ElementIndex];
611ece8a530Spatrick assert(sym.isBindingLocal());
6121cf9926bSpatrick // Need to return null if discarded here? data and func only do that when
6131cf9926bSpatrick // binding is not local.
6141cf9926bSpatrick if (section->discarded)
6151cf9926bSpatrick return nullptr;
616ece8a530Spatrick return make<SectionSymbol>(flags, section, this);
617ece8a530Spatrick }
6181cf9926bSpatrick case WASM_SYMBOL_TYPE_TAG: {
6191cf9926bSpatrick InputTag *tag = tags[sym.Info.ElementIndex - wasmObj->getNumImportedTags()];
620ece8a530Spatrick if (sym.isBindingLocal())
6211cf9926bSpatrick return make<DefinedTag>(name, flags, this, tag);
6221cf9926bSpatrick return symtab->addDefinedTag(name, flags, this, tag);
6231cf9926bSpatrick }
6241cf9926bSpatrick case WASM_SYMBOL_TYPE_TABLE: {
6251cf9926bSpatrick InputTable *table =
6261cf9926bSpatrick tables[sym.Info.ElementIndex - wasmObj->getNumImportedTables()];
6271cf9926bSpatrick if (sym.isBindingLocal())
6281cf9926bSpatrick return make<DefinedTable>(name, flags, this, table);
6291cf9926bSpatrick return symtab->addDefinedTable(name, flags, this, table);
630ece8a530Spatrick }
631ece8a530Spatrick }
632ece8a530Spatrick llvm_unreachable("unknown symbol kind");
633ece8a530Spatrick }
634ece8a530Spatrick
createUndefined(const WasmSymbol & sym,bool isCalledDirectly)635ece8a530Spatrick Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) {
636ece8a530Spatrick StringRef name = sym.Info.Name;
637ece8a530Spatrick uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED;
638ece8a530Spatrick
639ece8a530Spatrick switch (sym.Info.Kind) {
640ece8a530Spatrick case WASM_SYMBOL_TYPE_FUNCTION:
641ece8a530Spatrick if (sym.isBindingLocal())
642ece8a530Spatrick return make<UndefinedFunction>(name, sym.Info.ImportName,
643ece8a530Spatrick sym.Info.ImportModule, flags, this,
644ece8a530Spatrick sym.Signature, isCalledDirectly);
645ece8a530Spatrick return symtab->addUndefinedFunction(name, sym.Info.ImportName,
646ece8a530Spatrick sym.Info.ImportModule, flags, this,
647ece8a530Spatrick sym.Signature, isCalledDirectly);
648ece8a530Spatrick case WASM_SYMBOL_TYPE_DATA:
649ece8a530Spatrick if (sym.isBindingLocal())
650ece8a530Spatrick return make<UndefinedData>(name, flags, this);
651ece8a530Spatrick return symtab->addUndefinedData(name, flags, this);
652ece8a530Spatrick case WASM_SYMBOL_TYPE_GLOBAL:
653ece8a530Spatrick if (sym.isBindingLocal())
654ece8a530Spatrick return make<UndefinedGlobal>(name, sym.Info.ImportName,
655ece8a530Spatrick sym.Info.ImportModule, flags, this,
656ece8a530Spatrick sym.GlobalType);
657ece8a530Spatrick return symtab->addUndefinedGlobal(name, sym.Info.ImportName,
658ece8a530Spatrick sym.Info.ImportModule, flags, this,
659ece8a530Spatrick sym.GlobalType);
6601cf9926bSpatrick case WASM_SYMBOL_TYPE_TABLE:
6611cf9926bSpatrick if (sym.isBindingLocal())
6621cf9926bSpatrick return make<UndefinedTable>(name, sym.Info.ImportName,
6631cf9926bSpatrick sym.Info.ImportModule, flags, this,
6641cf9926bSpatrick sym.TableType);
6651cf9926bSpatrick return symtab->addUndefinedTable(name, sym.Info.ImportName,
6661cf9926bSpatrick sym.Info.ImportModule, flags, this,
6671cf9926bSpatrick sym.TableType);
668*dfe94b16Srobert case WASM_SYMBOL_TYPE_TAG:
669*dfe94b16Srobert if (sym.isBindingLocal())
670*dfe94b16Srobert return make<UndefinedTag>(name, sym.Info.ImportName,
671*dfe94b16Srobert sym.Info.ImportModule, flags, this,
672*dfe94b16Srobert sym.Signature);
673*dfe94b16Srobert return symtab->addUndefinedTag(name, sym.Info.ImportName,
674*dfe94b16Srobert sym.Info.ImportModule, flags, this,
675*dfe94b16Srobert sym.Signature);
676ece8a530Spatrick case WASM_SYMBOL_TYPE_SECTION:
677ece8a530Spatrick llvm_unreachable("section symbols cannot be undefined");
678ece8a530Spatrick }
679ece8a530Spatrick llvm_unreachable("unknown symbol kind");
680ece8a530Spatrick }
681ece8a530Spatrick
682*dfe94b16Srobert
strip(StringRef s)683*dfe94b16Srobert StringRef strip(StringRef s) {
684*dfe94b16Srobert while (s.starts_with(" ")) {
685*dfe94b16Srobert s = s.drop_front();
686*dfe94b16Srobert }
687*dfe94b16Srobert while (s.ends_with(" ")) {
688*dfe94b16Srobert s = s.drop_back();
689*dfe94b16Srobert }
690*dfe94b16Srobert return s;
691*dfe94b16Srobert }
692*dfe94b16Srobert
parse()693*dfe94b16Srobert void StubFile::parse() {
694*dfe94b16Srobert bool first = true;
695*dfe94b16Srobert
696*dfe94b16Srobert SmallVector<StringRef> lines;
697*dfe94b16Srobert mb.getBuffer().split(lines, '\n');
698*dfe94b16Srobert for (StringRef line : lines) {
699*dfe94b16Srobert line = line.trim();
700*dfe94b16Srobert
701*dfe94b16Srobert // File must begin with #STUB
702*dfe94b16Srobert if (first) {
703*dfe94b16Srobert assert(line == "#STUB");
704*dfe94b16Srobert first = false;
705*dfe94b16Srobert }
706*dfe94b16Srobert
707*dfe94b16Srobert // Lines starting with # are considered comments
708*dfe94b16Srobert if (line.startswith("#"))
709*dfe94b16Srobert continue;
710*dfe94b16Srobert
711*dfe94b16Srobert StringRef sym;
712*dfe94b16Srobert StringRef rest;
713*dfe94b16Srobert std::tie(sym, rest) = line.split(':');
714*dfe94b16Srobert sym = strip(sym);
715*dfe94b16Srobert rest = strip(rest);
716*dfe94b16Srobert
717*dfe94b16Srobert symbolDependencies[sym] = {};
718*dfe94b16Srobert
719*dfe94b16Srobert while (rest.size()) {
720*dfe94b16Srobert StringRef dep;
721*dfe94b16Srobert std::tie(dep, rest) = rest.split(',');
722*dfe94b16Srobert dep = strip(dep);
723*dfe94b16Srobert symbolDependencies[sym].push_back(dep);
724*dfe94b16Srobert }
725*dfe94b16Srobert }
726*dfe94b16Srobert }
727*dfe94b16Srobert
parse()728ece8a530Spatrick void ArchiveFile::parse() {
729ece8a530Spatrick // Parse a MemoryBufferRef as an archive file.
730ece8a530Spatrick LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
731ece8a530Spatrick file = CHECK(Archive::create(mb), toString(this));
732ece8a530Spatrick
733ece8a530Spatrick // Read the symbol table to construct Lazy symbols.
734ece8a530Spatrick int count = 0;
735ece8a530Spatrick for (const Archive::Symbol &sym : file->symbols()) {
736ece8a530Spatrick symtab->addLazy(this, &sym);
737ece8a530Spatrick ++count;
738ece8a530Spatrick }
739ece8a530Spatrick LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n");
740*dfe94b16Srobert (void) count;
741ece8a530Spatrick }
742ece8a530Spatrick
addMember(const Archive::Symbol * sym)743ece8a530Spatrick void ArchiveFile::addMember(const Archive::Symbol *sym) {
744ece8a530Spatrick const Archive::Child &c =
745ece8a530Spatrick CHECK(sym->getMember(),
746ece8a530Spatrick "could not get the member for symbol " + sym->getName());
747ece8a530Spatrick
748ece8a530Spatrick // Don't try to load the same member twice (this can happen when members
749ece8a530Spatrick // mutually reference each other).
750ece8a530Spatrick if (!seen.insert(c.getChildOffset()).second)
751ece8a530Spatrick return;
752ece8a530Spatrick
753ece8a530Spatrick LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n");
754ece8a530Spatrick LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
755ece8a530Spatrick
756ece8a530Spatrick MemoryBufferRef mb =
757ece8a530Spatrick CHECK(c.getMemoryBufferRef(),
758ece8a530Spatrick "could not get the buffer for the member defining symbol " +
759ece8a530Spatrick sym->getName());
760ece8a530Spatrick
761*dfe94b16Srobert InputFile *obj = createObjectFile(mb, getName(), c.getChildOffset());
762ece8a530Spatrick symtab->addFile(obj);
763ece8a530Spatrick }
764ece8a530Spatrick
mapVisibility(GlobalValue::VisibilityTypes gvVisibility)765ece8a530Spatrick static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
766ece8a530Spatrick switch (gvVisibility) {
767ece8a530Spatrick case GlobalValue::DefaultVisibility:
768ece8a530Spatrick return WASM_SYMBOL_VISIBILITY_DEFAULT;
769ece8a530Spatrick case GlobalValue::HiddenVisibility:
770ece8a530Spatrick case GlobalValue::ProtectedVisibility:
771ece8a530Spatrick return WASM_SYMBOL_VISIBILITY_HIDDEN;
772ece8a530Spatrick }
773ece8a530Spatrick llvm_unreachable("unknown visibility");
774ece8a530Spatrick }
775ece8a530Spatrick
createBitcodeSymbol(const std::vector<bool> & keptComdats,const lto::InputFile::Symbol & objSym,BitcodeFile & f)776ece8a530Spatrick static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
777ece8a530Spatrick const lto::InputFile::Symbol &objSym,
778ece8a530Spatrick BitcodeFile &f) {
779*dfe94b16Srobert StringRef name = saver().save(objSym.getName());
780ece8a530Spatrick
781ece8a530Spatrick uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
782ece8a530Spatrick flags |= mapVisibility(objSym.getVisibility());
783ece8a530Spatrick
784ece8a530Spatrick int c = objSym.getComdatIndex();
785ece8a530Spatrick bool excludedByComdat = c != -1 && !keptComdats[c];
786ece8a530Spatrick
787ece8a530Spatrick if (objSym.isUndefined() || excludedByComdat) {
788ece8a530Spatrick flags |= WASM_SYMBOL_UNDEFINED;
789ece8a530Spatrick if (objSym.isExecutable())
790*dfe94b16Srobert return symtab->addUndefinedFunction(name, std::nullopt, std::nullopt,
791*dfe94b16Srobert flags, &f, nullptr, true);
792ece8a530Spatrick return symtab->addUndefinedData(name, flags, &f);
793ece8a530Spatrick }
794ece8a530Spatrick
795ece8a530Spatrick if (objSym.isExecutable())
796ece8a530Spatrick return symtab->addDefinedFunction(name, flags, &f, nullptr);
797ece8a530Spatrick return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0);
798ece8a530Spatrick }
799ece8a530Spatrick
BitcodeFile(MemoryBufferRef m,StringRef archiveName,uint64_t offsetInArchive)800*dfe94b16Srobert BitcodeFile::BitcodeFile(MemoryBufferRef m, StringRef archiveName,
801*dfe94b16Srobert uint64_t offsetInArchive)
802*dfe94b16Srobert : InputFile(BitcodeKind, m) {
803*dfe94b16Srobert this->archiveName = std::string(archiveName);
804*dfe94b16Srobert
805*dfe94b16Srobert std::string path = mb.getBufferIdentifier().str();
806*dfe94b16Srobert
807*dfe94b16Srobert // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
808*dfe94b16Srobert // name. If two archives define two members with the same name, this
809*dfe94b16Srobert // causes a collision which result in only one of the objects being taken
810*dfe94b16Srobert // into consideration at LTO time (which very likely causes undefined
811*dfe94b16Srobert // symbols later in the link stage). So we append file offset to make
812*dfe94b16Srobert // filename unique.
813*dfe94b16Srobert StringRef name = archiveName.empty()
814*dfe94b16Srobert ? saver().save(path)
815*dfe94b16Srobert : saver().save(archiveName + "(" + path::filename(path) +
816*dfe94b16Srobert " at " + utostr(offsetInArchive) + ")");
817*dfe94b16Srobert MemoryBufferRef mbref(mb.getBuffer(), name);
818*dfe94b16Srobert
819*dfe94b16Srobert obj = check(lto::InputFile::create(mbref));
820*dfe94b16Srobert
821*dfe94b16Srobert // If this isn't part of an archive, it's eagerly linked, so mark it live.
822*dfe94b16Srobert if (archiveName.empty())
823*dfe94b16Srobert markLive();
824*dfe94b16Srobert }
825*dfe94b16Srobert
826bb684c34Spatrick bool BitcodeFile::doneLTO = false;
827bb684c34Spatrick
parse()828ece8a530Spatrick void BitcodeFile::parse() {
829bb684c34Spatrick if (doneLTO) {
830bb684c34Spatrick error(toString(this) + ": attempt to add bitcode file after LTO.");
831bb684c34Spatrick return;
832bb684c34Spatrick }
833bb684c34Spatrick
834ece8a530Spatrick Triple t(obj->getTargetTriple());
8351cf9926bSpatrick if (!t.isWasm()) {
8361cf9926bSpatrick error(toString(this) + ": machine type must be wasm32 or wasm64");
837ece8a530Spatrick return;
838ece8a530Spatrick }
8391cf9926bSpatrick checkArch(t.getArch());
840ece8a530Spatrick std::vector<bool> keptComdats;
8411cf9926bSpatrick // TODO Support nodeduplicate https://bugs.llvm.org/show_bug.cgi?id=50531
8421cf9926bSpatrick for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable())
8431cf9926bSpatrick keptComdats.push_back(symtab->addComdat(s.first));
844ece8a530Spatrick
845ece8a530Spatrick for (const lto::InputFile::Symbol &objSym : obj->symbols())
846ece8a530Spatrick symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this));
847ece8a530Spatrick }
848ece8a530Spatrick
849ece8a530Spatrick } // namespace wasm
850ece8a530Spatrick } // namespace lld
851