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