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   uint64_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   // Relocations for fixing up references in the data section.
228   std::vector<WasmRelocationEntry> DataRelocations;
229 
230   // Index values to use for fixing up call_indirect type indices.
231   // Maps function symbols to the index of the type of the function
232   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
233   // Maps function symbols to the table element index space. Used
234   // for TABLE_INDEX relocation types (i.e. address taken functions).
235   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
236   // Maps function/global symbols to the function/global/event/section index
237   // space.
238   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
239   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
240   // Maps data symbols to the Wasm segment and offset/size with the segment.
241   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
242 
243   // Stores output data (index, relocations, content offset) for custom
244   // section.
245   std::vector<WasmCustomSection> CustomSections;
246   std::unique_ptr<WasmCustomSection> ProducersSection;
247   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
248   // Relocations for fixing up references in the custom sections.
249   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
250       CustomSectionsRelocations;
251 
252   // Map from section to defining function symbol.
253   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
254 
255   DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
256   SmallVector<WasmSignature, 4> Signatures;
257   SmallVector<WasmDataSegment, 4> DataSegments;
258   unsigned NumFunctionImports = 0;
259   unsigned NumGlobalImports = 0;
260   unsigned NumEventImports = 0;
261   uint32_t SectionCount = 0;
262 
263   // TargetObjectWriter wrappers.
264   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
265   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
266 
267   void startSection(SectionBookkeeping &Section, unsigned SectionId);
268   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
269   void endSection(SectionBookkeeping &Section);
270 
271 public:
272   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
273                    raw_pwrite_stream &OS)
274       : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
275 
276 private:
277   void reset() override {
278     CodeRelocations.clear();
279     DataRelocations.clear();
280     TypeIndices.clear();
281     WasmIndices.clear();
282     GOTIndices.clear();
283     TableIndices.clear();
284     DataLocations.clear();
285     CustomSections.clear();
286     ProducersSection.reset();
287     TargetFeaturesSection.reset();
288     CustomSectionsRelocations.clear();
289     SignatureIndices.clear();
290     Signatures.clear();
291     DataSegments.clear();
292     SectionFunctions.clear();
293     NumFunctionImports = 0;
294     NumGlobalImports = 0;
295     MCObjectWriter::reset();
296   }
297 
298   void writeHeader(const MCAssembler &Asm);
299 
300   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
301                         const MCFragment *Fragment, const MCFixup &Fixup,
302                         MCValue Target, uint64_t &FixedValue) override;
303 
304   void executePostLayoutBinding(MCAssembler &Asm,
305                                 const MCAsmLayout &Layout) override;
306 
307   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
308 
309   void writeString(const StringRef Str) {
310     encodeULEB128(Str.size(), W.OS);
311     W.OS << Str;
312   }
313 
314   void writeI32(int32_t val) {
315     char Buffer[4];
316     support::endian::write32le(Buffer, val);
317     W.OS.write(Buffer, sizeof(Buffer));
318   }
319 
320   void writeI64(int64_t val) {
321     char Buffer[8];
322     support::endian::write64le(Buffer, val);
323     W.OS.write(Buffer, sizeof(Buffer));
324   }
325 
326   void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
327 
328   void writeTypeSection(ArrayRef<WasmSignature> Signatures);
329   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize,
330                           uint32_t NumElements);
331   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
332   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
333   void writeElemSection(ArrayRef<uint32_t> TableElems);
334   void writeDataCountSection();
335   uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
336                             ArrayRef<WasmFunction> Functions);
337   uint32_t writeDataSection(const MCAsmLayout &Layout);
338   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
339   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
340   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
341                          std::vector<WasmRelocationEntry> &Relocations);
342   void writeLinkingMetaDataSection(
343       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
344       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
345       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
346   void writeCustomSection(WasmCustomSection &CustomSection,
347                           const MCAssembler &Asm, const MCAsmLayout &Layout);
348   void writeCustomRelocSections();
349   void
350   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
351                                  const MCAsmLayout &Layout);
352 
353   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
354                                const MCAsmLayout &Layout);
355   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
356                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
357 
358   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
359   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
360   uint32_t getEventType(const MCSymbolWasm &Symbol);
361   void registerFunctionType(const MCSymbolWasm &Symbol);
362   void registerEventType(const MCSymbolWasm &Symbol);
363 };
364 
365 } // end anonymous namespace
366 
367 // Write out a section header and a patchable section size field.
368 void WasmObjectWriter::startSection(SectionBookkeeping &Section,
369                                     unsigned SectionId) {
370   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
371   W.OS << char(SectionId);
372 
373   Section.SizeOffset = W.OS.tell();
374 
375   // The section size. We don't know the size yet, so reserve enough space
376   // for any 32-bit value; we'll patch it later.
377   encodeULEB128(0, W.OS, 5);
378 
379   // The position where the section starts, for measuring its size.
380   Section.ContentsOffset = W.OS.tell();
381   Section.PayloadOffset = W.OS.tell();
382   Section.Index = SectionCount++;
383 }
384 
385 void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
386                                           StringRef Name) {
387   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
388   startSection(Section, wasm::WASM_SEC_CUSTOM);
389 
390   // The position where the section header ends, for measuring its size.
391   Section.PayloadOffset = W.OS.tell();
392 
393   // Custom sections in wasm also have a string identifier.
394   writeString(Name);
395 
396   // The position where the custom section starts.
397   Section.ContentsOffset = W.OS.tell();
398 }
399 
400 // Now that the section is complete and we know how big it is, patch up the
401 // section size field at the start of the section.
402 void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
403   uint64_t Size = W.OS.tell();
404   // /dev/null doesn't support seek/tell and can report offset of 0.
405   // Simply skip this patching in that case.
406   if (!Size)
407     return;
408 
409   Size -= Section.PayloadOffset;
410   if (uint32_t(Size) != Size)
411     report_fatal_error("section size does not fit in a uint32_t");
412 
413   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
414 
415   // Write the final section size to the payload_len field, which follows
416   // the section id byte.
417   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W.OS), Size,
418                        Section.SizeOffset);
419 }
420 
421 // Emit the Wasm header.
422 void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
423   W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
424   W.write<uint32_t>(wasm::WasmVersion);
425 }
426 
427 void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
428                                                 const MCAsmLayout &Layout) {
429   // Build a map of sections to the function that defines them, for use
430   // in recordRelocation.
431   for (const MCSymbol &S : Asm.symbols()) {
432     const auto &WS = static_cast<const MCSymbolWasm &>(S);
433     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
434       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
435       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
436       if (!Pair.second)
437         report_fatal_error("section already has a defining function: " +
438                            Sec.getName());
439     }
440   }
441 }
442 
443 void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
444                                         const MCAsmLayout &Layout,
445                                         const MCFragment *Fragment,
446                                         const MCFixup &Fixup, MCValue Target,
447                                         uint64_t &FixedValue) {
448   // The WebAssembly backend should never generate FKF_IsPCRel fixups
449   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
450            MCFixupKindInfo::FKF_IsPCRel));
451 
452   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
453   uint64_t C = Target.getConstant();
454   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
455   MCContext &Ctx = Asm.getContext();
456 
457   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
458     // To get here the A - B expression must have failed evaluateAsRelocatable.
459     // This means either A or B must be undefined and in WebAssembly we can't
460     // support either of those cases.
461     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
462     Ctx.reportError(
463         Fixup.getLoc(),
464         Twine("symbol '") + SymB.getName() +
465             "': unsupported subtraction expression used in relocation.");
466     return;
467   }
468 
469   // We either rejected the fixup or folded B into C at this point.
470   const MCSymbolRefExpr *RefA = Target.getSymA();
471   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
472 
473   // The .init_array isn't translated as data, so don't do relocations in it.
474   if (FixupSection.getName().startswith(".init_array")) {
475     SymA->setUsedInInitArray();
476     return;
477   }
478 
479   if (SymA->isVariable()) {
480     const MCExpr *Expr = SymA->getVariableValue();
481     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
482       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
483         llvm_unreachable("weakref used in reloc not yet implemented");
484   }
485 
486   // Put any constant offset in an addend. Offsets can be negative, and
487   // LLVM expects wrapping, in contrast to wasm's immediates which can't
488   // be negative and don't wrap.
489   FixedValue = 0;
490 
491   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
492 
493   // Absolute offset within a section or a function.
494   // Currently only supported for for metadata sections.
495   // See: test/MC/WebAssembly/blockaddress.ll
496   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
497       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
498     if (!FixupSection.getKind().isMetadata())
499       report_fatal_error("relocations for function or section offsets are "
500                          "only supported in metadata sections");
501 
502     const MCSymbol *SectionSymbol = nullptr;
503     const MCSection &SecA = SymA->getSection();
504     if (SecA.getKind().isText())
505       SectionSymbol = SectionFunctions.find(&SecA)->second;
506     else
507       SectionSymbol = SecA.getBeginSymbol();
508     if (!SectionSymbol)
509       report_fatal_error("section symbol is required for relocation");
510 
511     C += Layout.getSymbolOffset(*SymA);
512     SymA = cast<MCSymbolWasm>(SectionSymbol);
513   }
514 
515   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
516   // against a named symbol.
517   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
518     if (SymA->getName().empty())
519       report_fatal_error("relocations against un-named temporaries are not yet "
520                          "supported by wasm");
521 
522     SymA->setUsedInReloc();
523   }
524 
525   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
526     SymA->setUsedInGOT();
527 
528   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
529   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
530 
531   if (FixupSection.isWasmData()) {
532     DataRelocations.push_back(Rec);
533   } else if (FixupSection.getKind().isText()) {
534     CodeRelocations.push_back(Rec);
535   } else if (FixupSection.getKind().isMetadata()) {
536     CustomSectionsRelocations[&FixupSection].push_back(Rec);
537   } else {
538     llvm_unreachable("unexpected section type");
539   }
540 }
541 
542 // Compute a value to write into the code at the location covered
543 // by RelEntry. This value isn't used by the static linker; it just serves
544 // to make the object format more readable and more likely to be directly
545 // useable.
546 uint64_t
547 WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
548                                       const MCAsmLayout &Layout) {
549   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
550        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
551       !RelEntry.Symbol->isGlobal()) {
552     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
553     return GOTIndices[RelEntry.Symbol];
554   }
555 
556   switch (RelEntry.Type) {
557   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
558   case wasm::R_WASM_TABLE_INDEX_SLEB:
559   case wasm::R_WASM_TABLE_INDEX_SLEB64:
560   case wasm::R_WASM_TABLE_INDEX_I32:
561   case wasm::R_WASM_TABLE_INDEX_I64: {
562     // Provisional value is table address of the resolved symbol itself
563     const MCSymbolWasm *Base =
564         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
565     assert(Base->isFunction());
566     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
567       return TableIndices[Base] - InitialTableOffset;
568     else
569       return TableIndices[Base];
570   }
571   case wasm::R_WASM_TYPE_INDEX_LEB:
572     // Provisional value is same as the index
573     return getRelocationIndexValue(RelEntry);
574   case wasm::R_WASM_FUNCTION_INDEX_LEB:
575   case wasm::R_WASM_GLOBAL_INDEX_LEB:
576   case wasm::R_WASM_GLOBAL_INDEX_I32:
577   case wasm::R_WASM_EVENT_INDEX_LEB:
578     // Provisional value is function/global/event Wasm index
579     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
580     return WasmIndices[RelEntry.Symbol];
581   case wasm::R_WASM_FUNCTION_OFFSET_I32:
582   case wasm::R_WASM_SECTION_OFFSET_I32: {
583     const auto &Section =
584         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
585     return Section.getSectionOffset() + RelEntry.Addend;
586   }
587   case wasm::R_WASM_MEMORY_ADDR_LEB:
588   case wasm::R_WASM_MEMORY_ADDR_LEB64:
589   case wasm::R_WASM_MEMORY_ADDR_SLEB:
590   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
591   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
592   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
593   case wasm::R_WASM_MEMORY_ADDR_I32:
594   case wasm::R_WASM_MEMORY_ADDR_I64: {
595     // Provisional value is address of the global
596     const MCSymbolWasm *Base =
597         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
598     // For undefined symbols, use zero
599     if (!Base->isDefined())
600       return 0;
601     const wasm::WasmDataReference &Ref = DataLocations[Base];
602     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
603     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
604     return Segment.Offset + Ref.Offset + RelEntry.Addend;
605   }
606   default:
607     llvm_unreachable("invalid relocation type");
608   }
609 }
610 
611 static void addData(SmallVectorImpl<char> &DataBytes,
612                     MCSectionWasm &DataSection) {
613   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
614 
615   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
616 
617   for (const MCFragment &Frag : DataSection) {
618     if (Frag.hasInstructions())
619       report_fatal_error("only data supported in data sections");
620 
621     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
622       if (Align->getValueSize() != 1)
623         report_fatal_error("only byte values supported for alignment");
624       // If nops are requested, use zeros, as this is the data section.
625       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
626       uint64_t Size =
627           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
628                              DataBytes.size() + Align->getMaxBytesToEmit());
629       DataBytes.resize(Size, Value);
630     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
631       int64_t NumValues;
632       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
633         llvm_unreachable("The fill should be an assembler constant");
634       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
635                        Fill->getValue());
636     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
637       const SmallVectorImpl<char> &Contents = LEB->getContents();
638       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
639     } else {
640       const auto &DataFrag = cast<MCDataFragment>(Frag);
641       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
642       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
643     }
644   }
645 
646   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
647 }
648 
649 uint32_t
650 WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
651   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
652     if (!TypeIndices.count(RelEntry.Symbol))
653       report_fatal_error("symbol not found in type index space: " +
654                          RelEntry.Symbol->getName());
655     return TypeIndices[RelEntry.Symbol];
656   }
657 
658   return RelEntry.Symbol->getIndex();
659 }
660 
661 // Apply the portions of the relocation records that we can handle ourselves
662 // directly.
663 void WasmObjectWriter::applyRelocations(
664     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
665     const MCAsmLayout &Layout) {
666   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
667   for (const WasmRelocationEntry &RelEntry : Relocations) {
668     uint64_t Offset = ContentsOffset +
669                       RelEntry.FixupSection->getSectionOffset() +
670                       RelEntry.Offset;
671 
672     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
673     auto Value = getProvisionalValue(RelEntry, Layout);
674 
675     switch (RelEntry.Type) {
676     case wasm::R_WASM_FUNCTION_INDEX_LEB:
677     case wasm::R_WASM_TYPE_INDEX_LEB:
678     case wasm::R_WASM_GLOBAL_INDEX_LEB:
679     case wasm::R_WASM_MEMORY_ADDR_LEB:
680     case wasm::R_WASM_EVENT_INDEX_LEB:
681       writePatchableLEB<5>(Stream, Value, Offset);
682       break;
683     case wasm::R_WASM_MEMORY_ADDR_LEB64:
684       writePatchableLEB<10>(Stream, Value, Offset);
685       break;
686     case wasm::R_WASM_TABLE_INDEX_I32:
687     case wasm::R_WASM_MEMORY_ADDR_I32:
688     case wasm::R_WASM_FUNCTION_OFFSET_I32:
689     case wasm::R_WASM_SECTION_OFFSET_I32:
690     case wasm::R_WASM_GLOBAL_INDEX_I32:
691       patchI32(Stream, Value, Offset);
692       break;
693     case wasm::R_WASM_TABLE_INDEX_I64:
694     case wasm::R_WASM_MEMORY_ADDR_I64:
695       patchI64(Stream, Value, Offset);
696       break;
697     case wasm::R_WASM_TABLE_INDEX_SLEB:
698     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
699     case wasm::R_WASM_MEMORY_ADDR_SLEB:
700     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
701       writePatchableSLEB<5>(Stream, Value, Offset);
702       break;
703     case wasm::R_WASM_TABLE_INDEX_SLEB64:
704     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
705     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
706       writePatchableSLEB<10>(Stream, Value, Offset);
707       break;
708     default:
709       llvm_unreachable("invalid relocation type");
710     }
711   }
712 }
713 
714 void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
715   if (Signatures.empty())
716     return;
717 
718   SectionBookkeeping Section;
719   startSection(Section, wasm::WASM_SEC_TYPE);
720 
721   encodeULEB128(Signatures.size(), W.OS);
722 
723   for (const WasmSignature &Sig : Signatures) {
724     W.OS << char(wasm::WASM_TYPE_FUNC);
725     encodeULEB128(Sig.Params.size(), W.OS);
726     for (wasm::ValType Ty : Sig.Params)
727       writeValueType(Ty);
728     encodeULEB128(Sig.Returns.size(), W.OS);
729     for (wasm::ValType Ty : Sig.Returns)
730       writeValueType(Ty);
731   }
732 
733   endSection(Section);
734 }
735 
736 void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
737                                           uint64_t DataSize,
738                                           uint32_t NumElements) {
739   if (Imports.empty())
740     return;
741 
742   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
743 
744   SectionBookkeeping Section;
745   startSection(Section, wasm::WASM_SEC_IMPORT);
746 
747   encodeULEB128(Imports.size(), W.OS);
748   for (const wasm::WasmImport &Import : Imports) {
749     writeString(Import.Module);
750     writeString(Import.Field);
751     W.OS << char(Import.Kind);
752 
753     switch (Import.Kind) {
754     case wasm::WASM_EXTERNAL_FUNCTION:
755       encodeULEB128(Import.SigIndex, W.OS);
756       break;
757     case wasm::WASM_EXTERNAL_GLOBAL:
758       W.OS << char(Import.Global.Type);
759       W.OS << char(Import.Global.Mutable ? 1 : 0);
760       break;
761     case wasm::WASM_EXTERNAL_MEMORY:
762       encodeULEB128(Import.Memory.Flags, W.OS);
763       encodeULEB128(NumPages, W.OS);  // initial
764       break;
765     case wasm::WASM_EXTERNAL_TABLE:
766       W.OS << char(Import.Table.ElemType);
767       encodeULEB128(0, W.OS);           // flags
768       encodeULEB128(NumElements, W.OS); // initial
769       break;
770     case wasm::WASM_EXTERNAL_EVENT:
771       encodeULEB128(Import.Event.Attribute, W.OS);
772       encodeULEB128(Import.Event.SigIndex, W.OS);
773       break;
774     default:
775       llvm_unreachable("unsupported import kind");
776     }
777   }
778 
779   endSection(Section);
780 }
781 
782 void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
783   if (Functions.empty())
784     return;
785 
786   SectionBookkeeping Section;
787   startSection(Section, wasm::WASM_SEC_FUNCTION);
788 
789   encodeULEB128(Functions.size(), W.OS);
790   for (const WasmFunction &Func : Functions)
791     encodeULEB128(Func.SigIndex, W.OS);
792 
793   endSection(Section);
794 }
795 
796 void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
797   if (Events.empty())
798     return;
799 
800   SectionBookkeeping Section;
801   startSection(Section, wasm::WASM_SEC_EVENT);
802 
803   encodeULEB128(Events.size(), W.OS);
804   for (const wasm::WasmEventType &Event : Events) {
805     encodeULEB128(Event.Attribute, W.OS);
806     encodeULEB128(Event.SigIndex, W.OS);
807   }
808 
809   endSection(Section);
810 }
811 
812 void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
813   if (Globals.empty())
814     return;
815 
816   SectionBookkeeping Section;
817   startSection(Section, wasm::WASM_SEC_GLOBAL);
818 
819   encodeULEB128(Globals.size(), W.OS);
820   for (const wasm::WasmGlobal &Global : Globals) {
821     encodeULEB128(Global.Type.Type, W.OS);
822     W.OS << char(Global.Type.Mutable);
823     W.OS << char(Global.InitExpr.Opcode);
824     switch (Global.Type.Type) {
825     case wasm::WASM_TYPE_I32:
826       encodeSLEB128(0, W.OS);
827       break;
828     case wasm::WASM_TYPE_I64:
829       encodeSLEB128(0, W.OS);
830       break;
831     case wasm::WASM_TYPE_F32:
832       writeI32(0);
833       break;
834     case wasm::WASM_TYPE_F64:
835       writeI64(0);
836       break;
837     case wasm::WASM_TYPE_EXTERNREF:
838       writeValueType(wasm::ValType::EXTERNREF);
839       break;
840     default:
841       llvm_unreachable("unexpected type");
842     }
843     W.OS << char(wasm::WASM_OPCODE_END);
844   }
845 
846   endSection(Section);
847 }
848 
849 void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
850   if (Exports.empty())
851     return;
852 
853   SectionBookkeeping Section;
854   startSection(Section, wasm::WASM_SEC_EXPORT);
855 
856   encodeULEB128(Exports.size(), W.OS);
857   for (const wasm::WasmExport &Export : Exports) {
858     writeString(Export.Name);
859     W.OS << char(Export.Kind);
860     encodeULEB128(Export.Index, W.OS);
861   }
862 
863   endSection(Section);
864 }
865 
866 void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
867   if (TableElems.empty())
868     return;
869 
870   SectionBookkeeping Section;
871   startSection(Section, wasm::WASM_SEC_ELEM);
872 
873   encodeULEB128(1, W.OS); // number of "segments"
874   encodeULEB128(0, W.OS); // the table index
875 
876   // init expr for starting offset
877   W.OS << char(wasm::WASM_OPCODE_I32_CONST);
878   encodeSLEB128(InitialTableOffset, W.OS);
879   W.OS << char(wasm::WASM_OPCODE_END);
880 
881   encodeULEB128(TableElems.size(), W.OS);
882   for (uint32_t Elem : TableElems)
883     encodeULEB128(Elem, W.OS);
884 
885   endSection(Section);
886 }
887 
888 void WasmObjectWriter::writeDataCountSection() {
889   if (DataSegments.empty())
890     return;
891 
892   SectionBookkeeping Section;
893   startSection(Section, wasm::WASM_SEC_DATACOUNT);
894   encodeULEB128(DataSegments.size(), W.OS);
895   endSection(Section);
896 }
897 
898 uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
899                                             const MCAsmLayout &Layout,
900                                             ArrayRef<WasmFunction> Functions) {
901   if (Functions.empty())
902     return 0;
903 
904   SectionBookkeeping Section;
905   startSection(Section, wasm::WASM_SEC_CODE);
906 
907   encodeULEB128(Functions.size(), W.OS);
908 
909   for (const WasmFunction &Func : Functions) {
910     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
911 
912     int64_t Size = 0;
913     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
914       report_fatal_error(".size expression must be evaluatable");
915 
916     encodeULEB128(Size, W.OS);
917     FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
918     Asm.writeSectionData(W.OS, &FuncSection, Layout);
919   }
920 
921   // Apply fixups.
922   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
923 
924   endSection(Section);
925   return Section.Index;
926 }
927 
928 uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
929   if (DataSegments.empty())
930     return 0;
931 
932   SectionBookkeeping Section;
933   startSection(Section, wasm::WASM_SEC_DATA);
934 
935   encodeULEB128(DataSegments.size(), W.OS); // count
936 
937   for (const WasmDataSegment &Segment : DataSegments) {
938     encodeULEB128(Segment.InitFlags, W.OS); // flags
939     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
940       encodeULEB128(0, W.OS); // memory index
941     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
942       W.OS << char(Segment.Offset > INT32_MAX ? wasm::WASM_OPCODE_I64_CONST
943                                               : wasm::WASM_OPCODE_I32_CONST);
944       encodeSLEB128(Segment.Offset, W.OS); // offset
945       W.OS << char(wasm::WASM_OPCODE_END);
946     }
947     encodeULEB128(Segment.Data.size(), W.OS); // size
948     Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
949     W.OS << Segment.Data; // data
950   }
951 
952   // Apply fixups.
953   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
954 
955   endSection(Section);
956   return Section.Index;
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, Layout);
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 
1127   if (auto *Sig = Symbol.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   uint64_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   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1205                                      : wasm::WASM_LIMITS_FLAG_NONE;
1206   Imports.push_back(MemImport);
1207 
1208   // For now, always emit the table section, since indirect calls are not
1209   // valid without it. In the future, we could perhaps be more clever and omit
1210   // it if there are no indirect calls.
1211   wasm::WasmImport TableImport;
1212   TableImport.Module = "env";
1213   TableImport.Field = "__indirect_function_table";
1214   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1215   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1216   Imports.push_back(TableImport);
1217 
1218   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1219   // symbols.  This must be done before populating WasmIndices for defined
1220   // symbols.
1221   for (const MCSymbol &S : Asm.symbols()) {
1222     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1223 
1224     // Register types for all functions, including those with private linkage
1225     // (because wasm always needs a type signature).
1226     if (WS.isFunction()) {
1227       const MCSymbolWasm *Base = cast<MCSymbolWasm>(Layout.getBaseSymbol(S));
1228       registerFunctionType(*Base);
1229     }
1230 
1231     if (WS.isEvent())
1232       registerEventType(WS);
1233 
1234     if (WS.isTemporary())
1235       continue;
1236 
1237     // If the symbol is not defined in this translation unit, import it.
1238     if (!WS.isDefined() && !WS.isComdat()) {
1239       if (WS.isFunction()) {
1240         wasm::WasmImport Import;
1241         Import.Module = WS.getImportModule();
1242         Import.Field = WS.getImportName();
1243         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1244         Import.SigIndex = getFunctionType(WS);
1245         Imports.push_back(Import);
1246         assert(WasmIndices.count(&WS) == 0);
1247         WasmIndices[&WS] = NumFunctionImports++;
1248       } else if (WS.isGlobal()) {
1249         if (WS.isWeak())
1250           report_fatal_error("undefined global symbol cannot be weak");
1251 
1252         wasm::WasmImport Import;
1253         Import.Field = WS.getImportName();
1254         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1255         Import.Module = WS.getImportModule();
1256         Import.Global = WS.getGlobalType();
1257         Imports.push_back(Import);
1258         assert(WasmIndices.count(&WS) == 0);
1259         WasmIndices[&WS] = NumGlobalImports++;
1260       } else if (WS.isEvent()) {
1261         if (WS.isWeak())
1262           report_fatal_error("undefined event symbol cannot be weak");
1263 
1264         wasm::WasmImport Import;
1265         Import.Module = WS.getImportModule();
1266         Import.Field = WS.getImportName();
1267         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1268         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1269         Import.Event.SigIndex = getEventType(WS);
1270         Imports.push_back(Import);
1271         assert(WasmIndices.count(&WS) == 0);
1272         WasmIndices[&WS] = NumEventImports++;
1273       }
1274     }
1275   }
1276 
1277   // Add imports for GOT globals
1278   for (const MCSymbol &S : Asm.symbols()) {
1279     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1280     if (WS.isUsedInGOT()) {
1281       wasm::WasmImport Import;
1282       if (WS.isFunction())
1283         Import.Module = "GOT.func";
1284       else
1285         Import.Module = "GOT.mem";
1286       Import.Field = WS.getName();
1287       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1288       Import.Global = {wasm::WASM_TYPE_I32, true};
1289       Imports.push_back(Import);
1290       assert(GOTIndices.count(&WS) == 0);
1291       GOTIndices[&WS] = NumGlobalImports++;
1292     }
1293   }
1294 
1295   // Populate DataSegments and CustomSections, which must be done before
1296   // populating DataLocations.
1297   for (MCSection &Sec : Asm) {
1298     auto &Section = static_cast<MCSectionWasm &>(Sec);
1299     StringRef SectionName = Section.getName();
1300 
1301     // .init_array sections are handled specially elsewhere.
1302     if (SectionName.startswith(".init_array"))
1303       continue;
1304 
1305     // Code is handled separately
1306     if (Section.getKind().isText())
1307       continue;
1308 
1309     if (Section.isWasmData()) {
1310       uint32_t SegmentIndex = DataSegments.size();
1311       DataSize = alignTo(DataSize, Section.getAlignment());
1312       DataSegments.emplace_back();
1313       WasmDataSegment &Segment = DataSegments.back();
1314       Segment.Name = SectionName;
1315       Segment.InitFlags =
1316           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1317       Segment.Offset = DataSize;
1318       Segment.Section = &Section;
1319       addData(Segment.Data, Section);
1320       Segment.Alignment = Log2_32(Section.getAlignment());
1321       Segment.LinkerFlags = 0;
1322       DataSize += Segment.Data.size();
1323       Section.setSegmentIndex(SegmentIndex);
1324 
1325       if (const MCSymbolWasm *C = Section.getGroup()) {
1326         Comdats[C->getName()].emplace_back(
1327             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1328       }
1329     } else {
1330       // Create custom sections
1331       assert(Sec.getKind().isMetadata());
1332 
1333       StringRef Name = SectionName;
1334 
1335       // For user-defined custom sections, strip the prefix
1336       if (Name.startswith(".custom_section."))
1337         Name = Name.substr(strlen(".custom_section."));
1338 
1339       MCSymbol *Begin = Sec.getBeginSymbol();
1340       if (Begin) {
1341         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1342         if (SectionName != Begin->getName())
1343           report_fatal_error("section name and begin symbol should match: " +
1344                              Twine(SectionName));
1345       }
1346 
1347       // Separate out the producers and target features sections
1348       if (Name == "producers") {
1349         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1350         continue;
1351       }
1352       if (Name == "target_features") {
1353         TargetFeaturesSection =
1354             std::make_unique<WasmCustomSection>(Name, &Section);
1355         continue;
1356       }
1357 
1358       CustomSections.emplace_back(Name, &Section);
1359     }
1360   }
1361 
1362   // Populate WasmIndices and DataLocations for defined symbols.
1363   for (const MCSymbol &S : Asm.symbols()) {
1364     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1365     // or used in relocations.
1366     if (S.isTemporary() && S.getName().empty())
1367       continue;
1368 
1369     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1370     LLVM_DEBUG(
1371         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1372                << " isDefined=" << S.isDefined() << " isExternal="
1373                << S.isExternal() << " isTemporary=" << S.isTemporary()
1374                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1375                << " isVariable=" << WS.isVariable() << "\n");
1376 
1377     if (WS.isVariable())
1378       continue;
1379     if (WS.isComdat() && !WS.isDefined())
1380       continue;
1381 
1382     if (WS.isFunction()) {
1383       unsigned Index;
1384       if (WS.isDefined()) {
1385         if (WS.getOffset() != 0)
1386           report_fatal_error(
1387               "function sections must contain one function each");
1388 
1389         if (WS.getSize() == nullptr)
1390           report_fatal_error(
1391               "function symbols must have a size set with .size");
1392 
1393         // A definition. Write out the function body.
1394         Index = NumFunctionImports + Functions.size();
1395         WasmFunction Func;
1396         Func.SigIndex = getFunctionType(WS);
1397         Func.Sym = &WS;
1398         WasmIndices[&WS] = Index;
1399         Functions.push_back(Func);
1400 
1401         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1402         if (const MCSymbolWasm *C = Section.getGroup()) {
1403           Comdats[C->getName()].emplace_back(
1404               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1405         }
1406 
1407         if (WS.hasExportName()) {
1408           wasm::WasmExport Export;
1409           Export.Name = WS.getExportName();
1410           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1411           Export.Index = Index;
1412           Exports.push_back(Export);
1413         }
1414       } else {
1415         // An import; the index was assigned above.
1416         Index = WasmIndices.find(&WS)->second;
1417       }
1418 
1419       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1420 
1421     } else if (WS.isData()) {
1422       if (!isInSymtab(WS))
1423         continue;
1424 
1425       if (!WS.isDefined()) {
1426         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1427                           << "\n");
1428         continue;
1429       }
1430 
1431       if (!WS.getSize())
1432         report_fatal_error("data symbols must have a size set with .size: " +
1433                            WS.getName());
1434 
1435       int64_t Size = 0;
1436       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1437         report_fatal_error(".size expression must be evaluatable");
1438 
1439       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1440       if (!DataSection.isWasmData())
1441         report_fatal_error("data symbols must live in a data section: " +
1442                            WS.getName());
1443 
1444       // For each data symbol, export it in the symtab as a reference to the
1445       // corresponding Wasm data segment.
1446       wasm::WasmDataReference Ref = wasm::WasmDataReference{
1447           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
1448           static_cast<uint64_t>(Size)};
1449       DataLocations[&WS] = Ref;
1450       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1451 
1452     } else if (WS.isGlobal()) {
1453       // A "true" Wasm global (currently just __stack_pointer)
1454       if (WS.isDefined()) {
1455         assert(WasmIndices.count(&WS) == 0);
1456         wasm::WasmGlobal Global;
1457         Global.Type = WS.getGlobalType();
1458         Global.Index = NumGlobalImports + Globals.size();
1459         switch (Global.Type.Type) {
1460         case wasm::WASM_TYPE_I32:
1461           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
1462           break;
1463         case wasm::WASM_TYPE_I64:
1464           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
1465           break;
1466         case wasm::WASM_TYPE_F32:
1467           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
1468           break;
1469         case wasm::WASM_TYPE_F64:
1470           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
1471           break;
1472         case wasm::WASM_TYPE_EXTERNREF:
1473           Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
1474           break;
1475         default:
1476           llvm_unreachable("unexpected type");
1477         }
1478         WasmIndices[&WS] = Global.Index;
1479         Globals.push_back(Global);
1480       } else {
1481         // An import; the index was assigned above
1482         LLVM_DEBUG(dbgs() << "  -> global index: "
1483                           << WasmIndices.find(&WS)->second << "\n");
1484       }
1485     } else if (WS.isEvent()) {
1486       // C++ exception symbol (__cpp_exception)
1487       unsigned Index;
1488       if (WS.isDefined()) {
1489         assert(WasmIndices.count(&WS) == 0);
1490         Index = NumEventImports + Events.size();
1491         wasm::WasmEventType Event;
1492         Event.SigIndex = getEventType(WS);
1493         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1494         WasmIndices[&WS] = Index;
1495         Events.push_back(Event);
1496       } else {
1497         // An import; the index was assigned above.
1498         assert(WasmIndices.count(&WS) > 0);
1499       }
1500       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1501                         << "\n");
1502 
1503     } else {
1504       assert(WS.isSection());
1505     }
1506   }
1507 
1508   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1509   // process these in a separate pass because we need to have processed the
1510   // target of the alias before the alias itself and the symbols are not
1511   // necessarily ordered in this way.
1512   for (const MCSymbol &S : Asm.symbols()) {
1513     if (!S.isVariable())
1514       continue;
1515 
1516     assert(S.isDefined());
1517 
1518     const MCSymbolWasm *Base = cast<MCSymbolWasm>(Layout.getBaseSymbol(S));
1519 
1520     // Find the target symbol of this weak alias and export that index
1521     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1522     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n");
1523 
1524     if (Base->isFunction()) {
1525       assert(WasmIndices.count(Base) > 0);
1526       uint32_t WasmIndex = WasmIndices.find(Base)->second;
1527       assert(WasmIndices.count(&WS) == 0);
1528       WasmIndices[&WS] = WasmIndex;
1529       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1530     } else if (Base->isData()) {
1531       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1532       uint64_t Offset = Layout.getSymbolOffset(S);
1533       int64_t Size = 0;
1534       // For data symbol alias we use the size of the base symbol as the
1535       // size of the alias.  When an offset from the base is involved this
1536       // can result in a offset + size goes past the end of the data section
1537       // which out object format doesn't support.  So we must clamp it.
1538       if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
1539         report_fatal_error(".size expression must be evaluatable");
1540       const WasmDataSegment &Segment =
1541           DataSegments[DataSection.getSegmentIndex()];
1542       Size =
1543           std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
1544       wasm::WasmDataReference Ref = wasm::WasmDataReference{
1545           DataSection.getSegmentIndex(),
1546           static_cast<uint32_t>(Layout.getSymbolOffset(S)),
1547           static_cast<uint32_t>(Size)};
1548       DataLocations[&WS] = Ref;
1549       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
1550     } else {
1551       report_fatal_error("don't yet support global/event aliases");
1552     }
1553   }
1554 
1555   // Finally, populate the symbol table itself, in its "natural" order.
1556   for (const MCSymbol &S : Asm.symbols()) {
1557     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1558     if (!isInSymtab(WS)) {
1559       WS.setIndex(InvalidIndex);
1560       continue;
1561     }
1562     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1563 
1564     uint32_t Flags = 0;
1565     if (WS.isWeak())
1566       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1567     if (WS.isHidden())
1568       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1569     if (!WS.isExternal() && WS.isDefined())
1570       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1571     if (WS.isUndefined())
1572       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1573     if (WS.isNoStrip()) {
1574       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1575       if (isEmscripten()) {
1576         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1577       }
1578     }
1579     if (WS.hasImportName())
1580       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1581     if (WS.hasExportName())
1582       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1583 
1584     wasm::WasmSymbolInfo Info;
1585     Info.Name = WS.getName();
1586     Info.Kind = WS.getType();
1587     Info.Flags = Flags;
1588     if (!WS.isData()) {
1589       assert(WasmIndices.count(&WS) > 0);
1590       Info.ElementIndex = WasmIndices.find(&WS)->second;
1591     } else if (WS.isDefined()) {
1592       assert(DataLocations.count(&WS) > 0);
1593       Info.DataRef = DataLocations.find(&WS)->second;
1594     }
1595     WS.setIndex(SymbolInfos.size());
1596     SymbolInfos.emplace_back(Info);
1597   }
1598 
1599   {
1600     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1601       // Functions referenced by a relocation need to put in the table.  This is
1602       // purely to make the object file's provisional values readable, and is
1603       // ignored by the linker, which re-calculates the relocations itself.
1604       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1605           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
1606           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1607           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
1608           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1609         return;
1610       assert(Rel.Symbol->isFunction());
1611       const MCSymbolWasm *Base =
1612           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
1613       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
1614       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1615       if (TableIndices.try_emplace(Base, TableIndex).second) {
1616         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1617                           << " to table: " << TableIndex << "\n");
1618         TableElems.push_back(FunctionIndex);
1619         registerFunctionType(*Base);
1620       }
1621     };
1622 
1623     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1624       HandleReloc(RelEntry);
1625     for (const WasmRelocationEntry &RelEntry : DataRelocations)
1626       HandleReloc(RelEntry);
1627   }
1628 
1629   // Translate .init_array section contents into start functions.
1630   for (const MCSection &S : Asm) {
1631     const auto &WS = static_cast<const MCSectionWasm &>(S);
1632     if (WS.getName().startswith(".fini_array"))
1633       report_fatal_error(".fini_array sections are unsupported");
1634     if (!WS.getName().startswith(".init_array"))
1635       continue;
1636     if (WS.getFragmentList().empty())
1637       continue;
1638 
1639     // init_array is expected to contain a single non-empty data fragment
1640     if (WS.getFragmentList().size() != 3)
1641       report_fatal_error("only one .init_array section fragment supported");
1642 
1643     auto IT = WS.begin();
1644     const MCFragment &EmptyFrag = *IT;
1645     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1646       report_fatal_error(".init_array section should be aligned");
1647 
1648     IT = std::next(IT);
1649     const MCFragment &AlignFrag = *IT;
1650     if (AlignFrag.getKind() != MCFragment::FT_Align)
1651       report_fatal_error(".init_array section should be aligned");
1652     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1653       report_fatal_error(".init_array section should be aligned for pointers");
1654 
1655     const MCFragment &Frag = *std::next(IT);
1656     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1657       report_fatal_error("only data supported in .init_array section");
1658 
1659     uint16_t Priority = UINT16_MAX;
1660     unsigned PrefixLength = strlen(".init_array");
1661     if (WS.getName().size() > PrefixLength) {
1662       if (WS.getName()[PrefixLength] != '.')
1663         report_fatal_error(
1664             ".init_array section priority should start with '.'");
1665       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1666         report_fatal_error("invalid .init_array section priority");
1667     }
1668     const auto &DataFrag = cast<MCDataFragment>(Frag);
1669     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1670     for (const uint8_t *
1671              P = (const uint8_t *)Contents.data(),
1672             *End = (const uint8_t *)Contents.data() + Contents.size();
1673          P != End; ++P) {
1674       if (*P != 0)
1675         report_fatal_error("non-symbolic data in .init_array section");
1676     }
1677     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1678       assert(Fixup.getKind() ==
1679              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1680       const MCExpr *Expr = Fixup.getValue();
1681       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1682       if (!SymRef)
1683         report_fatal_error("fixups in .init_array should be symbol references");
1684       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1685       if (TargetSym.getIndex() == InvalidIndex)
1686         report_fatal_error("symbols in .init_array should exist in symtab");
1687       if (!TargetSym.isFunction())
1688         report_fatal_error("symbols in .init_array should be for functions");
1689       InitFuncs.push_back(
1690           std::make_pair(Priority, TargetSym.getIndex()));
1691     }
1692   }
1693 
1694   // Write out the Wasm header.
1695   writeHeader(Asm);
1696 
1697   writeTypeSection(Signatures);
1698   writeImportSection(Imports, DataSize, TableElems.size());
1699   writeFunctionSection(Functions);
1700   // Skip the "table" section; we import the table instead.
1701   // Skip the "memory" section; we import the memory instead.
1702   writeEventSection(Events);
1703   writeGlobalSection(Globals);
1704   writeExportSection(Exports);
1705   writeElemSection(TableElems);
1706   writeDataCountSection();
1707   uint32_t CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
1708   uint32_t DataSectionIndex = writeDataSection(Layout);
1709   for (auto &CustomSection : CustomSections)
1710     writeCustomSection(CustomSection, Asm, Layout);
1711   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1712   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1713   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1714   writeCustomRelocSections();
1715   if (ProducersSection)
1716     writeCustomSection(*ProducersSection, Asm, Layout);
1717   if (TargetFeaturesSection)
1718     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1719 
1720   // TODO: Translate the .comment section to the output.
1721   return W.OS.tell() - StartOffset;
1722 }
1723 
1724 std::unique_ptr<MCObjectWriter>
1725 llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1726                              raw_pwrite_stream &OS) {
1727   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
1728 }
1729