1 //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Wasm object file writer information.
12 //===----------------------------------------------------------------------===//
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"
37 #define DEBUG_TYPE "mc"
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;
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.
51 // Where the contents of the section starts (after the header).
52 uint64_t ContentsOffset;
55 // The signature of a wasm function, in a struct capable of being used as a
57 struct WasmFunctionType {
58 // Support empty and tombstone instances, needed by DenseMap.
59 enum { Plain, Empty, Tombstone } State;
61 // The return types of the function.
62 SmallVector<wasm::ValType, 1> Returns;
64 // The parameter types of the function.
65 SmallVector<wasm::ValType, 4> Params;
67 WasmFunctionType() : State(Plain) {}
69 bool operator==(const WasmFunctionType &Other) const {
70 return State == Other.State && Returns == Other.Returns &&
71 Params == Other.Params;
75 // Traits for using WasmFunctionType in a DenseMap.
76 struct WasmFunctionTypeDenseMapInfo {
77 static WasmFunctionType getEmptyKey() {
78 WasmFunctionType FuncTy;
79 FuncTy.State = WasmFunctionType::Empty;
82 static WasmFunctionType getTombstoneKey() {
83 WasmFunctionType FuncTy;
84 FuncTy.State = WasmFunctionType::Tombstone;
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));
95 static bool isEqual(const WasmFunctionType &LHS,
96 const WasmFunctionType &RHS) {
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;
111 SmallVector<char, 4> Data;
114 // A wasm import to be written into the import section.
116 StringRef ModuleName;
123 // A wasm function to be written into the function section.
124 struct WasmFunction {
126 const MCSymbolWasm *Sym;
129 // A wasm export to be written into the export section.
136 // A wasm global to be written into the global section.
141 uint64_t InitialValue;
142 uint32_t ImportIndex;
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
148 struct WasmComdatEntry {
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.
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) {}
167 bool hasAddend() const {
169 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
170 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
171 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
178 void print(raw_ostream &Out) const {
179 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
181 << ", FixupSection=" << FixupSection->getSectionName();
184 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
185 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
190 raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
196 class WasmObjectWriter : public MCObjectWriter {
197 /// The target specific Wasm writer instance.
198 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
200 // Relocations for fixing up references in the code section.
201 std::vector<WasmRelocationEntry> CodeRelocations;
203 // Relocations for fixing up references in the data section.
204 std::vector<WasmRelocationEntry> DataRelocations;
206 // Index values to use for fixing up call_indirect type indices.
207 // Maps function symbols to the index of the type of the function
208 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
209 // Maps function symbols to the table element index space. Used
210 // for TABLE_INDEX relocation types (i.e. address taken functions).
211 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
212 // Maps function/global symbols to the function/global index space.
213 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
215 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
217 SmallVector<WasmFunctionType, 4> FunctionTypes;
218 SmallVector<WasmGlobal, 4> Globals;
219 unsigned NumFunctionImports = 0;
220 unsigned NumGlobalImports = 0;
222 // TargetObjectWriter wrappers.
223 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
224 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
225 return TargetObjectWriter->getRelocType(Target, Fixup);
228 void startSection(SectionBookkeeping &Section, unsigned SectionId,
229 const char *Name = nullptr);
230 void endSection(SectionBookkeeping &Section);
233 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
234 raw_pwrite_stream &OS)
235 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
236 TargetObjectWriter(std::move(MOTW)) {}
238 ~WasmObjectWriter() override;
241 void reset() override {
242 CodeRelocations.clear();
243 DataRelocations.clear();
245 SymbolIndices.clear();
246 IndirectSymbolIndices.clear();
247 FunctionTypeIndices.clear();
248 FunctionTypes.clear();
250 MCObjectWriter::reset();
251 NumFunctionImports = 0;
252 NumGlobalImports = 0;
255 void writeHeader(const MCAssembler &Asm);
257 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
258 const MCFragment *Fragment, const MCFixup &Fixup,
259 MCValue Target, uint64_t &FixedValue) override;
261 void executePostLayoutBinding(MCAssembler &Asm,
262 const MCAsmLayout &Layout) override;
264 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
266 void writeString(const StringRef Str) {
267 encodeULEB128(Str.size(), getStream());
271 void writeValueType(wasm::ValType Ty) {
272 encodeSLEB128(int32_t(Ty), getStream());
275 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
276 void writeImportSection(ArrayRef<WasmImport> Imports, uint32_t DataSize,
277 uint32_t NumElements);
278 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
279 void writeGlobalSection();
280 void writeExportSection(ArrayRef<WasmExport> Exports);
281 void writeElemSection(ArrayRef<uint32_t> TableElems);
282 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
283 ArrayRef<WasmFunction> Functions);
284 void writeDataSection(ArrayRef<WasmDataSegment> Segments);
285 void writeCodeRelocSection();
286 void writeDataRelocSection();
287 void writeLinkingMetaDataSection(
288 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
289 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
290 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
291 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats);
293 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
294 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
295 uint64_t ContentsOffset);
297 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
298 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
299 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
300 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
303 } // end anonymous namespace
305 WasmObjectWriter::~WasmObjectWriter() {}
307 // Write out a section header and a patchable section size field.
308 void WasmObjectWriter::startSection(SectionBookkeeping &Section,
311 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
312 "Only custom sections can have names");
314 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
315 encodeULEB128(SectionId, getStream());
317 Section.SizeOffset = getStream().tell();
319 // The section size. We don't know the size yet, so reserve enough space
320 // for any 32-bit value; we'll patch it later.
321 encodeULEB128(UINT32_MAX, getStream());
323 // The position where the section starts, for measuring its size.
324 Section.ContentsOffset = getStream().tell();
326 // Custom sections in wasm also have a string identifier.
327 if (SectionId == wasm::WASM_SEC_CUSTOM) {
329 writeString(StringRef(Name));
333 // Now that the section is complete and we know how big it is, patch up the
334 // section size field at the start of the section.
335 void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
336 uint64_t Size = getStream().tell() - Section.ContentsOffset;
337 if (uint32_t(Size) != Size)
338 report_fatal_error("section size does not fit in a uint32_t");
340 DEBUG(dbgs() << "endSection size=" << Size << "\n");
342 // Write the final section size to the payload_len field, which follows
343 // the section id byte.
345 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
346 assert(SizeLen == 5);
347 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
350 // Emit the Wasm header.
351 void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
352 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
353 writeLE32(wasm::WasmVersion);
356 void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
357 const MCAsmLayout &Layout) {
360 void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
361 const MCAsmLayout &Layout,
362 const MCFragment *Fragment,
363 const MCFixup &Fixup, MCValue Target,
364 uint64_t &FixedValue) {
365 MCAsmBackend &Backend = Asm.getBackend();
366 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
367 MCFixupKindInfo::FKF_IsPCRel;
368 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
369 uint64_t C = Target.getConstant();
370 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
371 MCContext &Ctx = Asm.getContext();
373 // The .init_array isn't translated as data, so don't do relocations in it.
374 if (FixupSection.getSectionName().startswith(".init_array"))
377 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
378 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
379 "Should not have constructed this");
381 // Let A, B and C being the components of Target and R be the location of
382 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
383 // If it is pcrel, we want to compute (A - B + C - R).
385 // In general, Wasm has no relocations for -B. It can only represent (A + C)
386 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
387 // replace B to implement it: (A - R - K + C)
391 "No relocation available to represent this relative expression");
395 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
397 if (SymB.isUndefined()) {
398 Ctx.reportError(Fixup.getLoc(),
399 Twine("symbol '") + SymB.getName() +
400 "' can not be undefined in a subtraction expression");
404 assert(!SymB.isAbsolute() && "Should have been folded");
405 const MCSection &SecB = SymB.getSection();
406 if (&SecB != &FixupSection) {
407 Ctx.reportError(Fixup.getLoc(),
408 "Cannot represent a difference across sections");
412 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
413 uint64_t K = SymBOffset - FixupOffset;
418 // We either rejected the fixup or folded B into C at this point.
419 const MCSymbolRefExpr *RefA = Target.getSymA();
420 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
422 if (SymA && SymA->isVariable()) {
423 const MCExpr *Expr = SymA->getVariableValue();
424 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
425 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
426 llvm_unreachable("weakref used in reloc not yet implemented");
429 // Put any constant offset in an addend. Offsets can be negative, and
430 // LLVM expects wrapping, in contrast to wasm's immediates which can't
431 // be negative and don't wrap.
435 SymA->setUsedInReloc();
440 unsigned Type = getRelocType(Target, Fixup);
442 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
443 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
445 if (FixupSection.isWasmData())
446 DataRelocations.push_back(Rec);
447 else if (FixupSection.getKind().isText())
448 CodeRelocations.push_back(Rec);
449 else if (!FixupSection.getKind().isMetadata())
450 // TODO(sbc): Add support for debug sections.
451 llvm_unreachable("unexpected section type");
454 // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
455 // to allow patching.
457 WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
459 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
460 assert(SizeLen == 5);
461 Stream.pwrite((char *)Buffer, SizeLen, Offset);
464 // Write X as an signed LEB value at offset Offset in Stream, padded
465 // to allow patching.
467 WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
469 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
470 assert(SizeLen == 5);
471 Stream.pwrite((char *)Buffer, SizeLen, Offset);
474 // Write X as a plain integer value at offset Offset in Stream.
475 static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
477 support::endian::write32le(Buffer, X);
478 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
481 static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
482 if (Symbol.isVariable()) {
483 const MCExpr *Expr = Symbol.getVariableValue();
484 auto *Inner = cast<MCSymbolRefExpr>(Expr);
485 return cast<MCSymbolWasm>(&Inner->getSymbol());
490 // Compute a value to write into the code at the location covered
491 // by RelEntry. This value isn't used by the static linker; it just serves
492 // to make the object format more readable and more likely to be directly
495 WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
497 switch (RelEntry.Type) {
498 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
499 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
500 // Provitional value is the indirect symbol index
501 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
502 report_fatal_error("symbol not found in table index space: " +
503 RelEntry.Symbol->getName());
504 return IndirectSymbolIndices[RelEntry.Symbol];
505 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
506 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
507 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
508 // Provitional value is function/type/global index itself
509 return getRelocationIndexValue(RelEntry);
510 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
511 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
512 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
513 // Provitional value is address of the global
514 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
515 // For undefined symbols, use zero
516 if (!Sym->isDefined())
519 uint32_t GlobalIndex = SymbolIndices[Sym];
520 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
521 uint64_t Address = Global.InitialValue + RelEntry.Addend;
523 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
527 llvm_unreachable("invalid relocation type");
531 static void addData(SmallVectorImpl<char> &DataBytes,
532 MCSectionWasm &DataSection) {
533 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
535 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
537 size_t LastFragmentSize = 0;
538 for (const MCFragment &Frag : DataSection) {
539 if (Frag.hasInstructions())
540 report_fatal_error("only data supported in data sections");
542 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
543 if (Align->getValueSize() != 1)
544 report_fatal_error("only byte values supported for alignment");
545 // If nops are requested, use zeros, as this is the data section.
546 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
547 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
548 Align->getAlignment()),
550 Align->getMaxBytesToEmit());
551 DataBytes.resize(Size, Value);
552 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
554 if (!Fill->getSize().evaluateAsAbsolute(Size))
555 llvm_unreachable("The fill should be an assembler constant");
556 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
558 const auto &DataFrag = cast<MCDataFragment>(Frag);
559 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
561 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
562 LastFragmentSize = Contents.size();
566 // Don't allow empty segments, or segments that end with zero-sized
567 // fragment, otherwise the linker cannot map symbols to a unique
568 // data segment. This can be triggered by zero-sized structs
569 // See: test/MC/WebAssembly/bss.ll
570 if (LastFragmentSize == 0)
571 DataBytes.resize(DataBytes.size() + 1);
572 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
576 WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
577 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
578 if (!TypeIndices.count(RelEntry.Symbol))
579 report_fatal_error("symbol not found in type index space: " +
580 RelEntry.Symbol->getName());
581 return TypeIndices[RelEntry.Symbol];
584 if (!SymbolIndices.count(RelEntry.Symbol))
585 report_fatal_error("symbol not found in function/global index space: " +
586 RelEntry.Symbol->getName());
587 return SymbolIndices[RelEntry.Symbol];
590 // Apply the portions of the relocation records that we can handle ourselves
592 void WasmObjectWriter::applyRelocations(
593 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
594 raw_pwrite_stream &Stream = getStream();
595 for (const WasmRelocationEntry &RelEntry : Relocations) {
596 uint64_t Offset = ContentsOffset +
597 RelEntry.FixupSection->getSectionOffset() +
600 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
601 uint32_t Value = getProvisionalValue(RelEntry);
603 switch (RelEntry.Type) {
604 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
605 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
606 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
607 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
608 WritePatchableLEB(Stream, Value, Offset);
610 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
611 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
612 WriteI32(Stream, Value, Offset);
614 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
615 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
616 WritePatchableSLEB(Stream, Value, Offset);
619 llvm_unreachable("invalid relocation type");
624 // Write out the portions of the relocation records that the linker will
626 void WasmObjectWriter::writeRelocations(
627 ArrayRef<WasmRelocationEntry> Relocations) {
628 raw_pwrite_stream &Stream = getStream();
629 for (const WasmRelocationEntry& RelEntry : Relocations) {
631 uint64_t Offset = RelEntry.Offset +
632 RelEntry.FixupSection->getSectionOffset();
633 uint32_t Index = getRelocationIndexValue(RelEntry);
635 encodeULEB128(RelEntry.Type, Stream);
636 encodeULEB128(Offset, Stream);
637 encodeULEB128(Index, Stream);
638 if (RelEntry.hasAddend())
639 encodeSLEB128(RelEntry.Addend, Stream);
643 void WasmObjectWriter::writeTypeSection(
644 ArrayRef<WasmFunctionType> FunctionTypes) {
645 if (FunctionTypes.empty())
648 SectionBookkeeping Section;
649 startSection(Section, wasm::WASM_SEC_TYPE);
651 encodeULEB128(FunctionTypes.size(), getStream());
653 for (const WasmFunctionType &FuncTy : FunctionTypes) {
654 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
655 encodeULEB128(FuncTy.Params.size(), getStream());
656 for (wasm::ValType Ty : FuncTy.Params)
658 encodeULEB128(FuncTy.Returns.size(), getStream());
659 for (wasm::ValType Ty : FuncTy.Returns)
666 void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports,
668 uint32_t NumElements) {
672 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
674 SectionBookkeeping Section;
675 startSection(Section, wasm::WASM_SEC_IMPORT);
677 encodeULEB128(Imports.size(), getStream());
678 for (const WasmImport &Import : Imports) {
679 writeString(Import.ModuleName);
680 writeString(Import.FieldName);
682 encodeULEB128(Import.Kind, getStream());
684 switch (Import.Kind) {
685 case wasm::WASM_EXTERNAL_FUNCTION:
686 encodeULEB128(Import.Type, getStream());
688 case wasm::WASM_EXTERNAL_GLOBAL:
689 encodeSLEB128(int32_t(Import.Type), getStream());
690 encodeULEB128(int32_t(Import.IsMutable), getStream());
692 case wasm::WASM_EXTERNAL_MEMORY:
693 encodeULEB128(0, getStream()); // flags
694 encodeULEB128(NumPages, getStream()); // initial
696 case wasm::WASM_EXTERNAL_TABLE:
697 encodeSLEB128(int32_t(Import.Type), getStream());
698 encodeULEB128(0, getStream()); // flags
699 encodeULEB128(NumElements, getStream()); // initial
702 llvm_unreachable("unsupported import kind");
709 void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
710 if (Functions.empty())
713 SectionBookkeeping Section;
714 startSection(Section, wasm::WASM_SEC_FUNCTION);
716 encodeULEB128(Functions.size(), getStream());
717 for (const WasmFunction &Func : Functions)
718 encodeULEB128(Func.Type, getStream());
723 void WasmObjectWriter::writeGlobalSection() {
727 SectionBookkeeping Section;
728 startSection(Section, wasm::WASM_SEC_GLOBAL);
730 encodeULEB128(Globals.size(), getStream());
731 for (const WasmGlobal &Global : Globals) {
732 writeValueType(Global.Type);
733 write8(Global.IsMutable);
735 if (Global.HasImport) {
736 assert(Global.InitialValue == 0);
737 write8(wasm::WASM_OPCODE_GET_GLOBAL);
738 encodeULEB128(Global.ImportIndex, getStream());
740 assert(Global.ImportIndex == 0);
741 write8(wasm::WASM_OPCODE_I32_CONST);
742 encodeSLEB128(Global.InitialValue, getStream()); // offset
744 write8(wasm::WASM_OPCODE_END);
750 void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
754 SectionBookkeeping Section;
755 startSection(Section, wasm::WASM_SEC_EXPORT);
757 encodeULEB128(Exports.size(), getStream());
758 for (const WasmExport &Export : Exports) {
759 writeString(Export.FieldName);
760 encodeSLEB128(Export.Kind, getStream());
761 encodeULEB128(Export.Index, getStream());
767 void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
768 if (TableElems.empty())
771 SectionBookkeeping Section;
772 startSection(Section, wasm::WASM_SEC_ELEM);
774 encodeULEB128(1, getStream()); // number of "segments"
775 encodeULEB128(0, getStream()); // the table index
777 // init expr for starting offset
778 write8(wasm::WASM_OPCODE_I32_CONST);
779 encodeSLEB128(kInitialTableOffset, getStream());
780 write8(wasm::WASM_OPCODE_END);
782 encodeULEB128(TableElems.size(), getStream());
783 for (uint32_t Elem : TableElems)
784 encodeULEB128(Elem, getStream());
789 void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
790 const MCAsmLayout &Layout,
791 ArrayRef<WasmFunction> Functions) {
792 if (Functions.empty())
795 SectionBookkeeping Section;
796 startSection(Section, wasm::WASM_SEC_CODE);
798 encodeULEB128(Functions.size(), getStream());
800 for (const WasmFunction &Func : Functions) {
801 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
804 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
805 report_fatal_error(".size expression must be evaluatable");
807 encodeULEB128(Size, getStream());
808 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
809 Asm.writeSectionData(&FuncSection, Layout);
813 applyRelocations(CodeRelocations, Section.ContentsOffset);
818 void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
819 if (Segments.empty())
822 SectionBookkeeping Section;
823 startSection(Section, wasm::WASM_SEC_DATA);
825 encodeULEB128(Segments.size(), getStream()); // count
827 for (const WasmDataSegment & Segment : Segments) {
828 encodeULEB128(0, getStream()); // memory index
829 write8(wasm::WASM_OPCODE_I32_CONST);
830 encodeSLEB128(Segment.Offset, getStream()); // offset
831 write8(wasm::WASM_OPCODE_END);
832 encodeULEB128(Segment.Data.size(), getStream()); // size
833 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
834 writeBytes(Segment.Data); // data
838 applyRelocations(DataRelocations, Section.ContentsOffset);
843 void WasmObjectWriter::writeCodeRelocSection() {
844 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
845 // for descriptions of the reloc sections.
847 if (CodeRelocations.empty())
850 SectionBookkeeping Section;
851 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
853 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
854 encodeULEB128(CodeRelocations.size(), getStream());
856 writeRelocations(CodeRelocations);
861 void WasmObjectWriter::writeDataRelocSection() {
862 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
863 // for descriptions of the reloc sections.
865 if (DataRelocations.empty())
868 SectionBookkeeping Section;
869 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
871 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
872 encodeULEB128(DataRelocations.size(), getStream());
874 writeRelocations(DataRelocations);
879 void WasmObjectWriter::writeLinkingMetaDataSection(
880 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
881 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
882 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
883 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats) {
884 SectionBookkeeping Section;
885 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
886 SectionBookkeeping SubSection;
888 if (SymbolFlags.size() != 0) {
889 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
890 encodeULEB128(SymbolFlags.size(), getStream());
891 for (auto Pair: SymbolFlags) {
892 writeString(Pair.first);
893 encodeULEB128(Pair.second, getStream());
895 endSection(SubSection);
899 startSection(SubSection, wasm::WASM_DATA_SIZE);
900 encodeULEB128(DataSize, getStream());
901 endSection(SubSection);
904 if (Segments.size()) {
905 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
906 encodeULEB128(Segments.size(), getStream());
907 for (const WasmDataSegment &Segment : Segments) {
908 writeString(Segment.Name);
909 encodeULEB128(Segment.Alignment, getStream());
910 encodeULEB128(Segment.Flags, getStream());
912 endSection(SubSection);
915 if (!InitFuncs.empty()) {
916 startSection(SubSection, wasm::WASM_INIT_FUNCS);
917 encodeULEB128(InitFuncs.size(), getStream());
918 for (auto &StartFunc : InitFuncs) {
919 encodeULEB128(StartFunc.first, getStream()); // priority
920 encodeULEB128(StartFunc.second, getStream()); // function index
922 endSection(SubSection);
925 if (Comdats.size()) {
926 startSection(SubSection, wasm::WASM_COMDAT_INFO);
927 encodeULEB128(Comdats.size(), getStream());
928 for (const auto &C : Comdats) {
929 writeString(C.first);
930 encodeULEB128(0, getStream()); // flags for future use
931 encodeULEB128(C.second.size(), getStream());
932 for (const WasmComdatEntry &Entry : C.second) {
933 encodeULEB128(Entry.Kind, getStream());
934 encodeULEB128(Entry.Index, getStream());
937 endSection(SubSection);
943 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
944 assert(Symbol.isFunction());
945 assert(TypeIndices.count(&Symbol));
946 return TypeIndices[&Symbol];
949 uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
950 assert(Symbol.isFunction());
953 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
954 F.Returns = ResolvedSym->getReturns();
955 F.Params = ResolvedSym->getParams();
958 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
960 FunctionTypes.push_back(F);
961 TypeIndices[&Symbol] = Pair.first->second;
963 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
964 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
965 return Pair.first->second;
968 void WasmObjectWriter::writeObject(MCAssembler &Asm,
969 const MCAsmLayout &Layout) {
970 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
971 MCContext &Ctx = Asm.getContext();
972 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
974 // Collect information from the available symbols.
975 SmallVector<WasmFunction, 4> Functions;
976 SmallVector<uint32_t, 4> TableElems;
977 SmallVector<WasmImport, 4> Imports;
978 SmallVector<WasmExport, 4> Exports;
979 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags;
980 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
981 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
982 SmallVector<WasmDataSegment, 4> DataSegments;
983 uint32_t DataSize = 0;
985 // In the special .global_variables section, we've encoded global
986 // variables used by the function. Translate them into the Globals
988 MCSectionWasm *GlobalVars =
989 Ctx.getWasmSection(".global_variables", SectionKind::getMetadata());
990 if (!GlobalVars->getFragmentList().empty()) {
991 if (GlobalVars->getFragmentList().size() != 1)
992 report_fatal_error("only one .global_variables fragment supported");
993 const MCFragment &Frag = *GlobalVars->begin();
994 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
995 report_fatal_error("only data supported in .global_variables");
996 const auto &DataFrag = cast<MCDataFragment>(Frag);
997 if (!DataFrag.getFixups().empty())
998 report_fatal_error("fixups not supported in .global_variables");
999 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1000 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1001 *end = (const uint8_t *)Contents.data() + Contents.size();
1005 report_fatal_error("truncated global variable encoding");
1006 G.Type = wasm::ValType(int8_t(*p++));
1007 G.IsMutable = bool(*p++);
1008 G.HasImport = bool(*p++);
1013 Import.ModuleName = (const char *)p;
1014 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1016 report_fatal_error("global module name must be nul-terminated");
1018 nul = (const uint8_t *)memchr(p, '\0', end - p);
1020 report_fatal_error("global base name must be nul-terminated");
1021 Import.FieldName = (const char *)p;
1024 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1025 Import.Type = int32_t(G.Type);
1027 G.ImportIndex = NumGlobalImports;
1030 Imports.push_back(Import);
1033 G.InitialValue = decodeSLEB128(p, &n);
1035 if ((ptrdiff_t)n > end - p)
1036 report_fatal_error("global initial value must be valid SLEB128");
1039 Globals.push_back(G);
1043 // For now, always emit the memory import, since loads and stores are not
1044 // valid without it. In the future, we could perhaps be more clever and omit
1045 // it if there are no loads or stores.
1046 MCSymbolWasm *MemorySym =
1047 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
1048 WasmImport MemImport;
1049 MemImport.ModuleName = MemorySym->getModuleName();
1050 MemImport.FieldName = MemorySym->getName();
1051 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1052 Imports.push_back(MemImport);
1054 // For now, always emit the table section, since indirect calls are not
1055 // valid without it. In the future, we could perhaps be more clever and omit
1056 // it if there are no indirect calls.
1057 MCSymbolWasm *TableSym =
1058 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
1059 WasmImport TableImport;
1060 TableImport.ModuleName = TableSym->getModuleName();
1061 TableImport.FieldName = TableSym->getName();
1062 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1063 TableImport.Type = wasm::WASM_TYPE_ANYFUNC;
1064 Imports.push_back(TableImport);
1066 // Populate FunctionTypeIndices and Imports.
1067 for (const MCSymbol &S : Asm.symbols()) {
1068 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1070 // Register types for all functions, including those with private linkage
1071 // (because wasm always needs a type signature).
1072 if (WS.isFunction())
1073 registerFunctionType(WS);
1075 if (WS.isTemporary())
1078 // If the symbol is not defined in this translation unit, import it.
1079 if ((!WS.isDefined() && !WS.isComdat()) ||
1082 Import.ModuleName = WS.getModuleName();
1083 Import.FieldName = WS.getName();
1085 if (WS.isFunction()) {
1086 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1087 Import.Type = getFunctionType(WS);
1088 SymbolIndices[&WS] = NumFunctionImports;
1089 ++NumFunctionImports;
1091 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1092 Import.Type = int32_t(PtrType);
1093 Import.IsMutable = false;
1094 SymbolIndices[&WS] = NumGlobalImports;
1096 // If this global is the stack pointer, make it mutable.
1097 if (WS.getName() == "__stack_pointer")
1098 Import.IsMutable = true;
1103 Imports.push_back(Import);
1107 for (MCSection &Sec : Asm) {
1108 auto &Section = static_cast<MCSectionWasm &>(Sec);
1109 if (!Section.isWasmData())
1112 // .init_array sections are handled specially elsewhere.
1113 if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1116 uint32_t SegmentIndex = DataSegments.size();
1117 DataSize = alignTo(DataSize, Section.getAlignment());
1118 DataSegments.emplace_back();
1119 WasmDataSegment &Segment = DataSegments.back();
1120 Segment.Name = Section.getSectionName();
1121 Segment.Offset = DataSize;
1122 Segment.Section = &Section;
1123 addData(Segment.Data, Section);
1124 Segment.Alignment = Section.getAlignment();
1126 DataSize += Segment.Data.size();
1127 Section.setMemoryOffset(Segment.Offset);
1129 if (const MCSymbolWasm *C = Section.getGroup()) {
1130 Comdats[C->getName()].emplace_back(
1131 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1135 // Handle regular defined and undefined symbols.
1136 for (const MCSymbol &S : Asm.symbols()) {
1137 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1138 // or used in relocations.
1139 if (S.isTemporary() && S.getName().empty())
1142 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1143 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1144 << " isDefined=" << S.isDefined()
1145 << " isExternal=" << S.isExternal()
1146 << " isTemporary=" << S.isTemporary()
1147 << " isFunction=" << WS.isFunction()
1148 << " isWeak=" << WS.isWeak()
1149 << " isHidden=" << WS.isHidden()
1150 << " isVariable=" << WS.isVariable() << "\n");
1152 if (WS.isWeak() || WS.isHidden()) {
1153 uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) |
1154 (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
1155 SymbolFlags.emplace_back(WS.getName(), Flags);
1158 if (WS.isVariable())
1163 if (WS.isFunction()) {
1164 if (WS.isDefined()) {
1165 if (WS.getOffset() != 0)
1167 "function sections must contain one function each");
1169 if (WS.getSize() == 0)
1171 "function symbols must have a size set with .size");
1173 // A definition. Take the next available index.
1174 Index = NumFunctionImports + Functions.size();
1176 // Prepare the function.
1178 Func.Type = getFunctionType(WS);
1180 SymbolIndices[&WS] = Index;
1181 Functions.push_back(Func);
1183 // An import; the index was assigned above.
1184 Index = SymbolIndices.find(&WS)->second;
1187 DEBUG(dbgs() << " -> function index: " << Index << "\n");
1189 if (WS.isTemporary() && !WS.getSize())
1192 if (!WS.isDefined())
1196 report_fatal_error("data symbols must have a size set with .size: " +
1200 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1201 report_fatal_error(".size expression must be evaluatable");
1203 // For each global, prepare a corresponding wasm global holding its
1204 // address. For externals these will also be named exports.
1205 Index = NumGlobalImports + Globals.size();
1206 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1207 assert(DataSection.isWasmData());
1210 Global.Type = PtrType;
1211 Global.IsMutable = false;
1212 Global.HasImport = false;
1213 Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
1214 Global.ImportIndex = 0;
1215 SymbolIndices[&WS] = Index;
1216 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1217 Globals.push_back(Global);
1220 // If the symbol is visible outside this translation unit, export it.
1221 if (WS.isDefined()) {
1223 Export.FieldName = WS.getName();
1224 Export.Index = Index;
1225 if (WS.isFunction())
1226 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1228 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1229 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
1230 Exports.push_back(Export);
1232 if (!WS.isExternal())
1233 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
1235 if (WS.isFunction()) {
1236 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1237 if (const MCSymbolWasm *C = Section.getGroup())
1238 Comdats[C->getName()].emplace_back(
1239 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1244 // Handle weak aliases. We need to process these in a separate pass because
1245 // we need to have processed the target of the alias before the alias itself
1246 // and the symbols are not necessarily ordered in this way.
1247 for (const MCSymbol &S : Asm.symbols()) {
1248 if (!S.isVariable())
1251 assert(S.isDefined());
1253 // Find the target symbol of this weak alias and export that index
1254 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1255 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
1256 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1257 assert(SymbolIndices.count(ResolvedSym) > 0);
1258 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
1259 DEBUG(dbgs() << " -> index:" << Index << "\n");
1262 Export.FieldName = WS.getName();
1263 Export.Index = Index;
1264 if (WS.isFunction())
1265 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1267 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1268 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
1269 Exports.push_back(Export);
1271 if (!WS.isExternal())
1272 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
1276 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1277 // Functions referenced by a relocation need to prepared to be called
1279 const MCSymbolWasm& WS = *Rel.Symbol;
1280 if (WS.isFunction() && IndirectSymbolIndices.count(&WS) == 0) {
1282 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
1283 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
1284 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1285 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
1286 uint32_t Index = SymbolIndices.find(&WS)->second;
1287 IndirectSymbolIndices[&WS] = TableElems.size() + kInitialTableOffset;
1288 DEBUG(dbgs() << " -> adding " << WS.getName()
1289 << " to table: " << TableElems.size() << "\n");
1290 TableElems.push_back(Index);
1291 registerFunctionType(WS);
1300 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1301 HandleReloc(RelEntry);
1302 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1303 HandleReloc(RelEntry);
1306 // Translate .init_array section contents into start functions.
1307 for (const MCSection &S : Asm) {
1308 const auto &WS = static_cast<const MCSectionWasm &>(S);
1309 if (WS.getSectionName().startswith(".fini_array"))
1310 report_fatal_error(".fini_array sections are unsupported");
1311 if (!WS.getSectionName().startswith(".init_array"))
1313 if (WS.getFragmentList().empty())
1315 if (WS.getFragmentList().size() != 2)
1316 report_fatal_error("only one .init_array section fragment supported");
1317 const MCFragment &AlignFrag = *WS.begin();
1318 if (AlignFrag.getKind() != MCFragment::FT_Align)
1319 report_fatal_error(".init_array section should be aligned");
1320 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1321 report_fatal_error(".init_array section should be aligned for pointers");
1322 const MCFragment &Frag = *std::next(WS.begin());
1323 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1324 report_fatal_error("only data supported in .init_array section");
1325 uint16_t Priority = UINT16_MAX;
1326 if (WS.getSectionName().size() != 11) {
1327 if (WS.getSectionName()[11] != '.')
1328 report_fatal_error(".init_array section priority should start with '.'");
1329 if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1330 report_fatal_error("invalid .init_array section priority");
1332 const auto &DataFrag = cast<MCDataFragment>(Frag);
1333 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1334 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1335 *end = (const uint8_t *)Contents.data() + Contents.size();
1338 report_fatal_error("non-symbolic data in .init_array section");
1340 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1341 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1342 const MCExpr *Expr = Fixup.getValue();
1343 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1345 report_fatal_error("fixups in .init_array should be symbol references");
1346 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1347 report_fatal_error("symbols in .init_array should be for functions");
1348 auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1349 if (I == SymbolIndices.end())
1350 report_fatal_error("symbols in .init_array should be defined");
1351 uint32_t Index = I->second;
1352 InitFuncs.push_back(std::make_pair(Priority, Index));
1356 // Write out the Wasm header.
1359 writeTypeSection(FunctionTypes);
1360 writeImportSection(Imports, DataSize, TableElems.size());
1361 writeFunctionSection(Functions);
1362 // Skip the "table" section; we import the table instead.
1363 // Skip the "memory" section; we import the memory instead.
1364 writeGlobalSection();
1365 writeExportSection(Exports);
1366 writeElemSection(TableElems);
1367 writeCodeSection(Asm, Layout, Functions);
1368 writeDataSection(DataSegments);
1369 writeCodeRelocSection();
1370 writeDataRelocSection();
1371 writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags,
1372 InitFuncs, Comdats);
1374 // TODO: Translate the .comment section to the output.
1375 // TODO: Translate debug sections to the output.
1378 std::unique_ptr<MCObjectWriter>
1379 llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1380 raw_pwrite_stream &OS) {
1381 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);