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       SectionSymbol = SectionFunctions.find(&SecA)->second;
493     else
494       SectionSymbol = SecA.getBeginSymbol();
495     if (!SectionSymbol)
496       report_fatal_error("section symbol is required for relocation");
497 
498     C += Layout.getSymbolOffset(*SymA);
499     SymA = cast<MCSymbolWasm>(SectionSymbol);
500   }
501 
502   if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
503       Type == wasm::R_WASM_TABLE_INDEX_SLEB ||
504       Type == wasm::R_WASM_TABLE_INDEX_SLEB64 ||
505       Type == wasm::R_WASM_TABLE_INDEX_I32 ||
506       Type == wasm::R_WASM_TABLE_INDEX_I64) {
507     // TABLE_INDEX relocs implicitly use the default indirect function table.
508     auto TableName = "__indirect_function_table";
509     MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName));
510     if (Sym) {
511       if (!Sym->isFunctionTable())
512         Ctx.reportError(
513             Fixup.getLoc(),
514             "symbol '__indirect_function_table' is not a function table");
515     } else {
516       Sym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(TableName));
517       Sym->setFunctionTable();
518       // The default function table is synthesized by the linker.
519       Sym->setUndefined();
520     }
521     Sym->setUsedInReloc();
522     // Any time we have a TABLE_INDEX relocation against a function symbol, we
523     // need to ensure that table itself is part of the final output too.  In the
524     // future we may want to define a new kind of reloc against both the
525     // function and the table, so that the linker can see that the function
526     // symbol keeps the table alive, but for now manually mark the table as
527     // live.
528     Sym->setNoStrip();
529     Asm.registerSymbol(*Sym);
530   }
531 
532   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
533   // against a named symbol.
534   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
535     if (SymA->getName().empty())
536       report_fatal_error("relocations against un-named temporaries are not yet "
537                          "supported by wasm");
538 
539     SymA->setUsedInReloc();
540   }
541 
542   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
543     SymA->setUsedInGOT();
544 
545   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
546   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
547 
548   if (FixupSection.isWasmData()) {
549     DataRelocations.push_back(Rec);
550   } else if (FixupSection.getKind().isText()) {
551     CodeRelocations.push_back(Rec);
552   } else if (FixupSection.getKind().isMetadata()) {
553     CustomSectionsRelocations[&FixupSection].push_back(Rec);
554   } else {
555     llvm_unreachable("unexpected section type");
556   }
557 }
558 
559 // Compute a value to write into the code at the location covered
560 // by RelEntry. This value isn't used by the static linker; it just serves
561 // to make the object format more readable and more likely to be directly
562 // useable.
563 uint64_t
564 WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
565                                       const MCAsmLayout &Layout) {
566   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
567        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
568       !RelEntry.Symbol->isGlobal()) {
569     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
570     return GOTIndices[RelEntry.Symbol];
571   }
572 
573   switch (RelEntry.Type) {
574   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
575   case wasm::R_WASM_TABLE_INDEX_SLEB:
576   case wasm::R_WASM_TABLE_INDEX_SLEB64:
577   case wasm::R_WASM_TABLE_INDEX_I32:
578   case wasm::R_WASM_TABLE_INDEX_I64: {
579     // Provisional value is table address of the resolved symbol itself
580     const MCSymbolWasm *Base =
581         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
582     assert(Base->isFunction());
583     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
584       return TableIndices[Base] - InitialTableOffset;
585     else
586       return TableIndices[Base];
587   }
588   case wasm::R_WASM_TYPE_INDEX_LEB:
589     // Provisional value is same as the index
590     return getRelocationIndexValue(RelEntry);
591   case wasm::R_WASM_FUNCTION_INDEX_LEB:
592   case wasm::R_WASM_GLOBAL_INDEX_LEB:
593   case wasm::R_WASM_GLOBAL_INDEX_I32:
594   case wasm::R_WASM_EVENT_INDEX_LEB:
595   case wasm::R_WASM_TABLE_NUMBER_LEB:
596     // Provisional value is function/global/event Wasm index
597     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
598     return WasmIndices[RelEntry.Symbol];
599   case wasm::R_WASM_FUNCTION_OFFSET_I32:
600   case wasm::R_WASM_FUNCTION_OFFSET_I64:
601   case wasm::R_WASM_SECTION_OFFSET_I32: {
602     const auto &Section =
603         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
604     return Section.getSectionOffset() + RelEntry.Addend;
605   }
606   case wasm::R_WASM_MEMORY_ADDR_LEB:
607   case wasm::R_WASM_MEMORY_ADDR_LEB64:
608   case wasm::R_WASM_MEMORY_ADDR_SLEB:
609   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
610   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
611   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
612   case wasm::R_WASM_MEMORY_ADDR_I32:
613   case wasm::R_WASM_MEMORY_ADDR_I64:
614   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB: {
615     // Provisional value is address of the global plus the offset
616     const MCSymbolWasm *Base =
617         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
618     // For undefined symbols, use zero
619     if (!Base->isDefined())
620       return 0;
621     const wasm::WasmDataReference &BaseRef = DataLocations[Base],
622                                   &SymRef = DataLocations[RelEntry.Symbol];
623     const WasmDataSegment &Segment = DataSegments[BaseRef.Segment];
624     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
625     return Segment.Offset + BaseRef.Offset + SymRef.Offset + RelEntry.Addend;
626   }
627   default:
628     llvm_unreachable("invalid relocation type");
629   }
630 }
631 
632 static void addData(SmallVectorImpl<char> &DataBytes,
633                     MCSectionWasm &DataSection) {
634   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
635 
636   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
637 
638   for (const MCFragment &Frag : DataSection) {
639     if (Frag.hasInstructions())
640       report_fatal_error("only data supported in data sections");
641 
642     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
643       if (Align->getValueSize() != 1)
644         report_fatal_error("only byte values supported for alignment");
645       // If nops are requested, use zeros, as this is the data section.
646       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
647       uint64_t Size =
648           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
649                              DataBytes.size() + Align->getMaxBytesToEmit());
650       DataBytes.resize(Size, Value);
651     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
652       int64_t NumValues;
653       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
654         llvm_unreachable("The fill should be an assembler constant");
655       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
656                        Fill->getValue());
657     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
658       const SmallVectorImpl<char> &Contents = LEB->getContents();
659       llvm::append_range(DataBytes, Contents);
660     } else {
661       const auto &DataFrag = cast<MCDataFragment>(Frag);
662       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
663       llvm::append_range(DataBytes, Contents);
664     }
665   }
666 
667   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
668 }
669 
670 uint32_t
671 WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
672   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
673     if (!TypeIndices.count(RelEntry.Symbol))
674       report_fatal_error("symbol not found in type index space: " +
675                          RelEntry.Symbol->getName());
676     return TypeIndices[RelEntry.Symbol];
677   }
678 
679   return RelEntry.Symbol->getIndex();
680 }
681 
682 // Apply the portions of the relocation records that we can handle ourselves
683 // directly.
684 void WasmObjectWriter::applyRelocations(
685     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
686     const MCAsmLayout &Layout) {
687   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
688   for (const WasmRelocationEntry &RelEntry : Relocations) {
689     uint64_t Offset = ContentsOffset +
690                       RelEntry.FixupSection->getSectionOffset() +
691                       RelEntry.Offset;
692 
693     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
694     auto Value = getProvisionalValue(RelEntry, Layout);
695 
696     switch (RelEntry.Type) {
697     case wasm::R_WASM_FUNCTION_INDEX_LEB:
698     case wasm::R_WASM_TYPE_INDEX_LEB:
699     case wasm::R_WASM_GLOBAL_INDEX_LEB:
700     case wasm::R_WASM_MEMORY_ADDR_LEB:
701     case wasm::R_WASM_EVENT_INDEX_LEB:
702     case wasm::R_WASM_TABLE_NUMBER_LEB:
703       writePatchableLEB<5>(Stream, Value, Offset);
704       break;
705     case wasm::R_WASM_MEMORY_ADDR_LEB64:
706       writePatchableLEB<10>(Stream, Value, Offset);
707       break;
708     case wasm::R_WASM_TABLE_INDEX_I32:
709     case wasm::R_WASM_MEMORY_ADDR_I32:
710     case wasm::R_WASM_FUNCTION_OFFSET_I32:
711     case wasm::R_WASM_SECTION_OFFSET_I32:
712     case wasm::R_WASM_GLOBAL_INDEX_I32:
713       patchI32(Stream, Value, Offset);
714       break;
715     case wasm::R_WASM_TABLE_INDEX_I64:
716     case wasm::R_WASM_MEMORY_ADDR_I64:
717     case wasm::R_WASM_FUNCTION_OFFSET_I64:
718       patchI64(Stream, Value, Offset);
719       break;
720     case wasm::R_WASM_TABLE_INDEX_SLEB:
721     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
722     case wasm::R_WASM_MEMORY_ADDR_SLEB:
723     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
724     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
725       writePatchableSLEB<5>(Stream, Value, Offset);
726       break;
727     case wasm::R_WASM_TABLE_INDEX_SLEB64:
728     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
729     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
730       writePatchableSLEB<10>(Stream, Value, Offset);
731       break;
732     default:
733       llvm_unreachable("invalid relocation type");
734     }
735   }
736 }
737 
738 void WasmObjectWriter::writeTypeSection(
739     ArrayRef<wasm::WasmSignature> Signatures) {
740   if (Signatures.empty())
741     return;
742 
743   SectionBookkeeping Section;
744   startSection(Section, wasm::WASM_SEC_TYPE);
745 
746   encodeULEB128(Signatures.size(), W->OS);
747 
748   for (const wasm::WasmSignature &Sig : Signatures) {
749     W->OS << char(wasm::WASM_TYPE_FUNC);
750     encodeULEB128(Sig.Params.size(), W->OS);
751     for (wasm::ValType Ty : Sig.Params)
752       writeValueType(Ty);
753     encodeULEB128(Sig.Returns.size(), W->OS);
754     for (wasm::ValType Ty : Sig.Returns)
755       writeValueType(Ty);
756   }
757 
758   endSection(Section);
759 }
760 
761 void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
762                                           uint64_t DataSize,
763                                           uint32_t NumElements) {
764   if (Imports.empty())
765     return;
766 
767   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
768 
769   SectionBookkeeping Section;
770   startSection(Section, wasm::WASM_SEC_IMPORT);
771 
772   encodeULEB128(Imports.size(), W->OS);
773   for (const wasm::WasmImport &Import : Imports) {
774     writeString(Import.Module);
775     writeString(Import.Field);
776     W->OS << char(Import.Kind);
777 
778     switch (Import.Kind) {
779     case wasm::WASM_EXTERNAL_FUNCTION:
780       encodeULEB128(Import.SigIndex, W->OS);
781       break;
782     case wasm::WASM_EXTERNAL_GLOBAL:
783       W->OS << char(Import.Global.Type);
784       W->OS << char(Import.Global.Mutable ? 1 : 0);
785       break;
786     case wasm::WASM_EXTERNAL_MEMORY:
787       encodeULEB128(Import.Memory.Flags, W->OS);
788       encodeULEB128(NumPages, W->OS); // initial
789       break;
790     case wasm::WASM_EXTERNAL_TABLE:
791       W->OS << char(Import.Table.ElemType);
792       encodeULEB128(0, W->OS);           // flags
793       encodeULEB128(NumElements, W->OS); // initial
794       break;
795     case wasm::WASM_EXTERNAL_EVENT:
796       encodeULEB128(Import.Event.Attribute, W->OS);
797       encodeULEB128(Import.Event.SigIndex, W->OS);
798       break;
799     default:
800       llvm_unreachable("unsupported import kind");
801     }
802   }
803 
804   endSection(Section);
805 }
806 
807 void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
808   if (Functions.empty())
809     return;
810 
811   SectionBookkeeping Section;
812   startSection(Section, wasm::WASM_SEC_FUNCTION);
813 
814   encodeULEB128(Functions.size(), W->OS);
815   for (const WasmFunction &Func : Functions)
816     encodeULEB128(Func.SigIndex, W->OS);
817 
818   endSection(Section);
819 }
820 
821 void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
822   if (Events.empty())
823     return;
824 
825   SectionBookkeeping Section;
826   startSection(Section, wasm::WASM_SEC_EVENT);
827 
828   encodeULEB128(Events.size(), W->OS);
829   for (const wasm::WasmEventType &Event : Events) {
830     encodeULEB128(Event.Attribute, W->OS);
831     encodeULEB128(Event.SigIndex, W->OS);
832   }
833 
834   endSection(Section);
835 }
836 
837 void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
838   if (Globals.empty())
839     return;
840 
841   SectionBookkeeping Section;
842   startSection(Section, wasm::WASM_SEC_GLOBAL);
843 
844   encodeULEB128(Globals.size(), W->OS);
845   for (const wasm::WasmGlobal &Global : Globals) {
846     encodeULEB128(Global.Type.Type, W->OS);
847     W->OS << char(Global.Type.Mutable);
848     W->OS << char(Global.InitExpr.Opcode);
849     switch (Global.Type.Type) {
850     case wasm::WASM_TYPE_I32:
851       encodeSLEB128(0, W->OS);
852       break;
853     case wasm::WASM_TYPE_I64:
854       encodeSLEB128(0, W->OS);
855       break;
856     case wasm::WASM_TYPE_F32:
857       writeI32(0);
858       break;
859     case wasm::WASM_TYPE_F64:
860       writeI64(0);
861       break;
862     case wasm::WASM_TYPE_EXTERNREF:
863       writeValueType(wasm::ValType::EXTERNREF);
864       break;
865     default:
866       llvm_unreachable("unexpected type");
867     }
868     W->OS << char(wasm::WASM_OPCODE_END);
869   }
870 
871   endSection(Section);
872 }
873 
874 void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
875   if (Tables.empty())
876     return;
877 
878   SectionBookkeeping Section;
879   startSection(Section, wasm::WASM_SEC_TABLE);
880 
881   encodeULEB128(Tables.size(), W->OS);
882   for (const wasm::WasmTable &Table : Tables) {
883     encodeULEB128(Table.Type.ElemType, W->OS);
884     encodeULEB128(Table.Type.Limits.Flags, W->OS);
885     encodeULEB128(Table.Type.Limits.Initial, W->OS);
886     if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
887       encodeULEB128(Table.Type.Limits.Maximum, W->OS);
888   }
889   endSection(Section);
890 }
891 
892 void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
893   if (Exports.empty())
894     return;
895 
896   SectionBookkeeping Section;
897   startSection(Section, wasm::WASM_SEC_EXPORT);
898 
899   encodeULEB128(Exports.size(), W->OS);
900   for (const wasm::WasmExport &Export : Exports) {
901     writeString(Export.Name);
902     W->OS << char(Export.Kind);
903     encodeULEB128(Export.Index, W->OS);
904   }
905 
906   endSection(Section);
907 }
908 
909 void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
910   if (TableElems.empty())
911     return;
912 
913   SectionBookkeeping Section;
914   startSection(Section, wasm::WASM_SEC_ELEM);
915 
916   encodeULEB128(1, W->OS); // number of "segments"
917   encodeULEB128(0, W->OS); // the table index
918 
919   // init expr for starting offset
920   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
921   encodeSLEB128(InitialTableOffset, W->OS);
922   W->OS << char(wasm::WASM_OPCODE_END);
923 
924   encodeULEB128(TableElems.size(), W->OS);
925   for (uint32_t Elem : TableElems)
926     encodeULEB128(Elem, W->OS);
927 
928   endSection(Section);
929 }
930 
931 void WasmObjectWriter::writeDataCountSection() {
932   if (DataSegments.empty())
933     return;
934 
935   SectionBookkeeping Section;
936   startSection(Section, wasm::WASM_SEC_DATACOUNT);
937   encodeULEB128(DataSegments.size(), W->OS);
938   endSection(Section);
939 }
940 
941 uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
942                                             const MCAsmLayout &Layout,
943                                             ArrayRef<WasmFunction> Functions) {
944   if (Functions.empty())
945     return 0;
946 
947   SectionBookkeeping Section;
948   startSection(Section, wasm::WASM_SEC_CODE);
949 
950   encodeULEB128(Functions.size(), W->OS);
951 
952   for (const WasmFunction &Func : Functions) {
953     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
954 
955     int64_t Size = 0;
956     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
957       report_fatal_error(".size expression must be evaluatable");
958 
959     encodeULEB128(Size, W->OS);
960     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
961     Asm.writeSectionData(W->OS, &FuncSection, Layout);
962   }
963 
964   // Apply fixups.
965   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
966 
967   endSection(Section);
968   return Section.Index;
969 }
970 
971 uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
972   if (DataSegments.empty())
973     return 0;
974 
975   SectionBookkeeping Section;
976   startSection(Section, wasm::WASM_SEC_DATA);
977 
978   encodeULEB128(DataSegments.size(), W->OS); // count
979 
980   for (const WasmDataSegment &Segment : DataSegments) {
981     encodeULEB128(Segment.InitFlags, W->OS); // flags
982     if (Segment.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
983       encodeULEB128(0, W->OS); // memory index
984     if ((Segment.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
985       W->OS << char(Segment.Offset > INT32_MAX ? wasm::WASM_OPCODE_I64_CONST
986                                                : wasm::WASM_OPCODE_I32_CONST);
987       encodeSLEB128(Segment.Offset, W->OS); // offset
988       W->OS << char(wasm::WASM_OPCODE_END);
989     }
990     encodeULEB128(Segment.Data.size(), W->OS); // size
991     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
992     W->OS << Segment.Data; // data
993   }
994 
995   // Apply fixups.
996   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
997 
998   endSection(Section);
999   return Section.Index;
1000 }
1001 
1002 void WasmObjectWriter::writeRelocSection(
1003     uint32_t SectionIndex, StringRef Name,
1004     std::vector<WasmRelocationEntry> &Relocs) {
1005   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
1006   // for descriptions of the reloc sections.
1007 
1008   if (Relocs.empty())
1009     return;
1010 
1011   // First, ensure the relocations are sorted in offset order.  In general they
1012   // should already be sorted since `recordRelocation` is called in offset
1013   // order, but for the code section we combine many MC sections into single
1014   // wasm section, and this order is determined by the order of Asm.Symbols()
1015   // not the sections order.
1016   llvm::stable_sort(
1017       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
1018         return (A.Offset + A.FixupSection->getSectionOffset()) <
1019                (B.Offset + B.FixupSection->getSectionOffset());
1020       });
1021 
1022   SectionBookkeeping Section;
1023   startCustomSection(Section, std::string("reloc.") + Name.str());
1024 
1025   encodeULEB128(SectionIndex, W->OS);
1026   encodeULEB128(Relocs.size(), W->OS);
1027   for (const WasmRelocationEntry &RelEntry : Relocs) {
1028     uint64_t Offset =
1029         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
1030     uint32_t Index = getRelocationIndexValue(RelEntry);
1031 
1032     W->OS << char(RelEntry.Type);
1033     encodeULEB128(Offset, W->OS);
1034     encodeULEB128(Index, W->OS);
1035     if (RelEntry.hasAddend())
1036       encodeSLEB128(RelEntry.Addend, W->OS);
1037   }
1038 
1039   endSection(Section);
1040 }
1041 
1042 void WasmObjectWriter::writeCustomRelocSections() {
1043   for (const auto &Sec : CustomSections) {
1044     auto &Relocations = CustomSectionsRelocations[Sec.Section];
1045     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
1046   }
1047 }
1048 
1049 void WasmObjectWriter::writeLinkingMetaDataSection(
1050     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1051     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1052     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
1053   SectionBookkeeping Section;
1054   startCustomSection(Section, "linking");
1055   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
1056 
1057   SectionBookkeeping SubSection;
1058   if (SymbolInfos.size() != 0) {
1059     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
1060     encodeULEB128(SymbolInfos.size(), W->OS);
1061     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
1062       encodeULEB128(Sym.Kind, W->OS);
1063       encodeULEB128(Sym.Flags, W->OS);
1064       switch (Sym.Kind) {
1065       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1066       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1067       case wasm::WASM_SYMBOL_TYPE_EVENT:
1068       case wasm::WASM_SYMBOL_TYPE_TABLE:
1069         encodeULEB128(Sym.ElementIndex, W->OS);
1070         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
1071             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
1072           writeString(Sym.Name);
1073         break;
1074       case wasm::WASM_SYMBOL_TYPE_DATA:
1075         writeString(Sym.Name);
1076         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
1077           encodeULEB128(Sym.DataRef.Segment, W->OS);
1078           encodeULEB128(Sym.DataRef.Offset, W->OS);
1079           encodeULEB128(Sym.DataRef.Size, W->OS);
1080         }
1081         break;
1082       case wasm::WASM_SYMBOL_TYPE_SECTION: {
1083         const uint32_t SectionIndex =
1084             CustomSections[Sym.ElementIndex].OutputIndex;
1085         encodeULEB128(SectionIndex, W->OS);
1086         break;
1087       }
1088       default:
1089         llvm_unreachable("unexpected kind");
1090       }
1091     }
1092     endSection(SubSection);
1093   }
1094 
1095   if (DataSegments.size()) {
1096     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1097     encodeULEB128(DataSegments.size(), W->OS);
1098     for (const WasmDataSegment &Segment : DataSegments) {
1099       writeString(Segment.Name);
1100       encodeULEB128(Segment.Alignment, W->OS);
1101       encodeULEB128(Segment.LinkerFlags, W->OS);
1102     }
1103     endSection(SubSection);
1104   }
1105 
1106   if (!InitFuncs.empty()) {
1107     startSection(SubSection, wasm::WASM_INIT_FUNCS);
1108     encodeULEB128(InitFuncs.size(), W->OS);
1109     for (auto &StartFunc : InitFuncs) {
1110       encodeULEB128(StartFunc.first, W->OS);  // priority
1111       encodeULEB128(StartFunc.second, W->OS); // function index
1112     }
1113     endSection(SubSection);
1114   }
1115 
1116   if (Comdats.size()) {
1117     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1118     encodeULEB128(Comdats.size(), W->OS);
1119     for (const auto &C : Comdats) {
1120       writeString(C.first);
1121       encodeULEB128(0, W->OS); // flags for future use
1122       encodeULEB128(C.second.size(), W->OS);
1123       for (const WasmComdatEntry &Entry : C.second) {
1124         encodeULEB128(Entry.Kind, W->OS);
1125         encodeULEB128(Entry.Index, W->OS);
1126       }
1127     }
1128     endSection(SubSection);
1129   }
1130 
1131   endSection(Section);
1132 }
1133 
1134 void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1135                                           const MCAssembler &Asm,
1136                                           const MCAsmLayout &Layout) {
1137   SectionBookkeeping Section;
1138   auto *Sec = CustomSection.Section;
1139   startCustomSection(Section, CustomSection.Name);
1140 
1141   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
1142   Asm.writeSectionData(W->OS, Sec, Layout);
1143 
1144   CustomSection.OutputContentsOffset = Section.ContentsOffset;
1145   CustomSection.OutputIndex = Section.Index;
1146 
1147   endSection(Section);
1148 
1149   // Apply fixups.
1150   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1151   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
1152 }
1153 
1154 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
1155   assert(Symbol.isFunction());
1156   assert(TypeIndices.count(&Symbol));
1157   return TypeIndices[&Symbol];
1158 }
1159 
1160 uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1161   assert(Symbol.isEvent());
1162   assert(TypeIndices.count(&Symbol));
1163   return TypeIndices[&Symbol];
1164 }
1165 
1166 void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
1167   assert(Symbol.isFunction());
1168 
1169   wasm::WasmSignature S;
1170 
1171   if (auto *Sig = Symbol.getSignature()) {
1172     S.Returns = Sig->Returns;
1173     S.Params = Sig->Params;
1174   }
1175 
1176   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1177   if (Pair.second)
1178     Signatures.push_back(S);
1179   TypeIndices[&Symbol] = Pair.first->second;
1180 
1181   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1182                     << " new:" << Pair.second << "\n");
1183   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1184 }
1185 
1186 void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1187   assert(Symbol.isEvent());
1188 
1189   // TODO Currently we don't generate imported exceptions, but if we do, we
1190   // should have a way of infering types of imported exceptions.
1191   wasm::WasmSignature S;
1192   if (auto *Sig = Symbol.getSignature()) {
1193     S.Returns = Sig->Returns;
1194     S.Params = Sig->Params;
1195   }
1196 
1197   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1198   if (Pair.second)
1199     Signatures.push_back(S);
1200   TypeIndices[&Symbol] = Pair.first->second;
1201 
1202   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1203                     << "\n");
1204   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1205 }
1206 
1207 static bool isInSymtab(const MCSymbolWasm &Sym) {
1208   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
1209     return true;
1210 
1211   if (Sym.isComdat() && !Sym.isDefined())
1212     return false;
1213 
1214   if (Sym.isTemporary())
1215     return false;
1216 
1217   if (Sym.isSection())
1218     return false;
1219 
1220   return true;
1221 }
1222 
1223 void WasmObjectWriter::prepareImports(
1224     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
1225     const MCAsmLayout &Layout) {
1226   // For now, always emit the memory import, since loads and stores are not
1227   // valid without it. In the future, we could perhaps be more clever and omit
1228   // it if there are no loads or stores.
1229   wasm::WasmImport MemImport;
1230   MemImport.Module = "env";
1231   MemImport.Field = "__linear_memory";
1232   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1233   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1234                                      : wasm::WASM_LIMITS_FLAG_NONE;
1235   Imports.push_back(MemImport);
1236 
1237   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1238   // symbols.  This must be done before populating WasmIndices for defined
1239   // symbols.
1240   for (const MCSymbol &S : Asm.symbols()) {
1241     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1242 
1243     // Register types for all functions, including those with private linkage
1244     // (because wasm always needs a type signature).
1245     if (WS.isFunction()) {
1246       const auto *BS = Layout.getBaseSymbol(S);
1247       if (!BS)
1248         report_fatal_error(Twine(S.getName()) +
1249                            ": absolute addressing not supported!");
1250       registerFunctionType(*cast<MCSymbolWasm>(BS));
1251     }
1252 
1253     if (WS.isEvent())
1254       registerEventType(WS);
1255 
1256     if (WS.isTemporary())
1257       continue;
1258 
1259     // If the symbol is not defined in this translation unit, import it.
1260     if (!WS.isDefined() && !WS.isComdat()) {
1261       if (WS.isFunction()) {
1262         wasm::WasmImport Import;
1263         Import.Module = WS.getImportModule();
1264         Import.Field = WS.getImportName();
1265         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1266         Import.SigIndex = getFunctionType(WS);
1267         Imports.push_back(Import);
1268         assert(WasmIndices.count(&WS) == 0);
1269         WasmIndices[&WS] = NumFunctionImports++;
1270       } else if (WS.isGlobal()) {
1271         if (WS.isWeak())
1272           report_fatal_error("undefined global symbol cannot be weak");
1273 
1274         wasm::WasmImport Import;
1275         Import.Field = WS.getImportName();
1276         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1277         Import.Module = WS.getImportModule();
1278         Import.Global = WS.getGlobalType();
1279         Imports.push_back(Import);
1280         assert(WasmIndices.count(&WS) == 0);
1281         WasmIndices[&WS] = NumGlobalImports++;
1282       } else if (WS.isEvent()) {
1283         if (WS.isWeak())
1284           report_fatal_error("undefined event symbol cannot be weak");
1285 
1286         wasm::WasmImport Import;
1287         Import.Module = WS.getImportModule();
1288         Import.Field = WS.getImportName();
1289         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1290         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1291         Import.Event.SigIndex = getEventType(WS);
1292         Imports.push_back(Import);
1293         assert(WasmIndices.count(&WS) == 0);
1294         WasmIndices[&WS] = NumEventImports++;
1295       } else if (WS.isTable()) {
1296         if (WS.isWeak())
1297           report_fatal_error("undefined table symbol cannot be weak");
1298 
1299         wasm::WasmImport Import;
1300         Import.Module = WS.getImportModule();
1301         Import.Field = WS.getImportName();
1302         Import.Kind = wasm::WASM_EXTERNAL_TABLE;
1303         wasm::ValType ElemType = WS.getTableType();
1304         Import.Table.ElemType = uint8_t(ElemType);
1305         // FIXME: Extend table type to include limits? For now we don't specify
1306         // a min or max which does not place any restrictions on the size of the
1307         // imported table.
1308         Import.Table.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1309         Imports.push_back(Import);
1310         assert(WasmIndices.count(&WS) == 0);
1311         WasmIndices[&WS] = NumTableImports++;
1312       }
1313     }
1314   }
1315 
1316   // Add imports for GOT globals
1317   for (const MCSymbol &S : Asm.symbols()) {
1318     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1319     if (WS.isUsedInGOT()) {
1320       wasm::WasmImport Import;
1321       if (WS.isFunction())
1322         Import.Module = "GOT.func";
1323       else
1324         Import.Module = "GOT.mem";
1325       Import.Field = WS.getName();
1326       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1327       Import.Global = {wasm::WASM_TYPE_I32, true};
1328       Imports.push_back(Import);
1329       assert(GOTIndices.count(&WS) == 0);
1330       GOTIndices[&WS] = NumGlobalImports++;
1331     }
1332   }
1333 }
1334 
1335 uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1336                                        const MCAsmLayout &Layout) {
1337   support::endian::Writer MainWriter(*OS, support::little);
1338   W = &MainWriter;
1339   if (IsSplitDwarf) {
1340     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
1341     assert(DwoOS);
1342     support::endian::Writer DwoWriter(*DwoOS, support::little);
1343     W = &DwoWriter;
1344     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
1345   } else {
1346     return writeOneObject(Asm, Layout, DwoMode::AllSections);
1347   }
1348 }
1349 
1350 uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
1351                                           const MCAsmLayout &Layout,
1352                                           DwoMode Mode) {
1353   uint64_t StartOffset = W->OS.tell();
1354   SectionCount = 0;
1355   CustomSections.clear();
1356 
1357   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1358 
1359   // Collect information from the available symbols.
1360   SmallVector<WasmFunction, 4> Functions;
1361   SmallVector<uint32_t, 4> TableElems;
1362   SmallVector<wasm::WasmImport, 4> Imports;
1363   SmallVector<wasm::WasmExport, 4> Exports;
1364   SmallVector<wasm::WasmEventType, 1> Events;
1365   SmallVector<wasm::WasmGlobal, 1> Globals;
1366   SmallVector<wasm::WasmTable, 1> Tables;
1367   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1368   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1369   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
1370   uint64_t DataSize = 0;
1371   if (Mode != DwoMode::DwoOnly) {
1372     prepareImports(Imports, Asm, Layout);
1373   }
1374 
1375   // Populate DataSegments and CustomSections, which must be done before
1376   // populating DataLocations.
1377   for (MCSection &Sec : Asm) {
1378     auto &Section = static_cast<MCSectionWasm &>(Sec);
1379     StringRef SectionName = Section.getName();
1380 
1381     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
1382       continue;
1383     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
1384       continue;
1385 
1386     LLVM_DEBUG(dbgs() << "Processing Section " << SectionName << "  group "
1387                       << Section.getGroup() << "\n";);
1388 
1389     // .init_array sections are handled specially elsewhere.
1390     if (SectionName.startswith(".init_array"))
1391       continue;
1392 
1393     // Code is handled separately
1394     if (Section.getKind().isText())
1395       continue;
1396 
1397     if (Section.isWasmData()) {
1398       uint32_t SegmentIndex = DataSegments.size();
1399       DataSize = alignTo(DataSize, Section.getAlignment());
1400       DataSegments.emplace_back();
1401       WasmDataSegment &Segment = DataSegments.back();
1402       Segment.Name = SectionName;
1403       Segment.InitFlags = Section.getPassive()
1404                               ? (uint32_t)wasm::WASM_DATA_SEGMENT_IS_PASSIVE
1405                               : 0;
1406       Segment.Offset = DataSize;
1407       Segment.Section = &Section;
1408       addData(Segment.Data, Section);
1409       Segment.Alignment = Log2_32(Section.getAlignment());
1410       Segment.LinkerFlags = 0;
1411       DataSize += Segment.Data.size();
1412       Section.setSegmentIndex(SegmentIndex);
1413 
1414       if (const MCSymbolWasm *C = Section.getGroup()) {
1415         Comdats[C->getName()].emplace_back(
1416             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1417       }
1418     } else {
1419       // Create custom sections
1420       assert(Sec.getKind().isMetadata());
1421 
1422       StringRef Name = SectionName;
1423 
1424       // For user-defined custom sections, strip the prefix
1425       if (Name.startswith(".custom_section."))
1426         Name = Name.substr(strlen(".custom_section."));
1427 
1428       MCSymbol *Begin = Sec.getBeginSymbol();
1429       if (Begin) {
1430         assert(WasmIndices.count(cast<MCSymbolWasm>(Begin)) == 0);
1431         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1432       }
1433 
1434       // Separate out the producers and target features sections
1435       if (Name == "producers") {
1436         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1437         continue;
1438       }
1439       if (Name == "target_features") {
1440         TargetFeaturesSection =
1441             std::make_unique<WasmCustomSection>(Name, &Section);
1442         continue;
1443       }
1444 
1445       // Custom sections can also belong to COMDAT groups. In this case the
1446       // decriptor's "index" field is the section index (in the final object
1447       // file), but that is not known until after layout, so it must be fixed up
1448       // later
1449       if (const MCSymbolWasm *C = Section.getGroup()) {
1450         Comdats[C->getName()].emplace_back(
1451             WasmComdatEntry{wasm::WASM_COMDAT_SECTION,
1452                             static_cast<uint32_t>(CustomSections.size())});
1453       }
1454 
1455       CustomSections.emplace_back(Name, &Section);
1456     }
1457   }
1458 
1459   if (Mode != DwoMode::DwoOnly) {
1460     // Populate WasmIndices and DataLocations for defined symbols.
1461     for (const MCSymbol &S : Asm.symbols()) {
1462       // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1463       // or used in relocations.
1464       if (S.isTemporary() && S.getName().empty())
1465         continue;
1466 
1467       const auto &WS = static_cast<const MCSymbolWasm &>(S);
1468       LLVM_DEBUG(
1469           dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1470                  << " isDefined=" << S.isDefined() << " isExternal="
1471                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1472                  << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1473                  << " isVariable=" << WS.isVariable() << "\n");
1474 
1475       if (WS.isVariable())
1476         continue;
1477       if (WS.isComdat() && !WS.isDefined())
1478         continue;
1479 
1480       if (WS.isFunction()) {
1481         unsigned Index;
1482         if (WS.isDefined()) {
1483           if (WS.getOffset() != 0)
1484             report_fatal_error(
1485                 "function sections must contain one function each");
1486 
1487           if (WS.getSize() == nullptr)
1488             report_fatal_error(
1489                 "function symbols must have a size set with .size");
1490 
1491           // A definition. Write out the function body.
1492           Index = NumFunctionImports + Functions.size();
1493           WasmFunction Func;
1494           Func.SigIndex = getFunctionType(WS);
1495           Func.Sym = &WS;
1496           assert(WasmIndices.count(&WS) == 0);
1497           WasmIndices[&WS] = Index;
1498           Functions.push_back(Func);
1499 
1500           auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1501           if (const MCSymbolWasm *C = Section.getGroup()) {
1502             Comdats[C->getName()].emplace_back(
1503                 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1504           }
1505 
1506           if (WS.hasExportName()) {
1507             wasm::WasmExport Export;
1508             Export.Name = WS.getExportName();
1509             Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1510             Export.Index = Index;
1511             Exports.push_back(Export);
1512           }
1513         } else {
1514           // An import; the index was assigned above.
1515           Index = WasmIndices.find(&WS)->second;
1516         }
1517 
1518         LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1519 
1520       } else if (WS.isData()) {
1521         if (!isInSymtab(WS))
1522           continue;
1523 
1524         if (!WS.isDefined()) {
1525           LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1526                             << "\n");
1527           continue;
1528         }
1529 
1530         if (!WS.getSize())
1531           report_fatal_error("data symbols must have a size set with .size: " +
1532                              WS.getName());
1533 
1534         int64_t Size = 0;
1535         if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1536           report_fatal_error(".size expression must be evaluatable");
1537 
1538         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1539         if (!DataSection.isWasmData())
1540           report_fatal_error("data symbols must live in a data section: " +
1541                              WS.getName());
1542 
1543         // For each data symbol, export it in the symtab as a reference to the
1544         // corresponding Wasm data segment.
1545         wasm::WasmDataReference Ref = wasm::WasmDataReference{
1546             DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
1547             static_cast<uint64_t>(Size)};
1548         assert(DataLocations.count(&WS) == 0);
1549         DataLocations[&WS] = Ref;
1550         LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1551 
1552       } else if (WS.isGlobal()) {
1553         // A "true" Wasm global (currently just __stack_pointer)
1554         if (WS.isDefined()) {
1555           wasm::WasmGlobal Global;
1556           Global.Type = WS.getGlobalType();
1557           Global.Index = NumGlobalImports + Globals.size();
1558           switch (Global.Type.Type) {
1559           case wasm::WASM_TYPE_I32:
1560             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
1561             break;
1562           case wasm::WASM_TYPE_I64:
1563             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
1564             break;
1565           case wasm::WASM_TYPE_F32:
1566             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
1567             break;
1568           case wasm::WASM_TYPE_F64:
1569             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
1570             break;
1571           case wasm::WASM_TYPE_EXTERNREF:
1572             Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
1573             break;
1574           default:
1575             llvm_unreachable("unexpected type");
1576           }
1577           assert(WasmIndices.count(&WS) == 0);
1578           WasmIndices[&WS] = Global.Index;
1579           Globals.push_back(Global);
1580         } else {
1581           // An import; the index was assigned above
1582           LLVM_DEBUG(dbgs() << "  -> global index: "
1583                             << WasmIndices.find(&WS)->second << "\n");
1584         }
1585       } else if (WS.isTable()) {
1586         if (WS.isDefined()) {
1587           wasm::WasmTable Table;
1588           Table.Index = NumTableImports + Tables.size();
1589           Table.Type.ElemType = static_cast<uint8_t>(WS.getTableType());
1590           // FIXME: Work on custom limits is ongoing
1591           Table.Type.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1592           assert(WasmIndices.count(&WS) == 0);
1593           WasmIndices[&WS] = Table.Index;
1594           Tables.push_back(Table);
1595         }
1596         LLVM_DEBUG(dbgs() << " -> table index: "
1597                           << WasmIndices.find(&WS)->second << "\n");
1598       } else if (WS.isEvent()) {
1599         // C++ exception symbol (__cpp_exception)
1600         unsigned Index;
1601         if (WS.isDefined()) {
1602           Index = NumEventImports + Events.size();
1603           wasm::WasmEventType Event;
1604           Event.SigIndex = getEventType(WS);
1605           Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1606           assert(WasmIndices.count(&WS) == 0);
1607           WasmIndices[&WS] = Index;
1608           Events.push_back(Event);
1609         } else {
1610           // An import; the index was assigned above.
1611           assert(WasmIndices.count(&WS) > 0);
1612         }
1613         LLVM_DEBUG(dbgs() << "  -> event index: "
1614                           << WasmIndices.find(&WS)->second << "\n");
1615 
1616       } else {
1617         assert(WS.isSection());
1618       }
1619     }
1620 
1621     // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1622     // process these in a separate pass because we need to have processed the
1623     // target of the alias before the alias itself and the symbols are not
1624     // necessarily ordered in this way.
1625     for (const MCSymbol &S : Asm.symbols()) {
1626       if (!S.isVariable())
1627         continue;
1628 
1629       assert(S.isDefined());
1630 
1631       const auto *BS = Layout.getBaseSymbol(S);
1632       if (!BS)
1633         report_fatal_error(Twine(S.getName()) +
1634                            ": absolute addressing not supported!");
1635       const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
1636 
1637       // Find the target symbol of this weak alias and export that index
1638       const auto &WS = static_cast<const MCSymbolWasm &>(S);
1639       LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base
1640                         << "'\n");
1641 
1642       if (Base->isFunction()) {
1643         assert(WasmIndices.count(Base) > 0);
1644         uint32_t WasmIndex = WasmIndices.find(Base)->second;
1645         assert(WasmIndices.count(&WS) == 0);
1646         WasmIndices[&WS] = WasmIndex;
1647         LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1648       } else if (Base->isData()) {
1649         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1650         uint64_t Offset = Layout.getSymbolOffset(S);
1651         int64_t Size = 0;
1652         // For data symbol alias we use the size of the base symbol as the
1653         // size of the alias.  When an offset from the base is involved this
1654         // can result in a offset + size goes past the end of the data section
1655         // which out object format doesn't support.  So we must clamp it.
1656         if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
1657           report_fatal_error(".size expression must be evaluatable");
1658         const WasmDataSegment &Segment =
1659             DataSegments[DataSection.getSegmentIndex()];
1660         Size =
1661             std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
1662         wasm::WasmDataReference Ref = wasm::WasmDataReference{
1663             DataSection.getSegmentIndex(),
1664             static_cast<uint32_t>(Layout.getSymbolOffset(S)),
1665             static_cast<uint32_t>(Size)};
1666         DataLocations[&WS] = Ref;
1667         LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
1668       } else {
1669         report_fatal_error("don't yet support global/event aliases");
1670       }
1671     }
1672   }
1673 
1674   // Finally, populate the symbol table itself, in its "natural" order.
1675   for (const MCSymbol &S : Asm.symbols()) {
1676     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1677     if (!isInSymtab(WS)) {
1678       WS.setIndex(InvalidIndex);
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();
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