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. 207*0a6c4d8dSSam 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 311*0a6c4d8dSSam Clegg void writeI32(int32_t val) { 312*0a6c4d8dSSam Clegg char Buffer[4]; 313*0a6c4d8dSSam Clegg support::endian::write32le(Buffer, val); 314*0a6c4d8dSSam Clegg W.OS.write(Buffer, sizeof(Buffer)); 315*0a6c4d8dSSam Clegg } 316*0a6c4d8dSSam Clegg 317*0a6c4d8dSSam Clegg void writeI64(int64_t val) { 318*0a6c4d8dSSam Clegg char Buffer[8]; 319*0a6c4d8dSSam Clegg support::endian::write64le(Buffer, val); 320*0a6c4d8dSSam Clegg W.OS.write(Buffer, sizeof(Buffer)); 321*0a6c4d8dSSam Clegg } 322*0a6c4d8dSSam 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); 336*0a6c4d8dSSam 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()); 568f9edbe95SSam Clegg return TableIndices[Sym]; 569f9edbe95SSam Clegg } 570d1152a26SSam Clegg case wasm::R_WASM_TYPE_INDEX_LEB: 5716c899ba6SSam Clegg // Provisional value is same as the index 57260ec3034SSam Clegg return getRelocationIndexValue(RelEntry); 573d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_INDEX_LEB: 574d1152a26SSam Clegg case wasm::R_WASM_GLOBAL_INDEX_LEB: 57548139ebcSWouter van Oortmerssen case wasm::R_WASM_GLOBAL_INDEX_I32: 576d1152a26SSam Clegg case wasm::R_WASM_EVENT_INDEX_LEB: 577da419bdbSHeejin Ahn // Provisional value is function/global/event Wasm index 578492f7529SSam Clegg assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space"); 5796c899ba6SSam Clegg return WasmIndices[RelEntry.Symbol]; 580d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_OFFSET_I32: 581d1152a26SSam Clegg case wasm::R_WASM_SECTION_OFFSET_I32: { 5826a31a0d6SSam Clegg const auto &Section = 5836a31a0d6SSam Clegg static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection()); 5846a31a0d6SSam Clegg return Section.getSectionOffset() + RelEntry.Addend; 5856a31a0d6SSam Clegg } 586d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_LEB: 587d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_I32: 5882a7cac93SSam Clegg case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 589d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_SLEB: { 590f9edbe95SSam Clegg // Provisional value is address of the global 59118c56a07SHeejin Ahn const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol); 592270ed1b3SSam Clegg // For undefined symbols, use zero 593cd65f698SSam Clegg if (!Sym->isDefined()) 594270ed1b3SSam Clegg return 0; 5956c899ba6SSam Clegg const wasm::WasmDataReference &Ref = DataLocations[Sym]; 5966c899ba6SSam Clegg const WasmDataSegment &Segment = DataSegments[Ref.Segment]; 597d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 5986c899ba6SSam Clegg return Segment.Offset + Ref.Offset + RelEntry.Addend; 59960ec3034SSam Clegg } 60060ec3034SSam Clegg default: 60160ec3034SSam Clegg llvm_unreachable("invalid relocation type"); 60260ec3034SSam Clegg } 603d934cb88SDan Gohman } 604d934cb88SDan Gohman 605759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes, 60663ebb813SSam Clegg MCSectionWasm &DataSection) { 6077d1ff446SFangrui Song LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n"); 608759631c7SSam Clegg 60963ebb813SSam Clegg DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 61063ebb813SSam Clegg 611759631c7SSam Clegg for (const MCFragment &Frag : DataSection) { 612759631c7SSam Clegg if (Frag.hasInstructions()) 613759631c7SSam Clegg report_fatal_error("only data supported in data sections"); 614759631c7SSam Clegg 615759631c7SSam Clegg if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 616759631c7SSam Clegg if (Align->getValueSize() != 1) 617759631c7SSam Clegg report_fatal_error("only byte values supported for alignment"); 618759631c7SSam Clegg // If nops are requested, use zeros, as this is the data section. 619759631c7SSam Clegg uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 620f208f631SHeejin Ahn uint64_t Size = 621f208f631SHeejin Ahn std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()), 622f208f631SHeejin Ahn DataBytes.size() + Align->getMaxBytesToEmit()); 623759631c7SSam Clegg DataBytes.resize(Size, Value); 624759631c7SSam Clegg } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 625588fad4dSNirav Dave int64_t NumValues; 626588fad4dSNirav Dave if (!Fill->getNumValues().evaluateAsAbsolute(NumValues)) 627d707c370SRafael Espindola llvm_unreachable("The fill should be an assembler constant"); 628588fad4dSNirav Dave DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues, 629588fad4dSNirav Dave Fill->getValue()); 63024faf859SHeejin Ahn } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) { 63124faf859SHeejin Ahn const SmallVectorImpl<char> &Contents = LEB->getContents(); 63224faf859SHeejin Ahn DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 633759631c7SSam Clegg } else { 634759631c7SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 635759631c7SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 636759631c7SSam Clegg DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 637759631c7SSam Clegg } 638759631c7SSam Clegg } 639759631c7SSam Clegg 640d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 641759631c7SSam Clegg } 642759631c7SSam Clegg 64360ec3034SSam Clegg uint32_t 64460ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) { 645d1152a26SSam Clegg if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) { 646b7787fd0SSam Clegg if (!TypeIndices.count(RelEntry.Symbol)) 647b7787fd0SSam Clegg report_fatal_error("symbol not found in type index space: " + 648b7787fd0SSam Clegg RelEntry.Symbol->getName()); 649acd7d2b0SSam Clegg return TypeIndices[RelEntry.Symbol]; 650acd7d2b0SSam Clegg } 65160ec3034SSam Clegg 65225d8e68bSSam Clegg return RelEntry.Symbol->getIndex(); 653acd7d2b0SSam Clegg } 654acd7d2b0SSam Clegg 655d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 656d934cb88SDan Gohman // directly. 657acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations( 658acd7d2b0SSam Clegg ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) { 659f17b149dSPeter Collingbourne auto &Stream = static_cast<raw_pwrite_stream &>(W.OS); 660d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 661d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 662d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 663d934cb88SDan Gohman RelEntry.Offset; 664d934cb88SDan Gohman 665d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 66660ec3034SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 66760ec3034SSam Clegg 668acd7d2b0SSam Clegg switch (RelEntry.Type) { 669d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_INDEX_LEB: 670d1152a26SSam Clegg case wasm::R_WASM_TYPE_INDEX_LEB: 671d1152a26SSam Clegg case wasm::R_WASM_GLOBAL_INDEX_LEB: 672d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_LEB: 673d1152a26SSam Clegg case wasm::R_WASM_EVENT_INDEX_LEB: 67418c56a07SHeejin Ahn writePatchableLEB(Stream, Value, Offset); 675d934cb88SDan Gohman break; 676d1152a26SSam Clegg case wasm::R_WASM_TABLE_INDEX_I32: 677d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_I32: 678d1152a26SSam Clegg case wasm::R_WASM_FUNCTION_OFFSET_I32: 679d1152a26SSam Clegg case wasm::R_WASM_SECTION_OFFSET_I32: 68048139ebcSWouter van Oortmerssen case wasm::R_WASM_GLOBAL_INDEX_I32: 681*0a6c4d8dSSam Clegg patchI32(Stream, Value, Offset); 682d934cb88SDan Gohman break; 683d1152a26SSam Clegg case wasm::R_WASM_TABLE_INDEX_SLEB: 6842a7cac93SSam Clegg case wasm::R_WASM_TABLE_INDEX_REL_SLEB: 685d1152a26SSam Clegg case wasm::R_WASM_MEMORY_ADDR_SLEB: 6862a7cac93SSam Clegg case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 68718c56a07SHeejin Ahn writePatchableSLEB(Stream, Value, Offset); 68860ec3034SSam Clegg break; 689d934cb88SDan Gohman default: 6909d24fb7fSSam Clegg llvm_unreachable("invalid relocation type"); 691d934cb88SDan Gohman } 692d934cb88SDan Gohman } 69318eafb6cSDan Gohman } 69418eafb6cSDan Gohman 695da419bdbSHeejin Ahn void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) { 696da419bdbSHeejin Ahn if (Signatures.empty()) 6979e15f359SSam Clegg return; 6989e15f359SSam Clegg 6999e15f359SSam Clegg SectionBookkeeping Section; 7009e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TYPE); 7019e15f359SSam Clegg 702da419bdbSHeejin Ahn encodeULEB128(Signatures.size(), W.OS); 7039e15f359SSam Clegg 704da419bdbSHeejin Ahn for (const WasmSignature &Sig : Signatures) { 705f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_TYPE_FUNC); 706da419bdbSHeejin Ahn encodeULEB128(Sig.Params.size(), W.OS); 707da419bdbSHeejin Ahn for (wasm::ValType Ty : Sig.Params) 7089e15f359SSam Clegg writeValueType(Ty); 709da419bdbSHeejin Ahn encodeULEB128(Sig.Returns.size(), W.OS); 710da419bdbSHeejin Ahn for (wasm::ValType Ty : Sig.Returns) 7119e15f359SSam Clegg writeValueType(Ty); 7129e15f359SSam Clegg } 7139e15f359SSam Clegg 7149e15f359SSam Clegg endSection(Section); 7159e15f359SSam Clegg } 7169e15f359SSam Clegg 7178defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports, 718f950b24aSSam Clegg uint32_t DataSize, 719f950b24aSSam Clegg uint32_t NumElements) { 7209e15f359SSam Clegg if (Imports.empty()) 7219e15f359SSam Clegg return; 7229e15f359SSam Clegg 723f950b24aSSam Clegg uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 724f950b24aSSam Clegg 7259e15f359SSam Clegg SectionBookkeeping Section; 7269e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_IMPORT); 7279e15f359SSam Clegg 728f17b149dSPeter Collingbourne encodeULEB128(Imports.size(), W.OS); 7298defa952SSam Clegg for (const wasm::WasmImport &Import : Imports) { 7308defa952SSam Clegg writeString(Import.Module); 7318defa952SSam Clegg writeString(Import.Field); 732f17b149dSPeter Collingbourne W.OS << char(Import.Kind); 7339e15f359SSam Clegg 7349e15f359SSam Clegg switch (Import.Kind) { 7359e15f359SSam Clegg case wasm::WASM_EXTERNAL_FUNCTION: 736f17b149dSPeter Collingbourne encodeULEB128(Import.SigIndex, W.OS); 7379e15f359SSam Clegg break; 7389e15f359SSam Clegg case wasm::WASM_EXTERNAL_GLOBAL: 739f17b149dSPeter Collingbourne W.OS << char(Import.Global.Type); 740f17b149dSPeter Collingbourne W.OS << char(Import.Global.Mutable ? 1 : 0); 7419e15f359SSam Clegg break; 742f950b24aSSam Clegg case wasm::WASM_EXTERNAL_MEMORY: 743f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // flags 744f17b149dSPeter Collingbourne encodeULEB128(NumPages, W.OS); // initial 745f950b24aSSam Clegg break; 746f950b24aSSam Clegg case wasm::WASM_EXTERNAL_TABLE: 747f17b149dSPeter Collingbourne W.OS << char(Import.Table.ElemType); 748f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // flags 749f17b149dSPeter Collingbourne encodeULEB128(NumElements, W.OS); // initial 750f950b24aSSam Clegg break; 751da419bdbSHeejin Ahn case wasm::WASM_EXTERNAL_EVENT: 752da419bdbSHeejin Ahn encodeULEB128(Import.Event.Attribute, W.OS); 753da419bdbSHeejin Ahn encodeULEB128(Import.Event.SigIndex, W.OS); 754da419bdbSHeejin Ahn break; 7559e15f359SSam Clegg default: 7569e15f359SSam Clegg llvm_unreachable("unsupported import kind"); 7579e15f359SSam Clegg } 7589e15f359SSam Clegg } 7599e15f359SSam Clegg 7609e15f359SSam Clegg endSection(Section); 7619e15f359SSam Clegg } 7629e15f359SSam Clegg 763457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 7649e15f359SSam Clegg if (Functions.empty()) 7659e15f359SSam Clegg return; 7669e15f359SSam Clegg 7679e15f359SSam Clegg SectionBookkeeping Section; 7689e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_FUNCTION); 7699e15f359SSam Clegg 770f17b149dSPeter Collingbourne encodeULEB128(Functions.size(), W.OS); 7719e15f359SSam Clegg for (const WasmFunction &Func : Functions) 772da419bdbSHeejin Ahn encodeULEB128(Func.SigIndex, W.OS); 7739e15f359SSam Clegg 7749e15f359SSam Clegg endSection(Section); 7759e15f359SSam Clegg } 7769e15f359SSam Clegg 777da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) { 778da419bdbSHeejin Ahn if (Events.empty()) 779da419bdbSHeejin Ahn return; 780da419bdbSHeejin Ahn 781da419bdbSHeejin Ahn SectionBookkeeping Section; 782da419bdbSHeejin Ahn startSection(Section, wasm::WASM_SEC_EVENT); 783da419bdbSHeejin Ahn 784da419bdbSHeejin Ahn encodeULEB128(Events.size(), W.OS); 785da419bdbSHeejin Ahn for (const wasm::WasmEventType &Event : Events) { 786da419bdbSHeejin Ahn encodeULEB128(Event.Attribute, W.OS); 787da419bdbSHeejin Ahn encodeULEB128(Event.SigIndex, W.OS); 788da419bdbSHeejin Ahn } 789da419bdbSHeejin Ahn 790da419bdbSHeejin Ahn endSection(Section); 791da419bdbSHeejin Ahn } 792da419bdbSHeejin Ahn 793*0a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) { 794*0a6c4d8dSSam Clegg if (Globals.empty()) 795*0a6c4d8dSSam Clegg return; 796*0a6c4d8dSSam Clegg 797*0a6c4d8dSSam Clegg SectionBookkeeping Section; 798*0a6c4d8dSSam Clegg startSection(Section, wasm::WASM_SEC_GLOBAL); 799*0a6c4d8dSSam Clegg 800*0a6c4d8dSSam Clegg encodeULEB128(Globals.size(), W.OS); 801*0a6c4d8dSSam Clegg for (const wasm::WasmGlobal &Global : Globals) { 802*0a6c4d8dSSam Clegg encodeULEB128(Global.Type.Type, W.OS); 803*0a6c4d8dSSam Clegg W.OS << char(Global.Type.Mutable); 804*0a6c4d8dSSam Clegg W.OS << char(Global.InitExpr.Opcode); 805*0a6c4d8dSSam Clegg switch (Global.Type.Type) { 806*0a6c4d8dSSam Clegg case wasm::WASM_TYPE_I32: 807*0a6c4d8dSSam Clegg encodeSLEB128(0, W.OS); 808*0a6c4d8dSSam Clegg break; 809*0a6c4d8dSSam Clegg case wasm::WASM_TYPE_I64: 810*0a6c4d8dSSam Clegg encodeSLEB128(0, W.OS); 811*0a6c4d8dSSam Clegg break; 812*0a6c4d8dSSam Clegg case wasm::WASM_TYPE_F32: 813*0a6c4d8dSSam Clegg writeI32(0); 814*0a6c4d8dSSam Clegg break; 815*0a6c4d8dSSam Clegg case wasm::WASM_TYPE_F64: 816*0a6c4d8dSSam Clegg writeI64(0); 817*0a6c4d8dSSam Clegg break; 818*0a6c4d8dSSam Clegg default: 819*0a6c4d8dSSam Clegg llvm_unreachable("unexpected type"); 820*0a6c4d8dSSam Clegg } 821*0a6c4d8dSSam Clegg W.OS << char(wasm::WASM_OPCODE_END); 822*0a6c4d8dSSam Clegg } 823*0a6c4d8dSSam Clegg 824*0a6c4d8dSSam Clegg endSection(Section); 825*0a6c4d8dSSam Clegg } 826*0a6c4d8dSSam Clegg 8278defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) { 8289e15f359SSam Clegg if (Exports.empty()) 8299e15f359SSam Clegg return; 8309e15f359SSam Clegg 8319e15f359SSam Clegg SectionBookkeeping Section; 8329e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_EXPORT); 8339e15f359SSam Clegg 834f17b149dSPeter Collingbourne encodeULEB128(Exports.size(), W.OS); 8358defa952SSam Clegg for (const wasm::WasmExport &Export : Exports) { 8368defa952SSam Clegg writeString(Export.Name); 837f17b149dSPeter Collingbourne W.OS << char(Export.Kind); 838f17b149dSPeter Collingbourne encodeULEB128(Export.Index, W.OS); 8399e15f359SSam Clegg } 8409e15f359SSam Clegg 8419e15f359SSam Clegg endSection(Section); 8429e15f359SSam Clegg } 8439e15f359SSam Clegg 844457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 8459e15f359SSam Clegg if (TableElems.empty()) 8469e15f359SSam Clegg return; 8479e15f359SSam Clegg 8489e15f359SSam Clegg SectionBookkeeping Section; 8499e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_ELEM); 8509e15f359SSam Clegg 851f17b149dSPeter Collingbourne encodeULEB128(1, W.OS); // number of "segments" 852f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // the table index 8539e15f359SSam Clegg 8549e15f359SSam Clegg // init expr for starting offset 855f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_I32_CONST); 85618c56a07SHeejin Ahn encodeSLEB128(InitialTableOffset, W.OS); 857f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_END); 8589e15f359SSam Clegg 859f17b149dSPeter Collingbourne encodeULEB128(TableElems.size(), W.OS); 8609e15f359SSam Clegg for (uint32_t Elem : TableElems) 861f17b149dSPeter Collingbourne encodeULEB128(Elem, W.OS); 8629e15f359SSam Clegg 8639e15f359SSam Clegg endSection(Section); 8649e15f359SSam Clegg } 8659e15f359SSam Clegg 866fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() { 867fef8de66SThomas Lively if (DataSegments.empty()) 868fef8de66SThomas Lively return; 869fef8de66SThomas Lively 870fef8de66SThomas Lively SectionBookkeeping Section; 871fef8de66SThomas Lively startSection(Section, wasm::WASM_SEC_DATACOUNT); 872fef8de66SThomas Lively encodeULEB128(DataSegments.size(), W.OS); 873fef8de66SThomas Lively endSection(Section); 874fef8de66SThomas Lively } 875fef8de66SThomas Lively 876457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 877457fb0b4SSam Clegg const MCAsmLayout &Layout, 878457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions) { 8799e15f359SSam Clegg if (Functions.empty()) 8809e15f359SSam Clegg return; 8819e15f359SSam Clegg 8829e15f359SSam Clegg SectionBookkeeping Section; 8839e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CODE); 8846f08c84aSSam Clegg CodeSectionIndex = Section.Index; 8859e15f359SSam Clegg 886f17b149dSPeter Collingbourne encodeULEB128(Functions.size(), W.OS); 8879e15f359SSam Clegg 8889e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 889fe6414b0SSam Clegg auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 8909e15f359SSam Clegg 8919e15f359SSam Clegg int64_t Size = 0; 8929e15f359SSam Clegg if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 8939e15f359SSam Clegg report_fatal_error(".size expression must be evaluatable"); 8949e15f359SSam Clegg 895f17b149dSPeter Collingbourne encodeULEB128(Size, W.OS); 896f17b149dSPeter Collingbourne FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset); 897f17b149dSPeter Collingbourne Asm.writeSectionData(W.OS, &FuncSection, Layout); 8989e15f359SSam Clegg } 8999e15f359SSam Clegg 9009e15f359SSam Clegg // Apply fixups. 901acd7d2b0SSam Clegg applyRelocations(CodeRelocations, Section.ContentsOffset); 9029e15f359SSam Clegg 9039e15f359SSam Clegg endSection(Section); 9049e15f359SSam Clegg } 9059e15f359SSam Clegg 9066c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() { 9076c899ba6SSam Clegg if (DataSegments.empty()) 9087c395943SSam Clegg return; 9099e15f359SSam Clegg 9109e15f359SSam Clegg SectionBookkeeping Section; 9119e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_DATA); 9126f08c84aSSam Clegg DataSectionIndex = Section.Index; 9139e15f359SSam Clegg 914f17b149dSPeter Collingbourne encodeULEB128(DataSegments.size(), W.OS); // count 9157c395943SSam Clegg 9166c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 9172e150409SThomas Lively encodeULEB128(Segment.InitFlags, W.OS); // flags 9182e150409SThomas Lively if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX) 919f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // memory index 9202e150409SThomas Lively if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) { 921f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_I32_CONST); 922f17b149dSPeter Collingbourne encodeSLEB128(Segment.Offset, W.OS); // offset 923f17b149dSPeter Collingbourne W.OS << char(wasm::WASM_OPCODE_END); 9242e150409SThomas Lively } 925f17b149dSPeter Collingbourne encodeULEB128(Segment.Data.size(), W.OS); // size 926f17b149dSPeter Collingbourne Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset); 927f17b149dSPeter Collingbourne W.OS << Segment.Data; // data 9287c395943SSam Clegg } 9299e15f359SSam Clegg 9309e15f359SSam Clegg // Apply fixups. 9317c395943SSam Clegg applyRelocations(DataRelocations, Section.ContentsOffset); 9329e15f359SSam Clegg 9339e15f359SSam Clegg endSection(Section); 9349e15f359SSam Clegg } 9359e15f359SSam Clegg 9366f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection( 9376f08c84aSSam Clegg uint32_t SectionIndex, StringRef Name, 938f77dc2a8SSam Clegg std::vector<WasmRelocationEntry> &Relocs) { 9399e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 9409e15f359SSam Clegg // for descriptions of the reloc sections. 9419e15f359SSam Clegg 942f77dc2a8SSam Clegg if (Relocs.empty()) 9439e15f359SSam Clegg return; 9449e15f359SSam Clegg 945f77dc2a8SSam Clegg // First, ensure the relocations are sorted in offset order. In general they 946f77dc2a8SSam Clegg // should already be sorted since `recordRelocation` is called in offset 947f77dc2a8SSam Clegg // order, but for the code section we combine many MC sections into single 948f77dc2a8SSam Clegg // wasm section, and this order is determined by the order of Asm.Symbols() 949f77dc2a8SSam Clegg // not the sections order. 950efd94c56SFangrui Song llvm::stable_sort( 951efd94c56SFangrui Song Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) { 952f77dc2a8SSam Clegg return (A.Offset + A.FixupSection->getSectionOffset()) < 953f77dc2a8SSam Clegg (B.Offset + B.FixupSection->getSectionOffset()); 954f77dc2a8SSam Clegg }); 955f77dc2a8SSam Clegg 9569e15f359SSam Clegg SectionBookkeeping Section; 9576f08c84aSSam Clegg startCustomSection(Section, std::string("reloc.") + Name.str()); 9589e15f359SSam Clegg 959f17b149dSPeter Collingbourne encodeULEB128(SectionIndex, W.OS); 960f77dc2a8SSam Clegg encodeULEB128(Relocs.size(), W.OS); 961f77dc2a8SSam Clegg for (const WasmRelocationEntry &RelEntry : Relocs) { 962f208f631SHeejin Ahn uint64_t Offset = 963f208f631SHeejin Ahn RelEntry.Offset + RelEntry.FixupSection->getSectionOffset(); 9646f08c84aSSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 9659e15f359SSam Clegg 966f17b149dSPeter Collingbourne W.OS << char(RelEntry.Type); 967f17b149dSPeter Collingbourne encodeULEB128(Offset, W.OS); 968f17b149dSPeter Collingbourne encodeULEB128(Index, W.OS); 9696f08c84aSSam Clegg if (RelEntry.hasAddend()) 970f17b149dSPeter Collingbourne encodeSLEB128(RelEntry.Addend, W.OS); 9719e15f359SSam Clegg } 9729e15f359SSam Clegg 9739e15f359SSam Clegg endSection(Section); 9749e15f359SSam Clegg } 9759e15f359SSam Clegg 9766a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() { 9776a31a0d6SSam Clegg for (const auto &Sec : CustomSections) { 9786a31a0d6SSam Clegg auto &Relocations = CustomSectionsRelocations[Sec.Section]; 9796a31a0d6SSam Clegg writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations); 9806a31a0d6SSam Clegg } 9816a31a0d6SSam Clegg } 9826a31a0d6SSam Clegg 9839e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection( 98486b4a09aSSam Clegg ArrayRef<wasm::WasmSymbolInfo> SymbolInfos, 985ea7caceeSSam Clegg ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs, 986ea7caceeSSam Clegg const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) { 9879e15f359SSam Clegg SectionBookkeeping Section; 9882322a937SSam Clegg startCustomSection(Section, "linking"); 989f17b149dSPeter Collingbourne encodeULEB128(wasm::WasmMetadataVersion, W.OS); 9909e15f359SSam Clegg 9916bb5a41fSSam Clegg SectionBookkeeping SubSection; 9926c899ba6SSam Clegg if (SymbolInfos.size() != 0) { 9936c899ba6SSam Clegg startSection(SubSection, wasm::WASM_SYMBOL_TABLE); 994f17b149dSPeter Collingbourne encodeULEB128(SymbolInfos.size(), W.OS); 9956c899ba6SSam Clegg for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) { 996f17b149dSPeter Collingbourne encodeULEB128(Sym.Kind, W.OS); 997f17b149dSPeter Collingbourne encodeULEB128(Sym.Flags, W.OS); 9986c899ba6SSam Clegg switch (Sym.Kind) { 9996c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_FUNCTION: 10006c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1001da419bdbSHeejin Ahn case wasm::WASM_SYMBOL_TYPE_EVENT: 1002f17b149dSPeter Collingbourne encodeULEB128(Sym.ElementIndex, W.OS); 100329874ceaSDan Gohman if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 || 100429874ceaSDan Gohman (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) 10056c899ba6SSam Clegg writeString(Sym.Name); 10066c899ba6SSam Clegg break; 10076c899ba6SSam Clegg case wasm::WASM_SYMBOL_TYPE_DATA: 10086c899ba6SSam Clegg writeString(Sym.Name); 10096c899ba6SSam Clegg if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) { 1010f17b149dSPeter Collingbourne encodeULEB128(Sym.DataRef.Segment, W.OS); 1011f17b149dSPeter Collingbourne encodeULEB128(Sym.DataRef.Offset, W.OS); 1012f17b149dSPeter Collingbourne encodeULEB128(Sym.DataRef.Size, W.OS); 10136c899ba6SSam Clegg } 10146c899ba6SSam Clegg break; 10156a31a0d6SSam Clegg case wasm::WASM_SYMBOL_TYPE_SECTION: { 10166a31a0d6SSam Clegg const uint32_t SectionIndex = 10176a31a0d6SSam Clegg CustomSections[Sym.ElementIndex].OutputIndex; 1018f17b149dSPeter Collingbourne encodeULEB128(SectionIndex, W.OS); 10196a31a0d6SSam Clegg break; 10206a31a0d6SSam Clegg } 10216c899ba6SSam Clegg default: 10226c899ba6SSam Clegg llvm_unreachable("unexpected kind"); 10236c899ba6SSam Clegg } 1024b7787fd0SSam Clegg } 1025b7787fd0SSam Clegg endSection(SubSection); 1026b7787fd0SSam Clegg } 10279e15f359SSam Clegg 10286c899ba6SSam Clegg if (DataSegments.size()) { 102963ebb813SSam Clegg startSection(SubSection, wasm::WASM_SEGMENT_INFO); 1030f17b149dSPeter Collingbourne encodeULEB128(DataSegments.size(), W.OS); 10316c899ba6SSam Clegg for (const WasmDataSegment &Segment : DataSegments) { 1032d95ed959SSam Clegg writeString(Segment.Name); 1033f17b149dSPeter Collingbourne encodeULEB128(Segment.Alignment, W.OS); 10342e150409SThomas Lively encodeULEB128(Segment.LinkerFlags, W.OS); 103563ebb813SSam Clegg } 1036d95ed959SSam Clegg endSection(SubSection); 1037d95ed959SSam Clegg } 1038d95ed959SSam Clegg 1039bafe6902SSam Clegg if (!InitFuncs.empty()) { 1040bafe6902SSam Clegg startSection(SubSection, wasm::WASM_INIT_FUNCS); 1041f17b149dSPeter Collingbourne encodeULEB128(InitFuncs.size(), W.OS); 1042bafe6902SSam Clegg for (auto &StartFunc : InitFuncs) { 1043f17b149dSPeter Collingbourne encodeULEB128(StartFunc.first, W.OS); // priority 1044f17b149dSPeter Collingbourne encodeULEB128(StartFunc.second, W.OS); // function index 1045bafe6902SSam Clegg } 1046bafe6902SSam Clegg endSection(SubSection); 1047bafe6902SSam Clegg } 1048bafe6902SSam Clegg 1049ea7caceeSSam Clegg if (Comdats.size()) { 1050ea7caceeSSam Clegg startSection(SubSection, wasm::WASM_COMDAT_INFO); 1051f17b149dSPeter Collingbourne encodeULEB128(Comdats.size(), W.OS); 1052ea7caceeSSam Clegg for (const auto &C : Comdats) { 1053ea7caceeSSam Clegg writeString(C.first); 1054f17b149dSPeter Collingbourne encodeULEB128(0, W.OS); // flags for future use 1055f17b149dSPeter Collingbourne encodeULEB128(C.second.size(), W.OS); 1056ea7caceeSSam Clegg for (const WasmComdatEntry &Entry : C.second) { 1057f17b149dSPeter Collingbourne encodeULEB128(Entry.Kind, W.OS); 1058f17b149dSPeter Collingbourne encodeULEB128(Entry.Index, W.OS); 1059ea7caceeSSam Clegg } 1060ea7caceeSSam Clegg } 1061ea7caceeSSam Clegg endSection(SubSection); 1062ea7caceeSSam Clegg } 1063ea7caceeSSam Clegg 10649e15f359SSam Clegg endSection(Section); 10659e15f359SSam Clegg } 10669e15f359SSam Clegg 1067cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection, 1068cbda16ebSThomas Lively const MCAssembler &Asm, 10696a31a0d6SSam Clegg const MCAsmLayout &Layout) { 1070cfd44a2eSSam Clegg SectionBookkeeping Section; 10716a31a0d6SSam Clegg auto *Sec = CustomSection.Section; 10722322a937SSam Clegg startCustomSection(Section, CustomSection.Name); 10736a31a0d6SSam Clegg 1074f17b149dSPeter Collingbourne Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset); 1075f17b149dSPeter Collingbourne Asm.writeSectionData(W.OS, Sec, Layout); 10766a31a0d6SSam Clegg 10776a31a0d6SSam Clegg CustomSection.OutputContentsOffset = Section.ContentsOffset; 10786a31a0d6SSam Clegg CustomSection.OutputIndex = Section.Index; 10796a31a0d6SSam Clegg 1080cfd44a2eSSam Clegg endSection(Section); 10816a31a0d6SSam Clegg 10826a31a0d6SSam Clegg // Apply fixups. 10834d57fbd0SSam Clegg auto &Relocations = CustomSectionsRelocations[CustomSection.Section]; 10844d57fbd0SSam Clegg applyRelocations(Relocations, CustomSection.OutputContentsOffset); 10856a31a0d6SSam Clegg } 10866a31a0d6SSam Clegg 10875e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) { 10885e3d33a7SSam Clegg assert(Symbol.isFunction()); 10895e3d33a7SSam Clegg assert(TypeIndices.count(&Symbol)); 10905e3d33a7SSam Clegg return TypeIndices[&Symbol]; 10915e3d33a7SSam Clegg } 10925e3d33a7SSam Clegg 1093da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) { 1094da419bdbSHeejin Ahn assert(Symbol.isEvent()); 1095da419bdbSHeejin Ahn assert(TypeIndices.count(&Symbol)); 1096da419bdbSHeejin Ahn return TypeIndices[&Symbol]; 1097da419bdbSHeejin Ahn } 1098da419bdbSHeejin Ahn 109938b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) { 11005e3d33a7SSam Clegg assert(Symbol.isFunction()); 11015e3d33a7SSam Clegg 1102da419bdbSHeejin Ahn WasmSignature S; 110318c56a07SHeejin Ahn const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol); 110477a7a380SDerek Schuff if (auto *Sig = ResolvedSym->getSignature()) { 1105da419bdbSHeejin Ahn S.Returns = Sig->Returns; 1106da419bdbSHeejin Ahn S.Params = Sig->Params; 110777a7a380SDerek Schuff } 11085e3d33a7SSam Clegg 1109da419bdbSHeejin Ahn auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 11105e3d33a7SSam Clegg if (Pair.second) 1111da419bdbSHeejin Ahn Signatures.push_back(S); 11125e3d33a7SSam Clegg TypeIndices[&Symbol] = Pair.first->second; 11135e3d33a7SSam Clegg 1114d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol 1115d34e60caSNicola Zaghen << " new:" << Pair.second << "\n"); 1116d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 11175e3d33a7SSam Clegg } 11185e3d33a7SSam Clegg 111938b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) { 1120da419bdbSHeejin Ahn assert(Symbol.isEvent()); 1121da419bdbSHeejin Ahn 1122da419bdbSHeejin Ahn // TODO Currently we don't generate imported exceptions, but if we do, we 1123da419bdbSHeejin Ahn // should have a way of infering types of imported exceptions. 1124da419bdbSHeejin Ahn WasmSignature S; 1125da419bdbSHeejin Ahn if (auto *Sig = Symbol.getSignature()) { 1126da419bdbSHeejin Ahn S.Returns = Sig->Returns; 1127da419bdbSHeejin Ahn S.Params = Sig->Params; 1128da419bdbSHeejin Ahn } 1129da419bdbSHeejin Ahn 1130da419bdbSHeejin Ahn auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size())); 1131da419bdbSHeejin Ahn if (Pair.second) 1132da419bdbSHeejin Ahn Signatures.push_back(S); 1133da419bdbSHeejin Ahn TypeIndices[&Symbol] = Pair.first->second; 1134da419bdbSHeejin Ahn 1135da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second 1136da419bdbSHeejin Ahn << "\n"); 1137da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 1138da419bdbSHeejin Ahn } 1139da419bdbSHeejin Ahn 11404d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) { 11413ea1c62cSSam Clegg if (Sym.isUsedInReloc() || Sym.isUsedInInitArray()) 11424d57fbd0SSam Clegg return true; 11434d57fbd0SSam Clegg 11444d57fbd0SSam Clegg if (Sym.isComdat() && !Sym.isDefined()) 11454d57fbd0SSam Clegg return false; 11464d57fbd0SSam Clegg 11473ea1c62cSSam Clegg if (Sym.isTemporary()) 11484d57fbd0SSam Clegg return false; 11494d57fbd0SSam Clegg 11504d57fbd0SSam Clegg if (Sym.isSection()) 11514d57fbd0SSam Clegg return false; 11524d57fbd0SSam Clegg 11534d57fbd0SSam Clegg return true; 11544d57fbd0SSam Clegg } 11554d57fbd0SSam Clegg 1156438390faSPeter Collingbourne uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm, 115718eafb6cSDan Gohman const MCAsmLayout &Layout) { 1158438390faSPeter Collingbourne uint64_t StartOffset = W.OS.tell(); 1159438390faSPeter Collingbourne 1160d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 1161d934cb88SDan Gohman 1162d934cb88SDan Gohman // Collect information from the available symbols. 1163d934cb88SDan Gohman SmallVector<WasmFunction, 4> Functions; 1164d934cb88SDan Gohman SmallVector<uint32_t, 4> TableElems; 11658defa952SSam Clegg SmallVector<wasm::WasmImport, 4> Imports; 11668defa952SSam Clegg SmallVector<wasm::WasmExport, 4> Exports; 1167da419bdbSHeejin Ahn SmallVector<wasm::WasmEventType, 1> Events; 1168*0a6c4d8dSSam Clegg SmallVector<wasm::WasmGlobal, 1> Globals; 11696c899ba6SSam Clegg SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos; 1170bafe6902SSam Clegg SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 1171ea7caceeSSam Clegg std::map<StringRef, std::vector<WasmComdatEntry>> Comdats; 11727c395943SSam Clegg uint32_t DataSize = 0; 1173d934cb88SDan Gohman 1174f950b24aSSam Clegg // For now, always emit the memory import, since loads and stores are not 1175f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1176f950b24aSSam Clegg // it if there are no loads or stores. 11778defa952SSam Clegg wasm::WasmImport MemImport; 11781ed3a046SSam Clegg MemImport.Module = "env"; 11791ed3a046SSam Clegg MemImport.Field = "__linear_memory"; 1180f950b24aSSam Clegg MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1181f950b24aSSam Clegg Imports.push_back(MemImport); 1182f950b24aSSam Clegg 1183f950b24aSSam Clegg // For now, always emit the table section, since indirect calls are not 1184f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1185f950b24aSSam Clegg // it if there are no indirect calls. 11868defa952SSam Clegg wasm::WasmImport TableImport; 11871ed3a046SSam Clegg TableImport.Module = "env"; 11881ed3a046SSam Clegg TableImport.Field = "__indirect_function_table"; 1189f950b24aSSam Clegg TableImport.Kind = wasm::WASM_EXTERNAL_TABLE; 11906a87ddacSThomas Lively TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF; 1191f950b24aSSam Clegg Imports.push_back(TableImport); 1192f950b24aSSam Clegg 1193da419bdbSHeejin Ahn // Populate SignatureIndices, and Imports and WasmIndices for undefined 1194586320c0SNicholas Wilson // symbols. This must be done before populating WasmIndices for defined 1195586320c0SNicholas Wilson // symbols. 119632ce5ca0SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 119732ce5ca0SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 119832ce5ca0SDan Gohman 119932ce5ca0SDan Gohman // Register types for all functions, including those with private linkage 12009f3fe42eSSam Clegg // (because wasm always needs a type signature). 120132ce5ca0SDan Gohman if (WS.isFunction()) 120232ce5ca0SDan Gohman registerFunctionType(WS); 120332ce5ca0SDan Gohman 1204da419bdbSHeejin Ahn if (WS.isEvent()) 1205da419bdbSHeejin Ahn registerEventType(WS); 1206da419bdbSHeejin Ahn 120732ce5ca0SDan Gohman if (WS.isTemporary()) 120832ce5ca0SDan Gohman continue; 120932ce5ca0SDan Gohman 121032ce5ca0SDan Gohman // If the symbol is not defined in this translation unit, import it. 12116c899ba6SSam Clegg if (!WS.isDefined() && !WS.isComdat()) { 12126c899ba6SSam Clegg if (WS.isFunction()) { 12138defa952SSam Clegg wasm::WasmImport Import; 1214f726e445SDan Gohman Import.Module = WS.getImportModule(); 1215f726e445SDan Gohman Import.Field = WS.getImportName(); 121632ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 12178defa952SSam Clegg Import.SigIndex = getFunctionType(WS); 12186c899ba6SSam Clegg Imports.push_back(Import); 1219492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 12206c899ba6SSam Clegg WasmIndices[&WS] = NumFunctionImports++; 12216c899ba6SSam Clegg } else if (WS.isGlobal()) { 122215f349f7SNicholas Wilson if (WS.isWeak()) 122315f349f7SNicholas Wilson report_fatal_error("undefined global symbol cannot be weak"); 122415f349f7SNicholas Wilson 12256c899ba6SSam Clegg wasm::WasmImport Import; 1226f726e445SDan Gohman Import.Field = WS.getImportName(); 122732ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1228492f7529SSam Clegg Import.Module = WS.getImportModule(); 12296c899ba6SSam Clegg Import.Global = WS.getGlobalType(); 12306c899ba6SSam Clegg Imports.push_back(Import); 1231492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 12326c899ba6SSam Clegg WasmIndices[&WS] = NumGlobalImports++; 1233da419bdbSHeejin Ahn } else if (WS.isEvent()) { 1234da419bdbSHeejin Ahn if (WS.isWeak()) 1235da419bdbSHeejin Ahn report_fatal_error("undefined event symbol cannot be weak"); 1236da419bdbSHeejin Ahn 1237da419bdbSHeejin Ahn wasm::WasmImport Import; 1238f726e445SDan Gohman Import.Module = WS.getImportModule(); 1239f726e445SDan Gohman Import.Field = WS.getImportName(); 1240da419bdbSHeejin Ahn Import.Kind = wasm::WASM_EXTERNAL_EVENT; 1241da419bdbSHeejin Ahn Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION; 1242da419bdbSHeejin Ahn Import.Event.SigIndex = getEventType(WS); 1243da419bdbSHeejin Ahn Imports.push_back(Import); 1244492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 1245da419bdbSHeejin Ahn WasmIndices[&WS] = NumEventImports++; 124632ce5ca0SDan Gohman } 124732ce5ca0SDan Gohman } 124832ce5ca0SDan Gohman } 124932ce5ca0SDan Gohman 1250492f7529SSam Clegg // Add imports for GOT globals 1251492f7529SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1252492f7529SSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 1253492f7529SSam Clegg if (WS.isUsedInGOT()) { 1254492f7529SSam Clegg wasm::WasmImport Import; 1255492f7529SSam Clegg if (WS.isFunction()) 1256492f7529SSam Clegg Import.Module = "GOT.func"; 1257492f7529SSam Clegg else 1258492f7529SSam Clegg Import.Module = "GOT.mem"; 1259492f7529SSam Clegg Import.Field = WS.getName(); 1260492f7529SSam Clegg Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1261492f7529SSam Clegg Import.Global = {wasm::WASM_TYPE_I32, true}; 1262492f7529SSam Clegg Imports.push_back(Import); 1263492f7529SSam Clegg assert(GOTIndices.count(&WS) == 0); 1264492f7529SSam Clegg GOTIndices[&WS] = NumGlobalImports++; 1265492f7529SSam Clegg } 1266492f7529SSam Clegg } 1267492f7529SSam Clegg 12684d57fbd0SSam Clegg // Populate DataSegments and CustomSections, which must be done before 12694d57fbd0SSam Clegg // populating DataLocations. 1270759631c7SSam Clegg for (MCSection &Sec : Asm) { 1271759631c7SSam Clegg auto &Section = static_cast<MCSectionWasm &>(Sec); 12727d1ff446SFangrui Song StringRef SectionName = Section.getName(); 1273759631c7SSam Clegg 1274bafe6902SSam Clegg // .init_array sections are handled specially elsewhere. 12754d57fbd0SSam Clegg if (SectionName.startswith(".init_array")) 1276bafe6902SSam Clegg continue; 1277bafe6902SSam Clegg 12784d57fbd0SSam Clegg // Code is handled separately 12794d57fbd0SSam Clegg if (Section.getKind().isText()) 12804d57fbd0SSam Clegg continue; 12814d57fbd0SSam Clegg 12824d57fbd0SSam Clegg if (Section.isWasmData()) { 1283329e76d5SSam Clegg uint32_t SegmentIndex = DataSegments.size(); 1284759631c7SSam Clegg DataSize = alignTo(DataSize, Section.getAlignment()); 1285759631c7SSam Clegg DataSegments.emplace_back(); 1286759631c7SSam Clegg WasmDataSegment &Segment = DataSegments.back(); 12874d57fbd0SSam Clegg Segment.Name = SectionName; 12889b49f36aSSimon Pilgrim Segment.InitFlags = 12899b49f36aSSimon Pilgrim Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0; 1290759631c7SSam Clegg Segment.Offset = DataSize; 1291759631c7SSam Clegg Segment.Section = &Section; 129263ebb813SSam Clegg addData(Segment.Data, Section); 129356c587adSSam Clegg Segment.Alignment = Log2_32(Section.getAlignment()); 12942e150409SThomas Lively Segment.LinkerFlags = 0; 1295759631c7SSam Clegg DataSize += Segment.Data.size(); 12966c899ba6SSam Clegg Section.setSegmentIndex(SegmentIndex); 1297ea7caceeSSam Clegg 1298ea7caceeSSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 1299ea7caceeSSam Clegg Comdats[C->getName()].emplace_back( 1300329e76d5SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex}); 1301ea7caceeSSam Clegg } 13024d57fbd0SSam Clegg } else { 13034d57fbd0SSam Clegg // Create custom sections 13044d57fbd0SSam Clegg assert(Sec.getKind().isMetadata()); 13054d57fbd0SSam Clegg 13064d57fbd0SSam Clegg StringRef Name = SectionName; 13074d57fbd0SSam Clegg 13084d57fbd0SSam Clegg // For user-defined custom sections, strip the prefix 13094d57fbd0SSam Clegg if (Name.startswith(".custom_section.")) 13104d57fbd0SSam Clegg Name = Name.substr(strlen(".custom_section.")); 13114d57fbd0SSam Clegg 13124d57fbd0SSam Clegg MCSymbol *Begin = Sec.getBeginSymbol(); 1313fb807d4dSSam Clegg if (Begin) { 13144d57fbd0SSam Clegg WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size(); 1315b210c64bSSam Clegg if (SectionName != Begin->getName()) 1316fb807d4dSSam Clegg report_fatal_error("section name and begin symbol should match: " + 1317b210c64bSSam Clegg Twine(SectionName)); 1318fb807d4dSSam Clegg } 1319cbda16ebSThomas Lively 1320f6f4f843SThomas Lively // Separate out the producers and target features sections 1321cbda16ebSThomas Lively if (Name == "producers") { 13220eaee545SJonas Devlieghere ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section); 1323cbda16ebSThomas Lively continue; 1324cbda16ebSThomas Lively } 1325f6f4f843SThomas Lively if (Name == "target_features") { 1326f6f4f843SThomas Lively TargetFeaturesSection = 13270eaee545SJonas Devlieghere std::make_unique<WasmCustomSection>(Name, &Section); 1328f6f4f843SThomas Lively continue; 1329f6f4f843SThomas Lively } 1330cbda16ebSThomas Lively 13314d57fbd0SSam Clegg CustomSections.emplace_back(Name, &Section); 1332759631c7SSam Clegg } 13336a31a0d6SSam Clegg } 13346a31a0d6SSam Clegg 1335586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for defined symbols. 1336d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1337d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1338d934cb88SDan Gohman // or used in relocations. 1339d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 1340d934cb88SDan Gohman continue; 1341b7787fd0SSam Clegg 1342d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 1343d34e60caSNicola Zaghen LLVM_DEBUG( 1344d34e60caSNicola Zaghen dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'" 1345d34e60caSNicola Zaghen << " isDefined=" << S.isDefined() << " isExternal=" 1346d34e60caSNicola Zaghen << S.isExternal() << " isTemporary=" << S.isTemporary() 1347d34e60caSNicola Zaghen << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden() 1348b7787fd0SSam Clegg << " isVariable=" << WS.isVariable() << "\n"); 1349b7787fd0SSam Clegg 13505e3d33a7SSam Clegg if (WS.isVariable()) 13515e3d33a7SSam Clegg continue; 13526c899ba6SSam Clegg if (WS.isComdat() && !WS.isDefined()) 13536c899ba6SSam Clegg continue; 1354b7787fd0SSam Clegg 1355d934cb88SDan Gohman if (WS.isFunction()) { 13566c899ba6SSam Clegg unsigned Index; 1357cd65f698SSam Clegg if (WS.isDefined()) { 1358b7787fd0SSam Clegg if (WS.getOffset() != 0) 1359b7787fd0SSam Clegg report_fatal_error( 1360b7787fd0SSam Clegg "function sections must contain one function each"); 1361b7787fd0SSam Clegg 136218c56a07SHeejin Ahn if (WS.getSize() == nullptr) 1363b7787fd0SSam Clegg report_fatal_error( 1364b7787fd0SSam Clegg "function symbols must have a size set with .size"); 1365b7787fd0SSam Clegg 13666c899ba6SSam Clegg // A definition. Write out the function body. 13679f3fe42eSSam Clegg Index = NumFunctionImports + Functions.size(); 1368d934cb88SDan Gohman WasmFunction Func; 1369da419bdbSHeejin Ahn Func.SigIndex = getFunctionType(WS); 1370d934cb88SDan Gohman Func.Sym = &WS; 13716c899ba6SSam Clegg WasmIndices[&WS] = Index; 1372d934cb88SDan Gohman Functions.push_back(Func); 13736c899ba6SSam Clegg 13746c899ba6SSam Clegg auto &Section = static_cast<MCSectionWasm &>(WS.getSection()); 13756c899ba6SSam Clegg if (const MCSymbolWasm *C = Section.getGroup()) { 13766c899ba6SSam Clegg Comdats[C->getName()].emplace_back( 13776c899ba6SSam Clegg WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index}); 13786c899ba6SSam Clegg } 1379881d8778SSam Clegg 1380881d8778SSam Clegg if (WS.hasExportName()) { 1381881d8778SSam Clegg wasm::WasmExport Export; 1382881d8778SSam Clegg Export.Name = WS.getExportName(); 1383881d8778SSam Clegg Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1384881d8778SSam Clegg Export.Index = Index; 1385881d8778SSam Clegg Exports.push_back(Export); 1386881d8778SSam Clegg } 1387d934cb88SDan Gohman } else { 1388d934cb88SDan Gohman // An import; the index was assigned above. 13896c899ba6SSam Clegg Index = WasmIndices.find(&WS)->second; 1390d934cb88SDan Gohman } 1391d934cb88SDan Gohman 1392d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n"); 1393da419bdbSHeejin Ahn 13946c899ba6SSam Clegg } else if (WS.isData()) { 1395f3feb6adSWouter van Oortmerssen if (!isInSymtab(WS)) 1396c38e947eSSam Clegg continue; 1397c38e947eSSam Clegg 13986c899ba6SSam Clegg if (!WS.isDefined()) { 1399d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> segment index: -1" 1400d34e60caSNicola Zaghen << "\n"); 1401fe6414b0SSam Clegg continue; 14026c899ba6SSam Clegg } 1403fe6414b0SSam Clegg 1404d934cb88SDan Gohman if (!WS.getSize()) 1405c38e947eSSam Clegg report_fatal_error("data symbols must have a size set with .size: " + 1406c38e947eSSam Clegg WS.getName()); 1407d934cb88SDan Gohman 1408d934cb88SDan Gohman int64_t Size = 0; 1409d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1410d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 1411d934cb88SDan Gohman 1412759631c7SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 1413079cba04SSam Clegg if (!DataSection.isWasmData()) 1414079cba04SSam Clegg report_fatal_error("data symbols must live in a data section: " + 1415079cba04SSam Clegg WS.getName()); 14167c395943SSam Clegg 14176c899ba6SSam Clegg // For each data symbol, export it in the symtab as a reference to the 14186c899ba6SSam Clegg // corresponding Wasm data segment. 14196c899ba6SSam Clegg wasm::WasmDataReference Ref = wasm::WasmDataReference{ 14206c899ba6SSam Clegg DataSection.getSegmentIndex(), 14216c899ba6SSam Clegg static_cast<uint32_t>(Layout.getSymbolOffset(WS)), 14226c899ba6SSam Clegg static_cast<uint32_t>(Size)}; 14236c899ba6SSam Clegg DataLocations[&WS] = Ref; 1424d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n"); 1425da419bdbSHeejin Ahn 1426a165f2d6SSam Clegg } else if (WS.isGlobal()) { 14276c899ba6SSam Clegg // A "true" Wasm global (currently just __stack_pointer) 1428*0a6c4d8dSSam Clegg if (WS.isDefined()) { 1429*0a6c4d8dSSam Clegg assert(WasmIndices.count(&WS) == 0); 1430*0a6c4d8dSSam Clegg wasm::WasmGlobal Global; 1431*0a6c4d8dSSam Clegg Global.Type = WS.getGlobalType(); 1432*0a6c4d8dSSam Clegg Global.Index = NumGlobalImports + Globals.size(); 1433*0a6c4d8dSSam Clegg switch (Global.Type.Type) { 1434*0a6c4d8dSSam Clegg case wasm::WASM_TYPE_I32: 1435*0a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST; 1436*0a6c4d8dSSam Clegg break; 1437*0a6c4d8dSSam Clegg case wasm::WASM_TYPE_I64: 1438*0a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST; 1439*0a6c4d8dSSam Clegg break; 1440*0a6c4d8dSSam Clegg case wasm::WASM_TYPE_F32: 1441*0a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST; 1442*0a6c4d8dSSam Clegg break; 1443*0a6c4d8dSSam Clegg case wasm::WASM_TYPE_F64: 1444*0a6c4d8dSSam Clegg Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST; 1445*0a6c4d8dSSam Clegg break; 1446*0a6c4d8dSSam Clegg default: 1447*0a6c4d8dSSam Clegg llvm_unreachable("unexpected type"); 1448*0a6c4d8dSSam Clegg } 1449*0a6c4d8dSSam Clegg WasmIndices[&WS] = Global.Index; 1450*0a6c4d8dSSam Clegg Globals.push_back(Global); 1451*0a6c4d8dSSam Clegg } else { 1452545932beSEric Christopher // An import; the index was assigned above 1453d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> global index: " 1454d34e60caSNicola Zaghen << WasmIndices.find(&WS)->second << "\n"); 1455*0a6c4d8dSSam Clegg } 1456da419bdbSHeejin Ahn } else if (WS.isEvent()) { 1457da419bdbSHeejin Ahn // C++ exception symbol (__cpp_exception) 1458da419bdbSHeejin Ahn unsigned Index; 1459da419bdbSHeejin Ahn if (WS.isDefined()) { 1460*0a6c4d8dSSam Clegg assert(WasmIndices.count(&WS) == 0); 1461da419bdbSHeejin Ahn Index = NumEventImports + Events.size(); 1462da419bdbSHeejin Ahn wasm::WasmEventType Event; 1463da419bdbSHeejin Ahn Event.SigIndex = getEventType(WS); 1464da419bdbSHeejin Ahn Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION; 1465da419bdbSHeejin Ahn WasmIndices[&WS] = Index; 1466da419bdbSHeejin Ahn Events.push_back(Event); 1467da419bdbSHeejin Ahn } else { 1468da419bdbSHeejin Ahn // An import; the index was assigned above. 1469492f7529SSam Clegg assert(WasmIndices.count(&WS) > 0); 1470da419bdbSHeejin Ahn } 1471da419bdbSHeejin Ahn LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second 1472da419bdbSHeejin Ahn << "\n"); 1473da419bdbSHeejin Ahn 1474a165f2d6SSam Clegg } else { 1475a165f2d6SSam Clegg assert(WS.isSection()); 1476d934cb88SDan Gohman } 1477d934cb88SDan Gohman } 1478d934cb88SDan Gohman 1479586320c0SNicholas Wilson // Populate WasmIndices and DataLocations for aliased symbols. We need to 1480586320c0SNicholas Wilson // process these in a separate pass because we need to have processed the 1481586320c0SNicholas Wilson // target of the alias before the alias itself and the symbols are not 1482586320c0SNicholas Wilson // necessarily ordered in this way. 1483b7787fd0SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1484b7787fd0SSam Clegg if (!S.isVariable()) 1485b7787fd0SSam Clegg continue; 148631a2c809SSam Clegg 1487cd65f698SSam Clegg assert(S.isDefined()); 1488b7787fd0SSam Clegg 14895e3d33a7SSam Clegg // Find the target symbol of this weak alias and export that index 1490aff1c4dfSSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 149118c56a07SHeejin Ahn const MCSymbolWasm *ResolvedSym = resolveSymbol(WS); 1492d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym 1493d34e60caSNicola Zaghen << "'\n"); 1494b7787fd0SSam Clegg 1495ffba00bdSSam Clegg if (ResolvedSym->isFunction()) { 14966c899ba6SSam Clegg assert(WasmIndices.count(ResolvedSym) > 0); 14976c899ba6SSam Clegg uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second; 1498492f7529SSam Clegg assert(WasmIndices.count(&WS) == 0); 14996c899ba6SSam Clegg WasmIndices[&WS] = WasmIndex; 1500d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n"); 1501ffba00bdSSam Clegg } else if (ResolvedSym->isData()) { 15026c899ba6SSam Clegg assert(DataLocations.count(ResolvedSym) > 0); 15036c899ba6SSam Clegg const wasm::WasmDataReference &Ref = 15046c899ba6SSam Clegg DataLocations.find(ResolvedSym)->second; 15056c899ba6SSam Clegg DataLocations[&WS] = Ref; 1506d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n"); 15076c899ba6SSam Clegg } else { 1508da419bdbSHeejin Ahn report_fatal_error("don't yet support global/event aliases"); 15096c899ba6SSam Clegg } 1510586320c0SNicholas Wilson } 151131a2c809SSam Clegg 1512586320c0SNicholas Wilson // Finally, populate the symbol table itself, in its "natural" order. 1513586320c0SNicholas Wilson for (const MCSymbol &S : Asm.symbols()) { 1514586320c0SNicholas Wilson const auto &WS = static_cast<const MCSymbolWasm &>(S); 151525d8e68bSSam Clegg if (!isInSymtab(WS)) { 151618c56a07SHeejin Ahn WS.setIndex(InvalidIndex); 1517586320c0SNicholas Wilson continue; 151825d8e68bSSam Clegg } 1519d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n"); 1520586320c0SNicholas Wilson 1521586320c0SNicholas Wilson uint32_t Flags = 0; 1522586320c0SNicholas Wilson if (WS.isWeak()) 1523586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_WEAK; 1524586320c0SNicholas Wilson if (WS.isHidden()) 1525586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN; 1526586320c0SNicholas Wilson if (!WS.isExternal() && WS.isDefined()) 1527586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL; 1528586320c0SNicholas Wilson if (WS.isUndefined()) 1529586320c0SNicholas Wilson Flags |= wasm::WASM_SYMBOL_UNDEFINED; 1530da84b688SDan Gohman if (WS.isNoStrip()) { 1531da84b688SDan Gohman Flags |= wasm::WASM_SYMBOL_NO_STRIP; 1532da84b688SDan Gohman if (isEmscripten()) { 1533d6ef8da3SSam Clegg Flags |= wasm::WASM_SYMBOL_EXPORTED; 1534da84b688SDan Gohman } 1535da84b688SDan Gohman } 1536b4f4e370SSam Clegg if (WS.hasImportName()) 153729874ceaSDan Gohman Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME; 1538881d8778SSam Clegg if (WS.hasExportName()) 1539881d8778SSam Clegg Flags |= wasm::WASM_SYMBOL_EXPORTED; 1540586320c0SNicholas Wilson 1541586320c0SNicholas Wilson wasm::WasmSymbolInfo Info; 1542586320c0SNicholas Wilson Info.Name = WS.getName(); 1543586320c0SNicholas Wilson Info.Kind = WS.getType(); 1544586320c0SNicholas Wilson Info.Flags = Flags; 15454d57fbd0SSam Clegg if (!WS.isData()) { 15464d57fbd0SSam Clegg assert(WasmIndices.count(&WS) > 0); 1547586320c0SNicholas Wilson Info.ElementIndex = WasmIndices.find(&WS)->second; 15484d57fbd0SSam Clegg } else if (WS.isDefined()) { 15494d57fbd0SSam Clegg assert(DataLocations.count(&WS) > 0); 1550586320c0SNicholas Wilson Info.DataRef = DataLocations.find(&WS)->second; 15514d57fbd0SSam Clegg } 155225d8e68bSSam Clegg WS.setIndex(SymbolInfos.size()); 1553586320c0SNicholas Wilson SymbolInfos.emplace_back(Info); 1554b7787fd0SSam Clegg } 1555b7787fd0SSam Clegg 15566006e091SSam Clegg { 15576006e091SSam Clegg auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 1558f9edbe95SSam Clegg // Functions referenced by a relocation need to put in the table. This is 1559f9edbe95SSam Clegg // purely to make the object file's provisional values readable, and is 1560f9edbe95SSam Clegg // ignored by the linker, which re-calculates the relocations itself. 1561d1152a26SSam Clegg if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 && 1562d1152a26SSam Clegg Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB) 1563f9edbe95SSam Clegg return; 1564f9edbe95SSam Clegg assert(Rel.Symbol->isFunction()); 156518c56a07SHeejin Ahn const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol); 15666c899ba6SSam Clegg uint32_t FunctionIndex = WasmIndices.find(&WS)->second; 156718c56a07SHeejin Ahn uint32_t TableIndex = TableElems.size() + InitialTableOffset; 1568f9edbe95SSam Clegg if (TableIndices.try_emplace(&WS, TableIndex).second) { 1569d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " -> adding " << WS.getName() 1570f9edbe95SSam Clegg << " to table: " << TableIndex << "\n"); 15716c899ba6SSam Clegg TableElems.push_back(FunctionIndex); 15726006e091SSam Clegg registerFunctionType(WS); 15736006e091SSam Clegg } 15746006e091SSam Clegg }; 1575970d02c4SDan Gohman 15766006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : CodeRelocations) 15776006e091SSam Clegg HandleReloc(RelEntry); 15786006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : DataRelocations) 15796006e091SSam Clegg HandleReloc(RelEntry); 1580d934cb88SDan Gohman } 1581d934cb88SDan Gohman 1582bafe6902SSam Clegg // Translate .init_array section contents into start functions. 1583bafe6902SSam Clegg for (const MCSection &S : Asm) { 1584bafe6902SSam Clegg const auto &WS = static_cast<const MCSectionWasm &>(S); 15857d1ff446SFangrui Song if (WS.getName().startswith(".fini_array")) 1586bafe6902SSam Clegg report_fatal_error(".fini_array sections are unsupported"); 15877d1ff446SFangrui Song if (!WS.getName().startswith(".init_array")) 1588bafe6902SSam Clegg continue; 1589bafe6902SSam Clegg if (WS.getFragmentList().empty()) 1590bafe6902SSam Clegg continue; 1591b210c64bSSam Clegg 1592b210c64bSSam Clegg // init_array is expected to contain a single non-empty data fragment 1593b210c64bSSam Clegg if (WS.getFragmentList().size() != 3) 1594bafe6902SSam Clegg report_fatal_error("only one .init_array section fragment supported"); 1595b210c64bSSam Clegg 1596b210c64bSSam Clegg auto IT = WS.begin(); 1597b210c64bSSam Clegg const MCFragment &EmptyFrag = *IT; 1598b210c64bSSam Clegg if (EmptyFrag.getKind() != MCFragment::FT_Data) 1599b210c64bSSam Clegg report_fatal_error(".init_array section should be aligned"); 1600b210c64bSSam Clegg 1601b210c64bSSam Clegg IT = std::next(IT); 1602b210c64bSSam Clegg const MCFragment &AlignFrag = *IT; 1603bafe6902SSam Clegg if (AlignFrag.getKind() != MCFragment::FT_Align) 1604bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned"); 1605bafe6902SSam Clegg if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1606bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned for pointers"); 1607b210c64bSSam Clegg 1608b210c64bSSam Clegg const MCFragment &Frag = *std::next(IT); 1609bafe6902SSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1610bafe6902SSam Clegg report_fatal_error("only data supported in .init_array section"); 1611b210c64bSSam Clegg 1612bafe6902SSam Clegg uint16_t Priority = UINT16_MAX; 16134d57fbd0SSam Clegg unsigned PrefixLength = strlen(".init_array"); 16147d1ff446SFangrui Song if (WS.getName().size() > PrefixLength) { 16157d1ff446SFangrui Song if (WS.getName()[PrefixLength] != '.') 1616f208f631SHeejin Ahn report_fatal_error( 1617f208f631SHeejin Ahn ".init_array section priority should start with '.'"); 16187d1ff446SFangrui Song if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority)) 1619bafe6902SSam Clegg report_fatal_error("invalid .init_array section priority"); 1620bafe6902SSam Clegg } 1621bafe6902SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1622bafe6902SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1623f208f631SHeejin Ahn for (const uint8_t * 162418c56a07SHeejin Ahn P = (const uint8_t *)Contents.data(), 162518c56a07SHeejin Ahn *End = (const uint8_t *)Contents.data() + Contents.size(); 162618c56a07SHeejin Ahn P != End; ++P) { 162718c56a07SHeejin Ahn if (*P != 0) 1628bafe6902SSam Clegg report_fatal_error("non-symbolic data in .init_array section"); 1629bafe6902SSam Clegg } 1630bafe6902SSam Clegg for (const MCFixup &Fixup : DataFrag.getFixups()) { 1631f208f631SHeejin Ahn assert(Fixup.getKind() == 1632f208f631SHeejin Ahn MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1633bafe6902SSam Clegg const MCExpr *Expr = Fixup.getValue(); 16348fffa1dfSSam Clegg auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr); 16358fffa1dfSSam Clegg if (!SymRef) 1636bafe6902SSam Clegg report_fatal_error("fixups in .init_array should be symbol references"); 16378fffa1dfSSam Clegg const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol()); 16388fffa1dfSSam Clegg if (TargetSym.getIndex() == InvalidIndex) 16393ea1c62cSSam Clegg report_fatal_error("symbols in .init_array should exist in symtab"); 16408fffa1dfSSam Clegg if (!TargetSym.isFunction()) 16418fffa1dfSSam Clegg report_fatal_error("symbols in .init_array should be for functions"); 164225d8e68bSSam Clegg InitFuncs.push_back( 16438fffa1dfSSam Clegg std::make_pair(Priority, TargetSym.getIndex())); 1644bafe6902SSam Clegg } 1645bafe6902SSam Clegg } 1646bafe6902SSam Clegg 164718eafb6cSDan Gohman // Write out the Wasm header. 164818eafb6cSDan Gohman writeHeader(Asm); 164918eafb6cSDan Gohman 1650da419bdbSHeejin Ahn writeTypeSection(Signatures); 1651f950b24aSSam Clegg writeImportSection(Imports, DataSize, TableElems.size()); 16529e15f359SSam Clegg writeFunctionSection(Functions); 1653f950b24aSSam Clegg // Skip the "table" section; we import the table instead. 1654f950b24aSSam Clegg // Skip the "memory" section; we import the memory instead. 1655da419bdbSHeejin Ahn writeEventSection(Events); 1656*0a6c4d8dSSam Clegg writeGlobalSection(Globals); 16579e15f359SSam Clegg writeExportSection(Exports); 16589e15f359SSam Clegg writeElemSection(TableElems); 1659fef8de66SThomas Lively writeDataCountSection(); 1660acd7d2b0SSam Clegg writeCodeSection(Asm, Layout, Functions); 16616c899ba6SSam Clegg writeDataSection(); 1662cbda16ebSThomas Lively for (auto &CustomSection : CustomSections) 1663cbda16ebSThomas Lively writeCustomSection(CustomSection, Asm, Layout); 1664c22bfb6bSNicholas Wilson writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats); 16656f08c84aSSam Clegg writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations); 16666f08c84aSSam Clegg writeRelocSection(DataSectionIndex, "DATA", DataRelocations); 16676a31a0d6SSam Clegg writeCustomRelocSections(); 1668cbda16ebSThomas Lively if (ProducersSection) 1669cbda16ebSThomas Lively writeCustomSection(*ProducersSection, Asm, Layout); 1670f6f4f843SThomas Lively if (TargetFeaturesSection) 1671f6f4f843SThomas Lively writeCustomSection(*TargetFeaturesSection, Asm, Layout); 1672970d02c4SDan Gohman 1673d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 1674438390faSPeter Collingbourne return W.OS.tell() - StartOffset; 167518eafb6cSDan Gohman } 167618eafb6cSDan Gohman 167760fbc7ccSLang Hames std::unique_ptr<MCObjectWriter> 16781301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 167918eafb6cSDan Gohman raw_pwrite_stream &OS) { 16800eaee545SJonas Devlieghere return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS); 168118eafb6cSDan Gohman } 1682