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/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/ErrorHandling.h"
32 #include "llvm/Support/LEB128.h"
33 #include "llvm/Support/StringSaver.h"
34 #include <vector>
35 
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "mc"
39 
40 namespace {
41 
42 // Went we ceate the indirect function table we start at 1, so that there is
43 // and emtpy slot at 0 and therefore calling a null function pointer will trap.
44 static const uint32_t kInitialTableOffset = 1;
45 
46 // For patching purposes, we need to remember where each section starts, both
47 // for patching up the section size field, and for patching up references to
48 // locations within the section.
49 struct SectionBookkeeping {
50   // Where the size of the section is written.
51   uint64_t SizeOffset;
52   // Where the section header ends (without custom section name).
53   uint64_t PayloadOffset;
54   // Where the contents of the section starts.
55   uint64_t ContentsOffset;
56   uint32_t Index;
57 };
58 
59 // The signature of a wasm function or event, in a struct capable of being used
60 // as a DenseMap key.
61 // TODO: Consider using wasm::WasmSignature directly instead.
62 struct WasmSignature {
63   // Support empty and tombstone instances, needed by DenseMap.
64   enum { Plain, Empty, Tombstone } State;
65 
66   // The return types of the function.
67   SmallVector<wasm::ValType, 1> Returns;
68 
69   // The parameter types of the function.
70   SmallVector<wasm::ValType, 4> Params;
71 
WasmSignature__anona6c234df0111::WasmSignature72   WasmSignature() : State(Plain) {}
73 
operator ==__anona6c234df0111::WasmSignature74   bool operator==(const WasmSignature &Other) const {
75     return State == Other.State && Returns == Other.Returns &&
76            Params == Other.Params;
77   }
78 };
79 
80 // Traits for using WasmSignature in a DenseMap.
81 struct WasmSignatureDenseMapInfo {
getEmptyKey__anona6c234df0111::WasmSignatureDenseMapInfo82   static WasmSignature getEmptyKey() {
83     WasmSignature Sig;
84     Sig.State = WasmSignature::Empty;
85     return Sig;
86   }
getTombstoneKey__anona6c234df0111::WasmSignatureDenseMapInfo87   static WasmSignature getTombstoneKey() {
88     WasmSignature Sig;
89     Sig.State = WasmSignature::Tombstone;
90     return Sig;
91   }
getHashValue__anona6c234df0111::WasmSignatureDenseMapInfo92   static unsigned getHashValue(const WasmSignature &Sig) {
93     uintptr_t Value = Sig.State;
94     for (wasm::ValType Ret : Sig.Returns)
95       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
96     for (wasm::ValType Param : Sig.Params)
97       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
98     return Value;
99   }
isEqual__anona6c234df0111::WasmSignatureDenseMapInfo100   static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
101     return LHS == RHS;
102   }
103 };
104 
105 // A wasm data segment.  A wasm binary contains only a single data section
106 // but that can contain many segments, each with their own virtual location
107 // in memory.  Each MCSection data created by llvm is modeled as its own
108 // wasm data segment.
109 struct WasmDataSegment {
110   MCSectionWasm *Section;
111   StringRef Name;
112   uint32_t Offset;
113   uint32_t Alignment;
114   uint32_t Flags;
115   SmallVector<char, 4> Data;
116 };
117 
118 // A wasm function to be written into the function section.
119 struct WasmFunction {
120   uint32_t SigIndex;
121   const MCSymbolWasm *Sym;
122 };
123 
124 // A wasm global to be written into the global section.
125 struct WasmGlobal {
126   wasm::WasmGlobalType Type;
127   uint64_t InitialValue;
128 };
129 
130 // Information about a single item which is part of a COMDAT.  For each data
131 // segment or function which is in the COMDAT, there is a corresponding
132 // WasmComdatEntry.
133 struct WasmComdatEntry {
134   unsigned Kind;
135   uint32_t Index;
136 };
137 
138 // Information about a single relocation.
139 struct WasmRelocationEntry {
140   uint64_t Offset;                   // Where is the relocation.
141   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
142   int64_t Addend;                    // A value to add to the symbol.
143   unsigned Type;                     // The type of the relocation.
144   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
145 
WasmRelocationEntry__anona6c234df0111::WasmRelocationEntry146   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
147                       int64_t Addend, unsigned Type,
148                       const MCSectionWasm *FixupSection)
149       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
150         FixupSection(FixupSection) {}
151 
hasAddend__anona6c234df0111::WasmRelocationEntry152   bool hasAddend() const {
153     switch (Type) {
154     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
155     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
156     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
157     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
158     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
159       return true;
160     default:
161       return false;
162     }
163   }
164 
print__anona6c234df0111::WasmRelocationEntry165   void print(raw_ostream &Out) const {
166     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
167         << ", Sym=" << *Symbol << ", Addend=" << Addend
168         << ", FixupSection=" << FixupSection->getSectionName();
169   }
170 
171 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump__anona6c234df0111::WasmRelocationEntry172   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
173 #endif
174 };
175 
176 static const uint32_t INVALID_INDEX = -1;
177 
178 struct WasmCustomSection {
179 
180   StringRef Name;
181   MCSectionWasm *Section;
182 
183   uint32_t OutputContentsOffset;
184   uint32_t OutputIndex;
185 
WasmCustomSection__anona6c234df0111::WasmCustomSection186   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
187       : Name(Name), Section(Section), OutputContentsOffset(0),
188         OutputIndex(INVALID_INDEX) {}
189 };
190 
191 #if !defined(NDEBUG)
operator <<(raw_ostream & OS,const WasmRelocationEntry & Rel)192 raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
193   Rel.print(OS);
194   return OS;
195 }
196 #endif
197 
198 class WasmObjectWriter : public MCObjectWriter {
199   support::endian::Writer W;
200 
201   /// The target specific Wasm writer instance.
202   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
203 
204   // Relocations for fixing up references in the code section.
205   std::vector<WasmRelocationEntry> CodeRelocations;
206   uint32_t CodeSectionIndex;
207 
208   // Relocations for fixing up references in the data section.
209   std::vector<WasmRelocationEntry> DataRelocations;
210   uint32_t DataSectionIndex;
211 
212   // Index values to use for fixing up call_indirect type indices.
213   // Maps function symbols to the index of the type of the function
214   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
215   // Maps function symbols to the table element index space. Used
216   // for TABLE_INDEX relocation types (i.e. address taken functions).
217   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
218   // Maps function/global symbols to the function/global/event/section index
219   // space.
220   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
221   // Maps data symbols to the Wasm segment and offset/size with the segment.
222   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
223 
224   // Stores output data (index, relocations, content offset) for custom
225   // section.
226   std::vector<WasmCustomSection> CustomSections;
227   // Relocations for fixing up references in the custom sections.
228   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
229       CustomSectionsRelocations;
230 
231   // Map from section to defining function symbol.
232   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
233 
234   DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
235   SmallVector<WasmSignature, 4> Signatures;
236   SmallVector<WasmGlobal, 4> Globals;
237   SmallVector<WasmDataSegment, 4> DataSegments;
238   unsigned NumFunctionImports = 0;
239   unsigned NumGlobalImports = 0;
240   unsigned NumEventImports = 0;
241   uint32_t SectionCount = 0;
242 
243   // TargetObjectWriter wrappers.
is64Bit() const244   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
getRelocType(const MCValue & Target,const MCFixup & Fixup) const245   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
246     return TargetObjectWriter->getRelocType(Target, Fixup);
247   }
248 
249   void startSection(SectionBookkeeping &Section, unsigned SectionId);
250   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
251   void endSection(SectionBookkeeping &Section);
252 
253 public:
WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,raw_pwrite_stream & OS)254   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
255                    raw_pwrite_stream &OS)
256       : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
257 
258   ~WasmObjectWriter() override;
259 
260 private:
reset()261   void reset() override {
262     CodeRelocations.clear();
263     DataRelocations.clear();
264     TypeIndices.clear();
265     WasmIndices.clear();
266     TableIndices.clear();
267     DataLocations.clear();
268     CustomSectionsRelocations.clear();
269     SignatureIndices.clear();
270     Signatures.clear();
271     Globals.clear();
272     DataSegments.clear();
273     SectionFunctions.clear();
274     NumFunctionImports = 0;
275     NumGlobalImports = 0;
276     MCObjectWriter::reset();
277   }
278 
279   void writeHeader(const MCAssembler &Asm);
280 
281   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
282                         const MCFragment *Fragment, const MCFixup &Fixup,
283                         MCValue Target, uint64_t &FixedValue) override;
284 
285   void executePostLayoutBinding(MCAssembler &Asm,
286                                 const MCAsmLayout &Layout) override;
287 
288   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
289 
writeString(const StringRef Str)290   void writeString(const StringRef Str) {
291     encodeULEB128(Str.size(), W.OS);
292     W.OS << Str;
293   }
294 
writeValueType(wasm::ValType Ty)295   void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
296 
297   void writeTypeSection(ArrayRef<WasmSignature> Signatures);
298   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
299                           uint32_t NumElements);
300   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
301   void writeGlobalSection();
302   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
303   void writeElemSection(ArrayRef<uint32_t> TableElems);
304   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
305                         ArrayRef<WasmFunction> Functions);
306   void writeDataSection();
307   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
308   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
309                          std::vector<WasmRelocationEntry> &Relocations);
310   void writeLinkingMetaDataSection(
311       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
312       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
313       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
314   void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
315   void writeCustomRelocSections();
316   void
317   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
318                                  const MCAsmLayout &Layout);
319 
320   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
321   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
322                         uint64_t ContentsOffset);
323 
324   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
325   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
326   uint32_t getEventType(const MCSymbolWasm &Symbol);
327   void registerFunctionType(const MCSymbolWasm &Symbol);
328   void registerEventType(const MCSymbolWasm &Symbol);
329 };
330 
331 } // end anonymous namespace
332 
~WasmObjectWriter()333 WasmObjectWriter::~WasmObjectWriter() {}
334 
335 // Write out a section header and a patchable section size field.
startSection(SectionBookkeeping & Section,unsigned SectionId)336 void WasmObjectWriter::startSection(SectionBookkeeping &Section,
337                                     unsigned SectionId) {
338   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
339   W.OS << char(SectionId);
340 
341   Section.SizeOffset = W.OS.tell();
342 
343   // The section size. We don't know the size yet, so reserve enough space
344   // for any 32-bit value; we'll patch it later.
345   encodeULEB128(UINT32_MAX, W.OS);
346 
347   // The position where the section starts, for measuring its size.
348   Section.ContentsOffset = W.OS.tell();
349   Section.PayloadOffset = W.OS.tell();
350   Section.Index = SectionCount++;
351 }
352 
startCustomSection(SectionBookkeeping & Section,StringRef Name)353 void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
354                                           StringRef Name) {
355   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
356   startSection(Section, wasm::WASM_SEC_CUSTOM);
357 
358   // The position where the section header ends, for measuring its size.
359   Section.PayloadOffset = W.OS.tell();
360 
361   // Custom sections in wasm also have a string identifier.
362   writeString(Name);
363 
364   // The position where the custom section starts.
365   Section.ContentsOffset = W.OS.tell();
366 }
367 
368 // Now that the section is complete and we know how big it is, patch up the
369 // section size field at the start of the section.
endSection(SectionBookkeeping & Section)370 void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
371   uint64_t Size = W.OS.tell();
372   // /dev/null doesn't support seek/tell and can report offset of 0.
373   // Simply skip this patching in that case.
374   if (!Size)
375     return;
376 
377   Size -= Section.PayloadOffset;
378   if (uint32_t(Size) != Size)
379     report_fatal_error("section size does not fit in a uint32_t");
380 
381   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
382 
383   // Write the final section size to the payload_len field, which follows
384   // the section id byte.
385   uint8_t Buffer[16];
386   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
387   assert(SizeLen == 5);
388   static_cast<raw_pwrite_stream &>(W.OS).pwrite((char *)Buffer, SizeLen,
389                                                 Section.SizeOffset);
390 }
391 
392 // Emit the Wasm header.
writeHeader(const MCAssembler & Asm)393 void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
394   W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
395   W.write<uint32_t>(wasm::WasmVersion);
396 }
397 
executePostLayoutBinding(MCAssembler & Asm,const MCAsmLayout & Layout)398 void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
399                                                 const MCAsmLayout &Layout) {
400   // Build a map of sections to the function that defines them, for use
401   // in recordRelocation.
402   for (const MCSymbol &S : Asm.symbols()) {
403     const auto &WS = static_cast<const MCSymbolWasm &>(S);
404     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
405       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
406       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
407       if (!Pair.second)
408         report_fatal_error("section already has a defining function: " +
409                            Sec.getSectionName());
410     }
411   }
412 }
413 
recordRelocation(MCAssembler & Asm,const MCAsmLayout & Layout,const MCFragment * Fragment,const MCFixup & Fixup,MCValue Target,uint64_t & FixedValue)414 void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
415                                         const MCAsmLayout &Layout,
416                                         const MCFragment *Fragment,
417                                         const MCFixup &Fixup, MCValue Target,
418                                         uint64_t &FixedValue) {
419   MCAsmBackend &Backend = Asm.getBackend();
420   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
421                  MCFixupKindInfo::FKF_IsPCRel;
422   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
423   uint64_t C = Target.getConstant();
424   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
425   MCContext &Ctx = Asm.getContext();
426 
427   // The .init_array isn't translated as data, so don't do relocations in it.
428   if (FixupSection.getSectionName().startswith(".init_array"))
429     return;
430 
431   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
432     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
433            "Should not have constructed this");
434 
435     // Let A, B and C being the components of Target and R be the location of
436     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
437     // If it is pcrel, we want to compute (A - B + C - R).
438 
439     // In general, Wasm has no relocations for -B. It can only represent (A + C)
440     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
441     // replace B to implement it: (A - R - K + C)
442     if (IsPCRel) {
443       Ctx.reportError(
444           Fixup.getLoc(),
445           "No relocation available to represent this relative expression");
446       return;
447     }
448 
449     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
450 
451     if (SymB.isUndefined()) {
452       Ctx.reportError(Fixup.getLoc(),
453                       Twine("symbol '") + SymB.getName() +
454                           "' can not be undefined in a subtraction expression");
455       return;
456     }
457 
458     assert(!SymB.isAbsolute() && "Should have been folded");
459     const MCSection &SecB = SymB.getSection();
460     if (&SecB != &FixupSection) {
461       Ctx.reportError(Fixup.getLoc(),
462                       "Cannot represent a difference across sections");
463       return;
464     }
465 
466     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
467     uint64_t K = SymBOffset - FixupOffset;
468     IsPCRel = true;
469     C -= K;
470   }
471 
472   // We either rejected the fixup or folded B into C at this point.
473   const MCSymbolRefExpr *RefA = Target.getSymA();
474   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
475 
476   if (SymA && SymA->isVariable()) {
477     const MCExpr *Expr = SymA->getVariableValue();
478     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
479     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
480       llvm_unreachable("weakref used in reloc not yet implemented");
481   }
482 
483   // Put any constant offset in an addend. Offsets can be negative, and
484   // LLVM expects wrapping, in contrast to wasm's immediates which can't
485   // be negative and don't wrap.
486   FixedValue = 0;
487 
488   unsigned Type = getRelocType(Target, Fixup);
489   assert(!IsPCRel);
490   assert(SymA);
491 
492   // Absolute offset within a section or a function.
493   // Currently only supported for for metadata sections.
494   // See: test/MC/WebAssembly/blockaddress.ll
495   if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
496       Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
497     if (!FixupSection.getKind().isMetadata())
498       report_fatal_error("relocations for function or section offsets are "
499                          "only supported in metadata sections");
500 
501     const MCSymbol *SectionSymbol = nullptr;
502     const MCSection &SecA = SymA->getSection();
503     if (SecA.getKind().isText())
504       SectionSymbol = SectionFunctions.find(&SecA)->second;
505     else
506       SectionSymbol = SecA.getBeginSymbol();
507     if (!SectionSymbol)
508       report_fatal_error("section symbol is required for relocation");
509 
510     C += Layout.getSymbolOffset(*SymA);
511     SymA = cast<MCSymbolWasm>(SectionSymbol);
512   }
513 
514   // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
515   // against a named symbol.
516   if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
517     if (SymA->getName().empty())
518       report_fatal_error("relocations against un-named temporaries are not yet "
519                          "supported by wasm");
520 
521     SymA->setUsedInReloc();
522   }
523 
524   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
525   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
526 
527   if (FixupSection.isWasmData()) {
528     DataRelocations.push_back(Rec);
529   } else if (FixupSection.getKind().isText()) {
530     CodeRelocations.push_back(Rec);
531   } else if (FixupSection.getKind().isMetadata()) {
532     CustomSectionsRelocations[&FixupSection].push_back(Rec);
533   } else {
534     llvm_unreachable("unexpected section type");
535   }
536 }
537 
538 // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
539 // to allow patching.
WritePatchableLEB(raw_pwrite_stream & Stream,uint32_t X,uint64_t Offset)540 static void WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
541                               uint64_t Offset) {
542   uint8_t Buffer[5];
543   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
544   assert(SizeLen == 5);
545   Stream.pwrite((char *)Buffer, SizeLen, Offset);
546 }
547 
548 // Write X as an signed LEB value at offset Offset in Stream, padded
549 // to allow patching.
WritePatchableSLEB(raw_pwrite_stream & Stream,int32_t X,uint64_t Offset)550 static void WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
551                                uint64_t Offset) {
552   uint8_t Buffer[5];
553   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
554   assert(SizeLen == 5);
555   Stream.pwrite((char *)Buffer, SizeLen, Offset);
556 }
557 
558 // Write X as a plain integer value at offset Offset in Stream.
WriteI32(raw_pwrite_stream & Stream,uint32_t X,uint64_t Offset)559 static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
560   uint8_t Buffer[4];
561   support::endian::write32le(Buffer, X);
562   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
563 }
564 
ResolveSymbol(const MCSymbolWasm & Symbol)565 static const MCSymbolWasm *ResolveSymbol(const MCSymbolWasm &Symbol) {
566   if (Symbol.isVariable()) {
567     const MCExpr *Expr = Symbol.getVariableValue();
568     auto *Inner = cast<MCSymbolRefExpr>(Expr);
569     return cast<MCSymbolWasm>(&Inner->getSymbol());
570   }
571   return &Symbol;
572 }
573 
574 // Compute a value to write into the code at the location covered
575 // by RelEntry. This value isn't used by the static linker; it just serves
576 // to make the object format more readable and more likely to be directly
577 // useable.
578 uint32_t
getProvisionalValue(const WasmRelocationEntry & RelEntry)579 WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
580   switch (RelEntry.Type) {
581   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
582   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
583     // Provisional value is table address of the resolved symbol itself
584     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
585     assert(Sym->isFunction());
586     return TableIndices[Sym];
587   }
588   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
589     // Provisional value is same as the index
590     return getRelocationIndexValue(RelEntry);
591   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
592   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
593   case wasm::R_WEBASSEMBLY_EVENT_INDEX_LEB:
594     // Provisional value is function/global/event Wasm index
595     if (!WasmIndices.count(RelEntry.Symbol))
596       report_fatal_error("symbol not found in wasm index space: " +
597                          RelEntry.Symbol->getName());
598     return WasmIndices[RelEntry.Symbol];
599   case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
600   case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
601     const auto &Section =
602         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
603     return Section.getSectionOffset() + RelEntry.Addend;
604   }
605   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
606   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
607   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
608     // Provisional value is address of the global
609     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
610     // For undefined symbols, use zero
611     if (!Sym->isDefined())
612       return 0;
613     const wasm::WasmDataReference &Ref = DataLocations[Sym];
614     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
615     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
616     return Segment.Offset + Ref.Offset + RelEntry.Addend;
617   }
618   default:
619     llvm_unreachable("invalid relocation type");
620   }
621 }
622 
addData(SmallVectorImpl<char> & DataBytes,MCSectionWasm & DataSection)623 static void addData(SmallVectorImpl<char> &DataBytes,
624                     MCSectionWasm &DataSection) {
625   LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
626 
627   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
628 
629   for (const MCFragment &Frag : DataSection) {
630     if (Frag.hasInstructions())
631       report_fatal_error("only data supported in data sections");
632 
633     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
634       if (Align->getValueSize() != 1)
635         report_fatal_error("only byte values supported for alignment");
636       // If nops are requested, use zeros, as this is the data section.
637       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
638       uint64_t Size =
639           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
640                              DataBytes.size() + Align->getMaxBytesToEmit());
641       DataBytes.resize(Size, Value);
642     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
643       int64_t NumValues;
644       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
645         llvm_unreachable("The fill should be an assembler constant");
646       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
647                        Fill->getValue());
648     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
649       const SmallVectorImpl<char> &Contents = LEB->getContents();
650       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
651     } else {
652       const auto &DataFrag = cast<MCDataFragment>(Frag);
653       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
654       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
655     }
656   }
657 
658   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
659 }
660 
661 uint32_t
getRelocationIndexValue(const WasmRelocationEntry & RelEntry)662 WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
663   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
664     if (!TypeIndices.count(RelEntry.Symbol))
665       report_fatal_error("symbol not found in type index space: " +
666                          RelEntry.Symbol->getName());
667     return TypeIndices[RelEntry.Symbol];
668   }
669 
670   return RelEntry.Symbol->getIndex();
671 }
672 
673 // Apply the portions of the relocation records that we can handle ourselves
674 // directly.
applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,uint64_t ContentsOffset)675 void WasmObjectWriter::applyRelocations(
676     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
677   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
678   for (const WasmRelocationEntry &RelEntry : Relocations) {
679     uint64_t Offset = ContentsOffset +
680                       RelEntry.FixupSection->getSectionOffset() +
681                       RelEntry.Offset;
682 
683     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
684     uint32_t Value = getProvisionalValue(RelEntry);
685 
686     switch (RelEntry.Type) {
687     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
688     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
689     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
690     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
691     case wasm::R_WEBASSEMBLY_EVENT_INDEX_LEB:
692       WritePatchableLEB(Stream, Value, Offset);
693       break;
694     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
695     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
696     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
697     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
698       WriteI32(Stream, Value, Offset);
699       break;
700     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
701     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
702       WritePatchableSLEB(Stream, Value, Offset);
703       break;
704     default:
705       llvm_unreachable("invalid relocation type");
706     }
707   }
708 }
709 
writeTypeSection(ArrayRef<WasmSignature> Signatures)710 void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
711   if (Signatures.empty())
712     return;
713 
714   SectionBookkeeping Section;
715   startSection(Section, wasm::WASM_SEC_TYPE);
716 
717   encodeULEB128(Signatures.size(), W.OS);
718 
719   for (const WasmSignature &Sig : Signatures) {
720     W.OS << char(wasm::WASM_TYPE_FUNC);
721     encodeULEB128(Sig.Params.size(), W.OS);
722     for (wasm::ValType Ty : Sig.Params)
723       writeValueType(Ty);
724     encodeULEB128(Sig.Returns.size(), W.OS);
725     for (wasm::ValType Ty : Sig.Returns)
726       writeValueType(Ty);
727   }
728 
729   endSection(Section);
730 }
731 
writeImportSection(ArrayRef<wasm::WasmImport> Imports,uint32_t DataSize,uint32_t NumElements)732 void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
733                                           uint32_t DataSize,
734                                           uint32_t NumElements) {
735   if (Imports.empty())
736     return;
737 
738   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
739 
740   SectionBookkeeping Section;
741   startSection(Section, wasm::WASM_SEC_IMPORT);
742 
743   encodeULEB128(Imports.size(), W.OS);
744   for (const wasm::WasmImport &Import : Imports) {
745     writeString(Import.Module);
746     writeString(Import.Field);
747     W.OS << char(Import.Kind);
748 
749     switch (Import.Kind) {
750     case wasm::WASM_EXTERNAL_FUNCTION:
751       encodeULEB128(Import.SigIndex, W.OS);
752       break;
753     case wasm::WASM_EXTERNAL_GLOBAL:
754       W.OS << char(Import.Global.Type);
755       W.OS << char(Import.Global.Mutable ? 1 : 0);
756       break;
757     case wasm::WASM_EXTERNAL_MEMORY:
758       encodeULEB128(0, W.OS);        // flags
759       encodeULEB128(NumPages, W.OS); // initial
760       break;
761     case wasm::WASM_EXTERNAL_TABLE:
762       W.OS << char(Import.Table.ElemType);
763       encodeULEB128(0, W.OS);           // flags
764       encodeULEB128(NumElements, W.OS); // initial
765       break;
766     case wasm::WASM_EXTERNAL_EVENT:
767       encodeULEB128(Import.Event.Attribute, W.OS);
768       encodeULEB128(Import.Event.SigIndex, W.OS);
769       break;
770     default:
771       llvm_unreachable("unsupported import kind");
772     }
773   }
774 
775   endSection(Section);
776 }
777 
writeFunctionSection(ArrayRef<WasmFunction> Functions)778 void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
779   if (Functions.empty())
780     return;
781 
782   SectionBookkeeping Section;
783   startSection(Section, wasm::WASM_SEC_FUNCTION);
784 
785   encodeULEB128(Functions.size(), W.OS);
786   for (const WasmFunction &Func : Functions)
787     encodeULEB128(Func.SigIndex, W.OS);
788 
789   endSection(Section);
790 }
791 
writeGlobalSection()792 void WasmObjectWriter::writeGlobalSection() {
793   if (Globals.empty())
794     return;
795 
796   SectionBookkeeping Section;
797   startSection(Section, wasm::WASM_SEC_GLOBAL);
798 
799   encodeULEB128(Globals.size(), W.OS);
800   for (const WasmGlobal &Global : Globals) {
801     writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
802     W.OS << char(Global.Type.Mutable);
803 
804     W.OS << char(wasm::WASM_OPCODE_I32_CONST);
805     encodeSLEB128(Global.InitialValue, W.OS);
806     W.OS << char(wasm::WASM_OPCODE_END);
807   }
808 
809   endSection(Section);
810 }
811 
writeEventSection(ArrayRef<wasm::WasmEventType> Events)812 void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
813   if (Events.empty())
814     return;
815 
816   SectionBookkeeping Section;
817   startSection(Section, wasm::WASM_SEC_EVENT);
818 
819   encodeULEB128(Events.size(), W.OS);
820   for (const wasm::WasmEventType &Event : Events) {
821     encodeULEB128(Event.Attribute, W.OS);
822     encodeULEB128(Event.SigIndex, W.OS);
823   }
824 
825   endSection(Section);
826 }
827 
writeExportSection(ArrayRef<wasm::WasmExport> Exports)828 void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
829   if (Exports.empty())
830     return;
831 
832   SectionBookkeeping Section;
833   startSection(Section, wasm::WASM_SEC_EXPORT);
834 
835   encodeULEB128(Exports.size(), W.OS);
836   for (const wasm::WasmExport &Export : Exports) {
837     writeString(Export.Name);
838     W.OS << char(Export.Kind);
839     encodeULEB128(Export.Index, W.OS);
840   }
841 
842   endSection(Section);
843 }
844 
writeElemSection(ArrayRef<uint32_t> TableElems)845 void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
846   if (TableElems.empty())
847     return;
848 
849   SectionBookkeeping Section;
850   startSection(Section, wasm::WASM_SEC_ELEM);
851 
852   encodeULEB128(1, W.OS); // number of "segments"
853   encodeULEB128(0, W.OS); // the table index
854 
855   // init expr for starting offset
856   W.OS << char(wasm::WASM_OPCODE_I32_CONST);
857   encodeSLEB128(kInitialTableOffset, W.OS);
858   W.OS << char(wasm::WASM_OPCODE_END);
859 
860   encodeULEB128(TableElems.size(), W.OS);
861   for (uint32_t Elem : TableElems)
862     encodeULEB128(Elem, W.OS);
863 
864   endSection(Section);
865 }
866 
writeCodeSection(const MCAssembler & Asm,const MCAsmLayout & Layout,ArrayRef<WasmFunction> Functions)867 void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
868                                         const MCAsmLayout &Layout,
869                                         ArrayRef<WasmFunction> Functions) {
870   if (Functions.empty())
871     return;
872 
873   SectionBookkeeping Section;
874   startSection(Section, wasm::WASM_SEC_CODE);
875   CodeSectionIndex = Section.Index;
876 
877   encodeULEB128(Functions.size(), W.OS);
878 
879   for (const WasmFunction &Func : Functions) {
880     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
881 
882     int64_t Size = 0;
883     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
884       report_fatal_error(".size expression must be evaluatable");
885 
886     encodeULEB128(Size, W.OS);
887     FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
888     Asm.writeSectionData(W.OS, &FuncSection, Layout);
889   }
890 
891   // Apply fixups.
892   applyRelocations(CodeRelocations, Section.ContentsOffset);
893 
894   endSection(Section);
895 }
896 
writeDataSection()897 void WasmObjectWriter::writeDataSection() {
898   if (DataSegments.empty())
899     return;
900 
901   SectionBookkeeping Section;
902   startSection(Section, wasm::WASM_SEC_DATA);
903   DataSectionIndex = Section.Index;
904 
905   encodeULEB128(DataSegments.size(), W.OS); // count
906 
907   for (const WasmDataSegment &Segment : DataSegments) {
908     encodeULEB128(0, W.OS); // memory index
909     W.OS << char(wasm::WASM_OPCODE_I32_CONST);
910     encodeSLEB128(Segment.Offset, W.OS); // offset
911     W.OS << char(wasm::WASM_OPCODE_END);
912     encodeULEB128(Segment.Data.size(), W.OS); // size
913     Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
914     W.OS << Segment.Data; // data
915   }
916 
917   // Apply fixups.
918   applyRelocations(DataRelocations, Section.ContentsOffset);
919 
920   endSection(Section);
921 }
922 
writeRelocSection(uint32_t SectionIndex,StringRef Name,std::vector<WasmRelocationEntry> & Relocs)923 void WasmObjectWriter::writeRelocSection(
924     uint32_t SectionIndex, StringRef Name,
925     std::vector<WasmRelocationEntry> &Relocs) {
926   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
927   // for descriptions of the reloc sections.
928 
929   if (Relocs.empty())
930     return;
931 
932   // First, ensure the relocations are sorted in offset order.  In general they
933   // should already be sorted since `recordRelocation` is called in offset
934   // order, but for the code section we combine many MC sections into single
935   // wasm section, and this order is determined by the order of Asm.Symbols()
936   // not the sections order.
937   std::stable_sort(
938       Relocs.begin(), Relocs.end(),
939       [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
940         return (A.Offset + A.FixupSection->getSectionOffset()) <
941                (B.Offset + B.FixupSection->getSectionOffset());
942       });
943 
944   SectionBookkeeping Section;
945   startCustomSection(Section, std::string("reloc.") + Name.str());
946 
947   encodeULEB128(SectionIndex, W.OS);
948   encodeULEB128(Relocs.size(), W.OS);
949   for (const WasmRelocationEntry &RelEntry : Relocs) {
950     uint64_t Offset =
951         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
952     uint32_t Index = getRelocationIndexValue(RelEntry);
953 
954     W.OS << char(RelEntry.Type);
955     encodeULEB128(Offset, W.OS);
956     encodeULEB128(Index, W.OS);
957     if (RelEntry.hasAddend())
958       encodeSLEB128(RelEntry.Addend, W.OS);
959   }
960 
961   endSection(Section);
962 }
963 
writeCustomRelocSections()964 void WasmObjectWriter::writeCustomRelocSections() {
965   for (const auto &Sec : CustomSections) {
966     auto &Relocations = CustomSectionsRelocations[Sec.Section];
967     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
968   }
969 }
970 
writeLinkingMetaDataSection(ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,ArrayRef<std::pair<uint16_t,uint32_t>> InitFuncs,const std::map<StringRef,std::vector<WasmComdatEntry>> & Comdats)971 void WasmObjectWriter::writeLinkingMetaDataSection(
972     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
973     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
974     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
975   SectionBookkeeping Section;
976   startCustomSection(Section, "linking");
977   encodeULEB128(wasm::WasmMetadataVersion, W.OS);
978 
979   SectionBookkeeping SubSection;
980   if (SymbolInfos.size() != 0) {
981     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
982     encodeULEB128(SymbolInfos.size(), W.OS);
983     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
984       encodeULEB128(Sym.Kind, W.OS);
985       encodeULEB128(Sym.Flags, W.OS);
986       switch (Sym.Kind) {
987       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
988       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
989       case wasm::WASM_SYMBOL_TYPE_EVENT:
990         encodeULEB128(Sym.ElementIndex, W.OS);
991         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
992             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
993           writeString(Sym.Name);
994         break;
995       case wasm::WASM_SYMBOL_TYPE_DATA:
996         writeString(Sym.Name);
997         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
998           encodeULEB128(Sym.DataRef.Segment, W.OS);
999           encodeULEB128(Sym.DataRef.Offset, W.OS);
1000           encodeULEB128(Sym.DataRef.Size, W.OS);
1001         }
1002         break;
1003       case wasm::WASM_SYMBOL_TYPE_SECTION: {
1004         const uint32_t SectionIndex =
1005             CustomSections[Sym.ElementIndex].OutputIndex;
1006         encodeULEB128(SectionIndex, W.OS);
1007         break;
1008       }
1009       default:
1010         llvm_unreachable("unexpected kind");
1011       }
1012     }
1013     endSection(SubSection);
1014   }
1015 
1016   if (DataSegments.size()) {
1017     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1018     encodeULEB128(DataSegments.size(), W.OS);
1019     for (const WasmDataSegment &Segment : DataSegments) {
1020       writeString(Segment.Name);
1021       encodeULEB128(Segment.Alignment, W.OS);
1022       encodeULEB128(Segment.Flags, W.OS);
1023     }
1024     endSection(SubSection);
1025   }
1026 
1027   if (!InitFuncs.empty()) {
1028     startSection(SubSection, wasm::WASM_INIT_FUNCS);
1029     encodeULEB128(InitFuncs.size(), W.OS);
1030     for (auto &StartFunc : InitFuncs) {
1031       encodeULEB128(StartFunc.first, W.OS);  // priority
1032       encodeULEB128(StartFunc.second, W.OS); // function index
1033     }
1034     endSection(SubSection);
1035   }
1036 
1037   if (Comdats.size()) {
1038     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1039     encodeULEB128(Comdats.size(), W.OS);
1040     for (const auto &C : Comdats) {
1041       writeString(C.first);
1042       encodeULEB128(0, W.OS); // flags for future use
1043       encodeULEB128(C.second.size(), W.OS);
1044       for (const WasmComdatEntry &Entry : C.second) {
1045         encodeULEB128(Entry.Kind, W.OS);
1046         encodeULEB128(Entry.Index, W.OS);
1047       }
1048     }
1049     endSection(SubSection);
1050   }
1051 
1052   endSection(Section);
1053 }
1054 
writeCustomSections(const MCAssembler & Asm,const MCAsmLayout & Layout)1055 void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
1056                                            const MCAsmLayout &Layout) {
1057   for (auto &CustomSection : CustomSections) {
1058     SectionBookkeeping Section;
1059     auto *Sec = CustomSection.Section;
1060     startCustomSection(Section, CustomSection.Name);
1061 
1062     Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1063     Asm.writeSectionData(W.OS, Sec, Layout);
1064 
1065     CustomSection.OutputContentsOffset = Section.ContentsOffset;
1066     CustomSection.OutputIndex = Section.Index;
1067 
1068     endSection(Section);
1069 
1070     // Apply fixups.
1071     auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1072     applyRelocations(Relocations, CustomSection.OutputContentsOffset);
1073   }
1074 }
1075 
getFunctionType(const MCSymbolWasm & Symbol)1076 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
1077   assert(Symbol.isFunction());
1078   assert(TypeIndices.count(&Symbol));
1079   return TypeIndices[&Symbol];
1080 }
1081 
getEventType(const MCSymbolWasm & Symbol)1082 uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1083   assert(Symbol.isEvent());
1084   assert(TypeIndices.count(&Symbol));
1085   return TypeIndices[&Symbol];
1086 }
1087 
registerFunctionType(const MCSymbolWasm & Symbol)1088 void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
1089   assert(Symbol.isFunction());
1090 
1091   WasmSignature S;
1092   const MCSymbolWasm *ResolvedSym = ResolveSymbol(Symbol);
1093   if (auto *Sig = ResolvedSym->getSignature()) {
1094     S.Returns = Sig->Returns;
1095     S.Params = Sig->Params;
1096   }
1097 
1098   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1099   if (Pair.second)
1100     Signatures.push_back(S);
1101   TypeIndices[&Symbol] = Pair.first->second;
1102 
1103   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1104                     << " new:" << Pair.second << "\n");
1105   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1106 }
1107 
registerEventType(const MCSymbolWasm & Symbol)1108 void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1109   assert(Symbol.isEvent());
1110 
1111   // TODO Currently we don't generate imported exceptions, but if we do, we
1112   // should have a way of infering types of imported exceptions.
1113   WasmSignature S;
1114   if (auto *Sig = Symbol.getSignature()) {
1115     S.Returns = Sig->Returns;
1116     S.Params = Sig->Params;
1117   }
1118 
1119   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1120   if (Pair.second)
1121     Signatures.push_back(S);
1122   TypeIndices[&Symbol] = Pair.first->second;
1123 
1124   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1125                     << "\n");
1126   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1127 }
1128 
isInSymtab(const MCSymbolWasm & Sym)1129 static bool isInSymtab(const MCSymbolWasm &Sym) {
1130   if (Sym.isUsedInReloc())
1131     return true;
1132 
1133   if (Sym.isComdat() && !Sym.isDefined())
1134     return false;
1135 
1136   if (Sym.isTemporary() && Sym.getName().empty())
1137     return false;
1138 
1139   if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1140     return false;
1141 
1142   if (Sym.isSection())
1143     return false;
1144 
1145   return true;
1146 }
1147 
writeObject(MCAssembler & Asm,const MCAsmLayout & Layout)1148 uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1149                                        const MCAsmLayout &Layout) {
1150   uint64_t StartOffset = W.OS.tell();
1151 
1152   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1153   MCContext &Ctx = Asm.getContext();
1154 
1155   // Collect information from the available symbols.
1156   SmallVector<WasmFunction, 4> Functions;
1157   SmallVector<uint32_t, 4> TableElems;
1158   SmallVector<wasm::WasmImport, 4> Imports;
1159   SmallVector<wasm::WasmExport, 4> Exports;
1160   SmallVector<wasm::WasmEventType, 1> Events;
1161   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1162   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1163   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
1164   uint32_t DataSize = 0;
1165 
1166   // For now, always emit the memory import, since loads and stores are not
1167   // valid without it. In the future, we could perhaps be more clever and omit
1168   // it if there are no loads or stores.
1169   MCSymbolWasm *MemorySym =
1170       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
1171   wasm::WasmImport MemImport;
1172   MemImport.Module = MemorySym->getImportModule();
1173   MemImport.Field = MemorySym->getImportName();
1174   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1175   Imports.push_back(MemImport);
1176 
1177   // For now, always emit the table section, since indirect calls are not
1178   // valid without it. In the future, we could perhaps be more clever and omit
1179   // it if there are no indirect calls.
1180   MCSymbolWasm *TableSym =
1181       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
1182   wasm::WasmImport TableImport;
1183   TableImport.Module = TableSym->getImportModule();
1184   TableImport.Field = TableSym->getImportName();
1185   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1186   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1187   Imports.push_back(TableImport);
1188 
1189   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1190   // symbols.  This must be done before populating WasmIndices for defined
1191   // symbols.
1192   for (const MCSymbol &S : Asm.symbols()) {
1193     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1194 
1195     // Register types for all functions, including those with private linkage
1196     // (because wasm always needs a type signature).
1197     if (WS.isFunction())
1198       registerFunctionType(WS);
1199 
1200     if (WS.isEvent())
1201       registerEventType(WS);
1202 
1203     if (WS.isTemporary())
1204       continue;
1205 
1206     // If the symbol is not defined in this translation unit, import it.
1207     if (!WS.isDefined() && !WS.isComdat()) {
1208       if (WS.isFunction()) {
1209         wasm::WasmImport Import;
1210         Import.Module = WS.getImportModule();
1211         Import.Field = WS.getImportName();
1212         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1213         Import.SigIndex = getFunctionType(WS);
1214         Imports.push_back(Import);
1215         WasmIndices[&WS] = NumFunctionImports++;
1216       } else if (WS.isGlobal()) {
1217         if (WS.isWeak())
1218           report_fatal_error("undefined global symbol cannot be weak");
1219 
1220         wasm::WasmImport Import;
1221         Import.Module = WS.getImportModule();
1222         Import.Field = WS.getImportName();
1223         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1224         Import.Global = WS.getGlobalType();
1225         Imports.push_back(Import);
1226         WasmIndices[&WS] = NumGlobalImports++;
1227       } else if (WS.isEvent()) {
1228         if (WS.isWeak())
1229           report_fatal_error("undefined event symbol cannot be weak");
1230 
1231         wasm::WasmImport Import;
1232         Import.Module = WS.getImportModule();
1233         Import.Field = WS.getImportName();
1234         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1235         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1236         Import.Event.SigIndex = getEventType(WS);
1237         Imports.push_back(Import);
1238         WasmIndices[&WS] = NumEventImports++;
1239       }
1240     }
1241   }
1242 
1243   // Populate DataSegments and CustomSections, which must be done before
1244   // populating DataLocations.
1245   for (MCSection &Sec : Asm) {
1246     auto &Section = static_cast<MCSectionWasm &>(Sec);
1247     StringRef SectionName = Section.getSectionName();
1248 
1249     // .init_array sections are handled specially elsewhere.
1250     if (SectionName.startswith(".init_array"))
1251       continue;
1252 
1253     // Code is handled separately
1254     if (Section.getKind().isText())
1255       continue;
1256 
1257     if (Section.isWasmData()) {
1258       uint32_t SegmentIndex = DataSegments.size();
1259       DataSize = alignTo(DataSize, Section.getAlignment());
1260       DataSegments.emplace_back();
1261       WasmDataSegment &Segment = DataSegments.back();
1262       Segment.Name = SectionName;
1263       Segment.Offset = DataSize;
1264       Segment.Section = &Section;
1265       addData(Segment.Data, Section);
1266       Segment.Alignment = Log2_32(Section.getAlignment());
1267       Segment.Flags = 0;
1268       DataSize += Segment.Data.size();
1269       Section.setSegmentIndex(SegmentIndex);
1270 
1271       if (const MCSymbolWasm *C = Section.getGroup()) {
1272         Comdats[C->getName()].emplace_back(
1273             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1274       }
1275     } else {
1276       // Create custom sections
1277       assert(Sec.getKind().isMetadata());
1278 
1279       StringRef Name = SectionName;
1280 
1281       // For user-defined custom sections, strip the prefix
1282       if (Name.startswith(".custom_section."))
1283         Name = Name.substr(strlen(".custom_section."));
1284 
1285       MCSymbol *Begin = Sec.getBeginSymbol();
1286       if (Begin) {
1287         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1288         if (SectionName != Begin->getName())
1289           report_fatal_error("section name and begin symbol should match: " +
1290                              Twine(SectionName));
1291       }
1292       CustomSections.emplace_back(Name, &Section);
1293     }
1294   }
1295 
1296   // Populate WasmIndices and DataLocations for defined symbols.
1297   for (const MCSymbol &S : Asm.symbols()) {
1298     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1299     // or used in relocations.
1300     if (S.isTemporary() && S.getName().empty())
1301       continue;
1302 
1303     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1304     LLVM_DEBUG(
1305         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1306                << " isDefined=" << S.isDefined() << " isExternal="
1307                << S.isExternal() << " isTemporary=" << S.isTemporary()
1308                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1309                << " isVariable=" << WS.isVariable() << "\n");
1310 
1311     if (WS.isVariable())
1312       continue;
1313     if (WS.isComdat() && !WS.isDefined())
1314       continue;
1315 
1316     if (WS.isFunction()) {
1317       unsigned Index;
1318       if (WS.isDefined()) {
1319         if (WS.getOffset() != 0)
1320           report_fatal_error(
1321               "function sections must contain one function each");
1322 
1323         if (WS.getSize() == 0)
1324           report_fatal_error(
1325               "function symbols must have a size set with .size");
1326 
1327         // A definition. Write out the function body.
1328         Index = NumFunctionImports + Functions.size();
1329         WasmFunction Func;
1330         Func.SigIndex = getFunctionType(WS);
1331         Func.Sym = &WS;
1332         WasmIndices[&WS] = Index;
1333         Functions.push_back(Func);
1334 
1335         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1336         if (const MCSymbolWasm *C = Section.getGroup()) {
1337           Comdats[C->getName()].emplace_back(
1338               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1339         }
1340       } else {
1341         // An import; the index was assigned above.
1342         Index = WasmIndices.find(&WS)->second;
1343       }
1344 
1345       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1346 
1347     } else if (WS.isData()) {
1348       if (WS.isTemporary() && !WS.getSize())
1349         continue;
1350 
1351       if (!WS.isDefined()) {
1352         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1353                           << "\n");
1354         continue;
1355       }
1356 
1357       if (!WS.getSize())
1358         report_fatal_error("data symbols must have a size set with .size: " +
1359                            WS.getName());
1360 
1361       int64_t Size = 0;
1362       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1363         report_fatal_error(".size expression must be evaluatable");
1364 
1365       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1366       assert(DataSection.isWasmData());
1367 
1368       // For each data symbol, export it in the symtab as a reference to the
1369       // corresponding Wasm data segment.
1370       wasm::WasmDataReference Ref = wasm::WasmDataReference{
1371           DataSection.getSegmentIndex(),
1372           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1373           static_cast<uint32_t>(Size)};
1374       DataLocations[&WS] = Ref;
1375       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1376 
1377     } else if (WS.isGlobal()) {
1378       // A "true" Wasm global (currently just __stack_pointer)
1379       if (WS.isDefined())
1380         report_fatal_error("don't yet support defined globals");
1381 
1382       // An import; the index was assigned above
1383       LLVM_DEBUG(dbgs() << "  -> global index: "
1384                         << WasmIndices.find(&WS)->second << "\n");
1385 
1386     } else if (WS.isEvent()) {
1387       // C++ exception symbol (__cpp_exception)
1388       unsigned Index;
1389       if (WS.isDefined()) {
1390         Index = NumEventImports + Events.size();
1391         wasm::WasmEventType Event;
1392         Event.SigIndex = getEventType(WS);
1393         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1394         WasmIndices[&WS] = Index;
1395         Events.push_back(Event);
1396       } else {
1397         // An import; the index was assigned above.
1398         Index = WasmIndices.find(&WS)->second;
1399       }
1400       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1401                         << "\n");
1402 
1403     } else {
1404       assert(WS.isSection());
1405     }
1406   }
1407 
1408   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1409   // process these in a separate pass because we need to have processed the
1410   // target of the alias before the alias itself and the symbols are not
1411   // necessarily ordered in this way.
1412   for (const MCSymbol &S : Asm.symbols()) {
1413     if (!S.isVariable())
1414       continue;
1415 
1416     assert(S.isDefined());
1417 
1418     // Find the target symbol of this weak alias and export that index
1419     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1420     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
1421     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1422                       << "'\n");
1423 
1424     if (WS.isFunction()) {
1425       assert(WasmIndices.count(ResolvedSym) > 0);
1426       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1427       WasmIndices[&WS] = WasmIndex;
1428       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1429     } else if (WS.isData()) {
1430       assert(DataLocations.count(ResolvedSym) > 0);
1431       const wasm::WasmDataReference &Ref =
1432           DataLocations.find(ResolvedSym)->second;
1433       DataLocations[&WS] = Ref;
1434       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
1435     } else {
1436       report_fatal_error("don't yet support global/event aliases");
1437     }
1438   }
1439 
1440   // Finally, populate the symbol table itself, in its "natural" order.
1441   for (const MCSymbol &S : Asm.symbols()) {
1442     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1443     if (!isInSymtab(WS)) {
1444       WS.setIndex(INVALID_INDEX);
1445       continue;
1446     }
1447     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1448 
1449     uint32_t Flags = 0;
1450     if (WS.isWeak())
1451       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1452     if (WS.isHidden())
1453       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1454     if (!WS.isExternal() && WS.isDefined())
1455       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1456     if (WS.isUndefined())
1457       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1458     if (WS.getName() != WS.getImportName())
1459       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1460 
1461     wasm::WasmSymbolInfo Info;
1462     Info.Name = WS.getName();
1463     Info.Kind = WS.getType();
1464     Info.Flags = Flags;
1465     if (!WS.isData()) {
1466       assert(WasmIndices.count(&WS) > 0);
1467       Info.ElementIndex = WasmIndices.find(&WS)->second;
1468     } else if (WS.isDefined()) {
1469       assert(DataLocations.count(&WS) > 0);
1470       Info.DataRef = DataLocations.find(&WS)->second;
1471     }
1472     WS.setIndex(SymbolInfos.size());
1473     SymbolInfos.emplace_back(Info);
1474   }
1475 
1476   {
1477     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1478       // Functions referenced by a relocation need to put in the table.  This is
1479       // purely to make the object file's provisional values readable, and is
1480       // ignored by the linker, which re-calculates the relocations itself.
1481       if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1482           Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1483         return;
1484       assert(Rel.Symbol->isFunction());
1485       const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
1486       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
1487       uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1488       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1489         LLVM_DEBUG(dbgs() << "  -> adding " << WS.getName()
1490                           << " to table: " << TableIndex << "\n");
1491         TableElems.push_back(FunctionIndex);
1492         registerFunctionType(WS);
1493       }
1494     };
1495 
1496     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1497       HandleReloc(RelEntry);
1498     for (const WasmRelocationEntry &RelEntry : DataRelocations)
1499       HandleReloc(RelEntry);
1500   }
1501 
1502   // Translate .init_array section contents into start functions.
1503   for (const MCSection &S : Asm) {
1504     const auto &WS = static_cast<const MCSectionWasm &>(S);
1505     if (WS.getSectionName().startswith(".fini_array"))
1506       report_fatal_error(".fini_array sections are unsupported");
1507     if (!WS.getSectionName().startswith(".init_array"))
1508       continue;
1509     if (WS.getFragmentList().empty())
1510       continue;
1511 
1512     // init_array is expected to contain a single non-empty data fragment
1513     if (WS.getFragmentList().size() != 3)
1514       report_fatal_error("only one .init_array section fragment supported");
1515 
1516     auto IT = WS.begin();
1517     const MCFragment &EmptyFrag = *IT;
1518     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1519       report_fatal_error(".init_array section should be aligned");
1520 
1521     IT = std::next(IT);
1522     const MCFragment &AlignFrag = *IT;
1523     if (AlignFrag.getKind() != MCFragment::FT_Align)
1524       report_fatal_error(".init_array section should be aligned");
1525     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1526       report_fatal_error(".init_array section should be aligned for pointers");
1527 
1528     const MCFragment &Frag = *std::next(IT);
1529     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1530       report_fatal_error("only data supported in .init_array section");
1531 
1532     uint16_t Priority = UINT16_MAX;
1533     unsigned PrefixLength = strlen(".init_array");
1534     if (WS.getSectionName().size() > PrefixLength) {
1535       if (WS.getSectionName()[PrefixLength] != '.')
1536         report_fatal_error(
1537             ".init_array section priority should start with '.'");
1538       if (WS.getSectionName()
1539               .substr(PrefixLength + 1)
1540               .getAsInteger(10, Priority))
1541         report_fatal_error("invalid .init_array section priority");
1542     }
1543     const auto &DataFrag = cast<MCDataFragment>(Frag);
1544     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1545     for (const uint8_t *
1546              p = (const uint8_t *)Contents.data(),
1547             *end = (const uint8_t *)Contents.data() + Contents.size();
1548          p != end; ++p) {
1549       if (*p != 0)
1550         report_fatal_error("non-symbolic data in .init_array section");
1551     }
1552     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1553       assert(Fixup.getKind() ==
1554              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1555       const MCExpr *Expr = Fixup.getValue();
1556       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1557       if (!Sym)
1558         report_fatal_error("fixups in .init_array should be symbol references");
1559       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1560         report_fatal_error("symbols in .init_array should be for functions");
1561       if (Sym->getSymbol().getIndex() == INVALID_INDEX)
1562         report_fatal_error("symbols in .init_array should exist in symbtab");
1563       InitFuncs.push_back(
1564           std::make_pair(Priority, Sym->getSymbol().getIndex()));
1565     }
1566   }
1567 
1568   // Write out the Wasm header.
1569   writeHeader(Asm);
1570 
1571   writeTypeSection(Signatures);
1572   writeImportSection(Imports, DataSize, TableElems.size());
1573   writeFunctionSection(Functions);
1574   // Skip the "table" section; we import the table instead.
1575   // Skip the "memory" section; we import the memory instead.
1576   writeGlobalSection();
1577   writeEventSection(Events);
1578   writeExportSection(Exports);
1579   writeElemSection(TableElems);
1580   writeCodeSection(Asm, Layout, Functions);
1581   writeDataSection();
1582   writeCustomSections(Asm, Layout);
1583   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1584   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1585   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1586   writeCustomRelocSections();
1587 
1588   // TODO: Translate the .comment section to the output.
1589   return W.OS.tell() - StartOffset;
1590 }
1591 
1592 std::unique_ptr<MCObjectWriter>
createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,raw_pwrite_stream & OS)1593 llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1594                              raw_pwrite_stream &OS) {
1595   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
1596 }
1597