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