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