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 4330e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is 4430e1bbc1SSam Clegg // and emtpy 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; 702e150409SThomas Lively uint32_t LinkerFlags; 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 198388fb67bSPaulo Matos // function/global/table/event/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; 221388fb67bSPaulo Matos // NumTableImports is initialized to 1 to account for the hardcoded import of 222388fb67bSPaulo Matos // __indirect_function_table 223388fb67bSPaulo Matos unsigned NumTableImports = 1; 224da419bdbSHeejin Ahn unsigned NumEventImports = 0; 2257e1c3345SChandler Carruth uint32_t SectionCount = 0; 226d934cb88SDan Gohman 2270ff28fa6SDerek Schuff enum class DwoMode { 2280ff28fa6SDerek Schuff AllSections, 2290ff28fa6SDerek Schuff NonDwoOnly, 2300ff28fa6SDerek Schuff DwoOnly, 2310ff28fa6SDerek Schuff }; 2320ff28fa6SDerek Schuff bool IsSplitDwarf = false; 2330ff28fa6SDerek Schuff raw_pwrite_stream *OS = nullptr; 2340ff28fa6SDerek Schuff raw_pwrite_stream *DwoOS = nullptr; 2350ff28fa6SDerek Schuff 2360ff28fa6SDerek Schuff // TargetObjectWriter wranppers. 23718eafb6cSDan Gohman bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 238da84b688SDan Gohman bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); } 23918eafb6cSDan Gohman 2402322a937SSam Clegg void startSection(SectionBookkeeping &Section, unsigned SectionId); 2412322a937SSam Clegg void startCustomSection(SectionBookkeeping &Section, StringRef Name); 242d934cb88SDan Gohman void endSection(SectionBookkeeping &Section); 243d934cb88SDan Gohman 24418eafb6cSDan Gohman public: 2451301a878SLang Hames WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 2460ff28fa6SDerek Schuff raw_pwrite_stream &OS_) 2470ff28fa6SDerek Schuff : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {} 2480ff28fa6SDerek Schuff 2490ff28fa6SDerek Schuff WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 2500ff28fa6SDerek Schuff raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_) 2510ff28fa6SDerek Schuff : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_), 2520ff28fa6SDerek Schuff DwoOS(&DwoOS_) {} 25318eafb6cSDan Gohman 2540917c9e4SDan Gohman private: 255acd7d2b0SSam Clegg void reset() override { 256acd7d2b0SSam Clegg CodeRelocations.clear(); 257acd7d2b0SSam Clegg DataRelocations.clear(); 258acd7d2b0SSam Clegg TypeIndices.clear(); 2596c899ba6SSam Clegg WasmIndices.clear(); 260492f7529SSam Clegg GOTIndices.clear(); 261f9edbe95SSam Clegg TableIndices.clear(); 2626c899ba6SSam Clegg DataLocations.clear(); 263cbda16ebSThomas Lively CustomSections.clear(); 264cbda16ebSThomas Lively ProducersSection.reset(); 265f6f4f843SThomas Lively TargetFeaturesSection.reset(); 2666a31a0d6SSam Clegg CustomSectionsRelocations.clear(); 267da419bdbSHeejin Ahn SignatureIndices.clear(); 268da419bdbSHeejin Ahn Signatures.clear(); 2696c899ba6SSam Clegg DataSegments.clear(); 2706ccb59b3SSam Clegg SectionFunctions.clear(); 2719f3fe42eSSam Clegg NumFunctionImports = 0; 2727c395943SSam Clegg NumGlobalImports = 0; 273388fb67bSPaulo Matos NumTableImports = 1; 274105bdc25SSam Clegg MCObjectWriter::reset(); 275acd7d2b0SSam Clegg } 276acd7d2b0SSam Clegg 27718eafb6cSDan Gohman void writeHeader(const MCAssembler &Asm); 27818eafb6cSDan Gohman 27918eafb6cSDan Gohman void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 28018eafb6cSDan Gohman const MCFragment *Fragment, const MCFixup &Fixup, 281ceecfe5bSRafael Espindola MCValue Target, uint64_t &FixedValue) override; 28218eafb6cSDan Gohman 28318eafb6cSDan Gohman void executePostLayoutBinding(MCAssembler &Asm, 28418eafb6cSDan Gohman const MCAsmLayout &Layout) override; 2850ff28fa6SDerek Schuff void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports, 2860ff28fa6SDerek Schuff MCAssembler &Asm, const MCAsmLayout &Layout); 287438390faSPeter Collingbourne uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 2889e15f359SSam Clegg 2890ff28fa6SDerek Schuff uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout, 2900ff28fa6SDerek Schuff DwoMode Mode); 2910ff28fa6SDerek Schuff 292b7787fd0SSam Clegg void writeString(const StringRef Str) { 2930ff28fa6SDerek Schuff encodeULEB128(Str.size(), W->OS); 2940ff28fa6SDerek Schuff W->OS << Str; 295b7787fd0SSam Clegg } 296b7787fd0SSam Clegg 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); 316457fb0b4SSam Clegg void writeElemSection(ArrayRef<uint32_t> TableElems); 317fef8de66SThomas Lively void writeDataCountSection(); 318e49584a3SSam Clegg uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout, 319457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions); 320e49584a3SSam Clegg uint32_t writeDataSection(const MCAsmLayout &Layout); 321da419bdbSHeejin Ahn void writeEventSection(ArrayRef<wasm::WasmEventType> Events); 3220a6c4d8dSSam Clegg void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals); 323388fb67bSPaulo Matos void writeTableSection(ArrayRef<wasm::WasmTable> Tables); 3246f08c84aSSam Clegg void writeRelocSection(uint32_t SectionIndex, StringRef Name, 325f77dc2a8SSam Clegg std::vector<WasmRelocationEntry> &Relocations); 32631a2c809SSam Clegg void writeLinkingMetaDataSection( 32786b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 328ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 329ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats); 330cbda16ebSThomas Lively void writeCustomSection(WasmCustomSection &CustomSection, 331cbda16ebSThomas Lively const MCAssembler &Asm, const MCAsmLayout &Layout); 3326a31a0d6SSam Clegg void writeCustomRelocSections(); 3336a31a0d6SSam Clegg void 3346a31a0d6SSam Clegg updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions, 3356a31a0d6SSam Clegg const MCAsmLayout &Layout); 336acd7d2b0SSam Clegg 3377ee758d6SSam Clegg uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry, 3387ee758d6SSam Clegg const MCAsmLayout &Layout); 339acd7d2b0SSam Clegg void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations, 3407ee758d6SSam Clegg uint64_t ContentsOffset, const MCAsmLayout &Layout); 341acd7d2b0SSam Clegg 342acd7d2b0SSam Clegg uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry); 3435e3d33a7SSam Clegg uint32_t getFunctionType(const MCSymbolWasm &Symbol); 344da419bdbSHeejin Ahn uint32_t getEventType(const MCSymbolWasm &Symbol); 34538b12f5eSHeejin Ahn void registerFunctionType(const MCSymbolWasm &Symbol); 34638b12f5eSHeejin Ahn void registerEventType(const MCSymbolWasm &Symbol); 34718eafb6cSDan Gohman }; 3489e15f359SSam Clegg 34918eafb6cSDan Gohman } // end anonymous namespace 35018eafb6cSDan Gohman 351d934cb88SDan Gohman // Write out a section header and a patchable section size field. 352d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section, 3532322a937SSam Clegg unsigned SectionId) { 354d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n"); 3550ff28fa6SDerek Schuff W->OS << char(SectionId); 356d934cb88SDan Gohman 3570ff28fa6SDerek Schuff Section.SizeOffset = W->OS.tell(); 358d934cb88SDan Gohman 359d934cb88SDan Gohman // The section size. We don't know the size yet, so reserve enough space 360d934cb88SDan Gohman // for any 32-bit value; we'll patch it later. 3610ff28fa6SDerek Schuff encodeULEB128(0, W->OS, 5); 362d934cb88SDan Gohman 363d934cb88SDan Gohman // The position where the section starts, for measuring its size. 3640ff28fa6SDerek Schuff Section.ContentsOffset = W->OS.tell(); 3650ff28fa6SDerek Schuff Section.PayloadOffset = W->OS.tell(); 3666f08c84aSSam Clegg Section.Index = SectionCount++; 367d934cb88SDan Gohman } 3682322a937SSam Clegg 3692322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section, 3702322a937SSam Clegg StringRef Name) { 371d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n"); 3722322a937SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM); 3736a31a0d6SSam Clegg 3746a31a0d6SSam Clegg // The position where the section header ends, for measuring its size. 3750ff28fa6SDerek Schuff Section.PayloadOffset = W->OS.tell(); 3766a31a0d6SSam Clegg 3772322a937SSam Clegg // Custom sections in wasm also have a string identifier. 3782322a937SSam Clegg writeString(Name); 3796a31a0d6SSam Clegg 3806a31a0d6SSam Clegg // The position where the custom section starts. 3810ff28fa6SDerek Schuff Section.ContentsOffset = W->OS.tell(); 382d934cb88SDan Gohman } 383d934cb88SDan Gohman 384d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the 385d934cb88SDan Gohman // section size field at the start of the section. 386d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) { 3870ff28fa6SDerek Schuff uint64_t Size = W->OS.tell(); 388c0affde8SSam Clegg // /dev/null doesn't support seek/tell and can report offset of 0. 389c0affde8SSam Clegg // Simply skip this patching in that case. 390c0affde8SSam Clegg if (!Size) 391c0affde8SSam Clegg return; 392c0affde8SSam Clegg 393c0affde8SSam Clegg Size -= Section.PayloadOffset; 394d934cb88SDan Gohman if (uint32_t(Size) != Size) 395d934cb88SDan Gohman report_fatal_error("section size does not fit in a uint32_t"); 396d934cb88SDan Gohman 397d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n"); 398d934cb88SDan Gohman 399d934cb88SDan Gohman // Write the final section size to the payload_len field, which follows 400d934cb88SDan Gohman // the section id byte. 4010ff28fa6SDerek Schuff writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W->OS), Size, 402f17b149dSPeter Collingbourne Section.SizeOffset); 403d934cb88SDan Gohman } 404d934cb88SDan Gohman 40518eafb6cSDan Gohman // Emit the Wasm header. 40618eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { 4070ff28fa6SDerek Schuff W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic)); 4080ff28fa6SDerek Schuff W->write<uint32_t>(wasm::WasmVersion); 40918eafb6cSDan Gohman } 41018eafb6cSDan Gohman 41118eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 41218eafb6cSDan Gohman const MCAsmLayout &Layout) { 4136ccb59b3SSam Clegg // Build a map of sections to the function that defines them, for use 4146ccb59b3SSam Clegg // in recordRelocation. 4156ccb59b3SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 4166ccb59b3SSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 4176ccb59b3SSam Clegg if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) { 4186ccb59b3SSam Clegg const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection()); 4196ccb59b3SSam Clegg auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S)); 4206ccb59b3SSam Clegg if (!Pair.second) 4216ccb59b3SSam Clegg report_fatal_error("section already has a defining function: " + 4227d1ff446SFangrui Song Sec.getName()); 4236ccb59b3SSam Clegg } 4246ccb59b3SSam Clegg } 42518eafb6cSDan Gohman } 42618eafb6cSDan Gohman 42718eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 42818eafb6cSDan Gohman const MCAsmLayout &Layout, 42918eafb6cSDan Gohman const MCFragment *Fragment, 43018eafb6cSDan Gohman const MCFixup &Fixup, MCValue Target, 431ceecfe5bSRafael Espindola uint64_t &FixedValue) { 432ecc5e808SSam Clegg // The WebAssembly backend should never generate FKF_IsPCRel fixups 433e828ce1bSFangrui Song assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags & 434ecc5e808SSam Clegg MCFixupKindInfo::FKF_IsPCRel)); 435ecc5e808SSam Clegg 436fe6414b0SSam Clegg const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 437d934cb88SDan Gohman uint64_t C = Target.getConstant(); 438d934cb88SDan Gohman uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 439d934cb88SDan Gohman MCContext &Ctx = Asm.getContext(); 440d934cb88SDan Gohman 441d934cb88SDan Gohman if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 442ecc5e808SSam Clegg // To get here the A - B expression must have failed evaluateAsRelocatable. 443ecc5e808SSam Clegg // This means either A or B must be undefined and in WebAssembly we can't 444ecc5e808SSam Clegg // support either of those cases. 445ecc5e808SSam Clegg const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 446d934cb88SDan Gohman Ctx.reportError( 447d934cb88SDan Gohman Fixup.getLoc(), 448d934cb88SDan Gohman Twine("symbol '") + SymB.getName() + 449ecc5e808SSam Clegg "': unsupported subtraction expression used in relocation."); 450d934cb88SDan Gohman return; 451d934cb88SDan Gohman } 452d934cb88SDan Gohman 453d934cb88SDan Gohman // We either rejected the fixup or folded B into C at this point. 454d934cb88SDan Gohman const MCSymbolRefExpr *RefA = Target.getSymA(); 455ecc5e808SSam Clegg const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol()); 456d934cb88SDan Gohman 4573ea1c62cSSam Clegg // The .init_array isn't translated as data, so don't do relocations in it. 4587d1ff446SFangrui Song if (FixupSection.getName().startswith(".init_array")) { 4593ea1c62cSSam Clegg SymA->setUsedInInitArray(); 4603ea1c62cSSam Clegg return; 4613ea1c62cSSam Clegg } 4623ea1c62cSSam Clegg 463ecc5e808SSam Clegg if (SymA->isVariable()) { 464d934cb88SDan Gohman const MCExpr *Expr = SymA->getVariableValue(); 4657ee758d6SSam Clegg if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) 4666ad8f190SSam Clegg if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) 4676ad8f190SSam Clegg llvm_unreachable("weakref used in reloc not yet implemented"); 468d934cb88SDan Gohman } 469d934cb88SDan Gohman 470d934cb88SDan Gohman // Put any constant offset in an addend. Offsets can be negative, and 471d934cb88SDan Gohman // LLVM expects wrapping, in contrast to wasm's immediates which can't 472d934cb88SDan Gohman // be negative and don't wrap. 473d934cb88SDan Gohman FixedValue = 0; 474d934cb88SDan Gohman 475a5e175c6SSam Clegg unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup); 4769d24fb7fSSam Clegg 4774d57fbd0SSam Clegg // Absolute offset within a section or a function. 4784d57fbd0SSam Clegg // Currently only supported for for metadata sections. 4794d57fbd0SSam Clegg // See: test/MC/WebAssembly/blockaddress.ll 480d1152a26SSam Clegg if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 || 481d1152a26SSam Clegg Type == wasm::R_WASM_SECTION_OFFSET_I32) { 4824d57fbd0SSam Clegg if (!FixupSection.getKind().isMetadata()) 4834d57fbd0SSam Clegg report_fatal_error("relocations for function or section offsets are " 4844d57fbd0SSam Clegg "only supported in metadata sections"); 4854d57fbd0SSam Clegg 4864d57fbd0SSam Clegg const MCSymbol *SectionSymbol = nullptr; 4874d57fbd0SSam Clegg const MCSection &SecA = SymA->getSection(); 4884d57fbd0SSam Clegg if (SecA.getKind().isText()) 4896ccb59b3SSam Clegg SectionSymbol = SectionFunctions.find(&SecA)->second; 4904d57fbd0SSam Clegg else 4914d57fbd0SSam Clegg SectionSymbol = SecA.getBeginSymbol(); 4924d57fbd0SSam Clegg if (!SectionSymbol) 4934d57fbd0SSam Clegg report_fatal_error("section symbol is required for relocation"); 4944d57fbd0SSam Clegg 4954d57fbd0SSam Clegg C += Layout.getSymbolOffset(*SymA); 4964d57fbd0SSam Clegg SymA = cast<MCSymbolWasm>(SectionSymbol); 4974d57fbd0SSam Clegg } 4984d57fbd0SSam Clegg 499d1152a26SSam Clegg // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be 5004d57fbd0SSam Clegg // against a named symbol. 501d1152a26SSam Clegg if (Type != wasm::R_WASM_TYPE_INDEX_LEB) { 5024d57fbd0SSam Clegg if (SymA->getName().empty()) 5034d57fbd0SSam Clegg report_fatal_error("relocations against un-named temporaries are not yet " 5044d57fbd0SSam Clegg "supported by wasm"); 5054d57fbd0SSam Clegg 5064d57fbd0SSam Clegg SymA->setUsedInReloc(); 5074d57fbd0SSam Clegg } 508ae03c1e7SSam Clegg 509492f7529SSam Clegg if (RefA->getKind() == MCSymbolRefExpr::VK_GOT) 510492f7529SSam Clegg SymA->setUsedInGOT(); 511492f7529SSam Clegg 512d934cb88SDan Gohman WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 513d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 514d934cb88SDan Gohman 5156a31a0d6SSam Clegg if (FixupSection.isWasmData()) { 516d934cb88SDan Gohman DataRelocations.push_back(Rec); 5176a31a0d6SSam Clegg } else if (FixupSection.getKind().isText()) { 51812fd3da9SSam Clegg CodeRelocations.push_back(Rec); 5196a31a0d6SSam Clegg } else if (FixupSection.getKind().isMetadata()) { 5206a31a0d6SSam Clegg CustomSectionsRelocations[&FixupSection].push_back(Rec); 5216a31a0d6SSam Clegg } else { 52212fd3da9SSam Clegg llvm_unreachable("unexpected section type"); 523d934cb88SDan Gohman } 5246a31a0d6SSam Clegg } 525d934cb88SDan Gohman 526d934cb88SDan Gohman // Compute a value to write into the code at the location covered 52760ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves 52860ec3034SSam Clegg // to make the object format more readable and more likely to be directly 52960ec3034SSam Clegg // useable. 5303b29376eSWouter van Oortmerssen uint64_t 5317ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry, 5327ee758d6SSam Clegg const MCAsmLayout &Layout) { 53348139ebcSWouter van Oortmerssen if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB || 53448139ebcSWouter van Oortmerssen RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) && 53548139ebcSWouter van Oortmerssen !RelEntry.Symbol->isGlobal()) { 536492f7529SSam Clegg assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space"); 537492f7529SSam Clegg return GOTIndices[RelEntry.Symbol]; 538492f7529SSam Clegg } 539492f7529SSam Clegg 54060ec3034SSam Clegg switch (RelEntry.Type) { 5412a7cac93SSam Clegg case wasm::R_WASM_TABLE_INDEX_REL_SLEB: 542d1152a26SSam Clegg case wasm::R_WASM_TABLE_INDEX_SLEB: 543cc1b9b68SWouter van Oortmerssen case wasm::R_WASM_TABLE_INDEX_SLEB64: 544cc1b9b68SWouter van Oortmerssen case wasm::R_WASM_TABLE_INDEX_I32: 545cc1b9b68SWouter van Oortmerssen case wasm::R_WASM_TABLE_INDEX_I64: { 546f9edbe95SSam Clegg // Provisional value is table address of the resolved symbol itself 5477ee758d6SSam Clegg const MCSymbolWasm *Base = 5487ee758d6SSam Clegg cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol)); 5497ee758d6SSam Clegg assert(Base->isFunction()); 55081443ac1SSam Clegg if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB) 5517ee758d6SSam Clegg return TableIndices[Base] - InitialTableOffset; 55281443ac1SSam Clegg else 5537ee758d6SSam Clegg return TableIndices[Base]; 554f9edbe95SSam Clegg } 555d1152a26SSam Clegg case wasm::R_WASM_TYPE_INDEX_LEB: 5566c899ba6SSam Clegg // Provisional value is same as the index 55760ec3034SSam Clegg return getRelocationIndexValue(RelEntry); 558d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_INDEX_LEB: 559d1152a26SSam Clegg case wasm::R_WASM_GLOBAL_INDEX_LEB: 56048139ebcSWouter van Oortmerssen case wasm::R_WASM_GLOBAL_INDEX_I32: 561d1152a26SSam Clegg case wasm::R_WASM_EVENT_INDEX_LEB: 562*69e2797eSPaulo Matos case wasm::R_WASM_TABLE_NUMBER_LEB: 563da419bdbSHeejin Ahn // Provisional value is function/global/event Wasm index 564492f7529SSam Clegg assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space"); 5656c899ba6SSam Clegg return WasmIndices[RelEntry.Symbol]; 566d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_OFFSET_I32: 567d1152a26SSam Clegg case wasm::R_WASM_SECTION_OFFSET_I32: { 5686a31a0d6SSam Clegg const auto &Section = 5696a31a0d6SSam Clegg static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection()); 5706a31a0d6SSam Clegg return Section.getSectionOffset() + RelEntry.Addend; 5716a31a0d6SSam Clegg } 572d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_LEB: 5733b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_LEB64: 5743b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_SLEB: 5753b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_SLEB64: 5762a7cac93SSam Clegg case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 5773b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64: 5783b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_I32: 5793b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_I64: { 5809c7b5808SDominic Chen // Provisional value is address of the global plus the offset 5817ee758d6SSam Clegg const MCSymbolWasm *Base = 5827ee758d6SSam Clegg cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol)); 583270ed1b3SSam Clegg // For undefined symbols, use zero 5847ee758d6SSam Clegg if (!Base->isDefined()) 585270ed1b3SSam Clegg return 0; 5869c7b5808SDominic Chen const wasm::WasmDataReference &BaseRef = DataLocations[Base], 5879c7b5808SDominic Chen &SymRef = DataLocations[RelEntry.Symbol]; 5889c7b5808SDominic Chen const WasmDataSegment &Segment = DataSegments[BaseRef.Segment]; 589d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 5909c7b5808SDominic Chen return Segment.Offset + BaseRef.Offset + SymRef.Offset + RelEntry.Addend; 59160ec3034SSam Clegg } 59260ec3034SSam Clegg default: 59360ec3034SSam Clegg llvm_unreachable("invalid relocation type"); 59460ec3034SSam Clegg } 595d934cb88SDan Gohman } 596d934cb88SDan Gohman 597759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes, 59863ebb813SSam Clegg MCSectionWasm &DataSection) { 5997d1ff446SFangrui Song LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n"); 600759631c7SSam Clegg 60163ebb813SSam Clegg DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 60263ebb813SSam Clegg 603759631c7SSam Clegg for (const MCFragment &Frag : DataSection) { 604759631c7SSam Clegg if (Frag.hasInstructions()) 605759631c7SSam Clegg report_fatal_error("only data supported in data sections"); 606759631c7SSam Clegg 607759631c7SSam Clegg if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 608759631c7SSam Clegg if (Align->getValueSize() != 1) 609759631c7SSam Clegg report_fatal_error("only byte values supported for alignment"); 610759631c7SSam Clegg // If nops are requested, use zeros, as this is the data section. 611759631c7SSam Clegg uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 612f208f631SHeejin Ahn uint64_t Size = 613f208f631SHeejin Ahn std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()), 614f208f631SHeejin Ahn DataBytes.size() + Align->getMaxBytesToEmit()); 615759631c7SSam Clegg DataBytes.resize(Size, Value); 616759631c7SSam Clegg } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 617588fad4dSNirav Dave int64_t NumValues; 618588fad4dSNirav Dave if (!Fill->getNumValues().evaluateAsAbsolute(NumValues)) 619d707c370SRafael Espindola llvm_unreachable("The fill should be an assembler constant"); 620588fad4dSNirav Dave DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues, 621588fad4dSNirav Dave Fill->getValue()); 62224faf859SHeejin Ahn } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) { 62324faf859SHeejin Ahn const SmallVectorImpl<char> &Contents = LEB->getContents(); 62424faf859SHeejin Ahn DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 625759631c7SSam Clegg } else { 626759631c7SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 627759631c7SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 628759631c7SSam Clegg DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 629759631c7SSam Clegg } 630759631c7SSam Clegg } 631759631c7SSam Clegg 632d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 633759631c7SSam Clegg } 634759631c7SSam Clegg 63560ec3034SSam Clegg uint32_t 63660ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) { 637d1152a26SSam Clegg if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) { 638b7787fd0SSam Clegg if (!TypeIndices.count(RelEntry.Symbol)) 639b7787fd0SSam Clegg report_fatal_error("symbol not found in type index space: " + 640b7787fd0SSam Clegg RelEntry.Symbol->getName()); 641acd7d2b0SSam Clegg return TypeIndices[RelEntry.Symbol]; 642acd7d2b0SSam Clegg } 64360ec3034SSam Clegg 64425d8e68bSSam Clegg return RelEntry.Symbol->getIndex(); 645acd7d2b0SSam Clegg } 646acd7d2b0SSam Clegg 647d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 648d934cb88SDan Gohman // directly. 649acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations( 6507ee758d6SSam Clegg ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset, 6517ee758d6SSam Clegg const MCAsmLayout &Layout) { 6520ff28fa6SDerek Schuff auto &Stream = static_cast<raw_pwrite_stream &>(W->OS); 653d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 654d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 655d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 656d934cb88SDan Gohman RelEntry.Offset; 657d934cb88SDan Gohman 658d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 6597ee758d6SSam Clegg auto Value = getProvisionalValue(RelEntry, Layout); 66060ec3034SSam Clegg 661acd7d2b0SSam Clegg switch (RelEntry.Type) { 662d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_INDEX_LEB: 663d1152a26SSam Clegg case wasm::R_WASM_TYPE_INDEX_LEB: 664d1152a26SSam Clegg case wasm::R_WASM_GLOBAL_INDEX_LEB: 665d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_LEB: 666d1152a26SSam Clegg case wasm::R_WASM_EVENT_INDEX_LEB: 667*69e2797eSPaulo Matos case wasm::R_WASM_TABLE_NUMBER_LEB: 6683b29376eSWouter van Oortmerssen writePatchableLEB<5>(Stream, Value, Offset); 6693b29376eSWouter van Oortmerssen break; 6703b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_LEB64: 6713b29376eSWouter van Oortmerssen writePatchableLEB<10>(Stream, Value, Offset); 672d934cb88SDan Gohman break; 673d1152a26SSam Clegg case wasm::R_WASM_TABLE_INDEX_I32: 674d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_I32: 675d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_OFFSET_I32: 676d1152a26SSam Clegg case wasm::R_WASM_SECTION_OFFSET_I32: 67748139ebcSWouter van Oortmerssen case wasm::R_WASM_GLOBAL_INDEX_I32: 6780a6c4d8dSSam Clegg patchI32(Stream, Value, Offset); 679d934cb88SDan Gohman break; 680cc1b9b68SWouter van Oortmerssen case wasm::R_WASM_TABLE_INDEX_I64: 6813b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_I64: 6823b29376eSWouter van Oortmerssen patchI64(Stream, Value, Offset); 6833b29376eSWouter van Oortmerssen break; 684d1152a26SSam Clegg case wasm::R_WASM_TABLE_INDEX_SLEB: 6852a7cac93SSam Clegg case wasm::R_WASM_TABLE_INDEX_REL_SLEB: 686d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_SLEB: 6872a7cac93SSam Clegg case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 6883b29376eSWouter van Oortmerssen writePatchableSLEB<5>(Stream, Value, Offset); 6893b29376eSWouter van Oortmerssen break; 690cc1b9b68SWouter van Oortmerssen case wasm::R_WASM_TABLE_INDEX_SLEB64: 6913b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_SLEB64: 6923b29376eSWouter van Oortmerssen case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64: 6933b29376eSWouter van Oortmerssen writePatchableSLEB<10>(Stream, Value, Offset); 69460ec3034SSam Clegg break; 695d934cb88SDan Gohman default: 6969d24fb7fSSam Clegg llvm_unreachable("invalid relocation type"); 697d934cb88SDan Gohman } 698d934cb88SDan Gohman } 69918eafb6cSDan Gohman } 70018eafb6cSDan Gohman 7014c41fb5aSHeejin Ahn void WasmObjectWriter::writeTypeSection( 7024c41fb5aSHeejin Ahn ArrayRef<wasm::WasmSignature> Signatures) { 703da419bdbSHeejin Ahn if (Signatures.empty()) 7049e15f359SSam Clegg return; 7059e15f359SSam Clegg 7069e15f359SSam Clegg SectionBookkeeping Section; 7079e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TYPE); 7089e15f359SSam Clegg 7090ff28fa6SDerek Schuff encodeULEB128(Signatures.size(), W->OS); 7109e15f359SSam Clegg 7114c41fb5aSHeejin Ahn for (const wasm::WasmSignature &Sig : Signatures) { 7120ff28fa6SDerek Schuff W->OS << char(wasm::WASM_TYPE_FUNC); 7130ff28fa6SDerek Schuff encodeULEB128(Sig.Params.size(), W->OS); 714da419bdbSHeejin Ahn for (wasm::ValType Ty : Sig.Params) 7159e15f359SSam Clegg writeValueType(Ty); 7160ff28fa6SDerek Schuff encodeULEB128(Sig.Returns.size(), W->OS); 717da419bdbSHeejin Ahn for (wasm::ValType Ty : Sig.Returns) 7189e15f359SSam Clegg writeValueType(Ty); 7199e15f359SSam Clegg } 7209e15f359SSam Clegg 7219e15f359SSam Clegg endSection(Section); 7229e15f359SSam Clegg } 7239e15f359SSam Clegg 7248defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports, 7254d135b04SWouter van Oortmerssen uint64_t DataSize, 726f950b24aSSam Clegg uint32_t NumElements) { 7279e15f359SSam Clegg if (Imports.empty()) 7289e15f359SSam Clegg return; 7299e15f359SSam Clegg 7304d135b04SWouter van Oortmerssen uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 731f950b24aSSam Clegg 7329e15f359SSam Clegg SectionBookkeeping Section; 7339e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_IMPORT); 7349e15f359SSam Clegg 7350ff28fa6SDerek Schuff encodeULEB128(Imports.size(), W->OS); 7368defa952SSam Clegg for (const wasm::WasmImport &Import : Imports) { 7378defa952SSam Clegg writeString(Import.Module); 7388defa952SSam Clegg writeString(Import.Field); 7390ff28fa6SDerek Schuff W->OS << char(Import.Kind); 7409e15f359SSam Clegg 7419e15f359SSam Clegg switch (Import.Kind) { 7429e15f359SSam Clegg case wasm::WASM_EXTERNAL_FUNCTION: 7430ff28fa6SDerek Schuff encodeULEB128(Import.SigIndex, W->OS); 7449e15f359SSam Clegg break; 7459e15f359SSam Clegg case wasm::WASM_EXTERNAL_GLOBAL: 7460ff28fa6SDerek Schuff W->OS << char(Import.Global.Type); 7470ff28fa6SDerek Schuff W->OS << char(Import.Global.Mutable ? 1 : 0); 7489e15f359SSam Clegg break; 749f950b24aSSam Clegg case wasm::WASM_EXTERNAL_MEMORY: 7500ff28fa6SDerek Schuff encodeULEB128(Import.Memory.Flags, W->OS); 7510ff28fa6SDerek Schuff encodeULEB128(NumPages, W->OS); // initial 752f950b24aSSam Clegg break; 753f950b24aSSam Clegg case wasm::WASM_EXTERNAL_TABLE: 7540ff28fa6SDerek Schuff W->OS << char(Import.Table.ElemType); 7550ff28fa6SDerek Schuff encodeULEB128(0, W->OS); // flags 7560ff28fa6SDerek Schuff encodeULEB128(NumElements, W->OS); // initial 757f950b24aSSam Clegg break; 758da419bdbSHeejin Ahn case wasm::WASM_EXTERNAL_EVENT: 7590ff28fa6SDerek Schuff encodeULEB128(Import.Event.Attribute, W->OS); 7600ff28fa6SDerek Schuff encodeULEB128(Import.Event.SigIndex, W->OS); 761da419bdbSHeejin Ahn break; 7629e15f359SSam Clegg default: 7639e15f359SSam Clegg llvm_unreachable("unsupported import kind"); 7649e15f359SSam Clegg } 7659e15f359SSam Clegg } 7669e15f359SSam Clegg 7679e15f359SSam Clegg endSection(Section); 7689e15f359SSam Clegg } 7699e15f359SSam Clegg 770457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 7719e15f359SSam Clegg if (Functions.empty()) 7729e15f359SSam Clegg return; 7739e15f359SSam Clegg 7749e15f359SSam Clegg SectionBookkeeping Section; 7759e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_FUNCTION); 7769e15f359SSam Clegg 7770ff28fa6SDerek Schuff encodeULEB128(Functions.size(), W->OS); 7789e15f359SSam Clegg for (const WasmFunction &Func : Functions) 7790ff28fa6SDerek Schuff encodeULEB128(Func.SigIndex, W->OS); 7809e15f359SSam Clegg 7819e15f359SSam Clegg endSection(Section); 7829e15f359SSam Clegg } 7839e15f359SSam Clegg 784da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) { 785da419bdbSHeejin Ahn if (Events.empty()) 786da419bdbSHeejin Ahn return; 787da419bdbSHeejin Ahn 788da419bdbSHeejin Ahn SectionBookkeeping Section; 789da419bdbSHeejin Ahn startSection(Section, wasm::WASM_SEC_EVENT); 790da419bdbSHeejin Ahn 7910ff28fa6SDerek Schuff encodeULEB128(Events.size(), W->OS); 792da419bdbSHeejin Ahn for (const wasm::WasmEventType &Event : Events) { 7930ff28fa6SDerek Schuff encodeULEB128(Event.Attribute, W->OS); 7940ff28fa6SDerek Schuff encodeULEB128(Event.SigIndex, W->OS); 795da419bdbSHeejin Ahn } 796da419bdbSHeejin Ahn 797da419bdbSHeejin Ahn endSection(Section); 798da419bdbSHeejin Ahn } 799da419bdbSHeejin Ahn 8000a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) { 8010a6c4d8dSSam Clegg if (Globals.empty()) 8020a6c4d8dSSam Clegg return; 8030a6c4d8dSSam Clegg 8040a6c4d8dSSam Clegg SectionBookkeeping Section; 8050a6c4d8dSSam Clegg startSection(Section, wasm::WASM_SEC_GLOBAL); 8060a6c4d8dSSam Clegg 8070ff28fa6SDerek Schuff encodeULEB128(Globals.size(), W->OS); 8080a6c4d8dSSam Clegg for (const wasm::WasmGlobal &Global : Globals) { 8090ff28fa6SDerek Schuff encodeULEB128(Global.Type.Type, W->OS); 8100ff28fa6SDerek Schuff W->OS << char(Global.Type.Mutable); 8110ff28fa6SDerek Schuff W->OS << char(Global.InitExpr.Opcode); 8120a6c4d8dSSam Clegg switch (Global.Type.Type) { 8130a6c4d8dSSam Clegg case wasm::WASM_TYPE_I32: 8140ff28fa6SDerek Schuff encodeSLEB128(0, W->OS); 8150a6c4d8dSSam Clegg break; 8160a6c4d8dSSam Clegg case wasm::WASM_TYPE_I64: 8170ff28fa6SDerek Schuff encodeSLEB128(0, W->OS); 8180a6c4d8dSSam Clegg break; 8190a6c4d8dSSam Clegg case wasm::WASM_TYPE_F32: 8200a6c4d8dSSam Clegg writeI32(0); 8210a6c4d8dSSam Clegg break; 8220a6c4d8dSSam Clegg case wasm::WASM_TYPE_F64: 8230a6c4d8dSSam Clegg writeI64(0); 8240a6c4d8dSSam Clegg break; 82579aad89dSSam Clegg case wasm::WASM_TYPE_EXTERNREF: 82679aad89dSSam Clegg writeValueType(wasm::ValType::EXTERNREF); 82779aad89dSSam Clegg break; 8280a6c4d8dSSam Clegg default: 8290a6c4d8dSSam Clegg llvm_unreachable("unexpected type"); 8300a6c4d8dSSam Clegg } 8310ff28fa6SDerek Schuff W->OS << char(wasm::WASM_OPCODE_END); 8320a6c4d8dSSam Clegg } 8330a6c4d8dSSam Clegg 8340a6c4d8dSSam Clegg endSection(Section); 8350a6c4d8dSSam Clegg } 8360a6c4d8dSSam Clegg 837388fb67bSPaulo Matos void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) { 838388fb67bSPaulo Matos if (Tables.empty()) 839388fb67bSPaulo Matos return; 840388fb67bSPaulo Matos 841388fb67bSPaulo Matos SectionBookkeeping Section; 842388fb67bSPaulo Matos startSection(Section, wasm::WASM_SEC_TABLE); 843388fb67bSPaulo Matos 844388fb67bSPaulo Matos encodeULEB128(Tables.size(), W->OS); 845388fb67bSPaulo Matos for (const wasm::WasmTable &Table : Tables) { 846388fb67bSPaulo Matos encodeULEB128(Table.ElemType, W->OS); 847388fb67bSPaulo Matos encodeULEB128(Table.Limits.Flags, W->OS); 848388fb67bSPaulo Matos encodeULEB128(Table.Limits.Initial, W->OS); 849388fb67bSPaulo Matos if (Table.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX) 850388fb67bSPaulo Matos encodeULEB128(Table.Limits.Maximum, W->OS); 851388fb67bSPaulo Matos } 852388fb67bSPaulo Matos endSection(Section); 853388fb67bSPaulo Matos } 854388fb67bSPaulo Matos 8558defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) { 8569e15f359SSam Clegg if (Exports.empty()) 8579e15f359SSam Clegg return; 8589e15f359SSam Clegg 8599e15f359SSam Clegg SectionBookkeeping Section; 8609e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_EXPORT); 8619e15f359SSam Clegg 8620ff28fa6SDerek Schuff encodeULEB128(Exports.size(), W->OS); 8638defa952SSam Clegg for (const wasm::WasmExport &Export : Exports) { 8648defa952SSam Clegg writeString(Export.Name); 8650ff28fa6SDerek Schuff W->OS << char(Export.Kind); 8660ff28fa6SDerek Schuff encodeULEB128(Export.Index, W->OS); 8679e15f359SSam Clegg } 8689e15f359SSam Clegg 8699e15f359SSam Clegg endSection(Section); 8709e15f359SSam Clegg } 8719e15f359SSam Clegg 872457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 8739e15f359SSam Clegg if (TableElems.empty()) 8749e15f359SSam Clegg return; 8759e15f359SSam Clegg 8769e15f359SSam Clegg SectionBookkeeping Section; 8779e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_ELEM); 8789e15f359SSam Clegg 8790ff28fa6SDerek Schuff encodeULEB128(1, W->OS); // number of "segments" 8800ff28fa6SDerek Schuff encodeULEB128(0, W->OS); // the table index 8819e15f359SSam Clegg 8829e15f359SSam Clegg // init expr for starting offset 8830ff28fa6SDerek Schuff W->OS << char(wasm::WASM_OPCODE_I32_CONST); 8840ff28fa6SDerek Schuff encodeSLEB128(InitialTableOffset, W->OS); 8850ff28fa6SDerek Schuff W->OS << char(wasm::WASM_OPCODE_END); 8869e15f359SSam Clegg 8870ff28fa6SDerek Schuff encodeULEB128(TableElems.size(), W->OS); 8889e15f359SSam Clegg for (uint32_t Elem : TableElems) 8890ff28fa6SDerek Schuff encodeULEB128(Elem, W->OS); 8909e15f359SSam Clegg 8919e15f359SSam Clegg endSection(Section); 8929e15f359SSam Clegg } 8939e15f359SSam Clegg 894fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() { 895fef8de66SThomas Lively if (DataSegments.empty()) 896fef8de66SThomas Lively return; 897fef8de66SThomas Lively 898fef8de66SThomas Lively SectionBookkeeping Section; 899fef8de66SThomas Lively startSection(Section, wasm::WASM_SEC_DATACOUNT); 9000ff28fa6SDerek Schuff encodeULEB128(DataSegments.size(), W->OS); 901fef8de66SThomas Lively endSection(Section); 902fef8de66SThomas Lively } 903fef8de66SThomas Lively 904e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 905457fb0b4SSam Clegg const MCAsmLayout &Layout, 906457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions) { 9079e15f359SSam Clegg if (Functions.empty()) 908e49584a3SSam Clegg return 0; 9099e15f359SSam Clegg 9109e15f359SSam Clegg SectionBookkeeping Section; 9119e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CODE); 9129e15f359SSam Clegg 9130ff28fa6SDerek Schuff encodeULEB128(Functions.size(), W->OS); 9149e15f359SSam Clegg 9159e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 916fe6414b0SSam Clegg auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 9179e15f359SSam Clegg 9189e15f359SSam Clegg int64_t Size = 0; 9199e15f359SSam Clegg if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 9209e15f359SSam Clegg report_fatal_error(".size expression must be evaluatable"); 9219e15f359SSam Clegg 9220ff28fa6SDerek Schuff encodeULEB128(Size, W->OS); 9230ff28fa6SDerek Schuff FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset); 9240ff28fa6SDerek Schuff Asm.writeSectionData(W->OS, &FuncSection, Layout); 9259e15f359SSam Clegg } 9269e15f359SSam Clegg 9279e15f359SSam Clegg // Apply fixups. 9287ee758d6SSam Clegg applyRelocations(CodeRelocations, Section.ContentsOffset, Layout); 9299e15f359SSam Clegg 9309e15f359SSam Clegg endSection(Section); 931e49584a3SSam Clegg return Section.Index; 9329e15f359SSam Clegg } 9339e15f359SSam Clegg 934e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) { 9356c899ba6SSam Clegg if (DataSegments.empty()) 936e49584a3SSam Clegg return 0; 9379e15f359SSam Clegg 9389e15f359SSam Clegg SectionBookkeeping Section; 9399e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_DATA); 9409e15f359SSam Clegg 9410ff28fa6SDerek Schuff encodeULEB128(DataSegments.size(), W->OS); // count 9427c395943SSam Clegg 9436c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 9440ff28fa6SDerek Schuff encodeULEB128(Segment.InitFlags, W->OS); // flags 9452e150409SThomas Lively if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX) 9460ff28fa6SDerek Schuff encodeULEB128(0, W->OS); // memory index 9472e150409SThomas Lively if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) { 9480ff28fa6SDerek Schuff W->OS << char(Segment.Offset > INT32_MAX ? wasm::WASM_OPCODE_I64_CONST 9494d135b04SWouter van Oortmerssen : wasm::WASM_OPCODE_I32_CONST); 9500ff28fa6SDerek Schuff encodeSLEB128(Segment.Offset, W->OS); // offset 9510ff28fa6SDerek Schuff W->OS << char(wasm::WASM_OPCODE_END); 9522e150409SThomas Lively } 9530ff28fa6SDerek Schuff encodeULEB128(Segment.Data.size(), W->OS); // size 9540ff28fa6SDerek Schuff Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset); 9550ff28fa6SDerek Schuff W->OS << Segment.Data; // data 9567c395943SSam Clegg } 9579e15f359SSam Clegg 9589e15f359SSam Clegg // Apply fixups. 9597ee758d6SSam Clegg applyRelocations(DataRelocations, Section.ContentsOffset, Layout); 9609e15f359SSam Clegg 9619e15f359SSam Clegg endSection(Section); 962e49584a3SSam Clegg return Section.Index; 9639e15f359SSam Clegg } 9649e15f359SSam Clegg 9656f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection( 9666f08c84aSSam Clegg uint32_t SectionIndex, StringRef Name, 967f77dc2a8SSam Clegg std::vector<WasmRelocationEntry> &Relocs) { 9689e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 9699e15f359SSam Clegg // for descriptions of the reloc sections. 9709e15f359SSam Clegg 971f77dc2a8SSam Clegg if (Relocs.empty()) 9729e15f359SSam Clegg return; 9739e15f359SSam Clegg 974f77dc2a8SSam Clegg // First, ensure the relocations are sorted in offset order. In general they 975f77dc2a8SSam Clegg // should already be sorted since `recordRelocation` is called in offset 976f77dc2a8SSam Clegg // order, but for the code section we combine many MC sections into single 977f77dc2a8SSam Clegg // wasm section, and this order is determined by the order of Asm.Symbols() 978f77dc2a8SSam Clegg // not the sections order. 979efd94c56SFangrui Song llvm::stable_sort( 980efd94c56SFangrui Song Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) { 981f77dc2a8SSam Clegg return (A.Offset + A.FixupSection->getSectionOffset()) < 982f77dc2a8SSam Clegg (B.Offset + B.FixupSection->getSectionOffset()); 983f77dc2a8SSam Clegg }); 984f77dc2a8SSam Clegg 9859e15f359SSam Clegg SectionBookkeeping Section; 9866f08c84aSSam Clegg startCustomSection(Section, std::string("reloc.") + Name.str()); 9879e15f359SSam Clegg 9880ff28fa6SDerek Schuff encodeULEB128(SectionIndex, W->OS); 9890ff28fa6SDerek Schuff encodeULEB128(Relocs.size(), W->OS); 990f77dc2a8SSam Clegg for (const WasmRelocationEntry &RelEntry : Relocs) { 991f208f631SHeejin Ahn uint64_t Offset = 992f208f631SHeejin Ahn RelEntry.Offset + RelEntry.FixupSection->getSectionOffset(); 9936f08c84aSSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 9949e15f359SSam Clegg 9950ff28fa6SDerek Schuff W->OS << char(RelEntry.Type); 9960ff28fa6SDerek Schuff encodeULEB128(Offset, W->OS); 9970ff28fa6SDerek Schuff encodeULEB128(Index, W->OS); 9986f08c84aSSam Clegg if (RelEntry.hasAddend()) 9990ff28fa6SDerek Schuff encodeSLEB128(RelEntry.Addend, W->OS); 10009e15f359SSam Clegg } 10019e15f359SSam Clegg 10029e15f359SSam Clegg endSection(Section); 10039e15f359SSam Clegg } 10049e15f359SSam Clegg 10056a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() { 10066a31a0d6SSam Clegg for (const auto &Sec : CustomSections) { 10076a31a0d6SSam Clegg auto &Relocations = CustomSectionsRelocations[Sec.Section]; 10086a31a0d6SSam Clegg writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations); 10096a31a0d6SSam Clegg } 10106a31a0d6SSam Clegg } 10116a31a0d6SSam Clegg 10129e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection( 101386b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 1014ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 1015ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) { 10169e15f359SSam Clegg SectionBookkeeping Section; 10172322a937SSam Clegg startCustomSection(Section, "linking"); 10180ff28fa6SDerek Schuff encodeULEB128(wasm::WasmMetadataVersion, W->OS); 10199e15f359SSam Clegg 10206bb5a41fSSam Clegg SectionBookkeeping SubSection; 10216c899ba6SSam Clegg if (SymbolInfos.size() != 0) { 10226c899ba6SSam Clegg startSection(SubSection, wasm::WASM_SYMBOL_TABLE); 10230ff28fa6SDerek Schuff encodeULEB128(SymbolInfos.size(), W->OS); 10246c899ba6SSam Clegg for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) { 10250ff28fa6SDerek Schuff encodeULEB128(Sym.Kind, W->OS); 10260ff28fa6SDerek Schuff encodeULEB128(Sym.Flags, W->OS); 10276c899ba6SSam Clegg switch (Sym.Kind) { 10286c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_FUNCTION: 10296c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1030da419bdbSHeejin Ahn case wasm::WASM_SYMBOL_TYPE_EVENT: 1031388fb67bSPaulo Matos case wasm::WASM_SYMBOL_TYPE_TABLE: 10320ff28fa6SDerek Schuff encodeULEB128(Sym.ElementIndex, W->OS); 103329874ceaSDan Gohman if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 || 103429874ceaSDan Gohman (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) 10356c899ba6SSam Clegg writeString(Sym.Name); 10366c899ba6SSam Clegg break; 10376c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_DATA: 10386c899ba6SSam Clegg writeString(Sym.Name); 10396c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) { 10400ff28fa6SDerek Schuff encodeULEB128(Sym.DataRef.Segment, W->OS); 10410ff28fa6SDerek Schuff encodeULEB128(Sym.DataRef.Offset, W->OS); 10420ff28fa6SDerek Schuff encodeULEB128(Sym.DataRef.Size, W->OS); 10436c899ba6SSam Clegg } 10446c899ba6SSam Clegg break; 10456a31a0d6SSam Clegg case wasm::WASM_SYMBOL_TYPE_SECTION: { 10466a31a0d6SSam Clegg const uint32_t SectionIndex = 10476a31a0d6SSam Clegg CustomSections[Sym.ElementIndex].OutputIndex; 10480ff28fa6SDerek Schuff encodeULEB128(SectionIndex, W->OS); 10496a31a0d6SSam Clegg break; 10506a31a0d6SSam Clegg } 10516c899ba6SSam Clegg default: 10526c899ba6SSam Clegg llvm_unreachable("unexpected kind"); 10536c899ba6SSam Clegg } 1054b7787fd0SSam Clegg } 1055b7787fd0SSam Clegg endSection(SubSection); 1056b7787fd0SSam Clegg } 10579e15f359SSam Clegg 10586c899ba6SSam Clegg if (DataSegments.size()) { 105963ebb813SSam Clegg startSection(SubSection, wasm::WASM_SEGMENT_INFO); 10600ff28fa6SDerek Schuff encodeULEB128(DataSegments.size(), W->OS); 10616c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 1062d95ed959SSam Clegg writeString(Segment.Name); 10630ff28fa6SDerek Schuff encodeULEB128(Segment.Alignment, W->OS); 10640ff28fa6SDerek Schuff encodeULEB128(Segment.LinkerFlags, W->OS); 106563ebb813SSam Clegg } 1066d95ed959SSam Clegg endSection(SubSection); 1067d95ed959SSam Clegg } 1068d95ed959SSam Clegg 1069bafe6902SSam Clegg if (!InitFuncs.empty()) { 1070bafe6902SSam Clegg startSection(SubSection, wasm::WASM_INIT_FUNCS); 10710ff28fa6SDerek Schuff encodeULEB128(InitFuncs.size(), W->OS); 1072bafe6902SSam Clegg for (auto &StartFunc : InitFuncs) { 10730ff28fa6SDerek Schuff encodeULEB128(StartFunc.first, W->OS); // priority 10740ff28fa6SDerek Schuff encodeULEB128(StartFunc.second, W->OS); // function index 1075bafe6902SSam Clegg } 1076bafe6902SSam Clegg endSection(SubSection); 1077bafe6902SSam Clegg } 1078bafe6902SSam Clegg 1079ea7caceeSSam Clegg if (Comdats.size()) { 1080ea7caceeSSam Clegg startSection(SubSection, wasm::WASM_COMDAT_INFO); 10810ff28fa6SDerek Schuff encodeULEB128(Comdats.size(), W->OS); 1082ea7caceeSSam Clegg for (const auto &C : Comdats) { 1083ea7caceeSSam Clegg writeString(C.first); 10840ff28fa6SDerek Schuff encodeULEB128(0, W->OS); // flags for future use 10850ff28fa6SDerek Schuff encodeULEB128(C.second.size(), W->OS); 1086ea7caceeSSam Clegg for (const WasmComdatEntry &Entry : C.second) { 10870ff28fa6SDerek Schuff encodeULEB128(Entry.Kind, W->OS); 10880ff28fa6SDerek Schuff encodeULEB128(Entry.Index, W->OS); 1089ea7caceeSSam Clegg } 1090ea7caceeSSam Clegg } 1091ea7caceeSSam Clegg endSection(SubSection); 1092ea7caceeSSam Clegg } 1093ea7caceeSSam Clegg 10949e15f359SSam Clegg endSection(Section); 10959e15f359SSam Clegg } 10969e15f359SSam Clegg 1097cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection, 1098cbda16ebSThomas Lively const MCAssembler &Asm, 10996a31a0d6SSam Clegg const MCAsmLayout &Layout) { 1100cfd44a2eSSam Clegg SectionBookkeeping Section; 11016a31a0d6SSam Clegg auto *Sec = CustomSection.Section; 11022322a937SSam Clegg startCustomSection(Section, CustomSection.Name); 11036a31a0d6SSam Clegg 11040ff28fa6SDerek Schuff Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset); 11050ff28fa6SDerek Schuff Asm.writeSectionData(W->OS, Sec, Layout); 11066a31a0d6SSam Clegg 11076a31a0d6SSam Clegg CustomSection.OutputContentsOffset = Section.ContentsOffset; 11086a31a0d6SSam Clegg CustomSection.OutputIndex = Section.Index; 11096a31a0d6SSam Clegg 1110cfd44a2eSSam Clegg endSection(Section); 11116a31a0d6SSam Clegg 11126a31a0d6SSam Clegg // Apply fixups. 11134d57fbd0SSam Clegg auto &Relocations = CustomSectionsRelocations[CustomSection.Section]; 11147ee758d6SSam Clegg applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout); 11156a31a0d6SSam Clegg } 11166a31a0d6SSam Clegg 11175e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) { 11185e3d33a7SSam Clegg assert(Symbol.isFunction()); 11195e3d33a7SSam Clegg assert(TypeIndices.count(&Symbol)); 11205e3d33a7SSam Clegg return TypeIndices[&Symbol]; 11215e3d33a7SSam Clegg } 11225e3d33a7SSam Clegg 1123da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) { 1124da419bdbSHeejin Ahn assert(Symbol.isEvent()); 1125da419bdbSHeejin Ahn assert(TypeIndices.count(&Symbol)); 1126da419bdbSHeejin Ahn return TypeIndices[&Symbol]; 1127da419bdbSHeejin Ahn } 1128da419bdbSHeejin Ahn 112938b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) { 11305e3d33a7SSam Clegg assert(Symbol.isFunction()); 11315e3d33a7SSam Clegg 11324c41fb5aSHeejin Ahn wasm::WasmSignature S; 11337ee758d6SSam Clegg 11347ee758d6SSam Clegg if (auto *Sig = Symbol.getSignature()) { 1135da419bdbSHeejin Ahn S.Returns = Sig->Returns; 1136da419bdbSHeejin Ahn S.Params = Sig->Params; 113777a7a380SDerek Schuff } 11385e3d33a7SSam Clegg 1139da419bdbSHeejin Ahn auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 11405e3d33a7SSam Clegg if (Pair.second) 1141da419bdbSHeejin Ahn Signatures.push_back(S); 11425e3d33a7SSam Clegg TypeIndices[&Symbol] = Pair.first->second; 11435e3d33a7SSam Clegg 1144d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol 1145d34e60caSNicola Zaghen << " new:" << Pair.second << "\n"); 1146d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 11475e3d33a7SSam Clegg } 11485e3d33a7SSam Clegg 114938b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) { 1150da419bdbSHeejin Ahn assert(Symbol.isEvent()); 1151da419bdbSHeejin Ahn 1152da419bdbSHeejin Ahn // TODO Currently we don't generate imported exceptions, but if we do, we 1153da419bdbSHeejin Ahn // should have a way of infering types of imported exceptions. 11544c41fb5aSHeejin Ahn wasm::WasmSignature S; 1155da419bdbSHeejin Ahn if (auto *Sig = Symbol.getSignature()) { 1156da419bdbSHeejin Ahn S.Returns = Sig->Returns; 1157da419bdbSHeejin Ahn S.Params = Sig->Params; 1158da419bdbSHeejin Ahn } 1159da419bdbSHeejin Ahn 1160da419bdbSHeejin Ahn auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 1161da419bdbSHeejin Ahn if (Pair.second) 1162da419bdbSHeejin Ahn Signatures.push_back(S); 1163da419bdbSHeejin Ahn TypeIndices[&Symbol] = Pair.first->second; 1164da419bdbSHeejin Ahn 1165da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second 1166da419bdbSHeejin Ahn << "\n"); 1167da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 1168da419bdbSHeejin Ahn } 1169da419bdbSHeejin Ahn 11704d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) { 11713ea1c62cSSam Clegg if (Sym.isUsedInReloc() || Sym.isUsedInInitArray()) 11724d57fbd0SSam Clegg return true; 11734d57fbd0SSam Clegg 11744d57fbd0SSam Clegg if (Sym.isComdat() && !Sym.isDefined()) 11754d57fbd0SSam Clegg return false; 11764d57fbd0SSam Clegg 11773ea1c62cSSam Clegg if (Sym.isTemporary()) 11784d57fbd0SSam Clegg return false; 11794d57fbd0SSam Clegg 11804d57fbd0SSam Clegg if (Sym.isSection()) 11814d57fbd0SSam Clegg return false; 11824d57fbd0SSam Clegg 11834d57fbd0SSam Clegg return true; 11844d57fbd0SSam Clegg } 11850ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports( 11860ff28fa6SDerek Schuff SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm, 118718eafb6cSDan Gohman const MCAsmLayout &Layout) { 1188f950b24aSSam Clegg // For now, always emit the memory import, since loads and stores are not 1189f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1190f950b24aSSam Clegg // it if there are no loads or stores. 11918defa952SSam Clegg wasm::WasmImport MemImport; 11921ed3a046SSam Clegg MemImport.Module = "env"; 11931ed3a046SSam Clegg MemImport.Field = "__linear_memory"; 1194f950b24aSSam Clegg MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1195fd0964aeSWouter van Oortmerssen MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64 1196fd0964aeSWouter van Oortmerssen : wasm::WASM_LIMITS_FLAG_NONE; 1197f950b24aSSam Clegg Imports.push_back(MemImport); 1198f950b24aSSam Clegg 1199f950b24aSSam Clegg // For now, always emit the table section, since indirect calls are not 1200f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1201f950b24aSSam Clegg // it if there are no indirect calls. 12028defa952SSam Clegg wasm::WasmImport TableImport; 12031ed3a046SSam Clegg TableImport.Module = "env"; 12041ed3a046SSam Clegg TableImport.Field = "__indirect_function_table"; 1205f950b24aSSam Clegg TableImport.Kind = wasm::WASM_EXTERNAL_TABLE; 12066a87ddacSThomas Lively TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF; 1207f950b24aSSam Clegg Imports.push_back(TableImport); 1208f950b24aSSam Clegg 1209da419bdbSHeejin Ahn // Populate SignatureIndices, and Imports and WasmIndices for undefined 1210586320c0SNicholas Wilson // symbols. This must be done before populating WasmIndices for defined 1211586320c0SNicholas Wilson // symbols. 121232ce5ca0SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 121332ce5ca0SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 121432ce5ca0SDan Gohman 121532ce5ca0SDan Gohman // Register types for all functions, including those with private linkage 12169f3fe42eSSam Clegg // (because wasm always needs a type signature). 12177ee758d6SSam Clegg if (WS.isFunction()) { 12189c7b5808SDominic Chen const auto *BS = Layout.getBaseSymbol(S); 12199c7b5808SDominic Chen if (!BS) 12209c7b5808SDominic Chen report_fatal_error(Twine(S.getName()) + 12219c7b5808SDominic Chen ": absolute addressing not supported!"); 12229c7b5808SDominic Chen registerFunctionType(*cast<MCSymbolWasm>(BS)); 12237ee758d6SSam Clegg } 122432ce5ca0SDan Gohman 1225da419bdbSHeejin Ahn if (WS.isEvent()) 1226da419bdbSHeejin Ahn registerEventType(WS); 1227da419bdbSHeejin Ahn 122832ce5ca0SDan Gohman if (WS.isTemporary()) 122932ce5ca0SDan Gohman continue; 123032ce5ca0SDan Gohman 123132ce5ca0SDan Gohman // If the symbol is not defined in this translation unit, import it. 12326c899ba6SSam Clegg if (!WS.isDefined() && !WS.isComdat()) { 12336c899ba6SSam Clegg if (WS.isFunction()) { 12348defa952SSam Clegg wasm::WasmImport Import; 1235f726e445SDan Gohman Import.Module = WS.getImportModule(); 1236f726e445SDan Gohman Import.Field = WS.getImportName(); 123732ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 12388defa952SSam Clegg Import.SigIndex = getFunctionType(WS); 12396c899ba6SSam Clegg Imports.push_back(Import); 1240492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 12416c899ba6SSam Clegg WasmIndices[&WS] = NumFunctionImports++; 12426c899ba6SSam Clegg } else if (WS.isGlobal()) { 124315f349f7SNicholas Wilson if (WS.isWeak()) 124415f349f7SNicholas Wilson report_fatal_error("undefined global symbol cannot be weak"); 124515f349f7SNicholas Wilson 12466c899ba6SSam Clegg wasm::WasmImport Import; 1247f726e445SDan Gohman Import.Field = WS.getImportName(); 124832ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1249492f7529SSam Clegg Import.Module = WS.getImportModule(); 12506c899ba6SSam Clegg Import.Global = WS.getGlobalType(); 12516c899ba6SSam Clegg Imports.push_back(Import); 1252492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 12536c899ba6SSam Clegg WasmIndices[&WS] = NumGlobalImports++; 1254da419bdbSHeejin Ahn } else if (WS.isEvent()) { 1255da419bdbSHeejin Ahn if (WS.isWeak()) 1256da419bdbSHeejin Ahn report_fatal_error("undefined event symbol cannot be weak"); 1257da419bdbSHeejin Ahn 1258da419bdbSHeejin Ahn wasm::WasmImport Import; 1259f726e445SDan Gohman Import.Module = WS.getImportModule(); 1260f726e445SDan Gohman Import.Field = WS.getImportName(); 1261da419bdbSHeejin Ahn Import.Kind = wasm::WASM_EXTERNAL_EVENT; 1262da419bdbSHeejin Ahn Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION; 1263da419bdbSHeejin Ahn Import.Event.SigIndex = getEventType(WS); 1264da419bdbSHeejin Ahn Imports.push_back(Import); 1265492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 1266da419bdbSHeejin Ahn WasmIndices[&WS] = NumEventImports++; 126732ce5ca0SDan Gohman } 126832ce5ca0SDan Gohman } 126932ce5ca0SDan Gohman } 127032ce5ca0SDan Gohman 1271492f7529SSam Clegg // Add imports for GOT globals 1272492f7529SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1273492f7529SSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 1274492f7529SSam Clegg if (WS.isUsedInGOT()) { 1275492f7529SSam Clegg wasm::WasmImport Import; 1276492f7529SSam Clegg if (WS.isFunction()) 1277492f7529SSam Clegg Import.Module = "GOT.func"; 1278492f7529SSam Clegg else 1279492f7529SSam Clegg Import.Module = "GOT.mem"; 1280492f7529SSam Clegg Import.Field = WS.getName(); 1281492f7529SSam Clegg Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1282492f7529SSam Clegg Import.Global = {wasm::WASM_TYPE_I32, true}; 1283492f7529SSam Clegg Imports.push_back(Import); 1284492f7529SSam Clegg assert(GOTIndices.count(&WS) == 0); 1285492f7529SSam Clegg GOTIndices[&WS] = NumGlobalImports++; 1286492f7529SSam Clegg } 1287492f7529SSam Clegg } 12880ff28fa6SDerek Schuff } 1289492f7529SSam Clegg 12900ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm, 12910ff28fa6SDerek Schuff const MCAsmLayout &Layout) { 12920ff28fa6SDerek Schuff support::endian::Writer MainWriter(*OS, support::little); 12930ff28fa6SDerek Schuff W = &MainWriter; 12940ff28fa6SDerek Schuff if (IsSplitDwarf) { 12950ff28fa6SDerek Schuff uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly); 12960ff28fa6SDerek Schuff assert(DwoOS); 12970ff28fa6SDerek Schuff support::endian::Writer DwoWriter(*DwoOS, support::little); 12980ff28fa6SDerek Schuff W = &DwoWriter; 12990ff28fa6SDerek Schuff return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly); 13000ff28fa6SDerek Schuff } else { 13010ff28fa6SDerek Schuff return writeOneObject(Asm, Layout, DwoMode::AllSections); 13020ff28fa6SDerek Schuff } 13030ff28fa6SDerek Schuff } 13040ff28fa6SDerek Schuff 13050ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm, 13060ff28fa6SDerek Schuff const MCAsmLayout &Layout, 13070ff28fa6SDerek Schuff DwoMode Mode) { 13080ff28fa6SDerek Schuff uint64_t StartOffset = W->OS.tell(); 13090ff28fa6SDerek Schuff SectionCount = 0; 13100ff28fa6SDerek Schuff CustomSections.clear(); 13110ff28fa6SDerek Schuff 13120ff28fa6SDerek Schuff LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 13130ff28fa6SDerek Schuff 13140ff28fa6SDerek Schuff // Collect information from the available symbols. 13150ff28fa6SDerek Schuff SmallVector<WasmFunction, 4> Functions; 13160ff28fa6SDerek Schuff SmallVector<uint32_t, 4> TableElems; 13170ff28fa6SDerek Schuff SmallVector<wasm::WasmImport, 4> Imports; 13180ff28fa6SDerek Schuff SmallVector<wasm::WasmExport, 4> Exports; 13190ff28fa6SDerek Schuff SmallVector<wasm::WasmEventType, 1> Events; 13200ff28fa6SDerek Schuff SmallVector<wasm::WasmGlobal, 1> Globals; 1321388fb67bSPaulo Matos SmallVector<wasm::WasmTable, 1> Tables; 13220ff28fa6SDerek Schuff SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos; 13230ff28fa6SDerek Schuff SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 13240ff28fa6SDerek Schuff std::map<StringRef, std::vector<WasmComdatEntry>> Comdats; 13250ff28fa6SDerek Schuff uint64_t DataSize = 0; 13260ff28fa6SDerek Schuff if (Mode != DwoMode::DwoOnly) { 13270ff28fa6SDerek Schuff prepareImports(Imports, Asm, Layout); 13280ff28fa6SDerek Schuff } 13294d57fbd0SSam Clegg // Populate DataSegments and CustomSections, which must be done before 13304d57fbd0SSam Clegg // populating DataLocations. 1331759631c7SSam Clegg for (MCSection &Sec : Asm) { 1332759631c7SSam Clegg auto &Section = static_cast<MCSectionWasm &>(Sec); 13337d1ff446SFangrui Song StringRef SectionName = Section.getName(); 1334759631c7SSam Clegg 13350ff28fa6SDerek Schuff if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec)) 13360ff28fa6SDerek Schuff continue; 13370ff28fa6SDerek Schuff if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec)) 13380ff28fa6SDerek Schuff continue; 13390ff28fa6SDerek Schuff 1340bafe6902SSam Clegg // .init_array sections are handled specially elsewhere. 13414d57fbd0SSam Clegg if (SectionName.startswith(".init_array")) 1342bafe6902SSam Clegg continue; 1343bafe6902SSam Clegg 13444d57fbd0SSam Clegg // Code is handled separately 13454d57fbd0SSam Clegg if (Section.getKind().isText()) 13464d57fbd0SSam Clegg continue; 13474d57fbd0SSam Clegg 13484d57fbd0SSam Clegg if (Section.isWasmData()) { 1349329e76d5SSam Clegg uint32_t SegmentIndex = DataSegments.size(); 1350759631c7SSam Clegg DataSize = alignTo(DataSize, Section.getAlignment()); 1351759631c7SSam Clegg DataSegments.emplace_back(); 1352759631c7SSam Clegg WasmDataSegment &Segment = DataSegments.back(); 13534d57fbd0SSam Clegg Segment.Name = SectionName; 13549b49f36aSSimon Pilgrim Segment.InitFlags = 13559b49f36aSSimon Pilgrim Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0; 1356759631c7SSam Clegg Segment.Offset = DataSize; 1357759631c7SSam Clegg Segment.Section = &Section; 135863ebb813SSam Clegg addData(Segment.Data, Section); 135956c587adSSam Clegg Segment.Alignment = Log2_32(Section.getAlignment()); 13602e150409SThomas Lively Segment.LinkerFlags = 0; 1361759631c7SSam Clegg DataSize += Segment.Data.size(); 13626c899ba6SSam Clegg Section.setSegmentIndex(SegmentIndex); 1363ea7caceeSSam Clegg 1364ea7caceeSSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 1365ea7caceeSSam Clegg Comdats[C->getName()].emplace_back( 1366329e76d5SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex}); 1367ea7caceeSSam Clegg } 13684d57fbd0SSam Clegg } else { 13694d57fbd0SSam Clegg // Create custom sections 13704d57fbd0SSam Clegg assert(Sec.getKind().isMetadata()); 13714d57fbd0SSam Clegg 13724d57fbd0SSam Clegg StringRef Name = SectionName; 13734d57fbd0SSam Clegg 13744d57fbd0SSam Clegg // For user-defined custom sections, strip the prefix 13754d57fbd0SSam Clegg if (Name.startswith(".custom_section.")) 13764d57fbd0SSam Clegg Name = Name.substr(strlen(".custom_section.")); 13774d57fbd0SSam Clegg 13784d57fbd0SSam Clegg MCSymbol *Begin = Sec.getBeginSymbol(); 1379fb807d4dSSam Clegg if (Begin) { 13804d57fbd0SSam Clegg WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size(); 1381b210c64bSSam Clegg if (SectionName != Begin->getName()) 1382fb807d4dSSam Clegg report_fatal_error("section name and begin symbol should match: " + 1383b210c64bSSam Clegg Twine(SectionName)); 1384fb807d4dSSam Clegg } 1385cbda16ebSThomas Lively 1386f6f4f843SThomas Lively // Separate out the producers and target features sections 1387cbda16ebSThomas Lively if (Name == "producers") { 13880eaee545SJonas Devlieghere ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section); 1389cbda16ebSThomas Lively continue; 1390cbda16ebSThomas Lively } 1391f6f4f843SThomas Lively if (Name == "target_features") { 1392f6f4f843SThomas Lively TargetFeaturesSection = 13930eaee545SJonas Devlieghere std::make_unique<WasmCustomSection>(Name, &Section); 1394f6f4f843SThomas Lively continue; 1395f6f4f843SThomas Lively } 1396cbda16ebSThomas Lively 13974d57fbd0SSam Clegg CustomSections.emplace_back(Name, &Section); 1398759631c7SSam Clegg } 13996a31a0d6SSam Clegg } 14006a31a0d6SSam Clegg 1401586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for defined symbols. 1402d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1403d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1404d934cb88SDan Gohman // or used in relocations. 1405d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 1406d934cb88SDan Gohman continue; 1407b7787fd0SSam Clegg 1408d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 1409d34e60caSNicola Zaghen LLVM_DEBUG( 1410d34e60caSNicola Zaghen dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'" 1411d34e60caSNicola Zaghen << " isDefined=" << S.isDefined() << " isExternal=" 1412d34e60caSNicola Zaghen << S.isExternal() << " isTemporary=" << S.isTemporary() 1413d34e60caSNicola Zaghen << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden() 1414b7787fd0SSam Clegg << " isVariable=" << WS.isVariable() << "\n"); 1415b7787fd0SSam Clegg 14165e3d33a7SSam Clegg if (WS.isVariable()) 14175e3d33a7SSam Clegg continue; 14186c899ba6SSam Clegg if (WS.isComdat() && !WS.isDefined()) 14196c899ba6SSam Clegg continue; 1420b7787fd0SSam Clegg 1421d934cb88SDan Gohman if (WS.isFunction()) { 14226c899ba6SSam Clegg unsigned Index; 1423cd65f698SSam Clegg if (WS.isDefined()) { 1424b7787fd0SSam Clegg if (WS.getOffset() != 0) 1425b7787fd0SSam Clegg report_fatal_error( 1426b7787fd0SSam Clegg "function sections must contain one function each"); 1427b7787fd0SSam Clegg 142818c56a07SHeejin Ahn if (WS.getSize() == nullptr) 1429b7787fd0SSam Clegg report_fatal_error( 1430b7787fd0SSam Clegg "function symbols must have a size set with .size"); 1431b7787fd0SSam Clegg 14326c899ba6SSam Clegg // A definition. Write out the function body. 14339f3fe42eSSam Clegg Index = NumFunctionImports + Functions.size(); 1434d934cb88SDan Gohman WasmFunction Func; 1435da419bdbSHeejin Ahn Func.SigIndex = getFunctionType(WS); 1436d934cb88SDan Gohman Func.Sym = &WS; 14376c899ba6SSam Clegg WasmIndices[&WS] = Index; 1438d934cb88SDan Gohman Functions.push_back(Func); 14396c899ba6SSam Clegg 14406c899ba6SSam Clegg auto &Section = static_cast<MCSectionWasm &>(WS.getSection()); 14416c899ba6SSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 14426c899ba6SSam Clegg Comdats[C->getName()].emplace_back( 14436c899ba6SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index}); 14446c899ba6SSam Clegg } 1445881d8778SSam Clegg 1446881d8778SSam Clegg if (WS.hasExportName()) { 1447881d8778SSam Clegg wasm::WasmExport Export; 1448881d8778SSam Clegg Export.Name = WS.getExportName(); 1449881d8778SSam Clegg Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1450881d8778SSam Clegg Export.Index = Index; 1451881d8778SSam Clegg Exports.push_back(Export); 1452881d8778SSam Clegg } 1453d934cb88SDan Gohman } else { 1454d934cb88SDan Gohman // An import; the index was assigned above. 14556c899ba6SSam Clegg Index = WasmIndices.find(&WS)->second; 1456d934cb88SDan Gohman } 1457d934cb88SDan Gohman 1458d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n"); 1459da419bdbSHeejin Ahn 14606c899ba6SSam Clegg } else if (WS.isData()) { 1461f3feb6adSWouter van Oortmerssen if (!isInSymtab(WS)) 1462c38e947eSSam Clegg continue; 1463c38e947eSSam Clegg 14646c899ba6SSam Clegg if (!WS.isDefined()) { 1465d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> segment index: -1" 1466d34e60caSNicola Zaghen << "\n"); 1467fe6414b0SSam Clegg continue; 14686c899ba6SSam Clegg } 1469fe6414b0SSam Clegg 1470d934cb88SDan Gohman if (!WS.getSize()) 1471c38e947eSSam Clegg report_fatal_error("data symbols must have a size set with .size: " + 1472c38e947eSSam Clegg WS.getName()); 1473d934cb88SDan Gohman 1474d934cb88SDan Gohman int64_t Size = 0; 1475d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1476d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 1477d934cb88SDan Gohman 1478759631c7SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1479079cba04SSam Clegg if (!DataSection.isWasmData()) 1480079cba04SSam Clegg report_fatal_error("data symbols must live in a data section: " + 1481079cba04SSam Clegg WS.getName()); 14827c395943SSam Clegg 14836c899ba6SSam Clegg // For each data symbol, export it in the symtab as a reference to the 14846c899ba6SSam Clegg // corresponding Wasm data segment. 14856c899ba6SSam Clegg wasm::WasmDataReference Ref = wasm::WasmDataReference{ 14863b29376eSWouter van Oortmerssen DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS), 14873b29376eSWouter van Oortmerssen static_cast<uint64_t>(Size)}; 14886c899ba6SSam Clegg DataLocations[&WS] = Ref; 1489d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n"); 1490da419bdbSHeejin Ahn 1491a165f2d6SSam Clegg } else if (WS.isGlobal()) { 14926c899ba6SSam Clegg // A "true" Wasm global (currently just __stack_pointer) 14930a6c4d8dSSam Clegg if (WS.isDefined()) { 14940a6c4d8dSSam Clegg assert(WasmIndices.count(&WS) == 0); 14950a6c4d8dSSam Clegg wasm::WasmGlobal Global; 14960a6c4d8dSSam Clegg Global.Type = WS.getGlobalType(); 14970a6c4d8dSSam Clegg Global.Index = NumGlobalImports + Globals.size(); 14980a6c4d8dSSam Clegg switch (Global.Type.Type) { 14990a6c4d8dSSam Clegg case wasm::WASM_TYPE_I32: 15000a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST; 15010a6c4d8dSSam Clegg break; 15020a6c4d8dSSam Clegg case wasm::WASM_TYPE_I64: 15030a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST; 15040a6c4d8dSSam Clegg break; 15050a6c4d8dSSam Clegg case wasm::WASM_TYPE_F32: 15060a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST; 15070a6c4d8dSSam Clegg break; 15080a6c4d8dSSam Clegg case wasm::WASM_TYPE_F64: 15090a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST; 15100a6c4d8dSSam Clegg break; 151179aad89dSSam Clegg case wasm::WASM_TYPE_EXTERNREF: 151279aad89dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL; 151379aad89dSSam Clegg break; 15140a6c4d8dSSam Clegg default: 15150a6c4d8dSSam Clegg llvm_unreachable("unexpected type"); 15160a6c4d8dSSam Clegg } 15170a6c4d8dSSam Clegg WasmIndices[&WS] = Global.Index; 15180a6c4d8dSSam Clegg Globals.push_back(Global); 15190a6c4d8dSSam Clegg } else { 1520545932beSEric Christopher // An import; the index was assigned above 1521d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> global index: " 1522d34e60caSNicola Zaghen << WasmIndices.find(&WS)->second << "\n"); 15230a6c4d8dSSam Clegg } 1524388fb67bSPaulo Matos } else if (WS.isTable()) { 1525388fb67bSPaulo Matos if (WS.isDefined()) { 1526388fb67bSPaulo Matos assert(WasmIndices.count(&WS) == 0); 1527388fb67bSPaulo Matos wasm::WasmTable Table; 1528388fb67bSPaulo Matos Table.ElemType = static_cast<uint8_t>(WS.getTableType()); 1529388fb67bSPaulo Matos Table.Index = NumTableImports + Tables.size(); 1530388fb67bSPaulo Matos // FIXME: Work on custom limits is ongoing 1531388fb67bSPaulo Matos Table.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0}; 1532388fb67bSPaulo Matos 1533388fb67bSPaulo Matos WasmIndices[&WS] = Table.Index; 1534388fb67bSPaulo Matos Tables.push_back(Table); 1535388fb67bSPaulo Matos } 1536388fb67bSPaulo Matos LLVM_DEBUG(dbgs() << " -> table index: " << WasmIndices.find(&WS)->second 1537388fb67bSPaulo Matos << "\n"); 1538da419bdbSHeejin Ahn } else if (WS.isEvent()) { 1539da419bdbSHeejin Ahn // C++ exception symbol (__cpp_exception) 1540da419bdbSHeejin Ahn unsigned Index; 1541da419bdbSHeejin Ahn if (WS.isDefined()) { 15420a6c4d8dSSam Clegg assert(WasmIndices.count(&WS) == 0); 1543da419bdbSHeejin Ahn Index = NumEventImports + Events.size(); 1544da419bdbSHeejin Ahn wasm::WasmEventType Event; 1545da419bdbSHeejin Ahn Event.SigIndex = getEventType(WS); 1546da419bdbSHeejin Ahn Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION; 1547da419bdbSHeejin Ahn WasmIndices[&WS] = Index; 1548da419bdbSHeejin Ahn Events.push_back(Event); 1549da419bdbSHeejin Ahn } else { 1550da419bdbSHeejin Ahn // An import; the index was assigned above. 1551492f7529SSam Clegg assert(WasmIndices.count(&WS) > 0); 1552da419bdbSHeejin Ahn } 1553da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second 1554da419bdbSHeejin Ahn << "\n"); 1555da419bdbSHeejin Ahn 1556a165f2d6SSam Clegg } else { 1557a165f2d6SSam Clegg assert(WS.isSection()); 1558d934cb88SDan Gohman } 1559d934cb88SDan Gohman } 1560d934cb88SDan Gohman 1561586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for aliased symbols. We need to 1562586320c0SNicholas Wilson // process these in a separate pass because we need to have processed the 1563586320c0SNicholas Wilson // target of the alias before the alias itself and the symbols are not 1564586320c0SNicholas Wilson // necessarily ordered in this way. 1565b7787fd0SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1566b7787fd0SSam Clegg if (!S.isVariable()) 1567b7787fd0SSam Clegg continue; 156831a2c809SSam Clegg 1569cd65f698SSam Clegg assert(S.isDefined()); 1570b7787fd0SSam Clegg 15719c7b5808SDominic Chen const auto *BS = Layout.getBaseSymbol(S); 15729c7b5808SDominic Chen if (!BS) 15739c7b5808SDominic Chen report_fatal_error(Twine(S.getName()) + 15749c7b5808SDominic Chen ": absolute addressing not supported!"); 15759c7b5808SDominic Chen const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS); 15767ee758d6SSam Clegg 15775e3d33a7SSam Clegg // Find the target symbol of this weak alias and export that index 1578aff1c4dfSSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 15797ee758d6SSam Clegg LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n"); 1580b7787fd0SSam Clegg 15817ee758d6SSam Clegg if (Base->isFunction()) { 15827ee758d6SSam Clegg assert(WasmIndices.count(Base) > 0); 15837ee758d6SSam Clegg uint32_t WasmIndex = WasmIndices.find(Base)->second; 1584492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 15856c899ba6SSam Clegg WasmIndices[&WS] = WasmIndex; 1586d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n"); 15877ee758d6SSam Clegg } else if (Base->isData()) { 15887ee758d6SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 15897ee758d6SSam Clegg uint64_t Offset = Layout.getSymbolOffset(S); 15907ee758d6SSam Clegg int64_t Size = 0; 15917ee758d6SSam Clegg // For data symbol alias we use the size of the base symbol as the 15927ee758d6SSam Clegg // size of the alias. When an offset from the base is involved this 15937ee758d6SSam Clegg // can result in a offset + size goes past the end of the data section 15947ee758d6SSam Clegg // which out object format doesn't support. So we must clamp it. 15957ee758d6SSam Clegg if (!Base->getSize()->evaluateAsAbsolute(Size, Layout)) 15967ee758d6SSam Clegg report_fatal_error(".size expression must be evaluatable"); 15977ee758d6SSam Clegg const WasmDataSegment &Segment = 15987ee758d6SSam Clegg DataSegments[DataSection.getSegmentIndex()]; 15997ee758d6SSam Clegg Size = 16007ee758d6SSam Clegg std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset); 16017ee758d6SSam Clegg wasm::WasmDataReference Ref = wasm::WasmDataReference{ 16027ee758d6SSam Clegg DataSection.getSegmentIndex(), 16037ee758d6SSam Clegg static_cast<uint32_t>(Layout.getSymbolOffset(S)), 16047ee758d6SSam Clegg static_cast<uint32_t>(Size)}; 16056c899ba6SSam Clegg DataLocations[&WS] = Ref; 1606d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n"); 16076c899ba6SSam Clegg } else { 1608da419bdbSHeejin Ahn report_fatal_error("don't yet support global/event aliases"); 16096c899ba6SSam Clegg } 1610586320c0SNicholas Wilson } 161131a2c809SSam Clegg 1612586320c0SNicholas Wilson // Finally, populate the symbol table itself, in its "natural" order. 1613586320c0SNicholas Wilson for (const MCSymbol &S : Asm.symbols()) { 1614586320c0SNicholas Wilson const auto &WS = static_cast<const MCSymbolWasm &>(S); 161525d8e68bSSam Clegg if (!isInSymtab(WS)) { 161618c56a07SHeejin Ahn WS.setIndex(InvalidIndex); 1617586320c0SNicholas Wilson continue; 161825d8e68bSSam Clegg } 1619d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n"); 1620586320c0SNicholas Wilson 1621586320c0SNicholas Wilson uint32_t Flags = 0; 1622586320c0SNicholas Wilson if (WS.isWeak()) 1623586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_WEAK; 1624586320c0SNicholas Wilson if (WS.isHidden()) 1625586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN; 1626586320c0SNicholas Wilson if (!WS.isExternal() && WS.isDefined()) 1627586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL; 1628586320c0SNicholas Wilson if (WS.isUndefined()) 1629586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_UNDEFINED; 1630da84b688SDan Gohman if (WS.isNoStrip()) { 1631da84b688SDan Gohman Flags |= wasm::WASM_SYMBOL_NO_STRIP; 1632da84b688SDan Gohman if (isEmscripten()) { 1633d6ef8da3SSam Clegg Flags |= wasm::WASM_SYMBOL_EXPORTED; 1634da84b688SDan Gohman } 1635da84b688SDan Gohman } 1636b4f4e370SSam Clegg if (WS.hasImportName()) 163729874ceaSDan Gohman Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME; 1638881d8778SSam Clegg if (WS.hasExportName()) 1639881d8778SSam Clegg Flags |= wasm::WASM_SYMBOL_EXPORTED; 1640586320c0SNicholas Wilson 1641586320c0SNicholas Wilson wasm::WasmSymbolInfo Info; 1642586320c0SNicholas Wilson Info.Name = WS.getName(); 1643586320c0SNicholas Wilson Info.Kind = WS.getType(); 1644586320c0SNicholas Wilson Info.Flags = Flags; 16454d57fbd0SSam Clegg if (!WS.isData()) { 16464d57fbd0SSam Clegg assert(WasmIndices.count(&WS) > 0); 1647586320c0SNicholas Wilson Info.ElementIndex = WasmIndices.find(&WS)->second; 16484d57fbd0SSam Clegg } else if (WS.isDefined()) { 16494d57fbd0SSam Clegg assert(DataLocations.count(&WS) > 0); 1650586320c0SNicholas Wilson Info.DataRef = DataLocations.find(&WS)->second; 16514d57fbd0SSam Clegg } 165225d8e68bSSam Clegg WS.setIndex(SymbolInfos.size()); 1653586320c0SNicholas Wilson SymbolInfos.emplace_back(Info); 1654b7787fd0SSam Clegg } 1655b7787fd0SSam Clegg 16566006e091SSam Clegg { 16576006e091SSam Clegg auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 1658f9edbe95SSam Clegg // Functions referenced by a relocation need to put in the table. This is 1659f9edbe95SSam Clegg // purely to make the object file's provisional values readable, and is 1660f9edbe95SSam Clegg // ignored by the linker, which re-calculates the relocations itself. 1661d1152a26SSam Clegg if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 && 1662cc1b9b68SWouter van Oortmerssen Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 && 166381443ac1SSam Clegg Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB && 1664cc1b9b68SWouter van Oortmerssen Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 && 166581443ac1SSam Clegg Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB) 1666f9edbe95SSam Clegg return; 1667f9edbe95SSam Clegg assert(Rel.Symbol->isFunction()); 16687ee758d6SSam Clegg const MCSymbolWasm *Base = 16697ee758d6SSam Clegg cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol)); 16707ee758d6SSam Clegg uint32_t FunctionIndex = WasmIndices.find(Base)->second; 167118c56a07SHeejin Ahn uint32_t TableIndex = TableElems.size() + InitialTableOffset; 16727ee758d6SSam Clegg if (TableIndices.try_emplace(Base, TableIndex).second) { 16737ee758d6SSam Clegg LLVM_DEBUG(dbgs() << " -> adding " << Base->getName() 1674f9edbe95SSam Clegg << " to table: " << TableIndex << "\n"); 16756c899ba6SSam Clegg TableElems.push_back(FunctionIndex); 16767ee758d6SSam Clegg registerFunctionType(*Base); 16776006e091SSam Clegg } 16786006e091SSam Clegg }; 1679970d02c4SDan Gohman 16806006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : CodeRelocations) 16816006e091SSam Clegg HandleReloc(RelEntry); 16826006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : DataRelocations) 16836006e091SSam Clegg HandleReloc(RelEntry); 1684d934cb88SDan Gohman } 1685d934cb88SDan Gohman 1686bafe6902SSam Clegg // Translate .init_array section contents into start functions. 1687bafe6902SSam Clegg for (const MCSection &S : Asm) { 1688bafe6902SSam Clegg const auto &WS = static_cast<const MCSectionWasm &>(S); 16897d1ff446SFangrui Song if (WS.getName().startswith(".fini_array")) 1690bafe6902SSam Clegg report_fatal_error(".fini_array sections are unsupported"); 16917d1ff446SFangrui Song if (!WS.getName().startswith(".init_array")) 1692bafe6902SSam Clegg continue; 1693bafe6902SSam Clegg if (WS.getFragmentList().empty()) 1694bafe6902SSam Clegg continue; 1695b210c64bSSam Clegg 1696b210c64bSSam Clegg // init_array is expected to contain a single non-empty data fragment 1697b210c64bSSam Clegg if (WS.getFragmentList().size() != 3) 1698bafe6902SSam Clegg report_fatal_error("only one .init_array section fragment supported"); 1699b210c64bSSam Clegg 1700b210c64bSSam Clegg auto IT = WS.begin(); 1701b210c64bSSam Clegg const MCFragment &EmptyFrag = *IT; 1702b210c64bSSam Clegg if (EmptyFrag.getKind() != MCFragment::FT_Data) 1703b210c64bSSam Clegg report_fatal_error(".init_array section should be aligned"); 1704b210c64bSSam Clegg 1705b210c64bSSam Clegg IT = std::next(IT); 1706b210c64bSSam Clegg const MCFragment &AlignFrag = *IT; 1707bafe6902SSam Clegg if (AlignFrag.getKind() != MCFragment::FT_Align) 1708bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned"); 1709bafe6902SSam Clegg if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1710bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned for pointers"); 1711b210c64bSSam Clegg 1712b210c64bSSam Clegg const MCFragment &Frag = *std::next(IT); 1713bafe6902SSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1714bafe6902SSam Clegg report_fatal_error("only data supported in .init_array section"); 1715b210c64bSSam Clegg 1716bafe6902SSam Clegg uint16_t Priority = UINT16_MAX; 17174d57fbd0SSam Clegg unsigned PrefixLength = strlen(".init_array"); 17187d1ff446SFangrui Song if (WS.getName().size() > PrefixLength) { 17197d1ff446SFangrui Song if (WS.getName()[PrefixLength] != '.') 1720f208f631SHeejin Ahn report_fatal_error( 1721f208f631SHeejin Ahn ".init_array section priority should start with '.'"); 17227d1ff446SFangrui Song if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority)) 1723bafe6902SSam Clegg report_fatal_error("invalid .init_array section priority"); 1724bafe6902SSam Clegg } 1725bafe6902SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1726bafe6902SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1727f208f631SHeejin Ahn for (const uint8_t * 172818c56a07SHeejin Ahn P = (const uint8_t *)Contents.data(), 172918c56a07SHeejin Ahn *End = (const uint8_t *)Contents.data() + Contents.size(); 173018c56a07SHeejin Ahn P != End; ++P) { 173118c56a07SHeejin Ahn if (*P != 0) 1732bafe6902SSam Clegg report_fatal_error("non-symbolic data in .init_array section"); 1733bafe6902SSam Clegg } 1734bafe6902SSam Clegg for (const MCFixup &Fixup : DataFrag.getFixups()) { 1735f208f631SHeejin Ahn assert(Fixup.getKind() == 1736f208f631SHeejin Ahn MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1737bafe6902SSam Clegg const MCExpr *Expr = Fixup.getValue(); 17388fffa1dfSSam Clegg auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr); 17398fffa1dfSSam Clegg if (!SymRef) 1740bafe6902SSam Clegg report_fatal_error("fixups in .init_array should be symbol references"); 17418fffa1dfSSam Clegg const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol()); 17428fffa1dfSSam Clegg if (TargetSym.getIndex() == InvalidIndex) 17433ea1c62cSSam Clegg report_fatal_error("symbols in .init_array should exist in symtab"); 17448fffa1dfSSam Clegg if (!TargetSym.isFunction()) 17458fffa1dfSSam Clegg report_fatal_error("symbols in .init_array should be for functions"); 174625d8e68bSSam Clegg InitFuncs.push_back( 17478fffa1dfSSam Clegg std::make_pair(Priority, TargetSym.getIndex())); 1748bafe6902SSam Clegg } 1749bafe6902SSam Clegg } 1750bafe6902SSam Clegg 175118eafb6cSDan Gohman // Write out the Wasm header. 175218eafb6cSDan Gohman writeHeader(Asm); 175318eafb6cSDan Gohman 17540ff28fa6SDerek Schuff uint32_t CodeSectionIndex, DataSectionIndex; 17550ff28fa6SDerek Schuff if (Mode != DwoMode::DwoOnly) { 1756da419bdbSHeejin Ahn writeTypeSection(Signatures); 1757f950b24aSSam Clegg writeImportSection(Imports, DataSize, TableElems.size()); 17589e15f359SSam Clegg writeFunctionSection(Functions); 1759f950b24aSSam Clegg // Skip the "memory" section; we import the memory instead. 1760da419bdbSHeejin Ahn writeEventSection(Events); 17610a6c4d8dSSam Clegg writeGlobalSection(Globals); 1762388fb67bSPaulo Matos writeTableSection(Tables); 17639e15f359SSam Clegg writeExportSection(Exports); 17649e15f359SSam Clegg writeElemSection(TableElems); 1765fef8de66SThomas Lively writeDataCountSection(); 17660ff28fa6SDerek Schuff 17670ff28fa6SDerek Schuff CodeSectionIndex = writeCodeSection(Asm, Layout, Functions); 17680ff28fa6SDerek Schuff DataSectionIndex = writeDataSection(Layout); 17690ff28fa6SDerek Schuff } 17700ff28fa6SDerek Schuff 17710ff28fa6SDerek Schuff for (auto &CustomSection : CustomSections) { 1772cbda16ebSThomas Lively writeCustomSection(CustomSection, Asm, Layout); 17730ff28fa6SDerek Schuff } 17740ff28fa6SDerek Schuff 17750ff28fa6SDerek Schuff if (Mode != DwoMode::DwoOnly) { 1776c22bfb6bSNicholas Wilson writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats); 17770ff28fa6SDerek Schuff 17786f08c84aSSam Clegg writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations); 17796f08c84aSSam Clegg writeRelocSection(DataSectionIndex, "DATA", DataRelocations); 17800ff28fa6SDerek Schuff } 17816a31a0d6SSam Clegg writeCustomRelocSections(); 1782cbda16ebSThomas Lively if (ProducersSection) 1783cbda16ebSThomas Lively writeCustomSection(*ProducersSection, Asm, Layout); 1784f6f4f843SThomas Lively if (TargetFeaturesSection) 1785f6f4f843SThomas Lively writeCustomSection(*TargetFeaturesSection, Asm, Layout); 1786970d02c4SDan Gohman 1787d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 17880ff28fa6SDerek Schuff return W->OS.tell() - StartOffset; 178918eafb6cSDan Gohman } 179018eafb6cSDan Gohman 179160fbc7ccSLang Hames std::unique_ptr<MCObjectWriter> 17921301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 179318eafb6cSDan Gohman raw_pwrite_stream &OS) { 17940eaee545SJonas Devlieghere return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS); 179518eafb6cSDan Gohman } 17960ff28fa6SDerek Schuff 17970ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter> 17980ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 17990ff28fa6SDerek Schuff raw_pwrite_stream &OS, 18000ff28fa6SDerek Schuff raw_pwrite_stream &DwoOS) { 18010ff28fa6SDerek Schuff return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS); 18020ff28fa6SDerek Schuff } 1803