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   case wasm::R_WASM_TABLE_NUMBER_LEB:
563     // Provisional value is function/global/event Wasm index
564     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
565     return WasmIndices[RelEntry.Symbol];
566   case wasm::R_WASM_FUNCTION_OFFSET_I32:
567   case wasm::R_WASM_SECTION_OFFSET_I32: {
568     const auto &Section =
569         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
570     return Section.getSectionOffset() + RelEntry.Addend;
571   }
572   case wasm::R_WASM_MEMORY_ADDR_LEB:
573   case wasm::R_WASM_MEMORY_ADDR_LEB64:
574   case wasm::R_WASM_MEMORY_ADDR_SLEB:
575   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
576   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
577   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
578   case wasm::R_WASM_MEMORY_ADDR_I32:
579   case wasm::R_WASM_MEMORY_ADDR_I64: {
580     // Provisional value is address of the global plus the offset
581     const MCSymbolWasm *Base =
582         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
583     // For undefined symbols, use zero
584     if (!Base->isDefined())
585       return 0;
586     const wasm::WasmDataReference &BaseRef = DataLocations[Base],
587                                   &SymRef = DataLocations[RelEntry.Symbol];
588     const WasmDataSegment &Segment = DataSegments[BaseRef.Segment];
589     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
590     return Segment.Offset + BaseRef.Offset + SymRef.Offset + RelEntry.Addend;
591   }
592   default:
593     llvm_unreachable("invalid relocation type");
594   }
595 }
596 
597 static void addData(SmallVectorImpl<char> &DataBytes,
598                     MCSectionWasm &DataSection) {
599   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
600 
601   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
602 
603   for (const MCFragment &Frag : DataSection) {
604     if (Frag.hasInstructions())
605       report_fatal_error("only data supported in data sections");
606 
607     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
608       if (Align->getValueSize() != 1)
609         report_fatal_error("only byte values supported for alignment");
610       // If nops are requested, use zeros, as this is the data section.
611       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
612       uint64_t Size =
613           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
614                              DataBytes.size() + Align->getMaxBytesToEmit());
615       DataBytes.resize(Size, Value);
616     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
617       int64_t NumValues;
618       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
619         llvm_unreachable("The fill should be an assembler constant");
620       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
621                        Fill->getValue());
622     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
623       const SmallVectorImpl<char> &Contents = LEB->getContents();
624       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
625     } else {
626       const auto &DataFrag = cast<MCDataFragment>(Frag);
627       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
628       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
629     }
630   }
631 
632   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
633 }
634 
635 uint32_t
636 WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
637   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
638     if (!TypeIndices.count(RelEntry.Symbol))
639       report_fatal_error("symbol not found in type index space: " +
640                          RelEntry.Symbol->getName());
641     return TypeIndices[RelEntry.Symbol];
642   }
643 
644   return RelEntry.Symbol->getIndex();
645 }
646 
647 // Apply the portions of the relocation records that we can handle ourselves
648 // directly.
649 void WasmObjectWriter::applyRelocations(
650     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
651     const MCAsmLayout &Layout) {
652   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
653   for (const WasmRelocationEntry &RelEntry : Relocations) {
654     uint64_t Offset = ContentsOffset +
655                       RelEntry.FixupSection->getSectionOffset() +
656                       RelEntry.Offset;
657 
658     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
659     auto Value = getProvisionalValue(RelEntry, Layout);
660 
661     switch (RelEntry.Type) {
662     case wasm::R_WASM_FUNCTION_INDEX_LEB:
663     case wasm::R_WASM_TYPE_INDEX_LEB:
664     case wasm::R_WASM_GLOBAL_INDEX_LEB:
665     case wasm::R_WASM_MEMORY_ADDR_LEB:
666     case wasm::R_WASM_EVENT_INDEX_LEB:
667     case wasm::R_WASM_TABLE_NUMBER_LEB:
668       writePatchableLEB<5>(Stream, Value, Offset);
669       break;
670     case wasm::R_WASM_MEMORY_ADDR_LEB64:
671       writePatchableLEB<10>(Stream, Value, Offset);
672       break;
673     case wasm::R_WASM_TABLE_INDEX_I32:
674     case wasm::R_WASM_MEMORY_ADDR_I32:
675     case wasm::R_WASM_FUNCTION_OFFSET_I32:
676     case wasm::R_WASM_SECTION_OFFSET_I32:
677     case wasm::R_WASM_GLOBAL_INDEX_I32:
678       patchI32(Stream, Value, Offset);
679       break;
680     case wasm::R_WASM_TABLE_INDEX_I64:
681     case wasm::R_WASM_MEMORY_ADDR_I64:
682       patchI64(Stream, Value, Offset);
683       break;
684     case wasm::R_WASM_TABLE_INDEX_SLEB:
685     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
686     case wasm::R_WASM_MEMORY_ADDR_SLEB:
687     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
688       writePatchableSLEB<5>(Stream, Value, Offset);
689       break;
690     case wasm::R_WASM_TABLE_INDEX_SLEB64:
691     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
692     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
693       writePatchableSLEB<10>(Stream, Value, Offset);
694       break;
695     default:
696       llvm_unreachable("invalid relocation type");
697     }
698   }
699 }
700 
701 void WasmObjectWriter::writeTypeSection(
702     ArrayRef<wasm::WasmSignature> Signatures) {
703   if (Signatures.empty())
704     return;
705 
706   SectionBookkeeping Section;
707   startSection(Section, wasm::WASM_SEC_TYPE);
708 
709   encodeULEB128(Signatures.size(), W->OS);
710 
711   for (const wasm::WasmSignature &Sig : Signatures) {
712     W->OS << char(wasm::WASM_TYPE_FUNC);
713     encodeULEB128(Sig.Params.size(), W->OS);
714     for (wasm::ValType Ty : Sig.Params)
715       writeValueType(Ty);
716     encodeULEB128(Sig.Returns.size(), W->OS);
717     for (wasm::ValType Ty : Sig.Returns)
718       writeValueType(Ty);
719   }
720 
721   endSection(Section);
722 }
723 
724 void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
725                                           uint64_t DataSize,
726                                           uint32_t NumElements) {
727   if (Imports.empty())
728     return;
729 
730   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
731 
732   SectionBookkeeping Section;
733   startSection(Section, wasm::WASM_SEC_IMPORT);
734 
735   encodeULEB128(Imports.size(), W->OS);
736   for (const wasm::WasmImport &Import : Imports) {
737     writeString(Import.Module);
738     writeString(Import.Field);
739     W->OS << char(Import.Kind);
740 
741     switch (Import.Kind) {
742     case wasm::WASM_EXTERNAL_FUNCTION:
743       encodeULEB128(Import.SigIndex, W->OS);
744       break;
745     case wasm::WASM_EXTERNAL_GLOBAL:
746       W->OS << char(Import.Global.Type);
747       W->OS << char(Import.Global.Mutable ? 1 : 0);
748       break;
749     case wasm::WASM_EXTERNAL_MEMORY:
750       encodeULEB128(Import.Memory.Flags, W->OS);
751       encodeULEB128(NumPages, W->OS); // initial
752       break;
753     case wasm::WASM_EXTERNAL_TABLE:
754       W->OS << char(Import.Table.ElemType);
755       encodeULEB128(0, W->OS);           // flags
756       encodeULEB128(NumElements, W->OS); // initial
757       break;
758     case wasm::WASM_EXTERNAL_EVENT:
759       encodeULEB128(Import.Event.Attribute, W->OS);
760       encodeULEB128(Import.Event.SigIndex, W->OS);
761       break;
762     default:
763       llvm_unreachable("unsupported import kind");
764     }
765   }
766 
767   endSection(Section);
768 }
769 
770 void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
771   if (Functions.empty())
772     return;
773 
774   SectionBookkeeping Section;
775   startSection(Section, wasm::WASM_SEC_FUNCTION);
776 
777   encodeULEB128(Functions.size(), W->OS);
778   for (const WasmFunction &Func : Functions)
779     encodeULEB128(Func.SigIndex, W->OS);
780 
781   endSection(Section);
782 }
783 
784 void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
785   if (Events.empty())
786     return;
787 
788   SectionBookkeeping Section;
789   startSection(Section, wasm::WASM_SEC_EVENT);
790 
791   encodeULEB128(Events.size(), W->OS);
792   for (const wasm::WasmEventType &Event : Events) {
793     encodeULEB128(Event.Attribute, W->OS);
794     encodeULEB128(Event.SigIndex, W->OS);
795   }
796 
797   endSection(Section);
798 }
799 
800 void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
801   if (Globals.empty())
802     return;
803 
804   SectionBookkeeping Section;
805   startSection(Section, wasm::WASM_SEC_GLOBAL);
806 
807   encodeULEB128(Globals.size(), W->OS);
808   for (const wasm::WasmGlobal &Global : Globals) {
809     encodeULEB128(Global.Type.Type, W->OS);
810     W->OS << char(Global.Type.Mutable);
811     W->OS << char(Global.InitExpr.Opcode);
812     switch (Global.Type.Type) {
813     case wasm::WASM_TYPE_I32:
814       encodeSLEB128(0, W->OS);
815       break;
816     case wasm::WASM_TYPE_I64:
817       encodeSLEB128(0, W->OS);
818       break;
819     case wasm::WASM_TYPE_F32:
820       writeI32(0);
821       break;
822     case wasm::WASM_TYPE_F64:
823       writeI64(0);
824       break;
825     case wasm::WASM_TYPE_EXTERNREF:
826       writeValueType(wasm::ValType::EXTERNREF);
827       break;
828     default:
829       llvm_unreachable("unexpected type");
830     }
831     W->OS << char(wasm::WASM_OPCODE_END);
832   }
833 
834   endSection(Section);
835 }
836 
837 void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
838   if (Tables.empty())
839     return;
840 
841   SectionBookkeeping Section;
842   startSection(Section, wasm::WASM_SEC_TABLE);
843 
844   encodeULEB128(Tables.size(), W->OS);
845   for (const wasm::WasmTable &Table : Tables) {
846     encodeULEB128(Table.ElemType, W->OS);
847     encodeULEB128(Table.Limits.Flags, W->OS);
848     encodeULEB128(Table.Limits.Initial, W->OS);
849     if (Table.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
850       encodeULEB128(Table.Limits.Maximum, W->OS);
851   }
852   endSection(Section);
853 }
854 
855 void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
856   if (Exports.empty())
857     return;
858 
859   SectionBookkeeping Section;
860   startSection(Section, wasm::WASM_SEC_EXPORT);
861 
862   encodeULEB128(Exports.size(), W->OS);
863   for (const wasm::WasmExport &Export : Exports) {
864     writeString(Export.Name);
865     W->OS << char(Export.Kind);
866     encodeULEB128(Export.Index, W->OS);
867   }
868 
869   endSection(Section);
870 }
871 
872 void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
873   if (TableElems.empty())
874     return;
875 
876   SectionBookkeeping Section;
877   startSection(Section, wasm::WASM_SEC_ELEM);
878 
879   encodeULEB128(1, W->OS); // number of "segments"
880   encodeULEB128(0, W->OS); // the table index
881 
882   // init expr for starting offset
883   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
884   encodeSLEB128(InitialTableOffset, W->OS);
885   W->OS << char(wasm::WASM_OPCODE_END);
886 
887   encodeULEB128(TableElems.size(), W->OS);
888   for (uint32_t Elem : TableElems)
889     encodeULEB128(Elem, W->OS);
890 
891   endSection(Section);
892 }
893 
894 void WasmObjectWriter::writeDataCountSection() {
895   if (DataSegments.empty())
896     return;
897 
898   SectionBookkeeping Section;
899   startSection(Section, wasm::WASM_SEC_DATACOUNT);
900   encodeULEB128(DataSegments.size(), W->OS);
901   endSection(Section);
902 }
903 
904 uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
905                                             const MCAsmLayout &Layout,
906                                             ArrayRef<WasmFunction> Functions) {
907   if (Functions.empty())
908     return 0;
909 
910   SectionBookkeeping Section;
911   startSection(Section, wasm::WASM_SEC_CODE);
912 
913   encodeULEB128(Functions.size(), W->OS);
914 
915   for (const WasmFunction &Func : Functions) {
916     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
917 
918     int64_t Size = 0;
919     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
920       report_fatal_error(".size expression must be evaluatable");
921 
922     encodeULEB128(Size, W->OS);
923     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
924     Asm.writeSectionData(W->OS, &FuncSection, Layout);
925   }
926 
927   // Apply fixups.
928   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
929 
930   endSection(Section);
931   return Section.Index;
932 }
933 
934 uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
935   if (DataSegments.empty())
936     return 0;
937 
938   SectionBookkeeping Section;
939   startSection(Section, wasm::WASM_SEC_DATA);
940 
941   encodeULEB128(DataSegments.size(), W->OS); // count
942 
943   for (const WasmDataSegment &Segment : DataSegments) {
944     encodeULEB128(Segment.InitFlags, W->OS); // flags
945     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
946       encodeULEB128(0, W->OS); // memory index
947     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
948       W->OS << char(Segment.Offset > INT32_MAX ? wasm::WASM_OPCODE_I64_CONST
949                                                : wasm::WASM_OPCODE_I32_CONST);
950       encodeSLEB128(Segment.Offset, W->OS); // offset
951       W->OS << char(wasm::WASM_OPCODE_END);
952     }
953     encodeULEB128(Segment.Data.size(), W->OS); // size
954     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
955     W->OS << Segment.Data; // data
956   }
957 
958   // Apply fixups.
959   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
960 
961   endSection(Section);
962   return Section.Index;
963 }
964 
965 void WasmObjectWriter::writeRelocSection(
966     uint32_t SectionIndex, StringRef Name,
967     std::vector<WasmRelocationEntry> &Relocs) {
968   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
969   // for descriptions of the reloc sections.
970 
971   if (Relocs.empty())
972     return;
973 
974   // First, ensure the relocations are sorted in offset order.  In general they
975   // should already be sorted since `recordRelocation` is called in offset
976   // order, but for the code section we combine many MC sections into single
977   // wasm section, and this order is determined by the order of Asm.Symbols()
978   // not the sections order.
979   llvm::stable_sort(
980       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
981         return (A.Offset + A.FixupSection->getSectionOffset()) <
982                (B.Offset + B.FixupSection->getSectionOffset());
983       });
984 
985   SectionBookkeeping Section;
986   startCustomSection(Section, std::string("reloc.") + Name.str());
987 
988   encodeULEB128(SectionIndex, W->OS);
989   encodeULEB128(Relocs.size(), W->OS);
990   for (const WasmRelocationEntry &RelEntry : Relocs) {
991     uint64_t Offset =
992         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
993     uint32_t Index = getRelocationIndexValue(RelEntry);
994 
995     W->OS << char(RelEntry.Type);
996     encodeULEB128(Offset, W->OS);
997     encodeULEB128(Index, W->OS);
998     if (RelEntry.hasAddend())
999       encodeSLEB128(RelEntry.Addend, W->OS);
1000   }
1001 
1002   endSection(Section);
1003 }
1004 
1005 void WasmObjectWriter::writeCustomRelocSections() {
1006   for (const auto &Sec : CustomSections) {
1007     auto &Relocations = CustomSectionsRelocations[Sec.Section];
1008     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
1009   }
1010 }
1011 
1012 void WasmObjectWriter::writeLinkingMetaDataSection(
1013     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1014     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1015     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
1016   SectionBookkeeping Section;
1017   startCustomSection(Section, "linking");
1018   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
1019 
1020   SectionBookkeeping SubSection;
1021   if (SymbolInfos.size() != 0) {
1022     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
1023     encodeULEB128(SymbolInfos.size(), W->OS);
1024     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
1025       encodeULEB128(Sym.Kind, W->OS);
1026       encodeULEB128(Sym.Flags, W->OS);
1027       switch (Sym.Kind) {
1028       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1029       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1030       case wasm::WASM_SYMBOL_TYPE_EVENT:
1031       case wasm::WASM_SYMBOL_TYPE_TABLE:
1032         encodeULEB128(Sym.ElementIndex, W->OS);
1033         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
1034             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
1035           writeString(Sym.Name);
1036         break;
1037       case wasm::WASM_SYMBOL_TYPE_DATA:
1038         writeString(Sym.Name);
1039         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
1040           encodeULEB128(Sym.DataRef.Segment, W->OS);
1041           encodeULEB128(Sym.DataRef.Offset, W->OS);
1042           encodeULEB128(Sym.DataRef.Size, W->OS);
1043         }
1044         break;
1045       case wasm::WASM_SYMBOL_TYPE_SECTION: {
1046         const uint32_t SectionIndex =
1047             CustomSections[Sym.ElementIndex].OutputIndex;
1048         encodeULEB128(SectionIndex, W->OS);
1049         break;
1050       }
1051       default:
1052         llvm_unreachable("unexpected kind");
1053       }
1054     }
1055     endSection(SubSection);
1056   }
1057 
1058   if (DataSegments.size()) {
1059     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1060     encodeULEB128(DataSegments.size(), W->OS);
1061     for (const WasmDataSegment &Segment : DataSegments) {
1062       writeString(Segment.Name);
1063       encodeULEB128(Segment.Alignment, W->OS);
1064       encodeULEB128(Segment.LinkerFlags, W->OS);
1065     }
1066     endSection(SubSection);
1067   }
1068 
1069   if (!InitFuncs.empty()) {
1070     startSection(SubSection, wasm::WASM_INIT_FUNCS);
1071     encodeULEB128(InitFuncs.size(), W->OS);
1072     for (auto &StartFunc : InitFuncs) {
1073       encodeULEB128(StartFunc.first, W->OS);  // priority
1074       encodeULEB128(StartFunc.second, W->OS); // function index
1075     }
1076     endSection(SubSection);
1077   }
1078 
1079   if (Comdats.size()) {
1080     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1081     encodeULEB128(Comdats.size(), W->OS);
1082     for (const auto &C : Comdats) {
1083       writeString(C.first);
1084       encodeULEB128(0, W->OS); // flags for future use
1085       encodeULEB128(C.second.size(), W->OS);
1086       for (const WasmComdatEntry &Entry : C.second) {
1087         encodeULEB128(Entry.Kind, W->OS);
1088         encodeULEB128(Entry.Index, W->OS);
1089       }
1090     }
1091     endSection(SubSection);
1092   }
1093 
1094   endSection(Section);
1095 }
1096 
1097 void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1098                                           const MCAssembler &Asm,
1099                                           const MCAsmLayout &Layout) {
1100   SectionBookkeeping Section;
1101   auto *Sec = CustomSection.Section;
1102   startCustomSection(Section, CustomSection.Name);
1103 
1104   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
1105   Asm.writeSectionData(W->OS, Sec, Layout);
1106 
1107   CustomSection.OutputContentsOffset = Section.ContentsOffset;
1108   CustomSection.OutputIndex = Section.Index;
1109 
1110   endSection(Section);
1111 
1112   // Apply fixups.
1113   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1114   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
1115 }
1116 
1117 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
1118   assert(Symbol.isFunction());
1119   assert(TypeIndices.count(&Symbol));
1120   return TypeIndices[&Symbol];
1121 }
1122 
1123 uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1124   assert(Symbol.isEvent());
1125   assert(TypeIndices.count(&Symbol));
1126   return TypeIndices[&Symbol];
1127 }
1128 
1129 void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
1130   assert(Symbol.isFunction());
1131 
1132   wasm::WasmSignature S;
1133 
1134   if (auto *Sig = Symbol.getSignature()) {
1135     S.Returns = Sig->Returns;
1136     S.Params = Sig->Params;
1137   }
1138 
1139   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1140   if (Pair.second)
1141     Signatures.push_back(S);
1142   TypeIndices[&Symbol] = Pair.first->second;
1143 
1144   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1145                     << " new:" << Pair.second << "\n");
1146   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1147 }
1148 
1149 void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1150   assert(Symbol.isEvent());
1151 
1152   // TODO Currently we don't generate imported exceptions, but if we do, we
1153   // should have a way of infering types of imported exceptions.
1154   wasm::WasmSignature S;
1155   if (auto *Sig = Symbol.getSignature()) {
1156     S.Returns = Sig->Returns;
1157     S.Params = Sig->Params;
1158   }
1159 
1160   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1161   if (Pair.second)
1162     Signatures.push_back(S);
1163   TypeIndices[&Symbol] = Pair.first->second;
1164 
1165   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1166                     << "\n");
1167   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1168 }
1169 
1170 static bool isInSymtab(const MCSymbolWasm &Sym) {
1171   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
1172     return true;
1173 
1174   if (Sym.isComdat() && !Sym.isDefined())
1175     return false;
1176 
1177   if (Sym.isTemporary())
1178     return false;
1179 
1180   if (Sym.isSection())
1181     return false;
1182 
1183   return true;
1184 }
1185 void WasmObjectWriter::prepareImports(
1186     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
1187     const MCAsmLayout &Layout) {
1188   // For now, always emit the memory import, since loads and stores are not
1189   // valid without it. In the future, we could perhaps be more clever and omit
1190   // it if there are no loads or stores.
1191   wasm::WasmImport MemImport;
1192   MemImport.Module = "env";
1193   MemImport.Field = "__linear_memory";
1194   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1195   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1196                                      : wasm::WASM_LIMITS_FLAG_NONE;
1197   Imports.push_back(MemImport);
1198 
1199   // For now, always emit the table section, since indirect calls are not
1200   // valid without it. In the future, we could perhaps be more clever and omit
1201   // it if there are no indirect calls.
1202   wasm::WasmImport TableImport;
1203   TableImport.Module = "env";
1204   TableImport.Field = "__indirect_function_table";
1205   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1206   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1207   Imports.push_back(TableImport);
1208 
1209   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1210   // symbols.  This must be done before populating WasmIndices for defined
1211   // symbols.
1212   for (const MCSymbol &S : Asm.symbols()) {
1213     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1214 
1215     // Register types for all functions, including those with private linkage
1216     // (because wasm always needs a type signature).
1217     if (WS.isFunction()) {
1218       const auto *BS = Layout.getBaseSymbol(S);
1219       if (!BS)
1220         report_fatal_error(Twine(S.getName()) +
1221                            ": absolute addressing not supported!");
1222       registerFunctionType(*cast<MCSymbolWasm>(BS));
1223     }
1224 
1225     if (WS.isEvent())
1226       registerEventType(WS);
1227 
1228     if (WS.isTemporary())
1229       continue;
1230 
1231     // If the symbol is not defined in this translation unit, import it.
1232     if (!WS.isDefined() && !WS.isComdat()) {
1233       if (WS.isFunction()) {
1234         wasm::WasmImport Import;
1235         Import.Module = WS.getImportModule();
1236         Import.Field = WS.getImportName();
1237         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1238         Import.SigIndex = getFunctionType(WS);
1239         Imports.push_back(Import);
1240         assert(WasmIndices.count(&WS) == 0);
1241         WasmIndices[&WS] = NumFunctionImports++;
1242       } else if (WS.isGlobal()) {
1243         if (WS.isWeak())
1244           report_fatal_error("undefined global symbol cannot be weak");
1245 
1246         wasm::WasmImport Import;
1247         Import.Field = WS.getImportName();
1248         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1249         Import.Module = WS.getImportModule();
1250         Import.Global = WS.getGlobalType();
1251         Imports.push_back(Import);
1252         assert(WasmIndices.count(&WS) == 0);
1253         WasmIndices[&WS] = NumGlobalImports++;
1254       } else if (WS.isEvent()) {
1255         if (WS.isWeak())
1256           report_fatal_error("undefined event symbol cannot be weak");
1257 
1258         wasm::WasmImport Import;
1259         Import.Module = WS.getImportModule();
1260         Import.Field = WS.getImportName();
1261         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1262         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1263         Import.Event.SigIndex = getEventType(WS);
1264         Imports.push_back(Import);
1265         assert(WasmIndices.count(&WS) == 0);
1266         WasmIndices[&WS] = NumEventImports++;
1267       }
1268     }
1269   }
1270 
1271   // Add imports for GOT globals
1272   for (const MCSymbol &S : Asm.symbols()) {
1273     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1274     if (WS.isUsedInGOT()) {
1275       wasm::WasmImport Import;
1276       if (WS.isFunction())
1277         Import.Module = "GOT.func";
1278       else
1279         Import.Module = "GOT.mem";
1280       Import.Field = WS.getName();
1281       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1282       Import.Global = {wasm::WASM_TYPE_I32, true};
1283       Imports.push_back(Import);
1284       assert(GOTIndices.count(&WS) == 0);
1285       GOTIndices[&WS] = NumGlobalImports++;
1286     }
1287   }
1288 }
1289 
1290 uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1291                                        const MCAsmLayout &Layout) {
1292   support::endian::Writer MainWriter(*OS, support::little);
1293   W = &MainWriter;
1294   if (IsSplitDwarf) {
1295     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
1296     assert(DwoOS);
1297     support::endian::Writer DwoWriter(*DwoOS, support::little);
1298     W = &DwoWriter;
1299     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
1300   } else {
1301     return writeOneObject(Asm, Layout, DwoMode::AllSections);
1302   }
1303 }
1304 
1305 uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
1306                                           const MCAsmLayout &Layout,
1307                                           DwoMode Mode) {
1308   uint64_t StartOffset = W->OS.tell();
1309   SectionCount = 0;
1310   CustomSections.clear();
1311 
1312   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1313 
1314   // Collect information from the available symbols.
1315   SmallVector<WasmFunction, 4> Functions;
1316   SmallVector<uint32_t, 4> TableElems;
1317   SmallVector<wasm::WasmImport, 4> Imports;
1318   SmallVector<wasm::WasmExport, 4> Exports;
1319   SmallVector<wasm::WasmEventType, 1> Events;
1320   SmallVector<wasm::WasmGlobal, 1> Globals;
1321   SmallVector<wasm::WasmTable, 1> Tables;
1322   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1323   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1324   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
1325   uint64_t DataSize = 0;
1326   if (Mode != DwoMode::DwoOnly) {
1327     prepareImports(Imports, Asm, Layout);
1328   }
1329   // Populate DataSegments and CustomSections, which must be done before
1330   // populating DataLocations.
1331   for (MCSection &Sec : Asm) {
1332     auto &Section = static_cast<MCSectionWasm &>(Sec);
1333     StringRef SectionName = Section.getName();
1334 
1335     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
1336       continue;
1337     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
1338       continue;
1339 
1340     // .init_array sections are handled specially elsewhere.
1341     if (SectionName.startswith(".init_array"))
1342       continue;
1343 
1344     // Code is handled separately
1345     if (Section.getKind().isText())
1346       continue;
1347 
1348     if (Section.isWasmData()) {
1349       uint32_t SegmentIndex = DataSegments.size();
1350       DataSize = alignTo(DataSize, Section.getAlignment());
1351       DataSegments.emplace_back();
1352       WasmDataSegment &Segment = DataSegments.back();
1353       Segment.Name = SectionName;
1354       Segment.InitFlags =
1355           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1356       Segment.Offset = DataSize;
1357       Segment.Section = &Section;
1358       addData(Segment.Data, Section);
1359       Segment.Alignment = Log2_32(Section.getAlignment());
1360       Segment.LinkerFlags = 0;
1361       DataSize += Segment.Data.size();
1362       Section.setSegmentIndex(SegmentIndex);
1363 
1364       if (const MCSymbolWasm *C = Section.getGroup()) {
1365         Comdats[C->getName()].emplace_back(
1366             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1367       }
1368     } else {
1369       // Create custom sections
1370       assert(Sec.getKind().isMetadata());
1371 
1372       StringRef Name = SectionName;
1373 
1374       // For user-defined custom sections, strip the prefix
1375       if (Name.startswith(".custom_section."))
1376         Name = Name.substr(strlen(".custom_section."));
1377 
1378       MCSymbol *Begin = Sec.getBeginSymbol();
1379       if (Begin) {
1380         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1381       }
1382 
1383       // Separate out the producers and target features sections
1384       if (Name == "producers") {
1385         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1386         continue;
1387       }
1388       if (Name == "target_features") {
1389         TargetFeaturesSection =
1390             std::make_unique<WasmCustomSection>(Name, &Section);
1391         continue;
1392       }
1393 
1394       CustomSections.emplace_back(Name, &Section);
1395     }
1396   }
1397 
1398   // Populate WasmIndices and DataLocations for defined symbols.
1399   for (const MCSymbol &S : Asm.symbols()) {
1400     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1401     // or used in relocations.
1402     if (S.isTemporary() && S.getName().empty())
1403       continue;
1404 
1405     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1406     LLVM_DEBUG(
1407         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1408                << " isDefined=" << S.isDefined() << " isExternal="
1409                << S.isExternal() << " isTemporary=" << S.isTemporary()
1410                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1411                << " isVariable=" << WS.isVariable() << "\n");
1412 
1413     if (WS.isVariable())
1414       continue;
1415     if (WS.isComdat() && !WS.isDefined())
1416       continue;
1417 
1418     if (WS.isFunction()) {
1419       unsigned Index;
1420       if (WS.isDefined()) {
1421         if (WS.getOffset() != 0)
1422           report_fatal_error(
1423               "function sections must contain one function each");
1424 
1425         if (WS.getSize() == nullptr)
1426           report_fatal_error(
1427               "function symbols must have a size set with .size");
1428 
1429         // A definition. Write out the function body.
1430         Index = NumFunctionImports + Functions.size();
1431         WasmFunction Func;
1432         Func.SigIndex = getFunctionType(WS);
1433         Func.Sym = &WS;
1434         WasmIndices[&WS] = Index;
1435         Functions.push_back(Func);
1436 
1437         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1438         if (const MCSymbolWasm *C = Section.getGroup()) {
1439           Comdats[C->getName()].emplace_back(
1440               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1441         }
1442 
1443         if (WS.hasExportName()) {
1444           wasm::WasmExport Export;
1445           Export.Name = WS.getExportName();
1446           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1447           Export.Index = Index;
1448           Exports.push_back(Export);
1449         }
1450       } else {
1451         // An import; the index was assigned above.
1452         Index = WasmIndices.find(&WS)->second;
1453       }
1454 
1455       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1456 
1457     } else if (WS.isData()) {
1458       if (!isInSymtab(WS))
1459         continue;
1460 
1461       if (!WS.isDefined()) {
1462         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1463                           << "\n");
1464         continue;
1465       }
1466 
1467       if (!WS.getSize())
1468         report_fatal_error("data symbols must have a size set with .size: " +
1469                            WS.getName());
1470 
1471       int64_t Size = 0;
1472       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1473         report_fatal_error(".size expression must be evaluatable");
1474 
1475       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1476       if (!DataSection.isWasmData())
1477         report_fatal_error("data symbols must live in a data section: " +
1478                            WS.getName());
1479 
1480       // For each data symbol, export it in the symtab as a reference to the
1481       // corresponding Wasm data segment.
1482       wasm::WasmDataReference Ref = wasm::WasmDataReference{
1483           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
1484           static_cast<uint64_t>(Size)};
1485       DataLocations[&WS] = Ref;
1486       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1487 
1488     } else if (WS.isGlobal()) {
1489       // A "true" Wasm global (currently just __stack_pointer)
1490       if (WS.isDefined()) {
1491         assert(WasmIndices.count(&WS) == 0);
1492         wasm::WasmGlobal Global;
1493         Global.Type = WS.getGlobalType();
1494         Global.Index = NumGlobalImports + Globals.size();
1495         switch (Global.Type.Type) {
1496         case wasm::WASM_TYPE_I32:
1497           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
1498           break;
1499         case wasm::WASM_TYPE_I64:
1500           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
1501           break;
1502         case wasm::WASM_TYPE_F32:
1503           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
1504           break;
1505         case wasm::WASM_TYPE_F64:
1506           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
1507           break;
1508         case wasm::WASM_TYPE_EXTERNREF:
1509           Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
1510           break;
1511         default:
1512           llvm_unreachable("unexpected type");
1513         }
1514         WasmIndices[&WS] = Global.Index;
1515         Globals.push_back(Global);
1516       } else {
1517         // An import; the index was assigned above
1518         LLVM_DEBUG(dbgs() << "  -> global index: "
1519                           << WasmIndices.find(&WS)->second << "\n");
1520       }
1521     } else if (WS.isTable()) {
1522       if (WS.isDefined()) {
1523         assert(WasmIndices.count(&WS) == 0);
1524         wasm::WasmTable Table;
1525         Table.ElemType = static_cast<uint8_t>(WS.getTableType());
1526         Table.Index = NumTableImports + Tables.size();
1527         // FIXME: Work on custom limits is ongoing
1528         Table.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1529 
1530         WasmIndices[&WS] = Table.Index;
1531         Tables.push_back(Table);
1532       }
1533       LLVM_DEBUG(dbgs() << " -> table index: " << WasmIndices.find(&WS)->second
1534                         << "\n");
1535     } else if (WS.isEvent()) {
1536       // C++ exception symbol (__cpp_exception)
1537       unsigned Index;
1538       if (WS.isDefined()) {
1539         assert(WasmIndices.count(&WS) == 0);
1540         Index = NumEventImports + Events.size();
1541         wasm::WasmEventType Event;
1542         Event.SigIndex = getEventType(WS);
1543         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1544         WasmIndices[&WS] = Index;
1545         Events.push_back(Event);
1546       } else {
1547         // An import; the index was assigned above.
1548         assert(WasmIndices.count(&WS) > 0);
1549       }
1550       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1551                         << "\n");
1552 
1553     } else {
1554       assert(WS.isSection());
1555     }
1556   }
1557 
1558   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1559   // process these in a separate pass because we need to have processed the
1560   // target of the alias before the alias itself and the symbols are not
1561   // necessarily ordered in this way.
1562   for (const MCSymbol &S : Asm.symbols()) {
1563     if (!S.isVariable())
1564       continue;
1565 
1566     assert(S.isDefined());
1567 
1568     const auto *BS = Layout.getBaseSymbol(S);
1569     if (!BS)
1570       report_fatal_error(Twine(S.getName()) +
1571                          ": absolute addressing not supported!");
1572     const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
1573 
1574     // Find the target symbol of this weak alias and export that index
1575     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1576     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n");
1577 
1578     if (Base->isFunction()) {
1579       assert(WasmIndices.count(Base) > 0);
1580       uint32_t WasmIndex = WasmIndices.find(Base)->second;
1581       assert(WasmIndices.count(&WS) == 0);
1582       WasmIndices[&WS] = WasmIndex;
1583       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1584     } else if (Base->isData()) {
1585       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1586       uint64_t Offset = Layout.getSymbolOffset(S);
1587       int64_t Size = 0;
1588       // For data symbol alias we use the size of the base symbol as the
1589       // size of the alias.  When an offset from the base is involved this
1590       // can result in a offset + size goes past the end of the data section
1591       // which out object format doesn't support.  So we must clamp it.
1592       if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
1593         report_fatal_error(".size expression must be evaluatable");
1594       const WasmDataSegment &Segment =
1595           DataSegments[DataSection.getSegmentIndex()];
1596       Size =
1597           std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
1598       wasm::WasmDataReference Ref = wasm::WasmDataReference{
1599           DataSection.getSegmentIndex(),
1600           static_cast<uint32_t>(Layout.getSymbolOffset(S)),
1601           static_cast<uint32_t>(Size)};
1602       DataLocations[&WS] = Ref;
1603       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
1604     } else {
1605       report_fatal_error("don't yet support global/event aliases");
1606     }
1607   }
1608 
1609   // Finally, populate the symbol table itself, in its "natural" order.
1610   for (const MCSymbol &S : Asm.symbols()) {
1611     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1612     if (!isInSymtab(WS)) {
1613       WS.setIndex(InvalidIndex);
1614       continue;
1615     }
1616     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1617 
1618     uint32_t Flags = 0;
1619     if (WS.isWeak())
1620       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1621     if (WS.isHidden())
1622       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1623     if (!WS.isExternal() && WS.isDefined())
1624       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1625     if (WS.isUndefined())
1626       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1627     if (WS.isNoStrip()) {
1628       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1629       if (isEmscripten()) {
1630         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1631       }
1632     }
1633     if (WS.hasImportName())
1634       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1635     if (WS.hasExportName())
1636       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1637 
1638     wasm::WasmSymbolInfo Info;
1639     Info.Name = WS.getName();
1640     Info.Kind = WS.getType();
1641     Info.Flags = Flags;
1642     if (!WS.isData()) {
1643       assert(WasmIndices.count(&WS) > 0);
1644       Info.ElementIndex = WasmIndices.find(&WS)->second;
1645     } else if (WS.isDefined()) {
1646       assert(DataLocations.count(&WS) > 0);
1647       Info.DataRef = DataLocations.find(&WS)->second;
1648     }
1649     WS.setIndex(SymbolInfos.size());
1650     SymbolInfos.emplace_back(Info);
1651   }
1652 
1653   {
1654     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1655       // Functions referenced by a relocation need to put in the table.  This is
1656       // purely to make the object file's provisional values readable, and is
1657       // ignored by the linker, which re-calculates the relocations itself.
1658       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1659           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
1660           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1661           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
1662           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1663         return;
1664       assert(Rel.Symbol->isFunction());
1665       const MCSymbolWasm *Base =
1666           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
1667       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
1668       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1669       if (TableIndices.try_emplace(Base, TableIndex).second) {
1670         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1671                           << " to table: " << TableIndex << "\n");
1672         TableElems.push_back(FunctionIndex);
1673         registerFunctionType(*Base);
1674       }
1675     };
1676 
1677     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1678       HandleReloc(RelEntry);
1679     for (const WasmRelocationEntry &RelEntry : DataRelocations)
1680       HandleReloc(RelEntry);
1681   }
1682 
1683   // Translate .init_array section contents into start functions.
1684   for (const MCSection &S : Asm) {
1685     const auto &WS = static_cast<const MCSectionWasm &>(S);
1686     if (WS.getName().startswith(".fini_array"))
1687       report_fatal_error(".fini_array sections are unsupported");
1688     if (!WS.getName().startswith(".init_array"))
1689       continue;
1690     if (WS.getFragmentList().empty())
1691       continue;
1692 
1693     // init_array is expected to contain a single non-empty data fragment
1694     if (WS.getFragmentList().size() != 3)
1695       report_fatal_error("only one .init_array section fragment supported");
1696 
1697     auto IT = WS.begin();
1698     const MCFragment &EmptyFrag = *IT;
1699     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1700       report_fatal_error(".init_array section should be aligned");
1701 
1702     IT = std::next(IT);
1703     const MCFragment &AlignFrag = *IT;
1704     if (AlignFrag.getKind() != MCFragment::FT_Align)
1705       report_fatal_error(".init_array section should be aligned");
1706     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1707       report_fatal_error(".init_array section should be aligned for pointers");
1708 
1709     const MCFragment &Frag = *std::next(IT);
1710     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1711       report_fatal_error("only data supported in .init_array section");
1712 
1713     uint16_t Priority = UINT16_MAX;
1714     unsigned PrefixLength = strlen(".init_array");
1715     if (WS.getName().size() > PrefixLength) {
1716       if (WS.getName()[PrefixLength] != '.')
1717         report_fatal_error(
1718             ".init_array section priority should start with '.'");
1719       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1720         report_fatal_error("invalid .init_array section priority");
1721     }
1722     const auto &DataFrag = cast<MCDataFragment>(Frag);
1723     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1724     for (const uint8_t *
1725              P = (const uint8_t *)Contents.data(),
1726             *End = (const uint8_t *)Contents.data() + Contents.size();
1727          P != End; ++P) {
1728       if (*P != 0)
1729         report_fatal_error("non-symbolic data in .init_array section");
1730     }
1731     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1732       assert(Fixup.getKind() ==
1733              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1734       const MCExpr *Expr = Fixup.getValue();
1735       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1736       if (!SymRef)
1737         report_fatal_error("fixups in .init_array should be symbol references");
1738       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1739       if (TargetSym.getIndex() == InvalidIndex)
1740         report_fatal_error("symbols in .init_array should exist in symtab");
1741       if (!TargetSym.isFunction())
1742         report_fatal_error("symbols in .init_array should be for functions");
1743       InitFuncs.push_back(
1744           std::make_pair(Priority, TargetSym.getIndex()));
1745     }
1746   }
1747 
1748   // Write out the Wasm header.
1749   writeHeader(Asm);
1750 
1751   uint32_t CodeSectionIndex, DataSectionIndex;
1752   if (Mode != DwoMode::DwoOnly) {
1753     writeTypeSection(Signatures);
1754     writeImportSection(Imports, DataSize, TableElems.size());
1755     writeFunctionSection(Functions);
1756     // Skip the "memory" section; we import the memory instead.
1757     writeEventSection(Events);
1758     writeGlobalSection(Globals);
1759     writeTableSection(Tables);
1760     writeExportSection(Exports);
1761     writeElemSection(TableElems);
1762     writeDataCountSection();
1763 
1764     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
1765     DataSectionIndex = writeDataSection(Layout);
1766   }
1767 
1768   for (auto &CustomSection : CustomSections) {
1769     writeCustomSection(CustomSection, Asm, Layout);
1770   }
1771 
1772   if (Mode != DwoMode::DwoOnly) {
1773     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1774 
1775     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1776     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1777   }
1778   writeCustomRelocSections();
1779   if (ProducersSection)
1780     writeCustomSection(*ProducersSection, Asm, Layout);
1781   if (TargetFeaturesSection)
1782     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1783 
1784   // TODO: Translate the .comment section to the output.
1785   return W->OS.tell() - StartOffset;
1786 }
1787 
1788 std::unique_ptr<MCObjectWriter>
1789 llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1790                              raw_pwrite_stream &OS) {
1791   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
1792 }
1793 
1794 std::unique_ptr<MCObjectWriter>
1795 llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1796                                 raw_pwrite_stream &OS,
1797                                 raw_pwrite_stream &DwoOS) {
1798   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
1799 }
1800