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