1 //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements Wasm object file writer information.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/BinaryFormat/Wasm.h"
16 #include "llvm/Config/llvm-config.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/EndianStream.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/LEB128.h"
33 #include "llvm/Support/StringSaver.h"
34 #include <vector>
35 
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "mc"
39 
40 namespace {
41 
42 // Went we ceate the indirect function table we start at 1, so that there is
43 // and emtpy slot at 0 and therefore calling a null function pointer will trap.
44 static const uint32_t InitialTableOffset = 1;
45 
46 // For patching purposes, we need to remember where each section starts, both
47 // for patching up the section size field, and for patching up references to
48 // locations within the section.
49 struct SectionBookkeeping {
50   // Where the size of the section is written.
51   uint64_t SizeOffset;
52   // Where the section header ends (without custom section name).
53   uint64_t PayloadOffset;
54   // Where the contents of the section starts.
55   uint64_t ContentsOffset;
56   uint32_t Index;
57 };
58 
59 // The signature of a wasm function or event, in a struct capable of being used
60 // as a DenseMap key.
61 // TODO: Consider using wasm::WasmSignature directly instead.
62 struct WasmSignature {
63   // Support empty and tombstone instances, needed by DenseMap.
64   enum { Plain, Empty, Tombstone } State = Plain;
65 
66   // The return types of the function.
67   SmallVector<wasm::ValType, 1> Returns;
68 
69   // The parameter types of the function.
70   SmallVector<wasm::ValType, 4> Params;
71 
72   bool operator==(const WasmSignature &Other) const {
73     return State == Other.State && Returns == Other.Returns &&
74            Params == Other.Params;
75   }
76 };
77 
78 // Traits for using WasmSignature in a DenseMap.
79 struct WasmSignatureDenseMapInfo {
80   static WasmSignature getEmptyKey() {
81     WasmSignature Sig;
82     Sig.State = WasmSignature::Empty;
83     return Sig;
84   }
85   static WasmSignature getTombstoneKey() {
86     WasmSignature Sig;
87     Sig.State = WasmSignature::Tombstone;
88     return Sig;
89   }
90   static unsigned getHashValue(const WasmSignature &Sig) {
91     uintptr_t Value = Sig.State;
92     for (wasm::ValType Ret : Sig.Returns)
93       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
94     for (wasm::ValType Param : Sig.Params)
95       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
96     return Value;
97   }
98   static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
99     return LHS == RHS;
100   }
101 };
102 
103 // A wasm data segment.  A wasm binary contains only a single data section
104 // but that can contain many segments, each with their own virtual location
105 // in memory.  Each MCSection data created by llvm is modeled as its own
106 // wasm data segment.
107 struct WasmDataSegment {
108   MCSectionWasm *Section;
109   StringRef Name;
110   uint32_t InitFlags;
111   uint32_t Offset;
112   uint32_t Alignment;
113   uint32_t LinkerFlags;
114   SmallVector<char, 4> Data;
115 };
116 
117 // A wasm function to be written into the function section.
118 struct WasmFunction {
119   uint32_t SigIndex;
120   const MCSymbolWasm *Sym;
121 };
122 
123 // A wasm global to be written into the global section.
124 struct WasmGlobal {
125   wasm::WasmGlobalType Type;
126   uint64_t InitialValue;
127 };
128 
129 // Information about a single item which is part of a COMDAT.  For each data
130 // segment or function which is in the COMDAT, there is a corresponding
131 // WasmComdatEntry.
132 struct WasmComdatEntry {
133   unsigned Kind;
134   uint32_t Index;
135 };
136 
137 // Information about a single relocation.
138 struct WasmRelocationEntry {
139   uint64_t Offset;                   // Where is the relocation.
140   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
141   int64_t Addend;                    // A value to add to the symbol.
142   unsigned Type;                     // The type of the relocation.
143   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
144 
145   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
146                       int64_t Addend, unsigned Type,
147                       const MCSectionWasm *FixupSection)
148       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
149         FixupSection(FixupSection) {}
150 
151   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
152 
153   void print(raw_ostream &Out) const {
154     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
155         << ", Sym=" << *Symbol << ", Addend=" << Addend
156         << ", FixupSection=" << FixupSection->getName();
157   }
158 
159 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
161 #endif
162 };
163 
164 static const uint32_t InvalidIndex = -1;
165 
166 struct WasmCustomSection {
167 
168   StringRef Name;
169   MCSectionWasm *Section;
170 
171   uint32_t OutputContentsOffset;
172   uint32_t OutputIndex;
173 
174   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
175       : Name(Name), Section(Section), OutputContentsOffset(0),
176         OutputIndex(InvalidIndex) {}
177 };
178 
179 #if !defined(NDEBUG)
180 raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
181   Rel.print(OS);
182   return OS;
183 }
184 #endif
185 
186 // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
187 // to allow patching.
188 template <int W>
189 void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
190   uint8_t Buffer[W];
191   unsigned SizeLen = encodeULEB128(X, Buffer, W);
192   assert(SizeLen == W);
193   Stream.pwrite((char *)Buffer, SizeLen, Offset);
194 }
195 
196 // Write X as an signed LEB value at offset Offset in Stream, padded
197 // to allow patching.
198 template <int W>
199 void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) {
200   uint8_t Buffer[W];
201   unsigned SizeLen = encodeSLEB128(X, Buffer, W);
202   assert(SizeLen == W);
203   Stream.pwrite((char *)Buffer, SizeLen, Offset);
204 }
205 
206 // Write X as a plain integer value at offset Offset in Stream.
207 static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
208   uint8_t Buffer[4];
209   support::endian::write32le(Buffer, X);
210   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
211 }
212 
213 static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
214   uint8_t Buffer[8];
215   support::endian::write64le(Buffer, X);
216   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
217 }
218 
219 class WasmObjectWriter : public MCObjectWriter {
220   support::endian::Writer W;
221 
222   /// The target specific Wasm writer instance.
223   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
224 
225   // Relocations for fixing up references in the code section.
226   std::vector<WasmRelocationEntry> CodeRelocations;
227   uint32_t CodeSectionIndex;
228 
229   // Relocations for fixing up references in the data section.
230   std::vector<WasmRelocationEntry> DataRelocations;
231   uint32_t DataSectionIndex;
232 
233   // Index values to use for fixing up call_indirect type indices.
234   // Maps function symbols to the index of the type of the function
235   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
236   // Maps function symbols to the table element index space. Used
237   // for TABLE_INDEX relocation types (i.e. address taken functions).
238   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
239   // Maps function/global symbols to the function/global/event/section index
240   // space.
241   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
242   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
243   // Maps data symbols to the Wasm segment and offset/size with the segment.
244   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
245 
246   // Stores output data (index, relocations, content offset) for custom
247   // section.
248   std::vector<WasmCustomSection> CustomSections;
249   std::unique_ptr<WasmCustomSection> ProducersSection;
250   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
251   // Relocations for fixing up references in the custom sections.
252   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
253       CustomSectionsRelocations;
254 
255   // Map from section to defining function symbol.
256   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
257 
258   DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
259   SmallVector<WasmSignature, 4> Signatures;
260   SmallVector<WasmDataSegment, 4> DataSegments;
261   unsigned NumFunctionImports = 0;
262   unsigned NumGlobalImports = 0;
263   unsigned NumEventImports = 0;
264   uint32_t SectionCount = 0;
265 
266   // TargetObjectWriter wrappers.
267   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
268   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
269 
270   void startSection(SectionBookkeeping &Section, unsigned SectionId);
271   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
272   void endSection(SectionBookkeeping &Section);
273 
274 public:
275   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
276                    raw_pwrite_stream &OS)
277       : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
278 
279 private:
280   void reset() override {
281     CodeRelocations.clear();
282     DataRelocations.clear();
283     TypeIndices.clear();
284     WasmIndices.clear();
285     GOTIndices.clear();
286     TableIndices.clear();
287     DataLocations.clear();
288     CustomSections.clear();
289     ProducersSection.reset();
290     TargetFeaturesSection.reset();
291     CustomSectionsRelocations.clear();
292     SignatureIndices.clear();
293     Signatures.clear();
294     DataSegments.clear();
295     SectionFunctions.clear();
296     NumFunctionImports = 0;
297     NumGlobalImports = 0;
298     MCObjectWriter::reset();
299   }
300 
301   void writeHeader(const MCAssembler &Asm);
302 
303   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
304                         const MCFragment *Fragment, const MCFixup &Fixup,
305                         MCValue Target, uint64_t &FixedValue) override;
306 
307   void executePostLayoutBinding(MCAssembler &Asm,
308                                 const MCAsmLayout &Layout) override;
309 
310   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
311 
312   void writeString(const StringRef Str) {
313     encodeULEB128(Str.size(), W.OS);
314     W.OS << Str;
315   }
316 
317   void writeI32(int32_t val) {
318     char Buffer[4];
319     support::endian::write32le(Buffer, val);
320     W.OS.write(Buffer, sizeof(Buffer));
321   }
322 
323   void writeI64(int64_t val) {
324     char Buffer[8];
325     support::endian::write64le(Buffer, val);
326     W.OS.write(Buffer, sizeof(Buffer));
327   }
328 
329   void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
330 
331   void writeTypeSection(ArrayRef<WasmSignature> Signatures);
332   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
333                           uint32_t NumElements);
334   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
335   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
336   void writeElemSection(ArrayRef<uint32_t> TableElems);
337   void writeDataCountSection();
338   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
339                         ArrayRef<WasmFunction> Functions);
340   void writeDataSection();
341   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
342   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
343   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
344                          std::vector<WasmRelocationEntry> &Relocations);
345   void writeLinkingMetaDataSection(
346       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
347       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
348       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
349   void writeCustomSection(WasmCustomSection &CustomSection,
350                           const MCAssembler &Asm, const MCAsmLayout &Layout);
351   void writeCustomRelocSections();
352   void
353   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
354                                  const MCAsmLayout &Layout);
355 
356   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
357   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
358                         uint64_t ContentsOffset);
359 
360   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
361   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
362   uint32_t getEventType(const MCSymbolWasm &Symbol);
363   void registerFunctionType(const MCSymbolWasm &Symbol);
364   void registerEventType(const MCSymbolWasm &Symbol);
365 };
366 
367 } // end anonymous namespace
368 
369 // Write out a section header and a patchable section size field.
370 void WasmObjectWriter::startSection(SectionBookkeeping &Section,
371                                     unsigned SectionId) {
372   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
373   W.OS << char(SectionId);
374 
375   Section.SizeOffset = W.OS.tell();
376 
377   // The section size. We don't know the size yet, so reserve enough space
378   // for any 32-bit value; we'll patch it later.
379   encodeULEB128(0, W.OS, 5);
380 
381   // The position where the section starts, for measuring its size.
382   Section.ContentsOffset = W.OS.tell();
383   Section.PayloadOffset = W.OS.tell();
384   Section.Index = SectionCount++;
385 }
386 
387 void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
388                                           StringRef Name) {
389   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
390   startSection(Section, wasm::WASM_SEC_CUSTOM);
391 
392   // The position where the section header ends, for measuring its size.
393   Section.PayloadOffset = W.OS.tell();
394 
395   // Custom sections in wasm also have a string identifier.
396   writeString(Name);
397 
398   // The position where the custom section starts.
399   Section.ContentsOffset = W.OS.tell();
400 }
401 
402 // Now that the section is complete and we know how big it is, patch up the
403 // section size field at the start of the section.
404 void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
405   uint64_t Size = W.OS.tell();
406   // /dev/null doesn't support seek/tell and can report offset of 0.
407   // Simply skip this patching in that case.
408   if (!Size)
409     return;
410 
411   Size -= Section.PayloadOffset;
412   if (uint32_t(Size) != Size)
413     report_fatal_error("section size does not fit in a uint32_t");
414 
415   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
416 
417   // Write the final section size to the payload_len field, which follows
418   // the section id byte.
419   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W.OS), Size,
420                        Section.SizeOffset);
421 }
422 
423 // Emit the Wasm header.
424 void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
425   W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
426   W.write<uint32_t>(wasm::WasmVersion);
427 }
428 
429 void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
430                                                 const MCAsmLayout &Layout) {
431   // Build a map of sections to the function that defines them, for use
432   // in recordRelocation.
433   for (const MCSymbol &S : Asm.symbols()) {
434     const auto &WS = static_cast<const MCSymbolWasm &>(S);
435     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
436       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
437       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
438       if (!Pair.second)
439         report_fatal_error("section already has a defining function: " +
440                            Sec.getName());
441     }
442   }
443 }
444 
445 void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
446                                         const MCAsmLayout &Layout,
447                                         const MCFragment *Fragment,
448                                         const MCFixup &Fixup, MCValue Target,
449                                         uint64_t &FixedValue) {
450   // The WebAssembly backend should never generate FKF_IsPCRel fixups
451   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
452            MCFixupKindInfo::FKF_IsPCRel));
453 
454   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
455   uint64_t C = Target.getConstant();
456   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
457   MCContext &Ctx = Asm.getContext();
458 
459   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
460     // To get here the A - B expression must have failed evaluateAsRelocatable.
461     // This means either A or B must be undefined and in WebAssembly we can't
462     // support either of those cases.
463     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
464     Ctx.reportError(
465         Fixup.getLoc(),
466         Twine("symbol '") + SymB.getName() +
467             "': unsupported subtraction expression used in relocation.");
468     return;
469   }
470 
471   // We either rejected the fixup or folded B into C at this point.
472   const MCSymbolRefExpr *RefA = Target.getSymA();
473   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
474 
475   // The .init_array isn't translated as data, so don't do relocations in it.
476   if (FixupSection.getName().startswith(".init_array")) {
477     SymA->setUsedInInitArray();
478     return;
479   }
480 
481   if (SymA->isVariable()) {
482     const MCExpr *Expr = SymA->getVariableValue();
483     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
484     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
485       llvm_unreachable("weakref used in reloc not yet implemented");
486   }
487 
488   // Put any constant offset in an addend. Offsets can be negative, and
489   // LLVM expects wrapping, in contrast to wasm's immediates which can't
490   // be negative and don't wrap.
491   FixedValue = 0;
492 
493   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
494 
495   // Absolute offset within a section or a function.
496   // Currently only supported for for metadata sections.
497   // See: test/MC/WebAssembly/blockaddress.ll
498   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
499       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
500     if (!FixupSection.getKind().isMetadata())
501       report_fatal_error("relocations for function or section offsets are "
502                          "only supported in metadata sections");
503 
504     const MCSymbol *SectionSymbol = nullptr;
505     const MCSection &SecA = SymA->getSection();
506     if (SecA.getKind().isText())
507       SectionSymbol = SectionFunctions.find(&SecA)->second;
508     else
509       SectionSymbol = SecA.getBeginSymbol();
510     if (!SectionSymbol)
511       report_fatal_error("section symbol is required for relocation");
512 
513     C += Layout.getSymbolOffset(*SymA);
514     SymA = cast<MCSymbolWasm>(SectionSymbol);
515   }
516 
517   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
518   // against a named symbol.
519   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
520     if (SymA->getName().empty())
521       report_fatal_error("relocations against un-named temporaries are not yet "
522                          "supported by wasm");
523 
524     SymA->setUsedInReloc();
525   }
526 
527   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
528     SymA->setUsedInGOT();
529 
530   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
531   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
532 
533   if (FixupSection.isWasmData()) {
534     DataRelocations.push_back(Rec);
535   } else if (FixupSection.getKind().isText()) {
536     CodeRelocations.push_back(Rec);
537   } else if (FixupSection.getKind().isMetadata()) {
538     CustomSectionsRelocations[&FixupSection].push_back(Rec);
539   } else {
540     llvm_unreachable("unexpected section type");
541   }
542 }
543 
544 static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
545   const MCSymbolWasm* Ret = &Symbol;
546   while (Ret->isVariable()) {
547     const MCExpr *Expr = Ret->getVariableValue();
548     auto *Inner = cast<MCSymbolRefExpr>(Expr);
549     Ret = cast<MCSymbolWasm>(&Inner->getSymbol());
550   }
551   return Ret;
552 }
553 
554 // Compute a value to write into the code at the location covered
555 // by RelEntry. This value isn't used by the static linker; it just serves
556 // to make the object format more readable and more likely to be directly
557 // useable.
558 uint64_t
559 WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
560   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
561        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
562       !RelEntry.Symbol->isGlobal()) {
563     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
564     return GOTIndices[RelEntry.Symbol];
565   }
566 
567   switch (RelEntry.Type) {
568   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
569   case wasm::R_WASM_TABLE_INDEX_SLEB:
570   case wasm::R_WASM_TABLE_INDEX_I32: {
571     // Provisional value is table address of the resolved symbol itself
572     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
573     assert(Sym->isFunction());
574     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
575       return TableIndices[Sym] - InitialTableOffset;
576     else
577       return TableIndices[Sym];
578   }
579   case wasm::R_WASM_TYPE_INDEX_LEB:
580     // Provisional value is same as the index
581     return getRelocationIndexValue(RelEntry);
582   case wasm::R_WASM_FUNCTION_INDEX_LEB:
583   case wasm::R_WASM_GLOBAL_INDEX_LEB:
584   case wasm::R_WASM_GLOBAL_INDEX_I32:
585   case wasm::R_WASM_EVENT_INDEX_LEB:
586     // Provisional value is function/global/event Wasm index
587     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
588     return WasmIndices[RelEntry.Symbol];
589   case wasm::R_WASM_FUNCTION_OFFSET_I32:
590   case wasm::R_WASM_SECTION_OFFSET_I32: {
591     const auto &Section =
592         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
593     return Section.getSectionOffset() + RelEntry.Addend;
594   }
595   case wasm::R_WASM_MEMORY_ADDR_LEB:
596   case wasm::R_WASM_MEMORY_ADDR_LEB64:
597   case wasm::R_WASM_MEMORY_ADDR_SLEB:
598   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
599   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
600   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
601   case wasm::R_WASM_MEMORY_ADDR_I32:
602   case wasm::R_WASM_MEMORY_ADDR_I64: {
603     // Provisional value is address of the global
604     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
605     // For undefined symbols, use zero
606     if (!Sym->isDefined())
607       return 0;
608     const wasm::WasmDataReference &Ref = DataLocations[Sym];
609     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
610     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
611     return Segment.Offset + Ref.Offset + RelEntry.Addend;
612   }
613   default:
614     llvm_unreachable("invalid relocation type");
615   }
616 }
617 
618 static void addData(SmallVectorImpl<char> &DataBytes,
619                     MCSectionWasm &DataSection) {
620   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
621 
622   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
623 
624   for (const MCFragment &Frag : DataSection) {
625     if (Frag.hasInstructions())
626       report_fatal_error("only data supported in data sections");
627 
628     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
629       if (Align->getValueSize() != 1)
630         report_fatal_error("only byte values supported for alignment");
631       // If nops are requested, use zeros, as this is the data section.
632       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
633       uint64_t Size =
634           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
635                              DataBytes.size() + Align->getMaxBytesToEmit());
636       DataBytes.resize(Size, Value);
637     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
638       int64_t NumValues;
639       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
640         llvm_unreachable("The fill should be an assembler constant");
641       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
642                        Fill->getValue());
643     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
644       const SmallVectorImpl<char> &Contents = LEB->getContents();
645       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
646     } else {
647       const auto &DataFrag = cast<MCDataFragment>(Frag);
648       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
649       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
650     }
651   }
652 
653   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
654 }
655 
656 uint32_t
657 WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
658   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
659     if (!TypeIndices.count(RelEntry.Symbol))
660       report_fatal_error("symbol not found in type index space: " +
661                          RelEntry.Symbol->getName());
662     return TypeIndices[RelEntry.Symbol];
663   }
664 
665   return RelEntry.Symbol->getIndex();
666 }
667 
668 // Apply the portions of the relocation records that we can handle ourselves
669 // directly.
670 void WasmObjectWriter::applyRelocations(
671     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
672   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
673   for (const WasmRelocationEntry &RelEntry : Relocations) {
674     uint64_t Offset = ContentsOffset +
675                       RelEntry.FixupSection->getSectionOffset() +
676                       RelEntry.Offset;
677 
678     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
679     auto Value = getProvisionalValue(RelEntry);
680 
681     switch (RelEntry.Type) {
682     case wasm::R_WASM_FUNCTION_INDEX_LEB:
683     case wasm::R_WASM_TYPE_INDEX_LEB:
684     case wasm::R_WASM_GLOBAL_INDEX_LEB:
685     case wasm::R_WASM_MEMORY_ADDR_LEB:
686     case wasm::R_WASM_EVENT_INDEX_LEB:
687       writePatchableLEB<5>(Stream, Value, Offset);
688       break;
689     case wasm::R_WASM_MEMORY_ADDR_LEB64:
690       writePatchableLEB<10>(Stream, Value, Offset);
691       break;
692     case wasm::R_WASM_TABLE_INDEX_I32:
693     case wasm::R_WASM_MEMORY_ADDR_I32:
694     case wasm::R_WASM_FUNCTION_OFFSET_I32:
695     case wasm::R_WASM_SECTION_OFFSET_I32:
696     case wasm::R_WASM_GLOBAL_INDEX_I32:
697       patchI32(Stream, Value, Offset);
698       break;
699     case wasm::R_WASM_MEMORY_ADDR_I64:
700       patchI64(Stream, Value, Offset);
701       break;
702     case wasm::R_WASM_TABLE_INDEX_SLEB:
703     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
704     case wasm::R_WASM_MEMORY_ADDR_SLEB:
705     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
706       writePatchableSLEB<5>(Stream, Value, Offset);
707       break;
708     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
709     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
710       writePatchableSLEB<10>(Stream, Value, Offset);
711       break;
712     default:
713       llvm_unreachable("invalid relocation type");
714     }
715   }
716 }
717 
718 void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
719   if (Signatures.empty())
720     return;
721 
722   SectionBookkeeping Section;
723   startSection(Section, wasm::WASM_SEC_TYPE);
724 
725   encodeULEB128(Signatures.size(), W.OS);
726 
727   for (const WasmSignature &Sig : Signatures) {
728     W.OS << char(wasm::WASM_TYPE_FUNC);
729     encodeULEB128(Sig.Params.size(), W.OS);
730     for (wasm::ValType Ty : Sig.Params)
731       writeValueType(Ty);
732     encodeULEB128(Sig.Returns.size(), W.OS);
733     for (wasm::ValType Ty : Sig.Returns)
734       writeValueType(Ty);
735   }
736 
737   endSection(Section);
738 }
739 
740 void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
741                                           uint32_t DataSize,
742                                           uint32_t NumElements) {
743   if (Imports.empty())
744     return;
745 
746   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
747 
748   SectionBookkeeping Section;
749   startSection(Section, wasm::WASM_SEC_IMPORT);
750 
751   encodeULEB128(Imports.size(), W.OS);
752   for (const wasm::WasmImport &Import : Imports) {
753     writeString(Import.Module);
754     writeString(Import.Field);
755     W.OS << char(Import.Kind);
756 
757     switch (Import.Kind) {
758     case wasm::WASM_EXTERNAL_FUNCTION:
759       encodeULEB128(Import.SigIndex, W.OS);
760       break;
761     case wasm::WASM_EXTERNAL_GLOBAL:
762       W.OS << char(Import.Global.Type);
763       W.OS << char(Import.Global.Mutable ? 1 : 0);
764       break;
765     case wasm::WASM_EXTERNAL_MEMORY:
766       encodeULEB128(0, W.OS);        // flags
767       encodeULEB128(NumPages, W.OS); // initial
768       break;
769     case wasm::WASM_EXTERNAL_TABLE:
770       W.OS << char(Import.Table.ElemType);
771       encodeULEB128(0, W.OS);           // flags
772       encodeULEB128(NumElements, W.OS); // initial
773       break;
774     case wasm::WASM_EXTERNAL_EVENT:
775       encodeULEB128(Import.Event.Attribute, W.OS);
776       encodeULEB128(Import.Event.SigIndex, W.OS);
777       break;
778     default:
779       llvm_unreachable("unsupported import kind");
780     }
781   }
782 
783   endSection(Section);
784 }
785 
786 void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
787   if (Functions.empty())
788     return;
789 
790   SectionBookkeeping Section;
791   startSection(Section, wasm::WASM_SEC_FUNCTION);
792 
793   encodeULEB128(Functions.size(), W.OS);
794   for (const WasmFunction &Func : Functions)
795     encodeULEB128(Func.SigIndex, W.OS);
796 
797   endSection(Section);
798 }
799 
800 void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
801   if (Events.empty())
802     return;
803 
804   SectionBookkeeping Section;
805   startSection(Section, wasm::WASM_SEC_EVENT);
806 
807   encodeULEB128(Events.size(), W.OS);
808   for (const wasm::WasmEventType &Event : Events) {
809     encodeULEB128(Event.Attribute, W.OS);
810     encodeULEB128(Event.SigIndex, W.OS);
811   }
812 
813   endSection(Section);
814 }
815 
816 void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
817   if (Globals.empty())
818     return;
819 
820   SectionBookkeeping Section;
821   startSection(Section, wasm::WASM_SEC_GLOBAL);
822 
823   encodeULEB128(Globals.size(), W.OS);
824   for (const wasm::WasmGlobal &Global : Globals) {
825     encodeULEB128(Global.Type.Type, W.OS);
826     W.OS << char(Global.Type.Mutable);
827     W.OS << char(Global.InitExpr.Opcode);
828     switch (Global.Type.Type) {
829     case wasm::WASM_TYPE_I32:
830       encodeSLEB128(0, W.OS);
831       break;
832     case wasm::WASM_TYPE_I64:
833       encodeSLEB128(0, W.OS);
834       break;
835     case wasm::WASM_TYPE_F32:
836       writeI32(0);
837       break;
838     case wasm::WASM_TYPE_F64:
839       writeI64(0);
840       break;
841     default:
842       llvm_unreachable("unexpected type");
843     }
844     W.OS << char(wasm::WASM_OPCODE_END);
845   }
846 
847   endSection(Section);
848 }
849 
850 void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
851   if (Exports.empty())
852     return;
853 
854   SectionBookkeeping Section;
855   startSection(Section, wasm::WASM_SEC_EXPORT);
856 
857   encodeULEB128(Exports.size(), W.OS);
858   for (const wasm::WasmExport &Export : Exports) {
859     writeString(Export.Name);
860     W.OS << char(Export.Kind);
861     encodeULEB128(Export.Index, W.OS);
862   }
863 
864   endSection(Section);
865 }
866 
867 void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
868   if (TableElems.empty())
869     return;
870 
871   SectionBookkeeping Section;
872   startSection(Section, wasm::WASM_SEC_ELEM);
873 
874   encodeULEB128(1, W.OS); // number of "segments"
875   encodeULEB128(0, W.OS); // the table index
876 
877   // init expr for starting offset
878   W.OS << char(wasm::WASM_OPCODE_I32_CONST);
879   encodeSLEB128(InitialTableOffset, W.OS);
880   W.OS << char(wasm::WASM_OPCODE_END);
881 
882   encodeULEB128(TableElems.size(), W.OS);
883   for (uint32_t Elem : TableElems)
884     encodeULEB128(Elem, W.OS);
885 
886   endSection(Section);
887 }
888 
889 void WasmObjectWriter::writeDataCountSection() {
890   if (DataSegments.empty())
891     return;
892 
893   SectionBookkeeping Section;
894   startSection(Section, wasm::WASM_SEC_DATACOUNT);
895   encodeULEB128(DataSegments.size(), W.OS);
896   endSection(Section);
897 }
898 
899 void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
900                                         const MCAsmLayout &Layout,
901                                         ArrayRef<WasmFunction> Functions) {
902   if (Functions.empty())
903     return;
904 
905   SectionBookkeeping Section;
906   startSection(Section, wasm::WASM_SEC_CODE);
907   CodeSectionIndex = Section.Index;
908 
909   encodeULEB128(Functions.size(), W.OS);
910 
911   for (const WasmFunction &Func : Functions) {
912     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
913 
914     int64_t Size = 0;
915     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
916       report_fatal_error(".size expression must be evaluatable");
917 
918     encodeULEB128(Size, W.OS);
919     FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
920     Asm.writeSectionData(W.OS, &FuncSection, Layout);
921   }
922 
923   // Apply fixups.
924   applyRelocations(CodeRelocations, Section.ContentsOffset);
925 
926   endSection(Section);
927 }
928 
929 void WasmObjectWriter::writeDataSection() {
930   if (DataSegments.empty())
931     return;
932 
933   SectionBookkeeping Section;
934   startSection(Section, wasm::WASM_SEC_DATA);
935   DataSectionIndex = Section.Index;
936 
937   encodeULEB128(DataSegments.size(), W.OS); // count
938 
939   for (const WasmDataSegment &Segment : DataSegments) {
940     encodeULEB128(Segment.InitFlags, W.OS); // flags
941     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
942       encodeULEB128(0, W.OS); // memory index
943     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
944       W.OS << char(wasm::WASM_OPCODE_I32_CONST);
945       encodeSLEB128(Segment.Offset, W.OS); // offset
946       W.OS << char(wasm::WASM_OPCODE_END);
947     }
948     encodeULEB128(Segment.Data.size(), W.OS); // size
949     Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
950     W.OS << Segment.Data; // data
951   }
952 
953   // Apply fixups.
954   applyRelocations(DataRelocations, Section.ContentsOffset);
955 
956   endSection(Section);
957 }
958 
959 void WasmObjectWriter::writeRelocSection(
960     uint32_t SectionIndex, StringRef Name,
961     std::vector<WasmRelocationEntry> &Relocs) {
962   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
963   // for descriptions of the reloc sections.
964 
965   if (Relocs.empty())
966     return;
967 
968   // First, ensure the relocations are sorted in offset order.  In general they
969   // should already be sorted since `recordRelocation` is called in offset
970   // order, but for the code section we combine many MC sections into single
971   // wasm section, and this order is determined by the order of Asm.Symbols()
972   // not the sections order.
973   llvm::stable_sort(
974       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
975         return (A.Offset + A.FixupSection->getSectionOffset()) <
976                (B.Offset + B.FixupSection->getSectionOffset());
977       });
978 
979   SectionBookkeeping Section;
980   startCustomSection(Section, std::string("reloc.") + Name.str());
981 
982   encodeULEB128(SectionIndex, W.OS);
983   encodeULEB128(Relocs.size(), W.OS);
984   for (const WasmRelocationEntry &RelEntry : Relocs) {
985     uint64_t Offset =
986         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
987     uint32_t Index = getRelocationIndexValue(RelEntry);
988 
989     W.OS << char(RelEntry.Type);
990     encodeULEB128(Offset, W.OS);
991     encodeULEB128(Index, W.OS);
992     if (RelEntry.hasAddend())
993       encodeSLEB128(RelEntry.Addend, W.OS);
994   }
995 
996   endSection(Section);
997 }
998 
999 void WasmObjectWriter::writeCustomRelocSections() {
1000   for (const auto &Sec : CustomSections) {
1001     auto &Relocations = CustomSectionsRelocations[Sec.Section];
1002     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
1003   }
1004 }
1005 
1006 void WasmObjectWriter::writeLinkingMetaDataSection(
1007     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1008     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1009     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
1010   SectionBookkeeping Section;
1011   startCustomSection(Section, "linking");
1012   encodeULEB128(wasm::WasmMetadataVersion, W.OS);
1013 
1014   SectionBookkeeping SubSection;
1015   if (SymbolInfos.size() != 0) {
1016     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
1017     encodeULEB128(SymbolInfos.size(), W.OS);
1018     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
1019       encodeULEB128(Sym.Kind, W.OS);
1020       encodeULEB128(Sym.Flags, W.OS);
1021       switch (Sym.Kind) {
1022       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1023       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1024       case wasm::WASM_SYMBOL_TYPE_EVENT:
1025         encodeULEB128(Sym.ElementIndex, W.OS);
1026         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
1027             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
1028           writeString(Sym.Name);
1029         break;
1030       case wasm::WASM_SYMBOL_TYPE_DATA:
1031         writeString(Sym.Name);
1032         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
1033           encodeULEB128(Sym.DataRef.Segment, W.OS);
1034           encodeULEB128(Sym.DataRef.Offset, W.OS);
1035           encodeULEB128(Sym.DataRef.Size, W.OS);
1036         }
1037         break;
1038       case wasm::WASM_SYMBOL_TYPE_SECTION: {
1039         const uint32_t SectionIndex =
1040             CustomSections[Sym.ElementIndex].OutputIndex;
1041         encodeULEB128(SectionIndex, W.OS);
1042         break;
1043       }
1044       default:
1045         llvm_unreachable("unexpected kind");
1046       }
1047     }
1048     endSection(SubSection);
1049   }
1050 
1051   if (DataSegments.size()) {
1052     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1053     encodeULEB128(DataSegments.size(), W.OS);
1054     for (const WasmDataSegment &Segment : DataSegments) {
1055       writeString(Segment.Name);
1056       encodeULEB128(Segment.Alignment, W.OS);
1057       encodeULEB128(Segment.LinkerFlags, W.OS);
1058     }
1059     endSection(SubSection);
1060   }
1061 
1062   if (!InitFuncs.empty()) {
1063     startSection(SubSection, wasm::WASM_INIT_FUNCS);
1064     encodeULEB128(InitFuncs.size(), W.OS);
1065     for (auto &StartFunc : InitFuncs) {
1066       encodeULEB128(StartFunc.first, W.OS);  // priority
1067       encodeULEB128(StartFunc.second, W.OS); // function index
1068     }
1069     endSection(SubSection);
1070   }
1071 
1072   if (Comdats.size()) {
1073     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1074     encodeULEB128(Comdats.size(), W.OS);
1075     for (const auto &C : Comdats) {
1076       writeString(C.first);
1077       encodeULEB128(0, W.OS); // flags for future use
1078       encodeULEB128(C.second.size(), W.OS);
1079       for (const WasmComdatEntry &Entry : C.second) {
1080         encodeULEB128(Entry.Kind, W.OS);
1081         encodeULEB128(Entry.Index, W.OS);
1082       }
1083     }
1084     endSection(SubSection);
1085   }
1086 
1087   endSection(Section);
1088 }
1089 
1090 void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1091                                           const MCAssembler &Asm,
1092                                           const MCAsmLayout &Layout) {
1093   SectionBookkeeping Section;
1094   auto *Sec = CustomSection.Section;
1095   startCustomSection(Section, CustomSection.Name);
1096 
1097   Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1098   Asm.writeSectionData(W.OS, Sec, Layout);
1099 
1100   CustomSection.OutputContentsOffset = Section.ContentsOffset;
1101   CustomSection.OutputIndex = Section.Index;
1102 
1103   endSection(Section);
1104 
1105   // Apply fixups.
1106   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1107   applyRelocations(Relocations, CustomSection.OutputContentsOffset);
1108 }
1109 
1110 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
1111   assert(Symbol.isFunction());
1112   assert(TypeIndices.count(&Symbol));
1113   return TypeIndices[&Symbol];
1114 }
1115 
1116 uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1117   assert(Symbol.isEvent());
1118   assert(TypeIndices.count(&Symbol));
1119   return TypeIndices[&Symbol];
1120 }
1121 
1122 void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
1123   assert(Symbol.isFunction());
1124 
1125   WasmSignature S;
1126   const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
1127   if (auto *Sig = ResolvedSym->getSignature()) {
1128     S.Returns = Sig->Returns;
1129     S.Params = Sig->Params;
1130   }
1131 
1132   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1133   if (Pair.second)
1134     Signatures.push_back(S);
1135   TypeIndices[&Symbol] = Pair.first->second;
1136 
1137   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1138                     << " new:" << Pair.second << "\n");
1139   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1140 }
1141 
1142 void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1143   assert(Symbol.isEvent());
1144 
1145   // TODO Currently we don't generate imported exceptions, but if we do, we
1146   // should have a way of infering types of imported exceptions.
1147   WasmSignature S;
1148   if (auto *Sig = Symbol.getSignature()) {
1149     S.Returns = Sig->Returns;
1150     S.Params = Sig->Params;
1151   }
1152 
1153   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1154   if (Pair.second)
1155     Signatures.push_back(S);
1156   TypeIndices[&Symbol] = Pair.first->second;
1157 
1158   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1159                     << "\n");
1160   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1161 }
1162 
1163 static bool isInSymtab(const MCSymbolWasm &Sym) {
1164   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
1165     return true;
1166 
1167   if (Sym.isComdat() && !Sym.isDefined())
1168     return false;
1169 
1170   if (Sym.isTemporary())
1171     return false;
1172 
1173   if (Sym.isSection())
1174     return false;
1175 
1176   return true;
1177 }
1178 
1179 uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1180                                        const MCAsmLayout &Layout) {
1181   uint64_t StartOffset = W.OS.tell();
1182 
1183   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1184 
1185   // Collect information from the available symbols.
1186   SmallVector<WasmFunction, 4> Functions;
1187   SmallVector<uint32_t, 4> TableElems;
1188   SmallVector<wasm::WasmImport, 4> Imports;
1189   SmallVector<wasm::WasmExport, 4> Exports;
1190   SmallVector<wasm::WasmEventType, 1> Events;
1191   SmallVector<wasm::WasmGlobal, 1> Globals;
1192   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1193   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1194   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
1195   uint32_t DataSize = 0;
1196 
1197   // For now, always emit the memory import, since loads and stores are not
1198   // valid without it. In the future, we could perhaps be more clever and omit
1199   // it if there are no loads or stores.
1200   wasm::WasmImport MemImport;
1201   MemImport.Module = "env";
1202   MemImport.Field = "__linear_memory";
1203   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1204   Imports.push_back(MemImport);
1205 
1206   // For now, always emit the table section, since indirect calls are not
1207   // valid without it. In the future, we could perhaps be more clever and omit
1208   // it if there are no indirect calls.
1209   wasm::WasmImport TableImport;
1210   TableImport.Module = "env";
1211   TableImport.Field = "__indirect_function_table";
1212   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1213   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1214   Imports.push_back(TableImport);
1215 
1216   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1217   // symbols.  This must be done before populating WasmIndices for defined
1218   // symbols.
1219   for (const MCSymbol &S : Asm.symbols()) {
1220     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1221 
1222     // Register types for all functions, including those with private linkage
1223     // (because wasm always needs a type signature).
1224     if (WS.isFunction())
1225       registerFunctionType(WS);
1226 
1227     if (WS.isEvent())
1228       registerEventType(WS);
1229 
1230     if (WS.isTemporary())
1231       continue;
1232 
1233     // If the symbol is not defined in this translation unit, import it.
1234     if (!WS.isDefined() && !WS.isComdat()) {
1235       if (WS.isFunction()) {
1236         wasm::WasmImport Import;
1237         Import.Module = WS.getImportModule();
1238         Import.Field = WS.getImportName();
1239         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1240         Import.SigIndex = getFunctionType(WS);
1241         Imports.push_back(Import);
1242         assert(WasmIndices.count(&WS) == 0);
1243         WasmIndices[&WS] = NumFunctionImports++;
1244       } else if (WS.isGlobal()) {
1245         if (WS.isWeak())
1246           report_fatal_error("undefined global symbol cannot be weak");
1247 
1248         wasm::WasmImport Import;
1249         Import.Field = WS.getImportName();
1250         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1251         Import.Module = WS.getImportModule();
1252         Import.Global = WS.getGlobalType();
1253         Imports.push_back(Import);
1254         assert(WasmIndices.count(&WS) == 0);
1255         WasmIndices[&WS] = NumGlobalImports++;
1256       } else if (WS.isEvent()) {
1257         if (WS.isWeak())
1258           report_fatal_error("undefined event symbol cannot be weak");
1259 
1260         wasm::WasmImport Import;
1261         Import.Module = WS.getImportModule();
1262         Import.Field = WS.getImportName();
1263         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1264         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1265         Import.Event.SigIndex = getEventType(WS);
1266         Imports.push_back(Import);
1267         assert(WasmIndices.count(&WS) == 0);
1268         WasmIndices[&WS] = NumEventImports++;
1269       }
1270     }
1271   }
1272 
1273   // Add imports for GOT globals
1274   for (const MCSymbol &S : Asm.symbols()) {
1275     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1276     if (WS.isUsedInGOT()) {
1277       wasm::WasmImport Import;
1278       if (WS.isFunction())
1279         Import.Module = "GOT.func";
1280       else
1281         Import.Module = "GOT.mem";
1282       Import.Field = WS.getName();
1283       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1284       Import.Global = {wasm::WASM_TYPE_I32, true};
1285       Imports.push_back(Import);
1286       assert(GOTIndices.count(&WS) == 0);
1287       GOTIndices[&WS] = NumGlobalImports++;
1288     }
1289   }
1290 
1291   // Populate DataSegments and CustomSections, which must be done before
1292   // populating DataLocations.
1293   for (MCSection &Sec : Asm) {
1294     auto &Section = static_cast<MCSectionWasm &>(Sec);
1295     StringRef SectionName = Section.getName();
1296 
1297     // .init_array sections are handled specially elsewhere.
1298     if (SectionName.startswith(".init_array"))
1299       continue;
1300 
1301     // Code is handled separately
1302     if (Section.getKind().isText())
1303       continue;
1304 
1305     if (Section.isWasmData()) {
1306       uint32_t SegmentIndex = DataSegments.size();
1307       DataSize = alignTo(DataSize, Section.getAlignment());
1308       DataSegments.emplace_back();
1309       WasmDataSegment &Segment = DataSegments.back();
1310       Segment.Name = SectionName;
1311       Segment.InitFlags =
1312           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1313       Segment.Offset = DataSize;
1314       Segment.Section = &Section;
1315       addData(Segment.Data, Section);
1316       Segment.Alignment = Log2_32(Section.getAlignment());
1317       Segment.LinkerFlags = 0;
1318       DataSize += Segment.Data.size();
1319       Section.setSegmentIndex(SegmentIndex);
1320 
1321       if (const MCSymbolWasm *C = Section.getGroup()) {
1322         Comdats[C->getName()].emplace_back(
1323             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1324       }
1325     } else {
1326       // Create custom sections
1327       assert(Sec.getKind().isMetadata());
1328 
1329       StringRef Name = SectionName;
1330 
1331       // For user-defined custom sections, strip the prefix
1332       if (Name.startswith(".custom_section."))
1333         Name = Name.substr(strlen(".custom_section."));
1334 
1335       MCSymbol *Begin = Sec.getBeginSymbol();
1336       if (Begin) {
1337         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1338         if (SectionName != Begin->getName())
1339           report_fatal_error("section name and begin symbol should match: " +
1340                              Twine(SectionName));
1341       }
1342 
1343       // Separate out the producers and target features sections
1344       if (Name == "producers") {
1345         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1346         continue;
1347       }
1348       if (Name == "target_features") {
1349         TargetFeaturesSection =
1350             std::make_unique<WasmCustomSection>(Name, &Section);
1351         continue;
1352       }
1353 
1354       CustomSections.emplace_back(Name, &Section);
1355     }
1356   }
1357 
1358   // Populate WasmIndices and DataLocations for defined symbols.
1359   for (const MCSymbol &S : Asm.symbols()) {
1360     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1361     // or used in relocations.
1362     if (S.isTemporary() && S.getName().empty())
1363       continue;
1364 
1365     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1366     LLVM_DEBUG(
1367         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1368                << " isDefined=" << S.isDefined() << " isExternal="
1369                << S.isExternal() << " isTemporary=" << S.isTemporary()
1370                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1371                << " isVariable=" << WS.isVariable() << "\n");
1372 
1373     if (WS.isVariable())
1374       continue;
1375     if (WS.isComdat() && !WS.isDefined())
1376       continue;
1377 
1378     if (WS.isFunction()) {
1379       unsigned Index;
1380       if (WS.isDefined()) {
1381         if (WS.getOffset() != 0)
1382           report_fatal_error(
1383               "function sections must contain one function each");
1384 
1385         if (WS.getSize() == nullptr)
1386           report_fatal_error(
1387               "function symbols must have a size set with .size");
1388 
1389         // A definition. Write out the function body.
1390         Index = NumFunctionImports + Functions.size();
1391         WasmFunction Func;
1392         Func.SigIndex = getFunctionType(WS);
1393         Func.Sym = &WS;
1394         WasmIndices[&WS] = Index;
1395         Functions.push_back(Func);
1396 
1397         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1398         if (const MCSymbolWasm *C = Section.getGroup()) {
1399           Comdats[C->getName()].emplace_back(
1400               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1401         }
1402 
1403         if (WS.hasExportName()) {
1404           wasm::WasmExport Export;
1405           Export.Name = WS.getExportName();
1406           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1407           Export.Index = Index;
1408           Exports.push_back(Export);
1409         }
1410       } else {
1411         // An import; the index was assigned above.
1412         Index = WasmIndices.find(&WS)->second;
1413       }
1414 
1415       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1416 
1417     } else if (WS.isData()) {
1418       if (!isInSymtab(WS))
1419         continue;
1420 
1421       if (!WS.isDefined()) {
1422         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1423                           << "\n");
1424         continue;
1425       }
1426 
1427       if (!WS.getSize())
1428         report_fatal_error("data symbols must have a size set with .size: " +
1429                            WS.getName());
1430 
1431       int64_t Size = 0;
1432       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1433         report_fatal_error(".size expression must be evaluatable");
1434 
1435       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1436       if (!DataSection.isWasmData())
1437         report_fatal_error("data symbols must live in a data section: " +
1438                            WS.getName());
1439 
1440       // For each data symbol, export it in the symtab as a reference to the
1441       // corresponding Wasm data segment.
1442       wasm::WasmDataReference Ref = wasm::WasmDataReference{
1443           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
1444           static_cast<uint64_t>(Size)};
1445       DataLocations[&WS] = Ref;
1446       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1447 
1448     } else if (WS.isGlobal()) {
1449       // A "true" Wasm global (currently just __stack_pointer)
1450       if (WS.isDefined()) {
1451         assert(WasmIndices.count(&WS) == 0);
1452         wasm::WasmGlobal Global;
1453         Global.Type = WS.getGlobalType();
1454         Global.Index = NumGlobalImports + Globals.size();
1455         switch (Global.Type.Type) {
1456         case wasm::WASM_TYPE_I32:
1457           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
1458           break;
1459         case wasm::WASM_TYPE_I64:
1460           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
1461           break;
1462         case wasm::WASM_TYPE_F32:
1463           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
1464           break;
1465         case wasm::WASM_TYPE_F64:
1466           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
1467           break;
1468         default:
1469           llvm_unreachable("unexpected type");
1470         }
1471         WasmIndices[&WS] = Global.Index;
1472         Globals.push_back(Global);
1473       } else {
1474         // An import; the index was assigned above
1475         LLVM_DEBUG(dbgs() << "  -> global index: "
1476                           << WasmIndices.find(&WS)->second << "\n");
1477       }
1478     } else if (WS.isEvent()) {
1479       // C++ exception symbol (__cpp_exception)
1480       unsigned Index;
1481       if (WS.isDefined()) {
1482         assert(WasmIndices.count(&WS) == 0);
1483         Index = NumEventImports + Events.size();
1484         wasm::WasmEventType Event;
1485         Event.SigIndex = getEventType(WS);
1486         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1487         WasmIndices[&WS] = Index;
1488         Events.push_back(Event);
1489       } else {
1490         // An import; the index was assigned above.
1491         assert(WasmIndices.count(&WS) > 0);
1492       }
1493       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1494                         << "\n");
1495 
1496     } else {
1497       assert(WS.isSection());
1498     }
1499   }
1500 
1501   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1502   // process these in a separate pass because we need to have processed the
1503   // target of the alias before the alias itself and the symbols are not
1504   // necessarily ordered in this way.
1505   for (const MCSymbol &S : Asm.symbols()) {
1506     if (!S.isVariable())
1507       continue;
1508 
1509     assert(S.isDefined());
1510 
1511     // Find the target symbol of this weak alias and export that index
1512     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1513     const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
1514     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1515                       << "'\n");
1516 
1517     if (ResolvedSym->isFunction()) {
1518       assert(WasmIndices.count(ResolvedSym) > 0);
1519       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1520       assert(WasmIndices.count(&WS) == 0);
1521       WasmIndices[&WS] = WasmIndex;
1522       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1523     } else if (ResolvedSym->isData()) {
1524       assert(DataLocations.count(ResolvedSym) > 0);
1525       const wasm::WasmDataReference &Ref =
1526           DataLocations.find(ResolvedSym)->second;
1527       DataLocations[&WS] = Ref;
1528       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
1529     } else {
1530       report_fatal_error("don't yet support global/event aliases");
1531     }
1532   }
1533 
1534   // Finally, populate the symbol table itself, in its "natural" order.
1535   for (const MCSymbol &S : Asm.symbols()) {
1536     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1537     if (!isInSymtab(WS)) {
1538       WS.setIndex(InvalidIndex);
1539       continue;
1540     }
1541     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1542 
1543     uint32_t Flags = 0;
1544     if (WS.isWeak())
1545       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1546     if (WS.isHidden())
1547       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1548     if (!WS.isExternal() && WS.isDefined())
1549       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1550     if (WS.isUndefined())
1551       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1552     if (WS.isNoStrip()) {
1553       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1554       if (isEmscripten()) {
1555         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1556       }
1557     }
1558     if (WS.hasImportName())
1559       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1560     if (WS.hasExportName())
1561       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1562 
1563     wasm::WasmSymbolInfo Info;
1564     Info.Name = WS.getName();
1565     Info.Kind = WS.getType();
1566     Info.Flags = Flags;
1567     if (!WS.isData()) {
1568       assert(WasmIndices.count(&WS) > 0);
1569       Info.ElementIndex = WasmIndices.find(&WS)->second;
1570     } else if (WS.isDefined()) {
1571       assert(DataLocations.count(&WS) > 0);
1572       Info.DataRef = DataLocations.find(&WS)->second;
1573     }
1574     WS.setIndex(SymbolInfos.size());
1575     SymbolInfos.emplace_back(Info);
1576   }
1577 
1578   {
1579     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1580       // Functions referenced by a relocation need to put in the table.  This is
1581       // purely to make the object file's provisional values readable, and is
1582       // ignored by the linker, which re-calculates the relocations itself.
1583       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1584           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1585           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1586         return;
1587       assert(Rel.Symbol->isFunction());
1588       const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
1589       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
1590       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1591       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1592         LLVM_DEBUG(dbgs() << "  -> adding " << WS.getName()
1593                           << " to table: " << TableIndex << "\n");
1594         TableElems.push_back(FunctionIndex);
1595         registerFunctionType(WS);
1596       }
1597     };
1598 
1599     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1600       HandleReloc(RelEntry);
1601     for (const WasmRelocationEntry &RelEntry : DataRelocations)
1602       HandleReloc(RelEntry);
1603   }
1604 
1605   // Translate .init_array section contents into start functions.
1606   for (const MCSection &S : Asm) {
1607     const auto &WS = static_cast<const MCSectionWasm &>(S);
1608     if (WS.getName().startswith(".fini_array"))
1609       report_fatal_error(".fini_array sections are unsupported");
1610     if (!WS.getName().startswith(".init_array"))
1611       continue;
1612     if (WS.getFragmentList().empty())
1613       continue;
1614 
1615     // init_array is expected to contain a single non-empty data fragment
1616     if (WS.getFragmentList().size() != 3)
1617       report_fatal_error("only one .init_array section fragment supported");
1618 
1619     auto IT = WS.begin();
1620     const MCFragment &EmptyFrag = *IT;
1621     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1622       report_fatal_error(".init_array section should be aligned");
1623 
1624     IT = std::next(IT);
1625     const MCFragment &AlignFrag = *IT;
1626     if (AlignFrag.getKind() != MCFragment::FT_Align)
1627       report_fatal_error(".init_array section should be aligned");
1628     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1629       report_fatal_error(".init_array section should be aligned for pointers");
1630 
1631     const MCFragment &Frag = *std::next(IT);
1632     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1633       report_fatal_error("only data supported in .init_array section");
1634 
1635     uint16_t Priority = UINT16_MAX;
1636     unsigned PrefixLength = strlen(".init_array");
1637     if (WS.getName().size() > PrefixLength) {
1638       if (WS.getName()[PrefixLength] != '.')
1639         report_fatal_error(
1640             ".init_array section priority should start with '.'");
1641       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1642         report_fatal_error("invalid .init_array section priority");
1643     }
1644     const auto &DataFrag = cast<MCDataFragment>(Frag);
1645     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1646     for (const uint8_t *
1647              P = (const uint8_t *)Contents.data(),
1648             *End = (const uint8_t *)Contents.data() + Contents.size();
1649          P != End; ++P) {
1650       if (*P != 0)
1651         report_fatal_error("non-symbolic data in .init_array section");
1652     }
1653     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1654       assert(Fixup.getKind() ==
1655              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1656       const MCExpr *Expr = Fixup.getValue();
1657       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1658       if (!SymRef)
1659         report_fatal_error("fixups in .init_array should be symbol references");
1660       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1661       if (TargetSym.getIndex() == InvalidIndex)
1662         report_fatal_error("symbols in .init_array should exist in symtab");
1663       if (!TargetSym.isFunction())
1664         report_fatal_error("symbols in .init_array should be for functions");
1665       InitFuncs.push_back(
1666           std::make_pair(Priority, TargetSym.getIndex()));
1667     }
1668   }
1669 
1670   // Write out the Wasm header.
1671   writeHeader(Asm);
1672 
1673   writeTypeSection(Signatures);
1674   writeImportSection(Imports, DataSize, TableElems.size());
1675   writeFunctionSection(Functions);
1676   // Skip the "table" section; we import the table instead.
1677   // Skip the "memory" section; we import the memory instead.
1678   writeEventSection(Events);
1679   writeGlobalSection(Globals);
1680   writeExportSection(Exports);
1681   writeElemSection(TableElems);
1682   writeDataCountSection();
1683   writeCodeSection(Asm, Layout, Functions);
1684   writeDataSection();
1685   for (auto &CustomSection : CustomSections)
1686     writeCustomSection(CustomSection, Asm, Layout);
1687   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1688   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1689   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1690   writeCustomRelocSections();
1691   if (ProducersSection)
1692     writeCustomSection(*ProducersSection, Asm, Layout);
1693   if (TargetFeaturesSection)
1694     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1695 
1696   // TODO: Translate the .comment section to the output.
1697   return W.OS.tell() - StartOffset;
1698 }
1699 
1700 std::unique_ptr<MCObjectWriter>
1701 llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1702                              raw_pwrite_stream &OS) {
1703   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
1704 }
1705