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 > std::numeric_limits<int32_t>().max()
943                      ? wasm::WASM_OPCODE_I64_CONST
944                      : 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, Layout);
955 
956   endSection(Section);
957   return Section.Index;
958 }
959 
960 void WasmObjectWriter::writeRelocSection(
961     uint32_t SectionIndex, StringRef Name,
962     std::vector<WasmRelocationEntry> &Relocs) {
963   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
964   // for descriptions of the reloc sections.
965 
966   if (Relocs.empty())
967     return;
968 
969   // First, ensure the relocations are sorted in offset order.  In general they
970   // should already be sorted since `recordRelocation` is called in offset
971   // order, but for the code section we combine many MC sections into single
972   // wasm section, and this order is determined by the order of Asm.Symbols()
973   // not the sections order.
974   llvm::stable_sort(
975       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
976         return (A.Offset + A.FixupSection->getSectionOffset()) <
977                (B.Offset + B.FixupSection->getSectionOffset());
978       });
979 
980   SectionBookkeeping Section;
981   startCustomSection(Section, std::string("reloc.") + Name.str());
982 
983   encodeULEB128(SectionIndex, W.OS);
984   encodeULEB128(Relocs.size(), W.OS);
985   for (const WasmRelocationEntry &RelEntry : Relocs) {
986     uint64_t Offset =
987         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
988     uint32_t Index = getRelocationIndexValue(RelEntry);
989 
990     W.OS << char(RelEntry.Type);
991     encodeULEB128(Offset, W.OS);
992     encodeULEB128(Index, W.OS);
993     if (RelEntry.hasAddend())
994       encodeSLEB128(RelEntry.Addend, W.OS);
995   }
996 
997   endSection(Section);
998 }
999 
1000 void WasmObjectWriter::writeCustomRelocSections() {
1001   for (const auto &Sec : CustomSections) {
1002     auto &Relocations = CustomSectionsRelocations[Sec.Section];
1003     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
1004   }
1005 }
1006 
1007 void WasmObjectWriter::writeLinkingMetaDataSection(
1008     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1009     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1010     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
1011   SectionBookkeeping Section;
1012   startCustomSection(Section, "linking");
1013   encodeULEB128(wasm::WasmMetadataVersion, W.OS);
1014 
1015   SectionBookkeeping SubSection;
1016   if (SymbolInfos.size() != 0) {
1017     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
1018     encodeULEB128(SymbolInfos.size(), W.OS);
1019     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
1020       encodeULEB128(Sym.Kind, W.OS);
1021       encodeULEB128(Sym.Flags, W.OS);
1022       switch (Sym.Kind) {
1023       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1024       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1025       case wasm::WASM_SYMBOL_TYPE_EVENT:
1026         encodeULEB128(Sym.ElementIndex, W.OS);
1027         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
1028             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
1029           writeString(Sym.Name);
1030         break;
1031       case wasm::WASM_SYMBOL_TYPE_DATA:
1032         writeString(Sym.Name);
1033         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
1034           encodeULEB128(Sym.DataRef.Segment, W.OS);
1035           encodeULEB128(Sym.DataRef.Offset, W.OS);
1036           encodeULEB128(Sym.DataRef.Size, W.OS);
1037         }
1038         break;
1039       case wasm::WASM_SYMBOL_TYPE_SECTION: {
1040         const uint32_t SectionIndex =
1041             CustomSections[Sym.ElementIndex].OutputIndex;
1042         encodeULEB128(SectionIndex, W.OS);
1043         break;
1044       }
1045       default:
1046         llvm_unreachable("unexpected kind");
1047       }
1048     }
1049     endSection(SubSection);
1050   }
1051 
1052   if (DataSegments.size()) {
1053     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1054     encodeULEB128(DataSegments.size(), W.OS);
1055     for (const WasmDataSegment &Segment : DataSegments) {
1056       writeString(Segment.Name);
1057       encodeULEB128(Segment.Alignment, W.OS);
1058       encodeULEB128(Segment.LinkerFlags, W.OS);
1059     }
1060     endSection(SubSection);
1061   }
1062 
1063   if (!InitFuncs.empty()) {
1064     startSection(SubSection, wasm::WASM_INIT_FUNCS);
1065     encodeULEB128(InitFuncs.size(), W.OS);
1066     for (auto &StartFunc : InitFuncs) {
1067       encodeULEB128(StartFunc.first, W.OS);  // priority
1068       encodeULEB128(StartFunc.second, W.OS); // function index
1069     }
1070     endSection(SubSection);
1071   }
1072 
1073   if (Comdats.size()) {
1074     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1075     encodeULEB128(Comdats.size(), W.OS);
1076     for (const auto &C : Comdats) {
1077       writeString(C.first);
1078       encodeULEB128(0, W.OS); // flags for future use
1079       encodeULEB128(C.second.size(), W.OS);
1080       for (const WasmComdatEntry &Entry : C.second) {
1081         encodeULEB128(Entry.Kind, W.OS);
1082         encodeULEB128(Entry.Index, W.OS);
1083       }
1084     }
1085     endSection(SubSection);
1086   }
1087 
1088   endSection(Section);
1089 }
1090 
1091 void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1092                                           const MCAssembler &Asm,
1093                                           const MCAsmLayout &Layout) {
1094   SectionBookkeeping Section;
1095   auto *Sec = CustomSection.Section;
1096   startCustomSection(Section, CustomSection.Name);
1097 
1098   Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1099   Asm.writeSectionData(W.OS, Sec, Layout);
1100 
1101   CustomSection.OutputContentsOffset = Section.ContentsOffset;
1102   CustomSection.OutputIndex = Section.Index;
1103 
1104   endSection(Section);
1105 
1106   // Apply fixups.
1107   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1108   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
1109 }
1110 
1111 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
1112   assert(Symbol.isFunction());
1113   assert(TypeIndices.count(&Symbol));
1114   return TypeIndices[&Symbol];
1115 }
1116 
1117 uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1118   assert(Symbol.isEvent());
1119   assert(TypeIndices.count(&Symbol));
1120   return TypeIndices[&Symbol];
1121 }
1122 
1123 void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
1124   assert(Symbol.isFunction());
1125 
1126   WasmSignature S;
1127 
1128   if (auto *Sig = Symbol.getSignature()) {
1129     S.Returns = Sig->Returns;
1130     S.Params = Sig->Params;
1131   }
1132 
1133   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1134   if (Pair.second)
1135     Signatures.push_back(S);
1136   TypeIndices[&Symbol] = Pair.first->second;
1137 
1138   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1139                     << " new:" << Pair.second << "\n");
1140   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1141 }
1142 
1143 void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1144   assert(Symbol.isEvent());
1145 
1146   // TODO Currently we don't generate imported exceptions, but if we do, we
1147   // should have a way of infering types of imported exceptions.
1148   WasmSignature S;
1149   if (auto *Sig = Symbol.getSignature()) {
1150     S.Returns = Sig->Returns;
1151     S.Params = Sig->Params;
1152   }
1153 
1154   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1155   if (Pair.second)
1156     Signatures.push_back(S);
1157   TypeIndices[&Symbol] = Pair.first->second;
1158 
1159   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1160                     << "\n");
1161   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1162 }
1163 
1164 static bool isInSymtab(const MCSymbolWasm &Sym) {
1165   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
1166     return true;
1167 
1168   if (Sym.isComdat() && !Sym.isDefined())
1169     return false;
1170 
1171   if (Sym.isTemporary())
1172     return false;
1173 
1174   if (Sym.isSection())
1175     return false;
1176 
1177   return true;
1178 }
1179 
1180 uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1181                                        const MCAsmLayout &Layout) {
1182   uint64_t StartOffset = W.OS.tell();
1183 
1184   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1185 
1186   // Collect information from the available symbols.
1187   SmallVector<WasmFunction, 4> Functions;
1188   SmallVector<uint32_t, 4> TableElems;
1189   SmallVector<wasm::WasmImport, 4> Imports;
1190   SmallVector<wasm::WasmExport, 4> Exports;
1191   SmallVector<wasm::WasmEventType, 1> Events;
1192   SmallVector<wasm::WasmGlobal, 1> Globals;
1193   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1194   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1195   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
1196   uint64_t DataSize = 0;
1197 
1198   // For now, always emit the memory import, since loads and stores are not
1199   // valid without it. In the future, we could perhaps be more clever and omit
1200   // it if there are no loads or stores.
1201   wasm::WasmImport MemImport;
1202   MemImport.Module = "env";
1203   MemImport.Field = "__linear_memory";
1204   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1205   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1206                                      : wasm::WASM_LIMITS_FLAG_NONE;
1207   Imports.push_back(MemImport);
1208 
1209   // For now, always emit the table section, since indirect calls are not
1210   // valid without it. In the future, we could perhaps be more clever and omit
1211   // it if there are no indirect calls.
1212   wasm::WasmImport TableImport;
1213   TableImport.Module = "env";
1214   TableImport.Field = "__indirect_function_table";
1215   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1216   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1217   Imports.push_back(TableImport);
1218 
1219   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1220   // symbols.  This must be done before populating WasmIndices for defined
1221   // symbols.
1222   for (const MCSymbol &S : Asm.symbols()) {
1223     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1224 
1225     // Register types for all functions, including those with private linkage
1226     // (because wasm always needs a type signature).
1227     if (WS.isFunction()) {
1228       const MCSymbolWasm *Base = cast<MCSymbolWasm>(Layout.getBaseSymbol(S));
1229       registerFunctionType(*Base);
1230     }
1231 
1232     if (WS.isEvent())
1233       registerEventType(WS);
1234 
1235     if (WS.isTemporary())
1236       continue;
1237 
1238     // If the symbol is not defined in this translation unit, import it.
1239     if (!WS.isDefined() && !WS.isComdat()) {
1240       if (WS.isFunction()) {
1241         wasm::WasmImport Import;
1242         Import.Module = WS.getImportModule();
1243         Import.Field = WS.getImportName();
1244         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1245         Import.SigIndex = getFunctionType(WS);
1246         Imports.push_back(Import);
1247         assert(WasmIndices.count(&WS) == 0);
1248         WasmIndices[&WS] = NumFunctionImports++;
1249       } else if (WS.isGlobal()) {
1250         if (WS.isWeak())
1251           report_fatal_error("undefined global symbol cannot be weak");
1252 
1253         wasm::WasmImport Import;
1254         Import.Field = WS.getImportName();
1255         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1256         Import.Module = WS.getImportModule();
1257         Import.Global = WS.getGlobalType();
1258         Imports.push_back(Import);
1259         assert(WasmIndices.count(&WS) == 0);
1260         WasmIndices[&WS] = NumGlobalImports++;
1261       } else if (WS.isEvent()) {
1262         if (WS.isWeak())
1263           report_fatal_error("undefined event symbol cannot be weak");
1264 
1265         wasm::WasmImport Import;
1266         Import.Module = WS.getImportModule();
1267         Import.Field = WS.getImportName();
1268         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1269         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1270         Import.Event.SigIndex = getEventType(WS);
1271         Imports.push_back(Import);
1272         assert(WasmIndices.count(&WS) == 0);
1273         WasmIndices[&WS] = NumEventImports++;
1274       }
1275     }
1276   }
1277 
1278   // Add imports for GOT globals
1279   for (const MCSymbol &S : Asm.symbols()) {
1280     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1281     if (WS.isUsedInGOT()) {
1282       wasm::WasmImport Import;
1283       if (WS.isFunction())
1284         Import.Module = "GOT.func";
1285       else
1286         Import.Module = "GOT.mem";
1287       Import.Field = WS.getName();
1288       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1289       Import.Global = {wasm::WASM_TYPE_I32, true};
1290       Imports.push_back(Import);
1291       assert(GOTIndices.count(&WS) == 0);
1292       GOTIndices[&WS] = NumGlobalImports++;
1293     }
1294   }
1295 
1296   // Populate DataSegments and CustomSections, which must be done before
1297   // populating DataLocations.
1298   for (MCSection &Sec : Asm) {
1299     auto &Section = static_cast<MCSectionWasm &>(Sec);
1300     StringRef SectionName = Section.getName();
1301 
1302     // .init_array sections are handled specially elsewhere.
1303     if (SectionName.startswith(".init_array"))
1304       continue;
1305 
1306     // Code is handled separately
1307     if (Section.getKind().isText())
1308       continue;
1309 
1310     if (Section.isWasmData()) {
1311       uint32_t SegmentIndex = DataSegments.size();
1312       DataSize = alignTo(DataSize, Section.getAlignment());
1313       DataSegments.emplace_back();
1314       WasmDataSegment &Segment = DataSegments.back();
1315       Segment.Name = SectionName;
1316       Segment.InitFlags =
1317           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1318       Segment.Offset = DataSize;
1319       Segment.Section = &Section;
1320       addData(Segment.Data, Section);
1321       Segment.Alignment = Log2_32(Section.getAlignment());
1322       Segment.LinkerFlags = 0;
1323       DataSize += Segment.Data.size();
1324       Section.setSegmentIndex(SegmentIndex);
1325 
1326       if (const MCSymbolWasm *C = Section.getGroup()) {
1327         Comdats[C->getName()].emplace_back(
1328             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1329       }
1330     } else {
1331       // Create custom sections
1332       assert(Sec.getKind().isMetadata());
1333 
1334       StringRef Name = SectionName;
1335 
1336       // For user-defined custom sections, strip the prefix
1337       if (Name.startswith(".custom_section."))
1338         Name = Name.substr(strlen(".custom_section."));
1339 
1340       MCSymbol *Begin = Sec.getBeginSymbol();
1341       if (Begin) {
1342         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1343         if (SectionName != Begin->getName())
1344           report_fatal_error("section name and begin symbol should match: " +
1345                              Twine(SectionName));
1346       }
1347 
1348       // Separate out the producers and target features sections
1349       if (Name == "producers") {
1350         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1351         continue;
1352       }
1353       if (Name == "target_features") {
1354         TargetFeaturesSection =
1355             std::make_unique<WasmCustomSection>(Name, &Section);
1356         continue;
1357       }
1358 
1359       CustomSections.emplace_back(Name, &Section);
1360     }
1361   }
1362 
1363   // Populate WasmIndices and DataLocations for defined symbols.
1364   for (const MCSymbol &S : Asm.symbols()) {
1365     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1366     // or used in relocations.
1367     if (S.isTemporary() && S.getName().empty())
1368       continue;
1369 
1370     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1371     LLVM_DEBUG(
1372         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1373                << " isDefined=" << S.isDefined() << " isExternal="
1374                << S.isExternal() << " isTemporary=" << S.isTemporary()
1375                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1376                << " isVariable=" << WS.isVariable() << "\n");
1377 
1378     if (WS.isVariable())
1379       continue;
1380     if (WS.isComdat() && !WS.isDefined())
1381       continue;
1382 
1383     if (WS.isFunction()) {
1384       unsigned Index;
1385       if (WS.isDefined()) {
1386         if (WS.getOffset() != 0)
1387           report_fatal_error(
1388               "function sections must contain one function each");
1389 
1390         if (WS.getSize() == nullptr)
1391           report_fatal_error(
1392               "function symbols must have a size set with .size");
1393 
1394         // A definition. Write out the function body.
1395         Index = NumFunctionImports + Functions.size();
1396         WasmFunction Func;
1397         Func.SigIndex = getFunctionType(WS);
1398         Func.Sym = &WS;
1399         WasmIndices[&WS] = Index;
1400         Functions.push_back(Func);
1401 
1402         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1403         if (const MCSymbolWasm *C = Section.getGroup()) {
1404           Comdats[C->getName()].emplace_back(
1405               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1406         }
1407 
1408         if (WS.hasExportName()) {
1409           wasm::WasmExport Export;
1410           Export.Name = WS.getExportName();
1411           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1412           Export.Index = Index;
1413           Exports.push_back(Export);
1414         }
1415       } else {
1416         // An import; the index was assigned above.
1417         Index = WasmIndices.find(&WS)->second;
1418       }
1419 
1420       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1421 
1422     } else if (WS.isData()) {
1423       if (!isInSymtab(WS))
1424         continue;
1425 
1426       if (!WS.isDefined()) {
1427         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1428                           << "\n");
1429         continue;
1430       }
1431 
1432       if (!WS.getSize())
1433         report_fatal_error("data symbols must have a size set with .size: " +
1434                            WS.getName());
1435 
1436       int64_t Size = 0;
1437       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1438         report_fatal_error(".size expression must be evaluatable");
1439 
1440       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1441       if (!DataSection.isWasmData())
1442         report_fatal_error("data symbols must live in a data section: " +
1443                            WS.getName());
1444 
1445       // For each data symbol, export it in the symtab as a reference to the
1446       // corresponding Wasm data segment.
1447       wasm::WasmDataReference Ref = wasm::WasmDataReference{
1448           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
1449           static_cast<uint64_t>(Size)};
1450       DataLocations[&WS] = Ref;
1451       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1452 
1453     } else if (WS.isGlobal()) {
1454       // A "true" Wasm global (currently just __stack_pointer)
1455       if (WS.isDefined()) {
1456         assert(WasmIndices.count(&WS) == 0);
1457         wasm::WasmGlobal Global;
1458         Global.Type = WS.getGlobalType();
1459         Global.Index = NumGlobalImports + Globals.size();
1460         switch (Global.Type.Type) {
1461         case wasm::WASM_TYPE_I32:
1462           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
1463           break;
1464         case wasm::WASM_TYPE_I64:
1465           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
1466           break;
1467         case wasm::WASM_TYPE_F32:
1468           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
1469           break;
1470         case wasm::WASM_TYPE_F64:
1471           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
1472           break;
1473         case wasm::WASM_TYPE_EXTERNREF:
1474           Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
1475           break;
1476         default:
1477           llvm_unreachable("unexpected type");
1478         }
1479         WasmIndices[&WS] = Global.Index;
1480         Globals.push_back(Global);
1481       } else {
1482         // An import; the index was assigned above
1483         LLVM_DEBUG(dbgs() << "  -> global index: "
1484                           << WasmIndices.find(&WS)->second << "\n");
1485       }
1486     } else if (WS.isEvent()) {
1487       // C++ exception symbol (__cpp_exception)
1488       unsigned Index;
1489       if (WS.isDefined()) {
1490         assert(WasmIndices.count(&WS) == 0);
1491         Index = NumEventImports + Events.size();
1492         wasm::WasmEventType Event;
1493         Event.SigIndex = getEventType(WS);
1494         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1495         WasmIndices[&WS] = Index;
1496         Events.push_back(Event);
1497       } else {
1498         // An import; the index was assigned above.
1499         assert(WasmIndices.count(&WS) > 0);
1500       }
1501       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1502                         << "\n");
1503 
1504     } else {
1505       assert(WS.isSection());
1506     }
1507   }
1508 
1509   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1510   // process these in a separate pass because we need to have processed the
1511   // target of the alias before the alias itself and the symbols are not
1512   // necessarily ordered in this way.
1513   for (const MCSymbol &S : Asm.symbols()) {
1514     if (!S.isVariable())
1515       continue;
1516 
1517     assert(S.isDefined());
1518 
1519     const MCSymbolWasm *Base = cast<MCSymbolWasm>(Layout.getBaseSymbol(S));
1520 
1521     // Find the target symbol of this weak alias and export that index
1522     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1523     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n");
1524 
1525     if (Base->isFunction()) {
1526       assert(WasmIndices.count(Base) > 0);
1527       uint32_t WasmIndex = WasmIndices.find(Base)->second;
1528       assert(WasmIndices.count(&WS) == 0);
1529       WasmIndices[&WS] = WasmIndex;
1530       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1531     } else if (Base->isData()) {
1532       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1533       uint64_t Offset = Layout.getSymbolOffset(S);
1534       int64_t Size = 0;
1535       // For data symbol alias we use the size of the base symbol as the
1536       // size of the alias.  When an offset from the base is involved this
1537       // can result in a offset + size goes past the end of the data section
1538       // which out object format doesn't support.  So we must clamp it.
1539       if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
1540         report_fatal_error(".size expression must be evaluatable");
1541       const WasmDataSegment &Segment =
1542           DataSegments[DataSection.getSegmentIndex()];
1543       Size =
1544           std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
1545       wasm::WasmDataReference Ref = wasm::WasmDataReference{
1546           DataSection.getSegmentIndex(),
1547           static_cast<uint32_t>(Layout.getSymbolOffset(S)),
1548           static_cast<uint32_t>(Size)};
1549       DataLocations[&WS] = Ref;
1550       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
1551     } else {
1552       report_fatal_error("don't yet support global/event aliases");
1553     }
1554   }
1555 
1556   // Finally, populate the symbol table itself, in its "natural" order.
1557   for (const MCSymbol &S : Asm.symbols()) {
1558     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1559     if (!isInSymtab(WS)) {
1560       WS.setIndex(InvalidIndex);
1561       continue;
1562     }
1563     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1564 
1565     uint32_t Flags = 0;
1566     if (WS.isWeak())
1567       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1568     if (WS.isHidden())
1569       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1570     if (!WS.isExternal() && WS.isDefined())
1571       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1572     if (WS.isUndefined())
1573       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1574     if (WS.isNoStrip()) {
1575       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1576       if (isEmscripten()) {
1577         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1578       }
1579     }
1580     if (WS.hasImportName())
1581       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1582     if (WS.hasExportName())
1583       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1584 
1585     wasm::WasmSymbolInfo Info;
1586     Info.Name = WS.getName();
1587     Info.Kind = WS.getType();
1588     Info.Flags = Flags;
1589     if (!WS.isData()) {
1590       assert(WasmIndices.count(&WS) > 0);
1591       Info.ElementIndex = WasmIndices.find(&WS)->second;
1592     } else if (WS.isDefined()) {
1593       assert(DataLocations.count(&WS) > 0);
1594       Info.DataRef = DataLocations.find(&WS)->second;
1595     }
1596     WS.setIndex(SymbolInfos.size());
1597     SymbolInfos.emplace_back(Info);
1598   }
1599 
1600   {
1601     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1602       // Functions referenced by a relocation need to put in the table.  This is
1603       // purely to make the object file's provisional values readable, and is
1604       // ignored by the linker, which re-calculates the relocations itself.
1605       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1606           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
1607           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1608           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
1609           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1610         return;
1611       assert(Rel.Symbol->isFunction());
1612       const MCSymbolWasm *Base =
1613           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
1614       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
1615       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1616       if (TableIndices.try_emplace(Base, TableIndex).second) {
1617         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1618                           << " to table: " << TableIndex << "\n");
1619         TableElems.push_back(FunctionIndex);
1620         registerFunctionType(*Base);
1621       }
1622     };
1623 
1624     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1625       HandleReloc(RelEntry);
1626     for (const WasmRelocationEntry &RelEntry : DataRelocations)
1627       HandleReloc(RelEntry);
1628   }
1629 
1630   // Translate .init_array section contents into start functions.
1631   for (const MCSection &S : Asm) {
1632     const auto &WS = static_cast<const MCSectionWasm &>(S);
1633     if (WS.getName().startswith(".fini_array"))
1634       report_fatal_error(".fini_array sections are unsupported");
1635     if (!WS.getName().startswith(".init_array"))
1636       continue;
1637     if (WS.getFragmentList().empty())
1638       continue;
1639 
1640     // init_array is expected to contain a single non-empty data fragment
1641     if (WS.getFragmentList().size() != 3)
1642       report_fatal_error("only one .init_array section fragment supported");
1643 
1644     auto IT = WS.begin();
1645     const MCFragment &EmptyFrag = *IT;
1646     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1647       report_fatal_error(".init_array section should be aligned");
1648 
1649     IT = std::next(IT);
1650     const MCFragment &AlignFrag = *IT;
1651     if (AlignFrag.getKind() != MCFragment::FT_Align)
1652       report_fatal_error(".init_array section should be aligned");
1653     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1654       report_fatal_error(".init_array section should be aligned for pointers");
1655 
1656     const MCFragment &Frag = *std::next(IT);
1657     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1658       report_fatal_error("only data supported in .init_array section");
1659 
1660     uint16_t Priority = UINT16_MAX;
1661     unsigned PrefixLength = strlen(".init_array");
1662     if (WS.getName().size() > PrefixLength) {
1663       if (WS.getName()[PrefixLength] != '.')
1664         report_fatal_error(
1665             ".init_array section priority should start with '.'");
1666       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1667         report_fatal_error("invalid .init_array section priority");
1668     }
1669     const auto &DataFrag = cast<MCDataFragment>(Frag);
1670     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1671     for (const uint8_t *
1672              P = (const uint8_t *)Contents.data(),
1673             *End = (const uint8_t *)Contents.data() + Contents.size();
1674          P != End; ++P) {
1675       if (*P != 0)
1676         report_fatal_error("non-symbolic data in .init_array section");
1677     }
1678     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1679       assert(Fixup.getKind() ==
1680              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1681       const MCExpr *Expr = Fixup.getValue();
1682       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1683       if (!SymRef)
1684         report_fatal_error("fixups in .init_array should be symbol references");
1685       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1686       if (TargetSym.getIndex() == InvalidIndex)
1687         report_fatal_error("symbols in .init_array should exist in symtab");
1688       if (!TargetSym.isFunction())
1689         report_fatal_error("symbols in .init_array should be for functions");
1690       InitFuncs.push_back(
1691           std::make_pair(Priority, TargetSym.getIndex()));
1692     }
1693   }
1694 
1695   // Write out the Wasm header.
1696   writeHeader(Asm);
1697 
1698   writeTypeSection(Signatures);
1699   writeImportSection(Imports, DataSize, TableElems.size());
1700   writeFunctionSection(Functions);
1701   // Skip the "table" section; we import the table instead.
1702   // Skip the "memory" section; we import the memory instead.
1703   writeEventSection(Events);
1704   writeGlobalSection(Globals);
1705   writeExportSection(Exports);
1706   writeElemSection(TableElems);
1707   writeDataCountSection();
1708   uint32_t CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
1709   uint32_t DataSectionIndex = writeDataSection(Layout);
1710   for (auto &CustomSection : CustomSections)
1711     writeCustomSection(CustomSection, Asm, Layout);
1712   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1713   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1714   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1715   writeCustomRelocSections();
1716   if (ProducersSection)
1717     writeCustomSection(*ProducersSection, Asm, Layout);
1718   if (TargetFeaturesSection)
1719     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1720 
1721   // TODO: Translate the .comment section to the output.
1722   return W.OS.tell() - StartOffset;
1723 }
1724 
1725 std::unique_ptr<MCObjectWriter>
1726 llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1727                              raw_pwrite_stream &OS) {
1728   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
1729 }
1730