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" 17*432a3883SNico 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 { 1669bf73c07SSam Clegg Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend 167759631c7SSam Clegg << ", Type=" << Type 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 176cfd44a2eSSam Clegg struct WasmCustomSection { 1776a31a0d6SSam Clegg const uint32_t INVALID_INDEX = -1; 178cfd44a2eSSam Clegg 1796a31a0d6SSam Clegg StringRef Name; 1806a31a0d6SSam Clegg MCSectionWasm *Section; 1816a31a0d6SSam Clegg 1826a31a0d6SSam Clegg uint32_t OutputContentsOffset; 1836a31a0d6SSam Clegg uint32_t OutputIndex; 1846a31a0d6SSam Clegg 1856a31a0d6SSam Clegg WasmCustomSection(StringRef Name, MCSectionWasm *Section) 1866a31a0d6SSam Clegg : Name(Name), Section(Section), OutputContentsOffset(0), 1876a31a0d6SSam Clegg OutputIndex(INVALID_INDEX) {} 188cfd44a2eSSam Clegg }; 189cfd44a2eSSam Clegg 1901fb8daa6SSam Clegg #if !defined(NDEBUG) 1917f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) { 192b7787fd0SSam Clegg Rel.print(OS); 193b7787fd0SSam Clegg return OS; 194b7787fd0SSam Clegg } 1951fb8daa6SSam Clegg #endif 196b7787fd0SSam Clegg 19718eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter { 19818eafb6cSDan Gohman /// The target specific Wasm writer instance. 19918eafb6cSDan Gohman std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; 20018eafb6cSDan Gohman 201d934cb88SDan Gohman // Relocations for fixing up references in the code section. 202d934cb88SDan Gohman std::vector<WasmRelocationEntry> CodeRelocations; 2036f08c84aSSam Clegg uint32_t CodeSectionIndex; 204d934cb88SDan Gohman 205d934cb88SDan Gohman // Relocations for fixing up references in the data section. 206d934cb88SDan Gohman std::vector<WasmRelocationEntry> DataRelocations; 2076f08c84aSSam Clegg uint32_t DataSectionIndex; 208d934cb88SDan Gohman 209d934cb88SDan Gohman // Index values to use for fixing up call_indirect type indices. 210acd7d2b0SSam Clegg // Maps function symbols to the index of the type of the function 211acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices; 212d99f6078SSam Clegg // Maps function symbols to the table element index space. Used 213d99f6078SSam Clegg // for TABLE_INDEX relocation types (i.e. address taken functions). 214f9edbe95SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TableIndices; 2156c899ba6SSam Clegg // Maps function/global symbols to the (shared) Symbol index space. 216acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices; 2176c899ba6SSam Clegg // Maps function/global symbols to the function/global Wasm index space. 2186c899ba6SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices; 2196c899ba6SSam Clegg // Maps data symbols to the Wasm segment and offset/size with the segment. 2206c899ba6SSam Clegg DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations; 2216a31a0d6SSam Clegg // Maps section symbols to the section. 2226a31a0d6SSam Clegg DenseMap<const MCSymbolWasm *, const MCSectionWasm *> CustomSectionSymbols; 2236a31a0d6SSam Clegg 2246a31a0d6SSam Clegg // Stores output data (index, relocations, content offset) for custom 2256a31a0d6SSam Clegg // section. 2266a31a0d6SSam Clegg std::vector<WasmCustomSection> CustomSections; 2276a31a0d6SSam Clegg // Relocations for fixing up references in the custom sections. 2286a31a0d6SSam Clegg DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>> 2296a31a0d6SSam Clegg CustomSectionsRelocations; 230acd7d2b0SSam 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(); 263acd7d2b0SSam Clegg SymbolIndices.clear(); 2646c899ba6SSam Clegg WasmIndices.clear(); 265f9edbe95SSam Clegg TableIndices.clear(); 2666c899ba6SSam Clegg DataLocations.clear(); 2676a31a0d6SSam Clegg CustomSectionsRelocations.clear(); 268acd7d2b0SSam Clegg FunctionTypeIndices.clear(); 2695e3d33a7SSam Clegg FunctionTypes.clear(); 2707c395943SSam Clegg Globals.clear(); 2716c899ba6SSam Clegg DataSegments.clear(); 2726a31a0d6SSam Clegg CustomSectionSymbols.clear(); 273acd7d2b0SSam Clegg MCObjectWriter::reset(); 2749f3fe42eSSam Clegg NumFunctionImports = 0; 2757c395943SSam Clegg NumGlobalImports = 0; 276acd7d2b0SSam Clegg } 277acd7d2b0SSam Clegg 27818eafb6cSDan Gohman void writeHeader(const MCAssembler &Asm); 27918eafb6cSDan Gohman 28018eafb6cSDan Gohman void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 28118eafb6cSDan Gohman const MCFragment *Fragment, const MCFixup &Fixup, 282ceecfe5bSRafael Espindola MCValue Target, uint64_t &FixedValue) override; 28318eafb6cSDan Gohman 28418eafb6cSDan Gohman void executePostLayoutBinding(MCAssembler &Asm, 28518eafb6cSDan Gohman const MCAsmLayout &Layout) override; 28618eafb6cSDan Gohman 28718eafb6cSDan Gohman void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 2889e15f359SSam Clegg 289b7787fd0SSam Clegg void writeString(const StringRef Str) { 290b7787fd0SSam Clegg encodeULEB128(Str.size(), getStream()); 291b7787fd0SSam Clegg writeBytes(Str); 292b7787fd0SSam Clegg } 293b7787fd0SSam Clegg 2949e15f359SSam Clegg void writeValueType(wasm::ValType Ty) { 29503e101f1SSam Clegg write8(static_cast<uint8_t>(Ty)); 2969e15f359SSam Clegg } 2979e15f359SSam Clegg 298457fb0b4SSam Clegg void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes); 2998defa952SSam Clegg void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize, 300f950b24aSSam Clegg uint32_t NumElements); 301457fb0b4SSam Clegg void writeFunctionSection(ArrayRef<WasmFunction> Functions); 3027c395943SSam Clegg void writeGlobalSection(); 3038defa952SSam Clegg void writeExportSection(ArrayRef<wasm::WasmExport> Exports); 304457fb0b4SSam Clegg void writeElemSection(ArrayRef<uint32_t> TableElems); 3059e15f359SSam Clegg void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout, 306457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions); 3076c899ba6SSam Clegg void writeDataSection(); 3086f08c84aSSam Clegg void writeRelocSection(uint32_t SectionIndex, StringRef Name, 3096f08c84aSSam Clegg ArrayRef<WasmRelocationEntry> Relocations); 31031a2c809SSam Clegg void writeLinkingMetaDataSection( 31186b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 312ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 313ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats); 3146a31a0d6SSam Clegg void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout); 3156a31a0d6SSam Clegg void writeCustomRelocSections(); 3166a31a0d6SSam Clegg void 3176a31a0d6SSam Clegg updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions, 3186a31a0d6SSam Clegg const MCAsmLayout &Layout); 319acd7d2b0SSam Clegg 3207c395943SSam Clegg uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry); 321acd7d2b0SSam Clegg void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations, 322acd7d2b0SSam Clegg uint64_t ContentsOffset); 323acd7d2b0SSam Clegg 324acd7d2b0SSam Clegg uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry); 3255e3d33a7SSam Clegg uint32_t getFunctionType(const MCSymbolWasm &Symbol); 3265e3d33a7SSam Clegg uint32_t registerFunctionType(const MCSymbolWasm &Symbol); 32718eafb6cSDan Gohman }; 3289e15f359SSam Clegg 32918eafb6cSDan Gohman } // end anonymous namespace 33018eafb6cSDan Gohman 33118eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {} 33218eafb6cSDan Gohman 333d934cb88SDan Gohman // Write out a section header and a patchable section size field. 334d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section, 3352322a937SSam Clegg unsigned SectionId) { 3362322a937SSam Clegg DEBUG(dbgs() << "startSection " << SectionId << "\n"); 33703e101f1SSam Clegg write8(SectionId); 338d934cb88SDan Gohman 339d934cb88SDan Gohman Section.SizeOffset = getStream().tell(); 340d934cb88SDan Gohman 341d934cb88SDan Gohman // The section size. We don't know the size yet, so reserve enough space 342d934cb88SDan Gohman // for any 32-bit value; we'll patch it later. 343d934cb88SDan Gohman encodeULEB128(UINT32_MAX, getStream()); 344d934cb88SDan Gohman 345d934cb88SDan Gohman // The position where the section starts, for measuring its size. 346d934cb88SDan Gohman Section.ContentsOffset = getStream().tell(); 3476a31a0d6SSam Clegg Section.PayloadOffset = getStream().tell(); 3486f08c84aSSam Clegg Section.Index = SectionCount++; 349d934cb88SDan Gohman } 3502322a937SSam Clegg 3512322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section, 3522322a937SSam Clegg StringRef Name) { 3532322a937SSam Clegg DEBUG(dbgs() << "startCustomSection " << Name << "\n"); 3542322a937SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM); 3556a31a0d6SSam Clegg 3566a31a0d6SSam Clegg // The position where the section header ends, for measuring its size. 3576a31a0d6SSam Clegg Section.PayloadOffset = getStream().tell(); 3586a31a0d6SSam Clegg 3592322a937SSam Clegg // Custom sections in wasm also have a string identifier. 3602322a937SSam Clegg writeString(Name); 3616a31a0d6SSam Clegg 3626a31a0d6SSam Clegg // The position where the custom section starts. 3636a31a0d6SSam Clegg Section.ContentsOffset = getStream().tell(); 364d934cb88SDan Gohman } 365d934cb88SDan Gohman 366d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the 367d934cb88SDan Gohman // section size field at the start of the section. 368d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) { 3696a31a0d6SSam Clegg uint64_t Size = getStream().tell() - Section.PayloadOffset; 370d934cb88SDan Gohman if (uint32_t(Size) != Size) 371d934cb88SDan Gohman report_fatal_error("section size does not fit in a uint32_t"); 372d934cb88SDan Gohman 373b7787fd0SSam Clegg DEBUG(dbgs() << "endSection size=" << Size << "\n"); 374d934cb88SDan Gohman 375d934cb88SDan Gohman // Write the final section size to the payload_len field, which follows 376d934cb88SDan Gohman // the section id byte. 377d934cb88SDan Gohman uint8_t Buffer[16]; 37866a99e41SSam Clegg unsigned SizeLen = encodeULEB128(Size, Buffer, 5); 379d934cb88SDan Gohman assert(SizeLen == 5); 380d934cb88SDan Gohman getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset); 381d934cb88SDan Gohman } 382d934cb88SDan Gohman 38318eafb6cSDan Gohman // Emit the Wasm header. 38418eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { 3857ea5adffSDan Gohman writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic))); 3867ea5adffSDan Gohman writeLE32(wasm::WasmVersion); 38718eafb6cSDan Gohman } 38818eafb6cSDan Gohman 38918eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 39018eafb6cSDan Gohman const MCAsmLayout &Layout) { 39118eafb6cSDan Gohman } 39218eafb6cSDan Gohman 39318eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 39418eafb6cSDan Gohman const MCAsmLayout &Layout, 39518eafb6cSDan Gohman const MCFragment *Fragment, 39618eafb6cSDan Gohman const MCFixup &Fixup, MCValue Target, 397ceecfe5bSRafael Espindola uint64_t &FixedValue) { 398ceecfe5bSRafael Espindola MCAsmBackend &Backend = Asm.getBackend(); 399ceecfe5bSRafael Espindola bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags & 400ceecfe5bSRafael Espindola MCFixupKindInfo::FKF_IsPCRel; 401fe6414b0SSam Clegg const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 402d934cb88SDan Gohman uint64_t C = Target.getConstant(); 403d934cb88SDan Gohman uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 404d934cb88SDan Gohman MCContext &Ctx = Asm.getContext(); 405d934cb88SDan Gohman 406bafe6902SSam Clegg // The .init_array isn't translated as data, so don't do relocations in it. 407bafe6902SSam Clegg if (FixupSection.getSectionName().startswith(".init_array")) 408bafe6902SSam Clegg return; 409bafe6902SSam Clegg 4106a31a0d6SSam Clegg // TODO: Add support for non-debug metadata sections? 4116a31a0d6SSam Clegg if (FixupSection.getKind().isMetadata() && 4126a31a0d6SSam Clegg !FixupSection.getSectionName().startswith(".debug_")) 413b7a5469cSSam Clegg return; 414b7a5469cSSam Clegg 415d934cb88SDan Gohman if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 416d934cb88SDan Gohman assert(RefB->getKind() == MCSymbolRefExpr::VK_None && 417d934cb88SDan Gohman "Should not have constructed this"); 418d934cb88SDan Gohman 419d934cb88SDan Gohman // Let A, B and C being the components of Target and R be the location of 420d934cb88SDan Gohman // the fixup. If the fixup is not pcrel, we want to compute (A - B + C). 421d934cb88SDan Gohman // If it is pcrel, we want to compute (A - B + C - R). 422d934cb88SDan Gohman 423d934cb88SDan Gohman // In general, Wasm has no relocations for -B. It can only represent (A + C) 424d934cb88SDan Gohman // or (A + C - R). If B = R + K and the relocation is not pcrel, we can 425d934cb88SDan Gohman // replace B to implement it: (A - R - K + C) 426d934cb88SDan Gohman if (IsPCRel) { 427d934cb88SDan Gohman Ctx.reportError( 428d934cb88SDan Gohman Fixup.getLoc(), 429d934cb88SDan Gohman "No relocation available to represent this relative expression"); 430d934cb88SDan Gohman return; 431d934cb88SDan Gohman } 432d934cb88SDan Gohman 433d934cb88SDan Gohman const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 434d934cb88SDan Gohman 435d934cb88SDan Gohman if (SymB.isUndefined()) { 436d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 437d934cb88SDan Gohman Twine("symbol '") + SymB.getName() + 438d934cb88SDan Gohman "' can not be undefined in a subtraction expression"); 439d934cb88SDan Gohman return; 440d934cb88SDan Gohman } 441d934cb88SDan Gohman 442d934cb88SDan Gohman assert(!SymB.isAbsolute() && "Should have been folded"); 443d934cb88SDan Gohman const MCSection &SecB = SymB.getSection(); 444d934cb88SDan Gohman if (&SecB != &FixupSection) { 445d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 446d934cb88SDan Gohman "Cannot represent a difference across sections"); 447d934cb88SDan Gohman return; 448d934cb88SDan Gohman } 449d934cb88SDan Gohman 450d934cb88SDan Gohman uint64_t SymBOffset = Layout.getSymbolOffset(SymB); 451d934cb88SDan Gohman uint64_t K = SymBOffset - FixupOffset; 452d934cb88SDan Gohman IsPCRel = true; 453d934cb88SDan Gohman C -= K; 454d934cb88SDan Gohman } 455d934cb88SDan Gohman 456d934cb88SDan Gohman // We either rejected the fixup or folded B into C at this point. 457d934cb88SDan Gohman const MCSymbolRefExpr *RefA = Target.getSymA(); 458d934cb88SDan Gohman const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr; 459d934cb88SDan Gohman 460d934cb88SDan Gohman if (SymA && SymA->isVariable()) { 461d934cb88SDan Gohman const MCExpr *Expr = SymA->getVariableValue(); 4626ad8f190SSam Clegg const auto *Inner = cast<MCSymbolRefExpr>(Expr); 4636ad8f190SSam Clegg if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) 4646ad8f190SSam Clegg llvm_unreachable("weakref used in reloc not yet implemented"); 465d934cb88SDan Gohman } 466d934cb88SDan Gohman 467d934cb88SDan Gohman // Put any constant offset in an addend. Offsets can be negative, and 468d934cb88SDan Gohman // LLVM expects wrapping, in contrast to wasm's immediates which can't 469d934cb88SDan Gohman // be negative and don't wrap. 470d934cb88SDan Gohman FixedValue = 0; 471d934cb88SDan Gohman 4726ad8f190SSam Clegg if (SymA) 473d934cb88SDan Gohman SymA->setUsedInReloc(); 474d934cb88SDan Gohman 475ae03c1e7SSam Clegg assert(!IsPCRel); 4769d24fb7fSSam Clegg assert(SymA); 4779d24fb7fSSam Clegg 478ae03c1e7SSam Clegg unsigned Type = getRelocType(Target, Fixup); 479ae03c1e7SSam Clegg 480d934cb88SDan Gohman WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 481b7787fd0SSam Clegg DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 482d934cb88SDan Gohman 4836a31a0d6SSam Clegg // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB, 4846a31a0d6SSam Clegg // R_WEBASSEMBLY_SECTION_OFFSET_I32 or R_WEBASSEMBLY_FUNCTION_OFFSET_I32 4856a31a0d6SSam Clegg // are currently required to be against a named symbol. 486b7a5469cSSam Clegg // TODO(sbc): Add support for relocations against unnamed temporaries such 487b7a5469cSSam Clegg // as those generated by llvm's `blockaddress`. 488b7a5469cSSam Clegg // See: test/MC/WebAssembly/blockaddress.ll 4896a31a0d6SSam Clegg if (SymA->getName().empty() && 4906a31a0d6SSam Clegg !(Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB || 4916a31a0d6SSam Clegg Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 || 4926a31a0d6SSam Clegg Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32)) 493b7a5469cSSam Clegg report_fatal_error("relocations against un-named temporaries are not yet " 494b7a5469cSSam Clegg "supported by wasm"); 495b7a5469cSSam Clegg 4966a31a0d6SSam Clegg if (FixupSection.isWasmData()) { 497d934cb88SDan Gohman DataRelocations.push_back(Rec); 4986a31a0d6SSam Clegg } else if (FixupSection.getKind().isText()) { 49912fd3da9SSam Clegg CodeRelocations.push_back(Rec); 5006a31a0d6SSam Clegg } else if (FixupSection.getKind().isMetadata()) { 5016a31a0d6SSam Clegg assert(FixupSection.getSectionName().startswith(".debug_")); 5026a31a0d6SSam Clegg CustomSectionsRelocations[&FixupSection].push_back(Rec); 5036a31a0d6SSam Clegg } else { 50412fd3da9SSam Clegg llvm_unreachable("unexpected section type"); 505d934cb88SDan Gohman } 5066a31a0d6SSam Clegg } 507d934cb88SDan Gohman 508d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded 509d934cb88SDan Gohman // to allow patching. 510d934cb88SDan Gohman static void 511d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 512d934cb88SDan Gohman uint8_t Buffer[5]; 51366a99e41SSam Clegg unsigned SizeLen = encodeULEB128(X, Buffer, 5); 514d934cb88SDan Gohman assert(SizeLen == 5); 515d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 516d934cb88SDan Gohman } 517d934cb88SDan Gohman 518d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded 519d934cb88SDan Gohman // to allow patching. 520d934cb88SDan Gohman static void 521d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) { 522d934cb88SDan Gohman uint8_t Buffer[5]; 52366a99e41SSam Clegg unsigned SizeLen = encodeSLEB128(X, Buffer, 5); 524d934cb88SDan Gohman assert(SizeLen == 5); 525d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 526d934cb88SDan Gohman } 527d934cb88SDan Gohman 528d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream. 529d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 530d934cb88SDan Gohman uint8_t Buffer[4]; 531d934cb88SDan Gohman support::endian::write32le(Buffer, X); 532d934cb88SDan Gohman Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 533d934cb88SDan Gohman } 534d934cb88SDan Gohman 535aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) { 536aff1c4dfSSam Clegg if (Symbol.isVariable()) { 537aff1c4dfSSam Clegg const MCExpr *Expr = Symbol.getVariableValue(); 538aff1c4dfSSam Clegg auto *Inner = cast<MCSymbolRefExpr>(Expr); 539aff1c4dfSSam Clegg return cast<MCSymbolWasm>(&Inner->getSymbol()); 540aff1c4dfSSam Clegg } 541aff1c4dfSSam Clegg return &Symbol; 542aff1c4dfSSam Clegg } 543aff1c4dfSSam Clegg 544d934cb88SDan Gohman // Compute a value to write into the code at the location covered 54560ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves 54660ec3034SSam Clegg // to make the object format more readable and more likely to be directly 54760ec3034SSam Clegg // useable. 5487c395943SSam Clegg uint32_t 5497c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) { 55060ec3034SSam Clegg switch (RelEntry.Type) { 55160ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 552f9edbe95SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: { 553f9edbe95SSam Clegg // Provisional value is table address of the resolved symbol itself 554f9edbe95SSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 555f9edbe95SSam Clegg assert(Sym->isFunction()); 556f9edbe95SSam Clegg return TableIndices[Sym]; 557f9edbe95SSam Clegg } 55860ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 5596c899ba6SSam Clegg // Provisional value is same as the index 56060ec3034SSam Clegg return getRelocationIndexValue(RelEntry); 5616c899ba6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 5626c899ba6SSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 5636c899ba6SSam Clegg // Provisional value is function/global Wasm index 5646c899ba6SSam Clegg if (!WasmIndices.count(RelEntry.Symbol)) 5656c899ba6SSam Clegg report_fatal_error("symbol not found in wasm index space: " + 5666c899ba6SSam Clegg RelEntry.Symbol->getName()); 5676c899ba6SSam Clegg return WasmIndices[RelEntry.Symbol]; 5686a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: { 5696a31a0d6SSam Clegg const auto &Section = 5706a31a0d6SSam Clegg static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection()); 5716a31a0d6SSam Clegg return Section.getSectionOffset() + RelEntry.Addend; 5726a31a0d6SSam Clegg } 5736a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: { 5746a31a0d6SSam Clegg const auto &Section = *CustomSectionSymbols.find(RelEntry.Symbol)->second; 5756a31a0d6SSam Clegg return Section.getSectionOffset() + RelEntry.Addend; 5766a31a0d6SSam Clegg } 57760ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 57860ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 57960ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: { 580f9edbe95SSam Clegg // Provisional value is address of the global 58160ec3034SSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 582270ed1b3SSam Clegg // For undefined symbols, use zero 583cd65f698SSam Clegg if (!Sym->isDefined()) 584270ed1b3SSam Clegg return 0; 5856c899ba6SSam Clegg const wasm::WasmDataReference &Ref = DataLocations[Sym]; 5866c899ba6SSam Clegg const WasmDataSegment &Segment = DataSegments[Ref.Segment]; 587d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 5886c899ba6SSam Clegg return Segment.Offset + Ref.Offset + RelEntry.Addend; 58960ec3034SSam Clegg } 59060ec3034SSam Clegg default: 59160ec3034SSam Clegg llvm_unreachable("invalid relocation type"); 59260ec3034SSam Clegg } 593d934cb88SDan Gohman } 594d934cb88SDan Gohman 595759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes, 59663ebb813SSam Clegg MCSectionWasm &DataSection) { 597759631c7SSam Clegg DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n"); 598759631c7SSam Clegg 59963ebb813SSam Clegg DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 60063ebb813SSam Clegg 601759631c7SSam Clegg for (const MCFragment &Frag : DataSection) { 602759631c7SSam Clegg if (Frag.hasInstructions()) 603759631c7SSam Clegg report_fatal_error("only data supported in data sections"); 604759631c7SSam Clegg 605759631c7SSam Clegg if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 606759631c7SSam Clegg if (Align->getValueSize() != 1) 607759631c7SSam Clegg report_fatal_error("only byte values supported for alignment"); 608759631c7SSam Clegg // If nops are requested, use zeros, as this is the data section. 609759631c7SSam Clegg uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 610759631c7SSam Clegg uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(), 611759631c7SSam Clegg Align->getAlignment()), 612759631c7SSam Clegg DataBytes.size() + 613759631c7SSam Clegg Align->getMaxBytesToEmit()); 614759631c7SSam Clegg DataBytes.resize(Size, Value); 615759631c7SSam Clegg } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 616d707c370SRafael Espindola int64_t Size; 617d707c370SRafael Espindola if (!Fill->getSize().evaluateAsAbsolute(Size)) 618d707c370SRafael Espindola llvm_unreachable("The fill should be an assembler constant"); 619d707c370SRafael Espindola DataBytes.insert(DataBytes.end(), Size, Fill->getValue()); 620759631c7SSam Clegg } else { 621759631c7SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 622759631c7SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 623759631c7SSam Clegg 624759631c7SSam Clegg DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 625759631c7SSam Clegg } 626759631c7SSam Clegg } 627759631c7SSam Clegg 628759631c7SSam Clegg DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 629759631c7SSam Clegg } 630759631c7SSam Clegg 63160ec3034SSam Clegg uint32_t 63260ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) { 63360ec3034SSam Clegg if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) { 634b7787fd0SSam Clegg if (!TypeIndices.count(RelEntry.Symbol)) 635b7787fd0SSam Clegg report_fatal_error("symbol not found in type index space: " + 636b7787fd0SSam Clegg RelEntry.Symbol->getName()); 637acd7d2b0SSam Clegg return TypeIndices[RelEntry.Symbol]; 638acd7d2b0SSam Clegg } 63960ec3034SSam Clegg 64060ec3034SSam Clegg if (!SymbolIndices.count(RelEntry.Symbol)) 6416c899ba6SSam Clegg report_fatal_error("symbol not found in symbol index space: " + 64260ec3034SSam Clegg RelEntry.Symbol->getName()); 64360ec3034SSam Clegg return SymbolIndices[RelEntry.Symbol]; 644acd7d2b0SSam Clegg } 645acd7d2b0SSam Clegg 646d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 647d934cb88SDan Gohman // directly. 648acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations( 649acd7d2b0SSam Clegg ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) { 650acd7d2b0SSam Clegg raw_pwrite_stream &Stream = getStream(); 651d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 652d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 653d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 654d934cb88SDan Gohman RelEntry.Offset; 655d934cb88SDan Gohman 656b7787fd0SSam Clegg DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 65760ec3034SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 65860ec3034SSam Clegg 659acd7d2b0SSam Clegg switch (RelEntry.Type) { 660acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 6619d24fb7fSSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 66260ec3034SSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 66360ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 664d934cb88SDan Gohman WritePatchableLEB(Stream, Value, Offset); 665d934cb88SDan Gohman break; 66660ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 66760ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 6686a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: 6696a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: 670d934cb88SDan Gohman WriteI32(Stream, Value, Offset); 671d934cb88SDan Gohman break; 67260ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 67360ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 67460ec3034SSam Clegg WritePatchableSLEB(Stream, Value, Offset); 67560ec3034SSam Clegg break; 676d934cb88SDan Gohman default: 6779d24fb7fSSam Clegg llvm_unreachable("invalid relocation type"); 678d934cb88SDan Gohman } 679d934cb88SDan Gohman } 68018eafb6cSDan Gohman } 68118eafb6cSDan Gohman 6829e15f359SSam Clegg void WasmObjectWriter::writeTypeSection( 683457fb0b4SSam Clegg ArrayRef<WasmFunctionType> FunctionTypes) { 6849e15f359SSam Clegg if (FunctionTypes.empty()) 6859e15f359SSam Clegg return; 6869e15f359SSam Clegg 6879e15f359SSam Clegg SectionBookkeeping Section; 6889e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TYPE); 6899e15f359SSam Clegg 6909e15f359SSam Clegg encodeULEB128(FunctionTypes.size(), getStream()); 6919e15f359SSam Clegg 6929e15f359SSam Clegg for (const WasmFunctionType &FuncTy : FunctionTypes) { 69303e101f1SSam Clegg write8(wasm::WASM_TYPE_FUNC); 6949e15f359SSam Clegg encodeULEB128(FuncTy.Params.size(), getStream()); 6959e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Params) 6969e15f359SSam Clegg writeValueType(Ty); 6979e15f359SSam Clegg encodeULEB128(FuncTy.Returns.size(), getStream()); 6989e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Returns) 6999e15f359SSam Clegg writeValueType(Ty); 7009e15f359SSam Clegg } 7019e15f359SSam Clegg 7029e15f359SSam Clegg endSection(Section); 7039e15f359SSam Clegg } 7049e15f359SSam Clegg 7058defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports, 706f950b24aSSam Clegg uint32_t DataSize, 707f950b24aSSam Clegg uint32_t NumElements) { 7089e15f359SSam Clegg if (Imports.empty()) 7099e15f359SSam Clegg return; 7109e15f359SSam Clegg 711f950b24aSSam Clegg uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 712f950b24aSSam Clegg 7139e15f359SSam Clegg SectionBookkeeping Section; 7149e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_IMPORT); 7159e15f359SSam Clegg 7169e15f359SSam Clegg encodeULEB128(Imports.size(), getStream()); 7178defa952SSam Clegg for (const wasm::WasmImport &Import : Imports) { 7188defa952SSam Clegg writeString(Import.Module); 7198defa952SSam Clegg writeString(Import.Field); 72003e101f1SSam Clegg write8(Import.Kind); 7219e15f359SSam Clegg 7229e15f359SSam Clegg switch (Import.Kind) { 7239e15f359SSam Clegg case wasm::WASM_EXTERNAL_FUNCTION: 7248defa952SSam Clegg encodeULEB128(Import.SigIndex, getStream()); 7259e15f359SSam Clegg break; 7269e15f359SSam Clegg case wasm::WASM_EXTERNAL_GLOBAL: 72703e101f1SSam Clegg write8(Import.Global.Type); 72803e101f1SSam Clegg write8(Import.Global.Mutable ? 1 : 0); 7299e15f359SSam Clegg break; 730f950b24aSSam Clegg case wasm::WASM_EXTERNAL_MEMORY: 731f950b24aSSam Clegg encodeULEB128(0, getStream()); // flags 732f950b24aSSam Clegg encodeULEB128(NumPages, getStream()); // initial 733f950b24aSSam Clegg break; 734f950b24aSSam Clegg case wasm::WASM_EXTERNAL_TABLE: 73503e101f1SSam Clegg write8(Import.Table.ElemType); 736f950b24aSSam Clegg encodeULEB128(0, getStream()); // flags 737f950b24aSSam Clegg encodeULEB128(NumElements, getStream()); // initial 738f950b24aSSam Clegg break; 7399e15f359SSam Clegg default: 7409e15f359SSam Clegg llvm_unreachable("unsupported import kind"); 7419e15f359SSam Clegg } 7429e15f359SSam Clegg } 7439e15f359SSam Clegg 7449e15f359SSam Clegg endSection(Section); 7459e15f359SSam Clegg } 7469e15f359SSam Clegg 747457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 7489e15f359SSam Clegg if (Functions.empty()) 7499e15f359SSam Clegg return; 7509e15f359SSam Clegg 7519e15f359SSam Clegg SectionBookkeeping Section; 7529e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_FUNCTION); 7539e15f359SSam Clegg 7549e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 7559e15f359SSam Clegg for (const WasmFunction &Func : Functions) 7569e15f359SSam Clegg encodeULEB128(Func.Type, getStream()); 7579e15f359SSam Clegg 7589e15f359SSam Clegg endSection(Section); 7599e15f359SSam Clegg } 7609e15f359SSam Clegg 7617c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() { 7629e15f359SSam Clegg if (Globals.empty()) 7639e15f359SSam Clegg return; 7649e15f359SSam Clegg 7659e15f359SSam Clegg SectionBookkeeping Section; 7669e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_GLOBAL); 7679e15f359SSam Clegg 7689e15f359SSam Clegg encodeULEB128(Globals.size(), getStream()); 7699e15f359SSam Clegg for (const WasmGlobal &Global : Globals) { 7706e7f1826SSam Clegg writeValueType(static_cast<wasm::ValType>(Global.Type.Type)); 7716e7f1826SSam Clegg write8(Global.Type.Mutable); 7729e15f359SSam Clegg 7739e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 7746e7f1826SSam Clegg encodeSLEB128(Global.InitialValue, getStream()); 7759e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 7769e15f359SSam Clegg } 7779e15f359SSam Clegg 7789e15f359SSam Clegg endSection(Section); 7799e15f359SSam Clegg } 7809e15f359SSam Clegg 7818defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) { 7829e15f359SSam Clegg if (Exports.empty()) 7839e15f359SSam Clegg return; 7849e15f359SSam Clegg 7859e15f359SSam Clegg SectionBookkeeping Section; 7869e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_EXPORT); 7879e15f359SSam Clegg 7889e15f359SSam Clegg encodeULEB128(Exports.size(), getStream()); 7898defa952SSam Clegg for (const wasm::WasmExport &Export : Exports) { 7908defa952SSam Clegg writeString(Export.Name); 79103e101f1SSam Clegg write8(Export.Kind); 7929e15f359SSam Clegg encodeULEB128(Export.Index, getStream()); 7939e15f359SSam Clegg } 7949e15f359SSam Clegg 7959e15f359SSam Clegg endSection(Section); 7969e15f359SSam Clegg } 7979e15f359SSam Clegg 798457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 7999e15f359SSam Clegg if (TableElems.empty()) 8009e15f359SSam Clegg return; 8019e15f359SSam Clegg 8029e15f359SSam Clegg SectionBookkeeping Section; 8039e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_ELEM); 8049e15f359SSam Clegg 8059e15f359SSam Clegg encodeULEB128(1, getStream()); // number of "segments" 8069e15f359SSam Clegg encodeULEB128(0, getStream()); // the table index 8079e15f359SSam Clegg 8089e15f359SSam Clegg // init expr for starting offset 8099e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 81030e1bbc1SSam Clegg encodeSLEB128(kInitialTableOffset, getStream()); 8119e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 8129e15f359SSam Clegg 8139e15f359SSam Clegg encodeULEB128(TableElems.size(), getStream()); 8149e15f359SSam Clegg for (uint32_t Elem : TableElems) 8159e15f359SSam Clegg encodeULEB128(Elem, getStream()); 8169e15f359SSam Clegg 8179e15f359SSam Clegg endSection(Section); 8189e15f359SSam Clegg } 8199e15f359SSam Clegg 820457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 821457fb0b4SSam Clegg const MCAsmLayout &Layout, 822457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions) { 8239e15f359SSam Clegg if (Functions.empty()) 8249e15f359SSam Clegg return; 8259e15f359SSam Clegg 8269e15f359SSam Clegg SectionBookkeeping Section; 8279e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CODE); 8286f08c84aSSam Clegg CodeSectionIndex = Section.Index; 8299e15f359SSam Clegg 8309e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 8319e15f359SSam Clegg 8329e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 833fe6414b0SSam Clegg auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 8349e15f359SSam Clegg 8359e15f359SSam Clegg int64_t Size = 0; 8369e15f359SSam Clegg if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 8379e15f359SSam Clegg report_fatal_error(".size expression must be evaluatable"); 8389e15f359SSam Clegg 8399e15f359SSam Clegg encodeULEB128(Size, getStream()); 840fe6414b0SSam Clegg FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset); 8419e15f359SSam Clegg Asm.writeSectionData(&FuncSection, Layout); 8429e15f359SSam Clegg } 8439e15f359SSam Clegg 8449e15f359SSam Clegg // Apply fixups. 845acd7d2b0SSam Clegg applyRelocations(CodeRelocations, Section.ContentsOffset); 8469e15f359SSam Clegg 8479e15f359SSam Clegg endSection(Section); 8489e15f359SSam Clegg } 8499e15f359SSam Clegg 8506c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() { 8516c899ba6SSam Clegg if (DataSegments.empty()) 8527c395943SSam Clegg return; 8539e15f359SSam Clegg 8549e15f359SSam Clegg SectionBookkeeping Section; 8559e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_DATA); 8566f08c84aSSam Clegg DataSectionIndex = Section.Index; 8579e15f359SSam Clegg 8586c899ba6SSam Clegg encodeULEB128(DataSegments.size(), getStream()); // count 8597c395943SSam Clegg 8606c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 8619e15f359SSam Clegg encodeULEB128(0, getStream()); // memory index 8629e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 8637c395943SSam Clegg encodeSLEB128(Segment.Offset, getStream()); // offset 8649e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 8657c395943SSam Clegg encodeULEB128(Segment.Data.size(), getStream()); // size 8667c395943SSam Clegg Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset); 8677c395943SSam Clegg writeBytes(Segment.Data); // data 8687c395943SSam Clegg } 8699e15f359SSam Clegg 8709e15f359SSam Clegg // Apply fixups. 8717c395943SSam Clegg applyRelocations(DataRelocations, Section.ContentsOffset); 8729e15f359SSam Clegg 8739e15f359SSam Clegg endSection(Section); 8749e15f359SSam Clegg } 8759e15f359SSam Clegg 8766f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection( 8776f08c84aSSam Clegg uint32_t SectionIndex, StringRef Name, 8786f08c84aSSam Clegg ArrayRef<WasmRelocationEntry> Relocations) { 8799e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 8809e15f359SSam Clegg // for descriptions of the reloc sections. 8819e15f359SSam Clegg 8826f08c84aSSam Clegg if (Relocations.empty()) 8839e15f359SSam Clegg return; 8849e15f359SSam Clegg 8859e15f359SSam Clegg SectionBookkeeping Section; 8866f08c84aSSam Clegg startCustomSection(Section, std::string("reloc.") + Name.str()); 8879e15f359SSam Clegg 8886f08c84aSSam Clegg raw_pwrite_stream &Stream = getStream(); 8899e15f359SSam Clegg 8906f08c84aSSam Clegg encodeULEB128(SectionIndex, Stream); 8916f08c84aSSam Clegg encodeULEB128(Relocations.size(), Stream); 8926f08c84aSSam Clegg for (const WasmRelocationEntry& RelEntry : Relocations) { 8936f08c84aSSam Clegg uint64_t Offset = RelEntry.Offset + 8946f08c84aSSam Clegg RelEntry.FixupSection->getSectionOffset(); 8956f08c84aSSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 8969e15f359SSam Clegg 8976f08c84aSSam Clegg write8(RelEntry.Type); 8986f08c84aSSam Clegg encodeULEB128(Offset, Stream); 8996f08c84aSSam Clegg encodeULEB128(Index, Stream); 9006f08c84aSSam Clegg if (RelEntry.hasAddend()) 9016f08c84aSSam Clegg encodeSLEB128(RelEntry.Addend, Stream); 9029e15f359SSam Clegg } 9039e15f359SSam Clegg 9049e15f359SSam Clegg endSection(Section); 9059e15f359SSam Clegg } 9069e15f359SSam Clegg 9076a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() { 9086a31a0d6SSam Clegg for (const auto &Sec : CustomSections) { 9096a31a0d6SSam Clegg auto &Relocations = CustomSectionsRelocations[Sec.Section]; 9106a31a0d6SSam Clegg writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations); 9116a31a0d6SSam Clegg } 9126a31a0d6SSam Clegg } 9136a31a0d6SSam Clegg 9149e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection( 91586b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 916ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 917ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) { 9189e15f359SSam Clegg SectionBookkeeping Section; 9192322a937SSam Clegg startCustomSection(Section, "linking"); 9206bb5a41fSSam Clegg encodeULEB128(wasm::WasmMetadataVersion, getStream()); 9219e15f359SSam Clegg 9226bb5a41fSSam Clegg SectionBookkeeping SubSection; 9236c899ba6SSam Clegg if (SymbolInfos.size() != 0) { 9246c899ba6SSam Clegg startSection(SubSection, wasm::WASM_SYMBOL_TABLE); 9256c899ba6SSam Clegg encodeULEB128(SymbolInfos.size(), getStream()); 9266c899ba6SSam Clegg for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) { 9276c899ba6SSam Clegg encodeULEB128(Sym.Kind, getStream()); 9286c899ba6SSam Clegg encodeULEB128(Sym.Flags, getStream()); 9296c899ba6SSam Clegg switch (Sym.Kind) { 9306c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_FUNCTION: 9316c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_GLOBAL: 9326c899ba6SSam Clegg encodeULEB128(Sym.ElementIndex, getStream()); 9336c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) 9346c899ba6SSam Clegg writeString(Sym.Name); 9356c899ba6SSam Clegg break; 9366c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_DATA: 9376c899ba6SSam Clegg writeString(Sym.Name); 9386c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) { 9396c899ba6SSam Clegg encodeULEB128(Sym.DataRef.Segment, getStream()); 9406c899ba6SSam Clegg encodeULEB128(Sym.DataRef.Offset, getStream()); 9416c899ba6SSam Clegg encodeULEB128(Sym.DataRef.Size, getStream()); 9426c899ba6SSam Clegg } 9436c899ba6SSam Clegg break; 9446a31a0d6SSam Clegg case wasm::WASM_SYMBOL_TYPE_SECTION: { 9456a31a0d6SSam Clegg const uint32_t SectionIndex = 9466a31a0d6SSam Clegg CustomSections[Sym.ElementIndex].OutputIndex; 9476a31a0d6SSam Clegg encodeULEB128(SectionIndex, getStream()); 9486a31a0d6SSam Clegg break; 9496a31a0d6SSam Clegg } 9506c899ba6SSam Clegg default: 9516c899ba6SSam Clegg llvm_unreachable("unexpected kind"); 9526c899ba6SSam Clegg } 953b7787fd0SSam Clegg } 954b7787fd0SSam Clegg endSection(SubSection); 955b7787fd0SSam Clegg } 9569e15f359SSam Clegg 9576c899ba6SSam Clegg if (DataSegments.size()) { 95863ebb813SSam Clegg startSection(SubSection, wasm::WASM_SEGMENT_INFO); 9596c899ba6SSam Clegg encodeULEB128(DataSegments.size(), getStream()); 9606c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 961d95ed959SSam Clegg writeString(Segment.Name); 96263ebb813SSam Clegg encodeULEB128(Segment.Alignment, getStream()); 96363ebb813SSam Clegg encodeULEB128(Segment.Flags, getStream()); 96463ebb813SSam Clegg } 965d95ed959SSam Clegg endSection(SubSection); 966d95ed959SSam Clegg } 967d95ed959SSam Clegg 968bafe6902SSam Clegg if (!InitFuncs.empty()) { 969bafe6902SSam Clegg startSection(SubSection, wasm::WASM_INIT_FUNCS); 970bafe6902SSam Clegg encodeULEB128(InitFuncs.size(), getStream()); 971bafe6902SSam Clegg for (auto &StartFunc : InitFuncs) { 972bafe6902SSam Clegg encodeULEB128(StartFunc.first, getStream()); // priority 973bafe6902SSam Clegg encodeULEB128(StartFunc.second, getStream()); // function index 974bafe6902SSam Clegg } 975bafe6902SSam Clegg endSection(SubSection); 976bafe6902SSam Clegg } 977bafe6902SSam Clegg 978ea7caceeSSam Clegg if (Comdats.size()) { 979ea7caceeSSam Clegg startSection(SubSection, wasm::WASM_COMDAT_INFO); 980ea7caceeSSam Clegg encodeULEB128(Comdats.size(), getStream()); 981ea7caceeSSam Clegg for (const auto &C : Comdats) { 982ea7caceeSSam Clegg writeString(C.first); 983ea7caceeSSam Clegg encodeULEB128(0, getStream()); // flags for future use 984ea7caceeSSam Clegg encodeULEB128(C.second.size(), getStream()); 985ea7caceeSSam Clegg for (const WasmComdatEntry &Entry : C.second) { 986ea7caceeSSam Clegg encodeULEB128(Entry.Kind, getStream()); 987ea7caceeSSam Clegg encodeULEB128(Entry.Index, getStream()); 988ea7caceeSSam Clegg } 989ea7caceeSSam Clegg } 990ea7caceeSSam Clegg endSection(SubSection); 991ea7caceeSSam Clegg } 992ea7caceeSSam Clegg 9939e15f359SSam Clegg endSection(Section); 9949e15f359SSam Clegg } 9959e15f359SSam Clegg 9966a31a0d6SSam Clegg void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm, 9976a31a0d6SSam Clegg const MCAsmLayout &Layout) { 9986a31a0d6SSam Clegg for (auto &CustomSection : CustomSections) { 999cfd44a2eSSam Clegg SectionBookkeeping Section; 10006a31a0d6SSam Clegg auto *Sec = CustomSection.Section; 10012322a937SSam Clegg startCustomSection(Section, CustomSection.Name); 10026a31a0d6SSam Clegg 10036a31a0d6SSam Clegg Sec->setSectionOffset(getStream().tell() - Section.ContentsOffset); 10046a31a0d6SSam Clegg Asm.writeSectionData(Sec, Layout); 10056a31a0d6SSam Clegg 10066a31a0d6SSam Clegg CustomSection.OutputContentsOffset = Section.ContentsOffset; 10076a31a0d6SSam Clegg CustomSection.OutputIndex = Section.Index; 10086a31a0d6SSam Clegg 1009cfd44a2eSSam Clegg endSection(Section); 1010cfd44a2eSSam Clegg } 1011cfd44a2eSSam Clegg } 1012cfd44a2eSSam Clegg 10136a31a0d6SSam Clegg void WasmObjectWriter::updateCustomSectionRelocations( 10146a31a0d6SSam Clegg const SmallVector<WasmFunction, 4> &Functions, const MCAsmLayout &Layout) { 10156a31a0d6SSam Clegg std::map<const MCSection *, const MCSymbolWasm *> SectionSymbols; 10166a31a0d6SSam Clegg for (const auto &P : CustomSectionSymbols) 10176a31a0d6SSam Clegg SectionSymbols[P.second] = P.first; 10186a31a0d6SSam Clegg std::map<const MCSection *, const MCSymbolWasm *> FuncSymbols; 10196a31a0d6SSam Clegg for (const auto &FuncInfo : Functions) 10206a31a0d6SSam Clegg FuncSymbols[&FuncInfo.Sym->getSection()] = FuncInfo.Sym; 10216a31a0d6SSam Clegg 10226a31a0d6SSam Clegg // Patch relocation records for R_WEBASSEMBLY_FUNCTION_OFFSET_I32 and 10236a31a0d6SSam Clegg // R_WEBASSEMBLY_SECTION_OFFSET_I32. The Addend is stuffed the offset from 10246a31a0d6SSam Clegg // the beginning of the function or custom section -- all such relocations 10256a31a0d6SSam Clegg // target the function or custom section starts. 10266a31a0d6SSam Clegg for (auto &Section : CustomSections) { 10276a31a0d6SSam Clegg auto &Relocations = CustomSectionsRelocations[Section.Section]; 10286a31a0d6SSam Clegg for (WasmRelocationEntry &RelEntry : Relocations) { 10296a31a0d6SSam Clegg switch (RelEntry.Type) { 10306a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: { 10316a31a0d6SSam Clegg assert(RelEntry.hasAddend()); 10326a31a0d6SSam Clegg auto &Section = 10336a31a0d6SSam Clegg static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection()); 10346a31a0d6SSam Clegg RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol); 10356a31a0d6SSam Clegg RelEntry.Symbol = FuncSymbols[&Section]; 10366a31a0d6SSam Clegg break; 10376a31a0d6SSam Clegg } 10386a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: { 10396a31a0d6SSam Clegg assert(RelEntry.hasAddend()); 10406a31a0d6SSam Clegg auto &Section = 10416a31a0d6SSam Clegg static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection()); 10426a31a0d6SSam Clegg RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol); 10436a31a0d6SSam Clegg RelEntry.Symbol = SectionSymbols[&Section]; 10446a31a0d6SSam Clegg break; 10456a31a0d6SSam Clegg } 10466a31a0d6SSam Clegg default: 10476a31a0d6SSam Clegg break; 10486a31a0d6SSam Clegg } 10496a31a0d6SSam Clegg } 10506a31a0d6SSam Clegg 10516a31a0d6SSam Clegg // Apply fixups. 10526a31a0d6SSam Clegg applyRelocations(Relocations, Section.OutputContentsOffset); 10536a31a0d6SSam Clegg } 10546a31a0d6SSam Clegg } 10556a31a0d6SSam Clegg 10565e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) { 10575e3d33a7SSam Clegg assert(Symbol.isFunction()); 10585e3d33a7SSam Clegg assert(TypeIndices.count(&Symbol)); 10595e3d33a7SSam Clegg return TypeIndices[&Symbol]; 10605e3d33a7SSam Clegg } 10615e3d33a7SSam Clegg 10625e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) { 10635e3d33a7SSam Clegg assert(Symbol.isFunction()); 10645e3d33a7SSam Clegg 10655e3d33a7SSam Clegg WasmFunctionType F; 1066aff1c4dfSSam Clegg const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol); 10675e3d33a7SSam Clegg F.Returns = ResolvedSym->getReturns(); 10685e3d33a7SSam Clegg F.Params = ResolvedSym->getParams(); 10695e3d33a7SSam Clegg 10705e3d33a7SSam Clegg auto Pair = 10715e3d33a7SSam Clegg FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); 10725e3d33a7SSam Clegg if (Pair.second) 10735e3d33a7SSam Clegg FunctionTypes.push_back(F); 10745e3d33a7SSam Clegg TypeIndices[&Symbol] = Pair.first->second; 10755e3d33a7SSam Clegg 10765e3d33a7SSam Clegg DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n"); 10775e3d33a7SSam Clegg DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 10785e3d33a7SSam Clegg return Pair.first->second; 10795e3d33a7SSam Clegg } 10805e3d33a7SSam Clegg 108118eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm, 108218eafb6cSDan Gohman const MCAsmLayout &Layout) { 1083b7787fd0SSam Clegg DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 108482607f56SDan Gohman MCContext &Ctx = Asm.getContext(); 1085d934cb88SDan Gohman 1086d934cb88SDan Gohman // Collect information from the available symbols. 1087d934cb88SDan Gohman SmallVector<WasmFunction, 4> Functions; 1088d934cb88SDan Gohman SmallVector<uint32_t, 4> TableElems; 10898defa952SSam Clegg SmallVector<wasm::WasmImport, 4> Imports; 10908defa952SSam Clegg SmallVector<wasm::WasmExport, 4> Exports; 10916c899ba6SSam Clegg SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos; 1092bafe6902SSam Clegg SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 1093ea7caceeSSam Clegg std::map<StringRef, std::vector<WasmComdatEntry>> Comdats; 10947c395943SSam Clegg uint32_t DataSize = 0; 1095d934cb88SDan Gohman 1096f950b24aSSam Clegg // For now, always emit the memory import, since loads and stores are not 1097f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1098f950b24aSSam Clegg // it if there are no loads or stores. 1099f950b24aSSam Clegg MCSymbolWasm *MemorySym = 1100f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory")); 11018defa952SSam Clegg wasm::WasmImport MemImport; 11028defa952SSam Clegg MemImport.Module = MemorySym->getModuleName(); 11038defa952SSam Clegg MemImport.Field = MemorySym->getName(); 1104f950b24aSSam Clegg MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1105f950b24aSSam Clegg Imports.push_back(MemImport); 1106f950b24aSSam Clegg 1107f950b24aSSam Clegg // For now, always emit the table section, since indirect calls are not 1108f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1109f950b24aSSam Clegg // it if there are no indirect calls. 1110f950b24aSSam Clegg MCSymbolWasm *TableSym = 1111f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table")); 11128defa952SSam Clegg wasm::WasmImport TableImport; 11138defa952SSam Clegg TableImport.Module = TableSym->getModuleName(); 11148defa952SSam Clegg TableImport.Field = TableSym->getName(); 1115f950b24aSSam Clegg TableImport.Kind = wasm::WASM_EXTERNAL_TABLE; 11168defa952SSam Clegg TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC; 1117f950b24aSSam Clegg Imports.push_back(TableImport); 1118f950b24aSSam Clegg 1119586320c0SNicholas Wilson // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined 1120586320c0SNicholas Wilson // symbols. This must be done before populating WasmIndices for defined 1121586320c0SNicholas Wilson // symbols. 112232ce5ca0SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 112332ce5ca0SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 112432ce5ca0SDan Gohman 112532ce5ca0SDan Gohman // Register types for all functions, including those with private linkage 11269f3fe42eSSam Clegg // (because wasm always needs a type signature). 112732ce5ca0SDan Gohman if (WS.isFunction()) 112832ce5ca0SDan Gohman registerFunctionType(WS); 112932ce5ca0SDan Gohman 113032ce5ca0SDan Gohman if (WS.isTemporary()) 113132ce5ca0SDan Gohman continue; 113232ce5ca0SDan Gohman 113332ce5ca0SDan Gohman // If the symbol is not defined in this translation unit, import it. 11346c899ba6SSam Clegg if (!WS.isDefined() && !WS.isComdat()) { 11356c899ba6SSam Clegg if (WS.isFunction()) { 11368defa952SSam Clegg wasm::WasmImport Import; 11378defa952SSam Clegg Import.Module = WS.getModuleName(); 11388defa952SSam Clegg Import.Field = WS.getName(); 113932ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 11408defa952SSam Clegg Import.SigIndex = getFunctionType(WS); 11416c899ba6SSam Clegg Imports.push_back(Import); 11426c899ba6SSam Clegg WasmIndices[&WS] = NumFunctionImports++; 11436c899ba6SSam Clegg } else if (WS.isGlobal()) { 114415f349f7SNicholas Wilson if (WS.isWeak()) 114515f349f7SNicholas Wilson report_fatal_error("undefined global symbol cannot be weak"); 114615f349f7SNicholas Wilson 11476c899ba6SSam Clegg wasm::WasmImport Import; 11486c899ba6SSam Clegg Import.Module = WS.getModuleName(); 11496c899ba6SSam Clegg Import.Field = WS.getName(); 115032ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 11516c899ba6SSam Clegg Import.Global = WS.getGlobalType(); 11526c899ba6SSam Clegg Imports.push_back(Import); 11536c899ba6SSam Clegg WasmIndices[&WS] = NumGlobalImports++; 115432ce5ca0SDan Gohman } 115532ce5ca0SDan Gohman } 115632ce5ca0SDan Gohman } 115732ce5ca0SDan Gohman 1158586320c0SNicholas Wilson // Populate DataSegments, which must be done before populating DataLocations. 1159759631c7SSam Clegg for (MCSection &Sec : Asm) { 1160759631c7SSam Clegg auto &Section = static_cast<MCSectionWasm &>(Sec); 1161cfd44a2eSSam Clegg 11626a31a0d6SSam Clegg if (Section.getSectionName().startswith(".custom_section.")) { 1163cfd44a2eSSam Clegg if (Section.getFragmentList().empty()) 1164cfd44a2eSSam Clegg continue; 1165cfd44a2eSSam Clegg if (Section.getFragmentList().size() != 1) 1166cfd44a2eSSam Clegg report_fatal_error( 1167cfd44a2eSSam Clegg "only one .custom_section section fragment supported"); 1168cfd44a2eSSam Clegg const MCFragment &Frag = *Section.begin(); 1169cfd44a2eSSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1170cfd44a2eSSam Clegg report_fatal_error("only data supported in .custom_section section"); 1171cfd44a2eSSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1172cfd44a2eSSam Clegg if (!DataFrag.getFixups().empty()) 1173cfd44a2eSSam Clegg report_fatal_error("fixups not supported in .custom_section section"); 1174cfd44a2eSSam Clegg StringRef UserName = Section.getSectionName().substr(16); 11756a31a0d6SSam Clegg CustomSections.emplace_back(UserName, &Section); 1176cfd44a2eSSam Clegg continue; 1177cfd44a2eSSam Clegg } 1178cfd44a2eSSam Clegg 117912fd3da9SSam Clegg if (!Section.isWasmData()) 1180759631c7SSam Clegg continue; 1181759631c7SSam Clegg 1182bafe6902SSam Clegg // .init_array sections are handled specially elsewhere. 1183bafe6902SSam Clegg if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array")) 1184bafe6902SSam Clegg continue; 1185bafe6902SSam Clegg 1186329e76d5SSam Clegg uint32_t SegmentIndex = DataSegments.size(); 1187759631c7SSam Clegg DataSize = alignTo(DataSize, Section.getAlignment()); 1188759631c7SSam Clegg DataSegments.emplace_back(); 1189759631c7SSam Clegg WasmDataSegment &Segment = DataSegments.back(); 1190d95ed959SSam Clegg Segment.Name = Section.getSectionName(); 1191759631c7SSam Clegg Segment.Offset = DataSize; 1192759631c7SSam Clegg Segment.Section = &Section; 119363ebb813SSam Clegg addData(Segment.Data, Section); 119463ebb813SSam Clegg Segment.Alignment = Section.getAlignment(); 119563ebb813SSam Clegg Segment.Flags = 0; 1196759631c7SSam Clegg DataSize += Segment.Data.size(); 11976c899ba6SSam Clegg Section.setSegmentIndex(SegmentIndex); 1198ea7caceeSSam Clegg 1199ea7caceeSSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 1200ea7caceeSSam Clegg Comdats[C->getName()].emplace_back( 1201329e76d5SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex}); 1202ea7caceeSSam Clegg } 1203759631c7SSam Clegg } 1204759631c7SSam Clegg 12056a31a0d6SSam Clegg // Create symbols for debug/custom sections. 12066a31a0d6SSam Clegg for (MCSection &Sec : Asm) { 12076a31a0d6SSam Clegg auto &DebugSection = static_cast<MCSectionWasm &>(Sec); 12086a31a0d6SSam Clegg StringRef SectionName = DebugSection.getSectionName(); 12096a31a0d6SSam Clegg 12106a31a0d6SSam Clegg // TODO: Add support for non-debug metadata sections? 12116a31a0d6SSam Clegg if (!Sec.getKind().isMetadata() || !SectionName.startswith(".debug_")) 12126a31a0d6SSam Clegg continue; 12136a31a0d6SSam Clegg 12146a31a0d6SSam Clegg uint32_t ElementIndex = CustomSections.size(); 12156a31a0d6SSam Clegg CustomSections.emplace_back(SectionName, &DebugSection); 12166a31a0d6SSam Clegg 12176a31a0d6SSam Clegg MCSymbolWasm *SectionSym = 12186a31a0d6SSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SectionName)); 12196a31a0d6SSam Clegg CustomSectionSymbols[SectionSym] = &DebugSection; 12206a31a0d6SSam Clegg 12216a31a0d6SSam Clegg wasm::WasmSymbolInfo Info; 12226a31a0d6SSam Clegg Info.Name = SectionSym->getName(); 12236a31a0d6SSam Clegg Info.Kind = wasm::WASM_SYMBOL_TYPE_SECTION; 1224d5504a0aSSam Clegg Info.Flags = wasm::WASM_SYMBOL_BINDING_LOCAL; 12256a31a0d6SSam Clegg Info.ElementIndex = ElementIndex; 12266a31a0d6SSam Clegg SymbolIndices[SectionSym] = SymbolInfos.size(); 12276a31a0d6SSam Clegg SymbolInfos.emplace_back(Info); 12286a31a0d6SSam Clegg } 12296a31a0d6SSam Clegg 1230586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for defined symbols. 1231d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1232d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1233d934cb88SDan Gohman // or used in relocations. 1234d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 1235d934cb88SDan Gohman continue; 1236b7787fd0SSam Clegg 1237d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 1238b7787fd0SSam Clegg DEBUG(dbgs() << "MCSymbol: '" << S << "'" 1239329e76d5SSam Clegg << " isDefined=" << S.isDefined() 1240329e76d5SSam Clegg << " isExternal=" << S.isExternal() 1241329e76d5SSam Clegg << " isTemporary=" << S.isTemporary() 1242b7787fd0SSam Clegg << " isFunction=" << WS.isFunction() 1243b7787fd0SSam Clegg << " isWeak=" << WS.isWeak() 1244a2b35dacSSam Clegg << " isHidden=" << WS.isHidden() 1245b7787fd0SSam Clegg << " isVariable=" << WS.isVariable() << "\n"); 1246b7787fd0SSam Clegg 12475e3d33a7SSam Clegg if (WS.isVariable()) 12485e3d33a7SSam Clegg continue; 12496c899ba6SSam Clegg if (WS.isComdat() && !WS.isDefined()) 12506c899ba6SSam Clegg continue; 1251b7787fd0SSam Clegg 1252d934cb88SDan Gohman if (WS.isFunction()) { 12536c899ba6SSam Clegg unsigned Index; 1254cd65f698SSam Clegg if (WS.isDefined()) { 1255b7787fd0SSam Clegg if (WS.getOffset() != 0) 1256b7787fd0SSam Clegg report_fatal_error( 1257b7787fd0SSam Clegg "function sections must contain one function each"); 1258b7787fd0SSam Clegg 1259b7787fd0SSam Clegg if (WS.getSize() == 0) 1260b7787fd0SSam Clegg report_fatal_error( 1261b7787fd0SSam Clegg "function symbols must have a size set with .size"); 1262b7787fd0SSam Clegg 12636c899ba6SSam Clegg // A definition. Write out the function body. 12649f3fe42eSSam Clegg Index = NumFunctionImports + Functions.size(); 1265d934cb88SDan Gohman WasmFunction Func; 12665e3d33a7SSam Clegg Func.Type = getFunctionType(WS); 1267d934cb88SDan Gohman Func.Sym = &WS; 12686c899ba6SSam Clegg WasmIndices[&WS] = Index; 1269d934cb88SDan Gohman Functions.push_back(Func); 12706c899ba6SSam Clegg 12716c899ba6SSam Clegg auto &Section = static_cast<MCSectionWasm &>(WS.getSection()); 12726c899ba6SSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 12736c899ba6SSam Clegg Comdats[C->getName()].emplace_back( 12746c899ba6SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index}); 12756c899ba6SSam Clegg } 1276d934cb88SDan Gohman } else { 1277d934cb88SDan Gohman // An import; the index was assigned above. 12786c899ba6SSam Clegg Index = WasmIndices.find(&WS)->second; 1279d934cb88SDan Gohman } 1280d934cb88SDan Gohman 12815e3d33a7SSam Clegg DEBUG(dbgs() << " -> function index: " << Index << "\n"); 12826c899ba6SSam Clegg } else if (WS.isData()) { 1283c38e947eSSam Clegg if (WS.isTemporary() && !WS.getSize()) 1284c38e947eSSam Clegg continue; 1285c38e947eSSam Clegg 12866c899ba6SSam Clegg if (!WS.isDefined()) { 12876c899ba6SSam Clegg DEBUG(dbgs() << " -> segment index: -1"); 1288fe6414b0SSam Clegg continue; 12896c899ba6SSam Clegg } 1290fe6414b0SSam Clegg 1291d934cb88SDan Gohman if (!WS.getSize()) 1292c38e947eSSam Clegg report_fatal_error("data symbols must have a size set with .size: " + 1293c38e947eSSam Clegg WS.getName()); 1294d934cb88SDan Gohman 1295d934cb88SDan Gohman int64_t Size = 0; 1296d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1297d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 1298d934cb88SDan Gohman 1299759631c7SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1300ea7caceeSSam Clegg assert(DataSection.isWasmData()); 13017c395943SSam Clegg 13026c899ba6SSam Clegg // For each data symbol, export it in the symtab as a reference to the 13036c899ba6SSam Clegg // corresponding Wasm data segment. 13046c899ba6SSam Clegg wasm::WasmDataReference Ref = wasm::WasmDataReference{ 13056c899ba6SSam Clegg DataSection.getSegmentIndex(), 13066c899ba6SSam Clegg static_cast<uint32_t>(Layout.getSymbolOffset(WS)), 13076c899ba6SSam Clegg static_cast<uint32_t>(Size)}; 13086c899ba6SSam Clegg DataLocations[&WS] = Ref; 13096c899ba6SSam Clegg DEBUG(dbgs() << " -> segment index: " << Ref.Segment); 13106c899ba6SSam Clegg } else { 13116c899ba6SSam Clegg // A "true" Wasm global (currently just __stack_pointer) 1312545932beSEric Christopher if (WS.isDefined()) 13136c899ba6SSam Clegg report_fatal_error("don't yet support defined globals"); 13146c899ba6SSam Clegg 1315545932beSEric Christopher // An import; the index was assigned above 1316545932beSEric Christopher DEBUG(dbgs() << " -> global index: " << WasmIndices.find(&WS)->second 1317545932beSEric Christopher << "\n"); 1318d934cb88SDan Gohman } 1319d934cb88SDan Gohman } 1320d934cb88SDan Gohman 1321586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for aliased symbols. We need to 1322586320c0SNicholas Wilson // process these in a separate pass because we need to have processed the 1323586320c0SNicholas Wilson // target of the alias before the alias itself and the symbols are not 1324586320c0SNicholas Wilson // necessarily ordered in this way. 1325b7787fd0SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1326b7787fd0SSam Clegg if (!S.isVariable()) 1327b7787fd0SSam Clegg continue; 132831a2c809SSam Clegg 1329cd65f698SSam Clegg assert(S.isDefined()); 1330b7787fd0SSam Clegg 13315e3d33a7SSam Clegg // Find the target symbol of this weak alias and export that index 1332aff1c4dfSSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 1333aff1c4dfSSam Clegg const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS); 13345e3d33a7SSam Clegg DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n"); 1335b7787fd0SSam Clegg 13366c899ba6SSam Clegg if (WS.isFunction()) { 13376c899ba6SSam Clegg assert(WasmIndices.count(ResolvedSym) > 0); 13386c899ba6SSam Clegg uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second; 13396c899ba6SSam Clegg WasmIndices[&WS] = WasmIndex; 13406c899ba6SSam Clegg DEBUG(dbgs() << " -> index:" << WasmIndex << "\n"); 13416c899ba6SSam Clegg } else if (WS.isData()) { 13426c899ba6SSam Clegg assert(DataLocations.count(ResolvedSym) > 0); 13436c899ba6SSam Clegg const wasm::WasmDataReference &Ref = 13446c899ba6SSam Clegg DataLocations.find(ResolvedSym)->second; 13456c899ba6SSam Clegg DataLocations[&WS] = Ref; 13466c899ba6SSam Clegg DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n"); 13476c899ba6SSam Clegg } else { 13486c899ba6SSam Clegg report_fatal_error("don't yet support global aliases"); 13496c899ba6SSam Clegg } 1350586320c0SNicholas Wilson } 135131a2c809SSam Clegg 1352586320c0SNicholas Wilson // Finally, populate the symbol table itself, in its "natural" order. 1353586320c0SNicholas Wilson for (const MCSymbol &S : Asm.symbols()) { 1354586320c0SNicholas Wilson const auto &WS = static_cast<const MCSymbolWasm &>(S); 1355586320c0SNicholas Wilson if (WS.isTemporary() && WS.getName().empty()) 1356586320c0SNicholas Wilson continue; 1357586320c0SNicholas Wilson if (WS.isComdat() && !WS.isDefined()) 1358586320c0SNicholas Wilson continue; 1359586320c0SNicholas Wilson if (WS.isTemporary() && WS.isData() && !WS.getSize()) 1360586320c0SNicholas Wilson continue; 1361586320c0SNicholas Wilson 1362586320c0SNicholas Wilson uint32_t Flags = 0; 1363586320c0SNicholas Wilson if (WS.isWeak()) 1364586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_WEAK; 1365586320c0SNicholas Wilson if (WS.isHidden()) 1366586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN; 1367586320c0SNicholas Wilson if (!WS.isExternal() && WS.isDefined()) 1368586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL; 1369586320c0SNicholas Wilson if (WS.isUndefined()) 1370586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_UNDEFINED; 1371586320c0SNicholas Wilson 1372586320c0SNicholas Wilson wasm::WasmSymbolInfo Info; 1373586320c0SNicholas Wilson Info.Name = WS.getName(); 1374586320c0SNicholas Wilson Info.Kind = WS.getType(); 1375586320c0SNicholas Wilson Info.Flags = Flags; 1376586320c0SNicholas Wilson if (!WS.isData()) 1377586320c0SNicholas Wilson Info.ElementIndex = WasmIndices.find(&WS)->second; 1378586320c0SNicholas Wilson else if (WS.isDefined()) 1379586320c0SNicholas Wilson Info.DataRef = DataLocations.find(&WS)->second; 1380586320c0SNicholas Wilson SymbolIndices[&WS] = SymbolInfos.size(); 1381586320c0SNicholas Wilson SymbolInfos.emplace_back(Info); 1382b7787fd0SSam Clegg } 1383b7787fd0SSam Clegg 13846006e091SSam Clegg { 13856006e091SSam Clegg auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 1386f9edbe95SSam Clegg // Functions referenced by a relocation need to put in the table. This is 1387f9edbe95SSam Clegg // purely to make the object file's provisional values readable, and is 1388f9edbe95SSam Clegg // ignored by the linker, which re-calculates the relocations itself. 1389f9edbe95SSam Clegg if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 && 1390f9edbe95SSam Clegg Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB) 1391f9edbe95SSam Clegg return; 1392f9edbe95SSam Clegg assert(Rel.Symbol->isFunction()); 1393f9edbe95SSam Clegg const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol); 13946c899ba6SSam Clegg uint32_t FunctionIndex = WasmIndices.find(&WS)->second; 1395f9edbe95SSam Clegg uint32_t TableIndex = TableElems.size() + kInitialTableOffset; 1396f9edbe95SSam Clegg if (TableIndices.try_emplace(&WS, TableIndex).second) { 1397329e76d5SSam Clegg DEBUG(dbgs() << " -> adding " << WS.getName() 1398f9edbe95SSam Clegg << " to table: " << TableIndex << "\n"); 13996c899ba6SSam Clegg TableElems.push_back(FunctionIndex); 14006006e091SSam Clegg registerFunctionType(WS); 14016006e091SSam Clegg } 14026006e091SSam Clegg }; 1403970d02c4SDan Gohman 14046006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : CodeRelocations) 14056006e091SSam Clegg HandleReloc(RelEntry); 14066006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : DataRelocations) 14076006e091SSam Clegg HandleReloc(RelEntry); 1408d934cb88SDan Gohman } 1409d934cb88SDan Gohman 1410bafe6902SSam Clegg // Translate .init_array section contents into start functions. 1411bafe6902SSam Clegg for (const MCSection &S : Asm) { 1412bafe6902SSam Clegg const auto &WS = static_cast<const MCSectionWasm &>(S); 1413bafe6902SSam Clegg if (WS.getSectionName().startswith(".fini_array")) 1414bafe6902SSam Clegg report_fatal_error(".fini_array sections are unsupported"); 1415bafe6902SSam Clegg if (!WS.getSectionName().startswith(".init_array")) 1416bafe6902SSam Clegg continue; 1417bafe6902SSam Clegg if (WS.getFragmentList().empty()) 1418bafe6902SSam Clegg continue; 1419bafe6902SSam Clegg if (WS.getFragmentList().size() != 2) 1420bafe6902SSam Clegg report_fatal_error("only one .init_array section fragment supported"); 1421bafe6902SSam Clegg const MCFragment &AlignFrag = *WS.begin(); 1422bafe6902SSam Clegg if (AlignFrag.getKind() != MCFragment::FT_Align) 1423bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned"); 1424bafe6902SSam Clegg if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1425bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned for pointers"); 1426bafe6902SSam Clegg const MCFragment &Frag = *std::next(WS.begin()); 1427bafe6902SSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1428bafe6902SSam Clegg report_fatal_error("only data supported in .init_array section"); 1429bafe6902SSam Clegg uint16_t Priority = UINT16_MAX; 1430bafe6902SSam Clegg if (WS.getSectionName().size() != 11) { 1431bafe6902SSam Clegg if (WS.getSectionName()[11] != '.') 1432bafe6902SSam Clegg report_fatal_error(".init_array section priority should start with '.'"); 1433bafe6902SSam Clegg if (WS.getSectionName().substr(12).getAsInteger(10, Priority)) 1434bafe6902SSam Clegg report_fatal_error("invalid .init_array section priority"); 1435bafe6902SSam Clegg } 1436bafe6902SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1437bafe6902SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1438bafe6902SSam Clegg for (const uint8_t *p = (const uint8_t *)Contents.data(), 1439bafe6902SSam Clegg *end = (const uint8_t *)Contents.data() + Contents.size(); 1440bafe6902SSam Clegg p != end; ++p) { 1441bafe6902SSam Clegg if (*p != 0) 1442bafe6902SSam Clegg report_fatal_error("non-symbolic data in .init_array section"); 1443bafe6902SSam Clegg } 1444bafe6902SSam Clegg for (const MCFixup &Fixup : DataFrag.getFixups()) { 1445bafe6902SSam Clegg assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1446bafe6902SSam Clegg const MCExpr *Expr = Fixup.getValue(); 1447bafe6902SSam Clegg auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr); 1448bafe6902SSam Clegg if (!Sym) 1449bafe6902SSam Clegg report_fatal_error("fixups in .init_array should be symbol references"); 1450bafe6902SSam Clegg if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION) 1451bafe6902SSam Clegg report_fatal_error("symbols in .init_array should be for functions"); 1452bafe6902SSam Clegg auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol())); 1453bafe6902SSam Clegg if (I == SymbolIndices.end()) 1454bafe6902SSam Clegg report_fatal_error("symbols in .init_array should be defined"); 1455bafe6902SSam Clegg uint32_t Index = I->second; 1456bafe6902SSam Clegg InitFuncs.push_back(std::make_pair(Priority, Index)); 1457bafe6902SSam Clegg } 1458bafe6902SSam Clegg } 1459bafe6902SSam Clegg 146018eafb6cSDan Gohman // Write out the Wasm header. 146118eafb6cSDan Gohman writeHeader(Asm); 146218eafb6cSDan Gohman 14639e15f359SSam Clegg writeTypeSection(FunctionTypes); 1464f950b24aSSam Clegg writeImportSection(Imports, DataSize, TableElems.size()); 14659e15f359SSam Clegg writeFunctionSection(Functions); 1466f950b24aSSam Clegg // Skip the "table" section; we import the table instead. 1467f950b24aSSam Clegg // Skip the "memory" section; we import the memory instead. 14687c395943SSam Clegg writeGlobalSection(); 14699e15f359SSam Clegg writeExportSection(Exports); 14709e15f359SSam Clegg writeElemSection(TableElems); 1471acd7d2b0SSam Clegg writeCodeSection(Asm, Layout, Functions); 14726c899ba6SSam Clegg writeDataSection(); 14736a31a0d6SSam Clegg writeCustomSections(Asm, Layout); 14746a31a0d6SSam Clegg updateCustomSectionRelocations(Functions, Layout); 1475c22bfb6bSNicholas Wilson writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats); 14766f08c84aSSam Clegg writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations); 14776f08c84aSSam Clegg writeRelocSection(DataSectionIndex, "DATA", DataRelocations); 14786a31a0d6SSam Clegg writeCustomRelocSections(); 1479970d02c4SDan Gohman 1480d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 148118eafb6cSDan Gohman } 148218eafb6cSDan Gohman 148360fbc7ccSLang Hames std::unique_ptr<MCObjectWriter> 14841301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 148518eafb6cSDan Gohman raw_pwrite_stream &OS) { 14860917c9e4SDan Gohman return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS); 148718eafb6cSDan Gohman } 1488