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" 17432a3883SNico Weber #include "llvm/Config/llvm-config.h" 1818eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h" 1918eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h" 2018eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h" 2118eafb6cSDan Gohman #include "llvm/MC/MCContext.h" 2218eafb6cSDan Gohman #include "llvm/MC/MCExpr.h" 2318eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h" 2418eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h" 2518eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h" 2618eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h" 2718eafb6cSDan Gohman #include "llvm/MC/MCValue.h" 2818eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h" 29d934cb88SDan Gohman #include "llvm/Support/Casting.h" 3018eafb6cSDan Gohman #include "llvm/Support/Debug.h" 3118eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h" 32d934cb88SDan Gohman #include "llvm/Support/LEB128.h" 3318eafb6cSDan Gohman #include "llvm/Support/StringSaver.h" 3418eafb6cSDan Gohman #include <vector> 3518eafb6cSDan Gohman 3618eafb6cSDan Gohman using namespace llvm; 3718eafb6cSDan Gohman 385e3d33a7SSam Clegg #define DEBUG_TYPE "mc" 3918eafb6cSDan Gohman 4018eafb6cSDan Gohman namespace { 419e15f359SSam Clegg 4230e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is 4330e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap. 4430e1bbc1SSam Clegg static const uint32_t kInitialTableOffset = 1; 4530e1bbc1SSam Clegg 46d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both 47d934cb88SDan Gohman // for patching up the section size field, and for patching up references to 48d934cb88SDan Gohman // locations within the section. 49d934cb88SDan Gohman struct SectionBookkeeping { 50d934cb88SDan Gohman // Where the size of the section is written. 51d934cb88SDan Gohman uint64_t SizeOffset; 526a31a0d6SSam Clegg // Where the section header ends (without custom section name). 536a31a0d6SSam Clegg uint64_t PayloadOffset; 546a31a0d6SSam Clegg // Where the contents of the section starts. 55d934cb88SDan Gohman uint64_t ContentsOffset; 566f08c84aSSam Clegg uint32_t Index; 57d934cb88SDan Gohman }; 58d934cb88SDan Gohman 599e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a 609e15f359SSam Clegg // DenseMap key. 619e15f359SSam Clegg struct WasmFunctionType { 629e15f359SSam Clegg // Support empty and tombstone instances, needed by DenseMap. 639e15f359SSam Clegg enum { Plain, Empty, Tombstone } State; 649e15f359SSam Clegg 659e15f359SSam Clegg // The return types of the function. 669e15f359SSam Clegg SmallVector<wasm::ValType, 1> Returns; 679e15f359SSam Clegg 689e15f359SSam Clegg // The parameter types of the function. 699e15f359SSam Clegg SmallVector<wasm::ValType, 4> Params; 709e15f359SSam Clegg 719e15f359SSam Clegg WasmFunctionType() : State(Plain) {} 729e15f359SSam Clegg 739e15f359SSam Clegg bool operator==(const WasmFunctionType &Other) const { 749e15f359SSam Clegg return State == Other.State && Returns == Other.Returns && 759e15f359SSam Clegg Params == Other.Params; 769e15f359SSam Clegg } 779e15f359SSam Clegg }; 789e15f359SSam Clegg 799e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap. 809e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo { 819e15f359SSam Clegg static WasmFunctionType getEmptyKey() { 829e15f359SSam Clegg WasmFunctionType FuncTy; 839e15f359SSam Clegg FuncTy.State = WasmFunctionType::Empty; 849e15f359SSam Clegg return FuncTy; 859e15f359SSam Clegg } 869e15f359SSam Clegg static WasmFunctionType getTombstoneKey() { 879e15f359SSam Clegg WasmFunctionType FuncTy; 889e15f359SSam Clegg FuncTy.State = WasmFunctionType::Tombstone; 899e15f359SSam Clegg return FuncTy; 909e15f359SSam Clegg } 919e15f359SSam Clegg static unsigned getHashValue(const WasmFunctionType &FuncTy) { 929e15f359SSam Clegg uintptr_t Value = FuncTy.State; 939e15f359SSam Clegg for (wasm::ValType Ret : FuncTy.Returns) 949e15f359SSam Clegg Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret)); 959e15f359SSam Clegg for (wasm::ValType Param : FuncTy.Params) 969e15f359SSam Clegg Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param)); 979e15f359SSam Clegg return Value; 989e15f359SSam Clegg } 999e15f359SSam Clegg static bool isEqual(const WasmFunctionType &LHS, 1009e15f359SSam Clegg const WasmFunctionType &RHS) { 1019e15f359SSam Clegg return LHS == RHS; 1029e15f359SSam Clegg } 1039e15f359SSam Clegg }; 1049e15f359SSam Clegg 1057c395943SSam Clegg // A wasm data segment. A wasm binary contains only a single data section 1067c395943SSam Clegg // but that can contain many segments, each with their own virtual location 1077c395943SSam Clegg // in memory. Each MCSection data created by llvm is modeled as its own 1087c395943SSam Clegg // wasm data segment. 1097c395943SSam Clegg struct WasmDataSegment { 1107c395943SSam Clegg MCSectionWasm *Section; 111d95ed959SSam Clegg StringRef Name; 1127c395943SSam Clegg uint32_t Offset; 11363ebb813SSam Clegg uint32_t Alignment; 11463ebb813SSam Clegg uint32_t Flags; 1157c395943SSam Clegg SmallVector<char, 4> Data; 1167c395943SSam Clegg }; 1177c395943SSam Clegg 1189e15f359SSam Clegg // A wasm function to be written into the function section. 1199e15f359SSam Clegg struct WasmFunction { 1209e15f359SSam Clegg int32_t Type; 1219e15f359SSam Clegg const MCSymbolWasm *Sym; 1229e15f359SSam Clegg }; 1239e15f359SSam Clegg 1249e15f359SSam Clegg // A wasm global to be written into the global section. 1259e15f359SSam Clegg struct WasmGlobal { 1266e7f1826SSam Clegg wasm::WasmGlobalType Type; 1279e15f359SSam Clegg uint64_t InitialValue; 1289e15f359SSam Clegg }; 1299e15f359SSam Clegg 130ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT. For each data 131ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding 132ea7caceeSSam Clegg // WasmComdatEntry. 133ea7caceeSSam Clegg struct WasmComdatEntry { 134ea7caceeSSam Clegg unsigned Kind; 135ea7caceeSSam Clegg uint32_t Index; 136ea7caceeSSam Clegg }; 137ea7caceeSSam Clegg 1386dc65e91SSam Clegg // Information about a single relocation. 1396dc65e91SSam Clegg struct WasmRelocationEntry { 1406dc65e91SSam Clegg uint64_t Offset; // Where is the relocation. 1416dc65e91SSam Clegg const MCSymbolWasm *Symbol; // The symbol to relocate with. 1426dc65e91SSam Clegg int64_t Addend; // A value to add to the symbol. 1436dc65e91SSam Clegg unsigned Type; // The type of the relocation. 144fe6414b0SSam Clegg const MCSectionWasm *FixupSection;// The section the relocation is targeting. 1456dc65e91SSam Clegg 1466dc65e91SSam Clegg WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol, 1476dc65e91SSam Clegg int64_t Addend, unsigned Type, 148fe6414b0SSam Clegg const MCSectionWasm *FixupSection) 1496dc65e91SSam Clegg : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type), 1506dc65e91SSam Clegg FixupSection(FixupSection) {} 1516dc65e91SSam Clegg 152acd7d2b0SSam Clegg bool hasAddend() const { 153acd7d2b0SSam Clegg switch (Type) { 15413a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 15513a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 15613a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 1576a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: 1586a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: 159acd7d2b0SSam Clegg return true; 160acd7d2b0SSam Clegg default: 161acd7d2b0SSam Clegg return false; 162acd7d2b0SSam Clegg } 163acd7d2b0SSam Clegg } 164acd7d2b0SSam Clegg 1656dc65e91SSam Clegg void print(raw_ostream &Out) const { 1665f87ab33SSam Clegg Out << wasm::relocTypetoString(Type) 167a165f2d6SSam Clegg << " Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend 168759631c7SSam Clegg << ", FixupSection=" << FixupSection->getSectionName(); 1696dc65e91SSam Clegg } 170b7787fd0SSam Clegg 171615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 172b7787fd0SSam Clegg LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 173b7787fd0SSam Clegg #endif 1746dc65e91SSam Clegg }; 1756dc65e91SSam Clegg 17625d8e68bSSam Clegg static const uint32_t INVALID_INDEX = -1; 17725d8e68bSSam Clegg 178cfd44a2eSSam Clegg struct WasmCustomSection { 179cfd44a2eSSam Clegg 1806a31a0d6SSam Clegg StringRef Name; 1816a31a0d6SSam Clegg MCSectionWasm *Section; 1826a31a0d6SSam Clegg 1836a31a0d6SSam Clegg uint32_t OutputContentsOffset; 1846a31a0d6SSam Clegg uint32_t OutputIndex; 1856a31a0d6SSam Clegg 1866a31a0d6SSam Clegg WasmCustomSection(StringRef Name, MCSectionWasm *Section) 1876a31a0d6SSam Clegg : Name(Name), Section(Section), OutputContentsOffset(0), 1886a31a0d6SSam Clegg OutputIndex(INVALID_INDEX) {} 189cfd44a2eSSam Clegg }; 190cfd44a2eSSam Clegg 1911fb8daa6SSam Clegg #if !defined(NDEBUG) 1927f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) { 193b7787fd0SSam Clegg Rel.print(OS); 194b7787fd0SSam Clegg return OS; 195b7787fd0SSam Clegg } 1961fb8daa6SSam Clegg #endif 197b7787fd0SSam Clegg 19818eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter { 19918eafb6cSDan Gohman /// The target specific Wasm writer instance. 20018eafb6cSDan Gohman std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; 20118eafb6cSDan Gohman 202d934cb88SDan Gohman // Relocations for fixing up references in the code section. 203d934cb88SDan Gohman std::vector<WasmRelocationEntry> CodeRelocations; 2046f08c84aSSam Clegg uint32_t CodeSectionIndex; 205d934cb88SDan Gohman 206d934cb88SDan Gohman // Relocations for fixing up references in the data section. 207d934cb88SDan Gohman std::vector<WasmRelocationEntry> DataRelocations; 2086f08c84aSSam Clegg uint32_t DataSectionIndex; 209d934cb88SDan Gohman 210d934cb88SDan Gohman // Index values to use for fixing up call_indirect type indices. 211acd7d2b0SSam Clegg // Maps function symbols to the index of the type of the function 212acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices; 213d99f6078SSam Clegg // Maps function symbols to the table element index space. Used 214d99f6078SSam Clegg // for TABLE_INDEX relocation types (i.e. address taken functions). 215f9edbe95SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TableIndices; 216a165f2d6SSam Clegg // Maps function/global symbols to the function/global/section 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 2216a31a0d6SSam Clegg // Stores output data (index, relocations, content offset) for custom 2226a31a0d6SSam Clegg // section. 2236a31a0d6SSam Clegg std::vector<WasmCustomSection> CustomSections; 2246a31a0d6SSam Clegg // Relocations for fixing up references in the custom sections. 2256a31a0d6SSam Clegg DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>> 2266a31a0d6SSam Clegg CustomSectionsRelocations; 227acd7d2b0SSam Clegg 228*c0d41195SSam Clegg // Map from section to defining function symbol. 2296ccb59b3SSam Clegg DenseMap<const MCSection *, const MCSymbol *> SectionFunctions; 2306ccb59b3SSam Clegg 231acd7d2b0SSam Clegg DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo> 232acd7d2b0SSam Clegg FunctionTypeIndices; 2335e3d33a7SSam Clegg SmallVector<WasmFunctionType, 4> FunctionTypes; 2347c395943SSam Clegg SmallVector<WasmGlobal, 4> Globals; 2356c899ba6SSam Clegg SmallVector<WasmDataSegment, 4> DataSegments; 2369f3fe42eSSam Clegg unsigned NumFunctionImports = 0; 2377c395943SSam Clegg unsigned NumGlobalImports = 0; 2387e1c3345SChandler Carruth uint32_t SectionCount = 0; 239d934cb88SDan Gohman 24018eafb6cSDan Gohman // TargetObjectWriter wrappers. 24118eafb6cSDan Gohman bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 242ae03c1e7SSam Clegg unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const { 243ae03c1e7SSam Clegg return TargetObjectWriter->getRelocType(Target, Fixup); 24418eafb6cSDan Gohman } 24518eafb6cSDan Gohman 2462322a937SSam Clegg void startSection(SectionBookkeeping &Section, unsigned SectionId); 2472322a937SSam Clegg void startCustomSection(SectionBookkeeping &Section, StringRef Name); 248d934cb88SDan Gohman void endSection(SectionBookkeeping &Section); 249d934cb88SDan Gohman 25018eafb6cSDan Gohman public: 2511301a878SLang Hames WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 2521301a878SLang Hames raw_pwrite_stream &OS) 2531301a878SLang Hames : MCObjectWriter(OS, /*IsLittleEndian=*/true), 2541301a878SLang Hames TargetObjectWriter(std::move(MOTW)) {} 25518eafb6cSDan Gohman 25618eafb6cSDan Gohman ~WasmObjectWriter() override; 25718eafb6cSDan Gohman 2580917c9e4SDan Gohman private: 259acd7d2b0SSam Clegg void reset() override { 260acd7d2b0SSam Clegg CodeRelocations.clear(); 261acd7d2b0SSam Clegg DataRelocations.clear(); 262acd7d2b0SSam Clegg TypeIndices.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(); 2716ccb59b3SSam Clegg SectionFunctions.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) { 335d34e60caSNicola Zaghen LLVM_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) { 352d34e60caSNicola Zaghen LLVM_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 372d34e60caSNicola Zaghen LLVM_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) { 3906ccb59b3SSam Clegg // Build a map of sections to the function that defines them, for use 3916ccb59b3SSam Clegg // in recordRelocation. 3926ccb59b3SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 3936ccb59b3SSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 3946ccb59b3SSam Clegg if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) { 3956ccb59b3SSam Clegg const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection()); 3966ccb59b3SSam Clegg auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S)); 3976ccb59b3SSam Clegg if (!Pair.second) 3986ccb59b3SSam Clegg report_fatal_error("section already has a defining function: " + 3996ccb59b3SSam Clegg Sec.getSectionName()); 4006ccb59b3SSam Clegg } 4016ccb59b3SSam Clegg } 40218eafb6cSDan Gohman } 40318eafb6cSDan Gohman 40418eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 40518eafb6cSDan Gohman const MCAsmLayout &Layout, 40618eafb6cSDan Gohman const MCFragment *Fragment, 40718eafb6cSDan Gohman const MCFixup &Fixup, MCValue Target, 408ceecfe5bSRafael Espindola uint64_t &FixedValue) { 409ceecfe5bSRafael Espindola MCAsmBackend &Backend = Asm.getBackend(); 410ceecfe5bSRafael Espindola bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags & 411ceecfe5bSRafael Espindola MCFixupKindInfo::FKF_IsPCRel; 412fe6414b0SSam Clegg const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 413d934cb88SDan Gohman uint64_t C = Target.getConstant(); 414d934cb88SDan Gohman uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 415d934cb88SDan Gohman MCContext &Ctx = Asm.getContext(); 416d934cb88SDan Gohman 417bafe6902SSam Clegg // The .init_array isn't translated as data, so don't do relocations in it. 418bafe6902SSam Clegg if (FixupSection.getSectionName().startswith(".init_array")) 419bafe6902SSam Clegg return; 420bafe6902SSam Clegg 421d934cb88SDan Gohman if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 422d934cb88SDan Gohman assert(RefB->getKind() == MCSymbolRefExpr::VK_None && 423d934cb88SDan Gohman "Should not have constructed this"); 424d934cb88SDan Gohman 425d934cb88SDan Gohman // Let A, B and C being the components of Target and R be the location of 426d934cb88SDan Gohman // the fixup. If the fixup is not pcrel, we want to compute (A - B + C). 427d934cb88SDan Gohman // If it is pcrel, we want to compute (A - B + C - R). 428d934cb88SDan Gohman 429d934cb88SDan Gohman // In general, Wasm has no relocations for -B. It can only represent (A + C) 430d934cb88SDan Gohman // or (A + C - R). If B = R + K and the relocation is not pcrel, we can 431d934cb88SDan Gohman // replace B to implement it: (A - R - K + C) 432d934cb88SDan Gohman if (IsPCRel) { 433d934cb88SDan Gohman Ctx.reportError( 434d934cb88SDan Gohman Fixup.getLoc(), 435d934cb88SDan Gohman "No relocation available to represent this relative expression"); 436d934cb88SDan Gohman return; 437d934cb88SDan Gohman } 438d934cb88SDan Gohman 439d934cb88SDan Gohman const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 440d934cb88SDan Gohman 441d934cb88SDan Gohman if (SymB.isUndefined()) { 442d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 443d934cb88SDan Gohman Twine("symbol '") + SymB.getName() + 444d934cb88SDan Gohman "' can not be undefined in a subtraction expression"); 445d934cb88SDan Gohman return; 446d934cb88SDan Gohman } 447d934cb88SDan Gohman 448d934cb88SDan Gohman assert(!SymB.isAbsolute() && "Should have been folded"); 449d934cb88SDan Gohman const MCSection &SecB = SymB.getSection(); 450d934cb88SDan Gohman if (&SecB != &FixupSection) { 451d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 452d934cb88SDan Gohman "Cannot represent a difference across sections"); 453d934cb88SDan Gohman return; 454d934cb88SDan Gohman } 455d934cb88SDan Gohman 456d934cb88SDan Gohman uint64_t SymBOffset = Layout.getSymbolOffset(SymB); 457d934cb88SDan Gohman uint64_t K = SymBOffset - FixupOffset; 458d934cb88SDan Gohman IsPCRel = true; 459d934cb88SDan Gohman C -= K; 460d934cb88SDan Gohman } 461d934cb88SDan Gohman 462d934cb88SDan Gohman // We either rejected the fixup or folded B into C at this point. 463d934cb88SDan Gohman const MCSymbolRefExpr *RefA = Target.getSymA(); 464d934cb88SDan Gohman const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr; 465d934cb88SDan Gohman 466d934cb88SDan Gohman if (SymA && SymA->isVariable()) { 467d934cb88SDan Gohman const MCExpr *Expr = SymA->getVariableValue(); 4686ad8f190SSam Clegg const auto *Inner = cast<MCSymbolRefExpr>(Expr); 4696ad8f190SSam Clegg if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) 4706ad8f190SSam Clegg llvm_unreachable("weakref used in reloc not yet implemented"); 471d934cb88SDan Gohman } 472d934cb88SDan Gohman 473d934cb88SDan Gohman // Put any constant offset in an addend. Offsets can be negative, and 474d934cb88SDan Gohman // LLVM expects wrapping, in contrast to wasm's immediates which can't 475d934cb88SDan Gohman // be negative and don't wrap. 476d934cb88SDan Gohman FixedValue = 0; 477d934cb88SDan Gohman 4784d57fbd0SSam Clegg unsigned Type = getRelocType(Target, Fixup); 479ae03c1e7SSam Clegg assert(!IsPCRel); 4809d24fb7fSSam Clegg assert(SymA); 4819d24fb7fSSam Clegg 4824d57fbd0SSam Clegg // Absolute offset within a section or a function. 4834d57fbd0SSam Clegg // Currently only supported for for metadata sections. 4844d57fbd0SSam Clegg // See: test/MC/WebAssembly/blockaddress.ll 4854d57fbd0SSam Clegg if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 || 4864d57fbd0SSam Clegg Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) { 4874d57fbd0SSam Clegg if (!FixupSection.getKind().isMetadata()) 4884d57fbd0SSam Clegg report_fatal_error("relocations for function or section offsets are " 4894d57fbd0SSam Clegg "only supported in metadata sections"); 4904d57fbd0SSam Clegg 4914d57fbd0SSam Clegg const MCSymbol *SectionSymbol = nullptr; 4924d57fbd0SSam Clegg const MCSection &SecA = SymA->getSection(); 4934d57fbd0SSam Clegg if (SecA.getKind().isText()) 4946ccb59b3SSam Clegg SectionSymbol = SectionFunctions.find(&SecA)->second; 4954d57fbd0SSam Clegg else 4964d57fbd0SSam Clegg SectionSymbol = SecA.getBeginSymbol(); 4974d57fbd0SSam Clegg if (!SectionSymbol) 4984d57fbd0SSam Clegg report_fatal_error("section symbol is required for relocation"); 4994d57fbd0SSam Clegg 5004d57fbd0SSam Clegg C += Layout.getSymbolOffset(*SymA); 5014d57fbd0SSam Clegg SymA = cast<MCSymbolWasm>(SectionSymbol); 5024d57fbd0SSam Clegg } 5034d57fbd0SSam Clegg 5044d57fbd0SSam Clegg // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be 5054d57fbd0SSam Clegg // against a named symbol. 5064d57fbd0SSam Clegg if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) { 5074d57fbd0SSam Clegg if (SymA->getName().empty()) 5084d57fbd0SSam Clegg report_fatal_error("relocations against un-named temporaries are not yet " 5094d57fbd0SSam Clegg "supported by wasm"); 5104d57fbd0SSam Clegg 5114d57fbd0SSam Clegg SymA->setUsedInReloc(); 5124d57fbd0SSam Clegg } 513ae03c1e7SSam Clegg 514d934cb88SDan Gohman WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 515d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 516d934cb88SDan Gohman 5176a31a0d6SSam Clegg if (FixupSection.isWasmData()) { 518d934cb88SDan Gohman DataRelocations.push_back(Rec); 5196a31a0d6SSam Clegg } else if (FixupSection.getKind().isText()) { 52012fd3da9SSam Clegg CodeRelocations.push_back(Rec); 5216a31a0d6SSam Clegg } else if (FixupSection.getKind().isMetadata()) { 5226a31a0d6SSam Clegg CustomSectionsRelocations[&FixupSection].push_back(Rec); 5236a31a0d6SSam Clegg } else { 52412fd3da9SSam Clegg llvm_unreachable("unexpected section type"); 525d934cb88SDan Gohman } 5266a31a0d6SSam Clegg } 527d934cb88SDan Gohman 528d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded 529d934cb88SDan Gohman // to allow patching. 530d934cb88SDan Gohman static void 531d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 532d934cb88SDan Gohman uint8_t Buffer[5]; 53366a99e41SSam Clegg unsigned SizeLen = encodeULEB128(X, Buffer, 5); 534d934cb88SDan Gohman assert(SizeLen == 5); 535d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 536d934cb88SDan Gohman } 537d934cb88SDan Gohman 538d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded 539d934cb88SDan Gohman // to allow patching. 540d934cb88SDan Gohman static void 541d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) { 542d934cb88SDan Gohman uint8_t Buffer[5]; 54366a99e41SSam Clegg unsigned SizeLen = encodeSLEB128(X, Buffer, 5); 544d934cb88SDan Gohman assert(SizeLen == 5); 545d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 546d934cb88SDan Gohman } 547d934cb88SDan Gohman 548d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream. 549d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 550d934cb88SDan Gohman uint8_t Buffer[4]; 551d934cb88SDan Gohman support::endian::write32le(Buffer, X); 552d934cb88SDan Gohman Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 553d934cb88SDan Gohman } 554d934cb88SDan Gohman 555aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) { 556aff1c4dfSSam Clegg if (Symbol.isVariable()) { 557aff1c4dfSSam Clegg const MCExpr *Expr = Symbol.getVariableValue(); 558aff1c4dfSSam Clegg auto *Inner = cast<MCSymbolRefExpr>(Expr); 559aff1c4dfSSam Clegg return cast<MCSymbolWasm>(&Inner->getSymbol()); 560aff1c4dfSSam Clegg } 561aff1c4dfSSam Clegg return &Symbol; 562aff1c4dfSSam Clegg } 563aff1c4dfSSam Clegg 564d934cb88SDan Gohman // Compute a value to write into the code at the location covered 56560ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves 56660ec3034SSam Clegg // to make the object format more readable and more likely to be directly 56760ec3034SSam Clegg // useable. 5687c395943SSam Clegg uint32_t 5697c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) { 57060ec3034SSam Clegg switch (RelEntry.Type) { 57160ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 572f9edbe95SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: { 573f9edbe95SSam Clegg // Provisional value is table address of the resolved symbol itself 574f9edbe95SSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 575f9edbe95SSam Clegg assert(Sym->isFunction()); 576f9edbe95SSam Clegg return TableIndices[Sym]; 577f9edbe95SSam Clegg } 57860ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 5796c899ba6SSam Clegg // Provisional value is same as the index 58060ec3034SSam Clegg return getRelocationIndexValue(RelEntry); 5816c899ba6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 5826c899ba6SSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 5836c899ba6SSam Clegg // Provisional value is function/global Wasm index 5846c899ba6SSam Clegg if (!WasmIndices.count(RelEntry.Symbol)) 5856c899ba6SSam Clegg report_fatal_error("symbol not found in wasm index space: " + 5866c899ba6SSam Clegg RelEntry.Symbol->getName()); 5876c899ba6SSam Clegg return WasmIndices[RelEntry.Symbol]; 5884d57fbd0SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: 5894d57fbd0SSam Clegg case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: { 5906a31a0d6SSam Clegg const auto &Section = 5916a31a0d6SSam Clegg static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection()); 5926a31a0d6SSam Clegg return Section.getSectionOffset() + RelEntry.Addend; 5936a31a0d6SSam Clegg } 59460ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 59560ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 59660ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: { 597f9edbe95SSam Clegg // Provisional value is address of the global 59860ec3034SSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 599270ed1b3SSam Clegg // For undefined symbols, use zero 600cd65f698SSam Clegg if (!Sym->isDefined()) 601270ed1b3SSam Clegg return 0; 6026c899ba6SSam Clegg const wasm::WasmDataReference &Ref = DataLocations[Sym]; 6036c899ba6SSam Clegg const WasmDataSegment &Segment = DataSegments[Ref.Segment]; 604d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 6056c899ba6SSam Clegg return Segment.Offset + Ref.Offset + RelEntry.Addend; 60660ec3034SSam Clegg } 60760ec3034SSam Clegg default: 60860ec3034SSam Clegg llvm_unreachable("invalid relocation type"); 60960ec3034SSam Clegg } 610d934cb88SDan Gohman } 611d934cb88SDan Gohman 612759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes, 61363ebb813SSam Clegg MCSectionWasm &DataSection) { 614d34e60caSNicola Zaghen LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n"); 615759631c7SSam Clegg 61663ebb813SSam Clegg DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 61763ebb813SSam Clegg 618759631c7SSam Clegg for (const MCFragment &Frag : DataSection) { 619759631c7SSam Clegg if (Frag.hasInstructions()) 620759631c7SSam Clegg report_fatal_error("only data supported in data sections"); 621759631c7SSam Clegg 622759631c7SSam Clegg if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 623759631c7SSam Clegg if (Align->getValueSize() != 1) 624759631c7SSam Clegg report_fatal_error("only byte values supported for alignment"); 625759631c7SSam Clegg // If nops are requested, use zeros, as this is the data section. 626759631c7SSam Clegg uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 627759631c7SSam Clegg uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(), 628759631c7SSam Clegg Align->getAlignment()), 629759631c7SSam Clegg DataBytes.size() + 630759631c7SSam Clegg Align->getMaxBytesToEmit()); 631759631c7SSam Clegg DataBytes.resize(Size, Value); 632759631c7SSam Clegg } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 633d707c370SRafael Espindola int64_t Size; 634d707c370SRafael Espindola if (!Fill->getSize().evaluateAsAbsolute(Size)) 635d707c370SRafael Espindola llvm_unreachable("The fill should be an assembler constant"); 636d707c370SRafael Espindola DataBytes.insert(DataBytes.end(), Size, Fill->getValue()); 637759631c7SSam Clegg } else { 638759631c7SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 639759631c7SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 640759631c7SSam Clegg 641759631c7SSam Clegg DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 642759631c7SSam Clegg } 643759631c7SSam Clegg } 644759631c7SSam Clegg 645d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 646759631c7SSam Clegg } 647759631c7SSam Clegg 64860ec3034SSam Clegg uint32_t 64960ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) { 65060ec3034SSam Clegg if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) { 651b7787fd0SSam Clegg if (!TypeIndices.count(RelEntry.Symbol)) 652b7787fd0SSam Clegg report_fatal_error("symbol not found in type index space: " + 653b7787fd0SSam Clegg RelEntry.Symbol->getName()); 654acd7d2b0SSam Clegg return TypeIndices[RelEntry.Symbol]; 655acd7d2b0SSam Clegg } 65660ec3034SSam Clegg 65725d8e68bSSam Clegg return RelEntry.Symbol->getIndex(); 658acd7d2b0SSam Clegg } 659acd7d2b0SSam Clegg 660d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 661d934cb88SDan Gohman // directly. 662acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations( 663acd7d2b0SSam Clegg ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) { 664acd7d2b0SSam Clegg raw_pwrite_stream &Stream = getStream(); 665d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 666d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 667d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 668d934cb88SDan Gohman RelEntry.Offset; 669d934cb88SDan Gohman 670d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 67160ec3034SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 67260ec3034SSam Clegg 673acd7d2b0SSam Clegg switch (RelEntry.Type) { 674acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 6759d24fb7fSSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 67660ec3034SSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 67760ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 678d934cb88SDan Gohman WritePatchableLEB(Stream, Value, Offset); 679d934cb88SDan Gohman break; 68060ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 68160ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 6826a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: 6836a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: 684d934cb88SDan Gohman WriteI32(Stream, Value, Offset); 685d934cb88SDan Gohman break; 68660ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 68760ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 68860ec3034SSam Clegg WritePatchableSLEB(Stream, Value, Offset); 68960ec3034SSam Clegg break; 690d934cb88SDan Gohman default: 6919d24fb7fSSam Clegg llvm_unreachable("invalid relocation type"); 692d934cb88SDan Gohman } 693d934cb88SDan Gohman } 69418eafb6cSDan Gohman } 69518eafb6cSDan Gohman 6969e15f359SSam Clegg void WasmObjectWriter::writeTypeSection( 697457fb0b4SSam Clegg ArrayRef<WasmFunctionType> FunctionTypes) { 6989e15f359SSam Clegg if (FunctionTypes.empty()) 6999e15f359SSam Clegg return; 7009e15f359SSam Clegg 7019e15f359SSam Clegg SectionBookkeeping Section; 7029e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TYPE); 7039e15f359SSam Clegg 7049e15f359SSam Clegg encodeULEB128(FunctionTypes.size(), getStream()); 7059e15f359SSam Clegg 7069e15f359SSam Clegg for (const WasmFunctionType &FuncTy : FunctionTypes) { 70703e101f1SSam Clegg write8(wasm::WASM_TYPE_FUNC); 7089e15f359SSam Clegg encodeULEB128(FuncTy.Params.size(), getStream()); 7099e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Params) 7109e15f359SSam Clegg writeValueType(Ty); 7119e15f359SSam Clegg encodeULEB128(FuncTy.Returns.size(), getStream()); 7129e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Returns) 7139e15f359SSam Clegg writeValueType(Ty); 7149e15f359SSam Clegg } 7159e15f359SSam Clegg 7169e15f359SSam Clegg endSection(Section); 7179e15f359SSam Clegg } 7189e15f359SSam Clegg 7198defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports, 720f950b24aSSam Clegg uint32_t DataSize, 721f950b24aSSam Clegg uint32_t NumElements) { 7229e15f359SSam Clegg if (Imports.empty()) 7239e15f359SSam Clegg return; 7249e15f359SSam Clegg 725f950b24aSSam Clegg uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 726f950b24aSSam Clegg 7279e15f359SSam Clegg SectionBookkeeping Section; 7289e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_IMPORT); 7299e15f359SSam Clegg 7309e15f359SSam Clegg encodeULEB128(Imports.size(), getStream()); 7318defa952SSam Clegg for (const wasm::WasmImport &Import : Imports) { 7328defa952SSam Clegg writeString(Import.Module); 7338defa952SSam Clegg writeString(Import.Field); 73403e101f1SSam Clegg write8(Import.Kind); 7359e15f359SSam Clegg 7369e15f359SSam Clegg switch (Import.Kind) { 7379e15f359SSam Clegg case wasm::WASM_EXTERNAL_FUNCTION: 7388defa952SSam Clegg encodeULEB128(Import.SigIndex, getStream()); 7399e15f359SSam Clegg break; 7409e15f359SSam Clegg case wasm::WASM_EXTERNAL_GLOBAL: 74103e101f1SSam Clegg write8(Import.Global.Type); 74203e101f1SSam Clegg write8(Import.Global.Mutable ? 1 : 0); 7439e15f359SSam Clegg break; 744f950b24aSSam Clegg case wasm::WASM_EXTERNAL_MEMORY: 745f950b24aSSam Clegg encodeULEB128(0, getStream()); // flags 746f950b24aSSam Clegg encodeULEB128(NumPages, getStream()); // initial 747f950b24aSSam Clegg break; 748f950b24aSSam Clegg case wasm::WASM_EXTERNAL_TABLE: 74903e101f1SSam Clegg write8(Import.Table.ElemType); 750f950b24aSSam Clegg encodeULEB128(0, getStream()); // flags 751f950b24aSSam Clegg encodeULEB128(NumElements, getStream()); // initial 752f950b24aSSam Clegg break; 7539e15f359SSam Clegg default: 7549e15f359SSam Clegg llvm_unreachable("unsupported import kind"); 7559e15f359SSam Clegg } 7569e15f359SSam Clegg } 7579e15f359SSam Clegg 7589e15f359SSam Clegg endSection(Section); 7599e15f359SSam Clegg } 7609e15f359SSam Clegg 761457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 7629e15f359SSam Clegg if (Functions.empty()) 7639e15f359SSam Clegg return; 7649e15f359SSam Clegg 7659e15f359SSam Clegg SectionBookkeeping Section; 7669e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_FUNCTION); 7679e15f359SSam Clegg 7689e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 7699e15f359SSam Clegg for (const WasmFunction &Func : Functions) 7709e15f359SSam Clegg encodeULEB128(Func.Type, getStream()); 7719e15f359SSam Clegg 7729e15f359SSam Clegg endSection(Section); 7739e15f359SSam Clegg } 7749e15f359SSam Clegg 7757c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() { 7769e15f359SSam Clegg if (Globals.empty()) 7779e15f359SSam Clegg return; 7789e15f359SSam Clegg 7799e15f359SSam Clegg SectionBookkeeping Section; 7809e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_GLOBAL); 7819e15f359SSam Clegg 7829e15f359SSam Clegg encodeULEB128(Globals.size(), getStream()); 7839e15f359SSam Clegg for (const WasmGlobal &Global : Globals) { 7846e7f1826SSam Clegg writeValueType(static_cast<wasm::ValType>(Global.Type.Type)); 7856e7f1826SSam Clegg write8(Global.Type.Mutable); 7869e15f359SSam Clegg 7879e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 7886e7f1826SSam Clegg encodeSLEB128(Global.InitialValue, getStream()); 7899e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 7909e15f359SSam Clegg } 7919e15f359SSam Clegg 7929e15f359SSam Clegg endSection(Section); 7939e15f359SSam Clegg } 7949e15f359SSam Clegg 7958defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) { 7969e15f359SSam Clegg if (Exports.empty()) 7979e15f359SSam Clegg return; 7989e15f359SSam Clegg 7999e15f359SSam Clegg SectionBookkeeping Section; 8009e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_EXPORT); 8019e15f359SSam Clegg 8029e15f359SSam Clegg encodeULEB128(Exports.size(), getStream()); 8038defa952SSam Clegg for (const wasm::WasmExport &Export : Exports) { 8048defa952SSam Clegg writeString(Export.Name); 80503e101f1SSam Clegg write8(Export.Kind); 8069e15f359SSam Clegg encodeULEB128(Export.Index, getStream()); 8079e15f359SSam Clegg } 8089e15f359SSam Clegg 8099e15f359SSam Clegg endSection(Section); 8109e15f359SSam Clegg } 8119e15f359SSam Clegg 812457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 8139e15f359SSam Clegg if (TableElems.empty()) 8149e15f359SSam Clegg return; 8159e15f359SSam Clegg 8169e15f359SSam Clegg SectionBookkeeping Section; 8179e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_ELEM); 8189e15f359SSam Clegg 8199e15f359SSam Clegg encodeULEB128(1, getStream()); // number of "segments" 8209e15f359SSam Clegg encodeULEB128(0, getStream()); // the table index 8219e15f359SSam Clegg 8229e15f359SSam Clegg // init expr for starting offset 8239e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 82430e1bbc1SSam Clegg encodeSLEB128(kInitialTableOffset, getStream()); 8259e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 8269e15f359SSam Clegg 8279e15f359SSam Clegg encodeULEB128(TableElems.size(), getStream()); 8289e15f359SSam Clegg for (uint32_t Elem : TableElems) 8299e15f359SSam Clegg encodeULEB128(Elem, getStream()); 8309e15f359SSam Clegg 8319e15f359SSam Clegg endSection(Section); 8329e15f359SSam Clegg } 8339e15f359SSam Clegg 834457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 835457fb0b4SSam Clegg const MCAsmLayout &Layout, 836457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions) { 8379e15f359SSam Clegg if (Functions.empty()) 8389e15f359SSam Clegg return; 8399e15f359SSam Clegg 8409e15f359SSam Clegg SectionBookkeeping Section; 8419e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CODE); 8426f08c84aSSam Clegg CodeSectionIndex = Section.Index; 8439e15f359SSam Clegg 8449e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 8459e15f359SSam Clegg 8469e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 847fe6414b0SSam Clegg auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 8489e15f359SSam Clegg 8499e15f359SSam Clegg int64_t Size = 0; 8509e15f359SSam Clegg if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 8519e15f359SSam Clegg report_fatal_error(".size expression must be evaluatable"); 8529e15f359SSam Clegg 8539e15f359SSam Clegg encodeULEB128(Size, getStream()); 854fe6414b0SSam Clegg FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset); 8559e15f359SSam Clegg Asm.writeSectionData(&FuncSection, Layout); 8569e15f359SSam Clegg } 8579e15f359SSam Clegg 8589e15f359SSam Clegg // Apply fixups. 859acd7d2b0SSam Clegg applyRelocations(CodeRelocations, Section.ContentsOffset); 8609e15f359SSam Clegg 8619e15f359SSam Clegg endSection(Section); 8629e15f359SSam Clegg } 8639e15f359SSam Clegg 8646c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() { 8656c899ba6SSam Clegg if (DataSegments.empty()) 8667c395943SSam Clegg return; 8679e15f359SSam Clegg 8689e15f359SSam Clegg SectionBookkeeping Section; 8699e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_DATA); 8706f08c84aSSam Clegg DataSectionIndex = Section.Index; 8719e15f359SSam Clegg 8726c899ba6SSam Clegg encodeULEB128(DataSegments.size(), getStream()); // count 8737c395943SSam Clegg 8746c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 8759e15f359SSam Clegg encodeULEB128(0, getStream()); // memory index 8769e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 8777c395943SSam Clegg encodeSLEB128(Segment.Offset, getStream()); // offset 8789e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 8797c395943SSam Clegg encodeULEB128(Segment.Data.size(), getStream()); // size 8807c395943SSam Clegg Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset); 8817c395943SSam Clegg writeBytes(Segment.Data); // data 8827c395943SSam Clegg } 8839e15f359SSam Clegg 8849e15f359SSam Clegg // Apply fixups. 8857c395943SSam Clegg applyRelocations(DataRelocations, Section.ContentsOffset); 8869e15f359SSam Clegg 8879e15f359SSam Clegg endSection(Section); 8889e15f359SSam Clegg } 8899e15f359SSam Clegg 8906f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection( 8916f08c84aSSam Clegg uint32_t SectionIndex, StringRef Name, 8926f08c84aSSam Clegg ArrayRef<WasmRelocationEntry> Relocations) { 8939e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 8949e15f359SSam Clegg // for descriptions of the reloc sections. 8959e15f359SSam Clegg 8966f08c84aSSam Clegg if (Relocations.empty()) 8979e15f359SSam Clegg return; 8989e15f359SSam Clegg 8999e15f359SSam Clegg SectionBookkeeping Section; 9006f08c84aSSam Clegg startCustomSection(Section, std::string("reloc.") + Name.str()); 9019e15f359SSam Clegg 9026f08c84aSSam Clegg raw_pwrite_stream &Stream = getStream(); 9039e15f359SSam Clegg 9046f08c84aSSam Clegg encodeULEB128(SectionIndex, Stream); 9056f08c84aSSam Clegg encodeULEB128(Relocations.size(), Stream); 9066f08c84aSSam Clegg for (const WasmRelocationEntry& RelEntry : Relocations) { 9076f08c84aSSam Clegg uint64_t Offset = RelEntry.Offset + 9086f08c84aSSam Clegg RelEntry.FixupSection->getSectionOffset(); 9096f08c84aSSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 9109e15f359SSam Clegg 9116f08c84aSSam Clegg write8(RelEntry.Type); 9126f08c84aSSam Clegg encodeULEB128(Offset, Stream); 9136f08c84aSSam Clegg encodeULEB128(Index, Stream); 9146f08c84aSSam Clegg if (RelEntry.hasAddend()) 9156f08c84aSSam Clegg encodeSLEB128(RelEntry.Addend, Stream); 9169e15f359SSam Clegg } 9179e15f359SSam Clegg 9189e15f359SSam Clegg endSection(Section); 9199e15f359SSam Clegg } 9209e15f359SSam Clegg 9216a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() { 9226a31a0d6SSam Clegg for (const auto &Sec : CustomSections) { 9236a31a0d6SSam Clegg auto &Relocations = CustomSectionsRelocations[Sec.Section]; 9246a31a0d6SSam Clegg writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations); 9256a31a0d6SSam Clegg } 9266a31a0d6SSam Clegg } 9276a31a0d6SSam Clegg 9289e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection( 92986b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 930ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 931ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) { 9329e15f359SSam Clegg SectionBookkeeping Section; 9332322a937SSam Clegg startCustomSection(Section, "linking"); 9346bb5a41fSSam Clegg encodeULEB128(wasm::WasmMetadataVersion, getStream()); 9359e15f359SSam Clegg 9366bb5a41fSSam Clegg SectionBookkeeping SubSection; 9376c899ba6SSam Clegg if (SymbolInfos.size() != 0) { 9386c899ba6SSam Clegg startSection(SubSection, wasm::WASM_SYMBOL_TABLE); 9396c899ba6SSam Clegg encodeULEB128(SymbolInfos.size(), getStream()); 9406c899ba6SSam Clegg for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) { 9416c899ba6SSam Clegg encodeULEB128(Sym.Kind, getStream()); 9426c899ba6SSam Clegg encodeULEB128(Sym.Flags, getStream()); 9436c899ba6SSam Clegg switch (Sym.Kind) { 9446c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_FUNCTION: 9456c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_GLOBAL: 9466c899ba6SSam Clegg encodeULEB128(Sym.ElementIndex, getStream()); 9476c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) 9486c899ba6SSam Clegg writeString(Sym.Name); 9496c899ba6SSam Clegg break; 9506c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_DATA: 9516c899ba6SSam Clegg writeString(Sym.Name); 9526c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) { 9536c899ba6SSam Clegg encodeULEB128(Sym.DataRef.Segment, getStream()); 9546c899ba6SSam Clegg encodeULEB128(Sym.DataRef.Offset, getStream()); 9556c899ba6SSam Clegg encodeULEB128(Sym.DataRef.Size, getStream()); 9566c899ba6SSam Clegg } 9576c899ba6SSam Clegg break; 9586a31a0d6SSam Clegg case wasm::WASM_SYMBOL_TYPE_SECTION: { 9596a31a0d6SSam Clegg const uint32_t SectionIndex = 9606a31a0d6SSam Clegg CustomSections[Sym.ElementIndex].OutputIndex; 9616a31a0d6SSam Clegg encodeULEB128(SectionIndex, getStream()); 9626a31a0d6SSam Clegg break; 9636a31a0d6SSam Clegg } 9646c899ba6SSam Clegg default: 9656c899ba6SSam Clegg llvm_unreachable("unexpected kind"); 9666c899ba6SSam Clegg } 967b7787fd0SSam Clegg } 968b7787fd0SSam Clegg endSection(SubSection); 969b7787fd0SSam Clegg } 9709e15f359SSam Clegg 9716c899ba6SSam Clegg if (DataSegments.size()) { 97263ebb813SSam Clegg startSection(SubSection, wasm::WASM_SEGMENT_INFO); 9736c899ba6SSam Clegg encodeULEB128(DataSegments.size(), getStream()); 9746c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 975d95ed959SSam Clegg writeString(Segment.Name); 97663ebb813SSam Clegg encodeULEB128(Segment.Alignment, getStream()); 97763ebb813SSam Clegg encodeULEB128(Segment.Flags, getStream()); 97863ebb813SSam Clegg } 979d95ed959SSam Clegg endSection(SubSection); 980d95ed959SSam Clegg } 981d95ed959SSam Clegg 982bafe6902SSam Clegg if (!InitFuncs.empty()) { 983bafe6902SSam Clegg startSection(SubSection, wasm::WASM_INIT_FUNCS); 984bafe6902SSam Clegg encodeULEB128(InitFuncs.size(), getStream()); 985bafe6902SSam Clegg for (auto &StartFunc : InitFuncs) { 986bafe6902SSam Clegg encodeULEB128(StartFunc.first, getStream()); // priority 987bafe6902SSam Clegg encodeULEB128(StartFunc.second, getStream()); // function index 988bafe6902SSam Clegg } 989bafe6902SSam Clegg endSection(SubSection); 990bafe6902SSam Clegg } 991bafe6902SSam Clegg 992ea7caceeSSam Clegg if (Comdats.size()) { 993ea7caceeSSam Clegg startSection(SubSection, wasm::WASM_COMDAT_INFO); 994ea7caceeSSam Clegg encodeULEB128(Comdats.size(), getStream()); 995ea7caceeSSam Clegg for (const auto &C : Comdats) { 996ea7caceeSSam Clegg writeString(C.first); 997ea7caceeSSam Clegg encodeULEB128(0, getStream()); // flags for future use 998ea7caceeSSam Clegg encodeULEB128(C.second.size(), getStream()); 999ea7caceeSSam Clegg for (const WasmComdatEntry &Entry : C.second) { 1000ea7caceeSSam Clegg encodeULEB128(Entry.Kind, getStream()); 1001ea7caceeSSam Clegg encodeULEB128(Entry.Index, getStream()); 1002ea7caceeSSam Clegg } 1003ea7caceeSSam Clegg } 1004ea7caceeSSam Clegg endSection(SubSection); 1005ea7caceeSSam Clegg } 1006ea7caceeSSam Clegg 10079e15f359SSam Clegg endSection(Section); 10089e15f359SSam Clegg } 10099e15f359SSam Clegg 10106a31a0d6SSam Clegg void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm, 10116a31a0d6SSam Clegg const MCAsmLayout &Layout) { 10126a31a0d6SSam Clegg for (auto &CustomSection : CustomSections) { 1013cfd44a2eSSam Clegg SectionBookkeeping Section; 10146a31a0d6SSam Clegg auto *Sec = CustomSection.Section; 10152322a937SSam Clegg startCustomSection(Section, CustomSection.Name); 10166a31a0d6SSam Clegg 10176a31a0d6SSam Clegg Sec->setSectionOffset(getStream().tell() - Section.ContentsOffset); 10186a31a0d6SSam Clegg Asm.writeSectionData(Sec, Layout); 10196a31a0d6SSam Clegg 10206a31a0d6SSam Clegg CustomSection.OutputContentsOffset = Section.ContentsOffset; 10216a31a0d6SSam Clegg CustomSection.OutputIndex = Section.Index; 10226a31a0d6SSam Clegg 1023cfd44a2eSSam Clegg endSection(Section); 10246a31a0d6SSam Clegg 10256a31a0d6SSam Clegg // Apply fixups. 10264d57fbd0SSam Clegg auto &Relocations = CustomSectionsRelocations[CustomSection.Section]; 10274d57fbd0SSam Clegg applyRelocations(Relocations, CustomSection.OutputContentsOffset); 10286a31a0d6SSam Clegg } 10296a31a0d6SSam Clegg } 10306a31a0d6SSam Clegg 10315e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) { 10325e3d33a7SSam Clegg assert(Symbol.isFunction()); 10335e3d33a7SSam Clegg assert(TypeIndices.count(&Symbol)); 10345e3d33a7SSam Clegg return TypeIndices[&Symbol]; 10355e3d33a7SSam Clegg } 10365e3d33a7SSam Clegg 10375e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) { 10385e3d33a7SSam Clegg assert(Symbol.isFunction()); 10395e3d33a7SSam Clegg 10405e3d33a7SSam Clegg WasmFunctionType F; 1041aff1c4dfSSam Clegg const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol); 10425e3d33a7SSam Clegg F.Returns = ResolvedSym->getReturns(); 10435e3d33a7SSam Clegg F.Params = ResolvedSym->getParams(); 10445e3d33a7SSam Clegg 10455e3d33a7SSam Clegg auto Pair = 10465e3d33a7SSam Clegg FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); 10475e3d33a7SSam Clegg if (Pair.second) 10485e3d33a7SSam Clegg FunctionTypes.push_back(F); 10495e3d33a7SSam Clegg TypeIndices[&Symbol] = Pair.first->second; 10505e3d33a7SSam Clegg 1051d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol 1052d34e60caSNicola Zaghen << " new:" << Pair.second << "\n"); 1053d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 10545e3d33a7SSam Clegg return Pair.first->second; 10555e3d33a7SSam Clegg } 10565e3d33a7SSam Clegg 10574d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) { 10584d57fbd0SSam Clegg if (Sym.isUsedInReloc()) 10594d57fbd0SSam Clegg return true; 10604d57fbd0SSam Clegg 10614d57fbd0SSam Clegg if (Sym.isComdat() && !Sym.isDefined()) 10624d57fbd0SSam Clegg return false; 10634d57fbd0SSam Clegg 10644d57fbd0SSam Clegg if (Sym.isTemporary() && Sym.getName().empty()) 10654d57fbd0SSam Clegg return false; 10664d57fbd0SSam Clegg 10674d57fbd0SSam Clegg if (Sym.isTemporary() && Sym.isData() && !Sym.getSize()) 10684d57fbd0SSam Clegg return false; 10694d57fbd0SSam Clegg 10704d57fbd0SSam Clegg if (Sym.isSection()) 10714d57fbd0SSam Clegg return false; 10724d57fbd0SSam Clegg 10734d57fbd0SSam Clegg return true; 10744d57fbd0SSam Clegg } 10754d57fbd0SSam Clegg 107618eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm, 107718eafb6cSDan Gohman const MCAsmLayout &Layout) { 1078d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 107982607f56SDan Gohman MCContext &Ctx = Asm.getContext(); 1080d934cb88SDan Gohman 1081d934cb88SDan Gohman // Collect information from the available symbols. 1082d934cb88SDan Gohman SmallVector<WasmFunction, 4> Functions; 1083d934cb88SDan Gohman SmallVector<uint32_t, 4> TableElems; 10848defa952SSam Clegg SmallVector<wasm::WasmImport, 4> Imports; 10858defa952SSam Clegg SmallVector<wasm::WasmExport, 4> Exports; 10866c899ba6SSam Clegg SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos; 1087bafe6902SSam Clegg SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 1088ea7caceeSSam Clegg std::map<StringRef, std::vector<WasmComdatEntry>> Comdats; 10897c395943SSam Clegg uint32_t DataSize = 0; 1090d934cb88SDan Gohman 1091f950b24aSSam Clegg // For now, always emit the memory import, since loads and stores are not 1092f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1093f950b24aSSam Clegg // it if there are no loads or stores. 1094f950b24aSSam Clegg MCSymbolWasm *MemorySym = 1095f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory")); 10968defa952SSam Clegg wasm::WasmImport MemImport; 10978defa952SSam Clegg MemImport.Module = MemorySym->getModuleName(); 10988defa952SSam Clegg MemImport.Field = MemorySym->getName(); 1099f950b24aSSam Clegg MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1100f950b24aSSam Clegg Imports.push_back(MemImport); 1101f950b24aSSam Clegg 1102f950b24aSSam Clegg // For now, always emit the table section, since indirect calls are not 1103f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1104f950b24aSSam Clegg // it if there are no indirect calls. 1105f950b24aSSam Clegg MCSymbolWasm *TableSym = 1106f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table")); 11078defa952SSam Clegg wasm::WasmImport TableImport; 11088defa952SSam Clegg TableImport.Module = TableSym->getModuleName(); 11098defa952SSam Clegg TableImport.Field = TableSym->getName(); 1110f950b24aSSam Clegg TableImport.Kind = wasm::WASM_EXTERNAL_TABLE; 11118defa952SSam Clegg TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC; 1112f950b24aSSam Clegg Imports.push_back(TableImport); 1113f950b24aSSam Clegg 1114586320c0SNicholas Wilson // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined 1115586320c0SNicholas Wilson // symbols. This must be done before populating WasmIndices for defined 1116586320c0SNicholas Wilson // symbols. 111732ce5ca0SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 111832ce5ca0SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 111932ce5ca0SDan Gohman 112032ce5ca0SDan Gohman // Register types for all functions, including those with private linkage 11219f3fe42eSSam Clegg // (because wasm always needs a type signature). 112232ce5ca0SDan Gohman if (WS.isFunction()) 112332ce5ca0SDan Gohman registerFunctionType(WS); 112432ce5ca0SDan Gohman 112532ce5ca0SDan Gohman if (WS.isTemporary()) 112632ce5ca0SDan Gohman continue; 112732ce5ca0SDan Gohman 112832ce5ca0SDan Gohman // If the symbol is not defined in this translation unit, import it. 11296c899ba6SSam Clegg if (!WS.isDefined() && !WS.isComdat()) { 11306c899ba6SSam Clegg if (WS.isFunction()) { 11318defa952SSam Clegg wasm::WasmImport Import; 11328defa952SSam Clegg Import.Module = WS.getModuleName(); 11338defa952SSam Clegg Import.Field = WS.getName(); 113432ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 11358defa952SSam Clegg Import.SigIndex = getFunctionType(WS); 11366c899ba6SSam Clegg Imports.push_back(Import); 11376c899ba6SSam Clegg WasmIndices[&WS] = NumFunctionImports++; 11386c899ba6SSam Clegg } else if (WS.isGlobal()) { 113915f349f7SNicholas Wilson if (WS.isWeak()) 114015f349f7SNicholas Wilson report_fatal_error("undefined global symbol cannot be weak"); 114115f349f7SNicholas Wilson 11426c899ba6SSam Clegg wasm::WasmImport Import; 11436c899ba6SSam Clegg Import.Module = WS.getModuleName(); 11446c899ba6SSam Clegg Import.Field = WS.getName(); 114532ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 11466c899ba6SSam Clegg Import.Global = WS.getGlobalType(); 11476c899ba6SSam Clegg Imports.push_back(Import); 11486c899ba6SSam Clegg WasmIndices[&WS] = NumGlobalImports++; 114932ce5ca0SDan Gohman } 115032ce5ca0SDan Gohman } 115132ce5ca0SDan Gohman } 115232ce5ca0SDan Gohman 11534d57fbd0SSam Clegg // Populate DataSegments and CustomSections, which must be done before 11544d57fbd0SSam Clegg // populating DataLocations. 1155759631c7SSam Clegg for (MCSection &Sec : Asm) { 1156759631c7SSam Clegg auto &Section = static_cast<MCSectionWasm &>(Sec); 11574d57fbd0SSam Clegg StringRef SectionName = Section.getSectionName(); 1158759631c7SSam Clegg 1159bafe6902SSam Clegg // .init_array sections are handled specially elsewhere. 11604d57fbd0SSam Clegg if (SectionName.startswith(".init_array")) 1161bafe6902SSam Clegg continue; 1162bafe6902SSam Clegg 11634d57fbd0SSam Clegg // Code is handled separately 11644d57fbd0SSam Clegg if (Section.getKind().isText()) 11654d57fbd0SSam Clegg continue; 11664d57fbd0SSam Clegg 11674d57fbd0SSam Clegg if (Section.isWasmData()) { 1168329e76d5SSam Clegg uint32_t SegmentIndex = DataSegments.size(); 1169759631c7SSam Clegg DataSize = alignTo(DataSize, Section.getAlignment()); 1170759631c7SSam Clegg DataSegments.emplace_back(); 1171759631c7SSam Clegg WasmDataSegment &Segment = DataSegments.back(); 11724d57fbd0SSam Clegg Segment.Name = SectionName; 1173759631c7SSam Clegg Segment.Offset = DataSize; 1174759631c7SSam Clegg Segment.Section = &Section; 117563ebb813SSam Clegg addData(Segment.Data, Section); 117663ebb813SSam Clegg Segment.Alignment = Section.getAlignment(); 117763ebb813SSam Clegg Segment.Flags = 0; 1178759631c7SSam Clegg DataSize += Segment.Data.size(); 11796c899ba6SSam Clegg Section.setSegmentIndex(SegmentIndex); 1180ea7caceeSSam Clegg 1181ea7caceeSSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 1182ea7caceeSSam Clegg Comdats[C->getName()].emplace_back( 1183329e76d5SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex}); 1184ea7caceeSSam Clegg } 11854d57fbd0SSam Clegg } else { 11864d57fbd0SSam Clegg // Create custom sections 11874d57fbd0SSam Clegg assert(Sec.getKind().isMetadata()); 11884d57fbd0SSam Clegg 11894d57fbd0SSam Clegg StringRef Name = SectionName; 11904d57fbd0SSam Clegg 11914d57fbd0SSam Clegg // For user-defined custom sections, strip the prefix 11924d57fbd0SSam Clegg if (Name.startswith(".custom_section.")) 11934d57fbd0SSam Clegg Name = Name.substr(strlen(".custom_section.")); 11944d57fbd0SSam Clegg 11954d57fbd0SSam Clegg MCSymbol* Begin = Sec.getBeginSymbol(); 1196fb807d4dSSam Clegg if (Begin) { 11974d57fbd0SSam Clegg WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size(); 1198b210c64bSSam Clegg if (SectionName != Begin->getName()) 1199fb807d4dSSam Clegg report_fatal_error("section name and begin symbol should match: " + 1200b210c64bSSam Clegg Twine(SectionName)); 1201fb807d4dSSam Clegg } 12024d57fbd0SSam Clegg CustomSections.emplace_back(Name, &Section); 1203759631c7SSam Clegg } 12046a31a0d6SSam Clegg } 12056a31a0d6SSam Clegg 1206586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for defined symbols. 1207d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1208d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1209d934cb88SDan Gohman // or used in relocations. 1210d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 1211d934cb88SDan Gohman continue; 1212b7787fd0SSam Clegg 1213d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 1214d34e60caSNicola Zaghen LLVM_DEBUG( 1215d34e60caSNicola Zaghen dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'" 1216d34e60caSNicola Zaghen << " isDefined=" << S.isDefined() << " isExternal=" 1217d34e60caSNicola Zaghen << S.isExternal() << " isTemporary=" << S.isTemporary() 1218d34e60caSNicola Zaghen << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden() 1219b7787fd0SSam Clegg << " isVariable=" << WS.isVariable() << "\n"); 1220b7787fd0SSam Clegg 12215e3d33a7SSam Clegg if (WS.isVariable()) 12225e3d33a7SSam Clegg continue; 12236c899ba6SSam Clegg if (WS.isComdat() && !WS.isDefined()) 12246c899ba6SSam Clegg continue; 1225b7787fd0SSam Clegg 1226d934cb88SDan Gohman if (WS.isFunction()) { 12276c899ba6SSam Clegg unsigned Index; 1228cd65f698SSam Clegg if (WS.isDefined()) { 1229b7787fd0SSam Clegg if (WS.getOffset() != 0) 1230b7787fd0SSam Clegg report_fatal_error( 1231b7787fd0SSam Clegg "function sections must contain one function each"); 1232b7787fd0SSam Clegg 1233b7787fd0SSam Clegg if (WS.getSize() == 0) 1234b7787fd0SSam Clegg report_fatal_error( 1235b7787fd0SSam Clegg "function symbols must have a size set with .size"); 1236b7787fd0SSam Clegg 12376c899ba6SSam Clegg // A definition. Write out the function body. 12389f3fe42eSSam Clegg Index = NumFunctionImports + Functions.size(); 1239d934cb88SDan Gohman WasmFunction Func; 12405e3d33a7SSam Clegg Func.Type = getFunctionType(WS); 1241d934cb88SDan Gohman Func.Sym = &WS; 12426c899ba6SSam Clegg WasmIndices[&WS] = Index; 1243d934cb88SDan Gohman Functions.push_back(Func); 12446c899ba6SSam Clegg 12456c899ba6SSam Clegg auto &Section = static_cast<MCSectionWasm &>(WS.getSection()); 12466c899ba6SSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 12476c899ba6SSam Clegg Comdats[C->getName()].emplace_back( 12486c899ba6SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index}); 12496c899ba6SSam Clegg } 1250d934cb88SDan Gohman } else { 1251d934cb88SDan Gohman // An import; the index was assigned above. 12526c899ba6SSam Clegg Index = WasmIndices.find(&WS)->second; 1253d934cb88SDan Gohman } 1254d934cb88SDan Gohman 1255d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n"); 12566c899ba6SSam Clegg } else if (WS.isData()) { 1257c38e947eSSam Clegg if (WS.isTemporary() && !WS.getSize()) 1258c38e947eSSam Clegg continue; 1259c38e947eSSam Clegg 12606c899ba6SSam Clegg if (!WS.isDefined()) { 1261d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> segment index: -1" 1262d34e60caSNicola Zaghen << "\n"); 1263fe6414b0SSam Clegg continue; 12646c899ba6SSam Clegg } 1265fe6414b0SSam Clegg 1266d934cb88SDan Gohman if (!WS.getSize()) 1267c38e947eSSam Clegg report_fatal_error("data symbols must have a size set with .size: " + 1268c38e947eSSam Clegg WS.getName()); 1269d934cb88SDan Gohman 1270d934cb88SDan Gohman int64_t Size = 0; 1271d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1272d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 1273d934cb88SDan Gohman 1274759631c7SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1275ea7caceeSSam Clegg assert(DataSection.isWasmData()); 12767c395943SSam Clegg 12776c899ba6SSam Clegg // For each data symbol, export it in the symtab as a reference to the 12786c899ba6SSam Clegg // corresponding Wasm data segment. 12796c899ba6SSam Clegg wasm::WasmDataReference Ref = wasm::WasmDataReference{ 12806c899ba6SSam Clegg DataSection.getSegmentIndex(), 12816c899ba6SSam Clegg static_cast<uint32_t>(Layout.getSymbolOffset(WS)), 12826c899ba6SSam Clegg static_cast<uint32_t>(Size)}; 12836c899ba6SSam Clegg DataLocations[&WS] = Ref; 1284d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n"); 1285a165f2d6SSam Clegg } else if (WS.isGlobal()) { 12866c899ba6SSam Clegg // A "true" Wasm global (currently just __stack_pointer) 1287545932beSEric Christopher if (WS.isDefined()) 12886c899ba6SSam Clegg report_fatal_error("don't yet support defined globals"); 12896c899ba6SSam Clegg 1290545932beSEric Christopher // An import; the index was assigned above 1291d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> global index: " 1292d34e60caSNicola Zaghen << WasmIndices.find(&WS)->second << "\n"); 1293a165f2d6SSam Clegg } else { 1294a165f2d6SSam Clegg assert(WS.isSection()); 1295d934cb88SDan Gohman } 1296d934cb88SDan Gohman } 1297d934cb88SDan Gohman 1298586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for aliased symbols. We need to 1299586320c0SNicholas Wilson // process these in a separate pass because we need to have processed the 1300586320c0SNicholas Wilson // target of the alias before the alias itself and the symbols are not 1301586320c0SNicholas Wilson // necessarily ordered in this way. 1302b7787fd0SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1303b7787fd0SSam Clegg if (!S.isVariable()) 1304b7787fd0SSam Clegg continue; 130531a2c809SSam Clegg 1306cd65f698SSam Clegg assert(S.isDefined()); 1307b7787fd0SSam Clegg 13085e3d33a7SSam Clegg // Find the target symbol of this weak alias and export that index 1309aff1c4dfSSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 1310aff1c4dfSSam Clegg const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS); 1311d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym 1312d34e60caSNicola Zaghen << "'\n"); 1313b7787fd0SSam Clegg 13146c899ba6SSam Clegg if (WS.isFunction()) { 13156c899ba6SSam Clegg assert(WasmIndices.count(ResolvedSym) > 0); 13166c899ba6SSam Clegg uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second; 13176c899ba6SSam Clegg WasmIndices[&WS] = WasmIndex; 1318d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n"); 13196c899ba6SSam Clegg } else if (WS.isData()) { 13206c899ba6SSam Clegg assert(DataLocations.count(ResolvedSym) > 0); 13216c899ba6SSam Clegg const wasm::WasmDataReference &Ref = 13226c899ba6SSam Clegg DataLocations.find(ResolvedSym)->second; 13236c899ba6SSam Clegg DataLocations[&WS] = Ref; 1324d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n"); 13256c899ba6SSam Clegg } else { 13266c899ba6SSam Clegg report_fatal_error("don't yet support global aliases"); 13276c899ba6SSam Clegg } 1328586320c0SNicholas Wilson } 132931a2c809SSam Clegg 1330586320c0SNicholas Wilson // Finally, populate the symbol table itself, in its "natural" order. 1331586320c0SNicholas Wilson for (const MCSymbol &S : Asm.symbols()) { 1332586320c0SNicholas Wilson const auto &WS = static_cast<const MCSymbolWasm &>(S); 133325d8e68bSSam Clegg if (!isInSymtab(WS)) { 133425d8e68bSSam Clegg WS.setIndex(INVALID_INDEX); 1335586320c0SNicholas Wilson continue; 133625d8e68bSSam Clegg } 1337d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n"); 1338586320c0SNicholas Wilson 1339586320c0SNicholas Wilson uint32_t Flags = 0; 1340586320c0SNicholas Wilson if (WS.isWeak()) 1341586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_WEAK; 1342586320c0SNicholas Wilson if (WS.isHidden()) 1343586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN; 1344586320c0SNicholas Wilson if (!WS.isExternal() && WS.isDefined()) 1345586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL; 1346586320c0SNicholas Wilson if (WS.isUndefined()) 1347586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_UNDEFINED; 1348586320c0SNicholas Wilson 1349586320c0SNicholas Wilson wasm::WasmSymbolInfo Info; 1350586320c0SNicholas Wilson Info.Name = WS.getName(); 1351586320c0SNicholas Wilson Info.Kind = WS.getType(); 1352586320c0SNicholas Wilson Info.Flags = Flags; 13534d57fbd0SSam Clegg if (!WS.isData()) { 13544d57fbd0SSam Clegg assert(WasmIndices.count(&WS) > 0); 1355586320c0SNicholas Wilson Info.ElementIndex = WasmIndices.find(&WS)->second; 13564d57fbd0SSam Clegg } else if (WS.isDefined()) { 13574d57fbd0SSam Clegg assert(DataLocations.count(&WS) > 0); 1358586320c0SNicholas Wilson Info.DataRef = DataLocations.find(&WS)->second; 13594d57fbd0SSam Clegg } 136025d8e68bSSam Clegg WS.setIndex(SymbolInfos.size()); 1361586320c0SNicholas Wilson SymbolInfos.emplace_back(Info); 1362b7787fd0SSam Clegg } 1363b7787fd0SSam Clegg 13646006e091SSam Clegg { 13656006e091SSam Clegg auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 1366f9edbe95SSam Clegg // Functions referenced by a relocation need to put in the table. This is 1367f9edbe95SSam Clegg // purely to make the object file's provisional values readable, and is 1368f9edbe95SSam Clegg // ignored by the linker, which re-calculates the relocations itself. 1369f9edbe95SSam Clegg if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 && 1370f9edbe95SSam Clegg Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB) 1371f9edbe95SSam Clegg return; 1372f9edbe95SSam Clegg assert(Rel.Symbol->isFunction()); 1373f9edbe95SSam Clegg const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol); 13746c899ba6SSam Clegg uint32_t FunctionIndex = WasmIndices.find(&WS)->second; 1375f9edbe95SSam Clegg uint32_t TableIndex = TableElems.size() + kInitialTableOffset; 1376f9edbe95SSam Clegg if (TableIndices.try_emplace(&WS, TableIndex).second) { 1377d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> adding " << WS.getName() 1378f9edbe95SSam Clegg << " to table: " << TableIndex << "\n"); 13796c899ba6SSam Clegg TableElems.push_back(FunctionIndex); 13806006e091SSam Clegg registerFunctionType(WS); 13816006e091SSam Clegg } 13826006e091SSam Clegg }; 1383970d02c4SDan Gohman 13846006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : CodeRelocations) 13856006e091SSam Clegg HandleReloc(RelEntry); 13866006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : DataRelocations) 13876006e091SSam Clegg HandleReloc(RelEntry); 1388d934cb88SDan Gohman } 1389d934cb88SDan Gohman 1390bafe6902SSam Clegg // Translate .init_array section contents into start functions. 1391bafe6902SSam Clegg for (const MCSection &S : Asm) { 1392bafe6902SSam Clegg const auto &WS = static_cast<const MCSectionWasm &>(S); 1393bafe6902SSam Clegg if (WS.getSectionName().startswith(".fini_array")) 1394bafe6902SSam Clegg report_fatal_error(".fini_array sections are unsupported"); 1395bafe6902SSam Clegg if (!WS.getSectionName().startswith(".init_array")) 1396bafe6902SSam Clegg continue; 1397bafe6902SSam Clegg if (WS.getFragmentList().empty()) 1398bafe6902SSam Clegg continue; 1399b210c64bSSam Clegg 1400b210c64bSSam Clegg // init_array is expected to contain a single non-empty data fragment 1401b210c64bSSam Clegg if (WS.getFragmentList().size() != 3) 1402bafe6902SSam Clegg report_fatal_error("only one .init_array section fragment supported"); 1403b210c64bSSam Clegg 1404b210c64bSSam Clegg auto IT = WS.begin(); 1405b210c64bSSam Clegg const MCFragment &EmptyFrag = *IT; 1406b210c64bSSam Clegg if (EmptyFrag.getKind() != MCFragment::FT_Data) 1407b210c64bSSam Clegg report_fatal_error(".init_array section should be aligned"); 1408b210c64bSSam Clegg 1409b210c64bSSam Clegg IT = std::next(IT); 1410b210c64bSSam Clegg const MCFragment &AlignFrag = *IT; 1411bafe6902SSam Clegg if (AlignFrag.getKind() != MCFragment::FT_Align) 1412bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned"); 1413bafe6902SSam Clegg if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1414bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned for pointers"); 1415b210c64bSSam Clegg 1416b210c64bSSam Clegg const MCFragment &Frag = *std::next(IT); 1417bafe6902SSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1418bafe6902SSam Clegg report_fatal_error("only data supported in .init_array section"); 1419b210c64bSSam Clegg 1420bafe6902SSam Clegg uint16_t Priority = UINT16_MAX; 14214d57fbd0SSam Clegg unsigned PrefixLength = strlen(".init_array"); 14224d57fbd0SSam Clegg if (WS.getSectionName().size() > PrefixLength) { 14234d57fbd0SSam Clegg if (WS.getSectionName()[PrefixLength] != '.') 1424bafe6902SSam Clegg report_fatal_error(".init_array section priority should start with '.'"); 14254d57fbd0SSam Clegg if (WS.getSectionName() 14264d57fbd0SSam Clegg .substr(PrefixLength + 1) 14274d57fbd0SSam Clegg .getAsInteger(10, Priority)) 1428bafe6902SSam Clegg report_fatal_error("invalid .init_array section priority"); 1429bafe6902SSam Clegg } 1430bafe6902SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1431bafe6902SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1432bafe6902SSam Clegg for (const uint8_t *p = (const uint8_t *)Contents.data(), 1433bafe6902SSam Clegg *end = (const uint8_t *)Contents.data() + Contents.size(); 1434bafe6902SSam Clegg p != end; ++p) { 1435bafe6902SSam Clegg if (*p != 0) 1436bafe6902SSam Clegg report_fatal_error("non-symbolic data in .init_array section"); 1437bafe6902SSam Clegg } 1438bafe6902SSam Clegg for (const MCFixup &Fixup : DataFrag.getFixups()) { 1439bafe6902SSam Clegg assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1440bafe6902SSam Clegg const MCExpr *Expr = Fixup.getValue(); 1441bafe6902SSam Clegg auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr); 1442bafe6902SSam Clegg if (!Sym) 1443bafe6902SSam Clegg report_fatal_error("fixups in .init_array should be symbol references"); 1444bafe6902SSam Clegg if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION) 1445bafe6902SSam Clegg report_fatal_error("symbols in .init_array should be for functions"); 144625d8e68bSSam Clegg if (Sym->getSymbol().getIndex() == INVALID_INDEX) 144725d8e68bSSam Clegg report_fatal_error("symbols in .init_array should exist in symbtab"); 144825d8e68bSSam Clegg InitFuncs.push_back( 144925d8e68bSSam Clegg std::make_pair(Priority, Sym->getSymbol().getIndex())); 1450bafe6902SSam Clegg } 1451bafe6902SSam Clegg } 1452bafe6902SSam Clegg 145318eafb6cSDan Gohman // Write out the Wasm header. 145418eafb6cSDan Gohman writeHeader(Asm); 145518eafb6cSDan Gohman 14569e15f359SSam Clegg writeTypeSection(FunctionTypes); 1457f950b24aSSam Clegg writeImportSection(Imports, DataSize, TableElems.size()); 14589e15f359SSam Clegg writeFunctionSection(Functions); 1459f950b24aSSam Clegg // Skip the "table" section; we import the table instead. 1460f950b24aSSam Clegg // Skip the "memory" section; we import the memory instead. 14617c395943SSam Clegg writeGlobalSection(); 14629e15f359SSam Clegg writeExportSection(Exports); 14639e15f359SSam Clegg writeElemSection(TableElems); 1464acd7d2b0SSam Clegg writeCodeSection(Asm, Layout, Functions); 14656c899ba6SSam Clegg writeDataSection(); 14666a31a0d6SSam Clegg writeCustomSections(Asm, Layout); 1467c22bfb6bSNicholas Wilson writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats); 14686f08c84aSSam Clegg writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations); 14696f08c84aSSam Clegg writeRelocSection(DataSectionIndex, "DATA", DataRelocations); 14706a31a0d6SSam Clegg writeCustomRelocSections(); 1471970d02c4SDan Gohman 1472d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 147318eafb6cSDan Gohman } 147418eafb6cSDan Gohman 147560fbc7ccSLang Hames std::unique_ptr<MCObjectWriter> 14761301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 147718eafb6cSDan Gohman raw_pwrite_stream &OS) { 14780917c9e4SDan Gohman return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS); 147918eafb6cSDan Gohman } 1480