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" 16432a3883SNico Weber #include "llvm/Config/llvm-config.h" 1718eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h" 1818eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h" 1918eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h" 2018eafb6cSDan Gohman #include "llvm/MC/MCContext.h" 2118eafb6cSDan Gohman #include "llvm/MC/MCExpr.h" 2218eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h" 2318eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h" 2418eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h" 2518eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h" 2618eafb6cSDan Gohman #include "llvm/MC/MCValue.h" 2718eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h" 28d934cb88SDan Gohman #include "llvm/Support/Casting.h" 2918eafb6cSDan Gohman #include "llvm/Support/Debug.h" 30bcd7f777SSimon Pilgrim #include "llvm/Support/EndianStream.h" 3118eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h" 32d934cb88SDan Gohman #include "llvm/Support/LEB128.h" 3318eafb6cSDan Gohman #include "llvm/Support/StringSaver.h" 3418eafb6cSDan Gohman #include <vector> 3518eafb6cSDan Gohman 3618eafb6cSDan Gohman using namespace llvm; 3718eafb6cSDan Gohman 385e3d33a7SSam Clegg #define DEBUG_TYPE "mc" 3918eafb6cSDan Gohman 4018eafb6cSDan Gohman namespace { 419e15f359SSam Clegg 4230e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is 4330e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap. 4418c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1; 4530e1bbc1SSam Clegg 46d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both 47d934cb88SDan Gohman // for patching up the section size field, and for patching up references to 48d934cb88SDan Gohman // locations within the section. 49d934cb88SDan Gohman struct SectionBookkeeping { 50d934cb88SDan Gohman // Where the size of the section is written. 51d934cb88SDan Gohman uint64_t SizeOffset; 526a31a0d6SSam Clegg // Where the section header ends (without custom section name). 536a31a0d6SSam Clegg uint64_t PayloadOffset; 546a31a0d6SSam Clegg // Where the contents of the section starts. 55d934cb88SDan Gohman uint64_t ContentsOffset; 566f08c84aSSam Clegg uint32_t Index; 57d934cb88SDan Gohman }; 58d934cb88SDan Gohman 59da419bdbSHeejin Ahn // The signature of a wasm function or event, in a struct capable of being used 60da419bdbSHeejin Ahn // as a DenseMap key. 61da419bdbSHeejin Ahn // TODO: Consider using wasm::WasmSignature directly instead. 62da419bdbSHeejin Ahn struct WasmSignature { 639e15f359SSam Clegg // Support empty and tombstone instances, needed by DenseMap. 6418c56a07SHeejin Ahn enum { Plain, Empty, Tombstone } State = Plain; 659e15f359SSam Clegg 669e15f359SSam Clegg // The return types of the function. 679e15f359SSam Clegg SmallVector<wasm::ValType, 1> Returns; 689e15f359SSam Clegg 699e15f359SSam Clegg // The parameter types of the function. 709e15f359SSam Clegg SmallVector<wasm::ValType, 4> Params; 719e15f359SSam Clegg 72da419bdbSHeejin Ahn bool operator==(const WasmSignature &Other) const { 739e15f359SSam Clegg return State == Other.State && Returns == Other.Returns && 749e15f359SSam Clegg Params == Other.Params; 759e15f359SSam Clegg } 769e15f359SSam Clegg }; 779e15f359SSam Clegg 78da419bdbSHeejin Ahn // Traits for using WasmSignature in a DenseMap. 79da419bdbSHeejin Ahn struct WasmSignatureDenseMapInfo { 80da419bdbSHeejin Ahn static WasmSignature getEmptyKey() { 81da419bdbSHeejin Ahn WasmSignature Sig; 82da419bdbSHeejin Ahn Sig.State = WasmSignature::Empty; 83da419bdbSHeejin Ahn return Sig; 849e15f359SSam Clegg } 85da419bdbSHeejin Ahn static WasmSignature getTombstoneKey() { 86da419bdbSHeejin Ahn WasmSignature Sig; 87da419bdbSHeejin Ahn Sig.State = WasmSignature::Tombstone; 88da419bdbSHeejin Ahn return Sig; 899e15f359SSam Clegg } 90da419bdbSHeejin Ahn static unsigned getHashValue(const WasmSignature &Sig) { 91da419bdbSHeejin Ahn uintptr_t Value = Sig.State; 92da419bdbSHeejin Ahn for (wasm::ValType Ret : Sig.Returns) 934808914aSHeejin Ahn Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret)); 94da419bdbSHeejin Ahn for (wasm::ValType Param : Sig.Params) 954808914aSHeejin Ahn Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param)); 969e15f359SSam Clegg return Value; 979e15f359SSam Clegg } 98da419bdbSHeejin Ahn static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) { 999e15f359SSam Clegg return LHS == RHS; 1009e15f359SSam Clegg } 1019e15f359SSam Clegg }; 1029e15f359SSam Clegg 1037c395943SSam Clegg // A wasm data segment. A wasm binary contains only a single data section 1047c395943SSam Clegg // but that can contain many segments, each with their own virtual location 1057c395943SSam Clegg // in memory. Each MCSection data created by llvm is modeled as its own 1067c395943SSam Clegg // wasm data segment. 1077c395943SSam Clegg struct WasmDataSegment { 1087c395943SSam Clegg MCSectionWasm *Section; 109d95ed959SSam Clegg StringRef Name; 1102e150409SThomas Lively uint32_t InitFlags; 1117c395943SSam Clegg uint32_t Offset; 11263ebb813SSam Clegg uint32_t Alignment; 1132e150409SThomas Lively uint32_t LinkerFlags; 1147c395943SSam Clegg SmallVector<char, 4> Data; 1157c395943SSam Clegg }; 1167c395943SSam Clegg 1179e15f359SSam Clegg // A wasm function to be written into the function section. 1189e15f359SSam Clegg struct WasmFunction { 119da419bdbSHeejin Ahn uint32_t SigIndex; 1209e15f359SSam Clegg const MCSymbolWasm *Sym; 1219e15f359SSam Clegg }; 1229e15f359SSam Clegg 1239e15f359SSam Clegg // A wasm global to be written into the global section. 1249e15f359SSam Clegg struct WasmGlobal { 1256e7f1826SSam Clegg wasm::WasmGlobalType Type; 1269e15f359SSam Clegg uint64_t InitialValue; 1279e15f359SSam Clegg }; 1289e15f359SSam Clegg 129ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT. For each data 130ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding 131ea7caceeSSam Clegg // WasmComdatEntry. 132ea7caceeSSam Clegg struct WasmComdatEntry { 133ea7caceeSSam Clegg unsigned Kind; 134ea7caceeSSam Clegg uint32_t Index; 135ea7caceeSSam Clegg }; 136ea7caceeSSam Clegg 1376dc65e91SSam Clegg // Information about a single relocation. 1386dc65e91SSam Clegg struct WasmRelocationEntry { 1396dc65e91SSam Clegg uint64_t Offset; // Where is the relocation. 1406dc65e91SSam Clegg const MCSymbolWasm *Symbol; // The symbol to relocate with. 1416dc65e91SSam Clegg int64_t Addend; // A value to add to the symbol. 1426dc65e91SSam Clegg unsigned Type; // The type of the relocation. 143fe6414b0SSam Clegg const MCSectionWasm *FixupSection; // The section the relocation is targeting. 1446dc65e91SSam Clegg 1456dc65e91SSam Clegg WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol, 1466dc65e91SSam Clegg int64_t Addend, unsigned Type, 147fe6414b0SSam Clegg const MCSectionWasm *FixupSection) 1486dc65e91SSam Clegg : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type), 1496dc65e91SSam Clegg FixupSection(FixupSection) {} 1506dc65e91SSam Clegg 151cadcb9ebSKeno Fischer bool hasAddend() const { return wasm::relocTypeHasAddend(Type); } 152acd7d2b0SSam Clegg 1536dc65e91SSam Clegg void print(raw_ostream &Out) const { 154f208f631SHeejin Ahn Out << wasm::relocTypetoString(Type) << " Off=" << Offset 155f208f631SHeejin Ahn << ", Sym=" << *Symbol << ", Addend=" << Addend 1567d1ff446SFangrui Song << ", FixupSection=" << FixupSection->getName(); 1576dc65e91SSam Clegg } 158b7787fd0SSam Clegg 159615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 160b7787fd0SSam Clegg LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 161b7787fd0SSam Clegg #endif 1626dc65e91SSam Clegg }; 1636dc65e91SSam Clegg 16418c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1; 16525d8e68bSSam Clegg 166cfd44a2eSSam Clegg struct WasmCustomSection { 167cfd44a2eSSam Clegg 1686a31a0d6SSam Clegg StringRef Name; 1696a31a0d6SSam Clegg MCSectionWasm *Section; 1706a31a0d6SSam Clegg 1716a31a0d6SSam Clegg uint32_t OutputContentsOffset; 1726a31a0d6SSam Clegg uint32_t OutputIndex; 1736a31a0d6SSam Clegg 1746a31a0d6SSam Clegg WasmCustomSection(StringRef Name, MCSectionWasm *Section) 1756a31a0d6SSam Clegg : Name(Name), Section(Section), OutputContentsOffset(0), 17618c56a07SHeejin Ahn OutputIndex(InvalidIndex) {} 177cfd44a2eSSam Clegg }; 178cfd44a2eSSam Clegg 1791fb8daa6SSam Clegg #if !defined(NDEBUG) 1807f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) { 181b7787fd0SSam Clegg Rel.print(OS); 182b7787fd0SSam Clegg return OS; 183b7787fd0SSam Clegg } 1841fb8daa6SSam Clegg #endif 185b7787fd0SSam Clegg 18619e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded 18719e8befaSSam Clegg // to allow patching. 18818c56a07SHeejin Ahn static void writePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, 18919e8befaSSam Clegg uint64_t Offset) { 19019e8befaSSam Clegg uint8_t Buffer[5]; 19119e8befaSSam Clegg unsigned SizeLen = encodeULEB128(X, Buffer, 5); 19219e8befaSSam Clegg assert(SizeLen == 5); 19319e8befaSSam Clegg Stream.pwrite((char *)Buffer, SizeLen, Offset); 19419e8befaSSam Clegg } 19519e8befaSSam Clegg 19619e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded 19719e8befaSSam Clegg // to allow patching. 19818c56a07SHeejin Ahn static void writePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, 19919e8befaSSam Clegg uint64_t Offset) { 20019e8befaSSam Clegg uint8_t Buffer[5]; 20119e8befaSSam Clegg unsigned SizeLen = encodeSLEB128(X, Buffer, 5); 20219e8befaSSam Clegg assert(SizeLen == 5); 20319e8befaSSam Clegg Stream.pwrite((char *)Buffer, SizeLen, Offset); 20419e8befaSSam Clegg } 20519e8befaSSam Clegg 20619e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream. 2070a6c4d8dSSam Clegg static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 20819e8befaSSam Clegg uint8_t Buffer[4]; 20919e8befaSSam Clegg support::endian::write32le(Buffer, X); 21019e8befaSSam Clegg Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 21119e8befaSSam Clegg } 21219e8befaSSam Clegg 21318eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter { 214f17b149dSPeter Collingbourne support::endian::Writer W; 215f17b149dSPeter Collingbourne 21618eafb6cSDan Gohman /// The target specific Wasm writer instance. 21718eafb6cSDan Gohman std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; 21818eafb6cSDan Gohman 219d934cb88SDan Gohman // Relocations for fixing up references in the code section. 220d934cb88SDan Gohman std::vector<WasmRelocationEntry> CodeRelocations; 2216f08c84aSSam Clegg uint32_t CodeSectionIndex; 222d934cb88SDan Gohman 223d934cb88SDan Gohman // Relocations for fixing up references in the data section. 224d934cb88SDan Gohman std::vector<WasmRelocationEntry> DataRelocations; 2256f08c84aSSam Clegg uint32_t DataSectionIndex; 226d934cb88SDan Gohman 227d934cb88SDan Gohman // Index values to use for fixing up call_indirect type indices. 228acd7d2b0SSam Clegg // Maps function symbols to the index of the type of the function 229acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices; 230d99f6078SSam Clegg // Maps function symbols to the table element index space. Used 231d99f6078SSam Clegg // for TABLE_INDEX relocation types (i.e. address taken functions). 232f9edbe95SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TableIndices; 233da419bdbSHeejin Ahn // Maps function/global symbols to the function/global/event/section index 234da419bdbSHeejin Ahn // space. 2356c899ba6SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices; 236492f7529SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices; 2376c899ba6SSam Clegg // Maps data symbols to the Wasm segment and offset/size with the segment. 2386c899ba6SSam Clegg DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations; 2396a31a0d6SSam Clegg 2406a31a0d6SSam Clegg // Stores output data (index, relocations, content offset) for custom 2416a31a0d6SSam Clegg // section. 2426a31a0d6SSam Clegg std::vector<WasmCustomSection> CustomSections; 243cbda16ebSThomas Lively std::unique_ptr<WasmCustomSection> ProducersSection; 244f6f4f843SThomas Lively std::unique_ptr<WasmCustomSection> TargetFeaturesSection; 2456a31a0d6SSam Clegg // Relocations for fixing up references in the custom sections. 2466a31a0d6SSam Clegg DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>> 2476a31a0d6SSam Clegg CustomSectionsRelocations; 248acd7d2b0SSam Clegg 249c0d41195SSam Clegg // Map from section to defining function symbol. 2506ccb59b3SSam Clegg DenseMap<const MCSection *, const MCSymbol *> SectionFunctions; 2516ccb59b3SSam Clegg 252da419bdbSHeejin Ahn DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices; 253da419bdbSHeejin Ahn SmallVector<WasmSignature, 4> Signatures; 2546c899ba6SSam Clegg SmallVector<WasmDataSegment, 4> DataSegments; 2559f3fe42eSSam Clegg unsigned NumFunctionImports = 0; 2567c395943SSam Clegg unsigned NumGlobalImports = 0; 257da419bdbSHeejin Ahn unsigned NumEventImports = 0; 2587e1c3345SChandler Carruth uint32_t SectionCount = 0; 259d934cb88SDan Gohman 26018eafb6cSDan Gohman // TargetObjectWriter wrappers. 26118eafb6cSDan Gohman bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 262da84b688SDan Gohman bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); } 26318eafb6cSDan Gohman 2642322a937SSam Clegg void startSection(SectionBookkeeping &Section, unsigned SectionId); 2652322a937SSam Clegg void startCustomSection(SectionBookkeeping &Section, StringRef Name); 266d934cb88SDan Gohman void endSection(SectionBookkeeping &Section); 267d934cb88SDan Gohman 26818eafb6cSDan Gohman public: 2691301a878SLang Hames WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 2701301a878SLang Hames raw_pwrite_stream &OS) 27159a6fc46SPeter Collingbourne : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {} 27218eafb6cSDan Gohman 2730917c9e4SDan Gohman private: 274acd7d2b0SSam Clegg void reset() override { 275acd7d2b0SSam Clegg CodeRelocations.clear(); 276acd7d2b0SSam Clegg DataRelocations.clear(); 277acd7d2b0SSam Clegg TypeIndices.clear(); 2786c899ba6SSam Clegg WasmIndices.clear(); 279492f7529SSam Clegg GOTIndices.clear(); 280f9edbe95SSam Clegg TableIndices.clear(); 2816c899ba6SSam Clegg DataLocations.clear(); 282cbda16ebSThomas Lively CustomSections.clear(); 283cbda16ebSThomas Lively ProducersSection.reset(); 284f6f4f843SThomas Lively TargetFeaturesSection.reset(); 2856a31a0d6SSam Clegg CustomSectionsRelocations.clear(); 286da419bdbSHeejin Ahn SignatureIndices.clear(); 287da419bdbSHeejin Ahn Signatures.clear(); 2886c899ba6SSam Clegg DataSegments.clear(); 2896ccb59b3SSam Clegg SectionFunctions.clear(); 2909f3fe42eSSam Clegg NumFunctionImports = 0; 2917c395943SSam Clegg NumGlobalImports = 0; 292105bdc25SSam Clegg MCObjectWriter::reset(); 293acd7d2b0SSam Clegg } 294acd7d2b0SSam Clegg 29518eafb6cSDan Gohman void writeHeader(const MCAssembler &Asm); 29618eafb6cSDan Gohman 29718eafb6cSDan Gohman void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 29818eafb6cSDan Gohman const MCFragment *Fragment, const MCFixup &Fixup, 299ceecfe5bSRafael Espindola MCValue Target, uint64_t &FixedValue) override; 30018eafb6cSDan Gohman 30118eafb6cSDan Gohman void executePostLayoutBinding(MCAssembler &Asm, 30218eafb6cSDan Gohman const MCAsmLayout &Layout) override; 30318eafb6cSDan Gohman 304438390faSPeter Collingbourne uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 3059e15f359SSam Clegg 306b7787fd0SSam Clegg void writeString(const StringRef Str) { 307f17b149dSPeter Collingbourne encodeULEB128(Str.size(), W.OS); 308f17b149dSPeter Collingbourne W.OS << Str; 309b7787fd0SSam Clegg } 310b7787fd0SSam Clegg 3110a6c4d8dSSam Clegg void writeI32(int32_t val) { 3120a6c4d8dSSam Clegg char Buffer[4]; 3130a6c4d8dSSam Clegg support::endian::write32le(Buffer, val); 3140a6c4d8dSSam Clegg W.OS.write(Buffer, sizeof(Buffer)); 3150a6c4d8dSSam Clegg } 3160a6c4d8dSSam Clegg 3170a6c4d8dSSam Clegg void writeI64(int64_t val) { 3180a6c4d8dSSam Clegg char Buffer[8]; 3190a6c4d8dSSam Clegg support::endian::write64le(Buffer, val); 3200a6c4d8dSSam Clegg W.OS.write(Buffer, sizeof(Buffer)); 3210a6c4d8dSSam Clegg } 3220a6c4d8dSSam Clegg 323f208f631SHeejin Ahn void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); } 3249e15f359SSam Clegg 325da419bdbSHeejin Ahn void writeTypeSection(ArrayRef<WasmSignature> Signatures); 3268defa952SSam Clegg void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize, 327f950b24aSSam Clegg uint32_t NumElements); 328457fb0b4SSam Clegg void writeFunctionSection(ArrayRef<WasmFunction> Functions); 3298defa952SSam Clegg void writeExportSection(ArrayRef<wasm::WasmExport> Exports); 330457fb0b4SSam Clegg void writeElemSection(ArrayRef<uint32_t> TableElems); 331fef8de66SThomas Lively void writeDataCountSection(); 3329e15f359SSam Clegg void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout, 333457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions); 3346c899ba6SSam Clegg void writeDataSection(); 335da419bdbSHeejin Ahn void writeEventSection(ArrayRef<wasm::WasmEventType> Events); 3360a6c4d8dSSam Clegg void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals); 3376f08c84aSSam Clegg void writeRelocSection(uint32_t SectionIndex, StringRef Name, 338f77dc2a8SSam Clegg std::vector<WasmRelocationEntry> &Relocations); 33931a2c809SSam Clegg void writeLinkingMetaDataSection( 34086b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 341ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 342ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats); 343cbda16ebSThomas Lively void writeCustomSection(WasmCustomSection &CustomSection, 344cbda16ebSThomas Lively const MCAssembler &Asm, const MCAsmLayout &Layout); 3456a31a0d6SSam Clegg void writeCustomRelocSections(); 3466a31a0d6SSam Clegg void 3476a31a0d6SSam Clegg updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions, 3486a31a0d6SSam Clegg const MCAsmLayout &Layout); 349acd7d2b0SSam Clegg 3507c395943SSam Clegg uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry); 351acd7d2b0SSam Clegg void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations, 352acd7d2b0SSam Clegg uint64_t ContentsOffset); 353acd7d2b0SSam Clegg 354acd7d2b0SSam Clegg uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry); 3555e3d33a7SSam Clegg uint32_t getFunctionType(const MCSymbolWasm &Symbol); 356da419bdbSHeejin Ahn uint32_t getEventType(const MCSymbolWasm &Symbol); 35738b12f5eSHeejin Ahn void registerFunctionType(const MCSymbolWasm &Symbol); 35838b12f5eSHeejin Ahn void registerEventType(const MCSymbolWasm &Symbol); 35918eafb6cSDan Gohman }; 3609e15f359SSam Clegg 36118eafb6cSDan Gohman } // end anonymous namespace 36218eafb6cSDan Gohman 363d934cb88SDan Gohman // Write out a section header and a patchable section size field. 364d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section, 3652322a937SSam Clegg unsigned SectionId) { 366d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n"); 367f17b149dSPeter Collingbourne W.OS << char(SectionId); 368d934cb88SDan Gohman 369f17b149dSPeter Collingbourne Section.SizeOffset = W.OS.tell(); 370d934cb88SDan Gohman 371d934cb88SDan Gohman // The section size. We don't know the size yet, so reserve enough space 372d934cb88SDan Gohman // for any 32-bit value; we'll patch it later. 37319e8befaSSam Clegg encodeULEB128(0, W.OS, 5); 374d934cb88SDan Gohman 375d934cb88SDan Gohman // The position where the section starts, for measuring its size. 376f17b149dSPeter Collingbourne Section.ContentsOffset = W.OS.tell(); 377f17b149dSPeter Collingbourne Section.PayloadOffset = W.OS.tell(); 3786f08c84aSSam Clegg Section.Index = SectionCount++; 379d934cb88SDan Gohman } 3802322a937SSam Clegg 3812322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section, 3822322a937SSam Clegg StringRef Name) { 383d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n"); 3842322a937SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM); 3856a31a0d6SSam Clegg 3866a31a0d6SSam Clegg // The position where the section header ends, for measuring its size. 387f17b149dSPeter Collingbourne Section.PayloadOffset = W.OS.tell(); 3886a31a0d6SSam Clegg 3892322a937SSam Clegg // Custom sections in wasm also have a string identifier. 3902322a937SSam Clegg writeString(Name); 3916a31a0d6SSam Clegg 3926a31a0d6SSam Clegg // The position where the custom section starts. 393f17b149dSPeter Collingbourne Section.ContentsOffset = W.OS.tell(); 394d934cb88SDan Gohman } 395d934cb88SDan Gohman 396d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the 397d934cb88SDan Gohman // section size field at the start of the section. 398d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) { 399c0affde8SSam Clegg uint64_t Size = W.OS.tell(); 400c0affde8SSam Clegg // /dev/null doesn't support seek/tell and can report offset of 0. 401c0affde8SSam Clegg // Simply skip this patching in that case. 402c0affde8SSam Clegg if (!Size) 403c0affde8SSam Clegg return; 404c0affde8SSam Clegg 405c0affde8SSam Clegg Size -= Section.PayloadOffset; 406d934cb88SDan Gohman if (uint32_t(Size) != Size) 407d934cb88SDan Gohman report_fatal_error("section size does not fit in a uint32_t"); 408d934cb88SDan Gohman 409d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n"); 410d934cb88SDan Gohman 411d934cb88SDan Gohman // Write the final section size to the payload_len field, which follows 412d934cb88SDan Gohman // the section id byte. 41318c56a07SHeejin Ahn writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size, 414f17b149dSPeter Collingbourne Section.SizeOffset); 415d934cb88SDan Gohman } 416d934cb88SDan Gohman 41718eafb6cSDan Gohman // Emit the Wasm header. 41818eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { 419f17b149dSPeter Collingbourne W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic)); 420f17b149dSPeter Collingbourne W.write<uint32_t>(wasm::WasmVersion); 42118eafb6cSDan Gohman } 42218eafb6cSDan Gohman 42318eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 42418eafb6cSDan Gohman const MCAsmLayout &Layout) { 4256ccb59b3SSam Clegg // Build a map of sections to the function that defines them, for use 4266ccb59b3SSam Clegg // in recordRelocation. 4276ccb59b3SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 4286ccb59b3SSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 4296ccb59b3SSam Clegg if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) { 4306ccb59b3SSam Clegg const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection()); 4316ccb59b3SSam Clegg auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S)); 4326ccb59b3SSam Clegg if (!Pair.second) 4336ccb59b3SSam Clegg report_fatal_error("section already has a defining function: " + 4347d1ff446SFangrui Song Sec.getName()); 4356ccb59b3SSam Clegg } 4366ccb59b3SSam Clegg } 43718eafb6cSDan Gohman } 43818eafb6cSDan Gohman 43918eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 44018eafb6cSDan Gohman const MCAsmLayout &Layout, 44118eafb6cSDan Gohman const MCFragment *Fragment, 44218eafb6cSDan Gohman const MCFixup &Fixup, MCValue Target, 443ceecfe5bSRafael Espindola uint64_t &FixedValue) { 444ecc5e808SSam Clegg // The WebAssembly backend should never generate FKF_IsPCRel fixups 445e828ce1bSFangrui Song assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags & 446ecc5e808SSam Clegg MCFixupKindInfo::FKF_IsPCRel)); 447ecc5e808SSam Clegg 448fe6414b0SSam Clegg const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 449d934cb88SDan Gohman uint64_t C = Target.getConstant(); 450d934cb88SDan Gohman uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 451d934cb88SDan Gohman MCContext &Ctx = Asm.getContext(); 452d934cb88SDan Gohman 453d934cb88SDan Gohman if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 454ecc5e808SSam Clegg // To get here the A - B expression must have failed evaluateAsRelocatable. 455ecc5e808SSam Clegg // This means either A or B must be undefined and in WebAssembly we can't 456ecc5e808SSam Clegg // support either of those cases. 457ecc5e808SSam Clegg const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 458d934cb88SDan Gohman Ctx.reportError( 459d934cb88SDan Gohman Fixup.getLoc(), 460d934cb88SDan Gohman Twine("symbol '") + SymB.getName() + 461ecc5e808SSam Clegg "': unsupported subtraction expression used in relocation."); 462d934cb88SDan Gohman return; 463d934cb88SDan Gohman } 464d934cb88SDan Gohman 465d934cb88SDan Gohman // We either rejected the fixup or folded B into C at this point. 466d934cb88SDan Gohman const MCSymbolRefExpr *RefA = Target.getSymA(); 467ecc5e808SSam Clegg const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol()); 468d934cb88SDan Gohman 4693ea1c62cSSam Clegg // The .init_array isn't translated as data, so don't do relocations in it. 4707d1ff446SFangrui Song if (FixupSection.getName().startswith(".init_array")) { 4713ea1c62cSSam Clegg SymA->setUsedInInitArray(); 4723ea1c62cSSam Clegg return; 4733ea1c62cSSam Clegg } 4743ea1c62cSSam Clegg 475ecc5e808SSam Clegg if (SymA->isVariable()) { 476d934cb88SDan Gohman const MCExpr *Expr = SymA->getVariableValue(); 4776ad8f190SSam Clegg const auto *Inner = cast<MCSymbolRefExpr>(Expr); 4786ad8f190SSam Clegg if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) 4796ad8f190SSam Clegg llvm_unreachable("weakref used in reloc not yet implemented"); 480d934cb88SDan Gohman } 481d934cb88SDan Gohman 482d934cb88SDan Gohman // Put any constant offset in an addend. Offsets can be negative, and 483d934cb88SDan Gohman // LLVM expects wrapping, in contrast to wasm's immediates which can't 484d934cb88SDan Gohman // be negative and don't wrap. 485d934cb88SDan Gohman FixedValue = 0; 486d934cb88SDan Gohman 487a5e175c6SSam Clegg unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup); 4889d24fb7fSSam Clegg 4894d57fbd0SSam Clegg // Absolute offset within a section or a function. 4904d57fbd0SSam Clegg // Currently only supported for for metadata sections. 4914d57fbd0SSam Clegg // See: test/MC/WebAssembly/blockaddress.ll 492d1152a26SSam Clegg if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 || 493d1152a26SSam Clegg Type == wasm::R_WASM_SECTION_OFFSET_I32) { 4944d57fbd0SSam Clegg if (!FixupSection.getKind().isMetadata()) 4954d57fbd0SSam Clegg report_fatal_error("relocations for function or section offsets are " 4964d57fbd0SSam Clegg "only supported in metadata sections"); 4974d57fbd0SSam Clegg 4984d57fbd0SSam Clegg const MCSymbol *SectionSymbol = nullptr; 4994d57fbd0SSam Clegg const MCSection &SecA = SymA->getSection(); 5004d57fbd0SSam Clegg if (SecA.getKind().isText()) 5016ccb59b3SSam Clegg SectionSymbol = SectionFunctions.find(&SecA)->second; 5024d57fbd0SSam Clegg else 5034d57fbd0SSam Clegg SectionSymbol = SecA.getBeginSymbol(); 5044d57fbd0SSam Clegg if (!SectionSymbol) 5054d57fbd0SSam Clegg report_fatal_error("section symbol is required for relocation"); 5064d57fbd0SSam Clegg 5074d57fbd0SSam Clegg C += Layout.getSymbolOffset(*SymA); 5084d57fbd0SSam Clegg SymA = cast<MCSymbolWasm>(SectionSymbol); 5094d57fbd0SSam Clegg } 5104d57fbd0SSam Clegg 511d1152a26SSam Clegg // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be 5124d57fbd0SSam Clegg // against a named symbol. 513d1152a26SSam Clegg if (Type != wasm::R_WASM_TYPE_INDEX_LEB) { 5144d57fbd0SSam Clegg if (SymA->getName().empty()) 5154d57fbd0SSam Clegg report_fatal_error("relocations against un-named temporaries are not yet " 5164d57fbd0SSam Clegg "supported by wasm"); 5174d57fbd0SSam Clegg 5184d57fbd0SSam Clegg SymA->setUsedInReloc(); 5194d57fbd0SSam Clegg } 520ae03c1e7SSam Clegg 521492f7529SSam Clegg if (RefA->getKind() == MCSymbolRefExpr::VK_GOT) 522492f7529SSam Clegg SymA->setUsedInGOT(); 523492f7529SSam Clegg 524d934cb88SDan Gohman WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 525d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 526d934cb88SDan Gohman 5276a31a0d6SSam Clegg if (FixupSection.isWasmData()) { 528d934cb88SDan Gohman DataRelocations.push_back(Rec); 5296a31a0d6SSam Clegg } else if (FixupSection.getKind().isText()) { 53012fd3da9SSam Clegg CodeRelocations.push_back(Rec); 5316a31a0d6SSam Clegg } else if (FixupSection.getKind().isMetadata()) { 5326a31a0d6SSam Clegg CustomSectionsRelocations[&FixupSection].push_back(Rec); 5336a31a0d6SSam Clegg } else { 53412fd3da9SSam Clegg llvm_unreachable("unexpected section type"); 535d934cb88SDan Gohman } 5366a31a0d6SSam Clegg } 537d934cb88SDan Gohman 53818c56a07SHeejin Ahn static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) { 539ffba00bdSSam Clegg const MCSymbolWasm* Ret = &Symbol; 540ffba00bdSSam Clegg while (Ret->isVariable()) { 541ffba00bdSSam Clegg const MCExpr *Expr = Ret->getVariableValue(); 542aff1c4dfSSam Clegg auto *Inner = cast<MCSymbolRefExpr>(Expr); 543ffba00bdSSam Clegg Ret = cast<MCSymbolWasm>(&Inner->getSymbol()); 544aff1c4dfSSam Clegg } 545ffba00bdSSam Clegg return Ret; 546aff1c4dfSSam Clegg } 547aff1c4dfSSam Clegg 548d934cb88SDan Gohman // Compute a value to write into the code at the location covered 54960ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves 55060ec3034SSam Clegg // to make the object format more readable and more likely to be directly 55160ec3034SSam Clegg // useable. 5527c395943SSam Clegg uint32_t 5537c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) { 55448139ebcSWouter van Oortmerssen if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB || 55548139ebcSWouter van Oortmerssen RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) && 55648139ebcSWouter van Oortmerssen !RelEntry.Symbol->isGlobal()) { 557492f7529SSam Clegg assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space"); 558492f7529SSam Clegg return GOTIndices[RelEntry.Symbol]; 559492f7529SSam Clegg } 560492f7529SSam Clegg 56160ec3034SSam Clegg switch (RelEntry.Type) { 5622a7cac93SSam Clegg case wasm::R_WASM_TABLE_INDEX_REL_SLEB: 563d1152a26SSam Clegg case wasm::R_WASM_TABLE_INDEX_SLEB: 564d1152a26SSam Clegg case wasm::R_WASM_TABLE_INDEX_I32: { 565f9edbe95SSam Clegg // Provisional value is table address of the resolved symbol itself 56618c56a07SHeejin Ahn const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol); 567f9edbe95SSam Clegg assert(Sym->isFunction()); 568*81443ac1SSam Clegg if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB) 569*81443ac1SSam Clegg return TableIndices[Sym] - InitialTableOffset; 570*81443ac1SSam Clegg else 571f9edbe95SSam Clegg return TableIndices[Sym]; 572f9edbe95SSam Clegg } 573d1152a26SSam Clegg case wasm::R_WASM_TYPE_INDEX_LEB: 5746c899ba6SSam Clegg // Provisional value is same as the index 57560ec3034SSam Clegg return getRelocationIndexValue(RelEntry); 576d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_INDEX_LEB: 577d1152a26SSam Clegg case wasm::R_WASM_GLOBAL_INDEX_LEB: 57848139ebcSWouter van Oortmerssen case wasm::R_WASM_GLOBAL_INDEX_I32: 579d1152a26SSam Clegg case wasm::R_WASM_EVENT_INDEX_LEB: 580da419bdbSHeejin Ahn // Provisional value is function/global/event Wasm index 581492f7529SSam Clegg assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space"); 5826c899ba6SSam Clegg return WasmIndices[RelEntry.Symbol]; 583d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_OFFSET_I32: 584d1152a26SSam Clegg case wasm::R_WASM_SECTION_OFFSET_I32: { 5856a31a0d6SSam Clegg const auto &Section = 5866a31a0d6SSam Clegg static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection()); 5876a31a0d6SSam Clegg return Section.getSectionOffset() + RelEntry.Addend; 5886a31a0d6SSam Clegg } 589d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_LEB: 590d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_I32: 5912a7cac93SSam Clegg case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 592d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_SLEB: { 593f9edbe95SSam Clegg // Provisional value is address of the global 59418c56a07SHeejin Ahn const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol); 595270ed1b3SSam Clegg // For undefined symbols, use zero 596cd65f698SSam Clegg if (!Sym->isDefined()) 597270ed1b3SSam Clegg return 0; 5986c899ba6SSam Clegg const wasm::WasmDataReference &Ref = DataLocations[Sym]; 5996c899ba6SSam Clegg const WasmDataSegment &Segment = DataSegments[Ref.Segment]; 600d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 6016c899ba6SSam Clegg return Segment.Offset + Ref.Offset + RelEntry.Addend; 60260ec3034SSam Clegg } 60360ec3034SSam Clegg default: 60460ec3034SSam Clegg llvm_unreachable("invalid relocation type"); 60560ec3034SSam Clegg } 606d934cb88SDan Gohman } 607d934cb88SDan Gohman 608759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes, 60963ebb813SSam Clegg MCSectionWasm &DataSection) { 6107d1ff446SFangrui Song LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n"); 611759631c7SSam Clegg 61263ebb813SSam Clegg DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 61363ebb813SSam Clegg 614759631c7SSam Clegg for (const MCFragment &Frag : DataSection) { 615759631c7SSam Clegg if (Frag.hasInstructions()) 616759631c7SSam Clegg report_fatal_error("only data supported in data sections"); 617759631c7SSam Clegg 618759631c7SSam Clegg if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 619759631c7SSam Clegg if (Align->getValueSize() != 1) 620759631c7SSam Clegg report_fatal_error("only byte values supported for alignment"); 621759631c7SSam Clegg // If nops are requested, use zeros, as this is the data section. 622759631c7SSam Clegg uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 623f208f631SHeejin Ahn uint64_t Size = 624f208f631SHeejin Ahn std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()), 625f208f631SHeejin Ahn DataBytes.size() + Align->getMaxBytesToEmit()); 626759631c7SSam Clegg DataBytes.resize(Size, Value); 627759631c7SSam Clegg } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 628588fad4dSNirav Dave int64_t NumValues; 629588fad4dSNirav Dave if (!Fill->getNumValues().evaluateAsAbsolute(NumValues)) 630d707c370SRafael Espindola llvm_unreachable("The fill should be an assembler constant"); 631588fad4dSNirav Dave DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues, 632588fad4dSNirav Dave Fill->getValue()); 63324faf859SHeejin Ahn } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) { 63424faf859SHeejin Ahn const SmallVectorImpl<char> &Contents = LEB->getContents(); 63524faf859SHeejin Ahn DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 636759631c7SSam Clegg } else { 637759631c7SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 638759631c7SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 639759631c7SSam Clegg DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 640759631c7SSam Clegg } 641759631c7SSam Clegg } 642759631c7SSam Clegg 643d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 644759631c7SSam Clegg } 645759631c7SSam Clegg 64660ec3034SSam Clegg uint32_t 64760ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) { 648d1152a26SSam Clegg if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) { 649b7787fd0SSam Clegg if (!TypeIndices.count(RelEntry.Symbol)) 650b7787fd0SSam Clegg report_fatal_error("symbol not found in type index space: " + 651b7787fd0SSam Clegg RelEntry.Symbol->getName()); 652acd7d2b0SSam Clegg return TypeIndices[RelEntry.Symbol]; 653acd7d2b0SSam Clegg } 65460ec3034SSam Clegg 65525d8e68bSSam Clegg return RelEntry.Symbol->getIndex(); 656acd7d2b0SSam Clegg } 657acd7d2b0SSam Clegg 658d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 659d934cb88SDan Gohman // directly. 660acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations( 661acd7d2b0SSam Clegg ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) { 662f17b149dSPeter Collingbourne auto &Stream = static_cast<raw_pwrite_stream &>(W.OS); 663d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 664d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 665d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 666d934cb88SDan Gohman RelEntry.Offset; 667d934cb88SDan Gohman 668d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 66960ec3034SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 67060ec3034SSam Clegg 671acd7d2b0SSam Clegg switch (RelEntry.Type) { 672d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_INDEX_LEB: 673d1152a26SSam Clegg case wasm::R_WASM_TYPE_INDEX_LEB: 674d1152a26SSam Clegg case wasm::R_WASM_GLOBAL_INDEX_LEB: 675d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_LEB: 676d1152a26SSam Clegg case wasm::R_WASM_EVENT_INDEX_LEB: 67718c56a07SHeejin Ahn writePatchableLEB(Stream, Value, Offset); 678d934cb88SDan Gohman break; 679d1152a26SSam Clegg case wasm::R_WASM_TABLE_INDEX_I32: 680d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_I32: 681d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_OFFSET_I32: 682d1152a26SSam Clegg case wasm::R_WASM_SECTION_OFFSET_I32: 68348139ebcSWouter van Oortmerssen case wasm::R_WASM_GLOBAL_INDEX_I32: 6840a6c4d8dSSam Clegg patchI32(Stream, Value, Offset); 685d934cb88SDan Gohman break; 686d1152a26SSam Clegg case wasm::R_WASM_TABLE_INDEX_SLEB: 6872a7cac93SSam Clegg case wasm::R_WASM_TABLE_INDEX_REL_SLEB: 688d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_SLEB: 6892a7cac93SSam Clegg case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 69018c56a07SHeejin Ahn writePatchableSLEB(Stream, Value, Offset); 69160ec3034SSam Clegg break; 692d934cb88SDan Gohman default: 6939d24fb7fSSam Clegg llvm_unreachable("invalid relocation type"); 694d934cb88SDan Gohman } 695d934cb88SDan Gohman } 69618eafb6cSDan Gohman } 69718eafb6cSDan Gohman 698da419bdbSHeejin Ahn void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) { 699da419bdbSHeejin Ahn if (Signatures.empty()) 7009e15f359SSam Clegg return; 7019e15f359SSam Clegg 7029e15f359SSam Clegg SectionBookkeeping Section; 7039e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TYPE); 7049e15f359SSam Clegg 705da419bdbSHeejin Ahn encodeULEB128(Signatures.size(), W.OS); 7069e15f359SSam Clegg 707da419bdbSHeejin Ahn for (const WasmSignature &Sig : Signatures) { 708f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_TYPE_FUNC); 709da419bdbSHeejin Ahn encodeULEB128(Sig.Params.size(), W.OS); 710da419bdbSHeejin Ahn for (wasm::ValType Ty : Sig.Params) 7119e15f359SSam Clegg writeValueType(Ty); 712da419bdbSHeejin Ahn encodeULEB128(Sig.Returns.size(), W.OS); 713da419bdbSHeejin Ahn for (wasm::ValType Ty : Sig.Returns) 7149e15f359SSam Clegg writeValueType(Ty); 7159e15f359SSam Clegg } 7169e15f359SSam Clegg 7179e15f359SSam Clegg endSection(Section); 7189e15f359SSam Clegg } 7199e15f359SSam Clegg 7208defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports, 721f950b24aSSam Clegg uint32_t DataSize, 722f950b24aSSam Clegg uint32_t NumElements) { 7239e15f359SSam Clegg if (Imports.empty()) 7249e15f359SSam Clegg return; 7259e15f359SSam Clegg 726f950b24aSSam Clegg uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 727f950b24aSSam Clegg 7289e15f359SSam Clegg SectionBookkeeping Section; 7299e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_IMPORT); 7309e15f359SSam Clegg 731f17b149dSPeter Collingbourne encodeULEB128(Imports.size(), W.OS); 7328defa952SSam Clegg for (const wasm::WasmImport &Import : Imports) { 7338defa952SSam Clegg writeString(Import.Module); 7348defa952SSam Clegg writeString(Import.Field); 735f17b149dSPeter Collingbourne W.OS << char(Import.Kind); 7369e15f359SSam Clegg 7379e15f359SSam Clegg switch (Import.Kind) { 7389e15f359SSam Clegg case wasm::WASM_EXTERNAL_FUNCTION: 739f17b149dSPeter Collingbourne encodeULEB128(Import.SigIndex, W.OS); 7409e15f359SSam Clegg break; 7419e15f359SSam Clegg case wasm::WASM_EXTERNAL_GLOBAL: 742f17b149dSPeter Collingbourne W.OS << char(Import.Global.Type); 743f17b149dSPeter Collingbourne W.OS << char(Import.Global.Mutable ? 1 : 0); 7449e15f359SSam Clegg break; 745f950b24aSSam Clegg case wasm::WASM_EXTERNAL_MEMORY: 746f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // flags 747f17b149dSPeter Collingbourne encodeULEB128(NumPages, W.OS); // initial 748f950b24aSSam Clegg break; 749f950b24aSSam Clegg case wasm::WASM_EXTERNAL_TABLE: 750f17b149dSPeter Collingbourne W.OS << char(Import.Table.ElemType); 751f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // flags 752f17b149dSPeter Collingbourne encodeULEB128(NumElements, W.OS); // initial 753f950b24aSSam Clegg break; 754da419bdbSHeejin Ahn case wasm::WASM_EXTERNAL_EVENT: 755da419bdbSHeejin Ahn encodeULEB128(Import.Event.Attribute, W.OS); 756da419bdbSHeejin Ahn encodeULEB128(Import.Event.SigIndex, W.OS); 757da419bdbSHeejin Ahn break; 7589e15f359SSam Clegg default: 7599e15f359SSam Clegg llvm_unreachable("unsupported import kind"); 7609e15f359SSam Clegg } 7619e15f359SSam Clegg } 7629e15f359SSam Clegg 7639e15f359SSam Clegg endSection(Section); 7649e15f359SSam Clegg } 7659e15f359SSam Clegg 766457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 7679e15f359SSam Clegg if (Functions.empty()) 7689e15f359SSam Clegg return; 7699e15f359SSam Clegg 7709e15f359SSam Clegg SectionBookkeeping Section; 7719e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_FUNCTION); 7729e15f359SSam Clegg 773f17b149dSPeter Collingbourne encodeULEB128(Functions.size(), W.OS); 7749e15f359SSam Clegg for (const WasmFunction &Func : Functions) 775da419bdbSHeejin Ahn encodeULEB128(Func.SigIndex, W.OS); 7769e15f359SSam Clegg 7779e15f359SSam Clegg endSection(Section); 7789e15f359SSam Clegg } 7799e15f359SSam Clegg 780da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) { 781da419bdbSHeejin Ahn if (Events.empty()) 782da419bdbSHeejin Ahn return; 783da419bdbSHeejin Ahn 784da419bdbSHeejin Ahn SectionBookkeeping Section; 785da419bdbSHeejin Ahn startSection(Section, wasm::WASM_SEC_EVENT); 786da419bdbSHeejin Ahn 787da419bdbSHeejin Ahn encodeULEB128(Events.size(), W.OS); 788da419bdbSHeejin Ahn for (const wasm::WasmEventType &Event : Events) { 789da419bdbSHeejin Ahn encodeULEB128(Event.Attribute, W.OS); 790da419bdbSHeejin Ahn encodeULEB128(Event.SigIndex, W.OS); 791da419bdbSHeejin Ahn } 792da419bdbSHeejin Ahn 793da419bdbSHeejin Ahn endSection(Section); 794da419bdbSHeejin Ahn } 795da419bdbSHeejin Ahn 7960a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) { 7970a6c4d8dSSam Clegg if (Globals.empty()) 7980a6c4d8dSSam Clegg return; 7990a6c4d8dSSam Clegg 8000a6c4d8dSSam Clegg SectionBookkeeping Section; 8010a6c4d8dSSam Clegg startSection(Section, wasm::WASM_SEC_GLOBAL); 8020a6c4d8dSSam Clegg 8030a6c4d8dSSam Clegg encodeULEB128(Globals.size(), W.OS); 8040a6c4d8dSSam Clegg for (const wasm::WasmGlobal &Global : Globals) { 8050a6c4d8dSSam Clegg encodeULEB128(Global.Type.Type, W.OS); 8060a6c4d8dSSam Clegg W.OS << char(Global.Type.Mutable); 8070a6c4d8dSSam Clegg W.OS << char(Global.InitExpr.Opcode); 8080a6c4d8dSSam Clegg switch (Global.Type.Type) { 8090a6c4d8dSSam Clegg case wasm::WASM_TYPE_I32: 8100a6c4d8dSSam Clegg encodeSLEB128(0, W.OS); 8110a6c4d8dSSam Clegg break; 8120a6c4d8dSSam Clegg case wasm::WASM_TYPE_I64: 8130a6c4d8dSSam Clegg encodeSLEB128(0, W.OS); 8140a6c4d8dSSam Clegg break; 8150a6c4d8dSSam Clegg case wasm::WASM_TYPE_F32: 8160a6c4d8dSSam Clegg writeI32(0); 8170a6c4d8dSSam Clegg break; 8180a6c4d8dSSam Clegg case wasm::WASM_TYPE_F64: 8190a6c4d8dSSam Clegg writeI64(0); 8200a6c4d8dSSam Clegg break; 8210a6c4d8dSSam Clegg default: 8220a6c4d8dSSam Clegg llvm_unreachable("unexpected type"); 8230a6c4d8dSSam Clegg } 8240a6c4d8dSSam Clegg W.OS << char(wasm::WASM_OPCODE_END); 8250a6c4d8dSSam Clegg } 8260a6c4d8dSSam Clegg 8270a6c4d8dSSam Clegg endSection(Section); 8280a6c4d8dSSam Clegg } 8290a6c4d8dSSam Clegg 8308defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) { 8319e15f359SSam Clegg if (Exports.empty()) 8329e15f359SSam Clegg return; 8339e15f359SSam Clegg 8349e15f359SSam Clegg SectionBookkeeping Section; 8359e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_EXPORT); 8369e15f359SSam Clegg 837f17b149dSPeter Collingbourne encodeULEB128(Exports.size(), W.OS); 8388defa952SSam Clegg for (const wasm::WasmExport &Export : Exports) { 8398defa952SSam Clegg writeString(Export.Name); 840f17b149dSPeter Collingbourne W.OS << char(Export.Kind); 841f17b149dSPeter Collingbourne encodeULEB128(Export.Index, W.OS); 8429e15f359SSam Clegg } 8439e15f359SSam Clegg 8449e15f359SSam Clegg endSection(Section); 8459e15f359SSam Clegg } 8469e15f359SSam Clegg 847457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 8489e15f359SSam Clegg if (TableElems.empty()) 8499e15f359SSam Clegg return; 8509e15f359SSam Clegg 8519e15f359SSam Clegg SectionBookkeeping Section; 8529e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_ELEM); 8539e15f359SSam Clegg 854f17b149dSPeter Collingbourne encodeULEB128(1, W.OS); // number of "segments" 855f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // the table index 8569e15f359SSam Clegg 8579e15f359SSam Clegg // init expr for starting offset 858f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_I32_CONST); 85918c56a07SHeejin Ahn encodeSLEB128(InitialTableOffset, W.OS); 860f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_END); 8619e15f359SSam Clegg 862f17b149dSPeter Collingbourne encodeULEB128(TableElems.size(), W.OS); 8639e15f359SSam Clegg for (uint32_t Elem : TableElems) 864f17b149dSPeter Collingbourne encodeULEB128(Elem, W.OS); 8659e15f359SSam Clegg 8669e15f359SSam Clegg endSection(Section); 8679e15f359SSam Clegg } 8689e15f359SSam Clegg 869fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() { 870fef8de66SThomas Lively if (DataSegments.empty()) 871fef8de66SThomas Lively return; 872fef8de66SThomas Lively 873fef8de66SThomas Lively SectionBookkeeping Section; 874fef8de66SThomas Lively startSection(Section, wasm::WASM_SEC_DATACOUNT); 875fef8de66SThomas Lively encodeULEB128(DataSegments.size(), W.OS); 876fef8de66SThomas Lively endSection(Section); 877fef8de66SThomas Lively } 878fef8de66SThomas Lively 879457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 880457fb0b4SSam Clegg const MCAsmLayout &Layout, 881457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions) { 8829e15f359SSam Clegg if (Functions.empty()) 8839e15f359SSam Clegg return; 8849e15f359SSam Clegg 8859e15f359SSam Clegg SectionBookkeeping Section; 8869e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CODE); 8876f08c84aSSam Clegg CodeSectionIndex = Section.Index; 8889e15f359SSam Clegg 889f17b149dSPeter Collingbourne encodeULEB128(Functions.size(), W.OS); 8909e15f359SSam Clegg 8919e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 892fe6414b0SSam Clegg auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 8939e15f359SSam Clegg 8949e15f359SSam Clegg int64_t Size = 0; 8959e15f359SSam Clegg if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 8969e15f359SSam Clegg report_fatal_error(".size expression must be evaluatable"); 8979e15f359SSam Clegg 898f17b149dSPeter Collingbourne encodeULEB128(Size, W.OS); 899f17b149dSPeter Collingbourne FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset); 900f17b149dSPeter Collingbourne Asm.writeSectionData(W.OS, &FuncSection, Layout); 9019e15f359SSam Clegg } 9029e15f359SSam Clegg 9039e15f359SSam Clegg // Apply fixups. 904acd7d2b0SSam Clegg applyRelocations(CodeRelocations, Section.ContentsOffset); 9059e15f359SSam Clegg 9069e15f359SSam Clegg endSection(Section); 9079e15f359SSam Clegg } 9089e15f359SSam Clegg 9096c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() { 9106c899ba6SSam Clegg if (DataSegments.empty()) 9117c395943SSam Clegg return; 9129e15f359SSam Clegg 9139e15f359SSam Clegg SectionBookkeeping Section; 9149e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_DATA); 9156f08c84aSSam Clegg DataSectionIndex = Section.Index; 9169e15f359SSam Clegg 917f17b149dSPeter Collingbourne encodeULEB128(DataSegments.size(), W.OS); // count 9187c395943SSam Clegg 9196c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 9202e150409SThomas Lively encodeULEB128(Segment.InitFlags, W.OS); // flags 9212e150409SThomas Lively if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX) 922f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // memory index 9232e150409SThomas Lively if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) { 924f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_I32_CONST); 925f17b149dSPeter Collingbourne encodeSLEB128(Segment.Offset, W.OS); // offset 926f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_END); 9272e150409SThomas Lively } 928f17b149dSPeter Collingbourne encodeULEB128(Segment.Data.size(), W.OS); // size 929f17b149dSPeter Collingbourne Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset); 930f17b149dSPeter Collingbourne W.OS << Segment.Data; // data 9317c395943SSam Clegg } 9329e15f359SSam Clegg 9339e15f359SSam Clegg // Apply fixups. 9347c395943SSam Clegg applyRelocations(DataRelocations, Section.ContentsOffset); 9359e15f359SSam Clegg 9369e15f359SSam Clegg endSection(Section); 9379e15f359SSam Clegg } 9389e15f359SSam Clegg 9396f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection( 9406f08c84aSSam Clegg uint32_t SectionIndex, StringRef Name, 941f77dc2a8SSam Clegg std::vector<WasmRelocationEntry> &Relocs) { 9429e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 9439e15f359SSam Clegg // for descriptions of the reloc sections. 9449e15f359SSam Clegg 945f77dc2a8SSam Clegg if (Relocs.empty()) 9469e15f359SSam Clegg return; 9479e15f359SSam Clegg 948f77dc2a8SSam Clegg // First, ensure the relocations are sorted in offset order. In general they 949f77dc2a8SSam Clegg // should already be sorted since `recordRelocation` is called in offset 950f77dc2a8SSam Clegg // order, but for the code section we combine many MC sections into single 951f77dc2a8SSam Clegg // wasm section, and this order is determined by the order of Asm.Symbols() 952f77dc2a8SSam Clegg // not the sections order. 953efd94c56SFangrui Song llvm::stable_sort( 954efd94c56SFangrui Song Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) { 955f77dc2a8SSam Clegg return (A.Offset + A.FixupSection->getSectionOffset()) < 956f77dc2a8SSam Clegg (B.Offset + B.FixupSection->getSectionOffset()); 957f77dc2a8SSam Clegg }); 958f77dc2a8SSam Clegg 9599e15f359SSam Clegg SectionBookkeeping Section; 9606f08c84aSSam Clegg startCustomSection(Section, std::string("reloc.") + Name.str()); 9619e15f359SSam Clegg 962f17b149dSPeter Collingbourne encodeULEB128(SectionIndex, W.OS); 963f77dc2a8SSam Clegg encodeULEB128(Relocs.size(), W.OS); 964f77dc2a8SSam Clegg for (const WasmRelocationEntry &RelEntry : Relocs) { 965f208f631SHeejin Ahn uint64_t Offset = 966f208f631SHeejin Ahn RelEntry.Offset + RelEntry.FixupSection->getSectionOffset(); 9676f08c84aSSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 9689e15f359SSam Clegg 969f17b149dSPeter Collingbourne W.OS << char(RelEntry.Type); 970f17b149dSPeter Collingbourne encodeULEB128(Offset, W.OS); 971f17b149dSPeter Collingbourne encodeULEB128(Index, W.OS); 9726f08c84aSSam Clegg if (RelEntry.hasAddend()) 973f17b149dSPeter Collingbourne encodeSLEB128(RelEntry.Addend, W.OS); 9749e15f359SSam Clegg } 9759e15f359SSam Clegg 9769e15f359SSam Clegg endSection(Section); 9779e15f359SSam Clegg } 9789e15f359SSam Clegg 9796a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() { 9806a31a0d6SSam Clegg for (const auto &Sec : CustomSections) { 9816a31a0d6SSam Clegg auto &Relocations = CustomSectionsRelocations[Sec.Section]; 9826a31a0d6SSam Clegg writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations); 9836a31a0d6SSam Clegg } 9846a31a0d6SSam Clegg } 9856a31a0d6SSam Clegg 9869e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection( 98786b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 988ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 989ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) { 9909e15f359SSam Clegg SectionBookkeeping Section; 9912322a937SSam Clegg startCustomSection(Section, "linking"); 992f17b149dSPeter Collingbourne encodeULEB128(wasm::WasmMetadataVersion, W.OS); 9939e15f359SSam Clegg 9946bb5a41fSSam Clegg SectionBookkeeping SubSection; 9956c899ba6SSam Clegg if (SymbolInfos.size() != 0) { 9966c899ba6SSam Clegg startSection(SubSection, wasm::WASM_SYMBOL_TABLE); 997f17b149dSPeter Collingbourne encodeULEB128(SymbolInfos.size(), W.OS); 9986c899ba6SSam Clegg for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) { 999f17b149dSPeter Collingbourne encodeULEB128(Sym.Kind, W.OS); 1000f17b149dSPeter Collingbourne encodeULEB128(Sym.Flags, W.OS); 10016c899ba6SSam Clegg switch (Sym.Kind) { 10026c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_FUNCTION: 10036c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1004da419bdbSHeejin Ahn case wasm::WASM_SYMBOL_TYPE_EVENT: 1005f17b149dSPeter Collingbourne encodeULEB128(Sym.ElementIndex, W.OS); 100629874ceaSDan Gohman if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 || 100729874ceaSDan Gohman (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) 10086c899ba6SSam Clegg writeString(Sym.Name); 10096c899ba6SSam Clegg break; 10106c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_DATA: 10116c899ba6SSam Clegg writeString(Sym.Name); 10126c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) { 1013f17b149dSPeter Collingbourne encodeULEB128(Sym.DataRef.Segment, W.OS); 1014f17b149dSPeter Collingbourne encodeULEB128(Sym.DataRef.Offset, W.OS); 1015f17b149dSPeter Collingbourne encodeULEB128(Sym.DataRef.Size, W.OS); 10166c899ba6SSam Clegg } 10176c899ba6SSam Clegg break; 10186a31a0d6SSam Clegg case wasm::WASM_SYMBOL_TYPE_SECTION: { 10196a31a0d6SSam Clegg const uint32_t SectionIndex = 10206a31a0d6SSam Clegg CustomSections[Sym.ElementIndex].OutputIndex; 1021f17b149dSPeter Collingbourne encodeULEB128(SectionIndex, W.OS); 10226a31a0d6SSam Clegg break; 10236a31a0d6SSam Clegg } 10246c899ba6SSam Clegg default: 10256c899ba6SSam Clegg llvm_unreachable("unexpected kind"); 10266c899ba6SSam Clegg } 1027b7787fd0SSam Clegg } 1028b7787fd0SSam Clegg endSection(SubSection); 1029b7787fd0SSam Clegg } 10309e15f359SSam Clegg 10316c899ba6SSam Clegg if (DataSegments.size()) { 103263ebb813SSam Clegg startSection(SubSection, wasm::WASM_SEGMENT_INFO); 1033f17b149dSPeter Collingbourne encodeULEB128(DataSegments.size(), W.OS); 10346c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 1035d95ed959SSam Clegg writeString(Segment.Name); 1036f17b149dSPeter Collingbourne encodeULEB128(Segment.Alignment, W.OS); 10372e150409SThomas Lively encodeULEB128(Segment.LinkerFlags, W.OS); 103863ebb813SSam Clegg } 1039d95ed959SSam Clegg endSection(SubSection); 1040d95ed959SSam Clegg } 1041d95ed959SSam Clegg 1042bafe6902SSam Clegg if (!InitFuncs.empty()) { 1043bafe6902SSam Clegg startSection(SubSection, wasm::WASM_INIT_FUNCS); 1044f17b149dSPeter Collingbourne encodeULEB128(InitFuncs.size(), W.OS); 1045bafe6902SSam Clegg for (auto &StartFunc : InitFuncs) { 1046f17b149dSPeter Collingbourne encodeULEB128(StartFunc.first, W.OS); // priority 1047f17b149dSPeter Collingbourne encodeULEB128(StartFunc.second, W.OS); // function index 1048bafe6902SSam Clegg } 1049bafe6902SSam Clegg endSection(SubSection); 1050bafe6902SSam Clegg } 1051bafe6902SSam Clegg 1052ea7caceeSSam Clegg if (Comdats.size()) { 1053ea7caceeSSam Clegg startSection(SubSection, wasm::WASM_COMDAT_INFO); 1054f17b149dSPeter Collingbourne encodeULEB128(Comdats.size(), W.OS); 1055ea7caceeSSam Clegg for (const auto &C : Comdats) { 1056ea7caceeSSam Clegg writeString(C.first); 1057f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // flags for future use 1058f17b149dSPeter Collingbourne encodeULEB128(C.second.size(), W.OS); 1059ea7caceeSSam Clegg for (const WasmComdatEntry &Entry : C.second) { 1060f17b149dSPeter Collingbourne encodeULEB128(Entry.Kind, W.OS); 1061f17b149dSPeter Collingbourne encodeULEB128(Entry.Index, W.OS); 1062ea7caceeSSam Clegg } 1063ea7caceeSSam Clegg } 1064ea7caceeSSam Clegg endSection(SubSection); 1065ea7caceeSSam Clegg } 1066ea7caceeSSam Clegg 10679e15f359SSam Clegg endSection(Section); 10689e15f359SSam Clegg } 10699e15f359SSam Clegg 1070cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection, 1071cbda16ebSThomas Lively const MCAssembler &Asm, 10726a31a0d6SSam Clegg const MCAsmLayout &Layout) { 1073cfd44a2eSSam Clegg SectionBookkeeping Section; 10746a31a0d6SSam Clegg auto *Sec = CustomSection.Section; 10752322a937SSam Clegg startCustomSection(Section, CustomSection.Name); 10766a31a0d6SSam Clegg 1077f17b149dSPeter Collingbourne Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset); 1078f17b149dSPeter Collingbourne Asm.writeSectionData(W.OS, Sec, Layout); 10796a31a0d6SSam Clegg 10806a31a0d6SSam Clegg CustomSection.OutputContentsOffset = Section.ContentsOffset; 10816a31a0d6SSam Clegg CustomSection.OutputIndex = Section.Index; 10826a31a0d6SSam Clegg 1083cfd44a2eSSam Clegg endSection(Section); 10846a31a0d6SSam Clegg 10856a31a0d6SSam Clegg // Apply fixups. 10864d57fbd0SSam Clegg auto &Relocations = CustomSectionsRelocations[CustomSection.Section]; 10874d57fbd0SSam Clegg applyRelocations(Relocations, CustomSection.OutputContentsOffset); 10886a31a0d6SSam Clegg } 10896a31a0d6SSam Clegg 10905e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) { 10915e3d33a7SSam Clegg assert(Symbol.isFunction()); 10925e3d33a7SSam Clegg assert(TypeIndices.count(&Symbol)); 10935e3d33a7SSam Clegg return TypeIndices[&Symbol]; 10945e3d33a7SSam Clegg } 10955e3d33a7SSam Clegg 1096da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) { 1097da419bdbSHeejin Ahn assert(Symbol.isEvent()); 1098da419bdbSHeejin Ahn assert(TypeIndices.count(&Symbol)); 1099da419bdbSHeejin Ahn return TypeIndices[&Symbol]; 1100da419bdbSHeejin Ahn } 1101da419bdbSHeejin Ahn 110238b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) { 11035e3d33a7SSam Clegg assert(Symbol.isFunction()); 11045e3d33a7SSam Clegg 1105da419bdbSHeejin Ahn WasmSignature S; 110618c56a07SHeejin Ahn const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol); 110777a7a380SDerek Schuff if (auto *Sig = ResolvedSym->getSignature()) { 1108da419bdbSHeejin Ahn S.Returns = Sig->Returns; 1109da419bdbSHeejin Ahn S.Params = Sig->Params; 111077a7a380SDerek Schuff } 11115e3d33a7SSam Clegg 1112da419bdbSHeejin Ahn auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 11135e3d33a7SSam Clegg if (Pair.second) 1114da419bdbSHeejin Ahn Signatures.push_back(S); 11155e3d33a7SSam Clegg TypeIndices[&Symbol] = Pair.first->second; 11165e3d33a7SSam Clegg 1117d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol 1118d34e60caSNicola Zaghen << " new:" << Pair.second << "\n"); 1119d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 11205e3d33a7SSam Clegg } 11215e3d33a7SSam Clegg 112238b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) { 1123da419bdbSHeejin Ahn assert(Symbol.isEvent()); 1124da419bdbSHeejin Ahn 1125da419bdbSHeejin Ahn // TODO Currently we don't generate imported exceptions, but if we do, we 1126da419bdbSHeejin Ahn // should have a way of infering types of imported exceptions. 1127da419bdbSHeejin Ahn WasmSignature S; 1128da419bdbSHeejin Ahn if (auto *Sig = Symbol.getSignature()) { 1129da419bdbSHeejin Ahn S.Returns = Sig->Returns; 1130da419bdbSHeejin Ahn S.Params = Sig->Params; 1131da419bdbSHeejin Ahn } 1132da419bdbSHeejin Ahn 1133da419bdbSHeejin Ahn auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 1134da419bdbSHeejin Ahn if (Pair.second) 1135da419bdbSHeejin Ahn Signatures.push_back(S); 1136da419bdbSHeejin Ahn TypeIndices[&Symbol] = Pair.first->second; 1137da419bdbSHeejin Ahn 1138da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second 1139da419bdbSHeejin Ahn << "\n"); 1140da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 1141da419bdbSHeejin Ahn } 1142da419bdbSHeejin Ahn 11434d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) { 11443ea1c62cSSam Clegg if (Sym.isUsedInReloc() || Sym.isUsedInInitArray()) 11454d57fbd0SSam Clegg return true; 11464d57fbd0SSam Clegg 11474d57fbd0SSam Clegg if (Sym.isComdat() && !Sym.isDefined()) 11484d57fbd0SSam Clegg return false; 11494d57fbd0SSam Clegg 11503ea1c62cSSam Clegg if (Sym.isTemporary()) 11514d57fbd0SSam Clegg return false; 11524d57fbd0SSam Clegg 11534d57fbd0SSam Clegg if (Sym.isSection()) 11544d57fbd0SSam Clegg return false; 11554d57fbd0SSam Clegg 11564d57fbd0SSam Clegg return true; 11574d57fbd0SSam Clegg } 11584d57fbd0SSam Clegg 1159438390faSPeter Collingbourne uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm, 116018eafb6cSDan Gohman const MCAsmLayout &Layout) { 1161438390faSPeter Collingbourne uint64_t StartOffset = W.OS.tell(); 1162438390faSPeter Collingbourne 1163d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 1164d934cb88SDan Gohman 1165d934cb88SDan Gohman // Collect information from the available symbols. 1166d934cb88SDan Gohman SmallVector<WasmFunction, 4> Functions; 1167d934cb88SDan Gohman SmallVector<uint32_t, 4> TableElems; 11688defa952SSam Clegg SmallVector<wasm::WasmImport, 4> Imports; 11698defa952SSam Clegg SmallVector<wasm::WasmExport, 4> Exports; 1170da419bdbSHeejin Ahn SmallVector<wasm::WasmEventType, 1> Events; 11710a6c4d8dSSam Clegg SmallVector<wasm::WasmGlobal, 1> Globals; 11726c899ba6SSam Clegg SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos; 1173bafe6902SSam Clegg SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 1174ea7caceeSSam Clegg std::map<StringRef, std::vector<WasmComdatEntry>> Comdats; 11757c395943SSam Clegg uint32_t DataSize = 0; 1176d934cb88SDan Gohman 1177f950b24aSSam Clegg // For now, always emit the memory import, since loads and stores are not 1178f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1179f950b24aSSam Clegg // it if there are no loads or stores. 11808defa952SSam Clegg wasm::WasmImport MemImport; 11811ed3a046SSam Clegg MemImport.Module = "env"; 11821ed3a046SSam Clegg MemImport.Field = "__linear_memory"; 1183f950b24aSSam Clegg MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1184f950b24aSSam Clegg Imports.push_back(MemImport); 1185f950b24aSSam Clegg 1186f950b24aSSam Clegg // For now, always emit the table section, since indirect calls are not 1187f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1188f950b24aSSam Clegg // it if there are no indirect calls. 11898defa952SSam Clegg wasm::WasmImport TableImport; 11901ed3a046SSam Clegg TableImport.Module = "env"; 11911ed3a046SSam Clegg TableImport.Field = "__indirect_function_table"; 1192f950b24aSSam Clegg TableImport.Kind = wasm::WASM_EXTERNAL_TABLE; 11936a87ddacSThomas Lively TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF; 1194f950b24aSSam Clegg Imports.push_back(TableImport); 1195f950b24aSSam Clegg 1196da419bdbSHeejin Ahn // Populate SignatureIndices, and Imports and WasmIndices for undefined 1197586320c0SNicholas Wilson // symbols. This must be done before populating WasmIndices for defined 1198586320c0SNicholas Wilson // symbols. 119932ce5ca0SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 120032ce5ca0SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 120132ce5ca0SDan Gohman 120232ce5ca0SDan Gohman // Register types for all functions, including those with private linkage 12039f3fe42eSSam Clegg // (because wasm always needs a type signature). 120432ce5ca0SDan Gohman if (WS.isFunction()) 120532ce5ca0SDan Gohman registerFunctionType(WS); 120632ce5ca0SDan Gohman 1207da419bdbSHeejin Ahn if (WS.isEvent()) 1208da419bdbSHeejin Ahn registerEventType(WS); 1209da419bdbSHeejin Ahn 121032ce5ca0SDan Gohman if (WS.isTemporary()) 121132ce5ca0SDan Gohman continue; 121232ce5ca0SDan Gohman 121332ce5ca0SDan Gohman // If the symbol is not defined in this translation unit, import it. 12146c899ba6SSam Clegg if (!WS.isDefined() && !WS.isComdat()) { 12156c899ba6SSam Clegg if (WS.isFunction()) { 12168defa952SSam Clegg wasm::WasmImport Import; 1217f726e445SDan Gohman Import.Module = WS.getImportModule(); 1218f726e445SDan Gohman Import.Field = WS.getImportName(); 121932ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 12208defa952SSam Clegg Import.SigIndex = getFunctionType(WS); 12216c899ba6SSam Clegg Imports.push_back(Import); 1222492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 12236c899ba6SSam Clegg WasmIndices[&WS] = NumFunctionImports++; 12246c899ba6SSam Clegg } else if (WS.isGlobal()) { 122515f349f7SNicholas Wilson if (WS.isWeak()) 122615f349f7SNicholas Wilson report_fatal_error("undefined global symbol cannot be weak"); 122715f349f7SNicholas Wilson 12286c899ba6SSam Clegg wasm::WasmImport Import; 1229f726e445SDan Gohman Import.Field = WS.getImportName(); 123032ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1231492f7529SSam Clegg Import.Module = WS.getImportModule(); 12326c899ba6SSam Clegg Import.Global = WS.getGlobalType(); 12336c899ba6SSam Clegg Imports.push_back(Import); 1234492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 12356c899ba6SSam Clegg WasmIndices[&WS] = NumGlobalImports++; 1236da419bdbSHeejin Ahn } else if (WS.isEvent()) { 1237da419bdbSHeejin Ahn if (WS.isWeak()) 1238da419bdbSHeejin Ahn report_fatal_error("undefined event symbol cannot be weak"); 1239da419bdbSHeejin Ahn 1240da419bdbSHeejin Ahn wasm::WasmImport Import; 1241f726e445SDan Gohman Import.Module = WS.getImportModule(); 1242f726e445SDan Gohman Import.Field = WS.getImportName(); 1243da419bdbSHeejin Ahn Import.Kind = wasm::WASM_EXTERNAL_EVENT; 1244da419bdbSHeejin Ahn Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION; 1245da419bdbSHeejin Ahn Import.Event.SigIndex = getEventType(WS); 1246da419bdbSHeejin Ahn Imports.push_back(Import); 1247492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 1248da419bdbSHeejin Ahn WasmIndices[&WS] = NumEventImports++; 124932ce5ca0SDan Gohman } 125032ce5ca0SDan Gohman } 125132ce5ca0SDan Gohman } 125232ce5ca0SDan Gohman 1253492f7529SSam Clegg // Add imports for GOT globals 1254492f7529SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1255492f7529SSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 1256492f7529SSam Clegg if (WS.isUsedInGOT()) { 1257492f7529SSam Clegg wasm::WasmImport Import; 1258492f7529SSam Clegg if (WS.isFunction()) 1259492f7529SSam Clegg Import.Module = "GOT.func"; 1260492f7529SSam Clegg else 1261492f7529SSam Clegg Import.Module = "GOT.mem"; 1262492f7529SSam Clegg Import.Field = WS.getName(); 1263492f7529SSam Clegg Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1264492f7529SSam Clegg Import.Global = {wasm::WASM_TYPE_I32, true}; 1265492f7529SSam Clegg Imports.push_back(Import); 1266492f7529SSam Clegg assert(GOTIndices.count(&WS) == 0); 1267492f7529SSam Clegg GOTIndices[&WS] = NumGlobalImports++; 1268492f7529SSam Clegg } 1269492f7529SSam Clegg } 1270492f7529SSam Clegg 12714d57fbd0SSam Clegg // Populate DataSegments and CustomSections, which must be done before 12724d57fbd0SSam Clegg // populating DataLocations. 1273759631c7SSam Clegg for (MCSection &Sec : Asm) { 1274759631c7SSam Clegg auto &Section = static_cast<MCSectionWasm &>(Sec); 12757d1ff446SFangrui Song StringRef SectionName = Section.getName(); 1276759631c7SSam Clegg 1277bafe6902SSam Clegg // .init_array sections are handled specially elsewhere. 12784d57fbd0SSam Clegg if (SectionName.startswith(".init_array")) 1279bafe6902SSam Clegg continue; 1280bafe6902SSam Clegg 12814d57fbd0SSam Clegg // Code is handled separately 12824d57fbd0SSam Clegg if (Section.getKind().isText()) 12834d57fbd0SSam Clegg continue; 12844d57fbd0SSam Clegg 12854d57fbd0SSam Clegg if (Section.isWasmData()) { 1286329e76d5SSam Clegg uint32_t SegmentIndex = DataSegments.size(); 1287759631c7SSam Clegg DataSize = alignTo(DataSize, Section.getAlignment()); 1288759631c7SSam Clegg DataSegments.emplace_back(); 1289759631c7SSam Clegg WasmDataSegment &Segment = DataSegments.back(); 12904d57fbd0SSam Clegg Segment.Name = SectionName; 12919b49f36aSSimon Pilgrim Segment.InitFlags = 12929b49f36aSSimon Pilgrim Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0; 1293759631c7SSam Clegg Segment.Offset = DataSize; 1294759631c7SSam Clegg Segment.Section = &Section; 129563ebb813SSam Clegg addData(Segment.Data, Section); 129656c587adSSam Clegg Segment.Alignment = Log2_32(Section.getAlignment()); 12972e150409SThomas Lively Segment.LinkerFlags = 0; 1298759631c7SSam Clegg DataSize += Segment.Data.size(); 12996c899ba6SSam Clegg Section.setSegmentIndex(SegmentIndex); 1300ea7caceeSSam Clegg 1301ea7caceeSSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 1302ea7caceeSSam Clegg Comdats[C->getName()].emplace_back( 1303329e76d5SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex}); 1304ea7caceeSSam Clegg } 13054d57fbd0SSam Clegg } else { 13064d57fbd0SSam Clegg // Create custom sections 13074d57fbd0SSam Clegg assert(Sec.getKind().isMetadata()); 13084d57fbd0SSam Clegg 13094d57fbd0SSam Clegg StringRef Name = SectionName; 13104d57fbd0SSam Clegg 13114d57fbd0SSam Clegg // For user-defined custom sections, strip the prefix 13124d57fbd0SSam Clegg if (Name.startswith(".custom_section.")) 13134d57fbd0SSam Clegg Name = Name.substr(strlen(".custom_section.")); 13144d57fbd0SSam Clegg 13154d57fbd0SSam Clegg MCSymbol *Begin = Sec.getBeginSymbol(); 1316fb807d4dSSam Clegg if (Begin) { 13174d57fbd0SSam Clegg WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size(); 1318b210c64bSSam Clegg if (SectionName != Begin->getName()) 1319fb807d4dSSam Clegg report_fatal_error("section name and begin symbol should match: " + 1320b210c64bSSam Clegg Twine(SectionName)); 1321fb807d4dSSam Clegg } 1322cbda16ebSThomas Lively 1323f6f4f843SThomas Lively // Separate out the producers and target features sections 1324cbda16ebSThomas Lively if (Name == "producers") { 13250eaee545SJonas Devlieghere ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section); 1326cbda16ebSThomas Lively continue; 1327cbda16ebSThomas Lively } 1328f6f4f843SThomas Lively if (Name == "target_features") { 1329f6f4f843SThomas Lively TargetFeaturesSection = 13300eaee545SJonas Devlieghere std::make_unique<WasmCustomSection>(Name, &Section); 1331f6f4f843SThomas Lively continue; 1332f6f4f843SThomas Lively } 1333cbda16ebSThomas Lively 13344d57fbd0SSam Clegg CustomSections.emplace_back(Name, &Section); 1335759631c7SSam Clegg } 13366a31a0d6SSam Clegg } 13376a31a0d6SSam Clegg 1338586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for defined symbols. 1339d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1340d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1341d934cb88SDan Gohman // or used in relocations. 1342d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 1343d934cb88SDan Gohman continue; 1344b7787fd0SSam Clegg 1345d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 1346d34e60caSNicola Zaghen LLVM_DEBUG( 1347d34e60caSNicola Zaghen dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'" 1348d34e60caSNicola Zaghen << " isDefined=" << S.isDefined() << " isExternal=" 1349d34e60caSNicola Zaghen << S.isExternal() << " isTemporary=" << S.isTemporary() 1350d34e60caSNicola Zaghen << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden() 1351b7787fd0SSam Clegg << " isVariable=" << WS.isVariable() << "\n"); 1352b7787fd0SSam Clegg 13535e3d33a7SSam Clegg if (WS.isVariable()) 13545e3d33a7SSam Clegg continue; 13556c899ba6SSam Clegg if (WS.isComdat() && !WS.isDefined()) 13566c899ba6SSam Clegg continue; 1357b7787fd0SSam Clegg 1358d934cb88SDan Gohman if (WS.isFunction()) { 13596c899ba6SSam Clegg unsigned Index; 1360cd65f698SSam Clegg if (WS.isDefined()) { 1361b7787fd0SSam Clegg if (WS.getOffset() != 0) 1362b7787fd0SSam Clegg report_fatal_error( 1363b7787fd0SSam Clegg "function sections must contain one function each"); 1364b7787fd0SSam Clegg 136518c56a07SHeejin Ahn if (WS.getSize() == nullptr) 1366b7787fd0SSam Clegg report_fatal_error( 1367b7787fd0SSam Clegg "function symbols must have a size set with .size"); 1368b7787fd0SSam Clegg 13696c899ba6SSam Clegg // A definition. Write out the function body. 13709f3fe42eSSam Clegg Index = NumFunctionImports + Functions.size(); 1371d934cb88SDan Gohman WasmFunction Func; 1372da419bdbSHeejin Ahn Func.SigIndex = getFunctionType(WS); 1373d934cb88SDan Gohman Func.Sym = &WS; 13746c899ba6SSam Clegg WasmIndices[&WS] = Index; 1375d934cb88SDan Gohman Functions.push_back(Func); 13766c899ba6SSam Clegg 13776c899ba6SSam Clegg auto &Section = static_cast<MCSectionWasm &>(WS.getSection()); 13786c899ba6SSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 13796c899ba6SSam Clegg Comdats[C->getName()].emplace_back( 13806c899ba6SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index}); 13816c899ba6SSam Clegg } 1382881d8778SSam Clegg 1383881d8778SSam Clegg if (WS.hasExportName()) { 1384881d8778SSam Clegg wasm::WasmExport Export; 1385881d8778SSam Clegg Export.Name = WS.getExportName(); 1386881d8778SSam Clegg Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1387881d8778SSam Clegg Export.Index = Index; 1388881d8778SSam Clegg Exports.push_back(Export); 1389881d8778SSam Clegg } 1390d934cb88SDan Gohman } else { 1391d934cb88SDan Gohman // An import; the index was assigned above. 13926c899ba6SSam Clegg Index = WasmIndices.find(&WS)->second; 1393d934cb88SDan Gohman } 1394d934cb88SDan Gohman 1395d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n"); 1396da419bdbSHeejin Ahn 13976c899ba6SSam Clegg } else if (WS.isData()) { 1398f3feb6adSWouter van Oortmerssen if (!isInSymtab(WS)) 1399c38e947eSSam Clegg continue; 1400c38e947eSSam Clegg 14016c899ba6SSam Clegg if (!WS.isDefined()) { 1402d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> segment index: -1" 1403d34e60caSNicola Zaghen << "\n"); 1404fe6414b0SSam Clegg continue; 14056c899ba6SSam Clegg } 1406fe6414b0SSam Clegg 1407d934cb88SDan Gohman if (!WS.getSize()) 1408c38e947eSSam Clegg report_fatal_error("data symbols must have a size set with .size: " + 1409c38e947eSSam Clegg WS.getName()); 1410d934cb88SDan Gohman 1411d934cb88SDan Gohman int64_t Size = 0; 1412d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1413d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 1414d934cb88SDan Gohman 1415759631c7SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1416079cba04SSam Clegg if (!DataSection.isWasmData()) 1417079cba04SSam Clegg report_fatal_error("data symbols must live in a data section: " + 1418079cba04SSam Clegg WS.getName()); 14197c395943SSam Clegg 14206c899ba6SSam Clegg // For each data symbol, export it in the symtab as a reference to the 14216c899ba6SSam Clegg // corresponding Wasm data segment. 14226c899ba6SSam Clegg wasm::WasmDataReference Ref = wasm::WasmDataReference{ 14236c899ba6SSam Clegg DataSection.getSegmentIndex(), 14246c899ba6SSam Clegg static_cast<uint32_t>(Layout.getSymbolOffset(WS)), 14256c899ba6SSam Clegg static_cast<uint32_t>(Size)}; 14266c899ba6SSam Clegg DataLocations[&WS] = Ref; 1427d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n"); 1428da419bdbSHeejin Ahn 1429a165f2d6SSam Clegg } else if (WS.isGlobal()) { 14306c899ba6SSam Clegg // A "true" Wasm global (currently just __stack_pointer) 14310a6c4d8dSSam Clegg if (WS.isDefined()) { 14320a6c4d8dSSam Clegg assert(WasmIndices.count(&WS) == 0); 14330a6c4d8dSSam Clegg wasm::WasmGlobal Global; 14340a6c4d8dSSam Clegg Global.Type = WS.getGlobalType(); 14350a6c4d8dSSam Clegg Global.Index = NumGlobalImports + Globals.size(); 14360a6c4d8dSSam Clegg switch (Global.Type.Type) { 14370a6c4d8dSSam Clegg case wasm::WASM_TYPE_I32: 14380a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST; 14390a6c4d8dSSam Clegg break; 14400a6c4d8dSSam Clegg case wasm::WASM_TYPE_I64: 14410a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST; 14420a6c4d8dSSam Clegg break; 14430a6c4d8dSSam Clegg case wasm::WASM_TYPE_F32: 14440a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST; 14450a6c4d8dSSam Clegg break; 14460a6c4d8dSSam Clegg case wasm::WASM_TYPE_F64: 14470a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST; 14480a6c4d8dSSam Clegg break; 14490a6c4d8dSSam Clegg default: 14500a6c4d8dSSam Clegg llvm_unreachable("unexpected type"); 14510a6c4d8dSSam Clegg } 14520a6c4d8dSSam Clegg WasmIndices[&WS] = Global.Index; 14530a6c4d8dSSam Clegg Globals.push_back(Global); 14540a6c4d8dSSam Clegg } else { 1455545932beSEric Christopher // An import; the index was assigned above 1456d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> global index: " 1457d34e60caSNicola Zaghen << WasmIndices.find(&WS)->second << "\n"); 14580a6c4d8dSSam Clegg } 1459da419bdbSHeejin Ahn } else if (WS.isEvent()) { 1460da419bdbSHeejin Ahn // C++ exception symbol (__cpp_exception) 1461da419bdbSHeejin Ahn unsigned Index; 1462da419bdbSHeejin Ahn if (WS.isDefined()) { 14630a6c4d8dSSam Clegg assert(WasmIndices.count(&WS) == 0); 1464da419bdbSHeejin Ahn Index = NumEventImports + Events.size(); 1465da419bdbSHeejin Ahn wasm::WasmEventType Event; 1466da419bdbSHeejin Ahn Event.SigIndex = getEventType(WS); 1467da419bdbSHeejin Ahn Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION; 1468da419bdbSHeejin Ahn WasmIndices[&WS] = Index; 1469da419bdbSHeejin Ahn Events.push_back(Event); 1470da419bdbSHeejin Ahn } else { 1471da419bdbSHeejin Ahn // An import; the index was assigned above. 1472492f7529SSam Clegg assert(WasmIndices.count(&WS) > 0); 1473da419bdbSHeejin Ahn } 1474da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second 1475da419bdbSHeejin Ahn << "\n"); 1476da419bdbSHeejin Ahn 1477a165f2d6SSam Clegg } else { 1478a165f2d6SSam Clegg assert(WS.isSection()); 1479d934cb88SDan Gohman } 1480d934cb88SDan Gohman } 1481d934cb88SDan Gohman 1482586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for aliased symbols. We need to 1483586320c0SNicholas Wilson // process these in a separate pass because we need to have processed the 1484586320c0SNicholas Wilson // target of the alias before the alias itself and the symbols are not 1485586320c0SNicholas Wilson // necessarily ordered in this way. 1486b7787fd0SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1487b7787fd0SSam Clegg if (!S.isVariable()) 1488b7787fd0SSam Clegg continue; 148931a2c809SSam Clegg 1490cd65f698SSam Clegg assert(S.isDefined()); 1491b7787fd0SSam Clegg 14925e3d33a7SSam Clegg // Find the target symbol of this weak alias and export that index 1493aff1c4dfSSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 149418c56a07SHeejin Ahn const MCSymbolWasm *ResolvedSym = resolveSymbol(WS); 1495d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym 1496d34e60caSNicola Zaghen << "'\n"); 1497b7787fd0SSam Clegg 1498ffba00bdSSam Clegg if (ResolvedSym->isFunction()) { 14996c899ba6SSam Clegg assert(WasmIndices.count(ResolvedSym) > 0); 15006c899ba6SSam Clegg uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second; 1501492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 15026c899ba6SSam Clegg WasmIndices[&WS] = WasmIndex; 1503d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n"); 1504ffba00bdSSam Clegg } else if (ResolvedSym->isData()) { 15056c899ba6SSam Clegg assert(DataLocations.count(ResolvedSym) > 0); 15066c899ba6SSam Clegg const wasm::WasmDataReference &Ref = 15076c899ba6SSam Clegg DataLocations.find(ResolvedSym)->second; 15086c899ba6SSam Clegg DataLocations[&WS] = Ref; 1509d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n"); 15106c899ba6SSam Clegg } else { 1511da419bdbSHeejin Ahn report_fatal_error("don't yet support global/event aliases"); 15126c899ba6SSam Clegg } 1513586320c0SNicholas Wilson } 151431a2c809SSam Clegg 1515586320c0SNicholas Wilson // Finally, populate the symbol table itself, in its "natural" order. 1516586320c0SNicholas Wilson for (const MCSymbol &S : Asm.symbols()) { 1517586320c0SNicholas Wilson const auto &WS = static_cast<const MCSymbolWasm &>(S); 151825d8e68bSSam Clegg if (!isInSymtab(WS)) { 151918c56a07SHeejin Ahn WS.setIndex(InvalidIndex); 1520586320c0SNicholas Wilson continue; 152125d8e68bSSam Clegg } 1522d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n"); 1523586320c0SNicholas Wilson 1524586320c0SNicholas Wilson uint32_t Flags = 0; 1525586320c0SNicholas Wilson if (WS.isWeak()) 1526586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_WEAK; 1527586320c0SNicholas Wilson if (WS.isHidden()) 1528586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN; 1529586320c0SNicholas Wilson if (!WS.isExternal() && WS.isDefined()) 1530586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL; 1531586320c0SNicholas Wilson if (WS.isUndefined()) 1532586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_UNDEFINED; 1533da84b688SDan Gohman if (WS.isNoStrip()) { 1534da84b688SDan Gohman Flags |= wasm::WASM_SYMBOL_NO_STRIP; 1535da84b688SDan Gohman if (isEmscripten()) { 1536d6ef8da3SSam Clegg Flags |= wasm::WASM_SYMBOL_EXPORTED; 1537da84b688SDan Gohman } 1538da84b688SDan Gohman } 1539b4f4e370SSam Clegg if (WS.hasImportName()) 154029874ceaSDan Gohman Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME; 1541881d8778SSam Clegg if (WS.hasExportName()) 1542881d8778SSam Clegg Flags |= wasm::WASM_SYMBOL_EXPORTED; 1543586320c0SNicholas Wilson 1544586320c0SNicholas Wilson wasm::WasmSymbolInfo Info; 1545586320c0SNicholas Wilson Info.Name = WS.getName(); 1546586320c0SNicholas Wilson Info.Kind = WS.getType(); 1547586320c0SNicholas Wilson Info.Flags = Flags; 15484d57fbd0SSam Clegg if (!WS.isData()) { 15494d57fbd0SSam Clegg assert(WasmIndices.count(&WS) > 0); 1550586320c0SNicholas Wilson Info.ElementIndex = WasmIndices.find(&WS)->second; 15514d57fbd0SSam Clegg } else if (WS.isDefined()) { 15524d57fbd0SSam Clegg assert(DataLocations.count(&WS) > 0); 1553586320c0SNicholas Wilson Info.DataRef = DataLocations.find(&WS)->second; 15544d57fbd0SSam Clegg } 155525d8e68bSSam Clegg WS.setIndex(SymbolInfos.size()); 1556586320c0SNicholas Wilson SymbolInfos.emplace_back(Info); 1557b7787fd0SSam Clegg } 1558b7787fd0SSam Clegg 15596006e091SSam Clegg { 15606006e091SSam Clegg auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 1561f9edbe95SSam Clegg // Functions referenced by a relocation need to put in the table. This is 1562f9edbe95SSam Clegg // purely to make the object file's provisional values readable, and is 1563f9edbe95SSam Clegg // ignored by the linker, which re-calculates the relocations itself. 1564d1152a26SSam Clegg if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 && 1565*81443ac1SSam Clegg Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB && 1566*81443ac1SSam Clegg Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB) 1567f9edbe95SSam Clegg return; 1568f9edbe95SSam Clegg assert(Rel.Symbol->isFunction()); 156918c56a07SHeejin Ahn const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol); 15706c899ba6SSam Clegg uint32_t FunctionIndex = WasmIndices.find(&WS)->second; 157118c56a07SHeejin Ahn uint32_t TableIndex = TableElems.size() + InitialTableOffset; 1572f9edbe95SSam Clegg if (TableIndices.try_emplace(&WS, TableIndex).second) { 1573d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> adding " << WS.getName() 1574f9edbe95SSam Clegg << " to table: " << TableIndex << "\n"); 15756c899ba6SSam Clegg TableElems.push_back(FunctionIndex); 15766006e091SSam Clegg registerFunctionType(WS); 15776006e091SSam Clegg } 15786006e091SSam Clegg }; 1579970d02c4SDan Gohman 15806006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : CodeRelocations) 15816006e091SSam Clegg HandleReloc(RelEntry); 15826006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : DataRelocations) 15836006e091SSam Clegg HandleReloc(RelEntry); 1584d934cb88SDan Gohman } 1585d934cb88SDan Gohman 1586bafe6902SSam Clegg // Translate .init_array section contents into start functions. 1587bafe6902SSam Clegg for (const MCSection &S : Asm) { 1588bafe6902SSam Clegg const auto &WS = static_cast<const MCSectionWasm &>(S); 15897d1ff446SFangrui Song if (WS.getName().startswith(".fini_array")) 1590bafe6902SSam Clegg report_fatal_error(".fini_array sections are unsupported"); 15917d1ff446SFangrui Song if (!WS.getName().startswith(".init_array")) 1592bafe6902SSam Clegg continue; 1593bafe6902SSam Clegg if (WS.getFragmentList().empty()) 1594bafe6902SSam Clegg continue; 1595b210c64bSSam Clegg 1596b210c64bSSam Clegg // init_array is expected to contain a single non-empty data fragment 1597b210c64bSSam Clegg if (WS.getFragmentList().size() != 3) 1598bafe6902SSam Clegg report_fatal_error("only one .init_array section fragment supported"); 1599b210c64bSSam Clegg 1600b210c64bSSam Clegg auto IT = WS.begin(); 1601b210c64bSSam Clegg const MCFragment &EmptyFrag = *IT; 1602b210c64bSSam Clegg if (EmptyFrag.getKind() != MCFragment::FT_Data) 1603b210c64bSSam Clegg report_fatal_error(".init_array section should be aligned"); 1604b210c64bSSam Clegg 1605b210c64bSSam Clegg IT = std::next(IT); 1606b210c64bSSam Clegg const MCFragment &AlignFrag = *IT; 1607bafe6902SSam Clegg if (AlignFrag.getKind() != MCFragment::FT_Align) 1608bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned"); 1609bafe6902SSam Clegg if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1610bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned for pointers"); 1611b210c64bSSam Clegg 1612b210c64bSSam Clegg const MCFragment &Frag = *std::next(IT); 1613bafe6902SSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1614bafe6902SSam Clegg report_fatal_error("only data supported in .init_array section"); 1615b210c64bSSam Clegg 1616bafe6902SSam Clegg uint16_t Priority = UINT16_MAX; 16174d57fbd0SSam Clegg unsigned PrefixLength = strlen(".init_array"); 16187d1ff446SFangrui Song if (WS.getName().size() > PrefixLength) { 16197d1ff446SFangrui Song if (WS.getName()[PrefixLength] != '.') 1620f208f631SHeejin Ahn report_fatal_error( 1621f208f631SHeejin Ahn ".init_array section priority should start with '.'"); 16227d1ff446SFangrui Song if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority)) 1623bafe6902SSam Clegg report_fatal_error("invalid .init_array section priority"); 1624bafe6902SSam Clegg } 1625bafe6902SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1626bafe6902SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1627f208f631SHeejin Ahn for (const uint8_t * 162818c56a07SHeejin Ahn P = (const uint8_t *)Contents.data(), 162918c56a07SHeejin Ahn *End = (const uint8_t *)Contents.data() + Contents.size(); 163018c56a07SHeejin Ahn P != End; ++P) { 163118c56a07SHeejin Ahn if (*P != 0) 1632bafe6902SSam Clegg report_fatal_error("non-symbolic data in .init_array section"); 1633bafe6902SSam Clegg } 1634bafe6902SSam Clegg for (const MCFixup &Fixup : DataFrag.getFixups()) { 1635f208f631SHeejin Ahn assert(Fixup.getKind() == 1636f208f631SHeejin Ahn MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1637bafe6902SSam Clegg const MCExpr *Expr = Fixup.getValue(); 16388fffa1dfSSam Clegg auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr); 16398fffa1dfSSam Clegg if (!SymRef) 1640bafe6902SSam Clegg report_fatal_error("fixups in .init_array should be symbol references"); 16418fffa1dfSSam Clegg const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol()); 16428fffa1dfSSam Clegg if (TargetSym.getIndex() == InvalidIndex) 16433ea1c62cSSam Clegg report_fatal_error("symbols in .init_array should exist in symtab"); 16448fffa1dfSSam Clegg if (!TargetSym.isFunction()) 16458fffa1dfSSam Clegg report_fatal_error("symbols in .init_array should be for functions"); 164625d8e68bSSam Clegg InitFuncs.push_back( 16478fffa1dfSSam Clegg std::make_pair(Priority, TargetSym.getIndex())); 1648bafe6902SSam Clegg } 1649bafe6902SSam Clegg } 1650bafe6902SSam Clegg 165118eafb6cSDan Gohman // Write out the Wasm header. 165218eafb6cSDan Gohman writeHeader(Asm); 165318eafb6cSDan Gohman 1654da419bdbSHeejin Ahn writeTypeSection(Signatures); 1655f950b24aSSam Clegg writeImportSection(Imports, DataSize, TableElems.size()); 16569e15f359SSam Clegg writeFunctionSection(Functions); 1657f950b24aSSam Clegg // Skip the "table" section; we import the table instead. 1658f950b24aSSam Clegg // Skip the "memory" section; we import the memory instead. 1659da419bdbSHeejin Ahn writeEventSection(Events); 16600a6c4d8dSSam Clegg writeGlobalSection(Globals); 16619e15f359SSam Clegg writeExportSection(Exports); 16629e15f359SSam Clegg writeElemSection(TableElems); 1663fef8de66SThomas Lively writeDataCountSection(); 1664acd7d2b0SSam Clegg writeCodeSection(Asm, Layout, Functions); 16656c899ba6SSam Clegg writeDataSection(); 1666cbda16ebSThomas Lively for (auto &CustomSection : CustomSections) 1667cbda16ebSThomas Lively writeCustomSection(CustomSection, Asm, Layout); 1668c22bfb6bSNicholas Wilson writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats); 16696f08c84aSSam Clegg writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations); 16706f08c84aSSam Clegg writeRelocSection(DataSectionIndex, "DATA", DataRelocations); 16716a31a0d6SSam Clegg writeCustomRelocSections(); 1672cbda16ebSThomas Lively if (ProducersSection) 1673cbda16ebSThomas Lively writeCustomSection(*ProducersSection, Asm, Layout); 1674f6f4f843SThomas Lively if (TargetFeaturesSection) 1675f6f4f843SThomas Lively writeCustomSection(*TargetFeaturesSection, Asm, Layout); 1676970d02c4SDan Gohman 1677d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 1678438390faSPeter Collingbourne return W.OS.tell() - StartOffset; 167918eafb6cSDan Gohman } 168018eafb6cSDan Gohman 168160fbc7ccSLang Hames std::unique_ptr<MCObjectWriter> 16821301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 168318eafb6cSDan Gohman raw_pwrite_stream &OS) { 16840eaee545SJonas Devlieghere return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS); 168518eafb6cSDan Gohman } 1686