LCOV - code coverage report
Current view: top level - lib/MC - WasmObjectWriter.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 0 564 0.0 %
Date: 2018-02-23 15:42:53 Functions: 0 38 0.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file implements Wasm object file writer information.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "llvm/ADT/STLExtras.h"
      15             : #include "llvm/ADT/SmallPtrSet.h"
      16             : #include "llvm/BinaryFormat/Wasm.h"
      17             : #include "llvm/MC/MCAsmBackend.h"
      18             : #include "llvm/MC/MCAsmLayout.h"
      19             : #include "llvm/MC/MCAssembler.h"
      20             : #include "llvm/MC/MCContext.h"
      21             : #include "llvm/MC/MCExpr.h"
      22             : #include "llvm/MC/MCFixupKindInfo.h"
      23             : #include "llvm/MC/MCObjectWriter.h"
      24             : #include "llvm/MC/MCSectionWasm.h"
      25             : #include "llvm/MC/MCSymbolWasm.h"
      26             : #include "llvm/MC/MCValue.h"
      27             : #include "llvm/MC/MCWasmObjectWriter.h"
      28             : #include "llvm/Support/Casting.h"
      29             : #include "llvm/Support/Debug.h"
      30             : #include "llvm/Support/ErrorHandling.h"
      31             : #include "llvm/Support/LEB128.h"
      32             : #include "llvm/Support/StringSaver.h"
      33             : #include <vector>
      34             : 
      35             : using namespace llvm;
      36             : 
      37             : #define DEBUG_TYPE "mc"
      38             : 
      39             : namespace {
      40             : 
      41             : // Went we ceate the indirect function table we start at 1, so that there is
      42             : // and emtpy slot at 0 and therefore calling a null function pointer will trap.
      43             : static const uint32_t kInitialTableOffset = 1;
      44             : 
      45             : // For patching purposes, we need to remember where each section starts, both
      46             : // for patching up the section size field, and for patching up references to
      47             : // locations within the section.
      48             : struct SectionBookkeeping {
      49             :   // Where the size of the section is written.
      50             :   uint64_t SizeOffset;
      51             :   // Where the contents of the section starts (after the header).
      52             :   uint64_t ContentsOffset;
      53             : };
      54             : 
      55             : // The signature of a wasm function, in a struct capable of being used as a
      56             : // DenseMap key.
      57           0 : struct WasmFunctionType {
      58             :   // Support empty and tombstone instances, needed by DenseMap.
      59             :   enum { Plain, Empty, Tombstone } State;
      60             : 
      61             :   // The return types of the function.
      62             :   SmallVector<wasm::ValType, 1> Returns;
      63             : 
      64             :   // The parameter types of the function.
      65             :   SmallVector<wasm::ValType, 4> Params;
      66             : 
      67           0 :   WasmFunctionType() : State(Plain) {}
      68             : 
      69           0 :   bool operator==(const WasmFunctionType &Other) const {
      70           0 :     return State == Other.State && Returns == Other.Returns &&
      71           0 :            Params == Other.Params;
      72             :   }
      73             : };
      74             : 
      75             : // Traits for using WasmFunctionType in a DenseMap.
      76             : struct WasmFunctionTypeDenseMapInfo {
      77             :   static WasmFunctionType getEmptyKey() {
      78             :     WasmFunctionType FuncTy;
      79           0 :     FuncTy.State = WasmFunctionType::Empty;
      80             :     return FuncTy;
      81             :   }
      82             :   static WasmFunctionType getTombstoneKey() {
      83             :     WasmFunctionType FuncTy;
      84           0 :     FuncTy.State = WasmFunctionType::Tombstone;
      85             :     return FuncTy;
      86             :   }
      87             :   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
      88           0 :     uintptr_t Value = FuncTy.State;
      89           0 :     for (wasm::ValType Ret : FuncTy.Returns)
      90           0 :       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
      91           0 :     for (wasm::ValType Param : FuncTy.Params)
      92           0 :       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
      93           0 :     return Value;
      94             :   }
      95             :   static bool isEqual(const WasmFunctionType &LHS,
      96             :                       const WasmFunctionType &RHS) {
      97           0 :     return LHS == RHS;
      98             :   }
      99             : };
     100             : 
     101             : // A wasm data segment.  A wasm binary contains only a single data section
     102             : // but that can contain many segments, each with their own virtual location
     103             : // in memory.  Each MCSection data created by llvm is modeled as its own
     104             : // wasm data segment.
     105           0 : struct WasmDataSegment {
     106             :   MCSectionWasm *Section;
     107             :   StringRef Name;
     108             :   uint32_t Offset;
     109             :   uint32_t Alignment;
     110             :   uint32_t Flags;
     111             :   SmallVector<char, 4> Data;
     112             : };
     113             : 
     114             : // A wasm function to be written into the function section.
     115             : struct WasmFunction {
     116             :   int32_t Type;
     117             :   const MCSymbolWasm *Sym;
     118             : };
     119             : 
     120             : // A wasm global to be written into the global section.
     121             : struct WasmGlobal {
     122             :   wasm::WasmGlobalType Type;
     123             :   uint64_t InitialValue;
     124             : };
     125             : 
     126             : // Information about a single item which is part of a COMDAT.  For each data
     127             : // segment or function which is in the COMDAT, there is a corresponding
     128             : // WasmComdatEntry.
     129             : struct WasmComdatEntry {
     130             :   unsigned Kind;
     131             :   uint32_t Index;
     132             : };
     133             : 
     134             : // Information about a single relocation.
     135             : struct WasmRelocationEntry {
     136             :   uint64_t Offset;                  // Where is the relocation.
     137             :   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
     138             :   int64_t Addend;                   // A value to add to the symbol.
     139             :   unsigned Type;                    // The type of the relocation.
     140             :   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
     141             : 
     142             :   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
     143             :                       int64_t Addend, unsigned Type,
     144             :                       const MCSectionWasm *FixupSection)
     145           0 :       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
     146           0 :         FixupSection(FixupSection) {}
     147             : 
     148             :   bool hasAddend() const {
     149           0 :     switch (Type) {
     150             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
     151             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
     152             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
     153             :       return true;
     154             :     default:
     155             :       return false;
     156             :     }
     157             :   }
     158             : 
     159             :   void print(raw_ostream &Out) const {
     160             :     Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
     161             :         << ", Type=" << Type
     162             :         << ", FixupSection=" << FixupSection->getSectionName();
     163             :   }
     164             : 
     165             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
     166             :   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
     167             : #endif
     168             : };
     169             : 
     170             : #if !defined(NDEBUG)
     171             : raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
     172             :   Rel.print(OS);
     173             :   return OS;
     174             : }
     175             : #endif
     176             : 
     177             : class WasmObjectWriter : public MCObjectWriter {
     178             :   /// The target specific Wasm writer instance.
     179             :   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
     180             : 
     181             :   // Relocations for fixing up references in the code section.
     182             :   std::vector<WasmRelocationEntry> CodeRelocations;
     183             : 
     184             :   // Relocations for fixing up references in the data section.
     185             :   std::vector<WasmRelocationEntry> DataRelocations;
     186             : 
     187             :   // Index values to use for fixing up call_indirect type indices.
     188             :   // Maps function symbols to the index of the type of the function
     189             :   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
     190             :   // Maps function symbols to the table element index space. Used
     191             :   // for TABLE_INDEX relocation types (i.e. address taken functions).
     192             :   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
     193             :   // Maps function/global symbols to the (shared) Symbol index space.
     194             :   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
     195             :   // Maps function/global symbols to the function/global Wasm index space.
     196             :   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
     197             :   // Maps data symbols to the Wasm segment and offset/size with the segment.
     198             :   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
     199             : 
     200             :   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
     201             :       FunctionTypeIndices;
     202             :   SmallVector<WasmFunctionType, 4> FunctionTypes;
     203             :   SmallVector<WasmGlobal, 4> Globals;
     204             :   SmallVector<WasmDataSegment, 4> DataSegments;
     205             :   unsigned NumFunctionImports = 0;
     206             :   unsigned NumGlobalImports = 0;
     207             : 
     208             :   // TargetObjectWriter wrappers.
     209             :   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
     210             :   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
     211           0 :     return TargetObjectWriter->getRelocType(Target, Fixup);
     212             :   }
     213             : 
     214             :   void startSection(SectionBookkeeping &Section, unsigned SectionId,
     215             :                     const char *Name = nullptr);
     216             :   void endSection(SectionBookkeeping &Section);
     217             : 
     218             : public:
     219           0 :   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
     220             :                    raw_pwrite_stream &OS)
     221           0 :       : MCObjectWriter(OS, /*IsLittleEndian=*/true),
     222           0 :         TargetObjectWriter(std::move(MOTW)) {}
     223             : 
     224             :   ~WasmObjectWriter() override;
     225             : 
     226             : private:
     227           0 :   void reset() override {
     228             :     CodeRelocations.clear();
     229             :     DataRelocations.clear();
     230           0 :     TypeIndices.clear();
     231           0 :     SymbolIndices.clear();
     232           0 :     WasmIndices.clear();
     233           0 :     TableIndices.clear();
     234           0 :     DataLocations.clear();
     235           0 :     FunctionTypeIndices.clear();
     236             :     FunctionTypes.clear();
     237             :     Globals.clear();
     238           0 :     DataSegments.clear();
     239             :     MCObjectWriter::reset();
     240           0 :     NumFunctionImports = 0;
     241           0 :     NumGlobalImports = 0;
     242           0 :   }
     243             : 
     244             :   void writeHeader(const MCAssembler &Asm);
     245             : 
     246             :   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
     247             :                         const MCFragment *Fragment, const MCFixup &Fixup,
     248             :                         MCValue Target, uint64_t &FixedValue) override;
     249             : 
     250             :   void executePostLayoutBinding(MCAssembler &Asm,
     251             :                                 const MCAsmLayout &Layout) override;
     252             : 
     253             :   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
     254             : 
     255           0 :   void writeString(const StringRef Str) {
     256           0 :     encodeULEB128(Str.size(), getStream());
     257             :     writeBytes(Str);
     258           0 :   }
     259             : 
     260             :   void writeValueType(wasm::ValType Ty) {
     261           0 :     encodeSLEB128(int32_t(Ty), getStream());
     262             :   }
     263             : 
     264             :   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
     265             :   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
     266             :                           uint32_t NumElements);
     267             :   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
     268             :   void writeGlobalSection();
     269             :   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
     270             :   void writeElemSection(ArrayRef<uint32_t> TableElems);
     271             :   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
     272             :                         ArrayRef<WasmFunction> Functions);
     273             :   void writeDataSection();
     274             :   void writeCodeRelocSection();
     275             :   void writeDataRelocSection();
     276             :   void writeLinkingMetaDataSection(
     277             :       uint32_t DataSize, ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
     278             :       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
     279             :       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
     280             : 
     281             :   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
     282             :   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
     283             :                         uint64_t ContentsOffset);
     284             : 
     285             :   void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
     286             :   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
     287             :   uint32_t getFunctionType(const MCSymbolWasm& Symbol);
     288             :   uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
     289             : };
     290             : 
     291             : } // end anonymous namespace
     292             : 
     293           0 : WasmObjectWriter::~WasmObjectWriter() {}
     294             : 
     295             : // Write out a section header and a patchable section size field.
     296           0 : void WasmObjectWriter::startSection(SectionBookkeeping &Section,
     297             :                                     unsigned SectionId,
     298             :                                     const char *Name) {
     299             :   assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
     300             :          "Only custom sections can have names");
     301             : 
     302             :   DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
     303           0 :   encodeULEB128(SectionId, getStream());
     304             : 
     305           0 :   Section.SizeOffset = getStream().tell();
     306             : 
     307             :   // The section size. We don't know the size yet, so reserve enough space
     308             :   // for any 32-bit value; we'll patch it later.
     309           0 :   encodeULEB128(UINT32_MAX, getStream());
     310             : 
     311             :   // The position where the section starts, for measuring its size.
     312           0 :   Section.ContentsOffset = getStream().tell();
     313             : 
     314             :   // Custom sections in wasm also have a string identifier.
     315           0 :   if (SectionId == wasm::WASM_SEC_CUSTOM) {
     316             :     assert(Name);
     317           0 :     writeString(StringRef(Name));
     318             :   }
     319           0 : }
     320             : 
     321             : // Now that the section is complete and we know how big it is, patch up the
     322             : // section size field at the start of the section.
     323           0 : void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
     324           0 :   uint64_t Size = getStream().tell() - Section.ContentsOffset;
     325           0 :   if (uint32_t(Size) != Size)
     326           0 :     report_fatal_error("section size does not fit in a uint32_t");
     327             : 
     328             :   DEBUG(dbgs() << "endSection size=" << Size << "\n");
     329             : 
     330             :   // Write the final section size to the payload_len field, which follows
     331             :   // the section id byte.
     332             :   uint8_t Buffer[16];
     333           0 :   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
     334             :   assert(SizeLen == 5);
     335           0 :   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
     336           0 : }
     337             : 
     338             : // Emit the Wasm header.
     339           0 : void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
     340             :   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
     341           0 :   writeLE32(wasm::WasmVersion);
     342           0 : }
     343             : 
     344           0 : void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
     345             :                                                 const MCAsmLayout &Layout) {
     346           0 : }
     347             : 
     348           0 : void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
     349             :                                         const MCAsmLayout &Layout,
     350             :                                         const MCFragment *Fragment,
     351             :                                         const MCFixup &Fixup, MCValue Target,
     352             :                                         uint64_t &FixedValue) {
     353           0 :   MCAsmBackend &Backend = Asm.getBackend();
     354           0 :   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
     355             :                  MCFixupKindInfo::FKF_IsPCRel;
     356           0 :   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
     357           0 :   uint64_t C = Target.getConstant();
     358           0 :   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
     359           0 :   MCContext &Ctx = Asm.getContext();
     360             : 
     361             :   // The .init_array isn't translated as data, so don't do relocations in it.
     362             :   if (FixupSection.getSectionName().startswith(".init_array"))
     363           0 :     return;
     364             : 
     365             :   // TODO(sbc): Add support for debug sections.
     366           0 :   if (FixupSection.getKind().isMetadata())
     367             :     return;
     368             : 
     369           0 :   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
     370             :     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
     371             :            "Should not have constructed this");
     372             : 
     373             :     // Let A, B and C being the components of Target and R be the location of
     374             :     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
     375             :     // If it is pcrel, we want to compute (A - B + C - R).
     376             : 
     377             :     // In general, Wasm has no relocations for -B. It can only represent (A + C)
     378             :     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
     379             :     // replace B to implement it: (A - R - K + C)
     380           0 :     if (IsPCRel) {
     381           0 :       Ctx.reportError(
     382             :           Fixup.getLoc(),
     383             :           "No relocation available to represent this relative expression");
     384           0 :       return;
     385             :     }
     386             : 
     387           0 :     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
     388             : 
     389           0 :     if (SymB.isUndefined()) {
     390           0 :       Ctx.reportError(Fixup.getLoc(),
     391           0 :                       Twine("symbol '") + SymB.getName() +
     392           0 :                           "' can not be undefined in a subtraction expression");
     393           0 :       return;
     394             :     }
     395             : 
     396             :     assert(!SymB.isAbsolute() && "Should have been folded");
     397             :     const MCSection &SecB = SymB.getSection();
     398           0 :     if (&SecB != &FixupSection) {
     399           0 :       Ctx.reportError(Fixup.getLoc(),
     400             :                       "Cannot represent a difference across sections");
     401           0 :       return;
     402             :     }
     403             : 
     404           0 :     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
     405           0 :     uint64_t K = SymBOffset - FixupOffset;
     406             :     IsPCRel = true;
     407           0 :     C -= K;
     408             :   }
     409             : 
     410             :   // We either rejected the fixup or folded B into C at this point.
     411           0 :   const MCSymbolRefExpr *RefA = Target.getSymA();
     412           0 :   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
     413             : 
     414           0 :   if (SymA && SymA->isVariable()) {
     415             :     const MCExpr *Expr = SymA->getVariableValue();
     416             :     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
     417           0 :     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
     418           0 :       llvm_unreachable("weakref used in reloc not yet implemented");
     419             :   }
     420             : 
     421             :   // Put any constant offset in an addend. Offsets can be negative, and
     422             :   // LLVM expects wrapping, in contrast to wasm's immediates which can't
     423             :   // be negative and don't wrap.
     424           0 :   FixedValue = 0;
     425             : 
     426           0 :   if (SymA)
     427             :     SymA->setUsedInReloc();
     428             : 
     429             :   assert(!IsPCRel);
     430             :   assert(SymA);
     431             : 
     432             :   unsigned Type = getRelocType(Target, Fixup);
     433             : 
     434           0 :   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
     435             :   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
     436             : 
     437             :   // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are currently required
     438             :   // to be against a named symbol.
     439             :   // TODO(sbc): Add support for relocations against unnamed temporaries such
     440             :   // as those generated by llvm's `blockaddress`.
     441             :   // See: test/MC/WebAssembly/blockaddress.ll
     442           0 :   if (SymA->getName().empty() && Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
     443           0 :     report_fatal_error("relocations against un-named temporaries are not yet "
     444             :                        "supported by wasm");
     445             : 
     446           0 :   if (FixupSection.isWasmData())
     447           0 :     DataRelocations.push_back(Rec);
     448           0 :   else if (FixupSection.getKind().isText())
     449           0 :     CodeRelocations.push_back(Rec);
     450             :   else
     451           0 :     llvm_unreachable("unexpected section type");
     452             : }
     453             : 
     454             : // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
     455             : // to allow patching.
     456             : static void
     457           0 : WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
     458             :   uint8_t Buffer[5];
     459           0 :   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
     460             :   assert(SizeLen == 5);
     461           0 :   Stream.pwrite((char *)Buffer, SizeLen, Offset);
     462           0 : }
     463             : 
     464             : // Write X as an signed LEB value at offset Offset in Stream, padded
     465             : // to allow patching.
     466             : static void
     467           0 : WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
     468             :   uint8_t Buffer[5];
     469           0 :   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
     470             :   assert(SizeLen == 5);
     471           0 :   Stream.pwrite((char *)Buffer, SizeLen, Offset);
     472           0 : }
     473             : 
     474             : // Write X as a plain integer value at offset Offset in Stream.
     475             : static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
     476             :   uint8_t Buffer[4];
     477             :   support::endian::write32le(Buffer, X);
     478             :   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
     479             : }
     480             : 
     481             : static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
     482           0 :   if (Symbol.isVariable()) {
     483             :     const MCExpr *Expr = Symbol.getVariableValue();
     484             :     auto *Inner = cast<MCSymbolRefExpr>(Expr);
     485           0 :     return cast<MCSymbolWasm>(&Inner->getSymbol());
     486             :   }
     487             :   return &Symbol;
     488             : }
     489             : 
     490             : // Compute a value to write into the code at the location covered
     491             : // by RelEntry. This value isn't used by the static linker; it just serves
     492             : // to make the object format more readable and more likely to be directly
     493             : // useable.
     494             : uint32_t
     495           0 : WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
     496           0 :   switch (RelEntry.Type) {
     497           0 :   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
     498             :   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
     499             :     // Provisional value is table address of the resolved symbol itself
     500           0 :     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
     501             :     assert(Sym->isFunction());
     502           0 :     return TableIndices[Sym];
     503             :   }
     504           0 :   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
     505             :     // Provisional value is same as the index
     506           0 :     return getRelocationIndexValue(RelEntry);
     507           0 :   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
     508             :   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
     509             :     // Provisional value is function/global Wasm index
     510           0 :     if (!WasmIndices.count(RelEntry.Symbol))
     511           0 :       report_fatal_error("symbol not found in wasm index space: " +
     512           0 :                          RelEntry.Symbol->getName());
     513           0 :     return WasmIndices[RelEntry.Symbol];
     514           0 :   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
     515             :   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
     516             :   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
     517             :     // Provisional value is address of the global
     518           0 :     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
     519             :     // For undefined symbols, use zero
     520           0 :     if (!Sym->isDefined())
     521             :       return 0;
     522           0 :     const wasm::WasmDataReference &Ref = DataLocations[Sym];
     523           0 :     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
     524             :     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
     525           0 :     return Segment.Offset + Ref.Offset + RelEntry.Addend;
     526             :   }
     527           0 :   default:
     528           0 :     llvm_unreachable("invalid relocation type");
     529             :   }
     530             : }
     531             : 
     532           0 : static void addData(SmallVectorImpl<char> &DataBytes,
     533             :                     MCSectionWasm &DataSection) {
     534             :   DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
     535             : 
     536           0 :   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
     537             : 
     538           0 :   for (const MCFragment &Frag : DataSection) {
     539           0 :     if (Frag.hasInstructions())
     540           0 :       report_fatal_error("only data supported in data sections");
     541             : 
     542             :     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
     543           0 :       if (Align->getValueSize() != 1)
     544           0 :         report_fatal_error("only byte values supported for alignment");
     545             :       // If nops are requested, use zeros, as this is the data section.
     546           0 :       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
     547           0 :       uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
     548           0 :                                                  Align->getAlignment()),
     549           0 :                                          DataBytes.size() +
     550           0 :                                              Align->getMaxBytesToEmit());
     551           0 :       DataBytes.resize(Size, Value);
     552             :     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
     553             :       int64_t Size;
     554           0 :       if (!Fill->getSize().evaluateAsAbsolute(Size))
     555           0 :         llvm_unreachable("The fill should be an assembler constant");
     556           0 :       DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
     557             :     } else {
     558             :       const auto &DataFrag = cast<MCDataFragment>(Frag);
     559             :       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
     560             : 
     561           0 :       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
     562             :     }
     563             :   }
     564             : 
     565             :   DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
     566           0 : }
     567             : 
     568             : uint32_t
     569           0 : WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
     570           0 :   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
     571           0 :     if (!TypeIndices.count(RelEntry.Symbol))
     572           0 :       report_fatal_error("symbol not found in type index space: " +
     573           0 :                          RelEntry.Symbol->getName());
     574           0 :     return TypeIndices[RelEntry.Symbol];
     575             :   }
     576             : 
     577           0 :   if (!SymbolIndices.count(RelEntry.Symbol))
     578           0 :     report_fatal_error("symbol not found in symbol index space: " +
     579           0 :                        RelEntry.Symbol->getName());
     580           0 :   return SymbolIndices[RelEntry.Symbol];
     581             : }
     582             : 
     583             : // Apply the portions of the relocation records that we can handle ourselves
     584             : // directly.
     585           0 : void WasmObjectWriter::applyRelocations(
     586             :     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
     587           0 :   raw_pwrite_stream &Stream = getStream();
     588           0 :   for (const WasmRelocationEntry &RelEntry : Relocations) {
     589           0 :     uint64_t Offset = ContentsOffset +
     590           0 :                       RelEntry.FixupSection->getSectionOffset() +
     591           0 :                       RelEntry.Offset;
     592             : 
     593             :     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
     594           0 :     uint32_t Value = getProvisionalValue(RelEntry);
     595             : 
     596           0 :     switch (RelEntry.Type) {
     597           0 :     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
     598             :     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
     599             :     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
     600             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
     601           0 :       WritePatchableLEB(Stream, Value, Offset);
     602           0 :       break;
     603             :     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
     604             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
     605             :       WriteI32(Stream, Value, Offset);
     606             :       break;
     607           0 :     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
     608             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
     609           0 :       WritePatchableSLEB(Stream, Value, Offset);
     610           0 :       break;
     611           0 :     default:
     612           0 :       llvm_unreachable("invalid relocation type");
     613             :     }
     614             :   }
     615           0 : }
     616             : 
     617             : // Write out the portions of the relocation records that the linker will
     618             : // need to handle.
     619           0 : void WasmObjectWriter::writeRelocations(
     620             :     ArrayRef<WasmRelocationEntry> Relocations) {
     621           0 :   raw_pwrite_stream &Stream = getStream();
     622           0 :   for (const WasmRelocationEntry& RelEntry : Relocations) {
     623             : 
     624           0 :     uint64_t Offset = RelEntry.Offset +
     625           0 :                       RelEntry.FixupSection->getSectionOffset();
     626           0 :     uint32_t Index = getRelocationIndexValue(RelEntry);
     627             : 
     628           0 :     encodeULEB128(RelEntry.Type, Stream);
     629           0 :     encodeULEB128(Offset, Stream);
     630           0 :     encodeULEB128(Index, Stream);
     631           0 :     if (RelEntry.hasAddend())
     632           0 :       encodeSLEB128(RelEntry.Addend, Stream);
     633             :   }
     634           0 : }
     635             : 
     636           0 : void WasmObjectWriter::writeTypeSection(
     637             :     ArrayRef<WasmFunctionType> FunctionTypes) {
     638           0 :   if (FunctionTypes.empty())
     639           0 :     return;
     640             : 
     641             :   SectionBookkeeping Section;
     642           0 :   startSection(Section, wasm::WASM_SEC_TYPE);
     643             : 
     644           0 :   encodeULEB128(FunctionTypes.size(), getStream());
     645             : 
     646           0 :   for (const WasmFunctionType &FuncTy : FunctionTypes) {
     647           0 :     encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
     648           0 :     encodeULEB128(FuncTy.Params.size(), getStream());
     649           0 :     for (wasm::ValType Ty : FuncTy.Params)
     650             :       writeValueType(Ty);
     651           0 :     encodeULEB128(FuncTy.Returns.size(), getStream());
     652           0 :     for (wasm::ValType Ty : FuncTy.Returns)
     653             :       writeValueType(Ty);
     654             :   }
     655             : 
     656           0 :   endSection(Section);
     657             : }
     658             : 
     659           0 : void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
     660             :                                           uint32_t DataSize,
     661             :                                           uint32_t NumElements) {
     662           0 :   if (Imports.empty())
     663           0 :     return;
     664             : 
     665           0 :   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
     666             : 
     667             :   SectionBookkeeping Section;
     668           0 :   startSection(Section, wasm::WASM_SEC_IMPORT);
     669             : 
     670           0 :   encodeULEB128(Imports.size(), getStream());
     671           0 :   for (const wasm::WasmImport &Import : Imports) {
     672           0 :     writeString(Import.Module);
     673           0 :     writeString(Import.Field);
     674           0 :     encodeULEB128(Import.Kind, getStream());
     675             : 
     676           0 :     switch (Import.Kind) {
     677           0 :     case wasm::WASM_EXTERNAL_FUNCTION:
     678           0 :       encodeULEB128(Import.SigIndex, getStream());
     679           0 :       break;
     680           0 :     case wasm::WASM_EXTERNAL_GLOBAL:
     681           0 :       encodeSLEB128(Import.Global.Type, getStream());
     682           0 :       encodeULEB128(uint32_t(Import.Global.Mutable), getStream());
     683           0 :       break;
     684           0 :     case wasm::WASM_EXTERNAL_MEMORY:
     685           0 :       encodeULEB128(0, getStream()); // flags
     686           0 :       encodeULEB128(NumPages, getStream()); // initial
     687           0 :       break;
     688           0 :     case wasm::WASM_EXTERNAL_TABLE:
     689           0 :       encodeSLEB128(Import.Table.ElemType, getStream());
     690           0 :       encodeULEB128(0, getStream()); // flags
     691           0 :       encodeULEB128(NumElements, getStream()); // initial
     692           0 :       break;
     693           0 :     default:
     694           0 :       llvm_unreachable("unsupported import kind");
     695             :     }
     696             :   }
     697             : 
     698           0 :   endSection(Section);
     699             : }
     700             : 
     701           0 : void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
     702           0 :   if (Functions.empty())
     703           0 :     return;
     704             : 
     705             :   SectionBookkeeping Section;
     706           0 :   startSection(Section, wasm::WASM_SEC_FUNCTION);
     707             : 
     708           0 :   encodeULEB128(Functions.size(), getStream());
     709           0 :   for (const WasmFunction &Func : Functions)
     710           0 :     encodeULEB128(Func.Type, getStream());
     711             : 
     712           0 :   endSection(Section);
     713             : }
     714             : 
     715           0 : void WasmObjectWriter::writeGlobalSection() {
     716           0 :   if (Globals.empty())
     717           0 :     return;
     718             : 
     719             :   SectionBookkeeping Section;
     720           0 :   startSection(Section, wasm::WASM_SEC_GLOBAL);
     721             : 
     722           0 :   encodeULEB128(Globals.size(), getStream());
     723           0 :   for (const WasmGlobal &Global : Globals) {
     724           0 :     writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
     725           0 :     write8(Global.Type.Mutable);
     726             : 
     727           0 :     write8(wasm::WASM_OPCODE_I32_CONST);
     728           0 :     encodeSLEB128(Global.InitialValue, getStream());
     729           0 :     write8(wasm::WASM_OPCODE_END);
     730             :   }
     731             : 
     732           0 :   endSection(Section);
     733             : }
     734             : 
     735           0 : void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
     736           0 :   if (Exports.empty())
     737           0 :     return;
     738             : 
     739             :   SectionBookkeeping Section;
     740           0 :   startSection(Section, wasm::WASM_SEC_EXPORT);
     741             : 
     742           0 :   encodeULEB128(Exports.size(), getStream());
     743           0 :   for (const wasm::WasmExport &Export : Exports) {
     744           0 :     writeString(Export.Name);
     745           0 :     encodeSLEB128(Export.Kind, getStream());
     746           0 :     encodeULEB128(Export.Index, getStream());
     747             :   }
     748             : 
     749           0 :   endSection(Section);
     750             : }
     751             : 
     752           0 : void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
     753           0 :   if (TableElems.empty())
     754           0 :     return;
     755             : 
     756             :   SectionBookkeeping Section;
     757           0 :   startSection(Section, wasm::WASM_SEC_ELEM);
     758             : 
     759           0 :   encodeULEB128(1, getStream()); // number of "segments"
     760           0 :   encodeULEB128(0, getStream()); // the table index
     761             : 
     762             :   // init expr for starting offset
     763           0 :   write8(wasm::WASM_OPCODE_I32_CONST);
     764           0 :   encodeSLEB128(kInitialTableOffset, getStream());
     765           0 :   write8(wasm::WASM_OPCODE_END);
     766             : 
     767           0 :   encodeULEB128(TableElems.size(), getStream());
     768           0 :   for (uint32_t Elem : TableElems)
     769           0 :     encodeULEB128(Elem, getStream());
     770             : 
     771           0 :   endSection(Section);
     772             : }
     773             : 
     774           0 : void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
     775             :                                         const MCAsmLayout &Layout,
     776             :                                         ArrayRef<WasmFunction> Functions) {
     777           0 :   if (Functions.empty())
     778           0 :     return;
     779             : 
     780             :   SectionBookkeeping Section;
     781           0 :   startSection(Section, wasm::WASM_SEC_CODE);
     782             : 
     783           0 :   encodeULEB128(Functions.size(), getStream());
     784             : 
     785           0 :   for (const WasmFunction &Func : Functions) {
     786           0 :     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
     787             : 
     788           0 :     int64_t Size = 0;
     789           0 :     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
     790           0 :       report_fatal_error(".size expression must be evaluatable");
     791             : 
     792           0 :     encodeULEB128(Size, getStream());
     793           0 :     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
     794           0 :     Asm.writeSectionData(&FuncSection, Layout);
     795             :   }
     796             : 
     797             :   // Apply fixups.
     798           0 :   applyRelocations(CodeRelocations, Section.ContentsOffset);
     799             : 
     800           0 :   endSection(Section);
     801             : }
     802             : 
     803           0 : void WasmObjectWriter::writeDataSection() {
     804           0 :   if (DataSegments.empty())
     805           0 :     return;
     806             : 
     807             :   SectionBookkeeping Section;
     808           0 :   startSection(Section, wasm::WASM_SEC_DATA);
     809             : 
     810           0 :   encodeULEB128(DataSegments.size(), getStream()); // count
     811             : 
     812           0 :   for (const WasmDataSegment &Segment : DataSegments) {
     813           0 :     encodeULEB128(0, getStream()); // memory index
     814           0 :     write8(wasm::WASM_OPCODE_I32_CONST);
     815           0 :     encodeSLEB128(Segment.Offset, getStream()); // offset
     816           0 :     write8(wasm::WASM_OPCODE_END);
     817           0 :     encodeULEB128(Segment.Data.size(), getStream()); // size
     818           0 :     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
     819             :     writeBytes(Segment.Data); // data
     820             :   }
     821             : 
     822             :   // Apply fixups.
     823           0 :   applyRelocations(DataRelocations, Section.ContentsOffset);
     824             : 
     825           0 :   endSection(Section);
     826             : }
     827             : 
     828           0 : void WasmObjectWriter::writeCodeRelocSection() {
     829             :   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
     830             :   // for descriptions of the reloc sections.
     831             : 
     832           0 :   if (CodeRelocations.empty())
     833           0 :     return;
     834             : 
     835             :   SectionBookkeeping Section;
     836           0 :   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
     837             : 
     838           0 :   encodeULEB128(wasm::WASM_SEC_CODE, getStream());
     839           0 :   encodeULEB128(CodeRelocations.size(), getStream());
     840             : 
     841           0 :   writeRelocations(CodeRelocations);
     842             : 
     843           0 :   endSection(Section);
     844             : }
     845             : 
     846           0 : void WasmObjectWriter::writeDataRelocSection() {
     847             :   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
     848             :   // for descriptions of the reloc sections.
     849             : 
     850           0 :   if (DataRelocations.empty())
     851           0 :     return;
     852             : 
     853             :   SectionBookkeeping Section;
     854           0 :   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
     855             : 
     856           0 :   encodeULEB128(wasm::WASM_SEC_DATA, getStream());
     857           0 :   encodeULEB128(DataRelocations.size(), getStream());
     858             : 
     859           0 :   writeRelocations(DataRelocations);
     860             : 
     861           0 :   endSection(Section);
     862             : }
     863             : 
     864           0 : void WasmObjectWriter::writeLinkingMetaDataSection(
     865             :     uint32_t DataSize, ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
     866             :     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
     867             :     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
     868             :   SectionBookkeeping Section;
     869           0 :   startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
     870             :   SectionBookkeeping SubSection;
     871             : 
     872           0 :   if (SymbolInfos.size() != 0) {
     873           0 :     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
     874           0 :     encodeULEB128(SymbolInfos.size(), getStream());
     875           0 :     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
     876           0 :       encodeULEB128(Sym.Kind, getStream());
     877           0 :       encodeULEB128(Sym.Flags, getStream());
     878           0 :       switch (Sym.Kind) {
     879           0 :       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
     880             :       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
     881           0 :         encodeULEB128(Sym.ElementIndex, getStream());
     882           0 :         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
     883           0 :           writeString(Sym.Name);
     884             :         break;
     885           0 :       case wasm::WASM_SYMBOL_TYPE_DATA:
     886           0 :         writeString(Sym.Name);
     887           0 :         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
     888           0 :           encodeULEB128(Sym.DataRef.Segment, getStream());
     889           0 :           encodeULEB128(Sym.DataRef.Offset, getStream());
     890           0 :           encodeULEB128(Sym.DataRef.Size, getStream());
     891             :         }
     892             :         break;
     893           0 :       default:
     894           0 :         llvm_unreachable("unexpected kind");
     895             :       }
     896             :     }
     897           0 :     endSection(SubSection);
     898             :   }
     899             : 
     900           0 :   if (DataSize > 0) {
     901           0 :     startSection(SubSection, wasm::WASM_DATA_SIZE);
     902           0 :     encodeULEB128(DataSize, getStream());
     903           0 :     endSection(SubSection);
     904             :   }
     905             : 
     906           0 :   if (DataSegments.size()) {
     907           0 :     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
     908           0 :     encodeULEB128(DataSegments.size(), getStream());
     909           0 :     for (const WasmDataSegment &Segment : DataSegments) {
     910           0 :       writeString(Segment.Name);
     911           0 :       encodeULEB128(Segment.Alignment, getStream());
     912           0 :       encodeULEB128(Segment.Flags, getStream());
     913             :     }
     914           0 :     endSection(SubSection);
     915             :   }
     916             : 
     917           0 :   if (!InitFuncs.empty()) {
     918           0 :     startSection(SubSection, wasm::WASM_INIT_FUNCS);
     919           0 :     encodeULEB128(InitFuncs.size(), getStream());
     920           0 :     for (auto &StartFunc : InitFuncs) {
     921           0 :       encodeULEB128(StartFunc.first, getStream()); // priority
     922           0 :       encodeULEB128(StartFunc.second, getStream()); // function index
     923             :     }
     924           0 :     endSection(SubSection);
     925             :   }
     926             : 
     927           0 :   if (Comdats.size()) {
     928           0 :     startSection(SubSection, wasm::WASM_COMDAT_INFO);
     929           0 :     encodeULEB128(Comdats.size(), getStream());
     930           0 :     for (const auto &C : Comdats) {
     931           0 :       writeString(C.first);
     932           0 :       encodeULEB128(0, getStream()); // flags for future use
     933           0 :       encodeULEB128(C.second.size(), getStream());
     934           0 :       for (const WasmComdatEntry &Entry : C.second) {
     935           0 :         encodeULEB128(Entry.Kind, getStream());
     936           0 :         encodeULEB128(Entry.Index, getStream());
     937             :       }
     938             :     }
     939           0 :     endSection(SubSection);
     940             :   }
     941             : 
     942           0 :   endSection(Section);
     943           0 : }
     944             : 
     945             : uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
     946             :   assert(Symbol.isFunction());
     947             :   assert(TypeIndices.count(&Symbol));
     948           0 :   return TypeIndices[&Symbol];
     949             : }
     950             : 
     951           0 : uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
     952             :   assert(Symbol.isFunction());
     953             : 
     954           0 :   WasmFunctionType F;
     955             :   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
     956             :   F.Returns = ResolvedSym->getReturns();
     957             :   F.Params = ResolvedSym->getParams();
     958             : 
     959             :   auto Pair =
     960           0 :       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
     961           0 :   if (Pair.second)
     962           0 :     FunctionTypes.push_back(F);
     963           0 :   TypeIndices[&Symbol] = Pair.first->second;
     964             : 
     965             :   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
     966             :   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
     967           0 :   return Pair.first->second;
     968             : }
     969             : 
     970           0 : void WasmObjectWriter::writeObject(MCAssembler &Asm,
     971             :                                    const MCAsmLayout &Layout) {
     972             :   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
     973           0 :   MCContext &Ctx = Asm.getContext();
     974             : 
     975             :   // Collect information from the available symbols.
     976             :   SmallVector<WasmFunction, 4> Functions;
     977             :   SmallVector<uint32_t, 4> TableElems;
     978             :   SmallVector<wasm::WasmImport, 4> Imports;
     979             :   SmallVector<wasm::WasmExport, 4> Exports;
     980             :   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
     981             :   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
     982             :   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
     983           0 :   unsigned NumSymbols = 0;
     984             :   uint32_t DataSize = 0;
     985             : 
     986           0 :   auto AddSymbol = [&](const MCSymbolWasm &WS) {
     987             :     uint32_t Flags = 0;
     988           0 :     if (WS.isWeak())
     989             :       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
     990           0 :     if (WS.isHidden())
     991           0 :       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
     992           0 :     if (!WS.isExternal() && WS.isDefined())
     993           0 :       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
     994           0 :     if (WS.isUndefined())
     995           0 :       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
     996             : 
     997             :     wasm::WasmSymbolInfo Info;
     998           0 :     Info.Name = WS.getName();
     999           0 :     Info.Kind = WS.getType();
    1000           0 :     Info.Flags = Flags;
    1001           0 :     if (!WS.isData())
    1002           0 :       Info.ElementIndex = WasmIndices[&WS];
    1003           0 :     else if (WS.isDefined())
    1004           0 :       Info.DataRef = DataLocations[&WS];
    1005           0 :     SymbolInfos.emplace_back(Info);
    1006           0 :     SymbolIndices[&WS] = NumSymbols++;
    1007           0 :   };
    1008             : 
    1009             :   // For now, always emit the memory import, since loads and stores are not
    1010             :   // valid without it. In the future, we could perhaps be more clever and omit
    1011             :   // it if there are no loads or stores.
    1012             :   MCSymbolWasm *MemorySym =
    1013           0 :       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
    1014             :   wasm::WasmImport MemImport;
    1015           0 :   MemImport.Module = MemorySym->getModuleName();
    1016           0 :   MemImport.Field = MemorySym->getName();
    1017           0 :   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
    1018           0 :   Imports.push_back(MemImport);
    1019             : 
    1020             :   // For now, always emit the table section, since indirect calls are not
    1021             :   // valid without it. In the future, we could perhaps be more clever and omit
    1022             :   // it if there are no indirect calls.
    1023             :   MCSymbolWasm *TableSym =
    1024           0 :       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
    1025             :   wasm::WasmImport TableImport;
    1026           0 :   TableImport.Module = TableSym->getModuleName();
    1027           0 :   TableImport.Field = TableSym->getName();
    1028           0 :   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
    1029           0 :   TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
    1030           0 :   Imports.push_back(TableImport);
    1031             : 
    1032             :   // Populate FunctionTypeIndices and Imports.
    1033           0 :   for (const MCSymbol &S : Asm.symbols()) {
    1034             :     const auto &WS = static_cast<const MCSymbolWasm &>(S);
    1035             : 
    1036             :     // Register types for all functions, including those with private linkage
    1037             :     // (because wasm always needs a type signature).
    1038           0 :     if (WS.isFunction())
    1039           0 :       registerFunctionType(WS);
    1040             : 
    1041           0 :     if (WS.isTemporary())
    1042           0 :       continue;
    1043             : 
    1044             :     // If the symbol is not defined in this translation unit, import it.
    1045           0 :     if (!WS.isDefined() && !WS.isComdat()) {
    1046           0 :       if (WS.isFunction()) {
    1047             :         wasm::WasmImport Import;
    1048           0 :         Import.Module = WS.getModuleName();
    1049           0 :         Import.Field = WS.getName();
    1050           0 :         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
    1051           0 :         Import.SigIndex = getFunctionType(WS);
    1052           0 :         Imports.push_back(Import);
    1053           0 :         WasmIndices[&WS] = NumFunctionImports++;
    1054           0 :       } else if (WS.isGlobal()) {
    1055             :         wasm::WasmImport Import;
    1056           0 :         Import.Module = WS.getModuleName();
    1057           0 :         Import.Field = WS.getName();
    1058           0 :         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
    1059           0 :         Import.Global = WS.getGlobalType();
    1060           0 :         Imports.push_back(Import);
    1061           0 :         WasmIndices[&WS] = NumGlobalImports++;
    1062             :       }
    1063             : 
    1064             :       // TODO(ncw) We shouldn't be adding the symbol to the symbol table here!
    1065             :       // Instead it should be done by removing the "if (WS.isDefined())" block
    1066             :       // in the big loop below (line ~1284).  However - that would reorder all
    1067             :       // the symbols and thus require all the tests to be updated.  I think it's
    1068             :       // better to make that change therefore in a future commit, to isolate
    1069             :       // each test update from the change that caused it.
    1070           0 :       AddSymbol(WS);
    1071             :     }
    1072             :   }
    1073             : 
    1074           0 :   for (MCSection &Sec : Asm) {
    1075             :     auto &Section = static_cast<MCSectionWasm &>(Sec);
    1076           0 :     if (!Section.isWasmData())
    1077           0 :       continue;
    1078             : 
    1079             :     // .init_array sections are handled specially elsewhere.
    1080           0 :     if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
    1081           0 :       continue;
    1082             : 
    1083           0 :     uint32_t SegmentIndex = DataSegments.size();
    1084           0 :     DataSize = alignTo(DataSize, Section.getAlignment());
    1085           0 :     DataSegments.emplace_back();
    1086           0 :     WasmDataSegment &Segment = DataSegments.back();
    1087           0 :     Segment.Name = Section.getSectionName();
    1088           0 :     Segment.Offset = DataSize;
    1089           0 :     Segment.Section = &Section;
    1090           0 :     addData(Segment.Data, Section);
    1091           0 :     Segment.Alignment = Section.getAlignment();
    1092           0 :     Segment.Flags = 0;
    1093           0 :     DataSize += Segment.Data.size();
    1094             :     Section.setSegmentIndex(SegmentIndex);
    1095             : 
    1096           0 :     if (const MCSymbolWasm *C = Section.getGroup()) {
    1097           0 :       Comdats[C->getName()].emplace_back(
    1098           0 :           WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
    1099             :     }
    1100             :   }
    1101             : 
    1102             :   // Handle regular defined and undefined symbols.
    1103           0 :   for (const MCSymbol &S : Asm.symbols()) {
    1104             :     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
    1105             :     // or used in relocations.
    1106           0 :     if (S.isTemporary() && S.getName().empty())
    1107           0 :       continue;
    1108             : 
    1109             :     const auto &WS = static_cast<const MCSymbolWasm &>(S);
    1110             :     DEBUG(dbgs() << "MCSymbol: '" << S << "'"
    1111             :                  << " isDefined=" << S.isDefined()
    1112             :                  << " isExternal=" << S.isExternal()
    1113             :                  << " isTemporary=" << S.isTemporary()
    1114             :                  << " isFunction=" << WS.isFunction()
    1115             :                  << " isWeak=" << WS.isWeak()
    1116             :                  << " isHidden=" << WS.isHidden()
    1117             :                  << " isVariable=" << WS.isVariable() << "\n");
    1118             : 
    1119           0 :     if (WS.isVariable())
    1120           0 :       continue;
    1121           0 :     if (WS.isComdat() && !WS.isDefined())
    1122           0 :       continue;
    1123             : 
    1124           0 :     if (WS.isFunction()) {
    1125             :       unsigned Index;
    1126           0 :       if (WS.isDefined()) {
    1127           0 :         if (WS.getOffset() != 0)
    1128           0 :           report_fatal_error(
    1129             :               "function sections must contain one function each");
    1130             : 
    1131           0 :         if (WS.getSize() == 0)
    1132           0 :           report_fatal_error(
    1133             :               "function symbols must have a size set with .size");
    1134             : 
    1135             :         // A definition. Write out the function body.
    1136           0 :         Index = NumFunctionImports + Functions.size();
    1137             :         WasmFunction Func;
    1138           0 :         Func.Type = getFunctionType(WS);
    1139           0 :         Func.Sym = &WS;
    1140           0 :         WasmIndices[&WS] = Index;
    1141           0 :         Functions.push_back(Func);
    1142             : 
    1143             :         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
    1144           0 :         if (const MCSymbolWasm *C = Section.getGroup()) {
    1145           0 :           Comdats[C->getName()].emplace_back(
    1146           0 :               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
    1147             :         }
    1148             :       } else {
    1149             :         // An import; the index was assigned above.
    1150           0 :         Index = WasmIndices.find(&WS)->second;
    1151             :       }
    1152             : 
    1153             :       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
    1154           0 :     } else if (WS.isData()) {
    1155           0 :       if (WS.isTemporary() && !WS.getSize())
    1156           0 :         continue;
    1157             : 
    1158           0 :       if (!WS.isDefined()) {
    1159             :         DEBUG(dbgs() << "  -> segment index: -1");
    1160           0 :         continue;
    1161             :       }
    1162             : 
    1163           0 :       if (!WS.getSize())
    1164           0 :         report_fatal_error("data symbols must have a size set with .size: " +
    1165           0 :                            WS.getName());
    1166             : 
    1167           0 :       int64_t Size = 0;
    1168           0 :       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
    1169           0 :         report_fatal_error(".size expression must be evaluatable");
    1170             : 
    1171             :       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
    1172             :       assert(DataSection.isWasmData());
    1173             : 
    1174             :       // For each data symbol, export it in the symtab as a reference to the
    1175             :       // corresponding Wasm data segment.
    1176             :       wasm::WasmDataReference Ref = wasm::WasmDataReference{
    1177           0 :           DataSection.getSegmentIndex(),
    1178           0 :           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
    1179           0 :           static_cast<uint32_t>(Size)};
    1180           0 :       DataLocations[&WS] = Ref;
    1181             :       DEBUG(dbgs() << "  -> segment index: " << Ref.Segment);
    1182             :     } else {
    1183             :       // A "true" Wasm global (currently just __stack_pointer)
    1184             :       unsigned WasmIndex;
    1185           0 :       if (WS.isDefined()) {
    1186           0 :         report_fatal_error("don't yet support defined globals");
    1187             :       } else {
    1188             :         // An import; the index was assigned above
    1189           0 :         WasmIndex = WasmIndices.find(&WS)->second;
    1190             :       }
    1191             : 
    1192             :       DEBUG(dbgs() << "  -> global index: " << WasmIndex << "\n");
    1193             :     }
    1194             : 
    1195           0 :     if (WS.isDefined())
    1196           0 :       AddSymbol(WS);
    1197             :   }
    1198             : 
    1199             :   // Handle weak aliases. We need to process these in a separate pass because
    1200             :   // we need to have processed the target of the alias before the alias itself
    1201             :   // and the symbols are not necessarily ordered in this way.
    1202           0 :   for (const MCSymbol &S : Asm.symbols()) {
    1203           0 :     if (!S.isVariable())
    1204           0 :       continue;
    1205             : 
    1206             :     assert(S.isDefined());
    1207             : 
    1208             :     // Find the target symbol of this weak alias and export that index
    1209             :     const auto &WS = static_cast<const MCSymbolWasm &>(S);
    1210             :     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
    1211             :     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
    1212             : 
    1213           0 :     if (WS.isFunction()) {
    1214             :       assert(WasmIndices.count(ResolvedSym) > 0);
    1215           0 :       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
    1216           0 :       WasmIndices[&WS] = WasmIndex;
    1217             :       DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
    1218           0 :     } else if (WS.isData()) {
    1219             :       assert(DataLocations.count(ResolvedSym) > 0);
    1220             :       const wasm::WasmDataReference &Ref =
    1221           0 :           DataLocations.find(ResolvedSym)->second;
    1222           0 :       DataLocations[&WS] = Ref;
    1223             :       DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
    1224             :     } else {
    1225           0 :       report_fatal_error("don't yet support global aliases");
    1226             :     }
    1227             : 
    1228           0 :     AddSymbol(WS);
    1229             :   }
    1230             : 
    1231             :   {
    1232           0 :     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
    1233             :       // Functions referenced by a relocation need to put in the table.  This is
    1234             :       // purely to make the object file's provisional values readable, and is
    1235             :       // ignored by the linker, which re-calculates the relocations itself.
    1236           0 :       if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
    1237             :           Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
    1238           0 :         return;
    1239             :       assert(Rel.Symbol->isFunction());
    1240           0 :       const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
    1241           0 :       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
    1242           0 :       uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
    1243           0 :       if (TableIndices.try_emplace(&WS, TableIndex).second) {
    1244             :         DEBUG(dbgs() << "  -> adding " << WS.getName()
    1245             :                      << " to table: " << TableIndex << "\n");
    1246           0 :         TableElems.push_back(FunctionIndex);
    1247           0 :         registerFunctionType(WS);
    1248             :       }
    1249           0 :     };
    1250             : 
    1251           0 :     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
    1252           0 :       HandleReloc(RelEntry);
    1253           0 :     for (const WasmRelocationEntry &RelEntry : DataRelocations)
    1254           0 :       HandleReloc(RelEntry);
    1255             :   }
    1256             : 
    1257             :   // Translate .init_array section contents into start functions.
    1258           0 :   for (const MCSection &S : Asm) {
    1259             :     const auto &WS = static_cast<const MCSectionWasm &>(S);
    1260             :     if (WS.getSectionName().startswith(".fini_array"))
    1261           0 :       report_fatal_error(".fini_array sections are unsupported");
    1262           0 :     if (!WS.getSectionName().startswith(".init_array"))
    1263           0 :       continue;
    1264           0 :     if (WS.getFragmentList().empty())
    1265           0 :       continue;
    1266           0 :     if (WS.getFragmentList().size() != 2)
    1267           0 :       report_fatal_error("only one .init_array section fragment supported");
    1268             :     const MCFragment &AlignFrag = *WS.begin();
    1269           0 :     if (AlignFrag.getKind() != MCFragment::FT_Align)
    1270           0 :       report_fatal_error(".init_array section should be aligned");
    1271           0 :     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
    1272           0 :       report_fatal_error(".init_array section should be aligned for pointers");
    1273             :     const MCFragment &Frag = *std::next(WS.begin());
    1274           0 :     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
    1275           0 :       report_fatal_error("only data supported in .init_array section");
    1276             :     uint16_t Priority = UINT16_MAX;
    1277           0 :     if (WS.getSectionName().size() != 11) {
    1278           0 :       if (WS.getSectionName()[11] != '.')
    1279           0 :         report_fatal_error(".init_array section priority should start with '.'");
    1280           0 :       if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
    1281           0 :         report_fatal_error("invalid .init_array section priority");
    1282             :     }
    1283             :     const auto &DataFrag = cast<MCDataFragment>(Frag);
    1284             :     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
    1285           0 :     for (const uint8_t *p = (const uint8_t *)Contents.data(),
    1286             :                      *end = (const uint8_t *)Contents.data() + Contents.size();
    1287           0 :          p != end; ++p) {
    1288           0 :       if (*p != 0)
    1289           0 :         report_fatal_error("non-symbolic data in .init_array section");
    1290             :     }
    1291           0 :     for (const MCFixup &Fixup : DataFrag.getFixups()) {
    1292             :       assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
    1293           0 :       const MCExpr *Expr = Fixup.getValue();
    1294             :       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
    1295             :       if (!Sym)
    1296           0 :         report_fatal_error("fixups in .init_array should be symbol references");
    1297           0 :       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
    1298           0 :         report_fatal_error("symbols in .init_array should be for functions");
    1299           0 :       auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
    1300           0 :       if (I == SymbolIndices.end())
    1301           0 :         report_fatal_error("symbols in .init_array should be defined");
    1302           0 :       uint32_t Index = I->second;
    1303           0 :       InitFuncs.push_back(std::make_pair(Priority, Index));
    1304             :     }
    1305             :   }
    1306             : 
    1307             :   // Write out the Wasm header.
    1308           0 :   writeHeader(Asm);
    1309             : 
    1310           0 :   writeTypeSection(FunctionTypes);
    1311           0 :   writeImportSection(Imports, DataSize, TableElems.size());
    1312           0 :   writeFunctionSection(Functions);
    1313             :   // Skip the "table" section; we import the table instead.
    1314             :   // Skip the "memory" section; we import the memory instead.
    1315           0 :   writeGlobalSection();
    1316           0 :   writeExportSection(Exports);
    1317           0 :   writeElemSection(TableElems);
    1318           0 :   writeCodeSection(Asm, Layout, Functions);
    1319           0 :   writeDataSection();
    1320           0 :   writeCodeRelocSection();
    1321           0 :   writeDataRelocSection();
    1322           0 :   writeLinkingMetaDataSection(DataSize, SymbolInfos, InitFuncs, Comdats);
    1323             : 
    1324             :   // TODO: Translate the .comment section to the output.
    1325             :   // TODO: Translate debug sections to the output.
    1326           0 : }
    1327             : 
    1328             : std::unique_ptr<MCObjectWriter>
    1329           0 : llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
    1330             :                              raw_pwrite_stream &OS) {
    1331           0 :   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
    1332             : }

Generated by: LCOV version 1.13