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