1c94d393aSSam Clegg //===- InputFiles.cpp -----------------------------------------------------===//
2c94d393aSSam Clegg //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6c94d393aSSam Clegg //
7c94d393aSSam Clegg //===----------------------------------------------------------------------===//
8c94d393aSSam Clegg
9c94d393aSSam Clegg #include "InputFiles.h"
10c94d393aSSam Clegg #include "Config.h"
115fa274beSSam Clegg #include "InputChunks.h"
12a56e5749SAndy Wingo #include "InputElement.h"
13a28a4662SSam Clegg #include "OutputSegment.h"
14c94d393aSSam Clegg #include "SymbolTable.h"
1583d59e05SAlexandre Ganea #include "lld/Common/CommonLinkerContext.h"
1635150bb5SRui Ueyama #include "lld/Common/Reproduce.h"
17c94d393aSSam Clegg #include "llvm/Object/Binary.h"
18c94d393aSSam Clegg #include "llvm/Object/Wasm.h"
1928848e9eSSam Clegg #include "llvm/Support/Path.h"
2035150bb5SRui Ueyama #include "llvm/Support/TarWriter.h"
21c94d393aSSam Clegg #include "llvm/Support/raw_ostream.h"
22c94d393aSSam Clegg
23c94d393aSSam Clegg #define DEBUG_TYPE "lld"
24c94d393aSSam Clegg
25c94d393aSSam Clegg using namespace llvm;
26c94d393aSSam Clegg using namespace llvm::object;
27c94d393aSSam Clegg using namespace llvm::wasm;
2828848e9eSSam Clegg using namespace llvm::sys;
29c94d393aSSam Clegg
3033c59abfSFangrui Song namespace lld {
3135150bb5SRui Ueyama
3233c59abfSFangrui Song // Returns a string in the format of "foo.o" or "foo.a(bar.o)".
toString(const wasm::InputFile * file)3333c59abfSFangrui Song std::string toString(const wasm::InputFile *file) {
3433c59abfSFangrui Song if (!file)
3533c59abfSFangrui Song return "<internal>";
3633c59abfSFangrui Song
3733c59abfSFangrui Song if (file->archiveName.empty())
38adcd0268SBenjamin Kramer return std::string(file->getName());
3933c59abfSFangrui Song
4033c59abfSFangrui Song return (file->archiveName + "(" + file->getName() + ")").str();
4133c59abfSFangrui Song }
4233c59abfSFangrui Song
4333c59abfSFangrui Song namespace wasm {
44b8c2d60dSWouter van Oortmerssen
checkArch(Triple::ArchType arch) const45b8c2d60dSWouter van Oortmerssen void InputFile::checkArch(Triple::ArchType arch) const {
46b8c2d60dSWouter van Oortmerssen bool is64 = arch == Triple::wasm64;
47*5413bf1bSKazu Hirata if (is64 && !config->is64) {
48b8c2d60dSWouter van Oortmerssen fatal(toString(this) +
49b8c2d60dSWouter van Oortmerssen ": must specify -mwasm64 to process wasm64 object files");
50757d9d22SKazu Hirata } else if (config->is64.value_or(false) != is64) {
51b8c2d60dSWouter van Oortmerssen fatal(toString(this) +
52b8c2d60dSWouter van Oortmerssen ": wasm32 object file can't be linked in wasm64 mode");
53b8c2d60dSWouter van Oortmerssen }
54b8c2d60dSWouter van Oortmerssen }
55b8c2d60dSWouter van Oortmerssen
5633c59abfSFangrui Song std::unique_ptr<llvm::TarWriter> tar;
5733c59abfSFangrui Song
readFile(StringRef path)5833c59abfSFangrui Song Optional<MemoryBufferRef> readFile(StringRef path) {
59136d27abSRui Ueyama log("Loading: " + path);
60c94d393aSSam Clegg
61136d27abSRui Ueyama auto mbOrErr = MemoryBuffer::getFile(path);
62136d27abSRui Ueyama if (auto ec = mbOrErr.getError()) {
63136d27abSRui Ueyama error("cannot open " + path + ": " + ec.message());
64c94d393aSSam Clegg return None;
65c94d393aSSam Clegg }
66136d27abSRui Ueyama std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
67136d27abSRui Ueyama MemoryBufferRef mbref = mb->getMemBufferRef();
68136d27abSRui Ueyama make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
69c94d393aSSam Clegg
70136d27abSRui Ueyama if (tar)
71136d27abSRui Ueyama tar->append(relativeToRoot(path), mbref.getBuffer());
72136d27abSRui Ueyama return mbref;
73c94d393aSSam Clegg }
74c94d393aSSam Clegg
createObjectFile(MemoryBufferRef mb,StringRef archiveName,uint64_t offsetInArchive)7528848e9eSSam Clegg InputFile *createObjectFile(MemoryBufferRef mb, StringRef archiveName,
7628848e9eSSam Clegg uint64_t offsetInArchive) {
77136d27abSRui Ueyama file_magic magic = identify_magic(mb.getBuffer());
78136d27abSRui Ueyama if (magic == file_magic::wasm_object) {
79136d27abSRui Ueyama std::unique_ptr<Binary> bin =
80136d27abSRui Ueyama CHECK(createBinary(mb), mb.getBufferIdentifier());
81136d27abSRui Ueyama auto *obj = cast<WasmObjectFile>(bin.get());
82136d27abSRui Ueyama if (obj->isSharedObject())
83136d27abSRui Ueyama return make<SharedFile>(mb);
84136d27abSRui Ueyama return make<ObjFile>(mb, archiveName);
85a688a42cSSam Clegg }
868adf7ac5SSam Clegg
87136d27abSRui Ueyama if (magic == file_magic::bitcode)
8828848e9eSSam Clegg return make<BitcodeFile>(mb, archiveName, offsetInArchive);
898adf7ac5SSam Clegg
901cf6ebc0SSam Clegg std::string name = mb.getBufferIdentifier().str();
911cf6ebc0SSam Clegg if (!archiveName.empty()) {
921cf6ebc0SSam Clegg name = archiveName.str() + "(" + name + ")";
931cf6ebc0SSam Clegg }
941cf6ebc0SSam Clegg
951cf6ebc0SSam Clegg fatal("unknown file type: " + name);
968adf7ac5SSam Clegg }
978adf7ac5SSam Clegg
98c1be8230SSam Clegg // Relocations contain either symbol or type indices. This function takes a
99c1be8230SSam Clegg // relocation and returns relocated index (i.e. translates from the input
1006f4286fbSHeejin Ahn // symbol/type space to the output symbol/type space).
calcNewIndex(const WasmRelocation & reloc) const101136d27abSRui Ueyama uint32_t ObjFile::calcNewIndex(const WasmRelocation &reloc) const {
102136d27abSRui Ueyama if (reloc.Type == R_WASM_TYPE_INDEX_LEB) {
103136d27abSRui Ueyama assert(typeIsUsed[reloc.Index]);
104136d27abSRui Ueyama return typeMap[reloc.Index];
105d1063bb9SRui Ueyama }
106136d27abSRui Ueyama const Symbol *sym = symbols[reloc.Index];
107136d27abSRui Ueyama if (auto *ss = dyn_cast<SectionSymbol>(sym))
108136d27abSRui Ueyama sym = ss->getOutputSectionSymbol();
109136d27abSRui Ueyama return sym->getOutputSymbolIndex();
110d96d9357SSam Clegg }
111d96d9357SSam Clegg
112d177ab2aSSam Clegg // Relocations can contain addend for combined sections. This function takes a
113d177ab2aSSam Clegg // relocation and returns updated addend by offset in the output section.
calcNewAddend(const WasmRelocation & reloc) const1144c75521cSSam Clegg int64_t ObjFile::calcNewAddend(const WasmRelocation &reloc) const {
115136d27abSRui Ueyama switch (reloc.Type) {
11679e33171SSam Clegg case R_WASM_MEMORY_ADDR_LEB:
1173b29376eSWouter van Oortmerssen case R_WASM_MEMORY_ADDR_LEB64:
1183b29376eSWouter van Oortmerssen case R_WASM_MEMORY_ADDR_SLEB64:
11979e33171SSam Clegg case R_WASM_MEMORY_ADDR_SLEB:
1205bb0dcd9SKeno Fischer case R_WASM_MEMORY_ADDR_REL_SLEB:
1213b29376eSWouter van Oortmerssen case R_WASM_MEMORY_ADDR_REL_SLEB64:
12279e33171SSam Clegg case R_WASM_MEMORY_ADDR_I32:
1233b29376eSWouter van Oortmerssen case R_WASM_MEMORY_ADDR_I64:
12407b6aeb5SSam Clegg case R_WASM_MEMORY_ADDR_TLS_SLEB:
125670944fbSWouter van Oortmerssen case R_WASM_MEMORY_ADDR_TLS_SLEB64:
12679e33171SSam Clegg case R_WASM_FUNCTION_OFFSET_I32:
12716f02431SWouter van Oortmerssen case R_WASM_FUNCTION_OFFSET_I64:
128aa0c571aSYuta Saito case R_WASM_MEMORY_ADDR_LOCREL_I32:
129136d27abSRui Ueyama return reloc.Addend;
13079e33171SSam Clegg case R_WASM_SECTION_OFFSET_I32:
13114ffbb84SSam Clegg return getSectionSymbol(reloc.Index)->section->getOffset(reloc.Addend);
132d177ab2aSSam Clegg default:
133d177ab2aSSam Clegg llvm_unreachable("unexpected relocation type");
134d177ab2aSSam Clegg }
135d177ab2aSSam Clegg }
136d177ab2aSSam Clegg
137ab604a98SSam Clegg // Translate from the relocation's index into the final linked output value.
calcNewValue(const WasmRelocation & reloc,uint64_t tombstone,const InputChunk * chunk) const138aa0c571aSYuta Saito uint64_t ObjFile::calcNewValue(const WasmRelocation &reloc, uint64_t tombstone,
139aa0c571aSYuta Saito const InputChunk *chunk) const {
140136d27abSRui Ueyama const Symbol* sym = nullptr;
141136d27abSRui Ueyama if (reloc.Type != R_WASM_TYPE_INDEX_LEB) {
142136d27abSRui Ueyama sym = symbols[reloc.Index];
1437cdec273SSam Clegg
1447cdec273SSam Clegg // We can end up with relocations against non-live symbols. For example
1458b8088acSEric Leese // in debug sections. We return a tombstone value in debug symbol sections
1468b8088acSEric Leese // so this will not produce a valid range conflicting with ranges of actual
1478b8088acSEric Leese // code. In other sections we return reloc.Addend.
1488b8088acSEric Leese
1493e7bc0daSSam Clegg if (!isa<SectionSymbol>(sym) && !sym->isLive())
1508b8088acSEric Leese return tombstone ? tombstone : reloc.Addend;
1517cdec273SSam Clegg }
1527cdec273SSam Clegg
153136d27abSRui Ueyama switch (reloc.Type) {
15479e33171SSam Clegg case R_WASM_TABLE_INDEX_I32:
155cc1b9b68SWouter van Oortmerssen case R_WASM_TABLE_INDEX_I64:
15679e33171SSam Clegg case R_WASM_TABLE_INDEX_SLEB:
157cc1b9b68SWouter van Oortmerssen case R_WASM_TABLE_INDEX_SLEB64:
1583a293cbfSWouter van Oortmerssen case R_WASM_TABLE_INDEX_REL_SLEB:
1593a293cbfSWouter van Oortmerssen case R_WASM_TABLE_INDEX_REL_SLEB64: {
160cf2b8722SSam Clegg if (!getFunctionSymbol(reloc.Index)->hasTableIndex())
161ea38ac5bSSam Clegg return 0;
162937b9558SSam Clegg uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex();
1633a293cbfSWouter van Oortmerssen if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB ||
1643a293cbfSWouter van Oortmerssen reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB64)
165937b9558SSam Clegg index -= config->tableBase;
166937b9558SSam Clegg return index;
167937b9558SSam Clegg }
16879e33171SSam Clegg case R_WASM_MEMORY_ADDR_LEB:
1693b29376eSWouter van Oortmerssen case R_WASM_MEMORY_ADDR_LEB64:
1703b29376eSWouter van Oortmerssen case R_WASM_MEMORY_ADDR_SLEB:
1713b29376eSWouter van Oortmerssen case R_WASM_MEMORY_ADDR_SLEB64:
1722a7cac93SSam Clegg case R_WASM_MEMORY_ADDR_REL_SLEB:
1733b29376eSWouter van Oortmerssen case R_WASM_MEMORY_ADDR_REL_SLEB64:
1743b29376eSWouter van Oortmerssen case R_WASM_MEMORY_ADDR_I32:
175aa0c571aSYuta Saito case R_WASM_MEMORY_ADDR_I64:
176fad05465SSam Clegg case R_WASM_MEMORY_ADDR_TLS_SLEB:
177fad05465SSam Clegg case R_WASM_MEMORY_ADDR_TLS_SLEB64:
178aa0c571aSYuta Saito case R_WASM_MEMORY_ADDR_LOCREL_I32: {
1796c393e9dSSam Clegg if (isa<UndefinedData>(sym) || sym->isUndefWeak())
1809abe8c48SSam Clegg return 0;
181a28a4662SSam Clegg auto D = cast<DefinedData>(sym);
18219cedd3cSSam Clegg uint64_t value = D->getVA() + reloc.Addend;
183aa0c571aSYuta Saito if (reloc.Type == R_WASM_MEMORY_ADDR_LOCREL_I32) {
184aa0c571aSYuta Saito const auto *segment = cast<InputSegment>(chunk);
185aa0c571aSYuta Saito uint64_t p = segment->outputSeg->startVA + segment->outputSegmentOffset +
186aa0c571aSYuta Saito reloc.Offset - segment->getInputSectionOffset();
187aa0c571aSYuta Saito value -= p;
188aa0c571aSYuta Saito }
189aa0c571aSYuta Saito return value;
190a28a4662SSam Clegg }
19179e33171SSam Clegg case R_WASM_TYPE_INDEX_LEB:
192136d27abSRui Ueyama return typeMap[reloc.Index];
19379e33171SSam Clegg case R_WASM_FUNCTION_INDEX_LEB:
194136d27abSRui Ueyama return getFunctionSymbol(reloc.Index)->getFunctionIndex();
1957cdec273SSam Clegg case R_WASM_GLOBAL_INDEX_LEB:
19648139ebcSWouter van Oortmerssen case R_WASM_GLOBAL_INDEX_I32:
197136d27abSRui Ueyama if (auto gs = dyn_cast<GlobalSymbol>(sym))
198136d27abSRui Ueyama return gs->getGlobalIndex();
199136d27abSRui Ueyama return sym->getGOTIndex();
2001d891d44SHeejin Ahn case R_WASM_TAG_INDEX_LEB:
2011d891d44SHeejin Ahn return getTagSymbol(reloc.Index)->getTagIndex();
20216f02431SWouter van Oortmerssen case R_WASM_FUNCTION_OFFSET_I32:
20316f02431SWouter van Oortmerssen case R_WASM_FUNCTION_OFFSET_I64: {
2046f5c5cbeSSam Clegg if (isa<UndefinedFunction>(sym)) {
2056f5c5cbeSSam Clegg return tombstone ? tombstone : reloc.Addend;
2066f5c5cbeSSam Clegg }
207136d27abSRui Ueyama auto *f = cast<DefinedFunction>(sym);
20814ffbb84SSam Clegg return f->function->getOffset(f->function->getFunctionCodeOffset() +
20914ffbb84SSam Clegg reloc.Addend);
210d177ab2aSSam Clegg }
21179e33171SSam Clegg case R_WASM_SECTION_OFFSET_I32:
21214ffbb84SSam Clegg return getSectionSymbol(reloc.Index)->section->getOffset(reloc.Addend);
21353e3b81fSAndy Wingo case R_WASM_TABLE_NUMBER_LEB:
21453e3b81fSAndy Wingo return getTableSymbol(reloc.Index)->getTableNumber();
215ab604a98SSam Clegg default:
216ab604a98SSam Clegg llvm_unreachable("unknown relocation type");
217ab604a98SSam Clegg }
218ab604a98SSam Clegg }
219ab604a98SSam Clegg
22047078f56SSam Clegg template <class T>
setRelocs(const std::vector<T * > & chunks,const WasmSection * section)221136d27abSRui Ueyama static void setRelocs(const std::vector<T *> &chunks,
222136d27abSRui Ueyama const WasmSection *section) {
223136d27abSRui Ueyama if (!section)
22447078f56SSam Clegg return;
22547078f56SSam Clegg
226136d27abSRui Ueyama ArrayRef<WasmRelocation> relocs = section->Relocations;
2271647ff6eSGeorgii Rymar assert(llvm::is_sorted(
2281647ff6eSGeorgii Rymar relocs, [](const WasmRelocation &r1, const WasmRelocation &r2) {
229136d27abSRui Ueyama return r1.Offset < r2.Offset;
23047078f56SSam Clegg }));
2311647ff6eSGeorgii Rymar assert(llvm::is_sorted(chunks, [](InputChunk *c1, InputChunk *c2) {
232136d27abSRui Ueyama return c1->getInputSectionOffset() < c2->getInputSectionOffset();
23347078f56SSam Clegg }));
23447078f56SSam Clegg
235136d27abSRui Ueyama auto relocsNext = relocs.begin();
236136d27abSRui Ueyama auto relocsEnd = relocs.end();
237136d27abSRui Ueyama auto relocLess = [](const WasmRelocation &r, uint32_t val) {
238136d27abSRui Ueyama return r.Offset < val;
23947078f56SSam Clegg };
240136d27abSRui Ueyama for (InputChunk *c : chunks) {
241136d27abSRui Ueyama auto relocsStart = std::lower_bound(relocsNext, relocsEnd,
242136d27abSRui Ueyama c->getInputSectionOffset(), relocLess);
243136d27abSRui Ueyama relocsNext = std::lower_bound(
244136d27abSRui Ueyama relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(),
245136d27abSRui Ueyama relocLess);
246136d27abSRui Ueyama c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext));
24747078f56SSam Clegg }
24847078f56SSam Clegg }
24947078f56SSam Clegg
2504fc25573SAndy Wingo // An object file can have two approaches to tables. With the reference-types
2514fc25573SAndy Wingo // feature enabled, input files that define or use tables declare the tables
2524fc25573SAndy Wingo // using symbols, and record each use with a relocation. This way when the
2534fc25573SAndy Wingo // linker combines inputs, it can collate the tables used by the inputs,
2544fc25573SAndy Wingo // assigning them distinct table numbers, and renumber all the uses as
2554fc25573SAndy Wingo // appropriate. At the same time, the linker has special logic to build the
25663393828SAndy Wingo // indirect function table if it is needed.
25763393828SAndy Wingo //
2584fc25573SAndy Wingo // However, MVP object files (those that target WebAssembly 1.0, the "minimum
2594fc25573SAndy Wingo // viable product" version of WebAssembly) neither write table symbols nor
2604fc25573SAndy Wingo // record relocations. These files can have at most one table, the indirect
2614fc25573SAndy Wingo // function table used by call_indirect and which is the address space for
2624fc25573SAndy Wingo // function pointers. If this table is present, it is always an import. If we
2634fc25573SAndy Wingo // have a file with a table import but no table symbols, it is an MVP object
2644fc25573SAndy Wingo // file. synthesizeMVPIndirectFunctionTableSymbolIfNeeded serves as a shim when
2654fc25573SAndy Wingo // loading these input files, defining the missing symbol to allow the indirect
2664fc25573SAndy Wingo // function table to be built.
26763393828SAndy Wingo //
2684fc25573SAndy Wingo // As indirect function table table usage in MVP objects cannot be relocated,
2694fc25573SAndy Wingo // the linker must ensure that this table gets assigned index zero.
addLegacyIndirectFunctionTableIfNeeded(uint32_t tableSymbolCount)2704fc25573SAndy Wingo void ObjFile::addLegacyIndirectFunctionTableIfNeeded(
2714fc25573SAndy Wingo uint32_t tableSymbolCount) {
2724fc25573SAndy Wingo uint32_t tableCount = wasmObj->getNumImportedTables() + tables.size();
2734fc25573SAndy Wingo
2744fc25573SAndy Wingo // If there are symbols for all tables, then all is good.
2754fc25573SAndy Wingo if (tableCount == tableSymbolCount)
2764fc25573SAndy Wingo return;
2774fc25573SAndy Wingo
2784fc25573SAndy Wingo // It's possible for an input to define tables and also use the indirect
2794fc25573SAndy Wingo // function table, but forget to compile with -mattr=+reference-types.
2804fc25573SAndy Wingo // For these newer files, we require symbols for all tables, and
2814fc25573SAndy Wingo // relocations for all of their uses.
2824fc25573SAndy Wingo if (tableSymbolCount != 0) {
2834fc25573SAndy Wingo error(toString(this) +
2844fc25573SAndy Wingo ": expected one symbol table entry for each of the " +
2854fc25573SAndy Wingo Twine(tableCount) + " table(s) present, but got " +
2864fc25573SAndy Wingo Twine(tableSymbolCount) + " symbol(s) instead.");
2874fc25573SAndy Wingo return;
2884fc25573SAndy Wingo }
2894fc25573SAndy Wingo
2904fc25573SAndy Wingo // An MVP object file can have up to one table import, for the indirect
2914fc25573SAndy Wingo // function table, but will have no table definitions.
2924fc25573SAndy Wingo if (tables.size()) {
2934fc25573SAndy Wingo error(toString(this) +
2944fc25573SAndy Wingo ": unexpected table definition(s) without corresponding "
2954fc25573SAndy Wingo "symbol-table entries.");
2964fc25573SAndy Wingo return;
2974fc25573SAndy Wingo }
2984fc25573SAndy Wingo
2994fc25573SAndy Wingo // An MVP object file can have only one table import.
3004fc25573SAndy Wingo if (tableCount != 1) {
3014fc25573SAndy Wingo error(toString(this) +
3024fc25573SAndy Wingo ": multiple table imports, but no corresponding symbol-table "
3034fc25573SAndy Wingo "entries.");
3044fc25573SAndy Wingo return;
3054fc25573SAndy Wingo }
3064fc25573SAndy Wingo
3074fc25573SAndy Wingo const WasmImport *tableImport = nullptr;
3084fc25573SAndy Wingo for (const auto &import : wasmObj->imports()) {
3094fc25573SAndy Wingo if (import.Kind == WASM_EXTERNAL_TABLE) {
3104fc25573SAndy Wingo assert(!tableImport);
3114fc25573SAndy Wingo tableImport = &import;
3124fc25573SAndy Wingo }
3134fc25573SAndy Wingo }
3144fc25573SAndy Wingo assert(tableImport);
3154fc25573SAndy Wingo
3164fc25573SAndy Wingo // We can only synthesize a symtab entry for the indirect function table; if
3174fc25573SAndy Wingo // it has an unexpected name or type, assume that it's not actually the
3184fc25573SAndy Wingo // indirect function table.
3194fc25573SAndy Wingo if (tableImport->Field != functionTableName ||
3204fc25573SAndy Wingo tableImport->Table.ElemType != uint8_t(ValType::FUNCREF)) {
3214fc25573SAndy Wingo error(toString(this) + ": table import " + Twine(tableImport->Field) +
3224fc25573SAndy Wingo " is missing a symbol table entry.");
3234fc25573SAndy Wingo return;
3244fc25573SAndy Wingo }
3254fc25573SAndy Wingo
3264fc25573SAndy Wingo auto *info = make<WasmSymbolInfo>();
3274fc25573SAndy Wingo info->Name = tableImport->Field;
3284fc25573SAndy Wingo info->Kind = WASM_SYMBOL_TYPE_TABLE;
3294fc25573SAndy Wingo info->ImportModule = tableImport->Module;
3304fc25573SAndy Wingo info->ImportName = tableImport->Field;
3314fc25573SAndy Wingo info->Flags = WASM_SYMBOL_UNDEFINED;
3324fc25573SAndy Wingo info->Flags |= WASM_SYMBOL_NO_STRIP;
3334fc25573SAndy Wingo info->ElementIndex = 0;
3344fc25573SAndy Wingo LLVM_DEBUG(dbgs() << "Synthesizing symbol for table import: " << info->Name
3354fc25573SAndy Wingo << "\n");
33663393828SAndy Wingo const WasmGlobalType *globalType = nullptr;
33763393828SAndy Wingo const WasmSignature *signature = nullptr;
3383ec1760dSHeejin Ahn auto *wasmSym =
3393ec1760dSHeejin Ahn make<WasmSymbol>(*info, globalType, &tableImport->Table, signature);
3404fc25573SAndy Wingo Symbol *sym = createUndefined(*wasmSym, false);
3414fc25573SAndy Wingo // We're only sure it's a TableSymbol if the createUndefined succeeded.
3424fc25573SAndy Wingo if (errorCount())
3434fc25573SAndy Wingo return;
3444fc25573SAndy Wingo symbols.push_back(sym);
3454fc25573SAndy Wingo // Because there are no TABLE_NUMBER relocs, we can't compute accurate
3464fc25573SAndy Wingo // liveness info; instead, just mark the symbol as always live.
3474fc25573SAndy Wingo sym->markLive();
3484fc25573SAndy Wingo
3494fc25573SAndy Wingo // We assume that this compilation unit has unrelocatable references to
3504fc25573SAndy Wingo // this table.
3514fc25573SAndy Wingo config->legacyFunctionTable = true;
35263393828SAndy Wingo }
35363393828SAndy Wingo
shouldMerge(const WasmSection & sec)35445b7cf99SSam Clegg static bool shouldMerge(const WasmSection &sec) {
35545b7cf99SSam Clegg if (config->optimize == 0)
35645b7cf99SSam Clegg return false;
35745b7cf99SSam Clegg // Sadly we don't have section attributes yet for custom sections, so we
35845b7cf99SSam Clegg // currently go by the name alone.
35945b7cf99SSam Clegg // TODO(sbc): Add ability for wasm sections to carry flags so we don't
36045b7cf99SSam Clegg // need to use names here.
361c1a59fa5SSam Clegg // For now, keep in sync with uses of wasm::WASM_SEG_FLAG_STRINGS in
362c1a59fa5SSam Clegg // MCObjectFileInfo::initWasmMCObjectFileInfo which creates these custom
363c1a59fa5SSam Clegg // sections.
364c1a59fa5SSam Clegg return sec.Name == ".debug_str" || sec.Name == ".debug_str.dwo" ||
365c1a59fa5SSam Clegg sec.Name == ".debug_line_str";
36645b7cf99SSam Clegg }
36745b7cf99SSam Clegg
shouldMerge(const WasmSegment & seg)3683b8d2be5SSam Clegg static bool shouldMerge(const WasmSegment &seg) {
3693b8d2be5SSam Clegg // As of now we only support merging strings, and only with single byte
3703b8d2be5SSam Clegg // alignment (2^0).
3713b8d2be5SSam Clegg if (!(seg.Data.LinkingFlags & WASM_SEG_FLAG_STRINGS) ||
3723b8d2be5SSam Clegg (seg.Data.Alignment != 0))
3733b8d2be5SSam Clegg return false;
3743b8d2be5SSam Clegg
3753b8d2be5SSam Clegg // On a regular link we don't merge sections if -O0 (default is -O1). This
3763b8d2be5SSam Clegg // sometimes makes the linker significantly faster, although the output will
3773b8d2be5SSam Clegg // be bigger.
3783b8d2be5SSam Clegg if (config->optimize == 0)
3793b8d2be5SSam Clegg return false;
3803b8d2be5SSam Clegg
3813b8d2be5SSam Clegg // A mergeable section with size 0 is useless because they don't have
3823b8d2be5SSam Clegg // any data to merge. A mergeable string section with size 0 can be
3833b8d2be5SSam Clegg // argued as invalid because it doesn't end with a null character.
3843b8d2be5SSam Clegg // We'll avoid a mess by handling them as if they were non-mergeable.
3853b8d2be5SSam Clegg if (seg.Data.Content.size() == 0)
3863b8d2be5SSam Clegg return false;
3873b8d2be5SSam Clegg
3883b8d2be5SSam Clegg return true;
3893b8d2be5SSam Clegg }
3903b8d2be5SSam Clegg
parse(bool ignoreComdats)391136d27abSRui Ueyama void ObjFile::parse(bool ignoreComdats) {
392c94d393aSSam Clegg // Parse a memory buffer as a wasm file.
393e7245b42SNicola Zaghen LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
394136d27abSRui Ueyama std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this));
395c94d393aSSam Clegg
396136d27abSRui Ueyama auto *obj = dyn_cast<WasmObjectFile>(bin.get());
397136d27abSRui Ueyama if (!obj)
398c94d393aSSam Clegg fatal(toString(this) + ": not a wasm file");
399136d27abSRui Ueyama if (!obj->isRelocatableObject())
400c94d393aSSam Clegg fatal(toString(this) + ": not a relocatable wasm file");
401c94d393aSSam Clegg
402136d27abSRui Ueyama bin.release();
403136d27abSRui Ueyama wasmObj.reset(obj);
404c94d393aSSam Clegg
405b8c2d60dSWouter van Oortmerssen checkArch(obj->getArch());
406b8c2d60dSWouter van Oortmerssen
407dbd33b80SSam Clegg // Build up a map of function indices to table indices for use when
408dbd33b80SSam Clegg // verifying the existing table index relocations
409136d27abSRui Ueyama uint32_t totalFunctions =
410136d27abSRui Ueyama wasmObj->getNumImportedFunctions() + wasmObj->functions().size();
41181443ac1SSam Clegg tableEntriesRel.resize(totalFunctions);
412136d27abSRui Ueyama tableEntries.resize(totalFunctions);
413136d27abSRui Ueyama for (const WasmElemSegment &seg : wasmObj->elements()) {
4143b29376eSWouter van Oortmerssen int64_t offset;
4159504ab32SSam Clegg if (seg.Offset.Extended)
4169504ab32SSam Clegg fatal(toString(this) + ": extended init exprs not supported");
4179504ab32SSam Clegg else if (seg.Offset.Inst.Opcode == WASM_OPCODE_I32_CONST)
4189504ab32SSam Clegg offset = seg.Offset.Inst.Value.Int32;
4199504ab32SSam Clegg else if (seg.Offset.Inst.Opcode == WASM_OPCODE_I64_CONST)
4209504ab32SSam Clegg offset = seg.Offset.Inst.Value.Int64;
4213b29376eSWouter van Oortmerssen else
422dbd33b80SSam Clegg fatal(toString(this) + ": invalid table elements");
4233b29376eSWouter van Oortmerssen for (size_t index = 0; index < seg.Functions.size(); index++) {
4243b29376eSWouter van Oortmerssen auto functionIndex = seg.Functions[index];
42581443ac1SSam Clegg tableEntriesRel[functionIndex] = index;
426136d27abSRui Ueyama tableEntries[functionIndex] = offset + index;
427dbd33b80SSam Clegg }
428dbd33b80SSam Clegg }
429dbd33b80SSam Clegg
430dd6412c0SDerek Schuff ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats;
431dd6412c0SDerek Schuff for (StringRef comdat : comdats) {
432dd6412c0SDerek Schuff bool isNew = ignoreComdats || symtab->addComdat(comdat);
433dd6412c0SDerek Schuff keptComdats.push_back(isNew);
434dd6412c0SDerek Schuff }
435dd6412c0SDerek Schuff
436136d27abSRui Ueyama uint32_t sectionIndex = 0;
43756e970d4SSam Clegg
43856e970d4SSam Clegg // Bool for each symbol, true if called directly. This allows us to implement
43956e970d4SSam Clegg // a weaker form of signature checking where undefined functions that are not
44056e970d4SSam Clegg // called directly (i.e. only address taken) don't have to match the defined
44156e970d4SSam Clegg // function's signature. We cannot do this for directly called functions
44256e970d4SSam Clegg // because those signatures are checked at validation times.
44356e970d4SSam Clegg // See https://bugs.llvm.org/show_bug.cgi?id=40412
444136d27abSRui Ueyama std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false);
445136d27abSRui Ueyama for (const SectionRef &sec : wasmObj->sections()) {
446136d27abSRui Ueyama const WasmSection §ion = wasmObj->getWasmSection(sec);
44759f959ffSSam Clegg // Wasm objects can have at most one code and one data section.
448136d27abSRui Ueyama if (section.Type == WASM_SEC_CODE) {
449136d27abSRui Ueyama assert(!codeSection);
450136d27abSRui Ueyama codeSection = §ion;
451136d27abSRui Ueyama } else if (section.Type == WASM_SEC_DATA) {
452136d27abSRui Ueyama assert(!dataSection);
453136d27abSRui Ueyama dataSection = §ion;
454136d27abSRui Ueyama } else if (section.Type == WASM_SEC_CUSTOM) {
45545b7cf99SSam Clegg InputChunk *customSec;
45645b7cf99SSam Clegg if (shouldMerge(section))
45745b7cf99SSam Clegg customSec = make<MergeInputChunk>(section, this);
45845b7cf99SSam Clegg else
45945b7cf99SSam Clegg customSec = make<InputSection>(section, this);
460dd6412c0SDerek Schuff customSec->discarded = isExcludedByComdat(customSec);
461dd6412c0SDerek Schuff customSections.emplace_back(customSec);
462136d27abSRui Ueyama customSections.back()->setRelocations(section.Relocations);
463136d27abSRui Ueyama customSectionsByIndex[sectionIndex] = customSections.back();
464d177ab2aSSam Clegg }
465136d27abSRui Ueyama sectionIndex++;
4667ae3d335SKazuaki Ishizaki // Scans relocations to determine if a function symbol is called directly.
467136d27abSRui Ueyama for (const WasmRelocation &reloc : section.Relocations)
468136d27abSRui Ueyama if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB)
469136d27abSRui Ueyama isCalledDirectly[reloc.Index] = true;
470c94d393aSSam Clegg }
471c94d393aSSam Clegg
472136d27abSRui Ueyama typeMap.resize(getWasmObj()->types().size());
473136d27abSRui Ueyama typeIsUsed.resize(getWasmObj()->types().size(), false);
4748f6d2defSSam Clegg
475c4d9aa1bSNicholas Wilson
4760a9583ceSRui Ueyama // Populate `Segments`.
477136d27abSRui Ueyama for (const WasmSegment &s : wasmObj->dataSegments()) {
4785a9b25e1SSam Clegg InputChunk *seg;
479875ee937SSam Clegg if (shouldMerge(s))
48045b7cf99SSam Clegg seg = make<MergeInputChunk>(s, this);
481875ee937SSam Clegg else
48245b7cf99SSam Clegg seg = make<InputSegment>(s, this);
483136d27abSRui Ueyama seg->discarded = isExcludedByComdat(seg);
48444177e5fSSam Clegg // Older object files did not include WASM_SEG_FLAG_TLS and instead
48544177e5fSSam Clegg // relied on the naming convention. To maintain compat with such objects
48644177e5fSSam Clegg // we still imply the TLS flag based on the name of the segment.
48744177e5fSSam Clegg if (!seg->isTLS() &&
488875ee937SSam Clegg (seg->name.startswith(".tdata") || seg->name.startswith(".tbss")))
48944177e5fSSam Clegg seg->flags |= WASM_SEG_FLAG_TLS;
490136d27abSRui Ueyama segments.emplace_back(seg);
491fd54fa5dSSam Clegg }
492136d27abSRui Ueyama setRelocs(segments, dataSection);
493c94d393aSSam Clegg
4940a9583ceSRui Ueyama // Populate `Functions`.
495136d27abSRui Ueyama ArrayRef<WasmFunction> funcs = wasmObj->functions();
496136d27abSRui Ueyama ArrayRef<WasmSignature> types = wasmObj->types();
497136d27abSRui Ueyama functions.reserve(funcs.size());
4980a9583ceSRui Ueyama
499c0039de2SSam Clegg for (auto &f : funcs) {
500c0039de2SSam Clegg auto *func = make<InputFunction>(types[f.SigIndex], &f, this);
501136d27abSRui Ueyama func->discarded = isExcludedByComdat(func);
502136d27abSRui Ueyama functions.emplace_back(func);
503fd54fa5dSSam Clegg }
504136d27abSRui Ueyama setRelocs(functions, codeSection);
5058d146bbcSSam Clegg
50653e3b81fSAndy Wingo // Populate `Tables`.
50753e3b81fSAndy Wingo for (const WasmTable &t : wasmObj->tables())
50853e3b81fSAndy Wingo tables.emplace_back(make<InputTable>(t, this));
50953e3b81fSAndy Wingo
5100a9583ceSRui Ueyama // Populate `Globals`.
511136d27abSRui Ueyama for (const WasmGlobal &g : wasmObj->globals())
512136d27abSRui Ueyama globals.emplace_back(make<InputGlobal>(g, this));
5138d146bbcSSam Clegg
5141d891d44SHeejin Ahn // Populate `Tags`.
5151d891d44SHeejin Ahn for (const WasmTag &t : wasmObj->tags())
5163ec1760dSHeejin Ahn tags.emplace_back(make<InputTag>(types[t.SigIndex], t, this));
517e915a71fSHeejin Ahn
51833fdf82dSFangrui Song // Populate `Symbols` based on the symbols in the object.
519136d27abSRui Ueyama symbols.reserve(wasmObj->getNumberOfSymbols());
5204fc25573SAndy Wingo uint32_t tableSymbolCount = 0;
521136d27abSRui Ueyama for (const SymbolRef &sym : wasmObj->symbols()) {
522136d27abSRui Ueyama const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl());
52363393828SAndy Wingo if (wasmSym.isTypeTable())
5244fc25573SAndy Wingo tableSymbolCount++;
525136d27abSRui Ueyama if (wasmSym.isDefined()) {
52659f959ffSSam Clegg // createDefined may fail if the symbol is comdat excluded in which case
52759f959ffSSam Clegg // we fall back to creating an undefined symbol
528136d27abSRui Ueyama if (Symbol *d = createDefined(wasmSym)) {
529136d27abSRui Ueyama symbols.push_back(d);
53059f959ffSSam Clegg continue;
53159f959ffSSam Clegg }
53259f959ffSSam Clegg }
533136d27abSRui Ueyama size_t idx = symbols.size();
534136d27abSRui Ueyama symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx]));
5350a9583ceSRui Ueyama }
53663393828SAndy Wingo
5374fc25573SAndy Wingo addLegacyIndirectFunctionTableIfNeeded(tableSymbolCount);
53893102974SSam Clegg }
53993102974SSam Clegg
isExcludedByComdat(const InputChunk * chunk) const540c0039de2SSam Clegg bool ObjFile::isExcludedByComdat(const InputChunk *chunk) const {
541136d27abSRui Ueyama uint32_t c = chunk->getComdat();
542136d27abSRui Ueyama if (c == UINT32_MAX)
543dcf6234dSRui Ueyama return false;
544136d27abSRui Ueyama return !keptComdats[c];
545e0f6fcd0SSam Clegg }
546e0f6fcd0SSam Clegg
getFunctionSymbol(uint32_t index) const547136d27abSRui Ueyama FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const {
548136d27abSRui Ueyama return cast<FunctionSymbol>(symbols[index]);
54993102974SSam Clegg }
55093102974SSam Clegg
getGlobalSymbol(uint32_t index) const551136d27abSRui Ueyama GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const {
552136d27abSRui Ueyama return cast<GlobalSymbol>(symbols[index]);
55393102974SSam Clegg }
55493102974SSam Clegg
getTagSymbol(uint32_t index) const5551d891d44SHeejin Ahn TagSymbol *ObjFile::getTagSymbol(uint32_t index) const {
5561d891d44SHeejin Ahn return cast<TagSymbol>(symbols[index]);
557e915a71fSHeejin Ahn }
558e915a71fSHeejin Ahn
getTableSymbol(uint32_t index) const55953e3b81fSAndy Wingo TableSymbol *ObjFile::getTableSymbol(uint32_t index) const {
56053e3b81fSAndy Wingo return cast<TableSymbol>(symbols[index]);
56153e3b81fSAndy Wingo }
56253e3b81fSAndy Wingo
getSectionSymbol(uint32_t index) const563136d27abSRui Ueyama SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const {
564136d27abSRui Ueyama return cast<SectionSymbol>(symbols[index]);
565d177ab2aSSam Clegg }
566d177ab2aSSam Clegg
getDataSymbol(uint32_t index) const567136d27abSRui Ueyama DataSymbol *ObjFile::getDataSymbol(uint32_t index) const {
568136d27abSRui Ueyama return cast<DataSymbol>(symbols[index]);
56993102974SSam Clegg }
57093102974SSam Clegg
createDefined(const WasmSymbol & sym)571136d27abSRui Ueyama Symbol *ObjFile::createDefined(const WasmSymbol &sym) {
572136d27abSRui Ueyama StringRef name = sym.Info.Name;
573136d27abSRui Ueyama uint32_t flags = sym.Info.Flags;
574e89b0ef0SRui Ueyama
575136d27abSRui Ueyama switch (sym.Info.Kind) {
5764b56adceSRui Ueyama case WASM_SYMBOL_TYPE_FUNCTION: {
577136d27abSRui Ueyama InputFunction *func =
578136d27abSRui Ueyama functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
579136d27abSRui Ueyama if (sym.isBindingLocal())
580136d27abSRui Ueyama return make<DefinedFunction>(name, flags, this, func);
581accad76cSSam Clegg if (func->discarded)
582accad76cSSam Clegg return nullptr;
583136d27abSRui Ueyama return symtab->addDefinedFunction(name, flags, this, func);
5844b56adceSRui Ueyama }
5854b56adceSRui Ueyama case WASM_SYMBOL_TYPE_DATA: {
5865a9b25e1SSam Clegg InputChunk *seg = segments[sym.Info.DataRef.Segment];
5873b29376eSWouter van Oortmerssen auto offset = sym.Info.DataRef.Offset;
5883b29376eSWouter van Oortmerssen auto size = sym.Info.DataRef.Size;
589875ee937SSam Clegg // Support older (e.g. llvm 13) object files that pre-date the per-symbol
590875ee937SSam Clegg // TLS flag, and symbols were assumed to be TLS by being defined in a TLS
591875ee937SSam Clegg // segment.
592875ee937SSam Clegg if (!(flags & WASM_SYMBOL_TLS) && seg->isTLS())
59344177e5fSSam Clegg flags |= WASM_SYMBOL_TLS;
594136d27abSRui Ueyama if (sym.isBindingLocal())
595136d27abSRui Ueyama return make<DefinedData>(name, flags, this, seg, offset, size);
596accad76cSSam Clegg if (seg->discarded)
597accad76cSSam Clegg return nullptr;
598136d27abSRui Ueyama return symtab->addDefinedData(name, flags, this, seg, offset, size);
5994b56adceSRui Ueyama }
600d177ab2aSSam Clegg case WASM_SYMBOL_TYPE_GLOBAL: {
601136d27abSRui Ueyama InputGlobal *global =
602136d27abSRui Ueyama globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()];
603136d27abSRui Ueyama if (sym.isBindingLocal())
604136d27abSRui Ueyama return make<DefinedGlobal>(name, flags, this, global);
605136d27abSRui Ueyama return symtab->addDefinedGlobal(name, flags, this, global);
6064b56adceSRui Ueyama }
607d177ab2aSSam Clegg case WASM_SYMBOL_TYPE_SECTION: {
60845b7cf99SSam Clegg InputChunk *section = customSectionsByIndex[sym.Info.ElementIndex];
609136d27abSRui Ueyama assert(sym.isBindingLocal());
610dd6412c0SDerek Schuff // Need to return null if discarded here? data and func only do that when
611dd6412c0SDerek Schuff // binding is not local.
612dd6412c0SDerek Schuff if (section->discarded)
613dd6412c0SDerek Schuff return nullptr;
614136d27abSRui Ueyama return make<SectionSymbol>(flags, section, this);
615d177ab2aSSam Clegg }
6161d891d44SHeejin Ahn case WASM_SYMBOL_TYPE_TAG: {
6171d891d44SHeejin Ahn InputTag *tag = tags[sym.Info.ElementIndex - wasmObj->getNumImportedTags()];
618136d27abSRui Ueyama if (sym.isBindingLocal())
6191d891d44SHeejin Ahn return make<DefinedTag>(name, flags, this, tag);
6201d891d44SHeejin Ahn return symtab->addDefinedTag(name, flags, this, tag);
621e915a71fSHeejin Ahn }
62253e3b81fSAndy Wingo case WASM_SYMBOL_TYPE_TABLE: {
62353e3b81fSAndy Wingo InputTable *table =
62453e3b81fSAndy Wingo tables[sym.Info.ElementIndex - wasmObj->getNumImportedTables()];
62553e3b81fSAndy Wingo if (sym.isBindingLocal())
62653e3b81fSAndy Wingo return make<DefinedTable>(name, flags, this, table);
62753e3b81fSAndy Wingo return symtab->addDefinedTable(name, flags, this, table);
62853e3b81fSAndy Wingo }
629d177ab2aSSam Clegg }
630d177ab2aSSam Clegg llvm_unreachable("unknown symbol kind");
6314b56adceSRui Ueyama }
6324b56adceSRui Ueyama
createUndefined(const WasmSymbol & sym,bool isCalledDirectly)633136d27abSRui Ueyama Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) {
634136d27abSRui Ueyama StringRef name = sym.Info.Name;
635f6f4b98fSSam Clegg uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED;
636e3498ec5SRui Ueyama
637136d27abSRui Ueyama switch (sym.Info.Kind) {
638e3498ec5SRui Ueyama case WASM_SYMBOL_TYPE_FUNCTION:
639136d27abSRui Ueyama if (sym.isBindingLocal())
640136d27abSRui Ueyama return make<UndefinedFunction>(name, sym.Info.ImportName,
641136d27abSRui Ueyama sym.Info.ImportModule, flags, this,
642136d27abSRui Ueyama sym.Signature, isCalledDirectly);
643136d27abSRui Ueyama return symtab->addUndefinedFunction(name, sym.Info.ImportName,
644136d27abSRui Ueyama sym.Info.ImportModule, flags, this,
645136d27abSRui Ueyama sym.Signature, isCalledDirectly);
646e3498ec5SRui Ueyama case WASM_SYMBOL_TYPE_DATA:
647136d27abSRui Ueyama if (sym.isBindingLocal())
648136d27abSRui Ueyama return make<UndefinedData>(name, flags, this);
649136d27abSRui Ueyama return symtab->addUndefinedData(name, flags, this);
650e3498ec5SRui Ueyama case WASM_SYMBOL_TYPE_GLOBAL:
651136d27abSRui Ueyama if (sym.isBindingLocal())
652136d27abSRui Ueyama return make<UndefinedGlobal>(name, sym.Info.ImportName,
653136d27abSRui Ueyama sym.Info.ImportModule, flags, this,
654136d27abSRui Ueyama sym.GlobalType);
655136d27abSRui Ueyama return symtab->addUndefinedGlobal(name, sym.Info.ImportName,
656136d27abSRui Ueyama sym.Info.ImportModule, flags, this,
657136d27abSRui Ueyama sym.GlobalType);
65853e3b81fSAndy Wingo case WASM_SYMBOL_TYPE_TABLE:
65953e3b81fSAndy Wingo if (sym.isBindingLocal())
66053e3b81fSAndy Wingo return make<UndefinedTable>(name, sym.Info.ImportName,
66153e3b81fSAndy Wingo sym.Info.ImportModule, flags, this,
66253e3b81fSAndy Wingo sym.TableType);
66353e3b81fSAndy Wingo return symtab->addUndefinedTable(name, sym.Info.ImportName,
66453e3b81fSAndy Wingo sym.Info.ImportModule, flags, this,
66553e3b81fSAndy Wingo sym.TableType);
6669261ee32SHeejin Ahn case WASM_SYMBOL_TYPE_TAG:
6679261ee32SHeejin Ahn if (sym.isBindingLocal())
6689261ee32SHeejin Ahn return make<UndefinedTag>(name, sym.Info.ImportName,
6699261ee32SHeejin Ahn sym.Info.ImportModule, flags, this,
6709261ee32SHeejin Ahn sym.Signature);
6719261ee32SHeejin Ahn return symtab->addUndefinedTag(name, sym.Info.ImportName,
6729261ee32SHeejin Ahn sym.Info.ImportModule, flags, this,
6739261ee32SHeejin Ahn sym.Signature);
674d177ab2aSSam Clegg case WASM_SYMBOL_TYPE_SECTION:
675d177ab2aSSam Clegg llvm_unreachable("section symbols cannot be undefined");
676e3498ec5SRui Ueyama }
677d177ab2aSSam Clegg llvm_unreachable("unknown symbol kind");
678c94d393aSSam Clegg }
679c94d393aSSam Clegg
parse()680a282a61bSSam Clegg void ArchiveFile::parse() {
681c94d393aSSam Clegg // Parse a MemoryBufferRef as an archive file.
682e7245b42SNicola Zaghen LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
683136d27abSRui Ueyama file = CHECK(Archive::create(mb), toString(this));
684c94d393aSSam Clegg
685c94d393aSSam Clegg // Read the symbol table to construct Lazy symbols.
686136d27abSRui Ueyama int count = 0;
687136d27abSRui Ueyama for (const Archive::Symbol &sym : file->symbols()) {
688136d27abSRui Ueyama symtab->addLazy(this, &sym);
689136d27abSRui Ueyama ++count;
690c94d393aSSam Clegg }
691136d27abSRui Ueyama LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n");
69246776f75SMartin Storsjö (void) count;
693c94d393aSSam Clegg }
694c94d393aSSam Clegg
addMember(const Archive::Symbol * sym)695136d27abSRui Ueyama void ArchiveFile::addMember(const Archive::Symbol *sym) {
696136d27abSRui Ueyama const Archive::Child &c =
697136d27abSRui Ueyama CHECK(sym->getMember(),
698136d27abSRui Ueyama "could not get the member for symbol " + sym->getName());
699c94d393aSSam Clegg
700c94d393aSSam Clegg // Don't try to load the same member twice (this can happen when members
701c94d393aSSam Clegg // mutually reference each other).
702136d27abSRui Ueyama if (!seen.insert(c.getChildOffset()).second)
703c94d393aSSam Clegg return;
704c94d393aSSam Clegg
705136d27abSRui Ueyama LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n");
706e7245b42SNicola Zaghen LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
707c94d393aSSam Clegg
708136d27abSRui Ueyama MemoryBufferRef mb =
709136d27abSRui Ueyama CHECK(c.getMemoryBufferRef(),
710c94d393aSSam Clegg "could not get the buffer for the member defining symbol " +
711136d27abSRui Ueyama sym->getName());
712c94d393aSSam Clegg
71328848e9eSSam Clegg InputFile *obj = createObjectFile(mb, getName(), c.getChildOffset());
714136d27abSRui Ueyama symtab->addFile(obj);
715c94d393aSSam Clegg }
716c94d393aSSam Clegg
mapVisibility(GlobalValue::VisibilityTypes gvVisibility)717136d27abSRui Ueyama static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
718136d27abSRui Ueyama switch (gvVisibility) {
719c729c1b4SSam Clegg case GlobalValue::DefaultVisibility:
720c729c1b4SSam Clegg return WASM_SYMBOL_VISIBILITY_DEFAULT;
721c729c1b4SSam Clegg case GlobalValue::HiddenVisibility:
722c729c1b4SSam Clegg case GlobalValue::ProtectedVisibility:
723c729c1b4SSam Clegg return WASM_SYMBOL_VISIBILITY_HIDDEN;
724c729c1b4SSam Clegg }
725c729c1b4SSam Clegg llvm_unreachable("unknown visibility");
726c729c1b4SSam Clegg }
727c729c1b4SSam Clegg
createBitcodeSymbol(const std::vector<bool> & keptComdats,const lto::InputFile::Symbol & objSym,BitcodeFile & f)728136d27abSRui Ueyama static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
729136d27abSRui Ueyama const lto::InputFile::Symbol &objSym,
730136d27abSRui Ueyama BitcodeFile &f) {
73183d59e05SAlexandre Ganea StringRef name = saver().save(objSym.getName());
732c729c1b4SSam Clegg
733136d27abSRui Ueyama uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
734136d27abSRui Ueyama flags |= mapVisibility(objSym.getVisibility());
735c729c1b4SSam Clegg
736136d27abSRui Ueyama int c = objSym.getComdatIndex();
737136d27abSRui Ueyama bool excludedByComdat = c != -1 && !keptComdats[c];
738697f2149SSam Clegg
739136d27abSRui Ueyama if (objSym.isUndefined() || excludedByComdat) {
740f6f4b98fSSam Clegg flags |= WASM_SYMBOL_UNDEFINED;
741136d27abSRui Ueyama if (objSym.isExecutable())
742bd481277SSam Clegg return symtab->addUndefinedFunction(name, None, None, flags, &f, nullptr,
74367b05584SSam Clegg true);
744136d27abSRui Ueyama return symtab->addUndefinedData(name, flags, &f);
745c729c1b4SSam Clegg }
746c729c1b4SSam Clegg
747136d27abSRui Ueyama if (objSym.isExecutable())
748136d27abSRui Ueyama return symtab->addDefinedFunction(name, flags, &f, nullptr);
749136d27abSRui Ueyama return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0);
750c729c1b4SSam Clegg }
751c729c1b4SSam Clegg
BitcodeFile(MemoryBufferRef m,StringRef archiveName,uint64_t offsetInArchive)75228848e9eSSam Clegg BitcodeFile::BitcodeFile(MemoryBufferRef m, StringRef archiveName,
75328848e9eSSam Clegg uint64_t offsetInArchive)
75428848e9eSSam Clegg : InputFile(BitcodeKind, m) {
75528848e9eSSam Clegg this->archiveName = std::string(archiveName);
75628848e9eSSam Clegg
75728848e9eSSam Clegg std::string path = mb.getBufferIdentifier().str();
75828848e9eSSam Clegg
75928848e9eSSam Clegg // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
76028848e9eSSam Clegg // name. If two archives define two members with the same name, this
76128848e9eSSam Clegg // causes a collision which result in only one of the objects being taken
76228848e9eSSam Clegg // into consideration at LTO time (which very likely causes undefined
76328848e9eSSam Clegg // symbols later in the link stage). So we append file offset to make
76428848e9eSSam Clegg // filename unique.
76528848e9eSSam Clegg StringRef name = archiveName.empty()
76683d59e05SAlexandre Ganea ? saver().save(path)
76783d59e05SAlexandre Ganea : saver().save(archiveName + "(" + path::filename(path) +
76828848e9eSSam Clegg " at " + utostr(offsetInArchive) + ")");
76928848e9eSSam Clegg MemoryBufferRef mbref(mb.getBuffer(), name);
77028848e9eSSam Clegg
77128848e9eSSam Clegg obj = check(lto::InputFile::create(mbref));
77228848e9eSSam Clegg
77328848e9eSSam Clegg // If this isn't part of an archive, it's eagerly linked, so mark it live.
77428848e9eSSam Clegg if (archiveName.empty())
77528848e9eSSam Clegg markLive();
77628848e9eSSam Clegg }
77728848e9eSSam Clegg
778b062fe18SSam Clegg bool BitcodeFile::doneLTO = false;
779b062fe18SSam Clegg
parse()780a282a61bSSam Clegg void BitcodeFile::parse() {
781b062fe18SSam Clegg if (doneLTO) {
78273e575a8SSam Clegg error(toString(this) + ": attempt to add bitcode file after LTO.");
783b062fe18SSam Clegg return;
784b062fe18SSam Clegg }
785b062fe18SSam Clegg
786136d27abSRui Ueyama Triple t(obj->getTargetTriple());
78729f8c9f6SWouter van Oortmerssen if (!t.isWasm()) {
78829f8c9f6SWouter van Oortmerssen error(toString(this) + ": machine type must be wasm32 or wasm64");
789c729c1b4SSam Clegg return;
790c729c1b4SSam Clegg }
791b8c2d60dSWouter van Oortmerssen checkArch(t.getArch());
792136d27abSRui Ueyama std::vector<bool> keptComdats;
793db5e0786SFangrui Song // TODO Support nodeduplicate https://bugs.llvm.org/show_bug.cgi?id=50531
794db5e0786SFangrui Song for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable())
795db5e0786SFangrui Song keptComdats.push_back(symtab->addComdat(s.first));
796c729c1b4SSam Clegg
797136d27abSRui Ueyama for (const lto::InputFile::Symbol &objSym : obj->symbols())
798136d27abSRui Ueyama symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this));
799c729c1b4SSam Clegg }
800c729c1b4SSam Clegg
80133c59abfSFangrui Song } // namespace wasm
80233c59abfSFangrui Song } // namespace lld
803