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