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