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