1 //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements Wasm object file writer information.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/BinaryFormat/Wasm.h"
16 #include "llvm/BinaryFormat/WasmTraits.h"
17 #include "llvm/Config/llvm-config.h"
18 #include "llvm/MC/MCAsmBackend.h"
19 #include "llvm/MC/MCAsmLayout.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCFixupKindInfo.h"
24 #include "llvm/MC/MCObjectWriter.h"
25 #include "llvm/MC/MCSectionWasm.h"
26 #include "llvm/MC/MCSymbolWasm.h"
27 #include "llvm/MC/MCValue.h"
28 #include "llvm/MC/MCWasmObjectWriter.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/EndianStream.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/LEB128.h"
34 #include "llvm/Support/StringSaver.h"
35 #include <vector>
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "mc"
40 
41 namespace {
42 
43 // When we create the indirect function table we start at 1, so that there is
44 // and empty slot at 0 and therefore calling a null function pointer will trap.
45 static const uint32_t InitialTableOffset = 1;
46 
47 // For patching purposes, we need to remember where each section starts, both
48 // for patching up the section size field, and for patching up references to
49 // locations within the section.
50 struct SectionBookkeeping {
51   // Where the size of the section is written.
52   uint64_t SizeOffset;
53   // Where the section header ends (without custom section name).
54   uint64_t PayloadOffset;
55   // Where the contents of the section starts.
56   uint64_t ContentsOffset;
57   uint32_t Index;
58 };
59 
60 // A wasm data segment.  A wasm binary contains only a single data section
61 // but that can contain many segments, each with their own virtual location
62 // in memory.  Each MCSection data created by llvm is modeled as its own
63 // wasm data segment.
64 struct WasmDataSegment {
65   MCSectionWasm *Section;
66   StringRef Name;
67   uint32_t InitFlags;
68   uint64_t Offset;
69   uint32_t Alignment;
70   uint32_t LinkingFlags;
71   SmallVector<char, 4> Data;
72 };
73 
74 // A wasm function to be written into the function section.
75 struct WasmFunction {
76   uint32_t SigIndex;
77   const MCSymbolWasm *Sym;
78 };
79 
80 // A wasm global to be written into the global section.
81 struct WasmGlobal {
82   wasm::WasmGlobalType Type;
83   uint64_t InitialValue;
84 };
85 
86 // Information about a single item which is part of a COMDAT.  For each data
87 // segment or function which is in the COMDAT, there is a corresponding
88 // WasmComdatEntry.
89 struct WasmComdatEntry {
90   unsigned Kind;
91   uint32_t Index;
92 };
93 
94 // Information about a single relocation.
95 struct WasmRelocationEntry {
96   uint64_t Offset;                   // Where is the relocation.
97   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
98   int64_t Addend;                    // A value to add to the symbol.
99   unsigned Type;                     // The type of the relocation.
100   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
101 
102   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
103                       int64_t Addend, unsigned Type,
104                       const MCSectionWasm *FixupSection)
105       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
106         FixupSection(FixupSection) {}
107 
108   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
109 
110   void print(raw_ostream &Out) const {
111     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
112         << ", Sym=" << *Symbol << ", Addend=" << Addend
113         << ", FixupSection=" << FixupSection->getName();
114   }
115 
116 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
117   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
118 #endif
119 };
120 
121 static const uint32_t InvalidIndex = -1;
122 
123 struct WasmCustomSection {
124 
125   StringRef Name;
126   MCSectionWasm *Section;
127 
128   uint32_t OutputContentsOffset;
129   uint32_t OutputIndex;
130 
131   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
132       : Name(Name), Section(Section), OutputContentsOffset(0),
133         OutputIndex(InvalidIndex) {}
134 };
135 
136 #if !defined(NDEBUG)
137 raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
138   Rel.print(OS);
139   return OS;
140 }
141 #endif
142 
143 // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
144 // to allow patching.
145 template <int W>
146 void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
147   uint8_t Buffer[W];
148   unsigned SizeLen = encodeULEB128(X, Buffer, W);
149   assert(SizeLen == W);
150   Stream.pwrite((char *)Buffer, SizeLen, Offset);
151 }
152 
153 // Write X as an signed LEB value at offset Offset in Stream, padded
154 // to allow patching.
155 template <int W>
156 void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) {
157   uint8_t Buffer[W];
158   unsigned SizeLen = encodeSLEB128(X, Buffer, W);
159   assert(SizeLen == W);
160   Stream.pwrite((char *)Buffer, SizeLen, Offset);
161 }
162 
163 // Write X as a plain integer value at offset Offset in Stream.
164 static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
165   uint8_t Buffer[4];
166   support::endian::write32le(Buffer, X);
167   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
168 }
169 
170 static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
171   uint8_t Buffer[8];
172   support::endian::write64le(Buffer, X);
173   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
174 }
175 
176 bool isDwoSection(const MCSection &Sec) {
177   return Sec.getName().endswith(".dwo");
178 }
179 
180 class WasmObjectWriter : public MCObjectWriter {
181   support::endian::Writer *W;
182 
183   /// The target specific Wasm writer instance.
184   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
185 
186   // Relocations for fixing up references in the code section.
187   std::vector<WasmRelocationEntry> CodeRelocations;
188   // Relocations for fixing up references in the data section.
189   std::vector<WasmRelocationEntry> DataRelocations;
190 
191   // Index values to use for fixing up call_indirect type indices.
192   // Maps function symbols to the index of the type of the function
193   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
194   // Maps function symbols to the table element index space. Used
195   // for TABLE_INDEX relocation types (i.e. address taken functions).
196   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
197   // Maps function/global/table symbols to the
198   // function/global/table/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) {
540       report_fatal_error("missing indirect function table symbol");
541     } else {
542       if (!Sym->isFunctionTable())
543         report_fatal_error("__indirect_function_table symbol has wrong type");
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.Minimum, 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.LinkingFlags, 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         Import.Table = WS.getTableType();
1342         Imports.push_back(Import);
1343         assert(WasmIndices.count(&WS) == 0);
1344         WasmIndices[&WS] = NumTableImports++;
1345       }
1346     }
1347   }
1348 
1349   // Add imports for GOT globals
1350   for (const MCSymbol &S : Asm.symbols()) {
1351     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1352     if (WS.isUsedInGOT()) {
1353       wasm::WasmImport Import;
1354       if (WS.isFunction())
1355         Import.Module = "GOT.func";
1356       else
1357         Import.Module = "GOT.mem";
1358       Import.Field = WS.getName();
1359       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1360       Import.Global = {wasm::WASM_TYPE_I32, true};
1361       Imports.push_back(Import);
1362       assert(GOTIndices.count(&WS) == 0);
1363       GOTIndices[&WS] = NumGlobalImports++;
1364     }
1365   }
1366 }
1367 
1368 uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1369                                        const MCAsmLayout &Layout) {
1370   support::endian::Writer MainWriter(*OS, support::little);
1371   W = &MainWriter;
1372   if (IsSplitDwarf) {
1373     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
1374     assert(DwoOS);
1375     support::endian::Writer DwoWriter(*DwoOS, support::little);
1376     W = &DwoWriter;
1377     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
1378   } else {
1379     return writeOneObject(Asm, Layout, DwoMode::AllSections);
1380   }
1381 }
1382 
1383 uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
1384                                           const MCAsmLayout &Layout,
1385                                           DwoMode Mode) {
1386   uint64_t StartOffset = W->OS.tell();
1387   SectionCount = 0;
1388   CustomSections.clear();
1389 
1390   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1391 
1392   // Collect information from the available symbols.
1393   SmallVector<WasmFunction, 4> Functions;
1394   SmallVector<uint32_t, 4> TableElems;
1395   SmallVector<wasm::WasmImport, 4> Imports;
1396   SmallVector<wasm::WasmExport, 4> Exports;
1397   SmallVector<wasm::WasmEventType, 1> Events;
1398   SmallVector<wasm::WasmGlobal, 1> Globals;
1399   SmallVector<wasm::WasmTable, 1> Tables;
1400   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1401   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1402   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
1403   uint64_t DataSize = 0;
1404   if (Mode != DwoMode::DwoOnly) {
1405     prepareImports(Imports, Asm, Layout);
1406   }
1407 
1408   // Populate DataSegments and CustomSections, which must be done before
1409   // populating DataLocations.
1410   for (MCSection &Sec : Asm) {
1411     auto &Section = static_cast<MCSectionWasm &>(Sec);
1412     StringRef SectionName = Section.getName();
1413 
1414     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
1415       continue;
1416     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
1417       continue;
1418 
1419     LLVM_DEBUG(dbgs() << "Processing Section " << SectionName << "  group "
1420                       << Section.getGroup() << "\n";);
1421 
1422     // .init_array sections are handled specially elsewhere.
1423     if (SectionName.startswith(".init_array"))
1424       continue;
1425 
1426     // Code is handled separately
1427     if (Section.getKind().isText())
1428       continue;
1429 
1430     if (Section.isWasmData()) {
1431       uint32_t SegmentIndex = DataSegments.size();
1432       DataSize = alignTo(DataSize, Section.getAlignment());
1433       DataSegments.emplace_back();
1434       WasmDataSegment &Segment = DataSegments.back();
1435       Segment.Name = SectionName;
1436       Segment.InitFlags = Section.getPassive()
1437                               ? (uint32_t)wasm::WASM_DATA_SEGMENT_IS_PASSIVE
1438                               : 0;
1439       Segment.Offset = DataSize;
1440       Segment.Section = &Section;
1441       addData(Segment.Data, Section);
1442       Segment.Alignment = Log2_32(Section.getAlignment());
1443       Segment.LinkingFlags = Section.getSegmentFlags();
1444       DataSize += Segment.Data.size();
1445       Section.setSegmentIndex(SegmentIndex);
1446 
1447       if (const MCSymbolWasm *C = Section.getGroup()) {
1448         Comdats[C->getName()].emplace_back(
1449             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1450       }
1451     } else {
1452       // Create custom sections
1453       assert(Sec.getKind().isMetadata());
1454 
1455       StringRef Name = SectionName;
1456 
1457       // For user-defined custom sections, strip the prefix
1458       if (Name.startswith(".custom_section."))
1459         Name = Name.substr(strlen(".custom_section."));
1460 
1461       MCSymbol *Begin = Sec.getBeginSymbol();
1462       if (Begin) {
1463         assert(WasmIndices.count(cast<MCSymbolWasm>(Begin)) == 0);
1464         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1465       }
1466 
1467       // Separate out the producers and target features sections
1468       if (Name == "producers") {
1469         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1470         continue;
1471       }
1472       if (Name == "target_features") {
1473         TargetFeaturesSection =
1474             std::make_unique<WasmCustomSection>(Name, &Section);
1475         continue;
1476       }
1477 
1478       // Custom sections can also belong to COMDAT groups. In this case the
1479       // decriptor's "index" field is the section index (in the final object
1480       // file), but that is not known until after layout, so it must be fixed up
1481       // later
1482       if (const MCSymbolWasm *C = Section.getGroup()) {
1483         Comdats[C->getName()].emplace_back(
1484             WasmComdatEntry{wasm::WASM_COMDAT_SECTION,
1485                             static_cast<uint32_t>(CustomSections.size())});
1486       }
1487 
1488       CustomSections.emplace_back(Name, &Section);
1489     }
1490   }
1491 
1492   if (Mode != DwoMode::DwoOnly) {
1493     // Populate WasmIndices and DataLocations for defined symbols.
1494     for (const MCSymbol &S : Asm.symbols()) {
1495       // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1496       // or used in relocations.
1497       if (S.isTemporary() && S.getName().empty())
1498         continue;
1499 
1500       const auto &WS = static_cast<const MCSymbolWasm &>(S);
1501       LLVM_DEBUG(dbgs()
1502                  << "MCSymbol: "
1503                  << toString(WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA))
1504                  << " '" << S << "'"
1505                  << " isDefined=" << S.isDefined() << " isExternal="
1506                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1507                  << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1508                  << " isVariable=" << WS.isVariable() << "\n");
1509 
1510       if (WS.isVariable())
1511         continue;
1512       if (WS.isComdat() && !WS.isDefined())
1513         continue;
1514 
1515       if (WS.isFunction()) {
1516         unsigned Index;
1517         if (WS.isDefined()) {
1518           if (WS.getOffset() != 0)
1519             report_fatal_error(
1520                 "function sections must contain one function each");
1521 
1522           if (WS.getSize() == nullptr)
1523             report_fatal_error(
1524                 "function symbols must have a size set with .size");
1525 
1526           // A definition. Write out the function body.
1527           Index = NumFunctionImports + Functions.size();
1528           WasmFunction Func;
1529           Func.SigIndex = getFunctionType(WS);
1530           Func.Sym = &WS;
1531           assert(WasmIndices.count(&WS) == 0);
1532           WasmIndices[&WS] = Index;
1533           Functions.push_back(Func);
1534 
1535           auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1536           if (const MCSymbolWasm *C = Section.getGroup()) {
1537             Comdats[C->getName()].emplace_back(
1538                 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1539           }
1540 
1541           if (WS.hasExportName()) {
1542             wasm::WasmExport Export;
1543             Export.Name = WS.getExportName();
1544             Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1545             Export.Index = Index;
1546             Exports.push_back(Export);
1547           }
1548         } else {
1549           // An import; the index was assigned above.
1550           Index = WasmIndices.find(&WS)->second;
1551         }
1552 
1553         LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1554 
1555       } else if (WS.isData()) {
1556         if (!isInSymtab(WS))
1557           continue;
1558 
1559         if (!WS.isDefined()) {
1560           LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1561                             << "\n");
1562           continue;
1563         }
1564 
1565         if (!WS.getSize())
1566           report_fatal_error("data symbols must have a size set with .size: " +
1567                              WS.getName());
1568 
1569         int64_t Size = 0;
1570         if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1571           report_fatal_error(".size expression must be evaluatable");
1572 
1573         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1574         if (!DataSection.isWasmData())
1575           report_fatal_error("data symbols must live in a data section: " +
1576                              WS.getName());
1577 
1578         // For each data symbol, export it in the symtab as a reference to the
1579         // corresponding Wasm data segment.
1580         wasm::WasmDataReference Ref = wasm::WasmDataReference{
1581             DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
1582             static_cast<uint64_t>(Size)};
1583         assert(DataLocations.count(&WS) == 0);
1584         DataLocations[&WS] = Ref;
1585         LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1586 
1587       } else if (WS.isGlobal()) {
1588         // A "true" Wasm global (currently just __stack_pointer)
1589         if (WS.isDefined()) {
1590           wasm::WasmGlobal Global;
1591           Global.Type = WS.getGlobalType();
1592           Global.Index = NumGlobalImports + Globals.size();
1593           switch (Global.Type.Type) {
1594           case wasm::WASM_TYPE_I32:
1595             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
1596             break;
1597           case wasm::WASM_TYPE_I64:
1598             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
1599             break;
1600           case wasm::WASM_TYPE_F32:
1601             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
1602             break;
1603           case wasm::WASM_TYPE_F64:
1604             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
1605             break;
1606           case wasm::WASM_TYPE_EXTERNREF:
1607             Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
1608             break;
1609           default:
1610             llvm_unreachable("unexpected type");
1611           }
1612           assert(WasmIndices.count(&WS) == 0);
1613           WasmIndices[&WS] = Global.Index;
1614           Globals.push_back(Global);
1615         } else {
1616           // An import; the index was assigned above
1617           LLVM_DEBUG(dbgs() << "  -> global index: "
1618                             << WasmIndices.find(&WS)->second << "\n");
1619         }
1620       } else if (WS.isTable()) {
1621         if (WS.isDefined()) {
1622           wasm::WasmTable Table;
1623           Table.Index = NumTableImports + Tables.size();
1624           Table.Type = WS.getTableType();
1625           assert(WasmIndices.count(&WS) == 0);
1626           WasmIndices[&WS] = Table.Index;
1627           Tables.push_back(Table);
1628         }
1629         LLVM_DEBUG(dbgs() << " -> table index: "
1630                           << WasmIndices.find(&WS)->second << "\n");
1631       } else if (WS.isEvent()) {
1632         // C++ exception symbol (__cpp_exception)
1633         unsigned Index;
1634         if (WS.isDefined()) {
1635           Index = NumEventImports + Events.size();
1636           wasm::WasmEventType Event;
1637           Event.SigIndex = getEventType(WS);
1638           Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1639           assert(WasmIndices.count(&WS) == 0);
1640           WasmIndices[&WS] = Index;
1641           Events.push_back(Event);
1642         } else {
1643           // An import; the index was assigned above.
1644           assert(WasmIndices.count(&WS) > 0);
1645         }
1646         LLVM_DEBUG(dbgs() << "  -> event index: "
1647                           << WasmIndices.find(&WS)->second << "\n");
1648 
1649       } else {
1650         assert(WS.isSection());
1651       }
1652     }
1653 
1654     // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1655     // process these in a separate pass because we need to have processed the
1656     // target of the alias before the alias itself and the symbols are not
1657     // necessarily ordered in this way.
1658     for (const MCSymbol &S : Asm.symbols()) {
1659       if (!S.isVariable())
1660         continue;
1661 
1662       assert(S.isDefined());
1663 
1664       const auto *BS = Layout.getBaseSymbol(S);
1665       if (!BS)
1666         report_fatal_error(Twine(S.getName()) +
1667                            ": absolute addressing not supported!");
1668       const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
1669 
1670       // Find the target symbol of this weak alias and export that index
1671       const auto &WS = static_cast<const MCSymbolWasm &>(S);
1672       LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base
1673                         << "'\n");
1674 
1675       if (Base->isFunction()) {
1676         assert(WasmIndices.count(Base) > 0);
1677         uint32_t WasmIndex = WasmIndices.find(Base)->second;
1678         assert(WasmIndices.count(&WS) == 0);
1679         WasmIndices[&WS] = WasmIndex;
1680         LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1681       } else if (Base->isData()) {
1682         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1683         uint64_t Offset = Layout.getSymbolOffset(S);
1684         int64_t Size = 0;
1685         // For data symbol alias we use the size of the base symbol as the
1686         // size of the alias.  When an offset from the base is involved this
1687         // can result in a offset + size goes past the end of the data section
1688         // which out object format doesn't support.  So we must clamp it.
1689         if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
1690           report_fatal_error(".size expression must be evaluatable");
1691         const WasmDataSegment &Segment =
1692             DataSegments[DataSection.getSegmentIndex()];
1693         Size =
1694             std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
1695         wasm::WasmDataReference Ref = wasm::WasmDataReference{
1696             DataSection.getSegmentIndex(),
1697             static_cast<uint32_t>(Layout.getSymbolOffset(S)),
1698             static_cast<uint32_t>(Size)};
1699         DataLocations[&WS] = Ref;
1700         LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
1701       } else {
1702         report_fatal_error("don't yet support global/event aliases");
1703       }
1704     }
1705   }
1706 
1707   // Finally, populate the symbol table itself, in its "natural" order.
1708   for (const MCSymbol &S : Asm.symbols()) {
1709     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1710     if (!isInSymtab(WS)) {
1711       WS.setIndex(InvalidIndex);
1712       continue;
1713     }
1714     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1715 
1716     uint32_t Flags = 0;
1717     if (WS.isWeak())
1718       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1719     if (WS.isHidden())
1720       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1721     if (!WS.isExternal() && WS.isDefined())
1722       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1723     if (WS.isUndefined())
1724       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1725     if (WS.isNoStrip()) {
1726       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1727       if (isEmscripten()) {
1728         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1729       }
1730     }
1731     if (WS.hasImportName())
1732       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1733     if (WS.hasExportName())
1734       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1735 
1736     wasm::WasmSymbolInfo Info;
1737     Info.Name = WS.getName();
1738     Info.Kind = WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA);
1739     Info.Flags = Flags;
1740     if (!WS.isData()) {
1741       assert(WasmIndices.count(&WS) > 0);
1742       Info.ElementIndex = WasmIndices.find(&WS)->second;
1743     } else if (WS.isDefined()) {
1744       assert(DataLocations.count(&WS) > 0);
1745       Info.DataRef = DataLocations.find(&WS)->second;
1746     }
1747     WS.setIndex(SymbolInfos.size());
1748     SymbolInfos.emplace_back(Info);
1749   }
1750 
1751   {
1752     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1753       // Functions referenced by a relocation need to put in the table.  This is
1754       // purely to make the object file's provisional values readable, and is
1755       // ignored by the linker, which re-calculates the relocations itself.
1756       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1757           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
1758           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1759           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
1760           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1761         return;
1762       assert(Rel.Symbol->isFunction());
1763       const MCSymbolWasm *Base =
1764           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
1765       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
1766       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1767       if (TableIndices.try_emplace(Base, TableIndex).second) {
1768         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1769                           << " to table: " << TableIndex << "\n");
1770         TableElems.push_back(FunctionIndex);
1771         registerFunctionType(*Base);
1772       }
1773     };
1774 
1775     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1776       HandleReloc(RelEntry);
1777     for (const WasmRelocationEntry &RelEntry : DataRelocations)
1778       HandleReloc(RelEntry);
1779   }
1780 
1781   // Translate .init_array section contents into start functions.
1782   for (const MCSection &S : Asm) {
1783     const auto &WS = static_cast<const MCSectionWasm &>(S);
1784     if (WS.getName().startswith(".fini_array"))
1785       report_fatal_error(".fini_array sections are unsupported");
1786     if (!WS.getName().startswith(".init_array"))
1787       continue;
1788     if (WS.getFragmentList().empty())
1789       continue;
1790 
1791     // init_array is expected to contain a single non-empty data fragment
1792     if (WS.getFragmentList().size() != 3)
1793       report_fatal_error("only one .init_array section fragment supported");
1794 
1795     auto IT = WS.begin();
1796     const MCFragment &EmptyFrag = *IT;
1797     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1798       report_fatal_error(".init_array section should be aligned");
1799 
1800     IT = std::next(IT);
1801     const MCFragment &AlignFrag = *IT;
1802     if (AlignFrag.getKind() != MCFragment::FT_Align)
1803       report_fatal_error(".init_array section should be aligned");
1804     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1805       report_fatal_error(".init_array section should be aligned for pointers");
1806 
1807     const MCFragment &Frag = *std::next(IT);
1808     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1809       report_fatal_error("only data supported in .init_array section");
1810 
1811     uint16_t Priority = UINT16_MAX;
1812     unsigned PrefixLength = strlen(".init_array");
1813     if (WS.getName().size() > PrefixLength) {
1814       if (WS.getName()[PrefixLength] != '.')
1815         report_fatal_error(
1816             ".init_array section priority should start with '.'");
1817       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1818         report_fatal_error("invalid .init_array section priority");
1819     }
1820     const auto &DataFrag = cast<MCDataFragment>(Frag);
1821     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1822     for (const uint8_t *
1823              P = (const uint8_t *)Contents.data(),
1824             *End = (const uint8_t *)Contents.data() + Contents.size();
1825          P != End; ++P) {
1826       if (*P != 0)
1827         report_fatal_error("non-symbolic data in .init_array section");
1828     }
1829     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1830       assert(Fixup.getKind() ==
1831              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1832       const MCExpr *Expr = Fixup.getValue();
1833       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1834       if (!SymRef)
1835         report_fatal_error("fixups in .init_array should be symbol references");
1836       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1837       if (TargetSym.getIndex() == InvalidIndex)
1838         report_fatal_error("symbols in .init_array should exist in symtab");
1839       if (!TargetSym.isFunction())
1840         report_fatal_error("symbols in .init_array should be for functions");
1841       InitFuncs.push_back(
1842           std::make_pair(Priority, TargetSym.getIndex()));
1843     }
1844   }
1845 
1846   // Write out the Wasm header.
1847   writeHeader(Asm);
1848 
1849   uint32_t CodeSectionIndex, DataSectionIndex;
1850   if (Mode != DwoMode::DwoOnly) {
1851     writeTypeSection(Signatures);
1852     writeImportSection(Imports, DataSize, TableElems.size());
1853     writeFunctionSection(Functions);
1854     writeTableSection(Tables);
1855     // Skip the "memory" section; we import the memory instead.
1856     writeEventSection(Events);
1857     writeGlobalSection(Globals);
1858     writeExportSection(Exports);
1859     const MCSymbol *IndirectFunctionTable =
1860         Asm.getContext().lookupSymbol("__indirect_function_table");
1861     writeElemSection(cast_or_null<const MCSymbolWasm>(IndirectFunctionTable),
1862                      TableElems);
1863     writeDataCountSection();
1864 
1865     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
1866     DataSectionIndex = writeDataSection(Layout);
1867   }
1868 
1869   // The Sections in the COMDAT list have placeholder indices (their index among
1870   // custom sections, rather than among all sections). Fix them up here.
1871   for (auto &Group : Comdats) {
1872     for (auto &Entry : Group.second) {
1873       if (Entry.Kind == wasm::WASM_COMDAT_SECTION) {
1874         Entry.Index += SectionCount;
1875       }
1876     }
1877   }
1878   for (auto &CustomSection : CustomSections)
1879     writeCustomSection(CustomSection, Asm, Layout);
1880 
1881   if (Mode != DwoMode::DwoOnly) {
1882     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1883 
1884     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1885     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1886   }
1887   writeCustomRelocSections();
1888   if (ProducersSection)
1889     writeCustomSection(*ProducersSection, Asm, Layout);
1890   if (TargetFeaturesSection)
1891     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1892 
1893   // TODO: Translate the .comment section to the output.
1894   return W->OS.tell() - StartOffset;
1895 }
1896 
1897 std::unique_ptr<MCObjectWriter>
1898 llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1899                              raw_pwrite_stream &OS) {
1900   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
1901 }
1902 
1903 std::unique_ptr<MCObjectWriter>
1904 llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1905                                 raw_pwrite_stream &OS,
1906                                 raw_pwrite_stream &DwoOS) {
1907   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
1908 }
1909