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 LinkerFlags;
71   SmallVector<char, 4> Data;
72 };
73 
74 // A wasm function to be written into the function section.
75 struct WasmFunction {
76   uint32_t SigIndex;
77   const MCSymbolWasm *Sym;
78 };
79 
80 // A wasm global to be written into the global section.
81 struct WasmGlobal {
82   wasm::WasmGlobalType Type;
83   uint64_t InitialValue;
84 };
85 
86 // Information about a single item which is part of a COMDAT.  For each data
87 // segment or function which is in the COMDAT, there is a corresponding
88 // WasmComdatEntry.
89 struct WasmComdatEntry {
90   unsigned Kind;
91   uint32_t Index;
92 };
93 
94 // Information about a single relocation.
95 struct WasmRelocationEntry {
96   uint64_t Offset;                   // Where is the relocation.
97   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
98   int64_t Addend;                    // A value to add to the symbol.
99   unsigned Type;                     // The type of the relocation.
100   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
101 
102   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
103                       int64_t Addend, unsigned Type,
104                       const MCSectionWasm *FixupSection)
105       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
106         FixupSection(FixupSection) {}
107 
108   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
109 
110   void print(raw_ostream &Out) const {
111     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
112         << ", Sym=" << *Symbol << ", Addend=" << Addend
113         << ", FixupSection=" << FixupSection->getName();
114   }
115 
116 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
117   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
118 #endif
119 };
120 
121 static const uint32_t InvalidIndex = -1;
122 
123 struct WasmCustomSection {
124 
125   StringRef Name;
126   MCSectionWasm *Section;
127 
128   uint32_t OutputContentsOffset;
129   uint32_t OutputIndex;
130 
131   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
132       : Name(Name), Section(Section), OutputContentsOffset(0),
133         OutputIndex(InvalidIndex) {}
134 };
135 
136 #if !defined(NDEBUG)
137 raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
138   Rel.print(OS);
139   return OS;
140 }
141 #endif
142 
143 // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
144 // to allow patching.
145 template <int W>
146 void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
147   uint8_t Buffer[W];
148   unsigned SizeLen = encodeULEB128(X, Buffer, W);
149   assert(SizeLen == W);
150   Stream.pwrite((char *)Buffer, SizeLen, Offset);
151 }
152 
153 // Write X as an signed LEB value at offset Offset in Stream, padded
154 // to allow patching.
155 template <int W>
156 void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) {
157   uint8_t Buffer[W];
158   unsigned SizeLen = encodeSLEB128(X, Buffer, W);
159   assert(SizeLen == W);
160   Stream.pwrite((char *)Buffer, SizeLen, Offset);
161 }
162 
163 // Write X as a plain integer value at offset Offset in Stream.
164 static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
165   uint8_t Buffer[4];
166   support::endian::write32le(Buffer, X);
167   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
168 }
169 
170 static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
171   uint8_t Buffer[8];
172   support::endian::write64le(Buffer, X);
173   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
174 }
175 
176 bool isDwoSection(const MCSection &Sec) {
177   return Sec.getName().endswith(".dwo");
178 }
179 
180 class WasmObjectWriter : public MCObjectWriter {
181   support::endian::Writer *W;
182 
183   /// The target specific Wasm writer instance.
184   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
185 
186   // Relocations for fixing up references in the code section.
187   std::vector<WasmRelocationEntry> CodeRelocations;
188   // Relocations for fixing up references in the data section.
189   std::vector<WasmRelocationEntry> DataRelocations;
190 
191   // Index values to use for fixing up call_indirect type indices.
192   // Maps function symbols to the index of the type of the function
193   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
194   // Maps function symbols to the table element index space. Used
195   // for TABLE_INDEX relocation types (i.e. address taken functions).
196   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
197   // Maps function/global/table symbols to the
198   // function/global/table/event/section index space.
199   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
200   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
201   // Maps data symbols to the Wasm segment and offset/size with the segment.
202   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
203 
204   // Stores output data (index, relocations, content offset) for custom
205   // section.
206   std::vector<WasmCustomSection> CustomSections;
207   std::unique_ptr<WasmCustomSection> ProducersSection;
208   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
209   // Relocations for fixing up references in the custom sections.
210   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
211       CustomSectionsRelocations;
212 
213   // Map from section to defining function symbol.
214   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
215 
216   DenseMap<wasm::WasmSignature, uint32_t> SignatureIndices;
217   SmallVector<wasm::WasmSignature, 4> Signatures;
218   SmallVector<WasmDataSegment, 4> DataSegments;
219   unsigned NumFunctionImports = 0;
220   unsigned NumGlobalImports = 0;
221   unsigned NumTableImports = 0;
222   unsigned NumEventImports = 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 writeEventSection(ArrayRef<wasm::WasmEventType> Events);
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 getEventType(const MCSymbolWasm &Symbol);
341   void registerFunctionType(const MCSymbolWasm &Symbol);
342   void registerEventType(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 = TargetObjectWriter->getRelocType(Target, Fixup, IsLocRel);
502 
503   // Absolute offset within a section or a function.
504   // Currently only supported for for metadata sections.
505   // See: test/MC/WebAssembly/blockaddress.ll
506   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
507       Type == wasm::R_WASM_FUNCTION_OFFSET_I64 ||
508       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
509     if (!FixupSection.getKind().isMetadata())
510       report_fatal_error("relocations for function or section offsets are "
511                          "only supported in metadata sections");
512 
513     const MCSymbol *SectionSymbol = nullptr;
514     const MCSection &SecA = SymA->getSection();
515     if (SecA.getKind().isText()) {
516       auto SecSymIt = SectionFunctions.find(&SecA);
517       if (SecSymIt == SectionFunctions.end())
518         report_fatal_error("section doesn\'t have defining symbol");
519       SectionSymbol = SecSymIt->second;
520     } else {
521       SectionSymbol = SecA.getBeginSymbol();
522     }
523     if (!SectionSymbol)
524       report_fatal_error("section symbol is required for relocation");
525 
526     C += Layout.getSymbolOffset(*SymA);
527     SymA = cast<MCSymbolWasm>(SectionSymbol);
528   }
529 
530   if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
531       Type == wasm::R_WASM_TABLE_INDEX_SLEB ||
532       Type == wasm::R_WASM_TABLE_INDEX_SLEB64 ||
533       Type == wasm::R_WASM_TABLE_INDEX_I32 ||
534       Type == wasm::R_WASM_TABLE_INDEX_I64) {
535     // TABLE_INDEX relocs implicitly use the default indirect function table.
536     // We require the function table to have already been defined.
537     auto TableName = "__indirect_function_table";
538     MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName));
539     if (!Sym || !Sym->isFunctionTable()) {
540       Ctx.reportError(
541           Fixup.getLoc(),
542           "symbol '__indirect_function_table' is not a function table");
543     } else {
544       // Ensure that __indirect_function_table reaches the output.
545       Sym->setNoStrip();
546       Asm.registerSymbol(*Sym);
547     }
548   }
549 
550   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
551   // against a named symbol.
552   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
553     if (SymA->getName().empty())
554       report_fatal_error("relocations against un-named temporaries are not yet "
555                          "supported by wasm");
556 
557     SymA->setUsedInReloc();
558   }
559 
560   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
561     SymA->setUsedInGOT();
562 
563   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
564   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
565 
566   if (FixupSection.isWasmData()) {
567     DataRelocations.push_back(Rec);
568   } else if (FixupSection.getKind().isText()) {
569     CodeRelocations.push_back(Rec);
570   } else if (FixupSection.getKind().isMetadata()) {
571     CustomSectionsRelocations[&FixupSection].push_back(Rec);
572   } else {
573     llvm_unreachable("unexpected section type");
574   }
575 }
576 
577 // Compute a value to write into the code at the location covered
578 // by RelEntry. This value isn't used by the static linker; it just serves
579 // to make the object format more readable and more likely to be directly
580 // useable.
581 uint64_t
582 WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
583                                       const MCAsmLayout &Layout) {
584   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
585        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
586       !RelEntry.Symbol->isGlobal()) {
587     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
588     return GOTIndices[RelEntry.Symbol];
589   }
590 
591   switch (RelEntry.Type) {
592   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
593   case wasm::R_WASM_TABLE_INDEX_SLEB:
594   case wasm::R_WASM_TABLE_INDEX_SLEB64:
595   case wasm::R_WASM_TABLE_INDEX_I32:
596   case wasm::R_WASM_TABLE_INDEX_I64: {
597     // Provisional value is table address of the resolved symbol itself
598     const MCSymbolWasm *Base =
599         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
600     assert(Base->isFunction());
601     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
602       return TableIndices[Base] - InitialTableOffset;
603     else
604       return TableIndices[Base];
605   }
606   case wasm::R_WASM_TYPE_INDEX_LEB:
607     // Provisional value is same as the index
608     return getRelocationIndexValue(RelEntry);
609   case wasm::R_WASM_FUNCTION_INDEX_LEB:
610   case wasm::R_WASM_GLOBAL_INDEX_LEB:
611   case wasm::R_WASM_GLOBAL_INDEX_I32:
612   case wasm::R_WASM_EVENT_INDEX_LEB:
613   case wasm::R_WASM_TABLE_NUMBER_LEB:
614     // Provisional value is function/global/event Wasm index
615     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
616     return WasmIndices[RelEntry.Symbol];
617   case wasm::R_WASM_FUNCTION_OFFSET_I32:
618   case wasm::R_WASM_FUNCTION_OFFSET_I64:
619   case wasm::R_WASM_SECTION_OFFSET_I32: {
620     const auto &Section =
621         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
622     return Section.getSectionOffset() + RelEntry.Addend;
623   }
624   case wasm::R_WASM_MEMORY_ADDR_LEB:
625   case wasm::R_WASM_MEMORY_ADDR_LEB64:
626   case wasm::R_WASM_MEMORY_ADDR_SLEB:
627   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
628   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
629   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
630   case wasm::R_WASM_MEMORY_ADDR_I32:
631   case wasm::R_WASM_MEMORY_ADDR_I64:
632   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
633   case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32: {
634     // Provisional value is address of the global plus the offset
635     // For undefined symbols, use zero
636     if (!RelEntry.Symbol->isDefined())
637       return 0;
638     const wasm::WasmDataReference &SymRef = DataLocations[RelEntry.Symbol];
639     const WasmDataSegment &Segment = DataSegments[SymRef.Segment];
640     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
641     return Segment.Offset + SymRef.Offset + RelEntry.Addend;
642   }
643   default:
644     llvm_unreachable("invalid relocation type");
645   }
646 }
647 
648 static void addData(SmallVectorImpl<char> &DataBytes,
649                     MCSectionWasm &DataSection) {
650   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
651 
652   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
653 
654   for (const MCFragment &Frag : DataSection) {
655     if (Frag.hasInstructions())
656       report_fatal_error("only data supported in data sections");
657 
658     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
659       if (Align->getValueSize() != 1)
660         report_fatal_error("only byte values supported for alignment");
661       // If nops are requested, use zeros, as this is the data section.
662       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
663       uint64_t Size =
664           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
665                              DataBytes.size() + Align->getMaxBytesToEmit());
666       DataBytes.resize(Size, Value);
667     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
668       int64_t NumValues;
669       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
670         llvm_unreachable("The fill should be an assembler constant");
671       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
672                        Fill->getValue());
673     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
674       const SmallVectorImpl<char> &Contents = LEB->getContents();
675       llvm::append_range(DataBytes, Contents);
676     } else {
677       const auto &DataFrag = cast<MCDataFragment>(Frag);
678       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
679       llvm::append_range(DataBytes, Contents);
680     }
681   }
682 
683   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
684 }
685 
686 uint32_t
687 WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
688   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
689     if (!TypeIndices.count(RelEntry.Symbol))
690       report_fatal_error("symbol not found in type index space: " +
691                          RelEntry.Symbol->getName());
692     return TypeIndices[RelEntry.Symbol];
693   }
694 
695   return RelEntry.Symbol->getIndex();
696 }
697 
698 // Apply the portions of the relocation records that we can handle ourselves
699 // directly.
700 void WasmObjectWriter::applyRelocations(
701     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
702     const MCAsmLayout &Layout) {
703   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
704   for (const WasmRelocationEntry &RelEntry : Relocations) {
705     uint64_t Offset = ContentsOffset +
706                       RelEntry.FixupSection->getSectionOffset() +
707                       RelEntry.Offset;
708 
709     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
710     auto Value = getProvisionalValue(RelEntry, Layout);
711 
712     switch (RelEntry.Type) {
713     case wasm::R_WASM_FUNCTION_INDEX_LEB:
714     case wasm::R_WASM_TYPE_INDEX_LEB:
715     case wasm::R_WASM_GLOBAL_INDEX_LEB:
716     case wasm::R_WASM_MEMORY_ADDR_LEB:
717     case wasm::R_WASM_EVENT_INDEX_LEB:
718     case wasm::R_WASM_TABLE_NUMBER_LEB:
719       writePatchableLEB<5>(Stream, Value, Offset);
720       break;
721     case wasm::R_WASM_MEMORY_ADDR_LEB64:
722       writePatchableLEB<10>(Stream, Value, Offset);
723       break;
724     case wasm::R_WASM_TABLE_INDEX_I32:
725     case wasm::R_WASM_MEMORY_ADDR_I32:
726     case wasm::R_WASM_FUNCTION_OFFSET_I32:
727     case wasm::R_WASM_SECTION_OFFSET_I32:
728     case wasm::R_WASM_GLOBAL_INDEX_I32:
729     case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32:
730       patchI32(Stream, Value, Offset);
731       break;
732     case wasm::R_WASM_TABLE_INDEX_I64:
733     case wasm::R_WASM_MEMORY_ADDR_I64:
734     case wasm::R_WASM_FUNCTION_OFFSET_I64:
735       patchI64(Stream, Value, Offset);
736       break;
737     case wasm::R_WASM_TABLE_INDEX_SLEB:
738     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
739     case wasm::R_WASM_MEMORY_ADDR_SLEB:
740     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
741     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
742       writePatchableSLEB<5>(Stream, Value, Offset);
743       break;
744     case wasm::R_WASM_TABLE_INDEX_SLEB64:
745     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
746     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
747       writePatchableSLEB<10>(Stream, Value, Offset);
748       break;
749     default:
750       llvm_unreachable("invalid relocation type");
751     }
752   }
753 }
754 
755 void WasmObjectWriter::writeTypeSection(
756     ArrayRef<wasm::WasmSignature> Signatures) {
757   if (Signatures.empty())
758     return;
759 
760   SectionBookkeeping Section;
761   startSection(Section, wasm::WASM_SEC_TYPE);
762 
763   encodeULEB128(Signatures.size(), W->OS);
764 
765   for (const wasm::WasmSignature &Sig : Signatures) {
766     W->OS << char(wasm::WASM_TYPE_FUNC);
767     encodeULEB128(Sig.Params.size(), W->OS);
768     for (wasm::ValType Ty : Sig.Params)
769       writeValueType(Ty);
770     encodeULEB128(Sig.Returns.size(), W->OS);
771     for (wasm::ValType Ty : Sig.Returns)
772       writeValueType(Ty);
773   }
774 
775   endSection(Section);
776 }
777 
778 void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
779                                           uint64_t DataSize,
780                                           uint32_t NumElements) {
781   if (Imports.empty())
782     return;
783 
784   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
785 
786   SectionBookkeeping Section;
787   startSection(Section, wasm::WASM_SEC_IMPORT);
788 
789   encodeULEB128(Imports.size(), W->OS);
790   for (const wasm::WasmImport &Import : Imports) {
791     writeString(Import.Module);
792     writeString(Import.Field);
793     W->OS << char(Import.Kind);
794 
795     switch (Import.Kind) {
796     case wasm::WASM_EXTERNAL_FUNCTION:
797       encodeULEB128(Import.SigIndex, W->OS);
798       break;
799     case wasm::WASM_EXTERNAL_GLOBAL:
800       W->OS << char(Import.Global.Type);
801       W->OS << char(Import.Global.Mutable ? 1 : 0);
802       break;
803     case wasm::WASM_EXTERNAL_MEMORY:
804       encodeULEB128(Import.Memory.Flags, W->OS);
805       encodeULEB128(NumPages, W->OS); // initial
806       break;
807     case wasm::WASM_EXTERNAL_TABLE:
808       W->OS << char(Import.Table.ElemType);
809       encodeULEB128(0, W->OS);           // flags
810       encodeULEB128(NumElements, W->OS); // initial
811       break;
812     case wasm::WASM_EXTERNAL_EVENT:
813       encodeULEB128(Import.Event.Attribute, W->OS);
814       encodeULEB128(Import.Event.SigIndex, W->OS);
815       break;
816     default:
817       llvm_unreachable("unsupported import kind");
818     }
819   }
820 
821   endSection(Section);
822 }
823 
824 void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
825   if (Functions.empty())
826     return;
827 
828   SectionBookkeeping Section;
829   startSection(Section, wasm::WASM_SEC_FUNCTION);
830 
831   encodeULEB128(Functions.size(), W->OS);
832   for (const WasmFunction &Func : Functions)
833     encodeULEB128(Func.SigIndex, W->OS);
834 
835   endSection(Section);
836 }
837 
838 void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
839   if (Events.empty())
840     return;
841 
842   SectionBookkeeping Section;
843   startSection(Section, wasm::WASM_SEC_EVENT);
844 
845   encodeULEB128(Events.size(), W->OS);
846   for (const wasm::WasmEventType &Event : Events) {
847     encodeULEB128(Event.Attribute, W->OS);
848     encodeULEB128(Event.SigIndex, W->OS);
849   }
850 
851   endSection(Section);
852 }
853 
854 void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
855   if (Globals.empty())
856     return;
857 
858   SectionBookkeeping Section;
859   startSection(Section, wasm::WASM_SEC_GLOBAL);
860 
861   encodeULEB128(Globals.size(), W->OS);
862   for (const wasm::WasmGlobal &Global : Globals) {
863     encodeULEB128(Global.Type.Type, W->OS);
864     W->OS << char(Global.Type.Mutable);
865     W->OS << char(Global.InitExpr.Opcode);
866     switch (Global.Type.Type) {
867     case wasm::WASM_TYPE_I32:
868       encodeSLEB128(0, W->OS);
869       break;
870     case wasm::WASM_TYPE_I64:
871       encodeSLEB128(0, W->OS);
872       break;
873     case wasm::WASM_TYPE_F32:
874       writeI32(0);
875       break;
876     case wasm::WASM_TYPE_F64:
877       writeI64(0);
878       break;
879     case wasm::WASM_TYPE_EXTERNREF:
880       writeValueType(wasm::ValType::EXTERNREF);
881       break;
882     default:
883       llvm_unreachable("unexpected type");
884     }
885     W->OS << char(wasm::WASM_OPCODE_END);
886   }
887 
888   endSection(Section);
889 }
890 
891 void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
892   if (Tables.empty())
893     return;
894 
895   SectionBookkeeping Section;
896   startSection(Section, wasm::WASM_SEC_TABLE);
897 
898   encodeULEB128(Tables.size(), W->OS);
899   for (const wasm::WasmTable &Table : Tables) {
900     encodeULEB128(Table.Type.ElemType, W->OS);
901     encodeULEB128(Table.Type.Limits.Flags, W->OS);
902     encodeULEB128(Table.Type.Limits.Initial, W->OS);
903     if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
904       encodeULEB128(Table.Type.Limits.Maximum, W->OS);
905   }
906   endSection(Section);
907 }
908 
909 void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
910   if (Exports.empty())
911     return;
912 
913   SectionBookkeeping Section;
914   startSection(Section, wasm::WASM_SEC_EXPORT);
915 
916   encodeULEB128(Exports.size(), W->OS);
917   for (const wasm::WasmExport &Export : Exports) {
918     writeString(Export.Name);
919     W->OS << char(Export.Kind);
920     encodeULEB128(Export.Index, W->OS);
921   }
922 
923   endSection(Section);
924 }
925 
926 void WasmObjectWriter::writeElemSection(
927     const MCSymbolWasm *IndirectFunctionTable, ArrayRef<uint32_t> TableElems) {
928   if (TableElems.empty())
929     return;
930 
931   assert(IndirectFunctionTable);
932 
933   SectionBookkeeping Section;
934   startSection(Section, wasm::WASM_SEC_ELEM);
935 
936   encodeULEB128(1, W->OS); // number of "segments"
937 
938   assert(WasmIndices.count(IndirectFunctionTable));
939   uint32_t TableNumber = WasmIndices.find(IndirectFunctionTable)->second;
940   uint32_t Flags = 0;
941   if (TableNumber)
942     Flags |= wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER;
943   encodeULEB128(Flags, W->OS);
944   if (Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER)
945     encodeULEB128(TableNumber, W->OS); // the table number
946 
947   // init expr for starting offset
948   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
949   encodeSLEB128(InitialTableOffset, W->OS);
950   W->OS << char(wasm::WASM_OPCODE_END);
951 
952   if (Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) {
953     // We only write active function table initializers, for which the elem kind
954     // is specified to be written as 0x00 and interpreted to mean "funcref".
955     const uint8_t ElemKind = 0;
956     W->OS << ElemKind;
957   }
958 
959   encodeULEB128(TableElems.size(), W->OS);
960   for (uint32_t Elem : TableElems)
961     encodeULEB128(Elem, W->OS);
962 
963   endSection(Section);
964 }
965 
966 void WasmObjectWriter::writeDataCountSection() {
967   if (DataSegments.empty())
968     return;
969 
970   SectionBookkeeping Section;
971   startSection(Section, wasm::WASM_SEC_DATACOUNT);
972   encodeULEB128(DataSegments.size(), W->OS);
973   endSection(Section);
974 }
975 
976 uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
977                                             const MCAsmLayout &Layout,
978                                             ArrayRef<WasmFunction> Functions) {
979   if (Functions.empty())
980     return 0;
981 
982   SectionBookkeeping Section;
983   startSection(Section, wasm::WASM_SEC_CODE);
984 
985   encodeULEB128(Functions.size(), W->OS);
986 
987   for (const WasmFunction &Func : Functions) {
988     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
989 
990     int64_t Size = 0;
991     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
992       report_fatal_error(".size expression must be evaluatable");
993 
994     encodeULEB128(Size, W->OS);
995     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
996     Asm.writeSectionData(W->OS, &FuncSection, Layout);
997   }
998 
999   // Apply fixups.
1000   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
1001 
1002   endSection(Section);
1003   return Section.Index;
1004 }
1005 
1006 uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
1007   if (DataSegments.empty())
1008     return 0;
1009 
1010   SectionBookkeeping Section;
1011   startSection(Section, wasm::WASM_SEC_DATA);
1012 
1013   encodeULEB128(DataSegments.size(), W->OS); // count
1014 
1015   for (const WasmDataSegment &Segment : DataSegments) {
1016     encodeULEB128(Segment.InitFlags, W->OS); // flags
1017     if (Segment.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
1018       encodeULEB128(0, W->OS); // memory index
1019     if ((Segment.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
1020       W->OS << char(is64Bit() ? wasm::WASM_OPCODE_I64_CONST
1021                               : wasm::WASM_OPCODE_I32_CONST);
1022       encodeSLEB128(Segment.Offset, W->OS); // offset
1023       W->OS << char(wasm::WASM_OPCODE_END);
1024     }
1025     encodeULEB128(Segment.Data.size(), W->OS); // size
1026     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
1027     W->OS << Segment.Data; // data
1028   }
1029 
1030   // Apply fixups.
1031   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
1032 
1033   endSection(Section);
1034   return Section.Index;
1035 }
1036 
1037 void WasmObjectWriter::writeRelocSection(
1038     uint32_t SectionIndex, StringRef Name,
1039     std::vector<WasmRelocationEntry> &Relocs) {
1040   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
1041   // for descriptions of the reloc sections.
1042 
1043   if (Relocs.empty())
1044     return;
1045 
1046   // First, ensure the relocations are sorted in offset order.  In general they
1047   // should already be sorted since `recordRelocation` is called in offset
1048   // order, but for the code section we combine many MC sections into single
1049   // wasm section, and this order is determined by the order of Asm.Symbols()
1050   // not the sections order.
1051   llvm::stable_sort(
1052       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
1053         return (A.Offset + A.FixupSection->getSectionOffset()) <
1054                (B.Offset + B.FixupSection->getSectionOffset());
1055       });
1056 
1057   SectionBookkeeping Section;
1058   startCustomSection(Section, std::string("reloc.") + Name.str());
1059 
1060   encodeULEB128(SectionIndex, W->OS);
1061   encodeULEB128(Relocs.size(), W->OS);
1062   for (const WasmRelocationEntry &RelEntry : Relocs) {
1063     uint64_t Offset =
1064         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
1065     uint32_t Index = getRelocationIndexValue(RelEntry);
1066 
1067     W->OS << char(RelEntry.Type);
1068     encodeULEB128(Offset, W->OS);
1069     encodeULEB128(Index, W->OS);
1070     if (RelEntry.hasAddend())
1071       encodeSLEB128(RelEntry.Addend, W->OS);
1072   }
1073 
1074   endSection(Section);
1075 }
1076 
1077 void WasmObjectWriter::writeCustomRelocSections() {
1078   for (const auto &Sec : CustomSections) {
1079     auto &Relocations = CustomSectionsRelocations[Sec.Section];
1080     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
1081   }
1082 }
1083 
1084 void WasmObjectWriter::writeLinkingMetaDataSection(
1085     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1086     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1087     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
1088   SectionBookkeeping Section;
1089   startCustomSection(Section, "linking");
1090   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
1091 
1092   SectionBookkeeping SubSection;
1093   if (SymbolInfos.size() != 0) {
1094     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
1095     encodeULEB128(SymbolInfos.size(), W->OS);
1096     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
1097       encodeULEB128(Sym.Kind, W->OS);
1098       encodeULEB128(Sym.Flags, W->OS);
1099       switch (Sym.Kind) {
1100       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1101       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1102       case wasm::WASM_SYMBOL_TYPE_EVENT:
1103       case wasm::WASM_SYMBOL_TYPE_TABLE:
1104         encodeULEB128(Sym.ElementIndex, W->OS);
1105         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
1106             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
1107           writeString(Sym.Name);
1108         break;
1109       case wasm::WASM_SYMBOL_TYPE_DATA:
1110         writeString(Sym.Name);
1111         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
1112           encodeULEB128(Sym.DataRef.Segment, W->OS);
1113           encodeULEB128(Sym.DataRef.Offset, W->OS);
1114           encodeULEB128(Sym.DataRef.Size, W->OS);
1115         }
1116         break;
1117       case wasm::WASM_SYMBOL_TYPE_SECTION: {
1118         const uint32_t SectionIndex =
1119             CustomSections[Sym.ElementIndex].OutputIndex;
1120         encodeULEB128(SectionIndex, W->OS);
1121         break;
1122       }
1123       default:
1124         llvm_unreachable("unexpected kind");
1125       }
1126     }
1127     endSection(SubSection);
1128   }
1129 
1130   if (DataSegments.size()) {
1131     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1132     encodeULEB128(DataSegments.size(), W->OS);
1133     for (const WasmDataSegment &Segment : DataSegments) {
1134       writeString(Segment.Name);
1135       encodeULEB128(Segment.Alignment, W->OS);
1136       encodeULEB128(Segment.LinkerFlags, W->OS);
1137     }
1138     endSection(SubSection);
1139   }
1140 
1141   if (!InitFuncs.empty()) {
1142     startSection(SubSection, wasm::WASM_INIT_FUNCS);
1143     encodeULEB128(InitFuncs.size(), W->OS);
1144     for (auto &StartFunc : InitFuncs) {
1145       encodeULEB128(StartFunc.first, W->OS);  // priority
1146       encodeULEB128(StartFunc.second, W->OS); // function index
1147     }
1148     endSection(SubSection);
1149   }
1150 
1151   if (Comdats.size()) {
1152     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1153     encodeULEB128(Comdats.size(), W->OS);
1154     for (const auto &C : Comdats) {
1155       writeString(C.first);
1156       encodeULEB128(0, W->OS); // flags for future use
1157       encodeULEB128(C.second.size(), W->OS);
1158       for (const WasmComdatEntry &Entry : C.second) {
1159         encodeULEB128(Entry.Kind, W->OS);
1160         encodeULEB128(Entry.Index, W->OS);
1161       }
1162     }
1163     endSection(SubSection);
1164   }
1165 
1166   endSection(Section);
1167 }
1168 
1169 void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1170                                           const MCAssembler &Asm,
1171                                           const MCAsmLayout &Layout) {
1172   SectionBookkeeping Section;
1173   auto *Sec = CustomSection.Section;
1174   startCustomSection(Section, CustomSection.Name);
1175 
1176   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
1177   Asm.writeSectionData(W->OS, Sec, Layout);
1178 
1179   CustomSection.OutputContentsOffset = Section.ContentsOffset;
1180   CustomSection.OutputIndex = Section.Index;
1181 
1182   endSection(Section);
1183 
1184   // Apply fixups.
1185   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1186   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
1187 }
1188 
1189 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
1190   assert(Symbol.isFunction());
1191   assert(TypeIndices.count(&Symbol));
1192   return TypeIndices[&Symbol];
1193 }
1194 
1195 uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1196   assert(Symbol.isEvent());
1197   assert(TypeIndices.count(&Symbol));
1198   return TypeIndices[&Symbol];
1199 }
1200 
1201 void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
1202   assert(Symbol.isFunction());
1203 
1204   wasm::WasmSignature S;
1205 
1206   if (auto *Sig = Symbol.getSignature()) {
1207     S.Returns = Sig->Returns;
1208     S.Params = Sig->Params;
1209   }
1210 
1211   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1212   if (Pair.second)
1213     Signatures.push_back(S);
1214   TypeIndices[&Symbol] = Pair.first->second;
1215 
1216   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1217                     << " new:" << Pair.second << "\n");
1218   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1219 }
1220 
1221 void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1222   assert(Symbol.isEvent());
1223 
1224   // TODO Currently we don't generate imported exceptions, but if we do, we
1225   // should have a way of infering types of imported exceptions.
1226   wasm::WasmSignature S;
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() << "registerEventType: " << Symbol << " new:" << Pair.second
1238                     << "\n");
1239   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1240 }
1241 
1242 static bool isInSymtab(const MCSymbolWasm &Sym) {
1243   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
1244     return true;
1245 
1246   if (Sym.isComdat() && !Sym.isDefined())
1247     return false;
1248 
1249   if (Sym.isTemporary())
1250     return false;
1251 
1252   if (Sym.isSection())
1253     return false;
1254 
1255   if (Sym.omitFromLinkingSection())
1256     return false;
1257 
1258   return true;
1259 }
1260 
1261 void WasmObjectWriter::prepareImports(
1262     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
1263     const MCAsmLayout &Layout) {
1264   // For now, always emit the memory import, since loads and stores are not
1265   // valid without it. In the future, we could perhaps be more clever and omit
1266   // it if there are no loads or stores.
1267   wasm::WasmImport MemImport;
1268   MemImport.Module = "env";
1269   MemImport.Field = "__linear_memory";
1270   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1271   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1272                                      : wasm::WASM_LIMITS_FLAG_NONE;
1273   Imports.push_back(MemImport);
1274 
1275   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1276   // symbols.  This must be done before populating WasmIndices for defined
1277   // symbols.
1278   for (const MCSymbol &S : Asm.symbols()) {
1279     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1280 
1281     // Register types for all functions, including those with private linkage
1282     // (because wasm always needs a type signature).
1283     if (WS.isFunction()) {
1284       const auto *BS = Layout.getBaseSymbol(S);
1285       if (!BS)
1286         report_fatal_error(Twine(S.getName()) +
1287                            ": absolute addressing not supported!");
1288       registerFunctionType(*cast<MCSymbolWasm>(BS));
1289     }
1290 
1291     if (WS.isEvent())
1292       registerEventType(WS);
1293 
1294     if (WS.isTemporary())
1295       continue;
1296 
1297     // If the symbol is not defined in this translation unit, import it.
1298     if (!WS.isDefined() && !WS.isComdat()) {
1299       if (WS.isFunction()) {
1300         wasm::WasmImport Import;
1301         Import.Module = WS.getImportModule();
1302         Import.Field = WS.getImportName();
1303         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1304         Import.SigIndex = getFunctionType(WS);
1305         Imports.push_back(Import);
1306         assert(WasmIndices.count(&WS) == 0);
1307         WasmIndices[&WS] = NumFunctionImports++;
1308       } else if (WS.isGlobal()) {
1309         if (WS.isWeak())
1310           report_fatal_error("undefined global symbol cannot be weak");
1311 
1312         wasm::WasmImport Import;
1313         Import.Field = WS.getImportName();
1314         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1315         Import.Module = WS.getImportModule();
1316         Import.Global = WS.getGlobalType();
1317         Imports.push_back(Import);
1318         assert(WasmIndices.count(&WS) == 0);
1319         WasmIndices[&WS] = NumGlobalImports++;
1320       } else if (WS.isEvent()) {
1321         if (WS.isWeak())
1322           report_fatal_error("undefined event symbol cannot be weak");
1323 
1324         wasm::WasmImport Import;
1325         Import.Module = WS.getImportModule();
1326         Import.Field = WS.getImportName();
1327         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1328         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1329         Import.Event.SigIndex = getEventType(WS);
1330         Imports.push_back(Import);
1331         assert(WasmIndices.count(&WS) == 0);
1332         WasmIndices[&WS] = NumEventImports++;
1333       } else if (WS.isTable()) {
1334         if (WS.isWeak())
1335           report_fatal_error("undefined table symbol cannot be weak");
1336 
1337         wasm::WasmImport Import;
1338         Import.Module = WS.getImportModule();
1339         Import.Field = WS.getImportName();
1340         Import.Kind = wasm::WASM_EXTERNAL_TABLE;
1341         wasm::ValType ElemType = WS.getTableType();
1342         Import.Table.ElemType = uint8_t(ElemType);
1343         // FIXME: Extend table type to include limits? For now we don't specify
1344         // a min or max which does not place any restrictions on the size of the
1345         // imported table.
1346         Import.Table.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1347         Imports.push_back(Import);
1348         assert(WasmIndices.count(&WS) == 0);
1349         WasmIndices[&WS] = NumTableImports++;
1350       }
1351     }
1352   }
1353 
1354   // Add imports for GOT globals
1355   for (const MCSymbol &S : Asm.symbols()) {
1356     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1357     if (WS.isUsedInGOT()) {
1358       wasm::WasmImport Import;
1359       if (WS.isFunction())
1360         Import.Module = "GOT.func";
1361       else
1362         Import.Module = "GOT.mem";
1363       Import.Field = WS.getName();
1364       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1365       Import.Global = {wasm::WASM_TYPE_I32, true};
1366       Imports.push_back(Import);
1367       assert(GOTIndices.count(&WS) == 0);
1368       GOTIndices[&WS] = NumGlobalImports++;
1369     }
1370   }
1371 }
1372 
1373 uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1374                                        const MCAsmLayout &Layout) {
1375   support::endian::Writer MainWriter(*OS, support::little);
1376   W = &MainWriter;
1377   if (IsSplitDwarf) {
1378     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
1379     assert(DwoOS);
1380     support::endian::Writer DwoWriter(*DwoOS, support::little);
1381     W = &DwoWriter;
1382     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
1383   } else {
1384     return writeOneObject(Asm, Layout, DwoMode::AllSections);
1385   }
1386 }
1387 
1388 uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
1389                                           const MCAsmLayout &Layout,
1390                                           DwoMode Mode) {
1391   uint64_t StartOffset = W->OS.tell();
1392   SectionCount = 0;
1393   CustomSections.clear();
1394 
1395   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1396 
1397   // Collect information from the available symbols.
1398   SmallVector<WasmFunction, 4> Functions;
1399   SmallVector<uint32_t, 4> TableElems;
1400   SmallVector<wasm::WasmImport, 4> Imports;
1401   SmallVector<wasm::WasmExport, 4> Exports;
1402   SmallVector<wasm::WasmEventType, 1> Events;
1403   SmallVector<wasm::WasmGlobal, 1> Globals;
1404   SmallVector<wasm::WasmTable, 1> Tables;
1405   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1406   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1407   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
1408   uint64_t DataSize = 0;
1409   if (Mode != DwoMode::DwoOnly) {
1410     prepareImports(Imports, Asm, Layout);
1411   }
1412 
1413   // Populate DataSegments and CustomSections, which must be done before
1414   // populating DataLocations.
1415   for (MCSection &Sec : Asm) {
1416     auto &Section = static_cast<MCSectionWasm &>(Sec);
1417     StringRef SectionName = Section.getName();
1418 
1419     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
1420       continue;
1421     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
1422       continue;
1423 
1424     LLVM_DEBUG(dbgs() << "Processing Section " << SectionName << "  group "
1425                       << Section.getGroup() << "\n";);
1426 
1427     // .init_array sections are handled specially elsewhere.
1428     if (SectionName.startswith(".init_array"))
1429       continue;
1430 
1431     // Code is handled separately
1432     if (Section.getKind().isText())
1433       continue;
1434 
1435     if (Section.isWasmData()) {
1436       uint32_t SegmentIndex = DataSegments.size();
1437       DataSize = alignTo(DataSize, Section.getAlignment());
1438       DataSegments.emplace_back();
1439       WasmDataSegment &Segment = DataSegments.back();
1440       Segment.Name = SectionName;
1441       Segment.InitFlags = Section.getPassive()
1442                               ? (uint32_t)wasm::WASM_DATA_SEGMENT_IS_PASSIVE
1443                               : 0;
1444       Segment.Offset = DataSize;
1445       Segment.Section = &Section;
1446       addData(Segment.Data, Section);
1447       Segment.Alignment = Log2_32(Section.getAlignment());
1448       Segment.LinkerFlags = 0;
1449       DataSize += Segment.Data.size();
1450       Section.setSegmentIndex(SegmentIndex);
1451 
1452       if (const MCSymbolWasm *C = Section.getGroup()) {
1453         Comdats[C->getName()].emplace_back(
1454             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1455       }
1456     } else {
1457       // Create custom sections
1458       assert(Sec.getKind().isMetadata());
1459 
1460       StringRef Name = SectionName;
1461 
1462       // For user-defined custom sections, strip the prefix
1463       if (Name.startswith(".custom_section."))
1464         Name = Name.substr(strlen(".custom_section."));
1465 
1466       MCSymbol *Begin = Sec.getBeginSymbol();
1467       if (Begin) {
1468         assert(WasmIndices.count(cast<MCSymbolWasm>(Begin)) == 0);
1469         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1470       }
1471 
1472       // Separate out the producers and target features sections
1473       if (Name == "producers") {
1474         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1475         continue;
1476       }
1477       if (Name == "target_features") {
1478         TargetFeaturesSection =
1479             std::make_unique<WasmCustomSection>(Name, &Section);
1480         continue;
1481       }
1482 
1483       // Custom sections can also belong to COMDAT groups. In this case the
1484       // decriptor's "index" field is the section index (in the final object
1485       // file), but that is not known until after layout, so it must be fixed up
1486       // later
1487       if (const MCSymbolWasm *C = Section.getGroup()) {
1488         Comdats[C->getName()].emplace_back(
1489             WasmComdatEntry{wasm::WASM_COMDAT_SECTION,
1490                             static_cast<uint32_t>(CustomSections.size())});
1491       }
1492 
1493       CustomSections.emplace_back(Name, &Section);
1494     }
1495   }
1496 
1497   if (Mode != DwoMode::DwoOnly) {
1498     // Populate WasmIndices and DataLocations for defined symbols.
1499     for (const MCSymbol &S : Asm.symbols()) {
1500       // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1501       // or used in relocations.
1502       if (S.isTemporary() && S.getName().empty())
1503         continue;
1504 
1505       const auto &WS = static_cast<const MCSymbolWasm &>(S);
1506       LLVM_DEBUG(dbgs()
1507                  << "MCSymbol: "
1508                  << toString(WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA))
1509                  << " '" << S << "'"
1510                  << " isDefined=" << S.isDefined() << " isExternal="
1511                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1512                  << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1513                  << " isVariable=" << WS.isVariable() << "\n");
1514 
1515       if (WS.isVariable())
1516         continue;
1517       if (WS.isComdat() && !WS.isDefined())
1518         continue;
1519 
1520       if (WS.isFunction()) {
1521         unsigned Index;
1522         if (WS.isDefined()) {
1523           if (WS.getOffset() != 0)
1524             report_fatal_error(
1525                 "function sections must contain one function each");
1526 
1527           if (WS.getSize() == nullptr)
1528             report_fatal_error(
1529                 "function symbols must have a size set with .size");
1530 
1531           // A definition. Write out the function body.
1532           Index = NumFunctionImports + Functions.size();
1533           WasmFunction Func;
1534           Func.SigIndex = getFunctionType(WS);
1535           Func.Sym = &WS;
1536           assert(WasmIndices.count(&WS) == 0);
1537           WasmIndices[&WS] = Index;
1538           Functions.push_back(Func);
1539 
1540           auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1541           if (const MCSymbolWasm *C = Section.getGroup()) {
1542             Comdats[C->getName()].emplace_back(
1543                 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1544           }
1545 
1546           if (WS.hasExportName()) {
1547             wasm::WasmExport Export;
1548             Export.Name = WS.getExportName();
1549             Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1550             Export.Index = Index;
1551             Exports.push_back(Export);
1552           }
1553         } else {
1554           // An import; the index was assigned above.
1555           Index = WasmIndices.find(&WS)->second;
1556         }
1557 
1558         LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1559 
1560       } else if (WS.isData()) {
1561         if (!isInSymtab(WS))
1562           continue;
1563 
1564         if (!WS.isDefined()) {
1565           LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1566                             << "\n");
1567           continue;
1568         }
1569 
1570         if (!WS.getSize())
1571           report_fatal_error("data symbols must have a size set with .size: " +
1572                              WS.getName());
1573 
1574         int64_t Size = 0;
1575         if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1576           report_fatal_error(".size expression must be evaluatable");
1577 
1578         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1579         if (!DataSection.isWasmData())
1580           report_fatal_error("data symbols must live in a data section: " +
1581                              WS.getName());
1582 
1583         // For each data symbol, export it in the symtab as a reference to the
1584         // corresponding Wasm data segment.
1585         wasm::WasmDataReference Ref = wasm::WasmDataReference{
1586             DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
1587             static_cast<uint64_t>(Size)};
1588         assert(DataLocations.count(&WS) == 0);
1589         DataLocations[&WS] = Ref;
1590         LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1591 
1592       } else if (WS.isGlobal()) {
1593         // A "true" Wasm global (currently just __stack_pointer)
1594         if (WS.isDefined()) {
1595           wasm::WasmGlobal Global;
1596           Global.Type = WS.getGlobalType();
1597           Global.Index = NumGlobalImports + Globals.size();
1598           switch (Global.Type.Type) {
1599           case wasm::WASM_TYPE_I32:
1600             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
1601             break;
1602           case wasm::WASM_TYPE_I64:
1603             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
1604             break;
1605           case wasm::WASM_TYPE_F32:
1606             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
1607             break;
1608           case wasm::WASM_TYPE_F64:
1609             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
1610             break;
1611           case wasm::WASM_TYPE_EXTERNREF:
1612             Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
1613             break;
1614           default:
1615             llvm_unreachable("unexpected type");
1616           }
1617           assert(WasmIndices.count(&WS) == 0);
1618           WasmIndices[&WS] = Global.Index;
1619           Globals.push_back(Global);
1620         } else {
1621           // An import; the index was assigned above
1622           LLVM_DEBUG(dbgs() << "  -> global index: "
1623                             << WasmIndices.find(&WS)->second << "\n");
1624         }
1625       } else if (WS.isTable()) {
1626         if (WS.isDefined()) {
1627           wasm::WasmTable Table;
1628           Table.Index = NumTableImports + Tables.size();
1629           Table.Type.ElemType = static_cast<uint8_t>(WS.getTableType());
1630           // FIXME: Work on custom limits is ongoing
1631           Table.Type.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1632           assert(WasmIndices.count(&WS) == 0);
1633           WasmIndices[&WS] = Table.Index;
1634           Tables.push_back(Table);
1635         }
1636         LLVM_DEBUG(dbgs() << " -> table index: "
1637                           << WasmIndices.find(&WS)->second << "\n");
1638       } else if (WS.isEvent()) {
1639         // C++ exception symbol (__cpp_exception)
1640         unsigned Index;
1641         if (WS.isDefined()) {
1642           Index = NumEventImports + Events.size();
1643           wasm::WasmEventType Event;
1644           Event.SigIndex = getEventType(WS);
1645           Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1646           assert(WasmIndices.count(&WS) == 0);
1647           WasmIndices[&WS] = Index;
1648           Events.push_back(Event);
1649         } else {
1650           // An import; the index was assigned above.
1651           assert(WasmIndices.count(&WS) > 0);
1652         }
1653         LLVM_DEBUG(dbgs() << "  -> event index: "
1654                           << WasmIndices.find(&WS)->second << "\n");
1655 
1656       } else {
1657         assert(WS.isSection());
1658       }
1659     }
1660 
1661     // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1662     // process these in a separate pass because we need to have processed the
1663     // target of the alias before the alias itself and the symbols are not
1664     // necessarily ordered in this way.
1665     for (const MCSymbol &S : Asm.symbols()) {
1666       if (!S.isVariable())
1667         continue;
1668 
1669       assert(S.isDefined());
1670 
1671       const auto *BS = Layout.getBaseSymbol(S);
1672       if (!BS)
1673         report_fatal_error(Twine(S.getName()) +
1674                            ": absolute addressing not supported!");
1675       const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
1676 
1677       // Find the target symbol of this weak alias and export that index
1678       const auto &WS = static_cast<const MCSymbolWasm &>(S);
1679       LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base
1680                         << "'\n");
1681 
1682       if (Base->isFunction()) {
1683         assert(WasmIndices.count(Base) > 0);
1684         uint32_t WasmIndex = WasmIndices.find(Base)->second;
1685         assert(WasmIndices.count(&WS) == 0);
1686         WasmIndices[&WS] = WasmIndex;
1687         LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1688       } else if (Base->isData()) {
1689         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1690         uint64_t Offset = Layout.getSymbolOffset(S);
1691         int64_t Size = 0;
1692         // For data symbol alias we use the size of the base symbol as the
1693         // size of the alias.  When an offset from the base is involved this
1694         // can result in a offset + size goes past the end of the data section
1695         // which out object format doesn't support.  So we must clamp it.
1696         if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
1697           report_fatal_error(".size expression must be evaluatable");
1698         const WasmDataSegment &Segment =
1699             DataSegments[DataSection.getSegmentIndex()];
1700         Size =
1701             std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
1702         wasm::WasmDataReference Ref = wasm::WasmDataReference{
1703             DataSection.getSegmentIndex(),
1704             static_cast<uint32_t>(Layout.getSymbolOffset(S)),
1705             static_cast<uint32_t>(Size)};
1706         DataLocations[&WS] = Ref;
1707         LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
1708       } else {
1709         report_fatal_error("don't yet support global/event aliases");
1710       }
1711     }
1712   }
1713 
1714   // Finally, populate the symbol table itself, in its "natural" order.
1715   for (const MCSymbol &S : Asm.symbols()) {
1716     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1717     if (!isInSymtab(WS)) {
1718       WS.setIndex(InvalidIndex);
1719       continue;
1720     }
1721     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1722 
1723     uint32_t Flags = 0;
1724     if (WS.isWeak())
1725       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1726     if (WS.isHidden())
1727       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1728     if (!WS.isExternal() && WS.isDefined())
1729       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1730     if (WS.isUndefined())
1731       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1732     if (WS.isNoStrip()) {
1733       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1734       if (isEmscripten()) {
1735         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1736       }
1737     }
1738     if (WS.hasImportName())
1739       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1740     if (WS.hasExportName())
1741       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1742 
1743     wasm::WasmSymbolInfo Info;
1744     Info.Name = WS.getName();
1745     Info.Kind = WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA);
1746     Info.Flags = Flags;
1747     if (!WS.isData()) {
1748       assert(WasmIndices.count(&WS) > 0);
1749       Info.ElementIndex = WasmIndices.find(&WS)->second;
1750     } else if (WS.isDefined()) {
1751       assert(DataLocations.count(&WS) > 0);
1752       Info.DataRef = DataLocations.find(&WS)->second;
1753     }
1754     WS.setIndex(SymbolInfos.size());
1755     SymbolInfos.emplace_back(Info);
1756   }
1757 
1758   {
1759     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1760       // Functions referenced by a relocation need to put in the table.  This is
1761       // purely to make the object file's provisional values readable, and is
1762       // ignored by the linker, which re-calculates the relocations itself.
1763       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1764           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
1765           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1766           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
1767           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1768         return;
1769       assert(Rel.Symbol->isFunction());
1770       const MCSymbolWasm *Base =
1771           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
1772       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
1773       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1774       if (TableIndices.try_emplace(Base, TableIndex).second) {
1775         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1776                           << " to table: " << TableIndex << "\n");
1777         TableElems.push_back(FunctionIndex);
1778         registerFunctionType(*Base);
1779       }
1780     };
1781 
1782     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1783       HandleReloc(RelEntry);
1784     for (const WasmRelocationEntry &RelEntry : DataRelocations)
1785       HandleReloc(RelEntry);
1786   }
1787 
1788   // Translate .init_array section contents into start functions.
1789   for (const MCSection &S : Asm) {
1790     const auto &WS = static_cast<const MCSectionWasm &>(S);
1791     if (WS.getName().startswith(".fini_array"))
1792       report_fatal_error(".fini_array sections are unsupported");
1793     if (!WS.getName().startswith(".init_array"))
1794       continue;
1795     if (WS.getFragmentList().empty())
1796       continue;
1797 
1798     // init_array is expected to contain a single non-empty data fragment
1799     if (WS.getFragmentList().size() != 3)
1800       report_fatal_error("only one .init_array section fragment supported");
1801 
1802     auto IT = WS.begin();
1803     const MCFragment &EmptyFrag = *IT;
1804     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1805       report_fatal_error(".init_array section should be aligned");
1806 
1807     IT = std::next(IT);
1808     const MCFragment &AlignFrag = *IT;
1809     if (AlignFrag.getKind() != MCFragment::FT_Align)
1810       report_fatal_error(".init_array section should be aligned");
1811     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1812       report_fatal_error(".init_array section should be aligned for pointers");
1813 
1814     const MCFragment &Frag = *std::next(IT);
1815     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1816       report_fatal_error("only data supported in .init_array section");
1817 
1818     uint16_t Priority = UINT16_MAX;
1819     unsigned PrefixLength = strlen(".init_array");
1820     if (WS.getName().size() > PrefixLength) {
1821       if (WS.getName()[PrefixLength] != '.')
1822         report_fatal_error(
1823             ".init_array section priority should start with '.'");
1824       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1825         report_fatal_error("invalid .init_array section priority");
1826     }
1827     const auto &DataFrag = cast<MCDataFragment>(Frag);
1828     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1829     for (const uint8_t *
1830              P = (const uint8_t *)Contents.data(),
1831             *End = (const uint8_t *)Contents.data() + Contents.size();
1832          P != End; ++P) {
1833       if (*P != 0)
1834         report_fatal_error("non-symbolic data in .init_array section");
1835     }
1836     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1837       assert(Fixup.getKind() ==
1838              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1839       const MCExpr *Expr = Fixup.getValue();
1840       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1841       if (!SymRef)
1842         report_fatal_error("fixups in .init_array should be symbol references");
1843       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1844       if (TargetSym.getIndex() == InvalidIndex)
1845         report_fatal_error("symbols in .init_array should exist in symtab");
1846       if (!TargetSym.isFunction())
1847         report_fatal_error("symbols in .init_array should be for functions");
1848       InitFuncs.push_back(
1849           std::make_pair(Priority, TargetSym.getIndex()));
1850     }
1851   }
1852 
1853   // Write out the Wasm header.
1854   writeHeader(Asm);
1855 
1856   uint32_t CodeSectionIndex, DataSectionIndex;
1857   if (Mode != DwoMode::DwoOnly) {
1858     writeTypeSection(Signatures);
1859     writeImportSection(Imports, DataSize, TableElems.size());
1860     writeFunctionSection(Functions);
1861     writeTableSection(Tables);
1862     // Skip the "memory" section; we import the memory instead.
1863     writeEventSection(Events);
1864     writeGlobalSection(Globals);
1865     writeExportSection(Exports);
1866     const MCSymbol *IndirectFunctionTable =
1867         Asm.getContext().lookupSymbol("__indirect_function_table");
1868     writeElemSection(cast_or_null<const MCSymbolWasm>(IndirectFunctionTable),
1869                      TableElems);
1870     writeDataCountSection();
1871 
1872     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
1873     DataSectionIndex = writeDataSection(Layout);
1874   }
1875 
1876   // The Sections in the COMDAT list have placeholder indices (their index among
1877   // custom sections, rather than among all sections). Fix them up here.
1878   for (auto &Group : Comdats) {
1879     for (auto &Entry : Group.second) {
1880       if (Entry.Kind == wasm::WASM_COMDAT_SECTION) {
1881         Entry.Index += SectionCount;
1882       }
1883     }
1884   }
1885   for (auto &CustomSection : CustomSections)
1886     writeCustomSection(CustomSection, Asm, Layout);
1887 
1888   if (Mode != DwoMode::DwoOnly) {
1889     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1890 
1891     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1892     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1893   }
1894   writeCustomRelocSections();
1895   if (ProducersSection)
1896     writeCustomSection(*ProducersSection, Asm, Layout);
1897   if (TargetFeaturesSection)
1898     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1899 
1900   // TODO: Translate the .comment section to the output.
1901   return W->OS.tell() - StartOffset;
1902 }
1903 
1904 std::unique_ptr<MCObjectWriter>
1905 llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1906                              raw_pwrite_stream &OS) {
1907   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
1908 }
1909 
1910 std::unique_ptr<MCObjectWriter>
1911 llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1912                                 raw_pwrite_stream &OS,
1913                                 raw_pwrite_stream &DwoOS) {
1914   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
1915 }
1916