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