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