118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===// 218eafb6cSDan Gohman // 318eafb6cSDan Gohman // The LLVM Compiler Infrastructure 418eafb6cSDan Gohman // 518eafb6cSDan Gohman // This file is distributed under the University of Illinois Open Source 618eafb6cSDan Gohman // License. See LICENSE.TXT for details. 718eafb6cSDan Gohman // 818eafb6cSDan Gohman //===----------------------------------------------------------------------===// 918eafb6cSDan Gohman // 1018eafb6cSDan Gohman // This file implements Wasm object file writer information. 1118eafb6cSDan Gohman // 1218eafb6cSDan Gohman //===----------------------------------------------------------------------===// 1318eafb6cSDan Gohman 1418eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h" 1518eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h" 16264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h" 1718eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h" 1818eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h" 1918eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h" 2018eafb6cSDan Gohman #include "llvm/MC/MCContext.h" 2118eafb6cSDan Gohman #include "llvm/MC/MCExpr.h" 2218eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h" 2318eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h" 2418eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h" 2518eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h" 2618eafb6cSDan Gohman #include "llvm/MC/MCValue.h" 2718eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h" 28d934cb88SDan Gohman #include "llvm/Support/Casting.h" 2918eafb6cSDan Gohman #include "llvm/Support/Debug.h" 3018eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h" 31d934cb88SDan Gohman #include "llvm/Support/LEB128.h" 3218eafb6cSDan Gohman #include "llvm/Support/StringSaver.h" 3318eafb6cSDan Gohman #include <vector> 3418eafb6cSDan Gohman 3518eafb6cSDan Gohman using namespace llvm; 3618eafb6cSDan Gohman 375e3d33a7SSam Clegg #define DEBUG_TYPE "mc" 3818eafb6cSDan Gohman 3918eafb6cSDan Gohman namespace { 409e15f359SSam Clegg 4130e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is 4230e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap. 4330e1bbc1SSam Clegg static const uint32_t kInitialTableOffset = 1; 4430e1bbc1SSam Clegg 45d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both 46d934cb88SDan Gohman // for patching up the section size field, and for patching up references to 47d934cb88SDan Gohman // locations within the section. 48d934cb88SDan Gohman struct SectionBookkeeping { 49d934cb88SDan Gohman // Where the size of the section is written. 50d934cb88SDan Gohman uint64_t SizeOffset; 516a31a0d6SSam Clegg // Where the section header ends (without custom section name). 526a31a0d6SSam Clegg uint64_t PayloadOffset; 536a31a0d6SSam Clegg // Where the contents of the section starts. 54d934cb88SDan Gohman uint64_t ContentsOffset; 556f08c84aSSam Clegg uint32_t Index; 56d934cb88SDan Gohman }; 57d934cb88SDan Gohman 589e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a 599e15f359SSam Clegg // DenseMap key. 609e15f359SSam Clegg struct WasmFunctionType { 619e15f359SSam Clegg // Support empty and tombstone instances, needed by DenseMap. 629e15f359SSam Clegg enum { Plain, Empty, Tombstone } State; 639e15f359SSam Clegg 649e15f359SSam Clegg // The return types of the function. 659e15f359SSam Clegg SmallVector<wasm::ValType, 1> Returns; 669e15f359SSam Clegg 679e15f359SSam Clegg // The parameter types of the function. 689e15f359SSam Clegg SmallVector<wasm::ValType, 4> Params; 699e15f359SSam Clegg 709e15f359SSam Clegg WasmFunctionType() : State(Plain) {} 719e15f359SSam Clegg 729e15f359SSam Clegg bool operator==(const WasmFunctionType &Other) const { 739e15f359SSam Clegg return State == Other.State && Returns == Other.Returns && 749e15f359SSam Clegg Params == Other.Params; 759e15f359SSam Clegg } 769e15f359SSam Clegg }; 779e15f359SSam Clegg 789e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap. 799e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo { 809e15f359SSam Clegg static WasmFunctionType getEmptyKey() { 819e15f359SSam Clegg WasmFunctionType FuncTy; 829e15f359SSam Clegg FuncTy.State = WasmFunctionType::Empty; 839e15f359SSam Clegg return FuncTy; 849e15f359SSam Clegg } 859e15f359SSam Clegg static WasmFunctionType getTombstoneKey() { 869e15f359SSam Clegg WasmFunctionType FuncTy; 879e15f359SSam Clegg FuncTy.State = WasmFunctionType::Tombstone; 889e15f359SSam Clegg return FuncTy; 899e15f359SSam Clegg } 909e15f359SSam Clegg static unsigned getHashValue(const WasmFunctionType &FuncTy) { 919e15f359SSam Clegg uintptr_t Value = FuncTy.State; 929e15f359SSam Clegg for (wasm::ValType Ret : FuncTy.Returns) 939e15f359SSam Clegg Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret)); 949e15f359SSam Clegg for (wasm::ValType Param : FuncTy.Params) 959e15f359SSam Clegg Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param)); 969e15f359SSam Clegg return Value; 979e15f359SSam Clegg } 989e15f359SSam Clegg static bool isEqual(const WasmFunctionType &LHS, 999e15f359SSam Clegg const WasmFunctionType &RHS) { 1009e15f359SSam Clegg return LHS == RHS; 1019e15f359SSam Clegg } 1029e15f359SSam Clegg }; 1039e15f359SSam Clegg 1047c395943SSam Clegg // A wasm data segment. A wasm binary contains only a single data section 1057c395943SSam Clegg // but that can contain many segments, each with their own virtual location 1067c395943SSam Clegg // in memory. Each MCSection data created by llvm is modeled as its own 1077c395943SSam Clegg // wasm data segment. 1087c395943SSam Clegg struct WasmDataSegment { 1097c395943SSam Clegg MCSectionWasm *Section; 110d95ed959SSam Clegg StringRef Name; 1117c395943SSam Clegg uint32_t Offset; 11263ebb813SSam Clegg uint32_t Alignment; 11363ebb813SSam Clegg uint32_t Flags; 1147c395943SSam Clegg SmallVector<char, 4> Data; 1157c395943SSam Clegg }; 1167c395943SSam Clegg 1179e15f359SSam Clegg // A wasm function to be written into the function section. 1189e15f359SSam Clegg struct WasmFunction { 1199e15f359SSam Clegg int32_t Type; 1209e15f359SSam Clegg const MCSymbolWasm *Sym; 1219e15f359SSam Clegg }; 1229e15f359SSam Clegg 1239e15f359SSam Clegg // A wasm global to be written into the global section. 1249e15f359SSam Clegg struct WasmGlobal { 1256e7f1826SSam Clegg wasm::WasmGlobalType Type; 1269e15f359SSam Clegg uint64_t InitialValue; 1279e15f359SSam Clegg }; 1289e15f359SSam Clegg 129ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT. For each data 130ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding 131ea7caceeSSam Clegg // WasmComdatEntry. 132ea7caceeSSam Clegg struct WasmComdatEntry { 133ea7caceeSSam Clegg unsigned Kind; 134ea7caceeSSam Clegg uint32_t Index; 135ea7caceeSSam Clegg }; 136ea7caceeSSam Clegg 1376dc65e91SSam Clegg // Information about a single relocation. 1386dc65e91SSam Clegg struct WasmRelocationEntry { 1396dc65e91SSam Clegg uint64_t Offset; // Where is the relocation. 1406dc65e91SSam Clegg const MCSymbolWasm *Symbol; // The symbol to relocate with. 1416dc65e91SSam Clegg int64_t Addend; // A value to add to the symbol. 1426dc65e91SSam Clegg unsigned Type; // The type of the relocation. 143fe6414b0SSam Clegg const MCSectionWasm *FixupSection;// The section the relocation is targeting. 1446dc65e91SSam Clegg 1456dc65e91SSam Clegg WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol, 1466dc65e91SSam Clegg int64_t Addend, unsigned Type, 147fe6414b0SSam Clegg const MCSectionWasm *FixupSection) 1486dc65e91SSam Clegg : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type), 1496dc65e91SSam Clegg FixupSection(FixupSection) {} 1506dc65e91SSam Clegg 151acd7d2b0SSam Clegg bool hasAddend() const { 152acd7d2b0SSam Clegg switch (Type) { 15313a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 15413a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 15513a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 1566a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: 1576a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: 158acd7d2b0SSam Clegg return true; 159acd7d2b0SSam Clegg default: 160acd7d2b0SSam Clegg return false; 161acd7d2b0SSam Clegg } 162acd7d2b0SSam Clegg } 163acd7d2b0SSam Clegg 1646dc65e91SSam Clegg void print(raw_ostream &Out) const { 1659bf73c07SSam Clegg Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend 166759631c7SSam Clegg << ", Type=" << Type 167759631c7SSam Clegg << ", FixupSection=" << FixupSection->getSectionName(); 1686dc65e91SSam Clegg } 169b7787fd0SSam Clegg 170615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 171b7787fd0SSam Clegg LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 172b7787fd0SSam Clegg #endif 1736dc65e91SSam Clegg }; 1746dc65e91SSam Clegg 175cfd44a2eSSam Clegg struct WasmCustomSection { 1766a31a0d6SSam Clegg const uint32_t INVALID_INDEX = -1; 177cfd44a2eSSam Clegg 1786a31a0d6SSam Clegg StringRef Name; 1796a31a0d6SSam Clegg MCSectionWasm *Section; 1806a31a0d6SSam Clegg 1816a31a0d6SSam Clegg uint32_t OutputContentsOffset; 1826a31a0d6SSam Clegg uint32_t OutputIndex; 1836a31a0d6SSam Clegg 1846a31a0d6SSam Clegg WasmCustomSection(StringRef Name, MCSectionWasm *Section) 1856a31a0d6SSam Clegg : Name(Name), Section(Section), OutputContentsOffset(0), 1866a31a0d6SSam Clegg OutputIndex(INVALID_INDEX) {} 187cfd44a2eSSam Clegg }; 188cfd44a2eSSam Clegg 1891fb8daa6SSam Clegg #if !defined(NDEBUG) 1907f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) { 191b7787fd0SSam Clegg Rel.print(OS); 192b7787fd0SSam Clegg return OS; 193b7787fd0SSam Clegg } 1941fb8daa6SSam Clegg #endif 195b7787fd0SSam Clegg 19618eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter { 19718eafb6cSDan Gohman /// The target specific Wasm writer instance. 19818eafb6cSDan Gohman std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; 19918eafb6cSDan Gohman 200d934cb88SDan Gohman // Relocations for fixing up references in the code section. 201d934cb88SDan Gohman std::vector<WasmRelocationEntry> CodeRelocations; 2026f08c84aSSam Clegg uint32_t CodeSectionIndex; 203d934cb88SDan Gohman 204d934cb88SDan Gohman // Relocations for fixing up references in the data section. 205d934cb88SDan Gohman std::vector<WasmRelocationEntry> DataRelocations; 2066f08c84aSSam Clegg uint32_t DataSectionIndex; 207d934cb88SDan Gohman 208d934cb88SDan Gohman // Index values to use for fixing up call_indirect type indices. 209acd7d2b0SSam Clegg // Maps function symbols to the index of the type of the function 210acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices; 211d99f6078SSam Clegg // Maps function symbols to the table element index space. Used 212d99f6078SSam Clegg // for TABLE_INDEX relocation types (i.e. address taken functions). 213f9edbe95SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TableIndices; 2146c899ba6SSam Clegg // Maps function/global symbols to the (shared) Symbol index space. 215acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices; 2166c899ba6SSam Clegg // Maps function/global symbols to the function/global Wasm index space. 2176c899ba6SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices; 2186c899ba6SSam Clegg // Maps data symbols to the Wasm segment and offset/size with the segment. 2196c899ba6SSam Clegg DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations; 2206a31a0d6SSam Clegg // Maps section symbols to the section. 2216a31a0d6SSam Clegg DenseMap<const MCSymbolWasm *, const MCSectionWasm *> CustomSectionSymbols; 2226a31a0d6SSam Clegg 2236a31a0d6SSam Clegg // Stores output data (index, relocations, content offset) for custom 2246a31a0d6SSam Clegg // section. 2256a31a0d6SSam Clegg std::vector<WasmCustomSection> CustomSections; 2266a31a0d6SSam Clegg // Relocations for fixing up references in the custom sections. 2276a31a0d6SSam Clegg DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>> 2286a31a0d6SSam Clegg CustomSectionsRelocations; 229acd7d2b0SSam Clegg 230acd7d2b0SSam Clegg DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo> 231acd7d2b0SSam Clegg FunctionTypeIndices; 2325e3d33a7SSam Clegg SmallVector<WasmFunctionType, 4> FunctionTypes; 2337c395943SSam Clegg SmallVector<WasmGlobal, 4> Globals; 2346c899ba6SSam Clegg SmallVector<WasmDataSegment, 4> DataSegments; 2359f3fe42eSSam Clegg unsigned NumFunctionImports = 0; 2367c395943SSam Clegg unsigned NumGlobalImports = 0; 2377e1c3345SChandler Carruth uint32_t SectionCount = 0; 238d934cb88SDan Gohman 23918eafb6cSDan Gohman // TargetObjectWriter wrappers. 24018eafb6cSDan Gohman bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 241ae03c1e7SSam Clegg unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const { 242ae03c1e7SSam Clegg return TargetObjectWriter->getRelocType(Target, Fixup); 24318eafb6cSDan Gohman } 24418eafb6cSDan Gohman 2452322a937SSam Clegg void startSection(SectionBookkeeping &Section, unsigned SectionId); 2462322a937SSam Clegg void startCustomSection(SectionBookkeeping &Section, StringRef Name); 247d934cb88SDan Gohman void endSection(SectionBookkeeping &Section); 248d934cb88SDan Gohman 24918eafb6cSDan Gohman public: 2501301a878SLang Hames WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 2511301a878SLang Hames raw_pwrite_stream &OS) 2521301a878SLang Hames : MCObjectWriter(OS, /*IsLittleEndian=*/true), 2531301a878SLang Hames TargetObjectWriter(std::move(MOTW)) {} 25418eafb6cSDan Gohman 25518eafb6cSDan Gohman ~WasmObjectWriter() override; 25618eafb6cSDan Gohman 2570917c9e4SDan Gohman private: 258acd7d2b0SSam Clegg void reset() override { 259acd7d2b0SSam Clegg CodeRelocations.clear(); 260acd7d2b0SSam Clegg DataRelocations.clear(); 261acd7d2b0SSam Clegg TypeIndices.clear(); 262acd7d2b0SSam Clegg SymbolIndices.clear(); 2636c899ba6SSam Clegg WasmIndices.clear(); 264f9edbe95SSam Clegg TableIndices.clear(); 2656c899ba6SSam Clegg DataLocations.clear(); 2666a31a0d6SSam Clegg CustomSectionsRelocations.clear(); 267acd7d2b0SSam Clegg FunctionTypeIndices.clear(); 2685e3d33a7SSam Clegg FunctionTypes.clear(); 2697c395943SSam Clegg Globals.clear(); 2706c899ba6SSam Clegg DataSegments.clear(); 2716a31a0d6SSam Clegg CustomSectionSymbols.clear(); 272acd7d2b0SSam Clegg MCObjectWriter::reset(); 2739f3fe42eSSam Clegg NumFunctionImports = 0; 2747c395943SSam Clegg NumGlobalImports = 0; 275acd7d2b0SSam Clegg } 276acd7d2b0SSam Clegg 27718eafb6cSDan Gohman void writeHeader(const MCAssembler &Asm); 27818eafb6cSDan Gohman 27918eafb6cSDan Gohman void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 28018eafb6cSDan Gohman const MCFragment *Fragment, const MCFixup &Fixup, 281ceecfe5bSRafael Espindola MCValue Target, uint64_t &FixedValue) override; 28218eafb6cSDan Gohman 28318eafb6cSDan Gohman void executePostLayoutBinding(MCAssembler &Asm, 28418eafb6cSDan Gohman const MCAsmLayout &Layout) override; 28518eafb6cSDan Gohman 28618eafb6cSDan Gohman void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 2879e15f359SSam Clegg 288b7787fd0SSam Clegg void writeString(const StringRef Str) { 289b7787fd0SSam Clegg encodeULEB128(Str.size(), getStream()); 290b7787fd0SSam Clegg writeBytes(Str); 291b7787fd0SSam Clegg } 292b7787fd0SSam Clegg 2939e15f359SSam Clegg void writeValueType(wasm::ValType Ty) { 29403e101f1SSam Clegg write8(static_cast<uint8_t>(Ty)); 2959e15f359SSam Clegg } 2969e15f359SSam Clegg 297457fb0b4SSam Clegg void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes); 2988defa952SSam Clegg void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize, 299f950b24aSSam Clegg uint32_t NumElements); 300457fb0b4SSam Clegg void writeFunctionSection(ArrayRef<WasmFunction> Functions); 3017c395943SSam Clegg void writeGlobalSection(); 3028defa952SSam Clegg void writeExportSection(ArrayRef<wasm::WasmExport> Exports); 303457fb0b4SSam Clegg void writeElemSection(ArrayRef<uint32_t> TableElems); 3049e15f359SSam Clegg void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout, 305457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions); 3066c899ba6SSam Clegg void writeDataSection(); 3076f08c84aSSam Clegg void writeRelocSection(uint32_t SectionIndex, StringRef Name, 3086f08c84aSSam Clegg ArrayRef<WasmRelocationEntry> Relocations); 30931a2c809SSam Clegg void writeLinkingMetaDataSection( 31086b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 311ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 312ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats); 3136a31a0d6SSam Clegg void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout); 3146a31a0d6SSam Clegg void writeCustomRelocSections(); 3156a31a0d6SSam Clegg void 3166a31a0d6SSam Clegg updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions, 3176a31a0d6SSam Clegg const MCAsmLayout &Layout); 318acd7d2b0SSam Clegg 3197c395943SSam Clegg uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry); 320acd7d2b0SSam Clegg void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations, 321acd7d2b0SSam Clegg uint64_t ContentsOffset); 322acd7d2b0SSam Clegg 323acd7d2b0SSam Clegg uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry); 3245e3d33a7SSam Clegg uint32_t getFunctionType(const MCSymbolWasm &Symbol); 3255e3d33a7SSam Clegg uint32_t registerFunctionType(const MCSymbolWasm &Symbol); 32618eafb6cSDan Gohman }; 3279e15f359SSam Clegg 32818eafb6cSDan Gohman } // end anonymous namespace 32918eafb6cSDan Gohman 33018eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {} 33118eafb6cSDan Gohman 332d934cb88SDan Gohman // Write out a section header and a patchable section size field. 333d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section, 3342322a937SSam Clegg unsigned SectionId) { 3352322a937SSam Clegg DEBUG(dbgs() << "startSection " << SectionId << "\n"); 33603e101f1SSam Clegg write8(SectionId); 337d934cb88SDan Gohman 338d934cb88SDan Gohman Section.SizeOffset = getStream().tell(); 339d934cb88SDan Gohman 340d934cb88SDan Gohman // The section size. We don't know the size yet, so reserve enough space 341d934cb88SDan Gohman // for any 32-bit value; we'll patch it later. 342d934cb88SDan Gohman encodeULEB128(UINT32_MAX, getStream()); 343d934cb88SDan Gohman 344d934cb88SDan Gohman // The position where the section starts, for measuring its size. 345d934cb88SDan Gohman Section.ContentsOffset = getStream().tell(); 3466a31a0d6SSam Clegg Section.PayloadOffset = getStream().tell(); 3476f08c84aSSam Clegg Section.Index = SectionCount++; 348d934cb88SDan Gohman } 3492322a937SSam Clegg 3502322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section, 3512322a937SSam Clegg StringRef Name) { 3522322a937SSam Clegg DEBUG(dbgs() << "startCustomSection " << Name << "\n"); 3532322a937SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM); 3546a31a0d6SSam Clegg 3556a31a0d6SSam Clegg // The position where the section header ends, for measuring its size. 3566a31a0d6SSam Clegg Section.PayloadOffset = getStream().tell(); 3576a31a0d6SSam Clegg 3582322a937SSam Clegg // Custom sections in wasm also have a string identifier. 3592322a937SSam Clegg writeString(Name); 3606a31a0d6SSam Clegg 3616a31a0d6SSam Clegg // The position where the custom section starts. 3626a31a0d6SSam Clegg Section.ContentsOffset = getStream().tell(); 363d934cb88SDan Gohman } 364d934cb88SDan Gohman 365d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the 366d934cb88SDan Gohman // section size field at the start of the section. 367d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) { 3686a31a0d6SSam Clegg uint64_t Size = getStream().tell() - Section.PayloadOffset; 369d934cb88SDan Gohman if (uint32_t(Size) != Size) 370d934cb88SDan Gohman report_fatal_error("section size does not fit in a uint32_t"); 371d934cb88SDan Gohman 372b7787fd0SSam Clegg DEBUG(dbgs() << "endSection size=" << Size << "\n"); 373d934cb88SDan Gohman 374d934cb88SDan Gohman // Write the final section size to the payload_len field, which follows 375d934cb88SDan Gohman // the section id byte. 376d934cb88SDan Gohman uint8_t Buffer[16]; 37766a99e41SSam Clegg unsigned SizeLen = encodeULEB128(Size, Buffer, 5); 378d934cb88SDan Gohman assert(SizeLen == 5); 379d934cb88SDan Gohman getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset); 380d934cb88SDan Gohman } 381d934cb88SDan Gohman 38218eafb6cSDan Gohman // Emit the Wasm header. 38318eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { 3847ea5adffSDan Gohman writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic))); 3857ea5adffSDan Gohman writeLE32(wasm::WasmVersion); 38618eafb6cSDan Gohman } 38718eafb6cSDan Gohman 38818eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 38918eafb6cSDan Gohman const MCAsmLayout &Layout) { 39018eafb6cSDan Gohman } 39118eafb6cSDan Gohman 39218eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 39318eafb6cSDan Gohman const MCAsmLayout &Layout, 39418eafb6cSDan Gohman const MCFragment *Fragment, 39518eafb6cSDan Gohman const MCFixup &Fixup, MCValue Target, 396ceecfe5bSRafael Espindola uint64_t &FixedValue) { 397ceecfe5bSRafael Espindola MCAsmBackend &Backend = Asm.getBackend(); 398ceecfe5bSRafael Espindola bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags & 399ceecfe5bSRafael Espindola MCFixupKindInfo::FKF_IsPCRel; 400fe6414b0SSam Clegg const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 401d934cb88SDan Gohman uint64_t C = Target.getConstant(); 402d934cb88SDan Gohman uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 403d934cb88SDan Gohman MCContext &Ctx = Asm.getContext(); 404d934cb88SDan Gohman 405bafe6902SSam Clegg // The .init_array isn't translated as data, so don't do relocations in it. 406bafe6902SSam Clegg if (FixupSection.getSectionName().startswith(".init_array")) 407bafe6902SSam Clegg return; 408bafe6902SSam Clegg 4096a31a0d6SSam Clegg // TODO: Add support for non-debug metadata sections? 4106a31a0d6SSam Clegg if (FixupSection.getKind().isMetadata() && 4116a31a0d6SSam Clegg !FixupSection.getSectionName().startswith(".debug_")) 412b7a5469cSSam Clegg return; 413b7a5469cSSam Clegg 414d934cb88SDan Gohman if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 415d934cb88SDan Gohman assert(RefB->getKind() == MCSymbolRefExpr::VK_None && 416d934cb88SDan Gohman "Should not have constructed this"); 417d934cb88SDan Gohman 418d934cb88SDan Gohman // Let A, B and C being the components of Target and R be the location of 419d934cb88SDan Gohman // the fixup. If the fixup is not pcrel, we want to compute (A - B + C). 420d934cb88SDan Gohman // If it is pcrel, we want to compute (A - B + C - R). 421d934cb88SDan Gohman 422d934cb88SDan Gohman // In general, Wasm has no relocations for -B. It can only represent (A + C) 423d934cb88SDan Gohman // or (A + C - R). If B = R + K and the relocation is not pcrel, we can 424d934cb88SDan Gohman // replace B to implement it: (A - R - K + C) 425d934cb88SDan Gohman if (IsPCRel) { 426d934cb88SDan Gohman Ctx.reportError( 427d934cb88SDan Gohman Fixup.getLoc(), 428d934cb88SDan Gohman "No relocation available to represent this relative expression"); 429d934cb88SDan Gohman return; 430d934cb88SDan Gohman } 431d934cb88SDan Gohman 432d934cb88SDan Gohman const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 433d934cb88SDan Gohman 434d934cb88SDan Gohman if (SymB.isUndefined()) { 435d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 436d934cb88SDan Gohman Twine("symbol '") + SymB.getName() + 437d934cb88SDan Gohman "' can not be undefined in a subtraction expression"); 438d934cb88SDan Gohman return; 439d934cb88SDan Gohman } 440d934cb88SDan Gohman 441d934cb88SDan Gohman assert(!SymB.isAbsolute() && "Should have been folded"); 442d934cb88SDan Gohman const MCSection &SecB = SymB.getSection(); 443d934cb88SDan Gohman if (&SecB != &FixupSection) { 444d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 445d934cb88SDan Gohman "Cannot represent a difference across sections"); 446d934cb88SDan Gohman return; 447d934cb88SDan Gohman } 448d934cb88SDan Gohman 449d934cb88SDan Gohman uint64_t SymBOffset = Layout.getSymbolOffset(SymB); 450d934cb88SDan Gohman uint64_t K = SymBOffset - FixupOffset; 451d934cb88SDan Gohman IsPCRel = true; 452d934cb88SDan Gohman C -= K; 453d934cb88SDan Gohman } 454d934cb88SDan Gohman 455d934cb88SDan Gohman // We either rejected the fixup or folded B into C at this point. 456d934cb88SDan Gohman const MCSymbolRefExpr *RefA = Target.getSymA(); 457d934cb88SDan Gohman const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr; 458d934cb88SDan Gohman 459d934cb88SDan Gohman if (SymA && SymA->isVariable()) { 460d934cb88SDan Gohman const MCExpr *Expr = SymA->getVariableValue(); 4616ad8f190SSam Clegg const auto *Inner = cast<MCSymbolRefExpr>(Expr); 4626ad8f190SSam Clegg if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) 4636ad8f190SSam Clegg llvm_unreachable("weakref used in reloc not yet implemented"); 464d934cb88SDan Gohman } 465d934cb88SDan Gohman 466d934cb88SDan Gohman // Put any constant offset in an addend. Offsets can be negative, and 467d934cb88SDan Gohman // LLVM expects wrapping, in contrast to wasm's immediates which can't 468d934cb88SDan Gohman // be negative and don't wrap. 469d934cb88SDan Gohman FixedValue = 0; 470d934cb88SDan Gohman 4716ad8f190SSam Clegg if (SymA) 472d934cb88SDan Gohman SymA->setUsedInReloc(); 473d934cb88SDan Gohman 474ae03c1e7SSam Clegg assert(!IsPCRel); 4759d24fb7fSSam Clegg assert(SymA); 4769d24fb7fSSam Clegg 477ae03c1e7SSam Clegg unsigned Type = getRelocType(Target, Fixup); 478ae03c1e7SSam Clegg 479d934cb88SDan Gohman WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 480b7787fd0SSam Clegg DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 481d934cb88SDan Gohman 4826a31a0d6SSam Clegg // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB, 4836a31a0d6SSam Clegg // R_WEBASSEMBLY_SECTION_OFFSET_I32 or R_WEBASSEMBLY_FUNCTION_OFFSET_I32 4846a31a0d6SSam Clegg // are currently required to be against a named symbol. 485b7a5469cSSam Clegg // TODO(sbc): Add support for relocations against unnamed temporaries such 486b7a5469cSSam Clegg // as those generated by llvm's `blockaddress`. 487b7a5469cSSam Clegg // See: test/MC/WebAssembly/blockaddress.ll 4886a31a0d6SSam Clegg if (SymA->getName().empty() && 4896a31a0d6SSam Clegg !(Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB || 4906a31a0d6SSam Clegg Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 || 4916a31a0d6SSam Clegg Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32)) 492b7a5469cSSam Clegg report_fatal_error("relocations against un-named temporaries are not yet " 493b7a5469cSSam Clegg "supported by wasm"); 494b7a5469cSSam Clegg 4956a31a0d6SSam Clegg if (FixupSection.isWasmData()) { 496d934cb88SDan Gohman DataRelocations.push_back(Rec); 4976a31a0d6SSam Clegg } else if (FixupSection.getKind().isText()) { 49812fd3da9SSam Clegg CodeRelocations.push_back(Rec); 4996a31a0d6SSam Clegg } else if (FixupSection.getKind().isMetadata()) { 5006a31a0d6SSam Clegg assert(FixupSection.getSectionName().startswith(".debug_")); 5016a31a0d6SSam Clegg CustomSectionsRelocations[&FixupSection].push_back(Rec); 5026a31a0d6SSam Clegg } else { 50312fd3da9SSam Clegg llvm_unreachable("unexpected section type"); 504d934cb88SDan Gohman } 5056a31a0d6SSam Clegg } 506d934cb88SDan Gohman 507d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded 508d934cb88SDan Gohman // to allow patching. 509d934cb88SDan Gohman static void 510d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 511d934cb88SDan Gohman uint8_t Buffer[5]; 51266a99e41SSam Clegg unsigned SizeLen = encodeULEB128(X, Buffer, 5); 513d934cb88SDan Gohman assert(SizeLen == 5); 514d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 515d934cb88SDan Gohman } 516d934cb88SDan Gohman 517d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded 518d934cb88SDan Gohman // to allow patching. 519d934cb88SDan Gohman static void 520d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) { 521d934cb88SDan Gohman uint8_t Buffer[5]; 52266a99e41SSam Clegg unsigned SizeLen = encodeSLEB128(X, Buffer, 5); 523d934cb88SDan Gohman assert(SizeLen == 5); 524d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 525d934cb88SDan Gohman } 526d934cb88SDan Gohman 527d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream. 528d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 529d934cb88SDan Gohman uint8_t Buffer[4]; 530d934cb88SDan Gohman support::endian::write32le(Buffer, X); 531d934cb88SDan Gohman Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 532d934cb88SDan Gohman } 533d934cb88SDan Gohman 534aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) { 535aff1c4dfSSam Clegg if (Symbol.isVariable()) { 536aff1c4dfSSam Clegg const MCExpr *Expr = Symbol.getVariableValue(); 537aff1c4dfSSam Clegg auto *Inner = cast<MCSymbolRefExpr>(Expr); 538aff1c4dfSSam Clegg return cast<MCSymbolWasm>(&Inner->getSymbol()); 539aff1c4dfSSam Clegg } 540aff1c4dfSSam Clegg return &Symbol; 541aff1c4dfSSam Clegg } 542aff1c4dfSSam Clegg 543d934cb88SDan Gohman // Compute a value to write into the code at the location covered 54460ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves 54560ec3034SSam Clegg // to make the object format more readable and more likely to be directly 54660ec3034SSam Clegg // useable. 5477c395943SSam Clegg uint32_t 5487c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) { 54960ec3034SSam Clegg switch (RelEntry.Type) { 55060ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 551f9edbe95SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: { 552f9edbe95SSam Clegg // Provisional value is table address of the resolved symbol itself 553f9edbe95SSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 554f9edbe95SSam Clegg assert(Sym->isFunction()); 555f9edbe95SSam Clegg return TableIndices[Sym]; 556f9edbe95SSam Clegg } 55760ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 5586c899ba6SSam Clegg // Provisional value is same as the index 55960ec3034SSam Clegg return getRelocationIndexValue(RelEntry); 5606c899ba6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 5616c899ba6SSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 5626c899ba6SSam Clegg // Provisional value is function/global Wasm index 5636c899ba6SSam Clegg if (!WasmIndices.count(RelEntry.Symbol)) 5646c899ba6SSam Clegg report_fatal_error("symbol not found in wasm index space: " + 5656c899ba6SSam Clegg RelEntry.Symbol->getName()); 5666c899ba6SSam Clegg return WasmIndices[RelEntry.Symbol]; 5676a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: { 5686a31a0d6SSam Clegg const auto &Section = 5696a31a0d6SSam Clegg static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection()); 5706a31a0d6SSam Clegg return Section.getSectionOffset() + RelEntry.Addend; 5716a31a0d6SSam Clegg } 5726a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: { 5736a31a0d6SSam Clegg const auto &Section = *CustomSectionSymbols.find(RelEntry.Symbol)->second; 5746a31a0d6SSam Clegg return Section.getSectionOffset() + RelEntry.Addend; 5756a31a0d6SSam Clegg } 57660ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 57760ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 57860ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: { 579f9edbe95SSam Clegg // Provisional value is address of the global 58060ec3034SSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 581270ed1b3SSam Clegg // For undefined symbols, use zero 582cd65f698SSam Clegg if (!Sym->isDefined()) 583270ed1b3SSam Clegg return 0; 5846c899ba6SSam Clegg const wasm::WasmDataReference &Ref = DataLocations[Sym]; 5856c899ba6SSam Clegg const WasmDataSegment &Segment = DataSegments[Ref.Segment]; 586d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 5876c899ba6SSam Clegg return Segment.Offset + Ref.Offset + RelEntry.Addend; 58860ec3034SSam Clegg } 58960ec3034SSam Clegg default: 59060ec3034SSam Clegg llvm_unreachable("invalid relocation type"); 59160ec3034SSam Clegg } 592d934cb88SDan Gohman } 593d934cb88SDan Gohman 594759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes, 59563ebb813SSam Clegg MCSectionWasm &DataSection) { 596759631c7SSam Clegg DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n"); 597759631c7SSam Clegg 59863ebb813SSam Clegg DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 59963ebb813SSam Clegg 600759631c7SSam Clegg for (const MCFragment &Frag : DataSection) { 601759631c7SSam Clegg if (Frag.hasInstructions()) 602759631c7SSam Clegg report_fatal_error("only data supported in data sections"); 603759631c7SSam Clegg 604759631c7SSam Clegg if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 605759631c7SSam Clegg if (Align->getValueSize() != 1) 606759631c7SSam Clegg report_fatal_error("only byte values supported for alignment"); 607759631c7SSam Clegg // If nops are requested, use zeros, as this is the data section. 608759631c7SSam Clegg uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 609759631c7SSam Clegg uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(), 610759631c7SSam Clegg Align->getAlignment()), 611759631c7SSam Clegg DataBytes.size() + 612759631c7SSam Clegg Align->getMaxBytesToEmit()); 613759631c7SSam Clegg DataBytes.resize(Size, Value); 614759631c7SSam Clegg } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 615d707c370SRafael Espindola int64_t Size; 616d707c370SRafael Espindola if (!Fill->getSize().evaluateAsAbsolute(Size)) 617d707c370SRafael Espindola llvm_unreachable("The fill should be an assembler constant"); 618d707c370SRafael Espindola DataBytes.insert(DataBytes.end(), Size, Fill->getValue()); 619759631c7SSam Clegg } else { 620759631c7SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 621759631c7SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 622759631c7SSam Clegg 623759631c7SSam Clegg DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 624759631c7SSam Clegg } 625759631c7SSam Clegg } 626759631c7SSam Clegg 627759631c7SSam Clegg DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 628759631c7SSam Clegg } 629759631c7SSam Clegg 63060ec3034SSam Clegg uint32_t 63160ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) { 63260ec3034SSam Clegg if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) { 633b7787fd0SSam Clegg if (!TypeIndices.count(RelEntry.Symbol)) 634b7787fd0SSam Clegg report_fatal_error("symbol not found in type index space: " + 635b7787fd0SSam Clegg RelEntry.Symbol->getName()); 636acd7d2b0SSam Clegg return TypeIndices[RelEntry.Symbol]; 637acd7d2b0SSam Clegg } 63860ec3034SSam Clegg 63960ec3034SSam Clegg if (!SymbolIndices.count(RelEntry.Symbol)) 6406c899ba6SSam Clegg report_fatal_error("symbol not found in symbol index space: " + 64160ec3034SSam Clegg RelEntry.Symbol->getName()); 64260ec3034SSam Clegg return SymbolIndices[RelEntry.Symbol]; 643acd7d2b0SSam Clegg } 644acd7d2b0SSam Clegg 645d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 646d934cb88SDan Gohman // directly. 647acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations( 648acd7d2b0SSam Clegg ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) { 649acd7d2b0SSam Clegg raw_pwrite_stream &Stream = getStream(); 650d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 651d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 652d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 653d934cb88SDan Gohman RelEntry.Offset; 654d934cb88SDan Gohman 655b7787fd0SSam Clegg DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 65660ec3034SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 65760ec3034SSam Clegg 658acd7d2b0SSam Clegg switch (RelEntry.Type) { 659acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 6609d24fb7fSSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 66160ec3034SSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 66260ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 663d934cb88SDan Gohman WritePatchableLEB(Stream, Value, Offset); 664d934cb88SDan Gohman break; 66560ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 66660ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 6676a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: 6686a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: 669d934cb88SDan Gohman WriteI32(Stream, Value, Offset); 670d934cb88SDan Gohman break; 67160ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 67260ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 67360ec3034SSam Clegg WritePatchableSLEB(Stream, Value, Offset); 67460ec3034SSam Clegg break; 675d934cb88SDan Gohman default: 6769d24fb7fSSam Clegg llvm_unreachable("invalid relocation type"); 677d934cb88SDan Gohman } 678d934cb88SDan Gohman } 67918eafb6cSDan Gohman } 68018eafb6cSDan Gohman 6819e15f359SSam Clegg void WasmObjectWriter::writeTypeSection( 682457fb0b4SSam Clegg ArrayRef<WasmFunctionType> FunctionTypes) { 6839e15f359SSam Clegg if (FunctionTypes.empty()) 6849e15f359SSam Clegg return; 6859e15f359SSam Clegg 6869e15f359SSam Clegg SectionBookkeeping Section; 6879e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TYPE); 6889e15f359SSam Clegg 6899e15f359SSam Clegg encodeULEB128(FunctionTypes.size(), getStream()); 6909e15f359SSam Clegg 6919e15f359SSam Clegg for (const WasmFunctionType &FuncTy : FunctionTypes) { 69203e101f1SSam Clegg write8(wasm::WASM_TYPE_FUNC); 6939e15f359SSam Clegg encodeULEB128(FuncTy.Params.size(), getStream()); 6949e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Params) 6959e15f359SSam Clegg writeValueType(Ty); 6969e15f359SSam Clegg encodeULEB128(FuncTy.Returns.size(), getStream()); 6979e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Returns) 6989e15f359SSam Clegg writeValueType(Ty); 6999e15f359SSam Clegg } 7009e15f359SSam Clegg 7019e15f359SSam Clegg endSection(Section); 7029e15f359SSam Clegg } 7039e15f359SSam Clegg 7048defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports, 705f950b24aSSam Clegg uint32_t DataSize, 706f950b24aSSam Clegg uint32_t NumElements) { 7079e15f359SSam Clegg if (Imports.empty()) 7089e15f359SSam Clegg return; 7099e15f359SSam Clegg 710f950b24aSSam Clegg uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 711f950b24aSSam Clegg 7129e15f359SSam Clegg SectionBookkeeping Section; 7139e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_IMPORT); 7149e15f359SSam Clegg 7159e15f359SSam Clegg encodeULEB128(Imports.size(), getStream()); 7168defa952SSam Clegg for (const wasm::WasmImport &Import : Imports) { 7178defa952SSam Clegg writeString(Import.Module); 7188defa952SSam Clegg writeString(Import.Field); 71903e101f1SSam Clegg write8(Import.Kind); 7209e15f359SSam Clegg 7219e15f359SSam Clegg switch (Import.Kind) { 7229e15f359SSam Clegg case wasm::WASM_EXTERNAL_FUNCTION: 7238defa952SSam Clegg encodeULEB128(Import.SigIndex, getStream()); 7249e15f359SSam Clegg break; 7259e15f359SSam Clegg case wasm::WASM_EXTERNAL_GLOBAL: 72603e101f1SSam Clegg write8(Import.Global.Type); 72703e101f1SSam Clegg write8(Import.Global.Mutable ? 1 : 0); 7289e15f359SSam Clegg break; 729f950b24aSSam Clegg case wasm::WASM_EXTERNAL_MEMORY: 730f950b24aSSam Clegg encodeULEB128(0, getStream()); // flags 731f950b24aSSam Clegg encodeULEB128(NumPages, getStream()); // initial 732f950b24aSSam Clegg break; 733f950b24aSSam Clegg case wasm::WASM_EXTERNAL_TABLE: 73403e101f1SSam Clegg write8(Import.Table.ElemType); 735f950b24aSSam Clegg encodeULEB128(0, getStream()); // flags 736f950b24aSSam Clegg encodeULEB128(NumElements, getStream()); // initial 737f950b24aSSam Clegg break; 7389e15f359SSam Clegg default: 7399e15f359SSam Clegg llvm_unreachable("unsupported import kind"); 7409e15f359SSam Clegg } 7419e15f359SSam Clegg } 7429e15f359SSam Clegg 7439e15f359SSam Clegg endSection(Section); 7449e15f359SSam Clegg } 7459e15f359SSam Clegg 746457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 7479e15f359SSam Clegg if (Functions.empty()) 7489e15f359SSam Clegg return; 7499e15f359SSam Clegg 7509e15f359SSam Clegg SectionBookkeeping Section; 7519e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_FUNCTION); 7529e15f359SSam Clegg 7539e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 7549e15f359SSam Clegg for (const WasmFunction &Func : Functions) 7559e15f359SSam Clegg encodeULEB128(Func.Type, getStream()); 7569e15f359SSam Clegg 7579e15f359SSam Clegg endSection(Section); 7589e15f359SSam Clegg } 7599e15f359SSam Clegg 7607c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() { 7619e15f359SSam Clegg if (Globals.empty()) 7629e15f359SSam Clegg return; 7639e15f359SSam Clegg 7649e15f359SSam Clegg SectionBookkeeping Section; 7659e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_GLOBAL); 7669e15f359SSam Clegg 7679e15f359SSam Clegg encodeULEB128(Globals.size(), getStream()); 7689e15f359SSam Clegg for (const WasmGlobal &Global : Globals) { 7696e7f1826SSam Clegg writeValueType(static_cast<wasm::ValType>(Global.Type.Type)); 7706e7f1826SSam Clegg write8(Global.Type.Mutable); 7719e15f359SSam Clegg 7729e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 7736e7f1826SSam Clegg encodeSLEB128(Global.InitialValue, getStream()); 7749e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 7759e15f359SSam Clegg } 7769e15f359SSam Clegg 7779e15f359SSam Clegg endSection(Section); 7789e15f359SSam Clegg } 7799e15f359SSam Clegg 7808defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) { 7819e15f359SSam Clegg if (Exports.empty()) 7829e15f359SSam Clegg return; 7839e15f359SSam Clegg 7849e15f359SSam Clegg SectionBookkeeping Section; 7859e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_EXPORT); 7869e15f359SSam Clegg 7879e15f359SSam Clegg encodeULEB128(Exports.size(), getStream()); 7888defa952SSam Clegg for (const wasm::WasmExport &Export : Exports) { 7898defa952SSam Clegg writeString(Export.Name); 79003e101f1SSam Clegg write8(Export.Kind); 7919e15f359SSam Clegg encodeULEB128(Export.Index, getStream()); 7929e15f359SSam Clegg } 7939e15f359SSam Clegg 7949e15f359SSam Clegg endSection(Section); 7959e15f359SSam Clegg } 7969e15f359SSam Clegg 797457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 7989e15f359SSam Clegg if (TableElems.empty()) 7999e15f359SSam Clegg return; 8009e15f359SSam Clegg 8019e15f359SSam Clegg SectionBookkeeping Section; 8029e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_ELEM); 8039e15f359SSam Clegg 8049e15f359SSam Clegg encodeULEB128(1, getStream()); // number of "segments" 8059e15f359SSam Clegg encodeULEB128(0, getStream()); // the table index 8069e15f359SSam Clegg 8079e15f359SSam Clegg // init expr for starting offset 8089e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 80930e1bbc1SSam Clegg encodeSLEB128(kInitialTableOffset, getStream()); 8109e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 8119e15f359SSam Clegg 8129e15f359SSam Clegg encodeULEB128(TableElems.size(), getStream()); 8139e15f359SSam Clegg for (uint32_t Elem : TableElems) 8149e15f359SSam Clegg encodeULEB128(Elem, getStream()); 8159e15f359SSam Clegg 8169e15f359SSam Clegg endSection(Section); 8179e15f359SSam Clegg } 8189e15f359SSam Clegg 819457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 820457fb0b4SSam Clegg const MCAsmLayout &Layout, 821457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions) { 8229e15f359SSam Clegg if (Functions.empty()) 8239e15f359SSam Clegg return; 8249e15f359SSam Clegg 8259e15f359SSam Clegg SectionBookkeeping Section; 8269e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CODE); 8276f08c84aSSam Clegg CodeSectionIndex = Section.Index; 8289e15f359SSam Clegg 8299e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 8309e15f359SSam Clegg 8319e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 832fe6414b0SSam Clegg auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 8339e15f359SSam Clegg 8349e15f359SSam Clegg int64_t Size = 0; 8359e15f359SSam Clegg if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 8369e15f359SSam Clegg report_fatal_error(".size expression must be evaluatable"); 8379e15f359SSam Clegg 8389e15f359SSam Clegg encodeULEB128(Size, getStream()); 839fe6414b0SSam Clegg FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset); 8409e15f359SSam Clegg Asm.writeSectionData(&FuncSection, Layout); 8419e15f359SSam Clegg } 8429e15f359SSam Clegg 8439e15f359SSam Clegg // Apply fixups. 844acd7d2b0SSam Clegg applyRelocations(CodeRelocations, Section.ContentsOffset); 8459e15f359SSam Clegg 8469e15f359SSam Clegg endSection(Section); 8479e15f359SSam Clegg } 8489e15f359SSam Clegg 8496c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() { 8506c899ba6SSam Clegg if (DataSegments.empty()) 8517c395943SSam Clegg return; 8529e15f359SSam Clegg 8539e15f359SSam Clegg SectionBookkeeping Section; 8549e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_DATA); 8556f08c84aSSam Clegg DataSectionIndex = Section.Index; 8569e15f359SSam Clegg 8576c899ba6SSam Clegg encodeULEB128(DataSegments.size(), getStream()); // count 8587c395943SSam Clegg 8596c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 8609e15f359SSam Clegg encodeULEB128(0, getStream()); // memory index 8619e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 8627c395943SSam Clegg encodeSLEB128(Segment.Offset, getStream()); // offset 8639e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 8647c395943SSam Clegg encodeULEB128(Segment.Data.size(), getStream()); // size 8657c395943SSam Clegg Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset); 8667c395943SSam Clegg writeBytes(Segment.Data); // data 8677c395943SSam Clegg } 8689e15f359SSam Clegg 8699e15f359SSam Clegg // Apply fixups. 8707c395943SSam Clegg applyRelocations(DataRelocations, Section.ContentsOffset); 8719e15f359SSam Clegg 8729e15f359SSam Clegg endSection(Section); 8739e15f359SSam Clegg } 8749e15f359SSam Clegg 8756f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection( 8766f08c84aSSam Clegg uint32_t SectionIndex, StringRef Name, 8776f08c84aSSam Clegg ArrayRef<WasmRelocationEntry> Relocations) { 8789e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 8799e15f359SSam Clegg // for descriptions of the reloc sections. 8809e15f359SSam Clegg 8816f08c84aSSam Clegg if (Relocations.empty()) 8829e15f359SSam Clegg return; 8839e15f359SSam Clegg 8849e15f359SSam Clegg SectionBookkeeping Section; 8856f08c84aSSam Clegg startCustomSection(Section, std::string("reloc.") + Name.str()); 8869e15f359SSam Clegg 8876f08c84aSSam Clegg raw_pwrite_stream &Stream = getStream(); 8889e15f359SSam Clegg 8896f08c84aSSam Clegg encodeULEB128(SectionIndex, Stream); 8906f08c84aSSam Clegg encodeULEB128(Relocations.size(), Stream); 8916f08c84aSSam Clegg for (const WasmRelocationEntry& RelEntry : Relocations) { 8926f08c84aSSam Clegg uint64_t Offset = RelEntry.Offset + 8936f08c84aSSam Clegg RelEntry.FixupSection->getSectionOffset(); 8946f08c84aSSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 8959e15f359SSam Clegg 8966f08c84aSSam Clegg write8(RelEntry.Type); 8976f08c84aSSam Clegg encodeULEB128(Offset, Stream); 8986f08c84aSSam Clegg encodeULEB128(Index, Stream); 8996f08c84aSSam Clegg if (RelEntry.hasAddend()) 9006f08c84aSSam Clegg encodeSLEB128(RelEntry.Addend, Stream); 9019e15f359SSam Clegg } 9029e15f359SSam Clegg 9039e15f359SSam Clegg endSection(Section); 9049e15f359SSam Clegg } 9059e15f359SSam Clegg 9066a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() { 9076a31a0d6SSam Clegg for (const auto &Sec : CustomSections) { 9086a31a0d6SSam Clegg auto &Relocations = CustomSectionsRelocations[Sec.Section]; 9096a31a0d6SSam Clegg writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations); 9106a31a0d6SSam Clegg } 9116a31a0d6SSam Clegg } 9126a31a0d6SSam Clegg 9139e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection( 91486b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 915ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 916ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) { 9179e15f359SSam Clegg SectionBookkeeping Section; 9182322a937SSam Clegg startCustomSection(Section, "linking"); 9196bb5a41fSSam Clegg encodeULEB128(wasm::WasmMetadataVersion, getStream()); 9209e15f359SSam Clegg 9216bb5a41fSSam Clegg SectionBookkeeping SubSection; 9226c899ba6SSam Clegg if (SymbolInfos.size() != 0) { 9236c899ba6SSam Clegg startSection(SubSection, wasm::WASM_SYMBOL_TABLE); 9246c899ba6SSam Clegg encodeULEB128(SymbolInfos.size(), getStream()); 9256c899ba6SSam Clegg for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) { 9266c899ba6SSam Clegg encodeULEB128(Sym.Kind, getStream()); 9276c899ba6SSam Clegg encodeULEB128(Sym.Flags, getStream()); 9286c899ba6SSam Clegg switch (Sym.Kind) { 9296c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_FUNCTION: 9306c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_GLOBAL: 9316c899ba6SSam Clegg encodeULEB128(Sym.ElementIndex, getStream()); 9326c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) 9336c899ba6SSam Clegg writeString(Sym.Name); 9346c899ba6SSam Clegg break; 9356c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_DATA: 9366c899ba6SSam Clegg writeString(Sym.Name); 9376c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) { 9386c899ba6SSam Clegg encodeULEB128(Sym.DataRef.Segment, getStream()); 9396c899ba6SSam Clegg encodeULEB128(Sym.DataRef.Offset, getStream()); 9406c899ba6SSam Clegg encodeULEB128(Sym.DataRef.Size, getStream()); 9416c899ba6SSam Clegg } 9426c899ba6SSam Clegg break; 9436a31a0d6SSam Clegg case wasm::WASM_SYMBOL_TYPE_SECTION: { 9446a31a0d6SSam Clegg const uint32_t SectionIndex = 9456a31a0d6SSam Clegg CustomSections[Sym.ElementIndex].OutputIndex; 9466a31a0d6SSam Clegg encodeULEB128(SectionIndex, getStream()); 9476a31a0d6SSam Clegg break; 9486a31a0d6SSam Clegg } 9496c899ba6SSam Clegg default: 9506c899ba6SSam Clegg llvm_unreachable("unexpected kind"); 9516c899ba6SSam Clegg } 952b7787fd0SSam Clegg } 953b7787fd0SSam Clegg endSection(SubSection); 954b7787fd0SSam Clegg } 9559e15f359SSam Clegg 9566c899ba6SSam Clegg if (DataSegments.size()) { 95763ebb813SSam Clegg startSection(SubSection, wasm::WASM_SEGMENT_INFO); 9586c899ba6SSam Clegg encodeULEB128(DataSegments.size(), getStream()); 9596c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 960d95ed959SSam Clegg writeString(Segment.Name); 96163ebb813SSam Clegg encodeULEB128(Segment.Alignment, getStream()); 96263ebb813SSam Clegg encodeULEB128(Segment.Flags, getStream()); 96363ebb813SSam Clegg } 964d95ed959SSam Clegg endSection(SubSection); 965d95ed959SSam Clegg } 966d95ed959SSam Clegg 967bafe6902SSam Clegg if (!InitFuncs.empty()) { 968bafe6902SSam Clegg startSection(SubSection, wasm::WASM_INIT_FUNCS); 969bafe6902SSam Clegg encodeULEB128(InitFuncs.size(), getStream()); 970bafe6902SSam Clegg for (auto &StartFunc : InitFuncs) { 971bafe6902SSam Clegg encodeULEB128(StartFunc.first, getStream()); // priority 972bafe6902SSam Clegg encodeULEB128(StartFunc.second, getStream()); // function index 973bafe6902SSam Clegg } 974bafe6902SSam Clegg endSection(SubSection); 975bafe6902SSam Clegg } 976bafe6902SSam Clegg 977ea7caceeSSam Clegg if (Comdats.size()) { 978ea7caceeSSam Clegg startSection(SubSection, wasm::WASM_COMDAT_INFO); 979ea7caceeSSam Clegg encodeULEB128(Comdats.size(), getStream()); 980ea7caceeSSam Clegg for (const auto &C : Comdats) { 981ea7caceeSSam Clegg writeString(C.first); 982ea7caceeSSam Clegg encodeULEB128(0, getStream()); // flags for future use 983ea7caceeSSam Clegg encodeULEB128(C.second.size(), getStream()); 984ea7caceeSSam Clegg for (const WasmComdatEntry &Entry : C.second) { 985ea7caceeSSam Clegg encodeULEB128(Entry.Kind, getStream()); 986ea7caceeSSam Clegg encodeULEB128(Entry.Index, getStream()); 987ea7caceeSSam Clegg } 988ea7caceeSSam Clegg } 989ea7caceeSSam Clegg endSection(SubSection); 990ea7caceeSSam Clegg } 991ea7caceeSSam Clegg 9929e15f359SSam Clegg endSection(Section); 9939e15f359SSam Clegg } 9949e15f359SSam Clegg 9956a31a0d6SSam Clegg void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm, 9966a31a0d6SSam Clegg const MCAsmLayout &Layout) { 9976a31a0d6SSam Clegg for (auto &CustomSection : CustomSections) { 998cfd44a2eSSam Clegg SectionBookkeeping Section; 9996a31a0d6SSam Clegg auto *Sec = CustomSection.Section; 10002322a937SSam Clegg startCustomSection(Section, CustomSection.Name); 10016a31a0d6SSam Clegg 10026a31a0d6SSam Clegg Sec->setSectionOffset(getStream().tell() - Section.ContentsOffset); 10036a31a0d6SSam Clegg Asm.writeSectionData(Sec, Layout); 10046a31a0d6SSam Clegg 10056a31a0d6SSam Clegg CustomSection.OutputContentsOffset = Section.ContentsOffset; 10066a31a0d6SSam Clegg CustomSection.OutputIndex = Section.Index; 10076a31a0d6SSam Clegg 1008cfd44a2eSSam Clegg endSection(Section); 1009cfd44a2eSSam Clegg } 1010cfd44a2eSSam Clegg } 1011cfd44a2eSSam Clegg 10126a31a0d6SSam Clegg void WasmObjectWriter::updateCustomSectionRelocations( 10136a31a0d6SSam Clegg const SmallVector<WasmFunction, 4> &Functions, const MCAsmLayout &Layout) { 10146a31a0d6SSam Clegg std::map<const MCSection *, const MCSymbolWasm *> SectionSymbols; 10156a31a0d6SSam Clegg for (const auto &P : CustomSectionSymbols) 10166a31a0d6SSam Clegg SectionSymbols[P.second] = P.first; 10176a31a0d6SSam Clegg std::map<const MCSection *, const MCSymbolWasm *> FuncSymbols; 10186a31a0d6SSam Clegg for (const auto &FuncInfo : Functions) 10196a31a0d6SSam Clegg FuncSymbols[&FuncInfo.Sym->getSection()] = FuncInfo.Sym; 10206a31a0d6SSam Clegg 10216a31a0d6SSam Clegg // Patch relocation records for R_WEBASSEMBLY_FUNCTION_OFFSET_I32 and 10226a31a0d6SSam Clegg // R_WEBASSEMBLY_SECTION_OFFSET_I32. The Addend is stuffed the offset from 10236a31a0d6SSam Clegg // the beginning of the function or custom section -- all such relocations 10246a31a0d6SSam Clegg // target the function or custom section starts. 10256a31a0d6SSam Clegg for (auto &Section : CustomSections) { 10266a31a0d6SSam Clegg auto &Relocations = CustomSectionsRelocations[Section.Section]; 10276a31a0d6SSam Clegg for (WasmRelocationEntry &RelEntry : Relocations) { 10286a31a0d6SSam Clegg switch (RelEntry.Type) { 10296a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: { 10306a31a0d6SSam Clegg assert(RelEntry.hasAddend()); 10316a31a0d6SSam Clegg auto &Section = 10326a31a0d6SSam Clegg static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection()); 10336a31a0d6SSam Clegg RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol); 10346a31a0d6SSam Clegg RelEntry.Symbol = FuncSymbols[&Section]; 10356a31a0d6SSam Clegg break; 10366a31a0d6SSam Clegg } 10376a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: { 10386a31a0d6SSam Clegg assert(RelEntry.hasAddend()); 10396a31a0d6SSam Clegg auto &Section = 10406a31a0d6SSam Clegg static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection()); 10416a31a0d6SSam Clegg RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol); 10426a31a0d6SSam Clegg RelEntry.Symbol = SectionSymbols[&Section]; 10436a31a0d6SSam Clegg break; 10446a31a0d6SSam Clegg } 10456a31a0d6SSam Clegg default: 10466a31a0d6SSam Clegg break; 10476a31a0d6SSam Clegg } 10486a31a0d6SSam Clegg } 10496a31a0d6SSam Clegg 10506a31a0d6SSam Clegg // Apply fixups. 10516a31a0d6SSam Clegg applyRelocations(Relocations, Section.OutputContentsOffset); 10526a31a0d6SSam Clegg } 10536a31a0d6SSam Clegg } 10546a31a0d6SSam Clegg 10555e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) { 10565e3d33a7SSam Clegg assert(Symbol.isFunction()); 10575e3d33a7SSam Clegg assert(TypeIndices.count(&Symbol)); 10585e3d33a7SSam Clegg return TypeIndices[&Symbol]; 10595e3d33a7SSam Clegg } 10605e3d33a7SSam Clegg 10615e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) { 10625e3d33a7SSam Clegg assert(Symbol.isFunction()); 10635e3d33a7SSam Clegg 10645e3d33a7SSam Clegg WasmFunctionType F; 1065aff1c4dfSSam Clegg const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol); 10665e3d33a7SSam Clegg F.Returns = ResolvedSym->getReturns(); 10675e3d33a7SSam Clegg F.Params = ResolvedSym->getParams(); 10685e3d33a7SSam Clegg 10695e3d33a7SSam Clegg auto Pair = 10705e3d33a7SSam Clegg FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); 10715e3d33a7SSam Clegg if (Pair.second) 10725e3d33a7SSam Clegg FunctionTypes.push_back(F); 10735e3d33a7SSam Clegg TypeIndices[&Symbol] = Pair.first->second; 10745e3d33a7SSam Clegg 10755e3d33a7SSam Clegg DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n"); 10765e3d33a7SSam Clegg DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 10775e3d33a7SSam Clegg return Pair.first->second; 10785e3d33a7SSam Clegg } 10795e3d33a7SSam Clegg 108018eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm, 108118eafb6cSDan Gohman const MCAsmLayout &Layout) { 1082b7787fd0SSam Clegg DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 108382607f56SDan Gohman MCContext &Ctx = Asm.getContext(); 1084d934cb88SDan Gohman 1085d934cb88SDan Gohman // Collect information from the available symbols. 1086d934cb88SDan Gohman SmallVector<WasmFunction, 4> Functions; 1087d934cb88SDan Gohman SmallVector<uint32_t, 4> TableElems; 10888defa952SSam Clegg SmallVector<wasm::WasmImport, 4> Imports; 10898defa952SSam Clegg SmallVector<wasm::WasmExport, 4> Exports; 10906c899ba6SSam Clegg SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos; 1091bafe6902SSam Clegg SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 1092ea7caceeSSam Clegg std::map<StringRef, std::vector<WasmComdatEntry>> Comdats; 10937c395943SSam Clegg uint32_t DataSize = 0; 1094d934cb88SDan Gohman 1095f950b24aSSam Clegg // For now, always emit the memory import, since loads and stores are not 1096f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1097f950b24aSSam Clegg // it if there are no loads or stores. 1098f950b24aSSam Clegg MCSymbolWasm *MemorySym = 1099f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory")); 11008defa952SSam Clegg wasm::WasmImport MemImport; 11018defa952SSam Clegg MemImport.Module = MemorySym->getModuleName(); 11028defa952SSam Clegg MemImport.Field = MemorySym->getName(); 1103f950b24aSSam Clegg MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1104f950b24aSSam Clegg Imports.push_back(MemImport); 1105f950b24aSSam Clegg 1106f950b24aSSam Clegg // For now, always emit the table section, since indirect calls are not 1107f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1108f950b24aSSam Clegg // it if there are no indirect calls. 1109f950b24aSSam Clegg MCSymbolWasm *TableSym = 1110f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table")); 11118defa952SSam Clegg wasm::WasmImport TableImport; 11128defa952SSam Clegg TableImport.Module = TableSym->getModuleName(); 11138defa952SSam Clegg TableImport.Field = TableSym->getName(); 1114f950b24aSSam Clegg TableImport.Kind = wasm::WASM_EXTERNAL_TABLE; 11158defa952SSam Clegg TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC; 1116f950b24aSSam Clegg Imports.push_back(TableImport); 1117f950b24aSSam Clegg 1118586320c0SNicholas Wilson // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined 1119586320c0SNicholas Wilson // symbols. This must be done before populating WasmIndices for defined 1120586320c0SNicholas Wilson // symbols. 112132ce5ca0SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 112232ce5ca0SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 112332ce5ca0SDan Gohman 112432ce5ca0SDan Gohman // Register types for all functions, including those with private linkage 11259f3fe42eSSam Clegg // (because wasm always needs a type signature). 112632ce5ca0SDan Gohman if (WS.isFunction()) 112732ce5ca0SDan Gohman registerFunctionType(WS); 112832ce5ca0SDan Gohman 112932ce5ca0SDan Gohman if (WS.isTemporary()) 113032ce5ca0SDan Gohman continue; 113132ce5ca0SDan Gohman 113232ce5ca0SDan Gohman // If the symbol is not defined in this translation unit, import it. 11336c899ba6SSam Clegg if (!WS.isDefined() && !WS.isComdat()) { 11346c899ba6SSam Clegg if (WS.isFunction()) { 11358defa952SSam Clegg wasm::WasmImport Import; 11368defa952SSam Clegg Import.Module = WS.getModuleName(); 11378defa952SSam Clegg Import.Field = WS.getName(); 113832ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 11398defa952SSam Clegg Import.SigIndex = getFunctionType(WS); 11406c899ba6SSam Clegg Imports.push_back(Import); 11416c899ba6SSam Clegg WasmIndices[&WS] = NumFunctionImports++; 11426c899ba6SSam Clegg } else if (WS.isGlobal()) { 114315f349f7SNicholas Wilson if (WS.isWeak()) 114415f349f7SNicholas Wilson report_fatal_error("undefined global symbol cannot be weak"); 114515f349f7SNicholas Wilson 11466c899ba6SSam Clegg wasm::WasmImport Import; 11476c899ba6SSam Clegg Import.Module = WS.getModuleName(); 11486c899ba6SSam Clegg Import.Field = WS.getName(); 114932ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 11506c899ba6SSam Clegg Import.Global = WS.getGlobalType(); 11516c899ba6SSam Clegg Imports.push_back(Import); 11526c899ba6SSam Clegg WasmIndices[&WS] = NumGlobalImports++; 115332ce5ca0SDan Gohman } 115432ce5ca0SDan Gohman } 115532ce5ca0SDan Gohman } 115632ce5ca0SDan Gohman 1157586320c0SNicholas Wilson // Populate DataSegments, which must be done before populating DataLocations. 1158759631c7SSam Clegg for (MCSection &Sec : Asm) { 1159759631c7SSam Clegg auto &Section = static_cast<MCSectionWasm &>(Sec); 1160cfd44a2eSSam Clegg 11616a31a0d6SSam Clegg if (Section.getSectionName().startswith(".custom_section.")) { 1162cfd44a2eSSam Clegg if (Section.getFragmentList().empty()) 1163cfd44a2eSSam Clegg continue; 1164cfd44a2eSSam Clegg if (Section.getFragmentList().size() != 1) 1165cfd44a2eSSam Clegg report_fatal_error( 1166cfd44a2eSSam Clegg "only one .custom_section section fragment supported"); 1167cfd44a2eSSam Clegg const MCFragment &Frag = *Section.begin(); 1168cfd44a2eSSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1169cfd44a2eSSam Clegg report_fatal_error("only data supported in .custom_section section"); 1170cfd44a2eSSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1171cfd44a2eSSam Clegg if (!DataFrag.getFixups().empty()) 1172cfd44a2eSSam Clegg report_fatal_error("fixups not supported in .custom_section section"); 1173cfd44a2eSSam Clegg StringRef UserName = Section.getSectionName().substr(16); 11746a31a0d6SSam Clegg CustomSections.emplace_back(UserName, &Section); 1175cfd44a2eSSam Clegg continue; 1176cfd44a2eSSam Clegg } 1177cfd44a2eSSam Clegg 117812fd3da9SSam Clegg if (!Section.isWasmData()) 1179759631c7SSam Clegg continue; 1180759631c7SSam Clegg 1181bafe6902SSam Clegg // .init_array sections are handled specially elsewhere. 1182bafe6902SSam Clegg if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array")) 1183bafe6902SSam Clegg continue; 1184bafe6902SSam Clegg 1185329e76d5SSam Clegg uint32_t SegmentIndex = DataSegments.size(); 1186759631c7SSam Clegg DataSize = alignTo(DataSize, Section.getAlignment()); 1187759631c7SSam Clegg DataSegments.emplace_back(); 1188759631c7SSam Clegg WasmDataSegment &Segment = DataSegments.back(); 1189d95ed959SSam Clegg Segment.Name = Section.getSectionName(); 1190759631c7SSam Clegg Segment.Offset = DataSize; 1191759631c7SSam Clegg Segment.Section = &Section; 119263ebb813SSam Clegg addData(Segment.Data, Section); 119363ebb813SSam Clegg Segment.Alignment = Section.getAlignment(); 119463ebb813SSam Clegg Segment.Flags = 0; 1195759631c7SSam Clegg DataSize += Segment.Data.size(); 11966c899ba6SSam Clegg Section.setSegmentIndex(SegmentIndex); 1197ea7caceeSSam Clegg 1198ea7caceeSSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 1199ea7caceeSSam Clegg Comdats[C->getName()].emplace_back( 1200329e76d5SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex}); 1201ea7caceeSSam Clegg } 1202759631c7SSam Clegg } 1203759631c7SSam Clegg 12046a31a0d6SSam Clegg // Create symbols for debug/custom sections. 12056a31a0d6SSam Clegg for (MCSection &Sec : Asm) { 12066a31a0d6SSam Clegg auto &DebugSection = static_cast<MCSectionWasm &>(Sec); 12076a31a0d6SSam Clegg StringRef SectionName = DebugSection.getSectionName(); 12086a31a0d6SSam Clegg 12096a31a0d6SSam Clegg // TODO: Add support for non-debug metadata sections? 12106a31a0d6SSam Clegg if (!Sec.getKind().isMetadata() || !SectionName.startswith(".debug_")) 12116a31a0d6SSam Clegg continue; 12126a31a0d6SSam Clegg 12136a31a0d6SSam Clegg uint32_t ElementIndex = CustomSections.size(); 12146a31a0d6SSam Clegg CustomSections.emplace_back(SectionName, &DebugSection); 12156a31a0d6SSam Clegg 12166a31a0d6SSam Clegg MCSymbolWasm *SectionSym = 12176a31a0d6SSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SectionName)); 12186a31a0d6SSam Clegg CustomSectionSymbols[SectionSym] = &DebugSection; 12196a31a0d6SSam Clegg 12206a31a0d6SSam Clegg wasm::WasmSymbolInfo Info; 12216a31a0d6SSam Clegg Info.Name = SectionSym->getName(); 12226a31a0d6SSam Clegg Info.Kind = wasm::WASM_SYMBOL_TYPE_SECTION; 1223*d5504a0aSSam Clegg Info.Flags = wasm::WASM_SYMBOL_BINDING_LOCAL; 12246a31a0d6SSam Clegg Info.ElementIndex = ElementIndex; 12256a31a0d6SSam Clegg SymbolIndices[SectionSym] = SymbolInfos.size(); 12266a31a0d6SSam Clegg SymbolInfos.emplace_back(Info); 12276a31a0d6SSam Clegg } 12286a31a0d6SSam Clegg 1229586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for defined symbols. 1230d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1231d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1232d934cb88SDan Gohman // or used in relocations. 1233d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 1234d934cb88SDan Gohman continue; 1235b7787fd0SSam Clegg 1236d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 1237b7787fd0SSam Clegg DEBUG(dbgs() << "MCSymbol: '" << S << "'" 1238329e76d5SSam Clegg << " isDefined=" << S.isDefined() 1239329e76d5SSam Clegg << " isExternal=" << S.isExternal() 1240329e76d5SSam Clegg << " isTemporary=" << S.isTemporary() 1241b7787fd0SSam Clegg << " isFunction=" << WS.isFunction() 1242b7787fd0SSam Clegg << " isWeak=" << WS.isWeak() 1243a2b35dacSSam Clegg << " isHidden=" << WS.isHidden() 1244b7787fd0SSam Clegg << " isVariable=" << WS.isVariable() << "\n"); 1245b7787fd0SSam Clegg 12465e3d33a7SSam Clegg if (WS.isVariable()) 12475e3d33a7SSam Clegg continue; 12486c899ba6SSam Clegg if (WS.isComdat() && !WS.isDefined()) 12496c899ba6SSam Clegg continue; 1250b7787fd0SSam Clegg 1251d934cb88SDan Gohman if (WS.isFunction()) { 12526c899ba6SSam Clegg unsigned Index; 1253cd65f698SSam Clegg if (WS.isDefined()) { 1254b7787fd0SSam Clegg if (WS.getOffset() != 0) 1255b7787fd0SSam Clegg report_fatal_error( 1256b7787fd0SSam Clegg "function sections must contain one function each"); 1257b7787fd0SSam Clegg 1258b7787fd0SSam Clegg if (WS.getSize() == 0) 1259b7787fd0SSam Clegg report_fatal_error( 1260b7787fd0SSam Clegg "function symbols must have a size set with .size"); 1261b7787fd0SSam Clegg 12626c899ba6SSam Clegg // A definition. Write out the function body. 12639f3fe42eSSam Clegg Index = NumFunctionImports + Functions.size(); 1264d934cb88SDan Gohman WasmFunction Func; 12655e3d33a7SSam Clegg Func.Type = getFunctionType(WS); 1266d934cb88SDan Gohman Func.Sym = &WS; 12676c899ba6SSam Clegg WasmIndices[&WS] = Index; 1268d934cb88SDan Gohman Functions.push_back(Func); 12696c899ba6SSam Clegg 12706c899ba6SSam Clegg auto &Section = static_cast<MCSectionWasm &>(WS.getSection()); 12716c899ba6SSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 12726c899ba6SSam Clegg Comdats[C->getName()].emplace_back( 12736c899ba6SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index}); 12746c899ba6SSam Clegg } 1275d934cb88SDan Gohman } else { 1276d934cb88SDan Gohman // An import; the index was assigned above. 12776c899ba6SSam Clegg Index = WasmIndices.find(&WS)->second; 1278d934cb88SDan Gohman } 1279d934cb88SDan Gohman 12805e3d33a7SSam Clegg DEBUG(dbgs() << " -> function index: " << Index << "\n"); 12816c899ba6SSam Clegg } else if (WS.isData()) { 1282c38e947eSSam Clegg if (WS.isTemporary() && !WS.getSize()) 1283c38e947eSSam Clegg continue; 1284c38e947eSSam Clegg 12856c899ba6SSam Clegg if (!WS.isDefined()) { 12866c899ba6SSam Clegg DEBUG(dbgs() << " -> segment index: -1"); 1287fe6414b0SSam Clegg continue; 12886c899ba6SSam Clegg } 1289fe6414b0SSam Clegg 1290d934cb88SDan Gohman if (!WS.getSize()) 1291c38e947eSSam Clegg report_fatal_error("data symbols must have a size set with .size: " + 1292c38e947eSSam Clegg WS.getName()); 1293d934cb88SDan Gohman 1294d934cb88SDan Gohman int64_t Size = 0; 1295d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1296d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 1297d934cb88SDan Gohman 1298759631c7SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1299ea7caceeSSam Clegg assert(DataSection.isWasmData()); 13007c395943SSam Clegg 13016c899ba6SSam Clegg // For each data symbol, export it in the symtab as a reference to the 13026c899ba6SSam Clegg // corresponding Wasm data segment. 13036c899ba6SSam Clegg wasm::WasmDataReference Ref = wasm::WasmDataReference{ 13046c899ba6SSam Clegg DataSection.getSegmentIndex(), 13056c899ba6SSam Clegg static_cast<uint32_t>(Layout.getSymbolOffset(WS)), 13066c899ba6SSam Clegg static_cast<uint32_t>(Size)}; 13076c899ba6SSam Clegg DataLocations[&WS] = Ref; 13086c899ba6SSam Clegg DEBUG(dbgs() << " -> segment index: " << Ref.Segment); 13096c899ba6SSam Clegg } else { 13106c899ba6SSam Clegg // A "true" Wasm global (currently just __stack_pointer) 1311545932beSEric Christopher if (WS.isDefined()) 13126c899ba6SSam Clegg report_fatal_error("don't yet support defined globals"); 13136c899ba6SSam Clegg 1314545932beSEric Christopher // An import; the index was assigned above 1315545932beSEric Christopher DEBUG(dbgs() << " -> global index: " << WasmIndices.find(&WS)->second 1316545932beSEric Christopher << "\n"); 1317d934cb88SDan Gohman } 1318d934cb88SDan Gohman } 1319d934cb88SDan Gohman 1320586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for aliased symbols. We need to 1321586320c0SNicholas Wilson // process these in a separate pass because we need to have processed the 1322586320c0SNicholas Wilson // target of the alias before the alias itself and the symbols are not 1323586320c0SNicholas Wilson // necessarily ordered in this way. 1324b7787fd0SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1325b7787fd0SSam Clegg if (!S.isVariable()) 1326b7787fd0SSam Clegg continue; 132731a2c809SSam Clegg 1328cd65f698SSam Clegg assert(S.isDefined()); 1329b7787fd0SSam Clegg 13305e3d33a7SSam Clegg // Find the target symbol of this weak alias and export that index 1331aff1c4dfSSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 1332aff1c4dfSSam Clegg const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS); 13335e3d33a7SSam Clegg DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n"); 1334b7787fd0SSam Clegg 13356c899ba6SSam Clegg if (WS.isFunction()) { 13366c899ba6SSam Clegg assert(WasmIndices.count(ResolvedSym) > 0); 13376c899ba6SSam Clegg uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second; 13386c899ba6SSam Clegg WasmIndices[&WS] = WasmIndex; 13396c899ba6SSam Clegg DEBUG(dbgs() << " -> index:" << WasmIndex << "\n"); 13406c899ba6SSam Clegg } else if (WS.isData()) { 13416c899ba6SSam Clegg assert(DataLocations.count(ResolvedSym) > 0); 13426c899ba6SSam Clegg const wasm::WasmDataReference &Ref = 13436c899ba6SSam Clegg DataLocations.find(ResolvedSym)->second; 13446c899ba6SSam Clegg DataLocations[&WS] = Ref; 13456c899ba6SSam Clegg DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n"); 13466c899ba6SSam Clegg } else { 13476c899ba6SSam Clegg report_fatal_error("don't yet support global aliases"); 13486c899ba6SSam Clegg } 1349586320c0SNicholas Wilson } 135031a2c809SSam Clegg 1351586320c0SNicholas Wilson // Finally, populate the symbol table itself, in its "natural" order. 1352586320c0SNicholas Wilson for (const MCSymbol &S : Asm.symbols()) { 1353586320c0SNicholas Wilson const auto &WS = static_cast<const MCSymbolWasm &>(S); 1354586320c0SNicholas Wilson if (WS.isTemporary() && WS.getName().empty()) 1355586320c0SNicholas Wilson continue; 1356586320c0SNicholas Wilson if (WS.isComdat() && !WS.isDefined()) 1357586320c0SNicholas Wilson continue; 1358586320c0SNicholas Wilson if (WS.isTemporary() && WS.isData() && !WS.getSize()) 1359586320c0SNicholas Wilson continue; 1360586320c0SNicholas Wilson 1361586320c0SNicholas Wilson uint32_t Flags = 0; 1362586320c0SNicholas Wilson if (WS.isWeak()) 1363586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_WEAK; 1364586320c0SNicholas Wilson if (WS.isHidden()) 1365586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN; 1366586320c0SNicholas Wilson if (!WS.isExternal() && WS.isDefined()) 1367586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL; 1368586320c0SNicholas Wilson if (WS.isUndefined()) 1369586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_UNDEFINED; 1370586320c0SNicholas Wilson 1371586320c0SNicholas Wilson wasm::WasmSymbolInfo Info; 1372586320c0SNicholas Wilson Info.Name = WS.getName(); 1373586320c0SNicholas Wilson Info.Kind = WS.getType(); 1374586320c0SNicholas Wilson Info.Flags = Flags; 1375586320c0SNicholas Wilson if (!WS.isData()) 1376586320c0SNicholas Wilson Info.ElementIndex = WasmIndices.find(&WS)->second; 1377586320c0SNicholas Wilson else if (WS.isDefined()) 1378586320c0SNicholas Wilson Info.DataRef = DataLocations.find(&WS)->second; 1379586320c0SNicholas Wilson SymbolIndices[&WS] = SymbolInfos.size(); 1380586320c0SNicholas Wilson SymbolInfos.emplace_back(Info); 1381b7787fd0SSam Clegg } 1382b7787fd0SSam Clegg 13836006e091SSam Clegg { 13846006e091SSam Clegg auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 1385f9edbe95SSam Clegg // Functions referenced by a relocation need to put in the table. This is 1386f9edbe95SSam Clegg // purely to make the object file's provisional values readable, and is 1387f9edbe95SSam Clegg // ignored by the linker, which re-calculates the relocations itself. 1388f9edbe95SSam Clegg if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 && 1389f9edbe95SSam Clegg Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB) 1390f9edbe95SSam Clegg return; 1391f9edbe95SSam Clegg assert(Rel.Symbol->isFunction()); 1392f9edbe95SSam Clegg const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol); 13936c899ba6SSam Clegg uint32_t FunctionIndex = WasmIndices.find(&WS)->second; 1394f9edbe95SSam Clegg uint32_t TableIndex = TableElems.size() + kInitialTableOffset; 1395f9edbe95SSam Clegg if (TableIndices.try_emplace(&WS, TableIndex).second) { 1396329e76d5SSam Clegg DEBUG(dbgs() << " -> adding " << WS.getName() 1397f9edbe95SSam Clegg << " to table: " << TableIndex << "\n"); 13986c899ba6SSam Clegg TableElems.push_back(FunctionIndex); 13996006e091SSam Clegg registerFunctionType(WS); 14006006e091SSam Clegg } 14016006e091SSam Clegg }; 1402970d02c4SDan Gohman 14036006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : CodeRelocations) 14046006e091SSam Clegg HandleReloc(RelEntry); 14056006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : DataRelocations) 14066006e091SSam Clegg HandleReloc(RelEntry); 1407d934cb88SDan Gohman } 1408d934cb88SDan Gohman 1409bafe6902SSam Clegg // Translate .init_array section contents into start functions. 1410bafe6902SSam Clegg for (const MCSection &S : Asm) { 1411bafe6902SSam Clegg const auto &WS = static_cast<const MCSectionWasm &>(S); 1412bafe6902SSam Clegg if (WS.getSectionName().startswith(".fini_array")) 1413bafe6902SSam Clegg report_fatal_error(".fini_array sections are unsupported"); 1414bafe6902SSam Clegg if (!WS.getSectionName().startswith(".init_array")) 1415bafe6902SSam Clegg continue; 1416bafe6902SSam Clegg if (WS.getFragmentList().empty()) 1417bafe6902SSam Clegg continue; 1418bafe6902SSam Clegg if (WS.getFragmentList().size() != 2) 1419bafe6902SSam Clegg report_fatal_error("only one .init_array section fragment supported"); 1420bafe6902SSam Clegg const MCFragment &AlignFrag = *WS.begin(); 1421bafe6902SSam Clegg if (AlignFrag.getKind() != MCFragment::FT_Align) 1422bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned"); 1423bafe6902SSam Clegg if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1424bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned for pointers"); 1425bafe6902SSam Clegg const MCFragment &Frag = *std::next(WS.begin()); 1426bafe6902SSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1427bafe6902SSam Clegg report_fatal_error("only data supported in .init_array section"); 1428bafe6902SSam Clegg uint16_t Priority = UINT16_MAX; 1429bafe6902SSam Clegg if (WS.getSectionName().size() != 11) { 1430bafe6902SSam Clegg if (WS.getSectionName()[11] != '.') 1431bafe6902SSam Clegg report_fatal_error(".init_array section priority should start with '.'"); 1432bafe6902SSam Clegg if (WS.getSectionName().substr(12).getAsInteger(10, Priority)) 1433bafe6902SSam Clegg report_fatal_error("invalid .init_array section priority"); 1434bafe6902SSam Clegg } 1435bafe6902SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1436bafe6902SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1437bafe6902SSam Clegg for (const uint8_t *p = (const uint8_t *)Contents.data(), 1438bafe6902SSam Clegg *end = (const uint8_t *)Contents.data() + Contents.size(); 1439bafe6902SSam Clegg p != end; ++p) { 1440bafe6902SSam Clegg if (*p != 0) 1441bafe6902SSam Clegg report_fatal_error("non-symbolic data in .init_array section"); 1442bafe6902SSam Clegg } 1443bafe6902SSam Clegg for (const MCFixup &Fixup : DataFrag.getFixups()) { 1444bafe6902SSam Clegg assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1445bafe6902SSam Clegg const MCExpr *Expr = Fixup.getValue(); 1446bafe6902SSam Clegg auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr); 1447bafe6902SSam Clegg if (!Sym) 1448bafe6902SSam Clegg report_fatal_error("fixups in .init_array should be symbol references"); 1449bafe6902SSam Clegg if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION) 1450bafe6902SSam Clegg report_fatal_error("symbols in .init_array should be for functions"); 1451bafe6902SSam Clegg auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol())); 1452bafe6902SSam Clegg if (I == SymbolIndices.end()) 1453bafe6902SSam Clegg report_fatal_error("symbols in .init_array should be defined"); 1454bafe6902SSam Clegg uint32_t Index = I->second; 1455bafe6902SSam Clegg InitFuncs.push_back(std::make_pair(Priority, Index)); 1456bafe6902SSam Clegg } 1457bafe6902SSam Clegg } 1458bafe6902SSam Clegg 145918eafb6cSDan Gohman // Write out the Wasm header. 146018eafb6cSDan Gohman writeHeader(Asm); 146118eafb6cSDan Gohman 14629e15f359SSam Clegg writeTypeSection(FunctionTypes); 1463f950b24aSSam Clegg writeImportSection(Imports, DataSize, TableElems.size()); 14649e15f359SSam Clegg writeFunctionSection(Functions); 1465f950b24aSSam Clegg // Skip the "table" section; we import the table instead. 1466f950b24aSSam Clegg // Skip the "memory" section; we import the memory instead. 14677c395943SSam Clegg writeGlobalSection(); 14689e15f359SSam Clegg writeExportSection(Exports); 14699e15f359SSam Clegg writeElemSection(TableElems); 1470acd7d2b0SSam Clegg writeCodeSection(Asm, Layout, Functions); 14716c899ba6SSam Clegg writeDataSection(); 14726a31a0d6SSam Clegg writeCustomSections(Asm, Layout); 14736a31a0d6SSam Clegg updateCustomSectionRelocations(Functions, Layout); 1474c22bfb6bSNicholas Wilson writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats); 14756f08c84aSSam Clegg writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations); 14766f08c84aSSam Clegg writeRelocSection(DataSectionIndex, "DATA", DataRelocations); 14776a31a0d6SSam Clegg writeCustomRelocSections(); 1478970d02c4SDan Gohman 1479d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 148018eafb6cSDan Gohman } 148118eafb6cSDan Gohman 148260fbc7ccSLang Hames std::unique_ptr<MCObjectWriter> 14831301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 148418eafb6cSDan Gohman raw_pwrite_stream &OS) { 14850917c9e4SDan Gohman return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS); 148618eafb6cSDan Gohman } 1487