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