118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===// 218eafb6cSDan Gohman // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 618eafb6cSDan Gohman // 718eafb6cSDan Gohman //===----------------------------------------------------------------------===// 818eafb6cSDan Gohman // 918eafb6cSDan Gohman // This file implements Wasm object file writer information. 1018eafb6cSDan Gohman // 1118eafb6cSDan Gohman //===----------------------------------------------------------------------===// 1218eafb6cSDan Gohman 1318eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h" 1418eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h" 15264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h" 16b59dff4bSBenjamin Kramer #include "llvm/BinaryFormat/WasmTraits.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" 31bcd7f777SSimon Pilgrim #include "llvm/Support/EndianStream.h" 3218eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h" 33d934cb88SDan Gohman #include "llvm/Support/LEB128.h" 3418eafb6cSDan Gohman #include "llvm/Support/StringSaver.h" 3518eafb6cSDan Gohman #include <vector> 3618eafb6cSDan Gohman 3718eafb6cSDan Gohman using namespace llvm; 3818eafb6cSDan Gohman 395e3d33a7SSam Clegg #define DEBUG_TYPE "mc" 4018eafb6cSDan Gohman 4118eafb6cSDan Gohman namespace { 429e15f359SSam Clegg 43feac819eSAndy Wingo // When we create the indirect function table we start at 1, so that there is 44feac819eSAndy Wingo // and empty slot at 0 and therefore calling a null function pointer will trap. 4518c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1; 4630e1bbc1SSam Clegg 47d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both 48d934cb88SDan Gohman // for patching up the section size field, and for patching up references to 49d934cb88SDan Gohman // locations within the section. 50d934cb88SDan Gohman struct SectionBookkeeping { 51d934cb88SDan Gohman // Where the size of the section is written. 52d934cb88SDan Gohman uint64_t SizeOffset; 536a31a0d6SSam Clegg // Where the section header ends (without custom section name). 546a31a0d6SSam Clegg uint64_t PayloadOffset; 556a31a0d6SSam Clegg // Where the contents of the section starts. 56d934cb88SDan Gohman uint64_t ContentsOffset; 576f08c84aSSam Clegg uint32_t Index; 58d934cb88SDan Gohman }; 59d934cb88SDan Gohman 607c395943SSam Clegg // A wasm data segment. A wasm binary contains only a single data section 617c395943SSam Clegg // but that can contain many segments, each with their own virtual location 627c395943SSam Clegg // in memory. Each MCSection data created by llvm is modeled as its own 637c395943SSam Clegg // wasm data segment. 647c395943SSam Clegg struct WasmDataSegment { 657c395943SSam Clegg MCSectionWasm *Section; 66d95ed959SSam Clegg StringRef Name; 672e150409SThomas Lively uint32_t InitFlags; 684d135b04SWouter van Oortmerssen uint64_t Offset; 6963ebb813SSam Clegg uint32_t Alignment; 703b8d2be5SSam Clegg uint32_t LinkingFlags; 717c395943SSam Clegg SmallVector<char, 4> Data; 727c395943SSam Clegg }; 737c395943SSam Clegg 749e15f359SSam Clegg // A wasm function to be written into the function section. 759e15f359SSam Clegg struct WasmFunction { 76da419bdbSHeejin Ahn uint32_t SigIndex; 779e15f359SSam Clegg const MCSymbolWasm *Sym; 789e15f359SSam Clegg }; 799e15f359SSam Clegg 809e15f359SSam Clegg // A wasm global to be written into the global section. 819e15f359SSam Clegg struct WasmGlobal { 826e7f1826SSam Clegg wasm::WasmGlobalType Type; 839e15f359SSam Clegg uint64_t InitialValue; 849e15f359SSam Clegg }; 859e15f359SSam Clegg 86ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT. For each data 87ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding 88ea7caceeSSam Clegg // WasmComdatEntry. 89ea7caceeSSam Clegg struct WasmComdatEntry { 90ea7caceeSSam Clegg unsigned Kind; 91ea7caceeSSam Clegg uint32_t Index; 92ea7caceeSSam Clegg }; 93ea7caceeSSam Clegg 946dc65e91SSam Clegg // Information about a single relocation. 956dc65e91SSam Clegg struct WasmRelocationEntry { 966dc65e91SSam Clegg uint64_t Offset; // Where is the relocation. 976dc65e91SSam Clegg const MCSymbolWasm *Symbol; // The symbol to relocate with. 986dc65e91SSam Clegg int64_t Addend; // A value to add to the symbol. 996dc65e91SSam Clegg unsigned Type; // The type of the relocation. 100fe6414b0SSam Clegg const MCSectionWasm *FixupSection; // The section the relocation is targeting. 1016dc65e91SSam Clegg 1026dc65e91SSam Clegg WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol, 1036dc65e91SSam Clegg int64_t Addend, unsigned Type, 104fe6414b0SSam Clegg const MCSectionWasm *FixupSection) 1056dc65e91SSam Clegg : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type), 1066dc65e91SSam Clegg FixupSection(FixupSection) {} 1076dc65e91SSam Clegg 108cadcb9ebSKeno Fischer bool hasAddend() const { return wasm::relocTypeHasAddend(Type); } 109acd7d2b0SSam Clegg 1106dc65e91SSam Clegg void print(raw_ostream &Out) const { 111f208f631SHeejin Ahn Out << wasm::relocTypetoString(Type) << " Off=" << Offset 112f208f631SHeejin Ahn << ", Sym=" << *Symbol << ", Addend=" << Addend 1137d1ff446SFangrui Song << ", FixupSection=" << FixupSection->getName(); 1146dc65e91SSam Clegg } 115b7787fd0SSam Clegg 116615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 117b7787fd0SSam Clegg LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 118b7787fd0SSam Clegg #endif 1196dc65e91SSam Clegg }; 1206dc65e91SSam Clegg 12118c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1; 12225d8e68bSSam Clegg 123cfd44a2eSSam Clegg struct WasmCustomSection { 124cfd44a2eSSam Clegg 1256a31a0d6SSam Clegg StringRef Name; 1266a31a0d6SSam Clegg MCSectionWasm *Section; 1276a31a0d6SSam Clegg 1286a31a0d6SSam Clegg uint32_t OutputContentsOffset; 1296a31a0d6SSam Clegg uint32_t OutputIndex; 1306a31a0d6SSam Clegg 1316a31a0d6SSam Clegg WasmCustomSection(StringRef Name, MCSectionWasm *Section) 1326a31a0d6SSam Clegg : Name(Name), Section(Section), OutputContentsOffset(0), 13318c56a07SHeejin Ahn OutputIndex(InvalidIndex) {} 134cfd44a2eSSam Clegg }; 135cfd44a2eSSam Clegg 1361fb8daa6SSam Clegg #if !defined(NDEBUG) 1377f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) { 138b7787fd0SSam Clegg Rel.print(OS); 139b7787fd0SSam Clegg return OS; 140b7787fd0SSam Clegg } 1411fb8daa6SSam Clegg #endif 142b7787fd0SSam Clegg 14319e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded 14419e8befaSSam Clegg // to allow patching. 1453b29376eSWouter van Oortmerssen template <int W> 1463b29376eSWouter van Oortmerssen void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) { 1473b29376eSWouter van Oortmerssen uint8_t Buffer[W]; 1483b29376eSWouter van Oortmerssen unsigned SizeLen = encodeULEB128(X, Buffer, W); 1493b29376eSWouter van Oortmerssen assert(SizeLen == W); 15019e8befaSSam Clegg Stream.pwrite((char *)Buffer, SizeLen, Offset); 15119e8befaSSam Clegg } 15219e8befaSSam Clegg 15319e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded 15419e8befaSSam Clegg // to allow patching. 1553b29376eSWouter van Oortmerssen template <int W> 1563b29376eSWouter van Oortmerssen void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) { 1573b29376eSWouter van Oortmerssen uint8_t Buffer[W]; 1583b29376eSWouter van Oortmerssen unsigned SizeLen = encodeSLEB128(X, Buffer, W); 1593b29376eSWouter van Oortmerssen assert(SizeLen == W); 16019e8befaSSam Clegg Stream.pwrite((char *)Buffer, SizeLen, Offset); 16119e8befaSSam Clegg } 16219e8befaSSam Clegg 16319e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream. 1640a6c4d8dSSam Clegg static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 16519e8befaSSam Clegg uint8_t Buffer[4]; 16619e8befaSSam Clegg support::endian::write32le(Buffer, X); 16719e8befaSSam Clegg Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 16819e8befaSSam Clegg } 16919e8befaSSam Clegg 1703b29376eSWouter van Oortmerssen static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) { 1713b29376eSWouter van Oortmerssen uint8_t Buffer[8]; 1723b29376eSWouter van Oortmerssen support::endian::write64le(Buffer, X); 1733b29376eSWouter van Oortmerssen Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 1743b29376eSWouter van Oortmerssen } 1753b29376eSWouter van Oortmerssen 1760ff28fa6SDerek Schuff bool isDwoSection(const MCSection &Sec) { 1770ff28fa6SDerek Schuff return Sec.getName().endswith(".dwo"); 1780ff28fa6SDerek Schuff } 1790ff28fa6SDerek Schuff 18018eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter { 1810ff28fa6SDerek Schuff support::endian::Writer *W; 182f17b149dSPeter Collingbourne 18318eafb6cSDan Gohman /// The target specific Wasm writer instance. 18418eafb6cSDan Gohman std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; 18518eafb6cSDan Gohman 186d934cb88SDan Gohman // Relocations for fixing up references in the code section. 187d934cb88SDan Gohman std::vector<WasmRelocationEntry> CodeRelocations; 188d934cb88SDan Gohman // Relocations for fixing up references in the data section. 189d934cb88SDan Gohman std::vector<WasmRelocationEntry> DataRelocations; 190d934cb88SDan Gohman 191d934cb88SDan Gohman // Index values to use for fixing up call_indirect type indices. 192acd7d2b0SSam Clegg // Maps function symbols to the index of the type of the function 193acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices; 194d99f6078SSam Clegg // Maps function symbols to the table element index space. Used 195d99f6078SSam Clegg // for TABLE_INDEX relocation types (i.e. address taken functions). 196f9edbe95SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TableIndices; 197388fb67bSPaulo Matos // Maps function/global/table symbols to the 1981d891d44SHeejin Ahn // function/global/table/tag/section index space. 1996c899ba6SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices; 200492f7529SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices; 2016c899ba6SSam Clegg // Maps data symbols to the Wasm segment and offset/size with the segment. 2026c899ba6SSam Clegg DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations; 2036a31a0d6SSam Clegg 2046a31a0d6SSam Clegg // Stores output data (index, relocations, content offset) for custom 2056a31a0d6SSam Clegg // section. 2066a31a0d6SSam Clegg std::vector<WasmCustomSection> CustomSections; 207cbda16ebSThomas Lively std::unique_ptr<WasmCustomSection> ProducersSection; 208f6f4f843SThomas Lively std::unique_ptr<WasmCustomSection> TargetFeaturesSection; 2096a31a0d6SSam Clegg // Relocations for fixing up references in the custom sections. 2106a31a0d6SSam Clegg DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>> 2116a31a0d6SSam Clegg CustomSectionsRelocations; 212acd7d2b0SSam Clegg 213c0d41195SSam Clegg // Map from section to defining function symbol. 2146ccb59b3SSam Clegg DenseMap<const MCSection *, const MCSymbol *> SectionFunctions; 2156ccb59b3SSam Clegg 2164c41fb5aSHeejin Ahn DenseMap<wasm::WasmSignature, uint32_t> SignatureIndices; 2174c41fb5aSHeejin Ahn SmallVector<wasm::WasmSignature, 4> Signatures; 2186c899ba6SSam Clegg SmallVector<WasmDataSegment, 4> DataSegments; 2199f3fe42eSSam Clegg unsigned NumFunctionImports = 0; 2207c395943SSam Clegg unsigned NumGlobalImports = 0; 221feac819eSAndy Wingo unsigned NumTableImports = 0; 2221d891d44SHeejin Ahn unsigned NumTagImports = 0; 2237e1c3345SChandler Carruth uint32_t SectionCount = 0; 224d934cb88SDan Gohman 2250ff28fa6SDerek Schuff enum class DwoMode { 2260ff28fa6SDerek Schuff AllSections, 2270ff28fa6SDerek Schuff NonDwoOnly, 2280ff28fa6SDerek Schuff DwoOnly, 2290ff28fa6SDerek Schuff }; 2300ff28fa6SDerek Schuff bool IsSplitDwarf = false; 2310ff28fa6SDerek Schuff raw_pwrite_stream *OS = nullptr; 2320ff28fa6SDerek Schuff raw_pwrite_stream *DwoOS = nullptr; 2330ff28fa6SDerek Schuff 2340ff28fa6SDerek Schuff // TargetObjectWriter wranppers. 23518eafb6cSDan Gohman bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 236da84b688SDan Gohman bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); } 23718eafb6cSDan Gohman 2382322a937SSam Clegg void startSection(SectionBookkeeping &Section, unsigned SectionId); 2392322a937SSam Clegg void startCustomSection(SectionBookkeeping &Section, StringRef Name); 240d934cb88SDan Gohman void endSection(SectionBookkeeping &Section); 241d934cb88SDan Gohman 24218eafb6cSDan Gohman public: 2431301a878SLang Hames WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 2440ff28fa6SDerek Schuff raw_pwrite_stream &OS_) 2450ff28fa6SDerek Schuff : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {} 2460ff28fa6SDerek Schuff 2470ff28fa6SDerek Schuff WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 2480ff28fa6SDerek Schuff raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_) 2490ff28fa6SDerek Schuff : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_), 2500ff28fa6SDerek Schuff DwoOS(&DwoOS_) {} 25118eafb6cSDan Gohman 2520917c9e4SDan Gohman private: 253acd7d2b0SSam Clegg void reset() override { 254acd7d2b0SSam Clegg CodeRelocations.clear(); 255acd7d2b0SSam Clegg DataRelocations.clear(); 256acd7d2b0SSam Clegg TypeIndices.clear(); 2576c899ba6SSam Clegg WasmIndices.clear(); 258492f7529SSam Clegg GOTIndices.clear(); 259f9edbe95SSam Clegg TableIndices.clear(); 2606c899ba6SSam Clegg DataLocations.clear(); 261cbda16ebSThomas Lively CustomSections.clear(); 262cbda16ebSThomas Lively ProducersSection.reset(); 263f6f4f843SThomas Lively TargetFeaturesSection.reset(); 2646a31a0d6SSam Clegg CustomSectionsRelocations.clear(); 265da419bdbSHeejin Ahn SignatureIndices.clear(); 266da419bdbSHeejin Ahn Signatures.clear(); 2676c899ba6SSam Clegg DataSegments.clear(); 2686ccb59b3SSam Clegg SectionFunctions.clear(); 2699f3fe42eSSam Clegg NumFunctionImports = 0; 2707c395943SSam Clegg NumGlobalImports = 0; 271feac819eSAndy Wingo NumTableImports = 0; 272105bdc25SSam Clegg MCObjectWriter::reset(); 273acd7d2b0SSam Clegg } 274acd7d2b0SSam Clegg 27518eafb6cSDan Gohman void writeHeader(const MCAssembler &Asm); 27618eafb6cSDan Gohman 27718eafb6cSDan Gohman void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 27818eafb6cSDan Gohman const MCFragment *Fragment, const MCFixup &Fixup, 279ceecfe5bSRafael Espindola MCValue Target, uint64_t &FixedValue) override; 28018eafb6cSDan Gohman 28118eafb6cSDan Gohman void executePostLayoutBinding(MCAssembler &Asm, 28218eafb6cSDan Gohman const MCAsmLayout &Layout) override; 2830ff28fa6SDerek Schuff void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports, 2840ff28fa6SDerek Schuff MCAssembler &Asm, const MCAsmLayout &Layout); 285438390faSPeter Collingbourne uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 2869e15f359SSam Clegg 2870ff28fa6SDerek Schuff uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout, 2880ff28fa6SDerek Schuff DwoMode Mode); 2890ff28fa6SDerek Schuff 290b7787fd0SSam Clegg void writeString(const StringRef Str) { 2910ff28fa6SDerek Schuff encodeULEB128(Str.size(), W->OS); 2920ff28fa6SDerek Schuff W->OS << Str; 293b7787fd0SSam Clegg } 294b7787fd0SSam Clegg 295*1813fde9SYuta Saito void writeStringWithAlignment(const StringRef Str, unsigned Alignment); 296*1813fde9SYuta Saito 2970a6c4d8dSSam Clegg void writeI32(int32_t val) { 2980a6c4d8dSSam Clegg char Buffer[4]; 2990a6c4d8dSSam Clegg support::endian::write32le(Buffer, val); 3000ff28fa6SDerek Schuff W->OS.write(Buffer, sizeof(Buffer)); 3010a6c4d8dSSam Clegg } 3020a6c4d8dSSam Clegg 3030a6c4d8dSSam Clegg void writeI64(int64_t val) { 3040a6c4d8dSSam Clegg char Buffer[8]; 3050a6c4d8dSSam Clegg support::endian::write64le(Buffer, val); 3060ff28fa6SDerek Schuff W->OS.write(Buffer, sizeof(Buffer)); 3070a6c4d8dSSam Clegg } 3080a6c4d8dSSam Clegg 3090ff28fa6SDerek Schuff void writeValueType(wasm::ValType Ty) { W->OS << static_cast<char>(Ty); } 3109e15f359SSam Clegg 3114c41fb5aSHeejin Ahn void writeTypeSection(ArrayRef<wasm::WasmSignature> Signatures); 3124d135b04SWouter van Oortmerssen void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize, 313f950b24aSSam Clegg uint32_t NumElements); 314457fb0b4SSam Clegg void writeFunctionSection(ArrayRef<WasmFunction> Functions); 3158defa952SSam Clegg void writeExportSection(ArrayRef<wasm::WasmExport> Exports); 316a5a3659dSAndy Wingo void writeElemSection(const MCSymbolWasm *IndirectFunctionTable, 317a5a3659dSAndy Wingo ArrayRef<uint32_t> TableElems); 318fef8de66SThomas Lively void writeDataCountSection(); 319e49584a3SSam Clegg uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout, 320457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions); 321e49584a3SSam Clegg uint32_t writeDataSection(const MCAsmLayout &Layout); 3223ec1760dSHeejin Ahn void writeTagSection(ArrayRef<uint32_t> TagTypes); 3230a6c4d8dSSam Clegg void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals); 324388fb67bSPaulo Matos void writeTableSection(ArrayRef<wasm::WasmTable> Tables); 3256f08c84aSSam Clegg void writeRelocSection(uint32_t SectionIndex, StringRef Name, 326f77dc2a8SSam Clegg std::vector<WasmRelocationEntry> &Relocations); 32731a2c809SSam Clegg void writeLinkingMetaDataSection( 32886b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 329ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 330ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats); 331cbda16ebSThomas Lively void writeCustomSection(WasmCustomSection &CustomSection, 332cbda16ebSThomas Lively const MCAssembler &Asm, const MCAsmLayout &Layout); 3336a31a0d6SSam Clegg void writeCustomRelocSections(); 334acd7d2b0SSam Clegg 3357ee758d6SSam Clegg uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry, 3367ee758d6SSam Clegg const MCAsmLayout &Layout); 337acd7d2b0SSam Clegg void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations, 3387ee758d6SSam Clegg uint64_t ContentsOffset, const MCAsmLayout &Layout); 339acd7d2b0SSam Clegg 340acd7d2b0SSam Clegg uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry); 3415e3d33a7SSam Clegg uint32_t getFunctionType(const MCSymbolWasm &Symbol); 3421d891d44SHeejin Ahn uint32_t getTagType(const MCSymbolWasm &Symbol); 34338b12f5eSHeejin Ahn void registerFunctionType(const MCSymbolWasm &Symbol); 3441d891d44SHeejin Ahn void registerTagType(const MCSymbolWasm &Symbol); 34518eafb6cSDan Gohman }; 3469e15f359SSam Clegg 34718eafb6cSDan Gohman } // end anonymous namespace 34818eafb6cSDan Gohman 349d934cb88SDan Gohman // Write out a section header and a patchable section size field. 350d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section, 3512322a937SSam Clegg unsigned SectionId) { 352d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n"); 3530ff28fa6SDerek Schuff W->OS << char(SectionId); 354d934cb88SDan Gohman 3550ff28fa6SDerek Schuff Section.SizeOffset = W->OS.tell(); 356d934cb88SDan Gohman 357d934cb88SDan Gohman // The section size. We don't know the size yet, so reserve enough space 358d934cb88SDan Gohman // for any 32-bit value; we'll patch it later. 3590ff28fa6SDerek Schuff encodeULEB128(0, W->OS, 5); 360d934cb88SDan Gohman 361d934cb88SDan Gohman // The position where the section starts, for measuring its size. 3620ff28fa6SDerek Schuff Section.ContentsOffset = W->OS.tell(); 3630ff28fa6SDerek Schuff Section.PayloadOffset = W->OS.tell(); 3646f08c84aSSam Clegg Section.Index = SectionCount++; 365d934cb88SDan Gohman } 3662322a937SSam Clegg 367*1813fde9SYuta Saito // Write a string with extra paddings for trailing alignment 368*1813fde9SYuta Saito // TODO: support alignment at asm and llvm level? 369*1813fde9SYuta Saito void WasmObjectWriter::writeStringWithAlignment(const StringRef Str, 370*1813fde9SYuta Saito unsigned Alignment) { 371*1813fde9SYuta Saito 372*1813fde9SYuta Saito // Calculate the encoded size of str length and add pads based on it and 373*1813fde9SYuta Saito // alignment. 374*1813fde9SYuta Saito raw_null_ostream NullOS; 375*1813fde9SYuta Saito uint64_t StrSizeLength = encodeULEB128(Str.size(), NullOS); 376*1813fde9SYuta Saito uint64_t Offset = W->OS.tell() + StrSizeLength + Str.size(); 377*1813fde9SYuta Saito uint64_t Paddings = offsetToAlignment(Offset, Align(Alignment)); 378*1813fde9SYuta Saito Offset += Paddings; 379*1813fde9SYuta Saito 380*1813fde9SYuta Saito // LEB128 greater than 5 bytes is invalid 381*1813fde9SYuta Saito assert((StrSizeLength + Paddings) <= 5 && "too long string to align"); 382*1813fde9SYuta Saito 383*1813fde9SYuta Saito encodeSLEB128(Str.size(), W->OS, StrSizeLength + Paddings); 384*1813fde9SYuta Saito W->OS << Str; 385*1813fde9SYuta Saito 386*1813fde9SYuta Saito assert(W->OS.tell() == Offset && "invalid padding"); 387*1813fde9SYuta Saito } 388*1813fde9SYuta Saito 3892322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section, 3902322a937SSam Clegg StringRef Name) { 391d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n"); 3922322a937SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM); 3936a31a0d6SSam Clegg 3946a31a0d6SSam Clegg // The position where the section header ends, for measuring its size. 3950ff28fa6SDerek Schuff Section.PayloadOffset = W->OS.tell(); 3966a31a0d6SSam Clegg 3972322a937SSam Clegg // Custom sections in wasm also have a string identifier. 398*1813fde9SYuta Saito if (Name != "__clangast") { 3992322a937SSam Clegg writeString(Name); 400*1813fde9SYuta Saito } else { 401*1813fde9SYuta Saito // The on-disk hashtable in clangast needs to be aligned by 4 bytes. 402*1813fde9SYuta Saito writeStringWithAlignment(Name, 4); 403*1813fde9SYuta Saito } 4046a31a0d6SSam Clegg 4056a31a0d6SSam Clegg // The position where the custom section starts. 4060ff28fa6SDerek Schuff Section.ContentsOffset = W->OS.tell(); 407d934cb88SDan Gohman } 408d934cb88SDan Gohman 409d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the 410d934cb88SDan Gohman // section size field at the start of the section. 411d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) { 4120ff28fa6SDerek Schuff uint64_t Size = W->OS.tell(); 413c0affde8SSam Clegg // /dev/null doesn't support seek/tell and can report offset of 0. 414c0affde8SSam Clegg // Simply skip this patching in that case. 415c0affde8SSam Clegg if (!Size) 416c0affde8SSam Clegg return; 417c0affde8SSam Clegg 418c0affde8SSam Clegg Size -= Section.PayloadOffset; 419d934cb88SDan Gohman if (uint32_t(Size) != Size) 420d934cb88SDan Gohman report_fatal_error("section size does not fit in a uint32_t"); 421d934cb88SDan Gohman 422d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n"); 423d934cb88SDan Gohman 424d934cb88SDan Gohman // Write the final section size to the payload_len field, which follows 425d934cb88SDan Gohman // the section id byte. 4260ff28fa6SDerek Schuff writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W->OS), Size, 427f17b149dSPeter Collingbourne Section.SizeOffset); 428d934cb88SDan Gohman } 429d934cb88SDan Gohman 43018eafb6cSDan Gohman // Emit the Wasm header. 43118eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { 4320ff28fa6SDerek Schuff W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic)); 4330ff28fa6SDerek Schuff W->write<uint32_t>(wasm::WasmVersion); 43418eafb6cSDan Gohman } 43518eafb6cSDan Gohman 43618eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 43718eafb6cSDan Gohman const MCAsmLayout &Layout) { 4382632ba6aSAndy Wingo // Some compilation units require the indirect function table to be present 4392632ba6aSAndy Wingo // but don't explicitly reference it. This is the case for call_indirect 4402632ba6aSAndy Wingo // without the reference-types feature, and also function bitcasts in all 4412632ba6aSAndy Wingo // cases. In those cases the __indirect_function_table has the 4422632ba6aSAndy Wingo // WASM_SYMBOL_NO_STRIP attribute. Here we make sure this symbol makes it to 4432632ba6aSAndy Wingo // the assembler, if needed. 4442632ba6aSAndy Wingo if (auto *Sym = Asm.getContext().lookupSymbol("__indirect_function_table")) { 4452632ba6aSAndy Wingo const auto *WasmSym = static_cast<const MCSymbolWasm *>(Sym); 4462632ba6aSAndy Wingo if (WasmSym->isNoStrip()) 44796ef4f30SSam Clegg Asm.registerSymbol(*Sym); 4482632ba6aSAndy Wingo } 44996ef4f30SSam Clegg 4506ccb59b3SSam Clegg // Build a map of sections to the function that defines them, for use 4516ccb59b3SSam Clegg // in recordRelocation. 4526ccb59b3SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 4536ccb59b3SSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 4546ccb59b3SSam Clegg if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) { 4556ccb59b3SSam Clegg const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection()); 4566ccb59b3SSam Clegg auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S)); 4576ccb59b3SSam Clegg if (!Pair.second) 4586ccb59b3SSam Clegg report_fatal_error("section already has a defining function: " + 4597d1ff446SFangrui Song Sec.getName()); 4606ccb59b3SSam Clegg } 4616ccb59b3SSam Clegg } 46218eafb6cSDan Gohman } 46318eafb6cSDan Gohman 46418eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 46518eafb6cSDan Gohman const MCAsmLayout &Layout, 46618eafb6cSDan Gohman const MCFragment *Fragment, 46718eafb6cSDan Gohman const MCFixup &Fixup, MCValue Target, 468ceecfe5bSRafael Espindola uint64_t &FixedValue) { 469ecc5e808SSam Clegg // The WebAssembly backend should never generate FKF_IsPCRel fixups 470e828ce1bSFangrui Song assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags & 471ecc5e808SSam Clegg MCFixupKindInfo::FKF_IsPCRel)); 472ecc5e808SSam Clegg 473fe6414b0SSam Clegg const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 474d934cb88SDan Gohman uint64_t C = Target.getConstant(); 475d934cb88SDan Gohman uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 476d934cb88SDan Gohman MCContext &Ctx = Asm.getContext(); 477aa0c571aSYuta Saito bool IsLocRel = false; 478d934cb88SDan Gohman 479d934cb88SDan Gohman if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 480aa0c571aSYuta Saito 481ecc5e808SSam Clegg const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 482aa0c571aSYuta Saito 483aa0c571aSYuta Saito if (FixupSection.getKind().isText()) { 484aa0c571aSYuta Saito Ctx.reportError(Fixup.getLoc(), 485d934cb88SDan Gohman Twine("symbol '") + SymB.getName() + 486aa0c571aSYuta Saito "' unsupported subtraction expression used in " 487aa0c571aSYuta Saito "relocation in code section."); 488d934cb88SDan Gohman return; 489d934cb88SDan Gohman } 490d934cb88SDan Gohman 491aa0c571aSYuta Saito if (SymB.isUndefined()) { 492aa0c571aSYuta Saito Ctx.reportError(Fixup.getLoc(), 493aa0c571aSYuta Saito Twine("symbol '") + SymB.getName() + 494aa0c571aSYuta Saito "' can not be undefined in a subtraction expression"); 495aa0c571aSYuta Saito return; 496aa0c571aSYuta Saito } 497aa0c571aSYuta Saito const MCSection &SecB = SymB.getSection(); 498aa0c571aSYuta Saito if (&SecB != &FixupSection) { 499aa0c571aSYuta Saito Ctx.reportError(Fixup.getLoc(), 500aa0c571aSYuta Saito Twine("symbol '") + SymB.getName() + 501aa0c571aSYuta Saito "' can not be placed in a different section"); 502aa0c571aSYuta Saito return; 503aa0c571aSYuta Saito } 504aa0c571aSYuta Saito IsLocRel = true; 505aa0c571aSYuta Saito C += FixupOffset - Layout.getSymbolOffset(SymB); 506aa0c571aSYuta Saito } 507aa0c571aSYuta Saito 508d934cb88SDan Gohman // We either rejected the fixup or folded B into C at this point. 509d934cb88SDan Gohman const MCSymbolRefExpr *RefA = Target.getSymA(); 510ecc5e808SSam Clegg const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol()); 511d934cb88SDan Gohman 5123ea1c62cSSam Clegg // The .init_array isn't translated as data, so don't do relocations in it. 5137d1ff446SFangrui Song if (FixupSection.getName().startswith(".init_array")) { 5143ea1c62cSSam Clegg SymA->setUsedInInitArray(); 5153ea1c62cSSam Clegg return; 5163ea1c62cSSam Clegg } 5173ea1c62cSSam Clegg 518ecc5e808SSam Clegg if (SymA->isVariable()) { 519d934cb88SDan Gohman const MCExpr *Expr = SymA->getVariableValue(); 5207ee758d6SSam Clegg if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) 5216ad8f190SSam Clegg if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) 5226ad8f190SSam Clegg llvm_unreachable("weakref used in reloc not yet implemented"); 523d934cb88SDan Gohman } 524d934cb88SDan Gohman 525d934cb88SDan Gohman // Put any constant offset in an addend. Offsets can be negative, and 526d934cb88SDan Gohman // LLVM expects wrapping, in contrast to wasm's immediates which can't 527d934cb88SDan Gohman // be negative and don't wrap. 528d934cb88SDan Gohman FixedValue = 0; 529d934cb88SDan Gohman 530ad1f5457SDerek Schuff unsigned Type = 531ad1f5457SDerek Schuff TargetObjectWriter->getRelocType(Target, Fixup, FixupSection, IsLocRel); 5329d24fb7fSSam Clegg 5334d57fbd0SSam Clegg // Absolute offset within a section or a function. 5344d57fbd0SSam Clegg // Currently only supported for for metadata sections. 5354d57fbd0SSam Clegg // See: test/MC/WebAssembly/blockaddress.ll 536ad1f5457SDerek Schuff if ((Type == wasm::R_WASM_FUNCTION_OFFSET_I32 || 53716f02431SWouter van Oortmerssen Type == wasm::R_WASM_FUNCTION_OFFSET_I64 || 538ad1f5457SDerek Schuff Type == wasm::R_WASM_SECTION_OFFSET_I32) && 539ad1f5457SDerek Schuff SymA->isDefined()) { 540ad1f5457SDerek Schuff // SymA can be a temp data symbol that represents a function (in which case 541ad1f5457SDerek Schuff // it needs to be replaced by the section symbol), [XXX and it apparently 542ad1f5457SDerek Schuff // later gets changed again to a func symbol?] or it can be a real 543ad1f5457SDerek Schuff // function symbol, in which case it can be left as-is. 544ad1f5457SDerek Schuff 5454d57fbd0SSam Clegg if (!FixupSection.getKind().isMetadata()) 5464d57fbd0SSam Clegg report_fatal_error("relocations for function or section offsets are " 5474d57fbd0SSam Clegg "only supported in metadata sections"); 5484d57fbd0SSam Clegg 5494d57fbd0SSam Clegg const MCSymbol *SectionSymbol = nullptr; 5504d57fbd0SSam Clegg const MCSection &SecA = SymA->getSection(); 5515e5b2cb1SWouter van Oortmerssen if (SecA.getKind().isText()) { 5525e5b2cb1SWouter van Oortmerssen auto SecSymIt = SectionFunctions.find(&SecA); 5535e5b2cb1SWouter van Oortmerssen if (SecSymIt == SectionFunctions.end()) 5545e5b2cb1SWouter van Oortmerssen report_fatal_error("section doesn\'t have defining symbol"); 5555e5b2cb1SWouter van Oortmerssen SectionSymbol = SecSymIt->second; 5565e5b2cb1SWouter van Oortmerssen } else { 5574d57fbd0SSam Clegg SectionSymbol = SecA.getBeginSymbol(); 5585e5b2cb1SWouter van Oortmerssen } 5594d57fbd0SSam Clegg if (!SectionSymbol) 5604d57fbd0SSam Clegg report_fatal_error("section symbol is required for relocation"); 5614d57fbd0SSam Clegg 5624d57fbd0SSam Clegg C += Layout.getSymbolOffset(*SymA); 5634d57fbd0SSam Clegg SymA = cast<MCSymbolWasm>(SectionSymbol); 5644d57fbd0SSam Clegg } 5654d57fbd0SSam Clegg 566feac819eSAndy Wingo if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB || 5673a293cbfSWouter van Oortmerssen Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64 || 568feac819eSAndy Wingo Type == wasm::R_WASM_TABLE_INDEX_SLEB || 569feac819eSAndy Wingo Type == wasm::R_WASM_TABLE_INDEX_SLEB64 || 570feac819eSAndy Wingo Type == wasm::R_WASM_TABLE_INDEX_I32 || 571feac819eSAndy Wingo Type == wasm::R_WASM_TABLE_INDEX_I64) { 572feac819eSAndy Wingo // TABLE_INDEX relocs implicitly use the default indirect function table. 5732632ba6aSAndy Wingo // We require the function table to have already been defined. 574feac819eSAndy Wingo auto TableName = "__indirect_function_table"; 575feac819eSAndy Wingo MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName)); 576f23b259eSSam Clegg if (!Sym) { 577f23b259eSSam Clegg report_fatal_error("missing indirect function table symbol"); 578feac819eSAndy Wingo } else { 579f23b259eSSam Clegg if (!Sym->isFunctionTable()) 580f23b259eSSam Clegg report_fatal_error("__indirect_function_table symbol has wrong type"); 5812632ba6aSAndy Wingo // Ensure that __indirect_function_table reaches the output. 5822632ba6aSAndy Wingo Sym->setNoStrip(); 5837dc98adbSAndy Wingo Asm.registerSymbol(*Sym); 584861dbe1aSAndy Wingo } 5852632ba6aSAndy Wingo } 586feac819eSAndy Wingo 587d1152a26SSam Clegg // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be 5884d57fbd0SSam Clegg // against a named symbol. 589d1152a26SSam Clegg if (Type != wasm::R_WASM_TYPE_INDEX_LEB) { 5904d57fbd0SSam Clegg if (SymA->getName().empty()) 5914d57fbd0SSam Clegg report_fatal_error("relocations against un-named temporaries are not yet " 5924d57fbd0SSam Clegg "supported by wasm"); 5934d57fbd0SSam Clegg 5944d57fbd0SSam Clegg SymA->setUsedInReloc(); 5954d57fbd0SSam Clegg } 596ae03c1e7SSam Clegg 597ef8c9135SSam Clegg switch (RefA->getKind()) { 598ef8c9135SSam Clegg case MCSymbolRefExpr::VK_GOT: 599ef8c9135SSam Clegg case MCSymbolRefExpr::VK_WASM_GOT_TLS: 600492f7529SSam Clegg SymA->setUsedInGOT(); 601ef8c9135SSam Clegg break; 602ef8c9135SSam Clegg default: 603ef8c9135SSam Clegg break; 604ef8c9135SSam Clegg } 605492f7529SSam Clegg 606d934cb88SDan Gohman WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 607d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 608d934cb88SDan Gohman 6096a31a0d6SSam Clegg if (FixupSection.isWasmData()) { 610d934cb88SDan Gohman DataRelocations.push_back(Rec); 6116a31a0d6SSam Clegg } else if (FixupSection.getKind().isText()) { 61212fd3da9SSam Clegg CodeRelocations.push_back(Rec); 6136a31a0d6SSam Clegg } else if (FixupSection.getKind().isMetadata()) { 6146a31a0d6SSam Clegg CustomSectionsRelocations[&FixupSection].push_back(Rec); 6156a31a0d6SSam Clegg } else { 61612fd3da9SSam Clegg llvm_unreachable("unexpected section type"); 617d934cb88SDan Gohman } 6186a31a0d6SSam Clegg } 619d934cb88SDan Gohman 620d934cb88SDan Gohman // Compute a value to write into the code at the location covered 62160ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves 62260ec3034SSam Clegg // to make the object format more readable and more likely to be directly 62360ec3034SSam Clegg // useable. 6243b29376eSWouter van Oortmerssen uint64_t 6257ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry, 6267ee758d6SSam Clegg const MCAsmLayout &Layout) { 62748139ebcSWouter van Oortmerssen if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB || 62848139ebcSWouter van Oortmerssen RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) && 62948139ebcSWouter van Oortmerssen !RelEntry.Symbol->isGlobal()) { 630492f7529SSam Clegg assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space"); 631492f7529SSam Clegg return GOTIndices[RelEntry.Symbol]; 632492f7529SSam Clegg } 633492f7529SSam Clegg 63460ec3034SSam Clegg switch (RelEntry.Type) { 6352a7cac93SSam Clegg case wasm::R_WASM_TABLE_INDEX_REL_SLEB: 6363a293cbfSWouter van Oortmerssen case wasm::R_WASM_TABLE_INDEX_REL_SLEB64: 637d1152a26SSam Clegg case wasm::R_WASM_TABLE_INDEX_SLEB: 638cc1b9b68SWouter van Oortmerssen case wasm::R_WASM_TABLE_INDEX_SLEB64: 639cc1b9b68SWouter van Oortmerssen case wasm::R_WASM_TABLE_INDEX_I32: 640cc1b9b68SWouter van Oortmerssen case wasm::R_WASM_TABLE_INDEX_I64: { 641f9edbe95SSam Clegg // Provisional value is table address of the resolved symbol itself 6427ee758d6SSam Clegg const MCSymbolWasm *Base = 6437ee758d6SSam Clegg cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol)); 6447ee758d6SSam Clegg assert(Base->isFunction()); 6453a293cbfSWouter van Oortmerssen if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB || 6463a293cbfSWouter van Oortmerssen RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64) 6477ee758d6SSam Clegg return TableIndices[Base] - InitialTableOffset; 64881443ac1SSam Clegg else 6497ee758d6SSam Clegg return TableIndices[Base]; 650f9edbe95SSam Clegg } 651d1152a26SSam Clegg case wasm::R_WASM_TYPE_INDEX_LEB: 6526c899ba6SSam Clegg // Provisional value is same as the index 65360ec3034SSam Clegg return getRelocationIndexValue(RelEntry); 654d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_INDEX_LEB: 655d1152a26SSam Clegg case wasm::R_WASM_GLOBAL_INDEX_LEB: 65648139ebcSWouter van Oortmerssen case wasm::R_WASM_GLOBAL_INDEX_I32: 6571d891d44SHeejin Ahn case wasm::R_WASM_TAG_INDEX_LEB: 65869e2797eSPaulo Matos case wasm::R_WASM_TABLE_NUMBER_LEB: 6591d891d44SHeejin Ahn // Provisional value is function/global/tag Wasm index 660492f7529SSam Clegg assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space"); 6616c899ba6SSam Clegg return WasmIndices[RelEntry.Symbol]; 662d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_OFFSET_I32: 66316f02431SWouter van Oortmerssen case wasm::R_WASM_FUNCTION_OFFSET_I64: 664d1152a26SSam Clegg case wasm::R_WASM_SECTION_OFFSET_I32: { 665ad1f5457SDerek Schuff if (!RelEntry.Symbol->isDefined()) 666ad1f5457SDerek Schuff return 0; 6676a31a0d6SSam Clegg const auto &Section = 6686a31a0d6SSam Clegg static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection()); 6696a31a0d6SSam Clegg return Section.getSectionOffset() + RelEntry.Addend; 6706a31a0d6SSam Clegg } 671d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_LEB: 6723b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_LEB64: 6733b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_SLEB: 6743b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_SLEB64: 6752a7cac93SSam Clegg case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 6763b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64: 6773b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_I32: 678a28a4662SSam Clegg case wasm::R_WASM_MEMORY_ADDR_I64: 679aa0c571aSYuta Saito case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB: 680670944fbSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64: 681aa0c571aSYuta Saito case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32: { 6829c7b5808SDominic Chen // Provisional value is address of the global plus the offset 683270ed1b3SSam Clegg // For undefined symbols, use zero 68401a48535SSam Clegg if (!RelEntry.Symbol->isDefined()) 685270ed1b3SSam Clegg return 0; 68601a48535SSam Clegg const wasm::WasmDataReference &SymRef = DataLocations[RelEntry.Symbol]; 68701a48535SSam Clegg const WasmDataSegment &Segment = DataSegments[SymRef.Segment]; 688d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 68901a48535SSam Clegg return Segment.Offset + SymRef.Offset + RelEntry.Addend; 69060ec3034SSam Clegg } 69160ec3034SSam Clegg default: 69260ec3034SSam Clegg llvm_unreachable("invalid relocation type"); 69360ec3034SSam Clegg } 694d934cb88SDan Gohman } 695d934cb88SDan Gohman 696759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes, 69763ebb813SSam Clegg MCSectionWasm &DataSection) { 6987d1ff446SFangrui Song LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n"); 699759631c7SSam Clegg 70063ebb813SSam Clegg DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 70163ebb813SSam Clegg 702759631c7SSam Clegg for (const MCFragment &Frag : DataSection) { 703759631c7SSam Clegg if (Frag.hasInstructions()) 704759631c7SSam Clegg report_fatal_error("only data supported in data sections"); 705759631c7SSam Clegg 706759631c7SSam Clegg if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 707759631c7SSam Clegg if (Align->getValueSize() != 1) 708759631c7SSam Clegg report_fatal_error("only byte values supported for alignment"); 709759631c7SSam Clegg // If nops are requested, use zeros, as this is the data section. 710759631c7SSam Clegg uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 711f208f631SHeejin Ahn uint64_t Size = 712f208f631SHeejin Ahn std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()), 713f208f631SHeejin Ahn DataBytes.size() + Align->getMaxBytesToEmit()); 714759631c7SSam Clegg DataBytes.resize(Size, Value); 715759631c7SSam Clegg } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 716588fad4dSNirav Dave int64_t NumValues; 717588fad4dSNirav Dave if (!Fill->getNumValues().evaluateAsAbsolute(NumValues)) 718d707c370SRafael Espindola llvm_unreachable("The fill should be an assembler constant"); 719588fad4dSNirav Dave DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues, 720588fad4dSNirav Dave Fill->getValue()); 72124faf859SHeejin Ahn } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) { 72224faf859SHeejin Ahn const SmallVectorImpl<char> &Contents = LEB->getContents(); 7231d0bc055SKazu Hirata llvm::append_range(DataBytes, Contents); 724759631c7SSam Clegg } else { 725759631c7SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 726759631c7SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 7271d0bc055SKazu Hirata llvm::append_range(DataBytes, Contents); 728759631c7SSam Clegg } 729759631c7SSam Clegg } 730759631c7SSam Clegg 731d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 732759631c7SSam Clegg } 733759631c7SSam Clegg 73460ec3034SSam Clegg uint32_t 73560ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) { 736d1152a26SSam Clegg if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) { 737b7787fd0SSam Clegg if (!TypeIndices.count(RelEntry.Symbol)) 738b7787fd0SSam Clegg report_fatal_error("symbol not found in type index space: " + 739b7787fd0SSam Clegg RelEntry.Symbol->getName()); 740acd7d2b0SSam Clegg return TypeIndices[RelEntry.Symbol]; 741acd7d2b0SSam Clegg } 74260ec3034SSam Clegg 74325d8e68bSSam Clegg return RelEntry.Symbol->getIndex(); 744acd7d2b0SSam Clegg } 745acd7d2b0SSam Clegg 746d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 747d934cb88SDan Gohman // directly. 748acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations( 7497ee758d6SSam Clegg ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset, 7507ee758d6SSam Clegg const MCAsmLayout &Layout) { 7510ff28fa6SDerek Schuff auto &Stream = static_cast<raw_pwrite_stream &>(W->OS); 752d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 753d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 754d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 755d934cb88SDan Gohman RelEntry.Offset; 756d934cb88SDan Gohman 757d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 7587ee758d6SSam Clegg auto Value = getProvisionalValue(RelEntry, Layout); 75960ec3034SSam Clegg 760acd7d2b0SSam Clegg switch (RelEntry.Type) { 761d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_INDEX_LEB: 762d1152a26SSam Clegg case wasm::R_WASM_TYPE_INDEX_LEB: 763d1152a26SSam Clegg case wasm::R_WASM_GLOBAL_INDEX_LEB: 764d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_LEB: 7651d891d44SHeejin Ahn case wasm::R_WASM_TAG_INDEX_LEB: 76669e2797eSPaulo Matos case wasm::R_WASM_TABLE_NUMBER_LEB: 7673b29376eSWouter van Oortmerssen writePatchableLEB<5>(Stream, Value, Offset); 7683b29376eSWouter van Oortmerssen break; 7693b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_LEB64: 7703b29376eSWouter van Oortmerssen writePatchableLEB<10>(Stream, Value, Offset); 771d934cb88SDan Gohman break; 772d1152a26SSam Clegg case wasm::R_WASM_TABLE_INDEX_I32: 773d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_I32: 774d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_OFFSET_I32: 775d1152a26SSam Clegg case wasm::R_WASM_SECTION_OFFSET_I32: 77648139ebcSWouter van Oortmerssen case wasm::R_WASM_GLOBAL_INDEX_I32: 777aa0c571aSYuta Saito case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32: 7780a6c4d8dSSam Clegg patchI32(Stream, Value, Offset); 779d934cb88SDan Gohman break; 780cc1b9b68SWouter van Oortmerssen case wasm::R_WASM_TABLE_INDEX_I64: 7813b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_I64: 78216f02431SWouter van Oortmerssen case wasm::R_WASM_FUNCTION_OFFSET_I64: 7833b29376eSWouter van Oortmerssen patchI64(Stream, Value, Offset); 7843b29376eSWouter van Oortmerssen break; 785d1152a26SSam Clegg case wasm::R_WASM_TABLE_INDEX_SLEB: 7862a7cac93SSam Clegg case wasm::R_WASM_TABLE_INDEX_REL_SLEB: 787d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_SLEB: 7882a7cac93SSam Clegg case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 789a28a4662SSam Clegg case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB: 7903b29376eSWouter van Oortmerssen writePatchableSLEB<5>(Stream, Value, Offset); 7913b29376eSWouter van Oortmerssen break; 792cc1b9b68SWouter van Oortmerssen case wasm::R_WASM_TABLE_INDEX_SLEB64: 7933a293cbfSWouter van Oortmerssen case wasm::R_WASM_TABLE_INDEX_REL_SLEB64: 7943b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_SLEB64: 7953b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64: 796670944fbSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64: 7973b29376eSWouter van Oortmerssen writePatchableSLEB<10>(Stream, Value, Offset); 79860ec3034SSam Clegg break; 799d934cb88SDan Gohman default: 8009d24fb7fSSam Clegg llvm_unreachable("invalid relocation type"); 801d934cb88SDan Gohman } 802d934cb88SDan Gohman } 80318eafb6cSDan Gohman } 80418eafb6cSDan Gohman 8054c41fb5aSHeejin Ahn void WasmObjectWriter::writeTypeSection( 8064c41fb5aSHeejin Ahn ArrayRef<wasm::WasmSignature> Signatures) { 807da419bdbSHeejin Ahn if (Signatures.empty()) 8089e15f359SSam Clegg return; 8099e15f359SSam Clegg 8109e15f359SSam Clegg SectionBookkeeping Section; 8119e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TYPE); 8129e15f359SSam Clegg 8130ff28fa6SDerek Schuff encodeULEB128(Signatures.size(), W->OS); 8149e15f359SSam Clegg 8154c41fb5aSHeejin Ahn for (const wasm::WasmSignature &Sig : Signatures) { 8160ff28fa6SDerek Schuff W->OS << char(wasm::WASM_TYPE_FUNC); 8170ff28fa6SDerek Schuff encodeULEB128(Sig.Params.size(), W->OS); 818da419bdbSHeejin Ahn for (wasm::ValType Ty : Sig.Params) 8199e15f359SSam Clegg writeValueType(Ty); 8200ff28fa6SDerek Schuff encodeULEB128(Sig.Returns.size(), W->OS); 821da419bdbSHeejin Ahn for (wasm::ValType Ty : Sig.Returns) 8229e15f359SSam Clegg writeValueType(Ty); 8239e15f359SSam Clegg } 8249e15f359SSam Clegg 8259e15f359SSam Clegg endSection(Section); 8269e15f359SSam Clegg } 8279e15f359SSam Clegg 8288defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports, 8294d135b04SWouter van Oortmerssen uint64_t DataSize, 830f950b24aSSam Clegg uint32_t NumElements) { 8319e15f359SSam Clegg if (Imports.empty()) 8329e15f359SSam Clegg return; 8339e15f359SSam Clegg 8344d135b04SWouter van Oortmerssen uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 835f950b24aSSam Clegg 8369e15f359SSam Clegg SectionBookkeeping Section; 8379e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_IMPORT); 8389e15f359SSam Clegg 8390ff28fa6SDerek Schuff encodeULEB128(Imports.size(), W->OS); 8408defa952SSam Clegg for (const wasm::WasmImport &Import : Imports) { 8418defa952SSam Clegg writeString(Import.Module); 8428defa952SSam Clegg writeString(Import.Field); 8430ff28fa6SDerek Schuff W->OS << char(Import.Kind); 8449e15f359SSam Clegg 8459e15f359SSam Clegg switch (Import.Kind) { 8469e15f359SSam Clegg case wasm::WASM_EXTERNAL_FUNCTION: 8470ff28fa6SDerek Schuff encodeULEB128(Import.SigIndex, W->OS); 8489e15f359SSam Clegg break; 8499e15f359SSam Clegg case wasm::WASM_EXTERNAL_GLOBAL: 8500ff28fa6SDerek Schuff W->OS << char(Import.Global.Type); 8510ff28fa6SDerek Schuff W->OS << char(Import.Global.Mutable ? 1 : 0); 8529e15f359SSam Clegg break; 853f950b24aSSam Clegg case wasm::WASM_EXTERNAL_MEMORY: 8540ff28fa6SDerek Schuff encodeULEB128(Import.Memory.Flags, W->OS); 8550ff28fa6SDerek Schuff encodeULEB128(NumPages, W->OS); // initial 856f950b24aSSam Clegg break; 857f950b24aSSam Clegg case wasm::WASM_EXTERNAL_TABLE: 8580ff28fa6SDerek Schuff W->OS << char(Import.Table.ElemType); 8590ff28fa6SDerek Schuff encodeULEB128(0, W->OS); // flags 8600ff28fa6SDerek Schuff encodeULEB128(NumElements, W->OS); // initial 861f950b24aSSam Clegg break; 8621d891d44SHeejin Ahn case wasm::WASM_EXTERNAL_TAG: 8633ec1760dSHeejin Ahn W->OS << char(0); // Reserved 'attribute' field 8643ec1760dSHeejin Ahn encodeULEB128(Import.SigIndex, W->OS); 865da419bdbSHeejin Ahn break; 8669e15f359SSam Clegg default: 8679e15f359SSam Clegg llvm_unreachable("unsupported import kind"); 8689e15f359SSam Clegg } 8699e15f359SSam Clegg } 8709e15f359SSam Clegg 8719e15f359SSam Clegg endSection(Section); 8729e15f359SSam Clegg } 8739e15f359SSam Clegg 874457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 8759e15f359SSam Clegg if (Functions.empty()) 8769e15f359SSam Clegg return; 8779e15f359SSam Clegg 8789e15f359SSam Clegg SectionBookkeeping Section; 8799e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_FUNCTION); 8809e15f359SSam Clegg 8810ff28fa6SDerek Schuff encodeULEB128(Functions.size(), W->OS); 8829e15f359SSam Clegg for (const WasmFunction &Func : Functions) 8830ff28fa6SDerek Schuff encodeULEB128(Func.SigIndex, W->OS); 8849e15f359SSam Clegg 8859e15f359SSam Clegg endSection(Section); 8869e15f359SSam Clegg } 8879e15f359SSam Clegg 8883ec1760dSHeejin Ahn void WasmObjectWriter::writeTagSection(ArrayRef<uint32_t> TagTypes) { 8893ec1760dSHeejin Ahn if (TagTypes.empty()) 890da419bdbSHeejin Ahn return; 891da419bdbSHeejin Ahn 892da419bdbSHeejin Ahn SectionBookkeeping Section; 8931d891d44SHeejin Ahn startSection(Section, wasm::WASM_SEC_TAG); 894da419bdbSHeejin Ahn 8953ec1760dSHeejin Ahn encodeULEB128(TagTypes.size(), W->OS); 8963ec1760dSHeejin Ahn for (uint32_t Index : TagTypes) { 8973ec1760dSHeejin Ahn W->OS << char(0); // Reserved 'attribute' field 8983ec1760dSHeejin Ahn encodeULEB128(Index, W->OS); 899da419bdbSHeejin Ahn } 900da419bdbSHeejin Ahn 901da419bdbSHeejin Ahn endSection(Section); 902da419bdbSHeejin Ahn } 903da419bdbSHeejin Ahn 9040a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) { 9050a6c4d8dSSam Clegg if (Globals.empty()) 9060a6c4d8dSSam Clegg return; 9070a6c4d8dSSam Clegg 9080a6c4d8dSSam Clegg SectionBookkeeping Section; 9090a6c4d8dSSam Clegg startSection(Section, wasm::WASM_SEC_GLOBAL); 9100a6c4d8dSSam Clegg 9110ff28fa6SDerek Schuff encodeULEB128(Globals.size(), W->OS); 9120a6c4d8dSSam Clegg for (const wasm::WasmGlobal &Global : Globals) { 9130ff28fa6SDerek Schuff encodeULEB128(Global.Type.Type, W->OS); 9140ff28fa6SDerek Schuff W->OS << char(Global.Type.Mutable); 9150ff28fa6SDerek Schuff W->OS << char(Global.InitExpr.Opcode); 9160a6c4d8dSSam Clegg switch (Global.Type.Type) { 9170a6c4d8dSSam Clegg case wasm::WASM_TYPE_I32: 9180ff28fa6SDerek Schuff encodeSLEB128(0, W->OS); 9190a6c4d8dSSam Clegg break; 9200a6c4d8dSSam Clegg case wasm::WASM_TYPE_I64: 9210ff28fa6SDerek Schuff encodeSLEB128(0, W->OS); 9220a6c4d8dSSam Clegg break; 9230a6c4d8dSSam Clegg case wasm::WASM_TYPE_F32: 9240a6c4d8dSSam Clegg writeI32(0); 9250a6c4d8dSSam Clegg break; 9260a6c4d8dSSam Clegg case wasm::WASM_TYPE_F64: 9270a6c4d8dSSam Clegg writeI64(0); 9280a6c4d8dSSam Clegg break; 92979aad89dSSam Clegg case wasm::WASM_TYPE_EXTERNREF: 93079aad89dSSam Clegg writeValueType(wasm::ValType::EXTERNREF); 93179aad89dSSam Clegg break; 9320a6c4d8dSSam Clegg default: 9330a6c4d8dSSam Clegg llvm_unreachable("unexpected type"); 9340a6c4d8dSSam Clegg } 9350ff28fa6SDerek Schuff W->OS << char(wasm::WASM_OPCODE_END); 9360a6c4d8dSSam Clegg } 9370a6c4d8dSSam Clegg 9380a6c4d8dSSam Clegg endSection(Section); 9390a6c4d8dSSam Clegg } 9400a6c4d8dSSam Clegg 941388fb67bSPaulo Matos void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) { 942388fb67bSPaulo Matos if (Tables.empty()) 943388fb67bSPaulo Matos return; 944388fb67bSPaulo Matos 945388fb67bSPaulo Matos SectionBookkeeping Section; 946388fb67bSPaulo Matos startSection(Section, wasm::WASM_SEC_TABLE); 947388fb67bSPaulo Matos 948388fb67bSPaulo Matos encodeULEB128(Tables.size(), W->OS); 949388fb67bSPaulo Matos for (const wasm::WasmTable &Table : Tables) { 9501933c9d4SAndy Wingo encodeULEB128(Table.Type.ElemType, W->OS); 9511933c9d4SAndy Wingo encodeULEB128(Table.Type.Limits.Flags, W->OS); 9529ac5620cSAndy Wingo encodeULEB128(Table.Type.Limits.Minimum, W->OS); 9531933c9d4SAndy Wingo if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX) 9541933c9d4SAndy Wingo encodeULEB128(Table.Type.Limits.Maximum, W->OS); 955388fb67bSPaulo Matos } 956388fb67bSPaulo Matos endSection(Section); 957388fb67bSPaulo Matos } 958388fb67bSPaulo Matos 9598defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) { 9609e15f359SSam Clegg if (Exports.empty()) 9619e15f359SSam Clegg return; 9629e15f359SSam Clegg 9639e15f359SSam Clegg SectionBookkeeping Section; 9649e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_EXPORT); 9659e15f359SSam Clegg 9660ff28fa6SDerek Schuff encodeULEB128(Exports.size(), W->OS); 9678defa952SSam Clegg for (const wasm::WasmExport &Export : Exports) { 9688defa952SSam Clegg writeString(Export.Name); 9690ff28fa6SDerek Schuff W->OS << char(Export.Kind); 9700ff28fa6SDerek Schuff encodeULEB128(Export.Index, W->OS); 9719e15f359SSam Clegg } 9729e15f359SSam Clegg 9739e15f359SSam Clegg endSection(Section); 9749e15f359SSam Clegg } 9759e15f359SSam Clegg 976a5a3659dSAndy Wingo void WasmObjectWriter::writeElemSection( 977a5a3659dSAndy Wingo const MCSymbolWasm *IndirectFunctionTable, ArrayRef<uint32_t> TableElems) { 9789e15f359SSam Clegg if (TableElems.empty()) 9799e15f359SSam Clegg return; 9809e15f359SSam Clegg 981a5a3659dSAndy Wingo assert(IndirectFunctionTable); 982a5a3659dSAndy Wingo 9839e15f359SSam Clegg SectionBookkeeping Section; 9849e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_ELEM); 9859e15f359SSam Clegg 9860ff28fa6SDerek Schuff encodeULEB128(1, W->OS); // number of "segments" 987a5a3659dSAndy Wingo 988a5a3659dSAndy Wingo assert(WasmIndices.count(IndirectFunctionTable)); 989a5a3659dSAndy Wingo uint32_t TableNumber = WasmIndices.find(IndirectFunctionTable)->second; 990a5a3659dSAndy Wingo uint32_t Flags = 0; 991a5a3659dSAndy Wingo if (TableNumber) 992a5a3659dSAndy Wingo Flags |= wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER; 993a5a3659dSAndy Wingo encodeULEB128(Flags, W->OS); 994a5a3659dSAndy Wingo if (Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER) 995a5a3659dSAndy Wingo encodeULEB128(TableNumber, W->OS); // the table number 9969e15f359SSam Clegg 9979e15f359SSam Clegg // init expr for starting offset 9980ff28fa6SDerek Schuff W->OS << char(wasm::WASM_OPCODE_I32_CONST); 9990ff28fa6SDerek Schuff encodeSLEB128(InitialTableOffset, W->OS); 10000ff28fa6SDerek Schuff W->OS << char(wasm::WASM_OPCODE_END); 10019e15f359SSam Clegg 1002a5a3659dSAndy Wingo if (Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) { 1003a5a3659dSAndy Wingo // We only write active function table initializers, for which the elem kind 1004a5a3659dSAndy Wingo // is specified to be written as 0x00 and interpreted to mean "funcref". 1005a5a3659dSAndy Wingo const uint8_t ElemKind = 0; 1006a5a3659dSAndy Wingo W->OS << ElemKind; 1007a5a3659dSAndy Wingo } 1008a5a3659dSAndy Wingo 10090ff28fa6SDerek Schuff encodeULEB128(TableElems.size(), W->OS); 10109e15f359SSam Clegg for (uint32_t Elem : TableElems) 10110ff28fa6SDerek Schuff encodeULEB128(Elem, W->OS); 10129e15f359SSam Clegg 10139e15f359SSam Clegg endSection(Section); 10149e15f359SSam Clegg } 10159e15f359SSam Clegg 1016fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() { 1017fef8de66SThomas Lively if (DataSegments.empty()) 1018fef8de66SThomas Lively return; 1019fef8de66SThomas Lively 1020fef8de66SThomas Lively SectionBookkeeping Section; 1021fef8de66SThomas Lively startSection(Section, wasm::WASM_SEC_DATACOUNT); 10220ff28fa6SDerek Schuff encodeULEB128(DataSegments.size(), W->OS); 1023fef8de66SThomas Lively endSection(Section); 1024fef8de66SThomas Lively } 1025fef8de66SThomas Lively 1026e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 1027457fb0b4SSam Clegg const MCAsmLayout &Layout, 1028457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions) { 10299e15f359SSam Clegg if (Functions.empty()) 1030e49584a3SSam Clegg return 0; 10319e15f359SSam Clegg 10329e15f359SSam Clegg SectionBookkeeping Section; 10339e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CODE); 10349e15f359SSam Clegg 10350ff28fa6SDerek Schuff encodeULEB128(Functions.size(), W->OS); 10369e15f359SSam Clegg 10379e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 1038fe6414b0SSam Clegg auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 10399e15f359SSam Clegg 10409e15f359SSam Clegg int64_t Size = 0; 10419e15f359SSam Clegg if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 10429e15f359SSam Clegg report_fatal_error(".size expression must be evaluatable"); 10439e15f359SSam Clegg 10440ff28fa6SDerek Schuff encodeULEB128(Size, W->OS); 10450ff28fa6SDerek Schuff FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset); 10460ff28fa6SDerek Schuff Asm.writeSectionData(W->OS, &FuncSection, Layout); 10479e15f359SSam Clegg } 10489e15f359SSam Clegg 10499e15f359SSam Clegg // Apply fixups. 10507ee758d6SSam Clegg applyRelocations(CodeRelocations, Section.ContentsOffset, Layout); 10519e15f359SSam Clegg 10529e15f359SSam Clegg endSection(Section); 1053e49584a3SSam Clegg return Section.Index; 10549e15f359SSam Clegg } 10559e15f359SSam Clegg 1056e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) { 10576c899ba6SSam Clegg if (DataSegments.empty()) 1058e49584a3SSam Clegg return 0; 10599e15f359SSam Clegg 10609e15f359SSam Clegg SectionBookkeeping Section; 10619e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_DATA); 10629e15f359SSam Clegg 10630ff28fa6SDerek Schuff encodeULEB128(DataSegments.size(), W->OS); // count 10647c395943SSam Clegg 10656c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 10660ff28fa6SDerek Schuff encodeULEB128(Segment.InitFlags, W->OS); // flags 1067831a143eSAndy Wingo if (Segment.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX) 10680ff28fa6SDerek Schuff encodeULEB128(0, W->OS); // memory index 1069831a143eSAndy Wingo if ((Segment.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) { 10700d9b17d0SWouter van Oortmerssen W->OS << char(is64Bit() ? wasm::WASM_OPCODE_I64_CONST 10714d135b04SWouter van Oortmerssen : wasm::WASM_OPCODE_I32_CONST); 10720ff28fa6SDerek Schuff encodeSLEB128(Segment.Offset, W->OS); // offset 10730ff28fa6SDerek Schuff W->OS << char(wasm::WASM_OPCODE_END); 10742e150409SThomas Lively } 10750ff28fa6SDerek Schuff encodeULEB128(Segment.Data.size(), W->OS); // size 10760ff28fa6SDerek Schuff Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset); 10770ff28fa6SDerek Schuff W->OS << Segment.Data; // data 10787c395943SSam Clegg } 10799e15f359SSam Clegg 10809e15f359SSam Clegg // Apply fixups. 10817ee758d6SSam Clegg applyRelocations(DataRelocations, Section.ContentsOffset, Layout); 10829e15f359SSam Clegg 10839e15f359SSam Clegg endSection(Section); 1084e49584a3SSam Clegg return Section.Index; 10859e15f359SSam Clegg } 10869e15f359SSam Clegg 10876f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection( 10886f08c84aSSam Clegg uint32_t SectionIndex, StringRef Name, 1089f77dc2a8SSam Clegg std::vector<WasmRelocationEntry> &Relocs) { 10909e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 10919e15f359SSam Clegg // for descriptions of the reloc sections. 10929e15f359SSam Clegg 1093f77dc2a8SSam Clegg if (Relocs.empty()) 10949e15f359SSam Clegg return; 10959e15f359SSam Clegg 1096f77dc2a8SSam Clegg // First, ensure the relocations are sorted in offset order. In general they 1097f77dc2a8SSam Clegg // should already be sorted since `recordRelocation` is called in offset 1098f77dc2a8SSam Clegg // order, but for the code section we combine many MC sections into single 1099f77dc2a8SSam Clegg // wasm section, and this order is determined by the order of Asm.Symbols() 1100f77dc2a8SSam Clegg // not the sections order. 1101efd94c56SFangrui Song llvm::stable_sort( 1102efd94c56SFangrui Song Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) { 1103f77dc2a8SSam Clegg return (A.Offset + A.FixupSection->getSectionOffset()) < 1104f77dc2a8SSam Clegg (B.Offset + B.FixupSection->getSectionOffset()); 1105f77dc2a8SSam Clegg }); 1106f77dc2a8SSam Clegg 11079e15f359SSam Clegg SectionBookkeeping Section; 11086f08c84aSSam Clegg startCustomSection(Section, std::string("reloc.") + Name.str()); 11099e15f359SSam Clegg 11100ff28fa6SDerek Schuff encodeULEB128(SectionIndex, W->OS); 11110ff28fa6SDerek Schuff encodeULEB128(Relocs.size(), W->OS); 1112f77dc2a8SSam Clegg for (const WasmRelocationEntry &RelEntry : Relocs) { 1113f208f631SHeejin Ahn uint64_t Offset = 1114f208f631SHeejin Ahn RelEntry.Offset + RelEntry.FixupSection->getSectionOffset(); 11156f08c84aSSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 11169e15f359SSam Clegg 11170ff28fa6SDerek Schuff W->OS << char(RelEntry.Type); 11180ff28fa6SDerek Schuff encodeULEB128(Offset, W->OS); 11190ff28fa6SDerek Schuff encodeULEB128(Index, W->OS); 11206f08c84aSSam Clegg if (RelEntry.hasAddend()) 11210ff28fa6SDerek Schuff encodeSLEB128(RelEntry.Addend, W->OS); 11229e15f359SSam Clegg } 11239e15f359SSam Clegg 11249e15f359SSam Clegg endSection(Section); 11259e15f359SSam Clegg } 11269e15f359SSam Clegg 11276a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() { 11286a31a0d6SSam Clegg for (const auto &Sec : CustomSections) { 11296a31a0d6SSam Clegg auto &Relocations = CustomSectionsRelocations[Sec.Section]; 11306a31a0d6SSam Clegg writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations); 11316a31a0d6SSam Clegg } 11326a31a0d6SSam Clegg } 11336a31a0d6SSam Clegg 11349e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection( 113586b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 1136ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 1137ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) { 11389e15f359SSam Clegg SectionBookkeeping Section; 11392322a937SSam Clegg startCustomSection(Section, "linking"); 11400ff28fa6SDerek Schuff encodeULEB128(wasm::WasmMetadataVersion, W->OS); 11419e15f359SSam Clegg 11426bb5a41fSSam Clegg SectionBookkeeping SubSection; 11436c899ba6SSam Clegg if (SymbolInfos.size() != 0) { 11446c899ba6SSam Clegg startSection(SubSection, wasm::WASM_SYMBOL_TABLE); 11450ff28fa6SDerek Schuff encodeULEB128(SymbolInfos.size(), W->OS); 11466c899ba6SSam Clegg for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) { 11470ff28fa6SDerek Schuff encodeULEB128(Sym.Kind, W->OS); 11480ff28fa6SDerek Schuff encodeULEB128(Sym.Flags, W->OS); 11496c899ba6SSam Clegg switch (Sym.Kind) { 11506c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_FUNCTION: 11516c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_GLOBAL: 11521d891d44SHeejin Ahn case wasm::WASM_SYMBOL_TYPE_TAG: 1153388fb67bSPaulo Matos case wasm::WASM_SYMBOL_TYPE_TABLE: 11540ff28fa6SDerek Schuff encodeULEB128(Sym.ElementIndex, W->OS); 115529874ceaSDan Gohman if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 || 115629874ceaSDan Gohman (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) 11576c899ba6SSam Clegg writeString(Sym.Name); 11586c899ba6SSam Clegg break; 11596c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_DATA: 11606c899ba6SSam Clegg writeString(Sym.Name); 11616c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) { 11620ff28fa6SDerek Schuff encodeULEB128(Sym.DataRef.Segment, W->OS); 11630ff28fa6SDerek Schuff encodeULEB128(Sym.DataRef.Offset, W->OS); 11640ff28fa6SDerek Schuff encodeULEB128(Sym.DataRef.Size, W->OS); 11656c899ba6SSam Clegg } 11666c899ba6SSam Clegg break; 11676a31a0d6SSam Clegg case wasm::WASM_SYMBOL_TYPE_SECTION: { 11686a31a0d6SSam Clegg const uint32_t SectionIndex = 11696a31a0d6SSam Clegg CustomSections[Sym.ElementIndex].OutputIndex; 11700ff28fa6SDerek Schuff encodeULEB128(SectionIndex, W->OS); 11716a31a0d6SSam Clegg break; 11726a31a0d6SSam Clegg } 11736c899ba6SSam Clegg default: 11746c899ba6SSam Clegg llvm_unreachable("unexpected kind"); 11756c899ba6SSam Clegg } 1176b7787fd0SSam Clegg } 1177b7787fd0SSam Clegg endSection(SubSection); 1178b7787fd0SSam Clegg } 11799e15f359SSam Clegg 11806c899ba6SSam Clegg if (DataSegments.size()) { 118163ebb813SSam Clegg startSection(SubSection, wasm::WASM_SEGMENT_INFO); 11820ff28fa6SDerek Schuff encodeULEB128(DataSegments.size(), W->OS); 11836c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 1184d95ed959SSam Clegg writeString(Segment.Name); 11850ff28fa6SDerek Schuff encodeULEB128(Segment.Alignment, W->OS); 11863b8d2be5SSam Clegg encodeULEB128(Segment.LinkingFlags, W->OS); 118763ebb813SSam Clegg } 1188d95ed959SSam Clegg endSection(SubSection); 1189d95ed959SSam Clegg } 1190d95ed959SSam Clegg 1191bafe6902SSam Clegg if (!InitFuncs.empty()) { 1192bafe6902SSam Clegg startSection(SubSection, wasm::WASM_INIT_FUNCS); 11930ff28fa6SDerek Schuff encodeULEB128(InitFuncs.size(), W->OS); 1194bafe6902SSam Clegg for (auto &StartFunc : InitFuncs) { 11950ff28fa6SDerek Schuff encodeULEB128(StartFunc.first, W->OS); // priority 11960ff28fa6SDerek Schuff encodeULEB128(StartFunc.second, W->OS); // function index 1197bafe6902SSam Clegg } 1198bafe6902SSam Clegg endSection(SubSection); 1199bafe6902SSam Clegg } 1200bafe6902SSam Clegg 1201ea7caceeSSam Clegg if (Comdats.size()) { 1202ea7caceeSSam Clegg startSection(SubSection, wasm::WASM_COMDAT_INFO); 12030ff28fa6SDerek Schuff encodeULEB128(Comdats.size(), W->OS); 1204ea7caceeSSam Clegg for (const auto &C : Comdats) { 1205ea7caceeSSam Clegg writeString(C.first); 12060ff28fa6SDerek Schuff encodeULEB128(0, W->OS); // flags for future use 12070ff28fa6SDerek Schuff encodeULEB128(C.second.size(), W->OS); 1208ea7caceeSSam Clegg for (const WasmComdatEntry &Entry : C.second) { 12090ff28fa6SDerek Schuff encodeULEB128(Entry.Kind, W->OS); 12100ff28fa6SDerek Schuff encodeULEB128(Entry.Index, W->OS); 1211ea7caceeSSam Clegg } 1212ea7caceeSSam Clegg } 1213ea7caceeSSam Clegg endSection(SubSection); 1214ea7caceeSSam Clegg } 1215ea7caceeSSam Clegg 12169e15f359SSam Clegg endSection(Section); 12179e15f359SSam Clegg } 12189e15f359SSam Clegg 1219cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection, 1220cbda16ebSThomas Lively const MCAssembler &Asm, 12216a31a0d6SSam Clegg const MCAsmLayout &Layout) { 1222cfd44a2eSSam Clegg SectionBookkeeping Section; 12236a31a0d6SSam Clegg auto *Sec = CustomSection.Section; 12242322a937SSam Clegg startCustomSection(Section, CustomSection.Name); 12256a31a0d6SSam Clegg 12260ff28fa6SDerek Schuff Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset); 12270ff28fa6SDerek Schuff Asm.writeSectionData(W->OS, Sec, Layout); 12286a31a0d6SSam Clegg 12296a31a0d6SSam Clegg CustomSection.OutputContentsOffset = Section.ContentsOffset; 12306a31a0d6SSam Clegg CustomSection.OutputIndex = Section.Index; 12316a31a0d6SSam Clegg 1232cfd44a2eSSam Clegg endSection(Section); 12336a31a0d6SSam Clegg 12346a31a0d6SSam Clegg // Apply fixups. 12354d57fbd0SSam Clegg auto &Relocations = CustomSectionsRelocations[CustomSection.Section]; 12367ee758d6SSam Clegg applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout); 12376a31a0d6SSam Clegg } 12386a31a0d6SSam Clegg 12395e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) { 12405e3d33a7SSam Clegg assert(Symbol.isFunction()); 12415e3d33a7SSam Clegg assert(TypeIndices.count(&Symbol)); 12425e3d33a7SSam Clegg return TypeIndices[&Symbol]; 12435e3d33a7SSam Clegg } 12445e3d33a7SSam Clegg 12451d891d44SHeejin Ahn uint32_t WasmObjectWriter::getTagType(const MCSymbolWasm &Symbol) { 12461d891d44SHeejin Ahn assert(Symbol.isTag()); 1247da419bdbSHeejin Ahn assert(TypeIndices.count(&Symbol)); 1248da419bdbSHeejin Ahn return TypeIndices[&Symbol]; 1249da419bdbSHeejin Ahn } 1250da419bdbSHeejin Ahn 125138b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) { 12525e3d33a7SSam Clegg assert(Symbol.isFunction()); 12535e3d33a7SSam Clegg 12544c41fb5aSHeejin Ahn wasm::WasmSignature S; 12557ee758d6SSam Clegg 12567ee758d6SSam Clegg if (auto *Sig = Symbol.getSignature()) { 1257da419bdbSHeejin Ahn S.Returns = Sig->Returns; 1258da419bdbSHeejin Ahn S.Params = Sig->Params; 125977a7a380SDerek Schuff } 12605e3d33a7SSam Clegg 1261da419bdbSHeejin Ahn auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 12625e3d33a7SSam Clegg if (Pair.second) 1263da419bdbSHeejin Ahn Signatures.push_back(S); 12645e3d33a7SSam Clegg TypeIndices[&Symbol] = Pair.first->second; 12655e3d33a7SSam Clegg 1266d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol 1267d34e60caSNicola Zaghen << " new:" << Pair.second << "\n"); 1268d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 12695e3d33a7SSam Clegg } 12705e3d33a7SSam Clegg 12711d891d44SHeejin Ahn void WasmObjectWriter::registerTagType(const MCSymbolWasm &Symbol) { 12721d891d44SHeejin Ahn assert(Symbol.isTag()); 1273da419bdbSHeejin Ahn 1274da419bdbSHeejin Ahn // TODO Currently we don't generate imported exceptions, but if we do, we 1275da419bdbSHeejin Ahn // should have a way of infering types of imported exceptions. 12764c41fb5aSHeejin Ahn wasm::WasmSignature S; 1277da419bdbSHeejin Ahn if (auto *Sig = Symbol.getSignature()) { 1278da419bdbSHeejin Ahn S.Returns = Sig->Returns; 1279da419bdbSHeejin Ahn S.Params = Sig->Params; 1280da419bdbSHeejin Ahn } 1281da419bdbSHeejin Ahn 1282da419bdbSHeejin Ahn auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 1283da419bdbSHeejin Ahn if (Pair.second) 1284da419bdbSHeejin Ahn Signatures.push_back(S); 1285da419bdbSHeejin Ahn TypeIndices[&Symbol] = Pair.first->second; 1286da419bdbSHeejin Ahn 12871d891d44SHeejin Ahn LLVM_DEBUG(dbgs() << "registerTagType: " << Symbol << " new:" << Pair.second 1288da419bdbSHeejin Ahn << "\n"); 1289da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 1290da419bdbSHeejin Ahn } 1291da419bdbSHeejin Ahn 12924d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) { 12933ea1c62cSSam Clegg if (Sym.isUsedInReloc() || Sym.isUsedInInitArray()) 12944d57fbd0SSam Clegg return true; 12954d57fbd0SSam Clegg 12964d57fbd0SSam Clegg if (Sym.isComdat() && !Sym.isDefined()) 12974d57fbd0SSam Clegg return false; 12984d57fbd0SSam Clegg 12993ea1c62cSSam Clegg if (Sym.isTemporary()) 13004d57fbd0SSam Clegg return false; 13014d57fbd0SSam Clegg 13024d57fbd0SSam Clegg if (Sym.isSection()) 13034d57fbd0SSam Clegg return false; 13044d57fbd0SSam Clegg 13052632ba6aSAndy Wingo if (Sym.omitFromLinkingSection()) 13062632ba6aSAndy Wingo return false; 13072632ba6aSAndy Wingo 13084d57fbd0SSam Clegg return true; 13094d57fbd0SSam Clegg } 131030d314aaSSam Clegg 13110ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports( 13120ff28fa6SDerek Schuff SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm, 131318eafb6cSDan Gohman const MCAsmLayout &Layout) { 1314f950b24aSSam Clegg // For now, always emit the memory import, since loads and stores are not 1315f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1316f950b24aSSam Clegg // it if there are no loads or stores. 13178defa952SSam Clegg wasm::WasmImport MemImport; 13181ed3a046SSam Clegg MemImport.Module = "env"; 13191ed3a046SSam Clegg MemImport.Field = "__linear_memory"; 1320f950b24aSSam Clegg MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1321fd0964aeSWouter van Oortmerssen MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64 1322fd0964aeSWouter van Oortmerssen : wasm::WASM_LIMITS_FLAG_NONE; 1323f950b24aSSam Clegg Imports.push_back(MemImport); 1324f950b24aSSam Clegg 1325da419bdbSHeejin Ahn // Populate SignatureIndices, and Imports and WasmIndices for undefined 1326586320c0SNicholas Wilson // symbols. This must be done before populating WasmIndices for defined 1327586320c0SNicholas Wilson // symbols. 132832ce5ca0SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 132932ce5ca0SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 133032ce5ca0SDan Gohman 133132ce5ca0SDan Gohman // Register types for all functions, including those with private linkage 13329f3fe42eSSam Clegg // (because wasm always needs a type signature). 13337ee758d6SSam Clegg if (WS.isFunction()) { 13349c7b5808SDominic Chen const auto *BS = Layout.getBaseSymbol(S); 13359c7b5808SDominic Chen if (!BS) 13369c7b5808SDominic Chen report_fatal_error(Twine(S.getName()) + 13379c7b5808SDominic Chen ": absolute addressing not supported!"); 13389c7b5808SDominic Chen registerFunctionType(*cast<MCSymbolWasm>(BS)); 13397ee758d6SSam Clegg } 134032ce5ca0SDan Gohman 13411d891d44SHeejin Ahn if (WS.isTag()) 13421d891d44SHeejin Ahn registerTagType(WS); 1343da419bdbSHeejin Ahn 134432ce5ca0SDan Gohman if (WS.isTemporary()) 134532ce5ca0SDan Gohman continue; 134632ce5ca0SDan Gohman 134732ce5ca0SDan Gohman // If the symbol is not defined in this translation unit, import it. 13486c899ba6SSam Clegg if (!WS.isDefined() && !WS.isComdat()) { 13496c899ba6SSam Clegg if (WS.isFunction()) { 13508defa952SSam Clegg wasm::WasmImport Import; 1351f726e445SDan Gohman Import.Module = WS.getImportModule(); 1352f726e445SDan Gohman Import.Field = WS.getImportName(); 135332ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 13548defa952SSam Clegg Import.SigIndex = getFunctionType(WS); 13556c899ba6SSam Clegg Imports.push_back(Import); 1356492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 13576c899ba6SSam Clegg WasmIndices[&WS] = NumFunctionImports++; 13586c899ba6SSam Clegg } else if (WS.isGlobal()) { 135915f349f7SNicholas Wilson if (WS.isWeak()) 136015f349f7SNicholas Wilson report_fatal_error("undefined global symbol cannot be weak"); 136115f349f7SNicholas Wilson 13626c899ba6SSam Clegg wasm::WasmImport Import; 1363f726e445SDan Gohman Import.Field = WS.getImportName(); 136432ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1365492f7529SSam Clegg Import.Module = WS.getImportModule(); 13666c899ba6SSam Clegg Import.Global = WS.getGlobalType(); 13676c899ba6SSam Clegg Imports.push_back(Import); 1368492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 13696c899ba6SSam Clegg WasmIndices[&WS] = NumGlobalImports++; 13701d891d44SHeejin Ahn } else if (WS.isTag()) { 1371da419bdbSHeejin Ahn if (WS.isWeak()) 13721d891d44SHeejin Ahn report_fatal_error("undefined tag symbol cannot be weak"); 1373da419bdbSHeejin Ahn 1374da419bdbSHeejin Ahn wasm::WasmImport Import; 1375f726e445SDan Gohman Import.Module = WS.getImportModule(); 1376f726e445SDan Gohman Import.Field = WS.getImportName(); 13771d891d44SHeejin Ahn Import.Kind = wasm::WASM_EXTERNAL_TAG; 13783ec1760dSHeejin Ahn Import.SigIndex = getTagType(WS); 1379da419bdbSHeejin Ahn Imports.push_back(Import); 1380492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 13811d891d44SHeejin Ahn WasmIndices[&WS] = NumTagImports++; 1382feac819eSAndy Wingo } else if (WS.isTable()) { 1383feac819eSAndy Wingo if (WS.isWeak()) 1384feac819eSAndy Wingo report_fatal_error("undefined table symbol cannot be weak"); 1385feac819eSAndy Wingo 1386feac819eSAndy Wingo wasm::WasmImport Import; 1387feac819eSAndy Wingo Import.Module = WS.getImportModule(); 1388feac819eSAndy Wingo Import.Field = WS.getImportName(); 1389feac819eSAndy Wingo Import.Kind = wasm::WASM_EXTERNAL_TABLE; 1390c9801db2SAndy Wingo Import.Table = WS.getTableType(); 1391feac819eSAndy Wingo Imports.push_back(Import); 1392feac819eSAndy Wingo assert(WasmIndices.count(&WS) == 0); 1393feac819eSAndy Wingo WasmIndices[&WS] = NumTableImports++; 139432ce5ca0SDan Gohman } 139532ce5ca0SDan Gohman } 139632ce5ca0SDan Gohman } 139732ce5ca0SDan Gohman 1398492f7529SSam Clegg // Add imports for GOT globals 1399492f7529SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1400492f7529SSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 1401492f7529SSam Clegg if (WS.isUsedInGOT()) { 1402492f7529SSam Clegg wasm::WasmImport Import; 1403492f7529SSam Clegg if (WS.isFunction()) 1404492f7529SSam Clegg Import.Module = "GOT.func"; 1405492f7529SSam Clegg else 1406492f7529SSam Clegg Import.Module = "GOT.mem"; 1407492f7529SSam Clegg Import.Field = WS.getName(); 1408492f7529SSam Clegg Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1409492f7529SSam Clegg Import.Global = {wasm::WASM_TYPE_I32, true}; 1410492f7529SSam Clegg Imports.push_back(Import); 1411492f7529SSam Clegg assert(GOTIndices.count(&WS) == 0); 1412492f7529SSam Clegg GOTIndices[&WS] = NumGlobalImports++; 1413492f7529SSam Clegg } 1414492f7529SSam Clegg } 14150ff28fa6SDerek Schuff } 1416492f7529SSam Clegg 14170ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm, 14180ff28fa6SDerek Schuff const MCAsmLayout &Layout) { 14190ff28fa6SDerek Schuff support::endian::Writer MainWriter(*OS, support::little); 14200ff28fa6SDerek Schuff W = &MainWriter; 14210ff28fa6SDerek Schuff if (IsSplitDwarf) { 14220ff28fa6SDerek Schuff uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly); 14230ff28fa6SDerek Schuff assert(DwoOS); 14240ff28fa6SDerek Schuff support::endian::Writer DwoWriter(*DwoOS, support::little); 14250ff28fa6SDerek Schuff W = &DwoWriter; 14260ff28fa6SDerek Schuff return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly); 14270ff28fa6SDerek Schuff } else { 14280ff28fa6SDerek Schuff return writeOneObject(Asm, Layout, DwoMode::AllSections); 14290ff28fa6SDerek Schuff } 14300ff28fa6SDerek Schuff } 14310ff28fa6SDerek Schuff 14320ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm, 14330ff28fa6SDerek Schuff const MCAsmLayout &Layout, 14340ff28fa6SDerek Schuff DwoMode Mode) { 14350ff28fa6SDerek Schuff uint64_t StartOffset = W->OS.tell(); 14360ff28fa6SDerek Schuff SectionCount = 0; 14370ff28fa6SDerek Schuff CustomSections.clear(); 14380ff28fa6SDerek Schuff 14390ff28fa6SDerek Schuff LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 14400ff28fa6SDerek Schuff 14410ff28fa6SDerek Schuff // Collect information from the available symbols. 14420ff28fa6SDerek Schuff SmallVector<WasmFunction, 4> Functions; 14430ff28fa6SDerek Schuff SmallVector<uint32_t, 4> TableElems; 14440ff28fa6SDerek Schuff SmallVector<wasm::WasmImport, 4> Imports; 14450ff28fa6SDerek Schuff SmallVector<wasm::WasmExport, 4> Exports; 14463ec1760dSHeejin Ahn SmallVector<uint32_t, 2> TagTypes; 14470ff28fa6SDerek Schuff SmallVector<wasm::WasmGlobal, 1> Globals; 1448388fb67bSPaulo Matos SmallVector<wasm::WasmTable, 1> Tables; 14490ff28fa6SDerek Schuff SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos; 14500ff28fa6SDerek Schuff SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 14510ff28fa6SDerek Schuff std::map<StringRef, std::vector<WasmComdatEntry>> Comdats; 14520ff28fa6SDerek Schuff uint64_t DataSize = 0; 14530ff28fa6SDerek Schuff if (Mode != DwoMode::DwoOnly) { 14540ff28fa6SDerek Schuff prepareImports(Imports, Asm, Layout); 14550ff28fa6SDerek Schuff } 145630d314aaSSam Clegg 14574d57fbd0SSam Clegg // Populate DataSegments and CustomSections, which must be done before 14584d57fbd0SSam Clegg // populating DataLocations. 1459759631c7SSam Clegg for (MCSection &Sec : Asm) { 1460759631c7SSam Clegg auto &Section = static_cast<MCSectionWasm &>(Sec); 14617d1ff446SFangrui Song StringRef SectionName = Section.getName(); 1462759631c7SSam Clegg 14630ff28fa6SDerek Schuff if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec)) 14640ff28fa6SDerek Schuff continue; 14650ff28fa6SDerek Schuff if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec)) 14660ff28fa6SDerek Schuff continue; 14670ff28fa6SDerek Schuff 14688d396acaSDerek Schuff LLVM_DEBUG(dbgs() << "Processing Section " << SectionName << " group " 14698d396acaSDerek Schuff << Section.getGroup() << "\n";); 14708d396acaSDerek Schuff 1471bafe6902SSam Clegg // .init_array sections are handled specially elsewhere. 14724d57fbd0SSam Clegg if (SectionName.startswith(".init_array")) 1473bafe6902SSam Clegg continue; 1474bafe6902SSam Clegg 14754d57fbd0SSam Clegg // Code is handled separately 14764d57fbd0SSam Clegg if (Section.getKind().isText()) 14774d57fbd0SSam Clegg continue; 14784d57fbd0SSam Clegg 14794d57fbd0SSam Clegg if (Section.isWasmData()) { 1480329e76d5SSam Clegg uint32_t SegmentIndex = DataSegments.size(); 1481759631c7SSam Clegg DataSize = alignTo(DataSize, Section.getAlignment()); 1482759631c7SSam Clegg DataSegments.emplace_back(); 1483759631c7SSam Clegg WasmDataSegment &Segment = DataSegments.back(); 14844d57fbd0SSam Clegg Segment.Name = SectionName; 1485831a143eSAndy Wingo Segment.InitFlags = Section.getPassive() 1486831a143eSAndy Wingo ? (uint32_t)wasm::WASM_DATA_SEGMENT_IS_PASSIVE 1487831a143eSAndy Wingo : 0; 1488759631c7SSam Clegg Segment.Offset = DataSize; 1489759631c7SSam Clegg Segment.Section = &Section; 149063ebb813SSam Clegg addData(Segment.Data, Section); 149156c587adSSam Clegg Segment.Alignment = Log2_32(Section.getAlignment()); 14923b8d2be5SSam Clegg Segment.LinkingFlags = Section.getSegmentFlags(); 1493759631c7SSam Clegg DataSize += Segment.Data.size(); 14946c899ba6SSam Clegg Section.setSegmentIndex(SegmentIndex); 1495ea7caceeSSam Clegg 1496ea7caceeSSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 1497ea7caceeSSam Clegg Comdats[C->getName()].emplace_back( 1498329e76d5SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex}); 1499ea7caceeSSam Clegg } 15004d57fbd0SSam Clegg } else { 15014d57fbd0SSam Clegg // Create custom sections 15024d57fbd0SSam Clegg assert(Sec.getKind().isMetadata()); 15034d57fbd0SSam Clegg 15044d57fbd0SSam Clegg StringRef Name = SectionName; 15054d57fbd0SSam Clegg 15064d57fbd0SSam Clegg // For user-defined custom sections, strip the prefix 15074d57fbd0SSam Clegg if (Name.startswith(".custom_section.")) 15084d57fbd0SSam Clegg Name = Name.substr(strlen(".custom_section.")); 15094d57fbd0SSam Clegg 15104d57fbd0SSam Clegg MCSymbol *Begin = Sec.getBeginSymbol(); 1511fb807d4dSSam Clegg if (Begin) { 151230d314aaSSam Clegg assert(WasmIndices.count(cast<MCSymbolWasm>(Begin)) == 0); 15134d57fbd0SSam Clegg WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size(); 1514fb807d4dSSam Clegg } 1515cbda16ebSThomas Lively 1516f6f4f843SThomas Lively // Separate out the producers and target features sections 1517cbda16ebSThomas Lively if (Name == "producers") { 15180eaee545SJonas Devlieghere ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section); 1519cbda16ebSThomas Lively continue; 1520cbda16ebSThomas Lively } 1521f6f4f843SThomas Lively if (Name == "target_features") { 1522f6f4f843SThomas Lively TargetFeaturesSection = 15230eaee545SJonas Devlieghere std::make_unique<WasmCustomSection>(Name, &Section); 1524f6f4f843SThomas Lively continue; 1525f6f4f843SThomas Lively } 1526cbda16ebSThomas Lively 15270a391060SDerek Schuff // Custom sections can also belong to COMDAT groups. In this case the 15280a391060SDerek Schuff // decriptor's "index" field is the section index (in the final object 15290a391060SDerek Schuff // file), but that is not known until after layout, so it must be fixed up 15300a391060SDerek Schuff // later 15310a391060SDerek Schuff if (const MCSymbolWasm *C = Section.getGroup()) { 15320a391060SDerek Schuff Comdats[C->getName()].emplace_back( 15330a391060SDerek Schuff WasmComdatEntry{wasm::WASM_COMDAT_SECTION, 15340a391060SDerek Schuff static_cast<uint32_t>(CustomSections.size())}); 15350a391060SDerek Schuff } 15360a391060SDerek Schuff 15374d57fbd0SSam Clegg CustomSections.emplace_back(Name, &Section); 1538759631c7SSam Clegg } 15396a31a0d6SSam Clegg } 15406a31a0d6SSam Clegg 154130d314aaSSam Clegg if (Mode != DwoMode::DwoOnly) { 1542586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for defined symbols. 1543d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1544d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1545d934cb88SDan Gohman // or used in relocations. 1546d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 1547d934cb88SDan Gohman continue; 1548b7787fd0SSam Clegg 1549d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 15505e5b2cb1SWouter van Oortmerssen LLVM_DEBUG(dbgs() 15515e5b2cb1SWouter van Oortmerssen << "MCSymbol: " 15525e5b2cb1SWouter van Oortmerssen << toString(WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA)) 15535e5b2cb1SWouter van Oortmerssen << " '" << S << "'" 1554d34e60caSNicola Zaghen << " isDefined=" << S.isDefined() << " isExternal=" 1555d34e60caSNicola Zaghen << S.isExternal() << " isTemporary=" << S.isTemporary() 1556d34e60caSNicola Zaghen << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden() 1557b7787fd0SSam Clegg << " isVariable=" << WS.isVariable() << "\n"); 1558b7787fd0SSam Clegg 15595e3d33a7SSam Clegg if (WS.isVariable()) 15605e3d33a7SSam Clegg continue; 15616c899ba6SSam Clegg if (WS.isComdat() && !WS.isDefined()) 15626c899ba6SSam Clegg continue; 1563b7787fd0SSam Clegg 1564d934cb88SDan Gohman if (WS.isFunction()) { 15656c899ba6SSam Clegg unsigned Index; 1566cd65f698SSam Clegg if (WS.isDefined()) { 1567b7787fd0SSam Clegg if (WS.getOffset() != 0) 1568b7787fd0SSam Clegg report_fatal_error( 1569b7787fd0SSam Clegg "function sections must contain one function each"); 1570b7787fd0SSam Clegg 157118c56a07SHeejin Ahn if (WS.getSize() == nullptr) 1572b7787fd0SSam Clegg report_fatal_error( 1573b7787fd0SSam Clegg "function symbols must have a size set with .size"); 1574b7787fd0SSam Clegg 15756c899ba6SSam Clegg // A definition. Write out the function body. 15769f3fe42eSSam Clegg Index = NumFunctionImports + Functions.size(); 1577d934cb88SDan Gohman WasmFunction Func; 1578da419bdbSHeejin Ahn Func.SigIndex = getFunctionType(WS); 1579d934cb88SDan Gohman Func.Sym = &WS; 158030d314aaSSam Clegg assert(WasmIndices.count(&WS) == 0); 15816c899ba6SSam Clegg WasmIndices[&WS] = Index; 1582d934cb88SDan Gohman Functions.push_back(Func); 15836c899ba6SSam Clegg 15846c899ba6SSam Clegg auto &Section = static_cast<MCSectionWasm &>(WS.getSection()); 15856c899ba6SSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 15866c899ba6SSam Clegg Comdats[C->getName()].emplace_back( 15876c899ba6SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index}); 15886c899ba6SSam Clegg } 1589881d8778SSam Clegg 1590881d8778SSam Clegg if (WS.hasExportName()) { 1591881d8778SSam Clegg wasm::WasmExport Export; 1592881d8778SSam Clegg Export.Name = WS.getExportName(); 1593881d8778SSam Clegg Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1594881d8778SSam Clegg Export.Index = Index; 1595881d8778SSam Clegg Exports.push_back(Export); 1596881d8778SSam Clegg } 1597d934cb88SDan Gohman } else { 1598d934cb88SDan Gohman // An import; the index was assigned above. 15996c899ba6SSam Clegg Index = WasmIndices.find(&WS)->second; 1600d934cb88SDan Gohman } 1601d934cb88SDan Gohman 1602d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n"); 1603da419bdbSHeejin Ahn 16046c899ba6SSam Clegg } else if (WS.isData()) { 1605f3feb6adSWouter van Oortmerssen if (!isInSymtab(WS)) 1606c38e947eSSam Clegg continue; 1607c38e947eSSam Clegg 16086c899ba6SSam Clegg if (!WS.isDefined()) { 1609d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> segment index: -1" 1610d34e60caSNicola Zaghen << "\n"); 1611fe6414b0SSam Clegg continue; 16126c899ba6SSam Clegg } 1613fe6414b0SSam Clegg 1614d934cb88SDan Gohman if (!WS.getSize()) 1615c38e947eSSam Clegg report_fatal_error("data symbols must have a size set with .size: " + 1616c38e947eSSam Clegg WS.getName()); 1617d934cb88SDan Gohman 1618d934cb88SDan Gohman int64_t Size = 0; 1619d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1620d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 1621d934cb88SDan Gohman 1622759631c7SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1623079cba04SSam Clegg if (!DataSection.isWasmData()) 1624079cba04SSam Clegg report_fatal_error("data symbols must live in a data section: " + 1625079cba04SSam Clegg WS.getName()); 16267c395943SSam Clegg 16276c899ba6SSam Clegg // For each data symbol, export it in the symtab as a reference to the 16286c899ba6SSam Clegg // corresponding Wasm data segment. 16296c899ba6SSam Clegg wasm::WasmDataReference Ref = wasm::WasmDataReference{ 16303b29376eSWouter van Oortmerssen DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS), 16313b29376eSWouter van Oortmerssen static_cast<uint64_t>(Size)}; 163230d314aaSSam Clegg assert(DataLocations.count(&WS) == 0); 16336c899ba6SSam Clegg DataLocations[&WS] = Ref; 1634d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n"); 1635da419bdbSHeejin Ahn 1636a165f2d6SSam Clegg } else if (WS.isGlobal()) { 16376c899ba6SSam Clegg // A "true" Wasm global (currently just __stack_pointer) 16380a6c4d8dSSam Clegg if (WS.isDefined()) { 16390a6c4d8dSSam Clegg wasm::WasmGlobal Global; 16400a6c4d8dSSam Clegg Global.Type = WS.getGlobalType(); 16410a6c4d8dSSam Clegg Global.Index = NumGlobalImports + Globals.size(); 16420a6c4d8dSSam Clegg switch (Global.Type.Type) { 16430a6c4d8dSSam Clegg case wasm::WASM_TYPE_I32: 16440a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST; 16450a6c4d8dSSam Clegg break; 16460a6c4d8dSSam Clegg case wasm::WASM_TYPE_I64: 16470a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST; 16480a6c4d8dSSam Clegg break; 16490a6c4d8dSSam Clegg case wasm::WASM_TYPE_F32: 16500a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST; 16510a6c4d8dSSam Clegg break; 16520a6c4d8dSSam Clegg case wasm::WASM_TYPE_F64: 16530a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST; 16540a6c4d8dSSam Clegg break; 165579aad89dSSam Clegg case wasm::WASM_TYPE_EXTERNREF: 165679aad89dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL; 165779aad89dSSam Clegg break; 16580a6c4d8dSSam Clegg default: 16590a6c4d8dSSam Clegg llvm_unreachable("unexpected type"); 16600a6c4d8dSSam Clegg } 166130d314aaSSam Clegg assert(WasmIndices.count(&WS) == 0); 16620a6c4d8dSSam Clegg WasmIndices[&WS] = Global.Index; 16630a6c4d8dSSam Clegg Globals.push_back(Global); 16640a6c4d8dSSam Clegg } else { 1665545932beSEric Christopher // An import; the index was assigned above 1666d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> global index: " 1667d34e60caSNicola Zaghen << WasmIndices.find(&WS)->second << "\n"); 16680a6c4d8dSSam Clegg } 1669388fb67bSPaulo Matos } else if (WS.isTable()) { 1670388fb67bSPaulo Matos if (WS.isDefined()) { 1671388fb67bSPaulo Matos wasm::WasmTable Table; 1672388fb67bSPaulo Matos Table.Index = NumTableImports + Tables.size(); 1673c9801db2SAndy Wingo Table.Type = WS.getTableType(); 167430d314aaSSam Clegg assert(WasmIndices.count(&WS) == 0); 1675388fb67bSPaulo Matos WasmIndices[&WS] = Table.Index; 1676388fb67bSPaulo Matos Tables.push_back(Table); 1677388fb67bSPaulo Matos } 167830d314aaSSam Clegg LLVM_DEBUG(dbgs() << " -> table index: " 167930d314aaSSam Clegg << WasmIndices.find(&WS)->second << "\n"); 16801d891d44SHeejin Ahn } else if (WS.isTag()) { 168128780e59SHeejin Ahn // C++ exception symbol (__cpp_exception) or longjmp symbol 168228780e59SHeejin Ahn // (__c_longjmp) 1683da419bdbSHeejin Ahn unsigned Index; 1684da419bdbSHeejin Ahn if (WS.isDefined()) { 16853ec1760dSHeejin Ahn Index = NumTagImports + TagTypes.size(); 16863ec1760dSHeejin Ahn uint32_t SigIndex = getTagType(WS); 168730d314aaSSam Clegg assert(WasmIndices.count(&WS) == 0); 1688da419bdbSHeejin Ahn WasmIndices[&WS] = Index; 16893ec1760dSHeejin Ahn TagTypes.push_back(SigIndex); 1690da419bdbSHeejin Ahn } else { 1691da419bdbSHeejin Ahn // An import; the index was assigned above. 1692492f7529SSam Clegg assert(WasmIndices.count(&WS) > 0); 1693da419bdbSHeejin Ahn } 16941d891d44SHeejin Ahn LLVM_DEBUG(dbgs() << " -> tag index: " << WasmIndices.find(&WS)->second 16951d891d44SHeejin Ahn << "\n"); 1696da419bdbSHeejin Ahn 1697a165f2d6SSam Clegg } else { 1698a165f2d6SSam Clegg assert(WS.isSection()); 1699d934cb88SDan Gohman } 1700d934cb88SDan Gohman } 1701d934cb88SDan Gohman 1702586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for aliased symbols. We need to 1703586320c0SNicholas Wilson // process these in a separate pass because we need to have processed the 1704586320c0SNicholas Wilson // target of the alias before the alias itself and the symbols are not 1705586320c0SNicholas Wilson // necessarily ordered in this way. 1706b7787fd0SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1707b7787fd0SSam Clegg if (!S.isVariable()) 1708b7787fd0SSam Clegg continue; 170931a2c809SSam Clegg 1710cd65f698SSam Clegg assert(S.isDefined()); 1711b7787fd0SSam Clegg 17129c7b5808SDominic Chen const auto *BS = Layout.getBaseSymbol(S); 17139c7b5808SDominic Chen if (!BS) 17149c7b5808SDominic Chen report_fatal_error(Twine(S.getName()) + 17159c7b5808SDominic Chen ": absolute addressing not supported!"); 17169c7b5808SDominic Chen const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS); 17177ee758d6SSam Clegg 17185e3d33a7SSam Clegg // Find the target symbol of this weak alias and export that index 1719aff1c4dfSSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 172030d314aaSSam Clegg LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base 172130d314aaSSam Clegg << "'\n"); 1722b7787fd0SSam Clegg 17237ee758d6SSam Clegg if (Base->isFunction()) { 17247ee758d6SSam Clegg assert(WasmIndices.count(Base) > 0); 17257ee758d6SSam Clegg uint32_t WasmIndex = WasmIndices.find(Base)->second; 1726492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 17276c899ba6SSam Clegg WasmIndices[&WS] = WasmIndex; 1728d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n"); 17297ee758d6SSam Clegg } else if (Base->isData()) { 17307ee758d6SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 17317ee758d6SSam Clegg uint64_t Offset = Layout.getSymbolOffset(S); 17327ee758d6SSam Clegg int64_t Size = 0; 17337ee758d6SSam Clegg // For data symbol alias we use the size of the base symbol as the 17347ee758d6SSam Clegg // size of the alias. When an offset from the base is involved this 17357ee758d6SSam Clegg // can result in a offset + size goes past the end of the data section 17367ee758d6SSam Clegg // which out object format doesn't support. So we must clamp it. 17377ee758d6SSam Clegg if (!Base->getSize()->evaluateAsAbsolute(Size, Layout)) 17387ee758d6SSam Clegg report_fatal_error(".size expression must be evaluatable"); 17397ee758d6SSam Clegg const WasmDataSegment &Segment = 17407ee758d6SSam Clegg DataSegments[DataSection.getSegmentIndex()]; 17417ee758d6SSam Clegg Size = 17427ee758d6SSam Clegg std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset); 17437ee758d6SSam Clegg wasm::WasmDataReference Ref = wasm::WasmDataReference{ 17447ee758d6SSam Clegg DataSection.getSegmentIndex(), 17457ee758d6SSam Clegg static_cast<uint32_t>(Layout.getSymbolOffset(S)), 17467ee758d6SSam Clegg static_cast<uint32_t>(Size)}; 17476c899ba6SSam Clegg DataLocations[&WS] = Ref; 1748d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n"); 17496c899ba6SSam Clegg } else { 17501d891d44SHeejin Ahn report_fatal_error("don't yet support global/tag aliases"); 17516c899ba6SSam Clegg } 1752586320c0SNicholas Wilson } 175330d314aaSSam Clegg } 175431a2c809SSam Clegg 1755586320c0SNicholas Wilson // Finally, populate the symbol table itself, in its "natural" order. 1756586320c0SNicholas Wilson for (const MCSymbol &S : Asm.symbols()) { 1757586320c0SNicholas Wilson const auto &WS = static_cast<const MCSymbolWasm &>(S); 175825d8e68bSSam Clegg if (!isInSymtab(WS)) { 175918c56a07SHeejin Ahn WS.setIndex(InvalidIndex); 1760586320c0SNicholas Wilson continue; 176125d8e68bSSam Clegg } 1762d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n"); 1763586320c0SNicholas Wilson 1764586320c0SNicholas Wilson uint32_t Flags = 0; 1765586320c0SNicholas Wilson if (WS.isWeak()) 1766586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_WEAK; 1767586320c0SNicholas Wilson if (WS.isHidden()) 1768586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN; 1769586320c0SNicholas Wilson if (!WS.isExternal() && WS.isDefined()) 1770586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL; 1771586320c0SNicholas Wilson if (WS.isUndefined()) 1772586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_UNDEFINED; 1773da84b688SDan Gohman if (WS.isNoStrip()) { 1774da84b688SDan Gohman Flags |= wasm::WASM_SYMBOL_NO_STRIP; 1775da84b688SDan Gohman if (isEmscripten()) { 1776d6ef8da3SSam Clegg Flags |= wasm::WASM_SYMBOL_EXPORTED; 1777da84b688SDan Gohman } 1778da84b688SDan Gohman } 1779b4f4e370SSam Clegg if (WS.hasImportName()) 178029874ceaSDan Gohman Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME; 1781881d8778SSam Clegg if (WS.hasExportName()) 1782881d8778SSam Clegg Flags |= wasm::WASM_SYMBOL_EXPORTED; 178344177e5fSSam Clegg if (WS.isTLS()) 178444177e5fSSam Clegg Flags |= wasm::WASM_SYMBOL_TLS; 1785586320c0SNicholas Wilson 1786586320c0SNicholas Wilson wasm::WasmSymbolInfo Info; 1787586320c0SNicholas Wilson Info.Name = WS.getName(); 17885e5b2cb1SWouter van Oortmerssen Info.Kind = WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA); 1789586320c0SNicholas Wilson Info.Flags = Flags; 17904d57fbd0SSam Clegg if (!WS.isData()) { 17914d57fbd0SSam Clegg assert(WasmIndices.count(&WS) > 0); 1792586320c0SNicholas Wilson Info.ElementIndex = WasmIndices.find(&WS)->second; 17934d57fbd0SSam Clegg } else if (WS.isDefined()) { 17944d57fbd0SSam Clegg assert(DataLocations.count(&WS) > 0); 1795586320c0SNicholas Wilson Info.DataRef = DataLocations.find(&WS)->second; 17964d57fbd0SSam Clegg } 179725d8e68bSSam Clegg WS.setIndex(SymbolInfos.size()); 1798586320c0SNicholas Wilson SymbolInfos.emplace_back(Info); 1799b7787fd0SSam Clegg } 1800b7787fd0SSam Clegg 18016006e091SSam Clegg { 18026006e091SSam Clegg auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 1803f9edbe95SSam Clegg // Functions referenced by a relocation need to put in the table. This is 1804f9edbe95SSam Clegg // purely to make the object file's provisional values readable, and is 1805f9edbe95SSam Clegg // ignored by the linker, which re-calculates the relocations itself. 1806d1152a26SSam Clegg if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 && 1807cc1b9b68SWouter van Oortmerssen Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 && 180881443ac1SSam Clegg Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB && 1809cc1b9b68SWouter van Oortmerssen Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 && 18103a293cbfSWouter van Oortmerssen Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB && 18113a293cbfSWouter van Oortmerssen Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB64) 1812f9edbe95SSam Clegg return; 1813f9edbe95SSam Clegg assert(Rel.Symbol->isFunction()); 18147ee758d6SSam Clegg const MCSymbolWasm *Base = 18157ee758d6SSam Clegg cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol)); 18167ee758d6SSam Clegg uint32_t FunctionIndex = WasmIndices.find(Base)->second; 181718c56a07SHeejin Ahn uint32_t TableIndex = TableElems.size() + InitialTableOffset; 18187ee758d6SSam Clegg if (TableIndices.try_emplace(Base, TableIndex).second) { 18197ee758d6SSam Clegg LLVM_DEBUG(dbgs() << " -> adding " << Base->getName() 1820f9edbe95SSam Clegg << " to table: " << TableIndex << "\n"); 18216c899ba6SSam Clegg TableElems.push_back(FunctionIndex); 18227ee758d6SSam Clegg registerFunctionType(*Base); 18236006e091SSam Clegg } 18246006e091SSam Clegg }; 1825970d02c4SDan Gohman 18266006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : CodeRelocations) 18276006e091SSam Clegg HandleReloc(RelEntry); 18286006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : DataRelocations) 18296006e091SSam Clegg HandleReloc(RelEntry); 1830d934cb88SDan Gohman } 1831d934cb88SDan Gohman 1832bafe6902SSam Clegg // Translate .init_array section contents into start functions. 1833bafe6902SSam Clegg for (const MCSection &S : Asm) { 1834bafe6902SSam Clegg const auto &WS = static_cast<const MCSectionWasm &>(S); 18357d1ff446SFangrui Song if (WS.getName().startswith(".fini_array")) 1836bafe6902SSam Clegg report_fatal_error(".fini_array sections are unsupported"); 18377d1ff446SFangrui Song if (!WS.getName().startswith(".init_array")) 1838bafe6902SSam Clegg continue; 1839bafe6902SSam Clegg if (WS.getFragmentList().empty()) 1840bafe6902SSam Clegg continue; 1841b210c64bSSam Clegg 1842b210c64bSSam Clegg // init_array is expected to contain a single non-empty data fragment 1843b210c64bSSam Clegg if (WS.getFragmentList().size() != 3) 1844bafe6902SSam Clegg report_fatal_error("only one .init_array section fragment supported"); 1845b210c64bSSam Clegg 1846b210c64bSSam Clegg auto IT = WS.begin(); 1847b210c64bSSam Clegg const MCFragment &EmptyFrag = *IT; 1848b210c64bSSam Clegg if (EmptyFrag.getKind() != MCFragment::FT_Data) 1849b210c64bSSam Clegg report_fatal_error(".init_array section should be aligned"); 1850b210c64bSSam Clegg 1851b210c64bSSam Clegg IT = std::next(IT); 1852b210c64bSSam Clegg const MCFragment &AlignFrag = *IT; 1853bafe6902SSam Clegg if (AlignFrag.getKind() != MCFragment::FT_Align) 1854bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned"); 1855bafe6902SSam Clegg if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1856bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned for pointers"); 1857b210c64bSSam Clegg 1858b210c64bSSam Clegg const MCFragment &Frag = *std::next(IT); 1859bafe6902SSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1860bafe6902SSam Clegg report_fatal_error("only data supported in .init_array section"); 1861b210c64bSSam Clegg 1862bafe6902SSam Clegg uint16_t Priority = UINT16_MAX; 18634d57fbd0SSam Clegg unsigned PrefixLength = strlen(".init_array"); 18647d1ff446SFangrui Song if (WS.getName().size() > PrefixLength) { 18657d1ff446SFangrui Song if (WS.getName()[PrefixLength] != '.') 1866f208f631SHeejin Ahn report_fatal_error( 1867f208f631SHeejin Ahn ".init_array section priority should start with '.'"); 18687d1ff446SFangrui Song if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority)) 1869bafe6902SSam Clegg report_fatal_error("invalid .init_array section priority"); 1870bafe6902SSam Clegg } 1871bafe6902SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1872bafe6902SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1873f208f631SHeejin Ahn for (const uint8_t * 187418c56a07SHeejin Ahn P = (const uint8_t *)Contents.data(), 187518c56a07SHeejin Ahn *End = (const uint8_t *)Contents.data() + Contents.size(); 187618c56a07SHeejin Ahn P != End; ++P) { 187718c56a07SHeejin Ahn if (*P != 0) 1878bafe6902SSam Clegg report_fatal_error("non-symbolic data in .init_array section"); 1879bafe6902SSam Clegg } 1880bafe6902SSam Clegg for (const MCFixup &Fixup : DataFrag.getFixups()) { 1881f208f631SHeejin Ahn assert(Fixup.getKind() == 1882f208f631SHeejin Ahn MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1883bafe6902SSam Clegg const MCExpr *Expr = Fixup.getValue(); 18848fffa1dfSSam Clegg auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr); 18858fffa1dfSSam Clegg if (!SymRef) 1886bafe6902SSam Clegg report_fatal_error("fixups in .init_array should be symbol references"); 18878fffa1dfSSam Clegg const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol()); 18888fffa1dfSSam Clegg if (TargetSym.getIndex() == InvalidIndex) 18893ea1c62cSSam Clegg report_fatal_error("symbols in .init_array should exist in symtab"); 18908fffa1dfSSam Clegg if (!TargetSym.isFunction()) 18918fffa1dfSSam Clegg report_fatal_error("symbols in .init_array should be for functions"); 189225d8e68bSSam Clegg InitFuncs.push_back( 18938fffa1dfSSam Clegg std::make_pair(Priority, TargetSym.getIndex())); 1894bafe6902SSam Clegg } 1895bafe6902SSam Clegg } 1896bafe6902SSam Clegg 189718eafb6cSDan Gohman // Write out the Wasm header. 189818eafb6cSDan Gohman writeHeader(Asm); 189918eafb6cSDan Gohman 19000ff28fa6SDerek Schuff uint32_t CodeSectionIndex, DataSectionIndex; 19010ff28fa6SDerek Schuff if (Mode != DwoMode::DwoOnly) { 1902da419bdbSHeejin Ahn writeTypeSection(Signatures); 1903f950b24aSSam Clegg writeImportSection(Imports, DataSize, TableElems.size()); 19049e15f359SSam Clegg writeFunctionSection(Functions); 1905d823cc7cSAndy Wingo writeTableSection(Tables); 1906f950b24aSSam Clegg // Skip the "memory" section; we import the memory instead. 19073ec1760dSHeejin Ahn writeTagSection(TagTypes); 19080a6c4d8dSSam Clegg writeGlobalSection(Globals); 19099e15f359SSam Clegg writeExportSection(Exports); 1910a5a3659dSAndy Wingo const MCSymbol *IndirectFunctionTable = 1911a5a3659dSAndy Wingo Asm.getContext().lookupSymbol("__indirect_function_table"); 1912a5a3659dSAndy Wingo writeElemSection(cast_or_null<const MCSymbolWasm>(IndirectFunctionTable), 1913a5a3659dSAndy Wingo TableElems); 1914fef8de66SThomas Lively writeDataCountSection(); 19150ff28fa6SDerek Schuff 19160ff28fa6SDerek Schuff CodeSectionIndex = writeCodeSection(Asm, Layout, Functions); 19170ff28fa6SDerek Schuff DataSectionIndex = writeDataSection(Layout); 19180ff28fa6SDerek Schuff } 19190ff28fa6SDerek Schuff 19200a391060SDerek Schuff // The Sections in the COMDAT list have placeholder indices (their index among 19210a391060SDerek Schuff // custom sections, rather than among all sections). Fix them up here. 19220a391060SDerek Schuff for (auto &Group : Comdats) { 19230a391060SDerek Schuff for (auto &Entry : Group.second) { 19240a391060SDerek Schuff if (Entry.Kind == wasm::WASM_COMDAT_SECTION) { 19250a391060SDerek Schuff Entry.Index += SectionCount; 19260ff28fa6SDerek Schuff } 19270a391060SDerek Schuff } 19280a391060SDerek Schuff } 19290a391060SDerek Schuff for (auto &CustomSection : CustomSections) 19300a391060SDerek Schuff writeCustomSection(CustomSection, Asm, Layout); 19310ff28fa6SDerek Schuff 19320ff28fa6SDerek Schuff if (Mode != DwoMode::DwoOnly) { 1933c22bfb6bSNicholas Wilson writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats); 19340ff28fa6SDerek Schuff 19356f08c84aSSam Clegg writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations); 19366f08c84aSSam Clegg writeRelocSection(DataSectionIndex, "DATA", DataRelocations); 19370ff28fa6SDerek Schuff } 19386a31a0d6SSam Clegg writeCustomRelocSections(); 1939cbda16ebSThomas Lively if (ProducersSection) 1940cbda16ebSThomas Lively writeCustomSection(*ProducersSection, Asm, Layout); 1941f6f4f843SThomas Lively if (TargetFeaturesSection) 1942f6f4f843SThomas Lively writeCustomSection(*TargetFeaturesSection, Asm, Layout); 1943970d02c4SDan Gohman 1944d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 19450ff28fa6SDerek Schuff return W->OS.tell() - StartOffset; 194618eafb6cSDan Gohman } 194718eafb6cSDan Gohman 194860fbc7ccSLang Hames std::unique_ptr<MCObjectWriter> 19491301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 195018eafb6cSDan Gohman raw_pwrite_stream &OS) { 19510eaee545SJonas Devlieghere return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS); 195218eafb6cSDan Gohman } 19530ff28fa6SDerek Schuff 19540ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter> 19550ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 19560ff28fa6SDerek Schuff raw_pwrite_stream &OS, 19570ff28fa6SDerek Schuff raw_pwrite_stream &DwoOS) { 19580ff28fa6SDerek Schuff return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS); 19590ff28fa6SDerek Schuff } 1960