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 59*da419bdbSHeejin Ahn // The signature of a wasm function or event, in a struct capable of being used 60*da419bdbSHeejin Ahn // as a DenseMap key. 61*da419bdbSHeejin Ahn // TODO: Consider using wasm::WasmSignature directly instead. 62*da419bdbSHeejin Ahn struct WasmSignature { 639e15f359SSam Clegg // Support empty and tombstone instances, needed by DenseMap. 649e15f359SSam Clegg enum { Plain, Empty, Tombstone } State; 659e15f359SSam Clegg 669e15f359SSam Clegg // The return types of the function. 679e15f359SSam Clegg SmallVector<wasm::ValType, 1> Returns; 689e15f359SSam Clegg 699e15f359SSam Clegg // The parameter types of the function. 709e15f359SSam Clegg SmallVector<wasm::ValType, 4> Params; 719e15f359SSam Clegg 72*da419bdbSHeejin Ahn WasmSignature() : State(Plain) {} 739e15f359SSam Clegg 74*da419bdbSHeejin Ahn bool operator==(const WasmSignature &Other) const { 759e15f359SSam Clegg return State == Other.State && Returns == Other.Returns && 769e15f359SSam Clegg Params == Other.Params; 779e15f359SSam Clegg } 789e15f359SSam Clegg }; 799e15f359SSam Clegg 80*da419bdbSHeejin Ahn // Traits for using WasmSignature in a DenseMap. 81*da419bdbSHeejin Ahn struct WasmSignatureDenseMapInfo { 82*da419bdbSHeejin Ahn static WasmSignature getEmptyKey() { 83*da419bdbSHeejin Ahn WasmSignature Sig; 84*da419bdbSHeejin Ahn Sig.State = WasmSignature::Empty; 85*da419bdbSHeejin Ahn return Sig; 869e15f359SSam Clegg } 87*da419bdbSHeejin Ahn static WasmSignature getTombstoneKey() { 88*da419bdbSHeejin Ahn WasmSignature Sig; 89*da419bdbSHeejin Ahn Sig.State = WasmSignature::Tombstone; 90*da419bdbSHeejin Ahn return Sig; 919e15f359SSam Clegg } 92*da419bdbSHeejin Ahn static unsigned getHashValue(const WasmSignature &Sig) { 93*da419bdbSHeejin Ahn uintptr_t Value = Sig.State; 94*da419bdbSHeejin Ahn for (wasm::ValType Ret : Sig.Returns) 954808914aSHeejin Ahn Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret)); 96*da419bdbSHeejin Ahn for (wasm::ValType Param : Sig.Params) 974808914aSHeejin Ahn Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param)); 989e15f359SSam Clegg return Value; 999e15f359SSam Clegg } 100*da419bdbSHeejin Ahn static bool isEqual(const WasmSignature &LHS, const WasmSignature &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 { 120*da419bdbSHeejin Ahn uint32_t SigIndex; 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 { 166f208f631SHeejin Ahn Out << wasm::relocTypetoString(Type) << " Off=" << Offset 167f208f631SHeejin Ahn << ", 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 { 199f17b149dSPeter Collingbourne support::endian::Writer W; 200f17b149dSPeter Collingbourne 20118eafb6cSDan Gohman /// The target specific Wasm writer instance. 20218eafb6cSDan Gohman std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; 20318eafb6cSDan Gohman 204d934cb88SDan Gohman // Relocations for fixing up references in the code section. 205d934cb88SDan Gohman std::vector<WasmRelocationEntry> CodeRelocations; 2066f08c84aSSam Clegg uint32_t CodeSectionIndex; 207d934cb88SDan Gohman 208d934cb88SDan Gohman // Relocations for fixing up references in the data section. 209d934cb88SDan Gohman std::vector<WasmRelocationEntry> DataRelocations; 2106f08c84aSSam Clegg uint32_t DataSectionIndex; 211d934cb88SDan Gohman 212d934cb88SDan Gohman // Index values to use for fixing up call_indirect type indices. 213acd7d2b0SSam Clegg // Maps function symbols to the index of the type of the function 214acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices; 215d99f6078SSam Clegg // Maps function symbols to the table element index space. Used 216d99f6078SSam Clegg // for TABLE_INDEX relocation types (i.e. address taken functions). 217f9edbe95SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TableIndices; 218*da419bdbSHeejin Ahn // Maps function/global symbols to the function/global/event/section index 219*da419bdbSHeejin Ahn // space. 2206c899ba6SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices; 2216c899ba6SSam Clegg // Maps data symbols to the Wasm segment and offset/size with the segment. 2226c899ba6SSam Clegg DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations; 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 231c0d41195SSam Clegg // Map from section to defining function symbol. 2326ccb59b3SSam Clegg DenseMap<const MCSection *, const MCSymbol *> SectionFunctions; 2336ccb59b3SSam Clegg 234*da419bdbSHeejin Ahn DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices; 235*da419bdbSHeejin Ahn SmallVector<WasmSignature, 4> Signatures; 2367c395943SSam Clegg SmallVector<WasmGlobal, 4> Globals; 2376c899ba6SSam Clegg SmallVector<WasmDataSegment, 4> DataSegments; 2389f3fe42eSSam Clegg unsigned NumFunctionImports = 0; 2397c395943SSam Clegg unsigned NumGlobalImports = 0; 240*da419bdbSHeejin Ahn unsigned NumEventImports = 0; 2417e1c3345SChandler Carruth uint32_t SectionCount = 0; 242d934cb88SDan Gohman 24318eafb6cSDan Gohman // TargetObjectWriter wrappers. 24418eafb6cSDan Gohman bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 245ae03c1e7SSam Clegg unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const { 246ae03c1e7SSam Clegg return TargetObjectWriter->getRelocType(Target, Fixup); 24718eafb6cSDan Gohman } 24818eafb6cSDan Gohman 2492322a937SSam Clegg void startSection(SectionBookkeeping &Section, unsigned SectionId); 2502322a937SSam Clegg void startCustomSection(SectionBookkeeping &Section, StringRef Name); 251d934cb88SDan Gohman void endSection(SectionBookkeeping &Section); 252d934cb88SDan Gohman 25318eafb6cSDan Gohman public: 2541301a878SLang Hames WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 2551301a878SLang Hames raw_pwrite_stream &OS) 25659a6fc46SPeter Collingbourne : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {} 25718eafb6cSDan Gohman 25818eafb6cSDan Gohman ~WasmObjectWriter() override; 25918eafb6cSDan Gohman 2600917c9e4SDan Gohman private: 261acd7d2b0SSam Clegg void reset() override { 262acd7d2b0SSam Clegg CodeRelocations.clear(); 263acd7d2b0SSam Clegg DataRelocations.clear(); 264acd7d2b0SSam Clegg TypeIndices.clear(); 2656c899ba6SSam Clegg WasmIndices.clear(); 266f9edbe95SSam Clegg TableIndices.clear(); 2676c899ba6SSam Clegg DataLocations.clear(); 2686a31a0d6SSam Clegg CustomSectionsRelocations.clear(); 269*da419bdbSHeejin Ahn SignatureIndices.clear(); 270*da419bdbSHeejin Ahn Signatures.clear(); 2717c395943SSam Clegg Globals.clear(); 2726c899ba6SSam Clegg DataSegments.clear(); 2736ccb59b3SSam Clegg SectionFunctions.clear(); 2749f3fe42eSSam Clegg NumFunctionImports = 0; 2757c395943SSam Clegg NumGlobalImports = 0; 276105bdc25SSam Clegg MCObjectWriter::reset(); 277acd7d2b0SSam Clegg } 278acd7d2b0SSam Clegg 27918eafb6cSDan Gohman void writeHeader(const MCAssembler &Asm); 28018eafb6cSDan Gohman 28118eafb6cSDan Gohman void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 28218eafb6cSDan Gohman const MCFragment *Fragment, const MCFixup &Fixup, 283ceecfe5bSRafael Espindola MCValue Target, uint64_t &FixedValue) override; 28418eafb6cSDan Gohman 28518eafb6cSDan Gohman void executePostLayoutBinding(MCAssembler &Asm, 28618eafb6cSDan Gohman const MCAsmLayout &Layout) override; 28718eafb6cSDan Gohman 288438390faSPeter Collingbourne uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 2899e15f359SSam Clegg 290b7787fd0SSam Clegg void writeString(const StringRef Str) { 291f17b149dSPeter Collingbourne encodeULEB128(Str.size(), W.OS); 292f17b149dSPeter Collingbourne W.OS << Str; 293b7787fd0SSam Clegg } 294b7787fd0SSam Clegg 295f208f631SHeejin Ahn void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); } 2969e15f359SSam Clegg 297*da419bdbSHeejin Ahn void writeTypeSection(ArrayRef<WasmSignature> Signatures); 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(); 307*da419bdbSHeejin Ahn void writeEventSection(ArrayRef<wasm::WasmEventType> Events); 3086f08c84aSSam Clegg void writeRelocSection(uint32_t SectionIndex, StringRef Name, 309f77dc2a8SSam Clegg std::vector<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); 326*da419bdbSHeejin Ahn uint32_t getEventType(const MCSymbolWasm &Symbol); 3275e3d33a7SSam Clegg uint32_t registerFunctionType(const MCSymbolWasm &Symbol); 328*da419bdbSHeejin Ahn uint32_t registerEventType(const MCSymbolWasm &Symbol); 32918eafb6cSDan Gohman }; 3309e15f359SSam Clegg 33118eafb6cSDan Gohman } // end anonymous namespace 33218eafb6cSDan Gohman 33318eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {} 33418eafb6cSDan Gohman 335d934cb88SDan Gohman // Write out a section header and a patchable section size field. 336d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section, 3372322a937SSam Clegg unsigned SectionId) { 338d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n"); 339f17b149dSPeter Collingbourne W.OS << char(SectionId); 340d934cb88SDan Gohman 341f17b149dSPeter Collingbourne Section.SizeOffset = W.OS.tell(); 342d934cb88SDan Gohman 343d934cb88SDan Gohman // The section size. We don't know the size yet, so reserve enough space 344d934cb88SDan Gohman // for any 32-bit value; we'll patch it later. 345f17b149dSPeter Collingbourne encodeULEB128(UINT32_MAX, W.OS); 346d934cb88SDan Gohman 347d934cb88SDan Gohman // The position where the section starts, for measuring its size. 348f17b149dSPeter Collingbourne Section.ContentsOffset = W.OS.tell(); 349f17b149dSPeter Collingbourne Section.PayloadOffset = W.OS.tell(); 3506f08c84aSSam Clegg Section.Index = SectionCount++; 351d934cb88SDan Gohman } 3522322a937SSam Clegg 3532322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section, 3542322a937SSam Clegg StringRef Name) { 355d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n"); 3562322a937SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM); 3576a31a0d6SSam Clegg 3586a31a0d6SSam Clegg // The position where the section header ends, for measuring its size. 359f17b149dSPeter Collingbourne Section.PayloadOffset = W.OS.tell(); 3606a31a0d6SSam Clegg 3612322a937SSam Clegg // Custom sections in wasm also have a string identifier. 3622322a937SSam Clegg writeString(Name); 3636a31a0d6SSam Clegg 3646a31a0d6SSam Clegg // The position where the custom section starts. 365f17b149dSPeter Collingbourne Section.ContentsOffset = W.OS.tell(); 366d934cb88SDan Gohman } 367d934cb88SDan Gohman 368d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the 369d934cb88SDan Gohman // section size field at the start of the section. 370d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) { 371f17b149dSPeter Collingbourne uint64_t Size = W.OS.tell() - Section.PayloadOffset; 372d934cb88SDan Gohman if (uint32_t(Size) != Size) 373d934cb88SDan Gohman report_fatal_error("section size does not fit in a uint32_t"); 374d934cb88SDan Gohman 375d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n"); 376d934cb88SDan Gohman 377d934cb88SDan Gohman // Write the final section size to the payload_len field, which follows 378d934cb88SDan Gohman // the section id byte. 379d934cb88SDan Gohman uint8_t Buffer[16]; 38066a99e41SSam Clegg unsigned SizeLen = encodeULEB128(Size, Buffer, 5); 381d934cb88SDan Gohman assert(SizeLen == 5); 382f17b149dSPeter Collingbourne static_cast<raw_pwrite_stream &>(W.OS).pwrite((char *)Buffer, SizeLen, 383f17b149dSPeter Collingbourne Section.SizeOffset); 384d934cb88SDan Gohman } 385d934cb88SDan Gohman 38618eafb6cSDan Gohman // Emit the Wasm header. 38718eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { 388f17b149dSPeter Collingbourne W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic)); 389f17b149dSPeter Collingbourne W.write<uint32_t>(wasm::WasmVersion); 39018eafb6cSDan Gohman } 39118eafb6cSDan Gohman 39218eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 39318eafb6cSDan Gohman const MCAsmLayout &Layout) { 3946ccb59b3SSam Clegg // Build a map of sections to the function that defines them, for use 3956ccb59b3SSam Clegg // in recordRelocation. 3966ccb59b3SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 3976ccb59b3SSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 3986ccb59b3SSam Clegg if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) { 3996ccb59b3SSam Clegg const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection()); 4006ccb59b3SSam Clegg auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S)); 4016ccb59b3SSam Clegg if (!Pair.second) 4026ccb59b3SSam Clegg report_fatal_error("section already has a defining function: " + 4036ccb59b3SSam Clegg Sec.getSectionName()); 4046ccb59b3SSam Clegg } 4056ccb59b3SSam Clegg } 40618eafb6cSDan Gohman } 40718eafb6cSDan Gohman 40818eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 40918eafb6cSDan Gohman const MCAsmLayout &Layout, 41018eafb6cSDan Gohman const MCFragment *Fragment, 41118eafb6cSDan Gohman const MCFixup &Fixup, MCValue Target, 412ceecfe5bSRafael Espindola uint64_t &FixedValue) { 413ceecfe5bSRafael Espindola MCAsmBackend &Backend = Asm.getBackend(); 414ceecfe5bSRafael Espindola bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags & 415ceecfe5bSRafael Espindola MCFixupKindInfo::FKF_IsPCRel; 416fe6414b0SSam Clegg const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 417d934cb88SDan Gohman uint64_t C = Target.getConstant(); 418d934cb88SDan Gohman uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 419d934cb88SDan Gohman MCContext &Ctx = Asm.getContext(); 420d934cb88SDan Gohman 421bafe6902SSam Clegg // The .init_array isn't translated as data, so don't do relocations in it. 422bafe6902SSam Clegg if (FixupSection.getSectionName().startswith(".init_array")) 423bafe6902SSam Clegg return; 424bafe6902SSam Clegg 425d934cb88SDan Gohman if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 426d934cb88SDan Gohman assert(RefB->getKind() == MCSymbolRefExpr::VK_None && 427d934cb88SDan Gohman "Should not have constructed this"); 428d934cb88SDan Gohman 429d934cb88SDan Gohman // Let A, B and C being the components of Target and R be the location of 430d934cb88SDan Gohman // the fixup. If the fixup is not pcrel, we want to compute (A - B + C). 431d934cb88SDan Gohman // If it is pcrel, we want to compute (A - B + C - R). 432d934cb88SDan Gohman 433d934cb88SDan Gohman // In general, Wasm has no relocations for -B. It can only represent (A + C) 434d934cb88SDan Gohman // or (A + C - R). If B = R + K and the relocation is not pcrel, we can 435d934cb88SDan Gohman // replace B to implement it: (A - R - K + C) 436d934cb88SDan Gohman if (IsPCRel) { 437d934cb88SDan Gohman Ctx.reportError( 438d934cb88SDan Gohman Fixup.getLoc(), 439d934cb88SDan Gohman "No relocation available to represent this relative expression"); 440d934cb88SDan Gohman return; 441d934cb88SDan Gohman } 442d934cb88SDan Gohman 443d934cb88SDan Gohman const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 444d934cb88SDan Gohman 445d934cb88SDan Gohman if (SymB.isUndefined()) { 446d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 447d934cb88SDan Gohman Twine("symbol '") + SymB.getName() + 448d934cb88SDan Gohman "' can not be undefined in a subtraction expression"); 449d934cb88SDan Gohman return; 450d934cb88SDan Gohman } 451d934cb88SDan Gohman 452d934cb88SDan Gohman assert(!SymB.isAbsolute() && "Should have been folded"); 453d934cb88SDan Gohman const MCSection &SecB = SymB.getSection(); 454d934cb88SDan Gohman if (&SecB != &FixupSection) { 455d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 456d934cb88SDan Gohman "Cannot represent a difference across sections"); 457d934cb88SDan Gohman return; 458d934cb88SDan Gohman } 459d934cb88SDan Gohman 460d934cb88SDan Gohman uint64_t SymBOffset = Layout.getSymbolOffset(SymB); 461d934cb88SDan Gohman uint64_t K = SymBOffset - FixupOffset; 462d934cb88SDan Gohman IsPCRel = true; 463d934cb88SDan Gohman C -= K; 464d934cb88SDan Gohman } 465d934cb88SDan Gohman 466d934cb88SDan Gohman // We either rejected the fixup or folded B into C at this point. 467d934cb88SDan Gohman const MCSymbolRefExpr *RefA = Target.getSymA(); 468d934cb88SDan Gohman const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr; 469d934cb88SDan Gohman 470d934cb88SDan Gohman if (SymA && SymA->isVariable()) { 471d934cb88SDan Gohman const MCExpr *Expr = SymA->getVariableValue(); 4726ad8f190SSam Clegg const auto *Inner = cast<MCSymbolRefExpr>(Expr); 4736ad8f190SSam Clegg if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) 4746ad8f190SSam Clegg llvm_unreachable("weakref used in reloc not yet implemented"); 475d934cb88SDan Gohman } 476d934cb88SDan Gohman 477d934cb88SDan Gohman // Put any constant offset in an addend. Offsets can be negative, and 478d934cb88SDan Gohman // LLVM expects wrapping, in contrast to wasm's immediates which can't 479d934cb88SDan Gohman // be negative and don't wrap. 480d934cb88SDan Gohman FixedValue = 0; 481d934cb88SDan Gohman 4824d57fbd0SSam Clegg unsigned Type = getRelocType(Target, Fixup); 483ae03c1e7SSam Clegg assert(!IsPCRel); 4849d24fb7fSSam Clegg assert(SymA); 4859d24fb7fSSam Clegg 4864d57fbd0SSam Clegg // Absolute offset within a section or a function. 4874d57fbd0SSam Clegg // Currently only supported for for metadata sections. 4884d57fbd0SSam Clegg // See: test/MC/WebAssembly/blockaddress.ll 4894d57fbd0SSam Clegg if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 || 4904d57fbd0SSam Clegg Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) { 4914d57fbd0SSam Clegg if (!FixupSection.getKind().isMetadata()) 4924d57fbd0SSam Clegg report_fatal_error("relocations for function or section offsets are " 4934d57fbd0SSam Clegg "only supported in metadata sections"); 4944d57fbd0SSam Clegg 4954d57fbd0SSam Clegg const MCSymbol *SectionSymbol = nullptr; 4964d57fbd0SSam Clegg const MCSection &SecA = SymA->getSection(); 4974d57fbd0SSam Clegg if (SecA.getKind().isText()) 4986ccb59b3SSam Clegg SectionSymbol = SectionFunctions.find(&SecA)->second; 4994d57fbd0SSam Clegg else 5004d57fbd0SSam Clegg SectionSymbol = SecA.getBeginSymbol(); 5014d57fbd0SSam Clegg if (!SectionSymbol) 5024d57fbd0SSam Clegg report_fatal_error("section symbol is required for relocation"); 5034d57fbd0SSam Clegg 5044d57fbd0SSam Clegg C += Layout.getSymbolOffset(*SymA); 5054d57fbd0SSam Clegg SymA = cast<MCSymbolWasm>(SectionSymbol); 5064d57fbd0SSam Clegg } 5074d57fbd0SSam Clegg 5084d57fbd0SSam Clegg // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be 5094d57fbd0SSam Clegg // against a named symbol. 5104d57fbd0SSam Clegg if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) { 5114d57fbd0SSam Clegg if (SymA->getName().empty()) 5124d57fbd0SSam Clegg report_fatal_error("relocations against un-named temporaries are not yet " 5134d57fbd0SSam Clegg "supported by wasm"); 5144d57fbd0SSam Clegg 5154d57fbd0SSam Clegg SymA->setUsedInReloc(); 5164d57fbd0SSam Clegg } 517ae03c1e7SSam Clegg 518d934cb88SDan Gohman WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 519d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 520d934cb88SDan Gohman 5216a31a0d6SSam Clegg if (FixupSection.isWasmData()) { 522d934cb88SDan Gohman DataRelocations.push_back(Rec); 5236a31a0d6SSam Clegg } else if (FixupSection.getKind().isText()) { 52412fd3da9SSam Clegg CodeRelocations.push_back(Rec); 5256a31a0d6SSam Clegg } else if (FixupSection.getKind().isMetadata()) { 5266a31a0d6SSam Clegg CustomSectionsRelocations[&FixupSection].push_back(Rec); 5276a31a0d6SSam Clegg } else { 52812fd3da9SSam Clegg llvm_unreachable("unexpected section type"); 529d934cb88SDan Gohman } 5306a31a0d6SSam Clegg } 531d934cb88SDan Gohman 532d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded 533d934cb88SDan Gohman // to allow patching. 534f208f631SHeejin Ahn static void WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, 535f208f631SHeejin Ahn uint64_t Offset) { 536d934cb88SDan Gohman uint8_t Buffer[5]; 53766a99e41SSam Clegg unsigned SizeLen = encodeULEB128(X, Buffer, 5); 538d934cb88SDan Gohman assert(SizeLen == 5); 539d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 540d934cb88SDan Gohman } 541d934cb88SDan Gohman 542d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded 543d934cb88SDan Gohman // to allow patching. 544f208f631SHeejin Ahn static void WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, 545f208f631SHeejin Ahn uint64_t Offset) { 546d934cb88SDan Gohman uint8_t Buffer[5]; 54766a99e41SSam Clegg unsigned SizeLen = encodeSLEB128(X, Buffer, 5); 548d934cb88SDan Gohman assert(SizeLen == 5); 549d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 550d934cb88SDan Gohman } 551d934cb88SDan Gohman 552d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream. 553d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 554d934cb88SDan Gohman uint8_t Buffer[4]; 555d934cb88SDan Gohman support::endian::write32le(Buffer, X); 556d934cb88SDan Gohman Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 557d934cb88SDan Gohman } 558d934cb88SDan Gohman 559aff1c4dfSSam Clegg static const MCSymbolWasm *ResolveSymbol(const MCSymbolWasm &Symbol) { 560aff1c4dfSSam Clegg if (Symbol.isVariable()) { 561aff1c4dfSSam Clegg const MCExpr *Expr = Symbol.getVariableValue(); 562aff1c4dfSSam Clegg auto *Inner = cast<MCSymbolRefExpr>(Expr); 563aff1c4dfSSam Clegg return cast<MCSymbolWasm>(&Inner->getSymbol()); 564aff1c4dfSSam Clegg } 565aff1c4dfSSam Clegg return &Symbol; 566aff1c4dfSSam Clegg } 567aff1c4dfSSam Clegg 568d934cb88SDan Gohman // Compute a value to write into the code at the location covered 56960ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves 57060ec3034SSam Clegg // to make the object format more readable and more likely to be directly 57160ec3034SSam Clegg // useable. 5727c395943SSam Clegg uint32_t 5737c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) { 57460ec3034SSam Clegg switch (RelEntry.Type) { 57560ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 576f9edbe95SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: { 577f9edbe95SSam Clegg // Provisional value is table address of the resolved symbol itself 578f9edbe95SSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 579f9edbe95SSam Clegg assert(Sym->isFunction()); 580f9edbe95SSam Clegg return TableIndices[Sym]; 581f9edbe95SSam Clegg } 58260ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 5836c899ba6SSam Clegg // Provisional value is same as the index 58460ec3034SSam Clegg return getRelocationIndexValue(RelEntry); 5856c899ba6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 5866c899ba6SSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 587*da419bdbSHeejin Ahn case wasm::R_WEBASSEMBLY_EVENT_INDEX_LEB: 588*da419bdbSHeejin Ahn // Provisional value is function/global/event Wasm index 5896c899ba6SSam Clegg if (!WasmIndices.count(RelEntry.Symbol)) 5906c899ba6SSam Clegg report_fatal_error("symbol not found in wasm index space: " + 5916c899ba6SSam Clegg RelEntry.Symbol->getName()); 5926c899ba6SSam Clegg return WasmIndices[RelEntry.Symbol]; 5934d57fbd0SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: 5944d57fbd0SSam Clegg case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: { 5956a31a0d6SSam Clegg const auto &Section = 5966a31a0d6SSam Clegg static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection()); 5976a31a0d6SSam Clegg return Section.getSectionOffset() + RelEntry.Addend; 5986a31a0d6SSam Clegg } 59960ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 60060ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 60160ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: { 602f9edbe95SSam Clegg // Provisional value is address of the global 60360ec3034SSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 604270ed1b3SSam Clegg // For undefined symbols, use zero 605cd65f698SSam Clegg if (!Sym->isDefined()) 606270ed1b3SSam Clegg return 0; 6076c899ba6SSam Clegg const wasm::WasmDataReference &Ref = DataLocations[Sym]; 6086c899ba6SSam Clegg const WasmDataSegment &Segment = DataSegments[Ref.Segment]; 609d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 6106c899ba6SSam Clegg return Segment.Offset + Ref.Offset + RelEntry.Addend; 61160ec3034SSam Clegg } 61260ec3034SSam Clegg default: 61360ec3034SSam Clegg llvm_unreachable("invalid relocation type"); 61460ec3034SSam Clegg } 615d934cb88SDan Gohman } 616d934cb88SDan Gohman 617759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes, 61863ebb813SSam Clegg MCSectionWasm &DataSection) { 619d34e60caSNicola Zaghen LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n"); 620759631c7SSam Clegg 62163ebb813SSam Clegg DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 62263ebb813SSam Clegg 623759631c7SSam Clegg for (const MCFragment &Frag : DataSection) { 624759631c7SSam Clegg if (Frag.hasInstructions()) 625759631c7SSam Clegg report_fatal_error("only data supported in data sections"); 626759631c7SSam Clegg 627759631c7SSam Clegg if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 628759631c7SSam Clegg if (Align->getValueSize() != 1) 629759631c7SSam Clegg report_fatal_error("only byte values supported for alignment"); 630759631c7SSam Clegg // If nops are requested, use zeros, as this is the data section. 631759631c7SSam Clegg uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 632f208f631SHeejin Ahn uint64_t Size = 633f208f631SHeejin Ahn std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()), 634f208f631SHeejin Ahn DataBytes.size() + Align->getMaxBytesToEmit()); 635759631c7SSam Clegg DataBytes.resize(Size, Value); 636759631c7SSam Clegg } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 637588fad4dSNirav Dave int64_t NumValues; 638588fad4dSNirav Dave if (!Fill->getNumValues().evaluateAsAbsolute(NumValues)) 639d707c370SRafael Espindola llvm_unreachable("The fill should be an assembler constant"); 640588fad4dSNirav Dave DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues, 641588fad4dSNirav Dave Fill->getValue()); 64224faf859SHeejin Ahn } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) { 64324faf859SHeejin Ahn const SmallVectorImpl<char> &Contents = LEB->getContents(); 64424faf859SHeejin Ahn DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 645759631c7SSam Clegg } else { 646759631c7SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 647759631c7SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 648759631c7SSam Clegg DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 649759631c7SSam Clegg } 650759631c7SSam Clegg } 651759631c7SSam Clegg 652d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 653759631c7SSam Clegg } 654759631c7SSam Clegg 65560ec3034SSam Clegg uint32_t 65660ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) { 65760ec3034SSam Clegg if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) { 658b7787fd0SSam Clegg if (!TypeIndices.count(RelEntry.Symbol)) 659b7787fd0SSam Clegg report_fatal_error("symbol not found in type index space: " + 660b7787fd0SSam Clegg RelEntry.Symbol->getName()); 661acd7d2b0SSam Clegg return TypeIndices[RelEntry.Symbol]; 662acd7d2b0SSam Clegg } 66360ec3034SSam Clegg 66425d8e68bSSam Clegg return RelEntry.Symbol->getIndex(); 665acd7d2b0SSam Clegg } 666acd7d2b0SSam Clegg 667d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 668d934cb88SDan Gohman // directly. 669acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations( 670acd7d2b0SSam Clegg ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) { 671f17b149dSPeter Collingbourne auto &Stream = static_cast<raw_pwrite_stream &>(W.OS); 672d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 673d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 674d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 675d934cb88SDan Gohman RelEntry.Offset; 676d934cb88SDan Gohman 677d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 67860ec3034SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 67960ec3034SSam Clegg 680acd7d2b0SSam Clegg switch (RelEntry.Type) { 681acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 6829d24fb7fSSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 68360ec3034SSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 68460ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 685*da419bdbSHeejin Ahn case wasm::R_WEBASSEMBLY_EVENT_INDEX_LEB: 686d934cb88SDan Gohman WritePatchableLEB(Stream, Value, Offset); 687d934cb88SDan Gohman break; 68860ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 68960ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 6906a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: 6916a31a0d6SSam Clegg case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: 692d934cb88SDan Gohman WriteI32(Stream, Value, Offset); 693d934cb88SDan Gohman break; 69460ec3034SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 69560ec3034SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 69660ec3034SSam Clegg WritePatchableSLEB(Stream, Value, Offset); 69760ec3034SSam Clegg break; 698d934cb88SDan Gohman default: 6999d24fb7fSSam Clegg llvm_unreachable("invalid relocation type"); 700d934cb88SDan Gohman } 701d934cb88SDan Gohman } 70218eafb6cSDan Gohman } 70318eafb6cSDan Gohman 704*da419bdbSHeejin Ahn void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) { 705*da419bdbSHeejin Ahn if (Signatures.empty()) 7069e15f359SSam Clegg return; 7079e15f359SSam Clegg 7089e15f359SSam Clegg SectionBookkeeping Section; 7099e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TYPE); 7109e15f359SSam Clegg 711*da419bdbSHeejin Ahn encodeULEB128(Signatures.size(), W.OS); 7129e15f359SSam Clegg 713*da419bdbSHeejin Ahn for (const WasmSignature &Sig : Signatures) { 714f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_TYPE_FUNC); 715*da419bdbSHeejin Ahn encodeULEB128(Sig.Params.size(), W.OS); 716*da419bdbSHeejin Ahn for (wasm::ValType Ty : Sig.Params) 7179e15f359SSam Clegg writeValueType(Ty); 718*da419bdbSHeejin Ahn encodeULEB128(Sig.Returns.size(), W.OS); 719*da419bdbSHeejin Ahn for (wasm::ValType Ty : Sig.Returns) 7209e15f359SSam Clegg writeValueType(Ty); 7219e15f359SSam Clegg } 7229e15f359SSam Clegg 7239e15f359SSam Clegg endSection(Section); 7249e15f359SSam Clegg } 7259e15f359SSam Clegg 7268defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports, 727f950b24aSSam Clegg uint32_t DataSize, 728f950b24aSSam Clegg uint32_t NumElements) { 7299e15f359SSam Clegg if (Imports.empty()) 7309e15f359SSam Clegg return; 7319e15f359SSam Clegg 732f950b24aSSam Clegg uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 733f950b24aSSam Clegg 7349e15f359SSam Clegg SectionBookkeeping Section; 7359e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_IMPORT); 7369e15f359SSam Clegg 737f17b149dSPeter Collingbourne encodeULEB128(Imports.size(), W.OS); 7388defa952SSam Clegg for (const wasm::WasmImport &Import : Imports) { 7398defa952SSam Clegg writeString(Import.Module); 7408defa952SSam Clegg writeString(Import.Field); 741f17b149dSPeter Collingbourne W.OS << char(Import.Kind); 7429e15f359SSam Clegg 7439e15f359SSam Clegg switch (Import.Kind) { 7449e15f359SSam Clegg case wasm::WASM_EXTERNAL_FUNCTION: 745f17b149dSPeter Collingbourne encodeULEB128(Import.SigIndex, W.OS); 7469e15f359SSam Clegg break; 7479e15f359SSam Clegg case wasm::WASM_EXTERNAL_GLOBAL: 748f17b149dSPeter Collingbourne W.OS << char(Import.Global.Type); 749f17b149dSPeter Collingbourne W.OS << char(Import.Global.Mutable ? 1 : 0); 7509e15f359SSam Clegg break; 751f950b24aSSam Clegg case wasm::WASM_EXTERNAL_MEMORY: 752f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // flags 753f17b149dSPeter Collingbourne encodeULEB128(NumPages, W.OS); // initial 754f950b24aSSam Clegg break; 755f950b24aSSam Clegg case wasm::WASM_EXTERNAL_TABLE: 756f17b149dSPeter Collingbourne W.OS << char(Import.Table.ElemType); 757f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // flags 758f17b149dSPeter Collingbourne encodeULEB128(NumElements, W.OS); // initial 759f950b24aSSam Clegg break; 760*da419bdbSHeejin Ahn case wasm::WASM_EXTERNAL_EVENT: 761*da419bdbSHeejin Ahn encodeULEB128(Import.Event.Attribute, W.OS); 762*da419bdbSHeejin Ahn encodeULEB128(Import.Event.SigIndex, W.OS); 763*da419bdbSHeejin Ahn break; 7649e15f359SSam Clegg default: 7659e15f359SSam Clegg llvm_unreachable("unsupported import kind"); 7669e15f359SSam Clegg } 7679e15f359SSam Clegg } 7689e15f359SSam Clegg 7699e15f359SSam Clegg endSection(Section); 7709e15f359SSam Clegg } 7719e15f359SSam Clegg 772457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 7739e15f359SSam Clegg if (Functions.empty()) 7749e15f359SSam Clegg return; 7759e15f359SSam Clegg 7769e15f359SSam Clegg SectionBookkeeping Section; 7779e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_FUNCTION); 7789e15f359SSam Clegg 779f17b149dSPeter Collingbourne encodeULEB128(Functions.size(), W.OS); 7809e15f359SSam Clegg for (const WasmFunction &Func : Functions) 781*da419bdbSHeejin Ahn encodeULEB128(Func.SigIndex, W.OS); 7829e15f359SSam Clegg 7839e15f359SSam Clegg endSection(Section); 7849e15f359SSam Clegg } 7859e15f359SSam Clegg 7867c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() { 7879e15f359SSam Clegg if (Globals.empty()) 7889e15f359SSam Clegg return; 7899e15f359SSam Clegg 7909e15f359SSam Clegg SectionBookkeeping Section; 7919e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_GLOBAL); 7929e15f359SSam Clegg 793f17b149dSPeter Collingbourne encodeULEB128(Globals.size(), W.OS); 7949e15f359SSam Clegg for (const WasmGlobal &Global : Globals) { 7956e7f1826SSam Clegg writeValueType(static_cast<wasm::ValType>(Global.Type.Type)); 796f17b149dSPeter Collingbourne W.OS << char(Global.Type.Mutable); 7979e15f359SSam Clegg 798f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_I32_CONST); 799f17b149dSPeter Collingbourne encodeSLEB128(Global.InitialValue, W.OS); 800f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_END); 8019e15f359SSam Clegg } 8029e15f359SSam Clegg 8039e15f359SSam Clegg endSection(Section); 8049e15f359SSam Clegg } 8059e15f359SSam Clegg 806*da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) { 807*da419bdbSHeejin Ahn if (Events.empty()) 808*da419bdbSHeejin Ahn return; 809*da419bdbSHeejin Ahn 810*da419bdbSHeejin Ahn SectionBookkeeping Section; 811*da419bdbSHeejin Ahn startSection(Section, wasm::WASM_SEC_EVENT); 812*da419bdbSHeejin Ahn 813*da419bdbSHeejin Ahn encodeULEB128(Events.size(), W.OS); 814*da419bdbSHeejin Ahn for (const wasm::WasmEventType &Event : Events) { 815*da419bdbSHeejin Ahn encodeULEB128(Event.Attribute, W.OS); 816*da419bdbSHeejin Ahn encodeULEB128(Event.SigIndex, W.OS); 817*da419bdbSHeejin Ahn } 818*da419bdbSHeejin Ahn 819*da419bdbSHeejin Ahn endSection(Section); 820*da419bdbSHeejin Ahn } 821*da419bdbSHeejin Ahn 8228defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) { 8239e15f359SSam Clegg if (Exports.empty()) 8249e15f359SSam Clegg return; 8259e15f359SSam Clegg 8269e15f359SSam Clegg SectionBookkeeping Section; 8279e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_EXPORT); 8289e15f359SSam Clegg 829f17b149dSPeter Collingbourne encodeULEB128(Exports.size(), W.OS); 8308defa952SSam Clegg for (const wasm::WasmExport &Export : Exports) { 8318defa952SSam Clegg writeString(Export.Name); 832f17b149dSPeter Collingbourne W.OS << char(Export.Kind); 833f17b149dSPeter Collingbourne encodeULEB128(Export.Index, W.OS); 8349e15f359SSam Clegg } 8359e15f359SSam Clegg 8369e15f359SSam Clegg endSection(Section); 8379e15f359SSam Clegg } 8389e15f359SSam Clegg 839457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 8409e15f359SSam Clegg if (TableElems.empty()) 8419e15f359SSam Clegg return; 8429e15f359SSam Clegg 8439e15f359SSam Clegg SectionBookkeeping Section; 8449e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_ELEM); 8459e15f359SSam Clegg 846f17b149dSPeter Collingbourne encodeULEB128(1, W.OS); // number of "segments" 847f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // the table index 8489e15f359SSam Clegg 8499e15f359SSam Clegg // init expr for starting offset 850f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_I32_CONST); 851f17b149dSPeter Collingbourne encodeSLEB128(kInitialTableOffset, W.OS); 852f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_END); 8539e15f359SSam Clegg 854f17b149dSPeter Collingbourne encodeULEB128(TableElems.size(), W.OS); 8559e15f359SSam Clegg for (uint32_t Elem : TableElems) 856f17b149dSPeter Collingbourne encodeULEB128(Elem, W.OS); 8579e15f359SSam Clegg 8589e15f359SSam Clegg endSection(Section); 8599e15f359SSam Clegg } 8609e15f359SSam Clegg 861457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 862457fb0b4SSam Clegg const MCAsmLayout &Layout, 863457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions) { 8649e15f359SSam Clegg if (Functions.empty()) 8659e15f359SSam Clegg return; 8669e15f359SSam Clegg 8679e15f359SSam Clegg SectionBookkeeping Section; 8689e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CODE); 8696f08c84aSSam Clegg CodeSectionIndex = Section.Index; 8709e15f359SSam Clegg 871f17b149dSPeter Collingbourne encodeULEB128(Functions.size(), W.OS); 8729e15f359SSam Clegg 8739e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 874fe6414b0SSam Clegg auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 8759e15f359SSam Clegg 8769e15f359SSam Clegg int64_t Size = 0; 8779e15f359SSam Clegg if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 8789e15f359SSam Clegg report_fatal_error(".size expression must be evaluatable"); 8799e15f359SSam Clegg 880f17b149dSPeter Collingbourne encodeULEB128(Size, W.OS); 881f17b149dSPeter Collingbourne FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset); 882f17b149dSPeter Collingbourne Asm.writeSectionData(W.OS, &FuncSection, Layout); 8839e15f359SSam Clegg } 8849e15f359SSam Clegg 8859e15f359SSam Clegg // Apply fixups. 886acd7d2b0SSam Clegg applyRelocations(CodeRelocations, Section.ContentsOffset); 8879e15f359SSam Clegg 8889e15f359SSam Clegg endSection(Section); 8899e15f359SSam Clegg } 8909e15f359SSam Clegg 8916c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() { 8926c899ba6SSam Clegg if (DataSegments.empty()) 8937c395943SSam Clegg return; 8949e15f359SSam Clegg 8959e15f359SSam Clegg SectionBookkeeping Section; 8969e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_DATA); 8976f08c84aSSam Clegg DataSectionIndex = Section.Index; 8989e15f359SSam Clegg 899f17b149dSPeter Collingbourne encodeULEB128(DataSegments.size(), W.OS); // count 9007c395943SSam Clegg 9016c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 902f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // memory index 903f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_I32_CONST); 904f17b149dSPeter Collingbourne encodeSLEB128(Segment.Offset, W.OS); // offset 905f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_END); 906f17b149dSPeter Collingbourne encodeULEB128(Segment.Data.size(), W.OS); // size 907f17b149dSPeter Collingbourne Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset); 908f17b149dSPeter Collingbourne W.OS << Segment.Data; // data 9097c395943SSam Clegg } 9109e15f359SSam Clegg 9119e15f359SSam Clegg // Apply fixups. 9127c395943SSam Clegg applyRelocations(DataRelocations, Section.ContentsOffset); 9139e15f359SSam Clegg 9149e15f359SSam Clegg endSection(Section); 9159e15f359SSam Clegg } 9169e15f359SSam Clegg 9176f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection( 9186f08c84aSSam Clegg uint32_t SectionIndex, StringRef Name, 919f77dc2a8SSam Clegg std::vector<WasmRelocationEntry> &Relocs) { 9209e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 9219e15f359SSam Clegg // for descriptions of the reloc sections. 9229e15f359SSam Clegg 923f77dc2a8SSam Clegg if (Relocs.empty()) 9249e15f359SSam Clegg return; 9259e15f359SSam Clegg 926f77dc2a8SSam Clegg // First, ensure the relocations are sorted in offset order. In general they 927f77dc2a8SSam Clegg // should already be sorted since `recordRelocation` is called in offset 928f77dc2a8SSam Clegg // order, but for the code section we combine many MC sections into single 929f77dc2a8SSam Clegg // wasm section, and this order is determined by the order of Asm.Symbols() 930f77dc2a8SSam Clegg // not the sections order. 931f77dc2a8SSam Clegg std::stable_sort( 932f77dc2a8SSam Clegg Relocs.begin(), Relocs.end(), 933f77dc2a8SSam Clegg [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) { 934f77dc2a8SSam Clegg return (A.Offset + A.FixupSection->getSectionOffset()) < 935f77dc2a8SSam Clegg (B.Offset + B.FixupSection->getSectionOffset()); 936f77dc2a8SSam Clegg }); 937f77dc2a8SSam Clegg 9389e15f359SSam Clegg SectionBookkeeping Section; 9396f08c84aSSam Clegg startCustomSection(Section, std::string("reloc.") + Name.str()); 9409e15f359SSam Clegg 941f17b149dSPeter Collingbourne encodeULEB128(SectionIndex, W.OS); 942f77dc2a8SSam Clegg encodeULEB128(Relocs.size(), W.OS); 943f77dc2a8SSam Clegg for (const WasmRelocationEntry &RelEntry : Relocs) { 944f208f631SHeejin Ahn uint64_t Offset = 945f208f631SHeejin Ahn RelEntry.Offset + RelEntry.FixupSection->getSectionOffset(); 9466f08c84aSSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 9479e15f359SSam Clegg 948f17b149dSPeter Collingbourne W.OS << char(RelEntry.Type); 949f17b149dSPeter Collingbourne encodeULEB128(Offset, W.OS); 950f17b149dSPeter Collingbourne encodeULEB128(Index, W.OS); 9516f08c84aSSam Clegg if (RelEntry.hasAddend()) 952f17b149dSPeter Collingbourne encodeSLEB128(RelEntry.Addend, W.OS); 9539e15f359SSam Clegg } 9549e15f359SSam Clegg 9559e15f359SSam Clegg endSection(Section); 9569e15f359SSam Clegg } 9579e15f359SSam Clegg 9586a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() { 9596a31a0d6SSam Clegg for (const auto &Sec : CustomSections) { 9606a31a0d6SSam Clegg auto &Relocations = CustomSectionsRelocations[Sec.Section]; 9616a31a0d6SSam Clegg writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations); 9626a31a0d6SSam Clegg } 9636a31a0d6SSam Clegg } 9646a31a0d6SSam Clegg 9659e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection( 96686b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 967ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 968ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) { 9699e15f359SSam Clegg SectionBookkeeping Section; 9702322a937SSam Clegg startCustomSection(Section, "linking"); 971f17b149dSPeter Collingbourne encodeULEB128(wasm::WasmMetadataVersion, W.OS); 9729e15f359SSam Clegg 9736bb5a41fSSam Clegg SectionBookkeeping SubSection; 9746c899ba6SSam Clegg if (SymbolInfos.size() != 0) { 9756c899ba6SSam Clegg startSection(SubSection, wasm::WASM_SYMBOL_TABLE); 976f17b149dSPeter Collingbourne encodeULEB128(SymbolInfos.size(), W.OS); 9776c899ba6SSam Clegg for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) { 978f17b149dSPeter Collingbourne encodeULEB128(Sym.Kind, W.OS); 979f17b149dSPeter Collingbourne encodeULEB128(Sym.Flags, W.OS); 9806c899ba6SSam Clegg switch (Sym.Kind) { 9816c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_FUNCTION: 9826c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_GLOBAL: 983*da419bdbSHeejin Ahn case wasm::WASM_SYMBOL_TYPE_EVENT: 984f17b149dSPeter Collingbourne encodeULEB128(Sym.ElementIndex, W.OS); 9856c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) 9866c899ba6SSam Clegg writeString(Sym.Name); 9876c899ba6SSam Clegg break; 9886c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_DATA: 9896c899ba6SSam Clegg writeString(Sym.Name); 9906c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) { 991f17b149dSPeter Collingbourne encodeULEB128(Sym.DataRef.Segment, W.OS); 992f17b149dSPeter Collingbourne encodeULEB128(Sym.DataRef.Offset, W.OS); 993f17b149dSPeter Collingbourne encodeULEB128(Sym.DataRef.Size, W.OS); 9946c899ba6SSam Clegg } 9956c899ba6SSam Clegg break; 9966a31a0d6SSam Clegg case wasm::WASM_SYMBOL_TYPE_SECTION: { 9976a31a0d6SSam Clegg const uint32_t SectionIndex = 9986a31a0d6SSam Clegg CustomSections[Sym.ElementIndex].OutputIndex; 999f17b149dSPeter Collingbourne encodeULEB128(SectionIndex, W.OS); 10006a31a0d6SSam Clegg break; 10016a31a0d6SSam Clegg } 10026c899ba6SSam Clegg default: 10036c899ba6SSam Clegg llvm_unreachable("unexpected kind"); 10046c899ba6SSam Clegg } 1005b7787fd0SSam Clegg } 1006b7787fd0SSam Clegg endSection(SubSection); 1007b7787fd0SSam Clegg } 10089e15f359SSam Clegg 10096c899ba6SSam Clegg if (DataSegments.size()) { 101063ebb813SSam Clegg startSection(SubSection, wasm::WASM_SEGMENT_INFO); 1011f17b149dSPeter Collingbourne encodeULEB128(DataSegments.size(), W.OS); 10126c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 1013d95ed959SSam Clegg writeString(Segment.Name); 1014f17b149dSPeter Collingbourne encodeULEB128(Segment.Alignment, W.OS); 1015f17b149dSPeter Collingbourne encodeULEB128(Segment.Flags, W.OS); 101663ebb813SSam Clegg } 1017d95ed959SSam Clegg endSection(SubSection); 1018d95ed959SSam Clegg } 1019d95ed959SSam Clegg 1020bafe6902SSam Clegg if (!InitFuncs.empty()) { 1021bafe6902SSam Clegg startSection(SubSection, wasm::WASM_INIT_FUNCS); 1022f17b149dSPeter Collingbourne encodeULEB128(InitFuncs.size(), W.OS); 1023bafe6902SSam Clegg for (auto &StartFunc : InitFuncs) { 1024f17b149dSPeter Collingbourne encodeULEB128(StartFunc.first, W.OS); // priority 1025f17b149dSPeter Collingbourne encodeULEB128(StartFunc.second, W.OS); // function index 1026bafe6902SSam Clegg } 1027bafe6902SSam Clegg endSection(SubSection); 1028bafe6902SSam Clegg } 1029bafe6902SSam Clegg 1030ea7caceeSSam Clegg if (Comdats.size()) { 1031ea7caceeSSam Clegg startSection(SubSection, wasm::WASM_COMDAT_INFO); 1032f17b149dSPeter Collingbourne encodeULEB128(Comdats.size(), W.OS); 1033ea7caceeSSam Clegg for (const auto &C : Comdats) { 1034ea7caceeSSam Clegg writeString(C.first); 1035f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // flags for future use 1036f17b149dSPeter Collingbourne encodeULEB128(C.second.size(), W.OS); 1037ea7caceeSSam Clegg for (const WasmComdatEntry &Entry : C.second) { 1038f17b149dSPeter Collingbourne encodeULEB128(Entry.Kind, W.OS); 1039f17b149dSPeter Collingbourne encodeULEB128(Entry.Index, W.OS); 1040ea7caceeSSam Clegg } 1041ea7caceeSSam Clegg } 1042ea7caceeSSam Clegg endSection(SubSection); 1043ea7caceeSSam Clegg } 1044ea7caceeSSam Clegg 10459e15f359SSam Clegg endSection(Section); 10469e15f359SSam Clegg } 10479e15f359SSam Clegg 10486a31a0d6SSam Clegg void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm, 10496a31a0d6SSam Clegg const MCAsmLayout &Layout) { 10506a31a0d6SSam Clegg for (auto &CustomSection : CustomSections) { 1051cfd44a2eSSam Clegg SectionBookkeeping Section; 10526a31a0d6SSam Clegg auto *Sec = CustomSection.Section; 10532322a937SSam Clegg startCustomSection(Section, CustomSection.Name); 10546a31a0d6SSam Clegg 1055f17b149dSPeter Collingbourne Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset); 1056f17b149dSPeter Collingbourne Asm.writeSectionData(W.OS, Sec, Layout); 10576a31a0d6SSam Clegg 10586a31a0d6SSam Clegg CustomSection.OutputContentsOffset = Section.ContentsOffset; 10596a31a0d6SSam Clegg CustomSection.OutputIndex = Section.Index; 10606a31a0d6SSam Clegg 1061cfd44a2eSSam Clegg endSection(Section); 10626a31a0d6SSam Clegg 10636a31a0d6SSam Clegg // Apply fixups. 10644d57fbd0SSam Clegg auto &Relocations = CustomSectionsRelocations[CustomSection.Section]; 10654d57fbd0SSam Clegg applyRelocations(Relocations, CustomSection.OutputContentsOffset); 10666a31a0d6SSam Clegg } 10676a31a0d6SSam Clegg } 10686a31a0d6SSam Clegg 10695e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) { 10705e3d33a7SSam Clegg assert(Symbol.isFunction()); 10715e3d33a7SSam Clegg assert(TypeIndices.count(&Symbol)); 10725e3d33a7SSam Clegg return TypeIndices[&Symbol]; 10735e3d33a7SSam Clegg } 10745e3d33a7SSam Clegg 1075*da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) { 1076*da419bdbSHeejin Ahn assert(Symbol.isEvent()); 1077*da419bdbSHeejin Ahn assert(TypeIndices.count(&Symbol)); 1078*da419bdbSHeejin Ahn return TypeIndices[&Symbol]; 1079*da419bdbSHeejin Ahn } 1080*da419bdbSHeejin Ahn 10815e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) { 10825e3d33a7SSam Clegg assert(Symbol.isFunction()); 10835e3d33a7SSam Clegg 1084*da419bdbSHeejin Ahn WasmSignature S; 1085aff1c4dfSSam Clegg const MCSymbolWasm *ResolvedSym = ResolveSymbol(Symbol); 108677a7a380SDerek Schuff if (auto *Sig = ResolvedSym->getSignature()) { 1087*da419bdbSHeejin Ahn S.Returns = Sig->Returns; 1088*da419bdbSHeejin Ahn S.Params = Sig->Params; 108977a7a380SDerek Schuff } 10905e3d33a7SSam Clegg 1091*da419bdbSHeejin Ahn auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 10925e3d33a7SSam Clegg if (Pair.second) 1093*da419bdbSHeejin Ahn Signatures.push_back(S); 10945e3d33a7SSam Clegg TypeIndices[&Symbol] = Pair.first->second; 10955e3d33a7SSam Clegg 1096d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol 1097d34e60caSNicola Zaghen << " new:" << Pair.second << "\n"); 1098d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 10995e3d33a7SSam Clegg return Pair.first->second; 11005e3d33a7SSam Clegg } 11015e3d33a7SSam Clegg 1102*da419bdbSHeejin Ahn uint32_t WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) { 1103*da419bdbSHeejin Ahn assert(Symbol.isEvent()); 1104*da419bdbSHeejin Ahn 1105*da419bdbSHeejin Ahn // TODO Currently we don't generate imported exceptions, but if we do, we 1106*da419bdbSHeejin Ahn // should have a way of infering types of imported exceptions. 1107*da419bdbSHeejin Ahn WasmSignature S; 1108*da419bdbSHeejin Ahn if (auto *Sig = Symbol.getSignature()) { 1109*da419bdbSHeejin Ahn S.Returns = Sig->Returns; 1110*da419bdbSHeejin Ahn S.Params = Sig->Params; 1111*da419bdbSHeejin Ahn } 1112*da419bdbSHeejin Ahn 1113*da419bdbSHeejin Ahn auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 1114*da419bdbSHeejin Ahn if (Pair.second) 1115*da419bdbSHeejin Ahn Signatures.push_back(S); 1116*da419bdbSHeejin Ahn TypeIndices[&Symbol] = Pair.first->second; 1117*da419bdbSHeejin Ahn 1118*da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second 1119*da419bdbSHeejin Ahn << "\n"); 1120*da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 1121*da419bdbSHeejin Ahn return Pair.first->second; 1122*da419bdbSHeejin Ahn } 1123*da419bdbSHeejin Ahn 11244d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) { 11254d57fbd0SSam Clegg if (Sym.isUsedInReloc()) 11264d57fbd0SSam Clegg return true; 11274d57fbd0SSam Clegg 11284d57fbd0SSam Clegg if (Sym.isComdat() && !Sym.isDefined()) 11294d57fbd0SSam Clegg return false; 11304d57fbd0SSam Clegg 11314d57fbd0SSam Clegg if (Sym.isTemporary() && Sym.getName().empty()) 11324d57fbd0SSam Clegg return false; 11334d57fbd0SSam Clegg 11344d57fbd0SSam Clegg if (Sym.isTemporary() && Sym.isData() && !Sym.getSize()) 11354d57fbd0SSam Clegg return false; 11364d57fbd0SSam Clegg 11374d57fbd0SSam Clegg if (Sym.isSection()) 11384d57fbd0SSam Clegg return false; 11394d57fbd0SSam Clegg 11404d57fbd0SSam Clegg return true; 11414d57fbd0SSam Clegg } 11424d57fbd0SSam Clegg 1143438390faSPeter Collingbourne uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm, 114418eafb6cSDan Gohman const MCAsmLayout &Layout) { 1145438390faSPeter Collingbourne uint64_t StartOffset = W.OS.tell(); 1146438390faSPeter Collingbourne 1147d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 114882607f56SDan Gohman MCContext &Ctx = Asm.getContext(); 1149d934cb88SDan Gohman 1150d934cb88SDan Gohman // Collect information from the available symbols. 1151d934cb88SDan Gohman SmallVector<WasmFunction, 4> Functions; 1152d934cb88SDan Gohman SmallVector<uint32_t, 4> TableElems; 11538defa952SSam Clegg SmallVector<wasm::WasmImport, 4> Imports; 11548defa952SSam Clegg SmallVector<wasm::WasmExport, 4> Exports; 1155*da419bdbSHeejin Ahn SmallVector<wasm::WasmEventType, 1> Events; 11566c899ba6SSam Clegg SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos; 1157bafe6902SSam Clegg SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 1158ea7caceeSSam Clegg std::map<StringRef, std::vector<WasmComdatEntry>> Comdats; 11597c395943SSam Clegg uint32_t DataSize = 0; 1160d934cb88SDan Gohman 1161f950b24aSSam Clegg // For now, always emit the memory import, since loads and stores are not 1162f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1163f950b24aSSam Clegg // it if there are no loads or stores. 1164f950b24aSSam Clegg MCSymbolWasm *MemorySym = 1165f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory")); 11668defa952SSam Clegg wasm::WasmImport MemImport; 11678defa952SSam Clegg MemImport.Module = MemorySym->getModuleName(); 11688defa952SSam Clegg MemImport.Field = MemorySym->getName(); 1169f950b24aSSam Clegg MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1170f950b24aSSam Clegg Imports.push_back(MemImport); 1171f950b24aSSam Clegg 1172f950b24aSSam Clegg // For now, always emit the table section, since indirect calls are not 1173f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1174f950b24aSSam Clegg // it if there are no indirect calls. 1175f950b24aSSam Clegg MCSymbolWasm *TableSym = 1176f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table")); 11778defa952SSam Clegg wasm::WasmImport TableImport; 11788defa952SSam Clegg TableImport.Module = TableSym->getModuleName(); 11798defa952SSam Clegg TableImport.Field = TableSym->getName(); 1180f950b24aSSam Clegg TableImport.Kind = wasm::WASM_EXTERNAL_TABLE; 11818defa952SSam Clegg TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC; 1182f950b24aSSam Clegg Imports.push_back(TableImport); 1183f950b24aSSam Clegg 1184*da419bdbSHeejin Ahn // Populate SignatureIndices, and Imports and WasmIndices for undefined 1185586320c0SNicholas Wilson // symbols. This must be done before populating WasmIndices for defined 1186586320c0SNicholas Wilson // symbols. 118732ce5ca0SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 118832ce5ca0SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 118932ce5ca0SDan Gohman 119032ce5ca0SDan Gohman // Register types for all functions, including those with private linkage 11919f3fe42eSSam Clegg // (because wasm always needs a type signature). 119232ce5ca0SDan Gohman if (WS.isFunction()) 119332ce5ca0SDan Gohman registerFunctionType(WS); 119432ce5ca0SDan Gohman 1195*da419bdbSHeejin Ahn if (WS.isEvent()) 1196*da419bdbSHeejin Ahn registerEventType(WS); 1197*da419bdbSHeejin Ahn 119832ce5ca0SDan Gohman if (WS.isTemporary()) 119932ce5ca0SDan Gohman continue; 120032ce5ca0SDan Gohman 120132ce5ca0SDan Gohman // If the symbol is not defined in this translation unit, import it. 12026c899ba6SSam Clegg if (!WS.isDefined() && !WS.isComdat()) { 12036c899ba6SSam Clegg if (WS.isFunction()) { 12048defa952SSam Clegg wasm::WasmImport Import; 12058defa952SSam Clegg Import.Module = WS.getModuleName(); 12068defa952SSam Clegg Import.Field = WS.getName(); 120732ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 12088defa952SSam Clegg Import.SigIndex = getFunctionType(WS); 12096c899ba6SSam Clegg Imports.push_back(Import); 12106c899ba6SSam Clegg WasmIndices[&WS] = NumFunctionImports++; 12116c899ba6SSam Clegg } else if (WS.isGlobal()) { 121215f349f7SNicholas Wilson if (WS.isWeak()) 121315f349f7SNicholas Wilson report_fatal_error("undefined global symbol cannot be weak"); 121415f349f7SNicholas Wilson 12156c899ba6SSam Clegg wasm::WasmImport Import; 12166c899ba6SSam Clegg Import.Module = WS.getModuleName(); 12176c899ba6SSam Clegg Import.Field = WS.getName(); 121832ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 12196c899ba6SSam Clegg Import.Global = WS.getGlobalType(); 12206c899ba6SSam Clegg Imports.push_back(Import); 12216c899ba6SSam Clegg WasmIndices[&WS] = NumGlobalImports++; 1222*da419bdbSHeejin Ahn } else if (WS.isEvent()) { 1223*da419bdbSHeejin Ahn if (WS.isWeak()) 1224*da419bdbSHeejin Ahn report_fatal_error("undefined event symbol cannot be weak"); 1225*da419bdbSHeejin Ahn 1226*da419bdbSHeejin Ahn wasm::WasmImport Import; 1227*da419bdbSHeejin Ahn Import.Module = WS.getModuleName(); 1228*da419bdbSHeejin Ahn Import.Field = WS.getName(); 1229*da419bdbSHeejin Ahn Import.Kind = wasm::WASM_EXTERNAL_EVENT; 1230*da419bdbSHeejin Ahn Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION; 1231*da419bdbSHeejin Ahn Import.Event.SigIndex = getEventType(WS); 1232*da419bdbSHeejin Ahn Imports.push_back(Import); 1233*da419bdbSHeejin Ahn WasmIndices[&WS] = NumEventImports++; 123432ce5ca0SDan Gohman } 123532ce5ca0SDan Gohman } 123632ce5ca0SDan Gohman } 123732ce5ca0SDan Gohman 12384d57fbd0SSam Clegg // Populate DataSegments and CustomSections, which must be done before 12394d57fbd0SSam Clegg // populating DataLocations. 1240759631c7SSam Clegg for (MCSection &Sec : Asm) { 1241759631c7SSam Clegg auto &Section = static_cast<MCSectionWasm &>(Sec); 12424d57fbd0SSam Clegg StringRef SectionName = Section.getSectionName(); 1243759631c7SSam Clegg 1244bafe6902SSam Clegg // .init_array sections are handled specially elsewhere. 12454d57fbd0SSam Clegg if (SectionName.startswith(".init_array")) 1246bafe6902SSam Clegg continue; 1247bafe6902SSam Clegg 12484d57fbd0SSam Clegg // Code is handled separately 12494d57fbd0SSam Clegg if (Section.getKind().isText()) 12504d57fbd0SSam Clegg continue; 12514d57fbd0SSam Clegg 12524d57fbd0SSam Clegg if (Section.isWasmData()) { 1253329e76d5SSam Clegg uint32_t SegmentIndex = DataSegments.size(); 1254759631c7SSam Clegg DataSize = alignTo(DataSize, Section.getAlignment()); 1255759631c7SSam Clegg DataSegments.emplace_back(); 1256759631c7SSam Clegg WasmDataSegment &Segment = DataSegments.back(); 12574d57fbd0SSam Clegg Segment.Name = SectionName; 1258759631c7SSam Clegg Segment.Offset = DataSize; 1259759631c7SSam Clegg Segment.Section = &Section; 126063ebb813SSam Clegg addData(Segment.Data, Section); 126163ebb813SSam Clegg Segment.Alignment = Section.getAlignment(); 126263ebb813SSam Clegg Segment.Flags = 0; 1263759631c7SSam Clegg DataSize += Segment.Data.size(); 12646c899ba6SSam Clegg Section.setSegmentIndex(SegmentIndex); 1265ea7caceeSSam Clegg 1266ea7caceeSSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 1267ea7caceeSSam Clegg Comdats[C->getName()].emplace_back( 1268329e76d5SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex}); 1269ea7caceeSSam Clegg } 12704d57fbd0SSam Clegg } else { 12714d57fbd0SSam Clegg // Create custom sections 12724d57fbd0SSam Clegg assert(Sec.getKind().isMetadata()); 12734d57fbd0SSam Clegg 12744d57fbd0SSam Clegg StringRef Name = SectionName; 12754d57fbd0SSam Clegg 12764d57fbd0SSam Clegg // For user-defined custom sections, strip the prefix 12774d57fbd0SSam Clegg if (Name.startswith(".custom_section.")) 12784d57fbd0SSam Clegg Name = Name.substr(strlen(".custom_section.")); 12794d57fbd0SSam Clegg 12804d57fbd0SSam Clegg MCSymbol *Begin = Sec.getBeginSymbol(); 1281fb807d4dSSam Clegg if (Begin) { 12824d57fbd0SSam Clegg WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size(); 1283b210c64bSSam Clegg if (SectionName != Begin->getName()) 1284fb807d4dSSam Clegg report_fatal_error("section name and begin symbol should match: " + 1285b210c64bSSam Clegg Twine(SectionName)); 1286fb807d4dSSam Clegg } 12874d57fbd0SSam Clegg CustomSections.emplace_back(Name, &Section); 1288759631c7SSam Clegg } 12896a31a0d6SSam Clegg } 12906a31a0d6SSam Clegg 1291586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for defined symbols. 1292d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1293d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1294d934cb88SDan Gohman // or used in relocations. 1295d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 1296d934cb88SDan Gohman continue; 1297b7787fd0SSam Clegg 1298d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 1299d34e60caSNicola Zaghen LLVM_DEBUG( 1300d34e60caSNicola Zaghen dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'" 1301d34e60caSNicola Zaghen << " isDefined=" << S.isDefined() << " isExternal=" 1302d34e60caSNicola Zaghen << S.isExternal() << " isTemporary=" << S.isTemporary() 1303d34e60caSNicola Zaghen << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden() 1304b7787fd0SSam Clegg << " isVariable=" << WS.isVariable() << "\n"); 1305b7787fd0SSam Clegg 13065e3d33a7SSam Clegg if (WS.isVariable()) 13075e3d33a7SSam Clegg continue; 13086c899ba6SSam Clegg if (WS.isComdat() && !WS.isDefined()) 13096c899ba6SSam Clegg continue; 1310b7787fd0SSam Clegg 1311d934cb88SDan Gohman if (WS.isFunction()) { 13126c899ba6SSam Clegg unsigned Index; 1313cd65f698SSam Clegg if (WS.isDefined()) { 1314b7787fd0SSam Clegg if (WS.getOffset() != 0) 1315b7787fd0SSam Clegg report_fatal_error( 1316b7787fd0SSam Clegg "function sections must contain one function each"); 1317b7787fd0SSam Clegg 1318b7787fd0SSam Clegg if (WS.getSize() == 0) 1319b7787fd0SSam Clegg report_fatal_error( 1320b7787fd0SSam Clegg "function symbols must have a size set with .size"); 1321b7787fd0SSam Clegg 13226c899ba6SSam Clegg // A definition. Write out the function body. 13239f3fe42eSSam Clegg Index = NumFunctionImports + Functions.size(); 1324d934cb88SDan Gohman WasmFunction Func; 1325*da419bdbSHeejin Ahn Func.SigIndex = getFunctionType(WS); 1326d934cb88SDan Gohman Func.Sym = &WS; 13276c899ba6SSam Clegg WasmIndices[&WS] = Index; 1328d934cb88SDan Gohman Functions.push_back(Func); 13296c899ba6SSam Clegg 13306c899ba6SSam Clegg auto &Section = static_cast<MCSectionWasm &>(WS.getSection()); 13316c899ba6SSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 13326c899ba6SSam Clegg Comdats[C->getName()].emplace_back( 13336c899ba6SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index}); 13346c899ba6SSam Clegg } 1335d934cb88SDan Gohman } else { 1336d934cb88SDan Gohman // An import; the index was assigned above. 13376c899ba6SSam Clegg Index = WasmIndices.find(&WS)->second; 1338d934cb88SDan Gohman } 1339d934cb88SDan Gohman 1340d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n"); 1341*da419bdbSHeejin Ahn 13426c899ba6SSam Clegg } else if (WS.isData()) { 1343c38e947eSSam Clegg if (WS.isTemporary() && !WS.getSize()) 1344c38e947eSSam Clegg continue; 1345c38e947eSSam Clegg 13466c899ba6SSam Clegg if (!WS.isDefined()) { 1347d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> segment index: -1" 1348d34e60caSNicola Zaghen << "\n"); 1349fe6414b0SSam Clegg continue; 13506c899ba6SSam Clegg } 1351fe6414b0SSam Clegg 1352d934cb88SDan Gohman if (!WS.getSize()) 1353c38e947eSSam Clegg report_fatal_error("data symbols must have a size set with .size: " + 1354c38e947eSSam Clegg WS.getName()); 1355d934cb88SDan Gohman 1356d934cb88SDan Gohman int64_t Size = 0; 1357d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1358d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 1359d934cb88SDan Gohman 1360759631c7SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1361ea7caceeSSam Clegg assert(DataSection.isWasmData()); 13627c395943SSam Clegg 13636c899ba6SSam Clegg // For each data symbol, export it in the symtab as a reference to the 13646c899ba6SSam Clegg // corresponding Wasm data segment. 13656c899ba6SSam Clegg wasm::WasmDataReference Ref = wasm::WasmDataReference{ 13666c899ba6SSam Clegg DataSection.getSegmentIndex(), 13676c899ba6SSam Clegg static_cast<uint32_t>(Layout.getSymbolOffset(WS)), 13686c899ba6SSam Clegg static_cast<uint32_t>(Size)}; 13696c899ba6SSam Clegg DataLocations[&WS] = Ref; 1370d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n"); 1371*da419bdbSHeejin Ahn 1372a165f2d6SSam Clegg } else if (WS.isGlobal()) { 13736c899ba6SSam Clegg // A "true" Wasm global (currently just __stack_pointer) 1374545932beSEric Christopher if (WS.isDefined()) 13756c899ba6SSam Clegg report_fatal_error("don't yet support defined globals"); 13766c899ba6SSam Clegg 1377545932beSEric Christopher // An import; the index was assigned above 1378d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> global index: " 1379d34e60caSNicola Zaghen << WasmIndices.find(&WS)->second << "\n"); 1380*da419bdbSHeejin Ahn 1381*da419bdbSHeejin Ahn } else if (WS.isEvent()) { 1382*da419bdbSHeejin Ahn // C++ exception symbol (__cpp_exception) 1383*da419bdbSHeejin Ahn unsigned Index; 1384*da419bdbSHeejin Ahn if (WS.isDefined()) { 1385*da419bdbSHeejin Ahn Index = NumEventImports + Events.size(); 1386*da419bdbSHeejin Ahn wasm::WasmEventType Event; 1387*da419bdbSHeejin Ahn Event.SigIndex = getEventType(WS); 1388*da419bdbSHeejin Ahn Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION; 1389*da419bdbSHeejin Ahn WasmIndices[&WS] = Index; 1390*da419bdbSHeejin Ahn Events.push_back(Event); 1391*da419bdbSHeejin Ahn } else { 1392*da419bdbSHeejin Ahn // An import; the index was assigned above. 1393*da419bdbSHeejin Ahn Index = WasmIndices.find(&WS)->second; 1394*da419bdbSHeejin Ahn } 1395*da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second 1396*da419bdbSHeejin Ahn << "\n"); 1397*da419bdbSHeejin Ahn 1398a165f2d6SSam Clegg } else { 1399a165f2d6SSam Clegg assert(WS.isSection()); 1400d934cb88SDan Gohman } 1401d934cb88SDan Gohman } 1402d934cb88SDan Gohman 1403586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for aliased symbols. We need to 1404586320c0SNicholas Wilson // process these in a separate pass because we need to have processed the 1405586320c0SNicholas Wilson // target of the alias before the alias itself and the symbols are not 1406586320c0SNicholas Wilson // necessarily ordered in this way. 1407b7787fd0SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1408b7787fd0SSam Clegg if (!S.isVariable()) 1409b7787fd0SSam Clegg continue; 141031a2c809SSam Clegg 1411cd65f698SSam Clegg assert(S.isDefined()); 1412b7787fd0SSam Clegg 14135e3d33a7SSam Clegg // Find the target symbol of this weak alias and export that index 1414aff1c4dfSSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 1415aff1c4dfSSam Clegg const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS); 1416d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym 1417d34e60caSNicola Zaghen << "'\n"); 1418b7787fd0SSam Clegg 14196c899ba6SSam Clegg if (WS.isFunction()) { 14206c899ba6SSam Clegg assert(WasmIndices.count(ResolvedSym) > 0); 14216c899ba6SSam Clegg uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second; 14226c899ba6SSam Clegg WasmIndices[&WS] = WasmIndex; 1423d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n"); 14246c899ba6SSam Clegg } else if (WS.isData()) { 14256c899ba6SSam Clegg assert(DataLocations.count(ResolvedSym) > 0); 14266c899ba6SSam Clegg const wasm::WasmDataReference &Ref = 14276c899ba6SSam Clegg DataLocations.find(ResolvedSym)->second; 14286c899ba6SSam Clegg DataLocations[&WS] = Ref; 1429d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n"); 14306c899ba6SSam Clegg } else { 1431*da419bdbSHeejin Ahn report_fatal_error("don't yet support global/event aliases"); 14326c899ba6SSam Clegg } 1433586320c0SNicholas Wilson } 143431a2c809SSam Clegg 1435586320c0SNicholas Wilson // Finally, populate the symbol table itself, in its "natural" order. 1436586320c0SNicholas Wilson for (const MCSymbol &S : Asm.symbols()) { 1437586320c0SNicholas Wilson const auto &WS = static_cast<const MCSymbolWasm &>(S); 143825d8e68bSSam Clegg if (!isInSymtab(WS)) { 143925d8e68bSSam Clegg WS.setIndex(INVALID_INDEX); 1440586320c0SNicholas Wilson continue; 144125d8e68bSSam Clegg } 1442d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n"); 1443586320c0SNicholas Wilson 1444586320c0SNicholas Wilson uint32_t Flags = 0; 1445586320c0SNicholas Wilson if (WS.isWeak()) 1446586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_WEAK; 1447586320c0SNicholas Wilson if (WS.isHidden()) 1448586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN; 1449586320c0SNicholas Wilson if (!WS.isExternal() && WS.isDefined()) 1450586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL; 1451586320c0SNicholas Wilson if (WS.isUndefined()) 1452586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_UNDEFINED; 1453586320c0SNicholas Wilson 1454586320c0SNicholas Wilson wasm::WasmSymbolInfo Info; 1455586320c0SNicholas Wilson Info.Name = WS.getName(); 1456586320c0SNicholas Wilson Info.Kind = WS.getType(); 1457586320c0SNicholas Wilson Info.Flags = Flags; 14584d57fbd0SSam Clegg if (!WS.isData()) { 14594d57fbd0SSam Clegg assert(WasmIndices.count(&WS) > 0); 1460586320c0SNicholas Wilson Info.ElementIndex = WasmIndices.find(&WS)->second; 14614d57fbd0SSam Clegg } else if (WS.isDefined()) { 14624d57fbd0SSam Clegg assert(DataLocations.count(&WS) > 0); 1463586320c0SNicholas Wilson Info.DataRef = DataLocations.find(&WS)->second; 14644d57fbd0SSam Clegg } 146525d8e68bSSam Clegg WS.setIndex(SymbolInfos.size()); 1466586320c0SNicholas Wilson SymbolInfos.emplace_back(Info); 1467b7787fd0SSam Clegg } 1468b7787fd0SSam Clegg 14696006e091SSam Clegg { 14706006e091SSam Clegg auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 1471f9edbe95SSam Clegg // Functions referenced by a relocation need to put in the table. This is 1472f9edbe95SSam Clegg // purely to make the object file's provisional values readable, and is 1473f9edbe95SSam Clegg // ignored by the linker, which re-calculates the relocations itself. 1474f9edbe95SSam Clegg if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 && 1475f9edbe95SSam Clegg Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB) 1476f9edbe95SSam Clegg return; 1477f9edbe95SSam Clegg assert(Rel.Symbol->isFunction()); 1478f9edbe95SSam Clegg const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol); 14796c899ba6SSam Clegg uint32_t FunctionIndex = WasmIndices.find(&WS)->second; 1480f9edbe95SSam Clegg uint32_t TableIndex = TableElems.size() + kInitialTableOffset; 1481f9edbe95SSam Clegg if (TableIndices.try_emplace(&WS, TableIndex).second) { 1482d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> adding " << WS.getName() 1483f9edbe95SSam Clegg << " to table: " << TableIndex << "\n"); 14846c899ba6SSam Clegg TableElems.push_back(FunctionIndex); 14856006e091SSam Clegg registerFunctionType(WS); 14866006e091SSam Clegg } 14876006e091SSam Clegg }; 1488970d02c4SDan Gohman 14896006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : CodeRelocations) 14906006e091SSam Clegg HandleReloc(RelEntry); 14916006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : DataRelocations) 14926006e091SSam Clegg HandleReloc(RelEntry); 1493d934cb88SDan Gohman } 1494d934cb88SDan Gohman 1495bafe6902SSam Clegg // Translate .init_array section contents into start functions. 1496bafe6902SSam Clegg for (const MCSection &S : Asm) { 1497bafe6902SSam Clegg const auto &WS = static_cast<const MCSectionWasm &>(S); 1498bafe6902SSam Clegg if (WS.getSectionName().startswith(".fini_array")) 1499bafe6902SSam Clegg report_fatal_error(".fini_array sections are unsupported"); 1500bafe6902SSam Clegg if (!WS.getSectionName().startswith(".init_array")) 1501bafe6902SSam Clegg continue; 1502bafe6902SSam Clegg if (WS.getFragmentList().empty()) 1503bafe6902SSam Clegg continue; 1504b210c64bSSam Clegg 1505b210c64bSSam Clegg // init_array is expected to contain a single non-empty data fragment 1506b210c64bSSam Clegg if (WS.getFragmentList().size() != 3) 1507bafe6902SSam Clegg report_fatal_error("only one .init_array section fragment supported"); 1508b210c64bSSam Clegg 1509b210c64bSSam Clegg auto IT = WS.begin(); 1510b210c64bSSam Clegg const MCFragment &EmptyFrag = *IT; 1511b210c64bSSam Clegg if (EmptyFrag.getKind() != MCFragment::FT_Data) 1512b210c64bSSam Clegg report_fatal_error(".init_array section should be aligned"); 1513b210c64bSSam Clegg 1514b210c64bSSam Clegg IT = std::next(IT); 1515b210c64bSSam Clegg const MCFragment &AlignFrag = *IT; 1516bafe6902SSam Clegg if (AlignFrag.getKind() != MCFragment::FT_Align) 1517bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned"); 1518bafe6902SSam Clegg if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1519bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned for pointers"); 1520b210c64bSSam Clegg 1521b210c64bSSam Clegg const MCFragment &Frag = *std::next(IT); 1522bafe6902SSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1523bafe6902SSam Clegg report_fatal_error("only data supported in .init_array section"); 1524b210c64bSSam Clegg 1525bafe6902SSam Clegg uint16_t Priority = UINT16_MAX; 15264d57fbd0SSam Clegg unsigned PrefixLength = strlen(".init_array"); 15274d57fbd0SSam Clegg if (WS.getSectionName().size() > PrefixLength) { 15284d57fbd0SSam Clegg if (WS.getSectionName()[PrefixLength] != '.') 1529f208f631SHeejin Ahn report_fatal_error( 1530f208f631SHeejin Ahn ".init_array section priority should start with '.'"); 15314d57fbd0SSam Clegg if (WS.getSectionName() 15324d57fbd0SSam Clegg .substr(PrefixLength + 1) 15334d57fbd0SSam Clegg .getAsInteger(10, Priority)) 1534bafe6902SSam Clegg report_fatal_error("invalid .init_array section priority"); 1535bafe6902SSam Clegg } 1536bafe6902SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1537bafe6902SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1538f208f631SHeejin Ahn for (const uint8_t * 1539f208f631SHeejin Ahn p = (const uint8_t *)Contents.data(), 1540bafe6902SSam Clegg *end = (const uint8_t *)Contents.data() + Contents.size(); 1541bafe6902SSam Clegg p != end; ++p) { 1542bafe6902SSam Clegg if (*p != 0) 1543bafe6902SSam Clegg report_fatal_error("non-symbolic data in .init_array section"); 1544bafe6902SSam Clegg } 1545bafe6902SSam Clegg for (const MCFixup &Fixup : DataFrag.getFixups()) { 1546f208f631SHeejin Ahn assert(Fixup.getKind() == 1547f208f631SHeejin Ahn MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1548bafe6902SSam Clegg const MCExpr *Expr = Fixup.getValue(); 1549bafe6902SSam Clegg auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr); 1550bafe6902SSam Clegg if (!Sym) 1551bafe6902SSam Clegg report_fatal_error("fixups in .init_array should be symbol references"); 1552bafe6902SSam Clegg if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION) 1553bafe6902SSam Clegg report_fatal_error("symbols in .init_array should be for functions"); 155425d8e68bSSam Clegg if (Sym->getSymbol().getIndex() == INVALID_INDEX) 155525d8e68bSSam Clegg report_fatal_error("symbols in .init_array should exist in symbtab"); 155625d8e68bSSam Clegg InitFuncs.push_back( 155725d8e68bSSam Clegg std::make_pair(Priority, Sym->getSymbol().getIndex())); 1558bafe6902SSam Clegg } 1559bafe6902SSam Clegg } 1560bafe6902SSam Clegg 156118eafb6cSDan Gohman // Write out the Wasm header. 156218eafb6cSDan Gohman writeHeader(Asm); 156318eafb6cSDan Gohman 1564*da419bdbSHeejin Ahn writeTypeSection(Signatures); 1565f950b24aSSam Clegg writeImportSection(Imports, DataSize, TableElems.size()); 15669e15f359SSam Clegg writeFunctionSection(Functions); 1567f950b24aSSam Clegg // Skip the "table" section; we import the table instead. 1568f950b24aSSam Clegg // Skip the "memory" section; we import the memory instead. 15697c395943SSam Clegg writeGlobalSection(); 1570*da419bdbSHeejin Ahn writeEventSection(Events); 15719e15f359SSam Clegg writeExportSection(Exports); 15729e15f359SSam Clegg writeElemSection(TableElems); 1573acd7d2b0SSam Clegg writeCodeSection(Asm, Layout, Functions); 15746c899ba6SSam Clegg writeDataSection(); 15756a31a0d6SSam Clegg writeCustomSections(Asm, Layout); 1576c22bfb6bSNicholas Wilson writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats); 15776f08c84aSSam Clegg writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations); 15786f08c84aSSam Clegg writeRelocSection(DataSectionIndex, "DATA", DataRelocations); 15796a31a0d6SSam Clegg writeCustomRelocSections(); 1580970d02c4SDan Gohman 1581d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 1582438390faSPeter Collingbourne return W.OS.tell() - StartOffset; 158318eafb6cSDan Gohman } 158418eafb6cSDan Gohman 158560fbc7ccSLang Hames std::unique_ptr<MCObjectWriter> 15861301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 158718eafb6cSDan Gohman raw_pwrite_stream &OS) { 15880917c9e4SDan Gohman return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS); 158918eafb6cSDan Gohman } 1590