1 //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Wasm object file writer information.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/BinaryFormat/Wasm.h"
17 #include "llvm/MC/MCAsmBackend.h"
18 #include "llvm/MC/MCAsmLayout.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCFixupKindInfo.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCSectionWasm.h"
25 #include "llvm/MC/MCSymbolWasm.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/MC/MCWasmObjectWriter.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/LEB128.h"
32 #include "llvm/Support/StringSaver.h"
33 #include <vector>
34 
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "mc"
38 
39 namespace {
40 
41 // Went we ceate the indirect function table we start at 1, so that there is
42 // and emtpy slot at 0 and therefore calling a null function pointer will trap.
43 static const uint32_t kInitialTableOffset = 1;
44 
45 // For patching purposes, we need to remember where each section starts, both
46 // for patching up the section size field, and for patching up references to
47 // locations within the section.
48 struct SectionBookkeeping {
49   // Where the size of the section is written.
50   uint64_t SizeOffset;
51   // Where the contents of the section starts (after the header).
52   uint64_t ContentsOffset;
53 };
54 
55 // The signature of a wasm function, in a struct capable of being used as a
56 // DenseMap key.
57 struct WasmFunctionType {
58   // Support empty and tombstone instances, needed by DenseMap.
59   enum { Plain, Empty, Tombstone } State;
60 
61   // The return types of the function.
62   SmallVector<wasm::ValType, 1> Returns;
63 
64   // The parameter types of the function.
65   SmallVector<wasm::ValType, 4> Params;
66 
67   WasmFunctionType() : State(Plain) {}
68 
69   bool operator==(const WasmFunctionType &Other) const {
70     return State == Other.State && Returns == Other.Returns &&
71            Params == Other.Params;
72   }
73 };
74 
75 // Traits for using WasmFunctionType in a DenseMap.
76 struct WasmFunctionTypeDenseMapInfo {
77   static WasmFunctionType getEmptyKey() {
78     WasmFunctionType FuncTy;
79     FuncTy.State = WasmFunctionType::Empty;
80     return FuncTy;
81   }
82   static WasmFunctionType getTombstoneKey() {
83     WasmFunctionType FuncTy;
84     FuncTy.State = WasmFunctionType::Tombstone;
85     return FuncTy;
86   }
87   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
88     uintptr_t Value = FuncTy.State;
89     for (wasm::ValType Ret : FuncTy.Returns)
90       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
91     for (wasm::ValType Param : FuncTy.Params)
92       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
93     return Value;
94   }
95   static bool isEqual(const WasmFunctionType &LHS,
96                       const WasmFunctionType &RHS) {
97     return LHS == RHS;
98   }
99 };
100 
101 // A wasm data segment.  A wasm binary contains only a single data section
102 // but that can contain many segments, each with their own virtual location
103 // in memory.  Each MCSection data created by llvm is modeled as its own
104 // wasm data segment.
105 struct WasmDataSegment {
106   MCSectionWasm *Section;
107   StringRef Name;
108   uint32_t Offset;
109   uint32_t Alignment;
110   uint32_t Flags;
111   SmallVector<char, 4> Data;
112 };
113 
114 // A wasm import to be written into the import section.
115 struct WasmImport {
116   StringRef ModuleName;
117   StringRef FieldName;
118   unsigned Kind;
119   int32_t Type;
120   bool IsMutable;
121 };
122 
123 // A wasm function to be written into the function section.
124 struct WasmFunction {
125   int32_t Type;
126   const MCSymbolWasm *Sym;
127 };
128 
129 // A wasm export to be written into the export section.
130 struct WasmExport {
131   StringRef FieldName;
132   unsigned Kind;
133   uint32_t Index;
134 };
135 
136 // A wasm global to be written into the global section.
137 struct WasmGlobal {
138   wasm::ValType Type;
139   bool IsMutable;
140   bool HasImport;
141   uint64_t InitialValue;
142   uint32_t ImportIndex;
143 };
144 
145 // Information about a single item which is part of a COMDAT.  For each data
146 // segment or function which is in the COMDAT, there is a corresponding
147 // WasmComdatEntry.
148 struct WasmComdatEntry {
149   unsigned Kind;
150   uint32_t Index;
151 };
152 
153 // Information about a single relocation.
154 struct WasmRelocationEntry {
155   uint64_t Offset;                  // Where is the relocation.
156   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
157   int64_t Addend;                   // A value to add to the symbol.
158   unsigned Type;                    // The type of the relocation.
159   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
160 
161   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
162                       int64_t Addend, unsigned Type,
163                       const MCSectionWasm *FixupSection)
164       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
165         FixupSection(FixupSection) {}
166 
167   bool hasAddend() const {
168     switch (Type) {
169     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
170     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
171     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
172       return true;
173     default:
174       return false;
175     }
176   }
177 
178   void print(raw_ostream &Out) const {
179     Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
180         << ", Type=" << Type
181         << ", FixupSection=" << FixupSection->getSectionName();
182   }
183 
184 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
185   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
186 #endif
187 };
188 
189 #if !defined(NDEBUG)
190 raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
191   Rel.print(OS);
192   return OS;
193 }
194 #endif
195 
196 class WasmObjectWriter : public MCObjectWriter {
197   /// Helper struct for containing some precomputed information on symbols.
198   struct WasmSymbolData {
199     const MCSymbolWasm *Symbol;
200     StringRef Name;
201 
202     // Support lexicographic sorting.
203     bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
204   };
205 
206   /// The target specific Wasm writer instance.
207   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
208 
209   // Relocations for fixing up references in the code section.
210   std::vector<WasmRelocationEntry> CodeRelocations;
211 
212   // Relocations for fixing up references in the data section.
213   std::vector<WasmRelocationEntry> DataRelocations;
214 
215   // Index values to use for fixing up call_indirect type indices.
216   // Maps function symbols to the index of the type of the function
217   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
218   // Maps function symbols to the table element index space. Used
219   // for TABLE_INDEX relocation types (i.e. address taken functions).
220   DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
221   // Maps function/global symbols to the function/global index space.
222   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
223 
224   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
225       FunctionTypeIndices;
226   SmallVector<WasmFunctionType, 4> FunctionTypes;
227   SmallVector<WasmGlobal, 4> Globals;
228   unsigned NumFunctionImports = 0;
229   unsigned NumGlobalImports = 0;
230 
231   // TargetObjectWriter wrappers.
232   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
233   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
234     return TargetObjectWriter->getRelocType(Target, Fixup);
235   }
236 
237   void startSection(SectionBookkeeping &Section, unsigned SectionId,
238                     const char *Name = nullptr);
239   void endSection(SectionBookkeeping &Section);
240 
241 public:
242   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
243                    raw_pwrite_stream &OS)
244       : MCObjectWriter(OS, /*IsLittleEndian=*/true),
245         TargetObjectWriter(std::move(MOTW)) {}
246 
247   ~WasmObjectWriter() override;
248 
249 private:
250   void reset() override {
251     CodeRelocations.clear();
252     DataRelocations.clear();
253     TypeIndices.clear();
254     SymbolIndices.clear();
255     IndirectSymbolIndices.clear();
256     FunctionTypeIndices.clear();
257     FunctionTypes.clear();
258     Globals.clear();
259     MCObjectWriter::reset();
260     NumFunctionImports = 0;
261     NumGlobalImports = 0;
262   }
263 
264   void writeHeader(const MCAssembler &Asm);
265 
266   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
267                         const MCFragment *Fragment, const MCFixup &Fixup,
268                         MCValue Target, uint64_t &FixedValue) override;
269 
270   void executePostLayoutBinding(MCAssembler &Asm,
271                                 const MCAsmLayout &Layout) override;
272 
273   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
274 
275   void writeString(const StringRef Str) {
276     encodeULEB128(Str.size(), getStream());
277     writeBytes(Str);
278   }
279 
280   void writeValueType(wasm::ValType Ty) {
281     encodeSLEB128(int32_t(Ty), getStream());
282   }
283 
284   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
285   void writeImportSection(ArrayRef<WasmImport> Imports, uint32_t DataSize,
286                           uint32_t NumElements);
287   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
288   void writeGlobalSection();
289   void writeExportSection(ArrayRef<WasmExport> Exports);
290   void writeElemSection(ArrayRef<uint32_t> TableElems);
291   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
292                         ArrayRef<WasmFunction> Functions);
293   void writeDataSection(ArrayRef<WasmDataSegment> Segments);
294   void writeCodeRelocSection();
295   void writeDataRelocSection();
296   void writeLinkingMetaDataSection(
297       ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
298       ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
299       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
300       const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats);
301 
302   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
303   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
304                         uint64_t ContentsOffset);
305 
306   void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
307   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
308   uint32_t getFunctionType(const MCSymbolWasm& Symbol);
309   uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
310 };
311 
312 } // end anonymous namespace
313 
314 WasmObjectWriter::~WasmObjectWriter() {}
315 
316 // Write out a section header and a patchable section size field.
317 void WasmObjectWriter::startSection(SectionBookkeeping &Section,
318                                     unsigned SectionId,
319                                     const char *Name) {
320   assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
321          "Only custom sections can have names");
322 
323   DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
324   encodeULEB128(SectionId, getStream());
325 
326   Section.SizeOffset = getStream().tell();
327 
328   // The section size. We don't know the size yet, so reserve enough space
329   // for any 32-bit value; we'll patch it later.
330   encodeULEB128(UINT32_MAX, getStream());
331 
332   // The position where the section starts, for measuring its size.
333   Section.ContentsOffset = getStream().tell();
334 
335   // Custom sections in wasm also have a string identifier.
336   if (SectionId == wasm::WASM_SEC_CUSTOM) {
337     assert(Name);
338     writeString(StringRef(Name));
339   }
340 }
341 
342 // Now that the section is complete and we know how big it is, patch up the
343 // section size field at the start of the section.
344 void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
345   uint64_t Size = getStream().tell() - Section.ContentsOffset;
346   if (uint32_t(Size) != Size)
347     report_fatal_error("section size does not fit in a uint32_t");
348 
349   DEBUG(dbgs() << "endSection size=" << Size << "\n");
350 
351   // Write the final section size to the payload_len field, which follows
352   // the section id byte.
353   uint8_t Buffer[16];
354   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
355   assert(SizeLen == 5);
356   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
357 }
358 
359 // Emit the Wasm header.
360 void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
361   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
362   writeLE32(wasm::WasmVersion);
363 }
364 
365 void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
366                                                 const MCAsmLayout &Layout) {
367 }
368 
369 void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
370                                         const MCAsmLayout &Layout,
371                                         const MCFragment *Fragment,
372                                         const MCFixup &Fixup, MCValue Target,
373                                         uint64_t &FixedValue) {
374   MCAsmBackend &Backend = Asm.getBackend();
375   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
376                  MCFixupKindInfo::FKF_IsPCRel;
377   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
378   uint64_t C = Target.getConstant();
379   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
380   MCContext &Ctx = Asm.getContext();
381 
382   // The .init_array isn't translated as data, so don't do relocations in it.
383   if (FixupSection.getSectionName().startswith(".init_array"))
384     return;
385 
386   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
387     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
388            "Should not have constructed this");
389 
390     // Let A, B and C being the components of Target and R be the location of
391     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
392     // If it is pcrel, we want to compute (A - B + C - R).
393 
394     // In general, Wasm has no relocations for -B. It can only represent (A + C)
395     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
396     // replace B to implement it: (A - R - K + C)
397     if (IsPCRel) {
398       Ctx.reportError(
399           Fixup.getLoc(),
400           "No relocation available to represent this relative expression");
401       return;
402     }
403 
404     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
405 
406     if (SymB.isUndefined()) {
407       Ctx.reportError(Fixup.getLoc(),
408                       Twine("symbol '") + SymB.getName() +
409                           "' can not be undefined in a subtraction expression");
410       return;
411     }
412 
413     assert(!SymB.isAbsolute() && "Should have been folded");
414     const MCSection &SecB = SymB.getSection();
415     if (&SecB != &FixupSection) {
416       Ctx.reportError(Fixup.getLoc(),
417                       "Cannot represent a difference across sections");
418       return;
419     }
420 
421     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
422     uint64_t K = SymBOffset - FixupOffset;
423     IsPCRel = true;
424     C -= K;
425   }
426 
427   // We either rejected the fixup or folded B into C at this point.
428   const MCSymbolRefExpr *RefA = Target.getSymA();
429   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
430 
431   if (SymA && SymA->isVariable()) {
432     const MCExpr *Expr = SymA->getVariableValue();
433     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
434     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
435       llvm_unreachable("weakref used in reloc not yet implemented");
436   }
437 
438   // Put any constant offset in an addend. Offsets can be negative, and
439   // LLVM expects wrapping, in contrast to wasm's immediates which can't
440   // be negative and don't wrap.
441   FixedValue = 0;
442 
443   if (SymA)
444     SymA->setUsedInReloc();
445 
446   assert(!IsPCRel);
447   assert(SymA);
448 
449   unsigned Type = getRelocType(Target, Fixup);
450 
451   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
452   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
453 
454   if (FixupSection.isWasmData())
455     DataRelocations.push_back(Rec);
456   else if (FixupSection.getKind().isText())
457     CodeRelocations.push_back(Rec);
458   else if (!FixupSection.getKind().isMetadata())
459     // TODO(sbc): Add support for debug sections.
460     llvm_unreachable("unexpected section type");
461 }
462 
463 // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
464 // to allow patching.
465 static void
466 WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
467   uint8_t Buffer[5];
468   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
469   assert(SizeLen == 5);
470   Stream.pwrite((char *)Buffer, SizeLen, Offset);
471 }
472 
473 // Write X as an signed LEB value at offset Offset in Stream, padded
474 // to allow patching.
475 static void
476 WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
477   uint8_t Buffer[5];
478   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
479   assert(SizeLen == 5);
480   Stream.pwrite((char *)Buffer, SizeLen, Offset);
481 }
482 
483 // Write X as a plain integer value at offset Offset in Stream.
484 static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
485   uint8_t Buffer[4];
486   support::endian::write32le(Buffer, X);
487   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
488 }
489 
490 static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
491   if (Symbol.isVariable()) {
492     const MCExpr *Expr = Symbol.getVariableValue();
493     auto *Inner = cast<MCSymbolRefExpr>(Expr);
494     return cast<MCSymbolWasm>(&Inner->getSymbol());
495   }
496   return &Symbol;
497 }
498 
499 // Compute a value to write into the code at the location covered
500 // by RelEntry. This value isn't used by the static linker; it just serves
501 // to make the object format more readable and more likely to be directly
502 // useable.
503 uint32_t
504 WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
505 
506   switch (RelEntry.Type) {
507   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
508   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
509     // Provitional value is the indirect symbol index
510     if (!IndirectSymbolIndices.count(RelEntry.Symbol))
511       report_fatal_error("symbol not found in table index space: " +
512                          RelEntry.Symbol->getName());
513     return IndirectSymbolIndices[RelEntry.Symbol];
514   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
515   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
516   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
517     // Provitional value is function/type/global index itself
518     return getRelocationIndexValue(RelEntry);
519   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
520   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
521   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
522     // Provitional value is address of the global
523     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
524     // For undefined symbols, use zero
525     if (!Sym->isDefined())
526       return 0;
527 
528     uint32_t GlobalIndex = SymbolIndices[Sym];
529     const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
530     uint64_t Address = Global.InitialValue + RelEntry.Addend;
531 
532     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
533     return Address;
534   }
535   default:
536     llvm_unreachable("invalid relocation type");
537   }
538 }
539 
540 static void addData(SmallVectorImpl<char> &DataBytes,
541                     MCSectionWasm &DataSection) {
542   DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
543 
544   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
545 
546   size_t LastFragmentSize = 0;
547   for (const MCFragment &Frag : DataSection) {
548     if (Frag.hasInstructions())
549       report_fatal_error("only data supported in data sections");
550 
551     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
552       if (Align->getValueSize() != 1)
553         report_fatal_error("only byte values supported for alignment");
554       // If nops are requested, use zeros, as this is the data section.
555       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
556       uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
557                                                  Align->getAlignment()),
558                                          DataBytes.size() +
559                                              Align->getMaxBytesToEmit());
560       DataBytes.resize(Size, Value);
561     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
562       int64_t Size;
563       if (!Fill->getSize().evaluateAsAbsolute(Size))
564         llvm_unreachable("The fill should be an assembler constant");
565       DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
566     } else {
567       const auto &DataFrag = cast<MCDataFragment>(Frag);
568       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
569 
570       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
571       LastFragmentSize = Contents.size();
572     }
573   }
574 
575   // Don't allow empty segments, or segments that end with zero-sized
576   // fragment, otherwise the linker cannot map symbols to a unique
577   // data segment.  This can be triggered by zero-sized structs
578   // See: test/MC/WebAssembly/bss.ll
579   if (LastFragmentSize == 0)
580     DataBytes.resize(DataBytes.size() + 1);
581   DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
582 }
583 
584 uint32_t
585 WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
586   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
587     if (!TypeIndices.count(RelEntry.Symbol))
588       report_fatal_error("symbol not found in type index space: " +
589                          RelEntry.Symbol->getName());
590     return TypeIndices[RelEntry.Symbol];
591   }
592 
593   if (!SymbolIndices.count(RelEntry.Symbol))
594     report_fatal_error("symbol not found in function/global index space: " +
595                        RelEntry.Symbol->getName());
596   return SymbolIndices[RelEntry.Symbol];
597 }
598 
599 // Apply the portions of the relocation records that we can handle ourselves
600 // directly.
601 void WasmObjectWriter::applyRelocations(
602     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
603   raw_pwrite_stream &Stream = getStream();
604   for (const WasmRelocationEntry &RelEntry : Relocations) {
605     uint64_t Offset = ContentsOffset +
606                       RelEntry.FixupSection->getSectionOffset() +
607                       RelEntry.Offset;
608 
609     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
610     uint32_t Value = getProvisionalValue(RelEntry);
611 
612     switch (RelEntry.Type) {
613     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
614     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
615     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
616     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
617       WritePatchableLEB(Stream, Value, Offset);
618       break;
619     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
620     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
621       WriteI32(Stream, Value, Offset);
622       break;
623     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
624     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
625       WritePatchableSLEB(Stream, Value, Offset);
626       break;
627     default:
628       llvm_unreachable("invalid relocation type");
629     }
630   }
631 }
632 
633 // Write out the portions of the relocation records that the linker will
634 // need to handle.
635 void WasmObjectWriter::writeRelocations(
636     ArrayRef<WasmRelocationEntry> Relocations) {
637   raw_pwrite_stream &Stream = getStream();
638   for (const WasmRelocationEntry& RelEntry : Relocations) {
639 
640     uint64_t Offset = RelEntry.Offset +
641                       RelEntry.FixupSection->getSectionOffset();
642     uint32_t Index = getRelocationIndexValue(RelEntry);
643 
644     encodeULEB128(RelEntry.Type, Stream);
645     encodeULEB128(Offset, Stream);
646     encodeULEB128(Index, Stream);
647     if (RelEntry.hasAddend())
648       encodeSLEB128(RelEntry.Addend, Stream);
649   }
650 }
651 
652 void WasmObjectWriter::writeTypeSection(
653     ArrayRef<WasmFunctionType> FunctionTypes) {
654   if (FunctionTypes.empty())
655     return;
656 
657   SectionBookkeeping Section;
658   startSection(Section, wasm::WASM_SEC_TYPE);
659 
660   encodeULEB128(FunctionTypes.size(), getStream());
661 
662   for (const WasmFunctionType &FuncTy : FunctionTypes) {
663     encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
664     encodeULEB128(FuncTy.Params.size(), getStream());
665     for (wasm::ValType Ty : FuncTy.Params)
666       writeValueType(Ty);
667     encodeULEB128(FuncTy.Returns.size(), getStream());
668     for (wasm::ValType Ty : FuncTy.Returns)
669       writeValueType(Ty);
670   }
671 
672   endSection(Section);
673 }
674 
675 void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports,
676                                           uint32_t DataSize,
677                                           uint32_t NumElements) {
678   if (Imports.empty())
679     return;
680 
681   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
682 
683   SectionBookkeeping Section;
684   startSection(Section, wasm::WASM_SEC_IMPORT);
685 
686   encodeULEB128(Imports.size(), getStream());
687   for (const WasmImport &Import : Imports) {
688     writeString(Import.ModuleName);
689     writeString(Import.FieldName);
690 
691     encodeULEB128(Import.Kind, getStream());
692 
693     switch (Import.Kind) {
694     case wasm::WASM_EXTERNAL_FUNCTION:
695       encodeULEB128(Import.Type, getStream());
696       break;
697     case wasm::WASM_EXTERNAL_GLOBAL:
698       encodeSLEB128(int32_t(Import.Type), getStream());
699       encodeULEB128(int32_t(Import.IsMutable), getStream());
700       break;
701     case wasm::WASM_EXTERNAL_MEMORY:
702       encodeULEB128(0, getStream()); // flags
703       encodeULEB128(NumPages, getStream()); // initial
704       break;
705     case wasm::WASM_EXTERNAL_TABLE:
706       encodeSLEB128(int32_t(Import.Type), getStream());
707       encodeULEB128(0, getStream()); // flags
708       encodeULEB128(NumElements, getStream()); // initial
709       break;
710     default:
711       llvm_unreachable("unsupported import kind");
712     }
713   }
714 
715   endSection(Section);
716 }
717 
718 void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
719   if (Functions.empty())
720     return;
721 
722   SectionBookkeeping Section;
723   startSection(Section, wasm::WASM_SEC_FUNCTION);
724 
725   encodeULEB128(Functions.size(), getStream());
726   for (const WasmFunction &Func : Functions)
727     encodeULEB128(Func.Type, getStream());
728 
729   endSection(Section);
730 }
731 
732 void WasmObjectWriter::writeGlobalSection() {
733   if (Globals.empty())
734     return;
735 
736   SectionBookkeeping Section;
737   startSection(Section, wasm::WASM_SEC_GLOBAL);
738 
739   encodeULEB128(Globals.size(), getStream());
740   for (const WasmGlobal &Global : Globals) {
741     writeValueType(Global.Type);
742     write8(Global.IsMutable);
743 
744     if (Global.HasImport) {
745       assert(Global.InitialValue == 0);
746       write8(wasm::WASM_OPCODE_GET_GLOBAL);
747       encodeULEB128(Global.ImportIndex, getStream());
748     } else {
749       assert(Global.ImportIndex == 0);
750       write8(wasm::WASM_OPCODE_I32_CONST);
751       encodeSLEB128(Global.InitialValue, getStream()); // offset
752     }
753     write8(wasm::WASM_OPCODE_END);
754   }
755 
756   endSection(Section);
757 }
758 
759 void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
760   if (Exports.empty())
761     return;
762 
763   SectionBookkeeping Section;
764   startSection(Section, wasm::WASM_SEC_EXPORT);
765 
766   encodeULEB128(Exports.size(), getStream());
767   for (const WasmExport &Export : Exports) {
768     writeString(Export.FieldName);
769     encodeSLEB128(Export.Kind, getStream());
770     encodeULEB128(Export.Index, getStream());
771   }
772 
773   endSection(Section);
774 }
775 
776 void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
777   if (TableElems.empty())
778     return;
779 
780   SectionBookkeeping Section;
781   startSection(Section, wasm::WASM_SEC_ELEM);
782 
783   encodeULEB128(1, getStream()); // number of "segments"
784   encodeULEB128(0, getStream()); // the table index
785 
786   // init expr for starting offset
787   write8(wasm::WASM_OPCODE_I32_CONST);
788   encodeSLEB128(kInitialTableOffset, getStream());
789   write8(wasm::WASM_OPCODE_END);
790 
791   encodeULEB128(TableElems.size(), getStream());
792   for (uint32_t Elem : TableElems)
793     encodeULEB128(Elem, getStream());
794 
795   endSection(Section);
796 }
797 
798 void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
799                                         const MCAsmLayout &Layout,
800                                         ArrayRef<WasmFunction> Functions) {
801   if (Functions.empty())
802     return;
803 
804   SectionBookkeeping Section;
805   startSection(Section, wasm::WASM_SEC_CODE);
806 
807   encodeULEB128(Functions.size(), getStream());
808 
809   for (const WasmFunction &Func : Functions) {
810     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
811 
812     int64_t Size = 0;
813     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
814       report_fatal_error(".size expression must be evaluatable");
815 
816     encodeULEB128(Size, getStream());
817     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
818     Asm.writeSectionData(&FuncSection, Layout);
819   }
820 
821   // Apply fixups.
822   applyRelocations(CodeRelocations, Section.ContentsOffset);
823 
824   endSection(Section);
825 }
826 
827 void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
828   if (Segments.empty())
829     return;
830 
831   SectionBookkeeping Section;
832   startSection(Section, wasm::WASM_SEC_DATA);
833 
834   encodeULEB128(Segments.size(), getStream()); // count
835 
836   for (const WasmDataSegment & Segment : Segments) {
837     encodeULEB128(0, getStream()); // memory index
838     write8(wasm::WASM_OPCODE_I32_CONST);
839     encodeSLEB128(Segment.Offset, getStream()); // offset
840     write8(wasm::WASM_OPCODE_END);
841     encodeULEB128(Segment.Data.size(), getStream()); // size
842     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
843     writeBytes(Segment.Data); // data
844   }
845 
846   // Apply fixups.
847   applyRelocations(DataRelocations, Section.ContentsOffset);
848 
849   endSection(Section);
850 }
851 
852 void WasmObjectWriter::writeCodeRelocSection() {
853   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
854   // for descriptions of the reloc sections.
855 
856   if (CodeRelocations.empty())
857     return;
858 
859   SectionBookkeeping Section;
860   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
861 
862   encodeULEB128(wasm::WASM_SEC_CODE, getStream());
863   encodeULEB128(CodeRelocations.size(), getStream());
864 
865   writeRelocations(CodeRelocations);
866 
867   endSection(Section);
868 }
869 
870 void WasmObjectWriter::writeDataRelocSection() {
871   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
872   // for descriptions of the reloc sections.
873 
874   if (DataRelocations.empty())
875     return;
876 
877   SectionBookkeeping Section;
878   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
879 
880   encodeULEB128(wasm::WASM_SEC_DATA, getStream());
881   encodeULEB128(DataRelocations.size(), getStream());
882 
883   writeRelocations(DataRelocations);
884 
885   endSection(Section);
886 }
887 
888 void WasmObjectWriter::writeLinkingMetaDataSection(
889     ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
890     ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
891     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
892     const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats) {
893   SectionBookkeeping Section;
894   startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
895   SectionBookkeeping SubSection;
896 
897   if (SymbolFlags.size() != 0) {
898     startSection(SubSection, wasm::WASM_SYMBOL_INFO);
899     encodeULEB128(SymbolFlags.size(), getStream());
900     for (auto Pair: SymbolFlags) {
901       writeString(Pair.first);
902       encodeULEB128(Pair.second, getStream());
903     }
904     endSection(SubSection);
905   }
906 
907   if (DataSize > 0) {
908     startSection(SubSection, wasm::WASM_DATA_SIZE);
909     encodeULEB128(DataSize, getStream());
910     endSection(SubSection);
911   }
912 
913   if (Segments.size()) {
914     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
915     encodeULEB128(Segments.size(), getStream());
916     for (const WasmDataSegment &Segment : Segments) {
917       writeString(Segment.Name);
918       encodeULEB128(Segment.Alignment, getStream());
919       encodeULEB128(Segment.Flags, getStream());
920     }
921     endSection(SubSection);
922   }
923 
924   if (!InitFuncs.empty()) {
925     startSection(SubSection, wasm::WASM_INIT_FUNCS);
926     encodeULEB128(InitFuncs.size(), getStream());
927     for (auto &StartFunc : InitFuncs) {
928       encodeULEB128(StartFunc.first, getStream()); // priority
929       encodeULEB128(StartFunc.second, getStream()); // function index
930     }
931     endSection(SubSection);
932   }
933 
934   if (Comdats.size()) {
935     startSection(SubSection, wasm::WASM_COMDAT_INFO);
936     encodeULEB128(Comdats.size(), getStream());
937     for (const auto &C : Comdats) {
938       writeString(C.first);
939       encodeULEB128(0, getStream()); // flags for future use
940       encodeULEB128(C.second.size(), getStream());
941       for (const WasmComdatEntry &Entry : C.second) {
942         encodeULEB128(Entry.Kind, getStream());
943         encodeULEB128(Entry.Index, getStream());
944       }
945     }
946     endSection(SubSection);
947   }
948 
949   endSection(Section);
950 }
951 
952 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
953   assert(Symbol.isFunction());
954   assert(TypeIndices.count(&Symbol));
955   return TypeIndices[&Symbol];
956 }
957 
958 uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
959   assert(Symbol.isFunction());
960 
961   WasmFunctionType F;
962   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
963   F.Returns = ResolvedSym->getReturns();
964   F.Params = ResolvedSym->getParams();
965 
966   auto Pair =
967       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
968   if (Pair.second)
969     FunctionTypes.push_back(F);
970   TypeIndices[&Symbol] = Pair.first->second;
971 
972   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
973   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
974   return Pair.first->second;
975 }
976 
977 void WasmObjectWriter::writeObject(MCAssembler &Asm,
978                                    const MCAsmLayout &Layout) {
979   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
980   MCContext &Ctx = Asm.getContext();
981   wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
982 
983   // Collect information from the available symbols.
984   SmallVector<WasmFunction, 4> Functions;
985   SmallVector<uint32_t, 4> TableElems;
986   SmallVector<WasmImport, 4> Imports;
987   SmallVector<WasmExport, 4> Exports;
988   SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags;
989   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
990   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
991   SmallVector<WasmDataSegment, 4> DataSegments;
992   uint32_t DataSize = 0;
993 
994   // In the special .global_variables section, we've encoded global
995   // variables used by the function. Translate them into the Globals
996   // list.
997   MCSectionWasm *GlobalVars =
998       Ctx.getWasmSection(".global_variables", SectionKind::getMetadata());
999   if (!GlobalVars->getFragmentList().empty()) {
1000     if (GlobalVars->getFragmentList().size() != 1)
1001       report_fatal_error("only one .global_variables fragment supported");
1002     const MCFragment &Frag = *GlobalVars->begin();
1003     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1004       report_fatal_error("only data supported in .global_variables");
1005     const auto &DataFrag = cast<MCDataFragment>(Frag);
1006     if (!DataFrag.getFixups().empty())
1007       report_fatal_error("fixups not supported in .global_variables");
1008     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1009     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1010                      *end = (const uint8_t *)Contents.data() + Contents.size();
1011          p != end; ) {
1012       WasmGlobal G;
1013       if (end - p < 3)
1014         report_fatal_error("truncated global variable encoding");
1015       G.Type = wasm::ValType(int8_t(*p++));
1016       G.IsMutable = bool(*p++);
1017       G.HasImport = bool(*p++);
1018       if (G.HasImport) {
1019         G.InitialValue = 0;
1020 
1021         WasmImport Import;
1022         Import.ModuleName = (const char *)p;
1023         const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1024         if (!nul)
1025           report_fatal_error("global module name must be nul-terminated");
1026         p = nul + 1;
1027         nul = (const uint8_t *)memchr(p, '\0', end - p);
1028         if (!nul)
1029           report_fatal_error("global base name must be nul-terminated");
1030         Import.FieldName = (const char *)p;
1031         p = nul + 1;
1032 
1033         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1034         Import.Type = int32_t(G.Type);
1035 
1036         G.ImportIndex = NumGlobalImports;
1037         ++NumGlobalImports;
1038 
1039         Imports.push_back(Import);
1040       } else {
1041         unsigned n;
1042         G.InitialValue = decodeSLEB128(p, &n);
1043         G.ImportIndex = 0;
1044         if ((ptrdiff_t)n > end - p)
1045           report_fatal_error("global initial value must be valid SLEB128");
1046         p += n;
1047       }
1048       Globals.push_back(G);
1049     }
1050   }
1051 
1052   // For now, always emit the memory import, since loads and stores are not
1053   // valid without it. In the future, we could perhaps be more clever and omit
1054   // it if there are no loads or stores.
1055   MCSymbolWasm *MemorySym =
1056       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
1057   WasmImport MemImport;
1058   MemImport.ModuleName = MemorySym->getModuleName();
1059   MemImport.FieldName = MemorySym->getName();
1060   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1061   Imports.push_back(MemImport);
1062 
1063   // For now, always emit the table section, since indirect calls are not
1064   // valid without it. In the future, we could perhaps be more clever and omit
1065   // it if there are no indirect calls.
1066   MCSymbolWasm *TableSym =
1067       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
1068   WasmImport TableImport;
1069   TableImport.ModuleName = TableSym->getModuleName();
1070   TableImport.FieldName = TableSym->getName();
1071   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1072   TableImport.Type = wasm::WASM_TYPE_ANYFUNC;
1073   Imports.push_back(TableImport);
1074 
1075   // Populate FunctionTypeIndices and Imports.
1076   for (const MCSymbol &S : Asm.symbols()) {
1077     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1078 
1079     // Register types for all functions, including those with private linkage
1080     // (because wasm always needs a type signature).
1081     if (WS.isFunction())
1082       registerFunctionType(WS);
1083 
1084     if (WS.isTemporary())
1085       continue;
1086 
1087     // If the symbol is not defined in this translation unit, import it.
1088     if ((!WS.isDefined() && !WS.isComdat()) ||
1089         WS.isVariable()) {
1090       WasmImport Import;
1091       Import.ModuleName = WS.getModuleName();
1092       Import.FieldName = WS.getName();
1093 
1094       if (WS.isFunction()) {
1095         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1096         Import.Type = getFunctionType(WS);
1097         SymbolIndices[&WS] = NumFunctionImports;
1098         ++NumFunctionImports;
1099       } else {
1100         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1101         Import.Type = int32_t(PtrType);
1102         Import.IsMutable = false;
1103         SymbolIndices[&WS] = NumGlobalImports;
1104 
1105         // If this global is the stack pointer, make it mutable.
1106         if (WS.getName() == "__stack_pointer")
1107           Import.IsMutable = true;
1108 
1109         ++NumGlobalImports;
1110       }
1111 
1112       Imports.push_back(Import);
1113     }
1114   }
1115 
1116   for (MCSection &Sec : Asm) {
1117     auto &Section = static_cast<MCSectionWasm &>(Sec);
1118     if (!Section.isWasmData())
1119       continue;
1120 
1121     // .init_array sections are handled specially elsewhere.
1122     if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1123       continue;
1124 
1125     DataSize = alignTo(DataSize, Section.getAlignment());
1126     DataSegments.emplace_back();
1127     WasmDataSegment &Segment = DataSegments.back();
1128     Segment.Name = Section.getSectionName();
1129     Segment.Offset = DataSize;
1130     Segment.Section = &Section;
1131     addData(Segment.Data, Section);
1132     Segment.Alignment = Section.getAlignment();
1133     Segment.Flags = 0;
1134     DataSize += Segment.Data.size();
1135     Section.setMemoryOffset(Segment.Offset);
1136 
1137     if (const MCSymbolWasm *C = Section.getGroup()) {
1138       Comdats[C->getName()].emplace_back(
1139           WasmComdatEntry{wasm::WASM_COMDAT_DATA,
1140                           static_cast<uint32_t>(DataSegments.size()) - 1});
1141     }
1142   }
1143 
1144   // Handle regular defined and undefined symbols.
1145   for (const MCSymbol &S : Asm.symbols()) {
1146     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1147     // or used in relocations.
1148     if (S.isTemporary() && S.getName().empty())
1149       continue;
1150 
1151     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1152     DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1153                  << " isDefined=" << S.isDefined() << " isExternal="
1154                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1155                  << " isFunction=" << WS.isFunction()
1156                  << " isWeak=" << WS.isWeak()
1157                  << " isHidden=" << WS.isHidden()
1158                  << " isVariable=" << WS.isVariable() << "\n");
1159 
1160     if (WS.isWeak() || WS.isHidden()) {
1161       uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) |
1162           (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
1163       SymbolFlags.emplace_back(WS.getName(), Flags);
1164     }
1165 
1166     if (WS.isVariable())
1167       continue;
1168 
1169     unsigned Index;
1170 
1171     if (WS.isFunction()) {
1172       if (WS.isDefined()) {
1173         if (WS.getOffset() != 0)
1174           report_fatal_error(
1175               "function sections must contain one function each");
1176 
1177         if (WS.getSize() == 0)
1178           report_fatal_error(
1179               "function symbols must have a size set with .size");
1180 
1181         // A definition. Take the next available index.
1182         Index = NumFunctionImports + Functions.size();
1183 
1184         // Prepare the function.
1185         WasmFunction Func;
1186         Func.Type = getFunctionType(WS);
1187         Func.Sym = &WS;
1188         SymbolIndices[&WS] = Index;
1189         Functions.push_back(Func);
1190       } else {
1191         // An import; the index was assigned above.
1192         Index = SymbolIndices.find(&WS)->second;
1193       }
1194 
1195       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1196    } else {
1197       if (WS.isTemporary() && !WS.getSize())
1198         continue;
1199 
1200       if (!WS.isDefined())
1201         continue;
1202 
1203       if (!WS.getSize())
1204         report_fatal_error("data symbols must have a size set with .size: " +
1205                            WS.getName());
1206 
1207       int64_t Size = 0;
1208       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1209         report_fatal_error(".size expression must be evaluatable");
1210 
1211       // For each global, prepare a corresponding wasm global holding its
1212       // address.  For externals these will also be named exports.
1213       Index = NumGlobalImports + Globals.size();
1214       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1215       assert(DataSection.isWasmData());
1216 
1217       WasmGlobal Global;
1218       Global.Type = PtrType;
1219       Global.IsMutable = false;
1220       Global.HasImport = false;
1221       Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
1222       Global.ImportIndex = 0;
1223       SymbolIndices[&WS] = Index;
1224       DEBUG(dbgs() << "  -> global index: " << Index << "\n");
1225       Globals.push_back(Global);
1226     }
1227 
1228     // If the symbol is visible outside this translation unit, export it.
1229     if (WS.isDefined()) {
1230       WasmExport Export;
1231       Export.FieldName = WS.getName();
1232       Export.Index = Index;
1233       if (WS.isFunction())
1234         Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1235       else
1236         Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1237       DEBUG(dbgs() << "  -> export " << Exports.size() << "\n");
1238       Exports.push_back(Export);
1239 
1240       if (!WS.isExternal())
1241         SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
1242 
1243       if (WS.isFunction()) {
1244         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1245         if (const MCSymbolWasm *C = Section.getGroup())
1246           Comdats[C->getName()].emplace_back(
1247               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1248       }
1249     }
1250   }
1251 
1252   // Handle weak aliases. We need to process these in a separate pass because
1253   // we need to have processed the target of the alias before the alias itself
1254   // and the symbols are not necessarily ordered in this way.
1255   for (const MCSymbol &S : Asm.symbols()) {
1256     if (!S.isVariable())
1257       continue;
1258 
1259     assert(S.isDefined());
1260 
1261     // Find the target symbol of this weak alias and export that index
1262     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1263     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
1264     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1265     assert(SymbolIndices.count(ResolvedSym) > 0);
1266     uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
1267     DEBUG(dbgs() << "  -> index:" << Index << "\n");
1268 
1269     WasmExport Export;
1270     Export.FieldName = WS.getName();
1271     Export.Index = Index;
1272     if (WS.isFunction())
1273       Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1274     else
1275       Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1276     DEBUG(dbgs() << "  -> export " << Exports.size() << "\n");
1277     Exports.push_back(Export);
1278 
1279     if (!WS.isExternal())
1280       SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
1281   }
1282 
1283   {
1284     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1285       // Functions referenced by a relocation need to prepared to be called
1286       // indirectly.
1287       const MCSymbolWasm& WS = *Rel.Symbol;
1288       if (WS.isFunction() && IndirectSymbolIndices.count(&WS) == 0) {
1289         switch (Rel.Type) {
1290         case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
1291         case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
1292         case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1293         case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
1294           uint32_t Index = SymbolIndices.find(&WS)->second;
1295           IndirectSymbolIndices[&WS] = TableElems.size() + kInitialTableOffset;
1296           DEBUG(dbgs() << "  -> adding to table: " << TableElems.size() << "\n");
1297           TableElems.push_back(Index);
1298           registerFunctionType(WS);
1299           break;
1300         }
1301         default:
1302           break;
1303         }
1304       }
1305     };
1306 
1307     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1308       HandleReloc(RelEntry);
1309     for (const WasmRelocationEntry &RelEntry : DataRelocations)
1310       HandleReloc(RelEntry);
1311   }
1312 
1313   // Translate .init_array section contents into start functions.
1314   for (const MCSection &S : Asm) {
1315     const auto &WS = static_cast<const MCSectionWasm &>(S);
1316     if (WS.getSectionName().startswith(".fini_array"))
1317       report_fatal_error(".fini_array sections are unsupported");
1318     if (!WS.getSectionName().startswith(".init_array"))
1319       continue;
1320     if (WS.getFragmentList().empty())
1321       continue;
1322     if (WS.getFragmentList().size() != 2)
1323       report_fatal_error("only one .init_array section fragment supported");
1324     const MCFragment &AlignFrag = *WS.begin();
1325     if (AlignFrag.getKind() != MCFragment::FT_Align)
1326       report_fatal_error(".init_array section should be aligned");
1327     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1328       report_fatal_error(".init_array section should be aligned for pointers");
1329     const MCFragment &Frag = *std::next(WS.begin());
1330     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1331       report_fatal_error("only data supported in .init_array section");
1332     uint16_t Priority = UINT16_MAX;
1333     if (WS.getSectionName().size() != 11) {
1334       if (WS.getSectionName()[11] != '.')
1335         report_fatal_error(".init_array section priority should start with '.'");
1336       if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1337         report_fatal_error("invalid .init_array section priority");
1338     }
1339     const auto &DataFrag = cast<MCDataFragment>(Frag);
1340     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1341     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1342                      *end = (const uint8_t *)Contents.data() + Contents.size();
1343          p != end; ++p) {
1344       if (*p != 0)
1345         report_fatal_error("non-symbolic data in .init_array section");
1346     }
1347     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1348       assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1349       const MCExpr *Expr = Fixup.getValue();
1350       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1351       if (!Sym)
1352         report_fatal_error("fixups in .init_array should be symbol references");
1353       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1354         report_fatal_error("symbols in .init_array should be for functions");
1355       auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1356       if (I == SymbolIndices.end())
1357         report_fatal_error("symbols in .init_array should be defined");
1358       uint32_t Index = I->second;
1359       InitFuncs.push_back(std::make_pair(Priority, Index));
1360     }
1361   }
1362 
1363   // Write out the Wasm header.
1364   writeHeader(Asm);
1365 
1366   writeTypeSection(FunctionTypes);
1367   writeImportSection(Imports, DataSize, TableElems.size());
1368   writeFunctionSection(Functions);
1369   // Skip the "table" section; we import the table instead.
1370   // Skip the "memory" section; we import the memory instead.
1371   writeGlobalSection();
1372   writeExportSection(Exports);
1373   writeElemSection(TableElems);
1374   writeCodeSection(Asm, Layout, Functions);
1375   writeDataSection(DataSegments);
1376   writeCodeRelocSection();
1377   writeDataRelocSection();
1378   writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags,
1379                               InitFuncs, Comdats);
1380 
1381   // TODO: Translate the .comment section to the output.
1382   // TODO: Translate debug sections to the output.
1383 }
1384 
1385 std::unique_ptr<MCObjectWriter>
1386 llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1387                              raw_pwrite_stream &OS) {
1388   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
1389 }
1390